forked from zillevdr/vdr-plugin-softhddevice-drm
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsofthddevice.cpp
More file actions
1962 lines (1686 loc) · 54.7 KB
/
Copy pathsofthddevice.cpp
File metadata and controls
1962 lines (1686 loc) · 54.7 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 softhddevice.cpp
* Output Device
*
* This file defines cSoftHdDevice which is the implementation
* of cDevice. This is the place where all the device commands
* which are sent be VDR are placed in (i.e. Play(), TrickSpeed() ...)
*
* @copyright 2011 - 2015 by Johns. All Rights Reserved.
* @copyright 2018 - 2019 by zille. All Rights Reserved.
* @copyright 2025 - 2026 by Andreas Baierl. All Rights Reserved.
*
* @license{AGPL-3.0-or-later}
*/
#include <chrono>
#include <mutex>
#include <variant>
#include <libintl.h>
extern "C" {
#include <libavcodec/avcodec.h>
}
#include <vdr/dvbspu.h>
#include <vdr/skins.h>
#include <vdr/status.h>
#include <vdr/thread.h>
#include "audio.h"
#include "codec_audio.h"
#include "config.h"
#include "grab.h"
#include "hardwaredevice.h"
#include "jittertracker.h"
#include "logger.h"
#include "pes.h"
#include "pipreceiver.h"
#include "softhddevice.h"
#include "softhdosdprovider.h"
#include "statemachine.h"
#include "videorender.h"
#include "videostream.h"
/**
* Create the device
*
* Initializes some member variables
*
* @param config pointer to cSoftHdConfig class
*/
cSoftHdDevice::cSoftHdDevice(cSoftHdConfig *config)
: m_pConfig(config)
{
m_pStateMachine = std::make_unique<cStateMachine>(this);
}
/**
* Destroy the device
*
* Only delete objects, if they were created in Initialize()
*/
cSoftHdDevice::~cSoftHdDevice(void)
{
if (!m_initialized)
return;
m_initialized = false; // not necessary, just for documentation
delete m_pEventHandler;
delete m_pHardwareDevice;
delete m_pSpuDecoder;
}
/*********************************************************************
* VDR cPlugin interface (wrapped by cPluginSoftHdDevice)
********************************************************************/
/**
* Initialize the device
*/
bool cSoftHdDevice::Initialize(void)
{
LOGDEBUG("device: %s:", __FUNCTION__);
// the following are deleted in the destructor
m_pSpuDecoder = new cDvbSpuDecoder();
m_pHardwareDevice = new cHardwareDevice();
m_pEventHandler = new cEventHandler(m_pStateMachine.get());
m_channelSwitchStartTime = std::chrono::steady_clock::now();
m_dataReceivedTime = m_channelSwitchStartTime;
m_pipUseAlt = m_pConfig->ConfigPipUseAlt;
m_channelSwitchMode = static_cast<ChannelSwitchMode>(m_pConfig->ConfigVideoChannelSwitchMode);
m_initialized = true;
return true;
}
/**
* Called by VDR when the plugin is started.
*/
int cSoftHdDevice::Start(void)
{
LOGDEBUG("device: %s", __FUNCTION__);
TriggerEvent(AttachEvent{});
return true;
}
/**
* Called by VDR when the plugin is stopped.
*/
void cSoftHdDevice::Stop(void)
{
LOGDEBUG("device: %s", __FUNCTION__);
m_pPipHandler->Disable();
TriggerEvent(DetachEvent{});
}
/*********************************************************************
* VDR cDevice interface
********************************************************************/
/**
* Informs a device that it will be the primary device
*
* @param on flag if becoming or loosing primary
*/
void cSoftHdDevice::MakePrimaryDevice(bool on)
{
LOGDEBUG("device: %s: %d", __FUNCTION__, on);
if (on)
m_pOsdProvider = new cSoftOsdProvider(this); // no need to delete it, VDR does it
cDevice::MakePrimaryDevice(on);
}
/**
* Tells whether this device has an MPEG decoder
*/
bool cSoftHdDevice::HasDecoder(void) const
{
bool hasDecoder = !IsDetached();
// LOGDEBUG("device: %s: %d", __FUNCTION__, hasDecoder);
return hasDecoder;
}
/**
* Get the device SPU decoder.
*
* @return a pointer to the device's SPU decoder
* (or NULL, if this device doesn't have an SPU decoder)
*/
cSpuDecoder *cSoftHdDevice::GetSpuDecoder(void)
{
LOGDEBUG("device: %s:", __FUNCTION__);
if (!IsPrimaryDevice())
return NULL;
return m_pSpuDecoder;
}
/**
* Grabs the currently visible screen image
*
* @param size size of the returned data
* @param jpeg flag true, create JPEG data
* @param quality JPEG quality
* @param width number of horizontal pixels in the frame
* @param height number of vertical pixels in the frame
*/
uchar *cSoftHdDevice::GrabImage(int &size, bool jpeg, int quality, int width, int height)
{
if (!width || !height) {
LOGWARNING("device: %s: width or height is 0 - skip!", __FUNCTION__);
return nullptr;
}
if (IsDetached())
return nullptr;
if (m_pGrab->IsActive()) {
LOGWARNING("device: %s: wait for the last grab to be finished - skip!", __FUNCTION__);
return nullptr;
}
LOGDEBUG2(L_GRAB, "device: %s: %d, %d, %d, %dx%d", __FUNCTION__, size, jpeg, quality, width, height);
if (!m_pGrab->Start(jpeg, quality, width, height, m_screenWidth, m_screenHeight))
return nullptr;
if (!m_pGrab->ProcessGrab())
return nullptr;
size = m_pGrab->Size();
uchar *result = m_pGrab->Image();
m_pGrab->Finish();
return result;
}
/**
* Sets the video display format
*
* @param videoDisplayFormat video display format
* Set it to the given one (only useful if this device has an MPEG decoder).
*/
void cSoftHdDevice::SetVideoDisplayFormat(eVideoDisplayFormat videoDisplayFormat)
{
LOGDEBUG("device: %s: %d", __FUNCTION__, videoDisplayFormat);
cDevice::SetVideoDisplayFormat(videoDisplayFormat);
}
/**
* Set the video format
*
* Sets the output video format to either 16:9 or 4:3 (only useful
* if this device has an MPEG decoder).
*
* Should call SetVideoDisplayFormat
*
* @param videoFormat16_9 flag true 16:9.
*/
void cSoftHdDevice::SetVideoFormat(bool videoFormat16_9)
{
LOGDEBUG("device: %s: %d", __FUNCTION__, videoFormat16_9);
// FIXME: 4:3 / 16:9 video format not supported.
SetVideoDisplayFormat(eVideoDisplayFormat(Setup.VideoDisplayFormat));
}
/**
* Get the video size
*
* Return the width, height and aspect ratio of the currently
* displayed video material
*
* @param[out] width video width
* @param[out] height video height
* @param[out] aspectRatio video aspect ratio
*
* @note the video_aspect is used to scale the subtitle.
*/
void cSoftHdDevice::GetVideoSize(int &width, int &height, double &aspectRatio)
{
// LOGDEBUG("device: %s: %d x %d @ %f", __FUNCTION__, *width, *height, *aspectRatio);
if (IsDetached()) { // return default values according to vdr docs
width = 0;
height = 0;
aspectRatio = 1.0;
return;
}
m_pVideoStream->GetVideoSize(&width, &height, &aspectRatio);
}
/**
* Returns the width, height and aspect ratio the OSD should have
*
* @param[out] width osd width
* @param[out] height osd height
* @param[out] aspectRatio osd aspect ratio
*
* @todo: Called every second, for nothing (no OSD displayed)?
*/
void cSoftHdDevice::GetOsdSize(int &width, int &height, double &aspectRatio)
{
if (IsDetached()) { // hardcode to 1920x1080 in detached state
width = 1920;
height = 1080;
aspectRatio = (double)width / (double)height;
return;
}
std::lock_guard<std::mutex> lock(m_sizeMutex);
width = m_osdWidth;
height = m_osdHeight;
aspectRatio = (double)width / (double)height;
}
/**
* Sets the audio volume on this device (Volume = 0...255).
*
* @param volume device volume
*/
void cSoftHdDevice::SetVolumeDevice(int volume)
{
if (IsDetached())
return;
LOGDEBUG("device: %s: %d", __FUNCTION__, volume);
m_volume = volume;
m_pAudio->SetVolume((volume * 1000) / 255);
}
/**
* Return true if this device can currently start a replay session
*/
bool cSoftHdDevice::CanReplay(void) const
{
bool canReplay = !IsDetached();
LOGDEBUG("device: %s: %d", __FUNCTION__, canReplay);
return canReplay;
}
/**
* Sets the device into the given play mode.
*
* @param play_mode new play mode (Audio/Video/External...)
*/
bool cSoftHdDevice::SetPlayMode(ePlayMode play_mode)
{
LOGDEBUG("device: %s: %d", __FUNCTION__, play_mode);
// A new play mode arrived, attach first if we did detach because of an external player
if (m_externalPlayerActive) {
TriggerEvent(AttachEvent{});
m_externalPlayerActive = false;
}
switch (play_mode) {
case pmNone:
TriggerEvent(StopEvent{});
break;
case pmAudioVideo:
case pmAudioOnly:
case pmAudioOnlyBlack:
case pmVideoOnly:
TriggerEvent(PlayEvent{});
break;
case pmExtern_THIS_SHOULD_BE_AVOIDED:
// External players like mpv (vdr-plugin-mpv) want to acquire DRM/ALSA
// so we release it here and set a flag. As soon as the next SetPlayMode arrives
// we then can attach again before changing to the new playmode.
m_pPipHandler->Disable();
TriggerEvent(DetachEvent{});
m_externalPlayerActive = true;
break;
default:
LOGERROR("device: %s: playmode not supported %d", play_mode);
return false;
break;
}
return true;
}
/**
* Play an audio packet
*
* This is the main function, which is called by VDR to play audio data
*
* @param data data of exactly one complete PES packet
* @param size size of PES packet
* @param id PES packet type
*
* The caller must ensure, that PlayAudio() is not called in detached state.
* (CanReplay() and HasDecoder() return false in this state and we are not
* the primary device.)
*/
int cSoftHdDevice::PlayAudio(const uchar *data, int size, uchar id)
{
// LOGDEBUG("device: %s: %p %p %d %d", __FUNCTION__, this, data, size, id);
if (IsDetached())
return size;
m_receivedAudio = true;
if (m_pAudio->IsBufferFull())
return 0;
cPesAudio pesPacket((const uint8_t*)data, size);
if (!pesPacket.IsValid()) {
m_audioReassemblyBuffer.Reset();
return size;
}
if (!m_receivedValidAudio && Transferring()) {
auto now = std::chrono::steady_clock::now();
auto timeUntilFirstPacketReceived = std::chrono::duration_cast<std::chrono::milliseconds>(now - m_channelSwitchStartTime).count();
LOGDEBUG("device: first valid audio packet arrives %dms after channel switch was triggered", timeUntilFirstPacketReceived);
if (!m_receivedValidVideo)
m_dataReceivedTime = now;
}
m_receivedValidAudio = true;
if (Transferring()) { // compensation is only necessary with live streams
m_pAudio->ClockDriftCompensation();
m_audioJitterTracker.PacketReceived();
m_pConfig->StatMaxShortTermAudioJitterMs = m_audioJitterTracker.GetShortTermMaxJitterMs();
m_pConfig->StatMaxLongTermAudioJitterMs = m_audioJitterTracker.GetLongTermMaxJitterMs();
}
if (m_audioChannelID != id) {
m_audioChannelID = id;
m_audioReassemblyBuffer.Reset();
m_pAudioDecoder->Close();
LOGDEBUG("device: %s: new channel id 0x%02X", __FUNCTION__, m_audioChannelID);
}
m_audioReassemblyBuffer.Push(pesPacket.GetPayload(), pesPacket.GetPayloadSize(), pesPacket.GetPts());
if (IsBufferingThresholdReached())
TriggerEvent(BufferingThresholdReachedEvent{});
// unpause audio, if the fast channel switch mode wants it to be started,
// the audio buffer reached the threshold and we are in live tv mode
if (m_channelSwitchMode == CHANNEL_SWITCH_FAST_AUDIO && Transferring() && m_pAudio->IsPaused() && IsAudioBufferingThresholdReached())
m_pAudio->SetPaused(false);
AVPacket *avpkt;
do {
if (!(avpkt = m_audioReassemblyBuffer.PopAvPacket()))
break;
if (m_pAudioDecoder->GetCodecId() == AV_CODEC_ID_NONE && m_audioReassemblyBuffer.GetCodec() != AV_CODEC_ID_NONE) {
// The playback has just started
m_pAudioDecoder->Close();
m_pAudioDecoder->Open(m_audioReassemblyBuffer.GetCodec());
}
m_pAudioDecoder->Decode(avpkt);
AVPacket *copy = avpkt;
av_packet_free(©);
} while (avpkt != nullptr);
return size;
}
/**
* Play a video packet of the main videostream
*
* This is the main function, which is called by VDR to play video data
*
* @param data A complete PES packet with optionally fragmented payload
* @param size the length of the PES packet including header
*
* This is called directly from VDR
*
* The caller must ensure, that PlayVideo() is not called in detached state.
* (CanReplay() and HasDecoder() return false in this state and we are not
* the primary device.)
*/
int cSoftHdDevice::PlayVideo(const uchar *data, int size)
{
// LOGDEBUG("device: %s: %p %d", __FUNCTION__, data, size);
if (IsDetached())
return size;
m_receivedVideo = true;
return PlayVideoInternal(m_pVideoStream, &m_videoReassemblyBuffer, data, size, Transferring(), true);
}
/**
* Gets the current System Time Counter, which can be used to
* synchronize audio, video and subtitles.
*/
int64_t cSoftHdDevice::GetSTC(void)
{
if (IsDetached())
return AV_NOPTS_VALUE;
switch (m_playbackMode) {
case NONE:
return AV_NOPTS_VALUE;
case AUDIO_AND_VIDEO:
case VIDEO_ONLY:
return m_pRender->GetVideoClock();
case AUDIO_ONLY:
return m_pAudio->GetHardwareOutputPtsTimebaseUnits();
}
abort();
}
/**
* Ask the output, if it can scale video
*
* @param rect requested video window rectangle
*
* @return the real rectangle or cRect::NULL if invalid
*/
cRect cSoftHdDevice::CanScaleVideo(const cRect & rect, __attribute__ ((unused)) int alignment)
{
if (m_screenWidth == m_osdWidth && m_screenHeight == m_osdHeight)
return rect;
double scaleFactor = std::min((double)m_screenWidth / m_osdWidth, (double)m_screenHeight / m_osdHeight);
int width = std::lround(scaleFactor * rect.Width());
int height = std::lround(scaleFactor * rect.Height());
int x = std::lround(scaleFactor * rect.X());
int y = std::lround(scaleFactor * rect.Y());
x = std::max(0, x);
y = std::max(0, y);
if (x + width > m_screenWidth)
width = m_screenWidth - x;
if (y + height > m_screenHeight)
height = m_screenHeight - y;
if (width <= 0 || height <= 0)
return cRect::Null;
LOGDEBUG2(L_DRM, "device: %s: scale rect %dx%d-%d|%d -> %dx%d-%d|%d", __FUNCTION__,
rect.Width(), rect.Height(), rect.X(), rect.Y(), width, height, x, y);
return cRect(x, y, width, height);
}
/**
* Scale the currently shown video
*
* @param x video window x coordinate OSD relative
* @param y video window x coordinate OSD relative
* @param width video window width OSD relative
* @param height video window height OSD relative
*/
void cSoftHdDevice::ScaleVideo(const cRect & rect)
{
if (IsDetached())
return;
LOGDEBUG2(L_OSD, "device: %s: %dx%d%+d%+d",
__FUNCTION__, rect.Width(), rect.Height(), rect.X(), rect.Y());
if (m_pRender)
m_pRender->SetVideoOutputPosition(rect);
}
/**
* Sets the device into a mode where replay is done slower.
* Every single frame shall then be displayed the given number of
* times. Forward is true if replay is done in the normal (forward)
* direction, false if it is done reverse.
* The cDvbPlayer uses the following values for the various speeds:
* 1x 2x 3x
* Fast Forward 6 3 1
* Fast Reverse 6 3 1
* Slow Forward 8 4 2
* Slow Reverse 63 48 24
*/
void cSoftHdDevice::TrickSpeed(int speed, bool forward)
{
LOGDEBUG("device: %s: %d %s", __FUNCTION__, speed, forward ? "forward" : "backward");
// This normalizes the VDR frame displaying count into a factor, representing how fast/slow the playback shall be.
// For example, a factor of 2.0 means twice as fast as normal, a factor of 0.5 means half as fast as normal (slow-mo).
// This is necessary because VDR sends only I-frames during trickspeed, but the distance between I-frames depends on the encoding parameters.
// Therefore, we send a normalized factor for the further components, which then calculate the necessary frame displaying count by considering the distance between I-frames.
double normalizedSpeed = 1;
static constexpr double MAX_SPEED = 3;
// these are arbitrary values, which feel just right
static constexpr double FAST_TRICKSPEED_FACTOR = 5; // the higher the factor, the faster the fast forward/reverse
static constexpr double SLOW_FORWARD_FACTOR = 2; // the higher the factor, the slower the slow-mo
// Fastest speed in reverse slow-mo is the original speed. Slower speeds are too slow, because of the already low frame rate.
static constexpr double SLOW_REVERSE_FACTOR = 1;
// speed of the trickspeed (VDR's magic frame displaying count)
switch (speed) {
case 6:
case 8:
case 63:
normalizedSpeed = 1; // slowest (both, in fast trickspeed and slow-mo)
break;
case 3:
case 4:
case 48:
normalizedSpeed = 2;
break;
case 1:
case 2:
case 24:
normalizedSpeed = 3; // fastest (both, in fast trickspeed and slow-mo)
break;
}
// figure out if VDR demands slow-mo or fast trickspeed
double tmp;
switch (speed) {
case 8:
case 4:
case 2:
case 63:
case 48:
case 24:
// slow-mo
tmp = (MAX_SPEED + 1) - normalizedSpeed;
if (forward)
tmp *= SLOW_FORWARD_FACTOR;
else
tmp *= SLOW_REVERSE_FACTOR;
normalizedSpeed = 1 / tmp;
break;
default:
// fast trickspeed
normalizedSpeed *= FAST_TRICKSPEED_FACTOR;
break;
}
TriggerEvent(TrickSpeedEvent{normalizedSpeed, speed != 0, forward});
}
/**
* Clears all video and audio data from the device.
*
* This is called by VDR via DeviceClear() in the Empty() call.
*
* Empty() does clear all VDR internal packets.
*/
void cSoftHdDevice::Clear(void)
{
LOGDEBUG("device: %s:", __FUNCTION__);
cDevice::Clear();
if (IsDetached())
return;
m_pRender->Halt();
m_pVideoStream->Halt();
m_pRender->SetDisplayOneFrameThenPause(true);
m_pVideoStream->CancelFilterThread();
m_videoReassemblyBuffer.Reset();
m_pVideoStream->ClearVdrCoreToDecoderQueue();
m_pRender->ClearDecoderToDisplayQueue();
if (m_playbackMode == AUDIO_AND_VIDEO || m_playbackMode == VIDEO_ONLY)
m_pVideoStream->FlushDecoder();
m_pRender->Reset();
m_pAudio->SetPaused(true);
m_pAudio->ResetHwDelayBaseline();
FlushAudio();
m_pStateMachine->ChangeState(BUFFERING);
m_pRender->Resume();
m_pVideoStream->Resume();
}
/**
* Sets the device into play mode (after a previous trick mode, or pause)
*
* This is called by VDR via DevicePlay() in the Play() and Goto() call
*/
void cSoftHdDevice::Play(void)
{
cDevice::Play();
TriggerEvent(PlayEvent{});
}
/**
* Puts the device into "freeze frame" mode.
*/
void cSoftHdDevice::Freeze(void)
{
LOGDEBUG("device: %s:", __FUNCTION__);
cDevice::Freeze();
TriggerEvent(PauseEvent{});
}
/**
* Display the given I-frame as a still picture.
*
* @param data pes or ts data of a frame
* @param length length of data area
*/
void cSoftHdDevice::StillPicture(const uchar *data, int size)
{
LOGDEBUG("device: %s: %s %p %d", __FUNCTION__, data[0] == 0x47 ? "ts" : "pes", data, size);
if (data[0] == 0x47) { // ts sync byte
cDevice::StillPicture(data, size);
return;
}
TriggerEvent(StillPictureEvent{data, size});
}
/**
* Return true if the device itself or any of the file handles in
* poller is ready for further action.
* If TimeoutMs is not zero, the device will wait up to the given number
* of milliseconds before returning in case it can't accept any data.
*
* @param poller file handles (unused)
* @param timeoutMs timeout in ms to become ready
*
* @retval true if ready
* @retval false if busy
*/
bool cSoftHdDevice::Poll(__attribute__ ((unused)) cPoller & poller, int timeoutMs)
{
// LOGDEBUG("device: %s: timeout %d", __FUNCTION__, timeout_ms);
if (IsDetached())
return true;
if (!m_pAudio->IsBufferFull() && !m_pVideoStream->IsInputBufferFull())
return true;
usleep(timeoutMs * 1000);
return false;
}
/**
* Return true, if the output buffers are empty, false otherwise.
* Wait max. up to timeoutMs in case the buffers are not empty.
*
* This function does not initiate a decoder drain like Drain()
* so some data may stay unprocessed in the decoder, while the other
* buffers are already emtpy. Therefore, players should use the
* new Drain() function instead.
*
* @param timeoutMs timeout in ms to become ready
*
* @return true, if the buffers are empty, false otherwise
*
* @note Flush() is marked DEPRECATED since APIVERSION 14
*/
bool cSoftHdDevice::Flush(int timeoutMs)
{
if (IsDetached())
return true;
// LOGDEBUG("device: %s: timeout %d ms", __FUNCTION__, timeoutMs);
const auto buffersEmpty = [&]() {
return m_playbackMode == AUDIO_ONLY
? m_pAudio->IsBufferEmpty()
: m_pVideoStream->BuffersEmpty();
};
const cTimeMs timeout(timeoutMs);
while (!buffersEmpty() && !timeout.TimedOut())
cCondWait::SleepMs(std::min(5, timeoutMs));
return buffersEmpty();
}
#if APIVERSNUM >= 30014
/**
* Force a decoder drain and return true, if all buffers have been played out
*
* @return true, if the buffers are empty, false otherwise
*/
bool cSoftHdDevice::Drain(void)
{
if (IsDetached())
return true;
// enter drain mode once
if (!m_draining) {
LOGDEBUG("device: %s: start draining", __FUNCTION__);
m_draining = true;
if (!m_videoReassemblyBuffer.IsEmpty())
m_pVideoStream->PushAvPacket(m_videoReassemblyBuffer.PopAvPacket());
m_pVideoStream->Drain();
}
const auto buffersEmpty = [&]() {
return m_playbackMode == AUDIO_ONLY
? m_pAudio->IsBufferEmpty()
: m_pVideoStream->BuffersEmpty();
};
if (!buffersEmpty())
return false;
LOGDEBUG("device: %s: drained, buffers are empty", __FUNCTION__);
m_draining = false;
return true;
}
#endif
/*********************************************************************
* VDR cStatus interface
********************************************************************/
/**
* Monitor a channel switch triggered by VDR (cStatus::ChannelSwitch())
*
* Save the timestamp when a channel switch is initiated (channelNum == 0)
* for later time measurement.
*/
void cSoftHdDevice::ChannelSwitch(const cDevice *device, int channelNum, bool liveView)
{
if (device != cDevice::PrimaryDevice())
return;
if (!liveView)
return;
if (channelNum == 0)
m_channelSwitchStartTime = std::chrono::steady_clock::now();
}
/*********************************************************************
* cSoftHdDevice public API - playback, display, decoder control
********************************************************************/
/**
* Disables deinterlacer (called from setup menu or conf)
*/
void cSoftHdDevice::SetDisableDeint(void)
{
if (m_pVideoStream)
m_pVideoStream->DisableDeint(m_pConfig->ConfigDisableDeint);
}
/**
* Forces the h264 decoder to wait for an I-Frame to start
*/
void cSoftHdDevice::SetDecoderNeedsIFrame(void)
{
if (m_pVideoStream)
m_pVideoStream->SetStartDecodingWithIFrame(m_pConfig->ConfigDecoderNeedsIFrame);
}
/**
* Parse the h264 stream width and height before starting the decoder
*/
void cSoftHdDevice::SetParseH264Dimensions(void)
{
if (m_pVideoStream)
m_pVideoStream->SetParseH264Dimensions(m_pConfig->ConfigParseH264Dimensions);
}
/**
* Force the decoder to fallback to software if the hardware decoder fails
* after the configured amount of packets were sent and no frame was received
*/
void cSoftHdDevice::SetDecoderFallbackToSw(bool enable)
{
if (!m_pVideoStream)
return;
if (enable)
m_pVideoStream->SetDecoderFallbackToSwNumPkts(m_pConfig->ConfigDecoderFallbackToSwNumPkts);
else
m_pVideoStream->SetDecoderFallbackToSwNumPkts(0);
}
/**
* Enable HDR display mode
*/
void cSoftHdDevice::SetEnableHdr(bool enable)
{
m_pRender->SetEnableHdr(enable);
};
/**
* Trigger a display mode change event if the mode changed
*
* @param idx setup menu array index of the mode
*/
void cSoftHdDevice::SetDisplayMode(int idx)
{
sDrmMode *mode = &m_pConfig->AutoDetectedDrmMode;
if (idx == CONFIG_DISPLAY_MODE_FOLLOW_VIDEO ||
idx == CONFIG_DISPLAY_MODE_FOLLOW_VIDEO_INTERLACED) {
mode = &m_pConfig->CurrentVideoDrmMode;
if (!mode->width || !m_pRender->CanHandleMode(mode))
mode = &m_pConfig->AutoDetectedDrmMode;
} else if (idx >= CONFIG_DISPLAY_MODE_MANUAL)
mode = &m_pConfig->CollectedDrmModes[idx - CONFIG_DISPLAY_MODE_MANUAL];
// Check, if the requested mode differs from the current one at all
if (!m_pConfig->CompareCurrentMode(mode)) {
LOGDEBUG("Add display mode change event to %s mode %dx%d@%.2f%s",
idx == CONFIG_DISPLAY_MODE_DEFAULT ? "default" :
(idx == CONFIG_DISPLAY_MODE_FOLLOW_VIDEO ? "follow video" :
(idx == CONFIG_DISPLAY_MODE_FOLLOW_VIDEO_INTERLACED ? "follow video interlaced" :
"fixed")),
mode->width, mode->height, mode->refreshRateHz, mode->interlaced ? "i" : "");
m_pEventHandler->AddEvent(DisplayChangeEvent{*mode});
}
}
/**
* Check if the buffering threshold has been reached
*
* During the BUFFERING state, this method determines when sufficient audio/video data
* has been buffered to start playback.
*
* ThresholdReached (Sync-Ability) is signalled
* 1) in audio only mode:
* -> PlayAudio() was called
* -> audio input has a valid pts
* -> enough audio data is buffered
* 2) in video only mode:
* -> PlayVideo() was called
* -> video input has a valid pts
* -> enough video data is buffered (which implies "a video frame reached the renderer")
* 3) in audio/video mode:
* -> audio input has a valid pts
* -> video input has a valid pts
* -> video and audio has enough data buffered (calculated from the first output pts to play)
* -> the render output buffer queue is completely filled once (which implies "a video frame reached the renderer")
*
* @retval true if playback should start (audio or video only or buffering threshold reached)
* @retval false if playback should not start
*
* @note In order to signal ThresholdReached, both (audio and video) need to have a valid pts in audio + video mode!
*/
bool cSoftHdDevice::IsBufferingThresholdReached()
{
if (m_pStateMachine->GetState() != BUFFERING)
return false;
bool audioHasInputPts = m_pAudio->HasInputPts();
bool videoHasInputPts = m_pVideoStream->HasInputPts();
bool videoHasOutputPts = m_pRender->GetOutputPtsMs() != AV_NOPTS_VALUE;
// Assume audio only or video only if no PES fragment from the other stream has been received, while the buffering threshold of the other stream is reached.
// Check for buffer fill level only if at least one PES packet was reassembled and pushed to the respective decoder.
bool audioOnly = audioHasInputPts && !videoHasInputPts && m_receivedAudio && !m_receivedVideo;
bool videoOnly = !audioHasInputPts && videoHasInputPts && !m_receivedAudio && m_receivedVideo;
if (audioOnly && m_pAudio->GetInputPtsMs() - m_pAudio->GetOutputPtsMs() > GetBufferFillLevelThresholdMs()) {
LOGDEBUG("device: %s: Detected audio only", __FUNCTION__);
return true;
} else if (videoOnly && videoHasOutputPts && m_pVideoStream->GetInputPtsMs() - m_pRender->GetOutputPtsMs() > GetBufferFillLevelThresholdMs()) {
LOGDEBUG("device: %s: Detected video only", __FUNCTION__);
return true;
} else if (!audioHasInputPts || !videoHasInputPts || !videoHasOutputPts)
return false; // Either no video or no audio received, yet. Or, video didn't make it to the output buffer, yet.
int64_t syncedAudioBufferFillLevelMs = m_pAudio->GetInputPtsMs() - GetFirstAudioPtsMsToPlay();
int64_t syncedVideoBufferFillLevelMs = m_pVideoStream->GetInputPtsMs() - GetFirstVideoPtsMsToPlay();
int audioBehindVideo = m_pRender->GetOutputPtsMs() - m_pAudio->GetOutputPtsMs() - GetVideoAudioDelayMs();
// if channel switch mode is CHANNEL_SWITCH_FAST_AUDIO, wait for audio to come up with video before firing a BufferingThresholdReached
bool readyToStartVideoPlayback = m_channelSwitchMode == CHANNEL_SWITCH_FAST_AUDIO ? (audioBehindVideo <= 0) : true;
bool reached = m_pRender->IsOutputBufferFull() && // video decoder output buffer (audio hardware output buffer is negligible)
syncedVideoBufferFillLevelMs > GetBufferFillLevelThresholdMs() && // video decoder input buffer
syncedAudioBufferFillLevelMs > GetBufferFillLevelThresholdMs() && // audio decoder output buffer
readyToStartVideoPlayback;
if (reached) {
LOGDEBUG2(L_AV_SYNC, "buffering threshold reached - PTS: %s (audio), %s (video) - buffer fill levels: %ldms (audio) %ldms (video)",
Timestamp2String(m_pAudio->GetOutputPtsMs(), 1),
Timestamp2String(m_pRender->GetOutputPtsMs(), 1),
syncedAudioBufferFillLevelMs,
syncedVideoBufferFillLevelMs);
}
return reached;
}
/**
* Returns true, if audio buffer is filled enough to start audio playback
*
* @retval true if audio playback should start
* @retval false if audio playback should not start
*
* @note Used for fast channel switch
*/
bool cSoftHdDevice::IsAudioBufferingThresholdReached()
{
if (m_pStateMachine->GetState() != BUFFERING)
return false;
bool audioHasInputPts = m_pAudio->HasInputPts();
bool videoHasInputPts = m_pVideoStream->HasInputPts();
bool videoHasOutputPts = m_pRender->GetOutputPtsMs() != AV_NOPTS_VALUE;
// only start audio playback, if video is already there
if (!audioHasInputPts || !videoHasInputPts || !videoHasOutputPts)
return false;