niri
Clone
https://git.tahinli.com/Tahinli/niri.git
0 watching·0 forks·Rust·GPL-3.0·12.1 MiB·9ff2f83·Ivan Molodetskikh·1 year ago·2099 commits
| 1 | use std::cell::RefCell; |
| 2 | use std::collections::{HashMap, HashSet}; |
| 3 | use std::fmt::Write; |
| 4 | use std::iter::zip; |
| 5 | use std::num::NonZeroU64; |
| 6 | use std::os::fd::AsFd; |
| 7 | use std::path::Path; |
| 8 | use std::rc::Rc; |
| 9 | use std::sync::{Arc, Mutex}; |
| 10 | use std::time::Duration; |
| 11 | use std::{io, mem}; |
| 12 | |
| 13 | use anyhow::{anyhow, bail, ensure, Context}; |
| 14 | use bytemuck::cast_slice_mut; |
| 15 | use libc::dev_t; |
| 16 | use niri_config::{Config, OutputName}; |
| 17 | use smithay::backend::allocator::dmabuf::Dmabuf; |
| 18 | use smithay::backend::allocator::format::FormatSet; |
| 19 | use smithay::backend::allocator::gbm::{GbmAllocator, GbmBufferFlags, GbmDevice}; |
| 20 | use smithay::backend::allocator::Fourcc; |
| 21 | use smithay::backend::drm::compositor::{DrmCompositor, FrameFlags, PrimaryPlaneElement}; |
| 22 | use smithay::backend::drm::exporter::gbm::GbmFramebufferExporter; |
| 23 | use smithay::backend::drm::{ |
| 24 | DrmDevice, DrmDeviceFd, DrmEvent, DrmEventMetadata, DrmEventTime, DrmNode, NodeType, VrrSupport, |
| 25 | }; |
| 26 | use smithay::backend::egl::context::ContextPriority; |
| 27 | use smithay::backend::egl::{EGLDevice, EGLDisplay}; |
| 28 | use smithay::backend::libinput::{LibinputInputBackend, LibinputSessionInterface}; |
| 29 | use smithay::backend::renderer::gles::GlesRenderer; |
| 30 | use smithay::backend::renderer::multigpu::gbm::GbmGlesBackend; |
| 31 | use smithay::backend::renderer::multigpu::{GpuManager, MultiFrame, MultiRenderer}; |
| 32 | use smithay::backend::renderer::{DebugFlags, ImportDma, ImportEgl, RendererSuper}; |
| 33 | use smithay::backend::session::libseat::LibSeatSession; |
| 34 | use smithay::backend::session::{Event as SessionEvent, Session}; |
| 35 | use smithay::backend::udev::{self, UdevBackend, UdevEvent}; |
| 36 | use smithay::desktop::utils::OutputPresentationFeedback; |
| 37 | use smithay::output::{Mode, Output, OutputModeSource, PhysicalProperties}; |
| 38 | use smithay::reexports::calloop::timer::{TimeoutAction, Timer}; |
| 39 | use smithay::reexports::calloop::{Dispatcher, LoopHandle, RegistrationToken}; |
| 40 | use smithay::reexports::drm::control::{ |
| 41 | self, connector, crtc, property, Device, Mode as DrmMode, ModeFlags, ModeTypeFlags, |
| 42 | ResourceHandle, |
| 43 | }; |
| 44 | use smithay::reexports::gbm::Modifier; |
| 45 | use smithay::reexports::input::Libinput; |
| 46 | use smithay::reexports::rustix::fs::OFlags; |
| 47 | use smithay::reexports::wayland_protocols; |
| 48 | use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface; |
| 49 | use smithay::utils::DeviceFd; |
| 50 | use smithay::wayland::dmabuf::{DmabufFeedback, DmabufFeedbackBuilder, DmabufGlobal}; |
| 51 | use smithay::wayland::drm_lease::{ |
| 52 | DrmLease, DrmLeaseBuilder, DrmLeaseRequest, DrmLeaseState, LeaseRejected, |
| 53 | }; |
| 54 | use smithay::wayland::presentation::Refresh; |
| 55 | use smithay_drm_extras::drm_scanner::{DrmScanEvent, DrmScanner}; |
| 56 | use wayland_protocols::wp::linux_dmabuf::zv1::server::zwp_linux_dmabuf_feedback_v1::TrancheFlags; |
| 57 | use wayland_protocols::wp::presentation_time::server::wp_presentation_feedback; |
| 58 | |
| 59 | use super::{IpcOutputMap, RenderResult}; |
| 60 | use crate::backend::OutputId; |
| 61 | use crate::frame_clock::FrameClock; |
| 62 | use crate::niri::{Niri, RedrawState, State}; |
| 63 | use crate::render_helpers::debug::draw_damage; |
| 64 | use crate::render_helpers::renderer::AsGlesRenderer; |
| 65 | use crate::render_helpers::{resources, shaders, RenderTarget}; |
| 66 | use crate::utils::{get_monotonic_time, is_laptop_panel, logical_output}; |
| 67 | |
| 68 | const SUPPORTED_COLOR_FORMATS: [Fourcc; 4] = [ |
| 69 | Fourcc::Xrgb8888, |
| 70 | Fourcc::Xbgr8888, |
| 71 | Fourcc::Argb8888, |
| 72 | Fourcc::Abgr8888, |
| 73 | ]; |
| 74 | |
| 75 | pub struct Tty { |
| 76 | config: Rc<RefCell<Config>>, |
| 77 | session: LibSeatSession, |
| 78 | udev_dispatcher: Dispatcher<'static, UdevBackend, State>, |
| 79 | libinput: Libinput, |
| 80 | gpu_manager: GpuManager<GbmGlesBackend<GlesRenderer, DrmDeviceFd>>, |
| 81 | // DRM node corresponding to the primary GPU. May or may not be the same as |
| 82 | // primary_render_node. |
| 83 | primary_node: DrmNode, |
| 84 | // DRM render node corresponding to the primary GPU. |
| 85 | primary_render_node: DrmNode, |
| 86 | // Devices indexed by DRM node (not necessarily the render node). |
| 87 | devices: HashMap<DrmNode, OutputDevice>, |
| 88 | // The dma-buf global corresponds to the output device (the primary GPU). It is only `Some()` |
| 89 | // if we have a device corresponding to the primary GPU. |
| 90 | dmabuf_global: Option<DmabufGlobal>, |
| 91 | // The output config had changed, but the session is paused, so we need to update it on resume. |
| 92 | update_output_config_on_resume: bool, |
| 93 | // Whether the debug tinting is enabled. |
| 94 | debug_tint: bool, |
| 95 | ipc_outputs: Arc<Mutex<IpcOutputMap>>, |
| 96 | } |
| 97 | |
| 98 | pub type TtyRenderer<'render> = MultiRenderer< |
| 99 | 'render, |
| 100 | 'render, |
| 101 | GbmGlesBackend<GlesRenderer, DrmDeviceFd>, |
| 102 | GbmGlesBackend<GlesRenderer, DrmDeviceFd>, |
| 103 | >; |
| 104 | |
| 105 | pub type TtyFrame<'render, 'frame, 'buffer> = MultiFrame< |
| 106 | 'render, |
| 107 | 'render, |
| 108 | 'frame, |
| 109 | 'buffer, |
| 110 | GbmGlesBackend<GlesRenderer, DrmDeviceFd>, |
| 111 | GbmGlesBackend<GlesRenderer, DrmDeviceFd>, |
| 112 | >; |
| 113 | |
| 114 | pub type TtyRendererError<'render> = <TtyRenderer<'render> as RendererSuper>::Error; |
| 115 | |
| 116 | type GbmDrmCompositor = DrmCompositor< |
| 117 | GbmAllocator<DrmDeviceFd>, |
| 118 | GbmFramebufferExporter<DrmDeviceFd>, |
| 119 | (OutputPresentationFeedback, Duration), |
| 120 | DrmDeviceFd, |
| 121 | >; |
| 122 | |
| 123 | pub struct OutputDevice { |
| 124 | token: RegistrationToken, |
| 125 | render_node: DrmNode, |
| 126 | drm_scanner: DrmScanner, |
| 127 | surfaces: HashMap<crtc::Handle, Surface>, |
| 128 | known_crtcs: HashMap<crtc::Handle, CrtcInfo>, |
| 129 | // SAFETY: drop after all the objects used with them are dropped. |
| 130 | // See https://github.com/Smithay/smithay/issues/1102. |
| 131 | drm: DrmDevice, |
| 132 | gbm: GbmDevice<DrmDeviceFd>, |
| 133 | |
| 134 | pub drm_lease_state: Option<DrmLeaseState>, |
| 135 | non_desktop_connectors: HashSet<(connector::Handle, crtc::Handle)>, |
| 136 | active_leases: Vec<DrmLease>, |
| 137 | } |
| 138 | |
| 139 | // A connected, but not necessarily enabled, crtc. |
| 140 | #[derive(Debug, Clone)] |
| 141 | pub struct CrtcInfo { |
| 142 | id: OutputId, |
| 143 | name: OutputName, |
| 144 | } |
| 145 | |
| 146 | impl OutputDevice { |
| 147 | pub fn lease_request( |
| 148 | &self, |
| 149 | request: DrmLeaseRequest, |
| 150 | ) -> Result<DrmLeaseBuilder, LeaseRejected> { |
| 151 | let mut builder = DrmLeaseBuilder::new(&self.drm); |
| 152 | for connector in request.connectors { |
| 153 | let (_, crtc) = self |
| 154 | .non_desktop_connectors |
| 155 | .iter() |
| 156 | .find(|(conn, _)| connector == *conn) |
| 157 | .ok_or_else(|| { |
| 158 | warn!("Attempted to lease connector that is not non-desktop"); |
| 159 | LeaseRejected::default() |
| 160 | })?; |
| 161 | builder.add_connector(connector); |
| 162 | builder.add_crtc(*crtc); |
| 163 | let planes = self.drm.planes(crtc).map_err(LeaseRejected::with_cause)?; |
| 164 | let (primary_plane, primary_plane_claim) = planes |
| 165 | .primary |
| 166 | .iter() |
| 167 | .find_map(|plane| { |
| 168 | self.drm |
| 169 | .claim_plane(plane.handle, *crtc) |
| 170 | .map(|claim| (plane, claim)) |
| 171 | }) |
| 172 | .ok_or_else(LeaseRejected::default)?; |
| 173 | builder.add_plane(primary_plane.handle, primary_plane_claim); |
| 174 | } |
| 175 | Ok(builder) |
| 176 | } |
| 177 | |
| 178 | pub fn new_lease(&mut self, lease: DrmLease) { |
| 179 | self.active_leases.push(lease); |
| 180 | } |
| 181 | |
| 182 | pub fn remove_lease(&mut self, lease_id: u32) { |
| 183 | self.active_leases.retain(|l| l.id() != lease_id); |
| 184 | } |
| 185 | |
| 186 | pub fn known_crtc_name( |
| 187 | &self, |
| 188 | crtc: &crtc::Handle, |
| 189 | conn: &connector::Info, |
| 190 | disable_monitor_names: bool, |
| 191 | ) -> OutputName { |
| 192 | if disable_monitor_names { |
| 193 | let conn_name = format_connector_name(conn); |
| 194 | return OutputName { |
| 195 | connector: conn_name, |
| 196 | make: None, |
| 197 | model: None, |
| 198 | serial: None, |
| 199 | }; |
| 200 | } |
| 201 | |
| 202 | let Some(info) = self.known_crtcs.get(crtc) else { |
| 203 | let conn_name = format_connector_name(conn); |
| 204 | error!("crtc for connector {conn_name} missing from known"); |
| 205 | return OutputName { |
| 206 | connector: conn_name, |
| 207 | make: None, |
| 208 | model: None, |
| 209 | serial: None, |
| 210 | }; |
| 211 | }; |
| 212 | info.name.clone() |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | #[derive(Debug, Clone, Copy)] |
| 217 | struct TtyOutputState { |
| 218 | node: DrmNode, |
| 219 | crtc: crtc::Handle, |
| 220 | } |
| 221 | |
| 222 | struct Surface { |
| 223 | name: OutputName, |
| 224 | compositor: GbmDrmCompositor, |
| 225 | connector: connector::Handle, |
| 226 | dmabuf_feedback: Option<SurfaceDmabufFeedback>, |
| 227 | gamma_props: Option<GammaProps>, |
| 228 | /// Gamma change to apply upon session resume. |
| 229 | pending_gamma_change: Option<Option<Vec<u16>>>, |
| 230 | /// Tracy frame that goes from vblank to vblank. |
| 231 | vblank_frame: Option<tracy_client::Frame>, |
| 232 | /// Frame name for the VBlank frame. |
| 233 | vblank_frame_name: tracy_client::FrameName, |
| 234 | /// Plot name for the time since presentation plot. |
| 235 | time_since_presentation_plot_name: tracy_client::PlotName, |
| 236 | /// Plot name for the presentation misprediction plot. |
| 237 | presentation_misprediction_plot_name: tracy_client::PlotName, |
| 238 | sequence_delta_plot_name: tracy_client::PlotName, |
| 239 | } |
| 240 | |
| 241 | pub struct SurfaceDmabufFeedback { |
| 242 | pub render: DmabufFeedback, |
| 243 | pub scanout: DmabufFeedback, |
| 244 | } |
| 245 | |
| 246 | struct GammaProps { |
| 247 | crtc: crtc::Handle, |
| 248 | gamma_lut: property::Handle, |
| 249 | gamma_lut_size: property::Handle, |
| 250 | previous_blob: Option<NonZeroU64>, |
| 251 | } |
| 252 | |
| 253 | impl Tty { |
| 254 | pub fn new( |
| 255 | config: Rc<RefCell<Config>>, |
| 256 | event_loop: LoopHandle<'static, State>, |
| 257 | ) -> anyhow::Result<Self> { |
| 258 | let (session, notifier) = LibSeatSession::new().context( |
| 259 | "Error creating a session. This might mean that you're trying to run niri on a TTY \ |
| 260 | that is already busy, for example if you're running this inside tmux that had been \ |
| 261 | originally started on a different TTY", |
| 262 | )?; |
| 263 | let seat_name = session.seat(); |
| 264 | |
| 265 | let udev_backend = |
| 266 | UdevBackend::new(session.seat()).context("error creating a udev backend")?; |
| 267 | let udev_dispatcher = Dispatcher::new(udev_backend, move |event, _, state: &mut State| { |
| 268 | state.backend.tty().on_udev_event(&mut state.niri, event); |
| 269 | }); |
| 270 | event_loop |
| 271 | .register_dispatcher(udev_dispatcher.clone()) |
| 272 | .unwrap(); |
| 273 | |
| 274 | let mut libinput = Libinput::new_with_udev(LibinputSessionInterface::from(session.clone())); |
| 275 | libinput |
| 276 | .udev_assign_seat(&seat_name) |
| 277 | .map_err(|()| anyhow!("error assigning the seat to libinput"))?; |
| 278 | |
| 279 | let input_backend = LibinputInputBackend::new(libinput.clone()); |
| 280 | event_loop |
| 281 | .insert_source(input_backend, |mut event, _, state| { |
| 282 | state.process_libinput_event(&mut event); |
| 283 | state.process_input_event(event); |
| 284 | }) |
| 285 | .unwrap(); |
| 286 | |
| 287 | event_loop |
| 288 | .insert_source(notifier, move |event, _, state| { |
| 289 | state.backend.tty().on_session_event(&mut state.niri, event); |
| 290 | }) |
| 291 | .unwrap(); |
| 292 | |
| 293 | let api = GbmGlesBackend::with_context_priority(ContextPriority::High); |
| 294 | let gpu_manager = GpuManager::new(api).context("error creating the GPU manager")?; |
| 295 | |
| 296 | let (primary_node, primary_render_node) = primary_node_from_config(&config.borrow()) |
| 297 | .ok_or(()) |
| 298 | .or_else(|()| { |
| 299 | let primary_gpu_path = udev::primary_gpu(&seat_name) |
| 300 | .context("error getting the primary GPU")? |
| 301 | .context("couldn't find a GPU")?; |
| 302 | let primary_node = DrmNode::from_path(primary_gpu_path) |
| 303 | .context("error opening the primary GPU DRM node")?; |
| 304 | let primary_render_node = primary_node |
| 305 | .node_with_type(NodeType::Render) |
| 306 | .and_then(Result::ok) |
| 307 | .unwrap_or_else(|| { |
| 308 | warn!( |
| 309 | "error getting the render node for the primary GPU; proceeding anyway" |
| 310 | ); |
| 311 | primary_node |
| 312 | }); |
| 313 | |
| 314 | Ok::<_, anyhow::Error>((primary_node, primary_render_node)) |
| 315 | })?; |
| 316 | |
| 317 | let mut node_path = String::new(); |
| 318 | if let Some(path) = primary_render_node.dev_path() { |
| 319 | write!(node_path, "{:?}", path).unwrap(); |
| 320 | } else { |
| 321 | write!(node_path, "{}", primary_render_node).unwrap(); |
| 322 | } |
| 323 | info!("using as the render node: {}", node_path); |
| 324 | |
| 325 | Ok(Self { |
| 326 | config, |
| 327 | session, |
| 328 | udev_dispatcher, |
| 329 | libinput, |
| 330 | gpu_manager, |
| 331 | primary_node, |
| 332 | primary_render_node, |
| 333 | devices: HashMap::new(), |
| 334 | dmabuf_global: None, |
| 335 | update_output_config_on_resume: false, |
| 336 | debug_tint: false, |
| 337 | ipc_outputs: Arc::new(Mutex::new(HashMap::new())), |
| 338 | }) |
| 339 | } |
| 340 | |
| 341 | pub fn init(&mut self, niri: &mut Niri) { |
| 342 | for (device_id, path) in self.udev_dispatcher.clone().as_source_ref().device_list() { |
| 343 | if let Err(err) = self.device_added(device_id, path, niri) { |
| 344 | warn!("error adding device: {err:?}"); |
| 345 | } |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | fn on_udev_event(&mut self, niri: &mut Niri, event: UdevEvent) { |
| 350 | let _span = tracy_client::span!("Tty::on_udev_event"); |
| 351 | |
| 352 | match event { |
| 353 | UdevEvent::Added { device_id, path } => { |
| 354 | if !self.session.is_active() { |
| 355 | debug!("skipping UdevEvent::Added as session is inactive"); |
| 356 | return; |
| 357 | } |
| 358 | |
| 359 | if let Err(err) = self.device_added(device_id, &path, niri) { |
| 360 | warn!("error adding device: {err:?}"); |
| 361 | } |
| 362 | } |
| 363 | UdevEvent::Changed { device_id } => { |
| 364 | if !self.session.is_active() { |
| 365 | debug!("skipping UdevEvent::Changed as session is inactive"); |
| 366 | return; |
| 367 | } |
| 368 | |
| 369 | self.device_changed(device_id, niri) |
| 370 | } |
| 371 | UdevEvent::Removed { device_id } => { |
| 372 | if !self.session.is_active() { |
| 373 | debug!("skipping UdevEvent::Removed as session is inactive"); |
| 374 | return; |
| 375 | } |
| 376 | |
| 377 | self.device_removed(device_id, niri) |
| 378 | } |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | fn on_session_event(&mut self, niri: &mut Niri, event: SessionEvent) { |
| 383 | let _span = tracy_client::span!("Tty::on_session_event"); |
| 384 | |
| 385 | match event { |
| 386 | SessionEvent::PauseSession => { |
| 387 | debug!("pausing session"); |
| 388 | |
| 389 | self.libinput.suspend(); |
| 390 | |
| 391 | for device in self.devices.values_mut() { |
| 392 | device.drm.pause(); |
| 393 | |
| 394 | if let Some(lease_state) = &mut device.drm_lease_state { |
| 395 | lease_state.suspend(); |
| 396 | } |
| 397 | } |
| 398 | } |
| 399 | SessionEvent::ActivateSession => { |
| 400 | debug!("resuming session"); |
| 401 | |
| 402 | if self.libinput.resume().is_err() { |
| 403 | warn!("error resuming libinput"); |
| 404 | } |
| 405 | |
| 406 | let mut device_list = self |
| 407 | .udev_dispatcher |
| 408 | .as_source_ref() |
| 409 | .device_list() |
| 410 | .map(|(device_id, path)| (device_id, path.to_owned())) |
| 411 | .collect::<HashMap<_, _>>(); |
| 412 | |
| 413 | let removed_devices = self |
| 414 | .devices |
| 415 | .keys() |
| 416 | .filter(|node| !device_list.contains_key(&node.dev_id())) |
| 417 | .copied() |
| 418 | .collect::<Vec<_>>(); |
| 419 | |
| 420 | let remained_devices = self |
| 421 | .devices |
| 422 | .keys() |
| 423 | .filter(|node| device_list.contains_key(&node.dev_id())) |
| 424 | .copied() |
| 425 | .collect::<Vec<_>>(); |
| 426 | |
| 427 | // Remove removed devices. |
| 428 | for node in removed_devices { |
| 429 | device_list.remove(&node.dev_id()); |
| 430 | self.device_removed(node.dev_id(), niri); |
| 431 | } |
| 432 | |
| 433 | // Update remained devices. |
| 434 | for node in remained_devices { |
| 435 | device_list.remove(&node.dev_id()); |
| 436 | |
| 437 | // It hasn't been removed, update its state as usual. |
| 438 | let device = self.devices.get_mut(&node).unwrap(); |
| 439 | if let Err(err) = device.drm.activate(true) { |
| 440 | warn!("error activating DRM device: {err:?}"); |
| 441 | } |
| 442 | if let Some(lease_state) = &mut device.drm_lease_state { |
| 443 | lease_state.resume::<State>(); |
| 444 | } |
| 445 | |
| 446 | // Refresh the connectors. |
| 447 | self.device_changed(node.dev_id(), niri); |
| 448 | |
| 449 | // Apply pending gamma changes and restore our existing gamma. |
| 450 | let device = self.devices.get_mut(&node).unwrap(); |
| 451 | for (crtc, surface) in device.surfaces.iter_mut() { |
| 452 | if let Some(ramp) = surface.pending_gamma_change.take() { |
| 453 | let ramp = ramp.as_deref(); |
| 454 | let res = if let Some(gamma_props) = &mut surface.gamma_props { |
| 455 | gamma_props.set_gamma(&device.drm, ramp) |
| 456 | } else { |
| 457 | set_gamma_for_crtc(&device.drm, *crtc, ramp) |
| 458 | }; |
| 459 | if let Err(err) = res { |
| 460 | warn!("error applying pending gamma change: {err:?}"); |
| 461 | } |
| 462 | } else if let Some(gamma_props) = &surface.gamma_props { |
| 463 | if let Err(err) = gamma_props.restore_gamma(&device.drm) { |
| 464 | warn!("error restoring gamma: {err:?}"); |
| 465 | } |
| 466 | } |
| 467 | } |
| 468 | } |
| 469 | |
| 470 | // Add new devices. |
| 471 | for (device_id, path) in device_list.into_iter() { |
| 472 | if let Err(err) = self.device_added(device_id, &path, niri) { |
| 473 | warn!("error adding device: {err:?}"); |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | if self.update_output_config_on_resume { |
| 478 | self.on_output_config_changed(niri); |
| 479 | } |
| 480 | |
| 481 | self.refresh_ipc_outputs(niri); |
| 482 | |
| 483 | niri.notify_activity(); |
| 484 | niri.monitors_active = true; |
| 485 | self.set_monitors_active(true); |
| 486 | niri.queue_redraw_all(); |
| 487 | } |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | fn device_added( |
| 492 | &mut self, |
| 493 | device_id: dev_t, |
| 494 | path: &Path, |
| 495 | niri: &mut Niri, |
| 496 | ) -> anyhow::Result<()> { |
| 497 | debug!("device added: {device_id} {path:?}"); |
| 498 | |
| 499 | let node = DrmNode::from_dev_id(device_id)?; |
| 500 | |
| 501 | let open_flags = OFlags::RDWR | OFlags::CLOEXEC | OFlags::NOCTTY | OFlags::NONBLOCK; |
| 502 | let fd = self.session.open(path, open_flags)?; |
| 503 | let device_fd = DrmDeviceFd::new(DeviceFd::from(fd)); |
| 504 | |
| 505 | let (drm, drm_notifier) = DrmDevice::new(device_fd.clone(), true)?; |
| 506 | let gbm = GbmDevice::new(device_fd)?; |
| 507 | |
| 508 | let display = unsafe { EGLDisplay::new(gbm.clone())? }; |
| 509 | let egl_device = EGLDevice::device_for_display(&display)?; |
| 510 | |
| 511 | let render_node = egl_device |
| 512 | .try_get_render_node()? |
| 513 | .context("no render node")?; |
| 514 | self.gpu_manager |
| 515 | .as_mut() |
| 516 | .add_node(render_node, gbm.clone()) |
| 517 | .context("error adding render node to GPU manager")?; |
| 518 | |
| 519 | if node == self.primary_node || render_node == self.primary_render_node { |
| 520 | if node == self.primary_node { |
| 521 | debug!("this is the primary node"); |
| 522 | } |
| 523 | if render_node == self.primary_render_node { |
| 524 | debug!("this is the primary render node"); |
| 525 | } |
| 526 | |
| 527 | let mut renderer = self |
| 528 | .gpu_manager |
| 529 | .single_renderer(&render_node) |
| 530 | .context("error creating renderer")?; |
| 531 | |
| 532 | if let Err(err) = renderer.bind_wl_display(&niri.display_handle) { |
| 533 | warn!("error binding wl-display in EGL: {err:?}"); |
| 534 | } |
| 535 | |
| 536 | let gles_renderer = renderer.as_gles_renderer(); |
| 537 | resources::init(gles_renderer); |
| 538 | shaders::init(gles_renderer); |
| 539 | |
| 540 | let config = self.config.borrow(); |
| 541 | if let Some(src) = config.animations.window_resize.custom_shader.as_deref() { |
| 542 | shaders::set_custom_resize_program(gles_renderer, Some(src)); |
| 543 | } |
| 544 | if let Some(src) = config.animations.window_close.custom_shader.as_deref() { |
| 545 | shaders::set_custom_close_program(gles_renderer, Some(src)); |
| 546 | } |
| 547 | if let Some(src) = config.animations.window_open.custom_shader.as_deref() { |
| 548 | shaders::set_custom_open_program(gles_renderer, Some(src)); |
| 549 | } |
| 550 | drop(config); |
| 551 | |
| 552 | niri.update_shaders(); |
| 553 | |
| 554 | // Create the dmabuf global. |
| 555 | let primary_formats = renderer.dmabuf_formats(); |
| 556 | let default_feedback = |
| 557 | DmabufFeedbackBuilder::new(render_node.dev_id(), primary_formats.clone()) |
| 558 | .build() |
| 559 | .context("error building default dmabuf feedback")?; |
| 560 | let dmabuf_global = niri |
| 561 | .dmabuf_state |
| 562 | .create_global_with_default_feedback::<State>( |
| 563 | &niri.display_handle, |
| 564 | &default_feedback, |
| 565 | ); |
| 566 | assert!(self.dmabuf_global.replace(dmabuf_global).is_none()); |
| 567 | |
| 568 | // Update the dmabuf feedbacks for all surfaces. |
| 569 | for device in self.devices.values_mut() { |
| 570 | for surface in device.surfaces.values_mut() { |
| 571 | match surface_dmabuf_feedback( |
| 572 | &surface.compositor, |
| 573 | primary_formats.clone(), |
| 574 | self.primary_render_node, |
| 575 | device.render_node, |
| 576 | ) { |
| 577 | Ok(feedback) => { |
| 578 | surface.dmabuf_feedback = Some(feedback); |
| 579 | } |
| 580 | Err(err) => { |
| 581 | warn!("error building dmabuf feedback: {err:?}"); |
| 582 | } |
| 583 | } |
| 584 | } |
| 585 | } |
| 586 | } |
| 587 | |
| 588 | let token = niri |
| 589 | .event_loop |
| 590 | .insert_source(drm_notifier, move |event, meta, state| { |
| 591 | let tty = state.backend.tty(); |
| 592 | match event { |
| 593 | DrmEvent::VBlank(crtc) => { |
| 594 | let meta = meta.expect("VBlank events must have metadata"); |
| 595 | tty.on_vblank(&mut state.niri, node, crtc, meta); |
| 596 | } |
| 597 | DrmEvent::Error(error) => warn!("DRM error: {error}"), |
| 598 | }; |
| 599 | }) |
| 600 | .unwrap(); |
| 601 | |
| 602 | let drm_lease_state = DrmLeaseState::new::<State>(&niri.display_handle, &node) |
| 603 | .map_err(|err| warn!("error initializing DRM leasing for {node}: {err:?}")) |
| 604 | .ok(); |
| 605 | |
| 606 | let device = OutputDevice { |
| 607 | token, |
| 608 | render_node, |
| 609 | drm, |
| 610 | gbm, |
| 611 | drm_scanner: DrmScanner::new(), |
| 612 | surfaces: HashMap::new(), |
| 613 | known_crtcs: HashMap::new(), |
| 614 | drm_lease_state, |
| 615 | active_leases: Vec::new(), |
| 616 | non_desktop_connectors: HashSet::new(), |
| 617 | }; |
| 618 | assert!(self.devices.insert(node, device).is_none()); |
| 619 | |
| 620 | self.device_changed(device_id, niri); |
| 621 | |
| 622 | Ok(()) |
| 623 | } |
| 624 | |
| 625 | fn device_changed(&mut self, device_id: dev_t, niri: &mut Niri) { |
| 626 | debug!("device changed: {device_id}"); |
| 627 | |
| 628 | let Ok(node) = DrmNode::from_dev_id(device_id) else { |
| 629 | warn!("error creating DrmNode"); |
| 630 | return; |
| 631 | }; |
| 632 | |
| 633 | let Some(device) = self.devices.get_mut(&node) else { |
| 634 | warn!("no such device"); |
| 635 | return; |
| 636 | }; |
| 637 | |
| 638 | let scan_result = match device.drm_scanner.scan_connectors(&device.drm) { |
| 639 | Ok(x) => x, |
| 640 | Err(err) => { |
| 641 | warn!("error scanning connectors: {err:?}"); |
| 642 | return; |
| 643 | } |
| 644 | }; |
| 645 | |
| 646 | let mut added = Vec::new(); |
| 647 | let mut removed = Vec::new(); |
| 648 | for event in scan_result { |
| 649 | match event { |
| 650 | DrmScanEvent::Connected { |
| 651 | connector, |
| 652 | crtc: Some(crtc), |
| 653 | } => { |
| 654 | let connector_name = format_connector_name(&connector); |
| 655 | let name = make_output_name(&device.drm, connector.handle(), connector_name); |
| 656 | debug!( |
| 657 | "new connector: {} \"{}\"", |
| 658 | &name.connector, |
| 659 | name.format_make_model_serial(), |
| 660 | ); |
| 661 | |
| 662 | // Assign an id to this crtc. |
| 663 | let id = OutputId::next(); |
| 664 | added.push((crtc, CrtcInfo { id, name })); |
| 665 | } |
| 666 | DrmScanEvent::Disconnected { |
| 667 | crtc: Some(crtc), .. |
| 668 | } => { |
| 669 | removed.push(crtc); |
| 670 | } |
| 671 | _ => (), |
| 672 | } |
| 673 | } |
| 674 | |
| 675 | for crtc in &removed { |
| 676 | self.connector_disconnected(niri, node, *crtc); |
| 677 | } |
| 678 | |
| 679 | let Some(device) = self.devices.get_mut(&node) else { |
| 680 | error!("device disappeared"); |
| 681 | return; |
| 682 | }; |
| 683 | |
| 684 | for crtc in removed { |
| 685 | if device.known_crtcs.remove(&crtc).is_none() { |
| 686 | error!("output ID missing for disconnected crtc: {crtc:?}"); |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | for (crtc, mut info) in added { |
| 691 | // Make/model/serial can match exactly between different physical monitors. This doesn't |
| 692 | // happen often, but our Layout does not support such duplicates and will panic. |
| 693 | // |
| 694 | // As a workaround, search for duplicates, and unname the new connectors if one is |
| 695 | // found. Connector names are always unique. |
| 696 | let name = &mut info.name; |
| 697 | let formatted = name.format_make_model_serial_or_connector(); |
| 698 | for info in self.devices.values().flat_map(|d| d.known_crtcs.values()) { |
| 699 | if info.name.matches(&formatted) { |
| 700 | let connector = mem::take(&mut name.connector); |
| 701 | warn!( |
| 702 | "new connector {connector} duplicates make/model/serial \ |
| 703 | of existing connector {}, unnaming", |
| 704 | info.name.connector, |
| 705 | ); |
| 706 | *name = OutputName { |
| 707 | connector, |
| 708 | make: None, |
| 709 | model: None, |
| 710 | serial: None, |
| 711 | }; |
| 712 | break; |
| 713 | } |
| 714 | } |
| 715 | |
| 716 | // Insert it right away so next added connector will check against this one too. |
| 717 | let device = self.devices.get_mut(&node).unwrap(); |
| 718 | device.known_crtcs.insert(crtc, info); |
| 719 | } |
| 720 | |
| 721 | // This will connect any new connectors if needed, and apply other changes, such as |
| 722 | // connecting back the internal laptop monitor once it becomes the only monitor left. |
| 723 | // |
| 724 | // It will also call refresh_ipc_outputs(), which will catch the disconnected connectors |
| 725 | // above. |
| 726 | self.on_output_config_changed(niri); |
| 727 | } |
| 728 | |
| 729 | fn device_removed(&mut self, device_id: dev_t, niri: &mut Niri) { |
| 730 | debug!("device removed: {device_id}"); |
| 731 | |
| 732 | let Ok(node) = DrmNode::from_dev_id(device_id) else { |
| 733 | warn!("error creating DrmNode"); |
| 734 | return; |
| 735 | }; |
| 736 | |
| 737 | let Some(device) = self.devices.get_mut(&node) else { |
| 738 | warn!("no such device"); |
| 739 | return; |
| 740 | }; |
| 741 | |
| 742 | let crtcs: Vec<_> = device |
| 743 | .drm_scanner |
| 744 | .crtcs() |
| 745 | .map(|(_info, crtc)| crtc) |
| 746 | .collect(); |
| 747 | |
| 748 | for crtc in crtcs { |
| 749 | self.connector_disconnected(niri, node, crtc); |
| 750 | } |
| 751 | |
| 752 | let mut device = self.devices.remove(&node).unwrap(); |
| 753 | |
| 754 | if let Some(lease_state) = &mut device.drm_lease_state { |
| 755 | lease_state.disable_global::<State>(); |
| 756 | } |
| 757 | |
| 758 | if node == self.primary_node || device.render_node == self.primary_render_node { |
| 759 | match self.gpu_manager.single_renderer(&device.render_node) { |
| 760 | Ok(mut renderer) => renderer.unbind_wl_display(), |
| 761 | Err(err) => { |
| 762 | warn!("error creating renderer during device removal: {err}"); |
| 763 | } |
| 764 | } |
| 765 | |
| 766 | // Disable and destroy the dmabuf global. |
| 767 | if let Some(global) = self.dmabuf_global.take() { |
| 768 | niri.dmabuf_state |
| 769 | .disable_global::<State>(&niri.display_handle, &global); |
| 770 | niri.event_loop |
| 771 | .insert_source( |
| 772 | Timer::from_duration(Duration::from_secs(10)), |
| 773 | move |_, _, state| { |
| 774 | state |
| 775 | .niri |
| 776 | .dmabuf_state |
| 777 | .destroy_global::<State>(&state.niri.display_handle, global); |
| 778 | TimeoutAction::Drop |
| 779 | }, |
| 780 | ) |
| 781 | .unwrap(); |
| 782 | |
| 783 | // Clear the dmabuf feedbacks for all surfaces. |
| 784 | for device in self.devices.values_mut() { |
| 785 | for surface in device.surfaces.values_mut() { |
| 786 | surface.dmabuf_feedback = None; |
| 787 | } |
| 788 | } |
| 789 | } else { |
| 790 | error!("dmabuf global was already missing"); |
| 791 | } |
| 792 | } |
| 793 | |
| 794 | self.gpu_manager.as_mut().remove_node(&device.render_node); |
| 795 | niri.event_loop.remove(device.token); |
| 796 | |
| 797 | self.refresh_ipc_outputs(niri); |
| 798 | } |
| 799 | |
| 800 | fn connector_connected( |
| 801 | &mut self, |
| 802 | niri: &mut Niri, |
| 803 | node: DrmNode, |
| 804 | connector: connector::Info, |
| 805 | crtc: crtc::Handle, |
| 806 | ) -> anyhow::Result<()> { |
| 807 | let connector_name = format_connector_name(&connector); |
| 808 | debug!("connecting connector: {connector_name}"); |
| 809 | |
| 810 | let device = self.devices.get_mut(&node).context("missing device")?; |
| 811 | |
| 812 | let disable_monitor_names = self.config.borrow().debug.disable_monitor_names; |
| 813 | let output_name = device.known_crtc_name(&crtc, &connector, disable_monitor_names); |
| 814 | |
| 815 | let non_desktop = find_drm_property(&device.drm, connector.handle(), "non-desktop") |
| 816 | .and_then(|(_, info, value)| info.value_type().convert_value(value).as_boolean()) |
| 817 | .unwrap_or(false); |
| 818 | |
| 819 | if non_desktop { |
| 820 | debug!("output is non desktop"); |
| 821 | let description = output_name.format_description(); |
| 822 | if let Some(lease_state) = &mut device.drm_lease_state { |
| 823 | lease_state.add_connector::<State>(connector.handle(), connector_name, description); |
| 824 | } |
| 825 | device |
| 826 | .non_desktop_connectors |
| 827 | .insert((connector.handle(), crtc)); |
| 828 | return Ok(()); |
| 829 | } |
| 830 | |
| 831 | let config = self |
| 832 | .config |
| 833 | .borrow() |
| 834 | .outputs |
| 835 | .find(&output_name) |
| 836 | .cloned() |
| 837 | .unwrap_or_default(); |
| 838 | |
| 839 | for m in connector.modes() { |
| 840 | trace!("{m:?}"); |
| 841 | } |
| 842 | |
| 843 | let (mode, fallback) = |
| 844 | pick_mode(&connector, config.mode).ok_or_else(|| anyhow!("no mode"))?; |
| 845 | if fallback { |
| 846 | let target = config.mode.unwrap(); |
| 847 | warn!( |
| 848 | "configured mode {}x{}{} could not be found, falling back to preferred", |
| 849 | target.width, |
| 850 | target.height, |
| 851 | if let Some(refresh) = target.refresh { |
| 852 | format!("@{refresh}") |
| 853 | } else { |
| 854 | String::new() |
| 855 | }, |
| 856 | ); |
| 857 | } |
| 858 | debug!("picking mode: {mode:?}"); |
| 859 | |
| 860 | // We only use 8888 RGB formats, so set max bpc to 8 to allow more types of links to run. |
| 861 | match set_max_bpc(&device.drm, connector.handle(), 8) { |
| 862 | Ok(bpc) => debug!("set max bpc to {bpc}"), |
| 863 | Err(err) => debug!("error setting max bpc: {err:?}"), |
| 864 | } |
| 865 | |
| 866 | let mut gamma_props = GammaProps::new(&device.drm, crtc) |
| 867 | .map_err(|err| debug!("error getting gamma properties: {err:?}")) |
| 868 | .ok(); |
| 869 | |
| 870 | // Reset gamma in case it was set before. |
| 871 | let res = if let Some(gamma_props) = &mut gamma_props { |
| 872 | gamma_props.set_gamma(&device.drm, None) |
| 873 | } else { |
| 874 | set_gamma_for_crtc(&device.drm, crtc, None) |
| 875 | }; |
| 876 | if let Err(err) = res { |
| 877 | debug!("error resetting gamma: {err:?}"); |
| 878 | } |
| 879 | |
| 880 | let surface = device |
| 881 | .drm |
| 882 | .create_surface(crtc, mode, &[connector.handle()])?; |
| 883 | |
| 884 | // Try to enable VRR if requested. |
| 885 | match surface.vrr_supported(connector.handle()) { |
| 886 | Ok(VrrSupport::Supported | VrrSupport::RequiresModeset) => { |
| 887 | // Even if on-demand, we still disable it until later checks. |
| 888 | let vrr = config.is_vrr_always_on(); |
| 889 | let word = if vrr { "enabling" } else { "disabling" }; |
| 890 | |
| 891 | if let Err(err) = surface.use_vrr(vrr) { |
| 892 | warn!("error {} VRR: {err:?}", word); |
| 893 | } |
| 894 | } |
| 895 | Ok(VrrSupport::NotSupported) => { |
| 896 | if !config.is_vrr_always_off() { |
| 897 | warn!("cannot enable VRR because connector does not support it"); |
| 898 | } |
| 899 | |
| 900 | // Try to disable it anyway to work around a bug where resetting DRM state causes |
| 901 | // vrr_capable to be reset to 0, potentially leaving VRR_ENABLED at 1. |
| 902 | let _ = surface.use_vrr(false); |
| 903 | } |
| 904 | Err(err) => { |
| 905 | warn!("error querying for VRR support: {err:?}"); |
| 906 | } |
| 907 | } |
| 908 | |
| 909 | // Create GBM allocator. |
| 910 | let gbm_flags = GbmBufferFlags::RENDERING | GbmBufferFlags::SCANOUT; |
| 911 | let allocator = GbmAllocator::new(device.gbm.clone(), gbm_flags); |
| 912 | |
| 913 | // Update the output mode. |
| 914 | let (physical_width, physical_height) = connector.size().unwrap_or((0, 0)); |
| 915 | |
| 916 | let output = Output::new( |
| 917 | connector_name.clone(), |
| 918 | PhysicalProperties { |
| 919 | size: (physical_width as i32, physical_height as i32).into(), |
| 920 | subpixel: connector.subpixel().into(), |
| 921 | model: output_name.model.as_deref().unwrap_or("Unknown").to_owned(), |
| 922 | make: output_name.make.as_deref().unwrap_or("Unknown").to_owned(), |
| 923 | }, |
| 924 | ); |
| 925 | |
| 926 | let wl_mode = Mode::from(mode); |
| 927 | output.change_current_state(Some(wl_mode), None, None, None); |
| 928 | output.set_preferred(wl_mode); |
| 929 | |
| 930 | output |
| 931 | .user_data() |
| 932 | .insert_if_missing(|| TtyOutputState { node, crtc }); |
| 933 | output.user_data().insert_if_missing(|| output_name.clone()); |
| 934 | |
| 935 | let renderer = self.gpu_manager.single_renderer(&device.render_node)?; |
| 936 | let egl_context = renderer.as_ref().egl_context(); |
| 937 | let render_formats = egl_context.dmabuf_render_formats(); |
| 938 | |
| 939 | // Filter out the CCS modifiers as they have increased bandwidth, causing some monitor |
| 940 | // configurations to stop working. |
| 941 | // |
| 942 | // The invalid modifier attempt below should make this unnecessary in some cases, but it |
| 943 | // would still be a bad idea to remove this until Smithay has some kind of full-device |
| 944 | // modesetting test that is able to "downgrade" existing connector modifiers to get enough |
| 945 | // bandwidth for a newly connected one. |
| 946 | let render_formats = render_formats |
| 947 | .iter() |
| 948 | .copied() |
| 949 | .filter(|format| { |
| 950 | !matches!( |
| 951 | format.modifier, |
| 952 | Modifier::I915_y_tiled_ccs |
| 953 | // I915_FORMAT_MOD_Yf_TILED_CCS |
| 954 | | Modifier::Unrecognized(0x100000000000005) |
| 955 | | Modifier::I915_y_tiled_gen12_rc_ccs |
| 956 | | Modifier::I915_y_tiled_gen12_mc_ccs |
| 957 | // I915_FORMAT_MOD_Y_TILED_GEN12_RC_CCS_CC |
| 958 | | Modifier::Unrecognized(0x100000000000008) |
| 959 | // I915_FORMAT_MOD_4_TILED_DG2_RC_CCS |
| 960 | | Modifier::Unrecognized(0x10000000000000a) |
| 961 | // I915_FORMAT_MOD_4_TILED_DG2_MC_CCS |
| 962 | | Modifier::Unrecognized(0x10000000000000b) |
| 963 | // I915_FORMAT_MOD_4_TILED_DG2_RC_CCS_CC |
| 964 | | Modifier::Unrecognized(0x10000000000000c) |
| 965 | ) |
| 966 | }) |
| 967 | .collect::<FormatSet>(); |
| 968 | |
| 969 | // Create the compositor. |
| 970 | let res = DrmCompositor::new( |
| 971 | OutputModeSource::Auto(output.clone()), |
| 972 | surface, |
| 973 | None, |
| 974 | allocator.clone(), |
| 975 | GbmFramebufferExporter::new(device.gbm.clone()), |
| 976 | SUPPORTED_COLOR_FORMATS, |
| 977 | // This is only used to pick a good internal format, so it can use the surface's render |
| 978 | // formats, even though we only ever render on the primary GPU. |
| 979 | render_formats.clone(), |
| 980 | device.drm.cursor_size(), |
| 981 | Some(device.gbm.clone()), |
| 982 | ); |
| 983 | |
| 984 | let mut compositor = match res { |
| 985 | Ok(x) => x, |
| 986 | Err(err) => { |
| 987 | warn!("error creating DRM compositor, will try with invalid modifier: {err:?}"); |
| 988 | |
| 989 | let render_formats = render_formats |
| 990 | .iter() |
| 991 | .copied() |
| 992 | .filter(|format| format.modifier == Modifier::Invalid) |
| 993 | .collect::<FormatSet>(); |
| 994 | |
| 995 | // DrmCompositor::new() consumed the surface... |
| 996 | let surface = device |
| 997 | .drm |
| 998 | .create_surface(crtc, mode, &[connector.handle()])?; |
| 999 | |
| 1000 | DrmCompositor::new( |
| 1001 | OutputModeSource::Auto(output.clone()), |
| 1002 | surface, |
| 1003 | None, |
| 1004 | allocator, |
| 1005 | GbmFramebufferExporter::new(device.gbm.clone()), |
| 1006 | SUPPORTED_COLOR_FORMATS, |
| 1007 | render_formats, |
| 1008 | device.drm.cursor_size(), |
| 1009 | Some(device.gbm.clone()), |
| 1010 | ) |
| 1011 | .context("error creating DRM compositor")? |
| 1012 | } |
| 1013 | }; |
| 1014 | |
| 1015 | if self.debug_tint { |
| 1016 | compositor.set_debug_flags(DebugFlags::TINT); |
| 1017 | } |
| 1018 | |
| 1019 | let mut dmabuf_feedback = None; |
| 1020 | if let Ok(primary_renderer) = self.gpu_manager.single_renderer(&self.primary_render_node) { |
| 1021 | let primary_formats = primary_renderer.dmabuf_formats(); |
| 1022 | |
| 1023 | match surface_dmabuf_feedback( |
| 1024 | &compositor, |
| 1025 | primary_formats, |
| 1026 | self.primary_render_node, |
| 1027 | device.render_node, |
| 1028 | ) { |
| 1029 | Ok(feedback) => { |
| 1030 | dmabuf_feedback = Some(feedback); |
| 1031 | } |
| 1032 | Err(err) => { |
| 1033 | warn!("error building dmabuf feedback: {err:?}"); |
| 1034 | } |
| 1035 | } |
| 1036 | } |
| 1037 | |
| 1038 | // Some buggy monitors replug upon powering off, so powering on here would prevent such |
| 1039 | // monitors from powering off. Therefore, we avoid unconditionally powering on. |
| 1040 | if !niri.monitors_active { |
| 1041 | if let Err(err) = compositor.clear() { |
| 1042 | warn!("error clearing drm surface: {err:?}"); |
| 1043 | } |
| 1044 | } |
| 1045 | |
| 1046 | let vrr_enabled = compositor.vrr_enabled(); |
| 1047 | |
| 1048 | let vblank_frame_name = |
| 1049 | tracy_client::FrameName::new_leak(format!("vblank on {connector_name}")); |
| 1050 | let time_since_presentation_plot_name = tracy_client::PlotName::new_leak(format!( |
| 1051 | "{connector_name} time since presentation, ms" |
| 1052 | )); |
| 1053 | let presentation_misprediction_plot_name = tracy_client::PlotName::new_leak(format!( |
| 1054 | "{connector_name} presentation misprediction, ms" |
| 1055 | )); |
| 1056 | let sequence_delta_plot_name = |
| 1057 | tracy_client::PlotName::new_leak(format!("{connector_name} sequence delta")); |
| 1058 | |
| 1059 | let surface = Surface { |
| 1060 | name: output_name, |
| 1061 | connector: connector.handle(), |
| 1062 | compositor, |
| 1063 | dmabuf_feedback, |
| 1064 | gamma_props, |
| 1065 | pending_gamma_change: None, |
| 1066 | vblank_frame: None, |
| 1067 | vblank_frame_name, |
| 1068 | time_since_presentation_plot_name, |
| 1069 | presentation_misprediction_plot_name, |
| 1070 | sequence_delta_plot_name, |
| 1071 | }; |
| 1072 | |
| 1073 | let res = device.surfaces.insert(crtc, surface); |
| 1074 | assert!(res.is_none(), "crtc must not have already existed"); |
| 1075 | |
| 1076 | niri.add_output(output.clone(), Some(refresh_interval(mode)), vrr_enabled); |
| 1077 | |
| 1078 | if niri.monitors_active { |
| 1079 | // Redraw the new monitor. |
| 1080 | niri.event_loop.insert_idle(move |state| { |
| 1081 | // Guard against output disconnecting before the idle has a chance to run. |
| 1082 | if state.niri.output_state.contains_key(&output) { |
| 1083 | state.niri.queue_redraw(&output); |
| 1084 | } |
| 1085 | }); |
| 1086 | } |
| 1087 | |
| 1088 | Ok(()) |
| 1089 | } |
| 1090 | |
| 1091 | fn connector_disconnected(&mut self, niri: &mut Niri, node: DrmNode, crtc: crtc::Handle) { |
| 1092 | let Some(device) = self.devices.get_mut(&node) else { |
| 1093 | debug!("disconnecting connector for crtc: {crtc:?}"); |
| 1094 | error!("missing device"); |
| 1095 | return; |
| 1096 | }; |
| 1097 | |
| 1098 | let Some(surface) = device.surfaces.remove(&crtc) else { |
| 1099 | debug!("disconnecting connector for crtc: {crtc:?}"); |
| 1100 | |
| 1101 | if let Some((conn, _)) = device |
| 1102 | .non_desktop_connectors |
| 1103 | .iter() |
| 1104 | .find(|(_, crtc_)| *crtc_ == crtc) |
| 1105 | { |
| 1106 | debug!("withdrawing non-desktop connector from DRM leasing"); |
| 1107 | |
| 1108 | let conn = *conn; |
| 1109 | device.non_desktop_connectors.remove(&(conn, crtc)); |
| 1110 | |
| 1111 | if let Some(lease_state) = &mut device.drm_lease_state { |
| 1112 | lease_state.withdraw_connector(conn); |
| 1113 | } |
| 1114 | } else { |
| 1115 | debug!("crtc wasn't enabled"); |
| 1116 | } |
| 1117 | |
| 1118 | return; |
| 1119 | }; |
| 1120 | |
| 1121 | debug!("disconnecting connector: {:?}", surface.name.connector); |
| 1122 | |
| 1123 | let output = niri |
| 1124 | .global_space |
| 1125 | .outputs() |
| 1126 | .find(|output| { |
| 1127 | let tty_state: &TtyOutputState = output.user_data().get().unwrap(); |
| 1128 | tty_state.node == node && tty_state.crtc == crtc |
| 1129 | }) |
| 1130 | .cloned(); |
| 1131 | if let Some(output) = output { |
| 1132 | niri.remove_output(&output); |
| 1133 | } else { |
| 1134 | error!("missing output for crtc {crtc:?}"); |
| 1135 | }; |
| 1136 | } |
| 1137 | |
| 1138 | fn on_vblank( |
| 1139 | &mut self, |
| 1140 | niri: &mut Niri, |
| 1141 | node: DrmNode, |
| 1142 | crtc: crtc::Handle, |
| 1143 | meta: DrmEventMetadata, |
| 1144 | ) { |
| 1145 | let span = tracy_client::span!("Tty::on_vblank"); |
| 1146 | |
| 1147 | let now = get_monotonic_time(); |
| 1148 | |
| 1149 | let Some(device) = self.devices.get_mut(&node) else { |
| 1150 | // I've seen it happen. |
| 1151 | error!("missing device in vblank callback for crtc {crtc:?}"); |
| 1152 | return; |
| 1153 | }; |
| 1154 | |
| 1155 | let Some(surface) = device.surfaces.get_mut(&crtc) else { |
| 1156 | error!("missing surface in vblank callback for crtc {crtc:?}"); |
| 1157 | return; |
| 1158 | }; |
| 1159 | |
| 1160 | // Finish the Tracy frame, if any. |
| 1161 | drop(surface.vblank_frame.take()); |
| 1162 | |
| 1163 | let name = &surface.name.connector; |
| 1164 | trace!("vblank on {name} {meta:?}"); |
| 1165 | span.emit_text(name); |
| 1166 | |
| 1167 | let presentation_time = match meta.time { |
| 1168 | DrmEventTime::Monotonic(time) => time, |
| 1169 | DrmEventTime::Realtime(_) => { |
| 1170 | // Not supported. |
| 1171 | |
| 1172 | // This value will be ignored in the frame clock code. |
| 1173 | Duration::ZERO |
| 1174 | } |
| 1175 | }; |
| 1176 | let presentation_time = if niri.config.borrow().debug.emulate_zero_presentation_time { |
| 1177 | Duration::ZERO |
| 1178 | } else { |
| 1179 | presentation_time |
| 1180 | }; |
| 1181 | |
| 1182 | let message = if presentation_time.is_zero() { |
| 1183 | format!("vblank on {name}, presentation time unknown") |
| 1184 | } else if presentation_time > now { |
| 1185 | let diff = presentation_time - now; |
| 1186 | tracy_client::Client::running().unwrap().plot( |
| 1187 | surface.time_since_presentation_plot_name, |
| 1188 | -diff.as_secs_f64() * 1000., |
| 1189 | ); |
| 1190 | format!("vblank on {name}, presentation is {diff:?} later") |
| 1191 | } else { |
| 1192 | let diff = now - presentation_time; |
| 1193 | tracy_client::Client::running().unwrap().plot( |
| 1194 | surface.time_since_presentation_plot_name, |
| 1195 | diff.as_secs_f64() * 1000., |
| 1196 | ); |
| 1197 | format!("vblank on {name}, presentation was {diff:?} ago") |
| 1198 | }; |
| 1199 | tracy_client::Client::running() |
| 1200 | .unwrap() |
| 1201 | .message(&message, 0); |
| 1202 | |
| 1203 | let Some(output) = niri |
| 1204 | .global_space |
| 1205 | .outputs() |
| 1206 | .find(|output| { |
| 1207 | let tty_state: &TtyOutputState = output.user_data().get().unwrap(); |
| 1208 | tty_state.node == node && tty_state.crtc == crtc |
| 1209 | }) |
| 1210 | .cloned() |
| 1211 | else { |
| 1212 | error!("missing output in global space for {name}"); |
| 1213 | return; |
| 1214 | }; |
| 1215 | |
| 1216 | let Some(output_state) = niri.output_state.get_mut(&output) else { |
| 1217 | error!("missing output state for {name}"); |
| 1218 | return; |
| 1219 | }; |
| 1220 | |
| 1221 | let redraw_needed = match mem::replace(&mut output_state.redraw_state, RedrawState::Idle) { |
| 1222 | RedrawState::WaitingForVBlank { redraw_needed } => redraw_needed, |
| 1223 | state @ (RedrawState::Idle |
| 1224 | | RedrawState::Queued |
| 1225 | | RedrawState::WaitingForEstimatedVBlank(_) |
| 1226 | | RedrawState::WaitingForEstimatedVBlankAndQueued(_)) => { |
| 1227 | // This is an error!() because it shouldn't happen, but on some systems it somehow |
| 1228 | // does. Kernel sending rogue vblank events? |
| 1229 | // |
| 1230 | // https://github.com/YaLTeR/niri/issues/556 |
| 1231 | // https://github.com/YaLTeR/niri/issues/615 |
| 1232 | error!( |
| 1233 | "unexpected redraw state for output {name} (should be WaitingForVBlank); \ |
| 1234 | can happen when resuming from sleep or powering on monitors: {state:?}" |
| 1235 | ); |
| 1236 | true |
| 1237 | } |
| 1238 | }; |
| 1239 | |
| 1240 | // Mark the last frame as submitted. |
| 1241 | match surface.compositor.frame_submitted() { |
| 1242 | Ok(Some((mut feedback, target_presentation_time))) => { |
| 1243 | let refresh = match output_state.frame_clock.refresh_interval() { |
| 1244 | Some(refresh) => { |
| 1245 | if output_state.frame_clock.vrr() { |
| 1246 | Refresh::Variable(refresh) |
| 1247 | } else { |
| 1248 | Refresh::Fixed(refresh) |
| 1249 | } |
| 1250 | } |
| 1251 | None => Refresh::Unknown, |
| 1252 | }; |
| 1253 | |
| 1254 | // FIXME: ideally should be monotonically increasing for a surface. |
| 1255 | let seq = meta.sequence as u64; |
| 1256 | let mut flags = wp_presentation_feedback::Kind::Vsync |
| 1257 | | wp_presentation_feedback::Kind::HwCompletion; |
| 1258 | |
| 1259 | let time = if presentation_time.is_zero() { |
| 1260 | now |
| 1261 | } else { |
| 1262 | flags.insert(wp_presentation_feedback::Kind::HwClock); |
| 1263 | presentation_time |
| 1264 | }; |
| 1265 | |
| 1266 | feedback.presented::<_, smithay::utils::Monotonic>(time, refresh, seq, flags); |
| 1267 | |
| 1268 | if !presentation_time.is_zero() { |
| 1269 | let misprediction_s = |
| 1270 | presentation_time.as_secs_f64() - target_presentation_time.as_secs_f64(); |
| 1271 | tracy_client::Client::running().unwrap().plot( |
| 1272 | surface.presentation_misprediction_plot_name, |
| 1273 | misprediction_s * 1000., |
| 1274 | ); |
| 1275 | } |
| 1276 | } |
| 1277 | Ok(None) => (), |
| 1278 | Err(err) => { |
| 1279 | warn!("error marking frame as submitted: {err}"); |
| 1280 | } |
| 1281 | } |
| 1282 | |
| 1283 | if let Some(last_sequence) = output_state.last_drm_sequence { |
| 1284 | let delta = meta.sequence as f64 - last_sequence as f64; |
| 1285 | tracy_client::Client::running() |
| 1286 | .unwrap() |
| 1287 | .plot(surface.sequence_delta_plot_name, delta); |
| 1288 | } |
| 1289 | output_state.last_drm_sequence = Some(meta.sequence); |
| 1290 | |
| 1291 | output_state.frame_clock.presented(presentation_time); |
| 1292 | |
| 1293 | if redraw_needed || output_state.unfinished_animations_remain { |
| 1294 | let vblank_frame = tracy_client::Client::running() |
| 1295 | .unwrap() |
| 1296 | .non_continuous_frame(surface.vblank_frame_name); |
| 1297 | surface.vblank_frame = Some(vblank_frame); |
| 1298 | |
| 1299 | niri.queue_redraw(&output); |
| 1300 | } else { |
| 1301 | niri.send_frame_callbacks(&output); |
| 1302 | } |
| 1303 | } |
| 1304 | |
| 1305 | fn on_estimated_vblank_timer(&self, niri: &mut Niri, output: Output) { |
| 1306 | let span = tracy_client::span!("Tty::on_estimated_vblank_timer"); |
| 1307 | |
| 1308 | let name = output.name(); |
| 1309 | span.emit_text(&name); |
| 1310 | |
| 1311 | let Some(output_state) = niri.output_state.get_mut(&output) else { |
| 1312 | error!("missing output state for {name}"); |
| 1313 | return; |
| 1314 | }; |
| 1315 | |
| 1316 | // We waited for the timer, now we can send frame callbacks again. |
| 1317 | output_state.frame_callback_sequence = output_state.frame_callback_sequence.wrapping_add(1); |
| 1318 | |
| 1319 | match mem::replace(&mut output_state.redraw_state, RedrawState::Idle) { |
| 1320 | RedrawState::Idle => unreachable!(), |
| 1321 | RedrawState::Queued => unreachable!(), |
| 1322 | RedrawState::WaitingForVBlank { .. } => unreachable!(), |
| 1323 | RedrawState::WaitingForEstimatedVBlank(_) => (), |
| 1324 | // The timer fired just in front of a redraw. |
| 1325 | RedrawState::WaitingForEstimatedVBlankAndQueued(_) => { |
| 1326 | output_state.redraw_state = RedrawState::Queued; |
| 1327 | return; |
| 1328 | } |
| 1329 | } |
| 1330 | |
| 1331 | if output_state.unfinished_animations_remain { |
| 1332 | niri.queue_redraw(&output); |
| 1333 | } else { |
| 1334 | niri.send_frame_callbacks(&output); |
| 1335 | } |
| 1336 | } |
| 1337 | |
| 1338 | pub fn seat_name(&self) -> String { |
| 1339 | self.session.seat() |
| 1340 | } |
| 1341 | |
| 1342 | pub fn with_primary_renderer<T>( |
| 1343 | &mut self, |
| 1344 | f: impl FnOnce(&mut GlesRenderer) -> T, |
| 1345 | ) -> Option<T> { |
| 1346 | let mut renderer = self |
| 1347 | .gpu_manager |
| 1348 | .single_renderer(&self.primary_render_node) |
| 1349 | .ok()?; |
| 1350 | Some(f(renderer.as_gles_renderer())) |
| 1351 | } |
| 1352 | |
| 1353 | pub fn render( |
| 1354 | &mut self, |
| 1355 | niri: &mut Niri, |
| 1356 | output: &Output, |
| 1357 | target_presentation_time: Duration, |
| 1358 | ) -> RenderResult { |
| 1359 | let span = tracy_client::span!("Tty::render"); |
| 1360 | |
| 1361 | let mut rv = RenderResult::Skipped; |
| 1362 | |
| 1363 | let tty_state: &TtyOutputState = output.user_data().get().unwrap(); |
| 1364 | let Some(device) = self.devices.get_mut(&tty_state.node) else { |
| 1365 | error!("missing output device"); |
| 1366 | return rv; |
| 1367 | }; |
| 1368 | |
| 1369 | let Some(surface) = device.surfaces.get_mut(&tty_state.crtc) else { |
| 1370 | error!("missing surface"); |
| 1371 | return rv; |
| 1372 | }; |
| 1373 | |
| 1374 | span.emit_text(&surface.name.connector); |
| 1375 | |
| 1376 | if !device.drm.is_active() { |
| 1377 | warn!("device is inactive"); |
| 1378 | return rv; |
| 1379 | } |
| 1380 | |
| 1381 | let mut renderer = match self.gpu_manager.renderer( |
| 1382 | &self.primary_render_node, |
| 1383 | &device.render_node, |
| 1384 | surface.compositor.format(), |
| 1385 | ) { |
| 1386 | Ok(renderer) => renderer, |
| 1387 | Err(err) => { |
| 1388 | warn!("error creating renderer for primary GPU: {err:?}"); |
| 1389 | return rv; |
| 1390 | } |
| 1391 | }; |
| 1392 | |
| 1393 | // Render the elements. |
| 1394 | let mut elements = |
| 1395 | niri.render::<TtyRenderer>(&mut renderer, output, true, RenderTarget::Output); |
| 1396 | |
| 1397 | // Visualize the damage, if enabled. |
| 1398 | if niri.debug_draw_damage { |
| 1399 | let output_state = niri.output_state.get_mut(output).unwrap(); |
| 1400 | draw_damage(&mut output_state.debug_damage_tracker, &mut elements); |
| 1401 | } |
| 1402 | |
| 1403 | // Overlay planes are disabled by default as they cause weird performance issues on my |
| 1404 | // system. |
| 1405 | let flags = { |
| 1406 | let debug = &self.config.borrow().debug; |
| 1407 | |
| 1408 | let primary_scanout_flag = if debug.restrict_primary_scanout_to_matching_format { |
| 1409 | FrameFlags::ALLOW_PRIMARY_PLANE_SCANOUT |
| 1410 | } else { |
| 1411 | FrameFlags::ALLOW_PRIMARY_PLANE_SCANOUT_ANY |
| 1412 | }; |
| 1413 | let mut flags = primary_scanout_flag | FrameFlags::ALLOW_CURSOR_PLANE_SCANOUT; |
| 1414 | |
| 1415 | if debug.enable_overlay_planes { |
| 1416 | flags.insert(FrameFlags::ALLOW_OVERLAY_PLANE_SCANOUT); |
| 1417 | } |
| 1418 | if debug.disable_direct_scanout { |
| 1419 | flags.remove(primary_scanout_flag); |
| 1420 | flags.remove(FrameFlags::ALLOW_OVERLAY_PLANE_SCANOUT); |
| 1421 | } |
| 1422 | if debug.disable_cursor_plane { |
| 1423 | flags.remove(FrameFlags::ALLOW_CURSOR_PLANE_SCANOUT); |
| 1424 | } |
| 1425 | |
| 1426 | flags |
| 1427 | }; |
| 1428 | |
| 1429 | // Hand them over to the DRM. |
| 1430 | let drm_compositor = &mut surface.compositor; |
| 1431 | match drm_compositor.render_frame::<_, _>(&mut renderer, &elements, [0.; 4], flags) { |
| 1432 | Ok(res) => { |
| 1433 | let needs_sync = res.needs_sync() |
| 1434 | || self |
| 1435 | .config |
| 1436 | .borrow() |
| 1437 | .debug |
| 1438 | .wait_for_frame_completion_before_queueing; |
| 1439 | if needs_sync { |
| 1440 | if let PrimaryPlaneElement::Swapchain(element) = res.primary_element { |
| 1441 | let _span = tracy_client::span!("wait for completion"); |
| 1442 | if let Err(err) = element.sync.wait() { |
| 1443 | warn!("error waiting for frame completion: {err:?}"); |
| 1444 | } |
| 1445 | } |
| 1446 | } |
| 1447 | |
| 1448 | niri.update_primary_scanout_output(output, &res.states); |
| 1449 | if let Some(dmabuf_feedback) = surface.dmabuf_feedback.as_ref() { |
| 1450 | niri.send_dmabuf_feedbacks(output, dmabuf_feedback, &res.states); |
| 1451 | } |
| 1452 | |
| 1453 | if !res.is_empty { |
| 1454 | let presentation_feedbacks = |
| 1455 | niri.take_presentation_feedbacks(output, &res.states); |
| 1456 | let data = (presentation_feedbacks, target_presentation_time); |
| 1457 | |
| 1458 | match drm_compositor.queue_frame(data) { |
| 1459 | Ok(()) => { |
| 1460 | let output_state = niri.output_state.get_mut(output).unwrap(); |
| 1461 | let new_state = RedrawState::WaitingForVBlank { |
| 1462 | redraw_needed: false, |
| 1463 | }; |
| 1464 | match mem::replace(&mut output_state.redraw_state, new_state) { |
| 1465 | RedrawState::Idle => unreachable!(), |
| 1466 | RedrawState::Queued => (), |
| 1467 | RedrawState::WaitingForVBlank { .. } => unreachable!(), |
| 1468 | RedrawState::WaitingForEstimatedVBlank(_) => unreachable!(), |
| 1469 | RedrawState::WaitingForEstimatedVBlankAndQueued(token) => { |
| 1470 | niri.event_loop.remove(token); |
| 1471 | } |
| 1472 | }; |
| 1473 | |
| 1474 | // We queued this frame successfully, so the current client buffers were |
| 1475 | // latched. We can send frame callbacks now, since a new client commit |
| 1476 | // will no longer overwrite this frame and will wait for a VBlank. |
| 1477 | output_state.frame_callback_sequence = |
| 1478 | output_state.frame_callback_sequence.wrapping_add(1); |
| 1479 | |
| 1480 | return RenderResult::Submitted; |
| 1481 | } |
| 1482 | Err(err) => { |
| 1483 | warn!("error queueing frame: {err}"); |
| 1484 | } |
| 1485 | } |
| 1486 | } else { |
| 1487 | rv = RenderResult::NoDamage; |
| 1488 | } |
| 1489 | } |
| 1490 | Err(err) => { |
| 1491 | // Can fail if we switched to a different TTY. |
| 1492 | warn!("error rendering frame: {err}"); |
| 1493 | } |
| 1494 | } |
| 1495 | |
| 1496 | // We're not expecting a vblank right after this. |
| 1497 | drop(surface.vblank_frame.take()); |
| 1498 | |
| 1499 | // Queue a timer to fire at the predicted vblank time. |
| 1500 | queue_estimated_vblank_timer(niri, output.clone(), target_presentation_time); |
| 1501 | |
| 1502 | rv |
| 1503 | } |
| 1504 | |
| 1505 | pub fn change_vt(&mut self, vt: i32) { |
| 1506 | if let Err(err) = self.session.change_vt(vt) { |
| 1507 | warn!("error changing VT: {err}"); |
| 1508 | } |
| 1509 | } |
| 1510 | |
| 1511 | pub fn suspend(&self) { |
| 1512 | #[cfg(feature = "dbus")] |
| 1513 | if let Err(err) = suspend() { |
| 1514 | warn!("error suspending: {err:?}"); |
| 1515 | } |
| 1516 | } |
| 1517 | |
| 1518 | pub fn toggle_debug_tint(&mut self) { |
| 1519 | self.debug_tint = !self.debug_tint; |
| 1520 | |
| 1521 | for device in self.devices.values_mut() { |
| 1522 | for surface in device.surfaces.values_mut() { |
| 1523 | let compositor = &mut surface.compositor; |
| 1524 | |
| 1525 | let mut flags = compositor.debug_flags(); |
| 1526 | flags.set(DebugFlags::TINT, self.debug_tint); |
| 1527 | compositor.set_debug_flags(flags); |
| 1528 | } |
| 1529 | } |
| 1530 | } |
| 1531 | |
| 1532 | pub fn import_dmabuf(&mut self, dmabuf: &Dmabuf) -> bool { |
| 1533 | let mut renderer = match self.gpu_manager.single_renderer(&self.primary_render_node) { |
| 1534 | Ok(renderer) => renderer, |
| 1535 | Err(err) => { |
| 1536 | debug!("error creating renderer for primary GPU: {err:?}"); |
| 1537 | return false; |
| 1538 | } |
| 1539 | }; |
| 1540 | |
| 1541 | match renderer.import_dmabuf(dmabuf, None) { |
| 1542 | Ok(_texture) => { |
| 1543 | dmabuf.set_node(Some(self.primary_render_node)); |
| 1544 | true |
| 1545 | } |
| 1546 | Err(err) => { |
| 1547 | debug!("error importing dmabuf: {err:?}"); |
| 1548 | false |
| 1549 | } |
| 1550 | } |
| 1551 | } |
| 1552 | |
| 1553 | pub fn early_import(&mut self, surface: &WlSurface) { |
| 1554 | if let Err(err) = self.gpu_manager.early_import( |
| 1555 | // We always render on the primary GPU. |
| 1556 | self.primary_render_node, |
| 1557 | surface, |
| 1558 | ) { |
| 1559 | warn!("error doing early import: {err:?}"); |
| 1560 | } |
| 1561 | } |
| 1562 | |
| 1563 | pub fn get_gamma_size(&self, output: &Output) -> anyhow::Result<u32> { |
| 1564 | let tty_state = output.user_data().get::<TtyOutputState>().unwrap(); |
| 1565 | let crtc = tty_state.crtc; |
| 1566 | |
| 1567 | let device = self |
| 1568 | .devices |
| 1569 | .get(&tty_state.node) |
| 1570 | .context("missing device")?; |
| 1571 | |
| 1572 | let surface = device.surfaces.get(&crtc).context("missing surface")?; |
| 1573 | if let Some(gamma_props) = &surface.gamma_props { |
| 1574 | gamma_props.gamma_size(&device.drm) |
| 1575 | } else { |
| 1576 | let info = device |
| 1577 | .drm |
| 1578 | .get_crtc(crtc) |
| 1579 | .context("error getting crtc info")?; |
| 1580 | Ok(info.gamma_length()) |
| 1581 | } |
| 1582 | } |
| 1583 | |
| 1584 | pub fn set_gamma(&mut self, output: &Output, ramp: Option<Vec<u16>>) -> anyhow::Result<()> { |
| 1585 | let tty_state = output.user_data().get::<TtyOutputState>().unwrap(); |
| 1586 | let crtc = tty_state.crtc; |
| 1587 | |
| 1588 | let device = self |
| 1589 | .devices |
| 1590 | .get_mut(&tty_state.node) |
| 1591 | .context("missing device")?; |
| 1592 | let surface = device.surfaces.get_mut(&crtc).context("missing surface")?; |
| 1593 | |
| 1594 | // Cannot change properties while the device is inactive. |
| 1595 | if !self.session.is_active() { |
| 1596 | surface.pending_gamma_change = Some(ramp); |
| 1597 | return Ok(()); |
| 1598 | } |
| 1599 | |
| 1600 | let ramp = ramp.as_deref(); |
| 1601 | if let Some(gamma_props) = &mut surface.gamma_props { |
| 1602 | gamma_props.set_gamma(&device.drm, ramp) |
| 1603 | } else { |
| 1604 | set_gamma_for_crtc(&device.drm, crtc, ramp) |
| 1605 | } |
| 1606 | } |
| 1607 | |
| 1608 | fn refresh_ipc_outputs(&self, niri: &mut Niri) { |
| 1609 | let _span = tracy_client::span!("Tty::refresh_ipc_outputs"); |
| 1610 | |
| 1611 | let mut ipc_outputs = HashMap::new(); |
| 1612 | let disable_monitor_names = self.config.borrow().debug.disable_monitor_names; |
| 1613 | |
| 1614 | for (node, device) in &self.devices { |
| 1615 | for (connector, crtc) in device.drm_scanner.crtcs() { |
| 1616 | let connector_name = format_connector_name(connector); |
| 1617 | let physical_size = connector.size(); |
| 1618 | let output_name = device.known_crtc_name(&crtc, connector, disable_monitor_names); |
| 1619 | |
| 1620 | let surface = device.surfaces.get(&crtc); |
| 1621 | let current_crtc_mode = surface.map(|surface| surface.compositor.pending_mode()); |
| 1622 | let mut current_mode = None; |
| 1623 | |
| 1624 | let modes = connector |
| 1625 | .modes() |
| 1626 | .iter() |
| 1627 | .filter(|m| !m.flags().contains(ModeFlags::INTERLACE)) |
| 1628 | .enumerate() |
| 1629 | .map(|(idx, m)| { |
| 1630 | if Some(*m) == current_crtc_mode { |
| 1631 | current_mode = Some(idx); |
| 1632 | } |
| 1633 | |
| 1634 | niri_ipc::Mode { |
| 1635 | width: m.size().0, |
| 1636 | height: m.size().1, |
| 1637 | refresh_rate: Mode::from(*m).refresh as u32, |
| 1638 | is_preferred: m.mode_type().contains(ModeTypeFlags::PREFERRED), |
| 1639 | } |
| 1640 | }) |
| 1641 | .collect(); |
| 1642 | |
| 1643 | if let Some(crtc_mode) = current_crtc_mode { |
| 1644 | if current_mode.is_none() { |
| 1645 | if crtc_mode.flags().contains(ModeFlags::INTERLACE) { |
| 1646 | warn!("connector mode list missing current mode (interlaced)"); |
| 1647 | } else { |
| 1648 | error!("connector mode list missing current mode"); |
| 1649 | } |
| 1650 | } |
| 1651 | } |
| 1652 | |
| 1653 | let vrr_supported = surface |
| 1654 | .map(|surface| { |
| 1655 | matches!( |
| 1656 | surface.compositor.vrr_supported(connector.handle()), |
| 1657 | Ok(VrrSupport::Supported | VrrSupport::RequiresModeset) |
| 1658 | ) |
| 1659 | }) |
| 1660 | .unwrap_or_else(|| { |
| 1661 | is_vrr_capable(&device.drm, connector.handle()) == Some(true) |
| 1662 | }); |
| 1663 | let vrr_enabled = surface.is_some_and(|surface| surface.compositor.vrr_enabled()); |
| 1664 | |
| 1665 | let logical = niri |
| 1666 | .global_space |
| 1667 | .outputs() |
| 1668 | .find(|output| { |
| 1669 | let tty_state: &TtyOutputState = output.user_data().get().unwrap(); |
| 1670 | tty_state.node == *node && tty_state.crtc == crtc |
| 1671 | }) |
| 1672 | .map(logical_output); |
| 1673 | |
| 1674 | let id = device.known_crtcs.get(&crtc).map(|info| info.id); |
| 1675 | let id = id.unwrap_or_else(|| { |
| 1676 | error!("crtc for connector {connector_name} missing from known"); |
| 1677 | OutputId::next() |
| 1678 | }); |
| 1679 | |
| 1680 | let ipc_output = niri_ipc::Output { |
| 1681 | name: connector_name, |
| 1682 | make: output_name.make.unwrap_or_else(|| "Unknown".into()), |
| 1683 | model: output_name.model.unwrap_or_else(|| "Unknown".into()), |
| 1684 | serial: output_name.serial, |
| 1685 | physical_size, |
| 1686 | modes, |
| 1687 | current_mode, |
| 1688 | vrr_supported, |
| 1689 | vrr_enabled, |
| 1690 | logical, |
| 1691 | }; |
| 1692 | |
| 1693 | ipc_outputs.insert(id, ipc_output); |
| 1694 | } |
| 1695 | } |
| 1696 | |
| 1697 | let mut guard = self.ipc_outputs.lock().unwrap(); |
| 1698 | *guard = ipc_outputs; |
| 1699 | niri.ipc_outputs_changed = true; |
| 1700 | } |
| 1701 | |
| 1702 | pub fn ipc_outputs(&self) -> Arc<Mutex<IpcOutputMap>> { |
| 1703 | self.ipc_outputs.clone() |
| 1704 | } |
| 1705 | |
| 1706 | #[cfg(feature = "xdp-gnome-screencast")] |
| 1707 | pub fn primary_gbm_device(&self) -> Option<GbmDevice<DrmDeviceFd>> { |
| 1708 | // Try to find a device corresponding to the primary render node. |
| 1709 | let device = self |
| 1710 | .devices |
| 1711 | .values() |
| 1712 | .find(|d| d.render_node == self.primary_render_node); |
| 1713 | // Otherwise, try to get the device corresponding to the primary node. |
| 1714 | let device = device.or_else(|| self.devices.get(&self.primary_node)); |
| 1715 | |
| 1716 | Some(device?.gbm.clone()) |
| 1717 | } |
| 1718 | |
| 1719 | pub fn set_monitors_active(&mut self, active: bool) { |
| 1720 | // We only disable the CRTC here, this will also reset the |
| 1721 | // surface state so that the next call to `render_frame` will |
| 1722 | // always produce a new frame and `queue_frame` will change |
| 1723 | // the CRTC to active. This makes sure we always enable a CRTC |
| 1724 | // within an atomic operation. |
| 1725 | if active { |
| 1726 | return; |
| 1727 | } |
| 1728 | |
| 1729 | for device in self.devices.values_mut() { |
| 1730 | for surface in device.surfaces.values_mut() { |
| 1731 | if let Err(err) = surface.compositor.clear() { |
| 1732 | warn!("error clearing drm surface: {err:?}"); |
| 1733 | } |
| 1734 | } |
| 1735 | } |
| 1736 | } |
| 1737 | |
| 1738 | pub fn set_output_on_demand_vrr(&mut self, niri: &mut Niri, output: &Output, enable_vrr: bool) { |
| 1739 | let _span = tracy_client::span!("Tty::set_output_on_demand_vrr"); |
| 1740 | |
| 1741 | let output_state = niri.output_state.get_mut(output).unwrap(); |
| 1742 | output_state.on_demand_vrr_enabled = enable_vrr; |
| 1743 | if output_state.frame_clock.vrr() == enable_vrr { |
| 1744 | return; |
| 1745 | } |
| 1746 | for (&node, device) in self.devices.iter_mut() { |
| 1747 | for (&crtc, surface) in device.surfaces.iter_mut() { |
| 1748 | let tty_state: &TtyOutputState = output.user_data().get().unwrap(); |
| 1749 | if tty_state.node == node && tty_state.crtc == crtc { |
| 1750 | let word = if enable_vrr { "enabling" } else { "disabling" }; |
| 1751 | if let Err(err) = surface.compositor.use_vrr(enable_vrr) { |
| 1752 | warn!( |
| 1753 | "output {:?}: error {} VRR: {err:?}", |
| 1754 | surface.name.connector, word |
| 1755 | ); |
| 1756 | } |
| 1757 | output_state |
| 1758 | .frame_clock |
| 1759 | .set_vrr(surface.compositor.vrr_enabled()); |
| 1760 | |
| 1761 | self.refresh_ipc_outputs(niri); |
| 1762 | return; |
| 1763 | } |
| 1764 | } |
| 1765 | } |
| 1766 | } |
| 1767 | |
| 1768 | pub fn on_output_config_changed(&mut self, niri: &mut Niri) { |
| 1769 | let _span = tracy_client::span!("Tty::on_output_config_changed"); |
| 1770 | |
| 1771 | // If we're inactive, we can't do anything, so just set a flag for later. |
| 1772 | if !self.session.is_active() { |
| 1773 | self.update_output_config_on_resume = true; |
| 1774 | return; |
| 1775 | } |
| 1776 | self.update_output_config_on_resume = false; |
| 1777 | |
| 1778 | // Figure out if we should disable laptop panels. |
| 1779 | let mut disable_laptop_panels = false; |
| 1780 | if niri.is_lid_closed { |
| 1781 | let config = self.config.borrow(); |
| 1782 | if !config.debug.keep_laptop_panel_on_when_lid_is_closed { |
| 1783 | // Check if any external monitor is connected. |
| 1784 | 'outer: for device in self.devices.values() { |
| 1785 | for (connector, _crtc) in device.drm_scanner.crtcs() { |
| 1786 | if !is_laptop_panel(&format_connector_name(connector)) { |
| 1787 | disable_laptop_panels = true; |
| 1788 | break 'outer; |
| 1789 | } |
| 1790 | } |
| 1791 | } |
| 1792 | } |
| 1793 | } |
| 1794 | let should_disable = |connector: &str| disable_laptop_panels && is_laptop_panel(connector); |
| 1795 | |
| 1796 | let mut to_disconnect = vec![]; |
| 1797 | let mut to_connect = vec![]; |
| 1798 | |
| 1799 | for (&node, device) in &mut self.devices { |
| 1800 | for (&crtc, surface) in device.surfaces.iter_mut() { |
| 1801 | let config = self |
| 1802 | .config |
| 1803 | .borrow() |
| 1804 | .outputs |
| 1805 | .find(&surface.name) |
| 1806 | .cloned() |
| 1807 | .unwrap_or_default(); |
| 1808 | if config.off || should_disable(&surface.name.connector) { |
| 1809 | to_disconnect.push((node, crtc)); |
| 1810 | continue; |
| 1811 | } |
| 1812 | |
| 1813 | // Check if we need to change the mode. |
| 1814 | let Some(connector) = device.drm_scanner.connectors().get(&surface.connector) |
| 1815 | else { |
| 1816 | error!("missing enabled connector in drm_scanner"); |
| 1817 | continue; |
| 1818 | }; |
| 1819 | |
| 1820 | let Some((mode, fallback)) = pick_mode(connector, config.mode) else { |
| 1821 | warn!("couldn't pick mode for enabled connector"); |
| 1822 | continue; |
| 1823 | }; |
| 1824 | |
| 1825 | let change_mode = surface.compositor.pending_mode() != mode; |
| 1826 | |
| 1827 | let vrr_enabled = surface.compositor.vrr_enabled(); |
| 1828 | let change_always_vrr = vrr_enabled != config.is_vrr_always_on(); |
| 1829 | let is_on_demand_vrr = config.is_vrr_on_demand(); |
| 1830 | |
| 1831 | if !change_mode && !change_always_vrr && !is_on_demand_vrr { |
| 1832 | continue; |
| 1833 | } |
| 1834 | |
| 1835 | let output = niri |
| 1836 | .global_space |
| 1837 | .outputs() |
| 1838 | .find(|output| { |
| 1839 | let tty_state: &TtyOutputState = output.user_data().get().unwrap(); |
| 1840 | tty_state.node == node && tty_state.crtc == crtc |
| 1841 | }) |
| 1842 | .cloned(); |
| 1843 | let Some(output) = output else { |
| 1844 | error!("missing output for crtc: {crtc:?}"); |
| 1845 | continue; |
| 1846 | }; |
| 1847 | let Some(output_state) = niri.output_state.get_mut(&output) else { |
| 1848 | error!("missing state for output {:?}", surface.name.connector); |
| 1849 | continue; |
| 1850 | }; |
| 1851 | |
| 1852 | if (is_on_demand_vrr && vrr_enabled != output_state.on_demand_vrr_enabled) |
| 1853 | || (!is_on_demand_vrr && change_always_vrr) |
| 1854 | { |
| 1855 | let vrr = !vrr_enabled; |
| 1856 | let word = if vrr { "enabling" } else { "disabling" }; |
| 1857 | if let Err(err) = surface.compositor.use_vrr(vrr) { |
| 1858 | warn!( |
| 1859 | "output {:?}: error {} VRR: {err:?}", |
| 1860 | surface.name.connector, word |
| 1861 | ); |
| 1862 | } |
| 1863 | output_state |
| 1864 | .frame_clock |
| 1865 | .set_vrr(surface.compositor.vrr_enabled()); |
| 1866 | } |
| 1867 | |
| 1868 | if change_mode { |
| 1869 | if fallback { |
| 1870 | let target = config.mode.unwrap(); |
| 1871 | warn!( |
| 1872 | "output {:?}: configured mode {}x{}{} could not be found, \ |
| 1873 | falling back to preferred", |
| 1874 | surface.name.connector, |
| 1875 | target.width, |
| 1876 | target.height, |
| 1877 | if let Some(refresh) = target.refresh { |
| 1878 | format!("@{refresh}") |
| 1879 | } else { |
| 1880 | String::new() |
| 1881 | }, |
| 1882 | ); |
| 1883 | } |
| 1884 | |
| 1885 | debug!( |
| 1886 | "output {:?}: picking mode: {mode:?}", |
| 1887 | surface.name.connector |
| 1888 | ); |
| 1889 | if let Err(err) = surface.compositor.use_mode(mode) { |
| 1890 | warn!("error changing mode: {err:?}"); |
| 1891 | continue; |
| 1892 | } |
| 1893 | |
| 1894 | let wl_mode = Mode::from(mode); |
| 1895 | output.change_current_state(Some(wl_mode), None, None, None); |
| 1896 | output.set_preferred(wl_mode); |
| 1897 | output_state.frame_clock = FrameClock::new( |
| 1898 | Some(refresh_interval(mode)), |
| 1899 | surface.compositor.vrr_enabled(), |
| 1900 | ); |
| 1901 | niri.output_resized(&output); |
| 1902 | } |
| 1903 | } |
| 1904 | |
| 1905 | let config = self.config.borrow(); |
| 1906 | let disable_monitor_names = config.debug.disable_monitor_names; |
| 1907 | |
| 1908 | for (connector, crtc) in device.drm_scanner.crtcs() { |
| 1909 | // Check if connected. |
| 1910 | if connector.state() != connector::State::Connected { |
| 1911 | continue; |
| 1912 | } |
| 1913 | |
| 1914 | // Check if already enabled. |
| 1915 | if device.surfaces.contains_key(&crtc) |
| 1916 | || device |
| 1917 | .non_desktop_connectors |
| 1918 | .contains(&(connector.handle(), crtc)) |
| 1919 | { |
| 1920 | continue; |
| 1921 | } |
| 1922 | |
| 1923 | let output_name = device.known_crtc_name(&crtc, connector, disable_monitor_names); |
| 1924 | |
| 1925 | let config = config |
| 1926 | .outputs |
| 1927 | .find(&output_name) |
| 1928 | .cloned() |
| 1929 | .unwrap_or_default(); |
| 1930 | |
| 1931 | if !(config.off || should_disable(&output_name.connector)) { |
| 1932 | to_connect.push((node, connector.clone(), crtc, output_name)); |
| 1933 | } |
| 1934 | } |
| 1935 | } |
| 1936 | |
| 1937 | for (node, crtc) in to_disconnect { |
| 1938 | self.connector_disconnected(niri, node, crtc); |
| 1939 | } |
| 1940 | |
| 1941 | // Sort by output name to get more predictable first focused output at initial compositor |
| 1942 | // startup, when multiple connectors appear at once. |
| 1943 | to_connect.sort_unstable_by(|a, b| a.3.compare(&b.3)); |
| 1944 | |
| 1945 | for (node, connector, crtc, _name) in to_connect { |
| 1946 | if let Err(err) = self.connector_connected(niri, node, connector, crtc) { |
| 1947 | warn!("error connecting connector: {err:?}"); |
| 1948 | } |
| 1949 | } |
| 1950 | |
| 1951 | self.refresh_ipc_outputs(niri); |
| 1952 | } |
| 1953 | |
| 1954 | pub fn get_device_from_node(&mut self, node: DrmNode) -> Option<&mut OutputDevice> { |
| 1955 | self.devices.get_mut(&node) |
| 1956 | } |
| 1957 | |
| 1958 | pub fn disconnected_connector_name_by_name_match(&self, target: &str) -> Option<OutputName> { |
| 1959 | let disable_monitor_names = self.config.borrow().debug.disable_monitor_names; |
| 1960 | for device in self.devices.values() { |
| 1961 | for (connector, crtc) in device.drm_scanner.crtcs() { |
| 1962 | // Check if connected. |
| 1963 | if connector.state() != connector::State::Connected { |
| 1964 | continue; |
| 1965 | } |
| 1966 | |
| 1967 | // Check if already enabled. |
| 1968 | if device.surfaces.contains_key(&crtc) |
| 1969 | || device |
| 1970 | .non_desktop_connectors |
| 1971 | .contains(&(connector.handle(), crtc)) |
| 1972 | { |
| 1973 | continue; |
| 1974 | } |
| 1975 | |
| 1976 | let output_name = device.known_crtc_name(&crtc, connector, disable_monitor_names); |
| 1977 | if output_name.matches(target) { |
| 1978 | return Some(output_name); |
| 1979 | } |
| 1980 | } |
| 1981 | } |
| 1982 | |
| 1983 | None |
| 1984 | } |
| 1985 | } |
| 1986 | |
| 1987 | impl GammaProps { |
| 1988 | fn new(device: &DrmDevice, crtc: crtc::Handle) -> anyhow::Result<Self> { |
| 1989 | let mut gamma_lut = None; |
| 1990 | let mut gamma_lut_size = None; |
| 1991 | |
| 1992 | let props = device |
| 1993 | .get_properties(crtc) |
| 1994 | .context("error getting properties")?; |
| 1995 | for (prop, _) in props { |
| 1996 | let Ok(info) = device.get_property(prop) else { |
| 1997 | continue; |
| 1998 | }; |
| 1999 | |
| 2000 | let Ok(name) = info.name().to_str() else { |
| 2001 | continue; |
| 2002 | }; |
| 2003 | |
| 2004 | match name { |
| 2005 | "GAMMA_LUT" => { |
| 2006 | ensure!( |
| 2007 | matches!(info.value_type(), property::ValueType::Blob), |
| 2008 | "wrong GAMMA_LUT value type" |
| 2009 | ); |
| 2010 | gamma_lut = Some(prop); |
| 2011 | } |
| 2012 | "GAMMA_LUT_SIZE" => { |
| 2013 | ensure!( |
| 2014 | matches!(info.value_type(), property::ValueType::UnsignedRange(_, _)), |
| 2015 | "wrong GAMMA_LUT_SIZE value type" |
| 2016 | ); |
| 2017 | gamma_lut_size = Some(prop); |
| 2018 | } |
| 2019 | _ => (), |
| 2020 | } |
| 2021 | } |
| 2022 | |
| 2023 | let gamma_lut = gamma_lut.context("missing GAMMA_LUT property")?; |
| 2024 | let gamma_lut_size = gamma_lut_size.context("missing GAMMA_LUT_SIZE property")?; |
| 2025 | |
| 2026 | Ok(Self { |
| 2027 | crtc, |
| 2028 | gamma_lut, |
| 2029 | gamma_lut_size, |
| 2030 | previous_blob: None, |
| 2031 | }) |
| 2032 | } |
| 2033 | |
| 2034 | fn gamma_size(&self, device: &DrmDevice) -> anyhow::Result<u32> { |
| 2035 | let value = get_drm_property(device, self.crtc, self.gamma_lut_size) |
| 2036 | .context("missing GAMMA_LUT_SIZE property")?; |
| 2037 | Ok(value as u32) |
| 2038 | } |
| 2039 | |
| 2040 | fn set_gamma(&mut self, device: &DrmDevice, gamma: Option<&[u16]>) -> anyhow::Result<()> { |
| 2041 | let _span = tracy_client::span!("GammaProps::set_gamma"); |
| 2042 | |
| 2043 | let blob = if let Some(gamma) = gamma { |
| 2044 | let gamma_size = self |
| 2045 | .gamma_size(device) |
| 2046 | .context("error getting gamma size")? as usize; |
| 2047 | |
| 2048 | ensure!(gamma.len() == gamma_size * 3, "wrong gamma length"); |
| 2049 | |
| 2050 | #[allow(non_camel_case_types)] |
| 2051 | #[repr(C)] |
| 2052 | #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] |
| 2053 | pub struct drm_color_lut { |
| 2054 | pub red: u16, |
| 2055 | pub green: u16, |
| 2056 | pub blue: u16, |
| 2057 | pub reserved: u16, |
| 2058 | } |
| 2059 | |
| 2060 | let (red, rest) = gamma.split_at(gamma_size); |
| 2061 | let (blue, green) = rest.split_at(gamma_size); |
| 2062 | let mut data = zip(zip(red, blue), green) |
| 2063 | .map(|((&red, &green), &blue)| drm_color_lut { |
| 2064 | red, |
| 2065 | green, |
| 2066 | blue, |
| 2067 | reserved: 0, |
| 2068 | }) |
| 2069 | .collect::<Vec<_>>(); |
| 2070 | let data = cast_slice_mut(&mut data); |
| 2071 | |
| 2072 | let blob = drm_ffi::mode::create_property_blob(device.as_fd(), data) |
| 2073 | .context("error creating property blob")?; |
| 2074 | NonZeroU64::new(u64::from(blob.blob_id)) |
| 2075 | } else { |
| 2076 | None |
| 2077 | }; |
| 2078 | |
| 2079 | { |
| 2080 | let _span = tracy_client::span!("set_property"); |
| 2081 | |
| 2082 | let blob = blob.map(NonZeroU64::get).unwrap_or(0); |
| 2083 | device |
| 2084 | .set_property( |
| 2085 | self.crtc, |
| 2086 | self.gamma_lut, |
| 2087 | property::Value::Blob(blob).into(), |
| 2088 | ) |
| 2089 | .context("error setting GAMMA_LUT") |
| 2090 | .inspect_err(|_| { |
| 2091 | if blob != 0 { |
| 2092 | // Destroy the blob we just allocated. |
| 2093 | if let Err(err) = device.destroy_property_blob(blob) { |
| 2094 | warn!("error destroying GAMMA_LUT property blob: {err:?}"); |
| 2095 | } |
| 2096 | } |
| 2097 | })?; |
| 2098 | } |
| 2099 | |
| 2100 | if let Some(blob) = mem::replace(&mut self.previous_blob, blob) { |
| 2101 | if let Err(err) = device.destroy_property_blob(blob.get()) { |
| 2102 | warn!("error destroying previous GAMMA_LUT blob: {err:?}"); |
| 2103 | } |
| 2104 | } |
| 2105 | |
| 2106 | Ok(()) |
| 2107 | } |
| 2108 | |
| 2109 | fn restore_gamma(&self, device: &DrmDevice) -> anyhow::Result<()> { |
| 2110 | let _span = tracy_client::span!("GammaProps::restore_gamma"); |
| 2111 | |
| 2112 | let blob = self.previous_blob.map(NonZeroU64::get).unwrap_or(0); |
| 2113 | device |
| 2114 | .set_property( |
| 2115 | self.crtc, |
| 2116 | self.gamma_lut, |
| 2117 | property::Value::Blob(blob).into(), |
| 2118 | ) |
| 2119 | .context("error setting GAMMA_LUT")?; |
| 2120 | |
| 2121 | Ok(()) |
| 2122 | } |
| 2123 | } |
| 2124 | |
| 2125 | fn primary_node_from_config(config: &Config) -> Option<(DrmNode, DrmNode)> { |
| 2126 | let path = config.debug.render_drm_device.as_ref()?; |
| 2127 | debug!("attempting to use render node from config: {path:?}"); |
| 2128 | |
| 2129 | match DrmNode::from_path(path) { |
| 2130 | Ok(node) => { |
| 2131 | if node.ty() == NodeType::Render { |
| 2132 | match node.node_with_type(NodeType::Primary) { |
| 2133 | Some(Ok(primary_node)) => { |
| 2134 | return Some((primary_node, node)); |
| 2135 | } |
| 2136 | Some(Err(err)) => { |
| 2137 | warn!("error opening primary node for render node {path:?}: {err:?}"); |
| 2138 | } |
| 2139 | None => { |
| 2140 | warn!("error opening primary node for render node {path:?}"); |
| 2141 | } |
| 2142 | } |
| 2143 | } else { |
| 2144 | warn!("DRM node {path:?} is not a render node"); |
| 2145 | |
| 2146 | // Gracefully handle misconfiguration on regular desktop systems. |
| 2147 | if let Some(Ok(render_node)) = node.node_with_type(NodeType::Render) { |
| 2148 | return Some((node, render_node)); |
| 2149 | } |
| 2150 | |
| 2151 | warn!("could not get render node for DRM node {path:?}; proceeding anyway"); |
| 2152 | return Some((node, node)); |
| 2153 | } |
| 2154 | } |
| 2155 | Err(err) => { |
| 2156 | warn!("error opening {path:?} as DRM node: {err:?}"); |
| 2157 | } |
| 2158 | } |
| 2159 | None |
| 2160 | } |
| 2161 | |
| 2162 | fn surface_dmabuf_feedback( |
| 2163 | compositor: &GbmDrmCompositor, |
| 2164 | primary_formats: FormatSet, |
| 2165 | primary_render_node: DrmNode, |
| 2166 | surface_render_node: DrmNode, |
| 2167 | ) -> Result<SurfaceDmabufFeedback, io::Error> { |
| 2168 | let surface = compositor.surface(); |
| 2169 | let planes = surface.planes(); |
| 2170 | |
| 2171 | let primary_plane_formats = surface.plane_info().formats.clone(); |
| 2172 | let primary_or_overlay_plane_formats = primary_plane_formats |
| 2173 | .iter() |
| 2174 | .chain(planes.overlay.iter().flat_map(|p| p.formats.iter())) |
| 2175 | .copied() |
| 2176 | .collect::<FormatSet>(); |
| 2177 | |
| 2178 | // We limit the scan-out trache to formats we can also render from so that there is always a |
| 2179 | // fallback render path available in case the supplied buffer can not be scanned out directly. |
| 2180 | let mut primary_scanout_formats = primary_plane_formats |
| 2181 | .intersection(&primary_formats) |
| 2182 | .copied() |
| 2183 | .collect::<Vec<_>>(); |
| 2184 | let mut primary_or_overlay_scanout_formats = primary_or_overlay_plane_formats |
| 2185 | .intersection(&primary_formats) |
| 2186 | .copied() |
| 2187 | .collect::<Vec<_>>(); |
| 2188 | |
| 2189 | // HACK: AMD iGPU + dGPU systems share some modifiers between the two, and yet cross-device |
| 2190 | // buffers produce a glitched scanout if the modifier is not Linear... |
| 2191 | if primary_render_node != surface_render_node { |
| 2192 | primary_scanout_formats.retain(|f| f.modifier == Modifier::Linear); |
| 2193 | primary_or_overlay_scanout_formats.retain(|f| f.modifier == Modifier::Linear); |
| 2194 | } |
| 2195 | |
| 2196 | let builder = DmabufFeedbackBuilder::new(primary_render_node.dev_id(), primary_formats); |
| 2197 | |
| 2198 | trace!( |
| 2199 | "primary scanout formats: {}, overlay adds: {}", |
| 2200 | primary_scanout_formats.len(), |
| 2201 | primary_or_overlay_scanout_formats.len() - primary_scanout_formats.len(), |
| 2202 | ); |
| 2203 | |
| 2204 | // Prefer the primary-plane-only formats, then primary-or-overlay-plane formats. This will |
| 2205 | // increase the chance of scanning out a client even with our disabled-by-default overlay |
| 2206 | // planes. |
| 2207 | let scanout = builder |
| 2208 | .clone() |
| 2209 | .add_preference_tranche( |
| 2210 | surface_render_node.dev_id(), |
| 2211 | Some(TrancheFlags::Scanout), |
| 2212 | primary_scanout_formats, |
| 2213 | ) |
| 2214 | .add_preference_tranche( |
| 2215 | surface_render_node.dev_id(), |
| 2216 | Some(TrancheFlags::Scanout), |
| 2217 | primary_or_overlay_scanout_formats, |
| 2218 | ) |
| 2219 | .build()?; |
| 2220 | |
| 2221 | // If this is the primary node surface, send scanout formats in both tranches to avoid |
| 2222 | // duplication. |
| 2223 | let render = if primary_render_node == surface_render_node { |
| 2224 | scanout.clone() |
| 2225 | } else { |
| 2226 | builder.build()? |
| 2227 | }; |
| 2228 | |
| 2229 | Ok(SurfaceDmabufFeedback { render, scanout }) |
| 2230 | } |
| 2231 | |
| 2232 | fn find_drm_property( |
| 2233 | drm: &DrmDevice, |
| 2234 | resource: impl ResourceHandle, |
| 2235 | name: &str, |
| 2236 | ) -> Option<(property::Handle, property::Info, property::RawValue)> { |
| 2237 | let props = match drm.get_properties(resource) { |
| 2238 | Ok(props) => props, |
| 2239 | Err(err) => { |
| 2240 | warn!("error getting properties: {err:?}"); |
| 2241 | return None; |
| 2242 | } |
| 2243 | }; |
| 2244 | |
| 2245 | props.into_iter().find_map(|(handle, value)| { |
| 2246 | let info = drm.get_property(handle).ok()?; |
| 2247 | let n = info.name().to_str().ok()?; |
| 2248 | |
| 2249 | (n == name).then_some((handle, info, value)) |
| 2250 | }) |
| 2251 | } |
| 2252 | |
| 2253 | fn get_drm_property( |
| 2254 | drm: &DrmDevice, |
| 2255 | resource: impl ResourceHandle, |
| 2256 | prop: property::Handle, |
| 2257 | ) -> Option<property::RawValue> { |
| 2258 | let props = match drm.get_properties(resource) { |
| 2259 | Ok(props) => props, |
| 2260 | Err(err) => { |
| 2261 | warn!("error getting properties: {err:?}"); |
| 2262 | return None; |
| 2263 | } |
| 2264 | }; |
| 2265 | |
| 2266 | props |
| 2267 | .into_iter() |
| 2268 | .find_map(|(handle, value)| (handle == prop).then_some(value)) |
| 2269 | } |
| 2270 | |
| 2271 | fn refresh_interval(mode: DrmMode) -> Duration { |
| 2272 | let clock = mode.clock() as u64; |
| 2273 | let htotal = mode.hsync().2 as u64; |
| 2274 | let vtotal = mode.vsync().2 as u64; |
| 2275 | |
| 2276 | let mut numerator = htotal * vtotal * 1_000_000; |
| 2277 | let mut denominator = clock; |
| 2278 | |
| 2279 | if mode.flags().contains(ModeFlags::INTERLACE) { |
| 2280 | denominator *= 2; |
| 2281 | } |
| 2282 | |
| 2283 | if mode.flags().contains(ModeFlags::DBLSCAN) { |
| 2284 | numerator *= 2; |
| 2285 | } |
| 2286 | |
| 2287 | if mode.vscan() > 1 { |
| 2288 | numerator *= mode.vscan() as u64; |
| 2289 | } |
| 2290 | |
| 2291 | let refresh_interval = (numerator + denominator / 2) / denominator; |
| 2292 | Duration::from_nanos(refresh_interval) |
| 2293 | } |
| 2294 | |
| 2295 | #[cfg(feature = "dbus")] |
| 2296 | fn suspend() -> anyhow::Result<()> { |
| 2297 | let conn = zbus::blocking::Connection::system().context("error connecting to system bus")?; |
| 2298 | |
| 2299 | conn.call_method( |
| 2300 | Some("org.freedesktop.login1"), |
| 2301 | "/org/freedesktop/login1", |
| 2302 | Some("org.freedesktop.login1.Manager"), |
| 2303 | "Suspend", |
| 2304 | &(true), |
| 2305 | ) |
| 2306 | .context("error suspending")?; |
| 2307 | |
| 2308 | Ok(()) |
| 2309 | } |
| 2310 | |
| 2311 | fn queue_estimated_vblank_timer( |
| 2312 | niri: &mut Niri, |
| 2313 | output: Output, |
| 2314 | target_presentation_time: Duration, |
| 2315 | ) { |
| 2316 | let output_state = niri.output_state.get_mut(&output).unwrap(); |
| 2317 | match mem::take(&mut output_state.redraw_state) { |
| 2318 | RedrawState::Idle => unreachable!(), |
| 2319 | RedrawState::Queued => (), |
| 2320 | RedrawState::WaitingForVBlank { .. } => unreachable!(), |
| 2321 | RedrawState::WaitingForEstimatedVBlank(token) |
| 2322 | | RedrawState::WaitingForEstimatedVBlankAndQueued(token) => { |
| 2323 | output_state.redraw_state = RedrawState::WaitingForEstimatedVBlank(token); |
| 2324 | return; |
| 2325 | } |
| 2326 | } |
| 2327 | |
| 2328 | let now = get_monotonic_time(); |
| 2329 | let mut duration = target_presentation_time.saturating_sub(now); |
| 2330 | |
| 2331 | // No use setting a zero timer, since we'll send frame callbacks anyway right after the call to |
| 2332 | // render(). This can happen for example with unknown presentation time from DRM. |
| 2333 | if duration.is_zero() { |
| 2334 | duration += output_state |
| 2335 | .frame_clock |
| 2336 | .refresh_interval() |
| 2337 | // Unknown refresh interval, i.e. winit backend. Would be good to estimate it somehow |
| 2338 | // but it's not that important for this code path. |
| 2339 | .unwrap_or(Duration::from_micros(16_667)); |
| 2340 | } |
| 2341 | |
| 2342 | trace!("queueing estimated vblank timer to fire in {duration:?}"); |
| 2343 | |
| 2344 | let timer = Timer::from_duration(duration); |
| 2345 | let token = niri |
| 2346 | .event_loop |
| 2347 | .insert_source(timer, move |_, _, data| { |
| 2348 | data.backend |
| 2349 | .tty() |
| 2350 | .on_estimated_vblank_timer(&mut data.niri, output.clone()); |
| 2351 | TimeoutAction::Drop |
| 2352 | }) |
| 2353 | .unwrap(); |
| 2354 | output_state.redraw_state = RedrawState::WaitingForEstimatedVBlank(token); |
| 2355 | } |
| 2356 | |
| 2357 | fn pick_mode( |
| 2358 | connector: &connector::Info, |
| 2359 | target: Option<niri_ipc::ConfiguredMode>, |
| 2360 | ) -> Option<(control::Mode, bool)> { |
| 2361 | let mut mode = None; |
| 2362 | let mut fallback = false; |
| 2363 | |
| 2364 | if let Some(target) = target { |
| 2365 | let refresh = target.refresh.map(|r| (r * 1000.).round() as i32); |
| 2366 | |
| 2367 | for m in connector.modes() { |
| 2368 | if m.size() != (target.width, target.height) { |
| 2369 | continue; |
| 2370 | } |
| 2371 | |
| 2372 | // Interlaced modes don't appear to work. |
| 2373 | if m.flags().contains(ModeFlags::INTERLACE) { |
| 2374 | continue; |
| 2375 | } |
| 2376 | |
| 2377 | if let Some(refresh) = refresh { |
| 2378 | // If refresh is set, only pick modes with matching refresh. |
| 2379 | let wl_mode = Mode::from(*m); |
| 2380 | if wl_mode.refresh == refresh { |
| 2381 | mode = Some(m); |
| 2382 | } |
| 2383 | } else if let Some(curr) = mode { |
| 2384 | // If refresh isn't set, pick the mode with the highest refresh. |
| 2385 | if curr.vrefresh() < m.vrefresh() { |
| 2386 | mode = Some(m); |
| 2387 | } |
| 2388 | } else { |
| 2389 | mode = Some(m); |
| 2390 | } |
| 2391 | } |
| 2392 | |
| 2393 | if mode.is_none() { |
| 2394 | fallback = true; |
| 2395 | } |
| 2396 | } |
| 2397 | |
| 2398 | if mode.is_none() { |
| 2399 | // Pick a preferred mode. |
| 2400 | for m in connector.modes() { |
| 2401 | if !m.mode_type().contains(ModeTypeFlags::PREFERRED) { |
| 2402 | continue; |
| 2403 | } |
| 2404 | |
| 2405 | if let Some(curr) = mode { |
| 2406 | if curr.vrefresh() < m.vrefresh() { |
| 2407 | mode = Some(m); |
| 2408 | } |
| 2409 | } else { |
| 2410 | mode = Some(m); |
| 2411 | } |
| 2412 | } |
| 2413 | } |
| 2414 | |
| 2415 | if mode.is_none() { |
| 2416 | // Last attempt. |
| 2417 | mode = connector.modes().first(); |
| 2418 | } |
| 2419 | |
| 2420 | mode.map(|m| (*m, fallback)) |
| 2421 | } |
| 2422 | |
| 2423 | fn get_edid_info( |
| 2424 | device: &DrmDevice, |
| 2425 | connector: connector::Handle, |
| 2426 | ) -> anyhow::Result<libdisplay_info::info::Info> { |
| 2427 | let (_, info, value) = |
| 2428 | find_drm_property(device, connector, "EDID").context("no EDID property")?; |
| 2429 | let blob = info |
| 2430 | .value_type() |
| 2431 | .convert_value(value) |
| 2432 | .as_blob() |
| 2433 | .context("EDID was not blob type")?; |
| 2434 | let data = device |
| 2435 | .get_property_blob(blob) |
| 2436 | .context("error getting EDID blob value")?; |
| 2437 | libdisplay_info::info::Info::parse_edid(&data).context("error parsing EDID") |
| 2438 | } |
| 2439 | |
| 2440 | fn set_max_bpc(device: &DrmDevice, connector: connector::Handle, bpc: u64) -> anyhow::Result<u64> { |
| 2441 | let props = device |
| 2442 | .get_properties(connector) |
| 2443 | .context("error getting properties")?; |
| 2444 | for (prop, value) in props { |
| 2445 | let info = device |
| 2446 | .get_property(prop) |
| 2447 | .context("error getting property")?; |
| 2448 | if info.name().to_str() != Ok("max bpc") { |
| 2449 | continue; |
| 2450 | } |
| 2451 | |
| 2452 | let property::ValueType::UnsignedRange(min, max) = info.value_type() else { |
| 2453 | bail!("wrong property type") |
| 2454 | }; |
| 2455 | |
| 2456 | let bpc = bpc.clamp(min, max); |
| 2457 | |
| 2458 | let property::Value::UnsignedRange(value) = info.value_type().convert_value(value) else { |
| 2459 | bail!("wrong property type") |
| 2460 | }; |
| 2461 | if value == bpc { |
| 2462 | return Ok(bpc); |
| 2463 | } |
| 2464 | |
| 2465 | device |
| 2466 | .set_property(connector, prop, property::Value::UnsignedRange(bpc).into()) |
| 2467 | .context("error setting property")?; |
| 2468 | |
| 2469 | return Ok(bpc); |
| 2470 | } |
| 2471 | |
| 2472 | Err(anyhow!("couldn't find max bpc property")) |
| 2473 | } |
| 2474 | |
| 2475 | fn is_vrr_capable(device: &DrmDevice, connector: connector::Handle) -> Option<bool> { |
| 2476 | let (_, info, value) = find_drm_property(device, connector, "vrr_capable")?; |
| 2477 | info.value_type().convert_value(value).as_boolean() |
| 2478 | } |
| 2479 | |
| 2480 | pub fn set_gamma_for_crtc( |
| 2481 | device: &DrmDevice, |
| 2482 | crtc: crtc::Handle, |
| 2483 | ramp: Option<&[u16]>, |
| 2484 | ) -> anyhow::Result<()> { |
| 2485 | let _span = tracy_client::span!("set_gamma_for_crtc"); |
| 2486 | |
| 2487 | let info = device.get_crtc(crtc).context("error getting crtc info")?; |
| 2488 | let gamma_length = info.gamma_length() as usize; |
| 2489 | |
| 2490 | ensure!(gamma_length != 0, "setting gamma is not supported"); |
| 2491 | |
| 2492 | let mut temp; |
| 2493 | let ramp = if let Some(ramp) = ramp { |
| 2494 | ensure!(ramp.len() == gamma_length * 3, "wrong gamma length"); |
| 2495 | ramp |
| 2496 | } else { |
| 2497 | let _span = tracy_client::span!("generate linear gamma"); |
| 2498 | |
| 2499 | // The legacy API provides no way to reset the gamma, so set a linear one manually. |
| 2500 | temp = vec![0u16; gamma_length * 3]; |
| 2501 | |
| 2502 | let (red, rest) = temp.split_at_mut(gamma_length); |
| 2503 | let (green, blue) = rest.split_at_mut(gamma_length); |
| 2504 | let denom = gamma_length as u64 - 1; |
| 2505 | for (i, ((r, g), b)) in zip(zip(red, green), blue).enumerate() { |
| 2506 | let value = (0xFFFFu64 * i as u64 / denom) as u16; |
| 2507 | *r = value; |
| 2508 | *g = value; |
| 2509 | *b = value; |
| 2510 | } |
| 2511 | |
| 2512 | &temp |
| 2513 | }; |
| 2514 | |
| 2515 | let (red, ramp) = ramp.split_at(gamma_length); |
| 2516 | let (green, blue) = ramp.split_at(gamma_length); |
| 2517 | |
| 2518 | device |
| 2519 | .set_gamma(crtc, red, green, blue) |
| 2520 | .context("error setting gamma")?; |
| 2521 | |
| 2522 | Ok(()) |
| 2523 | } |
| 2524 | |
| 2525 | fn format_connector_name(connector: &connector::Info) -> String { |
| 2526 | format!( |
| 2527 | "{}-{}", |
| 2528 | connector.interface().as_str(), |
| 2529 | connector.interface_id(), |
| 2530 | ) |
| 2531 | } |
| 2532 | |
| 2533 | fn make_output_name( |
| 2534 | device: &DrmDevice, |
| 2535 | connector: connector::Handle, |
| 2536 | connector_name: String, |
| 2537 | ) -> OutputName { |
| 2538 | let info = get_edid_info(device, connector) |
| 2539 | .map_err(|err| warn!("error getting EDID info for {connector_name}: {err:?}")) |
| 2540 | .ok(); |
| 2541 | OutputName { |
| 2542 | connector: connector_name, |
| 2543 | make: info.as_ref().and_then(|info| info.make()), |
| 2544 | model: info.as_ref().and_then(|info| info.model()), |
| 2545 | serial: info.as_ref().and_then(|info| info.serial()), |
| 2546 | } |
| 2547 | } |