This repository has been archived by the owner on Jan 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
priv_aamp.cpp
12042 lines (11048 loc) · 370 KB
/
priv_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 2020 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 priv_aamp.cpp
* @brief Advanced Adaptive Media Player (AAMP) PrivateInstanceAAMP impl
*/
#include "isobmffprocessor.h"
#include "priv_aamp.h"
#include "AampJsonObject.h"
#include "isobmffbuffer.h"
#include "AampFnLogger.h"
#include "AampConstants.h"
#include "AampCacheHandler.h"
#include "AampUtils.h"
#include "iso639map.h"
#include "fragmentcollector_mpd.h"
#include "admanager_mpd.h"
#include "fragmentcollector_hls.h"
#include "fragmentcollector_progressive.h"
#include "MediaStreamContext.h"
#include "hdmiin_shim.h"
#include "compositein_shim.h"
#include "ota_shim.h"
#ifdef USE_CPP_THUNDER_PLUGIN_ACCESS
#include "rmf_shim.h"
#endif
#include "_base64.h"
#include "base16.h"
#include "aampgstplayer.h"
#include "AampDRMSessionManager.h"
#include "SubtecFactory.hpp"
#ifdef AAMP_CC_ENABLED
#include "AampCCManager.h"
#endif
#ifdef USE_OPENCDM // AampOutputProtection is compiled when this flag is enabled
#include "aampoutputprotection.h"
#endif
#include "AampCurlStore.h"
#ifdef IARM_MGR
#include "host.hpp"
#include "manager.hpp"
#include "libIBus.h"
#include "libIBusDaemon.h"
#include <hostIf_tr69ReqHandler.h>
#include <sstream>
#endif
#include <sys/time.h>
#include <cmath>
#include <regex>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <uuid/uuid.h>
#include <string.h>
#define LOCAL_HOST_IP "127.0.0.1"
#define AAMP_MAX_TIME_BW_UNDERFLOWS_TO_TRIGGER_RETUNE_MS (20*1000LL)
#define AAMP_MAX_TIME_LL_BW_UNDERFLOWS_TO_TRIGGER_RETUNE_MS (AAMP_MAX_TIME_BW_UNDERFLOWS_TO_TRIGGER_RETUNE_MS/10)
//Description size
#define MAX_DESCRIPTION_SIZE 128
//Stringification of Macro : use two levels of macros
#define MACRO_TO_STRING(s) X_STR(s)
#define X_STR(s) #s
// Uncomment to test GetMediaFormatType without locator inspection
#define TRUST_LOCATOR_EXTENSION_IF_PRESENT
#define VALIDATE_INT(param_name, param_value, default_value) \
if ((param_value <= 0) || (param_value > INT_MAX)) { \
AAMPLOG_WARN("Parameter '%s' not within INTEGER limit. Using default value instead.", param_name); \
param_value = default_value; \
}
#define VALIDATE_LONG(param_name, param_value, default_value) \
if ((param_value <= 0) || (param_value > LONG_MAX)) { \
AAMPLOG_WARN("Parameter '%s' not within LONG INTEGER limit. Using default value instead.", param_name); \
param_value = default_value; \
}
#define VALIDATE_DOUBLE(param_name, param_value, default_value) \
if ((param_value <= 0) || (param_value > DBL_MAX)) { \
AAMPLOG_WARN("Parameter '%s' not within DOUBLE limit. Using default value instead.", param_name); \
param_value = default_value; \
}
#define CURL_EASY_SETOPT(curl, CURLoption, option)\
if (curl_easy_setopt(curl, CURLoption, option) != 0) {\
logprintf("Failed at curl_easy_setopt ");\
} //CID:132698,135078 - checked return
#define FOG_REASON_STRING "Fog-Reason:"
#define CURLHEADER_X_REASON "X-Reason:"
#define BITRATE_HEADER_STRING "X-Bitrate:"
#define CONTENTLENGTH_STRING "Content-Length:"
#define SET_COOKIE_HEADER_STRING "Set-Cookie:"
#define LOCATION_HEADER_STRING "Location:"
#define CONTENT_ENCODING_STRING "Content-Encoding:"
#define FOG_RECORDING_ID_STRING "Fog-Recording-Id:"
#define CAPPED_PROFILE_STRING "Profile-Capped:"
#define TRANSFER_ENCODING_STRING "Transfer-Encoding:"
#define MAX_DOWNLOAD_DELAY_LIMIT_MS 30000
/**
* New state for treating a VOD asset as a "virtual linear" stream
*/
// Note that below state/impl currently assumes single profile, and so until fixed should be tested with "abr" in aamp.cfg to disable ABR
static long long simulation_start; // time at which main manifest was downloaded.
// Simulation_start is used to calculate elapsed time, used to advance virtual live window
static char *full_playlist_video_ptr = NULL; // Cache of initial full vod video playlist
static size_t full_playlist_video_len = 0; // Size (bytes) of initial full vod video playlist
static char *full_playlist_audio_ptr = NULL; // Cache of initial full vod audio playlist
static size_t full_playlist_audio_len = 0; // Size (bytes) of initial full vod audio playlist
/**
* @struct gActivePrivAAMP_t
* @brief Used for storing active PrivateInstanceAAMPs
*/
struct gActivePrivAAMP_t
{
PrivateInstanceAAMP* pAAMP;
bool reTune;
int numPtsErrors;
};
static std::list<gActivePrivAAMP_t> gActivePrivAAMPs = std::list<gActivePrivAAMP_t>();
static pthread_mutex_t gMutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t gCond = PTHREAD_COND_INITIALIZER;
static int PLAYERID_CNTR = 0;
static const char* strAAMPPipeName = "/tmp/ipc_aamp";
static bool activeInterfaceWifi = false;
static char previousInterface[20] = {'\0'};
static unsigned int ui32CurlTrace = 0;
/**
* @struct CurlCbContextSyncTime
* @brief context during curl callbacks
*/
struct CurlCbContextSyncTime
{
PrivateInstanceAAMP *aamp;
GrowableBuffer *buffer;
CurlCbContextSyncTime() : aamp(NULL), buffer(NULL){}
CurlCbContextSyncTime(PrivateInstanceAAMP *_aamp, GrowableBuffer *_buffer) : aamp(_aamp),buffer(_buffer){}
~CurlCbContextSyncTime() {}
CurlCbContextSyncTime(const CurlCbContextSyncTime &other) = delete;
CurlCbContextSyncTime& operator=(const CurlCbContextSyncTime& other) = delete;
};
/**
* @brief Enumeration for net_srv_mgr active interface event callback
*/
typedef enum _NetworkManager_EventId_t {
IARM_BUS_NETWORK_MANAGER_EVENT_SET_INTERFACE_ENABLED=50,
IARM_BUS_NETWORK_MANAGER_EVENT_INTERFACE_IPADDRESS=55,
IARM_BUS_NETWORK_MANAGER_MAX
} IARM_Bus_NetworkManager_EventId_t;
/**
* @struct _IARM_BUS_NetSrvMgr_Iface_EventData_t
* @brief IARM Bus struct contains active streaming interface, origional definition present in homenetworkingservice.h
*/
typedef struct _IARM_BUS_NetSrvMgr_Iface_EventData_t {
union{
char activeIface[10];
char allNetworkInterfaces[50];
char enableInterface[10];
};
char interfaceCount;
bool isInterfaceEnabled;
} IARM_BUS_NetSrvMgr_Iface_EventData_t;
static TuneFailureMap tuneFailureMap[] =
{
{AAMP_TUNE_INIT_FAILED, 10, "AAMP: init failed"}, //"Fragmentcollector initialization failed"
{AAMP_TUNE_INIT_FAILED_MANIFEST_DNLD_ERROR, 10, "AAMP: init failed (unable to download manifest)"},
{AAMP_TUNE_INIT_FAILED_MANIFEST_CONTENT_ERROR, 10, "AAMP: init failed (manifest missing tracks)"},
{AAMP_TUNE_INIT_FAILED_MANIFEST_PARSE_ERROR, 10, "AAMP: init failed (corrupt/invalid manifest)"},
{AAMP_TUNE_INIT_FAILED_PLAYLIST_VIDEO_DNLD_ERROR, 10, "AAMP: init failed (unable to download video playlist)"},
{AAMP_TUNE_INIT_FAILED_PLAYLIST_AUDIO_DNLD_ERROR, 10, "AAMP: init failed (unable to download audio playlist)"},
{AAMP_TUNE_INIT_FAILED_TRACK_SYNC_ERROR, 10, "AAMP: init failed (unsynchronized tracks)"},
{AAMP_TUNE_MANIFEST_REQ_FAILED, 10, "AAMP: Manifest Download failed"}, //"Playlist refresh failed"
{AAMP_TUNE_AUTHORISATION_FAILURE, 40, "AAMP: Authorization failure"},
{AAMP_TUNE_FRAGMENT_DOWNLOAD_FAILURE, 10, "AAMP: fragment download failures"},
{AAMP_TUNE_INIT_FRAGMENT_DOWNLOAD_FAILURE, 10, "AAMP: init fragment download failed"},
{AAMP_TUNE_UNTRACKED_DRM_ERROR, 50, "AAMP: DRM error untracked error"},
{AAMP_TUNE_DRM_INIT_FAILED, 50, "AAMP: DRM Initialization Failed"},
{AAMP_TUNE_DRM_DATA_BIND_FAILED, 50, "AAMP: InitData-DRM Binding Failed"},
{AAMP_TUNE_DRM_SESSIONID_EMPTY, 50, "AAMP: DRM Session ID Empty"},
{AAMP_TUNE_DRM_CHALLENGE_FAILED, 50, "AAMP: DRM License Challenge Generation Failed"},
{AAMP_TUNE_LICENCE_TIMEOUT, 50, "AAMP: DRM License Request Timed out"},
{AAMP_TUNE_LICENCE_REQUEST_FAILED, 50, "AAMP: DRM License Request Failed"},
{AAMP_TUNE_INVALID_DRM_KEY, 50, "AAMP: Invalid Key Error, from DRM"},
{AAMP_TUNE_UNSUPPORTED_STREAM_TYPE, 60, "AAMP: Unsupported Stream Type"}, //"Unable to determine stream type for DRM Init"
{AAMP_TUNE_UNSUPPORTED_AUDIO_TYPE, 60, "AAMP: No supported Audio Types in Manifest"},
{AAMP_TUNE_FAILED_TO_GET_KEYID, 50, "AAMP: Failed to parse key id from PSSH"},
{AAMP_TUNE_FAILED_TO_GET_ACCESS_TOKEN, 50, "AAMP: Failed to get access token from Auth Service"},
{AAMP_TUNE_CORRUPT_DRM_DATA, 51, "AAMP: DRM failure due to Corrupt DRM files"},
{AAMP_TUNE_CORRUPT_DRM_METADATA, 50, "AAMP: DRM failure due to Bad DRMMetadata in stream"},
{AAMP_TUNE_DRM_DECRYPT_FAILED, 50, "AAMP: DRM Decryption Failed for Fragments"},
{AAMP_TUNE_DRM_UNSUPPORTED, 50, "AAMP: DRM format Unsupported"},
{AAMP_TUNE_DRM_SELF_ABORT, 50, "AAMP: DRM license request aborted by player"},
{AAMP_TUNE_GST_PIPELINE_ERROR, 80, "AAMP: Error from gstreamer pipeline"},
{AAMP_TUNE_PLAYBACK_STALLED, 7600, "AAMP: Playback was stalled due to lack of new fragments"},
{AAMP_TUNE_CONTENT_NOT_FOUND, 20, "AAMP: Resource was not found at the URL(HTTP 404)"},
{AAMP_TUNE_DRM_KEY_UPDATE_FAILED, 50, "AAMP: Failed to process DRM key"},
{AAMP_TUNE_DEVICE_NOT_PROVISIONED, 52, "AAMP: Device not provisioned"},
{AAMP_TUNE_HDCP_COMPLIANCE_ERROR, 53, "AAMP: HDCP Compliance Check Failure"},
{AAMP_TUNE_INVALID_MANIFEST_FAILURE, 10, "AAMP: Invalid Manifest, parse failed"},
{AAMP_TUNE_FAILED_PTS_ERROR, 80, "AAMP: Playback failed due to PTS error"},
{AAMP_TUNE_MP4_INIT_FRAGMENT_MISSING, 10, "AAMP: init fragments missing in playlist"},
{AAMP_TUNE_FAILURE_UNKNOWN, 100, "AAMP: Unknown Failure"}
};
static constexpr const char *BITRATECHANGE_STR[] =
{
(const char *)"BitrateChanged - Network adaptation", // eAAMP_BITRATE_CHANGE_BY_ABR
(const char *)"BitrateChanged - Rampdown due to network failure", // eAAMP_BITRATE_CHANGE_BY_RAMPDOWN
(const char *)"BitrateChanged - Reset to default bitrate due to tune", // eAAMP_BITRATE_CHANGE_BY_TUNE
(const char *)"BitrateChanged - Reset to default bitrate due to seek", // eAAMP_BITRATE_CHANGE_BY_SEEK
(const char *)"BitrateChanged - Reset to default bitrate due to trickplay", // eAAMP_BITRATE_CHANGE_BY_TRICKPLAY
(const char *)"BitrateChanged - Rampup since buffers are full", // eAAMP_BITRATE_CHANGE_BY_BUFFER_FULL
(const char *)"BitrateChanged - Rampdown since buffers are empty", // eAAMP_BITRATE_CHANGE_BY_BUFFER_EMPTY
(const char *)"BitrateChanged - Network adaptation by FOG", // eAAMP_BITRATE_CHANGE_BY_FOG_ABR
(const char *)"BitrateChanged - Information from OTA", // eAAMP_BITRATE_CHANGE_BY_OTA
(const char *)"BitrateChanged - Video stream information from HDMIIN", // eAAMP_BITRATE_CHANGE_BY_HDMIIN
(const char *)"BitrateChanged - Unknown reason" // eAAMP_BITRATE_CHANGE_MAX
};
#define BITRATEREASON2STRING(id) BITRATECHANGE_STR[id]
static constexpr const char *ADEVENT_STR[] =
{
(const char *)"AAMP_EVENT_AD_RESERVATION_START",
(const char *)"AAMP_EVENT_AD_RESERVATION_END",
(const char *)"AAMP_EVENT_AD_PLACEMENT_START",
(const char *)"AAMP_EVENT_AD_PLACEMENT_END",
(const char *)"AAMP_EVENT_AD_PLACEMENT_ERROR",
(const char *)"AAMP_EVENT_AD_PLACEMENT_PROGRESS"
};
#define ADEVENT2STRING(id) ADEVENT_STR[id - AAMP_EVENT_AD_RESERVATION_START]
static constexpr const char *mMediaFormatName[] =
{
"HLS","DASH","PROGRESSIVE","HLS_MP4","OTA","HDMI_IN","COMPOSITE_IN","SMOOTH_STREAMING", "RMF", "UNKNOWN"
};
static_assert(sizeof(mMediaFormatName)/sizeof(mMediaFormatName[0]) == (eMEDIAFORMAT_UNKNOWN + 1), "Ensure 1:1 mapping between mMediaFormatName[] and enum MediaFormat");
/**
* @brief Get the idle task's source ID
* @retval source ID
*/
static guint aamp_GetSourceID()
{
guint callbackId = 0;
GSource *source = g_main_current_source();
if (source != NULL)
{
callbackId = g_source_get_id(source);
}
return callbackId;
}
/**
* @brief Idle task to resume aamp
* @param ptr pointer to PrivateInstanceAAMP object
* @retval True/False
*/
static gboolean PrivateInstanceAAMP_Resume(gpointer ptr)
{
bool retValue = true;
PrivateInstanceAAMP* aamp = (PrivateInstanceAAMP* )ptr;
aamp->NotifyFirstBufferProcessed();
TuneType tuneType = eTUNETYPE_SEEK;
if (!aamp->mSeekFromPausedState && (aamp->rate == AAMP_NORMAL_PLAY_RATE))
{
retValue = aamp->mStreamSink->Pause(false, false);
aamp->pipeline_paused = false;
}
else
{
// Live immediate : seek to live position from paused state.
if (aamp->mPausedBehavior == ePAUSED_BEHAVIOR_LIVE_IMMEDIATE)
{
tuneType = eTUNETYPE_SEEKTOLIVE;
}
aamp->rate = AAMP_NORMAL_PLAY_RATE;
aamp->pipeline_paused = false;
aamp->mSeekFromPausedState = false;
aamp->AcquireStreamLock();
aamp->TuneHelper(tuneType);
aamp->ReleaseStreamLock();
}
aamp->ResumeDownloads();
if(retValue)
{
aamp->NotifySpeedChanged(aamp->rate);
}
aamp->mAutoResumeTaskPending = false;
return G_SOURCE_REMOVE;
}
/**
* @brief Idle task to process discontinuity
* @param ptr pointer to PrivateInstanceAAMP object
* @retval G_SOURCE_REMOVE
*/
static gboolean PrivateInstanceAAMP_ProcessDiscontinuity(gpointer ptr)
{
PrivateInstanceAAMP* aamp = (PrivateInstanceAAMP*) ptr;
GSource *src = g_main_current_source();
if (src == NULL || !g_source_is_destroyed(src))
{
bool ret = aamp->ProcessPendingDiscontinuity();
// This is to avoid calling cond signal, in case Stop() interrupts the ProcessPendingDiscontinuity
if (ret)
{
aamp->SyncBegin();
aamp->mDiscontinuityTuneOperationId = 0;
aamp->SyncEnd();
}
pthread_cond_signal(&aamp->mCondDiscontinuity);
}
return G_SOURCE_REMOVE;
}
/**
* @brief Tune again to currently viewing asset. Used for internal error handling
* @param ptr pointer to PrivateInstanceAAMP object
* @retval G_SOURCE_REMOVE
*/
static gboolean PrivateInstanceAAMP_Retune(gpointer ptr)
{
PrivateInstanceAAMP* aamp = (PrivateInstanceAAMP*) ptr;
bool activeAAMPFound = false;
bool reTune = false;
gActivePrivAAMP_t *gAAMPInstance = NULL;
pthread_mutex_lock(&gMutex);
for (std::list<gActivePrivAAMP_t>::iterator iter = gActivePrivAAMPs.begin(); iter != gActivePrivAAMPs.end(); iter++)
{
if (aamp == iter->pAAMP)
{
gAAMPInstance = &(*iter);
activeAAMPFound = true;
reTune = gAAMPInstance->reTune;
break;
}
}
if (!activeAAMPFound)
{
AAMPLOG_WARN("PrivateInstanceAAMP: %p not in Active AAMP list", aamp);
}
else if (!reTune)
{
AAMPLOG_WARN("PrivateInstanceAAMP: %p reTune flag not set", aamp);
}
else
{
if (aamp->pipeline_paused)
{
aamp->pipeline_paused = false;
}
aamp->mIsRetuneInProgress = true;
pthread_mutex_unlock(&gMutex);
aamp->AcquireStreamLock();
aamp->TuneHelper(eTUNETYPE_RETUNE);
aamp->ReleaseStreamLock();
pthread_mutex_lock(&gMutex);
aamp->mIsRetuneInProgress = false;
gAAMPInstance->reTune = false;
pthread_cond_signal(&gCond);
}
pthread_mutex_unlock(&gMutex);
return G_SOURCE_REMOVE;
}
/**
* @brief Simulate VOD asset as a "virtual linear" stream.
*/
static void SimulateLinearWindow( struct GrowableBuffer *buffer, const char *ptr, size_t len )
{
// Calculate elapsed time in seconds since virtual linear stream started
float cull = (aamp_GetCurrentTimeMS() - simulation_start)/1000.0;
buffer->len = 0; // Reset Growable Buffer length
float window = 20.0; // Virtual live window size; can be increased/decreasedint
const char *fin = ptr+len;
bool wroteHeader = false; // Internal state used to decide whether HLS playlist header has already been output
int seqNo = 0;
while (ptr < fin)
{
int count = 0;
char line[1024];
float fragmentDuration;
for(;;)
{
char c = *ptr++;
line[count++] = c;
if( ptr>=fin || c<' ' ) break;
}
line[count] = 0x00;
if (sscanf(line,"#EXTINF:%f",&fragmentDuration) == 1)
{
if (cull > 0)
{
cull -= fragmentDuration;
seqNo++;
continue; // Not yet in active window
}
if (!wroteHeader)
{
// Write a simple linear HLS header, without the type:VOD, and with dynamic media sequence number
wroteHeader = true;
char header[1024];
sprintf( header,
"#EXTM3U\n"
"#EXT-X-VERSION:3\n"
"#EXT-X-TARGETDURATION:2\n"
"#EXT-X-MEDIA-SEQUENCE:%d\n", seqNo );
aamp_AppendBytes(buffer, header, strlen(header) );
}
window -= fragmentDuration;
if (window < 0.0)
{
// Finished writing virtual linear window
break;
}
}
if (wroteHeader)
{
aamp_AppendBytes(buffer, line, count );
}
}
// Following can be used to debug
// aamp_AppendNulTerminator( buffer );
// printf( "Virtual Linear Playlist:\n%s\n***\n", buffer->ptr );
}
/**
* @brief Get the telemetry type for a media type
* @param type media type
* @retval telemetry type
*/
static MediaTypeTelemetry aamp_GetMediaTypeForTelemetry(MediaType type)
{
MediaTypeTelemetry ret;
switch(type)
{
case eMEDIATYPE_VIDEO:
case eMEDIATYPE_AUDIO:
case eMEDIATYPE_SUBTITLE:
case eMEDIATYPE_AUX_AUDIO:
case eMEDIATYPE_IFRAME:
ret = eMEDIATYPE_TELEMETRY_AVS;
break;
case eMEDIATYPE_MANIFEST:
case eMEDIATYPE_PLAYLIST_VIDEO:
case eMEDIATYPE_PLAYLIST_AUDIO:
case eMEDIATYPE_PLAYLIST_SUBTITLE:
case eMEDIATYPE_PLAYLIST_AUX_AUDIO:
case eMEDIATYPE_PLAYLIST_IFRAME:
ret = eMEDIATYPE_TELEMETRY_MANIFEST;
break;
case eMEDIATYPE_INIT_VIDEO:
case eMEDIATYPE_INIT_AUDIO:
case eMEDIATYPE_INIT_SUBTITLE:
case eMEDIATYPE_INIT_AUX_AUDIO:
case eMEDIATYPE_INIT_IFRAME:
ret = eMEDIATYPE_TELEMETRY_INIT;
break;
case eMEDIATYPE_LICENCE:
ret = eMEDIATYPE_TELEMETRY_DRM;
break;
default:
ret = eMEDIATYPE_TELEMETRY_UNKNOWN;
break;
}
return ret;
}
/**
* @brief de-fog playback URL to play directly from CDN instead of fog
* @param[in][out] dst Buffer containing URL
*/
static void DeFog(std::string& url)
{
std::string prefix("&recordedUrl=");
size_t startPos = url.find(prefix);
if( startPos != std::string::npos )
{
startPos += prefix.size();
size_t len = url.find( '&',startPos );
if( len != std::string::npos )
{
len -= startPos;
}
url = url.substr(startPos,len);
aamp_DecodeUrlParameter(url);
}
}
/**
* @brief replace all occurrences of existingSubStringToReplace in str with replacementString
* @param str string to be scanned/modified
* @param existingSubStringToReplace substring to be replaced
* @param replacementString string to be substituted
* @retval true iff str was modified
*/
static bool replace(std::string &str, const char *existingSubStringToReplace, const char *replacementString)
{
bool rc = false;
std::size_t fromPos = 0;
size_t existingSubStringToReplaceLen = 0;
size_t replacementStringLen = 0;
for(;;)
{
std::size_t pos = str.find(existingSubStringToReplace,fromPos);
if( pos == std::string::npos )
{ // done - pattern not found
break;
}
if( !rc )
{ // lazily meaasure input strings - no need to measure unless match found
rc = true;
existingSubStringToReplaceLen = strlen(existingSubStringToReplace);
replacementStringLen = strlen(replacementString);
}
str.replace( pos, existingSubStringToReplaceLen, replacementString );
fromPos = pos + replacementStringLen;
}
return rc;
}
// Helper functions for loading configuration (from file/TR181)
#ifdef IARM_MGR
/**
* @brief
* @param paramName
* @param iConfigLen
* @retval
*/
char * GetTR181AAMPConfig(const char * paramName, size_t & iConfigLen)
{
char * strConfig = NULL;
IARM_Result_t result;
HOSTIF_MsgData_t param;
memset(¶m,0,sizeof(param));
snprintf(param.paramName,TR69HOSTIFMGR_MAX_PARAM_LEN,"%s",paramName);
param.reqType = HOSTIF_GET;
result = IARM_Bus_Call(IARM_BUS_TR69HOSTIFMGR_NAME,IARM_BUS_TR69HOSTIFMGR_API_GetParams,
(void *)¶m, sizeof(param));
if(result == IARM_RESULT_SUCCESS)
{
if(fcNoFault == param.faultCode)
{
if(param.paramtype == hostIf_StringType && param.paramLen > 0 )
{
std::string strforLog(param.paramValue,param.paramLen);
iConfigLen = param.paramLen;
const char *src = (const char*)(param.paramValue);
strConfig = (char * ) base64_Decode(src,&iConfigLen);
AAMPLOG_WARN("GetTR181AAMPConfig: Got:%s En-Len:%d Dec-len:%d",strforLog.c_str(),param.paramLen,iConfigLen);
}
else
{
AAMPLOG_WARN("GetTR181AAMPConfig: Not a string param type=%d or Invalid len:%d ",param.paramtype, param.paramLen);
}
}
}
else
{
AAMPLOG_WARN("GetTR181AAMPConfig: Failed to retrieve value result=%d",result);
}
return strConfig;
}
/**
* @brief Active interface state change from netsrvmgr
* @param owner reference to net_srv_mgr
* @param IARM eventId received
* @data pointer reference to interface struct
*/
void getActiveInterfaceEventHandler (const char *owner, IARM_EventId_t eventId, void *data, size_t len)
{
if (strcmp (owner, "NET_SRV_MGR") != 0)
return;
IARM_BUS_NetSrvMgr_Iface_EventData_t *param = (IARM_BUS_NetSrvMgr_Iface_EventData_t *) data;
if (NULL == strstr (param->activeIface, previousInterface) || (strlen(previousInterface) == 0))
{
memset(previousInterface, 0, sizeof(previousInterface));
strncpy(previousInterface, param->activeIface, sizeof(previousInterface) - 1);
AAMPLOG_WARN("getActiveInterfaceEventHandler EventId %d activeinterface %s", eventId, param->activeIface);
}
if (NULL != strstr (param->activeIface, "wlan"))
{
activeInterfaceWifi = true;
}
else if (NULL != strstr (param->activeIface, "eth"))
{
activeInterfaceWifi = false;
}
}
#endif
/**
* @brief convert https to https in recordedUrl part of manifestUrl
* @param[in][out] dst Buffer containing URL
* @param[in]string - https
* @param[in]string - http
*/
void ForceHttpCoversionforFog(std::string& url,const std::string& from, const std::string& to)
{
std::string prefix("&recordedUrl=");
size_t startPos = url.find(prefix);
if( startPos != std::string::npos )
{
startPos += prefix.size();
url.replace(startPos, from.length(), to);
}
}
/**
* @brief Active streaming interface is wifi
*
* @return bool - true if wifi interface connected
*/
static bool IsActiveStreamingInterfaceWifi (void)
{
bool wifiStatus = false;
#ifdef IARM_MGR
IARM_Result_t ret = IARM_RESULT_SUCCESS;
IARM_BUS_NetSrvMgr_Iface_EventData_t param;
ret = IARM_Bus_Call("NET_SRV_MGR", "getActiveInterface", (void*)¶m, sizeof(param));
if (ret != IARM_RESULT_SUCCESS) {
AAMPLOG_ERR("NET_SRV_MGR getActiveInterface read failed : %d", ret);
}
else
{
AAMPLOG_WARN("NET_SRV_MGR getActiveInterface = %s", param.activeIface);
if (!strcmp(param.activeIface, "WIFI")){
wifiStatus = true;
}
}
IARM_Bus_RegisterEventHandler("NET_SRV_MGR", IARM_BUS_NETWORK_MANAGER_EVENT_INTERFACE_IPADDRESS, getActiveInterfaceEventHandler);
#endif
return wifiStatus;
}
/**
* @brief helper function to avoid dependency on unsafe sscanf while reading strings
* @param buf pointer to CString buffer to scan
* @param prefixPtr - prefix string to match in bufPtr
* @param valueCopyPtr receives allocated copy of string following prefix (skipping delimiting whitesace) if prefix found
* @retval 0 if prefix not present or error
* @retval 1 if string extracted/copied to valueCopyPtr
*/
static int ReadConfigStringHelper(std::string buf, const char *prefixPtr, const char **valueCopyPtr)
{
int ret = 0;
if (buf.find(prefixPtr) != std::string::npos)
{
std::size_t pos = strlen(prefixPtr);
if (*valueCopyPtr != NULL)
{
free((void *)*valueCopyPtr);
*valueCopyPtr = NULL;
}
*valueCopyPtr = strdup(buf.substr(pos).c_str());
if (*valueCopyPtr)
{
ret = 1;
}
}
return ret;
}
/**
* @brief helper function to extract numeric value from given buf after removing prefix
* @param buf String buffer to scan
* @param prefixPtr - prefix string to match in bufPtr
* @param value - receives numeric value after extraction
* @retval 0 if prefix not present or error
* @retval 1 if string converted to numeric value
*/
template<typename T>
static int ReadConfigNumericHelper(std::string buf, const char* prefixPtr, T& value)
{
int ret = 0;
try
{
std::size_t pos = buf.rfind(prefixPtr,0); // starts with check
if (pos != std::string::npos)
{
pos += strlen(prefixPtr);
std::string valStr = buf.substr(pos);
if (std::is_same<T, int>::value)
value = std::stoi(valStr);
else if (std::is_same<T, long>::value)
value = std::stol(valStr);
else if (std::is_same<T, float>::value)
value = std::stof(valStr);
else
value = std::stod(valStr);
ret = 1;
}
}
catch(exception& e)
{
// NOP
}
return ret;
}
// End of helper functions for loading configuration
static std::string getTimeStamp(time_t epochTime, const char* format = "%Y-%m-%dT%H:%M:%S.%f%Z")
{
char timestamp[64] = {0};
strftime(timestamp, sizeof(timestamp), format, localtime(&epochTime));
return timestamp;
}
static time_t convertTimeToEpoch(const char* theTime, const char* format = "%Y-%m-%dT%H:%M:%S.%f%Z")
{
std::tm tmTime;
memset(&tmTime, 0, sizeof(tmTime));
strptime(theTime, format, &tmTime);
return mktime(&tmTime);
}
// Curl callback functions
/**
* @brief write callback to be used by CURL
* @param ptr pointer to buffer containing the data
* @param size size of the buffer
* @param nmemb number of bytes
* @param userdata CurlCallbackContext pointer
* @retval size consumed or 0 if interrupted
*/
static size_t SyncTime_write_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
{
size_t ret = 0;
CurlCbContextSyncTime *context = (CurlCbContextSyncTime *)userdata;
pthread_mutex_lock(&context->aamp->mLock);
size_t numBytesForBlock = size*nmemb;
aamp_AppendBytes(context->buffer, ptr, numBytesForBlock);
ret = numBytesForBlock;
pthread_mutex_unlock(&context->aamp->mLock);
return ret;
}
/**
* @brief HandleSSLWriteCallback - Handle write callback from CURL
*/
size_t PrivateInstanceAAMP::HandleSSLWriteCallback ( char *ptr, size_t size, size_t nmemb, void* userdata )
{
size_t ret = 0;
CurlCallbackContext *context = (CurlCallbackContext *)userdata;
if(!context) return ret;
pthread_mutex_lock(&context->aamp->mLock);
if (context->aamp->mDownloadsEnabled)
{
if ((NULL == context->buffer->ptr) && (context->contentLength > 0))
{
size_t len = context->contentLength + 2;
/*Add 2 additional characters to take care of extra characters inserted by aamp_AppendNulTerminator*/
if(context->downloadIsEncoded && (len < DEFAULT_ENCODED_CONTENT_BUFFER_SIZE))
{
// Allocate a fixed buffer for encoded contents. Content length is not trusted here
len = DEFAULT_ENCODED_CONTENT_BUFFER_SIZE;
}
assert(!context->buffer->ptr);
context->buffer->ptr = (char *)g_malloc( len );
context->buffer->avail = len;
}
size_t numBytesForBlock = size*nmemb;
aamp_AppendBytes(context->buffer, ptr, numBytesForBlock);
ret = numBytesForBlock;
if(context->aamp->GetLLDashServiceData()->lowLatencyMode &&
(context->fileType == eMEDIATYPE_VIDEO ||
context->fileType == eMEDIATYPE_AUDIO ||
context->fileType == eMEDIATYPE_SUBTITLE))
{
MediaStreamContext *mCtx = context->aamp->GetMediaStreamContext(context->fileType);
if(mCtx)
{
mCtx->CacheFragmentChunk(context->fileType, ptr, numBytesForBlock,context->remoteUrl,context->downloadStartTime);
}
}
}
else
{
if(ISCONFIGSET_PRIV(eAAMPConfig_EnableCurlStore) && mOrigManifestUrl.isRemotehost)
{
ret = (size*nmemb);
}
else
{
AAMPLOG_WARN("CurlTrace write_callback - interrupted, ret:%d", ret);
}
}
pthread_mutex_unlock(&context->aamp->mLock);
return ret;
}
/**
* @brief write callback to be used by CURL
* @param ptr pointer to buffer containing the data
* @param size size of the buffer
* @param nmemb number of bytes
* @param userdata CurlCallbackContext pointer
* @retval size consumed or 0 if interrupted
*/
static size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
{
size_t ret = 0;
CurlCallbackContext *context = (CurlCallbackContext *)userdata;
if(!context) return ret;
ret = context->aamp->HandleSSLWriteCallback( ptr, size, nmemb, userdata);
return ret;
}
/**
* @brief function to print header response during download failure and latency.
* @param fileType current media type
*/
static void print_headerResponse(std::vector<std::string> &allResponseHeadersForErrorLogging, MediaType fileType)
{
if (gpGlobalConfig->logging.curlHeader && (eMEDIATYPE_VIDEO == fileType || eMEDIATYPE_PLAYLIST_VIDEO == fileType))
{
int size = allResponseHeadersForErrorLogging.size();
AAMPLOG_WARN("################ Start :: Print Header response ################");
for (int i=0; i < size; i++)
{
AAMPLOG_WARN("* %s", allResponseHeadersForErrorLogging.at(i).c_str());
}
AAMPLOG_WARN("################ End :: Print Header response ################");
}
allResponseHeadersForErrorLogging.clear();
}
/**
* @brief HandleSSLHeaderCallback - Hanlde header callback from SSL
*/
size_t PrivateInstanceAAMP::HandleSSLHeaderCallback ( const char *ptr, size_t size, size_t nmemb, void* user_data )
{
CurlCallbackContext *context = static_cast<CurlCallbackContext *>(user_data);
httpRespHeaderData *httpHeader = context->responseHeaderData;
size_t len = nmemb * size;
size_t startPos = 0;
size_t endPos = len-2; // strip CRLF
bool isBitrateHeader = false;
bool isFogRecordingIdHeader = false;
bool isProfileCapHeader = false;
if( len<2 || ptr[endPos] != '\r' || ptr[endPos+1] != '\n' )
{ // only proceed if this is a CRLF terminated curl header, as expected
return len;
}
if (context->aamp->mConfig->IsConfigSet(eAAMPConfig_CurlHeader) && ptr[0] &&
(eMEDIATYPE_VIDEO == context->fileType || eMEDIATYPE_PLAYLIST_VIDEO == context->fileType))
{
std::string temp = std::string(ptr,endPos);
context->allResponseHeadersForErrorLogging.push_back(temp);
}
// As per Hypertext Transfer Protocol ==> Field names are case-insensitive
// HTTP/1.1 4.2 Message Headers : Each header field consists of a name followed by a colon (":") and the field value. Field names are case-insensitive
if (STARTS_WITH_IGNORE_CASE(ptr, FOG_REASON_STRING))
{
httpHeader->type = eHTTPHEADERTYPE_FOG_REASON;
startPos = STRLEN_LITERAL(FOG_REASON_STRING);
}
else if (STARTS_WITH_IGNORE_CASE(ptr, CURLHEADER_X_REASON))
{
httpHeader->type = eHTTPHEADERTYPE_XREASON;
startPos = STRLEN_LITERAL(CURLHEADER_X_REASON);
}
else if (STARTS_WITH_IGNORE_CASE(ptr, BITRATE_HEADER_STRING))
{
startPos = STRLEN_LITERAL(BITRATE_HEADER_STRING);
isBitrateHeader = true;
}
else if (STARTS_WITH_IGNORE_CASE(ptr, SET_COOKIE_HEADER_STRING))
{
httpHeader->type = eHTTPHEADERTYPE_COOKIE;
startPos = STRLEN_LITERAL(SET_COOKIE_HEADER_STRING);
}
else if (STARTS_WITH_IGNORE_CASE(ptr, LOCATION_HEADER_STRING))
{
httpHeader->type = eHTTPHEADERTYPE_EFF_LOCATION;
startPos = STRLEN_LITERAL(LOCATION_HEADER_STRING);
}
else if (STARTS_WITH_IGNORE_CASE(ptr, FOG_RECORDING_ID_STRING))
{
startPos = STRLEN_LITERAL(FOG_RECORDING_ID_STRING);
isFogRecordingIdHeader = true;
}
else if (STARTS_WITH_IGNORE_CASE(ptr, CONTENT_ENCODING_STRING ))
{
// Enabled IsEncoded as Content-Encoding header is present
// The Content-Encoding entity header incidcates media is compressed
context->downloadIsEncoded = true;
}
else if (context->aamp->mConfig->IsConfigSet(eAAMPConfig_LimitResolution) && context->aamp->IsFirstRequestToFog() && STARTS_WITH_IGNORE_CASE(ptr, CAPPED_PROFILE_STRING ))
{
startPos = STRLEN_LITERAL(CAPPED_PROFILE_STRING);
isProfileCapHeader = true;
}
else if (STARTS_WITH_IGNORE_CASE(ptr, TRANSFER_ENCODING_STRING ))
{
context->chunkedDownload = true;
}
else if (0 == context->buffer->avail)
{
if (STARTS_WITH_IGNORE_CASE(ptr, CONTENTLENGTH_STRING))
{
int contentLengthStartPosition = STRLEN_LITERAL(CONTENTLENGTH_STRING);
const char * contentLengthStr = ptr + contentLengthStartPosition;
context->contentLength = atoi(contentLengthStr);
}
}
// Check for http header tags, only if event listener for HTTPResponseHeaderEvent is available
if (eMEDIATYPE_MANIFEST == context->fileType && context->aamp->IsEventListenerAvailable(AAMP_EVENT_HTTP_RESPONSE_HEADER))
{
std::vector<std::string> responseHeaders = context->aamp->responseHeaders;
if (responseHeaders.size() > 0)
{
for (int header=0; header < responseHeaders.size(); header++) {
std::string headerType = responseHeaders[header].c_str();
// check if subscribed header is available
if (0 == strncasecmp(ptr, headerType.c_str() , headerType.length()))
{
startPos = headerType.length();