niri
Clone
https://git.tahinli.com/Tahinli/niri.git
0 watching·0 forks·Rust·GPL-3.0·12.1 MiB·b0eb8ad·Ivan Molodetskikh·3 months ago·2857 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, OwnedFd}; |
| 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 drm_ffi::drm_mode_modeinfo; |
| 16 | use libc::dev_t; |
| 17 | use niri_config::output::{MaxBpc, Modeline}; |
| 18 | use niri_config::{Config, OutputName}; |
| 19 | use niri_ipc::{HSyncPolarity, VSyncPolarity}; |
| 20 | use smithay::backend::allocator::dmabuf::Dmabuf; |
| 21 | use smithay::backend::allocator::format::FormatSet; |
| 22 | use smithay::backend::allocator::gbm::{GbmAllocator, GbmBufferFlags, GbmDevice}; |
| 23 | use smithay::backend::allocator::Fourcc; |
| 24 | use smithay::backend::drm::compositor::{DrmCompositor, FrameFlags, PrimaryPlaneElement}; |
| 25 | use smithay::backend::drm::exporter::gbm::GbmFramebufferExporter; |
| 26 | use smithay::backend::drm::{ |
| 27 | DrmDevice, DrmDeviceFd, DrmEvent, DrmEventMetadata, DrmEventTime, DrmNode, NodeType, VrrSupport, |
| 28 | }; |
| 29 | use smithay::backend::egl::context::ContextPriority; |
| 30 | use smithay::backend::egl::{EGLDevice, EGLDisplay}; |
| 31 | use smithay::backend::libinput::{LibinputInputBackend, LibinputSessionInterface}; |
| 32 | use smithay::backend::renderer::gles::GlesRenderer; |
| 33 | use smithay::backend::renderer::multigpu::gbm::GbmGlesBackend; |
| 34 | use smithay::backend::renderer::multigpu::{GpuManager, MultiFrame, MultiRenderer}; |
| 35 | use smithay::backend::renderer::{DebugFlags, ImportDma, ImportEgl, RendererSuper}; |
| 36 | use smithay::backend::session::libseat::LibSeatSession; |
| 37 | use smithay::backend::session::{Event as SessionEvent, Session}; |
| 38 | use smithay::backend::udev::{self, UdevBackend, UdevEvent}; |
| 39 | use smithay::desktop::utils::OutputPresentationFeedback; |
| 40 | use smithay::output::{Mode, Output, OutputModeSource, PhysicalProperties}; |
| 41 | use smithay::reexports::calloop::timer::{TimeoutAction, Timer}; |
| 42 | use smithay::reexports::calloop::{Dispatcher, LoopHandle, RegistrationToken}; |
| 43 | use smithay::reexports::drm::control::atomic::AtomicModeReq; |
| 44 | use smithay::reexports::drm::control::dumbbuffer::DumbBuffer; |
| 45 | use smithay::reexports::drm::control::{ |
| 46 | self, connector, crtc, plane, property, AtomicCommitFlags, Device, Mode as DrmMode, ModeFlags, |
| 47 | ModeTypeFlags, PlaneType, ResourceHandle, |
| 48 | }; |
| 49 | use smithay::reexports::gbm::Modifier; |
| 50 | use smithay::reexports::input::Libinput; |
| 51 | use smithay::reexports::rustix::fs::OFlags; |
| 52 | use smithay::reexports::wayland_protocols; |
| 53 | use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface; |
| 54 | use smithay::utils::{DeviceFd, Transform}; |
| 55 | use smithay::wayland::dmabuf::{DmabufFeedback, DmabufFeedbackBuilder, DmabufGlobal}; |
| 56 | use smithay::wayland::drm_lease::{ |
| 57 | DrmLease, DrmLeaseBuilder, DrmLeaseRequest, DrmLeaseState, LeaseRejected, |
| 58 | }; |
| 59 | use smithay::wayland::presentation::Refresh; |
| 60 | use smithay_drm_extras::drm_scanner::{DrmScanEvent, DrmScanner}; |
| 61 | use wayland_protocols::wp::linux_dmabuf::zv1::server::zwp_linux_dmabuf_feedback_v1::TrancheFlags; |
| 62 | use wayland_protocols::wp::presentation_time::server::wp_presentation_feedback; |
| 63 | |
| 64 | use super::{IpcOutputMap, RenderResult}; |
| 65 | use crate::backend::OutputId; |
| 66 | use crate::frame_clock::FrameClock; |
| 67 | use crate::niri::{Niri, RedrawState, State}; |
| 68 | use crate::render_helpers::debug::draw_damage; |
| 69 | use crate::render_helpers::renderer::AsGlesRenderer; |
| 70 | use crate::render_helpers::{resources, shaders, RenderCtx, RenderTarget}; |
| 71 | use crate::utils::{get_monotonic_time, is_laptop_panel, logical_output, PanelOrientation}; |
| 72 | |
| 73 | // When copying from rendering Nvidia dGPU to target iGPU, |
| 74 | // it only understands X/Abgr and not X/Argb. |
| 75 | const SUPPORTED_COLOR_FORMATS_10BIT: [Fourcc; 3] = |
| 76 | [Fourcc::Abgr2101010, Fourcc::Argb8888, Fourcc::Abgr8888]; |
| 77 | |
| 78 | // Smithay should fall back to Xrgb/Xbgr automatically if needed. |
| 79 | const SUPPORTED_COLOR_FORMATS: [Fourcc; 2] = [Fourcc::Argb8888, Fourcc::Abgr8888]; |
| 80 | |
| 81 | pub struct Tty { |
| 82 | config: Rc<RefCell<Config>>, |
| 83 | session: LibSeatSession, |
| 84 | udev_dispatcher: Dispatcher<'static, UdevBackend, State>, |
| 85 | libinput: Libinput, |
| 86 | gpu_manager: GpuManager<GbmGlesBackend<GlesRenderer, DrmDeviceFd>>, |
| 87 | // DRM node corresponding to the primary GPU. May or may not be the same as |
| 88 | // primary_render_node. |
| 89 | primary_node: DrmNode, |
| 90 | // DRM render node corresponding to the primary GPU. |
| 91 | primary_render_node: DrmNode, |
| 92 | // Ignored DRM nodes. |
| 93 | ignored_nodes: HashSet<DrmNode>, |
| 94 | // Devices indexed by DRM node (not necessarily the render node). |
| 95 | devices: HashMap<DrmNode, OutputDevice>, |
| 96 | // The dma-buf global corresponds to the output device (the primary GPU). It is only `Some()` |
| 97 | // if we have a device corresponding to the primary GPU. |
| 98 | dmabuf_global: Option<DmabufGlobal>, |
| 99 | // The output config had changed, but the session is paused, so we need to update it on resume. |
| 100 | update_output_config_on_resume: bool, |
| 101 | // Whether the debug tinting is enabled. |
| 102 | debug_tint: bool, |
| 103 | ipc_outputs: Arc<Mutex<IpcOutputMap>>, |
| 104 | } |
| 105 | |
| 106 | pub type TtyRenderer<'render> = MultiRenderer< |
| 107 | 'render, |
| 108 | 'render, |
| 109 | GbmGlesBackend<GlesRenderer, DrmDeviceFd>, |
| 110 | GbmGlesBackend<GlesRenderer, DrmDeviceFd>, |
| 111 | >; |
| 112 | |
| 113 | pub type TtyFrame<'render, 'frame, 'buffer> = MultiFrame< |
| 114 | 'render, |
| 115 | 'render, |
| 116 | 'frame, |
| 117 | 'buffer, |
| 118 | GbmGlesBackend<GlesRenderer, DrmDeviceFd>, |
| 119 | GbmGlesBackend<GlesRenderer, DrmDeviceFd>, |
| 120 | >; |
| 121 | |
| 122 | pub type TtyRendererError<'render> = <TtyRenderer<'render> as RendererSuper>::Error; |
| 123 | |
| 124 | type GbmDrmCompositor = DrmCompositor< |
| 125 | GbmAllocator<DrmDeviceFd>, |
| 126 | GbmFramebufferExporter<DrmDeviceFd>, |
| 127 | (OutputPresentationFeedback, Duration), |
| 128 | DrmDeviceFd, |
| 129 | >; |
| 130 | |
| 131 | pub struct OutputDevice { |
| 132 | token: RegistrationToken, |
| 133 | // Can be None for display-only devices such as DisplayLink. |
| 134 | render_node: Option<DrmNode>, |
| 135 | drm_scanner: DrmScanner, |
| 136 | surfaces: HashMap<crtc::Handle, Surface>, |
| 137 | known_crtcs: HashMap<crtc::Handle, CrtcInfo>, |
| 138 | // SAFETY: drop after all the objects used with them are dropped. |
| 139 | // See https://github.com/Smithay/smithay/issues/1102. |
| 140 | drm: DrmDevice, |
| 141 | gbm: GbmDevice<DrmDeviceFd>, |
| 142 | // For display-only devices this will be the allocator from the primary device. |
| 143 | allocator: GbmAllocator<DrmDeviceFd>, |
| 144 | |
| 145 | pub drm_lease_state: Option<DrmLeaseState>, |
| 146 | non_desktop_connectors: HashSet<(connector::Handle, crtc::Handle)>, |
| 147 | active_leases: Vec<DrmLease>, |
| 148 | } |
| 149 | |
| 150 | // A connected, but not necessarily enabled, crtc. |
| 151 | #[derive(Debug, Clone)] |
| 152 | pub struct CrtcInfo { |
| 153 | id: OutputId, |
| 154 | name: OutputName, |
| 155 | } |
| 156 | |
| 157 | impl OutputDevice { |
| 158 | pub fn lease_request( |
| 159 | &self, |
| 160 | request: DrmLeaseRequest, |
| 161 | ) -> Result<DrmLeaseBuilder, LeaseRejected> { |
| 162 | let mut builder = DrmLeaseBuilder::new(&self.drm); |
| 163 | for connector in request.connectors { |
| 164 | let (_, crtc) = self |
| 165 | .non_desktop_connectors |
| 166 | .iter() |
| 167 | .find(|(conn, _)| connector == *conn) |
| 168 | .ok_or_else(|| { |
| 169 | warn!("Attempted to lease connector that is not non-desktop"); |
| 170 | LeaseRejected::default() |
| 171 | })?; |
| 172 | builder.add_connector(connector); |
| 173 | builder.add_crtc(*crtc); |
| 174 | let planes = self.drm.planes(crtc).map_err(LeaseRejected::with_cause)?; |
| 175 | let (primary_plane, primary_plane_claim) = planes |
| 176 | .primary |
| 177 | .iter() |
| 178 | .find_map(|plane| { |
| 179 | self.drm |
| 180 | .claim_plane(plane.handle, *crtc) |
| 181 | .map(|claim| (plane, claim)) |
| 182 | }) |
| 183 | .ok_or_else(LeaseRejected::default)?; |
| 184 | builder.add_plane(primary_plane.handle, primary_plane_claim); |
| 185 | } |
| 186 | Ok(builder) |
| 187 | } |
| 188 | |
| 189 | pub fn new_lease(&mut self, lease: DrmLease) { |
| 190 | self.active_leases.push(lease); |
| 191 | } |
| 192 | |
| 193 | pub fn remove_lease(&mut self, lease_id: u32) { |
| 194 | self.active_leases.retain(|l| l.id() != lease_id); |
| 195 | } |
| 196 | |
| 197 | pub fn known_crtc_name( |
| 198 | &self, |
| 199 | crtc: &crtc::Handle, |
| 200 | conn: &connector::Info, |
| 201 | disable_monitor_names: bool, |
| 202 | ) -> OutputName { |
| 203 | if disable_monitor_names { |
| 204 | let conn_name = format_connector_name(conn); |
| 205 | return OutputName { |
| 206 | connector: conn_name, |
| 207 | make: None, |
| 208 | model: None, |
| 209 | serial: None, |
| 210 | }; |
| 211 | } |
| 212 | |
| 213 | let Some(info) = self.known_crtcs.get(crtc) else { |
| 214 | let conn_name = format_connector_name(conn); |
| 215 | error!("crtc for connector {conn_name} missing from known"); |
| 216 | return OutputName { |
| 217 | connector: conn_name, |
| 218 | make: None, |
| 219 | model: None, |
| 220 | serial: None, |
| 221 | }; |
| 222 | }; |
| 223 | info.name.clone() |
| 224 | } |
| 225 | |
| 226 | fn cleanup_mismatching_resources( |
| 227 | &self, |
| 228 | should_be_off: &dyn Fn(crtc::Handle, &connector::Info) -> bool, |
| 229 | ) -> anyhow::Result<()> { |
| 230 | let _span = tracy_client::span!("OutputDevice::cleanup_disconnected_resources"); |
| 231 | |
| 232 | let res_handles = self |
| 233 | .drm |
| 234 | .resource_handles() |
| 235 | .context("error getting plane handles")?; |
| 236 | let plane_handles = self |
| 237 | .drm |
| 238 | .plane_handles() |
| 239 | .context("error getting plane handles")?; |
| 240 | |
| 241 | let mut req = AtomicModeReq::new(); |
| 242 | |
| 243 | // We want to disable all CRTCs that do not correspond to a connector we're using. |
| 244 | let mut cleanup = HashSet::<crtc::Handle>::new(); |
| 245 | cleanup.extend(res_handles.crtcs()); |
| 246 | |
| 247 | for (conn, info) in self.drm_scanner.connectors() { |
| 248 | // We only keep the connector if it has a CRTC and the output isn't off in niri. |
| 249 | if let Some(crtc) = self.drm_scanner.crtc_for_connector(conn) { |
| 250 | // Verify that the connector's current CRTC matches the CRTC we expect. If not, |
| 251 | // clear the CRTC and the connector so that all connectors can get the expected |
| 252 | // CRTCs afterwards. (We do this because we do not handle CRTC rotations across TTY |
| 253 | // switches.) |
| 254 | let mut has_different_crtc = false; |
| 255 | if let Some(enc) = info.current_encoder() { |
| 256 | match self.drm.get_encoder(enc) { |
| 257 | Ok(enc) => { |
| 258 | if let Some(current_crtc) = enc.crtc() { |
| 259 | if current_crtc != crtc { |
| 260 | has_different_crtc = true; |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | Err(err) => { |
| 265 | debug!("couldn't get encoder: {err:?}"); |
| 266 | // Err on the safe side. |
| 267 | has_different_crtc = true; |
| 268 | } |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | if !has_different_crtc && !should_be_off(crtc, info) { |
| 273 | // Keep the corresponding CRTC. |
| 274 | cleanup.remove(&crtc); |
| 275 | continue; |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | // Clear the connector. |
| 280 | let Some((crtc_id, _, _)) = find_drm_property(&self.drm, *conn, "CRTC_ID") else { |
| 281 | debug!("couldn't find connector CRTC_ID property"); |
| 282 | continue; |
| 283 | }; |
| 284 | |
| 285 | req.add_property(*conn, crtc_id, property::Value::CRTC(None)); |
| 286 | } |
| 287 | |
| 288 | // Legacy fallback. |
| 289 | if !self.drm.is_atomic() { |
| 290 | for crtc in res_handles.crtcs() { |
| 291 | #[allow(deprecated)] |
| 292 | let _ = self.drm.set_cursor(*crtc, Option::<&DumbBuffer>::None); |
| 293 | } |
| 294 | for crtc in cleanup { |
| 295 | let _ = self.drm.set_crtc(crtc, None, (0, 0), &[], None); |
| 296 | } |
| 297 | return Ok(()); |
| 298 | } |
| 299 | |
| 300 | // Disable non-primary planes, and planes belonging to disabled CRTCs. |
| 301 | let is_primary = |plane: plane::Handle| { |
| 302 | if let Some((_, info, value)) = find_drm_property(&self.drm, plane, "type") { |
| 303 | match info.value_type().convert_value(value) { |
| 304 | property::Value::Enum(Some(val)) => val.value() == PlaneType::Primary as u64, |
| 305 | _ => false, |
| 306 | } |
| 307 | } else { |
| 308 | debug!("couldn't find plane type property"); |
| 309 | false |
| 310 | } |
| 311 | }; |
| 312 | |
| 313 | for plane in plane_handles { |
| 314 | let info = match self.drm.get_plane(plane) { |
| 315 | Ok(x) => x, |
| 316 | Err(err) => { |
| 317 | debug!("error getting plane: {err:?}"); |
| 318 | continue; |
| 319 | } |
| 320 | }; |
| 321 | |
| 322 | let Some(crtc) = info.crtc() else { |
| 323 | continue; |
| 324 | }; |
| 325 | |
| 326 | if !cleanup.contains(&crtc) && is_primary(plane) { |
| 327 | continue; |
| 328 | } |
| 329 | |
| 330 | let Some((crtc_id, _, _)) = find_drm_property(&self.drm, plane, "CRTC_ID") else { |
| 331 | debug!("couldn't find plane CRTC_ID property"); |
| 332 | continue; |
| 333 | }; |
| 334 | |
| 335 | let Some((fb_id, _, _)) = find_drm_property(&self.drm, plane, "FB_ID") else { |
| 336 | debug!("couldn't find plane FB_ID property"); |
| 337 | continue; |
| 338 | }; |
| 339 | |
| 340 | req.add_property(plane, crtc_id, property::Value::CRTC(None)); |
| 341 | req.add_property(plane, fb_id, property::Value::Framebuffer(None)); |
| 342 | } |
| 343 | |
| 344 | // Disable the CRTCs. |
| 345 | for crtc in cleanup { |
| 346 | let Some((mode_id, _, _)) = find_drm_property(&self.drm, crtc, "MODE_ID") else { |
| 347 | debug!("couldn't find CRTC MODE_ID property"); |
| 348 | continue; |
| 349 | }; |
| 350 | |
| 351 | let Some((active, _, _)) = find_drm_property(&self.drm, crtc, "ACTIVE") else { |
| 352 | debug!("couldn't find CRTC ACTIVE property"); |
| 353 | continue; |
| 354 | }; |
| 355 | |
| 356 | req.add_property(crtc, mode_id, property::Value::Unknown(0)); |
| 357 | req.add_property(crtc, active, property::Value::Boolean(false)); |
| 358 | } |
| 359 | |
| 360 | self.drm |
| 361 | .atomic_commit(AtomicCommitFlags::ALLOW_MODESET, req) |
| 362 | .context("error doing atomic commit")?; |
| 363 | |
| 364 | Ok(()) |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | #[derive(Debug, Clone, Copy)] |
| 369 | struct TtyOutputState { |
| 370 | node: DrmNode, |
| 371 | crtc: crtc::Handle, |
| 372 | } |
| 373 | |
| 374 | struct Surface { |
| 375 | name: OutputName, |
| 376 | compositor: GbmDrmCompositor, |
| 377 | connector: connector::Handle, |
| 378 | dmabuf_feedback: Option<SurfaceDmabufFeedback>, |
| 379 | gamma_props: Option<GammaProps>, |
| 380 | /// Gamma change to apply upon session resume. |
| 381 | pending_gamma_change: Option<Option<Vec<u16>>>, |
| 382 | /// Tracy frame that goes from vblank to vblank. |
| 383 | vblank_frame: Option<tracy_client::Frame>, |
| 384 | /// Frame name for the VBlank frame. |
| 385 | vblank_frame_name: tracy_client::FrameName, |
| 386 | /// Plot name for the time since presentation plot. |
| 387 | time_since_presentation_plot_name: tracy_client::PlotName, |
| 388 | /// Plot name for the presentation misprediction plot. |
| 389 | presentation_misprediction_plot_name: tracy_client::PlotName, |
| 390 | sequence_delta_plot_name: tracy_client::PlotName, |
| 391 | } |
| 392 | |
| 393 | pub struct SurfaceDmabufFeedback { |
| 394 | pub render: DmabufFeedback, |
| 395 | pub scanout: DmabufFeedback, |
| 396 | } |
| 397 | |
| 398 | struct GammaProps { |
| 399 | crtc: crtc::Handle, |
| 400 | gamma_lut: property::Handle, |
| 401 | gamma_lut_size: property::Handle, |
| 402 | previous_blob: Option<NonZeroU64>, |
| 403 | } |
| 404 | |
| 405 | struct ConnectorProperties<'a> { |
| 406 | device: &'a DrmDevice, |
| 407 | connector: connector::Handle, |
| 408 | properties: Vec<(property::Info, property::RawValue)>, |
| 409 | has_change: bool, |
| 410 | requests: AtomicModeReq, |
| 411 | } |
| 412 | |
| 413 | impl Tty { |
| 414 | pub fn new( |
| 415 | config: Rc<RefCell<Config>>, |
| 416 | event_loop: LoopHandle<'static, State>, |
| 417 | ) -> anyhow::Result<Self> { |
| 418 | let _span = tracy_client::span!("Tty::new"); |
| 419 | |
| 420 | let (session, notifier) = LibSeatSession::new().context( |
| 421 | "Error creating a session. This might mean that you're trying to run niri on a TTY \ |
| 422 | that is already busy, for example if you're running this inside tmux that had been \ |
| 423 | originally started on a different TTY", |
| 424 | )?; |
| 425 | let seat_name = session.seat(); |
| 426 | |
| 427 | let udev_backend = |
| 428 | UdevBackend::new(session.seat()).context("error creating a udev backend")?; |
| 429 | let udev_dispatcher = Dispatcher::new(udev_backend, move |event, _, state: &mut State| { |
| 430 | state.backend.tty().on_udev_event(&mut state.niri, event); |
| 431 | }); |
| 432 | event_loop |
| 433 | .register_dispatcher(udev_dispatcher.clone()) |
| 434 | .unwrap(); |
| 435 | |
| 436 | let mut libinput = Libinput::new_with_udev(LibinputSessionInterface::from(session.clone())); |
| 437 | unsafe { init_libinput_plugin_system(&libinput) }; |
| 438 | { |
| 439 | let _span = tracy_client::span!("Libinput::udev_assign_seat"); |
| 440 | libinput.udev_assign_seat(&seat_name) |
| 441 | } |
| 442 | .map_err(|()| anyhow!("error assigning the seat to libinput"))?; |
| 443 | |
| 444 | // If the session is not active at startup (e.g. niri was launched from a different TTY), |
| 445 | // suspend libinput now so that when ActivateSession fires, libinput.resume() performs a |
| 446 | // full re-enumeration of input devices instead of being a no-op. |
| 447 | if !session.is_active() { |
| 448 | debug!("session is not active, starting libinput in paused state"); |
| 449 | libinput.suspend(); |
| 450 | } |
| 451 | |
| 452 | let input_backend = LibinputInputBackend::new(libinput.clone()); |
| 453 | event_loop |
| 454 | .insert_source(input_backend, |mut event, _, state| { |
| 455 | state.process_libinput_event(&mut event); |
| 456 | state.process_input_event(event); |
| 457 | }) |
| 458 | .unwrap(); |
| 459 | |
| 460 | event_loop |
| 461 | .insert_source(notifier, move |event, _, state| { |
| 462 | state.backend.tty().on_session_event(&mut state.niri, event); |
| 463 | }) |
| 464 | .unwrap(); |
| 465 | |
| 466 | let api = GbmGlesBackend::with_context_priority(ContextPriority::High); |
| 467 | let gpu_manager = GpuManager::new(api).context("error creating the GPU manager")?; |
| 468 | |
| 469 | let (primary_node, primary_render_node) = primary_node_from_config(&config.borrow()) |
| 470 | .ok_or(()) |
| 471 | .or_else(|()| { |
| 472 | let primary_gpu_path = udev::primary_gpu(&seat_name) |
| 473 | .context("error getting the primary GPU")? |
| 474 | .context("couldn't find a GPU")?; |
| 475 | let primary_node = DrmNode::from_path(primary_gpu_path) |
| 476 | .context("error opening the primary GPU DRM node")?; |
| 477 | let primary_render_node = primary_node |
| 478 | .node_with_type(NodeType::Render) |
| 479 | .and_then(Result::ok) |
| 480 | .unwrap_or_else(|| { |
| 481 | warn!( |
| 482 | "error getting the render node for the primary GPU; proceeding anyway" |
| 483 | ); |
| 484 | primary_node |
| 485 | }); |
| 486 | |
| 487 | Ok::<_, anyhow::Error>((primary_node, primary_render_node)) |
| 488 | })?; |
| 489 | |
| 490 | let mut node_path = String::new(); |
| 491 | if let Some(path) = primary_render_node.dev_path() { |
| 492 | write!(node_path, "{path:?}").unwrap(); |
| 493 | } else { |
| 494 | write!(node_path, "{primary_render_node}").unwrap(); |
| 495 | } |
| 496 | info!("using as the render node: {node_path}"); |
| 497 | |
| 498 | Ok(Self { |
| 499 | config, |
| 500 | session, |
| 501 | udev_dispatcher, |
| 502 | libinput, |
| 503 | gpu_manager, |
| 504 | primary_node, |
| 505 | primary_render_node, |
| 506 | ignored_nodes: HashSet::new(), |
| 507 | devices: HashMap::new(), |
| 508 | dmabuf_global: None, |
| 509 | update_output_config_on_resume: false, |
| 510 | debug_tint: false, |
| 511 | ipc_outputs: Arc::new(Mutex::new(HashMap::new())), |
| 512 | }) |
| 513 | } |
| 514 | |
| 515 | pub fn init(&mut self, niri: &mut Niri) { |
| 516 | // If the session is inactive, skip initialization because we won't be able to do much with |
| 517 | // the devices anyway. We'll get ActivateSession and add the devices there instead. |
| 518 | // |
| 519 | // This can happen when starting niri while having a different TTY active (e.g. via tmux). |
| 520 | if !self.session.is_active() { |
| 521 | return; |
| 522 | } |
| 523 | |
| 524 | // Initialize the ignored nodes. |
| 525 | self.ignored_nodes = self.compute_ignored_nodes(); |
| 526 | |
| 527 | let udev = self.udev_dispatcher.clone(); |
| 528 | let udev = udev.as_source_ref(); |
| 529 | |
| 530 | // Initialize the primary node first as later nodes might depend on the primary render node |
| 531 | // being available. |
| 532 | if let Some((primary_device_id, primary_device_path)) = udev |
| 533 | .device_list() |
| 534 | .find(|&(device_id, _)| device_id == self.primary_node.dev_id()) |
| 535 | { |
| 536 | if let Err(err) = self.device_added(primary_device_id, primary_device_path, niri) { |
| 537 | warn!( |
| 538 | "error adding primary node device, display-only devices may not work: {err:?}" |
| 539 | ); |
| 540 | } |
| 541 | } else { |
| 542 | warn!("primary node is missing, display-only devices may not work"); |
| 543 | }; |
| 544 | |
| 545 | for (device_id, path) in udev.device_list() { |
| 546 | if device_id == self.primary_node.dev_id() { |
| 547 | continue; |
| 548 | } |
| 549 | |
| 550 | if let Err(err) = self.device_added(device_id, path, niri) { |
| 551 | warn!("error adding device: {err:?}"); |
| 552 | } |
| 553 | } |
| 554 | } |
| 555 | |
| 556 | fn on_udev_event(&mut self, niri: &mut Niri, event: UdevEvent) { |
| 557 | let _span = tracy_client::span!("Tty::on_udev_event"); |
| 558 | |
| 559 | match event { |
| 560 | UdevEvent::Added { device_id, path } => { |
| 561 | if !self.session.is_active() { |
| 562 | debug!("skipping UdevEvent::Added as session is inactive"); |
| 563 | return; |
| 564 | } |
| 565 | |
| 566 | // Recompute ignored nodes to resolve symlinks (like /dev/dri/by-path/...) to their |
| 567 | // new underlying device IDs. |
| 568 | self.ignored_nodes = self.compute_ignored_nodes(); |
| 569 | |
| 570 | if let Err(err) = self.device_added(device_id, &path, niri) { |
| 571 | warn!("error adding device: {err:?}"); |
| 572 | } |
| 573 | } |
| 574 | UdevEvent::Changed { device_id } => { |
| 575 | if !self.session.is_active() { |
| 576 | debug!("skipping UdevEvent::Changed as session is inactive"); |
| 577 | return; |
| 578 | } |
| 579 | |
| 580 | self.device_changed(device_id, niri, false) |
| 581 | } |
| 582 | UdevEvent::Removed { device_id } => { |
| 583 | if !self.session.is_active() { |
| 584 | debug!("skipping UdevEvent::Removed as session is inactive"); |
| 585 | return; |
| 586 | } |
| 587 | |
| 588 | self.device_removed(device_id, niri) |
| 589 | } |
| 590 | } |
| 591 | } |
| 592 | |
| 593 | fn on_session_event(&mut self, niri: &mut Niri, event: SessionEvent) { |
| 594 | let _span = tracy_client::span!("Tty::on_session_event"); |
| 595 | |
| 596 | match event { |
| 597 | SessionEvent::PauseSession => { |
| 598 | debug!("pausing session"); |
| 599 | |
| 600 | self.libinput.suspend(); |
| 601 | |
| 602 | for device in self.devices.values_mut() { |
| 603 | device.drm.pause(); |
| 604 | |
| 605 | if let Some(lease_state) = &mut device.drm_lease_state { |
| 606 | lease_state.suspend(); |
| 607 | } |
| 608 | } |
| 609 | } |
| 610 | SessionEvent::ActivateSession => { |
| 611 | debug!("resuming session"); |
| 612 | |
| 613 | if self.libinput.resume().is_err() { |
| 614 | warn!("error resuming libinput"); |
| 615 | } |
| 616 | |
| 617 | // While the session was suspended, GPUs could have been added, so |
| 618 | // /dev/dri/by-path/... symlinks need to be re-resolved. |
| 619 | self.ignored_nodes = self.compute_ignored_nodes(); |
| 620 | |
| 621 | let mut device_list = self |
| 622 | .udev_dispatcher |
| 623 | .as_source_ref() |
| 624 | .device_list() |
| 625 | .map(|(device_id, path)| (device_id, path.to_owned())) |
| 626 | .collect::<HashMap<_, _>>(); |
| 627 | |
| 628 | let removed_devices = self |
| 629 | .devices |
| 630 | .keys() |
| 631 | .filter(|node| { |
| 632 | !device_list.contains_key(&node.dev_id()) |
| 633 | || self.ignored_nodes.contains(node) |
| 634 | }) |
| 635 | .copied() |
| 636 | .collect::<Vec<_>>(); |
| 637 | |
| 638 | let remained_devices = self |
| 639 | .devices |
| 640 | .keys() |
| 641 | .filter(|node| { |
| 642 | device_list.contains_key(&node.dev_id()) |
| 643 | && !self.ignored_nodes.contains(node) |
| 644 | }) |
| 645 | .copied() |
| 646 | .collect::<Vec<_>>(); |
| 647 | |
| 648 | // Remove removed devices. |
| 649 | for node in removed_devices { |
| 650 | device_list.remove(&node.dev_id()); |
| 651 | self.device_removed(node.dev_id(), niri); |
| 652 | } |
| 653 | |
| 654 | // Update remained devices. |
| 655 | for node in remained_devices { |
| 656 | device_list.remove(&node.dev_id()); |
| 657 | |
| 658 | // It hasn't been removed, update its state as usual. |
| 659 | let device = self.devices.get_mut(&node).unwrap(); |
| 660 | |
| 661 | // Someone on an old device hit what seems to be a driver bug without this: |
| 662 | // https://github.com/niri-wm/niri/issues/3048 |
| 663 | let force_disable = self |
| 664 | .config |
| 665 | .borrow() |
| 666 | .debug |
| 667 | .force_disable_connectors_on_resume; |
| 668 | |
| 669 | if let Err(err) = device.drm.activate(force_disable) { |
| 670 | warn!("error activating DRM device: {err:?}"); |
| 671 | } |
| 672 | if let Some(lease_state) = &mut device.drm_lease_state { |
| 673 | lease_state.resume::<State>(); |
| 674 | } |
| 675 | |
| 676 | // Refresh the connectors. |
| 677 | self.device_changed(node.dev_id(), niri, true); |
| 678 | |
| 679 | // Apply pending gamma changes and restore our existing gamma. |
| 680 | let device = self.devices.get_mut(&node).unwrap(); |
| 681 | for (crtc, surface) in device.surfaces.iter_mut() { |
| 682 | if let Ok(mut props) = |
| 683 | ConnectorProperties::try_new(&device.drm, surface.connector) |
| 684 | { |
| 685 | let max_bpc = self |
| 686 | .config |
| 687 | .borrow() |
| 688 | .outputs |
| 689 | .find(&surface.name) |
| 690 | .and_then(|o| o.max_bpc); |
| 691 | set_connector_properties(&mut props, max_bpc, true); |
| 692 | } else { |
| 693 | warn!("failed to get connector properties"); |
| 694 | } |
| 695 | |
| 696 | if let Some(ramp) = surface.pending_gamma_change.take() { |
| 697 | let ramp = ramp.as_deref(); |
| 698 | let res = if let Some(gamma_props) = &mut surface.gamma_props { |
| 699 | gamma_props.set_gamma(&device.drm, ramp) |
| 700 | } else { |
| 701 | set_gamma_for_crtc(&device.drm, *crtc, ramp) |
| 702 | }; |
| 703 | if let Err(err) = res { |
| 704 | warn!("error applying pending gamma change: {err:?}"); |
| 705 | } |
| 706 | } else if let Some(gamma_props) = &surface.gamma_props { |
| 707 | if let Err(err) = gamma_props.restore_gamma(&device.drm) { |
| 708 | warn!("error restoring gamma: {err:?}"); |
| 709 | } |
| 710 | } |
| 711 | } |
| 712 | } |
| 713 | |
| 714 | // Add new devices. |
| 715 | // |
| 716 | // Add the primary node first as later nodes might depend on the primary render |
| 717 | // node being available. |
| 718 | let primary_device_id = self.primary_node.dev_id(); |
| 719 | let primary_device_path = device_list.remove(&primary_device_id); |
| 720 | let primary = primary_device_path.map(|path| (primary_device_id, path)); |
| 721 | |
| 722 | for (device_id, path) in primary.into_iter().chain(device_list) { |
| 723 | if let Err(err) = self.device_added(device_id, &path, niri) { |
| 724 | warn!("error adding device: {err:?}"); |
| 725 | } |
| 726 | } |
| 727 | |
| 728 | if self.update_output_config_on_resume { |
| 729 | self.on_output_config_changed(niri); |
| 730 | } |
| 731 | |
| 732 | self.refresh_ipc_outputs(niri); |
| 733 | |
| 734 | niri.notify_activity(); |
| 735 | niri.monitors_active = true; |
| 736 | self.set_monitors_active(true); |
| 737 | niri.queue_redraw_all(); |
| 738 | } |
| 739 | } |
| 740 | } |
| 741 | |
| 742 | fn device_added( |
| 743 | &mut self, |
| 744 | device_id: dev_t, |
| 745 | path: &Path, |
| 746 | niri: &mut Niri, |
| 747 | ) -> anyhow::Result<()> { |
| 748 | debug!("adding device: {device_id} {path:?}"); |
| 749 | |
| 750 | let node = DrmNode::from_dev_id(device_id)?; |
| 751 | |
| 752 | if node == self.primary_node { |
| 753 | debug!("this is the primary node"); |
| 754 | } |
| 755 | |
| 756 | // Only consider primary node on udev event |
| 757 | // https://gitlab.freedesktop.org/wlroots/wlroots/-/commit/768fbaad54027f8dd027e7e015e8eeb93cb38c52 |
| 758 | if node.ty() != NodeType::Primary { |
| 759 | debug!("not a primary node, skipping"); |
| 760 | return Ok(()); |
| 761 | } |
| 762 | |
| 763 | if self.ignored_nodes.contains(&node) { |
| 764 | debug!("node is ignored, skipping"); |
| 765 | return Ok(()); |
| 766 | } |
| 767 | |
| 768 | let _span = tracy_client::span!("Tty::device_added"); |
| 769 | |
| 770 | let open_flags = OFlags::RDWR | OFlags::CLOEXEC | OFlags::NOCTTY | OFlags::NONBLOCK; |
| 771 | let fd = { |
| 772 | let _span = tracy_client::span!("LibSeatSession::open"); |
| 773 | self.session.open(path, open_flags) |
| 774 | }?; |
| 775 | let device_fd = DrmDeviceFd::new(DeviceFd::from(fd)); |
| 776 | |
| 777 | let (drm, drm_notifier) = { |
| 778 | let _span = tracy_client::span!("DrmDevice::new"); |
| 779 | DrmDevice::new(device_fd.clone(), false) |
| 780 | }?; |
| 781 | let gbm = { |
| 782 | let _span = tracy_client::span!("GbmDevice::new"); |
| 783 | GbmDevice::new(device_fd) |
| 784 | }?; |
| 785 | |
| 786 | let mut try_initialize_gpu = || { |
| 787 | let display = unsafe { EGLDisplay::new(gbm.clone())? }; |
| 788 | let egl_device = EGLDevice::device_for_display(&display)?; |
| 789 | |
| 790 | // Software EGL devices (e.g., llvmpipe/softpipe) are rejected for now. They have some |
| 791 | // problems (segfault on importing dmabufs from other renderers) and need to be |
| 792 | // excluded from some places like DRM leasing. |
| 793 | ensure!( |
| 794 | !egl_device.is_software(), |
| 795 | "software EGL renderers are skipped" |
| 796 | ); |
| 797 | |
| 798 | let render_node = egl_device |
| 799 | .try_get_render_node() |
| 800 | .ok() |
| 801 | .flatten() |
| 802 | .unwrap_or(node); |
| 803 | self.gpu_manager |
| 804 | .as_mut() |
| 805 | .add_node(render_node, gbm.clone()) |
| 806 | .context("error adding render node to GPU manager")?; |
| 807 | |
| 808 | Ok(render_node) |
| 809 | }; |
| 810 | |
| 811 | let render_node = match try_initialize_gpu() { |
| 812 | Ok(render_node) => { |
| 813 | debug!("got render node: {render_node}"); |
| 814 | Some(render_node) |
| 815 | } |
| 816 | Err(err) => { |
| 817 | debug!("failed to initialize renderer, falling back to primary gpu: {err:?}"); |
| 818 | None |
| 819 | } |
| 820 | }; |
| 821 | |
| 822 | if render_node == Some(self.primary_render_node) && self.dmabuf_global.is_none() { |
| 823 | let render_node = self.primary_render_node; |
| 824 | debug!("initializing the primary renderer"); |
| 825 | |
| 826 | let mut renderer = self |
| 827 | .gpu_manager |
| 828 | .single_renderer(&render_node) |
| 829 | .context("error creating renderer")?; |
| 830 | |
| 831 | if let Err(err) = renderer.bind_wl_display(&niri.display_handle) { |
| 832 | // wl_drm is on its way out so this is expected on most modern distros. |
| 833 | trace!("error binding legacy EGL to wl_display: {err}"); |
| 834 | } else { |
| 835 | debug!("bound legacy EGL to wl_display"); |
| 836 | } |
| 837 | |
| 838 | let gles_renderer = renderer.as_gles_renderer(); |
| 839 | resources::init(gles_renderer); |
| 840 | shaders::init(gles_renderer); |
| 841 | |
| 842 | let config = self.config.borrow(); |
| 843 | if let Some(src) = config.animations.window_resize.custom_shader.as_deref() { |
| 844 | shaders::set_custom_resize_program(gles_renderer, Some(src)); |
| 845 | } |
| 846 | if let Some(src) = config.animations.window_close.custom_shader.as_deref() { |
| 847 | shaders::set_custom_close_program(gles_renderer, Some(src)); |
| 848 | } |
| 849 | if let Some(src) = config.animations.window_open.custom_shader.as_deref() { |
| 850 | shaders::set_custom_open_program(gles_renderer, Some(src)); |
| 851 | } |
| 852 | drop(config); |
| 853 | |
| 854 | niri.update_shaders(); |
| 855 | |
| 856 | // Create the dmabuf global. |
| 857 | let primary_formats = renderer.dmabuf_formats(); |
| 858 | let default_feedback = |
| 859 | DmabufFeedbackBuilder::new(render_node.dev_id(), primary_formats.clone()) |
| 860 | .build() |
| 861 | .context("error building default dmabuf feedback")?; |
| 862 | let dmabuf_global = niri |
| 863 | .dmabuf_state |
| 864 | .create_global_with_default_feedback::<State>( |
| 865 | &niri.display_handle, |
| 866 | &default_feedback, |
| 867 | ); |
| 868 | assert!(self.dmabuf_global.replace(dmabuf_global).is_none()); |
| 869 | |
| 870 | // Update the dmabuf feedbacks for all surfaces. |
| 871 | for (node, device) in self.devices.iter_mut() { |
| 872 | for surface in device.surfaces.values_mut() { |
| 873 | match surface_dmabuf_feedback( |
| 874 | &surface.compositor, |
| 875 | primary_formats.clone(), |
| 876 | self.primary_render_node, |
| 877 | device.render_node, |
| 878 | *node, |
| 879 | ) { |
| 880 | Ok(feedback) => { |
| 881 | surface.dmabuf_feedback = Some(feedback); |
| 882 | } |
| 883 | Err(err) => { |
| 884 | warn!("error building dmabuf feedback: {err:?}"); |
| 885 | } |
| 886 | } |
| 887 | } |
| 888 | } |
| 889 | } |
| 890 | |
| 891 | let allocator_gbm = if render_node.is_some() { |
| 892 | gbm.clone() |
| 893 | } else if let Some(primary_device) = self.devices.get(&self.primary_node) { |
| 894 | primary_device.gbm.clone() |
| 895 | } else { |
| 896 | bail!("no allocator available for device"); |
| 897 | }; |
| 898 | let gbm_flags = GbmBufferFlags::RENDERING | GbmBufferFlags::SCANOUT; |
| 899 | let allocator = GbmAllocator::new(allocator_gbm, gbm_flags); |
| 900 | |
| 901 | let token = niri |
| 902 | .event_loop |
| 903 | .insert_source(drm_notifier, move |event, meta, state| { |
| 904 | let tty = state.backend.tty(); |
| 905 | match event { |
| 906 | DrmEvent::VBlank(crtc) => { |
| 907 | let meta = meta.expect("VBlank events must have metadata"); |
| 908 | tty.on_vblank(&mut state.niri, node, crtc, meta); |
| 909 | } |
| 910 | DrmEvent::Error(error) => warn!("DRM error: {error}"), |
| 911 | }; |
| 912 | }) |
| 913 | .unwrap(); |
| 914 | |
| 915 | let drm_lease_state = DrmLeaseState::new::<State>(&niri.display_handle, &node) |
| 916 | .map_err(|err| warn!("error initializing DRM leasing for {node}: {err:?}")) |
| 917 | .ok(); |
| 918 | |
| 919 | let device = OutputDevice { |
| 920 | token, |
| 921 | render_node, |
| 922 | drm, |
| 923 | gbm, |
| 924 | allocator, |
| 925 | drm_scanner: DrmScanner::new(), |
| 926 | surfaces: HashMap::new(), |
| 927 | known_crtcs: HashMap::new(), |
| 928 | drm_lease_state, |
| 929 | active_leases: Vec::new(), |
| 930 | non_desktop_connectors: HashSet::new(), |
| 931 | }; |
| 932 | assert!(self.devices.insert(node, device).is_none()); |
| 933 | |
| 934 | self.device_changed(device_id, niri, true); |
| 935 | |
| 936 | Ok(()) |
| 937 | } |
| 938 | |
| 939 | fn device_changed(&mut self, device_id: dev_t, niri: &mut Niri, cleanup: bool) { |
| 940 | debug!("device changed: {device_id}"); |
| 941 | |
| 942 | let Ok(node) = DrmNode::from_dev_id(device_id) else { |
| 943 | warn!("error creating DrmNode"); |
| 944 | return; |
| 945 | }; |
| 946 | |
| 947 | if node.ty() != NodeType::Primary { |
| 948 | debug!("not a primary node, skipping"); |
| 949 | return; |
| 950 | } |
| 951 | |
| 952 | if self.ignored_nodes.contains(&node) { |
| 953 | debug!("node is ignored, skipping"); |
| 954 | return; |
| 955 | } |
| 956 | |
| 957 | let Some(device) = self.devices.get_mut(&node) else { |
| 958 | if let Some(path) = node.dev_path() { |
| 959 | warn!("unknown device; trying to add"); |
| 960 | |
| 961 | if let Err(err) = self.device_added(device_id, &path, niri) { |
| 962 | warn!("error adding device: {err:?}"); |
| 963 | } |
| 964 | } else { |
| 965 | warn!("unknown device"); |
| 966 | } |
| 967 | |
| 968 | return; |
| 969 | }; |
| 970 | |
| 971 | // DrmScanner will preserve any existing connector-CRTC mapping. |
| 972 | let scan_result = match device.drm_scanner.scan_connectors(&device.drm) { |
| 973 | Ok(x) => x, |
| 974 | Err(err) => { |
| 975 | warn!("error scanning connectors: {err:?}"); |
| 976 | return; |
| 977 | } |
| 978 | }; |
| 979 | |
| 980 | let mut added = Vec::new(); |
| 981 | let mut removed = Vec::new(); |
| 982 | for event in scan_result { |
| 983 | match event { |
| 984 | DrmScanEvent::Connected { |
| 985 | connector, |
| 986 | crtc: Some(crtc), |
| 987 | } => { |
| 988 | let connector_name = format_connector_name(&connector); |
| 989 | let name = make_output_name(&device.drm, connector.handle(), connector_name); |
| 990 | debug!( |
| 991 | "new connector: {} \"{}\"", |
| 992 | &name.connector, |
| 993 | name.format_make_model_serial(), |
| 994 | ); |
| 995 | |
| 996 | // Assign an id to this crtc. |
| 997 | let id = OutputId::next(); |
| 998 | added.push((crtc, CrtcInfo { id, name })); |
| 999 | } |
| 1000 | DrmScanEvent::Disconnected { |
| 1001 | crtc: Some(crtc), .. |
| 1002 | } => { |
| 1003 | removed.push(crtc); |
| 1004 | } |
| 1005 | // Emitted when the list of connector modes changes at runtime. |
| 1006 | // |
| 1007 | // Some devices, notably USB-C docks with DP-MST/alt-mode, report Connected before |
| 1008 | // the EDID has been read, with an empty mode list. Then, at a later point, the |
| 1009 | // modes will be populated, at which point we'll get this Changed event. |
| 1010 | DrmScanEvent::Changed { |
| 1011 | connector, |
| 1012 | crtc: Some(crtc), |
| 1013 | } => { |
| 1014 | let connector_name = format_connector_name(&connector); |
| 1015 | let name = make_output_name(&device.drm, connector.handle(), connector_name); |
| 1016 | debug!( |
| 1017 | "connector changed: {} \"{}\"", |
| 1018 | &name.connector, |
| 1019 | name.format_make_model_serial(), |
| 1020 | ); |
| 1021 | |
| 1022 | if !device.known_crtcs.contains_key(&crtc) { |
| 1023 | // I guess this can happen if the connector initially wasn't mapped to a |
| 1024 | // CRTC but then got mapped before being changed. |
| 1025 | warn!("changed connector missing from known crtcs"); |
| 1026 | } |
| 1027 | |
| 1028 | // We don't actually need to do anything here; on_output_config_changed() will |
| 1029 | // take care of picking a new mode if needed. |
| 1030 | } |
| 1031 | _ => (), |
| 1032 | } |
| 1033 | } |
| 1034 | |
| 1035 | for crtc in &removed { |
| 1036 | self.connector_disconnected(niri, node, *crtc); |
| 1037 | } |
| 1038 | |
| 1039 | let Some(device) = self.devices.get_mut(&node) else { |
| 1040 | error!("device disappeared"); |
| 1041 | return; |
| 1042 | }; |
| 1043 | |
| 1044 | for crtc in removed { |
| 1045 | if device.known_crtcs.remove(&crtc).is_none() { |
| 1046 | error!("output ID missing for disconnected crtc: {crtc:?}"); |
| 1047 | } |
| 1048 | } |
| 1049 | |
| 1050 | for (crtc, mut info) in added { |
| 1051 | // Make/model/serial can match exactly between different physical monitors. This doesn't |
| 1052 | // happen often, but our Layout does not support such duplicates and will panic. |
| 1053 | // |
| 1054 | // As a workaround, search for duplicates, and unname the new connectors if one is |
| 1055 | // found. Connector names are always unique. |
| 1056 | let name = &mut info.name; |
| 1057 | let formatted = name.format_make_model_serial_or_connector(); |
| 1058 | for info in self.devices.values().flat_map(|d| d.known_crtcs.values()) { |
| 1059 | if info.name.matches(&formatted) { |
| 1060 | let connector = mem::take(&mut name.connector); |
| 1061 | warn!( |
| 1062 | "new connector {connector} duplicates make/model/serial \ |
| 1063 | of existing connector {}, unnaming", |
| 1064 | info.name.connector, |
| 1065 | ); |
| 1066 | *name = OutputName { |
| 1067 | connector, |
| 1068 | make: None, |
| 1069 | model: None, |
| 1070 | serial: None, |
| 1071 | }; |
| 1072 | break; |
| 1073 | } |
| 1074 | } |
| 1075 | |
| 1076 | // Insert it right away so next added connector will check against this one too. |
| 1077 | let device = self.devices.get_mut(&node).unwrap(); |
| 1078 | device.known_crtcs.insert(crtc, info); |
| 1079 | } |
| 1080 | |
| 1081 | // If the device was just added or resumed, we need to cleanup any disconnected connectors |
| 1082 | // and planes. |
| 1083 | if cleanup { |
| 1084 | let device = self.devices.get(&node).unwrap(); |
| 1085 | |
| 1086 | // Follow the logic in on_output_config_changed(). |
| 1087 | let disable_laptop_panels = self.should_disable_laptop_panels(niri.is_lid_closed); |
| 1088 | let should_disable = |conn: &str| disable_laptop_panels && is_laptop_panel(conn); |
| 1089 | |
| 1090 | let config = self.config.borrow(); |
| 1091 | let disable_monitor_names = config.debug.disable_monitor_names; |
| 1092 | |
| 1093 | let should_be_off = |crtc, conn: &connector::Info| { |
| 1094 | let output_name = device.known_crtc_name(&crtc, conn, disable_monitor_names); |
| 1095 | |
| 1096 | let config = config |
| 1097 | .outputs |
| 1098 | .find(&output_name) |
| 1099 | .cloned() |
| 1100 | .unwrap_or_default(); |
| 1101 | |
| 1102 | config.off || should_disable(&output_name.connector) |
| 1103 | }; |
| 1104 | |
| 1105 | if let Err(err) = device.cleanup_mismatching_resources(&should_be_off) { |
| 1106 | warn!("error cleaning up connectors: {err:?}"); |
| 1107 | } |
| 1108 | |
| 1109 | let device = self.devices.get_mut(&node).unwrap(); |
| 1110 | for surface in device.surfaces.values_mut() { |
| 1111 | // We aren't force-clearing the CRTCs, so we need to make the surfaces read the |
| 1112 | // updated state after a session resume. This also causes a full damage for the |
| 1113 | // next redraw. |
| 1114 | if let Err(err) = surface.compositor.reset_state() { |
| 1115 | warn!("error resetting DrmCompositor state: {err:?}"); |
| 1116 | } |
| 1117 | surface.compositor.reset_buffers(); |
| 1118 | } |
| 1119 | } |
| 1120 | |
| 1121 | // This will connect any new connectors if needed, and apply other changes, such as |
| 1122 | // connecting back the internal laptop monitor once it becomes the only monitor left. |
| 1123 | // |
| 1124 | // It will also call refresh_ipc_outputs(), which will catch the disconnected connectors |
| 1125 | // above. |
| 1126 | self.on_output_config_changed(niri); |
| 1127 | } |
| 1128 | |
| 1129 | fn device_removed(&mut self, device_id: dev_t, niri: &mut Niri) { |
| 1130 | debug!("removing device: {device_id}"); |
| 1131 | |
| 1132 | let Ok(node) = DrmNode::from_dev_id(device_id) else { |
| 1133 | warn!("error creating DrmNode"); |
| 1134 | return; |
| 1135 | }; |
| 1136 | |
| 1137 | if node.ty() != NodeType::Primary { |
| 1138 | debug!("not a primary node, skipping"); |
| 1139 | return; |
| 1140 | } |
| 1141 | |
| 1142 | let Some(device) = self.devices.get_mut(&node) else { |
| 1143 | warn!("unknown device"); |
| 1144 | return; |
| 1145 | }; |
| 1146 | |
| 1147 | let crtcs: Vec<_> = device |
| 1148 | .drm_scanner |
| 1149 | .crtcs() |
| 1150 | .map(|(_info, crtc)| crtc) |
| 1151 | .collect(); |
| 1152 | |
| 1153 | for crtc in crtcs { |
| 1154 | self.connector_disconnected(niri, node, crtc); |
| 1155 | } |
| 1156 | |
| 1157 | let mut device = self.devices.remove(&node).unwrap(); |
| 1158 | let device_fd = device.drm.device_fd().device_fd(); |
| 1159 | |
| 1160 | if let Some(lease_state) = &mut device.drm_lease_state { |
| 1161 | lease_state.disable_global::<State>(); |
| 1162 | } |
| 1163 | |
| 1164 | if let Some(render_node) = device.render_node { |
| 1165 | // Sometimes (Asahi DisplayLink), multiple primary nodes will correspond to the same |
| 1166 | // render node. In this case, we want to keep the render node active until the last |
| 1167 | // primary node that uses it is gone. |
| 1168 | let was_last = !self |
| 1169 | .devices |
| 1170 | .values() |
| 1171 | .any(|device| device.render_node == Some(render_node)); |
| 1172 | |
| 1173 | if was_last && render_node == self.primary_render_node { |
| 1174 | debug!("destroying the primary renderer"); |
| 1175 | |
| 1176 | match self.gpu_manager.single_renderer(&self.primary_render_node) { |
| 1177 | Ok(mut renderer) => renderer.unbind_wl_display(), |
| 1178 | Err(err) => { |
| 1179 | warn!("error creating renderer during device removal: {err}"); |
| 1180 | } |
| 1181 | } |
| 1182 | |
| 1183 | // Disable and destroy the dmabuf global. |
| 1184 | if let Some(global) = self.dmabuf_global.take() { |
| 1185 | niri.dmabuf_state |
| 1186 | .disable_global::<State>(&niri.display_handle, &global); |
| 1187 | niri.event_loop |
| 1188 | .insert_source( |
| 1189 | Timer::from_duration(Duration::from_secs(10)), |
| 1190 | move |_, _, state| { |
| 1191 | state |
| 1192 | .niri |
| 1193 | .dmabuf_state |
| 1194 | .destroy_global::<State>(&state.niri.display_handle, global); |
| 1195 | TimeoutAction::Drop |
| 1196 | }, |
| 1197 | ) |
| 1198 | .unwrap(); |
| 1199 | |
| 1200 | // Clear the dmabuf feedbacks for all surfaces. |
| 1201 | for device in self.devices.values_mut() { |
| 1202 | for surface in device.surfaces.values_mut() { |
| 1203 | surface.dmabuf_feedback = None; |
| 1204 | } |
| 1205 | } |
| 1206 | } else { |
| 1207 | error!("dmabuf global was already missing"); |
| 1208 | } |
| 1209 | } |
| 1210 | |
| 1211 | if was_last { |
| 1212 | self.gpu_manager.as_mut().remove_node(&render_node); |
| 1213 | // Trigger re-enumeration in order to remove the device from gpu_manager. |
| 1214 | let _ = self.gpu_manager.devices(); |
| 1215 | } |
| 1216 | } |
| 1217 | |
| 1218 | niri.event_loop.remove(device.token); |
| 1219 | |
| 1220 | self.refresh_ipc_outputs(niri); |
| 1221 | |
| 1222 | drop(device); |
| 1223 | |
| 1224 | match TryInto::<OwnedFd>::try_into(device_fd) { |
| 1225 | Ok(fd) => { |
| 1226 | if let Err(err) = self.session.close(fd) { |
| 1227 | warn!("error closing DRM device fd: {err:?}"); |
| 1228 | } |
| 1229 | } |
| 1230 | Err(_) => { |
| 1231 | error!("unable to close DRM device cleanly: fd has unexpected references"); |
| 1232 | } |
| 1233 | } |
| 1234 | } |
| 1235 | |
| 1236 | fn connector_connected( |
| 1237 | &mut self, |
| 1238 | niri: &mut Niri, |
| 1239 | node: DrmNode, |
| 1240 | connector: connector::Info, |
| 1241 | crtc: crtc::Handle, |
| 1242 | ) -> anyhow::Result<()> { |
| 1243 | let connector_name = format_connector_name(&connector); |
| 1244 | debug!("connecting connector: {connector_name}"); |
| 1245 | |
| 1246 | let device = self.devices.get_mut(&node).context("missing device")?; |
| 1247 | |
| 1248 | let disable_monitor_names = self.config.borrow().debug.disable_monitor_names; |
| 1249 | let output_name = device.known_crtc_name(&crtc, &connector, disable_monitor_names); |
| 1250 | |
| 1251 | let non_desktop = find_drm_property(&device.drm, connector.handle(), "non-desktop") |
| 1252 | .and_then(|(_, info, value)| info.value_type().convert_value(value).as_boolean()) |
| 1253 | .unwrap_or(false); |
| 1254 | |
| 1255 | if non_desktop { |
| 1256 | debug!("output is non desktop"); |
| 1257 | let description = output_name.format_description(); |
| 1258 | if let Some(lease_state) = &mut device.drm_lease_state { |
| 1259 | lease_state.add_connector::<State>(connector.handle(), connector_name, description); |
| 1260 | } |
| 1261 | device |
| 1262 | .non_desktop_connectors |
| 1263 | .insert((connector.handle(), crtc)); |
| 1264 | return Ok(()); |
| 1265 | } |
| 1266 | |
| 1267 | let config = self |
| 1268 | .config |
| 1269 | .borrow() |
| 1270 | .outputs |
| 1271 | .find(&output_name) |
| 1272 | .cloned() |
| 1273 | .unwrap_or_default(); |
| 1274 | |
| 1275 | for m in connector.modes() { |
| 1276 | trace!("{m:?}"); |
| 1277 | } |
| 1278 | |
| 1279 | let mut mode = None; |
| 1280 | if let Some(modeline) = &config.modeline { |
| 1281 | match calculate_drm_mode_from_modeline(modeline) { |
| 1282 | Ok(x) => mode = Some(x), |
| 1283 | Err(err) => { |
| 1284 | warn!("invalid custom modeline; falling back to advertised modes: {err:?}"); |
| 1285 | } |
| 1286 | } |
| 1287 | } |
| 1288 | |
| 1289 | let (mode, fallback) = match mode { |
| 1290 | Some(x) => (x, false), |
| 1291 | None => pick_mode(&connector, config.mode).ok_or_else(|| anyhow!("no mode"))?, |
| 1292 | }; |
| 1293 | |
| 1294 | if fallback { |
| 1295 | let target = config.mode.unwrap(); |
| 1296 | warn!( |
| 1297 | "configured mode {}x{}{} could not be found, falling back to preferred", |
| 1298 | target.mode.width, |
| 1299 | target.mode.height, |
| 1300 | if let Some(refresh) = target.mode.refresh { |
| 1301 | format!("@{refresh}") |
| 1302 | } else { |
| 1303 | String::new() |
| 1304 | }, |
| 1305 | ); |
| 1306 | } |
| 1307 | |
| 1308 | debug!("picking mode: {mode:?}"); |
| 1309 | |
| 1310 | let mut orientation = None; |
| 1311 | if let Ok(mut props) = ConnectorProperties::try_new(&device.drm, connector.handle()) { |
| 1312 | set_connector_properties(&mut props, config.max_bpc, true); |
| 1313 | |
| 1314 | match props.get_panel_orientation() { |
| 1315 | Ok(x) => orientation = Some(x), |
| 1316 | Err(err) => { |
| 1317 | trace!("couldn't get panel orientation: {err:?}"); |
| 1318 | } |
| 1319 | } |
| 1320 | } else { |
| 1321 | warn!("failed to get connector properties"); |
| 1322 | } |
| 1323 | |
| 1324 | let mut gamma_props = GammaProps::new(&device.drm, crtc) |
| 1325 | .map_err(|err| debug!("couldn't get gamma properties: {err:?}")) |
| 1326 | .ok(); |
| 1327 | |
| 1328 | // Reset gamma in case it was set before. |
| 1329 | let res = if let Some(gamma_props) = &mut gamma_props { |
| 1330 | gamma_props.set_gamma(&device.drm, None) |
| 1331 | } else { |
| 1332 | set_gamma_for_crtc(&device.drm, crtc, None) |
| 1333 | }; |
| 1334 | if let Err(err) = res { |
| 1335 | debug!("couldn't reset gamma: {err:?}"); |
| 1336 | } |
| 1337 | |
| 1338 | let surface = device |
| 1339 | .drm |
| 1340 | .create_surface(crtc, mode, &[connector.handle()])?; |
| 1341 | |
| 1342 | // Try to enable VRR if requested. |
| 1343 | match surface.vrr_supported(connector.handle()) { |
| 1344 | Ok(VrrSupport::Supported | VrrSupport::RequiresModeset) => { |
| 1345 | // Even if on-demand, we still disable it until later checks. |
| 1346 | let vrr = config.is_vrr_always_on(); |
| 1347 | let word = if vrr { "enabling" } else { "disabling" }; |
| 1348 | |
| 1349 | if let Err(err) = surface.use_vrr(vrr) { |
| 1350 | warn!("error {} VRR: {err:?}", word); |
| 1351 | } |
| 1352 | } |
| 1353 | Ok(VrrSupport::NotSupported) => { |
| 1354 | if !config.is_vrr_always_off() { |
| 1355 | warn!("cannot enable VRR because connector does not support it"); |
| 1356 | } |
| 1357 | |
| 1358 | // Try to disable it anyway to work around a bug where resetting DRM state causes |
| 1359 | // vrr_capable to be reset to 0, potentially leaving VRR_ENABLED at 1. |
| 1360 | let _ = surface.use_vrr(false); |
| 1361 | } |
| 1362 | Err(err) => { |
| 1363 | warn!("error querying for VRR support: {err:?}"); |
| 1364 | } |
| 1365 | } |
| 1366 | |
| 1367 | // Update the output mode. |
| 1368 | let (physical_width, physical_height) = connector.size().unwrap_or((0, 0)); |
| 1369 | |
| 1370 | let output = Output::new( |
| 1371 | connector_name.clone(), |
| 1372 | PhysicalProperties { |
| 1373 | size: (physical_width as i32, physical_height as i32).into(), |
| 1374 | subpixel: connector.subpixel().into(), |
| 1375 | model: output_name.model.as_deref().unwrap_or("Unknown").to_owned(), |
| 1376 | make: output_name.make.as_deref().unwrap_or("Unknown").to_owned(), |
| 1377 | serial_number: output_name |
| 1378 | .serial |
| 1379 | .as_deref() |
| 1380 | .unwrap_or("Unknown") |
| 1381 | .to_owned(), |
| 1382 | }, |
| 1383 | ); |
| 1384 | |
| 1385 | let wl_mode = Mode::from(mode); |
| 1386 | output.change_current_state(Some(wl_mode), None, None, None); |
| 1387 | output.set_preferred(wl_mode); |
| 1388 | |
| 1389 | output |
| 1390 | .user_data() |
| 1391 | .insert_if_missing(|| TtyOutputState { node, crtc }); |
| 1392 | output.user_data().insert_if_missing(|| output_name.clone()); |
| 1393 | if let Some(x) = orientation { |
| 1394 | output.user_data().insert_if_missing(|| PanelOrientation(x)); |
| 1395 | } |
| 1396 | |
| 1397 | let render_node = device.render_node.unwrap_or(self.primary_render_node); |
| 1398 | let renderer = self.gpu_manager.single_renderer(&render_node)?; |
| 1399 | let egl_context = renderer.as_ref().egl_context(); |
| 1400 | let render_formats = egl_context.dmabuf_render_formats(); |
| 1401 | |
| 1402 | // Filter out the CCS modifiers as they have increased bandwidth, causing some monitor |
| 1403 | // configurations to stop working. |
| 1404 | // |
| 1405 | // For display only devices, restrict to linear buffers for best compatibility. |
| 1406 | // |
| 1407 | // The invalid modifier attempt below should make this unnecessary in some cases, but it |
| 1408 | // would still be a bad idea to remove this until Smithay has some kind of full-device |
| 1409 | // modesetting test that is able to "downgrade" existing connector modifiers to get enough |
| 1410 | // bandwidth for a newly connected one. |
| 1411 | let render_formats = render_formats |
| 1412 | .iter() |
| 1413 | .copied() |
| 1414 | .filter(|format| { |
| 1415 | if device.render_node.is_none() { |
| 1416 | return format.modifier == Modifier::Linear; |
| 1417 | } |
| 1418 | |
| 1419 | let is_ccs = matches!( |
| 1420 | format.modifier, |
| 1421 | Modifier::I915_y_tiled_ccs |
| 1422 | // I915_FORMAT_MOD_Yf_TILED_CCS |
| 1423 | | Modifier::Unrecognized(0x100000000000005) |
| 1424 | | Modifier::I915_y_tiled_gen12_rc_ccs |
| 1425 | | Modifier::I915_y_tiled_gen12_mc_ccs |
| 1426 | // I915_FORMAT_MOD_Y_TILED_GEN12_RC_CCS_CC |
| 1427 | | Modifier::Unrecognized(0x100000000000008) |
| 1428 | // I915_FORMAT_MOD_4_TILED_DG2_RC_CCS |
| 1429 | | Modifier::Unrecognized(0x10000000000000a) |
| 1430 | // I915_FORMAT_MOD_4_TILED_DG2_MC_CCS |
| 1431 | | Modifier::Unrecognized(0x10000000000000b) |
| 1432 | // I915_FORMAT_MOD_4_TILED_DG2_RC_CCS_CC |
| 1433 | | Modifier::Unrecognized(0x10000000000000c) |
| 1434 | ); |
| 1435 | |
| 1436 | !is_ccs |
| 1437 | }) |
| 1438 | .collect::<FormatSet>(); |
| 1439 | |
| 1440 | let color_formats = if self.config.borrow().debug.disable_10bit_output { |
| 1441 | &SUPPORTED_COLOR_FORMATS[..] |
| 1442 | } else { |
| 1443 | &SUPPORTED_COLOR_FORMATS_10BIT[..] |
| 1444 | } |
| 1445 | .iter() |
| 1446 | .copied(); |
| 1447 | |
| 1448 | // Create the compositor. |
| 1449 | let res = DrmCompositor::new( |
| 1450 | OutputModeSource::Auto(output.downgrade()), |
| 1451 | surface, |
| 1452 | None, |
| 1453 | device.allocator.clone(), |
| 1454 | GbmFramebufferExporter::new(device.gbm.clone(), device.render_node.into()), |
| 1455 | color_formats.clone(), |
| 1456 | // This is only used to pick a good internal format, so it can use the surface's render |
| 1457 | // formats, even though we only ever render on the primary GPU. |
| 1458 | render_formats.clone(), |
| 1459 | device.drm.cursor_size(), |
| 1460 | Some(device.gbm.clone()), |
| 1461 | ); |
| 1462 | |
| 1463 | let mut compositor = match res { |
| 1464 | Ok(x) => x, |
| 1465 | Err(err) => { |
| 1466 | warn!("error creating DRM compositor, will try with invalid modifier: {err:?}"); |
| 1467 | |
| 1468 | let render_formats = render_formats |
| 1469 | .iter() |
| 1470 | .copied() |
| 1471 | .filter(|format| format.modifier == Modifier::Invalid) |
| 1472 | .collect::<FormatSet>(); |
| 1473 | |
| 1474 | // DrmCompositor::new() consumed the surface... |
| 1475 | let surface = device |
| 1476 | .drm |
| 1477 | .create_surface(crtc, mode, &[connector.handle()])?; |
| 1478 | |
| 1479 | DrmCompositor::new( |
| 1480 | OutputModeSource::Auto(output.downgrade()), |
| 1481 | surface, |
| 1482 | None, |
| 1483 | device.allocator.clone(), |
| 1484 | GbmFramebufferExporter::new(device.gbm.clone(), device.render_node.into()), |
| 1485 | color_formats, |
| 1486 | render_formats, |
| 1487 | device.drm.cursor_size(), |
| 1488 | Some(device.gbm.clone()), |
| 1489 | ) |
| 1490 | .context("error creating DRM compositor")? |
| 1491 | } |
| 1492 | }; |
| 1493 | |
| 1494 | if self.debug_tint { |
| 1495 | compositor.set_debug_flags(DebugFlags::TINT); |
| 1496 | } |
| 1497 | |
| 1498 | let mut dmabuf_feedback = None; |
| 1499 | if let Ok(primary_renderer) = self.gpu_manager.single_renderer(&self.primary_render_node) { |
| 1500 | let primary_formats = primary_renderer.dmabuf_formats(); |
| 1501 | |
| 1502 | match surface_dmabuf_feedback( |
| 1503 | &compositor, |
| 1504 | primary_formats, |
| 1505 | self.primary_render_node, |
| 1506 | device.render_node, |
| 1507 | node, |
| 1508 | ) { |
| 1509 | Ok(feedback) => { |
| 1510 | dmabuf_feedback = Some(feedback); |
| 1511 | } |
| 1512 | Err(err) => { |
| 1513 | warn!("error building dmabuf feedback: {err:?}"); |
| 1514 | } |
| 1515 | } |
| 1516 | } |
| 1517 | |
| 1518 | // Some buggy monitors replug upon powering off, so powering on here would prevent such |
| 1519 | // monitors from powering off. Therefore, we avoid unconditionally powering on. |
| 1520 | if !niri.monitors_active { |
| 1521 | if let Err(err) = compositor.clear() { |
| 1522 | warn!("error clearing drm surface: {err:?}"); |
| 1523 | } |
| 1524 | } |
| 1525 | |
| 1526 | let vrr_enabled = compositor.vrr_enabled(); |
| 1527 | |
| 1528 | let vblank_frame_name = |
| 1529 | tracy_client::FrameName::new_leak(format!("vblank on {connector_name}")); |
| 1530 | let time_since_presentation_plot_name = tracy_client::PlotName::new_leak(format!( |
| 1531 | "{connector_name} time since presentation, ms" |
| 1532 | )); |
| 1533 | let presentation_misprediction_plot_name = tracy_client::PlotName::new_leak(format!( |
| 1534 | "{connector_name} presentation misprediction, ms" |
| 1535 | )); |
| 1536 | let sequence_delta_plot_name = |
| 1537 | tracy_client::PlotName::new_leak(format!("{connector_name} sequence delta")); |
| 1538 | |
| 1539 | let surface = Surface { |
| 1540 | name: output_name, |
| 1541 | connector: connector.handle(), |
| 1542 | compositor, |
| 1543 | dmabuf_feedback, |
| 1544 | gamma_props, |
| 1545 | pending_gamma_change: None, |
| 1546 | vblank_frame: None, |
| 1547 | vblank_frame_name, |
| 1548 | time_since_presentation_plot_name, |
| 1549 | presentation_misprediction_plot_name, |
| 1550 | sequence_delta_plot_name, |
| 1551 | }; |
| 1552 | |
| 1553 | let res = device.surfaces.insert(crtc, surface); |
| 1554 | assert!(res.is_none(), "crtc must not have already existed"); |
| 1555 | |
| 1556 | niri.add_output(output.clone(), Some(refresh_interval(mode)), vrr_enabled); |
| 1557 | |
| 1558 | if niri.monitors_active { |
| 1559 | // Redraw the new monitor. |
| 1560 | niri.event_loop.insert_idle(move |state| { |
| 1561 | // Guard against output disconnecting before the idle has a chance to run. |
| 1562 | if state.niri.output_state.contains_key(&output) { |
| 1563 | state.niri.queue_redraw(&output); |
| 1564 | } |
| 1565 | }); |
| 1566 | } |
| 1567 | |
| 1568 | Ok(()) |
| 1569 | } |
| 1570 | |
| 1571 | fn connector_disconnected(&mut self, niri: &mut Niri, node: DrmNode, crtc: crtc::Handle) { |
| 1572 | let Some(device) = self.devices.get_mut(&node) else { |
| 1573 | debug!("disconnecting connector for crtc: {crtc:?}"); |
| 1574 | error!("missing device"); |
| 1575 | return; |
| 1576 | }; |
| 1577 | |
| 1578 | let Some(surface) = device.surfaces.remove(&crtc) else { |
| 1579 | debug!("disconnecting connector for crtc: {crtc:?}"); |
| 1580 | |
| 1581 | if let Some((conn, _)) = device |
| 1582 | .non_desktop_connectors |
| 1583 | .iter() |
| 1584 | .find(|(_, crtc_)| *crtc_ == crtc) |
| 1585 | { |
| 1586 | debug!("withdrawing non-desktop connector from DRM leasing"); |
| 1587 | |
| 1588 | let conn = *conn; |
| 1589 | device.non_desktop_connectors.remove(&(conn, crtc)); |
| 1590 | |
| 1591 | if let Some(lease_state) = &mut device.drm_lease_state { |
| 1592 | lease_state.withdraw_connector(conn); |
| 1593 | } |
| 1594 | } else { |
| 1595 | debug!("crtc wasn't enabled"); |
| 1596 | } |
| 1597 | |
| 1598 | return; |
| 1599 | }; |
| 1600 | |
| 1601 | debug!("disconnecting connector: {:?}", surface.name.connector); |
| 1602 | |
| 1603 | let output = niri |
| 1604 | .global_space |
| 1605 | .outputs() |
| 1606 | .find(|output| { |
| 1607 | let tty_state: &TtyOutputState = output.user_data().get().unwrap(); |
| 1608 | tty_state.node == node && tty_state.crtc == crtc |
| 1609 | }) |
| 1610 | .cloned(); |
| 1611 | if let Some(output) = output { |
| 1612 | niri.remove_output(&output); |
| 1613 | } else { |
| 1614 | error!("missing output for crtc {crtc:?}"); |
| 1615 | }; |
| 1616 | } |
| 1617 | |
| 1618 | fn on_vblank( |
| 1619 | &mut self, |
| 1620 | niri: &mut Niri, |
| 1621 | node: DrmNode, |
| 1622 | crtc: crtc::Handle, |
| 1623 | meta: DrmEventMetadata, |
| 1624 | ) { |
| 1625 | let span = tracy_client::span!("Tty::on_vblank"); |
| 1626 | |
| 1627 | let now = get_monotonic_time(); |
| 1628 | |
| 1629 | let Some(device) = self.devices.get_mut(&node) else { |
| 1630 | // I've seen it happen. |
| 1631 | error!("missing device in vblank callback for crtc {crtc:?}"); |
| 1632 | return; |
| 1633 | }; |
| 1634 | |
| 1635 | let Some(surface) = device.surfaces.get_mut(&crtc) else { |
| 1636 | error!("missing surface in vblank callback for crtc {crtc:?}"); |
| 1637 | return; |
| 1638 | }; |
| 1639 | |
| 1640 | // Finish the Tracy frame, if any. |
| 1641 | drop(surface.vblank_frame.take()); |
| 1642 | |
| 1643 | let name = &surface.name.connector; |
| 1644 | trace!("vblank on {name} {meta:?}"); |
| 1645 | span.emit_text(name); |
| 1646 | |
| 1647 | let presentation_time = match meta.time { |
| 1648 | DrmEventTime::Monotonic(time) => time, |
| 1649 | DrmEventTime::Realtime(_) => { |
| 1650 | // Not supported. |
| 1651 | |
| 1652 | // This value will be ignored in the frame clock code. |
| 1653 | Duration::ZERO |
| 1654 | } |
| 1655 | }; |
| 1656 | let presentation_time = if niri.config.borrow().debug.emulate_zero_presentation_time { |
| 1657 | Duration::ZERO |
| 1658 | } else { |
| 1659 | presentation_time |
| 1660 | }; |
| 1661 | |
| 1662 | let message = if presentation_time.is_zero() { |
| 1663 | format!("vblank on {name}, presentation time unknown") |
| 1664 | } else if presentation_time > now { |
| 1665 | let diff = presentation_time - now; |
| 1666 | tracy_client::Client::running().unwrap().plot( |
| 1667 | surface.time_since_presentation_plot_name, |
| 1668 | -diff.as_secs_f64() * 1000., |
| 1669 | ); |
| 1670 | format!("vblank on {name}, presentation is {diff:?} later") |
| 1671 | } else { |
| 1672 | let diff = now - presentation_time; |
| 1673 | tracy_client::Client::running().unwrap().plot( |
| 1674 | surface.time_since_presentation_plot_name, |
| 1675 | diff.as_secs_f64() * 1000., |
| 1676 | ); |
| 1677 | format!("vblank on {name}, presentation was {diff:?} ago") |
| 1678 | }; |
| 1679 | tracy_client::Client::running() |
| 1680 | .unwrap() |
| 1681 | .message(&message, 0); |
| 1682 | |
| 1683 | let Some(output) = niri |
| 1684 | .global_space |
| 1685 | .outputs() |
| 1686 | .find(|output| { |
| 1687 | let tty_state: &TtyOutputState = output.user_data().get().unwrap(); |
| 1688 | tty_state.node == node && tty_state.crtc == crtc |
| 1689 | }) |
| 1690 | .cloned() |
| 1691 | else { |
| 1692 | error!("missing output in global space for {name}"); |
| 1693 | return; |
| 1694 | }; |
| 1695 | |
| 1696 | let Some(output_state) = niri.output_state.get_mut(&output) else { |
| 1697 | error!("missing output state for {name}"); |
| 1698 | return; |
| 1699 | }; |
| 1700 | |
| 1701 | let refresh_interval = output_state.frame_clock.refresh_interval(); |
| 1702 | |
| 1703 | let time = if presentation_time.is_zero() { |
| 1704 | now |
| 1705 | } else { |
| 1706 | presentation_time |
| 1707 | }; |
| 1708 | |
| 1709 | if output_state |
| 1710 | .vblank_throttle |
| 1711 | .throttle(refresh_interval, time, move |state| { |
| 1712 | let meta = DrmEventMetadata { |
| 1713 | sequence: meta.sequence, |
| 1714 | time: DrmEventTime::Monotonic(Duration::ZERO), |
| 1715 | }; |
| 1716 | |
| 1717 | let tty = state.backend.tty(); |
| 1718 | tty.on_vblank(&mut state.niri, node, crtc, meta); |
| 1719 | }) |
| 1720 | { |
| 1721 | // Throttled. |
| 1722 | return; |
| 1723 | } |
| 1724 | |
| 1725 | let redraw_needed = match mem::replace(&mut output_state.redraw_state, RedrawState::Idle) { |
| 1726 | RedrawState::WaitingForVBlank { redraw_needed } => redraw_needed, |
| 1727 | state @ (RedrawState::Idle |
| 1728 | | RedrawState::Queued |
| 1729 | | RedrawState::WaitingForEstimatedVBlank(_) |
| 1730 | | RedrawState::WaitingForEstimatedVBlankAndQueued(_)) => { |
| 1731 | // This is an error!() because it shouldn't happen, but on some systems it somehow |
| 1732 | // does. Kernel sending rogue vblank events? |
| 1733 | // |
| 1734 | // https://github.com/niri-wm/niri/issues/556 |
| 1735 | // https://github.com/niri-wm/niri/issues/615 |
| 1736 | error!( |
| 1737 | "unexpected redraw state for output {name} (should be WaitingForVBlank); \ |
| 1738 | can happen when resuming from sleep or powering on monitors: {state:?}" |
| 1739 | ); |
| 1740 | true |
| 1741 | } |
| 1742 | }; |
| 1743 | |
| 1744 | // Mark the last frame as submitted. |
| 1745 | match surface.compositor.frame_submitted() { |
| 1746 | Ok(Some((mut feedback, target_presentation_time))) => { |
| 1747 | let refresh = match refresh_interval { |
| 1748 | Some(refresh) => { |
| 1749 | if output_state.frame_clock.vrr() { |
| 1750 | Refresh::Variable(refresh) |
| 1751 | } else { |
| 1752 | Refresh::Fixed(refresh) |
| 1753 | } |
| 1754 | } |
| 1755 | None => Refresh::Unknown, |
| 1756 | }; |
| 1757 | |
| 1758 | // FIXME: ideally should be monotonically increasing for a surface. |
| 1759 | let seq = meta.sequence as u64; |
| 1760 | let mut flags = wp_presentation_feedback::Kind::Vsync |
| 1761 | | wp_presentation_feedback::Kind::HwCompletion; |
| 1762 | |
| 1763 | if !presentation_time.is_zero() { |
| 1764 | flags.insert(wp_presentation_feedback::Kind::HwClock); |
| 1765 | } |
| 1766 | |
| 1767 | feedback.presented::<_, smithay::utils::Monotonic>(time, refresh, seq, flags); |
| 1768 | |
| 1769 | if !presentation_time.is_zero() { |
| 1770 | let misprediction_s = |
| 1771 | presentation_time.as_secs_f64() - target_presentation_time.as_secs_f64(); |
| 1772 | tracy_client::Client::running().unwrap().plot( |
| 1773 | surface.presentation_misprediction_plot_name, |
| 1774 | misprediction_s * 1000., |
| 1775 | ); |
| 1776 | } |
| 1777 | } |
| 1778 | Ok(None) => (), |
| 1779 | Err(err) => { |
| 1780 | warn!("error marking frame as submitted: {err}"); |
| 1781 | } |
| 1782 | } |
| 1783 | |
| 1784 | if let Some(last_sequence) = output_state.last_drm_sequence { |
| 1785 | let delta = meta.sequence as f64 - last_sequence as f64; |
| 1786 | tracy_client::Client::running() |
| 1787 | .unwrap() |
| 1788 | .plot(surface.sequence_delta_plot_name, delta); |
| 1789 | } |
| 1790 | output_state.last_drm_sequence = Some(meta.sequence); |
| 1791 | |
| 1792 | output_state.frame_clock.presented(presentation_time); |
| 1793 | |
| 1794 | if redraw_needed || output_state.unfinished_animations_remain { |
| 1795 | let vblank_frame = tracy_client::Client::running() |
| 1796 | .unwrap() |
| 1797 | .non_continuous_frame(surface.vblank_frame_name); |
| 1798 | surface.vblank_frame = Some(vblank_frame); |
| 1799 | |
| 1800 | niri.queue_redraw(&output); |
| 1801 | } else { |
| 1802 | niri.send_frame_callbacks(&output); |
| 1803 | } |
| 1804 | } |
| 1805 | |
| 1806 | fn on_estimated_vblank_timer(&self, niri: &mut Niri, output: Output) { |
| 1807 | let span = tracy_client::span!("Tty::on_estimated_vblank_timer"); |
| 1808 | |
| 1809 | let name = output.name(); |
| 1810 | span.emit_text(&name); |
| 1811 | |
| 1812 | let Some(output_state) = niri.output_state.get_mut(&output) else { |
| 1813 | error!("missing output state for {name}"); |
| 1814 | return; |
| 1815 | }; |
| 1816 | |
| 1817 | // We waited for the timer, now we can send frame callbacks again. |
| 1818 | output_state.frame_callback_sequence = output_state.frame_callback_sequence.wrapping_add(1); |
| 1819 | |
| 1820 | match mem::replace(&mut output_state.redraw_state, RedrawState::Idle) { |
| 1821 | RedrawState::Idle => unreachable!(), |
| 1822 | RedrawState::Queued => unreachable!(), |
| 1823 | RedrawState::WaitingForVBlank { .. } => unreachable!(), |
| 1824 | RedrawState::WaitingForEstimatedVBlank(_) => (), |
| 1825 | // The timer fired just in front of a redraw. |
| 1826 | RedrawState::WaitingForEstimatedVBlankAndQueued(_) => { |
| 1827 | output_state.redraw_state = RedrawState::Queued; |
| 1828 | return; |
| 1829 | } |
| 1830 | } |
| 1831 | |
| 1832 | if output_state.unfinished_animations_remain { |
| 1833 | niri.queue_redraw(&output); |
| 1834 | } else { |
| 1835 | niri.send_frame_callbacks(&output); |
| 1836 | } |
| 1837 | } |
| 1838 | |
| 1839 | pub fn seat_name(&self) -> String { |
| 1840 | self.session.seat() |
| 1841 | } |
| 1842 | |
| 1843 | pub fn with_primary_renderer<T>( |
| 1844 | &mut self, |
| 1845 | f: impl FnOnce(&mut GlesRenderer) -> T, |
| 1846 | ) -> Option<T> { |
| 1847 | let mut renderer = self |
| 1848 | .gpu_manager |
| 1849 | .single_renderer(&self.primary_render_node) |
| 1850 | .ok()?; |
| 1851 | Some(f(renderer.as_gles_renderer())) |
| 1852 | } |
| 1853 | |
| 1854 | pub fn render( |
| 1855 | &mut self, |
| 1856 | niri: &mut Niri, |
| 1857 | output: &Output, |
| 1858 | target_presentation_time: Duration, |
| 1859 | ) -> RenderResult { |
| 1860 | let span = tracy_client::span!("Tty::render"); |
| 1861 | |
| 1862 | let mut rv = RenderResult::Skipped; |
| 1863 | |
| 1864 | let tty_state: &TtyOutputState = output.user_data().get().unwrap(); |
| 1865 | let Some(device) = self.devices.get_mut(&tty_state.node) else { |
| 1866 | error!("missing output device"); |
| 1867 | return rv; |
| 1868 | }; |
| 1869 | |
| 1870 | let Some(surface) = device.surfaces.get_mut(&tty_state.crtc) else { |
| 1871 | error!("missing surface"); |
| 1872 | return rv; |
| 1873 | }; |
| 1874 | |
| 1875 | span.emit_text(&surface.name.connector); |
| 1876 | |
| 1877 | if !device.drm.is_active() { |
| 1878 | // This branch hits any time we try to render while the user had switched to a |
| 1879 | // different VT, so don't print anything here. |
| 1880 | return rv; |
| 1881 | } |
| 1882 | |
| 1883 | let mut renderer = match self.gpu_manager.renderer( |
| 1884 | &self.primary_render_node, |
| 1885 | &device.render_node.unwrap_or(self.primary_render_node), |
| 1886 | surface.compositor.format(), |
| 1887 | ) { |
| 1888 | Ok(renderer) => renderer, |
| 1889 | Err(err) => { |
| 1890 | warn!("error creating renderer for primary GPU: {err:?}"); |
| 1891 | return rv; |
| 1892 | } |
| 1893 | }; |
| 1894 | |
| 1895 | // Render the elements. |
| 1896 | let ctx = RenderCtx { |
| 1897 | renderer: &mut renderer, |
| 1898 | target: RenderTarget::Output, |
| 1899 | xray: None, |
| 1900 | }; |
| 1901 | let mut elements = niri.render_to_vec(ctx, output, true); |
| 1902 | |
| 1903 | // Visualize the damage, if enabled. |
| 1904 | if niri.debug_draw_damage { |
| 1905 | let output_state = niri.output_state.get_mut(output).unwrap(); |
| 1906 | draw_damage(&mut output_state.debug_damage_tracker, &mut elements); |
| 1907 | } |
| 1908 | |
| 1909 | // Overlay planes are disabled by default as they cause weird performance issues on my |
| 1910 | // system. |
| 1911 | let flags = { |
| 1912 | let debug = &self.config.borrow().debug; |
| 1913 | |
| 1914 | let primary_scanout_flag = if debug.restrict_primary_scanout_to_matching_format { |
| 1915 | FrameFlags::ALLOW_PRIMARY_PLANE_SCANOUT |
| 1916 | } else { |
| 1917 | FrameFlags::ALLOW_PRIMARY_PLANE_SCANOUT_ANY |
| 1918 | }; |
| 1919 | let mut flags = primary_scanout_flag | FrameFlags::ALLOW_CURSOR_PLANE_SCANOUT; |
| 1920 | |
| 1921 | if debug.enable_overlay_planes { |
| 1922 | flags.insert(FrameFlags::ALLOW_OVERLAY_PLANE_SCANOUT); |
| 1923 | } |
| 1924 | if debug.disable_direct_scanout { |
| 1925 | flags.remove(primary_scanout_flag); |
| 1926 | flags.remove(FrameFlags::ALLOW_OVERLAY_PLANE_SCANOUT); |
| 1927 | } |
| 1928 | if debug.disable_cursor_plane { |
| 1929 | flags.remove(FrameFlags::ALLOW_CURSOR_PLANE_SCANOUT); |
| 1930 | } |
| 1931 | if debug.skip_cursor_only_updates_during_vrr { |
| 1932 | let output_state = niri.output_state.get(output).unwrap(); |
| 1933 | if output_state.frame_clock.vrr() { |
| 1934 | flags.insert(FrameFlags::SKIP_CURSOR_ONLY_UPDATES); |
| 1935 | } |
| 1936 | } |
| 1937 | |
| 1938 | flags |
| 1939 | }; |
| 1940 | |
| 1941 | // Hand them over to the DRM. |
| 1942 | let drm_compositor = &mut surface.compositor; |
| 1943 | match drm_compositor.render_frame::<_, _>(&mut renderer, &elements, [0.; 4], flags) { |
| 1944 | Ok(res) => { |
| 1945 | let needs_sync = res.needs_sync() |
| 1946 | || self |
| 1947 | .config |
| 1948 | .borrow() |
| 1949 | .debug |
| 1950 | .wait_for_frame_completion_before_queueing; |
| 1951 | if needs_sync { |
| 1952 | if let PrimaryPlaneElement::Swapchain(element) = res.primary_element { |
| 1953 | let _span = tracy_client::span!("wait for completion"); |
| 1954 | if let Err(err) = element.sync.wait() { |
| 1955 | warn!("error waiting for frame completion: {err:?}"); |
| 1956 | } |
| 1957 | } |
| 1958 | } |
| 1959 | |
| 1960 | niri.update_primary_scanout_output(output, &res.states); |
| 1961 | if let Some(dmabuf_feedback) = surface.dmabuf_feedback.as_ref() { |
| 1962 | niri.send_dmabuf_feedbacks(output, dmabuf_feedback, &res.states); |
| 1963 | } |
| 1964 | |
| 1965 | if !res.is_empty { |
| 1966 | let presentation_feedbacks = |
| 1967 | niri.take_presentation_feedbacks(output, &res.states); |
| 1968 | let data = (presentation_feedbacks, target_presentation_time); |
| 1969 | |
| 1970 | match drm_compositor.queue_frame(data) { |
| 1971 | Ok(()) => { |
| 1972 | let output_state = niri.output_state.get_mut(output).unwrap(); |
| 1973 | let new_state = RedrawState::WaitingForVBlank { |
| 1974 | redraw_needed: false, |
| 1975 | }; |
| 1976 | match mem::replace(&mut output_state.redraw_state, new_state) { |
| 1977 | RedrawState::Idle => unreachable!(), |
| 1978 | RedrawState::Queued => (), |
| 1979 | RedrawState::WaitingForVBlank { .. } => unreachable!(), |
| 1980 | RedrawState::WaitingForEstimatedVBlank(_) => unreachable!(), |
| 1981 | RedrawState::WaitingForEstimatedVBlankAndQueued(token) => { |
| 1982 | niri.event_loop.remove(token); |
| 1983 | } |
| 1984 | }; |
| 1985 | |
| 1986 | // We queued this frame successfully, so the current client buffers were |
| 1987 | // latched. We can send frame callbacks now, since a new client commit |
| 1988 | // will no longer overwrite this frame and will wait for a VBlank. |
| 1989 | output_state.frame_callback_sequence = |
| 1990 | output_state.frame_callback_sequence.wrapping_add(1); |
| 1991 | |
| 1992 | return RenderResult::Submitted; |
| 1993 | } |
| 1994 | Err(err) => { |
| 1995 | warn!("error queueing frame: {err}"); |
| 1996 | } |
| 1997 | } |
| 1998 | } else { |
| 1999 | rv = RenderResult::NoDamage; |
| 2000 | } |
| 2001 | } |
| 2002 | Err(err) => { |
| 2003 | // Can fail if we switched to a different TTY. |
| 2004 | warn!("error rendering frame: {err}"); |
| 2005 | } |
| 2006 | } |
| 2007 | |
| 2008 | // We're not expecting a vblank right after this. |
| 2009 | drop(surface.vblank_frame.take()); |
| 2010 | |
| 2011 | // Queue a timer to fire at the predicted vblank time. |
| 2012 | queue_estimated_vblank_timer(niri, output.clone(), target_presentation_time); |
| 2013 | |
| 2014 | rv |
| 2015 | } |
| 2016 | |
| 2017 | pub fn change_vt(&mut self, vt: i32) { |
| 2018 | if let Err(err) = self.session.change_vt(vt) { |
| 2019 | warn!("error changing VT: {err}"); |
| 2020 | } |
| 2021 | } |
| 2022 | |
| 2023 | pub fn suspend(&self) { |
| 2024 | #[cfg(feature = "dbus")] |
| 2025 | if let Err(err) = suspend() { |
| 2026 | warn!("error suspending: {err:?}"); |
| 2027 | } |
| 2028 | } |
| 2029 | |
| 2030 | pub fn toggle_debug_tint(&mut self) { |
| 2031 | self.debug_tint = !self.debug_tint; |
| 2032 | |
| 2033 | for device in self.devices.values_mut() { |
| 2034 | for surface in device.surfaces.values_mut() { |
| 2035 | let compositor = &mut surface.compositor; |
| 2036 | |
| 2037 | let mut flags = compositor.debug_flags(); |
| 2038 | flags.set(DebugFlags::TINT, self.debug_tint); |
| 2039 | compositor.set_debug_flags(flags); |
| 2040 | } |
| 2041 | } |
| 2042 | } |
| 2043 | |
| 2044 | pub fn import_dmabuf(&mut self, dmabuf: &Dmabuf) -> bool { |
| 2045 | let mut renderer = match self.gpu_manager.single_renderer(&self.primary_render_node) { |
| 2046 | Ok(renderer) => renderer, |
| 2047 | Err(err) => { |
| 2048 | debug!("error creating renderer for primary GPU: {err:?}"); |
| 2049 | return false; |
| 2050 | } |
| 2051 | }; |
| 2052 | |
| 2053 | match renderer.import_dmabuf(dmabuf, None) { |
| 2054 | Ok(_texture) => { |
| 2055 | if dmabuf.node().is_none() { |
| 2056 | dmabuf.set_node(Some(self.primary_render_node)); |
| 2057 | } |
| 2058 | true |
| 2059 | } |
| 2060 | Err(err) => { |
| 2061 | debug!("error importing dmabuf: {err:?}"); |
| 2062 | false |
| 2063 | } |
| 2064 | } |
| 2065 | } |
| 2066 | |
| 2067 | pub fn early_import(&mut self, surface: &WlSurface) { |
| 2068 | if let Err(err) = self.gpu_manager.early_import( |
| 2069 | // We always render on the primary GPU. |
| 2070 | self.primary_render_node, |
| 2071 | surface, |
| 2072 | ) { |
| 2073 | warn!("error doing early import: {err:?}"); |
| 2074 | } |
| 2075 | } |
| 2076 | |
| 2077 | pub fn get_gamma_size(&self, output: &Output) -> anyhow::Result<u32> { |
| 2078 | let tty_state = output.user_data().get::<TtyOutputState>().unwrap(); |
| 2079 | let crtc = tty_state.crtc; |
| 2080 | |
| 2081 | let device = self |
| 2082 | .devices |
| 2083 | .get(&tty_state.node) |
| 2084 | .context("missing device")?; |
| 2085 | |
| 2086 | let surface = device.surfaces.get(&crtc).context("missing surface")?; |
| 2087 | if let Some(gamma_props) = &surface.gamma_props { |
| 2088 | gamma_props.gamma_size(&device.drm) |
| 2089 | } else { |
| 2090 | let info = device |
| 2091 | .drm |
| 2092 | .get_crtc(crtc) |
| 2093 | .context("error getting crtc info")?; |
| 2094 | Ok(info.gamma_length()) |
| 2095 | } |
| 2096 | } |
| 2097 | |
| 2098 | pub fn set_gamma(&mut self, output: &Output, ramp: Option<Vec<u16>>) -> anyhow::Result<()> { |
| 2099 | let tty_state = output.user_data().get::<TtyOutputState>().unwrap(); |
| 2100 | let crtc = tty_state.crtc; |
| 2101 | |
| 2102 | let device = self |
| 2103 | .devices |
| 2104 | .get_mut(&tty_state.node) |
| 2105 | .context("missing device")?; |
| 2106 | let surface = device.surfaces.get_mut(&crtc).context("missing surface")?; |
| 2107 | |
| 2108 | // Cannot change properties while the device is inactive. |
| 2109 | if !self.session.is_active() { |
| 2110 | surface.pending_gamma_change = Some(ramp); |
| 2111 | return Ok(()); |
| 2112 | } |
| 2113 | |
| 2114 | let ramp = ramp.as_deref(); |
| 2115 | if let Some(gamma_props) = &mut surface.gamma_props { |
| 2116 | gamma_props.set_gamma(&device.drm, ramp) |
| 2117 | } else { |
| 2118 | set_gamma_for_crtc(&device.drm, crtc, ramp) |
| 2119 | } |
| 2120 | } |
| 2121 | |
| 2122 | fn refresh_ipc_outputs(&self, niri: &mut Niri) { |
| 2123 | let _span = tracy_client::span!("Tty::refresh_ipc_outputs"); |
| 2124 | |
| 2125 | let mut ipc_outputs = HashMap::new(); |
| 2126 | let disable_monitor_names = self.config.borrow().debug.disable_monitor_names; |
| 2127 | |
| 2128 | for (node, device) in &self.devices { |
| 2129 | for (connector, crtc) in device.drm_scanner.crtcs() { |
| 2130 | let connector_name = format_connector_name(connector); |
| 2131 | let physical_size = connector.size(); |
| 2132 | let output_name = device.known_crtc_name(&crtc, connector, disable_monitor_names); |
| 2133 | |
| 2134 | let surface = device.surfaces.get(&crtc); |
| 2135 | let current_crtc_mode = surface.map(|surface| surface.compositor.pending_mode()); |
| 2136 | let mut current_mode = None; |
| 2137 | let mut is_custom_mode = false; |
| 2138 | |
| 2139 | let mut modes: Vec<niri_ipc::Mode> = connector |
| 2140 | .modes() |
| 2141 | .iter() |
| 2142 | .filter(|m| !m.flags().contains(ModeFlags::INTERLACE)) |
| 2143 | .enumerate() |
| 2144 | .map(|(idx, m)| { |
| 2145 | if Some(*m) == current_crtc_mode { |
| 2146 | current_mode = Some(idx); |
| 2147 | } |
| 2148 | |
| 2149 | niri_ipc::Mode { |
| 2150 | width: m.size().0, |
| 2151 | height: m.size().1, |
| 2152 | refresh_rate: Mode::from(*m).refresh as u32, |
| 2153 | is_preferred: m.mode_type().contains(ModeTypeFlags::PREFERRED), |
| 2154 | } |
| 2155 | }) |
| 2156 | .collect(); |
| 2157 | |
| 2158 | if let Some(crtc_mode) = current_crtc_mode { |
| 2159 | // Custom mode |
| 2160 | if crtc_mode.mode_type().contains(ModeTypeFlags::USERDEF) { |
| 2161 | modes.insert( |
| 2162 | 0, |
| 2163 | niri_ipc::Mode { |
| 2164 | width: crtc_mode.size().0, |
| 2165 | height: crtc_mode.size().1, |
| 2166 | refresh_rate: Mode::from(crtc_mode).refresh as u32, |
| 2167 | is_preferred: false, |
| 2168 | }, |
| 2169 | ); |
| 2170 | current_mode = Some(0); |
| 2171 | is_custom_mode = true; |
| 2172 | } |
| 2173 | |
| 2174 | if current_mode.is_none() { |
| 2175 | if crtc_mode.flags().contains(ModeFlags::INTERLACE) { |
| 2176 | warn!("connector mode list missing current mode (interlaced)"); |
| 2177 | } else { |
| 2178 | error!("connector mode list missing current mode"); |
| 2179 | } |
| 2180 | } |
| 2181 | } |
| 2182 | |
| 2183 | let vrr_supported = surface |
| 2184 | .map(|surface| { |
| 2185 | matches!( |
| 2186 | surface.compositor.vrr_supported(connector.handle()), |
| 2187 | Ok(VrrSupport::Supported | VrrSupport::RequiresModeset) |
| 2188 | ) |
| 2189 | }) |
| 2190 | .unwrap_or_else(|| { |
| 2191 | is_vrr_capable(&device.drm, connector.handle()) == Some(true) |
| 2192 | }); |
| 2193 | let vrr_enabled = surface.is_some_and(|surface| surface.compositor.vrr_enabled()); |
| 2194 | |
| 2195 | let logical = niri |
| 2196 | .global_space |
| 2197 | .outputs() |
| 2198 | .find(|output| { |
| 2199 | let tty_state: &TtyOutputState = output.user_data().get().unwrap(); |
| 2200 | tty_state.node == *node && tty_state.crtc == crtc |
| 2201 | }) |
| 2202 | .map(logical_output); |
| 2203 | |
| 2204 | let id = device.known_crtcs.get(&crtc).map(|info| info.id); |
| 2205 | let id = id.unwrap_or_else(|| { |
| 2206 | error!("crtc for connector {connector_name} missing from known"); |
| 2207 | OutputId::next() |
| 2208 | }); |
| 2209 | |
| 2210 | let props = ConnectorProperties::try_new(&device.drm, connector.handle()).ok(); |
| 2211 | let max_bpc = props.as_ref().and_then(|p| p.find(c"max bpc").ok()); |
| 2212 | let max_bpc = max_bpc.and_then(|(info, value)| { |
| 2213 | info.value_type() |
| 2214 | .convert_value(*value) |
| 2215 | .as_unsigned_range() |
| 2216 | .map(|v| v as u8) |
| 2217 | }); |
| 2218 | |
| 2219 | let ipc_output = niri_ipc::Output { |
| 2220 | name: connector_name, |
| 2221 | make: output_name.make.unwrap_or_else(|| "Unknown".into()), |
| 2222 | model: output_name.model.unwrap_or_else(|| "Unknown".into()), |
| 2223 | serial: output_name.serial, |
| 2224 | physical_size, |
| 2225 | modes, |
| 2226 | current_mode, |
| 2227 | is_custom_mode, |
| 2228 | vrr_supported, |
| 2229 | vrr_enabled, |
| 2230 | logical, |
| 2231 | max_bpc, |
| 2232 | }; |
| 2233 | |
| 2234 | ipc_outputs.insert(id, ipc_output); |
| 2235 | } |
| 2236 | } |
| 2237 | |
| 2238 | let mut guard = self.ipc_outputs.lock().unwrap(); |
| 2239 | *guard = ipc_outputs; |
| 2240 | niri.ipc_outputs_changed = true; |
| 2241 | } |
| 2242 | |
| 2243 | pub fn ipc_outputs(&self) -> Arc<Mutex<IpcOutputMap>> { |
| 2244 | self.ipc_outputs.clone() |
| 2245 | } |
| 2246 | |
| 2247 | #[cfg(feature = "xdp-gnome-screencast")] |
| 2248 | pub fn primary_gbm_device(&self) -> Option<GbmDevice<DrmDeviceFd>> { |
| 2249 | // Try to find a device corresponding to the primary render node. |
| 2250 | let device = self |
| 2251 | .devices |
| 2252 | .values() |
| 2253 | .find(|d| d.render_node == Some(self.primary_render_node)); |
| 2254 | // Otherwise, try to get the device corresponding to the primary node. |
| 2255 | let device = device.or_else(|| self.devices.get(&self.primary_node)); |
| 2256 | |
| 2257 | Some(device?.gbm.clone()) |
| 2258 | } |
| 2259 | |
| 2260 | pub fn set_monitors_active(&mut self, active: bool) { |
| 2261 | // We only disable the CRTC here, this will also reset the |
| 2262 | // surface state so that the next call to `render_frame` will |
| 2263 | // always produce a new frame and `queue_frame` will change |
| 2264 | // the CRTC to active. This makes sure we always enable a CRTC |
| 2265 | // within an atomic operation. |
| 2266 | if active { |
| 2267 | return; |
| 2268 | } |
| 2269 | |
| 2270 | for device in self.devices.values_mut() { |
| 2271 | for surface in device.surfaces.values_mut() { |
| 2272 | if let Err(err) = surface.compositor.clear() { |
| 2273 | warn!("error clearing drm surface: {err:?}"); |
| 2274 | } |
| 2275 | } |
| 2276 | } |
| 2277 | } |
| 2278 | |
| 2279 | pub fn set_output_on_demand_vrr(&mut self, niri: &mut Niri, output: &Output, enable_vrr: bool) { |
| 2280 | let _span = tracy_client::span!("Tty::set_output_on_demand_vrr"); |
| 2281 | |
| 2282 | let output_state = niri.output_state.get_mut(output).unwrap(); |
| 2283 | output_state.on_demand_vrr_enabled = enable_vrr; |
| 2284 | if output_state.frame_clock.vrr() == enable_vrr { |
| 2285 | return; |
| 2286 | } |
| 2287 | for (&node, device) in self.devices.iter_mut() { |
| 2288 | for (&crtc, surface) in device.surfaces.iter_mut() { |
| 2289 | let tty_state: &TtyOutputState = output.user_data().get().unwrap(); |
| 2290 | if tty_state.node == node && tty_state.crtc == crtc { |
| 2291 | let word = if enable_vrr { "enabling" } else { "disabling" }; |
| 2292 | if let Err(err) = surface.compositor.use_vrr(enable_vrr) { |
| 2293 | warn!( |
| 2294 | "output {:?}: error {} VRR: {err:?}", |
| 2295 | surface.name.connector, word |
| 2296 | ); |
| 2297 | } |
| 2298 | output_state |
| 2299 | .frame_clock |
| 2300 | .set_vrr(surface.compositor.vrr_enabled()); |
| 2301 | |
| 2302 | self.refresh_ipc_outputs(niri); |
| 2303 | return; |
| 2304 | } |
| 2305 | } |
| 2306 | } |
| 2307 | } |
| 2308 | |
| 2309 | fn compute_ignored_nodes(&self) -> HashSet<DrmNode> { |
| 2310 | let mut ignored_nodes = ignored_nodes_from_config(&self.config.borrow()); |
| 2311 | if ignored_nodes.remove(&self.primary_node) |
| 2312 | || ignored_nodes.remove(&self.primary_render_node) |
| 2313 | { |
| 2314 | warn!("ignoring the primary node or render node is not allowed"); |
| 2315 | } |
| 2316 | ignored_nodes |
| 2317 | } |
| 2318 | |
| 2319 | pub fn update_ignored_nodes_config(&mut self, niri: &mut Niri) { |
| 2320 | let _span = tracy_client::span!("Tty::update_ignored_nodes_config"); |
| 2321 | |
| 2322 | // If we're inactive, we can't do anything, but we'll recompute in ActivateSession. |
| 2323 | if !self.session.is_active() { |
| 2324 | return; |
| 2325 | } |
| 2326 | |
| 2327 | let ignored_nodes = self.compute_ignored_nodes(); |
| 2328 | if ignored_nodes == self.ignored_nodes { |
| 2329 | return; |
| 2330 | } |
| 2331 | self.ignored_nodes = ignored_nodes; |
| 2332 | |
| 2333 | let mut device_list = self |
| 2334 | .udev_dispatcher |
| 2335 | .as_source_ref() |
| 2336 | .device_list() |
| 2337 | .map(|(device_id, path)| (device_id, path.to_owned())) |
| 2338 | .collect::<HashMap<_, _>>(); |
| 2339 | |
| 2340 | let removed_devices = self |
| 2341 | .devices |
| 2342 | .keys() |
| 2343 | .filter(|node| { |
| 2344 | self.ignored_nodes.contains(node) || !device_list.contains_key(&node.dev_id()) |
| 2345 | }) |
| 2346 | .copied() |
| 2347 | .collect::<Vec<_>>(); |
| 2348 | |
| 2349 | for node in removed_devices { |
| 2350 | device_list.remove(&node.dev_id()); |
| 2351 | self.device_removed(node.dev_id(), niri); |
| 2352 | } |
| 2353 | |
| 2354 | for node in self.devices.keys() { |
| 2355 | device_list.remove(&node.dev_id()); |
| 2356 | } |
| 2357 | |
| 2358 | for (device_id, path) in device_list { |
| 2359 | if let Err(err) = self.device_added(device_id, &path, niri) { |
| 2360 | warn!("error adding device {path:?}: {err:?}"); |
| 2361 | } |
| 2362 | } |
| 2363 | } |
| 2364 | |
| 2365 | fn should_disable_laptop_panels(&self, is_lid_closed: bool) -> bool { |
| 2366 | if !is_lid_closed { |
| 2367 | return false; |
| 2368 | } |
| 2369 | |
| 2370 | let config = self.config.borrow(); |
| 2371 | if !config.debug.keep_laptop_panel_on_when_lid_is_closed { |
| 2372 | // Check if any external monitor is connected. |
| 2373 | for device in self.devices.values() { |
| 2374 | for (connector, _crtc) in device.drm_scanner.crtcs() { |
| 2375 | if !is_laptop_panel(&format_connector_name(connector)) { |
| 2376 | return true; |
| 2377 | } |
| 2378 | } |
| 2379 | } |
| 2380 | } |
| 2381 | |
| 2382 | false |
| 2383 | } |
| 2384 | |
| 2385 | pub fn on_output_config_changed(&mut self, niri: &mut Niri) { |
| 2386 | let _span = tracy_client::span!("Tty::on_output_config_changed"); |
| 2387 | |
| 2388 | // If we're inactive, we can't do anything, so just set a flag for later. |
| 2389 | if !self.session.is_active() { |
| 2390 | self.update_output_config_on_resume = true; |
| 2391 | return; |
| 2392 | } |
| 2393 | self.update_output_config_on_resume = false; |
| 2394 | |
| 2395 | // Figure out if we should disable laptop panels. |
| 2396 | let disable_laptop_panels = self.should_disable_laptop_panels(niri.is_lid_closed); |
| 2397 | let should_disable = |connector: &str| disable_laptop_panels && is_laptop_panel(connector); |
| 2398 | |
| 2399 | let mut to_disconnect = vec![]; |
| 2400 | let mut to_connect = vec![]; |
| 2401 | |
| 2402 | for (&node, device) in &mut self.devices { |
| 2403 | for (&crtc, surface) in device.surfaces.iter_mut() { |
| 2404 | let config = self |
| 2405 | .config |
| 2406 | .borrow() |
| 2407 | .outputs |
| 2408 | .find(&surface.name) |
| 2409 | .cloned() |
| 2410 | .unwrap_or_default(); |
| 2411 | if config.off || should_disable(&surface.name.connector) { |
| 2412 | to_disconnect.push((node, crtc)); |
| 2413 | continue; |
| 2414 | } |
| 2415 | |
| 2416 | // Check if we need to change the mode. |
| 2417 | let Some(connector) = device.drm_scanner.connectors().get(&surface.connector) |
| 2418 | else { |
| 2419 | error!("missing enabled connector in drm_scanner"); |
| 2420 | continue; |
| 2421 | }; |
| 2422 | |
| 2423 | let mut mode = None; |
| 2424 | if let Some(modeline) = &config.modeline { |
| 2425 | match calculate_drm_mode_from_modeline(modeline) { |
| 2426 | Ok(x) => mode = Some(x), |
| 2427 | Err(err) => { |
| 2428 | warn!( |
| 2429 | "output {:?}: invalid custom modeline; \ |
| 2430 | falling back to advertised modes: {err:?}", |
| 2431 | surface.name.connector |
| 2432 | ); |
| 2433 | } |
| 2434 | } |
| 2435 | } |
| 2436 | |
| 2437 | let (mode, fallback) = match mode { |
| 2438 | Some(x) => (x, false), |
| 2439 | None => match pick_mode(connector, config.mode) { |
| 2440 | Some(result) => result, |
| 2441 | None => { |
| 2442 | warn!("couldn't pick mode for enabled connector"); |
| 2443 | continue; |
| 2444 | } |
| 2445 | }, |
| 2446 | }; |
| 2447 | |
| 2448 | if let Ok(mut props) = ConnectorProperties::try_new(&device.drm, surface.connector) |
| 2449 | { |
| 2450 | set_connector_properties(&mut props, config.max_bpc, false); |
| 2451 | } else { |
| 2452 | warn!("failed to get connector properties"); |
| 2453 | } |
| 2454 | |
| 2455 | let change_mode = surface.compositor.pending_mode() != mode; |
| 2456 | |
| 2457 | let vrr_enabled = surface.compositor.vrr_enabled(); |
| 2458 | let change_always_vrr = vrr_enabled != config.is_vrr_always_on(); |
| 2459 | let is_on_demand_vrr = config.is_vrr_on_demand(); |
| 2460 | |
| 2461 | if !change_mode && !change_always_vrr && !is_on_demand_vrr { |
| 2462 | continue; |
| 2463 | } |
| 2464 | |
| 2465 | let output = niri |
| 2466 | .global_space |
| 2467 | .outputs() |
| 2468 | .find(|output| { |
| 2469 | let tty_state: &TtyOutputState = output.user_data().get().unwrap(); |
| 2470 | tty_state.node == node && tty_state.crtc == crtc |
| 2471 | }) |
| 2472 | .cloned(); |
| 2473 | let Some(output) = output else { |
| 2474 | error!("missing output for crtc: {crtc:?}"); |
| 2475 | continue; |
| 2476 | }; |
| 2477 | let Some(output_state) = niri.output_state.get_mut(&output) else { |
| 2478 | error!("missing state for output {:?}", surface.name.connector); |
| 2479 | continue; |
| 2480 | }; |
| 2481 | |
| 2482 | if (is_on_demand_vrr && vrr_enabled != output_state.on_demand_vrr_enabled) |
| 2483 | || (!is_on_demand_vrr && change_always_vrr) |
| 2484 | { |
| 2485 | let vrr = !vrr_enabled; |
| 2486 | let word = if vrr { "enabling" } else { "disabling" }; |
| 2487 | if let Err(err) = surface.compositor.use_vrr(vrr) { |
| 2488 | warn!( |
| 2489 | "output {:?}: error {} VRR: {err:?}", |
| 2490 | surface.name.connector, word |
| 2491 | ); |
| 2492 | } |
| 2493 | output_state |
| 2494 | .frame_clock |
| 2495 | .set_vrr(surface.compositor.vrr_enabled()); |
| 2496 | } |
| 2497 | |
| 2498 | if change_mode { |
| 2499 | if fallback { |
| 2500 | let target = config.mode.unwrap(); |
| 2501 | warn!( |
| 2502 | "output {:?}: configured mode {}x{}{} could not be found, \ |
| 2503 | falling back to preferred", |
| 2504 | surface.name.connector, |
| 2505 | target.mode.width, |
| 2506 | target.mode.height, |
| 2507 | if let Some(refresh) = target.mode.refresh { |
| 2508 | format!("@{refresh}") |
| 2509 | } else { |
| 2510 | String::new() |
| 2511 | }, |
| 2512 | ); |
| 2513 | } |
| 2514 | |
| 2515 | debug!( |
| 2516 | "output {:?}: picking mode: {mode:?}", |
| 2517 | surface.name.connector |
| 2518 | ); |
| 2519 | if let Err(err) = surface.compositor.use_mode(mode) { |
| 2520 | warn!("error changing mode: {err:?}"); |
| 2521 | continue; |
| 2522 | } |
| 2523 | |
| 2524 | let wl_mode = Mode::from(mode); |
| 2525 | output.change_current_state(Some(wl_mode), None, None, None); |
| 2526 | output.set_preferred(wl_mode); |
| 2527 | output_state.frame_clock = FrameClock::new( |
| 2528 | Some(refresh_interval(mode)), |
| 2529 | surface.compositor.vrr_enabled(), |
| 2530 | ); |
| 2531 | niri.output_resized(&output); |
| 2532 | } |
| 2533 | } |
| 2534 | |
| 2535 | let config = self.config.borrow(); |
| 2536 | let disable_monitor_names = config.debug.disable_monitor_names; |
| 2537 | |
| 2538 | for (connector, crtc) in device.drm_scanner.crtcs() { |
| 2539 | // Check if connected. |
| 2540 | if connector.state() != connector::State::Connected { |
| 2541 | continue; |
| 2542 | } |
| 2543 | |
| 2544 | // Check if already enabled. |
| 2545 | if device.surfaces.contains_key(&crtc) |
| 2546 | || device |
| 2547 | .non_desktop_connectors |
| 2548 | .contains(&(connector.handle(), crtc)) |
| 2549 | { |
| 2550 | continue; |
| 2551 | } |
| 2552 | |
| 2553 | let output_name = device.known_crtc_name(&crtc, connector, disable_monitor_names); |
| 2554 | |
| 2555 | let config = config |
| 2556 | .outputs |
| 2557 | .find(&output_name) |
| 2558 | .cloned() |
| 2559 | .unwrap_or_default(); |
| 2560 | |
| 2561 | if !(config.off || should_disable(&output_name.connector)) { |
| 2562 | to_connect.push((node, connector.clone(), crtc, output_name)); |
| 2563 | } |
| 2564 | } |
| 2565 | } |
| 2566 | |
| 2567 | for (node, crtc) in to_disconnect { |
| 2568 | self.connector_disconnected(niri, node, crtc); |
| 2569 | } |
| 2570 | |
| 2571 | // Sort by output name to get more predictable first focused output at initial compositor |
| 2572 | // startup, when multiple connectors appear at once. |
| 2573 | to_connect.sort_unstable_by(|a, b| a.3.compare(&b.3)); |
| 2574 | |
| 2575 | for (node, connector, crtc, _name) in to_connect { |
| 2576 | if let Err(err) = self.connector_connected(niri, node, connector, crtc) { |
| 2577 | warn!("error connecting connector: {err:?}"); |
| 2578 | } |
| 2579 | } |
| 2580 | |
| 2581 | self.refresh_ipc_outputs(niri); |
| 2582 | } |
| 2583 | |
| 2584 | pub fn get_device_from_node(&mut self, node: DrmNode) -> Option<&mut OutputDevice> { |
| 2585 | self.devices.get_mut(&node) |
| 2586 | } |
| 2587 | |
| 2588 | pub fn disconnected_connector_name_by_name_match(&self, target: &str) -> Option<OutputName> { |
| 2589 | let disable_monitor_names = self.config.borrow().debug.disable_monitor_names; |
| 2590 | for device in self.devices.values() { |
| 2591 | for (connector, crtc) in device.drm_scanner.crtcs() { |
| 2592 | // Check if connected. |
| 2593 | if connector.state() != connector::State::Connected { |
| 2594 | continue; |
| 2595 | } |
| 2596 | |
| 2597 | // Check if already enabled. |
| 2598 | if device.surfaces.contains_key(&crtc) |
| 2599 | || device |
| 2600 | .non_desktop_connectors |
| 2601 | .contains(&(connector.handle(), crtc)) |
| 2602 | { |
| 2603 | continue; |
| 2604 | } |
| 2605 | |
| 2606 | let output_name = device.known_crtc_name(&crtc, connector, disable_monitor_names); |
| 2607 | if output_name.matches(target) { |
| 2608 | return Some(output_name); |
| 2609 | } |
| 2610 | } |
| 2611 | } |
| 2612 | |
| 2613 | None |
| 2614 | } |
| 2615 | } |
| 2616 | |
| 2617 | impl GammaProps { |
| 2618 | fn new(device: &DrmDevice, crtc: crtc::Handle) -> anyhow::Result<Self> { |
| 2619 | let mut gamma_lut = None; |
| 2620 | let mut gamma_lut_size = None; |
| 2621 | |
| 2622 | let props = device |
| 2623 | .get_properties(crtc) |
| 2624 | .context("error getting properties")?; |
| 2625 | for (prop, _) in props { |
| 2626 | let Ok(info) = device.get_property(prop) else { |
| 2627 | continue; |
| 2628 | }; |
| 2629 | |
| 2630 | let Ok(name) = info.name().to_str() else { |
| 2631 | continue; |
| 2632 | }; |
| 2633 | |
| 2634 | match name { |
| 2635 | "GAMMA_LUT" => { |
| 2636 | ensure!( |
| 2637 | matches!(info.value_type(), property::ValueType::Blob), |
| 2638 | "wrong GAMMA_LUT value type" |
| 2639 | ); |
| 2640 | gamma_lut = Some(prop); |
| 2641 | } |
| 2642 | "GAMMA_LUT_SIZE" => { |
| 2643 | ensure!( |
| 2644 | matches!(info.value_type(), property::ValueType::UnsignedRange(_, _)), |
| 2645 | "wrong GAMMA_LUT_SIZE value type" |
| 2646 | ); |
| 2647 | gamma_lut_size = Some(prop); |
| 2648 | } |
| 2649 | _ => (), |
| 2650 | } |
| 2651 | } |
| 2652 | |
| 2653 | let gamma_lut = gamma_lut.context("missing GAMMA_LUT property")?; |
| 2654 | let gamma_lut_size = gamma_lut_size.context("missing GAMMA_LUT_SIZE property")?; |
| 2655 | |
| 2656 | Ok(Self { |
| 2657 | crtc, |
| 2658 | gamma_lut, |
| 2659 | gamma_lut_size, |
| 2660 | previous_blob: None, |
| 2661 | }) |
| 2662 | } |
| 2663 | |
| 2664 | fn gamma_size(&self, device: &DrmDevice) -> anyhow::Result<u32> { |
| 2665 | let value = get_drm_property(device, self.crtc, self.gamma_lut_size) |
| 2666 | .context("missing GAMMA_LUT_SIZE property")?; |
| 2667 | Ok(value as u32) |
| 2668 | } |
| 2669 | |
| 2670 | fn set_gamma(&mut self, device: &DrmDevice, gamma: Option<&[u16]>) -> anyhow::Result<()> { |
| 2671 | let _span = tracy_client::span!("GammaProps::set_gamma"); |
| 2672 | |
| 2673 | let blob = if let Some(gamma) = gamma { |
| 2674 | let gamma_size = self |
| 2675 | .gamma_size(device) |
| 2676 | .context("error getting gamma size")? as usize; |
| 2677 | |
| 2678 | ensure!(gamma.len() == gamma_size * 3, "wrong gamma length"); |
| 2679 | |
| 2680 | #[allow(non_camel_case_types)] |
| 2681 | #[repr(C)] |
| 2682 | #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] |
| 2683 | pub struct drm_color_lut { |
| 2684 | pub red: u16, |
| 2685 | pub green: u16, |
| 2686 | pub blue: u16, |
| 2687 | pub reserved: u16, |
| 2688 | } |
| 2689 | |
| 2690 | let (red, rest) = gamma.split_at(gamma_size); |
| 2691 | let (blue, green) = rest.split_at(gamma_size); |
| 2692 | let mut data = zip(zip(red, blue), green) |
| 2693 | .map(|((&red, &green), &blue)| drm_color_lut { |
| 2694 | red, |
| 2695 | green, |
| 2696 | blue, |
| 2697 | reserved: 0, |
| 2698 | }) |
| 2699 | .collect::<Vec<_>>(); |
| 2700 | let data = cast_slice_mut(&mut data); |
| 2701 | |
| 2702 | let blob = drm_ffi::mode::create_property_blob(device.as_fd(), data) |
| 2703 | .context("error creating property blob")?; |
| 2704 | NonZeroU64::new(u64::from(blob.blob_id)) |
| 2705 | } else { |
| 2706 | None |
| 2707 | }; |
| 2708 | |
| 2709 | { |
| 2710 | let _span = tracy_client::span!("set_property"); |
| 2711 | |
| 2712 | let blob = blob.map(NonZeroU64::get).unwrap_or(0); |
| 2713 | device |
| 2714 | .set_property( |
| 2715 | self.crtc, |
| 2716 | self.gamma_lut, |
| 2717 | property::Value::Blob(blob).into(), |
| 2718 | ) |
| 2719 | .context("error setting GAMMA_LUT") |
| 2720 | .inspect_err(|_| { |
| 2721 | if blob != 0 { |
| 2722 | // Destroy the blob we just allocated. |
| 2723 | if let Err(err) = device.destroy_property_blob(blob) { |
| 2724 | warn!("error destroying GAMMA_LUT property blob: {err:?}"); |
| 2725 | } |
| 2726 | } |
| 2727 | })?; |
| 2728 | } |
| 2729 | |
| 2730 | if let Some(blob) = mem::replace(&mut self.previous_blob, blob) { |
| 2731 | if let Err(err) = device.destroy_property_blob(blob.get()) { |
| 2732 | warn!("error destroying previous GAMMA_LUT blob: {err:?}"); |
| 2733 | } |
| 2734 | } |
| 2735 | |
| 2736 | Ok(()) |
| 2737 | } |
| 2738 | |
| 2739 | fn restore_gamma(&self, device: &DrmDevice) -> anyhow::Result<()> { |
| 2740 | let _span = tracy_client::span!("GammaProps::restore_gamma"); |
| 2741 | |
| 2742 | let blob = self.previous_blob.map(NonZeroU64::get).unwrap_or(0); |
| 2743 | device |
| 2744 | .set_property( |
| 2745 | self.crtc, |
| 2746 | self.gamma_lut, |
| 2747 | property::Value::Blob(blob).into(), |
| 2748 | ) |
| 2749 | .context("error setting GAMMA_LUT")?; |
| 2750 | |
| 2751 | Ok(()) |
| 2752 | } |
| 2753 | } |
| 2754 | |
| 2755 | fn primary_node_from_render_node(path: &Path) -> Option<(DrmNode, DrmNode)> { |
| 2756 | match DrmNode::from_path(path) { |
| 2757 | Ok(node) => { |
| 2758 | if node.ty() == NodeType::Render { |
| 2759 | match node.node_with_type(NodeType::Primary) { |
| 2760 | Some(Ok(primary_node)) => { |
| 2761 | return Some((primary_node, node)); |
| 2762 | } |
| 2763 | Some(Err(err)) => { |
| 2764 | warn!("error opening primary node for render node {path:?}: {err:?}"); |
| 2765 | } |
| 2766 | None => { |
| 2767 | warn!("error opening primary node for render node {path:?}"); |
| 2768 | } |
| 2769 | } |
| 2770 | } else { |
| 2771 | warn!("DRM node {path:?} is not a render node"); |
| 2772 | |
| 2773 | // Gracefully handle misconfiguration on regular desktop systems. |
| 2774 | if let Some(Ok(render_node)) = node.node_with_type(NodeType::Render) { |
| 2775 | return Some((node, render_node)); |
| 2776 | } |
| 2777 | |
| 2778 | warn!("could not get render node for DRM node {path:?}; proceeding anyway"); |
| 2779 | return Some((node, node)); |
| 2780 | } |
| 2781 | } |
| 2782 | Err(err) => { |
| 2783 | warn!("error opening {path:?} as DRM node: {err:?}"); |
| 2784 | } |
| 2785 | } |
| 2786 | |
| 2787 | None |
| 2788 | } |
| 2789 | |
| 2790 | fn primary_node_from_config(config: &Config) -> Option<(DrmNode, DrmNode)> { |
| 2791 | let path = config.debug.render_drm_device.as_ref()?; |
| 2792 | debug!("attempting to use render node from config: {path:?}"); |
| 2793 | |
| 2794 | primary_node_from_render_node(path) |
| 2795 | } |
| 2796 | |
| 2797 | fn ignored_nodes_from_config(config: &Config) -> HashSet<DrmNode> { |
| 2798 | let mut disabled_nodes = HashSet::new(); |
| 2799 | |
| 2800 | for path in &config.debug.ignored_drm_devices { |
| 2801 | if let Some((primary_node, render_node)) = primary_node_from_render_node(path) { |
| 2802 | disabled_nodes.insert(primary_node); |
| 2803 | disabled_nodes.insert(render_node); |
| 2804 | } |
| 2805 | } |
| 2806 | |
| 2807 | disabled_nodes |
| 2808 | } |
| 2809 | |
| 2810 | fn surface_dmabuf_feedback( |
| 2811 | compositor: &GbmDrmCompositor, |
| 2812 | primary_formats: FormatSet, |
| 2813 | primary_render_node: DrmNode, |
| 2814 | surface_render_node: Option<DrmNode>, |
| 2815 | surface_scanout_node: DrmNode, |
| 2816 | ) -> Result<SurfaceDmabufFeedback, io::Error> { |
| 2817 | let surface = compositor.surface(); |
| 2818 | let planes = surface.planes(); |
| 2819 | |
| 2820 | let primary_plane_formats = surface.plane_info().formats.clone(); |
| 2821 | let primary_or_overlay_plane_formats = primary_plane_formats |
| 2822 | .iter() |
| 2823 | .chain(planes.overlay.iter().flat_map(|p| p.formats.iter())) |
| 2824 | .copied() |
| 2825 | .collect::<FormatSet>(); |
| 2826 | |
| 2827 | // We limit the scan-out trache to formats we can also render from so that there is always a |
| 2828 | // fallback render path available in case the supplied buffer can not be scanned out directly. |
| 2829 | let mut primary_scanout_formats = primary_plane_formats |
| 2830 | .intersection(&primary_formats) |
| 2831 | .copied() |
| 2832 | .collect::<Vec<_>>(); |
| 2833 | let mut primary_or_overlay_scanout_formats = primary_or_overlay_plane_formats |
| 2834 | .intersection(&primary_formats) |
| 2835 | .copied() |
| 2836 | .collect::<Vec<_>>(); |
| 2837 | |
| 2838 | // HACK: AMD iGPU + dGPU systems share some modifiers between the two, and yet cross-device |
| 2839 | // buffers produce a glitched scanout if the modifier is not Linear... |
| 2840 | // |
| 2841 | // Also limit scan-out formats to Linear if we have a device without a render node (i.e. |
| 2842 | // we're rendering on a different device). |
| 2843 | if surface_render_node != Some(primary_render_node) { |
| 2844 | primary_scanout_formats.retain(|f| f.modifier == Modifier::Linear); |
| 2845 | primary_or_overlay_scanout_formats.retain(|f| f.modifier == Modifier::Linear); |
| 2846 | } |
| 2847 | |
| 2848 | let builder = DmabufFeedbackBuilder::new(primary_render_node.dev_id(), primary_formats); |
| 2849 | |
| 2850 | trace!( |
| 2851 | "primary scanout formats: {}, overlay adds: {}", |
| 2852 | primary_scanout_formats.len(), |
| 2853 | primary_or_overlay_scanout_formats.len() - primary_scanout_formats.len(), |
| 2854 | ); |
| 2855 | |
| 2856 | // Prefer the primary-plane-only formats, then primary-or-overlay-plane formats. This will |
| 2857 | // increase the chance of scanning out a client even with our disabled-by-default overlay |
| 2858 | // planes. |
| 2859 | let scanout = builder |
| 2860 | .clone() |
| 2861 | .add_preference_tranche( |
| 2862 | surface_scanout_node.dev_id(), |
| 2863 | TrancheFlags::Scanout, |
| 2864 | primary_scanout_formats, |
| 2865 | 4..=6, |
| 2866 | ) |
| 2867 | .add_preference_tranche( |
| 2868 | surface_scanout_node.dev_id(), |
| 2869 | TrancheFlags::Scanout, |
| 2870 | primary_or_overlay_scanout_formats, |
| 2871 | 4..=6, |
| 2872 | ) |
| 2873 | .build()?; |
| 2874 | |
| 2875 | // If this is the primary node surface, send scanout formats in both tranches to avoid |
| 2876 | // duplication. |
| 2877 | let render = if surface_render_node == Some(primary_render_node) { |
| 2878 | scanout.clone() |
| 2879 | } else { |
| 2880 | builder.build()? |
| 2881 | }; |
| 2882 | |
| 2883 | Ok(SurfaceDmabufFeedback { render, scanout }) |
| 2884 | } |
| 2885 | |
| 2886 | fn find_drm_property( |
| 2887 | drm: &DrmDevice, |
| 2888 | resource: impl ResourceHandle, |
| 2889 | name: &str, |
| 2890 | ) -> Option<(property::Handle, property::Info, property::RawValue)> { |
| 2891 | let props = match drm.get_properties(resource) { |
| 2892 | Ok(props) => props, |
| 2893 | Err(err) => { |
| 2894 | warn!("error getting properties: {err:?}"); |
| 2895 | return None; |
| 2896 | } |
| 2897 | }; |
| 2898 | |
| 2899 | props.into_iter().find_map(|(handle, value)| { |
| 2900 | let info = drm.get_property(handle).ok()?; |
| 2901 | let n = info.name().to_str().ok()?; |
| 2902 | |
| 2903 | (n == name).then_some((handle, info, value)) |
| 2904 | }) |
| 2905 | } |
| 2906 | |
| 2907 | fn get_drm_property( |
| 2908 | drm: &DrmDevice, |
| 2909 | resource: impl ResourceHandle, |
| 2910 | prop: property::Handle, |
| 2911 | ) -> Option<property::RawValue> { |
| 2912 | let props = match drm.get_properties(resource) { |
| 2913 | Ok(props) => props, |
| 2914 | Err(err) => { |
| 2915 | warn!("error getting properties: {err:?}"); |
| 2916 | return None; |
| 2917 | } |
| 2918 | }; |
| 2919 | |
| 2920 | props |
| 2921 | .into_iter() |
| 2922 | .find_map(|(handle, value)| (handle == prop).then_some(value)) |
| 2923 | } |
| 2924 | |
| 2925 | fn refresh_interval(mode: DrmMode) -> Duration { |
| 2926 | let clock = mode.clock() as u64; |
| 2927 | let htotal = mode.hsync().2 as u64; |
| 2928 | let vtotal = mode.vsync().2 as u64; |
| 2929 | |
| 2930 | let mut numerator = htotal * vtotal * 1_000_000; |
| 2931 | let mut denominator = clock; |
| 2932 | |
| 2933 | if mode.flags().contains(ModeFlags::INTERLACE) { |
| 2934 | denominator *= 2; |
| 2935 | } |
| 2936 | |
| 2937 | if mode.flags().contains(ModeFlags::DBLSCAN) { |
| 2938 | numerator *= 2; |
| 2939 | } |
| 2940 | |
| 2941 | if mode.vscan() > 1 { |
| 2942 | numerator *= mode.vscan() as u64; |
| 2943 | } |
| 2944 | |
| 2945 | let refresh_interval = (numerator + denominator / 2) / denominator; |
| 2946 | Duration::from_nanos(refresh_interval) |
| 2947 | } |
| 2948 | |
| 2949 | #[cfg(feature = "dbus")] |
| 2950 | fn suspend() -> anyhow::Result<()> { |
| 2951 | let conn = zbus::blocking::Connection::system().context("error connecting to system bus")?; |
| 2952 | |
| 2953 | conn.call_method( |
| 2954 | Some("org.freedesktop.login1"), |
| 2955 | "/org/freedesktop/login1", |
| 2956 | Some("org.freedesktop.login1.Manager"), |
| 2957 | "Suspend", |
| 2958 | &(true), |
| 2959 | ) |
| 2960 | .context("error suspending")?; |
| 2961 | |
| 2962 | Ok(()) |
| 2963 | } |
| 2964 | |
| 2965 | fn queue_estimated_vblank_timer( |
| 2966 | niri: &mut Niri, |
| 2967 | output: Output, |
| 2968 | target_presentation_time: Duration, |
| 2969 | ) { |
| 2970 | let output_state = niri.output_state.get_mut(&output).unwrap(); |
| 2971 | match mem::take(&mut output_state.redraw_state) { |
| 2972 | RedrawState::Idle => unreachable!(), |
| 2973 | RedrawState::Queued => (), |
| 2974 | RedrawState::WaitingForVBlank { .. } => unreachable!(), |
| 2975 | RedrawState::WaitingForEstimatedVBlank(token) |
| 2976 | | RedrawState::WaitingForEstimatedVBlankAndQueued(token) => { |
| 2977 | output_state.redraw_state = RedrawState::WaitingForEstimatedVBlank(token); |
| 2978 | return; |
| 2979 | } |
| 2980 | } |
| 2981 | |
| 2982 | let now = get_monotonic_time(); |
| 2983 | let mut duration = target_presentation_time.saturating_sub(now); |
| 2984 | |
| 2985 | // No use setting a zero timer, since we'll send frame callbacks anyway right after the call to |
| 2986 | // render(). This can happen for example with unknown presentation time from DRM. |
| 2987 | if duration.is_zero() { |
| 2988 | duration += output_state |
| 2989 | .frame_clock |
| 2990 | .refresh_interval() |
| 2991 | // Unknown refresh interval, i.e. winit backend. Would be good to estimate it somehow |
| 2992 | // but it's not that important for this code path. |
| 2993 | .unwrap_or(Duration::from_micros(16_667)); |
| 2994 | } |
| 2995 | |
| 2996 | trace!("queueing estimated vblank timer to fire in {duration:?}"); |
| 2997 | |
| 2998 | let timer = Timer::from_duration(duration); |
| 2999 | let token = niri |
| 3000 | .event_loop |
| 3001 | .insert_source(timer, move |_, _, data| { |
| 3002 | data.backend |
| 3003 | .tty() |
| 3004 | .on_estimated_vblank_timer(&mut data.niri, output.clone()); |
| 3005 | TimeoutAction::Drop |
| 3006 | }) |
| 3007 | .unwrap(); |
| 3008 | output_state.redraw_state = RedrawState::WaitingForEstimatedVBlank(token); |
| 3009 | } |
| 3010 | |
| 3011 | pub fn calculate_drm_mode_from_modeline(modeline: &Modeline) -> anyhow::Result<DrmMode> { |
| 3012 | ensure!( |
| 3013 | modeline.hdisplay < modeline.hsync_start, |
| 3014 | "hdisplay {} must be < hsync_start {}", |
| 3015 | modeline.hdisplay, |
| 3016 | modeline.hsync_start |
| 3017 | ); |
| 3018 | ensure!( |
| 3019 | modeline.hsync_start < modeline.hsync_end, |
| 3020 | "hsync_start {} must be < hsync_end {}", |
| 3021 | modeline.hsync_start, |
| 3022 | modeline.hsync_end |
| 3023 | ); |
| 3024 | ensure!( |
| 3025 | modeline.hsync_end < modeline.htotal, |
| 3026 | "hsync_end {} must be < htotal {}", |
| 3027 | modeline.hsync_end, |
| 3028 | modeline.htotal |
| 3029 | ); |
| 3030 | ensure!( |
| 3031 | modeline.vdisplay < modeline.vsync_start, |
| 3032 | "vdisplay {} must be < vsync_start {}", |
| 3033 | modeline.vdisplay, |
| 3034 | modeline.vsync_start |
| 3035 | ); |
| 3036 | ensure!( |
| 3037 | modeline.vsync_start < modeline.vsync_end, |
| 3038 | "vsync_start {} must be < vsync_end {}", |
| 3039 | modeline.vsync_start, |
| 3040 | modeline.vsync_end |
| 3041 | ); |
| 3042 | ensure!( |
| 3043 | modeline.vsync_end < modeline.vtotal, |
| 3044 | "vsync_end {} must be < vtotal {}", |
| 3045 | modeline.vsync_end, |
| 3046 | modeline.vtotal |
| 3047 | ); |
| 3048 | |
| 3049 | let pixel_clock_kilo_hertz = modeline.clock * 1000.0; |
| 3050 | // Calculated as documented in the CVT 1.2 standard: |
| 3051 | // https://app.box.com/s/vcocw3z73ta09txiskj7cnk6289j356b/file/93518784646 |
| 3052 | let vrefresh_hertz = (pixel_clock_kilo_hertz * 1000.0) |
| 3053 | / (modeline.htotal as u64 * modeline.vtotal as u64) as f64; |
| 3054 | ensure!( |
| 3055 | vrefresh_hertz.is_finite(), |
| 3056 | "calculated refresh rate is not finite" |
| 3057 | ); |
| 3058 | let vrefresh_rounded = vrefresh_hertz.round() as u32; |
| 3059 | |
| 3060 | let flags = match modeline.hsync_polarity { |
| 3061 | HSyncPolarity::PHSync => ModeFlags::PHSYNC, |
| 3062 | HSyncPolarity::NHSync => ModeFlags::NHSYNC, |
| 3063 | } | match modeline.vsync_polarity { |
| 3064 | VSyncPolarity::PVSync => ModeFlags::PVSYNC, |
| 3065 | VSyncPolarity::NVSync => ModeFlags::NVSYNC, |
| 3066 | }; |
| 3067 | |
| 3068 | let mode_name = format!( |
| 3069 | "{}x{}@{:.2}", |
| 3070 | modeline.hdisplay, modeline.vdisplay, vrefresh_hertz |
| 3071 | ); |
| 3072 | let name = modeinfo_name_slice_from_string(&mode_name); |
| 3073 | |
| 3074 | // https://www.kernel.org/doc/html/v6.17/gpu/drm-uapi.html#c.drm_mode_modeinfo |
| 3075 | Ok(DrmMode::from(drm_mode_modeinfo { |
| 3076 | clock: pixel_clock_kilo_hertz.round() as u32, |
| 3077 | hdisplay: modeline.hdisplay, |
| 3078 | hsync_start: modeline.hsync_start, |
| 3079 | hsync_end: modeline.hsync_end, |
| 3080 | htotal: modeline.htotal, |
| 3081 | vdisplay: modeline.vdisplay, |
| 3082 | vsync_start: modeline.vsync_start, |
| 3083 | vsync_end: modeline.vsync_end, |
| 3084 | vtotal: modeline.vtotal, |
| 3085 | vrefresh: vrefresh_rounded, |
| 3086 | flags: flags.bits(), |
| 3087 | name, |
| 3088 | // Defaults |
| 3089 | type_: drm_ffi::DRM_MODE_TYPE_USERDEF, |
| 3090 | hskew: 0, |
| 3091 | vscan: 0, |
| 3092 | })) |
| 3093 | } |
| 3094 | |
| 3095 | pub fn calculate_mode_cvt(width: u16, height: u16, refresh: f64) -> DrmMode { |
| 3096 | // Cross-checked with sway's implementation: |
| 3097 | // https://gitlab.freedesktop.org/wlroots/wlroots/-/blob/22528542970687720556035790212df8d9bb30bb/backend/drm/util.c#L251 |
| 3098 | |
| 3099 | let options = libdisplay_info::cvt::Options { |
| 3100 | red_blank_ver: libdisplay_info::cvt::ReducedBlankingVersion::None, |
| 3101 | h_pixels: width as i32, |
| 3102 | v_lines: height as i32, |
| 3103 | ip_freq_rqd: refresh, |
| 3104 | |
| 3105 | // Defaults |
| 3106 | video_opt: false, |
| 3107 | vblank: 0f64, |
| 3108 | additional_hblank: 0, |
| 3109 | early_vsync_rqd: false, |
| 3110 | int_rqd: false, |
| 3111 | margins_rqd: false, |
| 3112 | }; |
| 3113 | let cvt_timing = libdisplay_info::cvt::Timing::compute(options); |
| 3114 | |
| 3115 | let hsync_start = width + cvt_timing.h_front_porch as u16; |
| 3116 | let vsync_start = (cvt_timing.v_lines_rnd + cvt_timing.v_front_porch) as u16; |
| 3117 | let hsync_end = hsync_start + cvt_timing.h_sync as u16; |
| 3118 | let vsync_end = vsync_start + cvt_timing.v_sync as u16; |
| 3119 | |
| 3120 | let htotal = hsync_end + cvt_timing.h_back_porch as u16; |
| 3121 | let vtotal = vsync_end + cvt_timing.v_back_porch as u16; |
| 3122 | |
| 3123 | let clock = f64::round(cvt_timing.act_pixel_freq * 1000f64) as u32; |
| 3124 | let vrefresh = f64::round(cvt_timing.act_frame_rate) as u32; |
| 3125 | |
| 3126 | let flags = drm_ffi::DRM_MODE_FLAG_NHSYNC | drm_ffi::DRM_MODE_FLAG_PVSYNC; |
| 3127 | |
| 3128 | let mode_name = format!("{width}x{height}@{:.2}", cvt_timing.act_frame_rate); |
| 3129 | let name = modeinfo_name_slice_from_string(&mode_name); |
| 3130 | |
| 3131 | let drm_ffi_mode = drm_ffi::drm_sys::drm_mode_modeinfo { |
| 3132 | clock, |
| 3133 | |
| 3134 | hdisplay: width, |
| 3135 | hsync_start, |
| 3136 | hsync_end, |
| 3137 | htotal, |
| 3138 | |
| 3139 | vdisplay: height, |
| 3140 | vsync_start, |
| 3141 | vsync_end, |
| 3142 | vtotal, |
| 3143 | |
| 3144 | vrefresh, |
| 3145 | |
| 3146 | flags, |
| 3147 | type_: drm_ffi::DRM_MODE_TYPE_USERDEF, |
| 3148 | name, |
| 3149 | |
| 3150 | // Defaults |
| 3151 | hskew: 0, |
| 3152 | vscan: 0, |
| 3153 | }; |
| 3154 | |
| 3155 | DrmMode::from(drm_ffi_mode) |
| 3156 | } |
| 3157 | |
| 3158 | // Returns a c-string of maximally 31 Rust string chars + null terminator. Excess characters are |
| 3159 | // dropped. |
| 3160 | fn modeinfo_name_slice_from_string(mode_name: &str) -> [core::ffi::c_char; 32] { |
| 3161 | let mut name: [core::ffi::c_char; 32] = [0; 32]; |
| 3162 | |
| 3163 | for (a, b) in zip(&mut name[..31], mode_name.as_bytes()) { |
| 3164 | // Can be u8 on aarch64 and i8 on x86_64. |
| 3165 | *a = *b as _; |
| 3166 | } |
| 3167 | |
| 3168 | name |
| 3169 | } |
| 3170 | |
| 3171 | fn pick_mode( |
| 3172 | connector: &connector::Info, |
| 3173 | target: Option<niri_config::output::Mode>, |
| 3174 | ) -> Option<(control::Mode, bool)> { |
| 3175 | let mut mode = None; |
| 3176 | let mut fallback = false; |
| 3177 | |
| 3178 | if let Some(target) = target { |
| 3179 | let target_mode = target.mode; |
| 3180 | |
| 3181 | if target.custom { |
| 3182 | if let Some(refresh) = target_mode.refresh { |
| 3183 | let custom_mode = |
| 3184 | calculate_mode_cvt(target_mode.width, target_mode.height, refresh); |
| 3185 | return Some((custom_mode, false)); |
| 3186 | } else { |
| 3187 | warn!("ignoring custom mode without refresh rate"); |
| 3188 | } |
| 3189 | } |
| 3190 | |
| 3191 | let refresh = target_mode.refresh.map(|r| (r * 1000.).round() as i32); |
| 3192 | for m in connector.modes() { |
| 3193 | if m.size() != (target.mode.width, target.mode.height) { |
| 3194 | continue; |
| 3195 | } |
| 3196 | |
| 3197 | // Interlaced modes don't appear to work. |
| 3198 | if m.flags().contains(ModeFlags::INTERLACE) { |
| 3199 | continue; |
| 3200 | } |
| 3201 | |
| 3202 | if let Some(refresh) = refresh { |
| 3203 | // If refresh is set, only pick modes with matching refresh. |
| 3204 | let wl_mode = Mode::from(*m); |
| 3205 | if wl_mode.refresh == refresh { |
| 3206 | mode = Some(m); |
| 3207 | } |
| 3208 | } else if let Some(curr) = mode { |
| 3209 | // If refresh isn't set, pick the mode with the highest refresh. |
| 3210 | if curr.vrefresh() < m.vrefresh() { |
| 3211 | mode = Some(m); |
| 3212 | } |
| 3213 | } else { |
| 3214 | mode = Some(m); |
| 3215 | } |
| 3216 | } |
| 3217 | |
| 3218 | if mode.is_none() { |
| 3219 | fallback = true; |
| 3220 | } |
| 3221 | } |
| 3222 | |
| 3223 | if mode.is_none() { |
| 3224 | // Pick a preferred mode. |
| 3225 | for m in connector.modes() { |
| 3226 | if !m.mode_type().contains(ModeTypeFlags::PREFERRED) { |
| 3227 | continue; |
| 3228 | } |
| 3229 | |
| 3230 | if let Some(curr) = mode { |
| 3231 | if curr.vrefresh() < m.vrefresh() { |
| 3232 | mode = Some(m); |
| 3233 | } |
| 3234 | } else { |
| 3235 | mode = Some(m); |
| 3236 | } |
| 3237 | } |
| 3238 | } |
| 3239 | |
| 3240 | if mode.is_none() { |
| 3241 | // Last attempt. |
| 3242 | mode = connector.modes().first(); |
| 3243 | } |
| 3244 | |
| 3245 | mode.map(|m| (*m, fallback)) |
| 3246 | } |
| 3247 | |
| 3248 | fn get_edid_info( |
| 3249 | device: &DrmDevice, |
| 3250 | connector: connector::Handle, |
| 3251 | ) -> anyhow::Result<libdisplay_info::info::Info> { |
| 3252 | let (_, info, value) = |
| 3253 | find_drm_property(device, connector, "EDID").context("no EDID property")?; |
| 3254 | let blob = info |
| 3255 | .value_type() |
| 3256 | .convert_value(value) |
| 3257 | .as_blob() |
| 3258 | .context("EDID was not blob type")?; |
| 3259 | let data = device |
| 3260 | .get_property_blob(blob) |
| 3261 | .context("error getting EDID blob value")?; |
| 3262 | libdisplay_info::info::Info::parse_edid(&data).context("error parsing EDID") |
| 3263 | } |
| 3264 | |
| 3265 | impl<'a> ConnectorProperties<'a> { |
| 3266 | fn try_new(device: &'a DrmDevice, connector: connector::Handle) -> anyhow::Result<Self> { |
| 3267 | let prop_vals = device |
| 3268 | .get_properties(connector) |
| 3269 | .context("error getting properties")?; |
| 3270 | |
| 3271 | let mut properties = Vec::new(); |
| 3272 | |
| 3273 | for (prop, value) in prop_vals { |
| 3274 | let info = device |
| 3275 | .get_property(prop) |
| 3276 | .context("error getting property")?; |
| 3277 | |
| 3278 | properties.push((info, value)); |
| 3279 | } |
| 3280 | |
| 3281 | Ok(Self { |
| 3282 | device, |
| 3283 | connector, |
| 3284 | properties, |
| 3285 | has_change: false, |
| 3286 | requests: AtomicModeReq::new(), |
| 3287 | }) |
| 3288 | } |
| 3289 | |
| 3290 | fn find(&self, name: &std::ffi::CStr) -> anyhow::Result<&(property::Info, property::RawValue)> { |
| 3291 | for prop in &self.properties { |
| 3292 | if prop.0.name() == name { |
| 3293 | return Ok(prop); |
| 3294 | } |
| 3295 | } |
| 3296 | |
| 3297 | Err(anyhow!("couldn't find property: {name:?}")) |
| 3298 | } |
| 3299 | |
| 3300 | fn get_panel_orientation(&self) -> anyhow::Result<Transform> { |
| 3301 | let (info, value) = self.find(c"panel orientation")?; |
| 3302 | match info.value_type().convert_value(*value) { |
| 3303 | property::Value::Enum(Some(val)) => match val.value() { |
| 3304 | // "Normal" |
| 3305 | 0 => Ok(Transform::Normal), |
| 3306 | // "Upside Down" |
| 3307 | 1 => Ok(Transform::_180), |
| 3308 | // "Left Side Up" |
| 3309 | 2 => Ok(Transform::_90), |
| 3310 | // "Right Side Up" |
| 3311 | 3 => Ok(Transform::_270), |
| 3312 | _ => bail!("panel orientation has invalid value: {:?}", val), |
| 3313 | }, |
| 3314 | _ => bail!("panel orientation has wrong value type"), |
| 3315 | } |
| 3316 | } |
| 3317 | |
| 3318 | fn reset_hdr(&mut self) -> anyhow::Result<()> { |
| 3319 | const DRM_MODE_COLORIMETRY_DEFAULT: u64 = 0; |
| 3320 | |
| 3321 | let (info, value) = self.find(c"HDR_OUTPUT_METADATA")?; |
| 3322 | |
| 3323 | let property::ValueType::Blob = info.value_type() else { |
| 3324 | bail!("wrong property type") |
| 3325 | }; |
| 3326 | if *value != 0 { |
| 3327 | self.requests |
| 3328 | .add_raw_property(self.connector.into(), info.handle(), 0); |
| 3329 | self.has_change = true; |
| 3330 | } |
| 3331 | |
| 3332 | let (info, value) = self.find(c"Colorspace")?; |
| 3333 | let property::ValueType::Enum(_) = info.value_type() else { |
| 3334 | bail!("wrong property type") |
| 3335 | }; |
| 3336 | if *value != DRM_MODE_COLORIMETRY_DEFAULT { |
| 3337 | self.requests.add_raw_property( |
| 3338 | self.connector.into(), |
| 3339 | info.handle(), |
| 3340 | DRM_MODE_COLORIMETRY_DEFAULT, |
| 3341 | ); |
| 3342 | self.has_change = true; |
| 3343 | } |
| 3344 | |
| 3345 | Ok(()) |
| 3346 | } |
| 3347 | |
| 3348 | fn set_max_bpc(&mut self, max_bpc: MaxBpc) -> anyhow::Result<u64> { |
| 3349 | let (info, value) = self.find(c"max bpc")?; |
| 3350 | |
| 3351 | let property::ValueType::UnsignedRange(min, max) = info.value_type() else { |
| 3352 | bail!("wrong property type") |
| 3353 | }; |
| 3354 | |
| 3355 | let max_bpc = max_bpc.0 as u64; |
| 3356 | if !(min..=max).contains(&max_bpc) { |
| 3357 | bail!("max-bpc {max_bpc} outside valid range of [{min}, {max}]"); |
| 3358 | } |
| 3359 | |
| 3360 | let property::Value::UnsignedRange(value) = info.value_type().convert_value(*value) else { |
| 3361 | bail!("wrong property type") |
| 3362 | }; |
| 3363 | |
| 3364 | if value != max_bpc { |
| 3365 | self.requests.add_raw_property( |
| 3366 | self.connector.into(), |
| 3367 | info.handle(), |
| 3368 | property::Value::UnsignedRange(max_bpc).into(), |
| 3369 | ); |
| 3370 | self.has_change = true; |
| 3371 | } |
| 3372 | |
| 3373 | Ok(max_bpc) |
| 3374 | } |
| 3375 | |
| 3376 | fn commit(&mut self) -> anyhow::Result<()> { |
| 3377 | if self.has_change { |
| 3378 | self.device.atomic_commit( |
| 3379 | AtomicCommitFlags::ALLOW_MODESET, |
| 3380 | std::mem::take(&mut self.requests), |
| 3381 | )?; |
| 3382 | } |
| 3383 | |
| 3384 | Ok(()) |
| 3385 | } |
| 3386 | } |
| 3387 | |
| 3388 | fn set_connector_properties( |
| 3389 | props: &mut ConnectorProperties, |
| 3390 | max_bpc: Option<MaxBpc>, |
| 3391 | reset_hdr: bool, |
| 3392 | ) { |
| 3393 | if let Some(max_bpc) = max_bpc { |
| 3394 | if let Err(err) = props.set_max_bpc(max_bpc) { |
| 3395 | debug!("failed to set `max bpc` property: {err}"); |
| 3396 | } |
| 3397 | } |
| 3398 | |
| 3399 | if reset_hdr { |
| 3400 | if let Err(err) = props.reset_hdr() { |
| 3401 | debug!("failed to set HDR properties: {err}"); |
| 3402 | } |
| 3403 | } |
| 3404 | |
| 3405 | if let Err(err) = props.commit() { |
| 3406 | warn!("failed to atomically commit properties: {err}"); |
| 3407 | } |
| 3408 | } |
| 3409 | |
| 3410 | fn is_vrr_capable(device: &DrmDevice, connector: connector::Handle) -> Option<bool> { |
| 3411 | let (_, info, value) = find_drm_property(device, connector, "vrr_capable")?; |
| 3412 | info.value_type().convert_value(value).as_boolean() |
| 3413 | } |
| 3414 | |
| 3415 | pub fn set_gamma_for_crtc( |
| 3416 | device: &DrmDevice, |
| 3417 | crtc: crtc::Handle, |
| 3418 | ramp: Option<&[u16]>, |
| 3419 | ) -> anyhow::Result<()> { |
| 3420 | let _span = tracy_client::span!("set_gamma_for_crtc"); |
| 3421 | |
| 3422 | let info = device.get_crtc(crtc).context("error getting crtc info")?; |
| 3423 | let gamma_length = info.gamma_length() as usize; |
| 3424 | |
| 3425 | ensure!(gamma_length != 0, "setting gamma is not supported"); |
| 3426 | |
| 3427 | let mut temp; |
| 3428 | let ramp = if let Some(ramp) = ramp { |
| 3429 | ensure!(ramp.len() == gamma_length * 3, "wrong gamma length"); |
| 3430 | ramp |
| 3431 | } else { |
| 3432 | let _span = tracy_client::span!("generate linear gamma"); |
| 3433 | |
| 3434 | // The legacy API provides no way to reset the gamma, so set a linear one manually. |
| 3435 | temp = vec![0u16; gamma_length * 3]; |
| 3436 | |
| 3437 | let (red, rest) = temp.split_at_mut(gamma_length); |
| 3438 | let (green, blue) = rest.split_at_mut(gamma_length); |
| 3439 | let denom = gamma_length as u64 - 1; |
| 3440 | for (i, ((r, g), b)) in zip(zip(red, green), blue).enumerate() { |
| 3441 | let value = (0xFFFFu64 * i as u64 / denom) as u16; |
| 3442 | *r = value; |
| 3443 | *g = value; |
| 3444 | *b = value; |
| 3445 | } |
| 3446 | |
| 3447 | &temp |
| 3448 | }; |
| 3449 | |
| 3450 | let (red, ramp) = ramp.split_at(gamma_length); |
| 3451 | let (green, blue) = ramp.split_at(gamma_length); |
| 3452 | |
| 3453 | device |
| 3454 | .set_gamma(crtc, red, green, blue) |
| 3455 | .context("error setting gamma")?; |
| 3456 | |
| 3457 | Ok(()) |
| 3458 | } |
| 3459 | |
| 3460 | fn format_connector_name(connector: &connector::Info) -> String { |
| 3461 | format!( |
| 3462 | "{}-{}", |
| 3463 | connector.interface().as_str(), |
| 3464 | connector.interface_id(), |
| 3465 | ) |
| 3466 | } |
| 3467 | |
| 3468 | fn make_output_name( |
| 3469 | device: &DrmDevice, |
| 3470 | connector: connector::Handle, |
| 3471 | connector_name: String, |
| 3472 | ) -> OutputName { |
| 3473 | let info = get_edid_info(device, connector) |
| 3474 | .map_err(|err| warn!("error getting EDID info for {connector_name}: {err:?}")) |
| 3475 | .ok(); |
| 3476 | OutputName { |
| 3477 | connector: connector_name, |
| 3478 | make: info.as_ref().and_then(|info| info.make()), |
| 3479 | model: info.as_ref().and_then(|info| info.model()), |
| 3480 | serial: info.as_ref().and_then(|info| info.serial()), |
| 3481 | } |
| 3482 | } |
| 3483 | |
| 3484 | /// Initializes the libinput plugin system. |
| 3485 | /// |
| 3486 | /// # Safety |
| 3487 | /// |
| 3488 | /// This function must be called before libinput iterates through the devices, i.e. before |
| 3489 | /// libinput_udev_assign_seat() or the first call to libinput_path_add_device(). |
| 3490 | unsafe fn init_libinput_plugin_system(libinput: &Libinput) { |
| 3491 | #[cfg(have_libinput_plugin_system)] |
| 3492 | unsafe { |
| 3493 | use std::ffi::{c_char, c_int, CString}; |
| 3494 | use std::os::unix::ffi::OsStringExt; |
| 3495 | |
| 3496 | use directories::BaseDirs; |
| 3497 | use input::ffi::libinput; |
| 3498 | use input::AsRaw as _; |
| 3499 | |
| 3500 | extern "C" { |
| 3501 | fn libinput_plugin_system_append_path(libinput: *const libinput, path: *const c_char); |
| 3502 | fn libinput_plugin_system_append_default_paths(libinput: *const libinput); |
| 3503 | fn libinput_plugin_system_load_plugins( |
| 3504 | libinput: *const libinput, |
| 3505 | flags: c_int, |
| 3506 | ) -> c_int; |
| 3507 | } |
| 3508 | const LIBINPUT_PLUGIN_SYSTEM_FLAG_NONE: c_int = 0; |
| 3509 | let libinput = libinput.as_raw(); |
| 3510 | |
| 3511 | // Also load plugins from $XDG_CONFIG_HOME/libinput/plugins. |
| 3512 | if let Some(dirs) = BaseDirs::new() { |
| 3513 | let mut plugins_dir = dirs.config_dir().to_path_buf(); |
| 3514 | plugins_dir.push("libinput"); |
| 3515 | plugins_dir.push("plugins"); |
| 3516 | if let Ok(plugins_dir) = CString::new(plugins_dir.into_os_string().into_vec()) { |
| 3517 | libinput_plugin_system_append_path(libinput, plugins_dir.as_ptr()); |
| 3518 | } |
| 3519 | } |
| 3520 | |
| 3521 | libinput_plugin_system_append_default_paths(libinput); |
| 3522 | libinput_plugin_system_load_plugins(libinput, LIBINPUT_PLUGIN_SYSTEM_FLAG_NONE); |
| 3523 | } |
| 3524 | #[cfg(not(have_libinput_plugin_system))] |
| 3525 | let _ = libinput; |
| 3526 | } |
| 3527 | |
| 3528 | #[cfg(test)] |
| 3529 | mod tests { |
| 3530 | use insta::assert_debug_snapshot; |
| 3531 | use niri_config::output::Modeline; |
| 3532 | use niri_ipc::{HSyncPolarity, VSyncPolarity}; |
| 3533 | |
| 3534 | use crate::backend::tty::{calculate_drm_mode_from_modeline, calculate_mode_cvt}; |
| 3535 | |
| 3536 | #[test] |
| 3537 | fn test_calculate_drmmode_from_modeline() { |
| 3538 | let modeline1 = Modeline { |
| 3539 | clock: 173.0, |
| 3540 | hdisplay: 1920, |
| 3541 | vdisplay: 1080, |
| 3542 | hsync_start: 2048, |
| 3543 | hsync_end: 2248, |
| 3544 | htotal: 2576, |
| 3545 | vsync_start: 1083, |
| 3546 | vsync_end: 1088, |
| 3547 | vtotal: 1120, |
| 3548 | hsync_polarity: HSyncPolarity::NHSync, |
| 3549 | vsync_polarity: VSyncPolarity::PVSync, |
| 3550 | }; |
| 3551 | assert_debug_snapshot!(calculate_drm_mode_from_modeline(&modeline1).unwrap(), @r#" |
| 3552 | Mode { |
| 3553 | name: "1920x1080@59.96", |
| 3554 | clock: 173000, |
| 3555 | size: ( |
| 3556 | 1920, |
| 3557 | 1080, |
| 3558 | ), |
| 3559 | hsync: ( |
| 3560 | 2048, |
| 3561 | 2248, |
| 3562 | 2576, |
| 3563 | ), |
| 3564 | vsync: ( |
| 3565 | 1083, |
| 3566 | 1088, |
| 3567 | 1120, |
| 3568 | ), |
| 3569 | hskew: 0, |
| 3570 | vscan: 0, |
| 3571 | vrefresh: 60, |
| 3572 | mode_type: ModeTypeFlags( |
| 3573 | USERDEF, |
| 3574 | ), |
| 3575 | } |
| 3576 | "#); |
| 3577 | let modeline2 = Modeline { |
| 3578 | clock: 452.5, |
| 3579 | hdisplay: 1920, |
| 3580 | vdisplay: 1080, |
| 3581 | hsync_start: 2088, |
| 3582 | hsync_end: 2296, |
| 3583 | htotal: 2672, |
| 3584 | vsync_start: 1083, |
| 3585 | vsync_end: 1088, |
| 3586 | vtotal: 1177, |
| 3587 | hsync_polarity: HSyncPolarity::NHSync, |
| 3588 | vsync_polarity: VSyncPolarity::PVSync, |
| 3589 | }; |
| 3590 | assert_debug_snapshot!(calculate_drm_mode_from_modeline(&modeline2).unwrap(), @r#" |
| 3591 | Mode { |
| 3592 | name: "1920x1080@143.88", |
| 3593 | clock: 452500, |
| 3594 | size: ( |
| 3595 | 1920, |
| 3596 | 1080, |
| 3597 | ), |
| 3598 | hsync: ( |
| 3599 | 2088, |
| 3600 | 2296, |
| 3601 | 2672, |
| 3602 | ), |
| 3603 | vsync: ( |
| 3604 | 1083, |
| 3605 | 1088, |
| 3606 | 1177, |
| 3607 | ), |
| 3608 | hskew: 0, |
| 3609 | vscan: 0, |
| 3610 | vrefresh: 144, |
| 3611 | mode_type: ModeTypeFlags( |
| 3612 | USERDEF, |
| 3613 | ), |
| 3614 | } |
| 3615 | "#); |
| 3616 | } |
| 3617 | |
| 3618 | #[test] |
| 3619 | fn test_calc_cvt() { |
| 3620 | // Crosschecked with other calculators like the cvt commandline utility. |
| 3621 | assert_debug_snapshot!(calculate_mode_cvt(1920, 1080, 60.0), @r#" |
| 3622 | Mode { |
| 3623 | name: "1920x1080@59.96", |
| 3624 | clock: 173000, |
| 3625 | size: ( |
| 3626 | 1920, |
| 3627 | 1080, |
| 3628 | ), |
| 3629 | hsync: ( |
| 3630 | 2048, |
| 3631 | 2248, |
| 3632 | 2576, |
| 3633 | ), |
| 3634 | vsync: ( |
| 3635 | 1083, |
| 3636 | 1088, |
| 3637 | 1120, |
| 3638 | ), |
| 3639 | hskew: 0, |
| 3640 | vscan: 0, |
| 3641 | vrefresh: 60, |
| 3642 | mode_type: ModeTypeFlags( |
| 3643 | USERDEF, |
| 3644 | ), |
| 3645 | } |
| 3646 | "#); |
| 3647 | assert_debug_snapshot!(calculate_mode_cvt(1920, 1080, 144.0), @r#" |
| 3648 | Mode { |
| 3649 | name: "1920x1080@143.88", |
| 3650 | clock: 452500, |
| 3651 | size: ( |
| 3652 | 1920, |
| 3653 | 1080, |
| 3654 | ), |
| 3655 | hsync: ( |
| 3656 | 2088, |
| 3657 | 2296, |
| 3658 | 2672, |
| 3659 | ), |
| 3660 | vsync: ( |
| 3661 | 1083, |
| 3662 | 1088, |
| 3663 | 1177, |
| 3664 | ), |
| 3665 | hskew: 0, |
| 3666 | vscan: 0, |
| 3667 | vrefresh: 144, |
| 3668 | mode_type: ModeTypeFlags( |
| 3669 | USERDEF, |
| 3670 | ), |
| 3671 | } |
| 3672 | "#); |
| 3673 | } |
| 3674 | } |