forked from zillevdr/vdr-plugin-softhddevice-drm
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathvideorender.cpp
More file actions
1641 lines (1376 loc) · 48.6 KB
/
Copy pathvideorender.cpp
File metadata and controls
1641 lines (1376 loc) · 48.6 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 videorender.cpp
* Video Renderer (Display)
*
* This file defines cVideoRender, which includes all methods to
* bring the video and osd to display.
*
* @copyright 2009 - 2015 by Johns. All Rights Reserved.
* @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 <chrono>
#include <cinttypes>
#include <cstdint>
#include <mutex>
#include <vector>
#ifdef USE_GLES
#include <assert.h>
#include <gbm.h>
#include <EGL/egl.h>
#endif
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavutil/hwcontext_drm.h>
}
#include <drm_fourcc.h>
#include <vdr/osd.h>
#include <vdr/thread.h>
#include <xf86drmMode.h>
#include "audio.h"
#include "config.h"
#include "drmdevice.h"
#include "drmhdr.h"
#include "grab.h"
#include "logger.h"
#include "misc.h"
#include "queue.h"
#include "softhddevice.h"
#include "statemachine.h"
#include "videorender.h"
#include "videostream.h"
/**
* Create the video renderer
*
* @param device pointer to cSoftHdDevice
*/
cVideoRender::cVideoRender(cSoftHdDevice *device)
: cThread("softhd display"),
m_pDevice(device),
m_pAudio(m_pDevice->Audio()),
m_pConfig(m_pDevice->Config()),
m_grabOsd("OSD"),
m_grabVideo("VIDEO"),
m_grabPip("PIP"),
m_pDrmDevice(new cDrmDevice(this, m_pConfig)),
m_pHdrMetadata(this),
m_enableHdr(m_pConfig->ConfigVideoEnableHDR)
{
#ifdef USE_GLES
m_disableOglOsd = m_pConfig->ConfigDisableOglOsd;
m_bo = nullptr;
m_pNextBo = nullptr;
m_pOldBo = nullptr;
#endif
m_timebase = av_make_q(1, 90000);
SetPipSize(m_pConfig->ConfigPipUseAlt);
}
/**
* Destroy the video renderer
*/
cVideoRender::~cVideoRender(void)
{
LOGDEBUG2(L_DRM, "videorender: %s", __FUNCTION__);
Stop();
delete m_pDrmDevice;
}
/**
* Clear (empty) the decoder to display queue
*/
void cVideoRender::ClearDecoderToDisplayQueue(void)
{
m_drmBufferQueue.Clear();
m_drmBufferPool.DestroyAllExcept(m_pCurrentlyDisplayed);
if (m_pCurrentlyDisplayed)
m_pCurrentlyDisplayed->SetDestroyAfterUse(true);
}
/**
* Clear (empty) the decoder to display queue
*/
void cVideoRender::ClearPipDecoderToDisplayQueue(void)
{
m_pipDrmBufferQueue.Clear();
m_pipDrmBufferPool.DestroyAllExcept(nullptr);
m_pCurrentlyPipDisplayed = nullptr;
}
/** @ingroup render */
struct sRect {
uint64_t x;
uint64_t y;
uint64_t w;
uint64_t h;
};
/**
* Fits the video frame into a given area
*
* @param frame AVFrame with frame dimensions and aspect ratio information
* @param dispX x offset of video area
* @param dispY y offset of video area
* @param dispWidth width of video area
* @param dispHeight height of video area
*
* @return the new computed video area or the given area if no frame was given
*/
static sRect ComputeFittedRect(AVFrame *frame, uint64_t dispX, uint64_t dispY, uint64_t dispWidth, uint64_t dispHeight)
{
if (!frame || dispWidth == 0 || dispHeight == 0)
return { dispX, dispY, dispWidth, dispHeight };
double frameWidth = frame->width > 0 ? frame->width : 1.0;
double frameHeight = frame->height > 0 ? frame->height : 1.0;
double frameSar = av_q2d(frame->sample_aspect_ratio) ? av_q2d(frame->sample_aspect_ratio) : 1.0;
double dispAspect = static_cast<double>(dispWidth) / static_cast<double>(dispHeight);
double frameAspect = frameWidth / frameHeight * frameSar;
double picWidthD = dispWidth;
double picHeightD = dispHeight;
if (dispAspect > frameAspect) {
// letterbox horizontally (frame narrower than display)
picWidthD = dispHeight * frameAspect;
if (picWidthD <= 0 || picWidthD > dispWidth)
picWidthD = dispWidth;
} else {
// pillarbox vertically (frame wider than display)
picHeightD = dispWidth / frameAspect;
if (picHeightD <= 0 || picHeightD > dispHeight)
picHeightD = dispHeight;
}
// round to the nearest pixel
uint64_t picWidth = std::llround(std::max(0.0, picWidthD));
uint64_t picHeight = std::llround(std::max(0.0, picHeightD));
int64_t offsetX = static_cast<int64_t>(dispWidth) - static_cast<int64_t>(picWidth);
int64_t offsetY = static_cast<int64_t>(dispHeight) - static_cast<int64_t>(picHeight);
uint64_t posX = dispX + static_cast<uint64_t>(std::max<int64_t>(0, offsetX / 2));
uint64_t posY = dispY + static_cast<uint64_t>(std::max<int64_t>(0, offsetY / 2));
return { posX, posY, picWidth, picHeight };
}
/**
* Create an hdr blob and set it for the connector
*
* @param hdrData hdr metadata
*/
void cVideoRender::SetHdrBlob(struct hdr_output_metadata hdrData)
{
uint32_t blobID = 0;
if (m_pDrmDevice->CreateHdrBlob(&hdrData, sizeof(hdrData), &blobID)) {
LOGERROR("videorender: %s: HDR: Failed to create hdr property blob.", __FUNCTION__);
} else if (m_pDrmDevice->SetConnectorHdrBlobProperty(blobID)) {
LOGERROR("videorender: %s: HDR: Failed to set hdr property", __FUNCTION__);
}
if (blobID)
m_pDrmDevice->DestroyHdrBlob(blobID);
if (!m_colorRangeStored) {
uint64_t value;
if (!m_pDrmDevice->GetVideoPlaneColorRange(&value)) {
m_originalColorRange = static_cast<drmColorRange>(value);
m_colorRangeStored = true;
}
}
}
/**
* Set kms color space, color encoding and color range
*
* depending on the hdr data
*
* @param colorRange color range to set
*/
void cVideoRender::SetColorSpace(drmColorRange colorRange)
{
drmModeAtomicReqPtr modeReq;
const uint32_t flags = DRM_MODE_ATOMIC_ALLOW_MODESET;
if (!(modeReq = m_pDrmDevice->ModeAtomicAlloc()))
LOGFATAL("videorender: %s: cannot allocate atomic request (%d): %m", __FUNCTION__, errno);
m_pDrmDevice->SetConnectorColorspace(modeReq, m_pHdrMetadata.GetColorPrimaries() == AVCOL_PRI_BT2020 ? COLORSPACE_BT2020_RGB : COLORSPACE_BT709_YCC);
m_pDrmDevice->SetVideoPlaneColorEncoding(modeReq, m_pHdrMetadata.GetColorPrimaries() == AVCOL_PRI_BT2020 ? COLORENCODING_BT2020 : COLORENCODING_BT709);
m_pDrmDevice->SetVideoPlaneColorRange(modeReq, colorRange);
LOGDEBUG2(L_DRM, "videorender: %s: HDR: connector %d -> Colorspace %s", __FUNCTION__,
m_pDrmDevice->ConnectorId(), m_pHdrMetadata.GetColorPrimaries() == AVCOL_PRI_BT2020 ? "BT2020_RGB" : "BT709_YCC");
LOGDEBUG2(L_DRM, "videorender: %s: HDR: plane %d -> COLOR_ENCODING %s, COLOR_RANGE %s (Color %d)", __FUNCTION__,
m_pDrmDevice->VideoPlane()->GetId(), m_pHdrMetadata.GetColorPrimaries() == AVCOL_PRI_BT2020 ? "YCBCR_BT20202" : "YCBCR_BT709",
colorRange == COLORRANGE_FULL ? "full" : "limited", m_pHdrMetadata.GetColorPrimaries());
if (m_pDrmDevice->ModeAtomicCommit(modeReq, flags, NULL) != 0) {
m_pDrmDevice->ModeAtomicFree(modeReq);
LOGFATAL("videorender: %s: cannot set atomic mode (%d): %m", __FUNCTION__, errno);
}
m_pDrmDevice->ModeAtomicFree(modeReq);
m_hasDoneHdrModeset = true;
}
/**
* Restore color space, color encoding and color range
* to BT709 and the original color range
*/
void cVideoRender::RestoreColorSpace(void)
{
drmModeAtomicReqPtr modeReq;
const uint32_t flags = DRM_MODE_ATOMIC_ALLOW_MODESET;
if (!(modeReq = m_pDrmDevice->ModeAtomicAlloc()))
LOGFATAL("videorender: %s: cannot allocate atomic request (%d): %m", __FUNCTION__, errno);
m_pDrmDevice->SetConnectorHdrOutputMetadata(modeReq, 0);
m_pDrmDevice->SetConnectorColorspace(modeReq, COLORSPACE_BT709_YCC);
m_pDrmDevice->SetVideoPlaneColorEncoding(modeReq, COLORENCODING_BT709);
m_pDrmDevice->SetVideoPlaneColorRange(modeReq, m_colorRangeStored ? static_cast<uint64_t>(m_originalColorRange) : static_cast<uint64_t>(COLORRANGE_LIMITED));
if (m_pDrmDevice->ModeAtomicCommit(modeReq, flags, NULL) != 0) {
m_pDrmDevice->ModeAtomicFree(modeReq);
LOGFATAL("videorender: %s: cannot set atomic mode (%d): %m", __FUNCTION__, errno);
}
m_pDrmDevice->ModeAtomicFree(modeReq);
m_hasDoneHdrModeset = false;
m_colorRangeStored = false;
}
/**
* Modesetting for video
*
* @param[in] buf drm video buffer to display
*
* @retval 1 no modesetting was done
* @retval 0 modesetting was done
*/
int cVideoRender::SetVideoBuffer(cDrmBuffer *buf)
{
if (!buf)
return 1;
AVFrame *frame = buf->frame;
if (frame && m_enableHdr) {
struct hdr_output_metadata hdrData;
AVFrameSideData *sd1 = av_frame_get_side_data(frame, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA);
AVFrameSideData *sd2 = av_frame_get_side_data(frame, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL);
if (!m_pHdrMetadata.Build(&hdrData, frame->color_primaries, frame->color_trc, sd1, sd2)) {
SetHdrBlob(hdrData);
SetColorSpace(COLORRANGE_LIMITED);
}
}
// set display dimensions as default
uint64_t dispWidth = m_pDrmDevice->DisplayWidth();
uint64_t dispHeight = m_pDrmDevice->DisplayHeight();
uint64_t dispX = 0;
uint64_t dispY = 0;
cDrmPlane *videoPlane = m_pDrmDevice->VideoPlane();
// get video size and position
if (m_videoIsScaled) {
dispWidth = m_videoRect.Width();
dispHeight = m_videoRect.Height();
dispX = m_videoRect.X();
dispY = m_videoRect.Y();
}
// fit frame into display
sRect fittedRect = ComputeFittedRect(frame, dispX, dispY, dispWidth, dispHeight);
// now set the plane parameters
videoPlane->SetParams(m_pDrmDevice->CrtcId(), buf->Id(),
fittedRect.x, fittedRect.y, fittedRect.w, fittedRect.h,
0, 0, buf->Width(), buf->Height());
buf->SetSizeOnScreen(fittedRect.x, fittedRect.y, fittedRect.w, fittedRect.h); // remember for grab
return 0;
}
/**
* Modesetting for osd
*
* @retval 1 osd is not dirty, do nothing
* @retval 0 osd modesetting was done
*/
int cVideoRender::SetOsdBuffer(drmModeAtomicReqPtr modeReq)
{
if (!m_pBufOsd || !m_pBufOsd->IsDirty())
return 1;
cDrmPlane *videoPlane = m_pDrmDevice->VideoPlane();
cDrmPlane *osdPlane = m_pDrmDevice->OsdPlane();
// We had draw activity on the osd buffer
if (m_pDrmDevice->UseZpos()) {
videoPlane->SetZpos(m_osdShown ? m_pDrmDevice->ZposPrimary() : m_pDrmDevice->ZposOverlay());
osdPlane->SetZpos(m_osdShown ? m_pDrmDevice->ZposOverlay() : m_pDrmDevice->ZposPrimary());
videoPlane->SetPlaneZpos(modeReq);
osdPlane->SetPlaneZpos(modeReq);
LOGDEBUG2(L_DRM, "videorender: %s: SetPlaneZpos: video->plane_id %d -> zpos %" PRIu64 ", osd->plane_id %d -> zpos %" PRIu64 "", __FUNCTION__,
videoPlane->GetId(), videoPlane->GetZpos(),
osdPlane->GetId(), osdPlane->GetZpos());
}
uint64_t crtcW = m_osdShown ? m_pDrmDevice->DisplayWidth() : 0;
uint64_t crtcH = m_osdShown ? m_pDrmDevice->DisplayHeight() : 0;
uint64_t srcW = m_osdShown ? m_pBufOsd->Width() : 0;
uint64_t srcH = m_osdShown ? m_pBufOsd->Height() : 0;
// now set the plane parameters
osdPlane->SetParams(m_pDrmDevice->CrtcId(), m_pBufOsd->Id(),
0, 0, crtcW, crtcH,
0, 0, srcW, srcH);
m_pBufOsd->SetSizeOnScreen(0, 0, crtcW, crtcH); // remember for grab
m_pBufOsd->MarkClean();
return 0;
}
/**
* Modesetting for pip
*
* @param[in] buf drm video buffer to display
*
* @retval 1 no modesetting was done
* @retval 0 modesetting was done
*/
int cVideoRender::SetPipBuffer(cDrmBuffer *buf)
{
if (!buf || !m_pipActive || m_videoIsScaled)
return 1;
AVFrame *frame = buf->frame;
// set display dimensions as default
uint64_t dispWidth = m_pDrmDevice->DisplayWidth();
uint64_t dispHeight = m_pDrmDevice->DisplayHeight();
uint64_t dispX = 0;
uint64_t dispY = 0;
cDrmPlane *pipPlane = m_pDrmDevice->PipPlane();
// Get video size and position
if (m_videoIsScaled) {
dispWidth = m_videoRect.Width();
dispHeight = m_videoRect.Height();
dispX = m_videoRect.X();
dispY = m_videoRect.Y();
}
// fit frame into display
sRect fittedRect = ComputeFittedRect(frame, dispX, dispY, dispWidth, dispHeight);
// compute pip window with given scaling and positioning values from menu
int64_t centerOffsetX = static_cast<int64_t>(dispWidth) - static_cast<int64_t>(fittedRect.w);
int64_t centerOffsetY = static_cast<int64_t>(dispHeight) - static_cast<int64_t>(fittedRect.h);
centerOffsetX = std::max<int64_t>(0, centerOffsetX / 2);
centerOffsetY = std::max<int64_t>(0, centerOffsetY / 2);
double crtcWD = fittedRect.w * m_pipScalePercent / 100.0;
double crtcHD = fittedRect.h * m_pipScalePercent / 100.0;
uint64_t crtcW = std::llround(crtcWD);
uint64_t crtcH = std::llround(crtcHD);
double spaceW = dispWidth - crtcW - centerOffsetX;
double spaceH = dispHeight - crtcH - centerOffsetY;
uint64_t crtcX = dispX + std::llround(spaceW * m_pipLeftPercent / 100.0 + centerOffsetX * m_pipScalePercent / 100.0);
uint64_t crtcY = dispY + std::llround(spaceH * m_pipTopPercent / 100.0 + centerOffsetY * m_pipScalePercent / 100.0);
// now set the plane parameters
pipPlane->SetParams(m_pDrmDevice->CrtcId(), buf->Id(),
crtcX, crtcY, crtcW, crtcH,
0, 0, buf->Width(), buf->Height());
buf->SetSizeOnScreen(crtcX, crtcY, crtcW, crtcH); // remember for grab
return 0;
}
/**
* Commit the frame to the hardware
*
* @param buf video drm buffer
*
* @retval 0 modesetting and commit was done, need to process outstanding DRM events
* @retval -1 no modesetting and commit was done
*/
int cVideoRender::CommitBuffer(cDrmBuffer *buf, cDrmBuffer *pip)
{
enum modeSetLevel {
MODESET_OSD = (1 << 0),
MODESET_VIDEO = (1 << 1),
MODESET_PIP = (1 << 2)
};
int modeSet = 0;
cDrmPlane *videoPlane = m_pDrmDevice->VideoPlane();
cDrmPlane *osdPlane = m_pDrmDevice->OsdPlane();
cDrmPlane *pipPlane = m_pDrmDevice->PipPlane();
drmModeAtomicReqPtr modeReq;
uint32_t flags = DRM_MODE_PAGE_FLIP_EVENT;
if (!(modeReq = m_pDrmDevice->ModeAtomicAlloc())) {
LOGERROR("videorender: %s: cannot allocate atomic request (%d): %m", __FUNCTION__, errno);
return -1;
}
// handle the video plane
// If no new video is available, set the old buffer again, if available.
// This is necessary to recognize a size-change in SetVideoBuffer().
// Though this is not expensive, maybe we should only call that, if size really changed.
if (!SetVideoBuffer(buf) || !SetVideoBuffer(m_pCurrentlyDisplayed)) {
videoPlane->SetPlane(modeReq);
modeSet |= MODESET_VIDEO;
// LOGDEBUG2(L_DRM, "videorender: %s: SetPlane Video (fb = %" PRIu64 ")", __FUNCTION__, videoPlane->GetFbId());
}
// handle the pip plane
if (pipPlane->GetId()) {
if (!SetPipBuffer(pip) || !SetPipBuffer(m_pCurrentlyPipDisplayed))
pipPlane->SetPlane(modeReq);
else
pipPlane->ClearPlane(modeReq);
modeSet |= MODESET_PIP;
}
// handle the osd plane
if (!SetOsdBuffer(modeReq)) {
osdPlane->SetPlane(modeReq);
modeSet |= MODESET_OSD;
// LOGDEBUG2(L_DRM, "videorender: %s: SetPlane OSD %d (fb = %" PRIu64 ")", __FUNCTION__, m_osdShown, osdPlane->GetFbId());
}
// return without an atomic commit (no video frame and osd activity)
if (!modeSet) {
m_pDrmDevice->ModeAtomicFree(modeReq);
return -1;
}
// do the atomic commit
if (m_pDrmDevice->ModeAtomicCommit(modeReq, flags, NULL) != 0) {
if (modeSet & MODESET_OSD)
osdPlane->DumpParameters("osd");
if (modeSet & MODESET_VIDEO)
videoPlane->DumpParameters("video");
if (modeSet & MODESET_PIP)
pipPlane->DumpParameters("pip");
m_pDrmDevice->ModeAtomicFree(modeReq);
LOGERROR("videorender: %s: page flip failed (%d): %m", __FUNCTION__, errno);
return -1;
}
m_pDrmDevice->ModeAtomicFree(modeReq);
return 0;
}
/**
* Log A/V sync debug message
*
* @param audioPtsMs audio pts
* @param videoPtsMs video pts
* @param audioBehindVideoByMs audio is behind video by this many ms
*/
void cVideoRender::LogDroppedDuped(int64_t audioPtsMs, int64_t videoPtsMs, int audioBehindVideoByMs)
{
bool logDropDup = true;
if (audioBehindVideoByMs > AV_SYNC_THRESHOLD_AUDIO_BEHIND_VIDEO_MS)
m_framesDuped++;
else if (audioBehindVideoByMs < -AV_SYNC_THRESHOLD_AUDIO_AHEAD_VIDEO_MS)
m_framesDropped++;
else
logDropDup = false;
LOGDEBUG2(L_AV_SYNC, "%s (%d|%d|%d) Pkts %d Frames %d Rb %d bytes (%dms) PTS: in %s a %s v %s user delay %dms hw delay %dms diff %dms",
(logDropDup && (audioBehindVideoByMs > 0)) ? "Frame duped" : (logDropDup ? "Frame dropped" : "Frames:"),
m_framesDropped,
m_framesDuped,
m_startCounter,
m_pDevice->VideoStream()->GetAvPacketsFilled(),
m_drmBufferQueue.Size(),
m_pAudio->GetUsedRingbufferBytes(),
m_pAudio->GetUsedRingbufferMs(),
Timestamp2String(m_pAudio->GetInputPtsMs(), 1),
Timestamp2String(audioPtsMs, 1),
Timestamp2String(videoPtsMs, 1),
m_pDevice->GetVideoAudioDelayMs(),
m_pAudio->GetHardwareOutputDelayMs(),
audioBehindVideoByMs);
}
/**
* Get frame flags
*
* @param frame AVFrame
*
* @return FRAME_FLAG_TRICKSPEED or FRAME_FLAG_STILLPICTURE
*/
int cVideoRender::GetFrameFlags(AVFrame *frame)
{
if (!frame || !frame->opaque_ref)
return 0;
int *frameFlags = (int *)frame->opaque_ref->data;
return *frameFlags;
}
/**
* Set frame flags
*
* @param frame AVFrame
* @param flags FRAME_FLAG_TRICKSPEED and/or FRAME_FLAG_STILLPICTURE
*/
void cVideoRender::SetFrameFlags(AVFrame *frame, int flags)
{
int *frameFlags;
if (!frame->opaque_ref) {
frame->opaque_ref = av_buffer_allocz(sizeof(*frameFlags));
if (!frame->opaque_ref) {
LOGFATAL("videorender: %s: cannot allocate private frame data", __FUNCTION__);
}
}
frameFlags = (int *)frame->opaque_ref->data;
*frameFlags = flags;
}
/**
* Do the pageflip
*
* @param buf drm buffer
* @param pipBuf drm pip buffer
* @return true if page flip was done
*/
bool cVideoRender::PageFlip(cDrmBuffer *buf, cDrmBuffer *pipBuf)
{
if (CommitBuffer(buf, pipBuf) < 0) {
// no modesetting was done
if (buf && buf->frame)
av_frame_free(&buf->frame);
if (pipBuf && pipBuf->frame)
av_frame_free(&pipBuf->frame);
return false;
} else {
if (m_pDrmDevice->HandleEvent() != 0)
LOGERROR("threads: display thread: drmHandleEvent failed!");
m_flipCounter++;
// now, that we had a successful commit, set the STC if we have a frame. Skip if only the OSD was updated.
if (buf && buf->frame) {
if (buf->frame->pts != AV_NOPTS_VALUE)
SetVideoClock(buf->frame->pts);
LOGDEBUG2(L_PACKET, "videorender: %s: ID %d: PTS %s", __FUNCTION__, buf->Id(), Timestamp2String(buf->frame->pts, 90));
}
return true;
}
}
/*****************************************************************************
* Thread
****************************************************************************/
/**
* Thread loop, which tries to display frames and processes events
*/
void cVideoRender::Action(void)
{
LOGDEBUG("videorender: display thread started");
while(Running()) {
m_mutex.lock();
bool scheduleImmediately = DisplayFrame();
m_mutex.unlock();
ProcessEvents();
if (scheduleImmediately)
usleep(100); // yield thread. give control also to threads with lower priority.
else
usleep(1000);
}
LOGDEBUG("videorender: display thread stopped");
}
/**
* Stop the thread
*/
void cVideoRender::Stop(void)
{
if (!Active())
return;
LOGDEBUG("videorender: stopping display thread");
Cancel(2);
}
/**
* Do the AV Sync
*
* @param audioPtsMs audio pts
* @param videoPtsMs video pts
*
* @return true if the frame should be dropped, false otherwise
*/
bool cVideoRender::FrameDropNecessary(int64_t audioPtsMs, int64_t videoPtsMs)
{
int audioBehindVideoByMs = videoPtsMs - audioPtsMs - m_pDevice->GetVideoAudioDelayMs();
bool skipSync = m_scheduleResyncAtPtsMs != AV_NOPTS_VALUE;
// resync, if the video pts reaches the scheduled resync pts
// skip the resync, if the difference between the resync-pts and the current video pts is greater
// than the AV_RESYNC_BORDER_MS to sort out false positives
if (m_scheduleResyncAtPtsMs != AV_NOPTS_VALUE && m_scheduleResyncAtPtsMs <= videoPtsMs) {
if (std::abs(PtsToMs(m_scheduleResyncAtPtsMs) - PtsToMs(videoPtsMs)) <= m_pAudio->GetAvResyncBorderMs()) {
LOGDEBUG2(L_AV_SYNC, "videorender: resync schedule arrived at %s, current audio pts %s video pts %s",
Timestamp2String(m_scheduleResyncAtPtsMs, 1), Timestamp2String(audioPtsMs, 1), Timestamp2String(videoPtsMs, 1));
m_eventQueue.push_back(ResyncEvent{});
}
m_scheduleResyncAtPtsMs = AV_NOPTS_VALUE;
}
// Pause was scheduled and we reached this pts now
if (m_videoPlaybackPauseScheduledAt != AV_NOPTS_VALUE && m_videoPlaybackPauseScheduledAt < videoPtsMs) {
LOGDEBUG2(L_AV_SYNC, "videorender: %s: pause was scheduled at %s)!", __FUNCTION__, Timestamp2String(videoPtsMs, 1));
m_videoPlaybackPauseScheduledAt = AV_NOPTS_VALUE;
m_displayOneFrameThenPause = true;
// Resuming audio from pause was scheduled audio needs to catch up video
} else if (m_resumeAudioScheduled && audioBehindVideoByMs >= 0 && !skipSync) {
LOGDEBUG2(L_AV_SYNC, "videorender: resuming audio playback: video %s, audio %s", Timestamp2String(videoPtsMs, 1), Timestamp2String(audioPtsMs, 1));
m_pAudio->SetPaused(false);
m_resumeAudioScheduled = false;
// Duplicate frame
} else if (audioBehindVideoByMs > AV_SYNC_THRESHOLD_AUDIO_BEHIND_VIDEO_MS &&
!skipSync && !m_pAudio->IsPaused()) {
LogDroppedDuped(audioPtsMs, videoPtsMs, audioBehindVideoByMs);
m_framePresentationCounter++; // display the current video frame one period longer
// Drop frame - max every second frame. Otherwise, the buffer gets drained immediately, if multiple frames in a row are dropped.
} else if (audioBehindVideoByMs < -AV_SYNC_THRESHOLD_AUDIO_AHEAD_VIDEO_MS &&
!m_lastFrameWasDropped && !skipSync && !m_pAudio->IsPaused()) {
LogDroppedDuped(audioPtsMs, videoPtsMs, audioBehindVideoByMs);
m_framePresentationCounter--; // skip this pageflip
m_lastFrameWasDropped = true;
return true;
}
// LogDroppedDuped(audioPtsMs, videoPtsMs, audioBehindVideoByMs);
// log AV diff for the first 10 frames and every 10 seconds
// if (m_startCounter < 10 || m_startCounter % 500 == 0)
// LOGDEBUG2(L_AV_SYNC, "drop %d, dup %d, total %d audio %s video %s Delay %dms kernel buffer delay %dms diff %dms",
// m_framesDropped, m_framesDuped, m_startCounter,
// Timestamp2String(audioPtsMs, 1), Timestamp2String(videoPtsMs, 1),
// m_pDevice->GetVideoAudioDelayMs(), m_pAudio->GetHardwareOutputDelayMs(), audioBehindVideoByMs);
m_startCounter++;
return false;
}
/**
* Display the frame (video and/or osd)
*
* @return true if it shall be scheduled immediately again
*/
bool cVideoRender::DisplayFrame(void)
{
bool frameTick = m_flipCounter % m_framesPerFlipCycle == 0;
if (m_pDevice->IsBufferingThresholdReached())
m_eventQueue.push_back(BufferingThresholdReachedEvent{});
bool skipBufferUnderrunCheck = m_videoPlaybackPaused ||
m_displayOneFrameThenPause ||
m_videoPlaybackPauseScheduledAt != AV_NOPTS_VALUE ||
m_pDevice->IsVideoOnlyPlayback() ||
IsTrickSpeed() ||
IsStillpicture() ||
m_pDevice->IsDraining() ||
m_schedulePlaybackStartAtPtsMs != AV_NOPTS_VALUE;
if (m_pDevice->VideoStream()->GetAvPacketsFilled() == 0 && !skipBufferUnderrunCheck)
m_eventQueue.push_back(BufferUnderrunEvent{VIDEO});
cDrmBuffer *drmBuffer = nullptr;
if ((!m_videoPlaybackPaused || m_schedulePlaybackStartAtPtsMs != AV_NOPTS_VALUE) && m_framePresentationCounter == 0 && frameTick)
drmBuffer = m_drmBufferQueue.Peek();
cDrmBuffer *pipBuffer = m_pipDrmBufferQueue.Pop();
bool pageFlipDone = false;
if (drmBuffer) {
if (m_framePresentationCounter == 0) {
if (m_pCurrentlyDisplayed) {
int64_t interFrameGapMs = std::abs(PtsToMs(drmBuffer->frame->pts - m_pCurrentlyDisplayed->frame->pts));
m_framePresentationCounter = GetFramePresentationCount(interFrameGapMs);
} else
m_framePresentationCounter = 1;
}
if (m_schedulePlaybackStartAtPtsMs != AV_NOPTS_VALUE) {
// check if playback shall start
if (PtsToMs(drmBuffer->frame->pts) < m_schedulePlaybackStartAtPtsMs) {
drmBuffer->PresentationFinished();
m_drmBufferQueue.Pop();
return true;
} else {
m_schedulePlaybackStartAtPtsMs = AV_NOPTS_VALUE;
m_videoPlaybackPaused = false;
}
} else if (!m_displayOneFrameThenPause && !IsStillpicture()) {
// A/V sync
int64_t audioPtsMs = m_pAudio->GetHardwareOutputPtsMs();
int64_t videoPtsMs = PtsToMs(drmBuffer->frame->pts);
if (audioPtsMs != AV_NOPTS_VALUE && FrameDropNecessary(audioPtsMs, videoPtsMs)) {
// drop frame
drmBuffer->PresentationFinished();
if (pipBuffer)
pipBuffer->PresentationFinished();
m_drmBufferQueue.Pop();
return true;
}
if (m_videoPlaybackPaused || IsTrickSpeed())
m_pAudio->DropSamplesOlderThanPtsMs(drmBuffer->frame->pts * 1000 * av_q2d(m_timebase));
}
pageFlipDone = PageFlip(drmBuffer, pipBuffer);
// log channel switch duration
if (m_pDevice->Transferring() && ((m_startCounter == 0 && m_displayOneFrameThenPause) || m_startCounter == 1)) {
auto now = std::chrono::steady_clock::now();
auto channelSwitchDurationMs = std::chrono::duration_cast<std::chrono::milliseconds>(now - m_pDevice->GetChannelSwitchStartTime()).count();
auto durationSinceFirstPacketMs = std::chrono::duration_cast<std::chrono::milliseconds>(now - m_pDevice->GetChannelSwitchFirstPacketTime()).count();
if (m_startCounter == 0) {
LOGDEBUG("first frame displayed %dms after channel switch, %dms after first packet was received", channelSwitchDurationMs, durationSinceFirstPacketMs);
} else {
if (m_pConfig->ConfigShowChannelSwitchDurationMessage)
Skins.Message(mtInfo, cString::sprintf(tr("channel switch done in %ldms (%ldms)"), channelSwitchDurationMs, durationSinceFirstPacketMs));
LOGDEBUG("playback start fired %dms after channel switch, %dms after first packet was received", channelSwitchDurationMs, durationSinceFirstPacketMs);
}
}
if (m_displayOneFrameThenPause) {
m_videoPlaybackPaused = true;
m_displayOneFrameThenPause = false;
}
if (m_pCurrentlyDisplayed)
m_pCurrentlyDisplayed->PresentationFinished();
m_lastFrameWasDropped = false;
m_pCurrentlyDisplayed = drmBuffer;
m_drmBufferQueue.Pop();
} else if (m_pCurrentlyDisplayed && !m_videoPlaybackPaused) {
// display the current frame again in trick speed mode or for A/V syncing
pageFlipDone = PageFlip(m_pCurrentlyDisplayed, pipBuffer);
} else if ((m_pBufOsd && m_pBufOsd->IsDirty()) || pipBuffer) {
pageFlipDone = PageFlip(NULL, pipBuffer);
}
if (pipBuffer) {
if (m_pCurrentlyPipDisplayed && m_pCurrentlyPipDisplayed != pipBuffer)
m_pCurrentlyPipDisplayed->PresentationFinished();
m_pCurrentlyPipDisplayed = pipBuffer;
}
if (m_framePresentationCounter > 0)
m_framePresentationCounter--;
CreateGrabBuffers(!m_videoIsScaled);
return pageFlipDone;
}
/**
* Display a black video frame
*/
void cVideoRender::DisplayBlackFrame(void)
{
LOGDEBUG2(L_DRM, "videorender: %s: closing, set a black FB", __FUNCTION__);
PageFlip(&m_bufBlack, NULL);
if (m_pCurrentlyDisplayed) {
av_frame_free(&m_pCurrentlyDisplayed->frame);
m_pCurrentlyDisplayed->Destroy();
m_pCurrentlyDisplayed = nullptr;
}
}
/**
* Convert a PTS to milliseconds
*/
int64_t cVideoRender::PtsToMs(int64_t pts)
{
std::lock_guard<std::mutex> lock(m_timebaseMutex);
return pts * 1000 * av_q2d(m_timebase);
}
/**
* Wrapper for drmHandleEvent()
*/
int cVideoRender::DrmHandleEvent(void)
{
return m_pDrmDevice->HandleEvent();
}
/**
* Return true, if the device can handle HDR
*/
bool cVideoRender::CanHandleHdr(void)
{
return m_pDrmDevice->CanHandleHdr();
}
/*****************************************************************************
* OSD
****************************************************************************/
/**
* Clear the OSD (draw an empty/ transparent OSD)
*/
void cVideoRender::OsdClear(void)
{
#ifdef USE_GLES
if (m_disableOglOsd) {
memset((void *)m_pBufOsd->Plane(0), 0,
(size_t)(m_pBufOsd->Pitch(0) * m_pBufOsd->Height()));
} else {
cDrmBuffer *buf;
EGL_CHECK(eglSwapBuffers(m_pDrmDevice->EglDisplay(), m_pDrmDevice->EglSurface()));
m_pNextBo = gbm_surface_lock_front_buffer(m_pDrmDevice->GbmSurface());
assert(m_pNextBo);
buf = m_pDrmDevice->GetBufFromBo(m_pNextBo);
if (!buf) {
LOGERROR("videorender: %s: Failed to get GL buffer", __FUNCTION__);
return;
}
m_pBufOsd = buf;
// release old buffer for writing again
if (m_bo)
gbm_surface_release_buffer(m_pDrmDevice->GbmSurface(), m_bo);
// rotate bos and create and keep bo as m_pOldBo to make it free'able
m_pOldBo = m_bo;
m_bo = m_pNextBo;
LOGDEBUG2(L_OPENGL, "videorender: %s: eglSwapBuffers m_eglDisplay %p eglSurface %p (%i x %i, %i)", __FUNCTION__, m_pDrmDevice->EglDisplay(), m_pDrmDevice->EglSurface(), buf->Width(), buf->Height(), buf->Pitch(0));
}
#else
memset((void *)m_pBufOsd->Plane(0), 0,
(size_t)(m_pBufOsd->Pitch(0) * m_pBufOsd->Height()));
#endif
m_pBufOsd->MarkDirty();
m_osdShown = false;
}
#define MIN(a, b) ((a) < (b) ? (a) : (b))
/**
* Draw an OSD ARGB image.
*
* @param xi x-coordinate in argb image
* @param yi y-coordinate in argb image
* @param height height in pixel in argb image
* @param width width in pixel in argb image
* @param pitch pitch of argb image
* @param argb 32bit ARGB image data
* @param x x-coordinate on screen of argb image
* @param y y-coordinate on screen of argb image
*/
void cVideoRender::OsdDrawARGB(int xi, int yi,
int width, int height, int pitch,
const uint8_t * argb, int x, int y)
{
#ifdef USE_GLES
if (m_disableOglOsd) {
LOGDEBUG2(L_OSD, "videorender: %s: width %d height %d pitch %d argb %p x %d y %d pitch buf %d xi %d yi %d", __FUNCTION__,
width, height, pitch, argb, x, y, m_pBufOsd->Pitch(0), xi, yi);
for (int i = 0; i < height; ++i) {
memcpy(m_pBufOsd->Plane(0) + x * 4 + (i + y) * m_pBufOsd->Pitch(0),
argb + i * pitch, MIN((size_t)pitch, m_pBufOsd->Pitch(0)));
}
} else {
cDrmBuffer *buf;
EGL_CHECK(eglSwapBuffers(m_pDrmDevice->EglDisplay(), m_pDrmDevice->EglSurface()));
m_pNextBo = gbm_surface_lock_front_buffer(m_pDrmDevice->GbmSurface());
assert(m_pNextBo);
buf = m_pDrmDevice->GetBufFromBo(m_pNextBo);
if (!buf) {
LOGERROR("videorender: %s: Failed to get GL buffer", __FUNCTION__);
return;
}
m_pBufOsd = buf;
// release old buffer for writing again
if (m_bo)
gbm_surface_release_buffer(m_pDrmDevice->GbmSurface(), m_bo);
// rotate bos and create and keep bo as m_pOldBo to make it free'able
m_pOldBo = m_bo;
m_bo = m_pNextBo;
LOGDEBUG2(L_OPENGL, "videorender: %s: eglSwapBuffers eglDisplay %p eglSurface %p (%i x %i, %i)", __FUNCTION__, m_pDrmDevice->EglDisplay(), m_pDrmDevice->EglSurface(), buf->Width(), buf->Height(), buf->Pitch(0));
}
#else
// suppress unused variable warnings ...
(void) xi;
(void) yi;
(void) width;
for (int i = 0; i < height; ++i) {
memcpy(m_pBufOsd->Plane(0) + x * 4 + (i + y) * m_pBufOsd->Pitch(0),
argb + i * pitch, (size_t)pitch);
}
#endif
m_pBufOsd->MarkDirty();
m_osdShown = true;
}
/**
* Callback free primedata if av_buffer is unreferenced
*/
static void ReleaseFrame( __attribute__ ((unused)) void *opaque, uint8_t *data)
{
AVDRMFrameDescriptor *primedata = (AVDRMFrameDescriptor *)data;
av_free(primedata);
}
/**
* Check, if the main render output buffer is full.
*
* @retval true render output buffer is full
*/
bool cVideoRender::IsOutputBufferFull(void)
{
return m_drmBufferQueue.IsFull();
}