RDK Documentation (Open Sourced RDK Components)
priv_aamp.cpp
Go to the documentation of this file.
1 /*
2  * If not stated otherwise in this file or this component's license file the
3  * following copyright and licenses apply:
4  *
5  * Copyright 2020 RDK Management
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18 */
19 
20 /**
21  * @file priv_aamp.cpp
22  * @brief Advanced Adaptive Media Player (AAMP) PrivateInstanceAAMP impl
23  */
24 #include "isobmffprocessor.h"
25 #include "priv_aamp.h"
26 #include "AampJsonObject.h"
27 #include "isobmffbuffer.h"
28 #include "AampFnLogger.h"
29 #include "AampConstants.h"
30 #include "AampCacheHandler.h"
31 #include "AampUtils.h"
32 #include "iso639map.h"
33 #include "fragmentcollector_mpd.h"
34 #include "admanager_mpd.h"
35 #include "fragmentcollector_hls.h"
37 #include "MediaStreamContext.h"
38 #include "hdmiin_shim.h"
39 #include "compositein_shim.h"
40 #include "ota_shim.h"
41 #ifdef USE_CPP_THUNDER_PLUGIN_ACCESS
42 #include "rmf_shim.h"
43 #endif
44 #include "_base64.h"
45 #include "base16.h"
46 #include "aampgstplayer.h"
47 #include "AampDRMSessionManager.h"
48 #include "SubtecFactory.hpp"
49 
50 #ifdef AAMP_CC_ENABLED
51 #include "AampCCManager.h"
52 #endif
53 #ifdef USE_OPENCDM // AampOutputProtection is compiled when this flag is enabled
54 #include "aampoutputprotection.h"
55 #endif
56 
57 #include "AampCurlStore.h"
58 
59 #ifdef IARM_MGR
60 #include "host.hpp"
61 #include "manager.hpp"
62 #include "libIBus.h"
63 #include "libIBusDaemon.h"
64 #include <hostIf_tr69ReqHandler.h>
65 #include <sstream>
66 #endif
67 #include <sys/time.h>
68 #include <cmath>
69 #include <regex>
70 #include <fstream>
71 #include <sys/types.h>
72 #include <sys/stat.h>
73 #include <fcntl.h>
74 #include <uuid/uuid.h>
75 #include <string.h>
76 
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)
80 
81 //Description size
82 #define MAX_DESCRIPTION_SIZE 128
83 
84 //Stringification of Macro : use two levels of macros
85 #define MACRO_TO_STRING(s) X_STR(s)
86 #define X_STR(s) #s
87 
88 // Uncomment to test GetMediaFormatType without locator inspection
89 #define TRUST_LOCATOR_EXTENSION_IF_PRESENT
90 
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; \
95  }
96 
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; \
101  }
102 
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; \
107  }
108 
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
113 
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:"
124 
125 #define MAX_DOWNLOAD_DELAY_LIMIT_MS 30000
126 
127 /**
128  * New state for treating a VOD asset as a "virtual linear" stream
129  */
130 // Note that below state/impl currently assumes single profile, and so until fixed should be tested with "abr" in aamp.cfg to disable ABR
131 static long long simulation_start; // time at which main manifest was downloaded.
132 // Simulation_start is used to calculate elapsed time, used to advance virtual live window
133 static char *full_playlist_video_ptr = NULL; // Cache of initial full vod video playlist
134 static size_t full_playlist_video_len = 0; // Size (bytes) of initial full vod video playlist
135 static char *full_playlist_audio_ptr = NULL; // Cache of initial full vod audio playlist
136 static size_t full_playlist_audio_len = 0; // Size (bytes) of initial full vod audio playlist
137 
138 /**
139  * @struct gActivePrivAAMP_t
140  * @brief Used for storing active PrivateInstanceAAMPs
141  */
143 {
144  PrivateInstanceAAMP* pAAMP;
145  bool reTune;
146  int numPtsErrors;
147 };
148 
149 static std::list<gActivePrivAAMP_t> gActivePrivAAMPs = std::list<gActivePrivAAMP_t>();
150 
151 static pthread_mutex_t gMutex = PTHREAD_MUTEX_INITIALIZER;
152 static pthread_cond_t gCond = PTHREAD_COND_INITIALIZER;
153 
154 static int PLAYERID_CNTR = 0;
155 
156 static const char* strAAMPPipeName = "/tmp/ipc_aamp";
157 
158 static bool activeInterfaceWifi = false;
159 
160 static char previousInterface[20] = {'\0'};
161 
162 static unsigned int ui32CurlTrace = 0;
163 /**
164  * @struct CurlCbContextSyncTime
165  * @brief context during curl callbacks
166  */
168 {
169  PrivateInstanceAAMP *aamp;
170  GrowableBuffer *buffer;
171 
172  CurlCbContextSyncTime() : aamp(NULL), buffer(NULL){}
173  CurlCbContextSyncTime(PrivateInstanceAAMP *_aamp, GrowableBuffer *_buffer) : aamp(_aamp),buffer(_buffer){}
175 
176  CurlCbContextSyncTime(const CurlCbContextSyncTime &other) = delete;
177  CurlCbContextSyncTime& operator=(const CurlCbContextSyncTime& other) = delete;
178 };
179 
180 /**
181  * @brief Enumeration for net_srv_mgr active interface event callback
182  */
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
188 
189 /**
190  * @struct _IARM_BUS_NetSrvMgr_Iface_EventData_t
191  * @brief IARM Bus struct contains active streaming interface, origional definition present in homenetworkingservice.h
192  */
194  union{
195  char activeIface[10];
196  char allNetworkInterfaces[50];
197  char enableInterface[10];
198  };
199  char interfaceCount;
200  bool isInterfaceEnabled;
202 
203 static TuneFailureMap tuneFailureMap[] =
204 {
205  {AAMP_TUNE_INIT_FAILED, 10, "AAMP: init failed"}, //"Fragmentcollector initialization failed"
206  {AAMP_TUNE_INIT_FAILED_MANIFEST_DNLD_ERROR, 10, "AAMP: init failed (unable to download manifest)"},
207  {AAMP_TUNE_INIT_FAILED_MANIFEST_CONTENT_ERROR, 10, "AAMP: init failed (manifest missing tracks)"},
208  {AAMP_TUNE_INIT_FAILED_MANIFEST_PARSE_ERROR, 10, "AAMP: init failed (corrupt/invalid manifest)"},
209  {AAMP_TUNE_INIT_FAILED_PLAYLIST_VIDEO_DNLD_ERROR, 10, "AAMP: init failed (unable to download video playlist)"},
210  {AAMP_TUNE_INIT_FAILED_PLAYLIST_AUDIO_DNLD_ERROR, 10, "AAMP: init failed (unable to download audio playlist)"},
211  {AAMP_TUNE_INIT_FAILED_TRACK_SYNC_ERROR, 10, "AAMP: init failed (unsynchronized tracks)"},
212  {AAMP_TUNE_MANIFEST_REQ_FAILED, 10, "AAMP: Manifest Download failed"}, //"Playlist refresh failed"
213  {AAMP_TUNE_AUTHORISATION_FAILURE, 40, "AAMP: Authorization failure"},
214  {AAMP_TUNE_FRAGMENT_DOWNLOAD_FAILURE, 10, "AAMP: fragment download failures"},
215  {AAMP_TUNE_INIT_FRAGMENT_DOWNLOAD_FAILURE, 10, "AAMP: init fragment download failed"},
216  {AAMP_TUNE_UNTRACKED_DRM_ERROR, 50, "AAMP: DRM error untracked error"},
217  {AAMP_TUNE_DRM_INIT_FAILED, 50, "AAMP: DRM Initialization Failed"},
218  {AAMP_TUNE_DRM_DATA_BIND_FAILED, 50, "AAMP: InitData-DRM Binding Failed"},
219  {AAMP_TUNE_DRM_SESSIONID_EMPTY, 50, "AAMP: DRM Session ID Empty"},
220  {AAMP_TUNE_DRM_CHALLENGE_FAILED, 50, "AAMP: DRM License Challenge Generation Failed"},
221  {AAMP_TUNE_LICENCE_TIMEOUT, 50, "AAMP: DRM License Request Timed out"},
222  {AAMP_TUNE_LICENCE_REQUEST_FAILED, 50, "AAMP: DRM License Request Failed"},
223  {AAMP_TUNE_INVALID_DRM_KEY, 50, "AAMP: Invalid Key Error, from DRM"},
224  {AAMP_TUNE_UNSUPPORTED_STREAM_TYPE, 60, "AAMP: Unsupported Stream Type"}, //"Unable to determine stream type for DRM Init"
225  {AAMP_TUNE_UNSUPPORTED_AUDIO_TYPE, 60, "AAMP: No supported Audio Types in Manifest"},
226  {AAMP_TUNE_FAILED_TO_GET_KEYID, 50, "AAMP: Failed to parse key id from PSSH"},
227  {AAMP_TUNE_FAILED_TO_GET_ACCESS_TOKEN, 50, "AAMP: Failed to get access token from Auth Service"},
228  {AAMP_TUNE_CORRUPT_DRM_DATA, 51, "AAMP: DRM failure due to Corrupt DRM files"},
229  {AAMP_TUNE_CORRUPT_DRM_METADATA, 50, "AAMP: DRM failure due to Bad DRMMetadata in stream"},
230  {AAMP_TUNE_DRM_DECRYPT_FAILED, 50, "AAMP: DRM Decryption Failed for Fragments"},
231  {AAMP_TUNE_DRM_UNSUPPORTED, 50, "AAMP: DRM format Unsupported"},
232  {AAMP_TUNE_DRM_SELF_ABORT, 50, "AAMP: DRM license request aborted by player"},
233  {AAMP_TUNE_GST_PIPELINE_ERROR, 80, "AAMP: Error from gstreamer pipeline"},
234  {AAMP_TUNE_PLAYBACK_STALLED, 7600, "AAMP: Playback was stalled due to lack of new fragments"},
235  {AAMP_TUNE_CONTENT_NOT_FOUND, 20, "AAMP: Resource was not found at the URL(HTTP 404)"},
236  {AAMP_TUNE_DRM_KEY_UPDATE_FAILED, 50, "AAMP: Failed to process DRM key"},
237  {AAMP_TUNE_DEVICE_NOT_PROVISIONED, 52, "AAMP: Device not provisioned"},
238  {AAMP_TUNE_HDCP_COMPLIANCE_ERROR, 53, "AAMP: HDCP Compliance Check Failure"},
239  {AAMP_TUNE_INVALID_MANIFEST_FAILURE, 10, "AAMP: Invalid Manifest, parse failed"},
240  {AAMP_TUNE_FAILED_PTS_ERROR, 80, "AAMP: Playback failed due to PTS error"},
241  {AAMP_TUNE_MP4_INIT_FRAGMENT_MISSING, 10, "AAMP: init fragments missing in playlist"},
242  {AAMP_TUNE_FAILURE_UNKNOWN, 100, "AAMP: Unknown Failure"}
243 };
244 
245 static constexpr const char *BITRATECHANGE_STR[] =
246 {
247  (const char *)"BitrateChanged - Network adaptation", // eAAMP_BITRATE_CHANGE_BY_ABR
248  (const char *)"BitrateChanged - Rampdown due to network failure", // eAAMP_BITRATE_CHANGE_BY_RAMPDOWN
249  (const char *)"BitrateChanged - Reset to default bitrate due to tune", // eAAMP_BITRATE_CHANGE_BY_TUNE
250  (const char *)"BitrateChanged - Reset to default bitrate due to seek", // eAAMP_BITRATE_CHANGE_BY_SEEK
251  (const char *)"BitrateChanged - Reset to default bitrate due to trickplay", // eAAMP_BITRATE_CHANGE_BY_TRICKPLAY
252  (const char *)"BitrateChanged - Rampup since buffers are full", // eAAMP_BITRATE_CHANGE_BY_BUFFER_FULL
253  (const char *)"BitrateChanged - Rampdown since buffers are empty", // eAAMP_BITRATE_CHANGE_BY_BUFFER_EMPTY
254  (const char *)"BitrateChanged - Network adaptation by FOG", // eAAMP_BITRATE_CHANGE_BY_FOG_ABR
255  (const char *)"BitrateChanged - Information from OTA", // eAAMP_BITRATE_CHANGE_BY_OTA
256  (const char *)"BitrateChanged - Video stream information from HDMIIN", // eAAMP_BITRATE_CHANGE_BY_HDMIIN
257  (const char *)"BitrateChanged - Unknown reason" // eAAMP_BITRATE_CHANGE_MAX
258 };
259 
260 #define BITRATEREASON2STRING(id) BITRATECHANGE_STR[id]
261 
262 static constexpr const char *ADEVENT_STR[] =
263 {
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"
270 };
271 
272 #define ADEVENT2STRING(id) ADEVENT_STR[id - AAMP_EVENT_AD_RESERVATION_START]
273 
274 static constexpr const char *mMediaFormatName[] =
275 {
276  "HLS","DASH","PROGRESSIVE","HLS_MP4","OTA","HDMI_IN","COMPOSITE_IN","SMOOTH_STREAMING", "RMF", "UNKNOWN"
277 };
278 
279 static_assert(sizeof(mMediaFormatName)/sizeof(mMediaFormatName[0]) == (eMEDIAFORMAT_UNKNOWN + 1), "Ensure 1:1 mapping between mMediaFormatName[] and enum MediaFormat");
280 /**
281  * @brief Get the idle task's source ID
282  * @retval source ID
283  */
284 static guint aamp_GetSourceID()
285 {
286  guint callbackId = 0;
287  GSource *source = g_main_current_source();
288  if (source != NULL)
289  {
290  callbackId = g_source_get_id(source);
291  }
292  return callbackId;
293 }
294 
295 /**
296  * @brief Idle task to resume aamp
297  * @param ptr pointer to PrivateInstanceAAMP object
298  * @retval True/False
299  */
300 static gboolean PrivateInstanceAAMP_Resume(gpointer ptr)
301 {
302  bool retValue = true;
305  TuneType tuneType = eTUNETYPE_SEEK;
306 
307  if (!aamp->mSeekFromPausedState && (aamp->rate == AAMP_NORMAL_PLAY_RATE))
308  {
309  retValue = aamp->mStreamSink->Pause(false, false);
310  aamp->pipeline_paused = false;
311  }
312  else
313  {
314  // Live immediate : seek to live position from paused state.
316  {
317  tuneType = eTUNETYPE_SEEKTOLIVE;
318  }
319  aamp->rate = AAMP_NORMAL_PLAY_RATE;
320  aamp->pipeline_paused = false;
321  aamp->mSeekFromPausedState = false;
322  aamp->AcquireStreamLock();
323  aamp->TuneHelper(tuneType);
324  aamp->ReleaseStreamLock();
325  }
326 
327  aamp->ResumeDownloads();
328  if(retValue)
329  {
330  aamp->NotifySpeedChanged(aamp->rate);
331  }
332  aamp->mAutoResumeTaskPending = false;
333  return G_SOURCE_REMOVE;
334 }
335 
336 /**
337  * @brief Idle task to process discontinuity
338  * @param ptr pointer to PrivateInstanceAAMP object
339  * @retval G_SOURCE_REMOVE
340  */
341 static gboolean PrivateInstanceAAMP_ProcessDiscontinuity(gpointer ptr)
342 {
344 
345  GSource *src = g_main_current_source();
346  if (src == NULL || !g_source_is_destroyed(src))
347  {
348  bool ret = aamp->ProcessPendingDiscontinuity();
349  // This is to avoid calling cond signal, in case Stop() interrupts the ProcessPendingDiscontinuity
350  if (ret)
351  {
352  aamp->SyncBegin();
353  aamp->mDiscontinuityTuneOperationId = 0;
354  aamp->SyncEnd();
355  }
356  pthread_cond_signal(&aamp->mCondDiscontinuity);
357 
358  }
359  return G_SOURCE_REMOVE;
360 }
361 
362 /**
363  * @brief Tune again to currently viewing asset. Used for internal error handling
364  * @param ptr pointer to PrivateInstanceAAMP object
365  * @retval G_SOURCE_REMOVE
366  */
367 static gboolean PrivateInstanceAAMP_Retune(gpointer ptr)
368 {
370  bool activeAAMPFound = false;
371  bool reTune = false;
372  gActivePrivAAMP_t *gAAMPInstance = NULL;
373  pthread_mutex_lock(&gMutex);
374  for (std::list<gActivePrivAAMP_t>::iterator iter = gActivePrivAAMPs.begin(); iter != gActivePrivAAMPs.end(); iter++)
375  {
376  if (aamp == iter->pAAMP)
377  {
378  gAAMPInstance = &(*iter);
379  activeAAMPFound = true;
380  reTune = gAAMPInstance->reTune;
381  break;
382  }
383  }
384  if (!activeAAMPFound)
385  {
386  AAMPLOG_WARN("PrivateInstanceAAMP: %p not in Active AAMP list", aamp);
387  }
388  else if (!reTune)
389  {
390  AAMPLOG_WARN("PrivateInstanceAAMP: %p reTune flag not set", aamp);
391  }
392  else
393  {
394  if (aamp->pipeline_paused)
395  {
396  aamp->pipeline_paused = false;
397  }
398 
399  aamp->mIsRetuneInProgress = true;
400  pthread_mutex_unlock(&gMutex);
401 
402  aamp->AcquireStreamLock();
404  aamp->ReleaseStreamLock();
405 
406  pthread_mutex_lock(&gMutex);
407  aamp->mIsRetuneInProgress = false;
408  gAAMPInstance->reTune = false;
409  pthread_cond_signal(&gCond);
410  }
411  pthread_mutex_unlock(&gMutex);
412  return G_SOURCE_REMOVE;
413 }
414 
415 
416 /**
417  * @brief Simulate VOD asset as a "virtual linear" stream.
418  */
419 static void SimulateLinearWindow( struct GrowableBuffer *buffer, const char *ptr, size_t len )
420 {
421  // Calculate elapsed time in seconds since virtual linear stream started
422  float cull = (aamp_GetCurrentTimeMS() - simulation_start)/1000.0;
423  buffer->len = 0; // Reset Growable Buffer length
424  float window = 20.0; // Virtual live window size; can be increased/decreasedint
425  const char *fin = ptr+len;
426  bool wroteHeader = false; // Internal state used to decide whether HLS playlist header has already been output
427  int seqNo = 0;
428 
429  while (ptr < fin)
430  {
431  int count = 0;
432  char line[1024];
433  float fragmentDuration;
434 
435  for(;;)
436  {
437  char c = *ptr++;
438  line[count++] = c;
439  if( ptr>=fin || c<' ' ) break;
440  }
441 
442  line[count] = 0x00;
443 
444  if (sscanf(line,"#EXTINF:%f",&fragmentDuration) == 1)
445  {
446  if (cull > 0)
447  {
448  cull -= fragmentDuration;
449  seqNo++;
450  continue; // Not yet in active window
451  }
452 
453  if (!wroteHeader)
454  {
455  // Write a simple linear HLS header, without the type:VOD, and with dynamic media sequence number
456  wroteHeader = true;
457  char header[1024];
458  snprintf( header, sizeof(header),
459  "#EXTM3U\n"
460  "#EXT-X-VERSION:3\n"
461  "#EXT-X-TARGETDURATION:2\n"
462  "#EXT-X-MEDIA-SEQUENCE:%d\n", seqNo );
463  aamp_AppendBytes(buffer, header, strlen(header) );
464  }
465 
466  window -= fragmentDuration;
467 
468  if (window < 0.0)
469  {
470  // Finished writing virtual linear window
471  break;
472  }
473  }
474 
475  if (wroteHeader)
476  {
477  aamp_AppendBytes(buffer, line, count );
478  }
479  }
480 
481  // Following can be used to debug
482  // aamp_AppendNulTerminator( buffer );
483  // printf( "Virtual Linear Playlist:\n%s\n***\n", buffer->ptr );
484 }
485 
486 /**
487  * @brief Get the telemetry type for a media type
488  * @param type media type
489  * @retval telemetry type
490  */
492 {
493  MediaTypeTelemetry ret;
494  switch(type)
495  {
496  case eMEDIATYPE_VIDEO:
497  case eMEDIATYPE_AUDIO:
498  case eMEDIATYPE_SUBTITLE:
500  case eMEDIATYPE_IFRAME:
502  break;
503  case eMEDIATYPE_MANIFEST:
510  break;
517  break;
518  case eMEDIATYPE_LICENCE:
520  break;
521  default:
523  break;
524  }
525  return ret;
526 }
527 
528 /**
529  * @brief de-fog playback URL to play directly from CDN instead of fog
530  * @param[in][out] dst Buffer containing URL
531  */
532 static void DeFog(std::string& url)
533 {
534  std::string prefix("&recordedUrl=");
535  size_t startPos = url.find(prefix);
536  if( startPos != std::string::npos )
537  {
538  startPos += prefix.size();
539  size_t len = url.find( '&',startPos );
540  if( len != std::string::npos )
541  {
542  len -= startPos;
543  }
544  url = url.substr(startPos,len);
546  }
547 }
548 
549 /**
550  * @brief replace all occurrences of existingSubStringToReplace in str with replacementString
551  * @param str string to be scanned/modified
552  * @param existingSubStringToReplace substring to be replaced
553  * @param replacementString string to be substituted
554  * @retval true iff str was modified
555  */
556 static bool replace(std::string &str, const char *existingSubStringToReplace, const char *replacementString)
557 {
558  bool rc = false;
559  std::size_t fromPos = 0;
560  size_t existingSubStringToReplaceLen = 0;
561  size_t replacementStringLen = 0;
562  for(;;)
563  {
564  std::size_t pos = str.find(existingSubStringToReplace,fromPos);
565  if( pos == std::string::npos )
566  { // done - pattern not found
567  break;
568  }
569  if( !rc )
570  { // lazily meaasure input strings - no need to measure unless match found
571  rc = true;
572  existingSubStringToReplaceLen = strlen(existingSubStringToReplace);
573  replacementStringLen = strlen(replacementString);
574  }
575  str.replace( pos, existingSubStringToReplaceLen, replacementString );
576  fromPos = pos + replacementStringLen;
577  }
578  return rc;
579 }
580 
581 #ifdef IARM_MGR
582 
583 /**
584  * @brief Active interface state change from netsrvmgr
585  * @param owner reference to net_srv_mgr
586  * @param IARM eventId received
587  * @data pointer reference to interface struct
588  */
589 void getActiveInterfaceEventHandler (const char *owner, IARM_EventId_t eventId, void *data, size_t len)
590 {
591 
592  if (strcmp (owner, "NET_SRV_MGR") != 0)
593  return;
594 
596 
597  if (NULL == strstr (param->activeIface, previousInterface) || (strlen(previousInterface) == 0))
598  {
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);
602  }
603 
604  if (NULL != strstr (param->activeIface, "wlan"))
605  {
606  activeInterfaceWifi = true;
607  }
608  else if (NULL != strstr (param->activeIface, "eth"))
609  {
610  activeInterfaceWifi = false;
611  }
612 }
613 #endif
614 
615 /**
616  * @brief convert https to https in recordedUrl part of manifestUrl
617  * @param[in][out] dst Buffer containing URL
618  * @param[in]string - https
619  * @param[in]string - http
620  */
621 void ForceHttpCoversionforFog(std::string& url,const std::string& from, const std::string& to)
622 {
623  std::string prefix("&recordedUrl=");
624  size_t startPos = url.find(prefix);
625  if( startPos != std::string::npos )
626  {
627  startPos += prefix.size();
628  url.replace(startPos, from.length(), to);
629  }
630 }
631 /**
632  * @brief Active streaming interface is wifi
633  *
634  * @return bool - true if wifi interface connected
635  */
637 {
638  bool wifiStatus = false;
639 #ifdef IARM_MGR
640  IARM_Result_t ret = IARM_RESULT_SUCCESS;
642 
643  ret = IARM_Bus_Call("NET_SRV_MGR", "getActiveInterface", (void*)&param, sizeof(param));
644  if (ret != IARM_RESULT_SUCCESS) {
645  AAMPLOG_ERR("NET_SRV_MGR getActiveInterface read failed : %d", ret);
646  }
647  else
648  {
649  AAMPLOG_WARN("NET_SRV_MGR getActiveInterface = %s", param.activeIface);
650  if (!strcmp(param.activeIface, "WIFI")){
651  wifiStatus = true;
652  }
653  }
654  IARM_Bus_RegisterEventHandler("NET_SRV_MGR", IARM_BUS_NETWORK_MANAGER_EVENT_INTERFACE_IPADDRESS, getActiveInterfaceEventHandler);
655 #endif
656  return wifiStatus;
657 }
658 
659 /**
660 * @brief helper function to avoid dependency on unsafe sscanf while reading strings
661 * @param buf pointer to CString buffer to scan
662 * @param prefixPtr - prefix string to match in bufPtr
663 * @param valueCopyPtr receives allocated copy of string following prefix (skipping delimiting whitesace) if prefix found
664 * @retval 0 if prefix not present or error
665 * @retval 1 if string extracted/copied to valueCopyPtr
666 */
667 static int ReadConfigStringHelper(std::string buf, const char *prefixPtr, const char **valueCopyPtr)
668 {
669  int ret = 0;
670  if (buf.find(prefixPtr) != std::string::npos)
671  {
672  std::size_t pos = strlen(prefixPtr);
673  if (*valueCopyPtr != NULL)
674  {
675  free((void *)*valueCopyPtr);
676  *valueCopyPtr = NULL;
677  }
678  *valueCopyPtr = strdup(buf.substr(pos).c_str());
679  if (*valueCopyPtr)
680  {
681  ret = 1;
682  }
683  }
684  return ret;
685 }
686 
687 /**
688 * @brief helper function to extract numeric value from given buf after removing prefix
689 * @param buf String buffer to scan
690 * @param prefixPtr - prefix string to match in bufPtr
691 * @param value - receives numeric value after extraction
692 * @retval 0 if prefix not present or error
693 * @retval 1 if string converted to numeric value
694 */
695 template<typename T>
696 static int ReadConfigNumericHelper(std::string buf, const char* prefixPtr, T& value)
697 {
698  int ret = 0;
699 
700  try
701  {
702  std::size_t pos = buf.rfind(prefixPtr,0); // starts with check
703  if (pos != std::string::npos)
704  {
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);
713  else
714  value = std::stod(valStr);
715  ret = 1;
716  }
717  }
718  catch(exception& e)
719  {
720  // NOP
721  }
722 
723  return ret;
724 }
725 
726 
727 // End of helper functions for loading configuration
728 
729 
730 static std::string getTimeStamp(time_t epochTime, const char* format = "%Y-%m-%dT%H:%M:%S.%f%Z")
731 {
732  char timestamp[64] = {0};
733  strftime(timestamp, sizeof(timestamp), format, localtime(&epochTime));
734  return timestamp;
735 }
736 
737 static time_t convertTimeToEpoch(const char* theTime, const char* format = "%Y-%m-%dT%H:%M:%S.%f%Z")
738 {
739  std::tm tmTime;
740  memset(&tmTime, 0, sizeof(tmTime));
741  strptime(theTime, format, &tmTime);
742  return mktime(&tmTime);
743 }
744 
745 // Curl callback functions
746 
747 /**
748  * @brief write callback to be used by CURL
749  * @param ptr pointer to buffer containing the data
750  * @param size size of the buffer
751  * @param nmemb number of bytes
752  * @param userdata CurlCallbackContext pointer
753  * @retval size consumed or 0 if interrupted
754  */
755 static size_t SyncTime_write_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
756 {
757  size_t ret = 0;
758  CurlCbContextSyncTime *context = (CurlCbContextSyncTime *)userdata;
759  pthread_mutex_lock(&context->aamp->mLock);
760  size_t numBytesForBlock = size*nmemb;
761  aamp_AppendBytes(context->buffer, ptr, numBytesForBlock);
762  ret = numBytesForBlock;
763  pthread_mutex_unlock(&context->aamp->mLock);
764  return ret;
765 }
766 
767 /**
768  * @brief HandleSSLWriteCallback - Handle write callback from CURL
769  */
770 size_t PrivateInstanceAAMP::HandleSSLWriteCallback ( char *ptr, size_t size, size_t nmemb, void* userdata )
771 {
772  size_t ret = 0;
773  CurlCallbackContext *context = (CurlCallbackContext *)userdata;
774  if(!context) return ret;
775  pthread_mutex_lock(&context->aamp->mLock);
776  if (context->aamp->mDownloadsEnabled)
777  {
778  if ((NULL == context->buffer->ptr) && (context->contentLength > 0))
779  {
780  size_t len = context->contentLength + 2;
781  /*Add 2 additional characters to take care of extra characters inserted by aamp_AppendNulTerminator*/
782  if(context->downloadIsEncoded && (len < DEFAULT_ENCODED_CONTENT_BUFFER_SIZE))
783  {
784  // Allocate a fixed buffer for encoded contents. Content length is not trusted here
786  }
787  assert(!context->buffer->ptr);
788  context->buffer->ptr = (char *)aamp_Malloc( len );
789  context->buffer->avail = len;
790  }
791  size_t numBytesForBlock = size*nmemb;
792  aamp_AppendBytes(context->buffer, ptr, numBytesForBlock);
793  ret = numBytesForBlock;
794 
795  if(context->aamp->GetLLDashServiceData()->lowLatencyMode &&
796  (context->fileType == eMEDIATYPE_VIDEO ||
797  context->fileType == eMEDIATYPE_AUDIO ||
798  context->fileType == eMEDIATYPE_SUBTITLE))
799  {
800  MediaStreamContext *mCtx = context->aamp->GetMediaStreamContext(context->fileType);
801  if(mCtx)
802  {
803  mCtx->CacheFragmentChunk(context->fileType, ptr, numBytesForBlock,context->remoteUrl,context->downloadStartTime);
804  }
805  }
806  }
807  else
808  {
809  if(ISCONFIGSET_PRIV(eAAMPConfig_EnableCurlStore) && mOrigManifestUrl.isRemotehost)
810  {
811  ret = (size*nmemb);
812  }
813  else
814  {
815  AAMPLOG_WARN("CurlTrace write_callback - interrupted, ret:%zu", ret);
816  }
817  }
818  pthread_mutex_unlock(&context->aamp->mLock);
819 
820  return ret;
821 }
822 /**
823  * @brief write callback to be used by CURL
824  * @param ptr pointer to buffer containing the data
825  * @param size size of the buffer
826  * @param nmemb number of bytes
827  * @param userdata CurlCallbackContext pointer
828  * @retval size consumed or 0 if interrupted
829  */
830 static size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
831 {
832  size_t ret = 0;
833  CurlCallbackContext *context = (CurlCallbackContext *)userdata;
834  if(!context) return ret;
835 
836  ret = context->aamp->HandleSSLWriteCallback( ptr, size, nmemb, userdata);
837  return ret;
838 }
839 
840 /**
841  * @brief function to print header response during download failure and latency.
842  * @param fileType current media type
843  */
844 static void print_headerResponse(std::vector<std::string> &allResponseHeadersForErrorLogging, MediaType fileType)
845 {
846  if (gpGlobalConfig->logging.curlHeader && (eMEDIATYPE_VIDEO == fileType || eMEDIATYPE_PLAYLIST_VIDEO == fileType))
847  {
848  int size = allResponseHeadersForErrorLogging.size();
849  AAMPLOG_WARN("################ Start :: Print Header response ################");
850  for (int i=0; i < size; i++)
851  {
852  AAMPLOG_WARN("* %s", allResponseHeadersForErrorLogging.at(i).c_str());
853  }
854  AAMPLOG_WARN("################ End :: Print Header response ################");
855  }
856 
857  allResponseHeadersForErrorLogging.clear();
858 }
859 
860 /**
861  * @brief HandleSSLHeaderCallback - Hanlde header callback from SSL
862  */
863 size_t PrivateInstanceAAMP::HandleSSLHeaderCallback ( const char *ptr, size_t size, size_t nmemb, void* user_data )
864 {
865  CurlCallbackContext *context = static_cast<CurlCallbackContext *>(user_data);
866  httpRespHeaderData *httpHeader = context->responseHeaderData;
867  size_t len = nmemb * size;
868  size_t startPos = 0;
869  size_t endPos = len-2; // strip CRLF
870 
871  bool isBitrateHeader = false;
872  bool isFogRecordingIdHeader = false;
873  bool isProfileCapHeader = false;
874 
875  if( len<2 || ptr[endPos] != '\r' || ptr[endPos+1] != '\n' )
876  { // only proceed if this is a CRLF terminated curl header, as expected
877  return len;
878  }
879 
880  if (context->aamp->mConfig->IsConfigSet(eAAMPConfig_CurlHeader) && ptr[0] &&
881  (eMEDIATYPE_VIDEO == context->fileType || eMEDIATYPE_PLAYLIST_VIDEO == context->fileType))
882  {
883  std::string temp = std::string(ptr,endPos);
884  context->allResponseHeadersForErrorLogging.push_back(temp);
885  }
886 
887  // As per Hypertext Transfer Protocol ==> Field names are case-insensitive
888  // HTTP/1.1 4.2 Message Headers : Each header field consists of a name followed by a colon (":") and the field value. Field names are case-insensitive
889  if (STARTS_WITH_IGNORE_CASE(ptr, FOG_REASON_STRING))
890  {
891  httpHeader->type = eHTTPHEADERTYPE_FOG_REASON;
892  startPos = STRLEN_LITERAL(FOG_REASON_STRING);
893  }
894  else if (STARTS_WITH_IGNORE_CASE(ptr, CURLHEADER_X_REASON))
895  {
896  httpHeader->type = eHTTPHEADERTYPE_XREASON;
897  startPos = STRLEN_LITERAL(CURLHEADER_X_REASON);
898  }
899  else if (STARTS_WITH_IGNORE_CASE(ptr, BITRATE_HEADER_STRING))
900  {
901  startPos = STRLEN_LITERAL(BITRATE_HEADER_STRING);
902  isBitrateHeader = true;
903  }
904  else if (STARTS_WITH_IGNORE_CASE(ptr, SET_COOKIE_HEADER_STRING))
905  {
906  httpHeader->type = eHTTPHEADERTYPE_COOKIE;
907  startPos = STRLEN_LITERAL(SET_COOKIE_HEADER_STRING);
908  }
909  else if (STARTS_WITH_IGNORE_CASE(ptr, LOCATION_HEADER_STRING))
910  {
911  httpHeader->type = eHTTPHEADERTYPE_EFF_LOCATION;
912  startPos = STRLEN_LITERAL(LOCATION_HEADER_STRING);
913  }
914  else if (STARTS_WITH_IGNORE_CASE(ptr, FOG_RECORDING_ID_STRING))
915  {
916  startPos = STRLEN_LITERAL(FOG_RECORDING_ID_STRING);
917  isFogRecordingIdHeader = true;
918  }
919  else if (STARTS_WITH_IGNORE_CASE(ptr, CONTENT_ENCODING_STRING ))
920  {
921  // Enabled IsEncoded as Content-Encoding header is present
922  // The Content-Encoding entity header incidcates media is compressed
923  context->downloadIsEncoded = true;
924  }
925  else if (context->aamp->mConfig->IsConfigSet(eAAMPConfig_LimitResolution) && context->aamp->IsFirstRequestToFog() && STARTS_WITH_IGNORE_CASE(ptr, CAPPED_PROFILE_STRING ))
926  {
927  startPos = STRLEN_LITERAL(CAPPED_PROFILE_STRING);
928  isProfileCapHeader = true;
929  }
930  else if (STARTS_WITH_IGNORE_CASE(ptr, TRANSFER_ENCODING_STRING ))
931  {
932  context->chunkedDownload = true;
933  }
934  else if (0 == context->buffer->avail)
935  {
936  if (STARTS_WITH_IGNORE_CASE(ptr, CONTENTLENGTH_STRING))
937  {
938  int contentLengthStartPosition = STRLEN_LITERAL(CONTENTLENGTH_STRING);
939  const char * contentLengthStr = ptr + contentLengthStartPosition;
940  context->contentLength = atoi(contentLengthStr);
941  }
942  }
943 
944  // Check for http header tags, only if event listener for HTTPResponseHeaderEvent is available
945  if (eMEDIATYPE_MANIFEST == context->fileType && context->aamp->IsEventListenerAvailable(AAMP_EVENT_HTTP_RESPONSE_HEADER))
946  {
947  std::vector<std::string> responseHeaders = context->aamp->responseHeaders;
948 
949  if (responseHeaders.size() > 0)
950  {
951  for (int header=0; header < responseHeaders.size(); header++) {
952  std::string headerType = responseHeaders[header].c_str();
953  // check if subscribed header is available
954  if (0 == strncasecmp(ptr, headerType.c_str() , headerType.length()))
955  {
956  startPos = headerType.length();
957  // strip only the header value from the response
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());
962  }
963  }
964  }
965  }
966  }
967 
968  if(startPos > 0)
969  {
970  while( endPos>startPos && ptr[endPos-1] == ' ' )
971  { // strip trailing whitespace
972  endPos--;
973  }
974  while( startPos < endPos && ptr[startPos] == ' ')
975  { // strip leading whitespace
976  startPos++;
977  }
978 
979  if(isBitrateHeader)
980  {
981  const char * strBitrate = ptr + startPos;
982  context->bitrate = atol(strBitrate);
983  AAMPLOG_TRACE("Parsed HTTP %s: %ld", isBitrateHeader? "Bitrate": "False", context->bitrate);
984  }
985  else if(isFogRecordingIdHeader)
986  {
987  context->aamp->mTsbRecordingId = string( ptr + startPos, endPos - startPos );
988  AAMPLOG_TRACE("Parsed Fog-Id : %s", context->aamp->mTsbRecordingId.c_str());
989  }
990  else if(isProfileCapHeader)
991  {
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);
995  }
996  else
997  {
998  httpHeader->data = string( ptr + startPos, endPos - startPos );
999  if(httpHeader->type != eHTTPHEADERTYPE_EFF_LOCATION)
1000  { //Append delimiter ";"
1001  httpHeader->data += ';';
1002  }
1003  }
1004 
1006  {
1007  AAMPLOG_TRACE("Parsed HTTP %s header: %s", httpHeader->type==eHTTPHEADERTYPE_COOKIE? "Cookie": "X-Reason", httpHeader->data.c_str());
1008  }
1009  }
1010 
1011  return len;
1012 }
1013 
1014 /**
1015  * @brief Convert to string and add suffix k, M, G
1016  * @param bps bytes Speed
1017  * @param str ptr String buffer
1018  * @retval ptr Converted String buffer
1019  */
1020 char* ConvertSpeedToStr(long bps, char *str)
1021 {
1022  #define ONE_KILO 1024
1023  #define ONE_MEGA ((1024) * ONE_KILO)
1024 
1025  if(bps < 100000)
1026  snprintf(str, 6, "%5ld", bps);
1027 
1028  else if(bps < (10000 * ONE_KILO))
1029  snprintf(str, 6, "%4ld" "k", bps/ONE_KILO);
1030 
1031  else if(bps < (100 * ONE_MEGA))
1032  snprintf(str, 6, "%2ld" ".%0ld" "M", bps/ONE_MEGA,
1033  (bps%ONE_MEGA) / (ONE_MEGA/10) );
1034  else
1035  snprintf(str, 6, "%4ld" "M", bps/ONE_MEGA);
1036 
1037  return str;
1038 }
1039 
1040 
1041 /**
1042  * @brief Get Current Content Download Speed
1043  * @param aamp ptr aamp context
1044  * @param fileType File Type
1045  * @param bDownloadStart Download start flag
1046  * @param start Download start time
1047  * @param dlnow current downloaded bytes
1048  * @retval bps bits per second
1049  */
1051  MediaType fileType, //File Type Download
1052  bool bDownloadStart,
1053  long start,
1054  double dlnow) // downloaded bytes so far)
1055 {
1056  long bitsPerSecond = 0;
1057  long time_now = 0;
1058  long time_diff = 0;
1059  long dl_diff = 0;
1060  char buffer[2][6] = {0,};
1061 
1062  struct SpeedCache* speedcache = NULL;
1063  speedcache = aamp->GetLLDashSpeedCache();
1064 
1065  if(!aamp->mhAbrManager.GetLowLatencyStartABR())
1066  {
1067  speedcache->last_sample_time_val = start;
1068  }
1069 
1070  time_now = NOW_STEADY_TS_MS;
1071  time_diff = (time_now - speedcache->last_sample_time_val);
1072 
1073  if(bDownloadStart)
1074  {
1075  speedcache->prev_dlnow = 0;
1076  }
1077 
1078  dl_diff = (long)dlnow - speedcache->prev_dlnow;
1079 
1080  long prevdlnow = speedcache->prev_dlnow;
1081  speedcache->prev_dlnow = dlnow;
1082 
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;
1088 
1089  //AAMPLOG_INFO("[%d] prev_dlnow: %ld dlnow: %ld dl_diff: %ld total_dl_diff: %ld Current Total Download: %ld Previous Total Download: %ld",fileType, prevdlnow, (long)dlnow, dl_diff,total_dl_diff,currentTotalDownloaded, speedcache->prevSampleTotalDownloaded);
1090 
1091  if(aamp->mhAbrManager.IsABRDataGoodToEstimate(time_diff))
1092  {
1093  aamp->mhAbrManager.CheckLLDashABRSpeedStoreSize(speedcache,bitsPerSecond,time_now,total_dl_diff,time_diff,currentTotalDownloaded);
1094  }
1095  else
1096  {
1097  AAMPLOG_TRACE("[%d] Ignore Speed Calculation -> time_diff [%ld]",fileType, time_diff);
1098  }
1099 
1100  speedcache->totalDownloaded += dl_diff;
1101 
1102  return bitsPerSecond;
1103 }
1104 
1105 /**
1106  * @brief HandleSSLProgressCallback - Process progress callback from CURL
1107  *
1108  * @param clientp opaque context passed by caller
1109  * @param dltotal total number of bytes libcurl expects to download
1110  * @param dlnow number of bytes downloaded so far
1111  * @param ultotal total number of bytes libcurl expects to upload
1112  * @param ulnow number of bytes uploaded so far
1113  *
1114  * @retval -1 to cancel in progress download
1115  */
1116 int PrivateInstanceAAMP::HandleSSLProgressCallback ( void *clientp, double dltotal, double dlnow, double ultotal, double ulnow )
1117 {
1118  CurlProgressCbContext *context = (CurlProgressCbContext *)clientp;
1119  PrivateInstanceAAMP *aamp = context->aamp;
1120  AampConfig *mConfig = context->aamp->mConfig;
1121 
1122  if(context->aamp->GetLLDashServiceData()->lowLatencyMode &&
1123  context->fileType == eMEDIATYPE_VIDEO &&
1124  context->aamp->CheckABREnabled() &&
1125  !(ISCONFIGSET_PRIV(eAAMPConfig_DisableLowLatencyABR)))
1126  {
1127  //AAMPLOG_WARN("[%d] dltotal: %.0f , dlnow: %.0f, ultotal: %.0f, ulnow: %.0f, time: %.0f\n", context->fileType,
1128  // dltotal, dlnow, ultotal, ulnow, difftime(time(NULL), 0));
1129 
1130  int AbrChunkThresholdSize = 0;
1131  GETCONFIGVALUE(eAAMPConfig_ABRChunkThresholdSize,AbrChunkThresholdSize);
1132 
1133  if (/*(dlnow > AbrChunkThresholdSize) &&*/ (context->downloadNow != dlnow))
1134  {
1135  long downloadbps = 0;
1136 
1137  context->downloadNow = dlnow;
1138  context->downloadNowUpdatedTime = NOW_STEADY_TS_MS;
1139 
1140  if(!aamp->mhAbrManager.GetLowLatencyStartABR())
1141  {
1142  //Reset speedcache when Fragment download Starts
1143  struct SpeedCache* speedcache = NULL;
1144  speedcache = aamp->GetLLDashSpeedCache();
1145  memset(speedcache, 0x00, sizeof(struct SpeedCache));
1146  }
1147 
1148  downloadbps = getCurrentContentDownloadSpeed(aamp, context->fileType, context->dlStarted, (long)context->downloadStartTime, dlnow);
1149 
1150  if(context->dlStarted)
1151  {
1152  context->dlStarted = false;
1153  }
1154 
1155  if(!aamp->mhAbrManager.GetLowLatencyStartABR())
1156  {
1157  aamp->mhAbrManager.SetLowLatencyStartABR(true);
1158  }
1159 
1160  if(downloadbps)
1161  {
1162  long currentProfilebps = context->aamp->mpStreamAbstractionAAMP->GetVideoBitrate();
1163 
1164  pthread_mutex_lock(&context->aamp->mLock);
1165  aamp->mhAbrManager.UpdateABRBitrateDataBasedOnCacheLength(context->aamp->mAbrBitrateData,downloadbps,true);
1166  pthread_mutex_unlock(&context->aamp->mLock);
1167  }
1168  }
1169  }
1170 
1171  int rc = 0;
1172  context->aamp->SyncBegin();
1173  if (!context->aamp->mDownloadsEnabled)
1174  {
1175  rc = -1; // CURLE_ABORTED_BY_CALLBACK
1176  }
1177 
1178  context->aamp->SyncEnd();
1179  if( rc==0 )
1180  { // only proceed if not an aborted download
1181  if (dlnow > 0 && context->stallTimeout > 0)
1182  {
1183  if (context->downloadSize == -1)
1184  { // first byte(s) downloaded
1185  context->downloadSize = dlnow;
1186  context->downloadUpdatedTime = NOW_STEADY_TS_MS;
1187  }
1188  else
1189  {
1190  if (dlnow == context->downloadSize)
1191  { // no change in downloaded bytes - check time since last update to infer stall
1192  double timeElapsedSinceLastUpdate = (NOW_STEADY_TS_MS - context->downloadUpdatedTime) / 1000.0; //in secs
1193  if (timeElapsedSinceLastUpdate >= context->stallTimeout)
1194  { // no change for at least <stallTimeout> seconds - consider download stalled and abort
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;
1197  rc = -1;
1198  }
1199  }
1200  else
1201  { // received additional bytes - update state to track new size/time
1202  context->downloadSize = dlnow;
1203  context->downloadUpdatedTime = NOW_STEADY_TS_MS;
1204  }
1205  }
1206  }
1207  if (dlnow == 0 && context->startTimeout > 0)
1208  { // check to handle scenario where <startTimeout> seconds delay occurs without any bytes having been downloaded (stall at start)
1209  double timeElapsedInSec = (double)(NOW_STEADY_TS_MS - context->downloadStartTime) / 1000; //in secs //CID:85922 - UNINTENDED_INTEGER_DIVISION
1210  if (timeElapsedInSec >= context->startTimeout)
1211  {
1212  AAMPLOG_WARN("Abort download as no data received for %.2f seconds", timeElapsedInSec);
1213  context->abortReason = eCURL_ABORT_REASON_START_TIMEDOUT;
1214  rc = -1;
1215  }
1216  }
1217  if (dlnow > 0 && context->lowBWTimeout> 0 && eMEDIATYPE_VIDEO == context->fileType)
1218  {
1219  double elapsedTimeMs = (double)(NOW_STEADY_TS_MS - context->downloadStartTime);
1220  if( elapsedTimeMs >= context->lowBWTimeout*1000 )
1221  {
1222  double predictedTotalDownloadTimeMs = elapsedTimeMs*dltotal/dlnow;
1223  if( predictedTotalDownloadTimeMs > aamp->mNetworkTimeoutMs )
1224  {
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;
1230  rc = -1;
1231  }
1232  }
1233  }
1234  }
1235 
1236  if(rc)
1237  {
1238  if( !( eCURL_ABORT_REASON_LOW_BANDWIDTH_TIMEDOUT == context->abortReason || eCURL_ABORT_REASON_START_TIMEDOUT == context->abortReason ||\
1239  eCURL_ABORT_REASON_STALL_TIMEDOUT == context->abortReason ) && (ISCONFIGSET_PRIV(eAAMPConfig_EnableCurlStore) && mOrigManifestUrl.isRemotehost ) )
1240  {
1241  rc = 0;
1242  }
1243  else
1244  {
1245  AAMPLOG_WARN("CurlTrace Progress interrupted, ret:%d", rc);
1246  }
1247  }
1248  return rc;
1249 }
1250 
1251 /**
1252  * @brief
1253  * @param clientp app-specific as optionally set with CURLOPT_PROGRESSDATA
1254  * @param dltotal total bytes expected to download
1255  * @param dlnow downloaded bytes so far
1256  * @param ultotal total bytes expected to upload
1257  * @param ulnow uploaded bytes so far
1258  * @retval
1259  */
1261  void *clientp, // app-specific as optionally set with CURLOPT_PROGRESSDATA
1262  double dltotal, // total bytes expected to download
1263  double dlnow, // downloaded bytes so far
1264  double ultotal, // total bytes expected to upload
1265  double ulnow // uploaded bytes so far
1266  )
1267 {
1268  CurlProgressCbContext *context = (CurlProgressCbContext *)clientp;
1269 
1270  return context->aamp->HandleSSLProgressCallback ( clientp, dltotal, dlnow, ultotal, ulnow );
1271 }
1272 
1273 // End of curl callback functions
1274 
1275 /**
1276  * @brief PrivateInstanceAAMP Constructor
1277  */
1278 PrivateInstanceAAMP::PrivateInstanceAAMP(AampConfig *config) : mReportProgressPosn(0.0), mAbrBitrateData(), mLock(), mMutexAttr(),
1279  mpStreamAbstractionAAMP(NULL), mInitSuccess(false), mVideoFormat(FORMAT_INVALID), mAudioFormat(FORMAT_INVALID), mDownloadsDisabled(),
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),
1284  durationSeconds(0.0), culledSeconds(0.0), culledOffset(0.0), maxRefreshPlaylistIntervalSecs(DEFAULT_INTERVAL_BETWEEN_PLAYLIST_UPDATES_MS/1000),
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),
1288  mState(eSTATE_RELEASED), mMediaFormat(eMEDIAFORMAT_HLS), mPersistedProfileIndex(0), mAvailableBandwidth(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(),
1295  mVideoEnd(NULL),
1296  mTimeToTopProfile(0),mTimeAtTopProfile(0),mPlaybackDuration(0),mTraceUUID(),
1297  mIsFirstRequestToFOG(false),
1298  mPausePositionMonitorMutex(), mPausePositionMonitorCV(), mPausePositionMonitoringThreadID(), mPausePositionMonitoringThreadStarted(false),
1299  mTuneType(eTUNETYPE_NEW_NORMAL)
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)
1305  ,waitforplaystart()
1306  ,mCurlShared(NULL)
1307  ,mDrmDecryptFailCount(MAX_SEG_DRM_DECRYPT_FAIL_COUNT)
1308  ,mPlaylistTimeoutMs(-1)
1309  ,mMutexPlaystart()
1310 #ifdef AAMP_HLS_DRM
1311  , fragmentCdmEncrypted(false) ,drmParserMutex(), aesCtrAttrDataList()
1312  , drmSessionThreadStarted(false), createDRMSessionThreadID(0)
1313 #endif
1314 #if defined(AAMP_MPD_DRM) || defined(AAMP_HLS_DRM)
1315  , mDRMSessionManager(NULL)
1316 #endif
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)
1325  , mCurrentDrm(), mDrmInitData(), mMinInitialCacheSeconds(DEFAULT_MINIMUM_INIT_CACHE_SECONDS)
1326  //, mLicenseServerUrls()
1327  , mFragmentCachingRequired(false), mFragmentCachingLock()
1328  , mPauseOnFirstVideoFrameDisp(false)
1329  , mPreferredTextTrack(), mFirstVideoFrameDisplayedEnabled(false)
1330  , mSessionToken()
1331  , vDynamicDrmData()
1332  , midFragmentSeekCache(false)
1333  , mPreviousAudioType (FORMAT_INVALID)
1334  , mTsbRecordingId()
1335  , mthumbIndexValue(-1)
1336  , mManifestRefreshCount (0)
1337  , mJumpToLiveFromPause(false), mPausedBehavior(ePAUSED_BEHAVIOR_AUTOPLAY_IMMEDIATE), mSeekFromPausedState(false)
1338  , mProgramDateTime (0), mMPDPeriodsInfo()
1339  , mProfileCappedStatus(false),mSchemeIdUriDai("")
1340  , mDisplayWidth(0)
1341  , mDisplayHeight(0)
1342  , preferredRenditionString("")
1343  , preferredRenditionList()
1344  , preferredTypeString("")
1345  , preferredCodecString("")
1346  , preferredCodecList()
1347  , mAudioTuple()
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)
1358  , mStreamLock()
1359  , mConfig (config),mSubLanguage(), mHarvestCountLimit(0), mHarvestConfig(0)
1360  , mIsWVKIDWorkaround(false)
1361  , mAuxFormat(FORMAT_INVALID), mAuxAudioLanguage()
1362  , mAbsoluteEndPosition(0), mIsLiveStream(false)
1363  , mbUsingExternalPlayer (false)
1364  , mCCId(0)
1365  , seiTimecode()
1366  , contentGaps()
1367  , mAampLLDashServiceData{}
1368  , bLowLatencyServiceConfigured(false)
1369  , bLLDashAdjustPlayerSpeed(false)
1370  , mLLDashCurrentPlayRate(AAMP_NORMAL_PLAY_RATE)
1371  , vidTimeScale(0)
1372  , audTimeScale(0)
1373  , speedCache {}
1374  , mTime (0)
1375  , mCurrentLatency(0)
1376  , mLiveOffsetAppRequest(false)
1377  , bLowLatencyStartABR(false)
1378  , mWaitForDiscoToComplete()
1379  , mDiscoCompleteLock()
1380  , mIsPeriodChangeMarked(false)
1381  , mLogObj(NULL)
1382  , mEventManager (NULL)
1383  , mbDetached(false)
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)
1395  , mbSeeked(false)
1396  , mFailureReason("")
1397  , mTimedMetadataStartTime(0)
1398  , mTimedMetadataDuration(0)
1399  , playerStartedWithTrickPlay(false)
1400  , mPlaybackMode("UNKNOWN")
1401  , mApplyVideoRect(false)
1402  , mVideoRect{}
1403  , mData(NULL)
1404  , mIsInbandCC(true)
1405  , bitrateList()
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)
1421  , playerrate(1.0)
1422  , mSetPlayerRateAfterFirstframe(false)
1423  , mEncryptedPeriodFound(false)
1424  , mPipelineIsClear(false)
1425  , mLLActualOffset(-1)
1426  , mIsStream4K(false)
1427  , mTextStyle()
1428 {
1429  for(int i=0; i<eMEDIATYPE_DEFAULT; i++)
1430  {
1431  lastId3Data[i] = NULL;
1432  lastId3DataLen[i] = 0;
1433  }
1434  mLogObj = mConfig->GetLoggerInstance();
1435  //LazilyLoadConfigIfNeeded();
1436  mAampCacheHandler = new AampCacheHandler(mConfig->GetLoggerInstance());
1437 #ifdef AAMP_CC_ENABLED
1438  AampCCManager::GetInstance()->SetLogger(mConfig->GetLoggerInstance());
1439 #endif
1440  profiler.SetLogger(mConfig->GetLoggerInstance());
1441  // Create the event manager for player instance
1442  mEventManager = new AampEventManager(mLogObj);
1443  SETCONFIGVALUE_PRIV(AAMP_APPLICATION_SETTING,eAAMPConfig_UserAgent, (std::string )AAMP_USERAGENT_BASE_STRING);
1444  int maxDrmSession;
1445  GETCONFIGVALUE_PRIV(eAAMPConfig_MaxDASHDRMSessions,maxDrmSession);
1446  GETCONFIGVALUE_PRIV(eAAMPConfig_PreferredAudioLanguage,preferredLanguagesString);
1447  GETCONFIGVALUE_PRIV(eAAMPConfig_PreferredAudioRendition,preferredRenditionString);
1448  GETCONFIGVALUE_PRIV(eAAMPConfig_PreferredAudioCodec,preferredCodecString);
1449  GETCONFIGVALUE_PRIV(eAAMPConfig_PreferredAudioLabel,preferredLabelsString);
1450  GETCONFIGVALUE_PRIV(eAAMPConfig_PreferredAudioType,preferredTypeString);
1451  GETCONFIGVALUE_PRIV(eAAMPConfig_PreferredTextRendition,preferredTextRenditionString);
1452  GETCONFIGVALUE_PRIV(eAAMPConfig_PreferredTextLanguage,preferredTextLanguagesString);
1453  GETCONFIGVALUE_PRIV(eAAMPConfig_PreferredTextLabel,preferredTextLabelString);
1454  GETCONFIGVALUE_PRIV(eAAMPConfig_PreferredTextType,preferredTextTypeString);
1455 #if defined(AAMP_MPD_DRM) || defined(AAMP_HLS_DRM)
1456  mDRMSessionManager = new AampDRMSessionManager(mLogObj, maxDrmSession);
1457 #endif
1458  pthread_cond_init(&mDownloadsDisabled, NULL);
1459  GETCONFIGVALUE_PRIV(eAAMPConfig_SubTitleLanguage,mSubLanguage);
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);
1469 
1470  for (int i = 0; i < eCURLINSTANCE_MAX; i++)
1471  {
1472  curl[i] = NULL;
1473  //cookieHeaders[i].clear();
1474  httpRespHeaders[i].type = eHTTPHEADERTYPE_UNKNOWN;
1475  httpRespHeaders[i].data.clear();
1476  curlDLTimeout[i] = 0;
1477  }
1478 
1479  if( ISCONFIGSET_PRIV(eAAMPConfig_EnableCurlStore) )
1480  {
1481  for (int i = 0; i < eCURLINSTANCE_MAX; i++)
1482  {
1483  curlhost[i] = new eCurlHostMap();
1484  }
1485  }
1486 
1487  for (int i = 0; i < AAMP_TRACK_COUNT; i++)
1488  {
1489  mbTrackDownloadsBlocked[i] = false;
1490  mTrackInjectionBlocked[i] = false;
1491  lastUnderFlowTimeMs[i] = 0;
1492  mProcessingDiscontinuity[i] = false;
1493  mIsDiscontinuityIgnored[i] = false;
1494  }
1495 
1496  pthread_mutex_lock(&gMutex);
1497  gActivePrivAAMP_t gAAMPInstance = { this, false, 0 };
1498  gActivePrivAAMPs.push_back(gAAMPInstance);
1499  pthread_mutex_unlock(&gMutex);
1500  mPendingAsyncEvents.clear();
1501 
1502  if (ISCONFIGSET_PRIV(eAAMPConfig_WifiCurlHeader)) {
1503  if (true == IsActiveStreamingInterfaceWifi()) {
1504  mCustomHeaders["Wifi:"] = std::vector<std::string> { "1" };
1505  activeInterfaceWifi = true;
1506  }
1507  else
1508  {
1509  mCustomHeaders["Wifi:"] = std::vector<std::string> { "0" };
1510  activeInterfaceWifi = false;
1511  }
1512  }
1513  // Add Connection: Keep-Alive custom header - DELIA-26832
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");
1521 
1522 #ifdef AAMP_HLS_DRM
1523  memset(&aesCtrAttrDataList, 0, sizeof(aesCtrAttrDataList));
1524  pthread_mutex_init(&drmParserMutex, NULL);
1525 #endif
1526  GETCONFIGVALUE_PRIV(eAAMPConfig_HarvestCountLimit,mHarvestCountLimit);
1527  GETCONFIGVALUE_PRIV(eAAMPConfig_HarvestConfig,mHarvestConfig);
1528  mAsyncTuneEnabled = ISCONFIGSET_PRIV(eAAMPConfig_AsyncTune);
1529  }
1530 
1531 /**
1532  * @brief PrivateInstanceAAMP Destructor
1533  */
1535 {
1536  StopPausePositionMonitoring("AAMP destroyed");
1537 #ifdef AAMP_CC_ENABLED
1539  mCCId = 0;
1540 #endif
1541  pthread_mutex_lock(&gMutex);
1542  auto iter = std::find_if(std::begin(gActivePrivAAMPs), std::end(gActivePrivAAMPs), [this](const gActivePrivAAMP_t& el)
1543  {
1544  return el.pAAMP == this;
1545  });
1546  if(iter != gActivePrivAAMPs.end())
1547  {
1548  gActivePrivAAMPs.erase(iter);
1549  }
1550  pthread_mutex_unlock(&gMutex);
1551 
1552  pthread_mutex_lock(&mLock);
1553 
1554  SAFE_DELETE(mVideoEnd);
1555 
1556  pthread_mutex_unlock(&mLock);
1557 
1558  pthread_cond_destroy(&mDownloadsDisabled);
1559  pthread_cond_destroy(&mWaitForDynamicDRMToUpdate);
1560  pthread_cond_destroy(&mCondDiscontinuity);
1561  pthread_cond_destroy(&waitforplaystart);
1562  pthread_cond_destroy(&mWaitForDiscoToComplete);
1563  pthread_mutex_destroy(&mMutexPlaystart);
1564  pthread_mutex_destroy(&mLock);
1565  pthread_mutex_destroy(&mDynamicDrmUpdateLock);
1566  pthread_mutex_destroy(&mParallelPlaylistFetchLock);
1567  pthread_mutex_destroy(&mFragmentCachingLock);
1568  pthread_mutex_destroy(&mEventLock);
1569  pthread_mutex_destroy(&mStreamLock);
1570  pthread_mutex_destroy(&mDiscoCompleteLock);
1571  pthread_mutexattr_destroy(&mMutexAttr);
1572 #ifdef AAMP_HLS_DRM
1573  aesCtrAttrDataList.clear();
1574  pthread_mutex_destroy(&drmParserMutex);
1575 #endif
1576  SAFE_DELETE(mAampCacheHandler);
1577 
1578 #if defined(AAMP_MPD_DRM) || defined(AAMP_HLS_DRM)
1579  SAFE_DELETE(mDRMSessionManager);
1580 #endif
1581 
1582  if( ISCONFIGSET_PRIV(eAAMPConfig_EnableCurlStore) )
1583  {
1584  for (int i = 0; i < eCURLINSTANCE_MAX; i++)
1585  {
1586  SAFE_DELETE(curlhost[i]);
1587  }
1588  }
1589 
1590  if ( !(ISCONFIGSET_PRIV(eAAMPConfig_EnableCurlStore)) )
1591  {
1592  if(mCurlShared)
1593  {
1594  curl_share_cleanup(mCurlShared);
1595  mCurlShared = NULL;
1596  }
1597  }
1598 #ifdef IARM_MGR
1599  IARM_Bus_RemoveEventHandler("NET_SRV_MGR", IARM_BUS_NETWORK_MANAGER_EVENT_INTERFACE_IPADDRESS, getActiveInterfaceEventHandler);
1600 #endif //IARM_MGR
1601  SAFE_DELETE(mEventManager);
1602 
1603  if (HasSidecarData())
1604  { // has sidecar data
1605  SAFE_DELETE_ARRAY(mData);
1606  mData = NULL;
1609  }
1610 }
1611 
1612 /**
1613  * @brief perform pause of the pipeline and notifications for PauseAt functionality
1614  */
1615 static gboolean PrivateInstanceAAMP_PausePosition(gpointer ptr)
1616 {
1618  long long pausePositionMilliseconds = aamp->mPausePositionMilliseconds;
1619  aamp->mPausePositionMilliseconds = AAMP_PAUSE_POSITION_INVALID_POSITION;
1620 
1621  if (pausePositionMilliseconds != AAMP_PAUSE_POSITION_INVALID_POSITION)
1622  {
1623  if (!aamp->mStreamSink->Pause(true, false))
1624  {
1625  AAMPLOG_ERR("Pause failed");
1626  }
1627  aamp->pipeline_paused = true;
1628 
1629  aamp->StopDownloads();
1630 
1631  if (aamp->mpStreamAbstractionAAMP)
1632  {
1634  }
1635 
1636  bool updateSeekPosition = false;
1637  if ((aamp->rate > AAMP_NORMAL_PLAY_RATE) || (aamp->rate < AAMP_RATE_PAUSE) ||
1639  {
1640  aamp->seek_pos_seconds = aamp->GetPositionSeconds();
1641  aamp->trickStartUTCMS = -1;
1642  AAMPLOG_INFO("Updated seek pos %fs", aamp->seek_pos_seconds);
1643  updateSeekPosition = true;
1644  }
1645  else
1646  {
1647  // (See SetRateInternal)
1649  {
1650  aamp->seek_pos_seconds = aamp->GetPositionSeconds();
1651  aamp->trickStartUTCMS = -1;
1652  AAMPLOG_INFO("Updated seek pos %fs", aamp->seek_pos_seconds);
1653  updateSeekPosition = true;
1654  }
1655  }
1656 
1657 
1658  long long positionMs = aamp->GetPositionMilliseconds();
1659  if (updateSeekPosition)
1660  {
1661  AAMPLOG_WARN("PLAYER[%d] Paused at position %lldms, requested position %lldms, rate %f, seek pos updated to %fs",
1662  aamp->mPlayerId, positionMs, pausePositionMilliseconds, aamp->rate, aamp->seek_pos_seconds);
1663  }
1664  else
1665  {
1666  AAMPLOG_WARN("PLAYER[%d] Paused at position %lldms, requested position %lldms, rate %f",
1667  aamp->mPlayerId, positionMs, pausePositionMilliseconds, aamp->rate);
1668  }
1669 
1670  // Notify the client that play has paused
1671  aamp->NotifySpeedChanged(0, true);
1672  }
1673  return G_SOURCE_REMOVE;
1674 }
1675 
1676 /**
1677  * @brief the PositionMonitoring thread used for PauseAt functionality
1678  */
1680 {
1681  long long localPauseAtMilliseconds = mPausePositionMilliseconds;
1682  long long posMs = GetPositionMilliseconds();
1683  int previousPollPeriodMs = 0;
1684  int previousVodTrickplayFPS = 0;
1685 
1686  AAMPLOG_WARN("PLAYER[%d] Pause at position %lldms, current position %lldms, rate %f",
1687  mPlayerId, mPausePositionMilliseconds.load(), posMs, rate);
1688 
1689  while(localPauseAtMilliseconds != AAMP_PAUSE_POSITION_INVALID_POSITION)
1690  {
1691  int pollPeriodMs = AAMP_PAUSE_POSITION_POLL_PERIOD_MS;
1692  long long trickplayTargetPosMs = localPauseAtMilliseconds;
1693  bool forcePause = false;
1694 
1695  if ((rate == AAMP_RATE_PAUSE) || pipeline_paused)
1696  {
1697  // Shouldn't get here if already paused
1698  AAMPLOG_WARN("Already paused, exiting loop");
1699  mPausePositionMilliseconds = AAMP_PAUSE_POSITION_INVALID_POSITION;
1700  break;
1701  }
1702  // If normal speed or slower, i.e. not iframe trick mode
1703  else if ((rate > AAMP_RATE_PAUSE) && (rate <= AAMP_NORMAL_PLAY_RATE))
1704  {
1705  // If current pos is within a poll period of the target position,
1706  // set the sleep time to be the difference, and then perform
1707  // the pause.
1708  if (posMs >= (localPauseAtMilliseconds - pollPeriodMs))
1709  {
1710  pollPeriodMs = (localPauseAtMilliseconds - posMs) / rate;
1711  forcePause = true;
1712  AAMPLOG_INFO("Requested pos %lldms current pos %lldms rate %f, pausing in %dms",
1713  localPauseAtMilliseconds, posMs, rate, pollPeriodMs);
1714  }
1715  else
1716  {
1717  // The first time print WARN diag
1718  if (previousPollPeriodMs != pollPeriodMs)
1719  {
1720  AAMPLOG_WARN("PLAYER[%d] Polling period %dms, rate %f",
1721  mPlayerId, pollPeriodMs, rate);
1722  previousPollPeriodMs = pollPeriodMs;
1723  }
1724  AAMPLOG_INFO("Requested pos %lldms current pos %lldms rate %f, polling period %dms",
1725  localPauseAtMilliseconds, posMs, rate, pollPeriodMs);
1726  }
1727  }
1728  else
1729  {
1730  int vodTrickplayFPS = 0;
1731  bool config_valid = GETCONFIGVALUE_PRIV(eAAMPConfig_VODTrickPlayFPS,vodTrickplayFPS);
1732 
1733  assert (config_valid && (vodTrickplayFPS != 0));
1734 
1735  // Poll at half the frame period (twice the frame rate)
1736  pollPeriodMs = (1000 / vodTrickplayFPS) / 2;
1737 
1738  // If rate > 0, the target position should be earlier than requested pos
1739  // If rate < 0, the target position should be later than requested pos
1740  trickplayTargetPosMs -= ((rate * 1000) / vodTrickplayFPS);
1741 
1742  if ((previousPollPeriodMs != pollPeriodMs) ||
1743  (previousVodTrickplayFPS != vodTrickplayFPS))
1744  {
1745  AAMPLOG_WARN("PLAYER[%d] Polling period %dms, rate %f, fps %d",
1746  mPlayerId, pollPeriodMs, rate, vodTrickplayFPS);
1747  previousPollPeriodMs = pollPeriodMs;
1748  previousVodTrickplayFPS = vodTrickplayFPS;
1749  }
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);
1752  }
1753 
1754  // The calculation of pollPeriodMs for playback speeds, could result in a negative value
1755  if (pollPeriodMs > 0)
1756  {
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);
1761 
1762  // Wait until now + pollPeriodMs, unless pauseAt is being cancelled
1763  while ((localPauseAtMilliseconds != AAMP_PAUSE_POSITION_INVALID_POSITION) &&
1764  (cvStatus == std::cv_status::no_timeout))
1765  {
1766  cvStatus = mPausePositionMonitorCV.wait_until(lock, waitUntilMs);
1767  localPauseAtMilliseconds = mPausePositionMilliseconds;
1768  }
1769  if (localPauseAtMilliseconds == AAMP_PAUSE_POSITION_INVALID_POSITION)
1770  {
1771  break;
1772  }
1773  }
1774 
1775  // Only need to get an updated pos if not forcing pause
1776  if (!forcePause)
1777  {
1778  posMs = GetPositionMilliseconds();
1779  }
1780 
1781  // Check if forcing pause at playback, or exceeded target position for trickplay
1782  if (forcePause ||
1783  ((rate > AAMP_NORMAL_PLAY_RATE) && (posMs >= trickplayTargetPosMs)) ||
1784  ((rate < AAMP_RATE_PAUSE) && (posMs <= trickplayTargetPosMs)))
1785  {
1786  (void)ScheduleAsyncTask(PrivateInstanceAAMP_PausePosition, this, "PrivateInstanceAAMP_PausePosition");
1787  break;
1788  }
1789  }
1790 }
1791 
1792 /**
1793  * @brief call the PausePositionMonitoring thread loop
1794  */
1795 static void *PausePositionMonitor(void *arg)
1796 {
1798 
1799  // Thread name restricted to 16 characters, including null
1800  if(aamp_pthread_setname(pthread_self(), "aampPauseMon"))
1801  {
1802  AAMPLOG_WARN("aamp_pthread_setname failed");
1803  }
1805  return nullptr;
1806 }
1807 
1808 /**
1809  * @brief start the PausePositionMonitoring thread used for PauseAt functionality
1810  */
1811 void PrivateInstanceAAMP::StartPausePositionMonitoring(long long pausePositionMilliseconds)
1812 {
1813  StopPausePositionMonitoring("Start new pos monitor");
1814 
1815  if (pausePositionMilliseconds < 0)
1816  {
1817  AAMPLOG_ERR("The position (%lld) must be >= 0", pausePositionMilliseconds);
1818  }
1819  else
1820  {
1821  mPausePositionMilliseconds = pausePositionMilliseconds;
1822 
1823  AAMPLOG_INFO("Start PausePositionMonitoring at position %lld", pausePositionMilliseconds);
1824 
1825  if (0 == pthread_create(&mPausePositionMonitoringThreadID, nullptr, &PausePositionMonitor, this))
1826  {
1827  mPausePositionMonitoringThreadStarted = true;
1828  }
1829  else
1830  {
1831  AAMPLOG_ERR("Failed to create PausePositionMonitor thread");
1832  }
1833  }
1834 }
1835 
1836 /**
1837  * @brief stop the PausePositionMonitoring thread used for PauseAt functionality
1838  */
1840 {
1841  if (mPausePositionMonitoringThreadStarted)
1842  {
1843  std::unique_lock<std::mutex> lock(mPausePositionMonitorMutex);
1844 
1845  if (mPausePositionMilliseconds != AAMP_PAUSE_POSITION_INVALID_POSITION)
1846  {
1847  long long positionMs = GetPositionMilliseconds();
1848  AAMPLOG_WARN("PLAYER[%d] Stop position monitoring, reason: '%s', current position %lldms, requested position %lldms, rate %f",
1849  mPlayerId, reason.c_str(), positionMs, mPausePositionMilliseconds.load(), rate);
1850  mPausePositionMilliseconds = AAMP_PAUSE_POSITION_INVALID_POSITION;
1851  mPausePositionMonitorCV.notify_one();
1852  }
1853  lock.unlock();
1854 
1855  int rc = pthread_join(mPausePositionMonitoringThreadID, NULL);
1856  if (rc != 0)
1857  {
1858  AAMPLOG_ERR("***pthread_join PausePositionMonitor returned %d(%s)", rc, strerror(rc));
1859  }
1860  else
1861  {
1862  AAMPLOG_INFO("Joined PausePositionMonitor");
1863  }
1864  mPausePositionMonitoringThreadStarted = false;
1865  }
1866 }
1867 
1868 /**
1869  * @brief wait for Discontinuity handling complete
1870  */
1872 {
1873  pthread_mutex_lock(&mDiscoCompleteLock);
1874  pthread_cond_wait(&mWaitForDiscoToComplete, &mDiscoCompleteLock);
1875  pthread_mutex_unlock(&mDiscoCompleteLock);
1876 }
1877 
1878 /**
1879  * @brief unblock wait for Discontinuity handling complete
1880  */
1882 {
1883  mIsPeriodChangeMarked = false;
1884 
1885  pthread_mutex_lock(&mDiscoCompleteLock);
1886  pthread_cond_signal(&mWaitForDiscoToComplete);
1887  pthread_mutex_unlock(&mDiscoCompleteLock);
1888 }
1889 
1890 /**
1891  * @brief GStreamer operation start
1892  */
1894 {
1895  pthread_mutex_lock(&mLock);
1896 }
1897 
1898 /**
1899  * @brief GStreamer operation end
1900  *
1901  */
1903 {
1904  pthread_mutex_unlock(&mLock);
1905 }
1906 
1907 /**
1908  * @brief Report progress event
1909  */
1910 long long PrivateInstanceAAMP::GetVideoPTS(bool bAddVideoBasePTS)
1911 {
1912  /*For HLS, tsprocessor.cpp removes the base PTS value and sends to gstreamer.
1913  **In order to report PTS of video currently being played out, we add the base PTS
1914  **to video PTS received from gstreamer
1915  */
1916  /*For DASH,mVideoBasePTS value will be zero */
1917  long long videoPTS = -1;
1918  videoPTS = mStreamSink->GetVideoPTS();
1919  if(bAddVideoBasePTS)
1920  videoPTS += mVideoBasePTS;
1921  AAMPLOG_WARN("Video-PTS=%lld, mVideoBasePTS=%lld Add VideoBase PTS[%d]",videoPTS,mVideoBasePTS,bAddVideoBasePTS);
1922  return videoPTS;
1923 }
1924 
1925 /**
1926  * @brief Report progress event to listeners
1927  */
1928 void PrivateInstanceAAMP::ReportProgress(bool sync, bool beginningOfStream)
1929 {
1930  PrivAAMPState state;
1931  GetState(state);
1932 
1933  if (state == eSTATE_SEEKING)
1934  {
1935  AAMPLOG_WARN("Progress reporting skipped whilst seeking.");
1936  }
1937 
1938  //Once GST_MESSAGE_EOS is received, AAMP does not want any stray progress to be sent to player. so added the condition state != eSTATE_COMPLETE
1939  if (mDownloadsEnabled && (state != eSTATE_IDLE) && (state != eSTATE_RELEASED) && (state != eSTATE_COMPLETE) && (state != eSTATE_SEEKING))
1940  {
1941  ReportAdProgress(sync);
1942 
1943  // set position to 0 if the rewind operation has reached Beginning Of Stream
1944  double position = beginningOfStream? 0: GetPositionMilliseconds();
1945  double duration = durationSeconds * 1000.0;
1946  float speed = pipeline_paused ? 0 : rate;
1947  double start = -1;
1948  double end = -1;
1949  long long videoPTS = -1;
1950  double bufferedDuration = 0.0;
1951  bool bProcessEvent = true;
1952 
1953  // If tsb is not available for linear send -1 for start and end
1954  // so that xre detect this as tsbless playabck
1955  // Override above logic if mEnableSeekableRange is set, used by third-party apps
1956  if (!ISCONFIGSET_PRIV(eAAMPConfig_EnableSeekRange) && (mContentType == ContentType_LINEAR && !mTSBEnabled))
1957  {
1958  start = -1;
1959  end = -1;
1960  }
1961  else
1962  { //DELIA-49735 - Report Progress report position based on Availability Start Time
1963  start = (culledSeconds*1000.0);
1965  {
1966  end = (mAbsoluteEndPosition * 1000);
1967  }
1968  else
1969  {
1970  end = start + duration;
1971  }
1972 
1973  if (position > end)
1974  { // clamp end
1975  //AAMPLOG_WARN("aamp clamp end");
1976  position = end;
1977  }
1978  else if (position < start)
1979  { // clamp start
1980  //AAMPLOG_WARN("aamp clamp start");
1981  position = start;
1982  }
1983  }
1984 
1985  if(ISCONFIGSET_PRIV(eAAMPConfig_ReportVideoPTS))
1986  {
1987  /*For HLS, tsprocessor.cpp removes the base PTS value and sends to gstreamer.
1988  **In order to report PTS of video currently being played out, we add the base PTS
1989  **to video PTS received from gstreamer
1990  */
1991  /*For DASH,mVideoBasePTS value will be zero */
1992  videoPTS = mStreamSink->GetVideoPTS() + mVideoBasePTS;
1993  }
1994 
1995  pthread_mutex_lock(&mStreamLock);
1997  {
1998  bufferedDuration = mpStreamAbstractionAAMP->GetBufferedVideoDurationSec() * 1000.0;
1999  }
2000  pthread_mutex_unlock(&mStreamLock);
2001 
2002  if ((mReportProgressPosn == position) && !pipeline_paused && beginningOfStream != true)
2003  {
2004  // Avoid sending the progress event, if the previous position and the current position is same when pipeline is in playing state.
2005  // Addded exception if it's beginning of stream to prevent JSPP not loading previous AD while rewind
2006  bProcessEvent = false;
2007  }
2008 
2009  /*LLAMA-7142 & LLAMA-7124
2010  **mNewSeekInfo is:
2011  ** -Used by PlayerInstanceAAMP::SetRateInternal() to calculate seek position.
2012  ** -Included for consistency with previous code but isn't directly related to reporting.
2013  ** -A good candidate for future refactoring*/
2014  mNewSeekInfo.Update(position, seek_pos_seconds);
2015 
2016  double reportFormatPosition = position;
2017  if(ISCONFIGSET_PRIV(eAAMPConfig_UseAbsoluteTimeline) && ISCONFIGSET_PRIV(eAAMPConfig_InterruptHandling) && mTSBEnabled)
2018  {
2019  start -= (mProgressReportOffset * 1000);
2020  reportFormatPosition -= (mProgressReportOffset * 1000);
2021  end -= (mProgressReportOffset * 1000);
2022  }
2023 
2024  ProgressEventPtr evt = std::make_shared<ProgressEvent>(duration, reportFormatPosition, start, end, speed, videoPTS, bufferedDuration, seiTimecode.c_str());
2025 
2026  if (trickStartUTCMS >= 0 && (bProcessEvent || mFirstProgress))
2027  {
2028  if (mFirstProgress)
2029  {
2030  mFirstProgress = false;
2031  AAMPLOG_WARN("Send first progress event with position %ld", (long)(reportFormatPosition / 1000));
2032  }
2033 
2034  if (ISCONFIGSET_PRIV(eAAMPConfig_ProgressLogging))
2035  {
2036  static int tick;
2037  if ((tick++ % 4) == 0)
2038  {
2039  AAMPLOG_WARN("aamp pos: [%ld..%ld..%ld..%lld..%ld..%s]",
2040  (long)(start / 1000),
2041  (long)(reportFormatPosition / 1000),
2042  (long)(end / 1000),
2043  (long long) videoPTS,
2044  (long)(bufferedDuration / 1000),
2045  seiTimecode.c_str() );
2046  }
2047  }
2048 
2049  if (sync)
2050  {
2052  }
2053  else
2054  {
2055  mEventManager->SendEvent(evt);
2056  }
2057 
2058  mReportProgressPosn = position;
2059  }
2060  }
2061 }
2062 
2063 /**
2064  * @brief Report Ad progress event to listeners
2065  * Sending Ad progress percentage to JSPP
2066  */
2068 {
2069  if (mDownloadsEnabled && !mAdProgressId.empty())
2070  {
2071  long long curTime = NOW_STEADY_TS_MS;
2072  if (!pipeline_paused)
2073  {
2074  //Update the percentage only if the pipeline is in playing.
2075  mAdCurOffset += (uint32_t)(curTime - mAdPrevProgressTime);
2076  if(mAdCurOffset > mAdDuration) mAdCurOffset = mAdDuration;
2077  }
2078  mAdPrevProgressTime = curTime;
2079 
2080  AdPlacementEventPtr evt = std::make_shared<AdPlacementEvent>(AAMP_EVENT_AD_PLACEMENT_PROGRESS, mAdProgressId, (uint32_t)(mAdCurOffset * 100) / mAdDuration);
2081  if(sync)
2082  {
2084  }
2085  else
2086  {
2087  mEventManager->SendEvent(evt);
2088  }
2089  }
2090 }
2091 
2092 /**
2093  * @brief Update playlist duration
2094  */
2096 {
2097  AAMPLOG_INFO("aamp_UpdateDuration(%f)", seconds);
2098  durationSeconds = seconds;
2099 }
2100 
2101 /**
2102  * @brief Update playlist culling
2103  */
2105 {
2106  if (culledSecs == 0)
2107  {
2108  return;
2109  }
2110 
2111  if((!this->culledSeconds) && culledSecs)
2112  {
2113  AAMPLOG_WARN("PrivateInstanceAAMP: culling started, first value %f", culledSecs);
2114  }
2115 
2116  this->culledSeconds += culledSecs;
2117  long long limitMs = (long long) std::round(this->culledSeconds * 1000.0);
2118 
2119  for (auto iter = timedMetadata.begin(); iter != timedMetadata.end(); )
2120  {
2121  // If the timed metadata has expired due to playlist refresh, remove it from local cache
2122  // For X-CONTENT-IDENTIFIER, -X-IDENTITY-ADS, X-MESSAGE_REF in DASH which has _timeMS as 0
2123  if (iter->_timeMS != 0 && iter->_timeMS < limitMs)
2124  {
2125  //AAMPLOG_WARN("ERASE(limit:%lld) aamp_ReportTimedMetadata(%lld, '%s', '%s', nb)", limitMs,iter->_timeMS, iter->_name.c_str(), iter->_content.c_str());
2126  //AAMPLOG_WARN("ERASE(limit:%lld) aamp_ReportTimedMetadata(%lld)", limitMs,iter->_timeMS);
2127  iter = timedMetadata.erase(iter);
2128  }
2129  else
2130  {
2131  iter++;
2132  }
2133  }
2134 
2135  // Remove contentGaps vector based on culling.
2136  if(ISCONFIGSET_PRIV(eAAMPConfig_InterruptHandling))
2137  {
2138  for (auto iter = contentGaps.begin(); iter != contentGaps.end();)
2139  {
2140  if (iter->_timeMS != 0 && iter->_timeMS < limitMs)
2141  {
2142  iter = contentGaps.erase(iter);
2143  }
2144  else
2145  {
2146  iter++;
2147  }
2148  }
2149  }
2150 
2151  // Check if we are paused and culled past paused playback position
2152  // AAMP internally caches fragments in sw and gst buffer, so we should be good here
2153  // Pipeline will be in Paused state when Lightning trickplay is done. During this state XRE will send the resume position to exit pause state .
2154  // Issue observed when culled position reaches the paused position during lightning trickplay and player resumes the playback with paused position as playback position ignoring XRE shown position.
2155  // Fix checks if the player is put into paused state with lighting mode(by checking last stored rate).
2156  // In this state player will not come out of Paused state, even if the culled position reaches paused position.
2157  // The rate check is a special case for a specific player, if this is contradicting to other players, we will have to add a config to enable/disable
2158  if (pipeline_paused && mpStreamAbstractionAAMP && (abs(rate) != AAMP_RATE_TRICKPLAY_MAX))
2159  {
2160  double position = GetPositionSeconds();
2161  double minPlaylistPositionToResume = (position < maxRefreshPlaylistIntervalSecs) ? position : (position - maxRefreshPlaylistIntervalSecs);
2162  if (this->culledSeconds >= position)
2163  {
2165  && this->culledSeconds != culledSecs /* Don't auto resume for first culled on PAUSED */)
2166  {
2167  // Immediate play from paused state, Execute player resume.
2168  // Live immediate - Play from live position
2169  // Autoplay immediate - Play from start of live window
2171  {
2172  // Enable this flag to perform seek to live.
2173  mSeekFromPausedState = true;
2174  }
2175  AAMPLOG_WARN("Resume playback since playlist start position(%f) has moved past paused position(%f) ", this->culledSeconds, position);
2176  if (!mAutoResumeTaskPending)
2177  {
2178  mAutoResumeTaskPending = true;
2179  mAutoResumeTaskId = ScheduleAsyncTask(PrivateInstanceAAMP_Resume, (void *)this, "PrivateInstanceAAMP_Resume");
2180  }
2181  else
2182  {
2183  AAMPLOG_WARN("Auto resume playback task already exists, avoid creating duplicates for now!");
2184  }
2185  }
2187  {
2188  // Wait for play() call to resume, enable mSeekFromPausedState for reconfigure.
2189  // Live differ - Play from live position
2190  // Autoplay differ -Play from eldest part (start of live window)
2191  mSeekFromPausedState = true;
2193  {
2194  mJumpToLiveFromPause = true;
2195  }
2196  }
2197  }
2198  else if (this->culledSeconds >= minPlaylistPositionToResume)
2199  {
2200  // Here there is a chance that paused position will be culled after next refresh playlist
2201  // AAMP internally caches fragments in sw bufffer after paused position, so we are at less risk
2202  // Make sure that culledSecs is within the limits of maxRefreshPlaylistIntervalSecs
2203  // This check helps us to avoid initial culling done by FOG after channel tune
2204 
2205  if (culledSecs <= maxRefreshPlaylistIntervalSecs)
2206  {
2208  {
2210  {
2211  mSeekFromPausedState = true;
2212  }
2213  AAMPLOG_WARN("Resume playback since start position(%f) moved very close to minimum resume position(%f) ", this->culledSeconds, minPlaylistPositionToResume);
2214  if (!mAutoResumeTaskPending)
2215  {
2216  mAutoResumeTaskPending = true;
2217  mAutoResumeTaskId = ScheduleAsyncTask(PrivateInstanceAAMP_Resume, (void *)this, "PrivateInstanceAAMP_Resume");
2218  }
2219  else
2220  {
2221  AAMPLOG_WARN("Auto resume playback task already exists, avoid creating duplicates for now!");
2222  }
2223  }
2225  {
2226  mSeekFromPausedState = true;
2228  {
2229  mJumpToLiveFromPause = true;
2230  }
2231  }
2232  }
2233  else
2234  {
2235  AAMPLOG_WARN("Auto resume playback task already exists, avoid creating duplicates for now!");
2236  }
2237  }
2238  }
2239 }
2240 
2241 /**
2242  * @brief Add listener to aamp events
2243  */
2245 {
2246  mEventManager->AddEventListener(eventType,eventListener);
2247 }
2248 
2249 
2250 /**
2251  * @brief Deregister event lister, Remove listener to aamp events
2252  */
2254 {
2255  mEventManager->RemoveEventListener(eventType,eventListener);
2256 }
2257 
2258 /**
2259  * @brief IsEventListenerAvailable Check if Event is registered
2260  */
2262 {
2263  return mEventManager->IsEventListenerAvailable(eventType);
2264 }
2265 
2266 /**
2267  * @brief Handles DRM errors and sends events to application if required.
2268  */
2269 void PrivateInstanceAAMP::SendDrmErrorEvent(DrmMetaDataEventPtr event, bool isRetryEnabled)
2270 {
2271  if (event)
2272  {
2273  AAMPTuneFailure tuneFailure = event->getFailure();
2274  long error_code = event->getResponseCode();
2275  bool isSecClientError = event->getSecclientError();
2276  long secManagerReasonCode = event->getSecManagerReasonCode();
2277 
2278  if(AAMP_TUNE_FAILED_TO_GET_ACCESS_TOKEN == tuneFailure || AAMP_TUNE_LICENCE_REQUEST_FAILED == tuneFailure)
2279  {
2280  char description[128] = {};
2281  //When using secmanager the erro_code would not be less than 100
2282  if(AAMP_TUNE_LICENCE_REQUEST_FAILED == tuneFailure && (error_code < 100 || ISCONFIGSET_PRIV(eAAMPConfig_UseSecManager)))
2283  {
2284 
2285  if (isSecClientError)
2286  {
2287  if(ISCONFIGSET_PRIV(eAAMPConfig_UseSecManager))
2288  {
2289  snprintf(description, MAX_ERROR_DESCRIPTION_LENGTH - 1, "%s : SecManager Error Code %ld:%ld", tuneFailureMap[tuneFailure].description,error_code, secManagerReasonCode);
2290  }
2291  else
2292  {
2293  snprintf(description, MAX_ERROR_DESCRIPTION_LENGTH - 1, "%s : Secclient Error Code %ld", tuneFailureMap[tuneFailure].description, error_code);
2294  }
2295  }
2296  else
2297  {
2298  snprintf(description, MAX_ERROR_DESCRIPTION_LENGTH - 1, "%s : Curl Error Code %ld", tuneFailureMap[tuneFailure].description, error_code);
2299  }
2300  }
2301  else if (AAMP_TUNE_FAILED_TO_GET_ACCESS_TOKEN == tuneFailure && eAUTHTOKEN_TOKEN_PARSE_ERROR == (AuthTokenErrors)error_code)
2302  {
2303  snprintf(description, MAX_ERROR_DESCRIPTION_LENGTH - 1, "%s : Access Token Parse Error", tuneFailureMap[tuneFailure].description);
2304  }
2306  {
2307  snprintf(description, MAX_ERROR_DESCRIPTION_LENGTH - 1, "%s : Invalid status code", tuneFailureMap[tuneFailure].description);
2308  }
2309  else
2310  {
2311  snprintf(description, MAX_ERROR_DESCRIPTION_LENGTH - 1, "%s : Http Error Code %ld", tuneFailureMap[tuneFailure].description, error_code);
2312  }
2313  SendErrorEvent(tuneFailure, description, isRetryEnabled, event->getSecManagerClassCode(),event->getSecManagerReasonCode(), event->getBusinessStatus());
2314  }
2315  else if(tuneFailure >= 0 && tuneFailure < AAMP_TUNE_FAILURE_UNKNOWN)
2316  {
2317  SendErrorEvent(tuneFailure, NULL, isRetryEnabled, event->getSecManagerClassCode(),event->getSecManagerReasonCode(), event->getBusinessStatus());
2318  }
2319  else
2320  {
2321  AAMPLOG_WARN("Received unknown error event %d", tuneFailure);
2323  }
2324  }
2325 }
2326 
2327 /**
2328  * @brief Handles download errors and sends events to application if required.
2329  */
2331 {
2332  AAMPTuneFailure actualFailure = tuneFailure;
2333  bool retryStatus = true;
2334 
2335  if(tuneFailure >= 0 && tuneFailure < AAMP_TUNE_FAILURE_UNKNOWN)
2336  {
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)
2339  {
2340  switch(error_code)
2341  {
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);
2346  break;
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);
2349  break;
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);
2352  break;
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);
2355  break;
2356  }
2357  }
2358  else if(error_code < 100)
2359  {
2360  snprintf(description,MAX_DESCRIPTION_SIZE, "%s : Curl Error Code %ld", tuneFailureMap[tuneFailure].description, error_code); //CID:86441 - DC>STRING_BUFFER
2361  }
2362  else
2363  {
2364  snprintf(description,MAX_DESCRIPTION_SIZE, "%s : Http Error Code %ld", tuneFailureMap[tuneFailure].description, error_code);
2365  if (error_code == 404)
2366  {
2367  actualFailure = AAMP_TUNE_CONTENT_NOT_FOUND;
2368  }
2369  else if (error_code == 421) // http 421 - Fog power saving mode failure
2370  {
2371  retryStatus = false;
2372  }
2373  }
2374  if( IsTSBSupported() )
2375  {
2376  strcat(description, "(FOG)");
2377  }
2378 
2379  SendErrorEvent(actualFailure, description, retryStatus);
2380  }
2381  else
2382  {
2383  AAMPLOG_WARN("Received unknown error event %d", tuneFailure);
2385  }
2386 }
2387 
2388 /**
2389  * @brief Sends Anomaly Error/warning messages
2390  */
2392 {
2394  {
2395  va_list args;
2396  va_start(args, format);
2397 
2398  char msgData[MAX_ANOMALY_BUFF_SIZE];
2399 
2400  msgData[(MAX_ANOMALY_BUFF_SIZE-1)] = 0;
2401  vsnprintf(msgData, (MAX_ANOMALY_BUFF_SIZE-1), format, args);
2402 
2403  AnomalyReportEventPtr e = std::make_shared<AnomalyReportEvent>(type, msgData);
2404 
2405  AAMPLOG_INFO("Anomaly evt:%d msg:%s", e->getSeverity(), msgData);
2407  va_end(args); //CID:82734 - VARAGAS
2408  }
2409 }
2410 
2411 
2412 /**
2413  * @brief Update playlist refresh interval
2414  */
2416 {
2417  AAMPLOG_INFO("maxRefreshPlaylistIntervalSecs (%f)", maxIntervalSecs);
2418  maxRefreshPlaylistIntervalSecs = maxIntervalSecs;
2419 }
2420 
2421 /**
2422  * @brief Sends UnderFlow Event messages
2423  */
2425 {
2426  // Buffer Change event indicate buffer availability
2427  // Buffering stop notification need to be inverted to indicate if buffer available or not
2428  // BufferChangeEvent with False = Underflow / non-availability of buffer to play
2429  // BufferChangeEvent with True = Availability of buffer to play
2430  BufferingChangedEventPtr e = std::make_shared<BufferingChangedEvent>(!bufferingStopped);
2431 
2432  SetBufUnderFlowStatus(bufferingStopped);
2433  AAMPLOG_INFO("PrivateInstanceAAMP: Sending Buffer Change event status (Buffering): %s", (e->buffering() ? "End": "Start"));
2435 }
2436 
2437 /**
2438  * @brief To change the the gstreamer pipeline to pause/play
2439  */
2440 bool PrivateInstanceAAMP::PausePipeline(bool pause, bool forceStopGstreamerPreBuffering)
2441 {
2442  if (true != mStreamSink->Pause(pause, forceStopGstreamerPreBuffering))
2443  {
2444  return false;
2445  }
2446  pipeline_paused = pause;
2447  return true;
2448 }
2449 
2450 /**
2451  * @brief Handles errors and sends events to application if required.
2452  * For download failures, use SendDownloadErrorEvent instead.
2453  */
2454 void PrivateInstanceAAMP::SendErrorEvent(AAMPTuneFailure tuneFailure, const char * description, bool isRetryEnabled, int32_t secManagerClassCode, int32_t secManagerReasonCode, int32_t secClientBusinessStatus)
2455 {
2456  bool sendErrorEvent = false;
2457  pthread_mutex_lock(&mLock);
2458  if(mState != eSTATE_ERROR)
2459  {
2460  if(IsTSBSupported() && mState <= eSTATE_PREPARED)
2461  {
2462  // Send a TSB delete request when player is not tuned successfully.
2463  // If player is once tuned, retune happens with same content and player can reuse same TSB.
2464  std::string remoteUrl = "127.0.0.1:9080/tsb";
2465  long http_error = -1;
2466  ProcessCustomCurlRequest(remoteUrl, NULL, &http_error, eCURL_DELETE);
2467  }
2468  sendErrorEvent = true;
2469  mState = eSTATE_ERROR;
2470  }
2471  pthread_mutex_unlock(&mLock);
2472  if (sendErrorEvent)
2473  {
2474  int code;
2475  const char *errorDescription = NULL;
2476  DisableDownloads();
2477  if(tuneFailure >= 0 && tuneFailure < AAMP_TUNE_FAILURE_UNKNOWN)
2478  {
2479  if (tuneFailure == AAMP_TUNE_PLAYBACK_STALLED)
2480  { // allow config override for stall detection error code
2481  GETCONFIGVALUE_PRIV(eAAMPConfig_StallErrorCode,code);
2482  }
2483  else
2484  {
2485  code = tuneFailureMap[tuneFailure].code;
2486  }
2487  if(description)
2488  {
2489  errorDescription = description;
2490  }
2491  else
2492  {
2493  errorDescription = tuneFailureMap[tuneFailure].description;
2494  }
2495  }
2496  else
2497  {
2498  code = tuneFailureMap[AAMP_TUNE_FAILURE_UNKNOWN].code;
2499  errorDescription = tuneFailureMap[AAMP_TUNE_FAILURE_UNKNOWN].description;
2500  }
2501 
2502  MediaErrorEventPtr e = std::make_shared<MediaErrorEvent>(tuneFailure, code, errorDescription, isRetryEnabled, secManagerClassCode, secManagerReasonCode, secClientBusinessStatus);
2503  SendAnomalyEvent(ANOMALY_ERROR, "Error[%d]:%s", tuneFailure, e->getDescription().c_str());
2504  if (!mAppName.empty())
2505  {
2506  AAMPLOG_ERR("%s PLAYER[%d] APP: %s Sending error %s",(mbPlayEnabled?STRFGPLAYER:STRBGPLAYER), mPlayerId, mAppName.c_str(), e->getDescription().c_str());
2507  }
2508  else
2509  {
2510  AAMPLOG_ERR("%s PLAYER[%d] Sending error %s",(mbPlayEnabled?STRFGPLAYER:STRBGPLAYER), mPlayerId, e->getDescription().c_str());
2511  }
2512 
2513  if (rate != AAMP_NORMAL_PLAY_RATE)
2514  {
2515  NotifySpeedChanged(AAMP_NORMAL_PLAY_RATE, false); // During trick play if the playback failed, send speed change event to XRE to reset its current speed rate.
2516  }
2517 
2519  mFailureReason=tuneFailureMap[tuneFailure].description;
2520  }
2521  else
2522  {
2523  AAMPLOG_WARN("PrivateInstanceAAMP: Ignore error %d[%s]", (int)tuneFailure, description);
2524  }
2525 }
2526 
2527 /**
2528  * @brief Send event to listeners
2529  */
2530 void PrivateInstanceAAMP::SendEvent(AAMPEventPtr eventData, AAMPEventMode eventMode)
2531 {
2532  mEventManager->SendEvent(eventData, eventMode);
2533 }
2534 
2535 /**
2536  * @brief Notify bit rate change event to listeners
2537  */
2538 void PrivateInstanceAAMP::NotifyBitRateChangeEvent(int bitrate, BitrateChangeReason reason, int width, int height, double frameRate, double position, bool GetBWIndex, VideoScanType scantype, int aspectRatioWidth, int aspectRatioHeight)
2539 {
2541  {
2542  AAMPEventPtr event = std::make_shared<BitrateChangeEvent>((int)aamp_GetCurrentTimeMS(), bitrate, BITRATEREASON2STRING(reason), width, height, frameRate, position, mProfileCappedStatus, mDisplayWidth, mDisplayHeight, scantype, aspectRatioWidth, aspectRatioHeight);
2543 
2544  /* START: Added As Part of DELIA-28363 and DELIA-28247 */
2545  if(GetBWIndex)
2546  {
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);
2549  }
2550  else
2551  {
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);
2554  }
2555  /* END: Added As Part of DELIA-28363 and DELIA-28247 */
2556 
2558  }
2559  else
2560  {
2561  /* START: Added As Part of DELIA-28363 and DELIA-28247 */
2562  if(GetBWIndex)
2563  {
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);
2566  }
2567  else
2568  {
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);
2571  }
2572  /* END: Added As Part of DELIA-28363 and DELIA-28247 */
2573  }
2574 
2575  AAMPLOG_WARN("BitrateChanged:%d", reason);
2576 }
2577 
2578 
2579 /**
2580  * @brief Notify speed change event to listeners
2581  */
2582 void PrivateInstanceAAMP::NotifySpeedChanged(float rate, bool changeState)
2583 {
2584  if (changeState)
2585  {
2586  if (rate == 0)
2587  {
2589  if (HasSidecarData())
2590  { // has sidecar data
2593  }
2594  }
2595  else if (rate == AAMP_NORMAL_PLAY_RATE)
2596  {
2597  if (mTrickplayInProgress)
2598  {
2599  mTrickplayInProgress = false;
2600  }
2601  else
2602  {
2603  if (HasSidecarData())
2604  { // has sidecar data
2606  mpStreamAbstractionAAMP->ResumeSubtitleOnPlay(subtitles_muted, mData);
2607  }
2608  }
2610  }
2611  else
2612  {
2613  mTrickplayInProgress = true;
2614  if (HasSidecarData())
2615  { // has sidecar data
2618  }
2619  }
2620  }
2621 
2622 #ifdef AAMP_CC_ENABLED
2623  if (ISCONFIGSET_PRIV(eAAMPConfig_NativeCCRendering))
2624  {
2625  if (rate == AAMP_NORMAL_PLAY_RATE)
2626  {
2628  }
2629  else
2630  {
2632  }
2633  }
2634 #endif
2635  //Hack For DELIA-51318 convert the incoming rates into acceptable rates
2636  if(ISCONFIGSET_PRIV(eAAMPConfig_RepairIframes))
2637  {
2638  AAMPLOG_WARN("mRepairIframes is set, sending pseudo rate %f for the actual rate %f", getPseudoTrickplayRate(rate), rate);
2639  SendEvent(std::make_shared<SpeedChangedEvent>(getPseudoTrickplayRate(rate)),AAMP_EVENT_ASYNC_MODE);
2640  }
2641  else
2642  {
2643  SendEvent(std::make_shared<SpeedChangedEvent>(rate),AAMP_EVENT_ASYNC_MODE);
2644  }
2645 #ifdef USE_SECMANAGER
2646  if(ISCONFIGSET_PRIV(eAAMPConfig_UseSecManager))
2647  {
2648  mDRMSessionManager->setPlaybackSpeedState(rate,seek_pos_seconds);
2649  }
2650 #endif
2651 }
2652 
2653 /**
2654  * @brief Send DRM metadata event
2655  */
2656 void PrivateInstanceAAMP::SendDRMMetaData(DrmMetaDataEventPtr e)
2657 {
2659  AAMPLOG_WARN("SendDRMMetaData name = %s value = %x", e->getAccessStatus().c_str(), e->getAccessStatusValue());
2660 }
2661 
2662 /**
2663  * @brief Check if discontinuity processing is pending
2664  */
2666 {
2667  bool vidDiscontinuity = (mVideoFormat != FORMAT_INVALID && mProcessingDiscontinuity[eMEDIATYPE_VIDEO]);
2668  bool audDiscontinuity = (mAudioFormat != FORMAT_INVALID && mProcessingDiscontinuity[eMEDIATYPE_AUDIO]);
2669  return (vidDiscontinuity || audDiscontinuity);
2670 }
2671 
2672 /**
2673  * @brief Process pending discontinuity and continue playback of stream after discontinuity
2674  *
2675  * @return true if pending discontinuity was processed successful, false if interrupted
2676  */
2678 {
2679  bool ret = true;
2680  SyncBegin();
2681  if (mDiscontinuityTuneOperationInProgress)
2682  {
2683  SyncEnd();
2684  AAMPLOG_WARN("PrivateInstanceAAMP: Discontinuity Tune Operation already in progress");
2686  return ret; // true so that PrivateInstanceAAMP_ProcessDiscontinuity can cleanup properly
2687  }
2688  SyncEnd();
2689 
2691  {
2692  AAMPLOG_ERR("PrivateInstanceAAMP: Discontinuity status of video - (%d), audio - (%d) and aux - (%d)", mProcessingDiscontinuity[eMEDIATYPE_VIDEO], mProcessingDiscontinuity[eMEDIATYPE_AUDIO], mProcessingDiscontinuity[eMEDIATYPE_AUX_AUDIO]);
2694  return ret; // true so that PrivateInstanceAAMP_ProcessDiscontinuity can cleanup properly
2695  }
2696 
2697  SyncBegin();
2698  mDiscontinuityTuneOperationInProgress = true;
2699  SyncEnd();
2700 
2702  {
2703  bool continueDiscontProcessing = true;
2704  AAMPLOG_WARN("PrivateInstanceAAMP: mProcessingDiscontinuity set");
2705  // DELIA-46559, there is a chance that synchronous progress event sent will take some time to return back to AAMP
2706  // This can lead to discontinuity stall detection kicking in. So once we start discontinuity processing, reset the flags
2709  lastUnderFlowTimeMs[eMEDIATYPE_VIDEO] = 0;
2710  lastUnderFlowTimeMs[eMEDIATYPE_AUDIO] = 0;
2711  lastUnderFlowTimeMs[eMEDIATYPE_AUX_AUDIO] = 0;
2712 
2713  {
2714  double newPosition = GetPositionSeconds();
2716  double startTimeofFirstSample = 0;
2717  AAMPLOG_WARN("PrivateInstanceAAMP: last injected position:%f position calcualted: %f", injectedPosition, newPosition);
2718 
2719  // Reset with injected position from StreamAbstractionAAMP. This ensures that any drift in
2720  // GStreamer position reporting is taken care of.
2721  // BCOM-4765: Set seek_pos_seconds to injected position only in case of westerossink. In cases with
2722  // brcmvideodecoder, we have noticed a drift of 500ms for HLS-TS assets (due to PTS restamping
2723  if (injectedPosition != 0 && (fabs(injectedPosition - newPosition) < 5.0) && ISCONFIGSET_PRIV(eAAMPConfig_UseWesterosSink))
2724  {
2725  seek_pos_seconds = injectedPosition;
2726  }
2727  else
2728  {
2729  seek_pos_seconds = newPosition;
2730  }
2731 
2732  if(!IsUninterruptedTSB() && (mMediaFormat == eMEDIAFORMAT_DASH))
2733  {
2734  startTimeofFirstSample = mpStreamAbstractionAAMP->GetStartTimeOfFirstPTS() / 1000;
2735  if(startTimeofFirstSample > 0)
2736  {
2737  AAMPLOG_WARN("PrivateInstanceAAMP: Position is updated to start time of discontinuity : %lf", startTimeofFirstSample);
2738  seek_pos_seconds = startTimeofFirstSample;
2739  }
2740  }
2741  AAMPLOG_WARN("PrivateInstanceAAMP: Updated seek_pos_seconds:%f", seek_pos_seconds);
2742  }
2743  trickStartUTCMS = -1;
2744 
2745  SyncBegin();
2746  mProgressReportFromProcessDiscontinuity = true;
2747  SyncEnd();
2748 
2749  // To notify app of discontinuity processing complete
2750  ReportProgress();
2751 
2752  // There is a chance some other operation maybe invoked from JS/App because of the above ReportProgress
2753  // Make sure we have still mDiscontinuityTuneOperationInProgress set
2754  SyncBegin();
2755  AAMPLOG_WARN("Progress event sent as part of ProcessPendingDiscontinuity, mDiscontinuityTuneOperationInProgress:%d", mDiscontinuityTuneOperationInProgress);
2756  mProgressReportFromProcessDiscontinuity = false;
2757  continueDiscontProcessing = mDiscontinuityTuneOperationInProgress;
2758  SyncEnd();
2759 
2760  if (continueDiscontProcessing)
2761  {
2762  // mStreamLock is not exactly required here, this will be called from Scheduler/GMainLoop based on AAMP config
2763  // The same thread will be executing operations involving TeardownStream.
2765 #ifndef AAMP_STOP_SINK_ON_SEEK
2766  if (mMediaFormat != eMEDIAFORMAT_HLS_MP4) // Avoid calling flush for fmp4 playback.
2767  {
2768  mStreamSink->Flush(mpStreamAbstractionAAMP->GetFirstPTS(), rate);
2769  }
2770 #else
2771  mStreamSink->Stop(true);
2772 #endif
2773  mpStreamAbstractionAAMP->GetStreamFormat(mVideoFormat, mAudioFormat, mAuxFormat, mSubtitleFormat);
2774  mStreamSink->Configure(
2775  mVideoFormat,
2776  mAudioFormat,
2777  mAuxFormat,
2778  mSubtitleFormat,
2781  mIsTrackIdMismatch /*setReadyAfterPipelineCreation*/);
2784  mStreamSink->Stream();
2785  mIsTrackIdMismatch = false;
2786  }
2787  else
2788  {
2789  ret = false;
2790  AAMPLOG_WARN("PrivateInstanceAAMP: mDiscontinuityTuneOperationInProgress was reset during operation, since other command received from app!");
2791  }
2792  }
2793 
2794  if (ret)
2795  {
2796  SyncBegin();
2797  mDiscontinuityTuneOperationInProgress = false;
2798  SyncEnd();
2799  }
2800 
2802  return ret;
2803 }
2804 
2805 /**
2806  * @brief Get the Current Audio Track Id
2807  * Currently it is implimented for AC4 track selection only
2808  * @return int return the index number of current audio track selected
2809  */
2811 {
2812  int trackId = -1;
2813  AudioTrackInfo currentAudioTrack;
2814 
2815  /** Only select track Id for setting gstplayer in case of muxed ac4 stream */
2816  if (mpStreamAbstractionAAMP->GetCurrentAudioTrack(currentAudioTrack) && (currentAudioTrack.codec.find("ac4") == std::string::npos) && currentAudioTrack.isMuxed )
2817  {
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(),
2820  currentAudioTrack.codec.c_str(), currentAudioTrack.contentType.c_str(), currentAudioTrack.bandwidth);
2821  trackId = std::stoi( currentAudioTrack.index );
2822 
2823  }
2824 
2825  return trackId;
2826 }
2827 
2828 /**
2829  * @brief Process EOS from Sink and notify listeners if required
2830  */
2832 {
2833  bool isDiscontinuity = IsDiscontinuityProcessPending();
2834  bool isLive = IsLive();
2835 
2836  AAMPLOG_WARN("Enter . processingDiscontinuity %d isLive %d", isDiscontinuity, isLive);
2837 
2838  if (!isDiscontinuity)
2839  {
2840  /*
2841  A temporary work around intended to reduce occurrences of LLAMA-6113.
2842  This appears to be caused by late calls to previously stopped/destroyed objects due to a scheduling issue.
2843  In this case it makes sense to exit this function ASAP.
2844  A more complete (larger, higher risk, more time consuming, threadsafe) change to scheduling is required in the future.
2845  */
2847  {
2848  AAMPLOG_ERR("null Stream Abstraction AAMP");
2849  return;
2850  }
2851 
2853  {
2854  AAMPLOG_ERR("Bogus EOS event received from GStreamer, discarding it!");
2855  return;
2856  }
2857  if (!isLive && rate > 0)
2858  {
2860  SendEvent(std::make_shared<AAMPEventObject>(AAMP_EVENT_EOS),AAMP_EVENT_ASYNC_MODE);
2861  if (ContentType_EAS == mContentType) //Fix for DELIA-25590
2862  {
2863  mStreamSink->Stop(false);
2864  }
2865  SendAnomalyEvent(ANOMALY_TRACE, "Generating EOS event");
2866  trickStartUTCMS = -1;
2867  return;
2868  }
2869 
2870  if (rate < 0)
2871  {
2872  seek_pos_seconds = culledSeconds;
2873  AAMPLOG_WARN("Updated seek_pos_seconds %f on BOS", seek_pos_seconds);
2874  if (trickStartUTCMS == -1)
2875  {
2876  // Resetting trickStartUTCMS if it's default due to no first frame on high speed rewind. This enables ReportProgress to
2877  // send BOS event to JSPP
2879  AAMPLOG_INFO("Resetting trickStartUTCMS to %lld since no first frame on trick play rate %f", trickStartUTCMS, rate);
2880  }
2881  // A new report progress event to be emitted with position 0 when rewind reaches BOS
2882  ReportProgress(true, true);
2883  rate = AAMP_NORMAL_PLAY_RATE;
2887  }
2888  else
2889  {
2890  rate = AAMP_NORMAL_PLAY_RATE;
2894  }
2895 
2897  }
2898  else
2899  {
2901  pthread_cond_signal(&mCondDiscontinuity);
2902  DeliverAdEvents();
2903  AAMPLOG_WARN("PrivateInstanceAAMP: EOS due to discontinuity handled");
2904  }
2905 }
2906 
2907 /**
2908  * @brief Notify when entering live point to listeners
2909  */
2911 {
2912  if (discardEnteringLiveEvt)
2913  {
2914  return;
2915  }
2916  SendEvent(std::make_shared<AAMPEventObject>(AAMP_EVENT_ENTERING_LIVE),AAMP_EVENT_ASYNC_MODE);
2917 }
2918 
2919 /**
2920  * @brief track description string from TrackType enum
2921  */
2922 static std::string TrackTypeString(const int track)
2923 {
2924  switch(track)
2925  {
2926  case eTRACK_VIDEO:
2927  return "Video";
2928  case eTRACK_AUDIO:
2929  return "Audio";
2930  case eTRACK_SUBTITLE:
2931  return "Subtitle";
2932  case eTRACK_AUX_AUDIO:
2933  return "Aux Audio";
2934  }
2935  return "unknown track type";
2936 }
2937 
2938 /**
2939 * @brief Additional Tune Fail Diagnostics
2940  */
2942 {
2943  mStreamSink->DumpStatus();
2944 
2945  {
2946  std::string downloadsBlockedMessage = "Downloads";
2947  if (!mbDownloadsBlocked)
2948  {
2949  downloadsBlockedMessage += " not";
2950  }
2951  downloadsBlockedMessage += " blocked, track download status: ";
2952  for (int i = 0; i < AAMP_TRACK_COUNT; i++)
2953  {
2954  downloadsBlockedMessage+=TrackTypeString(i);
2955  if (!mbTrackDownloadsBlocked[i])
2956  {
2957  downloadsBlockedMessage += " not";
2958  }
2959  downloadsBlockedMessage += " blocked, ";
2960  }
2961  AAMPLOG_WARN("%s", downloadsBlockedMessage.c_str());
2962  }
2963 
2964  {
2965  std::string injectionBlockedMessage = "Track injection status: ";
2966  for (int i = 0; i < AAMP_TRACK_COUNT; i++)
2967  {
2968  injectionBlockedMessage+=TrackTypeString(i);
2969  if (!mTrackInjectionBlocked[i])
2970  {
2971  injectionBlockedMessage += " not";
2972  }
2973  injectionBlockedMessage += " blocked, ";
2974  }
2975  AAMPLOG_WARN("%s", injectionBlockedMessage.c_str());
2976  }
2977 
2979  {
2980  std::string trackBufferStatusMessage = "Track buffer status: ";
2981  for (int i = 0; i < AAMP_TRACK_COUNT; i++)
2982  {
2983  trackBufferStatusMessage+=TrackTypeString(i);
2984  auto track = mpStreamAbstractionAAMP->GetMediaTrack(static_cast<TrackType>(i));
2985  if(nullptr != track)
2986  {
2987  const auto status = track->GetBufferStatus();
2988  trackBufferStatusMessage += " ";
2989  switch (status)
2990  {
2991  case BUFFER_STATUS_GREEN:
2992  trackBufferStatusMessage += "green";
2993  break;
2994  case BUFFER_STATUS_YELLOW:
2995  trackBufferStatusMessage += "yellow";
2996  break;
2997  case BUFFER_STATUS_RED:
2998  trackBufferStatusMessage += "red";
2999  break;
3000  default:
3001  trackBufferStatusMessage += "unknown";
3002  break;
3003  }
3004  }
3005  else
3006  {
3007  trackBufferStatusMessage += "invalid track";
3008  }
3009  trackBufferStatusMessage += ", ";
3010  }
3011  AAMPLOG_WARN( "%s", trackBufferStatusMessage.c_str());
3012  }
3013 }
3014 
3015 /**
3016  * @brief Profiler for failure tune
3017  */
3019 {
3020  PrivAAMPState state;
3021  GetState(state);
3022  TuneEndMetrics mTuneMetrics = {0, 0, 0,0,0,0,0,0,0,(ContentType)0};
3023  mTuneMetrics.mTotalTime = NOW_STEADY_TS_MS ;
3024  mTuneMetrics.success = ((state != eSTATE_ERROR) ? -1 : !fail);
3025  int streamType = getStreamType();
3026  mTuneMetrics.mFirstTune = mFirstTune;
3027  mTuneMetrics.mTimedMetadata = timedMetadata.size();
3029  mTuneMetrics.mTimedMetadataDuration = mTimedMetadataDuration;
3030  mTuneMetrics.mTuneAttempts = mTuneAttempts;
3031  mTuneMetrics.contentType = mContentType;
3032  mTuneMetrics.streamType = streamType;
3033  mTuneMetrics.mTSBEnabled = mTSBEnabled;
3034  if(mTuneMetrics.success == -1 && mPlayerPreBuffered)
3035  {
3036  LogPlayerPreBuffered(); //Need to calculate prebufferedtime when tune interruption happens with playerprebuffer
3037  }
3038  profiler.TuneEnd(mTuneMetrics, mAppName,(mbPlayEnabled?STRFGPLAYER:STRBGPLAYER), mPlayerId, mPlayerPreBuffered, durationSeconds, activeInterfaceWifi,mFailureReason);
3040 }
3041 
3042 /**
3043  * @brief Notify tune end for profiling/logging
3044  */
3046 {
3047  TuneEndMetrics mTuneMetrics = {0, 0, 0,0,0,0,0,0,0,(ContentType)0};
3048 
3049  mTuneMetrics.success = true;
3050  int streamType = getStreamType();
3051  mTuneMetrics.contentType = mContentType;
3052  mTuneMetrics.mTimedMetadata = timedMetadata.size();
3054  mTuneMetrics.mTimedMetadataDuration = mTimedMetadataDuration;
3055  mTuneMetrics.mTuneAttempts = mTuneAttempts;
3056  mTuneMetrics.streamType = streamType;
3057  mTuneMetrics.mTSBEnabled = mTSBEnabled;
3058  profiler.TuneEnd(mTuneMetrics,mAppName,(mbPlayEnabled?STRFGPLAYER:STRBGPLAYER), mPlayerId, mPlayerPreBuffered, durationSeconds, activeInterfaceWifi,mFailureReason);
3059  //update tunedManifestUrl if FOG was NOT used as manifestUrl might be updated with redirected url.
3060  if(!IsTSBSupported())
3061  {
3062  SetTunedManifestUrl(); /* Redirect URL in case on VOD */
3063  }
3064 
3065  if (!mTuneCompleted)
3066  {
3067  if(mLogTune)
3068  {
3069  char classicTuneStr[AAMP_MAX_PIPE_DATA_SIZE];
3070  mLogTune = false;
3071  if (ISCONFIGSET_PRIV(eAAMPConfig_XRESupportedTune)) {
3072  profiler.GetClassicTuneTimeInfo(mTuneMetrics.success, mTuneAttempts, mfirstTuneFmt, mPlayerLoadTime, streamType, IsLive(), durationSeconds, classicTuneStr);
3074  }
3075  mTuneCompleted = true;
3076  mFirstTune = false;
3077  }
3079  if(mTuneAttempts > 1 )
3080  {
3082  }
3083  std::string playbackType = GetContentTypString();
3084 
3085  if(mContentType == ContentType_LINEAR)
3086  {
3087  if(mTSBEnabled)
3088  {
3089  playbackType.append(":TSB=true");
3090  }
3091  else
3092  {
3093  playbackType.append(":TSB=false");
3094  }
3095  }
3096 
3097  SendAnomalyEvent(eMsgType, "Tune attempt#%d. %s:%s URL:%s", mTuneAttempts,playbackType.c_str(),getStreamTypeString().c_str(),GetTunedManifestUrl());
3098  }
3099 
3102 }
3103 
3104 /**
3105  * @brief Notifies profiler that first frame is presented
3106  */
3108 {
3110 }
3111 
3112 /**
3113  * @brief Profile Player changed from background to foreground i.e prebuffred
3114  */
3116 {
3118 }
3119 
3120 /**
3121  * @brief Notifies profiler that drm initialization is complete
3122  */
3124 {
3126 }
3127 
3128 /**
3129  * @brief Notifies profiler that decryption has started
3130  */
3132 {
3133  profiler.ProfileBegin(bucketType);
3134 }
3135 
3136 /**
3137  * @brief Notifies profiler that decryption has ended
3138  */
3140 {
3141  profiler.ProfileEnd(bucketType);
3142 }
3143 
3144 /**
3145  * @brief Stop downloads of all tracks.
3146  * Used by aamp internally to manage states
3147  */
3149 {
3150  AAMPLOG_TRACE ("PrivateInstanceAAMP");
3151  if (!mbDownloadsBlocked)
3152  {
3153  pthread_mutex_lock(&mLock);
3154  mbDownloadsBlocked = true;
3155  pthread_mutex_unlock(&mLock);
3156  }
3157 }
3158 
3159 /**
3160  * @brief Resume downloads of all tracks.
3161  * Used by aamp internally to manage states
3162  */
3164 {
3165  AAMPLOG_TRACE ("PrivateInstanceAAMP");
3166  if (mbDownloadsBlocked)
3167  {
3168  pthread_mutex_lock(&mLock);
3169  mbDownloadsBlocked = false;
3170  //log_current_time("gstreamer-needs-data");
3171  pthread_mutex_unlock(&mLock);
3172  }
3173 }
3174 
3175 /**
3176  * @brief Stop downloads for a track.
3177  * Called from StreamSink to control flow
3178  */
3180 { // called from gstreamer main event loop
3181 #ifdef AAMP_DEBUG_FETCH_INJECT
3182  if ((1 << type) & AAMP_DEBUG_FETCH_INJECT)
3183  {
3184  AAMPLOG_WARN ("PrivateInstanceAAMP: Enter. type = %d", (int) type);
3185  }
3186 #endif
3187  if (!mbTrackDownloadsBlocked[type])
3188  {
3189  AAMPLOG_TRACE("gstreamer-enough-data from source[%d]", type);
3190  pthread_mutex_lock(&mLock);
3191  mbTrackDownloadsBlocked[type] = true;
3192  pthread_mutex_unlock(&mLock);
3193  NotifySinkBufferFull(type);
3194  }
3195  AAMPLOG_TRACE ("PrivateInstanceAAMP:: Enter. type = %d", (int) type);
3196 }
3197 
3198 /**
3199  * @brief Resume downloads for a track.
3200  * Called from StreamSink to control flow
3201  */
3203 { // called from gstreamer main event loop
3204 #ifdef AAMP_DEBUG_FETCH_INJECT
3205  if ((1 << type) & AAMP_DEBUG_FETCH_INJECT)
3206  {
3207  AAMPLOG_WARN ("PrivateInstanceAAMP: Enter. type = %d", (int) type);
3208  }
3209 #endif
3210  if (mbTrackDownloadsBlocked[type])
3211  {
3212  AAMPLOG_TRACE("gstreamer-needs-data from source[%d]", type);
3213  pthread_mutex_lock(&mLock);
3214  mbTrackDownloadsBlocked[type] = false;
3215  //log_current_time("gstreamer-needs-data");
3216  pthread_mutex_unlock(&mLock);
3217  }
3218  AAMPLOG_TRACE ("PrivateInstanceAAMP::Exit. type = %d", (int) type);
3219 }
3220 
3221 /**
3222  * @brief Block the injector thread until the gstreanmer needs buffer/more data.
3223  */
3224 void PrivateInstanceAAMP::BlockUntilGstreamerWantsData(void(*cb)(void), int periodMs, int track)
3225 { // called from FragmentCollector thread; blocks until gstreamer wants data
3226  AAMPLOG_TRACE("PrivateInstanceAAMP::Enter. type = %d and downloads:%d", track, mbTrackDownloadsBlocked[track]);
3227  int elapsedMs = 0;
3228  while (mbDownloadsBlocked || mbTrackDownloadsBlocked[track])
3229  {
3230  if (!mDownloadsEnabled || mTrackInjectionBlocked[track])
3231  {
3232  AAMPLOG_WARN("PrivateInstanceAAMP: interrupted. mDownloadsEnabled:%d mTrackInjectionBlocked:%d", mDownloadsEnabled, mTrackInjectionBlocked[track]);
3233  break;
3234  }
3235  if (cb && periodMs)
3236  { // support for background tasks, i.e. refreshing manifest while gstreamer doesn't need additional data
3237  if (elapsedMs >= periodMs)
3238  {
3239  cb();
3240  elapsedMs -= periodMs;
3241  }
3242  elapsedMs += 10;
3243  }
3245  }
3246  AAMPLOG_TRACE("PrivateInstanceAAMP::Exit. type = %d", track);
3247 }
3248 
3249 /**
3250  * @brief Curl initialization function
3251  */
3252 void PrivateInstanceAAMP::CurlInit(AampCurlInstance startIdx, unsigned int instanceCount, std::string proxyName)
3253 {
3254  int instanceEnd = startIdx + instanceCount;
3255  std::string UserAgentString;
3256  UserAgentString=mConfig->GetUserAgentString();
3257  assert (instanceEnd <= eCURLINSTANCE_MAX);
3258 
3259  CurlStore::GetCurlStoreInstance(this)->CurlInit(this, startIdx, instanceCount, proxyName);
3260 }
3261 
3262 /**
3263  * @brief Storing audio language list
3264  */
3265 void PrivateInstanceAAMP::StoreLanguageList(const std::set<std::string> &langlist)
3266 {
3267  // store the language list
3268  int langCount = langlist.size();
3269  if (langCount > MAX_LANGUAGE_COUNT)
3270  {
3271  langCount = MAX_LANGUAGE_COUNT; //boundary check
3272  }
3273  mMaxLanguageCount = langCount;
3274  std::set<std::string>::const_iterator iter = langlist.begin();
3275  for (int cnt = 0; cnt < langCount; cnt++, iter++)
3276  {
3277  strncpy(mLanguageList[cnt], iter->c_str(), MAX_LANGUAGE_TAG_LENGTH);
3278  mLanguageList[cnt][MAX_LANGUAGE_TAG_LENGTH-1] = 0;
3279  if( this->mVideoEnd )
3280  {
3281  mVideoEnd->Setlanguage(VideoStatTrackType::STAT_AUDIO, (*iter), cnt+1);
3282  }
3283  }
3284 }
3285 
3286 /**
3287  * @brief Checking whether audio language supported
3288  */
3289 bool PrivateInstanceAAMP::IsAudioLanguageSupported (const char *checkLanguage)
3290 {
3291  bool retVal =false;
3292  for (int cnt=0; cnt < mMaxLanguageCount; cnt ++)
3293  {
3294  if(strncmp(mLanguageList[cnt], checkLanguage, MAX_LANGUAGE_TAG_LENGTH) == 0)
3295  {
3296  retVal = true;
3297  break;
3298  }
3299  }
3300 
3301  if(mMaxLanguageCount == 0)
3302  {
3303  AAMPLOG_WARN("IsAudioLanguageSupported No Audio language stored !!!");
3304  }
3305  else if(!retVal)
3306  {
3307  AAMPLOG_WARN("IsAudioLanguageSupported lang[%s] not available in list",checkLanguage);
3308  }
3309  return retVal;
3310 }
3311 
3312 /**
3313  * @brief Set curl timeout(CURLOPT_TIMEOUT)
3314  */
3316 {
3317  if(ContentType_EAS == mContentType)
3318  return;
3319  if(instance < eCURLINSTANCE_MAX && curl[instance])
3320  {
3321  CURL_EASY_SETOPT(curl[instance], CURLOPT_TIMEOUT_MS, timeoutMS);
3322  curlDLTimeout[instance] = timeoutMS;
3323  }
3324  else
3325  {
3326  AAMPLOG_WARN("Failed to update timeout for curl instace %d",instance);
3327  }
3328 }
3329 
3330 /**
3331  * @brief Terminate curl contexts
3332  */
3333 void PrivateInstanceAAMP::CurlTerm(AampCurlInstance startIdx, unsigned int instanceCount)
3334 {
3335  int instanceEnd = startIdx + instanceCount;
3336  assert (instanceEnd <= eCURLINSTANCE_MAX);
3337 
3338  if (ISCONFIGSET_PRIV(eAAMPConfig_EnableCurlStore) && \
3339  ( startIdx == eCURLINSTANCE_VIDEO ) && (eCURLINSTANCE_AUX_AUDIO < instanceEnd) )
3340  {
3341  for(int i=0; i<eCURLINSTANCE_MAX;++i)
3342  {
3343  if(curlhost[i]->curl)
3344  {
3345  CurlStore::GetCurlStoreInstance(this)->CurlTerm(this, (AampCurlInstance)i, 1, curlhost[i]->hostname);
3346  }
3347  curlhost[i]->isRemotehost=true;
3348  curlhost[i]->redirect=true;
3349  }
3350  }
3351 
3352  CurlStore::GetCurlStoreInstance(this)->CurlTerm(this, startIdx, instanceCount);
3353 }
3354 
3355 /**
3356  * @brief GetPlaylistCurlInstance - Function to return the curl instance for playlist download
3357  * Considers parallel download to decide the curl instance
3358  * @return AampCurlInstance - curl instance for download
3359  */
3361 {
3363  bool indivCurlInstanceFlag = false;
3364 
3365  //DELIA-41646
3366  // logic behind this function :
3367  // a. This function gets called during Init and during Refresh of playlist .So need to decide who called
3368  // b. Based on the decision flag is considerd . mParallelFetchPlaylist for Init and mParallelFetchPlaylistRefresh
3369  // for refresh
3370  // c. If respective configuration is enabled , then associate separate curl for each track type
3371  // d. If parallel fetch is disabled , then single curl instance is used to fetch all playlist(eCURLINSTANCE_MANIFEST_PLAYLIST)
3372 
3373  indivCurlInstanceFlag = isInitialDownload ? ISCONFIGSET_PRIV(eAAMPConfig_PlaylistParallelFetch) : ISCONFIGSET_PRIV(eAAMPConfig_PlaylistParallelRefresh);
3374  if(indivCurlInstanceFlag)
3375  {
3376  switch(type)
3377  {
3379  retType = eCURLINSTANCE_VIDEO;
3380  break;
3382  retType = eCURLINSTANCE_AUDIO;
3383  break;
3385  retType = eCURLINSTANCE_SUBTITLE;
3386  break;
3388  retType = eCURLINSTANCE_AUX_AUDIO;
3389  break;
3390  default:
3391  break;
3392  }
3393  }
3394  return retType;
3395 }
3396 
3397 /**
3398  * @brief Reset bandwidth value
3399  * Artificially resetting the bandwidth. Low for quicker tune times
3400  */
3401 void PrivateInstanceAAMP::ResetCurrentlyAvailableBandwidth(long bitsPerSecond , bool trickPlay,int profile)
3402 {
3403  pthread_mutex_lock(&mLock);
3404  if (mAbrBitrateData.size())
3405  {
3406  mAbrBitrateData.erase(mAbrBitrateData.begin(),mAbrBitrateData.end());
3407  }
3408  pthread_mutex_unlock(&mLock);
3409 }
3410 
3411 /**
3412  * @brief Get the current network bandwidth
3413  * using most recently recorded 3 samples
3414  * @return Available bandwidth in bps
3415  */
3417 {
3418  // 1. Check for any old bitrate beyond threshold time . remove those before calculation
3419  // 2. Sort and get median
3420  // 3. if any outliers , remove those entries based on a threshold value.
3421  // 4. Get the average of remaining data.
3422  // 5. if no item in the list , return -1 . Caller to ignore bandwidth based processing
3423 
3424  std::vector< long> tmpData;
3425  long ret = -1;
3426  pthread_mutex_lock(&mLock);
3427  mhAbrManager.UpdateABRBitrateDataBasedOnCacheLife(mAbrBitrateData,tmpData);
3428  pthread_mutex_unlock(&mLock);
3429 
3430  if (tmpData.size())
3431  {
3432  //AAMPLOG_WARN("NwBW with newlogic size[%d] avg[%ld] ",tmpData.size(), avg/tmpData.size());
3433  ret =mhAbrManager.UpdateABRBitrateDataBasedOnCacheOutlier(tmpData);
3434  mAvailableBandwidth = ret;
3435  //Store the PersistBandwidth and UpdatedTime on ABRManager
3436  //Bitrate Update only for foreground player
3437  if(ISCONFIGSET_PRIV(eAAMPConfig_PersistLowNetworkBandwidth)||ISCONFIGSET_PRIV(eAAMPConfig_PersistHighNetworkBandwidth))
3438  {
3439  if(mAvailableBandwidth > 0 && mbPlayEnabled)
3440  {
3441  ABRManager::setPersistBandwidth(mAvailableBandwidth );
3442  ABRManager::mPersistBandwidthUpdatedTime = aamp_GetCurrentTimeMS();
3443  }
3444  }
3445  }
3446  else
3447  {
3448  //AAMPLOG_WARN("No prior data available for abr , return -1 ");
3449  ret = -1;
3450  }
3451 
3452  return ret;
3453 }
3454 
3455 /**
3456  * @brief get Media Type in string
3457  */
3459 {
3460  switch(fileType)
3461  {
3462  case eMEDIATYPE_VIDEO:
3463  case eMEDIATYPE_INIT_VIDEO:
3464  return "VIDEO";
3465  case eMEDIATYPE_AUDIO:
3466  case eMEDIATYPE_INIT_AUDIO:
3467  return "AUDIO";
3468  case eMEDIATYPE_SUBTITLE:
3470  return "SUBTITLE";
3471  case eMEDIATYPE_AUX_AUDIO:
3473  return "AUX-AUDIO";
3474  case eMEDIATYPE_MANIFEST:
3475  return "MANIFEST";
3476  case eMEDIATYPE_LICENCE:
3477  return "LICENCE";
3478  case eMEDIATYPE_IFRAME:
3479  return "IFRAME";
3481  return "PLAYLIST_VIDEO";
3483  return "PLAYLIST_AUDIO";
3485  return "PLAYLIST_SUBTITLE";
3487  return "PLAYLIST_AUX-AUDIO";
3488  default:
3489  return "Unknown";
3490  }
3491 }
3492 
3493 /**
3494  * @brief Download a file from the server
3495  */
3496 bool PrivateInstanceAAMP::GetNetworkTime(enum UtcTiming timingType, const std::string& remoteUrl, long *http_error, CurlRequest request)
3497 {
3498  bool ret = false;
3499 
3500  CURLcode res;
3501  long httpCode = -1;
3502 
3503  if(eCURL_GET != request)
3504  return ret;
3505 
3506  CURL *curl = curl_easy_init();
3507  if(curl)
3508  {
3509  AAMPLOG_TRACE("%s, %d", remoteUrl.c_str(), request);
3510  GrowableBuffer buffer = {0,};
3511 
3512  CurlCbContextSyncTime context(this, &buffer);
3513 
3514  curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
3515  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, SyncTime_write_callback);
3516  curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L);
3517  curl_easy_setopt(curl, CURLOPT_WRITEDATA, &context);
3518  curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
3519 
3520  curl_easy_setopt(curl, CURLOPT_TIMEOUT, DEFAULT_CURL_TIMEOUT);
3521  curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER);
3522  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
3523  if(!ISCONFIGSET_PRIV(eAAMPConfig_SslVerifyPeer)){
3524  curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
3525  }
3526  else {
3527  curl_easy_setopt(curl, CURLOPT_SSLVERSION, mSupportedTLSVersion);
3528  curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
3529  }
3530 
3531  curl_easy_setopt(curl, CURLOPT_URL, remoteUrl.c_str());
3532 
3533  res = curl_easy_perform(curl);
3534  if (res == CURLE_OK)
3535  {
3536  curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
3537  if ((httpCode == 204) || (httpCode == 200))
3538  {
3539  if(buffer.len)
3540  {
3541  time_t currentTime;
3542  currentTime = time(0);
3543  struct tm *localTime;
3544  localTime = localtime(&currentTime);
3545  struct tm *stGMT;
3546  stGMT = gmtime(&currentTime);
3547  time_t currentTimeGMT;
3548  currentTimeGMT = mktime(stGMT);
3549 
3550  //2021-06-15T18:11:39Z - UTC Zulu
3551  //2021-06-15T19:03:48.795Z - <ProducerReferenceTime> WallClk UTC Zulu
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);
3555 
3556  aamp_Free(&buffer);
3557 
3558  ret = true;
3559  }
3560  }
3561  else
3562  {
3563  AAMPLOG_ERR(" Returned [%d]", httpCode);
3564  }
3565  }
3566  else
3567  {
3568  AAMPLOG_ERR("Failed to perform curl request, result:%d", res);
3569  }
3570 
3571  if(httpCode > 0)
3572  {
3573  *http_error = httpCode;
3574  }
3575 
3576  curl_easy_cleanup(curl);
3577  }
3578 
3579  return ret;
3580 }
3581 
3582 /**
3583  * @brief Download a file from the CDN
3584  */
3585 bool PrivateInstanceAAMP::GetFile(std::string remoteUrl,struct GrowableBuffer *buffer, std::string& effectiveUrl,
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)
3589 {
3590  MediaType simType = fileType; // remember the requested specific file type; fileType gets overridden later with simple VIDEO/AUDIO
3591  MediaTypeTelemetry mediaType = aamp_GetMediaTypeForTelemetry(fileType);
3592  std::unordered_map<std::string, std::vector<std::string>> mCMCDCustomHeaders;
3593  if((pCMCDMetrics!=NULL) && ISCONFIGSET_PRIV(eAAMPConfig_EnableCMCD))
3594  {
3595  CollectCMCDCustomHeaders(fileType,pCMCDMetrics);
3596  pCMCDMetrics->BuildCMCDCustomHeaders(mCMCDCustomHeaders);
3597 
3598  }
3599  long http_code = -1;
3600  double fileDownloadTime = 0;
3601  bool ret = false;
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);/*convert to MS */
3608  if (simType == eMEDIATYPE_INIT_VIDEO || simType == eMEDIATYPE_INIT_AUDIO || simType == eMEDIATYPE_INIT_AUX_AUDIO)
3609  {
3610  int InitFragmentRetryCount;
3611  GETCONFIGVALUE_PRIV(eAAMPConfig_InitFragmentRetryCount,InitFragmentRetryCount);
3612  maxDownloadAttempt += InitFragmentRetryCount;
3613  }
3614  else
3615  {
3616  maxDownloadAttempt += DEFAULT_DOWNLOAD_RETRY_COUNT;
3617  }
3618 
3619  if (resetBuffer)
3620  {
3621  if(buffer->avail)
3622  {
3623  AAMPLOG_TRACE("reset buffer %p avail %d", buffer, (int)buffer->avail);
3624  }
3625  memset(buffer, 0x00, sizeof(*buffer));
3626  }
3627  if (mDownloadsEnabled)
3628  {
3629  int downloadTimeMS = 0;
3630  bool isDownloadStalled = false;
3631  CurlAbortReason abortReason = eCURL_ABORT_REASON_NONE;
3632  double connectTime = 0;
3633  pthread_mutex_unlock(&mLock);
3634  std::string uriParameter;
3635  GETCONFIGVALUE_PRIV(eAAMPConfig_URIParameter,uriParameter);
3636  // append custom uri parameter with remoteUrl at the end before curl request if curlHeader logging enabled.
3637  if (ISCONFIGSET_PRIV(eAAMPConfig_CurlHeader) && (!uriParameter.empty()) && simType == eMEDIATYPE_MANIFEST)
3638  {
3639  if (remoteUrl.find("?") == std::string::npos)
3640  {
3641  uriParameter[0] = '?';
3642  }
3643 
3644  remoteUrl.append(uriParameter.c_str());
3645  //printf ("URL after appending uriParameter :: %s\n", remoteUrl.c_str());
3646  }
3647 
3648  if(ISCONFIGSET_PRIV(eAAMPConfig_EnableCurlStore) && mOrigManifestUrl.isRemotehost )
3649  {
3650  if( curlhost[curlInstance]->isRemotehost && curlhost[curlInstance]->redirect &&
3651  ( NULL == curlhost[curlInstance]->curl || std::string::npos == remoteUrl.find(curlhost[curlInstance]->hostname)) )
3652  {
3653  if(NULL != curlhost[curlInstance]->curl)
3654  {
3655  CurlStore::GetCurlStoreInstance(this)->CurlTerm(this, (AampCurlInstance)curlInstance, 1, curlhost[curlInstance]->hostname);
3656  }
3657 
3658  curlhost[curlInstance]->hostname = aamp_getHostFromURL(remoteUrl);
3659  curlhost[curlInstance]->isRemotehost =!(aamp_IsLocalHost(curlhost[curlInstance]->hostname));
3660  curlhost[curlInstance]->redirect = false;
3661 
3662  if( curlhost[curlInstance]->isRemotehost && (std::string::npos == mOrigManifestUrl.hostname.find(curlhost[curlInstance]->hostname)) )
3663  {
3664  CurlStore::GetCurlStoreInstance(this)->CurlInit(this, (AampCurlInstance)curlInstance, 1, GetNetworkProxy(), curlhost[curlInstance]->hostname);
3665  CURL_EASY_SETOPT(curlhost[curlInstance]->curl, CURLOPT_TIMEOUT_MS, curlDLTimeout[curlInstance]);
3666  }
3667  }
3668 
3669  if ( curlhost[curlInstance]->curl )
3670  curl=curlhost[curlInstance]->curl;
3671  }
3672 
3673  AAMPLOG_INFO("aamp url:%d,%d,%d,%f,%s", mediaType, simType, curlInstance,fragmentDurationSeconds, remoteUrl.c_str());
3674  CurlCallbackContext context;
3675  if (curl)
3676  {
3677  CURL_EASY_SETOPT(curl, CURLOPT_URL, remoteUrl.c_str());
3679  {
3680  CURL_EASY_SETOPT(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
3681  context.remoteUrl = remoteUrl;
3682  }
3683  context.aamp = this;
3684  context.buffer = buffer;
3685  context.responseHeaderData = &httpRespHeaders[curlInstance];
3686  context.fileType = simType;
3687 
3689  {
3690  CURL_EASY_SETOPT(curl, CURLOPT_WRITEDATA, &context);
3691  CURL_EASY_SETOPT(curl, CURLOPT_HEADERDATA, &context);
3692  }
3693  if(!ISCONFIGSET_PRIV(eAAMPConfig_SslVerifyPeer))
3694  {
3695  CURL_EASY_SETOPT(curl, CURLOPT_SSL_VERIFYHOST, 0L);
3696  CURL_EASY_SETOPT(curl, CURLOPT_SSL_VERIFYPEER, 0L);
3697  }
3698  else
3699  {
3700  CURL_EASY_SETOPT(curl, CURLOPT_SSLVERSION, mSupportedTLSVersion);
3701  CURL_EASY_SETOPT(curl, CURLOPT_SSL_VERIFYPEER, 1L);
3702  }
3703 
3704  CurlProgressCbContext progressCtx;
3705  progressCtx.aamp = this;
3706  progressCtx.fileType = simType;
3707  progressCtx.dlStarted = true;
3708  progressCtx.fragmentDurationMs = fragmentDurationMs;
3709 
3711  (simType == eMEDIATYPE_VIDEO))
3712  {
3713  progressCtx.remoteUrl = remoteUrl;
3714  }
3715 
3716  //Disable download stall detection checks for FOG playback done by JS PP
3717  if(simType == eMEDIATYPE_MANIFEST || simType == eMEDIATYPE_PLAYLIST_VIDEO ||
3718  simType == eMEDIATYPE_PLAYLIST_AUDIO || simType == eMEDIATYPE_PLAYLIST_SUBTITLE ||
3720  {
3721  // For Manifest file : Set starttimeout to 0 ( no wait for first byte). Playlist/Manifest with DAI
3722  // contents take more time , hence to avoid frequent timeout, its set as 0
3723  progressCtx.startTimeout = 0;
3724  }
3725  else
3726  {
3727  // for Video/Audio segments , set the start timeout as configured by Application
3728  GETCONFIGVALUE_PRIV(eAAMPConfig_CurlDownloadStartTimeout,progressCtx.startTimeout);
3729  GETCONFIGVALUE_PRIV(eAAMPConfig_CurlDownloadLowBWTimeout,progressCtx.lowBWTimeout);
3730  }
3731  GETCONFIGVALUE_PRIV(eAAMPConfig_CurlStallTimeout,progressCtx.stallTimeout);
3732 
3733  // note: win32 curl lib doesn't support multi-part range
3734  CURL_EASY_SETOPT(curl, CURLOPT_RANGE, range);
3735 
3736  if ((httpRespHeaders[curlInstance].type == eHTTPHEADERTYPE_COOKIE) && (httpRespHeaders[curlInstance].data.length() > 0))
3737  {
3738  AAMPLOG_TRACE("Appending cookie headers to HTTP request");
3739  //curl_easy_setopt(curl, CURLOPT_COOKIE, cookieHeaders[curlInstance].c_str());
3740  CURL_EASY_SETOPT(curl, CURLOPT_COOKIE, httpRespHeaders[curlInstance].data.c_str());
3741  }
3742  if ( ISCONFIGSET_PRIV(eAAMPConfig_EnableCMCD) && mCMCDCustomHeaders.size() > 0)
3743  {
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++)
3747  {
3748  customHeader.clear();
3749  headerValue.clear();
3750  customHeader.insert(0, it->first);
3751  customHeader.push_back(' ');
3752  if (it->first.compare("CMCD-Session:") == 0)
3753  {
3754  headerValue = it->second.at(0);
3755  }
3756  if (it->first.compare("CMCD-Object:") == 0)
3757  {
3758  headerValue = it->second.at(0);
3759  }
3760  if (it->first.compare("CMCD-Request:") == 0)
3761  {
3762  headerValue = it->second.at(0);
3763  }
3764  if (it->first.compare("CMCD-Status:") == 0)
3765  {
3766  headerValue = it->second.at(0);
3767  }
3768  customHeader.append(headerValue);
3769  httpHeaders = curl_slist_append(httpHeaders, customHeader.c_str());
3770  }
3771 
3772  }
3773  if (mCustomHeaders.size() > 0)
3774  {
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++)
3779  {
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)
3786  {
3787  if (mTSBEnabled && !mIsFirstRequestToFOG)
3788  {
3789  continue;
3790  }
3791  char buf[512];
3792  memset(buf, '\0', 512);
3793  if (it->second.size() >= 2)
3794  {
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(),
3799  }
3800  else if (it->second.size() == 1)
3801  {
3802  snprintf(buf, 512, "trace-id=%s;parent-id=%lld;span-id=%lld",
3803  (const char*)it->second.at(0).c_str(),
3806  }
3807  headerValue = buf;
3808  }
3809  if (it->first.compare("Wifi:") == 0)
3810  {
3811  if (true == activeInterfaceWifi)
3812  {
3813  headerValue = "1";
3814  }
3815  else
3816  {
3817  headerValue = "0";
3818  }
3819  }
3820  customHeader.append(headerValue);
3821  httpHeaders = curl_slist_append(httpHeaders, customHeader.c_str());
3822  }
3823  if (ISCONFIGSET_PRIV(eAAMPConfig_LimitResolution) && mIsFirstRequestToFOG && mTSBEnabled && eMEDIATYPE_MANIFEST == simType)
3824  {
3825  std::string customHeader;
3826  customHeader.clear();
3827  customHeader = "width: " + std::to_string(mDisplayWidth);
3828  httpHeaders = curl_slist_append(httpHeaders, customHeader.c_str());
3829  customHeader.clear();
3830  customHeader = "height: " + std::to_string(mDisplayHeight);
3831  httpHeaders = curl_slist_append(httpHeaders, customHeader.c_str());
3832  }
3833 
3834  if(mTSBEnabled && eMEDIATYPE_VIDEO == simType)
3835  {
3836  double bufferedDuration = mpStreamAbstractionAAMP->GetBufferedVideoDurationSec() * 1000.0;
3837  std::string customHeader;
3838  customHeader.clear();
3839  customHeader = "Buffer: " +std::to_string(bufferedDuration);
3840  httpHeaders = curl_slist_append(httpHeaders, customHeader.c_str());
3841  }
3842  if(mTSBEnabled && eMEDIATYPE_AUDIO == simType)
3843  {
3844  double bufferedAudioDuration = mpStreamAbstractionAAMP->GetBufferedDuration() * 1000.0;
3845  std::string customHeader;
3846  customHeader.clear();
3847  customHeader = "AudioBuffer: " +std::to_string(bufferedAudioDuration);
3848  httpHeaders = curl_slist_append(httpHeaders, customHeader.c_str());
3849  }
3850  if(mTSBEnabled && (eMEDIATYPE_VIDEO == simType || eMEDIATYPE_AUDIO == simType))
3851  {
3853  if((mediaTrack) && (mediaTrack->GetBufferStatus() == BUFFER_STATUS_RED))
3854  {
3855  std::string customHeader;
3856  customHeader.clear();
3857  customHeader = "BufferStarvation:";
3858  httpHeaders = curl_slist_append(httpHeaders, customHeader.c_str());
3859  }
3860  }
3861 
3862  if (ISCONFIGSET_PRIV(eAAMPConfig_CurlHeader) && (eMEDIATYPE_VIDEO == simType || eMEDIATYPE_PLAYLIST_VIDEO == simType))
3863  {
3864  std::string customheaderstr;
3865  GETCONFIGVALUE_PRIV(eAAMPConfig_CustomHeader,customheaderstr);
3866  if(!customheaderstr.empty())
3867  {
3868  //AAMPLOG_WARN ("Custom Header Data: Index( %d ) Data( %s )", i, &customheaderstr.at(i));
3869  httpHeaders = curl_slist_append(httpHeaders, customheaderstr.c_str());
3870  }
3871  }
3872 
3873  if (mIsFirstRequestToFOG && mTSBEnabled && eMEDIATYPE_MANIFEST == simType)
3874  {
3875  std::string customHeader = "4k: 1";
3876  if (ISCONFIGSET_PRIV(eAAMPConfig_Disable4K))
3877  {
3878  customHeader = "4k: 0";
3879  }
3880  httpHeaders = curl_slist_append(httpHeaders, customHeader.c_str());
3881  }
3882 
3883  if (httpHeaders != NULL)
3884  {
3885  CURL_EASY_SETOPT(curl, CURLOPT_HTTPHEADER, httpHeaders);
3886  }
3887  }
3888 
3889  while(downloadAttempt < maxDownloadAttempt)
3890  {
3891  progressCtx.downloadStartTime = NOW_STEADY_TS_MS;
3892 
3894  {
3895  context.downloadStartTime = progressCtx.downloadStartTime;
3896  CURL_EASY_SETOPT(curl, CURLOPT_WRITEDATA, &context);
3897  CURL_EASY_SETOPT(curl, CURLOPT_HEADERDATA, &context);
3898  }
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)
3904  {
3905  AAMPLOG_TRACE("reset length. buffer %p avail %d", buffer, (int)buffer->avail);
3906  buffer->len = 0;
3907  }
3908 
3909  isDownloadStalled = false;
3910  abortReason = eCURL_ABORT_REASON_NONE;
3911 
3912  long long tStartTime = NOW_STEADY_TS_MS;
3913  CURLcode res = curl_easy_perform(curl); // synchronous; callbacks allow interruption
3914 
3916  {
3917  int insertDownloadDelay=0;
3918  GETCONFIGVALUE_PRIV(eAAMPConfig_DownloadDelay,insertDownloadDelay);
3919  /* optionally locally induce extra per-download latency */
3920  if( insertDownloadDelay > 0 )
3921  {
3922  InterruptableMsSleep( insertDownloadDelay );
3923  }
3924  }
3925 
3926  long long tEndTime = NOW_STEADY_TS_MS;
3927  downloadAttempt++;
3928 
3929  downloadTimeMS = (int)(tEndTime - tStartTime);
3930  bool loopAgain = false;
3931  if (res == CURLE_OK)
3932  { // all data collected
3933  if( memcmp(remoteUrl.c_str(), "file:", 5) == 0 )
3934  { // file uri scheme
3935  // libCurl does not provide CURLINFO_RESPONSE_CODE for 'file:' protocol.
3936  // Handle CURL_OK to http_code mapping here, other values handled below (see http_code = res).
3937  http_code = 200;
3938  }
3939  else
3940  {
3941  curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
3942  }
3943  char *effectiveUrlPtr = NULL;
3944  if (http_code != 200 && http_code != 204 && http_code != 206)
3945  {
3946  AAMP_LOG_NETWORK_ERROR (remoteUrl.c_str(), AAMPNetworkErrorHttp, (int)http_code, simType);
3947  print_headerResponse(context.allResponseHeadersForErrorLogging, simType);
3948 
3949  if((http_code >= 500 && http_code != 502) && downloadAttempt < maxDownloadAttempt)
3950  {
3951  int waitTimeBeforeRetryHttp5xxMSValue;
3952  GETCONFIGVALUE_PRIV(eAAMPConfig_Http5XXRetryWaitInterval,waitTimeBeforeRetryHttp5xxMSValue);
3953  InterruptableMsSleep(waitTimeBeforeRetryHttp5xxMSValue);
3954  AAMPLOG_WARN("Download failed due to Server error. Retrying Attempt:%d!", downloadAttempt);
3955  loopAgain = true;
3956  }
3957  }
3958  if(http_code == 204)
3959  {
3960  if ( (httpRespHeaders[curlInstance].type == eHTTPHEADERTYPE_EFF_LOCATION) && (httpRespHeaders[curlInstance].data.length() > 0) )
3961  {
3962  AAMPLOG_WARN("Received Location header: '%s'", httpRespHeaders[curlInstance].data.c_str());
3963  effectiveUrlPtr = const_cast<char *>(httpRespHeaders[curlInstance].data.c_str());
3964  }
3965  }
3966  else
3967  {
3968  //When Fog is having tsb write error , then it will respond back with 302 with direct CDN url,In this case alone TSB should be disabled
3969  if(mTSBEnabled && http_code == 302)
3970  {
3971  mTSBEnabled = false;
3972  }
3973  res = curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effectiveUrlPtr);
3974  if((simType == eMEDIATYPE_INIT_VIDEO || simType == eMEDIATYPE_INIT_AUDIO))
3975  {
3976  IsoBmffBuffer isobuf(mLogObj);
3977  isobuf.setBuffer(reinterpret_cast<uint8_t *>(context.buffer->ptr), context.buffer->len);
3978 
3979  bool bParse = false;
3980  try
3981  {
3982  bParse = isobuf.parseBuffer();
3983  }
3984  catch( std::bad_alloc& ba)
3985  {
3986  AAMPLOG_ERR("Bad allocation: %s", ba.what() );
3987  }
3988  catch( std::exception &e)
3989  {
3990  AAMPLOG_ERR("Unhandled exception: %s", e.what() );
3991  }
3992  catch( ... )
3993  {
3994  AAMPLOG_ERR("Unknown exception");
3995  }
3996 
3997  if(!bParse)
3998  {
3999  AAMPLOG_ERR("[%d] Cant Find TimeScale. No Box available in Init File !!!", simType);
4000  }
4001  else
4002  {
4003  AAMPLOG_INFO("[%d] Buffer Length: %zu", simType, context.buffer->len);
4004 
4005  //Print box details
4006  //isobuf.printBoxes();
4007  if(isobuf.isInitSegment())
4008  {
4009  uint32_t timeScale = 0;
4010  isobuf.getTimeScale(timeScale);
4011  if(simType == eMEDIATYPE_INIT_VIDEO)
4012  {
4013  AAMPLOG_INFO("Video TimeScale [%d]", timeScale);
4014  SetVidTimeScale(timeScale);
4015  }
4016  else
4017  {
4018  AAMPLOG_INFO("Audio TimeScale [%d]", timeScale);
4019  SetAudTimeScale(timeScale);
4020  }
4021  }
4022  }
4023  }
4024  }
4025 
4026  if(effectiveUrlPtr)
4027  {
4028  effectiveUrl.assign(effectiveUrlPtr); //CID:81493 - Resolve Forward null
4029 
4030  if( ISCONFIGSET_PRIV(eAAMPConfig_EnableCurlStore) && (remoteUrl!=effectiveUrl) )
4031  {
4032  curlhost[curlInstance]->redirect = true;
4033  }
4034  }
4035 
4036  // check if redirected url is pointing to fog / local ip
4037  if(mIsFirstRequestToFOG)
4038  {
4039  if(mTsbRecordingId.empty())
4040  {
4041  AAMPLOG_INFO("TSB not avaialble from fog, playing from:%s ", effectiveUrl.c_str());
4042  }
4043  this->UpdateVideoEndTsbStatus(mTSBEnabled);
4044  }
4045 
4046  /*
4047  * Latency should be printed in the case of successful download which exceeds the download threshold value,
4048  * other than this case is assumed as network error and those will be logged with AAMP_LOG_NETWORK_ERROR.
4049  */
4050  if (fragmentDurationSeconds != 0.0)
4051  {
4052  /*in case of fetch fragment this will be non zero value */
4053  if (downloadTimeMS > fragmentDurationMs )
4054  {
4055  AAMP_LOG_NETWORK_LATENCY (effectiveUrl.c_str(), downloadTimeMS, fragmentDurationMs, simType);
4056  }
4057  }
4058  else if (downloadTimeMS > FRAGMENT_DOWNLOAD_WARNING_THRESHOLD )
4059  {
4060  AAMP_LOG_NETWORK_LATENCY (effectiveUrl.c_str(), downloadTimeMS, FRAGMENT_DOWNLOAD_WARNING_THRESHOLD, simType);
4061  print_headerResponse(context.allResponseHeadersForErrorLogging, simType);
4062  }
4063  }
4064  else
4065  {
4066  long curlDownloadTimeoutMS = curlDLTimeout[curlInstance]; // curlDLTimeout is in msec
4067  //abortReason for progress_callback exit scenarios
4068  // curl sometimes exceeds the wait time by few milliseconds.Added buffer of 10msec
4069  isDownloadStalled = ((res == CURLE_PARTIAL_FILE) || (progressCtx.abortReason != eCURL_ABORT_REASON_NONE));
4070  // set flag if download aborted with start/stall timeout.
4071  abortReason = progressCtx.abortReason;
4072 
4073  /* Curl 23 and 42 is not a real network error, so no need to log it here */
4074  //Log errors due to curl stall/start detection abort
4075  if (AAMP_IS_LOG_WORTHY_ERROR(res) || progressCtx.abortReason != eCURL_ABORT_REASON_NONE)
4076  {
4077  AAMP_LOG_NETWORK_ERROR (remoteUrl.c_str(), AAMPNetworkErrorCurl, (int)(progressCtx.abortReason == eCURL_ABORT_REASON_NONE ? res : CURLE_PARTIAL_FILE), simType);
4078  print_headerResponse(context.allResponseHeadersForErrorLogging, simType);
4079  }
4080 
4081  //Attempt retry for partial downloads, which have a higher chance to succeed
4082  if((res == CURLE_COULDNT_CONNECT || res == CURLE_OPERATION_TIMEDOUT || (isDownloadStalled && (eCURL_ABORT_REASON_LOW_BANDWIDTH_TIMEDOUT != abortReason))) && downloadAttempt < maxDownloadAttempt)
4083  {
4085  {
4086  if( simType == eMEDIATYPE_MANIFEST ||
4087  simType == eMEDIATYPE_AUDIO ||
4088  simType == eMEDIATYPE_VIDEO ||
4089  simType == eMEDIATYPE_INIT_VIDEO ||
4090  simType == eMEDIATYPE_PLAYLIST_AUDIO ||
4091  simType == eMEDIATYPE_INIT_AUDIO ||
4092  simType == eMEDIATYPE_AUX_AUDIO || simType == eMEDIATYPE_INIT_AUX_AUDIO)
4093  { // always retry small, critical fragments on timeout
4094  loopAgain = true;
4095  }
4096  else
4097  {
4098  double buffervalue = mpStreamAbstractionAAMP->GetBufferedDuration();
4099  // buffer is -1 when sesssion not created . buffer is 0 when session created but playlist not downloaded
4100  if( buffervalue == -1.0 || buffervalue == 0 || buffervalue*1000 > (curlDownloadTimeoutMS + fragmentDurationMs))
4101  {
4102  // GetBuffer will return -1 if session is not created
4103  // Check if buffer is available and more than timeout interval then only reattempt
4104  // Not to retry download if there is no buffer left
4105  loopAgain = true;
4106  if(simType == eMEDIATYPE_VIDEO)
4107  {
4108  if(buffer->len)
4109  {
4110  long downloadbps = ((long)(buffer->len / downloadTimeMS)*8000);
4111  long currentProfilebps = mpStreamAbstractionAAMP->GetVideoBitrate();
4112  if(currentProfilebps - downloadbps > BITRATE_ALLOWED_VARIATION_BAND)
4113  loopAgain = false;
4114  }
4115  curlDownloadTimeoutMS = mNetworkTimeoutMs;
4116  }
4117  }
4118  }
4119  }
4120  AAMPLOG_WARN("Download failed due to curl timeout or isDownloadStalled:%d Retrying:%d Attempt:%d", isDownloadStalled, loopAgain, downloadAttempt);
4121  }
4122 
4123  /*
4124  * Assigning curl error to http_code, for sending the error code as
4125  * part of error event if required
4126  * We can distinguish curl error and http error based on value
4127  * curl errors are below 100 and http error starts from 100
4128  */
4129  if( res == CURLE_FILE_COULDNT_READ_FILE )
4130  {
4131  http_code = 404; // translate file not found to URL not found
4132  }
4133  else if(abortReason == eCURL_ABORT_REASON_LOW_BANDWIDTH_TIMEDOUT)
4134  {
4135  http_code = CURLE_OPERATION_TIMEDOUT; // Timed out wrt configured low bandwidth timeout.
4136  }
4137  else
4138  {
4139  http_code = res;
4140  }
4141  #if 0
4142  if (isDownloadStalled)
4143  {
4144  AAMPLOG_INFO("Curl download stall detected - curl result:%d abortReason:%d downloadTimeMS:%lld curlTimeout:%ld", res, progressCtx.abortReason,
4145  downloadTimeMS, curlDownloadTimeoutMS);
4146  //To avoid updateBasedonFragmentCached being called on rampdown and to be discarded from ABR
4147  http_code = CURLE_PARTIAL_FILE;
4148  }
4149  #endif
4150  }
4151 
4152 
4153  double total, connect, startTransfer, resolve, appConnect, preTransfer, redirect, dlSize;
4154  long reqSize, downloadbps = 0;
4155  AAMP_LogLevel reqEndLogLevel = eLOGLEVEL_INFO;
4156  if(downloadTimeMS != 0 && buffer->len != 0)
4157  downloadbps = ((long)(buffer->len / downloadTimeMS)*8000);
4158 
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 /*seconds*/)
4164  {
4165  reqEndLogLevel = eLOGLEVEL_WARN;
4166  }
4167  if (gpGlobalConfig->logging.isLogLevelAllowed(reqEndLogLevel))
4168  {
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);
4177  if((pCMCDMetrics!=NULL) && ISCONFIGSET_PRIV(eAAMPConfig_EnableCMCD))
4178  {
4179  pCMCDMetrics->SetNetworkMetrics((int)(startTransfer*1000),(int)(total*1000),(int)(resolve*1000));
4180  }
4181 
4182  std::string appName, timeoutClass;
4183  if (!mAppName.empty())
4184  {
4185  // append app name with class data
4186  appName = mAppName + ",";
4187  }
4188  if (CURLE_OPERATION_TIMEDOUT == res || CURLE_PARTIAL_FILE == res || CURLE_COULDNT_CONNECT == res)
4189  {
4190  // introduce extra marker for connection status curl 7/18/28,
4191  // example 18(0) if connection failure with PARTIAL_FILE code
4192  timeoutClass = "(" + to_string(reqSize > 0) + ")";
4193  }
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,
4196  (((simType == eMEDIATYPE_VIDEO) || (simType == eMEDIATYPE_INIT_VIDEO) || (simType == eMEDIATYPE_PLAYLIST_VIDEO)) ? mpStreamAbstractionAAMP->GetVideoBitrate() : 0), // Video fragment current bitrate
4197  ((res == CURLE_OK) ? effectiveUrl.c_str() : remoteUrl.c_str())); // Effective URL could be different than remoteURL and it is updated only for CURLE_OK case
4198  if(ui32CurlTrace < 10 )
4199  {
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()));
4202  ++ui32CurlTrace;
4203  }
4204  }
4205 
4206  if(!loopAgain)
4207  break;
4208  }
4209  }
4210 
4211  if (http_code == 200 || http_code == 206 || http_code == CURLE_OPERATION_TIMEDOUT)
4212  {
4213  if (http_code == CURLE_OPERATION_TIMEDOUT && buffer->len > 0)
4214  {
4215  AAMPLOG_WARN("Download timedout and obtained a partial buffer of size %zu for a downloadTime=%d and isDownloadStalled:%d", buffer->len, downloadTimeMS, isDownloadStalled);
4216  }
4217 
4218  if (downloadTimeMS > 0 && fileType == eMEDIATYPE_VIDEO && CheckABREnabled())
4219  {
4220  int AbrThresholdSize;
4221  GETCONFIGVALUE_PRIV(eAAMPConfig_ABRThresholdSize,AbrThresholdSize);
4222  //HybridABRManager mhABRManager;
4223  HybridABRManager::CurlAbortReason hybridabortReason = (HybridABRManager::CurlAbortReason) abortReason;
4224  if((buffer->len > AbrThresholdSize) && (!GetLLDashServiceData()->lowLatencyMode ||
4226  {
4227  long currentProfilebps = mpStreamAbstractionAAMP->GetVideoBitrate();
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);
4232 
4233  }
4234  }
4235  }
4236  if (http_code == 200 || http_code == 206)
4237  {
4239  {
4240  /* Avoid chance of overwriting , in case of manifest and playlist, name will be always same */
4241  if(fileType == eMEDIATYPE_MANIFEST || fileType == eMEDIATYPE_PLAYLIST_AUDIO
4242  || fileType == eMEDIATYPE_PLAYLIST_IFRAME || fileType == eMEDIATYPE_PLAYLIST_SUBTITLE || fileType == eMEDIATYPE_PLAYLIST_VIDEO )
4243  {
4245  }
4246 
4247  AAMPLOG_WARN("aamp harvestCountLimit: %d mManifestRefreshCount %d", mHarvestCountLimit,mManifestRefreshCount);
4248  std::string harvestPath;
4249  GETCONFIGVALUE_PRIV(eAAMPConfig_HarvestPath,harvestPath);
4250  if(harvestPath.empty() )
4251  {
4252  getDefaultHarvestPath(harvestPath);
4253  AAMPLOG_WARN("Harvest path has not configured, taking default path %s", harvestPath.c_str());
4254  }
4255  if(buffer->ptr)
4256  {
4257  if(aamp_WriteFile(remoteUrl, buffer->ptr, buffer->len, fileType, mManifestRefreshCount,harvestPath.c_str()))
4259  } //CID:168113 - forward null
4260  }
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))
4263  {
4264  //Note: For non-compressed data, Content-Length header and buffer size should be same. For gzipped data, 'Content-Length' will be <= deflated data.
4265  AAMPLOG_WARN("AAMP Content-Length=%d actual=%d", (int)expectedContentLength, (int)buffer->len);
4266  http_code = 416; // Range Not Satisfiable
4267  ret = false; // redundant, but harmless
4268  aamp_Free(buffer);
4269  memset(buffer, 0x00, sizeof(*buffer));
4270  }
4271  else
4272  {
4273  if(fileType == eMEDIATYPE_MANIFEST)
4274  {
4275  fileType = (MediaType)curlInstance;
4276  }
4277  else if (remoteUrl.find("iframe") != std::string::npos)
4278  {
4279  fileType = eMEDIATYPE_IFRAME;
4280  }
4281  ret = true;
4282  }
4283  }
4284  else
4285  {
4286  if (AAMP_IS_LOG_WORTHY_ERROR(res))
4287  {
4288  AAMPLOG_WARN("BAD URL:%s", remoteUrl.c_str());
4289  }
4290  aamp_Free(buffer);
4291  memset(buffer, 0x00, sizeof(*buffer));
4292 
4293  if (rate != 1.0)
4294  {
4295  fileType = eMEDIATYPE_IFRAME;
4296  }
4297 
4298  // dont generate anomaly reports for write and aborted errors
4299  // these are generated after trick play options,
4300  if( !(http_code == CURLE_ABORTED_BY_CALLBACK || http_code == CURLE_WRITE_ERROR || http_code == 204))
4301  {
4302  SendAnomalyEvent(ANOMALY_WARNING, "%s:%s,%s-%d url:%s", (mTSBEnabled ? "FOG" : "CDN"),
4303  MediaTypeString(fileType), (http_code < 100) ? "Curl" : "HTTP", http_code, remoteUrl.c_str());
4304  }
4305 
4306  if ( (httpRespHeaders[curlInstance].type == eHTTPHEADERTYPE_XREASON) && (httpRespHeaders[curlInstance].data.length() > 0) )
4307  {
4308  AAMPLOG_WARN("Received X-Reason header from %s: '%s'", mTSBEnabled?"Fog":"CDN Server", httpRespHeaders[curlInstance].data.c_str());
4309  SendAnomalyEvent(ANOMALY_WARNING, "%s X-Reason:%s", mTSBEnabled ? "Fog" : "CDN", httpRespHeaders[curlInstance].data.c_str());
4310  }
4311  else if ( (httpRespHeaders[curlInstance].type == eHTTPHEADERTYPE_FOG_REASON) && (httpRespHeaders[curlInstance].data.length() > 0) )
4312  {
4313  //extract error and url used by fog to download content from cdn
4314  // it is part of fog-reason
4315  if(fogError)
4316  {
4317  std::regex errRegx("-(.*),");
4318  std::smatch match;
4319  if (std::regex_search(httpRespHeaders[curlInstance].data, match, errRegx) && match.size() > 1) {
4320  if (!match.str(1).empty())
4321  {
4322  *fogError = std::stoi(match.str(1));
4323  AAMPLOG_INFO("Received FOG-Reason fogError: '%d'", *fogError);
4324  }
4325  }
4326  }
4327 
4328  // get failed url from fog reason and update effectiveUrl
4329  if(!effectiveUrl.empty())
4330  {
4331  std::regex fromRegx("from:(.*),");
4332  std::smatch match;
4333 
4334  if (std::regex_search(httpRespHeaders[curlInstance].data, match, fromRegx) && match.size() > 1) {
4335  if (!match.str(1).empty())
4336  {
4337  effectiveUrl.assign(match.str(1).c_str());
4338  AAMPLOG_INFO("Received FOG-Reason effectiveUrl: '%s'", effectiveUrl.c_str());
4339  }
4340  }
4341  }
4342 
4343 
4344  AAMPLOG_WARN("Received FOG-Reason header: '%s'", httpRespHeaders[curlInstance].data.c_str());
4345  SendAnomalyEvent(ANOMALY_WARNING, "FOG-Reason:%s", httpRespHeaders[curlInstance].data.c_str());
4346  }
4347  }
4348 
4349  if (bitrate && (context.bitrate > 0))
4350  {
4351  AAMPLOG_INFO("Received getfile Bitrate : %ld", context.bitrate);
4352  *bitrate = context.bitrate;
4353  }
4354 
4355  if(abortReason != eCURL_ABORT_REASON_NONE && abortReason != eCURL_ABORT_REASON_LOW_BANDWIDTH_TIMEDOUT)
4356  {
4357  http_code = PARTIAL_FILE_START_STALL_TIMEOUT_AAMP;
4358  }
4359  else if (connectTime == 0.0)
4360  {
4361  //curl connection is failure
4362  if(CURLE_PARTIAL_FILE == http_code)
4363  {
4364  http_code = PARTIAL_FILE_CONNECTIVITY_AAMP;
4365  }
4366  else if(CURLE_OPERATION_TIMEDOUT == http_code)
4367  {
4368  http_code = OPERATION_TIMEOUT_CONNECTIVITY_AAMP;
4369  }
4370  }
4371  else if (CURLE_PARTIAL_FILE == http_code)
4372  {
4373  // download time expired with partial file for playlists/init fragments
4374  http_code = PARTIAL_FILE_DOWNLOAD_TIME_EXPIRED_AAMP;
4375  }
4376  pthread_mutex_lock(&mLock);
4377  }
4378  else
4379  {
4380  AAMPLOG_WARN("downloads disabled");
4381  }
4382  pthread_mutex_unlock(&mLock);
4383  if (http_error)
4384  {
4385  *http_error = http_code;
4386  if(downloadTime)
4387  {
4388  *downloadTime = fileDownloadTime;
4389  }
4390  }
4391  if (httpHeaders != NULL)
4392  {
4393  curl_slist_free_all(httpHeaders);
4394  }
4395  if (mIsFirstRequestToFOG)
4396  {
4397  mIsFirstRequestToFOG = false;
4398  }
4399 
4400  if (ISCONFIGSET_PRIV(eAAMPConfig_EnableLinearSimulator))
4401  {
4402  // NEW! note that for simulated playlists, ideally we'd not bother re-downloading playlist above
4403 
4404  AAMPLOG_INFO("*** Simulated Linear URL: %s\n", remoteUrl.c_str()); // Log incoming request
4405 
4406  switch( simType )
4407  {
4408  case eMEDIATYPE_MANIFEST:
4409  {
4410  // Reset state after requesting main manifest
4411  if( full_playlist_video_ptr )
4412  {
4413  // Flush old cached video playlist
4414 
4415  free( full_playlist_video_ptr );
4416  full_playlist_video_ptr = NULL;
4417  full_playlist_video_len = 0;
4418  }
4419 
4420  if( full_playlist_audio_ptr )
4421  {
4422  // Flush old cached audio playlist
4423 
4424  free( full_playlist_audio_ptr );
4425  full_playlist_audio_ptr = NULL;
4426  full_playlist_audio_len = 0;
4427  }
4428 
4430  }
4431  break; /* eMEDIATYPE_MANIFEST */
4432 
4434  {
4435  if( !full_playlist_audio_ptr )
4436  {
4437  // Cache the full vod audio playlist
4438 
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 );
4442  }
4443 
4444  SimulateLinearWindow( buffer, full_playlist_audio_ptr, full_playlist_audio_len );
4445  }
4446  break; /* eMEDIATYPE_PLAYLIST_AUDIO */
4447 
4449  {
4450  if( !full_playlist_video_ptr )
4451  {
4452  // Cache the full vod video playlist
4453 
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 );
4457  }
4458 
4459  SimulateLinearWindow( buffer, full_playlist_video_ptr, full_playlist_video_len );
4460  }
4461  break; /* eMEDIATYPE_PLAYLIST_VIDEO */
4462 
4463  default:
4464  break;
4465  }
4466  }
4467  //Stip downloaded chunked Iframes when ranged requests receives 200 as HTTP response for HLS MP4
4468  if( mConfig->IsConfigSet(eAAMPConfig_RepairIframes) && NULL != range && '\0' != range[0] && 200 == http_code && NULL != buffer->ptr && FORMAT_ISO_BMFF == this->mVideoFormat)
4469  {
4470  AAMPLOG_INFO( "Received HTTP 200 for ranged request (chunked iframe: %s: %s), starting to strip the fragment", range, remoteUrl.c_str() );
4471  size_t start;
4472  size_t end;
4473  try {
4474  if(2 == sscanf(range, "%zu-%zu", &start, &end))
4475  {
4476  // #EXT-X-BYTERANGE:19301@88 from manifest is equivalent to 88-19388 in HTTP range request
4477  size_t len = (end - start) + 1;
4478  if( buffer->len >= len)
4479  {
4480  memmove(buffer->ptr, buffer->ptr + start, len);
4481  buffer->len=len;
4482  }
4483 
4484  // hack - repair wrong size in box
4485  IsoBmffBuffer repair(mLogObj);
4486  repair.setBuffer((uint8_t *)buffer->ptr, buffer->len);
4487  repair.parseBuffer(true); //correctBoxSize=true
4488  AAMPLOG_INFO("Stripping the fragment for range request completed");
4489  }
4490  else
4491  {
4492  AAMPLOG_ERR("Stripping the fragment for range request failed, failed to parse range string");
4493  }
4494  }
4495  catch (std::exception &e)
4496  {
4497  AAMPLOG_ERR("Stripping the fragment for ranged request failed (%s)", e.what());
4498  }
4499  }
4500 
4501  return ret;
4502 }
4503 
4504 /**
4505  * @brief Download VideoEnd Session statistics from fog
4506  *
4507  * @return string tsbSessionEnd data from fog
4508  */
4510 {
4511  std::string remoteUrl = "127.0.0.1:9080/sessionstat";
4512  long http_error = -1;
4513  char* ret = NULL;
4514  if(!mTsbRecordingId.empty())
4515  {
4516  /* Request session statistics for current recording ID
4517  *
4518  * example request: 127.0.0.1:9080/sessionstat/<recordingID>
4519  *
4520  */
4521  remoteUrl.append("/");
4522  remoteUrl.append(mTsbRecordingId);
4523  GrowableBuffer data;
4524  if(ProcessCustomCurlRequest(remoteUrl, &data, &http_error))
4525  {
4526  // succesfully requested
4527  AAMPLOG_INFO("curl request %s success", remoteUrl.c_str());
4528  cJSON *root = cJSON_Parse(data.ptr);
4529  if (root == NULL)
4530  {
4531  const char *error_ptr = cJSON_GetErrorPtr();
4532  if (error_ptr != NULL)
4533  {
4534  AAMPLOG_ERR("Invalid Json format: %s", error_ptr);
4535  }
4536  }
4537  else
4538  {
4539  ret = cJSON_PrintUnformatted(root);
4540  cJSON_Delete(root);
4541  }
4542 
4543  }
4544  else
4545  {
4546  // Failure in request
4547  AAMPLOG_ERR("curl request %s failed[%d]", remoteUrl.c_str(), http_error);
4548  }
4549 
4550  aamp_Free(&data);
4551  }
4552 
4553  return ret;
4554 }
4555 
4556 /**
4557  * @brief Perform custom curl request
4558  */
4559 bool PrivateInstanceAAMP::ProcessCustomCurlRequest(std::string& remoteUrl, GrowableBuffer* buffer, long *http_error, CurlRequest request, std::string pData)
4560 {
4561  bool ret = false;
4562  CURLcode res;
4563  long httpCode = -1;
4564  CURL *curl = curl_easy_init();
4565  if(curl)
4566  {
4567  AAMPLOG_INFO("%s, %d", remoteUrl.c_str(), request);
4568 
4569  CURL_EASY_SETOPT(curl, CURLOPT_TIMEOUT, DEFAULT_CURL_TIMEOUT);
4570  CURL_EASY_SETOPT(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER);
4571  CURL_EASY_SETOPT(curl, CURLOPT_FOLLOWLOCATION, 1L);
4572 
4573  if(!ISCONFIGSET_PRIV(eAAMPConfig_SslVerifyPeer))
4574  {
4575  CURL_EASY_SETOPT(curl, CURLOPT_SSL_VERIFYPEER, 0L);
4576  }
4577  else
4578  {
4579  CURL_EASY_SETOPT(curl, CURLOPT_SSLVERSION, mSupportedTLSVersion);
4580  CURL_EASY_SETOPT(curl, CURLOPT_SSL_VERIFYPEER, 1L);
4581  }
4582  CURL_EASY_SETOPT(curl, CURLOPT_URL, remoteUrl.c_str());
4583 
4584  if(eCURL_GET == request)
4585  {
4586  CurlCallbackContext context(this, buffer);
4587  memset(buffer, 0x00, sizeof(*buffer));
4588  CurlProgressCbContext progressCtx(this, NOW_STEADY_TS_MS);
4589 
4590  CURL_EASY_SETOPT(curl, CURLOPT_NOSIGNAL, 1L);
4591  CURL_EASY_SETOPT(curl, CURLOPT_WRITEFUNCTION, write_callback);
4592  CURL_EASY_SETOPT(curl, CURLOPT_PROGRESSFUNCTION, progress_callback);
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); // DELIA-57728 - avoid out of scope use of progressCtx
4598  }
4599  else if(eCURL_DELETE == request)
4600  {
4601  CURL_EASY_SETOPT(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
4602  res = curl_easy_perform(curl);
4603  }
4604  else if(eCURL_POST == request)
4605  {
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);
4609  }
4610 
4611  if (res == CURLE_OK)
4612  {
4613  curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
4614  if ((httpCode == 204) || (httpCode == 200))
4615  {
4616  ret = true;
4617  }
4618  else
4619  {
4620  AAMPLOG_ERR("Returned [%d]", httpCode);
4621  }
4622  }
4623  else
4624  {
4625  AAMPLOG_ERR("Failed to perform curl request, result:%d", res);
4626  }
4627 
4628  if(httpCode > 0)
4629  {
4630  *http_error = httpCode;
4631  }
4632 
4633  curl_easy_cleanup(curl);
4634  }
4635  return ret;
4636 }
4637 
4638 /**
4639  * @brief Terminate the stream
4640  */
4642 {
4643  pthread_mutex_lock(&mLock);
4644  //Have to perfom this for trick and stop operations but avoid ad insertion related ones
4645  AAMPLOG_WARN(" mProgressReportFromProcessDiscontinuity:%d mDiscontinuityTuneOperationId:%d newTune:%d", mProgressReportFromProcessDiscontinuity, mDiscontinuityTuneOperationId, newTune);
4646  if ((mDiscontinuityTuneOperationId != 0) && (!newTune || mState == eSTATE_IDLE))
4647  {
4648  bool waitForDiscontinuityProcessing = true;
4649  if (mProgressReportFromProcessDiscontinuity)
4650  {
4651  AAMPLOG_WARN("TeardownStream invoked while mProgressReportFromProcessDiscontinuity and mDiscontinuityTuneOperationId[%d] set!", mDiscontinuityTuneOperationId);
4652  guint callbackID = aamp_GetSourceID();
4653  if ((callbackID != 0 && mDiscontinuityTuneOperationId == callbackID) || mAsyncTuneEnabled)
4654  {
4655  AAMPLOG_WARN("TeardownStream idle callback id[%d] and mDiscontinuityTuneOperationId[%d] match. Ignore further discontinuity processing!", callbackID, mDiscontinuityTuneOperationId);
4656  waitForDiscontinuityProcessing = false; // to avoid deadlock
4657  mDiscontinuityTuneOperationInProgress = false;
4658  mDiscontinuityTuneOperationId = 0;
4659  }
4660  }
4661  if (waitForDiscontinuityProcessing)
4662  {
4663  //wait for discontinuity tune operation to finish before proceeding with stop
4664  if (mDiscontinuityTuneOperationInProgress)
4665  {
4666  AAMPLOG_WARN("TeardownStream invoked while mDiscontinuityTuneOperationInProgress set. Wait until the Discontinuity Tune operation to complete!!");
4667  pthread_cond_wait(&mCondDiscontinuity, &mLock);
4668  }
4669  else
4670  {
4671  RemoveAsyncTask(mDiscontinuityTuneOperationId);
4672  mDiscontinuityTuneOperationId = 0;
4673  }
4674  }
4675  }
4676  // Maybe mDiscontinuityTuneOperationId is 0, ProcessPendingDiscontinuity can be invoked from NotifyEOSReached too
4677  else if (mProgressReportFromProcessDiscontinuity || mDiscontinuityTuneOperationInProgress)
4678  {
4679  if(mDiscontinuityTuneOperationInProgress)
4680  {
4681  AAMPLOG_WARN("TeardownStream invoked while mDiscontinuityTuneOperationInProgress set. Wait until the pending discontinuity tune operation to complete !!");
4682  pthread_cond_wait(&mCondDiscontinuity, &mLock);
4683  }
4684  else
4685  {
4686  AAMPLOG_WARN("TeardownStream invoked while mProgressReportFromProcessDiscontinuity set!");
4687  mDiscontinuityTuneOperationInProgress = false;
4688  }
4689  }
4690 
4691  //reset discontinuity related flags
4695  pthread_mutex_unlock(&mLock);
4696 
4698  {
4699  mpStreamAbstractionAAMP->Stop(false);
4700  SAFE_DELETE(mpStreamAbstractionAAMP);
4701  }
4702 
4703  pthread_mutex_lock(&mLock);
4704  mVideoFormat = FORMAT_INVALID;
4705  pthread_mutex_unlock(&mLock);
4706  if (streamerIsActive)
4707  {
4708 #ifdef AAMP_STOP_SINK_ON_SEEK
4709  const bool forceStop = true;
4710  // Don't send event if nativeCCRendering is ON
4711  if (!ISCONFIGSET_PRIV(eAAMPConfig_NativeCCRendering))
4712  {
4713  CCHandleEventPtr event = std::make_shared<CCHandleEvent>(0);
4714  mEventManager->SendEvent(event);
4715  AAMPLOG_WARN("Sent AAMP_EVENT_CC_HANDLE_RECEIVED with NULL handle");
4716  }
4717 #else
4718  const bool forceStop = false;
4719 #endif
4720  if (!forceStop && ((!newTune && ISCONFIGSET_PRIV(eAAMPConfig_DemuxVideoHLSTrack)) || ISCONFIGSET_PRIV(eAAMPConfig_PreservePipeline)))
4721  {
4722  mStreamSink->Flush(0, rate);
4723  }
4724  else
4725  {
4726 #ifdef AAMP_CC_ENABLED
4727  AAMPLOG_INFO("before CC Release - mTuneType:%d mbPlayEnabled:%d ", mTuneType, mbPlayEnabled);
4728  if (mbPlayEnabled && mTuneType != eTUNETYPE_RETUNE)
4729  {
4731  mCCId = 0;
4732  }
4733  else
4734  {
4735  AAMPLOG_WARN("CC Release - skipped ");
4736  }
4737 #endif
4739  {
4740  mStreamSink->Stop(!newTune);
4741  }
4742  }
4743  }
4744  else
4745  {
4746  for (int iTrack = 0; iTrack < AAMP_TRACK_COUNT; iTrack++)
4747  {
4748  mbTrackDownloadsBlocked[iTrack] = true;
4749  }
4750  streamerIsActive = true;
4751  }
4752  mAdProgressId = "";
4753  std::queue<AAMPEventPtr> emptyEvQ;
4754  {
4755  std::lock_guard<std::mutex> lock(mAdEventQMtx);
4756  std::swap( mAdEventsQ, emptyEvQ );
4757  }
4758 }
4759 
4760 /**
4761  * @brief Establish PIPE session with Receiver
4762  */
4764 {
4765  bool retVal = false;
4766  if(m_fd != -1)
4767  {
4768  retVal = true; //Pipe exists
4769  return retVal;
4770  }
4771  if(mkfifo(strAAMPPipeName, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) == -1)
4772  {
4773  if(errno == EEXIST)
4774  {
4775  // Pipe exists
4776  //AAMPLOG_WARN("CreatePipe: Pipe already exists");
4777  retVal = true;
4778  }
4779  else
4780  {
4781  // Error
4782  AAMPLOG_ERR("CreatePipe: Failed to create named pipe %s for reading errno = %d (%s)",
4783  strAAMPPipeName, errno, strerror(errno));
4784  }
4785  }
4786  else
4787  {
4788  // Success
4789  //AAMPLOG_WARN("CreatePipe: mkfifo succeeded");
4790  retVal = true;
4791  }
4792 
4793  if(retVal)
4794  {
4795  // Open the named pipe for writing
4796  m_fd = open(strAAMPPipeName, O_WRONLY | O_NONBLOCK );
4797  if (m_fd == -1)
4798  {
4799  // error
4800  AAMPLOG_WARN("OpenPipe: Failed to open named pipe %s for writing errno = %d (%s)",
4801  strAAMPPipeName, errno, strerror(errno));
4802  }
4803  else
4804  {
4805  // Success
4806  retVal = true;
4807  }
4808  }
4809  return retVal;
4810 }
4811 
4812 
4813 /**
4814  * @brief Close PIPE session with Receiver
4815  */
4817 {
4818  if(m_fd != -1)
4819  {
4820  close(m_fd);
4821  m_fd = -1;
4822  }
4823 }
4824 
4825 /**
4826  * @brief Send messages to Receiver over PIPE
4827  */
4828 void PrivateInstanceAAMP::SendMessageOverPipe(const char *str,int nToWrite)
4829 {
4830  if(m_fd != -1)
4831  {
4832  // Write the packet data to the pipe
4833  int nWritten = write(m_fd, str, nToWrite);
4834  if(nWritten != nToWrite)
4835  {
4836  // Error
4837  AAMPLOG_WARN("Error writing data written = %d, size = %d errno = %d (%s)",
4838  nWritten, nToWrite, errno, strerror(errno));
4839  if(errno == EPIPE)
4840  {
4841  // broken pipe, lets reset and open again when the pipe is avail
4842  ClosePipeSession();
4843  }
4844  }
4845  }
4846 }
4847 
4848 /**
4849  * @brief Send message to reciever over PIPE
4850  */
4852 {
4853 #ifdef CREATE_PIPE_SESSION_TO_XRE
4854  if(SetupPipeSession())
4855  {
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);
4863  SendMessageOverPipe((char *)tmp.data(), sizeToSend);
4864  }
4865 #else
4866  AAMPLOG_INFO("AAMP=>XRE: %s",data);
4867 #endif
4868 }
4869 
4870 /**
4871  * @brief The helper function which perform tuning
4872  * Common tune operations used on Tune, Seek, SetRate etc
4873  */
4874 void PrivateInstanceAAMP::TuneHelper(TuneType tuneType, bool seekWhilePaused)
4875 {
4876  bool newTune;
4877  for (int i = 0; i < AAMP_TRACK_COUNT; i++)
4878  {
4879  lastUnderFlowTimeMs[i] = 0;
4880  }
4881  pthread_mutex_lock(&mFragmentCachingLock);
4882  mFragmentCachingRequired = false;
4885  pthread_mutex_unlock(&mFragmentCachingLock);
4886 
4887  if( seekWhilePaused )
4888  { // XIONE-4261 Player state not updated correctly after seek
4889  // Prevent gstreamer callbacks from placing us back into playing state by setting these gate flags before CBs are triggered
4890  // in this routine. See NotifyFirstFrameReceived(), NotifyFirstBufferProcessed(), NotifyFirstVideoFrameDisplayed()
4893  }
4894 
4895 
4896  if (tuneType == eTUNETYPE_SEEK || tuneType == eTUNETYPE_SEEKTOLIVE || tuneType == eTUNETYPE_SEEKTOEND)
4897  {
4898  mSeekOperationInProgress = true;
4899  }
4900 
4901  if (eTUNETYPE_LAST == tuneType)
4902  {
4903  tuneType = mTuneType;
4904  }
4905  else
4906  {
4907  mTuneType = tuneType;
4908  }
4909 
4910  newTune = IsNewTune();
4911 
4912  // DELIA-39530 - Get position before pipeline is teared down
4913  if (eTUNETYPE_RETUNE == tuneType)
4914  {
4916  }
4917  else
4918  {
4919  //Only trigger the clear to encrypted pipeline switch while on retune
4920  mEncryptedPeriodFound = false;
4921  mPipelineIsClear = false;
4922  AAMPLOG_INFO ("Resetting mClearPipeline & mEncryptedPeriodFound");
4923  }
4924 
4925  TeardownStream(newTune|| (eTUNETYPE_RETUNE == tuneType));
4926 
4927 #if defined(AMLOGIC)
4928  // Send new SEGMENT event only on all trickplay and trickplay -> play, not on pause -> play / seek while paused
4929  // this shouldn't impact seekplay or ADs on Peacock & LLAMA
4930  if (tuneType == eTUNETYPE_SEEK && !(mbSeeked == true || rate == 0 || (rate == 1 && pipeline_paused == true)))
4931  for (int i = 0; i < AAMP_TRACK_COUNT; i++) mbNewSegmentEvtSent[i] = false;
4932 #endif
4933 
4934  ui32CurlTrace=0;
4935 
4936  if (newTune)
4937  {
4938 
4939  // send previouse tune VideoEnd Metrics data
4940  // this is done here because events are cleared on stop and there is chance that event may not get sent
4941  // check for mEnableVideoEndEvent and call SendVideoEndEvent ,object mVideoEnd is created inside SendVideoEndEvent
4942  if(mTuneAttempts == 1) // only for first attempt, dont send event when JSPP retunes.
4943  {
4945  }
4946 
4947  mTsbRecordingId.clear();
4948  // initialize defaults
4950  culledSeconds = 0;
4951  durationSeconds = 60 * 60; // 1 hour
4952  rate = AAMP_NORMAL_PLAY_RATE;
4953  StoreLanguageList(std::set<std::string>());
4954  mTunedEventPending = true;
4955  mProfileCappedStatus = false;
4956 #ifdef USE_OPENCDM
4959  pInstance->Release();
4960 #endif
4961  AAMPLOG_INFO ("Display Resolution width:%d height:%d", mDisplayWidth, mDisplayHeight);
4962 
4963  mOrigManifestUrl.hostname = aamp_getHostFromURL(mManifestUrl);
4964  mOrigManifestUrl.isRemotehost = !(aamp_IsLocalHost(mOrigManifestUrl.hostname));
4965  AAMPLOG_TRACE("CurlTrace OrigManifest url:%s", mOrigManifestUrl.hostname.c_str());
4966  }
4967 
4968  trickStartUTCMS = -1;
4969 
4970  double playlistSeekPos = seek_pos_seconds - culledSeconds;
4971  AAMPLOG_INFO("playlistSeek : %f seek_pos_seconds:%f culledSeconds : %f ",playlistSeekPos,seek_pos_seconds,culledSeconds);
4972  if (playlistSeekPos < 0)
4973  {
4974  playlistSeekPos = 0;
4975  seek_pos_seconds = culledSeconds;
4976  AAMPLOG_WARN("Updated seek_pos_seconds %f ", seek_pos_seconds);
4977  }
4978 
4979  if (mMediaFormat == eMEDIAFORMAT_DASH)
4980  {
4981  #if defined (INTELCE)
4982  AAMPLOG_WARN("Error: Dash playback not available");
4983  mInitSuccess = false;
4985  return;
4986  #else
4987  mpStreamAbstractionAAMP = new StreamAbstractionAAMP_MPD(mLogObj,this, playlistSeekPos, rate);
4988  if (NULL == mCdaiObject)
4989  {
4990  mCdaiObject = new CDAIObjectMPD(mLogObj, this); // special version for DASH
4991  }
4992  #endif
4993  }
4994  else if (mMediaFormat == eMEDIAFORMAT_HLS || mMediaFormat == eMEDIAFORMAT_HLS_MP4)
4995  { // m3u8
4996  mpStreamAbstractionAAMP = new StreamAbstractionAAMP_HLS(mLogObj,this, playlistSeekPos, rate);
4997  if(NULL == mCdaiObject)
4998  {
4999  mCdaiObject = new CDAIObject(mLogObj, this); //Placeholder to reject the SetAlternateContents()
5000  }
5001  }
5002  else if (mMediaFormat == eMEDIAFORMAT_PROGRESSIVE)
5003  {
5004  mpStreamAbstractionAAMP = new StreamAbstractionAAMP_PROGRESSIVE(mLogObj,this, playlistSeekPos, rate);
5005  if (NULL == mCdaiObject)
5006  {
5007  mCdaiObject = new CDAIObject(mLogObj, this); //Placeholder to reject the SetAlternateContents()
5008  }
5009  // Set to false so that EOS events can be sent. Flag value was whatever previous asset had set it to.
5010  SetIsLive(false);
5011  }
5012  else if (mMediaFormat == eMEDIAFORMAT_HDMI)
5013  {
5014  mpStreamAbstractionAAMP = new StreamAbstractionAAMP_HDMIIN(mLogObj,this, playlistSeekPos, rate);
5015  if (NULL == mCdaiObject)
5016  {
5017  mCdaiObject = new CDAIObject(mLogObj, this); //Placeholder to reject the SetAlternateContents()
5018  }
5019  }
5020  else if (mMediaFormat == eMEDIAFORMAT_OTA)
5021  {
5022  mpStreamAbstractionAAMP = new StreamAbstractionAAMP_OTA(mLogObj,this, playlistSeekPos, rate);
5023  if (NULL == mCdaiObject)
5024  {
5025  mCdaiObject = new CDAIObject(mLogObj, this); //Placeholder to reject the SetAlternateContents()
5026  }
5027  }
5028 #ifdef USE_CPP_THUNDER_PLUGIN_ACCESS
5029  else if (mMediaFormat == eMEDIAFORMAT_RMF)
5030  {
5031  mpStreamAbstractionAAMP = new StreamAbstractionAAMP_RMF(mLogObj,this, playlistSeekPos, rate);
5032  if (NULL == mCdaiObject)
5033  {
5034  mCdaiObject = new CDAIObject(mLogObj, this); //Placeholder to reject the SetAlternateContents()
5035  }
5036  }
5037 #endif //USE_CPP_THUNDER_PLUGIN_ACCESS
5038  else if (mMediaFormat == eMEDIAFORMAT_COMPOSITE)
5039  {
5040  mpStreamAbstractionAAMP = new StreamAbstractionAAMP_COMPOSITEIN(mLogObj,this, playlistSeekPos, rate);
5041  if (NULL == mCdaiObject)
5042  {
5043  mCdaiObject = new CDAIObject(mLogObj, this); //Placeholder to reject the SetAlternateContents()
5044  }
5045  }
5046  else if (mMediaFormat == eMEDIAFORMAT_SMOOTHSTREAMINGMEDIA)
5047  {
5048  AAMPLOG_ERR("Error: SmoothStreamingMedia playback not supported");
5049  mInitSuccess = false;
5051  return;
5052  }
5053 
5054  mInitSuccess = true;
5055  AAMPStatusType retVal;
5057  {
5059  retVal = mpStreamAbstractionAAMP->Init(tuneType);
5060  }
5061  else
5062  {
5063  retVal = eAAMPSTATUS_GENERIC_ERROR;
5064  }
5065 
5066  // Validate tune type
5067  // (need to find a better way to do this)
5068  if (tuneType == eTUNETYPE_NEW_NORMAL) // either no offset (mIsDefaultOffset = true) or -1 was specified
5069  {
5070  if(!IsLive() && !mIsDefaultOffset)
5071  {
5072  if (mMediaFormat == eMEDIAFORMAT_DASH) //curently only supported for dash
5073  {
5074  tuneType = eTUNETYPE_NEW_END;
5075  }
5076  }
5077  }
5078  mIsDefaultOffset = false;
5079 
5080  if ((tuneType == eTUNETYPE_NEW_END) ||
5081  (tuneType == eTUNETYPE_SEEKTOEND))
5082  {
5083  if (mMediaFormat != eMEDIAFORMAT_DASH)
5084  {
5085  AAMPLOG_WARN("PrivateInstanceAAMP: tune to end not supported for format");
5086  retVal = eAAMPSTATUS_GENERIC_ERROR;
5087  }
5088  }
5089 
5090  if (retVal != eAAMPSTATUS_OK)
5091  {
5092  // Check if the seek position is beyond the duration
5093  if(retVal == eAAMPSTATUS_SEEK_RANGE_ERROR)
5094  {
5095  AAMPLOG_WARN("mpStreamAbstractionAAMP Init Failed.Seek Position(%f) out of range(%lld)",mpStreamAbstractionAAMP->GetStreamPosition(),(GetDurationMs()/1000));
5096  NotifyEOSReached();
5097  }
5098  else if(mIsFakeTune)
5099  {
5100  if(retVal == eAAMPSTATUS_FAKE_TUNE_COMPLETE)
5101  {
5102  AAMPLOG(mLogObj, eLOGLEVEL_FATAL, "FATAL", "Fake tune completed");
5103  }
5104  else
5105  {
5107  mEventManager->SendEvent(std::make_shared<AAMPEventObject>(AAMP_EVENT_EOS));
5108  AAMPLOG(mLogObj, eLOGLEVEL_FATAL, "FATAL", "Stopping fake tune playback");
5109  }
5110  }
5111  else if (DownloadsAreEnabled())
5112  {
5113  AAMPLOG_ERR("mpStreamAbstractionAAMP Init Failed.Error(%d)",retVal);
5115  switch(retVal)
5116  {
5118  failReason = AAMP_TUNE_INIT_FAILED_MANIFEST_DNLD_ERROR; break;
5126  failReason = AAMP_TUNE_INIT_FAILED_MANIFEST_PARSE_ERROR; break;
5129  failReason = AAMP_TUNE_INIT_FAILED_TRACK_SYNC_ERROR; break;
5131  failReason = AAMP_TUNE_DRM_UNSUPPORTED; break;
5132  default :
5133  break;
5134  }
5135 
5137  {
5138  long http_error = mPlaylistFetchFailError;
5139  SendDownloadErrorEvent(failReason, http_error);
5140  }
5141  else
5142  {
5143  SendErrorEvent(failReason);
5144  }
5145  }
5146  mInitSuccess = false;
5147  return;
5148  }
5149  else
5150  {
5151  // LLAMA-7124 - explicitly invalidate previous position for consistency with previous code
5152  mPrevPositionMilliseconds.Invalidate();
5153 
5154  int volume = audio_volume;
5155  double updatedSeekPosition = mpStreamAbstractionAAMP->GetStreamPosition();
5156  seek_pos_seconds = updatedSeekPosition + culledSeconds;
5157  // Adjust seek_pos_second based on adjusted stream position and discontinuity start time for absolute progress reports
5158  if(ISCONFIGSET_PRIV(eAAMPConfig_UseAbsoluteTimeline) && !ISCONFIGSET_PRIV(eAAMPConfig_MidFragmentSeek) && !IsUninterruptedTSB())
5159  {
5160  double startTimeOfDiscontinuity = mpStreamAbstractionAAMP->GetStartTimeOfFirstPTS() / 1000;
5161  if(startTimeOfDiscontinuity > 0)
5162  {
5163  seek_pos_seconds = startTimeOfDiscontinuity + updatedSeekPosition;
5164  if(!IsLive())
5165  {
5166  // For dynamic => static cases, add culled seconds
5167  // For normal VOD, culledSeconds is expected to be 0.
5168  seek_pos_seconds += culledSeconds;
5169  }
5170  AAMPLOG_WARN("Position adjusted discontinuity start: %lf, Abs position: %lf", startTimeOfDiscontinuity, seek_pos_seconds);
5171  }
5172  }
5173  culledOffset = culledSeconds;
5175 #ifndef AAMP_STOP_SINK_ON_SEEK
5176  AAMPLOG_WARN("Updated seek_pos_seconds %f culledSeconds :%f", seek_pos_seconds,culledSeconds);
5177 #endif
5178  mpStreamAbstractionAAMP->GetStreamFormat(mVideoFormat, mAudioFormat, mAuxFormat, mSubtitleFormat);
5179  AAMPLOG_INFO("TuneHelper : mVideoFormat %d, mAudioFormat %d mAuxFormat %d", mVideoFormat, mAudioFormat, mAuxFormat);
5180 
5181  //Identify if HLS with mp4 fragments, to change media format
5182  if (mVideoFormat == FORMAT_ISO_BMFF && mMediaFormat == eMEDIAFORMAT_HLS)
5183  {
5184  mMediaFormat = eMEDIAFORMAT_HLS_MP4;
5185  }
5186 
5187  // Enable fragment initial caching. Retune not supported
5188  if(tuneType != eTUNETYPE_RETUNE
5189  && GetInitialBufferDuration() > 0
5190  && rate == AAMP_NORMAL_PLAY_RATE
5192  {
5194  mFragmentCachingRequired = true;
5195  }
5196 
5197  // Set Pause on First Video frame if seeking and requested
5198  if( mSeekOperationInProgress && seekWhilePaused )
5199  {
5202  }
5203 
5204 #ifndef AAMP_STOP_SINK_ON_SEEK
5205  if (mMediaFormat == eMEDIAFORMAT_HLS)
5206  {
5207  //Live adjust or syncTrack occurred, sent an updated flush event
5208  if ((!newTune && ISCONFIGSET_PRIV(eAAMPConfig_DemuxVideoHLSTrack)) || ISCONFIGSET_PRIV(eAAMPConfig_PreservePipeline))
5209  {
5210  mStreamSink->Flush(mpStreamAbstractionAAMP->GetFirstPTS(), rate);
5211  }
5212  }
5213  else if (mMediaFormat == eMEDIAFORMAT_DASH)
5214  {
5215  /*
5216  commenting the Flush call with updatedSeekPosition as a work around for
5217  Trick play freeze issues observed for rogers cDVR content (MBTROGERS-838)
5218  @TODO Need to investigate and identify proper way to send Flush and segment
5219  events to avoid the freeze
5220  if (!(newTune || (eTUNETYPE_RETUNE == tuneType)) && !IsTSBSupported())
5221  {
5222  mStreamSink->Flush(updatedSeekPosition, rate);
5223  }
5224  else
5225  {
5226  mStreamSink->Flush(0, rate);
5227  }
5228  */
5229  mStreamSink->Flush(mpStreamAbstractionAAMP->GetFirstPTS(), rate);
5230  }
5231  else if (mMediaFormat == eMEDIAFORMAT_PROGRESSIVE)
5232  {
5233  mStreamSink->Flush(updatedSeekPosition, rate);
5234  // ff trick mode, mp4 content is single file and muted audio to avoid glitch
5235  if (rate > AAMP_NORMAL_PLAY_RATE)
5236  {
5237  volume = 0;
5238  }
5239  // reset seek_pos after updating playback start, since mp4 content provide absolute position value
5240  seek_pos_seconds = 0;
5241  }
5242 #endif
5243  if (!mbUsingExternalPlayer)
5244  {
5245  mStreamSink->SetVideoZoom(zoom_mode);
5246  mStreamSink->SetVideoMute(video_muted);
5247  mStreamSink->SetAudioVolume(volume);
5248  if (mbPlayEnabled)
5249  {
5250  mStreamSink->Configure(mVideoFormat, mAudioFormat, mAuxFormat, mSubtitleFormat, mpStreamAbstractionAAMP->GetESChangeStatus(), mpStreamAbstractionAAMP->GetAudioFwdToAuxStatus());
5251  }
5252  }
5255  if (!mbUsingExternalPlayer)
5256  {
5257  if (mbPlayEnabled)
5258  mStreamSink->Stream();
5259  }
5260  }
5261 
5262  if (tuneType == eTUNETYPE_SEEK || tuneType == eTUNETYPE_SEEKTOLIVE || tuneType == eTUNETYPE_SEEKTOEND)
5263  {
5264  mSeekOperationInProgress = false;
5265  // Pipeline is not configured if mbPlayEnabled is false, so not required
5266  if (mbPlayEnabled && seekWhilePaused == false && pipeline_paused == true)
5267  {
5268  if(!mStreamSink->Pause(true, false))
5269  {
5270  AAMPLOG_INFO("mStreamSink Pause failed");
5271  }
5272  }
5273  }
5274 
5275 #ifdef AAMP_CC_ENABLED
5276  if(!mIsFakeTune)
5277  {
5278  AAMPLOG_INFO("mCCId: %d",mCCId);
5279  // if mCCId has non zero value means it is same instance and cc release was not calle then dont get id. if zero then call getid.
5280  if(mCCId == 0 )
5281  {
5282  mCCId = AampCCManager::GetInstance()->GetId();
5283  }
5284  //restore CC if it was enabled for previous content.
5285  if(mIsInbandCC)
5287  }
5288 #endif
5289 
5290  if (tuneType == eTUNETYPE_SEEK || tuneType == eTUNETYPE_SEEKTOLIVE || tuneType == eTUNETYPE_SEEKTOEND)
5291  {
5292  if (HasSidecarData())
5293  { // has sidecar data
5295  mpStreamAbstractionAAMP->ResumeSubtitleAfterSeek(subtitles_muted, mData);
5296  }
5297 
5298  if ((mpStreamAbstractionAAMP) && (!mTextStyle.empty()))
5299  {
5300  // Restore the subtitle text style after a seek.
5301  (void)mpStreamAbstractionAAMP->SetTextStyle(mTextStyle);
5302  }
5303  }
5304 
5305  if (newTune && !mIsFakeTune)
5306  {
5307  PrivAAMPState state;
5308  GetState(state);
5309  if((state != eSTATE_ERROR) && ((mMediaFormat != eMEDIAFORMAT_OTA) || (mMediaFormat != eMEDIAFORMAT_RMF)))
5310  {
5311  /*For OTA/RMF this event will be generated from StreamAbstractionAAMP_OTA*/
5314  }
5315  }
5316 }
5317 
5318 /**
5319  * @brief Reload TSB for same URL .
5320  */
5322 {
5323  TuneType tuneType = eTUNETYPE_SEEK;
5324 
5326  mManifestUrl = mTsbSessionRequestUrl + "&reloadTSB=true";
5327  // To post player configurations to fog on 1st time tune
5328  long configPassCode = -1;
5329  if(mTSBEnabled && ISCONFIGSET_PRIV(eAAMPConfig_EnableAampConfigToFog))
5330  {
5331  configPassCode = LoadFogConfig();
5332  }
5333  if(configPassCode == 200 || configPassCode == 204 || configPassCode == 206)
5334  {
5335  mMediaFormat = GetMediaFormatType(mManifestUrl.c_str());
5336  ResumeDownloads();
5337 
5338  mIsFirstRequestToFOG = (mTSBEnabled == true);
5339 
5340  {
5341  AAMPLOG_WARN("Reloading TSB, URL: %s", mManifestUrl.c_str());
5342  }
5343  }
5344 }
5345 
5346 /**
5347  * @brief Tune API
5348  */
5349 void PrivateInstanceAAMP::Tune(const char *mainManifestUrl, bool autoPlay, const char *contentType, bool bFirstAttempt, bool bFinalAttempt,const char *pTraceID,bool audioDecoderStreamSync)
5350 {
5351  int iCacheMaxSize = 0;
5352  int maxDrmSession = 1;
5353  double tmpVar=0;
5354  int intTmpVar=0;
5355 
5356  TuneType tuneType = eTUNETYPE_NEW_NORMAL;
5357  const char *remapUrl = mConfig->GetChannelOverride(mainManifestUrl);
5358  if (remapUrl )
5359  {
5360  const char *remapLicenseUrl = NULL;
5361  mainManifestUrl = remapUrl;
5362  remapLicenseUrl = mConfig->GetChannelLicenseOverride(mainManifestUrl);
5363  if (remapLicenseUrl )
5364  {
5365  AAMPLOG_INFO("Channel License Url Override: [%s]", remapLicenseUrl);
5366  SETCONFIGVALUE_PRIV(AAMP_TUNE_SETTING,eAAMPConfig_LicenseServerUrl,std::string(remapLicenseUrl));
5367  }
5368  }
5370  mConfig->CustomSearch(mainManifestUrl,mPlayerId,mAppName);
5371 
5374 
5375  GETCONFIGVALUE_PRIV(eAAMPConfig_PlaybackOffset,seek_pos_seconds);
5389  GETCONFIGVALUE_PRIV(eAAMPConfig_HarvestConfig,mHarvestConfig);
5390  GETCONFIGVALUE_PRIV(eAAMPConfig_AuthToken,mSessionToken);
5391  GETCONFIGVALUE_PRIV(eAAMPConfig_SubTitleLanguage,mSubLanguage);
5392  GETCONFIGVALUE_PRIV(eAAMPConfig_TLSVersion,mSupportedTLSVersion);
5393  mAsyncTuneEnabled = ISCONFIGSET_PRIV(eAAMPConfig_AsyncTune);
5394  GETCONFIGVALUE_PRIV(eAAMPConfig_LivePauseBehavior,intTmpVar);
5395  mPausedBehavior = (PausedBehavior)intTmpVar;
5396  GETCONFIGVALUE_PRIV(eAAMPConfig_NetworkTimeout,tmpVar);
5397  mNetworkTimeoutMs = (long)CONVERT_SEC_TO_MS(tmpVar);
5398  GETCONFIGVALUE_PRIV(eAAMPConfig_ManifestTimeout,tmpVar);
5399  mManifestTimeoutMs = (long)CONVERT_SEC_TO_MS(tmpVar);
5400  GETCONFIGVALUE_PRIV(eAAMPConfig_PlaylistTimeout,tmpVar);
5401  mPlaylistTimeoutMs = (long)CONVERT_SEC_TO_MS(tmpVar);
5402  if(mPlaylistTimeoutMs <= 0) mPlaylistTimeoutMs = mManifestTimeoutMs;
5403  mLogTimetoTopProfile = true;
5404  // Reset mProgramDateTime to 0 , to avoid spill over to next tune if same session is
5405  // reused
5406  mProgramDateTime = 0;
5407  mMPDPeriodsInfo.clear();
5408  // Reset current audio/text track index
5411 
5412  GETCONFIGVALUE_PRIV(eAAMPConfig_SchemeIdUriDaiStream,mSchemeIdUriDai);
5413 
5414  // Set the EventManager config
5415  // TODO When faketune code is added later , push the faketune status here
5416  mEventManager->SetAsyncTuneState(mAsyncTuneEnabled);
5417  mIsFakeTune = strcasestr(mainManifestUrl, "fakeTune=true");
5418  if(mIsFakeTune)
5419  {
5422  }
5423  mEventManager->SetFakeTuneFlag(mIsFakeTune);
5424 
5425  mTSBEnabled = strcasestr(mainManifestUrl, "tsb?") && ISCONFIGSET_PRIV(eAAMPConfig_Fog);
5426  SETCONFIGVALUE_PRIV(AAMP_STREAM_SETTING, eAAMPConfig_InterruptHandling, (mTSBEnabled && strcasestr(mainManifestUrl, "networkInterruption=true")));
5427  if(!ISCONFIGSET_PRIV(eAAMPConfig_UseAbsoluteTimeline) && ISCONFIGSET_PRIV(eAAMPConfig_InterruptHandling))
5428  {
5429  AAMPLOG_INFO("Absolute timeline reporting enabled for interrupt enabled TSB stream");
5430  SETCONFIGVALUE_PRIV(AAMP_TUNE_SETTING, eAAMPConfig_UseAbsoluteTimeline, true);
5431  }
5432  if (bFirstAttempt)
5433  {
5434  // To post player configurations to fog on 1st time tune
5435  if(mTSBEnabled && ISCONFIGSET_PRIV(eAAMPConfig_EnableAampConfigToFog))
5436  {
5437  LoadFogConfig();
5438  }
5439  else
5440  {
5442  }
5443  }
5444  //temporary hack for peacock
5445  if (STARTS_WITH_IGNORE_CASE(mAppName.c_str(), "peacock"))
5446  {
5447  if(NULL == mAampCacheHandler)
5448  {
5449  mAampCacheHandler = new AampCacheHandler(mConfig->GetLoggerInstance());
5450  }
5451 #if defined(AAMP_MPD_DRM) || defined(AAMP_HLS_DRM)
5452  // read the configured max drm session
5453  GETCONFIGVALUE_PRIV(eAAMPConfig_MaxDASHDRMSessions,maxDrmSession);
5454  if(NULL == mDRMSessionManager)
5455  {
5456  mDRMSessionManager = new AampDRMSessionManager(mLogObj, maxDrmSession);
5457  }
5458 #endif
5459  }
5460 
5461  /* Reset counter in new tune */
5463 
5464  // For PreCaching of playlist , no max limit set as size will vary for each playlist length
5465  GETCONFIGVALUE_PRIV(eAAMPConfig_MaxPlaylistCacheSize,iCacheMaxSize);
5466  if(iCacheMaxSize != MAX_PLAYLIST_CACHE_SIZE)
5467  {
5468  getAampCacheHandler()->SetMaxPlaylistCacheSize(iCacheMaxSize*1024); // convert KB inputs to bytes
5469  }
5470  else if(mPreCacheDnldTimeWindow > 0)
5471  {
5472  // if precaching enabled, then set cache to infinite
5473  // support download of all the playlist files
5474  getAampCacheHandler()->SetMaxPlaylistCacheSize(PLAYLIST_CACHE_SIZE_UNLIMITED);
5475  }
5476 
5477  // Set max no of init fragment to be maintained in cache table, ByDefault 5.
5478  GETCONFIGVALUE_PRIV(eAAMPConfig_MaxInitFragCachePerTrack,iCacheMaxSize);
5479  if(iCacheMaxSize != MAX_INIT_FRAGMENT_CACHE_PER_TRACK)
5480  {
5481  getAampCacheHandler()->SetMaxInitFragCacheSize(iCacheMaxSize);
5482  }
5483 
5484  mAudioDecoderStreamSync = audioDecoderStreamSync;
5485 
5486 
5487  mMediaFormat = GetMediaFormatType(mainManifestUrl);
5488 
5489  mbUsingExternalPlayer = (mMediaFormat == eMEDIAFORMAT_OTA) || (mMediaFormat== eMEDIAFORMAT_HDMI) || (mMediaFormat==eMEDIAFORMAT_COMPOSITE) || \
5490  (mMediaFormat == eMEDIAFORMAT_RMF);
5491 
5492  if (NULL == mStreamSink)
5493  {
5494  mStreamSink = new AAMPGstPlayer(mLogObj, this);
5495  }
5496  /* Initialize gstreamer plugins with correct priority to co-exist with webkit plugins.
5497  * Initial priority of aamp plugins is PRIMARY which is less than webkit plugins.
5498  * if aamp->Tune is called, aamp plugins should be used, so set priority to a greater value
5499  * than that of that of webkit plugins*/
5500  static bool gstPluginsInitialized = false;
5501  if ((!gstPluginsInitialized) && (!mbUsingExternalPlayer))
5502  {
5503  gstPluginsInitialized = true;
5505  }
5506 
5507  mbPlayEnabled = autoPlay;
5508  mPlayerPreBuffered = !autoPlay ;
5509 
5510  ResumeDownloads();
5511 
5512  if (!autoPlay)
5513  {
5514  pipeline_paused = true;
5515  AAMPLOG_WARN("AutoPlay disabled; Just caching the stream now.");
5516  }
5517 
5519  if (mIsDefaultOffset)
5520  {
5521  // eTUNETYPE_NEW_NORMAL
5522  // default behaviour is play live streams from 'live' point and VOD streams from the start
5523  seek_pos_seconds = 0;
5524  }
5525  else if (-1 == seek_pos_seconds)
5526  {
5527  // eTUNETYPE_NEW_NORMAL
5528  // behaviour is play live streams from 'live' point and VOD streams skip to the end (this will
5529  // be corrected later for vod)
5530  seek_pos_seconds = 0;
5531  }
5532  else
5533  {
5534  AAMPLOG_WARN("PrivateInstanceAAMP: seek position already set, so eTUNETYPE_NEW_SEEK");
5535  tuneType = eTUNETYPE_NEW_SEEK;
5536  }
5537 
5538  AAMPLOG_INFO("Paused behavior : %d", mPausedBehavior);
5539 
5540  for(int i = 0; i < eCURLINSTANCE_MAX; i++)
5541  {
5542  //cookieHeaders[i].clear();
5543  httpRespHeaders[i].type = eHTTPHEADERTYPE_UNKNOWN;
5544  httpRespHeaders[i].data.clear();
5545  }
5546 
5547  //Add Custom Header via config
5548  {
5549  std::string customLicenseHeaderStr;
5550  GETCONFIGVALUE_PRIV(eAAMPConfig_CustomHeaderLicense,customLicenseHeaderStr);
5551  if(!customLicenseHeaderStr.empty())
5552  {
5553  if (ISCONFIGSET_PRIV(eAAMPConfig_CurlLicenseLogging))
5554  {
5555  AAMPLOG_WARN("CustomHeader :%s",customLicenseHeaderStr.c_str());
5556  }
5557  char* token = NULL;
5558  char* tokenHeader = NULL;
5559  char* str = (char*) customLicenseHeaderStr.c_str();
5560 
5561  while ((token = strtok_r(str, ";", &str)))
5562  {
5563  int headerTokenIndex = 0;
5564  std::string headerName;
5565  std::vector<std::string> headerValue;
5566 
5567  while ((tokenHeader = strtok_r(token, ":", &token)))
5568  {
5569  if(headerTokenIndex == 0)
5570  headerName = tokenHeader;
5571  else if(headerTokenIndex == 1)
5572  headerValue.push_back(std::string(tokenHeader));
5573  else
5574  break;
5575 
5576  headerTokenIndex++;
5577  }
5578  if(!headerName.empty() && !headerValue.empty())
5579  {
5580  AddCustomHTTPHeader(headerName, headerValue, true);
5581  }
5582  }
5583  }
5584  }
5585  /** Least priority operator setting will override the value only if it is not set from dev config **/
5586  SETCONFIGVALUE_PRIV(AAMP_TUNE_SETTING,eAAMPConfig_WideVineKIDWorkaround,IsWideVineKIDWorkaround(mainManifestUrl));
5588  if (mIsWVKIDWorkaround)
5589  {
5590  /** Set prefered DRM as Widevine with highest configuration **/
5591  AAMPLOG_INFO("WideVine KeyID workaround present: Setting preferred DRM as Widevine");
5592  SETCONFIGVALUE_PRIV(AAMP_TUNE_SETTING,eAAMPConfig_PreferredDRM,(int)eDRM_WideVine);
5593  }
5594 
5595  std::tie(mManifestUrl, mDrmInitData) = ExtractDrmInitData(mainManifestUrl);
5596 
5597  mIsVSS = (strstr(mainManifestUrl, VSS_MARKER) || strstr(mainManifestUrl, VSS_MARKER_FOG));
5598  mTuneCompleted = false;
5599  mPersistedProfileIndex = -1;
5600  mServiceZone.clear(); //clear the value if present
5601  mIsIframeTrackPresent = false;
5602  mIsTrackIdMismatch = false;
5603  mCurrentAudioTrackId = -1;
5604  mCurrentVideoTrackId = -1;
5605  mCurrentDrm = nullptr;
5606 
5607  // DELIA-47965: Calling SetContentType without checking contentType != NULL, so that
5608  // mContentType will be reset to ContentType_UNKNOWN at the start of tune by default
5609  SetContentType(contentType);
5610  if (ContentType_CDVR == mContentType)
5611  {
5612  mIscDVR = true;
5613  }
5614 
5616 
5617  UpdateLiveOffset();
5618 #ifdef AAMP_CC_ENABLED
5619  if (eMEDIAFORMAT_OTA == mMediaFormat)
5620  {
5621  if (ISCONFIGSET_PRIV(eAAMPConfig_NativeCCRendering))
5622  {
5624  }
5625  }
5626 #endif
5627 
5628  if(bFirstAttempt)
5629  {
5630  mTuneAttempts = 1; //Only the first attempt is xreInitiated.
5631  mPlayerLoadTime = NOW_STEADY_TS_MS;
5632  mLogTune = true;
5633  mFirstProgress = true;
5634  }
5635  else
5636  {
5637  mTuneAttempts++;
5638  }
5639  profiler.TuneBegin();
5640  ResetBufUnderFlowStatus();
5641 
5642  if( !remapUrl )
5643  {
5644  std::string mapMPDStr, mapM3U8Str;
5645  GETCONFIGVALUE_PRIV(eAAMPConfig_MapMPD,mapMPDStr);
5646  GETCONFIGVALUE_PRIV(eAAMPConfig_MapM3U8,mapM3U8Str);
5647  if (!mapMPDStr.empty() && mMediaFormat == eMEDIAFORMAT_HLS && (mContentType != ContentType_EAS)) //Don't map, if it is dash and dont map if it is EAS
5648  {
5649  std::string hostName = aamp_getHostFromURL(mManifestUrl);
5650  if((hostName.find(mapMPDStr) != std::string::npos) || (mTSBEnabled && mManifestUrl.find(mapMPDStr) != std::string::npos))
5651  {
5652  replace(mManifestUrl, ".m3u8", ".mpd");
5653  mMediaFormat = eMEDIAFORMAT_DASH;
5654  }
5655  }
5656  else if (!mapM3U8Str.empty() && mMediaFormat == eMEDIAFORMAT_DASH)
5657  {
5658  std::string hostName = aamp_getHostFromURL(mManifestUrl);
5659  if((hostName.find(mapM3U8Str) != std::string::npos) || (mTSBEnabled && mManifestUrl.find(mapM3U8Str) != std::string::npos))
5660  {
5661  replace(mManifestUrl, ".mpd" , ".m3u8");
5662  mMediaFormat = eMEDIAFORMAT_HLS;
5663  }
5664  }
5665  //DELIA-47890 Fog can be disable by having option fog=0 option in aamp.cfg,based on that gpGlobalConfig->noFog is updated
5666  //Removed variable gpGlobalConfig->fogSupportsDash as it has similar usage
5667  if(!ISCONFIGSET_PRIV(eAAMPConfig_Fog))
5668  {
5669  DeFog(mManifestUrl);
5670  }
5671 
5672  if (ISCONFIGSET_PRIV(eAAMPConfig_ForceEC3))
5673  {
5674  replace(mManifestUrl,".m3u8", "-eac3.m3u8");
5675  }
5676  if (ISCONFIGSET_PRIV(eAAMPConfig_DisableEC3))
5677  {
5678  replace(mManifestUrl, "-eac3.m3u8", ".m3u8");
5679  }
5680 
5681  if(ISCONFIGSET_PRIV(eAAMPConfig_ForceHttp))
5682  {
5683  replace(mManifestUrl, "https://", "http://");
5684  if(mTSBEnabled)
5685  {
5686  ForceHttpCoversionforFog(mManifestUrl,"https","http");
5687  }
5688  }
5689 
5690  if (mManifestUrl.find("mpd")!= std::string::npos) // new - limit this option to linear content as part of DELIA-23975
5691  {
5692  replace(mManifestUrl, "-eac3.mpd", ".mpd");
5693  } // mpd
5694  } // !remap_url
5695 
5696  mIsFirstRequestToFOG = (mTSBEnabled == true);
5697 
5698  {
5699  char tuneStrPrefix[64];
5700  mTsbSessionRequestUrl.clear();
5701  memset(tuneStrPrefix, '\0', sizeof(tuneStrPrefix));
5702  if (!mAppName.empty())
5703  {
5704  snprintf(tuneStrPrefix, sizeof(tuneStrPrefix), "%s PLAYER[%d] APP: %s",(mbPlayEnabled?STRFGPLAYER:STRBGPLAYER), mPlayerId, mAppName.c_str());
5705  }
5706  else
5707  {
5708  snprintf(tuneStrPrefix, sizeof(tuneStrPrefix), "%s PLAYER[%d]", (mbPlayEnabled?STRFGPLAYER:STRBGPLAYER), mPlayerId);
5709  }
5710 
5711  if(mManifestUrl.length() < MAX_URL_LOG_SIZE)
5712  {
5713  AAMPLOG_WARN("%s aamp_tune: attempt: %d format: %s URL: %s", tuneStrPrefix, mTuneAttempts, mMediaFormatName[mMediaFormat], mManifestUrl.c_str());
5714  }
5715  else
5716  {
5717  AAMPLOG_WARN("%s aamp_tune: attempt: %d format: %s URL: (BIG)", tuneStrPrefix, mTuneAttempts, mMediaFormatName[mMediaFormat]);
5718  AAMPLOG_INFO("URL: %s", mManifestUrl.c_str());
5719  }
5720  if(IsTSBSupported())
5721  {
5722  mTsbSessionRequestUrl = mManifestUrl;
5723  }
5724  }
5725 
5726  // this function uses mIsVSS and mTSBEnabled, hence it should be called after these variables are updated.
5727  ExtractServiceZone(mManifestUrl);
5728  SetTunedManifestUrl(mTSBEnabled);
5729 
5730  if(bFirstAttempt)
5731  { // TODO: make mFirstTuneFormat of type MediaFormat
5732  mfirstTuneFmt = (int)mMediaFormat;
5733  }
5734  mCdaiObject = NULL;
5736  TuneHelper(tuneType);
5737 
5738  //Apply the cached video mute call as it got invoked when stream lock was not available
5740  {
5741  mApplyCachedVideoMute = false;
5742  AAMPLOG_INFO("Cached videoMute is being executed, mute value: %d", video_muted);
5744  {
5745  //There two fns are being called in PlayerInstanceAAMP::SetVideoMute
5746  SetVideoMute(video_muted);
5747  SetCCStatus(video_muted ? false : !subtitles_muted);
5748  }
5749  }
5751 
5752  // To check and apply stored video rectangle properties
5753  if (mApplyVideoRect)
5754  {
5755  if ((mMediaFormat == eMEDIAFORMAT_OTA) || (mMediaFormat == eMEDIAFORMAT_HDMI) || (mMediaFormat == eMEDIAFORMAT_COMPOSITE) || \
5756  (mMediaFormat == eMEDIAFORMAT_RMF))
5757  {
5758  mpStreamAbstractionAAMP->SetVideoRectangle(mVideoRect.horizontalPos, mVideoRect.verticalPos, mVideoRect.width, mVideoRect.height);
5759  }
5760  else
5761  {
5762  mStreamSink->SetVideoRectangle(mVideoRect.horizontalPos, mVideoRect.verticalPos, mVideoRect.width, mVideoRect.height);
5763  }
5764  AAMPLOG_INFO("Update SetVideoRectangle x:%d y:%d w:%d h:%d", mVideoRect.horizontalPos, mVideoRect.verticalPos, mVideoRect.width, mVideoRect.height);
5765  mApplyVideoRect = false;
5766  }
5767  // do not change location of this set, it should be done after sending perviouse VideoEnd data which
5768  // is done in TuneHelper->SendVideoEndEvent function.
5769  if(pTraceID)
5770  {
5771  this->mTraceUUID = pTraceID;
5772  AAMPLOG_WARN("CMCD Session Id:%s", this->mTraceUUID.c_str());
5773  }
5774  else
5775  {
5776  this->mTraceUUID = "unknown";
5777  }
5778  //generate uuid/session id for applications which do not send id along with tune.
5779  if(ISCONFIGSET_PRIV(eAAMPConfig_EnableCMCD) && pTraceID == NULL)
5780  {
5781  uuid_t uuid;
5782  uuid_generate(uuid);
5783  char sid[MAX_SESSION_ID_LENGTH];
5784  uuid_unparse(uuid, sid);
5785  for (char *ptr = sid; *ptr; ++ptr) {
5786  *ptr = tolower(*ptr);
5787  }
5788  this->mTraceUUID = sid;
5789  AAMPLOG_WARN("CMCD Session Id generated:%s", this->mTraceUUID.c_str());
5790  }
5791 }
5792 
5793 /**
5794  * @brief Get Language preference from aamp.cfg.
5795  */
5797 {
5798  int langCodePreference;
5799  GETCONFIGVALUE_PRIV(eAAMPConfig_LanguageCodePreference,langCodePreference);
5800  return (LangCodePreference)langCodePreference;
5801 }
5802 
5803 /**
5804  * @brief Get Mediaformat types by parsing the url
5805  */
5807 {
5809  std::string urlStr(url); // for convenience, convert to std::string
5810 
5811 #ifdef TRUST_LOCATOR_EXTENSION_IF_PRESENT // disable to exersize alternate path
5812  if( urlStr.rfind("hdmiin:",0)==0 )
5813  {
5814  rc = eMEDIAFORMAT_HDMI;
5815  }
5816  else if( urlStr.rfind("cvbsin:",0)==0 )
5817  {
5819  }
5820  else if((urlStr.rfind("live:",0)==0) || (urlStr.rfind("tune:",0)==0) || (urlStr.rfind("mr:",0)==0))
5821  {
5822  rc = eMEDIAFORMAT_OTA;
5823  }
5824  else if(urlStr.rfind("ocap:",0)==0)
5825  {
5826  rc = eMEDIAFORMAT_RMF;
5827  }
5828  else if(urlStr.rfind("http://127.0.0.1", 0) == 0) // starts with localhost
5829  { // where local host is used; inspect further to determine if this locator involves FOG
5830 
5831  size_t fogUrlStart = urlStr.find("recordedUrl=", 16); // search forward, skipping 16-char http://127.0.0.1
5832 
5833  if(fogUrlStart != std::string::npos)
5834  { // definitely FOG - extension is inside recordedUrl URI parameter
5835 
5836  size_t fogUrlEnd = urlStr.find("&", fogUrlStart); // end of recordedUrl
5837 
5838  if(fogUrlEnd != std::string::npos)
5839  {
5840  if(urlStr.rfind("m3u8", fogUrlEnd) != std::string::npos)
5841  {
5842  rc = eMEDIAFORMAT_HLS;
5843  }
5844  else if(urlStr.rfind("mpd", fogUrlEnd)!=std::string::npos)
5845  {
5846  rc = eMEDIAFORMAT_DASH;
5847  }
5848 
5849  // should never get here with UNKNOWN format, but if we do, just fall through to normal locator scanning
5850  }
5851  }
5852  }
5853 
5854  if(rc == eMEDIAFORMAT_UNKNOWN)
5855  { // do 'normal' (non-FOG) locator parsing
5856 
5857  size_t extensionEnd = urlStr.find("?"); // delimited for URI parameters, or end-of-string
5858  std::size_t extensionStart = urlStr.rfind(".", extensionEnd); // scan backwards to find final "."
5859  int extensionLength;
5860 
5861  if(extensionStart != std::string::npos)
5862  { // found an extension
5863  if(extensionEnd == std::string::npos)
5864  {
5865  extensionEnd = urlStr.length();
5866  }
5867 
5868  extensionStart++; // skip past the "." - no reason to re-compare it
5869 
5870  extensionLength = (int)(extensionEnd - extensionStart); // bytes between "." and end of query delimiter/end of string
5871 
5872  if(extensionLength == 4 && urlStr.compare(extensionStart, extensionLength, "m3u8") == 0)
5873  {
5874  rc = eMEDIAFORMAT_HLS;
5875  }
5876  else if(extensionLength == 3)
5877  {
5878  if(urlStr.compare(extensionStart,extensionLength,"mpd") == 0)
5879  {
5880  rc = eMEDIAFORMAT_DASH;
5881  }
5882  else if(urlStr.compare(extensionStart,extensionLength,"mp3") == 0 || urlStr.compare(extensionStart,extensionLength,"mp4") == 0 ||
5883  urlStr.compare(extensionStart,extensionLength,"mkv") == 0)
5884  {
5886  }
5887  }
5888  else if((extensionLength == 2) || (urlStr.rfind("srt:",0)==0))
5889  {
5890  if((urlStr.compare(extensionStart,extensionLength,"ts") == 0) || (urlStr.rfind("srt:",0)==0))
5891  {
5893  }
5894  }
5895  }
5896  }
5897 #endif // TRUST_LOCATOR_EXTENSION_IF_PRESENT
5898 
5899  if(rc == eMEDIAFORMAT_UNKNOWN)
5900  {
5901  // no extension - sniff first few bytes of file to disambiguate
5902  struct GrowableBuffer sniffedBytes = {0, 0, 0};
5903  std::string effectiveUrl;
5904  long http_error;
5905  double downloadTime;
5906  long bitrate;
5907  int fogError;
5908 
5909  mOrigManifestUrl.hostname=aamp_getHostFromURL(url);
5910  mOrigManifestUrl.isRemotehost = !(aamp_IsLocalHost(mOrigManifestUrl.hostname));
5912 
5913  bool gotManifest = GetFile(url,
5914  &sniffedBytes,
5915  effectiveUrl,
5916  &http_error,
5917  &downloadTime,
5918  "0-150", // download first few bytes only
5919  // TODO: ideally could use "0-6" for range but write_callback sometimes not called before curl returns http 206
5921  false,
5923  &bitrate,
5924  &fogError,
5925  0.0);
5926 
5927  if(gotManifest)
5928  {
5929  if(sniffedBytes.len >= 7 && memcmp(sniffedBytes.ptr, "#EXTM3U8", 7) == 0)
5930  {
5931  rc = eMEDIAFORMAT_HLS;
5932  }
5933  else if((sniffedBytes.len >= 6 && memcmp(sniffedBytes.ptr, "<?xml ", 6) == 0) || // can start with xml
5934  (sniffedBytes.len >= 5 && memcmp(sniffedBytes.ptr, "<MPD ", 5) == 0)) // or directly with mpd
5935  { // note: legal to have whitespace before leading tag
5936  aamp_AppendNulTerminator(&sniffedBytes);
5937  if (strstr(sniffedBytes.ptr, "SmoothStreamingMedia"))
5938  {
5940  }
5941  else
5942  {
5943  rc = eMEDIAFORMAT_DASH;
5944  }
5945  }
5946  else
5947  {
5949  }
5950  }
5951  aamp_Free(&sniffedBytes);
5953  }
5954  return rc;
5955 }
5956 
5957 /**
5958  * @brief Check if AAMP is in stalled state after it pushed EOS to
5959  * notify discontinuity
5960  */
5962 {
5963  AAMPLOG_TRACE("Enter mediaType %d", mediaType);
5964  long discontinuityTimeoutValue;
5965  GETCONFIGVALUE_PRIV(eAAMPConfig_DiscontinuityTimeout,discontinuityTimeoutValue);
5966  if(!(mStreamSink->CheckForPTSChangeWithTimeout(discontinuityTimeoutValue)))
5967  {
5968  pthread_mutex_lock(&mLock);
5969 
5970  if (mDiscontinuityTuneOperationId != 0 || mDiscontinuityTuneOperationInProgress)
5971  {
5972  AAMPLOG_WARN("PrivateInstanceAAMP: Ignored retune!! Discontinuity handler already spawned(%d) or inprogress(%d)",
5973  mDiscontinuityTuneOperationId, mDiscontinuityTuneOperationInProgress);
5974  pthread_mutex_unlock(&mLock);
5975  return;
5976  }
5977 
5978  pthread_mutex_unlock(&mLock);
5979 
5980  AAMPLOG_INFO("No change in PTS for more than %ld ms, schedule retune!", discontinuityTimeoutValue);
5982 
5985  }
5986  AAMPLOG_TRACE("Exit mediaType %d", mediaType);
5987 }
5988 
5989 /**
5990  * @brief updates mServiceZone (service zone) member with string extracted from locator &sz URI parameter
5991  */
5993 {
5994  if(mIsVSS && !url.empty())
5995  {
5996  if(mTSBEnabled)
5997  { // extract original locator from FOG recordedUrl URI parameter
5998  DeFog(url);
5999  }
6000  size_t vssStart = url.find(VSS_MARKER);
6001  if( vssStart != std::string::npos )
6002  {
6003  vssStart += VSS_MARKER_LEN; // skip "?sz="
6004  size_t vssLen = url.find('&',vssStart);
6005  if( vssLen != std::string::npos )
6006  {
6007  vssLen -= vssStart;
6008  }
6009  mServiceZone = url.substr(vssStart, vssLen );
6010  aamp_DecodeUrlParameter(mServiceZone); // DELIA-44703
6011  }
6012  else
6013  {
6014  AAMPLOG_ERR("PrivateInstanceAAMP: ERROR: url does not have vss marker :%s ",url.c_str());
6015  }
6016  }
6017 }
6018 
6019 /**
6020  * @brief Set Content Type
6021  */
6023 {
6024  std::string strRet;
6025  switch(mContentType)
6026  {
6027  case ContentType_CDVR :
6028  {
6029  strRet = "CDVR"; //cdvr
6030  break;
6031  }
6032  case ContentType_VOD :
6033  {
6034  strRet = "VOD"; //vod
6035  break;
6036  }
6037  case ContentType_LINEAR :
6038  {
6039  strRet = "LINEAR"; //linear
6040  break;
6041  }
6042  case ContentType_IVOD :
6043  {
6044  strRet = "IVOD"; //ivod
6045  break;
6046  }
6047  case ContentType_EAS :
6048  {
6049  strRet ="EAS"; //eas
6050  break;
6051  }
6052  case ContentType_CAMERA :
6053  {
6054  strRet = "XfinityHome"; //camera
6055  break;
6056  }
6057  case ContentType_DVR :
6058  {
6059  strRet = "DVR"; //dvr
6060  break;
6061  }
6062  case ContentType_MDVR :
6063  {
6064  strRet = "MDVR" ; //mdvr
6065  break;
6066  }
6067  case ContentType_IPDVR :
6068  {
6069  strRet ="IPDVR" ; //ipdvr
6070  break;
6071  }
6072  case ContentType_PPV :
6073  {
6074  strRet = "PPV"; //ppv
6075  break;
6076  }
6077  case ContentType_OTT :
6078  {
6079  strRet = "OTT"; //ott
6080  break;
6081  }
6082  case ContentType_OTA :
6083  {
6084  strRet = "OTA"; //ota
6085  break;
6086  }
6087  case ContentType_SLE :
6088  {
6089  strRet = "SLE"; // single live event
6090  break;
6091  }
6092  default:
6093  {
6094  strRet = "Unknown";
6095  break;
6096  }
6097  }
6098 
6099  return strRet;
6100 }
6101 
6102 /**
6103  * @brief Notify about sink buffer full
6104  */
6106 {
6107  if(type != eMEDIATYPE_VIDEO)
6108  return;
6109 
6111  {
6113  if(video && video->enabled)
6114  video->OnSinkBufferFull();
6115  }
6116 }
6117 
6118 /**
6119  * @brief Set Content Type
6120  */
6122 {
6123  mContentType = ContentType_UNKNOWN; //default unknown
6124  if(NULL != cType)
6125  {
6126  mPlaybackMode = std::string(cType);
6127  if(mPlaybackMode == "CDVR")
6128  {
6129  mContentType = ContentType_CDVR; //cdvr
6130  }
6131  else if(mPlaybackMode == "VOD")
6132  {
6133  mContentType = ContentType_VOD; //vod
6134  }
6135  else if(mPlaybackMode == "LINEAR_TV")
6136  {
6137  mContentType = ContentType_LINEAR; //linear
6138  }
6139  else if(mPlaybackMode == "IVOD")
6140  {
6141  mContentType = ContentType_IVOD; //ivod
6142  }
6143  else if(mPlaybackMode == "EAS")
6144  {
6145  mContentType = ContentType_EAS; //eas
6146  }
6147  else if(mPlaybackMode == "xfinityhome")
6148  {
6149  mContentType = ContentType_CAMERA; //camera
6150  }
6151  else if(mPlaybackMode == "DVR")
6152  {
6153  mContentType = ContentType_DVR; //dvr
6154  }
6155  else if(mPlaybackMode == "MDVR")
6156  {
6157  mContentType = ContentType_MDVR; //mdvr
6158  }
6159  else if(mPlaybackMode == "IPDVR")
6160  {
6161  mContentType = ContentType_IPDVR; //ipdvr
6162  }
6163  else if(mPlaybackMode == "PPV")
6164  {
6165  mContentType = ContentType_PPV; //ppv
6166  }
6167  else if(mPlaybackMode == "OTT")
6168  {
6169  mContentType = ContentType_OTT; //ott
6170  }
6171  else if(mPlaybackMode == "OTA")
6172  {
6173  mContentType = ContentType_OTA; //ota
6174  }
6175  else if(mPlaybackMode == "HDMI_IN")
6176  {
6177  mContentType = ContentType_HDMIIN; //ota
6178  }
6179  else if(mPlaybackMode == "COMPOSITE_IN")
6180  {
6181  mContentType = ContentType_COMPOSITEIN; //ota
6182  }
6183  else if(mPlaybackMode == "SLE")
6184  {
6185  mContentType = ContentType_SLE; //single live event
6186  }
6187  }
6188 }
6189 
6190 /**
6191  * @brief Get Content Type
6192  */
6194 {
6195  return mContentType;
6196 }
6197 
6198 /**
6199  * @brief Extract DRM init data from the provided URL
6200  * If present, the init data will be removed from the returned URL
6201  * and provided as a separate string
6202  * @return tuple containing the modified URL and DRM init data
6203  */
6204 const std::tuple<std::string, std::string> PrivateInstanceAAMP::ExtractDrmInitData(const char *url)
6205 {
6206  std::string urlStr(url);
6207  std::string drmInitDataStr;
6208 
6209  const size_t queryPos = urlStr.find("?");
6210  std::string modUrl;
6211  if (queryPos != std::string::npos)
6212  {
6213  // URL contains a query string. Strip off & decode the drmInitData (if present)
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, '&'))
6219  { // with each URI parameter
6220  if (parameter.rfind(parameterDefinition, 0) == 0)
6221  { // found drmInitData URI parameter
6222  drmInitDataStr = parameter.substr(parameterDefinition.length());
6223  aamp_DecodeUrlParameter( drmInitDataStr );
6224  }
6225  else
6226  { // filter out drmInitData; reintroduce all other URI parameters
6227  modUrl.append((queryPos == modUrl.length()) ? "?" : "&");
6228  modUrl.append(parameter);
6229  }
6230  }
6231  urlStr = modUrl;
6232  }
6233  return std::tuple<std::string, std::string>(urlStr, drmInitDataStr);
6234 }
6235 
6236 /**
6237  * @brief Check if autoplay enabled for current stream
6238  */
6240 {
6241  return mbPlayEnabled;
6242 }
6243 
6244 /**
6245  * @brief Soft stop the player instance.
6246  *
6247  */
6249 {
6250  if(mpStreamAbstractionAAMP && mbPlayEnabled) //Player is running
6251  {
6252  pipeline_paused = true;
6254  AAMPLOG_WARN("Player %s=>%s and soft release.Detach at position %f", STRFGPLAYER, STRBGPLAYER,seek_pos_seconds );
6255  DisableDownloads(); //disable download
6258 #ifdef AAMP_CC_ENABLED
6259  // Stop CC when pipeline is stopped
6260  if (ISCONFIGSET_PRIV(eAAMPConfig_NativeCCRendering))
6261  {
6263  mCCId = 0;
6264  }
6265 #endif
6266  mStreamSink->Stop(true);
6267  mbPlayEnabled = false;
6268  mbDetached=true;
6269  mPlayerPreBuffered = false;
6270  //EnableDownloads();// enable downloads
6271  }
6272 }
6273 
6274 /**
6275  * @brief Get AampCacheHandler instance
6276  */
6278 {
6279  return mAampCacheHandler;
6280 }
6281 
6282 /**
6283  * @brief Get maximum bitrate value.
6284  */
6286 {
6287  long lMaxBitrate;
6288  GETCONFIGVALUE_PRIV(eAAMPConfig_MaxBitrate,lMaxBitrate);
6289  return lMaxBitrate;
6290 }
6291 
6292 /**
6293  * @brief Get minimum bitrate value.
6294  */
6296 {
6297  long lMinBitrate;
6298  GETCONFIGVALUE_PRIV(eAAMPConfig_MinBitrate,lMinBitrate);
6299  return lMinBitrate;
6300 }
6301 
6302 /**
6303  * @brief Get default bitrate value.
6304  */
6306 {
6307  long defaultBitRate;
6308  GETCONFIGVALUE_PRIV(eAAMPConfig_DefaultBitrate,defaultBitRate);
6309  return defaultBitRate;
6310 }
6311 
6312 /**
6313  * @brief Get Default bitrate for 4K
6314  */
6316 {
6317  long defaultBitRate;
6318  GETCONFIGVALUE_PRIV(eAAMPConfig_DefaultBitrate4K,defaultBitRate);
6319  return defaultBitRate;
6320 }
6321 
6322 /**
6323  * @brief Get Default Iframe bitrate value.
6324  */
6326 {
6327  long defaultIframeBitRate;
6328  GETCONFIGVALUE_PRIV(eAAMPConfig_IFrameDefaultBitrate,defaultIframeBitRate);
6329  return defaultIframeBitRate;
6330 }
6331 
6332 /**
6333  * @brief Get Default Iframe bitrate 4K value.
6334  */
6336 {
6337  long defaultIframeBitRate4K;
6338  GETCONFIGVALUE_PRIV(eAAMPConfig_IFrameDefaultBitrate4K,defaultIframeBitRate4K);
6339  return defaultIframeBitRate4K;
6340 }
6341 
6342 /**
6343  * @brief Fetch a file from CDN and update profiler
6344  */
6345 char *PrivateInstanceAAMP::LoadFragment(ProfilerBucketType bucketType, std::string fragmentUrl, std::string& effectiveUrl, size_t *len, unsigned int curlInstance, const char *range, long * http_code, double *downloadTime, MediaType fileType,int * fogError)
6346 {
6347  profiler.ProfileBegin(bucketType);
6348  struct GrowableBuffer fragment = { 0, 0, 0 }; // TODO: leaks if thread killed
6349  if (!GetFile(fragmentUrl, &fragment, effectiveUrl, http_code, downloadTime, range, curlInstance, true, fileType,NULL,fogError))
6350  {
6351  profiler.ProfileError(bucketType, *http_code);
6352  profiler.ProfileEnd(bucketType);
6353  }
6354  else
6355  {
6356  profiler.ProfileEnd(bucketType);
6357  }
6358  *len = fragment.len;
6359  return fragment.ptr;
6360 }
6361 
6362 /**
6363  * @brief Fetch a file from CDN and update profiler
6364  */
6365 bool PrivateInstanceAAMP::LoadFragment(CMCDHeaders *pCMCDMetrics,ProfilerBucketType bucketType, std::string fragmentUrl,std::string& effectiveUrl, struct GrowableBuffer *fragment,
6366  unsigned int curlInstance, const char *range, MediaType fileType,long * http_code, double *downloadTime, long *bitrate,int * fogError, double fragmentDurationSeconds)
6367 {
6368  bool ret = true;
6369  profiler.ProfileBegin(bucketType);
6370  if (!GetFile(fragmentUrl, fragment, effectiveUrl, http_code, downloadTime, range, curlInstance, false,fileType, bitrate, NULL, fragmentDurationSeconds,pCMCDMetrics))
6371  {
6372  ret = false;
6373  profiler.ProfileError(bucketType, *http_code);
6374  profiler.ProfileEnd(bucketType);
6375  }
6376  else
6377  {
6378  profiler.ProfileEnd(bucketType);
6379  }
6380  return ret;
6381 }
6382 
6383 /**
6384  * @brief Push fragment to the gstreamer
6385  */
6386 void PrivateInstanceAAMP::PushFragment(MediaType mediaType, char *ptr, size_t len, double fragmentTime, double fragmentDuration)
6387 {
6388  BlockUntilGstreamerWantsData(NULL, 0, 0);
6389  SyncBegin();
6390  mStreamSink->SendCopy(mediaType, ptr, len, fragmentTime, fragmentTime, fragmentDuration);
6391  SyncEnd();
6392 }
6393 
6394 /**
6395  * @brief Push fragment to the gstreamer
6396  */
6397 void PrivateInstanceAAMP::PushFragment(MediaType mediaType, GrowableBuffer* buffer, double fragmentTime, double fragmentDuration)
6398 {
6399  BlockUntilGstreamerWantsData(NULL, 0, 0);
6400  SyncBegin();
6401  if( mStreamSink->SendTransfer(mediaType, buffer->ptr, buffer->len, fragmentTime, fragmentTime, fragmentDuration) )
6402  {
6403  aamp_TransferMemory(buffer->ptr);
6404  }
6405  else
6406  { // unable to transfer - free up the buffer we were passed.
6407  aamp_Free(buffer);
6408  }
6409  memset(buffer, 0x00, sizeof(GrowableBuffer));
6410  SyncEnd();
6411 }
6412 
6413 /**
6414  * @brief End of stream reached
6415  */
6417 {
6418  if (mediaType != eMEDIATYPE_SUBTITLE)
6419  {
6420  SyncBegin();
6421  mStreamSink->EndOfStreamReached(mediaType);
6422  SyncEnd();
6423 
6424  // If EOS during Buffering, set Playing and let buffer to dry out
6425  // Sink is already unpaused by EndOfStreamReached()
6426  pthread_mutex_lock(&mFragmentCachingLock);
6427  mFragmentCachingRequired = false;
6428  PrivAAMPState state;
6429  GetState(state);
6430  if(state == eSTATE_BUFFERING)
6431  {
6433  {
6435  }
6437  }
6438  pthread_mutex_unlock(&mFragmentCachingLock);
6439  }
6440 }
6441 
6442 /**
6443  * @brief Get seek base position
6444  */
6446 {
6447  return seek_pos_seconds;
6448 }
6449 
6450 /**
6451  * @brief Get current drm
6452  */
6453 std::shared_ptr<AampDrmHelper> PrivateInstanceAAMP::GetCurrentDRM(void)
6454 {
6455  return mCurrentDrm;
6456 }
6457 
6458 /**
6459  * @brief Get available thumbnail tracks.
6460  */
6462 {
6463  std::string op;
6466  {
6467  AAMPLOG_TRACE("Entering PrivateInstanceAAMP");
6468  std::vector<StreamInfo*> data = mpStreamAbstractionAAMP->GetAvailableThumbnailTracks();
6469  cJSON *root;
6470  cJSON *item;
6471  if(!data.empty())
6472  {
6473  root = cJSON_CreateArray();
6474  if(root)
6475  {
6476  for( int i = 0; i < data.size(); i++)
6477  {
6478  cJSON_AddItemToArray(root, item = cJSON_CreateObject());
6479  if(data[i]->bandwidthBitsPerSecond >= 0)
6480  {
6481  char buf[32];
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);
6485  }
6486  }
6487  char *jsonStr = cJSON_Print(root);
6488  if (jsonStr)
6489  {
6490  op.assign(jsonStr);
6491  free(jsonStr);
6492  }
6493  cJSON_Delete(root);
6494  }
6495  }
6496  AAMPLOG_TRACE("In PrivateInstanceAAMP::Json string:%s",op.c_str());
6497  }
6499  return op;
6500 }
6501 
6502 /**
6503  * @brief Get the Thumbnail Tile data.
6504  */
6505 std::string PrivateInstanceAAMP::GetThumbnails(double tStart, double tEnd)
6506 {
6507  std::string rc;
6510  {
6511  std::string baseurl;
6512  int raw_w, raw_h, width, height;
6513  std::vector<ThumbnailData> datavec = mpStreamAbstractionAAMP->GetThumbnailRangeData(tStart, tEnd, &baseurl, &raw_w, &raw_h, &width, &height);
6514  if( !datavec.empty() )
6515  {
6516  cJSON *root = cJSON_CreateObject();
6517  if(!baseurl.empty())
6518  {
6519  cJSON_AddStringToObject(root,"baseUrl",baseurl.c_str());
6520  }
6521  if(raw_w > 0)
6522  {
6523  cJSON_AddNumberToObject(root,"raw_w",raw_w);
6524  }
6525  if(raw_h > 0)
6526  {
6527  cJSON_AddNumberToObject(root,"raw_h",raw_h);
6528  }
6529  cJSON_AddNumberToObject(root,"width",width);
6530  cJSON_AddNumberToObject(root,"height",height);
6531 
6532  cJSON *tile = cJSON_AddArrayToObject(root,"tile");
6533  for( const ThumbnailData &iter : datavec )
6534  {
6535  cJSON *item;
6536  cJSON_AddItemToArray(tile, item = cJSON_CreateObject() );
6537  if(!iter.url.empty())
6538  {
6539  cJSON_AddStringToObject(item,"url",iter.url.c_str());
6540  }
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);
6545  }
6546  char *jsonStr = cJSON_Print(root);
6547  if( jsonStr )
6548  {
6549  rc.assign( jsonStr );
6550  }
6551  cJSON_Delete(root);
6552  }
6553  }
6555  return rc;
6556 }
6557 
6558 
6559 TunedEventConfig PrivateInstanceAAMP::GetTuneEventConfig(bool isLive)
6560 {
6561  int tunedEventConfig;
6562  GETCONFIGVALUE_PRIV(eAAMPConfig_TuneEventConfig,tunedEventConfig);
6563  return (TunedEventConfig)tunedEventConfig;
6564 }
6565 
6566 /**
6567  * @brief to update the preferredaudio codec, rendition and languages list
6568  */
6570 {
6571  if(!preferredRenditionString.empty())
6572  {
6573  preferredRenditionList.clear();
6574  std::istringstream ss(preferredRenditionString);
6575  std::string rendition;
6576  while(std::getline(ss, rendition, ','))
6577  {
6578  preferredRenditionList.push_back(rendition);
6579  AAMPLOG_INFO("Parsed preferred rendition: %s",rendition.c_str());
6580  }
6581  AAMPLOG_INFO("Number of preferred Renditions: %lu",
6582  preferredRenditionList.size());
6583  }
6584 
6585  if(!preferredCodecString.empty())
6586  {
6587  preferredCodecList.clear();
6588  std::istringstream ss(preferredCodecString);
6589  std::string codec;
6590  while(std::getline(ss, codec, ','))
6591  {
6592  preferredCodecList.push_back(codec);
6593  AAMPLOG_INFO("Parsed preferred codec: %s",codec.c_str());
6594  }
6595  AAMPLOG_INFO("Number of preferred codec: %lu",
6596  preferredCodecList.size());
6597  }
6598 
6599  if(!preferredLanguagesString.empty())
6600  {
6601  preferredLanguagesList.clear();
6602  std::istringstream ss(preferredLanguagesString);
6603  std::string lng;
6604  while(std::getline(ss, lng, ','))
6605  {
6606  preferredLanguagesList.push_back(lng);
6607  AAMPLOG_INFO("Parsed preferred lang: %s",lng.c_str());
6608  }
6609  AAMPLOG_INFO("Number of preferred languages: %lu",
6610  preferredLanguagesList.size());
6611  }
6612  if(!preferredLabelsString.empty())
6613  {
6614  preferredLabelList.clear();
6615  std::istringstream ss(preferredLabelsString);
6616  std::string lng;
6617  while(std::getline(ss, lng, ','))
6618  {
6619  preferredLabelList.push_back(lng);
6620  AAMPLOG_INFO("Parsed preferred Label: %s",lng.c_str());
6621  }
6622  AAMPLOG_INFO("Number of preferred Labels: %lu", preferredLabelList.size());
6623  }
6624 
6625 
6626 }
6627 
6628 /**
6629  * @brief Set async tune configuration for EventPriority
6630  */
6632 {
6633  if(bValue)
6634  {
6636  }
6637  else
6638  {
6639  mEventPriority = G_PRIORITY_DEFAULT_IDLE;
6640  }
6641 }
6642 
6643 /**
6644  * @brief Get async tune configuration
6645  */
6647 {
6648  return mAsyncTuneEnabled;
6649 }
6650 
6651 /**
6652  * @brief Set video rectangle
6653  */
6654 void PrivateInstanceAAMP::UpdateVideoRectangle (int x, int y, int w, int h)
6655 {
6656  mVideoRect.horizontalPos = x;
6657  mVideoRect.verticalPos = y;
6658  mVideoRect.width = w;
6659  mVideoRect.height = h;
6660  mApplyVideoRect = true;
6661  AAMPLOG_INFO("Backup VideoRectangle x:%d y:%d w:%d h:%d", x, y, w, h);
6662 }
6663 
6664 /**
6665  * @brief Set video rectangle
6666  */
6667 void PrivateInstanceAAMP::SetVideoRectangle(int x, int y, int w, int h)
6668 {
6669  pthread_mutex_lock(&mStreamLock);
6670  PrivAAMPState state;
6671  GetState(state);
6672 
6673  //Differenciate IP vs non IP playback
6674  bool isNonIPPlayback = (mMediaFormat == eMEDIAFORMAT_OTA) || (mMediaFormat == eMEDIAFORMAT_HDMI) || (mMediaFormat == eMEDIAFORMAT_COMPOSITE) || (mMediaFormat == eMEDIAFORMAT_RMF);
6675 
6676  // for ATSC eSTATE_PREPARED is sent when tune is successful, as Closed caption data wont be available till tune and stream check for CC is done,
6677  // for IP eSTATE_PREPARED is done after manifest parsing,
6678  // Incase of ATSC or HDMI SetVideoRectangle should be called after StreamAbstractionAAMP_OTA::Start or StreamAbstractionAAMP_VIDEOIN::StartHelper which is called tune function after
6679  // mpStreamAbstractionAAMP object is created, hence if mpStreamAbstractionAAMP is NULL then we should not call SetVideoRectangle and defer it, this happes when SetVideoRectangle called after load.
6680  // for IP SetVideoRectangle should be called after mStreamSink created i.e > eSTATE_PREPARING
6681  // hence in below "state" condition state check is done only for IP
6682 
6683  if (mpStreamAbstractionAAMP && (isNonIPPlayback || state > eSTATE_PREPARING))
6684  {
6685  if (isNonIPPlayback)
6686  {
6688  }
6689  else
6690  {
6691  mStreamSink->SetVideoRectangle(x, y, w, h);
6692  }
6693  }
6694  else
6695  {
6696  AAMPLOG_INFO("mpStreamAbstractionAAMP is not Ready, Backup video rect values, current player state: %d", state);
6697  UpdateVideoRectangle (x, y, w, h);
6698  }
6699  pthread_mutex_unlock(&mStreamLock);
6700 }
6701 /**
6702  * @brief Set video zoom.
6703  */
6705 {
6706  mStreamSink->SetVideoZoom(zoom);
6707 }
6708 
6709 /**
6710  * @brief Enable/ Disable Video.
6711  */
6713 {
6714  mStreamSink->SetVideoMute(muted);
6715 }
6716 
6717 /**
6718  * @brief Enable/ Disable Subtitles.
6719  *
6720  * @param muted - true to disable subtitles, false to enable subtitles.
6721  */
6723 {
6724  mStreamSink->SetSubtitleMute(muted);
6725 }
6726 
6727 /**
6728  * @brief Set Audio Volume.
6729  *
6730  * @param volume - Minimum 0, maximum 100.
6731  */
6733 {
6734  mStreamSink->SetAudioVolume(volume);
6735 }
6736 
6737 /**
6738  * @brief abort ongoing downloads and returns error on future downloads
6739  * called while stopping fragment collector thread
6740  */
6742 {
6743  pthread_mutex_lock(&mLock);
6744  mDownloadsEnabled = false;
6745  pthread_cond_broadcast(&mDownloadsDisabled);
6746  pthread_mutex_unlock(&mLock);
6747 }
6748 
6749 /**
6750  * @brief Check if track can inject data into GStreamer.
6751  */
6753 {
6754  return mDownloadsEnabled; // needs mutex protection?
6755 }
6756 
6757 /**
6758  * @brief Enable downloads after aamp_DisableDownloads.
6759  * Called after stopping fragment collector thread
6760  */
6762 {
6763  pthread_mutex_lock(&mLock);
6764  mDownloadsEnabled = true;
6765  pthread_mutex_unlock(&mLock);
6766 }
6767 
6768 /**
6769  * @brief Sleep until timeout is reached or interrupted
6770  */
6772 {
6773  if (timeInMs > 0)
6774  {
6775  struct timespec ts;
6776  int ret;
6777  ts = aamp_GetTimespec(timeInMs);
6778  pthread_mutex_lock(&mLock);
6779  if (mDownloadsEnabled)
6780  {
6781  ret = pthread_cond_timedwait(&mDownloadsDisabled, &mLock, &ts);
6782  if (0 == ret)
6783  {
6784  //AAMPLOG_WARN("sleep interrupted!");
6785  }
6786  else if (ETIMEDOUT != ret)
6787  {
6788  AAMPLOG_WARN("sleep - condition wait failed %s", strerror(ret));
6789  }
6790  }
6791  pthread_mutex_unlock(&mLock);
6792  }
6793 }
6794 
6795 /**
6796  * @brief Get asset duration in milliseconds
6797  */
6799 {
6800  if (mMediaFormat == eMEDIAFORMAT_PROGRESSIVE)
6801  {
6802  long long ms = mStreamSink->GetDurationMilliseconds();
6803  durationSeconds = ms/1000.0;
6804  return ms;
6805  }
6806  else
6807  {
6808  return (long long)(durationSeconds*1000.0);
6809  }
6810 }
6811 
6812 /**
6813  * @brief Get asset duration in milliseconds
6814  * For VIDEO TAG Based playback, mainly when
6815  * aamp is used as plugin
6816  */
6818 {
6819  if (mMediaFormat == eMEDIAFORMAT_PROGRESSIVE)
6820  {
6821  long long ms = mStreamSink->GetDurationMilliseconds();
6822  durationSeconds = ms/1000.0;
6823  return ms;
6824  }
6825  else
6826  {
6827  if( mIsLive )
6828  {
6829  long long ms = (culledSeconds * 1000.0) + (durationSeconds * 1000.0);
6830  return ms;
6831  }
6832  else
6833  {
6834  return (long long)(durationSeconds*1000.0);
6835  }
6836  }
6837 }
6838 
6839 /**
6840  * @brief Get current stream position
6841  */
6843 {
6844  const auto prevPositionInfo = mPrevPositionMilliseconds.GetInfo();
6845  double seek_pos_seconds_copy = seek_pos_seconds;
6846  if(prevPositionInfo.isPositionValid(seek_pos_seconds_copy))
6847  {
6848  return prevPositionInfo.getPosition();
6849  }
6850  else
6851  {
6852  if(prevPositionInfo.isPopulated())
6853  {
6854  //Since LLAMA-7124 previous position values calculated using different values of seek_pos_seconds are considered invalid.
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());
6856  }
6857  return GetPositionMilliseconds();
6858  }
6859 }
6860 
6862 {
6863  std::lock_guard<std::mutex> functionLock{mGetPositionMillisecondsMutexHard};
6864  if(!mGetPositionMillisecondsMutexSoft.try_lock())
6865  {
6866  //In situations that could have deadlocked, continue & make a log entry instead.
6867  AAMPLOG_ERR("Failed to acquire lock.");
6868  return false;
6869  }
6870  return true;
6871 }
6872 
6874 {
6875  std::lock_guard<std::mutex> functionLock{mGetPositionMillisecondsMutexHard};
6876 
6877  //Avoid the posibility of unlocking an unlocked mutex (undefined behaviour).
6878  if(mGetPositionMillisecondsMutexSoft.try_lock())
6879  {
6880  AAMPLOG_WARN("Acquire lock (unexpected condition unless a previous lock has failed or there is a missing call to LockGetPositionMilliseconds()).");
6881  }
6882  mGetPositionMillisecondsMutexSoft.unlock();
6883 }
6884 
6885 /**
6886  * @brief Get current stream playback position in milliseconds
6887  */
6889 {
6890  /* LLAMA-7124
6891  * Ideally between LockGetPositionMilliseconds() & UnlockGetPositionMilliseconds() this function would be blocked
6892  * (i.e. all mGetPositionMillisecondsMutexSoft.try_lock() replaced with lock()) this would
6893  * ensure mState & seek_pos_seconds are syncronised during this function.
6894  * however it is difficult to be certain that this would not result in a deadlock.
6895  * Instead raise an error and potentially return a spurious position in cases that could have deadlocked.
6896  */
6897  std::lock_guard<std::mutex> functionLock{mGetPositionMillisecondsMutexHard};
6898  bool locked = mGetPositionMillisecondsMutexSoft.try_lock();
6899  if(!locked)
6900  {
6901  AAMPLOG_ERR("Failed to acquire lock. A spurious position value may be calculated.");
6902  }
6903 
6904  //LLAMA-7124 - Local copy to avoid race. LLAMA-8500 will consider further improvements to the thread safety of this variable.
6905  double seek_pos_seconds_copy = seek_pos_seconds;
6906  long long positionMiliseconds = seek_pos_seconds_copy != -1 ? seek_pos_seconds_copy * 1000.0 : 0.0;
6907 
6908  //LLAMA-7124 - Local copy to avoid race. LLAMA-8500 will consider further improvements to the thread safety of this variable.
6909  auto trickStartUTCMS_copy = trickStartUTCMS;
6910  AAMPLOG_TRACE("trickStartUTCMS=%lld", trickStartUTCMS_copy);
6911  if (trickStartUTCMS_copy >= 0)
6912  {
6913  //LLAMA-7124 - Local copy to avoid race. LLAMA-8500 will consider further improvements to the thread safety of this variable.
6914  auto rate_copy = rate;
6915  AAMPLOG_TRACE("rate=%f", rate_copy);
6916 
6917  //DELIA-39530 - Audio only playback is un-tested. Hence disabled for now
6918  if (ISCONFIGSET_PRIV(eAAMPConfig_EnableGstPositionQuery) && !ISCONFIGSET_PRIV(eAAMPConfig_AudioOnlyPlayback) && !mAudioOnlyPb)
6919  {
6920  auto gstPosition = mStreamSink->GetPositionMilliseconds();
6921 
6922  /* LLAMA-7124 - Prevent spurious values being returned by this function during seek.
6923  * This fix is similar to LLAMA-8369 but applied at this lower level because
6924  * PrivateInstanceAAMP::GetPositionMilliseconds() is called elsewhere e.g. setting seek_pos_seconds
6925  * note for this to work correctly mState and seek_pos_seconds must updated atomically othewise
6926  * spuriously low (mState = eSTATE_SEEKING before seek_pos_seconds updated) or
6927  * spuriously high (seek_pos_seconds updated before mState = eSTATE_SEEKING) values could result.
6928  */
6929  if(mState == eSTATE_SEEKING)
6930  {
6931  if(gstPosition!=0)
6932  {
6933  AAMPLOG_WARN("Ignoring gst position of %ldms and using seek_pos_seconds only until seek completes.", gstPosition);
6934  }
6935  }
6936  else
6937  {
6938  positionMiliseconds += gstPosition;
6939  }
6940  }
6941  else
6942  {
6943  long long elapsedTime = aamp_GetCurrentTimeMS() - trickStartUTCMS_copy;
6944  positionMiliseconds += (((elapsedTime > 1000) ? elapsedTime : 0) * rate_copy);
6945  }
6946  if(AAMP_NORMAL_PLAY_RATE == rate_copy)
6947  {
6948  /*LLAMA-7124 - Standardised & tightened validity checking of previous position to
6949  avoid spurious 'restore prev-pos as current-pos!!' around seeks*/
6950  const auto prevPositionInfo = mPrevPositionMilliseconds.GetInfo();
6951  if(prevPositionInfo.isPositionValid(seek_pos_seconds_copy))
6952  {
6953  long long diff = positionMiliseconds - prevPositionInfo.getPosition();
6954 
6955  if ((diff > MAX_DIFF_BETWEEN_PTS_POS_MS) || (diff < 0))
6956  {
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();
6959  }
6960  }
6961  else if(prevPositionInfo.isPopulated())
6962  {
6963  //Since LLAMA-7124 previous position values calculated using different values of seek_pos_seconds are considered invalid.
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());
6965  }
6966  }
6967 
6968  if (positionMiliseconds < 0)
6969  {
6970  AAMPLOG_WARN("Correcting positionMiliseconds %lld to zero", positionMiliseconds);
6971  positionMiliseconds = 0;
6972  }
6973  else
6974  {
6975  if (!mIsLiveStream)
6976  {
6977  long long durationMs = GetDurationMs();
6978  if(positionMiliseconds > durationMs)
6979  {
6980  AAMPLOG_WARN("Correcting positionMiliseconds %lld to duration %lld", positionMiliseconds, durationMs);
6981  positionMiliseconds = durationMs;
6982  }
6983  }
6984  else
6985  {
6986  long long tsbEndMs = GetDurationMs() + (culledSeconds * 1000.0);
6987  if(positionMiliseconds > tsbEndMs)
6988  {
6989  AAMPLOG_WARN("Correcting positionMiliseconds %lld to tsbEndMs %lld", positionMiliseconds, tsbEndMs);
6990  positionMiliseconds = tsbEndMs;
6991  }
6992  }
6993  }
6994  }
6995 
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);
6998 
6999  if(locked)
7000  {
7001  mGetPositionMillisecondsMutexSoft.unlock();
7002  }
7003 
7004  return positionMiliseconds;
7005 }
7006 
7007 /**
7008  * @brief API to send audio/video stream into the sink.
7009  */
7010 void PrivateInstanceAAMP::SendStreamCopy(MediaType mediaType, const void *ptr, size_t len, double fpts, double fdts, double fDuration)
7011 {
7012  mStreamSink->SendCopy(mediaType, ptr, len, fpts, fdts, fDuration);
7013 }
7014 
7015 /**
7016  * @brief API to send audio/video stream into the sink.
7017  */
7018 void PrivateInstanceAAMP::SendStreamTransfer(MediaType mediaType, GrowableBuffer* buffer, double fpts, double fdts, double fDuration, bool initFragment)
7019 {
7020  if( mStreamSink->SendTransfer(mediaType, buffer->ptr, buffer->len, fpts, fdts, fDuration, initFragment) )
7021  {
7022  aamp_TransferMemory(buffer->ptr);
7023  }
7024  else
7025  { // unable to transfer - free up the buffer we were passed.
7026  aamp_Free(buffer);
7027  }
7028  memset(buffer, 0x00, sizeof(GrowableBuffer));
7029 }
7030 
7031 /**
7032  * @brief Setting the stream sink
7033  */
7035 {
7036  mStreamSink = streamSink;
7037 }
7038 
7039 /**
7040  * @brief Checking if the stream is live or not
7041  */
7043 {
7044  return mIsLive;
7045 }
7046 
7047 /**
7048  * @brief Check if audio playcontext creation skipped for Demuxed HLS file.
7049  * @retval true if playcontext creation skipped, false if not.
7050  */
7052 {
7053  return mIsAudioContextSkipped;
7054 }
7055 
7056 /**
7057  * @brief Check if stream is live
7058  */
7060 {
7061  return mIsLiveStream;
7062 }
7063 
7064 /**
7065  * @brief Stop playback and release resources.
7066  *
7067  */
7069 {
7070  // Clear all the player events in the queue and sets its state to RELEASED as everything is done
7073 
7074  pthread_mutex_lock(&gMutex);
7075  auto iter = std::find_if(std::begin(gActivePrivAAMPs), std::end(gActivePrivAAMPs), [this](const gActivePrivAAMP_t& el)
7076  {
7077  return el.pAAMP == this;
7078  });
7079 
7080  if(iter != gActivePrivAAMPs.end())
7081  {
7082  if (iter->reTune && mIsRetuneInProgress)
7083  {
7084  // Wait for any ongoing re-tune operation to complete
7085  pthread_cond_wait(&gCond, &gMutex);
7086  }
7087  iter->reTune = false;
7088  }
7089  pthread_mutex_unlock(&gMutex);
7090 
7091  if (mAutoResumeTaskPending)
7092  {
7094  mAutoResumeTaskId = AAMP_TASK_ID_INVALID;
7095  mAutoResumeTaskPending = false;
7096  }
7097 
7098  DisableDownloads();
7100 
7101  // Stopping the playback, release all DRM context
7103  {
7104 #if defined(AAMP_MPD_DRM) || defined(AAMP_HLS_DRM)
7105  if (mDRMSessionManager)
7106  {
7107  mDRMSessionManager->setLicenseRequestAbort(true);
7108  }
7109 #endif
7111  if (HasSidecarData())
7112  { // has sidecar data
7114  }
7115  //Deleting mpStreamAbstractionAAMP here will prevent the extra stop call in TeardownStream()
7116  //and will avoid enableDownlaod() call being made unnecessarily
7117  SAFE_DELETE(mpStreamAbstractionAAMP);
7118  }
7119 
7120  TeardownStream(true);
7121 
7122  for(int i=0; i<eMEDIATYPE_DEFAULT; i++)
7123  {
7125  }
7126  pthread_mutex_lock(&mEventLock);
7127  if (mPendingAsyncEvents.size() > 0)
7128  {
7129  AAMPLOG_WARN("PrivateInstanceAAMP: mPendingAsyncEvents.size - %lu", mPendingAsyncEvents.size());
7130  for (std::map<guint, bool>::iterator it = mPendingAsyncEvents.begin(); it != mPendingAsyncEvents.end(); it++)
7131  {
7132  if (it->first != 0)
7133  {
7134  if (it->second)
7135  {
7136  AAMPLOG_WARN("PrivateInstanceAAMP: remove id - %d", (int) it->first);
7137  g_source_remove(it->first);
7138  }
7139  else
7140  {
7141  AAMPLOG_WARN("PrivateInstanceAAMP: Not removing id - %d as not pending", (int) it->first);
7142  }
7143  }
7144  }
7145  mPendingAsyncEvents.clear();
7146  }
7147  pthread_mutex_unlock(&mEventLock);
7148 
7149  // Streamer threads are stopped when we reach here, thread synchronization not required
7150  if (timedMetadata.size() > 0)
7151  {
7152  timedMetadata.clear();
7153  }
7154  mFailureReason="";
7155 
7156 
7157  // LLAMA-7124 - explicitly invalidate previous position for consistency with previous code
7158  mPrevPositionMilliseconds.Invalidate();
7159  seek_pos_seconds = -1;
7160  culledSeconds = 0;
7161  mIsLiveStream = false;
7162  durationSeconds = 0;
7163  mProgressReportOffset = -1;
7164  rate = 1;
7165  // Set the state to eSTATE_IDLE
7166  // directly setting state variable . Calling SetState will trigger event :(
7167  mState = eSTATE_IDLE;
7168 
7169  mSeekOperationInProgress = false;
7170  mTrickplayInProgress = false;
7171  mMaxLanguageCount = 0; // reset language count
7172  //mPreferredAudioTrack = AudioTrackInfo(); // reset
7173  mPreferredTextTrack = TextTrackInfo(); // reset
7174  // send signal to any thread waiting for play
7175  pthread_mutex_lock(&mMutexPlaystart);
7176  pthread_cond_broadcast(&waitforplaystart);
7177  pthread_mutex_unlock(&mMutexPlaystart);
7178  if(mPreCachePlaylistThreadFlag)
7179  {
7180  pthread_join(mPreCachePlaylistThreadId,NULL);
7181  mPreCachePlaylistThreadFlag=false;
7182  mPreCachePlaylistThreadId = 0;
7183  }
7185 
7186 
7187  if (pipeline_paused)
7188  {
7189  pipeline_paused = false;
7190  }
7191 
7192  //temporary hack for peacock
7193  if (STARTS_WITH_IGNORE_CASE(mAppName.c_str(), "peacock"))
7194  {
7195  SAFE_DELETE(mAampCacheHandler);
7196 
7197 #if defined(AAMP_MPD_DRM) || defined(AAMP_HLS_DRM)
7198  SAFE_DELETE(mDRMSessionManager);
7199 #endif
7200  }
7201 
7202  SAFE_DELETE(mCdaiObject);
7203 
7204 #if 0
7205  /* Clear the session data*/
7206  if(!mSessionToken.empty()){
7207  mSessionToken.clear();
7208  }
7209 #endif
7210 
7211  EnableDownloads();
7212 }
7213 
7214 /**
7215  * @brief SaveTimedMetadata Function to store Metadata for bulk reporting during Initialization
7216  */
7217 void PrivateInstanceAAMP::SaveTimedMetadata(long long timeMilliseconds, const char* szName, const char* szContent, int nb, const char* id, double durationMS)
7218 {
7219  std::string content(szContent, nb);
7220  timedMetadata.push_back(TimedMetadata(timeMilliseconds, std::string((szName == NULL) ? "" : szName), content, std::string((id == NULL) ? "" : id), durationMS));
7221 }
7222 
7223 /**
7224  * @brief SaveNewTimedMetadata Function to store Metadata and reporting event one by one after DRM Initialization
7225  */
7226 void PrivateInstanceAAMP::SaveNewTimedMetadata(long long timeMilliseconds, const char* szName, const char* szContent, int nb, const char* id, double durationMS)
7227 {
7228  std::string content(szContent, nb);
7229  timedMetadataNew.push_back(TimedMetadata(timeMilliseconds, std::string((szName == NULL) ? "" : szName), content, std::string((id == NULL) ? "" : id), durationMS));
7230 }
7231 
7232 /**
7233  * @brief Report timed metadata Function to send timedMetadata
7234  */
7236 {
7237  bool bMetadata = ISCONFIGSET_PRIV(eAAMPConfig_BulkTimedMetaReport);
7238  if(bMetadata && init && IsNewTune())
7239  {
7241  }
7242  else
7243  {
7244  std::vector<TimedMetadata>::iterator iter;
7245  mTimedMetadataStartTime = NOW_STEADY_TS_MS ;
7246  for (iter = timedMetadataNew.begin(); iter != timedMetadataNew.end(); iter++)
7247  {
7248  ReportTimedMetadata(iter->_timeMS, iter->_name.c_str(), iter->_content.c_str(), iter->_content.size(), init, iter->_id.c_str(), iter->_durationMS);
7249  }
7250  timedMetadataNew.clear();
7251  mTimedMetadataDuration = (NOW_STEADY_TS_MS - mTimedMetadataStartTime);
7252  }
7253 }
7254 
7255 /**
7256  * @brief Report bulk timedMetadata Function to send bulk timedMetadata in json format
7257  */
7259 {
7260  mTimedMetadataStartTime = NOW_STEADY_TS_MS;
7261  std::vector<TimedMetadata>::iterator iter;
7262  if(ISCONFIGSET_PRIV(eAAMPConfig_EnableSubscribedTags) && timedMetadata.size())
7263  {
7264  AAMPLOG_INFO("Sending bulk Timed Metadata");
7265 
7266  cJSON *root;
7267  cJSON *item;
7268  root = cJSON_CreateArray();
7269  if(root)
7270  {
7271  for (iter = timedMetadata.begin(); iter != timedMetadata.end(); iter++)
7272  {
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());
7279  }
7280 
7281  char* bulkData = cJSON_PrintUnformatted(root);
7282  if(bulkData)
7283  {
7284  BulkTimedMetadataEventPtr eventData = std::make_shared<BulkTimedMetadataEvent>(std::string(bulkData));
7285  AAMPLOG_INFO("Sending bulkTimedData");
7286  if (ISCONFIGSET_PRIV(eAAMPConfig_MetadataLogging))
7287  {
7288  AAMPLOG_INFO("bulkTimedData : %s", bulkData);
7289  }
7290  // Sending BulkTimedMetaData event as synchronous event.
7291  // SCTE35 events are async events in TimedMetadata, and this event is sending only from HLS
7292  mEventManager->SendEvent(eventData);
7293  free(bulkData);
7294  }
7295  cJSON_Delete(root);
7296  }
7297  mTimedMetadataDuration = (NOW_STEADY_TS_MS - mTimedMetadataStartTime);
7298  }
7299 }
7300 
7301 /**
7302  * @brief Report timed metadata Function to send timedMetadata events
7303  */
7304 void PrivateInstanceAAMP::ReportTimedMetadata(long long timeMilliseconds, const char *szName, const char *szContent, int nb, bool bSyncCall, const char *id, double durationMS)
7305 {
7306  std::string content(szContent, nb);
7307  bool bFireEvent = false;
7308 
7309  // Check if timedMetadata was already reported
7310  std::vector<TimedMetadata>::iterator i;
7311  bool ignoreMetaAdd = false;
7312 
7313  for (i = timedMetadata.begin(); i != timedMetadata.end(); i++)
7314  {
7315  if ((timeMilliseconds >= i->_timeMS-1000 && timeMilliseconds <= i->_timeMS+1000 ))
7316  {
7317  if((i->_name.compare(szName) == 0) && (i->_content.compare(content) == 0))
7318  {
7319  // Already same exists , ignore
7320  ignoreMetaAdd = true;
7321  break;
7322  }
7323  else
7324  {
7325  continue;
7326  }
7327  }
7328  else if (i->_timeMS < timeMilliseconds)
7329  {
7330  // move to next entry
7331  continue;
7332  }
7333  else if (i->_timeMS > timeMilliseconds)
7334  {
7335  break;
7336  }
7337  }
7338 
7339  if(!ignoreMetaAdd)
7340  {
7341  bFireEvent = true;
7342  if(i == timedMetadata.end())
7343  {
7344  // Comes here for
7345  // 1.No entry in the table
7346  // 2.Entries available which is only having time < NewMetatime
7347  timedMetadata.push_back(TimedMetadata(timeMilliseconds, szName, content, id, durationMS));
7348  }
7349  else
7350  {
7351  // New entry in between saved entries.
7352  // i->_timeMS >= timeMilliseconds && no similar entry in table
7353  timedMetadata.insert(i, TimedMetadata(timeMilliseconds, szName, content, id, durationMS));
7354  }
7355  }
7356 
7357 
7358  if (bFireEvent)
7359  {
7360  //DELIA-40019: szContent should not contain any tag name and ":" delimiter. This is not checked in JS event listeners
7361  TimedMetadataEventPtr eventData = std::make_shared<TimedMetadataEvent>(((szName == NULL) ? "" : szName), ((id == NULL) ? "" : id), timeMilliseconds, durationMS, content);
7362 
7363  if (ISCONFIGSET_PRIV(eAAMPConfig_MetadataLogging))
7364  {
7365  AAMPLOG_WARN("aamp timedMetadata: [%ld] '%s'", (long)(timeMilliseconds), content.c_str());
7366  }
7367 
7368  if (!bSyncCall)
7369  {
7371  }
7372  else
7373  {
7375  }
7376  }
7377 }
7378 
7379 
7380 /**
7381  * @brief Report content gap events
7382  */
7383 void PrivateInstanceAAMP::ReportContentGap(long long timeMilliseconds, std::string id, double durationMS)
7384 {
7385  bool bFireEvent = false;
7386  bool ignoreMetaAdd = false;
7387  // Check if contentGap was already reported
7388  std::vector<ContentGapInfo>::iterator iter;
7389 
7390  for (iter = contentGaps.begin(); iter != contentGaps.end(); iter++)
7391  {
7392  if ((timeMilliseconds >= iter->_timeMS-1000 && timeMilliseconds <= iter->_timeMS+1000 ))
7393  {
7394  if(iter->_id == id)
7395  {
7396  // Already same exists , ignore if periodGap information is complete.
7397  if(iter->_complete)
7398  {
7399  ignoreMetaAdd = true;
7400  break;
7401  }
7402  else
7403  {
7404  if(durationMS >= 0)
7405  {
7406  // New request with duration, mark complete and report it.
7407  iter->_durationMS = durationMS;
7408  iter->_complete = true;
7409  }
7410  else
7411  {
7412  // Duplicate report request, already processed
7413  ignoreMetaAdd = true;
7414  break;
7415  }
7416  }
7417  }
7418  else
7419  {
7420  continue;
7421  }
7422  }
7423  else if (iter->_timeMS < timeMilliseconds)
7424  {
7425  // move to next entry
7426  continue;
7427  }
7428  else if (iter->_timeMS > timeMilliseconds)
7429  {
7430  break;
7431  }
7432  }
7433 
7434  if(!ignoreMetaAdd)
7435  {
7436  bFireEvent = true;
7437  if(iter == contentGaps.end())
7438  {
7439  contentGaps.push_back(ContentGapInfo(timeMilliseconds, id, durationMS));
7440  }
7441  else
7442  {
7443  contentGaps.insert(iter, ContentGapInfo(timeMilliseconds, id, durationMS));
7444  }
7445  }
7446 
7447 
7448  if (bFireEvent)
7449  {
7450  ContentGapEventPtr eventData = std::make_shared<ContentGapEvent>(timeMilliseconds, durationMS);
7451  AAMPLOG_INFO("aamp contentGap: start: %lld duration: %ld", timeMilliseconds, (long) durationMS);
7452  mEventManager->SendEvent(eventData);
7453  }
7454 }
7455 
7456 /**
7457  * @brief Initialize CC after first frame received
7458  * Sends CC handle event to listeners when first frame receives or video_dec handle rests
7459  */
7461 {
7462 #ifdef AAMP_STOP_SINK_ON_SEEK
7463  /*Do not send event on trickplay as CC is not enabled*/
7464  if (AAMP_NORMAL_PLAY_RATE != rate)
7465  {
7466  AAMPLOG_WARN("PrivateInstanceAAMP: not sending cc handle as rate = %f", rate);
7467  return;
7468  }
7469 #endif
7470  if (mStreamSink != NULL)
7471  {
7472 #ifdef AAMP_CC_ENABLED
7473  if (ISCONFIGSET_PRIV(eAAMPConfig_NativeCCRendering))
7474  {
7475  AampCCManager::GetInstance()->Init((void *)mStreamSink->getCCDecoderHandle());
7476 
7477  int overrideCfg;
7478  GETCONFIGVALUE_PRIV(eAAMPConfig_CEAPreferred,overrideCfg);
7479  if (overrideCfg == 0)
7480  {
7481  AAMPLOG_WARN("PrivateInstanceAAMP: CC format override to 608 present, selecting 608CC");
7483  }
7484 
7485  }
7486  else
7487 #endif
7488  {
7489  CCHandleEventPtr event = std::make_shared<CCHandleEvent>(mStreamSink->getCCDecoderHandle());
7490  mEventManager->SendEvent(event);
7491  }
7492  }
7493 }
7494 
7495 
7496 /**
7497  * @brief Notify first frame is displayed. Sends CC handle event to listeners.
7498  */
7500 {
7501  // In the middle of stop processing we can receive state changing callback (xione-7331)
7502  PrivAAMPState state;
7503  GetState(state);
7504  if (state == eSTATE_IDLE)
7505  {
7506  AAMPLOG_WARN( "skipped as in IDLE state" );
7507  return;
7508  }
7509 
7510  // If mFirstVideoFrameDisplayedEnabled, state will be changed in NotifyFirstVideoDisplayed()
7512  {
7514  }
7515  pthread_mutex_lock(&mMutexPlaystart);
7516  pthread_cond_broadcast(&waitforplaystart);
7517  pthread_mutex_unlock(&mMutexPlaystart);
7518 
7519  if (eTUNED_EVENT_ON_GST_PLAYING == GetTuneEventConfig(IsLive()))
7520  {
7521  // This is an idle callback, so we can sent event synchronously
7522  if (SendTunedEvent())
7523  {
7524  AAMPLOG_WARN("aamp: - sent tune event on Tune Completion.");
7525  }
7526  }
7527  InitializeCC();
7528 }
7529 
7530 /**
7531  * @brief Signal discontinuity of track.
7532  * Called from StreamAbstractionAAMP to signal discontinuity
7533  */
7534 bool PrivateInstanceAAMP::Discontinuity(MediaType track, bool setDiscontinuityFlag)
7535 {
7536  bool ret;
7537 
7538  if (setDiscontinuityFlag)
7539  {
7540  ret = true;
7541  }
7542  else
7543  {
7544  SyncBegin();
7545  ret = mStreamSink->Discontinuity(track);
7546  SyncEnd();
7547  }
7548 
7549  if (ret)
7550  {
7551  mProcessingDiscontinuity[track] = true;
7552  }
7553  return ret;
7554 }
7555 
7556 /**
7557  * @brief Schedules retune or discontinuity processing based on state.
7558  */
7560 {
7561  if (AAMP_NORMAL_PLAY_RATE == rate && ContentType_EAS != mContentType)
7562  {
7563  PrivAAMPState state;
7564  GetState(state);
7565  if (((state != eSTATE_PLAYING) && (eGST_ERROR_VIDEO_BUFFERING != errorType)) || mSeekOperationInProgress)
7566  {
7567  AAMPLOG_WARN("PrivateInstanceAAMP: Not processing reTune since state = %d, mSeekOperationInProgress = %d",
7568  state, mSeekOperationInProgress);
7569  return;
7570  }
7571 
7572  pthread_mutex_lock(&gMutex);
7573  if (this->mIsRetuneInProgress)
7574  {
7575  AAMPLOG_WARN("PrivateInstanceAAMP:: Already Retune inprogress");
7576  pthread_mutex_unlock(&gMutex);
7577  return;
7578  }
7579  pthread_mutex_unlock(&gMutex);
7580 
7581  /*If underflow is caused by a discontinuity processing, continue playback from discontinuity*/
7582  // If discontinuity process in progress, skip further processing
7583  // DELIA-46559 Since discontinuity flags are reset a bit earlier, additional checks added below to check if discontinuity processing in progress
7584  pthread_mutex_lock(&mLock);
7585  if ((errorType != eGST_ERROR_PTS) &&
7586  (IsDiscontinuityProcessPending() || mDiscontinuityTuneOperationId != 0 || mDiscontinuityTuneOperationInProgress))
7587  {
7588  if (mDiscontinuityTuneOperationId != 0 || mDiscontinuityTuneOperationInProgress)
7589  {
7590  AAMPLOG_WARN("PrivateInstanceAAMP: Discontinuity Tune handler already spawned(%d) or inprogress(%d)",
7591  mDiscontinuityTuneOperationId, mDiscontinuityTuneOperationInProgress);
7592  pthread_mutex_unlock(&mLock);
7593  return;
7594  }
7595  mDiscontinuityTuneOperationId = ScheduleAsyncTask(PrivateInstanceAAMP_ProcessDiscontinuity, (void *)this, "PrivateInstanceAAMP_ProcessDiscontinuity");
7596  pthread_mutex_unlock(&mLock);
7597 
7598  AAMPLOG_WARN("PrivateInstanceAAMP: Underflow due to discontinuity handled");
7599  return;
7600  }
7601 
7602  pthread_mutex_unlock(&mLock);
7603 
7605  {
7606  AAMPLOG_WARN("PrivateInstanceAAMP: Ignore reTune due to playback stall");
7607  return;
7608  }
7609  else if (!ISCONFIGSET_PRIV(eAAMPConfig_InternalReTune))
7610  {
7611  AAMPLOG_WARN("PrivateInstanceAAMP: Ignore reTune as disabled in configuration");
7612  return;
7613  }
7614 
7615  MediaTrack* mediaTrack = (mpStreamAbstractionAAMP != NULL) ? (mpStreamAbstractionAAMP->GetMediaTrack((TrackType)trackType)) : NULL;
7616 
7617  if((ISCONFIGSET_PRIV(eAAMPConfig_ReportBufferEvent)) &&
7618  (errorType == eGST_ERROR_UNDERFLOW) &&
7619  (trackType == eMEDIATYPE_VIDEO) &&
7620  (mediaTrack) &&
7621  (mediaTrack->GetBufferStatus() == BUFFER_STATUS_RED))
7622  {
7623  SendBufferChangeEvent(true); // Buffer state changed, buffer Under flow started
7624  if (!pipeline_paused && !PausePipeline(true, true))
7625  {
7626  AAMPLOG_ERR("Failed to pause the Pipeline");
7627  }
7628  }
7629 
7630  const char* errorString = (errorType == eGST_ERROR_PTS) ? "PTS ERROR" :
7631  (errorType == eGST_ERROR_UNDERFLOW) ? "Underflow" :
7632  (errorType == eSTALL_AFTER_DISCONTINUITY) ? "Stall After Discontinuity" :
7633  (errorType == eDASH_LOW_LATENCY_MAX_CORRECTION_REACHED)?"LL DASH Max Correction Reached":
7634  (errorType == eDASH_LOW_LATENCY_INPUT_PROTECTION_ERROR)?"LL DASH Input Protection Error":
7635  (errorType == eDASH_RECONFIGURE_FOR_ENC_PERIOD)?"Enrypted period found":
7636  (errorType == eGST_ERROR_GST_PIPELINE_INTERNAL) ? "GstPipeline Internal Error" : "STARTTIME RESET";
7637 
7638  SendAnomalyEvent(ANOMALY_WARNING, "%s %s", (trackType == eMEDIATYPE_VIDEO ? "VIDEO" : "AUDIO"), errorString);
7639  bool activeAAMPFound = false;
7640  pthread_mutex_lock(&gMutex);
7641  for (std::list<gActivePrivAAMP_t>::iterator iter = gActivePrivAAMPs.begin(); iter != gActivePrivAAMPs.end(); iter++)
7642  {
7643  if (this == iter->pAAMP)
7644  {
7645  gActivePrivAAMP_t *gAAMPInstance = &(*iter);
7646  if (gAAMPInstance->reTune)
7647  {
7648  AAMPLOG_WARN("PrivateInstanceAAMP: Already scheduled");
7649  }
7650  else
7651  {
7652  if(eGST_ERROR_PTS == errorType || eGST_ERROR_UNDERFLOW == errorType)
7653  {
7654  long long now = aamp_GetCurrentTimeMS();
7655  long long lastErrorReportedTimeMs = lastUnderFlowTimeMs[trackType];
7656  int ptsErrorThresholdValue = 0;
7657  GETCONFIGVALUE_PRIV(eAAMPConfig_PTSErrorThreshold,ptsErrorThresholdValue);
7658  if (lastErrorReportedTimeMs)
7659  {
7660  bool isRetuneRequried = false;
7661  long long diffMs = (now - lastErrorReportedTimeMs);
7663  {
7664  if (diffMs < AAMP_MAX_TIME_LL_BW_UNDERFLOWS_TO_TRIGGER_RETUNE_MS)
7665  {
7666  isRetuneRequried = true;
7667  }
7668  }
7669  else
7670  {
7671  if (diffMs < AAMP_MAX_TIME_BW_UNDERFLOWS_TO_TRIGGER_RETUNE_MS)
7672  {
7673  isRetuneRequried = true;
7674  }
7675  }
7676  if(isRetuneRequried)
7677  {
7678  gAAMPInstance->numPtsErrors++;
7679  if (gAAMPInstance->numPtsErrors >= ptsErrorThresholdValue)
7680  {
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",
7686  diffMs, GetLLDashServiceData()->lowLatencyMode?
7687  AAMP_MAX_TIME_LL_BW_UNDERFLOWS_TO_TRIGGER_RETUNE_MS:AAMP_MAX_TIME_BW_UNDERFLOWS_TO_TRIGGER_RETUNE_MS);
7689  ScheduleAsyncTask(PrivateInstanceAAMP_Retune, (void *)this, "PrivateInstanceAAMP_Retune");
7690  }
7691  }
7692  else
7693  {
7694  gAAMPInstance->numPtsErrors = 0;
7695  AAMPLOG_WARN("PrivateInstanceAAMP: Not scheduling reTune since (diff %lld > threshold %lld) numPtsErrors %d, ptsErrorThreshold %d.",
7696  diffMs, GetLLDashServiceData()->lowLatencyMode?
7697  AAMP_MAX_TIME_LL_BW_UNDERFLOWS_TO_TRIGGER_RETUNE_MS:AAMP_MAX_TIME_BW_UNDERFLOWS_TO_TRIGGER_RETUNE_MS,
7698  gAAMPInstance->numPtsErrors, ptsErrorThresholdValue);
7699  }
7700  }
7701  else
7702  {
7703  gAAMPInstance->numPtsErrors = 0;
7704  AAMPLOG_WARN("PrivateInstanceAAMP: Not scheduling reTune since first %s.", errorString);
7705  }
7706  lastUnderFlowTimeMs[trackType] = now;
7707  }
7708  else
7709  {
7710  AAMPLOG_WARN("PrivateInstanceAAMP: Schedule Retune errorType %d error %s", errorType, errorString);
7711  gAAMPInstance->reTune = true;
7713  ScheduleAsyncTask(PrivateInstanceAAMP_Retune, (void *)this, "PrivateInstanceAAMP_Retune");
7714  }
7715  }
7716  activeAAMPFound = true;
7717  break;
7718  }
7719  }
7720  pthread_mutex_unlock(&gMutex);
7721  if (!activeAAMPFound)
7722  {
7723  AAMPLOG_WARN("PrivateInstanceAAMP: %p not in Active AAMP list", this);
7724  }
7725  }
7726 }
7727 
7728 /**
7729  * @brief Set player state
7730  */
7732 {
7733  //bool sentSync = true;
7734 
7735  if (mState == state)
7736  { // noop
7737  return;
7738  }
7739 
7740  if ( (state == eSTATE_PLAYING || state == eSTATE_BUFFERING || state == eSTATE_PAUSED)
7742  {
7743  SeekedEventPtr event = std::make_shared<SeekedEvent>(GetPositionMilliseconds());
7745 
7746  }
7747 
7748  pthread_mutex_lock(&mLock);
7749  mState = state;
7750  pthread_mutex_unlock(&mLock);
7751 
7752  mScheduler->SetState(mState);
7754  {
7755  if (mState == eSTATE_PREPARING)
7756  {
7757  StateChangedEventPtr eventData = std::make_shared<StateChangedEvent>(eSTATE_INITIALIZED);
7759  }
7760 
7761  StateChangedEventPtr eventData = std::make_shared<StateChangedEvent>(mState);
7763  }
7764 }
7765 
7766 /**
7767  * @brief Get player state
7768  */
7770 {
7771  pthread_mutex_lock(&mLock);
7772  state = mState;
7773  pthread_mutex_unlock(&mLock);
7774 }
7775 
7776 /**
7777  * @brief Add high priority idle task to the gstreamer
7778  * @note task shall return 0 to be removed, 1 to be repeated
7779  */
7781 {
7782  gint callbackID = g_idle_add_full(G_PRIORITY_HIGH_IDLE, task, (gpointer)arg, dtask);
7783  return callbackID;
7784 }
7785 
7786 /**
7787  * @brief Check sink cache empty
7788  */
7790 {
7791  return mStreamSink->IsCacheEmpty(mediaType);
7792 }
7793 
7794 /**
7795  * @brief Reset EOS SignalledFlag
7796  */
7798 {
7799  return mStreamSink->ResetEOSSignalledFlag();
7800 }
7801 
7802 /**
7803  * @brief Notify fragment caching complete
7804  */
7806 {
7807  pthread_mutex_lock(&mFragmentCachingLock);
7808  mFragmentCachingRequired = false;
7809  mStreamSink->NotifyFragmentCachingComplete();
7810  PrivAAMPState state;
7811  GetState(state);
7812  if (state == eSTATE_BUFFERING)
7813  {
7815  {
7817  }
7819  }
7820  pthread_mutex_unlock(&mFragmentCachingLock);
7821 }
7822 
7823 /**
7824  * @brief Send tuned event to listeners if required
7825  */
7826 bool PrivateInstanceAAMP::SendTunedEvent(bool isSynchronous)
7827 {
7828  bool ret = false;
7829 
7830  // Required for synchronising btw audio and video tracks in case of cdmidecryptor
7831  pthread_mutex_lock(&mLock);
7832 
7833  ret = mTunedEventPending;
7834  mTunedEventPending = false;
7835 
7836  pthread_mutex_unlock(&mLock);
7837 
7838  if(ret)
7839  {
7840  AAMPEventPtr ev = std::make_shared<AAMPEventObject>(AAMP_EVENT_TUNED);
7842  }
7843  return ret;
7844 }
7845 
7846 /**
7847  * @brief Send VideoEndEvent
7848  */
7850 {
7851  bool ret = false;
7852  char * strVideoEndJson = NULL;
7853  // Required for protecting mVideoEnd object
7854  pthread_mutex_lock(&mLock);
7855  if(mVideoEnd)
7856  {
7857  //Update VideoEnd Data
7858  if(mTimeAtTopProfile > 0)
7859  {
7860  // Losing milisecons of data in conversion from double to long
7861  mVideoEnd->SetTimeAtTopProfile(mTimeAtTopProfile);
7862  mVideoEnd->SetTimeToTopProfile(mTimeToTopProfile);
7863  }
7864  mVideoEnd->SetTotalDuration(mPlaybackDuration);
7865 
7866  // re initialize for next tune collection
7867  mTimeToTopProfile = 0;
7868  mTimeAtTopProfile = 0;
7869  mPlaybackDuration = 0;
7871 
7872  //Memory of this string will be deleted after sending event by destructor of AsyncMetricsEventDescriptor
7874  {
7875  if(mTSBEnabled)
7876  {
7877  char* data = GetOnVideoEndSessionStatData();
7878  if(data)
7879  {
7880  AAMPLOG_INFO("TsbSessionEnd:%s", data);
7881  strVideoEndJson = mVideoEnd->ToJsonString(data);
7882  cJSON_free( data );
7883  data = NULL;
7884  }
7885  }
7886  else
7887  {
7888  strVideoEndJson = mVideoEnd->ToJsonString();
7889  }
7890  }
7891  SAFE_DELETE(mVideoEnd);
7892  }
7893  mVideoEnd = new CVideoStat(mMediaFormatName[mMediaFormat]);
7894  mVideoEnd->SetDisplayResolution(mDisplayWidth,mDisplayHeight);
7895  pthread_mutex_unlock(&mLock);
7896 
7897  if(strVideoEndJson)
7898  {
7899  AAMPLOG_INFO("VideoEnd:%s", strVideoEndJson);
7900  MetricsDataEventPtr e = std::make_shared<MetricsDataEvent>(MetricsDataType::AAMP_DATA_VIDEO_END, this->mTraceUUID, strVideoEndJson);
7902  free(strVideoEndJson);
7903  ret = true;
7904  }
7905  return ret;
7906 }
7907 
7908 /**
7909  * @brief updates profile Resolution to VideoStat object
7910  */
7911 void PrivateInstanceAAMP::UpdateVideoEndProfileResolution(MediaType mediaType, long bitrate, int width, int height)
7912 {
7913  pthread_mutex_lock(&mLock);
7914  if(mVideoEnd)
7915  {
7916  VideoStatTrackType trackType = VideoStatTrackType::STAT_VIDEO;
7917  if(mediaType == eMEDIATYPE_IFRAME)
7918  {
7919  trackType = VideoStatTrackType::STAT_IFRAME;
7920  }
7921  mVideoEnd->SetProfileResolution(trackType,bitrate,width,height);
7922  }
7923  pthread_mutex_unlock(&mLock);
7924 }
7925 
7926 /**
7927  * @brief updates download metrics to VideoStat object, this is used for VideoFragment as it takes duration for calcuation purpose.
7928  */
7929 void PrivateInstanceAAMP::UpdateVideoEndMetrics(MediaType mediaType, long bitrate, int curlOrHTTPCode, std::string& strUrl, double duration, double curlDownloadTime)
7930 {
7931  UpdateVideoEndMetrics(mediaType, bitrate, curlOrHTTPCode, strUrl,duration,curlDownloadTime, false,false);
7932 }
7933 
7934 /**
7935  * @brief updates time shift buffer status
7936  *
7937  */
7939 {
7940  pthread_mutex_lock(&mLock);
7941  if(mVideoEnd)
7942  {
7943 
7944  mVideoEnd->SetTsbStatus(btsbAvailable);
7945  }
7946  pthread_mutex_unlock(&mLock);
7947 }
7948 
7949 /**
7950  * @brief updates profile capped status
7951  */
7953 {
7954  pthread_mutex_lock(&mLock);
7955  if(mVideoEnd)
7956  {
7957  mVideoEnd->SetProfileCappedStatus(mProfileCappedStatus);
7958  }
7959  pthread_mutex_unlock(&mLock);
7960 }
7961 
7962 /**
7963  * @brief updates download metrics to VideoStat object, this is used for VideoFragment as it takes duration for calcuation purpose.
7964  */
7965 void PrivateInstanceAAMP::UpdateVideoEndMetrics(MediaType mediaType, long bitrate, int curlOrHTTPCode, std::string& strUrl, double duration, double curlDownloadTime, bool keyChanged, bool isEncrypted, ManifestData * manifestData)
7966 {
7967  int audioIndex = 1;
7968  // ignore for write and aborted errors
7969  // these are generated after trick play options,
7970  if( curlOrHTTPCode > 0 && !(curlOrHTTPCode == CURLE_ABORTED_BY_CALLBACK || curlOrHTTPCode == CURLE_WRITE_ERROR) )
7971  {
7972  VideoStatDataType dataType = VideoStatDataType::VE_DATA_UNKNOWN;
7973 
7974  VideoStatTrackType trackType = VideoStatTrackType::STAT_UNKNOWN;
7975  VideoStatCountType eCountType = VideoStatCountType::COUNT_UNKNOWN;
7976 
7977  /* COUNT_UNKNOWN,
7978  COUNT_LIC_TOTAL,
7979  COUNT_LIC_ENC_TO_CLR,
7980  COUNT_LIC_CLR_TO_ENC,
7981  COUNT_STALL,
7982  */
7983 
7984  switch(mediaType)
7985  {
7986  case eMEDIATYPE_MANIFEST:
7987  {
7988  dataType = VideoStatDataType::VE_DATA_MANIFEST;
7989  trackType = VideoStatTrackType::STAT_MAIN;
7990  }
7991  break;
7992 
7994  {
7995  dataType = VideoStatDataType::VE_DATA_MANIFEST;
7996  trackType = VideoStatTrackType::STAT_VIDEO;
7997  }
7998  break;
7999 
8001  {
8002  dataType = VideoStatDataType::VE_DATA_MANIFEST;
8003  trackType = VideoStatTrackType::STAT_AUDIO;
8004  audioIndex += mCurrentLanguageIndex;
8005  }
8006  break;
8007 
8009  {
8010  dataType = VideoStatDataType::VE_DATA_MANIFEST;
8011  trackType = VideoStatTrackType::STAT_AUDIO;
8012  audioIndex += mCurrentLanguageIndex;
8013  }
8014  break;
8015 
8017  {
8018  dataType = VideoStatDataType::VE_DATA_MANIFEST;
8019  trackType = STAT_IFRAME;
8020  }
8021  break;
8022 
8023  case eMEDIATYPE_VIDEO:
8024  {
8025  dataType = VideoStatDataType::VE_DATA_FRAGMENT;
8026  trackType = VideoStatTrackType::STAT_VIDEO;
8027  // always Video fragment will be from same thread so mutex required
8028 
8029  // !!!!!!!!!! To Do : Support this stats for Audio Only streams !!!!!!!!!!!!!!!!!!!!!
8030  //Is success
8031  if (((curlOrHTTPCode == 200) || (curlOrHTTPCode == 206)) && duration > 0)
8032  {
8034  {
8035  long maxBitrateSupported = mpStreamAbstractionAAMP->GetMaxBitrate();
8036  if(maxBitrateSupported == bitrate)
8037  {
8038  mTimeAtTopProfile += duration;
8039 
8040  }
8041 
8042  }
8043  if(mTimeAtTopProfile == 0) // we havent achived top profile yet
8044  {
8045  mTimeToTopProfile += duration; // started at top profile
8046  }
8047 
8048  mPlaybackDuration += duration;
8049  }
8050 
8051  }
8052  break;
8053  case eMEDIATYPE_AUDIO:
8054  {
8055  dataType = VideoStatDataType::VE_DATA_FRAGMENT;
8056  trackType = VideoStatTrackType::STAT_AUDIO;
8057  audioIndex += mCurrentLanguageIndex;
8058  }
8059  break;
8060  case eMEDIATYPE_AUX_AUDIO:
8061  {
8062  dataType = VideoStatDataType::VE_DATA_FRAGMENT;
8063  trackType = VideoStatTrackType::STAT_AUDIO;
8064  audioIndex += mCurrentLanguageIndex;
8065  }
8066  break;
8067  case eMEDIATYPE_IFRAME:
8068  {
8069  dataType = VideoStatDataType::VE_DATA_FRAGMENT;
8070  trackType = VideoStatTrackType::STAT_IFRAME;
8071  }
8072  break;
8073 
8075  {
8076  dataType = VideoStatDataType::VE_DATA_INIT_FRAGMENT;
8077  trackType = VideoStatTrackType::STAT_IFRAME;
8078  }
8079  break;
8080 
8081  case eMEDIATYPE_INIT_VIDEO:
8082  {
8083  dataType = VideoStatDataType::VE_DATA_INIT_FRAGMENT;
8084  trackType = VideoStatTrackType::STAT_VIDEO;
8085  }
8086  break;
8087 
8088  case eMEDIATYPE_INIT_AUDIO:
8089  {
8090  dataType = VideoStatDataType::VE_DATA_INIT_FRAGMENT;
8091  trackType = VideoStatTrackType::STAT_AUDIO;
8092  audioIndex += mCurrentLanguageIndex;
8093  }
8094  break;
8095 
8097  {
8098  dataType = VideoStatDataType::VE_DATA_INIT_FRAGMENT;
8099  trackType = VideoStatTrackType::STAT_AUDIO;
8100  audioIndex += mCurrentLanguageIndex;
8101  }
8102  break;
8103 
8104  case eMEDIATYPE_SUBTITLE:
8105  {
8106  dataType = VideoStatDataType::VE_DATA_FRAGMENT;
8107  trackType = VideoStatTrackType::STAT_SUBTITLE;
8108  }
8109  break;
8110 
8111  default:
8112  break;
8113  }
8114 
8115 
8116  // Required for protecting mVideoStat object
8117  if( dataType != VideoStatDataType::VE_DATA_UNKNOWN
8118  && trackType != VideoStatTrackType::STAT_UNKNOWN)
8119  {
8120  pthread_mutex_lock(&mLock);
8121  if(mVideoEnd)
8122  {
8123  //curl download time is in seconds, convert it into milliseconds for video end metrics
8124  mVideoEnd->Increment_Data(dataType,trackType,bitrate,curlDownloadTime * 1000,curlOrHTTPCode,false,audioIndex, manifestData);
8125  if((curlOrHTTPCode != 200) && (curlOrHTTPCode != 206) && strUrl.c_str())
8126  {
8127  //set failure url
8128  mVideoEnd->SetFailedFragmentUrl(trackType,bitrate,strUrl);
8129  }
8130  if(dataType == VideoStatDataType::VE_DATA_FRAGMENT)
8131  {
8132  mVideoEnd->Record_License_EncryptionStat(trackType,isEncrypted,keyChanged);
8133  }
8134  }
8135  pthread_mutex_unlock(&mLock);
8136 
8137  }
8138  else
8139  {
8140  AAMPLOG_INFO("PrivateInstanceAAMP: Could Not update VideoEnd Event dataType:%d trackType:%d response:%d",
8141  dataType,trackType,curlOrHTTPCode);
8142  }
8143  }
8144 }
8145 
8146 /**
8147  * @brief updates abr metrics to VideoStat object,
8148  */
8150 {
8151  //only for Ramp down case
8152  if(info.desiredProfileIndex < info.currentProfileIndex)
8153  {
8154  AAMPLOG_INFO("UpdateVideoEnd:abrinfo currIdx:%d desiredIdx:%d for:%d", info.currentProfileIndex,info.desiredProfileIndex,info.abrCalledFor);
8155 
8156  if(info.abrCalledFor == AAMPAbrType::AAMPAbrBandwidthUpdate)
8157  {
8158  pthread_mutex_lock(&mLock);
8159  if(mVideoEnd)
8160  {
8161  mVideoEnd->Increment_NetworkDropCount();
8162  }
8163  pthread_mutex_unlock(&mLock);
8164  }
8165  else if (info.abrCalledFor == AAMPAbrType::AAMPAbrFragmentDownloadFailed)
8166  {
8167  pthread_mutex_lock(&mLock);
8168  if(mVideoEnd)
8169  {
8170  mVideoEnd->Increment_ErrorDropCount();
8171  }
8172  pthread_mutex_unlock(&mLock);
8173  }
8174  }
8175 }
8176 
8177 /**
8178  * @brief updates download metrics to VideoStat object, this is used for VideoFragment as it takes duration for calcuation purpose.
8179  */
8180 void PrivateInstanceAAMP::UpdateVideoEndMetrics(MediaType mediaType, long bitrate, int curlOrHTTPCode, std::string& strUrl, double curlDownloadTime, ManifestData * manifestData)
8181 {
8182 
8183  UpdateVideoEndMetrics(mediaType, bitrate, curlOrHTTPCode, strUrl,0,curlDownloadTime, false, false, manifestData);
8184 }
8185 
8186 /**
8187  * @brief Check if fragment caching is required
8188  */
8190 {
8191  //Prevent enabling Fragment Caching during Seek While Pause
8193 }
8194 
8195 /**
8196  * @brief Get player video size
8197  */
8198 void PrivateInstanceAAMP::GetPlayerVideoSize(int &width, int &height)
8199 {
8200  mStreamSink->GetVideoSize(width, height);
8201 }
8202 
8203 /**
8204  * @brief Set an idle callback as event dispatched state
8205  */
8207 {
8208  pthread_mutex_lock(&mEventLock);
8209  std::map<guint, bool>::iterator itr = mPendingAsyncEvents.find(id);
8210  if(itr != mPendingAsyncEvents.end())
8211  {
8212  assert (itr->second);
8213  mPendingAsyncEvents.erase(itr);
8214  }
8215  else
8216  {
8217  AAMPLOG_WARN("id %d not in mPendingAsyncEvents, insert and mark as not pending", id);
8218  mPendingAsyncEvents[id] = false;
8219  }
8220  pthread_mutex_unlock(&mEventLock);
8221 }
8222 
8223 /**
8224  * @brief Set an idle callback as event pending state
8225  */
8227 {
8228  pthread_mutex_lock(&mEventLock);
8229  std::map<guint, bool>::iterator itr = mPendingAsyncEvents.find(id);
8230  if(itr != mPendingAsyncEvents.end())
8231  {
8232  assert (!itr->second);
8233  AAMPLOG_WARN("id %d already in mPendingAsyncEvents and completed, erase it", id);
8234  mPendingAsyncEvents.erase(itr);
8235  }
8236  else
8237  {
8238  mPendingAsyncEvents[id] = true;
8239  }
8240  pthread_mutex_unlock(&mEventLock);
8241 }
8242 
8243 /**
8244  * @brief Collect and send all key-value pairs for CMCD headers.
8245  */
8246 void PrivateInstanceAAMP::CollectCMCDCustomHeaders(MediaType fileType,class CMCDHeaders *pCMCDMetrics)
8247 {
8248  if(pCMCDMetrics!=NULL){
8249  MediaType simType = fileType;
8250  long temp=0;
8251  std::vector<long> bitrateList;
8252  pCMCDMetrics->SetSessionId(this->mTraceUUID);
8253  //For manifest sessionid and object type is passed as a part of CMCD Headers
8254  if(simType == eMEDIATYPE_MANIFEST)
8255  {
8256  pCMCDMetrics->SetMediaType("MANIFEST");
8257  }
8258  //For video sessionid,object type,currentvideobitrate,maximum videobitrate,bufferlength are send as a part of CMCD Headers
8259  if(simType == eMEDIATYPE_VIDEO)
8260  {
8261  pCMCDMetrics->SetMediaType("VIDEO");
8263  if(video && video->enabled)
8264  {
8265  if(video->GetBufferStatus() == BUFFER_STATUS_RED)//Bufferstarvation is send only when buffering turns red
8266  {
8267  pCMCDMetrics->SetBufferStarvation(true);
8268  }
8269  int videoBufferLength = ((int)video->GetBufferedDuration())*1000;
8270  int videoBitrate = ((int)mpStreamAbstractionAAMP->GetVideoBitrate())/1000;
8271  bitrateList = mpStreamAbstractionAAMP->GetVideoBitrates();
8272  for(int i = 0; i < bitrateList.size(); i++)
8273  {
8274  if(bitrateList[i]>temp)
8275  {
8276  temp=bitrateList[i];
8277  }
8278  }
8279  pCMCDMetrics->SetBitrate(videoBitrate);
8280  pCMCDMetrics->SetTopBitrate(temp/1000);
8281  pCMCDMetrics->SetNextUrl(mCMCDNextObjectRequest);
8282  pCMCDMetrics->SetBufferLength(videoBufferLength);
8283  AAMPLOG_INFO("video bufferlength %d video bitrate %d",videoBufferLength,videoBitrate);
8284  }
8285  }
8286  //For audio sessionid,object type,currentaudiobitrate,maximum audiobitrate,bufferlength are send as a part of CMCD Headers
8287  if(simType == eMEDIATYPE_AUDIO)
8288  {
8289  pCMCDMetrics->SetMediaType("AUDIO");
8291  if(audio && audio->enabled)
8292  {
8293  if(audio->GetBufferStatus() == BUFFER_STATUS_RED)//Bufferstarvation is send only when buffering turns red
8294  {
8295  pCMCDMetrics->SetBufferStarvation(true);
8296  }
8297  }
8298  bitrateList = mpStreamAbstractionAAMP->GetAudioBitrates();
8299  for(int i = 0; i < bitrateList.size(); i++)
8300  {
8301  if(bitrateList[i]>temp)
8302  {
8303  temp=bitrateList[i];
8304  }
8305  }
8306  int audioBufferLength = ((int)audio->GetBufferedDuration())*1000;
8307  pCMCDMetrics->SetBitrate(((int)mCMCDBandwidth)/1000);
8308  pCMCDMetrics->SetTopBitrate(temp/1000);
8309  pCMCDMetrics->SetNextUrl(mCMCDNextObjectRequest);
8310  pCMCDMetrics->SetBufferLength(audioBufferLength);
8311  AAMPLOG_INFO("audio bufferlength %daudio bitrate %d",audioBufferLength,((int)mCMCDBandwidth)/1000);
8312  }
8313  //For subtitle sessionid and object type are send as a part of CMCD Headers
8314  if(simType == eMEDIATYPE_SUBTITLE)
8315  {
8316 
8317  pCMCDMetrics->SetMediaType("SUBTITLE");
8318  }
8319  //For init fragment sessionid,object type,bitrate,maximum bitrate are send as a part of CMCD Headers
8320  if(simType == eMEDIATYPE_INIT_VIDEO)
8321  {
8322  pCMCDMetrics->SetMediaType("INIT_VIDEO");
8323  int initVideoBitrate = ((int)mpStreamAbstractionAAMP->GetVideoBitrate())/1000;
8324  bitrateList = mpStreamAbstractionAAMP->GetVideoBitrates();
8325  for(int i = 0; i < bitrateList.size(); i++)
8326  {
8327  if(bitrateList[i]>temp)
8328  {
8329  temp=bitrateList[i];
8330  }
8331  }
8332  pCMCDMetrics->SetBitrate(initVideoBitrate);
8333  pCMCDMetrics->SetTopBitrate(temp);
8334 
8335  }
8336  if(simType == eMEDIATYPE_INIT_AUDIO)
8337  {
8338  pCMCDMetrics->SetMediaType("INIT_AUDIO");
8339  bitrateList = mpStreamAbstractionAAMP->GetAudioBitrates();
8340  for(int i = 0; i < bitrateList.size(); i++)
8341  {
8342  if(bitrateList[i]>temp)
8343  {
8344  temp=bitrateList[i];
8345  }
8346  }
8347  pCMCDMetrics->SetBitrate(((int)mCMCDBandwidth)/1000);
8348  pCMCDMetrics->SetTopBitrate(temp);
8349  }
8350  //For muxed streams sessionid,object type,bitrate,maximum bitrate,bufferlength are send as a part of CMCD Headers
8352  {
8353  pCMCDMetrics->SetMediaType("MUXED");
8354  bitrateList = mpStreamAbstractionAAMP->GetVideoBitrates();
8355  for(int i = 0; i < bitrateList.size(); i++)
8356  {
8357  if(bitrateList[i]>temp)
8358  {
8359  temp=bitrateList[i];
8360  }
8361  }
8362  int muxedBitrate = ((int)mpStreamAbstractionAAMP->GetVideoBitrate())/1000;
8364  if(video)
8365  {
8366  if(video->GetBufferStatus() == BUFFER_STATUS_RED)///Bufferstarvation is send only when buffering turns red
8367  {
8368  pCMCDMetrics->SetBufferStarvation(true);
8369  }
8370  }
8371  int muxedBufferLength = ((int)mpStreamAbstractionAAMP->GetBufferedDuration())*1000;
8372  pCMCDMetrics->SetBitrate(muxedBitrate);
8373  pCMCDMetrics->SetTopBitrate(temp/1000);
8374  pCMCDMetrics->SetNextUrl(mCMCDNextObjectRequest);
8375  pCMCDMetrics->SetBufferLength(muxedBufferLength);
8376  AAMPLOG_INFO("muxed bufferlength %dmuxed bitrate %d",muxedBufferLength,muxedBitrate);
8377  }
8378  }
8379 }
8380 
8381 /**
8382  * @brief Add/Remove a custom HTTP header and value.
8383  */
8384 void PrivateInstanceAAMP::AddCustomHTTPHeader(std::string headerName, std::vector<std::string> headerValue, bool isLicenseHeader)
8385 {
8386  // Header name should be ending with :
8387  if(headerName.back() != ':')
8388  {
8389  headerName += ':';
8390  }
8391 
8392  if (isLicenseHeader)
8393  {
8394  if (headerValue.size() != 0)
8395  {
8396  mCustomLicenseHeaders[headerName] = headerValue;
8397  }
8398  else
8399  {
8400  mCustomLicenseHeaders.erase(headerName);
8401  }
8402  }
8403  else
8404  {
8405  if (headerValue.size() != 0)
8406  {
8407  mCustomHeaders[headerName] = headerValue;
8408  }
8409  else
8410  {
8411  mCustomHeaders.erase(headerName);
8412  }
8413  }
8414 }
8415 
8416 /**
8417  * @brief UpdateLiveOffset live offset [Sec]
8418  */
8420 {
8421  if(!IsLiveAdjustRequired()) /* Ideally checking the content is either "ivod/cdvr" to adjust the liveoffset on trickplay. */
8422  {
8423  GETCONFIGVALUE_PRIV(eAAMPConfig_CDVRLiveOffset,mLiveOffset);
8424  }
8425  else
8426  {
8427  GETCONFIGVALUE_PRIV(eAAMPConfig_LiveOffset,mLiveOffset);
8428  }
8429  AAMPLOG_INFO("Live offset value updated to %lf", mLiveOffset);
8430 }
8431 
8432 /**
8433  * @brief Send stalled event to listeners
8434  */
8436 {
8437  char description[MAX_ERROR_DESCRIPTION_LENGTH];
8438  memset(description, '\0', MAX_ERROR_DESCRIPTION_LENGTH);
8439  int stalltimeout;
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);
8443 }
8444 
8445 /**
8446  * @brief Sets up the timestamp sync for subtitle renderer
8447  */
8449 {
8451  {
8453  }
8454 }
8455 
8456 /**
8457  * @brief pause/un-pause subtitles
8458  *
8459  */
8461 {
8463  {
8465  }
8466 }
8467 
8468 /**
8469  * @brief Notify if first buffer processed by gstreamer
8470  */
8472 {
8473  // If mFirstVideoFrameDisplayedEnabled, state will be changed in NotifyFirstVideoDisplayed()
8474  PrivAAMPState state;
8475  GetState(state);
8476 
8477  // In the middle of stop processing we can receive state changing callback (xione-7331)
8478  if (state == eSTATE_IDLE)
8479  {
8480  AAMPLOG_WARN( "skipped as in IDLE state" );
8481  return;
8482  }
8483 
8485  && state == eSTATE_SEEKING)
8486  {
8488  }
8489  trickStartUTCMS = aamp_GetCurrentTimeMS();
8490  AAMPLOG_WARN("seek pos %.3f", seek_pos_seconds);
8491 
8492 
8493 #ifdef USE_SECMANAGER
8494  if(ISCONFIGSET_PRIV(eAAMPConfig_UseSecManager))
8495  {
8496  //Thread to call setplayback speed as it needs a 500ms delay here
8497  std::thread t([&](){
8498  mDRMSessionManager->setPlaybackSpeedState(rate,seek_pos_seconds, true);});
8499  t.detach();
8500  int x,y,w,h;
8501  sscanf(mStreamSink->GetVideoRectangle().c_str(),"%d,%d,%d,%d",&x,&y,&w,&h);
8502  AAMPLOG_WARN("calling setVideoWindowSize w:%d x h:%d ",w,h);
8503  mDRMSessionManager->setVideoWindowSize(w,h);
8504  }
8505 #endif
8506 
8507 }
8508 
8509 /**
8510  * @brief Reset trick start position
8511  */
8513 {
8514  trickStartUTCMS = aamp_GetCurrentTimeMS();
8515 }
8516 
8517 /**
8518  * @brief Get stream type
8519  */
8521 {
8522 
8523  int type = 0;
8524 
8525  if(mMediaFormat == eMEDIAFORMAT_DASH)
8526  {
8527  type = 20;
8528  }
8529  else if( mMediaFormat == eMEDIAFORMAT_HLS)
8530  {
8531  type = 10;
8532  }
8533  else if (mMediaFormat == eMEDIAFORMAT_PROGRESSIVE)// eMEDIAFORMAT_PROGRESSIVE
8534  {
8535  type = 30;
8536  }
8537  else if (mMediaFormat == eMEDIAFORMAT_HLS_MP4)
8538  {
8539  type = 40;
8540  }
8541  else
8542  {
8543  type = 0;
8544  }
8545 
8546  if (mCurrentDrm != nullptr) {
8547  type += mCurrentDrm->getDrmCodecType();
8548  }
8549  return type;
8550 }
8551 
8552 /**
8553  * @brief Get Mediaformat type
8554  *
8555  * @returns eMEDIAFORMAT
8556  */
8558 {
8559  return mMediaFormat;
8560 }
8561 
8562 #if defined(USE_SECCLIENT) || defined(USE_SECMANAGER)
8563 
8564 /**
8565  * @brief Extracts / Generates MoneyTrace string
8566  */
8567 void PrivateInstanceAAMP::GetMoneyTraceString(std::string &customHeader) const
8568 {
8569  char moneytracebuf[512];
8570  memset(moneytracebuf, 0, sizeof(moneytracebuf));
8571 
8572  if (mCustomHeaders.size() > 0)
8573  {
8574  for (std::unordered_map<std::string, std::vector<std::string>>::const_iterator it = mCustomHeaders.begin();
8575  it != mCustomHeaders.end(); it++)
8576  {
8577  if (it->first.compare("X-MoneyTrace:") == 0)
8578  {
8579  if (it->second.size() >= 2)
8580  {
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(),
8585  }
8586  else if (it->second.size() == 1)
8587  {
8588  snprintf(moneytracebuf, sizeof(moneytracebuf), "trace-id=%s;parent-id=%lld;span-id=%lld",
8589  (const char*)it->second.at(0).c_str(),
8592  }
8593  customHeader.append(moneytracebuf);
8594  break;
8595  }
8596  }
8597  }
8598  // No money trace is available in customheader from JS , create a new moneytrace locally
8599  if(customHeader.size() == 0)
8600  {
8601  // No Moneytrace info available in tune data
8602  AAMPLOG_WARN("No Moneytrace info available in tune request,need to generate one");
8603  uuid_t uuid;
8604  uuid_generate(uuid);
8605  char uuidstr[128];
8606  uuid_unparse(uuid, uuidstr);
8607  for (char *ptr = uuidstr; *ptr; ++ptr) {
8608  *ptr = tolower(*ptr);
8609  }
8610  snprintf(moneytracebuf,sizeof(moneytracebuf),"trace-id=%s;parent-id=%lld;span-id=%lld",uuidstr,aamp_GetCurrentTimeMS(),aamp_GetCurrentTimeMS());
8611  customHeader.append(moneytracebuf);
8612  }
8613  AAMPLOG_TRACE("[GetMoneyTraceString] MoneyTrace[%s]",customHeader.c_str());
8614 }
8615 #endif /* USE_SECCLIENT || USE_SECMANAGER */
8616 
8617 /**
8618  * @brief Notify the decryption completion of the fist fragment.
8619  */
8621 {
8622  if(mTunedEventPending)
8623  {
8624  if (eTUNED_EVENT_ON_FIRST_FRAGMENT_DECRYPTED == GetTuneEventConfig(IsLive()))
8625  {
8626  // For HLS - This is invoked by fetcher thread, so we have to sent asynchronously
8627  if (SendTunedEvent(false))
8628  {
8629  AAMPLOG_WARN("aamp: %s - sent tune event after first fragment fetch and decrypt", mMediaFormatName[mMediaFormat]);
8630  }
8631  }
8632  }
8633 }
8634 
8635 /**
8636  * @brief Get PTS of first sample.
8637  */
8639 {
8640  assert(NULL != mpStreamAbstractionAAMP);
8642 }
8643 
8644 /**
8645  * @brief Check if Live Adjust is required for current content. ( For "vod/ivod/ip-dvr/cdvr/eas", Live Adjust is not required ).
8646  */
8648 {
8649  bool retValue;
8650 
8651  switch (mContentType)
8652  {
8653  case ContentType_IVOD:
8654  case ContentType_VOD:
8655  case ContentType_CDVR:
8656  case ContentType_IPDVR:
8657  case ContentType_EAS:
8658  retValue = false;
8659  break;
8660 
8661  case ContentType_SLE:
8662  retValue = true;
8663  break;
8664 
8665  default:
8666  retValue = true;
8667  break;
8668  }
8669  return retValue;
8670 }
8671 
8672 /**
8673  * @brief Generate http header response event
8674  */
8676 {
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());
8681  }
8682 }
8683 
8684 /**
8685  * @brief Generate media metadata event based on parsed attribute values.
8686  *
8687  */
8689 {
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 };
8693  int langCount = 0;
8694  int bitrateCount = 0;
8695  int supportedSpeedCount = 0;
8696  int width = 1280;
8697  int height = 720;
8698 
8699  bitrateList = mpStreamAbstractionAAMP->GetVideoBitrates();
8700  for (int i = 0; i <mMaxLanguageCount; i++)
8701  {
8702  langList.insert(mLanguageList[i]);
8703  }
8704 
8705  GetPlayerVideoSize(width, height);
8706 
8707  std::string drmType = "NONE";
8708  std::shared_ptr<AampDrmHelper> helper = GetCurrentDRM();
8709  if (helper)
8710  {
8711  drmType = helper->friendlyName();
8712  }
8713 
8714  MediaMetadataEventPtr event = std::make_shared<MediaMetadataEvent>(CONVERT_SEC_TO_MS(durationSeconds), width, height, mpStreamAbstractionAAMP->hasDrm, IsLive(), drmType, mpStreamAbstractionAAMP->mProgramStartTime);
8715 
8716  for (auto iter = langList.begin(); iter != langList.end(); iter++)
8717  {
8718  if (!iter->empty())
8719  {
8720  // assert if size >= < MAX_LANGUAGE_TAG_LENGTH
8721  assert(iter->size() < MAX_LANGUAGE_TAG_LENGTH);
8722  event->addLanguage((*iter));
8723  }
8724  }
8725 
8726  for (int i = 0; i < bitrateList.size(); i++)
8727  {
8728  event->addBitrate(bitrateList[i]);
8729  }
8730 
8731  //Iframe track present and hence playbackRate change is supported
8733  {
8734  if(!(ISCONFIGSET_PRIV(eAAMPConfig_EnableSlowMotion)))
8735  {
8736  auto position = std::find(supportedPlaybackSpeeds.begin(), supportedPlaybackSpeeds.end(), 0.5);
8737  if(position != supportedPlaybackSpeeds.end())
8738  {
8739  supportedPlaybackSpeeds.erase(position); //remove 0.5 from supported speeds
8740  }
8741  }
8742 
8743  for(int i = 0; i < supportedPlaybackSpeeds.size(); i++)
8744  {
8745  event->addSupportedSpeed(supportedPlaybackSpeeds[i]);
8746  }
8747  }
8748  else
8749  {
8750  //Supports only pause and play
8751  event->addSupportedSpeed(0);
8752  if(ISCONFIGSET_PRIV(eAAMPConfig_EnableSlowMotion))
8753  {
8754  event->addSupportedSpeed(0.5);
8755  }
8756  event->addSupportedSpeed(1);
8757  }
8758 
8759  event->setMediaFormat(mMediaFormatName[mMediaFormat]);
8760 
8762 }
8763 
8764 /**
8765  * @brief Generate supported speeds changed event based on arg passed.
8766  */
8768 {
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;
8772 
8773  //Iframe track present and hence playbackRate change is supported
8774  if (isIframeTrackPresent)
8775  {
8776  if(!(ISCONFIGSET_PRIV(eAAMPConfig_EnableSlowMotion)))
8777  {
8778  auto position = std::find(supportedPlaybackSpeeds.begin(), supportedPlaybackSpeeds.end(), 0.5);
8779  if(position != supportedPlaybackSpeeds.end())
8780  {
8781  supportedPlaybackSpeeds.erase(position); //remove 0.5 from supported speeds
8782  }
8783  }
8784 
8785  for(int i = 0; i < supportedPlaybackSpeeds.size(); i++)
8786  {
8787  event->addSupportedSpeed(supportedPlaybackSpeeds[i]);;
8788  }
8789  }
8790  else
8791  {
8792  //Supports only pause and play
8793  event->addSupportedSpeed(0);
8794  if(ISCONFIGSET_PRIV(eAAMPConfig_EnableSlowMotion))
8795  {
8796  event->addSupportedSpeed(0.5);
8797  }
8798  event->addSupportedSpeed(1);
8799  }
8800 
8801  AAMPLOG_WARN("aamp: sending supported speeds changed event with count %d", event->getSupportedSpeedCount());
8803 }
8804 
8805 /**
8806  * @brief Generate Blocked event based on args passed.
8807  */
8808 void PrivateInstanceAAMP::SendBlockedEvent(const std::string & reason)
8809 {
8810  BlockedEventPtr event = std::make_shared<BlockedEvent>(reason);
8812 #ifdef AAMP_CC_ENABLED
8813  if (0 == reason.compare("SERVICE_PIN_LOCKED"))
8814  {
8815  if (ISCONFIGSET_PRIV(eAAMPConfig_NativeCCRendering))
8816  {
8818  }
8819  }
8820 #endif
8821 }
8822 
8823 /**
8824  * @brief Generate WatermarkSessionUpdate event based on args passed.
8825  */
8826 void PrivateInstanceAAMP::SendWatermarkSessionUpdateEvent(uint32_t sessionHandle, uint32_t status, const std::string &system)
8827 {
8828  WatermarkSessionUpdateEventPtr event = std::make_shared<WatermarkSessionUpdateEvent>(sessionHandle, status, system);
8830 }
8831 
8832 /**
8833  * @brief Check if tune completed or not.
8834  */
8836 {
8837  return mTuneCompleted;
8838 }
8839 
8840 /**
8841  * @brief Get Preferred DRM.
8842  */
8844 {
8845  int drmType;
8846  GETCONFIGVALUE_PRIV(eAAMPConfig_PreferredDRM,drmType);
8847  return (DRMSystems)drmType;
8848 }
8849 
8850 /**
8851  * @brief Notification from the stream abstraction that a new SCTE35 event is found.
8852  */
8853 void PrivateInstanceAAMP::FoundEventBreak(const std::string &adBreakId, uint64_t startMS, EventBreakInfo brInfo)
8854 {
8855  if(ISCONFIGSET_PRIV(eAAMPConfig_EnableClientDai) && !adBreakId.empty())
8856  {
8857  AAMPLOG_WARN("[CDAI] Found Adbreak on period[%s] Duration[%d]", adBreakId.c_str(), brInfo.duration);
8858  std::string adId("");
8859  std::string url("");
8860  mCdaiObject->SetAlternateContents(adBreakId, adId, url, startMS, brInfo.duration); //A placeholder to avoid multiple scte35 event firing for the same adbreak
8861  SaveNewTimedMetadata((long long) startMS, brInfo.name.c_str(), brInfo.payload.c_str(), brInfo.payload.size(), adBreakId.c_str(), brInfo.duration);
8862  }
8863 }
8864 
8865 /**
8866  * @brief Setting the alternate contents' (Ads/blackouts) URL
8867  */
8868 void PrivateInstanceAAMP::SetAlternateContents(const std::string &adBreakId, const std::string &adId, const std::string &url)
8869 {
8870  if(ISCONFIGSET_PRIV(eAAMPConfig_EnableClientDai))
8871  {
8872  mCdaiObject->SetAlternateContents(adBreakId, adId, url);
8873  }
8874  else
8875  {
8876  AAMPLOG_WARN("is called! CDAI not enabled!! Rejecting the promise.");
8877  SendAdResolvedEvent(adId, false, 0, 0);
8878  }
8879 }
8880 
8881 /**
8882  * @brief Send status of Ad manifest downloading & parsing
8883  */
8884 void PrivateInstanceAAMP::SendAdResolvedEvent(const std::string &adId, bool status, uint64_t startMS, uint64_t durationMs)
8885 {
8886  if (mDownloadsEnabled) //Send it, only if Stop not called
8887  {
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());
8891  }
8892 }
8893 
8894 /**
8895  * @brief Deliver all pending Ad events to JSPP
8896  */
8898 {
8899  std::lock_guard<std::mutex> lock(mAdEventQMtx);
8900  while (!mAdEventsQ.empty())
8901  {
8902  AAMPEventPtr e = mAdEventsQ.front();
8903  if(immediate)
8904  {
8906  }
8907  else
8908  {
8910  }
8911  AAMPEventType evtType = e->getType();
8912  AAMPLOG_WARN("PrivateInstanceAAMP:, [CDAI] Delivered AdEvent[%s] to JSPP.", ADEVENT2STRING(evtType));
8913  if(AAMP_EVENT_AD_PLACEMENT_START == evtType)
8914  {
8915  AdPlacementEventPtr placementEvt = std::dynamic_pointer_cast<AdPlacementEvent>(e);
8916  mAdProgressId = placementEvt->getAdId();
8917  mAdPrevProgressTime = NOW_STEADY_TS_MS;
8918  mAdCurOffset = placementEvt->getOffset();
8919  mAdDuration = placementEvt->getDuration();
8920  }
8921  else if(AAMP_EVENT_AD_PLACEMENT_END == evtType || AAMP_EVENT_AD_PLACEMENT_ERROR == evtType)
8922  {
8923  mAdProgressId = "";
8924  }
8925  mAdEventsQ.pop();
8926  }
8927 }
8928 
8929 /**
8930  * @brief Send Ad reservation event
8931  */
8932 void PrivateInstanceAAMP::SendAdReservationEvent(AAMPEventType type, const std::string &adBreakId, uint64_t position, bool immediate)
8933 {
8935  {
8936  AAMPLOG_INFO("PrivateInstanceAAMP: [CDAI] Pushed [%s] of adBreakId[%s] to Queue.", ADEVENT2STRING(type), adBreakId.c_str());
8937 
8938  AdReservationEventPtr e = std::make_shared<AdReservationEvent>(type, adBreakId, position);
8939 
8940  {
8941  {
8942  std::lock_guard<std::mutex> lock(mAdEventQMtx);
8943  mAdEventsQ.push(e);
8944  }
8945  if(immediate)
8946  {
8947  //Despatch all ad events now
8948  DeliverAdEvents(true);
8949  }
8950  }
8951  }
8952 }
8953 
8954 /**
8955  * @brief Send Ad placement event
8956  */
8957 void PrivateInstanceAAMP::SendAdPlacementEvent(AAMPEventType type, const std::string &adId, uint32_t position, uint32_t adOffset, uint32_t adDuration, bool immediate, long error_code)
8958 {
8959  if(AAMP_EVENT_AD_PLACEMENT_START <= type && AAMP_EVENT_AD_PLACEMENT_ERROR >= type)
8960  {
8961  AAMPLOG_INFO("PrivateInstanceAAMP: [CDAI] Pushed [%s] of adId[%s] to Queue.", ADEVENT2STRING(type), adId.c_str());
8962 
8963  AdPlacementEventPtr e = std::make_shared<AdPlacementEvent>(type, adId, position, adOffset * 1000 /*MS*/, adDuration, error_code);
8964 
8965  {
8966  {
8967  std::lock_guard<std::mutex> lock(mAdEventQMtx);
8968  mAdEventsQ.push(e);
8969  }
8970  if(immediate)
8971  {
8972  //Despatch all ad events now
8973  DeliverAdEvents(true);
8974  }
8975  }
8976  }
8977 }
8978 
8979 /**
8980  * @brief Get stream type as printable format
8981  */
8983 {
8984  std::string type = mMediaFormatName[mMediaFormat];
8985 
8986  if(mCurrentDrm != nullptr) //Incomplete Init won't be set the DRM
8987  {
8988  type += "/";
8989  type += mCurrentDrm->friendlyName();
8990  }
8991  else
8992  {
8993  type += "/Clear";
8994  }
8995  return type;
8996 }
8997 
8998 /**
8999  * @brief Convert media file type to profiler bucket type
9000  */
9002 {
9003  ProfilerBucketType pbt;
9004  switch(fileType)
9005  {
9006  case eMEDIATYPE_VIDEO:
9008  break;
9009  case eMEDIATYPE_AUDIO:
9011  break;
9012  case eMEDIATYPE_SUBTITLE:
9014  break;
9015  case eMEDIATYPE_AUX_AUDIO:
9017  break;
9018  case eMEDIATYPE_MANIFEST:
9020  break;
9021  case eMEDIATYPE_INIT_VIDEO:
9023  break;
9024  case eMEDIATYPE_INIT_AUDIO:
9026  break;
9029  break;
9032  break;
9035  break;
9038  break;
9041  break;
9044  break;
9045  default:
9046  pbt = (ProfilerBucketType)fileType;
9047  break;
9048  }
9049  return pbt;
9050 }
9051 
9052 /**
9053  * @brief Sets Recorded URL from Manifest received form XRE
9054  */
9056 {
9057  mTunedManifestUrl.assign(mManifestUrl);
9058  AAMPLOG_TRACE("mManifestUrl: %s",mManifestUrl.c_str());
9059  if(isrecordedUrl)
9060  {
9061  DeFog(mTunedManifestUrl);
9062  mTunedManifestUrl.replace(0,4,"_fog");
9063  }
9064  AAMPLOG_TRACE("PrivateInstanceAAMP::tunedManifestUrl:%s ", mTunedManifestUrl.c_str());
9065 }
9066 
9067 /**
9068  * @brief Gets Recorded URL from Manifest received form XRE.
9069  */
9071 {
9072  AAMPLOG_TRACE("PrivateInstanceAAMP::tunedManifestUrl:%s ", mTunedManifestUrl.c_str());
9073  return mTunedManifestUrl.c_str();
9074 }
9075 
9076 /**
9077  * @brief To get the network proxy
9078  */
9080 {
9081  std::string proxy;
9082  GETCONFIGVALUE_PRIV(eAAMPConfig_NetworkProxy,proxy);
9083  return proxy;
9084 }
9085 
9086 /**
9087  * @brief To get the proxy for license request
9088  */
9090 {
9091  std::string proxy;
9092  GETCONFIGVALUE_PRIV(eAAMPConfig_LicenseProxy,proxy);
9093  return proxy;
9094 }
9095 
9096 
9097 /**
9098  * @brief Signal trick mode discontinuity to stream sink
9099  */
9101 {
9102  if (mStreamSink)
9103  {
9104  mStreamSink->SignalTrickModeDiscontinuity();
9105  }
9106 }
9107 
9108 /**
9109  * @brief Check if current stream is muxed
9110  */
9112 {
9113  bool ret = false;
9115  {
9117  }
9118  return ret;
9119 }
9120 
9121 /**
9122  * @brief Stop injection for a track.
9123  * Called from StopInjection
9124  */
9126 {
9127 #ifdef AAMP_DEBUG_FETCH_INJECT
9128  if ((1 << type) & AAMP_DEBUG_FETCH_INJECT)
9129  {
9130  AAMPLOG_WARN ("PrivateInstanceAAMP: Enter. type = %d", (int) type);
9131  }
9132 #endif
9133  if (!mTrackInjectionBlocked[type])
9134  {
9135  AAMPLOG_TRACE("PrivateInstanceAAMP: for type %s", (type == eMEDIATYPE_AUDIO) ? "audio" : "video");
9136  pthread_mutex_lock(&mLock);
9137  mTrackInjectionBlocked[type] = true;
9138  pthread_mutex_unlock(&mLock);
9139  }
9140  AAMPLOG_TRACE ("PrivateInstanceAAMP::Exit. type = %d", (int) type);
9141 }
9142 
9143 /**
9144  * @brief Resume injection for a track.
9145  * Called from StartInjection
9146  */
9148 {
9149 #ifdef AAMP_DEBUG_FETCH_INJECT
9150  if ((1 << type) & AAMP_DEBUG_FETCH_INJECT)
9151  {
9152  AAMPLOG_WARN ("PrivateInstanceAAMP: Enter. type = %d", (int) type);
9153  }
9154 #endif
9155  if (mTrackInjectionBlocked[type])
9156  {
9157  AAMPLOG_TRACE("PrivateInstanceAAMP: for type %s", (type == eMEDIATYPE_AUDIO) ? "audio" : "video");
9158  pthread_mutex_lock(&mLock);
9159  mTrackInjectionBlocked[type] = false;
9160  pthread_mutex_unlock(&mLock);
9161  }
9162  AAMPLOG_TRACE ("PrivateInstanceAAMP::Exit. type = %d", (int) type);
9163 }
9164 
9165 /**
9166  * @brief Receives first video PTS of the current playback
9167  */
9168 void PrivateInstanceAAMP::NotifyFirstVideoPTS(unsigned long long pts, unsigned long timeScale)
9169 {
9171  {
9173  }
9174 }
9175 
9176 /**
9177  * @brief Notifies base PTS of the HLS video playback
9178  */
9179 void PrivateInstanceAAMP::NotifyVideoBasePTS(unsigned long long basepts, unsigned long timeScale)
9180 {
9181  mVideoBasePTS = basepts;
9182  AAMPLOG_INFO("mVideoBasePTS::%llus", mVideoBasePTS);
9183 }
9184 
9185 /**
9186  * @brief To send webvtt cue as an event
9187  */
9189 {
9190  //This function is called from an idle handler and hence we call SendEventSync
9192  {
9193  WebVttCueEventPtr ev = std::make_shared<WebVttCueEvent>(cue);
9195  }
9196 }
9197 
9198 /**
9199  * @brief To check if subtitles are enabled
9200  */
9202 {
9203  // Assumption being that enableSubtec and event listener will not be registered at the same time
9204  // in which case subtec gets priority over event listener
9205  return (ISCONFIGSET_PRIV(eAAMPConfig_Subtec_subtitle) || WebVTTCueListenersRegistered());
9206 }
9207 
9208 /**
9209  * @brief To check if JavaScript cue listeners are registered
9210  */
9212 {
9214 }
9215 
9216 /**
9217  * @brief To get any custom license HTTP headers that was set by application
9218  */
9219 void PrivateInstanceAAMP::GetCustomLicenseHeaders(std::unordered_map<std::string, std::vector<std::string>>& customHeaders)
9220 {
9221  customHeaders.insert(mCustomLicenseHeaders.begin(), mCustomLicenseHeaders.end());
9222 }
9223 
9224 /**
9225  * @brief Sends an ID3 metadata event.
9226  */
9228 {
9229  if(id3Metadata) {
9230  ID3MetadataEventPtr e = std::make_shared<ID3MetadataEvent>(id3Metadata->data, id3Metadata->schemeIdUri, id3Metadata->value, id3Metadata->timeScale, id3Metadata->presentationTime, id3Metadata->eventDuration, id3Metadata->id, id3Metadata->timestampOffset);
9231  if (ISCONFIGSET_PRIV(eAAMPConfig_ID3Logging))
9232  {
9233  std::vector<uint8_t> metadata = e->getMetadata();
9234  int metadataLen = e->getMetadataSize();
9235  int printableLen = 0;
9236  std::ostringstream tag;
9237 
9238  tag << "ID3 tag length: " << metadataLen;
9239 
9240  if (metadataLen > 0 )
9241  {
9242  tag << " payload: ";
9243 
9244  for (int i = 0; i < metadataLen; i++)
9245  {
9246  if (std::isprint(metadata[i]))
9247  {
9248  tag << metadata[i];
9249  printableLen++;
9250  }
9251  }
9252  }
9253  // Logger has a maximum message size limit, warn if too big
9254  // Current large ID3 tag size is 1055, but printable < MAX_DEBUG_LOG_BUFF_SIZE.
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());
9258 
9259  if (printableLen > MAX_DEBUG_LOG_BUFF_SIZE)
9260  {
9261  AAMPLOG_WARN("ID3 log was truncated, original size %d (printable %d)" , metadataLen, printableLen);
9262  }
9263  }
9265  }
9266 }
9267 
9268 /**
9269  * @brief Sending a flushing seek to stream sink with given position
9270  */
9271 void PrivateInstanceAAMP::FlushStreamSink(double position, double rate)
9272 {
9273 #ifndef AAMP_STOP_SINK_ON_SEEK
9274  if (mStreamSink)
9275  {
9276  if(ISCONFIGSET_PRIV(eAAMPConfig_MidFragmentSeek) && position != 0 )
9277  {
9278  //RDK-26957 Adding midSeekPtsOffset to position value.
9279  //Enables us to seek to the desired position in the mp4 fragment.
9280  mStreamSink->SeekStreamSink(position + GetFirstPTS(), rate);
9281  }
9282  else
9283  {
9284  mStreamSink->SeekStreamSink(position, rate);
9285  }
9286  }
9287 #endif
9288 }
9289 
9290 /**
9291  * @brief PreCachePlaylistDownloadTask Thread function for PreCaching Playlist
9292  */
9294 {
9295  // This is the thread function to download all the HLS Playlist in a
9296  // differed manner
9297  int maxWindowforDownload = mPreCacheDnldTimeWindow * 60; // convert to seconds
9298  int szPlaylistCount = mPreCacheDnldList.size();
9299  if(szPlaylistCount)
9300  {
9301  PrivAAMPState state;
9302  // First wait for Tune to complete to start this functionality
9303  pthread_mutex_lock(&mMutexPlaystart);
9304  pthread_cond_wait(&waitforplaystart, &mMutexPlaystart);
9305  pthread_mutex_unlock(&mMutexPlaystart);
9306  // May be Stop is called to release all resources .
9307  // Before download , check the state
9308  GetState(state);
9309  // Check for state not IDLE also to avoid DELIA-46092
9310  if(state != eSTATE_RELEASED && state != eSTATE_IDLE && state != eSTATE_ERROR)
9311  {
9313  SetCurlTimeout(mPlaylistTimeoutMs, eCURLINSTANCE_PLAYLISTPRECACHE);
9314  int sleepTimeBetweenDnld = (maxWindowforDownload / szPlaylistCount) * 1000; // time in milliSec
9315  int idx = 0;
9316  do
9317  {
9318  if(DownloadsAreEnabled())
9319  {
9320  InterruptableMsSleep(sleepTimeBetweenDnld);
9321 
9322  // First check if the file is already in Cache
9323  PreCacheUrlStruct newelem = mPreCacheDnldList.at(idx);
9324 
9325  // check if url cached ,if not download
9326  if(getAampCacheHandler()->IsUrlCached(newelem.url)==false)
9327  {
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;
9332  GrowableBuffer playlistStore ;
9333  long http_error;
9334  double downloadTime;
9335  if(GetFile(newelem.url, &playlistStore, playlistEffectiveUrl, &http_error, &downloadTime, NULL, eCURLINSTANCE_PLAYLISTPRECACHE, true, newelem.type))
9336  {
9337  // If successful download , then insert into Cache
9338  getAampCacheHandler()->InsertToPlaylistCache(newelem.url, &playlistStore, playlistEffectiveUrl, false, newelem.type);
9339  aamp_Free(&playlistStore);
9340  }
9341  }
9342  idx++;
9343  }
9344  else
9345  {
9346  // this can come here if trickplay is done or play started late
9347  if(state == eSTATE_SEEKING || state == eSTATE_PREPARED)
9348  {
9349  // wait for seek to complete
9350  sleep(1);
9351  }
9352  else
9353  {
9354  usleep(500000); // call sleep for other stats except seeking and prepared, otherwise this thread will run in highest priority until the state changes.
9355  }
9356  }
9357  GetState(state);
9358  }while (idx < mPreCacheDnldList.size() && state != eSTATE_RELEASED && state != eSTATE_IDLE && state != eSTATE_ERROR);
9359  mPreCacheDnldList.clear();
9361  }
9362  }
9363  AAMPLOG_WARN("End of PreCachePlaylistDownloadTask ");
9364 }
9365 
9366 /**
9367  * @brief SetPreCacheDownloadList - Function to assign the PreCaching file list
9368  */
9369 void PrivateInstanceAAMP::SetPreCacheDownloadList(PreCacheUrlList &dnldListInput)
9370 {
9371  mPreCacheDnldList = dnldListInput;
9372  if(mPreCacheDnldList.size())
9373  {
9374  AAMPLOG_WARN("Got Playlist PreCache list of Size : %lu", mPreCacheDnldList.size());
9375  }
9376 
9377 }
9378 
9379 /**
9380  * @brief get the current text preference set by user
9381  *
9382  * @return json string with preference data
9383  */
9385 {
9386  //Convert to JSON format
9387  std::string preferrence;
9388  cJSON *item;
9389  item = cJSON_CreateObject();
9390  if(!preferredTextLanguagesString.empty())
9391  {
9392  cJSON_AddStringToObject(item, "preferred-text-languages", preferredTextLanguagesString.c_str());
9393  }
9394  if(!preferredTextLabelString.empty())
9395  {
9396  cJSON_AddStringToObject(item, "preferred-text-labels", preferredTextLabelString.c_str());
9397  }
9398  if(!preferredTextRenditionString.empty())
9399  {
9400  cJSON_AddStringToObject(item, "preferred-text-rendition", preferredTextRenditionString.c_str());
9401  }
9402  if(!preferredTextTypeString.empty())
9403  {
9404  cJSON_AddStringToObject(item, "preferred-text-type", preferredTextTypeString.c_str());
9405  }
9406  if(!preferredTextAccessibilityNode.getSchemeId().empty())
9407  {
9408  cJSON *accessibility = cJSON_AddObjectToObject(item, "preferred-text-accessibility");
9409  cJSON_AddStringToObject(accessibility, "schemeId", preferredTextAccessibilityNode.getSchemeId().c_str());
9410  if (preferredTextAccessibilityNode.getTypeName() == "int_value")
9411  {
9412  cJSON_AddNumberToObject(accessibility, preferredTextAccessibilityNode.getTypeName().c_str(), preferredTextAccessibilityNode.getIntValue());
9413  }else
9414  {
9415  cJSON_AddStringToObject(accessibility, preferredTextAccessibilityNode.getTypeName().c_str(), preferredTextAccessibilityNode.getStrValue().c_str());
9416  }
9417  }
9418  char *jsonStr = cJSON_Print(item);
9419  if (jsonStr)
9420  {
9421  preferrence.assign(jsonStr);
9422  free(jsonStr);
9423  }
9424  cJSON_Delete(item);
9425  return preferrence;
9426 }
9427 
9428 /**
9429  * @brief get the current audio preference set by user
9430  */
9432 {
9433  //Convert to JSON format
9434  std::string preferrence;
9435  cJSON *item;
9436  item = cJSON_CreateObject();
9437  if(!preferredLanguagesString.empty())
9438  {
9439  cJSON_AddStringToObject(item, "preferred-audio-languages", preferredLanguagesString.c_str());
9440  }
9441  if(!preferredLabelsString.empty())
9442  {
9443  cJSON_AddStringToObject(item, "preferred-audio-labels", preferredLabelsString.c_str());
9444  }
9445  if(!preferredCodecString.empty())
9446  {
9447  cJSON_AddStringToObject(item, "preferred-audio-codecs", preferredCodecString.c_str());
9448  }
9449  if(!preferredRenditionString.empty())
9450  {
9451  cJSON_AddStringToObject(item, "preferred-audio-rendition", preferredRenditionString.c_str());
9452  }
9453  if(!preferredTypeString.empty())
9454  {
9455  cJSON_AddStringToObject(item, "preferred-audio-type", preferredTypeString.c_str());
9456  }
9457  if(!preferredAudioAccessibilityNode.getSchemeId().empty())
9458  {
9459  cJSON * accessibility = cJSON_AddObjectToObject(item, "preferred-audio-accessibility");
9460  cJSON_AddStringToObject(accessibility, "schemeId", preferredAudioAccessibilityNode.getSchemeId().c_str());
9461  if (preferredAudioAccessibilityNode.getTypeName() == "int_value")
9462  {
9463  cJSON_AddNumberToObject(accessibility, preferredAudioAccessibilityNode.getTypeName().c_str(), preferredAudioAccessibilityNode.getIntValue());
9464  }else
9465  {
9466  cJSON_AddStringToObject(accessibility, preferredAudioAccessibilityNode.getTypeName().c_str(), preferredAudioAccessibilityNode.getStrValue().c_str());
9467  }
9468  }
9469  char *jsonStr = cJSON_Print(item);
9470  if (jsonStr)
9471  {
9472  preferrence.assign(jsonStr);
9473  free(jsonStr);
9474  }
9475  cJSON_Delete(item);
9476  return preferrence;
9477 }
9478 
9479 /**
9480  * @brief Get available video tracks.
9481  */
9483 {
9484  std::string tracks;
9485 
9486  pthread_mutex_lock(&mStreamLock);
9488  {
9489  std::vector <StreamInfo*> trackInfo = mpStreamAbstractionAAMP->GetAvailableVideoTracks();
9490  if (!trackInfo.empty())
9491  {
9492  //Convert to JSON format
9493  cJSON *root;
9494  cJSON *item;
9495  root = cJSON_CreateArray();
9496  if(root)
9497  {
9498  for (int i = 0; i < trackInfo.size(); i++)
9499  {
9500  cJSON_AddItemToArray(root, item = cJSON_CreateObject());
9501  if (trackInfo[i]->bandwidthBitsPerSecond != -1)
9502  {
9503  cJSON_AddNumberToObject(item, "bandwidth", trackInfo[i]->bandwidthBitsPerSecond);
9504  }
9505  if (trackInfo[i]->resolution.width != -1)
9506  {
9507  cJSON_AddNumberToObject(item, "width", trackInfo[i]->resolution.width);
9508  }
9509  if (trackInfo[i]->resolution.height != -1)
9510  {
9511  cJSON_AddNumberToObject(item, "height", trackInfo[i]->resolution.height);
9512  }
9513  if (trackInfo[i]->resolution.framerate != -1)
9514  {
9515  cJSON_AddNumberToObject(item, "framerate", trackInfo[i]->resolution.framerate);
9516  }
9517 
9518  cJSON_AddNumberToObject(item, "enabled", trackInfo[i]->enabled);
9519 
9520  if (trackInfo[i]->codecs)
9521  {
9522  cJSON_AddStringToObject(item, "codec", trackInfo[i]->codecs);
9523  }
9524  }
9525  char *jsonStr = cJSON_Print(root);
9526  if (jsonStr)
9527  {
9528  tracks.assign(jsonStr);
9529  free(jsonStr);
9530  }
9531  cJSON_Delete(root);
9532  }
9533  }
9534  else
9535  {
9536  AAMPLOG_ERR("PrivateInstanceAAMP: No available video track information!");
9537  }
9538  }
9539  pthread_mutex_unlock(&mStreamLock);
9540  return tracks;
9541 }
9542 
9543 /**
9544  * @brief set birate for video tracks selection
9545  */
9546 void PrivateInstanceAAMP::SetVideoTracks(std::vector<long> bitrateList)
9547 {
9548  int bitrateSize = bitrateList.size();
9549  //clear cached bitrate list
9550  this->bitrateList.clear();
9551  // user profile stats enabled only for valid bitrate list, otherwise disabled for empty bitrates
9552  this->userProfileStatus = (bitrateSize > 0) ? true : false;
9553  AAMPLOG_INFO("User Profile filtering bitrate size:%d status:%d", bitrateSize, this->userProfileStatus);
9554  for (int i = 0; i < bitrateSize; i++)
9555  {
9556  this->bitrateList.push_back(bitrateList.at(i));
9557  AAMPLOG_WARN("User Profile Index : %d(%d) Bw : %ld", i, bitrateSize, bitrateList.at(i));
9558  }
9559  PrivAAMPState state;
9560  GetState(state);
9561  if (state > eSTATE_PREPARING)
9562  {
9566  }
9567 }
9568 
9569 /**
9570  * @brief Get available audio tracks.
9571  */
9573 {
9574  std::string tracks;
9575 
9576  pthread_mutex_lock(&mStreamLock);
9578  {
9579  std::vector<AudioTrackInfo> trackInfo = mpStreamAbstractionAAMP->GetAvailableAudioTracks(allTrack);
9580  if (!trackInfo.empty())
9581  {
9582  //Convert to JSON format
9583  cJSON *root;
9584  cJSON *item;
9585  cJSON *accessbilityArray = NULL;
9586  root = cJSON_CreateArray();
9587  if(root)
9588  {
9589  for (auto iter = trackInfo.begin(); iter != trackInfo.end(); iter++)
9590  {
9591  cJSON_AddItemToArray(root, item = cJSON_CreateObject());
9592  if (!iter->name.empty())
9593  {
9594  cJSON_AddStringToObject(item, "name", iter->name.c_str());
9595  }
9596  if (!iter->label.empty())
9597  {
9598  cJSON_AddStringToObject(item, "label", iter->label.c_str());
9599  }
9600  if (!iter->language.empty())
9601  {
9602  cJSON_AddStringToObject(item, "language", iter->language.c_str());
9603  }
9604  if (!iter->codec.empty())
9605  {
9606  cJSON_AddStringToObject(item, "codec", iter->codec.c_str());
9607  }
9608  if (!iter->rendition.empty())
9609  {
9610  cJSON_AddStringToObject(item, "rendition", iter->rendition.c_str());
9611  }
9612  if (!iter->accessibilityType.empty())
9613  {
9614  cJSON_AddStringToObject(item, "accessibilityType", iter->accessibilityType.c_str());
9615  }
9616  if (!iter->characteristics.empty())
9617  {
9618  cJSON_AddStringToObject(item, "characteristics", iter->characteristics.c_str());
9619  }
9620  if (iter->channels != 0)
9621  {
9622  cJSON_AddNumberToObject(item, "channels", iter->channels);
9623  }
9624  if (iter->bandwidth != -1)
9625  {
9626  cJSON_AddNumberToObject(item, "bandwidth", iter->bandwidth);
9627  }
9628  if (!iter->contentType.empty())
9629  {
9630  cJSON_AddStringToObject(item, "contentType", iter->contentType.c_str());
9631  }
9632  if (!iter->mixType.empty())
9633  {
9634  cJSON_AddStringToObject(item, "mixType", iter->mixType.c_str());
9635  }
9636  if (!iter->mType.empty())
9637  {
9638  cJSON_AddStringToObject(item, "Type", iter->mType.c_str());
9639  }
9640  cJSON_AddBoolToObject(item, "availability", iter->isAvailable);
9641  if (!iter->accessibilityItem.getSchemeId().empty())
9642  {
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")
9647  {
9648  cJSON_AddNumberToObject(accessibility, valueType.c_str(), iter->accessibilityItem.getIntValue());
9649  }else
9650  {
9651  cJSON_AddStringToObject(accessibility, valueType.c_str(), iter->accessibilityItem.getStrValue().c_str());
9652  }
9653  }
9654  }
9655  char *jsonStr = cJSON_Print(root);
9656  if (jsonStr)
9657  {
9658  tracks.assign(jsonStr);
9659  free(jsonStr);
9660  }
9661  cJSON_Delete(root);
9662  }
9663  }
9664  else
9665  {
9666  AAMPLOG_ERR("PrivateInstanceAAMP: No available audio track information!");
9667  }
9668  }
9669  pthread_mutex_unlock(&mStreamLock);
9670  return tracks;
9671 }
9672 
9673 /**
9674  * @brief Get available text tracks.
9675  */
9677 {
9678  std::string tracks;
9679 
9680  pthread_mutex_lock(&mStreamLock);
9682  {
9683  std::vector<TextTrackInfo> trackInfo = mpStreamAbstractionAAMP->GetAvailableTextTracks(allTrack);
9684 
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;});
9689 #endif
9690  if (!trackInfo.empty())
9691  {
9692  //Convert to JSON format
9693  cJSON *root;
9694  cJSON *item;
9695  root = cJSON_CreateArray();
9696  if(root)
9697  {
9698  for (auto iter = trackInfo.begin(); iter != trackInfo.end(); iter++)
9699  {
9700  cJSON_AddItemToArray(root, item = cJSON_CreateObject());
9701  if (!iter->name.empty())
9702  {
9703  cJSON_AddStringToObject(item, "name", iter->name.c_str());
9704  }
9705  if (!iter->label.empty())
9706  {
9707  cJSON_AddStringToObject(item, "label", iter->label.c_str());
9708  }
9709  if (iter->isCC)
9710  {
9711  cJSON_AddStringToObject(item, "sub-type", "CLOSED-CAPTIONS");
9712  }
9713  else
9714  {
9715  cJSON_AddStringToObject(item, "sub-type", "SUBTITLES");
9716  }
9717  if (!iter->language.empty())
9718  {
9719  cJSON_AddStringToObject(item, "language", iter->language.c_str());
9720  }
9721  if (!iter->rendition.empty())
9722  {
9723  cJSON_AddStringToObject(item, "rendition", iter->rendition.c_str());
9724  }
9725  if (!iter->accessibilityType.empty())
9726  {
9727  cJSON_AddStringToObject(item, "accessibilityType", iter->accessibilityType.c_str());
9728  }
9729  if (!iter->instreamId.empty())
9730  {
9731  cJSON_AddStringToObject(item, "instreamId", iter->instreamId.c_str());
9732  }
9733  if (!iter->characteristics.empty())
9734  {
9735  cJSON_AddStringToObject(item, "characteristics", iter->characteristics.c_str());
9736  }
9737  if (!iter->mType.empty())
9738  {
9739  cJSON_AddStringToObject(item, "type", iter->mType.c_str());
9740  }
9741  if (!iter->codec.empty())
9742  {
9743  cJSON_AddStringToObject(item, "codec", iter->codec.c_str());
9744  }
9745  cJSON_AddBoolToObject(item, "availability", iter->isAvailable);
9746  if (!iter->accessibilityItem.getSchemeId().empty())
9747  {
9748  cJSON *accessibility = cJSON_AddObjectToObject(item, "accessibility");
9749  cJSON_AddStringToObject(accessibility, "scheme", iter->accessibilityItem.getSchemeId().c_str());
9750 
9751  std::string valueType = iter->accessibilityItem.getTypeName();
9752  if (valueType == "int_value")
9753  {
9754  cJSON_AddNumberToObject(accessibility, valueType.c_str(), iter->accessibilityItem.getIntValue());
9755 
9756  }else
9757  {
9758  cJSON_AddStringToObject(accessibility, valueType.c_str(), iter->accessibilityItem.getStrValue().c_str());
9759  }
9760  }
9761  }
9762  char *jsonStr = cJSON_Print(root);
9763  if (jsonStr)
9764  {
9765  tracks.assign(jsonStr);
9766  free(jsonStr);
9767  }
9768  cJSON_Delete(root);
9769  }
9770  }
9771  else
9772  {
9773  AAMPLOG_ERR("PrivateInstanceAAMP: No available text track information!");
9774  }
9775  }
9776  pthread_mutex_unlock(&mStreamLock);
9777  return tracks;
9778 }
9779 
9780 /*
9781  * @brief Get the video window co-ordinates
9782  */
9783 std::string PrivateInstanceAAMP::GetVideoRectangle()
9784 {
9785  return mStreamSink->GetVideoRectangle();
9786 }
9787 
9788 /**
9789  * @brief Set the application name which has created PlayerInstanceAAMP, for logging purposes
9790  */
9791 void PrivateInstanceAAMP::SetAppName(std::string name)
9792 {
9793  mAppName = name;
9794 }
9795 
9796 /**
9797  * @brief Get the application name
9798  */
9800 {
9801  return mAppName;
9802 }
9803 
9804 /**
9805  * @brief DRM individualization callback
9806  */
9807 void PrivateInstanceAAMP::individualization(const std::string& payload)
9808 {
9809  DrmMessageEventPtr event = std::make_shared<DrmMessageEvent>(payload);
9811 }
9812 
9813 /**
9814  * @brief Get current initial buffer duration in seconds
9815  */
9817 {
9818  GETCONFIGVALUE_PRIV(eAAMPConfig_InitialBuffer,mMinInitialCacheSeconds);
9819  return mMinInitialCacheSeconds;
9820 }
9821 
9822 /**
9823  * @brief Check if First Video Frame Displayed Notification
9824  * is required.
9825  */
9827 {
9829 }
9830 
9831 /**
9832  * @brief Notify First Video Frame was displayed
9833  */
9835 {
9837  {
9838  return;
9839  }
9840 
9842 
9843  // In the middle of stop processing we can receive state changing callback (xione-7331)
9844  PrivAAMPState state;
9845  GetState(state);
9846  if (state == eSTATE_IDLE)
9847  {
9848  AAMPLOG_WARN( "skipped as in IDLE state" );
9849  return;
9850  }
9851 
9852  // Seek While Paused - pause on first Video frame displayed
9854  {
9856  PrivAAMPState state;
9857  GetState(state);
9858  if(state != eSTATE_SEEKING)
9859  {
9860  return;
9861  }
9862 
9863  AAMPLOG_INFO("Pausing Playback on First Frame Displayed");
9865  {
9867  }
9868  StopDownloads();
9869  if(PausePipeline(true, false))
9870  {
9872  }
9873  else
9874  {
9875  AAMPLOG_ERR("Failed to pause pipeline for first frame displayed!");
9876  }
9877  }
9878  // Otherwise check for setting BUFFERING state
9879  else if(!SetStateBufferingIfRequired())
9880  {
9881  // If Buffering state was not needed, set PLAYING state
9883  }
9884 }
9885 
9886 /**
9887  * @brief Set eSTATE_BUFFERING if required
9888  */
9890 {
9891  bool bufferingSet = false;
9892 
9893  pthread_mutex_lock(&mFragmentCachingLock);
9895  {
9896  bufferingSet = true;
9897  PrivAAMPState state;
9898  GetState(state);
9899  if(state != eSTATE_BUFFERING)
9900  {
9902  {
9904  }
9905 
9906  if(mStreamSink)
9907  {
9908  mStreamSink->NotifyFragmentCachingOngoing();
9909  }
9911  }
9912  }
9913  pthread_mutex_unlock(&mFragmentCachingLock);
9914 
9915  return bufferingSet;
9916 }
9917 
9918 /**
9919  * @brief Check to media track downloads are enabled
9920  */
9922 {
9923  bool ret = true;
9924  if (type >= AAMP_TRACK_COUNT) //CID:142718 - overrun
9925  {
9926  AAMPLOG_ERR("type[%d] is un-supported, returning default as false!", type);
9927  ret = false;
9928  }
9929  else
9930  {
9931  pthread_mutex_lock(&mLock);
9932  // If blocked, track downloads are disabled
9933  ret = !mbTrackDownloadsBlocked[type];
9934  pthread_mutex_unlock(&mLock);
9935  }
9936  return ret;
9937 }
9938 
9939 /**
9940  * @brief Stop buffering in AAMP and un-pause pipeline.
9941  */
9943 {
9944  mStreamSink->StopBuffering(forceStop);
9945 }
9946 
9947 /**
9948  * @brief Get license server url for a drm type
9949  */
9951 {
9952  std::string url;
9953  if (type == eDRM_PlayReady)
9954  {
9955  GETCONFIGVALUE_PRIV(eAAMPConfig_PRLicenseServerUrl,url);
9956  }
9957  else if (type == eDRM_WideVine)
9958  {
9959  GETCONFIGVALUE_PRIV(eAAMPConfig_WVLicenseServerUrl,url);
9960  }
9961  else if (type == eDRM_ClearKey)
9962  {
9963  GETCONFIGVALUE_PRIV(eAAMPConfig_CKLicenseServerUrl,url);
9964  }
9965 
9966  if(url.empty())
9967  {
9968  GETCONFIGVALUE_PRIV(eAAMPConfig_LicenseServerUrl,url);
9969  }
9970  return url;
9971 }
9972 
9973 /**
9974  * @brief Get current audio track index
9975  */
9977 {
9978  int idx = -1;
9981  {
9983  }
9985  return idx;
9986 }
9987 
9988 /**
9989  * @brief Get current audio track index
9990  */
9992 {
9993  std::string track;
9994 
9995 
9996  pthread_mutex_lock(&mStreamLock);
9998  {
9999  AudioTrackInfo trackInfo;
10001  {
10002  //Convert to JSON format
10003  cJSON *root;
10004  cJSON *item;
10005  root = cJSON_CreateArray();
10006  if(root)
10007  {
10008  cJSON_AddItemToArray(root, item = cJSON_CreateObject());
10009  if (!trackInfo.name.empty())
10010  {
10011  cJSON_AddStringToObject(item, "name", trackInfo.name.c_str());
10012  }
10013  if (!trackInfo.language.empty())
10014  {
10015  cJSON_AddStringToObject(item, "language", trackInfo.language.c_str());
10016  }
10017  if (!trackInfo.codec.empty())
10018  {
10019  cJSON_AddStringToObject(item, "codec", trackInfo.codec.c_str());
10020  }
10021  if (!trackInfo.rendition.empty())
10022  {
10023  cJSON_AddStringToObject(item, "rendition", trackInfo.rendition.c_str());
10024  }
10025  if (!trackInfo.label.empty())
10026  {
10027  cJSON_AddStringToObject(item, "label", trackInfo.label.c_str());
10028  }
10029  if (!trackInfo.accessibilityType.empty())
10030  {
10031  cJSON_AddStringToObject(item, "accessibilityType", trackInfo.accessibilityType.c_str());
10032  }
10033  if (!trackInfo.characteristics.empty())
10034  {
10035  cJSON_AddStringToObject(item, "characteristics", trackInfo.characteristics.c_str());
10036  }
10037  if (trackInfo.channels != 0)
10038  {
10039  cJSON_AddNumberToObject(item, "channels", trackInfo.channels);
10040  }
10041  if (trackInfo.bandwidth != -1)
10042  {
10043  cJSON_AddNumberToObject(item, "bandwidth", trackInfo.bandwidth);
10044  }
10045  if (!trackInfo.contentType.empty())
10046  {
10047  cJSON_AddStringToObject(item, "contentType", trackInfo.contentType.c_str());
10048  }
10049  if (!trackInfo.mixType.empty())
10050  {
10051  cJSON_AddStringToObject(item, "mixType", trackInfo.mixType.c_str());
10052  }
10053  if (!trackInfo.mType.empty())
10054  {
10055  cJSON_AddStringToObject(item, "type", trackInfo.mType.c_str());
10056  }
10057  if (!trackInfo.accessibilityItem.getSchemeId().empty())
10058  {
10059  cJSON *accessibility = cJSON_AddObjectToObject(item, "accessibility");
10060  cJSON_AddStringToObject(accessibility, "scheme", trackInfo.accessibilityItem.getSchemeId().c_str());
10061  if (trackInfo.accessibilityItem.getTypeName() == "int_value")
10062  {
10063  cJSON_AddNumberToObject(accessibility, trackInfo.accessibilityItem.getTypeName().c_str(), trackInfo.accessibilityItem.getIntValue());
10064  }
10065  else
10066  {
10067  cJSON_AddStringToObject(accessibility, trackInfo.accessibilityItem.getTypeName().c_str(), trackInfo.accessibilityItem.getStrValue().c_str());
10068  }
10069  }
10070  char *jsonStr = cJSON_Print(root);
10071  if (jsonStr)
10072  {
10073  track.assign(jsonStr);
10074  free(jsonStr);
10075  }
10076  cJSON_Delete(root);
10077  }
10078  }
10079  else
10080  {
10081  AAMPLOG_ERR("PrivateInstanceAAMP: No available Text track information!");
10082  }
10083  }
10084  else
10085  {
10086  AAMPLOG_ERR("PrivateInstanceAAMP: Not in playing state!");
10087  }
10088  pthread_mutex_unlock(&mStreamLock);
10089  return track;
10090 }
10091 
10092 /**
10093  * @brief Get current audio track index
10094  */
10096 {
10097  std::string track;
10098  pthread_mutex_lock(&mStreamLock);
10100  {
10101  TextTrackInfo trackInfo;
10103  {
10104  //Convert to JSON format
10105  cJSON *root;
10106  cJSON *item;
10107  root = cJSON_CreateArray();
10108  if(root)
10109  {
10110  cJSON_AddItemToArray(root, item = cJSON_CreateObject());
10111  if (!trackInfo.name.empty())
10112  {
10113  cJSON_AddStringToObject(item, "name", trackInfo.name.c_str());
10114  }
10115  if (!trackInfo.language.empty())
10116  {
10117  cJSON_AddStringToObject(item, "language", trackInfo.language.c_str());
10118  }
10119  if (!trackInfo.codec.empty())
10120  {
10121  cJSON_AddStringToObject(item, "codec", trackInfo.codec.c_str());
10122  }
10123  if (!trackInfo.rendition.empty())
10124  {
10125  cJSON_AddStringToObject(item, "rendition", trackInfo.rendition.c_str());
10126  }
10127  if (!trackInfo.label.empty())
10128  {
10129  cJSON_AddStringToObject(item, "label", trackInfo.label.c_str());
10130  }
10131  if (!trackInfo.accessibilityType.empty())
10132  {
10133  cJSON_AddStringToObject(item, "accessibilityType", trackInfo.accessibilityType.c_str());
10134  }
10135  if (!trackInfo.characteristics.empty())
10136  {
10137  cJSON_AddStringToObject(item, "characteristics", trackInfo.characteristics.c_str());
10138  }
10139  if (!trackInfo.mType.empty())
10140  {
10141  cJSON_AddStringToObject(item, "type", trackInfo.mType.c_str());
10142  }
10143  if (!trackInfo.accessibilityItem.getSchemeId().empty())
10144  {
10145  cJSON *accessibility = cJSON_AddObjectToObject(item, "accessibility");
10146  cJSON_AddStringToObject(accessibility, "scheme", trackInfo.accessibilityItem.getSchemeId().c_str());
10147  if (trackInfo.accessibilityItem.getTypeName() == "int_value")
10148  {
10149  cJSON_AddNumberToObject(accessibility, trackInfo.accessibilityItem.getTypeName().c_str(), trackInfo.accessibilityItem.getIntValue());
10150  }
10151  else
10152  {
10153  cJSON_AddStringToObject(accessibility, trackInfo.accessibilityItem.getTypeName().c_str(), trackInfo.accessibilityItem.getStrValue().c_str());
10154  }
10155  }
10156  char *jsonStr = cJSON_Print(root);
10157  if (jsonStr)
10158  {
10159  track.assign(jsonStr);
10160  free(jsonStr);
10161  }
10162  cJSON_Delete(root);
10163  }
10164  }
10165  else
10166  {
10167  AAMPLOG_ERR("PrivateInstanceAAMP: No available Text track information!");
10168  }
10169  }
10170  else
10171  {
10172  AAMPLOG_ERR("PrivateInstanceAAMP: Not in playing state!");
10173  }
10174  pthread_mutex_unlock(&mStreamLock);
10175  return track;
10176 }
10177 
10178 
10179 /**
10180  * @brief Create json data from track Info
10181  */
10182 static char* createJsonData(TextTrackInfo& track)
10183 {
10184  char *jsonStr = NULL;
10185  cJSON *item = cJSON_CreateObject();
10186  if (!track.name.empty())
10187  {
10188  cJSON_AddStringToObject(item, "name", track.name.c_str());
10189  }
10190  if (!track.language.empty())
10191  {
10192  cJSON_AddStringToObject(item, "languages", track.language.c_str());
10193  }
10194  if (!track.codec.empty())
10195  {
10196  cJSON_AddStringToObject(item, "codec", track.codec.c_str());
10197  }
10198  if (!track.rendition.empty())
10199  {
10200  cJSON_AddStringToObject(item, "rendition", track.rendition.c_str());
10201  }
10202  if (!track.label.empty())
10203  {
10204  cJSON_AddStringToObject(item, "label", track.label.c_str());
10205  }
10206  if (!track.accessibilityType.empty())
10207  {
10208  cJSON_AddStringToObject(item, "accessibilityType", track.accessibilityType.c_str());
10209  }
10210  if (!track.characteristics.empty())
10211  {
10212  cJSON_AddStringToObject(item, "characteristics", track.characteristics.c_str());
10213  }
10214  if (!track.mType.empty())
10215  {
10216  cJSON_AddStringToObject(item, "type", track.mType.c_str());
10217  }
10218  if (!track.accessibilityItem.getSchemeId().empty())
10219  {
10220  cJSON *accessibility = cJSON_AddObjectToObject(item, "accessibility");
10221  cJSON_AddStringToObject(accessibility, "scheme", track.accessibilityItem.getSchemeId().c_str());
10222  if (track.accessibilityItem.getTypeName() == "int_value")
10223  {
10224  cJSON_AddNumberToObject(accessibility, track.accessibilityItem.getTypeName().c_str(), track.accessibilityItem.getIntValue());
10225  }
10226  else
10227  {
10228  cJSON_AddStringToObject(accessibility, track.accessibilityItem.getTypeName().c_str(), track.accessibilityItem.getStrValue().c_str());
10229  }
10230  }
10231 
10232  jsonStr = cJSON_Print(item);
10233  cJSON_Delete(item);
10234  return jsonStr;
10235 }
10236 
10237 /**
10238  * @brief Set text track
10239  */
10240 void PrivateInstanceAAMP::SetTextTrack(int trackId, char *data)
10241 {
10242  AAMPLOG_INFO("trackId: %d", trackId);
10244  {
10245  // Passing in -1 as the track ID mutes subs
10246  if (MUTE_SUBTITLES_TRACKID == trackId)
10247  {
10248  SetCCStatus(false);
10249  return;
10250  }
10251 
10252  if (data == NULL)
10253  {
10254  std::vector<TextTrackInfo> tracks = mpStreamAbstractionAAMP->GetAvailableTextTracks();
10255  if (!tracks.empty() && (trackId >= 0 && trackId < tracks.size()))
10256  {
10257  TextTrackInfo track = tracks[trackId];
10258  // Check if CC / Subtitle track
10259  if (track.isCC)
10260  {
10261  mIsInbandCC = true;
10262 #ifdef AAMP_CC_ENABLED
10263  if (!track.instreamId.empty())
10264  {
10265  CCFormat format = eCLOSEDCAPTION_FORMAT_DEFAULT;
10266  // AampCCManager expects the CC type, ie 608 or 708
10267  // For DASH, there is a possibility that instreamId is just an integer so we infer rendition
10268  if (mMediaFormat == eMEDIAFORMAT_DASH && (std::isdigit(static_cast<unsigned char>(track.instreamId[0])) == 0) && !track.rendition.empty())
10269  {
10270  if (track.rendition.find("608") != std::string::npos)
10271  {
10272  format = eCLOSEDCAPTION_FORMAT_608;
10273  }
10274  else if (track.rendition.find("708") != std::string::npos)
10275  {
10276  format = eCLOSEDCAPTION_FORMAT_708;
10277  }
10278  }
10279 
10280  // preferredCEA708 overrides whatever we infer from track. USE WITH CAUTION
10281  int overrideCfg;
10282  GETCONFIGVALUE_PRIV(eAAMPConfig_CEAPreferred,overrideCfg);
10283  if (overrideCfg != -1)
10284  {
10285  format = (CCFormat)(overrideCfg & 1);
10286  AAMPLOG_WARN("PrivateInstanceAAMP: CC format override present, override format to: %d", format);
10287  }
10288  AampCCManager::GetInstance()->SetTrack(track.instreamId, format);
10289  }
10290  else
10291  {
10292  AAMPLOG_ERR("PrivateInstanceAAMP: Track number/instreamId is empty, skip operation");
10293  }
10294 #endif
10295  }
10296  else
10297  {
10298  mIsInbandCC = false;
10299  //Unmute subtitles
10300  SetCCStatus(true);
10301 
10302  //TODO: Effective handling between subtitle and CC tracks
10303  int textTrack = mpStreamAbstractionAAMP->GetTextTrack();
10304  AAMPLOG_WARN("GetPreferredTextTrack %d trackId %d", textTrack, trackId);
10305  if (trackId != textTrack)
10306  {
10307  if(mMediaFormat == eMEDIAFORMAT_DASH)
10308  {
10309  const char* jsonData = createJsonData(track);
10310  if(NULL != jsonData)
10311  {
10312  SetPreferredTextLanguages(jsonData);
10313  }
10314  }
10315  else
10316  {
10317  SetPreferredTextTrack(track);
10318  discardEnteringLiveEvt = true;
10321  TeardownStream(false);
10324  discardEnteringLiveEvt = false;
10325  }
10326  }
10327  }
10328  }
10329  }
10330  else
10331  {
10332  AAMPLOG_WARN("webvtt data received from application");
10333  mData = data;
10334  SetCCStatus(true);
10335 
10337  if (!mTextStyle.empty())
10338  {
10339  // Restore the subtitle text style after a track change.
10340  (void)mpStreamAbstractionAAMP->SetTextStyle(mTextStyle);
10341  }
10342  }
10343  }
10344 }
10345 
10346 
10347 /**
10348  * @brief Switch the subtitle track following a change to the
10349  * preferredTextTrack
10350  */
10352 {
10354  {
10356  }
10357 }
10358 
10359 /**
10360  * @brief Get current text track index
10361  */
10363 {
10364  int idx = -1;
10366 #ifdef AAMP_CC_ENABLED
10368  {
10369  std::string trackId = AampCCManager::GetInstance()->GetTrack();
10370  if (!trackId.empty())
10371  {
10372  std::vector<TextTrackInfo> tracks = mpStreamAbstractionAAMP->GetAvailableTextTracks();
10373  for (auto it = tracks.begin(); it != tracks.end(); it++)
10374  {
10375  if (it->instreamId == trackId)
10376  {
10377  idx = std::distance(tracks.begin(), it);
10378  }
10379  }
10380  }
10381  }
10382 #endif
10383  if (mpStreamAbstractionAAMP && idx == -1 && !subtitles_muted)
10384  {
10386  }
10388  return idx;
10389 }
10390 
10391 /**
10392  * @brief Set CC visibility on/off
10393  */
10395 {
10396 #ifdef AAMP_CC_ENABLED
10398 #endif
10400  subtitles_muted = !enabled;
10402  {
10403  mpStreamAbstractionAAMP->MuteSubtitles(subtitles_muted);
10404  if (HasSidecarData())
10405  { // has sidecar data
10407  }
10408  }
10409  SetSubtitleMute(subtitles_muted);
10411 }
10412 
10413 /**
10414  * @brief Get CC visibility on/off
10415  */
10417 {
10418  return !(subtitles_muted);
10419 }
10420 
10421 /**
10422  * @brief Function to notify available audio tracks changed
10423  */
10425 {
10426  SendEvent(std::make_shared<AAMPEventObject>(AAMP_EVENT_AUDIO_TRACKS_CHANGED),AAMP_EVENT_ASYNC_MODE);
10427 }
10428 
10429 /**
10430  * @brief Function to notify available text tracks changed
10431  */
10433 {
10434  SendEvent(std::make_shared<AAMPEventObject>(AAMP_EVENT_TEXT_TRACKS_CHANGED),AAMP_EVENT_ASYNC_MODE);
10435 }
10436 
10437 /**
10438  * @brief Set style options for text track rendering
10439  *
10440  */
10441 void PrivateInstanceAAMP::SetTextStyle(const std::string &options)
10442 {
10443  bool retVal = false;
10444 
10445  mTextStyle = options;
10446 
10448  {
10449  AAMPLOG_WARN("Calling StreamAbstractionAAMP::SetTextStyle(%s)", options.c_str());
10450  retVal = mpStreamAbstractionAAMP->SetTextStyle(options);
10451  }
10452  if (!retVal)
10453  {
10454 #ifdef AAMP_CC_ENABLED
10455  AAMPLOG_WARN("Calling AampCCManager::SetTextStyle(%s)", options.c_str());
10457 #endif
10458  }
10459 }
10460 
10461 /**
10462  * @brief Get style options for text track rendering
10463  */
10465 {
10466  return mTextStyle;
10467 }
10468 
10469 /**
10470  * @brief Check if any active PrivateInstanceAAMP available
10471  */
10473 {
10474  return !gActivePrivAAMPs.empty();
10475 }
10476 
10477 /**
10478  * @brief Set discontinuity ignored flag for given track
10479  */
10481 {
10482  mIsDiscontinuityIgnored[track] = true;
10483 }
10484 
10485 /**
10486  * @brief Check whether the given track discontinuity ignored earlier.
10487  */
10489 {
10490  return (mIsDiscontinuityIgnored[track]);
10491 }
10492 
10493 /**
10494  * @brief Reset discontinuity ignored flag for audio and video tracks
10495  */
10497 {
10498  mIsDiscontinuityIgnored[eTRACK_VIDEO] = false;
10499  mIsDiscontinuityIgnored[eTRACK_AUDIO] = false;
10500 }
10501 
10502 /**
10503  * @brief Set stream format for audio/video tracks
10504  */
10506 {
10507  bool reconfigure = false;
10508  AAMPLOG_WARN("Got format - videoFormat %d and audioFormat %d", videoFormat, audioFormat);
10509 
10510  // 1. Modified Configure() not to recreate all playbins if there is a change in track's format.
10511  // 2. For a demuxed scenario, this function will be called twice for each audio and video, so double the trouble.
10512  // Hence call Configure() only for following scenarios to reduce the overhead,
10513  // i.e FORMAT_INVALID to any KNOWN/FORMAT_UNKNOWN, FORMAT_UNKNOWN to any KNOWN and any FORMAT_KNOWN to FORMAT_KNOWN if it's not same.
10514  // Truth table
10515  // mVideFormat videoFormat reconfigure
10516  // * INVALID false
10517  // INVALID INVALID false
10518  // INVALID UNKNOWN true
10519  // INVALID KNOWN true
10520  // UNKNOWN INVALID false
10521  // UNKNOWN UNKNOWN false
10522  // UNKNOWN KNOWN true
10523  // KNOWN INVALID false
10524  // KNOWN UNKNOWN false
10525  // KNOWN KNOWN true if format changes, false if same
10526  pthread_mutex_lock(&mLock);
10527  if (videoFormat != FORMAT_INVALID && mVideoFormat != videoFormat && (videoFormat != FORMAT_UNKNOWN || mVideoFormat == FORMAT_INVALID))
10528  {
10529  reconfigure = true;
10530  mVideoFormat = videoFormat;
10531  }
10532  if (audioFormat != FORMAT_INVALID && mAudioFormat != audioFormat && (audioFormat != FORMAT_UNKNOWN || mAudioFormat == FORMAT_INVALID))
10533  {
10534  reconfigure = true;
10535  mAudioFormat = audioFormat;
10536  }
10537  if (auxFormat != mAuxFormat && (mAuxFormat == FORMAT_INVALID || (mAuxFormat != FORMAT_UNKNOWN && auxFormat != FORMAT_UNKNOWN)) && auxFormat != FORMAT_INVALID)
10538  {
10539  reconfigure = true;
10540  mAuxFormat = auxFormat;
10541  }
10542  if (IsMuxedStream() && (mVideoComponentCount == 0 || mAudioComponentCount == 0)) //Can be a Muxed stream/Demuxed with either of audio or video-only stream
10543  {
10544  AAMPLOG_INFO(" TS Processing Done. Number of Audio Components : %d and Video Components : %d",mAudioComponentCount,mVideoComponentCount);
10545  if (IsAudioOrVideoOnly(videoFormat, audioFormat, auxFormat))
10546  {
10547  bool newTune = IsNewTune();
10548  pthread_mutex_unlock(&mLock);
10549  mStreamSink->Stop(!newTune);
10550  pthread_mutex_lock(&mLock);
10551  reconfigure = true;
10552  }
10553  }
10554  if (reconfigure)
10555  {
10556  // Configure pipeline as TSProcessor might have detected the actual stream type
10557  // or even presence of audio
10558  mStreamSink->Configure(mVideoFormat, mAudioFormat, mAuxFormat, mSubtitleFormat, false, mpStreamAbstractionAAMP->GetAudioFwdToAuxStatus());
10559  }
10560  pthread_mutex_unlock(&mLock);
10561 }
10562 
10563 /**
10564  * @brief To check for audio/video only Playback
10565  */
10566 
10568 {
10569  AAMPLOG_WARN("Old Stream format - videoFormat %d and audioFormat %d",mVideoFormat,mAudioFormat);
10570  bool ret = false;
10571  if (mVideoComponentCount == 0 && (mVideoFormat != videoFormat && videoFormat == FORMAT_INVALID))
10572  {
10573  mAudioOnlyPb = true;
10574  mVideoFormat = videoFormat;
10575  AAMPLOG_INFO("Audio-Only PlayBack");
10576  ret = true;
10577  }
10578 
10579  else if (mAudioComponentCount == 0)
10580  {
10581  if (mAudioFormat != audioFormat && audioFormat == FORMAT_INVALID)
10582  {
10583  mAudioFormat = audioFormat;
10584  }
10585  else if (mAuxFormat != auxFormat && auxFormat == FORMAT_INVALID)
10586  {
10587  mAuxFormat = auxFormat;
10588  }
10589  mVideoOnlyPb = true;
10590  AAMPLOG_INFO("Video-Only PlayBack");
10591  ret = true;
10592  }
10593 
10594  return ret;
10595 }
10596 /**
10597  * @brief Disable Content Restrictions - unlock
10598  */
10599 void PrivateInstanceAAMP::DisableContentRestrictions(long grace, long time, bool eventChange)
10600 {
10603  {
10604  mpStreamAbstractionAAMP->DisableContentRestrictions(grace, time, eventChange);
10605 #ifdef AAMP_CC_ENABLED
10606  if (ISCONFIGSET_PRIV(eAAMPConfig_NativeCCRendering))
10607  {
10609  }
10610 #endif
10611  }
10613 }
10614 
10615 /**
10616  * @brief Enable Content Restrictions - lock
10617  */
10619 {
10622  {
10624  }
10626 }
10627 
10628 
10629 /**
10630  * @brief Add async task to scheduler
10631  */
10632 int PrivateInstanceAAMP::ScheduleAsyncTask(IdleTask task, void *arg, std::string taskName)
10633 {
10634  int taskId = AAMP_TASK_ID_INVALID;
10635  if (mScheduler)
10636  {
10637  taskId = mScheduler->ScheduleTask(AsyncTaskObj(task, arg, taskName));
10638  if (taskId == AAMP_TASK_ID_INVALID)
10639  {
10640  AAMPLOG_ERR("mScheduler returned invalid ID, dropping the schedule request!");
10641  }
10642  }
10643  else
10644  {
10645  taskId = g_idle_add(task, (gpointer)arg);
10646  }
10647  return taskId;
10648 }
10649 
10650 /**
10651  * @brief Remove async task scheduled earlier
10652  */
10654 {
10655  bool ret = false;
10656  if (mScheduler)
10657  {
10658  ret = mScheduler->RemoveTask(taskId);
10659  }
10660  else
10661  {
10662  ret = g_source_remove(taskId);
10663  }
10664  return ret;
10665 }
10666 
10667 
10668 /**
10669  * @brief acquire streamsink lock
10670  */
10672 {
10673  pthread_mutex_lock(&mStreamLock);
10674 }
10675 
10676 /**
10677  * @brief try to acquire streamsink lock
10678  *
10679  */
10681 {
10682  return (pthread_mutex_trylock(&mStreamLock) == 0);
10683 }
10684 
10685 /**
10686  * @brief release streamsink lock
10687  *
10688  */
10690 {
10691  pthread_mutex_unlock(&mStreamLock);
10692 }
10693 
10694 /**
10695  * @brief To check if auxiliary audio is enabled
10696  */
10698 {
10699  return !mAuxAudioLanguage.empty();
10700 }
10701 
10702 /**
10703  * @brief Check if discontinuity processed in all tracks
10704  *
10705  */
10707 {
10708  // Check if track is disabled or if mProcessingDiscontinuity is set
10709  // Split off the logical expression for better clarity
10710  bool vidDiscontinuity = (mVideoFormat == FORMAT_INVALID || mProcessingDiscontinuity[eMEDIATYPE_VIDEO]);
10711  bool audDiscontinuity = (mAudioFormat == FORMAT_INVALID || mProcessingDiscontinuity[eMEDIATYPE_AUDIO]);
10712  bool auxDiscontinuity = (mAuxFormat == FORMAT_INVALID || mProcessingDiscontinuity[eMEDIATYPE_AUX_AUDIO]);
10713 
10714  return (vidDiscontinuity && auxDiscontinuity && auxDiscontinuity);
10715 }
10716 
10717 /**
10718  * @brief Check if discontinuity processed in any track
10719  */
10721 {
10722  // Check if track is enabled and if mProcessingDiscontinuity is set
10723  // Split off the logical expression for better clarity
10724  bool vidDiscontinuity = (mVideoFormat != FORMAT_INVALID && mProcessingDiscontinuity[eMEDIATYPE_VIDEO]);
10725  bool audDiscontinuity = (mAudioFormat != FORMAT_INVALID && mProcessingDiscontinuity[eMEDIATYPE_AUDIO]);
10726  bool auxDiscontinuity = (mAuxFormat != FORMAT_INVALID && mProcessingDiscontinuity[eMEDIATYPE_AUX_AUDIO]);
10727 
10728  return (vidDiscontinuity || auxDiscontinuity || auxDiscontinuity);
10729 }
10730 
10731 /**
10732  * @brief Reset discontinuity flag for all tracks
10733  */
10735 {
10736  mProcessingDiscontinuity[eMEDIATYPE_VIDEO] = false;
10737  mProcessingDiscontinuity[eMEDIATYPE_AUDIO] = false;
10738  mProcessingDiscontinuity[eMEDIATYPE_AUX_AUDIO] = false;
10739 }
10740 
10741 /**
10742  * @brief set preferred Audio Language properties like language, rendition, type and codec
10743  */
10744 void PrivateInstanceAAMP::SetPreferredLanguages(const char *languageList, const char *preferredRendition, const char *preferredType, const char *codecList, const char *labelList )
10745 {
10746 
10747  /**< First argment is Json data then parse it and and assign the variables properly*/
10748  AampJsonObject* jsObject = NULL;
10749  bool isJson = false;
10750  bool isRetuneNeeded = false;
10751  bool accessibilityPresent = false;
10752  try
10753  {
10754  jsObject = new AampJsonObject(languageList);
10755  if (jsObject)
10756  {
10757  AAMPLOG_INFO("Preferred Language Properties received as json : %s", languageList);
10758  isJson = true;
10759  }
10760  }
10761  catch(const std::exception& e)
10762  {
10763  /**<Nothing to do exclude it*/
10764  }
10765 
10766  if (isJson)
10767  {
10768  std::vector<std::string> inputLanguagesList;
10769  std::string inputLanguagesString;
10770 
10771  /** Get language Properties*/
10772  if (jsObject->isArray("languages"))
10773  {
10774  if (jsObject->get("languages", inputLanguagesList))
10775  {
10776  for (auto preferredLanguage : inputLanguagesList)
10777  {
10778  if (!inputLanguagesString.empty())
10779  {
10780  inputLanguagesString += ",";
10781  }
10782  inputLanguagesString += preferredLanguage;
10783  }
10784  }
10785  }
10786  else if (jsObject->isString("languages"))
10787  {
10788  if (jsObject->get("languages", inputLanguagesString))
10789  {
10790  inputLanguagesList.push_back(inputLanguagesString);
10791  }
10792  }
10793  else
10794  {
10795  AAMPLOG_ERR("Preferred Audio Language Field Only support String or String Array");
10796  }
10797 
10798  AAMPLOG_INFO("Number of preferred languages received: %lu", inputLanguagesList.size());
10799  AAMPLOG_INFO("Preferred language string received: %s", inputLanguagesString.c_str());
10800 
10801  std::string inputLabelsString;
10802  /** Get Label Properties*/
10803  if (jsObject->isString("label"))
10804  {
10805  if (jsObject->get("label", inputLabelsString))
10806  {
10807  AAMPLOG_INFO("Preferred Label string: %s", inputLabelsString.c_str());
10808  }
10809  }
10810 
10811  string inputRenditionString;
10812 
10813  /** Get rendition or role Properties*/
10814  if (jsObject->isString("rendition"))
10815  {
10816  if (jsObject->get("rendition", inputRenditionString))
10817  {
10818  AAMPLOG_INFO("Preferred rendition string: %s", inputRenditionString.c_str());
10819  }
10820  }
10821 
10822  Accessibility inputAudioAccessibilityNode;
10823  /** Get accessibility Properties*/
10824  if (jsObject->isObject("accessibility"))
10825  {
10826  AampJsonObject accessNode;
10827  if (jsObject->get("accessibility", accessNode))
10828  {
10829  inputAudioAccessibilityNode = StreamAbstractionAAMP_MPD::getAccessibilityNode(accessNode);
10830  if (!inputAudioAccessibilityNode.getSchemeId().empty())
10831  {
10832  AAMPLOG_INFO("Preferred accessibility SchemeId: %s", inputAudioAccessibilityNode.getSchemeId().c_str());
10833  if (inputAudioAccessibilityNode.getTypeName() == "string_value")
10834  {
10835  AAMPLOG_INFO("Preferred accessibility Value Type %s and Value: %s", inputAudioAccessibilityNode.getTypeName().c_str(),
10836  inputAudioAccessibilityNode.getStrValue().c_str());
10837  }
10838  else
10839  {
10840  AAMPLOG_INFO("Preferred accessibility Value Type %s and Value : %d", inputAudioAccessibilityNode.getTypeName().c_str(),
10841  inputAudioAccessibilityNode.getIntValue());
10842  }
10843  }
10844  }
10845  if(preferredAudioAccessibilityNode != inputAudioAccessibilityNode )
10846  {
10847  accessibilityPresent = true;
10848  }
10849  }
10850 
10851  /**< Release json object **/
10852  delete jsObject;
10853  jsObject = NULL;
10854 
10855  if ((preferredAudioAccessibilityNode != inputAudioAccessibilityNode ) || (preferredRenditionString != inputRenditionString ) ||
10856  (preferredLabelsString != inputLabelsString) || (inputLanguagesList != preferredLanguagesList ))
10857  {
10858  isRetuneNeeded = true;
10859  }
10860 
10861  /** Clear the cache **/
10863  preferredLabelsString.clear();
10864  preferredRenditionString.clear();
10865  preferredLanguagesString.clear();
10866  preferredLanguagesList.clear();
10867 
10868  /** Reload the new values **/
10869  preferredAudioAccessibilityNode = inputAudioAccessibilityNode;
10870  preferredRenditionString = inputRenditionString;
10871  preferredLabelsString = inputLabelsString;
10872  preferredLanguagesList = inputLanguagesList;
10873  preferredLanguagesString = inputLanguagesString;
10874 
10875  SETCONFIGVALUE_PRIV(AAMP_APPLICATION_SETTING,eAAMPConfig_PreferredAudioRendition,preferredRenditionString);
10876  SETCONFIGVALUE_PRIV(AAMP_APPLICATION_SETTING,eAAMPConfig_PreferredAudioLabel,preferredLabelsString);
10877  SETCONFIGVALUE_PRIV(AAMP_APPLICATION_SETTING,eAAMPConfig_PreferredAudioLanguage,preferredLanguagesString);
10878  }
10879  else
10880  {
10881  if((languageList && preferredLanguagesString != languageList) ||
10882  (preferredRendition && preferredRenditionString != preferredRendition) ||
10883  (preferredType && preferredTypeString != preferredType) ||
10884  (codecList && preferredCodecString != codecList) ||
10885  (labelList && preferredLabelsString != labelList)
10886  )
10887  {
10888  isRetuneNeeded = true;
10889  if(languageList != NULL)
10890  {
10891  preferredLanguagesString.clear();
10892  preferredLanguagesList.clear();
10893  preferredLanguagesString = std::string(languageList);
10894  std::istringstream ss(preferredLanguagesString);
10895  std::string lng;
10896  while(std::getline(ss, lng, ','))
10897  {
10898  preferredLanguagesList.push_back(lng);
10899  AAMPLOG_INFO("Parsed preferred lang: %s", lng.c_str());
10900  }
10901 
10902  preferredLanguagesString = std::string(languageList);
10903  SETCONFIGVALUE_PRIV(AAMP_APPLICATION_SETTING,eAAMPConfig_PreferredAudioLanguage,preferredLanguagesString);
10904  }
10905 
10906  AAMPLOG_INFO("Number of preferred languages: %lu", preferredLanguagesList.size());
10907 
10908  if(labelList != NULL)
10909  {
10910  preferredLabelsString.clear();
10911  preferredLabelList.clear();
10912  preferredLabelsString = std::string(labelList);
10913  std::istringstream ss(preferredLabelsString);
10914  std::string lab;
10915  while(std::getline(ss, lab, ','))
10916  {
10917  preferredLabelList.push_back(lab);
10918  AAMPLOG_INFO("Parsed preferred label: %s", lab.c_str());
10919  }
10920 
10921  preferredLabelsString = std::string(labelList);
10922  SETCONFIGVALUE_PRIV(AAMP_APPLICATION_SETTING,eAAMPConfig_PreferredAudioLabel,preferredLabelsString);
10923  AAMPLOG_INFO("Number of preferred labels: %lu", preferredLabelList.size());
10924  }
10925 
10926  if( preferredRendition )
10927  {
10928  AAMPLOG_INFO("Setting rendition %s", preferredRendition);
10929  preferredRenditionString = std::string(preferredRendition);
10930  SETCONFIGVALUE_PRIV(AAMP_APPLICATION_SETTING,eAAMPConfig_PreferredAudioRendition,preferredRenditionString);
10931  }
10932  else
10933  {
10934  preferredRenditionString.clear();
10935  }
10936 
10937  if( preferredType )
10938  {
10939  preferredTypeString = std::string(preferredType);
10940  std::string delim = "_";
10941  auto pos = preferredTypeString.find(delim);
10942  auto end = preferredTypeString.length();
10943  if (pos != std::string::npos)
10944  {
10945  preferredTypeString = preferredTypeString.substr(pos+1, end);
10946  }
10947  AAMPLOG_INFO("Setting accessibility type %s", preferredTypeString.c_str());
10948  SETCONFIGVALUE_PRIV(AAMP_APPLICATION_SETTING, eAAMPConfig_PreferredAudioType, preferredTypeString);
10949  }
10950  else
10951  {
10952  preferredTypeString.clear();
10953  }
10954 
10955  if(codecList != NULL)
10956  {
10957  preferredCodecString.clear();
10958  preferredCodecList.clear();
10959  preferredCodecString = std::string(codecList);
10960  std::istringstream ss(preferredCodecString);
10961  std::string codec;
10962  while(std::getline(ss, codec, ','))
10963  {
10964  preferredCodecList.push_back(codec);
10965  AAMPLOG_INFO("Parsed preferred codec: %s", codec.c_str());
10966  }
10967  preferredCodecString = std::string(codecList);
10968  SETCONFIGVALUE_PRIV(AAMP_APPLICATION_SETTING,eAAMPConfig_PreferredAudioCodec,preferredCodecString);
10969  }
10970  AAMPLOG_INFO("Number of preferred codecs: %lu", preferredCodecList.size());
10971  }
10972  else
10973  {
10974  AAMPLOG_INFO("Discarding Retune set lanuage(s) (%s) , rendition (%s) and accessibility (%s) since already set",
10975  languageList?languageList:"", preferredRendition?preferredRendition:"", preferredType?preferredType:"");
10976  }
10977  }
10978 
10979  PrivAAMPState state;
10980  GetState(state);
10981  if (state != eSTATE_IDLE && state != eSTATE_RELEASED && state != eSTATE_ERROR && isRetuneNeeded)
10982  { // active playback session; apply immediately
10984  {
10985  bool languagePresent = false;
10986  bool renditionPresent = false;
10987  bool accessibilityTypePresent = false;
10988  bool codecPresent = false;
10989  bool labelPresent = false;
10990  int trackIndex = GetAudioTrack();
10991 
10992  bool languageAvailabilityInManifest = false;
10993  bool renditionAvailabilityInManifest = false;
10994  bool accessibilityAvailabilityInManifest = false;
10995  bool labelAvailabilityInManifest = false;
10996  std::string trackIndexStr;
10997 
10998  if (trackIndex >= 0)
10999  {
11000  std::vector<AudioTrackInfo> trackInfo = mpStreamAbstractionAAMP->GetAvailableAudioTracks();
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());
11006 
11007  // Logic to check whether the given language is present in the available tracks,
11008  // if available, it should not match with current preferredLanguagesString, then call tune to reflect the language change.
11009  // if not available, then avoid calling tune.
11010  if(preferredLanguagesList.size() > 0)
11011  {
11012  std::string firstLanguage = preferredLanguagesList.at(0);
11013  auto language = std::find_if(trackInfo.begin(), trackInfo.end(),
11014  [firstLanguage, currentPrefLanguage](AudioTrackInfo& temp)
11015  { return ((temp.language == firstLanguage) && (temp.language != currentPrefLanguage)); });
11016  languagePresent = (language != end(trackInfo) || (preferredLanguagesList.size() > 1)); /* If multiple value of language is present then retune */
11017  auto languageAvailable = std::find_if(trackInfo.begin(), trackInfo.end(),
11018  [firstLanguage, currentPrefLanguage](AudioTrackInfo& temp)
11019  { return ((temp.language == firstLanguage) && (temp.language != currentPrefLanguage) && (temp.isAvailable)); });
11020  languageAvailabilityInManifest = (languageAvailable != end(trackInfo) && languageAvailable->isAvailable);
11021  if(languagePresent && (language != end(trackInfo)))
11022  {
11023  trackIndexStr = language->index;
11024  }
11025  }
11026 
11027  // Logic to check whether the given label is present in the available tracks,
11028  // if available, it should not match with current preferredLabelsString, then call retune to reflect the language change.
11029  // if not available, then avoid calling tune. Call retune if multiple labels is present
11030  if(!preferredLabelsString.empty())
11031  {
11032  std::string curLabel = preferredLabelsString;
11033  auto label = std::find_if(trackInfo.begin(), trackInfo.end(),
11034  [curLabel, currentPrefLabel](AudioTrackInfo& temp)
11035  { return ((temp.label == curLabel) && (temp.label != currentPrefLabel)); });
11036  labelPresent = (label != end(trackInfo) || (preferredLabelList.size() > 1)); /* If multiple value of label is present then retune */
11037  auto labelAvailable = std::find_if(trackInfo.begin(), trackInfo.end(),
11038  [curLabel, currentPrefLabel](AudioTrackInfo& temp)
11039  { return ((temp.label == curLabel) && (temp.label != currentPrefLabel) && (temp.isAvailable)); });
11040  labelAvailabilityInManifest = ((labelAvailable != end(trackInfo) ) && labelAvailable->isAvailable);
11041 
11042  }
11043 
11044 
11045  // Logic to check whether the given rendition is present in the available tracks,
11046  // if available, it should not match with current preferredRenditionString, then call tune to reflect the rendition change.
11047  // if not available, then avoid calling tune.
11048  if(!preferredRenditionString.empty())
11049  {
11050  std::string curRendition = preferredRenditionString;
11051  auto rendition = std::find_if(trackInfo.begin(), trackInfo.end(),
11052  [curRendition, currentPrefRendition](AudioTrackInfo& temp)
11053  { return ((temp.rendition == curRendition) && (temp.rendition != currentPrefRendition)); });
11054  renditionPresent = (rendition != end(trackInfo));
11055  auto renditionAvailable = std::find_if(trackInfo.begin(), trackInfo.end(),
11056  [curRendition, currentPrefRendition](AudioTrackInfo& temp)
11057  { return ((temp.rendition == curRendition) && (temp.rendition != currentPrefRendition) && (temp.isAvailable)); });
11058  renditionAvailabilityInManifest = ((renditionAvailable != end(trackInfo)) && renditionAvailable->isAvailable);
11059  }
11060 
11061  // Logic to check whether the given accessibility is present in the available tracks,
11062  // if available, it should not match with current preferredTypeString, then call tune to reflect the accessibility change.
11063  // if not available, then avoid calling tune.
11064  if(!preferredTypeString.empty())
11065  {
11066  std:;string curType = preferredTypeString;
11067  auto accessType = std::find_if(trackInfo.begin(), trackInfo.end(),
11068  [curType, currentPrefAccessibility](AudioTrackInfo& temp)
11069  { return ((temp.accessibilityType == curType) && (temp.accessibilityType != currentPrefAccessibility)); });
11070  accessibilityTypePresent = (accessType != end(trackInfo));
11071  auto accessTypeAvailable = std::find_if(trackInfo.begin(), trackInfo.end(),
11072  [curType, currentPrefAccessibility](AudioTrackInfo& temp)
11073  { return ((temp.accessibilityType == curType) && (temp.accessibilityType != currentPrefAccessibility) && (temp.isAvailable)); });
11074  accessibilityAvailabilityInManifest = ((accessTypeAvailable != end(trackInfo)) && accessTypeAvailable->isAvailable);
11075  }
11076 
11077  // Logic to check whether the given codec is present in the available tracks,
11078  // if available, it should not match with current preferred codec, then call tune to reflect the codec change.
11079  // if not available, then avoid calling tune.
11080  if(preferredCodecList.size() > 0)
11081  {
11082  std::string firstCodec = preferredCodecList.at(0);
11083  auto codec = std::find_if(trackInfo.begin(), trackInfo.end(),
11084  [firstCodec, currentPrefCodec](AudioTrackInfo& temp)
11085  { return ((temp.codec == firstCodec) && (temp.codec != currentPrefCodec) && (temp.isAvailable)); });
11086  codecPresent = (codec != end(trackInfo) || (preferredCodecList.size() > 1) ); /* If multiple value of codec is present then retune */
11087  }
11088  }
11089 
11090  bool clearPreference = false;
11091  if(isRetuneNeeded && preferredCodecList.size() == 0 && preferredTypeString.empty() && preferredRenditionString.empty() \
11092  && preferredLabelsString.empty() && preferredLanguagesList.size() == 0)
11093  {
11094  /** Previouse preference set and API called to clear all preferences; so retune to make effect **/
11095  AAMPLOG_INFO("API to clear all preferences; retune to make it affect");
11096  clearPreference = true;
11097  }
11098 
11099  if((mMediaFormat == eMEDIAFORMAT_OTA) || (mMediaFormat == eMEDIAFORMAT_RMF))
11100  {
11102  }
11103  else if((mMediaFormat == eMEDIAFORMAT_HDMI) || (mMediaFormat == eMEDIAFORMAT_COMPOSITE))
11104  {
11105  /*Avoid retuning in case of HEMIIN and COMPOSITE IN*/
11106  }
11107  else if (languagePresent || renditionPresent || accessibilityTypePresent || codecPresent || labelPresent || accessibilityPresent || clearPreference) // call the tune only if there is a change in the language, rendition or accessibility.
11108  {
11109  if(!ISCONFIGSET_PRIV(eAAMPConfig_ChangeTrackWithoutRetune))
11110  {
11111  discardEnteringLiveEvt = true;
11112 
11114  mOffsetFromTunetimeForSAPWorkaround = (double)(aamp_GetCurrentTimeMS() / 1000) - mLiveOffset;
11115  mLanguageChangeInProgress = true;
11117  TeardownStream(false);
11118  if(IsTSBSupported() &&
11119  ((languagePresent && !languageAvailabilityInManifest) ||
11120  (renditionPresent && !renditionAvailabilityInManifest) ||
11121  (accessibilityTypePresent && !accessibilityAvailabilityInManifest) ||
11122  (labelPresent && !labelAvailabilityInManifest)))
11123  {
11124  ReloadTSB();
11125  }
11127  discardEnteringLiveEvt = false;
11129  }
11130  else if(!trackIndexStr.empty())
11131  {
11133  }
11134  }
11135  }
11136  }
11137 }
11138 
11139 /**
11140  * @brief Set Preferred Text Language
11141  */
11143 {
11144 
11145  /**< First argment is Json data then parse it and and assign the variables properly*/
11146  AampJsonObject* jsObject = NULL;
11147  bool isJson = false;
11148  bool isRetuneNeeded = false;
11149  bool accessibilityPresent = false;
11150  try
11151  {
11152  jsObject = new AampJsonObject(param);
11153  if (jsObject)
11154  {
11155  AAMPLOG_INFO("Preferred Text Language Properties received as json : %s", param);
11156  isJson = true;
11157  }
11158  }
11159  catch(const std::exception& e)
11160  {
11161  /**<Nothing to do exclude it*/
11162  }
11163 
11164  if (isJson)
11165  {
11166  std::vector<std::string> inputTextLanguagesList;
11167  std::string inputTextLanguagesString;
11168 
11169  /** Get language Properties*/
11170  if(jsObject->isArray("languages"))
11171  { // if starting with array, join to string
11172  if (jsObject->get("languages", inputTextLanguagesList))
11173  {
11174  for (auto preferredLanguage : inputTextLanguagesList)
11175  {
11176  if (!inputTextLanguagesString.empty())
11177  {
11178  inputTextLanguagesString += "," ;
11179  }
11180  inputTextLanguagesString += preferredLanguage;
11181  }
11182  }
11183  }
11184  else if (jsObject->isString("languages"))
11185  { // if starting with string, create simple array
11186  if (jsObject->get("languages", inputTextLanguagesString))
11187  {
11188  inputTextLanguagesList.push_back(inputTextLanguagesString);
11189  }
11190  }
11191  else
11192  {
11193  AAMPLOG_ERR("Preferred Text Language Field Only support String or String Array");
11194  }
11195 
11196  AAMPLOG_INFO("Number of preferred Text languages: %lu", inputTextLanguagesList.size());
11197  AAMPLOG_INFO("Preferred Text languages string: %s", inputTextLanguagesString.c_str());
11198 
11199  std::string inputTextRenditionString;
11200  /** Get rendition or role Properties*/
11201  if (jsObject->isString("rendition"))
11202  {
11203  if (jsObject->get("rendition", inputTextRenditionString))
11204  {
11205  AAMPLOG_INFO("Preferred text rendition string: %s", inputTextRenditionString.c_str());
11206  }
11207  }
11208 
11209  std::string inputTextLabelString;
11210  /** Get label Properties*/
11211  if (jsObject->isString("label"))
11212  {
11213  if (jsObject->get("label", inputTextLabelString))
11214  {
11215  AAMPLOG_INFO("Preferred text label string: %s", inputTextLabelString.c_str());
11216  }
11217  }
11218 
11219  std::string inputTextTypeString;
11220  /** Get accessibility type Properties*/
11221  if (jsObject->isString("accessibilityType"))
11222  {
11223  if (jsObject->get("accessibilityType", inputTextTypeString))
11224  {
11225  AAMPLOG_INFO("Preferred text type string: %s", inputTextTypeString.c_str());
11226  }
11227  }
11228 
11229  Accessibility inputTextAccessibilityNode;
11230  /** Get accessibility Properties*/
11231  if (jsObject->isObject("accessibility"))
11232  {
11233  AampJsonObject accessNode;
11234  if (jsObject->get("accessibility", accessNode))
11235  {
11236  inputTextAccessibilityNode = StreamAbstractionAAMP_MPD::getAccessibilityNode(accessNode);
11237  if (!inputTextAccessibilityNode.getSchemeId().empty())
11238  {
11239  AAMPLOG_INFO("Preferred accessibility SchemeId: %s", inputTextAccessibilityNode.getSchemeId().c_str());
11240  if (inputTextAccessibilityNode.getTypeName() == "string_value")
11241  {
11242  AAMPLOG_INFO("Preferred accessibility Value Type %s and Value: %s", inputTextAccessibilityNode.getTypeName().c_str(),
11243  inputTextAccessibilityNode.getStrValue().c_str());
11244  }
11245  else
11246  {
11247  AAMPLOG_INFO("Preferred accessibility Value Type %s and Value : %d", inputTextAccessibilityNode.getTypeName().c_str(),
11248  inputTextAccessibilityNode.getIntValue());
11249  }
11250  }
11251  if(inputTextAccessibilityNode != preferredTextAccessibilityNode)
11252  {
11253  accessibilityPresent = true;
11254  }
11255  }
11256  }
11257 
11258  /**< Release json object **/
11259  delete jsObject;
11260  jsObject = NULL;
11261 
11262  if((inputTextLanguagesList != preferredTextLanguagesList) || (inputTextRenditionString != preferredTextRenditionString) ||
11263  (inputTextAccessibilityNode != preferredTextAccessibilityNode))
11264  {
11265  isRetuneNeeded = true;
11266  }
11267 
11272  preferredTextLabelString.clear();
11273 
11274  preferredTextLanguagesList = inputTextLanguagesList;
11275  preferredTextLanguagesString = inputTextLanguagesString;
11276  preferredTextRenditionString = inputTextRenditionString;
11277  preferredTextAccessibilityNode = inputTextAccessibilityNode;
11278  preferredTextLabelString = inputTextLabelString;
11279  preferredTextTypeString = inputTextTypeString;
11280 
11281  SETCONFIGVALUE_PRIV(AAMP_APPLICATION_SETTING,eAAMPConfig_PreferredTextLanguage,preferredTextLanguagesString);
11282  SETCONFIGVALUE_PRIV(AAMP_APPLICATION_SETTING,eAAMPConfig_PreferredTextRendition,preferredTextRenditionString);
11283  SETCONFIGVALUE_PRIV(AAMP_APPLICATION_SETTING,eAAMPConfig_PreferredTextLabel,preferredTextLabelString);
11284  SETCONFIGVALUE_PRIV(AAMP_APPLICATION_SETTING,eAAMPConfig_PreferredTextType,preferredTextTypeString);
11285  }
11286  else if( param )
11287  {
11288  AAMPLOG_INFO("Setting Text Languages %s", param);
11289  std::string inputTextLanguagesString;
11290  inputTextLanguagesString = std::string(param);
11291 
11292  if (inputTextLanguagesString != preferredTextLanguagesString)
11293  {
11294  isRetuneNeeded = true;
11295  }
11297  preferredTextLanguagesList.push_back(inputTextLanguagesString);
11298  preferredTextLanguagesString = inputTextLanguagesString;
11299  SETCONFIGVALUE_PRIV(AAMP_APPLICATION_SETTING, eAAMPConfig_PreferredTextLanguage, preferredTextLanguagesString);
11300  }
11301  else
11302  {
11303  AAMPLOG_INFO("No valid Parameter Recieved");
11304  return;
11305  }
11306 
11307  PrivAAMPState state;
11308  GetState(state);
11309  if (state != eSTATE_IDLE && state != eSTATE_RELEASED && state != eSTATE_ERROR && isRetuneNeeded )
11310  { // active playback session; apply immediately
11312  {
11313  bool languagePresent = false;
11314  bool renditionPresent = false;
11315  bool accessibilityTypePresent = false;
11316  bool codecPresent = false;
11317  bool labelPresent = false;
11318  int trackIndex = GetTextTrack();
11319  bool languageAvailabilityInManifest = false;
11320  bool renditionAvailabilityInManifest = false;
11321  bool accessibilityAvailabilityInManifest = false;
11322  bool labelAvailabilityInManifest = false;
11323  bool trackNotEnabled = false;
11324 
11325  if (trackIndex >= 0)
11326  {
11327  std::vector<TextTrackInfo> trackInfo = mpStreamAbstractionAAMP->GetAvailableTextTracks();
11328  char *currentPrefLanguage = const_cast<char*>(trackInfo[trackIndex].language.c_str());
11329  char *currentPrefRendition = const_cast<char*>(trackInfo[trackIndex].rendition.c_str());
11330 
11331  // Logic to check whether the given language is present in the available tracks,
11332  // if available, it should not match with current preferredLanguagesString, then call tune to reflect the language change.
11333  // if not available, then avoid calling tune.
11334  if(preferredTextLanguagesList.size() > 0)
11335  {
11336  std::string firstLanguage = preferredTextLanguagesList.at(0);
11337  auto language = std::find_if(trackInfo.begin(), trackInfo.end(),
11338  [firstLanguage, currentPrefLanguage](TextTrackInfo& temp)
11339  { return ((temp.language == firstLanguage) && (temp.language != currentPrefLanguage)); });
11340  languagePresent = (language != end(trackInfo) || (preferredTextLanguagesList.size() > 1)); /* If multiple value of language is present then retune */
11341  auto languageAvailable = std::find_if(trackInfo.begin(), trackInfo.end(),
11342  [firstLanguage, currentPrefLanguage](TextTrackInfo& temp)
11343  { return ((temp.language == firstLanguage) && (temp.language != currentPrefLanguage) && (temp.isAvailable)); });
11344  languageAvailabilityInManifest = (languageAvailable != end(trackInfo) && languageAvailable->isAvailable);
11345  }
11346 
11347  // Logic to check whether the given rendition is present in the available tracks,
11348  // if available, it should not match with current preferredTextRenditionString, then call tune to reflect the rendition change.
11349  // if not available, then avoid calling tune.
11350  if(!preferredTextRenditionString.empty())
11351  {
11352  std::string curRendition = preferredTextRenditionString;
11353  auto rendition = std::find_if(trackInfo.begin(), trackInfo.end(),
11354  [curRendition, currentPrefRendition](TextTrackInfo& temp)
11355  { return ((temp.rendition == curRendition) && (temp.rendition != currentPrefRendition)); });
11356  renditionPresent = (rendition != end(trackInfo));
11357  auto renditionAvailable = std::find_if(trackInfo.begin(), trackInfo.end(),
11358  [curRendition, currentPrefRendition](TextTrackInfo& temp)
11359  { return ((temp.rendition == curRendition) && (temp.rendition != currentPrefRendition) && (temp.isAvailable)); });
11360  renditionAvailabilityInManifest = ((renditionAvailable != end(trackInfo)) && renditionAvailable->isAvailable);
11361  }
11362  }
11363  else
11364  {
11365  trackNotEnabled = true;
11366  }
11367 
11368  if((mMediaFormat == eMEDIAFORMAT_HDMI) || (mMediaFormat == eMEDIAFORMAT_COMPOSITE) || (mMediaFormat == eMEDIAFORMAT_OTA) || \
11369  (mMediaFormat == eMEDIAFORMAT_RMF))
11370  {
11371  /**< Avoid retuning in case of HEMIIN and COMPOSITE IN*/
11372  }
11373  else if (languagePresent || renditionPresent || accessibilityPresent || trackNotEnabled) /**< call the tune only if there is a change in the language, rendition or accessibility.*/
11374  {
11375  discardEnteringLiveEvt = true;
11377  mOffsetFromTunetimeForSAPWorkaround = (double)(aamp_GetCurrentTimeMS() / 1000) - mLiveOffset;
11378  mLanguageChangeInProgress = true;
11380  TeardownStream(false);
11381  if(IsTSBSupported() &&
11382  ((languagePresent && !languageAvailabilityInManifest) ||
11383  (renditionPresent && !renditionAvailabilityInManifest) ||
11384  (accessibilityTypePresent && !accessibilityAvailabilityInManifest) ||
11385  (labelPresent && !labelAvailabilityInManifest)))
11386  {
11387  ReloadTSB();
11388  }
11389 
11391  discardEnteringLiveEvt = false;
11393  }
11394  }
11395  }
11396 }
11397 
11398 #define WV_KID_WORKAROUND "SkyStoreDE="
11399 
11400 /**
11401  * @brief get the SkyDE Store workaround
11402  */
11404 {
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",
11410  pos, url.at(pos));
11411  enable = (url.at(pos) == '1');
11412  }
11413 
11414  return enable;
11415 }
11416 
11417 //#define ENABLE_DUMP 1 //uncomment this to enable dumping of PSSH Data
11418 
11419 /**
11420  * @brief Replace KeyID from PsshData
11421  */
11422 unsigned char* PrivateInstanceAAMP::ReplaceKeyIDPsshData(const unsigned char *InputData, const size_t InputDataLength, size_t & OutputDataLength)
11423 {
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, //dummy KeyId (16 byte)
11437  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //dummy KeyId (16 byte)
11438  0x22, 0x06, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x37
11439  };
11440  if (InputData){
11441  AAMPLOG_INFO("Converting system UUID of PSSH data size (%zu)", InputDataLength);
11442 #ifdef ENABLE_DUMP
11443  AAMPLOG_INFO("PSSH Data (%d) Before Modification : ", InputDataLength);
11444  DumpBlob(InputData, InputDataLength);
11445 #endif
11446 
11447  /** Replace KeyID of WV PSSH Data with Key ID of CK PSSH Data **/
11448  int iWVpssh = WIDEVINE_PSSH_KEYID_OFFSET;
11449  int CKPssh = CK_PSSH_KEYID_OFFSET;
11450  int size = 0;
11451  if (CK_PSSH_KEYID_OFFSET+COMMON_KEYID_SIZE <= InputDataLength){
11452  for (; size < COMMON_KEYID_SIZE; ++size, ++iWVpssh, ++CKPssh ){
11453  /** Transfer KeyID from CK PSSH data to WV PSSH Data **/
11454  WVSamplePSSH[iWVpssh] = InputData[CKPssh];
11455  }
11456 
11457  /** Allocate WV PSSH Data memory and transfer local data **/
11458  OutpuData = (unsigned char *)malloc(sizeof(WVSamplePSSH));
11459  if (OutpuData){
11460  memcpy(OutpuData, WVSamplePSSH, sizeof(WVSamplePSSH));
11461  OutputDataLength = sizeof(WVSamplePSSH);
11462 #ifdef ENABLE_DUMP
11463  AAMPLOG_INFO("PSSH Data (%d) after Modification : ", OutputDataLength);
11464  DumpBlob(OutpuData, OutputDataLength);
11465 #endif
11466  return OutpuData;
11467 
11468  }else{
11469  AAMPLOG_ERR("PSSH Data Memory allocation failed ");
11470  }
11471  }else{
11472  //Invalid PSSH data
11473  AAMPLOG_ERR("Invalid Clear Key PSSH data ");
11474  }
11475  }else{
11476  //Inalid argument - PSSH Data
11477  AAMPLOG_ERR("Invalid Argument of PSSH data ");
11478  }
11479  return NULL;
11480 }
11481 
11482 /**
11483  * @brief Check if segment starts with an ID3 section
11484  */
11485 bool PrivateInstanceAAMP::hasId3Header(const uint8_t* data, uint32_t length)
11486 {
11487  if (length >= 3)
11488  {
11489  /* Check file identifier ("ID3" = ID3v2) and major revision matches (>= ID3v2.2.x). */
11490  if (*data++ == 'I' && *data++ == 'D' && *data++ == '3' && *data++ >= 2)
11491  {
11492  return true;
11493  }
11494  }
11495  return false;
11496 }
11497 
11498 /**
11499  * @brief Process the ID3 metadata from segment
11500  */
11501 void PrivateInstanceAAMP::ProcessID3Metadata(char *segment, size_t size, MediaType type, uint64_t timeStampOffset)
11502 {
11503  // Logic for ID3 metadata
11505  {
11506  IsoBmffBuffer buffer(mLogObj);
11507  buffer.setBuffer((uint8_t *)segment, size);
11508  buffer.parseBuffer();
11509  if(!buffer.isInitSegment())
11510  {
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;
11518  uint32_t id = 0;
11519  if(buffer.getEMSGData(message, messageLen, schemeIDUri, value, presTime, timeScale, eventDuration, id))
11520  {
11521  if(message && messageLen > 0 && hasId3Header(message, messageLen))
11522  {
11523  AAMPLOG_TRACE("PrivateInstanceAAMP: Found ID3 metadata[%d]", type);
11524  if(mMediaFormat == eMEDIAFORMAT_DASH)
11525  {
11526  ReportID3Metadata(type, message, messageLen, (char*)(schemeIDUri), (char*)(value), presTime, id, eventDuration, timeScale, GetMediaStreamContext(type)->timeStampOffset);
11527  }else
11528  {
11529  ReportID3Metadata(type, message, messageLen, (char*)(schemeIDUri), (char*)(value), presTime, id, eventDuration, timeScale);
11530  }
11531  }
11532  }
11533  }
11534  }
11535 }
11536 
11537 /**
11538  * @brief Report ID3 metadata events
11539  */
11540 void PrivateInstanceAAMP::ReportID3Metadata(MediaType mediaType, const uint8_t* ptr, uint32_t len, const char* schemeIdURI, const char* id3Value, uint64_t presTime, uint32_t id3ID, uint32_t eventDur, uint32_t tScale, uint64_t tStampOffset)
11541 {
11542  FlushLastId3Data(mediaType);
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);
11544  lastId3Data[mediaType] = (uint8_t*)aamp_Malloc(len);
11545  if (lastId3Data[mediaType])
11546  {
11547  lastId3DataLen[mediaType] = len;
11548  memcpy(lastId3Data[mediaType], ptr, len);
11549  }
11550 
11551  SendId3MetadataEvent(id3Metadata);
11552  SAFE_DELETE(id3Metadata);
11553 }
11554 
11555 /**
11556  * @brief Flush last saved ID3 metadata
11557  */
11559 {
11560  if(lastId3Data[mediaType])
11561  {
11562  lastId3DataLen[mediaType] = 0;
11563  aamp_Free((void *)lastId3Data[mediaType]);
11564  lastId3Data[mediaType] = NULL;
11565  }
11566 }
11567 
11568 /**
11569  * @brief GetPauseOnFirstVideoFrameDisplay
11570  */
11572 {
11574 }
11575 
11576 /**
11577  * @brief Sets Low Latency Service Data
11578  */
11580 {
11581  this->mAampLLDashServiceData = stAampLLDashServiceData;
11582 }
11583 
11584 /**
11585  * @brief Gets Low Latency Service Data
11586  */
11588 {
11589  return &this->mAampLLDashServiceData;
11590 }
11591 
11592 
11593 /**
11594  * @brief Sets Low Video TimeScale
11595  */
11596 void PrivateInstanceAAMP::SetVidTimeScale(uint32_t vidTimeScale)
11597 {
11598  this->vidTimeScale = vidTimeScale;
11599 }
11600 
11601 /**
11602  * @brief Gets Video TimeScale
11603  */
11605 {
11606  return vidTimeScale;
11607 }
11608 
11609 /**
11610  * @brief Sets Low Audio TimeScale
11611  */
11612 void PrivateInstanceAAMP::SetAudTimeScale(uint32_t audTimeScale)
11613 {
11614  this->audTimeScale = audTimeScale;
11615 }
11616 
11617 /**
11618  * @brief Gets Audio TimeScale
11619  */
11621 {
11622  return audTimeScale;
11623 }
11624 /**
11625  * @brief Sets Speed Cache
11626  */
11628 {
11629  this->speedCache = speedCache;
11630 }
11631 
11632 /**
11633  * @brief Gets Speed Cache
11634  */
11636 {
11637  return &speedCache;
11638 }
11639 
11641 {
11642  return mLiveOffsetAppRequest;
11643 }
11644 
11645 /**
11646  * @brief set LiveOffset Request flag Status
11647  */
11648 void PrivateInstanceAAMP::SetLiveOffsetAppRequest(bool LiveOffsetAppRequest)
11649 {
11650  this->mLiveOffsetAppRequest = LiveOffsetAppRequest;
11651 }
11652 /**
11653  * @brief Get Low Latency Service Configuration Status
11654  */
11656 {
11657  return bLowLatencyServiceConfigured;
11658 }
11659 
11660 /**
11661  * @brief Set Low Latency Service Configuration Status
11662  */
11664 {
11665  bLowLatencyServiceConfigured = bConfig;
11666 }
11667 
11668 /**
11669  * @brief Get Utc Time
11670  */
11672 {
11673  return mTime;
11674 }
11675 
11676 /**
11677  * @brief Set Utc Time
11678  */
11680 {
11681  this->mTime = time;
11682 }
11683 
11684 /**
11685  * @brief Get Current Latency
11686  */
11688 {
11689  return mCurrentLatency;
11690 }
11691 
11692 /**
11693  * @brief Set Current Latency
11694  */
11696 {
11697  this->mCurrentLatency = currentLatency;
11698 }
11699 
11700 /**
11701  * @brief Get Media Stream Context
11702  */
11704 {
11706  (type == eMEDIATYPE_VIDEO ||
11707  type == eMEDIATYPE_AUDIO ||
11708  type == eMEDIATYPE_SUBTITLE ||
11709  type == eMEDIATYPE_AUX_AUDIO))
11710  {
11712  return context;
11713  }
11714  return NULL;
11715 }
11716 
11717 /**
11718  * @brief GetPeriodDurationTimeValue
11719  */
11721 {
11722  return mNextPeriodDuration;
11723 }
11724 
11725 /**
11726  * @brief GetPeriodStartTimeValue
11727  */
11729 {
11730  return mNextPeriodStartTime;
11731 }
11732 
11733 /**
11734  * @brief GetPeriodScaledPtoStartTime
11735  */
11737 {
11739 }
11740 
11741 /**
11742  * @brief Get playback stats for the session so far
11743  */
11745 {
11746  std::string strVideoStatsJson;
11747  long liveLatency = 0;
11748  //Update liveLatency only when playback is active and live
11750  liveLatency = mpStreamAbstractionAAMP->GetBufferedVideoDurationSec() * 1000.0;
11751 
11752  if(mVideoEnd)
11753  {
11754  mVideoEnd->setPlaybackMode(mPlaybackMode);
11755  mVideoEnd->setLiveLatency(liveLatency);
11756  mVideoEnd->SetDisplayResolution(mDisplayWidth,mDisplayHeight);
11757  //Update VideoEnd Data
11758  if(mTimeAtTopProfile > 0)
11759  {
11760  // Losing milisecons of data in conversion from double to long
11761  mVideoEnd->SetTimeAtTopProfile(mTimeAtTopProfile);
11762  mVideoEnd->SetTimeToTopProfile(mTimeToTopProfile);
11763  }
11764  mVideoEnd->SetTotalDuration(mPlaybackDuration);
11765  char * videoStatsPtr = mVideoEnd->ToJsonString(nullptr, true);
11766  if(videoStatsPtr)
11767  {
11768  strVideoStatsJson = videoStatsPtr;
11769  free(videoStatsPtr);
11770  }
11771  }
11772  else
11773  {
11774  AAMPLOG_ERR("GetPlaybackStats failed, mVideoEnd is NULL");
11775  }
11776 
11777  if(!strVideoStatsJson.empty())
11778  {
11779  AAMPLOG_INFO("Playback stats json:%s", strVideoStatsJson.c_str());
11780  }
11781  else
11782  {
11783  AAMPLOG_ERR("Failed to retrieve playback stats (video stats returned as empty from aamp metrics)");
11784  }
11785  return strVideoStatsJson;
11786 }
11787 
11788 /**
11789 * @brief LoadFogConfig - Load needed player Config to Fog
11790 */
11792 {
11793  std::string jsonStr;
11794  AampJsonObject jsondata;
11795  double tmpVar = 0;
11796  long tmpLongVar = 0;
11797  int maxdownload = 0;
11798 
11799  // langCodePreference
11800  jsondata.add("langCodePreference", (int) GetLangCodePreference());
11801 
11802  // networkTimeout value in sec and convert into MS
11803  GETCONFIGVALUE_PRIV(eAAMPConfig_NetworkTimeout,tmpVar);
11804  jsondata.add("downloadTimeoutMS", (long)CONVERT_SEC_TO_MS(tmpVar));
11805 
11806  tmpVar = 0;
11807  // manifestTimeout value in sec and convert into MS
11808  GETCONFIGVALUE_PRIV(eAAMPConfig_ManifestTimeout,tmpVar);
11809  jsondata.add("manifestTimeoutMS", (long)CONVERT_SEC_TO_MS(tmpVar));
11810 
11811  tmpLongVar = 0;
11812  //downloadStallTimeout in sec
11813  GETCONFIGVALUE_PRIV(eAAMPConfig_CurlStallTimeout,tmpLongVar);
11814  jsondata.add("downloadStallTimeout", tmpLongVar);
11815 
11816  tmpLongVar = 0;
11817  //downloadStartTimeout sec
11818  GETCONFIGVALUE_PRIV(eAAMPConfig_CurlDownloadStartTimeout,tmpLongVar);
11819  jsondata.add("downloadStartTimeout", tmpLongVar);
11820 
11821  tmpLongVar = 0;
11822  //downloadStartTimeout sec
11823  GETCONFIGVALUE_PRIV(eAAMPConfig_CurlDownloadLowBWTimeout,tmpLongVar);
11824  jsondata.add("downloadLowBWTimeout", tmpLongVar);
11825 
11826  //maxConcurrentDownloads
11827  GETCONFIGVALUE_PRIV(eAAMPConfig_FogMaxConcurrentDownloads, maxdownload);
11828  jsondata.add("maxConcurrentDownloads", (long)(maxdownload));
11829 
11830  //disableEC3
11831  jsondata.add("disableEC3", ISCONFIGSET_PRIV(eAAMPConfig_DisableEC3));
11832 
11833  //disableATMOS
11834  jsondata.add("disableATMOS", ISCONFIGSET_PRIV(eAAMPConfig_DisableATMOS));
11835 
11836  //disableAC4
11837  jsondata.add("disableAC4", ISCONFIGSET_PRIV(eAAMPConfig_DisableAC4));
11838 
11839  //persistLowNetworkBandwidth
11840  jsondata.add("persistLowNetworkBandwidth", ISCONFIGSET_PRIV(eAAMPConfig_PersistLowNetworkBandwidth));
11841 
11842  //disableAC3
11843  jsondata.add("disableAC3", ISCONFIGSET_PRIV(eAAMPConfig_DisableAC3));
11844 
11845  //persistHighNetworkBandwidth
11846  jsondata.add("persistHighNetworkBandwidth", ISCONFIGSET_PRIV(eAAMPConfig_PersistHighNetworkBandwidth));
11847 
11848  //enableCMCD
11849  jsondata.add("enableCMCD", ISCONFIGSET_PRIV(eAAMPConfig_EnableCMCD));
11850 
11851  //info
11852  jsondata.add("info", ISCONFIGSET_PRIV(eAAMPConfig_InfoLogging));
11853 
11854  //tsbInterruptHandling
11855  jsondata.add("tsbInterruptHandling", ISCONFIGSET_PRIV(eAAMPConfig_InterruptHandling));
11856 
11857  /*
11858  * Audio and subtitle preference
11859  * Disabled this for XRE supported TSB linear
11860  */
11861  if (!ISCONFIGSET_PRIV(eAAMPConfig_XRESupportedTune))
11862  {
11863  AampJsonObject jsondataForPreference;
11864  AampJsonObject audioPreference;
11865  AampJsonObject subtitlePreference;
11866  bool aPrefAvail = false;
11867  bool tPrefAvail = false;
11868  if((preferredLanguagesList.size() > 0) || !preferredRenditionString.empty() || !preferredLabelsString.empty() || !preferredAudioAccessibilityNode.getSchemeId().empty())
11869  {
11870  aPrefAvail = true;
11871  if ((preferredLanguagesList.size() > 0) && (GETCONFIGOWNER_PRIV(eAAMPConfig_PreferredAudioLanguage) > AAMP_DEFAULT_SETTING ))
11872  {
11873  audioPreference.add("languages", preferredLanguagesList);
11874  }
11876  {
11877  audioPreference.add("rendition", preferredRenditionString);
11878  }
11879  if(!preferredLabelsString.empty() && (GETCONFIGOWNER_PRIV(eAAMPConfig_PreferredAudioLabel) > AAMP_DEFAULT_SETTING ))
11880  {
11881  audioPreference.add("label", preferredLabelsString);
11882  }
11883  if(!preferredAudioAccessibilityNode.getSchemeId().empty())
11884  {
11885  AampJsonObject accessiblity;
11886  std::string schemeId = preferredAudioAccessibilityNode.getSchemeId();
11887  accessiblity.add("schemeId", schemeId);
11888  std::string value;
11889  if(preferredAudioAccessibilityNode.getTypeName() == "int_value")
11890  {
11891  value = std::to_string(preferredAudioAccessibilityNode.getIntValue());
11892  }
11893  else
11894  {
11895  value = preferredAudioAccessibilityNode.getStrValue();
11896  }
11897  accessiblity.add("value", value);
11898  audioPreference.add("accessibility", accessiblity);
11899  }
11900  }
11901 #if 0
11902  /** Time being disabled due to issues - LLAMA-7953, LLAMA-7760 **/
11903 
11904  if((preferredTextLanguagesList.size() > 0) || !preferredTextRenditionString.empty() || !preferredTextLabelString.empty() || !preferredTextAccessibilityNode.getSchemeId().empty())
11905  {
11906  tPrefAvail = true;
11907  if ((preferredTextLanguagesList.size() > 0) && (GETCONFIGOWNER_PRIV(eAAMPConfig_PreferredTextLanguage) > AAMP_DEFAULT_SETTING ))
11908  {
11909  subtitlePreference.add("languages", preferredTextLanguagesList);
11910  }
11912  {
11913  subtitlePreference.add("rendition", preferredTextRenditionString);
11914  }
11915  if(!preferredTextLabelString.empty() && (GETCONFIGOWNER_PRIV(eAAMPConfig_PreferredTextLabel) > AAMP_DEFAULT_SETTING ))
11916  {
11917  subtitlePreference.add("label", preferredTextLabelString);
11918  }
11919  if(!preferredTextAccessibilityNode.getSchemeId().empty())
11920  {
11921  AampJsonObject accessiblity;
11922  std::string schemeId = preferredTextAccessibilityNode.getSchemeId();
11923  accessiblity.add("schemeId", schemeId);
11924  std::string value;
11925  if(preferredTextAccessibilityNode.getTypeName() == "int_value")
11926  {
11927  value = std::to_string(preferredTextAccessibilityNode.getIntValue());
11928  }
11929  else
11930  {
11931  value = preferredTextAccessibilityNode.getStrValue();
11932  }
11933  accessiblity.add("value", value);
11934  subtitlePreference.add("accessibility", accessiblity);
11935  }
11936  }
11937 #endif
11938  bool trackAdded = false;
11939  if(aPrefAvail)
11940  {
11941  jsondataForPreference.add("audio", audioPreference);
11942  trackAdded = true;
11943  }
11944  if(tPrefAvail)
11945  {
11946  jsondataForPreference.add("text", subtitlePreference);
11947  trackAdded = true;
11948  }
11949 
11950  if(trackAdded)
11951  {
11952  jsondata.add("trackPreference", jsondataForPreference);
11953  }
11954  }
11955 
11956 
11957  jsonStr = jsondata.print_UnFormatted();
11958  AAMPLOG_TRACE("%s", jsonStr.c_str());
11959  std::string remoteUrl = "127.0.0.1:9080/playerconfig";
11960  long http_error = -1;
11961  ProcessCustomCurlRequest(remoteUrl, NULL, &http_error, eCURL_POST, jsonStr);
11962  return http_error;
11963 }
11964 
11965 
11966 /**
11967  * @brief -To Load needed config from player to aampabr
11968  */
11970 {
11971  HybridABRManager::AampAbrConfig mhAampAbrConfig;
11972  // ABR config values
11973  GETCONFIGVALUE_PRIV(eAAMPConfig_ABRCacheLife,mhAampAbrConfig.abrCacheLife);
11974  GETCONFIGVALUE_PRIV(eAAMPConfig_ABRCacheLength,mhAampAbrConfig.abrCacheLength);
11975  GETCONFIGVALUE_PRIV(eAAMPConfig_ABRSkipDuration,mhAampAbrConfig.abrSkipDuration);
11976  GETCONFIGVALUE_PRIV(eAAMPConfig_ABRNWConsistency,mhAampAbrConfig.abrNwConsistency);
11977  GETCONFIGVALUE_PRIV(eAAMPConfig_ABRThresholdSize,mhAampAbrConfig.abrThresholdSize);
11978  GETCONFIGVALUE_PRIV(eAAMPConfig_MaxABRNWBufferRampUp,mhAampAbrConfig.abrMaxBuffer);
11979  GETCONFIGVALUE_PRIV(eAAMPConfig_MinABRNWBufferRampDown,mhAampAbrConfig.abrMinBuffer);
11980 
11981  // Logging level support on aampabr
11982 
11983  mhAampAbrConfig.infologging = (ISCONFIGSET_PRIV(eAAMPConfig_InfoLogging) ? 1 :0);
11984  mhAampAbrConfig.debuglogging = (ISCONFIGSET_PRIV(eAAMPConfig_DebugLogging) ? 1 :0);
11985  mhAampAbrConfig.tracelogging = (ISCONFIGSET_PRIV(eAAMPConfig_TraceLogging) ? 1:0);
11986  mhAampAbrConfig.warnlogging = (ISCONFIGSET_PRIV(eAAMPConfig_WarnLogging) ? 1:0);
11987 
11988  mhAbrManager.ReadPlayerConfig(&mhAampAbrConfig);
11989 }
11990 
11991 /**
11992  * @brief Get License Custom Data
11993  */
11995 {
11996  std::string customData;
11997  GETCONFIGVALUE_PRIV(eAAMPConfig_CustomLicenseData,customData);
11998  return customData;
11999 }
12000 
12001 /**
12002  * @brief check if sidecar data available
12003  */
12005 {
12006  if (mData != NULL)
12007  {
12008  return true;
12009  }
12010  return false;
12011 }
PrivateInstanceAAMP::SendStalledErrorEvent
void SendStalledErrorEvent()
Send stalled events to listeners.
Definition: priv_aamp.cpp:8435
AAMP_EVENT_ASYNC_MODE
@ AAMP_EVENT_ASYNC_MODE
Definition: AampEvent.h:101
compositein_shim.h
shim for dispatching UVE Composite input playback
AampCCManagerBase::Release
virtual void Release(int iID)=0
Release CC resources.
PrivateInstanceAAMP::ExtractServiceZone
void ExtractServiceZone(std::string url)
updates mServiceZone (service zone) member with string extracted from locator &sz URI parameter
Definition: priv_aamp.cpp:5992
eHTTPHEADERTYPE_FOG_REASON
@ eHTTPHEADERTYPE_FOG_REASON
Definition: priv_aamp.h:231
progress_callback
static int progress_callback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
Definition: priv_aamp.cpp:1260
eAAMPConfig_CurlDownloadStartTimeout
@ eAAMPConfig_CurlDownloadStartTimeout
Definition: AampConfig.h:273
eTUNED_EVENT_ON_GST_PLAYING
@ eTUNED_EVENT_ON_GST_PLAYING
Definition: AampDefine.h:188
PrivateInstanceAAMP::GetVidTimeScale
uint32_t GetVidTimeScale(void)
Gets Video TimeScale.
Definition: priv_aamp.cpp:11604
AAMP_LogLevel
AAMP_LogLevel
Log level's of AAMP.
Definition: AampLogManager.h:97
PrivateInstanceAAMP::SetCurlTimeout
void SetCurlTimeout(long timeout, AampCurlInstance instance)
Set curl timeout(CURLOPT_TIMEOUT)
Definition: priv_aamp.cpp:3315
AampDRMSessionManager.h
Header file for DRM session manager.
PrivateInstanceAAMP::mProgressReportOffset
double mProgressReportOffset
Definition: priv_aamp.h:1065
BITRATE_ALLOWED_VARIATION_BAND
#define BITRATE_ALLOWED_VARIATION_BAND
Definition: AampDefine.h:110
AudioTrackInfo::isMuxed
bool isMuxed
Definition: main_aamp.h:193
StreamAbstractionAAMP::EnableContentRestrictions
virtual void EnableContentRestrictions()
Enable Content Restrictions - lock.
Definition: StreamAbstractionAAMP.h:1291
eAAMPConfig_PreferredTextLabel
@ eAAMPConfig_PreferredTextLabel
Definition: AampConfig.h:318
PrivateInstanceAAMP::IsUninterruptedTSB
bool IsUninterruptedTSB()
Checking whether fog is giving uninterrupted TSB.
Definition: priv_aamp.h:1693
TuneEndMetrics::mTimedMetadata
int mTimedMetadata
Definition: AampProfiler.h:128
PrivateInstanceAAMP::GetLicenseServerUrlForDrm
std::string GetLicenseServerUrlForDrm(DRMSystems type)
Get license server url for a drm type.
Definition: priv_aamp.cpp:9950
eAAMPConfig_PlaylistTimeout
@ eAAMPConfig_PlaylistTimeout
Definition: AampConfig.h:285
AAMP_TUNE_INIT_FAILED_MANIFEST_PARSE_ERROR
@ AAMP_TUNE_INIT_FAILED_MANIFEST_PARSE_ERROR
Definition: AampEvent.h:113
StreamAbstractionAAMP::GetMediaTrack
virtual MediaTrack * GetMediaTrack(TrackType type)=0
Return MediaTrack of requested type.
PrivateInstanceAAMP::SetLiveOffsetAppRequest
void SetLiveOffsetAppRequest(bool LiveOffsetAppRequest)
set LiveOffset Request flag Status
Definition: priv_aamp.cpp:11648
AampLogManager::trace
bool trace
Definition: AampLogManager.h:156
PrivateInstanceAAMP::LogDrmInitComplete
void LogDrmInitComplete(void)
Notifies profiler that drm initialization is complete.
Definition: priv_aamp.cpp:3123
CDAIObjectMPD
Client Side DAI object implementation for DASH.
Definition: admanager_mpd.h:44
aamp_Free
void aamp_Free(void *ptr)
wrapper for g_free, used for segment allocation
Definition: AampMemoryUtils.cpp:56
eCURLINSTANCE_AUDIO
@ eCURLINSTANCE_AUDIO
Definition: priv_aamp.h:159
PrivateInstanceAAMP::SendMessage2Receiver
void SendMessage2Receiver(AAMP2ReceiverMsgType type, const char *data)
Send message to reciever over PIPE.
Definition: priv_aamp.cpp:4851
ota_shim.h
shim for dispatching UVE OTA ATSC playback
PrivateInstanceAAMP::GetAudioTrack
int GetAudioTrack()
Get current audio track index.
Definition: priv_aamp.cpp:9976
eMEDIATYPE_TELEMETRY_UNKNOWN
@ eMEDIATYPE_TELEMETRY_UNKNOWN
Definition: main_aamp.h:98
eAAMPConfig_CurlLicenseLogging
@ eAAMPConfig_CurlLicenseLogging
Definition: AampConfig.h:144
PrivateInstanceAAMP::SendTunedEvent
bool SendTunedEvent(bool isSynchronous=true)
Send tuned event to listeners if required.
Definition: priv_aamp.cpp:7826
AampScheduler::ScheduleTask
int ScheduleTask(AsyncTaskObj obj)
To schedule a task to be executed later.
Definition: AampScheduler.cpp:64
PrivateInstanceAAMP::mInitSuccess
bool mInitSuccess
Definition: priv_aamp.h:811
PrivateInstanceAAMP::mParallelPlaylistFetchLock
pthread_mutex_t mParallelPlaylistFetchLock
Definition: priv_aamp.h:805
AAMP_TUNE_INIT_FAILED_PLAYLIST_VIDEO_DNLD_ERROR
@ AAMP_TUNE_INIT_FAILED_PLAYLIST_VIDEO_DNLD_ERROR
Definition: AampEvent.h:114
eAAMPConfig_Fog
@ eAAMPConfig_Fog
Definition: AampConfig.h:98
eDRM_WideVine
@ eDRM_WideVine
Definition: AampDrmSystems.h:36
PrivateInstanceAAMP::SignalTrickModeDiscontinuity
void SignalTrickModeDiscontinuity()
Signal trick mode discontinuity to stream sink.
Definition: priv_aamp.cpp:9100
PrivateInstanceAAMP::SendAdResolvedEvent
void SendAdResolvedEvent(const std::string &adId, bool status, uint64_t startMS=0, uint64_t durationMs=0)
Send status of Ad manifest downloading & parsing.
Definition: priv_aamp.cpp:8884
PrivateInstanceAAMP::mEncryptedPeriodFound
bool mEncryptedPeriodFound
Definition: priv_aamp.h:1033
eCURLINSTANCE_SUBTITLE
@ eCURLINSTANCE_SUBTITLE
Definition: priv_aamp.h:160
eAAMPConfig_InterruptHandling
@ eAAMPConfig_InterruptHandling
Definition: AampConfig.h:183
eMEDIAFORMAT_PROGRESSIVE
@ eMEDIAFORMAT_PROGRESSIVE
Definition: AampDrmMediaFormat.h:36
StreamSink::GetVideoRectangle
virtual std::string GetVideoRectangle()
Get the video window co-ordinates.
Definition: main_aamp.h:668
StreamOutputFormat
StreamOutputFormat
Media output format.
Definition: main_aamp.h:106
TuneEndMetrics
TuneEndMetrics structure to store tunemetrics data.
Definition: AampProfiler.h:124
PrivateInstanceAAMP::mPreferredTextTrack
TextTrackInfo mPreferredTextTrack
Definition: priv_aamp.h:4059
eGST_ERROR_GST_PIPELINE_INTERNAL
@ eGST_ERROR_GST_PIPELINE_INTERNAL
Definition: priv_aamp.h:180
PrivateInstanceAAMP::ClosePipeSession
void ClosePipeSession()
Close PIPE session with Receiver.
Definition: priv_aamp.cpp:4816
StreamSink::StopBuffering
virtual void StopBuffering(bool forceStop)
Stop buffering in sink.
Definition: main_aamp.h:676
PrivateInstanceAAMP::UpdateVideoEndTsbStatus
void UpdateVideoEndTsbStatus(bool btsbAvailable)
updates time shift buffer status
Definition: priv_aamp.cpp:7938
ContentType_IVOD
@ ContentType_IVOD
Definition: AampProfiler.h:105
VIDEO_ZOOM_FULL
@ VIDEO_ZOOM_FULL
Definition: main_aamp.h:131
AampConfig::logging
AampLogManager logging
Definition: AampConfig.h:462
eAAMPSTATUS_PLAYLIST_VIDEO_DOWNLOAD_ERROR
@ eAAMPSTATUS_PLAYLIST_VIDEO_DOWNLOAD_ERROR
Definition: priv_aamp.h:211
PrivateInstanceAAMP::NotifyEOSReached
void NotifyEOSReached()
Process EOS from Sink and notify listeners if required.
Definition: priv_aamp.cpp:2831
PrivateInstanceAAMP_ProcessDiscontinuity
static gboolean PrivateInstanceAAMP_ProcessDiscontinuity(gpointer ptr)
Idle task to process discontinuity.
Definition: priv_aamp.cpp:341
AAMP_TUNE_GST_PIPELINE_ERROR
@ AAMP_TUNE_GST_PIPELINE_ERROR
Definition: AampEvent.h:138
StreamAbstractionAAMP::GetBufferedVideoDurationSec
double GetBufferedVideoDurationSec()
Get buffered video duration in seconds.
Definition: streamabstraction.cpp:2960
eTRACK_VIDEO
@ eTRACK_VIDEO
Definition: StreamAbstractionAAMP.h:50
PrivateInstanceAAMP::SetCallbackAsPending
void SetCallbackAsPending(guint id)
Set an idle callback as event pending state.
Definition: priv_aamp.cpp:8226
fragmentcollector_mpd.h
Fragment collector MPEG DASH declarations.
PrivateInstanceAAMP::GetMaximumBitrate
long GetMaximumBitrate()
Get maximum bitrate value.
Definition: priv_aamp.cpp:6285
aampoutputprotection.h
Output protection management for Aamp.
PrivateInstanceAAMP::preferredLanguagesString
std::string preferredLanguagesString
Definition: priv_aamp.h:964
eAAMPConfig_PreservePipeline
@ eAAMPConfig_PreservePipeline
Definition: AampConfig.h:100
PrivateInstanceAAMP::ResetCurrentlyAvailableBandwidth
void ResetCurrentlyAvailableBandwidth(long bitsPerSecond, bool trickPlay, int profile=0)
Reset bandwidth value Artificially resetting the bandwidth. Low for quicker tune times.
Definition: priv_aamp.cpp:3401
PrivateInstanceAAMP::mCMCDNextObjectRequest
std::string mCMCDNextObjectRequest
Definition: priv_aamp.h:847
eAAMPConfig_MapM3U8
@ eAAMPConfig_MapM3U8
Definition: AampConfig.h:295
eDRM_PlayReady
@ eDRM_PlayReady
Definition: AampDrmSystems.h:37
eMEDIATYPE_INIT_IFRAME
@ eMEDIATYPE_INIT_IFRAME
Definition: AampMediaType.h:55
PrivateInstanceAAMP::AAMP2ReceiverMsgType
AAMP2ReceiverMsgType
Definition: priv_aamp.h:643
eAAMPConfig_AudioOnlyPlayback
@ eAAMPConfig_AudioOnlyPlayback
Definition: AampConfig.h:122
PrivateInstanceAAMP::DeliverAdEvents
void DeliverAdEvents(bool immediate=false)
Deliver all pending Ad events to JSPP.
Definition: priv_aamp.cpp:8897
StreamAbstractionAAMP::SetCDAIObject
virtual void SetCDAIObject(CDAIObject *cdaiObj)
Set Client Side DAI object instance.
Definition: StreamAbstractionAAMP.h:1091
eAAMPConfig_SubTitleLanguage
@ eAAMPConfig_SubTitleLanguage
Definition: AampConfig.h:302
PrivateInstanceAAMP::SendDownloadErrorEvent
void SendDownloadErrorEvent(AAMPTuneFailure tuneFailure, long error_code)
Handles download errors and sends events to application if required.
Definition: priv_aamp.cpp:2330
PrivateInstanceAAMP::mIsIframeTrackPresent
bool mIsIframeTrackPresent
Definition: priv_aamp.h:993
sessionHandle
Definition: dtcpmgr.cpp:25
eSTATE_INITIALIZED
@ eSTATE_INITIALIZED
Definition: AampEvent.h:160
StreamAbstractionAAMP::GetESChangeStatus
bool GetESChangeStatus(void)
Get elementary stream type change status for reconfigure the pipeline..
Definition: StreamAbstractionAAMP.h:725
StreamSink::GetVideoSize
virtual void GetVideoSize(int &w, int &h)
Get the video dimensions.
Definition: main_aamp.h:628
iso639map.h
ISO639 is a standard with representation of names for languages.
PrivateInstanceAAMP::mpStreamAbstractionAAMP
class StreamAbstractionAAMP * mpStreamAbstractionAAMP
Definition: priv_aamp.h:807
AAMP_LOG_NETWORK_LATENCY
#define AAMP_LOG_NETWORK_LATENCY
Macro for Triage Level Logging Support.
Definition: AampLogManager.h:69
fragmentcollector_hls.h
This file handles HLS Streaming functionality for AAMP player
AampCCManagerBase::SetTrack
int SetTrack(const std::string &track, const CCFormat format=eCLOSEDCAPTION_FORMAT_DEFAULT)
Set CC track.
Definition: AampCCManager.cpp:651
eAAMPConfig_PreferredTextType
@ eAAMPConfig_PreferredTextType
Definition: AampConfig.h:319
eAAMPConfig_WVLicenseServerUrl
@ eAAMPConfig_WVLicenseServerUrl
Definition: AampConfig.h:300
eMEDIATYPE_VIDEO
@ eMEDIATYPE_VIDEO
Definition: AampMediaType.h:39
eAAMPConfig_HarvestCountLimit
@ eAAMPConfig_HarvestCountLimit
Definition: AampConfig.h:211
AudioTrackInfo::contentType
std::string contentType
Definition: main_aamp.h:190
AAMP_LIVE_OFFSET
#define AAMP_LIVE_OFFSET
Definition: AampDefine.h:80
AAMP_TUNE_INIT_FAILED
@ AAMP_TUNE_INIT_FAILED
Definition: AampEvent.h:110
eAAMPConfig_CurlDownloadLowBWTimeout
@ eAAMPConfig_CurlDownloadLowBWTimeout
Definition: AampConfig.h:274
PrivateInstanceAAMP::PushFragment
void PushFragment(MediaType mediaType, char *ptr, size_t len, double fragmentTime, double fragmentDuration)
Push fragment to the gstreamer.
Definition: priv_aamp.cpp:6386
StreamAbstractionAAMP::GetAudioFwdToAuxStatus
bool GetAudioFwdToAuxStatus()
Get audio forward to aux pipeline status.
Definition: StreamAbstractionAAMP.h:1298
PrivateInstanceAAMP::mbDetached
bool mbDetached
Definition: priv_aamp.h:1073
eAAMPConfig_WarnLogging
@ eAAMPConfig_WarnLogging
Definition: AampConfig.h:139
eDRM_ClearKey
@ eDRM_ClearKey
Definition: AampDrmSystems.h:41
PrivateInstanceAAMP::SetContentType
void SetContentType(const char *contentType)
Set Content Type.
Definition: priv_aamp.cpp:6121
CONVERT_SEC_TO_MS
#define CONVERT_SEC_TO_MS(_x_)
Definition: priv_aamp.h:121
eTUNETYPE_SEEK
@ eTUNETYPE_SEEK
Definition: priv_aamp.h:194
StreamSink::CheckForPTSChangeWithTimeout
virtual bool CheckForPTSChangeWithTimeout(long timeout)
Check if PTS is changing.
Definition: main_aamp.h:592
StreamAbstractionAAMP::Stop
virtual void Stop(bool clearChannelData)=0
Stops streaming.
PrivateInstanceAAMP::preferredTextLabelString
std::string preferredTextLabelString
Definition: priv_aamp.h:977
PrivateInstanceAAMP::mPlayerPreBuffered
bool mPlayerPreBuffered
Definition: priv_aamp.h:1024
AAMP_USERAGENT_BASE_STRING
#define AAMP_USERAGENT_BASE_STRING
Definition: AampDefine.h:101
ContentType_IPDVR
@ ContentType_IPDVR
Definition: AampProfiler.h:110
eMEDIATYPE_PLAYLIST_IFRAME
@ eMEDIATYPE_PLAYLIST_IFRAME
Definition: AampMediaType.h:54
PrivateInstanceAAMP::NotifyFirstBufferProcessed
void NotifyFirstBufferProcessed()
Notify if first buffer processed by gstreamer.
Definition: priv_aamp.cpp:8471
AAMP_EVENT_AD_PLACEMENT_END
@ AAMP_EVENT_AD_PLACEMENT_END
Definition: AampEvent.h:78
PrivateInstanceAAMP::InterruptableMsSleep
void InterruptableMsSleep(int timeInMs)
Sleep until timeout is reached or interrupted.
Definition: priv_aamp.cpp:6771
PrivateInstanceAAMP::hasId3Header
bool hasId3Header(const uint8_t *data, uint32_t length)
Check if segment starts with an ID3 section.
Definition: priv_aamp.cpp:11485
AudioTrackInfo
Structure for audio track information Holds information about an audio track in playlist.
Definition: main_aamp.h:178
eAAMPConfig_PlaybackOffset
@ eAAMPConfig_PlaybackOffset
Definition: AampConfig.h:287
AampLLDashServiceData::lowLatencyMode
bool lowLatencyMode
Definition: priv_aamp.h:512
PrivateInstanceAAMP::LogTuneComplete
void LogTuneComplete(void)
Notify tune end for profiling/logging.
Definition: priv_aamp.cpp:3045
PrivateInstanceAAMP::NotifyTextTracksChanged
void NotifyTextTracksChanged()
Function to notify available text tracks changed.
Definition: priv_aamp.cpp:10432
PROFILE_BUCKET_FRAGMENT_VIDEO
@ PROFILE_BUCKET_FRAGMENT_VIDEO
Definition: AampProfiler.h:57
PrivateInstanceAAMP::GetDefaultBitrate
long GetDefaultBitrate()
Get default bitrate value.
Definition: priv_aamp.cpp:6305
PrivateInstanceAAMP::ResetTrickStartUTCTime
void ResetTrickStartUTCTime()
Reset trick start position.
Definition: priv_aamp.cpp:8512
PrivateInstanceAAMP::TuneHelper
void TuneHelper(TuneType tuneType, bool seekWhilePaused=false)
The helper function which perform tuning Common tune operations used on Tune, Seek,...
Definition: priv_aamp.cpp:4874
PrivateInstanceAAMP::SendVTTCueDataAsEvent
void SendVTTCueDataAsEvent(VTTCue *cue)
To send webvtt cue as an event.
Definition: priv_aamp.cpp:9188
PrivateInstanceAAMP::SetPreferredLanguages
void SetPreferredLanguages(const char *languageList, const char *preferredRendition, const char *preferredType, const char *codecList, const char *labelList)
set preferred Audio Language properties like language, rendition, type and codec
Definition: priv_aamp.cpp:10744
PrivateInstanceAAMP::EndOfStreamReached
void EndOfStreamReached(MediaType mediaType)
End of stream reached.
Definition: priv_aamp.cpp:6416
AAMP_TUNE_MP4_INIT_FRAGMENT_MISSING
@ AAMP_TUNE_MP4_INIT_FRAGMENT_MISSING
Definition: AampEvent.h:146
PrivateInstanceAAMP::ResetEOSSignalledFlag
void ResetEOSSignalledFlag()
Reset EOS SignalledFlag.
Definition: priv_aamp.cpp:7797
PrivateInstanceAAMP::mbSeeked
bool mbSeeked
Definition: priv_aamp.h:1074
eMEDIATYPE_TELEMETRY_AVS
@ eMEDIATYPE_TELEMETRY_AVS
Definition: main_aamp.h:94
PROFILE_BUCKET_FRAGMENT_AUDIO
@ PROFILE_BUCKET_FRAGMENT_AUDIO
Definition: AampProfiler.h:58
PrivateInstanceAAMP::GetPeriodDurationTimeValue
double GetPeriodDurationTimeValue(void)
GetPeriodDurationTimeValue.
Definition: priv_aamp.cpp:11720
DEFAULT_DOWNLOAD_RETRY_COUNT
#define DEFAULT_DOWNLOAD_RETRY_COUNT
Definition: AampDefine.h:91
TuneType
TuneType
Tune Typea.
Definition: priv_aamp.h:190
PrivateInstanceAAMP::GetContentTypString
std::string GetContentTypString()
Set Content Type.
Definition: priv_aamp.cpp:6022
eMEDIATYPE_MANIFEST
@ eMEDIATYPE_MANIFEST
Definition: AampMediaType.h:43
PrivateInstanceAAMP::GetPlaybackStats
std::string GetPlaybackStats()
Get playback stats for the session so far.
Definition: priv_aamp.cpp:11744
AAMP_TUNE_LICENCE_TIMEOUT
@ AAMP_TUNE_LICENCE_TIMEOUT
Definition: AampEvent.h:126
PrivateInstanceAAMP::SetupPipeSession
bool SetupPipeSession()
Establish PIPE session with Receiver.
Definition: priv_aamp.cpp:4763
AAMP_TUNE_INIT_FRAGMENT_DOWNLOAD_FAILURE
@ AAMP_TUNE_INIT_FRAGMENT_DOWNLOAD_FAILURE
Definition: AampEvent.h:120
PrivateInstanceAAMP::SendAdReservationEvent
void SendAdReservationEvent(AAMPEventType type, const std::string &adBreakId, uint64_t position, bool immediate=false)
Send Ad reservation event.
Definition: priv_aamp.cpp:8932
AampJsonObject::get
bool get(const std::string &name, std::vector< std::string > &values)
Get a string value.
Definition: AampJsonObject.cpp:291
PrivateInstanceAAMP::SetStreamFormat
void SetStreamFormat(StreamOutputFormat videoFormat, StreamOutputFormat audioFormat, StreamOutputFormat auxFormat)
Set stream format for audio/video tracks.
Definition: priv_aamp.cpp:10505
StreamAbstractionAAMP_HLS
HLS Stream handler class.
Definition: fragmentcollector_hls.h:566
EventListener
Class for sed event to Listener.
Definition: AampEventListener.h:35
ProfileEventAAMP::GetClassicTuneTimeInfo
void GetClassicTuneTimeInfo(bool success, int tuneRetries, int firstTuneType, long long playerLoadTime, int streamType, bool isLive, unsigned int durationinSec, char *TuneTimeInfoStr)
Method converting the AAMP style tune performance data to IP_EX_TUNETIME style data.
Definition: AampProfiler.cpp:242
PrivateInstanceAAMP::GetCurrentLatency
long GetCurrentLatency()
Get Current Latency.
Definition: priv_aamp.cpp:11687
AAMP_TUNE_DRM_SELF_ABORT
@ AAMP_TUNE_DRM_SELF_ABORT
Definition: AampEvent.h:137
eAAMPSTATUS_TRACKS_SYNCHRONISATION_ERROR
@ eAAMPSTATUS_TRACKS_SYNCHRONISATION_ERROR
Definition: priv_aamp.h:218
eCURLINSTANCE_AUX_AUDIO
@ eCURLINSTANCE_AUX_AUDIO
Definition: priv_aamp.h:161
PrivateInstanceAAMP::GetPeriodScaledPtoStartTime
double GetPeriodScaledPtoStartTime(void)
GetPeriodScaledPtoStartTime.
Definition: priv_aamp.cpp:11736
PrivateInstanceAAMP::mCurrentVideoTrackId
int mCurrentVideoTrackId
Definition: priv_aamp.h:1029
PrivateInstanceAAMP::ReplaceKeyIDPsshData
unsigned char * ReplaceKeyIDPsshData(const unsigned char *InputData, const size_t InputDataLength, size_t &OutputDataLength)
Replace KeyID from PsshData.
Definition: priv_aamp.cpp:11422
StreamSink::NotifyFragmentCachingComplete
virtual void NotifyFragmentCachingComplete()
API to notify that fragment caching done.
Definition: main_aamp.h:612
PrivateInstanceAAMP::GetLowLatencyServiceConfigured
bool GetLowLatencyServiceConfigured()
Get Low Latency Service Configuration Status.
Definition: priv_aamp.cpp:11655
PrivateInstanceAAMP::PositionInfo::getPosition
TPOSITION getPosition() const
The stored position value, may be invalid, check using isPositionValid()
Definition: priv_aamp.h:871
eAAMPConfig_EnableVideoEndEvent
@ eAAMPConfig_EnableVideoEndEvent
Definition: AampConfig.h:129
AampCCManagerBase::SetParentalControlStatus
void SetParentalControlStatus(bool locked)
To enable/disable CC when parental control locked/unlocked.
Definition: AampCCManager.cpp:628
StreamSink::Stream
virtual void Stream(void)
Start the stream.
Definition: main_aamp.h:441
AAMP_EVENT_REPORT_ANOMALY
@ AAMP_EVENT_REPORT_ANOMALY
Definition: AampEvent.h:72
PrivateInstanceAAMP::mPauseOnFirstVideoFrameDisp
bool mPauseOnFirstVideoFrameDisp
Definition: priv_aamp.h:4057
StreamAbstractionAAMP::GetAudioTrack
virtual int GetAudioTrack()
Get current audio track.
Definition: streamabstraction.cpp:3017
Id3CallbackData::data
std::vector< uint8_t > data
Definition: priv_aamp.h:4119
AAMP_TUNE_DRM_CHALLENGE_FAILED
@ AAMP_TUNE_DRM_CHALLENGE_FAILED
Definition: AampEvent.h:125
FORMAT_INVALID
@ FORMAT_INVALID
Definition: main_aamp.h:108
StreamAbstractionAAMP::IsEOSReached
virtual bool IsEOSReached()
Checks if streamer reached end of stream.
Definition: streamabstraction.cpp:2597
AampFnLogger.h
AAMP Log unitility.
CurlProgressCbContext
context during curl progress callbacks
Definition: AampCurlStore.h:263
eAAMPConfig_MaxDASHDRMSessions
@ eAAMPConfig_MaxDASHDRMSessions
Definition: AampConfig.h:231
FORMAT_ISO_BMFF
@ FORMAT_ISO_BMFF
Definition: main_aamp.h:110
ContentType_UNKNOWN
@ ContentType_UNKNOWN
Definition: AampProfiler.h:101
AudioTrackInfo::label
std::string label
Definition: main_aamp.h:186
BUFFER_STATUS_RED
@ BUFFER_STATUS_RED
Definition: StreamAbstractionAAMP.h:142
AAMP_TUNE_FAILED_TO_GET_KEYID
@ AAMP_TUNE_FAILED_TO_GET_KEYID
Definition: AampEvent.h:131
PrivateInstanceAAMP::GetThumbnails
std::string GetThumbnails(double start, double end)
Get the Thumbnail Tile data.
Definition: priv_aamp.cpp:6505
PrivateInstanceAAMP::userProfileStatus
bool userProfileStatus
Definition: priv_aamp.h:1093
ContentType_EAS
@ ContentType_EAS
Definition: AampProfiler.h:106
PrivateInstanceAAMP::IsTuneCompleted
bool IsTuneCompleted()
Check if tune completed or not.
Definition: priv_aamp.cpp:8835
AampEventManager::SetPlayerState
void SetPlayerState(PrivAAMPState state)
SetPlayerState - Flag to update player state.
Definition: AampEventManager.cpp:264
PrivateInstanceAAMP::SetTrackDiscontinuityIgnoredStatus
void SetTrackDiscontinuityIgnoredStatus(MediaType track)
Set discontinuity ignored flag for given track.
Definition: priv_aamp.cpp:10480
AampCCManagerBase::Init
int Init(void *handle)
Initialize CC resource.
Definition: AampCCManager.cpp:578
PrivateInstanceAAMP::HandleSSLWriteCallback
size_t HandleSSLWriteCallback(char *ptr, size_t size, size_t nmemb, void *userdata)
HandleSSLWriteCallback - Handle write callback from CURL.
Definition: priv_aamp.cpp:770
StreamAbstractionAAMP::GetVideoBitrates
virtual std::vector< long > GetVideoBitrates(void)=0
Get available video bitrates.
StreamAbstractionAAMP::GetBWIndex
virtual int GetBWIndex(long bandwidth)=0
Get profile index of given bandwidth.
fragmentcollector_progressive.h
Streamer for progressive mp3/mp4 playback.
StreamSink::SetVideoMute
virtual void SetVideoMute(bool muted)
Set video mute state.
Definition: main_aamp.h:546
PrivateInstanceAAMP::GetCurrentAudioTrackId
int GetCurrentAudioTrackId(void)
Get the Current Audio Track Id Currently it is implimented for AC4 track selection only.
Definition: priv_aamp.cpp:2810
PROFILE_BUCKET_INIT_VIDEO
@ PROFILE_BUCKET_INIT_VIDEO
Definition: AampProfiler.h:52
AampCacheHandler::InsertToPlaylistCache
void InsertToPlaylistCache(const std::string url, const GrowableBuffer *buffer, std::string effectiveUrl, bool trackLiveStatus, MediaType fileType=eMEDIATYPE_DEFAULT)
Retrieve playlist from cache
Definition: AampCacheHandler.cpp:31
PrivateInstanceAAMP::mDiscoCompleteLock
pthread_mutex_t mDiscoCompleteLock
Definition: priv_aamp.h:1080
eHTTPHEADERTYPE_EFF_LOCATION
@ eHTTPHEADERTYPE_EFF_LOCATION
Definition: priv_aamp.h:232
PrivateInstanceAAMP::SetAudioVolume
void SetAudioVolume(int volume)
Set audio volume.
Definition: priv_aamp.cpp:6732
PROFILE_BUCKET_MANIFEST
@ PROFILE_BUCKET_MANIFEST
Definition: AampProfiler.h:45
AampCCManagerBase::GetTrack
const std::string & GetTrack()
Get current CC track.
Definition: AampCCManager.h:94
PrivateInstanceAAMP::SetVideoMute
void SetVideoMute(bool muted)
Enable/ Disable Video.
Definition: priv_aamp.cpp:6712
StreamAbstractionAAMP::IsStreamerStalled
bool IsStreamerStalled(void)
Check if playback stalled in fragment collector side.
Definition: StreamAbstractionAAMP.h:1031
eAAMPConfig_ForceHttp
@ eAAMPConfig_ForceHttp
Definition: AampConfig.h:120
BUFFER_STATUS_GREEN
@ BUFFER_STATUS_GREEN
Definition: StreamAbstractionAAMP.h:140
PrivateInstanceAAMP::CurlInit
void CurlInit(AampCurlInstance startIdx, unsigned int instanceCount=1, std::string proxyName="")
Curl initialization function.
Definition: priv_aamp.cpp:3252
AAMP_EVENT_AD_RESERVATION_END
@ AAMP_EVENT_AD_RESERVATION_END
Definition: AampEvent.h:76
MAX_SEG_DRM_DECRYPT_FAIL_COUNT
#define MAX_SEG_DRM_DECRYPT_FAIL_COUNT
Definition: AampDefine.h:99
gpGlobalConfig
AampConfig * gpGlobalConfig
Global configuration.
Definition: main_aamp.cpp:48
DumpBlob
void DumpBlob(const unsigned char *ptr, size_t len)
Compactly log blobs of binary data.
Definition: aamplogging.cpp:533
PrivateInstanceAAMP::Tune
void Tune(const char *url, bool autoPlay, const char *contentType=NULL, bool bFirstAttempt=true, bool bFinalAttempt=false, const char *sessionUUID=NULL, bool audioDecoderStreamSync=true)
Tune API.
Definition: priv_aamp.cpp:5349
AampJsonObject::isArray
bool isArray(const std::string &name)
Check whether the value is Array or not.
Definition: AampJsonObject.cpp:404
ANOMALY_TRACE
@ ANOMALY_TRACE
Definition: main_aamp.h:73
AampJsonObject::isObject
bool isObject(const std::string &name)
Check whether the value is Object or not.
Definition: AampJsonObject.cpp:446
PrivateInstanceAAMP::SetState
void SetState(PrivAAMPState state)
Set player state.
Definition: priv_aamp.cpp:7731
PrivateInstanceAAMP::mPlaybackMode
std::string mPlaybackMode
Definition: priv_aamp.h:4039
AAMPGstPlayer
Class declaration of Gstreamer based player.
Definition: aampgstplayer.h:64
PrivateInstanceAAMP::LogPlayerPreBuffered
void LogPlayerPreBuffered(void)
Profile Player changed from background to foreground i.e prebuffred.
Definition: priv_aamp.cpp:3115
eAAMPConfig_LicenseServerUrl
@ eAAMPConfig_LicenseServerUrl
Definition: AampConfig.h:297
GrowableBuffer::len
size_t len
Definition: AampMemoryUtils.h:42
eAAMPConfig_EnableCMCD
@ eAAMPConfig_EnableCMCD
Definition: AampConfig.h:203
PrivateInstanceAAMP::getAampCacheHandler
AampCacheHandler * getAampCacheHandler()
Get AampCacheHandler instance.
Definition: priv_aamp.cpp:6277
StreamAbstractionAAMP::SetTextStyle
virtual bool SetTextStyle(const std::string &options)
Set the text style of the subtitle to the options passed.
Definition: streamabstraction.cpp:3192
FORMAT_UNKNOWN
@ FORMAT_UNKNOWN
Definition: main_aamp.h:122
eAAMPConfig_ABRNWConsistency
@ eAAMPConfig_ABRNWConsistency
Definition: AampConfig.h:218
PrivateInstanceAAMP::SetCurrentLatency
void SetCurrentLatency(long currentLatency)
Set Current Latency.
Definition: priv_aamp.cpp:11695
AAMP_TUNE_UNTRACKED_DRM_ERROR
@ AAMP_TUNE_UNTRACKED_DRM_ERROR
Definition: AampEvent.h:121
gActivePrivAAMP_t
Used for storing active PrivateInstanceAAMPs.
Definition: priv_aamp.cpp:142
ContentType_VOD
@ ContentType_VOD
Definition: AampProfiler.h:103
Id3CallbackData::schemeIdUri
std::string schemeIdUri
Definition: priv_aamp.h:4121
PrivateInstanceAAMP::SetTextStyle
void SetTextStyle(const std::string &options)
Set style options for text track rendering.
Definition: priv_aamp.cpp:10441
AampCCManagerBase::SetStatus
int SetStatus(bool enable)
Enable/disable CC rendering.
Definition: AampCCManager.cpp:755
CurlStore::CurlTerm
void CurlTerm(void *privContext, AampCurlInstance startIdx, unsigned int instanceCount, const std::string &remotehost=std::string(""))
Definition: AampCurlStore.cpp:468
IARM_Bus_Call
IARM_Result_t IARM_Bus_Call(const char *ownerName, const char *methodName, void *arg, size_t argLen)
This API is used to Invoke RPC method by its application name and method name.
Definition: iarm_bus.c:57
eAAMPConfig_PreferredTextLanguage
@ eAAMPConfig_PreferredTextLanguage
Definition: AampConfig.h:317
PrivateInstanceAAMP::SetTunedManifestUrl
void SetTunedManifestUrl(bool isrecordedUrl=false)
Sets Recorded URL from Manifest received form XRE.
Definition: priv_aamp.cpp:9055
AampJsonObject::isString
bool isString(const std::string &name)
Check whether the value is String or not.
Definition: AampJsonObject.cpp:418
PrivateInstanceAAMP::mCurrentAudioTrackIndex
int mCurrentAudioTrackIndex
Definition: priv_aamp.h:1104
StreamAbstractionAAMP::RefreshSubtitles
void RefreshSubtitles()
Refresh subtitle track.
Definition: streamabstraction.cpp:3055
AampDRMSessionManager
Controller for managing DRM sessions.
Definition: AampDRMSessionManager.h:145
AampEventManager::SetFakeTuneFlag
void SetFakeTuneFlag(bool isFakeTuneSetting)
SetFakeTuneFlag - Some events are restricted for FakeTune.
Definition: AampEventManager.cpp:236
PrivateInstanceAAMP::mSeekFromPausedState
bool mSeekFromPausedState
Definition: priv_aamp.h:1061
AAMP_TUNE_FAILED_PTS_ERROR
@ AAMP_TUNE_FAILED_PTS_ERROR
Definition: AampEvent.h:145
PrivateInstanceAAMP::AcquireStreamLock
void AcquireStreamLock()
acquire streamsink lock
Definition: priv_aamp.cpp:10671
eSTATE_PAUSED
@ eSTATE_PAUSED
Definition: AampEvent.h:164
MAX_INIT_FRAGMENT_CACHE_PER_TRACK
#define MAX_INIT_FRAGMENT_CACHE_PER_TRACK
Definition: AampDefine.h:117
StreamSink::Stop
virtual void Stop(bool keepLastFrame)
Definition: main_aamp.h:449
eAAMPConfig_EnableCurlStore
@ eAAMPConfig_EnableCurlStore
Definition: AampConfig.h:200
eAAMPConfig_BulkTimedMetaReport
@ eAAMPConfig_BulkTimedMetaReport
Definition: AampConfig.h:168
manager.hpp
It contains class referenced by manager.cpp file.
PrivateInstanceAAMP::ProcessID3Metadata
void ProcessID3Metadata(char *segment, size_t size, MediaType type, uint64_t timestampOffset=0)
Process the ID3 metadata from segment.
Definition: priv_aamp.cpp:11501
StreamAbstractionAAMP::NotifyFirstVideoPTS
virtual void NotifyFirstVideoPTS(unsigned long long pts, unsigned long timeScale)
Receives first video PTS for the current playback.
Definition: StreamAbstractionAAMP.h:1056
StreamSink::SendTransfer
virtual bool SendTransfer(MediaType mediaType, void *ptr, size_t len, double fpts, double fdts, double fDuration, bool initFragment=false)=0
API to send audio/video buffer into the sink.
StreamAbstractionAAMP::GetFirstPTS
virtual double GetFirstPTS()=0
Get PTS of first sample.
ISCONFIGSET
#define ISCONFIGSET(x)
Definition: AampConfig.h:84
AuthTokenErrors
AuthTokenErrors
Auth Token Failure codes.
Definition: main_aamp.h:142
PausePositionMonitor
static void * PausePositionMonitor(void *arg)
call the PausePositionMonitoring thread loop
Definition: priv_aamp.cpp:1795
StreamAbstractionAAMP::mProgramStartTime
double mProgramStartTime
Definition: StreamAbstractionAAMP.h:931
eAAMPConfig_NativeCCRendering
@ eAAMPConfig_NativeCCRendering
Definition: AampConfig.h:170
StreamAbstractionAAMP::Start
virtual void Start()=0
Start streaming.
PrivateInstanceAAMP::RemoveEventListener
void RemoveEventListener(AAMPEventType eventType, EventListener *eventListener)
Deregister event lister, Remove listener to aamp events.
Definition: priv_aamp.cpp:2253
TuneEndMetrics::mFirstTune
bool mFirstTune
Definition: AampProfiler.h:132
CurlStore::CurlInit
void CurlInit(void *privContext, AampCurlInstance startIdx, unsigned int instanceCount, std::string proxyName, const std::string &remotehost=std::string(""))
Definition: AampCurlStore.cpp:393
aamp_GetSourceID
static guint aamp_GetSourceID()
Get the idle task's source ID.
Definition: priv_aamp.cpp:284
AampOutputProtection::GetDisplayResolution
void GetDisplayResolution(int &width, int &height)
gets display resolution
Definition: aampoutputprotection.cpp:261
AAMP_DEFAULT_SETTING
@ AAMP_DEFAULT_SETTING
Definition: AampDefine.h:210
ContentType_LINEAR
@ ContentType_LINEAR
Definition: AampProfiler.h:104
PrivateInstanceAAMP::mEventPriority
int mEventPriority
Definition: priv_aamp.h:4066
PrivateInstanceAAMP::GetNetworkTime
bool GetNetworkTime(enum UtcTiming timingtype, const std::string &remoteUrl, long *http_error, CurlRequest request)
Download a file from the server.
Definition: priv_aamp.cpp:3496
PrivateInstanceAAMP::SetPreferredTextLanguages
void SetPreferredTextLanguages(const char *param)
Set Preferred Text Language.
Definition: priv_aamp.cpp:11142
eMEDIAFORMAT_COMPOSITE
@ eMEDIAFORMAT_COMPOSITE
Definition: AampDrmMediaFormat.h:40
PrivateInstanceAAMP::mIsPeriodChangeMarked
bool mIsPeriodChangeMarked
Definition: priv_aamp.h:1082
eAAMPConfig_MaxABRNWBufferRampUp
@ eAAMPConfig_MaxABRNWBufferRampUp
Definition: AampConfig.h:240
PrivateInstanceAAMP::TrackDownloadsAreEnabled
bool TrackDownloadsAreEnabled(MediaType type)
Check to media track downloads are enabled.
Definition: priv_aamp.cpp:9921
ContentType_SLE
@ ContentType_SLE
Definition: AampProfiler.h:116
eAAMPConfig_AuthToken
@ eAAMPConfig_AuthToken
Definition: AampConfig.h:308
eAAMPConfig_ReportVideoPTS
@ eAAMPConfig_ReportVideoPTS
Definition: AampConfig.h:131
PrivateInstanceAAMP::UpdateVideoEndMetrics
void UpdateVideoEndMetrics(MediaType mediaType, long bitrate, int curlOrHTTPCode, std::string &strUrl, double curlDownloadTime, ManifestData *manifestData=NULL)
updates download metrics to VideoStat object, this is used for VideoFragment as it takes duration for...
Definition: priv_aamp.cpp:8180
PrivateInstanceAAMP::SendStreamTransfer
void SendStreamTransfer(MediaType mediaType, GrowableBuffer *buffer, double fpts, double fdts, double fDuration, bool initFragment=0)
API to send audio/video stream into the sink.
Definition: priv_aamp.cpp:7018
PrivateInstanceAAMP::GetPeriodStartTimeValue
double GetPeriodStartTimeValue(void)
GetPeriodStartTimeValue.
Definition: priv_aamp.cpp:11728
aamp_GetMediaTypeForTelemetry
static MediaTypeTelemetry aamp_GetMediaTypeForTelemetry(MediaType type)
Get the telemetry type for a media type.
Definition: priv_aamp.cpp:491
PrivateInstanceAAMP_Retune
static gboolean PrivateInstanceAAMP_Retune(gpointer ptr)
Tune again to currently viewing asset. Used for internal error handling.
Definition: priv_aamp.cpp:367
AampConfig::GetChannelOverride
const char * GetChannelOverride(const std::string chName)
GetChannelOverride - Gets channel override url for channel Name.
Definition: AampConfig.cpp:764
PrivateInstanceAAMP::preferredCodecString
std::string preferredCodecString
Definition: priv_aamp.h:971
PrivateInstanceAAMP::RunPausePositionMonitoring
void RunPausePositionMonitoring(void)
the PositionMonitoring thread used for PauseAt functionality
Definition: priv_aamp.cpp:1679
MediaStreamContext::CacheFragmentChunk
bool CacheFragmentChunk(MediaType actualType, char *ptr, size_t size, std::string remoteUrl, long long dnldStartTime)
Cache Fragment Chunk.
Definition: MediaStreamContext.cpp:309
Id3CallbackData
Holds id3 metadata callback specific variables.
Definition: priv_aamp.h:4095
StreamAbstractionAAMP::ResetSubtitle
virtual void ResetSubtitle()
reset subtitle parser created for sidecar support
Definition: StreamAbstractionAAMP.h:1347
eHTTPHEADERTYPE_XREASON
@ eHTTPHEADERTYPE_XREASON
Definition: priv_aamp.h:230
eAAMPConfig_MinABRNWBufferRampDown
@ eAAMPConfig_MinABRNWBufferRampDown
Definition: AampConfig.h:239
AampScheduler::SetState
void SetState(PrivAAMPState sstate)
To player state to Scheduler.
Definition: AampScheduler.cpp:254
PrivateInstanceAAMP::mManifestRefreshCount
unsigned int mManifestRefreshCount
Definition: priv_aamp.h:4061
PrivateInstanceAAMP::mFirstVideoFrameDisplayedEnabled
bool mFirstVideoFrameDisplayedEnabled
Definition: priv_aamp.h:4060
ReadConfigNumericHelper
static int ReadConfigNumericHelper(std::string buf, const char *prefixPtr, T &value)
helper function to extract numeric value from given buf after removing prefix
Definition: priv_aamp.cpp:696
eMEDIATYPE_AUX_AUDIO
@ eMEDIATYPE_AUX_AUDIO
Definition: AampMediaType.h:42
StreamAbstractionAAMP::GetAvailableThumbnailTracks
virtual std::vector< StreamInfo * > GetAvailableThumbnailTracks(void)=0
Get available thumbnail bitrates.
PrivateInstanceAAMP::GetDefaultBitrate4K
long GetDefaultBitrate4K()
Get Default bitrate for 4K.
Definition: priv_aamp.cpp:6315
eMEDIAFORMAT_DASH
@ eMEDIAFORMAT_DASH
Definition: AampDrmMediaFormat.h:35
DEFAULT_MINIMUM_INIT_CACHE_SECONDS
#define DEFAULT_MINIMUM_INIT_CACHE_SECONDS
Definition: AampDefine.h:96
AAMP_TUNE_UNSUPPORTED_STREAM_TYPE
@ AAMP_TUNE_UNSUPPORTED_STREAM_TYPE
Definition: AampEvent.h:129
httpRespHeaderData::data
std::string data
Definition: priv_aamp.h:467
AAMP_EVENT_SYNC_MODE
@ AAMP_EVENT_SYNC_MODE
Definition: AampEvent.h:100
eHTTPHEADERTYPE_UNKNOWN
@ eHTTPHEADERTYPE_UNKNOWN
Definition: priv_aamp.h:233
PrivateInstanceAAMP::curlDLTimeout
long curlDLTimeout[eCURLINSTANCE_MAX]
Definition: priv_aamp.h:1022
AudioTrackInfo::characteristics
std::string characteristics
Definition: main_aamp.h:185
AAMP_TUNE_FAILURE_UNKNOWN
@ AAMP_TUNE_FAILURE_UNKNOWN
Definition: AampEvent.h:147
eAAMPConfig_EnableSeekRange
@ eAAMPConfig_EnableSeekRange
Definition: AampConfig.h:159
PrivateInstanceAAMP::UpdateVideoEndProfileResolution
void UpdateVideoEndProfileResolution(MediaType mediaType, long bitrate, int width, int height)
updates profile Resolution to VideoStat object
Definition: priv_aamp.cpp:7911
PrivateInstanceAAMP::GetUtcTime
time_t GetUtcTime()
Get Utc Time.
Definition: priv_aamp.cpp:11671
PrivateInstanceAAMP::IsTSBSupported
bool IsTSBSupported()
Checking whether TSB enabled or not.
Definition: priv_aamp.h:1679
PrivateInstanceAAMP::GetMinimumBitrate
long GetMinimumBitrate()
Get minimum bitrate value.
Definition: priv_aamp.cpp:6295
httpRespHeaderData
To store Set Cookie: headers and X-Reason headers in HTTP Response.
Definition: priv_aamp.h:462
eAAMPSTATUS_GENERIC_ERROR
@ eAAMPSTATUS_GENERIC_ERROR
Definition: priv_aamp.h:209
admanager_mpd.h
Client side DAI manger for MPEG DASH.
PausedBehavior
PausedBehavior
Enumeration for Paused state behavior.
Definition: AampDefine.h:195
eTUNETYPE_LAST
@ eTUNETYPE_LAST
Definition: priv_aamp.h:197
StreamSink::SetVideoZoom
virtual void SetVideoZoom(VideoZoomMode zoom)
Set video zoom state.
Definition: main_aamp.h:538
PrivateInstanceAAMP::preferredCodecList
std::vector< std::string > preferredCodecList
Definition: priv_aamp.h:972
getHarvestConfigForMedia
int getHarvestConfigForMedia(MediaType fileType)
Get harvest config corresponds to Media type.
Definition: AampUtils.cpp:807
ePAUSED_BEHAVIOR_LIVE_DEFER
@ ePAUSED_BEHAVIOR_LIVE_DEFER
Definition: AampDefine.h:200
eAAMPConfig_ChangeTrackWithoutRetune
@ eAAMPConfig_ChangeTrackWithoutRetune
Definition: AampConfig.h:199
PrivateInstanceAAMP::UpdateRefreshPlaylistInterval
void UpdateRefreshPlaylistInterval(float maxIntervalSecs)
Update playlist refresh interval.
Definition: priv_aamp.cpp:2415
ReadConfigStringHelper
static int ReadConfigStringHelper(std::string buf, const char *prefixPtr, const char **valueCopyPtr)
helper function to avoid dependency on unsafe sscanf while reading strings
Definition: priv_aamp.cpp:667
AAMP_TUNE_DRM_INIT_FAILED
@ AAMP_TUNE_DRM_INIT_FAILED
Definition: AampEvent.h:122
PrivateInstanceAAMP::GetDurationMs
long long GetDurationMs(void)
Get asset duration in milliseconds.
Definition: priv_aamp.cpp:6798
PrivateInstanceAAMP::RemoveAsyncTask
bool RemoveAsyncTask(int taskId)
Remove async task scheduled earlier.
Definition: priv_aamp.cpp:10653
PrivateInstanceAAMP::mServiceZone
std::string mServiceZone
Definition: priv_aamp.h:4037
TuneEndMetrics::mTuneAttempts
int mTuneAttempts
Definition: AampProfiler.h:131
MediaStreamContext.h
Handles operations for Media stream context.
PrivateInstanceAAMP::IsFragmentCachingRequired
bool IsFragmentCachingRequired()
Check if fragment caching is required.
Definition: priv_aamp.cpp:8189
AAMP_TUNE_INVALID_DRM_KEY
@ AAMP_TUNE_INVALID_DRM_KEY
Definition: AampEvent.h:128
PrivateInstanceAAMP::mIsTrackIdMismatch
bool mIsTrackIdMismatch
Definition: priv_aamp.h:1030
PrivateInstanceAAMP::mPausedBehavior
PausedBehavior mPausedBehavior
Definition: priv_aamp.h:1059
PrivateInstanceAAMP::mAudioDecoderStreamSync
bool mAudioDecoderStreamSync
Definition: priv_aamp.h:1050
simulation_start
static long long simulation_start
Definition: priv_aamp.cpp:131
AampEventManager::AddEventListener
void AddEventListener(AAMPEventType eventType, EventListener *eventListener)
AddEventListener - Register listener for one eventtype.
Definition: AampEventManager.cpp:155
PrivateInstanceAAMP::SetTextTrack
void SetTextTrack(int trackId, char *data=NULL)
Set text track.
Definition: priv_aamp.cpp:10240
PrivateInstanceAAMP::mTimedMetadataStartTime
long long mTimedMetadataStartTime
Definition: priv_aamp.h:1090
PrivateInstanceAAMP::getStreamType
int getStreamType()
Get stream type.
Definition: priv_aamp.cpp:8520
eTUNETYPE_NEW_END
@ eTUNETYPE_NEW_END
Definition: priv_aamp.h:198
PrivateInstanceAAMP::preferredTextLanguagesList
std::vector< std::string > preferredTextLanguagesList
Definition: priv_aamp.h:974
eAAMPConfig_CurlStallTimeout
@ eAAMPConfig_CurlStallTimeout
Definition: AampConfig.h:272
PrivateInstanceAAMP::UpdateCullingState
void UpdateCullingState(double culledSeconds)
Update playlist culling.
Definition: priv_aamp.cpp:2104
PrivateInstanceAAMP::mStreamLock
pthread_mutex_t mStreamLock
Definition: priv_aamp.h:4067
TunedEventConfig
TunedEventConfig
Enumeration for TUNED Event Configuration.
Definition: AampDefine.h:184
PrivateInstanceAAMP::UpdatePreferredAudioList
void UpdatePreferredAudioList()
to update the preferredaudio codec, rendition and languages list
Definition: priv_aamp.cpp:6569
PrivateInstanceAAMP::ProcessCustomCurlRequest
bool ProcessCustomCurlRequest(std::string &remoteUrl, struct GrowableBuffer *buffer, long *http_error, CurlRequest request=eCURL_GET, std::string pData="")
Perform custom curl request.
Definition: priv_aamp.cpp:4559
PROFILE_BUCKET_PLAYLIST_AUDIO
@ PROFILE_BUCKET_PLAYLIST_AUDIO
Definition: AampProfiler.h:48
eAAMPConfig_MinBitrate
@ eAAMPConfig_MinBitrate
Definition: AampConfig.h:276
StreamAbstractionAAMP_MPD::getAccessibilityNode
static Accessibility getAccessibilityNode(void *adaptationSet)
Definition: fragmentcollector_mpd.cpp:6797
PrivateInstanceAAMP::HandleSSLHeaderCallback
size_t HandleSSLHeaderCallback(const char *ptr, size_t size, size_t nmemb, void *userdata)
HandleSSLHeaderCallback - Hanlde header callback from SSL.
Definition: priv_aamp.cpp:863
PrivateInstanceAAMP::UpdateSubtitleTimestamp
void UpdateSubtitleTimestamp()
Sets up the timestamp sync for subtitle renderer.
Definition: priv_aamp.cpp:8448
PrivateInstanceAAMP::preferredTypeString
std::string preferredTypeString
Definition: priv_aamp.h:970
PrivateInstanceAAMP::ScheduleRetune
void ScheduleRetune(PlaybackErrorType errorType, MediaType trackType)
Schedules retune or discontinuity processing based on state.
Definition: priv_aamp.cpp:7559
StreamAbstractionAAMP::GetVideoBitrate
long GetVideoBitrate(void)
Get the bitrate of current video profile selected.
Definition: streamabstraction.cpp:2419
PrivateInstanceAAMP::GetAvailableVideoTracks
std::string GetAvailableVideoTracks()
Get available video tracks.
Definition: priv_aamp.cpp:9482
PrivateInstanceAAMP::ReportTimedMetadata
void ReportTimedMetadata(bool init=false)
Report timed metadata Function to send timedMetadata.
Definition: priv_aamp.cpp:7235
eAAMPConfig_IFrameDefaultBitrate4K
@ eAAMPConfig_IFrameDefaultBitrate4K
Definition: AampConfig.h:271
PrivateInstanceAAMP::PrivateInstanceAAMP
PrivateInstanceAAMP(AampConfig *config=NULL)
PrivateInstanceAAMP Constructor.
Definition: priv_aamp.cpp:1278
PrivateInstanceAAMP::mTraceUUID
std::string mTraceUUID
Definition: priv_aamp.h:4042
AudioTrackInfo::mixType
std::string mixType
Definition: main_aamp.h:191
IsoBmffBuffer::getTimeScale
bool getTimeScale(uint32_t &timeScale)
Get TimeScale value of buffer.
Definition: isobmffbuffer.cpp:307
AAMP_TUNE_DRM_SESSIONID_EMPTY
@ AAMP_TUNE_DRM_SESSIONID_EMPTY
Definition: AampEvent.h:124
PrivateInstanceAAMP::preferredTextLanguagesString
std::string preferredTextLanguagesString
Definition: priv_aamp.h:973
IARM_Bus_RegisterEventHandler
IARM_Result_t IARM_Bus_RegisterEventHandler(const char *ownerName, IARM_EventId_t eventId, IARM_EventHandler_t handler)
This API register to listen to event and provide the callback function for event notification....
Definition: iarmMgrMocks.cpp:43
eAAMPConfig_NetworkTimeout
@ eAAMPConfig_NetworkTimeout
Definition: AampConfig.h:283
AAMPLOG
#define AAMPLOG(MYLOGOBJ, LEVEL, LEVELSTR, FORMAT,...)
Macro for validating the log level to be enabled.
Definition: AampLogManager.h:50
StreamAbstractionAAMP::IsInitialCachingSupported
virtual bool IsInitialCachingSupported()
Check if Initial Fragment Caching is supported.
Definition: streamabstraction.cpp:1777
PrivateInstanceAAMP::InitializeCC
void InitializeCC(void)
Initialize CC after first frame received Sends CC handle event to listeners when first frame receives...
Definition: priv_aamp.cpp:7460
PrivateInstanceAAMP::seiTimecode
std::string seiTimecode
Definition: priv_aamp.h:1127
eMEDIATYPE_DEFAULT
@ eMEDIATYPE_DEFAULT
Definition: AampMediaType.h:58
PrivateInstanceAAMP::StopDownloads
void StopDownloads()
Stop downloads of all tracks. Used by aamp internally to manage states.
Definition: priv_aamp.cpp:3148
PrivateInstanceAAMP::SetSubtitleMute
void SetSubtitleMute(bool muted)
Set subtitle mute state.
Definition: priv_aamp.cpp:6722
AampConfig
AAMP Config Class defn.
Definition: AampConfig.h:457
PrivateInstanceAAMP::preferredLabelList
std::vector< std::string > preferredLabelList
Definition: priv_aamp.h:969
StreamAbstractionAAMP::InitSubtitleParser
virtual void InitSubtitleParser(char *data)
Initilaize subtitle parser for sidecar support.
Definition: StreamAbstractionAAMP.h:1340
VideoZoomMode
VideoZoomMode
Video zoom mode.
Definition: main_aamp.h:129
PrivateInstanceAAMP::LockGetPositionMilliseconds
bool LockGetPositionMilliseconds()
Lock GetPositionMilliseconds() returns true if successfull.
Definition: priv_aamp.cpp:6861
PrivateInstanceAAMP::Discontinuity
bool Discontinuity(MediaType track, bool setDiscontinuityFlag=false)
Signal discontinuity of track. Called from StreamAbstractionAAMP to signal discontinuity.
Definition: priv_aamp.cpp:7534
AAMP_TUNE_AUTHORISATION_FAILURE
@ AAMP_TUNE_AUTHORISATION_FAILURE
Definition: AampEvent.h:118
AAMP_MAX_PIPE_DATA_SIZE
#define AAMP_MAX_PIPE_DATA_SIZE
Definition: AampConstants.h:35
aamp_Malloc
void * aamp_Malloc(size_t numBytes)
wrapper for g_malloc, used for segment allocation
Definition: AampMemoryUtils.cpp:68
eAAMPSTATUS_SEEK_RANGE_ERROR
@ eAAMPSTATUS_SEEK_RANGE_ERROR
Definition: priv_aamp.h:217
ProfileEventAAMP::ProfilePerformed
void ProfilePerformed(ProfilerBucketType type)
Method to mark the end of a bucket, for which beginning is not marked.
Definition: AampProfiler.cpp:354
PrivateInstanceAAMP::preferredTextRenditionString
std::string preferredTextRenditionString
Definition: priv_aamp.h:975
StreamAbstractionAAMP::StopInjection
virtual void StopInjection(void)=0
Stop injection of fragments.
PrivateInstanceAAMP::SendWatermarkSessionUpdateEvent
void SendWatermarkSessionUpdateEvent(uint32_t sessionHandle, uint32_t status, const std::string &system)
Generate WatermarkSessionUpdate event based on args passed.
Definition: priv_aamp.cpp:8826
eAAMPConfig_DemuxVideoHLSTrack
@ eAAMPConfig_DemuxVideoHLSTrack
Definition: AampConfig.h:102
AudioTrackInfo::channels
int channels
Definition: main_aamp.h:187
AudioTrackInfo::bandwidth
long bandwidth
Definition: main_aamp.h:188
PrivateInstanceAAMP::HasSidecarData
bool HasSidecarData()
check if sidecar data available
Definition: priv_aamp.cpp:12004
PROFILE_BUCKET_PLAYLIST_VIDEO
@ PROFILE_BUCKET_PLAYLIST_VIDEO
Definition: AampProfiler.h:47
PrivateInstanceAAMP::GetState
void GetState(PrivAAMPState &state)
Get player state.
Definition: priv_aamp.cpp:7769
StreamAbstractionAAMP::GetTextTrack
int GetTextTrack()
Get current text track.
Definition: streamabstraction.cpp:3036
PrivateInstanceAAMP::SetPreferredTextTrack
void SetPreferredTextTrack(const TextTrackInfo track)
Set preferred text track Required to persist across trickplay or other operations.
Definition: priv_aamp.h:3409
TimedMetadata
Class for Timed Metadata.
Definition: priv_aamp.h:382
eAAMPSTATUS_UNSUPPORTED_DRM_ERROR
@ eAAMPSTATUS_UNSUPPORTED_DRM_ERROR
Definition: priv_aamp.h:220
eAAMPConfig_DebugLogging
@ eAAMPConfig_DebugLogging
Definition: AampConfig.h:137
VideoScanType
VideoScanType
VideoScanType - Progressive/Interlaced.
Definition: AampEvent.h:190
PrivateInstanceAAMP::mFailureReason
std::string mFailureReason
Definition: priv_aamp.h:1089
StreamAbstractionAAMP::GetStartTimeOfFirstPTS
virtual double GetStartTimeOfFirstPTS()=0
Get Start time PTS of first sample.
print_headerResponse
static void print_headerResponse(std::vector< std::string > &allResponseHeadersForErrorLogging, MediaType fileType)
function to print header response during download failure and latency.
Definition: priv_aamp.cpp:844
PrivateInstanceAAMP::lastId3Data
uint8_t * lastId3Data[eMEDIATYPE_DEFAULT]
Definition: priv_aamp.h:1071
PrivateInstanceAAMP::IsEventListenerAvailable
bool IsEventListenerAvailable(AAMPEventType eventType)
IsEventListenerAvailable Check if Event is registered.
Definition: priv_aamp.cpp:2261
AAMP_EVENT_ENTERING_LIVE
@ AAMP_EVENT_ENTERING_LIVE
Definition: AampEvent.h:56
eAAMPConfig_ManifestTimeout
@ eAAMPConfig_ManifestTimeout
Definition: AampConfig.h:284
eAAMPConfig_URIParameter
@ eAAMPConfig_URIParameter
Definition: AampConfig.h:305
PrivateInstanceAAMP::ReportAdProgress
void ReportAdProgress(bool sync=true)
Report Ad progress event to listeners Sending Ad progress percentage to JSPP.
Definition: priv_aamp.cpp:2067
PrivateInstanceAAMP::mAdEventsQ
std::queue< AAMPEventPtr > mAdEventsQ
Definition: priv_aamp.h:809
PrivateInstanceAAMP::GetCurrentlyAvailableBandwidth
long GetCurrentlyAvailableBandwidth(void)
Get the current network bandwidth using most recently recorded 3 samples.
Definition: priv_aamp.cpp:3416
StreamSink::DumpStatus
virtual void DumpStatus(void)
Dump the sink status for debugging purpose.
Definition: main_aamp.h:456
PrivateInstanceAAMP::E_AAMP2Receiver_TUNETIME
@ E_AAMP2Receiver_TUNETIME
Definition: priv_aamp.h:645
PrivateInstanceAAMP::IsDiscontinuityProcessPending
bool IsDiscontinuityProcessPending()
Check if discontinuity processing is pending.
Definition: priv_aamp.cpp:2665
DEFAULT_CURL_TIMEOUT
#define DEFAULT_CURL_TIMEOUT
Definition: priv_aamp.h:72
eSTATE_PREPARED
@ eSTATE_PREPARED
Definition: AampEvent.h:162
eSTATE_PREPARING
@ eSTATE_PREPARING
Definition: AampEvent.h:161
eAAMPConfig_Disable4K
@ eAAMPConfig_Disable4K
Definition: AampConfig.h:181
aamp_AppendNulTerminator
void aamp_AppendNulTerminator(struct GrowableBuffer *buffer)
Append nul character to buffer.
Definition: AampMemoryUtils.cpp:156
PrivateInstanceAAMP::GetOnVideoEndSessionStatData
char * GetOnVideoEndSessionStatData()
Download VideoEnd Session statistics from fog.
Definition: priv_aamp.cpp:4509
PrivateInstanceAAMP::SendDrmErrorEvent
void SendDrmErrorEvent(DrmMetaDataEventPtr event, bool isRetryEnabled)
Handles DRM errors and sends events to application if required.
Definition: priv_aamp.cpp:2269
AampOutputProtection
Class to enforce HDCP authentication.
Definition: aampoutputprotection.h:119
PrivateInstanceAAMP::SaveNewTimedMetadata
void SaveNewTimedMetadata(long long timeMS, const char *szName, const char *szContent, int nb, const char *id="", double durationMS=-1)
SaveNewTimedMetadata Function to store Metadata and reporting event one by one after DRM Initializati...
Definition: priv_aamp.cpp:7226
eAAMPConfig_MetadataLogging
@ eAAMPConfig_MetadataLogging
Definition: AampConfig.h:145
CurlCbContextSyncTime
context during curl callbacks
Definition: priv_aamp.cpp:167
StreamAbstractionAAMP::StartInjection
virtual void StartInjection(void)=0
Start injection of fragments.
IARM_Bus_RemoveEventHandler
IARM_Result_t IARM_Bus_RemoveEventHandler(const char *ownerName, IARM_EventId_t eventId, IARM_EventHandler_t handler)
Remove specific handler registered for the given event.
Definition: iarmMgrMocks.cpp:50
MediaTrack
Base Class for Media Track.
Definition: StreamAbstractionAAMP.h:159
eMEDIATYPE_AUDIO
@ eMEDIATYPE_AUDIO
Definition: AampMediaType.h:40
PrivateInstanceAAMP::mPreCacheDnldTimeWindow
int mPreCacheDnldTimeWindow
Definition: priv_aamp.h:840
StreamAbstractionAAMP_OTA
Fragment collector for OTA.
Definition: ota_shim.h:52
AudioTrackInfo::codec
std::string codec
Definition: main_aamp.h:184
eSTATE_ERROR
@ eSTATE_ERROR
Definition: AampEvent.h:170
PrivateInstanceAAMP::DurationFromStartOfPlaybackMs
long long DurationFromStartOfPlaybackMs(void)
Get asset duration in milliseconds For VIDEO TAG Based playback, mainly when aamp is used as plugin.
Definition: priv_aamp.cpp:6817
aamp_DecodeUrlParameter
void aamp_DecodeUrlParameter(std::string &uriParam)
unescape uri-encoded uri parameter
Definition: AampUtils.cpp:366
PrivateInstanceAAMP::GetLiveOffsetAppRequest
bool GetLiveOffsetAppRequest()
Definition: priv_aamp.cpp:11640
eTRACK_SUBTITLE
@ eTRACK_SUBTITLE
Definition: StreamAbstractionAAMP.h:52
StreamAbstractionAAMP::GetStreamFormat
virtual void GetStreamFormat(StreamOutputFormat &primaryOutputFormat, StreamOutputFormat &audioOutputFormat, StreamOutputFormat &auxAudioOutputFormat, StreamOutputFormat &subtitleOutputFormat)=0
Get output format of stream.
ProfileEventAAMP::ProfileError
void ProfileError(ProfilerBucketType type, int result=-1)
Marking error while executing a bucket.
Definition: AampProfiler.cpp:311
AampLLDashServiceData
To store Low Latency Service configurtions.
Definition: priv_aamp.h:511
eMEDIATYPE_PLAYLIST_AUX_AUDIO
@ eMEDIATYPE_PLAYLIST_AUX_AUDIO
Definition: AampMediaType.h:53
ContentType_OTA
@ ContentType_OTA
Definition: AampProfiler.h:113
ContentType_CAMERA
@ ContentType_CAMERA
Definition: AampProfiler.h:107
PrivateInstanceAAMP::mNextPeriodDuration
double mNextPeriodDuration
Definition: priv_aamp.h:1076
PrivateInstanceAAMP::WebVTTCueListenersRegistered
bool WebVTTCueListenersRegistered(void)
To check if JavaScript cue listeners are registered.
Definition: priv_aamp.cpp:9211
PrivateInstanceAAMP::GetTunedManifestUrl
const char * GetTunedManifestUrl()
Gets Recorded URL from Manifest received form XRE.
Definition: priv_aamp.cpp:9070
eAAMPConfig_NetworkProxy
@ eAAMPConfig_NetworkProxy
Definition: AampConfig.h:306
eCURLINSTANCE_PLAYLISTPRECACHE
@ eCURLINSTANCE_PLAYLISTPRECACHE
Definition: priv_aamp.h:165
eAAMPConfig_ABRCacheLength
@ eAAMPConfig_ABRCacheLength
Definition: AampConfig.h:214
PrivateInstanceAAMP::individualization
void individualization(const std::string &payload)
DRM individualization callback.
Definition: priv_aamp.cpp:9807
AAMP_EVENT_STATE_CHANGED
@ AAMP_EVENT_STATE_CHANGED
Definition: AampEvent.h:60
PrivateInstanceAAMP::SetVidTimeScale
void SetVidTimeScale(uint32_t vidTimeScale)
Sets Low Video TimeScale.
Definition: priv_aamp.cpp:11596
PrivateInstanceAAMP::mMinInitialCacheSeconds
int mMinInitialCacheSeconds
Definition: priv_aamp.h:4053
eAAMPConfig_PreferredTextRendition
@ eAAMPConfig_PreferredTextRendition
Definition: AampConfig.h:316
PrivateInstanceAAMP::GetThumbnailTracks
std::string GetThumbnailTracks()
Get available thumbnail tracks.
Definition: priv_aamp.cpp:6461
eHTTPHEADERTYPE_COOKIE
@ eHTTPHEADERTYPE_COOKIE
Definition: priv_aamp.h:229
TuneEndMetrics::mTSBEnabled
bool mTSBEnabled
Definition: AampProfiler.h:133
PrivateInstanceAAMP::GetMediaFormatTypeEnum
MediaFormat GetMediaFormatTypeEnum() const
Get Mediaformat type.
Definition: priv_aamp.cpp:8557
StreamAbstractionAAMP::ChangeMuxedAudioTrackIndex
virtual void ChangeMuxedAudioTrackIndex(std::string &index)
Change muxed audio track index.
Definition: StreamAbstractionAAMP.h:1330
PrivateInstanceAAMP::LogDrmDecryptEnd
void LogDrmDecryptEnd(ProfilerBucketType bucketType)
Notifies profiler that decryption has ended.
Definition: priv_aamp.cpp:3139
StreamAbstractionAAMP::PauseSubtitleParser
virtual void PauseSubtitleParser(bool pause)
Pause/unpause subtitles.
Definition: StreamAbstractionAAMP.h:1070
PrivateInstanceAAMP::mNextPeriodStartTime
double mNextPeriodStartTime
Definition: priv_aamp.h:1077
PrivateInstanceAAMP::GetInitialBufferDuration
int GetInitialBufferDuration()
Get current initial buffer duration in seconds.
Definition: priv_aamp.cpp:9816
eTUNETYPE_RETUNE
@ eTUNETYPE_RETUNE
Definition: priv_aamp.h:196
StreamSink::SetSubtitleMute
virtual void SetSubtitleMute(bool muted)
Set subtitle mute state.
Definition: main_aamp.h:554
eAAMPConfig_PlaylistParallelFetch
@ eAAMPConfig_PlaylistParallelFetch
Definition: AampConfig.h:166
PrivateInstanceAAMP::mPipelineIsClear
bool mPipelineIsClear
Definition: priv_aamp.h:1034
eAAMPConfig_LimitResolution
@ eAAMPConfig_LimitResolution
Definition: AampConfig.h:175
AampCCManagerBase::SetStyle
int SetStyle(const std::string &options)
Set CC styles for rendering.
Definition: AampCCManager.cpp:400
eAAMPConfig_EnableGstPositionQuery
@ eAAMPConfig_EnableGstPositionQuery
Definition: AampConfig.h:150
PrivateInstanceAAMP::mCMCDBandwidth
long mCMCDBandwidth
Definition: priv_aamp.h:848
PrivateInstanceAAMP::NotifyAudioTracksChanged
void NotifyAudioTracksChanged()
Function to notify available audio tracks changed.
Definition: priv_aamp.cpp:10424
PrivateInstanceAAMP::mOrigManifestUrl
AampURLInfoStruct mOrigManifestUrl
Definition: priv_aamp.h:836
eMEDIATYPE_INIT_AUDIO
@ eMEDIATYPE_INIT_AUDIO
Definition: AampMediaType.h:47
eMEDIATYPE_PLAYLIST_VIDEO
@ eMEDIATYPE_PLAYLIST_VIDEO
Definition: AampMediaType.h:50
PrivateInstanceAAMP_Resume
static gboolean PrivateInstanceAAMP_Resume(gpointer ptr)
Idle task to resume aamp.
Definition: priv_aamp.cpp:300
eGST_ERROR_PTS
@ eGST_ERROR_PTS
Definition: priv_aamp.h:174
PrivateInstanceAAMP::TuneFail
void TuneFail(bool fail)
Profiler for failure tune.
Definition: priv_aamp.cpp:3018
MediaTrack::GetBufferStatus
BufferHealthStatus GetBufferStatus()
Get buffer Status of track.
Definition: streamabstraction.cpp:83
PrivateInstanceAAMP::GetPositionMilliseconds
long long GetPositionMilliseconds(void)
Get current stream playback position in milliseconds.
Definition: priv_aamp.cpp:6888
PrivateInstanceAAMP::SendMediaMetadataEvent
void SendMediaMetadataEvent(void)
Generate media metadata event based on parsed attribute values.
Definition: priv_aamp.cpp:8688
eAAMPConfig_DRMDecryptThreshold
@ eAAMPConfig_DRMDecryptThreshold
Definition: AampConfig.h:236
PrivateInstanceAAMP::GetSeekBase
double GetSeekBase(void)
Get seek base position.
Definition: priv_aamp.cpp:6445
PrivateInstanceAAMP::SaveTimedMetadata
void SaveTimedMetadata(long long timeMS, const char *szName, const char *szContent, int nb, const char *id="", double durationMS=-1)
SaveTimedMetadata Function to store Metadata for bulk reporting during Initialization.
Definition: priv_aamp.cpp:7217
AAMPNetworkErrorHttp
@ AAMPNetworkErrorHttp
Definition: AampLogManager.h:112
eAAMPConfig_DisableLowLatencyABR
@ eAAMPConfig_DisableLowLatencyABR
Definition: AampConfig.h:185
TrackType
TrackType
Media Track Types.
Definition: StreamAbstractionAAMP.h:48
MediaTrack::enabled
bool enabled
Definition: StreamAbstractionAAMP.h:515
AAMP_TUNE_INIT_FAILED_MANIFEST_DNLD_ERROR
@ AAMP_TUNE_INIT_FAILED_MANIFEST_DNLD_ERROR
Definition: AampEvent.h:111
PrivateInstanceAAMP::mIsWVKIDWorkaround
bool mIsWVKIDWorkaround
Definition: priv_aamp.h:839
PrivateInstanceAAMP::IsDiscontinuityIgnoredForOtherTrack
bool IsDiscontinuityIgnoredForOtherTrack(MediaType track)
Check whether the given track discontinuity ignored earlier.
Definition: priv_aamp.cpp:10488
ConvertSpeedToStr
char * ConvertSpeedToStr(long bps, char *str)
Convert to string and add suffix k, M, G.
Definition: priv_aamp.cpp:1020
aamp_WriteFile
bool aamp_WriteFile(std::string fileName, const char *data, size_t len, MediaType &fileType, unsigned int count, const char *prefix)
Write - file to storage.
Definition: AampUtils.cpp:882
eAAMPConfig_CustomLicenseData
@ eAAMPConfig_CustomLicenseData
Definition: AampConfig.h:320
AAMP_TUNE_INVALID_MANIFEST_FAILURE
@ AAMP_TUNE_INVALID_MANIFEST_FAILURE
Definition: AampEvent.h:144
PrivateInstanceAAMP::GetNetworkProxy
std::string GetNetworkProxy()
To get the network proxy.
Definition: priv_aamp.cpp:9079
PrivateInstanceAAMP::ReleaseStreamLock
void ReleaseStreamLock()
release streamsink lock
Definition: priv_aamp.cpp:10689
PrivateInstanceAAMP::mHarvestCountLimit
int mHarvestCountLimit
Definition: priv_aamp.h:4068
eGST_ERROR_UNDERFLOW
@ eGST_ERROR_UNDERFLOW
Definition: priv_aamp.h:175
PrivateInstanceAAMP::RefreshSubtitles
void RefreshSubtitles()
Switch the subtitle track following a change to the preferredTextTrack.
Definition: priv_aamp.cpp:10351
AAMP_TUNE_FRAGMENT_DOWNLOAD_FAILURE
@ AAMP_TUNE_FRAGMENT_DOWNLOAD_FAILURE
Definition: AampEvent.h:119
AAMP_EVENT_AD_PLACEMENT_PROGRESS
@ AAMP_EVENT_AD_PLACEMENT_PROGRESS
Definition: AampEvent.h:80
eAAMPConfig_ABRThresholdSize
@ eAAMPConfig_ABRThresholdSize
Definition: AampConfig.h:219
ContentType_CDVR
@ ContentType_CDVR
Definition: AampProfiler.h:102
CurlCallbackContext
context during curl callbacks
Definition: AampCurlStore.h:232
StreamSink::GetDurationMilliseconds
virtual long GetDurationMilliseconds(void)
Get playback duration in milliseconds.
Definition: main_aamp.h:498
eTRACK_AUDIO
@ eTRACK_AUDIO
Definition: StreamAbstractionAAMP.h:51
StreamAbstractionAAMP::GetBufferedDuration
virtual double GetBufferedDuration(void)=0
Function to get the buffer duration of stream.
MediaType
MediaType
Media types.
Definition: AampMediaType.h:37
PrivateInstanceAAMP::ReportBulkTimedMetadata
void ReportBulkTimedMetadata()
Report bulk timedMetadata Function to send bulk timedMetadata in json format.
Definition: priv_aamp.cpp:7258
aamp_IsLocalHost
bool aamp_IsLocalHost(std::string Hostname)
check is local or not from given hostname
Definition: AampUtils.cpp:267
PrivateInstanceAAMP::PositionCache::Update
void Update(TPOSITIONCACHE Pos, double SeekPosSeconds)
Update the stored position information.
Definition: priv_aamp.h:925
AAMPEventMode
AAMPEventMode
AAMP event modes.
Definition: AampEvent.h:97
eAAMPConfig_MapMPD
@ eAAMPConfig_MapMPD
Definition: AampConfig.h:294
IsoBmffBuffer
Class for ISO BMFF Buffer.
Definition: isobmffbuffer.h:39
eAAMPConfig_DisableEC3
@ eAAMPConfig_DisableEC3
Definition: AampConfig.h:107
DeFog
static void DeFog(std::string &url)
de-fog playback URL to play directly from CDN instead of fog
Definition: priv_aamp.cpp:532
AsyncTaskObj
Async task operations.
Definition: AampScheduler.h:57
PrivateInstanceAAMP::NotifyFirstFrameReceived
void NotifyFirstFrameReceived(void)
Notify first frame is displayed. Sends CC handle event to listeners.
Definition: priv_aamp.cpp:7499
PrivateInstanceAAMP::preferredRenditionList
std::vector< std::string > preferredRenditionList
Definition: priv_aamp.h:967
PrivateInstanceAAMP::SendSupportedSpeedsChangedEvent
void SendSupportedSpeedsChangedEvent(bool isIframeTrackPresent)
Generate supported speeds changed event based on arg passed.
Definition: priv_aamp.cpp:8767
IsoBmffBuffer::setBuffer
void setBuffer(uint8_t *buf, size_t sz)
Set buffer.
Definition: isobmffbuffer.cpp:47
aamp_GetTimespec
struct timespec aamp_GetTimespec(int timeInMs)
To get the timespec.
Definition: AampUtils.cpp:741
StreamAbstractionAAMP_PROGRESSIVE
Streamer for progressive mp3/mp4 playback.
Definition: fragmentcollector_progressive.h:37
StreamSink::getCCDecoderHandle
virtual unsigned long getCCDecoderHandle(void)
Get closed caption handle.
Definition: main_aamp.h:519
PrivateInstanceAAMP::preferredTextAccessibilityNode
Accessibility preferredTextAccessibilityNode
Definition: priv_aamp.h:979
PrivateInstanceAAMP::NotifySinkBufferFull
void NotifySinkBufferFull(MediaType type)
Notify about sink buffer full.
Definition: priv_aamp.cpp:6105
PROFILE_BUCKET_INIT_SUBTITLE
@ PROFILE_BUCKET_INIT_SUBTITLE
Definition: AampProfiler.h:54
PrivateInstanceAAMP::mSupportedTLSVersion
long mSupportedTLSVersion
Definition: priv_aamp.h:1088
eSTATE_INITIALIZING
@ eSTATE_INITIALIZING
Definition: AampEvent.h:159
BitrateChangeReason
BitrateChangeReason
Different reasons for bitrate change.
Definition: priv_aamp.h:251
AampJsonObject.h
File to handle Json format.
AampEventManager
Class to Handle Aamp Events.
Definition: AampEventManager.h:55
AAMP_EVENT_AUDIO_TRACKS_CHANGED
@ AAMP_EVENT_AUDIO_TRACKS_CHANGED
Definition: AampEvent.h:66
PROFILE_BUCKET_INIT_AUXILIARY
@ PROFILE_BUCKET_INIT_AUXILIARY
Definition: AampProfiler.h:55
AudioTrackInfo::rendition
std::string rendition
Definition: main_aamp.h:182
AudioTrackInfo::language
std::string language
Definition: main_aamp.h:181
eAAMPConfig_LiveOffset
@ eAAMPConfig_LiveOffset
Definition: AampConfig.h:288
PrivateInstanceAAMP::SendEvent
void SendEvent(AAMPEventPtr eventData, AAMPEventMode eventMode=AAMP_EVENT_DEFAULT_MODE)
Send event to listeners.
Definition: priv_aamp.cpp:2530
StreamSink::Discontinuity
virtual bool Discontinuity(MediaType mediaType)=0
Process PTS discontinuity for a stream type.
PrivateInstanceAAMP::GetAvailableAudioTracks
std::string GetAvailableAudioTracks(bool allTrack=false)
Get available audio tracks.
Definition: priv_aamp.cpp:9572
eAAMPConfig_CKLicenseServerUrl
@ eAAMPConfig_CKLicenseServerUrl
Definition: AampConfig.h:298
PrivateInstanceAAMP::preferredAudioAccessibilityNode
Accessibility preferredAudioAccessibilityNode
Definition: priv_aamp.h:980
AAMP_DEFAULT_PLAYBACK_OFFSET
#define AAMP_DEFAULT_PLAYBACK_OFFSET
Definition: AampDefine.h:81
eAAMPConfig_PreferredAudioType
@ eAAMPConfig_PreferredAudioType
Definition: AampConfig.h:315
PrivateInstanceAAMP::mTsbRecordingId
std::string mTsbRecordingId
Definition: priv_aamp.h:1056
TuneFailureMap::code
int code
Definition: main_aamp.h:83
eAAMPConfig_LanguageCodePreference
@ eAAMPConfig_LanguageCodePreference
Definition: AampConfig.h:233
PrivateInstanceAAMP::StopTrackDownloads
void StopTrackDownloads(MediaType type)
Stop downloads for a track. Called from StreamSink to control flow.
Definition: priv_aamp.cpp:3179
StreamAbstractionAAMP::ResetESChangeStatus
void ResetESChangeStatus(void)
Reset elementary stream type change status once the pipeline reconfigured.
Definition: StreamAbstractionAAMP.h:713
StreamSink::SendCopy
virtual bool SendCopy(MediaType mediaType, const void *ptr, size_t len, double fpts, double fdts, double fDuration)=0
API to send audio/video buffer into the sink.
libIBus.h
RDK IARM-Bus API Declarations.
SpeedCache
Stroes the information for cache speed.
Definition: priv_aamp.h:489
DestroyTask
void(* DestroyTask)(void *arg)
Function pointer for the destroy task.
Definition: priv_aamp.h:457
eTRACK_AUX_AUDIO
@ eTRACK_AUX_AUDIO
Definition: StreamAbstractionAAMP.h:53
eAAMPConfig_UseWesterosSink
@ eAAMPConfig_UseWesterosSink
Definition: AampConfig.h:153
PROFILE_BUCKET_FRAGMENT_SUBTITLE
@ PROFILE_BUCKET_FRAGMENT_SUBTITLE
Definition: AampProfiler.h:59
PrivateInstanceAAMP::PositionCache::GetInfo
PositionInfo< TPOSITIONCACHE > GetInfo()
Retrieve the stored position information.
Definition: priv_aamp.h:934
PrivateInstanceAAMP::ReportContentGap
void ReportContentGap(long long timeMS, std::string id, double durationMS=-1)
Report content gap events.
Definition: priv_aamp.cpp:7383
eMEDIATYPE_INIT_SUBTITLE
@ eMEDIATYPE_INIT_SUBTITLE
Definition: AampMediaType.h:48
eMEDIATYPE_INIT_AUX_AUDIO
@ eMEDIATYPE_INIT_AUX_AUDIO
Definition: AampMediaType.h:49
AAMP_TUNE_DRM_DECRYPT_FAILED
@ AAMP_TUNE_DRM_DECRYPT_FAILED
Definition: AampEvent.h:135
StreamAbstractionAAMP::GetProfileCount
virtual int GetProfileCount()
Get number of profiles/ representations from subclass.
Definition: StreamAbstractionAAMP.h:964
AAMP_EVENT_TEXT_TRACKS_CHANGED
@ AAMP_EVENT_TEXT_TRACKS_CHANGED
Definition: AampEvent.h:67
PrivateInstanceAAMP::DisableContentRestrictions
void DisableContentRestrictions(long grace=0, long time=-1, bool eventChange=false)
Disable Content Restrictions - unlock.
Definition: priv_aamp.cpp:10599
PrivateInstanceAAMP::GetPreferredDRM
DRMSystems GetPreferredDRM()
Get Preferred DRM.
Definition: priv_aamp.cpp:8843
AAMP_TRACK_COUNT
#define AAMP_TRACK_COUNT
Definition: priv_aamp.h:67
PrivateInstanceAAMP::mAutoResumeTaskId
guint mAutoResumeTaskId
Definition: priv_aamp.h:4063
PrivateInstanceAAMP::SyncBegin
void SyncBegin(void)
GStreamer operation start.
Definition: priv_aamp.cpp:1893
eAAMPConfig_XRESupportedTune
@ eAAMPConfig_XRESupportedTune
Definition: AampConfig.h:193
GrowableBuffer::ptr
char * ptr
Definition: AampMemoryUtils.h:41
PrivateInstanceAAMP::WaitForDiscontinuityProcessToComplete
void WaitForDiscontinuityProcessToComplete(void)
wait for Discontinuity handling complete
Definition: priv_aamp.cpp:1871
PrivateInstanceAAMP::GetTextStyle
std::string GetTextStyle()
Get style options for text track rendering.
Definition: priv_aamp.cpp:10464
aampgstplayer.h
Gstreamer based player for AAMP.
AampScheduler::RemoveTask
bool RemoveTask(int id)
To remove a scheduled tasks with ID.
Definition: AampScheduler.cpp:218
StreamSink::SetVideoRectangle
virtual void SetVideoRectangle(int x, int y, int w, int h)
Set video display rectangle co-ordinates.
Definition: main_aamp.h:530
AampLogManager::isLogLevelAllowed
bool isLogLevelAllowed(AAMP_LogLevel chkLevel)
To check the given log level is allowed to print mechanism.
Definition: aamplogging.cpp:50
eAAMPConfig_DisableAC3
@ eAAMPConfig_DisableAC3
Definition: AampConfig.h:112
PrivateInstanceAAMP::PositionCache::Invalidate
void Invalidate()
Explicitly set the cache to an invalid state.
Definition: priv_aamp.h:943
AAMP_TUNE_FAILED_TO_GET_ACCESS_TOKEN
@ AAMP_TUNE_FAILED_TO_GET_ACCESS_TOKEN
Definition: AampEvent.h:132
StreamSink::NotifyFragmentCachingOngoing
virtual void NotifyFragmentCachingOngoing()
API to notify that fragment caching is ongoing.
Definition: main_aamp.h:619
PrivateInstanceAAMP::mhAbrManager
HybridABRManager mhAbrManager
Definition: priv_aamp.h:820
eAAMPSTATUS_OK
@ eAAMPSTATUS_OK
Definition: priv_aamp.h:207
TrackTypeString
static std::string TrackTypeString(const int track)
track description string from TrackType enum
Definition: priv_aamp.cpp:2922
eCurlHostMap
To have hostname mapped curl handles.
Definition: priv_aamp.h:598
AAMP_TUNE_DRM_DATA_BIND_FAILED
@ AAMP_TUNE_DRM_DATA_BIND_FAILED
Definition: AampEvent.h:123
AAMP_TUNE_INIT_FAILED_TRACK_SYNC_ERROR
@ AAMP_TUNE_INIT_FAILED_TRACK_SYNC_ERROR
Definition: AampEvent.h:116
PrivateInstanceAAMP::DiscontinuitySeenInAnyTracks
bool DiscontinuitySeenInAnyTracks()
Check if discontinuity processed in any track.
Definition: priv_aamp.cpp:10720
PrivateInstanceAAMP::GetMediaStreamContext
class MediaStreamContext * GetMediaStreamContext(MediaType type)
Get Media Stream Context.
Definition: priv_aamp.cpp:11703
PrivateInstanceAAMP::SetStreamSink
void SetStreamSink(StreamSink *streamSink)
Setting the stream sink.
Definition: priv_aamp.cpp:7034
PrivateInstanceAAMP::CheckForDiscontinuityStall
void CheckForDiscontinuityStall(MediaType mediaType)
Check if AAMP is in stalled state after it pushed EOS to notify discontinuity.
Definition: priv_aamp.cpp:5961
PrivateInstanceAAMP_PausePosition
static gboolean PrivateInstanceAAMP_PausePosition(gpointer ptr)
perform pause of the pipeline and notifications for PauseAt functionality
Definition: priv_aamp.cpp:1615
ContentType_DVR
@ ContentType_DVR
Definition: AampProfiler.h:108
PrivateInstanceAAMP::StopPausePositionMonitoring
void StopPausePositionMonitoring(std::string reason)
stop the PausePositionMonitoring thread used for PauseAt functionality
Definition: priv_aamp.cpp:1839
PrivateInstanceAAMP::mApplyVideoRect
bool mApplyVideoRect
Definition: priv_aamp.h:4084
eMEDIATYPE_TELEMETRY_DRM
@ eMEDIATYPE_TELEMETRY_DRM
Definition: main_aamp.h:95
PrivateInstanceAAMP::preferredLanguagesList
std::vector< std::string > preferredLanguagesList
Definition: priv_aamp.h:965
StreamSink::Pause
virtual bool Pause(bool pause, bool forceStopGstreamerPreBuffering)
Enabled or disable playback pause.
Definition: main_aamp.h:491
AampEventManager::IsSpecificEventListenerAvailable
bool IsSpecificEventListenerAvailable(AAMPEventType eventType)
IsSpecificEventListenerAvailable - Check if this particular listener present for this event.
Definition: AampEventManager.cpp:206
_base64.h
base64 source Encoder/Decoder
PrivateInstanceAAMP::Stop
void Stop(void)
Stop playback and release resources.
Definition: priv_aamp.cpp:7068
PrivateInstanceAAMP::SendHTTPHeaderResponse
void SendHTTPHeaderResponse()
Generate http header response event.
Definition: priv_aamp.cpp:8675
PrivateInstanceAAMP::IsLiveStream
bool IsLiveStream(void)
Check if stream is live.
Definition: priv_aamp.cpp:7059
PrivateInstanceAAMP::mDisplayWidth
int mDisplayWidth
Definition: priv_aamp.h:1062
PrivateInstanceAAMP::GetLLDashSpeedCache
struct SpeedCache * GetLLDashSpeedCache()
Gets Speed Cache.
Definition: priv_aamp.cpp:11635
IdleTask
int(* IdleTask)(void *arg)
Function pointer for the idle task.
Definition: priv_aamp.h:449
PrivateInstanceAAMP::mVideoOnlyPb
bool mVideoOnlyPb
Definition: priv_aamp.h:1103
getPseudoTrickplayRate
float getPseudoTrickplayRate(float rate)
Get reverse map the working rates to the rates given by platform player.
Definition: AampUtils.cpp:975
PrivateInstanceAAMP::GetTextTrackInfo
std::string GetTextTrackInfo()
Get current audio track index.
Definition: priv_aamp.cpp:10095
getCurrentContentDownloadSpeed
long getCurrentContentDownloadSpeed(PrivateInstanceAAMP *aamp, MediaType fileType, bool bDownloadStart, long start, double dlnow)
Get Current Content Download Speed.
Definition: priv_aamp.cpp:1050
PROFILE_BUCKET_FIRST_FRAME
@ PROFILE_BUCKET_FIRST_FRAME
Definition: AampProfiler.h:73
eMEDIATYPE_IFRAME
@ eMEDIATYPE_IFRAME
Definition: AampMediaType.h:45
eAAMPConfig_PreferredAudioLabel
@ eAAMPConfig_PreferredAudioLabel
Definition: AampConfig.h:314
AampOutputProtection::GetAampOutputProcectionInstance
static AampOutputProtection * GetAampOutputProcectionInstance()
Singleton for object creation.
Definition: aampoutputprotection.cpp:441
AampConfig::GetChannelLicenseOverride
const char * GetChannelLicenseOverride(const std::string chName)
GetChannelLicenseOverride - Gets channel License override url for channel Url.
Definition: AampConfig.cpp:785
PrivateInstanceAAMP::mPlaybackDuration
double mPlaybackDuration
Definition: priv_aamp.h:4046
replace
static bool replace(std::string &str, const char *existingSubStringToReplace, const char *replacementString)
replace all occurrences of existingSubStringToReplace in str with replacementString
Definition: priv_aamp.cpp:556
PrivateInstanceAAMP::TeardownStream
void TeardownStream(bool newTune)
Terminate the stream.
Definition: priv_aamp.cpp:4641
PrivateInstanceAAMP::GetContentType
ContentType GetContentType() const
Get Content Type.
Definition: priv_aamp.cpp:6193
eAUTHTOKEN_INVALID_STATUS_CODE
@ eAUTHTOKEN_INVALID_STATUS_CODE
Definition: main_aamp.h:144
AampCacheHandler.h
Cache handler for AAMP.
PrivateInstanceAAMP::SendId3MetadataEvent
void SendId3MetadataEvent(Id3CallbackData *id3Metadata)
Sends an ID3 metadata event.
Definition: priv_aamp.cpp:9227
MAX_URL_LOG_SIZE
#define MAX_URL_LOG_SIZE
Max URL log size.
Definition: priv_aamp.h:119
eMEDIAFORMAT_SMOOTHSTREAMINGMEDIA
@ eMEDIAFORMAT_SMOOTHSTREAMINGMEDIA
Definition: AampDrmMediaFormat.h:41
StreamAbstractionAAMP::GetCurrentAudioTrack
virtual bool GetCurrentAudioTrack(AudioTrackInfo &audioTrack)
Get current audio track information.
Definition: streamabstraction.cpp:2974
PrivateInstanceAAMP::mScheduler
AampScheduler * mScheduler
Definition: priv_aamp.h:4064
eDASH_RECONFIGURE_FOR_ENC_PERIOD
@ eDASH_RECONFIGURE_FOR_ENC_PERIOD
Definition: priv_aamp.h:183
eAAMPConfig_ABRSkipDuration
@ eAAMPConfig_ABRSkipDuration
Definition: AampConfig.h:217
aamp_getHostFromURL
std::string aamp_getHostFromURL(std::string url)
Extract host string from url.
Definition: AampUtils.cpp:232
PrivateInstanceAAMP::UpdateDuration
void UpdateDuration(double seconds)
Update playlist duration.
Definition: priv_aamp.cpp:2095
PrivateInstanceAAMP::SendStreamCopy
void SendStreamCopy(MediaType mediaType, const void *ptr, size_t len, double fpts, double fdts, double fDuration)
API to send audio/video stream into the sink.
Definition: priv_aamp.cpp:7010
eAAMPConfig_HarvestConfig
@ eAAMPConfig_HarvestConfig
Definition: AampConfig.h:212
BUFFER_STATUS_YELLOW
@ BUFFER_STATUS_YELLOW
Definition: StreamAbstractionAAMP.h:141
VTTCue
Data structure to hold a VTT cue.
Definition: vttCue.h:39
eAAMPConfig_ABRCacheLife
@ eAAMPConfig_ABRCacheLife
Definition: AampConfig.h:213
PrivateInstanceAAMP::ExtractDrmInitData
const std::tuple< std::string, std::string > ExtractDrmInitData(const char *url)
Extract DRM init data from the provided URL If present, the init data will be removed from the return...
Definition: priv_aamp.cpp:6204
StreamAbstractionAAMP_MPD
Fragment collector for MPEG DASH.
Definition: fragmentcollector_mpd.h:175
AAMPTuneFailure
AAMPTuneFailure
AAMP playback error codes.
Definition: AampEvent.h:108
PrivateInstanceAAMP::SetCallbackAsDispatched
void SetCallbackAsDispatched(guint id)
Set an idle callback as event dispatched state.
Definition: priv_aamp.cpp:8206
eSTATE_RELEASED
@ eSTATE_RELEASED
Definition: AampEvent.h:171
StreamAbstractionAAMP::GetAvailableAudioTracks
virtual std::vector< AudioTrackInfo > & GetAvailableAudioTracks(bool allTrack=false)
Get available audio tracks.
Definition: StreamAbstractionAAMP.h:1105
MediaTypeTelemetry
MediaTypeTelemetry
Media types for telemetry.
Definition: main_aamp.h:92
PrivateInstanceAAMP::NotifyFirstVideoFrameDisplayed
void NotifyFirstVideoFrameDisplayed()
Notify First Video Frame was displayed.
Definition: priv_aamp.cpp:9834
eLOGLEVEL_WARN
@ eLOGLEVEL_WARN
Definition: AampLogManager.h:101
PrivateInstanceAAMP::FoundEventBreak
void FoundEventBreak(const std::string &adBreakId, uint64_t startMS, EventBreakInfo brInfo)
Notification from the stream abstraction that a new SCTE35 event is found.
Definition: priv_aamp.cpp:8853
eAAMPConfig_LicenseProxy
@ eAAMPConfig_LicenseProxy
Definition: AampConfig.h:307
AudioTrackInfo::name
std::string name
Definition: main_aamp.h:183
_NetworkManager_EventId_t
_NetworkManager_EventId_t
Enumeration for net_srv_mgr active interface event callback.
Definition: priv_aamp.cpp:183
StreamAbstractionAAMP::Init
virtual AAMPStatusType Init(TuneType tuneType)=0
Initialize a newly created object. To be implemented by sub classes.
PrivateInstanceAAMP::ReportID3Metadata
void ReportID3Metadata(MediaType mediaType, const uint8_t *ptr, uint32_t len, const char *schemeIdURI=NULL, const char *id3Value=NULL, uint64_t presTime=0, uint32_t id3ID=0, uint32_t eventDur=0, uint32_t tScale=0, uint64_t tStampOffset=0)
Report ID3 metadata events.
Definition: priv_aamp.cpp:11540
PrivateInstanceAAMP::preferredTextTypeString
std::string preferredTextTypeString
Definition: priv_aamp.h:976
AampCacheHandler::StopPlaylistCache
void StopPlaylistCache()
Stop playlist caching.
Definition: AampCacheHandler.cpp:358
PrivateInstanceAAMP::GetLicenseCustomData
std::string GetLicenseCustomData()
Get License Custom Data.
Definition: priv_aamp.cpp:11994
PrivateInstanceAAMP::mFragmentCachingLock
pthread_mutex_t mFragmentCachingLock
Definition: priv_aamp.h:4056
eAAMPConfig_DiscontinuityTimeout
@ eAAMPConfig_DiscontinuityTimeout
Definition: AampConfig.h:275
AAMP_EVENT_EOS
@ AAMP_EVENT_EOS
Definition: AampEvent.h:50
MediaStreamContext
MPD media track.
Definition: MediaStreamContext.h:35
IARM_Bus_NetworkManager_EventId_t
enum _NetworkManager_EventId_t IARM_Bus_NetworkManager_EventId_t
Enumeration for net_srv_mgr active interface event callback.
StreamSink::IsCacheEmpty
virtual bool IsCacheEmpty(MediaType mediaType)
Check whether cach is empty.
Definition: main_aamp.h:600
PrivateInstanceAAMP::GetAppName
std::string GetAppName()
Get the application name.
Definition: priv_aamp.cpp:9799
PrivateInstanceAAMP::preferredLabelsString
std::string preferredLabelsString
Definition: priv_aamp.h:968
PROFILE_BUCKET_INIT_AUDIO
@ PROFILE_BUCKET_INIT_AUDIO
Definition: AampProfiler.h:53
PrivateInstanceAAMP::IsLive
bool IsLive(void)
Checking if the stream is live or not.
Definition: priv_aamp.cpp:7042
EventBreakInfo
Stores the detail about the Event break info.
Definition: priv_aamp.h:354
PrivateInstanceAAMP::mAdEventQMtx
std::mutex mAdEventQMtx
Definition: priv_aamp.h:810
AAMP_TUNE_DEVICE_NOT_PROVISIONED
@ AAMP_TUNE_DEVICE_NOT_PROVISIONED
Definition: AampEvent.h:142
AAMP_EVENT_ID3_METADATA
@ AAMP_EVENT_ID3_METADATA
Definition: AampEvent.h:82
PrivateInstanceAAMP::GetPreferredAudioProperties
std::string GetPreferredAudioProperties()
get the current audio preference set by user
Definition: priv_aamp.cpp:9431
CCFormat
CCFormat
Different CC formats.
Definition: AampCCManager.h:39
AampLogManager::curlHeader
bool curlHeader
Definition: AampLogManager.h:162
ProfileEventAAMP::ProfileBegin
void ProfileBegin(ProfilerBucketType type)
Marking the beginning of a bucket.
Definition: AampProfiler.cpp:297
eTUNETYPE_SEEKTOLIVE
@ eTUNETYPE_SEEKTOLIVE
Definition: priv_aamp.h:195
PrivateInstanceAAMP::IsLiveAdjustRequired
bool IsLiveAdjustRequired()
Check if Live Adjust is required for current content. ( For "vod/ivod/ip-dvr/cdvr/eas",...
Definition: priv_aamp.cpp:8647
aamp_TransferMemory
void aamp_TransferMemory(void *ptr)
called when ownership of memory of injected fragments passed to gstreamer
Definition: AampMemoryUtils.cpp:81
AudioTrackInfo::accessibilityItem
Accessibility accessibilityItem
Definition: main_aamp.h:194
PrivateInstanceAAMP::TryStreamLock
bool TryStreamLock()
try to acquire streamsink lock
Definition: priv_aamp.cpp:10680
PrivateInstanceAAMP::IsPlayEnabled
bool IsPlayEnabled()
Check if autoplay enabled for current stream.
Definition: priv_aamp.cpp:6239
AAMP_EVENT_TUNED
@ AAMP_EVENT_TUNED
Definition: AampEvent.h:47
StreamAbstractionAAMP::ResumeSubtitleOnPlay
virtual void ResumeSubtitleOnPlay(bool mute, char *data)
resume subtitles on play
Definition: StreamAbstractionAAMP.h:1363
eMEDIATYPE_PLAYLIST_SUBTITLE
@ eMEDIATYPE_PLAYLIST_SUBTITLE
Definition: AampMediaType.h:52
VSS_MARKER_FOG
#define VSS_MARKER_FOG
Definition: priv_aamp.h:92
PrivateInstanceAAMP::IsAuxiliaryAudioEnabled
bool IsAuxiliaryAudioEnabled(void)
To check if auxiliary audio is enabled.
Definition: priv_aamp.cpp:10697
priv_aamp.h
Private functions and types used internally by AAMP.
PrivateInstanceAAMP::NotifySpeedChanged
void NotifySpeedChanged(float rate, bool changeState=true)
Notify speed change event to listeners.
Definition: priv_aamp.cpp:2582
AAMP_EVENT_REPORT_METRICS_DATA
@ AAMP_EVENT_REPORT_METRICS_DATA
Definition: AampEvent.h:81
PrivateInstanceAAMP::seek_pos_seconds
double seek_pos_seconds
Definition: priv_aamp.h:954
PrivateInstanceAAMP::mFragmentCachingRequired
bool mFragmentCachingRequired
Definition: priv_aamp.h:4055
PrivateInstanceAAMP::mCurrentLanguageIndex
int mCurrentLanguageIndex
Definition: priv_aamp.h:962
AampEventManager::IsEventListenerAvailable
bool IsEventListenerAvailable(AAMPEventType eventType)
IsEventListenerAvailable - Check if any listners present for this event.
Definition: AampEventManager.cpp:221
eAAMPConfig_DisableATMOS
@ eAAMPConfig_DisableATMOS
Definition: AampConfig.h:108
PrivateInstanceAAMP::mLogTimetoTopProfile
bool mLogTimetoTopProfile
Definition: priv_aamp.h:998
PrivateInstanceAAMP::AddHighIdleTask
static gint AddHighIdleTask(IdleTask task, void *arg, DestroyTask dtask=NULL)
Add high priority idle task to the gstreamer.
Definition: priv_aamp.cpp:7780
eDASH_LOW_LATENCY_INPUT_PROTECTION_ERROR
@ eDASH_LOW_LATENCY_INPUT_PROTECTION_ERROR
Definition: priv_aamp.h:182
PrivateInstanceAAMP::DiscontinuitySeenInAllTracks
bool DiscontinuitySeenInAllTracks()
Check if discontinuity processed in all tracks.
Definition: priv_aamp.cpp:10706
PrivateInstanceAAMP::SetVideoTracks
void SetVideoTracks(std::vector< long > bitrateList)
set birate for video tracks selection
Definition: priv_aamp.cpp:9546
PrivateInstanceAAMP::AdditionalTuneFailLogEntries
void AdditionalTuneFailLogEntries()
Additional log entries to assist with tune failure diagnostics.
Definition: priv_aamp.cpp:2941
eAAMPConfig_PreferredAudioRendition
@ eAAMPConfig_PreferredAudioRendition
Definition: AampConfig.h:311
PrivateInstanceAAMP::SendAdPlacementEvent
void SendAdPlacementEvent(AAMPEventType type, const std::string &adId, uint32_t position, uint32_t adOffset, uint32_t adDuration, bool immediate=false, long error_code=0)
Send Ad placement event.
Definition: priv_aamp.cpp:8957
AAMP_TUNE_LICENCE_REQUEST_FAILED
@ AAMP_TUNE_LICENCE_REQUEST_FAILED
Definition: AampEvent.h:127
eAAMPConfig_TuneEventConfig
@ eAAMPConfig_TuneEventConfig
Definition: AampConfig.h:224
IsoBmffBuffer::parseBuffer
bool parseBuffer(bool correctBoxSize=false, int newTrackId=-1)
Parse ISOBMFF boxes from buffer.
Definition: isobmffbuffer.cpp:59
TuneEndMetrics::mTimedMetadataStartTime
long long mTimedMetadataStartTime
Definition: AampProfiler.h:129
eAAMPConfig_SslVerifyPeer
@ eAAMPConfig_SslVerifyPeer
Definition: AampConfig.h:126
PrivateInstanceAAMP::GetPositionMs
long long GetPositionMs(void)
Get current stream position.
Definition: priv_aamp.cpp:6842
GetStatus
static std::string GetStatus(gpointer pElementOrBin, int &recursionCount, gpointer pParent=nullptr)
returns a string describing pElementOrBin and its children (if any). The top level elements name:stat...
Definition: aampgstplayer.cpp:3226
PrivateInstanceAAMP::ScheduleAsyncTask
int ScheduleAsyncTask(IdleTask task, void *arg, std::string taskName="")
Add async task to scheduler.
Definition: priv_aamp.cpp:10632
eMEDIATYPE_TELEMETRY_INIT
@ eMEDIATYPE_TELEMETRY_INIT
Definition: main_aamp.h:96
PrivateInstanceAAMP::SendBlockedEvent
void SendBlockedEvent(const std::string &reason)
Generate Blocked event based on args passed.
Definition: priv_aamp.cpp:8808
PrivateInstanceAAMP::mLock
pthread_mutex_t mLock
Definition: priv_aamp.h:803
PrivateInstanceAAMP::LoadAampAbrConfig
void LoadAampAbrConfig(void)
-To Load needed config from player to aampabr
Definition: priv_aamp.cpp:11969
PrivateInstanceAAMP::CollectCMCDCustomHeaders
void CollectCMCDCustomHeaders(MediaType fileType, class CMCDHeaders *pCMCDMetrics)
Collect and send all key-value pairs for CMCD headers.
Definition: priv_aamp.cpp:8246
PrivateInstanceAAMP::mLanguageList
char mLanguageList[16][42]
Definition: priv_aamp.h:961
FRAGMENT_DOWNLOAD_WARNING_THRESHOLD
#define FRAGMENT_DOWNLOAD_WARNING_THRESHOLD
Definition: AampDefine.h:109
eAAMPSTATUS_INVALID_PLAYLIST_ERROR
@ eAAMPSTATUS_INVALID_PLAYLIST_ERROR
Definition: priv_aamp.h:219
PrivateInstanceAAMP::LoadFogConfig
long LoadFogConfig(void)
LoadFogConfig - Load needed player Config to Fog.
Definition: priv_aamp.cpp:11791
StreamSink::GetPositionMilliseconds
virtual long GetPositionMilliseconds(void)
Get playback position in milliseconds.
Definition: main_aamp.h:505
PrivateInstanceAAMP::GetLangCodePreference
LangCodePreference GetLangCodePreference()
Get Language preference from aamp.cfg.
Definition: priv_aamp.cpp:5796
StreamSink
GStreamer Abstraction class for the implementation of AAMPGstPlayer and gstaamp plugin.
Definition: main_aamp.h:385
PrivateInstanceAAMP::GetPlayerVideoSize
void GetPlayerVideoSize(int &w, int &h)
Get player video size.
Definition: priv_aamp.cpp:8198
eMEDIAFORMAT_OTA
@ eMEDIAFORMAT_OTA
Definition: AampDrmMediaFormat.h:38
AAMP_TUNE_CORRUPT_DRM_METADATA
@ AAMP_TUNE_CORRUPT_DRM_METADATA
Definition: AampEvent.h:134
AAMP_TUNE_CONTENT_NOT_FOUND
@ AAMP_TUNE_CONTENT_NOT_FOUND
Definition: AampEvent.h:140
ThumbnailData
Holds the Thumbnail information.
Definition: priv_aamp.h:474
AAMPNetworkErrorCurl
@ AAMPNetworkErrorCurl
Definition: AampLogManager.h:114
AAMP_TUNE_UNSUPPORTED_AUDIO_TYPE
@ AAMP_TUNE_UNSUPPORTED_AUDIO_TYPE
Definition: AampEvent.h:130
StreamSink::ResetEOSSignalledFlag
virtual void ResetEOSSignalledFlag()
Reset EOS SignalledFlag.
Definition: main_aamp.h:605
PrivateInstanceAAMP::CheckABREnabled
bool CheckABREnabled(void)
Check if ABR enabled for this playback session.
Definition: priv_aamp.h:2675
eAAMPConfig_PreferredAudioLanguage
@ eAAMPConfig_PreferredAudioLanguage
Definition: AampConfig.h:313
AAMPLOG_TRACE
#define AAMPLOG_TRACE(FORMAT,...)
AAMP logging defines, this can be enabled through setLogLevel() as per the need.
Definition: AampLogManager.h:83
eAAMPConfig_UseSecManager
@ eAAMPConfig_UseSecManager
Definition: AampConfig.h:190
PrivateInstanceAAMP::GetAsyncTuneConfig
bool GetAsyncTuneConfig()
Get async tune configuration.
Definition: priv_aamp.cpp:6646
eAAMPConfig_SchemeIdUriDaiStream
@ eAAMPConfig_SchemeIdUriDaiStream
Definition: AampConfig.h:321
StreamAbstractionAAMP::ResumeSubtitleAfterSeek
virtual void ResumeSubtitleAfterSeek(bool mute, char *data)
resume subtitles after trickplay
Definition: StreamAbstractionAAMP.h:1380
PrivateInstanceAAMP::mPlaylistFetchFailError
long mPlaylistFetchFailError
Definition: priv_aamp.h:1049
PrivateInstanceAAMP::ResetDiscontinuityInTracks
void ResetDiscontinuityInTracks()
Reset discontinuity flag for all tracks.
Definition: priv_aamp.cpp:10734
StreamAbstractionAAMP::NotifyPlaybackPaused
virtual void NotifyPlaybackPaused(bool paused)
Function called when playback is paused to update related flags.
Definition: streamabstraction.cpp:2245
AAMP_EVENT_AD_RESERVATION_START
@ AAMP_EVENT_AD_RESERVATION_START
Definition: AampEvent.h:75
eAAMPConfig_ForceEC3
@ eAAMPConfig_ForceEC3
Definition: AampConfig.h:106
PrivateInstanceAAMP::GetIframeBitrate4K
long GetIframeBitrate4K()
Get Default Iframe bitrate 4K value.
Definition: priv_aamp.cpp:6335
AampCurlInstance
AampCurlInstance
Enumeration for Curl Instances.
Definition: priv_aamp.h:156
PrivateInstanceAAMP::IsActiveInstancePresent
static bool IsActiveInstancePresent()
Check if any active PrivateInstanceAAMP available.
Definition: priv_aamp.cpp:10472
isobmffbuffer.h
Header file for ISO Base Media File Format Buffer.
GrowableBuffer
Structure of GrowableBuffer.
Definition: AampMemoryUtils.h:39
eCURLINSTANCE_MAX
@ eCURLINSTANCE_MAX
Definition: priv_aamp.h:166
StreamSink::GetVideoPTS
virtual long long GetVideoPTS(void)
Get Video 90 KHz Video PTS.
Definition: main_aamp.h:512
AampJsonObject::print_UnFormatted
std::string print_UnFormatted()
Print the constructed JSON to a string.
Definition: AampJsonObject.cpp:380
getDefaultHarvestPath
void getDefaultHarvestPath(std::string &value)
Get harvest path to dump the files.
Definition: AampUtils.cpp:102
StreamAbstractionAAMP::GetStreamPosition
virtual double GetStreamPosition()=0
Get current stream position.
PrivateInstanceAAMP::FlushLastId3Data
void FlushLastId3Data(MediaType mediaType)
Flush last saved ID3 metadata.
Definition: priv_aamp.cpp:11558
PrivateInstanceAAMP
Class representing the AAMP player's private instance, which is not exposed to outside world.
Definition: priv_aamp.h:640
PrivAAMPState
PrivAAMPState
Mapping all required status codes based on JS player requirement. These requirements may be forced by...
Definition: AampEvent.h:156
MAX_SESSION_ID_LENGTH
#define MAX_SESSION_ID_LENGTH
Definition: priv_aamp.h:80
AampConfig::CustomSearch
bool CustomSearch(std::string url, int playerId, std::string appname)
CustomSearch - Function to apply custom search.
Definition: AampConfig.cpp:1142
PrivateInstanceAAMP::StoreLanguageList
void StoreLanguageList(const std::set< std::string > &langlist)
Storing audio language list.
Definition: priv_aamp.cpp:3265
PrivateInstanceAAMP::GetAudTimeScale
uint32_t GetAudTimeScale(void)
Gets Audio TimeScale.
Definition: priv_aamp.cpp:11620
PrivateInstanceAAMP::StopBuffering
void StopBuffering(bool forceStop)
Stop buffering in AAMP and un-pause pipeline.
Definition: priv_aamp.cpp:9942
SimulateLinearWindow
static void SimulateLinearWindow(struct GrowableBuffer *buffer, const char *ptr, size_t len)
Simulate VOD asset as a "virtual linear" stream.
Definition: priv_aamp.cpp:419
StreamAbstractionAAMP::SetVideoRectangle
virtual void SetVideoRectangle(int x, int y, int w, int h)
setVideoRectangle sets the position coordinates (x,y) & size (w,h) for OTA streams only
Definition: StreamAbstractionAAMP.h:1206
eAAMPConfig_LivePauseBehavior
@ eAAMPConfig_LivePauseBehavior
Definition: AampConfig.h:250
PrivateInstanceAAMP::NotifyFirstVideoPTS
void NotifyFirstVideoPTS(unsigned long long pts, unsigned long timeScale=90000)
Receives first video PTS of the current playback.
Definition: priv_aamp.cpp:9168
AampCacheHandler
Handles Aamp Cahe operations.
Definition: AampCacheHandler.h:110
PrivateInstanceAAMP::mNextPeriodScaledPtoStartTime
double mNextPeriodScaledPtoStartTime
Definition: priv_aamp.h:1078
StreamAbstractionAAMP::GetAvailableTextTracks
virtual std::vector< TextTrackInfo > & GetAvailableTextTracks(bool allTrack=false)
Get available text tracks.
Definition: StreamAbstractionAAMP.h:1112
eMEDIAFORMAT_HLS
@ eMEDIAFORMAT_HLS
Definition: AampDrmMediaFormat.h:34
MAX_DEBUG_LOG_BUFF_SIZE
#define MAX_DEBUG_LOG_BUFF_SIZE
Max debug log buffer size.
Definition: priv_aamp.h:114
eAAMPConfig_AsyncTune
@ eAAMPConfig_AsyncTune
Definition: AampConfig.h:173
PrivateInstanceAAMP::BlockUntilGstreamerWantsData
void BlockUntilGstreamerWantsData(void(*cb)(void), int periodMs, int track)
Block the injector thread until the gstreanmer needs buffer/more data.
Definition: priv_aamp.cpp:3224
eAAMPConfig_PersistLowNetworkBandwidth
@ eAAMPConfig_PersistLowNetworkBandwidth
Definition: AampConfig.h:198
PrivateInstanceAAMP::waitforplaystart
pthread_cond_t waitforplaystart
Definition: priv_aamp.h:999
StreamSink::SignalTrickModeDiscontinuity
virtual void SignalTrickModeDiscontinuity()
Signal discontinuity on trickmode if restamping is done by stream sink.
Definition: main_aamp.h:652
PROFILE_BUCKET_PLAYLIST_AUXILIARY
@ PROFILE_BUCKET_PLAYLIST_AUXILIARY
Definition: AampProfiler.h:50
ProfileEventAAMP::TuneBegin
void TuneBegin(void)
Profiler method to perform tune begin related operations.
Definition: AampProfiler.cpp:94
PrivateInstanceAAMP::IsFirstVideoFrameDisplayedRequired
bool IsFirstVideoFrameDisplayedRequired()
Check if First Video Frame Displayed Notification is required.
Definition: priv_aamp.cpp:9826
PrivateInstanceAAMP::SyncEnd
void SyncEnd(void)
GStreamer operation end.
Definition: priv_aamp.cpp:1902
PrivateInstanceAAMP::SendErrorEvent
void SendErrorEvent(AAMPTuneFailure tuneFailure, const char *description=NULL, bool isRetryEnabled=true, int32_t secManagerClassCode=-1, int32_t secManagerReasonCode=-1, int32_t secClientBusinessStatus=-1)
Handles errors and sends events to application if required. For download failures,...
Definition: priv_aamp.cpp:2454
TextTrackInfo::accessibilityItem
Accessibility accessibilityItem
Definition: main_aamp.h:295
PrivateInstanceAAMP::mediaType2Bucket
ProfilerBucketType mediaType2Bucket(MediaType fileType)
Convert media file type to profiler bucket type.
Definition: priv_aamp.cpp:9001
eAAMPConfig_TraceLogging
@ eAAMPConfig_TraceLogging
Definition: AampConfig.h:138
PrivateInstanceAAMP::mHarvestConfig
int mHarvestConfig
Definition: priv_aamp.h:4069
AampJsonObject::add
bool add(const std::string &name, const std::string &value, const ENCODING encoding=ENCODING_STRING)
Add a string value.
Definition: AampJsonObject.cpp:69
PrivateInstanceAAMP::mIsVSS
bool mIsVSS
Definition: priv_aamp.h:1021
IsoBmffBuffer::isInitSegment
bool isInitSegment()
Check if buffer is an initialization segment.
Definition: isobmffbuffer.cpp:360
AAMPGstPlayer::InitializeAAMPGstreamerPlugins
static void InitializeAAMPGstreamerPlugins(AampLogManager *logObj=NULL)
Increase the rank of AAMP decryptor plugins.
Definition: aampgstplayer.cpp:4391
PrivateInstanceAAMP::GetPlaylistCurlInstance
AampCurlInstance GetPlaylistCurlInstance(MediaType type, bool IsInitDnld=true)
GetPlaylistCurlInstance - Function to return the curl instance for playlist download Considers parall...
Definition: priv_aamp.cpp:3360
AAMP_MAX_EVENT_PRIORITY
#define AAMP_MAX_EVENT_PRIORITY
Definition: AampDefine.h:158
write_callback
static size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
write callback to be used by CURL
Definition: priv_aamp.cpp:830
ContentType_MDVR
@ ContentType_MDVR
Definition: AampProfiler.h:109
eAAMPSTATUS_MANIFEST_DOWNLOAD_ERROR
@ eAAMPSTATUS_MANIFEST_DOWNLOAD_ERROR
Definition: priv_aamp.h:210
eAAMPConfig_UserAgent
@ eAAMPConfig_UserAgent
Definition: AampConfig.h:301
PrivateInstanceAAMP::UnlockGetPositionMilliseconds
void UnlockGetPositionMilliseconds()
Unlock GetPositionMilliseconds()
Definition: priv_aamp.cpp:6873
CurlStore::GetCurlStoreInstance
static CurlStore * GetCurlStoreInstance(void *pContext)
Definition: AampCurlStore.cpp:514
PrivateInstanceAAMP::mbPlayEnabled
bool mbPlayEnabled
Definition: priv_aamp.h:1043
PrivateInstanceAAMP::AddCustomHTTPHeader
void AddCustomHTTPHeader(std::string headerName, std::vector< std::string > headerValue, bool isLicenseHeader)
Add/Remove a custom HTTP header and value.
Definition: priv_aamp.cpp:8384
eAAMPConfig_MaxPlaylistCacheSize
@ eAAMPConfig_MaxPlaylistCacheSize
Definition: AampConfig.h:230
PrivateInstanceAAMP::CurlTerm
void CurlTerm(AampCurlInstance startIdx, unsigned int instanceCount=1)
Terminate curl contexts.
Definition: priv_aamp.cpp:3333
PrivateInstanceAAMP::GetCCStatus
bool GetCCStatus(void)
Get CC visibility on/off.
Definition: priv_aamp.cpp:10416
PrivateInstanceAAMP::mOffsetFromTunetimeForSAPWorkaround
double mOffsetFromTunetimeForSAPWorkaround
Definition: priv_aamp.h:1086
PrivateInstanceAAMP::IsAudioLanguageSupported
bool IsAudioLanguageSupported(const char *checkLanguage)
Checking whether audio language supported.
Definition: priv_aamp.cpp:3289
PrivateInstanceAAMP::GetIframeBitrate
long GetIframeBitrate()
Get Default Iframe bitrate value.
Definition: priv_aamp.cpp:6325
PrivateInstanceAAMP::GetMediaFormatType
MediaFormat GetMediaFormatType(const char *url)
Assign the correct mediaFormat by parsing the url.
Definition: priv_aamp.cpp:5806
PrivateInstanceAAMP::PausePipeline
bool PausePipeline(bool pause, bool forceStopGstreamerPreBuffering)
To change the the gstreamer pipeline to pause/play.
Definition: priv_aamp.cpp:2440
eAAMPConfig_DefaultBitrate
@ eAAMPConfig_DefaultBitrate
Definition: AampConfig.h:268
eAAMPConfig_CEAPreferred
@ eAAMPConfig_CEAPreferred
Definition: AampConfig.h:243
eDASH_LOW_LATENCY_MAX_CORRECTION_REACHED
@ eDASH_LOW_LATENCY_MAX_CORRECTION_REACHED
Definition: priv_aamp.h:181
ProfilerBucketType
ProfilerBucketType
Bucket types of AAMP profiler.
Definition: AampProfiler.h:43
eAAMPConfig_EnableClientDai
@ eAAMPConfig_EnableClientDai
Definition: AampConfig.h:127
eMEDIATYPE_INIT_VIDEO
@ eMEDIATYPE_INIT_VIDEO
Definition: AampMediaType.h:46
DEFAULT_INTERVAL_BETWEEN_PLAYLIST_UPDATES_MS
#define DEFAULT_INTERVAL_BETWEEN_PLAYLIST_UPDATES_MS
Definition: priv_aamp.h:76
AAMP_EVENT_WEBVTT_CUE_DATA
@ AAMP_EVENT_WEBVTT_CUE_DATA
Definition: AampEvent.h:73
eAAMPConfig_ID3Logging
@ eAAMPConfig_ID3Logging
Definition: AampConfig.h:148
eCURLINSTANCE_VIDEO
@ eCURLINSTANCE_VIDEO
Definition: priv_aamp.h:158
eAAMPConfig_CurlHeader
@ eAAMPConfig_CurlHeader
Definition: AampConfig.h:146
PrivateInstanceAAMP::IsAudioOrVideoOnly
bool IsAudioOrVideoOnly(StreamOutputFormat videoFormat, StreamOutputFormat audioFormat, StreamOutputFormat auxFormat)
To check for audio/video only Playback.
Definition: priv_aamp.cpp:10567
AampEventManager::SendEvent
void SendEvent(const AAMPEventPtr &eventData, AAMPEventMode eventMode=AAMP_EVENT_DEFAULT_MODE)
SendEvent - Generic function to send events.
Definition: AampEventManager.cpp:274
eSTATE_BUFFERING
@ eSTATE_BUFFERING
Definition: AampEvent.h:163
MediaTrack::OnSinkBufferFull
void OnSinkBufferFull()
Called if sink buffer is full.
Definition: streamabstraction.cpp:2674
AampEventManager::FlushPendingEvents
void FlushPendingEvents()
FlushPendingEvents - Clear all pending events from EventManager.
Definition: AampEventManager.cpp:85
AampCurlStore.h
Advanced Adaptive Media Player (AAMP) Curl store.
httpRespHeaderData::type
int type
Definition: priv_aamp.h:466
eAAMPSTATUS_PLAYLIST_AUDIO_DOWNLOAD_ERROR
@ eAAMPSTATUS_PLAYLIST_AUDIO_DOWNLOAD_ERROR
Definition: priv_aamp.h:212
AAMPStatusType
AAMPStatusType
AAMP Function return values.
Definition: priv_aamp.h:205
PrivateInstanceAAMP::mCdaiObject
class CDAIObject * mCdaiObject
Definition: priv_aamp.h:808
PrivateInstanceAAMP::UpdateProfileCappedStatus
void UpdateProfileCappedStatus(void)
updates profile capped status
Definition: priv_aamp.cpp:7952
PrivateInstanceAAMP::mWaitForDiscoToComplete
pthread_cond_t mWaitForDiscoToComplete
Definition: priv_aamp.h:1081
PrivateInstanceAAMP::SendAnomalyEvent
void SendAnomalyEvent(AAMPAnomalyMessageType type, const char *format,...)
Sends Anomaly Error/warning messages.
Definition: priv_aamp.cpp:2391
PrivateInstanceAAMP::pipeline_paused
bool pipeline_paused
Definition: priv_aamp.h:958
PrivateInstanceAAMP::PauseSubtitleParser
void PauseSubtitleParser(bool pause)
pause/un-pause subtitles
Definition: priv_aamp.cpp:8460
StreamAbstractionAAMP::SeekPosUpdate
virtual void SeekPosUpdate(double secondsRelativeToTuneTime)=0
Update seek position when player is initialized.
AampConstants.h
Constants in AAMP.
PrivateInstanceAAMP::mDisplayHeight
int mDisplayHeight
Definition: priv_aamp.h:1063
TuneFailureMap::description
const char * description
Definition: main_aamp.h:84
PrivateInstanceAAMP::LogDrmDecryptBegin
void LogDrmDecryptBegin(ProfilerBucketType bucketType)
Notifies profiler that decryption has started.
Definition: priv_aamp.cpp:3131
AampCCManagerBase::SetTrickplayStatus
void SetTrickplayStatus(bool enable)
To enable/disable CC when trickplay starts/ends.
Definition: AampCCManager.cpp:609
CDAIObject::SetAlternateContents
virtual void SetAlternateContents(const std::string &adBreakId, const std::string &adId, const std::string &url, uint64_t startMS=0, uint32_t breakdur=0)
Setting the alternate contents' (Ads/blackouts) URL.
Definition: AdManagerBase.h:100
StreamSink::Flush
virtual void Flush(double position=0, int rate=1, bool shouldTearDown=true)
Flush the pipeline.
Definition: main_aamp.h:466
eAAMPConfig_EnableAampConfigToFog
@ eAAMPConfig_EnableAampConfigToFog
Definition: AampConfig.h:192
PrivateInstanceAAMP::SetVideoZoom
void SetVideoZoom(VideoZoomMode zoom)
Set video zoom.
Definition: priv_aamp.cpp:6704
eAAMPConfig_Http5XXRetryWaitInterval
@ eAAMPConfig_Http5XXRetryWaitInterval
Definition: AampConfig.h:232
ePAUSED_BEHAVIOR_AUTOPLAY_DEFER
@ ePAUSED_BEHAVIOR_AUTOPLAY_DEFER
Definition: AampDefine.h:199
eAAMPConfig_Subtec_subtitle
@ eAAMPConfig_Subtec_subtitle
Definition: AampConfig.h:171
PrivateInstanceAAMP::mbUsingExternalPlayer
bool mbUsingExternalPlayer
Definition: priv_aamp.h:1069
PrivateInstanceAAMP::StartPausePositionMonitoring
void StartPausePositionMonitoring(long long pausePositionMilliseconds)
start the PausePositionMonitoring thread used for PauseAt functionality
Definition: priv_aamp.cpp:1811
PrivateInstanceAAMP::IsSubtitleEnabled
bool IsSubtitleEnabled(void)
To check if subtitles are enabled.
Definition: priv_aamp.cpp:9201
AampCCManagerBase::GetId
virtual int GetId()
Gets Handle or ID, Every client using subtec must call GetId in the begining , save id,...
Definition: AampCCManager.h:66
PrivateInstanceAAMP::ReportProgress
void ReportProgress(bool sync=true, bool beginningOfStream=false)
Report progress event to listeners.
Definition: priv_aamp.cpp:1928
AAMPEventType
AAMPEventType
Type of the events sending to the JSPP player.
Definition: AampEvent.h:44
PreCacheUrlData
Pre cache the data information.
Definition: main_aamp.h:151
aamp_GetCurrentTimeMS
long long aamp_GetCurrentTimeMS(void)
Get current time from epoch is milliseconds.
Definition: AampUtils.cpp:92
aamp_AppendBytes
void aamp_AppendBytes(struct GrowableBuffer *buffer, const void *ptr, size_t len)
append data to GrowableBuffer ADT
Definition: AampMemoryUtils.cpp:108
eAAMPConfig_ProgressLogging
@ eAAMPConfig_ProgressLogging
Definition: AampConfig.h:142
PrivateInstanceAAMP::SetVideoRectangle
void SetVideoRectangle(int x, int y, int w, int h)
Set video rectangle.
Definition: priv_aamp.cpp:6667
StreamAbstractionAAMP::MuteSubtitleOnPause
virtual void MuteSubtitleOnPause()
mute subtitles on pause
Definition: StreamAbstractionAAMP.h:1354
AampCCManager::GetInstance
static AampCCManagerBase * GetInstance()
Get the singleton instance.
Definition: AampCCManager.cpp:799
AAMP_TUNE_DRM_KEY_UPDATE_FAILED
@ AAMP_TUNE_DRM_KEY_UPDATE_FAILED
Definition: AampEvent.h:141
AAMP_TUNE_PLAYBACK_STALLED
@ AAMP_TUNE_PLAYBACK_STALLED
Definition: AampEvent.h:139
createJsonData
static char * createJsonData(TextTrackInfo &track)
Create json data from track Info.
Definition: priv_aamp.cpp:10182
PrivateInstanceAAMP::IsAudioPlayContextCreationSkipped
bool IsAudioPlayContextCreationSkipped(void)
Check if audio playcontext creation skipped for Demuxed HLS file.
Definition: priv_aamp.cpp:7051
StreamSink::SetAudioVolume
virtual void SetAudioVolume(int volume)
Set volume level.
Definition: main_aamp.h:570
ContentType_COMPOSITEIN
@ ContentType_COMPOSITEIN
Definition: AampProfiler.h:115
PrivateInstanceAAMP::ReloadTSB
void ReloadTSB()
API Used to reload TSB with new session.
Definition: priv_aamp.cpp:5321
PrivateInstanceAAMP::SetPreCacheDownloadList
void SetPreCacheDownloadList(PreCacheUrlList &dnldListInput)
SetPreCacheDownloadList - Function to assign the PreCaching file list.
Definition: priv_aamp.cpp:9369
TuneEndMetrics::success
int success
Definition: AampProfiler.h:126
TextTrackInfo
Structure for text track information Holds information about a text track in playlist.
Definition: main_aamp.h:282
eTUNETYPE_SEEKTOEND
@ eTUNETYPE_SEEKTOEND
Definition: priv_aamp.h:199
StreamAbstractionAAMP::GetMaxBitrate
virtual long GetMaxBitrate()
Gets Max bitrate supported.
Definition: StreamAbstractionAAMP.h:987
PrivateInstanceAAMP::preferredRenditionString
std::string preferredRenditionString
Definition: priv_aamp.h:966
eAAMPConfig_DisableAC4
@ eAAMPConfig_DisableAC4
Definition: AampConfig.h:109
PrivateInstanceAAMP::GetLicenseReqProxy
std::string GetLicenseReqProxy()
To get the proxy for license request.
Definition: priv_aamp.cpp:9089
AampCacheHandler::SetMaxInitFragCacheSize
void SetMaxInitFragCacheSize(int maxInitFragCacheSz)
SetMaxInitFragCacheSize - Set Max Cache Size.
Definition: AampCacheHandler.cpp:618
AampCacheHandler::SetMaxPlaylistCacheSize
void SetMaxPlaylistCacheSize(int maxPlaylistCacheSz)
SetMaxPlaylistCacheSize - Set Max Cache Size.
Definition: AampCacheHandler.cpp:396
StreamAbstractionAAMP::MuteSubtitles
void MuteSubtitles(bool mute)
Send a MUTE/UNMUTE packet to the subtitle renderer.
Definition: streamabstraction.cpp:2585
AudioTrackInfo::mType
std::string mType
Definition: main_aamp.h:195
eSTATE_IDLE
@ eSTATE_IDLE
Definition: AampEvent.h:158
eAAMPConfig_EnableSubscribedTags
@ eAAMPConfig_EnableSubscribedTags
Definition: AampConfig.h:114
PrivateInstanceAAMP::ResetTrackDiscontinuityIgnoredStatus
void ResetTrackDiscontinuityIgnoredStatus(void)
Reset discontinuity ignored flag for audio and video tracks.
Definition: priv_aamp.cpp:10496
ProfileEventAAMP::ProfileEnd
void ProfileEnd(ProfilerBucketType type)
Marking the end of a bucket.
Definition: AampProfiler.cpp:325
eAAMPConfig_PlaylistParallelRefresh
@ eAAMPConfig_PlaylistParallelRefresh
Definition: AampConfig.h:167
PrivateInstanceAAMP::GetFirstPTS
double GetFirstPTS()
Get PTS of first sample.
Definition: priv_aamp.cpp:8638
eAAMPConfig_VODTrickPlayFPS
@ eAAMPConfig_VODTrickPlayFPS
Definition: AampConfig.h:225
StreamAbstractionAAMP::GetLastInjectedFragmentPosition
double GetLastInjectedFragmentPosition()
Function to returns last injected fragment position.
Definition: streamabstraction.cpp:2624
PrivateInstanceAAMP::IsSinkCacheEmpty
bool IsSinkCacheEmpty(MediaType mediaType)
Check sink cache empty.
Definition: priv_aamp.cpp:7789
AAMP_EVENT_AD_PLACEMENT_START
@ AAMP_EVENT_AD_PLACEMENT_START
Definition: AampEvent.h:77
AAMP_TUNE_INIT_FAILED_PLAYLIST_AUDIO_DNLD_ERROR
@ AAMP_TUNE_INIT_FAILED_PLAYLIST_AUDIO_DNLD_ERROR
Definition: AampEvent.h:115
ContentType
ContentType
Asset's content types.
Definition: AampProfiler.h:99
PrivateInstanceAAMP::SendVideoEndEvent
bool SendVideoEndEvent()
Send VideoEndEvent.
Definition: priv_aamp.cpp:7849
PrivateInstanceAAMP::mAuxAudioLanguage
std::string mAuxAudioLanguage
Definition: priv_aamp.h:4070
ePAUSED_BEHAVIOR_LIVE_IMMEDIATE
@ ePAUSED_BEHAVIOR_LIVE_IMMEDIATE
Definition: AampDefine.h:198
DEFAULT_ENCODED_CONTENT_BUFFER_SIZE
#define DEFAULT_ENCODED_CONTENT_BUFFER_SIZE
Definition: AampDefine.h:60
_IARM_BUS_NetSrvMgr_Iface_EventData_t
IARM Bus struct contains active streaming interface, origional definition present in homenetworkingse...
Definition: priv_aamp.cpp:193
eTUNED_EVENT_ON_FIRST_FRAGMENT_DECRYPTED
@ eTUNED_EVENT_ON_FIRST_FRAGMENT_DECRYPTED
Definition: AampDefine.h:187
CDAIObject
Base class for the client side DAI object.
Definition: AdManagerBase.h:57
TuneFailureMap
Structure holding aamp tune failure code and corresponding application error code and description.
Definition: main_aamp.h:80
eAAMPConfig_DefaultBitrate4K
@ eAAMPConfig_DefaultBitrate4K
Definition: AampConfig.h:269
TuneEndMetrics::mTimedMetadataDuration
int mTimedMetadataDuration
Definition: AampProfiler.h:130
PrivateInstanceAAMP::ResumeTrackInjection
void ResumeTrackInjection(MediaType type)
Resume injection for a track. Called from StartInjection.
Definition: priv_aamp.cpp:9147
MAX_PLAYLIST_CACHE_SIZE
#define MAX_PLAYLIST_CACHE_SIZE
Definition: AampDefine.h:63
StreamAbstractionAAMP_COMPOSITEIN
Fragment collector for MPEG DASH.
Definition: compositein_shim.h:41
PrivateInstanceAAMP::mEventManager
AampEventManager * mEventManager
Definition: priv_aamp.h:4051
TuneEndMetrics::streamType
int streamType
Definition: AampProfiler.h:127
PrivateInstanceAAMP::SetEventPriorityAsyncTune
void SetEventPriorityAsyncTune(bool bValue)
Set async tune configuration for EventPriority.
Definition: priv_aamp.cpp:6631
PrivateInstanceAAMP::SetLLDashSpeedCache
void SetLLDashSpeedCache(struct SpeedCache &speedCache)
Sets Speed Cache.
Definition: priv_aamp.cpp:11627
eAUTHTOKEN_TOKEN_PARSE_ERROR
@ eAUTHTOKEN_TOKEN_PARSE_ERROR
Definition: main_aamp.h:143
PrivateInstanceAAMP::DownloadsAreEnabled
bool DownloadsAreEnabled(void)
Check if downloads are enabled.
Definition: priv_aamp.cpp:6752
PrivateInstanceAAMP::SetUtcTime
void SetUtcTime(time_t time)
Set Utc Time.
Definition: priv_aamp.cpp:11679
IsActiveStreamingInterfaceWifi
static bool IsActiveStreamingInterfaceWifi(void)
Active streaming interface is wifi.
Definition: priv_aamp.cpp:636
eAAMPConfig_ABRChunkThresholdSize
@ eAAMPConfig_ABRChunkThresholdSize
Definition: AampConfig.h:256
PrivateInstanceAAMP::HandleSSLProgressCallback
int HandleSSLProgressCallback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
HandleSSLProgressCallback - Process progress callback from CURL.
Definition: priv_aamp.cpp:1116
PrivateInstanceAAMP::GetCustomLicenseHeaders
void GetCustomLicenseHeaders(std::unordered_map< std::string, std::vector< std::string >> &customHeaders)
To get any custom license HTTP headers that was set by application.
Definition: priv_aamp.cpp:9219
eAAMPConfig_MaxBitrate
@ eAAMPConfig_MaxBitrate
Definition: AampConfig.h:277
PrivateInstanceAAMP::GetVideoPTS
long long GetVideoPTS(bool bAddVideoBasePTS)
Report progress event.
Definition: priv_aamp.cpp:1910
PrivateInstanceAAMP::mApplyCachedVideoMute
bool mApplyCachedVideoMute
Definition: priv_aamp.h:1094
PrivateInstanceAAMP::mAdCurOffset
uint32_t mAdCurOffset
Definition: priv_aamp.h:1014
AampConfig::IsConfigSet
bool IsConfigSet(AAMPConfigSettings cfg)
Gets the boolean configuration value.
Definition: AampConfig.cpp:649
PrivateInstanceAAMP::~PrivateInstanceAAMP
~PrivateInstanceAAMP()
PrivateInstanceAAMP Destructor.
Definition: priv_aamp.cpp:1534
PrivateInstanceAAMP::NotifyFragmentCachingComplete
void NotifyFragmentCachingComplete()
Notify fragment caching complete.
Definition: priv_aamp.cpp:7805
AampCCManagerBase::RestoreCC
void RestoreCC()
To restore cc state after new tune.
Definition: AampCCManager.cpp:744
PrivateInstanceAAMP::GetCurrentDRM
std::shared_ptr< AampDrmHelper > GetCurrentDRM()
Get current drm.
Definition: priv_aamp.cpp:6453
ProfileEventAAMP::TuneEnd
void TuneEnd(TuneEndMetrics &mTuneendmetrics, std::string appName, std::string playerActiveMode, int playerId, bool playerPreBuffered, unsigned int durationSeconds, bool interfaceWifi, std::string failureReason)
Logging performance metrics after successful tune completion. Metrics starts with IP_AAMP_TUNETIME.
Definition: AampProfiler.cpp:157
eAAMPConfig_CDVRLiveOffset
@ eAAMPConfig_CDVRLiveOffset
Definition: AampConfig.h:290
PrivateInstanceAAMP::FlushStreamSink
void FlushStreamSink(double position, double rate)
Sending a flushing seek to stream sink with given position.
Definition: priv_aamp.cpp:9271
PrivateInstanceAAMP::UnblockWaitForDiscontinuityProcessToComplete
void UnblockWaitForDiscontinuityProcessToComplete(void)
unblock wait for Discontinuity handling complete
Definition: priv_aamp.cpp:1881
PrivateInstanceAAMP::IsMuxedStream
bool IsMuxedStream()
Check if current stream is muxed.
Definition: priv_aamp.cpp:9111
AAMPAnomalyMessageType
AAMPAnomalyMessageType
AAMP anomaly message types.
Definition: main_aamp.h:69
DRMSystems
DRMSystems
DRM system types.
Definition: AampDrmSystems.h:33
eAAMPConfig_InternalReTune
@ eAAMPConfig_InternalReTune
Definition: AampConfig.h:121
StreamAbstractionAAMP::MuteSidecarSubtitles
virtual void MuteSidecarSubtitles(bool mute)
mute/unmute sidecar subtitles
Definition: StreamAbstractionAAMP.h:1371
PrivateInstanceAAMP::GetPauseOnFirstVideoFrameDisp
bool GetPauseOnFirstVideoFrameDisp(void)
GetPauseOnFirstVideoFrameDisplay.
Definition: priv_aamp.cpp:11571
AAMP_TUNE_MANIFEST_REQ_FAILED
@ AAMP_TUNE_MANIFEST_REQ_FAILED
Definition: AampEvent.h:117
AAMP_EVENT_SEEKED
@ AAMP_EVENT_SEEKED
Definition: AampEvent.h:62
StreamAbstractionAAMP::IsMuxedStream
bool IsMuxedStream()
Check if current stream is muxed.
Definition: streamabstraction.cpp:2438
eAAMPSTATUS_FAKE_TUNE_COMPLETE
@ eAAMPSTATUS_FAKE_TUNE_COMPLETE
Definition: priv_aamp.h:208
eMEDIAFORMAT_HLS_MP4
@ eMEDIAFORMAT_HLS_MP4
Definition: AampDrmMediaFormat.h:37
PrivateInstanceAAMP::DisableDownloads
void DisableDownloads(void)
abort ongoing downloads and returns error on future downloads called while stopping fragment collecto...
Definition: priv_aamp.cpp:6741
eAAMPConfig_CustomHeaderLicense
@ eAAMPConfig_CustomHeaderLicense
Definition: AampConfig.h:310
AampEventManager::SetAsyncTuneState
void SetAsyncTuneState(bool isAsyncTuneSetting)
SetAsyncTuneState - Flag for Async Tune.
Definition: AampEventManager.cpp:246
StreamSink::SeekStreamSink
virtual void SeekStreamSink(double position, double rate)
Seek stream sink to desired position and playback rate with a flushing seek.
Definition: main_aamp.h:661
PrivateInstanceAAMP::mCurrentAudioTrackId
int mCurrentAudioTrackId
Definition: priv_aamp.h:1028
ContentType_HDMIIN
@ ContentType_HDMIIN
Definition: AampProfiler.h:114
PrivateInstanceAAMP::NotifyVideoBasePTS
void NotifyVideoBasePTS(unsigned long long basepts, unsigned long timeScale=90000)
Notifies base PTS of the HLS video playback.
Definition: priv_aamp.cpp:9179
eAAMPConfig_FogMaxConcurrentDownloads
@ eAAMPConfig_FogMaxConcurrentDownloads
Definition: AampConfig.h:262
eAAMPConfig_IFrameDefaultBitrate
@ eAAMPConfig_IFrameDefaultBitrate
Definition: AampConfig.h:270
PrivateInstanceAAMP::mIsDefaultOffset
bool mIsDefaultOffset
Definition: priv_aamp.h:1032
PrivateInstanceAAMP::LogFirstFrame
void LogFirstFrame(void)
Notifies profiler that first frame is presented.
Definition: priv_aamp.cpp:3107
PROFILE_BUCKET_PLAYLIST_SUBTITLE
@ PROFILE_BUCKET_PLAYLIST_SUBTITLE
Definition: AampProfiler.h:49
PrivateInstanceAAMP::SetCCStatus
void SetCCStatus(bool enabled)
Set CC visibility on/off.
Definition: priv_aamp.cpp:10394
PrivateInstanceAAMP::mDrmInitData
std::string mDrmInitData
Definition: priv_aamp.h:4054
StreamAbstractionAAMP::StartSubtitleParser
virtual void StartSubtitleParser()
Kicks off subtitle display - sent at start of video presentation.
Definition: StreamAbstractionAAMP.h:1062
PrivateInstanceAAMP::getStreamTypeString
std::string getStreamTypeString()
Get stream type as printable format.
Definition: priv_aamp.cpp:8982
StreamSink::EndOfStreamReached
virtual void EndOfStreamReached(MediaType mediaType)
Notifies EOS to sink.
Definition: main_aamp.h:434
eAAMPConfig_MaxInitFragCachePerTrack
@ eAAMPConfig_MaxInitFragCachePerTrack
Definition: AampConfig.h:261
base16.h
optimized way way base16 Encode/Decode operation
PrivateInstanceAAMP::NotifyFirstFragmentDecrypted
void NotifyFirstFragmentDecrypted()
Notify the decryption completion of the fist fragment.
Definition: priv_aamp.cpp:8620
PrivateInstanceAAMP::EnableContentRestrictions
void EnableContentRestrictions()
Enable Content Restrictions - lock.
Definition: priv_aamp.cpp:10618
hdmiin_shim.h
shim for dispatching UVE HDMI input playback
PrivateInstanceAAMP::GetLLDashServiceData
AampLLDashServiceData * GetLLDashServiceData(void)
Gets Low Latency Service Data.
Definition: priv_aamp.cpp:11587
eMEDIATYPE_PLAYLIST_AUDIO
@ eMEDIATYPE_PLAYLIST_AUDIO
Definition: AampMediaType.h:51
eTUNETYPE_NEW_SEEK
@ eTUNETYPE_NEW_SEEK
Definition: priv_aamp.h:193
eSTALL_AFTER_DISCONTINUITY
@ eSTALL_AFTER_DISCONTINUITY
Definition: priv_aamp.h:179
StreamAbstractionAAMP::GetAudioBitrates
virtual std::vector< long > GetAudioBitrates(void)=0
Get available audio bitrates.
eAAMPSTATUS_MANIFEST_CONTENT_ERROR
@ eAAMPSTATUS_MANIFEST_CONTENT_ERROR
Definition: priv_aamp.h:214
ContentType_OTT
@ ContentType_OTT
Definition: AampProfiler.h:112
PrivateInstanceAAMP::SetAlternateContents
void SetAlternateContents(const std::string &adBreakId, const std::string &adId, const std::string &url)
Setting the alternate contents' (Ads/blackouts) URL.
Definition: priv_aamp.cpp:8868
eMEDIATYPE_LICENCE
@ eMEDIATYPE_LICENCE
Definition: AampMediaType.h:44
PrivateInstanceAAMP::GetAvailableTextTracks
std::string GetAvailableTextTracks(bool alltrack=false)
Get available text tracks.
Definition: priv_aamp.cpp:9676
PrivateInstanceAAMP::SetAudTimeScale
void SetAudTimeScale(uint32_t audTimeScale)
Sets Low Audio TimeScale.
Definition: priv_aamp.cpp:11612
eMEDIATYPE_SUBTITLE
@ eMEDIATYPE_SUBTITLE
Definition: AampMediaType.h:41
PrivateInstanceAAMP::GetTextTrack
int GetTextTrack()
Get current text track index.
Definition: priv_aamp.cpp:10362
PROFILE_BUCKET_LA_TOTAL
@ PROFILE_BUCKET_LA_TOTAL
Definition: AampProfiler.h:67
AAMP_TUNE_INIT_FAILED_MANIFEST_CONTENT_ERROR
@ AAMP_TUNE_INIT_FAILED_MANIFEST_CONTENT_ERROR
Definition: AampEvent.h:112
PrivateInstanceAAMP::GetPositionSeconds
double GetPositionSeconds(void)
Definition: priv_aamp.h:1607
AampEventManager::RemoveEventListener
void RemoveEventListener(AAMPEventType eventType, EventListener *eventListener)
RemoveEventListener - Remove one listener registration for one event.
Definition: AampEventManager.cpp:179
PrivateInstanceAAMP::SetLowLatencyServiceConfigured
void SetLowLatencyServiceConfigured(bool bConfig)
Set Low Latency Service Configuration Status.
Definition: priv_aamp.cpp:11663
eTUNETYPE_NEW_NORMAL
@ eTUNETYPE_NEW_NORMAL
Definition: priv_aamp.h:192
Accessibility
Data type to store Accessibility Node data.
Definition: Accessibility.hpp:29
PrivateInstanceAAMP::SendDRMMetaData
void SendDRMMetaData(DrmMetaDataEventPtr e)
Send DRM metadata event.
Definition: priv_aamp.cpp:2656
eAAMPConfig_PreCachePlaylistTime
@ eAAMPConfig_PreCachePlaylistTime
Definition: AampConfig.h:242
PrivateInstanceAAMP::EnableDownloads
void EnableDownloads(void)
Enable downloads after aamp_DisableDownloads. Called after stopping fragment collector thread.
Definition: priv_aamp.cpp:6761
StreamSink::Configure
virtual void Configure(StreamOutputFormat format, StreamOutputFormat audioFormat, StreamOutputFormat auxFormat, StreamOutputFormat subFormat, bool bESChangeStatus, bool forwardAudioToAux, bool setReadyAfterPipelineCreation=false)
Configure output formats.
Definition: main_aamp.h:400
PrivateInstanceAAMP::GetPreferredTextProperties
std::string GetPreferredTextProperties()
get the current text preference set by user
Definition: priv_aamp.cpp:9384
PrivateInstanceAAMP::lastId3DataLen
int32_t lastId3DataLen[eMEDIATYPE_DEFAULT]
Definition: priv_aamp.h:1070
PrivateInstanceAAMP::GetFile
bool GetFile(std::string remoteUrl, struct GrowableBuffer *buffer, std::string &effectiveUrl, long *http_error=NULL, double *downloadTime=NULL, const char *range=NULL, unsigned int curlInstance=0, bool resetBuffer=true, MediaType fileType=eMEDIATYPE_DEFAULT, long *bitrate=NULL, int *fogError=NULL, double fragmentDurationSec=0, class CMCDHeaders *pCMCDMetrics=NULL)
Download a file from the CDN.
Definition: priv_aamp.cpp:3585
PrivateInstanceAAMP::SetLLDashServiceData
void SetLLDashServiceData(AampLLDashServiceData &stAampLLDashServiceData)
Sets Low Latency Service Data.
Definition: priv_aamp.cpp:11579
PrivateInstanceAAMP::MediaTypeString
const char * MediaTypeString(MediaType fileType)
get Media Type in string
Definition: priv_aamp.cpp:3458
StreamAbstractionAAMP::GetCurrentTextTrack
virtual bool GetCurrentTextTrack(TextTrackInfo &textTrack)
Get current text track.
Definition: streamabstraction.cpp:2996
eMEDIATYPE_TELEMETRY_MANIFEST
@ eMEDIATYPE_TELEMETRY_MANIFEST
Definition: main_aamp.h:97
eAAMPConfig_InfoLogging
@ eAAMPConfig_InfoLogging
Definition: AampConfig.h:136
AampCCManager.h
Integration layer of ClosedCaption in AAMP.
PrivateInstanceAAMP::NotifyOnEnteringLive
void NotifyOnEnteringLive()
Notify when entering live point to listeners.
Definition: priv_aamp.cpp:2910
PrivateInstanceAAMP::IsWideVineKIDWorkaround
bool IsWideVineKIDWorkaround(const std::string url)
get the SkyDE Store workaround
Definition: priv_aamp.cpp:11403
eMEDIAFORMAT_HDMI
@ eMEDIAFORMAT_HDMI
Definition: AampDrmMediaFormat.h:39
eAAMPConfig_WideVineKIDWorkaround
@ eAAMPConfig_WideVineKIDWorkaround
Definition: AampConfig.h:178
eAAMPConfig_EnableLinearSimulator
@ eAAMPConfig_EnableLinearSimulator
Definition: AampConfig.h:154
PrivateInstanceAAMP::StopTrackInjection
void StopTrackInjection(MediaType type)
Stop injection for a track. Called from StopInjection.
Definition: priv_aamp.cpp:9125
AampCCManagerBase::updateLastTextTracks
void updateLastTextTracks(const std::vector< TextTrackInfo > &newTextTracks)
update stored list of text tracks
Definition: AampCCManager.h:152
AudioTrackInfo::index
std::string index
Definition: main_aamp.h:180
MediaFormat
MediaFormat
Media format types.
Definition: AampDrmMediaFormat.h:32
AAMP_TUNE_HDCP_COMPLIANCE_ERROR
@ AAMP_TUNE_HDCP_COMPLIANCE_ERROR
Definition: AampEvent.h:143
AAMP_EVENT_HTTP_RESPONSE_HEADER
@ AAMP_EVENT_HTTP_RESPONSE_HEADER
Definition: AampEvent.h:86
eAAMPSTATUS_MANIFEST_PARSE_ERROR
@ eAAMPSTATUS_MANIFEST_PARSE_ERROR
Definition: priv_aamp.h:213
AAMPAbrInfo
ABR info structure.
Definition: AampLogManager.h:132
ANOMALY_ERROR
@ ANOMALY_ERROR
Definition: main_aamp.h:71
PrivateInstanceAAMP::GetAudioTrackInfo
std::string GetAudioTrackInfo()
Get current audio track index.
Definition: priv_aamp.cpp:9991
eSTATE_PLAYING
@ eSTATE_PLAYING
Definition: AampEvent.h:166
LangCodePreference
LangCodePreference
Language Code Preference types.
Definition: main_aamp.h:165
PrivateInstanceAAMP::mProfileCappedStatus
bool mProfileCappedStatus
Definition: priv_aamp.h:1064
PrivateInstanceAAMP::SetAppName
void SetAppName(std::string name)
Set the application name which has created PlayerInstanceAAMP, for logging purposes.
Definition: priv_aamp.cpp:9791
CurlAbortReason
CurlAbortReason
Http Header Type.
Definition: priv_aamp.h:240
PrivateInstanceAAMP::mPausePositionMilliseconds
volatile std::atomic< long long > mPausePositionMilliseconds
Definition: priv_aamp.h:952
PlaybackErrorType
PlaybackErrorType
Definition: priv_aamp.h:172
eAAMPConfig_ReportBufferEvent
@ eAAMPConfig_ReportBufferEvent
Definition: AampConfig.h:135
StreamAbstractionAAMP_HDMIIN
Fragment collector for MPEG DASH.
Definition: hdmiin_shim.h:41
AAMP_EVENT_BITRATE_CHANGED
@ AAMP_EVENT_BITRATE_CHANGED
Definition: AampEvent.h:57
PrivateInstanceAAMP::mAbsoluteEndPosition
double mAbsoluteEndPosition
Definition: priv_aamp.h:1066
ContentGapInfo
Class for Content gap information.
Definition: priv_aamp.h:412
eAAMPConfig_UseAbsoluteTimeline
@ eAAMPConfig_UseAbsoluteTimeline
Definition: AampConfig.h:176
rmf_shim.h
shim for dispatching UVE RMF playback
eAAMPConfig_EnableSlowMotion
@ eAAMPConfig_EnableSlowMotion
Definition: AampConfig.h:204
StreamAbstractionAAMP::GetThumbnailRangeData
virtual std::vector< ThumbnailData > GetThumbnailRangeData(double, double, std::string *, int *, int *, int *, int *)=0
Get thumbnail data for duration value.
eSTATE_COMPLETE
@ eSTATE_COMPLETE
Definition: AampEvent.h:169
eAAMPConfig_InitFragmentRetryCount
@ eAAMPConfig_InitFragmentRetryCount
Definition: AampConfig.h:238
ContentType_PPV
@ ContentType_PPV
Definition: AampProfiler.h:111
eLOGLEVEL_FATAL
@ eLOGLEVEL_FATAL
Definition: AampLogManager.h:103
PROFILE_BUCKET_PLAYER_PRE_BUFFERED
@ PROFILE_BUCKET_PLAYER_PRE_BUFFERED
Definition: AampProfiler.h:74
PrivateInstanceAAMP::ResumeTrackDownloads
void ResumeTrackDownloads(MediaType type)
Resume downloads for a track. Called from StreamSink to control flow.
Definition: priv_aamp.cpp:3202
eMEDIAFORMAT_RMF
@ eMEDIAFORMAT_RMF
Definition: AampDrmMediaFormat.h:42
eMEDIAFORMAT_UNKNOWN
@ eMEDIAFORMAT_UNKNOWN
Definition: AampDrmMediaFormat.h:43
AAMP_EVENT_AD_PLACEMENT_ERROR
@ AAMP_EVENT_AD_PLACEMENT_ERROR
Definition: AampEvent.h:79
PrivateInstanceAAMP::SendMessageOverPipe
void SendMessageOverPipe(const char *str, int nToWrite)
Send messages to Receiver over PIPE.
Definition: priv_aamp.cpp:4828
ePAUSED_BEHAVIOR_AUTOPLAY_IMMEDIATE
@ ePAUSED_BEHAVIOR_AUTOPLAY_IMMEDIATE
Definition: AampDefine.h:197
AAMP_TUNE_DRM_UNSUPPORTED
@ AAMP_TUNE_DRM_UNSUPPORTED
Definition: AampEvent.h:136
eGST_ERROR_VIDEO_BUFFERING
@ eGST_ERROR_VIDEO_BUFFERING
Definition: priv_aamp.h:176
PrivateInstanceAAMP::SendBufferChangeEvent
void SendBufferChangeEvent(bool bufferingStopped=false)
Sends UnderFlow Event messages.
Definition: priv_aamp.cpp:2424
ANOMALY_WARNING
@ ANOMALY_WARNING
Definition: main_aamp.h:72
PrivateInstanceAAMP::rate
float rate
Definition: priv_aamp.h:955
PrivateInstanceAAMP::LoadFragment
char * LoadFragment(ProfilerBucketType bucketType, std::string fragmentUrl, std::string &effectiveUrl, size_t *len, unsigned int curlInstance=0, const char *range=NULL, long *http_code=NULL, double *downloadTime=NULL, MediaType fileType=eMEDIATYPE_MANIFEST, int *fogError=NULL)
Fetch a file from CDN and update profiler.
Definition: priv_aamp.cpp:6345
eLOGLEVEL_INFO
@ eLOGLEVEL_INFO
Definition: AampLogManager.h:100
StreamAbstractionAAMP::SetPreferredAudioLanguages
virtual void SetPreferredAudioLanguages()
SetPreferredAudioLanguages set the preferred audio languages and rendition. [currently for OTA].
Definition: StreamAbstractionAAMP.h:1253
PrivateInstanceAAMP::mJumpToLiveFromPause
bool mJumpToLiveFromPause
Definition: priv_aamp.h:1060
eAAMPConfig_PTSErrorThreshold
@ eAAMPConfig_PTSErrorThreshold
Definition: AampConfig.h:229
PrivateInstanceAAMP::UpdateVideoRectangle
void UpdateVideoRectangle(int x, int y, int w, int h)
Set video rectangle.
Definition: priv_aamp.cpp:6654
PrivateInstanceAAMP::SetIsLive
void SetIsLive(bool isLive)
Set is Live flag.
Definition: priv_aamp.h:2735
PrivateInstanceAAMP::mMutexPlaystart
pthread_mutex_t mMutexPlaystart
Definition: priv_aamp.h:1000
PrivateInstanceAAMP::NotifyBitRateChangeEvent
void NotifyBitRateChangeEvent(int bitrate, BitrateChangeReason reason, int width, int height, double framerate, double position, bool GetBWIndex=false, VideoScanType scantype=eVIDEOSCAN_UNKNOWN, int aspectRatioWidth=0, int aspectRatioHeight=0)
Notify bit rate change event to listeners.
Definition: priv_aamp.cpp:2538
StreamAbstractionAAMP::hasDrm
bool hasDrm
Definition: StreamAbstractionAAMP.h:922
eAAMPConfig_CustomHeader
@ eAAMPConfig_CustomHeader
Definition: AampConfig.h:304
eCURLINSTANCE_MANIFEST_PLAYLIST
@ eCURLINSTANCE_MANIFEST_PLAYLIST
Definition: priv_aamp.h:162
eSTATE_SEEKING
@ eSTATE_SEEKING
Definition: AampEvent.h:165
PrivateInstanceAAMP::SetStateBufferingIfRequired
bool SetStateBufferingIfRequired()
Set eSTATE_BUFFERING if required.
Definition: priv_aamp.cpp:9889
PrivateInstanceAAMP::mDrmDecryptFailCount
int mDrmDecryptFailCount
Definition: priv_aamp.h:1026
PrivateInstanceAAMP::UpdateLiveOffset
void UpdateLiveOffset()
UpdateLiveOffset live offset [Sec].
Definition: priv_aamp.cpp:8419
eAAMPConfig_PRLicenseServerUrl
@ eAAMPConfig_PRLicenseServerUrl
Definition: AampConfig.h:299
ForceHttpCoversionforFog
void ForceHttpCoversionforFog(std::string &url, const std::string &from, const std::string &to)
convert https to https in recordedUrl part of manifestUrl
Definition: priv_aamp.cpp:621
eAAMPConfig_MidFragmentSeek
@ eAAMPConfig_MidFragmentSeek
Definition: AampConfig.h:151
PrivateInstanceAAMP::mSessionToken
std::string mSessionToken
Definition: priv_aamp.h:1052
AAMP_TUNE_CORRUPT_DRM_DATA
@ AAMP_TUNE_CORRUPT_DRM_DATA
Definition: AampEvent.h:133
StreamAbstractionAAMP::DisableContentRestrictions
virtual void DisableContentRestrictions(long grace, long time, bool eventChange)
Disable Content Restrictions - unlock.
Definition: StreamAbstractionAAMP.h:1285
PrivateInstanceAAMP::mEventLock
pthread_mutex_t mEventLock
Definition: priv_aamp.h:4065
PrivateInstanceAAMP::ResumeDownloads
void ResumeDownloads()
Resume downloads of all tracks. Used by aamp internally to manage states.
Definition: priv_aamp.cpp:3163
isobmffprocessor.h
Header file for ISO Base Media File Format Fragment Processor.
eAAMPConfig_HarvestPath
@ eAAMPConfig_HarvestPath
Definition: AampConfig.h:296
PrivateInstanceAAMP::PreCachePlaylistDownloadTask
void PreCachePlaylistDownloadTask()
PreCachePlaylistDownloadTask Thread function for PreCaching Playlist.
Definition: priv_aamp.cpp:9293
PrivateInstanceAAMP::mAampLLDashServiceData
AampLLDashServiceData mAampLLDashServiceData
Definition: priv_aamp.h:4072
eAAMPConfig_PreferredAudioCodec
@ eAAMPConfig_PreferredAudioCodec
Definition: AampConfig.h:312
AudioTrackInfo::accessibilityType
std::string accessibilityType
Definition: main_aamp.h:192
AampJsonObject
Utility class to construct a JSON string.
Definition: AampJsonObject.h:37
eAAMPConfig_RepairIframes
@ eAAMPConfig_RepairIframes
Definition: AampConfig.h:179
PrivateInstanceAAMP::detach
void detach()
Soft stop the player instance.
Definition: priv_aamp.cpp:6248
PrivateInstanceAAMP::mAudioOnlyPb
bool mAudioOnlyPb
Definition: priv_aamp.h:1102
PrivateInstanceAAMP::AddEventListener
void AddEventListener(AAMPEventType eventType, EventListener *eventListener)
Add listener to aamp events.
Definition: priv_aamp.cpp:2244
AampLogManager::setLogLevel
void setLogLevel(AAMP_LogLevel newLevel)
Set the log level for print mechanism.
Definition: aamplogging.cpp:58
PrivateInstanceAAMP::mCurrentTextTrackIndex
int mCurrentTextTrackIndex
Definition: priv_aamp.h:1105
SyncTime_write_callback
static size_t SyncTime_write_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
write callback to be used by CURL
Definition: priv_aamp.cpp:755
PrivateInstanceAAMP::ProcessPendingDiscontinuity
bool ProcessPendingDiscontinuity()
Process pending discontinuity and continue playback of stream after discontinuity.
Definition: priv_aamp.cpp:2677
PROFILE_BUCKET_FRAGMENT_AUXILIARY
@ PROFILE_BUCKET_FRAGMENT_AUXILIARY
Definition: AampProfiler.h:60
PrivateInstanceAAMP::IsNewTune
bool IsNewTune()
IsNewTune Function to check if tune is New tune or retune.
Definition: priv_aamp.h:2788
eAAMPConfig_PreferredDRM
@ eAAMPConfig_PreferredDRM
Definition: AampConfig.h:223