Repository navigation
Expand file tree
/
Copy pathpriv_aamp.cpp
More file actions
9794 lines (9080 loc) · 293 KB
/
Copy pathpriv_aamp.cpp
File metadata and controls
9794 lines (9080 loc) · 293 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 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 "priv_aamp.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 "hdmiin_shim.h"
#include "compositein_shim.h"
#include "ota_shim.h"
#include "_base64.h"
#include "base16.h"
#include "aampgstplayer.h"
#include "AampDRMSessionManager.h"
#ifdef AAMP_RDK_CC_ENABLED
#include "AampRDKCCManager.h"
#endif
#ifdef USE_OPENCDM // AampOutputProtection is compiled when this flag is enabled
#include "aampoutputprotection.h"
#endif
#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>
#define LOCAL_HOST_IP "127.0.0.1"
#define AAMP_MAX_TIME_BW_UNDERFLOWS_TO_TRIGGER_RETUNE_MS (20*1000LL)
//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)) { \
logprintf("%s(): Parameter '%s' not within INTEGER limit. Using default value instead.", __FUNCTION__, param_name); \
param_value = default_value; \
}
#define VALIDATE_LONG(param_name, param_value, default_value) \
if ((param_value <= 0) || (param_value > LONG_MAX)) { \
logprintf("%s(): Parameter '%s' not within LONG INTEGER limit. Using default value instead.", __FUNCTION__, param_name); \
param_value = default_value; \
}
#define VALIDATE_DOUBLE(param_name, param_value, default_value) \
if ((param_value <= 0) || (param_value > DBL_MAX)) { \
logprintf("%s(): Parameter '%s' not within DOUBLE limit. Using default value instead.", __FUNCTION__, param_name); \
param_value = default_value; \
}
#define FOG_REASON_STRING "Fog-Reason:"
#define CURLHEADER_X_REASON "X-Reason:"
#define BITRATE_HEADER_STRING "X-Bitrate:"
#define CONTENTLENGTH_STRING "Content-Length:"
#define STRLEN_LITERAL(STRING) (sizeof(STRING)-1)
#define STARTS_WITH_IGNORE_CASE(STRING, PREFIX) (0 == strncasecmp(STRING, PREFIX, STRLEN_LITERAL(PREFIX)))
/**
* 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 pthread_mutex_t gCurlInitMutex = PTHREAD_MUTEX_INITIALIZER;
static int PLAYERID_CNTR = 0;
static const char* strAAMPPipeName = "/tmp/ipc_aamp";
static bool activeInterfaceWifi = false;
GlobalConfigAAMP *gpGlobalConfig;
/**
* @struct ChannelInfo
* @brief Holds information of a channel
*/
struct ChannelInfo
{
ChannelInfo() : name(), uri()
{
}
std::string name;
std::string uri;
};
static std::list<ChannelInfo> mChannelOverrideMap;
/**
* @struct CurlCallbackContext
* @brief context during curl callbacks
*/
struct CurlCallbackContext
{
PrivateInstanceAAMP *aamp;
MediaType fileType;
std::vector<std::string> allResponseHeadersForErrorLogging;
GrowableBuffer *buffer;
httpRespHeaderData *responseHeaderData;
long bitrate;
bool downloadIsEncoded;
CurlCallbackContext() : aamp(NULL), buffer(NULL), responseHeaderData(NULL),bitrate(0),downloadIsEncoded(false), fileType(eMEDIATYPE_DEFAULT), allResponseHeadersForErrorLogging{""}
{
}
~CurlCallbackContext() {}
CurlCallbackContext(const CurlCallbackContext &other) = delete;
CurlCallbackContext& operator=(const CurlCallbackContext& other) = delete;
};
/**
* @struct CurlProgressCbContext
* @brief context during curl progress callbacks
*/
struct CurlProgressCbContext
{
PrivateInstanceAAMP *aamp;
long long downloadStartTime;
long long downloadUpdatedTime;
long startTimeout;
long stallTimeout;
double downloadSize;
CurlAbortReason abortReason;
};
/**
* @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, 50, "AAMP: Unsupported Stream Type"}, //"Unable to determine stream type for DRM Init"
{AAMP_TUNE_UNSUPPORTED_AUDIO_TYPE, 50, "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_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 - 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]
/**
* @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
*/
static gboolean PrivateInstanceAAMP_Resume(gpointer ptr)
{
bool retValue = true;
PrivateInstanceAAMP* aamp = (PrivateInstanceAAMP* )ptr;
aamp->NotifyFirstBufferProcessed();
if (aamp->pipeline_paused)
{
if (aamp->rate == AAMP_NORMAL_PLAY_RATE)
{
retValue = aamp->mStreamSink->Pause(false, false);
aamp->pipeline_paused = false;
}
else
{
aamp->rate = AAMP_NORMAL_PLAY_RATE;
aamp->pipeline_paused = false;
aamp->TuneHelper(eTUNETYPE_SEEK);
}
aamp->ResumeDownloads();
if(retValue)
{
aamp->NotifySpeedChanged(aamp->rate);
}
}
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;
if (!g_source_is_destroyed(g_main_current_source()))
{
bool ret = aamp->ProcessPendingDiscontinuity();
// This is to avoid calling cond signal, in case Stop() interrupts the ProcessPendingDiscontinuity
if (ret)
{
aamp->SyncBegin();
aamp->mDiscontinuityTuneOperationId = 0;
pthread_cond_signal(&aamp->mCondDiscontinuity);
aamp->SyncEnd();
}
}
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)
{
logprintf("PrivateInstanceAAMP::%s : %p not in Active AAMP list", __FUNCTION__, aamp);
}
else if (!reTune)
{
logprintf("PrivateInstanceAAMP::%s : %p reTune flag not set", __FUNCTION__, aamp);
}
else
{
aamp->mIsRetuneInProgress = true;
pthread_mutex_unlock(&gMutex);
aamp->TuneHelper(eTUNETYPE_RETUNE);
pthread_mutex_lock(&gMutex);
aamp->mIsRetuneInProgress = false;
gAAMPInstance->reTune = false;
pthread_cond_signal(&gCond);
}
pthread_mutex_unlock(&gMutex);
return G_SOURCE_REMOVE;
}
/**
* @brief Function invoked at the end of idle task for freeing resources
* @param user_data pointer to AsyncEventDescriptor object
*/
static void AsyncEventDestroyNotify(gpointer user_data)
{
AsyncEventDescriptor* e = (AsyncEventDescriptor*)user_data;
delete e;
}
/**
* @brief Idle task for sending asynchronous event
* @param user_data pointer to AsyncEventDescriptor object
* @retval G_SOURCE_REMOVE
*/
static gboolean SendAsynchronousEvent(gpointer user_data)
{
//TODO protect mEventListener
AsyncEventDescriptor* e = (AsyncEventDescriptor*)user_data;
//Get current idle handler's id
guint callbackID = aamp_GetSourceID();
if (callbackID != 0)
{
e->aamp->SetCallbackAsDispatched(callbackID);
}
else
{
AAMPLOG_ERR("PrivateInstanceAAMP::%s:%d [type = %d] aamp_GetSourceID returned zero, which is unexpected behavior!", __FUNCTION__, __LINE__, e->event->getType());
}
e->aamp->SendEventSync(e->event);
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_IFRAME:
ret = eMEDIATYPE_TELEMETRY_AVS;
break;
case eMEDIATYPE_MANIFEST:
case eMEDIATYPE_PLAYLIST_VIDEO:
case eMEDIATYPE_PLAYLIST_AUDIO:
case eMEDIATYPE_PLAYLIST_SUBTITLE:
case eMEDIATYPE_PLAYLIST_IFRAME:
ret = eMEDIATYPE_TELEMETRY_MANIFEST;
break;
case eMEDIATYPE_INIT_VIDEO:
case eMEDIATYPE_INIT_AUDIO:
case eMEDIATYPE_INIT_SUBTITLE:
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 Check and replace if local overrides match manifest url
* @param mainManifestUrl manifest url
* @retval url to override or NULL
*/
static const char *RemapManifestUrl(const char *mainManifestUrl)
{
if (!mChannelOverrideMap.empty())
{
for (std::list<ChannelInfo>::iterator it = mChannelOverrideMap.begin(); it != mChannelOverrideMap.end(); ++it)
{
ChannelInfo &pChannelInfo = *it;
if (strstr(mainManifestUrl, pChannelInfo.name.c_str()))
{
logprintf("override!");
return pChannelInfo.uri.c_str();
}
}
}
return NULL;
}
/**
* @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 substitute given substring in str with the given string
* @param str String to be modified
* @param existingSubStringToReplace Substring to be replaced
* @param replacementString String to be substituted
* @retval
*/
static int replace(std::string &str, const char *existingSubStringToReplace, const char *replacementString)
{
//TODO: See if the replace in fragmentcollector_mpd can be replaced with this function
//CID:99836 - Removing the done variable wich is initialized but not used
int rc = 0;
std::size_t pos;
do
{
pos = str.find(existingSubStringToReplace);
if (pos != std::string::npos)
{
size_t charsToRemove = strlen(existingSubStringToReplace);
str.replace(pos, charsToRemove, replacementString);
rc = 1;
}
} while (pos != std::string::npos);
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);
logprintf("GetTR181AAMPConfig: Got:%s En-Len:%d Dec-len:%d",strforLog.c_str(),param.paramLen,iConfigLen);
}
else
{
logprintf("GetTR181AAMPConfig: Not a string param type=%d or Invalid len:%d ",param.paramtype, param.paramLen);
}
}
}
else
{
logprintf("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;
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 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
{
logprintf("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 bufPtr 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.find(prefixPtr);
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;
}
/**
* @brief Process config entries,i and update gpGlobalConfig params
* based on the config setting.
* @param cfg config to process
*/
static void ProcessConfigEntry(std::string cfg)
{
if (!cfg.empty() && cfg.at(0) != '#')
{ // ignore comments
//Removing unnecessary spaces and newlines
trim(cfg);
//CID:98018- Remove the seconds variable which is declared but not used
double inputTimeout;
int value;
char * tmpValue = NULL;
if(ReadConfigStringHelper(cfg, "map-mpd=", (const char**)&gpGlobalConfig->mapMPD))
{
logprintf("map-mpd=%s", gpGlobalConfig->mapMPD);
}
else if(ReadConfigStringHelper(cfg, "map-m3u8=", (const char**)&gpGlobalConfig->mapM3U8))
{
logprintf("map-m3u8=%s", gpGlobalConfig->mapM3U8);
}
else if (ReadConfigNumericHelper(cfg, "fragmp4-license-prefetch=", value) == 1)
{
gpGlobalConfig->fragmp4LicensePrefetch = (value != 0);
logprintf("fragmp4-license-prefetch=%d", gpGlobalConfig->fragmp4LicensePrefetch);
}
else if (ReadConfigNumericHelper(cfg, "fog-dash=", value) == 1)
{
gpGlobalConfig->fogSupportsDash = (value != 0);
logprintf("fog-dash=%d", value);
}
else if (ReadConfigNumericHelper(cfg, "enable_videoend_event=", value) == 1)
{
gpGlobalConfig->mEnableVideoEndEvent = (value==1);
logprintf("enable_videoend_event=%d", gpGlobalConfig->mEnableVideoEndEvent);
}
else if (ReadConfigNumericHelper(cfg, "fog=", value) == 1)
{
gpGlobalConfig->noFog = (value==0);
logprintf("fog=%d", value);
}
#ifdef AAMP_HARVEST_SUPPORT_ENABLED
else if (ReadConfigNumericHelper(cfg, "harvest=", gpGlobalConfig->harvest) == 1)
{
logprintf("harvest=%d", gpGlobalConfig->harvest);
}
else if (ReadConfigStringHelper(cfg, "harvestpath=", (const char**)&gpGlobalConfig->harvestpath))
{
logprintf("harvestpath=%s\n", gpGlobalConfig->harvestpath);
}
#endif
else if (ReadConfigNumericHelper(cfg, "forceEC3=", value) == 1)
{
gpGlobalConfig->forceEC3 = (TriState)(value != 0);
logprintf("forceEC3=%d", value);
}
else if (ReadConfigNumericHelper(cfg, "disableEC3=", value) == 1)
{
gpGlobalConfig->disableEC3 = (TriState)(value != 0);
logprintf("disableEC3=%d", value);
}
else if (ReadConfigNumericHelper(cfg, "disableATMOS=", value) == 1)
{
gpGlobalConfig->disableATMOS = (TriState)(value != 0);
logprintf("disableATMOS=%d", value);
}
else if (ReadConfigNumericHelper(cfg, "cdvrlive-offset=", gpGlobalConfig->cdvrliveOffset) == 1)
{
VALIDATE_INT("cdvrlive-offset", gpGlobalConfig->cdvrliveOffset, AAMP_CDVR_LIVE_OFFSET)
logprintf("cdvrlive-offset=%d", gpGlobalConfig->cdvrliveOffset);
}
else if (ReadConfigNumericHelper(cfg, "live-offset=", gpGlobalConfig->liveOffset) == 1)
{
VALIDATE_INT("live-offset", gpGlobalConfig->liveOffset, AAMP_LIVE_OFFSET)
logprintf("live-offset=%d", gpGlobalConfig->liveOffset);
}
else if (ReadConfigNumericHelper(cfg, "disablePlaylistIndexEvent=", gpGlobalConfig->disablePlaylistIndexEvent) == 1)
{
logprintf("disablePlaylistIndexEvent=%d", gpGlobalConfig->disablePlaylistIndexEvent);
}
else if (cfg.compare("enableSubscribedTags") == 0)
{
gpGlobalConfig->enableSubscribedTags = true;
logprintf("enableSubscribedTags set");
}
else if (cfg.compare("disableSubscribedTags") == 0)
{
gpGlobalConfig->enableSubscribedTags = false;
logprintf("disableSubscribedTags set");
}
else if (ReadConfigNumericHelper(cfg, "enableSubscribedTags=", gpGlobalConfig->enableSubscribedTags) == 1)
{
logprintf("enableSubscribedTags=%d", gpGlobalConfig->enableSubscribedTags);
}
else if (ReadConfigNumericHelper(cfg, "networkTimeout=", inputTimeout) == 1)
{
VALIDATE_DOUBLE("networkTimeout", inputTimeout, CURL_FRAGMENT_DL_TIMEOUT)
gpGlobalConfig->networkTimeoutMs = (long)CONVERT_SEC_TO_MS(inputTimeout);
logprintf("networkTimeout=%ld", gpGlobalConfig->networkTimeoutMs);
}
else if (ReadConfigNumericHelper(cfg, "manifestTimeout=", inputTimeout) == 1)
{
VALIDATE_DOUBLE("manifestTimeout", inputTimeout, CURL_FRAGMENT_DL_TIMEOUT)
gpGlobalConfig->manifestTimeoutMs = (long)CONVERT_SEC_TO_MS(inputTimeout);
logprintf("manifestTimeout=%ld ms", gpGlobalConfig->manifestTimeoutMs);
}
else if (ReadConfigNumericHelper(cfg, "playlistTimeout=", inputTimeout) == 1)
{
VALIDATE_DOUBLE("playlist", inputTimeout, CURL_FRAGMENT_DL_TIMEOUT)
gpGlobalConfig->playlistTimeoutMs = (long)CONVERT_SEC_TO_MS(inputTimeout);
logprintf("playlistTimeout=%ld ms", gpGlobalConfig->playlistTimeoutMs);
}
else if (cfg.compare("dash-ignore-base-url-if-slash") == 0)
{
gpGlobalConfig->dashIgnoreBaseURLIfSlash = true;
logprintf("dash-ignore-base-url-if-slash set");
}
else if (cfg.compare("license-anonymous-request") == 0)
{
gpGlobalConfig->licenseAnonymousRequest = true;
logprintf("license-anonymous-request set");
}
else if (cfg.compare("useLinearSimulator") == 0)
{
gpGlobalConfig->useLinearSimulator = true;
logprintf("useLinearSimulator set");
}
else if ((cfg.compare("info") == 0) && (!gpGlobalConfig->logging.debug))
{
gpGlobalConfig->logging.setLogLevel(eLOGLEVEL_INFO);
gpGlobalConfig->logging.info = true;
logprintf("info logging %s", gpGlobalConfig->logging.info ? "on" : "off");
}
else if (cfg.compare("failover") == 0)
{
gpGlobalConfig->logging.failover = true;
logprintf("failover logging %s", gpGlobalConfig->logging.failover ? "on" : "off");
}
else if (cfg.compare("curlHeader") == 0)
{
gpGlobalConfig->logging.curlHeader = true;
logprintf("curlHeader logging %s", gpGlobalConfig->logging.curlHeader ? "on" : "off");
}
else if(cfg.compare("logMetadata") == 0)
{
gpGlobalConfig->logging.logMetadata = true;
logprintf("logMetadata logging %s", gpGlobalConfig->logging.logMetadata ? "on" : "off");
}
else if (ReadConfigStringHelper(cfg, "customHeader=", (const char**)&tmpValue))
{
if (tmpValue)
{
gpGlobalConfig->customHeaderStr.push_back(tmpValue);
logprintf("customHeader = %s", tmpValue);
free(tmpValue);
tmpValue = NULL;
}
}
else if (ReadConfigStringHelper(cfg, "uriParameter=", (const char**)&gpGlobalConfig->uriParameter))
{
logprintf("uriParameter = %s", gpGlobalConfig->uriParameter);
}
else if (cfg.compare("gst") == 0)
{
gpGlobalConfig->logging.gst = !gpGlobalConfig->logging.gst;
logprintf("gst logging %s", gpGlobalConfig->logging.gst ? "on" : "off");
}
else if (cfg.compare("progress") == 0)
{
gpGlobalConfig->logging.progress = !gpGlobalConfig->logging.progress;
logprintf("progress logging %s", gpGlobalConfig->logging.progress ? "on" : "off");
}
else if (cfg.compare("debug") == 0)
{
gpGlobalConfig->logging.info = false;
gpGlobalConfig->logging.setLogLevel(eLOGLEVEL_TRACE);
gpGlobalConfig->logging.debug = true;
logprintf("debug logging %s", gpGlobalConfig->logging.debug ? "on" : "off");
}
else if (cfg.compare("trace") == 0)
{
gpGlobalConfig->logging.trace = !gpGlobalConfig->logging.trace;
logprintf("trace logging %s", gpGlobalConfig->logging.trace ? "on" : "off");
}
else if (cfg.compare("curl") == 0)
{
gpGlobalConfig->logging.curl = !gpGlobalConfig->logging.curl;
logprintf("curl logging %s", gpGlobalConfig->logging.curl ? "on" : "off");
}
else if (ReadConfigNumericHelper(cfg, "default-bitrate=", gpGlobalConfig->defaultBitrate) == 1)
{
VALIDATE_LONG("default-bitrate",gpGlobalConfig->defaultBitrate, DEFAULT_INIT_BITRATE)
logprintf("aamp default-bitrate: %ld", gpGlobalConfig->defaultBitrate);
}
else if (ReadConfigNumericHelper(cfg, "default-bitrate-4k=", gpGlobalConfig->defaultBitrate4K) == 1)
{
VALIDATE_LONG("default-bitrate-4k", gpGlobalConfig->defaultBitrate4K, DEFAULT_INIT_BITRATE_4K)
logprintf("aamp default-bitrate-4k: %ld", gpGlobalConfig->defaultBitrate4K);
}
else if (cfg.compare("abr") == 0)
{
gpGlobalConfig->bEnableABR = !gpGlobalConfig->bEnableABR;
logprintf("abr %s", gpGlobalConfig->bEnableABR ? "on" : "off");
}
else if (ReadConfigNumericHelper(cfg, "abr-cache-life=", gpGlobalConfig->abrCacheLife) == 1)
{
gpGlobalConfig->abrCacheLife *= 1000;
logprintf("aamp abr cache lifetime: %ldmsec", gpGlobalConfig->abrCacheLife);
}
else if (ReadConfigNumericHelper(cfg, "abr-cache-length=", gpGlobalConfig->abrCacheLength) == 1)
{