forked from zillevdr/vdr-plugin-softhddevice-drm
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdrmdevice.cpp
More file actions
1460 lines (1243 loc) · 43.5 KB
/
Copy pathdrmdevice.cpp
File metadata and controls
1460 lines (1243 loc) · 43.5 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
// SPDX-License-Identifier: AGPL-3.0-or-later
/**
* @file drmdevice.cpp
* DRM Device
*
* This file defines cDrmDevice, which keeps some functions
* to interact with the DRM (display) system.
*
* @copyright 2018 by zille. All Rights Reserved.
* @copyright 2025 - 2026 by Andreas Baierl. All Rights Reserved.
*
* @license{AGPL-3.0-or-later}
*/
#include <cerrno>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <cinttypes>
#include <string>
#include <vector>
#include <fcntl.h>
#include <unistd.h>
#ifdef USE_GLES
#include <assert.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#endif
#include <drm_fourcc.h>
#include <xf86drm.h>
#include <xf86drmMode.h>
#include "config.h"
#include "drmdevice.h"
#include "drmplane.h"
#include "logger.h"
#include "videorender.h"
/**
* Create a drm device
*
* @param render pointer to cVideoRender object
* @param config pointer to current plugin configuration
*/
cDrmDevice::cDrmDevice(cVideoRender *render, cSoftHdConfig *config)
: m_pRender(render),
m_pConfig(config),
m_userDrmDevice(m_pConfig->ConfigDrmDevice),
m_userDrmConnector(m_pConfig->ConfigDrmConnector)
{
sDrmMode *drmMode = nullptr;
if (m_pConfig->RequestedDrmMode.width > 0)
drmMode = &m_pConfig->RequestedDrmMode;
else if (m_pConfig->UserSetDrmMode.width > 0)
drmMode = &m_pConfig->UserSetDrmMode;
if (drmMode) {
m_userReqDisplayWidth = drmMode->width;
m_userReqDisplayHeight = drmMode->height;
m_userReqDisplayRefreshRate = drmMode->refreshRateHz;
m_userReqDisplayInterlaced = drmMode->interlaced;
LOGDEBUG("%s requested display mode: %dx%d@%.2f%s", __FUNCTION__,
m_userReqDisplayWidth, m_userReqDisplayHeight, m_userReqDisplayRefreshRate, m_userReqDisplayInterlaced ? "i" : "");
}
if (m_pConfig->ConfigOsdResolution)
sscanf(m_pConfig->ConfigOsdResolution, "%dx%d", &m_userReqOsdWidth, &m_userReqOsdHeight);
}
cDrmDevice::~cDrmDevice(void)
{
LOGDEBUG2(L_DRM, "drmdevice: %s", __FUNCTION__);
}
/** @ingroup drm */
static int get_resources(int fd, drmModeRes **resources)
{
*resources = drmModeGetResources(fd);
if (*resources == NULL) {
LOGERROR("drmdevice: %s: cannot retrieve DRM resources (%d): %m", __FUNCTION__, errno);
return -1;
}
return 0;
}
/**
* Test drm capabilities
*
* @retval 0 if all needed caps match
* @retval 1 on mismatch
*/
static int TestCaps(int fd)
{
uint64_t test;
if (drmGetCap(fd, DRM_CAP_DUMB_BUFFER, &test) < 0 || test == 0)
return 1;
if (drmSetClientCap(fd, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1) != 0)
return 1;
if (drmSetClientCap(fd, DRM_CLIENT_CAP_ATOMIC, 1) != 0)
return 1;
if (drmGetCap(fd, DRM_CAP_PRIME, &test) < 0)
return 1;
if (drmGetCap(fd, DRM_PRIME_CAP_EXPORT, &test) < 0)
return 1;
if (drmGetCap(fd, DRM_PRIME_CAP_IMPORT, &test) < 0)
return 1;
return 0;
}
/**
* Open the given device
*
* @param deviceName name of the device (e.g. "/dev/dri/card0")
*
* @retval file handle on success
* @retval -1 if open failed
*
* @ingroup drm
*/
static int OpenDrmDevice(const char* device, drmModeRes **resources)
{
int fd = -1;
if ((fd = open(device, O_RDWR)) < 0)
return -1;
if (TestCaps(fd) || get_resources(fd, resources)) {
close(fd);
return -1;
}
return fd;
}
/**
* Find and open a suitable device with the wanted capabilities
*
* @return the file descriptor of the opened device
*
* @ingroup drm
*/
static int FindDrmDevice(drmModeRes **resources)
{
int MAX_DRM_DEVICES = 64;
drmDevicePtr devices[MAX_DRM_DEVICES] = { NULL };
int num_devices, fd = -1;
num_devices = drmGetDevices2(0, devices, MAX_DRM_DEVICES);
if (num_devices < 0) {
LOGERROR("drmdevice: %s: drmGetDevices2 failed: %s", __FUNCTION__, strerror(-num_devices));
return fd;
}
for (int i = 0; i < num_devices && fd < 0; i++) {
drmDevicePtr device = devices[i];
int ret;
if (!(device->available_nodes & (1 << DRM_NODE_PRIMARY)))
continue;
fd = open(device->nodes[DRM_NODE_PRIMARY], O_RDWR);
if (fd < 0)
continue;
if (TestCaps(fd)) {
close(fd);
fd = -1;
continue;
}
ret = get_resources(fd, resources);
if (!ret)
break;
close(fd);
fd = -1;
}
drmFreeDevices(devices, num_devices);
if (fd < 0)
LOGERROR("drmdevice: %s: no drm device found!", __FUNCTION__);
return fd;
}
/**
* Returns the connector type name if available
*/
static std::string ConnectorName(drmModeConnector *connector)
{
const char *typeName = drmModeGetConnectorTypeName(connector->connector_type);
return (typeName ? typeName : std::string("Unknown")) + "-" + std::to_string(connector->connector_type_id);
}
/**
* Find a suitable connector, preferably a connected one
*
* Connector selection priority:
* 1) Try user requested connector (-x HDMI-A-1)
* 2) Try suitable connected connector
* 3) Try suitable unconnected connector
*
* @ingroup drm
*/
drmModeConnector *cDrmDevice::FindDrmConnector(int fd, drmModeRes *resources, const char *userRequestedConnector)
{
drmModeConnector *connector = NULL;
int i;
// search for the user requested connector (can be unconnected)
for (i = 0; i < resources->count_connectors && userRequestedConnector; i++) {
connector = drmModeGetConnector(fd, resources->connectors[i]);
if (connector && connector->count_modes > 0) {
if (ConnectorName(connector) == userRequestedConnector)
return connector;
}
drmModeFreeConnector(connector);
connector = NULL;
}
if (userRequestedConnector)
LOGWARNING("drmdevice: %s: cannot open user requested DRM connector %s, try others", __FUNCTION__, userRequestedConnector);
// search for a connected connector
for (i = 0; i < resources->count_connectors; i++) {
connector = drmModeGetConnector(fd, resources->connectors[i]);
if (connector && connector->connection == DRM_MODE_CONNECTED && connector->count_modes > 0)
return connector;
drmModeFreeConnector(connector);
connector = NULL;
}
// search for an unconnected connector, but with available modes
// this is a workaround for RPI: in case we don't have a monitor connected
// we can load an edid file at boot time, where the available modes are listed.
// To bring softhddevice up, we also have to go through the not connected connectors
for (i = 0; i < resources->count_connectors; i++) {
connector = drmModeGetConnector(fd, resources->connectors[i]);
if (connector && connector->count_modes > 0)
return connector;
drmModeFreeConnector(connector);
connector = NULL;
}
// we couldn't find a connector
return connector;
}
/**
* Calculate the refresh rate of the given mode to get the precise value and
* don't use m_drmModeInfo.vrefresh.
*
* @param modeInfo drm mode info
*/
static double GetRefreshRateHz(drmModeModeInfo *modeInfo)
{
return (double)modeInfo->clock * 1000.0 / ((double)modeInfo->htotal * (double)modeInfo->vtotal);
}
/**
* Returns true, if the interlaced flag of the mode is set
*/
static inline bool InterlacedMode(uint32_t flags)
{
return (flags & DRM_MODE_FLAG_INTERLACE) != 0;
}
/**
* Return true, if both values are equivalent within a tolerance
*/
static inline bool AlmostEqual(double a, double b)
{
return std::abs(a - b) < 0.001;
}
/**
* Test, if the given mode is included in the given array
*
* Only width, height, refresh rate and the interlaced flag is tested.
* Other flags and values are ignored.
*
* @param mode mode info of the mode
* @param modes mode array to search in
*
* @retval true if the mode is included
* @retval false if the mode is not included
*
* @ingroup drm
*/
static bool Contains(drmModeModeInfo *mode, std::vector<sDrmMode> modes)
{
for (size_t i = 0; i < modes.size(); i++) {
bool interlaced = InterlacedMode(mode->flags);
if (mode->hdisplay != modes[i].width ||
mode->vdisplay != modes[i].height ||
!AlmostEqual(GetRefreshRateHz(mode), modes[i].refreshRateHz) ||
interlaced != modes[i].interlaced) {
continue;
}
return true;
}
return false;
}
/**
* Return true, if the given mode is one of the collected ones
*/
bool cDrmDevice::CanHandleMode(sDrmMode *mode)
{
std::vector<sDrmMode> modes = m_pConfig->CollectedDrmModes;
// sometimes the stream has no framerate, use 50.00 as default
double refreshRateHz = mode->refreshRateHz ? mode->refreshRateHz : 50.00;
if (!mode->refreshRateHz && mode->interlaced)
refreshRateHz /= 2;
for (size_t i = 0; i < modes.size(); i++) {
if (mode->width != modes[i].width ||
mode->height != modes[i].height ||
!AlmostEqual(refreshRateHz, modes[i].refreshRateHz) ||
mode->interlaced != modes[i].interlaced) {
continue;
}
return true;
}
LOGDEBUG2(L_DRM, "drmdevice: %s: can't handle mode %dx%d@%.2f%s", __FUNCTION__,
mode->width, mode->height, mode->refreshRateHz,
mode->interlaced ? "i" : "");
return false;
}
/**
* Initiate the drm device
*
* 1) Try to open the user requested device (with -o /dev/dri/cardX)
* 2) On error or if not set, find a any suitable device
* 3) Find a connector (priority: user requested, connected, unconnected)
* 4) Find a connector mode
* 5) Find crtc encoder
* 6) Find suitable planes for video (NV12), OSD (ARGB) and PiP (NV12)
* 7) Init GBM
* 8) Init EGL
*
* @retval 0 on success
* @retval -errno on error
*/
int cDrmDevice::Init(void)
{
drmModeRes *resources = nullptr;
drmModeConnector *connector;
drmModeEncoder *encoder = nullptr;
drmModePlane *plane;
drmModePlaneRes *planeRes;
int i;
uint32_t j, k;
// first try to open the user given drm device
if (m_userDrmDevice) {
LOGDEBUG2(L_DRM, "drmdevice: %s: Try open user requested device %s", __FUNCTION__, m_userDrmDevice);
m_fdDrm = OpenDrmDevice(m_userDrmDevice, &resources);
}
// if manually set device failed, try to find a drm device
if (m_fdDrm < 0) {
if (m_userDrmDevice)
LOGWARNING("drmdevice: %s: Could not open user requested device %s, try other devices!", __FUNCTION__, m_userDrmDevice);
m_fdDrm = FindDrmDevice(&resources);
}
if (m_fdDrm < 0) {
LOGERROR("drmdevice: %s: Could not open device!", __FUNCTION__);
return -1;
}
LOGDEBUG2(L_DRM, "drmdevice: %s: fd: %d DRM have %i connectors, %i crtcs, %i encoders", __FUNCTION__,
m_fdDrm, resources->count_connectors, resources->count_crtcs,
resources->count_encoders);
// find a connector
connector = FindDrmConnector(m_fdDrm, resources, m_userDrmConnector);
if (!connector) {
LOGERROR("drmdevice: %s: cannot retrieve DRM connector (%d): %m", __FUNCTION__, errno);
return -errno;
}
m_connectorId = connector->connector_id;
m_connectorName = ConnectorName(connector);
bool connected = connector->connection == DRM_MODE_CONNECTED;
// fill config with available connector modes for later selection from setup menu
m_pConfig->CollectedDrmModes.clear();
for (i = 0; i < connector->count_modes; i++) {
drmModeModeInfo *current_mode = &connector->modes[i];
std::vector<sDrmMode> drmModeWhitelist(DrmModeWhitelist.begin(), DrmModeWhitelist.end());
if (!Contains(current_mode, drmModeWhitelist))
continue;
if (Contains(current_mode, m_pConfig->CollectedDrmModes))
continue;
m_pConfig->CollectedDrmModes.push_back({current_mode->hdisplay,
current_mode->vdisplay,
GetRefreshRateHz(current_mode),
InterlacedMode(current_mode->flags)});
LOGDEBUG2(L_DRM, "drmdevice: %s: adding display mode %dx%d@%.2f%s", __FUNCTION__,
current_mode->hdisplay, current_mode->vdisplay, GetRefreshRateHz(current_mode),
InterlacedMode(current_mode->flags) ? "i" : "");
}
// find connector mode
if (FindMode())
return -1;
m_pRender->SetOsdSize(OsdWidth(), OsdHeight());
// find encoder
for (i = 0; i < resources->count_encoders; i++) {
encoder = drmModeGetEncoder(m_fdDrm, resources->encoders[i]);
if (encoder->encoder_id == connector->encoder_id)
break;
drmModeFreeEncoder(encoder);
encoder = NULL;
}
if (encoder) {
m_crtcId = encoder->crtc_id;
LOGDEBUG2(L_DRM, "drmdevice: %s: have encoder, m_crtcId %d", __FUNCTION__, m_crtcId);
} else {
int32_t crtc_id = FindCrtcForConnector(resources, connector);
if (crtc_id == -1) {
LOGERROR("drmdevice: %s: No crtc found!", __FUNCTION__);
return -errno;
}
m_crtcId = crtc_id;
LOGDEBUG2(L_DRM, "drmdevice: %s: have no encoder, m_crtcId %d", __FUNCTION__, m_crtcId);
}
for (i = 0; i < resources->count_crtcs; i++) {
if (resources->crtcs[i] == m_crtcId) {
m_crtcIndex = i;
break;
}
}
m_hdrMetadata = GetPropertyID(m_connectorId, DRM_MODE_OBJECT_CONNECTOR, "HDR_OUTPUT_METADATA");
if (m_hdrMetadata != 0)
LOGDEBUG2(L_DRM, "drmdevice: %s: HDR output metadata ID %d in connector %d", __FUNCTION__, m_hdrMetadata, m_connectorId);
LOGINFO("DRM Setup: Using Monitor Mode %dx%d@%.2fHz on %s (%s), m_crtcId %d crtc_idx %d",
m_drmModeInfo.hdisplay, m_drmModeInfo.vdisplay, GetRefreshRateHz(&m_drmModeInfo), m_connectorName.c_str(), connected ? "connected" : "not connected", m_crtcId, m_crtcIndex);
drmModeFreeConnector(connector);
// find planes
if ((planeRes = drmModeGetPlaneResources(m_fdDrm)) == NULL) {
LOGERROR("drmdevice: %s: cannot retrieve PlaneResources (%d): %m", __FUNCTION__, errno);
return -1;
}
// test and list the local planes
cDrmPlane best_primary_video_plane; // NV12 capable primary plane with the lowest plane_id
cDrmPlane best_overlay_video_plane; // NV12 capable overlay plane with the lowest plane_id
cDrmPlane best_primary_osd_plane; // AR24 capable primary plane with the highest plane_id
cDrmPlane best_overlay_osd_plane; // AR24 capable overlay plane with the highest plane_id
// collect candidates for pip (NV12 overlay plane). The best one is chosen after we decided which
// planes are used for video and osd
std::vector<cDrmPlane> overlayNV12Candidates;
for (j = 0; j < planeRes->count_planes; j++) {
plane = drmModeGetPlane(m_fdDrm, planeRes->planes[j]);
if (plane == NULL) {
LOGERROR("drmdevice: %s: cannot query DRM-KMS plane %d", __FUNCTION__, j);
continue;
}
uint64_t type = 0;
uint64_t zpos = 0;
char pixelformats[256];
if (plane->possible_crtcs & (1 << m_crtcIndex)) {
if (GetPropertyValue(planeRes->planes[j], DRM_MODE_OBJECT_PLANE, "type", &type)) {
LOGDEBUG2(L_DRM, "drmdevice: %s: Failed to get property 'type'", __FUNCTION__);
}
if (GetPropertyValue(planeRes->planes[j], DRM_MODE_OBJECT_PLANE, "zpos", &zpos)) {
LOGDEBUG2(L_DRM, "drmdevice: %s: Failed to get property 'zpos'", __FUNCTION__);
} else {
m_useZpos = true;
}
LOGDEBUG2(L_DRM, "drmdevice: %s: %s: id %i possible_crtcs %i", __FUNCTION__,
(type == DRM_PLANE_TYPE_PRIMARY) ? "PRIMARY " :
(type == DRM_PLANE_TYPE_OVERLAY) ? "OVERLAY " :
(type == DRM_PLANE_TYPE_CURSOR) ? "CURSOR " : "UNKNOWN",
plane->plane_id, plane->possible_crtcs);
strcpy(pixelformats, " ");
// test pixel format and plane caps
for (k = 0; k < plane->count_formats; k++) {
if (encoder->possible_crtcs & plane->possible_crtcs) {
char tmp[10];
switch (plane->formats[k]) {
case DRM_FORMAT_NV12:
snprintf(tmp, sizeof(tmp), " %4.4s", (char *)&plane->formats[k]);
strcat(pixelformats, tmp);
if (type == DRM_PLANE_TYPE_PRIMARY && !best_primary_video_plane.GetId()) {
best_primary_video_plane.SetId(plane->plane_id);
best_primary_video_plane.SetType(type);
best_primary_video_plane.SetZpos(zpos);
strcat(pixelformats, "! ");
}
if (type == DRM_PLANE_TYPE_OVERLAY && !best_overlay_video_plane.GetId()) {
best_overlay_video_plane.SetId(plane->plane_id);
best_overlay_video_plane.SetType(type);
best_overlay_video_plane.SetZpos(zpos);
strcat(pixelformats, "! ");
}
// store overlay NV12 plane as a candidate for pip
if (type == DRM_PLANE_TYPE_OVERLAY) {
cDrmPlane cand;
cand.SetId(plane->plane_id);
cand.SetType(type);
cand.SetZpos(zpos);
overlayNV12Candidates.push_back(cand);
}
break;
case DRM_FORMAT_ARGB8888:
snprintf(tmp, sizeof(tmp), " %4.4s", (char *)&plane->formats[k]);
strcat(pixelformats, tmp);
if (type == DRM_PLANE_TYPE_PRIMARY) {
best_primary_osd_plane.SetId(plane->plane_id);
best_primary_osd_plane.SetType(type);
best_primary_osd_plane.SetZpos(zpos);
strcat(pixelformats, "! ");
}
if (type == DRM_PLANE_TYPE_OVERLAY) {
best_overlay_osd_plane.SetId(plane->plane_id);
best_overlay_osd_plane.SetType(type);
best_overlay_osd_plane.SetZpos(zpos);
strcat(pixelformats, "! ");
}
break;
default:
break;
}
}
}
LOGDEBUG2(L_DRM, "drmdevice: %s", __FUNCTION__, pixelformats);
}
drmModeFreePlane(plane);
}
// See which planes we should use for video and osd
if (best_primary_video_plane.GetId() && best_overlay_osd_plane.GetId()) {
m_videoPlane.SetId(best_primary_video_plane.GetId());
m_videoPlane.SetType(best_primary_video_plane.GetType());
m_zposPrimary = best_primary_video_plane.GetZpos();
m_videoPlane.SetZpos(m_zposPrimary);
m_osdPlane.SetId(best_overlay_osd_plane.GetId());
m_osdPlane.SetType(best_overlay_osd_plane.GetType());
m_zposOverlay = best_overlay_osd_plane.GetZpos();
m_osdPlane.SetZpos(m_zposOverlay);
} else if (best_overlay_video_plane.GetId() && best_primary_osd_plane.GetId()) {
m_videoPlane.SetId(best_overlay_video_plane.GetId());
m_videoPlane.SetType(best_overlay_video_plane.GetType());
m_zposOverlay = best_overlay_video_plane.GetZpos();
m_videoPlane.SetZpos(m_zposOverlay);
m_osdPlane.SetId(best_primary_osd_plane.GetId());
m_osdPlane.SetType(best_primary_osd_plane.GetType());
m_zposPrimary = best_primary_osd_plane.GetZpos();
m_osdPlane.SetZpos(m_zposPrimary);
m_useZpos = true;
} else {
LOGERROR("drmdevice: %s: No suitable planes found!", __FUNCTION__);
return -1;
}
// now pick the best pip plane from the NV12 overlay candidates we collected above
cDrmPlane best_overlay_pip_plane;
for (cDrmPlane &cand : overlayNV12Candidates) {
uint32_t pid = cand.GetId();
if (pid == m_videoPlane.GetId() || pid == m_osdPlane.GetId())
continue;
if (!best_overlay_pip_plane.GetId() || pid > best_overlay_pip_plane.GetId()) {
best_overlay_pip_plane = cand;
}
}
if (best_overlay_pip_plane.GetId()) {
m_pipPlane.SetId(best_overlay_pip_plane.GetId());
m_pipPlane.SetType(best_overlay_pip_plane.GetType());
m_zposPip = best_overlay_pip_plane.GetZpos();
m_pipPlane.SetZpos(m_zposPip);
} else {
LOGWARNING("drmdevice: %s: No suitable plane for Picture-in-Picture found. PIP will be disabled.", __FUNCTION__);
}
// debug output
if (best_primary_video_plane.GetId()) {
LOGDEBUG2(L_DRM, "drmdevice: %s: best_primary_video_plane: plane_id %d, type %s, zpos %" PRIu64 "", __FUNCTION__,
best_primary_video_plane.GetId(), best_primary_video_plane.GetType() == DRM_PLANE_TYPE_PRIMARY ? "PRIMARY" : "OVERLAY", best_primary_video_plane.GetZpos());
}
if (best_overlay_video_plane.GetId()) {
LOGDEBUG2(L_DRM, "drmdevice: %s: best_overlay_video_plane: plane_id %d, type %s, zpos %" PRIu64 "", __FUNCTION__,
best_overlay_video_plane.GetId(), best_overlay_video_plane.GetType() == DRM_PLANE_TYPE_PRIMARY ? "PRIMARY" : "OVERLAY", best_overlay_video_plane.GetZpos());
}
if (best_primary_osd_plane.GetId()) {
LOGDEBUG2(L_DRM, "drmdevice: %s: best_primary_osd_plane: plane_id %d, type %s, zpos %" PRIu64 "", __FUNCTION__,
best_primary_osd_plane.GetId(), best_primary_osd_plane.GetType() == DRM_PLANE_TYPE_PRIMARY ? "PRIMARY" : "OVERLAY", best_primary_osd_plane.GetZpos());
}
if (best_overlay_osd_plane.GetId()) {
LOGDEBUG2(L_DRM, "drmdevice: %s: best_overlay_osd_plane: plane_id %d, type %s, zpos %" PRIu64 "", __FUNCTION__,
best_overlay_osd_plane.GetId(), best_overlay_osd_plane.GetType() == DRM_PLANE_TYPE_PRIMARY ? "PRIMARY" : "OVERLAY", best_overlay_osd_plane.GetZpos());
}
if (best_overlay_pip_plane.GetId()) {
LOGDEBUG2(L_DRM, "drmdevice: %s: best_overlay_pip_plane: plane_id %d, type %s, zpos %" PRIu64 "", __FUNCTION__,
best_overlay_pip_plane.GetId(), best_overlay_pip_plane.GetType() == DRM_PLANE_TYPE_PRIMARY ? "PRIMARY" : "OVERLAY", best_overlay_pip_plane.GetZpos());
}
// fill the plane's properties to speed up SetPropertyRequest later
m_videoPlane.FillProperties(m_fdDrm);
m_osdPlane.FillProperties(m_fdDrm);
if (m_pipPlane.GetId())
m_pipPlane.FillProperties(m_fdDrm);
// Check, if we can set z-order (meson and rpi have fixed z-order, which cannot be changed)
if (m_useZpos && !m_videoPlane.HasZpos(m_fdDrm)) {
m_useZpos = false;
}
if (m_useZpos && !m_osdPlane.HasZpos(m_fdDrm)) {
m_useZpos = false;
}
if (m_useZpos && m_pipPlane.GetId() && !m_pipPlane.HasZpos(m_fdDrm)) {
m_useZpos = false;
}
// m_useZpos was set, if video is on OVERLAY, and osd is on PRIMARY
// Check if the OVERLAY plane really got a higher zpos than the PRIMARY plane
// If not, change their zpos values or hardcode them to
// 1 OVERLAY (Video)
// 0 PRIMARY (Osd)
if (m_useZpos && m_zposOverlay <= m_zposPrimary) {
char str_zpos[256];
strcpy(str_zpos, "drmdevice: Init: zpos values are wrong, so ");
if (m_zposOverlay == m_zposPrimary) {
// is this possible?
strcat(str_zpos, "hardcode them to 0 and 1, because they are equal");
m_zposPrimary = 0;
m_zposOverlay = 1;
} else {
strcat(str_zpos, "switch them");
uint64_t zpos_tmp = m_zposPrimary;
m_zposPrimary = m_zposOverlay;
m_zposOverlay = zpos_tmp;
}
LOGDEBUG2(L_DRM, "%s", str_zpos);
}
if (drmSetMaster(m_fdDrm) < 0) {
LOGDEBUG2(L_DRM, "drmdevice: Failed to set drm master, try authorize instead: {}", strerror(errno));
drm_magic_t magic;
if (drmGetMagic(m_fdDrm, &magic) < 0)
LOGFATAL("drmdevice: Failed to get drm magic: {}", strerror(errno));
if (drmAuthMagic(m_fdDrm, magic) < 0)
LOGFATAL("drmdevice: Failed to authorize drm magic: {}", strerror(errno));
}
drmModeFreePlaneResources(planeRes);
drmModeFreeEncoder(encoder);
drmModeFreeResources(resources);
if (m_pipPlane.GetId()) {
LOGINFO("DRM setup - CRTC: %i video_plane: %i (%s %" PRIu64 ") osd_plane: %i (%s %" PRIu64 ") pip_plane: %i (%s %" PRIu64 ") m_useZpos: %d",
m_crtcId,
m_videoPlane.GetId(),
m_videoPlane.GetType() == DRM_PLANE_TYPE_PRIMARY ? "PRIMARY" : "OVERLAY",
m_videoPlane.GetZpos(),
m_osdPlane.GetId(),
m_osdPlane.GetType() == DRM_PLANE_TYPE_PRIMARY ? "PRIMARY" : "OVERLAY",
m_osdPlane.GetZpos(),
m_pipPlane.GetId(),
m_pipPlane.GetType() == DRM_PLANE_TYPE_PRIMARY ? "PRIMARY" : "OVERLAY",
m_pipPlane.GetZpos(),
m_useZpos);
} else {
LOGINFO("DRM setup - CRTC: %i video_plane: %i (%s %" PRIu64 ") osd_plane: %i (%s %" PRIu64 ") m_useZpos: %d (pip disbled)",
m_crtcId,
m_videoPlane.GetId(),
m_videoPlane.GetType() == DRM_PLANE_TYPE_PRIMARY ? "PRIMARY" : "OVERLAY",
m_videoPlane.GetZpos(),
m_osdPlane.GetId(),
m_osdPlane.GetType() == DRM_PLANE_TYPE_PRIMARY ? "PRIMARY" : "OVERLAY",
m_osdPlane.GetZpos(),
m_useZpos);
}
return 0;
}
/**
* Find a suitable mode from the current connector
*
* Mode selection priority:
* 1) user requested
* 2) progressive mode with biggest width@50Hz
* 3) progressive mode with biggest width@60Hz
* 4) progressive mode with biggest width@anyHz
*/
int cDrmDevice::FindMode(void)
{
drmModeConnector *connector = drmModeGetConnector(m_fdDrm, m_connectorId);
drmModeModeInfo *drmmode = nullptr;
// find the user requested mode
if (m_userReqDisplayWidth > 0) {
for (int i = 0; i < connector->count_modes; i++) {
drmModeModeInfo *current_mode = &connector->modes[i];
if(current_mode->hdisplay == m_userReqDisplayWidth &&
current_mode->vdisplay == m_userReqDisplayHeight &&
AlmostEqual(GetRefreshRateHz(current_mode), m_userReqDisplayRefreshRate) &&
InterlacedMode(current_mode->flags) == m_userReqDisplayInterlaced) {
drmmode = current_mode;
LOGDEBUG2(L_DRM, "drmdevice: %s: Use user requested mode: %dx%d@%.2f%s", __FUNCTION__,
drmmode->hdisplay, drmmode->vdisplay, GetRefreshRateHz(drmmode), InterlacedMode(drmmode->flags) ? "i" : "");
break;
}
}
if (!drmmode)
LOGWARNING("drmdevice: %s: User requested mode not found, try default modes", __FUNCTION__);
}
double preferredHz[3] = {50.0, 60.0, 0.0};
// find the highest resolution (progressive) mode with 50, 60 or any refresh rate
if (!drmmode) {
int j = 0;
while (!drmmode && preferredHz[j]) {
for (int i = 0, width = 0; i < connector->count_modes; i++) {
drmModeModeInfo *current_mode = &connector->modes[i];
if (InterlacedMode(current_mode->flags))
continue;
if (preferredHz[j] && std::round(GetRefreshRateHz(current_mode) * 100.0) / 100.0 != preferredHz[j])
continue;
int current_width = current_mode->hdisplay;
if (current_width > width) {
drmmode = current_mode;
width = current_width;
}
}
j++;
}
if (drmmode)
LOGDEBUG2(L_DRM, "drmdevice: %s: Use mode with the biggest width: %dx%d@%.2f", __FUNCTION__,
drmmode->hdisplay, drmmode->vdisplay, GetRefreshRateHz(drmmode));
}
if (drmmode)
memcpy(&m_drmModeInfo, drmmode, sizeof(drmModeModeInfo));
drmModeFreeConnector(connector);
if (!drmmode) {
LOGERROR("drmdevice: %s: No monitor mode found! Probably no monitor connected, giving up!", __FUNCTION__);
return -1;
}
m_pConfig->CurrentDrmMode = {
m_drmModeInfo.hdisplay,
m_drmModeInfo.vdisplay,
GetRefreshRateHz(&m_drmModeInfo),
InterlacedMode(m_drmModeInfo.flags)
};
if (!m_pConfig->AutoDetectedDrmMode.width)
m_pConfig->AutoDetectedDrmMode = m_pConfig->CurrentDrmMode;
m_pRender->SetScreenSize(m_drmModeInfo.hdisplay, m_drmModeInfo.vdisplay, GetRefreshRateHz(&m_drmModeInfo), InterlacedMode(drmmode->flags));
return 0;
}
/**
* Re-Init the drm device with a new connector mode
*
* Mode selection priority:
* 1) selected mode from setup menu or mode depending on video resolution (RequestedDrmMode)
* 2) command line requested mode (UserSetDrmMode)
* 3) other suitable mode:
* - mode with biggest width@50Hz
* - mode with biggest width@60Hz
* - mode with biggest width@anyHz
*/
int cDrmDevice::ReInit(void)
{
sDrmMode *drmMode = nullptr;
if (m_pConfig->RequestedDrmMode.width > 0)
drmMode = &m_pConfig->RequestedDrmMode;
else if (m_pConfig->UserSetDrmMode.width > 0)
drmMode = &m_pConfig->UserSetDrmMode;
if (drmMode) {
m_userReqDisplayWidth = drmMode->width;
m_userReqDisplayHeight = drmMode->height;
m_userReqDisplayRefreshRate = drmMode->refreshRateHz;
m_userReqDisplayInterlaced = drmMode->interlaced;
LOGDEBUG("%s requested display mode: %dx%d@%.2f%s", __FUNCTION__,
m_userReqDisplayWidth, m_userReqDisplayHeight, m_userReqDisplayRefreshRate, m_userReqDisplayInterlaced ? "i" : "");
}
return FindMode();
}
#ifdef USE_GLES
/**
* Init gbm device and surface
*
* @retval 0 on success
* @retval -1 on error
*/
int cDrmDevice::InitGbm(void)
{
int w = OsdWidth();
int h = OsdHeight();
uint32_t format = DRM_FORMAT_ARGB8888;
uint64_t modifier = GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING;
m_pGbmDevice = gbm_create_device(m_fdDrm);
if (!m_pGbmDevice) {
LOGERROR("drmdevice: %s: failed to create gbm device!", __FUNCTION__);
return -1;
}
m_pGbmSurface = gbm_surface_create(m_pGbmDevice, w, h, format, modifier);
if (!m_pGbmSurface) {
gbm_device_destroy(m_pGbmDevice);
LOGERROR("drmdevice: %s: failed to create %d x %d surface bo", __FUNCTION__, w, h);
return -1;
}
return 0;
}
/**
* Free gbm device and surface
*/
void cDrmDevice::ExitGbm(void)
{
if (m_pGbmSurface) {
gbm_surface_destroy(m_pGbmSurface);
m_pGbmSurface = nullptr;
}
if (m_pGbmDevice) {
gbm_device_destroy(m_pGbmDevice);
m_pGbmDevice = nullptr;
}
}
PFNEGLGETPLATFORMDISPLAYEXTPROC get_platform_display = NULL;
PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC get_platform_surface = NULL;
/** @ingroup drm */
static const EGLint context_attribute_list[] =
{
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
/**
* Get a suitable EGLConfig
*
* @ingroup drm
*/
EGLConfig cDrmDevice::GetEGLConfig(void)
{
EGLint config_attribute_list[] = {
EGL_BUFFER_SIZE, 32,
EGL_STENCIL_SIZE, EGL_DONT_CARE,
EGL_DEPTH_SIZE, EGL_DONT_CARE,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_NONE
};
EGLConfig *configs = nullptr;
EGLint matched = 0;
EGLint count = 0;
EGL_CHECK(eglGetConfigs(m_eglDisplay, NULL, 0, &count));
if (count < 1)
LOGFATAL("drmdevice: %s: no EGL configs to choose from", __FUNCTION__);
LOGDEBUG2(L_OPENGL, "drmdevice: %s: %d EGL configs found", __FUNCTION__, count);
configs = (EGLConfig *)malloc(count * sizeof(*configs));
if (!configs)
LOGFATAL("drmdevice: %s: can't allocate space for EGL configs", __FUNCTION__);
EGL_CHECK(eglChooseConfig(m_eglDisplay, config_attribute_list, configs, count, &matched));
if (!matched) {
free(configs);
LOGFATAL("drmdevice: %s: no EGL configs with appropriate attributes", __FUNCTION__);
}
LOGDEBUG2(L_OPENGL, "drmdevice: %s: %d appropriate EGL configs found, which match attributes", __FUNCTION__, matched);
EGLConfig chosen = NULL;
for (int i = 0; i < matched; ++i) {
EGLint gbm_format;
EGL_CHECK(eglGetConfigAttrib(m_eglDisplay, configs[i], EGL_NATIVE_VISUAL_ID, &gbm_format));
if (gbm_format == GBM_FORMAT_ARGB8888) {
chosen = configs[i];
break;
}
}
free(configs);
if (chosen == NULL)
LOGFATAL("drmdevice: %s: no matching gbm config found", __FUNCTION__);
return chosen;
}
/**
* Init EGL context
*
* @retval 0 on success
* @retval -1 on error
*/
int cDrmDevice::InitEGL(void)
{
EGLint iMajorVersion, iMinorVersion;
PFNEGLGETPLATFORMDISPLAYEXTPROC get_platform_display = (PFNEGLGETPLATFORMDISPLAYEXTPROC)eglGetProcAddress("eglGetPlatformDisplayEXT");
assert(get_platform_display != NULL);
PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC get_platform_surface = (PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC)eglGetProcAddress("eglCreatePlatformWindowSurfaceEXT");
assert(get_platform_surface != NULL);
EGL_CHECK(m_eglDisplay = get_platform_display(EGL_PLATFORM_GBM_KHR, m_pGbmDevice, NULL));
if (!m_eglDisplay) {
LOGERROR("drmdevice: %s: failed to get eglDisplay", __FUNCTION__);
return -1;
}
if (!eglInitialize(m_eglDisplay, &iMajorVersion, &iMinorVersion)) {
LOGERROR("drmdevice: %s: eglInitialize failed", __FUNCTION__);
return -1;
}
LOGDEBUG2(L_OPENGL, "drmdevice: %s: Using display %p with EGL version %d.%d", __FUNCTION__, m_eglDisplay, iMajorVersion, iMinorVersion);
EGL_CHECK(LOGDEBUG2(L_OPENGL, " EGL Version: \"%s\"", eglQueryString(m_eglDisplay, EGL_VERSION)));
EGL_CHECK(LOGDEBUG2(L_OPENGL, " EGL Vendor: \"%s\"", eglQueryString(m_eglDisplay, EGL_VENDOR)));
EGL_CHECK(LOGDEBUG2(L_OPENGL, " EGL Extensions: \"%s\"", eglQueryString(m_eglDisplay, EGL_EXTENSIONS)));
EGL_CHECK(LOGDEBUG2(L_OPENGL, " EGL APIs: \"%s\"", eglQueryString(m_eglDisplay, EGL_CLIENT_APIS)));
EGLConfig eglConfig = GetEGLConfig();
EGL_CHECK(eglBindAPI(EGL_OPENGL_ES_API));
EGL_CHECK(m_eglContext = eglCreateContext(m_eglDisplay, eglConfig, EGL_NO_CONTEXT, context_attribute_list));
if (!m_eglContext) {
LOGERROR("drmdevice: %s: failed to create eglContext", __FUNCTION__);
return -1;
}
EGL_CHECK(m_eglSurface = get_platform_surface(m_eglDisplay, eglConfig, m_pGbmSurface, NULL));
if (m_eglSurface == EGL_NO_SURFACE) {
LOGERROR("drmdevice: %s: failed to create eglSurface", __FUNCTION__);
return -1;
}
EGLint s_width, s_height;
EGL_CHECK(eglQuerySurface(m_eglDisplay, m_eglSurface, EGL_WIDTH, &s_width));
EGL_CHECK(eglQuerySurface(m_eglDisplay, m_eglSurface, EGL_HEIGHT, &s_height));
LOGDEBUG2(L_OPENGL, "drmdevice: %s: GLSurface %p on EGLDisplay %p for %d x %d BO created", __FUNCTION__, m_eglSurface, m_eglDisplay, s_width, s_height);