forked from ValveSoftware/steamos-compositor
-
Notifications
You must be signed in to change notification settings - Fork 342
Expand file tree
/
Copy pathDRMBackend.cpp
More file actions
4078 lines (3359 loc) · 129 KB
/
DRMBackend.cpp
File metadata and controls
4078 lines (3359 loc) · 129 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
// DRM output stuff
#include "Script/Script.h"
#include <sys/eventfd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <poll.h>
#include <atomic>
#include <cassert>
#include <cinttypes>
#include <climits>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <map>
#include <mutex>
#include <optional>
#include <span>
#include <string>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "backend.h"
#include "color_helpers.h"
#include "Utils/Defer.h"
#include "drm_include.h"
#include "edid.h"
#include "gamescope_shared.h"
#include "gpuvis_trace_utils.h"
#include "log.hpp"
#include "main.hpp"
#include "modegen.hpp"
#include "rendervulkan.hpp"
#include "steamcompmgr.hpp"
#include "vblankmanager.hpp"
#include "wlserver.hpp"
#include "refresh_rate.h"
#include <sys/utsname.h>
#include "wlr_begin.hpp"
#include <libliftoff.h>
#include <wlr/types/wlr_buffer.h>
#include "libdisplay-info/info.h"
#include "libdisplay-info/edid.h"
#include "libdisplay-info/cta.h"
#include "wlr_end.hpp"
#include "gamescope-control-protocol.h"
static constexpr bool k_bUseCursorPlane = false;
extern int g_nPreferredOutputWidth;
extern int g_nPreferredOutputHeight;
gamescope::ConVar<bool> cv_drm_single_plane_optimizations( "drm_single_plane_optimizations", true, "Whether or not to enable optimizations for single plane usage." );
gamescope::ConVar<bool> cv_drm_debug_disable_shaper_and_3dlut( "drm_debug_disable_shaper_and_3dlut", false, "Shaper + 3DLUT chicken bit. (Force disable/DEFAULT, no logic change)" );
gamescope::ConVar<bool> cv_drm_debug_disable_degamma_tf( "drm_debug_disable_degamma_tf", false, "Degamma chicken bit. (Forces DEGAMMA_TF to DEFAULT, does not affect other logic)" );
gamescope::ConVar<bool> cv_drm_debug_disable_regamma_tf( "drm_debug_disable_regamma_tf", false, "Regamma chicken bit. (Forces REGAMMA_TF to DEFAULT, does not affect other logic)" );
gamescope::ConVar<bool> cv_drm_debug_disable_output_tf( "drm_debug_disable_output_tf", false, "Force default (identity) output TF, affects other logic. Not a property directly." );
gamescope::ConVar<bool> cv_drm_debug_disable_blend_tf( "drm_debug_disable_blend_tf", false, "Blending chicken bit. (Forces BLEND_TF to DEFAULT, does not affect other logic)" );
gamescope::ConVar<bool> cv_drm_debug_disable_ctm( "drm_debug_disable_ctm", false, "CTM chicken bit. (Forces CTM off, does not affect other logic)" );
gamescope::ConVar<bool> cv_drm_debug_disable_color_encoding( "drm_debug_disable_color_encoding", false, "YUV Color Encoding chicken bit. (Forces COLOR_ENCODING to DEFAULT, does not affect other logic)" );
gamescope::ConVar<bool> cv_drm_debug_disable_color_range( "drm_debug_disable_color_range", false, "YUV Color Range chicken bit. (Forces COLOR_RANGE to DEFAULT, does not affect other logic)" );
gamescope::ConVar<bool> cv_drm_debug_disable_explicit_sync( "drm_debug_disable_explicit_sync", false, "Force disable explicit sync on the DRM backend." );
gamescope::ConVar<bool> cv_drm_debug_disable_in_fence_fd( "drm_debug_disable_in_fence_fd", false, "Force disable IN_FENCE_FD being set to avoid over-synchronization on the DRM backend." );
gamescope::ConVar<bool> cv_drm_allow_dynamic_modes_for_external_display( "drm_allow_dynamic_modes_for_external_display", false, "Allow dynamic mode/refresh rate switching for external displays." );
int HackyDRMPresent( const FrameInfo_t *pFrameInfo, bool bAsync );
enum GamescopeBroadcastRGBMode_t : uint32_t
{
GAMESCOPE_BROADCAST_RGB_MODE_AUTOMATIC = 0,
GAMESCOPE_BROADCAST_RGB_MODE_FULL = 1,
GAMESCOPE_BROADCAST_RGB_MODE_LIMITED = 2,
};
struct saved_mode {
int width;
int height;
int refresh;
GamescopeBroadcastRGBMode_t broadcast_mode;
};
gamescope::ConVar<bool> cv_drm_ignore_internal_connectors( "drm_ignore_internal_connectors", false, "Disable internal displays for good, for debugging." );
namespace gamescope
{
class CDRMPlane;
class CDRMCRTC;
class CDRMConnector;
}
struct drm_t {
bool bUseLiftoff;
int fd = -1;
int preferred_width, preferred_height, preferred_refresh;
uint64_t cursor_width, cursor_height;
bool allow_modifiers;
struct wlr_drm_format_set formats;
std::vector< std::unique_ptr< gamescope::CDRMPlane > > planes;
std::vector< std::unique_ptr< gamescope::CDRMCRTC > > crtcs;
std::unordered_map< uint32_t, gamescope::CDRMConnector > connectors;
gamescope::CDRMPlane *pPrimaryPlane;
gamescope::CDRMCRTC *pCRTC;
gamescope::CDRMConnector *pConnector;
struct wlr_drm_format_set primary_formats;
drmModeAtomicReq *req;
uint32_t flags;
struct liftoff_device *lo_device;
struct liftoff_output *lo_output;
struct liftoff_layer *lo_layers[ k_nMaxLayers ];
std::shared_ptr<gamescope::BackendBlob> sdr_static_metadata;
struct drm_state_t {
std::shared_ptr<gamescope::BackendBlob> mode_id;
uint32_t color_mgmt_serial;
std::shared_ptr<gamescope::BackendBlob> lut3d_id[ EOTF_Count ];
std::shared_ptr<gamescope::BackendBlob> shaperlut_id[ EOTF_Count ];
amdgpu_transfer_function output_tf = AMDGPU_TRANSFER_FUNCTION_DEFAULT;
} current, pending;
// FBs in the atomic request, but not yet submitted to KMS
// Accessed only on req thread
std::vector<gamescope::Rc<gamescope::IBackendFb>> m_FbIdsInRequest;
// FBs currently queued to go on screen.
// May be accessed by page flip handler thread and req thread, thus mutex.
std::mutex m_QueuedFbIdsMutex;
std::vector<gamescope::Rc<gamescope::IBackendFb>> m_QueuedFbIds;
// FBs currently on screen.
// Accessed only on page flip handler thread.
std::mutex m_mutVisibleFbIds;
std::vector<gamescope::Rc<gamescope::IBackendFb>> m_VisibleFbIds;
std::atomic < uint32_t > uPendingFlipCount = { 0 };
std::atomic < bool > paused = { false };
std::atomic < int > out_of_date = { false };
std::atomic < bool > needs_modeset = { false };
std::unordered_map< std::string, int > connector_priorities;
char *device_name = nullptr;
};
void drm_drop_fbid( struct drm_t *drm, uint32_t fbid );
bool drm_set_mode( struct drm_t *drm, const drmModeModeInfo *mode );
using namespace std::literals;
struct drm_t g_DRM = {};
// Flip handler thread control. Keep the thread object global so we
// can join it during shutdown instead of detaching and risking the
// thread still using the DRM fd while we clean up.
static std::thread g_page_flip_handler_thread;
static std::atomic<bool> g_page_flip_handler_thread_should_exit{false};
static int g_page_flip_eventfd = -1;
namespace gamescope
{
class CDRMBackend;
std::tuple<int32_t, int32_t, int32_t> GetKernelVersion()
{
utsname name;
if ( uname( &name ) != 0 )
return std::make_tuple( 0, 0, 0 );
std::vector<std::string_view> szVersionParts = Split( name.release, "." );
uint32_t uVersion[3] = { 0 };
for ( size_t i = 0; i < szVersionParts.size() && i < 3; i++ )
{
auto oPart = Parse<int32_t>( szVersionParts[i] );
if ( !oPart )
break;
uVersion[i] = *oPart;
}
return std::make_tuple( uVersion[0], uVersion[1], uVersion[2] );
}
// Get a DRM mode in mHz
// Taken from wlroots, but we can't access it as we don't
// use the drm backend.
static int32_t GetModeRefresh(const drmModeModeInfo *mode)
{
int32_t nRefresh = (mode->clock * 1'000'000ll / mode->htotal + mode->vtotal / 2) / mode->vtotal;
if (mode->flags & DRM_MODE_FLAG_INTERLACE)
nRefresh *= 2;
if (mode->flags & DRM_MODE_FLAG_DBLSCAN)
nRefresh /= 2;
if (mode->vscan > 1)
nRefresh /= mode->vscan;
return nRefresh;
}
template <typename T>
using CAutoDeletePtr = std::unique_ptr<T, void(*)(T*)>;
////////////////////////////////////////
// DRM Object Wrappers + State Trackers
////////////////////////////////////////
struct DRMObjectRawProperty
{
uint32_t uPropertyId = 0ul;
uint64_t ulValue = 0ul;
};
using DRMObjectRawProperties = std::unordered_map<std::string, DRMObjectRawProperty>;
class CDRMAtomicObject
{
public:
CDRMAtomicObject( uint32_t ulObjectId );
uint32_t GetObjectId() const { return m_ulObjectId; }
// No copy or move constructors.
CDRMAtomicObject( const CDRMAtomicObject& ) = delete;
CDRMAtomicObject& operator=( const CDRMAtomicObject& ) = delete;
CDRMAtomicObject( CDRMAtomicObject&& ) = delete;
CDRMAtomicObject& operator=( CDRMAtomicObject&& ) = delete;
protected:
uint32_t m_ulObjectId = 0ul;
};
template < uint32_t DRMObjectType >
class CDRMAtomicTypedObject : public CDRMAtomicObject
{
public:
CDRMAtomicTypedObject( uint32_t ulObjectId );
protected:
std::optional<DRMObjectRawProperties> GetRawProperties();
};
class CDRMAtomicProperty
{
public:
CDRMAtomicProperty( CDRMAtomicObject *pObject, DRMObjectRawProperty rawProperty );
static std::optional<CDRMAtomicProperty> Instantiate( const char *pszName, CDRMAtomicObject *pObject, const DRMObjectRawProperties& rawProperties );
uint64_t GetPendingValue() const { return m_ulPendingValue; }
uint64_t GetCurrentValue() const { return m_ulCurrentValue; }
uint64_t GetInitialValue() const { return m_ulInitialValue; }
int SetPendingValue( drmModeAtomicReq *pRequest, uint64_t ulValue, bool bForce );
void OnCommit();
void Rollback();
private:
CDRMAtomicObject *m_pObject = nullptr;
uint32_t m_uPropertyId = 0u;
uint64_t m_ulPendingValue = 0ul;
uint64_t m_ulCurrentValue = 0ul;
uint64_t m_ulInitialValue = 0ul;
};
class CDRMPlane final : public CDRMAtomicTypedObject<DRM_MODE_OBJECT_PLANE>
{
public:
// Takes ownership of pPlane.
CDRMPlane( drmModePlane *pPlane );
void RefreshState();
drmModePlane *GetModePlane() const { return m_pPlane.get(); }
struct PlaneProperties
{
std::optional<CDRMAtomicProperty> *begin() { return &FB_ID; }
std::optional<CDRMAtomicProperty> *end() { return &DUMMY_END; }
std::optional<CDRMAtomicProperty> type; // Immutable
std::optional<CDRMAtomicProperty> IN_FORMATS; // Immutable
std::optional<CDRMAtomicProperty> FB_ID;
std::optional<CDRMAtomicProperty> IN_FENCE_FD;
std::optional<CDRMAtomicProperty> CRTC_ID;
std::optional<CDRMAtomicProperty> SRC_X;
std::optional<CDRMAtomicProperty> SRC_Y;
std::optional<CDRMAtomicProperty> SRC_W;
std::optional<CDRMAtomicProperty> SRC_H;
std::optional<CDRMAtomicProperty> CRTC_X;
std::optional<CDRMAtomicProperty> CRTC_Y;
std::optional<CDRMAtomicProperty> CRTC_W;
std::optional<CDRMAtomicProperty> CRTC_H;
std::optional<CDRMAtomicProperty> zpos;
std::optional<CDRMAtomicProperty> alpha;
std::optional<CDRMAtomicProperty> rotation;
std::optional<CDRMAtomicProperty> COLOR_ENCODING;
std::optional<CDRMAtomicProperty> COLOR_RANGE;
std::optional<CDRMAtomicProperty> AMD_PLANE_DEGAMMA_TF;
std::optional<CDRMAtomicProperty> AMD_PLANE_DEGAMMA_LUT;
std::optional<CDRMAtomicProperty> AMD_PLANE_CTM;
std::optional<CDRMAtomicProperty> AMD_PLANE_HDR_MULT;
std::optional<CDRMAtomicProperty> AMD_PLANE_SHAPER_LUT;
std::optional<CDRMAtomicProperty> AMD_PLANE_SHAPER_TF;
std::optional<CDRMAtomicProperty> AMD_PLANE_LUT3D;
std::optional<CDRMAtomicProperty> AMD_PLANE_BLEND_TF;
std::optional<CDRMAtomicProperty> AMD_PLANE_BLEND_LUT;
std::optional<CDRMAtomicProperty> DUMMY_END;
};
PlaneProperties &GetProperties() { return m_Props; }
const PlaneProperties &GetProperties() const { return m_Props; }
private:
CAutoDeletePtr<drmModePlane> m_pPlane;
PlaneProperties m_Props;
};
class CDRMCRTC final : public CDRMAtomicTypedObject<DRM_MODE_OBJECT_CRTC>
{
public:
// Takes ownership of pCRTC.
CDRMCRTC( drmModeCrtc *pCRTC, uint32_t uCRTCMask );
void RefreshState();
uint32_t GetCRTCMask() const { return m_uCRTCMask; }
struct CRTCProperties
{
std::optional<CDRMAtomicProperty> *begin() { return &ACTIVE; }
std::optional<CDRMAtomicProperty> *end() { return &DUMMY_END; }
std::optional<CDRMAtomicProperty> ACTIVE;
std::optional<CDRMAtomicProperty> MODE_ID;
std::optional<CDRMAtomicProperty> GAMMA_LUT;
std::optional<CDRMAtomicProperty> DEGAMMA_LUT;
std::optional<CDRMAtomicProperty> CTM;
std::optional<CDRMAtomicProperty> VRR_ENABLED;
std::optional<CDRMAtomicProperty> OUT_FENCE_PTR;
std::optional<CDRMAtomicProperty> AMD_CRTC_REGAMMA_TF;
std::optional<CDRMAtomicProperty> DUMMY_END;
};
CRTCProperties &GetProperties() { return m_Props; }
const CRTCProperties &GetProperties() const { return m_Props; }
private:
CAutoDeletePtr<drmModeCrtc> m_pCRTC;
uint32_t m_uCRTCMask = 0u;
CRTCProperties m_Props;
};
class CDRMConnector final : public CBaseBackendConnector, public CDRMAtomicTypedObject<DRM_MODE_OBJECT_CONNECTOR>
{
public:
CDRMConnector( CDRMBackend *pBackend, drmModeConnector *pConnector );
void RefreshState();
struct ConnectorProperties
{
std::optional<CDRMAtomicProperty> *begin() { return &CRTC_ID; }
std::optional<CDRMAtomicProperty> *end() { return &DUMMY_END; }
std::optional<CDRMAtomicProperty> CRTC_ID;
std::optional<CDRMAtomicProperty> Colorspace;
std::optional<CDRMAtomicProperty> content_type; // "content type" with space!
std::optional<CDRMAtomicProperty> panel_orientation; // "panel orientation" with space!
std::optional<CDRMAtomicProperty> HDR_OUTPUT_METADATA;
std::optional<CDRMAtomicProperty> vrr_capable;
std::optional<CDRMAtomicProperty> EDID;
std::optional<CDRMAtomicProperty> Broadcast_RGB;
std::optional<CDRMAtomicProperty> DUMMY_END;
};
ConnectorProperties &GetProperties() { return m_Props; }
const ConnectorProperties &GetProperties() const { return m_Props; }
drmModeConnector *GetModeConnector() { return m_pConnector.get(); }
const char *GetName() const override { return m_Mutable.szName; }
const char *GetMake() const override { return m_Mutable.pszMake; }
const char *GetModel() const override { return m_Mutable.szModel; }
const char *GetDataString() const { return m_Mutable.szDataString; }
uint32_t GetPossibleCRTCMask() const { return m_Mutable.uPossibleCRTCMask; }
std::span<const uint32_t> GetValidDynamicRefreshRates() const override { return m_Mutable.ValidDynamicRefreshRates; }
const displaycolorimetry_t& GetDisplayColorimetry() const { return m_Mutable.DisplayColorimetry; }
std::span<const uint8_t> GetRawEDID() const override { return std::span<const uint8_t>{ m_Mutable.EdidData.begin(), m_Mutable.EdidData.end() }; }
bool SupportsHDR10() const
{
return !!GetProperties().Colorspace && !!GetProperties().HDR_OUTPUT_METADATA && GetHDRInfo().IsHDR10();
}
bool SupportsHDRG22() const
{
return GetHDRInfo().IsHDRG22();
}
//////////////////////////////////////
// IBackendConnector implementation
//////////////////////////////////////
GamescopeScreenType GetScreenType() const override
{
if ( m_pConnector->connector_type == DRM_MODE_CONNECTOR_eDP ||
m_pConnector->connector_type == DRM_MODE_CONNECTOR_LVDS ||
m_pConnector->connector_type == DRM_MODE_CONNECTOR_DSI )
return GAMESCOPE_SCREEN_TYPE_INTERNAL;
return GAMESCOPE_SCREEN_TYPE_EXTERNAL;
}
GamescopePanelOrientation GetCurrentOrientation() const override
{
return m_ChosenOrientation;
}
bool SupportsHDR() const override
{
return SupportsHDR10() || SupportsHDRG22();
}
bool IsHDRActive() const override
{
if ( SupportsHDR10() )
{
return GetProperties().Colorspace->GetCurrentValue() == DRM_MODE_COLORIMETRY_BT2020_RGB;
}
else if ( SupportsHDRG22() )
{
return true;
}
return false;
}
const BackendConnectorHDRInfo &GetHDRInfo() const override { return m_Mutable.HDR; }
virtual bool IsVRRActive() const override
{
if ( !g_DRM.pCRTC || !g_DRM.pCRTC->GetProperties().VRR_ENABLED )
return false;
return !!g_DRM.pCRTC->GetProperties().VRR_ENABLED->GetCurrentValue();
}
virtual std::span<const BackendMode> GetModes() const override { return m_Mutable.BackendModes; }
bool SupportsVRR() const override
{
return this->GetProperties().vrr_capable && !!this->GetProperties().vrr_capable->GetCurrentValue();
}
void GetNativeColorimetry(
bool bHDR,
displaycolorimetry_t *displayColorimetry, EOTF *displayEOTF,
displaycolorimetry_t *outputEncodingColorimetry, EOTF *outputEncodingEOTF ) const override
{
*displayColorimetry = GetDisplayColorimetry();
*displayEOTF = EOTF_Gamma22;
if ( bHDR && GetHDRInfo().IsHDR10() )
{
// For HDR10 output, expected content colorspace != native colorspace.
*outputEncodingColorimetry = displaycolorimetry_2020;
*outputEncodingEOTF = GetHDRInfo().eOutputEncodingEOTF;
}
else
{
*outputEncodingColorimetry = GetDisplayColorimetry();
*outputEncodingEOTF = EOTF_Gamma22;
}
}
virtual int Present( const FrameInfo_t *pFrameInfo, bool bAsync ) override;
using DRMModeGenerator = std::function<drmModeModeInfo(const drmModeModeInfo *, int)>;
const DRMModeGenerator &GetModeGenerator() const
{
return m_Mutable.fnDynamicModeGenerator;
}
void UpdateEffectiveOrientation( const drmModeModeInfo *pMode );
private:
void ParseEDID();
CDRMBackend *m_pBackend = nullptr;
CAutoDeletePtr<drmModeConnector> m_pConnector;
struct MutableConnectorState
{
int nDefaultRefresh = 0;
uint32_t uPossibleCRTCMask = 0u;
char szName[32]{};
char szMakePNP[4]{};
char szModel[16]{};
char szDataString[16]{};
const char *pszMake = ""; // Not owned, no free. This is a pointer to pnp db or szMakePNP.
DRMModeGenerator fnDynamicModeGenerator;
std::vector<uint32_t> ValidDynamicRefreshRates{};
std::vector<uint8_t> EdidData; // Raw, unmodified.
std::vector<BackendMode> BackendModes;
displaycolorimetry_t DisplayColorimetry = displaycolorimetry_709;
BackendConnectorHDRInfo HDR;
} m_Mutable;
GamescopePanelOrientation m_ChosenOrientation = GAMESCOPE_PANEL_ORIENTATION_AUTO;
ConnectorProperties m_Props;
};
class CDRMFb final : public CBaseBackendFb
{
public:
CDRMFb( uint32_t uFbId );
~CDRMFb();
uint32_t GetFbId() const { return m_uFbId; }
private:
uint32_t m_uFbId = 0;
};
}
uint32_t g_nDRMFormat = DRM_FORMAT_INVALID;
uint32_t g_nDRMFormatOverlay = DRM_FORMAT_INVALID; // for partial composition, we may have more limited formats than base planes + alpha.
bool g_bRotated = false;
extern bool g_bDebugLayers;
struct DRMPresentCtx
{
uint64_t ulPendingFlipCount = 0;
};
extern gamescope::ConVar<bool> cv_composite_force;
extern bool g_bColorSliderInUse;
extern bool fadingOut;
extern std::string g_reshade_effect;
#ifndef DRM_CAP_ATOMIC_ASYNC_PAGE_FLIP
#define DRM_CAP_ATOMIC_ASYNC_PAGE_FLIP 0x15
#endif
bool drm_update_color_mgmt(struct drm_t *drm);
bool drm_supports_color_mgmt(struct drm_t *drm);
bool drm_set_connector( struct drm_t *drm, gamescope::CDRMConnector *conn );
struct drm_color_ctm2 {
/*
* Conversion matrix in S31.32 sign-magnitude
* (not two's complement!) format.
*/
__u64 matrix[12];
};
bool g_bSupportsAsyncFlips = false;
bool g_bSupportsSyncObjs = false;
extern gamescope::GamescopeModeGeneration g_eGamescopeModeGeneration;
extern GamescopePanelOrientation g_DesiredInternalOrientation;
extern bool g_bForceDisableColorMgmt;
static LogScope drm_log( "drm" );
static LogScope liftoff_log_scope( "liftoff" );
static std::unordered_map< std::string, std::string > pnps = {};
static void drm_unset_mode( struct drm_t *drm );
static void drm_unset_connector( struct drm_t *drm );
static constexpr uint32_t s_kSteamDeckLCDRates[] =
{
40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60,
};
static constexpr uint32_t s_kSteamDeckOLEDRates[] =
{
45, 47, 48, 49,
50, 51, 53, 55, 56, 59,
60, 62, 64, 65, 66, 68,
72, 73, 76, 77, 78,
80, 81, 82, 84, 85, 86, 87, 88,
90,
};
void update_connector_display_info_wl(struct drm_t *drm)
{
wlserver_lock();
for ( const auto &control : wlserver.gamescope_controls )
{
wlserver_send_gamescope_control( control );
}
wlserver_unlock();
}
inline uint64_t drm_calc_s31_32(float val)
{
// S31.32 sign-magnitude
float integral = 0.0f;
float fractional = modf( fabsf( val ), &integral );
union
{
struct
{
uint64_t fractional : 32;
uint64_t integral : 31;
uint64_t sign_part : 1;
} s31_32_bits;
uint64_t s31_32;
} color;
color.s31_32_bits.sign_part = val < 0 ? 1 : 0;
color.s31_32_bits.integral = uint64_t( integral );
color.s31_32_bits.fractional = uint64_t( fractional * float( 1ull << 32 ) );
return color.s31_32;
}
static gamescope::CDRMCRTC *find_crtc_for_connector( struct drm_t *drm, gamescope::CDRMConnector *pConnector )
{
for ( std::unique_ptr< gamescope::CDRMCRTC > &pCRTC : drm->crtcs )
{
if ( pConnector->GetPossibleCRTCMask() & pCRTC->GetCRTCMask() )
return pCRTC.get();
}
return nullptr;
}
static bool get_plane_formats( struct drm_t *drm, gamescope::CDRMPlane *pPlane, struct wlr_drm_format_set *pFormatSet )
{
for ( uint32_t i = 0; i < pPlane->GetModePlane()->count_formats; i++ )
{
const uint32_t uFormat = pPlane->GetModePlane()->formats[ i ];
wlr_drm_format_set_add( pFormatSet, uFormat, DRM_FORMAT_MOD_INVALID );
}
if ( pPlane->GetProperties().IN_FORMATS )
{
const uint64_t ulBlobId = pPlane->GetProperties().IN_FORMATS->GetCurrentValue();
drmModePropertyBlobRes *pBlob = drmModeGetPropertyBlob( drm->fd, ulBlobId );
if ( !pBlob )
{
drm_log.errorf_errno("drmModeGetPropertyBlob(IN_FORMATS) failed");
return false;
}
defer( drmModeFreePropertyBlob( pBlob ) );
drm_format_modifier_blob *pModifierBlob = reinterpret_cast<drm_format_modifier_blob *>( pBlob->data );
uint32_t *pFormats = reinterpret_cast<uint32_t *>( reinterpret_cast<uint8_t *>( pBlob->data ) + pModifierBlob->formats_offset );
drm_format_modifier *pMods = reinterpret_cast<drm_format_modifier *>( reinterpret_cast<uint8_t *>( pBlob->data ) + pModifierBlob->modifiers_offset );
for ( uint32_t i = 0; i < pModifierBlob->count_modifiers; i++ )
{
for ( uint32_t j = 0; j < 64; j++ )
{
if ( pMods[i].formats & ( uint64_t(1) << j ) )
wlr_drm_format_set_add( pFormatSet, pFormats[j + pMods[i].offset], pMods[i].modifier );
}
}
}
return true;
}
static uint32_t pick_plane_format( const struct wlr_drm_format_set *formats, uint32_t Xformat, uint32_t Aformat )
{
uint32_t result = DRM_FORMAT_INVALID;
for ( size_t i = 0; i < formats->len; i++ ) {
uint32_t fmt = formats->formats[i].format;
if ( fmt == Xformat ) {
// Prefer formats without alpha channel for main plane
result = fmt;
} else if ( result == DRM_FORMAT_INVALID && fmt == Aformat ) {
result = fmt;
}
}
return result;
}
/* Pick a primary plane that can be connected to the chosen CRTC. */
static gamescope::CDRMPlane *find_primary_plane(struct drm_t *drm)
{
if ( !drm->pCRTC )
return nullptr;
for ( std::unique_ptr< gamescope::CDRMPlane > &pPlane : drm->planes )
{
if ( pPlane->GetModePlane()->possible_crtcs & drm->pCRTC->GetCRTCMask() )
{
if ( pPlane->GetProperties().type->GetCurrentValue() == DRM_PLANE_TYPE_PRIMARY )
return pPlane.get();
}
}
return nullptr;
}
static bool have_overlay_planes(struct drm_t *drm)
{
if ( !drm->pCRTC )
return false;
for ( std::unique_ptr< gamescope::CDRMPlane > &pPlane : drm->planes )
{
if ( pPlane->GetModePlane()->possible_crtcs & drm->pCRTC->GetCRTCMask() )
{
if ( pPlane->GetProperties().type->GetCurrentValue() == DRM_PLANE_TYPE_OVERLAY )
return true;
}
}
return false;
}
extern void mangoapp_output_update( uint64_t vblanktime );
static void page_flip_handler(int fd, unsigned int frame, unsigned int sec, unsigned int usec, unsigned int crtc_id, void *data)
{
DRMPresentCtx *pCtx = reinterpret_cast<DRMPresentCtx *>( data );
// Make this const when we move into CDRMBackend.
GetBackend()->GetCurrentConnector()->PresentationFeedback().m_uCompletedPresents = pCtx->ulPendingFlipCount;
if ( !g_DRM.pCRTC )
return;
if ( g_DRM.pCRTC->GetObjectId() != crtc_id )
return;
static uint64_t ulLastVBlankTime = 0;
// This is the last vblank time
uint64_t vblanktime = sec * 1'000'000'000lu + usec * 1'000lu;
GetVBlankTimer().MarkVBlank( vblanktime, true );
// TODO: get the fbids_queued instance from data if we ever have more than one in flight
drm_log.debugf("page_flip_handler %" PRIu64 " delta: %" PRIu64, pCtx->ulPendingFlipCount, vblanktime - ulLastVBlankTime );
gpuvis_trace_printf("page_flip_handler %" PRIu64, pCtx->ulPendingFlipCount);
ulLastVBlankTime = vblanktime;
{
std::scoped_lock lock{ g_DRM.m_QueuedFbIdsMutex, g_DRM.m_mutVisibleFbIds };
// Swap and clear from queue -> visible to avoid allocations.
g_DRM.m_VisibleFbIds.swap( g_DRM.m_QueuedFbIds );
g_DRM.m_QueuedFbIds.clear();
}
g_DRM.uPendingFlipCount--;
g_DRM.uPendingFlipCount.notify_all();
mangoapp_output_update( vblanktime );
// Nudge so that steamcompmgr releases commits.
nudge_steamcompmgr();
}
void flip_handler_thread_run(void)
{
pthread_setname_np( pthread_self(), "gamescope-kms" );
// Prepare pollfds: one for DRM fd and for eventfd to
// wake up the poll immediately when requested to exit.
struct pollfd fds[2];
int nfds = 0;
fds[nfds].fd = g_DRM.fd;
fds[nfds].events = POLLIN;
nfds++;
if ( g_page_flip_eventfd != -1 ) {
fds[nfds].fd = g_page_flip_eventfd;
fds[nfds].events = POLLIN;
nfds++;
}
while ( !g_page_flip_handler_thread_should_exit.load( std::memory_order_acquire ) )
{
int ret = poll( fds, nfds, -1 );
if ( ret < 0 ) {
if ( errno == EINTR )
continue;
drm_log.errorf_errno( "polling for DRM events failed" );
break;
}
if ( ret == 0 ) {
// timeout, check exit condition again
continue;
}
// Check if eventfd signaled
if ( nfds > 1 && (fds[1].revents & POLLIN) ) {
uint64_t val;
ssize_t r = read( g_page_flip_eventfd, &val, sizeof( val ) );
(void)r;
}
if ( (fds[0].revents & POLLIN) ) {
drmEventContext evctx = {
.version = 3,
.page_flip_handler2 = page_flip_handler,
};
drmHandleEvent( g_DRM.fd, &evctx );
}
}
drm_log.debugf("page_flip_handler_thread exiting");
}
static bool refresh_state( drm_t *drm )
{
drmModeRes *pResources = drmModeGetResources( drm->fd );
if ( pResources == nullptr )
{
drm_log.errorf_errno( "drmModeGetResources failed" );
return false;
}
defer( drmModeFreeResources( pResources ) );
// Add connectors which appeared
for ( int i = 0; i < pResources->count_connectors; i++ )
{
uint32_t uConnectorId = pResources->connectors[i];
drmModeConnector *pConnector = drmModeGetConnector( drm->fd, uConnectorId );
if ( !pConnector )
continue;
if ( cv_drm_ignore_internal_connectors )
{
if ( pConnector->connector_type == DRM_MODE_CONNECTOR_eDP ||
pConnector->connector_type == DRM_MODE_CONNECTOR_LVDS ||
pConnector->connector_type == DRM_MODE_CONNECTOR_DSI )
{
drmModeFreeConnector( pConnector );
continue;
}
}
if ( !drm->connectors.contains( uConnectorId ) )
{
drm->connectors.emplace(
std::piecewise_construct,
std::forward_as_tuple( uConnectorId ),
std::forward_as_tuple( reinterpret_cast<gamescope::CDRMBackend *>( GetBackend() ), pConnector ) );
}
}
// Remove connectors which disappeared
for ( auto iter = drm->connectors.begin(); iter != drm->connectors.end(); )
{
gamescope::CDRMConnector *pConnector = &iter->second;
const bool bFound = std::any_of(
pResources->connectors,
pResources->connectors + pResources->count_connectors,
std::bind_front( std::equal_to{}, pConnector->GetObjectId() ) );
if ( !bFound )
{
drm_log.debugf( "Connector '%s' disappeared.", pConnector->GetName() );
if ( drm->pConnector == pConnector )
{
drm_log.infof( "Current connector '%s' disappeared.", pConnector->GetName() );
drm->pConnector = nullptr;
}
iter = drm->connectors.erase( iter );
}
else
iter++;
}
// Re-probe connectors props and status)
for ( auto &iter : drm->connectors )
{
gamescope::CDRMConnector *pConnector = &iter.second;
pConnector->RefreshState();
}
for ( std::unique_ptr< gamescope::CDRMCRTC > &pCRTC : drm->crtcs )
pCRTC->RefreshState();
for ( std::unique_ptr< gamescope::CDRMPlane > &pPlane : drm->planes )
pPlane->RefreshState();
return true;
}
static bool get_resources(struct drm_t *drm)
{
{
drmModeRes *pResources = drmModeGetResources( drm->fd );
if ( !pResources )
{
drm_log.errorf_errno( "drmModeGetResources failed" );
return false;
}
defer( drmModeFreeResources( pResources ) );
for ( int i = 0; i < pResources->count_crtcs; i++ )
{
drmModeCrtc *pCRTC = drmModeGetCrtc( drm->fd, pResources->crtcs[ i ] );
if ( pCRTC )
drm->crtcs.emplace_back( std::make_unique<gamescope::CDRMCRTC>( pCRTC, 1u << i ) );
}
}
{
drmModePlaneRes *pPlaneResources = drmModeGetPlaneResources( drm->fd );
if ( !pPlaneResources )
{
drm_log.errorf_errno( "drmModeGetPlaneResources failed" );
return false;
}
defer( drmModeFreePlaneResources( pPlaneResources ) );
for ( uint32_t i = 0; i < pPlaneResources->count_planes; i++ )
{
drmModePlane *pPlane = drmModeGetPlane( drm->fd, pPlaneResources->planes[ i ] );
if ( pPlane )
drm->planes.emplace_back( std::make_unique<gamescope::CDRMPlane>( pPlane ) );
}
}
return refresh_state( drm );
}
struct mode_blocklist_entry
{
uint32_t width, height, refresh;
};
// Filter out reporting some modes that are required for
// certain certifications, but are completely useless,
// and probably don't fit the display pixel size.
static mode_blocklist_entry g_badModes[] =
{
{ 4096, 2160, 0 },
};
static const drmModeModeInfo *find_mode( const drmModeConnector *connector, int hdisplay, int vdisplay, uint32_t vrefresh )
{
for (int i = 0; i < connector->count_modes; i++) {
const drmModeModeInfo *mode = &connector->modes[i];
bool bad = false;
for (const auto& badMode : g_badModes) {
bad |= (badMode.width == 0 || mode->hdisplay == badMode.width)
&& (badMode.height == 0 || mode->vdisplay == badMode.height)
&& (badMode.refresh == 0 || mode->vrefresh == badMode.refresh);
}
if (bad)
continue;
if (hdisplay != 0 && hdisplay != mode->hdisplay)
continue;
if (vdisplay != 0 && vdisplay != mode->vdisplay)
continue;
if (vrefresh != 0 && vrefresh != mode->vrefresh)
continue;
return mode;
}
return NULL;
}
static std::unordered_map<std::string, int> parse_connector_priorities(const char *str)
{