-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_aamp.cpp
executable file
·3227 lines (2894 loc) · 88.3 KB
/
main_aamp.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
/*
* If not stated otherwise in this file or this component's license file the
* following copyright and licenses apply:
*
* Copyright 2018 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.
*/
/**
* @file main_aamp.cpp
* @brief Advanced Adaptive Media Player (AAMP)
*/
#ifdef IARM_MGR
#include "host.hpp"
#include "manager.hpp"
#include "libIBus.h"
#include "libIBusDaemon.h"
#include "irMgr.h"
#endif
#include "main_aamp.h"
#include "AampConfig.h"
#include "AampCacheHandler.h"
#include "AampUtils.h"
#ifdef AAMP_CC_ENABLED
#include "AampCCManager.h"
#endif
#include "helper/AampDrmHelper.h"
#include "StreamAbstractionAAMP.h"
#include "aampgstplayer.h"
#include <dlfcn.h>
#include <termios.h>
#include <errno.h>
#include <regex>
AampConfig *gpGlobalConfig=NULL;
AampLogManager *mLogObj=NULL;
#ifdef USE_SECMANAGER
#include "AampSecManager.h"
#endif
#define ERROR_STATE_CHECK_VOID() \
PrivAAMPState state = GetState(); \
if( state == eSTATE_ERROR){ \
AAMPLOG_WARN("operation is not allowed when player in eSTATE_ERROR state !");\
return; \
}
#define ERROR_STATE_CHECK_VAL(val) \
PrivAAMPState state = GetState(); \
if( state == eSTATE_ERROR){ \
AAMPLOG_WARN("operation is not allowed when player in eSTATE_ERROR state !");\
return val; \
}
#define ERROR_OR_IDLE_STATE_CHECK_VOID() \
PrivAAMPState state = GetState(); \
if( state == eSTATE_ERROR || state == eSTATE_IDLE){ \
AAMPLOG_WARN("operation is not allowed when player in %s state !",\
(state == eSTATE_ERROR) ? "eSTATE_ERROR" : "eSTATE_IDLE" );\
return; \
}
#define NOT_IDLE_AND_NOT_RELEASED_STATE_CHECK_VOID() \
PrivAAMPState state = GetState(); \
if( state != eSTATE_IDLE && state != eSTATE_RELEASED){ \
AAMPLOG_WARN("operation is not allowed when player not in eSTATE_IDLE or eSTATE_RELEASED state !");\
return; \
}
#define ERROR_OR_IDLE_STATE_CHECK_VAL(val) \
PrivAAMPState state = GetState(); \
if( state == eSTATE_ERROR || state == eSTATE_IDLE){ \
AAMPLOG_WARN("operation is not allowed in %s state !",\
(state == eSTATE_ERROR) ? "eSTATE_ERROR" : "eSTATE_IDLE" );\
return val; \
}
#define PLAYING_STATE_CHECK() \
PrivAAMPState state = GetState(); \
if( state != eSTATE_STOPPED && state != eSTATE_IDLE && state != eSTATE_COMPLETE && state != eSTATE_RELEASED){ \
AAMPLOG_WARN("Operation is not allowed when player in playing state !!");\
return; \
}
static bool iarmInitialized = false;
std::mutex PlayerInstanceAAMP::mPrvAampMtx;
/**
* @brief PlayerInstanceAAMP Constructor.
*/
PlayerInstanceAAMP::PlayerInstanceAAMP(StreamSink* streamSink
, std::function< void(uint8_t *, int, int, int) > exportFrames
) : aamp(NULL), sp_aamp(nullptr), mInternalStreamSink(NULL), mJSBinding_DL(),mAsyncRunning(false),mConfig(),mAsyncTuneEnabled(false),mScheduler()
{
#ifdef IARM_MGR
if(!iarmInitialized)
{
char processName[20] = {0};
IARM_Result_t result;
snprintf(processName, sizeof(processName), "AAMP-PLAYER-%u", getpid());
if (IARM_RESULT_SUCCESS == (result = IARM_Bus_Init((const char*) &processName))) {
logprintf("IARM Interface Inited in AAMP");
}
else {
logprintf("IARM Interface Inited Externally : %d", result);
}
if (IARM_RESULT_SUCCESS == (result = IARM_Bus_Connect())) {
logprintf("IARM Interface Connected in AAMP");
}
else {
logprintf ("IARM Interface Connected Externally :%d", result);
}
iarmInitialized = true;
}
#endif
#ifdef SUPPORT_JS_EVENTS
#ifdef AAMP_WPEWEBKIT_JSBINDINGS //aamp_LoadJS defined in libaampjsbindings.so
const char* szJSLib = "libaampjsbindings.so";
#else
const char* szJSLib = "libaamp.so";
#endif
mJSBinding_DL = dlopen(szJSLib, RTLD_GLOBAL | RTLD_LAZY);
logprintf("[AAMP_JS] dlopen(\"%s\")=%p", szJSLib, mJSBinding_DL);
#endif
// Create very first instance of Aamp Config to read the cfg & Operator file .This is needed for very first
// tune only . After that every tune will use the same config parameters
if(gpGlobalConfig == NULL)
{
#ifdef AAMP_BUILD_INFO
std::string tmpstr = MACRO_TO_STRING(AAMP_BUILD_INFO);
logprintf(" AAMP_BUILD_INFO: %s",tmpstr.c_str());
#endif
gpGlobalConfig = new AampConfig();
// Init the default values
gpGlobalConfig->Initialize();
gpGlobalConfig->ReadDeviceCapability();
AAMPLOG_WARN("[AAMP_JS][%p]Creating GlobalConfig Instance[%p]",this,gpGlobalConfig);
if(!gpGlobalConfig->ReadAampCfgTxtFile())
{
gpGlobalConfig->ReadAampCfgJsonFile();
}
gpGlobalConfig->ReadOperatorConfiguration();
gpGlobalConfig->ShowDevCfgConfiguration();
gpGlobalConfig->ShowOperatorSetConfiguration();
::mLogObj = gpGlobalConfig->GetLoggerInstance();
}
// Copy the default configuration to session configuration .
// App can modify the configuration set
mConfig = *gpGlobalConfig;
sp_aamp = std::make_shared<PrivateInstanceAAMP>(&mConfig);
aamp = sp_aamp.get();
mLogObj = mConfig.GetLoggerInstance();
mConfig.logging.setPlayerId(aamp->mPlayerId);
// start Scheduler Worker for task handling
mScheduler.SetLogger(mLogObj);
mScheduler.StartScheduler();
if (NULL == streamSink)
{
mInternalStreamSink = new AAMPGstPlayer(mConfig.GetLoggerInstance(), aamp
#ifdef RENDER_FRAMES_IN_APP_CONTEXT
, exportFrames
#endif
);
streamSink = mInternalStreamSink;
}
else
{
// Disable async tune in aamp as plugin mode, since it already called from aamp gst as async call
SETCONFIGVALUE(AAMP_APPLICATION_SETTING, eAAMPConfig_AsyncTune, false);
mAsyncRunning = false;
}
aamp->SetStreamSink(streamSink);
aamp->SetScheduler(&mScheduler);
AsyncStartStop();
}
/**
* @brief PlayerInstanceAAMP Destructor.
*/
PlayerInstanceAAMP::~PlayerInstanceAAMP()
{
mLogObj = gpGlobalConfig->GetLoggerInstance();
#ifdef AAMP_CC_ENABLED
AampCCManager::GetInstance()->SetLogger(mLogObj);
#endif
if (aamp)
{
PrivAAMPState state;
aamp->GetState(state);
// Acquire the lock , to prevent new entries into scheduler
mScheduler.SuspendScheduler();
// Remove all the tasks
mScheduler.RemoveAllTasks();
if (state != eSTATE_IDLE && state != eSTATE_RELEASED)
{
//Avoid stop call since already stopped
aamp->Stop();
}
std::lock_guard<std::mutex> lock (mPrvAampMtx);
aamp = NULL;
}
SAFE_DELETE(mInternalStreamSink);
// Stop the scheduler
mAsyncRunning = false;
mScheduler.StopScheduler();
bool isLastPlayerInstance = !PrivateInstanceAAMP::IsActiveInstancePresent();
#ifdef AAMP_CC_ENABLED
if (isLastPlayerInstance)
{
AampCCManager::DestroyInstance();
}
#endif
#ifdef SUPPORT_JS_EVENTS
if (mJSBinding_DL && isLastPlayerInstance)
{
AAMPLOG_WARN("[AAMP_JS] dlclose(%p)", mJSBinding_DL);
dlclose(mJSBinding_DL);
}
#endif
#ifdef USE_SECMANAGER
if (isLastPlayerInstance)
{
AampSecManager::DestroyInstance();
}
#endif
if (isLastPlayerInstance && gpGlobalConfig)
{
AAMPLOG_WARN("[%p] Release GlobalConfig(%p)",this,gpGlobalConfig);
SAFE_DELETE(gpGlobalConfig);
}
}
/**
* @brief API to reset configuration across tunes for single player instance
*/
void PlayerInstanceAAMP::ResetConfiguration()
{
AAMPLOG_WARN("Resetting Configuration to default values ");
// Copy the default configuration to session configuration .App can modify the configuration set
mConfig = *gpGlobalConfig;
mLogObj = mConfig.GetLoggerInstance();
#ifdef AAMP_CC_ENABLED
AampCCManager::GetInstance()->SetLogger(mLogObj);
#endif
// Based on the default condition , reset the AsyncTune scheduler
AsyncStartStop();
}
/**
* @brief Stop playback and release resources.
*/
void PlayerInstanceAAMP::Stop(bool sendStateChangeEvent)
{
if (aamp)
{
PrivAAMPState state;
aamp->GetState(state);
// 1. Ensure scheduler is suspended and all tasks if any to be cleaned
// 2. Check for state ,if already in Idle / Released , ignore stopInternal
// 3. Restart the scheduler , needed if same instance is used for tune again
mScheduler.SuspendScheduler();
mScheduler.RemoveAllTasks();
//state will be eSTATE_IDLE or eSTATE_RELEASED, right after an init or post-processing of a Stop call
if (state != eSTATE_IDLE && state != eSTATE_RELEASED)
{
StopInternal(sendStateChangeEvent);
}
//Release lock
mScheduler.ResumeScheduler();
}
}
/**
* @brief Tune to a URL.
* DEPRECATED! This is included for backwards compatibility with current Sky AS integration
* audioDecoderStreamSync is a broadcom-specific hack (for original xi6 POC build) - this doesn't belong in Tune API.
*/
void PlayerInstanceAAMP::Tune(const char *mainManifestUrl, const char *contentType, bool bFirstAttempt, bool bFinalAttempt,const char *traceUUID,bool audioDecoderStreamSync)
{
Tune(mainManifestUrl, /*autoPlay*/ true, contentType,bFirstAttempt,bFinalAttempt,traceUUID,audioDecoderStreamSync);
}
/**
* @brief Tune to a URL.
*/
void PlayerInstanceAAMP::Tune(const char *mainManifestUrl, bool autoPlay, const char *contentType, bool bFirstAttempt, bool bFinalAttempt,const char *traceUUID,bool audioDecoderStreamSync)
{
#ifdef AMLOGIC
ManageAsyncTuneConfig(mainManifestUrl);
#endif
if(mAsyncTuneEnabled)
{
const std::string manifest {mainManifestUrl};
const std::string cType = (contentType != NULL) ? std::string(contentType) : std::string();
const std::string sTraceUUID = (traceUUID != NULL)? std::string(traceUUID) : std::string();
mScheduler.ScheduleTask(AsyncTaskObj(
[manifest, autoPlay , cType, bFirstAttempt, bFinalAttempt, sTraceUUID, audioDecoderStreamSync](void *data)
{
PlayerInstanceAAMP *instance = static_cast<PlayerInstanceAAMP *>(data);
const char * trace_uuid = sTraceUUID.empty() ? nullptr : sTraceUUID.c_str();
instance->TuneInternal(manifest.c_str(), autoPlay, cType.c_str(), bFirstAttempt, bFinalAttempt, trace_uuid, audioDecoderStreamSync);
},
(void *) this,
__FUNCTION__));
}
else
{
TuneInternal(mainManifestUrl, autoPlay , contentType, bFirstAttempt, bFinalAttempt,traceUUID,audioDecoderStreamSync);
}
}
/**
* @brief Tune to a URL.
*/
void PlayerInstanceAAMP::TuneInternal(const char *mainManifestUrl, bool autoPlay, const char *contentType, bool bFirstAttempt, bool bFinalAttempt,const char *traceUUID,bool audioDecoderStreamSync)
{
PrivAAMPState state;
if(aamp){
aamp->StopPausePositionMonitoring("Tune() called");
aamp->GetState(state);
bool IsOTAtoOTA = false;
if((aamp->IsOTAContent()) && (NULL != mainManifestUrl))
{
/* OTA to OTA tune does not need to call stop. */
std::string urlStr(mainManifestUrl); // for convenience, convert to std::string
if((urlStr.rfind("live:",0)==0) || (urlStr.rfind("tune:",0)==0))
{
IsOTAtoOTA = true;
}
}
if ((state != eSTATE_IDLE) && (state != eSTATE_RELEASED) && (!IsOTAtoOTA))
{
//Calling tune without closing previous tune
StopInternal(false);
}
aamp->getAampCacheHandler()->StartPlaylistCache();
aamp->Tune(mainManifestUrl, autoPlay, contentType, bFirstAttempt, bFinalAttempt,traceUUID,audioDecoderStreamSync);
}
}
/**
* @brief Soft stop the player instance.
*/
void PlayerInstanceAAMP::detach()
{
// detach is similar to Stop , need to run like stop in Sync mode
if(aamp){
//Acquire lock
mScheduler.SuspendScheduler();
aamp->StopPausePositionMonitoring("detach() called");
aamp->detach();
//Release lock
mScheduler.ResumeScheduler();
}
}
/**
* @brief Register event handler.
*/
void PlayerInstanceAAMP::RegisterEvents(EventListener* eventListener)
{
aamp->RegisterEvents(eventListener);
}
/**
* @brief UnRegister event handler.
*/
void PlayerInstanceAAMP::UnRegisterEvents(EventListener* eventListener)
{
aamp->UnRegisterEvents(eventListener);
}
/**
* @brief Set retry limit on Segment injection failure.
*/
void PlayerInstanceAAMP::SetSegmentInjectFailCount(int value)
{
SETCONFIGVALUE(AAMP_APPLICATION_SETTING,eAAMPConfig_SegmentInjectThreshold,value);
}
/**
* @brief Set retry limit on Segment drm decryption failure.
*/
void PlayerInstanceAAMP::SetSegmentDecryptFailCount(int value)
{
SETCONFIGVALUE(AAMP_APPLICATION_SETTING,eAAMPConfig_DRMDecryptThreshold,value);
}
/**
* @brief Set initial buffer duration in seconds
*/
void PlayerInstanceAAMP::SetInitialBufferDuration(int durationSec)
{
NOT_IDLE_AND_NOT_RELEASED_STATE_CHECK_VOID();
SETCONFIGVALUE(AAMP_APPLICATION_SETTING,eAAMPConfig_InitialBuffer,durationSec);
}
/**
* @brief Get initial buffer duration in seconds
*/
int PlayerInstanceAAMP::GetInitialBufferDuration(void)
{
int durationSec;
GETCONFIGVALUE(eAAMPConfig_InitialBuffer,durationSec);
return durationSec;
}
/**
* @brief Set Maximum Cache Size for storing playlist
*/
void PlayerInstanceAAMP::SetMaxPlaylistCacheSize(int cacheSize)
{
SETCONFIGVALUE(AAMP_APPLICATION_SETTING,eAAMPConfig_MaxPlaylistCacheSize,cacheSize);
}
/**
* @brief Set profile ramp down limit.
*/
void PlayerInstanceAAMP::SetRampDownLimit(int limit)
{
SETCONFIGVALUE(AAMP_APPLICATION_SETTING,eAAMPConfig_RampDownLimit,limit);
}
/**
* @brief Get profile ramp down limit.
*/
int PlayerInstanceAAMP::GetRampDownLimit(void)
{
int limit;
GETCONFIGVALUE(eAAMPConfig_RampDownLimit,limit);
return limit;
}
/**
* @brief Set Language preferred Format
*/
void PlayerInstanceAAMP::SetLanguageFormat(LangCodePreference preferredFormat, bool useRole)
{
//NOT_IDLE_AND_NOT_RELEASED_STATE_CHECK_VOID(); // why was this here?
SETCONFIGVALUE(AAMP_APPLICATION_SETTING,eAAMPConfig_LanguageCodePreference,(int)preferredFormat);
if( useRole )
{
AAMPLOG_WARN("SetLanguageFormat bDescriptiveAudioTrack deprecated!" );
}
//gpGlobalConfig->bDescriptiveAudioTrack = useRole;
}
/**
* @brief Set minimum bitrate value.
*/
void PlayerInstanceAAMP::SetMinimumBitrate(long bitrate)
{
if (bitrate > 0)
{
AAMPLOG_INFO("Setting minimum bitrate: %ld", bitrate);
SETCONFIGVALUE(AAMP_APPLICATION_SETTING,eAAMPConfig_MinBitrate,(int)bitrate);
}
else
{
AAMPLOG_WARN("Invalid bitrate value %ld", bitrate);
}
}
/**
* @brief Get minimum bitrate value.
*/
long PlayerInstanceAAMP::GetMinimumBitrate(void)
{
int bitrate;
GETCONFIGVALUE(eAAMPConfig_MinBitrate,bitrate);
return bitrate;
}
/**
* @brief Set maximum bitrate value.
*/
void PlayerInstanceAAMP::SetMaximumBitrate(long bitrate)
{
if (bitrate > 0)
{
AAMPLOG_INFO("Setting maximum bitrate : %ld", bitrate);
SETCONFIGVALUE(AAMP_APPLICATION_SETTING,eAAMPConfig_MaxBitrate,(int)bitrate);
}
else
{
AAMPLOG_WARN("Invalid bitrate value %ld", bitrate);
}
}
/**
* @brief Get maximum bitrate value.
*/
long PlayerInstanceAAMP::GetMaximumBitrate(void)
{
int bitrate;
GETCONFIGVALUE(eAAMPConfig_MaxBitrate,bitrate);
return bitrate;
}
/**
* @brief Check given rate is valid.
*/
bool PlayerInstanceAAMP::IsValidRate(int rate)
{
bool retValue = false;
if (abs(rate) <= AAMP_RATE_TRICKPLAY_MAX)
{
retValue = true;
}
return retValue;
}
/**
* @brief Set playback rate.
*/
void PlayerInstanceAAMP::SetRate(float rate,int overshootcorrection)
{
AAMPLOG_INFO("PLAYER[%d] rate=%f.", aamp->mPlayerId, rate);
if(aamp)
{
if (!IsValidRate(rate))
{
AAMPLOG_WARN("SetRate ignored!! Invalid rate (%f)", rate);
return;
}
if(mAsyncTuneEnabled)
{
mScheduler.ScheduleTask(AsyncTaskObj([rate,overshootcorrection](void *data)
{
PlayerInstanceAAMP *instance = static_cast<PlayerInstanceAAMP *>(data);
instance->SetRateInternal(rate,overshootcorrection);
}, (void *) this,__FUNCTION__));
}
else
{
SetRateInternal(rate,overshootcorrection);
}
}
}
/**
* @brief Set playback rate - Internal function
*/
void PlayerInstanceAAMP::SetRateInternal(float rate,int overshootcorrection)
{
AAMPLOG_INFO("PLAYER[%d] rate=%f.", aamp->mPlayerId, rate);
ERROR_STATE_CHECK_VOID();
if (!IsValidRate(rate))
{
AAMPLOG_WARN("SetRate ignored!! Invalid rate (%f)", rate);
return;
}
//Hack For DELIA-51318 convert the incoming rates into acceptable rates
if(ISCONFIGSET(eAAMPConfig_RepairIframes))
{
AAMPLOG_WARN("mRepairIframes is true, setting actual rate %f for the received rate %f", getWorkingTrickplayRate(rate), rate);
rate = getWorkingTrickplayRate(rate);
}
aamp->StopPausePositionMonitoring("SetRate() called");
if (aamp->mpStreamAbstractionAAMP && !(aamp->mbUsingExternalPlayer))
{
if ( AAMP_SLOWMOTION_RATE != rate && !aamp->mIsIframeTrackPresent && rate != AAMP_NORMAL_PLAY_RATE && rate != 0 && aamp->mMediaFormat != eMEDIAFORMAT_PROGRESSIVE)
{
AAMPLOG_WARN("Ignoring trickplay. No iframe tracks in stream");
aamp->NotifySpeedChanged(AAMP_NORMAL_PLAY_RATE); // Send speed change event to XRE to reset the speed to normal play since the trickplay ignored at player level.
return;
}
if(!(aamp->mbPlayEnabled) && aamp->pipeline_paused && (AAMP_RATE_PAUSE != rate) && (aamp->mbSeeked || !aamp->mbDetached))
{
AAMPLOG_WARN("PLAYER[%d] Player %s=>%s.", aamp->mPlayerId, STRBGPLAYER, STRFGPLAYER );
aamp->mbPlayEnabled = true;
if (AAMP_NORMAL_PLAY_RATE == rate)
{
aamp->LogPlayerPreBuffered();
aamp->mStreamSink->Configure(aamp->mVideoFormat, aamp->mAudioFormat, aamp->mAuxFormat, aamp->mSubtitleFormat, aamp->mpStreamAbstractionAAMP->GetESChangeStatus(), aamp->mpStreamAbstractionAAMP->GetAudioFwdToAuxStatus());
aamp->ResumeDownloads(); //To make sure that the playback resumes after a player switch if player was in paused state before being at background
aamp->mpStreamAbstractionAAMP->StartInjection();
aamp->mStreamSink->Stream();
aamp->pipeline_paused = false;
aamp->mbSeeked = false;
return;
}
else if(AAMP_RATE_PAUSE != rate)
{
AAMPLOG_INFO("Player switched at trickplay %f", rate);
aamp->playerStartedWithTrickPlay = true; //to be used to show atleast one frame
}
}
bool retValue = true;
if ( AAMP_SLOWMOTION_RATE != rate && rate > 0 && aamp->IsLive() && aamp->mpStreamAbstractionAAMP->IsStreamerAtLivePoint() && aamp->rate >= AAMP_NORMAL_PLAY_RATE && !aamp->mbDetached)
{
AAMPLOG_WARN("Already at logical live point, hence skipping operation");
aamp->NotifyOnEnteringLive();
return;
}
// DELIA-39691 If input rate is same as current playback rate, skip duplicate operation
// Additional check for pipeline_paused is because of 0(PAUSED) -> 1(PLAYING), where aamp->rate == 1.0 in PAUSED state
if ((!aamp->pipeline_paused && rate == aamp->rate && !aamp->GetPauseOnFirstVideoFrameDisp()) || (rate == 0 && aamp->pipeline_paused))
{
AAMPLOG_WARN("Already running at playback rate(%f) pipeline_paused(%d), hence skipping set rate for (%f)", aamp->rate, aamp->pipeline_paused, rate);
return;
}
//DELIA-30274 -- Get the trick play to a closer position
//Logic adapted
// XRE gives fixed overshoot position , not suited for aamp . So ignoring overshoot correction value
// instead use last reported posn vs the time player get play command
// a. During trickplay , last XRE reported position is aamp->mNewSeekInfo.getInfo().Position()
/// and last reported time is aamp->mNewSeekInfo.getInfo().UpdateTime()
// b. Calculate the time delta from last reported time
// c. Using this diff , calculate the best/nearest match position (works out 70-80%)
// d. If time delta is < 100ms ,still last video fragment rendering is not removed ,but position updated very recently
// So switch last displayed position - NewPosn -= Posn - ((aamp->rate/4)*1000)
// e. If time delta is > 950ms , possibility of next frame to come by the time play event is processed.
//So go to next fragment which might get displayed
// f. If none of above ,maintain the last displayed position .
//
// h. TODO (again trial n error) - for 3x/4x , within 1sec there might multiple frame displayed . Can use timedelta to calculate some more near,to be tried
const auto SeekInfo = aamp->mNewSeekInfo.GetInfo();
const int timeDeltaFromProgReport = SeekInfo.getTimeSinceUpdateMs();
//Skip this logic for either going to paused to coming out of paused scenarios with HLS
//What we would like to avoid here is the update of seek_pos_seconds because gstreamer position will report proper position
//Check for 1.0 -> 0.0 and 0.0 -> 1.0 usecase and avoid below logic
if (!((aamp->rate == AAMP_NORMAL_PLAY_RATE && rate == 0) || (aamp->pipeline_paused && rate == AAMP_NORMAL_PLAY_RATE)))
{
// when switching from trick to play mode only
if(aamp->rate && ( AAMP_SLOWMOTION_RATE == rate || rate == AAMP_NORMAL_PLAY_RATE) && !aamp->pipeline_paused)
{
const auto seek_pos_seconds_copy = aamp->seek_pos_seconds; //ensure the same value of seek_pos_seconds used in the check is logged
if(!SeekInfo.isPositionValid(seek_pos_seconds_copy))
{
AAMPLOG_WARN("Cached seek position (%f) is invalid. seek_pos_seconds = %f, seek_pos_seconds @ last report = %f.",SeekInfo.getPosition(), seek_pos_seconds_copy, SeekInfo.getSeekPositionSec());
}
else
{
double newSeekPosInSec = -1;
if (ISCONFIGSET(eAAMPConfig_EnableGstPositionQuery))
{
// Get the last frame position when resume from the trick play.
newSeekPosInSec = (SeekInfo.getPosition()/1000);
}
else
{
if(timeDeltaFromProgReport > 950) // diff > 950 mSec
{
// increment by 1x trickplay frame , next possible displayed frame
newSeekPosInSec = (SeekInfo.getPosition()+(aamp->rate*1000))/1000;
}
else if(timeDeltaFromProgReport > 100) // diff > 100 mSec
{
// Get the last shown frame itself
newSeekPosInSec = SeekInfo.getPosition()/1000;
}
else
{
// Go little back to last shown frame
newSeekPosInSec = (SeekInfo.getPosition()-(aamp->rate*1000))/1000;
}
}
if (newSeekPosInSec >= 0)
{
/* Note circular calculation:
* newSeekPosInSec is based on aamp->mNewSeekInfo
* aamp->mNewSeekInfo's position value is based on PrivateInstanceAAMP::GetPositionMilliseconds()
* PrivateInstanceAAMP::GetPositionMilliseconds() uses seek_pos_seconds
*/
aamp->seek_pos_seconds = newSeekPosInSec;
}
else
{
AAMPLOG_WARN("new seek_pos_seconds calculated is invalid(%f), discarding it!", newSeekPosInSec);
}
}
}
else
{
// Coming out of pause mode(aamp->rate=0) or when going into pause mode (rate=0)
// Show the last position
aamp->seek_pos_seconds = aamp->GetPositionSeconds();
}
aamp->trickStartUTCMS = -1;
}
else
{
// DELIA-39530 - For 1.0->0.0 and 0.0->1.0 if eAAMPConfig_EnableGstPositionQuery is enabled, GStreamer position query will give proper value
// Fallback case added for when eAAMPConfig_EnableGstPositionQuery is disabled, since we will be using elapsedTime to calculate position and
// trickStartUTCMS has to be reset
if (!ISCONFIGSET(eAAMPConfig_EnableGstPositionQuery) && !aamp->mbDetached)
{
aamp->seek_pos_seconds = aamp->GetPositionSeconds();
aamp->trickStartUTCMS = -1;
}
}
if( AAMP_SLOWMOTION_RATE == rate )
{
/* Handling of fwd slowmotion playback */
SetSlowMotionPlayRate(rate);
aamp->NotifySpeedChanged(rate, false);
return;
}
AAMPLOG_WARN("aamp_SetRate (%f)overshoot(%d) ProgressReportDelta:(%d) ", rate,overshootcorrection,timeDeltaFromProgReport);
AAMPLOG_WARN("aamp_SetRate rate(%f)->(%f) cur pipeline: %s. Adj position: %f Play/Pause Position:%lld", aamp->rate,rate,aamp->pipeline_paused ? "paused" : "playing",aamp->seek_pos_seconds,aamp->GetPositionMilliseconds()); // current position relative to tune time
if (!aamp->mSeekFromPausedState && (rate == aamp->rate) && !aamp->mbDetached)
{ // no change in desired play rate
// no deferring for playback resume
if (aamp->pipeline_paused && rate != 0)
{ // but need to unpause pipeline
AAMPLOG_INFO("Resuming Playback at Position '%lld'.", aamp->GetPositionMilliseconds());
// check if unpausing in the middle of fragments caching
if(!aamp->SetStateBufferingIfRequired())
{
aamp->mpStreamAbstractionAAMP->NotifyPlaybackPaused(false);
retValue = aamp->mStreamSink->Pause(false, false);
aamp->NotifyFirstBufferProcessed(); //required since buffers are already cached in paused state
}
aamp->pipeline_paused = false;
aamp->ResumeDownloads();
}
}
else if (rate == 0)
{
if (!aamp->pipeline_paused)
{
aamp->mpStreamAbstractionAAMP->NotifyPlaybackPaused(true);
aamp->StopDownloads();
retValue = aamp->mStreamSink->Pause(true, false);
aamp->pipeline_paused = true;
if(aamp->GetLLDashServiceData()->lowLatencyMode)
{
// PAUSED to PLAY without tune, LLD rate correction is disabled to keep position
AAMPLOG_INFO("LL-Dash speed correction disabled after Pause");
aamp->SetLLDashAdjustSpeed(false);
}
aamp->mDisableRateCorrection = true;
}
}
else
{
//Enable playback if setRate call after detach
if(aamp->mbDetached){
aamp->mbPlayEnabled = true;
}
TuneType tuneTypePlay = eTUNETYPE_SEEK;
if(aamp->mJumpToLiveFromPause)
{
tuneTypePlay = eTUNETYPE_SEEKTOLIVE;
aamp->mJumpToLiveFromPause = false;
}
/* if Gstreamer pipeline set to paused state by user, change it to playing state */
if( aamp->pipeline_paused == true )
{
aamp->mStreamSink->Pause(false, false);
}
aamp->rate = rate;
aamp->pipeline_paused = false;
aamp->mSeekFromPausedState = false;
/* Clear setting playerrate flag */
aamp->mSetPlayerRateAfterFirstframe=false;
aamp->EnableDownloads();
aamp->ResumeDownloads();
aamp->AcquireStreamLock();
aamp->TuneHelper(tuneTypePlay); // this unpauses pipeline as side effect
aamp->ReleaseStreamLock();
}
if(retValue)
{
// Do not update state if fragments caching is ongoing and pipeline not paused,
// target state will be updated once caching completed
aamp->NotifySpeedChanged(aamp->pipeline_paused ? 0 : aamp->rate,
(!aamp->IsFragmentCachingRequired() || aamp->pipeline_paused));
}
}
else
{
AAMPLOG_WARN("aamp_SetRate rate[%f] - mpStreamAbstractionAAMP[%p] state[%d]", aamp->rate, aamp->mpStreamAbstractionAAMP, state);
}
}
/**
* @brief Set PauseAt position.
*/
void PlayerInstanceAAMP::PauseAt(double position)
{
if(aamp)
{
if(mAsyncTuneEnabled)
{
(void)mScheduler.ScheduleTask(AsyncTaskObj([position](void *data)
{
PlayerInstanceAAMP *instance = static_cast<PlayerInstanceAAMP *>(data);
instance->PauseAtInternal(position);
}, (void *) this,__FUNCTION__));
}
else
{
PauseAtInternal(position);
}
}
}
/**
* @brief Set PauseAt position - Internal function
*/
void PlayerInstanceAAMP::PauseAtInternal(double position)
{
AAMPLOG_WARN("PLAYER[%d] aamp_PauseAt position=%f", aamp->mPlayerId, position);
ERROR_STATE_CHECK_VOID();
aamp->StopPausePositionMonitoring("PauseAt() called");
if (position >= 0)
{
if (!aamp->pipeline_paused)
{
aamp->StartPausePositionMonitoring(static_cast<long long>(position * 1000));
}
else
{
AAMPLOG_WARN("PauseAt called when already paused");
}
}
}
static gboolean SeekAfterPrepared(gpointer ptr)
{
PrivateInstanceAAMP* aamp = (PrivateInstanceAAMP*) ptr;
bool sentSpeedChangedEv = false;
bool isSeekToLiveOrEnd = false;
TuneType tuneType = eTUNETYPE_SEEK;
PrivAAMPState state;
aamp->GetState(state);
if( state == eSTATE_ERROR){
AAMPLOG_WARN("operation is not allowed when player in eSTATE_ERROR state !");\
return false;
}
if (AAMP_SEEK_TO_LIVE_POSITION == aamp->seek_pos_seconds )
{
isSeekToLiveOrEnd = true;
}
AAMPLOG_WARN("aamp_Seek(%f) and seekToLiveOrEnd(%d)", aamp->seek_pos_seconds, isSeekToLiveOrEnd);
if (isSeekToLiveOrEnd)
{
if (aamp->IsLive())
{
tuneType = eTUNETYPE_SEEKTOLIVE;
}
else
{
tuneType = eTUNETYPE_SEEKTOEND;
}
}
if (aamp->IsLive() && aamp->mpStreamAbstractionAAMP && aamp->mpStreamAbstractionAAMP->IsStreamerAtLivePoint())
{
double currPositionSecs = aamp->GetPositionSeconds();
if ((tuneType == eTUNETYPE_SEEKTOLIVE) || (aamp->seek_pos_seconds >= currPositionSecs))
{
AAMPLOG_WARN("Already at live point, skipping operation since requested position(%f) >= currPosition(%f) or seekToLive(%d)", aamp->seek_pos_seconds, currPositionSecs, isSeekToLiveOrEnd);
aamp->NotifyOnEnteringLive();
return false;
}
}
if ((aamp->mbPlayEnabled) && aamp->pipeline_paused)
{
// resume downloads and clear paused flag for foreground instance. state change will be done
// on streamSink configuration.
AAMPLOG_WARN("paused state, so resume downloads");
aamp->pipeline_paused = false;
aamp->ResumeDownloads();
sentSpeedChangedEv = true;
}
if (tuneType == eTUNETYPE_SEEK)
{
AAMPLOG_WARN("tune type is SEEK");
}
if (aamp->rate != AAMP_NORMAL_PLAY_RATE)
{
aamp->rate = AAMP_NORMAL_PLAY_RATE;
sentSpeedChangedEv = true;
}
if (aamp->mpStreamAbstractionAAMP)
{ // for seek while streaming
/* LLAMA-7124
* PositionMilisecondLock is intended to ensure both state and seek_pos_seconds (in TuneHelper)
* are updated before GetPositionMilliseconds() can be used*/
auto PositionMilisecondLocked = aamp->LockGetPositionMilliseconds();
aamp->SetState(eSTATE_SEEKING);
/* Clear setting playerrate flag */
aamp->mSetPlayerRateAfterFirstframe=false;
aamp->AcquireStreamLock();
aamp->TuneHelper(tuneType);
if(PositionMilisecondLocked)
{
aamp->UnlockGetPositionMilliseconds();
}
aamp->ReleaseStreamLock();
if (sentSpeedChangedEv)
{
aamp->NotifySpeedChanged(aamp->rate, false);
}
}
return false; // G_SOURCE_REMOVE = false , G_SOURCE_CONTINUE = true
}
/**
* @brief Seek to a time.
*/
void PlayerInstanceAAMP::Seek(double secondsRelativeToTuneTime, bool keepPaused)
{
if(aamp)
{
PrivAAMPState state;
aamp->GetState(state);
if(mAsyncTuneEnabled && state != eSTATE_IDLE && state != eSTATE_RELEASED)
{
mScheduler.ScheduleTask(AsyncTaskObj([secondsRelativeToTuneTime,keepPaused](void *data)
{
PlayerInstanceAAMP *instance = static_cast<PlayerInstanceAAMP *>(data);
instance->SeekInternal(secondsRelativeToTuneTime,keepPaused);
}, (void *) this,__FUNCTION__));
}
else
{
SeekInternal(secondsRelativeToTuneTime,keepPaused);
}
}
}
/**