-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathpriv_aamp.cpp
More file actions
15030 lines (13892 loc) · 473 KB
/
priv_aamp.cpp
File metadata and controls
15030 lines (13892 loc) · 473 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 "isobmffprocessor.h"
#include "priv_aamp.h"
#include "AampJsonObject.h"
#include "isobmffbuffer.h"
#include "AampConstants.h"
#include "AampCacheHandler.h"
#include "AampUtils.h"
#include "PlayerExternalsInterface.h"
#include "iso639map.h"
#include "fragmentcollector_mpd.h"
#include "admanager_mpd.h"
#include "fragmentcollector_hls.h"
#include "fragmentcollector_progressive.h"
#include "MediaStreamContext.h"
#include "AampLatencyMonitor.h"
#ifdef AAMP_NET_TRACE
#include "net_trace.h" // header-only, provides aamptrace::NetTrace and now_monotonic_s()
/**
* @brief Network trace burst detection threshold (seconds)
*
* Purpose: Minimum idle time in curl write callbacks to trigger burst splitting.
* Value of 5ms chosen to distinguish network-level bursts from application buffering.
* Bursts separated by gaps exceeding this threshold are recorded as separate entries.
*/
static constexpr double kNetTraceBurstGapThresholdS = 0.005; // 5 milliseconds
/**
* @brief Network trace late gap threshold (seconds)
*
* Purpose: Gaps exceeding this threshold mark bursts as "late" for QoS analysis.
* Value of 120ms chosen to identify bursts delayed beyond typical buffering jitter.
* Late bursts indicate potential network congestion or server-side delays.
*/
static constexpr double kNetTraceLateGapThresholdS = 0.120; // 120 milliseconds
#endif
#include "hdmiin_shim.h"
#include "compositein_shim.h"
#include "ota_shim.h"
#include "rmf_shim.h"
#include "_base64.h"
#include "base16.h"
#include "aampgstplayer.h"
#include "AampStreamSinkManager.h"
#include "SubtecFactory.hpp"
#include "AampGrowableBuffer.h"
#include "PlayerCCManager.h"
#include "AampDRMLicPreFetcher.h"
#include "AampDRMLicManager.h"
#ifdef AAMP_TELEMETRY_SUPPORT
#include <AampTelemetry2.hpp>
#endif //AAMP_TELEMETRY_SUPPORT
#include "ID3Metadata.hpp"
#include "AampSegmentInfo.hpp"
#include "AampCurlStore.h"
#include <iomanip>
#include <unordered_set>
#include <mutex>
#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 <cstring>
#include "AampCurlDownloader.h"
#include "AampMPDDownloader.h"
#include <sched.h>
#include "AampTSBSessionManager.h"
#include "SocUtils.h"
#include "AuthTokenErrors.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 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 BYTES_PER_MS_TO_BITS_PER_SEC 8000.0 // (bits per byte) * (1000 ms per sec)
/**
* @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 std::mutex gMutex;
static std::condition_variable gCond;
static int PLAYERID_CNTR = 0;
static const char* strAAMPPipeName = "/tmp/ipc_aamp";
static bool activeInterfaceWifi = false;
std::shared_ptr<PlayerExternalsInterface> pPlayerExternalsInterface = NULL;
static unsigned int ui32CurlTrace = 0;
/**
* @struct TuneFailureMap
* @brief Structure holding aamp tune failure code and corresponding application error code and description
*/
struct TuneFailureMap
{
AAMPTuneFailure tuneFailure; /**< Failure ID */
int code; /**< Major Error code */
int subCode; /**< Minor Error code */
const char* description; /**< Textual description */
};
static TuneFailureMap tuneFailureMap[] =
{
//Init failure
{AAMP_TUNE_INIT_FAILED, 10, 1, "AAMP: init failed"}, //"Fragmentcollector initialization failed"
{AAMP_TUNE_INIT_FAILED_MANIFEST_DNLD_ERROR, 10, 2, "AAMP: init failed (unable to download manifest)"},
{AAMP_TUNE_INIT_FAILED_MANIFEST_CONTENT_ERROR, 10, 3, "AAMP: init failed (manifest missing tracks)"},
{AAMP_TUNE_INIT_FAILED_MANIFEST_PARSE_ERROR, 10, 4, "AAMP: init failed (corrupt/invalid manifest)"},
{AAMP_TUNE_INIT_FAILED_PLAYLIST_VIDEO_DNLD_ERROR, 10, 5, "AAMP: init failed (unable to download video playlist)"},
{AAMP_TUNE_INIT_FAILED_PLAYLIST_AUDIO_DNLD_ERROR, 10, 6, "AAMP: init failed (unable to download audio playlist)"},
{AAMP_TUNE_INIT_FAILED_TRACK_SYNC_ERROR, 10, 7, "AAMP: init failed (unsynchronized tracks)"},
//Resource failure
{AAMP_TUNE_CONTENT_NOT_FOUND, 20, 1, "AAMP: Resource was not found at the URL(HTTP 404)"},
//Download failure
{AAMP_TUNE_MANIFEST_REQ_FAILED, 30, 1, "AAMP: Manifest Download failed"}, //"Playlist refresh failed"
{AAMP_TUNE_FRAGMENT_DOWNLOAD_FAILURE, 30, 2, "AAMP: fragment download failures"},
{AAMP_TUNE_INIT_FRAGMENT_DOWNLOAD_FAILURE, 30, 3, "AAMP: init fragment download failed"},
{AAMP_TUNE_INVALID_MANIFEST_FAILURE, 30, 4, "AAMP: Invalid Manifest, parse failed"},
{AAMP_TUNE_MP4_INIT_FRAGMENT_MISSING, 30, 5, "AAMP: init fragments missing in playlist"},
{AAMP_TUNE_DNS_RESOLVE_TIMEOUT, 30, 6, "AAMP: Manifest download failed due to DNS resolve timeout"},
{AAMP_TUNE_CURL_CONNECTION_TIMEOUT, 30, 7, "AAMP: Manifest download failed due to connection timeout"},
{AAMP_TUNE_DATA_TRANSFER_TIMEOUT, 30, 8, "AAMP: Manifest download failed due to data transfer timeout"},
//Authorization failure
{AAMP_TUNE_AUTHORIZATION_FAILURE, 40, 1, "AAMP: Authorization failure"},
//DRM Failure
{AAMP_TUNE_UNTRACKED_DRM_ERROR, 50, 1, "AAMP: DRM error untracked error"},
{AAMP_TUNE_DRM_INIT_FAILED, 50, 2, "AAMP: DRM Initialization Failed"},
{AAMP_TUNE_DRM_DATA_BIND_FAILED, 50, 3, "AAMP: InitData-DRM Binding Failed"},
{AAMP_TUNE_DRM_SESSIONID_EMPTY, 50, 4, "AAMP: DRM Session ID Empty"},
{AAMP_TUNE_DRM_CHALLENGE_FAILED, 50, 5, "AAMP: DRM License Challenge Generation Failed"},
{AAMP_TUNE_LICENCE_TIMEOUT, 50, 6, "AAMP: DRM License Request Timed out"},
{AAMP_TUNE_LICENCE_REQUEST_FAILED, 50, 7, "AAMP: DRM License Request Failed"},
{AAMP_TUNE_INVALID_DRM_KEY, 50, 8, "AAMP: Invalid Key Error, from DRM"},
{AAMP_TUNE_FAILED_TO_GET_KEYID, 50, 9, "AAMP: Failed to parse key id from PSSH"},
{AAMP_TUNE_CORRUPT_DRM_DATA, 50, 10, "AAMP: DRM failure due to Corrupt DRM files"},
{AAMP_TUNE_CORRUPT_DRM_METADATA, 50, 11, "AAMP: DRM failure due to Bad DRMMetadata in stream"},
{AAMP_TUNE_DRM_DECRYPT_FAILED, 50, 12, "AAMP: DRM Decryption Failed for Fragments"},
{AAMP_TUNE_DRM_UNSUPPORTED, 50, 13, "AAMP: DRM format Unsupported"},
{AAMP_TUNE_DRM_SELF_ABORT, 50, 14, "AAMP: DRM license request aborted by player"},
{AAMP_TUNE_FAILED_TO_GET_ACCESS_TOKEN, 50, 15, "AAMP: Failed to get access token from Auth Service"},
{AAMP_TUNE_DRM_KEY_UPDATE_FAILED, 50, 16, "AAMP: Failed to process DRM key"},
{AAMP_TUNE_DRM_SESSION_CREATE_FAILED, 50, 17, "AAMP: OCDM session construction failed"},
//Provisioning failure
{AAMP_TUNE_DEVICE_NOT_PROVISIONED, 51, 1, "AAMP: Device not provisioned"},
//Hdcp failure
{AAMP_TUNE_HDCP_COMPLIANCE_ERROR, 52, 1, "AAMP: HDCP Compliance Check Failure"},
//Stream failure
{AAMP_TUNE_UNSUPPORTED_STREAM_TYPE, 60, 1, "AAMP: Unsupported Stream Type"}, //"Unable to determine stream type for DRM Init"
{AAMP_TUNE_UNSUPPORTED_AUDIO_TYPE, 60, 2, "AAMP: No supported Audio Types in Manifest"},
//Gstreamer error
{AAMP_TUNE_GST_PIPELINE_ERROR, 80, 1, "AAMP: Error from gstreamer pipeline"},
{AAMP_TUNE_FAILED_PTS_ERROR, 80, 2, "AAMP: Playback failed due to PTS error"},
//Playback failure
{AAMP_TUNE_PLAYBACK_STALLED, 7600, 1, "AAMP: Playback was stalled due to lack of new fragments"},
//Unknown failure
{AAMP_TUNE_FAILURE_UNKNOWN, 100, 1, "AAMP: Unknown Failure"}
};
static const std::pair<std::string , std::string> gCDAIErrorDetails[] = {
{"1051-2", "A configuration issue prevents player from handling ads"},
{"1051-6", "An ad was unplayable due to invalid manifest/playlist formatting."},
{"1051-7", "An ad was unplayable due to invalid media."},
{"1051-8", "An ad was unplayable due to the content being out of spec and unInsertable."},
{"1051-11", "The ad decisioning service took too long to respond."},
{"1051-12", "The ad delivery service took too long to respond."},
{"1051-13", "The ad delivery service returned a HTTP error."},
{"1051-14", "The ad delivery service returned a error."},
{"1051-15", "An unknown error occurred when trying to insert an ad."},
{"", ""}
};
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;
TuneType tuneType = eTUNETYPE_SEEK;
StreamSink *sink = AampStreamSinkManager::GetInstance().GetStreamSink(aamp);
aamp->NotifyFirstBufferProcessed(sink ? sink->GetVideoRectangle() : std::string());
if (!aamp->mSeekFromPausedState && (aamp->rate == AAMP_NORMAL_PLAY_RATE) && !aamp->IsLocalAAMPTsb())
{
if(sink)
{
retValue = sink->Pause(false, false);
}
aamp->mSinkPaused = 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->mSinkPaused = false;
aamp->mSeekFromPausedState = false;
{
std::lock_guard<std::recursive_mutex> lock(aamp->GetStreamLock());
aamp->TuneHelper(tuneType);
}
}
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();
}
aamp->mCondDiscontinuity.notify_one();
}
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;
std::unique_lock<std::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->mSinkPaused.load())
{
aamp->mSinkPaused.store(false);
}
aamp->mIsRetuneInProgress = true;
lock.unlock();
{
std::lock_guard<std::recursive_mutex> streamLock(aamp->GetStreamLock());
aamp->TuneHelper(eTUNETYPE_RETUNE);
}
lock.lock();
aamp->mIsRetuneInProgress = false;
gAAMPInstance->reTune = false;
gCond.notify_one();
}
return G_SOURCE_REMOVE;
}
/**
* @brief Get the telemetry type for a media type
* @param type media type
* @retval telemetry type
*/
static MediaTypeTelemetry aamp_GetMediaTypeForTelemetry(AampMediaType 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;
}
double PrivateInstanceAAMP::RecalculatePTS(AampMediaType mediaType, const void *ptr, size_t len )
{
double ret = 0;
uint32_t timeScale = 0;
switch( mediaType )
{
case eMEDIATYPE_VIDEO:
timeScale = GetVidTimeScale();
break;
case eMEDIATYPE_AUDIO:
timeScale = GetAudTimeScale();
break;
case eMEDIATYPE_SUBTITLE:
timeScale = GetSubTimeScale();
break;
default:
AAMPLOG_WARN("Invalid media type %d", mediaType);
break;
}
IsoBmffBuffer isobuf;
isobuf.setBuffer((uint8_t *)ptr, len);
bool bParse = false;
try
{
bParse = isobuf.parseBuffer();
}
catch( std::bad_alloc& ba)
{
AAMPLOG_ERR("Bad allocation: %s", ba.what() );
}
catch( std::exception &e)
{
AAMPLOG_ERR("Unhandled exception: %s", e.what() );
}
catch( ... )
{
AAMPLOG_ERR("Unknown exception");
}
if(bParse && (0 != timeScale))
{
uint64_t fPts = 0;
bool bParse = isobuf.getFirstPTS(fPts);
if (bParse)
{
ret = fPts/(timeScale*1.0);
}
}
return ret;
}
/**
* @brief Updates a vector of CCTrackInfo objects with data from a vector of TextTrackInfo objects.
*
* This function clears the provided `updatedTextTracks` vector and populates it with
* CCTrackInfo objects created from the data in the `textTracksCopy` vector.
*
* @param[in] textTracksCopy A vector of TextTrackInfo objects to be processed.
* @param[out] updatedTextTracks A vector of CCTrackInfo objects to be updated with the processed data.
*/
void PrivateInstanceAAMP::UpdateCCTrackInfo(const std::vector<TextTrackInfo>& textTracksCopy, std::vector<CCTrackInfo>& updatedTextTracks)
{
updatedTextTracks.clear(); // Clear the vector to ensure no stale data remains.
for (const auto& track : textTracksCopy)
{
CCTrackInfo ccTrack;
ccTrack.language = track.language;
ccTrack.instreamId = track.instreamId;
updatedTextTracks.push_back(std::move(ccTrack));
}
}
/**
* @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 measure 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;
}
void PrivateInstanceAAMP::UpdatePersistBandwidth(BitsPerSecond bandwidth)
{
// Store the PersistBandwidth and UpdatedTime on ABRManager.
// Bitrate update only for foreground player.
if (!(
ISCONFIGSET_PRIV(eAAMPConfig_PersistLowNetworkBandwidth) ||
ISCONFIGSET_PRIV(eAAMPConfig_PersistHighNetworkBandwidth)))
{
return;
}
if (bandwidth <= 0 || !mbPlayEnabled)
{
return;
}
ABRManager::setPersistBandwidth(bandwidth);
ABRManager::mPersistBandwidthUpdatedTime = aamp_GetCurrentTimeMS();
}
/**
* @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 ForceHttpConversionForFog(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;
wifiStatus = pPlayerExternalsInterface->GetActiveInterface();
activeInterfaceWifi = wifiStatus;
return wifiStatus;
}
/**
* @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;
}
/**
* @brief Identify mp4 chunk boundary in buffer
* @param[in] type - media type
* @param[in] buffer - buffer to scan
* @param[in] bufferOffset - offset in buffer to start scanning from
* @param[out] chunkBoundaryOffset - offset of chunk boundary if found
* @param[out] chunkDurationInTicks - duration of chunk if boundary found
* @retval true if chunk boundary found
*/
static bool IdentifyMp4ChunkBoundary(AampMediaType type, std::vector<uint8_t> &buffer, size_t bufferOffset, size_t &chunkBoundaryOffset, uint64_t &chunkDurationInTicks)
{
bool found = false;
chunkBoundaryOffset = 0;
chunkDurationInTicks = 0;
IsoBmffBuffer isobmffBuffer;
isobmffBuffer.setBuffer(buffer.data() + bufferOffset, buffer.size() - bufferOffset);
try
{
if (isobmffBuffer.parseBuffer(false))
{
// Check for 'mdat' box which indicates the end of mp4 chunk
// Specified in the ISO Base Media File Format (ISO/IEC 14496-12) specification that in fragmented MP4 files,
// a moof (Movie Fragment) box precedes the corresponding mdat (Media Data) box
size_t mdatCount = 0;
size_t mdatStart = 0;
size_t mdatSize = 0;
// Get number of mdat boxes
if (isobmffBuffer.getMdatBoxCount(mdatCount) && mdatCount > 0)
{
// Get the last mdat box info
if (isobmffBuffer.getMdatBoxInfo(mdatCount - 1, mdatStart, mdatSize))
{
AAMPLOG_DEBUG("[%d] MDAT box count=%zu and start=%zu , size=%zu", type, mdatCount, mdatStart, mdatSize);
}
else
{
// Not expected
AAMPLOG_WARN("[%d] Failed to get MDAT box info for index=%zu (count=%zu)", type, mdatCount - 1, mdatCount);
}
}
else if (isobmffBuffer.getChunkedMdatBoxInfo(mdatStart, mdatSize))
{
AAMPLOG_DEBUG("[%d] Chunked MDAT box found start=%zu, size=%zu", type, mdatStart, mdatSize);
}
// start could be 0 if mdat is the first box in buffer
if (mdatSize > 0)
{
// Calculate chunk boundary offset
chunkBoundaryOffset = bufferOffset + mdatStart + mdatSize;
found = true;
// Get the index of last MDAT box w.r.t to the full mp4 box. MDAT should be preceded by a MOOF.
// This is expected by the getTotalChunkDurationInTicks API.
int mdatIndex = isobmffBuffer.getLastMdatBoxIndex();
if (mdatIndex > 0)
{
chunkDurationInTicks = isobmffBuffer.getTotalChunkDurationInTicks(mdatIndex);
}
}
}
}
catch (std::bad_alloc& ba)
{
AAMPLOG_ERR("Bad allocation: %s", ba.what());
}
catch (std::exception& e)
{
AAMPLOG_ERR("Unhandled exception: %s", e.what());
}
return found;
}
// End of helper functions for loading configuration
static const char *ChunkedTransferStateToName( ChunkedTransferState state )
{
const char *stateName = NULL;
switch( state )
{
case ChunkedTransferState::READING_CHUNK_SIZE:
stateName = "reading chunk size";
break;
case ChunkedTransferState::PENDING_CHUNK_START_LF:
stateName = "awaiting start LF";
break;
case ChunkedTransferState::READING_CHUNK_DATA:
stateName = "reading chunk data";
break;
case ChunkedTransferState::PENDING_CHUNK_END_CR:
stateName = "awaiting end CR";
break;
case ChunkedTransferState::PENDING_CHUNK_END_LF:
stateName = "awaiting end LF";
break;
case ChunkedTransferState::READING_EXTENSIONS:
stateName = "awaiting extension end CR";
break;
case ChunkedTransferState::PENDING_EXTENSION_END_LF:
stateName = "awaiting extension end LF";
break;
case ChunkedTransferState::DONE:
stateName = "done";
break;
case ChunkedTransferState::ERROR:
stateName = "error";
break;
}
return stateName;
}
/**
* @brief cURL write callback that parses HTTP/1.1 chunked transfer-encoded data.
*
* This callback is invoked by the downloader whenever a new block of bytes is
* received for a request that uses HTTP/1.1 chunked transfer encoding. It
* implements an incremental parser driven by a state machine stored in
* CurlCallbackContext::m_ChunkedTransferState. The parser consumes the input buffer,
* interpreting chunk-size lines, chunk payload, and the required CR/LF
* delimiters as defined by the HTTP/1.1 Chunked Transfer Protocol.
*
* The state machine transitions between:
* - READING_CHUNK_SIZE: parse the hexadecimal chunk size from the stream.
* - PENDING_CHUNK_START_LF: wait for the LF that terminates the chunk-size line.
* - READING_CHUNK_DATA: consume exactly the announced number of data bytes for the current chunk and deliver them to the underlying consumer.
* - PENDING_CHUNK_END_CR: wait for the CR after a chunk's payload.
* - PENDING_CHUNK_END_LF: wait for the LF that completes the CRLF sequence after a chunk.
*
* The function may be called multiple times with partial chunk boundaries; it
* maintains parsing progress across invocations via the transfer-state fields
* in the provided context.
*
* @param[in] ptr Pointer to the buffer containing newly received data.
* @param[in] numBytes Number of valid bytes available in @p ptr.
* @param[in] userdata Pointer to the CurlCallbackContext or user data
* associated with this transfer, used to track the
* current chunked-transfer parsing state.
*/
void PrivateInstanceAAMP::chunked_write_callback(const char *ptr, size_t numBytes, void *userdata)
{ // HTTP/1.1 Chunked Transfer Protocol
CurlCallbackContext *context = static_cast<CurlCallbackContext *>(userdata);
if (context == nullptr)
{
AAMPLOG_ERR("chunked_write_callback called with null context");
return;
}
// note - caller has context->aamp->mLock
const char *fin = &ptr[numBytes];
while( ptr<fin )
{
AAMPLOG_INFO( "%s (%s) remaining=%zu",
GetMediaTypeName(context->mediaType),
ChunkedTransferStateToName(context->m_ChunkedTransferState),
context->m_ChunkedBytesRemaining );
switch( context->m_ChunkedTransferState )
{
case ChunkedTransferState::READING_EXTENSIONS:
{
char c = *ptr++;
if( c == '\r' )
{
context->m_ChunkedTransferState = ChunkedTransferState::PENDING_EXTENSION_END_LF;
}
}
break;
case ChunkedTransferState::PENDING_EXTENSION_END_LF:
if( *ptr++ != '\n' )
{
AAMPLOG_ERR( "missing expected \\n" );
context->m_ChunkedTransferState = ChunkedTransferState::ERROR;
}
else
{
context->m_ChunkedTransferState = ChunkedTransferState::READING_CHUNK_DATA;
}
break;
case ChunkedTransferState::READING_CHUNK_SIZE:
{
char code = *ptr++;
if( code == '\r' )
{
context->m_ChunkedTransferState = ChunkedTransferState::PENDING_CHUNK_START_LF;
}
else if( code == ';' )
{
// RFC 7230 allows optional chunk extensions after the size, starting with ';'.
// we currently skip over them rather than interpret them
context->m_ChunkedTransferState = ChunkedTransferState::READING_EXTENSIONS;
}
else
{
int digit = hexCharToInt(code);
if( digit<0 )
{
AAMPLOG_ERR( "unexpected digit: 0x%02x", code );
context->m_ChunkedTransferState = ChunkedTransferState::ERROR;
}
else
{
context->m_ChunkedBytesRemaining = context->m_ChunkedBytesRemaining*16 + digit;
}
}
}
break;
case ChunkedTransferState::PENDING_CHUNK_START_LF:
if( *ptr++ != '\n' )
{
AAMPLOG_ERR( "missing expected \\n" );
context->m_ChunkedTransferState = ChunkedTransferState::ERROR;
}
else
{
if( context->m_ChunkedBytesRemaining )
{
AAMPLOG_INFO( "CHUNK_START %zu %s", context->m_ChunkedBytesRemaining, GetMediaTypeName(context->mediaType) );
context->m_ChunkedTransferState = ChunkedTransferState::READING_CHUNK_DATA;
}
else
{
AAMPLOG_INFO( "CHUNK_END %s", GetMediaTypeName(context->mediaType) );
context->m_ChunkedTransferState = ChunkedTransferState::DONE;
}
}
break;
case ChunkedTransferState::READING_CHUNK_DATA:
{
size_t n = fin - ptr;
if( n > context->m_ChunkedBytesRemaining )
{ // clamp - more bytes in write_callback than needed to complete current chunk
n = context->m_ChunkedBytesRemaining;
}
// Guard against std::bad_alloc crossing the C curl callback boundary.
// On allocation failure, flag ERROR and exit the parsing loop so the
// caller can return 0 to libcurl to abort the transfer cleanly.
try
{
context->buffer.insert(context->buffer.end(),
reinterpret_cast<const uint8_t*>(ptr),
reinterpret_cast<const uint8_t*>(ptr) + n);
}
catch( const std::exception &e )
{
AAMPLOG_ERR( "chunked_write_callback: buffer insert failed (%s); aborting transfer", e.what() );
context->abortReason = eCURL_ABORT_REASON_BUFFER_ALLOC_FAILURE;
context->m_ChunkedTransferState = ChunkedTransferState::ERROR;
ptr = fin; // consume remaining bytes to exit the parse loop
break;
}
ptr += n;
context->m_ChunkedBytesRemaining -= n;
if( context->m_ChunkedBytesRemaining == 0 )
{
// here we will presumably be at the end of an 'mdat', suitable for injection
// bytes collected so far may include 1..4 packed ('moov','mdat') boxes.
context->m_ChunkedTransferState = ChunkedTransferState::PENDING_CHUNK_END_CR;
}
}
break;
case ChunkedTransferState::PENDING_CHUNK_END_CR:
if( *ptr++ != '\r' )
{
AAMPLOG_ERR( "missing expected \\r" );
context->m_ChunkedTransferState = ChunkedTransferState::ERROR;
}
else
{
context->m_ChunkedTransferState = ChunkedTransferState::PENDING_CHUNK_END_LF;
}
break;
case ChunkedTransferState::PENDING_CHUNK_END_LF:
if( *ptr++ != '\n' )
{
AAMPLOG_ERR( "missing expected \\n" );
context->m_ChunkedTransferState = ChunkedTransferState::ERROR;
}
else
{
context->m_ChunkedTransferState = ChunkedTransferState::READING_CHUNK_SIZE;
if( context->m_ChunkedBytesRemaining != 0 )
{
AAMPLOG_ERR( "unexpected m_ChunkedBytesRemaining=%zu", context->m_ChunkedBytesRemaining );
context->m_ChunkedTransferState = ChunkedTransferState::ERROR;
}
}
break;
case ChunkedTransferState::DONE:
{
char c = *ptr++;
if( c == '\n' || c == '\r' )
{ // end marker CRLF
continue;
}
AAMPLOG_ERR( "unexpected data after final chunk" );
context->m_ChunkedTransferState = ChunkedTransferState::ERROR;
}
break;