forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB64a9351Ivan Molodetskikh2 years ago1319 commits

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