-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
SDL_kmsdrmvideo.c
1626 lines (1331 loc) · 55 KB
/
SDL_kmsdrmvideo.c
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
/*
Simple DirectMedia Layer
Copyright (C) 1997-2023 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "SDL_internal.h"
#ifdef SDL_VIDEO_DRIVER_KMSDRM
/* SDL internals */
#include "../../events/SDL_events_c.h"
#include "../../events/SDL_keyboard_c.h"
#include "../../events/SDL_mouse_c.h"
#include "../SDL_sysvideo.h"
#ifdef SDL_INPUT_LINUXEV
#include "../../core/linux/SDL_evdev.h"
#elif defined SDL_INPUT_WSCONS
#include "../../core/openbsd/SDL_wscons.h"
#endif
/* KMS/DRM declarations */
#include "SDL_kmsdrmdyn.h"
#include "SDL_kmsdrmevents.h"
#include "SDL_kmsdrmmouse.h"
#include "SDL_kmsdrmvideo.h"
#include "SDL_kmsdrmopengles.h"
#include "SDL_kmsdrmvulkan.h"
#include <dirent.h>
#include <errno.h>
#include <poll.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#ifdef __OpenBSD__
static SDL_bool moderndri = SDL_FALSE;
#else
static SDL_bool moderndri = SDL_TRUE;
#endif
static char kmsdrm_dri_path[16];
static int kmsdrm_dri_pathsize = 0;
static char kmsdrm_dri_devname[8];
static int kmsdrm_dri_devnamesize = 0;
static char kmsdrm_dri_cardpath[32];
#ifndef EGL_PLATFORM_GBM_MESA
#define EGL_PLATFORM_GBM_MESA 0x31D7
#endif
static int get_driindex(void)
{
int available = -ENOENT;
char device[sizeof(kmsdrm_dri_cardpath)];
int drm_fd;
int i;
int devindex = -1;
DIR *folder;
const char *hint;
hint = SDL_GetHint(SDL_HINT_KMSDRM_DEVICE_INDEX);
if (hint && *hint) {
char *endptr = NULL;
const int idx = (int)SDL_strtol(hint, &endptr, 10);
if ((*endptr == '\0') && (idx >= 0)) { /* *endptr==0 means "whole string was a valid number" */
return idx; /* we'll take the user's request here. */
}
}
SDL_strlcpy(device, kmsdrm_dri_path, sizeof(device));
folder = opendir(device);
if (!folder) {
SDL_SetError("Failed to open directory '%s'", device);
return -ENOENT;
}
SDL_strlcpy(device + kmsdrm_dri_pathsize, kmsdrm_dri_devname,
sizeof(device) - kmsdrm_dri_devnamesize);
for (struct dirent *res; (res = readdir(folder));) {
if (SDL_memcmp(res->d_name, kmsdrm_dri_devname,
kmsdrm_dri_devnamesize) == 0) {
SDL_strlcpy(device + kmsdrm_dri_pathsize + kmsdrm_dri_devnamesize,
res->d_name + kmsdrm_dri_devnamesize,
sizeof(device) - kmsdrm_dri_pathsize -
kmsdrm_dri_devnamesize);
drm_fd = open(device, O_RDWR | O_CLOEXEC);
if (drm_fd >= 0) {
devindex = SDL_atoi(device + kmsdrm_dri_pathsize +
kmsdrm_dri_devnamesize);
if (SDL_KMSDRM_LoadSymbols()) {
drmModeRes *resources = KMSDRM_drmModeGetResources(drm_fd);
if (resources) {
SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO,
"%s%d connector, encoder and CRTC counts are: %d %d %d",
kmsdrm_dri_cardpath, devindex,
resources->count_connectors,
resources->count_encoders,
resources->count_crtcs);
if (resources->count_connectors > 0 &&
resources->count_encoders > 0 &&
resources->count_crtcs > 0) {
available = -ENOENT;
for (i = 0; i < resources->count_connectors; i++) {
drmModeConnector *conn =
KMSDRM_drmModeGetConnector(
drm_fd, resources->connectors[i]);
if (!conn) {
continue;
}
if (conn->connection == DRM_MODE_CONNECTED &&
conn->count_modes) {
if (SDL_GetHintBoolean(
SDL_HINT_KMSDRM_REQUIRE_DRM_MASTER,
SDL_TRUE)) {
/* Skip this device if we can't obtain
* DRM master */
KMSDRM_drmSetMaster(drm_fd);
if (KMSDRM_drmAuthMagic(drm_fd, 0) ==
-EACCES) {
continue;
}
}
available = devindex;
break;
}
KMSDRM_drmModeFreeConnector(conn);
}
}
KMSDRM_drmModeFreeResources(resources);
}
SDL_KMSDRM_UnloadSymbols();
}
close(drm_fd);
}
SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO,
"Failed to open KMSDRM device %s, errno: %d\n", device,
errno);
}
}
closedir(folder);
return available;
}
static float CalculateRefreshRate(drmModeModeInfo *mode)
{
unsigned int num, den;
num = mode->clock * 1000;
den = mode->htotal * mode->vtotal;
if (mode->flags & DRM_MODE_FLAG_INTERLACE) {
num *= 2;
}
if (mode->flags & DRM_MODE_FLAG_DBLSCAN) {
den *= 2;
}
if (mode->vscan > 1) {
den *= mode->vscan;
}
return ((100 * (Sint64)num) / den) / 100.0f;
}
static int KMSDRM_Available(void)
{
#ifdef __OpenBSD__
struct utsname nameofsystem;
double releaseversion;
#endif
int ret = -ENOENT;
#ifdef __OpenBSD__
if (!(uname(&nameofsystem) < 0)) {
releaseversion = SDL_atof(nameofsystem.release);
if (releaseversion >= 6.9) {
moderndri = SDL_TRUE;
}
}
#endif
if (moderndri) {
SDL_strlcpy(kmsdrm_dri_path, "/dev/dri/", sizeof(kmsdrm_dri_path));
SDL_strlcpy(kmsdrm_dri_devname, "card", sizeof(kmsdrm_dri_devname));
} else {
SDL_strlcpy(kmsdrm_dri_path, "/dev/", sizeof(kmsdrm_dri_path));
SDL_strlcpy(kmsdrm_dri_devname, "drm", sizeof(kmsdrm_dri_devname));
}
kmsdrm_dri_pathsize = SDL_strlen(kmsdrm_dri_path);
kmsdrm_dri_devnamesize = SDL_strlen(kmsdrm_dri_devname);
(void)SDL_snprintf(kmsdrm_dri_cardpath, sizeof(kmsdrm_dri_cardpath), "%s%s",
kmsdrm_dri_path, kmsdrm_dri_devname);
ret = get_driindex();
if (ret >= 0) {
return 1;
}
return ret;
}
static void KMSDRM_DeleteDevice(SDL_VideoDevice *device)
{
if (device->driverdata) {
SDL_free(device->driverdata);
device->driverdata = NULL;
}
SDL_free(device);
SDL_KMSDRM_UnloadSymbols();
}
static SDL_VideoDevice *KMSDRM_CreateDevice(void)
{
SDL_VideoDevice *device;
SDL_VideoData *viddata;
int devindex;
if (!KMSDRM_Available()) {
return NULL;
}
devindex = get_driindex();
if (devindex < 0) {
SDL_SetError("devindex (%d) must not be negative.", devindex);
return NULL;
}
if (!SDL_KMSDRM_LoadSymbols()) {
return NULL;
}
device = (SDL_VideoDevice *)SDL_calloc(1, sizeof(SDL_VideoDevice));
if (!device) {
return NULL;
}
viddata = (SDL_VideoData *)SDL_calloc(1, sizeof(SDL_VideoData));
if (!viddata) {
goto cleanup;
}
viddata->devindex = devindex;
viddata->drm_fd = -1;
device->driverdata = viddata;
/* Setup all functions which we can handle */
device->VideoInit = KMSDRM_VideoInit;
device->VideoQuit = KMSDRM_VideoQuit;
device->GetDisplayModes = KMSDRM_GetDisplayModes;
device->SetDisplayMode = KMSDRM_SetDisplayMode;
device->CreateSDLWindow = KMSDRM_CreateWindow;
device->SetWindowTitle = KMSDRM_SetWindowTitle;
device->SetWindowPosition = KMSDRM_SetWindowPosition;
device->SetWindowSize = KMSDRM_SetWindowSize;
device->SetWindowFullscreen = KMSDRM_SetWindowFullscreen;
device->ShowWindow = KMSDRM_ShowWindow;
device->HideWindow = KMSDRM_HideWindow;
device->RaiseWindow = KMSDRM_RaiseWindow;
device->MaximizeWindow = KMSDRM_MaximizeWindow;
device->MinimizeWindow = KMSDRM_MinimizeWindow;
device->RestoreWindow = KMSDRM_RestoreWindow;
device->DestroyWindow = KMSDRM_DestroyWindow;
device->GL_LoadLibrary = KMSDRM_GLES_LoadLibrary;
device->GL_GetProcAddress = KMSDRM_GLES_GetProcAddress;
device->GL_UnloadLibrary = KMSDRM_GLES_UnloadLibrary;
device->GL_CreateContext = KMSDRM_GLES_CreateContext;
device->GL_MakeCurrent = KMSDRM_GLES_MakeCurrent;
device->GL_SetSwapInterval = KMSDRM_GLES_SetSwapInterval;
device->GL_GetSwapInterval = KMSDRM_GLES_GetSwapInterval;
device->GL_SwapWindow = KMSDRM_GLES_SwapWindow;
device->GL_DeleteContext = KMSDRM_GLES_DeleteContext;
device->GL_DefaultProfileConfig = KMSDRM_GLES_DefaultProfileConfig;
#ifdef SDL_VIDEO_VULKAN
device->Vulkan_LoadLibrary = KMSDRM_Vulkan_LoadLibrary;
device->Vulkan_UnloadLibrary = KMSDRM_Vulkan_UnloadLibrary;
device->Vulkan_GetInstanceExtensions = KMSDRM_Vulkan_GetInstanceExtensions;
device->Vulkan_CreateSurface = KMSDRM_Vulkan_CreateSurface;
#endif
device->PumpEvents = KMSDRM_PumpEvents;
device->free = KMSDRM_DeleteDevice;
return device;
cleanup:
if (device) {
SDL_free(device);
}
if (viddata) {
SDL_free(viddata);
}
return NULL;
}
VideoBootStrap KMSDRM_bootstrap = {
"KMSDRM",
"KMS/DRM Video Driver",
KMSDRM_CreateDevice
};
static void KMSDRM_FBDestroyCallback(struct gbm_bo *bo, void *data)
{
KMSDRM_FBInfo *fb_info = (KMSDRM_FBInfo *)data;
if (fb_info && fb_info->drm_fd >= 0 && fb_info->fb_id != 0) {
KMSDRM_drmModeRmFB(fb_info->drm_fd, fb_info->fb_id);
SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Delete DRM FB %u", fb_info->fb_id);
}
SDL_free(fb_info);
}
KMSDRM_FBInfo *KMSDRM_FBFromBO(SDL_VideoDevice *_this, struct gbm_bo *bo)
{
SDL_VideoData *viddata = _this->driverdata;
unsigned w, h;
int ret;
Uint32 stride, handle;
/* Check for an existing framebuffer */
KMSDRM_FBInfo *fb_info = (KMSDRM_FBInfo *)KMSDRM_gbm_bo_get_user_data(bo);
if (fb_info) {
return fb_info;
}
/* Create a structure that contains enough info to remove the framebuffer
when the backing buffer is destroyed */
fb_info = (KMSDRM_FBInfo *)SDL_calloc(1, sizeof(KMSDRM_FBInfo));
if (!fb_info) {
return NULL;
}
fb_info->drm_fd = viddata->drm_fd;
/* Create framebuffer object for the buffer */
w = KMSDRM_gbm_bo_get_width(bo);
h = KMSDRM_gbm_bo_get_height(bo);
stride = KMSDRM_gbm_bo_get_stride(bo);
handle = KMSDRM_gbm_bo_get_handle(bo).u32;
ret = KMSDRM_drmModeAddFB(viddata->drm_fd, w, h, 24, 32, stride, handle,
&fb_info->fb_id);
if (ret) {
SDL_free(fb_info);
return NULL;
}
SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "New DRM FB (%u): %ux%u, stride %u from BO %p",
fb_info->fb_id, w, h, stride, (void *)bo);
/* Associate our DRM framebuffer with this buffer object */
KMSDRM_gbm_bo_set_user_data(bo, fb_info, KMSDRM_FBDestroyCallback);
return fb_info;
}
static void KMSDRM_FlipHandler(int fd, unsigned int frame, unsigned int sec, unsigned int usec, void *data)
{
*((SDL_bool *)data) = SDL_FALSE;
}
SDL_bool KMSDRM_WaitPageflip(SDL_VideoDevice *_this, SDL_WindowData *windata)
{
SDL_VideoData *viddata = _this->driverdata;
drmEventContext ev = { 0 };
struct pollfd pfd = { 0 };
int ret;
ev.version = DRM_EVENT_CONTEXT_VERSION;
ev.page_flip_handler = KMSDRM_FlipHandler;
pfd.fd = viddata->drm_fd;
pfd.events = POLLIN;
/* Stay on the while loop until we get the desired event.
We need the while the loop because we could be in a situation where:
-We get and event on the FD in time, thus not on exiting on return number 1.
-The event is not an error, thus not exiting on return number 2.
-The event is of POLLIN type, but even then, if the event is not a pageflip,
drmHandleEvent() won't unset wait_for_pageflip, so we have to iterate
and go polling again.
If it wasn't for the while loop, we could erroneously exit the function
without the pageflip event to arrive!
For example, vblank events hit the FD and they are POLLIN events too (POLLIN
means "there's data to read on the FD"), but they are not the pageflip event
we are waiting for, so the drmEventHandle() doesn't run the flip handler, and
since waiting_for_flip is set on the pageflip handle, it's not set and we stay
on the loop, until we get the event for the pageflip, which is fine.
*/
while (windata->waiting_for_flip) {
pfd.revents = 0;
/* poll() waits for events arriving on the FD, and returns < 0 if timeout passes
with no events or a signal occurred before any requested event (-EINTR).
We wait forever (timeout = -1), but even if we DO get an event, we have yet
to see if it's of the required type, then if it's a pageflip, etc */
ret = poll(&pfd, 1, -1);
if (ret < 0) {
if (errno == EINTR) {
/* poll() returning < 0 and setting errno = EINTR means there was a signal before
any requested event, so we immediately poll again. */
continue;
} else {
/* There was another error. Don't pull again or we could get into a busy loop. */
SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "DRM poll error");
return SDL_FALSE; /* Return number 1. */
}
}
if (pfd.revents & (POLLHUP | POLLERR)) {
/* An event arrived on the FD in time, but it's an error. */
SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "DRM poll hup or error");
return SDL_FALSE; /* Return number 2. */
}
if (pfd.revents & POLLIN) {
/* There is data to read on the FD!
Is the event a pageflip? We know it is a pageflip if it matches the
event we are passing in &ev. If it does, drmHandleEvent() will unset
windata->waiting_for_flip and we will get out of the "while" loop.
If it's not, we keep iterating on the loop. */
KMSDRM_drmHandleEvent(viddata->drm_fd, &ev);
}
/* If we got to this point in the loop, we may iterate or exit the loop:
-A legit (non-error) event arrived, and it was a POLLING event, and it was consumed
by drmHandleEvent().
-If it was a PAGEFLIP event, waiting_for_flip will be unset by drmHandleEvent()
and we will exit the loop.
-If it wasn't a PAGEFLIP, drmHandleEvent() won't unset waiting_for_flip, so we
iterare back to polling.
-A legit (non-error) event arrived, but it's not a POLLIN event, so it hasn't to be
consumed by drmHandleEvent(), so waiting_for_flip isn't set and we iterate back
to polling. */
}
return SDL_TRUE;
}
/* Given w, h and refresh rate, returns the closest DRM video mode
available on the DRM connector of the display.
We use the SDL mode list (which we filled in KMSDRM_GetDisplayModes)
because it's ordered, while the list on the connector is mostly random.*/
static drmModeModeInfo *KMSDRM_GetClosestDisplayMode(SDL_VideoDisplay *display, int width, int height)
{
SDL_DisplayData *dispdata = display->driverdata;
drmModeConnector *connector = dispdata->connector;
const SDL_DisplayMode *closest;
drmModeModeInfo *drm_mode;
closest = SDL_GetClosestFullscreenDisplayMode(display->id, width, height, 0.0f, SDL_FALSE);
if (closest) {
const SDL_DisplayModeData *modedata = (const SDL_DisplayModeData *)closest->driverdata;
drm_mode = &connector->modes[modedata->mode_index];
return drm_mode;
} else {
return NULL;
}
}
/*****************************************************************************/
/* SDL Video and Display initialization/handling functions */
/* _this is a SDL_VideoDevice * */
/*****************************************************************************/
/* Deinitializes the driverdata of the SDL Displays in the SDL display list. */
static void KMSDRM_DeinitDisplays(SDL_VideoDevice *_this)
{
SDL_DisplayID *displays;
SDL_DisplayData *dispdata;
int i;
displays = SDL_GetDisplays(NULL);
if (displays) {
/* Iterate on the SDL Display list. */
for (i = 0; displays[i]; ++i) {
/* Get the driverdata for this display */
dispdata = SDL_GetDisplayDriverData(displays[i]);
/* Free connector */
if (dispdata && dispdata->connector) {
KMSDRM_drmModeFreeConnector(dispdata->connector);
dispdata->connector = NULL;
}
/* Free CRTC */
if (dispdata && dispdata->crtc) {
KMSDRM_drmModeFreeCrtc(dispdata->crtc);
dispdata->crtc = NULL;
}
}
SDL_free(displays);
}
}
static uint32_t KMSDRM_CrtcGetPropId(uint32_t drm_fd,
drmModeObjectPropertiesPtr props,
char const *name)
{
uint32_t i, prop_id = 0;
for (i = 0; !prop_id && i < props->count_props; ++i) {
drmModePropertyPtr drm_prop =
KMSDRM_drmModeGetProperty(drm_fd, props->props[i]);
if (!drm_prop) {
continue;
}
if (SDL_strcmp(drm_prop->name, name) == 0) {
prop_id = drm_prop->prop_id;
}
KMSDRM_drmModeFreeProperty(drm_prop);
}
return prop_id;
}
static SDL_bool KMSDRM_VrrPropId(uint32_t drm_fd, uint32_t crtc_id, uint32_t *vrr_prop_id)
{
drmModeObjectPropertiesPtr drm_props;
drm_props = KMSDRM_drmModeObjectGetProperties(drm_fd,
crtc_id,
DRM_MODE_OBJECT_CRTC);
if (!drm_props) {
return SDL_FALSE;
}
*vrr_prop_id = KMSDRM_CrtcGetPropId(drm_fd,
drm_props,
"VRR_ENABLED");
KMSDRM_drmModeFreeObjectProperties(drm_props);
return SDL_TRUE;
}
static SDL_bool KMSDRM_ConnectorCheckVrrCapable(uint32_t drm_fd,
uint32_t output_id,
char const *name)
{
uint32_t i;
SDL_bool found = SDL_FALSE;
uint64_t prop_value = 0;
drmModeObjectPropertiesPtr props = KMSDRM_drmModeObjectGetProperties(drm_fd,
output_id,
DRM_MODE_OBJECT_CONNECTOR);
if (!props) {
return SDL_FALSE;
}
for (i = 0; !found && i < props->count_props; ++i) {
drmModePropertyPtr drm_prop = KMSDRM_drmModeGetProperty(drm_fd, props->props[i]);
if (!drm_prop) {
continue;
}
if (SDL_strcasecmp(drm_prop->name, name) == 0) {
prop_value = props->prop_values[i];
found = SDL_TRUE;
}
KMSDRM_drmModeFreeProperty(drm_prop);
}
if (found) {
return prop_value ? SDL_TRUE : SDL_FALSE;
}
return SDL_FALSE;
}
static void KMSDRM_CrtcSetVrr(uint32_t drm_fd, uint32_t crtc_id, SDL_bool enabled)
{
uint32_t vrr_prop_id;
if (!KMSDRM_VrrPropId(drm_fd, crtc_id, &vrr_prop_id)) {
return;
}
KMSDRM_drmModeObjectSetProperty(drm_fd,
crtc_id,
DRM_MODE_OBJECT_CRTC,
vrr_prop_id,
enabled);
}
static SDL_bool KMSDRM_CrtcGetVrr(uint32_t drm_fd, uint32_t crtc_id)
{
uint32_t object_prop_id, vrr_prop_id;
drmModeObjectPropertiesPtr props;
SDL_bool object_prop_value;
int i;
if (!KMSDRM_VrrPropId(drm_fd, crtc_id, &vrr_prop_id)) {
return SDL_FALSE;
}
props = KMSDRM_drmModeObjectGetProperties(drm_fd,
crtc_id,
DRM_MODE_OBJECT_CRTC);
if (!props) {
return SDL_FALSE;
}
for (i = 0; i < props->count_props; ++i) {
drmModePropertyPtr drm_prop = KMSDRM_drmModeGetProperty(drm_fd, props->props[i]);
if (!drm_prop) {
continue;
}
object_prop_id = drm_prop->prop_id;
object_prop_value = props->prop_values[i] ? SDL_TRUE : SDL_FALSE;
KMSDRM_drmModeFreeProperty(drm_prop);
if (object_prop_id == vrr_prop_id) {
return object_prop_value;
}
}
return SDL_FALSE;
}
/* Gets a DRM connector, builds an SDL_Display with it, and adds it to the
list of SDL Displays in _this->displays[] */
static void KMSDRM_AddDisplay(SDL_VideoDevice *_this, drmModeConnector *connector, drmModeRes *resources)
{
SDL_VideoData *viddata = _this->driverdata;
SDL_DisplayData *dispdata = NULL;
SDL_VideoDisplay display = { 0 };
SDL_DisplayModeData *modedata = NULL;
drmModeEncoder *encoder = NULL;
drmModeCrtc *crtc = NULL;
int mode_index;
int i, j;
int ret = 0;
/* Reserve memory for the new display's driverdata. */
dispdata = (SDL_DisplayData *)SDL_calloc(1, sizeof(SDL_DisplayData));
if (!dispdata) {
ret = -1;
goto cleanup;
}
/* Initialize some of the members of the new display's driverdata
to sane values. */
dispdata->cursor_bo = NULL;
dispdata->cursor_bo_drm_fd = -1;
/* Since we create and show the default cursor on KMSDRM_InitMouse(),
and we call KMSDRM_InitMouse() when we create a window, we have to know
if the display used by the window already has a default cursor or not.
If we don't, new default cursors would stack up on mouse->cursors and SDL
would have to hide and delete them at quit, not to mention the memory leak... */
dispdata->default_cursor_init = SDL_FALSE;
/* Try to find the connector's current encoder */
for (i = 0; i < resources->count_encoders; i++) {
encoder = KMSDRM_drmModeGetEncoder(viddata->drm_fd, resources->encoders[i]);
if (!encoder) {
continue;
}
if (encoder->encoder_id == connector->encoder_id) {
break;
}
KMSDRM_drmModeFreeEncoder(encoder);
encoder = NULL;
}
if (!encoder) {
/* No encoder was connected, find the first supported one */
for (i = 0; i < resources->count_encoders; i++) {
encoder = KMSDRM_drmModeGetEncoder(viddata->drm_fd,
resources->encoders[i]);
if (!encoder) {
continue;
}
for (j = 0; j < connector->count_encoders; j++) {
if (connector->encoders[j] == encoder->encoder_id) {
break;
}
}
if (j != connector->count_encoders) {
break;
}
KMSDRM_drmModeFreeEncoder(encoder);
encoder = NULL;
}
}
if (!encoder) {
ret = SDL_SetError("No connected encoder found for connector.");
goto cleanup;
}
/* Try to find a CRTC connected to this encoder */
crtc = KMSDRM_drmModeGetCrtc(viddata->drm_fd, encoder->crtc_id);
/* If no CRTC was connected to the encoder, find the first CRTC
that is supported by the encoder, and use that. */
if (!crtc) {
for (i = 0; i < resources->count_crtcs; i++) {
if (encoder->possible_crtcs & (1 << i)) {
encoder->crtc_id = resources->crtcs[i];
crtc = KMSDRM_drmModeGetCrtc(viddata->drm_fd, encoder->crtc_id);
break;
}
}
}
if (!crtc) {
ret = SDL_SetError("No CRTC found for connector.");
goto cleanup;
}
/* Find the index of the mode attached to this CRTC */
mode_index = -1;
for (i = 0; i < connector->count_modes; i++) {
drmModeModeInfo *mode = &connector->modes[i];
if (!SDL_memcmp(mode, &crtc->mode, sizeof(crtc->mode))) {
mode_index = i;
break;
}
}
if (mode_index == -1) {
int current_area, largest_area = 0;
/* Find the preferred mode or the highest resolution mode */
for (i = 0; i < connector->count_modes; i++) {
drmModeModeInfo *mode = &connector->modes[i];
if (mode->type & DRM_MODE_TYPE_PREFERRED) {
mode_index = i;
break;
}
current_area = mode->hdisplay * mode->vdisplay;
if (current_area > largest_area) {
mode_index = i;
largest_area = current_area;
}
}
if (mode_index != -1) {
crtc->mode = connector->modes[mode_index];
}
}
if (mode_index == -1) {
ret = SDL_SetError("Failed to find index of mode attached to the CRTC.");
goto cleanup;
}
/*********************************************/
/* Create an SDL Display for this connector. */
/*********************************************/
/*********************************************/
/* Part 1: setup the SDL_Display driverdata. */
/*********************************************/
/* Get the mode currently setup for this display,
which is the mode currently setup on the CRTC
we found for the active connector. */
dispdata->mode = crtc->mode;
dispdata->original_mode = crtc->mode;
dispdata->fullscreen_mode = crtc->mode;
if (dispdata->mode.hdisplay == 0 || dispdata->mode.vdisplay == 0) {
ret = SDL_SetError("Couldn't get a valid connector videomode.");
goto cleanup;
}
/* Store the connector and crtc for this display. */
dispdata->connector = connector;
dispdata->crtc = crtc;
/* save previous vrr state */
dispdata->saved_vrr = KMSDRM_CrtcGetVrr(viddata->drm_fd, crtc->crtc_id);
/* try to enable vrr */
if (KMSDRM_ConnectorCheckVrrCapable(viddata->drm_fd, connector->connector_id, "VRR_CAPABLE")) {
SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Enabling VRR");
KMSDRM_CrtcSetVrr(viddata->drm_fd, crtc->crtc_id, SDL_TRUE);
}
/*****************************************/
/* Part 2: setup the SDL_Display itself. */
/*****************************************/
/* Setup the display.
There's no problem with it being still incomplete. */
modedata = SDL_calloc(1, sizeof(SDL_DisplayModeData));
if (!modedata) {
ret = -1;
goto cleanup;
}
modedata->mode_index = mode_index;
display.driverdata = dispdata;
display.desktop_mode.w = dispdata->mode.hdisplay;
display.desktop_mode.h = dispdata->mode.vdisplay;
display.desktop_mode.refresh_rate = CalculateRefreshRate(&dispdata->mode);
display.desktop_mode.format = SDL_PIXELFORMAT_ARGB8888;
display.desktop_mode.driverdata = modedata;
/* Add the display to the list of SDL displays. */
if (SDL_AddVideoDisplay(&display, SDL_FALSE) == 0) {
ret = -1;
goto cleanup;
}
cleanup:
if (encoder) {
KMSDRM_drmModeFreeEncoder(encoder);
}
if (ret) {
/* Error (complete) cleanup */
if (dispdata) {
if (dispdata->connector) {
KMSDRM_drmModeFreeConnector(dispdata->connector);
dispdata->connector = NULL;
}
if (dispdata->crtc) {
KMSDRM_drmModeFreeCrtc(dispdata->crtc);
dispdata->crtc = NULL;
}
SDL_free(dispdata);
}
}
} /* NOLINT(clang-analyzer-unix.Malloc): If no error `dispdata` is saved in the display */
/* Initializes the list of SDL displays: we build a new display for each
connecter connector we find.
Inoffeensive for VK compatibility, except we must leave the drm_fd
closed when we get to the end of this function.
This is to be called early, in VideoInit(), because it gets us
the videomode information, which SDL needs immediately after VideoInit(). */
static int KMSDRM_InitDisplays(SDL_VideoDevice *_this)
{
SDL_VideoData *viddata = _this->driverdata;
drmModeRes *resources = NULL;
uint64_t async_pageflip = 0;
int ret = 0;
int i;
/* Open /dev/dri/cardNN (/dev/drmN if on OpenBSD version less than 6.9) */
(void)SDL_snprintf(viddata->devpath, sizeof(viddata->devpath), "%s%d",
kmsdrm_dri_cardpath, viddata->devindex);
SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Opening device %s", viddata->devpath);
viddata->drm_fd = open(viddata->devpath, O_RDWR | O_CLOEXEC);
if (viddata->drm_fd < 0) {
ret = SDL_SetError("Could not open %s", viddata->devpath);
goto cleanup;
}
SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Opened DRM FD (%d)", viddata->drm_fd);
/* Get all of the available connectors / devices / crtcs */
resources = KMSDRM_drmModeGetResources(viddata->drm_fd);
if (!resources) {
ret = SDL_SetError("drmModeGetResources(%d) failed", viddata->drm_fd);
goto cleanup;
}
/* Iterate on the available connectors. For every connected connector,
we create an SDL_Display and add it to the list of SDL Displays. */
for (i = 0; i < resources->count_connectors; i++) {
drmModeConnector *connector = KMSDRM_drmModeGetConnector(viddata->drm_fd,
resources->connectors[i]);
if (!connector) {
continue;
}
if (connector->connection == DRM_MODE_CONNECTED && connector->count_modes) {
/* If it's a connected connector with available videomodes, try to add
an SDL Display representing it. KMSDRM_AddDisplay() is purposely void,
so if it fails (no encoder for connector, no valid video mode for
connector etc...) we can keep looking for connected connectors. */
KMSDRM_AddDisplay(_this, connector, resources);
} else {
/* If it's not, free it now. */
KMSDRM_drmModeFreeConnector(connector);
}
}
/* Have we added any SDL displays? */
if (SDL_GetPrimaryDisplay() == 0) {
ret = SDL_SetError("No connected displays found.");
goto cleanup;
}
/* Determine if video hardware supports async pageflips. */
ret = KMSDRM_drmGetCap(viddata->drm_fd, DRM_CAP_ASYNC_PAGE_FLIP, &async_pageflip);
if (ret) {
SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "Could not determine async page flip capability.");
}
viddata->async_pageflip_support = async_pageflip ? SDL_TRUE : SDL_FALSE;
/***********************************/
/* Block for Vulkan compatibility. */
/***********************************/
/* THIS IS FOR VULKAN! Leave the FD closed, so VK can work.
Will reopen this in CreateWindow, but only if requested a non-VK window. */
close(viddata->drm_fd);
viddata->drm_fd = -1;
cleanup:
if (resources) {
KMSDRM_drmModeFreeResources(resources);
}
if (ret) {
if (viddata->drm_fd >= 0) {
close(viddata->drm_fd);
viddata->drm_fd = -1;
}
}
return ret;
}
/* Init the Vulkan-INCOMPATIBLE stuff:
Reopen FD, create gbm dev, create dumb buffer and setup display plane.
This is to be called late, in WindowCreate(), and ONLY if this is not
a Vulkan window.
We are doing this so late to allow Vulkan to work if we build a VK window.
These things are incompatible with Vulkan, which accesses the same resources
internally so they must be free when trying to build a Vulkan surface.
*/
static int KMSDRM_GBMInit(SDL_VideoDevice *_this, SDL_DisplayData *dispdata)
{
SDL_VideoData *viddata = _this->driverdata;
int ret = 0;
/* Reopen the FD! */
viddata->drm_fd = open(viddata->devpath, O_RDWR | O_CLOEXEC);