-
Notifications
You must be signed in to change notification settings - Fork 366
Expand file tree
/
Copy pathmod.rs
More file actions
4598 lines (4163 loc) · 173 KB
/
Copy pathmod.rs
File metadata and controls
4598 lines (4163 loc) · 173 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Composition for [`Element`]s using drm planes
//!
//! When possible composition can be (partially) offloaded to the display driver by assigning
//! elements to drm planes. This is especially important for latency intensive fullscreen clients
//! like video renderers or games.
//!
//! The [`DrmCompositor`] does so by walking the stack of provided [`Element`]s from front to back
//! while trying to assign each element to a drm overlay plane. Each item that fails the plane test
//! will be rendered on the primary plane using the provided [`Renderer`].
//! Additionally it will try to assign the top most element that fit's into the cursor size (as specified
//! by the [`DrmDevice`](crate::backend::drm::DrmDevice)) on the cursor plane. If the element can not be
//! directly scanned out, pixman will be used to render the element.
//!
//! Note: While the [`DrmCompositor`] also works on *legacy* drm the use of overlay and cursor planes is disabled in that case.
//! Direct scan-out will only work with an atomic [`DrmSurface`].
//!
//! ## What makes a [`Element`] eligible for direct scan-out
//!
//! ### General
//!
//! First the element has to provide a [`UnderlyingStorage`] which can be exported as a drm framebuffer.
//! Currently this is limited to wayland buffers, but may be extended in the future.
//! This module provides a default exporter based on [`gbm`] which should fit most use-cases.
//!
//! If a certain combination of elements works can only be determined by asking the driver by submitting
//! a atomic commit test. If that test fails the element is scheduled to be rendered on the primary plane.
//!
//! ### Overlay planes
//!
//! The element can only be directly scanned out if it's geometry does not overlap with an already assigned
//! element on a plane higher in the stack.
//!
//! ### Underlay planes
//!
//! An underlay plane is only used if it does not overlap with an already assigned plane lower in the stack
//! and the element is fully opaque.
//!
//! ### Primary plane
//!
//! For an element to be considered to be directly scanned out on the primary plane it has to be the last remaining
//! visible element on the output and no other element has been assigned to the primary plane. If there are multiple
//! element assigned to the primary plane the renderer will be used to composite the primary plane into a allocator
//! provided buffer. Additionally the element has to be either fully opaque or the clear color has to match the CRTC
//! background color and no overlap with an underlay is found.
//!
//! # How to use it
//!
//! ```no_run
//! # use smithay::backend::{
//! # allocator::gbm::{GbmAllocator, GbmDevice},
//! # drm::{DrmDevice, DrmDeviceFd},
//! # renderer::{
//! # element::surface::WaylandSurfaceRenderElement,
//! # gles::{GlesTexture, GlesRenderer},
//! # },
//! # };
//! # use drm_fourcc::{DrmFormat, DrmFourcc, DrmModifier};
//! # use std::{collections::HashSet, mem::MaybeUninit};
//! #
//! use smithay::{
//! backend::drm::{
//! compositor::{DrmCompositor, FrameFlags},
//! exporter::gbm::GbmFramebufferExporter,
//! DrmSurface,
//! },
//! output::{Output, PhysicalProperties, Subpixel},
//! utils::Size,
//! };
//!
//! // ...initialize the output, drm device, drm surface and allocator
//! #
//! # const CLEAR_COLOR: [f32; 4] = [0f32, 0f32, 0f32, 0f32];
//! #
//! let output = Output::new(
//! "e-DP".into(),
//! PhysicalProperties {
//! size: Size::from((800, 600)),
//! make: "N/A".into(),
//! model: "N/A".into(),
//! subpixel: Subpixel::Unknown,
//! serial_number: "N/A".into(),
//! },
//! );
//!
//! # let device: DrmDevice = todo!();
//! # let surface: DrmSurface = todo!();
//! # let allocator: GbmAllocator<DrmDeviceFd> = todo!();
//! # let exporter: GbmFramebufferExporter<DrmDeviceFd> = todo!();
//! # let color_formats = [DrmFourcc::Argb8888];
//! # let renderer_formats = HashSet::from([DrmFormat {
//! # code: DrmFourcc::Argb8888,
//! # modifier: DrmModifier::Linear,
//! # }]);
//! # let gbm: GbmDevice<DrmDeviceFd> = todo!();
//! # let mut renderer: GlesRenderer = todo!();
//! #
//! let mut compositor: DrmCompositor<_, _, (), _> = DrmCompositor::new(
//! &output,
//! surface,
//! None,
//! allocator,
//! exporter,
//! color_formats,
//! renderer_formats,
//! device.cursor_size(),
//! Some(gbm),
//! )
//! .expect("failed to initialize drm compositor");
//!
//! # let elements: Vec<WaylandSurfaceRenderElement<GlesRenderer>> = Vec::new();
//! let render_frame_result = compositor
//! .render_frame::<_, _>(&mut renderer, &elements, CLEAR_COLOR, FrameFlags::DEFAULT)
//! .expect("failed to render frame");
//!
//! if !render_frame_result.is_empty {
//! compositor.queue_frame(()).expect("failed to queue frame");
//!
//! // ...wait for VBlank event
//!
//! compositor
//! .frame_submitted()
//! .expect("failed to mark frame as submitted");
//! } else {
//! // ...re-schedule frame
//! }
//! ```
use std::{
collections::HashMap,
fmt::Debug,
io::ErrorKind,
os::unix::io::{AsFd, OwnedFd},
str::FromStr,
sync::Arc,
};
use drm::{
Device, DriverCapability,
control::{Device as _, Mode, PlaneType, connector, crtc, framebuffer, plane},
};
use drm_fourcc::{DrmFormat, DrmFourcc, DrmModifier};
use indexmap::{IndexMap, IndexSet};
use smallvec::SmallVec;
use tracing::{debug, error, info, info_span, instrument, trace, warn};
use wayland_server::{Resource, protocol::wl_buffer::WlBuffer};
#[cfg(feature = "renderer_pixman")]
use crate::backend::renderer::{
Frame as _, ImportAll,
pixman::{PixmanError, PixmanRenderer, PixmanTexture},
};
use crate::{
backend::{
SwapBuffersError,
allocator::{
Allocator, Buffer, Slot, Swapchain,
dmabuf::{AsDmabuf, Dmabuf},
format::{get_opaque, has_alpha},
gbm::{GbmAllocator, GbmBuffer, GbmBufferFlags, GbmDevice},
},
drm::{DrmError, PlaneDamageClips, plane_has_property},
renderer::{
Bind, Color32F, DebugFlags, Renderer, RendererSuper, Texture, buffer_y_inverted,
damage::{Error as OutputDamageTrackerError, OutputDamageTracker},
element::{
Element, Id, Kind, RenderElement, RenderElementPresentationState, RenderElementState,
RenderElementStates, RenderingReason, UnderlyingStorage,
},
sync::SyncPoint,
utils::{CommitCounter, DamageBag},
},
},
output::OutputModeSource,
utils::{Buffer as BufferCoords, DevPath, Physical, Point, Rectangle, Scale, Size, Transform},
wayland::{shm, single_pixel_buffer},
};
use super::{
DrmSurface, Framebuffer, PlaneClaim, PlaneInfo, Planes,
error::AccessError,
exporter::{ExportBuffer, ExportFramebuffer, gbm::GbmFramebufferExporter, gbm::NodeFilter},
surface::VrrSupport,
};
mod elements;
mod frame_result;
use elements::*;
pub use frame_result::*;
impl RenderElementState {
pub(crate) fn zero_copy(visible_area: usize) -> Self {
RenderElementState {
visible_area,
presentation_state: RenderElementPresentationState::ZeroCopy,
needs_capture: false,
}
}
pub(crate) fn rendering_with_reason(reason: RenderingReason) -> Self {
RenderElementState {
visible_area: 0,
presentation_state: RenderElementPresentationState::Rendering { reason: Some(reason) },
needs_capture: false,
}
}
}
#[allow(dead_code)] // This structs purpose is to keep buffer objects alive, most variants won't be read
#[derive(Debug)]
enum ScanoutBuffer<B: Buffer> {
Wayland(crate::backend::renderer::utils::Buffer),
Swapchain(Arc<Slot<B>>),
Cursor(Arc<GbmBuffer>),
}
impl<B: Buffer> Clone for ScanoutBuffer<B> {
fn clone(&self) -> Self {
match self {
Self::Wayland(arg0) => Self::Wayland(arg0.clone()),
Self::Swapchain(arg0) => Self::Swapchain(arg0.clone()),
Self::Cursor(arg0) => Self::Cursor(arg0.clone()),
}
}
}
impl<B: Buffer> ScanoutBuffer<B> {
fn acquire_point(
&self,
signaled_fence: Option<&Arc<OwnedFd>>,
) -> Option<(SyncPoint, Option<Arc<OwnedFd>>)> {
if let Self::Wayland(buffer) = self {
// Assume `DrmSyncobjBlocker` is used, so acquire point has already
// been signaled. Instead of converting with `SyncPoint::from`.
if buffer.acquire_point().is_some() {
return Some((SyncPoint::signaled(), signaled_fence.cloned()));
}
}
None
}
}
impl<B: Buffer> ScanoutBuffer<B> {
#[inline]
fn from_underlying_storage(storage: UnderlyingStorage<'_>) -> Option<Self> {
match storage {
UnderlyingStorage::Wayland(buffer) => Some(Self::Wayland(buffer.clone())),
UnderlyingStorage::Memory { .. } => None,
}
}
}
enum DrmFramebuffer<F: Framebuffer> {
Exporter(F),
Gbm(super::gbm::GbmFramebuffer),
}
impl<F> AsRef<framebuffer::Handle> for DrmFramebuffer<F>
where
F: Framebuffer,
{
#[inline]
fn as_ref(&self) -> &framebuffer::Handle {
match self {
DrmFramebuffer::Exporter(e) => e.as_ref(),
DrmFramebuffer::Gbm(g) => g.as_ref(),
}
}
}
impl<F> Framebuffer for DrmFramebuffer<F>
where
F: Framebuffer,
{
#[inline]
fn format(&self) -> drm_fourcc::DrmFormat {
match self {
DrmFramebuffer::Exporter(e) => e.format(),
DrmFramebuffer::Gbm(g) => g.format(),
}
}
}
impl<F> std::fmt::Debug for DrmFramebuffer<F>
where
F: Framebuffer + std::fmt::Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Exporter(arg0) => f.debug_tuple("Exporter").field(arg0).finish(),
Self::Gbm(arg0) => f.debug_tuple("Gbm").field(arg0).finish(),
}
}
}
struct DrmScanoutBuffer<B: Buffer, F: Framebuffer> {
buffer: ScanoutBuffer<B>,
fb: CachedDrmFramebuffer<F>,
}
impl<B: Buffer, F: Framebuffer> Clone for DrmScanoutBuffer<B, F> {
fn clone(&self) -> Self {
DrmScanoutBuffer {
buffer: self.buffer.clone(),
fb: self.fb.clone(),
}
}
}
impl<B, F> std::fmt::Debug for DrmScanoutBuffer<B, F>
where
B: Buffer + std::fmt::Debug,
F: Framebuffer + std::fmt::Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DrmScanoutBuffer")
.field("buffer", &self.buffer)
.field("fb", &self.fb)
.finish()
}
}
impl<B: Buffer, F: Framebuffer> AsRef<framebuffer::Handle> for DrmScanoutBuffer<B, F> {
#[inline]
fn as_ref(&self) -> &drm::control::framebuffer::Handle {
self.fb.as_ref()
}
}
impl<B: Buffer, F: Framebuffer> Framebuffer for DrmScanoutBuffer<B, F> {
#[inline]
fn format(&self) -> drm_fourcc::DrmFormat {
self.fb.format()
}
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
enum ElementFramebufferCacheBuffer {
Wayland(wayland_server::Weak<WlBuffer>),
}
impl ElementFramebufferCacheBuffer {
#[inline]
fn from_underlying_storage(storage: &UnderlyingStorage<'_>) -> Option<Self> {
match storage {
UnderlyingStorage::Wayland(buffer) => Some(Self::Wayland(buffer.downgrade())),
UnderlyingStorage::Memory { .. } => None,
}
}
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
struct ElementFramebufferCacheKey {
allow_opaque_fallback: bool,
buffer: ElementFramebufferCacheBuffer,
}
impl ElementFramebufferCacheKey {
#[inline]
fn from_underlying_storage(storage: &UnderlyingStorage<'_>, allow_opaque_fallback: bool) -> Option<Self> {
let buffer = ElementFramebufferCacheBuffer::from_underlying_storage(storage)?;
Some(Self {
allow_opaque_fallback,
buffer,
})
}
}
impl ElementFramebufferCacheKey {
#[inline]
fn is_alive(&self) -> bool {
match self.buffer {
ElementFramebufferCacheBuffer::Wayland(ref buffer) => buffer.is_alive(),
}
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq)]
struct PlanesSnapshot {
primary: bool,
cursor_bitmask: u32,
overlay_bitmask: u32,
}
#[derive(Debug)]
struct ElementInstanceState {
properties: PlaneProperties,
active_planes: PlanesSnapshot,
failed_planes: PlanesSnapshot,
}
#[derive(Debug)]
struct ElementState<B: Framebuffer> {
instances: SmallVec<[ElementInstanceState; 1]>,
fb_cache: ElementFramebufferCache<B>,
}
#[derive(Debug)]
struct ElementFramebufferCache<B>
where
B: Framebuffer,
{
/// Cache for framebuffer handles per cache key (e.g. wayland buffer)
fb_cache: SmallVec<
[(
ElementFramebufferCacheKey,
Result<CachedDrmFramebuffer<B>, ExportBufferError>,
); 4],
>,
}
impl<B> ElementFramebufferCache<B>
where
B: Framebuffer,
{
#[inline]
fn get(
&self,
cache_key: &ElementFramebufferCacheKey,
) -> Option<Result<&CachedDrmFramebuffer<B>, ExportBufferError>> {
self.fb_cache.iter().find_map(|(k, r)| {
if k == cache_key {
Some(r.as_ref().map_err(|err| *err))
} else {
None
}
})
}
#[inline]
fn insert(
&mut self,
cache_key: ElementFramebufferCacheKey,
fb: Result<CachedDrmFramebuffer<B>, ExportBufferError>,
) {
self.fb_cache.push((cache_key, fb));
}
fn cleanup(&mut self) {
self.fb_cache.retain(|(key, _)| key.is_alive());
}
}
impl<B> Default for ElementFramebufferCache<B>
where
B: Framebuffer,
{
#[inline]
fn default() -> Self {
Self {
fb_cache: Default::default(),
}
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
struct PlaneProperties {
pub src: Rectangle<f64, BufferCoords>,
pub dst: Rectangle<i32, Physical>,
pub transform: Transform,
pub alpha: f32,
pub format: DrmFormat,
}
impl PlaneProperties {
#[inline]
fn is_compatible(&self, other: &PlaneProperties) -> bool {
self.src == other.src
&& self.dst == other.dst
&& self.transform == other.transform
&& self.alpha == other.alpha
&& self.format == other.format
}
}
struct ElementPlaneConfig<'a, B: Buffer, F: Framebuffer> {
z_index: usize,
geometry: Rectangle<i32, Physical>,
properties: PlaneProperties,
buffer: DrmScanoutBuffer<B, F>,
failed_planes: &'a mut PlanesSnapshot,
}
#[derive(Debug)]
struct PlaneConfig<B: Buffer, F: Framebuffer> {
pub properties: PlaneProperties,
pub buffer: DrmScanoutBuffer<B, F>,
pub damage_clips: Option<PlaneDamageClips>,
pub plane_claim: PlaneClaim,
pub sync: Option<(SyncPoint, Option<Arc<OwnedFd>>)>,
}
impl<B: Buffer, F: Framebuffer> PlaneConfig<B, F> {
#[inline]
pub fn is_compatible(&self, other: &PlaneConfig<B, F>) -> bool {
self.properties.is_compatible(&other.properties)
}
}
impl<B: Buffer, F: Framebuffer> Clone for PlaneConfig<B, F> {
#[inline]
fn clone(&self) -> Self {
Self {
properties: self.properties,
buffer: self.buffer.clone(),
damage_clips: self.damage_clips.clone(),
plane_claim: self.plane_claim.clone(),
sync: self.sync.clone(),
}
}
}
#[derive(Debug, Clone)]
struct PlaneElementState {
id: Id,
commit: CommitCounter,
z_index: usize,
cursor_size: Option<Size<i32, Physical>>,
}
#[derive(Debug)]
struct PlaneState<B: Buffer, F: Framebuffer> {
skip: bool,
needs_test: bool,
element_state: Option<PlaneElementState>,
config: Option<PlaneConfig<B, F>>,
}
impl<B: Buffer, F: Framebuffer> Default for PlaneState<B, F> {
#[inline]
fn default() -> Self {
Self {
skip: true,
needs_test: false,
element_state: Default::default(),
config: Default::default(),
}
}
}
impl<B: Buffer, F: Framebuffer> PlaneState<B, F> {
#[inline]
fn buffer(&self) -> Option<&DrmScanoutBuffer<B, F>> {
self.config.as_ref().map(|config| &config.buffer)
}
#[inline]
fn is_compatible(&self, other: &Self) -> bool {
match (self.config.as_ref(), other.config.as_ref()) {
(Some(a), Some(b)) => a.is_compatible(b),
(None, None) => true,
_ => false,
}
}
}
impl<B: Buffer, F: Framebuffer> Clone for PlaneState<B, F> {
#[inline]
fn clone(&self) -> Self {
Self {
skip: self.skip,
needs_test: self.needs_test,
element_state: self.element_state.clone(),
config: self.config.clone(),
}
}
}
#[derive(Debug)]
struct FrameState<B: Buffer, F: Framebuffer> {
planes: SmallVec<[(plane::Handle, PlaneState<B, F>); 10]>,
}
impl<B: Buffer, F: Framebuffer> FrameState<B, F> {
#[inline]
fn is_assigned(&self, handle: plane::Handle) -> bool {
self.planes
.iter()
.find_map(|(p, state)| {
if *p == handle {
Some(state.config.is_some())
} else {
None
}
})
.unwrap_or(false)
}
#[inline]
fn overlaps(&self, handle: plane::Handle, element_geometry: Rectangle<i32, Physical>) -> bool {
self.planes
.iter()
.find(|(p, _)| *p == handle)
.and_then(|(_, state)| {
state
.config
.as_ref()
.map(|config| config.properties.dst.overlaps(element_geometry))
})
.unwrap_or(false)
}
#[inline]
fn plane_state(&self, handle: plane::Handle) -> Option<&PlaneState<B, F>> {
self.planes
.iter()
.find_map(|(p, state)| if *p == handle { Some(state) } else { None })
}
#[inline]
fn plane_state_mut(&mut self, handle: plane::Handle) -> Option<&mut PlaneState<B, F>> {
self.planes
.iter_mut()
.find_map(|(p, state)| if *p == handle { Some(state) } else { None })
}
#[inline]
fn plane_properties(&self, handle: plane::Handle) -> Option<&PlaneProperties> {
self.plane_state(handle)
.and_then(|state| state.config.as_ref())
.map(|config| &config.properties)
}
#[inline]
fn plane_buffer(&self, handle: plane::Handle) -> Option<&DrmScanoutBuffer<B, F>> {
self.plane_state(handle)
.and_then(|state| state.config.as_ref().map(|config| &config.buffer))
}
}
impl<B: Buffer, F: Framebuffer> FrameState<B, F> {
fn from_planes(primary_plane: plane::Handle, planes: &Planes) -> Self {
let mut tmp = SmallVec::with_capacity(planes.overlay.len() + planes.cursor.len() + 1);
tmp.push((primary_plane, PlaneState::default()));
tmp.extend(
planes
.cursor
.iter()
.map(|info| (info.handle, PlaneState::default())),
);
tmp.extend(
planes
.overlay
.iter()
.map(|info| (info.handle, PlaneState::default())),
);
FrameState { planes: tmp }
}
}
impl<B: Buffer, F: Framebuffer> FrameState<B, F> {
#[profiling::function]
#[inline]
fn set_state(&mut self, plane: plane::Handle, state: PlaneState<B, F>) {
let current_config = match self.plane_state_mut(plane) {
Some(config) => config,
None => return,
};
*current_config = state;
}
#[profiling::function]
fn test_state(
&mut self,
surface: &DrmSurface,
supports_fencing: bool,
plane: plane::Handle,
state: PlaneState<B, F>,
allow_modeset: bool,
) -> Result<(), DrmError> {
let current_config = match self.plane_state_mut(plane) {
Some(config) => config,
None => return Ok(()),
};
let backup = current_config.clone();
*current_config = state;
let res = surface.test_state(self.build_planes(surface, supports_fencing, true), allow_modeset);
if res.is_err() {
// test failed, restore previous state
*self.plane_state_mut(plane).unwrap() = backup;
} else {
self.planes
.iter_mut()
.for_each(|(_, state)| state.needs_test = false);
}
res
}
#[profiling::function]
fn test_state_complete(
&mut self,
previous_frame: &Self,
surface: &DrmSurface,
supports_fencing: bool,
allow_modeset: bool,
allow_partial_update: bool,
) -> Result<(), DrmError> {
let needs_test = self.planes.iter().any(|(_, state)| state.needs_test);
let is_fully_compatible = self.planes.iter().all(|(handle, state)| {
previous_frame
.plane_state(*handle)
.map(|other| state.is_compatible(other))
.unwrap_or(false)
});
if allow_partial_update && (!needs_test || is_fully_compatible) {
trace!("skipping fully compatible state test");
self.planes
.iter_mut()
.for_each(|(_, state)| state.needs_test = false);
return Ok(());
}
let res = surface.test_state(
self.build_planes(surface, supports_fencing, allow_partial_update),
allow_modeset,
);
if res.is_ok() {
self.planes
.iter_mut()
.for_each(|(_, state)| state.needs_test = false);
}
res
}
#[profiling::function]
fn commit(
&mut self,
surface: &DrmSurface,
supports_fencing: bool,
allow_partial_update: bool,
event: bool,
) -> Result<(), crate::backend::drm::error::Error> {
debug_assert!(!self.planes.iter().any(|(_, state)| state.needs_test));
surface.commit(
self.build_planes(surface, supports_fencing, allow_partial_update),
event,
)
}
#[profiling::function]
fn page_flip(
&mut self,
surface: &DrmSurface,
supports_fencing: bool,
allow_partial_update: bool,
event: bool,
) -> Result<(), crate::backend::drm::error::Error> {
debug_assert!(!self.planes.iter().any(|(_, state)| state.needs_test));
surface.page_flip(
self.build_planes(surface, supports_fencing, allow_partial_update),
event,
)
}
#[profiling::function]
fn build_planes<'a>(
&'a mut self,
surface: &'a DrmSurface,
supports_fencing: bool,
allow_partial_update: bool,
) -> impl IntoIterator<Item = super::PlaneState<'a>> {
for (_, state) in self.planes.iter_mut().filter(|(_, state)| !state.skip) {
if let Some(config) = state.config.as_mut() {
// Try to extract a native fence out of the supplied sync point if any
// If the sync point has no native fence or the surface does not support
// fencing force a wait
if let Some((sync, fence)) = config.sync.as_mut() {
if supports_fencing && fence.is_none() {
*fence = sync.export().map(Arc::new);
}
}
}
}
self.planes
.iter_mut()
.filter(move |(handle, state)| {
// If we are not allowed to do an partial update we want to update all
// planes we can claim. This makes sure we also reset planes we never
// actually used. We can skip getting a claim here if we have a
// config as this means we already claimed the plane for us.
if allow_partial_update {
// A partial update would technically only have to include planes that
// actually changed. This includes planes we previously used and have to
// reset and planes we use and want to update.
// Both is already encoded into state.skip, so this should be the only
// thing we have to consider here.
//
// But...Unfortunately some drivers seem to have issues with partial
// updates, at least when it does not contain the primary plane, resulting
// in strange issues like e.g. repeating plane content, side-scrolling planes,
// wrapping planes around edges...
//
// So until these things are fixed just always send the whole state. We do not
// have to send planes we never used, but we include planes we want to reset or
// that explicitly changed represented by !state.skip and all planes currently in
// use represented by having an config defined.
!state.skip || state.config.is_some()
} else {
state.config.is_some() || surface.claim_plane(*handle).is_some()
}
})
.map(move |(handle, state)| super::surface::PlaneState {
handle: *handle,
config: state.config.as_mut().map(|config| super::PlaneConfig {
src: config.properties.src,
dst: config.properties.dst,
alpha: config.properties.alpha,
transform: config.properties.transform,
damage_clips: config.damage_clips.as_ref().map(|d| d.blob()),
fb: *config.buffer.as_ref(),
fence: config
.sync
.as_ref()
.and_then(|(_, fence)| fence.as_ref().map(|fence| fence.as_fd())),
}),
})
}
}
type CompositorFrameState<A, F> =
FrameState<<A as Allocator>::Buffer, <F as ExportFramebuffer<<A as Allocator>::Buffer>>::Framebuffer>;
type FrameErrorType<A, F> = FrameError<
<A as Allocator>::Error,
<<A as Allocator>::Buffer as AsDmabuf>::Error,
<F as ExportFramebuffer<<A as Allocator>::Buffer>>::Error,
>;
pub(crate) type FrameResult<T, A, F> = Result<T, FrameErrorType<A, F>>;
pub(crate) type RenderFrameErrorType<A, F, R> = RenderFrameError<
<A as Allocator>::Error,
<<A as Allocator>::Buffer as AsDmabuf>::Error,
<F as ExportFramebuffer<<A as Allocator>::Buffer>>::Error,
<R as RendererSuper>::Error,
>;
#[derive(Debug)]
struct CursorState<G: AsFd + 'static> {
allocator: GbmAllocator<G>,
framebuffer_exporter: GbmFramebufferExporter<G>,
previous_output_transform: Option<Transform>,
previous_output_scale: Option<Scale<f64>>,
#[cfg(feature = "renderer_pixman")]
pixman_renderer: Option<PixmanRenderer>,
}
#[derive(Debug, thiserror::Error, Copy, Clone)]
enum ExportBufferError {
#[error("the buffer has no underlying storage")]
NoUnderlyingStorage,
#[error("exporting the framebuffer failed")]
ExportFailed,
#[error("no framebuffer could be exported")]
Unsupported,
}
impl From<ExportBufferError> for Option<RenderingReason> {
#[inline]
fn from(err: ExportBufferError) -> Self {
if matches!(err, ExportBufferError::ExportFailed) {
// Export failed could mean the buffer could
// not be used to add a drm framebuffer. This
// especially can happen on kmsro devices where
// a buffer format not usable for scan-out can
// not be used to add a framebuffer
// We can try to give the client another chance
// by announcing a scan-out tranche
Some(RenderingReason::ScanoutFailed)
} else {
// We provide no reason for rendering here as there
// is no action that can be taken to make it work
None
}
}
}
#[derive(Debug)]
struct OverlayPlaneElementIds {
plane_ids: Vec<(plane::Handle, Id, Id)>,
}
impl OverlayPlaneElementIds {
fn from_planes(planes: &Planes) -> Self {
let overlay_plane_count = planes.overlay.len();
Self {
plane_ids: Vec::with_capacity(overlay_plane_count),
}
}
fn plane_id_for_element_id(&mut self, plane: &plane::Handle, element_id: &Id) -> Id {
// Either get the existing plane id for the plane when the stored element id
// matches or generate a new Id (and update the element id)
let existing = self.plane_ids.iter_mut().find(|(p, _, _)| p == plane);
if let Some((_, plane_id, current_element_id)) = existing {
if current_element_id != element_id {
*plane_id = Id::new();
*current_element_id = element_id.clone();
}
plane_id.clone()
} else {
let plane_id = Id::new();
self.plane_ids
.push((*plane, plane_id.clone(), element_id.clone()));
plane_id
}
}
fn contains_plane_id(&self, plane_id: &Id) -> bool {
self.plane_ids.iter().any(|(_, p, _)| p == plane_id)
}
fn remove_plane(&mut self, plane: &plane::Handle) {
self.plane_ids.retain(|(p, _, _)| p != plane);
}
}
struct PlaneAssignment {
handle: plane::Handle,
type_: PlaneType,
}
impl From<&PlaneInfo> for PlaneAssignment {
#[inline]
fn from(value: &PlaneInfo) -> Self {
PlaneAssignment {
handle: value.handle,
type_: value.type_,
}
}
}
struct PendingFrame<A: Allocator, F: ExportFramebuffer<<A as Allocator>::Buffer>, U> {
frame: CompositorFrameState<A, F>,
user_data: U,
}
impl<A, F, U> std::fmt::Debug for PendingFrame<A, F, U>
where
A: Allocator,
<A as Allocator>::Buffer: std::fmt::Debug,
F: ExportFramebuffer<<A as Allocator>::Buffer>,
<F as ExportFramebuffer<<A as Allocator>::Buffer>>::Framebuffer: std::fmt::Debug,
U: std::fmt::Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PendingFrame")
.field("frame", &self.frame)
.field("user_data", &self.user_data)
.finish()
}
}
struct QueuedFrame<A: Allocator, F: ExportFramebuffer<<A as Allocator>::Buffer>, U> {
prepared_frame: PreparedFrame<A, F>,
user_data: U,
}
impl<A, F, U> std::fmt::Debug for QueuedFrame<A, F, U>
where
A: Allocator,
<A as Allocator>::Buffer: std::fmt::Debug,
F: ExportFramebuffer<<A as Allocator>::Buffer>,
<F as ExportFramebuffer<<A as Allocator>::Buffer>>::Framebuffer: std::fmt::Debug,
U: std::fmt::Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("QueuedFrame")
.field("prepared_frame", &self.prepared_frame)
.field("user_data", &self.user_data)
.finish()
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum PreparedFrameKind {
Full,
Partial,
}
struct PreparedFrame<A: Allocator, F: ExportFramebuffer<<A as Allocator>::Buffer>> {
frame: CompositorFrameState<A, F>,
kind: PreparedFrameKind,
}
impl<A: Allocator, F: ExportFramebuffer<<A as Allocator>::Buffer>> PreparedFrame<A, F> {
#[inline]
fn is_empty(&self) -> bool {
// It can happen that we have no changes, but there is a pending commit or