-
Notifications
You must be signed in to change notification settings - Fork 341
/
mythplayer.cpp
2041 lines (1757 loc) · 59.7 KB
/
mythplayer.cpp
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
// -*- Mode: c++ -*-
#undef HAVE_AV_CONFIG_H
// C++ headers
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
// Qt headers
#include <QCoreApplication>
#include <QDir>
#include <QHash>
#include <QMap>
#include <QThread>
#include <QtCore/qnumeric.h>
#include <utility>
// MythTV headers
#include "mthread.h"
#include "mythconfig.h"
#include "mythplayer.h"
#include "DetectLetterbox.h"
#include "audioplayer.h"
#include "programinfo.h"
#include "mythcorecontext.h"
#include "livetvchain.h"
#include "avformatdecoder.h"
#include "dummydecoder.h"
#include "tv_play.h"
#include "mythlogging.h"
#include "mythmiscutil.h"
#include "audiooutput.h"
#include "cardutil.h"
#include "mythavutil.h"
#include "jitterometer.h"
#include "mythtimer.h"
#include "mythuiactions.h"
#include "io/mythmediabuffer.h"
#include "tv_actions.h"
#include "decoders/mythdecoderthread.h"
#include "mythvideooutnull.h"
#include "mythcodeccontext.h"
// MythUI headers
#include <mythmainwindow.h>
extern "C" {
#include "libavcodec/avcodec.h"
}
#include "remoteencoder.h"
static unsigned dbg_ident(const MythPlayer* /*player*/);
#define LOC QString("Player(%1): ").arg(dbg_ident(this),0,36)
const int MythPlayer::kNightModeBrightenssAdjustment = 10;
const int MythPlayer::kNightModeContrastAdjustment = 10;
// Exact frame seeking, no inaccuracy allowed.
const double MythPlayer::kInaccuracyNone = 0;
// By default, when seeking, snap to a keyframe if the keyframe's
// distance from the target frame is less than 10% of the total seek
// distance.
const double MythPlayer::kInaccuracyDefault = 0.1;
// Allow greater inaccuracy (50%) in the cutlist editor (unless the
// editor seek distance is set to 1 frame or 1 keyframe).
const double MythPlayer::kInaccuracyEditor = 0.5;
// Any negative value means completely inexact, i.e. seek to the
// keyframe that is closest to the target.
const double MythPlayer::kInaccuracyFull = -1.0;
MythPlayer::MythPlayer(PlayerContext* Context, PlayerFlags Flags)
: m_playerCtx(Context),
m_playerFlags(Flags),
// CC608/708
m_cc608(this), m_cc708(this),
// Audio
m_audio(this, (Flags & kAudioMuted) != 0)
{
m_playerThread = QThread::currentThread();
#ifdef Q_OS_ANDROID
m_playerThreadId = gettid();
#endif
m_deleteMap.SetPlayerContext(m_playerCtx);
m_liveTV = m_playerCtx->m_tvchain;
m_vbiMode = VBIMode::Parse(gCoreContext->GetSetting("VbiFormat"));
m_captionsEnabledbyDefault = gCoreContext->GetBoolSetting("DefaultCCMode");
m_endExitPrompt = gCoreContext->GetNumSetting("EndOfRecordingExitPrompt");
// Get VBI page number
QString mypage = gCoreContext->GetSetting("VBIpageNr", "888");
bool valid = false;
uint tmp = mypage.toInt(&valid, 16);
m_ttPageNum = (valid) ? tmp : m_ttPageNum;
m_cc608.SetTTPageNum(m_ttPageNum);
}
MythPlayer::~MythPlayer(void)
{
QMutexLocker lock2(&m_vidExitLock);
SetDecoder(nullptr);
delete m_decoderThread;
m_decoderThread = nullptr;
delete m_videoOutput;
m_videoOutput = nullptr;
}
void MythPlayer::SetWatchingRecording(bool mode)
{
m_watchingRecording = mode;
if (m_decoder)
m_decoder->SetWatchingRecording(mode);
}
bool MythPlayer::IsWatchingInprogress(void) const
{
return m_watchingRecording && m_playerCtx->m_recorder && m_playerCtx->m_recorder->IsValidRecorder();
}
void MythPlayer::PauseBuffer(void)
{
m_bufferPauseLock.lock();
if (m_playerCtx->m_buffer)
{
m_playerCtx->m_buffer->Pause();
m_playerCtx->m_buffer->WaitForPause();
}
m_bufferPaused = true;
m_bufferPauseLock.unlock();
}
void MythPlayer::UnpauseBuffer(void)
{
m_bufferPauseLock.lock();
if (m_playerCtx->m_buffer)
m_playerCtx->m_buffer->Unpause();
m_bufferPaused = false;
m_bufferPauseLock.unlock();
}
bool MythPlayer::Pause(void)
{
while (!m_pauseLock.tryLock(100))
{
LOG(VB_PLAYBACK, LOG_INFO, LOC + "Waited 100ms to get pause lock.");
DecoderPauseCheck();
}
bool already_paused = m_allPaused;
if (already_paused)
{
m_pauseLock.unlock();
return already_paused;
}
m_nextPlaySpeed = 0.0;
m_nextNormalSpeed = false;
PauseVideo();
m_audio.Pause(true);
PauseDecoder();
PauseBuffer();
if (!m_decoderPaused)
PauseDecoder(); // Retry in case audio only stream
m_allPaused = m_decoderPaused && m_videoPaused && m_bufferPaused;
{
if (FlagIsSet(kVideoIsNull) && m_decoder)
m_decoder->UpdateFramesPlayed();
else if (m_videoOutput && !FlagIsSet(kVideoIsNull))
m_framesPlayed = m_videoOutput->GetFramesPlayed();
}
m_pauseLock.unlock();
emit PauseChanged(m_allPaused);
return already_paused;
}
bool MythPlayer::Play(float speed, bool normal, bool unpauseaudio)
{
m_pauseLock.lock();
LOG(VB_PLAYBACK, LOG_INFO, LOC +
QString("Play(%1, normal %2, unpause audio %3)")
.arg(speed,5,'f',1).arg(normal).arg(unpauseaudio));
if (m_deleteMap.IsEditing())
{
LOG(VB_GENERAL, LOG_ERR, LOC + "Ignoring Play(), in edit mode.");
m_pauseLock.unlock();
return false;
}
m_avSync.InitAVSync();
SetEof(kEofStateNone);
UnpauseBuffer();
UnpauseDecoder();
if (unpauseaudio)
m_audio.Pause(false);
UnpauseVideo();
m_allPaused = false;
m_nextPlaySpeed = speed;
m_nextNormalSpeed = normal;
m_pauseLock.unlock();
emit PauseChanged(m_allPaused);
return true;
}
void MythPlayer::PauseVideo(void)
{
m_videoPauseLock.lock();
m_needNewPauseFrame = true;
m_videoPaused = true;
m_videoPauseLock.unlock();
}
void MythPlayer::UnpauseVideo(void)
{
m_videoPauseLock.lock();
m_videoPaused = false;
m_videoPauseLock.unlock();
}
void MythPlayer::SetPlayingInfo(const ProgramInfo &pginfo)
{
assert(m_playerCtx);
if (!m_playerCtx)
return;
m_playerCtx->LockPlayingInfo(__FILE__, __LINE__);
m_playerCtx->SetPlayingInfo(&pginfo);
m_playerCtx->UnlockPlayingInfo(__FILE__, __LINE__);
}
void MythPlayer::SetPlaying(bool is_playing)
{
QMutexLocker locker(&m_playingLock);
m_playing = is_playing;
m_playingWaitCond.wakeAll();
}
bool MythPlayer::IsPlaying(std::chrono::milliseconds wait_in_msec, bool wait_for) const
{
QMutexLocker locker(&m_playingLock);
if (wait_in_msec == 0ms)
return m_playing;
MythTimer t;
t.start();
while ((wait_for != m_playing) && (t.elapsed() < wait_in_msec))
{
m_playingWaitCond.wait(
&m_playingLock, std::max(0ms,wait_in_msec - t.elapsed()).count());
}
return m_playing;
}
bool MythPlayer::InitVideo(void)
{
if (!m_playerCtx)
return false;
if (!m_decoder)
{
LOG(VB_GENERAL, LOG_ERR, LOC + "Cannot create a video renderer without a decoder.");
return false;
}
m_videoOutput = MythVideoOutputNull::Create(m_videoDim, m_videoDispDim, m_videoAspect,
m_decoder->GetVideoCodecID());
if (!m_videoOutput)
{
LOG(VB_GENERAL, LOG_ERR, LOC + "Couldn't create VideoOutput instance. Exiting..");
SetErrored(tr("Failed to initialize video output"));
return false;
}
return true;
}
void MythPlayer::ReinitVideo(bool ForceUpdate)
{
bool aspect_only = false;
{
QMutexLocker locker(&m_vidExitLock);
m_videoOutput->SetVideoFrameRate(static_cast<float>(m_videoFrameRate));
float video_aspect = (m_forcedVideoAspect > 0) ? m_forcedVideoAspect : m_videoAspect;
if (!m_videoOutput->InputChanged(m_videoDim, m_videoDispDim, video_aspect,
m_decoder->GetVideoCodecID(), aspect_only,
m_maxReferenceFrames, ForceUpdate))
{
LOG(VB_GENERAL, LOG_ERR, LOC + "Failed to Reinitialize Video. Exiting..");
SetErrored(tr("Failed to reinitialize video output"));
return;
}
}
if (!aspect_only)
ClearAfterSeek();
}
void MythPlayer::SetKeyframeDistance(int keyframedistance)
{
m_keyframeDist = (keyframedistance > 0) ? static_cast<uint>(keyframedistance) : m_keyframeDist;
}
void MythPlayer::SetVideoParams(int width, int height, double fps,
float aspect, bool ForceUpdate,
int ReferenceFrames, FrameScanType /*scan*/, const QString& codecName)
{
bool paramsChanged = ForceUpdate;
if (width >= 0 && height >= 0)
{
paramsChanged = true;
m_videoDim = m_videoDispDim = QSize(width, height);
m_videoAspect = aspect > 0.0F ? aspect : static_cast<float>(width) / height;
}
if (!qIsNaN(fps) && fps > 0.0 && fps < 121.0)
{
paramsChanged = true;
m_videoFrameRate = fps;
if (m_ffrewSkip != 0 && m_ffrewSkip != 1)
{
UpdateFFRewSkip();
}
else
{
float temp_speed = (m_playSpeed == 0.0F) ?
m_audio.GetStretchFactor() : m_playSpeed;
SetFrameInterval(kScan_Progressive,
1.0 / (m_videoFrameRate * static_cast<double>(temp_speed)));
}
}
if (!codecName.isEmpty())
{
m_codecName = codecName;
paramsChanged = true;
}
if (ReferenceFrames > 0)
{
m_maxReferenceFrames = ReferenceFrames;
paramsChanged = true;
}
// Mediacodec/Surface has an issue rendering frames after seeks.
// Enable the FF/Rew work around when using it.
m_ffrewUseRenderOne =
m_decoder && codec_is_mediacodec(m_decoder->GetVideoCodecID());
if (!paramsChanged)
return;
if (m_videoOutput)
ReinitVideo(ForceUpdate);
if (IsErrored())
return;
}
void MythPlayer::SetFrameRate(double fps)
{
m_videoFrameRate = fps;
float temp_speed = (m_playSpeed == 0.0F) ? m_audio.GetStretchFactor() : m_playSpeed;
if (abs(m_ffrewSkip) > 1)
UpdateFFRewSkip();
else
SetFrameInterval(kScan_Progressive, 1.0 / (m_videoFrameRate * static_cast<double>(temp_speed)));
}
void MythPlayer::SetFileLength(std::chrono::seconds total, int frames)
{
m_totalLength = total;
m_totalFrames = frames;
}
void MythPlayer::SetDuration(std::chrono::seconds duration)
{
m_totalDuration = duration;
}
void MythPlayer::OpenDummy(void)
{
m_isDummy = true;
if (!m_videoOutput)
{
SetKeyframeDistance(15);
SetVideoParams(720, 576, 25.00, 1.25F, false, 2);
}
m_playerCtx->LockPlayingInfo(__FILE__, __LINE__);
auto *dec = new DummyDecoder(this, *(m_playerCtx->m_playingInfo));
m_playerCtx->UnlockPlayingInfo(__FILE__, __LINE__);
SetDecoder(dec);
}
void MythPlayer::CreateDecoder(TestBufferVec & TestBuffer)
{
if (AvFormatDecoder::CanHandle(TestBuffer, m_playerCtx->m_buffer->GetFilename()))
SetDecoder(new AvFormatDecoder(this, *m_playerCtx->m_playingInfo, m_playerFlags));
}
int MythPlayer::OpenFile(int Retries)
{
// Sanity check
if (!m_playerCtx || !m_playerCtx->m_buffer)
return -1;
LOG(VB_GENERAL, LOG_INFO, LOC + QString("Opening '%1'").arg(m_playerCtx->m_buffer->GetSafeFilename()));
m_isDummy = false;
m_liveTV = m_playerCtx->m_tvchain && m_playerCtx->m_buffer->LiveMode();
// Dummy setup for livetv transtions. Can we get rid of this?
if (m_playerCtx->m_tvchain)
{
int currentposition = m_playerCtx->m_tvchain->GetCurPos();
if (m_playerCtx->m_tvchain->GetInputType(currentposition) == "DUMMY")
{
OpenDummy();
return 0;
}
}
// Start the RingBuffer read ahead thread
m_playerCtx->m_buffer->Start();
/// OSX has a small stack, so we put this buffer on the heap instead.
TestBufferVec testbuf {};
testbuf.reserve(kDecoderProbeBufferSize);
UnpauseBuffer();
// delete any pre-existing recorder
SetDecoder(nullptr);
int testreadsize = 2048;
// Test the incoming buffer and create a suitable decoder
MythTimer bigTimer;
bigTimer.start();
std::chrono::milliseconds timeout =
std::max(500ms * (Retries + 1), 30000ms);
while (testreadsize <= kDecoderProbeBufferSize)
{
testbuf.resize(testreadsize);
MythTimer peekTimer;
peekTimer.start();
while (m_playerCtx->m_buffer->Peek(testbuf) != testreadsize)
{
// NB need to allow for streams encountering network congestion
if (peekTimer.elapsed() > 30s || bigTimer.elapsed() > timeout
|| m_playerCtx->m_buffer->GetStopReads())
{
LOG(VB_GENERAL, LOG_ERR, LOC +
QString("OpenFile(): Could not read first %1 bytes of '%2'")
.arg(testreadsize)
.arg(m_playerCtx->m_buffer->GetFilename()));
SetErrored(tr("Could not read first %1 bytes").arg(testreadsize));
return -1;
}
LOG(VB_GENERAL, LOG_WARNING, LOC + "OpenFile() waiting on data");
std::this_thread::sleep_for(50ms);
}
m_playerCtx->LockPlayingInfo(__FILE__, __LINE__);
CreateDecoder(testbuf);
m_playerCtx->UnlockPlayingInfo(__FILE__, __LINE__);
if (m_decoder || (bigTimer.elapsed() > timeout))
break;
testreadsize <<= 1;
}
// Fail
if (!m_decoder)
{
LOG(VB_GENERAL, LOG_ERR, LOC +
QString("Couldn't find an A/V decoder for: '%1'")
.arg(m_playerCtx->m_buffer->GetFilename()));
SetErrored(tr("Could not find an A/V decoder"));
return -1;
}
if (m_decoder->IsErrored())
{
LOG(VB_GENERAL, LOG_ERR, LOC + "Could not initialize A/V decoder.");
SetDecoder(nullptr);
SetErrored(tr("Could not initialize A/V decoder"));
return -1;
}
// Pre-init the decoder
m_decoder->SetSeekSnap(0);
m_decoder->SetLiveTVMode(m_liveTV);
m_decoder->SetWatchingRecording(m_watchingRecording);
// TODO (re)move this into MythTranscode player
m_decoder->SetTranscoding(m_transcoding);
// Open the decoder
int result = m_decoder->OpenFile(m_playerCtx->m_buffer, false, testbuf);
if (result < 0)
{
LOG(VB_GENERAL, LOG_ERR, QString("Couldn't open decoder for: %1")
.arg(m_playerCtx->m_buffer->GetFilename()));
SetErrored(tr("Could not open decoder"));
return -1;
}
// Disable audio if necessary
m_audio.CheckFormat();
// Livetv, recording or in-progress
if (result > 0)
{
m_hasFullPositionMap = true;
m_deleteMap.LoadMap();
m_deleteMap.TrackerReset(0);
}
// Determine the initial bookmark and update it for the cutlist
m_bookmarkSeek = GetBookmark();
m_deleteMap.TrackerReset(m_bookmarkSeek);
m_deleteMap.TrackerWantsToJump(m_bookmarkSeek, m_bookmarkSeek);
if (!gCoreContext->IsDatabaseIgnored() &&
m_playerCtx->m_playingInfo->QueryAutoExpire() == kLiveTVAutoExpire)
{
gCoreContext->SaveSetting("DefaultChanid",
static_cast<int>(m_playerCtx->m_playingInfo->GetChanID()));
QString callsign = m_playerCtx->m_playingInfo->GetChannelSchedulingID();
QString channum = m_playerCtx->m_playingInfo->GetChanNum();
gCoreContext->SaveSetting("DefaultChanKeys", callsign + "[]:[]" + channum);
if (m_playerCtx->m_recorder && m_playerCtx->m_recorder->IsValidRecorder())
{
uint cardid = static_cast<uint>(m_playerCtx->m_recorder->GetRecorderNumber());
CardUtil::SetStartChannel(cardid, channum);
}
}
return IsErrored() ? -1 : 0;
}
void MythPlayer::SetFramesPlayed(uint64_t played)
{
m_framesPlayed = played;
if (m_videoOutput)
m_videoOutput->SetFramesPlayed(played);
}
/** \fn MythPlayer::GetFreeVideoFrames(void)
* \brief Returns the number of frames available for decoding onto.
*/
int MythPlayer::GetFreeVideoFrames(void) const
{
if (m_videoOutput)
return m_videoOutput->FreeVideoFrames();
return 0;
}
/**
* \brief Removes a frame from the available queue for decoding onto.
*
* This places the frame in the limbo queue, from which frames are
* removed if they are added to another queue. Normally a frame is
* freed from limbo either by a ReleaseNextVideoFrame() or
* DiscardVideoFrame() call; but limboed frames are also freed
* during a seek reset.
*/
MythVideoFrame *MythPlayer::GetNextVideoFrame(void)
{
if (m_videoOutput)
return m_videoOutput->GetNextFreeFrame();
return nullptr;
}
/** \fn MythPlayer::ReleaseNextVideoFrame(VideoFrame*, int64_t)
* \brief Places frame on the queue of frames ready for display.
*/
void MythPlayer::ReleaseNextVideoFrame(MythVideoFrame *buffer,
std::chrono::milliseconds timecode,
bool wrap)
{
if (wrap)
WrapTimecode(timecode, TC_VIDEO);
buffer->m_timecode = timecode;
m_latestVideoTimecode = timecode;
if (m_decodeOneFrame)
LOG(VB_PLAYBACK, LOG_DEBUG, LOC + "Clearing decode one");
m_decodeOneFrame = false;
if (m_videoOutput)
{
if (abs(m_ffrewSkip) > 1 && m_ffrewUseRenderOne)
{
LOG(VB_PLAYBACK, LOG_DEBUG, LOC + "Setting render one");
m_renderOneFrame = true;
}
m_videoOutput->ReleaseFrame(buffer);
}
// FIXME need to handle this in the correct place in the main thread (DVD stills?)
//if (m_allPaused)
// CheckAspectRatio(buffer);
}
/** \fn MythPlayer::DiscardVideoFrame(VideoFrame*)
* \brief Places frame in the available frames queue.
*/
void MythPlayer::DiscardVideoFrame(MythVideoFrame *buffer)
{
if (m_videoOutput)
m_videoOutput->DiscardFrame(buffer);
}
/** \fn MythPlayer::DiscardVideoFrames(bool)
* \brief Places frames in the available frames queue.
*
* If called with 'Keyframe' set to false then all frames
* not in use by the decoder are made available for decoding. Otherwise,
* all frames are made available for decoding; this is only safe if
* the next frame is a keyframe.
*
* \param Keyframe if this is true all frames are placed
* in the available queue.
* \param Flushed indicates that the decoder has been flushed AND the decoder
* requires ALL frames to be released (used for VAAPI and VDPAU pause frames)
*/
void MythPlayer::DiscardVideoFrames(bool KeyFrame, bool Flushed)
{
if (m_videoOutput)
{
m_videoOutput->DiscardFrames(KeyFrame, Flushed);
if (m_renderOneFrame)
LOG(VB_PLAYBACK, LOG_DEBUG, LOC + "Clearing render one");
m_renderOneFrame = false;
}
}
bool MythPlayer::HasReachedEof(void) const
{
EofState eof = GetEof();
if (eof != kEofStateNone && !m_allPaused)
return true;
if (GetEditMode())
return false;
if (m_liveTV)
return false;
if (!m_deleteMap.IsEmpty() && m_framesPlayed >= m_deleteMap.GetLastFrame())
return true;
return false;
}
void MythPlayer::DeLimboFrame(MythVideoFrame *frame)
{
if (m_videoOutput)
m_videoOutput->DeLimboFrame(frame);
}
void MythPlayer::EnableForcedSubtitles(bool enable)
{
if (enable)
m_enableForcedSubtitles = true;
else
m_disableForcedSubtitles = true;
}
void MythPlayer::SetFrameInterval(FrameScanType scan, double frame_period)
{
if (m_decoder)
m_fpsMultiplier = m_decoder->GetfpsMultiplier();
m_frameInterval = microsecondsFromFloat(1000000.0 * frame_period / m_fpsMultiplier);
LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("SetFrameInterval Interval:%1 Speed:%2 Scan:%3 (Multiplier: %4)")
.arg(m_frameInterval.count()).arg(static_cast<double>(m_playSpeed)).arg(ScanTypeToString(scan)).arg(m_fpsMultiplier));
}
void MythPlayer::InitFrameInterval()
{
// try to get preferential scheduling, but ignore if we fail to.
myth_nice(-19);
}
void MythPlayer::SetBuffering(bool new_buffering)
{
if (!m_buffering && new_buffering)
{
LOG(VB_PLAYBACK, LOG_INFO, LOC + "Waiting for video buffers...");
m_buffering = true;
m_bufferingStart = QTime::currentTime();
m_bufferingLastMsg = QTime::currentTime();
}
else if (m_buffering && !new_buffering)
{
m_buffering = false;
}
}
// For debugging playback set this to increase the timeout so that
// playback does not fail if stepping through code.
// Set PREBUFFERDEBUG to any value and you will get 30 minutes.
static bool preBufferDebug = qEnvironmentVariableIsSet("PREBUFFERDEBUG");
bool MythPlayer::PrebufferEnoughFrames(int min_buffers)
{
if (!m_videoOutput)
return false;
auto wait = false;
if (min_buffers)
wait = m_videoOutput->ValidVideoFrames() < min_buffers;
else if (GetEof() != kEofStateNone)
wait = false;
else if (abs(m_ffrewSkip) > 1)
wait = !m_videoOutput->ValidVideoFrames();
else
wait = !m_videoOutput->EnoughDecodedFrames();
if (wait)
{
SetBuffering(true);
// This piece of code is to address the problem, when starting
// Live TV, of jerking and stuttering. Without this code
// that could go on forever, but is cured by a pause and play.
// This code inserts a brief pause and play when the potential
// for the jerking is detected.
if ((m_liveTV || IsWatchingInprogress())
&& !FlagIsSet(kMusicChoice)
&& m_ffrewSkip == 1)
{
uint64_t frameCount = GetCurrentFrameCount();
uint64_t framesLeft = frameCount - m_framesPlayed;
auto margin = static_cast<uint64_t>(m_videoFrameRate * 3.0);
if (framesLeft < margin)
{
if (m_avSync.ResetAVSyncForLiveTV(&m_audio))
{
LOG(VB_PLAYBACK, LOG_NOTICE, LOC + "Pause to allow live tv catch up");
LOG(VB_PLAYBACK, LOG_NOTICE, LOC + QString("Played: %1 Avail: %2 Buffered: %3 Margin: %4")
.arg(m_framesPlayed).arg(frameCount)
.arg(m_videoOutput->ValidVideoFrames()).arg(margin));
}
}
}
std::this_thread::sleep_for(m_frameInterval / 8);
auto waited_for = std::chrono::milliseconds(m_bufferingStart.msecsTo(QTime::currentTime()));
auto last_msg = std::chrono::milliseconds(m_bufferingLastMsg.msecsTo(QTime::currentTime()));
if (last_msg > 100ms && !FlagIsSet(kMusicChoice))
{
if (++m_bufferingCounter == 10)
LOG(VB_GENERAL, LOG_NOTICE, LOC +
"To see more buffering messages use -v playback");
if (m_bufferingCounter >= 10)
{
LOG(VB_PLAYBACK, LOG_NOTICE, LOC +
QString("Waited %1ms for video buffers %2")
.arg(waited_for.count()).arg(m_videoOutput->GetFrameStatus()));
}
else
{
LOG(VB_GENERAL, LOG_NOTICE, LOC +
QString("Waited %1ms for video buffers %2")
.arg(waited_for.count()).arg(m_videoOutput->GetFrameStatus()));
}
m_bufferingLastMsg = QTime::currentTime();
if (m_audio.IsBufferAlmostFull() && m_framesPlayed < 5
&& gCoreContext->GetBoolSetting("MusicChoiceEnabled", false))
{
m_playerFlags = static_cast<PlayerFlags>(m_playerFlags | kMusicChoice);
LOG(VB_GENERAL, LOG_NOTICE, LOC + "Music Choice program detected - disabling AV Sync.");
m_avSync.SetAVSyncMusicChoice(&m_audio);
}
if (waited_for > 7s && m_audio.IsBufferAlmostFull()
&& !FlagIsSet(kMusicChoice))
{
// We are likely to enter this condition
// if the audio buffer was too full during GetFrame in AVFD
LOG(VB_GENERAL, LOG_NOTICE, LOC + "Resetting audio buffer");
m_audio.Reset();
}
// Finish audio pause for sync after 1 second
// in case of infrequent video frames (e.g. music choice)
if (m_avSync.GetAVSyncAudioPause() && waited_for > 1s)
m_avSync.SetAVSyncMusicChoice(&m_audio);
}
std::chrono::milliseconds msecs { 500ms };
if (preBufferDebug)
msecs = 30min;
if ((waited_for > msecs) && !m_videoOutput->EnoughFreeFrames())
{
LOG(VB_GENERAL, LOG_NOTICE, LOC +
"Timed out waiting for frames, and"
"\n\t\t\tthere are not enough free frames. "
"Discarding buffered frames.");
// This call will result in some ugly frames, but allows us
// to recover from serious problems if frames get leaked.
DiscardVideoFrames(true, true);
}
msecs = 30s;
if (preBufferDebug)
msecs = 30min;
if (waited_for > msecs) // 30 seconds for internet streamed media
{
LOG(VB_GENERAL, LOG_ERR, LOC +
"Waited too long for decoder to fill video buffers. Exiting..");
SetErrored(tr("Video frame buffering failed too many times."));
}
return false;
}
if (!m_avSync.GetAVSyncAudioPause())
m_audio.Pause(false);
SetBuffering(false);
return m_videoOutput->ValidVideoFrames();
}
void MythPlayer::VideoEnd(void)
{
m_vidExitLock.lock();
delete m_videoOutput;
m_videoOutput = nullptr;
m_vidExitLock.unlock();
}
bool MythPlayer::FastForward(float seconds)
{
if (!m_videoOutput)
return false;
// Update m_totalFrames so we know how far we can skip
if (m_decoder)
m_decoder->SyncPositionMap();
if (m_ffTime <= 0)
{
float current = ComputeSecs(m_framesPlayed, true);
float dest = current + seconds;
float length = ComputeSecs(m_totalFrames, true);
if (dest > length)
{
auto msec = millisecondsFromFloat(seconds * 1000);
int64_t pos = TranslatePositionMsToFrame(msec, false);
if (CalcMaxFFTime(pos) < 0)
return true;
// Reach end of recording, go to 1 or 3s before the end
dest = (m_liveTV || IsWatchingInprogress()) ? -3.0 : -1.0;
}
uint64_t target = FindFrame(dest, true);
m_ffTime = target - m_framesPlayed;
}
return m_ffTime > CalcMaxFFTime(m_ffTime, false);
}
bool MythPlayer::Rewind(float seconds)
{
if (!m_videoOutput)
return false;
if (m_rewindTime <= 0)
{
float current = ComputeSecs(m_framesPlayed, true);
float dest = current - seconds;
if (dest < 0)
{
auto msec = millisecondsFromFloat(seconds * 1000);
int64_t pos = TranslatePositionMsToFrame(msec, false);
if (CalcRWTime(pos) < 0)
return true;
dest = 0;
}
uint64_t target = FindFrame(dest, true);
m_rewindTime = m_framesPlayed - target;
}
return (uint64_t)m_rewindTime >= m_framesPlayed;
}
bool MythPlayer::JumpToFrame(uint64_t frame)
{
if (!m_videoOutput)
return false;
bool ret = false;
m_ffTime = m_rewindTime = 0;
if (frame > m_framesPlayed)
{
m_ffTime = frame - m_framesPlayed;
ret = m_ffTime > CalcMaxFFTime(m_ffTime, false);
}
else if (frame < m_framesPlayed)
{
m_rewindTime = m_framesPlayed - frame;
ret = m_ffTime > CalcMaxFFTime(m_ffTime, false);
}
return ret;
}
void MythPlayer::JumpChapter(int chapter)
{
if (m_jumpChapter == 0)
m_jumpChapter = chapter;
}
void MythPlayer::ResetPlaying(bool resetframes)
{
ClearAfterSeek();
m_ffrewSkip = 1;
if (resetframes)
m_framesPlayed = 0;
if (m_decoder)
{
m_decoder->Reset(true, true, true);
if (m_decoder->IsErrored())
SetErrored("Unable to reset video decoder");
}
}
void MythPlayer::CheckTVChain(void)
{
bool last = !(m_playerCtx->m_tvchain->HasNext());
SetWatchingRecording(last);
}
// This is called from decoder thread. Set an indicator that will
// be checked and actioned in the player thread.
void MythPlayer::FileChangedCallback(void)
{
LOG(VB_PLAYBACK, LOG_INFO, LOC + "FileChangedCallback");
m_fileChanged = true;
}
void MythPlayer::StopPlaying()
{
LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("StopPlaying - begin"));
m_playerThread->setPriority(QThread::NormalPriority);
#ifdef Q_OS_ANDROID
setpriority(PRIO_PROCESS, m_playerThreadId, 0);
#endif
emit CheckCallbacks();
DecoderEnd();
VideoEnd();
AudioEnd();
LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("StopPlaying - end"));
}
void MythPlayer::AudioEnd(void)
{
m_audio.DeleteOutput();
}
bool MythPlayer::PauseDecoder(void)
{
m_decoderPauseLock.lock();
if (is_current_thread(m_decoderThread))
{
m_decoderPaused = true;
m_decoderThreadPause.wakeAll();
m_decoderPauseLock.unlock();
return m_decoderPaused;
}
int tries = 0;
m_pauseDecoder = true;
while (m_decoderThread && !m_killDecoder && (tries++ < 100) &&
!m_decoderThreadPause.wait(&m_decoderPauseLock, 100))
{
emit CheckCallbacks();
LOG(VB_GENERAL, LOG_WARNING, LOC + "Waited 100ms for decoder to pause");
}
m_pauseDecoder = false;
m_decoderPauseLock.unlock();
return m_decoderPaused;