31 #include "AampUtils.h"
41 #ifdef USE_CPP_THUNDER_PLUGIN_ACCESS
48 #include "SubtecFactory.hpp"
50 #ifdef AAMP_CC_ENABLED
53 #ifdef USE_OPENCDM // AampOutputProtection is compiled when this flag is enabled
63 #include "libIBusDaemon.h"
64 #include <hostIf_tr69ReqHandler.h>
71 #include <sys/types.h>
74 #include <uuid/uuid.h>
77 #define LOCAL_HOST_IP "127.0.0.1"
78 #define AAMP_MAX_TIME_BW_UNDERFLOWS_TO_TRIGGER_RETUNE_MS (20*1000LL)
79 #define AAMP_MAX_TIME_LL_BW_UNDERFLOWS_TO_TRIGGER_RETUNE_MS (AAMP_MAX_TIME_BW_UNDERFLOWS_TO_TRIGGER_RETUNE_MS/10)
82 #define MAX_DESCRIPTION_SIZE 128
85 #define MACRO_TO_STRING(s) X_STR(s)
89 #define TRUST_LOCATOR_EXTENSION_IF_PRESENT
91 #define VALIDATE_INT(param_name, param_value, default_value) \
92 if ((param_value <= 0) || (param_value > INT_MAX)) { \
93 AAMPLOG_WARN("Parameter '%s' not within INTEGER limit. Using default value instead.", param_name); \
94 param_value = default_value; \
97 #define VALIDATE_LONG(param_name, param_value, default_value) \
98 if ((param_value <= 0) || (param_value > LONG_MAX)) { \
99 AAMPLOG_WARN("Parameter '%s' not within LONG INTEGER limit. Using default value instead.", param_name); \
100 param_value = default_value; \
103 #define VALIDATE_DOUBLE(param_name, param_value, default_value) \
104 if ((param_value <= 0) || (param_value > DBL_MAX)) { \
105 AAMPLOG_WARN("Parameter '%s' not within DOUBLE limit. Using default value instead.", param_name); \
106 param_value = default_value; \
109 #define CURL_EASY_SETOPT(curl, CURLoption, option)\
110 if (curl_easy_setopt(curl, CURLoption, option) != 0) {\
111 logprintf("Failed at curl_easy_setopt ");\
112 } //CID:132698,135078 - checked return
114 #define FOG_REASON_STRING "Fog-Reason:"
115 #define CURLHEADER_X_REASON "X-Reason:"
116 #define BITRATE_HEADER_STRING "X-Bitrate:"
117 #define CONTENTLENGTH_STRING "Content-Length:"
118 #define SET_COOKIE_HEADER_STRING "Set-Cookie:"
119 #define LOCATION_HEADER_STRING "Location:"
120 #define CONTENT_ENCODING_STRING "Content-Encoding:"
121 #define FOG_RECORDING_ID_STRING "Fog-Recording-Id:"
122 #define CAPPED_PROFILE_STRING "Profile-Capped:"
123 #define TRANSFER_ENCODING_STRING "Transfer-Encoding:"
125 #define MAX_DOWNLOAD_DELAY_LIMIT_MS 30000
133 static char *full_playlist_video_ptr = NULL;
134 static size_t full_playlist_video_len = 0;
135 static char *full_playlist_audio_ptr = NULL;
136 static size_t full_playlist_audio_len = 0;
149 static std::list<gActivePrivAAMP_t> gActivePrivAAMPs = std::list<gActivePrivAAMP_t>();
151 static pthread_mutex_t gMutex = PTHREAD_MUTEX_INITIALIZER;
152 static pthread_cond_t gCond = PTHREAD_COND_INITIALIZER;
154 static int PLAYERID_CNTR = 0;
156 static const char* strAAMPPipeName =
"/tmp/ipc_aamp";
158 static bool activeInterfaceWifi =
false;
160 static char previousInterface[20] = {
'\0'};
162 static unsigned int ui32CurlTrace = 0;
184 IARM_BUS_NETWORK_MANAGER_EVENT_SET_INTERFACE_ENABLED=50,
185 IARM_BUS_NETWORK_MANAGER_EVENT_INTERFACE_IPADDRESS=55,
186 IARM_BUS_NETWORK_MANAGER_MAX
195 char activeIface[10];
196 char allNetworkInterfaces[50];
197 char enableInterface[10];
200 bool isInterfaceEnabled;
245 static constexpr
const char *BITRATECHANGE_STR[] =
247 (
const char *)
"BitrateChanged - Network adaptation",
248 (
const char *)
"BitrateChanged - Rampdown due to network failure",
249 (
const char *)
"BitrateChanged - Reset to default bitrate due to tune",
250 (
const char *)
"BitrateChanged - Reset to default bitrate due to seek",
251 (
const char *)
"BitrateChanged - Reset to default bitrate due to trickplay",
252 (
const char *)
"BitrateChanged - Rampup since buffers are full",
253 (
const char *)
"BitrateChanged - Rampdown since buffers are empty",
254 (
const char *)
"BitrateChanged - Network adaptation by FOG",
255 (
const char *)
"BitrateChanged - Information from OTA",
256 (
const char *)
"BitrateChanged - Video stream information from HDMIIN",
257 (
const char *)
"BitrateChanged - Unknown reason"
260 #define BITRATEREASON2STRING(id) BITRATECHANGE_STR[id]
262 static constexpr
const char *ADEVENT_STR[] =
264 (
const char *)
"AAMP_EVENT_AD_RESERVATION_START",
265 (
const char *)
"AAMP_EVENT_AD_RESERVATION_END",
266 (
const char *)
"AAMP_EVENT_AD_PLACEMENT_START",
267 (
const char *)
"AAMP_EVENT_AD_PLACEMENT_END",
268 (
const char *)
"AAMP_EVENT_AD_PLACEMENT_ERROR",
269 (
const char *)
"AAMP_EVENT_AD_PLACEMENT_PROGRESS"
272 #define ADEVENT2STRING(id) ADEVENT_STR[id - AAMP_EVENT_AD_RESERVATION_START]
274 static constexpr
const char *mMediaFormatName[] =
276 "HLS",
"DASH",
"PROGRESSIVE",
"HLS_MP4",
"OTA",
"HDMI_IN",
"COMPOSITE_IN",
"SMOOTH_STREAMING",
"RMF",
"UNKNOWN"
279 static_assert(
sizeof(mMediaFormatName)/
sizeof(mMediaFormatName[0]) == (
eMEDIAFORMAT_UNKNOWN + 1),
"Ensure 1:1 mapping between mMediaFormatName[] and enum MediaFormat");
286 guint callbackId = 0;
287 GSource *source = g_main_current_source();
290 callbackId = g_source_get_id(source);
302 bool retValue =
true;
309 retValue = aamp->mStreamSink->
Pause(
false,
false);
319 aamp->
rate = AAMP_NORMAL_PLAY_RATE;
332 aamp->mAutoResumeTaskPending =
false;
333 return G_SOURCE_REMOVE;
345 GSource *src = g_main_current_source();
346 if (src == NULL || !g_source_is_destroyed(src))
353 aamp->mDiscontinuityTuneOperationId = 0;
356 pthread_cond_signal(&aamp->mCondDiscontinuity);
359 return G_SOURCE_REMOVE;
370 bool activeAAMPFound =
false;
373 pthread_mutex_lock(&gMutex);
374 for (std::list<gActivePrivAAMP_t>::iterator iter = gActivePrivAAMPs.begin(); iter != gActivePrivAAMPs.end(); iter++)
376 if (aamp == iter->pAAMP)
378 gAAMPInstance = &(*iter);
379 activeAAMPFound =
true;
380 reTune = gAAMPInstance->reTune;
384 if (!activeAAMPFound)
386 AAMPLOG_WARN(
"PrivateInstanceAAMP: %p not in Active AAMP list", aamp);
390 AAMPLOG_WARN(
"PrivateInstanceAAMP: %p reTune flag not set", aamp);
399 aamp->mIsRetuneInProgress =
true;
400 pthread_mutex_unlock(&gMutex);
406 pthread_mutex_lock(&gMutex);
407 aamp->mIsRetuneInProgress =
false;
408 gAAMPInstance->reTune =
false;
409 pthread_cond_signal(&gCond);
411 pthread_mutex_unlock(&gMutex);
412 return G_SOURCE_REMOVE;
425 const char *fin = ptr+len;
426 bool wroteHeader =
false;
433 float fragmentDuration;
439 if( ptr>=fin || c<
' ' )
break;
444 if (sscanf(line,
"#EXTINF:%f",&fragmentDuration) == 1)
448 cull -= fragmentDuration;
458 snprintf( header,
sizeof(header),
461 "#EXT-X-TARGETDURATION:2\n"
462 "#EXT-X-MEDIA-SEQUENCE:%d\n", seqNo );
466 window -= fragmentDuration;
534 std::string prefix(
"&recordedUrl=");
535 size_t startPos = url.find(prefix);
536 if( startPos != std::string::npos )
538 startPos += prefix.size();
539 size_t len = url.find(
'&',startPos );
540 if( len != std::string::npos )
544 url = url.substr(startPos,len);
556 static bool replace(std::string &str,
const char *existingSubStringToReplace,
const char *replacementString)
559 std::size_t fromPos = 0;
560 size_t existingSubStringToReplaceLen = 0;
561 size_t replacementStringLen = 0;
564 std::size_t pos = str.find(existingSubStringToReplace,fromPos);
565 if( pos == std::string::npos )
572 existingSubStringToReplaceLen = strlen(existingSubStringToReplace);
573 replacementStringLen = strlen(replacementString);
575 str.replace( pos, existingSubStringToReplaceLen, replacementString );
576 fromPos = pos + replacementStringLen;
589 void getActiveInterfaceEventHandler (
const char *owner, IARM_EventId_t eventId,
void *data,
size_t len)
592 if (strcmp (owner,
"NET_SRV_MGR") != 0)
597 if (NULL == strstr (param->activeIface, previousInterface) || (strlen(previousInterface) == 0))
599 memset(previousInterface, 0,
sizeof(previousInterface));
600 strncpy(previousInterface, param->activeIface,
sizeof(previousInterface) - 1);
601 AAMPLOG_WARN(
"getActiveInterfaceEventHandler EventId %d activeinterface %s", eventId, param->activeIface);
604 if (NULL != strstr (param->activeIface,
"wlan"))
606 activeInterfaceWifi =
true;
608 else if (NULL != strstr (param->activeIface,
"eth"))
610 activeInterfaceWifi =
false;
623 std::string prefix(
"&recordedUrl=");
624 size_t startPos = url.find(prefix);
625 if( startPos != std::string::npos )
627 startPos += prefix.size();
628 url.replace(startPos, from.length(), to);
638 bool wifiStatus =
false;
640 IARM_Result_t ret = IARM_RESULT_SUCCESS;
643 ret =
IARM_Bus_Call(
"NET_SRV_MGR",
"getActiveInterface", (
void*)¶m,
sizeof(param));
644 if (ret != IARM_RESULT_SUCCESS) {
645 AAMPLOG_ERR(
"NET_SRV_MGR getActiveInterface read failed : %d", ret);
649 AAMPLOG_WARN(
"NET_SRV_MGR getActiveInterface = %s", param.activeIface);
650 if (!strcmp(param.activeIface,
"WIFI")){
670 if (buf.find(prefixPtr) != std::string::npos)
672 std::size_t pos = strlen(prefixPtr);
673 if (*valueCopyPtr != NULL)
675 free((
void *)*valueCopyPtr);
676 *valueCopyPtr = NULL;
678 *valueCopyPtr = strdup(buf.substr(pos).c_str());
702 std::size_t pos = buf.rfind(prefixPtr,0);
703 if (pos != std::string::npos)
705 pos += strlen(prefixPtr);
706 std::string valStr = buf.substr(pos);
707 if (std::is_same<T, int>::value)
708 value = std::stoi(valStr);
709 else if (std::is_same<T, long>::value)
710 value = std::stol(valStr);
711 else if (std::is_same<T, float>::value)
712 value = std::stof(valStr);
714 value = std::stod(valStr);
730 static std::string getTimeStamp(time_t epochTime,
const char* format =
"%Y-%m-%dT%H:%M:%S.%f%Z")
732 char timestamp[64] = {0};
733 strftime(timestamp,
sizeof(timestamp), format, localtime(&epochTime));
737 static time_t convertTimeToEpoch(
const char* theTime,
const char* format =
"%Y-%m-%dT%H:%M:%S.%f%Z")
740 memset(&tmTime, 0,
sizeof(tmTime));
741 strptime(theTime, format, &tmTime);
742 return mktime(&tmTime);
759 pthread_mutex_lock(&context->aamp->mLock);
760 size_t numBytesForBlock = size*nmemb;
762 ret = numBytesForBlock;
763 pthread_mutex_unlock(&context->aamp->mLock);
774 if(!context)
return ret;
775 pthread_mutex_lock(&context->aamp->mLock);
776 if (context->aamp->mDownloadsEnabled)
778 if ((NULL == context->buffer->ptr) && (context->contentLength > 0))
780 size_t len = context->contentLength + 2;
787 assert(!context->buffer->ptr);
789 context->buffer->avail = len;
791 size_t numBytesForBlock = size*nmemb;
793 ret = numBytesForBlock;
795 if(context->aamp->GetLLDashServiceData()->lowLatencyMode &&
803 mCtx->
CacheFragmentChunk(context->fileType, ptr, numBytesForBlock,context->remoteUrl,context->downloadStartTime);
815 AAMPLOG_WARN(
"CurlTrace write_callback - interrupted, ret:%zu", ret);
818 pthread_mutex_unlock(&context->aamp->mLock);
830 static size_t write_callback(
char *ptr,
size_t size,
size_t nmemb,
void *userdata)
834 if(!context)
return ret;
836 ret = context->aamp->HandleSSLWriteCallback( ptr, size, nmemb, userdata);
848 int size = allResponseHeadersForErrorLogging.size();
849 AAMPLOG_WARN(
"################ Start :: Print Header response ################");
850 for (
int i=0; i < size; i++)
852 AAMPLOG_WARN(
"* %s", allResponseHeadersForErrorLogging.at(i).c_str());
854 AAMPLOG_WARN(
"################ End :: Print Header response ################");
857 allResponseHeadersForErrorLogging.clear();
867 size_t len = nmemb * size;
869 size_t endPos = len-2;
871 bool isBitrateHeader =
false;
872 bool isFogRecordingIdHeader =
false;
873 bool isProfileCapHeader =
false;
875 if( len<2 || ptr[endPos] !=
'\r' || ptr[endPos+1] !=
'\n' )
883 std::string temp = std::string(ptr,endPos);
884 context->allResponseHeadersForErrorLogging.push_back(temp);
889 if (STARTS_WITH_IGNORE_CASE(ptr, FOG_REASON_STRING))
892 startPos = STRLEN_LITERAL(FOG_REASON_STRING);
894 else if (STARTS_WITH_IGNORE_CASE(ptr, CURLHEADER_X_REASON))
897 startPos = STRLEN_LITERAL(CURLHEADER_X_REASON);
899 else if (STARTS_WITH_IGNORE_CASE(ptr, BITRATE_HEADER_STRING))
901 startPos = STRLEN_LITERAL(BITRATE_HEADER_STRING);
902 isBitrateHeader =
true;
904 else if (STARTS_WITH_IGNORE_CASE(ptr, SET_COOKIE_HEADER_STRING))
907 startPos = STRLEN_LITERAL(SET_COOKIE_HEADER_STRING);
909 else if (STARTS_WITH_IGNORE_CASE(ptr, LOCATION_HEADER_STRING))
912 startPos = STRLEN_LITERAL(LOCATION_HEADER_STRING);
914 else if (STARTS_WITH_IGNORE_CASE(ptr, FOG_RECORDING_ID_STRING))
916 startPos = STRLEN_LITERAL(FOG_RECORDING_ID_STRING);
917 isFogRecordingIdHeader =
true;
919 else if (STARTS_WITH_IGNORE_CASE(ptr, CONTENT_ENCODING_STRING ))
923 context->downloadIsEncoded =
true;
925 else if (context->aamp->mConfig->IsConfigSet(
eAAMPConfig_LimitResolution) && context->aamp->IsFirstRequestToFog() && STARTS_WITH_IGNORE_CASE(ptr, CAPPED_PROFILE_STRING ))
927 startPos = STRLEN_LITERAL(CAPPED_PROFILE_STRING);
928 isProfileCapHeader =
true;
930 else if (STARTS_WITH_IGNORE_CASE(ptr, TRANSFER_ENCODING_STRING ))
932 context->chunkedDownload =
true;
934 else if (0 == context->buffer->avail)
936 if (STARTS_WITH_IGNORE_CASE(ptr, CONTENTLENGTH_STRING))
938 int contentLengthStartPosition = STRLEN_LITERAL(CONTENTLENGTH_STRING);
939 const char * contentLengthStr = ptr + contentLengthStartPosition;
940 context->contentLength = atoi(contentLengthStr);
947 std::vector<std::string> responseHeaders = context->aamp->responseHeaders;
949 if (responseHeaders.size() > 0)
951 for (
int header=0; header < responseHeaders.size(); header++) {
952 std::string headerType = responseHeaders[header].c_str();
954 if (0 == strncasecmp(ptr, headerType.c_str() , headerType.length()))
956 startPos = headerType.length();
958 context->aamp->httpHeaderResponses[headerType] = std::string( ptr + startPos + 2, endPos - startPos - 2).c_str();
959 AAMPLOG_INFO(
"httpHeaderResponses");
960 for (
auto const& pair: context->aamp->httpHeaderResponses) {
961 AAMPLOG_INFO(
"{ %s, %s }", pair.first.c_str(), pair.second.c_str());
970 while( endPos>startPos && ptr[endPos-1] ==
' ' )
974 while( startPos < endPos && ptr[startPos] ==
' ')
981 const char * strBitrate = ptr + startPos;
982 context->bitrate = atol(strBitrate);
983 AAMPLOG_TRACE(
"Parsed HTTP %s: %ld", isBitrateHeader?
"Bitrate":
"False", context->bitrate);
985 else if(isFogRecordingIdHeader)
987 context->aamp->mTsbRecordingId = string( ptr + startPos, endPos - startPos );
988 AAMPLOG_TRACE(
"Parsed Fog-Id : %s", context->aamp->mTsbRecordingId.c_str());
990 else if(isProfileCapHeader)
992 const char * strProfileCap = ptr + startPos;
993 context->aamp->mProfileCappedStatus = atol(strProfileCap)? true :
false;
994 AAMPLOG_TRACE(
"Parsed Profile-Capped Header : %d", context->aamp->mProfileCappedStatus);
998 httpHeader->
data = string( ptr + startPos, endPos - startPos );
1001 httpHeader->
data +=
';';
1022 #define ONE_KILO 1024
1023 #define ONE_MEGA ((1024) * ONE_KILO)
1026 snprintf(str, 6,
"%5ld", bps);
1028 else if(bps < (10000 * ONE_KILO))
1029 snprintf(str, 6,
"%4ld" "k", bps/ONE_KILO);
1031 else if(bps < (100 * ONE_MEGA))
1032 snprintf(str, 6,
"%2ld" ".%0ld" "M", bps/ONE_MEGA,
1033 (bps%ONE_MEGA) / (ONE_MEGA/10) );
1035 snprintf(str, 6,
"%4ld" "M", bps/ONE_MEGA);
1052 bool bDownloadStart,
1056 long bitsPerSecond = 0;
1060 char buffer[2][6] = {0,};
1067 speedcache->last_sample_time_val = start;
1070 time_now = NOW_STEADY_TS_MS;
1071 time_diff = (time_now - speedcache->last_sample_time_val);
1075 speedcache->prev_dlnow = 0;
1078 dl_diff = (long)dlnow - speedcache->prev_dlnow;
1080 long prevdlnow = speedcache->prev_dlnow;
1081 speedcache->prev_dlnow = dlnow;
1083 long currentTotalDownloaded = 0;
1084 long total_dl_diff = 0;
1085 currentTotalDownloaded = speedcache->totalDownloaded + dl_diff;
1086 total_dl_diff = currentTotalDownloaded - speedcache->prevSampleTotalDownloaded;
1087 if(total_dl_diff<=0) total_dl_diff = 0;
1091 if(aamp->
mhAbrManager.IsABRDataGoodToEstimate(time_diff))
1093 aamp->
mhAbrManager.CheckLLDashABRSpeedStoreSize(speedcache,bitsPerSecond,time_now,total_dl_diff,time_diff,currentTotalDownloaded);
1097 AAMPLOG_TRACE(
"[%d] Ignore Speed Calculation -> time_diff [%ld]",fileType, time_diff);
1100 speedcache->totalDownloaded += dl_diff;
1102 return bitsPerSecond;
1120 AampConfig *mConfig = context->aamp->mConfig;
1122 if(context->aamp->GetLLDashServiceData()->lowLatencyMode &&
1124 context->aamp->CheckABREnabled() &&
1130 int AbrChunkThresholdSize = 0;
1133 if ( (context->downloadNow != dlnow))
1135 long downloadbps = 0;
1137 context->downloadNow = dlnow;
1138 context->downloadNowUpdatedTime = NOW_STEADY_TS_MS;
1145 memset(speedcache, 0x00,
sizeof(
struct SpeedCache));
1150 if(context->dlStarted)
1152 context->dlStarted =
false;
1162 long currentProfilebps = context->aamp->mpStreamAbstractionAAMP->GetVideoBitrate();
1164 pthread_mutex_lock(&context->aamp->mLock);
1165 aamp->
mhAbrManager.UpdateABRBitrateDataBasedOnCacheLength(context->aamp->mAbrBitrateData,downloadbps,
true);
1166 pthread_mutex_unlock(&context->aamp->mLock);
1172 context->aamp->SyncBegin();
1173 if (!context->aamp->mDownloadsEnabled)
1178 context->aamp->SyncEnd();
1181 if (dlnow > 0 && context->stallTimeout > 0)
1183 if (context->downloadSize == -1)
1185 context->downloadSize = dlnow;
1186 context->downloadUpdatedTime = NOW_STEADY_TS_MS;
1190 if (dlnow == context->downloadSize)
1192 double timeElapsedSinceLastUpdate = (NOW_STEADY_TS_MS - context->downloadUpdatedTime) / 1000.0;
1193 if (timeElapsedSinceLastUpdate >= context->stallTimeout)
1195 AAMPLOG_WARN(
"Abort download as mid-download stall detected for %.2f seconds, download size:%.2f bytes", timeElapsedSinceLastUpdate, dlnow);
1196 context->abortReason = eCURL_ABORT_REASON_STALL_TIMEDOUT;
1202 context->downloadSize = dlnow;
1203 context->downloadUpdatedTime = NOW_STEADY_TS_MS;
1207 if (dlnow == 0 && context->startTimeout > 0)
1209 double timeElapsedInSec = (double)(NOW_STEADY_TS_MS - context->downloadStartTime) / 1000;
1210 if (timeElapsedInSec >= context->startTimeout)
1212 AAMPLOG_WARN(
"Abort download as no data received for %.2f seconds", timeElapsedInSec);
1213 context->abortReason = eCURL_ABORT_REASON_START_TIMEDOUT;
1217 if (dlnow > 0 && context->lowBWTimeout> 0 &&
eMEDIATYPE_VIDEO == context->fileType)
1219 double elapsedTimeMs = (double)(NOW_STEADY_TS_MS - context->downloadStartTime);
1220 if( elapsedTimeMs >= context->lowBWTimeout*1000 )
1222 double predictedTotalDownloadTimeMs = elapsedTimeMs*dltotal/dlnow;
1223 if( predictedTotalDownloadTimeMs > aamp->mNetworkTimeoutMs )
1225 AAMPLOG_WARN(
"lowBWTimeout=%lds; predictedTotalDownloadTime=%fs>%fs (network timeout)",
1226 context->lowBWTimeout,
1227 predictedTotalDownloadTimeMs/1000.0,
1228 aamp->mNetworkTimeoutMs/1000.0 );
1229 context->abortReason = eCURL_ABORT_REASON_LOW_BANDWIDTH_TIMEDOUT;
1238 if( !( eCURL_ABORT_REASON_LOW_BANDWIDTH_TIMEDOUT == context->abortReason || eCURL_ABORT_REASON_START_TIMEDOUT == context->abortReason ||\
1245 AAMPLOG_WARN(
"CurlTrace Progress interrupted, ret:%d", rc);
1270 return context->aamp->HandleSSLProgressCallback ( clientp, dltotal, dlnow, ultotal, ulnow );
1280 mDownloadsEnabled(true), mStreamSink(NULL), profiler(), licenceFromManifest(false), previousAudioType(eAUDIO_UNKNOWN),isPreferredDRMConfigured(false),
1281 mbDownloadsBlocked(false), streamerIsActive(false), mTSBEnabled(false), mIscDVR(false), mLiveOffset(
AAMP_LIVE_OFFSET),
1282 seek_pos_seconds(-1), rate(0), pipeline_paused(false), mMaxLanguageCount(0), zoom_mode(
VIDEO_ZOOM_FULL),
1283 video_muted(false), subtitles_muted(true), audio_volume(100), subscribedTags(), responseHeaders(), httpHeaderResponses(), timedMetadata(), timedMetadataNew(), IsTuneTypeNew(false), trickStartUTCMS(-1),mLogTimetoTopProfile(true),
1285 mEventListener(NULL), mNewSeekInfo(), discardEnteringLiveEvt(false),
1286 mIsRetuneInProgress(false), mCondDiscontinuity(), mDiscontinuityTuneOperationId(0), mIsVSS(false),
1287 m_fd(-1), mIsLive(false), mIsAudioContextSkipped(false), mLogTune(false), mTuneCompleted(false), mFirstTune(true), mfirstTuneFmt(-1), mTuneAttempts(0), mPlayerLoadTime(0),
1289 mDiscontinuityTuneOperationInProgress(false), mContentType(
ContentType_UNKNOWN), mTunedEventPending(false),
1290 mSeekOperationInProgress(false), mTrickplayInProgress(false), mPendingAsyncEvents(), mCustomHeaders(),
1291 mCMCDNextObjectRequest(
""),mCMCDBandwidth(0),
1292 mManifestUrl(
""), mTunedManifestUrl(
""), mOrigManifestUrl(), mServiceZone(), mVssVirtualStreamId(),
1293 mCurrentLanguageIndex(0),
1294 preferredLanguagesString(), preferredLanguagesList(), preferredLabelList(),mhAbrManager(),
1296 mTimeToTopProfile(0),mTimeAtTopProfile(0),mPlaybackDuration(0),mTraceUUID(),
1297 mIsFirstRequestToFOG(false),
1298 mPausePositionMonitorMutex(), mPausePositionMonitorCV(), mPausePositionMonitoringThreadID(), mPausePositionMonitoringThreadStarted(false),
1300 ,mCdaiObject(NULL), mAdEventsQ(),mAdEventQMtx(), mAdPrevProgressTime(0), mAdCurOffset(0), mAdDuration(0), mAdProgressId(
"")
1301 ,mBufUnderFlowStatus(false), mVideoBasePTS(0)
1302 ,mCustomLicenseHeaders(), mIsIframeTrackPresent(false), mManifestTimeoutMs(-1), mNetworkTimeoutMs(-1)
1303 ,mbPlayEnabled(true), mPlayerPreBuffered(false), mPlayerId(PLAYERID_CNTR++),mAampCacheHandler(NULL)
1304 ,mAsyncTuneEnabled(false)
1308 ,mPlaylistTimeoutMs(-1)
1311 , fragmentCdmEncrypted(false) ,drmParserMutex(), aesCtrAttrDataList()
1312 , drmSessionThreadStarted(false), createDRMSessionThreadID(0)
1314 #if defined(AAMP_MPD_DRM) || defined(AAMP_HLS_DRM)
1315 , mDRMSessionManager(NULL)
1317 , mPreCachePlaylistThreadId(0), mPreCachePlaylistThreadFlag(false) , mPreCacheDnldList()
1318 , mPreCacheDnldTimeWindow(0), mParallelPlaylistFetchLock(), mAppName()
1319 , mProgressReportFromProcessDiscontinuity(false)
1320 , mPlaylistFetchFailError(0L),mAudioDecoderStreamSync(true)
1321 , mPrevPositionMilliseconds()
1322 , mGetPositionMillisecondsMutexHard()
1323 , mGetPositionMillisecondsMutexSoft()
1324 , mPausePositionMilliseconds(AAMP_PAUSE_POSITION_INVALID_POSITION)
1327 , mFragmentCachingRequired(false), mFragmentCachingLock()
1328 , mPauseOnFirstVideoFrameDisp(false)
1329 , mPreferredTextTrack(), mFirstVideoFrameDisplayedEnabled(false)
1332 , midFragmentSeekCache(false)
1335 , mthumbIndexValue(-1)
1336 , mManifestRefreshCount (0)
1338 , mProgramDateTime (0), mMPDPeriodsInfo()
1339 , mProfileCappedStatus(false),mSchemeIdUriDai(
"")
1342 , preferredRenditionString(
"")
1343 , preferredRenditionList()
1344 , preferredTypeString(
"")
1345 , preferredCodecString(
"")
1346 , preferredCodecList()
1348 , preferredLabelsString(
"")
1349 , preferredAudioAccessibilityNode()
1350 , preferredTextLanguagesString(
"")
1351 , preferredTextLanguagesList()
1352 , preferredTextRenditionString(
"")
1353 , preferredTextTypeString(
"")
1354 , preferredTextLabelString(
"")
1355 , preferredTextAccessibilityNode()
1356 , mProgressReportOffset(-1)
1357 , mAutoResumeTaskId(AAMP_TASK_ID_INVALID), mAutoResumeTaskPending(false), mScheduler(NULL), mEventLock(), mEventPriority(G_PRIORITY_DEFAULT_IDLE)
1359 , mConfig (config),mSubLanguage(), mHarvestCountLimit(0), mHarvestConfig(0)
1360 , mIsWVKIDWorkaround(false)
1362 , mAbsoluteEndPosition(0), mIsLiveStream(false)
1363 , mbUsingExternalPlayer (false)
1367 , mAampLLDashServiceData{}
1368 , bLowLatencyServiceConfigured(
false)
1369 , bLLDashAdjustPlayerSpeed(
false)
1370 , mLLDashCurrentPlayRate(AAMP_NORMAL_PLAY_RATE)
1375 , mCurrentLatency(0)
1376 , mLiveOffsetAppRequest(
false)
1377 , bLowLatencyStartABR(
false)
1378 , mWaitForDiscoToComplete()
1379 , mDiscoCompleteLock()
1380 , mIsPeriodChangeMarked(
false)
1382 , mEventManager (NULL)
1384 , mIsFakeTune(
false)
1385 , mCurrentAudioTrackId(-1)
1386 , mCurrentVideoTrackId(-1)
1387 , mIsTrackIdMismatch(
false)
1388 , mIsDefaultOffset(
false)
1389 , mNextPeriodDuration(0)
1390 , mNextPeriodStartTime(0)
1391 , mNextPeriodScaledPtoStartTime(0)
1392 , mOffsetFromTunetimeForSAPWorkaround(0)
1393 , mLanguageChangeInProgress(
false)
1394 , mSupportedTLSVersion(0)
1396 , mFailureReason(
"")
1397 , mTimedMetadataStartTime(0)
1398 , mTimedMetadataDuration(0)
1399 , playerStartedWithTrickPlay(
false)
1400 , mPlaybackMode(
"UNKNOWN")
1401 , mApplyVideoRect(
false)
1406 , userProfileStatus(
false)
1407 , mApplyCachedVideoMute(
false)
1408 , mFirstProgress(
false)
1409 , mTsbSessionRequestUrl()
1410 , mcurrent_keyIdArray()
1411 , mDynamicDrmDefaultconfig()
1412 , mWaitForDynamicDRMToUpdate()
1413 , mDynamicDrmUpdateLock()
1414 , mDynamicDrmCache()
1415 , mAudioComponentCount(-1)
1416 , mVideoComponentCount(-1)
1417 , mAudioOnlyPb(
false)
1418 , mVideoOnlyPb(
false)
1419 , mCurrentAudioTrackIndex(-1)
1420 , mCurrentTextTrackIndex(-1)
1422 , mSetPlayerRateAfterFirstframe(
false)
1423 , mEncryptedPeriodFound(
false)
1424 , mPipelineIsClear(
false)
1425 , mLLActualOffset(-1)
1426 , mIsStream4K(
false)
1431 lastId3Data[i] = NULL;
1432 lastId3DataLen[i] = 0;
1434 mLogObj = mConfig->GetLoggerInstance();
1437 #ifdef AAMP_CC_ENABLED
1440 profiler.SetLogger(mConfig->GetLoggerInstance());
1455 #if defined(AAMP_MPD_DRM) || defined(AAMP_HLS_DRM)
1458 pthread_cond_init(&mDownloadsDisabled, NULL);
1460 pthread_mutexattr_init(&mMutexAttr);
1461 pthread_mutexattr_settype(&mMutexAttr, PTHREAD_MUTEX_RECURSIVE);
1462 pthread_mutex_init(&mLock, &mMutexAttr);
1463 pthread_mutex_init(&mParallelPlaylistFetchLock, &mMutexAttr);
1464 pthread_mutex_init(&mFragmentCachingLock, &mMutexAttr);
1465 pthread_mutex_init(&mEventLock, &mMutexAttr);
1466 pthread_mutex_init(&mDynamicDrmUpdateLock,&mMutexAttr);
1467 pthread_mutex_init(&mStreamLock, &mMutexAttr);
1468 pthread_mutex_init(&mDiscoCompleteLock,&mMutexAttr);
1475 httpRespHeaders[i].data.clear();
1476 curlDLTimeout[i] = 0;
1489 mbTrackDownloadsBlocked[i] =
false;
1490 mTrackInjectionBlocked[i] =
false;
1491 lastUnderFlowTimeMs[i] = 0;
1492 mProcessingDiscontinuity[i] =
false;
1493 mIsDiscontinuityIgnored[i] =
false;
1496 pthread_mutex_lock(&gMutex);
1498 gActivePrivAAMPs.push_back(gAAMPInstance);
1499 pthread_mutex_unlock(&gMutex);
1500 mPendingAsyncEvents.clear();
1502 if (ISCONFIGSET_PRIV(eAAMPConfig_WifiCurlHeader)) {
1504 mCustomHeaders[
"Wifi:"] = std::vector<std::string> {
"1" };
1505 activeInterfaceWifi =
true;
1509 mCustomHeaders[
"Wifi:"] = std::vector<std::string> {
"0" };
1510 activeInterfaceWifi =
false;
1514 mCustomHeaders[
"Connection:"] = std::vector<std::string> {
"Keep-Alive" };
1515 pthread_cond_init(&mCondDiscontinuity, NULL);
1516 pthread_cond_init(&waitforplaystart, NULL);
1517 pthread_cond_init(&mWaitForDynamicDRMToUpdate,NULL);
1518 pthread_mutex_init(&mMutexPlaystart, NULL);
1519 pthread_cond_init(&mWaitForDiscoToComplete,NULL);
1520 preferredLanguagesList.push_back(
"en");
1523 memset(&aesCtrAttrDataList, 0,
sizeof(aesCtrAttrDataList));
1524 pthread_mutex_init(&drmParserMutex, NULL);
1537 #ifdef AAMP_CC_ENABLED
1541 pthread_mutex_lock(&gMutex);
1542 auto iter = std::find_if(std::begin(gActivePrivAAMPs), std::end(gActivePrivAAMPs), [
this](
const gActivePrivAAMP_t& el)
1544 return el.pAAMP ==
this;
1546 if(iter != gActivePrivAAMPs.end())
1548 gActivePrivAAMPs.erase(iter);
1550 pthread_mutex_unlock(&gMutex);
1552 pthread_mutex_lock(&
mLock);
1554 SAFE_DELETE(mVideoEnd);
1556 pthread_mutex_unlock(&
mLock);
1558 pthread_cond_destroy(&mDownloadsDisabled);
1559 pthread_cond_destroy(&mWaitForDynamicDRMToUpdate);
1560 pthread_cond_destroy(&mCondDiscontinuity);
1564 pthread_mutex_destroy(&
mLock);
1565 pthread_mutex_destroy(&mDynamicDrmUpdateLock);
1571 pthread_mutexattr_destroy(&mMutexAttr);
1573 aesCtrAttrDataList.clear();
1574 pthread_mutex_destroy(&drmParserMutex);
1576 SAFE_DELETE(mAampCacheHandler);
1578 #if defined(AAMP_MPD_DRM) || defined(AAMP_HLS_DRM)
1579 SAFE_DELETE(mDRMSessionManager);
1586 SAFE_DELETE(curlhost[i]);
1594 curl_share_cleanup(mCurlShared);
1605 SAFE_DELETE_ARRAY(mData);
1621 if (pausePositionMilliseconds != AAMP_PAUSE_POSITION_INVALID_POSITION)
1623 if (!aamp->mStreamSink->
Pause(
true,
false))
1625 AAMPLOG_ERR(
"Pause failed");
1636 bool updateSeekPosition =
false;
1637 if ((aamp->
rate > AAMP_NORMAL_PLAY_RATE) || (aamp->
rate < AAMP_RATE_PAUSE) ||
1641 aamp->trickStartUTCMS = -1;
1643 updateSeekPosition =
true;
1651 aamp->trickStartUTCMS = -1;
1653 updateSeekPosition =
true;
1659 if (updateSeekPosition)
1661 AAMPLOG_WARN(
"PLAYER[%d] Paused at position %lldms, requested position %lldms, rate %f, seek pos updated to %fs",
1666 AAMPLOG_WARN(
"PLAYER[%d] Paused at position %lldms, requested position %lldms, rate %f",
1667 aamp->mPlayerId, positionMs, pausePositionMilliseconds, aamp->
rate);
1673 return G_SOURCE_REMOVE;
1683 int previousPollPeriodMs = 0;
1684 int previousVodTrickplayFPS = 0;
1686 AAMPLOG_WARN(
"PLAYER[%d] Pause at position %lldms, current position %lldms, rate %f",
1689 while(localPauseAtMilliseconds != AAMP_PAUSE_POSITION_INVALID_POSITION)
1691 int pollPeriodMs = AAMP_PAUSE_POSITION_POLL_PERIOD_MS;
1692 long long trickplayTargetPosMs = localPauseAtMilliseconds;
1693 bool forcePause =
false;
1698 AAMPLOG_WARN(
"Already paused, exiting loop");
1703 else if ((
rate > AAMP_RATE_PAUSE) && (
rate <= AAMP_NORMAL_PLAY_RATE))
1708 if (posMs >= (localPauseAtMilliseconds - pollPeriodMs))
1710 pollPeriodMs = (localPauseAtMilliseconds - posMs) /
rate;
1712 AAMPLOG_INFO(
"Requested pos %lldms current pos %lldms rate %f, pausing in %dms",
1713 localPauseAtMilliseconds, posMs,
rate, pollPeriodMs);
1718 if (previousPollPeriodMs != pollPeriodMs)
1720 AAMPLOG_WARN(
"PLAYER[%d] Polling period %dms, rate %f",
1721 mPlayerId, pollPeriodMs,
rate);
1722 previousPollPeriodMs = pollPeriodMs;
1724 AAMPLOG_INFO(
"Requested pos %lldms current pos %lldms rate %f, polling period %dms",
1725 localPauseAtMilliseconds, posMs,
rate, pollPeriodMs);
1730 int vodTrickplayFPS = 0;
1733 assert (config_valid && (vodTrickplayFPS != 0));
1736 pollPeriodMs = (1000 / vodTrickplayFPS) / 2;
1740 trickplayTargetPosMs -= ((
rate * 1000) / vodTrickplayFPS);
1742 if ((previousPollPeriodMs != pollPeriodMs) ||
1743 (previousVodTrickplayFPS != vodTrickplayFPS))
1745 AAMPLOG_WARN(
"PLAYER[%d] Polling period %dms, rate %f, fps %d",
1746 mPlayerId, pollPeriodMs,
rate, vodTrickplayFPS);
1747 previousPollPeriodMs = pollPeriodMs;
1748 previousVodTrickplayFPS = vodTrickplayFPS;
1750 AAMPLOG_INFO(
"Requested pos %lldms current pos %lldms target pos %lld rate %f, fps %d, polling period %dms",
1751 localPauseAtMilliseconds, posMs, trickplayTargetPosMs,
rate, vodTrickplayFPS, pollPeriodMs);
1755 if (pollPeriodMs > 0)
1757 std::unique_lock<std::mutex> lock(mPausePositionMonitorMutex);
1758 std::cv_status cvStatus = std::cv_status::no_timeout;
1759 std::chrono::time_point<std::chrono::system_clock> waitUntilMs = std::chrono::system_clock::now() +
1760 std::chrono::milliseconds(pollPeriodMs);
1763 while ((localPauseAtMilliseconds != AAMP_PAUSE_POSITION_INVALID_POSITION) &&
1764 (cvStatus == std::cv_status::no_timeout))
1766 cvStatus = mPausePositionMonitorCV.wait_until(lock, waitUntilMs);
1769 if (localPauseAtMilliseconds == AAMP_PAUSE_POSITION_INVALID_POSITION)
1783 ((
rate > AAMP_NORMAL_PLAY_RATE) && (posMs >= trickplayTargetPosMs)) ||
1784 ((
rate < AAMP_RATE_PAUSE) && (posMs <= trickplayTargetPosMs)))
1800 if(aamp_pthread_setname(pthread_self(),
"aampPauseMon"))
1802 AAMPLOG_WARN(
"aamp_pthread_setname failed");
1815 if (pausePositionMilliseconds < 0)
1817 AAMPLOG_ERR(
"The position (%lld) must be >= 0", pausePositionMilliseconds);
1823 AAMPLOG_INFO(
"Start PausePositionMonitoring at position %lld", pausePositionMilliseconds);
1825 if (0 == pthread_create(&mPausePositionMonitoringThreadID,
nullptr, &
PausePositionMonitor,
this))
1827 mPausePositionMonitoringThreadStarted =
true;
1831 AAMPLOG_ERR(
"Failed to create PausePositionMonitor thread");
1841 if (mPausePositionMonitoringThreadStarted)
1843 std::unique_lock<std::mutex> lock(mPausePositionMonitorMutex);
1848 AAMPLOG_WARN(
"PLAYER[%d] Stop position monitoring, reason: '%s', current position %lldms, requested position %lldms, rate %f",
1851 mPausePositionMonitorCV.notify_one();
1855 int rc = pthread_join(mPausePositionMonitoringThreadID, NULL);
1858 AAMPLOG_ERR(
"***pthread_join PausePositionMonitor returned %d(%s)", rc, strerror(rc));
1862 AAMPLOG_INFO(
"Joined PausePositionMonitor");
1864 mPausePositionMonitoringThreadStarted =
false;
1895 pthread_mutex_lock(&
mLock);
1904 pthread_mutex_unlock(&
mLock);
1917 long long videoPTS = -1;
1919 if(bAddVideoBasePTS)
1920 videoPTS += mVideoBasePTS;
1921 AAMPLOG_WARN(
"Video-PTS=%lld, mVideoBasePTS=%lld Add VideoBase PTS[%d]",videoPTS,mVideoBasePTS,bAddVideoBasePTS);
1935 AAMPLOG_WARN(
"Progress reporting skipped whilst seeking.");
1945 double duration = durationSeconds * 1000.0;
1949 long long videoPTS = -1;
1950 double bufferedDuration = 0.0;
1951 bool bProcessEvent =
true;
1963 start = (culledSeconds*1000.0);
1970 end = start + duration;
1978 else if (position < start)
1992 videoPTS = mStreamSink->
GetVideoPTS() + mVideoBasePTS;
2002 if ((mReportProgressPosn == position) && !
pipeline_paused && beginningOfStream !=
true)
2006 bProcessEvent =
false;
2016 double reportFormatPosition = position;
2024 ProgressEventPtr evt = std::make_shared<ProgressEvent>(duration, reportFormatPosition, start, end, speed, videoPTS, bufferedDuration,
seiTimecode.c_str());
2026 if (trickStartUTCMS >= 0 && (bProcessEvent || mFirstProgress))
2030 mFirstProgress =
false;
2031 AAMPLOG_WARN(
"Send first progress event with position %ld", (
long)(reportFormatPosition / 1000));
2037 if ((tick++ % 4) == 0)
2039 AAMPLOG_WARN(
"aamp pos: [%ld..%ld..%ld..%lld..%ld..%s]",
2040 (
long)(start / 1000),
2041 (
long)(reportFormatPosition / 1000),
2043 (
long long) videoPTS,
2044 (
long)(bufferedDuration / 1000),
2058 mReportProgressPosn = position;
2069 if (mDownloadsEnabled && !mAdProgressId.empty())
2071 long long curTime = NOW_STEADY_TS_MS;
2075 mAdCurOffset += (uint32_t)(curTime - mAdPrevProgressTime);
2078 mAdPrevProgressTime = curTime;
2097 AAMPLOG_INFO(
"aamp_UpdateDuration(%f)", seconds);
2098 durationSeconds = seconds;
2106 if (culledSecs == 0)
2111 if((!this->culledSeconds) && culledSecs)
2113 AAMPLOG_WARN(
"PrivateInstanceAAMP: culling started, first value %f", culledSecs);
2116 this->culledSeconds += culledSecs;
2117 long long limitMs = (
long long) std::round(this->culledSeconds * 1000.0);
2119 for (
auto iter = timedMetadata.begin(); iter != timedMetadata.end(); )
2123 if (iter->_timeMS != 0 && iter->_timeMS < limitMs)
2127 iter = timedMetadata.erase(iter);
2138 for (
auto iter = contentGaps.begin(); iter != contentGaps.end();)
2140 if (iter->_timeMS != 0 && iter->_timeMS < limitMs)
2142 iter = contentGaps.erase(iter);
2161 double minPlaylistPositionToResume = (position < maxRefreshPlaylistIntervalSecs) ? position : (position - maxRefreshPlaylistIntervalSecs);
2162 if (this->culledSeconds >= position)
2165 && this->culledSeconds != culledSecs )
2175 AAMPLOG_WARN(
"Resume playback since playlist start position(%f) has moved past paused position(%f) ", this->culledSeconds, position);
2176 if (!mAutoResumeTaskPending)
2178 mAutoResumeTaskPending =
true;
2183 AAMPLOG_WARN(
"Auto resume playback task already exists, avoid creating duplicates for now!");
2198 else if (this->culledSeconds >= minPlaylistPositionToResume)
2205 if (culledSecs <= maxRefreshPlaylistIntervalSecs)
2213 AAMPLOG_WARN(
"Resume playback since start position(%f) moved very close to minimum resume position(%f) ", this->culledSeconds, minPlaylistPositionToResume);
2214 if (!mAutoResumeTaskPending)
2216 mAutoResumeTaskPending =
true;
2221 AAMPLOG_WARN(
"Auto resume playback task already exists, avoid creating duplicates for now!");
2235 AAMPLOG_WARN(
"Auto resume playback task already exists, avoid creating duplicates for now!");
2274 long error_code =
event->getResponseCode();
2275 bool isSecClientError =
event->getSecclientError();
2276 long secManagerReasonCode =
event->getSecManagerReasonCode();
2280 char description[128] = {};
2285 if (isSecClientError)
2289 snprintf(description, MAX_ERROR_DESCRIPTION_LENGTH - 1,
"%s : SecManager Error Code %ld:%ld", tuneFailureMap[tuneFailure].description,error_code, secManagerReasonCode);
2293 snprintf(description, MAX_ERROR_DESCRIPTION_LENGTH - 1,
"%s : Secclient Error Code %ld", tuneFailureMap[tuneFailure].description, error_code);
2298 snprintf(description, MAX_ERROR_DESCRIPTION_LENGTH - 1,
"%s : Curl Error Code %ld", tuneFailureMap[tuneFailure].description, error_code);
2303 snprintf(description, MAX_ERROR_DESCRIPTION_LENGTH - 1,
"%s : Access Token Parse Error", tuneFailureMap[tuneFailure].description);
2307 snprintf(description, MAX_ERROR_DESCRIPTION_LENGTH - 1,
"%s : Invalid status code", tuneFailureMap[tuneFailure].description);
2311 snprintf(description, MAX_ERROR_DESCRIPTION_LENGTH - 1,
"%s : Http Error Code %ld", tuneFailureMap[tuneFailure].description, error_code);
2313 SendErrorEvent(tuneFailure, description, isRetryEnabled, event->getSecManagerClassCode(),event->getSecManagerReasonCode(), event->getBusinessStatus());
2317 SendErrorEvent(tuneFailure, NULL, isRetryEnabled, event->getSecManagerClassCode(),event->getSecManagerReasonCode(), event->getBusinessStatus());
2321 AAMPLOG_WARN(
"Received unknown error event %d", tuneFailure);
2333 bool retryStatus =
true;
2337 char description[MAX_DESCRIPTION_SIZE] = {};
2338 if (((error_code >= PARTIAL_FILE_CONNECTIVITY_AAMP) && (error_code <= PARTIAL_FILE_START_STALL_TIMEOUT_AAMP)) || error_code == CURLE_OPERATION_TIMEDOUT)
2342 case PARTIAL_FILE_DOWNLOAD_TIME_EXPIRED_AAMP:
2343 error_code = CURLE_PARTIAL_FILE;
2344 case CURLE_OPERATION_TIMEDOUT:
2345 snprintf(description,MAX_DESCRIPTION_SIZE,
"%s : Curl Error Code %ld, Download time expired", tuneFailureMap[tuneFailure].description, error_code);
2347 case PARTIAL_FILE_START_STALL_TIMEOUT_AAMP:
2348 snprintf(description,MAX_DESCRIPTION_SIZE,
"%s : Curl Error Code %d, Start/Stall timeout", tuneFailureMap[tuneFailure].description, CURLE_PARTIAL_FILE);
2350 case OPERATION_TIMEOUT_CONNECTIVITY_AAMP:
2351 snprintf(description,MAX_DESCRIPTION_SIZE,
"%s : Curl Error Code %d, Connectivity failure", tuneFailureMap[tuneFailure].description, CURLE_OPERATION_TIMEDOUT);
2353 case PARTIAL_FILE_CONNECTIVITY_AAMP:
2354 snprintf(description,MAX_DESCRIPTION_SIZE,
"%s : Curl Error Code %d, Connectivity failure", tuneFailureMap[tuneFailure].description, CURLE_PARTIAL_FILE);
2358 else if(error_code < 100)
2360 snprintf(description,MAX_DESCRIPTION_SIZE,
"%s : Curl Error Code %ld", tuneFailureMap[tuneFailure].description, error_code);
2364 snprintf(description,MAX_DESCRIPTION_SIZE,
"%s : Http Error Code %ld", tuneFailureMap[tuneFailure].description, error_code);
2365 if (error_code == 404)
2369 else if (error_code == 421)
2371 retryStatus =
false;
2376 strcat(description,
"(FOG)");
2383 AAMPLOG_WARN(
"Received unknown error event %d", tuneFailure);
2396 va_start(args, format);
2398 char msgData[MAX_ANOMALY_BUFF_SIZE];
2400 msgData[(MAX_ANOMALY_BUFF_SIZE-1)] = 0;
2401 vsnprintf(msgData, (MAX_ANOMALY_BUFF_SIZE-1), format, args);
2403 AnomalyReportEventPtr e = std::make_shared<AnomalyReportEvent>(type, msgData);
2405 AAMPLOG_INFO(
"Anomaly evt:%d msg:%s", e->getSeverity(), msgData);
2417 AAMPLOG_INFO(
"maxRefreshPlaylistIntervalSecs (%f)", maxIntervalSecs);
2418 maxRefreshPlaylistIntervalSecs = maxIntervalSecs;
2430 BufferingChangedEventPtr e = std::make_shared<BufferingChangedEvent>(!bufferingStopped);
2432 SetBufUnderFlowStatus(bufferingStopped);
2433 AAMPLOG_INFO(
"PrivateInstanceAAMP: Sending Buffer Change event status (Buffering): %s", (e->buffering() ?
"End":
"Start"));
2442 if (
true != mStreamSink->
Pause(pause, forceStopGstreamerPreBuffering))
2456 bool sendErrorEvent =
false;
2457 pthread_mutex_lock(&
mLock);
2464 std::string remoteUrl =
"127.0.0.1:9080/tsb";
2465 long http_error = -1;
2468 sendErrorEvent =
true;
2471 pthread_mutex_unlock(&
mLock);
2475 const char *errorDescription = NULL;
2481 GETCONFIGVALUE_PRIV(eAAMPConfig_StallErrorCode,code);
2485 code = tuneFailureMap[tuneFailure].
code;
2489 errorDescription = description;
2493 errorDescription = tuneFailureMap[tuneFailure].
description;
2502 MediaErrorEventPtr e = std::make_shared<MediaErrorEvent>(tuneFailure, code, errorDescription, isRetryEnabled, secManagerClassCode, secManagerReasonCode, secClientBusinessStatus);
2504 if (!mAppName.empty())
2506 AAMPLOG_ERR(
"%s PLAYER[%d] APP: %s Sending error %s",(
mbPlayEnabled?STRFGPLAYER:STRBGPLAYER), mPlayerId, mAppName.c_str(), e->getDescription().c_str());
2510 AAMPLOG_ERR(
"%s PLAYER[%d] Sending error %s",(
mbPlayEnabled?STRFGPLAYER:STRBGPLAYER), mPlayerId, e->getDescription().c_str());
2513 if (
rate != AAMP_NORMAL_PLAY_RATE)
2523 AAMPLOG_WARN(
"PrivateInstanceAAMP: Ignore error %d[%s]", (
int)tuneFailure, description);
2542 AAMPEventPtr
event = std::make_shared<BitrateChangeEvent>((
int)
aamp_GetCurrentTimeMS(), bitrate, BITRATEREASON2STRING(reason), width, height, frameRate, position,
mProfileCappedStatus,
mDisplayWidth,
mDisplayHeight, scantype, aspectRatioWidth, aspectRatioHeight);
2547 AAMPLOG_WARN(
"NotifyBitRateChangeEvent :: bitrate:%d desc:%s width:%d height:%d fps:%f position:%f IndexFromTopProfile: %d%s profileCap:%d tvWidth:%d tvHeight:%d, scantype:%d, aspectRatioW:%d, aspectRatioH:%d",
2548 bitrate, BITRATEREASON2STRING(reason), width, height, frameRate, position,
mpStreamAbstractionAAMP->
GetBWIndex(bitrate), (
IsTSBSupported()?
", fog":
" "),
mProfileCappedStatus,
mDisplayWidth,
mDisplayHeight, scantype, aspectRatioWidth, aspectRatioHeight);
2552 AAMPLOG_WARN(
"NotifyBitRateChangeEvent :: bitrate:%d desc:%s width:%d height:%d fps:%f position:%f %s profileCap:%d tvWidth:%d tvHeight:%d, scantype:%d, aspectRatioW:%d, aspectRatioH:%d",
2553 bitrate, BITRATEREASON2STRING(reason), width, height, frameRate, position, (
IsTSBSupported()?
", fog":
" "),
mProfileCappedStatus,
mDisplayWidth,
mDisplayHeight, scantype, aspectRatioWidth, aspectRatioHeight);
2564 AAMPLOG_WARN(
"NotifyBitRateChangeEvent ::NO LISTENERS bitrate:%d desc:%s width:%d height:%d, fps:%f position:%f IndexFromTopProfile: %d%s profileCap:%d tvWidth:%d tvHeight:%d, scantype:%d, aspectRatioW:%d, aspectRatioH:%d",
2565 bitrate, BITRATEREASON2STRING(reason), width, height, frameRate, position,
mpStreamAbstractionAAMP->
GetBWIndex(bitrate), (
IsTSBSupported()?
", fog":
" "),
mProfileCappedStatus,
mDisplayWidth,
mDisplayHeight, scantype, aspectRatioWidth, aspectRatioHeight);
2569 AAMPLOG_WARN(
"NotifyBitRateChangeEvent ::NO LISTENERS bitrate:%d desc:%s width:%d height:%d fps:%f position:%f %s profileCap:%d tvWidth:%d tvHeight:%d, scantype:%d, aspectRatioW:%d, aspectRatioH:%d",
2570 bitrate, BITRATEREASON2STRING(reason), width, height, frameRate, position, (
IsTSBSupported()?
", fog":
" "),
mProfileCappedStatus,
mDisplayWidth,
mDisplayHeight, scantype, aspectRatioWidth, aspectRatioHeight);
2575 AAMPLOG_WARN(
"BitrateChanged:%d", reason);
2595 else if (
rate == AAMP_NORMAL_PLAY_RATE)
2597 if (mTrickplayInProgress)
2599 mTrickplayInProgress =
false;
2613 mTrickplayInProgress =
true;
2622 #ifdef AAMP_CC_ENABLED
2625 if (
rate == AAMP_NORMAL_PLAY_RATE)
2645 #ifdef USE_SECMANAGER
2659 AAMPLOG_WARN(
"SendDRMMetaData name = %s value = %x", e->getAccessStatus().c_str(), e->getAccessStatusValue());
2669 return (vidDiscontinuity || audDiscontinuity);
2681 if (mDiscontinuityTuneOperationInProgress)
2684 AAMPLOG_WARN(
"PrivateInstanceAAMP: Discontinuity Tune Operation already in progress");
2698 mDiscontinuityTuneOperationInProgress =
true;
2703 bool continueDiscontProcessing =
true;
2704 AAMPLOG_WARN(
"PrivateInstanceAAMP: mProcessingDiscontinuity set");
2716 double startTimeofFirstSample = 0;
2717 AAMPLOG_WARN(
"PrivateInstanceAAMP: last injected position:%f position calcualted: %f", injectedPosition, newPosition);
2735 if(startTimeofFirstSample > 0)
2737 AAMPLOG_WARN(
"PrivateInstanceAAMP: Position is updated to start time of discontinuity : %lf", startTimeofFirstSample);
2741 AAMPLOG_WARN(
"PrivateInstanceAAMP: Updated seek_pos_seconds:%f",
seek_pos_seconds);
2743 trickStartUTCMS = -1;
2746 mProgressReportFromProcessDiscontinuity =
true;
2755 AAMPLOG_WARN(
"Progress event sent as part of ProcessPendingDiscontinuity, mDiscontinuityTuneOperationInProgress:%d", mDiscontinuityTuneOperationInProgress);
2756 mProgressReportFromProcessDiscontinuity =
false;
2757 continueDiscontProcessing = mDiscontinuityTuneOperationInProgress;
2760 if (continueDiscontProcessing)
2765 #ifndef AAMP_STOP_SINK_ON_SEEK
2771 mStreamSink->
Stop(
true);
2790 AAMPLOG_WARN(
"PrivateInstanceAAMP: mDiscontinuityTuneOperationInProgress was reset during operation, since other command received from app!");
2797 mDiscontinuityTuneOperationInProgress =
false;
2818 AAMPLOG_INFO(
"Found AC4 track as current Audio track index = %s language - %s role - %s codec %s type %s bandwidth = %ld",
2819 currentAudioTrack.
index.c_str(), currentAudioTrack.
language.c_str(), currentAudioTrack.
rendition.c_str(),
2821 trackId = std::stoi( currentAudioTrack.
index );
2836 AAMPLOG_WARN(
"Enter . processingDiscontinuity %d isLive %d", isDiscontinuity, isLive);
2838 if (!isDiscontinuity)
2848 AAMPLOG_ERR(
"null Stream Abstraction AAMP");
2854 AAMPLOG_ERR(
"Bogus EOS event received from GStreamer, discarding it!");
2857 if (!isLive &&
rate > 0)
2863 mStreamSink->
Stop(
false);
2866 trickStartUTCMS = -1;
2874 if (trickStartUTCMS == -1)
2879 AAMPLOG_INFO(
"Resetting trickStartUTCMS to %lld since no first frame on trick play rate %f", trickStartUTCMS,
rate);
2883 rate = AAMP_NORMAL_PLAY_RATE;
2890 rate = AAMP_NORMAL_PLAY_RATE;
2901 pthread_cond_signal(&mCondDiscontinuity);
2903 AAMPLOG_WARN(
"PrivateInstanceAAMP: EOS due to discontinuity handled");
2912 if (discardEnteringLiveEvt)
2935 return "unknown track type";
2946 std::string downloadsBlockedMessage =
"Downloads";
2947 if (!mbDownloadsBlocked)
2949 downloadsBlockedMessage +=
" not";
2951 downloadsBlockedMessage +=
" blocked, track download status: ";
2955 if (!mbTrackDownloadsBlocked[i])
2957 downloadsBlockedMessage +=
" not";
2959 downloadsBlockedMessage +=
" blocked, ";
2961 AAMPLOG_WARN(
"%s", downloadsBlockedMessage.c_str());
2965 std::string injectionBlockedMessage =
"Track injection status: ";
2969 if (!mTrackInjectionBlocked[i])
2971 injectionBlockedMessage +=
" not";
2973 injectionBlockedMessage +=
" blocked, ";
2975 AAMPLOG_WARN(
"%s", injectionBlockedMessage.c_str());
2980 std::string trackBufferStatusMessage =
"Track buffer status: ";
2985 if(
nullptr != track)
2988 trackBufferStatusMessage +=
" ";
2992 trackBufferStatusMessage +=
"green";
2995 trackBufferStatusMessage +=
"yellow";
2998 trackBufferStatusMessage +=
"red";
3001 trackBufferStatusMessage +=
"unknown";
3007 trackBufferStatusMessage +=
"invalid track";
3009 trackBufferStatusMessage +=
", ";
3011 AAMPLOG_WARN(
"%s", trackBufferStatusMessage.c_str());
3023 mTuneMetrics.mTotalTime = NOW_STEADY_TS_MS ;
3031 mTuneMetrics.contentType = mContentType;
3051 mTuneMetrics.contentType = mContentType;
3065 if (!mTuneCompleted)
3075 mTuneCompleted =
true;
3079 if(mTuneAttempts > 1 )
3089 playbackType.append(
":TSB=true");
3093 playbackType.append(
":TSB=false");
3151 if (!mbDownloadsBlocked)
3153 pthread_mutex_lock(&
mLock);
3154 mbDownloadsBlocked =
true;
3155 pthread_mutex_unlock(&
mLock);
3166 if (mbDownloadsBlocked)
3168 pthread_mutex_lock(&
mLock);
3169 mbDownloadsBlocked =
false;
3171 pthread_mutex_unlock(&
mLock);
3181 #ifdef AAMP_DEBUG_FETCH_INJECT
3182 if ((1 << type) & AAMP_DEBUG_FETCH_INJECT)
3184 AAMPLOG_WARN (
"PrivateInstanceAAMP: Enter. type = %d", (
int) type);
3187 if (!mbTrackDownloadsBlocked[type])
3189 AAMPLOG_TRACE(
"gstreamer-enough-data from source[%d]", type);
3190 pthread_mutex_lock(&
mLock);
3191 mbTrackDownloadsBlocked[type] =
true;
3192 pthread_mutex_unlock(&
mLock);
3195 AAMPLOG_TRACE (
"PrivateInstanceAAMP:: Enter. type = %d", (
int) type);
3204 #ifdef AAMP_DEBUG_FETCH_INJECT
3205 if ((1 << type) & AAMP_DEBUG_FETCH_INJECT)
3207 AAMPLOG_WARN (
"PrivateInstanceAAMP: Enter. type = %d", (
int) type);
3210 if (mbTrackDownloadsBlocked[type])
3212 AAMPLOG_TRACE(
"gstreamer-needs-data from source[%d]", type);
3213 pthread_mutex_lock(&
mLock);
3214 mbTrackDownloadsBlocked[type] =
false;
3216 pthread_mutex_unlock(&
mLock);
3218 AAMPLOG_TRACE (
"PrivateInstanceAAMP::Exit. type = %d", (
int) type);
3226 AAMPLOG_TRACE(
"PrivateInstanceAAMP::Enter. type = %d and downloads:%d", track, mbTrackDownloadsBlocked[track]);
3228 while (mbDownloadsBlocked || mbTrackDownloadsBlocked[track])
3230 if (!mDownloadsEnabled || mTrackInjectionBlocked[track])
3232 AAMPLOG_WARN(
"PrivateInstanceAAMP: interrupted. mDownloadsEnabled:%d mTrackInjectionBlocked:%d", mDownloadsEnabled, mTrackInjectionBlocked[track]);
3237 if (elapsedMs >= periodMs)
3240 elapsedMs -= periodMs;
3246 AAMPLOG_TRACE(
"PrivateInstanceAAMP::Exit. type = %d", track);
3254 int instanceEnd = startIdx + instanceCount;
3255 std::string UserAgentString;
3256 UserAgentString=mConfig->GetUserAgentString();
3268 int langCount = langlist.size();
3269 if (langCount > MAX_LANGUAGE_COUNT)
3271 langCount = MAX_LANGUAGE_COUNT;
3273 mMaxLanguageCount = langCount;
3274 std::set<std::string>::const_iterator iter = langlist.begin();
3275 for (
int cnt = 0; cnt < langCount; cnt++, iter++)
3277 strncpy(
mLanguageList[cnt], iter->c_str(), MAX_LANGUAGE_TAG_LENGTH);
3279 if( this->mVideoEnd )
3281 mVideoEnd->Setlanguage(VideoStatTrackType::STAT_AUDIO, (*iter), cnt+1);
3292 for (
int cnt=0; cnt < mMaxLanguageCount; cnt ++)
3294 if(strncmp(
mLanguageList[cnt], checkLanguage, MAX_LANGUAGE_TAG_LENGTH) == 0)
3301 if(mMaxLanguageCount == 0)
3303 AAMPLOG_WARN(
"IsAudioLanguageSupported No Audio language stored !!!");
3307 AAMPLOG_WARN(
"IsAudioLanguageSupported lang[%s] not available in list",checkLanguage);
3321 CURL_EASY_SETOPT(curl[instance], CURLOPT_TIMEOUT_MS, timeoutMS);
3326 AAMPLOG_WARN(
"Failed to update timeout for curl instace %d",instance);
3335 int instanceEnd = startIdx + instanceCount;
3343 if(curlhost[i]->curl)
3347 curlhost[i]->isRemotehost=
true;
3348 curlhost[i]->redirect=
true;
3363 bool indivCurlInstanceFlag =
false;
3374 if(indivCurlInstanceFlag)
3403 pthread_mutex_lock(&
mLock);
3404 if (mAbrBitrateData.size())
3406 mAbrBitrateData.erase(mAbrBitrateData.begin(),mAbrBitrateData.end());
3408 pthread_mutex_unlock(&
mLock);
3424 std::vector< long> tmpData;
3426 pthread_mutex_lock(&
mLock);
3427 mhAbrManager.UpdateABRBitrateDataBasedOnCacheLife(mAbrBitrateData,tmpData);
3428 pthread_mutex_unlock(&
mLock);
3433 ret =
mhAbrManager.UpdateABRBitrateDataBasedOnCacheOutlier(tmpData);
3434 mAvailableBandwidth = ret;
3441 ABRManager::setPersistBandwidth(mAvailableBandwidth );
3481 return "PLAYLIST_VIDEO";
3483 return "PLAYLIST_AUDIO";
3485 return "PLAYLIST_SUBTITLE";
3487 return "PLAYLIST_AUX-AUDIO";
3503 if(eCURL_GET != request)
3506 CURL *curl = curl_easy_init();
3514 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
3516 curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L);
3517 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &context);
3518 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
3521 curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER);
3522 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
3524 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
3528 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
3531 curl_easy_setopt(curl, CURLOPT_URL, remoteUrl.c_str());
3533 res = curl_easy_perform(curl);
3534 if (res == CURLE_OK)
3536 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
3537 if ((httpCode == 204) || (httpCode == 200))
3542 currentTime = time(0);
3543 struct tm *localTime;
3544 localTime = localtime(¤tTime);
3546 stGMT = gmtime(¤tTime);
3547 time_t currentTimeGMT;
3548 currentTimeGMT = mktime(stGMT);
3552 const char* format =
"%Y-%m-%dT%H:%M:%SZ";
3553 mTime = convertTimeToEpoch((
const char*)buffer.ptr, format);
3554 AAMPLOG_WARN(
"ProducerReferenceTime Wallclock (Epoch): [%ld]", mTime);
3563 AAMPLOG_ERR(
" Returned [%d]", httpCode);
3568 AAMPLOG_ERR(
"Failed to perform curl request, result:%d", res);
3573 *http_error = httpCode;
3576 curl_easy_cleanup(curl);
3586 long * http_error,
double *downloadTime,
const char *range,
unsigned int curlInstance,
3587 bool resetBuffer,
MediaType fileType,
long *bitrate,
int * fogError,
3588 double fragmentDurationSeconds,CMCDHeaders *pCMCDMetrics)
3592 std::unordered_map<std::string, std::vector<std::string>> mCMCDCustomHeaders;
3596 pCMCDMetrics->BuildCMCDCustomHeaders(mCMCDCustomHeaders);
3599 long http_code = -1;
3600 double fileDownloadTime = 0;
3602 int downloadAttempt = 0;
3603 int maxDownloadAttempt = 1;
3604 CURL* curl = this->curl[curlInstance];
3605 struct curl_slist* httpHeaders = NULL;
3606 CURLcode res = CURLE_OK;
3607 int fragmentDurationMs = (int)(fragmentDurationSeconds*1000);
3610 int InitFragmentRetryCount;
3612 maxDownloadAttempt += InitFragmentRetryCount;
3623 AAMPLOG_TRACE(
"reset buffer %p avail %d", buffer, (
int)buffer->avail);
3625 memset(buffer, 0x00,
sizeof(*buffer));
3627 if (mDownloadsEnabled)
3629 int downloadTimeMS = 0;
3630 bool isDownloadStalled =
false;
3632 double connectTime = 0;
3633 pthread_mutex_unlock(&
mLock);
3634 std::string uriParameter;
3639 if (remoteUrl.find(
"?") == std::string::npos)
3641 uriParameter[0] =
'?';
3644 remoteUrl.append(uriParameter.c_str());
3650 if( curlhost[curlInstance]->isRemotehost && curlhost[curlInstance]->redirect &&
3651 ( NULL == curlhost[curlInstance]->curl || std::string::npos == remoteUrl.find(curlhost[curlInstance]->hostname)) )
3653 if(NULL != curlhost[curlInstance]->curl)
3659 curlhost[curlInstance]->isRemotehost =!(
aamp_IsLocalHost(curlhost[curlInstance]->hostname));
3660 curlhost[curlInstance]->redirect =
false;
3662 if( curlhost[curlInstance]->isRemotehost && (std::string::npos ==
mOrigManifestUrl.hostname.find(curlhost[curlInstance]->hostname)) )
3665 CURL_EASY_SETOPT(curlhost[curlInstance]->curl, CURLOPT_TIMEOUT_MS,
curlDLTimeout[curlInstance]);
3669 if ( curlhost[curlInstance]->curl )
3670 curl=curlhost[curlInstance]->curl;
3673 AAMPLOG_INFO(
"aamp url:%d,%d,%d,%f,%s", mediaType, simType, curlInstance,fragmentDurationSeconds, remoteUrl.c_str());
3677 CURL_EASY_SETOPT(curl, CURLOPT_URL, remoteUrl.c_str());
3680 CURL_EASY_SETOPT(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
3681 context.remoteUrl = remoteUrl;
3683 context.aamp =
this;
3684 context.buffer = buffer;
3685 context.responseHeaderData = &httpRespHeaders[curlInstance];
3686 context.fileType = simType;
3690 CURL_EASY_SETOPT(curl, CURLOPT_WRITEDATA, &context);
3691 CURL_EASY_SETOPT(curl, CURLOPT_HEADERDATA, &context);
3695 CURL_EASY_SETOPT(curl, CURLOPT_SSL_VERIFYHOST, 0L);
3696 CURL_EASY_SETOPT(curl, CURLOPT_SSL_VERIFYPEER, 0L);
3701 CURL_EASY_SETOPT(curl, CURLOPT_SSL_VERIFYPEER, 1L);
3705 progressCtx.aamp =
this;
3706 progressCtx.fileType = simType;
3707 progressCtx.dlStarted =
true;
3708 progressCtx.fragmentDurationMs = fragmentDurationMs;
3713 progressCtx.remoteUrl = remoteUrl;
3723 progressCtx.startTimeout = 0;
3734 CURL_EASY_SETOPT(curl, CURLOPT_RANGE, range);
3736 if ((httpRespHeaders[curlInstance].type ==
eHTTPHEADERTYPE_COOKIE) && (httpRespHeaders[curlInstance].data.length() > 0))
3740 CURL_EASY_SETOPT(curl, CURLOPT_COOKIE, httpRespHeaders[curlInstance].data.c_str());
3744 std::string customHeader;
3745 std::string headerValue;
3746 for (std::unordered_map<std::string, std::vector<std::string>>::iterator it = mCMCDCustomHeaders.begin();it != mCMCDCustomHeaders.end(); it++)
3748 customHeader.clear();
3749 headerValue.clear();
3750 customHeader.insert(0, it->first);
3751 customHeader.push_back(
' ');
3752 if (it->first.compare(
"CMCD-Session:") == 0)
3754 headerValue = it->second.at(0);
3756 if (it->first.compare(
"CMCD-Object:") == 0)
3758 headerValue = it->second.at(0);
3760 if (it->first.compare(
"CMCD-Request:") == 0)
3762 headerValue = it->second.at(0);
3764 if (it->first.compare(
"CMCD-Status:") == 0)
3766 headerValue = it->second.at(0);
3768 customHeader.append(headerValue);
3769 httpHeaders = curl_slist_append(httpHeaders, customHeader.c_str());
3773 if (mCustomHeaders.size() > 0)
3775 std::string customHeader;
3776 std::string headerValue;
3777 for (std::unordered_map<std::string, std::vector<std::string>>::iterator it = mCustomHeaders.begin();
3778 it != mCustomHeaders.end(); it++)
3780 customHeader.clear();
3781 headerValue.clear();
3782 customHeader.insert(0, it->first);
3783 customHeader.push_back(
' ');
3784 headerValue = it->second.at(0);
3785 if (it->first.compare(
"X-MoneyTrace:") == 0)
3787 if (mTSBEnabled && !mIsFirstRequestToFOG)
3792 memset(buf,
'\0', 512);
3793 if (it->second.size() >= 2)
3795 snprintf(buf, 512,
"trace-id=%s;parent-id=%s;span-id=%lld",
3796 (
const char*)it->second.at(0).c_str(),
3797 (
const char*)it->second.at(1).c_str(),
3800 else if (it->second.size() == 1)
3802 snprintf(buf, 512,
"trace-id=%s;parent-id=%lld;span-id=%lld",
3803 (
const char*)it->second.at(0).c_str(),
3809 if (it->first.compare(
"Wifi:") == 0)
3811 if (
true == activeInterfaceWifi)
3820 customHeader.append(headerValue);
3821 httpHeaders = curl_slist_append(httpHeaders, customHeader.c_str());
3825 std::string customHeader;
3826 customHeader.clear();
3828 httpHeaders = curl_slist_append(httpHeaders, customHeader.c_str());
3829 customHeader.clear();
3831 httpHeaders = curl_slist_append(httpHeaders, customHeader.c_str());
3837 std::string customHeader;
3838 customHeader.clear();
3839 customHeader =
"Buffer: " +std::to_string(bufferedDuration);
3840 httpHeaders = curl_slist_append(httpHeaders, customHeader.c_str());
3845 std::string customHeader;
3846 customHeader.clear();
3847 customHeader =
"AudioBuffer: " +std::to_string(bufferedAudioDuration);
3848 httpHeaders = curl_slist_append(httpHeaders, customHeader.c_str());
3855 std::string customHeader;
3856 customHeader.clear();
3857 customHeader =
"BufferStarvation:";
3858 httpHeaders = curl_slist_append(httpHeaders, customHeader.c_str());
3864 std::string customheaderstr;
3866 if(!customheaderstr.empty())
3869 httpHeaders = curl_slist_append(httpHeaders, customheaderstr.c_str());
3875 std::string customHeader =
"4k: 1";
3878 customHeader =
"4k: 0";
3880 httpHeaders = curl_slist_append(httpHeaders, customHeader.c_str());
3883 if (httpHeaders != NULL)
3885 CURL_EASY_SETOPT(curl, CURLOPT_HTTPHEADER, httpHeaders);
3889 while(downloadAttempt < maxDownloadAttempt)
3891 progressCtx.downloadStartTime = NOW_STEADY_TS_MS;
3895 context.downloadStartTime = progressCtx.downloadStartTime;
3896 CURL_EASY_SETOPT(curl, CURLOPT_WRITEDATA, &context);
3897 CURL_EASY_SETOPT(curl, CURLOPT_HEADERDATA, &context);
3899 progressCtx.downloadUpdatedTime = -1;
3900 progressCtx.downloadSize = -1;
3901 progressCtx.abortReason = eCURL_ABORT_REASON_NONE;
3902 CURL_EASY_SETOPT(curl, CURLOPT_PROGRESSDATA, &progressCtx);
3903 if(buffer->ptr != NULL)
3905 AAMPLOG_TRACE(
"reset length. buffer %p avail %d", buffer, (
int)buffer->avail);
3909 isDownloadStalled =
false;
3910 abortReason = eCURL_ABORT_REASON_NONE;
3912 long long tStartTime = NOW_STEADY_TS_MS;
3913 CURLcode res = curl_easy_perform(curl);
3917 int insertDownloadDelay=0;
3918 GETCONFIGVALUE_PRIV(eAAMPConfig_DownloadDelay,insertDownloadDelay);
3920 if( insertDownloadDelay > 0 )
3926 long long tEndTime = NOW_STEADY_TS_MS;
3929 downloadTimeMS = (int)(tEndTime - tStartTime);
3930 bool loopAgain =
false;
3931 if (res == CURLE_OK)
3933 if( memcmp(remoteUrl.c_str(),
"file:", 5) == 0 )
3941 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
3943 char *effectiveUrlPtr = NULL;
3944 if (http_code != 200 && http_code != 204 && http_code != 206)
3949 if((http_code >= 500 && http_code != 502) && downloadAttempt < maxDownloadAttempt)
3951 int waitTimeBeforeRetryHttp5xxMSValue;
3954 AAMPLOG_WARN(
"Download failed due to Server error. Retrying Attempt:%d!", downloadAttempt);
3958 if(http_code == 204)
3962 AAMPLOG_WARN(
"Received Location header: '%s'", httpRespHeaders[curlInstance].data.c_str());
3963 effectiveUrlPtr =
const_cast<char *
>(httpRespHeaders[curlInstance].
data.c_str());
3969 if(mTSBEnabled && http_code == 302)
3971 mTSBEnabled =
false;
3973 res = curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effectiveUrlPtr);
3977 isobuf.
setBuffer(
reinterpret_cast<uint8_t *
>(context.buffer->ptr), context.buffer->len);
3979 bool bParse =
false;
3984 catch( std::bad_alloc& ba)
3986 AAMPLOG_ERR(
"Bad allocation: %s", ba.what() );
3988 catch( std::exception &e)
3990 AAMPLOG_ERR(
"Unhandled exception: %s", e.what() );
3994 AAMPLOG_ERR(
"Unknown exception");
3999 AAMPLOG_ERR(
"[%d] Cant Find TimeScale. No Box available in Init File !!!", simType);
4003 AAMPLOG_INFO(
"[%d] Buffer Length: %zu", simType, context.buffer->len);
4009 uint32_t timeScale = 0;
4013 AAMPLOG_INFO(
"Video TimeScale [%d]", timeScale);
4018 AAMPLOG_INFO(
"Audio TimeScale [%d]", timeScale);
4028 effectiveUrl.assign(effectiveUrlPtr);
4032 curlhost[curlInstance]->redirect =
true;
4037 if(mIsFirstRequestToFOG)
4041 AAMPLOG_INFO(
"TSB not avaialble from fog, playing from:%s ", effectiveUrl.c_str());
4050 if (fragmentDurationSeconds != 0.0)
4053 if (downloadTimeMS > fragmentDurationMs )
4069 isDownloadStalled = ((res == CURLE_PARTIAL_FILE) || (progressCtx.abortReason != eCURL_ABORT_REASON_NONE));
4071 abortReason = progressCtx.abortReason;
4075 if (AAMP_IS_LOG_WORTHY_ERROR(res) || progressCtx.abortReason != eCURL_ABORT_REASON_NONE)
4077 AAMP_LOG_NETWORK_ERROR (remoteUrl.c_str(),
AAMPNetworkErrorCurl, (
int)(progressCtx.abortReason == eCURL_ABORT_REASON_NONE ? res : CURLE_PARTIAL_FILE), simType);
4082 if((res == CURLE_COULDNT_CONNECT || res == CURLE_OPERATION_TIMEDOUT || (isDownloadStalled && (eCURL_ABORT_REASON_LOW_BANDWIDTH_TIMEDOUT != abortReason))) && downloadAttempt < maxDownloadAttempt)
4100 if( buffervalue == -1.0 || buffervalue == 0 || buffervalue*1000 > (curlDownloadTimeoutMS + fragmentDurationMs))
4110 long downloadbps = ((long)(buffer->len / downloadTimeMS)*8000);
4115 curlDownloadTimeoutMS = mNetworkTimeoutMs;
4120 AAMPLOG_WARN(
"Download failed due to curl timeout or isDownloadStalled:%d Retrying:%d Attempt:%d", isDownloadStalled, loopAgain, downloadAttempt);
4129 if( res == CURLE_FILE_COULDNT_READ_FILE )
4133 else if(abortReason == eCURL_ABORT_REASON_LOW_BANDWIDTH_TIMEDOUT)
4135 http_code = CURLE_OPERATION_TIMEDOUT;
4142 if (isDownloadStalled)
4144 AAMPLOG_INFO(
"Curl download stall detected - curl result:%d abortReason:%d downloadTimeMS:%lld curlTimeout:%ld", res, progressCtx.abortReason,
4145 downloadTimeMS, curlDownloadTimeoutMS);
4147 http_code = CURLE_PARTIAL_FILE;
4153 double total, connect, startTransfer, resolve, appConnect, preTransfer, redirect, dlSize;
4154 long reqSize, downloadbps = 0;
4156 if(downloadTimeMS != 0 && buffer->len != 0)
4157 downloadbps = ((long)(buffer->len / downloadTimeMS)*8000);
4159 curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME , &total);
4160 curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &connect);
4161 connectTime = connect;
4162 fileDownloadTime = total;
4163 if(res != CURLE_OK || http_code == 0 || http_code >= 400 || total > 2.0 )
4169 double totalPerformRequest = (double)(downloadTimeMS)/1000;
4170 curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME, &resolve);
4171 curl_easy_getinfo(curl, CURLINFO_APPCONNECT_TIME, &appConnect);
4172 curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &preTransfer);
4173 curl_easy_getinfo(curl, CURLINFO_STARTTRANSFER_TIME, &startTransfer);
4174 curl_easy_getinfo(curl, CURLINFO_REDIRECT_TIME, &redirect);
4175 curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &dlSize);
4176 curl_easy_getinfo(curl, CURLINFO_REQUEST_SIZE, &reqSize);
4179 pCMCDMetrics->SetNetworkMetrics((
int)(startTransfer*1000),(
int)(total*1000),(
int)(resolve*1000));
4182 std::string appName, timeoutClass;
4183 if (!mAppName.empty())
4186 appName = mAppName +
",";
4188 if (CURLE_OPERATION_TIMEDOUT == res || CURLE_PARTIAL_FILE == res || CURLE_COULDNT_CONNECT == res)
4192 timeoutClass =
"(" + to_string(reqSize > 0) +
")";
4194 AAMPLOG(mLogObj, reqEndLogLevel,
"WARN",
"HttpRequestEnd: %s%d,%d,%d%s,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%g,%ld,%ld,%ld,%.500s",
4195 appName.c_str(), mediaType, simType, http_code, timeoutClass.c_str(), totalPerformRequest, total, connect, startTransfer, resolve, appConnect, preTransfer, redirect, dlSize, reqSize,downloadbps,
4197 ((res == CURLE_OK) ? effectiveUrl.c_str() : remoteUrl.c_str()));
4198 if(ui32CurlTrace < 10 )
4200 AAMPLOG_INFO(
"%d.CurlTrace:Dns:%2.4f, Conn:%2.4f, Ssl:%2.4f, Redir:%2.4f, Pre:Start[%2.4f:%2.4f], Hdl:%p, Url:%s",
4201 ui32CurlTrace, resolve, connect, appConnect, redirect, preTransfer, startTransfer, curl,((res==CURLE_OK)?effectiveUrl.c_str():remoteUrl.c_str()));
4211 if (http_code == 200 || http_code == 206 || http_code == CURLE_OPERATION_TIMEDOUT)
4213 if (http_code == CURLE_OPERATION_TIMEDOUT && buffer->len > 0)
4215 AAMPLOG_WARN(
"Download timedout and obtained a partial buffer of size %zu for a downloadTime=%d and isDownloadStalled:%d", buffer->len, downloadTimeMS, isDownloadStalled);
4220 int AbrThresholdSize;
4228 long downloadbps =
mhAbrManager.CheckAbrThresholdSize(buffer->len,downloadTimeMS,currentProfilebps,fragmentDurationMs,hybridabortReason);
4229 pthread_mutex_lock(&
mLock);
4230 mhAbrManager.UpdateABRBitrateDataBasedOnCacheLength(mAbrBitrateData,downloadbps,
false);
4231 pthread_mutex_unlock(&
mLock);
4236 if (http_code == 200 || http_code == 206)
4248 std::string harvestPath;
4250 if(harvestPath.empty() )
4253 AAMPLOG_WARN(
"Harvest path has not configured, taking default path %s", harvestPath.c_str());
4261 double expectedContentLength = 0;
4262 if ((!context.downloadIsEncoded) && CURLE_OK==curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &expectedContentLength) && ((
int)expectedContentLength>0) && ((
int)expectedContentLength != (
int)buffer->len))
4265 AAMPLOG_WARN(
"AAMP Content-Length=%d actual=%d", (
int)expectedContentLength, (
int)buffer->len);
4269 memset(buffer, 0x00,
sizeof(*buffer));
4277 else if (remoteUrl.find(
"iframe") != std::string::npos)
4286 if (AAMP_IS_LOG_WORTHY_ERROR(res))
4288 AAMPLOG_WARN(
"BAD URL:%s", remoteUrl.c_str());
4291 memset(buffer, 0x00,
sizeof(*buffer));
4300 if( !(http_code == CURLE_ABORTED_BY_CALLBACK || http_code == CURLE_WRITE_ERROR || http_code == 204))
4303 MediaTypeString(fileType), (http_code < 100) ?
"Curl" :
"HTTP", http_code, remoteUrl.c_str());
4306 if ( (httpRespHeaders[curlInstance].type ==
eHTTPHEADERTYPE_XREASON) && (httpRespHeaders[curlInstance].data.length() > 0) )
4308 AAMPLOG_WARN(
"Received X-Reason header from %s: '%s'", mTSBEnabled?
"Fog":
"CDN Server", httpRespHeaders[curlInstance].data.c_str());
4311 else if ( (httpRespHeaders[curlInstance].type ==
eHTTPHEADERTYPE_FOG_REASON) && (httpRespHeaders[curlInstance].data.length() > 0) )
4317 std::regex errRegx(
"-(.*),");
4319 if (std::regex_search(httpRespHeaders[curlInstance].data, match, errRegx) && match.size() > 1) {
4320 if (!match.str(1).empty())
4322 *fogError = std::stoi(match.str(1));
4323 AAMPLOG_INFO(
"Received FOG-Reason fogError: '%d'", *fogError);
4329 if(!effectiveUrl.empty())
4331 std::regex fromRegx(
"from:(.*),");
4334 if (std::regex_search(httpRespHeaders[curlInstance].data, match, fromRegx) && match.size() > 1) {
4335 if (!match.str(1).empty())
4337 effectiveUrl.assign(match.str(1).c_str());
4338 AAMPLOG_INFO(
"Received FOG-Reason effectiveUrl: '%s'", effectiveUrl.c_str());
4344 AAMPLOG_WARN(
"Received FOG-Reason header: '%s'", httpRespHeaders[curlInstance].data.c_str());
4349 if (bitrate && (context.bitrate > 0))
4351 AAMPLOG_INFO(
"Received getfile Bitrate : %ld", context.bitrate);
4352 *bitrate = context.bitrate;
4355 if(abortReason != eCURL_ABORT_REASON_NONE && abortReason != eCURL_ABORT_REASON_LOW_BANDWIDTH_TIMEDOUT)
4357 http_code = PARTIAL_FILE_START_STALL_TIMEOUT_AAMP;
4359 else if (connectTime == 0.0)
4362 if(CURLE_PARTIAL_FILE == http_code)
4364 http_code = PARTIAL_FILE_CONNECTIVITY_AAMP;
4366 else if(CURLE_OPERATION_TIMEDOUT == http_code)
4368 http_code = OPERATION_TIMEOUT_CONNECTIVITY_AAMP;
4371 else if (CURLE_PARTIAL_FILE == http_code)
4374 http_code = PARTIAL_FILE_DOWNLOAD_TIME_EXPIRED_AAMP;
4376 pthread_mutex_lock(&
mLock);
4380 AAMPLOG_WARN(
"downloads disabled");
4382 pthread_mutex_unlock(&
mLock);
4385 *http_error = http_code;
4388 *downloadTime = fileDownloadTime;
4391 if (httpHeaders != NULL)
4393 curl_slist_free_all(httpHeaders);
4395 if (mIsFirstRequestToFOG)
4397 mIsFirstRequestToFOG =
false;
4404 AAMPLOG_INFO(
"*** Simulated Linear URL: %s\n", remoteUrl.c_str());
4411 if( full_playlist_video_ptr )
4415 free( full_playlist_video_ptr );
4416 full_playlist_video_ptr = NULL;
4417 full_playlist_video_len = 0;
4420 if( full_playlist_audio_ptr )
4424 free( full_playlist_audio_ptr );
4425 full_playlist_audio_ptr = NULL;
4426 full_playlist_audio_len = 0;
4435 if( !full_playlist_audio_ptr )
4439 full_playlist_audio_len = buffer->len;
4440 full_playlist_audio_ptr = (
char *)malloc(buffer->len);
4441 memcpy( full_playlist_audio_ptr, buffer->ptr, buffer->len );
4450 if( !full_playlist_video_ptr )
4454 full_playlist_video_len = buffer->len;
4455 full_playlist_video_ptr = (
char *)malloc(buffer->len);
4456 memcpy( full_playlist_video_ptr, buffer->ptr, buffer->len );
4470 AAMPLOG_INFO(
"Received HTTP 200 for ranged request (chunked iframe: %s: %s), starting to strip the fragment", range, remoteUrl.c_str() );
4474 if(2 == sscanf(range,
"%zu-%zu", &start, &end))
4477 size_t len = (end - start) + 1;
4478 if( buffer->len >= len)
4480 memmove(buffer->ptr, buffer->ptr + start, len);
4486 repair.
setBuffer((uint8_t *)buffer->ptr, buffer->len);
4488 AAMPLOG_INFO(
"Stripping the fragment for range request completed");
4492 AAMPLOG_ERR(
"Stripping the fragment for range request failed, failed to parse range string");
4495 catch (std::exception &e)
4497 AAMPLOG_ERR(
"Stripping the fragment for ranged request failed (%s)", e.what());
4511 std::string remoteUrl =
"127.0.0.1:9080/sessionstat";
4512 long http_error = -1;
4521 remoteUrl.append(
"/");
4527 AAMPLOG_INFO(
"curl request %s success", remoteUrl.c_str());
4528 cJSON *root = cJSON_Parse(data.
ptr);
4531 const char *error_ptr = cJSON_GetErrorPtr();
4532 if (error_ptr != NULL)
4534 AAMPLOG_ERR(
"Invalid Json format: %s", error_ptr);
4539 ret = cJSON_PrintUnformatted(root);
4547 AAMPLOG_ERR(
"curl request %s failed[%d]", remoteUrl.c_str(), http_error);
4564 CURL *curl = curl_easy_init();
4567 AAMPLOG_INFO(
"%s, %d", remoteUrl.c_str(), request);
4570 CURL_EASY_SETOPT(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER);
4571 CURL_EASY_SETOPT(curl, CURLOPT_FOLLOWLOCATION, 1L);
4575 CURL_EASY_SETOPT(curl, CURLOPT_SSL_VERIFYPEER, 0L);
4580 CURL_EASY_SETOPT(curl, CURLOPT_SSL_VERIFYPEER, 1L);
4582 CURL_EASY_SETOPT(curl, CURLOPT_URL, remoteUrl.c_str());
4584 if(eCURL_GET == request)
4587 memset(buffer, 0x00,
sizeof(*buffer));
4590 CURL_EASY_SETOPT(curl, CURLOPT_NOSIGNAL, 1L);
4593 CURL_EASY_SETOPT(curl, CURLOPT_PROGRESSDATA, &progressCtx);
4594 CURL_EASY_SETOPT(curl, CURLOPT_NOPROGRESS, 0L);
4595 CURL_EASY_SETOPT(curl, CURLOPT_WRITEDATA, &context);
4596 CURL_EASY_SETOPT(curl, CURLOPT_HTTPGET, 1L);
4597 res = curl_easy_perform(curl);
4599 else if(eCURL_DELETE == request)
4601 CURL_EASY_SETOPT(curl, CURLOPT_CUSTOMREQUEST,
"DELETE");
4602 res = curl_easy_perform(curl);
4604 else if(eCURL_POST == request)
4606 CURL_EASY_SETOPT(curl, CURLOPT_POSTFIELDSIZE, pData.size());
4607 CURL_EASY_SETOPT(curl, CURLOPT_POSTFIELDS,(uint8_t * )pData.c_str());
4608 res = curl_easy_perform(curl);
4611 if (res == CURLE_OK)
4613 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
4614 if ((httpCode == 204) || (httpCode == 200))
4620 AAMPLOG_ERR(
"Returned [%d]", httpCode);
4625 AAMPLOG_ERR(
"Failed to perform curl request, result:%d", res);
4630 *http_error = httpCode;
4633 curl_easy_cleanup(curl);
4643 pthread_mutex_lock(&
mLock);
4645 AAMPLOG_WARN(
" mProgressReportFromProcessDiscontinuity:%d mDiscontinuityTuneOperationId:%d newTune:%d", mProgressReportFromProcessDiscontinuity, mDiscontinuityTuneOperationId, newTune);
4646 if ((mDiscontinuityTuneOperationId != 0) && (!newTune || mState ==
eSTATE_IDLE))
4648 bool waitForDiscontinuityProcessing =
true;
4649 if (mProgressReportFromProcessDiscontinuity)
4651 AAMPLOG_WARN(
"TeardownStream invoked while mProgressReportFromProcessDiscontinuity and mDiscontinuityTuneOperationId[%d] set!", mDiscontinuityTuneOperationId);
4653 if ((callbackID != 0 && mDiscontinuityTuneOperationId == callbackID) || mAsyncTuneEnabled)
4655 AAMPLOG_WARN(
"TeardownStream idle callback id[%d] and mDiscontinuityTuneOperationId[%d] match. Ignore further discontinuity processing!", callbackID, mDiscontinuityTuneOperationId);
4656 waitForDiscontinuityProcessing =
false;
4657 mDiscontinuityTuneOperationInProgress =
false;
4658 mDiscontinuityTuneOperationId = 0;
4661 if (waitForDiscontinuityProcessing)
4664 if (mDiscontinuityTuneOperationInProgress)
4666 AAMPLOG_WARN(
"TeardownStream invoked while mDiscontinuityTuneOperationInProgress set. Wait until the Discontinuity Tune operation to complete!!");
4667 pthread_cond_wait(&mCondDiscontinuity, &
mLock);
4672 mDiscontinuityTuneOperationId = 0;
4677 else if (mProgressReportFromProcessDiscontinuity || mDiscontinuityTuneOperationInProgress)
4679 if(mDiscontinuityTuneOperationInProgress)
4681 AAMPLOG_WARN(
"TeardownStream invoked while mDiscontinuityTuneOperationInProgress set. Wait until the pending discontinuity tune operation to complete !!");
4682 pthread_cond_wait(&mCondDiscontinuity, &
mLock);
4686 AAMPLOG_WARN(
"TeardownStream invoked while mProgressReportFromProcessDiscontinuity set!");
4687 mDiscontinuityTuneOperationInProgress =
false;
4695 pthread_mutex_unlock(&
mLock);
4703 pthread_mutex_lock(&
mLock);
4705 pthread_mutex_unlock(&
mLock);
4706 if (streamerIsActive)
4708 #ifdef AAMP_STOP_SINK_ON_SEEK
4709 const bool forceStop =
true;
4713 CCHandleEventPtr
event = std::make_shared<CCHandleEvent>(0);
4715 AAMPLOG_WARN(
"Sent AAMP_EVENT_CC_HANDLE_RECEIVED with NULL handle");
4718 const bool forceStop =
false;
4726 #ifdef AAMP_CC_ENABLED
4727 AAMPLOG_INFO(
"before CC Release - mTuneType:%d mbPlayEnabled:%d ", mTuneType,
mbPlayEnabled);
4735 AAMPLOG_WARN(
"CC Release - skipped ");
4740 mStreamSink->
Stop(!newTune);
4748 mbTrackDownloadsBlocked[iTrack] =
true;
4750 streamerIsActive =
true;
4753 std::queue<AAMPEventPtr> emptyEvQ;
4765 bool retVal =
false;
4771 if(mkfifo(strAAMPPipeName, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) == -1)
4782 AAMPLOG_ERR(
"CreatePipe: Failed to create named pipe %s for reading errno = %d (%s)",
4783 strAAMPPipeName, errno, strerror(errno));
4796 m_fd = open(strAAMPPipeName, O_WRONLY | O_NONBLOCK );
4800 AAMPLOG_WARN(
"OpenPipe: Failed to open named pipe %s for writing errno = %d (%s)",
4801 strAAMPPipeName, errno, strerror(errno));
4833 int nWritten = write(m_fd, str, nToWrite);
4834 if(nWritten != nToWrite)
4837 AAMPLOG_WARN(
"Error writing data written = %d, size = %d errno = %d (%s)",
4838 nWritten, nToWrite, errno, strerror(errno));
4853 #ifdef CREATE_PIPE_SESSION_TO_XRE
4856 int dataLen = strlen(data);
4857 int sizeToSend = AAMP2ReceiverMsgHdrSz + dataLen;
4858 std::vector<uint8_t> tmp(sizeToSend,0);
4859 AAMP2ReceiverMsg *msg = (AAMP2ReceiverMsg *)(tmp.data());
4860 msg->type = (
unsigned int)type;
4861 msg->length = dataLen;
4862 memcpy(msg->data, data, dataLen);
4866 AAMPLOG_INFO(
"AAMP=>XRE: %s",data);
4879 lastUnderFlowTimeMs[i] = 0;
4887 if( seekWhilePaused )
4898 mSeekOperationInProgress =
true;
4903 tuneType = mTuneType;
4907 mTuneType = tuneType;
4922 AAMPLOG_INFO (
"Resetting mClearPipeline & mEncryptedPeriodFound");
4927 #if defined(AMLOGIC)
4942 if(mTuneAttempts == 1)
4951 durationSeconds = 60 * 60;
4952 rate = AAMP_NORMAL_PLAY_RATE;
4954 mTunedEventPending =
true;
4959 pInstance->Release();
4968 trickStartUTCMS = -1;
4971 AAMPLOG_INFO(
"playlistSeek : %f seek_pos_seconds:%f culledSeconds : %f ",playlistSeekPos,
seek_pos_seconds,culledSeconds);
4972 if (playlistSeekPos < 0)
4974 playlistSeekPos = 0;
4981 #if defined (INTELCE)
4982 AAMPLOG_WARN(
"Error: Dash playback not available");
5028 #ifdef USE_CPP_THUNDER_PLUGIN_ACCESS
5037 #endif //USE_CPP_THUNDER_PLUGIN_ACCESS
5048 AAMPLOG_ERR(
"Error: SmoothStreamingMedia playback not supported");
5085 AAMPLOG_WARN(
"PrivateInstanceAAMP: tune to end not supported for format");
5098 else if(mIsFakeTune)
5113 AAMPLOG_ERR(
"mpStreamAbstractionAAMP Init Failed.Error(%d)",retVal);
5154 int volume = audio_volume;
5161 if(startTimeOfDiscontinuity > 0)
5170 AAMPLOG_WARN(
"Position adjusted discontinuity start: %lf, Abs position: %lf", startTimeOfDiscontinuity,
seek_pos_seconds);
5173 culledOffset = culledSeconds;
5175 #ifndef AAMP_STOP_SINK_ON_SEEK
5176 AAMPLOG_WARN(
"Updated seek_pos_seconds %f culledSeconds :%f",
seek_pos_seconds,culledSeconds);
5179 AAMPLOG_INFO(
"TuneHelper : mVideoFormat %d, mAudioFormat %d mAuxFormat %d", mVideoFormat, mAudioFormat, mAuxFormat);
5190 &&
rate == AAMP_NORMAL_PLAY_RATE
5198 if( mSeekOperationInProgress && seekWhilePaused )
5204 #ifndef AAMP_STOP_SINK_ON_SEEK
5233 mStreamSink->
Flush(updatedSeekPosition,
rate);
5235 if (
rate > AAMP_NORMAL_PLAY_RATE)
5264 mSeekOperationInProgress =
false;
5268 if(!mStreamSink->
Pause(
true,
false))
5270 AAMPLOG_INFO(
"mStreamSink Pause failed");
5275 #ifdef AAMP_CC_ENABLED
5278 AAMPLOG_INFO(
"mCCId: %d",mCCId);
5305 if (newTune && !mIsFakeTune)
5326 mManifestUrl = mTsbSessionRequestUrl +
"&reloadTSB=true";
5328 long configPassCode = -1;
5333 if(configPassCode == 200 || configPassCode == 204 || configPassCode == 206)
5338 mIsFirstRequestToFOG = (mTSBEnabled ==
true);
5341 AAMPLOG_WARN(
"Reloading TSB, URL: %s", mManifestUrl.c_str());
5349 void PrivateInstanceAAMP::Tune(
const char *mainManifestUrl,
bool autoPlay,
const char *contentType,
bool bFirstAttempt,
bool bFinalAttempt,
const char *pTraceID,
bool audioDecoderStreamSync)
5351 int iCacheMaxSize = 0;
5352 int maxDrmSession = 1;
5360 const char *remapLicenseUrl = NULL;
5361 mainManifestUrl = remapUrl;
5363 if (remapLicenseUrl )
5365 AAMPLOG_INFO(
"Channel License Url Override: [%s]", remapLicenseUrl);
5370 mConfig->
CustomSearch(mainManifestUrl,mPlayerId,mAppName);
5402 if(mPlaylistTimeoutMs <= 0) mPlaylistTimeoutMs = mManifestTimeoutMs;
5406 mProgramDateTime = 0;
5407 mMPDPeriodsInfo.clear();
5417 mIsFakeTune = strcasestr(mainManifestUrl,
"fakeTune=true");
5425 mTSBEnabled = strcasestr(mainManifestUrl,
"tsb?") && ISCONFIGSET_PRIV(
eAAMPConfig_Fog);
5426 SETCONFIGVALUE_PRIV(AAMP_STREAM_SETTING,
eAAMPConfig_InterruptHandling, (mTSBEnabled && strcasestr(mainManifestUrl,
"networkInterruption=true")));
5429 AAMPLOG_INFO(
"Absolute timeline reporting enabled for interrupt enabled TSB stream");
5445 if (STARTS_WITH_IGNORE_CASE(mAppName.c_str(),
"peacock"))
5447 if(NULL == mAampCacheHandler)
5451 #if defined(AAMP_MPD_DRM) || defined(AAMP_HLS_DRM)
5454 if(NULL == mDRMSessionManager)
5492 if (NULL == mStreamSink)
5500 static bool gstPluginsInitialized =
false;
5503 gstPluginsInitialized =
true;
5515 AAMPLOG_WARN(
"AutoPlay disabled; Just caching the stream now.");
5534 AAMPLOG_WARN(
"PrivateInstanceAAMP: seek position already set, so eTUNETYPE_NEW_SEEK");
5544 httpRespHeaders[i].
data.clear();
5549 std::string customLicenseHeaderStr;
5551 if(!customLicenseHeaderStr.empty())
5555 AAMPLOG_WARN(
"CustomHeader :%s",customLicenseHeaderStr.c_str());
5558 char* tokenHeader = NULL;
5559 char* str = (
char*) customLicenseHeaderStr.c_str();
5561 while ((token = strtok_r(str,
";", &str)))
5563 int headerTokenIndex = 0;
5564 std::string headerName;
5565 std::vector<std::string> headerValue;
5567 while ((tokenHeader = strtok_r(token,
":", &token)))
5569 if(headerTokenIndex == 0)
5570 headerName = tokenHeader;
5571 else if(headerTokenIndex == 1)
5572 headerValue.push_back(std::string(tokenHeader));
5578 if(!headerName.empty() && !headerValue.empty())
5591 AAMPLOG_INFO(
"WideVine KeyID workaround present: Setting preferred DRM as Widevine");
5598 mTuneCompleted =
false;
5599 mPersistedProfileIndex = -1;
5605 mCurrentDrm =
nullptr;
5618 #ifdef AAMP_CC_ENABLED
5631 mPlayerLoadTime = NOW_STEADY_TS_MS;
5633 mFirstProgress =
true;
5640 ResetBufUnderFlowStatus();
5644 std::string mapMPDStr, mapM3U8Str;
5650 if((hostName.find(mapMPDStr) != std::string::npos) || (mTSBEnabled && mManifestUrl.find(mapMPDStr) != std::string::npos))
5652 replace(mManifestUrl,
".m3u8",
".mpd");
5659 if((hostName.find(mapM3U8Str) != std::string::npos) || (mTSBEnabled && mManifestUrl.find(mapM3U8Str) != std::string::npos))
5661 replace(mManifestUrl,
".mpd" ,
".m3u8");
5669 DeFog(mManifestUrl);
5674 replace(mManifestUrl,
".m3u8",
"-eac3.m3u8");
5678 replace(mManifestUrl,
"-eac3.m3u8",
".m3u8");
5683 replace(mManifestUrl,
"https://",
"http://");
5690 if (mManifestUrl.find(
"mpd")!= std::string::npos)
5692 replace(mManifestUrl,
"-eac3.mpd",
".mpd");
5696 mIsFirstRequestToFOG = (mTSBEnabled ==
true);
5699 char tuneStrPrefix[64];
5700 mTsbSessionRequestUrl.clear();
5701 memset(tuneStrPrefix,
'\0',
sizeof(tuneStrPrefix));
5702 if (!mAppName.empty())
5704 snprintf(tuneStrPrefix,
sizeof(tuneStrPrefix),
"%s PLAYER[%d] APP: %s",(
mbPlayEnabled?STRFGPLAYER:STRBGPLAYER), mPlayerId, mAppName.c_str());
5708 snprintf(tuneStrPrefix,
sizeof(tuneStrPrefix),
"%s PLAYER[%d]", (
mbPlayEnabled?STRFGPLAYER:STRBGPLAYER), mPlayerId);
5713 AAMPLOG_WARN(
"%s aamp_tune: attempt: %d format: %s URL: %s", tuneStrPrefix, mTuneAttempts, mMediaFormatName[mMediaFormat], mManifestUrl.c_str());
5717 AAMPLOG_WARN(
"%s aamp_tune: attempt: %d format: %s URL: (BIG)", tuneStrPrefix, mTuneAttempts, mMediaFormatName[mMediaFormat]);
5718 AAMPLOG_INFO(
"URL: %s", mManifestUrl.c_str());
5722 mTsbSessionRequestUrl = mManifestUrl;
5732 mfirstTuneFmt = (int)mMediaFormat;
5742 AAMPLOG_INFO(
"Cached videoMute is being executed, mute value: %d", video_muted);
5747 SetCCStatus(video_muted ?
false : !subtitles_muted);
5762 mStreamSink->
SetVideoRectangle(mVideoRect.horizontalPos, mVideoRect.verticalPos, mVideoRect.width, mVideoRect.height);
5764 AAMPLOG_INFO(
"Update SetVideoRectangle x:%d y:%d w:%d h:%d", mVideoRect.horizontalPos, mVideoRect.verticalPos, mVideoRect.width, mVideoRect.height);
5772 AAMPLOG_WARN(
"CMCD Session Id:%s", this->
mTraceUUID.c_str());
5782 uuid_generate(uuid);
5784 uuid_unparse(uuid, sid);
5785 for (
char *ptr = sid; *ptr; ++ptr) {
5786 *ptr = tolower(*ptr);
5789 AAMPLOG_WARN(
"CMCD Session Id generated:%s", this->
mTraceUUID.c_str());
5798 int langCodePreference;
5809 std::string urlStr(url);
5811 #ifdef TRUST_LOCATOR_EXTENSION_IF_PRESENT // disable to exersize alternate path
5812 if( urlStr.rfind(
"hdmiin:",0)==0 )
5816 else if( urlStr.rfind(
"cvbsin:",0)==0 )
5820 else if((urlStr.rfind(
"live:",0)==0) || (urlStr.rfind(
"tune:",0)==0) || (urlStr.rfind(
"mr:",0)==0))
5824 else if(urlStr.rfind(
"ocap:",0)==0)
5828 else if(urlStr.rfind(
"http://127.0.0.1", 0) == 0)
5831 size_t fogUrlStart = urlStr.find(
"recordedUrl=", 16);
5833 if(fogUrlStart != std::string::npos)
5836 size_t fogUrlEnd = urlStr.find(
"&", fogUrlStart);
5838 if(fogUrlEnd != std::string::npos)
5840 if(urlStr.rfind(
"m3u8", fogUrlEnd) != std::string::npos)
5844 else if(urlStr.rfind(
"mpd", fogUrlEnd)!=std::string::npos)
5857 size_t extensionEnd = urlStr.find(
"?");
5858 std::size_t extensionStart = urlStr.rfind(
".", extensionEnd);
5859 int extensionLength;
5861 if(extensionStart != std::string::npos)
5863 if(extensionEnd == std::string::npos)
5865 extensionEnd = urlStr.length();
5870 extensionLength = (int)(extensionEnd - extensionStart);
5872 if(extensionLength == 4 && urlStr.compare(extensionStart, extensionLength,
"m3u8") == 0)
5876 else if(extensionLength == 3)
5878 if(urlStr.compare(extensionStart,extensionLength,
"mpd") == 0)
5882 else if(urlStr.compare(extensionStart,extensionLength,
"mp3") == 0 || urlStr.compare(extensionStart,extensionLength,
"mp4") == 0 ||
5883 urlStr.compare(extensionStart,extensionLength,
"mkv") == 0)
5888 else if((extensionLength == 2) || (urlStr.rfind(
"srt:",0)==0))
5890 if((urlStr.compare(extensionStart,extensionLength,
"ts") == 0) || (urlStr.rfind(
"srt:",0)==0))
5897 #endif // TRUST_LOCATOR_EXTENSION_IF_PRESENT
5903 std::string effectiveUrl;
5905 double downloadTime;
5913 bool gotManifest =
GetFile(url,
5929 if(sniffedBytes.
len >= 7 && memcmp(sniffedBytes.
ptr,
"#EXTM3U8", 7) == 0)
5933 else if((sniffedBytes.
len >= 6 && memcmp(sniffedBytes.
ptr,
"<?xml ", 6) == 0) ||
5934 (sniffedBytes.
len >= 5 && memcmp(sniffedBytes.
ptr,
"<MPD ", 5) == 0))
5937 if (strstr(sniffedBytes.
ptr,
"SmoothStreamingMedia"))
5964 long discontinuityTimeoutValue;
5968 pthread_mutex_lock(&
mLock);
5970 if (mDiscontinuityTuneOperationId != 0 || mDiscontinuityTuneOperationInProgress)
5972 AAMPLOG_WARN(
"PrivateInstanceAAMP: Ignored retune!! Discontinuity handler already spawned(%d) or inprogress(%d)",
5973 mDiscontinuityTuneOperationId, mDiscontinuityTuneOperationInProgress);
5974 pthread_mutex_unlock(&
mLock);
5978 pthread_mutex_unlock(&
mLock);
5980 AAMPLOG_INFO(
"No change in PTS for more than %ld ms, schedule retune!", discontinuityTimeoutValue);
5994 if(
mIsVSS && !url.empty())
6000 size_t vssStart = url.find(VSS_MARKER);
6001 if( vssStart != std::string::npos )
6003 vssStart += VSS_MARKER_LEN;
6004 size_t vssLen = url.find(
'&',vssStart);
6005 if( vssLen != std::string::npos )
6014 AAMPLOG_ERR(
"PrivateInstanceAAMP: ERROR: url does not have vss marker :%s ",url.c_str());
6025 switch(mContentType)
6054 strRet =
"XfinityHome";
6195 return mContentType;
6206 std::string urlStr(url);
6207 std::string drmInitDataStr;
6209 const size_t queryPos = urlStr.find(
"?");
6211 if (queryPos != std::string::npos)
6214 modUrl = urlStr.substr(0, queryPos);
6215 const std::string parameterDefinition(
"drmInitData=");
6216 std::string parameter;
6217 std::stringstream querySs(urlStr.substr(queryPos + 1, std::string::npos));
6218 while (std::getline(querySs, parameter,
'&'))
6220 if (parameter.rfind(parameterDefinition, 0) == 0)
6222 drmInitDataStr = parameter.substr(parameterDefinition.length());
6227 modUrl.append((queryPos == modUrl.length()) ?
"?" :
"&");
6228 modUrl.append(parameter);
6233 return std::tuple<std::string, std::string>(urlStr, drmInitDataStr);
6254 AAMPLOG_WARN(
"Player %s=>%s and soft release.Detach at position %f", STRFGPLAYER, STRBGPLAYER,
seek_pos_seconds );
6258 #ifdef AAMP_CC_ENABLED
6266 mStreamSink->
Stop(
true);
6279 return mAampCacheHandler;
6307 long defaultBitRate;
6309 return defaultBitRate;
6317 long defaultBitRate;
6319 return defaultBitRate;
6327 long defaultIframeBitRate;
6329 return defaultIframeBitRate;
6337 long defaultIframeBitRate4K;
6339 return defaultIframeBitRate4K;
6349 if (!
GetFile(fragmentUrl, &fragment, effectiveUrl, http_code, downloadTime, range, curlInstance,
true, fileType,NULL,fogError))
6359 return fragment.
ptr;
6366 unsigned int curlInstance,
const char *range,
MediaType fileType,
long * http_code,
double *downloadTime,
long *bitrate,
int * fogError,
double fragmentDurationSeconds)
6370 if (!
GetFile(fragmentUrl, fragment, effectiveUrl, http_code, downloadTime, range, curlInstance,
false,fileType, bitrate, NULL, fragmentDurationSeconds,pCMCDMetrics))
6390 mStreamSink->
SendCopy(mediaType,
ptr,
len, fragmentTime, fragmentTime, fragmentDuration);
6401 if( mStreamSink->
SendTransfer(mediaType, buffer->ptr, buffer->len, fragmentTime, fragmentTime, fragmentDuration) )
6473 root = cJSON_CreateArray();
6476 for(
int i = 0; i < data.size(); i++)
6478 cJSON_AddItemToArray(root, item = cJSON_CreateObject());
6479 if(data[i]->bandwidthBitsPerSecond >= 0)
6482 snprintf(buf,
sizeof(buf),
"%dx%d",data[i]->resolution.width,data[i]->resolution.height);
6483 cJSON_AddStringToObject(item,
"RESOLUTION",buf);
6484 cJSON_AddNumberToObject(item,
"BANDWIDTH",data[i]->bandwidthBitsPerSecond);
6487 char *jsonStr = cJSON_Print(root);
6496 AAMPLOG_TRACE(
"In PrivateInstanceAAMP::Json string:%s",op.c_str());
6511 std::string baseurl;
6512 int raw_w, raw_h, width, height;
6514 if( !datavec.empty() )
6516 cJSON *root = cJSON_CreateObject();
6517 if(!baseurl.empty())
6519 cJSON_AddStringToObject(root,
"baseUrl",baseurl.c_str());
6523 cJSON_AddNumberToObject(root,
"raw_w",raw_w);
6527 cJSON_AddNumberToObject(root,
"raw_h",raw_h);
6529 cJSON_AddNumberToObject(root,
"width",width);
6530 cJSON_AddNumberToObject(root,
"height",height);
6532 cJSON *tile = cJSON_AddArrayToObject(root,
"tile");
6536 cJSON_AddItemToArray(tile, item = cJSON_CreateObject() );
6537 if(!iter.url.empty())
6539 cJSON_AddStringToObject(item,
"url",iter.url.c_str());
6541 cJSON_AddNumberToObject(item,
"t",iter.t);
6542 cJSON_AddNumberToObject(item,
"d",iter.d);
6543 cJSON_AddNumberToObject(item,
"x",iter.x);
6544 cJSON_AddNumberToObject(item,
"y",iter.y);
6546 char *jsonStr = cJSON_Print(root);
6549 rc.assign( jsonStr );
6561 int tunedEventConfig;
6575 std::string rendition;
6576 while(std::getline(ss, rendition,
','))
6579 AAMPLOG_INFO(
"Parsed preferred rendition: %s",rendition.c_str());
6581 AAMPLOG_INFO(
"Number of preferred Renditions: %lu",
6590 while(std::getline(ss, codec,
','))
6593 AAMPLOG_INFO(
"Parsed preferred codec: %s",codec.c_str());
6595 AAMPLOG_INFO(
"Number of preferred codec: %lu",
6604 while(std::getline(ss, lng,
','))
6607 AAMPLOG_INFO(
"Parsed preferred lang: %s",lng.c_str());
6609 AAMPLOG_INFO(
"Number of preferred languages: %lu",
6617 while(std::getline(ss, lng,
','))
6620 AAMPLOG_INFO(
"Parsed preferred Label: %s",lng.c_str());
6648 return mAsyncTuneEnabled;
6656 mVideoRect.horizontalPos = x;
6657 mVideoRect.verticalPos = y;
6658 mVideoRect.width = w;
6659 mVideoRect.height = h;
6661 AAMPLOG_INFO(
"Backup VideoRectangle x:%d y:%d w:%d h:%d", x, y, w, h);
6685 if (isNonIPPlayback)
6696 AAMPLOG_INFO(
"mpStreamAbstractionAAMP is not Ready, Backup video rect values, current player state: %d", state);
6743 pthread_mutex_lock(&
mLock);
6744 mDownloadsEnabled =
false;
6745 pthread_cond_broadcast(&mDownloadsDisabled);
6746 pthread_mutex_unlock(&
mLock);
6754 return mDownloadsEnabled;
6763 pthread_mutex_lock(&
mLock);
6764 mDownloadsEnabled =
true;
6765 pthread_mutex_unlock(&
mLock);
6778 pthread_mutex_lock(&
mLock);
6779 if (mDownloadsEnabled)
6781 ret = pthread_cond_timedwait(&mDownloadsDisabled, &
mLock, &ts);
6786 else if (ETIMEDOUT != ret)
6788 AAMPLOG_WARN(
"sleep - condition wait failed %s", strerror(ret));
6791 pthread_mutex_unlock(&
mLock);
6803 durationSeconds = ms/1000.0;
6808 return (
long long)(durationSeconds*1000.0);
6822 durationSeconds = ms/1000.0;
6829 long long ms = (culledSeconds * 1000.0) + (durationSeconds * 1000.0);
6834 return (
long long)(durationSeconds*1000.0);
6844 const auto prevPositionInfo = mPrevPositionMilliseconds.
GetInfo();
6846 if(prevPositionInfo.isPositionValid(seek_pos_seconds_copy))
6848 return prevPositionInfo.getPosition();
6852 if(prevPositionInfo.isPopulated())
6855 AAMPLOG_WARN(
"prev-pos-ms (%lld) is invalid. seek_pos_seconds = %f, seek_pos_seconds when prev-pos-ms was stored = %f.",prevPositionInfo.getPosition(), seek_pos_seconds_copy, prevPositionInfo.getSeekPositionSec());
6863 std::lock_guard<std::mutex> functionLock{mGetPositionMillisecondsMutexHard};
6864 if(!mGetPositionMillisecondsMutexSoft.try_lock())
6867 AAMPLOG_ERR(
"Failed to acquire lock.");
6875 std::lock_guard<std::mutex> functionLock{mGetPositionMillisecondsMutexHard};
6878 if(mGetPositionMillisecondsMutexSoft.try_lock())
6880 AAMPLOG_WARN(
"Acquire lock (unexpected condition unless a previous lock has failed or there is a missing call to LockGetPositionMilliseconds()).");
6882 mGetPositionMillisecondsMutexSoft.unlock();
6897 std::lock_guard<std::mutex> functionLock{mGetPositionMillisecondsMutexHard};
6898 bool locked = mGetPositionMillisecondsMutexSoft.try_lock();
6901 AAMPLOG_ERR(
"Failed to acquire lock. A spurious position value may be calculated.");
6906 long long positionMiliseconds = seek_pos_seconds_copy != -1 ? seek_pos_seconds_copy * 1000.0 : 0.0;
6909 auto trickStartUTCMS_copy = trickStartUTCMS;
6910 AAMPLOG_TRACE(
"trickStartUTCMS=%lld", trickStartUTCMS_copy);
6911 if (trickStartUTCMS_copy >= 0)
6914 auto rate_copy =
rate;
6933 AAMPLOG_WARN(
"Ignoring gst position of %ldms and using seek_pos_seconds only until seek completes.", gstPosition);
6938 positionMiliseconds += gstPosition;
6944 positionMiliseconds += (((elapsedTime > 1000) ? elapsedTime : 0) * rate_copy);
6946 if(AAMP_NORMAL_PLAY_RATE == rate_copy)
6950 const auto prevPositionInfo = mPrevPositionMilliseconds.
GetInfo();
6951 if(prevPositionInfo.isPositionValid(seek_pos_seconds_copy))
6953 long long diff = positionMiliseconds - prevPositionInfo.
getPosition();
6955 if ((diff > MAX_DIFF_BETWEEN_PTS_POS_MS) || (diff < 0))
6957 AAMPLOG_WARN(
"diff %lld prev-pos-ms %lld current-pos-ms %lld, restore prev-pos as current-pos!!", diff, prevPositionInfo.getPosition(), positionMiliseconds);
6958 positionMiliseconds = prevPositionInfo.getPosition();
6961 else if(prevPositionInfo.isPopulated())
6964 AAMPLOG_WARN(
"prev-pos-ms (%lld) is invalid. seek_pos_seconds = %f, seek_pos_seconds when prev-pos-ms was stored = %f.",prevPositionInfo.getPosition(), seek_pos_seconds_copy, prevPositionInfo.getSeekPositionSec());
6968 if (positionMiliseconds < 0)
6970 AAMPLOG_WARN(
"Correcting positionMiliseconds %lld to zero", positionMiliseconds);
6971 positionMiliseconds = 0;
6978 if(positionMiliseconds > durationMs)
6980 AAMPLOG_WARN(
"Correcting positionMiliseconds %lld to duration %lld", positionMiliseconds, durationMs);
6981 positionMiliseconds = durationMs;
6986 long long tsbEndMs =
GetDurationMs() + (culledSeconds * 1000.0);
6987 if(positionMiliseconds > tsbEndMs)
6989 AAMPLOG_WARN(
"Correcting positionMiliseconds %lld to tsbEndMs %lld", positionMiliseconds, tsbEndMs);
6990 positionMiliseconds = tsbEndMs;
6996 AAMPLOG_TRACE(
"Returning Position as %lld (seek_pos_seconds = %f) and updating previous position.", positionMiliseconds, seek_pos_seconds_copy);
6997 mPrevPositionMilliseconds.
Update(positionMiliseconds ,seek_pos_seconds_copy);
7001 mGetPositionMillisecondsMutexSoft.unlock();
7004 return positionMiliseconds;
7012 mStreamSink->
SendCopy(mediaType, ptr, len, fpts, fdts, fDuration);
7020 if( mStreamSink->
SendTransfer(mediaType, buffer->ptr, buffer->len, fpts, fdts, fDuration, initFragment) )
7036 mStreamSink = streamSink;
7053 return mIsAudioContextSkipped;
7061 return mIsLiveStream;
7074 pthread_mutex_lock(&gMutex);
7075 auto iter = std::find_if(std::begin(gActivePrivAAMPs), std::end(gActivePrivAAMPs), [
this](
const gActivePrivAAMP_t& el)
7077 return el.pAAMP ==
this;
7080 if(iter != gActivePrivAAMPs.end())
7082 if (iter->reTune && mIsRetuneInProgress)
7085 pthread_cond_wait(&gCond, &gMutex);
7087 iter->reTune =
false;
7089 pthread_mutex_unlock(&gMutex);
7091 if (mAutoResumeTaskPending)
7095 mAutoResumeTaskPending =
false;
7104 #if defined(AAMP_MPD_DRM) || defined(AAMP_HLS_DRM)
7105 if (mDRMSessionManager)
7107 mDRMSessionManager->setLicenseRequestAbort(
true);
7127 if (mPendingAsyncEvents.size() > 0)
7129 AAMPLOG_WARN(
"PrivateInstanceAAMP: mPendingAsyncEvents.size - %lu", mPendingAsyncEvents.size());
7130 for (std::map<guint, bool>::iterator it = mPendingAsyncEvents.begin(); it != mPendingAsyncEvents.end(); it++)
7136 AAMPLOG_WARN(
"PrivateInstanceAAMP: remove id - %d", (
int) it->first);
7137 g_source_remove(it->first);
7141 AAMPLOG_WARN(
"PrivateInstanceAAMP: Not removing id - %d as not pending", (
int) it->first);
7145 mPendingAsyncEvents.clear();
7150 if (timedMetadata.size() > 0)
7152 timedMetadata.clear();
7161 mIsLiveStream =
false;
7162 durationSeconds = 0;
7169 mSeekOperationInProgress =
false;
7170 mTrickplayInProgress =
false;
7171 mMaxLanguageCount = 0;
7178 if(mPreCachePlaylistThreadFlag)
7180 pthread_join(mPreCachePlaylistThreadId,NULL);
7181 mPreCachePlaylistThreadFlag=
false;
7182 mPreCachePlaylistThreadId = 0;
7193 if (STARTS_WITH_IGNORE_CASE(mAppName.c_str(),
"peacock"))
7195 SAFE_DELETE(mAampCacheHandler);
7197 #if defined(AAMP_MPD_DRM) || defined(AAMP_HLS_DRM)
7198 SAFE_DELETE(mDRMSessionManager);
7219 std::string content(szContent, nb);
7220 timedMetadata.push_back(
TimedMetadata(timeMilliseconds, std::string((szName == NULL) ?
"" : szName), content, std::string((
id == NULL) ?
"" :
id), durationMS));
7228 std::string content(szContent, nb);
7229 timedMetadataNew.push_back(
TimedMetadata(timeMilliseconds, std::string((szName == NULL) ?
"" : szName), content, std::string((
id == NULL) ?
"" :
id), durationMS));
7244 std::vector<TimedMetadata>::iterator iter;
7246 for (iter = timedMetadataNew.begin(); iter != timedMetadataNew.end(); iter++)
7248 ReportTimedMetadata(iter->_timeMS, iter->_name.c_str(), iter->_content.c_str(), iter->_content.size(), init, iter->_id.c_str(), iter->_durationMS);
7250 timedMetadataNew.clear();
7261 std::vector<TimedMetadata>::iterator iter;
7264 AAMPLOG_INFO(
"Sending bulk Timed Metadata");
7268 root = cJSON_CreateArray();
7271 for (iter = timedMetadata.begin(); iter != timedMetadata.end(); iter++)
7273 cJSON_AddItemToArray(root, item = cJSON_CreateObject());
7274 cJSON_AddStringToObject(item,
"name", iter->_name.c_str());
7275 cJSON_AddStringToObject(item,
"id", iter->_id.c_str());
7276 cJSON_AddNumberToObject(item,
"timeMs", iter->_timeMS);
7277 cJSON_AddNumberToObject (item,
"durationMs",iter->_durationMS);
7278 cJSON_AddStringToObject(item,
"data", iter->_content.c_str());
7281 char* bulkData = cJSON_PrintUnformatted(root);
7284 BulkTimedMetadataEventPtr eventData = std::make_shared<BulkTimedMetadataEvent>(std::string(bulkData));
7285 AAMPLOG_INFO(
"Sending bulkTimedData");
7288 AAMPLOG_INFO(
"bulkTimedData : %s", bulkData);
7306 std::string content(szContent, nb);
7307 bool bFireEvent =
false;
7310 std::vector<TimedMetadata>::iterator i;
7311 bool ignoreMetaAdd =
false;
7313 for (i = timedMetadata.begin(); i != timedMetadata.end(); i++)
7315 if ((timeMilliseconds >= i->_timeMS-1000 && timeMilliseconds <= i->_timeMS+1000 ))
7317 if((i->_name.compare(szName) == 0) && (i->_content.compare(content) == 0))
7320 ignoreMetaAdd =
true;
7328 else if (i->_timeMS < timeMilliseconds)
7333 else if (i->_timeMS > timeMilliseconds)
7342 if(i == timedMetadata.end())
7347 timedMetadata.push_back(
TimedMetadata(timeMilliseconds, szName, content,
id, durationMS));
7353 timedMetadata.insert(i,
TimedMetadata(timeMilliseconds, szName, content,
id, durationMS));
7361 TimedMetadataEventPtr eventData = std::make_shared<TimedMetadataEvent>(((szName == NULL) ?
"" : szName), ((
id == NULL) ?
"" :
id), timeMilliseconds, durationMS, content);
7365 AAMPLOG_WARN(
"aamp timedMetadata: [%ld] '%s'", (
long)(timeMilliseconds), content.c_str());
7385 bool bFireEvent =
false;
7386 bool ignoreMetaAdd =
false;
7388 std::vector<ContentGapInfo>::iterator iter;
7390 for (iter = contentGaps.begin(); iter != contentGaps.end(); iter++)
7392 if ((timeMilliseconds >= iter->_timeMS-1000 && timeMilliseconds <= iter->_timeMS+1000 ))
7399 ignoreMetaAdd =
true;
7407 iter->_durationMS = durationMS;
7408 iter->_complete =
true;
7413 ignoreMetaAdd =
true;
7423 else if (iter->_timeMS < timeMilliseconds)
7428 else if (iter->_timeMS > timeMilliseconds)
7437 if(iter == contentGaps.end())
7439 contentGaps.push_back(
ContentGapInfo(timeMilliseconds,
id, durationMS));
7443 contentGaps.insert(iter,
ContentGapInfo(timeMilliseconds,
id, durationMS));
7450 ContentGapEventPtr eventData = std::make_shared<ContentGapEvent>(timeMilliseconds, durationMS);
7451 AAMPLOG_INFO(
"aamp contentGap: start: %lld duration: %ld", timeMilliseconds, (
long) durationMS);
7462 #ifdef AAMP_STOP_SINK_ON_SEEK
7464 if (AAMP_NORMAL_PLAY_RATE !=
rate)
7466 AAMPLOG_WARN(
"PrivateInstanceAAMP: not sending cc handle as rate = %f",
rate);
7470 if (mStreamSink != NULL)
7472 #ifdef AAMP_CC_ENABLED
7479 if (overrideCfg == 0)
7481 AAMPLOG_WARN(
"PrivateInstanceAAMP: CC format override to 608 present, selecting 608CC");
7489 CCHandleEventPtr
event = std::make_shared<CCHandleEvent>(mStreamSink->
getCCDecoderHandle());
7506 AAMPLOG_WARN(
"skipped as in IDLE state" );
7524 AAMPLOG_WARN(
"aamp: - sent tune event on Tune Completion.");
7538 if (setDiscontinuityFlag)
7551 mProcessingDiscontinuity[track] =
true;
7567 AAMPLOG_WARN(
"PrivateInstanceAAMP: Not processing reTune since state = %d, mSeekOperationInProgress = %d",
7568 state, mSeekOperationInProgress);
7572 pthread_mutex_lock(&gMutex);
7573 if (this->mIsRetuneInProgress)
7575 AAMPLOG_WARN(
"PrivateInstanceAAMP:: Already Retune inprogress");
7576 pthread_mutex_unlock(&gMutex);
7579 pthread_mutex_unlock(&gMutex);
7584 pthread_mutex_lock(&
mLock);
7588 if (mDiscontinuityTuneOperationId != 0 || mDiscontinuityTuneOperationInProgress)
7590 AAMPLOG_WARN(
"PrivateInstanceAAMP: Discontinuity Tune handler already spawned(%d) or inprogress(%d)",
7591 mDiscontinuityTuneOperationId, mDiscontinuityTuneOperationInProgress);
7592 pthread_mutex_unlock(&
mLock);
7596 pthread_mutex_unlock(&
mLock);
7598 AAMPLOG_WARN(
"PrivateInstanceAAMP: Underflow due to discontinuity handled");
7602 pthread_mutex_unlock(&
mLock);
7606 AAMPLOG_WARN(
"PrivateInstanceAAMP: Ignore reTune due to playback stall");
7611 AAMPLOG_WARN(
"PrivateInstanceAAMP: Ignore reTune as disabled in configuration");
7626 AAMPLOG_ERR(
"Failed to pause the Pipeline");
7630 const char* errorString = (errorType ==
eGST_ERROR_PTS) ?
"PTS ERROR" :
7639 bool activeAAMPFound =
false;
7640 pthread_mutex_lock(&gMutex);
7641 for (std::list<gActivePrivAAMP_t>::iterator iter = gActivePrivAAMPs.begin(); iter != gActivePrivAAMPs.end(); iter++)
7643 if (
this == iter->pAAMP)
7646 if (gAAMPInstance->reTune)
7648 AAMPLOG_WARN(
"PrivateInstanceAAMP: Already scheduled");
7655 long long lastErrorReportedTimeMs = lastUnderFlowTimeMs[trackType];
7656 int ptsErrorThresholdValue = 0;
7658 if (lastErrorReportedTimeMs)
7660 bool isRetuneRequried =
false;
7661 long long diffMs = (now - lastErrorReportedTimeMs);
7664 if (diffMs < AAMP_MAX_TIME_LL_BW_UNDERFLOWS_TO_TRIGGER_RETUNE_MS)
7666 isRetuneRequried =
true;
7671 if (diffMs < AAMP_MAX_TIME_BW_UNDERFLOWS_TO_TRIGGER_RETUNE_MS)
7673 isRetuneRequried =
true;
7676 if(isRetuneRequried)
7678 gAAMPInstance->numPtsErrors++;
7679 if (gAAMPInstance->numPtsErrors >= ptsErrorThresholdValue)
7681 AAMPLOG_WARN(
"PrivateInstanceAAMP: numPtsErrors %d, ptsErrorThreshold %d",
7682 gAAMPInstance->numPtsErrors, ptsErrorThresholdValue);
7683 gAAMPInstance->numPtsErrors = 0;
7684 gAAMPInstance->reTune =
true;
7685 AAMPLOG_WARN(
"PrivateInstanceAAMP: Schedule Retune. diffMs %lld < threshold %lld",
7687 AAMP_MAX_TIME_LL_BW_UNDERFLOWS_TO_TRIGGER_RETUNE_MS:AAMP_MAX_TIME_BW_UNDERFLOWS_TO_TRIGGER_RETUNE_MS);
7694 gAAMPInstance->numPtsErrors = 0;
7695 AAMPLOG_WARN(
"PrivateInstanceAAMP: Not scheduling reTune since (diff %lld > threshold %lld) numPtsErrors %d, ptsErrorThreshold %d.",
7697 AAMP_MAX_TIME_LL_BW_UNDERFLOWS_TO_TRIGGER_RETUNE_MS:AAMP_MAX_TIME_BW_UNDERFLOWS_TO_TRIGGER_RETUNE_MS,
7698 gAAMPInstance->numPtsErrors, ptsErrorThresholdValue);
7703 gAAMPInstance->numPtsErrors = 0;
7704 AAMPLOG_WARN(
"PrivateInstanceAAMP: Not scheduling reTune since first %s.", errorString);
7706 lastUnderFlowTimeMs[trackType] = now;
7710 AAMPLOG_WARN(
"PrivateInstanceAAMP: Schedule Retune errorType %d error %s", errorType, errorString);
7711 gAAMPInstance->reTune =
true;
7716 activeAAMPFound =
true;
7720 pthread_mutex_unlock(&gMutex);
7721 if (!activeAAMPFound)
7723 AAMPLOG_WARN(
"PrivateInstanceAAMP: %p not in Active AAMP list",
this);
7735 if (mState == state)
7748 pthread_mutex_lock(&
mLock);
7750 pthread_mutex_unlock(&
mLock);
7757 StateChangedEventPtr eventData = std::make_shared<StateChangedEvent>(
eSTATE_INITIALIZED);
7761 StateChangedEventPtr eventData = std::make_shared<StateChangedEvent>(mState);
7771 pthread_mutex_lock(&
mLock);
7773 pthread_mutex_unlock(&
mLock);
7782 gint callbackID = g_idle_add_full(G_PRIORITY_HIGH_IDLE, task, (gpointer)arg, dtask);
7831 pthread_mutex_lock(&
mLock);
7833 ret = mTunedEventPending;
7834 mTunedEventPending =
false;
7836 pthread_mutex_unlock(&
mLock);
7852 char * strVideoEndJson = NULL;
7854 pthread_mutex_lock(&
mLock);
7858 if(mTimeAtTopProfile > 0)
7861 mVideoEnd->SetTimeAtTopProfile(mTimeAtTopProfile);
7862 mVideoEnd->SetTimeToTopProfile(mTimeToTopProfile);
7867 mTimeToTopProfile = 0;
7868 mTimeAtTopProfile = 0;
7880 AAMPLOG_INFO(
"TsbSessionEnd:%s", data);
7881 strVideoEndJson = mVideoEnd->ToJsonString(data);
7888 strVideoEndJson = mVideoEnd->ToJsonString();
7891 SAFE_DELETE(mVideoEnd);
7893 mVideoEnd =
new CVideoStat(mMediaFormatName[mMediaFormat]);
7895 pthread_mutex_unlock(&
mLock);
7899 AAMPLOG_INFO(
"VideoEnd:%s", strVideoEndJson);
7900 MetricsDataEventPtr e = std::make_shared<MetricsDataEvent>(MetricsDataType::AAMP_DATA_VIDEO_END, this->
mTraceUUID, strVideoEndJson);
7902 free(strVideoEndJson);
7913 pthread_mutex_lock(&
mLock);
7916 VideoStatTrackType trackType = VideoStatTrackType::STAT_VIDEO;
7919 trackType = VideoStatTrackType::STAT_IFRAME;
7921 mVideoEnd->SetProfileResolution(trackType,bitrate,width,height);
7923 pthread_mutex_unlock(&
mLock);
7931 UpdateVideoEndMetrics(mediaType, bitrate, curlOrHTTPCode, strUrl,duration,curlDownloadTime,
false,
false);
7940 pthread_mutex_lock(&
mLock);
7944 mVideoEnd->SetTsbStatus(btsbAvailable);
7946 pthread_mutex_unlock(&
mLock);
7954 pthread_mutex_lock(&
mLock);
7959 pthread_mutex_unlock(&
mLock);
7970 if( curlOrHTTPCode > 0 && !(curlOrHTTPCode == CURLE_ABORTED_BY_CALLBACK || curlOrHTTPCode == CURLE_WRITE_ERROR) )
7972 VideoStatDataType dataType = VideoStatDataType::VE_DATA_UNKNOWN;
7974 VideoStatTrackType trackType = VideoStatTrackType::STAT_UNKNOWN;
7975 VideoStatCountType eCountType = VideoStatCountType::COUNT_UNKNOWN;
7988 dataType = VideoStatDataType::VE_DATA_MANIFEST;
7989 trackType = VideoStatTrackType::STAT_MAIN;
7995 dataType = VideoStatDataType::VE_DATA_MANIFEST;
7996 trackType = VideoStatTrackType::STAT_VIDEO;
8002 dataType = VideoStatDataType::VE_DATA_MANIFEST;
8003 trackType = VideoStatTrackType::STAT_AUDIO;
8010 dataType = VideoStatDataType::VE_DATA_MANIFEST;
8011 trackType = VideoStatTrackType::STAT_AUDIO;
8018 dataType = VideoStatDataType::VE_DATA_MANIFEST;
8019 trackType = STAT_IFRAME;
8025 dataType = VideoStatDataType::VE_DATA_FRAGMENT;
8026 trackType = VideoStatTrackType::STAT_VIDEO;
8031 if (((curlOrHTTPCode == 200) || (curlOrHTTPCode == 206)) && duration > 0)
8036 if(maxBitrateSupported == bitrate)
8038 mTimeAtTopProfile += duration;
8043 if(mTimeAtTopProfile == 0)
8045 mTimeToTopProfile += duration;
8055 dataType = VideoStatDataType::VE_DATA_FRAGMENT;
8056 trackType = VideoStatTrackType::STAT_AUDIO;
8062 dataType = VideoStatDataType::VE_DATA_FRAGMENT;
8063 trackType = VideoStatTrackType::STAT_AUDIO;
8069 dataType = VideoStatDataType::VE_DATA_FRAGMENT;
8070 trackType = VideoStatTrackType::STAT_IFRAME;
8076 dataType = VideoStatDataType::VE_DATA_INIT_FRAGMENT;
8077 trackType = VideoStatTrackType::STAT_IFRAME;
8083 dataType = VideoStatDataType::VE_DATA_INIT_FRAGMENT;
8084 trackType = VideoStatTrackType::STAT_VIDEO;
8090 dataType = VideoStatDataType::VE_DATA_INIT_FRAGMENT;
8091 trackType = VideoStatTrackType::STAT_AUDIO;
8098 dataType = VideoStatDataType::VE_DATA_INIT_FRAGMENT;
8099 trackType = VideoStatTrackType::STAT_AUDIO;
8106 dataType = VideoStatDataType::VE_DATA_FRAGMENT;
8107 trackType = VideoStatTrackType::STAT_SUBTITLE;
8117 if( dataType != VideoStatDataType::VE_DATA_UNKNOWN
8118 && trackType != VideoStatTrackType::STAT_UNKNOWN)
8120 pthread_mutex_lock(&
mLock);
8124 mVideoEnd->Increment_Data(dataType,trackType,bitrate,curlDownloadTime * 1000,curlOrHTTPCode,
false,audioIndex, manifestData);
8125 if((curlOrHTTPCode != 200) && (curlOrHTTPCode != 206) && strUrl.c_str())
8128 mVideoEnd->SetFailedFragmentUrl(trackType,bitrate,strUrl);
8130 if(dataType == VideoStatDataType::VE_DATA_FRAGMENT)
8132 mVideoEnd->Record_License_EncryptionStat(trackType,isEncrypted,keyChanged);
8135 pthread_mutex_unlock(&
mLock);
8140 AAMPLOG_INFO(
"PrivateInstanceAAMP: Could Not update VideoEnd Event dataType:%d trackType:%d response:%d",
8141 dataType,trackType,curlOrHTTPCode);
8152 if(info.desiredProfileIndex < info.currentProfileIndex)
8154 AAMPLOG_INFO(
"UpdateVideoEnd:abrinfo currIdx:%d desiredIdx:%d for:%d", info.currentProfileIndex,info.desiredProfileIndex,info.abrCalledFor);
8156 if(info.abrCalledFor == AAMPAbrType::AAMPAbrBandwidthUpdate)
8158 pthread_mutex_lock(&
mLock);
8161 mVideoEnd->Increment_NetworkDropCount();
8163 pthread_mutex_unlock(&
mLock);
8165 else if (info.abrCalledFor == AAMPAbrType::AAMPAbrFragmentDownloadFailed)
8167 pthread_mutex_lock(&
mLock);
8170 mVideoEnd->Increment_ErrorDropCount();
8172 pthread_mutex_unlock(&
mLock);
8183 UpdateVideoEndMetrics(mediaType, bitrate, curlOrHTTPCode, strUrl,0,curlDownloadTime,
false,
false, manifestData);
8209 std::map<guint, bool>::iterator itr = mPendingAsyncEvents.find(
id);
8210 if(itr != mPendingAsyncEvents.end())
8212 assert (itr->second);
8213 mPendingAsyncEvents.erase(itr);
8217 AAMPLOG_WARN(
"id %d not in mPendingAsyncEvents, insert and mark as not pending",
id);
8218 mPendingAsyncEvents[id] =
false;
8229 std::map<guint, bool>::iterator itr = mPendingAsyncEvents.find(
id);
8230 if(itr != mPendingAsyncEvents.end())
8232 assert (!itr->second);
8233 AAMPLOG_WARN(
"id %d already in mPendingAsyncEvents and completed, erase it",
id);
8234 mPendingAsyncEvents.erase(itr);
8238 mPendingAsyncEvents[id] =
true;
8248 if(pCMCDMetrics!=NULL){
8251 std::vector<long> bitrateList;
8252 pCMCDMetrics->SetSessionId(this->
mTraceUUID);
8256 pCMCDMetrics->SetMediaType(
"MANIFEST");
8261 pCMCDMetrics->SetMediaType(
"VIDEO");
8267 pCMCDMetrics->SetBufferStarvation(
true);
8269 int videoBufferLength = ((int)video->GetBufferedDuration())*1000;
8272 for(
int i = 0; i < bitrateList.size(); i++)
8274 if(bitrateList[i]>temp)
8276 temp=bitrateList[i];
8279 pCMCDMetrics->SetBitrate(videoBitrate);
8280 pCMCDMetrics->SetTopBitrate(temp/1000);
8282 pCMCDMetrics->SetBufferLength(videoBufferLength);
8283 AAMPLOG_INFO(
"video bufferlength %d video bitrate %d",videoBufferLength,videoBitrate);
8289 pCMCDMetrics->SetMediaType(
"AUDIO");
8295 pCMCDMetrics->SetBufferStarvation(
true);
8299 for(
int i = 0; i < bitrateList.size(); i++)
8301 if(bitrateList[i]>temp)
8303 temp=bitrateList[i];
8306 int audioBufferLength = ((int)audio->GetBufferedDuration())*1000;
8308 pCMCDMetrics->SetTopBitrate(temp/1000);
8310 pCMCDMetrics->SetBufferLength(audioBufferLength);
8311 AAMPLOG_INFO(
"audio bufferlength %daudio bitrate %d",audioBufferLength,((
int)
mCMCDBandwidth)/1000);
8317 pCMCDMetrics->SetMediaType(
"SUBTITLE");
8322 pCMCDMetrics->SetMediaType(
"INIT_VIDEO");
8325 for(
int i = 0; i < bitrateList.size(); i++)
8327 if(bitrateList[i]>temp)
8329 temp=bitrateList[i];
8332 pCMCDMetrics->SetBitrate(initVideoBitrate);
8333 pCMCDMetrics->SetTopBitrate(temp);
8338 pCMCDMetrics->SetMediaType(
"INIT_AUDIO");
8340 for(
int i = 0; i < bitrateList.size(); i++)
8342 if(bitrateList[i]>temp)
8344 temp=bitrateList[i];
8348 pCMCDMetrics->SetTopBitrate(temp);
8353 pCMCDMetrics->SetMediaType(
"MUXED");
8355 for(
int i = 0; i < bitrateList.size(); i++)
8357 if(bitrateList[i]>temp)
8359 temp=bitrateList[i];
8368 pCMCDMetrics->SetBufferStarvation(
true);
8372 pCMCDMetrics->SetBitrate(muxedBitrate);
8373 pCMCDMetrics->SetTopBitrate(temp/1000);
8375 pCMCDMetrics->SetBufferLength(muxedBufferLength);
8376 AAMPLOG_INFO(
"muxed bufferlength %dmuxed bitrate %d",muxedBufferLength,muxedBitrate);
8387 if(headerName.back() !=
':')
8392 if (isLicenseHeader)
8394 if (headerValue.size() != 0)
8396 mCustomLicenseHeaders[headerName] = headerValue;
8400 mCustomLicenseHeaders.erase(headerName);
8405 if (headerValue.size() != 0)
8407 mCustomHeaders[headerName] = headerValue;
8411 mCustomHeaders.erase(headerName);
8429 AAMPLOG_INFO(
"Live offset value updated to %lf", mLiveOffset);
8437 char description[MAX_ERROR_DESCRIPTION_LENGTH];
8438 memset(description,
'\0', MAX_ERROR_DESCRIPTION_LENGTH);
8440 GETCONFIGVALUE_PRIV(eAAMPConfig_StallTimeoutMS,stalltimeout);
8441 snprintf(description, (MAX_ERROR_DESCRIPTION_LENGTH - 1),
"Playback has been stalled for more than %d ms due to lack of new fragments", stalltimeout);
8480 AAMPLOG_WARN(
"skipped as in IDLE state" );
8493 #ifdef USE_SECMANAGER
8497 std::thread t([&](){
8502 AAMPLOG_WARN(
"calling setVideoWindowSize w:%d x h:%d ",w,h);
8503 mDRMSessionManager->setVideoWindowSize(w,h);
8546 if (mCurrentDrm !=
nullptr) {
8547 type += mCurrentDrm->getDrmCodecType();
8559 return mMediaFormat;
8562 #if defined(USE_SECCLIENT) || defined(USE_SECMANAGER)
8567 void PrivateInstanceAAMP::GetMoneyTraceString(std::string &customHeader)
const
8569 char moneytracebuf[512];
8570 memset(moneytracebuf, 0,
sizeof(moneytracebuf));
8572 if (mCustomHeaders.size() > 0)
8574 for (std::unordered_map<std::string, std::vector<std::string>>::const_iterator it = mCustomHeaders.begin();
8575 it != mCustomHeaders.end(); it++)
8577 if (it->first.compare(
"X-MoneyTrace:") == 0)
8579 if (it->second.size() >= 2)
8581 snprintf(moneytracebuf,
sizeof(moneytracebuf),
"trace-id=%s;parent-id=%s;span-id=%lld",
8582 (
const char*)it->second.at(0).c_str(),
8583 (
const char*)it->second.at(1).c_str(),
8586 else if (it->second.size() == 1)
8588 snprintf(moneytracebuf,
sizeof(moneytracebuf),
"trace-id=%s;parent-id=%lld;span-id=%lld",
8589 (
const char*)it->second.at(0).c_str(),
8593 customHeader.append(moneytracebuf);
8599 if(customHeader.size() == 0)
8602 AAMPLOG_WARN(
"No Moneytrace info available in tune request,need to generate one");
8604 uuid_generate(uuid);
8606 uuid_unparse(uuid, uuidstr);
8607 for (
char *ptr = uuidstr; *ptr; ++ptr) {
8608 *ptr = tolower(*ptr);
8611 customHeader.append(moneytracebuf);
8613 AAMPLOG_TRACE(
"[GetMoneyTraceString] MoneyTrace[%s]",customHeader.c_str());
8622 if(mTunedEventPending)
8629 AAMPLOG_WARN(
"aamp: %s - sent tune event after first fragment fetch and decrypt", mMediaFormatName[mMediaFormat]);
8651 switch (mContentType)
8677 for (
auto const& pair: httpHeaderResponses) {
8678 HTTPResponseHeaderEventPtr
event = std::make_shared<HTTPResponseHeaderEvent>(pair.first.c_str(), pair.second);
8679 AAMPLOG_INFO(
"HTTPResponseHeader evt Header:%s Response:%s", event->getHeader().c_str(), event->getResponse().c_str());
8690 std::vector<long> bitrateList;
8691 std::set<std::string> langList;
8692 std::vector<float> supportedPlaybackSpeeds { -64, -32, -16, -4, -1, 0, 0.5, 1, 4, 16, 32, 64 };
8694 int bitrateCount = 0;
8695 int supportedSpeedCount = 0;
8700 for (
int i = 0; i <mMaxLanguageCount; i++)
8707 std::string drmType =
"NONE";
8711 drmType = helper->friendlyName();
8716 for (
auto iter = langList.begin(); iter != langList.end(); iter++)
8721 assert(iter->size() < MAX_LANGUAGE_TAG_LENGTH);
8722 event->addLanguage((*iter));
8726 for (
int i = 0; i < bitrateList.size(); i++)
8728 event->addBitrate(bitrateList[i]);
8736 auto position = std::find(supportedPlaybackSpeeds.begin(), supportedPlaybackSpeeds.end(), 0.5);
8737 if(position != supportedPlaybackSpeeds.end())
8739 supportedPlaybackSpeeds.erase(position);
8743 for(
int i = 0; i < supportedPlaybackSpeeds.size(); i++)
8745 event->addSupportedSpeed(supportedPlaybackSpeeds[i]);
8751 event->addSupportedSpeed(0);
8754 event->addSupportedSpeed(0.5);
8756 event->addSupportedSpeed(1);
8759 event->setMediaFormat(mMediaFormatName[mMediaFormat]);
8769 SupportedSpeedsChangedEventPtr
event = std::make_shared<SupportedSpeedsChangedEvent>();
8770 std::vector<float> supportedPlaybackSpeeds { -64, -32, -16, -4, -1, 0, 0.5, 1, 4, 16, 32, 64 };
8771 int supportedSpeedCount = 0;
8774 if (isIframeTrackPresent)
8778 auto position = std::find(supportedPlaybackSpeeds.begin(), supportedPlaybackSpeeds.end(), 0.5);
8779 if(position != supportedPlaybackSpeeds.end())
8781 supportedPlaybackSpeeds.erase(position);
8785 for(
int i = 0; i < supportedPlaybackSpeeds.size(); i++)
8787 event->addSupportedSpeed(supportedPlaybackSpeeds[i]);;
8793 event->addSupportedSpeed(0);
8796 event->addSupportedSpeed(0.5);
8798 event->addSupportedSpeed(1);
8801 AAMPLOG_WARN(
"aamp: sending supported speeds changed event with count %d", event->getSupportedSpeedCount());
8810 BlockedEventPtr
event = std::make_shared<BlockedEvent>(reason);
8812 #ifdef AAMP_CC_ENABLED
8813 if (0 == reason.compare(
"SERVICE_PIN_LOCKED"))
8828 WatermarkSessionUpdateEventPtr
event = std::make_shared<WatermarkSessionUpdateEvent>(
sessionHandle, status, system);
8837 return mTuneCompleted;
8857 AAMPLOG_WARN(
"[CDAI] Found Adbreak on period[%s] Duration[%d]", adBreakId.c_str(), brInfo.duration);
8858 std::string adId(
"");
8859 std::string url(
"");
8861 SaveNewTimedMetadata((
long long) startMS, brInfo.name.c_str(), brInfo.payload.c_str(), brInfo.payload.size(), adBreakId.c_str(), brInfo.duration);
8876 AAMPLOG_WARN(
"is called! CDAI not enabled!! Rejecting the promise.");
8886 if (mDownloadsEnabled)
8888 AdResolvedEventPtr e = std::make_shared<AdResolvedEvent>(status, adId, startMS, durationMs);
8889 AAMPLOG_WARN(
"PrivateInstanceAAMP: [CDAI] Sent resolved status=%d for adId[%s]", status, adId.c_str());
8912 AAMPLOG_WARN(
"PrivateInstanceAAMP:, [CDAI] Delivered AdEvent[%s] to JSPP.", ADEVENT2STRING(evtType));
8915 AdPlacementEventPtr placementEvt = std::dynamic_pointer_cast<AdPlacementEvent>(e);
8916 mAdProgressId = placementEvt->getAdId();
8917 mAdPrevProgressTime = NOW_STEADY_TS_MS;
8919 mAdDuration = placementEvt->getDuration();
8936 AAMPLOG_INFO(
"PrivateInstanceAAMP: [CDAI] Pushed [%s] of adBreakId[%s] to Queue.", ADEVENT2STRING(type), adBreakId.c_str());
8938 AdReservationEventPtr e = std::make_shared<AdReservationEvent>(type, adBreakId, position);
8959 if(AAMP_EVENT_AD_PLACEMENT_START <= type && AAMP_EVENT_AD_PLACEMENT_ERROR >= type)
8961 AAMPLOG_INFO(
"PrivateInstanceAAMP: [CDAI] Pushed [%s] of adId[%s] to Queue.", ADEVENT2STRING(type), adId.c_str());
8963 AdPlacementEventPtr e = std::make_shared<AdPlacementEvent>(type, adId, position, adOffset * 1000 , adDuration, error_code);
8984 std::string type = mMediaFormatName[mMediaFormat];
8986 if(mCurrentDrm !=
nullptr)
8989 type += mCurrentDrm->friendlyName();
9057 mTunedManifestUrl.assign(mManifestUrl);
9061 DeFog(mTunedManifestUrl);
9062 mTunedManifestUrl.replace(0,4,
"_fog");
9064 AAMPLOG_TRACE(
"PrivateInstanceAAMP::tunedManifestUrl:%s ", mTunedManifestUrl.c_str());
9072 AAMPLOG_TRACE(
"PrivateInstanceAAMP::tunedManifestUrl:%s ", mTunedManifestUrl.c_str());
9073 return mTunedManifestUrl.c_str();
9127 #ifdef AAMP_DEBUG_FETCH_INJECT
9128 if ((1 << type) & AAMP_DEBUG_FETCH_INJECT)
9130 AAMPLOG_WARN (
"PrivateInstanceAAMP: Enter. type = %d", (
int) type);
9133 if (!mTrackInjectionBlocked[type])
9136 pthread_mutex_lock(&
mLock);
9137 mTrackInjectionBlocked[type] =
true;
9138 pthread_mutex_unlock(&
mLock);
9140 AAMPLOG_TRACE (
"PrivateInstanceAAMP::Exit. type = %d", (
int) type);
9149 #ifdef AAMP_DEBUG_FETCH_INJECT
9150 if ((1 << type) & AAMP_DEBUG_FETCH_INJECT)
9152 AAMPLOG_WARN (
"PrivateInstanceAAMP: Enter. type = %d", (
int) type);
9155 if (mTrackInjectionBlocked[type])
9158 pthread_mutex_lock(&
mLock);
9159 mTrackInjectionBlocked[type] =
false;
9160 pthread_mutex_unlock(&
mLock);
9162 AAMPLOG_TRACE (
"PrivateInstanceAAMP::Exit. type = %d", (
int) type);
9181 mVideoBasePTS = basepts;
9182 AAMPLOG_INFO(
"mVideoBasePTS::%llus", mVideoBasePTS);
9193 WebVttCueEventPtr ev = std::make_shared<WebVttCueEvent>(cue);
9221 customHeaders.insert(mCustomLicenseHeaders.begin(), mCustomLicenseHeaders.end());
9230 ID3MetadataEventPtr e = std::make_shared<ID3MetadataEvent>(id3Metadata->
data, id3Metadata->
schemeIdUri, id3Metadata->value, id3Metadata->timeScale, id3Metadata->presentationTime, id3Metadata->eventDuration, id3Metadata->id, id3Metadata->timestampOffset);
9233 std::vector<uint8_t> metadata = e->getMetadata();
9234 int metadataLen = e->getMetadataSize();
9235 int printableLen = 0;
9236 std::ostringstream tag;
9238 tag <<
"ID3 tag length: " << metadataLen;
9240 if (metadataLen > 0 )
9242 tag <<
" payload: ";
9244 for (
int i = 0; i < metadataLen; i++)
9246 if (std::isprint(metadata[i]))
9255 std::string tagLog(tag.str());
9256 AAMPLOG_INFO(
"%s", tag.str().c_str());
9257 AAMPLOG_INFO(
"{schemeIdUri:\"%s\",value:\"%s\",presentationTime:%" PRIu64
",timeScale:%" PRIu32
",eventDuration:%" PRIu32
",id:%" PRIu32
",timestampOffset:%" PRIu64
"}",e->getSchemeIdUri().c_str(), e->getValue().c_str(), e->getPresentationTime(), e->getTimeScale(), e->getEventDuration(), e->getId(), e->getTimestampOffset());
9261 AAMPLOG_WARN(
"ID3 log was truncated, original size %d (printable %d)" , metadataLen, printableLen);
9273 #ifndef AAMP_STOP_SINK_ON_SEEK
9298 int szPlaylistCount = mPreCacheDnldList.size();
9314 int sleepTimeBetweenDnld = (maxWindowforDownload / szPlaylistCount) * 1000;
9328 AAMPLOG_WARN(
"Downloading Playlist Type:%d for PreCaching:%s",
9329 newelem.type, newelem.url.c_str());
9330 std::string playlistUrl;
9331 std::string playlistEffectiveUrl;
9334 double downloadTime;
9359 mPreCacheDnldList.clear();
9363 AAMPLOG_WARN(
"End of PreCachePlaylistDownloadTask ");
9371 mPreCacheDnldList = dnldListInput;
9372 if(mPreCacheDnldList.size())
9374 AAMPLOG_WARN(
"Got Playlist PreCache list of Size : %lu", mPreCacheDnldList.size());
9387 std::string preferrence;
9389 item = cJSON_CreateObject();
9408 cJSON *accessibility = cJSON_AddObjectToObject(item,
"preferred-text-accessibility");
9418 char *jsonStr = cJSON_Print(item);
9421 preferrence.assign(jsonStr);
9434 std::string preferrence;
9436 item = cJSON_CreateObject();
9459 cJSON * accessibility = cJSON_AddObjectToObject(item,
"preferred-audio-accessibility");
9469 char *jsonStr = cJSON_Print(item);
9472 preferrence.assign(jsonStr);
9490 if (!trackInfo.empty())
9495 root = cJSON_CreateArray();
9498 for (
int i = 0; i < trackInfo.size(); i++)
9500 cJSON_AddItemToArray(root, item = cJSON_CreateObject());
9501 if (trackInfo[i]->bandwidthBitsPerSecond != -1)
9503 cJSON_AddNumberToObject(item,
"bandwidth", trackInfo[i]->bandwidthBitsPerSecond);
9505 if (trackInfo[i]->resolution.width != -1)
9507 cJSON_AddNumberToObject(item,
"width", trackInfo[i]->resolution.width);
9509 if (trackInfo[i]->resolution.height != -1)
9511 cJSON_AddNumberToObject(item,
"height", trackInfo[i]->resolution.height);
9513 if (trackInfo[i]->resolution.framerate != -1)
9515 cJSON_AddNumberToObject(item,
"framerate", trackInfo[i]->resolution.framerate);
9518 cJSON_AddNumberToObject(item,
"enabled", trackInfo[i]->enabled);
9520 if (trackInfo[i]->codecs)
9522 cJSON_AddStringToObject(item,
"codec", trackInfo[i]->codecs);
9525 char *jsonStr = cJSON_Print(root);
9528 tracks.assign(jsonStr);
9536 AAMPLOG_ERR(
"PrivateInstanceAAMP: No available video track information!");
9548 int bitrateSize = bitrateList.size();
9550 this->bitrateList.clear();
9553 AAMPLOG_INFO(
"User Profile filtering bitrate size:%d status:%d", bitrateSize, this->
userProfileStatus);
9554 for (
int i = 0; i < bitrateSize; i++)
9556 this->bitrateList.push_back(bitrateList.at(i));
9557 AAMPLOG_WARN(
"User Profile Index : %d(%d) Bw : %ld", i, bitrateSize, bitrateList.at(i));
9580 if (!trackInfo.empty())
9585 cJSON *accessbilityArray = NULL;
9586 root = cJSON_CreateArray();
9589 for (
auto iter = trackInfo.begin(); iter != trackInfo.end(); iter++)
9591 cJSON_AddItemToArray(root, item = cJSON_CreateObject());
9592 if (!iter->name.empty())
9594 cJSON_AddStringToObject(item,
"name", iter->name.c_str());
9596 if (!iter->label.empty())
9598 cJSON_AddStringToObject(item,
"label", iter->label.c_str());
9600 if (!iter->language.empty())
9602 cJSON_AddStringToObject(item,
"language", iter->language.c_str());
9604 if (!iter->codec.empty())
9606 cJSON_AddStringToObject(item,
"codec", iter->codec.c_str());
9608 if (!iter->rendition.empty())
9610 cJSON_AddStringToObject(item,
"rendition", iter->rendition.c_str());
9612 if (!iter->accessibilityType.empty())
9614 cJSON_AddStringToObject(item,
"accessibilityType", iter->accessibilityType.c_str());
9616 if (!iter->characteristics.empty())
9618 cJSON_AddStringToObject(item,
"characteristics", iter->characteristics.c_str());
9620 if (iter->channels != 0)
9622 cJSON_AddNumberToObject(item,
"channels", iter->channels);
9624 if (iter->bandwidth != -1)
9626 cJSON_AddNumberToObject(item,
"bandwidth", iter->bandwidth);
9628 if (!iter->contentType.empty())
9630 cJSON_AddStringToObject(item,
"contentType", iter->contentType.c_str());
9632 if (!iter->mixType.empty())
9634 cJSON_AddStringToObject(item,
"mixType", iter->mixType.c_str());
9636 if (!iter->mType.empty())
9638 cJSON_AddStringToObject(item,
"Type", iter->mType.c_str());
9640 cJSON_AddBoolToObject(item,
"availability", iter->isAvailable);
9641 if (!iter->accessibilityItem.getSchemeId().empty())
9643 cJSON *accessibility = cJSON_AddObjectToObject(item,
"accessibility");
9644 cJSON_AddStringToObject(accessibility,
"scheme", iter->accessibilityItem.getSchemeId().c_str());
9645 std::string valueType = iter->accessibilityItem.getTypeName();
9646 if (valueType ==
"int_value")
9648 cJSON_AddNumberToObject(accessibility, valueType.c_str(), iter->accessibilityItem.getIntValue());
9651 cJSON_AddStringToObject(accessibility, valueType.c_str(), iter->accessibilityItem.getStrValue().c_str());
9655 char *jsonStr = cJSON_Print(root);
9658 tracks.assign(jsonStr);
9666 AAMPLOG_ERR(
"PrivateInstanceAAMP: No available audio track information!");
9685 #ifdef AAMP_CC_ENABLED
9686 std::vector<TextTrackInfo> textTracksCopy;
9687 std::copy_if(begin(trackInfo), end(trackInfo), back_inserter(textTracksCopy), [](
const TextTrackInfo& e){
return e.isCC;});
9690 if (!trackInfo.empty())
9695 root = cJSON_CreateArray();
9698 for (
auto iter = trackInfo.begin(); iter != trackInfo.end(); iter++)
9700 cJSON_AddItemToArray(root, item = cJSON_CreateObject());
9701 if (!iter->name.empty())
9703 cJSON_AddStringToObject(item,
"name", iter->name.c_str());
9705 if (!iter->label.empty())
9707 cJSON_AddStringToObject(item,
"label", iter->label.c_str());
9711 cJSON_AddStringToObject(item,
"sub-type",
"CLOSED-CAPTIONS");
9715 cJSON_AddStringToObject(item,
"sub-type",
"SUBTITLES");
9717 if (!iter->language.empty())
9719 cJSON_AddStringToObject(item,
"language", iter->language.c_str());
9721 if (!iter->rendition.empty())
9723 cJSON_AddStringToObject(item,
"rendition", iter->rendition.c_str());
9725 if (!iter->accessibilityType.empty())
9727 cJSON_AddStringToObject(item,
"accessibilityType", iter->accessibilityType.c_str());
9729 if (!iter->instreamId.empty())
9731 cJSON_AddStringToObject(item,
"instreamId", iter->instreamId.c_str());
9733 if (!iter->characteristics.empty())
9735 cJSON_AddStringToObject(item,
"characteristics", iter->characteristics.c_str());
9737 if (!iter->mType.empty())
9739 cJSON_AddStringToObject(item,
"type", iter->mType.c_str());
9741 if (!iter->codec.empty())
9743 cJSON_AddStringToObject(item,
"codec", iter->codec.c_str());
9745 cJSON_AddBoolToObject(item,
"availability", iter->isAvailable);
9746 if (!iter->accessibilityItem.getSchemeId().empty())
9748 cJSON *accessibility = cJSON_AddObjectToObject(item,
"accessibility");
9749 cJSON_AddStringToObject(accessibility,
"scheme", iter->accessibilityItem.getSchemeId().c_str());
9751 std::string valueType = iter->accessibilityItem.getTypeName();
9752 if (valueType ==
"int_value")
9754 cJSON_AddNumberToObject(accessibility, valueType.c_str(), iter->accessibilityItem.getIntValue());
9758 cJSON_AddStringToObject(accessibility, valueType.c_str(), iter->accessibilityItem.getStrValue().c_str());
9762 char *jsonStr = cJSON_Print(root);
9765 tracks.assign(jsonStr);
9773 AAMPLOG_ERR(
"PrivateInstanceAAMP: No available text track information!");
9783 std::string PrivateInstanceAAMP::GetVideoRectangle()
9809 DrmMessageEventPtr
event = std::make_shared<DrmMessageEvent>(payload);
9848 AAMPLOG_WARN(
"skipped as in IDLE state" );
9863 AAMPLOG_INFO(
"Pausing Playback on First Frame Displayed");
9875 AAMPLOG_ERR(
"Failed to pause pipeline for first frame displayed!");
9891 bool bufferingSet =
false;
9896 bufferingSet =
true;
9915 return bufferingSet;
9926 AAMPLOG_ERR(
"type[%d] is un-supported, returning default as false!", type);
9931 pthread_mutex_lock(&
mLock);
9933 ret = !mbTrackDownloadsBlocked[type];
9934 pthread_mutex_unlock(&
mLock);
10005 root = cJSON_CreateArray();
10008 cJSON_AddItemToArray(root, item = cJSON_CreateObject());
10009 if (!trackInfo.
name.empty())
10011 cJSON_AddStringToObject(item,
"name", trackInfo.
name.c_str());
10015 cJSON_AddStringToObject(item,
"language", trackInfo.
language.c_str());
10017 if (!trackInfo.
codec.empty())
10019 cJSON_AddStringToObject(item,
"codec", trackInfo.
codec.c_str());
10023 cJSON_AddStringToObject(item,
"rendition", trackInfo.
rendition.c_str());
10025 if (!trackInfo.
label.empty())
10027 cJSON_AddStringToObject(item,
"label", trackInfo.
label.c_str());
10031 cJSON_AddStringToObject(item,
"accessibilityType", trackInfo.
accessibilityType.c_str());
10035 cJSON_AddStringToObject(item,
"characteristics", trackInfo.
characteristics.c_str());
10039 cJSON_AddNumberToObject(item,
"channels", trackInfo.
channels);
10043 cJSON_AddNumberToObject(item,
"bandwidth", trackInfo.
bandwidth);
10047 cJSON_AddStringToObject(item,
"contentType", trackInfo.
contentType.c_str());
10049 if (!trackInfo.
mixType.empty())
10051 cJSON_AddStringToObject(item,
"mixType", trackInfo.
mixType.c_str());
10053 if (!trackInfo.
mType.empty())
10055 cJSON_AddStringToObject(item,
"type", trackInfo.
mType.c_str());
10059 cJSON *accessibility = cJSON_AddObjectToObject(item,
"accessibility");
10060 cJSON_AddStringToObject(accessibility,
"scheme", trackInfo.
accessibilityItem.getSchemeId().c_str());
10070 char *jsonStr = cJSON_Print(root);
10073 track.assign(jsonStr);
10076 cJSON_Delete(root);
10081 AAMPLOG_ERR(
"PrivateInstanceAAMP: No available Text track information!");
10086 AAMPLOG_ERR(
"PrivateInstanceAAMP: Not in playing state!");
10107 root = cJSON_CreateArray();
10110 cJSON_AddItemToArray(root, item = cJSON_CreateObject());
10111 if (!trackInfo.name.empty())
10113 cJSON_AddStringToObject(item,
"name", trackInfo.name.c_str());
10115 if (!trackInfo.language.empty())
10117 cJSON_AddStringToObject(item,
"language", trackInfo.language.c_str());
10119 if (!trackInfo.codec.empty())
10121 cJSON_AddStringToObject(item,
"codec", trackInfo.codec.c_str());
10123 if (!trackInfo.rendition.empty())
10125 cJSON_AddStringToObject(item,
"rendition", trackInfo.rendition.c_str());
10127 if (!trackInfo.label.empty())
10129 cJSON_AddStringToObject(item,
"label", trackInfo.label.c_str());
10131 if (!trackInfo.accessibilityType.empty())
10133 cJSON_AddStringToObject(item,
"accessibilityType", trackInfo.accessibilityType.c_str());
10135 if (!trackInfo.characteristics.empty())
10137 cJSON_AddStringToObject(item,
"characteristics", trackInfo.characteristics.c_str());
10139 if (!trackInfo.mType.empty())
10141 cJSON_AddStringToObject(item,
"type", trackInfo.mType.c_str());
10145 cJSON *accessibility = cJSON_AddObjectToObject(item,
"accessibility");
10146 cJSON_AddStringToObject(accessibility,
"scheme", trackInfo.
accessibilityItem.getSchemeId().c_str());
10156 char *jsonStr = cJSON_Print(root);
10159 track.assign(jsonStr);
10162 cJSON_Delete(root);
10167 AAMPLOG_ERR(
"PrivateInstanceAAMP: No available Text track information!");
10172 AAMPLOG_ERR(
"PrivateInstanceAAMP: Not in playing state!");
10184 char *jsonStr = NULL;
10185 cJSON *item = cJSON_CreateObject();
10186 if (!track.name.empty())
10188 cJSON_AddStringToObject(item,
"name", track.name.c_str());
10190 if (!track.language.empty())
10192 cJSON_AddStringToObject(item,
"languages", track.language.c_str());
10194 if (!track.codec.empty())
10196 cJSON_AddStringToObject(item,
"codec", track.codec.c_str());
10198 if (!track.rendition.empty())
10200 cJSON_AddStringToObject(item,
"rendition", track.rendition.c_str());
10202 if (!track.label.empty())
10204 cJSON_AddStringToObject(item,
"label", track.label.c_str());
10206 if (!track.accessibilityType.empty())
10208 cJSON_AddStringToObject(item,
"accessibilityType", track.accessibilityType.c_str());
10210 if (!track.characteristics.empty())
10212 cJSON_AddStringToObject(item,
"characteristics", track.characteristics.c_str());
10214 if (!track.mType.empty())
10216 cJSON_AddStringToObject(item,
"type", track.mType.c_str());
10220 cJSON *accessibility = cJSON_AddObjectToObject(item,
"accessibility");
10221 cJSON_AddStringToObject(accessibility,
"scheme", track.
accessibilityItem.getSchemeId().c_str());
10232 jsonStr = cJSON_Print(item);
10233 cJSON_Delete(item);
10242 AAMPLOG_INFO(
"trackId: %d", trackId);
10246 if (MUTE_SUBTITLES_TRACKID == trackId)
10255 if (!tracks.empty() && (trackId >= 0 && trackId < tracks.size()))
10261 mIsInbandCC =
true;
10262 #ifdef AAMP_CC_ENABLED
10263 if (!track.instreamId.empty())
10265 CCFormat format = eCLOSEDCAPTION_FORMAT_DEFAULT;
10268 if (mMediaFormat ==
eMEDIAFORMAT_DASH && (std::isdigit(
static_cast<unsigned char>(track.instreamId[0])) == 0) && !track.rendition.empty())
10270 if (track.rendition.find(
"608") != std::string::npos)
10272 format = eCLOSEDCAPTION_FORMAT_608;
10274 else if (track.rendition.find(
"708") != std::string::npos)
10276 format = eCLOSEDCAPTION_FORMAT_708;
10283 if (overrideCfg != -1)
10285 format = (
CCFormat)(overrideCfg & 1);
10286 AAMPLOG_WARN(
"PrivateInstanceAAMP: CC format override present, override format to: %d", format);
10292 AAMPLOG_ERR(
"PrivateInstanceAAMP: Track number/instreamId is empty, skip operation");
10298 mIsInbandCC =
false;
10304 AAMPLOG_WARN(
"GetPreferredTextTrack %d trackId %d", textTrack, trackId);
10305 if (trackId != textTrack)
10310 if(NULL != jsonData)
10318 discardEnteringLiveEvt =
true;
10324 discardEnteringLiveEvt =
false;
10332 AAMPLOG_WARN(
"webvtt data received from application");
10337 if (!mTextStyle.empty())
10366 #ifdef AAMP_CC_ENABLED
10370 if (!trackId.empty())
10373 for (
auto it = tracks.begin(); it != tracks.end(); it++)
10375 if (it->instreamId == trackId)
10377 idx = std::distance(tracks.begin(), it);
10396 #ifdef AAMP_CC_ENABLED
10400 subtitles_muted = !enabled;
10418 return !(subtitles_muted);
10443 bool retVal =
false;
10445 mTextStyle = options;
10449 AAMPLOG_WARN(
"Calling StreamAbstractionAAMP::SetTextStyle(%s)", options.c_str());
10454 #ifdef AAMP_CC_ENABLED
10455 AAMPLOG_WARN(
"Calling AampCCManager::SetTextStyle(%s)", options.c_str());
10474 return !gActivePrivAAMPs.empty();
10482 mIsDiscontinuityIgnored[track] =
true;
10490 return (mIsDiscontinuityIgnored[track]);
10507 bool reconfigure =
false;
10508 AAMPLOG_WARN(
"Got format - videoFormat %d and audioFormat %d", videoFormat, audioFormat);
10526 pthread_mutex_lock(&
mLock);
10529 reconfigure =
true;
10530 mVideoFormat = videoFormat;
10534 reconfigure =
true;
10535 mAudioFormat = audioFormat;
10539 reconfigure =
true;
10540 mAuxFormat = auxFormat;
10542 if (
IsMuxedStream() && (mVideoComponentCount == 0 || mAudioComponentCount == 0))
10544 AAMPLOG_INFO(
" TS Processing Done. Number of Audio Components : %d and Video Components : %d",mAudioComponentCount,mVideoComponentCount);
10548 pthread_mutex_unlock(&
mLock);
10549 mStreamSink->
Stop(!newTune);
10550 pthread_mutex_lock(&
mLock);
10551 reconfigure =
true;
10560 pthread_mutex_unlock(&
mLock);
10569 AAMPLOG_WARN(
"Old Stream format - videoFormat %d and audioFormat %d",mVideoFormat,mAudioFormat);
10571 if (mVideoComponentCount == 0 && (mVideoFormat != videoFormat && videoFormat ==
FORMAT_INVALID))
10574 mVideoFormat = videoFormat;
10575 AAMPLOG_INFO(
"Audio-Only PlayBack");
10579 else if (mAudioComponentCount == 0)
10581 if (mAudioFormat != audioFormat && audioFormat ==
FORMAT_INVALID)
10583 mAudioFormat = audioFormat;
10585 else if (mAuxFormat != auxFormat && auxFormat ==
FORMAT_INVALID)
10587 mAuxFormat = auxFormat;
10590 AAMPLOG_INFO(
"Video-Only PlayBack");
10605 #ifdef AAMP_CC_ENABLED
10634 int taskId = AAMP_TASK_ID_INVALID;
10638 if (taskId == AAMP_TASK_ID_INVALID)
10640 AAMPLOG_ERR(
"mScheduler returned invalid ID, dropping the schedule request!");
10645 taskId = g_idle_add(task, (gpointer)arg);
10662 ret = g_source_remove(taskId);
10682 return (pthread_mutex_trylock(&
mStreamLock) == 0);
10714 return (vidDiscontinuity && auxDiscontinuity && auxDiscontinuity);
10728 return (vidDiscontinuity || auxDiscontinuity || auxDiscontinuity);
10749 bool isJson =
false;
10750 bool isRetuneNeeded =
false;
10751 bool accessibilityPresent =
false;
10757 AAMPLOG_INFO(
"Preferred Language Properties received as json : %s", languageList);
10761 catch(
const std::exception& e)
10768 std::vector<std::string> inputLanguagesList;
10769 std::string inputLanguagesString;
10772 if (jsObject->
isArray(
"languages"))
10774 if (jsObject->
get(
"languages", inputLanguagesList))
10776 for (
auto preferredLanguage : inputLanguagesList)
10778 if (!inputLanguagesString.empty())
10780 inputLanguagesString +=
",";
10782 inputLanguagesString += preferredLanguage;
10786 else if (jsObject->
isString(
"languages"))
10788 if (jsObject->
get(
"languages", inputLanguagesString))
10790 inputLanguagesList.push_back(inputLanguagesString);
10795 AAMPLOG_ERR(
"Preferred Audio Language Field Only support String or String Array");
10798 AAMPLOG_INFO(
"Number of preferred languages received: %lu", inputLanguagesList.size());
10799 AAMPLOG_INFO(
"Preferred language string received: %s", inputLanguagesString.c_str());
10801 std::string inputLabelsString;
10805 if (jsObject->
get(
"label", inputLabelsString))
10807 AAMPLOG_INFO(
"Preferred Label string: %s", inputLabelsString.c_str());
10811 string inputRenditionString;
10814 if (jsObject->
isString(
"rendition"))
10816 if (jsObject->
get(
"rendition", inputRenditionString))
10818 AAMPLOG_INFO(
"Preferred rendition string: %s", inputRenditionString.c_str());
10824 if (jsObject->
isObject(
"accessibility"))
10827 if (jsObject->
get(
"accessibility", accessNode))
10830 if (!inputAudioAccessibilityNode.getSchemeId().empty())
10832 AAMPLOG_INFO(
"Preferred accessibility SchemeId: %s", inputAudioAccessibilityNode.getSchemeId().c_str());
10833 if (inputAudioAccessibilityNode.getTypeName() ==
"string_value")
10835 AAMPLOG_INFO(
"Preferred accessibility Value Type %s and Value: %s", inputAudioAccessibilityNode.getTypeName().c_str(),
10836 inputAudioAccessibilityNode.getStrValue().c_str());
10840 AAMPLOG_INFO(
"Preferred accessibility Value Type %s and Value : %d", inputAudioAccessibilityNode.getTypeName().c_str(),
10841 inputAudioAccessibilityNode.getIntValue());
10847 accessibilityPresent =
true;
10858 isRetuneNeeded =
true;
10888 isRetuneNeeded =
true;
10889 if(languageList != NULL)
10896 while(std::getline(ss, lng,
','))
10899 AAMPLOG_INFO(
"Parsed preferred lang: %s", lng.c_str());
10908 if(labelList != NULL)
10915 while(std::getline(ss, lab,
','))
10918 AAMPLOG_INFO(
"Parsed preferred label: %s", lab.c_str());
10926 if( preferredRendition )
10928 AAMPLOG_INFO(
"Setting rendition %s", preferredRendition);
10937 if( preferredType )
10940 std::string delim =
"_";
10943 if (pos != std::string::npos)
10955 if(codecList != NULL)
10962 while(std::getline(ss, codec,
','))
10965 AAMPLOG_INFO(
"Parsed preferred codec: %s", codec.c_str());
10974 AAMPLOG_INFO(
"Discarding Retune set lanuage(s) (%s) , rendition (%s) and accessibility (%s) since already set",
10975 languageList?languageList:
"", preferredRendition?preferredRendition:
"", preferredType?preferredType:
"");
10985 bool languagePresent =
false;
10986 bool renditionPresent =
false;
10987 bool accessibilityTypePresent =
false;
10988 bool codecPresent =
false;
10989 bool labelPresent =
false;
10992 bool languageAvailabilityInManifest =
false;
10993 bool renditionAvailabilityInManifest =
false;
10994 bool accessibilityAvailabilityInManifest =
false;
10995 bool labelAvailabilityInManifest =
false;
10996 std::string trackIndexStr;
10998 if (trackIndex >= 0)
11001 char *currentPrefLanguage =
const_cast<char*
>(trackInfo[trackIndex].language.c_str());
11002 char *currentPrefRendition =
const_cast<char*
>(trackInfo[trackIndex].rendition.c_str());
11003 char *currentPrefAccessibility =
const_cast<char*
>(trackInfo[trackIndex].accessibilityType.c_str());
11004 char *currentPrefCodec =
const_cast<char*
>(trackInfo[trackIndex].codec.c_str());
11005 char *currentPrefLabel =
const_cast<char*
>(trackInfo[trackIndex].label.c_str());
11013 auto language = std::find_if(trackInfo.begin(), trackInfo.end(),
11015 { return ((temp.language == firstLanguage) && (temp.language != currentPrefLanguage)); });
11017 auto languageAvailable = std::find_if(trackInfo.begin(), trackInfo.end(),
11019 { return ((temp.language == firstLanguage) && (temp.language != currentPrefLanguage) && (temp.isAvailable)); });
11020 languageAvailabilityInManifest = (languageAvailable != end(trackInfo) && languageAvailable->isAvailable);
11021 if(languagePresent && (language != end(trackInfo)))
11023 trackIndexStr = language->index;
11033 auto label = std::find_if(trackInfo.begin(), trackInfo.end(),
11035 { return ((temp.label == curLabel) && (temp.label != currentPrefLabel)); });
11037 auto labelAvailable = std::find_if(trackInfo.begin(), trackInfo.end(),
11039 { return ((temp.label == curLabel) && (temp.label != currentPrefLabel) && (temp.isAvailable)); });
11040 labelAvailabilityInManifest = ((labelAvailable != end(trackInfo) ) && labelAvailable->isAvailable);
11051 auto rendition = std::find_if(trackInfo.begin(), trackInfo.end(),
11053 { return ((temp.rendition == curRendition) && (temp.rendition != currentPrefRendition)); });
11054 renditionPresent = (rendition != end(trackInfo));
11055 auto renditionAvailable = std::find_if(trackInfo.begin(), trackInfo.end(),
11057 { return ((temp.rendition == curRendition) && (temp.rendition != currentPrefRendition) && (temp.isAvailable)); });
11058 renditionAvailabilityInManifest = ((renditionAvailable != end(trackInfo)) && renditionAvailable->isAvailable);
11067 auto accessType = std::find_if(trackInfo.begin(), trackInfo.end(),
11069 { return ((temp.accessibilityType == curType) && (temp.accessibilityType != currentPrefAccessibility)); });
11070 accessibilityTypePresent = (accessType != end(trackInfo));
11071 auto accessTypeAvailable = std::find_if(trackInfo.begin(), trackInfo.end(),
11073 { return ((temp.accessibilityType == curType) && (temp.accessibilityType != currentPrefAccessibility) && (temp.isAvailable)); });
11074 accessibilityAvailabilityInManifest = ((accessTypeAvailable != end(trackInfo)) && accessTypeAvailable->isAvailable);
11083 auto codec = std::find_if(trackInfo.begin(), trackInfo.end(),
11085 { return ((temp.codec == firstCodec) && (temp.codec != currentPrefCodec) && (temp.isAvailable)); });
11090 bool clearPreference =
false;
11095 AAMPLOG_INFO(
"API to clear all preferences; retune to make it affect");
11096 clearPreference =
true;
11107 else if (languagePresent || renditionPresent || accessibilityTypePresent || codecPresent || labelPresent || accessibilityPresent || clearPreference)
11111 discardEnteringLiveEvt =
true;
11115 mLanguageChangeInProgress =
true;
11119 ((languagePresent && !languageAvailabilityInManifest) ||
11120 (renditionPresent && !renditionAvailabilityInManifest) ||
11121 (accessibilityTypePresent && !accessibilityAvailabilityInManifest) ||
11122 (labelPresent && !labelAvailabilityInManifest)))
11127 discardEnteringLiveEvt =
false;
11130 else if(!trackIndexStr.empty())
11147 bool isJson =
false;
11148 bool isRetuneNeeded =
false;
11149 bool accessibilityPresent =
false;
11155 AAMPLOG_INFO(
"Preferred Text Language Properties received as json : %s", param);
11159 catch(
const std::exception& e)
11166 std::vector<std::string> inputTextLanguagesList;
11167 std::string inputTextLanguagesString;
11170 if(jsObject->
isArray(
"languages"))
11172 if (jsObject->
get(
"languages", inputTextLanguagesList))
11174 for (
auto preferredLanguage : inputTextLanguagesList)
11176 if (!inputTextLanguagesString.empty())
11178 inputTextLanguagesString +=
"," ;
11180 inputTextLanguagesString += preferredLanguage;
11184 else if (jsObject->
isString(
"languages"))
11186 if (jsObject->
get(
"languages", inputTextLanguagesString))
11188 inputTextLanguagesList.push_back(inputTextLanguagesString);
11193 AAMPLOG_ERR(
"Preferred Text Language Field Only support String or String Array");
11196 AAMPLOG_INFO(
"Number of preferred Text languages: %lu", inputTextLanguagesList.size());
11197 AAMPLOG_INFO(
"Preferred Text languages string: %s", inputTextLanguagesString.c_str());
11199 std::string inputTextRenditionString;
11201 if (jsObject->
isString(
"rendition"))
11203 if (jsObject->
get(
"rendition", inputTextRenditionString))
11205 AAMPLOG_INFO(
"Preferred text rendition string: %s", inputTextRenditionString.c_str());
11209 std::string inputTextLabelString;
11213 if (jsObject->
get(
"label", inputTextLabelString))
11215 AAMPLOG_INFO(
"Preferred text label string: %s", inputTextLabelString.c_str());
11219 std::string inputTextTypeString;
11221 if (jsObject->
isString(
"accessibilityType"))
11223 if (jsObject->
get(
"accessibilityType", inputTextTypeString))
11225 AAMPLOG_INFO(
"Preferred text type string: %s", inputTextTypeString.c_str());
11231 if (jsObject->
isObject(
"accessibility"))
11234 if (jsObject->
get(
"accessibility", accessNode))
11237 if (!inputTextAccessibilityNode.getSchemeId().empty())
11239 AAMPLOG_INFO(
"Preferred accessibility SchemeId: %s", inputTextAccessibilityNode.getSchemeId().c_str());
11240 if (inputTextAccessibilityNode.getTypeName() ==
"string_value")
11242 AAMPLOG_INFO(
"Preferred accessibility Value Type %s and Value: %s", inputTextAccessibilityNode.getTypeName().c_str(),
11243 inputTextAccessibilityNode.getStrValue().c_str());
11247 AAMPLOG_INFO(
"Preferred accessibility Value Type %s and Value : %d", inputTextAccessibilityNode.getTypeName().c_str(),
11248 inputTextAccessibilityNode.getIntValue());
11253 accessibilityPresent =
true;
11265 isRetuneNeeded =
true;
11288 AAMPLOG_INFO(
"Setting Text Languages %s", param);
11289 std::string inputTextLanguagesString;
11290 inputTextLanguagesString = std::string(param);
11294 isRetuneNeeded =
true;
11303 AAMPLOG_INFO(
"No valid Parameter Recieved");
11313 bool languagePresent =
false;
11314 bool renditionPresent =
false;
11315 bool accessibilityTypePresent =
false;
11316 bool codecPresent =
false;
11317 bool labelPresent =
false;
11319 bool languageAvailabilityInManifest =
false;
11320 bool renditionAvailabilityInManifest =
false;
11321 bool accessibilityAvailabilityInManifest =
false;
11322 bool labelAvailabilityInManifest =
false;
11323 bool trackNotEnabled =
false;
11325 if (trackIndex >= 0)
11328 char *currentPrefLanguage =
const_cast<char*
>(trackInfo[trackIndex].language.c_str());
11329 char *currentPrefRendition =
const_cast<char*
>(trackInfo[trackIndex].rendition.c_str());
11337 auto language = std::find_if(trackInfo.begin(), trackInfo.end(),
11339 { return ((temp.language == firstLanguage) && (temp.language != currentPrefLanguage)); });
11341 auto languageAvailable = std::find_if(trackInfo.begin(), trackInfo.end(),
11343 { return ((temp.language == firstLanguage) && (temp.language != currentPrefLanguage) && (temp.isAvailable)); });
11344 languageAvailabilityInManifest = (languageAvailable != end(trackInfo) && languageAvailable->isAvailable);
11353 auto rendition = std::find_if(trackInfo.begin(), trackInfo.end(),
11355 { return ((temp.rendition == curRendition) && (temp.rendition != currentPrefRendition)); });
11356 renditionPresent = (rendition != end(trackInfo));
11357 auto renditionAvailable = std::find_if(trackInfo.begin(), trackInfo.end(),
11359 { return ((temp.rendition == curRendition) && (temp.rendition != currentPrefRendition) && (temp.isAvailable)); });
11360 renditionAvailabilityInManifest = ((renditionAvailable != end(trackInfo)) && renditionAvailable->isAvailable);
11365 trackNotEnabled =
true;
11373 else if (languagePresent || renditionPresent || accessibilityPresent || trackNotEnabled)
11375 discardEnteringLiveEvt =
true;
11378 mLanguageChangeInProgress =
true;
11382 ((languagePresent && !languageAvailabilityInManifest) ||
11383 (renditionPresent && !renditionAvailabilityInManifest) ||
11384 (accessibilityTypePresent && !accessibilityAvailabilityInManifest) ||
11385 (labelPresent && !labelAvailabilityInManifest)))
11391 discardEnteringLiveEvt =
false;
11398 #define WV_KID_WORKAROUND "SkyStoreDE="
11405 bool enable =
false;
11406 int pos = url.find(WV_KID_WORKAROUND);
11407 if (pos != string::npos){
11408 pos = pos + strlen(WV_KID_WORKAROUND);
11409 AAMPLOG_INFO(
"URL found WideVine KID Workaround at %d key = %c",
11411 enable = (url.at(pos) ==
'1');
11424 unsigned char *OutpuData = NULL;
11425 unsigned int WIDEVINE_PSSH_KEYID_OFFSET = 36u;
11426 unsigned int WIDEVINE_PSSH_DATA_SIZE = 60u;
11427 unsigned int CK_PSSH_KEYID_OFFSET = 32u;
11428 unsigned int COMMON_KEYID_SIZE = 16u;
11429 unsigned char WVSamplePSSH[] = {
11430 0x00, 0x00, 0x00, 0x3c,
11431 0x70, 0x73, 0x73, 0x68,
11432 0x00, 0x00, 0x00, 0x00,
11433 0xed, 0xef, 0x8b, 0xa9, 0x79, 0xd6, 0x4a, 0xce,
11434 0xa3, 0xc8, 0x27, 0xdc, 0xd5, 0x1d, 0x21, 0xed,
11435 0x00, 0x00, 0x00, 0x1c, 0x08, 0x01, 0x12, 0x10,
11436 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
11437 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
11438 0x22, 0x06, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x37
11441 AAMPLOG_INFO(
"Converting system UUID of PSSH data size (%zu)", InputDataLength);
11443 AAMPLOG_INFO(
"PSSH Data (%d) Before Modification : ", InputDataLength);
11444 DumpBlob(InputData, InputDataLength);
11448 int iWVpssh = WIDEVINE_PSSH_KEYID_OFFSET;
11449 int CKPssh = CK_PSSH_KEYID_OFFSET;
11451 if (CK_PSSH_KEYID_OFFSET+COMMON_KEYID_SIZE <= InputDataLength){
11452 for (; size < COMMON_KEYID_SIZE; ++size, ++iWVpssh, ++CKPssh ){
11454 WVSamplePSSH[iWVpssh] = InputData[CKPssh];
11458 OutpuData = (
unsigned char *)malloc(
sizeof(WVSamplePSSH));
11460 memcpy(OutpuData, WVSamplePSSH,
sizeof(WVSamplePSSH));
11461 OutputDataLength =
sizeof(WVSamplePSSH);
11463 AAMPLOG_INFO(
"PSSH Data (%d) after Modification : ", OutputDataLength);
11464 DumpBlob(OutpuData, OutputDataLength);
11469 AAMPLOG_ERR(
"PSSH Data Memory allocation failed ");
11473 AAMPLOG_ERR(
"Invalid Clear Key PSSH data ");
11477 AAMPLOG_ERR(
"Invalid Argument of PSSH data ");
11490 if (*data++ ==
'I' && *data++ ==
'D' && *data++ ==
'3' && *data++ >= 2)
11507 buffer.setBuffer((uint8_t *)segment, size);
11508 buffer.parseBuffer();
11509 if(!buffer.isInitSegment())
11511 uint8_t* message =
nullptr;
11512 uint32_t messageLen = 0;
11513 uint8_t* schemeIDUri =
nullptr;
11514 uint8_t* value =
nullptr;
11515 uint64_t presTime = 0;
11516 uint32_t timeScale = 0;
11517 uint32_t eventDuration = 0;
11519 if(buffer.getEMSGData(message, messageLen, schemeIDUri, value, presTime, timeScale, eventDuration,
id))
11521 if(message && messageLen > 0 &&
hasId3Header(message, messageLen))
11523 AAMPLOG_TRACE(
"PrivateInstanceAAMP: Found ID3 metadata[%d]", type);
11529 ReportID3Metadata(type, message, messageLen, (
char*)(schemeIDUri), (
char*)(value), presTime,
id, eventDuration, timeScale);
11543 Id3CallbackData* id3Metadata =
new Id3CallbackData(
this,
static_cast<const uint8_t*
>(ptr), len,
static_cast<const char*
>(schemeIdURI),
static_cast<const char*
>(id3Value), presTime, id3ID, eventDur, tScale, tStampOffset);
11552 SAFE_DELETE(id3Metadata);
11598 this->vidTimeScale = vidTimeScale;
11606 return vidTimeScale;
11614 this->audTimeScale = audTimeScale;
11622 return audTimeScale;
11629 this->speedCache = speedCache;
11637 return &speedCache;
11642 return mLiveOffsetAppRequest;
11650 this->mLiveOffsetAppRequest = LiveOffsetAppRequest;
11657 return bLowLatencyServiceConfigured;
11665 bLowLatencyServiceConfigured = bConfig;
11681 this->mTime = time;
11689 return mCurrentLatency;
11697 this->mCurrentLatency = currentLatency;
11746 std::string strVideoStatsJson;
11747 long liveLatency = 0;
11755 mVideoEnd->setLiveLatency(liveLatency);
11758 if(mTimeAtTopProfile > 0)
11761 mVideoEnd->SetTimeAtTopProfile(mTimeAtTopProfile);
11762 mVideoEnd->SetTimeToTopProfile(mTimeToTopProfile);
11765 char * videoStatsPtr = mVideoEnd->ToJsonString(
nullptr,
true);
11768 strVideoStatsJson = videoStatsPtr;
11769 free(videoStatsPtr);
11774 AAMPLOG_ERR(
"GetPlaybackStats failed, mVideoEnd is NULL");
11777 if(!strVideoStatsJson.empty())
11779 AAMPLOG_INFO(
"Playback stats json:%s", strVideoStatsJson.c_str());
11783 AAMPLOG_ERR(
"Failed to retrieve playback stats (video stats returned as empty from aamp metrics)");
11785 return strVideoStatsJson;
11793 std::string jsonStr;
11796 long tmpLongVar = 0;
11797 int maxdownload = 0;
11814 jsondata.
add(
"downloadStallTimeout", tmpLongVar);
11819 jsondata.
add(
"downloadStartTimeout", tmpLongVar);
11824 jsondata.
add(
"downloadLowBWTimeout", tmpLongVar);
11828 jsondata.
add(
"maxConcurrentDownloads", (
long)(maxdownload));
11846 jsondata.
add(
"persistHighNetworkBandwidth", ISCONFIGSET_PRIV(eAAMPConfig_PersistHighNetworkBandwidth));
11866 bool aPrefAvail =
false;
11867 bool tPrefAvail =
false;
11887 accessiblity.
add(
"schemeId", schemeId);
11897 accessiblity.
add(
"value", value);
11898 audioPreference.
add(
"accessibility", accessiblity);
11923 accessiblity.
add(
"schemeId", schemeId);
11933 accessiblity.
add(
"value", value);
11934 subtitlePreference.
add(
"accessibility", accessiblity);
11938 bool trackAdded =
false;
11941 jsondataForPreference.
add(
"audio", audioPreference);
11946 jsondataForPreference.
add(
"text", subtitlePreference);
11952 jsondata.
add(
"trackPreference", jsondataForPreference);
11959 std::string remoteUrl =
"127.0.0.1:9080/playerconfig";
11960 long http_error = -1;
11971 HybridABRManager::AampAbrConfig mhAampAbrConfig;
11996 std::string customData;