Repository navigation
Expand file tree
/
Copy pathdevice.cpp
More file actions
2425 lines (2073 loc) · 70.2 KB
/
Copy pathdevice.cpp
File metadata and controls
2425 lines (2073 loc) · 70.2 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 device.cpp
* Output Device
*
* This file defines cOutputDevice 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 <cinttypes>
#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 "device.h"
#include "grab.h"
#include "hardwaredevice.h"
#include "jittertracker.h"
#include "logger.h"
#include "osdprovider.h"
#include "pes.h"
#include "pip.h"
#include "statemachine.h"
#include "videorender.h"
#include "videostream.h"
/**
* Create the device
*
* Initializes some member variables
*
* @param config pointer to cDeviceConfig class
*/
cOutputDevice::cOutputDevice(cDeviceConfig *config)
: m_pConfig(config)
{
m_pStateMachine = std::make_unique<cStateMachine>(this);
}
/**
* Destroy the device
*
* Only delete objects, if they were created in Initialize()
*/
cOutputDevice::~cOutputDevice(void)
{
if (!m_initialized)
return;
m_initialized = false; // not necessary, just for documentation
delete m_pEventHandler;
delete m_pPipHandler;
delete m_pHardwareDevice;
delete m_pSpuDecoder;
}
/*********************************************************************
* VDR cPlugin interface (wrapped by cPluginDrmDevice)
********************************************************************/
/**
* Initialize the device
*/
bool cOutputDevice::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_pPipHandler = new cPipHandler(this);
auto channelSwitchStartTime = std::chrono::steady_clock::now();
LOGGER->SetChannelSwitchStartTime(channelSwitchStartTime);
LOGGER->SetChannelSwitchDataReceivedTime(channelSwitchStartTime);
m_pipUseAlt = m_pConfig->ConfigPipUseAlt;
m_channelSwitchMode = static_cast<ChannelSwitchMode>(m_pConfig->ConfigVideoChannelSwitchMode);
m_passthroughOn = m_pConfig->ConfigAudioPassthroughState;
m_initialized = true;
return true;
}
/**
* Called by VDR when the plugin is started.
*/
int cOutputDevice::Start(void)
{
LOGDEBUG("device: %s", __FUNCTION__);
TriggerEvent(AttachEvent{});
return true;
}
/**
* Called by VDR when the plugin is stopped.
*/
void cOutputDevice::Stop(void)
{
LOGDEBUG("device: %s", __FUNCTION__);
TriggerDetachEvent();
}
/*********************************************************************
* VDR cDevice interface
********************************************************************/
/**
* Informs a device that it will be the primary device
*
* @param on flag if becoming or loosing primary
*/
void cOutputDevice::MakePrimaryDevice(bool on)
{
LOGDEBUG("device: %s: %d", __FUNCTION__, on);
if (on)
m_pOsdProvider = new cDeviceOsdProvider(this); // no need to delete it, VDR does it
cDevice::MakePrimaryDevice(on);
}
/**
* Tells whether this device has an MPEG decoder
*/
bool cOutputDevice::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 *cOutputDevice::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 *cOutputDevice::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 cOutputDevice::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 cOutputDevice::SetVideoFormat(bool videoFormat16_9)
{
LOGDEBUG("device: %s: %d", __FUNCTION__, videoFormat16_9);
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 cOutputDevice::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 cOutputDevice::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 cOutputDevice::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 cOutputDevice::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 cOutputDevice::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;
}
auto now = std::chrono::steady_clock::now();
auto durationSinceChannelSwitchMs = std::chrono::duration_cast<std::chrono::milliseconds>(now - LOGGER->GetChannelSwitchStartTime()).count();
SetDrain(false);
switch (play_mode) {
case pmNone:
TriggerEvent(StopEvent{});
break;
case pmAudioVideo:
case pmAudioOnly:
case pmAudioOnlyBlack:
case pmVideoOnly:
m_logPlaybackStart = true;
LOGDEBUG2(L_AV_SYNC, "TRACE: +%5dms SetPlayMode()", (int)durationSinceChannelSwitchMs);
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.
TriggerDetachEvent();
m_externalPlayerActive = true;
break;
default:
LOGERROR("device: %s: playmode not supported %d", __FUNCTION__, 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 cOutputDevice::PlayAudio(const uchar *data, int size, uchar id)
{
// LOGDEBUG("device: %s: %p %p %d %d", __FUNCTION__, this, data, size, id);
if (IsDetached())
return size;
// audio, which can't be decoded, is dropped: the playback starts with the video only
m_receivedAudio = !m_pAudioDecoder->OpenFailed();
// Special audio-only trickspeed handling:
// Advance the pts and block the thread depending on the pts difference and trickspeed factor.
// Don't forward any data to the hardware, because audio is muted anyway.
bool slowForward = m_pAudio->IsForwardTrickSpeed() && m_pAudio->IsSlowTrickSpeed();
if (m_playbackMode == AUDIO_ONLY && m_pStateMachine->GetState() == State::TRICK_SPEED && !slowForward) {
cPesAudio pesPacket((const uint8_t*)data, size);
if (pesPacket.IsValid() && pesPacket.GetPts() != AV_NOPTS_VALUE)
m_pAudio->AdvanceTrickSpeedPts(pesPacket.GetPts());
return size;
}
if (m_pAudio->IsBufferFull())
return 0;
cPesAudio pesPacket((const uint8_t*)data, size);
if (!pesPacket.IsValid()) {
m_audioReassemblyBuffer.Reset();
return size;
}
if (!m_receivedValidAudio) {
auto now = std::chrono::steady_clock::now();
auto durationSinceChannelSwitchMs = std::chrono::duration_cast<std::chrono::milliseconds>(now - LOGGER->GetChannelSwitchStartTime()).count();
LOGDEBUG2(L_AV_SYNC, "TRACE: +%5dms PlayAudio() first valid audio data", (int)durationSinceChannelSwitchMs);
if (!m_receivedValidVideo)
LOGGER->SetChannelSwitchDataReceivedTime(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);
}
const uint8_t *payload = pesPacket.GetPayload();
int payloadSize = pesPacket.GetPayloadSize();
AVPacket *lpcmPkt = nullptr;
// DVD audio (e.g. of the dvd plugin) starts with the sub stream header
if (IsDvdAudioSubStream(id)) {
if (payloadSize <= DVD_SUBSTREAM_HEADER_SIZE)
return size;
payload += DVD_SUBSTREAM_HEADER_SIZE;
payloadSize -= DVD_SUBSTREAM_HEADER_SIZE;
}
// LPCM has no sync words, every packet is decoded (starting with the LPCM header)
if (IsDvdLpcmSubStream(id)) {
if (!(lpcmPkt = av_packet_alloc()) || av_new_packet(lpcmPkt, payloadSize) < 0) {
av_packet_free(&lpcmPkt);
return size;
}
memcpy(lpcmPkt->data, payload, payloadSize);
lpcmPkt->pts = pesPacket.GetPts();
} else
m_audioReassemblyBuffer.Push(payload, payloadSize, pesPacket.GetPts());
// fire playback start, if all buffers reached the threshold fill levels
if (CheckPlaybackStartConditions())
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 (CheckAudioPlaybackStartConditions())
m_pAudio->SetPaused(false);
AVPacket *avpkt;
do {
AVCodecID codecId;
if (lpcmPkt) {
avpkt = lpcmPkt;
lpcmPkt = nullptr;
codecId = AV_CODEC_ID_PCM_DVD;
} else if (IsDvdLpcmSubStream(id) || !(avpkt = m_audioReassemblyBuffer.PopAvPacket())) {
break;
} else
codecId = m_audioReassemblyBuffer.GetCodec();
// (Re)open the decoder, if the playback has just started or the codec changed.
// The PES stream id doesn't change between AC-3 and E-AC-3 (both are private stream 1),
// so the codec has to be compared.
if (codecId != AV_CODEC_ID_NONE && m_pAudioDecoder->GetCodecId() != codecId) {
if (m_pAudioDecoder->GetCodecId() != AV_CODEC_ID_NONE)
LOGINFO("device: %s: audio codec changed from %s to %s", __FUNCTION__,
avcodec_get_name(m_pAudioDecoder->GetCodecId()), avcodec_get_name(codecId));
m_pAudioDecoder->Close();
m_pAudioDecoder->Open(codecId);
}
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 cOutputDevice::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 cOutputDevice::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:
bool slowForward = m_pAudio->IsForwardTrickSpeed() && m_pAudio->IsSlowTrickSpeed();
if (m_pStateMachine->GetState() == State::TRICK_SPEED && !slowForward)
return m_pAudio->GetTrickSpeedPtsTimebaseUnits();
return m_pAudio->GetHardwareOutputPtsTimebaseUnits();
}
abort();
}
/**
* Ask the output, if it can scale video
*
* @param rect requested video window rectangle
* @param alignment requested alignment of the video window (unused)
*
* @return the real rectangle or cRect::Null if invalid
*/
cRect cOutputDevice::CanScaleVideo(const cRect & rect, [[maybe_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 rect video window (OSD relative), cRect::Null for full screen
*/
void cOutputDevice::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 cOutputDevice::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 cOutputDevice::Clear(void)
{
LOGDEBUG("device: %s:", __FUNCTION__);
cDevice::Clear();
if (IsDetached())
return;
m_pRender->Halt();
m_pVideoStream->Halt();
SetDrain(false);
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 cOutputDevice::Play(void)
{
LOGDEBUG("device: %s:", __FUNCTION__);
cDevice::Play();
TriggerEvent(PlayEvent{});
}
/**
* Puts the device into "freeze frame" mode.
*/
void cOutputDevice::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 size length of data area
*/
void cOutputDevice::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 cOutputDevice::Poll([[maybe_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 DrainDevice()
* so some data may stay unprocessed in the decoder, while the other
* buffers are already emtpy. Therefore, players should use the
* DrainDevice() 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 cOutputDevice::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();
};
// the buffered data is played, even if the buffering threshold isn't reached
m_flushing = true;
const cTimeMs timeout(timeoutMs);
while (!buffersEmpty() && !timeout.TimedOut())
cCondWait::SleepMs(std::min(5, timeoutMs));
m_flushing = false;
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 cOutputDevice::DrainDevice(void)
{
if (IsDetached())
return true;
// enter drain mode once
if (!m_draining) {
if (!m_videoReassemblyBuffer.IsEmpty()) {
// VDR calls DrainDevice() until it returns true, so retry later instead of dropping the last frame
if (m_pVideoStream->IsInputBufferFull())
return false;
m_pVideoStream->PushAvPacket(m_videoReassemblyBuffer.PopAvPacket());
}
if (!m_pVideoStream->Drain())
return false;
SetDrain(true);
}
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__);
SetDrain(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, and try a failed audio passthrough again.
*/
void cOutputDevice::ChannelSwitch(const cDevice *device, int channelNum, bool liveView)
{
if (device != cDevice::PrimaryDevice() || !liveView || channelNum != 0)
return;
auto now = std::chrono::steady_clock::now();
LOGGER->SetChannelSwitchStartTime(now);
LOGDEBUG2(L_AV_SYNC, "TRACE: channel switch");
// the zoom is chosen for the content
m_zoomLevel = 0;
// the receiver may have been switched on meanwhile
if (!IsDetached())
m_pAudioDecoder->RetryPassthrough();
}
/**
* Monitor a replay start or end
*
* Save the timestamp when a replay is started for later time measurement,
* and try a failed audio passthrough again.
*/
void cOutputDevice::Replaying([[maybe_unused]]const cControl *control,
[[maybe_unused]]const char *name,
[[maybe_unused]]const char *filenameDevice,
bool on)
{
if (!on)
return;
auto now = std::chrono::steady_clock::now();
LOGGER->SetChannelSwitchStartTime(now);
LOGDEBUG2(L_AV_SYNC, "TRACE: replay start");
// the zoom is chosen for the content
m_zoomLevel = 0;
// the receiver may have been switched on meanwhile
if (!IsDetached())
m_pAudioDecoder->RetryPassthrough();
}
/*********************************************************************
* cOutputDevice public API - playback, display, decoder control
********************************************************************/
/**
* Disables deinterlacer (called from setup menu or conf)
*/
void cOutputDevice::SetDisableDeint(void)
{
if (m_pVideoStream)
m_pVideoStream->DisableDeint(m_pConfig->ConfigDisableDeint);
}
/**
* 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 cOutputDevice::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 cOutputDevice::SetEnableHdr(bool enable)
{
m_pRender->SetEnableHdr(enable);
};
/**
* Get the zoom-in factor of the active zoom level
*
* @return zoom-in factor in 1/10 % (0 = no zoom)
*/
int cOutputDevice::GetZoom(void)
{
int level = m_zoomLevel;
if (level < 1 || level > cDeviceConfig::ZOOM_LEVELS)
return 0;
return m_pConfig->ConfigZoomLevel[level - 1];
}
/**
* Select a zoom level
*
* The zoom level is reset with every channel switch and replay start.
*
* @param level zoom level (1 - 5) or 0 to disable the zoom
*
* @return false, if the level doesn't exist or is disabled in the setup
*/
bool cOutputDevice::SetZoomLevel(int level)
{
if (level < 0 || level > cDeviceConfig::ZOOM_LEVELS ||
(level > 0 && !m_pConfig->ConfigZoomLevel[level - 1]))
return false;
m_zoomLevel = level;
LOGDEBUG("device: %s: zoom level %d (+%d.%d%%)", __FUNCTION__, level, GetZoom() / 10, GetZoom() % 10);