-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathInterfacePlayerRDK.cpp
More file actions
5450 lines (5066 loc) · 202 KB
/
InterfacePlayerRDK.cpp
File metadata and controls
5450 lines (5066 loc) · 202 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
/*
* If not stated otherwise in this file or this component's license file the
* following copyright and licenses apply:
*
* Copyright 2024 RDK Management
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include "InterfacePlayerRDK.h"
#include "InterfacePlayerPriv.h"
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include "PlayerLogManager.h"
#include "GstUtils.h"
#include <sys/time.h>
#include "PlayerExternalsInterface.h" //ToDo: Replace once outputprotection moved to middleware
#include <inttypes.h>
#include "TextStyleAttributes.h"
#include <memory>
#include <gst/gst.h>
#ifdef USE_EXTERNAL_STATS
#include "player-xternal-stats.h"
#endif
#include "PlayerUtils.h"
#define DEFAULT_BUFFERING_TO_MS 10 /**< TimeOut interval to check buffer fullness */
#define DEFAULT_BUFFERING_MAX_MS (1000) /**< max buffering time */
#define DEFAULT_BUFFERING_MAX_CNT (DEFAULT_BUFFERING_MAX_MS/DEFAULT_BUFFERING_TO_MS) /**< max buffering timeout count */
#define NORMAL_PLAY_RATE 1
#define DEFAULT_TIMEOUT_FOR_SOURCE_SETUP (1000) /**< Default timeout value in milliseconds */
#define DEFAULT_AVSYNC_FREERUN_THRESHOLD_SECS 12 /**< Currently MAX FRAG DURATION + 2*/
#define INVALID_RATE -9999
#if GLIB_CHECK_VERSION(2, 68, 0)
// avoid deprecated g_memdup when g_memdup2 available
#define PLAYER_G_MEMDUP(src, size) g_memdup2((src), (gsize)(size))
#else
#define PLAYER_G_MEMDUP(src, size) g_memdup((src), (guint)(size))
#endif
#define GST_DELAY_BETWEEN_PTS_CHECK_FOR_EOS_ON_UNDERFLOW 500 /**< A timeout interval in milliseconds to check pts in case of underflow */
#define GST_MIN_DECODE_ERROR_INTERVAL 10000 /**< Minimum time interval in milliseconds between two decoder error CB to send anomaly error */
#define BUFFERING_TIMEOUT_PRIORITY -70 /**< 0 is DEFAULT priority whereas -100 is the HIGH_PRIORITY */
// for now name is being kept as aamp should be changed when gst-plugins are migrated
static const char* GstPluginNamePR = "playreadydecryptor";
static const char* GstPluginNameWV = "widevinedecryptor";
static const char* GstPluginNameCK = "clearkeydecryptor";
static const char* GstPluginNameVMX = "verimatrixdecryptor";
#define GST_MIN_PTS_UPDATE_INTERVAL 4000 /**< Time duration in milliseconds if exceeded and pts has not changed; it is concluded pts is not changing */
#include <assert.h>
#define GST_NORMAL_PLAY_RATE 1
std::pair <CipherType, const char *> CipherToStringMap[] = {
{CIPHER_TYPE_CENC, "cenc"},
{CIPHER_TYPE_CBC1, "cbc1"},
{CIPHER_TYPE_CENS, "cens"},
{CIPHER_TYPE_CBCS, "cbcs"},
{CIPHER_TYPE_NONE, "none"}
};
const char * CipherTypeToString(CipherType type)
{
for (const auto& pair : CipherToStringMap)
{
if (pair.first == type)
{
return pair.second;
}
}
return "unknown";
}
/*InterfacePlayerRDK constructor*/
InterfacePlayerRDK::InterfacePlayerRDK() :
mProtectionLock(), mPauseInjector(false), mSourceSetupMutex(), stopCallback(NULL), tearDownCb(NULL), notifyFirstFrameCallback(NULL),
mSourceSetupCV(), mScheduler(), callbackMap(), setupStreamCallbackMap(), mDrmSystem(NULL), mEncrypt(NULL), mDRMSessionManager(NULL)
{
interfacePlayerPriv = new InterfacePlayerPriv();
m_gstConfigParam = new Configs();
m_gstConfigParam->framesToQueue = SocUtils::RequiredQueuedFrames();
pthread_mutex_init(&mProtectionLock, NULL);
for (int i = 0; i < GST_TRACK_COUNT; i++)
pthread_mutex_init(&interfacePlayerPriv->gstPrivateContext->stream[i].sourceLock, NULL);
// start Scheduler Worker for task handling
mScheduler.StartScheduler();
}
/* InterfacePlayerRDK destructor*/
InterfacePlayerRDK::~InterfacePlayerRDK()
{
DestroyPipeline();
if (mDrmSystem)
{
delete[] mDrmSystem;
}
/* safe delete configuration parameter */
MW_SAFE_DELETE(m_gstConfigParam);
mScheduler.StopScheduler();
for (int i = 0; i < GST_TRACK_COUNT; i++)
{
pthread_mutex_destroy(&interfacePlayerPriv->gstPrivateContext->stream[i].sourceLock);
}
pthread_mutex_destroy(&mProtectionLock);
delete interfacePlayerPriv;
}
InterfacePlayerPriv::InterfacePlayerPriv():mPlayerName()
{
gstPrivateContext = new GstPlayerPriv();
socInterface = SocInterface::CreateSocInterface();
}
InterfacePlayerPriv::~InterfacePlayerPriv()
{
delete gstPrivateContext;
gstPrivateContext = nullptr;
}
/*GstPlayerPriv constructor*/
GstPlayerPriv::GstPlayerPriv() : monitorAVstate(), pipeline(NULL), bus(NULL),
total_bytes(0), n_audio(0), current_audio(0),
periodicProgressCallbackIdleTaskId(GST_TASK_ID_INVALID),
bufferingTimeoutTimerId(GST_TASK_ID_INVALID), video_dec(NULL), audio_dec(NULL), TaskControlMutex(), firstProgressCallbackIdleTask("FirstProgressCallback"),
video_sink(NULL), audio_sink(NULL), subtitle_sink(NULL), task_pool(NULL),
rate(GST_NORMAL_PLAY_RATE), zoom(GST_VIDEO_ZOOM_NONE), videoMuted(false), audioMuted(false), volumeMuteMutex(), subtitleMuted(true),
audioVolume(1.0), eosCallbackIdleTaskId(GST_TASK_ID_INVALID), eosCallbackIdleTaskPending(false),
firstFrameReceived(false), pendingPlayState(false), decoderHandleNotified(false),
firstFrameCallbackIdleTaskId(GST_TASK_ID_INVALID), firstFrameCallbackIdleTaskPending(false),
using_westerossink(false), usingRialtoSink(false), usingClosedCaptionsControl(false), pauseOnStartPlayback(false), eosSignalled(false),
buffering_enabled(FALSE), buffering_in_progress(FALSE), buffering_timeout_cnt(0),
buffering_target_state(GST_STATE_NULL),
lastKnownPTS(0), ptsUpdatedTimeMS(0), ptsCheckForEosOnUnderflowIdleTaskId(GST_TASK_ID_INVALID),
numberOfVideoBuffersSent(0), segmentStart(0), positionQuery(NULL), durationQuery(NULL),
paused(false), pipelineState(GST_STATE_NULL),
firstVideoFrameDisplayedCallbackTask("FirstVideoFrameDisplayedCallback"),
firstTuneWithWesterosSinkOff(false),
decodeErrorMsgTimeMS(0), decodeErrorCBCount(0),
progressiveBufferingEnabled(false), progressiveBufferingStatus(false),
enableSEITimeCode(true), firstVideoFrameReceived(false), firstAudioFrameReceived(false), NumberOfTracks(0), playbackQuality{},
filterAudioDemuxBuffers(false), isMp4DemuxPlayback(false),
aSyncControl(), syncControl(), callbackControl(), seekPosition(0)
{
memset(videoRectangle, '\0', VIDEO_COORDINATES_SIZE);
/* default video scaling should take into account actual graphics
* resolution instead of assuming 1280x720.
* By default we where setting the resolution has 0,0,1280,720.
* For Full HD this default resolution will not scale to full size.
* So, we no need to set any default rectangle size here,
* since the video will display full screen, if a gstreamer pipeline is started
* using the westerossink connected using westeros compositor.
*/
strcpy(videoRectangle, "");
for (int i = 0; i < GST_TRACK_COUNT; i++)
{
protectionEvent[i] = NULL;
}
}
/*GstPlayerPriv destructor*/
GstPlayerPriv::~GstPlayerPriv()
{
g_clear_object(&pipeline);
g_clear_object(&bus);
g_clear_object(&video_dec);
g_clear_object(&audio_dec);
g_clear_object(&video_sink);
g_clear_object(&audio_sink);
g_clear_object(&subtitle_sink);
g_clear_object(&task_pool);
for (int i = 0; i < GST_TRACK_COUNT; i++)
{
g_clear_object(&protectionEvent[i]);
}
g_clear_object(&positionQuery);
g_clear_object(&durationQuery);
}
/**
* @brief Callback for handling video samples in Player's GStreamer player.
* @param[in] object The GStreamer element.
* @param[in] _this The instance of the player.
* @return The flow return status.
*/
static GstFlowReturn InterfacePlayerRDK_OnVideoSample(GstElement *object, void *_this);
InterfacePlayerPriv* InterfacePlayerRDK::GetPrivatePlayer()
{
return interfacePlayerPriv;
}
/**
* @brief Callback for handling video samples in Player's GStreamer player.
* @param[in] object The GStreamer element.
* @param[in] _this The instance of the player.
* @return The flow return status.
*/
bool InterfacePlayerRDK::IsPipelinePaused()
{
return interfacePlayerPriv->gstPrivateContext->paused;
}
/**
* @brief Sets a flag indicating that pipeline transition to PLAYING state is pending
*/
void InterfacePlayerRDK::EnablePendingPlayState()
{
interfacePlayerPriv->gstPrivateContext->pendingPlayState = true;
}
/**
* @brief Sets a flag indicating that pipeline transition to PLAYING state is pending
*/
const char *gstGetMediaTypeName(GstMediaType mediaType)
{
static const char *name[] =
{
"video",//eMEDIATYPE_VIDEO
"audio",//eMEDIATYPE_AUDIO
"text",//eMEDIATYPE_SUBTITLE
"reserved",//eMEDIATYPE_RESERVED
"manifest",//eMEDIATYPE_MANIFEST
"licence",//eMEDIATYPE_LICENCE
"iframe",//eMEDIATYPE_IFRAME
"init_video",//eMEDIATYPE_INIT_VIDEO
"init_audio",//eMEDIATYPE_INIT_AUDIO
"init_text",//eMEDIATYPE_INIT_SUBTITLE
"init_reserved",//eMEDIATYPE_INIT_RESERVED
"playlist_video",//eMEDIATYPE_PLAYLIST_VIDEO
"playlist_audio",//eMEDIATYPE_PLAYLIST_AUDIO
"playlist_text",//eMEDIATYPE_PLAYLIST_SUBTITLE
"playlist_reserved",//eMEDIATYPE_PLAYLIST_RESERVED
"playlist_iframe",//eMEDIATYPE_PLAYLIST_IFRAME
"init_iframe",//eMEDIATYPE_INIT_IFRAME
"dsm_cc",//eMEDIATYPE_DSM_CC
"image",//eMEDIATYPE_IMAGE
};
if( mediaType < eGST_MEDIATYPE_DEFAULT )
{
return name[mediaType];
}
else
{
return "UNKNOWN";
}
}
static GstStateChangeReturn SetStateWithWarnings(GstElement *element, GstState targetState);
/**
* @brief Decorate a GstBuffer with DRM metadata
* @param[in] buffer The GstBuffer to decorate
* @param[in] drmMetadata The DRM metadata
*/
static void DecorateGstBufferWithDrmMetadata(GstBuffer *buffer, const MediaDrmMetadata &drmMetadata);
/**
* @brief Configures the GStreamer pipeline.
* @param format Video format.
* @param audioFormat Audio format.
* @param subFormat Whether subtitle format is enabled.
* @param bESChangeStatus Whether ES change status is enabled.
* @param setReadyAfterPipelineCreation Whether to set the player as ready after pipeline creation.
* @param isSubEnable Whether subtitles are enabled.
* @param trackId Track ID.
* @param rate Bitrate.
* @param pipelineName Pipeline name.
* @param PipelinePriority Pipeline priority.
*/
void InterfacePlayerRDK::ConfigurePipeline(int format, int audioFormat, int subFormat,
bool bESChangeStatus, bool setReadyAfterPipelineCreation,
bool isSubEnable, int32_t trackId, gint rate, const char *pipelineName, int PipelinePriority, bool FirstFrameFlag, std::string manifestUrl)
{
mFirstFrameRequired = FirstFrameFlag;
GstStreamOutputFormat gstFormat = static_cast<GstStreamOutputFormat>(format);
GstStreamOutputFormat gstAudioFormat = static_cast<GstStreamOutputFormat>(audioFormat);
GstStreamOutputFormat gstSubFormat = static_cast<GstStreamOutputFormat>(subFormat);
GstStreamOutputFormat newFormat[GST_TRACK_COUNT];
newFormat[eGST_MEDIATYPE_VIDEO] = gstFormat;
newFormat[eGST_MEDIATYPE_AUDIO] = gstAudioFormat;
bool newClosedCaptionsControl = false;
if(isSubEnable)
{
MW_LOG_MIL("Gstreamer subs enabled");
newFormat[eGST_MEDIATYPE_SUBTITLE] = gstSubFormat;
}
else
{
MW_LOG_MIL("Gstreamer subs disabled");
newFormat[eGST_MEDIATYPE_SUBTITLE]=GST_FORMAT_INVALID;
}
if(!(m_gstConfigParam->useWesterosSink))
{
interfacePlayerPriv->gstPrivateContext->using_westerossink = false;
interfacePlayerPriv->gstPrivateContext->firstTuneWithWesterosSinkOff = interfacePlayerPriv->socInterface->IsFirstTuneWithWesteros();
}
else
{
interfacePlayerPriv->gstPrivateContext->using_westerossink = true;
interfacePlayerPriv->socInterface->SetWesterosSinkState(true);
}
if(!(m_gstConfigParam->useRialtoSink))
{
interfacePlayerPriv->gstPrivateContext->usingRialtoSink = false;
MW_LOG_MIL("Rialto disabled");
}
else
{
interfacePlayerPriv->gstPrivateContext->usingRialtoSink = true;
// If no subtitles defined, then create a closed caption control stream
newClosedCaptionsControl = (gstSubFormat == GST_FORMAT_INVALID);
// To avoid out of band subtitles being removed during trickplay,
// check if they were previously configured, and don't enable Closed Caption Control.
newClosedCaptionsControl &= (interfacePlayerPriv->gstPrivateContext->stream[eGST_MEDIATYPE_SUBTITLE].format == GST_FORMAT_INVALID);
if (interfacePlayerPriv->gstPrivateContext->using_westerossink)
{
MW_LOG_WARN("Rialto and Westeros Sink enabled");
}
else
{
MW_LOG_MIL("Rialto enabled");
}
if (newClosedCaptionsControl)
{
MW_LOG_MIL("Using CC Control Stream");
}
}
if(rate != INVALID_RATE)
{
interfacePlayerPriv->gstPrivateContext->rate = rate;
}
if (interfacePlayerPriv->gstPrivateContext->pipeline == NULL || interfacePlayerPriv->gstPrivateContext->bus == NULL)
{
MW_LOG_MIL("Create pipeline %s (pipeline %p bus %p)", pipelineName, interfacePlayerPriv->gstPrivateContext->pipeline, interfacePlayerPriv->gstPrivateContext->bus);
CreatePipeline(pipelineName, PipelinePriority); /*Create a new pipeline if pipeline or the message bus does not exist*/
}
if(setReadyAfterPipelineCreation)
{
if(SetStateWithWarnings(interfacePlayerPriv->gstPrivateContext->pipeline, GST_STATE_READY) == GST_STATE_CHANGE_FAILURE)
{
MW_LOG_ERR("InterfacePlayerRDK_Configure GST_STATE_READY failed on forceful set");
}
else
{
MW_LOG_INFO("Forcefully set pipeline to ready state due to track_id change");
PipelineSetToReady = true;
}
}
bool configureStream[GST_TRACK_COUNT] = {};
for (int i = 0; i < GST_TRACK_COUNT; i++)
{
gst_media_stream *stream = &interfacePlayerPriv->gstPrivateContext->stream[i];
if(stream->format != newFormat[i])
{
bool isInitialSetup = (stream->format == GST_FORMAT_INVALID || stream->format == GST_FORMAT_UNKNOWN);
bool isValidNewFormat = (newFormat[i] != GST_FORMAT_INVALID && newFormat[i] != GST_FORMAT_UNKNOWN);
if (isValidNewFormat || isInitialSetup)
{
MW_LOG_MIL("Closing stream %d old format = %d, new format = %d",i, stream->format, newFormat[i]);
configureStream[i] = true;
interfacePlayerPriv->gstPrivateContext->NumberOfTracks++;
}
else
{
MW_LOG_MIL("Skipping reconfiguration for stream %d - both format invalid/unknown",i);
}
}
if(interfacePlayerPriv->socInterface->ShouldTearDownForTrickplay())
{
if(interfacePlayerPriv->gstPrivateContext->rate > 1 || interfacePlayerPriv->gstPrivateContext->rate < 0)
{
if (eGST_MEDIATYPE_VIDEO == i)
configureStream[i] = true;
else
{
TearDownStream((int)i);
configureStream[i] = false;
}
}
}
/* Force configure the bin for mid stream audio type change */
if (!configureStream[i] && bESChangeStatus && (eGST_MEDIATYPE_AUDIO == i))
{
MW_LOG_MIL("AudioType Changed. Force configure pipeline");
configureStream[i] = true;
}
stream->resetPosition = true;
stream->eosReached = false;
stream->firstBufferProcessed = false;
}
for (int i = 0; i < GST_TRACK_COUNT; i++)
{
gst_media_stream *stream = &interfacePlayerPriv->gstPrivateContext->stream[i];
if ((configureStream[i] && (newFormat[i] != GST_FORMAT_INVALID)) ||
/* Allow to create audio pipeline along with video pipeline if trickplay initiated before the pipeline going to play/paused state to fix unthrottled trickplay */
(trickTeardown && (eGST_MEDIATYPE_AUDIO == i))) // remove the trickTeardown api not required
{
trickTeardown = false;
TearDownStream((int)i);
stream->format = newFormat[i];
stream->trackId = trackId;
/* Sets up the stream for the given MediaType */
if(0 != InterfacePlayer_SetupStream((GstMediaType)i, manifestUrl))
{
MW_LOG_ERR("InterfacePlayerRDK: track %d failed", i);
//Don't kill the tune for subtitles
if (eGST_MEDIATYPE_SUBTITLE != (GstMediaType)i)
{
return;
}
}
}
else if ((eGST_MEDIATYPE_SUBTITLE == i) &&
newClosedCaptionsControl &&
!interfacePlayerPriv->gstPrivateContext->usingClosedCaptionsControl)
{
TearDownStream(eGST_MEDIATYPE_SUBTITLE);
interfacePlayerPriv->gstPrivateContext->usingClosedCaptionsControl = true;
SetupClosedCaptionControlStream();
}
}
if ((interfacePlayerPriv->gstPrivateContext->usingRialtoSink) && (m_gstConfigParam->media != eGST_MEDIAFORMAT_PROGRESSIVE))
{
/* Reconfigure the Rialto video sink to update the single path stream
* property. This enables rialtomsevideosink to call
* allSourcesAttached() at the right time to enable streaming on the
* server side.
* For progressive media, we don't know what tracks are used.
*/
GstElement* vidsink = NULL;
g_object_get(interfacePlayerPriv->gstPrivateContext->stream[eGST_MEDIATYPE_VIDEO].sinkbin, "video-sink", &vidsink, NULL);
if(vidsink)
{
gboolean videoOnly = (audioFormat == GST_FORMAT_INVALID);
MW_LOG_INFO("Setting single-path-stream to %d", videoOnly);
g_object_set(vidsink, "single-path-stream", videoOnly, NULL);
}
else
{
MW_LOG_WARN("Couldn't get video-sink");
}
}
if (interfacePlayerPriv->gstPrivateContext->pauseOnStartPlayback && GST_NORMAL_PLAY_RATE == interfacePlayerPriv->gstPrivateContext->rate)
{
MW_LOG_INFO("Setting state to GST_STATE_PAUSED - pause on playback enabled");
interfacePlayerPriv->gstPrivateContext->paused = true;
interfacePlayerPriv->gstPrivateContext->pendingPlayState = false;
if (SetStateWithWarnings(interfacePlayerPriv->gstPrivateContext->pipeline, GST_STATE_PAUSED) == GST_STATE_CHANGE_FAILURE)
{
MW_LOG_ERR("InterfacePlayerRDK: GST_STATE_PAUSED failed");
}
}
/* If buffering is enabled, set the pipeline in Paused state, once sufficient content has been buffered the pipeline will be set to GST_STATE_PLAYING */
else if (interfacePlayerPriv->gstPrivateContext->buffering_enabled && format != GST_FORMAT_INVALID && GST_NORMAL_PLAY_RATE == interfacePlayerPriv->gstPrivateContext->rate)
{
MW_LOG_INFO("Setting state to GST_STATE_PAUSED, target state to GST_STATE_PLAYING");
interfacePlayerPriv->gstPrivateContext->buffering_target_state = GST_STATE_PLAYING;
interfacePlayerPriv->gstPrivateContext->buffering_in_progress = true;
interfacePlayerPriv->gstPrivateContext->buffering_timeout_cnt = DEFAULT_BUFFERING_MAX_CNT;
if (SetStateWithWarnings(interfacePlayerPriv->gstPrivateContext->pipeline, GST_STATE_PAUSED) == GST_STATE_CHANGE_FAILURE)
{
MW_LOG_ERR("InterfacePlayerRDK_Configure GST_STATE_PAUSED failed");
}
interfacePlayerPriv->gstPrivateContext->pendingPlayState = false;
interfacePlayerPriv->gstPrivateContext->paused = false;
}
else
{
MW_LOG_INFO("Setting state to GST_STATE_PLAYING");
if (SetStateWithWarnings(interfacePlayerPriv->gstPrivateContext->pipeline, GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE)
{
MW_LOG_ERR("InterfacePlayerRDK: GST_STATE_PLAYING failed");
}
interfacePlayerPriv->gstPrivateContext->pendingPlayState = false;
interfacePlayerPriv->gstPrivateContext->paused = false;
}
interfacePlayerPriv->gstPrivateContext->eosSignalled = false;
interfacePlayerPriv->gstPrivateContext->numberOfVideoBuffersSent = 0;
interfacePlayerPriv->gstPrivateContext->decodeErrorMsgTimeMS = 0;
interfacePlayerPriv->gstPrivateContext->decodeErrorCBCount = 0;
if (interfacePlayerPriv->gstPrivateContext->usingRialtoSink)
{
MW_LOG_INFO("RialtoSink subtitle_sink = %p ",interfacePlayerPriv->gstPrivateContext->subtitle_sink);
GstContext *context = gst_context_new("streams-info", false);
GstStructure *contextStructure = gst_context_writable_structure(context);
if( !interfacePlayerPriv->gstPrivateContext->subtitle_sink ) MW_LOG_WARN( "subtitle_sink==NULL" );
gst_structure_set(
contextStructure,
"video-streams", G_TYPE_UINT, (interfacePlayerPriv->gstPrivateContext->video_sink)?0x1u:0x0u,
"audio-streams", G_TYPE_UINT, (interfacePlayerPriv->gstPrivateContext->audio_sink)?0x1u:0x0u,
"text-streams", G_TYPE_UINT, (interfacePlayerPriv->gstPrivateContext->subtitle_sink)?0x1u:0x0u,
nullptr );
gst_element_set_context(GST_ELEMENT(interfacePlayerPriv->gstPrivateContext->pipeline), context);
gst_context_unref(context);
}
}
/**
* @brief Invoked synchronously when a message is available on the bus
* @param[in] bus the GstBus that sent the message
* @param[in] msg the GstMessage
* @param[in] pInterfacePlayerRDK pointer to InterfacePlayerRDK instance
* @retval GST_BUS_PASS to pass the message to the async queue
*/
static GstBusSyncReply bus_sync_handler(GstBus * bus, GstMessage * msg, InterfacePlayerRDK * pInterfacePlayerRDK);
void InterfacePlayerRDK::SetPauseOnStartPlayback(bool enable)
{
interfacePlayerPriv->gstPrivateContext->pauseOnStartPlayback = enable;
}
/**
* @brief Idle callback to notify first frame rendered event
* @param[in] user_data pointer to InterfacePlayerRDK instance
* @retval G_SOURCE_REMOVE, if the source should be removed
*/
gboolean InterfacePlayerRDK::IdleCallbackOnFirstFrame(gpointer user_data)
{
InterfacePlayerRDK *pInterfacePlayerRDK = (InterfacePlayerRDK *)user_data;
InterfacePlayerPriv* privatePlayer = nullptr;
if (pInterfacePlayerRDK)
{
privatePlayer = pInterfacePlayerRDK->GetPrivatePlayer();
pInterfacePlayerRDK->TriggerEvent(InterfaceCB::firstVideoFrameReceived);
privatePlayer->gstPrivateContext->firstFrameCallbackIdleTaskId = PLAYER_TASK_ID_INVALID;
privatePlayer->gstPrivateContext->firstFrameCallbackIdleTaskPending = false;
}
return G_SOURCE_REMOVE;
}
/**
* @brief Callback invoked after first video frame decoded
* @param[in] object pointer to element raising the callback
* @param[in] arg0 number of arguments
* @param[in] arg1 array of arguments
* @param[in] pInterfacePlayerRDK pointer to InterfacePlayerRDK instance
*/
static void GstPlayer_OnFirstVideoFrameCallback(GstElement* object, guint arg0, gpointer arg1,
InterfacePlayerRDK * pInterfacePlayerRDK)
{
InterfacePlayerPriv* privatePlayer = pInterfacePlayerRDK->GetPrivatePlayer();
HANDLER_CONTROL_HELPER_CALLBACK_VOID();
privatePlayer->gstPrivateContext->firstVideoFrameReceived = true;
pInterfacePlayerRDK->NotifyFirstFrame(eGST_MEDIATYPE_VIDEO);
}
/**Add commentMore actions
* @brief Gets the monitor AV state.
* @return A pointer to the MonitorAVState structure containing the AV status or nullptr.
*/
const MonitorAVState& InterfacePlayerRDK::GetMonitorAVState()
{
return interfacePlayerPriv->gstPrivateContext->monitorAVstate;
}
/**
* @brief Callback invoked after first audio buffer decoded
* @param[in] object pointer to element raising the callback
* @param[in] arg0 number of arguments
* @param[in] arg1 array of arguments
* @param[in] pInterfacePlayerRDK pointer to InterfacePlayerRDK instance
*/
static void GstPlayer_OnAudioFirstFrameAudDecoder(GstElement* object, guint arg0, gpointer arg1,
InterfacePlayerRDK * pInterfacePlayerRDK)
{
InterfacePlayerPriv* privatePlayer = pInterfacePlayerRDK->GetPrivatePlayer();
HANDLER_CONTROL_HELPER_CALLBACK_VOID();
privatePlayer->gstPrivateContext->firstAudioFrameReceived = true;
pInterfacePlayerRDK->NotifyFirstFrame(eGST_MEDIATYPE_AUDIO);
}
/**
* @brief Idle callback to notify end-of-stream event
* @param[in] user_data pointer to InterfacePlayerRDK instance
* @retval G_SOURCE_REMOVE, if the source should be removed
*/
gboolean InterfacePlayerRDK::IdleCallbackOnEOS(gpointer user_data)
{
InterfacePlayerRDK *pInterfacePlayerRDK = (InterfacePlayerRDK *)user_data;
InterfacePlayerPriv* privatePlayer = nullptr;
if (pInterfacePlayerRDK)
{
privatePlayer = pInterfacePlayerRDK->GetPrivatePlayer();
MW_LOG_MIL("eosCallbackIdleTaskId %d", privatePlayer->gstPrivateContext->eosCallbackIdleTaskId);
pInterfacePlayerRDK->TriggerEvent(InterfaceCB::notifyEOS);
privatePlayer->gstPrivateContext->eosCallbackIdleTaskId = PLAYER_TASK_ID_INVALID;
privatePlayer->gstPrivateContext->eosCallbackIdleTaskPending = false;
}
return G_SOURCE_REMOVE;
}
/**
* @brief Updates the monitor AV status.
*
* @param[in] pInterfacePlayerRDK pointer to InterfacePlayerRDK instance
*/
void MonitorAV( InterfacePlayerRDK *pInterfacePlayerRDK )
{
const int AVSYNC_POSITIVE_THRESHOLD_MS = pInterfacePlayerRDK->m_gstConfigParam->monitorAvsyncThresholdPositiveMs;
const int AVSYNC_NEGATIVE_THRESHOLD_MS = pInterfacePlayerRDK->m_gstConfigParam->monitorAvsyncThresholdNegativeMs;
const int JUMP_THRESHOLD_MS = pInterfacePlayerRDK->m_gstConfigParam->monitorAvJumpThresholdMs;
GstState state = GST_STATE_VOID_PENDING;
GstState pending = GST_STATE_VOID_PENDING;
InterfacePlayerPriv* privatePlayer = pInterfacePlayerRDK->GetPrivatePlayer();
GstClockTime timeout = 0;
gint64 av_position[2] = {0,0};
gint rc = gst_element_get_state(privatePlayer->gstPrivateContext->pipeline, &state, &pending, timeout );
if( rc == GST_STATE_CHANGE_SUCCESS )
{
if( state == GST_STATE_PLAYING )
{
struct MonitorAVState *monitorAVState = &privatePlayer->gstPrivateContext->monitorAVstate;
const char *description = NULL;
int numTracks = 0;
bool bigJump = false;
long long tNow = GetCurrentTimeMS();
if( !monitorAVState->tLastReported )
{
monitorAVState->tLastReported = tNow;
}
// skip reading audio position when trickplay is active
int maxTracks = (privatePlayer->gstPrivateContext->rate == GST_NORMAL_PLAY_RATE) ? 2 : 1;
for( int i=0; i<maxTracks; i++ )
{ // eMEDIATYPE_VIDEO=0, eMEDIATYPE_AUDIO=1
auto sinkbin = privatePlayer->gstPrivateContext->stream[i].sinkbin;
if( sinkbin && (privatePlayer->gstPrivateContext->stream[i].format != GST_FORMAT_INVALID))
{
gint64 position = GST_CLOCK_TIME_NONE;
if( gst_element_query_position(sinkbin, GST_FORMAT_TIME, &position) )
{
long long ms = GST_TIME_AS_MSECONDS(position);
if( ms == monitorAVState->av_position[i] )
{
if( description )
{ // both tracks stalled
description = "stall";
}
else
{
description = (i==eGST_MEDIATYPE_VIDEO)?"video freeze":"audio drop";
}
}
else if( i == eGST_MEDIATYPE_VIDEO && monitorAVState->happy )
{
auto actualDelta = ms - monitorAVState->av_position[i];
auto expectedDelta = tNow - monitorAVState->tLastSampled;
if( actualDelta > expectedDelta+JUMP_THRESHOLD_MS )
{
bigJump = true;
}
}
av_position[i] = ms;
numTracks++;
}
}
}
monitorAVState->tLastSampled = tNow;
switch( numTracks )
{
case 0:
description = "eos";
break;
case 1:
description = "trickplay";
break;
case 2:
{
int delta = (int)(av_position[eGST_MEDIATYPE_VIDEO] - av_position[eGST_MEDIATYPE_AUDIO]);
if( delta > AVSYNC_POSITIVE_THRESHOLD_MS || delta < AVSYNC_NEGATIVE_THRESHOLD_MS )
{
if( !description )
{ // both moving, but diverged
description = "avsync";
}
}
else if( bigJump )
{ // workaround to detect decoders that jump over AV gaps without delay
description = "jump";
}
}
break;
default:
break;
}
if( !description )
{ // fill in OK if nothing flagged
description = "ok";
}
if( monitorAVState->description!=description )
{ // log only when interpretation of AV state has changed
if( monitorAVState->description )
{ // avoid logging for initial NULL description
MW_LOG_MIL( "MonitorAV_%s: %" G_GINT64_FORMAT ",%" G_GINT64_FORMAT ",%d, %" G_GINT64_FORMAT "",
monitorAVState->description,
(gint64)monitorAVState->av_position[eGST_MEDIATYPE_VIDEO],
(gint64)monitorAVState->av_position[eGST_MEDIATYPE_AUDIO],
(int)(monitorAVState->av_position[eGST_MEDIATYPE_VIDEO] - monitorAVState->av_position[eGST_MEDIATYPE_AUDIO]),
(gint64)monitorAVState->tLastSampled - monitorAVState->tLastReported );
}
MW_LOG_MIL( "MonitorAV_%s: %" G_GINT64_FORMAT ",%" G_GINT64_FORMAT ",%d,0",
description,
av_position[eGST_MEDIATYPE_VIDEO],
av_position[eGST_MEDIATYPE_AUDIO],
(int)(av_position[eGST_MEDIATYPE_VIDEO] - av_position[eGST_MEDIATYPE_AUDIO]) );
monitorAVState->tLastReported = monitorAVState->tLastSampled;
monitorAVState->description = description;
}
// remember most recently sniffed pair of video and audio positions
monitorAVState->av_position[eGST_MEDIATYPE_VIDEO] = av_position[eGST_MEDIATYPE_VIDEO];
monitorAVState->av_position[eGST_MEDIATYPE_AUDIO] = av_position[eGST_MEDIATYPE_AUDIO];
}
}
else
{
MW_LOG_WARN( "gst_element_get_state %d, rc=%d", state, rc );
}
}
/**
* @brief Timer's callback to notify playback progress event
* @param[in] user_data pointer to InterfacePlayerRDK instance
* @retval G_SOURCE_CONTINUE, this function to be called periodically
*/
gboolean InterfacePlayerRDK::ProgressCallbackOnTimeout(gpointer user_data)
{
InterfacePlayerRDK *pInterfacePlayerRDK = (InterfacePlayerRDK *)user_data;
InterfacePlayerPriv* privatePlayer = nullptr;
if (pInterfacePlayerRDK)
{
privatePlayer = pInterfacePlayerRDK->GetPrivatePlayer();
if (pInterfacePlayerRDK->m_gstConfigParam->monitorAV)
{
MonitorAV(pInterfacePlayerRDK);
}
pInterfacePlayerRDK->TriggerEvent(InterfaceCB::progressCb);
MW_LOG_TRACE("current %d, stored %d ", g_source_get_id(g_main_current_source()), privatePlayer->gstPrivateContext->periodicProgressCallbackIdleTaskId);
}
return G_SOURCE_CONTINUE;
}
/**
* @brief Idle callback to start progress notifier timer
* @param[in] user_data pointer to InterfacePlayerRDK instance
* @retval G_SOURCE_REMOVE, if the source should be removed
*/
gboolean InterfacePlayerRDK::IdleCallback(gpointer user_data)
{
InterfacePlayerRDK *pInterfacePlayerRDK = (InterfacePlayerRDK *)user_data;
InterfacePlayerPriv* privatePlayer = nullptr;
if (pInterfacePlayerRDK)
{
privatePlayer = pInterfacePlayerRDK->GetPrivatePlayer();
pInterfacePlayerRDK->TriggerEvent(InterfaceCB::idleCb);
pInterfacePlayerRDK->IdleTaskClearFlags(privatePlayer->gstPrivateContext->firstProgressCallbackIdleTask);
if ( !(pInterfacePlayerRDK->TimerIsRunning( privatePlayer->gstPrivateContext->periodicProgressCallbackIdleTaskId)) )
{
double reportProgressInterval = pInterfacePlayerRDK->m_gstConfigParam->progressTimer;
reportProgressInterval *= 1000; //convert s to ms
GSourceFunc timerFunc = ProgressCallbackOnTimeout;
pInterfacePlayerRDK->TimerAdd(timerFunc, (int)reportProgressInterval, privatePlayer->gstPrivateContext->periodicProgressCallbackIdleTaskId, user_data, "periodicProgressCallbackIdleTask");
}
else
{
MW_LOG_INFO("Progress callback already available: periodicProgressCallbackIdleTaskId %d", privatePlayer->gstPrivateContext->periodicProgressCallbackIdleTaskId);
}
}
return G_SOURCE_REMOVE;
}
/**
* @brief Idle callback to notify first video frame was displayed
* @param[in] user_data pointer to InterfacePlayerRDK instance
* @retval G_SOURCE_REMOVE, if the source should be removed
*/
gboolean InterfacePlayerRDK::IdleCallbackFirstVideoFrameDisplayed(gpointer user_data)
{
InterfacePlayerRDK *pInterfacePlayerRDK = (InterfacePlayerRDK *)user_data;
InterfacePlayerPriv* privatePlayer = nullptr;
if (pInterfacePlayerRDK)
{
privatePlayer = pInterfacePlayerRDK->GetPrivatePlayer();
pInterfacePlayerRDK->TriggerEvent(InterfaceCB::firstVideoFrameDisplayed);
pInterfacePlayerRDK->IdleTaskRemove(privatePlayer->gstPrivateContext->firstVideoFrameDisplayedCallbackTask);
}
return G_SOURCE_REMOVE;
}
bool gst_StartsWith( const char *inputStr, const char *prefix );
/**
*@brief set the encrypted content, should be used by playready plugin
*/
void InterfacePlayerRDK::setEncryption(void *Encrypt, void *DRMSessionManager)
{
mEncrypt = Encrypt;
mDRMSessionManager = DRMSessionManager;
}
/**
*@brief sets the preferred drm by app
*@param[in] drmID preferred drm
*/
void InterfacePlayerRDK::SetPreferredDRM(const char *drmID)
{
if (drmID != NULL)
{
if (mDrmSystem != NULL)
{
delete[] mDrmSystem;
}
mDrmSystem = new char[strlen(drmID) + 1];
if (mDrmSystem != NULL)
{
strcpy(mDrmSystem, drmID);
}
else
{
MW_LOG_ERR("Memory allocation failed for mDrmSystem\n");
}
}
}
/**
* @brief Called from the mainloop when a message is available on the bus
* @param[in] bus the GstBus that sent the message
* @param[in] msg the GstMessage
* @param[in] pInterfacePlayerRDK pointer to InterfacePlayerRDK instance
* @retval FALSE if the event source should be removed.
*/
static gboolean bus_message(GstBus * bus, GstMessage * msg, InterfacePlayerRDK * pInterfacePlayerRDK);
/**
* @brief check if element is instance
*/
static void type_check_instance( const char * str, GstElement * elem);
/**
* @fn InterfacePlayerRDK_SignalEOS
* @brief Signal EOS to the appsrc associated with the supplied media stream
* @param[in] media_stream the media stream to inject EOS into
*/
static void GstPlayer_SignalEOS(gst_media_stream& stream)
{
if (stream.source)
{
auto ret = gst_app_src_end_of_stream(GST_APP_SRC_CAST(stream.source));
//GST_FLOW_OK is expected in PAUSED or PLAYING states; GST_FLOW_FLUSHING is expected in other states.
if (ret != GST_FLOW_OK)
{
MW_LOG_WARN("gst_app_src_push_buffer error: %d", ret);
}
}
}
static void GstPlayer_SignalEOS(gst_media_stream* stream)
{
if(stream)
{
GstPlayer_SignalEOS(*stream);
}
}
/**
* @brief inject EOS for all media types to ensure the pipeline can be set to NULL quickly*/
static void GstPlayer_SignalEOS(GstPlayerPriv* gstPrivateContext)
{
MW_LOG_MIL(" InterfacePlayer: Inject EOS into all streams.");
if(gstPrivateContext && gstPrivateContext->pipeline)
{
for(int mediaType=eGST_MEDIATYPE_VIDEO; mediaType<=eGST_MEDIATYPE_SUBTITLE; mediaType++)
{
GstPlayer_SignalEOS(gstPrivateContext->stream[mediaType]);
}
}
else
{
MW_LOG_WARN(" InterfacePlayer: null pointer check failed");
}
}
/**
* @fn SetSeekPosition
* @param[in] positionSecs - the start position to seek the pipeline to in seconds
*/
void InterfacePlayerRDK::SetSeekPosition(double positionSecs)
{
interfacePlayerPriv->gstPrivateContext->seekPosition = positionSecs;
for (int i = 0; i < GST_TRACK_COUNT; i++)
{
interfacePlayerPriv->gstPrivateContext->stream[i].pendingSeek = true;
}
}
static constexpr int RECURSION_LIMIT = 10;
/**
* @brief GetElementPointers adds the supplied element/bin and any child elements up to RECURSION_LIMIT depth to elements
*/
static void GetElementPointers(gpointer pElementOrBin, std::set<gpointer>& elements, int& recursionCount)
{
recursionCount++;
if(RECURSION_LIMIT < recursionCount)
{
MW_LOG_ERR(" Interface recursion limit exceeded");
}
else if(GST_IS_ELEMENT(pElementOrBin))
{
elements.insert(pElementOrBin);
if(GST_IS_BIN(pElementOrBin))
{
for (auto currentListItem = GST_BIN_CHILDREN(reinterpret_cast<_GstElement*>(pElementOrBin));
currentListItem;
currentListItem = currentListItem->next)
{
auto currentChildElement = currentListItem->data;
if (nullptr != currentChildElement)
{
//Recursive function call to support nesting of gst elements up RECURSION_LIMIT
GetElementPointers(currentChildElement, elements, recursionCount);
}
}
}
}
recursionCount--;
}
/**
* @brief GetElementPointers returns a set of pointers to the supplied element/bin and any child elements up to RECURSION_LIMIT depth
*/
static std::set<gpointer> GetElementPointers(gpointer pElementOrBin)
{
int recursionCount = 0;
std::set<gpointer> elements;
GetElementPointers(pElementOrBin, elements, recursionCount);
return elements;
}
void InterfacePlayerRDK::DisconnectSignals()
{
const std::lock_guard<std::mutex> lock(interfacePlayerPriv->gstPrivateContext->mSignalVectorAccessMutex);
if(m_gstConfigParam->enableDisconnectSignals)
{
std::set<gpointer> elements = GetElementPointers(interfacePlayerPriv->gstPrivateContext->pipeline);
for(const auto& data: interfacePlayerPriv->gstPrivateContext->mCallBackIdentifiers)
{
if (data.instance == nullptr)
{
MW_LOG_ERR(" InterfacePlayerRDK: %s signal handler, connected instance pointer is null", data.name.c_str());
}
else if(data.id == 0)
{
MW_LOG_ERR(" InterfacePlayerRDK: %s signal handler id is 0", data.name.c_str());
}
else if(!elements.count(data.instance))
{
// This is expected following some tune failures
MW_LOG_WARN(" InterfacePlayerRDK: %s signal handler, connected instance is not in the pipeline", data.name.c_str());
}