9bd8fee92f
Upgrade Video.js core to v7.18.0 from v5.10.7 Upgrade Dash.js to v4.2.8 from v2.6.3 Upgrade videojs-contrib-dash to v5.1.1 from v2.9.1 Modify videojs-resolution-switcher
1 line
3.1 MiB
1 line
3.1 MiB
{"version":3,"sources":["webpack://dashjs/webpack/universalModuleDefinition","webpack://dashjs/webpack/bootstrap","webpack://dashjs/./src/dash/constants/DashConstants.js","webpack://dashjs/./src/streaming/constants/Constants.js","webpack://dashjs/./src/core/events/Events.js","webpack://dashjs/./src/core/events/CoreEvents.js","webpack://dashjs/./src/core/FactoryMaker.js","webpack://dashjs/./src/streaming/MediaPlayerEvents.js","webpack://dashjs/./src/streaming/vo/metrics/HTTPRequest.js","webpack://dashjs/./src/core/Debug.js","webpack://dashjs/./src/core/EventBus.js","webpack://dashjs/./src/streaming/vo/DashJSError.js","webpack://dashjs/./src/core/errors/Errors.js","webpack://dashjs/./src/dash/utils/SegmentsUtils.js","webpack://dashjs/./src/streaming/utils/DefaultURLUtils.js","webpack://dashjs/./src/streaming/utils/URLUtils.js","webpack://dashjs/./src/streaming/vo/FragmentRequest.js","webpack://dashjs/./src/streaming/utils/SupervisorTools.js","webpack://dashjs/./src/core/Utils.js","webpack://dashjs/./src/core/Settings.js","webpack://dashjs/./src/streaming/metrics/MetricsReportingEvents.js","webpack://dashjs/./src/core/events/EventsBase.js","webpack://dashjs/./src/streaming/models/FragmentModel.js","webpack://dashjs/./src/streaming/net/URLLoader.js","webpack://dashjs/./src/streaming/vo/IsoBox.js","webpack://dashjs/./src/streaming/utils/IsoFile.js","webpack://dashjs/./src/streaming/vo/IsoBoxSearchInfo.js","webpack://dashjs/./src/streaming/utils/BoxParser.js","webpack://dashjs/(webpack)/buildin/global.js","webpack://dashjs/./node_modules/codem-isoboxer/dist/iso_boxer.js","webpack://dashjs/./src/streaming/utils/RequestModifier.js","webpack://dashjs/./src/core/errors/ErrorsBase.js","webpack://dashjs/./src/streaming/net/XHRLoader.js","webpack://dashjs/./node_modules/process/browser.js","webpack://dashjs/./src/dash/vo/Segment.js","webpack://dashjs/./src/dash/vo/Representation.js","webpack://dashjs/./src/dash/vo/AdaptationSet.js","webpack://dashjs/./src/dash/vo/Period.js","webpack://dashjs/./src/dash/vo/Mpd.js","webpack://dashjs/./src/dash/vo/EventStream.js","webpack://dashjs/./src/dash/models/DashManifestModel.js","webpack://dashjs/./src/streaming/vo/ThumbnailTrackInfo.js","webpack://dashjs/./src/streaming/thumbnail/ThumbnailTracks.js","webpack://dashjs/./node_modules/readable-stream/lib/_stream_duplex.js","webpack://dashjs/./src/dash/DashHandler.js","webpack://dashjs/./src/dash/utils/TimelineSegmentsGetter.js","webpack://dashjs/./src/dash/utils/TemplateSegmentsGetter.js","webpack://dashjs/./src/dash/utils/ListSegmentsGetter.js","webpack://dashjs/./src/dash/utils/SegmentBaseGetter.js","webpack://dashjs/./src/dash/controllers/SegmentsController.js","webpack://dashjs/./src/dash/vo/BaseURL.js","webpack://dashjs/./node_modules/inherits/inherits_browser.js","webpack://dashjs/./externals/cea608-parser.js","webpack://dashjs/./src/streaming/models/CmcdModel.js","webpack://dashjs/./src/dash/vo/UTCTiming.js","webpack://dashjs/./src/dash/vo/Event.js","webpack://dashjs/./src/streaming/utils/ObjectUtils.js","webpack://dashjs/./externals/xml2json.js","webpack://dashjs/./src/streaming/net/FetchLoader.js","webpack://dashjs/./src/streaming/models/LowLatencyThroughputModel.js","webpack://dashjs/./src/streaming/net/HTTPLoader.js","webpack://dashjs/./src/streaming/net/SchemeLoaderFactory.js","webpack://dashjs/./node_modules/core-util-is/lib/util.js","webpack://dashjs/./node_modules/path-browserify/index.js","webpack://dashjs/./node_modules/imsc/src/main/js/main.js","webpack://dashjs/./src/streaming/utils/CustomTimeRanges.js","webpack://dashjs/./src/streaming/utils/Capabilities.js","webpack://dashjs/./node_modules/imsc/src/main/js/names.js","webpack://dashjs/./node_modules/process-nextick-args/index.js","webpack://dashjs/./node_modules/safe-buffer/index.js","webpack://dashjs/./src/streaming/constants/MetricsConstants.js","webpack://dashjs/./src/streaming/controllers/PlaybackController.js","webpack://dashjs/./src/streaming/SourceBufferSink.js","webpack://dashjs/./src/streaming/utils/InitCache.js","webpack://dashjs/./src/streaming/controllers/BufferController.js","webpack://dashjs/./src/streaming/text/NotFragmentedTextBufferController.js","webpack://dashjs/./src/streaming/controllers/ScheduleController.js","webpack://dashjs/./src/streaming/vo/metrics/PlayList.js","webpack://dashjs/./src/streaming/StreamProcessor.js","webpack://dashjs/./src/streaming/controllers/FragmentController.js","webpack://dashjs/./src/streaming/vo/Thumbnail.js","webpack://dashjs/./src/streaming/vo/BitrateInfo.js","webpack://dashjs/./src/streaming/thumbnail/ThumbnailController.js","webpack://dashjs/./src/streaming/controllers/BlacklistController.js","webpack://dashjs/./src/streaming/Stream.js","webpack://dashjs/./src/streaming/ManifestUpdater.js","webpack://dashjs/./src/streaming/controllers/TimeSyncController.js","webpack://dashjs/./src/streaming/controllers/MediaSourceController.js","webpack://dashjs/./src/streaming/controllers/EventController.js","webpack://dashjs/./src/streaming/constants/ConformanceViolationConstants.js","webpack://dashjs/./src/streaming/controllers/StreamController.js","webpack://dashjs/./src/streaming/controllers/GapController.js","webpack://dashjs/./src/streaming/controllers/MediaController.js","webpack://dashjs/./src/streaming/models/BaseURLTreeModel.js","webpack://dashjs/./src/streaming/utils/baseUrlResolution/DVBSelector.js","webpack://dashjs/./src/streaming/utils/baseUrlResolution/BasicSelector.js","webpack://dashjs/./src/streaming/utils/BaseURLSelector.js","webpack://dashjs/./src/streaming/controllers/BaseURLController.js","webpack://dashjs/./src/streaming/vo/TextRequest.js","webpack://dashjs/./src/streaming/XlinkLoader.js","webpack://dashjs/./src/streaming/controllers/XlinkController.js","webpack://dashjs/./src/streaming/ManifestLoader.js","webpack://dashjs/./src/streaming/utils/ErrorHandler.js","webpack://dashjs/./src/streaming/utils/CapabilitiesFilter.js","webpack://dashjs/./src/streaming/vo/URIFragmentData.js","webpack://dashjs/./src/streaming/models/URIFragmentModel.js","webpack://dashjs/./src/streaming/models/ManifestModel.js","webpack://dashjs/./src/streaming/rules/SwitchRequest.js","webpack://dashjs/./src/streaming/rules/abr/ThroughputRule.js","webpack://dashjs/./src/streaming/rules/abr/InsufficientBufferRule.js","webpack://dashjs/./src/streaming/rules/abr/AbandonRequestsRule.js","webpack://dashjs/./src/streaming/rules/abr/DroppedFramesRule.js","webpack://dashjs/./src/streaming/rules/abr/SwitchHistoryRule.js","webpack://dashjs/./src/streaming/rules/abr/BolaRule.js","webpack://dashjs/./src/streaming/rules/abr/L2ARule.js","webpack://dashjs/./src/streaming/rules/abr/lolp/LearningAbrController.js","webpack://dashjs/./src/streaming/rules/abr/lolp/QoeInfo.js","webpack://dashjs/./src/streaming/rules/abr/lolp/LoLpQoEEvaluator.js","webpack://dashjs/./src/streaming/rules/abr/lolp/LoLpWeightSelector.js","webpack://dashjs/./src/streaming/rules/abr/lolp/LoLpRule.js","webpack://dashjs/./src/streaming/rules/abr/ABRRulesCollection.js","webpack://dashjs/./src/streaming/models/MediaPlayerModel.js","webpack://dashjs/./src/streaming/rules/RulesContext.js","webpack://dashjs/./src/streaming/rules/SwitchRequestHistory.js","webpack://dashjs/./src/streaming/rules/DroppedFramesHistory.js","webpack://dashjs/./src/streaming/rules/ThroughputHistory.js","webpack://dashjs/./src/streaming/controllers/AbrController.js","webpack://dashjs/./src/streaming/models/VideoModel.js","webpack://dashjs/./src/streaming/utils/DOMStorage.js","webpack://dashjs/./src/dash/SegmentBaseLoader.js","webpack://dashjs/./src/streaming/utils/EBMLParser.js","webpack://dashjs/./src/dash/WebmSegmentBaseLoader.js","webpack://dashjs/./src/dash/controllers/SegmentBaseController.js","webpack://dashjs/./src/dash/vo/RepresentationInfo.js","webpack://dashjs/./src/dash/vo/MediaInfo.js","webpack://dashjs/./src/dash/vo/StreamInfo.js","webpack://dashjs/./src/dash/vo/ManifestInfo.js","webpack://dashjs/./src/dash/vo/SimpleXPath.js","webpack://dashjs/./src/dash/vo/PatchOperation.js","webpack://dashjs/./src/dash/models/PatchManifestModel.js","webpack://dashjs/./src/dash/DashAdapter.js","webpack://dashjs/./src/dash/utils/Round10.js","webpack://dashjs/./src/streaming/vo/MetricsList.js","webpack://dashjs/./src/streaming/vo/metrics/RepresentationSwitch.js","webpack://dashjs/./src/streaming/vo/metrics/BufferLevel.js","webpack://dashjs/./src/streaming/vo/metrics/BufferState.js","webpack://dashjs/./src/streaming/vo/metrics/DVRInfo.js","webpack://dashjs/./src/streaming/vo/metrics/DroppedFrames.js","webpack://dashjs/./src/streaming/vo/metrics/ManifestUpdate.js","webpack://dashjs/./src/streaming/vo/metrics/SchedulingInfo.js","webpack://dashjs/./src/streaming/vo/metrics/RequestsQueue.js","webpack://dashjs/./src/streaming/models/MetricsModel.js","webpack://dashjs/./src/dash/DashMetrics.js","webpack://dashjs/./src/dash/utils/TimelineConverter.js","webpack://dashjs/./src/streaming/vo/TextTrackInfo.js","webpack://dashjs/./src/streaming/text/EmbeddedTextHtmlRender.js","webpack://dashjs/./src/streaming/text/TextSourceBuffer.js","webpack://dashjs/./src/streaming/text/TextTracks.js","webpack://dashjs/./src/streaming/utils/VTTParser.js","webpack://dashjs/./src/streaming/utils/TTMLParser.js","webpack://dashjs/./src/streaming/text/TextController.js","webpack://dashjs/./src/streaming/MediaPlayer.js","webpack://dashjs/./src/core/Version.js","webpack://dashjs/./externals/base64.js","webpack://dashjs/./src/dash/controllers/RepresentationController.js","webpack://dashjs/./src/streaming/vo/DataChunk.js","webpack://dashjs/./node_modules/fast-deep-equal/index.js","webpack://dashjs/./src/dash/parser/objectiron.js","webpack://dashjs/./src/dash/parser/matchers/BaseMatcher.js","webpack://dashjs/./src/dash/parser/matchers/StringMatcher.js","webpack://dashjs/./src/dash/parser/matchers/DurationMatcher.js","webpack://dashjs/./src/dash/parser/matchers/DateTimeMatcher.js","webpack://dashjs/./src/dash/parser/matchers/NumericMatcher.js","webpack://dashjs/./src/dash/parser/maps/CommonProperty.js","webpack://dashjs/./src/dash/parser/maps/MapNode.js","webpack://dashjs/./src/dash/parser/maps/RepresentationBaseValuesMap.js","webpack://dashjs/./src/dash/parser/maps/SegmentValuesMap.js","webpack://dashjs/./src/dash/parser/DashParser.js","webpack://dashjs/./src/streaming/vo/HeadRequest.js","webpack://dashjs/./src/streaming/FragmentLoader.js","webpack://dashjs/./node_modules/imsc/src/main/js/styles.js","webpack://dashjs/./node_modules/node-libs-browser/node_modules/buffer/index.js","webpack://dashjs/./node_modules/node-libs-browser/node_modules/events/events.js","webpack://dashjs/./node_modules/readable-stream/readable-browser.js","webpack://dashjs/./node_modules/readable-stream/lib/_stream_writable.js","webpack://dashjs/./node_modules/string_decoder/lib/string_decoder.js","webpack://dashjs/./node_modules/imsc/src/main/js/utils.js","webpack://dashjs/./node_modules/isarray/index.js","webpack://dashjs/./node_modules/readable-stream/lib/_stream_readable.js","webpack://dashjs/./node_modules/readable-stream/lib/internal/streams/stream-browser.js","webpack://dashjs/./node_modules/readable-stream/lib/internal/streams/destroy.js","webpack://dashjs/./node_modules/readable-stream/lib/_stream_transform.js","webpack://dashjs/./src/streaming/protection/CommonEncryption.js","webpack://dashjs/./src/streaming/protection/vo/MediaCapability.js","webpack://dashjs/./src/streaming/protection/vo/KeySystemConfiguration.js","webpack://dashjs/./src/streaming/protection/errors/ProtectionErrors.js","webpack://dashjs/./src/streaming/protection/vo/LicenseRequest.js","webpack://dashjs/./src/streaming/protection/vo/LicenseResponse.js","webpack://dashjs/./src/streaming/protection/controllers/ProtectionController.js","webpack://dashjs/./src/streaming/protection/vo/KeyPair.js","webpack://dashjs/./src/streaming/protection/vo/ClearKeyKeySet.js","webpack://dashjs/./src/streaming/constants/ProtectionConstants.js","webpack://dashjs/./src/streaming/protection/drm/KeySystemClearKey.js","webpack://dashjs/./src/streaming/protection/drm/KeySystemW3CClearKey.js","webpack://dashjs/./src/streaming/protection/drm/KeySystemWidevine.js","webpack://dashjs/./src/streaming/protection/drm/KeySystemPlayReady.js","webpack://dashjs/./src/streaming/protection/servers/DRMToday.js","webpack://dashjs/./src/streaming/protection/servers/PlayReady.js","webpack://dashjs/./src/streaming/protection/servers/Widevine.js","webpack://dashjs/./src/streaming/protection/servers/ClearKey.js","webpack://dashjs/./src/streaming/protection/controllers/ProtectionKeyController.js","webpack://dashjs/./src/streaming/protection/ProtectionEvents.js","webpack://dashjs/./src/streaming/protection/vo/NeedKey.js","webpack://dashjs/./src/streaming/protection/vo/KeyMessage.js","webpack://dashjs/./src/streaming/protection/vo/KeySystemAccess.js","webpack://dashjs/./src/streaming/protection/models/ProtectionModel_21Jan2015.js","webpack://dashjs/./src/streaming/protection/models/ProtectionModel_3Feb2014.js","webpack://dashjs/./src/streaming/protection/models/ProtectionModel_01b.js","webpack://dashjs/./src/streaming/protection/Protection.js","webpack://dashjs/./src/streaming/metrics/vo/DVBErrors.js","webpack://dashjs/./src/streaming/metrics/utils/DVBErrorsTranslator.js","webpack://dashjs/./src/streaming/metrics/controllers/RangeController.js","webpack://dashjs/./src/streaming/metrics/utils/MetricSerialiser.js","webpack://dashjs/./src/streaming/metrics/utils/RNG.js","webpack://dashjs/./src/streaming/metrics/reporting/reporters/DVBReporting.js","webpack://dashjs/./src/streaming/metrics/reporting/ReportingFactory.js","webpack://dashjs/./src/streaming/metrics/controllers/ReportingController.js","webpack://dashjs/./src/streaming/metrics/utils/HandlerHelpers.js","webpack://dashjs/./src/streaming/metrics/metrics/handlers/BufferLevelHandler.js","webpack://dashjs/./src/streaming/metrics/metrics/handlers/DVBErrorsHandler.js","webpack://dashjs/./src/streaming/metrics/metrics/handlers/HttpListHandler.js","webpack://dashjs/./src/streaming/metrics/metrics/handlers/GenericMetricHandler.js","webpack://dashjs/./src/streaming/metrics/metrics/MetricsHandlerFactory.js","webpack://dashjs/./src/streaming/metrics/controllers/MetricsHandlersController.js","webpack://dashjs/./src/streaming/metrics/controllers/MetricsController.js","webpack://dashjs/./src/streaming/metrics/vo/Metrics.js","webpack://dashjs/./src/streaming/metrics/vo/Range.js","webpack://dashjs/./src/streaming/metrics/vo/Reporting.js","webpack://dashjs/./src/streaming/metrics/utils/ManifestParsing.js","webpack://dashjs/./src/streaming/metrics/controllers/MetricsCollectionController.js","webpack://dashjs/./src/streaming/metrics/MetricsReporting.js","webpack://dashjs/./index_mediaplayerOnly.js","webpack://dashjs/./node_modules/imsc/src/main/js/isd.js","webpack://dashjs/./node_modules/imsc/src/main/js/doc.js","webpack://dashjs/./node_modules/sax/lib/sax.js","webpack://dashjs/./node_modules/base64-js/index.js","webpack://dashjs/./node_modules/ieee754/index.js","webpack://dashjs/./node_modules/stream-browserify/index.js","webpack://dashjs/./node_modules/readable-stream/lib/internal/streams/BufferList.js","webpack://dashjs/./node_modules/node-libs-browser/node_modules/timers-browserify/main.js","webpack://dashjs/./node_modules/setimmediate/setImmediate.js","webpack://dashjs/./node_modules/util-deprecate/browser.js","webpack://dashjs/./node_modules/readable-stream/lib/_stream_passthrough.js","webpack://dashjs/./node_modules/readable-stream/writable-browser.js","webpack://dashjs/./node_modules/readable-stream/duplex-browser.js","webpack://dashjs/./node_modules/readable-stream/transform.js","webpack://dashjs/./node_modules/readable-stream/passthrough.js","webpack://dashjs/./node_modules/imsc/src/main/js/html.js","webpack://dashjs/./node_modules/es6-promise/auto.js","webpack://dashjs/./node_modules/es6-promise/dist/es6-promise.js","webpack://dashjs/./src/streaming/MediaPlayerFactory.js","webpack://dashjs/./index.js"],"names":["root","factory","exports","module","define","amd","window","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","constants","this","init","BASE_URL","SEGMENT_BASE","SEGMENT_TEMPLATE","SEGMENT_LIST","SEGMENT_URL","SEGMENT_TIMELINE","SEGMENT_PROFILES","ADAPTATION_SET","REPRESENTATION","REPRESENTATION_INDEX","SUB_REPRESENTATION","INITIALIZATION","INITIALIZATION_MINUS","MPD","PERIOD","ASSET_IDENTIFIER","EVENT_STREAM","ID","PROFILES","SERVICE_LOCATION","RANGE","INDEX","MEDIA","BYTE_RANGE","INDEX_RANGE","MEDIA_RANGE","VALUE","CONTENT_TYPE","MIME_TYPE","BITSTREAM_SWITCHING","BITSTREAM_SWITCHING_MINUS","CODECS","DEPENDENCY_ID","MEDIA_STREAM_STRUCTURE_ID","METRICS","METRICS_MINUS","REPORTING","WIDTH","HEIGHT","SAR","FRAMERATE","AUDIO_SAMPLING_RATE","MAXIMUM_SAP_PERIOD","START_WITH_SAP","MAX_PLAYOUT_RATE","CODING_DEPENDENCY","SCAN_TYPE","FRAME_PACKING","AUDIO_CHANNEL_CONFIGURATION","CONTENT_PROTECTION","ESSENTIAL_PROPERTY","SUPPLEMENTAL_PROPERTY","INBAND_EVENT_STREAM","ACCESSIBILITY","ROLE","RATING","CONTENT_COMPONENT","SUBSET","LANG","VIEWPOINT","ROLE_ASARRAY","ACCESSIBILITY_ASARRAY","AUDIOCHANNELCONFIGURATION_ASARRAY","CONTENTPROTECTION_ASARRAY","MAIN","DYNAMIC","STATIC","MEDIA_PRESENTATION_DURATION","MINIMUM_UPDATE_PERIOD","CODEC_PRIVATE_DATA","BANDWITH","SOURCE_URL","TIMESCALE","DURATION","START_NUMBER","PRESENTATION_TIME_OFFSET","AVAILABILITY_START_TIME","AVAILABILITY_END_TIME","TIMESHIFT_BUFFER_DEPTH","MAX_SEGMENT_DURATION","PRESENTATION_TIME","MIN_BUFFER_TIME","MAX_SUBSEGMENT_DURATION","START","AVAILABILITY_TIME_OFFSET","AVAILABILITY_TIME_COMPLETE","CENC_DEFAULT_KID","DVB_PRIORITY","DVB_WEIGHT","SUGGESTED_PRESENTATION_DELAY","SERVICE_DESCRIPTION","SERVICE_DESCRIPTION_SCOPE","SERVICE_DESCRIPTION_LATENCY","SERVICE_DESCRIPTION_PLAYBACK_RATE","PATCH_LOCATION","PUBLISH_TIME","ORIGINAL_PUBLISH_TIME","ORIGINAL_MPD_ID","STREAM","VIDEO","AUDIO","TEXT","MUXED","IMAGE","STPP","TTML","VTT","WVTT","ABR_STRATEGY_DYNAMIC","ABR_STRATEGY_BOLA","ABR_STRATEGY_L2A","ABR_STRATEGY_LoLP","ABR_STRATEGY_THROUGHPUT","ABR_FETCH_THROUGHPUT_CALCULATION_DOWNLOADED_DATA","ABR_FETCH_THROUGHPUT_CALCULATION_MOOF_PARSING","ABR_FETCH_THROUGHPUT_CALCULATION_AAST","LIVE_CATCHUP_MODE_DEFAULT","LIVE_CATCHUP_MODE_LOLP","MOVING_AVERAGE_SLIDING_WINDOW","MOVING_AVERAGE_EWMA","BAD_ARGUMENT_ERROR","MISSING_CONFIG_ERROR","TRACK_SWITCH_MODE_ALWAYS_REPLACE","TRACK_SWITCH_MODE_NEVER_REPLACE","TRACK_SELECTION_MODE_FIRST_TRACK","TRACK_SELECTION_MODE_HIGHEST_BITRATE","TRACK_SELECTION_MODE_HIGHEST_EFFICIENCY","TRACK_SELECTION_MODE_WIDEST_RANGE","TRACK_SELECTION_MODE_HIGHEST_SELECTION_PRIORITY","CMCD_MODE_QUERY","CMCD_MODE_HEADER","LOCATION","INITIALIZE","TEXT_SHOWING","TEXT_HIDDEN","CC1","CC3","UTF8","SCHEME_ID_URI","START_TIME","SERVICE_DESCRIPTION_LL_SCHEME","SUPPLEMENTAL_PROPERTY_LL_SCHEME","XML","ARRAY_BUFFER","DVB_REPORTING_URL","DVB_PROBABILITY","VIDEO_ELEMENT_READY_STATES","HAVE_NOTHING","HAVE_METADATA","HAVE_CURRENT_DATA","HAVE_FUTURE_DATA","HAVE_ENOUGH_DATA","events","ATTEMPT_BACKGROUND_SYNC","BUFFERING_COMPLETED","BUFFER_CLEARED","BYTES_APPENDED_END_FRAGMENT","BUFFER_REPLACEMENT_STARTED","CHECK_FOR_EXISTENCE_COMPLETED","CURRENT_TRACK_CHANGED","DATA_UPDATE_COMPLETED","INBAND_EVENTS","INITIAL_STREAM_SWITCH","INIT_FRAGMENT_LOADED","INIT_FRAGMENT_NEEDED","INTERNAL_MANIFEST_LOADED","ORIGINAL_MANIFEST_LOADED","LOADING_COMPLETED","LOADING_PROGRESS","LOADING_DATA_PROGRESS","LOADING_ABANDONED","MANIFEST_UPDATED","MEDIA_FRAGMENT_LOADED","MEDIA_FRAGMENT_NEEDED","QUOTA_EXCEEDED","SEGMENT_LOCATION_BLACKLIST_ADD","SEGMENT_LOCATION_BLACKLIST_CHANGED","SERVICE_LOCATION_BLACKLIST_ADD","SERVICE_LOCATION_BLACKLIST_CHANGED","SET_FRAGMENTED_TEXT_AFTER_DISABLED","SET_NON_FRAGMENTED_TEXT","SOURCE_BUFFER_ERROR","STREAMS_COMPOSED","STREAM_BUFFERING_COMPLETED","STREAM_REQUESTING_COMPLETED","TEXT_TRACKS_QUEUE_INITIALIZED","TIME_SYNCHRONIZATION_COMPLETED","UPDATE_TIME_SYNC_OFFSET","URL_RESOLUTION_FAILED","VIDEO_CHUNK_RECEIVED","WALLCLOCK_TIME_UPDATED","XLINK_ELEMENT_LOADED","XLINK_READY","SEEK_TARGET","EventsBase","FactoryMaker","instance","singletonContexts","singletonFactories","classFactories","getSingletonInstance","context","className","obj","getFactoryByName","factoriesArray","updateFactory","merge","classConstructor","args","classInstance","__dashjs_factory_name","extensionObject","extension","override","apply","prop","parent","getClassName","extend","childInstance","setSingletonInstance","push","deleteSingletonInstances","filter","x","getSingletonFactory","undefined","getInstance","arguments","getSingletonFactoryByName","updateSingletonFactory","getClassFactory","getClassFactoryByName","updateClassFactory","mediaPlayerEvents","AST_IN_FUTURE","BUFFER_EMPTY","BUFFER_LOADED","BUFFER_LEVEL_STATE_CHANGED","BUFFER_LEVEL_UPDATED","DYNAMIC_TO_STATIC","ERROR","FRAGMENT_LOADING_COMPLETED","FRAGMENT_LOADING_PROGRESS","FRAGMENT_LOADING_STARTED","FRAGMENT_LOADING_ABANDONED","LOG","MANIFEST_LOADED","METRICS_CHANGED","METRIC_CHANGED","METRIC_ADDED","METRIC_UPDATED","PERIOD_SWITCH_STARTED","PERIOD_SWITCH_COMPLETED","QUALITY_CHANGE_REQUESTED","QUALITY_CHANGE_RENDERED","TRACK_CHANGE_RENDERED","STREAM_INITIALIZING","STREAM_UPDATED","STREAM_ACTIVATED","STREAM_DEACTIVATED","STREAM_INITIALIZED","STREAM_TEARDOWN_COMPLETE","TEXT_TRACKS_ADDED","TEXT_TRACK_ADDED","TTML_PARSED","TTML_TO_PARSE","CAPTION_RENDERED","CAPTION_CONTAINER_RESIZE","CAN_PLAY","CAN_PLAY_THROUGH","PLAYBACK_ENDED","PLAYBACK_ERROR","PLAYBACK_NOT_ALLOWED","PLAYBACK_METADATA_LOADED","PLAYBACK_LOADED_DATA","PLAYBACK_PAUSED","PLAYBACK_PLAYING","PLAYBACK_PROGRESS","PLAYBACK_RATE_CHANGED","PLAYBACK_SEEKED","PLAYBACK_SEEKING","PLAYBACK_SEEK_ASKED","PLAYBACK_STALLED","PLAYBACK_STARTED","PLAYBACK_TIME_UPDATED","PLAYBACK_WAITING","MANIFEST_VALIDITY_CHANGED","EVENT_MODE_ON_START","EVENT_MODE_ON_RECEIVE","CONFORMANCE_VIOLATION","REPRESENTATION_SWITCH","HTTPRequest","tcpid","type","url","actualurl","range","trequest","tresponse","responsecode","interval","trace","_stream","_tfinish","_mediaduration","_quality","_responseHeaders","_serviceLocation","HTTPRequestTrace","b","GET","HEAD","MPD_TYPE","XLINK_EXPANSION_TYPE","INIT_SEGMENT_TYPE","INDEX_SEGMENT_TYPE","MEDIA_SEGMENT_TYPE","BITSTREAM_SWITCHING_SEGMENT_TYPE","MSS_FRAGMENT_INFO_SEGMENT_TYPE","LICENSE","OTHER_TYPE","LOG_LEVEL_FATAL","LOG_LEVEL_ERROR","LOG_LEVEL_WARNING","LOG_LEVEL_INFO","LOG_LEVEL_DEBUG","Debug","config","showLogTimestamp","showCalleeName","startTime","eventBus","EventBus","settings","logFn","getLogFn","fn","console","log","fatal","params","doLog","error","warn","info","debug","level","_this","message","logTime","Date","getTime","getType","length","Array","forEach","item","logLevel","dispatchEvent","trigger","Events","getLogger","setLogTimestampVisible","setCalleeNameVisible","LOG_LEVEL_NONE","handlers","getHandlerIdx","listener","scope","idx","some","index","callback","on","options","Error","priority","handler","getStreamId","streamId","mediaType","inserted","splice","off","payload","filters","MediaPlayerEvents","reset","EVENT_PRIORITY_LOW","EVENT_PRIORITY_HIGH","DashJSError","code","data","errors","MANIFEST_LOADER_PARSING_FAILURE_ERROR_CODE","MANIFEST_LOADER_LOADING_FAILURE_ERROR_CODE","XLINK_LOADER_LOADING_FAILURE_ERROR_CODE","SEGMENT_BASE_LOADER_ERROR_CODE","TIME_SYNC_FAILED_ERROR_CODE","FRAGMENT_LOADER_LOADING_FAILURE_ERROR_CODE","FRAGMENT_LOADER_NULL_REQUEST_ERROR_CODE","URL_RESOLUTION_FAILED_GENERIC_ERROR_CODE","APPEND_ERROR_CODE","REMOVE_ERROR_CODE","DATA_UPDATE_FAILED_ERROR_CODE","CAPABILITY_MEDIASOURCE_ERROR_CODE","CAPABILITY_MEDIAKEYS_ERROR_CODE","DOWNLOAD_ERROR_ID_MANIFEST_CODE","DOWNLOAD_ERROR_ID_SIDX_CODE","DOWNLOAD_ERROR_ID_CONTENT_CODE","DOWNLOAD_ERROR_ID_INITIALIZATION_CODE","DOWNLOAD_ERROR_ID_XLINK_CODE","MANIFEST_ERROR_ID_PARSE_CODE","MANIFEST_ERROR_ID_NOSTREAMS_CODE","TIMED_TEXT_ERROR_ID_PARSE_CODE","MANIFEST_ERROR_ID_MULTIPLEXED_CODE","MEDIASOURCE_TYPE_UNSUPPORTED_CODE","MANIFEST_LOADER_PARSING_FAILURE_ERROR_MESSAGE","MANIFEST_LOADER_LOADING_FAILURE_ERROR_MESSAGE","XLINK_LOADER_LOADING_FAILURE_ERROR_MESSAGE","SEGMENTS_UPDATE_FAILED_ERROR_MESSAGE","SEGMENTS_UNAVAILABLE_ERROR_MESSAGE","SEGMENT_BASE_LOADER_ERROR_MESSAGE","TIME_SYNC_FAILED_ERROR_MESSAGE","FRAGMENT_LOADER_NULL_REQUEST_ERROR_MESSAGE","URL_RESOLUTION_FAILED_GENERIC_ERROR_MESSAGE","APPEND_ERROR_MESSAGE","REMOVE_ERROR_MESSAGE","DATA_UPDATE_FAILED_ERROR_MESSAGE","CAPABILITY_MEDIASOURCE_ERROR_MESSAGE","CAPABILITY_MEDIAKEYS_ERROR_MESSAGE","TIMED_TEXT_ERROR_MESSAGE_PARSE","MEDIASOURCE_TYPE_UNSUPPORTED_MESSAGE","ErrorsBase","zeroPadToLength","numStr","minStrLength","unescapeDollarsInTemplate","split","join","replaceIDForTemplate","indexOf","v","toString","replaceTokenForTemplate","token","startPos","endPos","formatTagPos","specifier","width","paddedValue","tokenLen","formatTagLen","charAt","parseInt","substring","toUpperCase","getSegment","representation","duration","presentationStartTime","mediaStartTime","timelineConverter","presentationEndTime","isDynamic","segmentIndex","seg","Segment","availabilityStartTime","calcAvailabilityStartTimeFromPresentationTime","availabilityEndTime","calcAvailabilityEndTimeFromPresentationTime","wallStartTime","calcWallTimeForSegment","replacementNumber","startNumber","isSegmentAvailable","segment","voPeriod","adaptation","period","isFinite","start","availabilityTimeOffset","refTime","getClientReferenceTime","getIndexBasedSegment","segmentDuration","isNaN","parseFloat","toFixed","calcMediaTimeFromPresentationTime","getTimeBasedSegment","time","fTimescale","tManifest","scaledTime","scaledDuration","calcPresentationTimeFromMediaTime","replacementTime","media","mediaRange","DefaultURLUtils","resolveFunction","schemeRegex","httpUrlRegex","httpsUrlRegex","originRegex","nativeURLResolver","baseUrl","URL","e","dumbURLResolver","baseUrlParseFunc","parseBaseUrl","isRelative","isPathAbsolute","parseOrigin","isSchemeRelative","parseScheme","base","joinChar","slashIndex","lastSlashIndex","lastIndexOf","matches","match","test","setup","isHTTPURL","isHTTPS","removeHostname","exec","resolve","URLUtils","defaultURLUtils","regexUtils","internalCall","functionName","utils","regex","getUtils","registerUrlRegex","FragmentRequest","action","ACTION_DOWNLOAD","NaN","mediaInfo","timescale","serviceLocation","requestStartDate","firstByteDate","requestEndDate","quality","bytesLoaded","bytesTotal","delayLoadingTime","responseType","representationId","end","ACTION_COMPLETE","checkParameterType","parameter","Constants","checkInteger","Utils","dest","source","copy","empty","mixin","src","clone","modifiedUrl","param","searchParams","set","href","headerStr","headers","headerPairs","trim","ilen","headerPair","dt","replace","Math","random","floor","string","hash","charCodeAt","originalUrl","targetUrl","original","target","protocol","origin","relativePath","path","relative","pathname","substr","startIndexOffset","Settings","defaultSettings","streaming","abandonLoadTimeout","wallclockTimeUpdateInterval","lowLatencyEnabled","lowLatencyEnabledByManifest","manifestUpdateRetryInterval","cacheInitSegments","eventControllerRefreshDelay","capabilities","filterUnsupportedEssentialProperties","useMediaCapabilitiesApi","timeShiftBuffer","calcFromSegmentTimeline","fallbackToSegmentTimeline","metrics","maxListDepth","delay","liveDelayFragmentCount","liveDelay","useSuggestedPresentationDelay","applyServiceDescription","protection","keepProtectionMediaKeys","ignoreEmeEncryptedEvent","buffer","enableSeekDecorrelationFix","fastSwitchEnabled","flushBufferAtTrackSwitch","reuseExistingSourceBuffers","bufferPruningInterval","bufferToKeep","bufferTimeAtTopQuality","bufferTimeAtTopQualityLongForm","initialBufferLevel","stableBufferTime","longFormContentDurationThreshold","stallThreshold","useAppendWindow","setStallState","gaps","jumpGaps","jumpLargeGaps","smallGapLimit","threshold","enableSeekFix","utcSynchronization","enabled","useManifestDateHeaderTimeSource","backgroundAttempts","timeBetweenSyncAttempts","maximumTimeBetweenSyncAttempts","minimumTimeBetweenSyncAttempts","timeBetweenSyncAttemptsAdjustmentFactor","maximumAllowedDrift","enableBackgroundSyncAfterSegmentDownloadError","defaultTimingSource","scheme","scheduling","defaultTimeout","lowLatencyTimeout","scheduleWhilePaused","text","defaultEnabled","liveCatchup","minDrift","maxDrift","playbackRate","latencyThreshold","playbackBufferMin","lastBitrateCachingInfo","ttl","lastMediaSettingsCachingInfo","cacheLoadThresholds","video","audio","trackSwitchMode","selectionModeForInitialTrack","fragmentRequestTimeout","retryIntervals","retryAttempts","abr","movingAverageMethod","ABRStrategy","additionalAbrRules","insufficientBufferRule","switchHistoryRule","droppedFramesRule","abandonRequestsRule","bandwidthSafetyFactor","useDefaultABRRules","useDeadTimeLatency","limitBitrateByPortal","usePixelRatioInLimitBitrateByPortal","maxBitrate","minBitrate","maxRepresentationRatio","initialBitrate","initialRepresentationRatio","autoSwitchBitrate","fetchThroughputCalculationMode","cmcd","sid","cid","rtp","rtpSafetyFactor","recoverAttempts","mediaErrorDecode","update","settingsObj","mixinSettings","slice","metricsReportingEvents","METRICS_INITIALISATION_COMPLETE","BECAME_REPORTING_PLAYER","CMCD_DATA_GENERATED","publicOnly","evt","FragmentModel","logger","executedRequests","loadingRequests","dashMetrics","fragmentLoader","streamInfo","isFragmentLoaded","request","isLoaded","req","req1","req2","adaptationIndex","isEqualInit","isEqualComplete","getRequestThreshold","min","removeExecutedRequestsBeforeTime","removeExecutedRequestsInTimeRange","getRequestForTime","arr","addSchedulingInfoMetrics","state","addSchedulingInfo","addRequestsQueue","onLoadingCompleted","sender","response","id","onLoadingInProgress","onLoadingAborted","resetInitialSettings","getRequests","states","filteredRequests","requests","getRequestsForState","concat","filterRequests","isFragmentLoadedOrPending","removeExecutedRequestsAfterTime","syncExecutedRequestsWithBufferedRange","bufferedRanges","streamDuration","ln","abortRequests","abort","executeRequest","load","loadCurrentFragment","addExecutedRequest","FRAGMENT_MODEL_LOADING","FRAGMENT_MODEL_EXECUTED","FRAGMENT_MODEL_CANCELED","FRAGMENT_MODEL_FAILED","URLLoader","cfg","schemeLoaderFactory","loader","SchemeLoaderFactory","loaderFactory","getLoader","errHandler","mediaPlayerModel","requestModifier","boxParser","dashConstants","urlUtils","requestTimeout","IsoBox","boxData","offset","_offset","size","boxes","isComplete","earliest_presentation_time","first_offset","references","reference","reference_type","referenced_size","subsegment_duration","version","scheme_id_uri","presentation_time_delta","presentation_time","event_duration","message_data","sequence_number","entry_count","entries","base_data_offset","sample_description_index","default_sample_duration","default_sample_size","default_sample_flags","flags","baseMediaDecodeTime","sample_count","first_sample_flags","data_offset","samples","sample","sample_size","sample_duration","sample_composition_time_offset","IsoFile","parsedIsoFile","getBoxes","fetchAll","box","convertToDashIsoBox","_incomplete","getBox","fetch","setData","getLastBox","IsoBoxSearchInfo","lastCompletedOffset","found","BoxParser","parse","fileStart","parsedFile","ISOBoxer","parseBuffer","dashIsoFile","parseUint32","parseIsoBoxType","String","fromCharCode","findLastTopIsoBoxCompleted","types","byteLength","boxInfo","ArrayBuffer","Uint8Array","boxSize","boxType","getMediaTimescaleFromMoov","ab","isoFile","mdhdBox","getSamplesInfo","sampleList","lastSequenceNumber","totalDuration","numSequences","sampleDuration","sampleCount","sampleSize","sampleDts","j","k","dataOffset","moofBoxes","mfhdBoxes","subsIndex","nextSubsSample","moofBox","trafBoxes","getChildBoxes","trafBox","tfhdBox","getChildBox","tfdtBox","trunBoxes","subsBoxes","trunBox","sampleData","subsBox","sample_delta","subSizes","entry","subsample_count","subsamples","subsample_size","findInitRange","initRange","ftyp","moov","parsePayload","g","Function","arrayBuffer","ISOFile","parser","ISOBox","_boxProcessors","pos","newBox","append","createBox","dataViewToString","dataView","encoding","impliedEncoding","TextDecoder","decode","a","getUint8","utf8ToByteArray","u","TextEncoder","encode","appendBox","_cursor","_root","_raw","_parent","addBoxProcessor","createFile","createFullBox","Cursor","initialOffset","DataView","result","returnEarly","_sweep","write","getLength","bytes","_rawo","_parseBox","byteOffset","_boxContainers","_procField","_parsing","_readField","_writeField","_procFieldArray","_procFullBox","_procEntries","_procSubEntries","_procEntryField","_procSubBoxes","_readUint","_readInt","_readTemplate","_readTerminatedString","_readString","_readData","_readUTF8String","getInt8","getInt16","getInt32","s1","s2","pow","getUint16","getUint32","str","char","largesize","_parseContainerBox","_data","_parseFullBox","_writeData","_writeInt","setInt8","setInt16","setInt32","setUint32","_writeUint","setUint8","setUint16","_writeString","_writeTerminatedString","_writeTemplate","pre","post","_writeUTF8String","nbCompatibleBrands","language","DataSize","reference_count","sap","starts_with_SAP","SAP_type","SAP_delta_time","subsegment_count","subsegment","ranges_count","subsample","reserved","length_size_of_traf_num","length_size_of_trun_num","length_size_of_sample_num","number_of_entry","RequestModifier","modifyRequestURL","modifyRequestHeader","err","XHRLoader","httpRequest","requestStartTime","xhr","XMLHttpRequest","open","method","setRequestHeader","header","withCredentials","onload","onloadend","onend","onerror","onprogress","progress","onabort","ontimeout","timeout","send","cachedSetTimeout","cachedClearTimeout","process","defaultSetTimout","defaultClearTimeout","runTimeout","fun","setTimeout","clearTimeout","currentQueue","queue","draining","queueIndex","cleanUpNextTick","drainQueue","len","run","marker","runClearTimeout","Item","array","noop","nextTick","title","browser","env","argv","versions","addListener","once","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","dir","umask","indexRange","Representation","segmentInfoType","initialization","codecs","mimeType","codecPrivateData","presentationTimeOffset","MSETimeOffset","mediaFinishedInformation","numberOfSegments","mediaTimeOfLastSignaledSegment","bandwidth","height","scanType","maxPlayoutRate","availabilityTimeComplete","DashConstants","AdaptationSet","Period","mpd","nextPeriodId","DEFAULT_ID","Mpd","manifest","suggestedPresentationDelay","Number","POSITIVE_INFINITY","timeShiftBufferDepth","maxSegmentDuration","publishTime","minimumUpdatePeriod","mediaPresentationDuration","EventStream","adaptionSet","schemeIdUri","DashManifestModel","BASE64","isInteger","getIsTypeOf","Representation_asArray","essentialProperties","getEssentialPropertiesForRepresentation","THUMBNAILS_SCHEME_ID_URIS","ContentComponent_asArray","contentType","mimeTypeRegEx","RegExp","getIsFragmented","getIsAudio","getIsVideo","getIsText","getIsImage","getRepresentationSortFunction","processAdaptation","realAdaptation","isArray","sort","getRealAdaptations","periodIndex","Period_asArray","AdaptationSet_asArray","getRealPeriods","getIsDynamic","realRepresentation","EssentialProperty_asArray","map","calcSegmentDuration","segmentTimeline","S_asArray","s0","getPeriodId","realPeriod","getEventStreams","inbandStreams","eventStreams","eventStream","getBaseURLsFromElement","node","baseUrls","BaseURL_asArray","baseUri","earlyReturn","BaseURL","__text","dvb_priority","dvb_weight","getLanguageForAdaptation","lang","getViewpointForAdaptation","Viewpoint","getRolesForAdaptation","Role_asArray","getAccessibilityForAdaptation","Accessibility_asArray","getAudioChannelConfigurationForAdaptation","AudioChannelConfiguration_asArray","getAudioChannelConfigurationForRepresentation","getAdaptationForIndex","realAdaptations","getIndexForAdaptation","ObjectUtils","areEqual","getAdaptationForId","getAdaptationsForType","adaptations","getRealPeriodForIndex","realPeriods","getCodec","addResolutionInfo","codec","getSelectionPriority","realAdaption","selectionPriority","getMimeType","getKID","getLabelsForAdaptation","Label_asArray","labelArray","getContentProtectionData","ContentProtection_asArray","getId","hasProfile","profile","has","profiles","getDuration","MAX_SAFE_INTEGER","MAX_VALUE","getBandwidth","getManifestUpdatePeriod","latencyOfLastUpdate","max","getPublishTime","getRepresentationCount","getBitrateListForAdaptation","processedRealAdaptation","getRepresentationFor","getRepresentationsForAdaptation","voAdaptation","segmentInfo","presentationOffset","voRepresentations","periodArray","getRealAdaptationFor","voRepresentation","SegmentBase","SegmentList","SegmentTemplate","Initialization","sourceURL","SegmentTimeline","periodStart","getAdaptationsForPeriod","voAdaptationSet","realAdaptationSet","voAdaptations","getRegularPeriods","voPeriods","realPreviousPeriod","voPreviousPeriod","checkConfig","periodEnd","Errors","getEndTimeForLastPeriod","getMpd","loadedTime","getEventsForPeriod","EventStream_asArray","Event_asArray","currentMpdEvent","event","Event","presentationTime","calculatedPresentationTime","Signal","Binary","messageData","decodeArray","__cdata","getEventStreamForAdaptationSet","adaptationArray","InbandEventStream_asArray","getEventStreamForRepresentation","representationArray","getUTCTimingSources","hasAST","utcTimingsArray","UTCTiming_asArray","utcTimingEntries","utcTiming","UTCTiming","getLocation","Location","Location_asArray","getPatchLocation","PatchLocation","PatchLocation_asArray","getSuggestedPresentationDelay","getAvailabilityStartTime","getServiceDescriptions","serviceDescriptions","ServiceDescription_asArray","sd","latency","getSupplementalProperties","supplementalProperties","SupplementalProperty_asArray","sp","setConfig","ThumbnailTrackInfo","bitrate","tilesHor","tilesVert","widthPerTile","heightPerTile","templateUrl","ThumbnailTracks","tracks","dashHandler","currentTrackIndex","segmentsController","adapter","baseURLController","_createTrack","useSegmentBase","track","vars","updateSegmentData","then","cache","segments","count","_normalizeSegments","readThumbnail","cached","el","ss","baseURL","blob","Blob","imageUrl","createObjectURL","_handleUpdatedSegmentData","buildTemplateUrl","getTracks","addTracks","getMediaInfoForType","voReps","getVoRepresentations","rep","setTrackByIndex","getCurrentTrack","getCurrentTrackIndex","getThumbnailRequestForTime","currentVoRep","getSegmentRequestForTime","SegmentsController","segmentBaseController","DashHandler","initialize","pna","objectKeys","keys","Duplex","util","inherits","Readable","Writable","readable","writable","allowHalfOpen","_writableState","ended","onEndNT","self","highWaterMark","_readableState","destroyed","_destroy","cb","lastSegment","isDynamicManifest","mediaHasFinished","_setRequestUrl","destination","_getRequestForSegment","getSegmentByTime","_onDynamicToStatic","getStreamInfo","getInitRequest","_generateInitRequest","getCurrentIndex","getNextSegmentRequest","indexToRequest","getSegmentByIndex","isLastSegmentRequested","bufferingTime","getNextSegmentRequestIdempotent","getValidSeekTimeCloseToTargetTime","targetThreshold","currentUpperTime","currentLowerTime","adjustedTime","targetRequest","upperRequest","lowerRequest","requestEndTime","TimelineSegmentsGetter","iterateSegments","iterFunc","fragments","frag","repeat","timeline","list","SegmentURL_asArray","relativeIdx","breakIterator","_calculateRepeatCountForNegativeR","nextFrag","repeatEndTime","availabilityEnd","dvrWindow","getCurrentDVRInfo","ceil","lastSegmentTime","requestedTime","requiredMediaTime","getMediaFinishedInformation","availableSegments","TemplateSegmentsGetter","template","round","periodTime","calcPeriodRelativeTimeFromMpdRelativeTime","ListSegmentsGetter","offsetToSubtract","relativeIndex","SegmentBaseGetter","epsilon","ft","fd","getIndexByTime","getters","getSegmentsGetter","updateInitData","hasInitialization","Promise","getSegmentBaseInitSegment","hasSegments","getSegmentList","weight","DEFAULT_DVB_PRIORITY","DEFAULT_DVB_WEIGHT","ctor","superCtor","super_","constructor","configurable","TempCtor","specialCea608CharsCodes","getCharForByte","byte","charCode","rowsLowCh1","rowsHighCh1","rowsLowCh2","rowsHighCh2","backgroundColors","verboseFilter","verboseLevel","setTime","newTime","severity","msg","minLevel","numArrayToHexArray","numArray","hexArray","PenState","foreground","underline","italics","background","flash","setStyles","styles","attribs","style","isDefault","equals","other","newPenState","StyledUnicodeChar","uchar","penState","setChar","setPenState","newChar","isEmpty","Row","chars","currPenState","equal","setCursor","absPos","moveCursor","relPos","newPos","backSpace","insertChar","clearFromPos","clear","clearToEndOfRow","getTextString","setPenStyles","CaptionScreen","rows","currRow","NR_ROWS","nrRollUpRows","setPen","setPAC","pacData","JSON","stringify","newRow","row","indent","prevPos","color","setBkgData","bkgData","setRollUpRows","nrRows","rollUp","getDisplayText","topRowIndex","topRow","asOneRow","displayText","rowNr","rowText","getTextAndFormat","Cea608Channel","channelNumber","outputFilter","chNr","verbose","displayedMemory","nonDisplayedMemory","lastOutputScreen","currRollUpRow","writeScreen","cueStartTime","modes","lastCueEndTime","getHandler","setHandler","newHandler","setMode","newMode","insertChars","screen","outputDataUpdate","cc_RCL","cc_BS","cc_AOF","cc_AON","cc_DER","cc_RU","cc_FON","cc_RDC","cc_TR","cc_RTD","cc_EDM","cc_CR","cc_ENM","cc_EOC","tmp","cc_TO","nrCols","cc_MIDROW","secondByte","colorIndex","updateData","newCue","cueSplitAtTime","Cea608Parser","field","out1","out2","outputs","channels","currChNr","lastCmdA","lastCmdB","bufferedData","lastTime","dataCounters","addData","byteList","cmdFound","charsFound","parseCmd","parseMidrow","parsePAC","parseBackgroundAttributes","parseChars","cmd","padding","channel","interpretPAC","pacIndex","channelNr","charCodes","charCode1","oneCode","hexCodes","findCea608Nalus","raw","nalSize","cursor","cea608NaluRanges","isCEA608SEI","payloadType","payloadSize","countryCode","providerCode","userIdentifier","userDataTypeCode","extractCea608DataFromRange","cea608Range","fieldData","ccCount","ccValid","ccType","ccData1","ccData2","OBJECT_TYPES","STREAMING_FORMATS","STREAM_TYPES","CmcdModel","dashManifestModel","internalData","abrController","playbackController","streamProcessors","_isStartup","_bufferLevelStarved","_initialMediaRequestsDone","_resetInitialSettings","pr","nor","st","sf","generateUuid","_updateStreamProcessors","_onPeriodSwitchComplete","streamController","getStreamController","getActiveStream","activeStream","getProcessors","_copyParameters","parameterNames","copiedData","_getCmcdData","_getGenericCmcdData","ot","_initForMediaType","encodedBitrate","bitrateList","_getBitrateByRequest","_getObjectDurationByRequest","mtp","getThroughputHistory","getSafeAverageThroughput","_getMeasuredThroughputByType","dl","bufferLevel","getCurrentBufferLevel","_getDeadlineByType","bl","_getBufferLevelByType","tb","getTopBitrateInfoFor","_getTopBitrateByType","nextRequest","streamProcessor","probeNextRequest","_probeNextRequest","getPlaybackRate","currentBufferLevel","minBandwidth","_calculateRtp","encodeURIComponent","getRelativeUrl","nrr","br","bs","su","_getCmcdDataForMediaSegment","_getCmcdDataForInitSegment","_getCmcdDataForOther","_getCmcdDataForLicense","_onPlaybackRateChanged","_onManifestLoaded","_onBufferLevelStateChanged","_onPlaybackSeeked","_buildFinalString","cmcdData","localeCompare","cmcdString","reduce","acc","getQueryParameter","finalPayloadString","MetricsReportingEvents","getHeaderParameters","cmcdObjectHeader","cmcdRequestHeader","cmcdStatusHeader","cmcdSessionHeader","presentationTimeDelta","obj1","obj2","deepEqual","X2JS","escapeMode","attributePrefix","arrayAccessForm","emptyNodeForm","enableToStringFunc","arrayAccessFormPaths","skipEmptyTextNodesForObj","stripWhitespaces","datetimeAccessFormPaths","useDoubleQuotes","xmlElementsFilter","jsonPropertiesFilter","keepCData","ignoreRoot","initConfigDefaults","DOMNodeTypes","getNodeLocalName","nodeLocalName","localName","baseName","nodeName","escapeXmlChars","checkInStdFiltersArrayForm","stdFiltersArrayForm","filterPath","toArrayAccessForm","childName","fromXmlDateTime","bits","secondBits","setHours","setMilliseconds","offsetMinutes","setMinutes","getMinutes","getTimezoneOffset","UTC","getFullYear","getMonth","getDate","getHours","getSeconds","getMilliseconds","checkXmlElementsFilter","childType","childPath","parseDOMChildren","nodeType","nodeChildren","childNodes","cidx","child","__cnt","children","__children","aidx","attributes","attr","value2","ml","matchers","matchobj","converter","nodePrefix","prefix","getNodePrefix","__prefix","fullPath","checkFromXmlDateTimePaths","nodeValue","startTag","jsonObj","element","attrList","closed","resultStr","attrName","attrVal","endTag","elementName","jsonXmlSpecialElem","jsonObjField","suffix","jsonXmlElemCount","elementsCnt","it","checkJsonObjPropertiesFilter","propertyName","jsonObjPath","parseJSONAttributes","ait","parseJSONTextObject","jsonTxtObj","parseJSONTextAttrs","getJsonPropertyPath","jsonPropName","parseJSONArray","jsonArrRoot","jsonArrObj","arIdx","parseJSONObject","subObj","toISOString","parseXmlString","xmlDocStr","xmlDoc","ActiveXObject","DOMParser","parseFromString","getElementsByTagNameNS","async","loadXML","asArray","toXmlDateTime","asDateTime","xml2json","xml_str2json","json2xml_str","json2xml","getVersion","FetchLoader","lowLatencyThroughputModel","read","processResult","reader","status","calculateDownloadedTime","downloadedData","bytesReceived","avgTimeDistance","ts","next","distance","abortController","Headers","AbortController","signal","reqOptions","credentials","calculationMode","requestTime","now","throughputCapacityDelayMS","getThroughputCapacityDelayMS","markBeforeFetch","statusText","responseURL","ok","responseHeaders","body","loaded","total","stream","measurement","totalBytes","signaledFirstByte","remaining","markA","markB","tee","forMeasure","forConsumer","getReader","processFetch","done","chunkDownloadDurationMS","chunkBytes","chunkDownloadTimeRelativeMS","kbps","fetchDuration","bytesAllChunks","prev","curr","addMeasurement","lengthComputable","getEstimatedDownloadDurationMS","startTimeData","endTimeData","lastChunkWasFinished","calculatedThroughput","datum","datumE","dataE","chunkThroughputs","shortDurationBytesReceived","shortDurationStartTime","chunkDownloadTime","cumulatedChunkDownloadTime","calculateThroughputByChunkData","throughput","concatTypedArray","performance","boxesInfo","subarray","noTrace","cancel","LowLatencyThroughputModel","measurements","createBufferLevelTrendFunction","chunkMeasurements","sumX","sumY","sumXY","sumXSq","N","isBufferSafeAndStable","lastMeasurements","lastBitrate","aveBufferLevelLastSegements","bufferLevelAtSegmentEnd","abs","bufferLevelAtSegmentStart","fetchDownloadDurationMS","requestTimeMS","bitrateEntry","find","repId","adjustedAvailabilityStartTimeMS","segDurationMS","chunksDurationMS","segmentBytes","getEstimatedBufferLevel","shift","currentBufferLevelMS","lastThreeMeasurements","lastMeasurement","pop","lastChunkRelativeTimeMS","isBufferStable","selectedOptimisticFactor","chunkAvailablePeriod","chunkBytesBBLE","chunkDownloadtimeMSBBLE","chunkCount","chunk","downloadThroughput","estimatedDownloadtimeMS","nextHigherBitrate","HTTPLoader","delayedRequests","retryRequests","downloadErrorToRequestTypeMap","cmcdModel","internalLoad","remainingAttempts","traces","firstProgress","needFailureReport","lastTraceTime","lastTraceReceivedCount","handleLoaded","success","checkExistenceOnly","responseUrl","responseStatus","getAllResponseHeaders","addHttpRequest","addManifestUpdate","getRetryAttemptsForType","retryRequest","getRetryIntervalsForType","complete","cmcdMode","additionalQueryParameter","cmcdQueryParameter","_getAdditionalQueryParameter","addAditionalQueryParameterToUrl","verb","getXHRWithCredentialsForType","currentTime","timeoutMessage","percentageComplete","delayedRequest","delayTimeout","schemeLoaderMap","unregisterAllLoader","startsWith","registerLoader","unregisterLoader","objectToString","arg","isBoolean","isNull","isNullOrUndefined","isNumber","isString","isSymbol","isUndefined","isRegExp","re","isObject","isDate","isError","isFunction","isPrimitive","isBuffer","Buffer","normalizeArray","parts","allowAboveRoot","up","last","unshift","xs","f","res","resolvedPath","resolvedAbsolute","TypeError","normalize","isAbsolute","trailingSlash","paths","from","to","fromParts","toParts","samePartsLength","outputParts","sep","delimiter","dirname","hasRoot","matchedSlash","basename","ext","extname","startDot","startPart","preDotState","generateISD","fromXML","renderHTML","render","CustomTimeRanges","customTimeRangeArray","add","mergeRanges","remove","rangeIndex1","rangeIndex2","range1","range2","codecCompatibilityTable","supportsMediaSource","hasWebKit","hasMediaSource","Capabilities","encryptedMediaSupported","supportsEncryptedMedia","supportsCodec","navigator","mediaCapabilities","decodingInfo","framerate","_canUseMediaCapabilitiesApi","configuration","supported","_checkCodecWithMediaCapabilities","MediaSource","isTypeSupported","WebKitMediaSource","_checkCodecWithMse","setEncryptedMediaSupported","supportsEssentialProperty","ep","codecRootCompatibleWithCodec","codec1","codec2","compatTableCodec","codecRoot","rootCompatible","compatibleCodecs","compatibleCodec","imscNames","ns_tt","ns_tts","ns_ttp","ns_xml","ns_itts","ns_ittp","ns_smpte","ns_ebutts","arg1","arg2","arg3","copyProps","dst","SafeBuffer","encodingOrOffset","alloc","allocUnsafe","allocUnsafeSlow","fill","buf","SlowBuffer","TCP_CONNECTION","HTTP_REQUEST","TRACK_SWITCH","BUFFER_LEVEL","ABANDON_LOAD","ALLOW_LOAD","BUFFER_STATE","DVR_INFO","DROPPED_FRAMES","SCHEDULING_INFO","REQUESTS_QUEUE","MANIFEST_UPDATE","MANIFEST_UPDATE_STREAM_INFO","MANIFEST_UPDATE_TRACK_INFO","PLAY_LIST","DVB_ERRORS","PlaybackController","videoModel","wallclockTimeIntervalId","playOnceInitialized","lastLivePlaybackTime","seekTarget","internalSeek","isLowLatencySeekingInProgress","playbackStalled","minPlaybackRateChange","manifestUpdateInProgress","getTimeToStreamEnd","sInfo","getStreamEndTime","refInfo","play","getElement","isPaused","pause","isSeeking","isStalled","seek","stickToBuffered","internal","setCurrentTime","getNormalizedTime","timeOffset","getEnded","getCurrentLiveLatency","getClientTimeOffset","_onDataUpdateCompleted","_onFragmentLoadProgress","_onManifestUpdated","_onStreamsComposed","_onPlaybackProgression","_onPlaybackEnded","_onStreamInitializing","_onRepresentationSwitch","setPlaybackRate","stopUpdatingWallclockTime","removeEventListener","_onCanPlay","_onCanPlayThrough","_onPlaybackStart","_onPlaybackWaiting","_onPlaybackPlaying","_onPlaybackPaused","_onPlaybackError","_onPlaybackSeeking","_onPlaybackTimeUpdated","_onPlaybackProgress","_onPlaybackMetaDataLoaded","_onPlaybackLoadedData","onPlaybackStalled","_onNativePlaybackEnded","getActualPresentationTime","mediatype","DVRMetrics","DVRWindow","startUpdatingWallclockTime","setInterval","addDVRMetric","updateCurrentTime","clearInterval","getReadyState","hasVideoTrack","actualTime","timeChanged","representationInfo","convertRepresentationToRepresentationInfo","currentRepresentation","playingTime","seekTime","timeToEnd","rate","getActiveStreamInfo","isLast","srcElement","_isCatchupEnabled","catchupMode","_getCatchupMode","currentLiveLatency","getLiveDelay","liveCatchupLatencyThreshold","getLiveCatchupLatencyThreshold","liveCatchUpMinDrift","currentBuffer","getBufferLevel","latencyDrift","_lolpNeedToCatchUpCustom","_defaultNeedToCatchUp","_needToCatchUp","results","currentPlaybackRate","liveCatchupPlaybackRate","liveCatchUpPlaybackRate","newRate","cpr","E","_calculateNewPlaybackRateLolP","deltaLatency","_calculateNewPlaybackRateDefault","startPlaybackCatchUp","stopPlaybackCatchUp","filterList","getActiveStreamProcessors","minDelay","MetricsConstants","activeStreamInfo","periodSwitch","addEventListener","manifestInfo","ua","userAgent","toLowerCase","isSafari","_initializeForFirstStream","getIsManifestUpdateInProgress","getPlayedRanges","computeAndSetLiveDelay","fragmentDuration","ret","adjustedFragmentDuration","llsd","_applyServiceDescription","minBufferTime","dvrWindowSize","targetDelayCapping","SourceBufferSink","intervalId","textController","callbacks","appendQueue","isAppendingInProgress","mediaSource","lastRequestAppended","changeType","_waitForUpdateEnd","_initializeForText","getTextSourceBuffer","_addEventListeners","_updateEndHandler","_errHandler","updateAppendWindow","appendWindowEnd","appendWindowStart","updateTimestampOffset","timestampOffset","_abortBeforeAppend","_appendNextInQueue","nextChunk","afterSuccess","segmentType","promise","appendBuffer","reject","_executeCallback","updating","eventType","getAllBufferRanges","buffered","getBuffer","unintended","readyState","setTextTrack","_removeEventListeners","removeSourceBuffer","initializeForStreamSwitch","mInfo","selectedRepresentation","oldSourceBufferSink","_copyPreviousSinkData","promises","all","initializeForFirstUse","addSourceBuffer","isFragmented","InitCache","save","extract","BufferController","isBufferingCompleted","criticalBufferLevel","maxAppendedIndex","maximumIndex","sourceBufferSink","bufferState","appendedBytesInfo","wallclockTicked","isPruningInProgress","isQuotaExceeded","initCache","pendingPruningRanges","replacingBuffer","fragmentModel","representationController","setMediaSource","_getRepresentationInfo","getRepresentationForQuality","_initializeSink","oldBufferSinks","requiredQuality","_onInitFragmentLoaded","_appendToBuffer","_onMediaFragmentLoaded","_onAppended","_triggerEvent","_showBufferRanges","ranges","getTotalBufferedTime","bufferAhead","_handleQuotaExceededError","hasEnoughSpaceToAppend","quotaExceededTime","clearBuffers","getClearRanges","_updateBufferLevel","endFragment","_checkIfBufferingCompleted","getRangeAt","getCurrentRepresentation","_adjustSeekTarget","pruneAllSafely","getAllRangesWithSafetyFactor","clearRanges","behindPruningRange","targetTime","bufferToKeepBehind","startOfBuffer","rangeEnd","currentTimeRequest","_getRangeBehindForPruning","aheadPruningRange","endOfBuffer","bufferToKeepAhead","rangeStart","_getRangeAheadForPruning","isTextEnabled","_onPlaybackStalled","checkIfSufficientBuffer","tolerance","firstStart","lastEnd","gap","toler","getBufferLength","isLastIdxAppended","periodBuffered","setIsBufferingCompleted","_notifyBufferStateChanged","startRangeToKeep","behindRange","_addClearRangeWithPromise","clearNextRange","sourceBuffer","_onRemoved","quotaExceeded","updateBufferTimestampOffset","_onWallclockTimeUpdated","totalBufferedTime","errored","keepBuffers","tmpSourceBufferSinkToReset","getBufferControllerType","createBufferSink","getQualityFor","getMediaSource","appendInitSegmentFromCache","getIsBufferingCompleted","getIsPruningInProgress","prepareForPlaybackSeek","prepareForReplacementTrackSwitch","prepareForNonReplacementTrackSwitch","prepareForReplacementQualitySwitch","getContinuousBufferTimeForTargetTime","setSeekTarget","segmentRequestingCompleted","NotFragmentedTextBufferController","initialized","ScheduleController","currentRepresentationInfo","timeToLoadDelay","scheduleTimeout","lastFragmentRequest","topQualityIndex","lastInitializedQuality","switchTrack","initSegmentRequired","checkPlaybackQuality","bufferController","startScheduleTimer","clearScheduleTimer","timeoutValue","schedule","getInitialPlayback","getAutoPlay","_shouldClearScheduleTimer","newTopQualityIndex","getMaxAllowedIndexFor","getBufferTarget","_shouldBuffer","_shouldScheduleNextRequest","qualityChange","bufferTarget","schedulingInfo","getCurrentSchedulingInfo","_getBufferTargetForFragmentedText","videoBufferLevel","_getBufferTargetForAudio","isPlayingAtTopQuality","getStableBufferTime","_getGenericBufferTarget","_completeQualityChange","oldMediaInfo","newMediaInfo","oldQuality","newQuality","_onBytesAppended","_onURLResolutionFailed","_onPlaybackStarted","updatePlayListTraceMetrics","playbackspeed","_hasVideoTrack","setCurrentRepresentation","setTimeToLoadDelay","getTimeToLoadDelay","setSwitchTrack","getSwitchStrack","getPlaybackController","setCheckPlaybackQuality","setInitSegmentRequired","PlayList","mstart","starttype","INITIAL_PLAYOUT_START_REASON","SEEK_START_REASON","RESUME_FROM_PAUSE_START_REASON","METRICS_COLLECTION_START_REASON","PlayListTrace","representationid","subreplevel","stopreason","REPRESENTATION_SWITCH_STOP_REASON","REBUFFERING_REASON","USER_REQUEST_STOP_REASON","END_OF_PERIOD_STOP_REASON","END_OF_CONTENT_STOP_REASON","METRICS_COLLECTION_STOP_REASON","FAILURE_STOP_REASON","StreamProcessor","mediaInfoArr","scheduleController","shouldUseExplicitTimeForRequest","qualityChangeInProgress","manifestModel","mediaController","segmentBlacklistController","getIsTextTrack","getData","_onInitFragmentNeeded","rescheduleIfNoRequest","_noValidRequest","_onMediaFragmentNeeded","_getFragmentRequest","_mediaRequestGenerated","_noMediaRequestGenerated","blacklistUrl","contains","_shouldIgnoreRequest","getRepresentationInfo","useTime","addBufferState","pushPlayListTraceMetrics","_onBufferCleared","setExplicitBufferingTime","_onSourceBufferError","_prepareForDefaultQualitySwitch","_bufferClearedForNonReplacement","_onFragmentLoadingAbandoned","isInitializationRequest","_onFragmentLoadingCompleted","_handleFragmentLoadingError","_onSetFragmentedTextAfterDisabled","getScheduleController","_onSetNonFragmentedText","currentTrackInfo","selectMediaInfo","_onQuotaExceeded","newRealAdaptation","getRealAdaptation","maxQuality","minIdx","getMinAllowedIndexFor","getAverageThroughput","getInitialBitrateFor","getQualityForBitrate","eventStreamMedia","getEventsFor","eventStreamTrack","mediaInbandEvents","trackInbandEvents","inbandEvents","eventBoxes","sidx","mediaAnchorTime","fragmentMediaStartTime","getEvent","_handleInbandEvents","_bufferClearedForReplacement","continuousBufferTime","_onSeekTarget","registerStreamType","RepresentationController","controller","_createBufferControllerForType","isUpdating","getBufferController","getFragmentModel","getRepresentationController","createBufferSinks","previousBufferSinks","updateStreamInfo","newStreamInfo","clearMediaInfoArray","addMediaInfo","prepareTrackSwitch","shouldReplace","prepareQualityChange","reason","forceReplace","abandonmentState","getAbandonmentStateFor","_prepareForFastQualitySwitch","createPlaylistTraceMetrics","getMediaInfo","finalisePlayList","prepareInnerPeriodPlaybackSeeking","prepareOuterPeriodPlaybackSeeking","unRegisterStreamType","FragmentController","fragmentModels","model","onFragmentLoadingCompleted","isInit","strInfo","DataChunk","createDataChunk","getModel","FragmentLoader","Thumbnail","y","BitrateInfo","qualityIndex","ThumbnailController","thumbnailTracks","provide","thumbIndex","thumbnail","seq","seqIdx","_buildUrlFromTemplate","getBitrateList","bitrateInfo","BlackListController","blacklist","updateEventName","addBlacklistEventName","onAddBlackList","query","MEDIA_TYPES","Stream","isInitialized","isActive","hasFinishedBuffering","hasAudioTrack","updateError","fragmentController","thumbnailController","preloaded","isEndedEventSignaled","trackChangedEvents","manifestUpdater","eventController","protectionController","_commonMediaInitialization","addInlineEvents","previousBuffersSinks","initialMediaInfo","allMediaForType","getAllMediaInfoForType","embeddedMediaInfos","isEmbedded","addEmbeddedTrack","_isMediaSupported","addTrack","setInitialMediaSettingsForType","setInitialSettings","getInitialSettings","addMediaInfosToBuffer","_createStreamProcessor","getCurrentTrackFor","updateTopQualityIndex","_initializeMediaForType","buffers","bufferSinks","sink","getValue","_checkIfInitializationCompleted","createTracks","contentProtection","deactivate","deactivateStream","setPreloaded","setIsEndedEventSignaled","getStartTime","onProtectionError","initializeForMedia","waitForReadyState","onBufferingCompleted","processors","onDataUpdateCompleted","onInbandEvents","addInbandEvents","getProcessorForMediaInfo","_getProcessorByType","processor","_compareProtectionConfig","newStream","currentStreamInfo","newAdaptation","getAdaptationForType","currentAdaptation","_isAdaptationDrmProtected","ContentProtection","compareCodecs","previousStream","sameMimeType","oldCodecs","newCodecs","codecMatch","newCodec","partialCodecMatch","oldCodec","getPreloaded","KEY_ERROR","SERVER_CERTIFICATE_UPDATED","LICENSE_REQUEST_COMPLETE","KEY_SYSTEM_SELECTED","KEY_SESSION_CREATED","KEY_STATUSES_CHANGED","initializeForStream","activate","_initializeMedia","getIsActive","getHasAudioTrack","getHasVideoTrack","startPreloading","previousBuffers","getThumbnailController","getBitrateListFor","updatedStreamInfo","currentMediaInfo","areMediaInfosEqual","trackChangedEvent","clearDataForStream","isMediaCodecCompatible","isProtectionCompatible","getIsEndedEventSignaled","getAdapter","getHasFinishedBuffering","startScheduleControllers","prepareTrackChange","setCurrentMediaInfo","refreshManifestOnSwitchTrack","getIsUpdating","refreshManifest","BlacklistController","ManifestUpdater","refreshDelay","refreshTimer","isStopped","manifestLoader","stopManifestRefreshTimer","startManifestRefreshTimer","onRefreshTimer","ignorePatch","patchLocation","location","getIsPatch","patch","isPatchValid","patchSuccessful","applyPatchToManifest","updatedPublishTime","setValue","date","onManifestLoaded","onPlaybackStarted","onPlaybackPaused","onStreamsComposed","setManifest","TimeSyncController","isSynchronizing","isBackgroundSynchronizing","backgroundSyncTimeOffsets","timingSources","timeOfLastSync","timeOfLastBackgroundSync","lastOffset","lastTimingSource","internalTimeBetweenSyncAttempts","_onAttemptBackgroundSync","_attemptBackgroundSync","attempts","_completeBackgroundTimeSyncSequence","deviceTimeBeforeSync","serverTime","deviceTimeAfterSync","_calculateOffset","_onComplete","failed","_checkForDateHeader","_completeTimeSyncSequence","_xsdatetimeDecoder","xsdatetimeStr","parsedDate","utcDate","timezoneOffset","_alternateXsdatetimeDecoder","_iso8601Decoder","isoStr","_rfc1123Decoder","dateStr","_notSupportedHandler","onSuccessCB","onFailureCB","_directHandler","_httpHandler","decoder","isHeadRequest","oncomplete","urls","getResponseHeader","_httpHeadHandler","dateHeaderValue","getLatestMPDRequestHeaderValueByID","dateHeaderTime","adjustedTimeBetweenSyncAttempts","isOffsetDriftWithinThreshold","_isOffsetDriftWithinThreshold","_adjustTimeBetweenSyncAttempts","shouldAttemptBackgroundSync","averageOffset","maxAllowedDrift","attemptSync","tSources","_shouldPerformSynchronization","_attemptRecursiveSync","sourceIndex","HTTP_TIMEOUT_MS","MediaSourceController","createMediaSource","attachMediaSource","objectURL","setSource","detachMediaSource","setDuration","sourceBuffers","isBufferUpdating","setSeekable","setLiveSeekableRange","clearLiveSeekableRange","signalEndOfStream","endOfStream","EventController","inlineEvents","eventInterval","lastEventTimerCall","eventHandlingInProgress","isStarted","EVENT_HANDLED_STATES","_stop","_triggerRemainingEvents","_onStopEventController","_addOrUpdateEvent","shouldOverwriteExistingEvents","eventState","indexOfExistingEvent","findIndex","_handleManifestReloadEvent","newDuration","validUntil","newManifestValidAfter","_onEventTimer","currentVideoTime","presentationTimeThreshold","_triggerEvents","_iterateAndTriggerCallback","_startEvent","calculatedPresentationTimeInSeconds","_eventHasExpired","periodEndTime","_eventIsInvalid","_removeEvent","periodDuration","schemeIdUris","eventId","_refreshManifest","_sendCallbackRequest","values","getInbandEvents","getInlineEvents","LEVELS","SUGGESTION","WARNING","EVENTS","NO_UTC_TIMING_ELEMENT","NON_COMPLIANT_SMPTE_IMAGE_ATTRIBUTE","INVALID_DVR_WINDOW","StreamController","capabilitiesFilter","mediaSourceController","timeSyncController","uriFragmentModel","streams","protectionData","autoPlay","isStreamSwitchingInProgress","hasMediaError","hasInitialisationError","initialPlayback","playbackEndedTimerInterval","preloadingStreams","supportsChangeType","firstLicenseIsFetched","waitForPlaybackStartTimeout","errorInformation","_onTimeSyncCompleted","streamsInfo","getStreamsInfo","updateManifestUpdateInfo","getBufferRange","clientTimeOffset","shouldKeepStream","_filterOutdatedStreams","_initializeOrUpdateStream","addManifestUpdateStreamInfo","dvrRange","waitingTime","streamInfos","maxFragmentDuration","fragmentDurations","_getFragmentDurationForLiveDelayCalculation","dvrInfo","liveEdge","startTimeFromUri","_getStartTimeFromUriParameters","getStreams","_getInitialStartTime","initialStream","getStreamForTime","startStream","_switchStream","_checkIfPrebufferingCanStart","_composeStreams","_onKeySessionUpdated","getStreamById","fromStreamInfo","toStreamInfo","_canSourceBuffersBeReused","_openMediaSource","sourceUrl","_onMediaSourceOpen","revokeObjectURL","_setMediaDuration","_activateStream","_open","sinks","oldTime","seekToStream","_cancelPreloading","_handleOuterPeriodSeek","_flushPlaylistMetrics","_handleInnerPeriodSeek","_createPlaylistMetrics","_deactivateAllPreloadingStreams","_onCurrentTrackChanged","nextStream","_onStreamCanLoadNext","seamlessPeriodSwitch","calcTimeShiftBufferWindow","activeStreamProcessors","addDVRInfo","_onBufferLevelUpdated","getInitialBufferLevel","excludedStreamProcessors","addBufferLevel","_onQualityChanged","playbackQuality","getPlaybackQuality","addDroppedFrames","_onStreamBufferingCompleted","upcomingStreams","refStream","refStreamInfo","_getNextStreams","_stopPlaybackEndedTimerInterval","targetIndex","lastDiff","diff","_getNextStream","manifestDuration","fragData","getURIFragmentData","refStreamStartTime","posix","updatePeriods","manifestUTCTimingSources","ConformanceViolationConstants","allUTCTimingSources","getDefaultUtcTimingSource","filterUnsupportedFeatures","addPlayList","startReason","createPlaylistMetrics","counts","_handleMediaErrorDecode","msExtendedCode","_checkConfig","_onManifestValidityChanged","_onMetricAdded","KEY_SESSION_UPDATED","clearAllCurrentMetrics","PROTECTION_DESTROYED","metric","targetMediaType","autoPl","protData","PROTECTION_CREATED","setMediaElement","setProtectionData","registerEvents","getTimeRelativeToStreamId","baseStart","streamStart","streamDur","loadWithManifest","_checkInitialize","getIsStreamSwitchInProgress","switchToVideoElement","getHasMediaOrInitialisationError","GapController","lastPlaybackTime","gapHandlerInterval","lastGapJumpPosition","jumpTimeoutHandler","trackSwitchByMediaType","_onInitialStreamSwitch","_onBufferReplacementStarted","_onBufferReplacementEnded","_unregisterEvents","_shouldCheckForGaps","_jumpGap","_startGapHandler","checkSeekingState","trackSwitchInProgress","shouldIgnoreSeekingState","_shouldIgnoreSeekingState","streamEnd","_getNextRangeIndex","nextRangeIndex","seekToPosition","jumpToStreamEnd","timeToStreamEnd","timeUntilGapEnd","timeToWait","_registerEvents","MediaController","initialSettings","lastSelectedTracks","domStorage","customInitialTrackSelectionFunction","getTracksFor","current","setTrack","noSettingsSave","isTracksEqual","switchMode","extractSettings","storeLastSettings","roles","role","accessibility","audioChannelConfiguration","setSavedMediaSettings","t1","t2","sameId","sameViewpoint","viewpoint","sameLang","sameCodec","sameRoles","sameAccessibility","sameAudioChannelConfiguration","matchSettings","isTrackActive","matchLang","matchIndex","matchViewPoint","matchRole","matchAccessibility","matchAudioChannelConfiguration","getTracksWithHighestBitrate","trackArr","getTracksWithHighestEfficiency","Infinity","sum","resolution","getTracksWithWidestRange","representationCount","selectInitialTrack","tmpArr","_trackSelectionModeHighestSelectionPriority","_trackSelectionModeHighestBitrate","_trackSelectionModeFirstTrack","_trackSelectionModeHighestEfficiency","_trackSelectionModeWidestRange","tracksForType","getSavedMediaSettings","image","mediaTracks","isCurrentTrack","setCustomInitialTrackSelectionFunction","customFunc","saveTextSettingsDisabled","Node","_baseUrls","_selectedIdx","selectedIdx","BaseURLTreeModel","objectUtils","updateChildData","getBaseURLCollectionsFromManifest","pi","ai","ri","getForPath","nodes","invalidateSelectedIndexes","walk","DVBSelector","blacklistController","select","availableUrls","rn","totalWeight","cumulWeights","every","limit","selectByWeight","removedPriorities","BasicSelector","selectedBaseUrl","BaseURLSelector","serviceLocationBlacklistController","basicSelector","dvbSelector","selector","chooseSelector","isDVB","BaseURLController","baseURLTreeModel","baseURLSelector","onBlackListChanged","getIsDVB","TextRequest","XlinkLoader","urlLoader","resolveObject","report","content","resolveToZero","resolved","resolvedContent","XlinkController","iron","xlinkLoader","elements","resolveType","onXlinkAllElementsLoaded","originalContent","onXlinkElementLoaded","mergedContent","elementsToResolve","isResolvingFinished","resolvedElements","parentElement","mergeElementsBack","getElementsToResolve","xlinkObject","toResolve","createXlinkObject","resolveManifestOnLoad","setMatchers","setIron","ManifestLoader","xlinkController","mssHandler","onXlinkReady","textStatus","actualUrl","createMssParser","DashParser","createParser","getMatchers","getIron","originalManifest","errorText","ErrorHandler","CapabilitiesFilter","customCapabilitiesFilters","_filterUnsupportedCodecs","as","configurations","frameRate","_createVideoConfiguration","samplerate","audioSamplingRate","_createAudioConfiguration","_createConfiguration","_","_filterUnsupportedRepresentationsOfAdaptation","_filterUnsupportedAdaptationSetsOfPeriod","_filterUnsupportedEssentialProperties","customFilter","_applyCustomFilters","setCustomCapabilitiesFilters","customFilters","URIFragmentData","xywh","URIFragmentModel","URIFragmentDataVO","uri","hashIndex","fragment","equalIndex","ManifestModel","PRIORITY","DEFAULT","STRONG","WEAK","SwitchRequest","q","getPriority","NO_CHANGE","ThroughputRule","getMaxIndex","rulesContext","switchRequest","getMediaType","currentBufferState","getCurrentBufferState","getAbrController","throughputHistory","getAverageLatency","useBufferOccupancyABR","InsufficientBufferRule","bufferStateDict","ignoreCount","shouldIgnore","AbandonRequestsRule","fragmentDict","abandonDict","throughputArray","shouldAbandon","getCurrentRequest","fragmentInfo","firstByteTime","elapsedTime","storeLastRequestThroughputByType","totalSampledValue","measuredBandwidthInKbps","estimatedTimeOfDownload","bytesRemaining","minQuality","fragmentID","DroppedFramesRule","droppedFramesHistory","getDroppedFramesHistory","dfh","getFrameHistory","droppedFrames","totalFrames","maxIndex","droppedVideoFrames","totalVideoFrames","SwitchHistoryRule","switchRequestHistory","getSwitchHistory","switchRequests","getSwitchRequests","drops","noDrops","dropSize","BolaRule","bolaStateDict","calculateBolaParameters","bitrates","utilities","highestUtilityIndex","highestIndex","uIndex","bufferTime","gp","Vp","getInitialBolaState","initialState","utilitiesFromBitrates","lastQuality","clearBolaStateOnSeek","bolaState","placeholderBuffer","mostAdvancedSegmentStart","lastSegmentWasReplacement","lastSegmentStart","lastSegmentDurationS","lastSegmentRequestTimeMs","lastSegmentFinishTimeMs","checkBolaStateStableBufferTime","effectiveBufferLevel","maxBufferLevelForQuality","minBufferLevelForQuality","qBitrate","qUtility","iBitrate","iUtility","onBufferEmpty","onPlaybackSeeking","onMediaFragmentLoaded","checkNewSegment","onMetricAdded","bufferAtLastSegmentRequest","maxEffectiveBufferForLastSegment","maxPlaceholderBuffer","onQualityChangeRequested","abrQuality","onFragmentLoadingAbandoned","wantEffectiveBufferLevel","getBolaState","safeThroughput","nowMs","lastCallTimeMs","updatePlaceholderBuffer","bitrateCount","score","getQualityFromBufferLevel","qualityForThroughput","delayS","L2ARule","l2AStateDict","l2AParameterDict","_getInitialL2AState","w","prev_w","Q","segment_request_start_s","segment_download_finish_s","B_target","_initializeL2AParameters","_clearL2AStateOnSeek","l2AState","l2aState","l2AParameters","_checkNewSegment","L2AState","_onQualityChangeRequested","_dotmultiplication","arr1","arr2","sumdot","vl","alpha","sqrt","useL2AABR","getVideoModel","_getL2AState","l2AParameter","diff1","throughputMeasureTime","getCurrentHttpRequest","downloadBytes","lastthroughput","V","sign","bget","ii","tmpsum","tmax","euclideanProjection","temp","WEIGHT_SELECTION_MODES","LearningAbrController","somBitrateNeurons","bitrateNormalizationFactor","latencyNormalizationFactor","weights","sortedCenters","weightSelectionMode","_getMaxThroughput","maxThroughput","neuron","_getDistance","_getNeuronDistance","rebuffer","_updateNeurons","winnerNeuron","somElements","somNeuron","neuronDistance","_updateNeuronState","exp","neighbourHood","_dynamicWeightSelection","dynamicWeightsSelector","currentLatency","currentThroughput","weightVector","findWeightVector","getNextQuality","bufferSize","currentQualityIndex","bitrateVector","magnitude","switch","centers","randomDataSet","dataArray","_getRandomData","distanceWeights","nextPoint","maxDistance","currentPoint","minDistance","leastSimilarIndex","minIndex","_getInitialKmeansPlusPlusCenters","_getSomBitrateNeurons","throughputNormalized","currentNeuron","downloadTime","getSegmentDuration","getMinBuffer","maxSuitableBitrate","_getDownShiftNeuron","neuronCount","weightCount","W","upperBound","_getXavierWeights","_randomWeightSelection","somNeuronState","somData","nextBuffer","getNextBufferWithBitrate","isBufferLow","bitrateSwitch","QoeInfo","bitrateReward","bitrateSwitchPenalty","rebufferPenalty","latencyPenalty","playbackSpeedPenalty","bitrateWSum","bitrateSwitchWSum","rebufferWSum","latencyWSum","playbackSpeedWSum","totalQoe","LoLpQoeEvaluator","voPerSegmentQoeInfo","maxBitrateKbps","minBitrateKbps","_createQoeInfo","fragmentType","qoeInfo","penalty","_logMetricsInQoeInfo","rebufferTime","playbackSpeed","latencyRange","setupPerSegmentQoe","sDuration","maxBrKbps","minBrKbps","logSegmentMetrics","segmentBitrate","segmentRebufferTime","currentPlaybackSpeed","getPerSegmentQoe","calculateSingleUseQoe","singleUseQoeInfo","LoLpWeightSelector","weightOptions","previousLatency","targetLatency","bufferMin","qoeEvaluator","getNextBuffer","bitrateToDownload","neurons","currentRebuffer","maxQoE","winnerWeights","winnerBitrate","weightsObj","weightedRebuffer","weightedLatency","totalQoE","nextLatency","_checkConstraints","generate","perm","currLen","currPerm","val","LoLPRule","learningController","currentQuality","bufferStateVO","useLoLPABR","currentBitrateKbps","lastFragmentDownloadTime","ABRRulesCollection","qualitySwitchRules","abandonFragmentRules","_getRulesWithChange","srArray","sr","getMinSwitchRequest","newSwitchReq","getABRCustomRules","rule","rules","getMaxQuality","shouldAbandonFragment","getQualitySwitchRules","QUALITY_SWITCH_RULES","ABANDON_FRAGMENT_RULES","MediaPlayerModel","UTCTimingSources","xhrWithCredentials","customABRRule","findABRCustomRuleIndex","rulename","addUTCTimingSource","removeUTCTimingSource","vo","addABRCustomRule","removeABRCustomRule","lowLatencyMultiplyFactor","lowLatencyReductionFactor","liveCatchupMinDrift","maximumLiveDelay","clearDefaultUTCTimingSources","restoreDefaultUTCTimingSources","defaultUtcTimingSource","setXHRWithCredentialsForType","useCreds","default","RulesContext","switchHistory","currentRequest","bufferOccupancyABR","l2AABR","loLP","SwitchRequestHistory","srHistory","newValue","oldValue","indexDiff","drop","noDrop","srHistoryFirst","DroppedFramesHistory","lastDroppedFrames","lastTotalFrames","intervalDroppedFrames","intervalTotalFrames","clearForStream","ThroughputHistory","throughputDict","latencyDict","ewmaThroughputDict","ewmaLatencyDict","ewmaHalfLife","updateEwmaEstimate","ewmaObj","halfLife","fastAlpha","fast","fastEstimate","slowAlpha","slow","slowEstimate","getAverage","isThroughput","throughputHalfLife","latencyHalfLife","getAverageEwma","ratio","getSampleSize","elem","getAverageSlidingWindow","checkSettingsForMediaType","latencyTimeInMilliseconds","downloadTimeInMilliseconds","sumOfThroughputValues","latencyMs","downloadTimeMs","isCachedResponse","hasCachedEntries","clearSettingsForMediaType","average","AbrController","abrRulesCollection","topQualities","qualityDict","streamProcessorDict","abandonmentStateDict","abandonmentTimeout","windowResizeEventCalled","elementWidth","elementHeight","playbackIndex","switchHistoryDict","isUsingBufferOccupancyAbrDict","isUsingL2AAbrDict","isUsingLoLPAbrDict","confidence","setPlaybackQuality","_onQualityChangeRendered","switchOnThreshold","switchOffThreshold","useBufferABR","newUseBufferABR","_updateDynamicAbrStrategy","setElementSize","newIdx","_checkPortalSize","maxIdx","_checkMaxRepresentationRatio","_getMaxIndexBasedOnBitrateFor","_checkMaxBitrate","_getMinIndexBasedOnBitrateFor","topQualityIdx","_changeQuality","_getBitrateInfoForQuality","setSavedBitrateSettings","deadTimeRatio","infoList","pixelRatio","devicePixelRatio","getClientWidth","getClientHeight","audioQuality","videoQuality","savedBitrate","getSavedBitrateSettings","configBitrate","configRatio","currentValue","setWindowResizeEventCalled","strategy","_initializeAbrStrategy","QUALITY_DEFAULT","READY_STATES_TO_EVENT_NAMES","Map","VideoModel","TTMLRenderingDiv","stalledStreams","onPlaybackCanPlay","onPlaying","document","createEvent","initEvent","eventName","eventCallBack","getTextTrack","kind","label","isTTML","textTracks","targetReadyState","func","_listenOnce","closestTime","closestDistance","distanceToStart","distanceToEnd","stickTimeToBuffered","INVALID_STATE_ERR","autoplay","paused","seeking","ignoreReadyState","played","addStalledStream","removeStalledStream","stallStream","setElement","preload","removeAttribute","getSource","getTTMLRenderingDiv","setTTMLRenderingDiv","div","position","display","overflow","pointerEvents","top","left","getVideoPlaybackQuality","webkitDroppedFrameCount","webkitDecodedFrameCount","creationTime","clientWidth","clientHeight","getTextTracks","addTextTrack","appendChild","childElement","removeChild","getVideoWidth","videoWidth","getVideoHeight","videoHeight","getVideoRelativeOffsetTop","parentNode","host","getBoundingClientRect","getVideoRelativeOffsetLeft","legacyKeysAndReplacements","oldKey","newKey","DOMStorage","isSupported","storage","setItem","removeItem","getTimestamp","canStore","storageType","localStorage","getItem","isExpired","timestamp","mediaSettings","SegmentBaseLoader","onLoaded","getFragmentRequest","setInfo","loadInitialization","_loadInitializationRecursively","loadingInfo","searching","bytesToLoad","loadSegments","_loadSegmentsRecursively","hasRange","extraBytes","loadedLength","loadMultiSidx","ref","se","segs","tmpCallback","refs","getSegmentsForSidx","lastBox","EBMLParser","consumeTag","tag","bytesConsumed","required","getMatroskaCodedNum","retainMSB","bytesUsed","mask","num","ch","getPos","setPos","consumeTagAndSize","parseTag","skipOverElement","headerSize","getMatroskaFloat","outFloat","getFloat32","getFloat64","getMatroskaUint","moreData","WebmSegmentBaseLoader","WebM","parseSegments","segmentStart","segmentEnd","parsed","cue","cueTrack","cues","ebmlParser","Cues","CuePoint","CueTime","CueTracks","CueTrackPositions","cueTrackPositionSize","Track","CueTrack","ClusterPosition","CueClusterPosition","parseCues","theRange","EBML","Info","SeekHead","Tracks","Void","infoTag","infoElementSize","Duration","parseEbmlHeader","TimecodeScale","SegmentBaseController","segmentBaseLoader","webmSegmentBaseLoader","isWebM","RepresentationInfo","MediaInfo","labels","KID","StreamInfo","ManifestInfo","availableFrom","SimpleXPath","valid","component","qualifierPoint","qualifier","equalityPoint","attribute","findsAttribute","isSiblingOperation","leaf","elm","PatchOperation","xpath","getMpdTarget","PatchManifestModel","getOriginalPublishTime","getMpdId","getPatchOperations","nodeContainer","sel","isValid","groups","operation","DashAdapter","patchManifestModel","cea608parser","allMediaInfoForType","mInfoOne","mInfoTwo","_getAllMediaInfo","embeddedText","mediaArr","convertAdaptationToMediaInfo","accessibilityLength","convertVideoInfoToEmbeddedTextInfo","externalManifest","voLocalPeriods","selectedVoPeriod","getPeriodForStreamInfo","adaptationsForType","getManifest","getAdaptationForMediaInfo","voPeriodsArray","convertPeriodToStreamInfo","accessibilityValue","accessibilityData","search","embeddedCaptions","keyIds","cp","kid","keyId","isText","getPeriod","periodIdx","findRepresentation","returnIndex","adaptationSetArray","adaptationSetArrayIndex","representationArrayIndex","getBandwidthForRepresentation","getIndexForRepresentation","findRepresentationIndex","getMaxIndexForBufferType","bufferType","adaptationSet","findMaxBufferIndex","maxStreamsInfo","getRealPeriodByIndex","eventBox","newManifest","getPeriodById","periods","manifestId","patchManifestId","manifestPublishTime","patchPublishTime","originalManifestPublishTime","relativePosition","insertBefore","targetArray","insert","insertNodes","updatedNodes","Round10","_decimalAdjust","MetricsList","TcpList","HttpList","RepSwitchList","BufferLevel","BufferState","DroppedFrames","SchedulingInfo","DVRInfo","ManifestUpdate","RequestsQueue","DVBErrors","RepresentationSwitch","mt","lto","fetchTime","ManifestUpdateStreamInfo","ManifestUpdateRepresentationInfo","streamIndex","fragmentInfoType","MetricsModel","streamMetrics","metricsChanged","metricChanged","metricUpdated","metricType","metricAdded","getMetricsFor","readOnly","pushMetrics","pushAndNotify","metricObject","clearCurrentMetricsForType","tfinish","mediaduration","appendHttpTrace","addRepresentationSwitch","TrackSwitch","manifestUpdate","updatedFields","addManifestUpdateRepresentationInfo","addDVBErrors","DashMetrics","playListTraceMetricsClosed","playListTraceMetrics","playListMetrics","metricsModel","httpListLastIndex","httpList","currentHttpList","getHttpRequests","getCurrent","metricName","getCurrentRepresentationSwitch","round10","getCurrentDroppedFrames","getCurrentManifestUpdate","getLatestFragmentRequestHeaderValueByID","parseHttpHeaders","httpRequestList","manifestUpdateInfo","speed","traceToUpdate","endTime","TimelineConverter","timelineAnchorAvailabilityOffset","clientServerTimeShift","setClientTimeOffset","_calcAvailabilityTimeFromPresentationTime","calculateAvailabilityEndTime","availabilityTime","calcPresentationTimeFromWallTime","wallTime","mediaTime","_calcTimeShiftBufferWindowForDynamicTimelineManifest","periodRange","_calcRangeForTimeline","currentVoPeriod","adjustedEndTime","_adjustTimeBasedOnPeriodRanges","_adjustTimelineAnchorAvailabilityOffset","isEndOfDvrWindow","_onUpdateTimeSyncOffset","mpdRelativeTime","displayStartTime","_calcTimeshiftBufferForStaticManifest","timelineRefData","_calcTimeShiftBufferWindowForDynamicManifest","TextTrackInfo","captionData","defaultTrack","EmbeddedTextHtmlRender","captionId","checkIndent","line","getRegionProperties","region","y1","y2","createRGB","getStyle","videoElement","fontSize","ltrim","rtrim","createHTMLCaptionsFromScreen","captionScreen","currRegion","lastRowHasText","lastRowIndentL","currP","spans","currentStyle","seenRegions","styleStates","regions","prevPenState","rowIndent","contat","uc","currPenStateString","captionsArray","cueID","finalDiv","createElement","cueRegionProperties","cssText","bodyDiv","cueUniWrapper","ptag","lastSpanRow","span","brElement","sameRow","spanStyle","spanElement","textContent","cueHTMLElement","cellResolution","isFromCEA608","lineHeight","linePadding","TextSourceBuffer","mediaInfos","initializationSegmentReceived","fragmentedTracks","firstFragmentedSubtitleStart","currFragmentedTrackIdx","embeddedTracks","embeddedTimescale","embeddedLastSequenceNumber","embeddedCea608FieldParsers","embeddedTextHtmlRender","vttParser","ttmlParser","embeddedInitialized","_createTextTrackFromMediaInfo","textTrackInfo","getIsDefault","_checkTtml","trackKindMap","caption","subtitle","_getKind","_onVideoChunkReceived","setCurrentFragmentedTrackIdx","codecType","samplesInfo","cts","getParser","sampleStart","_getTimestampOffset","ccContent","images","subOffset","inData","offsetTime","ttmlTimeIsRelative","addCaptions","_appendFragmentedSttp","captionArray","sampleBoxes","box1","box2","cue_text","start_time","end_time","_appendFragmentedWebVtt","_appendFragmentedText","sequenceNumber","trackIdx","getTrackIdxForId","_makeCueAdderForIndex","_setupCeaParser","allCcData","splits","fields","cea608Ranges","lastSampleTime","ccData","_extractCea608Data","fieldNr","fieldParser","_appendEmbeddedText","getCurrentTrackIdx","_appendText","trackIndex","onVideoBufferCleared","deleteCuesFromTrackIdx","addMediaInfos","mInfos","fModel","currFragTrack","resetMediaInfos","resetEmbedded","deleteAllTextTracks","getConfig","TextTracks","Cue","textTrackQueue","nativeTrackElementArr","currentTrackIdx","actualVideoLeft","actualVideoTop","actualVideoWidth","actualVideoHeight","captionContainer","videoSizeCheckInterval","fullscreenAttribute","displayCCOnTop","previousISDState","topZIndex","resizeObserver","getVideoVisibleVideoSize","viewWidth","viewHeight","aspectRatio","use80Percent","videoPictureWidth","videoPictureHeight","videoPictureXAspect","videoPictureYAspect","videoPictureWidthAspect","videoPictureHeightAspect","h","checkVideoSize","forceDrawing","videoOffsetTop","videoOffsetLeft","realVideoSize","newVideoWidth","newVideoHeight","newVideoLeft","newVideoTop","containerStyle","zIndex","activeCues","scaleCue","activeCue","replaceValue","valueFontSize","valueLineHeight","cellUnit","elementsSpan","getElementsByClassName","isd","htmlCaptionDiv","getElementById","renderCaption","finalCue","imsc1ImgUrnTester","smpteImgUrnTester","imageId","btoa","embeddedImages","captionDiv","getTrackByIdx","currentItem","align","onenter","onexit","divs","cueInTrack","addCue","deleteTrackCues","setCurrentTrackIdx","setCueStyleOnTrack","renderingType","ResizeObserver","observe","clearCaptionContainer","setNativeCueStyle","removeNativeCueStyle","cueInRange","removeCue","styleElement","head","stylesheet","sheet","insertRule","classList","firstChild","VTTCue","TextTrackCue","fullscreenElement","webkitIsFullScreen","msFullscreenElement","mozFullScreen","textTrackInfoVO","defaultIndex","textTrack","onMetadataLoaded","videoTextTrack","trackId","getCurrentTrackInfo","setModeForTrackIdx","unobserve","deleteTextTrack","VTTParser","regExNewLine","regExToken","regExWhiteSpace","regExWhiteSpaceWordBoundary","convertCuePointTimes","timeArray","parseItemAttributes","vttCuePoints","cuePoints","getCaptionStyles","styleObject","getSublines","lineCount","subline","lineData","lastStartTime","TTMLParser","cueCounter","startTimeSegment","endTimeSegment","errorMsg","currentImageId","accumulated_image_data","metadataHandler","onOpenTag","attrs","onCloseTag","onText","contents","imsc1doc","ttmlString","ttmlDoc","mediaTimeEvents","getMediaTimeEvents","topLevelContents","TextController","streamData","textSourceBuffers","initialSettingsSet","allTracksAreDisabled","forceTextStreaming","textTracksAdded","disableTextBeforeTextTracksAdded","_onTextTracksAdded","lastEnabledIndex","oldTrackIdx","currentFragTrack","_setFragmentedTextTrack","_setNonFragmentedTextTrack","textSourceBuffer","getAllTracksAreDisabled","enableText","enable","enableForcedTextStreaming","MediaPlayer","mediaPlayerInitialized","streamingInitialized","playbackInitialized","metricsReportingController","offlineController","gapController","licenseRequestFilters","licenseResponseFilters","STREAMING_NOT_INITIALIZED_ERROR","PLAYBACK_NOT_INITIALIZED_ERROR","ELEMENT_NOT_ATTACHED_ERROR","attachSource","attachView","isReady","getVersionString","getDVRSeekOffset","getVideoElement","setAutoPlay","getDashMetrics","_detectProtection","MetricsReporting","dashjs","metricsReporting","createMetricsReporting","mediaElement","metricsConstants","_detectMetricsReporting","MssHandler","initSegmentType","_detectMss","_resetPlaybackControllers","_initializePlayback","unregisterFilter","urlOrManifest","stop","_createManifestLoader","Protection","createProtectionSystem","setLicenseRequestFilters","setLicenseResponseFilters","_detectOffline","OfflineController","_getAsUTC","valToConvert","resetRecords","view","AutoPlay","parentNameString","setMute","muted","isMuted","setVolume","volume","getVolume","timeAsUTC","durationAsUTC","getDVRWindowSize","convertToTimeCode","formatUTC","locales","hour12","withDate","toLocaleDateString","toLocaleTimeString","getDebug","setQualityFor","updatePortalSize","getBitrateInfoListFor","getStreamsFromManifest","getTracksForTypeFromManifest","setInitialMediaSettingsFor","getInitialMediaSettingsFor","setCurrentTrack","removeAllABRCustomRule","retrieveManifest","getProtectionController","attachProtectionController","registerLicenseRequestFilter","registerLicenseResponseFilter","unregisterLicenseRequestFilter","unregisterLicenseResponseFilter","registerCustomCapabilitiesFilter","unregisterCustomCapabilitiesFilter","resetCustomInitialTrackSelectionFunction","attachTTMLRenderingDiv","getCurrentTextTrackIndex","provideThumbnail","timeInPeriod","getDashAdapter","getOfflineController","getSettings","updateSettings","resetSettings","destroy","T","encodeArray","R","ASCII","encodeASCII","decodeASCII","voAvailableRepresentations","currentVoRepresentation","_updateRepresentation","currentRep","_onInitLoaded","_onSegmentsLoaded","repInfo","alreadyAdded","isAllRepresentationsUpdated","_addRepresentationSwitch","endDataUpdate","_onRepresentationUpdated","currentVideoTimeMs","numberOfRepresentations","_setCurrentVoRepresentation","onManifestValidityChanged","availableRepresentations","keyList","hasProp","arrA","arrB","dateA","dateB","regexpA","regexpB","ObjectIron","mappers","mergeValues","parentItem","childItem","mapProperties","properties","parentValue","childValue","mapItem","len2","childNode","periodMapper","adaptationSets","adaptationSetMapper","adaptationset","BaseMatcher","_test","_converter","StringMatcher","stringAttrsInElements","attrNames","durationRegex","DurationMatcher","attributeList","datetimeRegex","DateTimeMatcher","numericRegex","NumericMatcher","CommonProperty","_name","_merge","MapNode","_properties","_children","RepresentationBaseValuesMap","commonProperties","SegmentValuesMap","objectIron","jsonTime","Patch","add_asArray","operand","replace_asArray","ironedTime","toPrecision","HeadRequest","checkForExistenceOnly","checkForExistence","exists","headRequest","imscStyles","imscUtils","StylingAttributeDefinition","initialValue","appliesTo","isInherit","isAnimatable","parseFunc","computeFunc","qname","inherit","animatable","initial","applies","compute","parseColor","parseLength","doc","unit","pxDimensions","ffs","rslt","fs","styleAttrs","byName","lh","writingMode","out","extent","thickness","byQName","base64","ieee754","kMaxLength","TYPED_ARRAY_SUPPORT","createBuffer","that","RangeError","__proto__","fromArrayLike","fromArrayBuffer","isEncoding","actual","fromString","checked","fromObject","assertSize","isView","loweredCase","utf8ToBytes","base64ToBytes","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","bidirectionalIndexOf","arrayIndexOf","indexSize","arrLength","valLength","readUInt16BE","foundIndex","hexWrite","strLen","utf8Write","blitBuffer","asciiWrite","byteArray","asciiToBytes","latin1Write","base64Write","ucs2Write","units","hi","lo","utf16leToBytes","fromByteArray","thirdByte","fourthByte","tempCodePoint","firstByte","codePoint","bytesPerSequence","codePoints","decodeCodePointsArray","INSPECT_MAX_BYTES","global","foo","typedArraySupport","poolSize","_augment","species","_isBuffer","compare","swap16","swap32","swap64","inspect","thisStart","thisEnd","thisCopy","targetCopy","includes","toJSON","_arr","toHex","checkOffset","checkInt","objectWriteUInt16","littleEndian","objectWriteUInt32","checkIEEE754","writeFloat","noAssert","writeDouble","newBuf","sliceLen","readUIntLE","mul","readUIntBE","readUInt8","readUInt16LE","readUInt32LE","readUInt32BE","readIntLE","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","readFloatBE","readDoubleLE","readDoubleBE","writeUIntLE","writeUIntBE","writeUInt8","writeUInt16LE","writeUInt16BE","writeUInt32LE","writeUInt32BE","writeIntLE","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32LE","writeInt32BE","writeFloatLE","writeFloatBE","writeDoubleLE","writeDoubleBE","targetStart","INVALID_BASE64_RE","leadSurrogate","toByteArray","stringtrim","base64clean","ReflectOwnKeys","Reflect","ReflectApply","receiver","ownKeys","getOwnPropertySymbols","getOwnPropertyNames","NumberIsNaN","EventEmitter","emitter","errorListener","resolver","eventTargetAgnosticAddListener","addErrorHandlerIfEventEmitter","_events","_eventsCount","_maxListeners","defaultMaxListeners","checkListener","_getMaxListeners","_addListener","prepend","existing","warning","newListener","warned","onceWrapper","fired","wrapFn","_onceWrap","wrapped","_listeners","unwrap","evlistener","unwrapListeners","arrayClone","listenerCount","wrapListener","getPrototypeOf","setMaxListeners","getMaxListeners","doError","er","originalListener","spliceOne","rawListeners","eventNames","Transform","PassThrough","CorkedRequest","finish","corkReq","pendingcb","corkedRequestsFree","onCorkedFinish","asyncWrite","setImmediate","WritableState","internalUtil","deprecate","OurUint8Array","realHasInstance","destroyImpl","nop","isDuplex","objectMode","writableObjectMode","hwm","writableHwm","writableHighWaterMark","defaultHwm","finalCalled","needDrain","ending","finished","noDecode","decodeStrings","defaultEncoding","writing","corked","sync","bufferProcessing","onwrite","writecb","writelen","onwriteStateUpdate","finishMaybe","errorEmitted","onwriteError","needFinish","bufferedRequest","clearBuffer","afterWrite","lastBufferedRequest","prefinished","bufferedRequestCount","_write","writev","_writev","final","_final","doWrite","onwriteDrain","holder","allBuffers","isBuf","callFinal","need","prefinish","hasInstance","pipe","_uint8ArrayToBuffer","writeAfterEnd","validChunk","newChunk","decodeChunk","writeOrBuffer","cork","uncork","setDefaultEncoding","endWritable","_undestroy","undestroy","StringDecoder","nb","enc","nenc","retried","_normalizeEncoding","normalizeEncoding","utf16Text","utf16End","fillLast","utf8FillLast","base64Text","base64End","simpleWrite","simpleEnd","lastNeed","lastTotal","lastChar","utf8CheckByte","utf8CheckExtraBytes","utf8CheckIncomplete","HEX_COLOR_RE","DEC_COLOR_RE","DEC_COLORA_RE","NAMED_COLOR","transparent","black","silver","gray","white","maroon","red","purple","fuchsia","magenta","green","lime","olive","yellow","navy","blue","teal","aqua","cyan","nc","LENGTH_RE","ReadableState","EElistenerCount","debugUtil","debuglog","BufferList","kProxyEvents","readableObjectMode","readableHwm","readableHighWaterMark","pipes","pipesCount","flowing","endEmitted","reading","needReadable","emittedReadable","readableListening","resumeScheduled","awaitDrain","readingMore","_read","readableAddChunk","addToFront","skipChunkCheck","emitReadable","onEofChunk","chunkInvalid","addChunk","maybeReadMore","needMoreData","setEncoding","howMuchToRead","computeNewHighWaterMark","emitReadable_","flow","maybeReadMore_","nReadingNextTick","resume_","fromList","hasStrings","tail","copyFromBufferString","copyFromBuffer","fromListPartial","endReadable","endReadableNT","nOrig","doRead","pipeOpts","endFn","stdout","stderr","unpipe","onunpipe","unpipeInfo","hasUnpiped","onclose","onfinish","ondrain","ondata","cleanedUp","pipeOnDrain","increasedAwaitDrain","resume","dests","ev","wrap","_fromList","emitErrorNT","readableDestroyed","writableDestroyed","afterTransform","_transformState","transforming","writechunk","rs","needTransform","writeencoding","transform","_transform","flush","_flush","_this2","err2","LICENSE_SERVER_MANIFEST_CONFIGURATIONS","prefixes","CommonEncryption","cpArray","retVal","pssh","keySystem","initData","psshList","parsePSSHList","uuid","cpData","dv","byteCursor","nextBox","systemID","boxStart","licenseServer","targetProtectionData","ckData","MediaCapability","robustness","KeySystemConfiguration","audioCapabilities","videoCapabilities","distinctiveIdentifier","persistentState","sessionTypes","initDataTypes","protectionErrors","MEDIA_KEYERR_CODE","MEDIA_KEYERR_UNKNOWN_CODE","MEDIA_KEYERR_CLIENT_CODE","MEDIA_KEYERR_SERVICE_CODE","MEDIA_KEYERR_OUTPUT_CODE","MEDIA_KEYERR_HARDWARECHANGE_CODE","MEDIA_KEYERR_DOMAIN_CODE","MEDIA_KEY_MESSAGE_ERROR_CODE","MEDIA_KEY_MESSAGE_NO_CHALLENGE_ERROR_CODE","SERVER_CERTIFICATE_UPDATED_ERROR_CODE","KEY_STATUS_CHANGED_EXPIRED_ERROR_CODE","MEDIA_KEY_MESSAGE_NO_LICENSE_SERVER_URL_ERROR_CODE","KEY_SYSTEM_ACCESS_DENIED_ERROR_CODE","KEY_SESSION_CREATED_ERROR_CODE","MEDIA_KEY_MESSAGE_LICENSER_ERROR_CODE","MEDIA_KEYERR_UNKNOWN_MESSAGE","MEDIA_KEYERR_CLIENT_MESSAGE","MEDIA_KEYERR_SERVICE_MESSAGE","MEDIA_KEYERR_OUTPUT_MESSAGE","MEDIA_KEYERR_HARDWARECHANGE_MESSAGE","MEDIA_KEYERR_DOMAIN_MESSAGE","MEDIA_KEY_MESSAGE_ERROR_MESSAGE","MEDIA_KEY_MESSAGE_NO_CHALLENGE_ERROR_MESSAGE","SERVER_CERTIFICATE_UPDATED_ERROR_MESSAGE","KEY_STATUS_CHANGED_EXPIRED_ERROR_MESSAGE","MEDIA_KEY_MESSAGE_NO_LICENSE_SERVER_URL_ERROR_MESSAGE","KEY_SYSTEM_ACCESS_DENIED_ERROR_MESSAGE","KEY_SESSION_CREATED_ERROR_MESSAGE","MEDIA_KEY_MESSAGE_LICENSER_ERROR_MESSAGE","LicenseRequest","messageType","sessionId","LicenseResponse","ProtectionController","pendingKeySystemData","protDataSet","sessionType","robustnessLevel","selectedKeySystem","keySystemSelectionInProgress","protectionKeyController","protectionModel","needkeyRetries","_selectKeySystem","supportedKS","fromManifest","ksIdx","ks","_loadOrCreateKeySession","_initiateWithExistingKeySystem","keySystemAccess","requestedKeySystems","keySystemConfiguration","_getKeySystemConfiguration","configs","requestKeySystemAccess","selectedSystemString","mksa","systemString","selectKeySystem","_getProtDataForKeySystem","serverCertificate","setServerCertificate","ProtectionErrors","_selectInitialKeySystem","keySystemInfo","isClearKey","kids","clearkeys","loadKeySession","createKeySession","initDataForKS","getPSSHForKeySystem","sessions","getSessions","getKeyId","_isKeyIdDuplicate","_isInitDataDuplicate","keySystemString","currentInitData","getAllInitData","initDataEquals","NEED_KEY","_onNeedKey","keySystemData","audioRobustness","videoRobustness","ksSessionType","_onKeyStatusChanged","_onKeyMessage","keyMessage","KEY_MESSAGE","sessionToken","licenseServerModelInstance","getLicenseServerModelInstance","eventData","getSessionId","_sendLicenseRequestCompleteEvent","processClearKeyLicenseRequest","updateKeySession","licenseServerData","serverURL","laURL","getLicenseServerUrlFromMediaInfo","schemeIdURI","psshData","getPSSHData","getLicenseServerURLFromInitData","getServerURLFromMessage","_getLicenseServerUrl","reqHeaders","_updateHeaders","httpRequestHeaders","headersFromMessage","getRequestHeadersFromMessage","onLoad","licenseResponse","_applyFilters","licenseMessage","getLicenseMessage","_reportError","onAbort","onError","reqPayload","getLicenseRequestFromMessage","reqMethod","getHTTPMethod","getResponseType","httpTimeout","licenseRequest","_doLicenseRequest","retriesCount","cmcdParams","cmcdHeaders","_retryRequest","retryInterval","LICENSE_REQUEST_SENDING","_issueLicenseRequest","getErrorResponse","retry","initDataType","abInitData","getSupportedKeySystemsFromSegmentPssh","getSupportedKeySystemsFromContentProtection","ksA","ksB","removeKeySession","closeKeySession","setSessionType","setRobustnessLevel","cps","getKeySystems","setKeySystems","keySystems","INTERNAL_KEY_MESSAGE","INTERNAL_KEY_STATUS_CHANGED","retryTimeout","KeyPair","keyID","ClearKeyKeySet","keyPairs","numKeys","jwk","kty","alg","jwkString","bView","CLEARKEY_KEYSTEM_STRING","WIDEVINE_KEYSTEM_STRING","PLAYREADY_KEYSTEM_STRING","PLAYREADY_RECOMMENDATION_KEYSTEM_STRING","INITIALIZATION_DATA_TYPE_CENC","INITIALIZATION_DATA_TYPE_KEYIDS","INITIALIZATION_DATA_TYPE_WEBM","ProtectionConstants","KeySystemClearKey","getInitData","cencContentProtection","parseInitDataFromContentProtection","cencDefaultKid","cencDefaultKidToBase64Representation","getCDMData","getClearKeysFromProtectionData","clearkeySet","jsonMsg","clearkeyID","clearkey","KeySystemW3CClearKey","KeySystemWidevine","KeySystemPlayReady","messageFormat","PROSize","PSSHSize","PSSHBoxBuffer","PSSHBox","PSSHData","PSSHBoxType","playreadySystemID","uint8arraydecodedPROHeader","pro","prheader","dataview","Uint16Array","headerNameList","getElementsByTagName","headerValueList","Content","Challenge","numRecords","recordType","recordLength","recordData","record","laurl","luiurl","_cdmData","customData","cdmData","cdmDataBytes","setPlayReadyMessageFormat","format","DRMToday","license","keySystemStr","serverResponse","PlayReady","soap","uintToString","encodedString","decodeURIComponent","escape","parseServerResponse","stringResponse","envelope","parseErrorResponse","faultstring","statusCode","idStart","idEnd","fault","detail","exception","errorString","Widevine","ClearKey","keypair","keyid","ProtectionKeyController","clearkeyKeySystem","clearkeyW3CKeySystem","_getSessionId","_getSessionType","protectionDataSet","initData1","initData2","data1","data2","newKeySystems","getKeySystemBySystemString","cpIdx","findCencContentProtection","protectionEvents","KEY_ADDED","KEY_SESSION_CLOSED","KEY_SESSION_REMOVED","KEY_SYSTEM_ACCESS_COMPLETE","TEARDOWN_COMPLETE","VIDEO_ELEMENT_SELECTED","NeedKey","KeyMessage","defaultURL","KeySystemAccess","ksConfiguration","SYSTEM_STRING_PRIORITY","ProtectionModel_21Jan2015","mediaKeys","eventHandler","_closeKeySessionInternal","session","close","removeSession","parseKeyStatus","createSessionToken","ksInfo","handleEvent","keyStatuses","keyStatus","getSessionType","getExpirationTime","expiration","getKeyStatuses","getUsable","usable","ksConfigurations","_requestKeySystemAccessInternal","requestMediaKeySystemAccess","protDataSystemStringPriority","systemStringPriority","currentKeySystem","systemStringsToApply","_checkAccessForSystemStrings","mediaKeySystemAccess","_checkAccessForKeySystem","getConfiguration","createMediaKeys","mkeys","setMediaKeys","createSession","dataType","generateRequest","toJWK","numSessions","ProtectionModel_3Feb2014","api","needkey","ready","release","boundDoSetKeys","doSetKeys","supportedAudio","supportedVideo","configIdx","audios","videos","audioIdx","MediaKeys","videoIdx","ksConfig","errorMessage","ksAccess","keySession","destinationURL","ProtectionModel_01b","pendingSessions","moreSessionsAllowed","removeEventListeners","cancelKeyRequest","findSessionByID","sessionArray","keyerror","keymessage","keyadded","ve","canPlayType","newSession","generateKeyRequest","addKey","errorCode","systemCode","APIS_ProtectionModel_01b","APIS_ProtectionModel_3Feb2014","_getAPI","apis","onencrypted","_getProtectionModel","ProtectionEvents","mpdurl","errorcode","terror","ipaddress","servicelocation","SSL_CONNECTION_FAILED_PREFIX","DNS_RESOLUTION_FAILED","HOST_UNREACHABLE","CONNECTION_REFUSED","CONNECTION_ERROR","CORRUPT_MEDIA_ISOBMFF","CORRUPT_MEDIA_OTHER","BASE_URL_CHANGED","BECAME_REPORTER","DVBErrorsTranslator","onManifestUpdate","onServiceLocationChanged","onBecameReporter","onMetricEvent","onPlaybackError","MediaError","MEDIA_ERR_NETWORK","MEDIA_ERR_DECODE","initialise","RangeController","useWallClockTime","starttime","_useWallClockTime","isEnabled","numRanges","MetricSerialiser","serialise","pairs","isBuiltIn","RNG","randomNumbers","crypto","msCrypto","ArrayType","Uint32Array","BYTES_PER_ELEMENT","getRandomValues","DVBReporting","metricSerialiser","randomNumberGenerator","reportingPlayerStatusDecided","isReportingPlayer","reportingUrl","rangeController","pendingRequests","vos","successCB","failureCB","reqIndex","doGetRequest","rc","probability","dvb_reportingUrl","dvb_probability","ReportingFactory","knownReportingSchemeIdUris","reporting","register","moduleName","unregister","ReportingController","reporters","reportingFactory","reporter","HandlerHelpers","reconstructFullMetricName","mn","validateN","n_ms","BufferLevelHandler","reportingController","lastReportedTime","handlerHelpers","storedVOs","intervalCallback","getLowestBufferLevelVO","handleNewMetric","onInitialisationComplete","unused","HttpListHandler","storedVos","requestType","GenericMetricHandler","MetricsHandlerFactory","keyRegex","knownFactoryProducts","listType","MetricsHandlersController","metricsHandlerFactory","handle","midx","ms","nextm","MetricsController","metricsHandlersController","metricsEntry","Range","Reporting","Metrics","ManifestParsing","getMetrics","Metrics_asArray","metricEntry","Range_asArray","rangeEntry","dynamic","reportingStartTime","getMetricsRangeStartTime","Reporting_asArray","reportingEntry","MetricsCollectionController","metricsControllers","controllersToRemove","resetMetricsControllers","getReportingFactory","getMetricsHandlerFactory","Version","imscISD","isdProcessContentElement","inherited_region_id","errorHandler","begin","associated_region_id","regionID","isd_element","ISDContentElement","sets","spec_attr","direction","wm","sa","textDecoration","ps","es","outs","ivs","z","cs","cstyle","reportError","qnameb","space","trimmedspan","elist","constructSpanList","br_pos","pruneEmptySpans","backgroundImage","showBackground","region_id","ISD","tt","ttelem","sname","layout","imscDoc","sax","resolveTiming","prev_sibling","isinseq","timeContainer","implicit_begin","explicit_begin","implicit_end","set_i","content_i","explicit_end","explicit_dur","_registerEvent","ForeignElement","TT","Head","styling","Styling","Style","styleRefs","Layout","ContentElement","IdentifiedElement","LayoutElement","StyledElement","AnimatedElement","ContainerElement","TimedElement","Body","Div","P","Span","AnonymousSpan","Br","Region","Set","elementGetXMLID","elementGetStyleRefs","elementGetStyles","local","reportWarning","findAttribute","parseTimeExpression","tickRate","effectiveFrameRate","mergeChainedStyles","sref","mergeStylesIfNotPresent","mergeReferencedStyles","stylerefs","styleattrs","from_styles","into_styles","reportFatal","searchval","cur","curval","xmlstring","xmlns","estack","xmllangstack","xmlspacestack","metadata_depth","onclosetag","ontext","initFromText","onopentag","xmlspace","xmllang","column","initFromNode","hasRegions","dr","createDefaultRegion","region_i","cr","extractCellResolution","frtr","fps_attr","fps","frm_attr","frm","efps","tr","trattr","extractFrameAndTickRate","ar","extractAspectRatio","extractExtent","b_i","e_i","getMediaTimeRange","elementGetRegionID","dur","processTiming","tc","elementGetTimeContainer","strict","opt","SAXParser","SAXStream","createStream","MAX_BUFFER_LENGTH","bufferCheckPosition","lowercase","lowercasetags","looseCase","tags","closedRoot","sawRoot","noscript","S","BEGIN","strictEntities","ENTITIES","XML_ENTITIES","attribList","rootNS","trackPosition","F","BEGIN_WHITESPACE","beginWhiteSpace","starti","textNode","not","whitespace","strictFail","TEXT_ENTITY","OPEN_WAKA","startTagPosition","SCRIPT","SCRIPT_ENDING","script","CLOSE_TAG","SGML_DECL","sgmlDecl","is","nameStart","OPEN_TAG","tagName","PROC_INST","procInstName","procInstBody","pad","emitNode","CDATA","cdata","COMMENT","comment","DOCTYPE","doctype","quote","SGML_DECL_QUOTED","DOCTYPE_DTD","DOCTYPE_QUOTED","DOCTYPE_DTD_QUOTED","COMMENT_ENDING","COMMENT_ENDED","textopts","CDATA_ENDING","CDATA_ENDING_2","PROC_INST_ENDING","PROC_INST_BODY","nameBody","newTag","openTag","OPEN_TAG_SLASH","ATTRIB","closeTag","attribName","attribValue","ATTRIB_NAME","ATTRIB_VALUE","attrib","ATTRIB_NAME_SAW_WHITE","ATTRIB_VALUE_QUOTED","ATTRIB_VALUE_UNQUOTED","ATTRIB_VALUE_ENTITY_Q","ATTRIB_VALUE_CLOSED","attribEnd","ATTRIB_VALUE_ENTITY_U","CLOSE_TAG_SAW_WHITE","returnState","parseEntity","entity","entityBody","entityStart","maxAllowed","maxActual","closeText","checkBufferLength","ex","streamWraps","_parser","me","_decoder","SD","number","letter","XML_NAMESPACE","xml","charClass","charclass","stringFromCharCode","fromCodePoint","STATE","COMMENT_STARTING","qualName","qn","selfClosing","nv","isSelfClosing","closeTo","entityLC","highSurrogate","lowSurrogate","MAX_SIZE","codeUnits","b64","lens","getLens","validLen","placeHoldersLen","Arr","_byteLength","curByte","revLookup","uint8","encodeChunk","lookup","output","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","rt","LN2","EE","_isStdio","didOnEnd","cleanup","Constructor","_classCallCheck","custom","Timeout","clearFn","_id","_clearFn","unref","enroll","msecs","_idleTimeoutId","_idleTimeout","unenroll","_unrefActive","active","_onTimeout","clearImmediate","registerImmediate","html","messagePrefix","onGlobalMessage","nextHandle","tasksByHandle","currentlyRunningATask","attachTo","runIfPresent","postMessage","importScripts","postMessageIsAsynchronous","oldOnMessage","onmessage","canUsePostMessage","MessageChannel","port1","port2","documentElement","onreadystatechange","attachEvent","task","imscHTML","processElement","dom_parent","margin","STYLING_MAP_DEFS","sm","proc_e","wdir","ipd","bpd","lp","padmeasure","paddingLeft","paddingRight","paddingTop","paddingBottom","mra","multiRowAlign","textAlign","fillLineGap","flg","cbuf","cc","linelist","constructLineList","lineList","lastnode","nextSibling","applyMultiRowAlign","start_elem","ee","end_elem","pospadpxlen","negpadpxlen","borderLeftColor","bgcolor","borderLeftStyle","borderLeftWidth","marginLeft","borderRightColor","borderRightStyle","borderRightWidth","marginRight","borderTopColor","borderTopStyle","borderTopWidth","marginTop","borderBottomColor","borderBottomStyle","borderBottomWidth","marginBottom","applyLinePadding","par_edges","rect2edges","par_before","par_after","frontier","before","after","backgroundColor","applyFillLineGap","enableRollUp","displayAlign","rb","RegionPBuffer","currentISDState","plist","body_elem","firstElementChild","bottom","transition","rect","edges","right","llist","before1","after1","before2","after2","curbgcolor","childElementCount","bpd_dir","ipd_dir","ELEMENT_NODE","HTMLStylingMapDefintion","qName","mapFunc","imgResolver","eheight","ewidth","displayForcedOnlyMode","twidth","rootcontainer","regionH","regionW","dom_element","flexDirection","justifyContent","hdelta","wdelta","fontFamily","fontStyle","fontWeight","opacity","ta","textShadow","ub","unicodeBidi","visibility","whiteSpace","img","STYLMAP_BY_QNAME","polyfill","vertxNext","customSchedulerFn","asap","scheduleFlush","browserWindow","browserGlobal","BrowserMutationObserver","MutationObserver","WebKitMutationObserver","isNode","isWorker","Uint8ClampedArray","useSetTimeout","globalSetTimeout","iterations","observer","onFulfillment","onRejection","PROMISE_ID","makePromise","_state","invokeCallback","_result","subscribe","resolve$1","createTextNode","characterData","vertx","require","runOnLoop","runOnContext","attemptVertx","handleMaybeThenable","maybeThenable","then$$1","thenable","fulfill","handleOwnThenable","sealed","fulfillmentHandler","rejectionHandler","tryThen","_label","handleForeignThenable","publishRejection","_onerror","publish","_subscribers","subscribers","settled","hasCallback","succeeded","Enumerator","input","_instanceConstructor","_remaining","_enumerate","_eachEntry","resolve$$1","_then","didError","_settledAt","Promise$1","_willSettleAt","enumerator","needsResolver","initializePromise","needsNew","catch","finally","race","_setScheduler","scheduleFn","_setAsap","asapFn","_asap","promiseToString","cast","loadInterval","_dashjs_player","player","videoID","querySelectorAll","findVideo","createAll","aPlayers","sources","MediaPlayerFactory","skipAutoCreate","loadHandler"],"mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAgB,OAAID,IAEpBD,EAAa,OAAIC,IARnB,CASGK,QAAQ,WACX,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUP,QAGnC,IAAIC,EAASI,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GAAG,EACHT,QAAS,IAUV,OANAU,EAAQH,GAAUI,KAAKV,EAAOD,QAASC,EAAQA,EAAOD,QAASM,GAG/DL,EAAOQ,GAAI,EAGJR,EAAOD,Q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iBAAmBA,UAC1BC,OAAOkkD,mBAAqBA,EAC5BlkD,OAAOp1H,MAAQA,IACfo1H,OAAOppE,oBAAsBA,IAEdopE,oB","file":"dash.all.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"dashjs\"] = factory();\n\telse\n\t\troot[\"dashjs\"] = factory();\n})(window, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"/dist/\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 104);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * Dash constants declaration\n * @class\n * @ignore\n */\nclass DashConstants {\n\n init() {\n this.BASE_URL = 'BaseURL';\n this.SEGMENT_BASE = 'SegmentBase';\n this.SEGMENT_TEMPLATE = 'SegmentTemplate';\n this.SEGMENT_LIST = 'SegmentList';\n this.SEGMENT_URL = 'SegmentURL';\n this.SEGMENT_TIMELINE = 'SegmentTimeline';\n this.SEGMENT_PROFILES = 'segmentProfiles';\n this.ADAPTATION_SET = 'AdaptationSet';\n this.REPRESENTATION = 'Representation';\n this.REPRESENTATION_INDEX = 'RepresentationIndex';\n this.SUB_REPRESENTATION = 'SubRepresentation';\n this.INITIALIZATION = 'Initialization';\n this.INITIALIZATION_MINUS = 'initialization';\n this.MPD = 'MPD';\n this.PERIOD = 'Period';\n this.ASSET_IDENTIFIER = 'AssetIdentifier';\n this.EVENT_STREAM = 'EventStream';\n this.ID = 'id';\n this.PROFILES = 'profiles';\n this.SERVICE_LOCATION = 'serviceLocation';\n this.RANGE = 'range';\n this.INDEX = 'index';\n this.MEDIA = 'media';\n this.BYTE_RANGE = 'byteRange';\n this.INDEX_RANGE = 'indexRange';\n this.MEDIA_RANGE = 'mediaRange';\n this.VALUE = 'value';\n this.CONTENT_TYPE = 'contentType';\n this.MIME_TYPE = 'mimeType';\n this.BITSTREAM_SWITCHING = 'BitstreamSwitching';\n this.BITSTREAM_SWITCHING_MINUS = 'bitstreamSwitching';\n this.CODECS = 'codecs';\n this.DEPENDENCY_ID = 'dependencyId';\n this.MEDIA_STREAM_STRUCTURE_ID = 'mediaStreamStructureId';\n this.METRICS = 'Metrics';\n this.METRICS_MINUS = 'metrics';\n this.REPORTING = 'Reporting';\n this.WIDTH = 'width';\n this.HEIGHT = 'height';\n this.SAR = 'sar';\n this.FRAMERATE = 'frameRate';\n this.AUDIO_SAMPLING_RATE = 'audioSamplingRate';\n this.MAXIMUM_SAP_PERIOD = 'maximumSAPPeriod';\n this.START_WITH_SAP = 'startWithSAP';\n this.MAX_PLAYOUT_RATE = 'maxPlayoutRate';\n this.CODING_DEPENDENCY = 'codingDependency';\n this.SCAN_TYPE = 'scanType';\n this.FRAME_PACKING = 'FramePacking';\n this.AUDIO_CHANNEL_CONFIGURATION = 'AudioChannelConfiguration';\n this.CONTENT_PROTECTION = 'ContentProtection';\n this.ESSENTIAL_PROPERTY = 'EssentialProperty';\n this.SUPPLEMENTAL_PROPERTY = 'SupplementalProperty';\n this.INBAND_EVENT_STREAM = 'InbandEventStream';\n this.ACCESSIBILITY = 'Accessibility';\n this.ROLE = 'Role';\n this.RATING = 'Rating';\n this.CONTENT_COMPONENT = 'ContentComponent';\n this.SUBSET = 'Subset';\n this.LANG = 'lang';\n this.VIEWPOINT = 'Viewpoint';\n this.ROLE_ASARRAY = 'Role_asArray';\n this.ACCESSIBILITY_ASARRAY = 'Accessibility_asArray';\n this.AUDIOCHANNELCONFIGURATION_ASARRAY = 'AudioChannelConfiguration_asArray';\n this.CONTENTPROTECTION_ASARRAY = 'ContentProtection_asArray';\n this.MAIN = 'main';\n this.DYNAMIC = 'dynamic';\n this.STATIC = 'static';\n this.MEDIA_PRESENTATION_DURATION = 'mediaPresentationDuration';\n this.MINIMUM_UPDATE_PERIOD = 'minimumUpdatePeriod';\n this.CODEC_PRIVATE_DATA = 'codecPrivateData';\n this.BANDWITH = 'bandwidth';\n this.SOURCE_URL = 'sourceURL';\n this.TIMESCALE = 'timescale';\n this.DURATION = 'duration';\n this.START_NUMBER = 'startNumber';\n this.PRESENTATION_TIME_OFFSET = 'presentationTimeOffset';\n this.AVAILABILITY_START_TIME = 'availabilityStartTime';\n this.AVAILABILITY_END_TIME = 'availabilityEndTime';\n this.TIMESHIFT_BUFFER_DEPTH = 'timeShiftBufferDepth';\n this.MAX_SEGMENT_DURATION = 'maxSegmentDuration';\n this.PRESENTATION_TIME = 'presentationTime';\n this.MIN_BUFFER_TIME = 'minBufferTime';\n this.MAX_SUBSEGMENT_DURATION = 'maxSubsegmentDuration';\n this.START = 'start';\n this.AVAILABILITY_TIME_OFFSET = 'availabilityTimeOffset';\n this.AVAILABILITY_TIME_COMPLETE = 'availabilityTimeComplete';\n this.CENC_DEFAULT_KID = 'cenc:default_KID';\n this.DVB_PRIORITY = 'dvb:priority';\n this.DVB_WEIGHT = 'dvb:weight';\n this.SUGGESTED_PRESENTATION_DELAY = 'suggestedPresentationDelay';\n this.SERVICE_DESCRIPTION = 'ServiceDescription';\n this.SERVICE_DESCRIPTION_SCOPE = 'Scope';\n this.SERVICE_DESCRIPTION_LATENCY = 'Latency';\n this.SERVICE_DESCRIPTION_PLAYBACK_RATE = 'PlaybackRate';\n this.PATCH_LOCATION = 'PatchLocation';\n this.PUBLISH_TIME = 'publishTime';\n this.ORIGINAL_PUBLISH_TIME = 'originalPublishTime';\n this.ORIGINAL_MPD_ID = 'mpdId';\n }\n\n constructor () {\n this.init();\n }\n}\n\nlet constants = new DashConstants();\nexport default constants;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * Constants declaration\n * @class\n * @ignore\n * @hideconstructor\n */\nclass Constants {\n\n init() {\n /**\n * @constant {string} STREAM Stream media type. Mainly used to report metrics relative to the full stream\n * @memberof Constants#\n * @static\n */\n this.STREAM = 'stream';\n\n /**\n * @constant {string} VIDEO Video media type\n * @memberof Constants#\n * @static\n */\n this.VIDEO = 'video';\n\n /**\n * @constant {string} AUDIO Audio media type\n * @memberof Constants#\n * @static\n */\n this.AUDIO = 'audio';\n\n /**\n * @constant {string} TEXT Text media type\n * @memberof Constants#\n * @static\n */\n this.TEXT = 'text';\n\n /**\n * @constant {string} MUXED Muxed (video/audio in the same chunk) media type\n * @memberof Constants#\n * @static\n */\n this.MUXED = 'muxed';\n\n /**\n * @constant {string} IMAGE Image media type\n * @memberof Constants#\n * @static\n */\n this.IMAGE = 'image';\n\n /**\n * @constant {string} STPP STTP Subtitles format\n * @memberof Constants#\n * @static\n */\n this.STPP = 'stpp';\n\n /**\n * @constant {string} TTML STTP Subtitles format\n * @memberof Constants#\n * @static\n */\n this.TTML = 'ttml';\n\n /**\n * @constant {string} VTT STTP Subtitles format\n * @memberof Constants#\n * @static\n */\n this.VTT = 'vtt';\n\n /**\n * @constant {string} WVTT STTP Subtitles format\n * @memberof Constants#\n * @static\n */\n this.WVTT = 'wvtt';\n\n /**\n * @constant {string} ABR_STRATEGY_DYNAMIC Dynamic Adaptive bitrate algorithm\n * @memberof Constants#\n * @static\n */\n this.ABR_STRATEGY_DYNAMIC = 'abrDynamic';\n\n /**\n * @constant {string} ABR_STRATEGY_BOLA Adaptive bitrate algorithm based on Bola (buffer level)\n * @memberof Constants#\n * @static\n */\n this.ABR_STRATEGY_BOLA = 'abrBola';\n\n /**\n * @constant {string} ABR_STRATEGY_L2A Adaptive bitrate algorithm based on L2A (online learning)\n * @memberof Constants#\n * @static\n */\n this.ABR_STRATEGY_L2A = 'abrL2A';\n\n /**\n * @constant {string} ABR_STRATEGY_LoLP Adaptive bitrate algorithm based on LoL+\n * @memberof Constants#\n * @static\n */\n this.ABR_STRATEGY_LoLP = 'abrLoLP';\n\n /**\n * @constant {string} ABR_STRATEGY_THROUGHPUT Adaptive bitrate algorithm based on throughput\n * @memberof Constants#\n * @static\n */\n this.ABR_STRATEGY_THROUGHPUT = 'abrThroughput';\n\n /**\n * @constant {string} ABR_FETCH_THROUGHPUT_CALUCUALTION_DOWNLOADED_DATA Throughput calculation based on downloaded data array\n * @memberof Constants#\n * @static\n */\n this.ABR_FETCH_THROUGHPUT_CALCULATION_DOWNLOADED_DATA = 'abrFetchThroughputCalculationDownloadedData';\n\n /**\n * @constant {string} ABR_FETCH_THROUGHPUT_CALCULATION_MOOF_PARSING Throughput calculation based on moof parsing\n * @memberof Constants#\n * @static\n */\n this.ABR_FETCH_THROUGHPUT_CALCULATION_MOOF_PARSING = 'abrFetchThroughputCalculationMoofParsing';\n\n /**\n * @constant {string} ABR_FETCH_THROUGHPUT_CALCULATION_AAST Throughput calculation based on adjusted availability start time in low latency mode\n * @memberof Constants#\n * @static\n */\n this.ABR_FETCH_THROUGHPUT_CALCULATION_AAST = 'abrFetchThroughputCalculationAAST';\n\n /**\n * @constant {string} LIVE_CATCHUP_MODE_DEFAULT Throughput calculation based on moof parsing\n * @memberof Constants#\n * @static\n */\n this.LIVE_CATCHUP_MODE_DEFAULT = 'liveCatchupModeDefault';\n\n /**\n * @constant {string} LIVE_CATCHUP_MODE_LOLP Throughput calculation based on moof parsing\n * @memberof Constants#\n * @static\n */\n this.LIVE_CATCHUP_MODE_LOLP = 'liveCatchupModeLoLP';\n\n /**\n * @constant {string} MOVING_AVERAGE_SLIDING_WINDOW Moving average sliding window\n * @memberof Constants#\n * @static\n */\n this.MOVING_AVERAGE_SLIDING_WINDOW = 'slidingWindow';\n\n /**\n * @constant {string} EWMA Exponential moving average\n * @memberof Constants#\n * @static\n */\n this.MOVING_AVERAGE_EWMA = 'ewma';\n\n /**\n * @constant {string} BAD_ARGUMENT_ERROR Invalid Arguments type of error\n * @memberof Constants#\n * @static\n */\n this.BAD_ARGUMENT_ERROR = 'Invalid Arguments';\n\n /**\n * @constant {string} MISSING_CONFIG_ERROR Missing configuration parameters type of error\n * @memberof Constants#\n * @static\n */\n this.MISSING_CONFIG_ERROR = 'Missing config parameter(s)';\n\n /**\n * @constant {string} TRACK_SWITCH_MODE_ALWAYS_REPLACE used to clear the buffered data (prior to current playback position) after track switch. Default for audio\n * @memberof Constants#\n * @static\n */\n this.TRACK_SWITCH_MODE_ALWAYS_REPLACE = 'alwaysReplace';\n\n /**\n * @constant {string} TRACK_SWITCH_MODE_NEVER_REPLACE used to forbid clearing the buffered data (prior to current playback position) after track switch. Defers to fastSwitchEnabled for placement of new data. Default for video\n * @memberof Constants#\n * @static\n */\n this.TRACK_SWITCH_MODE_NEVER_REPLACE = 'neverReplace';\n\n /**\n * @constant {string} TRACK_SELECTION_MODE_FIRST_TRACK makes the player select the first track found in the manifest.\n * @memberof Constants#\n * @static\n */\n this.TRACK_SELECTION_MODE_FIRST_TRACK = 'firstTrack';\n\n /**\n * @constant {string} TRACK_SELECTION_MODE_HIGHEST_BITRATE makes the player select the track with a highest bitrate. This mode is a default mode.\n * @memberof Constants#\n * @static\n */\n this.TRACK_SELECTION_MODE_HIGHEST_BITRATE = 'highestBitrate';\n\n /**\n * @constant {string} TRACK_SELECTION_MODE_HIGHEST_EFFICIENCY makes the player select the track with the lowest bitrate per pixel average.\n * @memberof Constants#\n * @static\n */\n this.TRACK_SELECTION_MODE_HIGHEST_EFFICIENCY = 'highestEfficiency';\n\n /**\n * @constant {string} TRACK_SELECTION_MODE_WIDEST_RANGE makes the player select the track with a widest range of bitrates.\n * @memberof Constants#\n * @static\n */\n this.TRACK_SELECTION_MODE_WIDEST_RANGE = 'widestRange';\n\n /**\n * @constant {string} TRACK_SELECTION_MODE_WIDEST_RANGE makes the player select the track with the highest selectionPriority as defined in the manifest\n * @memberof Constants#\n * @static\n */\n this.TRACK_SELECTION_MODE_HIGHEST_SELECTION_PRIORITY = 'highestSelectionPriority';\n\n /**\n * @constant {string} CMCD_MODE_QUERY specifies to attach CMCD metrics as query parameters.\n * @memberof Constants#\n * @static\n */\n this.CMCD_MODE_QUERY = 'query';\n\n /**\n * @constant {string} CMCD_MODE_HEADER specifies to attach CMCD metrics as HTTP headers.\n * @memberof Constants#\n * @static\n */\n this.CMCD_MODE_HEADER = 'header';\n\n\n this.LOCATION = 'Location';\n this.INITIALIZE = 'initialize';\n this.TEXT_SHOWING = 'showing';\n this.TEXT_HIDDEN = 'hidden';\n this.CC1 = 'CC1';\n this.CC3 = 'CC3';\n this.UTF8 = 'utf-8';\n this.SCHEME_ID_URI = 'schemeIdUri';\n this.START_TIME = 'starttime';\n this.SERVICE_DESCRIPTION_LL_SCHEME = 'urn:dvb:dash:lowlatency:scope:2019';\n this.SUPPLEMENTAL_PROPERTY_LL_SCHEME = 'urn:dvb:dash:lowlatency:critical:2019';\n this.XML = 'XML';\n this.ARRAY_BUFFER = 'ArrayBuffer';\n this.DVB_REPORTING_URL = 'dvb:reportingUrl';\n this.DVB_PROBABILITY = 'dvb:probability';\n this.VIDEO_ELEMENT_READY_STATES = {\n HAVE_NOTHING: 0,\n HAVE_METADATA: 1,\n HAVE_CURRENT_DATA: 2,\n HAVE_FUTURE_DATA: 3,\n HAVE_ENOUGH_DATA: 4\n };\n }\n\n constructor() {\n this.init();\n }\n}\n\nconst constants = new Constants();\nexport default constants;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nimport CoreEvents from './CoreEvents';\nclass Events extends CoreEvents {\n}\nlet events = new Events();\nexport default events;","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport EventsBase from './EventsBase';\n\n/**\n * These are internal events that should not be needed at the player level.\n * If you find and event in here that you would like access to from MediaPlayer level\n * please add an issue at https://github.com/Dash-Industry-Forum/dash.js/issues/new\n * @class\n * @ignore\n */\nclass CoreEvents extends EventsBase {\n constructor () {\n super();\n this.ATTEMPT_BACKGROUND_SYNC = 'attemptBackgroundSync';\n this.BUFFERING_COMPLETED = 'bufferingCompleted';\n this.BUFFER_CLEARED = 'bufferCleared';\n this.BYTES_APPENDED_END_FRAGMENT = 'bytesAppendedEndFragment';\n this.BUFFER_REPLACEMENT_STARTED = 'bufferReplacementStarted';\n this.CHECK_FOR_EXISTENCE_COMPLETED = 'checkForExistenceCompleted';\n this.CURRENT_TRACK_CHANGED = 'currentTrackChanged';\n this.DATA_UPDATE_COMPLETED = 'dataUpdateCompleted';\n this.INBAND_EVENTS = 'inbandEvents';\n this.INITIAL_STREAM_SWITCH = 'initialStreamSwitch';\n this.INIT_FRAGMENT_LOADED = 'initFragmentLoaded';\n this.INIT_FRAGMENT_NEEDED = 'initFragmentNeeded';\n this.INTERNAL_MANIFEST_LOADED = 'internalManifestLoaded';\n this.ORIGINAL_MANIFEST_LOADED = 'originalManifestLoaded';\n this.LOADING_COMPLETED = 'loadingCompleted';\n this.LOADING_PROGRESS = 'loadingProgress';\n this.LOADING_DATA_PROGRESS = 'loadingDataProgress';\n this.LOADING_ABANDONED = 'loadingAborted';\n this.MANIFEST_UPDATED = 'manifestUpdated';\n this.MEDIA_FRAGMENT_LOADED = 'mediaFragmentLoaded';\n this.MEDIA_FRAGMENT_NEEDED = 'mediaFragmentNeeded';\n this.QUOTA_EXCEEDED = 'quotaExceeded';\n this.SEGMENT_LOCATION_BLACKLIST_ADD = 'segmentLocationBlacklistAdd';\n this.SEGMENT_LOCATION_BLACKLIST_CHANGED = 'segmentLocationBlacklistChanged';\n this.SERVICE_LOCATION_BLACKLIST_ADD = 'serviceLocationBlacklistAdd';\n this.SERVICE_LOCATION_BLACKLIST_CHANGED = 'serviceLocationBlacklistChanged';\n this.SET_FRAGMENTED_TEXT_AFTER_DISABLED = 'setFragmentedTextAfterDisabled';\n this.SET_NON_FRAGMENTED_TEXT = 'setNonFragmentedText';\n this.SOURCE_BUFFER_ERROR = 'sourceBufferError';\n this.STREAMS_COMPOSED = 'streamsComposed';\n this.STREAM_BUFFERING_COMPLETED = 'streamBufferingCompleted';\n this.STREAM_REQUESTING_COMPLETED = 'streamRequestingCompleted';\n this.TEXT_TRACKS_QUEUE_INITIALIZED = 'textTracksQueueInitialized';\n this.TIME_SYNCHRONIZATION_COMPLETED = 'timeSynchronizationComplete';\n this.UPDATE_TIME_SYNC_OFFSET = 'updateTimeSyncOffset';\n this.URL_RESOLUTION_FAILED = 'urlResolutionFailed';\n this.VIDEO_CHUNK_RECEIVED = 'videoChunkReceived';\n this.WALLCLOCK_TIME_UPDATED = 'wallclockTimeUpdated';\n this.XLINK_ELEMENT_LOADED = 'xlinkElementLoaded';\n this.XLINK_READY = 'xlinkReady';\n this.SEEK_TARGET = 'seekTarget';\n }\n}\n\nexport default CoreEvents;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @module FactoryMaker\n * @ignore\n */\nconst FactoryMaker = (function () {\n\n let instance;\n let singletonContexts = [];\n const singletonFactories = {};\n const classFactories = {};\n\n function extend(name, childInstance, override, context) {\n if (!context[name] && childInstance) {\n context[name] = {\n instance: childInstance,\n override: override\n };\n }\n }\n\n /**\n * Use this method from your extended object. this.factory is injected into your object.\n * this.factory.getSingletonInstance(this.context, 'VideoModel')\n * will return the video model for use in the extended object.\n *\n * @param {Object} context - injected into extended object as this.context\n * @param {string} className - string name found in all dash.js objects\n * with name __dashjs_factory_name Will be at the bottom. Will be the same as the object's name.\n * @returns {*} Context aware instance of specified singleton name.\n * @memberof module:FactoryMaker\n * @instance\n */\n function getSingletonInstance(context, className) {\n for (const i in singletonContexts) {\n const obj = singletonContexts[i];\n if (obj.context === context && obj.name === className) {\n return obj.instance;\n }\n }\n return null;\n }\n\n /**\n * Use this method to add an singleton instance to the system. Useful for unit testing to mock objects etc.\n *\n * @param {Object} context\n * @param {string} className\n * @param {Object} instance\n * @memberof module:FactoryMaker\n * @instance\n */\n function setSingletonInstance(context, className, instance) {\n for (const i in singletonContexts) {\n const obj = singletonContexts[i];\n if (obj.context === context && obj.name === className) {\n singletonContexts[i].instance = instance;\n return;\n }\n }\n singletonContexts.push({\n name: className,\n context: context,\n instance: instance\n });\n }\n\n /**\n * Use this method to remove all singleton instances associated with a particular context.\n *\n * @param {Object} context\n * @memberof module:FactoryMaker\n * @instance\n */\n function deleteSingletonInstances(context) {\n singletonContexts = singletonContexts.filter(x => x.context !== context);\n }\n\n /*------------------------------------------------------------------------------------------*/\n\n // Factories storage Management\n\n /*------------------------------------------------------------------------------------------*/\n\n function getFactoryByName(name, factoriesArray) {\n return factoriesArray[name];\n }\n\n function updateFactory(name, factory, factoriesArray) {\n if (name in factoriesArray) {\n factoriesArray[name] = factory;\n }\n }\n\n /*------------------------------------------------------------------------------------------*/\n\n // Class Factories Management\n\n /*------------------------------------------------------------------------------------------*/\n\n function updateClassFactory(name, factory) {\n updateFactory(name, factory, classFactories);\n }\n\n function getClassFactoryByName(name) {\n return getFactoryByName(name, classFactories);\n }\n\n function getClassFactory(classConstructor) {\n let factory = getFactoryByName(classConstructor.__dashjs_factory_name, classFactories);\n\n if (!factory) {\n factory = function (context) {\n if (context === undefined) {\n context = {};\n }\n return {\n create: function () {\n return merge(classConstructor, context, arguments);\n }\n };\n };\n\n classFactories[classConstructor.__dashjs_factory_name] = factory; // store factory\n }\n return factory;\n }\n\n /*------------------------------------------------------------------------------------------*/\n\n // Singleton Factory MAangement\n\n /*------------------------------------------------------------------------------------------*/\n\n function updateSingletonFactory(name, factory) {\n updateFactory(name, factory, singletonFactories);\n }\n\n function getSingletonFactoryByName(name) {\n return getFactoryByName(name, singletonFactories);\n }\n\n function getSingletonFactory(classConstructor) {\n let factory = getFactoryByName(classConstructor.__dashjs_factory_name, singletonFactories);\n if (!factory) {\n factory = function (context) {\n let instance;\n if (context === undefined) {\n context = {};\n }\n return {\n getInstance: function () {\n // If we don't have an instance yet check for one on the context\n if (!instance) {\n instance = getSingletonInstance(context, classConstructor.__dashjs_factory_name);\n }\n // If there's no instance on the context then create one\n if (!instance) {\n instance = merge(classConstructor, context, arguments);\n singletonContexts.push({\n name: classConstructor.__dashjs_factory_name,\n context: context,\n instance: instance\n });\n }\n return instance;\n }\n };\n };\n singletonFactories[classConstructor.__dashjs_factory_name] = factory; // store factory\n }\n\n return factory;\n }\n\n function merge(classConstructor, context, args) {\n\n let classInstance;\n const className = classConstructor.__dashjs_factory_name;\n const extensionObject = context[className];\n\n if (extensionObject) {\n\n let extension = extensionObject.instance;\n\n if (extensionObject.override) { //Override public methods in parent but keep parent.\n\n classInstance = classConstructor.apply({context}, args);\n extension = extension.apply({\n context,\n factory: instance,\n parent: classInstance\n }, args);\n\n for (const prop in extension) {\n if (classInstance.hasOwnProperty(prop)) {\n classInstance[prop] = extension[prop];\n }\n }\n\n } else { //replace parent object completely with new object. Same as dijon.\n\n return extension.apply({\n context,\n factory: instance\n }, args);\n\n }\n } else {\n // Create new instance of the class\n classInstance = classConstructor.apply({context}, args);\n }\n\n // Add getClassName function to class instance prototype (used by Debug)\n classInstance.getClassName = function () {return className;};\n\n return classInstance;\n }\n\n instance = {\n extend: extend,\n getSingletonInstance: getSingletonInstance,\n setSingletonInstance: setSingletonInstance,\n deleteSingletonInstances: deleteSingletonInstances,\n getSingletonFactory: getSingletonFactory,\n getSingletonFactoryByName: getSingletonFactoryByName,\n updateSingletonFactory: updateSingletonFactory,\n getClassFactory: getClassFactory,\n getClassFactoryByName: getClassFactoryByName,\n updateClassFactory: updateClassFactory\n };\n\n return instance;\n\n}());\n\nexport default FactoryMaker;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport EventsBase from '../core/events/EventsBase';\n\n/**\n * @class\n * @implements EventsBase\n */\nclass MediaPlayerEvents extends EventsBase {\n\n /**\n * @description Public facing external events to be used when developing a player that implements dash.js.\n */\n constructor() {\n super();\n /**\n * Triggered when playback will not start yet\n * as the MPD's availabilityStartTime is in the future.\n * Check delay property in payload to determine time before playback will start.\n * @event MediaPlayerEvents#AST_IN_FUTURE\n */\n this.AST_IN_FUTURE = 'astInFuture';\n\n /**\n * Triggered when the video element's buffer state changes to stalled.\n * Check mediaType in payload to determine type (Video, Audio, FragmentedText).\n * @event MediaPlayerEvents#BUFFER_EMPTY\n */\n this.BUFFER_EMPTY = 'bufferStalled';\n\n /**\n * Triggered when the video element's buffer state changes to loaded.\n * Check mediaType in payload to determine type (Video, Audio, FragmentedText).\n * @event MediaPlayerEvents#BUFFER_LOADED\n */\n this.BUFFER_LOADED = 'bufferLoaded';\n\n /**\n * Triggered when the video element's buffer state changes, either stalled or loaded. Check payload for state.\n * @event MediaPlayerEvents#BUFFER_LEVEL_STATE_CHANGED\n */\n this.BUFFER_LEVEL_STATE_CHANGED = 'bufferStateChanged';\n\n /**\n * Triggered when the buffer level of a media type has been updated\n * @event MediaPlayerEvents#BUFFER_LEVEL_UPDATED\n */\n this.BUFFER_LEVEL_UPDATED = 'bufferLevelUpdated';\n\n /**\n * Triggered when a dynamic stream changed to static (transition phase between Live and On-Demand).\n * @event MediaPlayerEvents#DYNAMIC_TO_STATIC\n */\n this.DYNAMIC_TO_STATIC = 'dynamicToStatic';\n\n /**\n * Triggered when there is an error from the element or MSE source buffer.\n * @event MediaPlayerEvents#ERROR\n */\n this.ERROR = 'error';\n /**\n * Triggered when a fragment download has completed.\n * @event MediaPlayerEvents#FRAGMENT_LOADING_COMPLETED\n */\n this.FRAGMENT_LOADING_COMPLETED = 'fragmentLoadingCompleted';\n\n /**\n * Triggered when a partial fragment download has completed.\n * @event MediaPlayerEvents#FRAGMENT_LOADING_PROGRESS\n */\n this.FRAGMENT_LOADING_PROGRESS = 'fragmentLoadingProgress';\n /**\n * Triggered when a fragment download has started.\n * @event MediaPlayerEvents#FRAGMENT_LOADING_STARTED\n */\n this.FRAGMENT_LOADING_STARTED = 'fragmentLoadingStarted';\n\n /**\n * Triggered when a fragment download is abandoned due to detection of slow download base on the ABR abandon rule..\n * @event MediaPlayerEvents#FRAGMENT_LOADING_ABANDONED\n */\n this.FRAGMENT_LOADING_ABANDONED = 'fragmentLoadingAbandoned';\n\n /**\n * Triggered when {@link module:Debug} logger methods are called.\n * @event MediaPlayerEvents#LOG\n */\n this.LOG = 'log';\n\n /**\n * Triggered when the manifest load is complete\n * @event MediaPlayerEvents#MANIFEST_LOADED\n */\n this.MANIFEST_LOADED = 'manifestLoaded';\n\n /**\n * Triggered anytime there is a change to the overall metrics.\n * @event MediaPlayerEvents#METRICS_CHANGED\n */\n this.METRICS_CHANGED = 'metricsChanged';\n\n /**\n * Triggered when an individual metric is added, updated or cleared.\n * @event MediaPlayerEvents#METRIC_CHANGED\n */\n this.METRIC_CHANGED = 'metricChanged';\n\n /**\n * Triggered every time a new metric is added.\n * @event MediaPlayerEvents#METRIC_ADDED\n */\n this.METRIC_ADDED = 'metricAdded';\n\n /**\n * Triggered every time a metric is updated.\n * @event MediaPlayerEvents#METRIC_UPDATED\n */\n this.METRIC_UPDATED = 'metricUpdated';\n\n /**\n * Triggered when a new stream (period) starts.\n * @event MediaPlayerEvents#PERIOD_SWITCH_STARTED\n */\n this.PERIOD_SWITCH_STARTED = 'periodSwitchStarted';\n\n /**\n * Triggered at the stream end of a period.\n * @event MediaPlayerEvents#PERIOD_SWITCH_COMPLETED\n */\n this.PERIOD_SWITCH_COMPLETED = 'periodSwitchCompleted';\n\n /**\n * Triggered when an ABR up /down switch is initiated; either by user in manual mode or auto mode via ABR rules.\n * @event MediaPlayerEvents#QUALITY_CHANGE_REQUESTED\n */\n this.QUALITY_CHANGE_REQUESTED = 'qualityChangeRequested';\n\n /**\n * Triggered when the new ABR quality is being rendered on-screen.\n * @event MediaPlayerEvents#QUALITY_CHANGE_RENDERED\n */\n this.QUALITY_CHANGE_RENDERED = 'qualityChangeRendered';\n\n /**\n * Triggered when the new track is being rendered.\n * @event MediaPlayerEvents#TRACK_CHANGE_RENDERED\n */\n this.TRACK_CHANGE_RENDERED = 'trackChangeRendered';\n\n /**\n * Triggered when a stream (period) is being loaded\n * @event MediaPlayerEvents#STREAM_INITIALIZING\n */\n this.STREAM_INITIALIZING = 'streamInitializing';\n\n /**\n * Triggered when a stream (period) is loaded\n * @event MediaPlayerEvents#STREAM_UPDATED\n */\n this.STREAM_UPDATED = 'streamUpdated';\n\n /**\n * Triggered when a stream (period) is activated\n * @event MediaPlayerEvents#STREAM_ACTIVATED\n */\n this.STREAM_ACTIVATED = 'streamActivated';\n\n /**\n * Triggered when a stream (period) is deactivated\n * @event MediaPlayerEvents#STREAM_DEACTIVATED\n */\n this.STREAM_DEACTIVATED = 'streamDeactivated';\n\n /**\n * Triggered when a stream (period) is activated\n * @event MediaPlayerEvents#STREAM_INITIALIZED\n */\n this.STREAM_INITIALIZED = 'streamInitialized';\n\n /**\n * Triggered when the player has been reset.\n * @event MediaPlayerEvents#STREAM_TEARDOWN_COMPLETE\n */\n this.STREAM_TEARDOWN_COMPLETE = 'streamTeardownComplete';\n\n /**\n * Triggered once all text tracks detected in the MPD are added to the video element.\n * @event MediaPlayerEvents#TEXT_TRACKS_ADDED\n */\n this.TEXT_TRACKS_ADDED = 'allTextTracksAdded';\n\n /**\n * Triggered when a text track is added to the video element's TextTrackList\n * @event MediaPlayerEvents#TEXT_TRACK_ADDED\n */\n this.TEXT_TRACK_ADDED = 'textTrackAdded';\n\n /**\n * Triggered when a ttml chunk is parsed.\n * @event MediaPlayerEvents#TTML_PARSED\n */\n this.TTML_PARSED = 'ttmlParsed';\n\n /**\n * Triggered when a ttml chunk has to be parsed.\n * @event MediaPlayerEvents#TTML_TO_PARSE\n */\n this.TTML_TO_PARSE = 'ttmlToParse';\n\n /**\n * Triggered when a caption is rendered.\n * @event MediaPlayerEvents#CAPTION_RENDERED\n */\n this.CAPTION_RENDERED = 'captionRendered';\n\n /**\n * Triggered when the caption container is resized.\n * @event MediaPlayerEvents#CAPTION_CONTAINER_RESIZE\n */\n this.CAPTION_CONTAINER_RESIZE = 'captionContainerResize';\n\n /**\n * Sent when enough data is available that the media can be played,\n * at least for a couple of frames. This corresponds to the\n * HAVE_ENOUGH_DATA readyState.\n * @event MediaPlayerEvents#CAN_PLAY\n */\n this.CAN_PLAY = 'canPlay';\n\n /**\n * This corresponds to the CAN_PLAY_THROUGH readyState.\n * @event MediaPlayerEvents#CAN_PLAY_THROUGH\n */\n this.CAN_PLAY_THROUGH = 'canPlayThrough';\n\n /**\n * Sent when playback completes.\n * @event MediaPlayerEvents#PLAYBACK_ENDED\n */\n this.PLAYBACK_ENDED = 'playbackEnded';\n\n /**\n * Sent when an error occurs. The element's error\n * attribute contains more information.\n * @event MediaPlayerEvents#PLAYBACK_ERROR\n */\n this.PLAYBACK_ERROR = 'playbackError';\n\n /**\n * Sent when playback is not allowed (for example if user gesture is needed).\n * @event MediaPlayerEvents#PLAYBACK_NOT_ALLOWED\n */\n this.PLAYBACK_NOT_ALLOWED = 'playbackNotAllowed';\n\n /**\n * The media's metadata has finished loading; all attributes now\n * contain as much useful information as they're going to.\n * @event MediaPlayerEvents#PLAYBACK_METADATA_LOADED\n */\n this.PLAYBACK_METADATA_LOADED = 'playbackMetaDataLoaded';\n\n /**\n * The media's metadata has finished loading; all attributes now\n * contain as much useful information as they're going to.\n * @event MediaPlayerEvents#PLAYBACK_METADATA_LOADED\n */\n this.PLAYBACK_LOADED_DATA = 'playbackLoadedData';\n\n /**\n * Sent when playback is paused.\n * @event MediaPlayerEvents#PLAYBACK_PAUSED\n */\n this.PLAYBACK_PAUSED = 'playbackPaused';\n\n /**\n * Sent when the media begins to play (either for the first time, after having been paused,\n * or after ending and then restarting).\n *\n * @event MediaPlayerEvents#PLAYBACK_PLAYING\n */\n this.PLAYBACK_PLAYING = 'playbackPlaying';\n\n /**\n * Sent periodically to inform interested parties of progress downloading\n * the media. Information about the current amount of the media that has\n * been downloaded is available in the media element's buffered attribute.\n * @event MediaPlayerEvents#PLAYBACK_PROGRESS\n */\n this.PLAYBACK_PROGRESS = 'playbackProgress';\n\n /**\n * Sent when the playback speed changes.\n * @event MediaPlayerEvents#PLAYBACK_RATE_CHANGED\n */\n this.PLAYBACK_RATE_CHANGED = 'playbackRateChanged';\n\n /**\n * Sent when a seek operation completes.\n * @event MediaPlayerEvents#PLAYBACK_SEEKED\n */\n this.PLAYBACK_SEEKED = 'playbackSeeked';\n\n /**\n * Sent when a seek operation begins.\n * @event MediaPlayerEvents#PLAYBACK_SEEKING\n */\n this.PLAYBACK_SEEKING = 'playbackSeeking';\n\n /**\n * Sent when a seek operation has been asked.\n * @event MediaPlayerEvents#PLAYBACK_SEEK_ASKED\n */\n this.PLAYBACK_SEEK_ASKED = 'playbackSeekAsked';\n\n /**\n * Sent when the video element reports stalled\n * @event MediaPlayerEvents#PLAYBACK_STALLED\n */\n this.PLAYBACK_STALLED = 'playbackStalled';\n\n /**\n * Sent when playback of the media starts after having been paused;\n * that is, when playback is resumed after a prior pause event.\n *\n * @event MediaPlayerEvents#PLAYBACK_STARTED\n */\n this.PLAYBACK_STARTED = 'playbackStarted';\n\n /**\n * The time indicated by the element's currentTime attribute has changed.\n * @event MediaPlayerEvents#PLAYBACK_TIME_UPDATED\n */\n this.PLAYBACK_TIME_UPDATED = 'playbackTimeUpdated';\n\n /**\n * Sent when the media playback has stopped because of a temporary lack of data.\n *\n * @event MediaPlayerEvents#PLAYBACK_WAITING\n */\n this.PLAYBACK_WAITING = 'playbackWaiting';\n\n /**\n * Manifest validity changed - As a result of an MPD validity expiration event.\n * @event MediaPlayerEvents#MANIFEST_VALIDITY_CHANGED\n */\n this.MANIFEST_VALIDITY_CHANGED = 'manifestValidityChanged';\n\n /**\n * Dash events are triggered at their respective start points on the timeline.\n * @event MediaPlayerEvents#EVENT_MODE_ON_START\n */\n this.EVENT_MODE_ON_START = 'eventModeOnStart';\n\n /**\n * Dash events are triggered as soon as they were parsed.\n * @event MediaPlayerEvents#EVENT_MODE_ON_RECEIVE\n */\n this.EVENT_MODE_ON_RECEIVE = 'eventModeOnReceive';\n\n /**\n * Event that is dispatched whenever the player encounters a potential conformance validation that might lead to unexpected/not optimal behavior\n * @event MediaPlayerEvents#CONFORMANCE_VIOLATION\n */\n this.CONFORMANCE_VIOLATION = 'conformanceViolation';\n\n /**\n * Event that is dispatched whenever the player switches to a different representation\n * @event MediaPlayerEvents#REPRESENTATION_SWITCH\n */\n this.REPRESENTATION_SWITCH = 'representationSwitch';\n }\n}\n\nlet mediaPlayerEvents = new MediaPlayerEvents();\nexport default mediaPlayerEvents;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @classdesc This Object holds reference to the HTTPRequest for manifest, fragment and xlink loading.\n * Members which are not defined in ISO23009-1 Annex D should be prefixed by a _ so that they are ignored\n * by Metrics Reporting code.\n * @ignore\n */\nclass HTTPRequest {\n /**\n * @class\n */\n constructor() {\n /**\n * Identifier of the TCP connection on which the HTTP request was sent.\n * @public\n */\n this.tcpid = null;\n /**\n * This is an optional parameter and should not be included in HTTP request/response transactions for progressive download.\n * The type of the request:\n * - MPD\n * - XLink expansion\n * - Initialization Fragment\n * - Index Fragment\n * - Media Fragment\n * - Bitstream Switching Fragment\n * - other\n * @public\n */\n this.type = null;\n /**\n * The original URL (before any redirects or failures)\n * @public\n */\n this.url = null;\n /**\n * The actual URL requested, if different from above\n * @public\n */\n this.actualurl = null;\n /**\n * The contents of the byte-range-spec part of the HTTP Range header.\n * @public\n */\n this.range = null;\n /**\n * Real-Time | The real time at which the request was sent.\n * @public\n */\n this.trequest = null;\n /**\n * Real-Time | The real time at which the first byte of the response was received.\n * @public\n */\n this.tresponse = null;\n /**\n * The HTTP response code.\n * @public\n */\n this.responsecode = null;\n /**\n * The duration of the throughput trace intervals (ms), for successful requests only.\n * @public\n */\n this.interval = null;\n /**\n * Throughput traces, for successful requests only.\n * @public\n */\n this.trace = [];\n\n /**\n * Type of stream (\"audio\" | \"video\" etc..)\n * @public\n */\n this._stream = null;\n /**\n * Real-Time | The real time at which the request finished.\n * @public\n */\n this._tfinish = null;\n /**\n * The duration of the media requests, if available, in seconds.\n * @public\n */\n this._mediaduration = null;\n /**\n * The media segment quality\n * @public\n */\n this._quality = null;\n /**\n * all the response headers from request.\n * @public\n */\n this._responseHeaders = null;\n /**\n * The selected service location for the request. string.\n * @public\n */\n this._serviceLocation = null;\n }\n}\n\n/**\n * @classdesc This Object holds reference to the progress of the HTTPRequest.\n * @ignore\n */\nclass HTTPRequestTrace {\n /**\n * @class\n */\n constructor() {\n /**\n * Real-Time | Measurement stream start.\n * @public\n */\n this.s = null;\n /**\n * Measurement stream duration (ms).\n * @public\n */\n this.d = null;\n /**\n * List of integers counting the bytes received in each trace interval within the measurement stream.\n * @public\n */\n this.b = [];\n /**\n * Measurement throughput in kbits/s\n * @public\n */\n this.t = null;\n }\n}\n\nHTTPRequest.GET = 'GET';\nHTTPRequest.HEAD = 'HEAD';\nHTTPRequest.MPD_TYPE = 'MPD';\nHTTPRequest.XLINK_EXPANSION_TYPE = 'XLinkExpansion';\nHTTPRequest.INIT_SEGMENT_TYPE = 'InitializationSegment';\nHTTPRequest.INDEX_SEGMENT_TYPE = 'IndexSegment';\nHTTPRequest.MEDIA_SEGMENT_TYPE = 'MediaSegment';\nHTTPRequest.BITSTREAM_SWITCHING_SEGMENT_TYPE = 'BitstreamSwitchingSegment';\nHTTPRequest.MSS_FRAGMENT_INFO_SEGMENT_TYPE = 'FragmentInfoSegment';\nHTTPRequest.LICENSE = 'license';\nHTTPRequest.OTHER_TYPE = 'other';\n\nexport { HTTPRequest, HTTPRequestTrace };\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport EventBus from './EventBus';\nimport Events from './events/Events';\nimport FactoryMaker from './FactoryMaker';\n\nconst LOG_LEVEL_NONE = 0;\nconst LOG_LEVEL_FATAL = 1;\nconst LOG_LEVEL_ERROR = 2;\nconst LOG_LEVEL_WARNING = 3;\nconst LOG_LEVEL_INFO = 4;\nconst LOG_LEVEL_DEBUG = 5;\n\n/**\n * @module Debug\n * @param {object} config\n * @ignore\n */\nfunction Debug(config) {\n\n config = config || {};\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n const settings = config.settings;\n\n const logFn = [];\n\n let instance,\n showLogTimestamp,\n showCalleeName,\n startTime;\n\n function setup() {\n showLogTimestamp = true;\n showCalleeName = true;\n startTime = new Date().getTime();\n\n if (typeof window !== 'undefined' && window.console) {\n logFn[LOG_LEVEL_FATAL] = getLogFn(window.console.error);\n logFn[LOG_LEVEL_ERROR] = getLogFn(window.console.error);\n logFn[LOG_LEVEL_WARNING] = getLogFn(window.console.warn);\n logFn[LOG_LEVEL_INFO] = getLogFn(window.console.info);\n logFn[LOG_LEVEL_DEBUG] = getLogFn(window.console.debug);\n }\n }\n\n function getLogFn(fn) {\n if (fn && fn.bind) {\n return fn.bind(window.console);\n }\n // if not define, return the default function for reporting logs\n return window.console.log.bind(window.console);\n }\n\n /**\n * Retrieves a logger which can be used to write logging information in browser console.\n * @param {object} instance Object for which the logger is created. It is used\n * to include calle object information in log messages.\n * @memberof module:Debug\n * @returns {Logger}\n * @instance\n */\n function getLogger(instance) {\n return {\n fatal: fatal.bind(instance),\n error: error.bind(instance),\n warn: warn.bind(instance),\n info: info.bind(instance),\n debug: debug.bind(instance)\n };\n }\n\n /**\n * Prepends a timestamp in milliseconds to each log message.\n * @param {boolean} value Set to true if you want to see a timestamp in each log message.\n * @default LOG_LEVEL_WARNING\n * @memberof module:Debug\n * @instance\n */\n function setLogTimestampVisible(value) {\n showLogTimestamp = value;\n }\n\n /**\n * Prepends the callee object name, and media type if available, to each log message.\n * @param {boolean} value Set to true if you want to see the callee object name and media type in each log message.\n * @default true\n * @memberof module:Debug\n * @instance\n */\n function setCalleeNameVisible(value) {\n showCalleeName = value;\n }\n\n function fatal(...params) {\n doLog(LOG_LEVEL_FATAL, this, ...params);\n }\n\n function error(...params) {\n doLog(LOG_LEVEL_ERROR, this, ...params);\n }\n\n function warn(...params) {\n doLog(LOG_LEVEL_WARNING, this, ...params);\n }\n\n function info(...params) {\n doLog(LOG_LEVEL_INFO, this, ...params);\n }\n\n function debug(...params) {\n doLog(LOG_LEVEL_DEBUG, this, ...params);\n }\n\n function doLog(level, _this, ...params) {\n let message = '';\n let logTime = null;\n\n if (showLogTimestamp) {\n logTime = new Date().getTime();\n message += '[' + (logTime - startTime) + ']';\n }\n\n if (showCalleeName && _this && _this.getClassName) {\n message += '[' + _this.getClassName() + ']';\n if (_this.getType) {\n message += '[' + _this.getType() + ']';\n }\n }\n\n if (message.length > 0) {\n message += ' ';\n }\n\n Array.apply(null, params).forEach(function (item) {\n message += item + ' ';\n });\n\n // log to console if the log level is high enough\n if (logFn[level] && settings.get().debug.logLevel >= level) {\n logFn[level](message);\n }\n\n // send log event regardless of log level\n if (settings && settings.get().debug.dispatchEvent) {\n eventBus.trigger(Events.LOG, { message: message, level: level });\n }\n }\n\n instance = {\n getLogger: getLogger,\n setLogTimestampVisible: setLogTimestampVisible,\n setCalleeNameVisible: setCalleeNameVisible\n };\n\n setup();\n\n return instance;\n}\n\nDebug.__dashjs_factory_name = 'Debug';\n\nconst factory = FactoryMaker.getSingletonFactory(Debug);\nfactory.LOG_LEVEL_NONE = LOG_LEVEL_NONE;\nfactory.LOG_LEVEL_FATAL = LOG_LEVEL_FATAL;\nfactory.LOG_LEVEL_ERROR = LOG_LEVEL_ERROR;\nfactory.LOG_LEVEL_WARNING = LOG_LEVEL_WARNING;\nfactory.LOG_LEVEL_INFO = LOG_LEVEL_INFO;\nfactory.LOG_LEVEL_DEBUG = LOG_LEVEL_DEBUG;\nFactoryMaker.updateSingletonFactory(Debug.__dashjs_factory_name, factory);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport FactoryMaker from './FactoryMaker';\nimport MediaPlayerEvents from '../streaming/MediaPlayerEvents';\n\nconst EVENT_PRIORITY_LOW = 0;\nconst EVENT_PRIORITY_HIGH = 5000;\n\nfunction EventBus() {\n\n let handlers = {};\n\n function on(type, listener, scope, options = {}) {\n\n if (!type) {\n throw new Error('event type cannot be null or undefined');\n }\n if (!listener || typeof (listener) !== 'function') {\n throw new Error('listener must be a function: ' + listener);\n }\n\n let priority = options.priority || EVENT_PRIORITY_LOW;\n\n if (getHandlerIdx(type, listener, scope) >= 0) return;\n\n handlers[type] = handlers[type] || [];\n\n const handler = {\n callback: listener,\n scope,\n priority\n };\n\n if (scope && scope.getStreamId) {\n handler.streamId = scope.getStreamId();\n }\n if (scope && scope.getType) {\n handler.mediaType = scope.getType();\n }\n if (options && options.mode) {\n handler.mode = options.mode;\n }\n\n const inserted = handlers[type].some((item, idx) => {\n if (item && priority > item.priority) {\n handlers[type].splice(idx, 0, handler);\n return true;\n }\n });\n\n if (!inserted) {\n handlers[type].push(handler);\n }\n }\n\n function off(type, listener, scope) {\n if (!type || !listener || !handlers[type]) return;\n const idx = getHandlerIdx(type, listener, scope);\n if (idx < 0) return;\n handlers[type][idx] = null;\n }\n\n function trigger(type, payload = {}, filters = {}) {\n if (!type || !handlers[type]) return;\n\n payload = payload || {};\n\n if (payload.hasOwnProperty('type')) throw new Error('\\'type\\' is a reserved word for event dispatching');\n\n payload.type = type;\n\n if (filters.streamId) {\n payload.streamId = filters.streamId;\n }\n if (filters.mediaType) {\n payload.mediaType = filters.mediaType;\n }\n\n handlers[type]\n .filter((handler) => {\n if (!handler) {\n return false;\n }\n if (filters.streamId && handler.streamId && handler.streamId !== filters.streamId) {\n return false;\n }\n if (filters.mediaType && handler.mediaType && handler.mediaType !== filters.mediaType) {\n return false;\n }\n // This is used for dispatching DASH events. By default we use the onStart mode. Consequently we filter everything that has a non matching mode and the onReceive events for handlers that did not specify a mode.\n if ((filters.mode && handler.mode && handler.mode !== filters.mode) || (!handler.mode && filters.mode && filters.mode === MediaPlayerEvents.EVENT_MODE_ON_RECEIVE)) {\n return false;\n }\n return true;\n })\n .forEach(handler => handler && handler.callback.call(handler.scope, payload));\n }\n\n function getHandlerIdx(type, listener, scope) {\n\n let idx = -1;\n\n if (!handlers[type]) return idx;\n\n handlers[type].some((item, index) => {\n if (item && item.callback === listener && (!scope || scope === item.scope)) {\n idx = index;\n return true;\n }\n });\n return idx;\n }\n\n function reset() {\n handlers = {};\n }\n\n const instance = {\n on: on,\n off: off,\n trigger: trigger,\n reset: reset\n };\n\n return instance;\n}\n\nEventBus.__dashjs_factory_name = 'EventBus';\nconst factory = FactoryMaker.getSingletonFactory(EventBus);\nfactory.EVENT_PRIORITY_LOW = EVENT_PRIORITY_LOW;\nfactory.EVENT_PRIORITY_HIGH = EVENT_PRIORITY_HIGH;\nFactoryMaker.updateSingletonFactory(EventBus.__dashjs_factory_name, factory);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass DashJSError {\n constructor(code, message, data) {\n this.code = code || null;\n this.message = message || null;\n this.data = data || null;\n }\n}\n\nexport default DashJSError;","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport ErrorsBase from './ErrorsBase';\n/**\n * Errors declaration\n * @class\n */\nclass Errors extends ErrorsBase {\n constructor () {\n super();\n\n /**\n * Error code returned when a manifest parsing error occurs\n */\n this.MANIFEST_LOADER_PARSING_FAILURE_ERROR_CODE = 10;\n\n /**\n * Error code returned when a manifest loading error occurs\n */\n this.MANIFEST_LOADER_LOADING_FAILURE_ERROR_CODE = 11;\n\n /**\n * Error code returned when a xlink loading error occurs\n */\n this.XLINK_LOADER_LOADING_FAILURE_ERROR_CODE = 12;\n\n /**\n * Error code returned when no segment ranges could be determined from the sidx box\n */\n this.SEGMENT_BASE_LOADER_ERROR_CODE = 15;\n\n /**\n * Error code returned when the time synchronization failed\n */\n this.TIME_SYNC_FAILED_ERROR_CODE = 16;\n\n /**\n * Error code returned when loading a fragment failed\n */\n this.FRAGMENT_LOADER_LOADING_FAILURE_ERROR_CODE = 17;\n\n /**\n * Error code returned when the FragmentLoader did not receive a request object\n */\n this.FRAGMENT_LOADER_NULL_REQUEST_ERROR_CODE = 18;\n\n /**\n * Error code returned when the BaseUrl resolution failed\n */\n this.URL_RESOLUTION_FAILED_GENERIC_ERROR_CODE = 19;\n\n /**\n * Error code returned when the append operation in the SourceBuffer failed\n */\n this.APPEND_ERROR_CODE = 20;\n\n /**\n * Error code returned when the remove operation in the SourceBuffer failed\n */\n this.REMOVE_ERROR_CODE = 21;\n\n /**\n * Error code returned when updating the internal objects after loading an MPD failed\n */\n this.DATA_UPDATE_FAILED_ERROR_CODE = 22;\n\n /**\n * Error code returned when MediaSource is not supported by the browser\n */\n this.CAPABILITY_MEDIASOURCE_ERROR_CODE = 23;\n\n /**\n * Error code returned when Protected contents are not supported\n */\n this.CAPABILITY_MEDIAKEYS_ERROR_CODE = 24;\n\n /**\n * Error code returned when loading the manifest failed\n */\n this.DOWNLOAD_ERROR_ID_MANIFEST_CODE = 25;\n\n /**\n * Error code returned when loading the sidx failed\n */\n this.DOWNLOAD_ERROR_ID_SIDX_CODE = 26;\n\n /**\n * Error code returned when loading the media content failed\n */\n this.DOWNLOAD_ERROR_ID_CONTENT_CODE = 27;\n\n /**\n * Error code returned when loading the init segment failed\n */\n this.DOWNLOAD_ERROR_ID_INITIALIZATION_CODE = 28;\n\n /**\n * Error code returned when loading the XLink content failed\n */\n this.DOWNLOAD_ERROR_ID_XLINK_CODE = 29;\n\n /**\n * Error code returned when parsing the MPD resulted in a logical error\n */\n this.MANIFEST_ERROR_ID_PARSE_CODE = 31;\n\n /**\n * Error code returned when no stream (period) has been detected in the manifest\n */\n this.MANIFEST_ERROR_ID_NOSTREAMS_CODE = 32;\n\n /**\n * Error code returned when something wrong has happened during parsing and appending subtitles (TTML or VTT)\n */\n this.TIMED_TEXT_ERROR_ID_PARSE_CODE = 33;\n\n /**\n * Error code returned when a 'muxed' media type has been detected in the manifest. This type is not supported\n */\n\n this.MANIFEST_ERROR_ID_MULTIPLEXED_CODE = 34;\n\n /**\n * Error code returned when a media source type is not supported\n */\n this.MEDIASOURCE_TYPE_UNSUPPORTED_CODE = 35;\n\n this.MANIFEST_LOADER_PARSING_FAILURE_ERROR_MESSAGE = 'parsing failed for ';\n this.MANIFEST_LOADER_LOADING_FAILURE_ERROR_MESSAGE = 'Failed loading manifest: ';\n this.XLINK_LOADER_LOADING_FAILURE_ERROR_MESSAGE = 'Failed loading Xlink element: ';\n this.SEGMENTS_UPDATE_FAILED_ERROR_MESSAGE = 'Segments update failed';\n this.SEGMENTS_UNAVAILABLE_ERROR_MESSAGE = 'no segments are available yet';\n this.SEGMENT_BASE_LOADER_ERROR_MESSAGE = 'error loading segment ranges from sidx';\n this.TIME_SYNC_FAILED_ERROR_MESSAGE = 'Failed to synchronize client and server time';\n this.FRAGMENT_LOADER_NULL_REQUEST_ERROR_MESSAGE = 'request is null';\n this.URL_RESOLUTION_FAILED_GENERIC_ERROR_MESSAGE = 'Failed to resolve a valid URL';\n this.APPEND_ERROR_MESSAGE = 'chunk is not defined';\n this.REMOVE_ERROR_MESSAGE = 'Removing data from the SourceBuffer';\n this.DATA_UPDATE_FAILED_ERROR_MESSAGE = 'Data update failed';\n this.CAPABILITY_MEDIASOURCE_ERROR_MESSAGE = 'mediasource is not supported';\n this.CAPABILITY_MEDIAKEYS_ERROR_MESSAGE = 'mediakeys is not supported';\n this.TIMED_TEXT_ERROR_MESSAGE_PARSE = 'parsing error :';\n this.MEDIASOURCE_TYPE_UNSUPPORTED_MESSAGE = 'Error creating source buffer of type : ';\n }\n}\n\nlet errors = new Errors();\nexport default errors;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport Segment from './../vo/Segment';\n\n\nfunction zeroPadToLength(numStr, minStrLength) {\n while (numStr.length < minStrLength) {\n numStr = '0' + numStr;\n }\n return numStr;\n}\n\nfunction getNumberForSegment(segment, segmentIndex) {\n return segment.representation.startNumber + segmentIndex;\n}\n\nexport function unescapeDollarsInTemplate(url) {\n return url ? url.split('$$').join('$') : url;\n}\n\nexport function replaceIDForTemplate(url, value) {\n if (!value || !url || url.indexOf('$RepresentationID$') === -1) {\n return url;\n }\n let v = value.toString();\n return url.split('$RepresentationID$').join(v);\n}\n\nexport function replaceTokenForTemplate(url, token, value) {\n const formatTag = '%0';\n\n let startPos,\n endPos,\n formatTagPos,\n specifier,\n width,\n paddedValue;\n\n const tokenLen = token.length;\n const formatTagLen = formatTag.length;\n\n if (!url) {\n return url;\n }\n\n // keep looping round until all instances of <token> have been\n // replaced. once that has happened, startPos below will be -1\n // and the completed url will be returned.\n while (true) {\n\n // check if there is a valid $<token>...$ identifier\n // if not, return the url as is.\n startPos = url.indexOf('$' + token);\n if (startPos < 0) {\n return url;\n }\n\n // the next '$' must be the end of the identifier\n // if there isn't one, return the url as is.\n endPos = url.indexOf('$', startPos + tokenLen);\n if (endPos < 0) {\n return url;\n }\n\n // now see if there is an additional format tag suffixed to\n // the identifier within the enclosing '$' characters\n formatTagPos = url.indexOf(formatTag, startPos + tokenLen);\n if (formatTagPos > startPos && formatTagPos < endPos) {\n\n specifier = url.charAt(endPos - 1);\n width = parseInt(url.substring(formatTagPos + formatTagLen, endPos - 1), 10);\n\n // support the minimum specifiers required by IEEE 1003.1\n // (d, i , o, u, x, and X) for completeness\n switch (specifier) {\n // treat all int types as uint,\n // hence deliberate fallthrough\n case 'd':\n case 'i':\n case 'u':\n paddedValue = zeroPadToLength(value.toString(), width);\n break;\n case 'x':\n paddedValue = zeroPadToLength(value.toString(16), width);\n break;\n case 'X':\n paddedValue = zeroPadToLength(value.toString(16), width).toUpperCase();\n break;\n case 'o':\n paddedValue = zeroPadToLength(value.toString(8), width);\n break;\n default:\n return url;\n }\n } else {\n paddedValue = value;\n }\n\n url = url.substring(0, startPos) + paddedValue + url.substring(endPos + 1);\n }\n}\n\nfunction getSegment(representation, duration, presentationStartTime, mediaStartTime,\n timelineConverter, presentationEndTime, isDynamic, index) {\n let seg = new Segment();\n\n seg.representation = representation;\n seg.duration = duration;\n seg.presentationStartTime = presentationStartTime;\n seg.mediaStartTime = mediaStartTime;\n seg.availabilityStartTime = timelineConverter.calcAvailabilityStartTimeFromPresentationTime(presentationEndTime, representation, isDynamic);\n seg.availabilityEndTime = timelineConverter.calcAvailabilityEndTimeFromPresentationTime(presentationEndTime + duration, representation, isDynamic);\n seg.wallStartTime = timelineConverter.calcWallTimeForSegment(seg, isDynamic);\n seg.replacementNumber = getNumberForSegment(seg, index);\n seg.index = index;\n\n return seg;\n}\n\nfunction isSegmentAvailable(timelineConverter, representation, segment, isDynamic) {\n const voPeriod = representation.adaptation.period;\n\n // Avoid requesting segments that overlap the period boundary\n if (isFinite(voPeriod.duration) && voPeriod.start + voPeriod.duration <= segment.presentationStartTime) {\n return false;\n }\n\n if (isDynamic) {\n\n if (representation.availabilityTimeOffset === 'INF') {\n return true;\n }\n\n // For dynamic manifests we check if the presentation start time + duration is included in the availability window\n // SAST = Period@start + seg@presentationStartTime + seg@duration\n // ASAST = SAST - ATO\n // SAET = SAST + TSBD + seg@duration\n // refTime serves as an anchor time to compare the availability time of the segments against.\n const refTime = timelineConverter.getClientReferenceTime();\n return segment.availabilityStartTime.getTime() <= refTime && (!isFinite(segment.availabilityEndTime) || segment.availabilityEndTime.getTime() >= refTime);\n }\n\n return true;\n}\n\nexport function getIndexBasedSegment(timelineConverter, isDynamic, representation, index) {\n let duration,\n presentationStartTime,\n presentationEndTime;\n\n\n duration = representation.segmentDuration;\n\n /*\n * From spec - If neither @duration attribute nor SegmentTimeline element is present, then the Representation\n * shall contain exactly one Media Segment. The MPD start time is 0 and the MPD duration is obtained\n * in the same way as for the last Media Segment in the Representation.\n */\n if (isNaN(duration)) {\n duration = representation.adaptation.period.duration;\n }\n\n presentationStartTime = parseFloat((representation.adaptation.period.start + (index * duration)).toFixed(5));\n presentationEndTime = parseFloat((presentationStartTime + duration).toFixed(5));\n\n const mediaTime = timelineConverter.calcMediaTimeFromPresentationTime(presentationStartTime, representation);\n\n const segment = getSegment(representation, duration, presentationStartTime, mediaTime,\n timelineConverter, presentationEndTime, isDynamic, index);\n\n if (!isSegmentAvailable(timelineConverter, representation, segment, isDynamic)) {\n return null;\n }\n\n return segment;\n}\n\nexport function getTimeBasedSegment(timelineConverter, isDynamic, representation, time, duration, fTimescale, url, range, index, tManifest) {\n const scaledTime = time / fTimescale;\n const scaledDuration = duration / fTimescale;\n\n let presentationStartTime,\n presentationEndTime,\n seg;\n\n presentationStartTime = timelineConverter.calcPresentationTimeFromMediaTime(scaledTime, representation);\n presentationEndTime = presentationStartTime + scaledDuration;\n\n seg = getSegment(representation, scaledDuration, presentationStartTime,\n scaledTime,\n timelineConverter, presentationEndTime, isDynamic, index);\n\n if (!isSegmentAvailable(timelineConverter, representation, seg, isDynamic)) {\n return null;\n }\n\n seg.replacementTime = tManifest ? tManifest : time;\n\n url = replaceTokenForTemplate(url, 'Number', seg.replacementNumber);\n url = replaceTokenForTemplate(url, 'Time', seg.replacementTime);\n seg.media = url;\n seg.mediaRange = range;\n\n return seg;\n}\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport FactoryMaker from '../../core/FactoryMaker';\n\n/**\n * @module DefaultURLUtils\n * @description Provides utility functions for operating on URLs.\n * Initially this is simply a method to determine the Base URL of a URL, but\n * should probably include other things provided all over the place such as\n * determining whether a URL is relative/absolute, resolving two paths etc.\n * @ignore\n */\nfunction DefaultURLUtils() {\n\n let resolveFunction;\n\n const schemeRegex = /^[a-z][a-z0-9+\\-_.]*:/i;\n const httpUrlRegex = /^https?:\\/\\//i;\n const httpsUrlRegex = /^https:\\/\\//i;\n const originRegex = /^([a-z][a-z0-9+\\-_.]*:\\/\\/[^\\/]+)\\/?/i;\n\n /**\n * Resolves a url given an optional base url\n * Uses window.URL to do the resolution.\n *\n * @param {string} url\n * @param {string} [baseUrl]\n * @return {string}\n * @memberof module:DefaultURLUtils\n * @instance\n * @private\n */\n const nativeURLResolver = (url, baseUrl) => {\n try {\n return new window.URL(url, baseUrl).toString();\n } catch (e) {\n return url;\n }\n };\n\n /**\n * Resolves a url given an optional base url\n * Does not resolve ./, ../ etc but will do enough to construct something\n * which will satisfy XHR etc when window.URL is not available ie\n * IE11/node etc.\n *\n * @param {string} url\n * @param {string} [baseUrl]\n * @return {string}\n * @memberof module:DefaultURLUtils\n * @instance\n * @private\n */\n const dumbURLResolver = (url, baseUrl) => {\n let baseUrlParseFunc = parseBaseUrl;\n\n if (!baseUrl) {\n return url;\n }\n\n if (!isRelative(url)) {\n return url;\n }\n\n if (isPathAbsolute(url)) {\n baseUrlParseFunc = parseOrigin;\n }\n\n if (isSchemeRelative(url)) {\n baseUrlParseFunc = parseScheme;\n }\n\n const base = baseUrlParseFunc(baseUrl);\n const joinChar =\n base.charAt(base.length - 1) !== '/' &&\n url.charAt(0) !== '/' ?\n '/' : '';\n\n return [base, url].join(joinChar);\n };\n\n function setup() {\n try {\n const u = new window.URL('x', 'http://y'); // eslint-disable-line\n resolveFunction = nativeURLResolver;\n } catch (e) {\n // must be IE11/Node etc\n } finally {\n resolveFunction = resolveFunction || dumbURLResolver;\n }\n }\n\n /**\n * Returns a string that contains the Base URL of a URL, if determinable.\n * @param {string} url - full url\n * @return {string}\n * @memberof module:DefaultURLUtils\n * @instance\n */\n function parseBaseUrl(url) {\n const slashIndex = url.indexOf('/');\n const lastSlashIndex = url.lastIndexOf('/');\n\n if (slashIndex !== -1) {\n // if there is only '//'\n if (lastSlashIndex === slashIndex + 1) {\n return url;\n }\n\n if (url.indexOf('?') !== -1) {\n url = url.substring(0, url.indexOf('?'));\n }\n\n return url.substring(0, lastSlashIndex + 1);\n }\n\n return '';\n }\n\n /**\n * Returns a string that contains the scheme and origin of a URL,\n * if determinable.\n * @param {string} url - full url\n * @return {string}\n * @memberof module:DefaultURLUtils\n * @instance\n */\n function parseOrigin(url) {\n const matches = url.match(originRegex);\n\n if (matches) {\n return matches[1];\n }\n\n return '';\n }\n\n /**\n * Returns a string that contains the fragment of a URL without scheme,\n * if determinable.\n * @param {string} url - full url\n * @return {string}\n * @memberof module:DefaultURLUtils\n * @instance\n */\n function removeHostname(url) {\n let urlParts = /^(?:\\w+\\:\\/\\/)?([^\\/]+)(.*)$/.exec(url); //[1] = host / [2] = path\n return urlParts[2].substring(1);\n }\n\n /**\n * Returns a string that contains the scheme of a URL, if determinable.\n * @param {string} url - full url\n * @return {string}\n * @memberof module:DefaultURLUtils\n * @instance\n */\n function parseScheme(url) {\n const matches = url.match(schemeRegex);\n\n if (matches) {\n return matches[0];\n }\n\n return '';\n }\n\n /**\n * Determines whether the url is relative.\n * @return {boolean}\n * @param {string} url\n * @memberof module:DefaultURLUtils\n * @instance\n */\n function isRelative(url) {\n return !schemeRegex.test(url);\n }\n\n /**\n * Determines whether the url is path-absolute.\n * @return {bool}\n * @param {string} url\n * @memberof module:DefaultURLUtils\n * @instance\n */\n function isPathAbsolute(url) {\n return isRelative(url) && url.charAt(0) === '/';\n }\n\n /**\n * Determines whether the url is scheme-relative.\n * @return {bool}\n * @param {string} url\n * @memberof module:DefaultURLUtils\n * @instance\n */\n function isSchemeRelative(url) {\n return url.indexOf('//') === 0;\n }\n\n /**\n * Determines whether the url is an HTTP-URL as defined in ISO/IEC\n * 23009-1:2014 3.1.15. ie URL with a fixed scheme of http or https\n * @return {bool}\n * @param {string} url\n * @memberof module:DefaultURLUtils\n * @instance\n */\n function isHTTPURL(url) {\n return httpUrlRegex.test(url);\n }\n\n /**\n * Determines whether the supplied url has https scheme\n * @return {bool}\n * @param {string} url\n * @memberof module:DefaultURLUtils\n * @instance\n */\n function isHTTPS(url) {\n return httpsUrlRegex.test(url);\n }\n\n /**\n * Resolves a url given an optional base url\n * @return {string}\n * @param {string} url\n * @param {string} [baseUrl]\n * @memberof module:DefaultURLUtils\n * @instance\n */\n function resolve(url, baseUrl) {\n return resolveFunction(url, baseUrl);\n }\n\n setup();\n\n const instance = {\n parseBaseUrl: parseBaseUrl,\n parseOrigin: parseOrigin,\n parseScheme: parseScheme,\n isRelative: isRelative,\n isPathAbsolute: isPathAbsolute,\n isSchemeRelative: isSchemeRelative,\n isHTTPURL: isHTTPURL,\n isHTTPS: isHTTPS,\n removeHostname: removeHostname,\n resolve: resolve\n };\n\n return instance;\n}\n\nDefaultURLUtils.__dashjs_factory_name = 'DefaultURLUtils';\nexport default FactoryMaker.getSingletonFactory(DefaultURLUtils);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport FactoryMaker from '../../core/FactoryMaker';\nimport DefaultURLUtils from './DefaultURLUtils';\n\n/**\n * @module URLUtils\n * @ignore\n * @description Provides utility functions for operating on URLs.\n * Initially this is simply a method to determine the Base URL of a URL, but\n * should probably include other things provided all over the place such as\n * determining whether a URL is relative/absolute, resolving two paths etc.\n */\nfunction URLUtils() {\n\n let instance;\n let defaultURLUtils;\n let regexUtils = [];\n const context = this.context;\n\n function getUtils(url) {\n let i;\n for (i = 0; i < regexUtils.length; i++) {\n let regex = regexUtils[i].regex;\n if (regex.test(url)) {\n return regexUtils[i].utils;\n }\n }\n return defaultURLUtils;\n }\n\n function setup() {\n defaultURLUtils = DefaultURLUtils(context).getInstance();\n }\n\n /**\n * Register a module to handle specific url.\n * @param {regex} regex - url regex\n * @param {object} utils - object that handles the regex\n * @memberof module:URLUtils\n * @instance\n */\n function registerUrlRegex(regex, utils) {\n regexUtils.push({regex: regex, utils: utils});\n }\n\n function internalCall(functionName, url, baseUrl) {\n let utils = getUtils(baseUrl || url);\n return utils && typeof (utils[functionName]) === 'function' ? utils[functionName](url, baseUrl) : defaultURLUtils[functionName](url, baseUrl);\n }\n\n /**\n * Returns a string that contains the Base URL of a URL, if determinable.\n * @param {string} url - full url\n * @return {string}\n * @memberof module:URLUtils\n * @instance\n */\n function parseBaseUrl(url) {\n return internalCall('parseBaseUrl', url);\n }\n\n /**\n * Returns a string that contains the scheme and origin of a URL,\n * if determinable.\n * @param {string} url - full url\n * @return {string}\n * @memberof module:URLUtils\n * @instance\n */\n function parseOrigin(url) {\n return internalCall('parseOrigin', url);\n }\n\n /**\n * Returns a string that contains the fragment of a URL without scheme,\n * if determinable.\n * @param {string} url - full url\n * @return {string}\n * @memberof module:URLUtils\n * @instance\n */\n function removeHostname(url) {\n return internalCall('removeHostname', url);\n }\n\n /**\n * Returns a string that contains the scheme of a URL, if determinable.\n * @param {string} url - full url\n * @return {string}\n * @memberof module:URLUtils\n * @instance\n */\n function parseScheme(url) {\n return internalCall('parseScheme', url);\n }\n\n /**\n * Determines whether the url is relative.\n * @return {boolean}\n * @param {string} url\n * @memberof module:URLUtils\n * @instance\n */\n function isRelative(url) {\n return internalCall('isRelative', url);\n }\n\n /**\n * Determines whether the url is path-absolute.\n * @return {bool}\n * @param {string} url\n * @memberof module:URLUtils\n * @instance\n */\n function isPathAbsolute(url) {\n return internalCall('isPathAbsolute', url);\n }\n\n /**\n * Determines whether the url is scheme-relative.\n * @return {bool}\n * @param {string} url\n * @memberof module:URLUtils\n * @instance\n */\n function isSchemeRelative(url) {\n return internalCall('isSchemeRelative', url);\n }\n\n /**\n * Determines whether the url is an HTTP-URL as defined in ISO/IEC\n * 23009-1:2014 3.1.15. ie URL with a fixed scheme of http or https\n * @return {bool}\n * @param {string} url\n * @memberof module:URLUtils\n * @instance\n */\n function isHTTPURL(url) {\n return internalCall('isHTTPURL', url);\n }\n\n /**\n * Determines whether the supplied url has https scheme\n * @return {bool}\n * @param {string} url\n * @memberof module:URLUtils\n * @instance\n */\n function isHTTPS(url) {\n return internalCall('isHTTPS', url);\n }\n\n /**\n * Resolves a url given an optional base url\n * @return {string}\n * @param {string} url\n * @param {string} [baseUrl]\n * @memberof module:URLUtils\n * @instance\n */\n function resolve(url, baseUrl) {\n return internalCall('resolve', url, baseUrl);\n }\n\n setup();\n instance = {\n registerUrlRegex: registerUrlRegex,\n parseBaseUrl: parseBaseUrl,\n parseOrigin: parseOrigin,\n parseScheme: parseScheme,\n isRelative: isRelative,\n isPathAbsolute: isPathAbsolute,\n isSchemeRelative: isSchemeRelative,\n isHTTPURL: isHTTPURL,\n isHTTPS: isHTTPS,\n removeHostname: removeHostname,\n resolve: resolve\n };\n\n return instance;\n}\n\nURLUtils.__dashjs_factory_name = 'URLUtils';\nconst factory = FactoryMaker.getSingletonFactory(URLUtils);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport { HTTPRequest } from '../vo/metrics/HTTPRequest';\n\n/**\n * @class\n * @ignore\n */\nclass FragmentRequest {\n constructor(url) {\n this.action = FragmentRequest.ACTION_DOWNLOAD;\n this.startTime = NaN;\n this.mediaStartTime = NaN;\n this.mediaType = null;\n this.mediaInfo = null;\n this.type = null;\n this.duration = NaN;\n this.timescale = NaN;\n this.range = null;\n this.url = url || null;\n this.serviceLocation = null;\n this.requestStartDate = null;\n this.firstByteDate = null;\n this.requestEndDate = null;\n this.quality = NaN;\n this.index = NaN;\n this.availabilityStartTime = null;\n this.availabilityEndTime = null;\n this.wallStartTime = null;\n this.bytesLoaded = NaN;\n this.bytesTotal = NaN;\n this.delayLoadingTime = NaN;\n this.responseType = 'arraybuffer';\n this.representationId = null;\n }\n\n isInitializationRequest() {\n return (this.type && this.type === HTTPRequest.INIT_SEGMENT_TYPE);\n }\n\n setInfo(info) {\n this.type = info && info.init ? HTTPRequest.INIT_SEGMENT_TYPE : HTTPRequest.MEDIA_SEGMENT_TYPE;\n this.url = info && info.url ? info.url : null;\n this.range = info && info.range ? info.range.start + '-' + info.range.end : null;\n this.mediaType = info && info.mediaType ? info.mediaType : null;\n }\n}\n\nFragmentRequest.ACTION_DOWNLOAD = 'download';\nFragmentRequest.ACTION_COMPLETE = 'complete';\n\nexport default FragmentRequest;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Constants from '../constants/Constants';\n\nexport function checkParameterType(parameter, type) {\n if (typeof parameter !== type) {\n throw Constants.BAD_ARGUMENT_ERROR;\n }\n}\n\nexport function checkInteger(parameter) {\n const isInt = parameter !== null && !isNaN(parameter) && (parameter % 1 === 0);\n\n if (!isInt) {\n throw Constants.BAD_ARGUMENT_ERROR + ' : argument is not an integer';\n }\n}\n\nexport function checkRange(parameter, min, max) {\n if (parameter < min || parameter > max) {\n throw Constants.BAD_ARGUMENT_ERROR + ' : argument out of range';\n }\n}\n\nexport function checkIsVideoOrAudioType(type) {\n if (typeof type !== 'string' || (type !== Constants.AUDIO && type !== Constants.VIDEO)) {\n throw Constants.BAD_ARGUMENT_ERROR;\n }\n}","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * @class\n * @ignore\n */\n\nimport path from 'path-browserify'\n\nclass Utils {\n static mixin(dest, source, copy) {\n let s;\n let empty = {};\n if (dest) {\n for (let name in source) {\n if (source.hasOwnProperty(name)) {\n s = source[name];\n if (!(name in dest) || (dest[name] !== s && (!(name in empty) || empty[name] !== s))) {\n if (typeof dest[name] === 'object' && dest[name] !== null) {\n dest[name] = Utils.mixin(dest[name], s, copy);\n } else {\n dest[name] = copy(s);\n }\n }\n }\n }\n }\n return dest;\n }\n\n static clone(src) {\n if (!src || typeof src !== 'object') {\n return src; // anything\n }\n let r;\n if (src instanceof Array) {\n // array\n r = [];\n for (let i = 0, l = src.length; i < l; ++i) {\n if (i in src) {\n r.push(Utils.clone(src[i]));\n }\n }\n } else {\n r = {};\n }\n return Utils.mixin(r, src, Utils.clone);\n }\n\n static addAditionalQueryParameterToUrl(url, params) {\n try {\n if (!params || params.length === 0) {\n return url;\n }\n\n let modifiedUrl = new URL(url);\n\n params.forEach((param) => {\n if (param.key && param.value) {\n modifiedUrl.searchParams.set(param.key, param.value);\n }\n });\n\n return modifiedUrl.href;\n\n\n } catch (e) {\n return url;\n }\n }\n\n static parseHttpHeaders(headerStr) {\n let headers = {};\n if (!headerStr) {\n return headers;\n }\n\n // Trim headerStr to fix a MS Edge bug with xhr.getAllResponseHeaders method\n // which send a string starting with a \"\\n\" character\n let headerPairs = headerStr.trim().split('\\u000d\\u000a');\n for (let i = 0, ilen = headerPairs.length; i < ilen; i++) {\n let headerPair = headerPairs[i];\n let index = headerPair.indexOf('\\u003a\\u0020');\n if (index > 0) {\n headers[headerPair.substring(0, index)] = headerPair.substring(index + 2);\n }\n }\n return headers;\n }\n\n static generateUuid() {\n let dt = new Date().getTime();\n const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n const r = (dt + Math.random() * 16) % 16 | 0;\n dt = Math.floor(dt / 16);\n return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);\n });\n return uuid;\n }\n\n static generateHashCode(string) {\n let hash = 0;\n\n if (string.length === 0) {\n return hash;\n }\n\n for (let i = 0; i < string.length; i++) {\n const chr = string.charCodeAt(i);\n hash = ((hash << 5) - hash) + chr;\n hash |= 0;\n }\n return hash;\n }\n\n /**\n * Compares both urls and returns a relative url (target relative to original)\n * @param {string} original\n * @param {string} target\n * @return {string|*}\n */\n static getRelativeUrl(originalUrl, targetUrl) {\n try {\n const original = new URL(originalUrl);\n const target = new URL(targetUrl);\n\n // Unify the protocol to compare the origins\n original.protocol = target.protocol;\n if (original.origin !== target.origin) {\n return targetUrl;\n }\n\n // Use the relative path implementation of the path library. We need to cut off the actual filename in the end to get the relative path\n let relativePath = path.relative(original.pathname.substr(0, original.pathname.lastIndexOf('/')), target.pathname.substr(0, target.pathname.lastIndexOf('/')));\n\n // In case the relative path is empty (both path are equal) return the filename only. Otherwise add a slash in front of the filename\n const startIndexOffset = relativePath.length === 0 ? 1 : 0;\n relativePath += target.pathname.substr(target.pathname.lastIndexOf('/') + startIndexOffset, target.pathname.length - 1);\n\n // Build the other candidate, e.g. the 'host relative' path that starts with \"/\", and return the shortest of the two candidates.\n if (target.pathname.length < relativePath.length) {\n return target.pathname;\n }\n return relativePath;\n } catch (e) {\n return targetUrl\n }\n }\n}\n\nexport default Utils;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport FactoryMaker from './FactoryMaker';\nimport Utils from './Utils.js';\nimport Debug from '../core/Debug';\nimport Constants from '../streaming/constants/Constants';\nimport {HTTPRequest} from '../streaming/vo/metrics/HTTPRequest';\n\n/** @module Settings\n * @description Define the configuration parameters of Dash.js MediaPlayer.\n * @see {@link module:Settings~PlayerSettings PlayerSettings} for further information about the supported configuration properties.\n */\n\n\n/**\n * @typedef {Object} PlayerSettings\n * @property {module:Settings~DebugSettings} [debug]\n * Debug related settings.\n * @property {module:Settings~ErrorSettings} [errors]\n * Error related settings\n * @property {module:Settings~StreamingSettings} [streaming]\n * Streaming related settings.\n * @example\n *\n * // Full settings object\n * settings = {\n * debug: {\n * logLevel: Debug.LOG_LEVEL_WARNING,\n * dispatchEvent: false\n * },\n * streaming: {\n * abandonLoadTimeout: 10000,\n * wallclockTimeUpdateInterval: 100,\n * lowLatencyEnabled: false,\n * lowLatencyEnabledByManifest: true,\n * manifestUpdateRetryInterval: 100,\n * cacheInitSegments: true,\n * eventControllerRefreshDelay: 100,\n * capabilities: {\n * filterUnsupportedEssentialProperties: true,\n * useMediaCapabilitiesApi: false\n * },\n * timeShiftBuffer: {\n * calcFromSegmentTimeline: false,\n * fallbackToSegmentTimeline: true\n * },\n * metrics: {\n * maxListDepth: 100\n * },\n * delay: {\n * liveDelayFragmentCount: NaN,\n * liveDelay: NaN,\n * useSuggestedPresentationDelay: true,\n * applyServiceDescription: true\n * },\n * protection: {\n * keepProtectionMediaKeys: false\n * },\n * buffer: {\n * enableSeekDecorrelationFix: true,\n * fastSwitchEnabled: true,\n * flushBufferAtTrackSwitch: false,\n * reuseExistingSourceBuffers: true,\n * bufferPruningInterval: 10,\n * bufferToKeep: 20,\n * bufferTimeAtTopQuality: 30,\n * bufferTimeAtTopQualityLongForm: 60,\n * initialBufferLevel: NaN,\n * stableBufferTime: 12,\n * longFormContentDurationThreshold: 600,\n * stallThreshold: 0.5,\n * useAppendWindow: true,\n * setStallState: false\n * },\n * gaps: {\n * jumpGaps: true,\n * jumpLargeGaps: true,\n * smallGapLimit: 1.5,\n * threshold: 0.3,\n * enableSeekFix: false\n * },\n * utcSynchronization: {\n * enabled: true,\n * useManifestDateHeaderTimeSource: true,\n * backgroundAttempts: 2,\n * timeBetweenSyncAttempts: 30,\n * maximumTimeBetweenSyncAttempts: 600,\n * minimumTimeBetweenSyncAttempts: 2,\n * timeBetweenSyncAttemptsAdjustmentFactor: 2,\n * maximumAllowedDrift: 100,\n * enableBackgroundSyncAfterSegmentDownloadError: true,\n * defaultTimingSource: {\n * scheme: 'urn:mpeg:dash:utc:http-xsdate:2014',\n * value: 'http://time.akamai.com/?iso&ms'\n * }\n * },\n * scheduling: {\n * defaultTimeout: 300,\n * lowLatencyTimeout: 100,\n * scheduleWhilePaused: true\n * },\n * text: {\n * defaultEnabled: true\n * },\n * liveCatchup: {\n * minDrift: 0.02,\n * maxDrift: 12,\n * playbackRate: 0.5,\n * latencyThreshold: 60,\n * playbackBufferMin: 0.5,\n * enabled: false,\n * mode: Constants.LIVE_CATCHUP_MODE_DEFAULT\n * },\n * lastBitrateCachingInfo: { enabled: true, ttl: 360000 },\n * lastMediaSettingsCachingInfo: { enabled: true, ttl: 360000 },\n * cacheLoadThresholds: { video: 50, audio: 5 },\n * trackSwitchMode: {\n * audio: Constants.TRACK_SWITCH_MODE_ALWAYS_REPLACE,\n * video: Constants.TRACK_SWITCH_MODE_NEVER_REPLACE\n * },\n * selectionModeForInitialTrack: Constants.TRACK_SELECTION_MODE_HIGHEST_SELECTION_PRIORITY,\n * fragmentRequestTimeout: 0,\n * retryIntervals: {\n * [HTTPRequest.MPD_TYPE]: 500,\n * [HTTPRequest.XLINK_EXPANSION_TYPE]: 500,\n * [HTTPRequest.MEDIA_SEGMENT_TYPE]: 1000,\n * [HTTPRequest.INIT_SEGMENT_TYPE]: 1000,\n * [HTTPRequest.BITSTREAM_SWITCHING_SEGMENT_TYPE]: 1000,\n * [HTTPRequest.INDEX_SEGMENT_TYPE]: 1000,\n * [HTTPRequest.MSS_FRAGMENT_INFO_SEGMENT_TYPE]: 1000,\n * [HTTPRequest.LICENSE]: 1000,\n * [HTTPRequest.OTHER_TYPE]: 1000,\n * lowLatencyReductionFactor: 10\n * },\n * retryAttempts: {\n * [HTTPRequest.MPD_TYPE]: 3,\n * [HTTPRequest.XLINK_EXPANSION_TYPE]: 1,\n * [HTTPRequest.MEDIA_SEGMENT_TYPE]: 3,\n * [HTTPRequest.INIT_SEGMENT_TYPE]: 3,\n * [HTTPRequest.BITSTREAM_SWITCHING_SEGMENT_TYPE]: 3,\n * [HTTPRequest.INDEX_SEGMENT_TYPE]: 3,\n * [HTTPRequest.MSS_FRAGMENT_INFO_SEGMENT_TYPE]: 3,\n * [HTTPRequest.LICENSE]: 3,\n * [HTTPRequest.OTHER_TYPE]: 3,\n * lowLatencyMultiplyFactor: 5\n * },\n * abr: {\n * movingAverageMethod: Constants.MOVING_AVERAGE_SLIDING_WINDOW,\n * ABRStrategy: Constants.ABR_STRATEGY_DYNAMIC,\n * additionalAbrRules: {\n * insufficientBufferRule: false,\n * switchHistoryRule: true,\n * droppedFramesRule: true,\n * abandonRequestsRule: false\n * },\n * bandwidthSafetyFactor: 0.9,\n * useDefaultABRRules: true,\n * useDeadTimeLatency: true,\n * limitBitrateByPortal: false,\n * usePixelRatioInLimitBitrateByPortal: false,\n * maxBitrate: { audio: -1, video: -1 },\n * minBitrate: { audio: -1, video: -1 },\n * maxRepresentationRatio: { audio: 1, video: 1 },\n * initialBitrate: { audio: -1, video: -1 },\n * initialRepresentationRatio: { audio: -1, video: -1 },\n * autoSwitchBitrate: { audio: true, video: true },\n * fetchThroughputCalculationMode: Constants.ABR_FETCH_THROUGHPUT_CALCULATION_DOWNLOADED_DATA\n * },\n * cmcd: {\n * enabled: false,\n * sid: null,\n * cid: null,\n * rtp: null,\n * rtpSafetyFactor: 5,\n * mode: Constants.CMCD_MODE_QUERY\n * }\n * },\n * errors: {\n * recoverAttempts: {\n * mediaErrorDecode: 5\n * }\n * }\n * }\n */\n\n/**\n * @typedef {Object} TimeShiftBuffer\n * @property {boolean} [calcFromSegmentTimeline=false]\n * Enable calculation of the DVR window for SegmentTimeline manifests based on the entries in \\<SegmentTimeline\\>.\n * * @property {boolean} [fallbackToSegmentTimeline=true]\n * In case the MPD uses \\<SegmentTimeline\\ and no segment is found within the DVR window the DVR window is calculated based on the entries in \\<SegmentTimeline\\>.\n */\n\n/**\n * @typedef {Object} LiveDelay\n * @property {number} [liveDelayFragmentCount=NaN]\n * Changing this value will lower or increase live stream latency.\n *\n * The detected segment duration will be multiplied by this value to define a time in seconds to delay a live stream from the live edge.\n *\n * Lowering this value will lower latency but may decrease the player's ability to build a stable buffer.\n * @property {number} [liveDelay]\n * Equivalent in seconds of setLiveDelayFragmentCount.\n *\n * Lowering this value will lower latency but may decrease the player's ability to build a stable buffer.\n *\n * This value should be less than the manifest duration by a couple of segment durations to avoid playback issues.\n *\n * If set, this parameter will take precedence over setLiveDelayFragmentCount and manifest info.\n * @property {boolean} [useSuggestedPresentationDelay=true]\n * Set to true if you would like to overwrite the default live delay and honor the SuggestedPresentationDelay attribute in by the manifest.\n * @property {boolean} [applyServiceDescription=true]\n * Set to true if dash.js should use latency targets defined in ServiceDescription elements\n */\n\n/**\n * @typedef {Object} Buffer\n * @property {boolean} [enableSeekDecorrelationFix=false]\n * Enables a workaround for playback start on some devices, e.g. WebOS 4.9.\n * It is necessary because some browsers do not support setting currentTime on video element to a value that is outside of current buffer.\n *\n * If you experience unexpected seeking triggered by BufferController, you can try setting this value to false.\n\n * @property {boolean} [fastSwitchEnabled=true]\n * When enabled, after an ABR up-switch in quality, instead of requesting and appending the next fragment at the end of the current buffer range it is requested and appended closer to the current time.\n *\n * When enabled, The maximum time to render a higher quality is current time + (1.5 * fragment duration).\n *\n * Note, When ABR down-switch is detected, we appended the lower quality at the end of the buffer range to preserve the\n * higher quality media for as long as possible.\n *\n * If enabled, it should be noted there are a few cases when the client will not replace inside buffer range but rather just append at the end.\n * 1. When the buffer level is less than one fragment duration.\n * 2. The client is in an Abandonment State due to recent fragment abandonment event.\n *\n * Known issues:\n * 1. In IE11 with auto switching off, if a user switches to a quality they can not download in time the fragment may be appended in the same range as the playhead or even in the past, in IE11 it may cause a stutter or stall in playback.\n * @property {boolean} [flushBufferAtTrackSwitch=false]\n * When enabled, after a track switch and in case buffer is being replaced, the video element is flushed (seek at current playback time) once a segment of the new track is appended in buffer in order to force video decoder to play new track.\n *\n * This can be required on some devices like GoogleCast devices to make track switching functional.\n *\n * Otherwise track switching will be effective only once after previous buffered track is fully consumed.\n * @property {boolean} [reuseExistingSourceBuffers=true]\n * Enable reuse of existing MediaSource Sourcebuffers during period transition.\n * @property {number} [bufferPruningInterval=10]\n * The interval of pruning buffer in seconds.\n * @property {number} [bufferToKeep=20]\n * This value influences the buffer pruning logic.\n *\n * Allows you to modify the buffer that is kept in source buffer in seconds.\n * 0|-----------bufferToPrune-----------|-----bufferToKeep-----|currentTime|\n * @property {number} [bufferTimeAtTopQuality=30]\n * The time that the internal buffer target will be set to once playing the top quality.\n *\n * If there are multiple bitrates in your adaptation, and the media is playing at the highest bitrate, then we try to build a larger buffer at the top quality to increase stability and to maintain media quality.\n * @property {number} [bufferTimeAtTopQualityLongForm=60]\n * The time that the internal buffer target will be set to once playing the top quality for long form content.\n * @property {number} [longFormContentDurationThreshold=600]\n * The threshold which defines if the media is considered long form content.\n *\n * This will directly affect the buffer targets when playing back at the top quality.\n * @property {number} [initialBufferLevel=NaN]\n * Initial buffer level before playback starts\n * @property {number} [stableBufferTime=12]\n * The time that the internal buffer target will be set to post startup/seeks (NOT top quality).\n *\n * When the time is set higher than the default you will have to wait longer to see automatic bitrate switches but will have a larger buffer which will increase stability.\n * @property {number} [stallThreshold=0.3]\n * Stall threshold used in BufferController.js to determine whether a track should still be changed and which buffer range to prune.\n * @property {boolean} [useAppendWindow=true]\n * Specifies if the appendWindow attributes of the MSE SourceBuffers should be set according to content duration from manifest.\n * @property {boolean} [setStallState=false]\n * Specifies if we fire manual waiting events once the stall threshold is reached\n */\n\n/**\n * @typedef {Object} module:Settings~AudioVideoSettings\n * @property {number|boolean|string} [audio]\n * Configuration for audio media type of tracks.\n * @property {number|boolean|string} [video]\n * Configuration for video media type of tracks.\n */\n\n/**\n * @typedef {Object} DebugSettings\n * @property {number} [logLevel=dashjs.Debug.LOG_LEVEL_WARNING]\n * Sets up the log level. The levels are cumulative.\n *\n * For example, if you set the log level to dashjs.Debug.LOG_LEVEL_WARNING all warnings, errors and fatals will be logged.\n *\n * Possible values.\n *\n * - dashjs.Debug.LOG_LEVEL_NONE\n * No message is written in the browser console.\n *\n * - dashjs.Debug.LOG_LEVEL_FATAL\n * Log fatal errors.\n * An error is considered fatal when it causes playback to fail completely.\n *\n * - dashjs.Debug.LOG_LEVEL_ERROR\n * Log error messages.\n *\n * - dashjs.Debug.LOG_LEVEL_WARNING\n * Log warning messages.\n *\n * - dashjs.Debug.LOG_LEVEL_INFO\n * Log info messages.\n *\n * - dashjs.Debug.LOG_LEVEL_DEBUG\n * Log debug messages.\n * @property {boolean} [dispatchEvent=false]\n * Enable to trigger a Events.LOG event whenever log output is generated.\n *\n * Note this will be dispatched regardless of log level.\n */\n\n/**\n * @typedef {Object} module:Settings~ErrorSettings\n * @property {object} [recoverAttempts={mediaErrorDecode: 5}]\n * Defines the maximum number of recover attempts for specific media errors.\n *\n * For mediaErrorDecode the player will reset the MSE and skip the blacklisted segment that caused the decode error. The resulting gap will be handled by the GapController.\n */\n\n/**\n * @typedef {Object} CachingInfoSettings\n * @property {boolean} [enable]\n * Enable or disable the caching feature.\n * @property {number} [ttl]\n * Time to live.\n *\n * A value defined in milliseconds representing how log to cache the settings for.\n */\n\n/**\n * @typedef {Object} Gaps\n * @property {boolean} [jumpGaps=true]\n * Sets whether player should jump small gaps (discontinuities) in the buffer.\n * @property {boolean} [jumpLargeGaps=true]\n * Sets whether player should jump large gaps (discontinuities) in the buffer.\n * @property {number} [smallGapLimit=1.5]\n * Time in seconds for a gap to be considered small.\n * @property {number} [threshold=0.3]\n * Threshold at which the gap handling is executed. If currentRangeEnd - currentTime < threshold the gap jump will be triggered.\n * For live stream the jump might be delayed to keep a consistent live edge.\n * Note that the amount of buffer at which platforms automatically stall might differ.\n * @property {boolean} [enableSeekFix=false]\n * Enables the adjustment of the seek target once no valid segment request could be generated for a specific seek time. This can happen if the user seeks to a position for which there is a gap in the timeline.\n */\n\n/**\n * @typedef {Object} UtcSynchronizationSettings\n * @property {boolean} [enabled=true]\n * Enables or disables the UTC clock synchronization\n * @property {boolean} [useManifestDateHeaderTimeSource=true]\n * Allows you to enable the use of the Date Header, if exposed with CORS, as a timing source for live edge detection.\n *\n * The use of the date header will happen only after the other timing source that take precedence fail or are omitted as described.\n * @property {number} [backgroundAttempts=2]\n * Number of synchronization attempts to perform in the background after an initial synchronization request has been done. This is used to verify that the derived client-server offset is correct.\n *\n * The background requests are async and done in parallel to the start of the playback.\n *\n * This value is also used to perform a resync after 404 errors on segments.\n * @property {number} [timeBetweenSyncAttempts=30]\n * The time in seconds between two consecutive sync attempts.\n *\n * Note: This value is used as an initial starting value. The internal value of the TimeSyncController is adjusted during playback based on the drift between two consecutive synchronization attempts.\n *\n * Note: A sync is only performed after an MPD update. In case the @minimumUpdatePeriod is larger than this value the sync will be delayed until the next MPD update.\n * @property {number} [maximumTimeBetweenSyncAttempts=600]\n * The maximum time in seconds between two consecutive sync attempts.\n *\n * @property {number} [minimumTimeBetweenSyncAttempts=2]\n * The minimum time in seconds between two consecutive sync attempts.\n *\n * @property {number} [timeBetweenSyncAttemptsAdjustmentFactor=2]\n * The factor used to multiply or divide the timeBetweenSyncAttempts parameter after a sync. The maximumAllowedDrift defines whether this value is used as a factor or a dividend.\n *\n * @property {number} [maximumAllowedDrift=100]\n * The maximum allowed drift specified in milliseconds between two consecutive synchronization attempts.\n *\n * @property {boolean} [enableBackgroundSyncAfterSegmentDownloadError=true]\n * Enables or disables the background sync after the player ran into a segment download error.\n *\n * @property {object} [defaultTimingSource={scheme:'urn:mpeg:dash:utc:http-xsdate:2014',value: 'http://time.akamai.com/?iso&ms'}]\n * The default timing source to be used. The timing sources in the MPD take precedence over this one.\n */\n\n/**\n * @typedef {Object} Scheduling\n * @property {number} [defaultTimeout=300]\n * Default timeout between two consecutive segment scheduling attempts\n * @property {number} [lowLatencyTimeout]\n * Default timeout between two consecutive low-latency segment scheduling attempts\n * @property {boolean} [scheduleWhilePaused=true]\n * Set to true if you would like dash.js to keep downloading fragments in the background when the video element is paused.\n */\n\n/**\n * @typedef {Object} Text\n * @property {number} [defaultEnabled=true]\n * Enable/disable subtitle rendering by default.\n */\n\n/**\n * @typedef {Object} LiveCatchupSettings\n * @property {number} [minDrift=0.02]\n * Use this method to set the minimum latency deviation allowed before activating catch-up mechanism.\n *\n * In low latency mode, when the difference between the measured latency and the target one, as an absolute number, is higher than the one sets with this method, then dash.js increases/decreases playback rate until target latency is reached.\n *\n * LowLatencyMinDrift should be provided in seconds, and it uses values between 0.0 and 0.5.\n *\n * Note: Catch-up mechanism is only applied when playing low latency live streams.\n * @property {number} [maxDrift=12]\n * Use this method to set the maximum latency deviation allowed before dash.js to do a seeking to live position.\n *\n * In low latency mode, when the difference between the measured latency and the target one, as an absolute number, is higher than the one sets with this method, then dash.js does a seek to live edge position minus the target live delay.\n *\n * LowLatencyMaxDriftBeforeSeeking should be provided in seconds.\n *\n * If 0, then seeking operations won't be used for fixing latency deviations.\n *\n * Note: Catch-up mechanism is only applied when playing low latency live streams.\n * @property {number} [playbackRate=0.5]\n * Use this parameter to set the maximum catch up rate, as a percentage, for low latency live streams.\n *\n * In low latency mode, when measured latency is higher/lower than the target one, dash.js increases/decreases playback rate respectively up to (+/-) the percentage defined with this method until target is reached.\n *\n * Valid values for catch up rate are in range 0-0.5 (0-50%).\n *\n * Set it to 0 to turn off live catch up feature.\n *\n * Note: Catch-up mechanism is only applied when playing low latency live streams.\n * @property {number} [latencyThreshold=NaN]\n * Use this parameter to set the maximum threshold for which live catch up is applied.\n *\n * For instance, if this value is set to 8 seconds, then live catchup is only applied if the current live latency is equal or below 8 seconds.\n *\n * The reason behind this parameter is to avoid an increase of the playback rate if the user seeks within the DVR window.\n *\n * If no value is specified this will be twice the maximum live delay.\n *\n * The maximum live delay is either specified in the manifest as part of a ServiceDescriptor or calculated the following:\n * maximumLiveDelay = targetDelay + liveCatchupMinDrift.\n *\n * @property {number} [playbackBufferMin=NaN]\n * Use this parameter to specify the minimum buffer which is used for LoL+ based playback rate reduction.\n *\n *\n * @property {boolean} [enabled=false]\n * Use this parameter to enable the catchup mode for non low-latency streams.\n *\n * @property {string} [mode=\"liveCatchupModeDefault\"]\n * Use this parameter to switch between different catchup modes.\n *\n * Options: \"liveCatchupModeDefault\" or \"liveCatchupModeLOLP\".\n *\n * Note: Catch-up mechanism is automatically applied when playing low latency live streams.\n */\n\n/**\n * @typedef {Object} RequestTypeSettings\n * @property {number} [MPD]\n * Manifest type of requests.\n * @property {number} [XLinkExpansion]\n * XLink expansion type of requests.\n * @property {number} [InitializationSegment]\n * Request to retrieve an initialization segment.\n * @property {number} [IndexSegment]\n * Request to retrieve an index segment (SegmentBase).\n * @property {number} [MediaSegment]\n * Request to retrieve a media segment (video/audio/image/text chunk).\n * @property {number} [BitstreamSwitchingSegment]\n * Bitrate stream switching type of request.\n * @property {number} [FragmentInfoSegment]\n * Request to retrieve a FragmentInfo segment (specific to Smooth Streaming live streams).\n * @property {number} [other]\n * Other type of request.\n * @property {number} [lowLatencyReductionFactor]\n * For low latency mode, values of type of request are divided by lowLatencyReductionFactor.\n *\n * Note: It's not type of request.\n * @property {number} [lowLatencyMultiplyFactor]\n * For low latency mode, values of type of request are multiplied by lowLatencyMultiplyFactor.\n *\n * Note: It's not type of request.\n */\n\n/**\n * @typedef {Object} Protection\n * @property {boolean} [keepProtectionMediaKeys=false]\n * Set the value for the ProtectionController and MediaKeys life cycle.\n *\n * If true, the ProtectionController and then created MediaKeys and MediaKeySessions will be preserved during the MediaPlayer lifetime.\n * @property {boolean} ignoreEmeEncryptedEvent\n * If set to true the player will ignore \"encrypted\" and \"needkey\" events thrown by the EME.\n */\n\n/**\n * @typedef {Object} Capabilities\n * @property {boolean} [filterUnsupportedEssentialProperties=true]\n * Enable to filter all the AdaptationSets and Representations which contain an unsupported \\<EssentialProperty\\> element.\n * @property {boolean} [useMediaCapabilitiesApi=false]\n * Enable to use the MediaCapabilities API to check whether codecs are supported. If disabled MSE.isTypeSupported will be used instead.\n */\n\n/**\n * @typedef {Object} AbrSettings\n * @property {string} [movingAverageMethod=\"slidingWindow\"]\n * Sets the moving average method used for smoothing throughput estimates.\n *\n * Valid methods are \"slidingWindow\" and \"ewma\".\n *\n * The call has no effect if an invalid method is passed.\n *\n * The sliding window moving average method computes the average throughput using the last four segments downloaded.\n *\n * If the stream is live (as opposed to VOD), then only the last three segments are used.\n *\n * If wide variations in throughput are detected, the number of segments can be dynamically increased to avoid oscillations.\n *\n * The exponentially weighted moving average (EWMA) method computes the average using exponential smoothing.\n *\n * Two separate estimates are maintained, a fast one with a three-second half life and a slow one with an eight-second half life.\n *\n * The throughput estimate at any time is the minimum of the fast and slow estimates.\n *\n * This allows a fast reaction to a bandwidth drop and prevents oscillations on bandwidth spikes.\n * @property {string} [ABRStrategy=\"abrDynamic\"]\n * Returns the current ABR strategy being used: \"abrDynamic\", \"abrBola\" or \"abrThroughput\".\n * @property {object} [trackSwitchMode={video: \"neverReplace\", audio: \"alwaysReplace\"}]\n * @property {object} [additionalAbrRules={insufficientBufferRule: false,switchHistoryRule: true,droppedFramesRule: true,abandonRequestsRule: false}]\n * Enable/Disable additional ABR rules in case ABRStrategy is set to \"abrDynamic\", \"abrBola\" or \"abrThroughput\".\n * @property {number} [bandwidthSafetyFactor=0.9]\n * Standard ABR throughput rules multiply the throughput by this value.\n *\n * It should be between 0 and 1, with lower values giving less rebuffering (but also lower quality).\n * @property {boolean} [useDefaultABRRules=true]\n * Should the default ABR rules be used, or the custom ones added.\n * @property {boolean} [useDeadTimeLatency=true]\n * If true, only the download portion will be considered part of the download bitrate and latency will be regarded as static.\n *\n * If false, the reciprocal of the whole transfer time will be used.\n * @property {boolean} [limitBitrateByPortal=false]\n * If true, the size of the video portal will limit the max chosen video resolution.\n * @property {boolean} [usePixelRatioInLimitBitrateByPortal=false]\n * Sets whether to take into account the device's pixel ratio when defining the portal dimensions.\n *\n * Useful on, for example, retina displays.\n * @property {module:Settings~AudioVideoSettings} [maxBitrate={audio: -1, video: -1}]\n * The maximum bitrate that the ABR algorithms will choose.\n *\n * Use NaN for no limit.\n * @property {module:Settings~AudioVideoSettings} [minBitrate={audio: -1, video: -1}]\n * The minimum bitrate that the ABR algorithms will choose.\n *\n * Use NaN for no limit.\n * @property {module:Settings~AudioVideoSettings} [maxRepresentationRatio={audio: 1, video: 1}]\n * When switching multi-bitrate content (auto or manual mode) this property specifies the maximum representation allowed, as a proportion of the size of the representation set.\n *\n * You can set or remove this cap at anytime before or during playback.\n *\n * To clear this setting you set the value to 1.\n *\n * If both this and maxAllowedBitrate are defined, maxAllowedBitrate is evaluated first, then maxAllowedRepresentation, i.e. the lowest value from executing these rules is used.\n *\n * This feature is typically used to reserve higher representations for playback only when connected over a fast connection.\n * @property {module:Settings~AudioVideoSettings} [initialBitrate={audio: -1, video: -1}]\n * Explicitly set the starting bitrate for audio or video.\n * @property {module:Settings~AudioVideoSettings} [initialRepresentationRatio={audio: -1, video: -1}]\n * Explicitly set the initial representation ratio.\n *\n * If initalBitrate is specified, this is ignored.\n * @property {module:Settings~AudioVideoSettings} [autoSwitchBitrate={audio: true, video: true}]\n * Indicates whether the player should enable ABR algorithms to switch the bitrate.\n *\n * @property {string} [fetchThroughputCalculationMode=\"abrFetchThroughputCalculationDownloadedData\"]\n * Algorithm to determine the throughput in case the Fetch API is used for low latency streaming.\n *\n * For details please check the samples section and FetchLoader.js.\n */\n\n/**\n * @typedef {Object} module:Settings~CmcdSettings\n * @property {boolean} [enable=false]\n * Enable or disable the CMCD reporting.\n * @property {string} [sid]\n * GUID identifying the current playback session.\n *\n * Should be in UUID format.\n *\n * If not specified a UUID will be automatically generated.\n * @property {string} [cid]\n * A unique string to identify the current content.\n *\n * If not specified it will be a hash of the MPD url.\n * @property {number} [rtp]\n * The requested maximum throughput that the client considers sufficient for delivery of the asset.\n *\n * If not specified this value will be dynamically calculated in the CMCDModel based on the current buffer level.\n * @property {number} [rtpSafetyFactor]\n * This value is used as a factor for the rtp value calculation: rtp = minBandwidth * rtpSafetyFactor\n *\n * If not specified this value defaults to 5. Note that this value is only used when no static rtp value is defined.\n * @property {number} [mode]\n * The method to use to attach cmcd metrics to the requests. 'query' to use query parameters, 'header' to use http headers.\n *\n * If not specified this value defaults to 'query'.\n */\n\n/**\n * @typedef {Object} Metrics\n * @property {number} [metricsMaxListDepth=100]\n * Maximum number of metrics that are persisted per type.\n */\n\n/**\n * @typedef {Object} StreamingSettings\n * @property {number} [abandonLoadTimeout=10000]\n * A timeout value in seconds, which during the ABRController will block switch-up events.\n *\n * This will only take effect after an abandoned fragment event occurs.\n * @property {number} [wallclockTimeUpdateInterval=50]\n * How frequently the wallclockTimeUpdated internal event is triggered (in milliseconds).\n * @property {boolean} [lowLatencyEnabled=false]\n * Manually enable or disable low latency mode.\n *\n * @property {boolean} [lowLatencyEnabledByManifest=true]\n * If this value is set to true we enable the low latency mode based on MPD attributes: Specifically in case \"availabilityTimeComplete\" of the current representation is set to false.\n *\n * @property {number} [manifestUpdateRetryInterval=100]\n * For live streams, set the interval-frequency in milliseconds at which dash.js will check if the current manifest is still processed before downloading the next manifest once the minimumUpdatePeriod time has.\n * @property {boolean} [cacheInitSegments=true]\n * Enables the caching of init segments to avoid requesting the init segments before each representation switch.\n * @property {number} [eventControllerRefreshDelay=100]\n * Defines the delay in milliseconds between two consecutive checks for events to be fired.\n * @property {module:Settings~Metrics} metrics Metric settings\n * @property {module:Settings~LiveDelay} delay Live Delay settings\n * @property {module:Settings~TimeShiftBuffer} timeShiftBuffer TimeShiftBuffer settings\n * @property {module:Settings~Protection} protection DRM related settings\n * @property {module:Settings~Capabilities} capabilities Capability related settings\n * @property {module:Settings~Buffer} buffer Buffer related settings\n * @property {module:Settings~Gaps} gaps Gap related settings\n * @property {module:Settings~UtcSynchronizationSettings} utcSynchronization Settings related to UTC clock synchronization\n * @property {module:Settings~Scheduling} scheduling Settings related to segment scheduling\n * @property {module:Settings~Text} text Settings related to Subtitles and captions\n * @property {module:Settings~LiveCatchupSettings} liveCatchup Settings related to live catchup.\n * @property {module:Settings~CachingInfoSettings} [lastBitrateCachingInfo={enabled: true, ttl: 360000}]\n * Set to false if you would like to disable the last known bit rate from being stored during playback and used to set the initial bit rate for subsequent playback within the expiration window.\n *\n * The default expiration is one hour, defined in milliseconds.\n *\n * If expired, the default initial bit rate (closest to 1000 kbps) will be used for that session and a new bit rate will be stored during that session.\n * @property {module:Settings~AudioVideoSettings} [cacheLoadThresholds={video: 50, audio: 5}]\n * For a given media type, the threshold which defines if the response to a fragment request is coming from browser cache or not.\n * @property {module:Settings~AudioVideoSettings} [trackSwitchMode={video: \"neverReplace\", audio: \"alwaysReplace\"}]\n * For a given media type defines if existing segments in the buffer should be overwritten once the track is switched. For instance if the user switches the audio language the existing segments in the audio buffer will be replaced when setting this value to \"alwaysReplace\".\n *\n * Possible values\n *\n * - Constants.TRACK_SWITCH_MODE_ALWAYS_REPLACE\n * Replace existing segments in the buffer\n *\n * - Constants.TRACK_SWITCH_MODE_NEVER_REPLACE\n * Do not replace existing segments in the buffer\n *\n * @property {string} [selectionModeForInitialTrack=\"highestBitrate\"]\n * Sets the selection mode for the initial track. This mode defines how the initial track will be selected if no initial media settings are set. If initial media settings are set this parameter will be ignored. Available options are:\n *\n * Possible values\n *\n * - Constants.TRACK_SELECTION_MODE_HIGHEST_SELECTION_PRIORITY\n * This mode makes the player select the track with the highest selectionPriority as defined in the manifest. If not selectionPriority is given we fallback to TRACK_SELECTION_MODE_HIGHEST_BITRATE. This mode is a default mode.\n *\n * - Constants.TRACK_SELECTION_MODE_HIGHEST_BITRATE\n * This mode makes the player select the track with a highest bitrate.\n *\n * - Constants.TRACK_SELECTION_MODE_FIRST_TRACK\n * This mode makes the player select the first track found in the manifest.\n *\n * - Constants.TRACK_SELECTION_MODE_HIGHEST_EFFICIENCY\n * This mode makes the player select the track with the lowest bitrate per pixel average.\n *\n * - Constants.TRACK_SELECTION_MODE_WIDEST_RANGE\n * This mode makes the player select the track with a widest range of bitrates.\n *\n *\n * @property {number} [fragmentRequestTimeout=0]\n * Time in milliseconds before timing out on loading a media fragment.\n *\n * Fragments that timeout are retried as if they failed.\n * @property {module:Settings~RequestTypeSettings} [retryIntervals]\n * Time in milliseconds of which to reload a failed file load attempt.\n *\n * For low latency mode these values are divided by lowLatencyReductionFactor.\n * @property {module:Settings~RequestTypeSettings} [retryAttempts]\n * Total number of retry attempts that will occur on a file load before it fails.\n *\n * For low latency mode these values are multiplied by lowLatencyMultiplyFactor.\n * @property {module:Settings~AbrSettings} abr\n * Adaptive Bitrate algorithm related settings.\n * @property {module:Settings~CmcdSettings} cmcd\n * Settings related to Common Media Client Data reporting.\n */\n\n\n/**\n * @class\n * @ignore\n */\nfunction Settings() {\n let instance;\n\n /**\n * @const {PlayerSettings} defaultSettings\n * @ignore\n */\n const defaultSettings = {\n debug: {\n logLevel: Debug.LOG_LEVEL_WARNING,\n dispatchEvent: false\n },\n streaming: {\n abandonLoadTimeout: 10000,\n wallclockTimeUpdateInterval: 100,\n lowLatencyEnabled: false,\n lowLatencyEnabledByManifest: true,\n manifestUpdateRetryInterval: 100,\n cacheInitSegments: false,\n eventControllerRefreshDelay: 150,\n capabilities: {\n filterUnsupportedEssentialProperties: true,\n useMediaCapabilitiesApi: false\n },\n timeShiftBuffer: {\n calcFromSegmentTimeline: false,\n fallbackToSegmentTimeline: true\n },\n metrics: {\n maxListDepth: 100\n },\n delay: {\n liveDelayFragmentCount: NaN,\n liveDelay: NaN,\n useSuggestedPresentationDelay: true,\n applyServiceDescription: true\n },\n protection: {\n keepProtectionMediaKeys: false,\n ignoreEmeEncryptedEvent: false\n },\n buffer: {\n enableSeekDecorrelationFix: false,\n fastSwitchEnabled: true,\n flushBufferAtTrackSwitch: false,\n reuseExistingSourceBuffers: true,\n bufferPruningInterval: 10,\n bufferToKeep: 20,\n bufferTimeAtTopQuality: 30,\n bufferTimeAtTopQualityLongForm: 60,\n initialBufferLevel: NaN,\n stableBufferTime: 12,\n longFormContentDurationThreshold: 600,\n stallThreshold: 0.3,\n useAppendWindow: true,\n setStallState: true\n },\n gaps: {\n jumpGaps: true,\n jumpLargeGaps: true,\n smallGapLimit: 1.5,\n threshold: 0.3,\n enableSeekFix: true\n },\n utcSynchronization: {\n enabled: true,\n useManifestDateHeaderTimeSource: true,\n backgroundAttempts: 2,\n timeBetweenSyncAttempts: 30,\n maximumTimeBetweenSyncAttempts: 600,\n minimumTimeBetweenSyncAttempts: 2,\n timeBetweenSyncAttemptsAdjustmentFactor: 2,\n maximumAllowedDrift: 100,\n enableBackgroundSyncAfterSegmentDownloadError: true,\n defaultTimingSource: {\n scheme: 'urn:mpeg:dash:utc:http-xsdate:2014',\n value: 'https://time.akamai.com/?iso&ms'\n }\n },\n scheduling: {\n defaultTimeout: 500,\n lowLatencyTimeout: 0,\n scheduleWhilePaused: true\n },\n text: {\n defaultEnabled: true\n },\n liveCatchup: {\n minDrift: 0.02,\n maxDrift: 12,\n playbackRate: 0.5,\n latencyThreshold: 60,\n playbackBufferMin: 0.5,\n enabled: false,\n mode: Constants.LIVE_CATCHUP_MODE_DEFAULT\n },\n lastBitrateCachingInfo: {\n enabled: true,\n ttl: 360000\n },\n lastMediaSettingsCachingInfo: {\n enabled: true,\n ttl: 360000\n },\n cacheLoadThresholds: {\n video: 50,\n audio: 5\n },\n trackSwitchMode: {\n audio: Constants.TRACK_SWITCH_MODE_ALWAYS_REPLACE,\n video: Constants.TRACK_SWITCH_MODE_NEVER_REPLACE\n },\n selectionModeForInitialTrack: Constants.TRACK_SELECTION_MODE_HIGHEST_SELECTION_PRIORITY,\n fragmentRequestTimeout: 10000,\n retryIntervals: {\n [HTTPRequest.MPD_TYPE]: 500,\n [HTTPRequest.XLINK_EXPANSION_TYPE]: 500,\n [HTTPRequest.MEDIA_SEGMENT_TYPE]: 1000,\n [HTTPRequest.INIT_SEGMENT_TYPE]: 1000,\n [HTTPRequest.BITSTREAM_SWITCHING_SEGMENT_TYPE]: 1000,\n [HTTPRequest.INDEX_SEGMENT_TYPE]: 1000,\n [HTTPRequest.MSS_FRAGMENT_INFO_SEGMENT_TYPE]: 1000,\n [HTTPRequest.LICENSE]: 1000,\n [HTTPRequest.OTHER_TYPE]: 1000,\n lowLatencyReductionFactor: 10\n },\n retryAttempts: {\n [HTTPRequest.MPD_TYPE]: 3,\n [HTTPRequest.XLINK_EXPANSION_TYPE]: 1,\n [HTTPRequest.MEDIA_SEGMENT_TYPE]: 3,\n [HTTPRequest.INIT_SEGMENT_TYPE]: 3,\n [HTTPRequest.BITSTREAM_SWITCHING_SEGMENT_TYPE]: 3,\n [HTTPRequest.INDEX_SEGMENT_TYPE]: 3,\n [HTTPRequest.MSS_FRAGMENT_INFO_SEGMENT_TYPE]: 3,\n [HTTPRequest.LICENSE]: 3,\n [HTTPRequest.OTHER_TYPE]: 3,\n lowLatencyMultiplyFactor: 5\n },\n abr: {\n movingAverageMethod: Constants.MOVING_AVERAGE_SLIDING_WINDOW,\n ABRStrategy: Constants.ABR_STRATEGY_DYNAMIC,\n additionalAbrRules: {\n insufficientBufferRule: true,\n switchHistoryRule: true,\n droppedFramesRule: true,\n abandonRequestsRule: false\n },\n bandwidthSafetyFactor: 0.9,\n useDefaultABRRules: true,\n useDeadTimeLatency: true,\n limitBitrateByPortal: false,\n usePixelRatioInLimitBitrateByPortal: false,\n maxBitrate: {\n audio: -1,\n video: -1\n },\n minBitrate: {\n audio: -1,\n video: -1\n },\n maxRepresentationRatio: {\n audio: 1,\n video: 1\n },\n initialBitrate: {\n audio: -1,\n video: -1\n },\n initialRepresentationRatio: {\n audio: -1,\n video: -1\n },\n autoSwitchBitrate: {\n audio: true,\n video: true\n },\n fetchThroughputCalculationMode: Constants.ABR_FETCH_THROUGHPUT_CALCULATION_MOOF_PARSING\n },\n cmcd: {\n enabled: false,\n sid: null,\n cid: null,\n rtp: null,\n rtpSafetyFactor: 5,\n mode: Constants.CMCD_MODE_QUERY\n }\n },\n errors: {\n recoverAttempts: {\n mediaErrorDecode: 5\n }\n }\n };\n\n let settings = Utils.clone(defaultSettings);\n\n //Merge in the settings. If something exists in the new config that doesn't match the schema of the default config,\n //regard it as an error and log it.\n function mixinSettings(source, dest, path) {\n for (let n in source) {\n if (source.hasOwnProperty(n)) {\n if (dest.hasOwnProperty(n)) {\n if (typeof source[n] === 'object' && source[n] !== null) {\n mixinSettings(source[n], dest[n], path.slice() + n + '.');\n } else {\n dest[n] = Utils.clone(source[n]);\n }\n } else {\n throw new Error('Settings parameter ' + path + n + ' is not supported');\n }\n }\n }\n }\n\n /**\n * Return the settings object. Don't copy/store this object, you won't get updates.\n * @func\n * @instance\n */\n function get() {\n return settings;\n }\n\n /**\n * @func\n * @instance\n * @param {object} settingsObj - This should be a partial object of the Settings.Schema type. That is, fields defined should match the path (e.g.\n * settingsObj.streaming.abr.autoSwitchBitrate.audio -> defaultSettings.streaming.abr.autoSwitchBitrate.audio). Where an element's path does\n * not match it is ignored, and a warning is logged.\n *\n * Use to change the settings object. Any new values defined will overwrite the settings and anything undefined will not change.\n * Implementers of new settings should add it in an approriate namespace to the defaultSettings object and give it a default value (that is not undefined).\n *\n */\n function update(settingsObj) {\n if (typeof settingsObj === 'object') {\n mixinSettings(settingsObj, settings, '');\n }\n }\n\n /**\n * Resets the settings object. Everything is set to its default value.\n * @func\n * @instance\n *\n */\n function reset() {\n settings = Utils.clone(defaultSettings);\n }\n\n instance = {\n get: get,\n update: update,\n reset: reset\n };\n\n return instance;\n}\n\n\nSettings.__dashjs_factory_name = 'Settings';\nlet factory = FactoryMaker.getSingletonFactory(Settings);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport EventsBase from '../../core/events/EventsBase';\n\n/**\n * @class\n * @implements EventsBase\n */\nclass MetricsReportingEvents extends EventsBase {\n constructor () {\n super();\n\n this.METRICS_INITIALISATION_COMPLETE = 'internal_metricsReportingInitialized';\n this.BECAME_REPORTING_PLAYER = 'internal_becameReportingPlayer';\n\n /**\n * Triggered when CMCD data was generated for a HTTP request\n * @event MetricsReportingEvents#CMCD_DATA_GENERATED\n */\n this.CMCD_DATA_GENERATED = 'cmcdDataGenerated';\n }\n}\n\nlet metricsReportingEvents = new MetricsReportingEvents();\nexport default metricsReportingEvents;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass EventsBase {\n extend (events, config) {\n if (!events) return;\n\n let override = config ? config.override : false;\n let publicOnly = config ? config.publicOnly : false;\n\n\n for (const evt in events) {\n if (!events.hasOwnProperty(evt) || (this[evt] && !override)) continue;\n if (publicOnly && events[evt].indexOf('public_') === -1) continue;\n this[evt] = events[evt];\n\n }\n }\n}\n\nexport default EventsBase;","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport FactoryMaker from '../../core/FactoryMaker';\nimport FragmentRequest from '../vo/FragmentRequest';\n\nconst FRAGMENT_MODEL_LOADING = 'loading';\nconst FRAGMENT_MODEL_EXECUTED = 'executed';\nconst FRAGMENT_MODEL_CANCELED = 'canceled';\nconst FRAGMENT_MODEL_FAILED = 'failed';\n\nfunction FragmentModel(config) {\n\n config = config || {};\n const eventBus = config.eventBus;\n const events = config.events;\n const dashMetrics = config.dashMetrics;\n const fragmentLoader = config.fragmentLoader;\n const debug = config.debug;\n const streamInfo = config.streamInfo;\n const type = config.type;\n\n let instance,\n logger,\n executedRequests,\n loadingRequests;\n\n function setup() {\n logger = debug.getLogger(instance);\n resetInitialSettings();\n eventBus.on(events.LOADING_COMPLETED, onLoadingCompleted, instance);\n eventBus.on(events.LOADING_DATA_PROGRESS, onLoadingInProgress, instance);\n eventBus.on(events.LOADING_ABANDONED, onLoadingAborted, instance);\n }\n\n function getStreamId() {\n return streamInfo.id;\n }\n\n function getType() {\n return type;\n }\n\n function isFragmentLoaded(request) {\n const isEqualComplete = function (req1, req2) {\n return ((req1.action === FragmentRequest.ACTION_COMPLETE) && (req1.action === req2.action));\n };\n\n const isEqualMedia = function (req1, req2) {\n return !isNaN(req1.index) && (req1.startTime === req2.startTime) && (req1.adaptationIndex === req2.adaptationIndex) && (req1.type === req2.type);\n };\n\n const isEqualInit = function (req1, req2) {\n return isNaN(req1.index) && isNaN(req2.index) && (req1.quality === req2.quality);\n };\n\n const check = function (requests) {\n let isLoaded = false;\n\n requests.some(req => {\n if (isEqualMedia(request, req) || isEqualInit(request, req) || isEqualComplete(request, req)) {\n isLoaded = true;\n return isLoaded;\n }\n });\n return isLoaded;\n };\n\n if (!request) {\n return false;\n }\n\n return check(executedRequests);\n }\n\n function isFragmentLoadedOrPending(request) {\n let isLoaded = false;\n let i = 0;\n let req;\n\n // First, check if the fragment has already been loaded\n isLoaded = isFragmentLoaded(request);\n\n // Then, check if the fragment is about to be loeaded\n if (!isLoaded) {\n for (i = 0; i < loadingRequests.length; i++) {\n req = loadingRequests[i];\n if ((request.url === req.url) && (request.startTime === req.startTime)) {\n isLoaded = true;\n }\n }\n }\n\n return isLoaded;\n }\n\n /**\n *\n * Gets an array of {@link FragmentRequest} objects\n *\n * @param {Object} filter The object with properties by which the method filters the requests to be returned.\n * the only mandatory property is state, which must be a value from\n * other properties should match the properties of {@link FragmentRequest}. E.g.:\n * getRequests({state: FragmentModel.FRAGMENT_MODEL_EXECUTED, quality: 0}) - returns\n * all the requests from executedRequests array where requests.quality = filter.quality\n *\n * @returns {Array}\n * @memberof FragmentModel#\n */\n function getRequests(filter) {\n const states = filter ? filter.state instanceof Array ? filter.state : [filter.state] : [];\n\n let filteredRequests = [];\n states.forEach(state => {\n const requests = getRequestsForState(state);\n filteredRequests = filteredRequests.concat(filterRequests(requests, filter));\n });\n\n return filteredRequests;\n }\n\n function getRequestThreshold(req) {\n return isNaN(req.duration) ? 0.25 : Math.min(req.duration / 8, 0.5);\n }\n\n function removeExecutedRequestsBeforeTime(time) {\n executedRequests = executedRequests.filter(req => {\n const threshold = getRequestThreshold(req);\n return isNaN(req.startTime) || (time !== undefined ? req.startTime >= time - threshold : false);\n });\n }\n\n function removeExecutedRequestsAfterTime(time) {\n executedRequests = executedRequests.filter(req => {\n return isNaN(req.startTime) || (time !== undefined ? req.startTime < time : false);\n });\n }\n\n function removeExecutedRequestsInTimeRange(start, end) {\n if (end <= start + 0.5) {\n return;\n }\n\n executedRequests = executedRequests.filter(req => {\n const threshold = getRequestThreshold(req);\n return (isNaN(req.startTime) || req.startTime >= (end - threshold)) ||\n (isNaN(req.duration) || (req.startTime + req.duration) <= (start + threshold));\n });\n }\n\n // Remove requests that are not \"represented\" by any of buffered ranges\n function syncExecutedRequestsWithBufferedRange(bufferedRanges, streamDuration) {\n if (!bufferedRanges || bufferedRanges.length === 0) {\n removeExecutedRequestsBeforeTime();\n return;\n }\n\n let start = 0;\n for (let i = 0, ln = bufferedRanges.length; i < ln; i++) {\n removeExecutedRequestsInTimeRange(start, bufferedRanges.start(i));\n start = bufferedRanges.end(i);\n }\n if (streamDuration > 0) {\n removeExecutedRequestsInTimeRange(start, streamDuration);\n }\n }\n\n function abortRequests() {\n logger.debug('abort requests');\n fragmentLoader.abort();\n loadingRequests = [];\n }\n\n function executeRequest(request) {\n switch (request.action) {\n case FragmentRequest.ACTION_DOWNLOAD:\n addSchedulingInfoMetrics(request, FRAGMENT_MODEL_LOADING);\n loadingRequests.push(request);\n loadCurrentFragment(request);\n break;\n default:\n logger.warn('Unknown request action.');\n }\n }\n\n function loadCurrentFragment(request) {\n eventBus.trigger(events.FRAGMENT_LOADING_STARTED,\n { request: request },\n { streamId: streamInfo.id, mediaType: type }\n );\n fragmentLoader.load(request);\n }\n\n function getRequestForTime(arr, time, threshold) {\n // loop through the executed requests and pick the one for which the playback interval matches the given time\n const lastIdx = arr.length - 1;\n for (let i = lastIdx; i >= 0; i--) {\n const req = arr[i];\n const start = req.startTime;\n const end = start + req.duration;\n threshold = !isNaN(threshold) ? threshold : getRequestThreshold(req);\n if ((!isNaN(start) && !isNaN(end) && ((time + threshold) >= start) && ((time - threshold) < end)) || (isNaN(start) && isNaN(time))) {\n return req;\n }\n }\n return null;\n }\n\n function filterRequests(arr, filter) {\n // for time use a specific filtration function\n if (filter.hasOwnProperty('time')) {\n return [getRequestForTime(arr, filter.time, filter.threshold)];\n }\n\n return arr.filter(request => {\n for (const prop in filter) {\n if (prop === 'state') continue;\n if (filter.hasOwnProperty(prop) && request[prop] != filter[prop]) return false;\n }\n\n return true;\n });\n }\n\n function getRequestsForState(state) {\n let requests;\n switch (state) {\n case FRAGMENT_MODEL_LOADING:\n requests = loadingRequests;\n break;\n case FRAGMENT_MODEL_EXECUTED:\n requests = executedRequests;\n break;\n default:\n requests = [];\n }\n return requests;\n }\n\n function addSchedulingInfoMetrics(request, state) {\n dashMetrics.addSchedulingInfo(request, state);\n dashMetrics.addRequestsQueue(request.mediaType, loadingRequests, executedRequests);\n }\n\n function onLoadingCompleted(e) {\n if (e.sender !== fragmentLoader) return;\n\n loadingRequests.splice(loadingRequests.indexOf(e.request), 1);\n\n if (e.response && !e.error) {\n executedRequests.push(e.request);\n }\n\n addSchedulingInfoMetrics(e.request, e.error ? FRAGMENT_MODEL_FAILED : FRAGMENT_MODEL_EXECUTED);\n\n eventBus.trigger(events.FRAGMENT_LOADING_COMPLETED,\n {\n request: e.request,\n response: e.response,\n error: e.error,\n sender: this\n },\n { streamId: streamInfo.id, mediaType: type }\n );\n }\n\n function onLoadingInProgress(e) {\n if (e.sender !== fragmentLoader) return;\n\n eventBus.trigger(events.FRAGMENT_LOADING_PROGRESS,\n {\n request: e.request,\n response: e.response,\n error: e.error,\n sender: this\n },\n { streamId: streamInfo.id, mediaType: type }\n );\n }\n\n function onLoadingAborted(e) {\n if (e.sender !== fragmentLoader) return;\n\n eventBus.trigger(events.FRAGMENT_LOADING_ABANDONED,\n { request: e.request },\n { streamId: streamInfo.id, mediaType: type }\n );\n }\n\n function resetInitialSettings() {\n executedRequests = [];\n loadingRequests = [];\n }\n\n function reset() {\n eventBus.off(events.LOADING_COMPLETED, onLoadingCompleted, this);\n eventBus.off(events.LOADING_DATA_PROGRESS, onLoadingInProgress, this);\n eventBus.off(events.LOADING_ABANDONED, onLoadingAborted, this);\n\n if (fragmentLoader) {\n fragmentLoader.reset();\n }\n resetInitialSettings();\n }\n\n function addExecutedRequest(request) {\n executedRequests.push(request);\n }\n\n instance = {\n getStreamId,\n getType,\n getRequests,\n isFragmentLoaded,\n isFragmentLoadedOrPending,\n removeExecutedRequestsBeforeTime,\n removeExecutedRequestsAfterTime,\n syncExecutedRequestsWithBufferedRange,\n abortRequests,\n executeRequest,\n reset,\n resetInitialSettings,\n addExecutedRequest\n };\n\n setup();\n return instance;\n}\n\nFragmentModel.__dashjs_factory_name = 'FragmentModel';\nconst factory = FactoryMaker.getClassFactory(FragmentModel);\nfactory.FRAGMENT_MODEL_LOADING = FRAGMENT_MODEL_LOADING;\nfactory.FRAGMENT_MODEL_EXECUTED = FRAGMENT_MODEL_EXECUTED;\nfactory.FRAGMENT_MODEL_CANCELED = FRAGMENT_MODEL_CANCELED;\nfactory.FRAGMENT_MODEL_FAILED = FRAGMENT_MODEL_FAILED;\nFactoryMaker.updateClassFactory(FragmentModel.__dashjs_factory_name, factory);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport FactoryMaker from '../../core/FactoryMaker';\nimport SchemeLoaderFactory from '../../streaming/net/SchemeLoaderFactory';\n\n/**\n * @class URLLoader\n * @description Call Offline Loader or Online Loader dependaing on URL\n * @param {Object} cfg - dependances\n * @ignore\n*/\nfunction URLLoader(cfg) {\n\n cfg = cfg || {};\n const context = this.context;\n\n let instance,\n schemeLoaderFactory,\n loader;\n\n schemeLoaderFactory = SchemeLoaderFactory(context).getInstance();\n\n function load(config) {\n if (!loader) {\n let loaderFactory = schemeLoaderFactory.getLoader(config && config.request ? config.request.url : null);\n loader = loaderFactory(context).create({\n errHandler: cfg.errHandler,\n mediaPlayerModel: cfg.mediaPlayerModel,\n requestModifier: cfg.requestModifier,\n dashMetrics: cfg.dashMetrics,\n boxParser: cfg.boxParser ? cfg.boxParser : null,\n constants: cfg.constants ? cfg.constants : null,\n dashConstants: cfg.dashConstants ? cfg.dashConstants : null,\n urlUtils: cfg.urlUtils ? cfg.urlUtils : null,\n requestTimeout: !isNaN(cfg.requestTimeout) ? cfg.requestTimeout : 0,\n errors: cfg.errors\n });\n }\n loader.load(config);\n }\n\n function abort() {\n if (loader) {\n loader.abort();\n }\n }\n instance = {\n load: load,\n abort: abort\n };\n\n return instance;\n\n}\nURLLoader.__dashjs_factory_name = 'URLLoader';\n\nconst factory = FactoryMaker.getClassFactory(URLLoader);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass IsoBox {\n constructor(boxData) {\n this.offset = boxData._offset;\n this.type = boxData.type;\n this.size = boxData.size;\n this.boxes = [];\n if (boxData.boxes) {\n for (let i = 0; i < boxData.boxes.length; i++) {\n this.boxes.push(new IsoBox(boxData.boxes[i]));\n }\n }\n this.isComplete = true;\n\n switch (boxData.type) {\n case 'sidx':\n this.timescale = boxData.timescale;\n this.earliest_presentation_time = boxData.earliest_presentation_time;\n this.first_offset = boxData.first_offset;\n this.references = boxData.references;\n if (boxData.references) {\n this.references = [];\n for (let i = 0; i < boxData.references.length; i++) {\n let reference = {\n reference_type: boxData.references[i].reference_type,\n referenced_size: boxData.references[i].referenced_size,\n subsegment_duration: boxData.references[i].subsegment_duration\n };\n this.references.push(reference);\n }\n }\n break;\n case 'emsg':\n this.id = boxData.id;\n this.version = boxData.version === 1 ? 1 : 0;\n this.value = boxData.value;\n this.timescale = boxData.timescale;\n this.scheme_id_uri = boxData.scheme_id_uri;\n this.presentation_time_delta = boxData.version === 1 ? boxData.presentation_time : boxData.presentation_time_delta;\n this.event_duration = boxData.event_duration;\n this.message_data = boxData.message_data;\n break;\n case 'mdhd':\n this.timescale = boxData.timescale;\n break;\n case 'mfhd':\n this.sequence_number = boxData.sequence_number;\n break;\n case 'subs':\n this.entry_count = boxData.entry_count;\n this.entries = boxData.entries;\n break;\n case 'tfhd':\n this.base_data_offset = boxData.base_data_offset;\n this.sample_description_index = boxData.sample_description_index;\n this.default_sample_duration = boxData.default_sample_duration;\n this.default_sample_size = boxData.default_sample_size;\n this.default_sample_flags = boxData.default_sample_flags;\n this.flags = boxData.flags;\n break;\n case 'tfdt':\n this.version = boxData.version;\n this.baseMediaDecodeTime = boxData.baseMediaDecodeTime;\n this.flags = boxData.flags;\n break;\n case 'trun':\n this.sample_count = boxData.sample_count;\n this.first_sample_flags = boxData.first_sample_flags;\n this.data_offset = boxData.data_offset;\n this.flags = boxData.flags;\n this.samples = boxData.samples;\n if (boxData.samples) {\n this.samples = [];\n for (let i = 0, ln = boxData.samples.length; i < ln; i++) {\n let sample = {\n sample_size: boxData.samples[i].sample_size,\n sample_duration: boxData.samples[i].sample_duration,\n sample_composition_time_offset: boxData.samples[i].sample_composition_time_offset\n };\n this.samples.push(sample);\n }\n }\n break;\n }\n\n }\n\n getChildBox(type) {\n for (let i = 0; i < this.boxes.length; i++) {\n if (this.boxes[i].type === type) {\n return this.boxes[i];\n }\n }\n }\n\n getChildBoxes(type) {\n let boxes = [];\n for (let i = 0; i < this.boxes.length; i++) {\n if (this.boxes[i].type === type) {\n boxes.push(this.boxes[i]);\n }\n }\n return boxes;\n }\n\n}\n\nexport default IsoBox;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport IsoBox from '../vo/IsoBox';\nimport FactoryMaker from '../../core/FactoryMaker';\n\nfunction IsoFile() {\n\n let instance,\n parsedIsoFile;\n\n /**\n * @param {string} type\n * @returns {IsoBox|null}\n * @memberof IsoFile#\n */\n function getBox(type) {\n if (!type || !parsedIsoFile || !parsedIsoFile.boxes || (parsedIsoFile.boxes.length === 0) || typeof parsedIsoFile.fetch !== 'function') return null;\n\n return convertToDashIsoBox(parsedIsoFile.fetch(type));\n }\n\n /**\n * @param {string} type\n * @returns {Array|null} array of {@link IsoBox}\n * @memberof IsoFile#\n */\n function getBoxes(type) {\n let boxes = [];\n\n if (!type || !parsedIsoFile || typeof parsedIsoFile.fetchAll !== 'function') {\n return boxes;\n }\n\n let boxData = parsedIsoFile.fetchAll(type);\n let box;\n\n for (let i = 0, ln = boxData.length; i < ln; i++) {\n box = convertToDashIsoBox(boxData[i]);\n\n if (box) {\n boxes.push(box);\n }\n }\n\n return boxes;\n }\n\n /**\n * @param {string} value\n * @memberof IsoFile#\n */\n function setData(value) {\n parsedIsoFile = value;\n }\n\n /**\n * @returns {IsoBox|null}\n * @memberof IsoFile#\n */\n function getLastBox() {\n if (!parsedIsoFile || !parsedIsoFile.boxes || !parsedIsoFile.boxes.length) return null;\n\n let type = parsedIsoFile.boxes[parsedIsoFile.boxes.length - 1].type;\n let boxes = getBoxes(type);\n\n return boxes.length > 0 ? boxes[boxes.length - 1] : null;\n }\n\n function convertToDashIsoBox(boxData) {\n if (!boxData) return null;\n\n let box = new IsoBox(boxData);\n\n if (boxData.hasOwnProperty('_incomplete')) {\n box.isComplete = !boxData._incomplete;\n }\n\n return box;\n }\n\n instance = {\n getBox: getBox,\n getBoxes: getBoxes,\n setData: setData,\n getLastBox: getLastBox\n };\n\n return instance;\n}\nIsoFile.__dashjs_factory_name = 'IsoFile';\nexport default FactoryMaker.getClassFactory(IsoFile);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass IsoBoxSearchInfo {\n constructor(lastCompletedOffset, found, size) {\n this.lastCompletedOffset = lastCompletedOffset;\n this.found = found;\n this.size = size;\n }\n}\n\nexport default IsoBoxSearchInfo;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport Debug from '../../core/Debug';\nimport IsoFile from './IsoFile';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport ISOBoxer from 'codem-isoboxer';\n\nimport IsoBoxSearchInfo from '../vo/IsoBoxSearchInfo';\n\nfunction BoxParser(/*config*/) {\n\n let logger,\n instance;\n let context = this.context;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n }\n\n /**\n * @param {ArrayBuffer} data\n * @returns {IsoFile|null}\n * @memberof BoxParser#\n */\n function parse(data) {\n if (!data) return null;\n\n if (data.fileStart === undefined) {\n data.fileStart = 0;\n }\n\n let parsedFile = ISOBoxer.parseBuffer(data);\n let dashIsoFile = IsoFile(context).create();\n\n dashIsoFile.setData(parsedFile);\n\n return dashIsoFile;\n }\n\n /**\n * From the list of type boxes to look for, returns the latest one that is fully completed (header + payload). This\n * method only looks into the list of top boxes and doesn't analyze nested boxes.\n * @param {string[]} types\n * @param {ArrayBuffer|uint8Array} buffer\n * @param {number} offset\n * @returns {IsoBoxSearchInfo}\n * @memberof BoxParser#\n */\n function findLastTopIsoBoxCompleted(types, buffer, offset) {\n if (offset === undefined) {\n offset = 0;\n }\n\n // 8 = size (uint32) + type (4 characters)\n if (!buffer || offset + 8 >= buffer.byteLength) {\n return new IsoBoxSearchInfo(0, false);\n }\n\n const data = (buffer instanceof ArrayBuffer) ? new Uint8Array(buffer) : buffer;\n let boxInfo;\n let lastCompletedOffset = 0;\n while (offset < data.byteLength) {\n const boxSize = parseUint32(data, offset);\n const boxType = parseIsoBoxType(data, offset + 4);\n\n if (boxSize === 0) {\n break;\n }\n\n if (offset + boxSize <= data.byteLength) {\n if (types.indexOf(boxType) >= 0) {\n boxInfo = new IsoBoxSearchInfo(offset, true, boxSize);\n } else {\n lastCompletedOffset = offset + boxSize;\n }\n }\n\n offset += boxSize;\n }\n\n if (!boxInfo) {\n return new IsoBoxSearchInfo(lastCompletedOffset, false);\n }\n\n return boxInfo;\n }\n\n function getSamplesInfo(ab) {\n if (!ab || ab.byteLength === 0) {\n return {sampleList: [], lastSequenceNumber: NaN, totalDuration: NaN, numSequences: NaN};\n }\n let isoFile = parse(ab);\n // zero or more moofs\n let moofBoxes = isoFile.getBoxes('moof');\n // exactly one mfhd per moof\n let mfhdBoxes = isoFile.getBoxes('mfhd');\n\n let sampleDuration,\n sampleCompositionTimeOffset,\n sampleCount,\n sampleSize,\n sampleDts,\n sampleList,\n sample,\n i, j, k, l, m, n,\n dataOffset,\n lastSequenceNumber,\n numSequences,\n totalDuration;\n\n numSequences = isoFile.getBoxes('moof').length;\n lastSequenceNumber = mfhdBoxes[mfhdBoxes.length - 1].sequence_number;\n sampleCount = 0;\n\n sampleList = [];\n let subsIndex = -1;\n let nextSubsSample = -1;\n for (l = 0; l < moofBoxes.length; l++) {\n let moofBox = moofBoxes[l];\n // zero or more trafs per moof\n let trafBoxes = moofBox.getChildBoxes('traf');\n for (j = 0; j < trafBoxes.length; j++) {\n let trafBox = trafBoxes[j];\n // exactly one tfhd per traf\n let tfhdBox = trafBox.getChildBox('tfhd');\n // zero or one tfdt per traf\n let tfdtBox = trafBox.getChildBox('tfdt');\n sampleDts = tfdtBox.baseMediaDecodeTime;\n // zero or more truns per traf\n let trunBoxes = trafBox.getChildBoxes('trun');\n // zero or more subs per traf\n let subsBoxes = trafBox.getChildBoxes('subs');\n for (k = 0; k < trunBoxes.length; k++) {\n let trunBox = trunBoxes[k];\n sampleCount = trunBox.sample_count;\n dataOffset = (tfhdBox.base_data_offset || 0) + (trunBox.data_offset || 0);\n\n for (i = 0; i < sampleCount; i++) {\n sample = trunBox.samples[i];\n sampleDuration = (sample.sample_duration !== undefined) ? sample.sample_duration : tfhdBox.default_sample_duration;\n sampleSize = (sample.sample_size !== undefined) ? sample.sample_size : tfhdBox.default_sample_size;\n sampleCompositionTimeOffset = (sample.sample_composition_time_offset !== undefined) ? sample.sample_composition_time_offset : 0;\n let sampleData = {\n 'dts': sampleDts,\n 'cts': (sampleDts + sampleCompositionTimeOffset),\n 'duration': sampleDuration,\n 'offset': moofBox.offset + dataOffset,\n 'size': sampleSize,\n 'subSizes': [sampleSize]\n };\n if (subsBoxes) {\n for (m = 0; m < subsBoxes.length; m++) {\n let subsBox = subsBoxes[m];\n if (subsIndex < (subsBox.entry_count - 1) && i > nextSubsSample) {\n subsIndex++;\n nextSubsSample += subsBox.entries[subsIndex].sample_delta;\n }\n if (i == nextSubsSample) {\n sampleData.subSizes = [];\n let entry = subsBox.entries[subsIndex];\n for (n = 0; n < entry.subsample_count; n++) {\n sampleData.subSizes.push(entry.subsamples[n].subsample_size);\n }\n }\n }\n }\n sampleList.push(sampleData);\n dataOffset += sampleSize;\n sampleDts += sampleDuration;\n }\n }\n totalDuration = sampleDts - tfdtBox.baseMediaDecodeTime;\n }\n }\n return {sampleList: sampleList, lastSequenceNumber: lastSequenceNumber, totalDuration: totalDuration, numSequences: numSequences};\n }\n\n function getMediaTimescaleFromMoov(ab) {\n let isoFile = parse(ab);\n let mdhdBox = isoFile ? isoFile.getBox('mdhd') : undefined;\n\n return mdhdBox ? mdhdBox.timescale : NaN;\n }\n\n function parseUint32(data, offset) {\n return data[offset + 3] >>> 0 |\n (data[offset + 2] << 8) >>> 0 |\n (data[offset + 1] << 16) >>> 0 |\n (data[offset] << 24) >>> 0;\n }\n\n function parseIsoBoxType(data, offset) {\n return String.fromCharCode(data[offset++]) +\n String.fromCharCode(data[offset++]) +\n String.fromCharCode(data[offset++]) +\n String.fromCharCode(data[offset]);\n }\n\n function findInitRange(data) {\n let initRange = null;\n let start,\n end;\n\n const isoFile = parse(data);\n\n if (!isoFile) {\n return initRange;\n }\n\n const ftyp = isoFile.getBox('ftyp');\n const moov = isoFile.getBox('moov');\n\n logger.debug('Searching for initialization.');\n\n if (moov && moov.isComplete) {\n start = ftyp ? ftyp.offset : moov.offset;\n end = moov.offset + moov.size - 1;\n initRange = start + '-' + end;\n\n logger.debug('Found the initialization. Range: ' + initRange);\n }\n\n return initRange;\n }\n\n /**\n * Real-time parsing (whenever data is loaded in the buffer payload) of the payload to capture the moof of a chunk\n * @param {array} types\n * @param {ArrayBuffer} buffer\n * @param {number} offset\n * @return {IsoBoxSearchInfo}\n */\n function parsePayload(types, buffer, offset) {\n if (offset === undefined) {\n offset = 0;\n }\n\n if (!buffer || offset + 8 >= buffer.byteLength) {\n return new IsoBoxSearchInfo(0, false);\n }\n\n const data = (buffer instanceof ArrayBuffer) ? new Uint8Array(buffer) : buffer;\n let boxInfo;\n let lastCompletedOffset = 0;\n while (offset < data.byteLength) {\n const boxSize = parseUint32(data, offset);\n const boxType = parseIsoBoxType(data, offset + 4);\n\n if (boxSize === 0) {\n break;\n }\n\n if (offset + boxSize <= data.byteLength) {\n if (types.indexOf(boxType) >= 0) {\n boxInfo = new IsoBoxSearchInfo(offset, true, boxSize, boxType);\n } else {\n lastCompletedOffset = offset + boxSize;\n }\n }\n\n offset += boxSize;\n }\n\n if (!boxInfo) {\n return new IsoBoxSearchInfo(lastCompletedOffset, false);\n }\n\n return boxInfo;\n }\n\n instance = {\n parse,\n findLastTopIsoBoxCompleted,\n getMediaTimescaleFromMoov,\n getSamplesInfo,\n findInitRange,\n parsePayload\n };\n\n setup();\n\n return instance;\n}\nBoxParser.__dashjs_factory_name = 'BoxParser';\nexport default FactoryMaker.getSingletonFactory(BoxParser);\n","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n","/*! codem-isoboxer v0.3.6 https://github.com/madebyhiro/codem-isoboxer/blob/master/LICENSE.txt */\nvar ISOBoxer = {};\n\nISOBoxer.parseBuffer = function(arrayBuffer) {\n return new ISOFile(arrayBuffer).parse();\n};\n\nISOBoxer.addBoxProcessor = function(type, parser) {\n if (typeof type !== 'string' || typeof parser !== 'function') {\n return;\n }\n ISOBox.prototype._boxProcessors[type] = parser;\n};\n\nISOBoxer.createFile = function() {\n return new ISOFile();\n};\n\n// See ISOBoxer.append() for 'pos' parameter syntax\nISOBoxer.createBox = function(type, parent, pos) {\n var newBox = ISOBox.create(type);\n if (parent) {\n parent.append(newBox, pos);\n }\n return newBox;\n};\n\n// See ISOBoxer.append() for 'pos' parameter syntax\nISOBoxer.createFullBox = function(type, parent, pos) {\n var newBox = ISOBoxer.createBox(type, parent, pos);\n newBox.version = 0;\n newBox.flags = 0;\n return newBox;\n};\n\nISOBoxer.Utils = {};\nISOBoxer.Utils.dataViewToString = function(dataView, encoding) {\n var impliedEncoding = encoding || 'utf-8';\n if (typeof TextDecoder !== 'undefined') {\n return new TextDecoder(impliedEncoding).decode(dataView);\n }\n var a = [];\n var i = 0;\n\n if (impliedEncoding === 'utf-8') {\n /* The following algorithm is essentially a rewrite of the UTF8.decode at\n http://bannister.us/weblog/2007/simple-base64-encodedecode-javascript/\n */\n\n while (i < dataView.byteLength) {\n var c = dataView.getUint8(i++);\n if (c < 0x80) {\n // 1-byte character (7 bits)\n } else if (c < 0xe0) {\n // 2-byte character (11 bits)\n c = (c & 0x1f) << 6;\n c |= (dataView.getUint8(i++) & 0x3f);\n } else if (c < 0xf0) {\n // 3-byte character (16 bits)\n c = (c & 0xf) << 12;\n c |= (dataView.getUint8(i++) & 0x3f) << 6;\n c |= (dataView.getUint8(i++) & 0x3f);\n } else {\n // 4-byte character (21 bits)\n c = (c & 0x7) << 18;\n c |= (dataView.getUint8(i++) & 0x3f) << 12;\n c |= (dataView.getUint8(i++) & 0x3f) << 6;\n c |= (dataView.getUint8(i++) & 0x3f);\n }\n a.push(String.fromCharCode(c));\n }\n } else { // Just map byte-by-byte (probably wrong)\n while (i < dataView.byteLength) {\n a.push(String.fromCharCode(dataView.getUint8(i++)));\n }\n }\n return a.join('');\n};\n\nISOBoxer.Utils.utf8ToByteArray = function(string) {\n // Only UTF-8 encoding is supported by TextEncoder\n var u, i;\n if (typeof TextEncoder !== 'undefined') {\n u = new TextEncoder().encode(string);\n } else {\n u = [];\n for (i = 0; i < string.length; ++i) {\n var c = string.charCodeAt(i);\n if (c < 0x80) {\n u.push(c);\n } else if (c < 0x800) {\n u.push(0xC0 | (c >> 6));\n u.push(0x80 | (63 & c));\n } else if (c < 0x10000) {\n u.push(0xE0 | (c >> 12));\n u.push(0x80 | (63 & (c >> 6)));\n u.push(0x80 | (63 & c));\n } else {\n u.push(0xF0 | (c >> 18));\n u.push(0x80 | (63 & (c >> 12)));\n u.push(0x80 | (63 & (c >> 6)));\n u.push(0x80 | (63 & c));\n }\n }\n }\n return u;\n};\n\n// Method to append a box in the list of child boxes\n// The 'pos' parameter can be either:\n// - (number) a position index at which to insert the new box\n// - (string) the type of the box after which to insert the new box\n// - (object) the box after which to insert the new box\nISOBoxer.Utils.appendBox = function(parent, box, pos) {\n box._offset = parent._cursor.offset;\n box._root = (parent._root ? parent._root : parent);\n box._raw = parent._raw;\n box._parent = parent;\n\n if (pos === -1) {\n // The new box is a sub-box of the parent but not added in boxes array,\n // for example when the new box is set as an entry (see dref and stsd for example)\n return;\n }\n\n if (pos === undefined || pos === null) {\n parent.boxes.push(box);\n return;\n }\n\n var index = -1,\n type;\n\n if (typeof pos === \"number\") {\n index = pos;\n } else {\n if (typeof pos === \"string\") {\n type = pos;\n } else if (typeof pos === \"object\" && pos.type) {\n type = pos.type;\n } else {\n parent.boxes.push(box);\n return;\n }\n\n for (var i = 0; i < parent.boxes.length; i++) {\n if (type === parent.boxes[i].type) {\n index = i + 1;\n break;\n }\n }\n }\n parent.boxes.splice(index, 0, box);\n};\n\nif (typeof exports !== 'undefined') {\n exports.parseBuffer = ISOBoxer.parseBuffer;\n exports.addBoxProcessor = ISOBoxer.addBoxProcessor;\n exports.createFile = ISOBoxer.createFile;\n exports.createBox = ISOBoxer.createBox;\n exports.createFullBox = ISOBoxer.createFullBox;\n exports.Utils = ISOBoxer.Utils;\n}\n\nISOBoxer.Cursor = function(initialOffset) {\n this.offset = (typeof initialOffset == 'undefined' ? 0 : initialOffset);\n};\n\nvar ISOFile = function(arrayBuffer) {\n this._cursor = new ISOBoxer.Cursor();\n this.boxes = [];\n if (arrayBuffer) {\n this._raw = new DataView(arrayBuffer);\n }\n};\n\nISOFile.prototype.fetch = function(type) {\n var result = this.fetchAll(type, true);\n return (result.length ? result[0] : null);\n};\n\nISOFile.prototype.fetchAll = function(type, returnEarly) {\n var result = [];\n ISOFile._sweep.call(this, type, result, returnEarly);\n return result;\n};\n\nISOFile.prototype.parse = function() {\n this._cursor.offset = 0;\n this.boxes = [];\n while (this._cursor.offset < this._raw.byteLength) {\n var box = ISOBox.parse(this);\n\n // Box could not be parsed\n if (typeof box.type === 'undefined') break;\n\n this.boxes.push(box);\n }\n return this;\n};\n\nISOFile._sweep = function(type, result, returnEarly) {\n if (this.type && this.type == type) result.push(this);\n for (var box in this.boxes) {\n if (result.length && returnEarly) return;\n ISOFile._sweep.call(this.boxes[box], type, result, returnEarly);\n }\n};\n\nISOFile.prototype.write = function() {\n\n var length = 0,\n i;\n\n for (i = 0; i < this.boxes.length; i++) {\n length += this.boxes[i].getLength(false);\n }\n\n var bytes = new Uint8Array(length);\n this._rawo = new DataView(bytes.buffer);\n this.bytes = bytes;\n this._cursor.offset = 0;\n\n for (i = 0; i < this.boxes.length; i++) {\n this.boxes[i].write();\n }\n\n return bytes.buffer;\n};\n\nISOFile.prototype.append = function(box, pos) {\n ISOBoxer.Utils.appendBox(this, box, pos);\n};\nvar ISOBox = function() {\n this._cursor = new ISOBoxer.Cursor();\n};\n\nISOBox.parse = function(parent) {\n var newBox = new ISOBox();\n newBox._offset = parent._cursor.offset;\n newBox._root = (parent._root ? parent._root : parent);\n newBox._raw = parent._raw;\n newBox._parent = parent;\n newBox._parseBox();\n parent._cursor.offset = newBox._raw.byteOffset + newBox._raw.byteLength;\n return newBox;\n};\n\nISOBox.create = function(type) {\n var newBox = new ISOBox();\n newBox.type = type;\n newBox.boxes = [];\n return newBox;\n};\n\nISOBox.prototype._boxContainers = ['dinf', 'edts', 'mdia', 'meco', 'mfra', 'minf', 'moof', 'moov', 'mvex', 'stbl', 'strk', 'traf', 'trak', 'tref', 'udta', 'vttc', 'sinf', 'schi', 'encv', 'enca'];\n\nISOBox.prototype._boxProcessors = {};\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n// Generic read/write functions\n\nISOBox.prototype._procField = function (name, type, size) {\n if (this._parsing) {\n this[name] = this._readField(type, size);\n }\n else {\n this._writeField(type, size, this[name]);\n }\n};\n\nISOBox.prototype._procFieldArray = function (name, length, type, size) {\n var i;\n if (this._parsing) {\n this[name] = [];\n for (i = 0; i < length; i++) {\n this[name][i] = this._readField(type, size);\n }\n }\n else {\n for (i = 0; i < this[name].length; i++) {\n this._writeField(type, size, this[name][i]);\n }\n }\n};\n\nISOBox.prototype._procFullBox = function() {\n this._procField('version', 'uint', 8);\n this._procField('flags', 'uint', 24);\n};\n\nISOBox.prototype._procEntries = function(name, length, fn) {\n var i;\n if (this._parsing) {\n this[name] = [];\n for (i = 0; i < length; i++) {\n this[name].push({});\n fn.call(this, this[name][i]);\n }\n }\n else {\n for (i = 0; i < length; i++) {\n fn.call(this, this[name][i]);\n }\n }\n};\n\nISOBox.prototype._procSubEntries = function(entry, name, length, fn) {\n var i;\n if (this._parsing) {\n entry[name] = [];\n for (i = 0; i < length; i++) {\n entry[name].push({});\n fn.call(this, entry[name][i]);\n }\n }\n else {\n for (i = 0; i < length; i++) {\n fn.call(this, entry[name][i]);\n }\n }\n};\n\nISOBox.prototype._procEntryField = function (entry, name, type, size) {\n if (this._parsing) {\n entry[name] = this._readField(type, size);\n }\n else {\n this._writeField(type, size, entry[name]);\n }\n};\n\nISOBox.prototype._procSubBoxes = function(name, length) {\n var i;\n if (this._parsing) {\n this[name] = [];\n for (i = 0; i < length; i++) {\n this[name].push(ISOBox.parse(this));\n }\n }\n else {\n for (i = 0; i < length; i++) {\n if (this._rawo) {\n this[name][i].write();\n } else {\n this.size += this[name][i].getLength();\n }\n }\n }\n};\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n// Read/parse functions\n\nISOBox.prototype._readField = function(type, size) {\n switch (type) {\n case 'uint':\n return this._readUint(size);\n case 'int':\n return this._readInt(size);\n case 'template':\n return this._readTemplate(size);\n case 'string':\n return (size === -1) ? this._readTerminatedString() : this._readString(size);\n case 'data':\n return this._readData(size);\n case 'utf8':\n return this._readUTF8String();\n default:\n return -1;\n }\n};\n\nISOBox.prototype._readInt = function(size) {\n var result = null,\n offset = this._cursor.offset - this._raw.byteOffset;\n switch(size) {\n case 8:\n result = this._raw.getInt8(offset);\n break;\n case 16:\n result = this._raw.getInt16(offset);\n break;\n case 32:\n result = this._raw.getInt32(offset);\n break;\n case 64:\n // Warning: JavaScript cannot handle 64-bit integers natively.\n // This will give unexpected results for integers >= 2^53\n var s1 = this._raw.getInt32(offset);\n var s2 = this._raw.getInt32(offset + 4);\n result = (s1 * Math.pow(2,32)) + s2;\n break;\n }\n this._cursor.offset += (size >> 3);\n return result;\n};\n\nISOBox.prototype._readUint = function(size) {\n var result = null,\n offset = this._cursor.offset - this._raw.byteOffset,\n s1, s2;\n switch(size) {\n case 8:\n result = this._raw.getUint8(offset);\n break;\n case 16:\n result = this._raw.getUint16(offset);\n break;\n case 24:\n s1 = this._raw.getUint16(offset);\n s2 = this._raw.getUint8(offset + 2);\n result = (s1 << 8) + s2;\n break;\n case 32:\n result = this._raw.getUint32(offset);\n break;\n case 64:\n // Warning: JavaScript cannot handle 64-bit integers natively.\n // This will give unexpected results for integers >= 2^53\n s1 = this._raw.getUint32(offset);\n s2 = this._raw.getUint32(offset + 4);\n result = (s1 * Math.pow(2,32)) + s2;\n break;\n }\n this._cursor.offset += (size >> 3);\n return result;\n};\n\nISOBox.prototype._readString = function(length) {\n var str = '';\n for (var c = 0; c < length; c++) {\n var char = this._readUint(8);\n str += String.fromCharCode(char);\n }\n return str;\n};\n\nISOBox.prototype._readTemplate = function(size) {\n var pre = this._readUint(size / 2);\n var post = this._readUint(size / 2);\n return pre + (post / Math.pow(2, size / 2));\n};\n\nISOBox.prototype._readTerminatedString = function() {\n var str = '';\n while (this._cursor.offset - this._offset < this._raw.byteLength) {\n var char = this._readUint(8);\n if (char === 0) break;\n str += String.fromCharCode(char);\n }\n return str;\n};\n\nISOBox.prototype._readData = function(size) {\n var length = (size > 0) ? size : (this._raw.byteLength - (this._cursor.offset - this._offset));\n if (length > 0) {\n var data = new Uint8Array(this._raw.buffer, this._cursor.offset, length);\n\n this._cursor.offset += length;\n return data;\n }\n else {\n return null;\n }\n};\n\nISOBox.prototype._readUTF8String = function() {\n var length = this._raw.byteLength - (this._cursor.offset - this._offset);\n var data = null;\n if (length > 0) {\n data = new DataView(this._raw.buffer, this._cursor.offset, length);\n this._cursor.offset += length;\n }\n \n return data ? ISOBoxer.Utils.dataViewToString(data) : data;\n};\n\nISOBox.prototype._parseBox = function() {\n this._parsing = true;\n this._cursor.offset = this._offset;\n\n // return immediately if there are not enough bytes to read the header\n if (this._offset + 8 > this._raw.buffer.byteLength) {\n this._root._incomplete = true;\n return;\n }\n\n this._procField('size', 'uint', 32);\n this._procField('type', 'string', 4);\n\n if (this.size === 1) { this._procField('largesize', 'uint', 64); }\n if (this.type === 'uuid') { this._procFieldArray('usertype', 16, 'uint', 8); }\n\n switch(this.size) {\n case 0:\n this._raw = new DataView(this._raw.buffer, this._offset, (this._raw.byteLength - this._cursor.offset + 8));\n break;\n case 1:\n if (this._offset + this.size > this._raw.buffer.byteLength) {\n this._incomplete = true;\n this._root._incomplete = true;\n } else {\n this._raw = new DataView(this._raw.buffer, this._offset, this.largesize);\n }\n break;\n default:\n if (this._offset + this.size > this._raw.buffer.byteLength) {\n this._incomplete = true;\n this._root._incomplete = true;\n } else {\n this._raw = new DataView(this._raw.buffer, this._offset, this.size);\n }\n }\n\n // additional parsing\n if (!this._incomplete) {\n if (this._boxProcessors[this.type]) {\n this._boxProcessors[this.type].call(this);\n }\n if (this._boxContainers.indexOf(this.type) !== -1) {\n this._parseContainerBox();\n } else{\n // Unknown box => read and store box content\n this._data = this._readData();\n }\n }\n};\n\nISOBox.prototype._parseFullBox = function() {\n this.version = this._readUint(8);\n this.flags = this._readUint(24);\n};\n\nISOBox.prototype._parseContainerBox = function() {\n this.boxes = [];\n while (this._cursor.offset - this._raw.byteOffset < this._raw.byteLength) {\n this.boxes.push(ISOBox.parse(this));\n }\n};\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n// Write functions\n\nISOBox.prototype.append = function(box, pos) {\n ISOBoxer.Utils.appendBox(this, box, pos);\n};\n\nISOBox.prototype.getLength = function() {\n this._parsing = false;\n this._rawo = null;\n\n this.size = 0;\n this._procField('size', 'uint', 32);\n this._procField('type', 'string', 4);\n\n if (this.size === 1) { this._procField('largesize', 'uint', 64); }\n if (this.type === 'uuid') { this._procFieldArray('usertype', 16, 'uint', 8); }\n\n if (this._boxProcessors[this.type]) {\n this._boxProcessors[this.type].call(this);\n }\n\n if (this._boxContainers.indexOf(this.type) !== -1) {\n for (var i = 0; i < this.boxes.length; i++) {\n this.size += this.boxes[i].getLength();\n }\n } \n\n if (this._data) {\n this._writeData(this._data);\n }\n\n return this.size;\n};\n\nISOBox.prototype.write = function() {\n this._parsing = false;\n this._cursor.offset = this._parent._cursor.offset;\n\n switch(this.size) {\n case 0:\n this._rawo = new DataView(this._parent._rawo.buffer, this._cursor.offset, (this.parent._rawo.byteLength - this._cursor.offset));\n break;\n case 1:\n this._rawo = new DataView(this._parent._rawo.buffer, this._cursor.offset, this.largesize);\n break;\n default:\n this._rawo = new DataView(this._parent._rawo.buffer, this._cursor.offset, this.size);\n }\n\n this._procField('size', 'uint', 32);\n this._procField('type', 'string', 4);\n\n if (this.size === 1) { this._procField('largesize', 'uint', 64); }\n if (this.type === 'uuid') { this._procFieldArray('usertype', 16, 'uint', 8); }\n\n if (this._boxProcessors[this.type]) {\n this._boxProcessors[this.type].call(this);\n }\n\n if (this._boxContainers.indexOf(this.type) !== -1) {\n for (var i = 0; i < this.boxes.length; i++) {\n this.boxes[i].write();\n }\n } \n\n if (this._data) {\n this._writeData(this._data);\n }\n\n this._parent._cursor.offset += this.size;\n\n return this.size;\n};\n\nISOBox.prototype._writeInt = function(size, value) {\n if (this._rawo) {\n var offset = this._cursor.offset - this._rawo.byteOffset;\n switch(size) {\n case 8:\n this._rawo.setInt8(offset, value);\n break;\n case 16:\n this._rawo.setInt16(offset, value);\n break;\n case 32:\n this._rawo.setInt32(offset, value);\n break;\n case 64:\n // Warning: JavaScript cannot handle 64-bit integers natively.\n // This will give unexpected results for integers >= 2^53\n var s1 = Math.floor(value / Math.pow(2,32));\n var s2 = value - (s1 * Math.pow(2,32));\n this._rawo.setUint32(offset, s1);\n this._rawo.setUint32(offset + 4, s2);\n break;\n }\n this._cursor.offset += (size >> 3);\n } else {\n this.size += (size >> 3);\n }\n};\n\nISOBox.prototype._writeUint = function(size, value) {\n\n if (this._rawo) {\n var offset = this._cursor.offset - this._rawo.byteOffset,\n s1, s2;\n switch(size) {\n case 8:\n this._rawo.setUint8(offset, value);\n break;\n case 16:\n this._rawo.setUint16(offset, value);\n break;\n case 24:\n s1 = (value & 0xFFFF00) >> 8;\n s2 = (value & 0x0000FF);\n this._rawo.setUint16(offset, s1);\n this._rawo.setUint8(offset + 2, s2);\n break;\n case 32:\n this._rawo.setUint32(offset, value);\n break;\n case 64:\n // Warning: JavaScript cannot handle 64-bit integers natively.\n // This will give unexpected results for integers >= 2^53\n s1 = Math.floor(value / Math.pow(2,32));\n s2 = value - (s1 * Math.pow(2,32));\n this._rawo.setUint32(offset, s1);\n this._rawo.setUint32(offset + 4, s2);\n break;\n }\n this._cursor.offset += (size >> 3);\n } else {\n this.size += (size >> 3);\n }\n};\n\nISOBox.prototype._writeString = function(size, str) {\n for (var c = 0; c < size; c++) {\n this._writeUint(8, str.charCodeAt(c));\n }\n};\n\nISOBox.prototype._writeTerminatedString = function(str) {\n if (str.length === 0) {\n return;\n }\n for (var c = 0; c < str.length; c++) {\n this._writeUint(8, str.charCodeAt(c));\n }\n this._writeUint(8, 0);\n};\n\nISOBox.prototype._writeTemplate = function(size, value) {\n var pre = Math.floor(value);\n var post = (value - pre) * Math.pow(2, size / 2);\n this._writeUint(size / 2, pre);\n this._writeUint(size / 2, post);\n};\n\nISOBox.prototype._writeData = function(data) {\n var i;\n //data to copy\n if (data) {\n if (this._rawo) {\n //Array and Uint8Array has also to be managed\n if (data instanceof Array) {\n var offset = this._cursor.offset - this._rawo.byteOffset;\n for (var i = 0; i < data.length; i++) {\n this._rawo.setInt8(offset + i, data[i]);\n }\n this._cursor.offset += data.length;\n } \n\n if (data instanceof Uint8Array) {\n this._root.bytes.set(data, this._cursor.offset);\n this._cursor.offset += data.length;\n }\n\n } else {\n //nothing to copy only size to compute\n this.size += data.length;\n }\n }\n};\n\nISOBox.prototype._writeUTF8String = function(string) {\n var u = ISOBoxer.Utils.utf8ToByteArray(string);\n if (this._rawo) {\n var dataView = new DataView(this._rawo.buffer, this._cursor.offset, u.length);\n for (var i = 0; i < u.length; i++) {\n dataView.setUint8(i, u[i]);\n }\n } else {\n this.size += u.length;\n }\n};\n\nISOBox.prototype._writeField = function(type, size, value) {\n switch (type) {\n case 'uint':\n this._writeUint(size, value);\n break;\n case 'int':\n this._writeInt(size, value);\n break;\n case 'template':\n this._writeTemplate(size, value);\n break;\n case 'string':\n if (size == -1) {\n this._writeTerminatedString(value);\n } else {\n this._writeString(size, value);\n }\n break;\n case 'data':\n this._writeData(value);\n break;\n case 'utf8':\n this._writeUTF8String(value);\n break;\n default:\n break;\n }\n};\n\n// ISO/IEC 14496-15:2014 - avc1 box\nISOBox.prototype._boxProcessors['avc1'] = ISOBox.prototype._boxProcessors['encv'] = function() {\n // SampleEntry fields\n this._procFieldArray('reserved1', 6, 'uint', 8);\n this._procField('data_reference_index', 'uint', 16);\n // VisualSampleEntry fields\n this._procField('pre_defined1', 'uint', 16);\n this._procField('reserved2', 'uint', 16);\n this._procFieldArray('pre_defined2', 3, 'uint', 32);\n this._procField('width', 'uint', 16);\n this._procField('height', 'uint', 16);\n this._procField('horizresolution', 'template', 32);\n this._procField('vertresolution', 'template', 32);\n this._procField('reserved3', 'uint', 32);\n this._procField('frame_count', 'uint', 16);\n this._procFieldArray('compressorname', 32,'uint', 8);\n this._procField('depth', 'uint', 16);\n this._procField('pre_defined3', 'int', 16);\n // AVCSampleEntry fields\n this._procField('config', 'data', -1);\n};\n\n// ISO/IEC 14496-12:2012 - 8.7.2 Data Reference Box\nISOBox.prototype._boxProcessors['dref'] = function() {\n this._procFullBox();\n this._procField('entry_count', 'uint', 32);\n this._procSubBoxes('entries', this.entry_count);\n};\n\n// ISO/IEC 14496-12:2012 - 8.6.6 Edit List Box\nISOBox.prototype._boxProcessors['elst'] = function() {\n this._procFullBox();\n this._procField('entry_count', 'uint', 32);\n this._procEntries('entries', this.entry_count, function(entry) {\n this._procEntryField(entry, 'segment_duration', 'uint', (this.version === 1) ? 64 : 32);\n this._procEntryField(entry, 'media_time', 'int', (this.version === 1) ? 64 : 32);\n this._procEntryField(entry, 'media_rate_integer', 'int', 16);\n this._procEntryField(entry, 'media_rate_fraction', 'int', 16);\n });\n};\n\n// ISO/IEC 23009-1:2014 - 5.10.3.3 Event Message Box\nISOBox.prototype._boxProcessors['emsg'] = function() {\n this._procFullBox();\n if (this.version == 1) {\n this._procField('timescale', 'uint', 32);\n this._procField('presentation_time', 'uint', 64);\n this._procField('event_duration', 'uint', 32);\n this._procField('id', 'uint', 32);\n this._procField('scheme_id_uri', 'string', -1);\n this._procField('value', 'string', -1);\n } else {\n this._procField('scheme_id_uri', 'string', -1);\n this._procField('value', 'string', -1);\n this._procField('timescale', 'uint', 32);\n this._procField('presentation_time_delta', 'uint', 32);\n this._procField('event_duration', 'uint', 32);\n this._procField('id', 'uint', 32);\n }\n this._procField('message_data', 'data', -1);\n};\n// ISO/IEC 14496-12:2012 - 8.1.2 Free Space Box\nISOBox.prototype._boxProcessors['free'] = ISOBox.prototype._boxProcessors['skip'] = function() {\n this._procField('data', 'data', -1);\n};\n\n// ISO/IEC 14496-12:2012 - 8.12.2 Original Format Box\nISOBox.prototype._boxProcessors['frma'] = function() {\n this._procField('data_format', 'uint', 32);\n};\n// ISO/IEC 14496-12:2012 - 4.3 File Type Box / 8.16.2 Segment Type Box\nISOBox.prototype._boxProcessors['ftyp'] =\nISOBox.prototype._boxProcessors['styp'] = function() {\n this._procField('major_brand', 'string', 4);\n this._procField('minor_version', 'uint', 32);\n var nbCompatibleBrands = -1;\n if (this._parsing) {\n nbCompatibleBrands = (this._raw.byteLength - (this._cursor.offset - this._raw.byteOffset)) / 4;\n }\n this._procFieldArray('compatible_brands', nbCompatibleBrands, 'string', 4);\n};\n\n// ISO/IEC 14496-12:2012 - 8.4.3 Handler Reference Box\nISOBox.prototype._boxProcessors['hdlr'] = function() {\n this._procFullBox();\n this._procField('pre_defined', 'uint', 32);\n this._procField('handler_type', 'string', 4);\n this._procFieldArray('reserved', 3, 'uint', 32);\n this._procField('name', 'string', -1);\n};\n\n// ISO/IEC 14496-12:2012 - 8.1.1 Media Data Box\nISOBox.prototype._boxProcessors['mdat'] = function() {\n this._procField('data', 'data', -1);\n};\n\n// ISO/IEC 14496-12:2012 - 8.4.2 Media Header Box\nISOBox.prototype._boxProcessors['mdhd'] = function() {\n this._procFullBox();\n this._procField('creation_time', 'uint', (this.version == 1) ? 64 : 32);\n this._procField('modification_time', 'uint', (this.version == 1) ? 64 : 32);\n this._procField('timescale', 'uint', 32);\n this._procField('duration', 'uint', (this.version == 1) ? 64 : 32);\n if (!this._parsing && typeof this.language === 'string') {\n // In case of writing and language has been set as a string, then convert it into char codes array\n this.language = ((this.language.charCodeAt(0) - 0x60) << 10) |\n ((this.language.charCodeAt(1) - 0x60) << 5) |\n ((this.language.charCodeAt(2) - 0x60));\n }\n this._procField('language', 'uint', 16);\n if (this._parsing) {\n this.language = String.fromCharCode(((this.language >> 10) & 0x1F) + 0x60,\n ((this.language >> 5) & 0x1F) + 0x60,\n (this.language & 0x1F) + 0x60);\n }\n this._procField('pre_defined', 'uint', 16);\n};\n\n// ISO/IEC 14496-12:2012 - 8.8.2 Movie Extends Header Box\nISOBox.prototype._boxProcessors['mehd'] = function() {\n this._procFullBox();\n this._procField('fragment_duration', 'uint', (this.version == 1) ? 64 : 32);\n};\n\n// ISO/IEC 14496-12:2012 - 8.8.5 Movie Fragment Header Box\nISOBox.prototype._boxProcessors['mfhd'] = function() {\n this._procFullBox();\n this._procField('sequence_number', 'uint', 32);\n};\n\n// ISO/IEC 14496-12:2012 - 8.8.11 Movie Fragment Random Access Box\nISOBox.prototype._boxProcessors['mfro'] = function() {\n this._procFullBox();\n this._procField('mfra_size', 'uint', 32); // Called mfra_size to distinguish from the normal \"size\" attribute of a box\n};\n\n\n// ISO/IEC 14496-12:2012 - 8.5.2.2 mp4a box (use AudioSampleEntry definition and naming)\nISOBox.prototype._boxProcessors['mp4a'] = ISOBox.prototype._boxProcessors['enca'] = function() {\n // SampleEntry fields\n this._procFieldArray('reserved1', 6, 'uint', 8);\n this._procField('data_reference_index', 'uint', 16);\n // AudioSampleEntry fields\n this._procFieldArray('reserved2', 2, 'uint', 32);\n this._procField('channelcount', 'uint', 16);\n this._procField('samplesize', 'uint', 16);\n this._procField('pre_defined', 'uint', 16);\n this._procField('reserved3', 'uint', 16);\n this._procField('samplerate', 'template', 32);\n // ESDescriptor fields\n this._procField('esds', 'data', -1);\n};\n\n// ISO/IEC 14496-12:2012 - 8.2.2 Movie Header Box\nISOBox.prototype._boxProcessors['mvhd'] = function() {\n this._procFullBox();\n this._procField('creation_time', 'uint', (this.version == 1) ? 64 : 32);\n this._procField('modification_time', 'uint', (this.version == 1) ? 64 : 32);\n this._procField('timescale', 'uint', 32);\n this._procField('duration', 'uint', (this.version == 1) ? 64 : 32);\n this._procField('rate', 'template', 32);\n this._procField('volume', 'template', 16);\n this._procField('reserved1', 'uint', 16);\n this._procFieldArray('reserved2', 2, 'uint', 32);\n this._procFieldArray('matrix', 9, 'template', 32);\n this._procFieldArray('pre_defined', 6,'uint', 32);\n this._procField('next_track_ID', 'uint', 32);\n};\n\n// ISO/IEC 14496-30:2014 - WebVTT Cue Payload Box.\nISOBox.prototype._boxProcessors['payl'] = function() {\n this._procField('cue_text', 'utf8');\n};\n\n//ISO/IEC 23001-7:2011 - 8.1 Protection System Specific Header Box\nISOBox.prototype._boxProcessors['pssh'] = function() {\n this._procFullBox();\n \n this._procFieldArray('SystemID', 16, 'uint', 8);\n this._procField('DataSize', 'uint', 32);\n this._procFieldArray('Data', this.DataSize, 'uint', 8);\n};\n// ISO/IEC 14496-12:2012 - 8.12.5 Scheme Type Box\nISOBox.prototype._boxProcessors['schm'] = function() {\n this._procFullBox();\n \n this._procField('scheme_type', 'uint', 32);\n this._procField('scheme_version', 'uint', 32);\n\n if (this.flags & 0x000001) {\n this._procField('scheme_uri', 'string', -1);\n }\n};\n// ISO/IEC 14496-12:2012 - 8.6.4.1 sdtp box \nISOBox.prototype._boxProcessors['sdtp'] = function() {\n this._procFullBox();\n\n var sample_count = -1;\n if (this._parsing) {\n sample_count = (this._raw.byteLength - (this._cursor.offset - this._raw.byteOffset));\n }\n\n this._procFieldArray('sample_dependency_table', sample_count, 'uint', 8);\n};\n\n// ISO/IEC 14496-12:2012 - 8.16.3 Segment Index Box\nISOBox.prototype._boxProcessors['sidx'] = function() {\n this._procFullBox();\n this._procField('reference_ID', 'uint', 32);\n this._procField('timescale', 'uint', 32);\n this._procField('earliest_presentation_time', 'uint', (this.version == 1) ? 64 : 32);\n this._procField('first_offset', 'uint', (this.version == 1) ? 64 : 32);\n this._procField('reserved', 'uint', 16);\n this._procField('reference_count', 'uint', 16);\n this._procEntries('references', this.reference_count, function(entry) {\n if (!this._parsing) {\n entry.reference = (entry.reference_type & 0x00000001) << 31;\n entry.reference |= (entry.referenced_size & 0x7FFFFFFF);\n entry.sap = (entry.starts_with_SAP & 0x00000001) << 31;\n entry.sap |= (entry.SAP_type & 0x00000003) << 28;\n entry.sap |= (entry.SAP_delta_time & 0x0FFFFFFF);\n }\n this._procEntryField(entry, 'reference', 'uint', 32);\n this._procEntryField(entry, 'subsegment_duration', 'uint', 32);\n this._procEntryField(entry, 'sap', 'uint', 32);\n if (this._parsing) {\n entry.reference_type = (entry.reference >> 31) & 0x00000001;\n entry.referenced_size = entry.reference & 0x7FFFFFFF;\n entry.starts_with_SAP = (entry.sap >> 31) & 0x00000001;\n entry.SAP_type = (entry.sap >> 28) & 0x00000007;\n entry.SAP_delta_time = (entry.sap & 0x0FFFFFFF);\n }\n });\n};\n\n// ISO/IEC 14496-12:2012 - 8.4.5.3 Sound Media Header Box\nISOBox.prototype._boxProcessors['smhd'] = function() {\n this._procFullBox();\n this._procField('balance', 'uint', 16);\n this._procField('reserved', 'uint', 16);\n};\n\n// ISO/IEC 14496-12:2012 - 8.16.4 Subsegment Index Box\nISOBox.prototype._boxProcessors['ssix'] = function() {\n this._procFullBox();\n this._procField('subsegment_count', 'uint', 32);\n this._procEntries('subsegments', this.subsegment_count, function(subsegment) {\n this._procEntryField(subsegment, 'ranges_count', 'uint', 32);\n this._procSubEntries(subsegment, 'ranges', subsegment.ranges_count, function(range) {\n this._procEntryField(range, 'level', 'uint', 8);\n this._procEntryField(range, 'range_size', 'uint', 24);\n });\n });\n};\n\n// ISO/IEC 14496-12:2012 - 8.5.2 Sample Description Box\nISOBox.prototype._boxProcessors['stsd'] = function() {\n this._procFullBox();\n this._procField('entry_count', 'uint', 32);\n this._procSubBoxes('entries', this.entry_count);\n};\n\n// ISO/IEC 14496-12:2015 - 8.7.7 Sub-Sample Information Box\nISOBox.prototype._boxProcessors['subs'] = function () {\n this._procFullBox();\n this._procField('entry_count', 'uint', 32);\n this._procEntries('entries', this.entry_count, function(entry) {\n this._procEntryField(entry, 'sample_delta', 'uint', 32);\n this._procEntryField(entry, 'subsample_count', 'uint', 16);\n this._procSubEntries(entry, 'subsamples', entry.subsample_count, function(subsample) {\n this._procEntryField(subsample, 'subsample_size', 'uint', (this.version === 1) ? 32 : 16);\n this._procEntryField(subsample, 'subsample_priority', 'uint', 8);\n this._procEntryField(subsample, 'discardable', 'uint', 8);\n this._procEntryField(subsample, 'codec_specific_parameters', 'uint', 32);\n });\n });\n};\n\n//ISO/IEC 23001-7:2011 - 8.2 Track Encryption Box\nISOBox.prototype._boxProcessors['tenc'] = function() {\n this._procFullBox();\n\n this._procField('default_IsEncrypted', 'uint', 24);\n this._procField('default_IV_size', 'uint', 8);\n this._procFieldArray('default_KID', 16, 'uint', 8);\n };\n\n// ISO/IEC 14496-12:2012 - 8.8.12 Track Fragmnent Decode Time\nISOBox.prototype._boxProcessors['tfdt'] = function() {\n this._procFullBox();\n this._procField('baseMediaDecodeTime', 'uint', (this.version == 1) ? 64 : 32);\n};\n\n// ISO/IEC 14496-12:2012 - 8.8.7 Track Fragment Header Box\nISOBox.prototype._boxProcessors['tfhd'] = function() {\n this._procFullBox();\n this._procField('track_ID', 'uint', 32);\n if (this.flags & 0x01) this._procField('base_data_offset', 'uint', 64);\n if (this.flags & 0x02) this._procField('sample_description_offset', 'uint', 32);\n if (this.flags & 0x08) this._procField('default_sample_duration', 'uint', 32);\n if (this.flags & 0x10) this._procField('default_sample_size', 'uint', 32);\n if (this.flags & 0x20) this._procField('default_sample_flags', 'uint', 32);\n};\n\n// ISO/IEC 14496-12:2012 - 8.8.10 Track Fragment Random Access Box\nISOBox.prototype._boxProcessors['tfra'] = function() {\n this._procFullBox();\n this._procField('track_ID', 'uint', 32);\n if (!this._parsing) {\n this.reserved = 0;\n this.reserved |= (this.length_size_of_traf_num & 0x00000030) << 4;\n this.reserved |= (this.length_size_of_trun_num & 0x0000000C) << 2;\n this.reserved |= (this.length_size_of_sample_num & 0x00000003);\n }\n this._procField('reserved', 'uint', 32);\n if (this._parsing) {\n this.length_size_of_traf_num = (this.reserved & 0x00000030) >> 4;\n this.length_size_of_trun_num = (this.reserved & 0x0000000C) >> 2;\n this.length_size_of_sample_num = (this.reserved & 0x00000003);\n }\n this._procField('number_of_entry', 'uint', 32);\n this._procEntries('entries', this.number_of_entry, function(entry) {\n this._procEntryField(entry, 'time', 'uint', (this.version === 1) ? 64 : 32);\n this._procEntryField(entry, 'moof_offset', 'uint', (this.version === 1) ? 64 : 32);\n this._procEntryField(entry, 'traf_number', 'uint', (this.length_size_of_traf_num + 1) * 8);\n this._procEntryField(entry, 'trun_number', 'uint', (this.length_size_of_trun_num + 1) * 8);\n this._procEntryField(entry, 'sample_number', 'uint', (this.length_size_of_sample_num + 1) * 8);\n });\n};\n\n// ISO/IEC 14496-12:2012 - 8.3.2 Track Header Box\nISOBox.prototype._boxProcessors['tkhd'] = function() {\n this._procFullBox();\n this._procField('creation_time', 'uint', (this.version == 1) ? 64 : 32);\n this._procField('modification_time', 'uint', (this.version == 1) ? 64 : 32);\n this._procField('track_ID', 'uint', 32);\n this._procField('reserved1', 'uint', 32);\n this._procField('duration', 'uint', (this.version == 1) ? 64 : 32);\n this._procFieldArray('reserved2', 2, 'uint', 32);\n this._procField('layer', 'uint', 16);\n this._procField('alternate_group', 'uint', 16);\n this._procField('volume', 'template', 16);\n this._procField('reserved3', 'uint', 16);\n this._procFieldArray('matrix', 9, 'template', 32);\n this._procField('width', 'template', 32);\n this._procField('height', 'template', 32);\n};\n\n// ISO/IEC 14496-12:2012 - 8.8.3 Track Extends Box\nISOBox.prototype._boxProcessors['trex'] = function() {\n this._procFullBox();\n this._procField('track_ID', 'uint', 32);\n this._procField('default_sample_description_index', 'uint', 32);\n this._procField('default_sample_duration', 'uint', 32);\n this._procField('default_sample_size', 'uint', 32);\n this._procField('default_sample_flags', 'uint', 32);\n};\n\n// ISO/IEC 14496-12:2012 - 8.8.8 Track Run Box\n// Note: the 'trun' box has a direct relation to the 'tfhd' box for defaults.\n// These defaults are not set explicitly here, but are left to resolve for the user.\nISOBox.prototype._boxProcessors['trun'] = function() {\n this._procFullBox();\n this._procField('sample_count', 'uint', 32);\n if (this.flags & 0x1) this._procField('data_offset', 'int', 32);\n if (this.flags & 0x4) this._procField('first_sample_flags', 'uint', 32);\n this._procEntries('samples', this.sample_count, function(sample) {\n if (this.flags & 0x100) this._procEntryField(sample, 'sample_duration', 'uint', 32);\n if (this.flags & 0x200) this._procEntryField(sample, 'sample_size', 'uint', 32);\n if (this.flags & 0x400) this._procEntryField(sample, 'sample_flags', 'uint', 32);\n if (this.flags & 0x800) this._procEntryField(sample, 'sample_composition_time_offset', (this.version === 1) ? 'int' : 'uint', 32);\n });\n};\n\n// ISO/IEC 14496-12:2012 - 8.7.2 Data Reference Box\nISOBox.prototype._boxProcessors['url '] = ISOBox.prototype._boxProcessors['urn '] = function() {\n this._procFullBox();\n if (this.type === 'urn ') {\n this._procField('name', 'string', -1);\n }\n this._procField('location', 'string', -1);\n};\n\n// ISO/IEC 14496-30:2014 - WebVTT Source Label Box\nISOBox.prototype._boxProcessors['vlab'] = function() {\n this._procField('source_label', 'utf8');\n};\n\n// ISO/IEC 14496-12:2012 - 8.4.5.2 Video Media Header Box\nISOBox.prototype._boxProcessors['vmhd'] = function() {\n this._procFullBox();\n this._procField('graphicsmode', 'uint', 16);\n this._procFieldArray('opcolor', 3, 'uint', 16);\n};\n\n// ISO/IEC 14496-30:2014 - WebVTT Configuration Box\nISOBox.prototype._boxProcessors['vttC'] = function() {\n this._procField('config', 'utf8');\n};\n\n// ISO/IEC 14496-30:2014 - WebVTT Empty Sample Box\nISOBox.prototype._boxProcessors['vtte'] = function() {\n // Nothing should happen here.\n};\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport FactoryMaker from '../../core/FactoryMaker';\n\nfunction RequestModifier() {\n\n let instance;\n\n function modifyRequestURL(url) {\n return url;\n }\n\n function modifyRequestHeader(request) {\n return request;\n }\n\n instance = {\n modifyRequestURL: modifyRequestURL,\n modifyRequestHeader: modifyRequestHeader\n };\n\n return instance;\n}\n\nRequestModifier.__dashjs_factory_name = 'RequestModifier';\nexport default FactoryMaker.getSingletonFactory(RequestModifier);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass ErrorsBase {\n extend (errors, config) {\n if (!errors) return;\n\n let override = config ? config.override : false;\n let publicOnly = config ? config.publicOnly : false;\n\n\n for (const err in errors) {\n if (!errors.hasOwnProperty(err) || (this[err] && !override)) continue;\n if (publicOnly && errors[err].indexOf('public_') === -1) continue;\n this[err] = errors[err];\n\n }\n }\n}\n\nexport default ErrorsBase;","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport FactoryMaker from '../../core/FactoryMaker';\n\n/**\n * @module XHRLoader\n * @ignore\n * @description Manages download of resources via HTTP.\n * @param {Object} cfg - dependencies from parent\n */\nfunction XHRLoader(cfg) {\n\n cfg = cfg || {};\n const requestModifier = cfg.requestModifier;\n\n let instance;\n\n function load(httpRequest) {\n\n // Variables will be used in the callback functions\n const requestStartTime = new Date();\n const request = httpRequest.request;\n\n let xhr = new XMLHttpRequest();\n xhr.open(httpRequest.method, httpRequest.url, true);\n\n if (request.responseType) {\n xhr.responseType = request.responseType;\n }\n\n if (request.range) {\n xhr.setRequestHeader('Range', 'bytes=' + request.range);\n }\n\n if (!request.requestStartDate) {\n request.requestStartDate = requestStartTime;\n }\n\n if (requestModifier) {\n xhr = requestModifier.modifyRequestHeader(xhr);\n }\n\n if (httpRequest.headers) {\n for (let header in httpRequest.headers) {\n let value = httpRequest.headers[header];\n if (value) {\n xhr.setRequestHeader(header, value);\n }\n }\n }\n\n xhr.withCredentials = httpRequest.withCredentials;\n\n xhr.onload = httpRequest.onload;\n xhr.onloadend = httpRequest.onend;\n xhr.onerror = httpRequest.onerror;\n xhr.onprogress = httpRequest.progress;\n xhr.onabort = httpRequest.onabort;\n xhr.ontimeout = httpRequest.ontimeout;\n xhr.timeout = httpRequest.timeout;\n\n xhr.send();\n\n httpRequest.response = xhr;\n }\n\n function abort(request) {\n const x = request.response;\n x.onloadend = x.onerror = x.onprogress = undefined; //Ignore events from aborted requests.\n x.abort();\n }\n\n instance = {\n load: load,\n abort: abort\n };\n\n return instance;\n}\n\nXHRLoader.__dashjs_factory_name = 'XHRLoader';\n\nconst factory = FactoryMaker.getClassFactory(XHRLoader);\nexport default factory;\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass Segment {\n constructor() {\n this.indexRange = null;\n // The index of the segment in the list of segments. We start at 0\n this.index = null;\n this.mediaRange = null;\n this.media = null;\n this.duration = NaN;\n // this is the time that should be inserted into the media url\n this.replacementTime = null;\n // this is the number that should be inserted into the media url\n this.replacementNumber = NaN;\n // This is supposed to match the time encoded in the media Segment\n this.mediaStartTime = NaN;\n // When the source buffer timeOffset is set to MSETimeOffset this is the\n // time that will match the seekTarget and video.currentTime\n this.presentationStartTime = NaN;\n // Do not schedule this segment until\n this.availabilityStartTime = NaN;\n // Ignore and discard this segment after\n this.availabilityEndTime = NaN;\n // For dynamic mpd's, this is the wall clock time that the video\n // element currentTime should be presentationStartTime\n this.wallStartTime = NaN;\n this.representation = null;\n }\n}\n\nexport default Segment;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\n\nimport DashConstants from '../constants/DashConstants';\n\nclass Representation {\n constructor() {\n this.id = null;\n this.index = -1;\n this.adaptation = null;\n this.segmentInfoType = null;\n this.initialization = null;\n this.codecs = null;\n this.mimeType = null;\n this.codecPrivateData = null;\n this.segmentDuration = NaN;\n this.timescale = 1;\n this.startNumber = 1;\n this.indexRange = null;\n this.range = null;\n this.presentationTimeOffset = 0;\n // Set the source buffer timeOffset to this\n this.MSETimeOffset = NaN;\n // The information we need in the DashHandler to determine whether the last segment has been loaded\n this.mediaFinishedInformation = { numberOfSegments: 0, mediaTimeOfLastSignaledSegment: NaN };\n this.bandwidth = NaN;\n this.width = NaN;\n this.height = NaN;\n this.scanType = null;\n this.maxPlayoutRate = NaN;\n this.availabilityTimeOffset = 0;\n this.availabilityTimeComplete = true;\n }\n\n hasInitialization() {\n return (this.initialization !== null || this.range !== null);\n }\n\n hasSegments() {\n return this.segmentInfoType !== DashConstants.BASE_URL &&\n this.segmentInfoType !== DashConstants.SEGMENT_BASE &&\n !this.indexRange;\n }\n}\n\nexport default Representation;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass AdaptationSet {\n constructor() {\n this.period = null;\n this.index = -1;\n this.type = null;\n }\n}\n\nexport default AdaptationSet;","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass Period {\n constructor() {\n this.id = null;\n this.index = -1;\n this.duration = NaN;\n this.start = NaN;\n this.mpd = null;\n this.nextPeriodId = null;\n }\n}\n\nPeriod.DEFAULT_ID = 'defaultId';\n\nexport default Period;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass Mpd {\n constructor() {\n this.manifest = null;\n this.suggestedPresentationDelay = 0;\n this.availabilityStartTime = null;\n this.availabilityEndTime = Number.POSITIVE_INFINITY;\n this.timeShiftBufferDepth = Number.POSITIVE_INFINITY;\n this.maxSegmentDuration = Number.POSITIVE_INFINITY;\n this.publishTime = null;\n this.minimumUpdatePeriod = NaN;\n this.mediaPresentationDuration = NaN;\n }\n}\n\nexport default Mpd;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass EventStream {\n constructor() {\n this.adaptionSet = null;\n this.representation = null;\n this.period = null;\n this.timescale = 1;\n this.value = '';\n this.schemeIdUri = '';\n this.presentationTimeOffset = 0;\n }\n}\n\nexport default EventStream;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Constants from '../../streaming/constants/Constants';\nimport DashConstants from '../constants/DashConstants';\nimport Representation from '../vo/Representation';\nimport AdaptationSet from '../vo/AdaptationSet';\nimport Period from '../vo/Period';\nimport Mpd from '../vo/Mpd';\nimport UTCTiming from '../vo/UTCTiming';\nimport Event from '../vo/Event';\nimport BaseURL from '../vo/BaseURL';\nimport EventStream from '../vo/EventStream';\nimport ObjectUtils from '../../streaming/utils/ObjectUtils';\nimport URLUtils from '../../streaming/utils/URLUtils';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Debug from '../../core/Debug';\nimport DashJSError from '../../streaming/vo/DashJSError';\nimport Errors from '../../core/errors/Errors';\nimport {THUMBNAILS_SCHEME_ID_URIS} from '../../streaming/thumbnail/ThumbnailTracks';\n\nfunction DashManifestModel() {\n let instance,\n logger,\n errHandler,\n BASE64;\n\n const context = this.context;\n const urlUtils = URLUtils(context).getInstance();\n\n const isInteger = Number.isInteger || function (value) {\n return typeof value === 'number' &&\n isFinite(value) &&\n Math.floor(value) === value;\n };\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n }\n\n function getIsTypeOf(adaptation, type) {\n if (!adaptation) {\n throw new Error('adaptation is not defined');\n }\n\n if (!type) {\n throw new Error('type is not defined');\n }\n\n // Check for thumbnail images\n if (adaptation.Representation_asArray && adaptation.Representation_asArray.length) {\n const essentialProperties = getEssentialPropertiesForRepresentation(adaptation.Representation_asArray[0]);\n if (essentialProperties && essentialProperties.length > 0 && THUMBNAILS_SCHEME_ID_URIS.indexOf(essentialProperties[0].schemeIdUri) >= 0) {\n return (type === Constants.IMAGE);\n }\n }\n\n // Check ContentComponent.contentType\n if (adaptation.ContentComponent_asArray && adaptation.ContentComponent_asArray.length > 0) {\n if (adaptation.ContentComponent_asArray.length > 1) {\n return (type === Constants.MUXED);\n } else if (adaptation.ContentComponent_asArray[0].contentType === type) {\n return true;\n }\n }\n\n const mimeTypeRegEx = (type === Constants.TEXT) ? new RegExp('(ttml|vtt|wvtt|stpp)') : new RegExp(type);\n\n // Check codecs\n if (adaptation.Representation_asArray && adaptation.Representation_asArray.length) {\n const codecs = adaptation.Representation_asArray[0].codecs;\n if (mimeTypeRegEx.test(codecs)) {\n return true;\n }\n }\n\n // Check Adaptation's mimeType\n if (adaptation.hasOwnProperty(DashConstants.MIME_TYPE)) {\n return mimeTypeRegEx.test(adaptation.mimeType);\n }\n\n // Check Representation's mimeType\n if (adaptation.Representation_asArray) {\n let representation;\n for (let i = 0; i < adaptation.Representation_asArray.length; i++) {\n representation = adaptation.Representation_asArray[i];\n if (representation.hasOwnProperty(DashConstants.MIME_TYPE)) {\n return mimeTypeRegEx.test(representation.mimeType);\n }\n }\n }\n\n return false;\n }\n\n function getIsFragmented(adaptation) {\n if (!adaptation) {\n throw new Error('adaptation is not defined');\n }\n if (adaptation.hasOwnProperty(DashConstants.SEGMENT_TEMPLATE) ||\n adaptation.hasOwnProperty(DashConstants.SEGMENT_TIMELINE) ||\n adaptation.hasOwnProperty(DashConstants.SEGMENT_LIST) ||\n adaptation.hasOwnProperty(DashConstants.SEGMENT_BASE)) {\n return true;\n }\n if (adaptation.Representation_asArray && adaptation.Representation_asArray.length > 0) {\n const representation = adaptation.Representation_asArray[0];\n if (representation.hasOwnProperty(DashConstants.SEGMENT_TEMPLATE) ||\n representation.hasOwnProperty(DashConstants.SEGMENT_TIMELINE) ||\n representation.hasOwnProperty(DashConstants.SEGMENT_LIST) ||\n representation.hasOwnProperty(DashConstants.SEGMENT_BASE)) {\n return true;\n }\n }\n return false;\n }\n\n function getIsAudio(adaptation) {\n return getIsTypeOf(adaptation, Constants.AUDIO);\n }\n\n function getIsVideo(adaptation) {\n return getIsTypeOf(adaptation, Constants.VIDEO);\n }\n\n function getIsText(adaptation) {\n return getIsTypeOf(adaptation, Constants.TEXT);\n }\n\n function getIsMuxed(adaptation) {\n return getIsTypeOf(adaptation, Constants.MUXED);\n }\n\n function getIsImage(adaptation) {\n return getIsTypeOf(adaptation, Constants.IMAGE);\n }\n\n function getLanguageForAdaptation(adaptation) {\n let lang = '';\n\n if (adaptation && adaptation.hasOwnProperty(DashConstants.LANG)) {\n //Filter out any other characters not allowed according to RFC5646\n lang = adaptation.lang.replace(/[^A-Za-z0-9-]/g, '');\n }\n\n return lang;\n }\n\n function getViewpointForAdaptation(adaptation) {\n return adaptation && adaptation.hasOwnProperty(DashConstants.VIEWPOINT) ? adaptation.Viewpoint : null;\n }\n\n function getRolesForAdaptation(adaptation) {\n return adaptation && adaptation.hasOwnProperty(DashConstants.ROLE_ASARRAY) ? adaptation.Role_asArray : [];\n }\n\n function getAccessibilityForAdaptation(adaptation) {\n return adaptation && adaptation.hasOwnProperty(DashConstants.ACCESSIBILITY_ASARRAY) ? adaptation.Accessibility_asArray : [];\n }\n\n function getAudioChannelConfigurationForAdaptation(adaptation) {\n return adaptation && adaptation.hasOwnProperty(DashConstants.AUDIOCHANNELCONFIGURATION_ASARRAY) ? adaptation.AudioChannelConfiguration_asArray : [];\n }\n\n function getAudioChannelConfigurationForRepresentation(representation) {\n return representation && representation.hasOwnProperty(DashConstants.AUDIOCHANNELCONFIGURATION_ASARRAY) ? representation.AudioChannelConfiguration_asArray : [];\n }\n\n function getRepresentationSortFunction() {\n return (a, b) => a.bandwidth - b.bandwidth;\n }\n\n function processAdaptation(realAdaptation) {\n if (realAdaptation && Array.isArray(realAdaptation.Representation_asArray)) {\n realAdaptation.Representation_asArray.sort(getRepresentationSortFunction());\n }\n\n return realAdaptation;\n }\n\n function getRealAdaptations(manifest, periodIndex) {\n return manifest && manifest.Period_asArray && isInteger(periodIndex) ? manifest.Period_asArray[periodIndex] ? manifest.Period_asArray[periodIndex].AdaptationSet_asArray : [] : [];\n }\n\n function getRealPeriods(manifest) {\n return manifest && manifest.Period_asArray ? manifest.Period_asArray : [];\n }\n\n function getRealPeriodForIndex(index, manifest) {\n const realPeriods = getRealPeriods(manifest);\n if (realPeriods.length > 0 && isInteger(index)) {\n return realPeriods[index];\n } else {\n return null;\n }\n }\n\n function getAdaptationForId(id, manifest, periodIndex) {\n const realAdaptations = getRealAdaptations(manifest, periodIndex);\n let i,\n len;\n\n for (i = 0, len = realAdaptations.length; i < len; i++) {\n if (realAdaptations[i].hasOwnProperty(DashConstants.ID) && realAdaptations[i].id === id) {\n return realAdaptations[i];\n }\n }\n\n return null;\n }\n\n function getAdaptationForIndex(index, manifest, periodIndex) {\n const realAdaptations = getRealAdaptations(manifest, periodIndex);\n if (realAdaptations.length > 0 && isInteger(index)) {\n return realAdaptations[index];\n } else {\n return null;\n }\n }\n\n function getIndexForAdaptation(realAdaptation, manifest, periodIndex) {\n if (!realAdaptation) {\n return -1;\n }\n\n const realAdaptations = getRealAdaptations(manifest, periodIndex);\n\n for (let i = 0; i < realAdaptations.length; i++) {\n let objectUtils = ObjectUtils(context).getInstance();\n if (objectUtils.areEqual(realAdaptations[i], realAdaptation)) {\n return i;\n }\n }\n\n return -1;\n }\n\n function getAdaptationsForType(manifest, periodIndex, type) {\n const realAdaptations = getRealAdaptations(manifest, periodIndex);\n let i,\n len;\n const adaptations = [];\n\n for (i = 0, len = realAdaptations.length; i < len; i++) {\n if (getIsTypeOf(realAdaptations[i], type)) {\n adaptations.push(processAdaptation(realAdaptations[i]));\n }\n }\n\n return adaptations;\n }\n\n function getCodec(adaptation, representationId, addResolutionInfo) {\n let codec = null;\n\n if (adaptation && adaptation.Representation_asArray && adaptation.Representation_asArray.length > 0) {\n const representation = isInteger(representationId) && representationId >= 0 && representationId < adaptation.Representation_asArray.length ?\n adaptation.Representation_asArray[representationId] : adaptation.Representation_asArray[0];\n if (representation) {\n codec = representation.mimeType + ';codecs=\"' + representation.codecs + '\"';\n if (addResolutionInfo && representation.width !== undefined) {\n codec += ';width=\"' + representation.width + '\";height=\"' + representation.height + '\"';\n }\n }\n }\n\n // If the codec contains a profiles parameter we remove it. Otherwise it will cause problems when checking for codec capabilities of the platform\n if (codec) {\n codec = codec.replace(/\\sprofiles=[^;]*/g, '');\n }\n\n return codec;\n }\n\n function getMimeType(adaptation) {\n return adaptation && adaptation.Representation_asArray && adaptation.Representation_asArray.length > 0 ? adaptation.Representation_asArray[0].mimeType : null;\n }\n\n function getKID(adaptation) {\n if (!adaptation || !adaptation.hasOwnProperty(DashConstants.CENC_DEFAULT_KID)) {\n return null;\n }\n return adaptation[DashConstants.CENC_DEFAULT_KID];\n }\n\n function getLabelsForAdaptation(adaptation) {\n if (!adaptation || !Array.isArray(adaptation.Label_asArray)) {\n return [];\n }\n\n const labelArray = [];\n\n for (let i = 0; i < adaptation.Label_asArray.length; i++) {\n labelArray.push({\n lang: adaptation.Label_asArray[i].lang,\n text: adaptation.Label_asArray[i].__text || adaptation.Label_asArray[i]\n });\n }\n\n return labelArray;\n }\n\n function getContentProtectionData(adaptation) {\n if (!adaptation || !adaptation.hasOwnProperty(DashConstants.CONTENTPROTECTION_ASARRAY) || adaptation.ContentProtection_asArray.length === 0) {\n return null;\n }\n return adaptation.ContentProtection_asArray;\n }\n\n function getIsDynamic(manifest) {\n let isDynamic = false;\n if (manifest && manifest.hasOwnProperty('type')) {\n isDynamic = (manifest.type === DashConstants.DYNAMIC);\n }\n return isDynamic;\n }\n\n function getId(manifest) {\n return (manifest && manifest[DashConstants.ID]) || null;\n }\n\n function hasProfile(manifest, profile) {\n let has = false;\n\n if (manifest && manifest.profiles && manifest.profiles.length > 0) {\n has = (manifest.profiles.indexOf(profile) !== -1);\n }\n\n return has;\n }\n\n function getDuration(manifest) {\n let mpdDuration;\n //@mediaPresentationDuration specifies the duration of the entire Media Presentation.\n //If the attribute is not present, the duration of the Media Presentation is unknown.\n if (manifest && manifest.hasOwnProperty(DashConstants.MEDIA_PRESENTATION_DURATION)) {\n mpdDuration = manifest.mediaPresentationDuration;\n } else if (manifest && manifest.type == 'dynamic') {\n mpdDuration = Number.POSITIVE_INFINITY;\n } else {\n mpdDuration = Number.MAX_SAFE_INTEGER || Number.MAX_VALUE;\n }\n\n return mpdDuration;\n }\n\n function getBandwidth(representation) {\n return representation && representation.bandwidth ? representation.bandwidth : NaN;\n }\n\n function getManifestUpdatePeriod(manifest, latencyOfLastUpdate = 0) {\n let delay = NaN;\n if (manifest && manifest.hasOwnProperty(DashConstants.MINIMUM_UPDATE_PERIOD)) {\n delay = manifest.minimumUpdatePeriod;\n }\n return isNaN(delay) ? delay : Math.max(delay - latencyOfLastUpdate, 1);\n }\n\n function getPublishTime(manifest) {\n return manifest && manifest.hasOwnProperty(DashConstants.PUBLISH_TIME) ? new Date(manifest[DashConstants.PUBLISH_TIME]) : null;\n }\n\n function getRepresentationCount(adaptation) {\n return adaptation && Array.isArray(adaptation.Representation_asArray) ? adaptation.Representation_asArray.length : 0;\n }\n\n function getBitrateListForAdaptation(realAdaptation) {\n const processedRealAdaptation = processAdaptation(realAdaptation);\n const realRepresentations = processedRealAdaptation && Array.isArray(processedRealAdaptation.Representation_asArray) ? processedRealAdaptation.Representation_asArray : [];\n\n return realRepresentations.map((realRepresentation) => {\n return {\n bandwidth: realRepresentation.bandwidth,\n width: realRepresentation.width || 0,\n height: realRepresentation.height || 0,\n scanType: realRepresentation.scanType || null,\n id: realRepresentation.id || null\n };\n });\n }\n\n function getSelectionPriority(realAdaption) {\n try {\n const priority = realAdaption && typeof realAdaption.selectionPriority !== 'undefined' ? parseInt(realAdaption.selectionPriority) : 1;\n\n return isNaN(priority) ? 1 : priority;\n } catch (e) {\n return 1;\n }\n }\n\n function getEssentialPropertiesForRepresentation(realRepresentation) {\n if (!realRepresentation || !realRepresentation.EssentialProperty_asArray || !realRepresentation.EssentialProperty_asArray.length) return null;\n\n return realRepresentation.EssentialProperty_asArray.map((prop) => {\n return {\n schemeIdUri: prop.schemeIdUri,\n value: prop.value\n };\n });\n }\n\n function getRepresentationFor(index, adaptation) {\n return adaptation && adaptation.Representation_asArray && adaptation.Representation_asArray.length > 0 &&\n isInteger(index) ? adaptation.Representation_asArray[index] : null;\n }\n\n function getRealAdaptationFor(voAdaptation) {\n if (voAdaptation && voAdaptation.period && isInteger(voAdaptation.period.index)) {\n const periodArray = voAdaptation.period.mpd.manifest.Period_asArray[voAdaptation.period.index];\n if (periodArray && periodArray.AdaptationSet_asArray && isInteger(voAdaptation.index)) {\n return processAdaptation(periodArray.AdaptationSet_asArray[voAdaptation.index]);\n }\n }\n }\n\n function getRepresentationsForAdaptation(voAdaptation) {\n const voRepresentations = [];\n const processedRealAdaptation = getRealAdaptationFor(voAdaptation);\n let segmentInfo,\n baseUrl;\n\n if (processedRealAdaptation && processedRealAdaptation.Representation_asArray) {\n // TODO: TO BE REMOVED. We should get just the baseUrl elements that affects to the representations\n // that we are processing. Making it works properly will require much further changes and given\n // parsing base Urls parameters is needed for our ultra low latency examples, we will\n // keep this \"tricky\" code until the real (and good) solution comes\n if (voAdaptation && voAdaptation.period && isInteger(voAdaptation.period.index)) {\n const baseUrls = getBaseURLsFromElement(voAdaptation.period.mpd.manifest);\n if (baseUrls) {\n baseUrl = baseUrls[0];\n }\n }\n for (let i = 0, len = processedRealAdaptation.Representation_asArray.length; i < len; ++i) {\n const realRepresentation = processedRealAdaptation.Representation_asArray[i];\n const voRepresentation = new Representation();\n voRepresentation.index = i;\n voRepresentation.adaptation = voAdaptation;\n\n if (realRepresentation.hasOwnProperty(DashConstants.ID)) {\n voRepresentation.id = realRepresentation.id;\n }\n if (realRepresentation.hasOwnProperty(DashConstants.CODECS)) {\n voRepresentation.codecs = realRepresentation.codecs;\n }\n if (realRepresentation.hasOwnProperty(DashConstants.MIME_TYPE)) {\n voRepresentation.mimeType = realRepresentation[DashConstants.MIME_TYPE];\n }\n if (realRepresentation.hasOwnProperty(DashConstants.CODEC_PRIVATE_DATA)) {\n voRepresentation.codecPrivateData = realRepresentation.codecPrivateData;\n }\n if (realRepresentation.hasOwnProperty(DashConstants.BANDWITH)) {\n voRepresentation.bandwidth = realRepresentation.bandwidth;\n }\n if (realRepresentation.hasOwnProperty(DashConstants.WIDTH)) {\n voRepresentation.width = realRepresentation.width;\n }\n if (realRepresentation.hasOwnProperty(DashConstants.HEIGHT)) {\n voRepresentation.height = realRepresentation.height;\n }\n if (realRepresentation.hasOwnProperty(DashConstants.SCAN_TYPE)) {\n voRepresentation.scanType = realRepresentation.scanType;\n }\n if (realRepresentation.hasOwnProperty(DashConstants.MAX_PLAYOUT_RATE)) {\n voRepresentation.maxPlayoutRate = realRepresentation.maxPlayoutRate;\n }\n\n if (realRepresentation.hasOwnProperty(DashConstants.SEGMENT_BASE)) {\n segmentInfo = realRepresentation.SegmentBase;\n voRepresentation.segmentInfoType = DashConstants.SEGMENT_BASE;\n } else if (realRepresentation.hasOwnProperty(DashConstants.SEGMENT_LIST)) {\n segmentInfo = realRepresentation.SegmentList;\n\n if (segmentInfo.hasOwnProperty(DashConstants.SEGMENT_TIMELINE)) {\n voRepresentation.segmentInfoType = DashConstants.SEGMENT_TIMELINE;\n } else {\n voRepresentation.segmentInfoType = DashConstants.SEGMENT_LIST;\n }\n } else if (realRepresentation.hasOwnProperty(DashConstants.SEGMENT_TEMPLATE)) {\n segmentInfo = realRepresentation.SegmentTemplate;\n\n if (segmentInfo.hasOwnProperty(DashConstants.SEGMENT_TIMELINE)) {\n voRepresentation.segmentInfoType = DashConstants.SEGMENT_TIMELINE;\n } else {\n voRepresentation.segmentInfoType = DashConstants.SEGMENT_TEMPLATE;\n }\n\n if (segmentInfo.hasOwnProperty(DashConstants.INITIALIZATION_MINUS)) {\n voRepresentation.initialization = segmentInfo.initialization.split('$Bandwidth$')\n .join(realRepresentation.bandwidth).split('$RepresentationID$').join(realRepresentation.id);\n }\n } else {\n voRepresentation.segmentInfoType = DashConstants.BASE_URL;\n }\n\n voRepresentation.essentialProperties = getEssentialPropertiesForRepresentation(realRepresentation);\n\n if (segmentInfo) {\n if (segmentInfo.hasOwnProperty(DashConstants.INITIALIZATION)) {\n const initialization = segmentInfo.Initialization;\n\n if (initialization.hasOwnProperty(DashConstants.SOURCE_URL)) {\n voRepresentation.initialization = initialization.sourceURL;\n }\n\n if (initialization.hasOwnProperty(DashConstants.RANGE)) {\n voRepresentation.range = initialization.range;\n // initialization source url will be determined from\n // BaseURL when resolved at load time.\n }\n } else if (getIsText(processedRealAdaptation) &&\n getIsFragmented(processedRealAdaptation) &&\n processedRealAdaptation.mimeType &&\n processedRealAdaptation.mimeType.indexOf('application/mp4') === -1) {\n voRepresentation.range = 0;\n }\n\n if (segmentInfo.hasOwnProperty(DashConstants.TIMESCALE)) {\n voRepresentation.timescale = segmentInfo.timescale;\n }\n if (segmentInfo.hasOwnProperty(DashConstants.DURATION)) {\n // TODO according to the spec @maxSegmentDuration specifies the maximum duration of any Segment in any Representation in the Media Presentation\n // It is also said that for a SegmentTimeline any @d value shall not exceed the value of MPD@maxSegmentDuration, but nothing is said about\n // SegmentTemplate @duration attribute. We need to find out if @maxSegmentDuration should be used instead of calculated duration if the the duration\n // exceeds @maxSegmentDuration\n voRepresentation.segmentDuration = segmentInfo.duration / voRepresentation.timescale;\n } else if (realRepresentation.hasOwnProperty(DashConstants.SEGMENT_TEMPLATE)) {\n segmentInfo = realRepresentation.SegmentTemplate;\n\n if (segmentInfo.hasOwnProperty(DashConstants.SEGMENT_TIMELINE)) {\n voRepresentation.segmentDuration = calcSegmentDuration(segmentInfo.SegmentTimeline) / voRepresentation.timescale;\n }\n }\n if (segmentInfo.hasOwnProperty(DashConstants.MEDIA)) {\n voRepresentation.media = segmentInfo.media;\n }\n if (segmentInfo.hasOwnProperty(DashConstants.START_NUMBER)) {\n voRepresentation.startNumber = segmentInfo.startNumber;\n }\n if (segmentInfo.hasOwnProperty(DashConstants.INDEX_RANGE)) {\n voRepresentation.indexRange = segmentInfo.indexRange;\n }\n if (segmentInfo.hasOwnProperty(DashConstants.PRESENTATION_TIME_OFFSET)) {\n voRepresentation.presentationTimeOffset = segmentInfo.presentationTimeOffset / voRepresentation.timescale;\n }\n if (segmentInfo.hasOwnProperty(DashConstants.AVAILABILITY_TIME_OFFSET)) {\n voRepresentation.availabilityTimeOffset = segmentInfo.availabilityTimeOffset;\n } else if (baseUrl && baseUrl.availabilityTimeOffset !== undefined) {\n voRepresentation.availabilityTimeOffset = baseUrl.availabilityTimeOffset;\n }\n if (segmentInfo.hasOwnProperty(DashConstants.AVAILABILITY_TIME_COMPLETE)) {\n voRepresentation.availabilityTimeComplete = segmentInfo.availabilityTimeComplete !== 'false';\n } else if (baseUrl && baseUrl.availabilityTimeComplete !== undefined) {\n voRepresentation.availabilityTimeComplete = baseUrl.availabilityTimeComplete;\n }\n }\n\n voRepresentation.MSETimeOffset = calcMSETimeOffset(voRepresentation);\n voRepresentation.path = [voAdaptation.period.index, voAdaptation.index, i];\n voRepresentations.push(voRepresentation);\n }\n }\n\n return voRepresentations;\n }\n\n function calcSegmentDuration(segmentTimeline) {\n if (!segmentTimeline || !segmentTimeline.S_asArray) {\n return NaN;\n }\n let s0 = segmentTimeline.S_asArray[0];\n let s1 = segmentTimeline.S_asArray[1];\n return s0.hasOwnProperty('d') ? s0.d : (s1.t - s0.t);\n }\n\n function calcMSETimeOffset(representation) {\n // The MSEOffset is offset from AST for media. It is Period@start - presentationTimeOffset\n const presentationOffset = representation.presentationTimeOffset;\n const periodStart = representation.adaptation.period.start;\n return (periodStart - presentationOffset);\n }\n\n function getAdaptationsForPeriod(voPeriod) {\n const realPeriod = voPeriod && isInteger(voPeriod.index) ? voPeriod.mpd.manifest.Period_asArray[voPeriod.index] : null;\n const voAdaptations = [];\n let voAdaptationSet,\n realAdaptationSet,\n i;\n\n if (realPeriod && realPeriod.AdaptationSet_asArray) {\n for (i = 0; i < realPeriod.AdaptationSet_asArray.length; i++) {\n realAdaptationSet = realPeriod.AdaptationSet_asArray[i];\n voAdaptationSet = new AdaptationSet();\n if (realAdaptationSet.hasOwnProperty(DashConstants.ID)) {\n voAdaptationSet.id = realAdaptationSet.id;\n }\n voAdaptationSet.index = i;\n voAdaptationSet.period = voPeriod;\n\n if (getIsMuxed(realAdaptationSet)) {\n voAdaptationSet.type = Constants.MUXED;\n } else if (getIsAudio(realAdaptationSet)) {\n voAdaptationSet.type = Constants.AUDIO;\n } else if (getIsVideo(realAdaptationSet)) {\n voAdaptationSet.type = Constants.VIDEO;\n } else if (getIsText(realAdaptationSet)) {\n voAdaptationSet.type = Constants.TEXT;\n } else if (getIsImage(realAdaptationSet)) {\n voAdaptationSet.type = Constants.IMAGE;\n } else {\n logger.warn('Unknown Adaptation stream type');\n }\n voAdaptations.push(voAdaptationSet);\n }\n }\n\n return voAdaptations;\n }\n\n function getRegularPeriods(mpd) {\n const isDynamic = mpd ? getIsDynamic(mpd.manifest) : false;\n const voPeriods = [];\n let realPreviousPeriod = null;\n let realPeriod = null;\n let voPreviousPeriod = null;\n let voPeriod = null;\n let len,\n i;\n\n for (i = 0, len = mpd && mpd.manifest && mpd.manifest.Period_asArray ? mpd.manifest.Period_asArray.length : 0; i < len; i++) {\n realPeriod = mpd.manifest.Period_asArray[i];\n\n // If the attribute @start is present in the Period, then the\n // Period is a regular Period and the PeriodStart is equal\n // to the value of this attribute.\n if (realPeriod.hasOwnProperty(DashConstants.START)) {\n voPeriod = new Period();\n voPeriod.start = realPeriod.start;\n }\n // If the @start attribute is absent, but the previous Period\n // element contains a @duration attribute then then this new\n // Period is also a regular Period. The start time of the new\n // Period PeriodStart is the sum of the start time of the previous\n // Period PeriodStart and the value of the attribute @duration\n // of the previous Period.\n else if (realPreviousPeriod !== null && realPreviousPeriod.hasOwnProperty(DashConstants.DURATION) && voPreviousPeriod !== null) {\n voPeriod = new Period();\n voPeriod.start = parseFloat((voPreviousPeriod.start + voPreviousPeriod.duration).toFixed(5));\n }\n // If (i) @start attribute is absent, and (ii) the Period element\n // is the first in the MPD, and (iii) the MPD@type is 'static',\n // then the PeriodStart time shall be set to zero.\n else if (i === 0 && !isDynamic) {\n voPeriod = new Period();\n voPeriod.start = 0;\n }\n\n // The Period extends until the PeriodStart of the next Period.\n // The difference between the PeriodStart time of a Period and\n // the PeriodStart time of the following Period.\n if (voPreviousPeriod !== null && isNaN(voPreviousPeriod.duration)) {\n if (voPeriod !== null) {\n voPreviousPeriod.duration = parseFloat((voPeriod.start - voPreviousPeriod.start).toFixed(5));\n } else {\n logger.warn('First period duration could not be calculated because lack of start and duration period properties. This will cause timing issues during playback');\n }\n }\n\n if (voPeriod !== null) {\n voPeriod.id = getPeriodId(realPeriod, i);\n voPeriod.index = i;\n voPeriod.mpd = mpd;\n\n if (realPeriod.hasOwnProperty(DashConstants.DURATION)) {\n voPeriod.duration = realPeriod.duration;\n }\n\n if (voPreviousPeriod) {\n voPreviousPeriod.nextPeriodId = voPeriod.id;\n }\n\n voPeriods.push(voPeriod);\n realPreviousPeriod = realPeriod;\n voPreviousPeriod = voPeriod;\n }\n\n realPeriod = null;\n voPeriod = null;\n }\n\n if (voPeriods.length === 0) {\n return voPeriods;\n }\n\n // The last Period extends until the end of the Media Presentation.\n // The difference between the PeriodStart time of the last Period\n // and the mpd duration\n if (voPreviousPeriod !== null && isNaN(voPreviousPeriod.duration)) {\n voPreviousPeriod.duration = parseFloat((getEndTimeForLastPeriod(voPreviousPeriod) - voPreviousPeriod.start).toFixed(5));\n }\n\n return voPeriods;\n }\n\n function getPeriodId(realPeriod, i) {\n if (!realPeriod) {\n throw new Error('Period cannot be null or undefined');\n }\n\n let id = Period.DEFAULT_ID + '_' + i;\n\n if (realPeriod.hasOwnProperty(DashConstants.ID) && realPeriod.id.length > 0 && realPeriod.id !== '__proto__') {\n id = realPeriod.id;\n }\n\n return id;\n }\n\n function getMpd(manifest) {\n const mpd = new Mpd();\n\n if (manifest) {\n mpd.manifest = manifest;\n\n if (manifest.hasOwnProperty(DashConstants.AVAILABILITY_START_TIME)) {\n mpd.availabilityStartTime = new Date(manifest.availabilityStartTime.getTime());\n } else {\n if (manifest.loadedTime) {\n mpd.availabilityStartTime = new Date(manifest.loadedTime.getTime());\n }\n }\n\n if (manifest.hasOwnProperty(DashConstants.AVAILABILITY_END_TIME)) {\n mpd.availabilityEndTime = new Date(manifest.availabilityEndTime.getTime());\n }\n\n if (manifest.hasOwnProperty(DashConstants.MINIMUM_UPDATE_PERIOD)) {\n mpd.minimumUpdatePeriod = manifest.minimumUpdatePeriod;\n }\n\n if (manifest.hasOwnProperty(DashConstants.MEDIA_PRESENTATION_DURATION)) {\n mpd.mediaPresentationDuration = manifest.mediaPresentationDuration;\n }\n\n if (manifest.hasOwnProperty(DashConstants.SUGGESTED_PRESENTATION_DELAY)) {\n mpd.suggestedPresentationDelay = manifest.suggestedPresentationDelay;\n }\n\n if (manifest.hasOwnProperty(DashConstants.TIMESHIFT_BUFFER_DEPTH)) {\n mpd.timeShiftBufferDepth = manifest.timeShiftBufferDepth;\n }\n\n if (manifest.hasOwnProperty(DashConstants.MAX_SEGMENT_DURATION)) {\n mpd.maxSegmentDuration = manifest.maxSegmentDuration;\n }\n\n if (manifest.hasOwnProperty(DashConstants.PUBLISH_TIME)) {\n mpd.publishTime = new Date(manifest.publishTime);\n }\n }\n\n return mpd;\n }\n\n function checkConfig() {\n if (!errHandler || !errHandler.hasOwnProperty('error')) {\n throw new Error(Constants.MISSING_CONFIG_ERROR);\n }\n }\n\n function getEndTimeForLastPeriod(voPeriod) {\n checkConfig();\n const isDynamic = getIsDynamic(voPeriod.mpd.manifest);\n\n let periodEnd;\n if (voPeriod.mpd.manifest.mediaPresentationDuration) {\n periodEnd = voPeriod.mpd.manifest.mediaPresentationDuration;\n } else if (voPeriod.duration) {\n periodEnd = voPeriod.duration;\n } else if (isDynamic) {\n periodEnd = Number.POSITIVE_INFINITY;\n } else {\n errHandler.error(new DashJSError(Errors.MANIFEST_ERROR_ID_PARSE_CODE, 'Must have @mediaPresentationDuration on MPD or an explicit @duration on the last period.', voPeriod));\n }\n\n return periodEnd;\n }\n\n function getEventsForPeriod(period) {\n const manifest = period && period.mpd && period.mpd.manifest ? period.mpd.manifest : null;\n const periodArray = manifest ? manifest.Period_asArray : null;\n const eventStreams = periodArray && period && isInteger(period.index) ? periodArray[period.index].EventStream_asArray : null;\n const events = [];\n let i,\n j;\n\n if (eventStreams) {\n for (i = 0; i < eventStreams.length; i++) {\n const eventStream = new EventStream();\n eventStream.period = period;\n eventStream.timescale = 1;\n\n if (eventStreams[i].hasOwnProperty(Constants.SCHEME_ID_URI)) {\n eventStream.schemeIdUri = eventStreams[i][Constants.SCHEME_ID_URI];\n } else {\n throw new Error('Invalid EventStream. SchemeIdUri has to be set');\n }\n if (eventStreams[i].hasOwnProperty(DashConstants.TIMESCALE)) {\n eventStream.timescale = eventStreams[i][DashConstants.TIMESCALE];\n }\n if (eventStreams[i].hasOwnProperty(DashConstants.VALUE)) {\n eventStream.value = eventStreams[i][DashConstants.VALUE];\n }\n if (eventStreams[i].hasOwnProperty(DashConstants.PRESENTATION_TIME_OFFSET)) {\n eventStream.presentationTimeOffset = eventStreams[i][DashConstants.PRESENTATION_TIME_OFFSET];\n }\n for (j = 0; eventStreams[i].Event_asArray && j < eventStreams[i].Event_asArray.length; j++) {\n const currentMpdEvent = eventStreams[i].Event_asArray[j];\n const event = new Event();\n event.presentationTime = 0;\n event.eventStream = eventStream;\n\n if (currentMpdEvent.hasOwnProperty(DashConstants.PRESENTATION_TIME)) {\n event.presentationTime = currentMpdEvent.presentationTime;\n }\n const presentationTimeOffset = eventStream.presentationTimeOffset ? eventStream.presentationTimeOffset / eventStream.timescale : 0;\n event.calculatedPresentationTime = event.presentationTime / eventStream.timescale + period.start - presentationTimeOffset;\n\n if (currentMpdEvent.hasOwnProperty(DashConstants.DURATION)) {\n event.duration = currentMpdEvent.duration / eventStream.timescale;\n }\n if (currentMpdEvent.hasOwnProperty(DashConstants.ID)) {\n event.id = currentMpdEvent.id;\n } else {\n event.id = null;\n }\n\n if (currentMpdEvent.Signal && currentMpdEvent.Signal.Binary) {\n // toString is used to manage both regular and namespaced tags\n event.messageData = BASE64.decodeArray(currentMpdEvent.Signal.Binary.toString());\n } else {\n // From Cor.1: 'NOTE: this attribute is an alternative\n // to specifying a complete XML element(s) in the Event.\n // It is useful when an event leans itself to a compact\n // string representation'.\n event.messageData =\n currentMpdEvent.messageData ||\n currentMpdEvent.__cdata ||\n currentMpdEvent.__text;\n }\n\n events.push(event);\n }\n }\n }\n\n return events;\n }\n\n function getEventStreams(inbandStreams, representation) {\n const eventStreams = [];\n let i;\n\n if (!inbandStreams) return eventStreams;\n\n for (i = 0; i < inbandStreams.length; i++) {\n const eventStream = new EventStream();\n eventStream.timescale = 1;\n eventStream.representation = representation;\n\n if (inbandStreams[i].hasOwnProperty(Constants.SCHEME_ID_URI)) {\n eventStream.schemeIdUri = inbandStreams[i].schemeIdUri;\n } else {\n throw new Error('Invalid EventStream. SchemeIdUri has to be set');\n }\n if (inbandStreams[i].hasOwnProperty(DashConstants.TIMESCALE)) {\n eventStream.timescale = inbandStreams[i].timescale;\n }\n if (inbandStreams[i].hasOwnProperty(DashConstants.VALUE)) {\n eventStream.value = inbandStreams[i].value;\n }\n eventStreams.push(eventStream);\n }\n\n return eventStreams;\n }\n\n function getEventStreamForAdaptationSet(manifest, adaptation) {\n let inbandStreams,\n periodArray,\n adaptationArray;\n\n if (manifest && manifest.Period_asArray && adaptation && adaptation.period && isInteger(adaptation.period.index)) {\n periodArray = manifest.Period_asArray[adaptation.period.index];\n if (periodArray && periodArray.AdaptationSet_asArray && isInteger(adaptation.index)) {\n adaptationArray = periodArray.AdaptationSet_asArray[adaptation.index];\n if (adaptationArray) {\n inbandStreams = adaptationArray.InbandEventStream_asArray;\n }\n }\n }\n\n return getEventStreams(inbandStreams, null);\n }\n\n function getEventStreamForRepresentation(manifest, representation) {\n let inbandStreams,\n periodArray,\n adaptationArray,\n representationArray;\n\n if (manifest && manifest.Period_asArray && representation && representation.adaptation && representation.adaptation.period && isInteger(representation.adaptation.period.index)) {\n periodArray = manifest.Period_asArray[representation.adaptation.period.index];\n if (periodArray && periodArray.AdaptationSet_asArray && isInteger(representation.adaptation.index)) {\n adaptationArray = periodArray.AdaptationSet_asArray[representation.adaptation.index];\n if (adaptationArray && adaptationArray.Representation_asArray && isInteger(representation.index)) {\n representationArray = adaptationArray.Representation_asArray[representation.index];\n if (representationArray) {\n inbandStreams = representationArray.InbandEventStream_asArray;\n }\n }\n }\n }\n\n return getEventStreams(inbandStreams, representation);\n }\n\n function getUTCTimingSources(manifest) {\n const isDynamic = getIsDynamic(manifest);\n const hasAST = manifest ? manifest.hasOwnProperty(DashConstants.AVAILABILITY_START_TIME) : false;\n const utcTimingsArray = manifest ? manifest.UTCTiming_asArray : null;\n const utcTimingEntries = [];\n\n // do not bother synchronizing the clock unless MPD is live,\n // or it is static and has availabilityStartTime attribute\n if ((isDynamic || hasAST)) {\n if (utcTimingsArray) {\n // the order is important here - 23009-1 states that the order\n // in the manifest \"indicates relative preference, first having\n // the highest, and the last the lowest priority\".\n utcTimingsArray.forEach(function (utcTiming) {\n const entry = new UTCTiming();\n\n if (utcTiming.hasOwnProperty(Constants.SCHEME_ID_URI)) {\n entry.schemeIdUri = utcTiming.schemeIdUri;\n } else {\n // entries of type DescriptorType with no schemeIdUri\n // are meaningless. let's just ignore this entry and\n // move on.\n return;\n }\n\n // this is (incorrectly) interpreted as a number - schema\n // defines it as a string\n if (utcTiming.hasOwnProperty(DashConstants.VALUE)) {\n entry.value = utcTiming.value.toString();\n } else {\n // without a value, there's not a lot we can do with\n // this entry. let's just ignore this one and move on\n return;\n }\n\n // we're not interested in the optional id or any other\n // attributes which might be attached to the entry\n\n utcTimingEntries.push(entry);\n });\n }\n }\n\n return utcTimingEntries;\n }\n\n function getBaseURLsFromElement(node) {\n const baseUrls = [];\n // if node.BaseURL_asArray and node.baseUri are undefined entries\n // will be [undefined] which entries.some will just skip\n const entries = node.BaseURL_asArray || [node.baseUri];\n let earlyReturn = false;\n\n entries.some(entry => {\n if (entry) {\n const baseUrl = new BaseURL();\n let text = entry.__text || entry;\n\n if (urlUtils.isRelative(text)) {\n // it doesn't really make sense to have relative and\n // absolute URLs at the same level, or multiple\n // relative URLs at the same level, so assume we are\n // done from this level of the MPD\n earlyReturn = true;\n\n // deal with the specific case where the MPD@BaseURL\n // is specified and is relative. when no MPD@BaseURL\n // entries exist, that case is handled by the\n // [node.baseUri] in the entries definition.\n if (node.baseUri) {\n text = urlUtils.resolve(text, node.baseUri);\n }\n }\n\n baseUrl.url = text;\n\n // serviceLocation is optional, but we need it in order\n // to blacklist correctly. if it's not available, use\n // anything unique since there's no relationship to any\n // other BaseURL and, in theory, the url should be\n // unique so use this instead.\n if (entry.hasOwnProperty(DashConstants.SERVICE_LOCATION) &&\n entry.serviceLocation.length) {\n baseUrl.serviceLocation = entry.serviceLocation;\n } else {\n baseUrl.serviceLocation = text;\n }\n\n if (entry.hasOwnProperty(DashConstants.DVB_PRIORITY)) {\n baseUrl.dvb_priority = entry[DashConstants.DVB_PRIORITY];\n }\n\n if (entry.hasOwnProperty(DashConstants.DVB_WEIGHT)) {\n baseUrl.dvb_weight = entry[DashConstants.DVB_WEIGHT];\n }\n\n if (entry.hasOwnProperty(DashConstants.AVAILABILITY_TIME_OFFSET)) {\n baseUrl.availabilityTimeOffset = entry[DashConstants.AVAILABILITY_TIME_OFFSET];\n }\n\n if (entry.hasOwnProperty(DashConstants.AVAILABILITY_TIME_COMPLETE)) {\n baseUrl.availabilityTimeComplete = entry[DashConstants.AVAILABILITY_TIME_COMPLETE] !== 'false';\n }\n /* NOTE: byteRange currently unused\n */\n\n baseUrls.push(baseUrl);\n\n return earlyReturn;\n }\n });\n\n return baseUrls;\n }\n\n function getLocation(manifest) {\n if (manifest && manifest.hasOwnProperty(Constants.LOCATION)) {\n // for now, do not support multiple Locations -\n // just set Location to the first Location.\n manifest.Location = manifest.Location_asArray[0];\n\n return manifest.Location;\n }\n\n // may well be undefined\n return undefined;\n }\n\n function getPatchLocation(manifest) {\n if (manifest && manifest.hasOwnProperty(DashConstants.PATCH_LOCATION)) {\n // only include support for single patch location currently\n manifest.PatchLocation = manifest.PatchLocation_asArray[0];\n\n return manifest.PatchLocation;\n }\n\n // no patch location provided\n return undefined;\n }\n\n function getSuggestedPresentationDelay(mpd) {\n return mpd && mpd.hasOwnProperty(DashConstants.SUGGESTED_PRESENTATION_DELAY) ? mpd.suggestedPresentationDelay : null;\n }\n\n function getAvailabilityStartTime(mpd) {\n return mpd && mpd.hasOwnProperty(DashConstants.AVAILABILITY_START_TIME) && mpd.availabilityStartTime !== null ? mpd.availabilityStartTime.getTime() : null;\n }\n\n function getServiceDescriptions(manifest) {\n const serviceDescriptions = [];\n if (manifest && manifest.hasOwnProperty(DashConstants.SERVICE_DESCRIPTION)) {\n for (const sd of manifest.ServiceDescription_asArray) {\n // Convert each of the properties defined in\n let id, schemeIdUri, latency, playbackRate;\n for (const prop in sd) {\n if (sd.hasOwnProperty(prop)) {\n if (prop === DashConstants.ID) {\n id = sd[prop];\n } else if (prop === DashConstants.SERVICE_DESCRIPTION_SCOPE) {\n schemeIdUri = sd[prop].schemeIdUri;\n } else if (prop === DashConstants.SERVICE_DESCRIPTION_LATENCY) {\n latency = {\n target: sd[prop].target,\n max: sd[prop].max,\n min: sd[prop].min\n };\n } else if (prop === DashConstants.SERVICE_DESCRIPTION_PLAYBACK_RATE) {\n playbackRate = {\n max: sd[prop].max,\n min: sd[prop].min\n };\n }\n }\n }\n // we have a ServiceDescription for low latency. Add it if it really has parameters defined\n if (schemeIdUri === Constants.SERVICE_DESCRIPTION_LL_SCHEME && (latency || playbackRate)) {\n serviceDescriptions.push({\n id,\n schemeIdUri,\n latency,\n playbackRate\n });\n }\n }\n }\n\n return serviceDescriptions;\n }\n\n function getSupplementalProperties(adaptation) {\n const supplementalProperties = {};\n\n if (adaptation && adaptation.hasOwnProperty(DashConstants.SUPPLEMENTAL_PROPERTY)) {\n for (const sp of adaptation.SupplementalProperty_asArray) {\n if (sp.hasOwnProperty(Constants.SCHEME_ID_URI) && sp.hasOwnProperty(DashConstants.VALUE)) {\n supplementalProperties[sp[Constants.SCHEME_ID_URI]] = sp[DashConstants.VALUE];\n }\n }\n }\n return supplementalProperties;\n }\n\n function setConfig(config) {\n if (!config) return;\n\n if (config.errHandler) {\n errHandler = config.errHandler;\n }\n\n if (config.BASE64) {\n BASE64 = config.BASE64;\n }\n }\n\n instance = {\n getIsTypeOf,\n getIsText,\n getIsFragmented,\n getLanguageForAdaptation,\n getViewpointForAdaptation,\n getRolesForAdaptation,\n getAccessibilityForAdaptation,\n getAudioChannelConfigurationForAdaptation,\n getAudioChannelConfigurationForRepresentation,\n getAdaptationForIndex,\n getIndexForAdaptation,\n getAdaptationForId,\n getAdaptationsForType,\n getRealPeriods,\n getRealPeriodForIndex,\n getCodec,\n getSelectionPriority,\n getMimeType,\n getKID,\n getLabelsForAdaptation,\n getContentProtectionData,\n getIsDynamic,\n getId,\n hasProfile,\n getDuration,\n getBandwidth,\n getManifestUpdatePeriod,\n getPublishTime,\n getRepresentationCount,\n getBitrateListForAdaptation,\n getRepresentationFor,\n getRepresentationsForAdaptation,\n getAdaptationsForPeriod,\n getRegularPeriods,\n getMpd,\n getEventsForPeriod,\n getEssentialPropertiesForRepresentation,\n getEventStreamForAdaptationSet,\n getEventStreamForRepresentation,\n getUTCTimingSources,\n getBaseURLsFromElement,\n getRepresentationSortFunction,\n getLocation,\n getPatchLocation,\n getSuggestedPresentationDelay,\n getAvailabilityStartTime,\n getServiceDescriptions,\n getSupplementalProperties,\n setConfig\n };\n\n setup();\n\n return instance;\n}\n\nDashManifestModel.__dashjs_factory_name = 'DashManifestModel';\nexport default FactoryMaker.getSingletonFactory(DashManifestModel);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass ThumbnailTrackInfo {\n constructor() {\n this.bitrate = 0;\n this.width = 0;\n this.height = 0;\n this.tilesHor = 0;\n this.tilesVert = 0;\n this.widthPerTile = 0;\n this.heightPerTile = 0;\n this.startNumber = 0;\n this.segmentDuration = 0;\n this.timescale = 0;\n this.templateUrl = '';\n this.id = '';\n }\n}\n\nexport default ThumbnailTrackInfo;","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Constants from '../constants/Constants';\nimport DashConstants from '../../dash/constants/DashConstants';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport ThumbnailTrackInfo from '../vo/ThumbnailTrackInfo';\nimport URLUtils from '../../streaming/utils/URLUtils';\nimport {replaceIDForTemplate, getTimeBasedSegment} from '../../dash/utils/SegmentsUtils';\nimport BoxParser from '../../streaming/utils/BoxParser';\nimport XHRLoader from '../../streaming/net/XHRLoader';\nimport DashHandler from '../../dash/DashHandler';\nimport SegmentsController from '../../dash/controllers/SegmentsController';\n\nexport const THUMBNAILS_SCHEME_ID_URIS = ['http://dashif.org/thumbnail_tile',\n 'http://dashif.org/guidelines/thumbnail_tile'];\n\nfunction ThumbnailTracks(config) {\n const context = this.context;\n const adapter = config.adapter;\n const baseURLController = config.baseURLController;\n const streamInfo = config.streamInfo;\n const timelineConverter = config.timelineConverter;\n const debug = config.debug;\n const eventBus = config.eventBus;\n const events = config.events;\n const dashConstants = config.dashConstants;\n\n const urlUtils = URLUtils(context).getInstance();\n\n let instance,\n tracks,\n dashHandler,\n currentTrackIndex,\n mediaInfo,\n segmentsController,\n loader,\n boxParser;\n\n function setup() {\n reset();\n loader = XHRLoader(context).create({});\n boxParser = BoxParser(context).getInstance();\n\n segmentsController = SegmentsController(context).create({\n events,\n eventBus,\n streamInfo,\n timelineConverter,\n dashConstants,\n dashMetrics: config.dashMetrics,\n segmentBaseController: config.segmentBaseController,\n type: Constants.IMAGE\n });\n\n dashHandler = DashHandler(context).create({\n streamInfo,\n type: Constants.IMAGE,\n timelineConverter,\n segmentsController,\n baseURLController,\n debug,\n eventBus,\n events,\n dashConstants,\n urlUtils\n });\n\n // initialize controllers\n dashHandler.initialize(adapter ? adapter.getIsDynamic() : false);\n }\n\n function addTracks() {\n if (!streamInfo || !adapter) {\n return;\n }\n\n // Extract thumbnail tracks\n mediaInfo = adapter.getMediaInfoForType(streamInfo, Constants.IMAGE);\n if (!mediaInfo) {\n return;\n }\n\n const voReps = adapter.getVoRepresentations(mediaInfo);\n\n if (voReps && voReps.length > 0) {\n voReps.forEach((rep) => {\n if ((rep.segmentInfoType === DashConstants.SEGMENT_TEMPLATE && rep.segmentDuration > 0 && rep.media) ||\n rep.segmentInfoType === DashConstants.SEGMENT_TIMELINE) {\n _createTrack(rep);\n }\n if (rep.segmentInfoType === DashConstants.SEGMENT_BASE) {\n _createTrack(rep, true);\n }\n });\n }\n\n if (tracks.length > 0) {\n // Sort bitrates and select the lowest bitrate rendition\n tracks.sort((a, b) => a.bitrate - b.bitrate);\n }\n }\n\n function _createTrack(representation, useSegmentBase) {\n const track = new ThumbnailTrackInfo();\n track.id = representation.id;\n track.bitrate = representation.bandwidth;\n track.width = representation.width;\n track.height = representation.height;\n track.tilesHor = 1;\n track.tilesVert = 1;\n\n if (representation.essentialProperties) {\n representation.essentialProperties.forEach((p) => {\n if (THUMBNAILS_SCHEME_ID_URIS.indexOf(p.schemeIdUri) >= 0 && p.value) {\n const vars = p.value.split('x');\n if (vars.length === 2 && !isNaN(vars[0]) && !isNaN(vars[1])) {\n track.tilesHor = parseInt(vars[0], 10);\n track.tilesVert = parseInt(vars[1], 10);\n }\n }\n });\n }\n\n if (useSegmentBase) {\n segmentsController.updateSegmentData(representation)\n .then((data) => {\n _handleUpdatedSegmentData(track, representation, data);\n });\n\n } else {\n track.startNumber = representation.startNumber;\n track.segmentDuration = representation.segmentDuration;\n track.timescale = representation.timescale;\n track.templateUrl = buildTemplateUrl(representation);\n }\n\n if (track.tilesHor > 0 && track.tilesVert > 0) {\n // Precalculate width and heigth per tile for perf reasons\n track.widthPerTile = track.width / track.tilesHor;\n track.heightPerTile = track.height / track.tilesVert;\n tracks.push(track);\n }\n }\n\n function _handleUpdatedSegmentData(track, representation, data) {\n let cache = [];\n const segments = _normalizeSegments(data, representation);\n representation.segments = segments;\n track.segmentDuration = representation.segments[0].duration; //assume all segments have the same duration\n\n track.readThumbnail = function (time, callback) {\n\n let cached = null;\n cache.some(el => {\n if (el.start <= time && el.end > time) {\n cached = el.url;\n return true;\n }\n });\n if (cached) {\n callback(cached);\n } else {\n representation.segments.some((ss) => {\n if (ss.mediaStartTime <= time && ss.mediaStartTime + ss.duration > time) {\n const baseURL = baseURLController.resolve(representation.path);\n loader.load({\n method: 'get',\n url: baseURL.url,\n request: {\n range: ss.mediaRange,\n responseType: 'arraybuffer'\n },\n onload: function (e) {\n let info = boxParser.getSamplesInfo(e.target.response);\n let blob = new Blob([e.target.response.slice(info.sampleList[0].offset, info.sampleList[0].offset + info.sampleList[0].size)], { type: 'image/jpeg' });\n let imageUrl = window.URL.createObjectURL(blob);\n cache.push({\n start: ss.mediaStartTime,\n end: ss.mediaStartTime + ss.duration,\n url: imageUrl\n });\n if (callback)\n callback(imageUrl);\n }\n });\n return true;\n }\n });\n }\n };\n }\n\n function _normalizeSegments(data, representation) {\n const segments = [];\n let count = 0;\n\n let i,\n len,\n s,\n seg;\n\n for (i = 0, len = data.segments.length; i < len; i++) {\n s = data.segments[i];\n\n seg = getTimeBasedSegment(\n timelineConverter,\n adapter.getIsDynamic(),\n representation,\n s.startTime,\n s.duration,\n s.timescale,\n s.media,\n s.mediaRange,\n count);\n\n if (seg) {\n segments.push(seg);\n seg = null;\n count++;\n }\n }\n return segments;\n }\n\n function buildTemplateUrl(representation) {\n const templateUrl = urlUtils.isRelative(representation.media) ?\n urlUtils.resolve(representation.media, baseURLController.resolve(representation.path).url) : representation.media;\n\n if (!templateUrl) {\n return '';\n }\n\n return replaceIDForTemplate(templateUrl, representation.id);\n }\n\n function getTracks() {\n return tracks;\n }\n\n function getCurrentTrackIndex() {\n return currentTrackIndex;\n }\n\n function getCurrentTrack() {\n if (currentTrackIndex < 0) {\n return null;\n }\n return tracks[currentTrackIndex];\n }\n\n function setTrackByIndex(index) {\n if (!tracks || tracks.length === 0) {\n return;\n }\n // select highest bitrate in case selected index is higher than bitrate list length\n if (index >= tracks.length) {\n index = tracks.length - 1;\n }\n currentTrackIndex = index;\n }\n\n function getThumbnailRequestForTime(time) {\n let currentVoRep;\n const voReps = adapter.getVoRepresentations(mediaInfo);\n for (let i = 0; i < voReps.length; i++) {\n if (tracks[currentTrackIndex].id === voReps[i].id) {\n currentVoRep = voReps[i];\n break;\n }\n }\n\n return dashHandler.getSegmentRequestForTime(mediaInfo, currentVoRep, time);\n }\n\n function reset() {\n tracks = [];\n currentTrackIndex = -1;\n mediaInfo = null;\n }\n\n instance = {\n getTracks,\n addTracks,\n reset,\n setTrackByIndex,\n getCurrentTrack,\n getCurrentTrackIndex,\n getThumbnailRequestForTime\n };\n\n setup();\n\n return instance;\n}\n\nThumbnailTracks.__dashjs_factory_name = 'ThumbnailTracks';\nexport default FactoryMaker.getClassFactory(ThumbnailTracks);\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n\n'use strict';\n\n/*<replacement>*/\n\nvar pna = require('process-nextick-args');\n/*</replacement>*/\n\n/*<replacement>*/\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) {\n keys.push(key);\n }return keys;\n};\n/*</replacement>*/\n\nmodule.exports = Duplex;\n\n/*<replacement>*/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/*</replacement>*/\n\nvar Readable = require('./_stream_readable');\nvar Writable = require('./_stream_writable');\n\nutil.inherits(Duplex, Readable);\n\n{\n // avoid scope creep, the keys array can then be collected\n var keys = objectKeys(Writable.prototype);\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n\n Readable.call(this, options);\n Writable.call(this, options);\n\n if (options && options.readable === false) this.readable = false;\n\n if (options && options.writable === false) this.writable = false;\n\n this.allowHalfOpen = true;\n if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;\n\n this.once('end', onend);\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// the no-half-open enforcer\nfunction onend() {\n // if we allow half-open state, or if the writable side ended,\n // then we're ok.\n if (this.allowHalfOpen || this._writableState.ended) return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n pna.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});\n\nDuplex.prototype._destroy = function (err, cb) {\n this.push(null);\n this.end();\n\n pna.nextTick(cb, err);\n};","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport FragmentRequest from '../streaming/vo/FragmentRequest';\nimport {HTTPRequest} from '../streaming/vo/metrics/HTTPRequest';\nimport FactoryMaker from '../core/FactoryMaker';\nimport MediaPlayerEvents from '../streaming/MediaPlayerEvents';\nimport {\n replaceIDForTemplate,\n replaceTokenForTemplate,\n unescapeDollarsInTemplate\n} from './utils/SegmentsUtils';\nimport DashConstants from './constants/DashConstants';\n\n\nconst DEFAULT_ADJUST_SEEK_TIME_THRESHOLD = 0.5;\n\n\nfunction DashHandler(config) {\n\n config = config || {};\n\n const eventBus = config.eventBus;\n const debug = config.debug;\n const urlUtils = config.urlUtils;\n const type = config.type;\n const streamInfo = config.streamInfo;\n const segmentsController = config.segmentsController;\n const timelineConverter = config.timelineConverter;\n const baseURLController = config.baseURLController;\n\n let instance,\n logger,\n lastSegment,\n isDynamicManifest,\n mediaHasFinished;\n\n function setup() {\n logger = debug.getLogger(instance);\n resetInitialSettings();\n\n eventBus.on(MediaPlayerEvents.DYNAMIC_TO_STATIC, _onDynamicToStatic, instance);\n }\n\n function initialize(isDynamic) {\n isDynamicManifest = isDynamic;\n mediaHasFinished = false;\n segmentsController.initialize(isDynamic);\n }\n\n function getStreamId() {\n return streamInfo.id;\n }\n\n function getType() {\n return type;\n }\n\n function getStreamInfo() {\n return streamInfo;\n }\n\n function resetInitialSettings() {\n lastSegment = null;\n }\n\n function reset() {\n resetInitialSettings();\n eventBus.off(MediaPlayerEvents.DYNAMIC_TO_STATIC, _onDynamicToStatic, instance);\n }\n\n function _setRequestUrl(request, destination, representation) {\n const baseURL = baseURLController.resolve(representation.path);\n let url,\n serviceLocation;\n\n if (!baseURL || (destination === baseURL.url) || (!urlUtils.isRelative(destination))) {\n url = destination;\n } else {\n url = baseURL.url;\n serviceLocation = baseURL.serviceLocation;\n\n if (destination) {\n url = urlUtils.resolve(destination, url);\n }\n }\n\n if (urlUtils.isRelative(url)) {\n return false;\n }\n\n request.url = url;\n request.serviceLocation = serviceLocation;\n\n return true;\n }\n\n function getInitRequest(mediaInfo, representation) {\n if (!representation) return null;\n return _generateInitRequest(mediaInfo, representation, getType());\n }\n\n function _generateInitRequest(mediaInfo, representation, mediaType) {\n const request = new FragmentRequest();\n const period = representation.adaptation.period;\n const presentationStartTime = period.start;\n\n request.mediaType = mediaType;\n request.type = HTTPRequest.INIT_SEGMENT_TYPE;\n request.range = representation.range;\n request.availabilityStartTime = timelineConverter.calcAvailabilityStartTimeFromPresentationTime(presentationStartTime, representation, isDynamicManifest);\n request.availabilityEndTime = timelineConverter.calcAvailabilityEndTimeFromPresentationTime(presentationStartTime + period.duration, representation, isDynamicManifest);\n request.quality = representation.index;\n request.mediaInfo = mediaInfo;\n request.representationId = representation.id;\n\n if (_setRequestUrl(request, representation.initialization, representation)) {\n request.url = replaceTokenForTemplate(request.url, 'Bandwidth', representation.bandwidth);\n return request;\n }\n }\n\n function _getRequestForSegment(mediaInfo, segment) {\n if (segment === null || segment === undefined) {\n return null;\n }\n\n const request = new FragmentRequest();\n const representation = segment.representation;\n const bandwidth = representation.adaptation.period.mpd.manifest.Period_asArray[representation.adaptation.period.index].AdaptationSet_asArray[representation.adaptation.index].Representation_asArray[representation.index].bandwidth;\n let url = segment.media;\n\n url = replaceTokenForTemplate(url, 'Number', segment.replacementNumber);\n url = replaceTokenForTemplate(url, 'Time', segment.replacementTime);\n url = replaceTokenForTemplate(url, 'Bandwidth', bandwidth);\n url = replaceIDForTemplate(url, representation.id);\n url = unescapeDollarsInTemplate(url);\n\n request.mediaType = getType();\n request.type = HTTPRequest.MEDIA_SEGMENT_TYPE;\n request.range = segment.mediaRange;\n request.startTime = segment.presentationStartTime;\n request.mediaStartTime = segment.mediaStartTime;\n request.duration = segment.duration;\n request.timescale = representation.timescale;\n request.availabilityStartTime = segment.availabilityStartTime;\n request.availabilityEndTime = segment.availabilityEndTime;\n request.wallStartTime = segment.wallStartTime;\n request.quality = representation.index;\n request.index = segment.index;\n request.mediaInfo = mediaInfo;\n request.adaptationIndex = representation.adaptation.index;\n request.representationId = representation.id;\n\n if (_setRequestUrl(request, url, representation)) {\n return request;\n }\n }\n\n function isLastSegmentRequested(representation, bufferingTime) {\n if (!representation || !lastSegment) {\n return false;\n }\n\n // Either transition from dynamic to static was done or no next static segment found\n if (mediaHasFinished) {\n return true;\n }\n\n // Period is endless\n if (!isFinite(representation.adaptation.period.duration)) {\n return false;\n }\n\n // we are replacing existing stuff in the buffer for instance after a track switch\n if (lastSegment.presentationStartTime + lastSegment.duration > bufferingTime) {\n return false;\n }\n\n // Additional segment references may be added to the last period.\n // Additional periods may be added to the end of the MPD.\n // Segment references SHALL NOT be added to any period other than the last period.\n // An MPD update MAY combine adding segment references to the last period with adding of new periods. An MPD update that adds content MAY be combined with an MPD update that removes content.\n // The index of the last requested segment is higher than the number of available segments.\n // For SegmentTimeline and SegmentTemplate the index does not include the startNumber.\n // For SegmentList the index includes the startnumber which is why the numberOfSegments includes this as well\n if (representation.mediaFinishedInformation && !isNaN(representation.mediaFinishedInformation.numberOfSegments) && !isNaN(lastSegment.index) && lastSegment.index >= (representation.mediaFinishedInformation.numberOfSegments - 1)) {\n // For static manifests and Template addressing we can compare the index against the number of available segments\n if (!isDynamicManifest || representation.segmentInfoType === DashConstants.SEGMENT_TEMPLATE) {\n return true;\n }\n // For SegmentList we need to check if the next period is signaled\n else if (isDynamicManifest && representation.segmentInfoType === DashConstants.SEGMENT_LIST && representation.adaptation.period.nextPeriodId) {\n return true\n }\n }\n\n // For dynamic SegmentTimeline manifests we need to check if the next period is already signaled and the segment we fetched before is the last one that is signaled.\n // We can not simply use the index, as numberOfSegments might have decreased after an MPD update\n return !!(isDynamicManifest && representation.adaptation.period.nextPeriodId && representation.segmentInfoType === DashConstants.SEGMENT_TIMELINE && representation.mediaFinishedInformation &&\n !isNaN(representation.mediaFinishedInformation.mediaTimeOfLastSignaledSegment) && lastSegment && !isNaN(lastSegment.mediaStartTime) && !isNaN(lastSegment.duration) && lastSegment.mediaStartTime + lastSegment.duration >= (representation.mediaFinishedInformation.mediaTimeOfLastSignaledSegment - 0.05));\n }\n\n\n function getSegmentRequestForTime(mediaInfo, representation, time) {\n let request = null;\n\n if (!representation || !representation.segmentInfoType) {\n return request;\n }\n\n const segment = segmentsController.getSegmentByTime(representation, time);\n if (segment) {\n lastSegment = segment;\n logger.debug('Index for time ' + time + ' is ' + segment.index);\n request = _getRequestForSegment(mediaInfo, segment);\n }\n\n return request;\n }\n\n /**\n * This function returns the next segment request without modifying any internal variables. Any class (e.g CMCD Model) that needs information about the upcoming request should use this method.\n * @param {object} mediaInfo\n * @param {object} representation\n * @return {FragmentRequest|null}\n */\n function getNextSegmentRequestIdempotent(mediaInfo, representation) {\n let request = null;\n let indexToRequest = lastSegment ? lastSegment.index + 1 : 0;\n const segment = segmentsController.getSegmentByIndex(\n representation,\n indexToRequest,\n lastSegment ? lastSegment.mediaStartTime : -1\n );\n if (!segment) return null;\n request = _getRequestForSegment(mediaInfo, segment);\n return request;\n }\n\n /**\n * Main function to get the next segment request.\n * @param {object} mediaInfo\n * @param {object} representation\n * @return {FragmentRequest|null}\n */\n function getNextSegmentRequest(mediaInfo, representation) {\n let request = null;\n\n if (!representation || !representation.segmentInfoType) {\n return null;\n }\n\n let indexToRequest = lastSegment ? lastSegment.index + 1 : 0;\n\n const segment = segmentsController.getSegmentByIndex(representation, indexToRequest, lastSegment ? lastSegment.mediaStartTime : -1);\n\n // No segment found\n if (!segment) {\n // Dynamic manifest there might be something available in the next iteration\n if (isDynamicManifest && !mediaHasFinished) {\n logger.debug(getType() + ' No segment found at index: ' + indexToRequest + '. Wait for next loop');\n return null;\n } else {\n mediaHasFinished = true;\n }\n } else {\n request = _getRequestForSegment(mediaInfo, segment);\n lastSegment = segment;\n }\n\n return request;\n }\n\n /**\n * This function returns a time for which we can generate a request. It is supposed to be as close as possible to the target time.\n * This is useful in scenarios in which the user seeks into a gap. We will not find a valid request then and need to adjust the seektime.\n * @param {number} time\n * @param {object} mediaInfo\n * @param {object} representation\n * @param {number} targetThreshold\n */\n function getValidSeekTimeCloseToTargetTime(time, mediaInfo, representation, targetThreshold) {\n try {\n\n if (isNaN(time) || !mediaInfo || !representation) {\n return NaN;\n }\n\n if (time < 0) {\n time = 0;\n }\n\n if (isNaN(targetThreshold)) {\n targetThreshold = DEFAULT_ADJUST_SEEK_TIME_THRESHOLD;\n }\n\n if (getSegmentRequestForTime(mediaInfo, representation, time)) {\n return time;\n }\n\n const start = representation.adaptation.period.start;\n const end = representation.adaptation.period.start + representation.adaptation.period.duration;\n let currentUpperTime = Math.min(time + targetThreshold, end);\n let currentLowerTime = Math.max(time - targetThreshold, start);\n let adjustedTime = NaN;\n let targetRequest = null;\n\n while (currentUpperTime <= end || currentLowerTime >= start) {\n let upperRequest = null;\n let lowerRequest = null;\n if (currentUpperTime <= end) {\n upperRequest = getSegmentRequestForTime(mediaInfo, representation, currentUpperTime);\n }\n if (currentLowerTime >= start) {\n lowerRequest = getSegmentRequestForTime(mediaInfo, representation, currentLowerTime);\n }\n\n if (lowerRequest) {\n adjustedTime = currentLowerTime;\n targetRequest = lowerRequest;\n break;\n } else if (upperRequest) {\n adjustedTime = currentUpperTime;\n targetRequest = upperRequest;\n break;\n }\n\n currentUpperTime += targetThreshold;\n currentLowerTime -= targetThreshold;\n }\n\n if (targetRequest) {\n const requestEndTime = targetRequest.startTime + targetRequest.duration;\n\n // Keep the original start time in case it is covered by a segment\n if (time >= targetRequest.startTime && requestEndTime - time > targetThreshold) {\n return time;\n }\n\n // If target time is before the start of the request use request starttime\n if (time < targetRequest.startTime) {\n return targetRequest.startTime;\n }\n\n return Math.min(requestEndTime - targetThreshold, adjustedTime);\n }\n\n return adjustedTime;\n\n\n } catch (e) {\n return NaN;\n }\n }\n\n function getCurrentIndex() {\n return lastSegment ? lastSegment.index : -1;\n }\n\n function _onDynamicToStatic() {\n logger.debug('Dynamic stream complete');\n mediaHasFinished = true;\n }\n\n instance = {\n initialize,\n getStreamId,\n getType,\n getStreamInfo,\n getInitRequest,\n getSegmentRequestForTime,\n getCurrentIndex,\n getNextSegmentRequest,\n isLastSegmentRequested,\n reset,\n getNextSegmentRequestIdempotent,\n getValidSeekTimeCloseToTargetTime\n };\n\n setup();\n\n return instance;\n}\n\nDashHandler.__dashjs_factory_name = 'DashHandler';\nexport default FactoryMaker.getClassFactory(DashHandler);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Constants from '../../streaming/constants/Constants';\n\nimport {getTimeBasedSegment} from './SegmentsUtils';\n\nfunction TimelineSegmentsGetter(config, isDynamic) {\n\n config = config || {};\n const timelineConverter = config.timelineConverter;\n const dashMetrics = config.dashMetrics;\n\n let instance;\n\n function checkConfig() {\n if (!timelineConverter) {\n throw new Error(Constants.MISSING_CONFIG_ERROR);\n }\n }\n\n function getMediaFinishedInformation(representation) {\n if (!representation) {\n return 0;\n }\n\n const base = representation.adaptation.period.mpd.manifest.Period_asArray[representation.adaptation.period.index].AdaptationSet_asArray[representation.adaptation.index].Representation_asArray[representation.index].SegmentTemplate ||\n representation.adaptation.period.mpd.manifest.Period_asArray[representation.adaptation.period.index].AdaptationSet_asArray[representation.adaptation.index].Representation_asArray[representation.index].SegmentList;\n const timeline = base.SegmentTimeline;\n\n let time = 0;\n let scaledTime = 0;\n let availableSegments = 0;\n\n let fragments,\n frag,\n i,\n len,\n j,\n repeat,\n fTimescale;\n\n fTimescale = representation.timescale;\n fragments = timeline.S_asArray;\n\n len = fragments.length;\n\n for (i = 0; i < len; i++) {\n frag = fragments[i];\n repeat = 0;\n if (frag.hasOwnProperty('r')) {\n repeat = frag.r;\n }\n\n // For a repeated S element, t belongs only to the first segment\n if (frag.hasOwnProperty('t')) {\n time = frag.t;\n scaledTime = time / fTimescale;\n }\n\n // This is a special case: \"A negative value of the @r attribute of the S element indicates that the duration indicated in @d attribute repeats until the start of the next S element, the end of the Period or until the\n // next MPD update.\"\n if (repeat < 0) {\n const nextFrag = fragments[i + 1];\n repeat = _calculateRepeatCountForNegativeR(representation, nextFrag, frag, fTimescale, scaledTime);\n }\n\n for (j = 0; j <= repeat; j++) {\n availableSegments++;\n\n time += frag.d;\n scaledTime = time / fTimescale;\n }\n }\n\n // We need to account for the index of the segments starting at 0. We subtract 1\n return { numberOfSegments: availableSegments, mediaTimeOfLastSignaledSegment: scaledTime };\n }\n\n function iterateSegments(representation, iterFunc) {\n const base = representation.adaptation.period.mpd.manifest.Period_asArray[representation.adaptation.period.index].AdaptationSet_asArray[representation.adaptation.index].Representation_asArray[representation.index].SegmentTemplate ||\n representation.adaptation.period.mpd.manifest.Period_asArray[representation.adaptation.period.index].AdaptationSet_asArray[representation.adaptation.index].Representation_asArray[representation.index].SegmentList;\n const timeline = base.SegmentTimeline;\n const list = base.SegmentURL_asArray;\n\n let time = 0;\n let scaledTime = 0;\n let relativeIdx = -1;\n\n let fragments,\n frag,\n i,\n len,\n j,\n repeat,\n fTimescale;\n\n fTimescale = representation.timescale;\n fragments = timeline.S_asArray;\n\n let breakIterator = false;\n\n for (i = 0, len = fragments.length; i < len && !breakIterator; i++) {\n frag = fragments[i];\n repeat = 0;\n if (frag.hasOwnProperty('r')) {\n repeat = frag.r;\n }\n\n // For a repeated S element, t belongs only to the first segment\n if (frag.hasOwnProperty('t')) {\n time = frag.t;\n scaledTime = time / fTimescale;\n }\n\n // This is a special case: \"A negative value of the @r attribute of the S element indicates that the duration indicated in @d attribute repeats until the start of the next S element, the end of the Period or until the\n // next MPD update.\"\n if (repeat < 0) {\n const nextFrag = fragments[i + 1];\n repeat = _calculateRepeatCountForNegativeR(representation, nextFrag, frag, fTimescale, scaledTime);\n }\n\n for (j = 0; j <= repeat && !breakIterator; j++) {\n relativeIdx++;\n\n breakIterator = iterFunc(time, scaledTime, base, list, frag, fTimescale, relativeIdx, i);\n\n if (breakIterator) {\n representation.segmentDuration = frag.d / fTimescale;\n }\n\n time += frag.d;\n scaledTime = time / fTimescale;\n }\n }\n }\n\n function _calculateRepeatCountForNegativeR(representation, nextFrag, frag, fTimescale, scaledTime) {\n let repeatEndTime;\n\n if (nextFrag && nextFrag.hasOwnProperty('t')) {\n repeatEndTime = nextFrag.t / fTimescale;\n } else {\n try {\n let availabilityEnd = 0;\n if (!isNaN(representation.adaptation.period.start) && !isNaN(representation.adaptation.period.duration) && isFinite(representation.adaptation.period.duration)) {\n // use end of the Period\n availabilityEnd = representation.adaptation.period.start + representation.adaptation.period.duration;\n } else {\n // use DVR window\n const dvrWindow = dashMetrics.getCurrentDVRInfo();\n availabilityEnd = !isNaN(dvrWindow.end) ? dvrWindow.end : 0;\n }\n repeatEndTime = timelineConverter.calcMediaTimeFromPresentationTime(availabilityEnd, representation);\n representation.segmentDuration = frag.d / fTimescale;\n } catch (e) {\n repeatEndTime = 0;\n }\n }\n\n return Math.max(Math.ceil((repeatEndTime - scaledTime) / (frag.d / fTimescale)) - 1, 0);\n }\n\n\n function getSegmentByIndex(representation, index, lastSegmentTime) {\n checkConfig();\n\n if (!representation) {\n return null;\n }\n\n let segment = null;\n let found = false;\n\n iterateSegments(representation, function (time, scaledTime, base, list, frag, fTimescale, relativeIdx, i) {\n if (found || lastSegmentTime < 0) {\n let media = base.media;\n let mediaRange = frag.mediaRange;\n\n if (list) {\n media = list[i].media || '';\n mediaRange = list[i].mediaRange;\n }\n\n segment = getTimeBasedSegment(\n timelineConverter,\n isDynamic,\n representation,\n time,\n frag.d,\n fTimescale,\n media,\n mediaRange,\n relativeIdx,\n frag.tManifest);\n\n return true;\n } else if (scaledTime >= lastSegmentTime - frag.d * 0.5 / fTimescale) { // same logic, if deviation is\n // 50% of segment duration, segment is found if scaledTime is greater than or equal to (startTime of previous segment - half of the previous segment duration)\n found = true;\n }\n\n return false;\n });\n\n return segment;\n }\n\n function getSegmentByTime(representation, requestedTime) {\n checkConfig();\n\n if (!representation) {\n return null;\n }\n\n if (requestedTime === undefined) {\n requestedTime = null;\n }\n\n let segment = null;\n const requiredMediaTime = timelineConverter.calcMediaTimeFromPresentationTime(requestedTime, representation);\n\n iterateSegments(representation, function (time, scaledTime, base, list, frag, fTimescale, relativeIdx, i) {\n // In some cases when requiredMediaTime = actual end time of the last segment\n // it is possible that this time a bit exceeds the declared end time of the last segment.\n // in this case we still need to include the last segment in the segment list.\n if ((requiredMediaTime < (scaledTime + (frag.d / fTimescale))) && requiredMediaTime >= scaledTime) {\n let media = base.media;\n let mediaRange = frag.mediaRange;\n\n if (list) {\n media = list[i].media || '';\n mediaRange = list[i].mediaRange;\n }\n\n segment = getTimeBasedSegment(\n timelineConverter,\n isDynamic,\n representation,\n time,\n frag.d,\n fTimescale,\n media,\n mediaRange,\n relativeIdx,\n frag.tManifest);\n\n return true;\n }\n\n return false;\n });\n\n return segment;\n }\n\n\n instance = {\n getSegmentByIndex,\n getSegmentByTime,\n getMediaFinishedInformation\n };\n\n return instance;\n}\n\nTimelineSegmentsGetter.__dashjs_factory_name = 'TimelineSegmentsGetter';\nconst factory = FactoryMaker.getClassFactory(TimelineSegmentsGetter);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Constants from '../../streaming/constants/Constants';\n\nimport {replaceTokenForTemplate, getIndexBasedSegment} from './SegmentsUtils';\n\nfunction TemplateSegmentsGetter(config, isDynamic) {\n config = config || {};\n const timelineConverter = config.timelineConverter;\n\n let instance;\n\n function checkConfig() {\n if (!timelineConverter || !timelineConverter.hasOwnProperty('calcPeriodRelativeTimeFromMpdRelativeTime')) {\n throw new Error(Constants.MISSING_CONFIG_ERROR);\n }\n }\n\n function getMediaFinishedInformation(representation) {\n const mediaFinishedInformation = { numberOfSegments: 0, mediaTimeOfLastSignaledSegment: NaN }\n if (!representation) {\n return mediaFinishedInformation\n }\n\n const duration = representation.segmentDuration;\n if (isNaN(duration)) {\n mediaFinishedInformation.numberOfSegments = 1;\n } else {\n mediaFinishedInformation.numberOfSegments = Math.ceil(representation.adaptation.period.duration / duration);\n }\n\n return mediaFinishedInformation;\n }\n\n function getSegmentByIndex(representation, index) {\n checkConfig();\n\n if (!representation) {\n return null;\n }\n\n const template = representation.adaptation.period.mpd.manifest.Period_asArray[representation.adaptation.period.index].AdaptationSet_asArray[representation.adaptation.index].Representation_asArray[representation.index].SegmentTemplate;\n\n // This is the index without @startNumber\n index = Math.max(index, 0);\n\n const seg = getIndexBasedSegment(timelineConverter, isDynamic, representation, index);\n if (seg) {\n seg.replacementTime = Math.round((index - 1) * representation.segmentDuration * representation.timescale, 10);\n\n let url = template.media;\n url = replaceTokenForTemplate(url, 'Number', seg.replacementNumber);\n url = replaceTokenForTemplate(url, 'Time', seg.replacementTime);\n seg.media = url;\n }\n\n return seg;\n }\n\n function getSegmentByTime(representation, requestedTime) {\n checkConfig();\n\n if (!representation) {\n return null;\n }\n\n const duration = representation.segmentDuration;\n\n if (isNaN(duration)) {\n return null;\n }\n\n // Calculate the relative time for the requested time in this period\n let periodTime = timelineConverter.calcPeriodRelativeTimeFromMpdRelativeTime(representation, requestedTime);\n const index = Math.floor(periodTime / duration);\n\n return getSegmentByIndex(representation, index);\n }\n\n instance = {\n getSegmentByIndex,\n getSegmentByTime,\n getMediaFinishedInformation\n };\n\n return instance;\n}\n\nTemplateSegmentsGetter.__dashjs_factory_name = 'TemplateSegmentsGetter';\nconst factory = FactoryMaker.getClassFactory(TemplateSegmentsGetter);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Constants from '../../streaming/constants/Constants';\n\nimport {getIndexBasedSegment} from './SegmentsUtils';\n\nfunction ListSegmentsGetter(config, isDynamic) {\n\n config = config || {};\n const timelineConverter = config.timelineConverter;\n\n let instance;\n\n function checkConfig() {\n if (!timelineConverter || !timelineConverter.hasOwnProperty('calcPeriodRelativeTimeFromMpdRelativeTime')) {\n throw new Error(Constants.MISSING_CONFIG_ERROR);\n }\n }\n\n function getMediaFinishedInformation(representation) {\n const mediaFinishedInformation = { numberOfSegments: 0, mediaTimeOfLastSignaledSegment: NaN }\n\n if (!representation) {\n return mediaFinishedInformation;\n }\n\n const list = representation.adaptation.period.mpd.manifest.Period_asArray[representation.adaptation.period.index].AdaptationSet_asArray[representation.adaptation.index].Representation_asArray[representation.index].SegmentList;\n const startNumber = representation && !isNaN(representation.startNumber) ? representation.startNumber : 1;\n const offset = Math.max(startNumber - 1, 0);\n\n mediaFinishedInformation.numberOfSegments = offset + list.SegmentURL_asArray.length;\n\n return mediaFinishedInformation\n }\n\n function getSegmentByIndex(representation, index) {\n checkConfig();\n\n if (!representation) {\n return null;\n }\n\n const list = representation.adaptation.period.mpd.manifest.Period_asArray[representation.adaptation.period.index].AdaptationSet_asArray[representation.adaptation.index].Representation_asArray[representation.index].SegmentList;\n const len = list.SegmentURL_asArray.length;\n\n const startNumber = representation && !isNaN(representation.startNumber) ? representation.startNumber : 1;\n const offsetToSubtract = Math.max(startNumber - 1, 0);\n\n const relativeIndex = Math.max(index - offsetToSubtract, 0);\n\n let segment = null;\n if (relativeIndex < len) {\n const s = list.SegmentURL_asArray[relativeIndex];\n\n segment = getIndexBasedSegment(timelineConverter, isDynamic, representation, index);\n if (segment) {\n segment.replacementTime = (startNumber + index - 1) * representation.segmentDuration;\n segment.media = s.media ? s.media : '';\n segment.mediaRange = s.mediaRange;\n segment.indexRange = s.indexRange;\n }\n }\n\n return segment;\n }\n\n function getSegmentByTime(representation, requestedTime) {\n checkConfig();\n\n if (!representation) {\n return null;\n }\n\n const duration = representation.segmentDuration;\n\n if (isNaN(duration)) {\n return null;\n }\n\n const periodTime = timelineConverter.calcPeriodRelativeTimeFromMpdRelativeTime(representation, requestedTime);\n const index = Math.floor(periodTime / duration);\n\n return getSegmentByIndex(representation, index);\n }\n\n instance = {\n getSegmentByIndex,\n getSegmentByTime,\n getMediaFinishedInformation\n };\n\n return instance;\n}\n\nListSegmentsGetter.__dashjs_factory_name = 'ListSegmentsGetter';\nconst factory = FactoryMaker.getClassFactory(ListSegmentsGetter);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Constants from '../../streaming/constants/Constants';\n\n\nfunction SegmentBaseGetter(config) {\n\n config = config || {};\n const timelineConverter = config.timelineConverter;\n\n let instance;\n\n function checkConfig() {\n if (!timelineConverter || !timelineConverter.hasOwnProperty('calcPeriodRelativeTimeFromMpdRelativeTime')) {\n throw new Error(Constants.MISSING_CONFIG_ERROR);\n }\n }\n\n function getMediaFinishedInformation(representation) {\n const mediaFinishedInformation = { numberOfSegments: 0, mediaTimeOfLastSignaledSegment: NaN }\n\n if (!representation || !representation.segments) {\n return mediaFinishedInformation\n }\n\n mediaFinishedInformation.numberOfSegments = representation.segments.length;\n\n return mediaFinishedInformation;\n }\n\n function getSegmentByIndex(representation, index) {\n checkConfig();\n\n if (!representation) {\n return null;\n }\n\n const len = representation.segments ? representation.segments.length : -1;\n let seg;\n if (index < len) {\n seg = representation.segments[index];\n if (seg && seg.index === index) {\n return seg;\n }\n }\n\n for (let i = 0; i < len; i++) {\n seg = representation.segments[i];\n\n if (seg && seg.index === index) {\n return seg;\n }\n }\n\n return null;\n }\n\n function getSegmentByTime(representation, requestedTime) {\n checkConfig();\n\n const index = getIndexByTime(representation, requestedTime);\n\n return getSegmentByIndex(representation, index);\n }\n\n function getIndexByTime(representation, time) {\n if (!representation) {\n return -1;\n }\n\n const segments = representation.segments;\n const ln = segments ? segments.length : null;\n\n let idx = -1;\n let epsilon,\n seg,\n ft,\n fd,\n i;\n\n if (segments && ln > 0) {\n for (i = 0; i < ln; i++) {\n seg = segments[i];\n ft = seg.presentationStartTime;\n fd = seg.duration;\n\n epsilon = fd / 2;\n if ((time + epsilon) >= ft &&\n (time - epsilon) < (ft + fd)) {\n idx = seg.index;\n break;\n }\n }\n }\n\n return idx;\n }\n\n instance = {\n getSegmentByIndex,\n getSegmentByTime,\n getMediaFinishedInformation\n };\n\n return instance;\n}\n\nSegmentBaseGetter.__dashjs_factory_name = 'SegmentBaseGetter';\nconst factory = FactoryMaker.getClassFactory(SegmentBaseGetter);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport FactoryMaker from '../../core/FactoryMaker';\nimport TimelineSegmentsGetter from '../utils/TimelineSegmentsGetter';\nimport TemplateSegmentsGetter from '../utils/TemplateSegmentsGetter';\nimport ListSegmentsGetter from '../utils/ListSegmentsGetter';\nimport SegmentBaseGetter from '../utils/SegmentBaseGetter';\n\nfunction SegmentsController(config) {\n config = config || {};\n\n const context = this.context;\n const dashConstants = config.dashConstants;\n const type = config.type;\n const segmentBaseController = config.segmentBaseController;\n\n let instance,\n getters;\n\n function setup() {\n getters = {};\n }\n\n function initialize(isDynamic) {\n getters[dashConstants.SEGMENT_TIMELINE] = TimelineSegmentsGetter(context).create(config, isDynamic);\n getters[dashConstants.SEGMENT_TEMPLATE] = TemplateSegmentsGetter(context).create(config, isDynamic);\n getters[dashConstants.SEGMENT_LIST] = ListSegmentsGetter(context).create(config, isDynamic);\n getters[dashConstants.SEGMENT_BASE] = SegmentBaseGetter(context).create(config, isDynamic);\n }\n\n function updateInitData(voRepresentation, hasInitialization) {\n if (hasInitialization) {\n return Promise.resolve();\n }\n return segmentBaseController.getSegmentBaseInitSegment({\n representation: voRepresentation,\n mediaType: type\n });\n }\n\n function updateSegmentData(voRepresentation, hasSegments) {\n if (hasSegments) {\n return Promise.resolve();\n }\n return segmentBaseController.getSegmentList({\n mimeType: voRepresentation.mimeType,\n representation: voRepresentation,\n mediaType: type\n });\n }\n\n function getSegmentsGetter(representation) {\n return representation ? representation.segments ? getters[dashConstants.SEGMENT_BASE] : getters[representation.segmentInfoType] : null;\n }\n\n function getSegmentByIndex(representation, index, lastSegmentTime) {\n const getter = getSegmentsGetter(representation);\n return getter ? getter.getSegmentByIndex(representation, index, lastSegmentTime) : null;\n }\n\n function getSegmentByTime(representation, time) {\n const getter = getSegmentsGetter(representation);\n return getter ? getter.getSegmentByTime(representation, time) : null;\n }\n\n function getMediaFinishedInformation(representation) {\n const getter = getSegmentsGetter(representation);\n return getter ? getter.getMediaFinishedInformation(representation) : {\n numberOfSegments: 0,\n mediaTimeOfLastSignaledSegment: NaN\n };\n }\n\n instance = {\n initialize,\n updateInitData,\n updateSegmentData,\n getSegmentByIndex,\n getSegmentByTime,\n getMediaFinishedInformation\n };\n\n setup();\n\n return instance;\n}\n\nSegmentsController.__dashjs_factory_name = 'SegmentsController';\nconst factory = FactoryMaker.getClassFactory(SegmentsController);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\n\nconst DEFAULT_DVB_PRIORITY = 1;\nconst DEFAULT_DVB_WEIGHT = 1;\n\nclass BaseURL {\n constructor(url, serviceLocation, priority, weight) {\n this.url = url || '';\n this.serviceLocation = serviceLocation || url || '';\n\n // DVB extensions\n this.dvb_priority = priority || DEFAULT_DVB_PRIORITY;\n this.dvb_weight = weight || DEFAULT_DVB_WEIGHT;\n\n this.availabilityTimeOffset = 0;\n this.availabilityTimeComplete = true;\n\n /* currently unused:\n * byteRange,\n */\n }\n}\n\nBaseURL.DEFAULT_DVB_PRIORITY = DEFAULT_DVB_PRIORITY;\nBaseURL.DEFAULT_DVB_WEIGHT = DEFAULT_DVB_WEIGHT;\n\nexport default BaseURL;\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2015-2016, DASH Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * 2. Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n(function(exports) {\n\n \"use strict\";\n\n /**\n * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes\n */\n\n var specialCea608CharsCodes = {\n 0x2a : 0xe1, // lowercase a, acute accent\n 0x5c : 0xe9, // lowercase e, acute accent\n 0x5e : 0xed, // lowercase i, acute accent\n 0x5f : 0xf3, // lowercase o, acute accent\n 0x60 : 0xfa, // lowercase u, acute accent\n 0x7b : 0xe7, // lowercase c with cedilla\n 0x7c : 0xf7, // division symbol\n 0x7d : 0xd1, // uppercase N tilde\n 0x7e : 0xf1, // lowercase n tilde\n 0x7f : 0x2588, // Full block\n // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F\n // THIS MEANS THAT \\x50 MUST BE ADDED TO THE VALUES\n 0x80 : 0xae, // Registered symbol (R)\n 0x81 : 0xb0, // degree sign\n 0x82 : 0xbd, // 1/2 symbol\n 0x83 : 0xbf, // Inverted (open) question mark\n 0x84 : 0x2122, // Trademark symbol (TM)\n 0x85 : 0xa2, // Cents symbol\n 0x86 : 0xa3, // Pounds sterling\n 0x87 : 0x266a, // Music 8'th note\n 0x88 : 0xe0, // lowercase a, grave accent\n 0x89 : 0x20, // transparent space (regular)\n 0x8a : 0xe8, // lowercase e, grave accent\n 0x8b : 0xe2, // lowercase a, circumflex accent\n 0x8c : 0xea, // lowercase e, circumflex accent\n 0x8d : 0xee, // lowercase i, circumflex accent\n 0x8e : 0xf4, // lowercase o, circumflex accent\n 0x8f : 0xfb, // lowercase u, circumflex accent\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F\n 0x90 : 0xc1, // capital letter A with acute\n 0x91 : 0xc9, // capital letter E with acute\n 0x92 : 0xd3, // capital letter O with acute\n 0x93 : 0xda, // capital letter U with acute\n 0x94 : 0xdc, // capital letter U with diaresis\n 0x95 : 0xfc, // lowercase letter U with diaeresis\n 0x96 : 0x2018, // opening single quote\n 0x97 : 0xa1, // inverted exclamation mark\n 0x98 : 0x2a, // asterisk\n 0x99 : 0x2019, // closing single quote\n 0x9a : 0x2501, // box drawings heavy horizontal\n 0x9b : 0xa9, // copyright sign\n 0x9c : 0x2120, // Service mark\n 0x9d : 0x2022, // (round) bullet\n 0x9e : 0x201c, // Left double quotation mark\n 0x9f : 0x201d, // Right double quotation mark\n 0xa0 : 0xc0, // uppercase A, grave accent\n 0xa1 : 0xc2, // uppercase A, circumflex\n 0xa2 : 0xc7, // uppercase C with cedilla\n 0xa3 : 0xc8, // uppercase E, grave accent\n 0xa4 : 0xca, // uppercase E, circumflex\n 0xa5 : 0xcb, // capital letter E with diaresis\n 0xa6 : 0xeb, // lowercase letter e with diaresis\n 0xa7 : 0xce, // uppercase I, circumflex\n 0xa8 : 0xcf, // uppercase I, with diaresis\n 0xa9 : 0xef, // lowercase i, with diaresis\n 0xaa : 0xd4, // uppercase O, circumflex\n 0xab : 0xd9, // uppercase U, grave accent\n 0xac : 0xf9, // lowercase u, grave accent\n 0xad : 0xdb, // uppercase U, circumflex\n 0xae : 0xab, // left-pointing double angle quotation mark\n 0xaf : 0xbb, // right-pointing double angle quotation mark\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F\n 0xb0 : 0xc3, // Uppercase A, tilde\n 0xb1 : 0xe3, // Lowercase a, tilde\n 0xb2 : 0xcd, // Uppercase I, acute accent\n 0xb3 : 0xcc, // Uppercase I, grave accent\n 0xb4 : 0xec, // Lowercase i, grave accent\n 0xb5 : 0xd2, // Uppercase O, grave accent\n 0xb6 : 0xf2, // Lowercase o, grave accent\n 0xb7 : 0xd5, // Uppercase O, tilde\n 0xb8 : 0xf5, // Lowercase o, tilde\n 0xb9 : 0x7b, // Open curly brace\n 0xba : 0x7d, // Closing curly brace\n 0xbb : 0x5c, // Backslash\n 0xbc : 0x5e, // Caret\n 0xbd : 0x5f, // Underscore\n 0xbe : 0x7c, // Pipe (vertical line)\n 0xbf : 0x223c, // Tilde operator\n 0xc0 : 0xc4, // Uppercase A, umlaut\n 0xc1 : 0xe4, // Lowercase A, umlaut\n 0xc2 : 0xd6, // Uppercase O, umlaut\n 0xc3 : 0xf6, // Lowercase o, umlaut\n 0xc4 : 0xdf, // Esszett (sharp S)\n 0xc5 : 0xa5, // Yen symbol\n 0xc6 : 0xa4, // Generic currency sign\n 0xc7 : 0x2503, // Box drawings heavy vertical\n 0xc8 : 0xc5, // Uppercase A, ring\n 0xc9 : 0xe5, // Lowercase A, ring\n 0xca : 0xd8, // Uppercase O, stroke\n 0xcb : 0xf8, // Lowercase o, strok\n 0xcc : 0x250f, // Box drawings heavy down and right\n 0xcd : 0x2513, // Box drawings heavy down and left\n 0xce : 0x2517, // Box drawings heavy up and right\n 0xcf : 0x251b // Box drawings heavy up and left\n };\n\n /**\n * Get Unicode Character from CEA-608 byte code\n */\n var getCharForByte = function(byte) {\n var charCode = byte;\n if (specialCea608CharsCodes.hasOwnProperty(byte)) {\n charCode = specialCea608CharsCodes[byte];\n }\n return String.fromCharCode(charCode);\n };\n\n var NR_ROWS = 15,\n NR_COLS = 32;\n // Tables to look up row from PAC data\n var rowsLowCh1 = {0x11 : 1, 0x12 : 3, 0x15 : 5, 0x16 : 7, 0x17 : 9, 0x10 : 11, 0x13 : 12, 0x14 : 14};\n var rowsHighCh1 = {0x11 : 2, 0x12 : 4, 0x15 : 6, 0x16 : 8, 0x17 : 10, 0x13 : 13, 0x14 : 15};\n var rowsLowCh2 = {0x19 : 1, 0x1A : 3, 0x1D : 5, 0x1E : 7, 0x1F : 9, 0x18 : 11, 0x1B : 12, 0x1C : 14};\n var rowsHighCh2 = {0x19 : 2, 0x1A : 4, 0x1D : 6, 0x1E : 8, 0x1F : 10, 0x1B : 13, 0x1C : 15};\n\n var backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];\n\n /**\n * Simple logger class to be able to write with time-stamps and filter on level.\n */\n var logger = {\n verboseFilter : {'DATA' : 3, 'DEBUG' : 3, 'INFO' : 2, 'WARNING' : 2, 'TEXT' : 1, 'ERROR' : 0},\n time : null,\n verboseLevel : 0, // Only write errors\n setTime : function(newTime) {\n this.time = newTime;\n },\n log : function(severity, msg) {\n var minLevel = this.verboseFilter[severity];\n if (this.verboseLevel >= minLevel) {\n console.log(this.time + \" [\" + severity + \"] \" + msg);\n }\n }\n };\n\n var numArrayToHexArray = function(numArray) {\n var hexArray = [];\n for (var j = 0; j < numArray.length; j++) {\n hexArray.push(numArray[j].toString(16));\n }\n return hexArray;\n };\n\n /**\n * State of CEA-608 pen or character\n * @constructor\n */\n var PenState = function(foreground, underline, italics, background, flash) {\n this.foreground = foreground || \"white\";\n this.underline = underline || false;\n this.italics = italics || false;\n this.background = background || \"black\";\n this.flash = flash || false;\n };\n\n PenState.prototype = {\n \n reset : function() {\n this.foreground = \"white\";\n this.underline = false;\n this.italics = false;\n this.background = \"black\";\n this.flash = false;\n },\n \n setStyles : function(styles) {\n var attribs = [\"foreground\", \"underline\", \"italics\", \"background\", \"flash\"];\n for (var i = 0 ; i < attribs.length; i++) {\n var style = attribs[i];\n if (styles.hasOwnProperty(style)) {\n this[style] = styles[style];\n }\n }\n },\n \n isDefault : function() {\n return (this.foreground === \"white\" && !this.underline && !this.italics && \n this.background === \"black\" && !this.flash);\n },\n\n equals : function(other) {\n return ( (this.foreground === other.foreground) && \n (this.underline === other.underline) &&\n (this.italics === other.italics) &&\n (this.background === other.background) &&\n (this.flash === other.flash) );\n },\n\n copy : function(newPenState) {\n this.foreground = newPenState.foreground;\n this.underline = newPenState.underline;\n this.italics = newPenState.italics;\n this.background = newPenState.background;\n this.flash = newPenState.flash;\n },\n \n toString: function() {\n return (\"color=\" + this.foreground + \", underline=\" + this.underline + \", italics=\" + this.italics +\n \", background=\" + this.background + \", flash=\" + this.flash);\n }\n };\n\n /**\n * Unicode character with styling and background.\n * @constructor\n */\n var StyledUnicodeChar = function(uchar, foreground, underline, italics, background, flash) {\n this.uchar = uchar || ' '; // unicode character\n this.penState = new PenState(foreground, underline,italics, background, flash);\n };\n\n StyledUnicodeChar.prototype = {\n \n reset: function() {\n this.uchar = ' ';\n this.penState.reset();\n },\n \n setChar: function(uchar, newPenState) {\n this.uchar = uchar;\n this.penState.copy(newPenState);\n },\n \n setPenState: function(newPenState) {\n this.penState.copy(newPenState);\n },\n \n equals: function(other) {\n return this.uchar === other.uchar && this.penState.equals(other.penState);\n },\n \n copy: function(newChar) {\n this.uchar = newChar.uchar;\n this.penState.copy(newChar.penState);\n },\n \n isEmpty : function() {\n return this.uchar === ' ' && this.penState.isDefault();\n }\n };\n\n /**\n * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.\n * @constructor\n */\n var Row = function() {\n this.chars = [];\n for (var i = 0 ; i < NR_COLS ; i++) {\n this.chars.push(new StyledUnicodeChar());\n }\n this.pos = 0;\n this.currPenState = new PenState();\n };\n\n Row.prototype = {\n \n equals: function(other) {\n var equal = true;\n for (var i = 0 ; i < NR_COLS; i ++) {\n if (!this.chars[i].equals(other.chars[i])) {\n equal = false;\n break;\n }\n }\n return equal;\n },\n \n copy: function(other) {\n for (var i = 0 ; i < NR_COLS; i ++) {\n this.chars[i].copy(other.chars[i]);\n }\n },\n \n isEmpty : function() {\n var empty = true;\n for (var i = 0 ; i < NR_COLS; i ++) {\n if (!this.chars[i].isEmpty()) {\n empty = false;\n break;\n }\n }\n return empty;\n },\n\n /**\n * Set the cursor to a valid column.\n */\n setCursor : function(absPos) {\n if (this.pos !== absPos) {\n this.pos = absPos;\n }\n if (this.pos < 0) {\n logger.log(\"ERROR\", \"Negative cursor position \" + this.pos);\n this.pos = 0;\n } else if (this.pos > NR_COLS) {\n logger.log(\"ERROR\", \"Too large cursor position \" + this.pos);\n this.pos = NR_COLS;\n }\n },\n\n /** \n * Move the cursor relative to current position.\n */\n moveCursor : function(relPos) {\n var newPos = this.pos + relPos;\n if (relPos > 1) {\n for (var i = this.pos+1; i < newPos+1 ; i++) {\n this.chars[i].setPenState(this.currPenState);\n }\n }\n this.setCursor(newPos);\n },\n\n /**\n * Backspace, move one step back and clear character.\n */\n backSpace : function () {\n this.moveCursor(-1);\n this.chars[this.pos].setChar(' ', this.currPenState);\n },\n\n insertChar: function(byte) {\n if (byte >= 0x90) { //Extended char\n this.backSpace();\n }\n var char = getCharForByte(byte);\n if (this.pos >= NR_COLS) {\n logger.log(\"ERROR\", \"Cannot insert \" + byte.toString(16) + \n \" (\" + char + \") at position \" + this.pos + \". Skipping it!\");\n return;\n }\n this.chars[this.pos].setChar(char, this.currPenState);\n this.moveCursor(1);\n },\n\n clearFromPos : function(startPos) {\n var i;\n for (i = startPos ; i < NR_COLS ; i++) {\n this.chars[i].reset();\n }\n },\n\n clear : function() {\n this.clearFromPos(0);\n this.pos = 0;\n this.currPenState.reset();\n },\n\n clearToEndOfRow : function() {\n this.clearFromPos(this.pos);\n },\n\n getTextString: function() {\n var chars = [];\n var empty = true;\n for (var i = 0 ; i < NR_COLS ; i++) {\n var char = this.chars[i].uchar;\n if (char !== \" \") {\n empty = false;\n }\n chars.push(char);\n }\n if (empty) {\n return \"\";\n } else {\n return chars.join(\"\");\n }\n },\n\n setPenStyles: function(styles) {\n this.currPenState.setStyles(styles);\n var currChar = this.chars[this.pos];\n currChar.setPenState(this.currPenState);\n }\n };\n\n /**\n * Keep a CEA-608 screen of 32x15 styled characters\n * @constructor\n */\n var CaptionScreen = function() {\n\n this.rows = [];\n for (var i = 0 ; i < NR_ROWS; i++) {\n this.rows.push(new Row()); // Note that we use zero-based numbering (0-14)\n }\n this.currRow = NR_ROWS - 1;\n this.nrRollUpRows = null;\n this.reset();\n };\n\n CaptionScreen.prototype = {\n\n reset : function() {\n for (var i = 0 ; i < NR_ROWS ; i++) {\n this.rows[i].clear();\n }\n this.currRow = NR_ROWS - 1;\n },\n\n equals : function(other) {\n var equal = true;\n for (var i = 0 ; i < NR_ROWS ; i++) {\n if (!this.rows[i].equals(other.rows[i])) {\n equal = false;\n break;\n }\n }\n return equal;\n },\n\n copy : function(other) {\n for (var i = 0 ; i < NR_ROWS ; i++) {\n this.rows[i].copy(other.rows[i]);\n }\n },\n\n isEmpty : function() {\n var empty = true;\n for (var i = 0 ; i < NR_ROWS ; i++) {\n if (!this.rows[i].isEmpty()) {\n empty = false;\n break;\n }\n }\n return empty;\n },\n\n backSpace : function() {\n var row = this.rows[this.currRow]; \n row.backSpace();\n },\n\n clearToEndOfRow : function() {\n var row = this.rows[this.currRow];\n row.clearToEndOfRow();\n },\n\n /**\n * Insert a character (without styling) in the current row.\n */\n insertChar : function(char) {\n var row = this.rows[this.currRow];\n row.insertChar(char);\n },\n\n setPen : function(styles) {\n var row = this.rows[this.currRow];\n row.setPenStyles(styles);\n },\n\n moveCursor : function(relPos) {\n var row = this.rows[this.currRow];\n row.moveCursor(relPos); \n },\n\n setCursor : function(absPos) {\n logger.log(\"INFO\", \"setCursor: \" + absPos);\n var row = this.rows[this.currRow];\n row.setCursor(absPos);\n },\n\n setPAC : function(pacData) {\n logger.log(\"INFO\", \"pacData = \" + JSON.stringify(pacData));\n var newRow = pacData.row - 1;\n if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {\n newRow = this.nrRollUpRows-1;\n }\n this.currRow = newRow;\n var row = this.rows[this.currRow];\n if (pacData.indent !== null) {\n var indent = pacData.indent;\n var prevPos = Math.max(indent-1, 0);\n row.setCursor(pacData.indent);\n pacData.color = row.chars[prevPos].penState.foreground;\n }\n var styles = {foreground : pacData.color, underline : pacData.underline, italics : pacData.italics, background : 'black', flash : false};\n this.setPen(styles);\n },\n\n /**\n * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).\n */\n setBkgData : function(bkgData) {\n\n logger.log(\"INFO\", \"bkgData = \" + JSON.stringify(bkgData));\n this.backSpace();\n this.setPen(bkgData);\n this.insertChar(0x20); //Space\n },\n\n setRollUpRows : function(nrRows) {\n this.nrRollUpRows = nrRows;\n },\n\n rollUp : function() {\n if (this.nrRollUpRows === null) {\n logger.log(\"DEBUG\", \"roll_up but nrRollUpRows not set yet\");\n return; //Not properly setup\n }\n logger.log(\"TEXT\", this.getDisplayText());\n var topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n var topRow = this.rows.splice(topRowIndex, 1)[0];\n topRow.clear();\n this.rows.splice(this.currRow, 0, topRow);\n logger.log(\"INFO\", \"Rolling up\");\n //logger.log(\"TEXT\", this.get_display_text())\n },\n\n /**\n * Get all non-empty rows with as unicode text. \n */ \n getDisplayText : function(asOneRow) {\n asOneRow = asOneRow || false;\n var displayText = [];\n var text = \"\";\n var rowNr = -1;\n for (var i = 0 ; i < NR_ROWS ; i++) {\n var rowText = this.rows[i].getTextString();\n if (rowText) {\n rowNr = i+1;\n if (asOneRow) {\n displayText.push(\"Row \" + rowNr + ': \"' + rowText + '\"');\n } else {\n displayText.push(rowText.trim());\n }\n }\n }\n if (displayText.length > 0) {\n if (asOneRow) {\n text = \"[\" + displayText.join(\" | \") + \"]\";\n } else {\n text = displayText.join(\"\\n\");\n }\n }\n return text;\n },\n\n getTextAndFormat : function() {\n return this.rows;\n }\n };\n\n /**\n * Handle a CEA-608 channel and send decoded data to outputFilter\n * @constructor\n * @param {Number} channelNumber (1 or 2)\n * @param {CueHandler} outputFilter Output from channel1 newCue(startTime, endTime, captionScreen)\n */\n var Cea608Channel = function(channelNumber, outputFilter) {\n\n this.chNr = channelNumber;\n this.outputFilter = outputFilter;\n this.mode = null;\n this.verbose = 0;\n this.displayedMemory = new CaptionScreen();\n this.nonDisplayedMemory = new CaptionScreen();\n this.lastOutputScreen = new CaptionScreen();\n this.currRollUpRow = this.displayedMemory.rows[NR_ROWS-1];\n this.writeScreen = this.displayedMemory;\n this.mode = null;\n this.cueStartTime = null; // Keeps track of where a cue started.\n };\n\n Cea608Channel.prototype = {\n \n modes : [\"MODE_ROLL-UP\", \"MODE_POP-ON\", \"MODE_PAINT-ON\", \"MODE_TEXT\"],\n \n reset : function() {\n this.mode = null;\n this.displayedMemory.reset();\n this.nonDisplayedMemory.reset();\n this.lastOutputScreen.reset();\n this.currRollUpRow = this.displayedMemory.rows[NR_ROWS-1];\n this.writeScreen = this.displayedMemory;\n this.mode = null;\n this.cueStartTime = null;\n this.lastCueEndTime = null;\n },\n\n getHandler : function() {\n return this.outputFilter;\n },\n\n setHandler : function(newHandler) {\n this.outputFilter = newHandler;\n },\n\n setPAC : function(pacData) {\n this.writeScreen.setPAC(pacData);\n },\n\n setBkgData : function(bkgData) {\n this.writeScreen.setBkgData(bkgData);\n },\n\n setMode : function(newMode) {\n if (newMode === this.mode) {\n return;\n }\n this.mode = newMode;\n logger.log(\"INFO\", \"MODE=\" + newMode);\n if (this.mode == \"MODE_POP-ON\") {\n this.writeScreen = this.nonDisplayedMemory;\n } else {\n this.writeScreen = this.displayedMemory;\n this.writeScreen.reset();\n }\n if (this.mode !== \"MODE_ROLL-UP\") {\n this.displayedMemory.nrRollUpRows = null;\n this.nonDisplayedMemory.nrRollUpRows = null;\n }\n this.mode = newMode;\n },\n\n insertChars : function(chars) {\n for (var i = 0 ; i < chars.length ; i++) {\n this.writeScreen.insertChar(chars[i]);\n }\n var screen = this.writeScreen === this.displayedMemory ? \"DISP\" : \"NON_DISP\";\n logger.log(\"INFO\", screen + \": \" + this.writeScreen.getDisplayText(true));\n if (this.mode === \"MODE_PAINT-ON\" || this.mode === \"MODE_ROLL-UP\") {\n logger.log(\"TEXT\", \"DISPLAYED: \" + this.displayedMemory.getDisplayText(true));\n this.outputDataUpdate();\n }\n },\n\n cc_RCL: function() { // Resume Caption Loading (switch mode to Pop On)\n logger.log(\"INFO\", \"RCL - Resume Caption Loading\");\n this.setMode(\"MODE_POP-ON\");\n },\n cc_BS: function() { // BackSpace\n logger.log(\"INFO\", \"BS - BackSpace\");\n if (this.mode === \"MODE_TEXT\") {\n return;\n }\n this.writeScreen.backSpace();\n if (this.writeScreen === this.displayedMemory) {\n this.outputDataUpdate();\n }\n },\n cc_AOF : function() { // Reserved (formerly Alarm Off)\n return;\n },\n cc_AON: function() { // Reserved (formerly Alarm On)\n return;\n },\n cc_DER: function() { // Delete to End of Row\n logger.log(\"INFO\", \"DER- Delete to End of Row\");\n this.writeScreen.clearToEndOfRow();\n this.outputDataUpdate();\n },\n cc_RU: function(nrRows) { //Roll-Up Captions-2,3,or 4 Rows\n logger.log(\"INFO\", \"RU(\" + nrRows +\") - Roll Up\");\n this.writeScreen = this.displayedMemory;\n this.setMode(\"MODE_ROLL-UP\");\n this.writeScreen.setRollUpRows(nrRows);\n },\n cc_FON: function() { //Flash On\n logger.log(\"INFO\", \"FON - Flash On\");\n this.writeScreen.setPen({flash : true});\n },\n cc_RDC: function() { // Resume Direct Captioning (switch mode to PaintOn)\n logger.log(\"INFO\", \"RDC - Resume Direct Captioning\");\n this.setMode(\"MODE_PAINT-ON\");\n },\n cc_TR: function() { // Text Restart in text mode (not supported, however)\n logger.log(\"INFO\", \"TR\");\n this.setMode(\"MODE_TEXT\");\n },\n cc_RTD: function() { // Resume Text Display in Text mode (not supported, however)\n logger.log(\"INFO\", \"RTD\");\n this.setMode(\"MODE_TEXT\");\n },\n cc_EDM: function() { // Erase Displayed Memory\n logger.log(\"INFO\", \"EDM - Erase Displayed Memory\");\n this.displayedMemory.reset();\n this.outputDataUpdate();\n },\n cc_CR: function() { // Carriage Return\n logger.log(\"CR - Carriage Return\");\n this.writeScreen.rollUp();\n this.outputDataUpdate();\n },\n cc_ENM: function() { //Erase Non-Displayed Memory\n logger.log(\"INFO\", \"ENM - Erase Non-displayed Memory\");\n this.nonDisplayedMemory.reset();\n },\n cc_EOC: function() { //End of Caption (Flip Memories)\n logger.log(\"INFO\", \"EOC - End Of Caption\");\n if (this.mode === \"MODE_POP-ON\") {\n var tmp = this.displayedMemory;\n this.displayedMemory = this.nonDisplayedMemory;\n this.nonDisplayedMemory = tmp;\n this.writeScreen = this.nonDisplayedMemory;\n logger.log(\"TEXT\", \"DISP: \" + this.displayedMemory.getDisplayText());\n }\n this.outputDataUpdate();\n },\n cc_TO: function(nrCols) { // Tab Offset 1,2, or 3 columns\n logger.log(\"INFO\", \"TO(\" + nrCols + \") - Tab Offset\");\n this.writeScreen.moveCursor(nrCols);\n },\n cc_MIDROW: function(secondByte) { // Parse MIDROW command\n var styles = {flash : false};\n styles.underline = secondByte % 2 === 1;\n styles.italics = secondByte >= 0x2e;\n if (!styles.italics) {\n var colorIndex = Math.floor(secondByte/2) - 0x10;\n var colors = [\"white\", \"green\", \"blue\", \"cyan\", \"red\", \"yellow\", \"magenta\"];\n styles.foreground = colors[colorIndex];\n } else {\n styles.foreground = \"white\";\n }\n logger.log(\"INFO\", \"MIDROW: \" + JSON.stringify(styles));\n this.writeScreen.setPen(styles);\n },\n\n outputDataUpdate: function() {\n var t = logger.time;\n if (t === null) {\n return;\n }\n if (this.outputFilter) {\n if (this.outputFilter.updateData) {\n this.outputFilter.updateData(t, this.displayedMemory);\n }\n if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) { // Start of a new cue\n this.cueStartTime = t;\n } else {\n if (!this.displayedMemory.equals(this.lastOutputScreen)) { \n if (this.outputFilter.newCue) {\n this.outputFilter.newCue(this.cueStartTime, t, this.lastOutputScreen);\n }\n this.cueStartTime = this.displayedMemory.isEmpty() ? null : t;\n }\n }\n this.lastOutputScreen.copy(this.displayedMemory);\n }\n },\n\n cueSplitAtTime : function(t) {\n if (this.outputFilter) {\n if (!this.displayedMemory.isEmpty()) {\n if (this.outputFilter.newCue) {\n this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);\n }\n this.cueStartTime = t;\n }\n }\n }\n };\n\n /**\n * Parse CEA-608 data and send decoded data to out1 and out2.\n * @constructor\n * @param {Number} field CEA-608 field (1 or 2)\n * @param {CueHandler} out1 Output from channel1 newCue(startTime, endTime, captionScreen)\n * @param {CueHandler} out2 Output from channel2 newCue(startTime, endTime, captionScreen)\n */\n var Cea608Parser = function(field, out1, out2) {\n this.field = field || 1;\n this.outputs = [out1, out2];\n this.channels = [new Cea608Channel(1, out1), new Cea608Channel(2, out2)];\n this.currChNr = -1; // Will be 1 or 2\n this.lastCmdA = null; // First byte of last command\n this.lastCmdB = null; // Second byte of last command\n this.bufferedData = [];\n this.startTime = null;\n this.lastTime = null;\n this.dataCounters = {'padding' : 0, 'char' : 0, 'cmd' : 0, 'other' : 0};\n };\n\n Cea608Parser.prototype = {\n \n getHandler : function(index) {\n return this.channels[index].getHandler();\n },\n \n setHandler : function(index, newHandler) {\n this.channels[index].setHandler(newHandler);\n },\n\n /**\n * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.\n */\n addData : function(t, byteList) {\n var cmdFound, a, b, \n charsFound = false;\n \n this.lastTime = t;\n logger.setTime(t);\n\n for (var i = 0 ; i < byteList.length ; i+=2) {\n a = byteList[i] & 0x7f;\n b = byteList[i+1] & 0x7f;\n\n if (a >= 0x10 && a <= 0x1f && a === this.lastCmdA && b === this.lastCmdB) {\n this.lastCmdA = null;\n this.lastCmdB = null;\n logger.log(\"DEBUG\", \"Repeated command (\" + numArrayToHexArray([a, b]) + \") is dropped\");\n continue; // Repeated commands are dropped (once)\n }\n\n if (a === 0 && b === 0) {\n this.dataCounters.padding += 2;\n continue;\n } else {\n logger.log(\"DATA\", \"[\" + numArrayToHexArray([byteList[i], byteList[i+1]]) +\"] -> (\" + numArrayToHexArray([a, b]) + \")\");\n }\n cmdFound = this.parseCmd(a, b);\n if (!cmdFound) {\n cmdFound = this.parseMidrow(a, b);\n }\n if (!cmdFound) {\n cmdFound = this.parsePAC(a, b);\n }\n if (!cmdFound) {\n cmdFound = this.parseBackgroundAttributes(a, b);\n }\n if (!cmdFound) {\n charsFound = this.parseChars(a, b);\n if (charsFound) {\n if (this.currChNr && this.currChNr >=0) {\n var channel = this.channels[this.currChNr-1];\n channel.insertChars(charsFound);\n } else {\n logger.log(\"WARNING\", \"No channel found yet. TEXT-MODE?\");\n }\n }\n }\n if (cmdFound) {\n this.dataCounters.cmd += 2;\n } else if (charsFound) {\n this.dataCounters.char += 2;\n } else {\n this.dataCounters.other += 2;\n logger.log(\"WARNING\", \"Couldn't parse cleaned data \" + numArrayToHexArray([a, b]) +\n \" orig: \" + numArrayToHexArray([byteList[i], byteList[i+1]]));\n }\n }\n },\n\n /**\n * Parse Command.\n * @returns {Boolean} Tells if a command was found\n */\n parseCmd: function(a, b) {\n var chNr = null;\n\n var cond1 = (a === 0x14 || a === 0x15 || a === 0x1C || a === 0x1D) && (0x20 <= b && b <= 0x2F);\n var cond2 = (a === 0x17 || a === 0x1F) && (0x21 <= b && b <= 0x23);\n if (!(cond1 || cond2)) {\n return false;\n }\n \n if (a === 0x14 || a === 0x15 || a === 0x17) {\n chNr = 1;\n } else {\n chNr = 2; // (a === 0x1C || a === 0x1D || a=== 0x1f)\n }\n\n var channel = this.channels[chNr - 1];\n\n if (a === 0x14 || a === 0x15 || a === 0x1C || a === 0x1D) {\n if (b === 0x20) {\n channel.cc_RCL();\n } else if (b === 0x21) {\n channel.cc_BS();\n } else if (b === 0x22) {\n channel.cc_AOF();\n } else if (b === 0x23) {\n channel.cc_AON();\n } else if (b === 0x24) {\n channel.cc_DER();\n } else if (b === 0x25) {\n channel.cc_RU(2);\n } else if (b === 0x26) {\n channel.cc_RU(3);\n } else if (b === 0x27) {\n channel.cc_RU(4);\n } else if (b === 0x28) {\n channel.cc_FON();\n } else if (b === 0x29) {\n channel.cc_RDC();\n } else if (b === 0x2A) {\n channel.cc_TR();\n } else if (b === 0x2B) {\n channel.cc_RTD();\n } else if (b === 0x2C) {\n channel.cc_EDM();\n } else if (b === 0x2D) {\n channel.cc_CR();\n } else if (b === 0x2E) {\n channel.cc_ENM();\n } else if (b === 0x2F) {\n channel.cc_EOC();\n }\n } else { //a == 0x17 || a == 0x1F\n channel.cc_TO(b - 0x20);\n }\n this.lastCmdA = a;\n this.lastCmdB = b;\n this.currChNr = chNr;\n return true;\n },\n\n /**\n * Parse midrow styling command\n * @returns {Boolean}\n */\n parseMidrow : function(a, b) {\n var chNr = null;\n \n if ( ((a === 0x11) || (a === 0x19)) && 0x20 <= b && b <= 0x2f) {\n if (a === 0x11) {\n chNr = 1;\n } else {\n chNr = 2;\n }\n if (chNr !== this.currChNr) {\n logger.log(\"ERROR\", \"Mismatch channel in midrow parsing\");\n return false;\n }\n var channel = this.channels[chNr-1];\n // cea608 spec says midrow codes should inject a space\n channel.insertChars([0x20]);\n channel.cc_MIDROW(b);\n logger.log(\"DEBUG\", \"MIDROW (\" + numArrayToHexArray([a, b]) + \")\");\n this.lastCmdA = a;\n this.lastCmdB = b;\n return true;\n }\n return false;\n },\n /**\n * Parse Preable Access Codes (Table 53).\n * @returns {Boolean} Tells if PAC found\n */\n parsePAC : function(a, b) {\n\n var chNr = null;\n var row = null;\n \n var case1 = ((0x11 <= a && a <= 0x17) || (0x19 <= a && a <= 0x1F)) && (0x40 <= b && b <= 0x7F);\n var case2 = (a === 0x10 || a === 0x18) && (0x40 <= b && b <= 0x5F);\n if (! (case1 || case2)) {\n return false;\n }\n\n chNr = (a <= 0x17) ? 1 : 2;\n\n if (0x40 <= b && b <= 0x5F) {\n row = (chNr === 1) ? rowsLowCh1[a] : rowsLowCh2[a];\n } else { // 0x60 <= b <= 0x7F\n row = (chNr === 1) ? rowsHighCh1[a] : rowsHighCh2[a];\n }\n var pacData = this.interpretPAC(row, b);\n var channel = this.channels[chNr-1];\n channel.setPAC(pacData);\n this.lastCmdA = a;\n this.lastCmdB = b;\n this.currChNr = chNr;\n return true;\n },\n\n /**\n * Interpret the second byte of the pac, and return the information.\n * @returns {Object} pacData with style parameters.\n */\n interpretPAC : function (row, byte) {\n var pacIndex = byte;\n var pacData = {color : null, italics : false, indent : null, underline : false, row : row};\n \n if (byte > 0x5F) {\n pacIndex = byte - 0x60;\n } else {\n pacIndex = byte - 0x40;\n }\n pacData.underline = (pacIndex & 1) === 1;\n if (pacIndex <= 0xd) {\n pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex/2)];\n } else if (pacIndex <= 0xf) {\n pacData.italics = true;\n pacData.color = 'white';\n } else {\n pacData.indent = (Math.floor((pacIndex-0x10)/2))*4;\n }\n return pacData; // Note that row has zero offset. The spec uses 1.\n },\n\n /**\n * Parse characters.\n * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.\n */\n parseChars : function(a, b) {\n\n var channelNr = null,\n charCodes = null,\n charCode1 = null,\n charCode2 = null;\n\n if (a >= 0x19) {\n channelNr = 2;\n charCode1 = a - 8;\n } else {\n channelNr = 1;\n charCode1 = a;\n }\n if (0x11 <= charCode1 && charCode1 <= 0x13) {\n // Special character\n var oneCode = b;\n if (charCode1 === 0x11) {\n oneCode = b + 0x50;\n } else if (charCode1 === 0x12) {\n oneCode = b + 0x70;\n } else {\n oneCode = b + 0x90;\n }\n logger.log(\"INFO\", \"Special char '\" + getCharForByte(oneCode) + \"' in channel \" + channelNr);\n charCodes = [oneCode];\n this.lastCmdA = a;\n this.lastCmdB = b;\n } else if (0x20 <= a && a <= 0x7f) {\n charCodes = (b === 0) ? [a] : [a, b];\n this.lastCmdA = null;\n this.lastCmdB = null;\n }\n if (charCodes) {\n var hexCodes = numArrayToHexArray(charCodes);\n logger.log(\"DEBUG\", \"Char codes = \" + hexCodes.join(\",\"));\n }\n return charCodes;\n },\n \n /**\n * Parse extended background attributes as well as new foreground color black.\n * @returns{Boolean} Tells if background attributes are found\n */\n parseBackgroundAttributes : function(a, b) {\n var bkgData,\n index,\n chNr,\n channel;\n\n var case1 = (a === 0x10 || a === 0x18) && (0x20 <= b && b <= 0x2f);\n var case2 = (a === 0x17 || a === 0x1f) && (0x2d <=b && b <= 0x2f);\n if (!(case1 || case2)) {\n return false;\n }\n bkgData = {};\n if (a === 0x10 || a === 0x18) {\n index = Math.floor((b-0x20)/2);\n bkgData.background = backgroundColors[index];\n if (b % 2 === 1) {\n bkgData.background = bkgData.background + \"_semi\";\n }\n } else if (b === 0x2d) {\n bkgData.background = \"transparent\";\n } else {\n bkgData.foreground = \"black\";\n if (b === 0x2f) {\n bkgData.underline = true;\n }\n }\n chNr = (a < 0x18) ? 1 : 2;\n channel = this.channels[chNr-1];\n channel.setBkgData(bkgData);\n this.lastCmdA = a;\n this.lastCmdB = b;\n return true;\n },\n\n /**\n * Reset state of parser and its channels.\n */\n reset : function() {\n for (var i=0 ; i < this.channels.length ; i++) {\n if (this.channels[i]) {\n this.channels[i].reset();\n }\n }\n this.lastCmdA = null;\n this.lastCmdB = null;\n },\n\n /**\n * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.\n */\n cueSplitAtTime : function(t) {\n for (var i=0 ; i < this.channels.length ; i++) {\n if (this.channels[i]) {\n this.channels[i].cueSplitAtTime(t);\n }\n }\n },\n };\n\n /**\n * Find ranges corresponding to SEA CEA-608 NALUS in sizeprepended NALU array.\n * @param {raw} dataView of binary data\n * @param {startPos} start position in raw\n * @param {size} total size of data in raw to consider\n * @returns \n */\n var findCea608Nalus = function(raw, startPos, size) {\n var nalSize = 0,\n cursor = startPos,\n nalType = 0,\n cea608NaluRanges = [],\n // Check SEI data according to ANSI-SCTE 128\n isCEA608SEI = function (payloadType, payloadSize, raw, pos) {\n if (payloadType !== 4 || payloadSize < 8) {\n return null;\n }\n var countryCode = raw.getUint8(pos);\n var providerCode = raw.getUint16(pos + 1);\n var userIdentifier = raw.getUint32(pos + 3);\n var userDataTypeCode = raw.getUint8(pos + 7);\n return countryCode == 0xB5 && providerCode == 0x31 && userIdentifier == 0x47413934 && userDataTypeCode == 0x3;\n };\n while (cursor < startPos + size) {\n nalSize = raw.getUint32(cursor);\n nalType = raw.getUint8(cursor + 4) & 0x1F;\n //console.log(time + \" NAL \" + nalType);\n if (nalType === 6) {\n // SEI NAL Unit. The NAL header is the first byte\n //console.log(\"SEI NALU of size \" + nalSize + \" at time \" + time);\n var pos = cursor + 5;\n var payloadType = -1;\n while (pos < cursor + 4 + nalSize - 1) { // The last byte should be rbsp_trailing_bits\n payloadType = 0;\n var b = 0xFF;\n while (b === 0xFF) {\n b = raw.getUint8(pos);\n payloadType += b;\n pos++;\n }\n var payloadSize = 0;\n b = 0xFF;\n while (b === 0xFF) {\n b = raw.getUint8(pos);\n payloadSize += b;\n pos++;\n }\n if (isCEA608SEI(payloadType, payloadSize, raw, pos)) {\n //console.log(\"CEA608 SEI \" + time + \" \" + payloadSize);\n cea608NaluRanges.push([pos, payloadSize]);\n }\n pos += payloadSize;\n }\n }\n cursor += nalSize + 4;\n }\n return cea608NaluRanges;\n };\n \n var extractCea608DataFromRange = function(raw, cea608Range) {\n var pos = cea608Range[0];\n var fieldData = [[], []];\n\n pos += 8; // Skip the identifier up to userDataTypeCode\n var ccCount = raw.getUint8(pos) & 0x1f;\n pos += 2; // Advance 1 and skip reserved byte\n \n for (var i = 0; i < ccCount; i++) {\n var byte = raw.getUint8(pos);\n var ccValid = byte & 0x4;\n var ccType = byte & 0x3;\n pos++;\n var ccData1 = raw.getUint8(pos); // Keep parity bit\n pos++;\n var ccData2 = raw.getUint8(pos); // Keep parity bit\n pos++;\n if (ccValid && ((ccData1 & 0x7f) + (ccData2 & 0x7f) !== 0)) { //Check validity and non-empty data\n if (ccType === 0) {\n fieldData[0].push(ccData1);\n fieldData[0].push(ccData2);\n } else if (ccType === 1) {\n fieldData[1].push(ccData1);\n fieldData[1].push(ccData2);\n }\n }\n }\n return fieldData;\n };\n\n exports.logger = logger;\n exports.PenState = PenState;\n exports.CaptionScreen = CaptionScreen; \n exports.Cea608Parser = Cea608Parser;\n exports.findCea608Nalus = findCea608Nalus;\n exports.extractCea608DataFromRange = extractCea608DataFromRange;\n\n}(typeof exports === 'undefined' ? this.cea608parser = {} : exports));\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport EventBus from '../../core/EventBus';\nimport MediaPlayerEvents from '../MediaPlayerEvents';\nimport MetricsReportingEvents from '../metrics/MetricsReportingEvents';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Settings from '../../core/Settings';\nimport Constants from '../../streaming/constants/Constants';\nimport {HTTPRequest} from '../vo/metrics/HTTPRequest';\nimport DashManifestModel from '../../dash/models/DashManifestModel';\nimport Utils from '../../core/Utils';\n\nconst CMCD_REQUEST_FIELD_NAME = 'CMCD';\nconst CMCD_VERSION = 1;\nconst OBJECT_TYPES = {\n MANIFEST: 'm',\n AUDIO: 'a',\n VIDEO: 'v',\n INIT: 'i',\n CAPTION: 'c',\n ISOBMFF_TEXT_TRACK: 'tt',\n ENCRYPTION_KEY: 'k',\n OTHER: 'o'\n};\nconst STREAMING_FORMATS = {\n DASH: 'd',\n MSS: 's'\n};\nconst STREAM_TYPES = {\n VOD: 'v',\n LIVE: 'l'\n};\nconst RTP_SAFETY_FACTOR = 5;\n\nfunction CmcdModel() {\n\n let dashManifestModel,\n instance,\n internalData,\n abrController,\n dashMetrics,\n playbackController,\n streamProcessors,\n _isStartup,\n _bufferLevelStarved,\n _initialMediaRequestsDone;\n\n let context = this.context;\n let eventBus = EventBus(context).getInstance();\n let settings = Settings(context).getInstance();\n\n function setup() {\n dashManifestModel = DashManifestModel(context).getInstance();\n\n _resetInitialSettings();\n }\n\n function initialize() {\n eventBus.on(MediaPlayerEvents.PLAYBACK_RATE_CHANGED, _onPlaybackRateChanged, instance);\n eventBus.on(MediaPlayerEvents.MANIFEST_LOADED, _onManifestLoaded, instance);\n eventBus.on(MediaPlayerEvents.BUFFER_LEVEL_STATE_CHANGED, _onBufferLevelStateChanged, instance);\n eventBus.on(MediaPlayerEvents.PLAYBACK_SEEKED, _onPlaybackSeeked, instance);\n eventBus.on(MediaPlayerEvents.PERIOD_SWITCH_COMPLETED, _onPeriodSwitchComplete, instance);\n }\n\n function setConfig(config) {\n if (!config) return;\n\n if (config.abrController) {\n abrController = config.abrController;\n }\n\n if (config.dashMetrics) {\n dashMetrics = config.dashMetrics;\n }\n\n if (config.playbackController) {\n playbackController = config.playbackController;\n }\n }\n\n function _resetInitialSettings() {\n internalData = {\n pr: 1,\n nor: null,\n st: null,\n sf: null,\n sid: `${Utils.generateUuid()}`,\n cid: null\n };\n _bufferLevelStarved = {};\n _isStartup = {};\n _initialMediaRequestsDone = {};\n _updateStreamProcessors();\n }\n\n function _onPeriodSwitchComplete() {\n _updateStreamProcessors();\n }\n\n function _updateStreamProcessors() {\n if (!playbackController) return;\n const streamController = playbackController.getStreamController();\n if (!streamController) return;\n if (typeof streamController.getActiveStream !== 'function') return;\n const activeStream = streamController.getActiveStream();\n if (!activeStream) return;\n streamProcessors = activeStream.getProcessors();\n }\n\n function getQueryParameter(request) {\n try {\n if (settings.get().streaming.cmcd && settings.get().streaming.cmcd.enabled) {\n const cmcdData = _getCmcdData(request);\n const finalPayloadString = _buildFinalString(cmcdData);\n\n eventBus.trigger(MetricsReportingEvents.CMCD_DATA_GENERATED, {\n url: request.url,\n mediaType: request.mediaType,\n cmcdData,\n cmcdString: finalPayloadString\n });\n return {\n key: CMCD_REQUEST_FIELD_NAME,\n value: finalPayloadString\n };\n }\n\n return null;\n } catch (e) {\n return null;\n }\n }\n\n function _copyParameters(data, parameterNames) {\n const copiedData = {};\n for (let name of parameterNames) {\n if (data[name]) {\n copiedData[name] = data[name];\n }\n }\n return copiedData;\n }\n\n function getHeaderParameters(request) {\n try {\n if (settings.get().streaming.cmcd && settings.get().streaming.cmcd.enabled) {\n const cmcdData = _getCmcdData(request);\n const cmcdObjectHeader = _copyParameters(cmcdData, ['br', 'd', 'ot', 'tb']);\n const cmcdRequestHeader = _copyParameters(cmcdData, ['bl', 'dl', 'mtp', 'nor', 'nrr', 'su']);\n const cmcdStatusHeader = _copyParameters(cmcdData, ['bs', 'rtp']);\n const cmcdSessionHeader = _copyParameters(cmcdData, ['cid', 'pr', 'sf', 'sid', 'st', 'v']);\n const headers = {\n 'CMCD-Object': _buildFinalString(cmcdObjectHeader),\n 'CMCD-Request': _buildFinalString(cmcdRequestHeader),\n 'CMCD-Status': _buildFinalString(cmcdStatusHeader),\n 'CMCD-Session': _buildFinalString(cmcdSessionHeader)\n };\n\n eventBus.trigger(MetricsReportingEvents.CMCD_DATA_GENERATED, {\n url: request.url,\n mediaType: request.mediaType,\n cmcdData,\n headers\n });\n return headers;\n }\n\n return null;\n } catch (e) {\n return null;\n }\n }\n\n function _getCmcdData(request) {\n try {\n let cmcdData = null;\n\n if (request.type === HTTPRequest.MPD_TYPE) {\n return _getCmcdDataForMpd(request);\n } else if (request.type === HTTPRequest.MEDIA_SEGMENT_TYPE) {\n _initForMediaType(request.mediaType);\n return _getCmcdDataForMediaSegment(request);\n } else if (request.type === HTTPRequest.INIT_SEGMENT_TYPE) {\n return _getCmcdDataForInitSegment(request);\n } else if (request.type === HTTPRequest.OTHER_TYPE || request.type === HTTPRequest.XLINK_EXPANSION_TYPE) {\n return _getCmcdDataForOther(request);\n } else if (request.type === HTTPRequest.LICENSE) {\n return _getCmcdDataForLicense(request);\n }\n\n return cmcdData;\n } catch (e) {\n return null;\n }\n }\n\n function _getCmcdDataForLicense(request) {\n const data = _getGenericCmcdData(request);\n\n data.ot = OBJECT_TYPES.ENCRYPTION_KEY;\n\n return data;\n }\n\n function _getCmcdDataForMpd() {\n const data = _getGenericCmcdData();\n\n data.ot = OBJECT_TYPES.MANIFEST;\n\n return data;\n }\n\n function _getCmcdDataForMediaSegment(request) {\n const data = _getGenericCmcdData();\n const encodedBitrate = _getBitrateByRequest(request);\n const d = _getObjectDurationByRequest(request);\n const mtp = _getMeasuredThroughputByType(request.mediaType);\n const dl = _getDeadlineByType(request.mediaType);\n const bl = _getBufferLevelByType(request.mediaType);\n const tb = _getTopBitrateByType(request.mediaType);\n const pr = internalData.pr;\n\n const nextRequest = _probeNextRequest(request.mediaType);\n\n let ot;\n if (request.mediaType === Constants.VIDEO) ot = OBJECT_TYPES.VIDEO;\n if (request.mediaType === Constants.AUDIO) ot = OBJECT_TYPES.AUDIO;\n if (request.mediaType === Constants.TEXT) {\n if (request.mediaInfo.mimeType === 'application/mp4') {\n ot = OBJECT_TYPES.ISOBMFF_TEXT_TRACK;\n } else {\n ot = OBJECT_TYPES.CAPTION;\n }\n }\n\n let rtp = settings.get().streaming.cmcd.rtp;\n if (!rtp) {\n rtp = _calculateRtp(request);\n }\n data.rtp = rtp;\n\n if (nextRequest) {\n if (request.url !== nextRequest.url) {\n data.nor = encodeURIComponent(Utils.getRelativeUrl(request.url, nextRequest.url));\n } else if (nextRequest.range) {\n data.nrr = nextRequest.range;\n }\n }\n\n if (encodedBitrate) {\n data.br = encodedBitrate;\n }\n\n if (ot) {\n data.ot = ot;\n }\n\n if (!isNaN(d)) {\n data.d = d;\n }\n\n if (!isNaN(mtp)) {\n data.mtp = mtp;\n }\n\n if (!isNaN(dl)) {\n data.dl = dl;\n }\n\n if (!isNaN(bl)) {\n data.bl = bl;\n }\n\n if (!isNaN(tb)) {\n data.tb = tb;\n }\n\n if (!isNaN(pr) && pr !== 1) {\n data.pr = pr;\n }\n\n if (_bufferLevelStarved[request.mediaType]) {\n data.bs = true;\n _bufferLevelStarved[request.mediaType] = false;\n }\n\n if (_isStartup[request.mediaType] || !_initialMediaRequestsDone[request.mediaType]) {\n data.su = true;\n _isStartup[request.mediaType] = false;\n _initialMediaRequestsDone[request.mediaType] = true;\n }\n\n return data;\n }\n\n function _initForMediaType(mediaType) {\n\n if (!_initialMediaRequestsDone.hasOwnProperty(mediaType)) {\n _initialMediaRequestsDone[mediaType] = false;\n }\n\n if (!_isStartup.hasOwnProperty(mediaType)) {\n _isStartup[mediaType] = false;\n }\n\n if (!_bufferLevelStarved.hasOwnProperty(mediaType)) {\n _bufferLevelStarved[mediaType] = false;\n }\n }\n\n function _getCmcdDataForInitSegment() {\n const data = _getGenericCmcdData();\n\n data.ot = OBJECT_TYPES.INIT;\n data.su = true;\n\n return data;\n }\n\n function _getCmcdDataForOther() {\n const data = _getGenericCmcdData();\n\n data.ot = OBJECT_TYPES.OTHER;\n\n return data;\n }\n\n\n function _getGenericCmcdData() {\n const data = {};\n\n let cid = settings.get().streaming.cmcd.cid ? settings.get().streaming.cmcd.cid : internalData.cid;\n\n data.v = CMCD_VERSION;\n data.sid = settings.get().streaming.cmcd.sid ? settings.get().streaming.cmcd.sid : internalData.sid;\n\n data.sid = `${data.sid}`;\n\n if (cid) {\n data.cid = `${cid}`;\n }\n\n if (!isNaN(internalData.pr) && internalData.pr !== 1 && internalData.pr !== null) {\n data.pr = internalData.pr;\n }\n\n if (internalData.st) {\n data.st = internalData.st;\n }\n\n if (internalData.sf) {\n data.sf = internalData.sf;\n }\n\n return data;\n }\n\n function _getBitrateByRequest(request) {\n try {\n const quality = request.quality;\n const bitrateList = request.mediaInfo.bitrateList;\n\n return parseInt(bitrateList[quality].bandwidth / 1000);\n } catch (e) {\n return null;\n }\n }\n\n function _getTopBitrateByType(mediaType) {\n try {\n const info = abrController.getTopBitrateInfoFor(mediaType);\n return Math.round(info.bitrate / 1000);\n } catch (e) {\n return null;\n }\n }\n\n function _getObjectDurationByRequest(request) {\n try {\n return !isNaN(request.duration) ? Math.round(request.duration * 1000) : null;\n } catch (e) {\n return null;\n }\n }\n\n function _getMeasuredThroughputByType(mediaType) {\n try {\n return parseInt(abrController.getThroughputHistory().getSafeAverageThroughput(mediaType) / 100) * 100;\n } catch (e) {\n return null;\n }\n }\n\n function _getDeadlineByType(mediaType) {\n try {\n const playbackRate = internalData.pr;\n const bufferLevel = dashMetrics.getCurrentBufferLevel(mediaType);\n\n if (!isNaN(playbackRate) && !isNaN(bufferLevel)) {\n return parseInt((bufferLevel / playbackRate) * 10) * 100;\n }\n\n return null;\n } catch (e) {\n return null;\n }\n }\n\n function _getBufferLevelByType(mediaType) {\n try {\n const bufferLevel = dashMetrics.getCurrentBufferLevel(mediaType);\n\n if (!isNaN(bufferLevel)) {\n return parseInt(bufferLevel * 10) * 100;\n }\n\n return null;\n } catch (e) {\n return null;\n }\n }\n\n function _onPlaybackRateChanged(data) {\n try {\n internalData.pr = data.playbackRate;\n } catch (e) {\n\n }\n }\n\n function _onManifestLoaded(data) {\n try {\n const isDynamic = dashManifestModel.getIsDynamic(data.data);\n const st = isDynamic ? STREAM_TYPES.LIVE : STREAM_TYPES.VOD;\n const sf = data.protocol && data.protocol === 'MSS' ? STREAMING_FORMATS.MSS : STREAMING_FORMATS.DASH;\n\n internalData.st = `${st}`;\n internalData.sf = `${sf}`;\n } catch (e) {\n }\n }\n\n function _onBufferLevelStateChanged(data) {\n try {\n if (data.state && data.mediaType) {\n if (data.state === MediaPlayerEvents.BUFFER_EMPTY) {\n\n if (!_bufferLevelStarved[data.mediaType]) {\n _bufferLevelStarved[data.mediaType] = true;\n }\n if (!_isStartup[data.mediaType]) {\n _isStartup[data.mediaType] = true;\n }\n }\n }\n } catch (e) {\n\n }\n }\n\n function _onPlaybackSeeked() {\n for (let key in _bufferLevelStarved) {\n if (_bufferLevelStarved.hasOwnProperty(key)) {\n _bufferLevelStarved[key] = true;\n }\n }\n\n for (let key in _isStartup) {\n if (_isStartup.hasOwnProperty(key)) {\n _isStartup[key] = true;\n }\n }\n }\n\n function _buildFinalString(cmcdData) {\n try {\n if (!cmcdData) {\n return null;\n }\n const keys = Object.keys(cmcdData).sort((a, b) => a.localeCompare(b));\n const length = keys.length;\n\n let cmcdString = keys.reduce((acc, key, index) => {\n if (key === 'v' && cmcdData[key] === 1) return acc; // Version key should only be reported if it is != 1\n if (typeof cmcdData[key] === 'string' && key !== 'ot' && key !== 'sf' && key !== 'st') {\n acc += `${key}=${JSON.stringify(cmcdData[key])}`;\n } else {\n acc += `${key}=${cmcdData[key]}`;\n }\n if (index < length - 1) {\n acc += ',';\n }\n\n return acc;\n }, '');\n\n cmcdString = cmcdString.replace(/=true/g, '');\n\n // Remove last comma at the end\n cmcdString = cmcdString.replace(/,\\s*$/, '');\n\n return cmcdString;\n } catch (e) {\n return null;\n }\n }\n\n function _probeNextRequest(mediaType) {\n if (!streamProcessors || streamProcessors.length === 0) return;\n for (let streamProcessor of streamProcessors) {\n if (streamProcessor.getType() === mediaType) {\n return streamProcessor.probeNextRequest();\n }\n }\n }\n\n function _calculateRtp(request) {\n // Get the values we need\n let playbackRate = playbackController.getPlaybackRate();\n if (!playbackRate) playbackRate = 1;\n let { quality, mediaType, mediaInfo, duration } = request;\n let currentBufferLevel = _getBufferLevelByType(mediaType);\n if (currentBufferLevel === 0) currentBufferLevel = 500;\n let bitrate = mediaInfo.bitrateList[quality].bandwidth;\n\n // Calculate RTP\n let segmentSize = (bitrate * duration) / 1000; // Calculate file size in kilobits\n let timeToLoad = (currentBufferLevel / playbackRate) / 1000; // Calculate time available to load file in seconds\n let minBandwidth = segmentSize / timeToLoad; // Calculate the exact bandwidth required\n let rtpSafetyFactor = settings.get().streaming.cmcd.rtpSafetyFactor && !isNaN(settings.get().streaming.cmcd.rtpSafetyFactor) ? settings.get().streaming.cmcd.rtpSafetyFactor : RTP_SAFETY_FACTOR;\n let maxBandwidth = minBandwidth * rtpSafetyFactor; // Include a safety buffer\n\n let rtp = (parseInt(maxBandwidth / 100) + 1) * 100; // Round to the next multiple of 100\n\n return rtp;\n }\n\n function reset() {\n eventBus.off(MediaPlayerEvents.PLAYBACK_RATE_CHANGED, _onPlaybackRateChanged, this);\n eventBus.off(MediaPlayerEvents.MANIFEST_LOADED, _onManifestLoaded, this);\n eventBus.off(MediaPlayerEvents.BUFFER_LEVEL_STATE_CHANGED, _onBufferLevelStateChanged, instance);\n eventBus.off(MediaPlayerEvents.PLAYBACK_SEEKED, _onPlaybackSeeked, instance);\n\n _resetInitialSettings();\n }\n\n instance = {\n getQueryParameter,\n getHeaderParameters,\n setConfig,\n reset,\n initialize\n };\n\n setup();\n\n return instance;\n}\n\nCmcdModel.__dashjs_factory_name = 'CmcdModel';\nexport default FactoryMaker.getSingletonFactory(CmcdModel);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass UTCTiming {\n constructor() {\n // UTCTiming is a DescriptorType and doesn't have any additional fields\n this.schemeIdUri = '';\n this.value = '';\n }\n}\n\nexport default UTCTiming;","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass Event {\n constructor() {\n this.duration = NaN;\n this.presentationTime = NaN;\n this.id = NaN;\n this.messageData = '';\n this.eventStream = null;\n this.presentationTimeDelta = NaN; // Specific EMSG Box parameter\n }\n}\n\nexport default Event;","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport FactoryMaker from '../../core/FactoryMaker';\nimport deepEqual from 'fast-deep-equal';\n\n/**\n * @module ObjectUtils\n * @ignore\n * @description Provides utility functions for objects\n */\nfunction ObjectUtils() {\n\n let instance;\n\n /**\n * Returns true if objects are equal\n * @return {boolean}\n * @param {object} obj1\n * @param {object} obj2\n * @memberof module:ObjectUtils\n * @instance\n */\n function areEqual(obj1, obj2) {\n return deepEqual(obj1, obj2);\n }\n\n instance = {\n areEqual: areEqual\n };\n\n return instance;\n}\n\nObjectUtils.__dashjs_factory_name = 'ObjectUtils';\nexport default FactoryMaker.getSingletonFactory(ObjectUtils);\n","/*\n Copyright 2011-2013 Abdulla Abdurakhmanov\n Original sources are available at https://code.google.com/p/x2js/\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\n/*\n Further modified for dashjs to:\n - keep track of children nodes in order in attribute __children.\n - add type conversion matchers\n - re-add ignoreRoot\n - allow zero-length attributePrefix\n - don't add white-space text nodes\n - remove explicit RequireJS support\n*/\n\nfunction X2JS(config) {\n 'use strict';\n\n var VERSION = \"1.2.0\";\n\n config = config || {};\n initConfigDefaults();\n initRequiredPolyfills();\n\n function initConfigDefaults() {\n if(config.escapeMode === undefined) {\n config.escapeMode = true;\n }\n\n if (config.attributePrefix === undefined) {\n config.attributePrefix = \"_\";\n }\n\n config.arrayAccessForm = config.arrayAccessForm || \"none\";\n config.emptyNodeForm = config.emptyNodeForm || \"text\";\n\n if(config.enableToStringFunc === undefined) {\n config.enableToStringFunc = true;\n }\n config.arrayAccessFormPaths = config.arrayAccessFormPaths || [];\n if(config.skipEmptyTextNodesForObj === undefined) {\n config.skipEmptyTextNodesForObj = true;\n }\n if(config.stripWhitespaces === undefined) {\n config.stripWhitespaces = true;\n }\n config.datetimeAccessFormPaths = config.datetimeAccessFormPaths || [];\n\n if(config.useDoubleQuotes === undefined) {\n config.useDoubleQuotes = false;\n }\n\n config.xmlElementsFilter = config.xmlElementsFilter || [];\n config.jsonPropertiesFilter = config.jsonPropertiesFilter || [];\n\n if(config.keepCData === undefined) {\n config.keepCData = false;\n }\n\n if (config.ignoreRoot === undefined) {\n config.ignoreRoot = false;\n }\n }\n\n var DOMNodeTypes = {\n ELEMENT_NODE \t : 1,\n TEXT_NODE \t : 3,\n CDATA_SECTION_NODE : 4,\n COMMENT_NODE\t : 8,\n DOCUMENT_NODE \t : 9\n };\n\n function initRequiredPolyfills() {\n }\n\n function getNodeLocalName( node ) {\n var nodeLocalName = node.localName;\n if(nodeLocalName == null) // Yeah, this is IE!!\n nodeLocalName = node.baseName;\n if(nodeLocalName == null || nodeLocalName==\"\") // ==\"\" is IE too\n nodeLocalName = node.nodeName;\n return nodeLocalName;\n }\n\n function getNodePrefix(node) {\n return node.prefix;\n }\n\n function escapeXmlChars(str) {\n if(typeof(str) == \"string\")\n return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"').replace(/'/g, ''');\n else\n return str;\n }\n\n function unescapeXmlChars(str) {\n return str.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '\"').replace(/'/g, \"'\").replace(/&/g, '&');\n }\n\n function checkInStdFiltersArrayForm(stdFiltersArrayForm, obj, name, path) {\n var idx = 0;\n for(; idx < stdFiltersArrayForm.length; idx++) {\n var filterPath = stdFiltersArrayForm[idx];\n if( typeof filterPath === \"string\" ) {\n if(filterPath == path)\n break;\n }\n else\n if( filterPath instanceof RegExp) {\n if(filterPath.test(path))\n break;\n }\n else\n if( typeof filterPath === \"function\") {\n if(filterPath(obj, name, path))\n break;\n }\n }\n return idx!=stdFiltersArrayForm.length;\n }\n\n function toArrayAccessForm(obj, childName, path) {\n switch(config.arrayAccessForm) {\n case \"property\":\n if(!(obj[childName] instanceof Array))\n obj[childName+\"_asArray\"] = [obj[childName]];\n else\n obj[childName+\"_asArray\"] = obj[childName];\n break;\n /*case \"none\":\n break;*/\n }\n\n if(!(obj[childName] instanceof Array) && config.arrayAccessFormPaths.length > 0) {\n if(checkInStdFiltersArrayForm(config.arrayAccessFormPaths, obj, childName, path)) {\n obj[childName] = [obj[childName]];\n }\n }\n }\n\n function fromXmlDateTime(prop) {\n // Implementation based up on http://stackoverflow.com/questions/8178598/xml-datetime-to-javascript-date-object\n // Improved to support full spec and optional parts\n var bits = prop.split(/[-T:+Z]/g);\n\n var d = new Date(bits[0], bits[1]-1, bits[2]);\n var secondBits = bits[5].split(\"\\.\");\n d.setHours(bits[3], bits[4], secondBits[0]);\n if(secondBits.length>1)\n d.setMilliseconds(secondBits[1]);\n\n // Get supplied time zone offset in minutes\n if(bits[6] && bits[7]) {\n var offsetMinutes = bits[6] * 60 + Number(bits[7]);\n var sign = /\\d\\d-\\d\\d:\\d\\d$/.test(prop)? '-' : '+';\n\n // Apply the sign\n offsetMinutes = 0 + (sign == '-'? -1 * offsetMinutes : offsetMinutes);\n\n // Apply offset and local timezone\n d.setMinutes(d.getMinutes() - offsetMinutes - d.getTimezoneOffset())\n }\n else\n if(prop.indexOf(\"Z\", prop.length - 1) !== -1) {\n d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()));\n }\n\n // d is now a local time equivalent to the supplied time\n return d;\n }\n\n function checkFromXmlDateTimePaths(value, childName, fullPath) {\n if(config.datetimeAccessFormPaths.length > 0) {\n var path = fullPath.split(\"\\.#\")[0];\n if(checkInStdFiltersArrayForm(config.datetimeAccessFormPaths, value, childName, path)) {\n return fromXmlDateTime(value);\n }\n else\n return value;\n }\n else\n return value;\n }\n\n function checkXmlElementsFilter(obj, childType, childName, childPath) {\n if( childType == DOMNodeTypes.ELEMENT_NODE && config.xmlElementsFilter.length > 0) {\n return checkInStdFiltersArrayForm(config.xmlElementsFilter, obj, childName, childPath);\n }\n else\n return true;\n }\n\n function parseDOMChildren( node, path ) {\n if(node.nodeType == DOMNodeTypes.DOCUMENT_NODE) {\n var result = new Object;\n var nodeChildren = node.childNodes;\n // Alternative for firstElementChild which is not supported in some environments\n for(var cidx=0; cidx <nodeChildren.length; cidx++) {\n var child = nodeChildren[cidx];\n if(child.nodeType == DOMNodeTypes.ELEMENT_NODE) {\n if (config.ignoreRoot) {\n result = parseDOMChildren(child);\n } else {\n result = {};\n var childName = getNodeLocalName(child);\n result[childName] = parseDOMChildren(child);\n }\n }\n }\n return result;\n }\n else\n if(node.nodeType == DOMNodeTypes.ELEMENT_NODE) {\n var result = new Object;\n result.__cnt=0;\n\n var children = [];\n var nodeChildren = node.childNodes;\n\n // Children nodes\n for(var cidx=0; cidx <nodeChildren.length; cidx++) {\n var child = nodeChildren[cidx];\n var childName = getNodeLocalName(child);\n\n if(child.nodeType!= DOMNodeTypes.COMMENT_NODE) {\n var childPath = path+\".\"+childName;\n if (checkXmlElementsFilter(result,child.nodeType,childName,childPath)) {\n result.__cnt++;\n if(result[childName] == null) {\n var c = parseDOMChildren(child, childPath);\n if (childName != \"#text\" || /[^\\s]/.test(c)) {\n var o = {};\n o[childName] = c;\n children.push(o);\n }\n result[childName] = c;\n toArrayAccessForm(result, childName, childPath);\n }\n else {\n if(result[childName] != null) {\n if( !(result[childName] instanceof Array)) {\n result[childName] = [result[childName]];\n toArrayAccessForm(result, childName, childPath);\n }\n }\n\n var c = parseDOMChildren(child, childPath);\n if (childName != \"#text\" || /[^\\s]/.test(c)) { // Don't add white-space text nodes\n var o = {};\n o[childName] = c;\n children.push( o );\n }\n (result[childName])[result[childName].length] = c;\n }\n }\n }\n }\n\n result.__children = children;\n\n // Attributes\n var nodeLocalName = getNodeLocalName(node)\n for(var aidx=0; aidx <node.attributes.length; aidx++) {\n var attr = node.attributes[aidx];\n result.__cnt++;\n\n var value2 = attr.value;\n for(var m=0, ml=config.matchers.length; m < ml; m++) {\n var matchobj = config.matchers[m];\n if (matchobj.test(attr, nodeLocalName))\n value2 = matchobj.converter(attr.value);\n }\n\n result[config.attributePrefix+attr.name]=value2;\n }\n\n // Node namespace prefix\n var nodePrefix = getNodePrefix(node);\n if(nodePrefix!=null && nodePrefix!=\"\") {\n result.__cnt++;\n result.__prefix=nodePrefix;\n }\n\n if(result[\"#text\"]!=null) {\n result.__text = result[\"#text\"];\n if(result.__text instanceof Array) {\n result.__text = result.__text.join(\"\\n\");\n }\n //if(config.escapeMode)\n //\tresult.__text = unescapeXmlChars(result.__text);\n if(config.stripWhitespaces)\n result.__text = result.__text.trim();\n delete result[\"#text\"];\n if(config.arrayAccessForm==\"property\")\n delete result[\"#text_asArray\"];\n result.__text = checkFromXmlDateTimePaths(result.__text, childName, path+\".\"+childName);\n }\n if(result[\"#cdata-section\"]!=null) {\n result.__cdata = result[\"#cdata-section\"];\n delete result[\"#cdata-section\"];\n if(config.arrayAccessForm==\"property\")\n delete result[\"#cdata-section_asArray\"];\n }\n\n if( result.__cnt == 0 && config.emptyNodeForm==\"text\" ) {\n result = '';\n }\n else\n if( result.__cnt == 1 && result.__text!=null ) {\n result = result.__text;\n }\n else\n if( result.__cnt == 1 && result.__cdata!=null && !config.keepCData ) {\n result = result.__cdata;\n }\n else\n if ( result.__cnt > 1 && result.__text!=null && config.skipEmptyTextNodesForObj) {\n if( (config.stripWhitespaces && result.__text==\"\") || (result.__text.trim()==\"\")) {\n delete result.__text;\n }\n }\n delete result.__cnt;\n\n if( config.enableToStringFunc && (result.__text!=null || result.__cdata!=null )) {\n result.toString = function() {\n return (this.__text!=null? this.__text:'')+( this.__cdata!=null ? this.__cdata:'');\n };\n }\n\n return result;\n }\n else\n if(node.nodeType == DOMNodeTypes.TEXT_NODE || node.nodeType == DOMNodeTypes.CDATA_SECTION_NODE) {\n return node.nodeValue;\n }\n }\n\n function startTag(jsonObj, element, attrList, closed) {\n var resultStr = \"<\"+ ( (jsonObj!=null && jsonObj.__prefix!=null)? (jsonObj.__prefix+\":\"):\"\") + element;\n if(attrList!=null) {\n for(var aidx = 0; aidx < attrList.length; aidx++) {\n var attrName = attrList[aidx];\n var attrVal = jsonObj[attrName];\n if(config.escapeMode)\n attrVal=escapeXmlChars(attrVal);\n resultStr+=\" \"+attrName.substr(config.attributePrefix.length)+\"=\";\n if(config.useDoubleQuotes)\n resultStr+='\"'+attrVal+'\"';\n else\n resultStr+=\"'\"+attrVal+\"'\";\n }\n }\n if(!closed)\n resultStr+=\">\";\n else\n resultStr+=\"/>\";\n return resultStr;\n }\n\n function endTag(jsonObj,elementName) {\n return \"</\"+ (jsonObj.__prefix!=null? (jsonObj.__prefix+\":\"):\"\")+elementName+\">\";\n }\n\n function endsWith(str, suffix) {\n return str.indexOf(suffix, str.length - suffix.length) !== -1;\n }\n\n function jsonXmlSpecialElem ( jsonObj, jsonObjField ) {\n if((config.arrayAccessForm==\"property\" && endsWith(jsonObjField.toString(),(\"_asArray\")))\n || jsonObjField.toString().indexOf(config.attributePrefix)==0\n || jsonObjField.toString().indexOf(\"__\")==0\n || (jsonObj[jsonObjField] instanceof Function) )\n return true;\n else\n return false;\n }\n\n function jsonXmlElemCount ( jsonObj ) {\n var elementsCnt = 0;\n if(jsonObj instanceof Object ) {\n for( var it in jsonObj ) {\n if(jsonXmlSpecialElem ( jsonObj, it) )\n continue;\n elementsCnt++;\n }\n }\n return elementsCnt;\n }\n\n function checkJsonObjPropertiesFilter(jsonObj, propertyName, jsonObjPath) {\n return config.jsonPropertiesFilter.length == 0\n || jsonObjPath==\"\"\n || checkInStdFiltersArrayForm(config.jsonPropertiesFilter, jsonObj, propertyName, jsonObjPath);\n }\n\n function parseJSONAttributes ( jsonObj ) {\n var attrList = [];\n if(jsonObj instanceof Object ) {\n for( var ait in jsonObj ) {\n if(ait.toString().indexOf(\"__\")== -1 && ait.toString().indexOf(config.attributePrefix)==0) {\n attrList.push(ait);\n }\n }\n }\n return attrList;\n }\n\n function parseJSONTextAttrs ( jsonTxtObj ) {\n var result =\"\";\n\n if(jsonTxtObj.__cdata!=null) {\n result+=\"<![CDATA[\"+jsonTxtObj.__cdata+\"]]>\";\n }\n\n if(jsonTxtObj.__text!=null) {\n if(config.escapeMode)\n result+=escapeXmlChars(jsonTxtObj.__text);\n else\n result+=jsonTxtObj.__text;\n }\n return result;\n }\n\n function parseJSONTextObject ( jsonTxtObj ) {\n var result =\"\";\n\n if( jsonTxtObj instanceof Object ) {\n result+=parseJSONTextAttrs ( jsonTxtObj );\n }\n else\n if(jsonTxtObj!=null) {\n if(config.escapeMode)\n result+=escapeXmlChars(jsonTxtObj);\n else\n result+=jsonTxtObj;\n }\n\n return result;\n }\n\n function getJsonPropertyPath(jsonObjPath, jsonPropName) {\n if (jsonObjPath===\"\") {\n return jsonPropName;\n }\n else\n return jsonObjPath+\".\"+jsonPropName;\n }\n\n function parseJSONArray ( jsonArrRoot, jsonArrObj, attrList, jsonObjPath ) {\n var result = \"\";\n if(jsonArrRoot.length == 0) {\n result+=startTag(jsonArrRoot, jsonArrObj, attrList, true);\n }\n else {\n for(var arIdx = 0; arIdx < jsonArrRoot.length; arIdx++) {\n result+=startTag(jsonArrRoot[arIdx], jsonArrObj, parseJSONAttributes(jsonArrRoot[arIdx]), false);\n result+=parseJSONObject(jsonArrRoot[arIdx], getJsonPropertyPath(jsonObjPath,jsonArrObj));\n result+=endTag(jsonArrRoot[arIdx],jsonArrObj);\n }\n }\n return result;\n }\n\n function parseJSONObject ( jsonObj, jsonObjPath ) {\n var result = \"\";\n\n var elementsCnt = jsonXmlElemCount ( jsonObj );\n\n if(elementsCnt > 0) {\n for( var it in jsonObj ) {\n\n if(jsonXmlSpecialElem ( jsonObj, it) || (jsonObjPath!=\"\" && !checkJsonObjPropertiesFilter(jsonObj, it, getJsonPropertyPath(jsonObjPath,it))) )\n continue;\n\n var subObj = jsonObj[it];\n\n var attrList = parseJSONAttributes( subObj )\n\n if(subObj == null || subObj == undefined) {\n result+=startTag(subObj, it, attrList, true);\n }\n else\n if(subObj instanceof Object) {\n\n if(subObj instanceof Array) {\n result+=parseJSONArray( subObj, it, attrList, jsonObjPath );\n }\n else if(subObj instanceof Date) {\n result+=startTag(subObj, it, attrList, false);\n result+=subObj.toISOString();\n result+=endTag(subObj,it);\n }\n else {\n var subObjElementsCnt = jsonXmlElemCount ( subObj );\n if(subObjElementsCnt > 0 || subObj.__text!=null || subObj.__cdata!=null) {\n result+=startTag(subObj, it, attrList, false);\n result+=parseJSONObject(subObj, getJsonPropertyPath(jsonObjPath,it));\n result+=endTag(subObj,it);\n }\n else {\n result+=startTag(subObj, it, attrList, true);\n }\n }\n }\n else {\n result+=startTag(subObj, it, attrList, false);\n result+=parseJSONTextObject(subObj);\n result+=endTag(subObj,it);\n }\n }\n }\n result+=parseJSONTextObject(jsonObj);\n\n return result;\n }\n\n this.parseXmlString = function(xmlDocStr) {\n var isIEParser = window.ActiveXObject || \"ActiveXObject\" in window;\n if (xmlDocStr === undefined) {\n return null;\n }\n var xmlDoc;\n if (window.DOMParser) {\n var parser=new window.DOMParser();\n var parsererrorNS = null;\n try {\n xmlDoc = parser.parseFromString( xmlDocStr, \"text/xml\" );\n if(xmlDoc.getElementsByTagNameNS(\"*\", \"parsererror\").length > 0) {\n xmlDoc = null;\n }\n }\n catch(err) {\n xmlDoc = null;\n }\n }\n else {\n // IE :(\n if(xmlDocStr.indexOf(\"<?\")==0) {\n xmlDocStr = xmlDocStr.substr( xmlDocStr.indexOf(\"?>\") + 2 );\n }\n xmlDoc=new ActiveXObject(\"Microsoft.XMLDOM\");\n xmlDoc.async=\"false\";\n xmlDoc.loadXML(xmlDocStr);\n }\n return xmlDoc;\n };\n\n this.asArray = function(prop) {\n if (prop === undefined || prop == null)\n return [];\n else\n if(prop instanceof Array)\n return prop;\n else\n return [prop];\n };\n\n this.toXmlDateTime = function(dt) {\n if(dt instanceof Date)\n return dt.toISOString();\n else\n if(typeof(dt) === 'number' )\n return new Date(dt).toISOString();\n else\n return null;\n };\n\n this.asDateTime = function(prop) {\n if(typeof(prop) == \"string\") {\n return fromXmlDateTime(prop);\n }\n else\n return prop;\n };\n\n this.xml2json = function (xmlDoc) {\n return parseDOMChildren ( xmlDoc );\n };\n\n this.xml_str2json = function (xmlDocStr) {\n var xmlDoc = this.parseXmlString(xmlDocStr);\n if(xmlDoc!=null)\n return this.xml2json(xmlDoc);\n else\n return null;\n };\n\n this.json2xml_str = function (jsonObj) {\n return parseJSONObject ( jsonObj, \"\" );\n };\n\n this.json2xml = function (jsonObj) {\n var xmlDocStr = this.json2xml_str (jsonObj);\n return this.parseXmlString(xmlDocStr);\n };\n\n this.getVersion = function () {\n return VERSION;\n };\n}\n\nexport default X2JS;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Settings from '../../core/Settings';\nimport Constants from '../constants/Constants';\n\n/**\n * @module FetchLoader\n * @ignore\n * @description Manages download of resources via HTTP using fetch.\n * @param {Object} cfg - dependencies from parent\n */\nfunction FetchLoader(cfg) {\n\n cfg = cfg || {};\n const context = this.context;\n const requestModifier = cfg.requestModifier;\n const lowLatencyThroughputModel = cfg.lowLatencyThroughputModel;\n const boxParser = cfg.boxParser;\n const settings = Settings(context).getInstance();\n let instance, dashMetrics;\n\n function setup(cfg) {\n dashMetrics = cfg.dashMetrics;\n }\n\n function load(httpRequest) {\n\n // Variables will be used in the callback functions\n const requestStartTime = new Date();\n const request = httpRequest.request;\n\n const headers = new Headers(); /*jshint ignore:line*/\n if (request.range) {\n headers.append('Range', 'bytes=' + request.range);\n }\n\n if (httpRequest.headers) {\n for (let header in httpRequest.headers) {\n let value = httpRequest.headers[header];\n if (value) {\n headers.append(header, value);\n }\n }\n }\n\n if (!request.requestStartDate) {\n request.requestStartDate = requestStartTime;\n }\n\n if (requestModifier) {\n // modifyRequestHeader expects a XMLHttpRequest object so,\n // to keep backward compatibility, we should expose a setRequestHeader method\n // TODO: Remove RequestModifier dependency on XMLHttpRequest object and define\n // a more generic way to intercept/modify requests\n requestModifier.modifyRequestHeader({\n setRequestHeader: function (header, value) {\n headers.append(header, value);\n }\n });\n }\n\n let abortController;\n if (typeof window.AbortController === 'function') {\n abortController = new AbortController(); /*jshint ignore:line*/\n httpRequest.abortController = abortController;\n abortController.signal.onabort = httpRequest.onabort;\n }\n\n const reqOptions = {\n method: httpRequest.method,\n headers: headers,\n credentials: httpRequest.withCredentials ? 'include' : undefined,\n signal: abortController ? abortController.signal : undefined\n };\n\n const calculationMode = settings.get().streaming.abr.fetchThroughputCalculationMode;\n const requestTime = Date.now();\n let throughputCapacityDelayMS = 0;\n\n new Promise((resolve) => {\n if (calculationMode === Constants.ABR_FETCH_THROUGHPUT_CALCULATION_AAST && lowLatencyThroughputModel) {\n throughputCapacityDelayMS = lowLatencyThroughputModel.getThroughputCapacityDelayMS(request, dashMetrics.getCurrentBufferLevel(request.mediaType) * 1000);\n if (throughputCapacityDelayMS) {\n // safely delay the \"fetch\" call a bit to be able to meassure the throughput capacity of the line.\n // this will lead to first few chunks downloaded at max network speed\n return setTimeout(resolve, throughputCapacityDelayMS);\n }\n }\n resolve();\n })\n .then(() => {\n let markBeforeFetch = Date.now();\n\n fetch(httpRequest.url, reqOptions).then(function (response) {\n if (!httpRequest.response) {\n httpRequest.response = {};\n }\n httpRequest.response.status = response.status;\n httpRequest.response.statusText = response.statusText;\n httpRequest.response.responseURL = response.url;\n\n if (!response.ok) {\n httpRequest.onerror();\n }\n\n let responseHeaders = '';\n for (const key of response.headers.keys()) {\n responseHeaders += key + ': ' + response.headers.get(key) + '\\r\\n';\n }\n httpRequest.response.responseHeaders = responseHeaders;\n\n if (!response.body) {\n // Fetch returning a ReadableStream response body is not currently supported by all browsers.\n // Browser compatibility: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\n // If it is not supported, returning the whole segment when it's ready (as xhr)\n return response.arrayBuffer().then(function (buffer) {\n httpRequest.response.response = buffer;\n const event = {\n loaded: buffer.byteLength,\n total: buffer.byteLength,\n stream: false\n };\n httpRequest.progress(event);\n httpRequest.onload();\n httpRequest.onend();\n return;\n });\n }\n\n const totalBytes = parseInt(response.headers.get('Content-Length'), 10);\n let bytesReceived = 0;\n let signaledFirstByte = false;\n let remaining = new Uint8Array();\n let offset = 0;\n\n if (calculationMode === Constants.ABR_FETCH_THROUGHPUT_CALCULATION_AAST && lowLatencyThroughputModel) {\n let markA = markBeforeFetch;\n let markB = 0;\n\n function fetchMeassurement(stream) {\n const reader = stream.getReader();\n const measurement = [];\n\n reader.read().then(function processFetch(args) {\n const value = args.value;\n const done = args.done;\n markB = Date.now()\n\n if (value && value.length) {\n const chunkDownloadDurationMS = markB - markA;\n const chunkBytes = value.length;\n measurement.push({\n chunkDownloadTimeRelativeMS: markB - markBeforeFetch,\n chunkDownloadDurationMS,\n chunkBytes,\n kbps: Math.round(8 * chunkBytes / (chunkDownloadDurationMS / 1000)),\n bufferLevel: dashMetrics.getCurrentBufferLevel(request.mediaType)\n });\n }\n\n if (done) {\n\n const fetchDuration = markB - markBeforeFetch;\n const bytesAllChunks = measurement.reduce((prev, curr) => prev + curr.chunkBytes, 0);\n\n lowLatencyThroughputModel.addMeasurement(request, fetchDuration, measurement, requestTime, throughputCapacityDelayMS, responseHeaders);\n\n httpRequest.progress({\n loaded: bytesAllChunks,\n total: bytesAllChunks,\n lengthComputable: true,\n time: lowLatencyThroughputModel.getEstimatedDownloadDurationMS(request),\n stream: true\n });\n return;\n }\n markA = Date.now();\n return reader.read().then(processFetch);\n });\n }\n // tee'ing streams is supported by all current major browsers\n // https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/tee\n const [forMeasure, forConsumer] = response.body.tee();\n fetchMeassurement(forMeasure);\n httpRequest.reader = forConsumer.getReader();\n } else {\n httpRequest.reader = response.body.getReader();\n }\n\n let downloadedData = [];\n let startTimeData = [];\n let endTimeData = [];\n let lastChunkWasFinished = true;\n\n\n const processResult = function ({ value, done }) { // Bug fix Parse whenever data is coming [value] better than 1ms looking that increase CPU\n if (done) {\n if (remaining) {\n if (calculationMode !== Constants.ABR_FETCH_THROUGHPUT_CALCULATION_AAST) {\n // If there is pending data, call progress so network metrics\n // are correctly generated\n // Same structure as https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestEventTarget/\n let calculatedThroughput = null;\n if (calculationMode === Constants.ABR_FETCH_THROUGHPUT_CALCULATION_MOOF_PARSING) {\n calculatedThroughput = calculateThroughputByChunkData(startTimeData, endTimeData);\n }\n\n httpRequest.progress({\n loaded: bytesReceived,\n total: isNaN(totalBytes) ? bytesReceived : totalBytes,\n lengthComputable: true,\n time: calculateDownloadedTime(downloadedData, bytesReceived),\n throughput: calculatedThroughput,\n stream: true\n });\n }\n\n httpRequest.response.response = remaining.buffer;\n }\n httpRequest.onload();\n httpRequest.onend();\n return;\n }\n\n if (value && value.length > 0) {\n remaining = concatTypedArray(remaining, value);\n bytesReceived += value.length;\n\n downloadedData.push({\n ts: Date.now(),\n bytes: value.length\n });\n\n if (calculationMode === Constants.ABR_FETCH_THROUGHPUT_CALCULATION_MOOF_PARSING && lastChunkWasFinished) {\n // Parse the payload and capture the the 'moof' box\n const boxesInfo = boxParser.findLastTopIsoBoxCompleted(['moof'], remaining, offset);\n if (boxesInfo.found) {\n // Store the beginning time of each chunk download in array StartTimeData\n lastChunkWasFinished = false;\n startTimeData.push({\n ts: performance.now(), /* jshint ignore:line */\n bytes: value.length\n });\n }\n }\n\n const boxesInfo = boxParser.findLastTopIsoBoxCompleted(['moov', 'mdat'], remaining, offset);\n if (boxesInfo.found) {\n const end = boxesInfo.lastCompletedOffset + boxesInfo.size;\n\n // Store the end time of each chunk download with its size in array EndTimeData\n if (calculationMode === Constants.ABR_FETCH_THROUGHPUT_CALCULATION_MOOF_PARSING && !lastChunkWasFinished) {\n lastChunkWasFinished = true;\n endTimeData.push({\n ts: performance.now(), /* jshint ignore:line */\n bytes: remaining.length\n });\n }\n\n // If we are going to pass full buffer, avoid copying it and pass\n // complete buffer. Otherwise clone the part of the buffer that is completed\n // and adjust remaining buffer. A clone is needed because ArrayBuffer of a typed-array\n // keeps a reference to the original data\n let data;\n if (end === remaining.length) {\n data = remaining;\n remaining = new Uint8Array();\n } else {\n data = new Uint8Array(remaining.subarray(0, end));\n remaining = remaining.subarray(end);\n }\n // Announce progress but don't track traces. Throughput measures are quite unstable\n // when they are based in small amount of data\n httpRequest.progress({\n data: data.buffer,\n lengthComputable: false,\n noTrace: true\n });\n\n offset = 0;\n } else {\n offset = boxesInfo.lastCompletedOffset;\n // Call progress so it generates traces that will be later used to know when the first byte\n // were received\n if (!signaledFirstByte) {\n httpRequest.progress({\n lengthComputable: false,\n noTrace: true\n });\n signaledFirstByte = true;\n }\n }\n }\n read(httpRequest, processResult);\n };\n read(httpRequest, processResult);\n })\n .catch(function (e) {\n if (httpRequest.onerror) {\n httpRequest.onerror(e);\n }\n });\n });\n }\n\n function read(httpRequest, processResult) {\n httpRequest.reader.read()\n .then(processResult)\n .catch(function (e) {\n if (httpRequest.onerror && httpRequest.response.status === 200) {\n // Error, but response code is 200, trigger error\n httpRequest.onerror(e);\n }\n });\n }\n\n function concatTypedArray(remaining, data) {\n if (remaining.length === 0) {\n return data;\n }\n const result = new Uint8Array(remaining.length + data.length);\n result.set(remaining);\n result.set(data, remaining.length);\n return result;\n }\n\n function abort(request) {\n if (request.abortController) {\n // For firefox and edge\n request.abortController.abort();\n } else if (request.reader) {\n // For Chrome\n try {\n request.reader.cancel();\n request.onabort();\n } catch (e) {\n // throw exceptions (TypeError) when reader was previously closed,\n // for example, because a network issue\n }\n }\n }\n\n function calculateDownloadedTime(downloadedData, bytesReceived) {\n try {\n downloadedData = downloadedData.filter(data => data.bytes > ((bytesReceived / 4) / downloadedData.length));\n if (downloadedData.length > 1) {\n let time = 0;\n const avgTimeDistance = (downloadedData[downloadedData.length - 1].ts - downloadedData[0].ts) / downloadedData.length;\n downloadedData.forEach((data, index) => {\n // To be counted the data has to be over a threshold\n const next = downloadedData[index + 1];\n if (next) {\n const distance = next.ts - data.ts;\n time += distance < avgTimeDistance ? distance : 0;\n }\n });\n return time;\n }\n return null;\n } catch (e) {\n return null;\n }\n }\n\n function calculateThroughputByChunkData(startTimeData, endTimeData) {\n try {\n let datum, datumE;\n // Filter the last chunks in a segment in both arrays [StartTimeData and EndTimeData]\n datum = startTimeData.filter((data, i) => i < startTimeData.length - 1);\n datumE = endTimeData.filter((dataE, i) => i < endTimeData.length - 1);\n let chunkThroughputs = [];\n // Compute the average throughput of the filtered chunk data\n if (datum.length > 1) {\n let shortDurationBytesReceived = 0;\n let shortDurationStartTime = 0;\n for (let i = 0; i < datum.length; i++) {\n if (datum[i] && datumE[i]) {\n let chunkDownloadTime = datumE[i].ts - datum[i].ts;\n if (chunkDownloadTime > 1) {\n chunkThroughputs.push((8 * datumE[i].bytes) / chunkDownloadTime);\n } else {\n if (shortDurationStartTime === 0) {\n shortDurationStartTime = datum[i].ts;\n }\n let cumulatedChunkDownloadTime = datumE[i].ts - shortDurationStartTime;\n if (cumulatedChunkDownloadTime > 1) {\n chunkThroughputs.push((8 * shortDurationBytesReceived) / cumulatedChunkDownloadTime);\n shortDurationBytesReceived = 0;\n shortDurationStartTime = 0;\n } else {\n // continue cumulating short duration data\n shortDurationBytesReceived += datumE[i].bytes;\n }\n }\n }\n }\n\n if (chunkThroughputs.length > 0) {\n const sumOfChunkThroughputs = chunkThroughputs.reduce((a, b) => a + b, 0);\n return sumOfChunkThroughputs / chunkThroughputs.length;\n }\n }\n\n return null;\n } catch (e) {\n return null;\n }\n }\n\n instance = {\n load: load,\n abort: abort,\n calculateDownloadedTime: calculateDownloadedTime,\n setup\n };\n\n return instance;\n}\n\nFetchLoader.__dashjs_factory_name = 'FetchLoader';\n\nconst factory = FactoryMaker.getClassFactory(FetchLoader);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Debug from '../../core/Debug';\nimport FactoryMaker from '../../core/FactoryMaker';\n\nfunction LowLatencyThroughputModel() {\n\n const LLTM_MAX_MEASUREMENTS = 10;\n // factor (<1) is used to reduce the real needed download time when at very bleeding live edge\n const LLTM_SEMI_OPTIMISTIC_ESTIMATE_FACTOR = 0.8;\n const LLTM_OPTIMISTIC_ESTIMATE_FACTOR = 0.6;\n\n const LLTM_SLOW_SEGMENT_DOWNLOAD_TOLERANCE = 1.05;\n const LLTM_MAX_DELAY_MS = 250;\n\n const context = this.context;\n let instance;\n let logger;\n let measurements = {};\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n }\n\n /**\n * Linear regression with least squares method to get a trend function for buffer lavel at chunk receive timestamps\n * @param {*} chunkMeasurements\n * @returns linear trend function\n */\n function createBufferLevelTrendFunction(chunkMeasurements) {\n const result = {};\n\n let sumX = 0\n let sumY = 0\n let sumXY = 0\n let sumXSq = 0\n const N = chunkMeasurements.length\n\n\n for (var i = 0; i < N; ++i) {\n sumX += chunkMeasurements[i].chunkDownloadTimeRelativeMS;\n sumY += chunkMeasurements[i].bufferLevel;\n sumXY += chunkMeasurements[i].chunkDownloadTimeRelativeMS * chunkMeasurements[i].bufferLevel;\n sumXSq += chunkMeasurements[i].chunkDownloadTimeRelativeMS * chunkMeasurements[i].chunkDownloadTimeRelativeMS\n }\n\n result.m = ((sumXY - sumX * sumY / N)) / (sumXSq - sumX * sumX / N)\n result.b = sumY / N - result.m * sumX / N\n\n return function (x) {\n return result.m * x + result.b\n }\n }\n\n function isBufferSafeAndStable(lastMeasurements) {\n let isBufferSafeAndStable = true;\n let lastBitrate;\n const aveBufferLevelLastSegements = lastMeasurements.reduce((prev, curr) => prev + curr.bufferLevelAtSegmentEnd, 0) / lastMeasurements.length;\n lastMeasurements.forEach(m => {\n // inner segment buffer stability\n if (Math.abs(m.bufferLevelAtSegmentEnd / m.bufferLevelAtSegmentStart) < 0.95) {\n isBufferSafeAndStable = false;\n }\n\n // inter segment buffer stability\n if (m.bufferLevelAtSegmentEnd / aveBufferLevelLastSegements < 0.8) {\n isBufferSafeAndStable = false;\n }\n\n // representation bitrate remained at least constant\n if (!lastBitrate) {\n lastBitrate = m.bitrate;\n } else if (lastBitrate > m.bitrate) {\n isBufferSafeAndStable = false;\n }\n });\n return isBufferSafeAndStable;\n }\n\n /**\n * Based on the MPD, timing and buffer information of the last recent segments and their chunks\n * the most stable download time (in milliseconds) is calculated.\n * @param {*} request HTTPLoader request object\n * @returns download time in milliseconds of last fetched segment\n */\n function getEstimatedDownloadDurationMS(request) {\n const lastMeasurement = measurements[request.mediaType].slice(-1).pop();\n const lastThreeMeasurements = measurements[request.mediaType].slice(-3)\n\n // calculate and remember the buffer level trend during the last fetched segment\n const lastChunkRelativeTimeMS = lastMeasurement.chunkMeasurements.slice(-1).pop().chunkDownloadTimeRelativeMS;\n lastMeasurement.bufferLevelAtSegmentStart = lastMeasurement.getEstimatedBufferLevel(lastChunkRelativeTimeMS / 2);\n lastMeasurement.bufferLevelAtSegmentEnd = lastMeasurement.getEstimatedBufferLevel(lastChunkRelativeTimeMS);\n\n const isBufferStable = isBufferSafeAndStable(lastThreeMeasurements);\n\n const selectedOptimisticFactor = isBufferStable ? LLTM_OPTIMISTIC_ESTIMATE_FACTOR : LLTM_SEMI_OPTIMISTIC_ESTIMATE_FACTOR;\n\n // fetch duration was longer than segment duration, but buffer was stable\n if (lastMeasurement.isBufferStable && lastMeasurement.segDurationMS * LLTM_SLOW_SEGMENT_DOWNLOAD_TOLERANCE < lastMeasurement.fetchDownloadDurationMS) {\n return lastMeasurement.fetchDownloadDurationMS;\n }\n // buffer is drying or fetch took too long\n if (!isBufferStable || lastMeasurement.segDurationMS < lastMeasurement.fetchDownloadDurationMS) {\n return lastMeasurement.fetchDownloadDurationMS * LLTM_SEMI_OPTIMISTIC_ESTIMATE_FACTOR;\n }\n\n // did we requested a fully available segment? -> most accurate throughput calculation\n // we use adjusted availability start time to decide\n // Note: this \"download mode\" usually happens at startup and if requests are delayed artificially\n if (lastMeasurement.adjustedAvailabilityStartTimeMS <= (lastMeasurement.requestTimeMS + lastMeasurement.throughputCapacityDelayMS) - lastMeasurement.segDurationMS) {\n return lastMeasurement.fetchDownloadDurationMS * LLTM_SEMI_OPTIMISTIC_ESTIMATE_FACTOR;\n }\n\n // get all chunks that have been downloaded before fetch reached bleeding live edge\n // the remaining chunks loaded at production rate we will approximated\n const chunkAvailablePeriod = (lastMeasurement.requestTimeMS + lastMeasurement.throughputCapacityDelayMS) - lastMeasurement.adjustedAvailabilityStartTimeMS;\n let chunkBytesBBLE = 0; // BBLE -> Before bleeding live edge\n let chunkDownloadtimeMSBBLE = 0;\n let chunkCount = 0;\n for (let index = 0; index < lastMeasurement.chunkMeasurements.length; index++) {\n const chunk = lastMeasurement.chunkMeasurements[index];\n if (chunkAvailablePeriod < chunkDownloadtimeMSBBLE + chunk.chunkDownloadDurationMS) {\n break;\n }\n chunkDownloadtimeMSBBLE += chunk.chunkDownloadDurationMS;\n chunkBytesBBLE += chunk.chunkBytes;\n chunkCount++;\n }\n\n if (chunkAvailablePeriod < 0) {\n logger.warn('request time was before adjusted availibitly start time');\n }\n\n // there have to be some chunks available (20% of max count)\n // otherwise we are at bleeding live edge and the few chunks are insufficient to estimate correctly\n if (chunkBytesBBLE && chunkDownloadtimeMSBBLE && chunkCount > lastMeasurement.chunkMeasurements.length * 0.2) {\n const downloadThroughput = chunkBytesBBLE / chunkDownloadtimeMSBBLE; // bytes per millesecond\n const estimatedDownloadtimeMS = lastMeasurement.segmentBytes / downloadThroughput;\n // if real download was shorter then report this incl. semi optimistical estimate factor\n if (lastMeasurement.fetchDownloadDurationMS < estimatedDownloadtimeMS) {\n return lastMeasurement.fetchDownloadDurationMS * selectedOptimisticFactor;\n }\n return estimatedDownloadtimeMS * selectedOptimisticFactor;\n }\n\n // when we are to tight at live edge and it's stable then\n // we start to optimistically estimate download time\n // in such a way that a switch to next rep will be possible\n // optimistical estimate: assume download was fast enough for next higher rendition\n let nextHigherBitrate = lastMeasurement.bitrate;\n lastMeasurement.bitrateList.some(b => {\n if (b.bandwidth > lastMeasurement.bitrate) {\n nextHigherBitrate = b.bandwidth;\n return true;\n }\n });\n // already highest bitrate?\n\n if (nextHigherBitrate === lastMeasurement.bitrate) {\n return lastMeasurement.fetchDownloadDurationMS * selectedOptimisticFactor;\n }\n return selectedOptimisticFactor * lastMeasurement.segmentBytes * 8 * 1000 / nextHigherBitrate;\n }\n\n /**\n * Get calculated value for a safe artificial delay of the next request to allow to accumulate some chunks.\n * This allows better line throughput measurement.\n * @param {*} request\n * @param {*} currentBufferLevel current buffer level in milliseconds\n * @returns delay in milliseconds\n */\n function getThroughputCapacityDelayMS(request, currentBufferLevelMS) {\n const lastThreeMeasurements = measurements[request.mediaType] && measurements[request.mediaType].slice(-3);\n\n if (!lastThreeMeasurements || lastThreeMeasurements.length < 3) {\n return 0;\n }\n\n\n\n // in case not stable buffer, no artificially delay for the next request\n if (!isBufferSafeAndStable(lastThreeMeasurements)) {\n return 0;\n }\n\n // allowed artificial delay is the min of quater of buffer level in milliseconds and LLTM_MAX_DELAY_MS\n return currentBufferLevelMS / 4 > LLTM_MAX_DELAY_MS ? LLTM_MAX_DELAY_MS : currentBufferLevelMS / 4;\n }\n\n /**\n * Add some measurement data for bookkeeping and being able to derive decisions on estimated throughput.\n * @param {*} request HTTPLoader object to get MPD and media info from\n * @param {*} fetchDownloadDurationMS Duration how long the fetch actually took\n * @param {*} chunkMeasurements Array containing chunk timings and buffer levels\n * @param {*} requestTimeMS Timestamp at which the fetch was initiated\n * @param {*} throughputCapacityDelayMS An artificial delay that was used for this request\n */\n function addMeasurement(request, fetchDownloadDurationMS, chunkMeasurements, requestTimeMS, throughputCapacityDelayMS) {\n if (request && request.mediaType && !measurements[request.mediaType]) {\n measurements[request.mediaType] = [];\n }\n const bitrateEntry = request.mediaInfo.bitrateList.find(item => item.id === request.representationId);\n measurements[request.mediaType].push({\n index: request.index,\n repId: request.representationId,\n mediaType: request.mediaType,\n requestTimeMS,\n adjustedAvailabilityStartTimeMS: request.availabilityStartTime.getTime(),\n segDurationMS: request.duration * 1000,\n chunksDurationMS: chunkMeasurements.reduce((prev, curr) => prev + curr.chunkDownloadDurationMS, 0),\n segmentBytes: chunkMeasurements.reduce((prev, curr) => prev + curr.chunkBytes, 0),\n bitrate: bitrateEntry && bitrateEntry.bandwidth,\n bitrateList: request.mediaInfo.bitrateList,\n chunkMeasurements,\n fetchDownloadDurationMS,\n throughputCapacityDelayMS,\n getEstimatedBufferLevel: createBufferLevelTrendFunction(chunkMeasurements.slice(1)) // don't use first chunk's buffer level\n });\n // maintain only a maximum amount of most recent measurements\n if (measurements[request.mediaType].length > LLTM_MAX_MEASUREMENTS) {\n measurements[request.mediaType].shift();\n }\n }\n\n instance = {\n setup,\n addMeasurement,\n getThroughputCapacityDelayMS,\n getEstimatedDownloadDurationMS\n };\n\n setup()\n\n return instance;\n}\n\nLowLatencyThroughputModel.__dashjs_factory_name = 'LowLatencyThroughputModel';\nexport default FactoryMaker.getSingletonFactory(LowLatencyThroughputModel);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport XHRLoader from './XHRLoader';\nimport FetchLoader from './FetchLoader';\nimport {HTTPRequest} from '../vo/metrics/HTTPRequest';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport DashJSError from '../vo/DashJSError';\nimport CmcdModel from '../models/CmcdModel';\nimport Utils from '../../core/Utils';\nimport Debug from '../../core/Debug';\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\nimport Settings from '../../core/Settings';\nimport Constants from '../constants/Constants';\nimport LowLatencyThroughputModel from '../models/LowLatencyThroughputModel';\n\n/**\n * @module HTTPLoader\n * @ignore\n * @description Manages download of resources via HTTP.\n * @param {Object} cfg - dependancies from parent\n */\nfunction HTTPLoader(cfg) {\n\n cfg = cfg || {};\n\n const context = this.context;\n const errHandler = cfg.errHandler;\n const dashMetrics = cfg.dashMetrics;\n const mediaPlayerModel = cfg.mediaPlayerModel;\n const requestModifier = cfg.requestModifier;\n const boxParser = cfg.boxParser;\n const errors = cfg.errors;\n const requestTimeout = cfg.requestTimeout || 0;\n const eventBus = EventBus(context).getInstance();\n const settings = Settings(context).getInstance();\n\n let instance,\n requests,\n delayedRequests,\n retryRequests,\n downloadErrorToRequestTypeMap,\n cmcdModel,\n lowLatencyThroughputModel,\n logger;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n requests = [];\n delayedRequests = [];\n retryRequests = [];\n cmcdModel = CmcdModel(context).getInstance();\n lowLatencyThroughputModel = LowLatencyThroughputModel(context).getInstance();\n\n downloadErrorToRequestTypeMap = {\n [HTTPRequest.MPD_TYPE]: errors.DOWNLOAD_ERROR_ID_MANIFEST_CODE,\n [HTTPRequest.XLINK_EXPANSION_TYPE]: errors.DOWNLOAD_ERROR_ID_XLINK_CODE,\n [HTTPRequest.INIT_SEGMENT_TYPE]: errors.DOWNLOAD_ERROR_ID_INITIALIZATION_CODE,\n [HTTPRequest.MEDIA_SEGMENT_TYPE]: errors.DOWNLOAD_ERROR_ID_CONTENT_CODE,\n [HTTPRequest.INDEX_SEGMENT_TYPE]: errors.DOWNLOAD_ERROR_ID_CONTENT_CODE,\n [HTTPRequest.BITSTREAM_SWITCHING_SEGMENT_TYPE]: errors.DOWNLOAD_ERROR_ID_CONTENT_CODE,\n [HTTPRequest.OTHER_TYPE]: errors.DOWNLOAD_ERROR_ID_CONTENT_CODE\n };\n }\n\n function internalLoad(config, remainingAttempts) {\n const request = config.request;\n const traces = [];\n let firstProgress = true;\n let needFailureReport = true;\n let requestStartTime = new Date();\n let lastTraceTime = requestStartTime;\n let lastTraceReceivedCount = 0;\n let httpRequest;\n\n if (!requestModifier || !dashMetrics || !errHandler) {\n throw new Error('config object is not correct or missing');\n }\n\n const handleLoaded = function (success) {\n needFailureReport = false;\n\n request.requestStartDate = requestStartTime;\n request.requestEndDate = new Date();\n request.firstByteDate = request.firstByteDate || requestStartTime;\n\n if (!request.checkExistenceOnly) {\n const responseUrl = httpRequest.response ? httpRequest.response.responseURL : null;\n const responseStatus = httpRequest.response ? httpRequest.response.status : null;\n const responseHeaders = httpRequest.response && httpRequest.response.getAllResponseHeaders ? httpRequest.response.getAllResponseHeaders() :\n httpRequest.response ? httpRequest.response.responseHeaders : [];\n\n dashMetrics.addHttpRequest(request, responseUrl, responseStatus, responseHeaders, success ? traces : null);\n\n if (request.type === HTTPRequest.MPD_TYPE) {\n dashMetrics.addManifestUpdate(request);\n }\n }\n };\n\n const onloadend = function () {\n if (requests.indexOf(httpRequest) === -1) {\n return;\n } else {\n requests.splice(requests.indexOf(httpRequest), 1);\n }\n\n if (needFailureReport) {\n handleLoaded(false);\n\n if (remainingAttempts > 0) {\n\n // If we get a 404 to a media segment we should check the client clock again and perform a UTC sync in the background.\n try {\n if (settings.get().streaming.utcSynchronization.enableBackgroundSyncAfterSegmentDownloadError && request.type === HTTPRequest.MEDIA_SEGMENT_TYPE) {\n // Only trigger a sync if the loading failed for the first time\n const initialNumberOfAttempts = mediaPlayerModel.getRetryAttemptsForType(HTTPRequest.MEDIA_SEGMENT_TYPE);\n if (initialNumberOfAttempts === remainingAttempts) {\n eventBus.trigger(Events.ATTEMPT_BACKGROUND_SYNC);\n }\n }\n } catch (e) {\n\n }\n\n remainingAttempts--;\n let retryRequest = { config: config };\n retryRequests.push(retryRequest);\n retryRequest.timeout = setTimeout(function () {\n if (retryRequests.indexOf(retryRequest) === -1) {\n return;\n } else {\n retryRequests.splice(retryRequests.indexOf(retryRequest), 1);\n }\n internalLoad(config, remainingAttempts);\n }, mediaPlayerModel.getRetryIntervalsForType(request.type));\n } else {\n if (request.type === HTTPRequest.MSS_FRAGMENT_INFO_SEGMENT_TYPE) {\n return;\n }\n\n errHandler.error(new DashJSError(downloadErrorToRequestTypeMap[request.type], request.url + ' is not available', {\n request: request,\n response: httpRequest.response\n }));\n\n if (config.error) {\n config.error(request, 'error', httpRequest.response.statusText);\n }\n\n if (config.complete) {\n config.complete(request, httpRequest.response.statusText);\n }\n }\n }\n };\n\n const progress = function (event) {\n const currentTime = new Date();\n\n if (firstProgress) {\n firstProgress = false;\n if (!event.lengthComputable ||\n (event.lengthComputable && event.total !== event.loaded)) {\n request.firstByteDate = currentTime;\n }\n }\n\n if (event.lengthComputable) {\n request.bytesLoaded = event.loaded;\n request.bytesTotal = event.total;\n }\n\n if (!event.noTrace) {\n traces.push({\n s: lastTraceTime,\n d: event.time ? event.time : currentTime.getTime() - lastTraceTime.getTime(),\n b: [event.loaded ? event.loaded - lastTraceReceivedCount : 0],\n t: event.throughput\n });\n\n lastTraceTime = currentTime;\n lastTraceReceivedCount = event.loaded;\n }\n\n if (config.progress && event) {\n config.progress(event);\n }\n };\n\n const onload = function () {\n if (httpRequest.response.status >= 200 && httpRequest.response.status <= 299) {\n handleLoaded(true);\n\n if (config.success) {\n config.success(httpRequest.response.response, httpRequest.response.statusText, httpRequest.response.responseURL);\n }\n\n if (config.complete) {\n config.complete(request, httpRequest.response.statusText);\n }\n }\n };\n\n const onabort = function () {\n if (config.abort) {\n config.abort(request);\n }\n };\n\n const ontimeout = function (event) {\n let timeoutMessage;\n if (event.lengthComputable) {\n let percentageComplete = (event.loaded / event.total) * 100;\n timeoutMessage = 'Request timeout: loaded: ' + event.loaded + ', out of: ' + event.total + ' : ' + percentageComplete.toFixed(3) + '% Completed';\n } else {\n timeoutMessage = 'Request timeout: non-computable download size';\n }\n logger.warn(timeoutMessage);\n };\n\n let loader;\n if (settings.get().streaming.lowLatencyEnabled && window.fetch && request.responseType === 'arraybuffer' && request.type === HTTPRequest.MEDIA_SEGMENT_TYPE) {\n loader = FetchLoader(context).create({\n requestModifier: requestModifier,\n lowLatencyThroughputModel,\n boxParser: boxParser\n });\n loader.setup({\n dashMetrics\n });\n } else {\n loader = XHRLoader(context).create({\n requestModifier: requestModifier\n });\n }\n\n let headers = null;\n let modifiedUrl = requestModifier.modifyRequestURL(request.url);\n if (settings.get().streaming.cmcd && settings.get().streaming.cmcd.enabled) {\n const cmcdMode = settings.get().streaming.cmcd.mode;\n if (cmcdMode === Constants.CMCD_MODE_QUERY) {\n const additionalQueryParameter = _getAdditionalQueryParameter(request);\n modifiedUrl = Utils.addAditionalQueryParameterToUrl(modifiedUrl, additionalQueryParameter);\n } else if (cmcdMode === Constants.CMCD_MODE_HEADER) {\n headers = cmcdModel.getHeaderParameters(request);\n }\n }\n request.url = modifiedUrl;\n const verb = request.checkExistenceOnly ? HTTPRequest.HEAD : HTTPRequest.GET;\n const withCredentials = mediaPlayerModel.getXHRWithCredentialsForType(request.type);\n\n\n httpRequest = {\n url: modifiedUrl,\n method: verb,\n withCredentials: withCredentials,\n request: request,\n onload: onload,\n onend: onloadend,\n onerror: onloadend,\n progress: progress,\n onabort: onabort,\n ontimeout: ontimeout,\n loader: loader,\n timeout: requestTimeout,\n headers: headers\n };\n\n // Adds the ability to delay single fragment loading time to control buffer.\n let now = new Date().getTime();\n if (isNaN(request.delayLoadingTime) || now >= request.delayLoadingTime) {\n // no delay - just send\n requests.push(httpRequest);\n loader.load(httpRequest);\n } else {\n // delay\n let delayedRequest = { httpRequest: httpRequest };\n delayedRequests.push(delayedRequest);\n delayedRequest.delayTimeout = setTimeout(function () {\n if (delayedRequests.indexOf(delayedRequest) === -1) {\n return;\n } else {\n delayedRequests.splice(delayedRequests.indexOf(delayedRequest), 1);\n }\n try {\n requestStartTime = new Date();\n lastTraceTime = requestStartTime;\n requests.push(delayedRequest.httpRequest);\n loader.load(delayedRequest.httpRequest);\n } catch (e) {\n delayedRequest.httpRequest.onerror();\n }\n }, (request.delayLoadingTime - now));\n }\n }\n\n function _getAdditionalQueryParameter(request) {\n try {\n const additionalQueryParameter = [];\n const cmcdQueryParameter = cmcdModel.getQueryParameter(request);\n\n if (cmcdQueryParameter) {\n additionalQueryParameter.push(cmcdQueryParameter);\n }\n\n return additionalQueryParameter;\n } catch (e) {\n return [];\n }\n }\n\n /**\n * Initiates a download of the resource described by config.request\n * @param {Object} config - contains request (FragmentRequest or derived type), and callbacks\n * @memberof module:HTTPLoader\n * @instance\n */\n function load(config) {\n if (config.request) {\n internalLoad(\n config,\n mediaPlayerModel.getRetryAttemptsForType(\n config.request.type\n )\n );\n } else {\n if (config.error) {\n config.error(config.request, 'error');\n }\n }\n }\n\n /**\n * Aborts any inflight downloads\n * @memberof module:HTTPLoader\n * @instance\n */\n function abort() {\n retryRequests.forEach(t => {\n clearTimeout(t.timeout);\n // abort request in order to trigger LOADING_ABANDONED event\n if (t.config.request && t.config.abort) {\n t.config.abort(t.config.request);\n }\n });\n retryRequests = [];\n\n delayedRequests.forEach(x => clearTimeout(x.delayTimeout));\n delayedRequests = [];\n\n requests.forEach(x => {\n // MSS patch: ignore FragmentInfo requests\n if (x.request.type === HTTPRequest.MSS_FRAGMENT_INFO_SEGMENT_TYPE) {\n return;\n }\n\n // abort will trigger onloadend which we don't want\n // when deliberately aborting inflight requests -\n // set them to undefined so they are not called\n x.onloadend = x.onerror = x.onprogress = undefined;\n x.loader.abort(x);\n });\n requests = [];\n }\n\n instance = {\n load: load,\n abort: abort\n };\n\n setup();\n\n return instance;\n}\n\nHTTPLoader.__dashjs_factory_name = 'HTTPLoader';\n\nconst factory = FactoryMaker.getClassFactory(HTTPLoader);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport FactoryMaker from '../../core/FactoryMaker';\nimport HTTPLoader from '../../streaming/net/HTTPLoader';\n\n/**\n * @module\n * @description Choose right url loader for scheme\n * @ignore\n */\nfunction SchemeLoaderFactory() {\n\n let instance;\n\n let schemeLoaderMap;\n\n function registerLoader(scheme, loader) {\n schemeLoaderMap[scheme] = loader;\n }\n\n function unregisterLoader(scheme) {\n if (schemeLoaderMap[scheme]) {\n delete schemeLoaderMap[scheme];\n }\n }\n\n function unregisterAllLoader() {\n schemeLoaderMap = {};\n }\n\n function getLoader(url) {\n\n // iterates through schemeLoaderMap to find a loader for the scheme\n for (var scheme in schemeLoaderMap) {\n if (schemeLoaderMap.hasOwnProperty(scheme) && url.startsWith(scheme)) {\n return schemeLoaderMap[scheme];\n }\n }\n\n return HTTPLoader;\n }\n\n function reset() {\n unregisterAllLoader();\n }\n\n function setup() {\n reset();\n }\n\n setup();\n\n instance = {\n getLoader: getLoader,\n registerLoader: registerLoader,\n unregisterLoader: unregisterLoader,\n unregisterAllLoader: unregisterAllLoader,\n reset: reset\n };\n\n return instance;\n}\n\nSchemeLoaderFactory.__dashjs_factory_name = 'SchemeLoaderFactory';\nconst factory = FactoryMaker.getSingletonFactory(SchemeLoaderFactory);\nexport default factory;\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\n\nfunction isArray(arg) {\n if (Array.isArray) {\n return Array.isArray(arg);\n }\n return objectToString(arg) === '[object Array]';\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = Buffer.isBuffer;\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n","// .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,\n// backported and transplited with Babel, with backwards-compat fixes\n\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// resolves . and .. elements in a path array with directory names there\n// must be no slashes, empty elements, or device names (c:\\) in the array\n// (so also no leading and trailing slashes - it does not distinguish\n// relative and absolute paths)\nfunction normalizeArray(parts, allowAboveRoot) {\n // if the path tries to go above the root, `up` ends up > 0\n var up = 0;\n for (var i = parts.length - 1; i >= 0; i--) {\n var last = parts[i];\n if (last === '.') {\n parts.splice(i, 1);\n } else if (last === '..') {\n parts.splice(i, 1);\n up++;\n } else if (up) {\n parts.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (allowAboveRoot) {\n for (; up--; up) {\n parts.unshift('..');\n }\n }\n\n return parts;\n}\n\n// path.resolve([from ...], to)\n// posix version\nexports.resolve = function() {\n var resolvedPath = '',\n resolvedAbsolute = false;\n\n for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n var path = (i >= 0) ? arguments[i] : process.cwd();\n\n // Skip empty and invalid entries\n if (typeof path !== 'string') {\n throw new TypeError('Arguments to path.resolve must be strings');\n } else if (!path) {\n continue;\n }\n\n resolvedPath = path + '/' + resolvedPath;\n resolvedAbsolute = path.charAt(0) === '/';\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {\n return !!p;\n }), !resolvedAbsolute).join('/');\n\n return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';\n};\n\n// path.normalize(path)\n// posix version\nexports.normalize = function(path) {\n var isAbsolute = exports.isAbsolute(path),\n trailingSlash = substr(path, -1) === '/';\n\n // Normalize the path\n path = normalizeArray(filter(path.split('/'), function(p) {\n return !!p;\n }), !isAbsolute).join('/');\n\n if (!path && !isAbsolute) {\n path = '.';\n }\n if (path && trailingSlash) {\n path += '/';\n }\n\n return (isAbsolute ? '/' : '') + path;\n};\n\n// posix version\nexports.isAbsolute = function(path) {\n return path.charAt(0) === '/';\n};\n\n// posix version\nexports.join = function() {\n var paths = Array.prototype.slice.call(arguments, 0);\n return exports.normalize(filter(paths, function(p, index) {\n if (typeof p !== 'string') {\n throw new TypeError('Arguments to path.join must be strings');\n }\n return p;\n }).join('/'));\n};\n\n\n// path.relative(from, to)\n// posix version\nexports.relative = function(from, to) {\n from = exports.resolve(from).substr(1);\n to = exports.resolve(to).substr(1);\n\n function trim(arr) {\n var start = 0;\n for (; start < arr.length; start++) {\n if (arr[start] !== '') break;\n }\n\n var end = arr.length - 1;\n for (; end >= 0; end--) {\n if (arr[end] !== '') break;\n }\n\n if (start > end) return [];\n return arr.slice(start, end - start + 1);\n }\n\n var fromParts = trim(from.split('/'));\n var toParts = trim(to.split('/'));\n\n var length = Math.min(fromParts.length, toParts.length);\n var samePartsLength = length;\n for (var i = 0; i < length; i++) {\n if (fromParts[i] !== toParts[i]) {\n samePartsLength = i;\n break;\n }\n }\n\n var outputParts = [];\n for (var i = samePartsLength; i < fromParts.length; i++) {\n outputParts.push('..');\n }\n\n outputParts = outputParts.concat(toParts.slice(samePartsLength));\n\n return outputParts.join('/');\n};\n\nexports.sep = '/';\nexports.delimiter = ':';\n\nexports.dirname = function (path) {\n if (typeof path !== 'string') path = path + '';\n if (path.length === 0) return '.';\n var code = path.charCodeAt(0);\n var hasRoot = code === 47 /*/*/;\n var end = -1;\n var matchedSlash = true;\n for (var i = path.length - 1; i >= 1; --i) {\n code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n if (!matchedSlash) {\n end = i;\n break;\n }\n } else {\n // We saw the first non-path separator\n matchedSlash = false;\n }\n }\n\n if (end === -1) return hasRoot ? '/' : '.';\n if (hasRoot && end === 1) {\n // return '//';\n // Backwards-compat fix:\n return '/';\n }\n return path.slice(0, end);\n};\n\nfunction basename(path) {\n if (typeof path !== 'string') path = path + '';\n\n var start = 0;\n var end = -1;\n var matchedSlash = true;\n var i;\n\n for (i = path.length - 1; i >= 0; --i) {\n if (path.charCodeAt(i) === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n } else if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // path component\n matchedSlash = false;\n end = i + 1;\n }\n }\n\n if (end === -1) return '';\n return path.slice(start, end);\n}\n\n// Uses a mixed approach for backwards-compatibility, as ext behavior changed\n// in new Node.js versions, so only basename() above is backported here\nexports.basename = function (path, ext) {\n var f = basename(path);\n if (ext && f.substr(-1 * ext.length) === ext) {\n f = f.substr(0, f.length - ext.length);\n }\n return f;\n};\n\nexports.extname = function (path) {\n if (typeof path !== 'string') path = path + '';\n var startDot = -1;\n var startPart = 0;\n var end = -1;\n var matchedSlash = true;\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n var preDotState = 0;\n for (var i = path.length - 1; i >= 0; --i) {\n var code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (code === 46 /*.*/) {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1)\n startDot = i;\n else if (preDotState !== 1)\n preDotState = 1;\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n\n if (startDot === -1 || end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {\n return '';\n }\n return path.slice(startDot, end);\n};\n\nfunction filter (xs, f) {\n if (xs.filter) return xs.filter(f);\n var res = [];\n for (var i = 0; i < xs.length; i++) {\n if (f(xs[i], i, xs)) res.push(xs[i]);\n }\n return res;\n}\n\n// String.prototype.substr - negative index don't work in IE8\nvar substr = 'ab'.substr(-1) === 'b'\n ? function (str, start, len) { return str.substr(start, len) }\n : function (str, start, len) {\n if (start < 0) start = str.length + start;\n return str.substr(start, len);\n }\n;\n","/* \r\n * Copyright (c) 2016, Pierre-Anthony Lemieux <pal@sandflow.com>\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *\r\n * * Redistributions of source code must retain the above copyright notice, this\r\n * list of conditions and the following disclaimer.\r\n * * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the documentation\r\n * and/or other materials provided with the distribution.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\r\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n * POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\nexports.generateISD = require('./isd').generateISD;\r\nexports.fromXML = require('./doc').fromXML;\r\nexports.renderHTML = require('./html').render;","/**\n* The copyright in this software is being made available under the BSD License,\n* included below. This software may be subject to other third party and contributor\n* rights, including patent rights, and no such rights are granted under this license.\n*\n* Copyright (c) 2013, Dash Industry Forum.\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification,\n* are permitted provided that the following conditions are met:\n* * Redistributions of source code must retain the above copyright notice, this\n* list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright notice,\n* this list of conditions and the following disclaimer in the documentation and/or\n* other materials provided with the distribution.\n* * Neither the name of Dash Industry Forum nor the names of its\n* contributors may be used to endorse or promote products derived from this software\n* without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*/\nimport FactoryMaker from '../../core/FactoryMaker';\nimport { checkInteger } from '../utils/SupervisorTools';\n\nfunction CustomTimeRanges(/*config*/) {\n let customTimeRangeArray = [];\n let length = 0;\n\n function add(start, end) {\n let i = 0;\n\n for (i = 0; (i < this.customTimeRangeArray.length) && (start > this.customTimeRangeArray[i].start); i++);\n\n this.customTimeRangeArray.splice(i, 0, {start: start,end: end});\n\n for (i = 0; i < this.customTimeRangeArray.length - 1; i++) {\n if (this.mergeRanges(i,i + 1)) {\n i--;\n }\n }\n this.length = this.customTimeRangeArray.length;\n }\n\n function clear() {\n this.customTimeRangeArray = [];\n this.length = 0;\n }\n\n function remove(start, end) {\n for (let i = 0; i < this.customTimeRangeArray.length; i++) {\n if (start <= this.customTimeRangeArray[i].start && end >= this.customTimeRangeArray[i].end) {\n // |--------------Range i-------|\n //|---------------Range to remove ---------------|\n // or\n //|--------------Range i-------|\n //|--------------Range to remove ---------------|\n // or\n // |--------------Range i-------|\n //|--------------Range to remove ---------------|\n this.customTimeRangeArray.splice(i,1);\n i--;\n\n } else if (start > this.customTimeRangeArray[i].start && end < this.customTimeRangeArray[i].end) {\n //|-----------------Range i----------------|\n // |-------Range to remove -----|\n this.customTimeRangeArray.splice(i + 1, 0, {start: end,end: this.customTimeRangeArray[i].end});\n this.customTimeRangeArray[i].end = start;\n break;\n } else if ( start > this.customTimeRangeArray[i].start && start < this.customTimeRangeArray[i].end) {\n //|-----------Range i----------|\n // |---------Range to remove --------|\n // or\n //|-----------------Range i----------------|\n // |-------Range to remove -----|\n this.customTimeRangeArray[i].end = start;\n } else if ( end > this.customTimeRangeArray[i].start && end < this.customTimeRangeArray[i].end) {\n // |-----------Range i----------|\n //|---------Range to remove --------|\n // or\n //|-----------------Range i----------------|\n //|-------Range to remove -----|\n this.customTimeRangeArray[i].start = end;\n }\n }\n\n this.length = this.customTimeRangeArray.length;\n }\n\n function mergeRanges(rangeIndex1, rangeIndex2) {\n let range1 = this.customTimeRangeArray[rangeIndex1];\n let range2 = this.customTimeRangeArray[rangeIndex2];\n\n if (range1.start <= range2.start && range2.start <= range1.end && range1.end <= range2.end) {\n //|-----------Range1----------|\n // |-----------Range2----------|\n range1.end = range2.end;\n this.customTimeRangeArray.splice(rangeIndex2,1);\n return true;\n\n } else if (range2.start <= range1.start && range1.start <= range2.end && range2.end <= range1.end) {\n // |-----------Range1----------|\n //|-----------Range2----------|\n range1.start = range2.start;\n this.customTimeRangeArray.splice(rangeIndex2,1);\n return true;\n } else if (range2.start <= range1.start && range1.start <= range2.end && range1.end <= range2.end) {\n // |--------Range1-------|\n //|---------------Range2--------------|\n this.customTimeRangeArray.splice(rangeIndex1,1);\n return true;\n } else if (range1.start <= range2.start && range2.start <= range1.end && range2.end <= range1.end) {\n //|-----------------Range1--------------|\n // |-----------Range2----------|\n this.customTimeRangeArray.splice(rangeIndex2,1);\n return true;\n }\n return false;\n }\n\n function start(index) {\n checkInteger(index);\n\n if (index >= this.customTimeRangeArray.length || index < 0) {\n return NaN;\n }\n\n return this.customTimeRangeArray[index].start;\n }\n\n function end(index) {\n checkInteger(index);\n\n if (index >= this.customTimeRangeArray.length || index < 0) {\n return NaN;\n }\n\n return this.customTimeRangeArray[index].end;\n }\n\n return {\n customTimeRangeArray: customTimeRangeArray,\n length: length,\n add: add,\n clear: clear,\n remove: remove,\n mergeRanges: mergeRanges,\n start: start,\n end: end\n };\n}\nCustomTimeRanges.__dashjs_factory_name = 'CustomTimeRanges';\nexport default FactoryMaker.getClassFactory(CustomTimeRanges);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport FactoryMaker from '../../core/FactoryMaker';\nimport {THUMBNAILS_SCHEME_ID_URIS} from '../thumbnail/ThumbnailTracks';\nimport Constants from '../constants/Constants';\n\nconst codecCompatibilityTable = [\n {\n 'codec': 'avc1',\n 'compatibleCodecs': ['avc3']\n },\n {\n 'codec': 'avc3',\n 'compatibleCodecs': ['avc1']\n }\n];\n\nexport function supportsMediaSource() {\n let hasWebKit = ('WebKitMediaSource' in window);\n let hasMediaSource = ('MediaSource' in window);\n\n return (hasWebKit || hasMediaSource);\n}\n\nfunction Capabilities() {\n\n let instance,\n settings,\n encryptedMediaSupported;\n\n function setup() {\n encryptedMediaSupported = false;\n }\n\n function setConfig(config) {\n if (!config) {\n return;\n }\n\n if (config.settings) {\n settings = config.settings;\n }\n }\n\n /**\n * Returns whether Encrypted Media Extensions are supported on this\n * user agent\n *\n * @return {boolean} true if EME is supported, false otherwise\n */\n function supportsEncryptedMedia() {\n return encryptedMediaSupported;\n }\n\n /**\n *\n * @param {boolean} value\n */\n function setEncryptedMediaSupported(value) {\n encryptedMediaSupported = value;\n }\n\n /**\n * Check if a codec is supported by the MediaSource. We use the MediaCapabilities API or the MSE to check.\n * @param {object} config\n * @param {string} type\n * @return {Promise<boolean>}\n */\n function supportsCodec(config, type) {\n\n if (type !== Constants.AUDIO && type !== Constants.VIDEO) {\n return Promise.resolve(true);\n }\n\n if (_canUseMediaCapabilitiesApi(config, type)) {\n return _checkCodecWithMediaCapabilities(config, type);\n }\n\n return _checkCodecWithMse(config);\n }\n\n /**\n * MediaCapabilitiesAPI throws an error if one of the attribute is missing. We only use it if we have all required information.\n * @param {object} config\n * @param {string} type\n * @return {*|boolean|boolean}\n * @private\n */\n function _canUseMediaCapabilitiesApi(config, type) {\n\n return settings.get().streaming.capabilities.useMediaCapabilitiesApi && navigator.mediaCapabilities && navigator.mediaCapabilities.decodingInfo && ((config.codec && type === Constants.AUDIO) || (type === Constants.VIDEO && config.codec && config.width && config.height && config.bitrate && config.framerate));\n }\n\n /**\n * Check codec support using the MSE\n * @param {object} config\n * @return {Promise<void> | Promise<boolean>}\n * @private\n */\n function _checkCodecWithMse(config) {\n return new Promise((resolve) => {\n if (!config || !config.codec) {\n resolve(false);\n return;\n }\n\n let codec = config.codec;\n if (config.width && config.height) {\n codec += ';width=\"' + config.width + '\";height=\"' + config.height + '\"';\n }\n\n if ('MediaSource' in window && MediaSource.isTypeSupported(codec)) {\n resolve(true);\n return;\n } else if ('WebKitMediaSource' in window && WebKitMediaSource.isTypeSupported(codec)) {\n resolve(true);\n return;\n }\n\n resolve(false);\n });\n\n }\n\n /**\n * Check codec support using the MediaCapabilities API\n * @param {object} config\n * @param {string} type\n * @return {Promise<boolean>}\n * @private\n */\n function _checkCodecWithMediaCapabilities(config, type) {\n return new Promise((resolve) => {\n\n if (!config || !config.codec) {\n resolve(false);\n return;\n }\n\n const configuration = {\n type: 'media-source'\n };\n\n configuration[type] = {};\n configuration[type].contentType = config.codec;\n configuration[type].width = config.width;\n configuration[type].height = config.height;\n configuration[type].bitrate = parseInt(config.bitrate);\n configuration[type].framerate = parseFloat(config.framerate);\n\n navigator.mediaCapabilities.decodingInfo(configuration)\n .then((result) => {\n resolve(result.supported);\n })\n .catch(() => {\n resolve(false);\n });\n });\n }\n\n /**\n * Check if a specific EssentialProperty is supported\n * @param {object} ep\n * @return {boolean}\n */\n function supportsEssentialProperty(ep) {\n try {\n return THUMBNAILS_SCHEME_ID_URIS.indexOf(ep.schemeIdUri) !== -1;\n } catch (e) {\n return true;\n }\n }\n\n /**\n * Check if the root of the old codec is the same as the new one, or if it's declared as compatible in the compat table\n * @param {string} codec1\n * @param {string} codec2\n * @return {boolean}\n */\n function codecRootCompatibleWithCodec(codec1, codec2) {\n const codecRoot = codec1.split('.')[0];\n const rootCompatible = codec2.indexOf(codecRoot) === 0;\n let compatTableCodec;\n for (let i = 0; i < codecCompatibilityTable.length; i++) {\n if (codecCompatibilityTable[i].codec === codecRoot) {\n compatTableCodec = codecCompatibilityTable[i];\n break;\n }\n }\n if (compatTableCodec) {\n return rootCompatible || compatTableCodec.compatibleCodecs.some((compatibleCodec) => codec2.indexOf(compatibleCodec) === 0);\n }\n return rootCompatible;\n }\n\n instance = {\n setConfig,\n supportsMediaSource,\n supportsEncryptedMedia,\n supportsCodec,\n setEncryptedMediaSupported,\n supportsEssentialProperty,\n codecRootCompatibleWithCodec\n };\n\n setup();\n\n return instance;\n}\n\nCapabilities.__dashjs_factory_name = 'Capabilities';\nexport default FactoryMaker.getSingletonFactory(Capabilities);\n","/* \r\n * Copyright (c) 2016, Pierre-Anthony Lemieux <pal@sandflow.com>\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *\r\n * * Redistributions of source code must retain the above copyright notice, this\r\n * list of conditions and the following disclaimer.\r\n * * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the documentation\r\n * and/or other materials provided with the distribution.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\r\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n * POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\n/**\r\n * @module imscNames\r\n */\r\n\r\n;\r\n(function (imscNames) { // wrapper for non-node envs\r\n\r\n imscNames.ns_tt = \"http://www.w3.org/ns/ttml\";\r\n imscNames.ns_tts = \"http://www.w3.org/ns/ttml#styling\";\r\n imscNames.ns_ttp = \"http://www.w3.org/ns/ttml#parameter\";\r\n imscNames.ns_xml = \"http://www.w3.org/XML/1998/namespace\";\r\n imscNames.ns_itts = \"http://www.w3.org/ns/ttml/profile/imsc1#styling\";\r\n imscNames.ns_ittp = \"http://www.w3.org/ns/ttml/profile/imsc1#parameter\";\r\n imscNames.ns_smpte = \"http://www.smpte-ra.org/schemas/2052-1/2010/smpte-tt\";\r\n imscNames.ns_ebutts = \"urn:ebu:tt:style\";\r\n \r\n})(typeof exports === 'undefined' ? this.imscNames = {} : exports);\r\n\r\n\r\n\r\n\r\n","'use strict';\n\nif (!process.version ||\n process.version.indexOf('v0.') === 0 ||\n process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {\n module.exports = { nextTick: nextTick };\n} else {\n module.exports = process\n}\n\nfunction nextTick(fn, arg1, arg2, arg3) {\n if (typeof fn !== 'function') {\n throw new TypeError('\"callback\" argument must be a function');\n }\n var len = arguments.length;\n var args, i;\n switch (len) {\n case 0:\n case 1:\n return process.nextTick(fn);\n case 2:\n return process.nextTick(function afterTickOne() {\n fn.call(null, arg1);\n });\n case 3:\n return process.nextTick(function afterTickTwo() {\n fn.call(null, arg1, arg2);\n });\n case 4:\n return process.nextTick(function afterTickThree() {\n fn.call(null, arg1, arg2, arg3);\n });\n default:\n args = new Array(len - 1);\n i = 0;\n while (i < args.length) {\n args[i++] = arguments[i];\n }\n return process.nextTick(function afterTick() {\n fn.apply(null, args);\n });\n }\n}\n\n","/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * Metrics Constants declaration\n * @class\n * @ignore\n */\nclass MetricsConstants {\n\n init () {\n this.TCP_CONNECTION = 'TcpList';\n this.HTTP_REQUEST = 'HttpList';\n this.TRACK_SWITCH = 'RepSwitchList';\n this.BUFFER_LEVEL = 'BufferLevel';\n this.BUFFER_LOADED = 'bufferLoaded';\n this.ABANDON_LOAD = 'abandonload';\n this.ALLOW_LOAD = 'allowload';\n this.BUFFER_EMPTY = 'bufferStalled';\n this.BUFFER_STATE = 'BufferState';\n this.DVR_INFO = 'DVRInfo';\n this.DROPPED_FRAMES = 'DroppedFrames';\n this.SCHEDULING_INFO = 'SchedulingInfo';\n this.REQUESTS_QUEUE = 'RequestsQueue';\n this.MANIFEST_UPDATE = 'ManifestUpdate';\n this.MANIFEST_UPDATE_STREAM_INFO = 'ManifestUpdatePeriodInfo';\n this.MANIFEST_UPDATE_TRACK_INFO = 'ManifestUpdateRepresentationInfo';\n this.PLAY_LIST = 'PlayList';\n this.DVB_ERRORS = 'DVBErrors';\n }\n\n constructor() {\n this.init();\n }\n}\n\nlet constants = new MetricsConstants();\nexport default constants;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Constants from '../constants/Constants';\nimport MetricsConstants from '../constants/MetricsConstants';\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Debug from '../../core/Debug';\nimport MediaPlayerEvents from '../../streaming/MediaPlayerEvents';\n\nconst LIVE_UPDATE_PLAYBACK_TIME_INTERVAL_MS = 500;\n\nfunction PlaybackController() {\n\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n\n let instance,\n logger,\n streamController,\n dashMetrics,\n adapter,\n videoModel,\n timelineConverter,\n wallclockTimeIntervalId,\n liveDelay,\n streamInfo,\n isDynamic,\n mediaPlayerModel,\n playOnceInitialized,\n lastLivePlaybackTime,\n availabilityStartTime,\n seekTarget,\n internalSeek,\n isLowLatencySeekingInProgress,\n playbackStalled,\n minPlaybackRateChange,\n manifestUpdateInProgress,\n settings;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n\n reset();\n }\n\n /**\n * Initializes the PlaybackController. This function is called whenever the stream is switched.\n * @param {object} sInfo\n * @param {boolean} periodSwitch\n */\n function initialize(sInfo, periodSwitch) {\n streamInfo = sInfo;\n\n if (periodSwitch !== true) {\n _initializeForFirstStream();\n } else {\n _initializeAfterStreamSwitch();\n }\n }\n\n /**\n * Initializes the PlaybackController when the first stream is to be played.\n * @private\n */\n function _initializeForFirstStream() {\n addAllListeners();\n isDynamic = streamInfo.manifestInfo.isDynamic;\n isLowLatencySeekingInProgress = false;\n playbackStalled = false;\n internalSeek = false;\n\n // Detect safari browser (special behavior for low latency streams)\n const ua = typeof navigator !== 'undefined' ? navigator.userAgent.toLowerCase() : '';\n const isSafari = /safari/.test(ua) && !/chrome/.test(ua);\n minPlaybackRateChange = isSafari ? 0.25 : 0.02;\n\n eventBus.on(Events.DATA_UPDATE_COMPLETED, _onDataUpdateCompleted, instance);\n eventBus.on(Events.LOADING_PROGRESS, _onFragmentLoadProgress, instance);\n eventBus.on(Events.MANIFEST_UPDATED, _onManifestUpdated, instance);\n eventBus.on(Events.STREAMS_COMPOSED, _onStreamsComposed, instance);\n eventBus.on(MediaPlayerEvents.BUFFER_LEVEL_STATE_CHANGED, _onBufferLevelStateChanged, instance);\n eventBus.on(MediaPlayerEvents.PLAYBACK_PROGRESS, _onPlaybackProgression, instance);\n eventBus.on(MediaPlayerEvents.PLAYBACK_TIME_UPDATED, _onPlaybackProgression, instance);\n eventBus.on(MediaPlayerEvents.PLAYBACK_ENDED, _onPlaybackEnded, instance, { priority: EventBus.EVENT_PRIORITY_HIGH });\n eventBus.on(MediaPlayerEvents.STREAM_INITIALIZING, _onStreamInitializing, instance);\n eventBus.on(MediaPlayerEvents.REPRESENTATION_SWITCH, _onRepresentationSwitch, instance);\n\n if (playOnceInitialized) {\n playOnceInitialized = false;\n play();\n }\n }\n\n /**\n * Initializes the PlaybackController after the stream is switched. This will only happen with multiperiod MPDs.\n * @private\n */\n function _initializeAfterStreamSwitch() {\n\n }\n\n function getTimeToStreamEnd(sInfo = null) {\n return parseFloat((getStreamEndTime(sInfo) - getTime()).toFixed(5));\n }\n\n function getStreamEndTime(sInfo) {\n const refInfo = sInfo ? sInfo : streamInfo;\n return refInfo.start + refInfo.duration;\n }\n\n function play() {\n if (streamInfo && videoModel && videoModel.getElement()) {\n videoModel.play();\n } else {\n playOnceInitialized = true;\n }\n }\n\n function isPaused() {\n return streamInfo && videoModel ? videoModel.isPaused() : null;\n }\n\n function pause() {\n if (streamInfo && videoModel) {\n videoModel.pause();\n }\n }\n\n function isSeeking() {\n return streamInfo && videoModel ? videoModel.isSeeking() : null;\n }\n\n function isStalled() {\n return streamInfo && videoModel ? videoModel.isStalled() : null;\n }\n\n function seek(time, stickToBuffered, internal) {\n if (!streamInfo || !videoModel) return;\n\n let currentTime = !isNaN(seekTarget) ? seekTarget : videoModel.getTime();\n if (time === currentTime) return;\n\n internalSeek = (internal === true);\n\n if (!internalSeek) {\n seekTarget = time;\n eventBus.trigger(Events.PLAYBACK_SEEK_ASKED);\n }\n logger.info('Requesting seek to time: ' + time + (internalSeek ? ' (internal)' : ''));\n videoModel.setCurrentTime(time, stickToBuffered);\n }\n\n function seekToLive() {\n const type = streamController && streamController.hasVideoTrack() ? Constants.VIDEO : Constants.AUDIO;\n const DVRMetrics = dashMetrics.getCurrentDVRInfo(type);\n const DVRWindow = DVRMetrics ? DVRMetrics.range : null;\n\n if (DVRWindow && !isNaN(DVRWindow.end)) {\n seek(DVRWindow.end - mediaPlayerModel.getLiveDelay(), true, false);\n }\n }\n\n function getTime() {\n return streamInfo && videoModel ? videoModel.getTime() : null;\n }\n\n function getNormalizedTime() {\n let t = getTime();\n\n if (isDynamic && !isNaN(availabilityStartTime)) {\n const timeOffset = availabilityStartTime / 1000;\n // Fix current time for firefox and safari (returned as an absolute time)\n if (t > timeOffset) {\n t -= timeOffset;\n }\n }\n return t;\n }\n\n function getPlaybackRate() {\n return streamInfo && videoModel ? videoModel.getPlaybackRate() : null;\n }\n\n function getPlayedRanges() {\n return streamInfo && videoModel ? videoModel.getPlayedRanges() : null;\n }\n\n function getEnded() {\n return streamInfo && videoModel ? videoModel.getEnded() : null;\n }\n\n function getIsDynamic() {\n return isDynamic;\n }\n\n function getStreamController() {\n return streamController;\n }\n\n function getIsManifestUpdateInProgress() {\n return manifestUpdateInProgress;\n }\n\n /**\n * Computes the desirable delay for the live edge to avoid a risk of getting 404 when playing at the bleeding edge\n * @param {number} fragmentDuration - seconds?\n * @param {object} manifestInfo\n * @returns {number} object\n * @memberof PlaybackController#\n */\n function computeAndSetLiveDelay(fragmentDuration, manifestInfo) {\n let delay,\n ret,\n startTime;\n const END_OF_PLAYLIST_PADDING = 10;\n const MIN_BUFFER_TIME_FACTOR = 4;\n const FRAGMENT_DURATION_FACTOR = 4;\n const adjustedFragmentDuration = !isNaN(fragmentDuration) && isFinite(fragmentDuration) ? fragmentDuration : NaN;\n\n let suggestedPresentationDelay = adapter.getSuggestedPresentationDelay();\n\n\n // Apply live delay from ServiceDescription\n if (settings.get().streaming.delay.applyServiceDescription && isNaN(settings.get().streaming.delay.liveDelay) && isNaN(settings.get().streaming.delay.liveDelayFragmentCount)) {\n _applyServiceDescription(manifestInfo);\n }\n\n if (mediaPlayerModel.getLiveDelay()) {\n delay = mediaPlayerModel.getLiveDelay(); // If set by user, this value takes precedence\n } else if (settings.get().streaming.delay.liveDelayFragmentCount !== null && !isNaN(settings.get().streaming.delay.liveDelayFragmentCount) && !isNaN(adjustedFragmentDuration)) {\n delay = adjustedFragmentDuration * settings.get().streaming.delay.liveDelayFragmentCount;\n } else if (settings.get().streaming.delay.useSuggestedPresentationDelay === true && suggestedPresentationDelay !== null && !isNaN(suggestedPresentationDelay) && suggestedPresentationDelay > 0) {\n delay = suggestedPresentationDelay;\n } else if (!isNaN(adjustedFragmentDuration)) {\n delay = adjustedFragmentDuration * FRAGMENT_DURATION_FACTOR;\n } else {\n delay = manifestInfo && !isNaN(manifestInfo.minBufferTime) ? manifestInfo.minBufferTime * MIN_BUFFER_TIME_FACTOR : streamInfo.manifestInfo.minBufferTime * MIN_BUFFER_TIME_FACTOR;\n }\n\n startTime = adapter.getAvailabilityStartTime();\n\n if (startTime !== null) {\n availabilityStartTime = startTime;\n }\n\n if (manifestInfo && manifestInfo.dvrWindowSize > 0) {\n // cap target latency to:\n // - dvrWindowSize / 2 for short playlists\n // - dvrWindowSize - END_OF_PLAYLIST_PADDING for longer playlists\n const targetDelayCapping = Math.max(manifestInfo.dvrWindowSize - END_OF_PLAYLIST_PADDING, manifestInfo.dvrWindowSize / 2);\n ret = Math.min(delay, targetDelayCapping);\n } else {\n ret = delay;\n }\n liveDelay = ret;\n return ret;\n }\n\n function _applyServiceDescription(manifestInfo) {\n if (!manifestInfo || !manifestInfo.serviceDescriptions) {\n return;\n }\n\n let llsd = null;\n\n for (let i = 0; i < manifestInfo.serviceDescriptions.length; i++) {\n const sd = manifestInfo.serviceDescriptions[i];\n if (sd.schemeIdUri === Constants.SERVICE_DESCRIPTION_LL_SCHEME) {\n llsd = sd;\n break;\n }\n }\n\n if (llsd) {\n if (llsd.latency && llsd.latency.target > 0) {\n logger.debug('Apply LL properties coming from service description. Target Latency (ms):', llsd.latency.target);\n settings.update({\n streaming: {\n delay: {\n liveDelay: llsd.latency.target / 1000,\n },\n liveCatchup: {\n minDrift: (llsd.latency.target + 500) / 1000,\n maxDrift: llsd.latency.max > llsd.latency.target ? (llsd.latency.max - llsd.latency.target + 500) / 1000 : undefined\n }\n }\n });\n }\n if (llsd.playbackRate && llsd.playbackRate.max > 1.0) {\n logger.debug('Apply LL properties coming from service description. Max PlaybackRate:', llsd.playbackRate.max);\n settings.update({\n streaming: {\n liveCatchup: {\n playbackRate: llsd.playbackRate.max - 1.0\n }\n }\n });\n }\n }\n }\n\n function getAvailabilityStartTime() {\n return availabilityStartTime;\n }\n\n function getLiveDelay() {\n return liveDelay;\n }\n\n function getCurrentLiveLatency() {\n if (!isDynamic || isNaN(availabilityStartTime)) {\n return NaN;\n }\n let currentTime = getNormalizedTime();\n if (isNaN(currentTime) || currentTime === 0) {\n return 0;\n }\n\n const now = new Date().getTime() + timelineConverter.getClientTimeOffset() * 1000;\n return Math.max(((now - availabilityStartTime - currentTime * 1000) / 1000).toFixed(3), 0);\n }\n\n function reset() {\n pause();\n playOnceInitialized = false;\n liveDelay = 0;\n availabilityStartTime = 0;\n manifestUpdateInProgress = false;\n seekTarget = NaN;\n if (videoModel) {\n eventBus.off(Events.DATA_UPDATE_COMPLETED, _onDataUpdateCompleted, instance);\n eventBus.off(Events.LOADING_PROGRESS, _onFragmentLoadProgress, instance);\n eventBus.off(Events.MANIFEST_UPDATED, _onManifestUpdated, instance);\n eventBus.off(Events.STREAMS_COMPOSED, _onStreamsComposed, instance);\n eventBus.off(MediaPlayerEvents.BUFFER_LEVEL_STATE_CHANGED, _onBufferLevelStateChanged, instance);\n eventBus.off(MediaPlayerEvents.PLAYBACK_PROGRESS, _onPlaybackProgression, instance);\n eventBus.off(MediaPlayerEvents.PLAYBACK_TIME_UPDATED, _onPlaybackProgression, instance);\n eventBus.off(MediaPlayerEvents.PLAYBACK_ENDED, _onPlaybackEnded, instance);\n eventBus.off(MediaPlayerEvents.STREAM_INITIALIZING, _onStreamInitializing, instance);\n eventBus.off(MediaPlayerEvents.REPRESENTATION_SWITCH, _onRepresentationSwitch, instance);\n videoModel.setPlaybackRate(1.0, true);\n stopUpdatingWallclockTime();\n removeAllListeners();\n }\n wallclockTimeIntervalId = null;\n videoModel = null;\n streamInfo = null;\n isDynamic = null;\n }\n\n function setConfig(config) {\n if (!config) return;\n\n if (config.streamController) {\n streamController = config.streamController;\n }\n if (config.dashMetrics) {\n dashMetrics = config.dashMetrics;\n }\n if (config.mediaPlayerModel) {\n mediaPlayerModel = config.mediaPlayerModel;\n }\n if (config.adapter) {\n adapter = config.adapter;\n }\n if (config.videoModel) {\n videoModel = config.videoModel;\n }\n if (config.timelineConverter) {\n timelineConverter = config.timelineConverter;\n }\n if (config.settings) {\n settings = config.settings;\n }\n }\n\n function getActualPresentationTime(currentTime, mediatype) {\n const DVRMetrics = dashMetrics.getCurrentDVRInfo(mediatype);\n const DVRWindow = DVRMetrics ? DVRMetrics.range : null;\n let actualTime;\n\n if (!DVRWindow) {\n return NaN;\n }\n\n if (currentTime > DVRWindow.end) {\n actualTime = Math.max(DVRWindow.end - liveDelay, DVRWindow.start);\n\n } else if (currentTime > 0 && currentTime + 0.250 < DVRWindow.start && Math.abs(currentTime - DVRWindow.start) < 315360000) {\n\n // Checking currentTime plus 250ms as the 'timeupdate' is fired with a frequency between 4Hz and 66Hz\n // https://developer.mozilla.org/en-US/docs/Web/Events/timeupdate\n // http://w3c.github.io/html/single-page.html#offsets-into-the-media-resource\n // Checking also duration of the DVR makes sense. We detected temporary situations in which currentTime\n // is bad reported by the browser which causes playback to jump to start (315360000 = 1 year)\n if (settings.get().streaming.lowLatencyEnabled) {\n actualTime = Math.max(DVRWindow.end - liveDelay, DVRWindow.start);\n } else {\n actualTime = DVRWindow.start;\n }\n } else {\n actualTime = currentTime;\n }\n\n return actualTime;\n }\n\n function startUpdatingWallclockTime() {\n if (wallclockTimeIntervalId !== null) return;\n\n const tick = function () {\n _onWallclockTime();\n };\n\n wallclockTimeIntervalId = setInterval(tick, settings.get().streaming.wallclockTimeUpdateInterval);\n }\n\n function stopUpdatingWallclockTime() {\n clearInterval(wallclockTimeIntervalId);\n wallclockTimeIntervalId = null;\n }\n\n /**\n * Compare the current time of the video against the DVR window. If we are out of the DVR window we need to seek.\n * @param {object} mediaType\n */\n function updateCurrentTime(mediaType = null) {\n if (isPaused() || !isDynamic || videoModel.getReadyState() === 0 || isSeeking() || manifestUpdateInProgress) return;\n\n // Note: In some cases we filter certain media types completely (for instance due to an unsupported video codec). This happens after the first entry to the DVR metric has been added.\n // Now the DVR window for the filtered media type is not updated anymore. Consequently, always use a mediaType that is available to get a valid DVR window.\n if (!mediaType) {\n mediaType = streamController.hasVideoTrack() ? Constants.VIDEO : Constants.AUDIO;\n }\n // Compare the current time of the video element against the range defined in the DVR window.\n const currentTime = getNormalizedTime();\n const actualTime = getActualPresentationTime(currentTime, mediaType);\n const timeChanged = (!isNaN(actualTime) && actualTime !== currentTime);\n if (timeChanged && !isSeeking() && (isStalled() || playbackStalled || videoModel.getReadyState() === 1)) {\n logger.debug(`UpdateCurrentTime: Seek to actual time: ${actualTime} from currentTime: ${currentTime}`);\n seek(actualTime);\n }\n }\n\n function _onDataUpdateCompleted(e) {\n const representationInfo = adapter.convertRepresentationToRepresentationInfo(e.currentRepresentation);\n const info = representationInfo ? representationInfo.mediaInfo.streamInfo : null;\n\n if (info === null || streamInfo.id !== info.id) return;\n streamInfo = info;\n }\n\n function _onCanPlay() {\n eventBus.trigger(Events.CAN_PLAY);\n }\n\n function _onCanPlayThrough() {\n eventBus.trigger(Events.CAN_PLAY_THROUGH);\n }\n\n function _onPlaybackStart() {\n logger.info('Native video element event: play');\n updateCurrentTime();\n startUpdatingWallclockTime();\n eventBus.trigger(Events.PLAYBACK_STARTED, { startTime: getTime() });\n }\n\n function _onPlaybackWaiting() {\n logger.info('Native video element event: waiting');\n eventBus.trigger(Events.PLAYBACK_WAITING, { playingTime: getTime() });\n }\n\n function _onPlaybackPlaying() {\n logger.info('Native video element event: playing');\n eventBus.trigger(Events.PLAYBACK_PLAYING, { playingTime: getTime() });\n }\n\n function _onPlaybackPaused() {\n logger.info('Native video element event: pause');\n eventBus.trigger(Events.PLAYBACK_PAUSED, { ended: getEnded() });\n }\n\n function _onPlaybackSeeking() {\n // Check if internal seeking to be ignored\n if (internalSeek) {\n internalSeek = false;\n return;\n }\n\n let seekTime = getTime();\n // On some browsers/devices, in case of live streams, setting current time on video element fails when there is no buffered data at requested time\n // Then re-set seek target time and video element will be seeked afterwhile once data is buffered (see BufferContoller)\n if (!isNaN(seekTarget) && seekTarget !== seekTime) {\n seekTime = seekTarget;\n }\n seekTarget = NaN;\n\n logger.info('Seeking to: ' + seekTime);\n startUpdatingWallclockTime();\n eventBus.trigger(Events.PLAYBACK_SEEKING, {\n seekTime: seekTime,\n streamId: streamInfo.id\n });\n }\n\n function _onPlaybackSeeked() {\n logger.info('Native video element event: seeked');\n eventBus.trigger(Events.PLAYBACK_SEEKED);\n }\n\n function _onPlaybackTimeUpdated() {\n if (streamInfo) {\n eventBus.trigger(Events.PLAYBACK_TIME_UPDATED, {\n timeToEnd: getTimeToStreamEnd(),\n time: getTime(),\n streamId: streamInfo.id\n });\n }\n }\n\n function _onPlaybackProgress() {\n eventBus.trigger(Events.PLAYBACK_PROGRESS, { streamId: streamInfo.id });\n }\n\n function _onPlaybackRateChanged() {\n const rate = getPlaybackRate();\n logger.info('Native video element event: ratechange: ', rate);\n eventBus.trigger(Events.PLAYBACK_RATE_CHANGED, { playbackRate: rate });\n }\n\n function _onPlaybackMetaDataLoaded() {\n logger.info('Native video element event: loadedmetadata');\n eventBus.trigger(Events.PLAYBACK_METADATA_LOADED);\n startUpdatingWallclockTime();\n }\n\n function _onPlaybackLoadedData() {\n logger.info('Native video element event: loadeddata');\n eventBus.trigger(Events.PLAYBACK_LOADED_DATA);\n }\n\n // Event to handle the native video element ended event\n function _onNativePlaybackEnded() {\n logger.info('Native video element event: ended');\n pause();\n stopUpdatingWallclockTime();\n const streamInfo = streamController ? streamController.getActiveStreamInfo() : null;\n if (!streamInfo) return;\n eventBus.trigger(Events.PLAYBACK_ENDED, { 'isLast': streamInfo.isLast });\n }\n\n // Handle DASH PLAYBACK_ENDED event\n function _onPlaybackEnded(e) {\n if (wallclockTimeIntervalId && e.isLast) {\n // PLAYBACK_ENDED was triggered elsewhere, react.\n logger.info('onPlaybackEnded -- PLAYBACK_ENDED but native video element didn\\'t fire ended');\n const seekTime = e.seekTime ? e.seekTime : getStreamEndTime();\n videoModel.setCurrentTime(seekTime);\n pause();\n stopUpdatingWallclockTime();\n }\n }\n\n function _onPlaybackError(event) {\n const target = event.target || event.srcElement;\n eventBus.trigger(Events.PLAYBACK_ERROR, { error: target.error });\n }\n\n function _onWallclockTime() {\n eventBus.trigger(Events.WALLCLOCK_TIME_UPDATED, {\n isDynamic: isDynamic,\n time: new Date()\n });\n\n // Updates playback time for paused dynamic streams\n // (video element doesn't call timeupdate when the playback is paused)\n if (getIsDynamic()) {\n streamController.addDVRMetric();\n if (isPaused()) {\n _updateLivePlaybackTime();\n } else {\n updateCurrentTime();\n }\n }\n }\n\n function _updateLivePlaybackTime() {\n const now = Date.now();\n if (!lastLivePlaybackTime || now > lastLivePlaybackTime + LIVE_UPDATE_PLAYBACK_TIME_INTERVAL_MS) {\n lastLivePlaybackTime = now;\n _onPlaybackTimeUpdated();\n }\n }\n\n\n function _onPlaybackProgression() {\n if (\n isDynamic &&\n _isCatchupEnabled() &&\n settings.get().streaming.liveCatchup.playbackRate > 0 &&\n !isPaused() &&\n !isSeeking()\n ) {\n if (_needToCatchUp()) {\n startPlaybackCatchUp();\n } else {\n stopPlaybackCatchUp();\n }\n }\n }\n\n function _isCatchupEnabled() {\n return settings.get().streaming.liveCatchup.enabled || settings.get().streaming.lowLatencyEnabled;\n }\n\n /**\n * Returns the combined minimum buffer level of all StreamProcessors. If a filter list is provided the types specified in the filter list are excluded.\n * @param {array} filterList StreamProcessor types to exclude\n * @return {null}\n */\n function getBufferLevel(filterList = null) {\n let bufferLevel = null;\n streamController.getActiveStreamProcessors().forEach(p => {\n if (!filterList || filterList.length === 0 || filterList.indexOf(p.getType()) === -1) {\n const bl = p.getBufferLevel();\n if (bufferLevel === null) {\n bufferLevel = bl;\n } else {\n bufferLevel = Math.min(bufferLevel, bl);\n }\n }\n });\n\n return bufferLevel;\n }\n\n /**\n * Returns the mode for live playback catchup.\n * @return {String}\n * @private\n */\n function _getCatchupMode() {\n const playbackBufferMin = settings.get().streaming.liveCatchup.playbackBufferMin;\n\n return settings.get().streaming.liveCatchup.mode === Constants.LIVE_CATCHUP_MODE_LOLP && playbackBufferMin !== null && !isNaN(playbackBufferMin) ? Constants.LIVE_CATCHUP_MODE_LOLP : Constants.LIVE_CATCHUP_MODE_DEFAULT;\n }\n\n /**\n * Checks whether the catchup mechanism should be enabled\n * @return {boolean}\n */\n function _needToCatchUp() {\n try {\n if (_isCatchupEnabled() && settings.get().streaming.liveCatchup.playbackRate > 0 && getTime() > 0) {\n\n const catchupMode = _getCatchupMode();\n const currentLiveLatency = getCurrentLiveLatency();\n const liveDelay = mediaPlayerModel.getLiveDelay();\n const liveCatchupLatencyThreshold = mediaPlayerModel.getLiveCatchupLatencyThreshold();\n const liveCatchUpMinDrift = settings.get().streaming.liveCatchup.minDrift;\n\n if (catchupMode === Constants.LIVE_CATCHUP_MODE_LOLP) {\n const currentBuffer = getBufferLevel();\n const playbackBufferMin = settings.get().streaming.liveCatchup.playbackBufferMin;\n\n return _lolpNeedToCatchUpCustom(currentLiveLatency, liveDelay, liveCatchUpMinDrift, currentBuffer, playbackBufferMin, liveCatchupLatencyThreshold);\n } else {\n return _defaultNeedToCatchUp(currentLiveLatency, liveDelay, liveCatchupLatencyThreshold, liveCatchUpMinDrift);\n }\n }\n } catch (e) {\n return false;\n }\n }\n\n /**\n * Default algorithm to determine if catchup mode should be enabled\n * @param {number} currentLiveLatency\n * @param {number} liveDelay\n * @param {number} liveCatchupLatencyThreshold\n * @param {number} minDrift\n * @return {boolean}\n * @private\n */\n function _defaultNeedToCatchUp(currentLiveLatency, liveDelay, liveCatchupLatencyThreshold, minDrift) {\n try {\n const latencyDrift = Math.abs(currentLiveLatency - liveDelay);\n\n return latencyDrift > minDrift && (isNaN(liveCatchupLatencyThreshold) || currentLiveLatency <= liveCatchupLatencyThreshold);\n } catch (e) {\n return false;\n }\n }\n\n /**\n * LoL+ logic to determine if catchup mode should be enabled\n * @param {number} currentLiveLatency\n * @param {number} liveDelay\n * @param {number} minDrift\n * @param {number} currentBuffer\n * @param {number} playbackBufferMin\n * @param {number} liveCatchupLatencyThreshold\n * @return {boolean}\n * @private\n */\n function _lolpNeedToCatchUpCustom(currentLiveLatency, liveDelay, minDrift, currentBuffer, playbackBufferMin, liveCatchupLatencyThreshold) {\n try {\n const latencyDrift = Math.abs(currentLiveLatency - liveDelay);\n\n return (isNaN(liveCatchupLatencyThreshold) || currentLiveLatency <= liveCatchupLatencyThreshold) && (latencyDrift > minDrift || currentBuffer < playbackBufferMin);\n } catch (e) {\n return false;\n }\n }\n\n /**\n * Apply catchup mode\n */\n function startPlaybackCatchUp() {\n if (videoModel) {\n let results;\n const currentPlaybackRate = videoModel.getPlaybackRate();\n const liveCatchupPlaybackRate = settings.get().streaming.liveCatchup.playbackRate;\n const currentLiveLatency = getCurrentLiveLatency();\n const liveDelay = mediaPlayerModel.getLiveDelay();\n const bufferLevel = getBufferLevel();\n // Custom playback control: Based on buffer level\n if (_getCatchupMode() === Constants.LIVE_CATCHUP_MODE_LOLP) {\n const liveCatchUpMinDrift = settings.get().streaming.liveCatchup.minDrift;\n const playbackBufferMin = settings.get().streaming.liveCatchup.playbackBufferMin;\n results = _calculateNewPlaybackRateLolP(liveCatchupPlaybackRate, currentLiveLatency, liveDelay, liveCatchUpMinDrift, playbackBufferMin, bufferLevel, currentPlaybackRate);\n } else {\n // Default playback control: Based on target and current latency\n results = _calculateNewPlaybackRateDefault(liveCatchupPlaybackRate, currentLiveLatency, liveDelay, bufferLevel, currentPlaybackRate);\n }\n\n // Obtain newRate and apply to video model\n let newRate = results.newRate;\n if (newRate) { // non-null\n videoModel.setPlaybackRate(newRate);\n }\n\n const deltaLatency = currentLiveLatency - liveDelay;\n if (settings.get().streaming.liveCatchup.maxDrift > 0 && !isLowLatencySeekingInProgress &&\n deltaLatency > settings.get().streaming.liveCatchup.maxDrift) {\n logger.info('Low Latency catchup mechanism. Latency too high, doing a seek to live point');\n isLowLatencySeekingInProgress = true;\n seekToLive();\n } else {\n isLowLatencySeekingInProgress = false;\n }\n }\n }\n\n /**\n * Default algorithm to calculate the new playback rate\n * @param {number} liveCatchUpPlaybackRate\n * @param {number} currentLiveLatency\n * @param {number} liveDelay\n * @param {number} bufferLevel\n * @param {number} currentPlaybackRate\n * @return {{newRate: number}}\n * @private\n */\n function _calculateNewPlaybackRateDefault(liveCatchUpPlaybackRate, currentLiveLatency, liveDelay, bufferLevel, currentPlaybackRate) {\n const cpr = liveCatchUpPlaybackRate;\n const deltaLatency = currentLiveLatency - liveDelay;\n const d = deltaLatency * 5;\n\n // Playback rate must be between (1 - cpr) - (1 + cpr)\n // ex: if cpr is 0.5, it can have values between 0.5 - 1.5\n const s = (cpr * 2) / (1 + Math.pow(Math.E, -d));\n let newRate = (1 - cpr) + s;\n // take into account situations in which there are buffer stalls,\n // in which increasing playbackRate to reach target latency will\n // just cause more and more stall situations\n if (playbackStalled) {\n // const bufferLevel = getBufferLevel();\n if (bufferLevel > liveDelay / 2) {\n // playbackStalled = false;\n playbackStalled = false;\n } else if (deltaLatency > 0) {\n newRate = 1.0;\n }\n }\n\n // don't change playbackrate for small variations (don't overload element with playbackrate changes)\n if (Math.abs(currentPlaybackRate - newRate) <= minPlaybackRateChange) {\n newRate = null;\n }\n\n return {\n newRate: newRate\n };\n\n }\n\n /**\n * Lol+ algorithm to calculate the new playback rate\n * @param {number} liveCatchUpPlaybackRate\n * @param {number} currentLiveLatency\n * @param {number} liveDelay\n * @param {number} minDrift\n * @param {number} playbackBufferMin\n * @param {number} bufferLevel\n * @param {number} currentPlaybackRate\n * @return {{newRate: number}}\n * @private\n */\n function _calculateNewPlaybackRateLolP(liveCatchUpPlaybackRate, currentLiveLatency, liveDelay, minDrift, playbackBufferMin, bufferLevel, currentPlaybackRate) {\n const cpr = liveCatchUpPlaybackRate;\n let newRate;\n\n // Hybrid: Buffer-based\n if (bufferLevel < playbackBufferMin) {\n // Buffer in danger, slow down\n const deltaBuffer = bufferLevel - playbackBufferMin; // -ve value\n const d = deltaBuffer * 5;\n\n // Playback rate must be between (1 - cpr) - (1 + cpr)\n // ex: if cpr is 0.5, it can have values between 0.5 - 1.5\n const s = (cpr * 2) / (1 + Math.pow(Math.E, -d));\n newRate = (1 - cpr) + s;\n\n logger.debug('[LoL+ playback control_buffer-based] bufferLevel: ' + bufferLevel + ', newRate: ' + newRate);\n } else {\n // Hybrid: Latency-based\n // Buffer is safe, vary playback rate based on latency\n\n // Check if latency is within range of target latency\n const minDifference = 0.02;\n if (Math.abs(currentLiveLatency - liveDelay) <= (minDifference * liveDelay)) {\n newRate = 1;\n } else {\n const deltaLatency = currentLiveLatency - liveDelay;\n const d = deltaLatency * 5;\n\n // Playback rate must be between (1 - cpr) - (1 + cpr)\n // ex: if cpr is 0.5, it can have values between 0.5 - 1.5\n const s = (cpr * 2) / (1 + Math.pow(Math.E, -d));\n newRate = (1 - cpr) + s;\n }\n\n logger.debug('[LoL+ playback control_latency-based] latency: ' + currentLiveLatency + ', newRate: ' + newRate);\n }\n\n if (playbackStalled) {\n if (bufferLevel > liveDelay / 2) {\n playbackStalled = false;\n }\n }\n\n // don't change playbackrate for small variations (don't overload element with playbackrate changes)\n if (Math.abs(currentPlaybackRate - newRate) <= minPlaybackRateChange) {\n newRate = null;\n }\n\n return {\n newRate: newRate\n };\n }\n\n function stopPlaybackCatchUp() {\n if (videoModel) {\n videoModel.setPlaybackRate(1.0);\n }\n }\n\n function _onFragmentLoadProgress(e) {\n // If using fetch and stream mode is not available, readjust live latency so it is 20% higher than segment duration\n if (e.stream === false && settings.get().streaming.lowLatencyEnabled && !isNaN(e.request.duration)) {\n const minDelay = 1.2 * e.request.duration;\n if (minDelay > mediaPlayerModel.getLiveDelay()) {\n logger.warn('Browser does not support fetch API with StreamReader. Increasing live delay to be 20% higher than segment duration:', minDelay.toFixed(2));\n settings.update({\n streaming: {\n delay: {\n liveDelay: minDelay,\n }\n }\n });\n }\n }\n }\n\n function _onBufferLevelStateChanged(e) {\n // do not stall playback when get an event from Stream that is not active\n if (e.streamId !== streamInfo.id) return;\n\n if (_isCatchupEnabled()) {\n if (e.state === MetricsConstants.BUFFER_EMPTY && !isSeeking()) {\n if (!playbackStalled) {\n playbackStalled = true;\n stopPlaybackCatchUp();\n }\n }\n } else {\n if (settings.get().streaming.buffer.setStallState) {\n videoModel.setStallState(e.mediaType, e.state === MetricsConstants.BUFFER_EMPTY);\n }\n }\n }\n\n function onPlaybackStalled(e) {\n eventBus.trigger(Events.PLAYBACK_STALLED, { e: e });\n }\n\n function _onStreamInitializing(e) {\n _checkEnableLowLatency(e.mediaInfo);\n }\n\n /**\n * We enable low latency playback if for the current representation availabilityTimeComplete is set to false\n * @param e\n * @private\n */\n function _onRepresentationSwitch(e) {\n const activeStreamInfo = streamController.getActiveStreamInfo();\n if (!settings.get().streaming.lowLatencyEnabledByManifest || !e || !activeStreamInfo || !e.currentRepresentation || !e.streamId || e.streamId !== activeStreamInfo.id || !e.mediaType || (e.mediaType !== Constants.VIDEO && e.mediaType !== Constants.AUDIO)) {\n return;\n }\n\n const lowLatencyEnabled = !e.currentRepresentation.availabilityTimeComplete;\n\n if (lowLatencyEnabled) {\n settings.update({\n streaming: {\n lowLatencyEnabled: lowLatencyEnabled\n }\n });\n }\n }\n\n /**\n * A new manifest has been loaded, updating is still in progress.\n * @private\n */\n function _onManifestUpdated() {\n manifestUpdateInProgress = true;\n }\n\n /**\n * Manifest update was completed\n * @private\n */\n function _onStreamsComposed() {\n manifestUpdateInProgress = false;\n }\n\n\n function _checkEnableLowLatency(mediaInfo) {\n if (mediaInfo && mediaInfo.supplementalProperties &&\n mediaInfo.supplementalProperties[Constants.SUPPLEMENTAL_PROPERTY_LL_SCHEME] === 'true') {\n logger.debug('Low Latency critical SupplementalProperty set: Enabling low Latency');\n settings.update({\n streaming: {\n lowLatencyEnabled: true\n }\n });\n }\n }\n\n function addAllListeners() {\n videoModel.addEventListener('canplay', _onCanPlay);\n videoModel.addEventListener('canplaythrough', _onCanPlayThrough);\n videoModel.addEventListener('play', _onPlaybackStart);\n videoModel.addEventListener('waiting', _onPlaybackWaiting);\n videoModel.addEventListener('playing', _onPlaybackPlaying);\n videoModel.addEventListener('pause', _onPlaybackPaused);\n videoModel.addEventListener('error', _onPlaybackError);\n videoModel.addEventListener('seeking', _onPlaybackSeeking);\n videoModel.addEventListener('seeked', _onPlaybackSeeked);\n videoModel.addEventListener('timeupdate', _onPlaybackTimeUpdated);\n videoModel.addEventListener('progress', _onPlaybackProgress);\n videoModel.addEventListener('ratechange', _onPlaybackRateChanged);\n videoModel.addEventListener('loadedmetadata', _onPlaybackMetaDataLoaded);\n videoModel.addEventListener('loadeddata', _onPlaybackLoadedData);\n videoModel.addEventListener('stalled', onPlaybackStalled);\n videoModel.addEventListener('ended', _onNativePlaybackEnded);\n }\n\n function removeAllListeners() {\n videoModel.removeEventListener('canplay', _onCanPlay);\n videoModel.removeEventListener('canplaythrough', _onCanPlayThrough);\n videoModel.removeEventListener('play', _onPlaybackStart);\n videoModel.removeEventListener('waiting', _onPlaybackWaiting);\n videoModel.removeEventListener('playing', _onPlaybackPlaying);\n videoModel.removeEventListener('pause', _onPlaybackPaused);\n videoModel.removeEventListener('error', _onPlaybackError);\n videoModel.removeEventListener('seeking', _onPlaybackSeeking);\n videoModel.removeEventListener('seeked', _onPlaybackSeeked);\n videoModel.removeEventListener('timeupdate', _onPlaybackTimeUpdated);\n videoModel.removeEventListener('progress', _onPlaybackProgress);\n videoModel.removeEventListener('ratechange', _onPlaybackRateChanged);\n videoModel.removeEventListener('loadedmetadata', _onPlaybackMetaDataLoaded);\n videoModel.removeEventListener('loadeddata', _onPlaybackLoadedData);\n videoModel.removeEventListener('stalled', onPlaybackStalled);\n videoModel.removeEventListener('ended', _onNativePlaybackEnded);\n }\n\n instance = {\n initialize,\n setConfig,\n getTimeToStreamEnd,\n getBufferLevel,\n getTime,\n getNormalizedTime,\n getIsManifestUpdateInProgress,\n getPlaybackRate,\n getPlayedRanges,\n getEnded,\n getIsDynamic,\n getStreamController,\n computeAndSetLiveDelay,\n getLiveDelay,\n getCurrentLiveLatency,\n play,\n isPaused,\n pause,\n isSeeking,\n getStreamEndTime,\n seek,\n reset,\n updateCurrentTime,\n getAvailabilityStartTime\n };\n\n setup();\n\n return instance;\n}\n\nPlaybackController.__dashjs_factory_name = 'PlaybackController';\nexport default FactoryMaker.getSingletonFactory(PlaybackController);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Debug from '../core/Debug';\nimport DashJSError from './vo/DashJSError';\nimport FactoryMaker from '../core/FactoryMaker';\nimport Errors from '../core/errors/Errors';\nimport Settings from '../core/Settings';\nimport constants from './constants/Constants';\nimport {HTTPRequest} from './vo/metrics/HTTPRequest';\nimport Events from '../core/events/Events';\n\nconst APPEND_WINDOW_START_OFFSET = 0.1;\nconst APPEND_WINDOW_END_OFFSET = 0.01;\n\n/**\n * @class SourceBufferSink\n * @ignore\n * @implements FragmentSink\n */\n\nconst CHECK_INTERVAL = 50;\n\nfunction SourceBufferSink(config) {\n const context = this.context;\n const settings = Settings(context).getInstance();\n const textController = config.textController;\n const eventBus = config.eventBus;\n\n let instance,\n type,\n logger,\n buffer,\n mediaInfo,\n intervalId;\n\n let callbacks = [];\n let appendQueue = [];\n let isAppendingInProgress = false;\n let mediaSource = config.mediaSource;\n let lastRequestAppended = null;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n }\n\n function initializeForStreamSwitch(mInfo, selectedRepresentation, oldSourceBufferSink) {\n mediaInfo = mInfo;\n type = mediaInfo.type;\n const codec = mediaInfo.codec;\n\n _copyPreviousSinkData(oldSourceBufferSink);\n _addEventListeners();\n\n const promises = [];\n\n promises.push(_abortBeforeAppend);\n promises.push(updateAppendWindow(mediaInfo.streamInfo));\n promises.push(changeType(codec));\n\n if (selectedRepresentation && selectedRepresentation.MSETimeOffset !== undefined) {\n promises.push(updateTimestampOffset(selectedRepresentation.MSETimeOffset));\n }\n\n return Promise.all(promises);\n }\n\n function changeType(codec) {\n return new Promise((resolve) => {\n _waitForUpdateEnd(() => {\n if (buffer.changeType) {\n buffer.changeType(codec);\n }\n resolve();\n });\n });\n }\n\n function _copyPreviousSinkData(oldSourceBufferSink) {\n buffer = oldSourceBufferSink.getBuffer();\n }\n\n function initializeForFirstUse(streamInfo, mInfo, selectedRepresentation) {\n mediaInfo = mInfo;\n type = mediaInfo.type;\n const codec = mediaInfo.codec;\n try {\n // Safari claims to support anything starting 'application/mp4'.\n // it definitely doesn't understand 'application/mp4;codecs=\"stpp\"'\n // - currently no browser does, so check for it and use our own\n // implementation. The same is true for codecs=\"wvtt\".\n if (codec.match(/application\\/mp4;\\s*codecs=\"(stpp|wvtt).*\"/i)) {\n return _initializeForText(streamInfo);\n }\n\n buffer = mediaSource.addSourceBuffer(codec);\n\n _addEventListeners();\n\n const promises = [];\n\n promises.push(updateAppendWindow(mediaInfo.streamInfo));\n\n if (selectedRepresentation && selectedRepresentation.MSETimeOffset !== undefined) {\n promises.push(updateTimestampOffset(selectedRepresentation.MSETimeOffset));\n }\n\n return Promise.all(promises);\n\n } catch (e) {\n // Note that in the following, the quotes are open to allow for extra text after stpp and wvtt\n if ((mediaInfo.type == constants.TEXT && !mediaInfo.isFragmented) || (codec.indexOf('codecs=\"stpp') !== -1) || (codec.indexOf('codecs=\"vtt') !== -1)) {\n return _initializeForText(streamInfo);\n }\n return Promise.reject(e);\n }\n }\n\n function _initializeForText(streamInfo) {\n buffer = textController.getTextSourceBuffer(streamInfo);\n return Promise.resolve();\n }\n\n function _addEventListeners() {\n // use updateend event if possible\n if (typeof buffer.addEventListener === 'function') {\n try {\n buffer.addEventListener('updateend', _updateEndHandler, false);\n buffer.addEventListener('error', _errHandler, false);\n buffer.addEventListener('abort', _errHandler, false);\n\n } catch (err) {\n // use setInterval to periodically check if updating has been completed\n intervalId = setInterval(_updateEndHandler, CHECK_INTERVAL);\n }\n } else {\n // use setInterval to periodically check if updating has been completed\n intervalId = setInterval(_updateEndHandler, CHECK_INTERVAL);\n }\n }\n\n function getType() {\n return type;\n }\n\n function _removeEventListeners() {\n try {\n if (typeof buffer.removeEventListener === 'function') {\n buffer.removeEventListener('updateend', _updateEndHandler, false);\n buffer.removeEventListener('error', _errHandler, false);\n buffer.removeEventListener('abort', _errHandler, false);\n }\n clearInterval(intervalId);\n } catch (e) {\n logger.error(e);\n }\n }\n\n function updateAppendWindow(sInfo) {\n return new Promise((resolve) => {\n\n if (!buffer || !settings.get().streaming.buffer.useAppendWindow) {\n resolve();\n return;\n }\n\n _waitForUpdateEnd(() => {\n try {\n if (!buffer) {\n resolve();\n return;\n }\n\n let appendWindowEnd = mediaSource.duration;\n let appendWindowStart = 0;\n if (sInfo && !isNaN(sInfo.start) && !isNaN(sInfo.duration) && isFinite(sInfo.duration)) {\n appendWindowEnd = sInfo.start + sInfo.duration;\n }\n if (sInfo && !isNaN(sInfo.start)) {\n appendWindowStart = sInfo.start;\n }\n if (buffer.appendWindowEnd !== appendWindowEnd || buffer.appendWindowStart !== appendWindowStart) {\n buffer.appendWindowStart = 0;\n buffer.appendWindowEnd = appendWindowEnd + APPEND_WINDOW_END_OFFSET;\n buffer.appendWindowStart = Math.max(appendWindowStart - APPEND_WINDOW_START_OFFSET, 0);\n logger.debug(`Updated append window for ${mediaInfo.type}. Set start to ${buffer.appendWindowStart} and end to ${buffer.appendWindowEnd}`);\n }\n\n resolve();\n } catch (e) {\n logger.warn(`Failed to set append window`);\n resolve();\n }\n });\n });\n }\n\n function updateTimestampOffset(MSETimeOffset) {\n return new Promise((resolve) => {\n\n if (!buffer) {\n resolve();\n return;\n }\n\n _waitForUpdateEnd(() => {\n try {\n if (buffer.timestampOffset !== MSETimeOffset && !isNaN(MSETimeOffset)) {\n buffer.timestampOffset = MSETimeOffset;\n logger.debug(`Set MSE timestamp offset to ${MSETimeOffset}`);\n }\n resolve();\n } catch (e) {\n resolve();\n }\n });\n });\n }\n\n\n function reset() {\n if (buffer) {\n try {\n callbacks = [];\n _removeEventListeners();\n isAppendingInProgress = false;\n appendQueue = [];\n if (!buffer.getClassName || buffer.getClassName() !== 'TextSourceBuffer') {\n logger.debug(`Removing sourcebuffer from media source`);\n mediaSource.removeSourceBuffer(buffer);\n }\n } catch (e) {\n\n }\n buffer = null;\n }\n lastRequestAppended = null;\n }\n\n function getBuffer() {\n return buffer;\n }\n\n function getAllBufferRanges() {\n try {\n return buffer.buffered;\n } catch (e) {\n logger.error('getAllBufferRanges exception: ' + e.message);\n return null;\n }\n }\n\n function append(chunk, request = null) {\n return new Promise((resolve, reject) => {\n if (!chunk) {\n reject({\n chunk: chunk,\n error: new DashJSError(Errors.APPEND_ERROR_CODE, Errors.APPEND_ERROR_MESSAGE)\n });\n return;\n }\n appendQueue.push({ data: chunk, promise: { resolve, reject }, request });\n _waitForUpdateEnd(_appendNextInQueue.bind(this));\n });\n }\n\n function _abortBeforeAppend() {\n return new Promise((resolve) => {\n _waitForUpdateEnd(() => {\n // Save the append window, which is reset on abort().\n const appendWindowStart = buffer.appendWindowStart;\n const appendWindowEnd = buffer.appendWindowEnd;\n\n if (buffer) {\n buffer.abort();\n buffer.appendWindowStart = appendWindowStart;\n buffer.appendWindowEnd = appendWindowEnd;\n }\n resolve();\n });\n });\n }\n\n function remove(range) {\n return new Promise((resolve, reject) => {\n const start = range.start;\n const end = range.end;\n\n // make sure that the given time range is correct. Otherwise we will get InvalidAccessError\n if (!((start >= 0) && (end > start))) {\n resolve();\n return;\n }\n\n _waitForUpdateEnd(function () {\n try {\n buffer.remove(start, end);\n // updating is in progress, we should wait for it to complete before signaling that this operation is done\n _waitForUpdateEnd(function () {\n resolve({\n from: start,\n to: end,\n unintended: false\n });\n if (range.resolve) {\n range.resolve();\n }\n });\n } catch (err) {\n reject({\n from: start,\n to: end,\n unintended: false,\n error: new DashJSError(Errors.REMOVE_ERROR_CODE, Errors.REMOVE_ERROR_MESSAGE)\n });\n if (range.reject) {\n range.reject(err);\n }\n }\n });\n });\n }\n\n function _appendNextInQueue() {\n if (isAppendingInProgress) {\n return;\n }\n\n if (appendQueue.length > 0) {\n isAppendingInProgress = true;\n const nextChunk = appendQueue[0];\n appendQueue.splice(0, 1);\n\n const afterSuccess = function () {\n isAppendingInProgress = false;\n if (appendQueue.length > 0) {\n _appendNextInQueue.call(this);\n }\n // Init segments are cached. In any other case we dont need the chunk bytes anymore and can free the memory\n if (nextChunk && nextChunk.data && nextChunk.data.segmentType && nextChunk.data.segmentType !== HTTPRequest.INIT_SEGMENT_TYPE) {\n delete nextChunk.data.bytes;\n }\n nextChunk.promise.resolve({ chunk: nextChunk.data });\n };\n\n try {\n lastRequestAppended = nextChunk.request;\n if (nextChunk.data.bytes.byteLength === 0) {\n afterSuccess.call(this);\n } else {\n if (buffer.appendBuffer) {\n buffer.appendBuffer(nextChunk.data.bytes);\n } else {\n buffer.append(nextChunk.data.bytes, nextChunk.data);\n }\n // updating is in progress, we should wait for it to complete before signaling that this operation is done\n _waitForUpdateEnd(afterSuccess.bind(this));\n }\n } catch (err) {\n logger.fatal('SourceBuffer append failed \"' + err + '\"');\n if (appendQueue.length > 0) {\n _appendNextInQueue();\n } else {\n isAppendingInProgress = false;\n }\n\n delete nextChunk.data.bytes;\n nextChunk.promise.reject({ chunk: nextChunk.data, error: new DashJSError(err.code, err.message) });\n }\n }\n }\n\n function abort() {\n return new Promise((resolve) => {\n try {\n appendQueue = [];\n if (mediaSource.readyState === 'open') {\n _waitForUpdateEnd(() => {\n try {\n if (buffer) {\n buffer.abort();\n }\n resolve();\n } catch (e) {\n resolve();\n }\n });\n } else if (buffer && buffer.setTextTrack && mediaSource.readyState === 'ended') {\n buffer.abort(); //The cues need to be removed from the TextSourceBuffer via a call to abort()\n resolve();\n } else {\n resolve();\n }\n } catch (e) {\n resolve();\n }\n });\n }\n\n function _executeCallback() {\n if (callbacks.length > 0) {\n if (!buffer.updating) {\n const cb = callbacks.shift();\n cb();\n // Try to execute next callback if still not updating\n _executeCallback();\n }\n }\n }\n\n function _updateEndHandler() {\n // if updating is still in progress do nothing and wait for the next check again.\n if (buffer.updating) {\n return;\n }\n\n // updating is completed, now we can stop checking and resolve the promise\n _executeCallback();\n }\n\n function _errHandler(e) {\n const error = e.target || {};\n _triggerEvent(Events.SOURCE_BUFFER_ERROR, { error, lastRequestAppended })\n }\n\n function _triggerEvent(eventType, data) {\n let payload = data || {};\n eventBus.trigger(eventType, payload, { streamId: mediaInfo.streamInfo.id, mediaType: type });\n }\n\n function _waitForUpdateEnd(callback) {\n callbacks.push(callback);\n\n if (!buffer.updating) {\n _executeCallback();\n }\n }\n\n instance = {\n getType,\n getAllBufferRanges,\n getBuffer,\n append,\n remove,\n abort,\n reset,\n updateTimestampOffset,\n initializeForStreamSwitch,\n initializeForFirstUse,\n updateAppendWindow,\n changeType\n };\n\n setup();\n\n return instance;\n}\n\nSourceBufferSink.__dashjs_factory_name = 'SourceBufferSink';\nconst factory = FactoryMaker.getClassFactory(SourceBufferSink);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * Represents data structure to keep and drive {DataChunk}\n */\n\nimport FactoryMaker from '../../core/FactoryMaker';\n\nfunction InitCache() {\n\n let data = {};\n\n function save (chunk) {\n const id = chunk.streamId;\n const representationId = chunk.representationId;\n\n data[id] = data[id] || {};\n data[id][representationId] = chunk;\n }\n\n function extract (streamId, representationId) {\n if (data && data[streamId] && data[streamId][representationId]) {\n return data[streamId][representationId];\n } else {\n return null;\n }\n }\n\n\n function reset () {\n data = {};\n }\n\n const instance = {\n save: save,\n extract: extract,\n reset: reset\n };\n\n return instance;\n}\n\nInitCache.__dashjs_factory_name = 'InitCache';\nexport default FactoryMaker.getSingletonFactory(InitCache);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Constants from '../constants/Constants';\nimport MetricsConstants from '../constants/MetricsConstants';\nimport FragmentModel from '../models/FragmentModel';\nimport SourceBufferSink from '../SourceBufferSink';\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Debug from '../../core/Debug';\nimport InitCache from '../utils/InitCache';\nimport DashJSError from '../vo/DashJSError';\nimport Errors from '../../core/errors/Errors';\nimport {HTTPRequest} from '../vo/metrics/HTTPRequest';\nimport MediaPlayerEvents from '../../streaming/MediaPlayerEvents';\n\nconst BUFFER_END_THRESHOLD = 0.5;\nconst BUFFER_RANGE_CALCULATION_THRESHOLD = 0.01;\nconst QUOTA_EXCEEDED_ERROR_CODE = 22;\n\nconst BUFFER_CONTROLLER_TYPE = 'BufferController';\n\nfunction BufferController(config) {\n\n config = config || {};\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n const errHandler = config.errHandler;\n const fragmentModel = config.fragmentModel;\n const representationController = config.representationController;\n const adapter = config.adapter;\n const textController = config.textController;\n const abrController = config.abrController;\n const playbackController = config.playbackController;\n const streamInfo = config.streamInfo;\n const type = config.type;\n const settings = config.settings;\n\n let instance,\n logger,\n isBufferingCompleted,\n bufferLevel,\n criticalBufferLevel,\n mediaSource,\n maxAppendedIndex,\n maximumIndex,\n sourceBufferSink,\n bufferState,\n appendedBytesInfo,\n wallclockTicked,\n isPruningInProgress,\n isQuotaExceeded,\n initCache,\n pendingPruningRanges,\n replacingBuffer,\n seekTarget;\n\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n initCache = InitCache(context).getInstance();\n\n resetInitialSettings();\n }\n\n /**\n * Initialize the BufferController. Sets the media source and registers the event handlers.\n * @param {object} mediaSource\n */\n function initialize(mediaSource) {\n setMediaSource(mediaSource);\n\n eventBus.on(Events.INIT_FRAGMENT_LOADED, _onInitFragmentLoaded, instance);\n eventBus.on(Events.MEDIA_FRAGMENT_LOADED, _onMediaFragmentLoaded, instance);\n eventBus.on(Events.WALLCLOCK_TIME_UPDATED, _onWallclockTimeUpdated, instance);\n\n eventBus.on(MediaPlayerEvents.PLAYBACK_PLAYING, _onPlaybackPlaying, instance);\n eventBus.on(MediaPlayerEvents.PLAYBACK_PROGRESS, _onPlaybackProgression, instance);\n eventBus.on(MediaPlayerEvents.PLAYBACK_TIME_UPDATED, _onPlaybackProgression, instance);\n eventBus.on(MediaPlayerEvents.PLAYBACK_RATE_CHANGED, _onPlaybackRateChanged, instance);\n eventBus.on(MediaPlayerEvents.PLAYBACK_STALLED, _onPlaybackStalled, instance);\n }\n\n /**\n * Returns the stream id\n * @return {string}\n */\n function getStreamId() {\n return streamInfo.id;\n }\n\n /**\n * Returns the media type\n * @return {type}\n */\n function getType() {\n return type;\n }\n\n /**\n * Returns the type of the BufferController. We distinguish between standard buffer controllers and buffer controllers related to texttracks.\n * @return {string}\n */\n function getBufferControllerType() {\n return BUFFER_CONTROLLER_TYPE;\n }\n\n /**\n * Sets the mediasource.\n * @param {object} value\n */\n function setMediaSource(value) {\n mediaSource = value;\n }\n\n /**\n * Get the RepresentationInfo for a certain quality.\n * @param {number} quality\n * @return {object}\n * @private\n */\n function _getRepresentationInfo(quality) {\n return adapter.convertRepresentationToRepresentationInfo(representationController.getRepresentationForQuality(quality));\n }\n\n /**\n * Creates a SourceBufferSink object\n * @param {object} mediaInfo\n * @param {array} oldBufferSinks\n * @return {object|null} SourceBufferSink\n */\n function createBufferSink(mediaInfo, oldBufferSinks = []) {\n return new Promise((resolve, reject) => {\n if (!initCache || !mediaInfo || !mediaSource) {\n resolve(null);\n return;\n }\n\n const requiredQuality = abrController.getQualityFor(type, streamInfo.id);\n sourceBufferSink = SourceBufferSink(context).create({\n mediaSource,\n textController,\n eventBus\n });\n _initializeSink(mediaInfo, oldBufferSinks, requiredQuality)\n .then(() => {\n return updateBufferTimestampOffset(_getRepresentationInfo(requiredQuality));\n })\n .then(() => {\n resolve(sourceBufferSink);\n })\n .catch((e) => {\n logger.fatal('Caught error on create SourceBuffer: ' + e);\n errHandler.error(new DashJSError(Errors.MEDIASOURCE_TYPE_UNSUPPORTED_CODE, Errors.MEDIASOURCE_TYPE_UNSUPPORTED_MESSAGE + type));\n reject(e);\n });\n });\n }\n\n function _initializeSink(mediaInfo, oldBufferSinks, requiredQuality) {\n const selectedRepresentation = _getRepresentationInfo(requiredQuality);\n\n if (oldBufferSinks && oldBufferSinks[type] && (type === Constants.VIDEO || type === Constants.AUDIO)) {\n return sourceBufferSink.initializeForStreamSwitch(mediaInfo, selectedRepresentation, oldBufferSinks[type]);\n } else {\n return sourceBufferSink.initializeForFirstUse(streamInfo, mediaInfo, selectedRepresentation);\n }\n }\n\n\n /**\n * Callback handler when init segment has been loaded. Based on settings, the init segment is saved to the cache, and appended to the buffer.\n * @param {object} e\n * @private\n */\n function _onInitFragmentLoaded(e) {\n if (settings.get().streaming.cacheInitSegments) {\n logger.info('Init fragment finished loading saving to', type + '\\'s init cache');\n initCache.save(e.chunk);\n }\n logger.debug('Append Init fragment', type, ' with representationId:', e.chunk.representationId, ' and quality:', e.chunk.quality, ', data size:', e.chunk.bytes.byteLength);\n _appendToBuffer(e.chunk);\n }\n\n /**\n * Append the init segment for a certain representation to the buffer. If the init segment is cached we take the one from the cache. Otherwise the function returns false and the segment has to be requested again.\n * @param {string} representationId\n * @return {boolean}\n */\n function appendInitSegmentFromCache(representationId) {\n // Get init segment from cache\n const chunk = initCache.extract(streamInfo.id, representationId);\n\n if (!chunk) {\n // Init segment not in cache, shall be requested\n return false;\n }\n\n // Append init segment into buffer\n logger.info('Append Init fragment', type, ' with representationId:', chunk.representationId, ' and quality:', chunk.quality, ', data size:', chunk.bytes.byteLength);\n _appendToBuffer(chunk);\n\n return true;\n }\n\n /**\n * Calls the _appendToBuffer function to append the segment to the buffer. In case of a track switch the buffer might be cleared.\n * @param {object} e\n */\n function _onMediaFragmentLoaded(e) {\n _appendToBuffer(e.chunk, e.request);\n }\n\n /**\n * Append data to the MSE buffer using the SourceBufferSink\n * @param {object} chunk\n * @private\n */\n function _appendToBuffer(chunk, request = null) {\n sourceBufferSink.append(chunk, request)\n .then((e) => {\n _onAppended(e);\n })\n .catch((e) => {\n _onAppended(e);\n });\n\n if (chunk.mediaInfo.type === Constants.VIDEO) {\n _triggerEvent(Events.VIDEO_CHUNK_RECEIVED, { chunk: chunk });\n }\n }\n\n function _showBufferRanges(ranges) {\n if (ranges && ranges.length > 0) {\n for (let i = 0, len = ranges.length; i < len; i++) {\n logger.debug('Buffered range: ' + ranges.start(i) + ' - ' + ranges.end(i) + ', currentTime = ', playbackController.getTime());\n }\n }\n }\n\n function _onAppended(e) {\n if (e.error) {\n // If we receive a QUOTA_EXCEEDED_ERROR_CODE we should adjust the target buffer times to avoid this error in the future.\n if (e.error.code === QUOTA_EXCEEDED_ERROR_CODE) {\n _handleQuotaExceededError();\n }\n if (e.error.code === QUOTA_EXCEEDED_ERROR_CODE || !hasEnoughSpaceToAppend()) {\n logger.warn('Clearing playback buffer to overcome quota exceed situation');\n // Notify ScheduleController to stop scheduling until buffer has been pruned\n _triggerEvent(Events.QUOTA_EXCEEDED, {\n criticalBufferLevel: criticalBufferLevel,\n quotaExceededTime: e.chunk.start\n });\n clearBuffers(getClearRanges());\n }\n return;\n }\n\n // Check if session has not been stopped in the meantime (while last segment was being appended)\n if (!sourceBufferSink) return;\n\n _updateBufferLevel();\n\n isQuotaExceeded = false;\n appendedBytesInfo = e.chunk;\n\n if (!appendedBytesInfo || !appendedBytesInfo.endFragment) {\n return;\n }\n\n if (appendedBytesInfo && !isNaN(appendedBytesInfo.index)) {\n maxAppendedIndex = Math.max(appendedBytesInfo.index, maxAppendedIndex);\n _checkIfBufferingCompleted();\n }\n\n const ranges = sourceBufferSink.getAllBufferRanges();\n if (appendedBytesInfo.segmentType === HTTPRequest.MEDIA_SEGMENT_TYPE) {\n _showBufferRanges(ranges);\n _onPlaybackProgression();\n _adjustSeekTarget();\n }\n\n if (appendedBytesInfo) {\n _triggerEvent(Events.BYTES_APPENDED_END_FRAGMENT, {\n quality: appendedBytesInfo.quality,\n startTime: appendedBytesInfo.start,\n index: appendedBytesInfo.index,\n bufferedRanges: ranges,\n segmentType: appendedBytesInfo.segmentType,\n mediaType: type\n });\n }\n }\n\n /**\n * In some cases the segment we requested might start at a different time than we initially aimed for. segments timeline/template tolerance.\n * We might need to do an internal seek if there is drift.\n * @private\n */\n function _adjustSeekTarget() {\n if (isNaN(seekTarget)) return;\n // Check buffered data only for audio and video\n if (type !== Constants.AUDIO && type !== Constants.VIDEO) {\n seekTarget = NaN;\n return;\n }\n\n // Check if current buffered range already contains seek target (and current video element time)\n const currentTime = playbackController.getTime();\n let range = getRangeAt(seekTarget, 0);\n if (currentTime === seekTarget && range) {\n seekTarget = NaN;\n return;\n }\n\n // Get buffered range corresponding to the seek target\n const segmentDuration = representationController.getCurrentRepresentation().segmentDuration;\n range = getRangeAt(seekTarget, segmentDuration);\n if (!range) return;\n\n if (settings.get().streaming.buffer.enableSeekDecorrelationFix && Math.abs(currentTime - seekTarget) > segmentDuration) {\n // If current video model time is decorrelated from seek target (and appended buffer) then seek video element\n // (in case of live streams on some browsers/devices for which we can't set video element time at unavalaible range)\n\n // Check if appended segment is not anterior from seek target (segments timeline/template tolerance)\n if (seekTarget <= range.end) {\n // Seek video element to seek target or range start if appended buffer starts after seek target (segments timeline/template tolerance)\n playbackController.seek(Math.max(seekTarget, range.start), false, true);\n }\n } else if (currentTime < range.start) {\n // If appended buffer starts after seek target (segments timeline/template tolerance) then seek to range start\n playbackController.seek(range.start, false, true);\n }\n }\n\n function _handleQuotaExceededError() {\n isQuotaExceeded = true;\n criticalBufferLevel = getTotalBufferedTime() * 0.8;\n logger.warn('Quota exceeded, Critical Buffer: ' + criticalBufferLevel);\n\n if (criticalBufferLevel > 0) {\n // recalculate buffer lengths according to criticalBufferLevel\n const bufferToKeep = Math.max(0.2 * criticalBufferLevel, 1);\n const bufferAhead = criticalBufferLevel - bufferToKeep;\n const bufferTimeAtTopQuality = Math.min(settings.get().streaming.buffer.bufferTimeAtTopQuality, bufferAhead * 0.9);\n const bufferTimeAtTopQualityLongForm = Math.min(settings.get().streaming.buffer.bufferTimeAtTopQualityLongForm, bufferAhead * 0.9);\n const s = {\n streaming: {\n buffer: {\n bufferToKeep: parseFloat(bufferToKeep.toFixed(5)),\n bufferTimeAtTopQuality: parseFloat(bufferTimeAtTopQuality.toFixed(5)),\n bufferTimeAtTopQualityLongForm: parseFloat(bufferTimeAtTopQualityLongForm.toFixed(5))\n }\n }\n };\n settings.update(s);\n }\n }\n\n //**********************************************************************\n // START Buffer Level, State & Sufficiency Handling.\n //**********************************************************************\n function prepareForPlaybackSeek() {\n if (isBufferingCompleted) {\n setIsBufferingCompleted(false);\n }\n\n // Abort the current request and empty all possible segments to be appended\n return sourceBufferSink.abort();\n }\n\n function prepareForReplacementTrackSwitch(codec) {\n return new Promise((resolve, reject) => {\n sourceBufferSink.abort()\n .then(() => {\n return updateAppendWindow();\n })\n .then(() => {\n return sourceBufferSink.changeType(codec);\n })\n .then(() => {\n return pruneAllSafely();\n })\n .then(() => {\n setIsBufferingCompleted(false);\n resolve();\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n function prepareForReplacementQualitySwitch() {\n return new Promise((resolve, reject) => {\n sourceBufferSink.abort()\n .then(() => {\n return updateAppendWindow();\n })\n .then(() => {\n return pruneAllSafely();\n })\n .then(() => {\n setIsBufferingCompleted(false);\n resolve();\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n function prepareForNonReplacementTrackSwitch(codec) {\n return new Promise((resolve, reject) => {\n updateAppendWindow()\n .then(() => {\n return sourceBufferSink.changeType(codec);\n })\n .then(() => {\n resolve();\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n function pruneAllSafely() {\n return new Promise((resolve, reject) => {\n let ranges = getAllRangesWithSafetyFactor();\n\n if (!ranges || ranges.length === 0) {\n _onPlaybackProgression();\n resolve();\n return;\n }\n\n clearBuffers(ranges)\n .then(() => {\n resolve();\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n function getAllRangesWithSafetyFactor(seekTime) {\n const clearRanges = [];\n const ranges = sourceBufferSink.getAllBufferRanges();\n\n // no valid ranges\n if (!ranges || ranges.length === 0) {\n return clearRanges;\n }\n\n // if no target time is provided we clear everyhing\n if ((!seekTime && seekTime !== 0) || isNaN(seekTime)) {\n clearRanges.push({\n start: ranges.start(0),\n end: ranges.end(ranges.length - 1) + BUFFER_END_THRESHOLD\n });\n }\n\n // otherwise we need to calculate the correct pruning range\n else {\n\n const behindPruningRange = _getRangeBehindForPruning(seekTime, ranges);\n const aheadPruningRange = _getRangeAheadForPruning(seekTime, ranges);\n\n if (behindPruningRange) {\n clearRanges.push(behindPruningRange);\n }\n\n if (aheadPruningRange) {\n clearRanges.push(aheadPruningRange);\n }\n }\n\n return clearRanges;\n }\n\n function _getRangeBehindForPruning(targetTime, ranges) {\n const bufferToKeepBehind = settings.get().streaming.buffer.bufferToKeep;\n const startOfBuffer = ranges.start(0);\n\n // if we do a seek ahead of the current play position we do need to prune behind the new play position\n const behindDiff = targetTime - startOfBuffer;\n if (behindDiff > bufferToKeepBehind) {\n\n let rangeEnd = Math.max(0, targetTime - bufferToKeepBehind);\n // Ensure we keep full range of current fragment\n const currentTimeRequest = fragmentModel.getRequests({\n state: FragmentModel.FRAGMENT_MODEL_EXECUTED,\n time: targetTime,\n threshold: BUFFER_RANGE_CALCULATION_THRESHOLD\n })[0];\n\n if (currentTimeRequest) {\n rangeEnd = Math.min(currentTimeRequest.startTime, rangeEnd);\n }\n if (rangeEnd > 0) {\n return {\n start: startOfBuffer,\n end: rangeEnd\n };\n }\n }\n\n return null;\n }\n\n function _getRangeAheadForPruning(targetTime, ranges) {\n // if we do a seek behind the current play position we do need to prune ahead of the new play position\n const endOfBuffer = ranges.end(ranges.length - 1) + BUFFER_END_THRESHOLD;\n const isLongFormContent = streamInfo.manifestInfo.duration >= settings.get().streaming.buffer.longFormContentDurationThreshold;\n const bufferToKeepAhead = isLongFormContent ? settings.get().streaming.buffer.bufferTimeAtTopQualityLongForm : settings.get().streaming.buffer.bufferTimeAtTopQuality;\n const aheadDiff = endOfBuffer - targetTime;\n\n if (aheadDiff > bufferToKeepAhead) {\n\n let rangeStart = targetTime + bufferToKeepAhead;\n // Ensure we keep full range of current fragment\n const currentTimeRequest = fragmentModel.getRequests({\n state: FragmentModel.FRAGMENT_MODEL_EXECUTED,\n time: targetTime,\n threshold: BUFFER_RANGE_CALCULATION_THRESHOLD\n })[0];\n\n if (currentTimeRequest) {\n rangeStart = Math.max(currentTimeRequest.startTime + currentTimeRequest.duration, rangeStart);\n }\n if (rangeStart < endOfBuffer) {\n return {\n start: rangeStart,\n end: endOfBuffer\n };\n }\n }\n\n return null;\n }\n\n function _onPlaybackProgression() {\n if (!replacingBuffer || (type === Constants.TEXT && textController.isTextEnabled())) {\n _updateBufferLevel();\n }\n }\n\n function _onPlaybackStalled() {\n checkIfSufficientBuffer();\n }\n\n function _onPlaybackPlaying() {\n checkIfSufficientBuffer();\n seekTarget = NaN;\n }\n\n function getRangeAt(time, tolerance) {\n const ranges = sourceBufferSink.getAllBufferRanges();\n let start = 0;\n let end = 0;\n let firstStart = null;\n let lastEnd = null;\n let gap = 0;\n let len,\n i;\n\n const toler = !isNaN(tolerance) ? tolerance : 0.15;\n\n if (ranges !== null && ranges !== undefined) {\n for (i = 0, len = ranges.length; i < len; i++) {\n start = ranges.start(i);\n end = ranges.end(i);\n if (firstStart === null) {\n gap = Math.abs(start - time);\n if (time >= start && time < end) {\n // start the range\n firstStart = start;\n lastEnd = end;\n } else if (gap <= toler) {\n // start the range even though the buffer does not contain time 0\n firstStart = start;\n lastEnd = end;\n }\n } else {\n gap = start - lastEnd;\n if (gap <= toler) {\n // the discontinuity is smaller than the tolerance, combine the ranges\n lastEnd = end;\n } else {\n break;\n }\n }\n }\n\n if (firstStart !== null) {\n return {\n start: firstStart,\n end: lastEnd\n };\n }\n }\n\n return null;\n }\n\n function getBufferLength(time, tolerance) {\n let range,\n length;\n\n // Consider gap/discontinuity limit as tolerance\n if (settings.get().streaming.gaps.jumpGaps) {\n tolerance = settings.get().streaming.gaps.smallGapLimit;\n }\n\n range = getRangeAt(time, tolerance);\n\n if (range === null) {\n length = 0;\n } else {\n length = range.end - time;\n }\n\n return length;\n }\n\n function _updateBufferLevel() {\n if (playbackController) {\n const tolerance = settings.get().streaming.gaps.jumpGaps && !isNaN(settings.get().streaming.gaps.smallGapLimit) ? settings.get().streaming.gaps.smallGapLimit : NaN;\n bufferLevel = Math.max(getBufferLength(playbackController.getTime() || 0, tolerance), 0);\n _triggerEvent(Events.BUFFER_LEVEL_UPDATED, { mediaType: type, bufferLevel: bufferLevel });\n checkIfSufficientBuffer();\n }\n }\n\n function _checkIfBufferingCompleted() {\n const isLastIdxAppended = maxAppendedIndex >= maximumIndex - 1; // Handles 0 and non 0 based request index\n const periodBuffered = playbackController.getTimeToStreamEnd(streamInfo) - bufferLevel <= 0;\n\n if ((isLastIdxAppended || periodBuffered) && !isBufferingCompleted) {\n setIsBufferingCompleted(true);\n logger.debug(`checkIfBufferingCompleted trigger BUFFERING_COMPLETED for stream id ${streamInfo.id} and type ${type}`);\n }\n }\n\n function checkIfSufficientBuffer() {\n // No need to check buffer if type is not audio or video (for example if several errors occur during text parsing, so that the buffer cannot be filled, no error must occur on video playback)\n if (type !== Constants.AUDIO && type !== Constants.VIDEO) return;\n\n // When the player is working in low latency mode, the buffer is often below STALL_THRESHOLD.\n // So, when in low latency mode, change dash.js behavior so it notifies a stall just when\n // buffer reach 0 seconds\n if (((!settings.get().streaming.lowLatencyEnabled && bufferLevel < settings.get().streaming.buffer.stallThreshold) || bufferLevel === 0) && !isBufferingCompleted) {\n _notifyBufferStateChanged(MetricsConstants.BUFFER_EMPTY);\n } else {\n if (isBufferingCompleted || bufferLevel >= settings.get().streaming.buffer.stallThreshold || (settings.get().streaming.lowLatencyEnabled && bufferLevel > 0)) {\n _notifyBufferStateChanged(MetricsConstants.BUFFER_LOADED);\n }\n }\n }\n\n function _notifyBufferStateChanged(state) {\n if (bufferState === state ||\n (state === MetricsConstants.BUFFER_EMPTY && playbackController.getTime() === 0) || // Don't trigger BUFFER_EMPTY if it's initial loading\n (type === Constants.TEXT && !textController.isTextEnabled())) {\n return;\n }\n\n bufferState = state;\n\n _triggerEvent(Events.BUFFER_LEVEL_STATE_CHANGED, { state: state });\n _triggerEvent(state === MetricsConstants.BUFFER_LOADED ? Events.BUFFER_LOADED : Events.BUFFER_EMPTY);\n logger.debug(state === MetricsConstants.BUFFER_LOADED ? 'Got enough buffer to start' : 'Waiting for more buffer before starting playback');\n }\n\n /* prune buffer on our own in background to avoid browsers pruning buffer silently */\n function pruneBuffer() {\n if (!sourceBufferSink || type === Constants.TEXT) {\n return;\n }\n\n if (!isBufferingCompleted) {\n clearBuffers(getClearRanges());\n }\n }\n\n function getClearRanges() {\n const clearRanges = [];\n const ranges = sourceBufferSink.getAllBufferRanges();\n if (!ranges || ranges.length === 0) {\n return clearRanges;\n }\n\n const currentTime = playbackController.getTime();\n let startRangeToKeep = Math.max(0, currentTime - settings.get().streaming.buffer.bufferToKeep);\n\n const currentTimeRequest = fragmentModel.getRequests({\n state: FragmentModel.FRAGMENT_MODEL_EXECUTED,\n time: currentTime,\n threshold: BUFFER_RANGE_CALCULATION_THRESHOLD\n })[0];\n\n // Ensure we keep full range of current fragment\n if (currentTimeRequest) {\n startRangeToKeep = Math.min(currentTimeRequest.startTime, startRangeToKeep);\n } else if (currentTime === 0 && playbackController.getIsDynamic()) {\n // Don't prune before the live stream starts, it messes with low latency\n return [];\n }\n\n if (ranges.start(0) <= startRangeToKeep) {\n const behindRange = {\n start: 0,\n end: startRangeToKeep\n };\n for (let i = 0; i < ranges.length && ranges.end(i) <= startRangeToKeep; i++) {\n behindRange.end = ranges.end(i);\n }\n if (behindRange.start < behindRange.end) {\n clearRanges.push(behindRange);\n }\n }\n\n return clearRanges;\n }\n\n function clearBuffers(ranges) {\n return new Promise((resolve, reject) => {\n if (!ranges || !sourceBufferSink || ranges.length === 0) {\n resolve();\n return;\n }\n\n const promises = [];\n ranges.forEach((range) => {\n promises.push(_addClearRangeWithPromise(range));\n });\n\n\n if (!isPruningInProgress) {\n clearNextRange();\n }\n\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n function _addClearRangeWithPromise(range) {\n return new Promise((resolve, reject) => {\n range.resolve = resolve;\n range.reject = reject;\n pendingPruningRanges.push(range);\n });\n }\n\n function clearNextRange() {\n try {\n // If there's nothing to prune reset state\n if (pendingPruningRanges.length === 0 || !sourceBufferSink) {\n logger.debug('Nothing to prune, halt pruning');\n pendingPruningRanges = [];\n isPruningInProgress = false;\n return;\n }\n\n const sourceBuffer = sourceBufferSink.getBuffer();\n // If there's nothing buffered any pruning is invalid, so reset our state\n if (!sourceBuffer || !sourceBuffer.buffered || sourceBuffer.buffered.length === 0) {\n logger.debug('SourceBuffer is empty (or does not exist), halt pruning');\n pendingPruningRanges = [];\n isPruningInProgress = false;\n return;\n }\n\n const range = pendingPruningRanges.shift();\n logger.debug(`${type}: Removing buffer from: ${range.start} to ${range.end}`);\n isPruningInProgress = true;\n\n // If removing buffer ahead current playback position, update maxAppendedIndex\n const currentTime = playbackController.getTime();\n if (currentTime < range.end) {\n setIsBufferingCompleted(false);\n }\n\n sourceBufferSink.remove(range)\n .then((e) => {\n _onRemoved(e);\n })\n .catch((e) => {\n _onRemoved(e);\n });\n } catch (e) {\n isPruningInProgress = false;\n }\n }\n\n function _onRemoved(e) {\n logger.debug('onRemoved buffer from:', e.from, 'to', e.to);\n\n const ranges = sourceBufferSink.getAllBufferRanges();\n _showBufferRanges(ranges);\n\n if (pendingPruningRanges.length === 0) {\n isPruningInProgress = false;\n _updateBufferLevel();\n }\n\n if (e.unintended) {\n logger.warn('Detected unintended removal from:', e.from, 'to', e.to, 'setting streamprocessor time to', e.from);\n _triggerEvent(Events.SEEK_TARGET, { time: e.from });\n }\n\n if (isPruningInProgress) {\n clearNextRange();\n } else {\n if (!replacingBuffer) {\n _updateBufferLevel();\n } else {\n replacingBuffer = false;\n }\n _triggerEvent(Events.BUFFER_CLEARED, {\n from: e.from,\n to: e.to,\n unintended: e.unintended,\n hasEnoughSpaceToAppend: hasEnoughSpaceToAppend(),\n quotaExceeded: isQuotaExceeded\n });\n }\n }\n\n function updateBufferTimestampOffset(representationInfo) {\n return new Promise((resolve) => {\n if (!representationInfo || representationInfo.MSETimeOffset === undefined || !sourceBufferSink || !sourceBufferSink.updateTimestampOffset) {\n resolve();\n return;\n }\n // Each track can have its own @presentationTimeOffset, so we should set the offset\n // if it has changed after switching the quality or updating an mpd\n sourceBufferSink.updateTimestampOffset(representationInfo.MSETimeOffset)\n .then(() => {\n resolve();\n })\n .catch(() => {\n resolve();\n });\n });\n\n }\n\n function updateAppendWindow() {\n if (sourceBufferSink && !isBufferingCompleted) {\n return sourceBufferSink.updateAppendWindow(streamInfo);\n }\n return Promise.resolve();\n }\n\n function segmentRequestingCompleted(segmentIndex) {\n if (!isNaN(segmentIndex)) {\n maximumIndex = segmentIndex;\n _checkIfBufferingCompleted();\n }\n }\n\n function _onWallclockTimeUpdated() {\n wallclockTicked++;\n const secondsElapsed = (wallclockTicked * (settings.get().streaming.wallclockTimeUpdateInterval / 1000));\n if ((secondsElapsed >= settings.get().streaming.buffer.bufferPruningInterval)) {\n wallclockTicked = 0;\n pruneBuffer();\n }\n }\n\n function _onPlaybackRateChanged() {\n checkIfSufficientBuffer();\n }\n\n function getBuffer() {\n return sourceBufferSink;\n }\n\n function getBufferLevel() {\n return bufferLevel;\n }\n\n function getMediaSource() {\n return mediaSource;\n }\n\n function getIsBufferingCompleted() {\n return isBufferingCompleted;\n }\n\n function setIsBufferingCompleted(value) {\n if (isBufferingCompleted === value) {\n return;\n }\n\n isBufferingCompleted = value;\n\n if (isBufferingCompleted) {\n _triggerEvent(Events.BUFFERING_COMPLETED);\n } else {\n maximumIndex = Number.POSITIVE_INFINITY;\n }\n }\n\n function getIsPruningInProgress() {\n return isPruningInProgress;\n }\n\n function getTotalBufferedTime() {\n try {\n const ranges = sourceBufferSink.getAllBufferRanges();\n let totalBufferedTime = 0;\n let ln,\n i;\n\n if (!ranges) return totalBufferedTime;\n\n for (i = 0, ln = ranges.length; i < ln; i++) {\n totalBufferedTime += ranges.end(i) - ranges.start(i);\n }\n\n return totalBufferedTime;\n } catch (e) {\n return 0;\n }\n }\n\n /**\n * This function returns the maximum time for which the buffer is continuous starting from a target time.\n * As soon as there is a gap we return the time before the gap starts\n * @param {number} targetTime\n */\n function getContinuousBufferTimeForTargetTime(targetTime) {\n try {\n let adjustedTime = targetTime;\n const ranges = sourceBufferSink.getAllBufferRanges();\n\n if (!ranges || ranges.length === 0) {\n return NaN;\n }\n\n let i = 0;\n\n while (adjustedTime === targetTime && i < ranges.length) {\n const start = ranges.start(i);\n const end = ranges.end(i);\n\n if (adjustedTime >= start && adjustedTime <= end) {\n adjustedTime = end;\n }\n\n i += 1;\n }\n\n return adjustedTime === targetTime ? NaN : adjustedTime;\n\n } catch (e) {\n\n }\n }\n\n function hasEnoughSpaceToAppend() {\n const totalBufferedTime = getTotalBufferedTime();\n return (isNaN(totalBufferedTime) || totalBufferedTime < criticalBufferLevel);\n }\n\n function setSeekTarget(value) {\n seekTarget = value;\n }\n\n function _triggerEvent(eventType, data) {\n let payload = data || {};\n eventBus.trigger(eventType, payload, { streamId: streamInfo.id, mediaType: type });\n }\n\n function resetInitialSettings(errored, keepBuffers) {\n criticalBufferLevel = Number.POSITIVE_INFINITY;\n bufferState = undefined;\n maximumIndex = Number.POSITIVE_INFINITY;\n maxAppendedIndex = 0;\n appendedBytesInfo = null;\n isBufferingCompleted = false;\n isPruningInProgress = false;\n isQuotaExceeded = false;\n bufferLevel = 0;\n wallclockTicked = 0;\n pendingPruningRanges = [];\n seekTarget = NaN;\n\n if (sourceBufferSink) {\n let tmpSourceBufferSinkToReset = sourceBufferSink;\n sourceBufferSink = null;\n if (!errored && !keepBuffers) {\n tmpSourceBufferSinkToReset.abort()\n .then(() => {\n tmpSourceBufferSinkToReset.reset(keepBuffers);\n tmpSourceBufferSinkToReset = null;\n });\n }\n }\n\n replacingBuffer = false;\n }\n\n function reset(errored, keepBuffers) {\n eventBus.off(Events.INIT_FRAGMENT_LOADED, _onInitFragmentLoaded, this);\n eventBus.off(Events.MEDIA_FRAGMENT_LOADED, _onMediaFragmentLoaded, this);\n eventBus.off(Events.WALLCLOCK_TIME_UPDATED, _onWallclockTimeUpdated, this);\n\n eventBus.off(MediaPlayerEvents.PLAYBACK_PLAYING, _onPlaybackPlaying, this);\n eventBus.off(MediaPlayerEvents.PLAYBACK_PROGRESS, _onPlaybackProgression, this);\n eventBus.off(MediaPlayerEvents.PLAYBACK_TIME_UPDATED, _onPlaybackProgression, this);\n eventBus.off(MediaPlayerEvents.PLAYBACK_RATE_CHANGED, _onPlaybackRateChanged, this);\n eventBus.off(MediaPlayerEvents.PLAYBACK_STALLED, _onPlaybackStalled, this);\n\n\n resetInitialSettings(errored, keepBuffers);\n }\n\n instance = {\n initialize,\n getStreamId,\n getType,\n getBufferControllerType,\n createBufferSink,\n getBuffer,\n getBufferLevel,\n getRangeAt,\n setMediaSource,\n getMediaSource,\n appendInitSegmentFromCache,\n getIsBufferingCompleted,\n setIsBufferingCompleted,\n getIsPruningInProgress,\n reset,\n prepareForPlaybackSeek,\n prepareForReplacementTrackSwitch,\n prepareForNonReplacementTrackSwitch,\n prepareForReplacementQualitySwitch,\n updateAppendWindow,\n getAllRangesWithSafetyFactor,\n getContinuousBufferTimeForTargetTime,\n clearBuffers,\n pruneAllSafely,\n updateBufferTimestampOffset,\n setSeekTarget,\n segmentRequestingCompleted\n };\n\n setup();\n return instance;\n}\n\nBufferController.__dashjs_factory_name = BUFFER_CONTROLLER_TYPE;\nexport default FactoryMaker.getClassFactory(BufferController);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport InitCache from '../utils/InitCache';\nimport SourceBufferSink from '../SourceBufferSink';\nimport DashJSError from '../../streaming/vo/DashJSError';\nimport Errors from '../../core/errors/Errors';\n\nconst BUFFER_CONTROLLER_TYPE = 'NotFragmentedTextBufferController';\n\nfunction NotFragmentedTextBufferController(config) {\n\n config = config || {};\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n\n const textController = config.textController;\n const errHandler = config.errHandler;\n const streamInfo = config.streamInfo;\n const type = config.type;\n\n let instance,\n isBufferingCompleted,\n initialized,\n mediaSource,\n sourceBufferSink,\n initCache;\n\n function setup() {\n initialized = false;\n mediaSource = null;\n isBufferingCompleted = false;\n\n initCache = InitCache(context).getInstance();\n\n eventBus.on(Events.INIT_FRAGMENT_LOADED, _onInitFragmentLoaded, instance);\n }\n\n function getBufferControllerType() {\n return BUFFER_CONTROLLER_TYPE;\n }\n\n function initialize(source) {\n setMediaSource(source);\n }\n\n function createBufferSink(mediaInfo) {\n return new Promise((resolve, reject) => {\n try {\n sourceBufferSink = SourceBufferSink(context).create({ mediaSource, textController, eventBus });\n sourceBufferSink.initializeForFirstUse(streamInfo, mediaInfo);\n if (!initialized) {\n if (sourceBufferSink.getBuffer() && typeof sourceBufferSink.getBuffer().initialize === 'function') {\n sourceBufferSink.getBuffer().initialize();\n }\n initialized = true;\n }\n resolve(sourceBufferSink);\n } catch (e) {\n errHandler.error(new DashJSError(Errors.MEDIASOURCE_TYPE_UNSUPPORTED_CODE, Errors.MEDIASOURCE_TYPE_UNSUPPORTED_MESSAGE + type));\n reject(e);\n }\n });\n\n }\n\n function getStreamId() {\n return streamInfo.id;\n }\n\n function getType() {\n return type;\n }\n\n function getBuffer() {\n return sourceBufferSink;\n }\n\n function setMediaSource(value) {\n mediaSource = value;\n }\n\n function getMediaSource() {\n return mediaSource;\n }\n\n function getIsPruningInProgress() {\n return false;\n }\n\n function getBufferLevel() {\n return 0;\n }\n\n function getIsBufferingCompleted() {\n return isBufferingCompleted;\n }\n\n function setIsBufferingCompleted(value) {\n if (isBufferingCompleted === value) {\n return;\n }\n\n isBufferingCompleted = value;\n\n if (isBufferingCompleted) {\n triggerEvent(Events.BUFFERING_COMPLETED);\n }\n }\n\n function reset(errored) {\n eventBus.off(Events.INIT_FRAGMENT_LOADED, _onInitFragmentLoaded, instance);\n\n if (!errored && sourceBufferSink) {\n sourceBufferSink.abort();\n sourceBufferSink.reset();\n sourceBufferSink = null;\n }\n }\n\n function appendInitSegmentFromCache(representationId) {\n // If text data file already in cache then no need to append it again\n return initCache.extract(streamInfo.id, representationId) !== null;\n }\n\n function _onInitFragmentLoaded(e) {\n if (!e.chunk.bytes || isBufferingCompleted) return;\n\n initCache.save(e.chunk);\n\n sourceBufferSink.append(e.chunk);\n\n setIsBufferingCompleted(true);\n }\n\n function getRangeAt() {\n return null;\n }\n\n function getAllRangesWithSafetyFactor() {\n return [];\n }\n\n function getContinuousBufferTimeForTargetTime() {\n return Number.POSITIVE_INFINITY;\n }\n\n function clearBuffers() {\n return Promise.resolve();\n }\n\n function updateBufferTimestampOffset() {\n return Promise.resolve();\n }\n\n function prepareForPlaybackSeek() {\n return Promise.resolve();\n }\n\n function prepareForReplacementTrackSwitch() {\n isBufferingCompleted = false;\n return Promise.resolve();\n }\n\n function updateAppendWindow() {\n return Promise.resolve();\n }\n\n function setSeekTarget() {\n\n }\n\n function segmentRequestingCompleted() {\n\n }\n\n function pruneAllSafely() {\n return Promise.resolve();\n }\n\n function triggerEvent(eventType, data) {\n let payload = data || {};\n eventBus.trigger(eventType, payload, { streamId: streamInfo.id, mediaType: type });\n }\n\n instance = {\n initialize,\n getStreamId,\n getType,\n getBufferControllerType,\n createBufferSink,\n getBuffer,\n getBufferLevel,\n getRangeAt,\n getAllRangesWithSafetyFactor,\n getContinuousBufferTimeForTargetTime,\n setMediaSource,\n getMediaSource,\n appendInitSegmentFromCache,\n getIsBufferingCompleted,\n setIsBufferingCompleted,\n getIsPruningInProgress,\n reset,\n clearBuffers,\n prepareForPlaybackSeek,\n prepareForReplacementTrackSwitch,\n setSeekTarget,\n updateAppendWindow,\n pruneAllSafely,\n updateBufferTimestampOffset,\n segmentRequestingCompleted\n };\n\n setup();\n\n return instance;\n}\n\nNotFragmentedTextBufferController.__dashjs_factory_name = BUFFER_CONTROLLER_TYPE;\nexport default FactoryMaker.getClassFactory(NotFragmentedTextBufferController);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Constants from '../constants/Constants';\nimport FragmentModel from '../models/FragmentModel';\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Debug from '../../core/Debug';\nimport MetricsConstants from '../constants/MetricsConstants';\nimport MediaPlayerEvents from '../MediaPlayerEvents';\n\nfunction ScheduleController(config) {\n\n config = config || {};\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n const dashMetrics = config.dashMetrics;\n const mediaPlayerModel = config.mediaPlayerModel;\n const fragmentModel = config.fragmentModel;\n const abrController = config.abrController;\n const playbackController = config.playbackController;\n const textController = config.textController;\n const type = config.type;\n const bufferController = config.bufferController;\n const settings = config.settings;\n\n let instance,\n streamInfo,\n logger,\n currentRepresentationInfo,\n timeToLoadDelay,\n scheduleTimeout,\n hasVideoTrack,\n lastFragmentRequest,\n topQualityIndex,\n lastInitializedQuality,\n switchTrack,\n initSegmentRequired,\n checkPlaybackQuality;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n resetInitialSettings();\n streamInfo = config.streamInfo;\n }\n\n function initialize(_hasVideoTrack) {\n hasVideoTrack = _hasVideoTrack;\n\n eventBus.on(Events.BYTES_APPENDED_END_FRAGMENT, _onBytesAppended, instance);\n eventBus.on(Events.URL_RESOLUTION_FAILED, _onURLResolutionFailed, instance);\n eventBus.on(MediaPlayerEvents.PLAYBACK_STARTED, _onPlaybackStarted, instance);\n eventBus.on(MediaPlayerEvents.PLAYBACK_RATE_CHANGED, _onPlaybackRateChanged, instance);\n eventBus.on(MediaPlayerEvents.PLAYBACK_TIME_UPDATED, _onPlaybackTimeUpdated, instance);\n }\n\n function getType() {\n return type;\n }\n\n function getStreamId() {\n return streamInfo.id;\n }\n\n function setCurrentRepresentation(representationInfo) {\n currentRepresentationInfo = representationInfo;\n }\n\n function startScheduleTimer(value) {\n if (bufferController.getIsBufferingCompleted()) return;\n\n clearScheduleTimer();\n const timeoutValue = !isNaN(value) ? value : 0;\n scheduleTimeout = setTimeout(schedule, timeoutValue);\n }\n\n function clearScheduleTimer() {\n if (scheduleTimeout) {\n clearTimeout(scheduleTimeout);\n scheduleTimeout = null;\n }\n }\n\n function hasTopQualityChanged() {\n const streamId = streamInfo.id;\n const newTopQualityIndex = abrController.getMaxAllowedIndexFor(type, streamId);\n\n if (isNaN(topQualityIndex) || topQualityIndex != newTopQualityIndex) {\n logger.info('Top quality ' + type + ' index has changed from ' + topQualityIndex + ' to ' + newTopQualityIndex);\n topQualityIndex = newTopQualityIndex;\n return true;\n }\n return false;\n\n }\n\n /**\n * Schedule the request for an init or a media segment\n */\n function schedule() {\n try {\n // Check if we are supposed to stop scheduling\n if (_shouldClearScheduleTimer()) {\n clearScheduleTimer();\n return;\n }\n\n if (_shouldScheduleNextRequest()) {\n let qualityChange = false;\n if (checkPlaybackQuality) {\n // in case the playback quality is supposed to be changed, the corresponding StreamProcessor will update the currentRepresentation.\n // The StreamProcessor will also start the schedule timer again once the quality switch has beeen prepared. Consequently, we only call _getNextFragment if the quality is not changed.\n qualityChange = abrController.checkPlaybackQuality(type, streamInfo.id);\n }\n if (!qualityChange) {\n _getNextFragment();\n }\n\n } else {\n startScheduleTimer(settings.get().streaming.lowLatencyEnabled ? settings.get().streaming.scheduling.lowLatencyTimeout : settings.get().streaming.scheduling.defaultTimeout);\n }\n } catch (e) {\n startScheduleTimer(settings.get().streaming.lowLatencyEnabled ? settings.get().streaming.scheduling.lowLatencyTimeout : settings.get().streaming.scheduling.defaultTimeout);\n }\n }\n\n /**\n * Triggers the events to start requesting an init or a media segment. This will be picked up by the corresponding StreamProcessor.\n * @private\n */\n function _getNextFragment() {\n // A quality changed occured or we are switching the AdaptationSet. In that case we need to load a new init segment\n if (initSegmentRequired || currentRepresentationInfo.quality !== lastInitializedQuality || switchTrack) {\n if (switchTrack) {\n logger.debug('Switch track for ' + type + ', representation id = ' + currentRepresentationInfo.id);\n switchTrack = false;\n } else {\n logger.debug('Quality has changed, get init request for representationid = ' + currentRepresentationInfo.id);\n }\n eventBus.trigger(Events.INIT_FRAGMENT_NEEDED,\n { representationId: currentRepresentationInfo.id, sender: instance },\n { streamId: streamInfo.id, mediaType: type }\n );\n checkPlaybackQuality = false;\n initSegmentRequired = false;\n }\n\n // Request a media segment instead\n else {\n logger.debug(`Media segment needed for ${type} and stream id ${streamInfo.id}`);\n eventBus.trigger(Events.MEDIA_FRAGMENT_NEEDED,\n {},\n { streamId: streamInfo.id, mediaType: type }\n );\n checkPlaybackQuality = true;\n }\n\n }\n\n /**\n * Check if we need to stop scheduling for now.\n * @return {boolean}\n * @private\n */\n function _shouldClearScheduleTimer() {\n try {\n return (((type === Constants.TEXT) && !textController.isTextEnabled()) ||\n (playbackController.isPaused() && (!playbackController.getStreamController().getInitialPlayback() || !playbackController.getStreamController().getAutoPlay()) && !settings.get().streaming.scheduling.scheduleWhilePaused));\n } catch (e) {\n return false;\n }\n }\n\n /**\n * Check if we can start scheduling the next request\n * @return {boolean}\n * @private\n */\n function _shouldScheduleNextRequest() {\n try {\n return currentRepresentationInfo && (isNaN(lastInitializedQuality) || switchTrack || hasTopQualityChanged() || _shouldBuffer());\n } catch (e) {\n return false;\n }\n }\n\n /**\n * Check if the current buffer level is below our buffer target.\n * @return {boolean}\n * @private\n */\n function _shouldBuffer() {\n if (!type || !currentRepresentationInfo) {\n return true;\n }\n const bufferLevel = dashMetrics.getCurrentBufferLevel(type);\n return bufferLevel < getBufferTarget();\n }\n\n /**\n * Determine the buffer target depending on the type and whether we have audio and video AdaptationSets available\n * @return {number}\n */\n function getBufferTarget() {\n let bufferTarget = NaN;\n\n if (!type || !currentRepresentationInfo) {\n return bufferTarget;\n }\n\n if (type === Constants.TEXT) {\n bufferTarget = _getBufferTargetForFragmentedText();\n } else if (type === Constants.AUDIO && hasVideoTrack) {\n bufferTarget = _getBufferTargetForAudio();\n } else {\n bufferTarget = _getGenericBufferTarget();\n }\n\n return bufferTarget;\n }\n\n /**\n * Returns the buffer target for fragmented text tracks\n * @return {number}\n * @private\n */\n function _getBufferTargetForFragmentedText() {\n try {\n if (textController.isTextEnabled()) {\n if (isNaN(currentRepresentationInfo.fragmentDuration)) { //fragmentDuration of currentRepresentationInfo is not defined,\n // call metrics function to have data in the latest scheduling info...\n // if no metric, returns 0. In this case, rule will return false.\n const schedulingInfo = dashMetrics.getCurrentSchedulingInfo(MetricsConstants.SCHEDULING_INFO);\n return schedulingInfo ? schedulingInfo.duration : 0;\n } else {\n return currentRepresentationInfo.fragmentDuration;\n }\n } else { // text is disabled, rule will return false\n return 0;\n }\n } catch (e) {\n return 0;\n }\n }\n\n /**\n * Returns the buffer target for audio tracks in case we have a video track available as well\n * @return {number}\n * @private\n */\n function _getBufferTargetForAudio() {\n try {\n const videoBufferLevel = dashMetrics.getCurrentBufferLevel(Constants.VIDEO);\n // For multiperiod we need to consider that audio and video segments might have different durations.\n // This can lead to scenarios in which we completely buffered the video segments and the video buffer level for the current period is not changing anymore. However we might still need a small audio segment to finish buffering audio as well.\n // If we set the buffer time of audio equal to the video buffer time scheduling for the remaining audio segment will only be triggered when audio fragmentDuration > videoBufferLevel. That will delay preloading of the upcoming period.\n // Should find a better solution than just adding 1\n if (isNaN(currentRepresentationInfo.fragmentDuration)) {\n return videoBufferLevel + 1;\n } else {\n return Math.max(videoBufferLevel + 1, currentRepresentationInfo.fragmentDuration);\n }\n } catch (e) {\n return 0;\n }\n }\n\n /**\n * Determines the generic buffer target, for instance for video tracks\n * @return {number}\n * @private\n */\n function _getGenericBufferTarget() {\n try {\n const streamInfo = currentRepresentationInfo.mediaInfo.streamInfo;\n if (abrController.isPlayingAtTopQuality(streamInfo)) {\n const isLongFormContent = streamInfo.manifestInfo.duration >= settings.get().streaming.buffer.longFormContentDurationThreshold;\n return isLongFormContent ? settings.get().streaming.buffer.bufferTimeAtTopQualityLongForm : settings.get().streaming.buffer.bufferTimeAtTopQuality;\n } else {\n return mediaPlayerModel.getStableBufferTime();\n }\n } catch (e) {\n return mediaPlayerModel.getStableBufferTime();\n }\n }\n\n function setSwitchTrack(value) {\n switchTrack = value;\n }\n\n function getSwitchStrack() {\n return switchTrack;\n }\n\n function _onPlaybackTimeUpdated() {\n _completeQualityChange(true);\n }\n\n function _completeQualityChange(trigger) {\n if (playbackController && fragmentModel) {\n const item = fragmentModel.getRequests({\n state: FragmentModel.FRAGMENT_MODEL_EXECUTED,\n time: playbackController.getTime(),\n threshold: 0\n })[0];\n\n if (item && playbackController.getTime() >= item.startTime) {\n if ((!lastFragmentRequest.mediaInfo || (item.mediaInfo.type === lastFragmentRequest.mediaInfo.type && item.mediaInfo.id !== lastFragmentRequest.mediaInfo.id)) && trigger) {\n eventBus.trigger(Events.TRACK_CHANGE_RENDERED, {\n mediaType: type,\n oldMediaInfo: lastFragmentRequest.mediaInfo,\n newMediaInfo: item.mediaInfo,\n streamId: streamInfo.id\n });\n }\n if ((item.quality !== lastFragmentRequest.quality || item.adaptationIndex !== lastFragmentRequest.adaptationIndex) && trigger) {\n logger.debug(`Quality change rendered for streamId ${streamInfo.id} and type ${type}`);\n eventBus.trigger(Events.QUALITY_CHANGE_RENDERED, {\n mediaType: type,\n oldQuality: lastFragmentRequest.quality,\n newQuality: item.quality,\n streamId: streamInfo.id\n });\n }\n lastFragmentRequest = {\n mediaInfo: item.mediaInfo,\n quality: item.quality,\n adaptationIndex: item.adaptationIndex\n };\n }\n }\n }\n\n function _onBytesAppended(e) {\n logger.debug(`Appended bytes for ${e.mediaType} and stream id ${streamInfo.id}`);\n\n // we save the last initialized quality. That way we make sure that the media fragments we are about to append match the init segment\n if (isNaN(e.index) || isNaN(lastInitializedQuality)) {\n lastInitializedQuality = e.quality;\n logger.info('[' + type + '] ' + 'lastInitializedRepresentationInfo changed to ' + e.quality);\n }\n\n startScheduleTimer(0);\n }\n\n function _onURLResolutionFailed() {\n fragmentModel.abortRequests();\n clearScheduleTimer();\n }\n\n function _onPlaybackStarted() {\n if (!settings.get().streaming.scheduling.scheduleWhilePaused) {\n startScheduleTimer();\n }\n }\n\n function _onPlaybackRateChanged(e) {\n dashMetrics.updatePlayListTraceMetrics({ playbackspeed: e.playbackRate.toString() });\n }\n\n function setTimeToLoadDelay(value) {\n timeToLoadDelay = value;\n }\n\n function getTimeToLoadDelay() {\n return timeToLoadDelay;\n }\n\n function setCheckPlaybackQuality(value) {\n checkPlaybackQuality = value;\n }\n\n function setInitSegmentRequired(value) {\n initSegmentRequired = value;\n }\n\n function resetInitialSettings() {\n checkPlaybackQuality = true;\n timeToLoadDelay = 0;\n lastInitializedQuality = NaN;\n lastFragmentRequest = {\n mediaInfo: undefined,\n quality: NaN,\n adaptationIndex: NaN\n };\n topQualityIndex = NaN;\n switchTrack = false;\n initSegmentRequired = false;\n }\n\n function reset() {\n eventBus.off(Events.BYTES_APPENDED_END_FRAGMENT, _onBytesAppended, instance);\n eventBus.off(Events.URL_RESOLUTION_FAILED, _onURLResolutionFailed, instance);\n eventBus.off(MediaPlayerEvents.PLAYBACK_STARTED, _onPlaybackStarted, instance);\n eventBus.off(MediaPlayerEvents.PLAYBACK_RATE_CHANGED, _onPlaybackRateChanged, instance);\n eventBus.off(MediaPlayerEvents.PLAYBACK_TIME_UPDATED, _onPlaybackTimeUpdated, instance);\n\n clearScheduleTimer();\n _completeQualityChange(false);\n resetInitialSettings();\n streamInfo = null;\n }\n\n function getPlaybackController() {\n return playbackController;\n }\n\n instance = {\n initialize,\n getType,\n getStreamId,\n setCurrentRepresentation,\n setTimeToLoadDelay,\n getTimeToLoadDelay,\n setSwitchTrack,\n getSwitchStrack,\n startScheduleTimer,\n clearScheduleTimer,\n reset,\n getBufferTarget,\n getPlaybackController,\n setCheckPlaybackQuality,\n setInitSegmentRequired\n };\n\n setup();\n\n return instance;\n}\n\nScheduleController.__dashjs_factory_name = 'ScheduleController';\nexport default FactoryMaker.getClassFactory(ScheduleController);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @classdesc a PlayList from ISO23009-1 Annex D, this Object holds reference to the playback session information\n * @ignore\n */\nclass PlayList {\n /**\n * @class\n */\n constructor() {\n\n /**\n * Timestamp of the user action that starts the playback stream...\n * @public\n */\n this.start = null;\n /**\n * Presentation time at which playout was requested by the user...\n * @public\n */\n this.mstart = null;\n /**\n * Type of user action which triggered playout\n * - New playout request (e.g. initial playout or seeking)\n * - Resume from pause\n * - Other user request (e.g. user-requested quality change)\n * - Start of a metrics collection stream (hence earlier entries in the play list not collected)\n * @public\n */\n this.starttype = null;\n\n /**\n * List of streams of continuous rendering of decoded samples.\n * @public\n */\n this.trace = [];\n }\n}\n\n/* Public Static Constants */\nPlayList.INITIAL_PLAYOUT_START_REASON = 'initial_playout';\nPlayList.SEEK_START_REASON = 'seek';\nPlayList.RESUME_FROM_PAUSE_START_REASON = 'resume';\nPlayList.METRICS_COLLECTION_START_REASON = 'metrics_collection_start';\n\n/**\n * @classdesc a PlayList.Trace from ISO23009-1 Annex D\n * @ignore\n */\nclass PlayListTrace {\n /**\n * @class\n */\n constructor() {\n /**\n * The value of the Representation@id of the Representation from which the samples were taken.\n * @type {string}\n * @public\n */\n this.representationid = null;\n /**\n * If not present, this metrics concerns the Representation as a whole.\n * If present, subreplevel indicates the greatest value of any\n * Subrepresentation@level being rendered.\n * @type {number}\n * @public\n */\n this.subreplevel = null;\n /**\n * The time at which the first sample was rendered\n * @type {number}\n * @public\n */\n this.start = null;\n /**\n * The presentation time of the first sample rendered.\n * @type {number}\n * @public\n */\n this.mstart = null;\n /**\n * The duration of the continuously presented samples (which is the same in real time and media time). \"Continuously presented\" means that the media clock continued to advance at the playout speed throughout the interval. NOTE: the spec does not call out the units, but all other durations etc are in ms, and we use ms too.\n * @type {number}\n * @public\n */\n this.duration = null;\n /**\n * The playback speed relative to normal playback speed (i.e.normal forward playback speed is 1.0).\n * @type {number}\n * @public\n */\n this.playbackspeed = null;\n /**\n * The reason why continuous presentation of this Representation was stopped.\n * representation switch\n * rebuffering\n * user request\n * end of Period\n * end of Stream\n * end of content\n * end of a metrics collection period\n *\n * @type {string}\n * @public\n */\n this.stopreason = null;\n }\n}\n\nPlayListTrace.REPRESENTATION_SWITCH_STOP_REASON = 'representation_switch';\nPlayListTrace.REBUFFERING_REASON = 'rebuffering';\nPlayListTrace.USER_REQUEST_STOP_REASON = 'user_request';\nPlayListTrace.END_OF_PERIOD_STOP_REASON = 'end_of_period';\nPlayListTrace.END_OF_CONTENT_STOP_REASON = 'end_of_content';\nPlayListTrace.METRICS_COLLECTION_STOP_REASON = 'metrics_collection_end';\nPlayListTrace.FAILURE_STOP_REASON = 'failure';\n\nexport { PlayList, PlayListTrace };\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Constants from './constants/Constants';\nimport DashConstants from '../dash/constants/DashConstants';\nimport MetricsConstants from './constants/MetricsConstants';\nimport FragmentModel from './models/FragmentModel';\nimport BufferController from './controllers/BufferController';\nimport NotFragmentedTextBufferController from './text/NotFragmentedTextBufferController';\nimport ScheduleController from './controllers/ScheduleController';\nimport RepresentationController from '../dash/controllers/RepresentationController';\nimport FactoryMaker from '../core/FactoryMaker';\nimport {checkInteger} from './utils/SupervisorTools';\nimport EventBus from '../core/EventBus';\nimport Events from '../core/events/Events';\nimport DashHandler from '../dash/DashHandler';\nimport Errors from '../core/errors/Errors';\nimport DashJSError from './vo/DashJSError';\nimport Debug from '../core/Debug';\nimport RequestModifier from './utils/RequestModifier';\nimport URLUtils from '../streaming/utils/URLUtils';\nimport BoxParser from './utils/BoxParser';\nimport {PlayListTrace} from './vo/metrics/PlayList';\nimport SegmentsController from '../dash/controllers/SegmentsController';\nimport {HTTPRequest} from './vo/metrics/HTTPRequest';\n\nfunction StreamProcessor(config) {\n\n config = config || {};\n let context = this.context;\n let eventBus = EventBus(context).getInstance();\n\n let streamInfo = config.streamInfo;\n let type = config.type;\n let errHandler = config.errHandler;\n let mimeType = config.mimeType;\n let timelineConverter = config.timelineConverter;\n let adapter = config.adapter;\n let manifestModel = config.manifestModel;\n let mediaPlayerModel = config.mediaPlayerModel;\n let fragmentModel = config.fragmentModel;\n let abrController = config.abrController;\n let playbackController = config.playbackController;\n let mediaController = config.mediaController;\n let textController = config.textController;\n let dashMetrics = config.dashMetrics;\n let settings = config.settings;\n let boxParser = config.boxParser;\n let segmentBlacklistController = config.segmentBlacklistController;\n\n let instance,\n logger,\n isDynamic,\n mediaInfo,\n mediaInfoArr,\n bufferController,\n scheduleController,\n representationController,\n shouldUseExplicitTimeForRequest,\n qualityChangeInProgress,\n dashHandler,\n segmentsController,\n bufferingTime;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n resetInitialSettings();\n\n eventBus.on(Events.DATA_UPDATE_COMPLETED, _onDataUpdateCompleted, instance, { priority: EventBus.EVENT_PRIORITY_HIGH }); // High priority to be notified before Stream\n eventBus.on(Events.INIT_FRAGMENT_NEEDED, _onInitFragmentNeeded, instance);\n eventBus.on(Events.MEDIA_FRAGMENT_NEEDED, _onMediaFragmentNeeded, instance);\n eventBus.on(Events.MEDIA_FRAGMENT_LOADED, _onMediaFragmentLoaded, instance);\n eventBus.on(Events.BUFFER_LEVEL_STATE_CHANGED, _onBufferLevelStateChanged, instance);\n eventBus.on(Events.BUFFER_CLEARED, _onBufferCleared, instance);\n eventBus.on(Events.SEEK_TARGET, _onSeekTarget, instance);\n eventBus.on(Events.FRAGMENT_LOADING_ABANDONED, _onFragmentLoadingAbandoned, instance);\n eventBus.on(Events.FRAGMENT_LOADING_COMPLETED, _onFragmentLoadingCompleted, instance);\n eventBus.on(Events.QUOTA_EXCEEDED, _onQuotaExceeded, instance);\n eventBus.on(Events.SET_FRAGMENTED_TEXT_AFTER_DISABLED, _onSetFragmentedTextAfterDisabled, instance);\n eventBus.on(Events.SET_NON_FRAGMENTED_TEXT, _onSetNonFragmentedText, instance);\n eventBus.on(Events.SOURCE_BUFFER_ERROR, _onSourceBufferError, instance);\n }\n\n function initialize(mediaSource, hasVideoTrack, isFragmented) {\n\n segmentsController = SegmentsController(context).create({\n events: Events,\n eventBus,\n streamInfo,\n timelineConverter,\n dashConstants: DashConstants,\n segmentBaseController: config.segmentBaseController,\n type\n });\n\n dashHandler = DashHandler(context).create({\n streamInfo,\n type,\n timelineConverter,\n dashMetrics,\n mediaPlayerModel,\n baseURLController: config.baseURLController,\n errHandler,\n segmentsController,\n settings,\n boxParser,\n events: Events,\n eventBus,\n errors: Errors,\n debug: Debug(context).getInstance(),\n requestModifier: RequestModifier(context).getInstance(),\n dashConstants: DashConstants,\n constants: Constants,\n urlUtils: URLUtils(context).getInstance()\n });\n\n isDynamic = streamInfo.manifestInfo.isDynamic;\n\n // Create/initialize controllers\n dashHandler.initialize(isDynamic);\n abrController.registerStreamType(type, instance);\n\n representationController = RepresentationController(context).create({\n streamInfo,\n type,\n abrController,\n dashMetrics,\n playbackController,\n timelineConverter,\n dashConstants: DashConstants,\n events: Events,\n eventBus,\n errors: Errors,\n isDynamic,\n segmentsController\n });\n\n bufferController = _createBufferControllerForType(type, isFragmented);\n if (bufferController) {\n bufferController.initialize(mediaSource);\n }\n\n scheduleController = ScheduleController(context).create({\n streamInfo,\n type,\n mimeType,\n adapter,\n dashMetrics,\n mediaPlayerModel,\n fragmentModel,\n abrController,\n playbackController,\n textController,\n mediaController,\n bufferController,\n settings\n });\n\n scheduleController.initialize(hasVideoTrack);\n\n bufferingTime = 0;\n shouldUseExplicitTimeForRequest = false;\n }\n\n function getStreamId() {\n return streamInfo.id;\n }\n\n function getType() {\n return type;\n }\n\n function getIsTextTrack() {\n return adapter.getIsTextTrack(representationController.getData());\n }\n\n function resetInitialSettings() {\n mediaInfoArr = [];\n mediaInfo = null;\n bufferingTime = 0;\n shouldUseExplicitTimeForRequest = false;\n qualityChangeInProgress = false;\n }\n\n function reset(errored, keepBuffers) {\n if (dashHandler) {\n dashHandler.reset();\n }\n\n if (bufferController) {\n bufferController.reset(errored, keepBuffers);\n bufferController = null;\n }\n\n if (scheduleController) {\n scheduleController.reset();\n scheduleController = null;\n }\n\n if (representationController) {\n representationController.reset();\n representationController = null;\n }\n\n if (segmentsController) {\n segmentsController = null;\n }\n\n if (abrController) {\n abrController.unRegisterStreamType(getStreamId(), type);\n }\n\n eventBus.off(Events.DATA_UPDATE_COMPLETED, _onDataUpdateCompleted, instance);\n eventBus.off(Events.INIT_FRAGMENT_NEEDED, _onInitFragmentNeeded, instance);\n eventBus.off(Events.MEDIA_FRAGMENT_NEEDED, _onMediaFragmentNeeded, instance);\n eventBus.off(Events.MEDIA_FRAGMENT_LOADED, _onMediaFragmentLoaded, instance);\n eventBus.off(Events.BUFFER_LEVEL_STATE_CHANGED, _onBufferLevelStateChanged, instance);\n eventBus.off(Events.BUFFER_CLEARED, _onBufferCleared, instance);\n eventBus.off(Events.SEEK_TARGET, _onSeekTarget, instance);\n eventBus.off(Events.FRAGMENT_LOADING_ABANDONED, _onFragmentLoadingAbandoned, instance);\n eventBus.off(Events.FRAGMENT_LOADING_COMPLETED, _onFragmentLoadingCompleted, instance);\n eventBus.off(Events.SET_FRAGMENTED_TEXT_AFTER_DISABLED, _onSetFragmentedTextAfterDisabled, instance);\n eventBus.off(Events.SET_NON_FRAGMENTED_TEXT, _onSetNonFragmentedText, instance);\n eventBus.off(Events.QUOTA_EXCEEDED, _onQuotaExceeded, instance);\n eventBus.off(Events.SOURCE_BUFFER_ERROR, _onSourceBufferError, instance);\n\n resetInitialSettings();\n type = null;\n streamInfo = null;\n }\n\n function isUpdating() {\n return representationController ? representationController.isUpdating() : false;\n }\n\n /**\n * When a seek within the corresponding period occurs this function initiates the clearing of the buffer and sets the correct buffering time.\n * @param {object} e\n * @private\n */\n function prepareInnerPeriodPlaybackSeeking(e) {\n return new Promise((resolve) => {\n // Stop segment requests until we have figured out for which time we need to request a segment. We don't want to replace existing segments.\n scheduleController.clearScheduleTimer();\n fragmentModel.abortRequests();\n\n // Abort operations to the SourceBuffer Sink and reset the BufferControllers isBufferingCompleted state.\n bufferController.prepareForPlaybackSeek()\n .then(() => {\n // Clear the buffer. We need to prune everything which is not in the target interval.\n const clearRanges = bufferController.getAllRangesWithSafetyFactor(e.seekTime);\n // When everything has been pruned go on\n return bufferController.clearBuffers(clearRanges);\n })\n .then(() => {\n // Figure out the correct segment request time.\n const continuousBufferTime = bufferController.getContinuousBufferTimeForTargetTime(e.seekTime);\n\n // If the buffer is continuous and exceeds the duration of the period we are still done buffering. We need to trigger the buffering completed event in order to start prebuffering upcoming periods again\n if (!isNaN(continuousBufferTime) && !isNaN(streamInfo.duration) && isFinite(streamInfo.duration) && continuousBufferTime >= streamInfo.start + streamInfo.duration) {\n bufferController.setIsBufferingCompleted(true);\n resolve();\n } else {\n const targetTime = isNaN(continuousBufferTime) ? e.seekTime : continuousBufferTime;\n setExplicitBufferingTime(targetTime);\n bufferController.setSeekTarget(targetTime);\n\n const promises = [];\n\n // append window has been reset by abort() operation. Set the correct values again\n promises.push(bufferController.updateAppendWindow());\n\n // Timestamp offset couldve been changed by preloading period\n const representationInfo = getRepresentationInfo();\n promises.push(bufferController.updateBufferTimestampOffset(representationInfo));\n\n Promise.all(promises)\n .then(() => {\n // We might have aborted the append operation of an init segment. Append init segment again.\n scheduleController.setInitSegmentRequired(true);\n\n // Right after a seek we should not immediately check the playback quality\n scheduleController.setCheckPlaybackQuality(false);\n scheduleController.startScheduleTimer();\n resolve();\n });\n }\n })\n .catch((e) => {\n logger.error(e);\n });\n });\n\n }\n\n /**\n * Seek outside of the current period.\n * @return {Promise<unknown>}\n */\n function prepareOuterPeriodPlaybackSeeking() {\n return new Promise((resolve, reject) => {\n try {\n // Stop scheduling\n scheduleController.clearScheduleTimer();\n\n // Abort all ongoing requests\n fragmentModel.abortRequests();\n\n // buffering not complete anymore and abort current append operation to SourceBuffer\n bufferController.prepareForPlaybackSeek()\n .then(() => {\n // Clear the buffers completely.\n return bufferController.pruneAllSafely();\n })\n .then(() => {\n resolve();\n });\n\n } catch (e) {\n reject(e);\n }\n });\n }\n\n /**\n * ScheduleController indicates that an init segment needs to be fetched.\n * @param {object} e\n * @param {boolean} rescheduleIfNoRequest - Defines whether we reschedule in case no valid request could be generated\n * @private\n */\n function _onInitFragmentNeeded(e, rescheduleIfNoRequest = true) {\n // Event propagation may have been stopped (see MssHandler)\n if (!e.sender) return;\n\n if (playbackController.getIsManifestUpdateInProgress()) {\n _noValidRequest();\n return;\n }\n\n if (getIsTextTrack() && !textController.isTextEnabled()) return;\n\n if (bufferController && e.representationId) {\n if (!bufferController.appendInitSegmentFromCache(e.representationId)) {\n const rep = representationController.getCurrentRepresentation();\n // Dummy init segment (fragmented tracks without initialization segment)\n if (rep.range === 0) {\n _onMediaFragmentNeeded();\n return;\n }\n // Init segment not in cache, send new request\n const request = dashHandler ? dashHandler.getInitRequest(mediaInfo, rep) : null;\n if (request) {\n fragmentModel.executeRequest(request);\n } else if (rescheduleIfNoRequest) {\n scheduleController.setInitSegmentRequired(true);\n _noValidRequest();\n }\n }\n }\n }\n\n /**\n * ScheduleController indicates that a media segment is needed\n * @param {boolean} rescheduleIfNoRequest - Defines whether we reschedule in case no valid request could be generated\n * @private\n */\n function _onMediaFragmentNeeded(e, rescheduleIfNoRequest = true) {\n // Don't schedule next fragments while updating manifest or pruning to avoid buffer inconsistencies\n if (playbackController.getIsManifestUpdateInProgress() || bufferController.getIsPruningInProgress()) {\n _noValidRequest();\n return;\n }\n\n let request = _getFragmentRequest();\n if (request) {\n shouldUseExplicitTimeForRequest = false;\n _mediaRequestGenerated(request);\n } else {\n _noMediaRequestGenerated(rescheduleIfNoRequest);\n }\n }\n\n /**\n * If we generated a valid media request we can execute the request. In some cases the segment might be blacklisted.\n * @param {object} request\n * @private\n */\n function _mediaRequestGenerated(request) {\n if (!isNaN(request.startTime + request.duration)) {\n bufferingTime = request.startTime + request.duration;\n }\n request.delayLoadingTime = new Date().getTime() + scheduleController.getTimeToLoadDelay();\n scheduleController.setTimeToLoadDelay(0);\n if (!_shouldIgnoreRequest(request)) {\n logger.debug(`Next fragment request url for stream id ${streamInfo.id} and media type ${type} is ${request.url}`);\n fragmentModel.executeRequest(request);\n } else {\n logger.warn(`Fragment request url ${request.url} for stream id ${streamInfo.id} and media type ${type} is on the ignore list and will be skipped`);\n _noValidRequest();\n }\n }\n\n /**\n * We could not generate a valid request. Check if the media is finished, we are stuck in a gap or simply need to wait for the next segment to be available.\n * @param {boolean} rescheduleIfNoRequest\n * @private\n */\n function _noMediaRequestGenerated(rescheduleIfNoRequest) {\n const representation = representationController.getCurrentRepresentation();\n\n // If this statement is true we are stuck. A static manifest does not change and we did not find a valid request for the target time\n // There is no point in trying again. We need to adjust the time in order to find a valid request. This can happen if the user/app seeked into a gap.\n if (settings.get().streaming.gaps.enableSeekFix && !isDynamic && shouldUseExplicitTimeForRequest && (playbackController.isSeeking() || playbackController.getTime() === 0)) {\n const adjustedTime = dashHandler.getValidSeekTimeCloseToTargetTime(bufferingTime, mediaInfo, representation, settings.get().streaming.gaps.threshold);\n if (!isNaN(adjustedTime)) {\n playbackController.seek(adjustedTime, false, false);\n return;\n }\n }\n\n // Check if the media is finished. If so, no need to schedule another request\n const isLastSegmentRequested = dashHandler.isLastSegmentRequested(representation, bufferingTime);\n if (isLastSegmentRequested) {\n const segmentIndex = dashHandler.getCurrentIndex();\n logger.debug(`Segment requesting for stream ${streamInfo.id} has finished`);\n eventBus.trigger(Events.STREAM_REQUESTING_COMPLETED, { segmentIndex }, {\n streamId: streamInfo.id,\n mediaType: type\n });\n bufferController.segmentRequestingCompleted(segmentIndex);\n scheduleController.clearScheduleTimer();\n return;\n }\n\n if (rescheduleIfNoRequest) {\n _noValidRequest();\n }\n }\n\n /**\n * In certain situations we need to ignore a request. For instance, if a segment is blacklisted because it caused an MSE error.\n * @private\n */\n function _shouldIgnoreRequest(request) {\n let blacklistUrl = request.url;\n\n if (request.range) {\n blacklistUrl = blacklistUrl.concat('_', request.range);\n }\n\n return segmentBlacklistController.contains(blacklistUrl)\n }\n\n /**\n * Get the init or media segment request using the DashHandler.\n * @return {null|FragmentRequest|null}\n * @private\n */\n function _getFragmentRequest() {\n const representationInfo = getRepresentationInfo();\n let request;\n\n if (isNaN(bufferingTime) || (getType() === Constants.TEXT && !textController.isTextEnabled())) {\n return null;\n }\n\n // Use time just whenever is strictly needed\n const useTime = shouldUseExplicitTimeForRequest;\n\n if (dashHandler) {\n const representation = representationController && representationInfo ? representationController.getRepresentationForQuality(representationInfo.quality) : null;\n\n if (useTime) {\n request = dashHandler.getSegmentRequestForTime(mediaInfo, representation, bufferingTime);\n } else {\n request = dashHandler.getNextSegmentRequest(mediaInfo, representation);\n }\n }\n\n return request;\n }\n\n /**\n * Whenever we can not generate a valid request we restart scheduling according to the timeouts defined in the settings.\n * @private\n */\n function _noValidRequest() {\n scheduleController.startScheduleTimer(settings.get().streaming.lowLatencyEnabled ? settings.get().streaming.scheduling.lowLatencyTimeout : settings.get().streaming.scheduling.defaultTimeout);\n }\n\n function _onDataUpdateCompleted(e) {\n if (!e.error) {\n // Update representation if no error\n scheduleController.setCurrentRepresentation(adapter.convertRepresentationToRepresentationInfo(e.currentRepresentation));\n if (!bufferController.getIsBufferingCompleted()) {\n bufferController.updateBufferTimestampOffset(e.currentRepresentation);\n }\n }\n }\n\n function _onBufferLevelStateChanged(e) {\n dashMetrics.addBufferState(type, e.state, scheduleController.getBufferTarget());\n if (e.state === MetricsConstants.BUFFER_EMPTY && !playbackController.isSeeking()) {\n logger.info('Buffer is empty! Stalling!');\n dashMetrics.pushPlayListTraceMetrics(new Date(), PlayListTrace.REBUFFERING_REASON);\n }\n }\n\n function _onBufferCleared(e) {\n // Remove executed requests not buffered anymore\n fragmentModel.syncExecutedRequestsWithBufferedRange(\n bufferController.getBuffer().getAllBufferRanges(),\n streamInfo.duration);\n\n // If buffer removed ahead current time (QuotaExceededError or automatic buffer pruning) then adjust current index handler time\n if (e.quotaExceeded && e.from > playbackController.getTime()) {\n setExplicitBufferingTime(e.from);\n }\n\n // (Re)start schedule once buffer has been pruned after a QuotaExceededError\n if (e.hasEnoughSpaceToAppend && e.quotaExceeded) {\n scheduleController.startScheduleTimer();\n }\n }\n\n /**\n * This function is called when the corresponding SourceBuffer encountered an error.\n * We blacklist the last segment assuming it caused the error\n * @param {object} e\n * @private\n */\n function _onSourceBufferError(e) {\n if (!e || !e.lastRequestAppended || !e.lastRequestAppended.url) {\n return;\n }\n\n let blacklistUrl = e.lastRequestAppended.url;\n\n if (e.lastRequestAppended.range) {\n blacklistUrl = blacklistUrl.concat('_', e.lastRequestAppended.range);\n }\n logger.warn(`Blacklisting segment with url ${blacklistUrl}`);\n segmentBlacklistController.add(blacklistUrl);\n }\n\n /**\n * The quality has changed which means we have switched to a different representation.\n * If we want to aggressively replace existing parts in the buffer we need to make sure that the new quality is higher than the already buffered one.\n * @param {object} e\n * @private\n */\n function prepareQualityChange(e) {\n logger.debug(`Preparing quality switch for type ${type}`);\n const newQuality = e.newQuality;\n\n qualityChangeInProgress = true;\n\n // Stop scheduling until we are done with preparing the quality switch\n scheduleController.clearScheduleTimer();\n\n const representationInfo = getRepresentationInfo(newQuality);\n scheduleController.setCurrentRepresentation(representationInfo);\n representationController.prepareQualityChange(newQuality);\n\n // Abort the current request to avoid inconsistencies. A quality switch can also be triggered manually by the application.\n // If we update the buffer values now, or initialize a request to the new init segment, the currently downloading media segment might \"work\" with wrong values.\n // Everything that is already in the buffer queue is ok and will be handled by the corresponding function below depending on the switch mode.\n fragmentModel.abortRequests();\n\n // In any case we need to update the MSE.timeOffset\n bufferController.updateBufferTimestampOffset(representationInfo)\n .then(() => {\n\n // If the switch should occur immediately we need to replace existing stuff in the buffer\n if (e.reason && e.reason.forceReplace) {\n _prepareReplacementQualitySwitch();\n }\n\n // If fast switch is enabled we check if we are supposed to replace existing stuff in the buffer\n else if (settings.get().streaming.buffer.fastSwitchEnabled) {\n _prepareForFastQualitySwitch(representationInfo);\n }\n\n // Default quality switch. We append the new quality to the already buffered stuff\n else {\n _prepareForDefaultQualitySwitch();\n }\n\n dashMetrics.pushPlayListTraceMetrics(new Date(), PlayListTrace.REPRESENTATION_SWITCH_STOP_REASON);\n dashMetrics.createPlaylistTraceMetrics(representationInfo.id, playbackController.getTime() * 1000, playbackController.getPlaybackRate());\n })\n }\n\n function _prepareReplacementQualitySwitch() {\n\n // Inform other classes like the GapController that we are replacing existing stuff\n eventBus.trigger(Events.BUFFER_REPLACEMENT_STARTED, {\n mediaType: type,\n streamId: streamInfo.id\n }, { mediaType: type, streamId: streamInfo.id });\n\n // Abort appending segments to the buffer. Also adjust the appendWindow as we might have been in the progress of prebuffering stuff.\n bufferController.prepareForReplacementQualitySwitch()\n .then(() => {\n _bufferClearedForReplacement();\n qualityChangeInProgress = false;\n })\n .catch(() => {\n _bufferClearedForReplacement();\n qualityChangeInProgress = false;\n });\n }\n\n function _prepareForFastQualitySwitch(representationInfo) {\n // if we switch up in quality and need to replace existing parts in the buffer we need to adjust the buffer target\n const time = playbackController.getTime();\n let safeBufferLevel = 1.5;\n const request = fragmentModel.getRequests({\n state: FragmentModel.FRAGMENT_MODEL_EXECUTED,\n time: time + safeBufferLevel,\n threshold: 0\n })[0];\n\n if (request && !getIsTextTrack()) {\n const bufferLevel = bufferController.getBufferLevel();\n const abandonmentState = abrController.getAbandonmentStateFor(streamInfo.id, type);\n\n if (request.quality < representationInfo.quality && bufferLevel >= safeBufferLevel && abandonmentState !== MetricsConstants.ABANDON_LOAD) {\n const targetTime = time + safeBufferLevel;\n setExplicitBufferingTime(targetTime);\n scheduleController.setCheckPlaybackQuality(false);\n scheduleController.startScheduleTimer();\n } else {\n _prepareForDefaultQualitySwitch();\n }\n } else {\n scheduleController.startScheduleTimer();\n }\n qualityChangeInProgress = false;\n }\n\n function _prepareForDefaultQualitySwitch() {\n // We might have aborted the current request. We need to set an explicit buffer time based on what we already have in the buffer.\n _bufferClearedForNonReplacement()\n qualityChangeInProgress = false;\n }\n\n /**\n * We have canceled the download of a fragment and need to adjust the buffer time or reload an init segment\n * @param {object} e\n */\n function _onFragmentLoadingAbandoned(e) {\n logger.info('onFragmentLoadingAbandoned request: ' + e.request.url + ' has been aborted');\n\n // we only need to handle this if we are not seeking, not switching the tracks and not switching the quality\n if (!playbackController.isSeeking() && !scheduleController.getSwitchStrack() && !qualityChangeInProgress) {\n logger.info('onFragmentLoadingAbandoned request: ' + e.request.url + ' has to be downloaded again, origin is not seeking process or switch track call');\n\n // in case of an init segment we force the download of an init segment\n if (e.request && e.request.isInitializationRequest()) {\n scheduleController.setInitSegmentRequired(true);\n }\n\n // in case of a media segment we reset the buffering time\n else {\n setExplicitBufferingTime(e.request.startTime + (e.request.duration / 2));\n }\n\n // In case of a seek the schedule controller was stopped and will be started once the buffer has been pruned.\n scheduleController.startScheduleTimer(0);\n }\n }\n\n /**\n * When a fragment has been loaded we need to start the schedule timer again in case of an error.\n * @param {object} e\n */\n function _onFragmentLoadingCompleted(e) {\n logger.info('OnFragmentLoadingCompleted for stream id ' + streamInfo.id + ' and media type ' + type + ' - Url:', e.request ? e.request.url : 'undefined', e.request.range ? ', Range:' + e.request.range : '');\n\n if (getIsTextTrack()) {\n scheduleController.startScheduleTimer(0);\n }\n\n if (e.error && e.request.serviceLocation) {\n _handleFragmentLoadingError(e);\n }\n }\n\n /**\n * If we encountered an error when loading the fragment we need to handle it according to the segment type\n * @private\n */\n function _handleFragmentLoadingError(e) {\n logger.info(`Fragment loading completed with an error`);\n\n if (!e || !e.request || !e.request.type) {\n return;\n }\n\n // In case there are baseUrls that can still be tried a valid request can be generated. If no valid request can be generated we ran out of baseUrls.\n // Consequently, we need to signal that we dont want to retry in case no valid request could be generated otherwise we keep trying with the same url infinitely.\n\n // Init segment could not be loaded. If we have multiple baseUrls we still have a chance to get a valid segment.\n if (e.request.type === HTTPRequest.INIT_SEGMENT_TYPE) {\n _onInitFragmentNeeded({\n representationId: e.request.representationId,\n sender: {}\n }, false)\n }\n\n // Media segment could not be loaded\n else if (e.request.type === HTTPRequest.MEDIA_SEGMENT_TYPE) {\n setExplicitBufferingTime(e.request.startTime + (e.request.duration / 2));\n _onMediaFragmentNeeded({}, false);\n }\n }\n\n /**\n * Callback function triggered by the TextController whenever a track is changed for fragmented text. Will only be triggered if textracks have previously been disabled.\n * @private\n */\n function _onSetFragmentedTextAfterDisabled() {\n setExplicitBufferingTime(playbackController.getTime());\n getScheduleController().startScheduleTimer();\n }\n\n /**\n * Callback function triggered by the TextController whenever a track is changed for non fragmented text\n * @param {object} e\n * @private\n */\n function _onSetNonFragmentedText(e) {\n const currentTrackInfo = e.currentTrackInfo;\n\n if (!currentTrackInfo) {\n return;\n }\n\n const mInfo = mediaInfoArr.find((info) => {\n return info.index === currentTrackInfo.index && info.lang === currentTrackInfo.lang;\n });\n\n if (mInfo) {\n selectMediaInfo(mInfo)\n .then(() => {\n bufferController.setIsBufferingCompleted(false);\n setExplicitBufferingTime(playbackController.getTime());\n scheduleController.setInitSegmentRequired(true);\n scheduleController.startScheduleTimer();\n });\n }\n }\n\n function _onQuotaExceeded(e) {\n // Stop scheduler (will be restarted once buffer is pruned)\n setExplicitBufferingTime(e.quotaExceededTime);\n scheduleController.clearScheduleTimer();\n }\n\n function getRepresentationController() {\n return representationController;\n }\n\n function getBuffer() {\n return bufferController ? bufferController.getBuffer() : null;\n }\n\n function getBufferController() {\n return bufferController;\n }\n\n function getFragmentModel() {\n return fragmentModel;\n }\n\n function updateStreamInfo(newStreamInfo) {\n streamInfo = newStreamInfo;\n if (!isBufferingCompleted()) {\n return bufferController.updateAppendWindow();\n }\n return Promise.resolve();\n }\n\n function getStreamInfo() {\n return streamInfo;\n }\n\n /**\n * Called once the StreamProcessor is initialized and when the track is switched. We only have one StreamProcessor per media type. So we need to adjust the mediaInfo once we switch/select a track.\n * @param {object} newMediaInfo\n */\n function selectMediaInfo(newMediaInfo) {\n if (newMediaInfo !== mediaInfo && (!newMediaInfo || !mediaInfo || (newMediaInfo.type === mediaInfo.type))) {\n mediaInfo = newMediaInfo;\n }\n\n const newRealAdaptation = adapter.getRealAdaptation(streamInfo, mediaInfo);\n const voRepresentations = adapter.getVoRepresentations(mediaInfo);\n\n if (representationController) {\n const realAdaptation = representationController.getData();\n const maxQuality = abrController.getMaxAllowedIndexFor(type, streamInfo.id);\n const minIdx = abrController.getMinAllowedIndexFor(type, streamInfo.id);\n\n let quality,\n averageThroughput;\n let bitrate = null;\n\n if ((realAdaptation === null || (realAdaptation.id !== newRealAdaptation.id)) && type !== Constants.TEXT) {\n averageThroughput = abrController.getThroughputHistory().getAverageThroughput(type, isDynamic);\n bitrate = averageThroughput || abrController.getInitialBitrateFor(type, streamInfo.id);\n quality = abrController.getQualityForBitrate(mediaInfo, bitrate, streamInfo.id);\n } else {\n quality = abrController.getQualityFor(type, streamInfo.id);\n }\n\n if (minIdx !== undefined && quality < minIdx) {\n quality = minIdx;\n }\n if (quality > maxQuality) {\n quality = maxQuality;\n }\n return representationController.updateData(newRealAdaptation, voRepresentations, type, mediaInfo.isFragmented, quality);\n } else {\n return Promise.resolve();\n }\n }\n\n function addMediaInfo(newMediaInfo) {\n if (mediaInfoArr.indexOf(newMediaInfo) === -1) {\n mediaInfoArr.push(newMediaInfo);\n }\n }\n\n function clearMediaInfoArray() {\n mediaInfoArr = [];\n }\n\n function getMediaInfo() {\n return mediaInfo;\n }\n\n function getMediaSource() {\n return bufferController.getMediaSource();\n }\n\n function setMediaSource(mediaSource) {\n bufferController.setMediaSource(mediaSource);\n }\n\n function getScheduleController() {\n return scheduleController;\n }\n\n /**\n * Get a specific voRepresentation. If quality parameter is defined, this function will return the voRepresentation for this quality.\n * Otherwise, this function will return the current voRepresentation used by the representationController.\n * @param {number} quality - quality index of the voRepresentaion expected.\n */\n function getRepresentationInfo(quality) {\n let voRepresentation;\n\n if (quality !== undefined) {\n checkInteger(quality);\n voRepresentation = representationController ? representationController.getRepresentationForQuality(quality) : null;\n } else {\n voRepresentation = representationController ? representationController.getCurrentRepresentation() : null;\n }\n\n return adapter.convertRepresentationToRepresentationInfo(voRepresentation);\n }\n\n function isBufferingCompleted() {\n return bufferController ? bufferController.getIsBufferingCompleted() : false;\n }\n\n function getBufferLevel() {\n return bufferController ? bufferController.getBufferLevel() : 0;\n }\n\n /**\n * Probe the next request. This is used in the CMCD model to get information about the upcoming request. Note: No actual request is performed here.\n * @return {FragmentRequest|null}\n */\n function probeNextRequest() {\n const representationInfo = getRepresentationInfo();\n\n const representation = representationController && representationInfo ?\n representationController.getRepresentationForQuality(representationInfo.quality) : null;\n\n let request = dashHandler.getNextSegmentRequestIdempotent(\n mediaInfo,\n representation\n );\n\n return request;\n }\n\n function _onMediaFragmentLoaded(e) {\n const chunk = e.chunk;\n\n const bytes = chunk.bytes;\n const quality = chunk.quality;\n const currentRepresentation = getRepresentationInfo(quality);\n const voRepresentation = representationController && currentRepresentation ? representationController.getRepresentationForQuality(currentRepresentation.quality) : null;\n\n // If we switch tracks this event might be fired after the representations in the RepresentationController have been updated according to the new MediaInfo.\n // In this case there will be no currentRepresentation and voRepresentation matching the \"old\" quality\n if (currentRepresentation && voRepresentation) {\n const eventStreamMedia = adapter.getEventsFor(currentRepresentation.mediaInfo);\n const eventStreamTrack = adapter.getEventsFor(currentRepresentation, voRepresentation);\n\n if (eventStreamMedia && eventStreamMedia.length > 0 || eventStreamTrack && eventStreamTrack.length > 0) {\n const request = fragmentModel.getRequests({\n state: FragmentModel.FRAGMENT_MODEL_EXECUTED,\n quality: quality,\n index: chunk.index\n })[0];\n\n const events = _handleInbandEvents(bytes, request, eventStreamMedia, eventStreamTrack);\n eventBus.trigger(Events.INBAND_EVENTS,\n { events: events },\n { streamId: streamInfo.id }\n );\n }\n }\n }\n\n function _handleInbandEvents(data, request, mediaInbandEvents, trackInbandEvents) {\n try {\n const eventStreams = {};\n const events = [];\n\n /* Extract the possible schemeIdUri : If a DASH client detects an event message box with a scheme that is not defined in MPD, the client is expected to ignore it */\n const inbandEvents = mediaInbandEvents.concat(trackInbandEvents);\n for (let i = 0, ln = inbandEvents.length; i < ln; i++) {\n eventStreams[inbandEvents[i].schemeIdUri + '/' + inbandEvents[i].value] = inbandEvents[i];\n }\n\n const isoFile = BoxParser(context).getInstance().parse(data);\n const eventBoxes = isoFile.getBoxes('emsg');\n\n if (!eventBoxes || eventBoxes.length === 0) {\n return events;\n }\n\n const sidx = isoFile.getBox('sidx');\n const mediaAnchorTime = sidx && !isNaN(sidx.earliest_presentation_time) && !isNaN(sidx.timescale) ? sidx.earliest_presentation_time / sidx.timescale : request && !isNaN(request.mediaStartTime) ? request.mediaStartTime : 0;\n const fragmentMediaStartTime = Math.max(mediaAnchorTime, 0);\n const voRepresentation = representationController.getCurrentRepresentation();\n\n for (let i = 0, ln = eventBoxes.length; i < ln; i++) {\n const event = adapter.getEvent(eventBoxes[i], eventStreams, fragmentMediaStartTime, voRepresentation);\n\n if (event) {\n events.push(event);\n }\n }\n\n return events;\n } catch (e) {\n return [];\n }\n }\n\n function createBufferSinks(previousBufferSinks) {\n const buffer = getBuffer();\n\n if (buffer) {\n return Promise.resolve(buffer);\n }\n\n return bufferController ? bufferController.createBufferSink(mediaInfo, previousBufferSinks) : Promise.resolve(null);\n }\n\n function prepareTrackSwitch() {\n return new Promise((resolve) => {\n logger.debug(`Preparing track switch for type ${type}`);\n const shouldReplace = type === Constants.TEXT || (settings.get().streaming.trackSwitchMode[type] === Constants.TRACK_SWITCH_MODE_ALWAYS_REPLACE && playbackController.getTimeToStreamEnd(streamInfo) > settings.get().streaming.buffer.stallThreshold);\n\n // when buffering is completed and we are not supposed to replace anything do nothing.\n // Still we need to trigger preloading again and call change type in case user seeks back before transitioning to next period\n if (bufferController.getIsBufferingCompleted() && !shouldReplace) {\n bufferController.prepareForNonReplacementTrackSwitch(mediaInfo.codec)\n .then(() => {\n eventBus.trigger(Events.BUFFERING_COMPLETED, {}, { streamId: streamInfo.id, mediaType: type })\n })\n .catch(() => {\n eventBus.trigger(Events.BUFFERING_COMPLETED, {}, { streamId: streamInfo.id, mediaType: type })\n })\n resolve();\n return;\n }\n\n // We stop the schedule controller and signal a track switch. That way we request a new init segment next\n scheduleController.clearScheduleTimer();\n scheduleController.setSwitchTrack(true);\n\n // when we are supposed to replace it does not matter if buffering is already completed\n if (shouldReplace) {\n // Inform other classes like the GapController that we are replacing existing stuff\n eventBus.trigger(Events.BUFFER_REPLACEMENT_STARTED, {\n mediaType: type,\n streamId: streamInfo.id\n }, { mediaType: type, streamId: streamInfo.id });\n\n // Abort the current request it will be removed from the buffer anyways\n fragmentModel.abortRequests();\n\n // Abort appending segments to the buffer. Also adjust the appendWindow as we might have been in the progress of prebuffering stuff.\n bufferController.prepareForReplacementTrackSwitch(mediaInfo.codec)\n .then(() => {\n // Timestamp offset couldve been changed by preloading period\n const representationInfo = getRepresentationInfo();\n return bufferController.updateBufferTimestampOffset(representationInfo);\n })\n .then(() => {\n _bufferClearedForReplacement();\n resolve();\n })\n .catch(() => {\n _bufferClearedForReplacement();\n resolve();\n });\n } else {\n // We do not replace anything that is already in the buffer. Still we need to prepare the buffer for the track switch\n bufferController.prepareForNonReplacementTrackSwitch(mediaInfo.codec)\n .then(() => {\n _bufferClearedForNonReplacement();\n resolve();\n })\n .catch(() => {\n _bufferClearedForNonReplacement();\n resolve();\n });\n }\n })\n\n }\n\n /**\n * For an instant track switch we need to adjust the buffering time after the buffer has been pruned.\n * @private\n */\n function _bufferClearedForReplacement() {\n const targetTime = playbackController.getTime();\n\n if (settings.get().streaming.buffer.flushBufferAtTrackSwitch) {\n // For some devices (like chromecast) it is necessary to seek the video element to reset the internal decoding buffer,\n // otherwise audio track switch will be effective only once after previous buffered track is consumed\n playbackController.seek(targetTime + 0.001, false, true);\n }\n\n setExplicitBufferingTime(targetTime);\n bufferController.setSeekTarget(targetTime);\n scheduleController.startScheduleTimer();\n }\n\n function _bufferClearedForNonReplacement() {\n const time = playbackController.getTime();\n const continuousBufferTime = bufferController.getContinuousBufferTimeForTargetTime(time);\n const targetTime = isNaN(continuousBufferTime) ? time : continuousBufferTime;\n\n setExplicitBufferingTime(targetTime);\n scheduleController.startScheduleTimer();\n }\n\n\n function _createBufferControllerForType(type, isFragmented) {\n let controller = null;\n\n if (!type) {\n errHandler.error(new DashJSError(Errors.MEDIASOURCE_TYPE_UNSUPPORTED_CODE, Errors.MEDIASOURCE_TYPE_UNSUPPORTED_MESSAGE + 'not properly defined'));\n return null;\n }\n\n if (type === Constants.TEXT && !isFragmented) {\n controller = NotFragmentedTextBufferController(context).create({\n streamInfo,\n type,\n mimeType,\n fragmentModel,\n textController,\n errHandler,\n settings\n });\n } else {\n controller = BufferController(context).create({\n streamInfo,\n type,\n mediaPlayerModel,\n manifestModel,\n fragmentModel,\n errHandler,\n mediaController,\n representationController,\n adapter,\n textController,\n abrController,\n playbackController,\n settings\n });\n }\n\n return controller;\n }\n\n function _onSeekTarget(e) {\n if (e && !isNaN(e.time)) {\n setExplicitBufferingTime(e.time);\n bufferController.setSeekTarget(e.time);\n }\n }\n\n function setExplicitBufferingTime(value) {\n bufferingTime = value;\n shouldUseExplicitTimeForRequest = true;\n }\n\n function finalisePlayList(time, reason) {\n dashMetrics.pushPlayListTraceMetrics(time, reason);\n }\n\n instance = {\n initialize,\n getStreamId,\n getType,\n isUpdating,\n getBufferController,\n getFragmentModel,\n getScheduleController,\n getRepresentationController,\n getRepresentationInfo,\n getBufferLevel,\n isBufferingCompleted,\n createBufferSinks,\n updateStreamInfo,\n getStreamInfo,\n selectMediaInfo,\n clearMediaInfoArray,\n addMediaInfo,\n prepareTrackSwitch,\n prepareQualityChange,\n getMediaInfo,\n getMediaSource,\n setMediaSource,\n getBuffer,\n setExplicitBufferingTime,\n finalisePlayList,\n probeNextRequest,\n prepareInnerPeriodPlaybackSeeking,\n prepareOuterPeriodPlaybackSeeking,\n reset\n };\n\n setup();\n\n return instance;\n}\n\nStreamProcessor.__dashjs_factory_name = 'StreamProcessor';\nexport default FactoryMaker.getClassFactory(StreamProcessor);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Constants from '../constants/Constants';\nimport DataChunk from '../vo/DataChunk';\nimport FragmentModel from '../models/FragmentModel';\nimport FragmentLoader from '../FragmentLoader';\nimport RequestModifier from '../utils/RequestModifier';\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\nimport MediaPlayerEvents from '../MediaPlayerEvents';\nimport Errors from '../../core/errors/Errors';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Debug from '../../core/Debug';\n\nfunction FragmentController(config) {\n\n config = config || {};\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n\n const errHandler = config.errHandler;\n const mediaPlayerModel = config.mediaPlayerModel;\n const dashMetrics = config.dashMetrics;\n const debug = Debug(context).getInstance();\n const streamInfo = config.streamInfo;\n\n let instance,\n logger,\n fragmentModels;\n\n function setup() {\n logger = debug.getLogger(instance);\n resetInitialSettings();\n eventBus.on(MediaPlayerEvents.FRAGMENT_LOADING_COMPLETED, onFragmentLoadingCompleted, instance);\n eventBus.on(MediaPlayerEvents.FRAGMENT_LOADING_PROGRESS, onFragmentLoadingCompleted, instance);\n }\n\n function getStreamId() {\n return streamInfo.id;\n }\n\n function getModel(type) {\n let model = fragmentModels[type];\n if (!model) {\n model = FragmentModel(context).create({\n streamInfo: streamInfo,\n type: type,\n dashMetrics: dashMetrics,\n fragmentLoader: FragmentLoader(context).create({\n dashMetrics: dashMetrics,\n mediaPlayerModel: mediaPlayerModel,\n errHandler: errHandler,\n requestModifier: RequestModifier(context).getInstance(),\n settings: config.settings,\n boxParser: config.boxParser,\n eventBus: eventBus,\n events: Events,\n errors: Errors,\n dashConstants: config.dashConstants,\n urlUtils: config.urlUtils,\n streamId: getStreamId()\n }),\n debug: debug,\n eventBus: eventBus,\n events: Events\n });\n\n fragmentModels[type] = model;\n }\n\n return model;\n }\n\n function resetInitialSettings() {\n for (let model in fragmentModels) {\n fragmentModels[model].reset();\n }\n fragmentModels = {};\n }\n\n function reset() {\n eventBus.off(MediaPlayerEvents.FRAGMENT_LOADING_COMPLETED, onFragmentLoadingCompleted, this);\n eventBus.off(MediaPlayerEvents.FRAGMENT_LOADING_PROGRESS, onFragmentLoadingCompleted, this);\n resetInitialSettings();\n }\n\n function createDataChunk(bytes, request, streamId, endFragment) {\n const chunk = new DataChunk();\n\n chunk.streamId = streamId;\n chunk.mediaInfo = request.mediaInfo;\n chunk.segmentType = request.type;\n chunk.start = request.startTime;\n chunk.duration = request.duration;\n chunk.end = chunk.start + chunk.duration;\n chunk.bytes = bytes;\n chunk.index = request.index;\n chunk.quality = request.quality;\n chunk.representationId = request.representationId;\n chunk.endFragment = endFragment;\n\n return chunk;\n }\n\n function onFragmentLoadingCompleted(e) {\n // Event propagation may have been stopped (see MssHandler)\n if (!e.sender) return;\n\n const request = e.request;\n const bytes = e.response;\n const isInit = request.isInitializationRequest();\n const strInfo = request.mediaInfo.streamInfo;\n\n if (e.error) {\n if (request.mediaType === Constants.AUDIO || request.mediaType === Constants.VIDEO || (request.mediaType === Constants.TEXT && request.mediaInfo.isFragmented)) {\n // add service location to blacklist controller - only for audio or video. text should not set errors\n eventBus.trigger(Events.SERVICE_LOCATION_BLACKLIST_ADD, { entry: e.request.serviceLocation });\n }\n }\n\n if (!bytes || !strInfo) {\n logger.warn('No ' + request.mediaType + ' bytes to push or stream is inactive.');\n return;\n }\n const chunk = createDataChunk(bytes, request, streamInfo.id, e.type !== Events.FRAGMENT_LOADING_PROGRESS);\n eventBus.trigger(isInit ? Events.INIT_FRAGMENT_LOADED : Events.MEDIA_FRAGMENT_LOADED,\n {\n chunk: chunk,\n request: request\n },\n { streamId: strInfo.id, mediaType: request.mediaType }\n );\n }\n\n instance = {\n getStreamId: getStreamId,\n getModel: getModel,\n reset: reset\n };\n\n setup();\n\n return instance;\n}\n\nFragmentController.__dashjs_factory_name = 'FragmentController';\nexport default FactoryMaker.getClassFactory(FragmentController);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass Thumbnail {\n constructor() {\n this.url = null;\n this.width = null;\n this.height = null;\n this.x = null;\n this.y = null;\n }\n}\n\nexport default Thumbnail;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass BitrateInfo {\n constructor() {\n this.mediaType = null;\n this.bitrate = null;\n this.width = null;\n this.height = null;\n this.scanType = null;\n this.qualityIndex = NaN;\n }\n}\n\nexport default BitrateInfo;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Constants from '../constants/Constants';\nimport Thumbnail from '../vo/Thumbnail';\nimport ThumbnailTracks from './ThumbnailTracks';\nimport BitrateInfo from '../vo/BitrateInfo';\nimport {replaceTokenForTemplate, unescapeDollarsInTemplate} from '../../dash/utils/SegmentsUtils';\n\nfunction ThumbnailController(config) {\n\n const context = this.context;\n const streamInfo = config.streamInfo;\n\n let instance,\n thumbnailTracks;\n\n function setup() {\n reset();\n thumbnailTracks = ThumbnailTracks(context).create({\n streamInfo: streamInfo,\n adapter: config.adapter,\n baseURLController: config.baseURLController,\n timelineConverter: config.timelineConverter,\n debug: config.debug,\n eventBus: config.eventBus,\n events: config.events,\n dashConstants: config.dashConstants,\n dashMetrics: config.dashMetrics,\n segmentBaseController: config.segmentBaseController\n });\n }\n\n function initialize() {\n thumbnailTracks.addTracks();\n const tracks = thumbnailTracks.getTracks();\n\n if (tracks && tracks.length > 0) {\n setTrackByIndex(0);\n }\n }\n\n function getStreamId() {\n return streamInfo.id;\n }\n\n function provide(time, callback) {\n\n if (typeof callback !== 'function') {\n return;\n }\n const track = thumbnailTracks.getCurrentTrack();\n let offset,\n request;\n if (!track || track.segmentDuration <= 0 || time === undefined || time === null) {\n callback(null);\n return;\n }\n\n request = thumbnailTracks.getThumbnailRequestForTime(time);\n if (request) {\n track.segmentDuration = request.duration;\n }\n\n offset = time % track.segmentDuration;\n\n const thumbIndex = Math.floor((offset * track.tilesHor * track.tilesVert) / track.segmentDuration);\n // Create and return the thumbnail\n const thumbnail = new Thumbnail();\n\n thumbnail.width = Math.floor(track.widthPerTile);\n thumbnail.height = Math.floor(track.heightPerTile);\n thumbnail.x = Math.floor(thumbIndex % track.tilesHor) * track.widthPerTile;\n thumbnail.y = Math.floor(thumbIndex / track.tilesHor) * track.heightPerTile;\n\n if ('readThumbnail' in track) {\n return track.readThumbnail(time, (url) => {\n thumbnail.url = url;\n callback(thumbnail);\n });\n } else {\n if (!request) {\n const seq = Math.floor(time / track.segmentDuration);\n thumbnail.url = _buildUrlFromTemplate(track, seq);\n } else {\n thumbnail.url = request.url;\n track.segmentDuration = NaN;\n }\n callback(thumbnail);\n }\n }\n\n function _buildUrlFromTemplate(track, seq) {\n const seqIdx = seq + track.startNumber;\n let url = replaceTokenForTemplate(track.templateUrl, 'Number', seqIdx);\n url = replaceTokenForTemplate(url, 'Time', (seqIdx - 1) * track.segmentDuration * track.timescale);\n url = replaceTokenForTemplate(url, 'Bandwidth', track.bandwidth);\n return unescapeDollarsInTemplate(url);\n }\n\n function setTrackByIndex(index) {\n thumbnailTracks.setTrackByIndex(index);\n }\n\n function getCurrentTrackIndex() {\n return thumbnailTracks.getCurrentTrackIndex();\n }\n\n function getBitrateList() {\n const tracks = thumbnailTracks.getTracks();\n let i = 0;\n\n return tracks.map((t) => {\n const bitrateInfo = new BitrateInfo();\n bitrateInfo.mediaType = Constants.IMAGE;\n bitrateInfo.qualityIndex = i++;\n bitrateInfo.bitrate = t.bitrate;\n bitrateInfo.width = t.width;\n bitrateInfo.height = t.height;\n return bitrateInfo;\n });\n }\n\n function reset() {\n if (thumbnailTracks) {\n thumbnailTracks.reset();\n }\n }\n\n instance = {\n getStreamId,\n initialize,\n provide,\n setTrackByIndex,\n getCurrentTrackIndex,\n getBitrateList,\n reset\n };\n\n setup();\n\n return instance;\n}\n\nThumbnailController.__dashjs_factory_name = 'ThumbnailController';\nexport default FactoryMaker.getClassFactory(ThumbnailController);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport FactoryMaker from '../../core/FactoryMaker';\nimport EventBus from '../../core/EventBus';\n\nfunction BlackListController(config) {\n\n config = config || {};\n let instance;\n let blacklist = [];\n\n const eventBus = EventBus(this.context).getInstance();\n const updateEventName = config.updateEventName;\n const addBlacklistEventName = config.addBlacklistEventName;\n\n function contains(query) {\n if (!blacklist.length || !query || !query.length) {\n return false;\n }\n\n return (blacklist.indexOf(query) !== -1);\n }\n\n function add(entry) {\n if (blacklist.indexOf(entry) !== -1) {\n return;\n }\n\n blacklist.push(entry);\n\n eventBus.trigger(updateEventName, { entry: entry });\n }\n\n function onAddBlackList(e) {\n add(e.entry);\n }\n\n function setup() {\n if (addBlacklistEventName) {\n eventBus.on(addBlacklistEventName, onAddBlackList, instance);\n }\n }\n\n function reset() {\n blacklist = [];\n }\n\n instance = {\n add: add,\n contains: contains,\n reset: reset\n };\n\n setup();\n return instance;\n}\n\nBlackListController.__dashjs_factory_name = 'BlackListController';\nexport default FactoryMaker.getClassFactory(BlackListController);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Constants from './constants/Constants';\nimport DashConstants from '../dash/constants/DashConstants';\nimport StreamProcessor from './StreamProcessor';\nimport FragmentController from './controllers/FragmentController';\nimport ThumbnailController from './thumbnail/ThumbnailController';\nimport EventBus from '../core/EventBus';\nimport Events from '../core/events/Events';\nimport Debug from '../core/Debug';\nimport Errors from '../core/errors/Errors';\nimport FactoryMaker from '../core/FactoryMaker';\nimport DashJSError from './vo/DashJSError';\nimport BoxParser from './utils/BoxParser';\nimport URLUtils from './utils/URLUtils';\nimport BlacklistController from './controllers/BlacklistController';\n\n\nconst MEDIA_TYPES = [Constants.VIDEO, Constants.AUDIO, Constants.TEXT, Constants.MUXED, Constants.IMAGE];\n\n\nfunction Stream(config) {\n\n config = config || {};\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n const urlUtils = URLUtils(context).getInstance();\n\n const manifestModel = config.manifestModel;\n const mediaPlayerModel = config.mediaPlayerModel;\n const dashMetrics = config.dashMetrics;\n const manifestUpdater = config.manifestUpdater;\n const adapter = config.adapter;\n const timelineConverter = config.timelineConverter;\n const capabilities = config.capabilities;\n const errHandler = config.errHandler;\n const abrController = config.abrController;\n const playbackController = config.playbackController;\n const eventController = config.eventController;\n const mediaController = config.mediaController;\n const protectionController = config.protectionController;\n const textController = config.textController;\n const videoModel = config.videoModel;\n let streamInfo = config.streamInfo;\n const settings = config.settings;\n\n\n let instance,\n logger,\n streamProcessors,\n isInitialized,\n isActive,\n hasFinishedBuffering,\n hasVideoTrack,\n hasAudioTrack,\n updateError,\n isUpdating,\n fragmentController,\n thumbnailController,\n segmentBlacklistController,\n preloaded,\n boxParser,\n debug,\n isEndedEventSignaled,\n trackChangedEvents;\n\n /**\n * Setup the stream\n */\n function setup() {\n try {\n debug = Debug(context).getInstance();\n logger = debug.getLogger(instance);\n resetInitialSettings();\n\n boxParser = BoxParser(context).getInstance();\n\n segmentBlacklistController = BlacklistController(context).create({\n updateEventName: Events.SEGMENT_LOCATION_BLACKLIST_CHANGED,\n addBlacklistEventName: Events.SEGMENT_LOCATION_BLACKLIST_ADD\n });\n\n fragmentController = FragmentController(context).create({\n streamInfo: streamInfo,\n mediaPlayerModel: mediaPlayerModel,\n dashMetrics: dashMetrics,\n errHandler: errHandler,\n settings: settings,\n boxParser: boxParser,\n dashConstants: DashConstants,\n urlUtils: urlUtils\n });\n\n } catch (e) {\n throw e;\n }\n }\n\n /**\n * Initialize the events\n */\n function initialize() {\n registerEvents();\n registerProtectionEvents();\n textController.initializeForStream(streamInfo);\n eventBus.trigger(Events.STREAM_UPDATED, { streamInfo: streamInfo });\n }\n\n /**\n * Register the streaming events\n */\n function registerEvents() {\n eventBus.on(Events.BUFFERING_COMPLETED, onBufferingCompleted, instance);\n eventBus.on(Events.DATA_UPDATE_COMPLETED, onDataUpdateCompleted, instance);\n eventBus.on(Events.INBAND_EVENTS, onInbandEvents, instance);\n }\n\n /**\n * Unregister the streaming events\n */\n function unRegisterEvents() {\n eventBus.off(Events.DATA_UPDATE_COMPLETED, onDataUpdateCompleted, instance);\n eventBus.off(Events.BUFFERING_COMPLETED, onBufferingCompleted, instance);\n eventBus.off(Events.INBAND_EVENTS, onInbandEvents, instance);\n }\n\n /**\n * Register the protection events\n */\n function registerProtectionEvents() {\n if (protectionController) {\n eventBus.on(Events.KEY_ERROR, onProtectionError, instance);\n eventBus.on(Events.SERVER_CERTIFICATE_UPDATED, onProtectionError, instance);\n eventBus.on(Events.LICENSE_REQUEST_COMPLETE, onProtectionError, instance);\n eventBus.on(Events.KEY_SYSTEM_SELECTED, onProtectionError, instance);\n eventBus.on(Events.KEY_SESSION_CREATED, onProtectionError, instance);\n eventBus.on(Events.KEY_STATUSES_CHANGED, onProtectionError, instance);\n }\n }\n\n /**\n * Unregister the protection events\n */\n function unRegisterProtectionEvents() {\n if (protectionController) {\n eventBus.off(Events.KEY_ERROR, onProtectionError, instance);\n eventBus.off(Events.SERVER_CERTIFICATE_UPDATED, onProtectionError, instance);\n eventBus.off(Events.LICENSE_REQUEST_COMPLETE, onProtectionError, instance);\n eventBus.off(Events.KEY_SYSTEM_SELECTED, onProtectionError, instance);\n eventBus.off(Events.KEY_SESSION_CREATED, onProtectionError, instance);\n eventBus.off(Events.KEY_STATUSES_CHANGED, onProtectionError, instance);\n }\n }\n\n /**\n * Returns the stream id\n * @return {*|null}\n */\n function getStreamId() {\n return streamInfo ? streamInfo.id : null;\n }\n\n /**\n * Activates Stream by re-initializing some of its components\n * @param {MediaSource} mediaSource\n * @param {array} previousBufferSinks\n * @memberof Stream#\n */\n function activate(mediaSource, previousBufferSinks) {\n return new Promise((resolve, reject) => {\n if (isActive) {\n resolve(previousBufferSinks);\n return;\n }\n\n if (getPreloaded()) {\n isActive = true;\n eventBus.trigger(Events.STREAM_ACTIVATED, {\n streamInfo\n });\n resolve(previousBufferSinks);\n return;\n }\n\n\n _initializeMedia(mediaSource, previousBufferSinks)\n .then((bufferSinks) => {\n isActive = true;\n eventBus.trigger(Events.STREAM_ACTIVATED, {\n streamInfo\n });\n resolve(bufferSinks);\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n /**\n *\n * @param {object} mediaSource\n * @param {array} previousBufferSinks\n * @return {Promise<Array>}\n * @private\n */\n function _initializeMedia(mediaSource, previousBufferSinks) {\n return _commonMediaInitialization(mediaSource, previousBufferSinks);\n }\n\n function startPreloading(mediaSource, previousBuffers) {\n return new Promise((resolve, reject) => {\n\n if (getPreloaded()) {\n reject();\n return;\n }\n\n logger.info(`[startPreloading] Preloading next stream with id ${getId()}`);\n setPreloaded(true);\n\n _commonMediaInitialization(mediaSource, previousBuffers)\n .then(() => {\n for (let i = 0; i < streamProcessors.length && streamProcessors[i]; i++) {\n streamProcessors[i].setExplicitBufferingTime(getStartTime());\n streamProcessors[i].getScheduleController().startScheduleTimer();\n }\n resolve();\n })\n .catch(() => {\n setPreloaded(false);\n reject();\n });\n });\n }\n\n /**\n *\n * @param {object} mediaSource\n * @param {array} previousBufferSinks\n * @return {Promise<array>}\n * @private\n */\n function _commonMediaInitialization(mediaSource, previousBufferSinks) {\n return new Promise((resolve, reject) => {\n checkConfig();\n\n isUpdating = true;\n addInlineEvents();\n\n\n let element = videoModel.getElement();\n\n MEDIA_TYPES.forEach((mediaType) => {\n if (mediaType !== Constants.VIDEO || (!element || (element && (/^VIDEO$/i).test(element.nodeName)))) {\n _initializeMediaForType(mediaType, mediaSource);\n }\n });\n\n _createBufferSinks(previousBufferSinks)\n .then((bufferSinks) => {\n isUpdating = false;\n\n if (streamProcessors.length === 0) {\n const msg = 'No streams to play.';\n errHandler.error(new DashJSError(Errors.MANIFEST_ERROR_ID_NOSTREAMS_CODE, msg, manifestModel.getValue()));\n logger.fatal(msg);\n } else {\n _checkIfInitializationCompleted();\n }\n\n // All mediaInfos for texttracks are added to the TextSourceBuffer by now. We can start creating the tracks\n textController.createTracks(streamInfo);\n\n resolve(bufferSinks);\n })\n .catch((e) => {\n reject(e);\n });\n });\n\n }\n\n\n /**\n * Initialize for a given media type. Creates a corresponding StreamProcessor\n * @param {string} type\n * @param {object} mediaSource\n * @private\n */\n function _initializeMediaForType(type, mediaSource) {\n let allMediaForType = adapter.getAllMediaInfoForType(streamInfo, type);\n let embeddedMediaInfos = [];\n\n let mediaInfo = null;\n let initialMediaInfo;\n\n if (!allMediaForType || allMediaForType.length === 0) {\n logger.info('No ' + type + ' data.');\n return;\n }\n\n if (type === Constants.VIDEO) {\n hasVideoTrack = true;\n }\n\n if (type === Constants.AUDIO) {\n hasAudioTrack = true;\n }\n\n for (let i = 0, ln = allMediaForType.length; i < ln; i++) {\n mediaInfo = allMediaForType[i];\n\n if (type === Constants.TEXT && !!mediaInfo.isEmbedded) {\n textController.addEmbeddedTrack(streamInfo, mediaInfo);\n embeddedMediaInfos.push(mediaInfo);\n }\n if (_isMediaSupported(mediaInfo)) {\n mediaController.addTrack(mediaInfo);\n }\n }\n\n if (embeddedMediaInfos.length > 0) {\n mediaController.setInitialMediaSettingsForType(type, streamInfo);\n textController.setInitialSettings(mediaController.getInitialSettings(type));\n textController.addMediaInfosToBuffer(streamInfo, type, embeddedMediaInfos);\n }\n\n // Filter out embedded text track before creating StreamProcessor\n allMediaForType = allMediaForType.filter(mediaInfo => {\n return !mediaInfo.isEmbedded;\n });\n if (allMediaForType.length === 0) {\n return;\n }\n\n if (type === Constants.IMAGE) {\n thumbnailController = ThumbnailController(context).create({\n streamInfo: streamInfo,\n adapter: adapter,\n baseURLController: config.baseURLController,\n timelineConverter: config.timelineConverter,\n debug: debug,\n eventBus: eventBus,\n events: Events,\n dashConstants: DashConstants,\n dashMetrics: config.dashMetrics,\n segmentBaseController: config.segmentBaseController\n });\n thumbnailController.initialize();\n return;\n }\n\n eventBus.trigger(Events.STREAM_INITIALIZING, {\n streamInfo: streamInfo,\n mediaInfo: mediaInfo\n });\n\n mediaController.setInitialMediaSettingsForType(type, streamInfo);\n\n let streamProcessor = _createStreamProcessor(allMediaForType, mediaSource);\n\n initialMediaInfo = mediaController.getCurrentTrackFor(type, streamInfo.id);\n\n if (initialMediaInfo) {\n abrController.updateTopQualityIndex(initialMediaInfo);\n // In case of mixed fragmented and embedded text tracks, check if initial selected text track is not an embedded track\n streamProcessor.selectMediaInfo((type !== Constants.TEXT || !initialMediaInfo.isEmbedded) ? initialMediaInfo : allMediaForType[0]);\n }\n\n }\n\n function _isMediaSupported(mediaInfo) {\n const type = mediaInfo ? mediaInfo.type : null;\n let msg;\n\n if (type === Constants.MUXED) {\n msg = 'Multiplexed representations are intentionally not supported, as they are not compliant with the DASH-AVC/264 guidelines';\n logger.fatal(msg);\n errHandler.error(new DashJSError(Errors.MANIFEST_ERROR_ID_MULTIPLEXED_CODE, msg, manifestModel.getValue()));\n return false;\n }\n\n if (type === Constants.TEXT || type === Constants.IMAGE) {\n return true;\n }\n\n if (!!mediaInfo.contentProtection && !capabilities.supportsEncryptedMedia()) {\n errHandler.error(new DashJSError(Errors.CAPABILITY_MEDIAKEYS_ERROR_CODE, Errors.CAPABILITY_MEDIAKEYS_ERROR_MESSAGE));\n return false;\n }\n\n return true;\n }\n\n /**\n * Creates the StreamProcessor for a given media type.\n * @param {object} initialMediaInfo\n * @param {array} allMediaForType\n * @param {object} mediaSource\n * @private\n */\n function _createStreamProcessor(allMediaForType, mediaSource) {\n\n const mediaInfo = (allMediaForType && allMediaForType.length > 0) ? allMediaForType[0] : null;\n let fragmentModel = fragmentController.getModel(mediaInfo ? mediaInfo.type : null);\n const type = mediaInfo ? mediaInfo.type : null;\n const mimeType = mediaInfo ? mediaInfo.mimeType : null;\n const isFragmented = mediaInfo ? mediaInfo.isFragmented : null;\n\n let streamProcessor = StreamProcessor(context).create({\n streamInfo,\n type,\n mimeType,\n timelineConverter,\n adapter,\n manifestModel,\n mediaPlayerModel,\n fragmentModel,\n dashMetrics: config.dashMetrics,\n baseURLController: config.baseURLController,\n segmentBaseController: config.segmentBaseController,\n abrController,\n playbackController,\n mediaController,\n textController,\n errHandler,\n settings,\n boxParser,\n segmentBlacklistController\n });\n\n streamProcessor.initialize(mediaSource, hasVideoTrack, isFragmented);\n streamProcessors.push(streamProcessor);\n\n for (let i = 0; i < allMediaForType.length; i++) {\n streamProcessor.addMediaInfo(allMediaForType[i]);\n }\n\n if (type === Constants.TEXT) {\n textController.addMediaInfosToBuffer(streamInfo, type, allMediaForType, fragmentModel);\n }\n\n return streamProcessor;\n }\n\n /**\n * Creates the SourceBufferSink objects for all StreamProcessors\n * @param {array} previousBuffersSinks\n * @return {Promise<object>}\n * @private\n */\n function _createBufferSinks(previousBuffersSinks) {\n return new Promise((resolve) => {\n const buffers = {};\n const promises = streamProcessors.map((sp) => {\n return sp.createBufferSinks(previousBuffersSinks);\n });\n\n Promise.all(promises)\n .then((bufferSinks) => {\n bufferSinks.forEach((sink) => {\n if (sink) {\n buffers[sink.getType()] = sink;\n }\n });\n resolve(buffers);\n })\n .catch(() => {\n resolve(buffers);\n });\n });\n }\n\n /**\n * Partially resets some of the Stream elements. This function is called when preloading of streams is canceled or a stream switch occurs.\n * @memberof Stream#\n * @param {boolean} keepBuffers\n */\n function deactivate(keepBuffers) {\n let ln = streamProcessors ? streamProcessors.length : 0;\n const errored = false;\n for (let i = 0; i < ln; i++) {\n let fragmentModel = streamProcessors[i].getFragmentModel();\n fragmentModel.abortRequests();\n fragmentModel.resetInitialSettings();\n streamProcessors[i].reset(errored, keepBuffers);\n }\n if (textController) {\n textController.deactivateStream(streamInfo);\n }\n streamProcessors = [];\n isActive = false;\n hasFinishedBuffering = false;\n setPreloaded(false);\n setIsEndedEventSignaled(false);\n eventBus.trigger(Events.STREAM_DEACTIVATED, { streamInfo });\n }\n\n function getIsActive() {\n return isActive;\n }\n\n function setMediaSource(mediaSource) {\n for (let i = 0; i < streamProcessors.length;) {\n if (_isMediaSupported(streamProcessors[i].getMediaInfo())) {\n streamProcessors[i].setMediaSource(mediaSource);\n i++;\n } else {\n streamProcessors[i].reset();\n streamProcessors.splice(i, 1);\n }\n }\n\n if (streamProcessors.length === 0) {\n const msg = 'No streams to play.';\n errHandler.error(new DashJSError(Errors.MANIFEST_ERROR_ID_NOSTREAMS_CODE, msg + 'nostreams', manifestModel.getValue()));\n logger.fatal(msg);\n }\n }\n\n function resetInitialSettings(keepBuffers) {\n deactivate(keepBuffers);\n isInitialized = false;\n hasVideoTrack = false;\n hasAudioTrack = false;\n updateError = {};\n isUpdating = false;\n isEndedEventSignaled = false;\n trackChangedEvents = [];\n }\n\n function reset(keepBuffers) {\n\n if (fragmentController) {\n fragmentController.reset();\n fragmentController = null;\n }\n\n if (abrController && streamInfo) {\n abrController.clearDataForStream(streamInfo.id);\n }\n\n if (segmentBlacklistController) {\n segmentBlacklistController.reset();\n segmentBlacklistController = null;\n }\n\n resetInitialSettings(keepBuffers);\n\n streamInfo = null;\n\n unRegisterEvents();\n\n unRegisterProtectionEvents();\n\n }\n\n function getDuration() {\n return streamInfo ? streamInfo.duration : NaN;\n }\n\n function getIsEndedEventSignaled() {\n return isEndedEventSignaled;\n }\n\n function setIsEndedEventSignaled(value) {\n isEndedEventSignaled = value;\n }\n\n function getStartTime() {\n return streamInfo ? streamInfo.start : NaN;\n }\n\n function getId() {\n return streamInfo ? streamInfo.id : null;\n }\n\n function getStreamInfo() {\n return streamInfo;\n }\n\n function getHasAudioTrack() {\n return hasAudioTrack;\n }\n\n function getHasVideoTrack() {\n return hasVideoTrack;\n }\n\n function getThumbnailController() {\n return thumbnailController;\n }\n\n function checkConfig() {\n if (!videoModel || !abrController) {\n throw new Error(Constants.MISSING_CONFIG_ERROR);\n }\n }\n\n /**\n * @param {string} type\n * @returns {Array}\n * @memberof Stream#\n */\n function getBitrateListFor(type) {\n checkConfig();\n if (type === Constants.IMAGE) {\n if (!thumbnailController) {\n return [];\n }\n return thumbnailController.getBitrateList();\n }\n const mediaInfo = getMediaInfo(type);\n return abrController.getBitrateList(mediaInfo);\n }\n\n function onProtectionError(event) {\n if (event.error) {\n errHandler.error(event.error);\n logger.fatal(event.error.message);\n }\n }\n\n function prepareTrackChange(e) {\n if (!isActive || !streamInfo) {\n return;\n }\n\n hasFinishedBuffering = false;\n\n let mediaInfo = e.newMediaInfo;\n let manifest = manifestModel.getValue();\n\n adapter.setCurrentMediaInfo(streamInfo.id, mediaInfo.type, mediaInfo);\n\n let processor = getProcessorForMediaInfo(mediaInfo);\n if (!processor) return;\n\n let currentTime = playbackController.getTime();\n logger.info('Stream - Process track changed at current time ' + currentTime);\n\n // Applies only for MSS streams\n if (manifest.refreshManifestOnSwitchTrack) {\n trackChangedEvents.push(e);\n if (!manifestUpdater.getIsUpdating()) {\n logger.debug('Stream - Refreshing manifest for switch track');\n manifestUpdater.refreshManifest();\n }\n } else {\n processor.selectMediaInfo(mediaInfo)\n .then(() => {\n if (mediaInfo.type === Constants.VIDEO || mediaInfo.type === Constants.AUDIO) {\n abrController.updateTopQualityIndex(mediaInfo);\n }\n processor.prepareTrackSwitch();\n });\n }\n }\n\n function prepareQualityChange(e) {\n const processor = _getProcessorByType(e.mediaType);\n\n if (processor) {\n processor.prepareQualityChange(e);\n }\n }\n\n function addInlineEvents() {\n if (eventController) {\n const events = adapter.getEventsFor(streamInfo);\n eventController.addInlineEvents(events);\n }\n }\n\n function _checkIfInitializationCompleted() {\n const ln = streamProcessors.length;\n const hasError = !!updateError.audio || !!updateError.video;\n let error = hasError ? new DashJSError(Errors.DATA_UPDATE_FAILED_ERROR_CODE, Errors.DATA_UPDATE_FAILED_ERROR_MESSAGE) : null;\n\n for (let i = 0; i < ln; i++) {\n if (streamProcessors[i].isUpdating() || isUpdating) {\n return;\n }\n }\n\n if (protectionController) {\n // Need to check if streamProcessors exists because streamProcessors\n // could be cleared in case an error is detected while initializing DRM keysystem\n protectionController.clearMediaInfoArray();\n for (let i = 0; i < ln && streamProcessors[i]; i++) {\n const type = streamProcessors[i].getType();\n const mediaInfo = streamProcessors[i].getMediaInfo();\n if (type === Constants.AUDIO ||\n type === Constants.VIDEO ||\n (type === Constants.TEXT && mediaInfo.isFragmented)) {\n let mediaInfo = streamProcessors[i].getMediaInfo();\n if (mediaInfo) {\n protectionController.initializeForMedia(mediaInfo);\n }\n }\n }\n }\n\n if (error) {\n errHandler.error(error);\n } else if (!isInitialized) {\n isInitialized = true;\n videoModel.waitForReadyState(Constants.VIDEO_ELEMENT_READY_STATES.HAVE_METADATA, () => {\n eventBus.trigger(Events.STREAM_INITIALIZED, {\n streamInfo: streamInfo\n });\n })\n }\n\n }\n\n function getMediaInfo(type) {\n let streamProcessor = null;\n\n for (let i = 0; i < streamProcessors.length; i++) {\n streamProcessor = streamProcessors[i];\n\n if (streamProcessor.getType() === type) {\n return streamProcessor.getMediaInfo();\n }\n }\n\n return null;\n }\n\n function onBufferingCompleted() {\n let processors = getProcessors();\n const ln = processors.length;\n\n if (ln === 0) {\n logger.warn('onBufferingCompleted - can\\'t trigger STREAM_BUFFERING_COMPLETED because no streamProcessor is defined');\n return;\n }\n\n // if there is at least one buffer controller that has not completed buffering yet do nothing\n for (let i = 0; i < ln; i++) {\n //if audio or video buffer is not buffering completed state, do not send STREAM_BUFFERING_COMPLETED\n if (!processors[i].isBufferingCompleted() && (processors[i].getType() === Constants.AUDIO || processors[i].getType() === Constants.VIDEO)) {\n logger.debug('onBufferingCompleted - One streamProcessor has finished but', processors[i].getType(), 'one is not buffering completed');\n return;\n }\n }\n\n logger.debug('onBufferingCompleted - trigger STREAM_BUFFERING_COMPLETED');\n hasFinishedBuffering = true;\n eventBus.trigger(Events.STREAM_BUFFERING_COMPLETED, { streamInfo: streamInfo }, { streamInfo });\n }\n\n function onDataUpdateCompleted(e) {\n updateError[e.mediaType] = e.error;\n _checkIfInitializationCompleted();\n }\n\n function onInbandEvents(e) {\n if (eventController) {\n eventController.addInbandEvents(e.events);\n }\n }\n\n function getProcessorForMediaInfo(mediaInfo) {\n if (!mediaInfo || !mediaInfo.type) {\n return null;\n }\n\n return _getProcessorByType(mediaInfo.type);\n }\n\n function _getProcessorByType(type) {\n if (!type) {\n return null;\n }\n\n let processors = getProcessors();\n\n return processors.filter(function (processor) {\n return (processor.getType() === type);\n })[0];\n }\n\n function getProcessors() {\n let arr = [];\n\n let type,\n streamProcessor;\n\n for (let i = 0; i < streamProcessors.length; i++) {\n streamProcessor = streamProcessors[i];\n type = streamProcessor.getType();\n\n if (type === Constants.AUDIO || type === Constants.VIDEO || type === Constants.TEXT) {\n arr.push(streamProcessor);\n }\n }\n\n return arr;\n }\n\n function startScheduleControllers() {\n const ln = streamProcessors.length;\n for (let i = 0; i < ln && streamProcessors[i]; i++) {\n streamProcessors[i].getScheduleController().startScheduleTimer();\n }\n }\n\n function updateData(updatedStreamInfo) {\n return new Promise((resolve) => {\n isUpdating = true;\n streamInfo = updatedStreamInfo;\n\n if (eventController) {\n addInlineEvents();\n }\n\n let promises = [];\n for (let i = 0, ln = streamProcessors.length; i < ln; i++) {\n let streamProcessor = streamProcessors[i];\n const currentMediaInfo = streamProcessor.getMediaInfo();\n promises.push(streamProcessor.updateStreamInfo(streamInfo));\n let allMediaForType = adapter.getAllMediaInfoForType(streamInfo, streamProcessor.getType());\n // Check if AdaptationSet has not been removed in MPD update\n if (allMediaForType) {\n // Remove the current mediaInfo objects before adding the updated ones\n streamProcessor.clearMediaInfoArray();\n for (let j = 0; j < allMediaForType.length; j++) {\n const mInfo = allMediaForType[j];\n streamProcessor.addMediaInfo(allMediaForType[j]);\n if (adapter.areMediaInfosEqual(currentMediaInfo, mInfo)) {\n abrController.updateTopQualityIndex(mInfo);\n promises.push(streamProcessor.selectMediaInfo(mInfo))\n }\n }\n }\n }\n\n Promise.all(promises)\n .then(() => {\n promises = [];\n\n while (trackChangedEvents.length > 0) {\n let trackChangedEvent = trackChangedEvents.pop();\n let mediaInfo = trackChangedEvent.newMediaInfo;\n let processor = getProcessorForMediaInfo(trackChangedEvent.oldMediaInfo);\n if (!processor) return;\n promises.push(processor.prepareTrackSwitch());\n processor.selectMediaInfo(mediaInfo);\n }\n\n return Promise.all(promises)\n })\n .then(() => {\n isUpdating = false;\n _checkIfInitializationCompleted();\n eventBus.trigger(Events.STREAM_UPDATED, { streamInfo: streamInfo });\n resolve();\n })\n\n })\n }\n\n function isMediaCodecCompatible(newStream, previousStream = null) {\n return compareCodecs(newStream, Constants.VIDEO, previousStream) && compareCodecs(newStream, Constants.AUDIO, previousStream);\n }\n\n function isProtectionCompatible(newStream) {\n if (!newStream) {\n return true;\n }\n return _compareProtectionConfig(Constants.VIDEO, newStream) && _compareProtectionConfig(Constants.AUDIO, newStream);\n }\n\n function _compareProtectionConfig(type, newStream) {\n const currentStreamInfo = getStreamInfo();\n const newStreamInfo = newStream.getStreamInfo();\n\n if (!newStreamInfo || !currentStreamInfo) {\n return true;\n }\n\n const newAdaptation = adapter.getAdaptationForType(newStreamInfo.index, type, newStreamInfo);\n const currentAdaptation = adapter.getAdaptationForType(currentStreamInfo.index, type, currentStreamInfo);\n\n if (!newAdaptation || !currentAdaptation) {\n // If there is no adaptation for neither the old or the new stream they're compatible\n return !newAdaptation && !currentAdaptation;\n }\n\n // If the current period is unencrypted and the upcoming one is encrypted we need to reset sourcebuffers.\n return !(!_isAdaptationDrmProtected(currentAdaptation) && _isAdaptationDrmProtected(newAdaptation));\n }\n\n function _isAdaptationDrmProtected(adaptation) {\n\n if (!adaptation) {\n // If there is no adaptation for neither the old or the new stream they're compatible\n return false;\n }\n\n // If the current period is unencrypted and the upcoming one is encrypted we need to reset sourcebuffers.\n return !!(adaptation.ContentProtection || (adaptation.Representation && adaptation.Representation.length > 0 && adaptation.Representation[0].ContentProtection));\n }\n\n function compareCodecs(newStream, type, previousStream = null) {\n if (!newStream || !newStream.hasOwnProperty('getStreamInfo')) {\n return false;\n }\n const newStreamInfo = newStream.getStreamInfo();\n const currentStreamInfo = previousStream ? previousStream.getStreamInfo() : getStreamInfo();\n\n if (!newStreamInfo || !currentStreamInfo) {\n return false;\n }\n\n const newAdaptation = adapter.getAdaptationForType(newStreamInfo.index, type, newStreamInfo);\n const currentAdaptation = adapter.getAdaptationForType(currentStreamInfo.index, type, currentStreamInfo);\n\n if (!newAdaptation || !currentAdaptation) {\n // If there is no adaptation for neither the old or the new stream they're compatible\n return !newAdaptation && !currentAdaptation;\n }\n\n const sameMimeType = newAdaptation && currentAdaptation && newAdaptation.mimeType === currentAdaptation.mimeType;\n const oldCodecs = currentAdaptation.Representation_asArray.map((representation) => {\n return representation.codecs;\n });\n\n const newCodecs = newAdaptation.Representation_asArray.map((representation) => {\n return representation.codecs;\n });\n\n const codecMatch = newCodecs.some((newCodec) => {\n return oldCodecs.indexOf(newCodec) > -1;\n });\n\n const partialCodecMatch = newCodecs.some((newCodec) => oldCodecs.some((oldCodec) => capabilities.codecRootCompatibleWithCodec(oldCodec, newCodec)));\n return codecMatch || (partialCodecMatch && sameMimeType);\n }\n\n function setPreloaded(value) {\n preloaded = value;\n }\n\n function getPreloaded() {\n return preloaded;\n }\n\n function getHasFinishedBuffering() {\n return hasFinishedBuffering;\n }\n\n function getAdapter() {\n return adapter;\n }\n\n instance = {\n initialize,\n getStreamId,\n activate,\n deactivate,\n getIsActive,\n getDuration,\n getStartTime,\n getId,\n getStreamInfo,\n getHasAudioTrack,\n getHasVideoTrack,\n startPreloading,\n getThumbnailController,\n getBitrateListFor,\n updateData,\n reset,\n getProcessors,\n setMediaSource,\n isMediaCodecCompatible,\n isProtectionCompatible,\n getPreloaded,\n getIsEndedEventSignaled,\n setIsEndedEventSignaled,\n getAdapter,\n getHasFinishedBuffering,\n setPreloaded,\n startScheduleControllers,\n prepareTrackChange,\n prepareQualityChange\n };\n\n setup();\n return instance;\n}\n\nStream.__dashjs_factory_name = 'Stream';\nexport default FactoryMaker.getClassFactory(Stream);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport EventBus from '../core/EventBus';\nimport Events from '../core/events/Events';\nimport MediaPlayerEvents from '../streaming/MediaPlayerEvents';\nimport FactoryMaker from '../core/FactoryMaker';\nimport Debug from '../core/Debug';\nimport Errors from '../core/errors/Errors';\nimport DashConstants from '../dash/constants/DashConstants';\nimport URLUtils from './utils/URLUtils';\n\nfunction ManifestUpdater() {\n\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n const urlUtils = URLUtils(context).getInstance();\n\n let instance,\n logger,\n refreshDelay,\n refreshTimer,\n isPaused,\n isStopped,\n isUpdating,\n manifestLoader,\n manifestModel,\n adapter,\n errHandler,\n settings;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n }\n\n function setConfig(config) {\n if (!config) return;\n\n if (config.manifestModel) {\n manifestModel = config.manifestModel;\n }\n if (config.adapter) {\n adapter = config.adapter;\n }\n if (config.manifestLoader) {\n manifestLoader = config.manifestLoader;\n }\n if (config.errHandler) {\n errHandler = config.errHandler;\n }\n if (config.settings) {\n settings = config.settings;\n }\n }\n\n function initialize() {\n resetInitialSettings();\n\n eventBus.on(Events.STREAMS_COMPOSED, onStreamsComposed, this);\n eventBus.on(MediaPlayerEvents.PLAYBACK_STARTED, onPlaybackStarted, this);\n eventBus.on(MediaPlayerEvents.PLAYBACK_PAUSED, onPlaybackPaused, this);\n eventBus.on(Events.INTERNAL_MANIFEST_LOADED, onManifestLoaded, this);\n }\n\n function setManifest(manifest) {\n update(manifest);\n }\n\n function resetInitialSettings() {\n refreshDelay = NaN;\n isUpdating = false;\n isPaused = true;\n isStopped = false;\n stopManifestRefreshTimer();\n }\n\n function reset() {\n\n eventBus.off(MediaPlayerEvents.PLAYBACK_STARTED, onPlaybackStarted, this);\n eventBus.off(MediaPlayerEvents.PLAYBACK_PAUSED, onPlaybackPaused, this);\n eventBus.off(Events.STREAMS_COMPOSED, onStreamsComposed, this);\n eventBus.off(Events.INTERNAL_MANIFEST_LOADED, onManifestLoaded, this);\n\n resetInitialSettings();\n }\n\n function stopManifestRefreshTimer() {\n if (refreshTimer !== null) {\n clearTimeout(refreshTimer);\n refreshTimer = null;\n }\n }\n\n function startManifestRefreshTimer(delay) {\n stopManifestRefreshTimer();\n\n if (isStopped) {\n return;\n }\n\n if (isNaN(delay) && !isNaN(refreshDelay)) {\n delay = refreshDelay * 1000;\n }\n\n if (!isNaN(delay)) {\n logger.debug('Refresh manifest in ' + delay + ' milliseconds.');\n refreshTimer = setTimeout(onRefreshTimer, delay);\n }\n }\n\n function refreshManifest(ignorePatch = false) {\n isUpdating = true;\n const manifest = manifestModel.getValue();\n\n // default to the original url in the manifest\n let url = manifest.url;\n\n // Check for PatchLocation and Location alternatives\n const patchLocation = adapter.getPatchLocation(manifest);\n const location = adapter.getLocation(manifest);\n if (patchLocation && !ignorePatch) {\n url = patchLocation;\n } else if (location) {\n url = location;\n }\n\n // if one of the alternatives was relative, convert to absolute\n if (urlUtils.isRelative(url)) {\n url = urlUtils.resolve(url, manifest.url);\n }\n\n manifestLoader.load(url);\n }\n\n function update(manifest) {\n if (!manifest) {\n // successful update with no content implies existing manifest remains valid\n manifest = manifestModel.getValue();\n\n // override load time to avoid invalid latency tracking and ensure update cadence\n manifest.loadedTime = new Date();\n } else if (adapter.getIsPatch(manifest)) {\n // with patches the in-memory manifest is our base\n let patch = manifest;\n manifest = manifestModel.getValue();\n\n // check for patch validity\n let isPatchValid = adapter.isPatchValid(manifest, patch);\n let patchSuccessful = isPatchValid;\n\n if (isPatchValid) {\n // grab publish time before update\n let publishTime = adapter.getPublishTime(manifest);\n\n // apply validated patch to manifest\n patchSuccessful = adapter.applyPatchToManifest(manifest, patch);\n\n // get the updated publish time\n let updatedPublishTime = adapter.getPublishTime(manifest);\n\n // ensure the patch properly updated the in-memory publish time\n patchSuccessful = publishTime.getTime() != updatedPublishTime.getTime();\n }\n\n // if the patch failed to apply, force a full manifest refresh\n if (!patchSuccessful) {\n logger.debug('Patch provided is invalid, performing full manifest refresh');\n refreshManifest(true);\n return;\n }\n\n // override load time to avoid invalid latency tracking and ensure update cadence\n manifest.loadedTime = new Date();\n }\n\n // See DASH-IF IOP v4.3 section 4.6.4 \"Transition Phase between Live and On-Demand\"\n // Stop manifest update, ignore static manifest and signal end of dynamic stream to detect end of stream\n if (manifestModel.getValue() && manifestModel.getValue().type === DashConstants.DYNAMIC && manifest.type === DashConstants.STATIC) {\n eventBus.trigger(Events.DYNAMIC_TO_STATIC);\n isUpdating = false;\n isStopped = true;\n return;\n }\n\n manifestModel.setValue(manifest);\n\n const date = new Date();\n const latencyOfLastUpdate = (date.getTime() - manifest.loadedTime.getTime()) / 1000;\n refreshDelay = adapter.getManifestUpdatePeriod(manifest, latencyOfLastUpdate);\n // setTimeout uses a 32 bit number to store the delay. Any number greater than it\n // will cause event associated with setTimeout to trigger immediately\n if (refreshDelay * 1000 > 0x7FFFFFFF) {\n refreshDelay = 0x7FFFFFFF / 1000;\n }\n eventBus.trigger(Events.MANIFEST_UPDATED, { manifest: manifest });\n logger.info('Manifest has been refreshed at ' + date + '[' + date.getTime() / 1000 + '] ');\n\n if (!isPaused) {\n startManifestRefreshTimer();\n }\n }\n\n function onRefreshTimer() {\n if (isPaused) {\n return;\n }\n if (isUpdating) {\n startManifestRefreshTimer(settings.get().streaming.manifestUpdateRetryInterval);\n return;\n }\n refreshManifest();\n }\n\n function onManifestLoaded(e) {\n if (!e.error) {\n update(e.manifest);\n } else if (e.error.code === Errors.MANIFEST_LOADER_PARSING_FAILURE_ERROR_CODE) {\n errHandler.error(e.error);\n }\n }\n\n function onPlaybackStarted (/*e*/) {\n isPaused = false;\n startManifestRefreshTimer();\n }\n\n function onPlaybackPaused(/*e*/) {\n isPaused = !settings.get().streaming.scheduling.scheduleWhilePaused;\n\n if (isPaused) {\n stopManifestRefreshTimer();\n }\n }\n\n function onStreamsComposed(/*e*/) {\n // When streams are ready we can consider manifest update completed. Resolve the update promise.\n isUpdating = false;\n }\n\n function getIsUpdating() {\n return isUpdating;\n }\n\n instance = {\n initialize: initialize,\n setManifest: setManifest,\n refreshManifest: refreshManifest,\n getIsUpdating: getIsUpdating,\n setConfig: setConfig,\n reset: reset\n };\n\n setup();\n return instance;\n}\nManifestUpdater.__dashjs_factory_name = 'ManifestUpdater';\nexport default FactoryMaker.getClassFactory(ManifestUpdater);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport DashJSError from './../vo/DashJSError';\nimport {HTTPRequest} from '../vo/metrics/HTTPRequest';\nimport EventBus from './../../core/EventBus';\nimport Events from './../../core/events/Events';\nimport Errors from './../../core/errors/Errors';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Debug from '../../core/Debug';\nimport URLUtils from '../utils/URLUtils';\n\nconst HTTP_TIMEOUT_MS = 5000;\nconst DEFAULT_MAXIMUM_ALLOWED_DRIFT = 100;\nconst DEFAULT_TIME_BETWEEN_SYNC_ATTEMPTS_ADJUSTMENT_FACTOR = 2;\nconst DEFAULT_BACKGROUND_ATTEMPTS = 2;\nconst DEFAULT_TIME_BETWEEN_SYNC_ATTEMPTS = 30;\nconst DEFAULT_MINIMUM_TIME_BETWEEN_BACKGROUND_SYNC_ATTEMPTS = 30;\nconst DEFAULT_MAXIMUM_TIME_BETWEEN_SYNC = 600;\nconst DEFAULT_MINIMUM_TIME_BETWEEN_SYNC = 2;\n\nfunction TimeSyncController() {\n\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n const urlUtils = URLUtils(context).getInstance();\n\n let instance,\n logger,\n isSynchronizing,\n isBackgroundSynchronizing,\n settings,\n handlers,\n dashMetrics,\n backgroundSyncTimeOffsets,\n timingSources,\n timeOfLastSync,\n timeOfLastBackgroundSync,\n lastOffset,\n lastTimingSource,\n internalTimeBetweenSyncAttempts,\n errHandler,\n baseURLController;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n\n eventBus.on(Events.ATTEMPT_BACKGROUND_SYNC, _onAttemptBackgroundSync, instance);\n }\n\n function setConfig(config) {\n if (!config) return;\n\n if (config.dashMetrics) {\n dashMetrics = config.dashMetrics;\n }\n\n if (config.baseURLController) {\n baseURLController = config.baseURLController;\n }\n\n if (config.errHandler) {\n errHandler = config.errHandler;\n }\n\n if (config.settings) {\n settings = config.settings;\n }\n }\n\n function _resetInitialSettings() {\n backgroundSyncTimeOffsets = [];\n timingSources = [];\n timeOfLastSync = null;\n timeOfLastBackgroundSync = null;\n lastTimingSource = null;\n lastOffset = NaN;\n isSynchronizing = false;\n isBackgroundSynchronizing = false;\n internalTimeBetweenSyncAttempts = settings.get().streaming.utcSynchronization.timeBetweenSyncAttempts;\n }\n\n /**\n * Register the timing handler depending on the schemeIdUris. This method is called once when the StreamController is initialized\n */\n function initialize() {\n _resetInitialSettings();\n\n // a list of known schemeIdUris and a method to call with @value\n handlers = {\n 'urn:mpeg:dash:utc:http-head:2014': _httpHeadHandler,\n 'urn:mpeg:dash:utc:http-xsdate:2014': _httpHandler.bind(null, _xsdatetimeDecoder),\n 'urn:mpeg:dash:utc:http-iso:2014': _httpHandler.bind(null, _iso8601Decoder),\n 'urn:mpeg:dash:utc:direct:2014': _directHandler,\n\n // some specs referencing early ISO23009-1 drafts incorrectly use\n // 2012 in the URI, rather than 2014. support these for now.\n 'urn:mpeg:dash:utc:http-head:2012': _httpHeadHandler,\n 'urn:mpeg:dash:utc:http-xsdate:2012': _httpHandler.bind(null, _xsdatetimeDecoder),\n 'urn:mpeg:dash:utc:http-iso:2012': _httpHandler.bind(null, _iso8601Decoder),\n 'urn:mpeg:dash:utc:direct:2012': _directHandler,\n\n // it isn't clear how the data returned would be formatted, and\n // no public examples available so http-ntp not supported for now.\n // presumably you would do an arraybuffer type xhr and decode the\n // binary data returned but I would want to see a sample first.\n 'urn:mpeg:dash:utc:http-ntp:2014': _notSupportedHandler,\n\n // not clear how this would be supported in javascript (in browser)\n 'urn:mpeg:dash:utc:ntp:2014': _notSupportedHandler,\n 'urn:mpeg:dash:utc:sntp:2014': _notSupportedHandler\n };\n\n }\n\n /**\n * Sync against a timing source. T\n * @param {array} tSources\n * @param {boolean} isDynamic\n */\n function attemptSync(tSources, isDynamic) {\n\n timingSources = tSources;\n\n // Stop if we are already synchronizing\n if (isSynchronizing) {\n return;\n }\n\n // No synchronization required we can signal the completion immediately\n if (!_shouldPerformSynchronization(isDynamic)) {\n eventBus.trigger(Events.TIME_SYNCHRONIZATION_COMPLETED);\n return;\n }\n\n isSynchronizing = true;\n _attemptRecursiveSync();\n }\n\n /**\n * Does a synchronization in the background in case the last offset should be verified or a 404 occurs\n */\n function _onAttemptBackgroundSync() {\n if (!settings.get().streaming.utcSynchronization.enabled || isSynchronizing || isBackgroundSynchronizing || !lastTimingSource || !lastTimingSource.value || !lastTimingSource.schemeIdUri || isNaN(lastOffset) || isNaN(settings.get().streaming.utcSynchronization.backgroundAttempts)) {\n return;\n }\n\n if (timeOfLastBackgroundSync && ((Date.now() - timeOfLastBackgroundSync) / 1000) < DEFAULT_MINIMUM_TIME_BETWEEN_BACKGROUND_SYNC_ATTEMPTS) {\n return;\n }\n\n backgroundSyncTimeOffsets = [];\n isBackgroundSynchronizing = true;\n const backgroundAttempts = !isNaN(settings.get().streaming.utcSynchronization.backgroundAttempts) ? settings.get().streaming.utcSynchronization.backgroundAttempts : DEFAULT_BACKGROUND_ATTEMPTS;\n _attemptBackgroundSync(backgroundAttempts);\n }\n\n /**\n * Perform a defined number of background attempts\n * @param {number} attempts\n * @private\n */\n function _attemptBackgroundSync(attempts) {\n try {\n if (attempts <= 0) {\n _completeBackgroundTimeSyncSequence();\n return;\n }\n\n const deviceTimeBeforeSync = Date.now();\n handlers[lastTimingSource.schemeIdUri](\n lastTimingSource.value,\n function (serverTime) {\n // the timing source returned something useful\n const deviceTimeAfterSync = Date.now();\n const offset = _calculateOffset(deviceTimeBeforeSync, deviceTimeAfterSync, serverTime);\n\n backgroundSyncTimeOffsets.push(offset);\n _attemptBackgroundSync(attempts - 1);\n },\n function () {\n _completeBackgroundTimeSyncSequence();\n }\n );\n } catch (e) {\n _completeBackgroundTimeSyncSequence();\n }\n }\n\n /**\n * Sync against a timing source. This method is called recursively if the time sync for the first entry in timingSources fails.\n * @param {number} sourceIndex\n */\n function _attemptRecursiveSync(sourceIndex = null) {\n // if called with no sourceIndex, use zero (highest priority)\n let index = sourceIndex || 0;\n\n // the sources should be ordered in priority from the manifest.\n // try each in turn, from the top, until either something\n // sensible happens, or we run out of sources to try.\n if (!timingSources || timingSources.length === 0 || index >= timingSources.length) {\n _onComplete();\n return;\n }\n let source = timingSources[index];\n\n if (source) {\n // check if there is a handler for this @schemeIdUri\n if (handlers.hasOwnProperty(source.schemeIdUri)) {\n // if so, call it with its @value\n const deviceTimeBeforeSync = new Date().getTime();\n handlers[source.schemeIdUri](\n source.value,\n function (serverTime) {\n // the timing source returned something useful\n const deviceTimeAfterSync = new Date().getTime();\n const offset = _calculateOffset(deviceTimeBeforeSync, deviceTimeAfterSync, serverTime);\n lastTimingSource = source;\n\n _onComplete(offset);\n },\n function () {\n // the timing source was probably uncontactable\n // or returned something we can't use - try again\n // with the remaining sources\n _attemptRecursiveSync(index + 1);\n }\n );\n } else {\n // an unknown schemeIdUri must have been found\n // try again with the remaining sources\n _attemptRecursiveSync(index + 1);\n }\n } else {\n // no valid time source could be found, just use device time\n _onComplete();\n }\n\n }\n\n /**\n * Calculate the offset between client and server. Account for the roundtrip time\n * @param {number} deviceTimeBeforeSync\n * @param {number} deviceTimeAfterSync\n * @param {number} serverTime\n * @return {number}\n * @private\n */\n function _calculateOffset(deviceTimeBeforeSync, deviceTimeAfterSync, serverTime) {\n const deviceReferenceTime = deviceTimeAfterSync - ((deviceTimeAfterSync - deviceTimeBeforeSync) / 2);\n\n return serverTime - deviceReferenceTime;\n }\n\n /**\n * Checks if a synchronization is required\n * @param {boolean} isDynamic\n * @return {boolean}\n * @private\n */\n function _shouldPerformSynchronization(isDynamic) {\n try {\n if (!isDynamic || !settings.get().streaming.utcSynchronization.enabled) {\n return false;\n }\n const timeBetweenSyncAttempts = !isNaN(internalTimeBetweenSyncAttempts) ? internalTimeBetweenSyncAttempts : DEFAULT_TIME_BETWEEN_SYNC_ATTEMPTS;\n\n if (!timeOfLastSync || !timeBetweenSyncAttempts || isNaN(timeBetweenSyncAttempts)) {\n return true;\n }\n\n return ((Date.now() - timeOfLastSync) / 1000) >= timeBetweenSyncAttempts;\n } catch (e) {\n return true;\n }\n }\n\n /**\n * Callback after sync has been completed\n * @param {number} offset\n * @private\n */\n function _onComplete(offset = NaN) {\n let failed = isNaN(offset);\n if (failed && settings.get().streaming.utcSynchronization.useManifestDateHeaderTimeSource) {\n //Before falling back to binary search , check if date header exists on MPD. if so, use for a time source.\n _checkForDateHeader();\n } else {\n _completeTimeSyncSequence(failed, offset);\n }\n }\n\n /**\n * Takes xsdatetime and returns milliseconds since UNIX epoch. May not be necessary as xsdatetime is very similar to ISO 8601 which is natively understood by javascript Date parser\n * @param {string} xsdatetimeStr\n * @return {number}\n * @private\n */\n function _alternateXsdatetimeDecoder(xsdatetimeStr) {\n // taken from DashParser - should probably refactor both uses\n const SECONDS_IN_MIN = 60;\n const MINUTES_IN_HOUR = 60;\n const MILLISECONDS_IN_SECONDS = 1000;\n let datetimeRegex = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2})(?::([0-9]*)(\\.[0-9]*)?)?(?:([+\\-])([0-9]{2})([0-9]{2}))?/;\n\n let utcDate,\n timezoneOffset;\n\n let match = datetimeRegex.exec(xsdatetimeStr);\n\n // If the string does not contain a timezone offset different browsers can interpret it either\n // as UTC or as a local time so we have to parse the string manually to normalize the given date value for\n // all browsers\n utcDate = Date.UTC(\n parseInt(match[1], 10),\n parseInt(match[2], 10) - 1, // months start from zero\n parseInt(match[3], 10),\n parseInt(match[4], 10),\n parseInt(match[5], 10),\n (match[6] && (parseInt(match[6], 10) || 0)),\n (match[7] && parseFloat(match[7]) * MILLISECONDS_IN_SECONDS) || 0\n );\n // If the date has timezone offset take it into account as well\n if (match[9] && match[10]) {\n timezoneOffset = parseInt(match[9], 10) * MINUTES_IN_HOUR + parseInt(match[10], 10);\n utcDate += (match[8] === '+' ? -1 : +1) * timezoneOffset * SECONDS_IN_MIN * MILLISECONDS_IN_SECONDS;\n }\n\n return new Date(utcDate).getTime();\n }\n\n\n /**\n * Try to use the built in parser, since xsdate is a constrained ISO8601 which is supported natively by Date.parse. if that fails, try a regex-based version used elsewhere in this application.\n * @param {string} xsdatetimeStr\n * @return {number}\n */\n function _xsdatetimeDecoder(xsdatetimeStr) {\n let parsedDate = Date.parse(xsdatetimeStr);\n\n if (isNaN(parsedDate)) {\n parsedDate = _alternateXsdatetimeDecoder(xsdatetimeStr);\n }\n\n return parsedDate;\n }\n\n /**\n * Takes ISO 8601 timestamp and returns milliseconds since UNIX epoch\n * @param {string} isoStr\n * @return {number}\n */\n function _iso8601Decoder(isoStr) {\n return Date.parse(isoStr);\n }\n\n /**\n * Takes RFC 1123 timestamp (which is same as ISO8601) and returns milliseconds since UNIX epoch\n * @param {string} dateStr\n * @return {number}\n */\n function _rfc1123Decoder(dateStr) {\n return Date.parse(dateStr);\n }\n\n /**\n * Handler for unsupported scheme ids.\n * @param {string} url\n * @param {function} onSuccessCB\n * @param {function} onFailureCB\n * @private\n */\n function _notSupportedHandler(url, onSuccessCB, onFailureCB) {\n onFailureCB();\n }\n\n /**\n * Direct handler\n * @param {string} xsdatetimeStr\n * @param {function} onSuccessCB\n * @param {function} onFailureCB\n */\n function _directHandler(xsdatetimeStr, onSuccessCB, onFailureCB) {\n let time = _xsdatetimeDecoder(xsdatetimeStr);\n\n if (!isNaN(time)) {\n onSuccessCB(time);\n return;\n }\n\n onFailureCB();\n }\n\n /**\n * Generic http handler\n * @param {function} decoder\n * @param {string} url\n * @param {function} onSuccessCB\n * @param {function} onFailureCB\n * @param {boolean} isHeadRequest\n * @private\n */\n function _httpHandler(decoder, url, onSuccessCB, onFailureCB, isHeadRequest) {\n let oncomplete,\n onload;\n let complete = false;\n let req = new XMLHttpRequest();\n\n let verb = isHeadRequest ? HTTPRequest.HEAD : HTTPRequest.GET;\n let urls = url.match(/\\S+/g);\n\n // according to ISO 23009-1, url could be a white-space\n // separated list of URLs. just handle one at a time.\n url = urls.shift();\n\n oncomplete = function () {\n if (complete) {\n return;\n }\n\n // we only want to pass through here once per xhr,\n // regardless of whether the load was successful.\n complete = true;\n\n // if there are more urls to try, call self.\n if (urls.length) {\n _httpHandler(decoder, urls.join(' '), onSuccessCB, onFailureCB, isHeadRequest);\n } else {\n onFailureCB();\n }\n };\n\n onload = function () {\n let time,\n result;\n\n if (req.status === 200) {\n time = isHeadRequest ?\n req.getResponseHeader('Date') :\n req.response;\n\n result = decoder(time);\n\n // decoder returns NaN if non-standard input\n if (!isNaN(result)) {\n onSuccessCB(result);\n complete = true;\n }\n }\n };\n\n if (urlUtils.isRelative(url)) {\n // passing no path to resolve will return just MPD BaseURL/baseUri\n const baseUrl = baseURLController.resolve();\n if (baseUrl) {\n url = urlUtils.resolve(url, baseUrl.url);\n }\n }\n\n req.open(verb, url);\n req.timeout = HTTP_TIMEOUT_MS || 0;\n req.onload = onload;\n req.onloadend = oncomplete;\n req.send();\n }\n\n /**\n * Handler for http-head schemeIdUri\n * @param {string} url\n * @param {function} onSuccessCB\n * @param {function} onFailureCB\n * @private\n */\n function _httpHeadHandler(url, onSuccessCB, onFailureCB) {\n _httpHandler(_rfc1123Decoder, url, onSuccessCB, onFailureCB, true);\n }\n\n /**\n * Checks if a date header is present in the MPD response and calculates the offset based on the header\n * @private\n */\n function _checkForDateHeader() {\n let dateHeaderValue = dashMetrics.getLatestMPDRequestHeaderValueByID('Date');\n let dateHeaderTime = dateHeaderValue !== null ? new Date(dateHeaderValue).getTime() : Number.NaN;\n\n if (!isNaN(dateHeaderTime)) {\n const offsetToDeviceTimeMs = dateHeaderTime - Date.now();\n _completeTimeSyncSequence(false, offsetToDeviceTimeMs);\n } else {\n _completeTimeSyncSequence(true);\n }\n }\n\n /**\n * Triggers the event to signal that the time synchronization was completed\n * @param {boolean} failed\n * @param {number} offset\n * @private\n */\n function _completeTimeSyncSequence(failed, offset) {\n\n // Adjust the time of the next sync based on the drift between current offset and last offset\n if (!isNaN(lastOffset) && !isNaN(offset) && !failed) {\n _adjustTimeBetweenSyncAttempts(offset);\n }\n\n // Update the internal data\n if (!failed && !isNaN(offset)) {\n timeOfLastSync = Date.now();\n isSynchronizing = false;\n\n // if this is the first sync we are doing perform background syncs as well to confirm current offset\n const shouldAttemptBackgroundSync = isNaN(lastOffset);\n lastOffset = offset;\n if (shouldAttemptBackgroundSync) {\n _onAttemptBackgroundSync();\n }\n logger.debug(`Completed UTC sync. Setting client - server offset to ${offset}`);\n }\n\n if (failed) {\n lastTimingSource = null;\n isSynchronizing = false;\n errHandler.error(new DashJSError(Errors.TIME_SYNC_FAILED_ERROR_CODE, Errors.TIME_SYNC_FAILED_ERROR_MESSAGE));\n }\n\n // Notify other classes\n eventBus.trigger(Events.UPDATE_TIME_SYNC_OFFSET, {\n offset: offset,\n });\n eventBus.trigger(Events.TIME_SYNCHRONIZATION_COMPLETED);\n }\n\n function _adjustTimeBetweenSyncAttempts(offset) {\n try {\n const isOffsetDriftWithinThreshold = _isOffsetDriftWithinThreshold(offset);\n const timeBetweenSyncAttempts = !isNaN(internalTimeBetweenSyncAttempts) ? internalTimeBetweenSyncAttempts : DEFAULT_TIME_BETWEEN_SYNC_ATTEMPTS;\n const timeBetweenSyncAttemptsAdjustmentFactor = !isNaN(settings.get().streaming.utcSynchronization.timeBetweenSyncAttemptsAdjustmentFactor) ? settings.get().streaming.utcSynchronization.timeBetweenSyncAttemptsAdjustmentFactor : DEFAULT_TIME_BETWEEN_SYNC_ATTEMPTS_ADJUSTMENT_FACTOR;\n const maximumTimeBetweenSyncAttempts = !isNaN(settings.get().streaming.utcSynchronization.maximumTimeBetweenSyncAttempts) ? settings.get().streaming.utcSynchronization.maximumTimeBetweenSyncAttempts : DEFAULT_MAXIMUM_TIME_BETWEEN_SYNC;\n const minimumTimeBetweenSyncAttempts = !isNaN(settings.get().streaming.utcSynchronization.minimumTimeBetweenSyncAttempts) ? settings.get().streaming.utcSynchronization.minimumTimeBetweenSyncAttempts : DEFAULT_MINIMUM_TIME_BETWEEN_SYNC;\n let adjustedTimeBetweenSyncAttempts;\n\n if (isOffsetDriftWithinThreshold) {\n // The drift between the current offset and the last offset is within the allowed threshold. Increase sync time\n adjustedTimeBetweenSyncAttempts = Math.min(timeBetweenSyncAttempts * timeBetweenSyncAttemptsAdjustmentFactor, maximumTimeBetweenSyncAttempts);\n logger.debug(`Increasing timeBetweenSyncAttempts to ${adjustedTimeBetweenSyncAttempts}`);\n } else {\n // Drift between the current offset and the last offset is not within the allowed threshold. Decrease sync time\n adjustedTimeBetweenSyncAttempts = Math.max(timeBetweenSyncAttempts / timeBetweenSyncAttemptsAdjustmentFactor, minimumTimeBetweenSyncAttempts);\n logger.debug(`Decreasing timeBetweenSyncAttempts to ${adjustedTimeBetweenSyncAttempts}`);\n }\n\n internalTimeBetweenSyncAttempts = adjustedTimeBetweenSyncAttempts;\n } catch (e) {\n\n }\n }\n\n /**\n * Callback after all background syncs have been completed.\n * @private\n */\n function _completeBackgroundTimeSyncSequence() {\n if (!backgroundSyncTimeOffsets || backgroundSyncTimeOffsets.length === 0) {\n return;\n }\n\n const averageOffset = backgroundSyncTimeOffsets.reduce((acc, curr) => {\n return acc + curr;\n }, 0) / backgroundSyncTimeOffsets.length;\n\n if (!_isOffsetDriftWithinThreshold(averageOffset)) {\n logger.debug(`Completed background UTC sync. Setting client - server offset to ${averageOffset}`);\n lastOffset = averageOffset;\n eventBus.trigger(Events.UPDATE_TIME_SYNC_OFFSET, {\n offset: lastOffset\n });\n } else {\n logger.debug(`Completed background UTC sync. Offset is within allowed threshold and is not adjusted.`);\n }\n\n isBackgroundSynchronizing = false;\n timeOfLastBackgroundSync = Date.now();\n }\n\n function _isOffsetDriftWithinThreshold(offset) {\n try {\n if (isNaN(lastOffset)) {\n return true;\n }\n\n const maxAllowedDrift = settings.get().streaming.utcSynchronization.maximumAllowedDrift && !isNaN(settings.get().streaming.utcSynchronization.maximumAllowedDrift) ? settings.get().streaming.utcSynchronization.maximumAllowedDrift : DEFAULT_MAXIMUM_ALLOWED_DRIFT;\n const lowerBound = lastOffset - maxAllowedDrift;\n const upperBound = lastOffset + maxAllowedDrift;\n\n return offset >= lowerBound && offset <= upperBound;\n } catch (e) {\n return true;\n }\n }\n\n function reset() {\n _resetInitialSettings();\n\n eventBus.off(Events.ATTEMPT_BACKGROUND_SYNC, _onAttemptBackgroundSync, instance);\n }\n\n instance = {\n initialize,\n attemptSync,\n setConfig,\n reset\n };\n\n setup();\n\n return instance;\n}\n\nTimeSyncController.__dashjs_factory_name = 'TimeSyncController';\nconst factory = FactoryMaker.getSingletonFactory(TimeSyncController);\nfactory.HTTP_TIMEOUT_MS = HTTP_TIMEOUT_MS;\nFactoryMaker.updateSingletonFactory(TimeSyncController.__dashjs_factory_name, factory);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Debug from '../../core/Debug';\n\nfunction MediaSourceController() {\n\n let instance,\n mediaSource,\n logger;\n\n const context = this.context;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n }\n\n function createMediaSource() {\n\n let hasWebKit = ('WebKitMediaSource' in window);\n let hasMediaSource = ('MediaSource' in window);\n\n if (hasMediaSource) {\n mediaSource = new MediaSource();\n } else if (hasWebKit) {\n mediaSource = new WebKitMediaSource();\n }\n\n return mediaSource;\n }\n\n function attachMediaSource(videoModel) {\n\n let objectURL = window.URL.createObjectURL(mediaSource);\n\n videoModel.setSource(objectURL);\n\n return objectURL;\n }\n\n function detachMediaSource(videoModel) {\n videoModel.setSource(null);\n }\n\n function setDuration(value) {\n if (!mediaSource || mediaSource.readyState !== 'open') return;\n if (value === null && isNaN(value)) return;\n if (mediaSource.duration === value) return;\n\n if (!isBufferUpdating(mediaSource)) {\n logger.info('Set MediaSource duration:' + value);\n mediaSource.duration = value;\n } else {\n setTimeout(setDuration.bind(null, value), 50);\n }\n }\n\n function setSeekable(start, end) {\n if (mediaSource && typeof mediaSource.setLiveSeekableRange === 'function' && typeof mediaSource.clearLiveSeekableRange === 'function' &&\n mediaSource.readyState === 'open' && start >= 0 && start < end) {\n mediaSource.clearLiveSeekableRange();\n mediaSource.setLiveSeekableRange(start, end);\n }\n }\n\n function signalEndOfStream(source) {\n if (!source || source.readyState !== 'open') {\n return;\n }\n\n let buffers = source.sourceBuffers;\n\n for (let i = 0; i < buffers.length; i++) {\n if (buffers[i].updating) {\n return;\n }\n if (buffers[i].buffered.length === 0) {\n return;\n }\n }\n logger.info('call to mediaSource endOfStream');\n source.endOfStream();\n }\n\n function isBufferUpdating(source) {\n let buffers = source.sourceBuffers;\n for (let i = 0; i < buffers.length; i++) {\n if (buffers[i].updating) {\n return true;\n }\n }\n return false;\n }\n\n instance = {\n createMediaSource,\n attachMediaSource,\n detachMediaSource,\n setDuration,\n setSeekable,\n signalEndOfStream\n };\n\n setup();\n\n return instance;\n}\n\nMediaSourceController.__dashjs_factory_name = 'MediaSourceController';\nexport default FactoryMaker.getSingletonFactory(MediaSourceController);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Debug from '../../core/Debug';\nimport EventBus from '../../core/EventBus';\nimport MediaPlayerEvents from '../../streaming/MediaPlayerEvents';\nimport XHRLoader from '../net/XHRLoader';\n\nfunction EventController() {\n\n const MPD_RELOAD_SCHEME = 'urn:mpeg:dash:event:2012';\n const MPD_RELOAD_VALUE = 1;\n\n const MPD_CALLBACK_SCHEME = 'urn:mpeg:dash:event:callback:2015';\n const MPD_CALLBACK_VALUE = 1;\n\n const REMAINING_EVENTS_THRESHOLD = 300;\n\n const EVENT_HANDLED_STATES = {\n DISCARDED: 'discarded',\n UPDATED: 'updated',\n ADDED: 'added'\n };\n\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n\n let instance,\n logger,\n inlineEvents, // Holds all Inline Events not triggered yet\n inbandEvents, // Holds all Inband Events not triggered yet\n eventInterval, // variable holding the setInterval\n lastEventTimerCall,\n manifestUpdater,\n playbackController,\n settings,\n eventHandlingInProgress,\n isStarted;\n\n /**\n * Internal setup when class is instanced\n */\n function _setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n _resetInitialSettings();\n }\n\n /**\n * Checks if the provded configuration is valid\n */\n function checkConfig() {\n if (!manifestUpdater || !playbackController) {\n throw new Error('setConfig function has to be called previously');\n }\n }\n\n /**\n * Reset to initial settings\n */\n function _resetInitialSettings() {\n isStarted = false;\n inlineEvents = {}; // Format inlineEvents[schemeIdUri]\n inbandEvents = {}; // Format inlineEvents[schemeIdUri]\n eventInterval = null;\n eventHandlingInProgress = false;\n lastEventTimerCall = Date.now() / 1000;\n }\n\n /**\n * Stops the EventController by clearing the event interval\n */\n function _stop() {\n try {\n if (eventInterval !== null && isStarted) {\n clearInterval(eventInterval);\n eventInterval = null;\n isStarted = false;\n _onStopEventController();\n }\n } catch (e) {\n throw e;\n }\n }\n\n /**\n * Starts the interval function of the EventController\n */\n function start() {\n try {\n checkConfig();\n logger.debug('Start Event Controller');\n const refreshDelay = settings.get().streaming.eventControllerRefreshDelay;\n if (!isStarted && !isNaN(refreshDelay)) {\n isStarted = true;\n eventInterval = setInterval(_onEventTimer, refreshDelay);\n }\n } catch (e) {\n throw e;\n }\n }\n\n /**\n * Add MPD events to the list of events.\n * Events that are not in the MPD anymore but not triggered yet will still be deleted.\n * Existing events might get updated.\n * @param {Array.<Object>} values\n */\n function addInlineEvents(values) {\n try {\n checkConfig();\n\n if (values) {\n for (let i = 0; i < values.length; i++) {\n let event = values[i];\n let result = _addOrUpdateEvent(event, inlineEvents, true);\n\n if (result === EVENT_HANDLED_STATES.ADDED) {\n logger.debug(`Added inline event with id ${event.id}`);\n // If we see the event for the first time we trigger it in onReceive mode\n _startEvent(event, values, MediaPlayerEvents.EVENT_MODE_ON_RECEIVE);\n } else if (result === EVENT_HANDLED_STATES.UPDATED) {\n logger.debug(`Updated inline event with id ${event.id}`);\n }\n }\n }\n } catch (e) {\n throw e;\n }\n }\n\n /**\n * Add EMSG events to the list of events\n * Messages with the same id within the scope of the same scheme_id_uri and value pair are equivalent , i.e. processing of any one event message box with the same id is sufficient.\n * @param {Array.<Object>} values\n */\n function addInbandEvents(values) {\n try {\n checkConfig();\n\n for (let i = 0; i < values.length; i++) {\n let event = values[i];\n let result = _addOrUpdateEvent(event, inbandEvents, false);\n\n if (result === EVENT_HANDLED_STATES.ADDED) {\n if (event.eventStream.schemeIdUri === MPD_RELOAD_SCHEME && inbandEvents[event.id] === undefined) {\n _handleManifestReloadEvent(event);\n }\n logger.debug('Added inband event with id ' + event.id);\n _startEvent(event, values, MediaPlayerEvents.EVENT_MODE_ON_RECEIVE);\n } else {\n logger.debug(`Inband event with scheme_id_uri ${event.eventStream.schemeIdUri}, value ${event.eventStream.value} and id ${event.id} was ignored because it has been added before.`);\n }\n }\n _onEventTimer();\n } catch (e) {\n throw e;\n }\n }\n\n /**\n * Adds or updates an event to/in the list of events\n * @param {object} event\n * @param {object} events\n * @param {boolean} shouldOverwriteExistingEvents\n * @return {string}\n * @private\n */\n function _addOrUpdateEvent(event, events, shouldOverwriteExistingEvents = false) {\n const schemeIdUri = event.eventStream.schemeIdUri;\n const value = event.eventStream.value;\n const id = event.id;\n let eventState = EVENT_HANDLED_STATES.DISCARDED;\n\n if (!events[schemeIdUri]) {\n events[schemeIdUri] = [];\n }\n\n const indexOfExistingEvent = events[schemeIdUri].findIndex((e) => {\n return ((!value || (e.eventStream.value && e.eventStream.value === value)) && (e.id === id));\n });\n\n if (indexOfExistingEvent === -1) {\n events[schemeIdUri].push(event);\n eventState = EVENT_HANDLED_STATES.ADDED;\n } else if (shouldOverwriteExistingEvents) {\n events[schemeIdUri][indexOfExistingEvent] = event;\n eventState = EVENT_HANDLED_STATES.UPDATED;\n }\n\n return eventState;\n }\n\n /**\n * Triggers an MPD reload\n * @param {object} event\n * @private\n */\n function _handleManifestReloadEvent(event) {\n try {\n if (event.eventStream.value == MPD_RELOAD_VALUE) {\n const validUntil = event.calculatedPresentationTime;\n let newDuration;\n if (event.calculatedPresentationTime == 0xFFFFFFFF) {//0xFF... means remaining duration unknown\n newDuration = NaN;\n } else {\n newDuration = event.calculatedPresentationTime + event.duration;\n }\n //logger.info('Manifest validity changed: Valid until: ' + validUntil + '; remaining duration: ' + newDuration);\n eventBus.trigger(MediaPlayerEvents.MANIFEST_VALIDITY_CHANGED, {\n id: event.id,\n validUntil: validUntil,\n newDuration: newDuration,\n newManifestValidAfter: NaN //event.message_data - this is an arraybuffer with a timestring in it, but not used yet\n }, {\n mode: MediaPlayerEvents.EVENT_MODE_ON_START\n });\n }\n } catch (e) {\n }\n }\n\n /**\n * Iterate through the eventList and trigger the events\n */\n function _onEventTimer() {\n try {\n if (!eventHandlingInProgress) {\n eventHandlingInProgress = true;\n const currentVideoTime = playbackController.getTime();\n let presentationTimeThreshold = (currentVideoTime - lastEventTimerCall);\n\n // For dynamic streams lastEventTimeCall will be large in the first iteration. Avoid firing all events at once.\n presentationTimeThreshold = lastEventTimerCall > 0 ? Math.max(0, presentationTimeThreshold) : 0;\n\n _triggerEvents(inbandEvents, presentationTimeThreshold, currentVideoTime);\n _triggerEvents(inlineEvents, presentationTimeThreshold, currentVideoTime);\n\n lastEventTimerCall = currentVideoTime;\n eventHandlingInProgress = false;\n }\n } catch (e) {\n eventHandlingInProgress = false;\n }\n }\n\n /**\n * When the EventController is stopped this callback is triggered. Starts the remaining events.\n * @private\n */\n function _onStopEventController() {\n try {\n // EventController might be stopped before the period is over. Before we stop the event controller we check for events that needs to be triggered at the period boundary.\n _triggerRemainingEvents(inbandEvents);\n _triggerRemainingEvents(inlineEvents);\n } catch (e) {\n\n }\n }\n\n /**\n * Iterate over a list of events and trigger the ones for which the presentation time is within the current timing interval\n * @param {object} events\n * @param {number} presentationTimeThreshold\n * @param {number} currentVideoTime\n * @private\n */\n function _triggerEvents(events, presentationTimeThreshold, currentVideoTime) {\n try {\n const callback = function (event) {\n if (event !== undefined) {\n const duration = !isNaN(event.duration) ? event.duration : 0;\n // The event is either about to start or has already been started and we are within its duration\n if ((event.calculatedPresentationTime <= currentVideoTime && event.calculatedPresentationTime + presentationTimeThreshold + duration >= currentVideoTime)) {\n _startEvent(event, events, MediaPlayerEvents.EVENT_MODE_ON_START);\n } else if (_eventHasExpired(currentVideoTime, duration + presentationTimeThreshold, event.calculatedPresentationTime) || _eventIsInvalid(event)) {\n logger.debug(`Deleting event ${event.id} as it is expired or invalid`);\n _removeEvent(events, event);\n }\n }\n };\n\n _iterateAndTriggerCallback(events, callback);\n } catch (e) {\n }\n }\n\n /**\n * Triggers the remaining events after the EventController has been stopped\n * @param {object} events\n * @private\n */\n function _triggerRemainingEvents(events) {\n try {\n const currentTime = playbackController.getTime();\n const callback = function (event) {\n const periodDuration = event.eventStream && event.eventStream.period && !isNaN(event.eventStream.period.duration) ? event.eventStream.period.duration : NaN;\n const periodStart = event.eventStream && event.eventStream.period && !isNaN(event.eventStream.period.start) ? event.eventStream.period.start : NaN;\n\n if (isNaN(periodDuration) || isNaN(periodStart)) {\n return;\n }\n\n const calculatedPresentationTimeInSeconds = event.calculatedPresentationTime;\n\n if (Math.abs(calculatedPresentationTimeInSeconds - currentTime) < REMAINING_EVENTS_THRESHOLD) {\n _startEvent(event, events, MediaPlayerEvents.EVENT_MODE_ON_START);\n }\n\n };\n\n _iterateAndTriggerCallback(events, callback);\n\n } catch (e) {\n\n }\n }\n\n /**\n * Iterates over the inline/inband event object and triggers a callback for each event\n * @param {object} events\n * @param {function} callback\n * @private\n */\n function _iterateAndTriggerCallback(events, callback) {\n try {\n if (events) {\n const schemeIdUris = Object.keys(events);\n for (let i = 0; i < schemeIdUris.length; i++) {\n const schemeIdEvents = events[schemeIdUris[i]];\n schemeIdEvents.forEach((event) => {\n if (event !== undefined) {\n callback(event);\n }\n });\n }\n }\n } catch (e) {\n\n }\n }\n\n /**\n * Checks if an event is expired. For instance if the presentationTime + the duration of an event are smaller than the current video time.\n * @param {number} currentVideoTime\n * @param {number} threshold\n * @param {number} calculatedPresentationTimeInSeconds\n * @return {boolean}\n * @private\n */\n function _eventHasExpired(currentVideoTime, threshold, calculatedPresentationTimeInSeconds) {\n try {\n return currentVideoTime - threshold > calculatedPresentationTimeInSeconds;\n } catch (e) {\n return false;\n }\n }\n\n /**\n * Checks if an event is invalid. This is the case if the end time of the parent period is smaller than the presentation time of the event.\n * @param {object} event\n * @return {boolean}\n * @private\n */\n function _eventIsInvalid(event) {\n try {\n const periodEndTime = event.eventStream.period.start + event.eventStream.period.duration;\n\n return event.calculatedPresentationTime > periodEndTime;\n } catch (e) {\n return false;\n }\n }\n\n /**\n * Starts an event. Depending on the schemeIdUri we distinguis between\n * - MPD Reload events\n * - MPD Callback events\n * - Events to be dispatched to the application\n * Events should be removed from the list before beeing triggered. Otherwise the event handler might cause an error and the remove function will not be called.\n * @param {object} event\n * @param {object} events\n * @param {String} mode\n * @private\n */\n function _startEvent(event, events, mode) {\n try {\n const currentVideoTime = playbackController.getTime();\n const eventId = event.id;\n\n if (mode === MediaPlayerEvents.EVENT_MODE_ON_RECEIVE) {\n logger.debug(`Received event ${eventId}`);\n eventBus.trigger(event.eventStream.schemeIdUri, { event: event }, { mode });\n return;\n }\n\n if (event.eventStream.schemeIdUri === MPD_RELOAD_SCHEME && event.eventStream.value == MPD_RELOAD_VALUE) {\n if (event.duration !== 0 || event.presentationTimeDelta !== 0) { //If both are set to zero, it indicates the media is over at this point. Don't reload the manifest.\n logger.debug(`Starting manifest refresh event ${eventId} at ${currentVideoTime}`);\n _removeEvent(events, event);\n _refreshManifest();\n }\n } else if (event.eventStream.schemeIdUri === MPD_CALLBACK_SCHEME && event.eventStream.value == MPD_CALLBACK_VALUE) {\n logger.debug(`Starting callback event ${eventId} at ${currentVideoTime}`);\n _removeEvent(events, event);\n _sendCallbackRequest(event.messageData);\n } else {\n logger.debug(`Starting event ${eventId} at ${currentVideoTime}`);\n _removeEvent(events, event);\n eventBus.trigger(event.eventStream.schemeIdUri, { event: event }, { mode });\n }\n\n } catch (e) {\n }\n }\n\n /**\n * Removes an event from the list. If this is the last event of type \"schemeIdUri\" the corresponding schemeIdUri Object in the list of events is deleted.\n * @param {object} events\n * @param {object} event\n * @private\n */\n function _removeEvent(events, event) {\n const schemeIdUri = event.eventStream.schemeIdUri;\n const value = event.eventStream.value;\n const id = event.id;\n\n events[schemeIdUri] = events[schemeIdUri].filter((e) => {\n return (value && e.eventStream.value && e.eventStream.value !== value) || e.id !== id;\n });\n\n if (events[schemeIdUri].length === 0) {\n delete events[schemeIdUri];\n }\n\n }\n\n /**\n * Refresh the manifest\n * @private\n */\n function _refreshManifest() {\n try {\n checkConfig();\n manifestUpdater.refreshManifest();\n } catch (e) {\n }\n }\n\n /**\n * Send a callback request\n * @param {String} url\n * @private\n */\n function _sendCallbackRequest(url) {\n try {\n let loader = XHRLoader(context).create({});\n loader.load({\n method: 'get',\n url: url,\n request: {\n responseType: 'arraybuffer'\n }\n });\n } catch (e) {\n throw e;\n }\n }\n\n /**\n * Set the config of the EventController\n * @param {object} config\n */\n function setConfig(config) {\n try {\n if (!config) {\n return;\n }\n if (config.manifestUpdater) {\n manifestUpdater = config.manifestUpdater;\n }\n if (config.playbackController) {\n playbackController = config.playbackController;\n }\n if (config.settings) {\n settings = config.settings;\n }\n\n } catch (e) {\n throw e;\n }\n }\n\n /**\n * Returns all inline events that have not been triggered yet\n * @return {object}\n */\n function getInlineEvents() {\n return inlineEvents;\n }\n\n /**\n * Returns all inband events that have not been triggered yet\n * @return {object}\n */\n function getInbandEvents() {\n return inbandEvents;\n }\n\n /**\n * Stop the EventController and reset all initial settings\n */\n function reset() {\n _stop();\n _resetInitialSettings();\n }\n\n instance = {\n addInlineEvents,\n addInbandEvents,\n getInbandEvents,\n getInlineEvents,\n start,\n setConfig,\n reset\n };\n\n _setup();\n\n return instance;\n}\n\nEventController.__dashjs_factory_name = 'EventController';\nexport default FactoryMaker.getSingletonFactory(EventController);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nexport default {\n LEVELS: {\n SUGGESTION: 'Suggestion',\n WARNING: 'Warning',\n ERROR: 'Error'\n },\n EVENTS: {\n NO_UTC_TIMING_ELEMENT: {\n key: 'NO_UTC_TIMING_ELEMENT',\n message: 'No UTCTiming element is present in the manifest. You may experience playback failures. For a detailed validation use https://conformance.dashif.org/'\n },\n NON_COMPLIANT_SMPTE_IMAGE_ATTRIBUTE: {\n key: 'NON_COMPLIANT_SMPTE_IMAGE_ATTRIBUTE',\n message: 'SMPTE 2052-1:2013 defines the attribute name as \"imageType\" and does not define \"imagetype\"'\n },\n INVALID_DVR_WINDOW: {\n key: 'INVALID_DVR_WINDOW',\n message: 'No valid segment found when applying a specification compliant DVR window calculation. Using SegmentTimeline entries as a fallback.'\n }\n }\n};\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Constants from '../constants/Constants';\nimport MetricsConstants from '../constants/MetricsConstants';\nimport Stream from '../Stream';\nimport ManifestUpdater from '../ManifestUpdater';\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport {\n PlayList,\n PlayListTrace\n} from '../vo/metrics/PlayList';\nimport Debug from '../../core/Debug';\nimport InitCache from '../utils/InitCache';\nimport URLUtils from '../utils/URLUtils';\nimport MediaPlayerEvents from '../MediaPlayerEvents';\nimport TimeSyncController from './TimeSyncController';\nimport MediaSourceController from './MediaSourceController';\nimport DashJSError from '../vo/DashJSError';\nimport Errors from '../../core/errors/Errors';\nimport EventController from './EventController';\nimport ConformanceViolationConstants from '../constants/ConformanceViolationConstants';\n\nconst PLAYBACK_ENDED_TIMER_INTERVAL = 200;\nconst DVR_WAITING_OFFSET = 2;\n\nfunction StreamController() {\n\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n\n let instance,\n logger,\n capabilities,\n capabilitiesFilter,\n manifestUpdater,\n manifestLoader,\n manifestModel,\n adapter,\n dashMetrics,\n mediaSourceController,\n timeSyncController,\n baseURLController,\n segmentBaseController,\n uriFragmentModel,\n abrController,\n mediaController,\n eventController,\n initCache,\n urlUtils,\n errHandler,\n timelineConverter,\n streams,\n activeStream,\n protectionController,\n textController,\n protectionData,\n autoPlay,\n isStreamSwitchingInProgress,\n hasMediaError,\n hasInitialisationError,\n mediaSource,\n videoModel,\n playbackController,\n mediaPlayerModel,\n isPaused,\n initialPlayback,\n playbackEndedTimerInterval,\n bufferSinks,\n preloadingStreams,\n supportsChangeType,\n settings,\n firstLicenseIsFetched,\n waitForPlaybackStartTimeout,\n errorInformation;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n timeSyncController = TimeSyncController(context).getInstance();\n mediaSourceController = MediaSourceController(context).getInstance();\n initCache = InitCache(context).getInstance();\n urlUtils = URLUtils(context).getInstance();\n\n resetInitialSettings();\n }\n\n function initialize(autoPl, protData) {\n _checkConfig();\n\n autoPlay = autoPl;\n protectionData = protData;\n timelineConverter.initialize();\n\n manifestUpdater = ManifestUpdater(context).create();\n manifestUpdater.setConfig({\n manifestModel: manifestModel,\n adapter: adapter,\n manifestLoader: manifestLoader,\n errHandler: errHandler,\n settings: settings\n });\n manifestUpdater.initialize();\n\n eventController = EventController(context).getInstance();\n eventController.setConfig({\n manifestUpdater: manifestUpdater,\n playbackController: playbackController,\n settings\n });\n eventController.start();\n\n\n timeSyncController.setConfig({\n dashMetrics,\n baseURLController,\n errHandler,\n settings\n });\n timeSyncController.initialize();\n\n if (protectionController) {\n eventBus.trigger(Events.PROTECTION_CREATED, {\n controller: protectionController\n });\n protectionController.setMediaElement(videoModel.getElement());\n if (protectionData) {\n protectionController.setProtectionData(protectionData);\n }\n }\n\n registerEvents();\n }\n\n function registerEvents() {\n eventBus.on(MediaPlayerEvents.PLAYBACK_TIME_UPDATED, _onPlaybackTimeUpdated, instance);\n eventBus.on(MediaPlayerEvents.PLAYBACK_SEEKING, _onPlaybackSeeking, instance);\n eventBus.on(MediaPlayerEvents.PLAYBACK_ERROR, _onPlaybackError, instance);\n eventBus.on(MediaPlayerEvents.PLAYBACK_STARTED, _onPlaybackStarted, instance);\n eventBus.on(MediaPlayerEvents.PLAYBACK_PAUSED, _onPlaybackPaused, instance);\n eventBus.on(MediaPlayerEvents.PLAYBACK_ENDED, _onPlaybackEnded, instance);\n eventBus.on(MediaPlayerEvents.METRIC_ADDED, _onMetricAdded, instance);\n eventBus.on(MediaPlayerEvents.MANIFEST_VALIDITY_CHANGED, _onManifestValidityChanged, instance);\n eventBus.on(MediaPlayerEvents.BUFFER_LEVEL_UPDATED, _onBufferLevelUpdated, instance);\n eventBus.on(MediaPlayerEvents.QUALITY_CHANGE_REQUESTED, _onQualityChanged, instance);\n\n if (Events.KEY_SESSION_UPDATED) {\n eventBus.on(Events.KEY_SESSION_UPDATED, _onKeySessionUpdated, instance);\n }\n\n eventBus.on(Events.MANIFEST_UPDATED, _onManifestUpdated, instance);\n eventBus.on(Events.STREAM_BUFFERING_COMPLETED, _onStreamBufferingCompleted, instance);\n eventBus.on(Events.TIME_SYNCHRONIZATION_COMPLETED, _onTimeSyncCompleted, instance);\n eventBus.on(Events.CURRENT_TRACK_CHANGED, _onCurrentTrackChanged, instance);\n }\n\n function unRegisterEvents() {\n eventBus.off(MediaPlayerEvents.PLAYBACK_TIME_UPDATED, _onPlaybackTimeUpdated, instance);\n eventBus.off(MediaPlayerEvents.PLAYBACK_SEEKING, _onPlaybackSeeking, instance);\n eventBus.off(MediaPlayerEvents.PLAYBACK_ERROR, _onPlaybackError, instance);\n eventBus.off(MediaPlayerEvents.PLAYBACK_STARTED, _onPlaybackStarted, instance);\n eventBus.off(MediaPlayerEvents.PLAYBACK_PAUSED, _onPlaybackPaused, instance);\n eventBus.off(MediaPlayerEvents.PLAYBACK_ENDED, _onPlaybackEnded, instance);\n eventBus.off(MediaPlayerEvents.METRIC_ADDED, _onMetricAdded, instance);\n eventBus.off(MediaPlayerEvents.MANIFEST_VALIDITY_CHANGED, _onManifestValidityChanged, instance);\n eventBus.off(MediaPlayerEvents.BUFFER_LEVEL_UPDATED, _onBufferLevelUpdated, instance);\n eventBus.off(MediaPlayerEvents.QUALITY_CHANGE_REQUESTED, _onQualityChanged, instance);\n\n if (Events.KEY_SESSION_UPDATED) {\n eventBus.off(Events.KEY_SESSION_UPDATED, _onKeySessionUpdated, instance);\n }\n\n eventBus.off(Events.MANIFEST_UPDATED, _onManifestUpdated, instance);\n eventBus.off(Events.STREAM_BUFFERING_COMPLETED, _onStreamBufferingCompleted, instance);\n eventBus.off(Events.TIME_SYNCHRONIZATION_COMPLETED, _onTimeSyncCompleted, instance);\n eventBus.off(Events.CURRENT_TRACK_CHANGED, _onCurrentTrackChanged, instance);\n }\n\n /**\n * When the UTC snychronization is completed we can compose the streams\n * @private\n */\n function _onTimeSyncCompleted( /*e*/) {\n _composeStreams();\n }\n\n /**\n *\n * @private\n */\n function _onKeySessionUpdated() {\n firstLicenseIsFetched = true;\n }\n\n /**\n * Setup the stream objects after the stream start and each MPD reload. This function is called after the UTC sync has been done (TIME_SYNCHRONIZATION_COMPLETED)\n * @private\n */\n function _composeStreams() {\n try {\n const streamsInfo = adapter.getStreamsInfo();\n\n if (!activeStream && streamsInfo.length === 0) {\n throw new Error('There are no streams');\n }\n\n if (activeStream) {\n dashMetrics.updateManifestUpdateInfo({\n currentTime: playbackController.getTime(),\n buffered: videoModel.getBufferRange(),\n presentationStartTime: streamsInfo[0].start,\n clientTimeOffset: timelineConverter.getClientTimeOffset()\n });\n }\n\n // Filter streams that are outdated and not included in the MPD anymore\n if (streams.length > 0) {\n _filterOutdatedStreams(streamsInfo);\n }\n\n const promises = [];\n for (let i = 0, ln = streamsInfo.length; i < ln; i++) {\n const streamInfo = streamsInfo[i];\n promises.push(_initializeOrUpdateStream(streamInfo));\n dashMetrics.addManifestUpdateStreamInfo(streamInfo);\n }\n\n Promise.all(promises)\n .then(() => {\n if (!activeStream) {\n _initializeForFirstStream(streamsInfo);\n }\n\n eventBus.trigger(Events.STREAMS_COMPOSED);\n // Additional periods might have been added after an MPD update. Check again if we can start prebuffering.\n _checkIfPrebufferingCanStart();\n })\n .catch((e) => {\n throw e;\n })\n\n } catch (e) {\n errHandler.error(new DashJSError(Errors.MANIFEST_ERROR_ID_NOSTREAMS_CODE, e.message + 'nostreamscomposed', manifestModel.getValue()));\n hasInitialisationError = true;\n reset();\n }\n }\n\n /**\n * Called for each stream when composition is performed. Either a new instance of Stream is created or the existing one is updated.\n * @param {object} streamInfo\n * @private\n */\n function _initializeOrUpdateStream(streamInfo) {\n let stream = getStreamById(streamInfo.id);\n\n // If the Stream object does not exist we probably loaded the manifest the first time or it was\n // introduced in the updated manifest, so we need to create a new Stream and perform all the initialization operations\n if (!stream) {\n stream = Stream(context).create({\n manifestModel,\n mediaPlayerModel,\n dashMetrics,\n manifestUpdater,\n adapter,\n timelineConverter,\n capabilities,\n capabilitiesFilter,\n errHandler,\n baseURLController,\n segmentBaseController,\n textController,\n abrController,\n playbackController,\n eventController,\n mediaController,\n protectionController,\n videoModel,\n streamInfo,\n settings\n });\n streams.push(stream);\n stream.initialize();\n return Promise.resolve();\n } else {\n return stream.updateData(streamInfo);\n }\n }\n\n /**\n * Initialize playback for the first period.\n * @param {object} streamsInfo\n * @private\n */\n function _initializeForFirstStream(streamsInfo) {\n\n // Add the DVR window so we can calculate the right starting point\n addDVRMetric();\n\n // If the start is in the future we need to wait\n const dvrRange = dashMetrics.getCurrentDVRInfo().range;\n if (dvrRange.end < dvrRange.start) {\n if (waitForPlaybackStartTimeout) {\n clearTimeout(waitForPlaybackStartTimeout);\n }\n const waitingTime = Math.min((((dvrRange.end - dvrRange.start) * -1) + DVR_WAITING_OFFSET) * 1000, 2147483647);\n logger.debug(`Waiting for ${waitingTime} ms before playback can start`);\n eventBus.trigger(Events.AST_IN_FUTURE, { delay: waitingTime });\n waitForPlaybackStartTimeout = setTimeout(() => {\n _initializeForFirstStream(streamsInfo);\n }, waitingTime);\n return;\n }\n\n // Compute and set the live delay\n if (adapter.getIsDynamic() && streams.length) {\n const manifestInfo = streamsInfo[0].manifestInfo;\n const fragmentDuration = _getFragmentDurationForLiveDelayCalculation(streamsInfo, manifestInfo);\n playbackController.computeAndSetLiveDelay(fragmentDuration, manifestInfo);\n }\n\n // Figure out the correct start time and the correct start period\n const startTime = _getInitialStartTime();\n let initialStream = getStreamForTime(startTime);\n const startStream = initialStream !== null ? initialStream : streams[0];\n\n eventBus.trigger(Events.INITIAL_STREAM_SWITCH, { startTime });\n _switchStream(startStream, null, startTime);\n _startPlaybackEndedTimerInterval();\n }\n\n /**\n * Switch from the current stream (period) to the next stream (period).\n * @param {object} stream\n * @param {object} previousStream\n * @param {number} seekTime\n * @private\n */\n function _switchStream(stream, previousStream, seekTime) {\n try {\n if (isStreamSwitchingInProgress || !stream || (previousStream === stream && stream.getIsActive())) {\n return;\n }\n\n isStreamSwitchingInProgress = true;\n eventBus.trigger(Events.PERIOD_SWITCH_STARTED, {\n fromStreamInfo: previousStream ? previousStream.getStreamInfo() : null,\n toStreamInfo: stream.getStreamInfo()\n });\n\n let keepBuffers = false;\n activeStream = stream;\n\n if (previousStream) {\n keepBuffers = _canSourceBuffersBeReused(stream, previousStream);\n previousStream.deactivate(keepBuffers);\n }\n\n // Determine seek time when switching to new period\n // - seek at given seek time\n // - or seek at period start if upcoming period is not prebuffered\n seekTime = !isNaN(seekTime) ? seekTime : (!keepBuffers && previousStream ? stream.getStreamInfo().start : NaN);\n logger.info(`Switch to stream ${stream.getId()}. Seektime is ${seekTime}, current playback time is ${playbackController.getTime()}. Seamless period switch is set to ${keepBuffers}`);\n\n preloadingStreams = preloadingStreams.filter((s) => {\n return s.getId() !== activeStream.getId();\n });\n playbackController.initialize(getActiveStreamInfo(), !!previousStream);\n\n if (videoModel.getElement()) {\n _openMediaSource(seekTime, keepBuffers);\n }\n } catch (e) {\n isStreamSwitchingInProgress = false;\n }\n }\n\n /**\n * Setup the Media Source. Open MSE and attach event listeners\n * @param {number} seekTime\n * @param {boolean} keepBuffers\n * @private\n */\n function _openMediaSource(seekTime, keepBuffers) {\n let sourceUrl;\n\n function _onMediaSourceOpen() {\n // Manage situations in which a call to reset happens while MediaSource is being opened\n if (!mediaSource || mediaSource.readyState !== 'open') return;\n\n logger.debug('MediaSource is open!');\n window.URL.revokeObjectURL(sourceUrl);\n mediaSource.removeEventListener('sourceopen', _onMediaSourceOpen);\n mediaSource.removeEventListener('webkitsourceopen', _onMediaSourceOpen);\n\n _setMediaDuration();\n const dvrInfo = dashMetrics.getCurrentDVRInfo();\n mediaSourceController.setSeekable(dvrInfo.range.start, dvrInfo.range.end);\n _activateStream(seekTime, keepBuffers);\n }\n\n function _open() {\n mediaSource.addEventListener('sourceopen', _onMediaSourceOpen, false);\n mediaSource.addEventListener('webkitsourceopen', _onMediaSourceOpen, false);\n sourceUrl = mediaSourceController.attachMediaSource(videoModel);\n logger.debug('MediaSource attached to element. Waiting on open...');\n }\n\n if (!mediaSource) {\n mediaSource = mediaSourceController.createMediaSource();\n _open();\n } else {\n if (keepBuffers) {\n _activateStream(seekTime, keepBuffers);\n } else {\n mediaSourceController.detachMediaSource(videoModel);\n _open();\n }\n }\n }\n\n /**\n * Activates a new stream.\n * @param {number} seekTime\n * @param {boolean} keepBuffers\n */\n function _activateStream(seekTime, keepBuffers) {\n activeStream.activate(mediaSource, keepBuffers ? bufferSinks : undefined, seekTime)\n .then((sinks) => {\n // check if change type is supported by the browser\n if (sinks) {\n const keys = Object.keys(sinks);\n if (keys.length > 0 && sinks[keys[0]].getBuffer().changeType) {\n supportsChangeType = true;\n }\n bufferSinks = sinks;\n }\n\n // Set the initial time for this stream in the StreamProcessor\n if (!isNaN(seekTime)) {\n eventBus.trigger(Events.SEEK_TARGET, { time: seekTime }, { streamId: activeStream.getId() });\n playbackController.seek(seekTime, false, true);\n activeStream.startScheduleControllers();\n }\n\n isStreamSwitchingInProgress = false;\n eventBus.trigger(Events.PERIOD_SWITCH_COMPLETED, { toStreamInfo: getActiveStreamInfo() });\n });\n }\n\n /**\n * A playback seeking event was triggered. We need to disable the preloading streams and call the respective seeking handler.\n * We distinguish between inner period seeks and outer period seeks\n * @param {object} e\n * @private\n */\n function _onPlaybackSeeking(e) {\n const oldTime = playbackController.getTime();\n const newTime = e.seekTime;\n const seekToStream = getStreamForTime(newTime);\n\n if (!seekToStream || seekToStream === activeStream) {\n _cancelPreloading(oldTime, newTime);\n _handleInnerPeriodSeek(e);\n } else if (seekToStream && seekToStream !== activeStream) {\n _cancelPreloading(oldTime, newTime, seekToStream);\n _handleOuterPeriodSeek(e, seekToStream);\n }\n\n _createPlaylistMetrics(PlayList.SEEK_START_REASON);\n }\n\n /**\n * Cancels the preloading of certain streams based on the position we are seeking to.\n * @param {number} oldTime\n * @param {number} newTime\n * @param {boolean} isInnerPeriodSeek\n * @private\n */\n function _cancelPreloading(oldTime, newTime, seekToStream = null) {\n // Inner period seek forward\n if (oldTime <= newTime && !seekToStream) {\n _deactivateAllPreloadingStreams();\n }\n\n // Inner period seek: If we seek backwards we might need to prune the period(s) that are currently being prebuffered. For now deactivate everything\n else if (oldTime > newTime && !seekToStream) {\n _deactivateAllPreloadingStreams();\n }\n\n // Outer period seek: Deactivate everything for now\n else {\n _deactivateAllPreloadingStreams();\n }\n\n }\n\n /**\n * Deactivates all preloading streams\n * @private\n */\n function _deactivateAllPreloadingStreams() {\n if (preloadingStreams && preloadingStreams.length > 0) {\n preloadingStreams.forEach((s) => {\n s.deactivate(true);\n });\n preloadingStreams = [];\n }\n }\n\n /**\n * Handle an inner period seek. Prepare all StreamProcessors for the seek.\n * @param {object} e\n * @private\n */\n function _handleInnerPeriodSeek(e) {\n const streamProcessors = activeStream.getProcessors();\n\n streamProcessors.forEach((sp) => {\n return sp.prepareInnerPeriodPlaybackSeeking(e);\n });\n\n _flushPlaylistMetrics(PlayListTrace.USER_REQUEST_STOP_REASON);\n }\n\n /**\n * Handle an outer period seek. Dispatch the corresponding event to be handled in the BufferControllers and the ScheduleControllers\n * @param {object} e\n * @param {object} seekToStream\n * @private\n */\n function _handleOuterPeriodSeek(e, seekToStream) {\n // Stop segment requests\n const seekTime = e && !isNaN(e.seekTime) ? e.seekTime : NaN;\n const streamProcessors = activeStream.getProcessors();\n\n const promises = streamProcessors.map((sp) => {\n // Cancel everything in case the active stream is still buffering\n return sp.prepareOuterPeriodPlaybackSeeking(e);\n });\n\n Promise.all(promises)\n .then(() => {\n _switchStream(seekToStream, activeStream, seekTime);\n })\n .catch((e) => {\n errHandler.error(e);\n });\n }\n\n /**\n * A track change occured. We deactivate the preloading streams\n * @param {object} e\n * @private\n */\n function _onCurrentTrackChanged(e) {\n // Track was changed in non active stream. No need to do anything, this only happens when a stream starts preloading\n if (e.newMediaInfo.streamInfo.id !== activeStream.getId()) {\n return;\n }\n\n // If the track was changed in the active stream we need to stop preloading and remove the already prebuffered stuff. Since we do not support preloading specific handling of specific AdaptationSets yet.\n _deactivateAllPreloadingStreams();\n\n activeStream.prepareTrackChange(e);\n }\n\n /**\n * If the source buffer can be reused we can potentially start buffering the next period\n * @param {object} nextStream\n * @param {object} previousStream\n * @return {boolean}\n * @private\n */\n function _canSourceBuffersBeReused(nextStream, previousStream) {\n try {\n // Seamless period switch allowed only if:\n // - none of the periods uses contentProtection.\n // - AND changeType method implemented by browser or periods use the same codec.\n return (settings.get().streaming.buffer.reuseExistingSourceBuffers && (previousStream.isProtectionCompatible(nextStream) || firstLicenseIsFetched) && (supportsChangeType || previousStream.isMediaCodecCompatible(nextStream, previousStream)));\n } catch (e) {\n return false;\n }\n }\n\n /**\n * Initiate the preloading of the next stream\n * @param {object} nextStream\n * @param {object} previousStream\n * @private\n */\n function _onStreamCanLoadNext(nextStream, previousStream = null) {\n\n if (mediaSource && !nextStream.getPreloaded()) {\n let seamlessPeriodSwitch = _canSourceBuffersBeReused(nextStream, previousStream);\n\n if (seamlessPeriodSwitch) {\n nextStream.startPreloading(mediaSource, bufferSinks)\n .then(() => {\n preloadingStreams.push(nextStream);\n });\n }\n }\n }\n\n /**\n * Returns the corresponding stream object for a specific presentation time.\n * @param {number} time\n * @return {null|object}\n */\n function getStreamForTime(time) {\n\n if (isNaN(time)) {\n return null;\n }\n\n const ln = streams.length;\n\n for (let i = 0; i < ln; i++) {\n const stream = streams[i];\n const streamEnd = parseFloat((stream.getStartTime() + stream.getDuration()).toFixed(5));\n\n if (time < streamEnd) {\n return stream;\n }\n }\n\n return null;\n }\n\n /**\n * Add the DVR window to the metric list. We need the DVR window to restrict the seeking and calculate the right start time.\n */\n function addDVRMetric() {\n try {\n const isDynamic = adapter.getIsDynamic();\n const streamsInfo = adapter.getStreamsInfo();\n const manifestInfo = streamsInfo[0].manifestInfo;\n const time = playbackController.getTime();\n const range = timelineConverter.calcTimeShiftBufferWindow(streams, isDynamic);\n const activeStreamProcessors = getActiveStreamProcessors();\n\n if (typeof range.start === 'undefined' || typeof range.end === 'undefined') {\n return;\n }\n\n if (!activeStreamProcessors || activeStreamProcessors.length === 0) {\n dashMetrics.addDVRInfo(Constants.VIDEO, time, manifestInfo, range);\n } else {\n activeStreamProcessors.forEach((sp) => {\n dashMetrics.addDVRInfo(sp.getType(), time, manifestInfo, range);\n });\n }\n } catch (e) {\n }\n }\n\n /**\n * The buffer level for a certain media type has been updated. If this is the initial playback and we want to autoplay the content we check if we can start playback now.\n * For livestreams we might have a drift of the target live delay compared to the current live delay because reaching the initial buffer level took time.\n * @param {object} e\n * @private\n */\n function _onBufferLevelUpdated(e) {\n\n // check if this is the initial playback and we reached the buffer target. If autoplay is true we start playback\n if (initialPlayback && autoPlay) {\n const initialBufferLevel = mediaPlayerModel.getInitialBufferLevel();\n const excludedStreamProcessors = [Constants.TEXT];\n if (isNaN(initialBufferLevel) || initialBufferLevel <= playbackController.getBufferLevel(excludedStreamProcessors) || (adapter.getIsDynamic() && initialBufferLevel > playbackController.getLiveDelay())) {\n initialPlayback = false;\n _createPlaylistMetrics(PlayList.INITIAL_PLAYOUT_START_REASON);\n playbackController.play();\n }\n }\n\n if (e && e.mediaType) {\n dashMetrics.addBufferLevel(e.mediaType, new Date(), e.bufferLevel * 1000);\n }\n }\n\n /**\n * When the quality is changed in the currently active stream and we do an aggressive replacement we must stop prebuffering. This is similar to a replacing track switch\n * Otherwise preloading can go on.\n * @param e\n * @private\n */\n function _onQualityChanged(e) {\n if (e.streamInfo.id === activeStream.getId() && e.reason && e.reason.forceReplace) {\n _deactivateAllPreloadingStreams();\n }\n\n const stream = getStreamById(e.streamInfo.id);\n\n stream.prepareQualityChange(e);\n }\n\n /**\n * When the playback time is updated we add the droppedFrames metric to the dash metric object\n * @private\n */\n function _onPlaybackTimeUpdated(/*e*/) {\n if (hasVideoTrack()) {\n const playbackQuality = videoModel.getPlaybackQuality();\n if (playbackQuality) {\n dashMetrics.addDroppedFrames(playbackQuality);\n }\n }\n }\n\n /**\n * Once playback starts add playlist metrics depending on whether this was the first playback or playback resumed after pause\n * @private\n */\n function _onPlaybackStarted( /*e*/) {\n logger.debug('[onPlaybackStarted]');\n if (!initialPlayback && isPaused) {\n _createPlaylistMetrics(PlayList.RESUME_FROM_PAUSE_START_REASON);\n }\n if (initialPlayback) {\n initialPlayback = false;\n }\n isPaused = false;\n }\n\n /**\n * Once playback is paused flush metrics\n * @param {object} e\n * @private\n */\n function _onPlaybackPaused(e) {\n logger.debug('[onPlaybackPaused]');\n if (!e.ended) {\n isPaused = true;\n _flushPlaylistMetrics(PlayListTrace.USER_REQUEST_STOP_REASON);\n }\n }\n\n /**\n * Callback once a stream/period is completely buffered. We can either signal the end of the stream or start prebuffering the next period.\n * @param {object} e\n * @private\n */\n function _onStreamBufferingCompleted(e) {\n logger.debug(`Stream with id ${e.streamInfo.id} finished buffering`);\n const isLast = e.streamInfo.isLast;\n if (mediaSource && isLast) {\n logger.info('[onStreamBufferingCompleted] calls signalEndOfStream of mediaSourceController.');\n mediaSourceController.signalEndOfStream(mediaSource);\n } else {\n _checkIfPrebufferingCanStart();\n }\n }\n\n /**\n * Check if we can start prebuffering the next period.\n * @private\n */\n function _checkIfPrebufferingCanStart() {\n // In multiperiod situations, we can start buffering the next stream\n if (!activeStream || !activeStream.getHasFinishedBuffering()) {\n return;\n }\n const upcomingStreams = _getNextStreams(activeStream);\n let i = 0;\n\n while (i < upcomingStreams.length) {\n const stream = upcomingStreams[i];\n const previousStream = i === 0 ? activeStream : upcomingStreams[i - 1];\n\n // If the preloading for the current stream is not scheduled, but its predecessor has finished buffering we can start prebuffering this stream\n if (!stream.getPreloaded() && previousStream.getHasFinishedBuffering()) {\n if (mediaSource) {\n _onStreamCanLoadNext(stream, previousStream);\n }\n }\n i += 1;\n }\n }\n\n /**\n * In some cases we need to fire the playback ended event manually\n * @private\n */\n function _startPlaybackEndedTimerInterval() {\n if (!playbackEndedTimerInterval) {\n playbackEndedTimerInterval = setInterval(function () {\n if (!isStreamSwitchingInProgress && playbackController.getTimeToStreamEnd() <= 0 && !playbackController.isSeeking()) {\n eventBus.trigger(Events.PLAYBACK_ENDED, { 'isLast': getActiveStreamInfo().isLast });\n }\n }, PLAYBACK_ENDED_TIMER_INTERVAL);\n }\n }\n\n /**\n * Stop the check if the playback has ended\n * @private\n */\n function _stopPlaybackEndedTimerInterval() {\n if (playbackEndedTimerInterval) {\n clearInterval(playbackEndedTimerInterval);\n playbackEndedTimerInterval = null;\n }\n }\n\n /**\n * Returns a playhead time, in seconds, converted to be relative\n * to the start of an identified stream/period or null if no such stream\n * @param {number} time\n * @param {string} id\n * @returns {number|null}\n */\n function getTimeRelativeToStreamId(time, id) {\n let stream = null;\n let baseStart = 0;\n let streamStart = 0;\n let streamDur = null;\n\n for (let i = 0; i < streams.length; i++) {\n stream = streams[i];\n streamStart = stream.getStartTime();\n streamDur = stream.getDuration();\n\n // use start time, if not undefined or NaN or similar\n if (Number.isFinite(streamStart)) {\n baseStart = streamStart;\n }\n\n if (stream.getId() === id) {\n return time - baseStart;\n } else {\n // use duration if not undefined or NaN or similar\n if (Number.isFinite(streamDur)) {\n baseStart += streamDur;\n }\n }\n }\n\n return null;\n }\n\n /**\n * Returns the streamProcessors of the active stream.\n * @return {array}\n */\n function getActiveStreamProcessors() {\n return activeStream ? activeStream.getProcessors() : [];\n }\n\n /**\n * Once playback has ended we switch to the next stream\n * @param {object} e\n */\n function _onPlaybackEnded(e) {\n if (activeStream && !activeStream.getIsEndedEventSignaled()) {\n activeStream.setIsEndedEventSignaled(true);\n const nextStream = _getNextStream();\n if (nextStream) {\n logger.debug(`StreamController onEnded, found next stream with id ${nextStream.getStreamInfo().id}. Switching from ${activeStream.getStreamInfo().id} to ${nextStream.getStreamInfo().id}`);\n _switchStream(nextStream, activeStream, NaN);\n } else {\n logger.debug('StreamController no next stream found');\n activeStream.setIsEndedEventSignaled(false);\n }\n _flushPlaylistMetrics(nextStream ? PlayListTrace.END_OF_PERIOD_STOP_REASON : PlayListTrace.END_OF_CONTENT_STOP_REASON);\n }\n if (e && e.isLast) {\n _stopPlaybackEndedTimerInterval();\n }\n }\n\n /**\n * Returns the next stream to be played relative to the stream provided. If no stream is provided we use the active stream.\n * In order to avoid rounding issues we should not use the duration of the periods. Instead find the stream with starttime closest to startTime of the previous stream.\n * @param {object} stream\n * @return {null|object}\n */\n function _getNextStream(stream = null) {\n const refStream = stream ? stream : activeStream ? activeStream : null;\n\n if (!refStream) {\n return null;\n }\n\n const refStreamInfo = refStream.getStreamInfo();\n const start = refStreamInfo.start;\n let i = 0;\n let targetIndex = -1;\n let lastDiff = NaN;\n\n while (i < streams.length) {\n const s = streams[i];\n const sInfo = s.getStreamInfo();\n const diff = sInfo.start - start;\n\n if (diff > 0 && (isNaN(lastDiff) || diff < lastDiff) && refStreamInfo.id !== sInfo.id) {\n lastDiff = diff;\n targetIndex = i;\n }\n\n i += 1;\n }\n\n if (targetIndex >= 0) {\n return streams[targetIndex];\n }\n\n return null;\n }\n\n /**\n * Returns all upcoming streams relative to the provided stream. If no stream is provided we use the active stream.\n * @param {object} stream\n * @return {array}\n */\n function _getNextStreams(stream = null) {\n try {\n const refStream = stream ? stream : activeStream ? activeStream : null;\n\n if (refStream) {\n const refStreamInfo = refStream.getStreamInfo();\n\n return streams.filter(function (stream) {\n const sInfo = stream.getStreamInfo();\n return sInfo.start > refStreamInfo.start && refStreamInfo.id !== sInfo.id;\n });\n }\n } catch (e) {\n return [];\n }\n }\n\n /**\n * Sets the duration attribute of the MediaSource using the MediaSourceController.\n * @param {number} duration\n * @private\n */\n function _setMediaDuration(duration) {\n const manifestDuration = duration ? duration : getActiveStreamInfo().manifestInfo.duration;\n mediaSourceController.setDuration(manifestDuration);\n }\n\n /**\n * Returns the active stream\n * @return {object}\n */\n function getActiveStream() {\n return activeStream;\n }\n\n /**\n * Initial playback indicates if we have called play() for the first time yet.\n * @return {*}\n */\n function getInitialPlayback() {\n return initialPlayback;\n }\n\n /**\n * Auto Play indicates if the stream starts automatically as soon as it is initialized.\n * @return {boolean}\n */\n function getAutoPlay() {\n return autoPlay;\n }\n\n /**\n * Called once the first stream has been initialized. We only use this function to seek to the right start time.\n * @return {number}\n * @private\n */\n function _getInitialStartTime() {\n // Seek new stream in priority order:\n // - at start time provided in URI parameters\n // - at stream/period start time (for static streams) or live start time (for dynamic streams)\n let startTime;\n if (adapter.getIsDynamic()) {\n // For dynamic stream, start by default at (live edge - live delay)\n const dvrInfo = dashMetrics.getCurrentDVRInfo();\n const liveEdge = dvrInfo && dvrInfo.range ? dvrInfo.range.end : 0;\n // we are already in the right start period. so time should not be smaller than period@start and should not be larger than period@end\n startTime = liveEdge - playbackController.getLiveDelay();\n // If start time in URI, take min value between live edge time and time from URI (capped by DVR window range)\n const dvrWindow = dvrInfo ? dvrInfo.range : null;\n if (dvrWindow) {\n // #t shall be relative to period start\n const startTimeFromUri = _getStartTimeFromUriParameters(true);\n if (!isNaN(startTimeFromUri)) {\n logger.info('Start time from URI parameters: ' + startTimeFromUri);\n // If calcFromSegmentTimeline is enabled we saw problems caused by the MSE.seekableRange when starting at dvrWindow.start. Apply a small offset to avoid this problem.\n const offset = settings.get().streaming.timeShiftBuffer.calcFromSegmentTimeline ? 0.1 : 0;\n startTime = Math.max(Math.min(startTime, startTimeFromUri), dvrWindow.start + offset);\n }\n }\n } else {\n // For static stream, start by default at period start\n const streams = getStreams();\n const streamInfo = streams[0].getStreamInfo();\n startTime = streamInfo.start;\n // If start time in URI, take max value between period start and time from URI (if in period range)\n const startTimeFromUri = _getStartTimeFromUriParameters(false);\n if (!isNaN(startTimeFromUri)) {\n logger.info('Start time from URI parameters: ' + startTimeFromUri);\n startTime = Math.max(startTime, startTimeFromUri);\n }\n }\n\n return startTime;\n }\n\n /**\n * 23009-1 Annex C.4 defines MPD anchors to use URI fragment syntax to start a presentation at a given time and a given state\n * @param {boolean} isDynamic\n * @return {number}\n * @private\n */\n function _getStartTimeFromUriParameters(isDynamic) {\n const fragData = uriFragmentModel.getURIFragmentData();\n if (!fragData || !fragData.t) {\n return NaN;\n }\n const refStream = getStreams()[0];\n const refStreamStartTime = refStream.getStreamInfo().start;\n // Consider only start time of MediaRange\n // TODO: consider end time of MediaRange to stop playback at provided end time\n fragData.t = fragData.t.split(',')[0];\n // \"t=<time>\" : time is relative to 1st period start\n // \"t=posix:<time>\" : time is absolute start time as number of seconds since 01-01-1970\n const posix = fragData.t.indexOf('posix:') !== -1 ? fragData.t.substring(6) === 'now' ? Date.now() / 1000 : parseInt(fragData.t.substring(6)) : NaN;\n let startTime = (isDynamic && !isNaN(posix)) ? posix - playbackController.getAvailabilityStartTime() / 1000 : parseInt(fragData.t) + refStreamStartTime;\n return startTime;\n }\n\n /**\n * Streams that are no longer in the manifest can be filtered\n * @param {object} streamsInfo\n * @private\n */\n function _filterOutdatedStreams(streamsInfo) {\n streams = streams.filter((stream) => {\n const isStillIncluded = streamsInfo.filter((sInfo) => {\n return sInfo.id === stream.getId();\n }).length > 0;\n\n const shouldKeepStream = isStillIncluded || stream.getId() === activeStream.getId();\n\n if (!shouldKeepStream) {\n logger.debug(`Removing stream ${stream.getId()}`);\n stream.reset(true);\n }\n\n return shouldKeepStream;\n });\n }\n\n /**\n * In order to calculate the initial live delay we might required the duration of the segments.\n * @param {array} streamInfos\n * @param {object} manifestInfo\n * @return {number}\n * @private\n */\n function _getFragmentDurationForLiveDelayCalculation(streamInfos, manifestInfo) {\n try {\n let fragmentDuration = NaN;\n\n // We use the maxFragmentDuration attribute if present\n if (manifestInfo && !isNaN(manifestInfo.maxFragmentDuration) && isFinite(manifestInfo.maxFragmentDuration)) {\n return manifestInfo.maxFragmentDuration;\n }\n\n // For single period manifests we can iterate over all AS and use the maximum segment length\n if (streamInfos && streamInfos.length === 1) {\n const streamInfo = streamInfos[0];\n const mediaTypes = [Constants.VIDEO, Constants.AUDIO, Constants.TEXT];\n\n\n const fragmentDurations = mediaTypes\n .reduce((acc, mediaType) => {\n const mediaInfo = adapter.getMediaInfoForType(streamInfo, mediaType);\n\n if (mediaInfo && mediaInfo.isFragmented !== false) {\n acc.push(mediaInfo);\n }\n\n return acc;\n }, [])\n .reduce((acc, mediaInfo) => {\n const voRepresentations = adapter.getVoRepresentations(mediaInfo);\n\n if (voRepresentations && voRepresentations.length > 0) {\n voRepresentations.forEach((voRepresentation) => {\n if (voRepresentation) {\n acc.push(voRepresentation);\n }\n });\n }\n\n return acc;\n }, [])\n .reduce((acc, voRepresentation) => {\n const representation = adapter.convertRepresentationToRepresentationInfo(voRepresentation);\n\n if (representation && representation.fragmentDuration && !isNaN(representation.fragmentDuration)) {\n acc.push(representation.fragmentDuration);\n }\n\n return acc;\n }, []);\n\n fragmentDuration = Math.max(...fragmentDurations);\n }\n\n return isFinite(fragmentDuration) ? fragmentDuration : NaN;\n } catch (e) {\n return NaN;\n }\n }\n\n /**\n * Callback handler after the manifest has been updated. Trigger an update in the adapter and filter unsupported stuff.\n * Finally attempt UTC sync\n * @param {object} e\n * @private\n */\n function _onManifestUpdated(e) {\n if (!e.error) {\n logger.info('Manifest updated... updating data system wide.');\n //Since streams are not composed yet , need to manually look up useCalculatedLiveEdgeTime to detect if stream\n //is SegmentTimeline to avoid using time source\n const manifest = e.manifest;\n adapter.updatePeriods(manifest);\n\n let manifestUTCTimingSources = adapter.getUTCTimingSources();\n\n if (adapter.getIsDynamic() && (!manifestUTCTimingSources || manifestUTCTimingSources.length === 0)) {\n eventBus.trigger(MediaPlayerEvents.CONFORMANCE_VIOLATION, {\n level: ConformanceViolationConstants.LEVELS.WARNING,\n event: ConformanceViolationConstants.EVENTS.NO_UTC_TIMING_ELEMENT\n });\n }\n\n let allUTCTimingSources = (!adapter.getIsDynamic()) ? manifestUTCTimingSources : manifestUTCTimingSources.concat(mediaPlayerModel.getUTCTimingSources());\n const isHTTPS = urlUtils.isHTTPS(e.manifest.url);\n\n //If https is detected on manifest then lets apply that protocol to only the default time source(s). In the future we may find the need to apply this to more then just default so left code at this level instead of in MediaPlayer.\n allUTCTimingSources.forEach(function (item) {\n if (item.value.replace(/.*?:\\/\\//g, '') === mediaPlayerModel.getDefaultUtcTimingSource().value.replace(/.*?:\\/\\//g, '')) {\n item.value = item.value.replace(isHTTPS ? new RegExp(/^(http:)?\\/\\//i) : new RegExp(/^(https:)?\\/\\//i), isHTTPS ? 'https://' : 'http://');\n logger.debug('Matching default timing source protocol to manifest protocol: ', item.value);\n }\n });\n\n // It is important to filter before initializing the baseUrlController. Otherwise we might end up with wrong references in case we remove AdaptationSets.\n capabilitiesFilter.filterUnsupportedFeatures(manifest)\n .then(() => {\n baseURLController.initialize(manifest);\n timeSyncController.attemptSync(allUTCTimingSources, adapter.getIsDynamic());\n });\n } else {\n hasInitialisationError = true;\n reset();\n }\n }\n\n /**\n * Check if the stream has a video track\n * @return {boolean}\n */\n function hasVideoTrack() {\n return activeStream ? activeStream.getHasVideoTrack() : false;\n }\n\n /**\n * Check if the stream has an audio track\n * @return {boolean}\n */\n function hasAudioTrack() {\n return activeStream ? activeStream.getHasAudioTrack() : false;\n }\n\n\n function switchToVideoElement(seekTime) {\n if (activeStream) {\n playbackController.initialize(getActiveStreamInfo());\n _openMediaSource(seekTime, false);\n }\n }\n\n function _flushPlaylistMetrics(reason, time) {\n time = time || new Date();\n\n getActiveStreamProcessors().forEach(p => {\n p.finalisePlayList(time, reason);\n });\n dashMetrics.addPlayList();\n }\n\n function _createPlaylistMetrics(startReason) {\n dashMetrics.createPlaylistMetrics(playbackController.getTime() * 1000, startReason);\n }\n\n function _onPlaybackError(e) {\n if (!e.error) return;\n\n let msg = '';\n\n switch (e.error.code) {\n case 1:\n msg = 'MEDIA_ERR_ABORTED';\n break;\n case 2:\n msg = 'MEDIA_ERR_NETWORK';\n break;\n case 3:\n msg = 'MEDIA_ERR_DECODE';\n errorInformation.counts.mediaErrorDecode += 1;\n break;\n case 4:\n msg = 'MEDIA_ERR_SRC_NOT_SUPPORTED';\n break;\n case 5:\n msg = 'MEDIA_ERR_ENCRYPTED';\n break;\n default:\n msg = 'UNKNOWN';\n break;\n }\n\n\n if (msg === 'MEDIA_ERR_DECODE' && settings.get().errors.recoverAttempts.mediaErrorDecode >= errorInformation.counts.mediaErrorDecode) {\n _handleMediaErrorDecode();\n return;\n }\n\n hasMediaError = true;\n\n if (e.error.message) {\n msg += ' (' + e.error.message + ')';\n }\n\n if (e.error.msExtendedCode) {\n msg += ' (0x' + (e.error.msExtendedCode >>> 0).toString(16).toUpperCase() + ')';\n }\n\n logger.fatal('Video Element Error: ' + msg);\n if (e.error) {\n logger.fatal(e.error);\n }\n errHandler.error(new DashJSError(e.error.code, msg));\n reset();\n }\n\n /**\n * Handles mediaError\n * @private\n */\n function _handleMediaErrorDecode() {\n logger.warn('A MEDIA_ERR_DECODE occured: Resetting the MediaSource');\n const time = playbackController.getTime();\n // Deactivate the current stream.\n activeStream.deactivate(false);\n\n // Reset MSE\n logger.warn(`MediaSource has been resetted. Resuming playback from time ${time}`);\n _openMediaSource(time, false);\n }\n\n function getActiveStreamInfo() {\n return activeStream ? activeStream.getStreamInfo() : null;\n }\n\n function getIsStreamSwitchInProgress() {\n return isStreamSwitchingInProgress;\n }\n\n function getHasMediaOrInitialisationError() {\n return hasMediaError || hasInitialisationError;\n }\n\n function getStreamById(id) {\n for (let i = 0, ln = streams.length; i < ln; i++) {\n if (streams[i].getId() === id) {\n return streams[i];\n }\n }\n return null;\n }\n\n function _checkConfig() {\n if (!manifestLoader || !manifestLoader.hasOwnProperty('load') || !timelineConverter || !timelineConverter.hasOwnProperty('initialize') ||\n !timelineConverter.hasOwnProperty('reset') || !timelineConverter.hasOwnProperty('getClientTimeOffset') || !manifestModel || !errHandler ||\n !dashMetrics || !playbackController) {\n throw new Error(Constants.MISSING_CONFIG_ERROR);\n }\n }\n\n function _checkInitialize() {\n if (!manifestUpdater || !manifestUpdater.hasOwnProperty('setManifest')) {\n throw new Error('initialize function has to be called previously');\n }\n }\n\n function load(url) {\n _checkConfig();\n manifestLoader.load(url);\n }\n\n function loadWithManifest(manifest) {\n _checkInitialize();\n manifestUpdater.setManifest(manifest);\n }\n\n function _onManifestValidityChanged(e) {\n if (!isNaN(e.newDuration)) {\n _setMediaDuration(e.newDuration);\n }\n }\n\n function setConfig(config) {\n if (!config) return;\n\n if (config.capabilities) {\n capabilities = config.capabilities;\n }\n if (config.capabilitiesFilter) {\n capabilitiesFilter = config.capabilitiesFilter;\n }\n if (config.manifestLoader) {\n manifestLoader = config.manifestLoader;\n }\n if (config.manifestModel) {\n manifestModel = config.manifestModel;\n }\n if (config.mediaPlayerModel) {\n mediaPlayerModel = config.mediaPlayerModel;\n }\n if (config.protectionController) {\n protectionController = config.protectionController;\n }\n if (config.adapter) {\n adapter = config.adapter;\n }\n if (config.dashMetrics) {\n dashMetrics = config.dashMetrics;\n }\n if (config.errHandler) {\n errHandler = config.errHandler;\n }\n if (config.timelineConverter) {\n timelineConverter = config.timelineConverter;\n }\n if (config.videoModel) {\n videoModel = config.videoModel;\n }\n if (config.playbackController) {\n playbackController = config.playbackController;\n }\n if (config.textController) {\n textController = config.textController;\n }\n if (config.abrController) {\n abrController = config.abrController;\n }\n if (config.mediaController) {\n mediaController = config.mediaController;\n }\n if (config.settings) {\n settings = config.settings;\n }\n if (config.baseURLController) {\n baseURLController = config.baseURLController;\n }\n if (config.uriFragmentModel) {\n uriFragmentModel = config.uriFragmentModel;\n }\n if (config.segmentBaseController) {\n segmentBaseController = config.segmentBaseController;\n }\n }\n\n function setProtectionData(protData) {\n protectionData = protData;\n if (protectionController) {\n protectionController.setProtectionData(protectionData);\n }\n }\n\n function resetInitialSettings() {\n streams = [];\n protectionController = null;\n isStreamSwitchingInProgress = false;\n activeStream = null;\n hasMediaError = false;\n hasInitialisationError = false;\n initialPlayback = true;\n isPaused = false;\n autoPlay = true;\n playbackEndedTimerInterval = null;\n firstLicenseIsFetched = false;\n supportsChangeType = false;\n preloadingStreams = [];\n waitForPlaybackStartTimeout = null;\n errorInformation = {\n counts: {\n mediaErrorDecode: 0\n }\n }\n }\n\n function reset() {\n _checkConfig();\n\n timeSyncController.reset();\n\n _flushPlaylistMetrics(\n hasMediaError || hasInitialisationError ?\n PlayListTrace.FAILURE_STOP_REASON :\n PlayListTrace.USER_REQUEST_STOP_REASON\n );\n\n for (let i = 0, ln = streams ? streams.length : 0; i < ln; i++) {\n const stream = streams[i];\n stream.reset(hasMediaError);\n }\n\n unRegisterEvents();\n\n baseURLController.reset();\n manifestUpdater.reset();\n eventController.reset();\n dashMetrics.clearAllCurrentMetrics();\n manifestModel.setValue(null);\n manifestLoader.reset();\n timelineConverter.reset();\n initCache.reset();\n\n if (mediaSource) {\n mediaSourceController.detachMediaSource(videoModel);\n mediaSource = null;\n }\n videoModel = null;\n if (protectionController) {\n protectionController = null;\n protectionData = null;\n if (manifestModel.getValue()) {\n eventBus.trigger(Events.PROTECTION_DESTROYED, { data: manifestModel.getValue().url });\n }\n }\n\n _stopPlaybackEndedTimerInterval();\n eventBus.trigger(Events.STREAM_TEARDOWN_COMPLETE);\n resetInitialSettings();\n }\n\n function _onMetricAdded(e) {\n if (e.metric === MetricsConstants.DVR_INFO) {\n //Match media type? How can DVR window be different for media types?\n //Should we normalize and union the two?\n const targetMediaType = hasAudioTrack() ? Constants.AUDIO : Constants.VIDEO;\n if (e.mediaType === targetMediaType) {\n mediaSourceController.setSeekable(e.value.range.start, e.value.range.end);\n }\n }\n }\n\n function getStreams() {\n return streams;\n }\n\n instance = {\n initialize,\n getActiveStreamInfo,\n addDVRMetric,\n hasVideoTrack,\n hasAudioTrack,\n getStreamById,\n getStreamForTime,\n getTimeRelativeToStreamId,\n load,\n loadWithManifest,\n getActiveStreamProcessors,\n setConfig,\n setProtectionData,\n getIsStreamSwitchInProgress,\n switchToVideoElement,\n getHasMediaOrInitialisationError,\n getStreams,\n getActiveStream,\n getInitialPlayback,\n getAutoPlay,\n reset\n };\n\n setup();\n\n return instance;\n}\n\nStreamController.__dashjs_factory_name = 'StreamController';\nexport default FactoryMaker.getSingletonFactory(StreamController);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Debug from '../../core/Debug';\nimport Events from '../../core/events/Events';\nimport EventBus from '../../core/EventBus';\n\nconst GAP_HANDLER_INTERVAL = 100;\nconst THRESHOLD_TO_STALLS = 10;\nconst GAP_JUMP_WAITING_TIME_OFFSET = 0.1;\n\nfunction GapController() {\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n\n let instance,\n lastPlaybackTime,\n settings,\n wallclockTicked,\n gapHandlerInterval,\n lastGapJumpPosition,\n playbackController,\n streamController,\n videoModel,\n jumpTimeoutHandler,\n trackSwitchByMediaType,\n logger;\n\n function initialize() {\n _registerEvents();\n }\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n\n reset();\n }\n\n function reset() {\n _stopGapHandler();\n _unregisterEvents();\n resetInitialSettings();\n }\n\n function resetInitialSettings() {\n gapHandlerInterval = null;\n lastGapJumpPosition = NaN;\n wallclockTicked = 0;\n jumpTimeoutHandler = null;\n trackSwitchByMediaType = {};\n }\n\n function setConfig(config) {\n if (!config) {\n return;\n }\n if (config.settings) {\n settings = config.settings;\n }\n if (config.playbackController) {\n playbackController = config.playbackController;\n }\n if (config.streamController) {\n streamController = config.streamController;\n }\n if (config.videoModel) {\n videoModel = config.videoModel;\n }\n }\n\n function _registerEvents() {\n eventBus.on(Events.WALLCLOCK_TIME_UPDATED, _onWallclockTimeUpdated, this);\n eventBus.on(Events.INITIAL_STREAM_SWITCH, _onInitialStreamSwitch, this);\n eventBus.on(Events.PLAYBACK_SEEKING, _onPlaybackSeeking, this);\n eventBus.on(Events.BUFFER_REPLACEMENT_STARTED, _onBufferReplacementStarted, instance);\n eventBus.on(Events.TRACK_CHANGE_RENDERED, _onBufferReplacementEnded, instance);\n }\n\n function _unregisterEvents() {\n eventBus.off(Events.WALLCLOCK_TIME_UPDATED, _onWallclockTimeUpdated, this);\n eventBus.off(Events.INITIAL_STREAM_SWITCH, _onInitialStreamSwitch, this);\n eventBus.off(Events.PLAYBACK_SEEKING, _onPlaybackSeeking, this);\n eventBus.off(Events.BUFFER_REPLACEMENT_STARTED, _onBufferReplacementStarted, instance);\n eventBus.off(Events.TRACK_CHANGE_RENDERED, _onBufferReplacementEnded, instance);\n }\n\n /**\n * Clear scheduled gap jump when seeking\n * @private\n */\n function _onPlaybackSeeking() {\n if (jumpTimeoutHandler) {\n clearTimeout(jumpTimeoutHandler);\n jumpTimeoutHandler = null;\n }\n }\n\n /**\n * If the track was changed in the current active period and the player might aggressively replace segments the buffer will be empty for a short period of time. Avoid gap jumping at that time.\n * We wait until the next media fragment of the target type has been appended before activating again\n * @param {object} e\n * @private\n */\n function _onBufferReplacementStarted(e) {\n try {\n if (e.streamId !== streamController.getActiveStreamInfo().id || !e.mediaType) {\n return;\n }\n\n if (e.streamId === streamController.getActiveStreamInfo().id) {\n trackSwitchByMediaType[e.mediaType] = true;\n }\n } catch (e) {\n logger.error(e);\n }\n }\n\n /**\n * Activate gap jumping again once segment of target type has been appended\n * @param {object} e\n * @private\n */\n function _onBufferReplacementEnded(e) {\n if (!e || !e.mediaType) {\n return;\n }\n\n trackSwitchByMediaType[e.mediaType] = false;\n }\n\n /**\n * Activate the gap handler after the first stream switch\n * @private\n */\n function _onInitialStreamSwitch() {\n if (!gapHandlerInterval) {\n _startGapHandler();\n }\n }\n\n /**\n * Callback handler for when the wallclock time has been updated\n * @private\n */\n function _onWallclockTimeUpdated(/*e*/) {\n if (!_shouldCheckForGaps(settings.get().streaming.gaps.enableSeekFix)) {\n return;\n }\n\n wallclockTicked++;\n if (wallclockTicked >= THRESHOLD_TO_STALLS) {\n const currentTime = playbackController.getTime();\n if (lastPlaybackTime === currentTime) {\n _jumpGap(currentTime, true);\n } else {\n lastPlaybackTime = currentTime;\n lastGapJumpPosition = NaN;\n }\n wallclockTicked = 0;\n }\n }\n\n /**\n * Returns if we are supposed to check for gaps\n * @param {boolean} checkSeekingState - Usually we are not checking for gaps in the videolement is in seeking state. If this flag is set to true we check for a potential exceptions of this rule.\n * @return {boolean}\n * @private\n */\n function _shouldCheckForGaps(checkSeekingState = false) {\n if (!streamController.getActiveStream()) {\n return false;\n }\n const trackSwitchInProgress = Object.keys(trackSwitchByMediaType).some((key) => {\n return trackSwitchByMediaType[key];\n });\n const shouldIgnoreSeekingState = checkSeekingState ? _shouldIgnoreSeekingState() : false;\n\n return !trackSwitchInProgress && settings.get().streaming.gaps.jumpGaps && streamController.getActiveStreamProcessors().length > 0 && (!playbackController.isSeeking() || shouldIgnoreSeekingState) && !playbackController.isPaused() && !streamController.getIsStreamSwitchInProgress() &&\n !streamController.getHasMediaOrInitialisationError();\n }\n\n /**\n * There are cases in which we never transition out of the seeking state and still need to jump a gap. For instance if the user seeks right before a gap and video element will not transition out of the seeking state.\n * For now limit this to period boundaries. In this case the current period is completely buffered and we are right before the end of the period.\n * @private\n */\n function _shouldIgnoreSeekingState() {\n const activeStream = streamController.getActiveStream();\n const streamEnd = parseFloat((activeStream.getStartTime() + activeStream.getDuration()).toFixed(5))\n\n return playbackController.getTime() + settings.get().streaming.gaps.threshold >= streamEnd;\n }\n\n /**\n * Returns the index of the range object that comes after the current time\n * @param {object} ranges\n * @param {number} currentTime\n * @private\n * @return {null|number}\n */\n function _getNextRangeIndex(ranges, currentTime) {\n try {\n\n if (!ranges || (ranges.length <= 1 && currentTime > 0)) {\n return NaN;\n }\n let nextRangeIndex = NaN;\n let j = 0;\n\n while (isNaN(nextRangeIndex) && j < ranges.length) {\n const rangeEnd = j > 0 ? ranges.end(j - 1) : 0;\n if (currentTime < ranges.start(j) && rangeEnd - currentTime < settings.get().streaming.gaps.threshold) {\n nextRangeIndex = j;\n }\n j += 1;\n }\n return nextRangeIndex;\n\n } catch (e) {\n return null;\n }\n }\n\n /**\n * Starts the interval that checks for gaps\n * @private\n */\n function _startGapHandler() {\n try {\n if (!gapHandlerInterval) {\n logger.debug('Starting the gap controller');\n gapHandlerInterval = setInterval(() => {\n if (!_shouldCheckForGaps()) {\n return;\n }\n const currentTime = playbackController.getTime();\n _jumpGap(currentTime);\n\n }, GAP_HANDLER_INTERVAL);\n }\n } catch (e) {\n }\n }\n\n /**\n * Clears the gap interval handler\n * @private\n */\n function _stopGapHandler() {\n logger.debug('Stopping the gap controller');\n if (gapHandlerInterval) {\n clearInterval(gapHandlerInterval);\n gapHandlerInterval = null;\n }\n }\n\n /**\n * Jump a gap\n * @param {number} currentTime\n * @param {boolean} playbackStalled\n * @private\n */\n function _jumpGap(currentTime, playbackStalled = false) {\n const smallGapLimit = settings.get().streaming.gaps.smallGapLimit;\n const jumpLargeGaps = settings.get().streaming.gaps.jumpLargeGaps;\n const ranges = videoModel.getBufferRange();\n let nextRangeIndex;\n let seekToPosition = NaN;\n let jumpToStreamEnd = false;\n\n\n // Get the range just after current time position\n nextRangeIndex = _getNextRangeIndex(ranges, currentTime);\n\n if (!isNaN(nextRangeIndex)) {\n const start = ranges.start(nextRangeIndex);\n const gap = start - currentTime;\n if (gap > 0 && (gap <= smallGapLimit || jumpLargeGaps)) {\n seekToPosition = start;\n }\n }\n\n // Playback has stalled before period end. We seek to the end of the period\n const timeToStreamEnd = playbackController.getTimeToStreamEnd();\n if (isNaN(seekToPosition) && playbackStalled && isFinite(timeToStreamEnd) && !isNaN(timeToStreamEnd) && timeToStreamEnd < smallGapLimit) {\n seekToPosition = parseFloat(playbackController.getStreamEndTime().toFixed(5));\n jumpToStreamEnd = true;\n }\n\n if (seekToPosition > 0 && lastGapJumpPosition !== seekToPosition && seekToPosition > currentTime && !jumpTimeoutHandler) {\n const timeUntilGapEnd = seekToPosition - currentTime;\n\n if (jumpToStreamEnd) {\n const nextStream = streamController.getStreamForTime(seekToPosition);\n const internalSeek = nextStream && !!nextStream.getPreloaded();\n\n logger.warn(`Jumping to end of stream because of gap from ${currentTime} to ${seekToPosition}. Gap duration: ${timeUntilGapEnd}`);\n playbackController.seek(seekToPosition, true, internalSeek);\n } else {\n const isDynamic = playbackController.getIsDynamic();\n const start = nextRangeIndex > 0 ? ranges.end(nextRangeIndex - 1) : currentTime;\n const timeToWait = !isDynamic ? 0 : Math.max(0, timeUntilGapEnd - GAP_JUMP_WAITING_TIME_OFFSET) * 1000;\n\n jumpTimeoutHandler = window.setTimeout(() => {\n playbackController.seek(seekToPosition, true, true);\n logger.warn(`Jumping gap occuring in period ${streamController.getActiveStream().getStreamId()} starting at ${start} and ending at ${seekToPosition}. Jumping by: ${timeUntilGapEnd - (timeToWait / 1000)}`);\n jumpTimeoutHandler = null;\n }, timeToWait);\n }\n lastGapJumpPosition = seekToPosition;\n }\n }\n\n instance = {\n reset,\n setConfig,\n initialize\n };\n\n setup();\n\n return instance;\n}\n\nGapController.__dashjs_factory_name = 'GapController';\nexport default FactoryMaker.getSingletonFactory(GapController);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Constants from '../constants/Constants';\nimport Events from '../../core/events/Events';\nimport EventBus from '../../core/EventBus';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Debug from '../../core/Debug';\n\nfunction MediaController() {\n\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n\n let instance,\n logger,\n tracks,\n settings,\n initialSettings,\n lastSelectedTracks,\n domStorage,\n customInitialTrackSelectionFunction;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n reset();\n }\n\n /**\n * @param {string} type\n * @param {StreamInfo} streamInfo\n * @memberof MediaController#\n */\n function setInitialMediaSettingsForType(type, streamInfo) {\n let settings = lastSelectedTracks[type] || getInitialSettings(type);\n const tracksForType = getTracksFor(type, streamInfo.id);\n const tracks = [];\n\n if (!settings) {\n settings = domStorage.getSavedMediaSettings(type);\n setInitialSettings(type, settings);\n }\n\n if (!tracksForType || (tracksForType.length === 0)) return;\n\n if (settings) {\n tracksForType.forEach(function (track) {\n if (matchSettings(settings, track, !!lastSelectedTracks[type])) {\n tracks.push(track);\n }\n });\n }\n\n if (tracks.length === 0) {\n setTrack(selectInitialTrack(type, tracksForType), true);\n } else {\n if (tracks.length > 1) {\n setTrack(selectInitialTrack(type, tracks, !!lastSelectedTracks[type]));\n } else {\n setTrack(tracks[0]);\n }\n }\n }\n\n /**\n * @param {MediaInfo} track\n * @memberof MediaController#\n */\n function addTrack(track) {\n if (!track) return;\n\n const mediaType = track.type;\n if (!_isMultiTrackSupportedByType(mediaType)) return;\n\n let streamId = track.streamInfo.id;\n if (!tracks[streamId]) {\n tracks[streamId] = createTrackInfo();\n }\n\n const mediaTracks = tracks[streamId][mediaType].list;\n for (let i = 0, len = mediaTracks.length; i < len; ++i) {\n //track is already set.\n if (isTracksEqual(mediaTracks[i], track)) {\n return;\n }\n }\n\n mediaTracks.push(track);\n }\n\n /**\n * @param {string} type\n * @param {string} streamId\n * @returns {Array}\n * @memberof MediaController#\n */\n function getTracksFor(type, streamId) {\n if (!type) return [];\n\n if (!tracks[streamId] || !tracks[streamId][type]) return [];\n\n return tracks[streamId][type].list;\n }\n\n /**\n * @param {string} type\n * @param {string} streamId\n * @returns {Object|null}\n * @memberof MediaController#\n */\n function getCurrentTrackFor(type, streamId) {\n if (!type || !tracks[streamId] || !tracks[streamId][type]) return null;\n return tracks[streamId][type].current;\n }\n\n /**\n * @param {MediaInfo} track\n * @returns {boolean}\n * @memberof MediaController#\n */\n function isCurrentTrack(track) {\n if (!track) {\n return false;\n }\n const type = track.type;\n const id = track.streamInfo.id;\n\n return (tracks[id] && tracks[id][type] && isTracksEqual(tracks[id][type].current, track));\n }\n\n /**\n * @param {MediaInfo} track\n * @param {boolean} noSettingsSave specify if settings must be not be saved\n * @memberof MediaController#\n */\n function setTrack(track, noSettingsSave = false) {\n if (!track || !track.streamInfo) return;\n\n const type = track.type;\n const streamInfo = track.streamInfo;\n const id = streamInfo.id;\n const current = getCurrentTrackFor(type, id);\n\n if (!tracks[id] || !tracks[id][type] || isTracksEqual(track, current)) return;\n\n tracks[id][type].current = track;\n\n if (tracks[id][type].current && (type !== Constants.TEXT || (type === Constants.TEXT && track.isFragmented))) {\n eventBus.trigger(Events.CURRENT_TRACK_CHANGED, {\n oldMediaInfo: current,\n newMediaInfo: track,\n switchMode: settings.get().streaming.trackSwitchMode[type]\n }, { streamId: id });\n }\n\n if (!noSettingsSave) {\n\n let settings = extractSettings(track);\n\n if (!settings || !tracks[id][type].storeLastSettings) return;\n\n if (settings.roles) {\n settings.role = settings.roles[0];\n delete settings.roles;\n }\n\n if (settings.accessibility) {\n settings.accessibility = settings.accessibility[0];\n }\n\n if (settings.audioChannelConfiguration) {\n settings.audioChannelConfiguration = settings.audioChannelConfiguration[0];\n }\n\n lastSelectedTracks[type] = settings;\n domStorage.setSavedMediaSettings(type, settings);\n }\n }\n\n /**\n * @param {string} type\n * @param {Object} value\n * @memberof MediaController#\n */\n function setInitialSettings(type, value) {\n if (!type || !value) return;\n\n initialSettings[type] = value;\n }\n\n /**\n * @param {string} type\n * @returns {Object|null}\n * @memberof MediaController#\n */\n function getInitialSettings(type) {\n if (!type) return null;\n\n return initialSettings[type];\n }\n\n /**\n * @memberof MediaController#\n */\n function saveTextSettingsDisabled() {\n domStorage.setSavedMediaSettings(Constants.TEXT, null);\n }\n\n /**\n * @param {string} type\n * @returns {boolean}\n * @memberof MediaController#\n */\n function _isMultiTrackSupportedByType(type) {\n return (type === Constants.AUDIO || type === Constants.VIDEO || type === Constants.TEXT || type === Constants.IMAGE);\n }\n\n /**\n * @param {MediaInfo} t1 - first track to compare\n * @param {MediaInfo} t2 - second track to compare\n * @returns {boolean}\n * @memberof MediaController#\n */\n function isTracksEqual(t1, t2) {\n if (!t1 && !t2) {\n return true;\n }\n\n if (!t1 || !t2) {\n return false;\n }\n\n const sameId = t1.id === t2.id;\n const sameViewpoint = t1.viewpoint === t2.viewpoint;\n const sameLang = t1.lang === t2.lang;\n const sameCodec = t1.codec === t2.codec;\n const sameRoles = t1.roles.toString() === t2.roles.toString();\n const sameAccessibility = t1.accessibility.toString() === t2.accessibility.toString();\n const sameAudioChannelConfiguration = t1.audioChannelConfiguration.toString() === t2.audioChannelConfiguration.toString();\n\n return (sameId && sameCodec && sameViewpoint && sameLang && sameRoles && sameAccessibility && sameAudioChannelConfiguration);\n }\n\n function setConfig(config) {\n if (!config) return;\n\n if (config.domStorage) {\n domStorage = config.domStorage;\n }\n\n if (config.settings) {\n settings = config.settings;\n }\n }\n\n /**\n * @memberof MediaController#\n */\n function reset() {\n tracks = {};\n lastSelectedTracks = {};\n resetInitialSettings();\n }\n\n function extractSettings(mediaInfo) {\n const settings = {\n lang: mediaInfo.lang,\n viewpoint: mediaInfo.viewpoint,\n roles: mediaInfo.roles,\n accessibility: mediaInfo.accessibility,\n audioChannelConfiguration: mediaInfo.audioChannelConfiguration\n };\n let notEmpty = settings.lang || settings.viewpoint || (settings.role && settings.role.length > 0) ||\n (settings.accessibility && settings.accessibility.length > 0) || (settings.audioChannelConfiguration && settings.audioChannelConfiguration.length > 0);\n\n return notEmpty ? settings : null;\n }\n\n function matchSettings(settings, track, isTrackActive = false) {\n const matchLang = !settings.lang || (track.lang.match(settings.lang));\n const matchIndex = (settings.index === undefined) || (settings.index === null) || (track.index === settings.index);\n const matchViewPoint = !settings.viewpoint || (settings.viewpoint === track.viewpoint);\n const matchRole = !settings.role || !!track.roles.filter(function (item) {\n return item === settings.role;\n })[0];\n let matchAccessibility = !settings.accessibility || !!track.accessibility.filter(function (item) {\n return item === settings.accessibility;\n })[0];\n let matchAudioChannelConfiguration = !settings.audioChannelConfiguration || !!track.audioChannelConfiguration.filter(function (item) {\n return item === settings.audioChannelConfiguration;\n })[0];\n\n\n return (matchLang && matchIndex && matchViewPoint && (matchRole || (track.type === Constants.AUDIO && isTrackActive)) && matchAccessibility && matchAudioChannelConfiguration);\n }\n\n function resetInitialSettings() {\n initialSettings = {\n audio: null,\n video: null,\n text: null\n };\n }\n\n function getTracksWithHighestSelectionPriority(trackArr) {\n let max = 0;\n let result = [];\n\n trackArr.forEach((track) => {\n if(!isNaN(track.selectionPriority)) {\n // Higher max value. Reset list and add new entry\n if (track.selectionPriority > max) {\n max = track.selectionPriority;\n result = [track];\n }\n // Same max value add to list\n else if (track.selectionPriority === max) {\n result.push(track);\n }\n\n }\n })\n\n return result;\n }\n\n function getTracksWithHighestBitrate(trackArr) {\n let max = 0;\n let result = [];\n let tmp;\n\n trackArr.forEach(function (track) {\n tmp = Math.max.apply(Math, track.bitrateList.map(function (obj) {\n return obj.bandwidth;\n }));\n\n if (tmp > max) {\n max = tmp;\n result = [track];\n } else if (tmp === max) {\n result.push(track);\n }\n });\n\n return result;\n }\n\n function getTracksWithHighestEfficiency(trackArr) {\n let min = Infinity;\n let result = [];\n let tmp;\n\n trackArr.forEach(function (track) {\n const sum = track.bitrateList.reduce(function (acc, obj) {\n const resolution = Math.max(1, obj.width * obj.height);\n const efficiency = obj.bandwidth / resolution;\n return acc + efficiency;\n }, 0);\n tmp = sum / track.bitrateList.length;\n\n if (tmp < min) {\n min = tmp;\n result = [track];\n } else if (tmp === min) {\n result.push(track);\n }\n });\n\n return result;\n }\n\n function getTracksWithWidestRange(trackArr) {\n let max = 0;\n let result = [];\n let tmp;\n\n trackArr.forEach(function (track) {\n tmp = track.representationCount;\n\n if (tmp > max) {\n max = tmp;\n result = [track];\n } else if (tmp === max) {\n result.push(track);\n }\n });\n\n return result;\n }\n\n function setCustomInitialTrackSelectionFunction(customFunc) {\n customInitialTrackSelectionFunction = customFunc;\n }\n\n function selectInitialTrack(type, tracks) {\n if (type === Constants.TEXT) return tracks[0];\n\n let mode = settings.get().streaming.selectionModeForInitialTrack;\n let tmpArr;\n\n if (customInitialTrackSelectionFunction && typeof customInitialTrackSelectionFunction === 'function') {\n tmpArr = customInitialTrackSelectionFunction(tracks);\n } else {\n switch (mode) {\n case Constants.TRACK_SELECTION_MODE_HIGHEST_SELECTION_PRIORITY:\n tmpArr = _trackSelectionModeHighestSelectionPriority(tracks);\n break;\n case Constants.TRACK_SELECTION_MODE_HIGHEST_BITRATE:\n tmpArr = _trackSelectionModeHighestBitrate(tracks);\n break;\n case Constants.TRACK_SELECTION_MODE_FIRST_TRACK:\n tmpArr = _trackSelectionModeFirstTrack(tracks);\n break;\n case Constants.TRACK_SELECTION_MODE_HIGHEST_EFFICIENCY:\n tmpArr = _trackSelectionModeHighestEfficiency(tracks);\n break;\n case Constants.TRACK_SELECTION_MODE_WIDEST_RANGE:\n tmpArr = _trackSelectionModeWidestRange(tracks);\n break;\n default:\n logger.warn(`Track selection mode ${mode} is not supported. Falling back to TRACK_SELECTION_MODE_FIRST_TRACK`);\n tmpArr = _trackSelectionModeFirstTrack(tracks);\n break;\n }\n }\n\n return tmpArr.length > 0 ? tmpArr[0] : tracks[0];\n }\n\n\n function _trackSelectionModeHighestSelectionPriority(tracks) {\n let tmpArr = getTracksWithHighestSelectionPriority(tracks);\n\n if (tmpArr.length > 1) {\n tmpArr = getTracksWithHighestBitrate(tmpArr);\n }\n\n if (tmpArr.length > 1) {\n tmpArr = getTracksWithWidestRange(tmpArr);\n }\n\n return tmpArr;\n }\n\n function _trackSelectionModeHighestBitrate(tracks) {\n let tmpArr = getTracksWithHighestBitrate(tracks);\n\n if (tmpArr.length > 1) {\n tmpArr = getTracksWithWidestRange(tmpArr);\n }\n\n return tmpArr;\n }\n\n function _trackSelectionModeFirstTrack(tracks) {\n return tracks[0];\n }\n\n function _trackSelectionModeHighestEfficiency(tracks) {\n let tmpArr = getTracksWithHighestEfficiency(tracks);\n\n if (tmpArr.length > 1) {\n tmpArr = getTracksWithHighestBitrate(tmpArr);\n }\n\n return tmpArr;\n }\n\n function _trackSelectionModeWidestRange(tracks) {\n let tmpArr = getTracksWithWidestRange(tracks);\n\n if (tmpArr.length > 1) {\n tmpArr = getTracksWithHighestBitrate(tracks);\n }\n\n return tmpArr;\n }\n\n\n function createTrackInfo() {\n return {\n audio: {\n list: [],\n storeLastSettings: true,\n current: null\n },\n video: {\n list: [],\n storeLastSettings: true,\n current: null\n },\n text: {\n list: [],\n storeLastSettings: true,\n current: null\n },\n image: {\n list: [],\n storeLastSettings: true,\n current: null\n }\n };\n }\n\n instance = {\n setInitialMediaSettingsForType,\n addTrack,\n getTracksFor,\n getCurrentTrackFor,\n isCurrentTrack,\n setTrack,\n selectInitialTrack,\n setCustomInitialTrackSelectionFunction,\n setInitialSettings,\n getInitialSettings,\n getTracksWithHighestBitrate,\n getTracksWithHighestEfficiency,\n getTracksWithWidestRange,\n isTracksEqual,\n matchSettings,\n saveTextSettingsDisabled,\n setConfig,\n reset\n };\n\n setup();\n\n return instance;\n}\n\nMediaController.__dashjs_factory_name = 'MediaController';\nconst factory = FactoryMaker.getSingletonFactory(MediaController);\nFactoryMaker.updateSingletonFactory(MediaController.__dashjs_factory_name, factory);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport ObjectUtils from '../utils/ObjectUtils';\nimport FactoryMaker from '../../core/FactoryMaker';\n\nconst DEFAULT_INDEX = NaN;\n\nclass Node {\n constructor(_baseUrls, _selectedIdx) {\n this.data = {\n baseUrls: _baseUrls || null,\n selectedIdx: _selectedIdx || DEFAULT_INDEX\n };\n this.children = [];\n }\n}\n\nfunction BaseURLTreeModel() {\n let instance,\n root,\n adapter;\n\n const context = this.context;\n const objectUtils = ObjectUtils(context).getInstance();\n\n function setup() {\n reset();\n }\n\n function setConfig(config) {\n if (config.adapter) {\n adapter = config.adapter;\n }\n }\n\n function checkConfig() {\n if (!adapter || !adapter.hasOwnProperty('getBaseURLsFromElement') || !adapter.hasOwnProperty('getRepresentationSortFunction')) {\n throw new Error('setConfig function has to be called previously');\n }\n }\n\n function updateChildData(node, index, element) {\n const baseUrls = adapter.getBaseURLsFromElement(element);\n\n if (!node[index]) {\n node[index] = new Node(baseUrls);\n } else {\n if (!objectUtils.areEqual(baseUrls, node[index].data.baseUrls)) {\n node[index].data.baseUrls = baseUrls;\n node[index].data.selectedIdx = DEFAULT_INDEX;\n }\n }\n }\n\n function getBaseURLCollectionsFromManifest(manifest) {\n checkConfig();\n const baseUrls = adapter.getBaseURLsFromElement(manifest);\n\n if (!objectUtils.areEqual(baseUrls, root.data.baseUrls)) {\n root.data.baseUrls = baseUrls;\n root.data.selectedIdx = DEFAULT_INDEX;\n }\n\n if (manifest && manifest.Period_asArray) {\n manifest.Period_asArray.forEach((p, pi) => {\n updateChildData(root.children, pi, p);\n\n if (p.AdaptationSet_asArray) {\n p.AdaptationSet_asArray.forEach((a, ai) => {\n updateChildData(root.children[pi].children, ai, a);\n\n if (a.Representation_asArray) {\n a.Representation_asArray.sort(\n adapter.getRepresentationSortFunction()\n ).forEach((r, ri) => {\n updateChildData(\n root.children[pi].children[ai].children,\n ri,\n r\n );\n });\n }\n });\n }\n });\n }\n }\n\n function walk(callback, node) {\n const target = node || root;\n\n callback(target.data);\n\n if (target.children) {\n target.children.forEach(child => walk(callback, child));\n }\n }\n\n function invalidateSelectedIndexes(serviceLocation) {\n walk((data) => {\n if (!isNaN(data.selectedIdx)) {\n if (serviceLocation === data.baseUrls[data.selectedIdx].serviceLocation) {\n data.selectedIdx = DEFAULT_INDEX;\n }\n }\n });\n }\n\n function update(manifest) {\n getBaseURLCollectionsFromManifest(manifest);\n }\n\n function reset() {\n root = new Node();\n }\n\n function getForPath(path) {\n let target = root;\n const nodes = [target.data];\n\n if (path) {\n path.forEach(p => {\n target = target.children[p];\n\n if (target) {\n nodes.push(target.data);\n }\n });\n }\n\n return nodes.filter(n => n.baseUrls.length);\n }\n\n instance = {\n reset: reset,\n update: update,\n getForPath: getForPath,\n invalidateSelectedIndexes: invalidateSelectedIndexes,\n setConfig: setConfig\n };\n\n setup();\n\n return instance;\n}\n\nBaseURLTreeModel.__dashjs_factory_name = 'BaseURLTreeModel';\nexport default FactoryMaker.getClassFactory(BaseURLTreeModel);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport FactoryMaker from '../../../core/FactoryMaker';\n\nfunction DVBSelector(config) {\n\n config = config || {};\n let instance;\n\n const blacklistController = config.blacklistController;\n\n function getNonBlacklistedBaseUrls(urls) {\n let removedPriorities = [];\n\n const samePrioritiesFilter = function (el) {\n if (removedPriorities.length) {\n if ((el.dvb_priority) &&\n (removedPriorities.indexOf(el.dvb_priority) !== -1)) {\n return false;\n }\n }\n\n return true;\n };\n\n const serviceLocationFilter = function (baseUrl) {\n if (blacklistController.contains(baseUrl.serviceLocation)) {\n // whenever a BaseURL is removed from the available list of\n // BaseURLs, any other BaseURL with the same @priority\n // value as the BaseURL being removed shall also be removed\n if (baseUrl.dvb_priority) {\n removedPriorities.push(baseUrl.dvb_priority);\n }\n\n // all URLs in the list which have a @serviceLocation\n // attribute matching an entry in the blacklist shall be\n // removed from the available list of BaseURLs\n return false;\n }\n\n return true;\n };\n\n return urls.filter(serviceLocationFilter).filter(samePrioritiesFilter);\n }\n\n function selectByWeight(availableUrls) {\n const prioritySorter = function (a, b) {\n let diff = a.dvb_priority - b.dvb_priority;\n return isNaN(diff) ? 0 : diff;\n };\n\n const topPriorityFilter = function (baseUrl, idx, arr) {\n return !idx || (\n (arr[0].dvb_priority && baseUrl.dvb_priority) &&\n (arr[0].dvb_priority === baseUrl.dvb_priority)\n );\n };\n\n let totalWeight = 0;\n let cumulWeights = [];\n let idx = 0;\n let rn,\n urls;\n\n // It shall begin by taking the set of resolved BaseURLs present or inherited at the current\n // position in the MPD, resolved and filtered as described in 10.8.2.1, that have the lowest\n // @priority attribute value.\n urls = availableUrls.sort(prioritySorter).filter(topPriorityFilter);\n\n if (urls.length) {\n if (urls.length > 1) {\n // If there is more than one BaseURL with this lowest @priority attribute value then the Player\n // shall select one of them at random such that the probability of each BaseURL being chosen\n // is proportional to the value of its @weight attribute. The method described in RFC 2782\n // [26] or picking from a number of weighted entries is suitable for this, but there may be other\n // algorithms which achieve the same effect.\n\n // add all the weights together, storing the accumulated weight per entry\n urls.forEach(baseUrl => {\n totalWeight += baseUrl.dvb_weight;\n cumulWeights.push(totalWeight);\n });\n\n // pick a random number between zero and totalWeight\n rn = Math.floor(Math.random() * (totalWeight - 1));\n\n // select the index for the range rn falls within\n cumulWeights.every((limit, index) => {\n idx = index;\n\n if (rn < limit) {\n return false;\n }\n\n return true;\n });\n }\n\n return urls[idx];\n }\n }\n\n function select(baseUrls) {\n return baseUrls && selectByWeight(\n getNonBlacklistedBaseUrls(\n baseUrls\n )\n );\n }\n\n instance = {\n select: select\n };\n\n return instance;\n}\n\nDVBSelector.__dashjs_factory_name = 'DVBSelector';\nexport default FactoryMaker.getClassFactory(DVBSelector);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport FactoryMaker from '../../../core/FactoryMaker';\n\nfunction BasicSelector(config) {\n\n config = config || {};\n let instance;\n\n const blacklistController = config.blacklistController;\n\n function select(baseUrls) {\n let index = 0;\n let selectedBaseUrl;\n\n if (baseUrls && baseUrls.some((baseUrl, idx) => {\n index = idx;\n\n return (!blacklistController.contains(baseUrl.serviceLocation));\n })) {\n selectedBaseUrl = baseUrls[index];\n }\n\n return selectedBaseUrl;\n }\n\n instance = {\n select: select\n };\n\n return instance;\n}\n\nBasicSelector.__dashjs_factory_name = 'BasicSelector';\nexport default FactoryMaker.getClassFactory(BasicSelector);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport Errors from '../../core/errors/Errors';\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\nimport BlacklistController from '../controllers/BlacklistController';\nimport DVBSelector from './baseUrlResolution/DVBSelector';\nimport BasicSelector from './baseUrlResolution/BasicSelector';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport DashJSError from '../vo/DashJSError';\nimport { checkParameterType } from '../utils/SupervisorTools';\n\nfunction BaseURLSelector() {\n\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n\n let instance,\n serviceLocationBlacklistController,\n basicSelector,\n dvbSelector,\n selector;\n\n function setup() {\n serviceLocationBlacklistController = BlacklistController(context).create({\n updateEventName: Events.SERVICE_LOCATION_BLACKLIST_CHANGED,\n addBlacklistEventName: Events.SERVICE_LOCATION_BLACKLIST_ADD\n });\n\n basicSelector = BasicSelector(context).create({\n blacklistController: serviceLocationBlacklistController\n });\n\n dvbSelector = DVBSelector(context).create({\n blacklistController: serviceLocationBlacklistController\n });\n\n selector = basicSelector;\n }\n\n function setConfig(config) {\n if (config.selector) {\n selector = config.selector;\n }\n }\n\n function chooseSelector(isDVB) {\n checkParameterType(isDVB, 'boolean');\n selector = isDVB ? dvbSelector : basicSelector;\n }\n\n function select(data) {\n if (!data) {\n return;\n }\n const baseUrls = data.baseUrls;\n const selectedIdx = data.selectedIdx;\n\n // Once a random selection has been carried out amongst a group of BaseURLs with the same\n // @priority attribute value, then that choice should be re-used if the selection needs to be made again\n // unless the blacklist has been modified or the available BaseURLs have changed.\n if (!isNaN(selectedIdx)) {\n return baseUrls[selectedIdx];\n }\n\n let selectedBaseUrl = selector.select(baseUrls);\n\n if (!selectedBaseUrl) {\n eventBus.trigger(Events.URL_RESOLUTION_FAILED, {\n error: new DashJSError(\n Errors.URL_RESOLUTION_FAILED_GENERIC_ERROR_CODE,\n Errors.URL_RESOLUTION_FAILED_GENERIC_ERROR_MESSAGE\n )\n });\n if (selector === basicSelector) {\n reset();\n }\n return;\n }\n\n data.selectedIdx = baseUrls.indexOf(selectedBaseUrl);\n\n return selectedBaseUrl;\n }\n\n function reset() {\n serviceLocationBlacklistController.reset();\n }\n\n instance = {\n chooseSelector: chooseSelector,\n select: select,\n reset: reset,\n setConfig: setConfig\n };\n\n setup();\n\n return instance;\n}\n\nBaseURLSelector.__dashjs_factory_name = 'BaseURLSelector';\nexport default FactoryMaker.getClassFactory(BaseURLSelector);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport BaseURLTreeModel from '../models/BaseURLTreeModel';\nimport BaseURLSelector from '../utils/BaseURLSelector';\nimport URLUtils from '../utils/URLUtils';\nimport BaseURL from '../../dash/vo/BaseURL';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\n\nfunction BaseURLController() {\n\n let instance,\n adapter;\n\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n const urlUtils = URLUtils(context).getInstance();\n\n let baseURLTreeModel,\n baseURLSelector;\n\n function onBlackListChanged(e) {\n baseURLTreeModel.invalidateSelectedIndexes(e.entry);\n }\n\n function setup() {\n baseURLTreeModel = BaseURLTreeModel(context).create();\n baseURLSelector = BaseURLSelector(context).create();\n\n eventBus.on(Events.SERVICE_LOCATION_BLACKLIST_CHANGED, onBlackListChanged, instance);\n }\n\n function setConfig(config) {\n if (config.baseURLTreeModel) {\n baseURLTreeModel = config.baseURLTreeModel;\n }\n\n if (config.baseURLSelector) {\n baseURLSelector = config.baseURLSelector;\n }\n\n if (config.adapter) {\n adapter = config.adapter;\n }\n }\n\n function update(manifest) {\n baseURLTreeModel.update(manifest);\n baseURLSelector.chooseSelector(adapter.getIsDVB(manifest));\n }\n\n function resolve(path) {\n const baseUrls = baseURLTreeModel.getForPath(path);\n\n const baseUrl = baseUrls.reduce((p, c) => {\n const b = baseURLSelector.select(c);\n\n if (b) {\n if (!urlUtils.isRelative(b.url)) {\n p.url = b.url;\n p.serviceLocation = b.serviceLocation;\n } else {\n p.url = urlUtils.resolve(b.url, p.url);\n }\n p.availabilityTimeOffset = b.availabilityTimeOffset;\n p.availabilityTimeComplete = b.availabilityTimeComplete;\n } else {\n return new BaseURL();\n }\n\n return p;\n }, new BaseURL());\n\n if (!urlUtils.isRelative(baseUrl.url)) {\n return baseUrl;\n }\n }\n\n function reset() {\n baseURLTreeModel.reset();\n baseURLSelector.reset();\n }\n\n function initialize(data) {\n\n // report config to baseURLTreeModel and baseURLSelector\n baseURLTreeModel.setConfig({\n adapter: adapter\n });\n\n update(data);\n }\n\n instance = {\n reset: reset,\n initialize: initialize,\n resolve: resolve,\n setConfig: setConfig\n };\n\n setup();\n\n return instance;\n}\n\nBaseURLController.__dashjs_factory_name = 'BaseURLController';\nexport default FactoryMaker.getClassFactory(BaseURLController);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nimport Constants from '../constants/Constants';\nimport FragmentRequest from './FragmentRequest';\n\nclass TextRequest extends FragmentRequest {\n constructor(url, type) {\n super();\n this.url = url || null;\n this.type = type || null;\n this.mediaType = Constants.STREAM;\n this.responseType = ''; //'text' value returns a bad encoding response in Firefox\n }\n}\n\nexport default TextRequest;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport DashJSError from './vo/DashJSError';\nimport URLLoader from './net/URLLoader';\nimport {HTTPRequest} from './vo/metrics/HTTPRequest';\nimport TextRequest from './vo/TextRequest';\nimport EventBus from '../core/EventBus';\nimport Events from '../core/events/Events';\nimport FactoryMaker from '../core/FactoryMaker';\nimport Errors from '../core/errors/Errors';\n\nfunction XlinkLoader(config) {\n\n config = config || {};\n const RESOLVE_TO_ZERO = 'urn:mpeg:dash:resolve-to-zero:2013';\n\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n\n let urlLoader = URLLoader(context).create({\n errHandler: config.errHandler,\n dashMetrics: config.dashMetrics,\n mediaPlayerModel: config.mediaPlayerModel,\n requestModifier: config.requestModifier,\n errors: Errors\n });\n\n let instance;\n\n function load(url, element, resolveObject) {\n const report = function (content, resolveToZero) {\n element.resolved = true;\n element.resolvedContent = content ? content : null;\n\n eventBus.trigger(Events.XLINK_ELEMENT_LOADED, {\n element: element,\n resolveObject: resolveObject,\n error: content || resolveToZero ?\n null :\n new DashJSError(\n Errors.XLINK_LOADER_LOADING_FAILURE_ERROR_CODE,\n Errors.XLINK_LOADER_LOADING_FAILURE_ERROR_MESSAGE + url\n )\n });\n };\n\n if (url === RESOLVE_TO_ZERO) {\n report(null, true);\n } else {\n const request = new TextRequest(url, HTTPRequest.XLINK_EXPANSION_TYPE);\n\n urlLoader.load({\n request: request,\n success: function (data) {\n report(data);\n },\n error: function () {\n report(null);\n }\n });\n }\n }\n\n function reset() {\n if (urlLoader) {\n urlLoader.abort();\n urlLoader = null;\n }\n }\n\n instance = {\n load: load,\n reset: reset\n };\n\n return instance;\n}\n\nXlinkLoader.__dashjs_factory_name = 'XlinkLoader';\nexport default FactoryMaker.getClassFactory(XlinkLoader);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport XlinkLoader from '../XlinkLoader';\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport X2JS from '../../../externals/xml2json';\nimport URLUtils from '../utils/URLUtils';\nimport DashConstants from '../../dash/constants/DashConstants';\n\nconst RESOLVE_TYPE_ONLOAD = 'onLoad';\nconst RESOLVE_TYPE_ONACTUATE = 'onActuate';\nconst RESOLVE_TO_ZERO = 'urn:mpeg:dash:resolve-to-zero:2013';\n\nfunction XlinkController(config) {\n\n config = config || {};\n let context = this.context;\n let eventBus = EventBus(context).getInstance();\n const urlUtils = URLUtils(context).getInstance();\n\n let instance,\n matchers,\n iron,\n manifest,\n converter,\n xlinkLoader;\n\n function setup() {\n eventBus.on(Events.XLINK_ELEMENT_LOADED, onXlinkElementLoaded, instance);\n\n xlinkLoader = XlinkLoader(context).create({\n errHandler: config.errHandler,\n dashMetrics: config.dashMetrics,\n mediaPlayerModel: config.mediaPlayerModel,\n requestModifier: config.requestModifier,\n settings: config.settings\n });\n }\n\n function setMatchers(value) {\n if (value) {\n matchers = value;\n }\n }\n\n function setIron(value) {\n if (value) {\n iron = value;\n }\n }\n\n /**\n * <p>Triggers the resolution of the xlink.onLoad attributes in the manifest file </p>\n * @param {Object} mpd - the manifest\n */\n function resolveManifestOnLoad(mpd) {\n let elements;\n // First resolve all periods, so unnecessary requests inside onLoad Periods with Default content are avoided\n converter = new X2JS({\n escapeMode: false,\n attributePrefix: '',\n arrayAccessForm: 'property',\n emptyNodeForm: 'object',\n stripWhitespaces: false,\n enableToStringFunc: false,\n ignoreRoot: true,\n matchers: matchers\n });\n\n manifest = mpd;\n\n if (manifest.Period_asArray) {\n elements = getElementsToResolve(manifest.Period_asArray, manifest, DashConstants.PERIOD, RESOLVE_TYPE_ONLOAD);\n resolve(elements, DashConstants.PERIOD, RESOLVE_TYPE_ONLOAD);\n } else {\n eventBus.trigger(Events.XLINK_READY, {manifest: manifest});\n }\n }\n\n function reset() {\n eventBus.off(Events.XLINK_ELEMENT_LOADED, onXlinkElementLoaded, instance);\n\n if (xlinkLoader) {\n xlinkLoader.reset();\n xlinkLoader = null;\n }\n }\n\n function resolve(elements, type, resolveType) {\n let resolveObject = {};\n let element,\n url;\n\n resolveObject.elements = elements;\n resolveObject.type = type;\n resolveObject.resolveType = resolveType;\n // If nothing to resolve, directly call allElementsLoaded\n if (resolveObject.elements.length === 0) {\n onXlinkAllElementsLoaded(resolveObject);\n }\n for (let i = 0; i < resolveObject.elements.length; i++) {\n element = resolveObject.elements[i];\n if (urlUtils.isHTTPURL(element.url)) {\n url = element.url;\n } else {\n url = element.originalContent.BaseURL + element.url;\n }\n xlinkLoader.load(url, element, resolveObject);\n }\n }\n\n function onXlinkElementLoaded(event) {\n let element,\n resolveObject;\n\n const openingTag = '<response>';\n const closingTag = '</response>';\n let mergedContent = '';\n\n element = event.element;\n resolveObject = event.resolveObject;\n // if the element resolved into content parse the content\n if (element.resolvedContent) {\n let index = 0;\n // we add a parent elements so the converter is able to parse multiple elements of the same type which are not wrapped inside a container\n if (element.resolvedContent.indexOf('<?xml') === 0) {\n index = element.resolvedContent.indexOf('?>') + 2; //find the closing position of the xml declaration, if it exists.\n }\n mergedContent = element.resolvedContent.substr(0,index) + openingTag + element.resolvedContent.substr(index) + closingTag;\n element.resolvedContent = converter.xml_str2json(mergedContent);\n }\n if (isResolvingFinished(resolveObject)) {\n onXlinkAllElementsLoaded(resolveObject);\n }\n }\n\n // We got to wait till all elements of the current queue are resolved before merging back\n function onXlinkAllElementsLoaded (resolveObject) {\n let elements = [];\n let i,\n obj;\n\n mergeElementsBack(resolveObject);\n if (resolveObject.resolveType === RESOLVE_TYPE_ONACTUATE) {\n eventBus.trigger(Events.XLINK_READY, { manifest: manifest });\n }\n if (resolveObject.resolveType === RESOLVE_TYPE_ONLOAD) {\n switch (resolveObject.type) {\n // Start resolving the other elements. We can do Adaptation Set and EventStream in parallel\n case DashConstants.PERIOD:\n for (i = 0; i < manifest[DashConstants.PERIOD + '_asArray'].length; i++) {\n obj = manifest[DashConstants.PERIOD + '_asArray'][i];\n if (obj.hasOwnProperty(DashConstants.ADAPTATION_SET + '_asArray')) {\n elements = elements.concat(getElementsToResolve(obj[DashConstants.ADAPTATION_SET + '_asArray'], obj, DashConstants.ADAPTATION_SET, RESOLVE_TYPE_ONLOAD));\n }\n if (obj.hasOwnProperty(DashConstants.EVENT_STREAM + '_asArray')) {\n elements = elements.concat(getElementsToResolve(obj[DashConstants.EVENT_STREAM + '_asArray'], obj, DashConstants.EVENT_STREAM, RESOLVE_TYPE_ONLOAD));\n }\n }\n resolve(elements, DashConstants.ADAPTATION_SET, RESOLVE_TYPE_ONLOAD);\n break;\n case DashConstants.ADAPTATION_SET:\n // TODO: Resolve SegmentList here\n eventBus.trigger(Events.XLINK_READY, { manifest: manifest });\n break;\n }\n }\n }\n\n // Returns the elements with the specific resolve Type\n function getElementsToResolve(elements, parentElement, type, resolveType) {\n let toResolve = [];\n let element,\n i,\n xlinkObject;\n // first remove all the resolve-to-zero elements\n for (i = elements.length - 1; i >= 0; i--) {\n element = elements[i];\n if (element.hasOwnProperty('xlink:href') && element['xlink:href'] === RESOLVE_TO_ZERO) {\n elements.splice(i, 1);\n }\n }\n // now get the elements with the right resolve type\n for (i = 0; i < elements.length; i++) {\n element = elements[i];\n if (element.hasOwnProperty('xlink:href') && element.hasOwnProperty('xlink:actuate') && element['xlink:actuate'] === resolveType) {\n xlinkObject = createXlinkObject(element['xlink:href'], parentElement, type, i, resolveType, element);\n toResolve.push(xlinkObject);\n }\n }\n return toResolve;\n }\n\n function mergeElementsBack(resolveObject) {\n let resolvedElements = [];\n let element,\n type,\n obj,\n i,\n j,\n k;\n // Start merging back from the end because of index shifting. Note that the elements with the same parent have to be ordered by index ascending\n for (i = resolveObject.elements.length - 1; i >= 0; i --) {\n element = resolveObject.elements[i];\n type = element.type + '_asArray';\n\n // Element couldn't be resolved or is TODO Inappropriate target: Remove all Xlink attributes\n if (!element.resolvedContent || isInappropriateTarget()) {\n delete element.originalContent['xlink:actuate'];\n delete element.originalContent['xlink:href'];\n resolvedElements.push(element.originalContent);\n }\n // Element was successfully resolved\n else if (element.resolvedContent) {\n for (j = 0; j < element.resolvedContent[type].length; j++) {\n //TODO Contains another Xlink attribute with xlink:actuate set to onload. Remove all xLink attributes\n obj = element.resolvedContent[type][j];\n resolvedElements.push(obj);\n }\n }\n // Replace the old elements in the parent with the resolved ones\n element.parentElement[type].splice(element.index, 1);\n for (k = 0; k < resolvedElements.length; k++) {\n element.parentElement[type].splice(element.index + k, 0, resolvedElements[k]);\n }\n resolvedElements = [];\n }\n if (resolveObject.elements.length > 0) {\n iron.run(manifest);\n }\n }\n\n function createXlinkObject(url, parentElement, type, index, resolveType, originalContent) {\n return {\n url: url,\n parentElement: parentElement,\n type: type,\n index: index,\n resolveType: resolveType,\n originalContent: originalContent,\n resolvedContent: null,\n resolved: false\n };\n }\n\n // Check if all pending requests are finished\n function isResolvingFinished(elementsToResolve) {\n let i,\n obj;\n for (i = 0; i < elementsToResolve.elements.length; i++) {\n obj = elementsToResolve.elements[i];\n if (obj.resolved === false) {\n return false;\n }\n }\n return true;\n }\n\n // TODO : Do some syntax check here if the target is valid or not\n function isInappropriateTarget() {\n return false;\n }\n\n instance = {\n resolveManifestOnLoad: resolveManifestOnLoad,\n setMatchers: setMatchers,\n setIron: setIron,\n reset: reset\n };\n\n setup();\n return instance;\n}\n\nXlinkController.__dashjs_factory_name = 'XlinkController';\nexport default FactoryMaker.getClassFactory(XlinkController);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Constants from './constants/Constants';\nimport DashConstants from '../dash/constants/DashConstants';\nimport XlinkController from './controllers/XlinkController';\nimport URLLoader from './net/URLLoader';\nimport URLUtils from './utils/URLUtils';\nimport TextRequest from './vo/TextRequest';\nimport DashJSError from './vo/DashJSError';\nimport {HTTPRequest} from './vo/metrics/HTTPRequest';\nimport EventBus from '../core/EventBus';\nimport Events from '../core/events/Events';\nimport Errors from '../core/errors/Errors';\nimport FactoryMaker from '../core/FactoryMaker';\nimport DashParser from '../dash/parser/DashParser';\n\nfunction ManifestLoader(config) {\n\n config = config || {};\n const context = this.context;\n const debug = config.debug;\n const eventBus = EventBus(context).getInstance();\n const urlUtils = URLUtils(context).getInstance();\n\n let instance,\n logger,\n urlLoader,\n xlinkController,\n parser;\n\n let mssHandler = config.mssHandler;\n let errHandler = config.errHandler;\n\n function setup() {\n logger = debug.getLogger(instance);\n eventBus.on(Events.XLINK_READY, onXlinkReady, instance);\n\n urlLoader = URLLoader(context).create({\n errHandler: config.errHandler,\n dashMetrics: config.dashMetrics,\n mediaPlayerModel: config.mediaPlayerModel,\n requestModifier: config.requestModifier,\n urlUtils: urlUtils,\n constants: Constants,\n dashConstants: DashConstants,\n errors: Errors\n });\n\n xlinkController = XlinkController(context).create({\n errHandler: errHandler,\n dashMetrics: config.dashMetrics,\n mediaPlayerModel: config.mediaPlayerModel,\n requestModifier: config.requestModifier,\n settings: config.settings\n });\n\n parser = null;\n }\n\n function onXlinkReady(event) {\n eventBus.trigger(Events.INTERNAL_MANIFEST_LOADED, { manifest: event.manifest });\n }\n\n function createParser(data) {\n let parser = null;\n // Analyze manifest content to detect protocol and select appropriate parser\n if (data.indexOf('SmoothStreamingMedia') > -1) {\n //do some business to transform it into a Dash Manifest\n if (mssHandler) {\n parser = mssHandler.createMssParser();\n mssHandler.registerEvents();\n }\n return parser;\n } else if (data.indexOf('MPD') > -1 || data.indexOf('Patch') > -1) {\n return DashParser(context).create({debug: debug});\n } else {\n return parser;\n }\n }\n\n function load(url) {\n\n const request = new TextRequest(url, HTTPRequest.MPD_TYPE);\n\n urlLoader.load({\n request: request,\n success: function (data, textStatus, responseURL) {\n // Manage situations in which success is called after calling reset\n if (!xlinkController) return;\n\n let actualUrl,\n baseUri,\n manifest;\n\n // Handle redirects for the MPD - as per RFC3986 Section 5.1.3\n // also handily resolves relative MPD URLs to absolute\n if (responseURL && responseURL !== url) {\n baseUri = urlUtils.parseBaseUrl(responseURL);\n actualUrl = responseURL;\n } else {\n // usually this case will be caught and resolved by\n // responseURL above but it is not available for IE11 and Edge/12 and Edge/13\n // baseUri must be absolute for BaseURL resolution later\n if (urlUtils.isRelative(url)) {\n url = urlUtils.resolve(url, window.location.href);\n }\n\n baseUri = urlUtils.parseBaseUrl(url);\n }\n\n // A response of no content implies in-memory is properly up to date\n if (textStatus == 'No Content') {\n eventBus.trigger(\n Events.INTERNAL_MANIFEST_LOADED, {\n manifest: null\n }\n );\n return;\n }\n\n // Create parser according to manifest type\n if (parser === null) {\n parser = createParser(data);\n }\n\n if (parser === null) {\n eventBus.trigger(Events.INTERNAL_MANIFEST_LOADED, {\n manifest: null,\n error: new DashJSError(\n Errors.MANIFEST_LOADER_PARSING_FAILURE_ERROR_CODE,\n Errors.MANIFEST_LOADER_PARSING_FAILURE_ERROR_MESSAGE + `${url}`\n )\n });\n return;\n }\n\n // init xlinkcontroller with matchers and iron object from created parser\n xlinkController.setMatchers(parser.getMatchers());\n xlinkController.setIron(parser.getIron());\n\n try {\n manifest = parser.parse(data);\n } catch (e) {\n eventBus.trigger(Events.INTERNAL_MANIFEST_LOADED, {\n manifest: null,\n error: new DashJSError(\n Errors.MANIFEST_LOADER_PARSING_FAILURE_ERROR_CODE,\n Errors.MANIFEST_LOADER_PARSING_FAILURE_ERROR_MESSAGE + `${url}`\n )\n });\n return;\n }\n\n if (manifest) {\n manifest.url = actualUrl || url;\n\n // URL from which the MPD was originally retrieved (MPD updates will not change this value)\n if (!manifest.originalUrl) {\n manifest.originalUrl = manifest.url;\n }\n\n // In the following, we only use the first Location entry even if many are available\n // Compare with ManifestUpdater/DashManifestModel\n if (manifest.hasOwnProperty(Constants.LOCATION)) {\n baseUri = urlUtils.parseBaseUrl(manifest.Location_asArray[0]);\n logger.debug('BaseURI set by Location to: ' + baseUri);\n }\n\n manifest.baseUri = baseUri;\n manifest.loadedTime = new Date();\n xlinkController.resolveManifestOnLoad(manifest);\n\n eventBus.trigger(Events.ORIGINAL_MANIFEST_LOADED, { originalManifest: data });\n } else {\n eventBus.trigger(Events.INTERNAL_MANIFEST_LOADED, {\n manifest: null,\n error: new DashJSError(\n Errors.MANIFEST_LOADER_PARSING_FAILURE_ERROR_CODE,\n Errors.MANIFEST_LOADER_PARSING_FAILURE_ERROR_MESSAGE + `${url}`\n )\n });\n }\n },\n error: function (request, statusText, errorText) {\n eventBus.trigger(Events.INTERNAL_MANIFEST_LOADED, {\n manifest: null,\n error: new DashJSError(\n Errors.MANIFEST_LOADER_LOADING_FAILURE_ERROR_CODE,\n Errors.MANIFEST_LOADER_LOADING_FAILURE_ERROR_MESSAGE + `${url}, ${errorText}`\n )\n });\n }\n });\n }\n\n function reset() {\n eventBus.off(Events.XLINK_READY, onXlinkReady, instance);\n\n if (mssHandler) {\n mssHandler.reset();\n }\n\n if (xlinkController) {\n xlinkController.reset();\n xlinkController = null;\n }\n\n if (urlLoader) {\n urlLoader.abort();\n urlLoader = null;\n }\n }\n\n instance = {\n load: load,\n reset: reset\n };\n\n setup();\n\n return instance;\n}\n\nManifestLoader.__dashjs_factory_name = 'ManifestLoader';\n\nconst factory = FactoryMaker.getClassFactory(ManifestLoader);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\nimport FactoryMaker from '../../core/FactoryMaker';\n\n/**\n * @module ErrorHandler\n * @ignore\n */\nfunction ErrorHandler() {\n\n let instance;\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n\n /**\n * @param {object} err DashJSError with code, message and data attributes\n * @memberof module:ErrorHandler\n */\n function error(err) {\n eventBus.trigger(Events.ERROR, { error: err });\n }\n instance = {\n error: error\n };\n\n return instance;\n}\n\nErrorHandler.__dashjs_factory_name = 'ErrorHandler';\nexport default FactoryMaker.getSingletonFactory(ErrorHandler);\n","import FactoryMaker from '../../core/FactoryMaker';\nimport Debug from '../../core/Debug';\nimport Constants from '../constants/Constants';\n\nfunction CapabilitiesFilter() {\n const context = this.context;\n let instance,\n adapter,\n capabilities,\n settings,\n logger,\n customCapabilitiesFilters;\n\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n }\n\n function setConfig(config) {\n if (!config) {\n return;\n }\n\n if (config.adapter) {\n adapter = config.adapter;\n }\n\n if (config.capabilities) {\n capabilities = config.capabilities;\n }\n\n if (config.settings) {\n settings = config.settings;\n }\n\n }\n\n function filterUnsupportedFeatures(manifest) {\n return new Promise((resolve) => {\n const promises = [];\n\n promises.push(_filterUnsupportedCodecs(Constants.VIDEO, manifest));\n promises.push(_filterUnsupportedCodecs(Constants.AUDIO, manifest));\n\n Promise.all(promises)\n .then(() => {\n if (settings.get().streaming.capabilities.filterUnsupportedEssentialProperties) {\n _filterUnsupportedEssentialProperties(manifest);\n }\n _applyCustomFilters(manifest);\n resolve();\n })\n .catch(() => {\n resolve();\n });\n });\n }\n\n\n function _filterUnsupportedCodecs(type, manifest) {\n if (!manifest || !manifest.Period_asArray || manifest.Period_asArray.length === 0) {\n return Promise.resolve();\n }\n\n const promises = [];\n manifest.Period_asArray.forEach((period) => {\n promises.push(_filterUnsupportedAdaptationSetsOfPeriod(period, type));\n });\n\n return Promise.all(promises);\n }\n\n function _filterUnsupportedAdaptationSetsOfPeriod(period, type) {\n return new Promise((resolve) => {\n\n if (!period || !period.AdaptationSet_asArray || period.AdaptationSet_asArray.length === 0) {\n resolve();\n return;\n }\n\n const promises = [];\n period.AdaptationSet_asArray.forEach((as) => {\n if (adapter.getIsTypeOf(as, type)) {\n promises.push(_filterUnsupportedRepresentationsOfAdaptation(as, type));\n }\n });\n\n Promise.all(promises)\n .then(() => {\n period.AdaptationSet_asArray = period.AdaptationSet_asArray.filter((as) => {\n const supported = as.Representation_asArray && as.Representation_asArray.length > 0;\n\n if (!supported) {\n logger.warn(`AdaptationSet has been removed because of no supported Representation`);\n }\n\n return supported;\n });\n\n resolve();\n })\n .catch(() => {\n resolve();\n });\n });\n\n }\n\n function _filterUnsupportedRepresentationsOfAdaptation(as, type) {\n return new Promise((resolve) => {\n\n if (!as.Representation_asArray || as.Representation_asArray.length === 0) {\n resolve();\n return;\n }\n\n const promises = [];\n const configurations = [];\n\n as.Representation_asArray.forEach((rep, i) => {\n const codec = adapter.getCodec(as, i, false);\n const config = _createConfiguration(type,rep, codec);\n\n configurations.push(config);\n promises.push(capabilities.supportsCodec(config, type));\n });\n\n Promise.all(promises)\n .then((supported) => {\n as.Representation_asArray = as.Representation_asArray.filter((_, i) => {\n if (!supported[i]) {\n logger.debug(`[Stream] Codec ${configurations[i].codec} not supported `);\n }\n return supported[i];\n });\n resolve();\n })\n .catch(() => {\n resolve();\n });\n });\n }\n\n function _createConfiguration(type, rep, codec) {\n switch (type) {\n case Constants.VIDEO:\n return _createVideoConfiguration(rep, codec);\n case Constants.AUDIO:\n return _createAudioConfiguration(rep, codec);\n default:\n return null;\n\n }\n }\n\n function _createVideoConfiguration(rep, codec) {\n const width = rep.width || null;\n const height = rep.height || null;\n const framerate = rep.frameRate || null;\n const bitrate = rep.bandwidth || null;\n\n return {\n codec,\n width,\n height,\n framerate,\n bitrate\n };\n }\n\n function _createAudioConfiguration(rep, codec) {\n const samplerate = rep.audioSamplingRate || null;\n const bitrate = rep.bandwidth || null;\n\n return {\n codec,\n bitrate,\n samplerate\n };\n }\n\n function _filterUnsupportedEssentialProperties(manifest) {\n\n if (!manifest || !manifest.Period_asArray || manifest.Period_asArray.length === 0) {\n return;\n }\n\n manifest.Period_asArray.forEach((period) => {\n period.AdaptationSet_asArray = period.AdaptationSet_asArray.filter((as) => {\n\n if (!as.Representation_asArray || as.Representation_asArray.length === 0) {\n return true;\n }\n\n as.Representation_asArray = as.Representation_asArray.filter((rep) => {\n const essentialProperties = adapter.getEssentialPropertiesForRepresentation(rep);\n\n if (essentialProperties && essentialProperties.length > 0) {\n let i = 0;\n while (i < essentialProperties.length) {\n if (!capabilities.supportsEssentialProperty(essentialProperties[i])) {\n logger.debug('[Stream] EssentialProperty not supported: ' + essentialProperties[i].schemeIdUri);\n return false;\n }\n i += 1;\n }\n }\n\n return true;\n });\n\n return as.Representation_asArray && as.Representation_asArray.length > 0;\n });\n });\n\n }\n\n function _applyCustomFilters(manifest) {\n if (!customCapabilitiesFilters || customCapabilitiesFilters.length === 0 || !manifest || !manifest.Period_asArray || manifest.Period_asArray.length === 0) {\n return;\n }\n\n manifest.Period_asArray.forEach((period) => {\n period.AdaptationSet_asArray = period.AdaptationSet_asArray.filter((as) => {\n\n if (!as.Representation_asArray || as.Representation_asArray.length === 0) {\n return true;\n }\n\n as.Representation_asArray = as.Representation_asArray.filter((representation) => {\n return !customCapabilitiesFilters.some(customFilter => !customFilter(representation));\n });\n\n return as.Representation_asArray && as.Representation_asArray.length > 0;\n });\n });\n }\n\n function setCustomCapabilitiesFilters(customFilters) {\n customCapabilitiesFilters = customFilters;\n }\n\n instance = {\n setConfig,\n filterUnsupportedFeatures,\n setCustomCapabilitiesFilters\n };\n\n setup();\n\n return instance;\n}\n\nCapabilitiesFilter.__dashjs_factory_name = 'CapabilitiesFilter';\nexport default FactoryMaker.getSingletonFactory(CapabilitiesFilter);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass URIFragmentData {\n constructor() {\n this.t = null;\n this.xywh = null;\n this.track = null;\n this.id = null;\n this.s = null;\n this.r = null;\n }\n}\n\nexport default URIFragmentData;\n\n/*\n From Spec http://www.w3.org/TR/media-frags/\n\n temporal (t) - This dimension denotes a specific time range in the original media, such as \"starting at second 10, continuing until second 20\";\n spatial (xywh) - this dimension denotes a specific range of pixels in the original media, such as \"a rectangle with size (100,100) with its top-left at coordinate (10,10)\";\n Media fragments support also addressing the media along two additional dimensions (in the advanced version defined in Media Fragments 1.0 URI (advanced)):\n track (track) - this dimension denotes one or more tracks in the original media, such as \"the english audio and the video track\";\n id (id) - this dimension denotes a named temporal fragment within the original media, such as \"chapter 2\", and can be seen as a convenient way of specifying a temporal fragment.\n\n\n ## Note\n Akamai is purposing to add #s=X to the ISO standard.\n - (X) Value would be a start time to seek to at startup instead of starting at 0 or live edge\n - Allows for seeking back before the start time unlike a temporal clipping.\n*/","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport URIFragmentData from '../vo/URIFragmentData';\nimport FactoryMaker from '../../core/FactoryMaker';\n\n/**\n * Model class managing URI fragments.\n * @ignore\n */\nfunction URIFragmentModel() {\n\n let instance,\n URIFragmentDataVO;\n\n /**\n * @param {string} uri The URI to parse for fragment extraction\n * @memberof module:URIFragmentModel\n * @instance\n */\n function initialize(uri) {\n URIFragmentDataVO = new URIFragmentData();\n\n if (!uri) return null;\n\n const hashIndex = uri.indexOf('#');\n if (hashIndex !== -1) {\n const fragments = uri.substr(hashIndex + 1).split('&');\n for (let i = 0, len = fragments.length; i < len; ++i) {\n const fragment = fragments[i];\n const equalIndex = fragment.indexOf('=');\n if (equalIndex !== -1) {\n const key = fragment.substring(0,equalIndex);\n if (URIFragmentDataVO.hasOwnProperty(key)) {\n URIFragmentDataVO[key] = fragment.substr(equalIndex + 1);\n }\n }\n }\n }\n }\n\n /**\n * @returns {URIFragmentData} Object containing supported URI fragments\n * @memberof module:URIFragmentModel\n * @instance\n */\n function getURIFragmentData() {\n return URIFragmentDataVO;\n }\n\n instance = {\n initialize: initialize,\n getURIFragmentData: getURIFragmentData\n };\n\n return instance;\n}\n\nURIFragmentModel.__dashjs_factory_name = 'URIFragmentModel';\nexport default FactoryMaker.getSingletonFactory(URIFragmentModel);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\nimport FactoryMaker from '../../core/FactoryMaker';\n\nfunction ManifestModel() {\n\n let context = this.context;\n let eventBus = EventBus(context).getInstance();\n\n let instance,\n manifest;\n\n function getValue() {\n return manifest;\n }\n\n function setValue(value) {\n manifest = value;\n if (value) {\n eventBus.trigger(Events.MANIFEST_LOADED, { data: value });\n }\n }\n\n instance = {\n getValue: getValue,\n setValue: setValue\n };\n\n return instance;\n}\n\nManifestModel.__dashjs_factory_name = 'ManifestModel';\nexport default FactoryMaker.getSingletonFactory(ManifestModel);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport FactoryMaker from '../../core/FactoryMaker';\n\nconst NO_CHANGE = -1;\nconst PRIORITY = {\n DEFAULT: 0.5,\n STRONG: 1,\n WEAK: 0\n};\n\nfunction SwitchRequest(q, r, p) {\n //TODO refactor all the calls to this to use config to be like everything else.\n let instance,\n quality,\n priority,\n reason;\n\n // check priority value\n function getPriority(p) {\n let ret = PRIORITY.DEFAULT;\n\n // check that p is one of declared priority value\n if (p === PRIORITY.DEFAULT || p === PRIORITY.STRONG || p === PRIORITY.WEAK) {\n ret = p;\n }\n return ret;\n }\n\n // init attributes\n quality = (q === undefined) ? NO_CHANGE : q;\n priority = getPriority(p);\n reason = (r === undefined) ? null : r;\n\n instance = {\n quality: quality,\n reason: reason,\n priority: priority\n };\n\n return instance;\n}\n\nSwitchRequest.__dashjs_factory_name = 'SwitchRequest';\nconst factory = FactoryMaker.getClassFactory(SwitchRequest);\nfactory.NO_CHANGE = NO_CHANGE;\nfactory.PRIORITY = PRIORITY;\nFactoryMaker.updateClassFactory(SwitchRequest.__dashjs_factory_name, factory);\n\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport FactoryMaker from '../../../core/FactoryMaker';\nimport SwitchRequest from '../SwitchRequest';\nimport Constants from '../../constants/Constants';\nimport MetricsConstants from '../../constants/MetricsConstants';\n\nfunction ThroughputRule(config) {\n\n config = config || {};\n const context = this.context;\n const dashMetrics = config.dashMetrics;\n\n let instance;\n\n function setup() {\n }\n\n function checkConfig() {\n if (!dashMetrics || !dashMetrics.hasOwnProperty('getCurrentBufferState')) {\n throw new Error(Constants.MISSING_CONFIG_ERROR);\n }\n }\n\n function getMaxIndex(rulesContext) {\n const switchRequest = SwitchRequest(context).create();\n\n if (!rulesContext || !rulesContext.hasOwnProperty('getMediaInfo') || !rulesContext.hasOwnProperty('getMediaType') || !rulesContext.hasOwnProperty('useBufferOccupancyABR') ||\n !rulesContext.hasOwnProperty('getAbrController') || !rulesContext.hasOwnProperty('getScheduleController')) {\n return switchRequest;\n }\n\n checkConfig();\n\n const mediaInfo = rulesContext.getMediaInfo();\n const mediaType = rulesContext.getMediaType();\n const currentBufferState = dashMetrics.getCurrentBufferState(mediaType);\n const scheduleController = rulesContext.getScheduleController();\n const abrController = rulesContext.getAbrController();\n const streamInfo = rulesContext.getStreamInfo();\n const streamId = streamInfo ? streamInfo.id : null;\n const isDynamic = streamInfo && streamInfo.manifestInfo ? streamInfo.manifestInfo.isDynamic : null;\n const throughputHistory = abrController.getThroughputHistory();\n const throughput = throughputHistory.getSafeAverageThroughput(mediaType, isDynamic);\n const latency = throughputHistory.getAverageLatency(mediaType);\n const useBufferOccupancyABR = rulesContext.useBufferOccupancyABR();\n\n if (isNaN(throughput) || !currentBufferState || useBufferOccupancyABR) {\n return switchRequest;\n }\n\n if (abrController.getAbandonmentStateFor(streamId, mediaType) !== MetricsConstants.ABANDON_LOAD) {\n if (currentBufferState.state === MetricsConstants.BUFFER_LOADED || isDynamic) {\n switchRequest.quality = abrController.getQualityForBitrate(mediaInfo, throughput, streamId, latency);\n scheduleController.setTimeToLoadDelay(0);\n switchRequest.reason = {throughput: throughput, latency: latency};\n }\n }\n\n return switchRequest;\n }\n\n function reset() {\n // no persistent information to reset\n }\n\n instance = {\n getMaxIndex,\n reset\n };\n\n setup();\n\n return instance;\n}\n\nThroughputRule.__dashjs_factory_name = 'ThroughputRule';\nexport default FactoryMaker.getClassFactory(ThroughputRule);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport EventBus from '../../../core/EventBus';\nimport Events from '../../../core/events/Events';\nimport FactoryMaker from '../../../core/FactoryMaker';\nimport Debug from '../../../core/Debug';\nimport SwitchRequest from '../SwitchRequest';\nimport Constants from '../../constants/Constants';\nimport MetricsConstants from '../../constants/MetricsConstants';\nimport MediaPlayerEvents from '../../MediaPlayerEvents';\n\nfunction InsufficientBufferRule(config) {\n\n config = config || {};\n const INSUFFICIENT_BUFFER_SAFETY_FACTOR = 0.5;\n const SEGMENT_IGNORE_COUNT = 2;\n\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n const dashMetrics = config.dashMetrics;\n const settings = config.settings;\n\n let instance,\n logger,\n bufferStateDict;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n resetInitialSettings();\n eventBus.on(MediaPlayerEvents.PLAYBACK_SEEKING, _onPlaybackSeeking, instance);\n eventBus.on(Events.BYTES_APPENDED_END_FRAGMENT, _onBytesAppended, instance);\n }\n\n function checkConfig() {\n if (!dashMetrics || !dashMetrics.hasOwnProperty('getCurrentBufferLevel') || !dashMetrics.hasOwnProperty('getCurrentBufferState')) {\n throw new Error(Constants.MISSING_CONFIG_ERROR);\n }\n }\n\n\n /**\n * If a BUFFER_EMPTY event happens, then InsufficientBufferRule returns switchRequest.quality=0 until BUFFER_LOADED happens.\n * Otherwise InsufficientBufferRule gives a maximum bitrate depending on throughput and bufferLevel such that\n * a whole fragment can be downloaded before the buffer runs out, subject to a conservative safety factor of 0.5.\n * If the bufferLevel is low, then InsufficientBufferRule avoids rebuffering risk.\n * If the bufferLevel is high, then InsufficientBufferRule give a high MaxIndex allowing other rules to take over.\n * @param rulesContext\n * @return {object}\n */\n function getMaxIndex(rulesContext) {\n const switchRequest = SwitchRequest(context).create();\n\n if (!rulesContext || !rulesContext.hasOwnProperty('getMediaType')) {\n return switchRequest;\n }\n\n checkConfig();\n\n const mediaType = rulesContext.getMediaType();\n const currentBufferState = dashMetrics.getCurrentBufferState(mediaType);\n const representationInfo = rulesContext.getRepresentationInfo();\n const fragmentDuration = representationInfo.fragmentDuration;\n const streamInfo = rulesContext.getStreamInfo();\n const streamId = streamInfo ? streamInfo.id : null;\n const isDynamic = streamInfo && streamInfo.manifestInfo && streamInfo.manifestInfo.isDynamic;\n\n // Don't ask for a bitrate change if there is not info about buffer state or if fragmentDuration is not defined\n if (shouldIgnore(mediaType) || !fragmentDuration) {\n return switchRequest;\n }\n\n if (currentBufferState && currentBufferState.state === MetricsConstants.BUFFER_EMPTY) {\n logger.debug('[' + mediaType + '] Switch to index 0; buffer is empty.');\n switchRequest.quality = 0;\n switchRequest.reason = 'InsufficientBufferRule: Buffer is empty';\n } else {\n const mediaInfo = rulesContext.getMediaInfo();\n const abrController = rulesContext.getAbrController();\n const throughputHistory = abrController.getThroughputHistory();\n\n const bufferLevel = dashMetrics.getCurrentBufferLevel(mediaType);\n const throughput = throughputHistory.getAverageThroughput(mediaType, isDynamic);\n const latency = throughputHistory.getAverageLatency(mediaType);\n const bitrate = throughput * (bufferLevel / fragmentDuration) * INSUFFICIENT_BUFFER_SAFETY_FACTOR;\n\n switchRequest.quality = abrController.getQualityForBitrate(mediaInfo, bitrate, streamId, latency);\n switchRequest.reason = 'InsufficientBufferRule: being conservative to avoid immediate rebuffering';\n }\n\n return switchRequest;\n\n }\n\n function shouldIgnore(mediaType) {\n return !settings.get().streaming.lowLatencyEnabled && bufferStateDict[mediaType].ignoreCount > 0;\n }\n\n function resetInitialSettings() {\n bufferStateDict = {};\n bufferStateDict[Constants.VIDEO] = { ignoreCount: SEGMENT_IGNORE_COUNT };\n bufferStateDict[Constants.AUDIO] = { ignoreCount: SEGMENT_IGNORE_COUNT };\n }\n\n function _onPlaybackSeeking() {\n resetInitialSettings();\n }\n\n function _onBytesAppended(e) {\n if (!isNaN(e.startTime) && (e.mediaType === Constants.AUDIO || e.mediaType === Constants.VIDEO)) {\n if (bufferStateDict[e.mediaType].ignoreCount > 0) {\n bufferStateDict[e.mediaType].ignoreCount--;\n }\n }\n }\n\n function reset() {\n resetInitialSettings();\n eventBus.off(MediaPlayerEvents.PLAYBACK_SEEKING, _onPlaybackSeeking, instance);\n eventBus.off(Events.BYTES_APPENDED_END_FRAGMENT, _onBytesAppended, instance);\n }\n\n instance = {\n getMaxIndex,\n reset\n };\n\n setup();\n\n return instance;\n}\n\nInsufficientBufferRule.__dashjs_factory_name = 'InsufficientBufferRule';\nexport default FactoryMaker.getClassFactory(InsufficientBufferRule);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport SwitchRequest from '../SwitchRequest';\nimport FactoryMaker from '../../../core/FactoryMaker';\nimport Debug from '../../../core/Debug';\n\nfunction AbandonRequestsRule(config) {\n\n config = config || {};\n const ABANDON_MULTIPLIER = 1.8;\n const GRACE_TIME_THRESHOLD = 500;\n const MIN_LENGTH_TO_AVERAGE = 5;\n\n const context = this.context;\n const mediaPlayerModel = config.mediaPlayerModel;\n const dashMetrics = config.dashMetrics;\n const settings = config.settings;\n\n let instance,\n logger,\n fragmentDict,\n abandonDict,\n throughputArray;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n reset();\n }\n\n function setFragmentRequestDict(type, id) {\n fragmentDict[type] = fragmentDict[type] || {};\n fragmentDict[type][id] = fragmentDict[type][id] || {};\n }\n\n function storeLastRequestThroughputByType(type, throughput) {\n throughputArray[type] = throughputArray[type] || [];\n throughputArray[type].push(throughput);\n }\n\n function shouldAbandon(rulesContext) {\n const switchRequest = SwitchRequest(context).create(SwitchRequest.NO_CHANGE, {name: AbandonRequestsRule.__dashjs_factory_name});\n\n if (!rulesContext || !rulesContext.hasOwnProperty('getMediaInfo') || !rulesContext.hasOwnProperty('getMediaType') || !rulesContext.hasOwnProperty('getCurrentRequest') ||\n !rulesContext.hasOwnProperty('getRepresentationInfo') || !rulesContext.hasOwnProperty('getAbrController')) {\n return switchRequest;\n }\n\n const mediaInfo = rulesContext.getMediaInfo();\n const mediaType = rulesContext.getMediaType();\n const streamInfo = rulesContext.getStreamInfo();\n const streamId = streamInfo ? streamInfo.id : null;\n const req = rulesContext.getCurrentRequest();\n\n if (!isNaN(req.index)) {\n setFragmentRequestDict(mediaType, req.index);\n\n const stableBufferTime = mediaPlayerModel.getStableBufferTime();\n const bufferLevel = dashMetrics.getCurrentBufferLevel(mediaType);\n if ( bufferLevel > stableBufferTime ) {\n return switchRequest;\n }\n\n const fragmentInfo = fragmentDict[mediaType][req.index];\n if (fragmentInfo === null || req.firstByteDate === null || abandonDict.hasOwnProperty(fragmentInfo.id)) {\n return switchRequest;\n }\n\n //setup some init info based on first progress event\n if (fragmentInfo.firstByteTime === undefined) {\n throughputArray[mediaType] = [];\n fragmentInfo.firstByteTime = req.firstByteDate.getTime();\n fragmentInfo.segmentDuration = req.duration;\n fragmentInfo.bytesTotal = req.bytesTotal;\n fragmentInfo.id = req.index;\n }\n fragmentInfo.bytesLoaded = req.bytesLoaded;\n fragmentInfo.elapsedTime = new Date().getTime() - fragmentInfo.firstByteTime;\n\n if (fragmentInfo.bytesLoaded > 0 && fragmentInfo.elapsedTime > 0) {\n storeLastRequestThroughputByType(mediaType, Math.round(fragmentInfo.bytesLoaded * 8 / fragmentInfo.elapsedTime));\n }\n\n if (throughputArray[mediaType].length >= MIN_LENGTH_TO_AVERAGE &&\n fragmentInfo.elapsedTime > GRACE_TIME_THRESHOLD &&\n fragmentInfo.bytesLoaded < fragmentInfo.bytesTotal) {\n\n const totalSampledValue = throughputArray[mediaType].reduce((a, b) => a + b, 0);\n fragmentInfo.measuredBandwidthInKbps = Math.round(totalSampledValue / throughputArray[mediaType].length);\n fragmentInfo.estimatedTimeOfDownload = +((fragmentInfo.bytesTotal * 8 / fragmentInfo.measuredBandwidthInKbps) / 1000).toFixed(2);\n\n if (fragmentInfo.estimatedTimeOfDownload < fragmentInfo.segmentDuration * ABANDON_MULTIPLIER || rulesContext.getRepresentationInfo().quality === 0 ) {\n return switchRequest;\n } else if (!abandonDict.hasOwnProperty(fragmentInfo.id)) {\n\n const abrController = rulesContext.getAbrController();\n const bytesRemaining = fragmentInfo.bytesTotal - fragmentInfo.bytesLoaded;\n const bitrateList = abrController.getBitrateList(mediaInfo);\n const quality = abrController.getQualityForBitrate(mediaInfo, fragmentInfo.measuredBandwidthInKbps * settings.get().streaming.abr.bandwidthSafetyFactor, streamId);\n const minQuality = abrController.getMinAllowedIndexFor(mediaType, streamId);\n const newQuality = (minQuality !== undefined) ? Math.max(minQuality, quality) : quality;\n const estimateOtherBytesTotal = fragmentInfo.bytesTotal * bitrateList[newQuality].bitrate / bitrateList[abrController.getQualityFor(mediaType, streamId)].bitrate;\n\n if (bytesRemaining > estimateOtherBytesTotal) {\n switchRequest.quality = newQuality;\n switchRequest.reason.throughput = fragmentInfo.measuredBandwidthInKbps;\n switchRequest.reason.fragmentID = fragmentInfo.id;\n abandonDict[fragmentInfo.id] = fragmentInfo;\n logger.debug('[' + mediaType + '] frag id',fragmentInfo.id,' is asking to abandon and switch to quality to ', newQuality, ' measured bandwidth was', fragmentInfo.measuredBandwidthInKbps);\n delete fragmentDict[mediaType][fragmentInfo.id];\n }\n }\n } else if (fragmentInfo.bytesLoaded === fragmentInfo.bytesTotal) {\n delete fragmentDict[mediaType][fragmentInfo.id];\n }\n }\n\n return switchRequest;\n }\n\n function reset() {\n fragmentDict = {};\n abandonDict = {};\n throughputArray = [];\n }\n\n instance = {\n shouldAbandon: shouldAbandon,\n reset: reset\n };\n\n setup();\n\n return instance;\n}\n\nAbandonRequestsRule.__dashjs_factory_name = 'AbandonRequestsRule';\nexport default FactoryMaker.getClassFactory(AbandonRequestsRule);\n","import FactoryMaker from '../../../core/FactoryMaker';\nimport SwitchRequest from '../SwitchRequest';\nimport Debug from '../../../core/Debug';\n\nfunction DroppedFramesRule() {\n\n const context = this.context;\n let instance,\n logger;\n\n const DROPPED_PERCENTAGE_FORBID = 0.15;\n const GOOD_SAMPLE_SIZE = 375; //Don't apply the rule until this many frames have been rendered(and counted under those indices).\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n }\n\n function getMaxIndex(rulesContext) {\n const switchRequest = SwitchRequest(context).create();\n\n if (!rulesContext || !rulesContext.hasOwnProperty('getDroppedFramesHistory')) {\n return switchRequest;\n }\n\n const droppedFramesHistory = rulesContext.getDroppedFramesHistory();\n const streamId = rulesContext.getStreamInfo().id;\n\n if (droppedFramesHistory) {\n const dfh = droppedFramesHistory.getFrameHistory(streamId);\n\n if (!dfh || dfh.length === 0) {\n return switchRequest;\n }\n\n let droppedFrames = 0;\n let totalFrames = 0;\n let maxIndex = SwitchRequest.NO_CHANGE;\n\n //No point in measuring dropped frames for the zeroeth index.\n for (let i = 1; i < dfh.length; i++) {\n if (dfh[i]) {\n droppedFrames = dfh[i].droppedVideoFrames;\n totalFrames = dfh[i].totalVideoFrames;\n\n if (totalFrames > GOOD_SAMPLE_SIZE && droppedFrames / totalFrames > DROPPED_PERCENTAGE_FORBID) {\n maxIndex = i - 1;\n logger.debug('index: ' + maxIndex + ' Dropped Frames: ' + droppedFrames + ' Total Frames: ' + totalFrames);\n break;\n }\n }\n }\n return SwitchRequest(context).create(maxIndex, { droppedFrames: droppedFrames });\n }\n\n return switchRequest;\n }\n\n instance = {\n getMaxIndex\n };\n\n setup();\n\n return instance;\n}\n\nDroppedFramesRule.__dashjs_factory_name = 'DroppedFramesRule';\nexport default FactoryMaker.getClassFactory(DroppedFramesRule);\n","\nimport FactoryMaker from '../../../core/FactoryMaker';\nimport Debug from '../../../core/Debug';\nimport SwitchRequest from '../SwitchRequest';\n\nfunction SwitchHistoryRule() {\n\n const context = this.context;\n\n let instance,\n logger;\n\n //MAX_SWITCH is the number of drops made. It doesn't consider the size of the drop.\n const MAX_SWITCH = 0.075;\n\n //Before this number of switch requests(no switch or actual), don't apply the rule.\n //must be < SwitchRequestHistory SWITCH_REQUEST_HISTORY_DEPTH to enable rule\n const SAMPLE_SIZE = 6;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n }\n\n function getMaxIndex(rulesContext) {\n const switchRequestHistory = rulesContext ? rulesContext.getSwitchHistory() : null;\n const switchRequests = switchRequestHistory ? switchRequestHistory.getSwitchRequests() : [];\n let drops = 0;\n let noDrops = 0;\n let dropSize = 0;\n const switchRequest = SwitchRequest(context).create();\n\n for (let i = 0; i < switchRequests.length; i++) {\n if (switchRequests[i] !== undefined) {\n drops += switchRequests[i].drops;\n noDrops += switchRequests[i].noDrops;\n dropSize += switchRequests[i].dropSize;\n\n if (drops + noDrops >= SAMPLE_SIZE && (drops / noDrops > MAX_SWITCH)) {\n switchRequest.quality = (i > 0 && switchRequests[i].drops > 0) ? i - 1 : i;\n switchRequest.reason = {index: switchRequest.quality, drops: drops, noDrops: noDrops, dropSize: dropSize};\n logger.debug('Switch history rule index: ' + switchRequest.quality + ' samples: ' + (drops + noDrops) + ' drops: ' + drops);\n break;\n }\n }\n }\n\n return switchRequest;\n }\n\n instance = {\n getMaxIndex: getMaxIndex\n };\n\n setup();\n\n return instance;\n}\n\n\nSwitchHistoryRule.__dashjs_factory_name = 'SwitchHistoryRule';\nexport default FactoryMaker.getClassFactory(SwitchHistoryRule);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2016, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n// For a description of the BOLA adaptive bitrate (ABR) algorithm, see http://arxiv.org/abs/1601.06748\n\nimport MetricsConstants from '../../constants/MetricsConstants';\nimport SwitchRequest from '../SwitchRequest';\nimport FactoryMaker from '../../../core/FactoryMaker';\nimport { HTTPRequest } from '../../vo/metrics/HTTPRequest';\nimport EventBus from '../../../core/EventBus';\nimport Events from '../../../core/events/Events';\nimport Debug from '../../../core/Debug';\nimport MediaPlayerEvents from '../../MediaPlayerEvents';\n\n// BOLA_STATE_ONE_BITRATE : If there is only one bitrate (or initialization failed), always return NO_CHANGE.\n// BOLA_STATE_STARTUP : Set placeholder buffer such that we download fragments at most recently measured throughput.\n// BOLA_STATE_STEADY : Buffer primed, we switch to steady operation.\n// TODO: add BOLA_STATE_SEEK and tune BOLA behavior on seeking\nconst BOLA_STATE_ONE_BITRATE = 0;\nconst BOLA_STATE_STARTUP = 1;\nconst BOLA_STATE_STEADY = 2;\n\nconst MINIMUM_BUFFER_S = 10; // BOLA should never add artificial delays if buffer is less than MINIMUM_BUFFER_S.\nconst MINIMUM_BUFFER_PER_BITRATE_LEVEL_S = 2;\n// E.g. if there are 5 bitrates, BOLA switches to top bitrate at buffer = 10 + 5 * 2 = 20s.\n// If Schedule Controller does not allow buffer to reach that level, it can be achieved through the placeholder buffer level.\n\nconst PLACEHOLDER_BUFFER_DECAY = 0.99; // Make sure placeholder buffer does not stick around too long.\n\nfunction BolaRule(config) {\n\n config = config || {};\n const context = this.context;\n\n const dashMetrics = config.dashMetrics;\n const mediaPlayerModel = config.mediaPlayerModel;\n const eventBus = EventBus(context).getInstance();\n\n let instance,\n logger,\n bolaStateDict;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n resetInitialSettings();\n\n eventBus.on(MediaPlayerEvents.BUFFER_EMPTY, onBufferEmpty, instance);\n eventBus.on(MediaPlayerEvents.PLAYBACK_SEEKING, onPlaybackSeeking, instance);\n eventBus.on(MediaPlayerEvents.METRIC_ADDED, onMetricAdded, instance);\n eventBus.on(MediaPlayerEvents.QUALITY_CHANGE_REQUESTED, onQualityChangeRequested, instance);\n eventBus.on(MediaPlayerEvents.FRAGMENT_LOADING_ABANDONED, onFragmentLoadingAbandoned, instance);\n\n eventBus.on(Events.MEDIA_FRAGMENT_LOADED, onMediaFragmentLoaded, instance);\n }\n\n function utilitiesFromBitrates(bitrates) {\n return bitrates.map(b => Math.log(b));\n // no need to worry about offset, utilities will be offset (uniformly) anyway later\n }\n\n // NOTE: in live streaming, the real buffer level can drop below minimumBufferS, but bola should not stick to lowest bitrate by using a placeholder buffer level\n function calculateBolaParameters(stableBufferTime, bitrates, utilities) {\n const highestUtilityIndex = utilities.reduce((highestIndex, u, uIndex) => (u > utilities[highestIndex] ? uIndex : highestIndex), 0);\n\n if (highestUtilityIndex === 0) {\n // if highestUtilityIndex === 0, then always use lowest bitrate\n return null;\n }\n\n const bufferTime = Math.max(stableBufferTime, MINIMUM_BUFFER_S + MINIMUM_BUFFER_PER_BITRATE_LEVEL_S * bitrates.length);\n\n // TODO: Investigate if following can be better if utilities are not the default Math.log utilities.\n // If using Math.log utilities, we can choose Vp and gp to always prefer bitrates[0] at minimumBufferS and bitrates[max] at bufferTarget.\n // (Vp * (utility + gp) - bufferLevel) / bitrate has the maxima described when:\n // Vp * (utilities[0] + gp - 1) === minimumBufferS and Vp * (utilities[max] + gp - 1) === bufferTarget\n // giving:\n const gp = (utilities[highestUtilityIndex] - 1) / (bufferTime / MINIMUM_BUFFER_S - 1);\n const Vp = MINIMUM_BUFFER_S / gp;\n // note that expressions for gp and Vp assume utilities[0] === 1, which is true because of normalization\n\n return {gp: gp, Vp: Vp};\n }\n\n function getInitialBolaState(rulesContext) {\n const initialState = {};\n const mediaInfo = rulesContext.getMediaInfo();\n const bitrates = mediaInfo.bitrateList.map(b => b.bandwidth);\n let utilities = utilitiesFromBitrates(bitrates);\n utilities = utilities.map(u => u - utilities[0] + 1); // normalize\n const stableBufferTime = mediaPlayerModel.getStableBufferTime();\n const params = calculateBolaParameters(stableBufferTime, bitrates, utilities);\n\n if (!params) {\n // only happens when there is only one bitrate level\n initialState.state = BOLA_STATE_ONE_BITRATE;\n } else {\n initialState.state = BOLA_STATE_STARTUP;\n\n initialState.bitrates = bitrates;\n initialState.utilities = utilities;\n initialState.stableBufferTime = stableBufferTime;\n initialState.Vp = params.Vp;\n initialState.gp = params.gp;\n\n initialState.lastQuality = 0;\n clearBolaStateOnSeek(initialState);\n }\n\n return initialState;\n }\n\n function clearBolaStateOnSeek(bolaState) {\n bolaState.placeholderBuffer = 0;\n bolaState.mostAdvancedSegmentStart = NaN;\n bolaState.lastSegmentWasReplacement = false;\n bolaState.lastSegmentStart = NaN;\n bolaState.lastSegmentDurationS = NaN;\n bolaState.lastSegmentRequestTimeMs = NaN;\n bolaState.lastSegmentFinishTimeMs = NaN;\n }\n\n // If the buffer target is changed (can this happen mid-stream?), then adjust BOLA parameters accordingly.\n function checkBolaStateStableBufferTime(bolaState, mediaType) {\n const stableBufferTime = mediaPlayerModel.getStableBufferTime();\n if (bolaState.stableBufferTime !== stableBufferTime) {\n const params = calculateBolaParameters(stableBufferTime, bolaState.bitrates, bolaState.utilities);\n if (params.Vp !== bolaState.Vp || params.gp !== bolaState.gp) {\n // correct placeholder buffer using two criteria:\n // 1. do not change effective buffer level at effectiveBufferLevel === MINIMUM_BUFFER_S ( === Vp * gp )\n // 2. scale placeholder buffer by Vp subject to offset indicated in 1.\n\n const bufferLevel = dashMetrics.getCurrentBufferLevel(mediaType);\n let effectiveBufferLevel = bufferLevel + bolaState.placeholderBuffer;\n\n effectiveBufferLevel -= MINIMUM_BUFFER_S;\n effectiveBufferLevel *= params.Vp / bolaState.Vp;\n effectiveBufferLevel += MINIMUM_BUFFER_S;\n\n bolaState.stableBufferTime = stableBufferTime;\n bolaState.Vp = params.Vp;\n bolaState.gp = params.gp;\n bolaState.placeholderBuffer = Math.max(0, effectiveBufferLevel - bufferLevel);\n }\n }\n }\n\n function getBolaState(rulesContext) {\n const mediaType = rulesContext.getMediaType();\n let bolaState = bolaStateDict[mediaType];\n if (!bolaState) {\n bolaState = getInitialBolaState(rulesContext);\n bolaStateDict[mediaType] = bolaState;\n } else if (bolaState.state !== BOLA_STATE_ONE_BITRATE) {\n checkBolaStateStableBufferTime(bolaState, mediaType);\n }\n return bolaState;\n }\n\n // The core idea of BOLA.\n function getQualityFromBufferLevel(bolaState, bufferLevel) {\n const bitrateCount = bolaState.bitrates.length;\n let quality = NaN;\n let score = NaN;\n for (let i = 0; i < bitrateCount; ++i) {\n let s = (bolaState.Vp * (bolaState.utilities[i] + bolaState.gp) - bufferLevel) / bolaState.bitrates[i];\n if (isNaN(score) || s >= score) {\n score = s;\n quality = i;\n }\n }\n return quality;\n }\n\n // maximum buffer level which prefers to download at quality rather than wait\n function maxBufferLevelForQuality(bolaState, quality) {\n return bolaState.Vp * (bolaState.utilities[quality] + bolaState.gp);\n }\n\n // the minimum buffer level that would cause BOLA to choose quality rather than a lower bitrate\n function minBufferLevelForQuality(bolaState, quality) {\n const qBitrate = bolaState.bitrates[quality];\n const qUtility = bolaState.utilities[quality];\n\n let min = 0;\n for (let i = quality - 1; i >= 0; --i) {\n // for each bitrate less than bitrates[quality], BOLA should prefer quality (unless other bitrate has higher utility)\n if (bolaState.utilities[i] < bolaState.utilities[quality]) {\n const iBitrate = bolaState.bitrates[i];\n const iUtility = bolaState.utilities[i];\n\n const level = bolaState.Vp * (bolaState.gp + (qBitrate * iUtility - iBitrate * qUtility) / (qBitrate - iBitrate));\n min = Math.max(min, level); // we want min to be small but at least level(i) for all i\n }\n }\n return min;\n }\n\n /*\n * The placeholder buffer increases the effective buffer that is used to calculate the bitrate.\n * There are two main reasons we might want to increase the placeholder buffer:\n *\n * 1. When a segment finishes downloading, we would expect to get a call on getMaxIndex() regarding the quality for\n * the next segment. However, there might be a delay before the next call. E.g. when streaming live content, the\n * next segment might not be available yet. If the call to getMaxIndex() does happens after a delay, we don't\n * want the delay to change the BOLA decision - we only want to factor download time to decide on bitrate level.\n *\n * 2. It is possible to get a call to getMaxIndex() without having a segment download. The buffer target in dash.js\n * is different for top-quality segments and lower-quality segments. If getMaxIndex() returns a lower-than-top\n * quality, then the buffer controller might decide not to download a segment. When dash.js is ready for the next\n * segment, getMaxIndex() will be called again. We don't want this extra delay to factor in the bitrate decision.\n */\n function updatePlaceholderBuffer(bolaState, mediaType) {\n const nowMs = Date.now();\n\n if (!isNaN(bolaState.lastSegmentFinishTimeMs)) {\n // compensate for non-bandwidth-derived delays, e.g., live streaming availability, buffer controller\n const delay = 0.001 * (nowMs - bolaState.lastSegmentFinishTimeMs);\n bolaState.placeholderBuffer += Math.max(0, delay);\n } else if (!isNaN(bolaState.lastCallTimeMs)) {\n // no download after last call, compensate for delay between calls\n const delay = 0.001 * (nowMs - bolaState.lastCallTimeMs);\n bolaState.placeholderBuffer += Math.max(0, delay);\n }\n\n bolaState.lastCallTimeMs = nowMs;\n bolaState.lastSegmentStart = NaN;\n bolaState.lastSegmentRequestTimeMs = NaN;\n bolaState.lastSegmentFinishTimeMs = NaN;\n\n checkBolaStateStableBufferTime(bolaState, mediaType);\n }\n\n function onBufferEmpty() {\n // if we rebuffer, we don't want the placeholder buffer to artificially raise BOLA quality\n for (const mediaType in bolaStateDict) {\n if (bolaStateDict.hasOwnProperty(mediaType) && bolaStateDict[mediaType].state === BOLA_STATE_STEADY) {\n bolaStateDict[mediaType].placeholderBuffer = 0;\n }\n }\n }\n\n function onPlaybackSeeking() {\n // TODO: 1. Verify what happens if we seek mid-fragment.\n // TODO: 2. If e.g. we have 10s fragments and seek, we might want to download the first fragment at a lower quality to restart playback quickly.\n for (const mediaType in bolaStateDict) {\n if (bolaStateDict.hasOwnProperty(mediaType)) {\n const bolaState = bolaStateDict[mediaType];\n if (bolaState.state !== BOLA_STATE_ONE_BITRATE) {\n bolaState.state = BOLA_STATE_STARTUP; // TODO: BOLA_STATE_SEEK?\n clearBolaStateOnSeek(bolaState);\n }\n }\n }\n }\n\n function onMediaFragmentLoaded(e) {\n if (e && e.chunk && e.chunk.mediaInfo) {\n const bolaState = bolaStateDict[e.chunk.mediaInfo.type];\n if (bolaState && bolaState.state !== BOLA_STATE_ONE_BITRATE) {\n const start = e.chunk.start;\n if (isNaN(bolaState.mostAdvancedSegmentStart) || start > bolaState.mostAdvancedSegmentStart) {\n bolaState.mostAdvancedSegmentStart = start;\n bolaState.lastSegmentWasReplacement = false;\n } else {\n bolaState.lastSegmentWasReplacement = true;\n }\n\n bolaState.lastSegmentStart = start;\n bolaState.lastSegmentDurationS = e.chunk.duration;\n bolaState.lastQuality = e.chunk.quality;\n\n checkNewSegment(bolaState, e.chunk.mediaInfo.type);\n }\n }\n }\n\n function onMetricAdded(e) {\n if (e && e.metric === MetricsConstants.HTTP_REQUEST && e.value && e.value.type === HTTPRequest.MEDIA_SEGMENT_TYPE && e.value.trace && e.value.trace.length) {\n const bolaState = bolaStateDict[e.mediaType];\n if (bolaState && bolaState.state !== BOLA_STATE_ONE_BITRATE) {\n bolaState.lastSegmentRequestTimeMs = e.value.trequest.getTime();\n bolaState.lastSegmentFinishTimeMs = e.value._tfinish.getTime();\n\n checkNewSegment(bolaState, e.mediaType);\n }\n }\n }\n\n /*\n * When a new segment is downloaded, we get two notifications: onMediaFragmentLoaded() and onMetricAdded(). It is\n * possible that the quality for the downloaded segment was lower (not higher) than the quality indicated by BOLA.\n * This might happen because of other rules such as the DroppedFramesRule. When this happens, we trim the\n * placeholder buffer to make BOLA more stable. This mechanism also avoids inflating the buffer when BOLA itself\n * decides not to increase the quality to avoid oscillations.\n *\n * We should also check for replacement segments (fast switching). In this case, a segment is downloaded but does\n * not grow the actual buffer. Fast switching might cause the buffer to deplete, causing BOLA to drop the bitrate.\n * We avoid this by growing the placeholder buffer.\n */\n function checkNewSegment(bolaState, mediaType) {\n if (!isNaN(bolaState.lastSegmentStart) && !isNaN(bolaState.lastSegmentRequestTimeMs) && !isNaN(bolaState.placeholderBuffer)) {\n bolaState.placeholderBuffer *= PLACEHOLDER_BUFFER_DECAY;\n\n // Find what maximum buffer corresponding to last segment was, and ensure placeholder is not relatively larger.\n if (!isNaN(bolaState.lastSegmentFinishTimeMs)) {\n const bufferLevel = dashMetrics.getCurrentBufferLevel(mediaType);\n const bufferAtLastSegmentRequest = bufferLevel + 0.001 * (bolaState.lastSegmentFinishTimeMs - bolaState.lastSegmentRequestTimeMs); // estimate\n const maxEffectiveBufferForLastSegment = maxBufferLevelForQuality(bolaState, bolaState.lastQuality);\n const maxPlaceholderBuffer = Math.max(0, maxEffectiveBufferForLastSegment - bufferAtLastSegmentRequest);\n bolaState.placeholderBuffer = Math.min(maxPlaceholderBuffer, bolaState.placeholderBuffer);\n }\n\n // then see if we should grow placeholder buffer\n\n if (bolaState.lastSegmentWasReplacement && !isNaN(bolaState.lastSegmentDurationS)) {\n // compensate for segments that were downloaded but did not grow the buffer\n bolaState.placeholderBuffer += bolaState.lastSegmentDurationS;\n }\n\n bolaState.lastSegmentStart = NaN;\n bolaState.lastSegmentRequestTimeMs = NaN;\n }\n }\n\n function onQualityChangeRequested(e) {\n // Useful to store change requests when abandoning a download.\n if (e) {\n const bolaState = bolaStateDict[e.mediaType];\n if (bolaState && bolaState.state !== BOLA_STATE_ONE_BITRATE) {\n bolaState.abrQuality = e.newQuality;\n }\n }\n }\n\n function onFragmentLoadingAbandoned(e) {\n if (e) {\n const bolaState = bolaStateDict[e.mediaType];\n if (bolaState && bolaState.state !== BOLA_STATE_ONE_BITRATE) {\n // deflate placeholderBuffer - note that we want to be conservative when abandoning\n const bufferLevel = dashMetrics.getCurrentBufferLevel(e.mediaType);\n let wantEffectiveBufferLevel;\n if (bolaState.abrQuality > 0) {\n // deflate to point where BOLA just chooses newQuality over newQuality-1\n wantEffectiveBufferLevel = minBufferLevelForQuality(bolaState, bolaState.abrQuality);\n } else {\n wantEffectiveBufferLevel = MINIMUM_BUFFER_S;\n }\n const maxPlaceholderBuffer = Math.max(0, wantEffectiveBufferLevel - bufferLevel);\n bolaState.placeholderBuffer = Math.min(bolaState.placeholderBuffer, maxPlaceholderBuffer);\n }\n }\n }\n\n function getMaxIndex(rulesContext) {\n const switchRequest = SwitchRequest(context).create();\n\n if (!rulesContext || !rulesContext.hasOwnProperty('getMediaInfo') || !rulesContext.hasOwnProperty('getMediaType') ||\n !rulesContext.hasOwnProperty('getScheduleController') || !rulesContext.hasOwnProperty('getStreamInfo') ||\n !rulesContext.hasOwnProperty('getAbrController') || !rulesContext.hasOwnProperty('useBufferOccupancyABR')) {\n return switchRequest;\n }\n const mediaInfo = rulesContext.getMediaInfo();\n const mediaType = rulesContext.getMediaType();\n const scheduleController = rulesContext.getScheduleController();\n const streamInfo = rulesContext.getStreamInfo();\n const abrController = rulesContext.getAbrController();\n const throughputHistory = abrController.getThroughputHistory();\n const streamId = streamInfo ? streamInfo.id : null;\n const isDynamic = streamInfo && streamInfo.manifestInfo && streamInfo.manifestInfo.isDynamic;\n const useBufferOccupancyABR = rulesContext.useBufferOccupancyABR();\n switchRequest.reason = switchRequest.reason || {};\n\n if (!useBufferOccupancyABR) {\n return switchRequest;\n }\n\n scheduleController.setTimeToLoadDelay(0);\n\n const bolaState = getBolaState(rulesContext);\n\n if (bolaState.state === BOLA_STATE_ONE_BITRATE) {\n // shouldn't even have been called\n return switchRequest;\n }\n\n const bufferLevel = dashMetrics.getCurrentBufferLevel(mediaType);\n const throughput = throughputHistory.getAverageThroughput(mediaType, isDynamic);\n const safeThroughput = throughputHistory.getSafeAverageThroughput(mediaType, isDynamic);\n const latency = throughputHistory.getAverageLatency(mediaType);\n let quality;\n\n switchRequest.reason.state = bolaState.state;\n switchRequest.reason.throughput = throughput;\n switchRequest.reason.latency = latency;\n\n if (isNaN(throughput)) { // isNaN(throughput) === isNaN(safeThroughput) === isNaN(latency)\n // still starting up - not enough information\n return switchRequest;\n }\n\n switch (bolaState.state) {\n case BOLA_STATE_STARTUP:\n quality = abrController.getQualityForBitrate(mediaInfo, safeThroughput, streamId, latency);\n\n switchRequest.quality = quality;\n switchRequest.reason.throughput = safeThroughput;\n\n bolaState.placeholderBuffer = Math.max(0, minBufferLevelForQuality(bolaState, quality) - bufferLevel);\n bolaState.lastQuality = quality;\n\n if (!isNaN(bolaState.lastSegmentDurationS) && bufferLevel >= bolaState.lastSegmentDurationS) {\n bolaState.state = BOLA_STATE_STEADY;\n }\n\n break; // BOLA_STATE_STARTUP\n\n case BOLA_STATE_STEADY:\n\n // NB: The placeholder buffer is added to bufferLevel to come up with a bitrate.\n // This might lead BOLA to be too optimistic and to choose a bitrate that would lead to rebuffering -\n // if the real buffer bufferLevel runs out, the placeholder buffer cannot prevent rebuffering.\n // However, the InsufficientBufferRule takes care of this scenario.\n\n updatePlaceholderBuffer(bolaState, mediaType);\n\n quality = getQualityFromBufferLevel(bolaState, bufferLevel + bolaState.placeholderBuffer);\n\n // we want to avoid oscillations\n // We implement the \"BOLA-O\" variant: when network bandwidth lies between two encoded bitrate levels, stick to the lowest level.\n const qualityForThroughput = abrController.getQualityForBitrate(mediaInfo, safeThroughput, streamId, latency);\n if (quality > bolaState.lastQuality && quality > qualityForThroughput) {\n // only intervene if we are trying to *increase* quality to an *unsustainable* level\n // we are only avoid oscillations - do not drop below last quality\n\n quality = Math.max(qualityForThroughput, bolaState.lastQuality);\n }\n\n // We do not want to overfill buffer with low quality chunks.\n // Note that there will be no delay if buffer level is below MINIMUM_BUFFER_S, probably even with some margin higher than MINIMUM_BUFFER_S.\n let delayS = Math.max(0, bufferLevel + bolaState.placeholderBuffer - maxBufferLevelForQuality(bolaState, quality));\n\n // First reduce placeholder buffer, then tell schedule controller to pause.\n if (delayS <= bolaState.placeholderBuffer) {\n bolaState.placeholderBuffer -= delayS;\n delayS = 0;\n } else {\n delayS -= bolaState.placeholderBuffer;\n bolaState.placeholderBuffer = 0;\n\n if (quality < abrController.getMaxAllowedIndexFor(mediaType, streamId)) {\n // At top quality, allow schedule controller to decide how far to fill buffer.\n scheduleController.setTimeToLoadDelay(1000 * delayS);\n } else {\n delayS = 0;\n }\n }\n\n switchRequest.quality = quality;\n switchRequest.reason.throughput = throughput;\n switchRequest.reason.latency = latency;\n switchRequest.reason.bufferLevel = bufferLevel;\n switchRequest.reason.placeholderBuffer = bolaState.placeholderBuffer;\n switchRequest.reason.delay = delayS;\n\n bolaState.lastQuality = quality;\n // keep bolaState.state === BOLA_STATE_STEADY\n\n break; // BOLA_STATE_STEADY\n\n default:\n logger.debug('BOLA ABR rule invoked in bad state.');\n // should not arrive here, try to recover\n switchRequest.quality = abrController.getQualityForBitrate(mediaInfo, safeThroughput, streamId, latency);\n switchRequest.reason.state = bolaState.state;\n switchRequest.reason.throughput = safeThroughput;\n switchRequest.reason.latency = latency;\n bolaState.state = BOLA_STATE_STARTUP;\n clearBolaStateOnSeek(bolaState);\n }\n\n return switchRequest;\n }\n\n function resetInitialSettings() {\n bolaStateDict = {};\n }\n\n function reset() {\n resetInitialSettings();\n\n eventBus.off(MediaPlayerEvents.BUFFER_EMPTY, onBufferEmpty, instance);\n eventBus.off(MediaPlayerEvents.PLAYBACK_SEEKING, onPlaybackSeeking, instance);\n eventBus.off(MediaPlayerEvents.METRIC_ADDED, onMetricAdded, instance);\n eventBus.off(MediaPlayerEvents.QUALITY_CHANGE_REQUESTED, onQualityChangeRequested, instance);\n eventBus.off(MediaPlayerEvents.FRAGMENT_LOADING_ABANDONED, onFragmentLoadingAbandoned, instance);\n\n eventBus.off(Events.MEDIA_FRAGMENT_LOADED, onMediaFragmentLoaded, instance);\n }\n\n instance = {\n getMaxIndex: getMaxIndex,\n reset: reset\n };\n\n setup();\n return instance;\n}\n\nBolaRule.__dashjs_factory_name = 'BolaRule';\nexport default FactoryMaker.getClassFactory(BolaRule);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2020, Unified Streaming.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n// For a description of the Learn2Adapt-LowLatency (L2A-LL) bitrate adaptation algorithm, see https://github.com/unifiedstreaming/Learn2Adapt-LowLatency/blob/master/Online_learning_for_bitrate_adaptation_in_low_latency_live_streaming_CR.pdf\n\nimport MetricsConstants from '../../constants/MetricsConstants';\nimport SwitchRequest from '../SwitchRequest';\nimport FactoryMaker from '../../../core/FactoryMaker';\nimport {HTTPRequest} from '../../vo/metrics/HTTPRequest';\nimport EventBus from '../../../core/EventBus';\nimport Events from '../../../core/events/Events';\nimport Debug from '../../../core/Debug';\nimport Constants from '../../constants/Constants';\n\nconst L2A_STATE_ONE_BITRATE = 0; // If there is only one bitrate (or initialization failed), always return NO_CHANGE.\nconst L2A_STATE_STARTUP = 1; // Set placeholder buffer such that we download fragments at most recently measured throughput.\nconst L2A_STATE_STEADY = 2; // Buffer primed, we switch to steady operation.\n\n\nfunction L2ARule(config) {\n config = config || {};\n const context = this.context;\n\n const dashMetrics = config.dashMetrics;\n const eventBus = EventBus(context).getInstance();\n\n let instance,\n l2AStateDict,\n l2AParameterDict,\n logger;\n\n /**\n * Setup function to initialize L2ARule\n */\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n _resetInitialSettings();\n\n eventBus.on(Events.PLAYBACK_SEEKING, _onPlaybackSeeking, instance);\n eventBus.on(Events.MEDIA_FRAGMENT_LOADED, _onMediaFragmentLoaded, instance);\n eventBus.on(Events.METRIC_ADDED, _onMetricAdded, instance);\n eventBus.on(Events.QUALITY_CHANGE_REQUESTED, _onQualityChangeRequested, instance);\n }\n\n /**\n * Sets the initial state of the algorithm. Calls the initialize function for the paramteters.\n * @param {object} rulesContext\n * @return {object} initialState\n * @private\n */\n function _getInitialL2AState(rulesContext) {\n const initialState = {};\n const mediaInfo = rulesContext.getMediaInfo();\n const bitrates = mediaInfo.bitrateList.map((b) => {\n return b.bandwidth / 1000;\n });\n\n initialState.state = L2A_STATE_STARTUP;\n initialState.bitrates = bitrates;\n initialState.lastQuality = 0;\n\n _initializeL2AParameters(mediaInfo);\n _clearL2AStateOnSeek(initialState);\n\n return initialState;\n }\n\n /**\n * Initializes the parameters of the algorithm. This will be done once for each media type.\n * @param {object} mediaInfo\n * @private\n */\n function _initializeL2AParameters(mediaInfo) {\n\n if (!mediaInfo || !mediaInfo.type) {\n return;\n }\n l2AParameterDict[mediaInfo.type] = {};\n l2AParameterDict[mediaInfo.type].w = []; //Vector of probabilities associated with bitrate decisions\n l2AParameterDict[mediaInfo.type].prev_w = []; //Vector of probabilities associated with bitrate decisions calculated in the previous step\n l2AParameterDict[mediaInfo.type].Q = 0; //Initialization of Lagrangian multiplier (This keeps track of the buffer displacement)\n l2AParameterDict[mediaInfo.type].segment_request_start_s = 0;\n l2AParameterDict[mediaInfo.type].segment_download_finish_s = 0;\n l2AParameterDict[mediaInfo.type].B_target = 1.5; //Target buffer level\n }\n\n\n /**\n * Clears the state object\n * @param {object} l2AState\n * @private\n */\n function _clearL2AStateOnSeek(l2AState) {\n l2AState.placeholderBuffer = 0;\n l2AState.mostAdvancedSegmentStart = NaN;\n l2AState.lastSegmentWasReplacement = false;\n l2AState.lastSegmentStart = NaN;\n l2AState.lastSegmentDurationS = NaN;\n l2AState.lastSegmentRequestTimeMs = NaN;\n l2AState.lastSegmentFinishTimeMs = NaN;\n }\n\n\n /**\n * Returns the state object for a fiven media type. If the state object is not yet defined _getInitialL2AState is called\n * @param {object} rulesContext\n * @return {object} l2AState\n * @private\n */\n function _getL2AState(rulesContext) {\n const mediaType = rulesContext.getMediaType();\n let l2AState = l2AStateDict[mediaType];\n\n if (!l2AState) {\n l2AState = _getInitialL2AState(rulesContext);\n l2AStateDict[mediaType] = l2AState;\n }\n\n return l2AState;\n }\n\n /**\n * Event handler for the seeking event.\n * @private\n */\n function _onPlaybackSeeking() {\n for (const mediaType in l2AStateDict) {\n if (l2AStateDict.hasOwnProperty(mediaType)) {\n const l2aState = l2AStateDict[mediaType];\n if (l2aState.state !== L2A_STATE_ONE_BITRATE) {\n l2aState.state = L2A_STATE_STARTUP;\n _clearL2AStateOnSeek(l2aState);\n }\n }\n }\n }\n\n /**\n * Event handler for the mediaFragmentLoaded event\n * @param {object} e\n * @private\n */\n function _onMediaFragmentLoaded(e) {\n if (e && e.chunk && e.chunk.mediaInfo) {\n const l2AState = l2AStateDict[e.chunk.mediaInfo.type];\n const l2AParameters = l2AParameterDict[e.chunk.mediaInfo.type];\n\n if (l2AState && l2AState.state !== L2A_STATE_ONE_BITRATE) {\n const start = e.chunk.start;\n if (isNaN(l2AState.mostAdvancedSegmentStart) || start > l2AState.mostAdvancedSegmentStart) {\n l2AState.mostAdvancedSegmentStart = start;\n l2AState.lastSegmentWasReplacement = false;\n } else {\n l2AState.lastSegmentWasReplacement = true;\n }\n\n l2AState.lastSegmentStart = start;\n l2AState.lastSegmentDurationS = e.chunk.duration;\n l2AState.lastQuality = e.chunk.quality;\n\n _checkNewSegment(l2AState, l2AParameters);\n }\n }\n }\n\n /**\n * Event handler for the metricAdded event\n * @param {object} e\n * @private\n */\n function _onMetricAdded(e) {\n if (e && e.metric === MetricsConstants.HTTP_REQUEST && e.value && e.value.type === HTTPRequest.MEDIA_SEGMENT_TYPE && e.value.trace && e.value.trace.length) {\n const l2AState = l2AStateDict[e.mediaType];\n const l2AParameters = l2AParameterDict[e.mediaType];\n\n if (l2AState && l2AState.state !== L2A_STATE_ONE_BITRATE) {\n l2AState.lastSegmentRequestTimeMs = e.value.trequest.getTime();\n l2AState.lastSegmentFinishTimeMs = e.value._tfinish.getTime();\n _checkNewSegment(l2AState, l2AParameters);\n }\n }\n }\n\n /**\n * When a new metric has been added or a media fragment has been loaded the state is adjusted accordingly\n * @param {object} L2AState\n * @param {object} l2AParameters\n * @private\n */\n function _checkNewSegment(L2AState, l2AParameters) {\n if (!isNaN(L2AState.lastSegmentStart) && !isNaN(L2AState.lastSegmentRequestTimeMs)) {\n l2AParameters.segment_request_start_s = 0.001 * L2AState.lastSegmentRequestTimeMs;\n l2AParameters.segment_download_finish_s = 0.001 * L2AState.lastSegmentFinishTimeMs;\n L2AState.lastSegmentStart = NaN;\n L2AState.lastSegmentRequestTimeMs = NaN;\n }\n }\n\n /**\n * Event handler for the qualityChangeRequested event\n * @param {object} e\n * @private\n */\n function _onQualityChangeRequested(e) {\n // Useful to store change requests when abandoning a download.\n if (e && e.mediaType) {\n const L2AState = l2AStateDict[e.mediaType];\n if (L2AState && L2AState.state !== L2A_STATE_ONE_BITRATE) {\n L2AState.abrQuality = e.newQuality;\n }\n }\n }\n\n /**\n * Dot multiplication of two arrays\n * @param {array} arr1\n * @param {array} arr2\n * @return {number} sumdot\n * @private\n */\n\n function _dotmultiplication(arr1, arr2) {\n if (arr1.length !== arr2.length) {\n return -1;\n }\n let sumdot = 0;\n for (let i = 0; i < arr1.length; i++) {\n sumdot = sumdot + arr1[i] * arr2[i];\n }\n return sumdot;\n }\n\n /**\n * Project an n-dim vector y to the simplex Dn\n * Dn = { x : x n-dim, 1 >= x >= 0, sum(x) = 1}\n * Algorithm is explained at http://arxiv.org/abs/1101.6081\n * @param {array} arr\n * @return {array}\n */\n function euclideanProjection(arr) {\n const m = arr.length;\n let bget = false;\n let arr2 = [];\n for (let ii = 0; ii < m; ++ii) {\n arr2[ii] = arr[ii];\n }\n let s = arr.sort(function (a, b) {\n return b - a;\n });\n let tmpsum = 0;\n let tmax = 0;\n let x = [];\n for (let ii = 0; ii < m - 1; ++ii) {\n tmpsum = tmpsum + s[ii];\n tmax = (tmpsum - 1) / (ii + 1);\n if (tmax >= s[ii + 1]) {\n bget = true;\n break;\n }\n }\n if (!bget) {\n tmax = (tmpsum + s[m - 1] - 1) / m;\n }\n for (let ii = 0; ii < m; ++ii) {\n x[ii] = Math.max(arr2[ii] - tmax, 0);\n }\n return x;\n }\n\n /**\n * Returns a switch request object indicating which quality is to be played\n * @param {object} rulesContext\n * @return {object}\n */\n function getMaxIndex(rulesContext) {\n const switchRequest = SwitchRequest(context).create();\n const horizon = 4; // Optimization horizon (The amount of steps required to achieve convergence)\n const vl = Math.pow(horizon, 0.99);// Cautiousness parameter, used to control aggressiveness of the bitrate decision process.\n const alpha = Math.max(Math.pow(horizon, 1), vl * Math.sqrt(horizon));// Step size, used for gradient descent exploration granularity\n const mediaInfo = rulesContext.getMediaInfo();\n const mediaType = rulesContext.getMediaType();\n const bitrates = mediaInfo.bitrateList.map(b => b.bandwidth);\n const bitrateCount = bitrates.length;\n const scheduleController = rulesContext.getScheduleController();\n const streamInfo = rulesContext.getStreamInfo();\n const abrController = rulesContext.getAbrController();\n const throughputHistory = abrController.getThroughputHistory();\n const isDynamic = streamInfo && streamInfo.manifestInfo && streamInfo.manifestInfo.isDynamic;\n const useL2AABR = rulesContext.useL2AABR();\n const bufferLevel = dashMetrics.getCurrentBufferLevel(mediaType, true);\n const safeThroughput = throughputHistory.getSafeAverageThroughput(mediaType, isDynamic);\n const throughput = throughputHistory.getAverageThroughput(mediaType, isDynamic); // In kbits/s\n const react = 2; // Reactiveness to volatility (abrupt throughput drops), used to re-calibrate Lagrangian multiplier Q\n const latency = throughputHistory.getAverageLatency(mediaType);\n const videoModel = rulesContext.getVideoModel();\n let quality;\n let currentPlaybackRate = videoModel.getPlaybackRate();\n\n if (!rulesContext || !rulesContext.hasOwnProperty('getMediaInfo') || !rulesContext.hasOwnProperty('getMediaType') ||\n !rulesContext.hasOwnProperty('getScheduleController') || !rulesContext.hasOwnProperty('getStreamInfo') ||\n !rulesContext.hasOwnProperty('getAbrController') || !rulesContext.hasOwnProperty('useL2AABR')) {\n return switchRequest;\n }\n\n switchRequest.reason = switchRequest.reason || {};\n\n if ((!useL2AABR) || (mediaType === Constants.AUDIO)) {// L2A decides bitrate only for video. Audio to be included in decision process in a later stage\n return switchRequest;\n }\n\n scheduleController.setTimeToLoadDelay(0);\n\n const l2AState = _getL2AState(rulesContext);\n\n if (l2AState.state === L2A_STATE_ONE_BITRATE) {\n // shouldn't even have been called\n return switchRequest;\n }\n\n const l2AParameter = l2AParameterDict[mediaType];\n\n if (!l2AParameter) {\n return switchRequest;\n }\n\n switchRequest.reason.state = l2AState.state;\n switchRequest.reason.throughput = throughput;\n switchRequest.reason.latency = latency;\n\n if (isNaN(throughput)) {\n // still starting up - not enough information\n return switchRequest;\n }\n\n switch (l2AState.state) {\n case L2A_STATE_STARTUP:\n quality = abrController.getQualityForBitrate(mediaInfo, safeThroughput, streamInfo.id, latency);//During strat-up phase abr.controller is responsible for bitrate decisions.\n switchRequest.quality = quality;\n switchRequest.reason.throughput = safeThroughput;\n l2AState.lastQuality = quality;\n\n if (!isNaN(l2AState.lastSegmentDurationS) && bufferLevel >= l2AParameter.B_target) {\n l2AState.state = L2A_STATE_STEADY;\n l2AParameter.Q = vl;// Initialization of Q langrangian multiplier\n // Update of probability vector w, to be used in main adaptation logic of L2A below (steady state)\n for (let i = 0; i < bitrateCount; ++i) {\n if (i === l2AState.lastQuality) {\n l2AParameter.prev_w[i] = 1;\n } else {\n l2AParameter.prev_w[i] = 0;\n }\n }\n }\n\n break; // L2A_STATE_STARTUP\n case L2A_STATE_STEADY:\n let diff1 = [];//Used to calculate the difference between consecutive decisions (w-w_prev)\n\n // Manual calculation of latency and throughput during previous request\n let throughputMeasureTime = dashMetrics.getCurrentHttpRequest(mediaType).trace.reduce((a, b) => a + b.d, 0);\n const downloadBytes = dashMetrics.getCurrentHttpRequest(mediaType).trace.reduce((a, b) => a + b.b[0], 0);\n let lastthroughput = Math.round((8 * downloadBytes) / throughputMeasureTime); // bits/ms = kbits/s\n\n if (lastthroughput < 1) {\n lastthroughput = 1;\n }//To avoid division with 0 (avoid infinity) in case of an absolute network outage\n\n let V = l2AState.lastSegmentDurationS;\n let sign = 1;\n\n //Main adaptation logic of L2A-LL\n for (let i = 0; i < bitrateCount; ++i) {\n bitrates[i] = bitrates[i] / 1000; // Originally in bps, now in Kbps\n if (currentPlaybackRate * bitrates[i] > lastthroughput) {// In this case buffer would deplete, leading to a stall, which increases latency and thus the particular probability of selsection of bitrate[i] should be decreased.\n sign = -1;\n }\n // The objective of L2A is to minimize the overall latency=request-response time + buffer length after download+ potential stalling (if buffer less than chunk downlad time)\n l2AParameter.w[i] = l2AParameter.prev_w[i] + sign * (V / (2 * alpha)) * ((l2AParameter.Q + vl) * (currentPlaybackRate * bitrates[i] / lastthroughput));//Lagrangian descent\n }\n\n // Apply euclidean projection on w to ensure w expresses a probability distribution\n l2AParameter.w = euclideanProjection(l2AParameter.w);\n\n for (let i = 0; i < bitrateCount; ++i) {\n diff1[i] = l2AParameter.w[i] - l2AParameter.prev_w[i];\n l2AParameter.prev_w[i] = l2AParameter.w[i];\n }\n\n // Lagrangian multiplier Q calculation:\n l2AParameter.Q = Math.max(0, l2AParameter.Q - V + V * currentPlaybackRate * ((_dotmultiplication(bitrates, l2AParameter.prev_w) + _dotmultiplication(bitrates, diff1)) / lastthroughput));\n\n // Quality is calculated as argmin of the absolute difference between available bitrates (bitrates[i]) and bitrate estimation (dotmultiplication(w,bitrates)).\n let temp = [];\n for (let i = 0; i < bitrateCount; ++i) {\n temp[i] = Math.abs(bitrates[i] - _dotmultiplication(l2AParameter.w, bitrates));\n }\n\n // Quality is calculated based on the probability distribution w (the output of L2A)\n quality = temp.indexOf(Math.min(...temp));\n\n // We employ a cautious -stepwise- ascent\n if (quality > l2AState.lastQuality) {\n if (bitrates[l2AState.lastQuality + 1] <= lastthroughput) {\n quality = l2AState.lastQuality + 1;\n }\n }\n\n // Provision against bitrate over-estimation, by re-calibrating the Lagrangian multiplier Q, to be taken into account for the next chunk\n if (bitrates[quality] >= lastthroughput) {\n l2AParameter.Q = react * Math.max(vl, l2AParameter.Q);\n }\n\n switchRequest.quality = quality;\n switchRequest.reason.throughput = throughput;\n switchRequest.reason.latency = latency;\n switchRequest.reason.bufferLevel = bufferLevel;\n l2AState.lastQuality = switchRequest.quality;\n break;\n default:\n // should not arrive here, try to recover\n logger.debug('L2A ABR rule invoked in bad state.');\n switchRequest.quality = abrController.getQualityForBitrate(mediaInfo, safeThroughput, streamInfo.id, latency);\n switchRequest.reason.state = l2AState.state;\n switchRequest.reason.throughput = safeThroughput;\n switchRequest.reason.latency = latency;\n l2AState.state = L2A_STATE_STARTUP;\n _clearL2AStateOnSeek(l2AState);\n }\n return switchRequest;\n }\n\n /**\n * Reset objects to their initial state\n * @private\n */\n function _resetInitialSettings() {\n l2AStateDict = {};\n l2AParameterDict = {};\n }\n\n /**\n * Reset the rule\n */\n function reset() {\n _resetInitialSettings();\n eventBus.off(Events.PLAYBACK_SEEKING, _onPlaybackSeeking, instance);\n eventBus.off(Events.MEDIA_FRAGMENT_LOADED, _onMediaFragmentLoaded, instance);\n eventBus.off(Events.METRIC_ADDED, _onMetricAdded, instance);\n eventBus.off(Events.QUALITY_CHANGE_REQUESTED, _onQualityChangeRequested, instance);\n }\n\n instance = {\n getMaxIndex: getMaxIndex,\n reset: reset\n };\n\n setup();\n return instance;\n}\n\nL2ARule.__dashjs_factory_name = 'L2ARule';\nexport default FactoryMaker.getClassFactory(L2ARule);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * Authors:\n * Abdelhak Bentaleb | National University of Singapore | bentaleb@comp.nus.edu.sg\n * Mehmet N. Akcay | Ozyegin University | necmettin.akcay@ozu.edu.tr\n * May Lim | National University of Singapore | maylim@comp.nus.edu.sg\n */\n\nimport FactoryMaker from '../../../../core/FactoryMaker';\nimport Debug from '../../../../core/Debug';\n\nconst WEIGHT_SELECTION_MODES = {\n MANUAL: 'manual_weight_selection',\n RANDOM: 'random_weight_selection',\n DYNAMIC: 'dynamic_weight_selection'\n};\n\nfunction LearningAbrController() {\n const context = this.context;\n\n let instance,\n logger,\n somBitrateNeurons,\n bitrateNormalizationFactor,\n latencyNormalizationFactor,\n minBitrate,\n weights,\n sortedCenters,\n weightSelectionMode;\n\n /**\n * Setup the class\n */\n function _setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n _resetInitialSettings();\n }\n\n /**\n * Reset all values\n */\n function reset() {\n _resetInitialSettings();\n }\n\n /**\n * Reset to initial settings\n * @private\n */\n function _resetInitialSettings() {\n somBitrateNeurons = null;\n bitrateNormalizationFactor = 1;\n latencyNormalizationFactor = 100;\n minBitrate = 0;\n weights = null;\n sortedCenters = null;\n weightSelectionMode = WEIGHT_SELECTION_MODES.DYNAMIC;\n }\n\n /**\n * Returns the maximum throughput\n * @return {number}\n * @private\n */\n function _getMaxThroughput() {\n let maxThroughput = 0;\n\n if (somBitrateNeurons) {\n for (let i = 0; i < somBitrateNeurons.length; i++) {\n let neuron = somBitrateNeurons[i];\n if (neuron.state.throughput > maxThroughput) {\n maxThroughput = neuron.state.throughput;\n }\n }\n }\n\n return maxThroughput;\n }\n\n /**\n *\n * @param {array} w\n * @return {number}\n * @private\n */\n function _getMagnitude(w) {\n const magnitude = w.map((x) => (Math.pow(x, 2))).reduce((sum, now) => sum + now);\n\n return Math.sqrt(magnitude);\n }\n\n /**\n *\n * @param {array} a\n * @param {array} b\n * @param {array} w\n * @return {number}\n * @private\n */\n function _getDistance(a, b, w) {\n let sum = a\n .map((x, i) => (w[i] * (Math.pow(x - b[i], 2)))) // square the difference*w\n .reduce((sum, now) => sum + now); // sum\n let sign = (sum < 0) ? -1 : 1;\n\n return sign * Math.sqrt(Math.abs(sum));\n }\n\n /**\n *\n * @param {object} a\n * @param {object} b\n * @return {number}\n * @private\n */\n function _getNeuronDistance(a, b) {\n let aState = [a.state.throughput, a.state.latency, a.state.rebuffer, a.state.switch];\n let bState = [b.state.throughput, b.state.latency, b.state.rebuffer, b.state.switch];\n\n return _getDistance(aState, bState, [1, 1, 1, 1]);\n }\n\n /**\n *\n * @param {object} winnerNeuron\n * @param {array} somElements\n * @param {array} x\n * @private\n */\n function _updateNeurons(winnerNeuron, somElements, x) {\n for (let i = 0; i < somElements.length; i++) {\n let somNeuron = somElements[i];\n let sigma = 0.1;\n const neuronDistance = _getNeuronDistance(somNeuron, winnerNeuron);\n let neighbourHood = Math.exp(-1 * Math.pow(neuronDistance, 2) / (2 * Math.pow(sigma, 2)));\n _updateNeuronState(somNeuron, x, neighbourHood);\n }\n }\n\n /**\n *\n * @param {object} neuron\n * @param {array} x\n * @param {object} neighbourHood\n * @private\n */\n function _updateNeuronState(neuron, x, neighbourHood) {\n let state = neuron.state;\n let w = [0.01, 0.01, 0.01, 0.01]; // learning rate\n\n state.throughput = state.throughput + (x[0] - state.throughput) * w[0] * neighbourHood;\n state.latency = state.latency + (x[1] - state.latency) * w[1] * neighbourHood;\n state.rebuffer = state.rebuffer + (x[2] - state.rebuffer) * w[2] * neighbourHood;\n state.switch = state.switch + (x[3] - state.switch) * w[3] * neighbourHood;\n }\n\n /**\n *\n * @param {object} currentNeuron\n * @param {number} currentThroughput\n * @return {object}\n * @private\n */\n function _getDownShiftNeuron(currentNeuron, currentThroughput) {\n let maxSuitableBitrate = 0;\n let result = currentNeuron;\n\n if (somBitrateNeurons) {\n for (let i = 0; i < somBitrateNeurons.length; i++) {\n let n = somBitrateNeurons[i];\n if (n.bitrate < currentNeuron.bitrate && n.bitrate > maxSuitableBitrate && currentThroughput > n.bitrate) {\n // possible downshiftable neuron\n maxSuitableBitrate = n.bitrate;\n result = n;\n }\n }\n }\n\n return result;\n }\n\n /**\n *\n * @param {object} mediaInfo\n * @param {number} throughput\n * @param {number} latency\n * @param {number} bufferSize\n * @param {number} playbackRate\n * @param {number} currentQualityIndex\n * @param {object} dynamicWeightsSelector\n * @return {null|*}\n */\n function getNextQuality(mediaInfo, throughput, latency, bufferSize, playbackRate, currentQualityIndex, dynamicWeightsSelector) {\n // For Dynamic Weights Selector\n let currentLatency = latency;\n let currentBuffer = bufferSize;\n let currentThroughput = throughput;\n\n let somElements = _getSomBitrateNeurons(mediaInfo);\n // normalize throughput\n let throughputNormalized = throughput / bitrateNormalizationFactor;\n // saturate values higher than 1\n if (throughputNormalized > 1) {\n throughputNormalized = _getMaxThroughput();\n }\n // normalize latency\n latency = latency / latencyNormalizationFactor;\n\n const targetLatency = 0;\n const targetRebufferLevel = 0;\n const targetSwitch = 0;\n // 10K + video encoding is the recommended throughput\n const throughputDelta = 10000;\n\n logger.debug(`getNextQuality called throughput:${throughputNormalized} latency:${latency} bufferSize:${bufferSize} currentQualityIndex:${currentQualityIndex} playbackRate:${playbackRate}`);\n\n let currentNeuron = somElements[currentQualityIndex];\n let downloadTime = (currentNeuron.bitrate * dynamicWeightsSelector.getSegmentDuration()) / currentThroughput;\n let rebuffer = Math.max(0, (downloadTime - currentBuffer));\n\n // check buffer for possible stall\n if (currentBuffer - downloadTime < dynamicWeightsSelector.getMinBuffer()) {\n logger.debug(`Buffer is low for bitrate= ${currentNeuron.bitrate} downloadTime=${downloadTime} currentBuffer=${currentBuffer} rebuffer=${rebuffer}`);\n return _getDownShiftNeuron(currentNeuron, currentThroughput).qualityIndex;\n }\n\n switch (weightSelectionMode) {\n case WEIGHT_SELECTION_MODES.MANUAL:\n _manualWeightSelection();\n break;\n case WEIGHT_SELECTION_MODES.RANDOM:\n _randomWeightSelection(somElements);\n break;\n case WEIGHT_SELECTION_MODES.DYNAMIC:\n _dynamicWeightSelection(dynamicWeightsSelector, somElements, currentLatency, currentBuffer, rebuffer, currentThroughput, playbackRate);\n break;\n default:\n _dynamicWeightSelection(dynamicWeightsSelector, somElements, currentLatency, currentBuffer, rebuffer, currentThroughput, playbackRate);\n\n }\n\n let minDistance = null;\n let minIndex = null;\n let winnerNeuron = null;\n\n for (let i = 0; i < somElements.length; i++) {\n let somNeuron = somElements[i];\n let somNeuronState = somNeuron.state;\n let somData = [somNeuronState.throughput,\n somNeuronState.latency,\n somNeuronState.rebuffer,\n somNeuronState.switch];\n\n let distanceWeights = weights.slice();\n let nextBuffer = dynamicWeightsSelector.getNextBufferWithBitrate(somNeuron.bitrate, currentBuffer, currentThroughput);\n let isBufferLow = nextBuffer < dynamicWeightsSelector.getMinBuffer();\n if (isBufferLow) {\n logger.debug(`Buffer is low for bitrate=${somNeuron.bitrate} downloadTime=${downloadTime} currentBuffer=${currentBuffer} nextBuffer=${nextBuffer}`);\n }\n // special condition downshift immediately\n if (somNeuron.bitrate > throughput - throughputDelta || isBufferLow) {\n if (somNeuron.bitrate !== minBitrate) {\n // encourage to pick smaller bitrates throughputWeight=100\n distanceWeights[0] = 100;\n }\n }\n\n // calculate the distance with the target\n let distance = _getDistance(somData, [throughputNormalized, targetLatency, targetRebufferLevel, targetSwitch], distanceWeights);\n if (minDistance === null || distance < minDistance) {\n minDistance = distance;\n minIndex = somNeuron.qualityIndex;\n winnerNeuron = somNeuron;\n }\n }\n\n // update current neuron and the neighbourhood with the calculated QoE\n // will punish current if it is not picked\n let bitrateSwitch = Math.abs(currentNeuron.bitrate - winnerNeuron.bitrate) / bitrateNormalizationFactor;\n _updateNeurons(currentNeuron, somElements, [throughputNormalized, latency, rebuffer, bitrateSwitch]);\n\n // update bmu and neighbours with targetQoE=1, targetLatency=0\n _updateNeurons(winnerNeuron, somElements, [throughputNormalized, targetLatency, targetRebufferLevel, bitrateSwitch]);\n\n return minIndex;\n }\n\n /**\n * Option 1: Manual weights\n * @private\n */\n function _manualWeightSelection() {\n let throughputWeight = 0.4;\n let latencyWeight = 0.4;\n let bufferWeight = 0.4;\n let switchWeight = 0.4;\n\n weights = [throughputWeight, latencyWeight, bufferWeight, switchWeight]; // throughput, latency, buffer, switch\n }\n\n /**\n * Option 2: Random (Xavier) weights\n * @param {array} somElements\n * @private\n */\n function _randomWeightSelection(somElements) {\n weights = _getXavierWeights(somElements.length, 4);\n }\n\n /**\n * Dynamic Weight Selector weights\n * @param {object} dynamicWeightsSelector\n * @param {array} somElements\n * @param {number} currentLatency\n * @param {number} currentBuffer\n * @param {number} rebuffer\n * @param {number} currentThroughput\n * @param {number} playbackRate\n * @private\n */\n function _dynamicWeightSelection(dynamicWeightsSelector, somElements, currentLatency, currentBuffer, rebuffer, currentThroughput, playbackRate) {\n if (!weights) {\n weights = sortedCenters[sortedCenters.length - 1];\n }\n // Dynamic Weights Selector (step 2/2: find weights)\n let weightVector = dynamicWeightsSelector.findWeightVector(somElements, currentLatency, currentBuffer, rebuffer, currentThroughput, playbackRate);\n if (weightVector !== null && weightVector !== -1) { // null: something went wrong, -1: constraints not met\n weights = weightVector;\n }\n }\n\n /**\n *\n * @param {number }neuronCount\n * @param {number }weightCount\n * @return {array}\n * @private\n */\n function _getXavierWeights(neuronCount, weightCount) {\n let W = [];\n let upperBound = Math.sqrt((2 / neuronCount));\n\n for (let i = 0; i < weightCount; i++) {\n W.push(Math.random() * upperBound);\n }\n\n weights = W;\n\n return weights;\n }\n\n /**\n *\n * @param {object} mediaInfo\n * @return {array}\n * @private\n */\n function _getSomBitrateNeurons(mediaInfo) {\n if (!somBitrateNeurons) {\n somBitrateNeurons = [];\n const bitrateList = mediaInfo.bitrateList;\n let bitrateVector = [];\n minBitrate = bitrateList[0].bandwidth;\n\n bitrateList.forEach(element => {\n bitrateVector.push(element.bandwidth);\n if (element.bandwidth < minBitrate) {\n minBitrate = element.bandwidth;\n }\n });\n bitrateNormalizationFactor = _getMagnitude(bitrateVector);\n\n for (let i = 0; i < bitrateList.length; i++) {\n let neuron = {\n qualityIndex: i,\n bitrate: bitrateList[i].bandwidth,\n state: {\n // normalize throughputs\n throughput: bitrateList[i].bandwidth / bitrateNormalizationFactor,\n latency: 0,\n rebuffer: 0,\n switch: 0\n }\n };\n somBitrateNeurons.push(neuron);\n }\n\n sortedCenters = _getInitialKmeansPlusPlusCenters(somBitrateNeurons);\n }\n\n return somBitrateNeurons;\n }\n\n /**\n *\n * @param {number} size\n * @return {array}\n * @private\n */\n function _getRandomData(size) {\n let dataArray = [];\n\n for (let i = 0; i < size; i++) {\n let data = [\n Math.random() * _getMaxThroughput(), //throughput\n Math.random(), //latency\n Math.random(), //buffersize\n Math.random() //switch\n ];\n dataArray.push(data);\n }\n\n return dataArray;\n }\n\n /**\n *\n * @param {array} somElements\n * @return {array}\n * @private\n */\n function _getInitialKmeansPlusPlusCenters(somElements) {\n let centers = [];\n let randomDataSet = _getRandomData(Math.pow(somElements.length, 2));\n centers.push(randomDataSet[0]);\n let distanceWeights = [1, 1, 1, 1];\n\n for (let k = 1; k < somElements.length; k++) {\n let nextPoint = null;\n let maxDistance = null;\n for (let i = 0; i < randomDataSet.length; i++) {\n let currentPoint = randomDataSet[i];\n let minDistance = null;\n for (let j = 0; j < centers.length; j++) {\n let distance = _getDistance(currentPoint, centers[j], distanceWeights);\n if (minDistance === null || distance < minDistance) {\n minDistance = distance;\n }\n }\n if (maxDistance === null || minDistance > maxDistance) {\n nextPoint = currentPoint;\n maxDistance = minDistance;\n }\n }\n centers.push(nextPoint);\n }\n\n // find the least similar center\n let maxDistance = null;\n let leastSimilarIndex = null;\n for (let i = 0; i < centers.length; i++) {\n let distance = 0;\n for (let j = 0; j < centers.length; j++) {\n if (i === j) continue;\n distance += _getDistance(centers[i], centers[j], distanceWeights);\n }\n if (maxDistance === null || distance > maxDistance) {\n maxDistance = distance;\n leastSimilarIndex = i;\n }\n }\n\n // move centers to sortedCenters\n let sortedCenters = [];\n sortedCenters.push(centers[leastSimilarIndex]);\n centers.splice(leastSimilarIndex, 1);\n while (centers.length > 0) {\n let minDistance = null;\n let minIndex = null;\n for (let i = 0; i < centers.length; i++) {\n let distance = _getDistance(sortedCenters[0], centers[i], distanceWeights);\n if (minDistance === null || distance < minDistance) {\n minDistance = distance;\n minIndex = i;\n }\n }\n sortedCenters.push(centers[minIndex]);\n centers.splice(minIndex, 1);\n }\n\n return sortedCenters;\n }\n\n instance = {\n getNextQuality,\n reset\n };\n\n _setup();\n return instance;\n}\n\nLearningAbrController.__dashjs_factory_name = 'LearningAbrController';\nexport default FactoryMaker.getClassFactory(LearningAbrController);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * @class\n * @ignore\n */\nclass QoeInfo {\n\n constructor() {\n // Type e.g. 'segment'\n this.type = null;\n\n // Store lastBitrate for calculation of bitrateSwitchWSum\n this.lastBitrate = null;\n\n // Weights for each Qoe factor\n this.weights = {};\n this.weights.bitrateReward = null;\n this.weights.bitrateSwitchPenalty = null;\n this.weights.rebufferPenalty = null;\n this.weights.latencyPenalty = null;\n this.weights.playbackSpeedPenalty = null;\n\n // Weighted Sum for each Qoe factor\n this.bitrateWSum = 0; // kbps\n this.bitrateSwitchWSum = 0; // kbps\n this.rebufferWSum = 0; // seconds\n this.latencyWSum = 0; // seconds\n this.playbackSpeedWSum = 0; // e.g. 0.95, 1.0, 1.05\n\n // Store total Qoe value based on current Weighted Sum values\n this.totalQoe = 0;\n }\n}\n\nexport default QoeInfo;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * Authors:\n * Abdelhak Bentaleb | National University of Singapore | bentaleb@comp.nus.edu.sg\n * Mehmet N. Akcay | Ozyegin University | necmettin.akcay@ozu.edu.tr\n * May Lim | National University of Singapore | maylim@comp.nus.edu.sg\n */\nimport FactoryMaker from '../../../../core/FactoryMaker';\nimport QoeInfo from './QoeInfo';\n\nfunction LoLpQoeEvaluator() {\n\n let instance,\n voPerSegmentQoeInfo,\n segmentDuration,\n maxBitrateKbps,\n minBitrateKbps;\n\n function _setup() {\n _resetInitialSettings();\n }\n\n function _resetInitialSettings() {\n voPerSegmentQoeInfo = null;\n segmentDuration = null;\n maxBitrateKbps = null;\n minBitrateKbps = null;\n }\n\n function setupPerSegmentQoe(sDuration, maxBrKbps, minBrKbps) {\n // Set up Per Segment QoeInfo\n voPerSegmentQoeInfo = _createQoeInfo('segment', sDuration, maxBrKbps, minBrKbps);\n segmentDuration = sDuration;\n maxBitrateKbps = maxBrKbps;\n minBitrateKbps = minBrKbps;\n }\n\n function _createQoeInfo(fragmentType, fragmentDuration, maxBitrateKbps, minBitrateKbps) {\n /*\n * [Weights][Source: Abdelhak Bentaleb, 2020 (last updated: 30 Mar 2020)]\n * bitrateReward: segment duration, e.g. 0.5s\n * bitrateSwitchPenalty: 0.02s or 1s if the bitrate switch is too important\n * rebufferPenalty: max encoding bitrate, e.g. 1000kbps\n * latencyPenalty: if L ≤ 1.1 seconds then = min encoding bitrate * 0.05, otherwise = max encoding bitrate * 0.1\n * playbackSpeedPenalty: min encoding bitrate, e.g. 200kbps\n */\n\n // Create new QoeInfo object\n let qoeInfo = new QoeInfo();\n qoeInfo.type = fragmentType;\n\n // Set weight: bitrateReward\n // set some safe value, else consider throwing error\n if (!fragmentDuration) {\n qoeInfo.weights.bitrateReward = 1;\n }\n else {\n qoeInfo.weights.bitrateReward = fragmentDuration;\n }\n\n // Set weight: bitrateSwitchPenalty\n // qoeInfo.weights.bitrateSwitchPenalty = 0.02;\n qoeInfo.weights.bitrateSwitchPenalty = 1;\n\n // Set weight: rebufferPenalty\n // set some safe value, else consider throwing error\n if (!maxBitrateKbps) {\n qoeInfo.weights.rebufferPenalty = 1000;\n }\n else {\n qoeInfo.weights.rebufferPenalty = maxBitrateKbps;\n }\n\n // Set weight: latencyPenalty\n qoeInfo.weights.latencyPenalty = [];\n qoeInfo.weights.latencyPenalty.push({ threshold: 1.1, penalty: (minBitrateKbps * 0.05) });\n qoeInfo.weights.latencyPenalty.push({ threshold: 100000000, penalty: (maxBitrateKbps * 0.1) });\n\n // Set weight: playbackSpeedPenalty\n if (!minBitrateKbps) qoeInfo.weights.playbackSpeedPenalty = 200; // set some safe value, else consider throwing error\n else qoeInfo.weights.playbackSpeedPenalty = minBitrateKbps;\n\n return qoeInfo;\n }\n\n function logSegmentMetrics(segmentBitrate, segmentRebufferTime, currentLatency, currentPlaybackSpeed) {\n if (voPerSegmentQoeInfo) {\n _logMetricsInQoeInfo(segmentBitrate, segmentRebufferTime, currentLatency, currentPlaybackSpeed, voPerSegmentQoeInfo);\n }\n }\n\n function _logMetricsInQoeInfo(bitrate, rebufferTime, latency, playbackSpeed, qoeInfo) {\n // Update: bitrate Weighted Sum value\n qoeInfo.bitrateWSum += (qoeInfo.weights.bitrateReward * bitrate);\n\n // Update: bitrateSwitch Weighted Sum value\n if (qoeInfo.lastBitrate) {\n qoeInfo.bitrateSwitchWSum += (qoeInfo.weights.bitrateSwitchPenalty * Math.abs(bitrate - qoeInfo.lastBitrate));\n }\n qoeInfo.lastBitrate = bitrate;\n\n // Update: rebuffer Weighted Sum value\n qoeInfo.rebufferWSum += (qoeInfo.weights.rebufferPenalty * rebufferTime);\n\n // Update: latency Weighted Sum value\n for (let i = 0; i < qoeInfo.weights.latencyPenalty.length; i++) {\n let latencyRange = qoeInfo.weights.latencyPenalty[i];\n if (latency <= latencyRange.threshold) {\n qoeInfo.latencyWSum += (latencyRange.penalty * latency);\n break;\n }\n }\n\n // Update: playbackSpeed Weighted Sum value\n qoeInfo.playbackSpeedWSum += (qoeInfo.weights.playbackSpeedPenalty * Math.abs(1 - playbackSpeed));\n\n // Update: Total Qoe value\n qoeInfo.totalQoe = qoeInfo.bitrateWSum - qoeInfo.bitrateSwitchWSum - qoeInfo.rebufferWSum - qoeInfo.latencyWSum - qoeInfo.playbackSpeedWSum;\n }\n\n // Returns current Per Segment QoeInfo\n function getPerSegmentQoe() {\n return voPerSegmentQoeInfo;\n }\n\n // For one-time use only\n // Returns totalQoe based on a single set of metrics.\n function calculateSingleUseQoe(segmentBitrate, segmentRebufferTime, currentLatency, currentPlaybackSpeed) {\n let singleUseQoeInfo = null;\n\n if (segmentDuration && maxBitrateKbps && minBitrateKbps) {\n singleUseQoeInfo = _createQoeInfo('segment', segmentDuration, maxBitrateKbps, minBitrateKbps);\n }\n\n if (singleUseQoeInfo) {\n _logMetricsInQoeInfo(segmentBitrate, segmentRebufferTime, currentLatency, currentPlaybackSpeed, singleUseQoeInfo);\n return singleUseQoeInfo.totalQoe;\n } else {\n // Something went wrong..\n return 0;\n }\n }\n\n function reset() {\n _resetInitialSettings();\n }\n\n instance = {\n setupPerSegmentQoe,\n logSegmentMetrics,\n getPerSegmentQoe,\n calculateSingleUseQoe,\n reset\n };\n\n _setup();\n\n return instance;\n}\n\nLoLpQoeEvaluator.__dashjs_factory_name = 'LoLpQoeEvaluator';\nexport default FactoryMaker.getClassFactory(LoLpQoeEvaluator);\n\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * Authors:\n * Abdelhak Bentaleb | National University of Singapore | bentaleb@comp.nus.edu.sg\n * Mehmet N. Akcay | Ozyegin University | necmettin.akcay@ozu.edu.tr\n * May Lim | National University of Singapore | maylim@comp.nus.edu.sg\n */\n\nimport FactoryMaker from '../../../../core/FactoryMaker';\n\nfunction LoLpWeightSelector(config) {\n let targetLatency = config.targetLatency;\n let bufferMin = config.bufferMin;\n let segmentDuration = config.segmentDuration;\n let qoeEvaluator = config.qoeEvaluator;\n let instance,\n valueList,\n weightTypeCount,\n weightOptions,\n previousLatency;\n\n /**\n *\n * @private\n */\n function _setup() {\n _resetInitialSettings();\n }\n\n /**\n *\n * @private\n */\n function _resetInitialSettings() {\n valueList = [0.2, 0.4, 0.6, 0.8, 1];\n weightTypeCount = 4;\n weightOptions = _getPermutations(valueList, weightTypeCount);\n previousLatency = 0;\n }\n\n /**\n * Next, at each segment boundary, ABR to input current neurons and target state (only used in Method II) to find the desired weight vector\n * @param {array} neurons\n * @param {number} currentLatency\n * @param {number} currentBuffer\n * @param {number} currentRebuffer\n * @param {number} currentThroughput\n * @param {number} playbackRate\n * @return {null}\n * @private\n */\n function findWeightVector(neurons, currentLatency, currentBuffer, currentRebuffer, currentThroughput, playbackRate) {\n let maxQoE = null;\n let winnerWeights = null;\n let winnerBitrate = null;\n let deltaLatency = Math.abs(currentLatency - previousLatency);\n\n // For each neuron, m\n neurons.forEach((neuron) => {\n\n // For each possible weight vector, z\n // E.g. For [ throughput, latency, buffer, playbackRate, QoE ]\n // Possible weightVector = [ 0.2, 0.4, 0.2, 0, 0.2 ]\n weightOptions.forEach((weightVector) => {\n\n // Apply weightVector to neuron, compute utility and determine winnerWeights\n // Method I: Utility based on QoE given current state\n\n let weightsObj = {\n throughput: weightVector[0],\n latency: weightVector[1],\n buffer: weightVector[2],\n switch: weightVector[3]\n };\n\n let downloadTime = (neuron.bitrate * segmentDuration) / currentThroughput;\n let nextBuffer = getNextBuffer(currentBuffer, downloadTime);\n let rebuffer = Math.max(0.00001, (downloadTime - nextBuffer));\n let wt;\n if (weightsObj.buffer === 0) {\n wt = 10;\n } else {\n wt = (1 / weightsObj.buffer);\n }\n let weightedRebuffer = wt * rebuffer;\n\n if (weightsObj.latency === 0) {\n wt = 10;\n } else {\n wt = (1 / weightsObj.latency); // inverse the weight because wt and latency should have positive relationship, i.e., higher latency = higher wt\n }\n let weightedLatency = wt * neuron.state.latency;\n\n let totalQoE = qoeEvaluator.calculateSingleUseQoe(neuron.bitrate, weightedRebuffer, weightedLatency, playbackRate);\n if ((maxQoE === null || totalQoE > maxQoE) && _checkConstraints(currentLatency, nextBuffer, deltaLatency)) {\n maxQoE = totalQoE;\n winnerWeights = weightVector;\n winnerBitrate = neuron.bitrate;\n }\n });\n });\n\n // winnerWeights was found, check if constraints are satisfied\n if (winnerWeights === null && winnerBitrate === null) {\n winnerWeights = -1;\n }\n\n previousLatency = currentLatency;\n return winnerWeights;\n }\n\n /**\n *\n * @param {number} nextLatency\n * @param {number} nextBuffer\n * @param {number} deltaLatency\n * @return {boolean}\n * @private\n */\n function _checkConstraints(nextLatency, nextBuffer, deltaLatency) {\n // A1\n // disabled till we find a better way of estimating latency\n // fails for all with current value\n if (nextLatency > targetLatency + deltaLatency) {\n return false;\n }\n\n return nextBuffer >= bufferMin;\n }\n\n /**\n *\n * @param {array} list\n * @param {number} length\n * @return {*}\n * @private\n */\n function _getPermutations(list, length) {\n // Copy initial values as arrays\n let perm = list.map(function (val) {\n return [val];\n });\n // Our permutation generator\n let generate = function (perm, length, currLen) {\n // Reached desired length\n if (currLen === length) {\n return perm;\n }\n // For each existing permutation\n let len = perm.length;\n for (let i = 0; i < len; i++) {\n let currPerm = perm.shift();\n // Create new permutation\n for (let k = 0; k < list.length; k++) {\n perm.push(currPerm.concat(list[k]));\n }\n }\n // Recurse\n return generate(perm, length, currLen + 1);\n };\n // Start with size 1 because of initial values\n return generate(perm, length, 1);\n }\n\n /**\n *\n * @return {number}\n */\n function getMinBuffer() {\n return bufferMin;\n }\n\n /**\n *\n * @return {number}\n */\n function getSegmentDuration() {\n return segmentDuration;\n }\n\n /**\n *\n * @param {number} bitrateToDownload\n * @param {number} currentBuffer\n * @param {number} currentThroughput\n * @return {number}\n */\n function getNextBufferWithBitrate(bitrateToDownload, currentBuffer, currentThroughput) {\n let downloadTime = (bitrateToDownload * segmentDuration) / currentThroughput;\n return getNextBuffer(currentBuffer, downloadTime);\n }\n\n /**\n *\n * @param {number} currentBuffer\n * @param {number} downloadTime\n * @return {number}\n */\n function getNextBuffer(currentBuffer, downloadTime) {\n const segmentDuration = getSegmentDuration();\n let nextBuffer;\n if (downloadTime > segmentDuration) {\n nextBuffer = currentBuffer - segmentDuration;\n } else {\n nextBuffer = currentBuffer + segmentDuration - downloadTime;\n }\n return nextBuffer;\n }\n\n instance = {\n getMinBuffer,\n getSegmentDuration,\n getNextBufferWithBitrate,\n getNextBuffer,\n findWeightVector\n };\n\n _setup();\n\n return instance;\n}\n\nLoLpWeightSelector.__dashjs_factory_name = 'LoLpWeightSelector';\nexport default FactoryMaker.getClassFactory(LoLpWeightSelector);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * Authors:\n * Abdelhak Bentaleb | National University of Singapore | bentaleb@comp.nus.edu.sg\n * Mehmet N. Akcay | Ozyegin University | necmettin.akcay@ozu.edu.tr\n * May Lim | National University of Singapore | maylim@comp.nus.edu.sg\n */\n\nimport Debug from '../../../../core/Debug';\nimport FactoryMaker from '../../../../core/FactoryMaker';\nimport LearningAbrController from './LearningAbrController';\nimport LoLpQoeEvaluator from './LoLpQoEEvaluator';\nimport SwitchRequest from '../../SwitchRequest';\nimport MetricsConstants from '../../../constants/MetricsConstants';\nimport LoLpWeightSelector from './LoLpWeightSelector';\nimport Constants from '../../../constants/Constants';\n\nconst DWS_TARGET_LATENCY = 1.5;\nconst DWS_BUFFER_MIN = 0.3;\n\nfunction LoLPRule(config) {\n\n config = config || {};\n\n let dashMetrics = config.dashMetrics;\n let context = this.context;\n\n let logger,\n instance,\n learningController,\n qoeEvaluator;\n\n function _setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n learningController = LearningAbrController(context).create();\n qoeEvaluator = LoLpQoeEvaluator(context).create();\n }\n\n function getMaxIndex(rulesContext) {\n try {\n let switchRequest = SwitchRequest(context).create();\n let mediaType = rulesContext.getMediaInfo().type;\n let abrController = rulesContext.getAbrController();\n const streamInfo = rulesContext.getStreamInfo();\n let currentQuality = abrController.getQualityFor(mediaType, streamInfo.id);\n const mediaInfo = rulesContext.getMediaInfo();\n const bufferStateVO = dashMetrics.getCurrentBufferState(mediaType);\n const scheduleController = rulesContext.getScheduleController();\n const currentBufferLevel = dashMetrics.getCurrentBufferLevel(mediaType, true);\n const isDynamic = streamInfo && streamInfo.manifestInfo ? streamInfo.manifestInfo.isDynamic : null;\n const playbackController = scheduleController.getPlaybackController();\n let latency = playbackController.getCurrentLiveLatency();\n\n if (!rulesContext.useLoLPABR() || (mediaType === Constants.AUDIO)) {\n return switchRequest;\n }\n\n if (!latency) {\n latency = 0;\n }\n\n const playbackRate = playbackController.getPlaybackRate();\n const throughputHistory = abrController.getThroughputHistory();\n const throughput = throughputHistory.getSafeAverageThroughput(mediaType, isDynamic);\n logger.debug(`Throughput ${Math.round(throughput)} kbps`);\n\n if (isNaN(throughput) || !bufferStateVO) {\n return switchRequest;\n }\n\n if (abrController.getAbandonmentStateFor(streamInfo.id, mediaType) === MetricsConstants.ABANDON_LOAD) {\n return switchRequest;\n }\n\n // QoE parameters\n let bitrateList = mediaInfo.bitrateList; // [{bandwidth: 200000, width: 640, height: 360}, ...]\n let segmentDuration = rulesContext.getRepresentationInfo().fragmentDuration;\n let minBitrateKbps = bitrateList[0].bandwidth / 1000.0; // min bitrate level\n let maxBitrateKbps = bitrateList[bitrateList.length - 1].bandwidth / 1000.0; // max bitrate level\n for (let i = 0; i < bitrateList.length; i++) { // in case bitrateList is not sorted as expected\n let b = bitrateList[i].bandwidth / 1000.0;\n if (b > maxBitrateKbps)\n maxBitrateKbps = b;\n else if (b < minBitrateKbps) {\n minBitrateKbps = b;\n }\n }\n\n // Learning rule pre-calculations\n let currentBitrate = bitrateList[currentQuality].bandwidth;\n let currentBitrateKbps = currentBitrate / 1000.0;\n let httpRequest = dashMetrics.getCurrentHttpRequest(mediaType, true);\n let lastFragmentDownloadTime = (httpRequest.tresponse.getTime() - httpRequest.trequest.getTime()) / 1000;\n let segmentRebufferTime = lastFragmentDownloadTime > segmentDuration ? lastFragmentDownloadTime - segmentDuration : 0;\n qoeEvaluator.setupPerSegmentQoe(segmentDuration, maxBitrateKbps, minBitrateKbps);\n qoeEvaluator.logSegmentMetrics(currentBitrateKbps, segmentRebufferTime, latency, playbackRate);\n\n /*\n * Dynamic Weights Selector (step 1/2: initialization)\n */\n let dynamicWeightsSelector = LoLpWeightSelector(context).create({\n targetLatency: DWS_TARGET_LATENCY,\n bufferMin: DWS_BUFFER_MIN,\n segmentDuration,\n qoeEvaluator\n });\n\n /*\n * Select next quality\n */\n switchRequest.quality = learningController.getNextQuality(mediaInfo, throughput * 1000, latency, currentBufferLevel, playbackRate, currentQuality, dynamicWeightsSelector);\n switchRequest.reason = { throughput: throughput, latency: latency };\n switchRequest.priority = SwitchRequest.PRIORITY.STRONG;\n\n scheduleController.setTimeToLoadDelay(0);\n\n if (switchRequest.quality !== currentQuality) {\n console.log('[TgcLearningRule][' + mediaType + '] requesting switch to index: ', switchRequest.quality, 'Average throughput', Math.round(throughput), 'kbps');\n }\n\n return switchRequest;\n } catch (e) {\n throw e;\n }\n }\n\n /**\n * Reset objects to their initial state\n * @private\n */\n function _resetInitialSettings() {\n learningController.reset();\n qoeEvaluator.reset();\n }\n\n /**\n * Reset the rule\n */\n function reset() {\n _resetInitialSettings();\n }\n\n instance = {\n getMaxIndex,\n reset\n };\n\n _setup();\n\n return instance;\n}\n\nLoLPRule.__dashjs_factory_name = 'LoLPRule';\nexport default FactoryMaker.getClassFactory(LoLPRule);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport ThroughputRule from './ThroughputRule';\nimport InsufficientBufferRule from './InsufficientBufferRule';\nimport AbandonRequestsRule from './AbandonRequestsRule';\nimport DroppedFramesRule from './DroppedFramesRule';\nimport SwitchHistoryRule from './SwitchHistoryRule';\nimport BolaRule from './BolaRule';\nimport L2ARule from './L2ARule.js';\nimport LoLPRule from './lolp/LoLpRule.js';\nimport FactoryMaker from '../../../core/FactoryMaker';\nimport SwitchRequest from '../SwitchRequest';\nimport Constants from '../../constants/Constants';\n\nconst QUALITY_SWITCH_RULES = 'qualitySwitchRules';\nconst ABANDON_FRAGMENT_RULES = 'abandonFragmentRules';\n\n\nfunction ABRRulesCollection(config) {\n\n config = config || {};\n const context = this.context;\n\n const mediaPlayerModel = config.mediaPlayerModel;\n const dashMetrics = config.dashMetrics;\n const settings = config.settings;\n\n let instance,\n qualitySwitchRules,\n abandonFragmentRules;\n\n function initialize() {\n qualitySwitchRules = [];\n abandonFragmentRules = [];\n\n if (settings.get().streaming.abr.useDefaultABRRules) {\n\n // If L2A is used we only need this one rule\n if (settings.get().streaming.abr.ABRStrategy === Constants.ABR_STRATEGY_L2A) {\n qualitySwitchRules.push(\n L2ARule(context).create({\n dashMetrics: dashMetrics,\n mediaPlayerModel: mediaPlayerModel,\n settings: settings\n })\n );\n }\n // If LoLP is used we only need this one rule\n else if (settings.get().streaming.abr.ABRStrategy === Constants.ABR_STRATEGY_LoLP) {\n qualitySwitchRules.push(\n LoLPRule(context).create({\n dashMetrics: dashMetrics\n })\n );\n } else {\n // Only one of BolaRule and ThroughputRule will give a switchRequest.quality !== SwitchRequest.NO_CHANGE.\n // This is controlled by useBufferOccupancyABR mechanism in AbrController.\n qualitySwitchRules.push(\n BolaRule(context).create({\n dashMetrics: dashMetrics,\n mediaPlayerModel: mediaPlayerModel,\n settings: settings\n })\n );\n\n qualitySwitchRules.push(\n ThroughputRule(context).create({\n dashMetrics: dashMetrics\n })\n );\n\n if (settings.get().streaming.abr.additionalAbrRules.insufficientBufferRule) {\n qualitySwitchRules.push(\n InsufficientBufferRule(context).create({\n dashMetrics: dashMetrics,\n settings\n })\n );\n }\n\n if (settings.get().streaming.abr.additionalAbrRules.switchHistoryRule) {\n qualitySwitchRules.push(\n SwitchHistoryRule(context).create()\n );\n }\n\n if (settings.get().streaming.abr.additionalAbrRules.droppedFramesRule) {\n qualitySwitchRules.push(\n DroppedFramesRule(context).create()\n );\n }\n\n if (settings.get().streaming.abr.additionalAbrRules.abandonRequestsRule) {\n abandonFragmentRules.push(\n AbandonRequestsRule(context).create({\n dashMetrics: dashMetrics,\n mediaPlayerModel: mediaPlayerModel,\n settings: settings\n })\n );\n }\n }\n }\n\n // add custom ABR rules if any\n const customRules = mediaPlayerModel.getABRCustomRules();\n customRules.forEach(function (rule) {\n if (rule.type === QUALITY_SWITCH_RULES) {\n qualitySwitchRules.push(rule.rule(context).create());\n }\n\n if (rule.type === ABANDON_FRAGMENT_RULES) {\n abandonFragmentRules.push(rule.rule(context).create());\n }\n });\n }\n\n function _getRulesWithChange(srArray) {\n return srArray.filter(sr => sr.quality > SwitchRequest.NO_CHANGE);\n }\n\n /**\n *\n * @param {array} srArray\n * @return {object} SwitchRequest\n */\n function getMinSwitchRequest(srArray) {\n const values = {};\n let newSwitchReq = null;\n let i,\n len,\n req,\n quality,\n reason;\n\n if (srArray.length === 0) {\n return;\n }\n\n values[SwitchRequest.PRIORITY.STRONG] = { quality: SwitchRequest.NO_CHANGE, reason: null };\n values[SwitchRequest.PRIORITY.WEAK] = { quality: SwitchRequest.NO_CHANGE, reason: null };\n values[SwitchRequest.PRIORITY.DEFAULT] = { quality: SwitchRequest.NO_CHANGE, reason: null };\n\n for (i = 0, len = srArray.length; i < len; i += 1) {\n req = srArray[i];\n if (req.quality !== SwitchRequest.NO_CHANGE) {\n // We only use the new quality in case it is lower than the already saved one or if no new quality has been selected for the respective priority\n if (values[req.priority].quality === SwitchRequest.NO_CHANGE || values[req.priority].quality > req.quality) {\n values[req.priority].quality = req.quality;\n values[req.priority].reason = req.reason || null;\n }\n }\n }\n\n if (values[SwitchRequest.PRIORITY.WEAK].quality !== SwitchRequest.NO_CHANGE) {\n newSwitchReq = values[SwitchRequest.PRIORITY.WEAK];\n }\n\n if (values[SwitchRequest.PRIORITY.DEFAULT].quality !== SwitchRequest.NO_CHANGE) {\n newSwitchReq = values[SwitchRequest.PRIORITY.DEFAULT];\n }\n\n if (values[SwitchRequest.PRIORITY.STRONG].quality !== SwitchRequest.NO_CHANGE) {\n newSwitchReq = values[SwitchRequest.PRIORITY.STRONG];\n }\n\n if (newSwitchReq) {\n quality = newSwitchReq.quality;\n reason = newSwitchReq.reason;\n }\n\n return SwitchRequest(context).create(quality, reason);\n }\n\n function getMaxQuality(rulesContext) {\n const switchRequestArray = qualitySwitchRules.map(rule => rule.getMaxIndex(rulesContext));\n const activeRules = _getRulesWithChange(switchRequestArray);\n const maxQuality = getMinSwitchRequest(activeRules);\n\n return maxQuality || SwitchRequest(context).create();\n }\n\n function shouldAbandonFragment(rulesContext, streamId) {\n const abandonRequestArray = abandonFragmentRules.map(rule => rule.shouldAbandon(rulesContext, streamId));\n const activeRules = _getRulesWithChange(abandonRequestArray);\n const shouldAbandon = getMinSwitchRequest(activeRules);\n\n return shouldAbandon || SwitchRequest(context).create();\n }\n\n function reset() {\n [qualitySwitchRules, abandonFragmentRules].forEach(rules => {\n if (rules && rules.length) {\n rules.forEach(rule => rule.reset && rule.reset());\n }\n });\n qualitySwitchRules = [];\n abandonFragmentRules = [];\n }\n\n function getQualitySwitchRules() {\n return qualitySwitchRules;\n }\n\n instance = {\n initialize,\n reset,\n getMaxQuality,\n getMinSwitchRequest,\n shouldAbandonFragment,\n getQualitySwitchRules\n };\n\n return instance;\n}\n\nABRRulesCollection.__dashjs_factory_name = 'ABRRulesCollection';\nconst factory = FactoryMaker.getClassFactory(ABRRulesCollection);\nfactory.QUALITY_SWITCH_RULES = QUALITY_SWITCH_RULES;\nfactory.ABANDON_FRAGMENT_RULES = ABANDON_FRAGMENT_RULES;\nFactoryMaker.updateSingletonFactory(ABRRulesCollection.__dashjs_factory_name, factory);\n\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport UTCTiming from '../../dash/vo/UTCTiming';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Constants from '../constants/Constants';\nimport ABRRulesCollection from '../rules/abr/ABRRulesCollection';\nimport Settings from '../../core/Settings';\nimport {checkParameterType} from '../utils/SupervisorTools';\n\n\nconst DEFAULT_MIN_BUFFER_TIME = 12;\nconst DEFAULT_MIN_BUFFER_TIME_FAST_SWITCH = 20;\n\nconst DEFAULT_LOW_LATENCY_LIVE_DELAY = 3.0;\nconst LOW_LATENCY_REDUCTION_FACTOR = 10;\nconst LOW_LATENCY_MULTIPLY_FACTOR = 5;\nconst DEFAULT_LIVE_LATENCY_CATCHUP_THRESHOLD_FACTOR = 4;\nconst MINIMUM_LIVE_LATENCY_CATCHUP = 5;\n\nconst DEFAULT_XHR_WITH_CREDENTIALS = false;\n\nfunction MediaPlayerModel() {\n\n let instance,\n UTCTimingSources,\n xhrWithCredentials,\n customABRRule;\n\n const context = this.context;\n const settings = Settings(context).getInstance();\n\n function setup() {\n UTCTimingSources = [];\n xhrWithCredentials = {\n default: DEFAULT_XHR_WITH_CREDENTIALS\n };\n customABRRule = [];\n }\n\n //TODO Should we use Object.define to have setters/getters? makes more readable code on other side.\n function findABRCustomRuleIndex(rulename) {\n let i;\n for (i = 0; i < customABRRule.length; i++) {\n if (customABRRule[i].rulename === rulename) {\n return i;\n }\n }\n return -1;\n }\n\n function getABRCustomRules() {\n return customABRRule;\n }\n\n function addABRCustomRule(type, rulename, rule) {\n if (typeof type !== 'string' || (type !== ABRRulesCollection.ABANDON_FRAGMENT_RULES && type !== ABRRulesCollection.QUALITY_SWITCH_RULES) ||\n typeof rulename !== 'string') {\n throw Constants.BAD_ARGUMENT_ERROR;\n }\n let index = findABRCustomRuleIndex(rulename);\n if (index === -1) {\n // add rule\n customABRRule.push({\n type: type,\n rulename: rulename,\n rule: rule\n });\n } else {\n // update rule\n customABRRule[index].type = type;\n customABRRule[index].rule = rule;\n }\n }\n\n function removeABRCustomRule(rulename) {\n if (rulename) {\n let index = findABRCustomRuleIndex(rulename);\n //if no rulename custom rule has been found, do nothing\n if (index !== -1) {\n // remove rule\n customABRRule.splice(index, 1);\n }\n } else {\n //if no rulename is defined, remove all ABR custome rules\n customABRRule = [];\n }\n }\n\n function getInitialBufferLevel() {\n const initialBufferLevel = settings.get().streaming.buffer.initialBufferLevel;\n\n if (isNaN(initialBufferLevel) || initialBufferLevel < 0) {\n return 0;\n }\n\n return Math.min(getStableBufferTime(), initialBufferLevel);\n }\n\n function getStableBufferTime() {\n if (settings.get().streaming.lowLatencyEnabled) {\n return getLiveDelay();\n }\n\n const stableBufferTime = settings.get().streaming.buffer.stableBufferTime;\n return stableBufferTime > 0 ? stableBufferTime : settings.get().streaming.buffer.fastSwitchEnabled ? DEFAULT_MIN_BUFFER_TIME_FAST_SWITCH : DEFAULT_MIN_BUFFER_TIME;\n }\n\n function getRetryAttemptsForType(type) {\n const lowLatencyMultiplyFactor = !isNaN(settings.get().streaming.retryAttempts.lowLatencyMultiplyFactor) ? settings.get().streaming.retryAttempts.lowLatencyMultiplyFactor : LOW_LATENCY_MULTIPLY_FACTOR;\n\n return settings.get().streaming.lowLatencyEnabled ? settings.get().streaming.retryAttempts[type] * lowLatencyMultiplyFactor : settings.get().streaming.retryAttempts[type];\n }\n\n function getRetryIntervalsForType(type) {\n const lowLatencyReductionFactor = !isNaN(settings.get().streaming.retryIntervals.lowLatencyReductionFactor) ? settings.get().streaming.retryIntervals.lowLatencyReductionFactor : LOW_LATENCY_REDUCTION_FACTOR;\n\n return settings.get().streaming.lowLatencyEnabled ? settings.get().streaming.retryIntervals[type] / lowLatencyReductionFactor : settings.get().streaming.retryIntervals[type];\n }\n\n function getLiveDelay() {\n if (settings.get().streaming.lowLatencyEnabled) {\n return settings.get().streaming.delay.liveDelay || DEFAULT_LOW_LATENCY_LIVE_DELAY;\n }\n return settings.get().streaming.delay.liveDelay;\n }\n\n function getLiveCatchupLatencyThreshold() {\n try {\n const liveCatchupLatencyThreshold = settings.get().streaming.liveCatchup.latencyThreshold;\n const liveDelay = getLiveDelay();\n\n if (liveCatchupLatencyThreshold !== null && !isNaN(liveCatchupLatencyThreshold)) {\n return Math.max(liveCatchupLatencyThreshold, liveDelay);\n }\n\n\n const liveCatchupMinDrift = settings.get().streaming.liveCatchup.minDrift;\n const maximumLiveDelay = !isNaN(liveDelay) && liveDelay ? !isNaN(liveCatchupMinDrift) ? settings.get().streaming.liveCatchup.minDrift + getLiveDelay() : getLiveDelay() : NaN;\n\n if (maximumLiveDelay && !isNaN(maximumLiveDelay)) {\n return Math.max(maximumLiveDelay * DEFAULT_LIVE_LATENCY_CATCHUP_THRESHOLD_FACTOR, MINIMUM_LIVE_LATENCY_CATCHUP);\n }\n\n return NaN;\n\n } catch (e) {\n return NaN;\n }\n }\n\n function addUTCTimingSource(schemeIdUri, value) {\n removeUTCTimingSource(schemeIdUri, value); //check if it already exists and remove if so.\n let vo = new UTCTiming();\n vo.schemeIdUri = schemeIdUri;\n vo.value = value;\n UTCTimingSources.push(vo);\n }\n\n function getUTCTimingSources() {\n return UTCTimingSources;\n }\n\n function removeUTCTimingSource(schemeIdUri, value) {\n checkParameterType(schemeIdUri, 'string');\n checkParameterType(value, 'string');\n UTCTimingSources.forEach(function (obj, idx) {\n if (obj.schemeIdUri === schemeIdUri && obj.value === value) {\n UTCTimingSources.splice(idx, 1);\n }\n });\n }\n\n function clearDefaultUTCTimingSources() {\n UTCTimingSources = [];\n }\n\n function restoreDefaultUTCTimingSources() {\n let defaultUtcTimingSource = settings.get().streaming.utcSynchronization.defaultTimingSource;\n addUTCTimingSource(defaultUtcTimingSource.scheme, defaultUtcTimingSource.value);\n }\n\n function setXHRWithCredentialsForType(type, value) {\n if (!type) {\n Object.keys(xhrWithCredentials).forEach(key => {\n setXHRWithCredentialsForType(key, value);\n });\n } else {\n xhrWithCredentials[type] = !!value;\n }\n }\n\n function getXHRWithCredentialsForType(type) {\n const useCreds = xhrWithCredentials[type];\n\n return useCreds === undefined ? xhrWithCredentials.default : useCreds;\n }\n\n function getDefaultUtcTimingSource() {\n return settings.get().streaming.utcSynchronization.defaultTimingSource;\n }\n\n function reset() {\n //TODO need to figure out what props to persist across sessions and which to reset if any.\n //setup();\n }\n\n instance = {\n getABRCustomRules,\n addABRCustomRule,\n removeABRCustomRule,\n getStableBufferTime,\n getInitialBufferLevel,\n getRetryAttemptsForType,\n getRetryIntervalsForType,\n getLiveDelay,\n getLiveCatchupLatencyThreshold,\n addUTCTimingSource,\n removeUTCTimingSource,\n getUTCTimingSources,\n clearDefaultUTCTimingSources,\n restoreDefaultUTCTimingSources,\n setXHRWithCredentialsForType,\n getXHRWithCredentialsForType,\n getDefaultUtcTimingSource,\n reset\n };\n\n setup();\n\n return instance;\n}\n\n//TODO see if you can move this and not export and just getter to get default value.\nMediaPlayerModel.__dashjs_factory_name = 'MediaPlayerModel';\nexport default FactoryMaker.getSingletonFactory(MediaPlayerModel);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport FactoryMaker from '../../core/FactoryMaker';\n\nfunction RulesContext(config) {\n\n config = config || {};\n let instance;\n const abrController = config.abrController;\n const switchHistory = config.switchHistory;\n const droppedFramesHistory = config.droppedFramesHistory;\n const currentRequest = config.currentRequest;\n const bufferOccupancyABR = config.useBufferOccupancyABR;\n const l2AABR = config.useL2AABR;\n const loLP = config.useLoLPABR;\n const scheduleController = config.streamProcessor ? config.streamProcessor.getScheduleController() : null;\n const representationInfo = config.streamProcessor ? config.streamProcessor.getRepresentationInfo() : null;\n const videoModel = config.videoModel ? config.videoModel : null;\n\n function getMediaType() {\n const mediaInfo = getMediaInfo();\n return mediaInfo ? mediaInfo.type : null;\n }\n\n function getStreamInfo() {\n const mediaInfo = getMediaInfo();\n return mediaInfo ? mediaInfo.streamInfo : null;\n }\n\n function getMediaInfo() {\n return representationInfo ? representationInfo.mediaInfo : null;\n }\n\n function getRepresentationInfo() {\n return representationInfo;\n }\n\n function getScheduleController() {\n return scheduleController;\n }\n\n function getAbrController() {\n return abrController;\n }\n\n function getSwitchHistory() {\n return switchHistory;\n }\n\n function getVideoModel() {\n return videoModel;\n }\n\n function getDroppedFramesHistory() {\n return droppedFramesHistory;\n }\n\n function getCurrentRequest() {\n return currentRequest;\n }\n\n function useBufferOccupancyABR() {\n return bufferOccupancyABR;\n }\n function useL2AABR() {\n return l2AABR;\n }\n\n function useLoLPABR() {\n return loLP;\n }\n\n instance = {\n getMediaType,\n getMediaInfo,\n getDroppedFramesHistory,\n getCurrentRequest,\n getSwitchHistory,\n getStreamInfo,\n getScheduleController,\n getAbrController,\n getRepresentationInfo,\n useBufferOccupancyABR,\n useL2AABR,\n useLoLPABR,\n getVideoModel\n };\n\n return instance;\n}\n\nRulesContext.__dashjs_factory_name = 'RulesContext';\nexport default FactoryMaker.getClassFactory(RulesContext);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport FactoryMaker from '../../core/FactoryMaker';\nimport SwitchRequest from './SwitchRequest';\n\nconst SWITCH_REQUEST_HISTORY_DEPTH = 8; // must be > SwitchHistoryRule SAMPLE_SIZE to enable rule\n\nfunction SwitchRequestHistory() {\n let switchRequests = []; // running total\n let srHistory = []; // history of each switch\n\n function push(switchRequest) {\n if (switchRequest.newValue === SwitchRequest.NO_CHANGE) {\n switchRequest.newValue = switchRequest.oldValue;\n }\n if (!switchRequests[switchRequest.oldValue]) {\n switchRequests[switchRequest.oldValue] = {noDrops: 0, drops: 0, dropSize: 0};\n }\n\n // Set switch details\n let indexDiff = switchRequest.newValue - switchRequest.oldValue;\n let drop = (indexDiff < 0) ? 1 : 0;\n let dropSize = drop ? -indexDiff : 0;\n let noDrop = drop ? 0 : 1;\n\n // Update running totals\n switchRequests[switchRequest.oldValue].drops += drop;\n switchRequests[switchRequest.oldValue].dropSize += dropSize;\n switchRequests[switchRequest.oldValue].noDrops += noDrop;\n\n // Save to history\n srHistory.push({idx: switchRequest.oldValue, noDrop: noDrop, drop: drop, dropSize: dropSize});\n\n // Shift earliest switch off srHistory and readjust to keep depth of running totals constant\n if ( srHistory.length > SWITCH_REQUEST_HISTORY_DEPTH ) {\n let srHistoryFirst = srHistory.shift();\n switchRequests[srHistoryFirst.idx].drops -= srHistoryFirst.drop;\n switchRequests[srHistoryFirst.idx].dropSize -= srHistoryFirst.dropSize;\n switchRequests[srHistoryFirst.idx].noDrops -= srHistoryFirst.noDrop;\n }\n }\n\n function getSwitchRequests() {\n return switchRequests;\n }\n\n function reset() {\n switchRequests = [];\n srHistory = [];\n }\n\n return {\n push: push,\n getSwitchRequests: getSwitchRequests,\n reset: reset\n };\n}\n\nSwitchRequestHistory.__dashjs_factory_name = 'SwitchRequestHistory';\nconst factory = FactoryMaker.getClassFactory(SwitchRequestHistory);\nexport default factory;\n","import FactoryMaker from '../../core/FactoryMaker';\n\nfunction DroppedFramesHistory() {\n\n let values = {};\n let lastDroppedFrames = {};\n let lastTotalFrames = {};\n\n function push(streamId, index, playbackQuality) {\n\n if (!index) {\n return;\n }\n\n if (!values[streamId]) {\n values[streamId] = [];\n lastDroppedFrames[streamId] = 0;\n lastTotalFrames[streamId] = 0;\n }\n\n let droppedVideoFrames = playbackQuality && playbackQuality.droppedVideoFrames ? playbackQuality.droppedVideoFrames : 0;\n let totalVideoFrames = playbackQuality && playbackQuality.totalVideoFrames ? playbackQuality.totalVideoFrames : 0;\n\n let intervalDroppedFrames = droppedVideoFrames - lastDroppedFrames;\n lastDroppedFrames[streamId] = droppedVideoFrames;\n\n let intervalTotalFrames = totalVideoFrames - lastTotalFrames;\n lastTotalFrames[streamId] = totalVideoFrames;\n\n const current = values[streamId];\n if (!isNaN(index)) {\n if (!current[index]) {\n current[index] = { droppedVideoFrames: intervalDroppedFrames, totalVideoFrames: intervalTotalFrames };\n } else {\n current[index].droppedVideoFrames += intervalDroppedFrames;\n current[index].totalVideoFrames += intervalTotalFrames;\n }\n }\n }\n\n function getFrameHistory(streamId) {\n return values[streamId];\n }\n\n function clearForStream(streamId) {\n try {\n delete values[streamId];\n delete lastDroppedFrames[streamId];\n delete lastTotalFrames[streamId];\n } catch (e) {\n\n }\n }\n\n function reset() {\n values = {};\n lastDroppedFrames = {};\n lastTotalFrames = {};\n }\n\n return {\n push,\n getFrameHistory,\n clearForStream,\n reset\n };\n}\n\nDroppedFramesHistory.__dashjs_factory_name = 'DroppedFramesHistory';\nconst factory = FactoryMaker.getClassFactory(DroppedFramesHistory);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2017, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport Constants from '../constants/Constants';\nimport FactoryMaker from '../../core/FactoryMaker';\n\n// throughput generally stored in kbit/s\n// latency generally stored in ms\n\nfunction ThroughputHistory(config) {\n\n config = config || {};\n // sliding window constants\n const MAX_MEASUREMENTS_TO_KEEP = 20;\n const AVERAGE_THROUGHPUT_SAMPLE_AMOUNT_LIVE = 3;\n const AVERAGE_THROUGHPUT_SAMPLE_AMOUNT_VOD = 4;\n const AVERAGE_LATENCY_SAMPLE_AMOUNT = 4;\n const THROUGHPUT_DECREASE_SCALE = 1.3;\n const THROUGHPUT_INCREASE_SCALE = 1.3;\n\n // EWMA constants\n const EWMA_THROUGHPUT_SLOW_HALF_LIFE_SECONDS = 8;\n const EWMA_THROUGHPUT_FAST_HALF_LIFE_SECONDS = 3;\n const EWMA_LATENCY_SLOW_HALF_LIFE_COUNT = 2;\n const EWMA_LATENCY_FAST_HALF_LIFE_COUNT = 1;\n\n const settings = config.settings;\n\n let throughputDict,\n latencyDict,\n ewmaThroughputDict,\n ewmaLatencyDict,\n ewmaHalfLife;\n\n function setup() {\n ewmaHalfLife = {\n throughputHalfLife: {\n fast: EWMA_THROUGHPUT_FAST_HALF_LIFE_SECONDS,\n slow: EWMA_THROUGHPUT_SLOW_HALF_LIFE_SECONDS\n },\n latencyHalfLife: { fast: EWMA_LATENCY_FAST_HALF_LIFE_COUNT, slow: EWMA_LATENCY_SLOW_HALF_LIFE_COUNT }\n };\n\n reset();\n }\n\n function isCachedResponse(mediaType, latencyMs, downloadTimeMs) {\n if (mediaType === Constants.VIDEO) {\n return downloadTimeMs < settings.get().streaming.cacheLoadThresholds[Constants.VIDEO];\n } else if (mediaType === Constants.AUDIO) {\n return downloadTimeMs < settings.get().streaming.cacheLoadThresholds[Constants.AUDIO];\n }\n }\n\n function push(mediaType, httpRequest, useDeadTimeLatency) {\n if (!httpRequest.trace || !httpRequest.trace.length) {\n return;\n }\n\n const latencyTimeInMilliseconds = (httpRequest.tresponse.getTime() - httpRequest.trequest.getTime()) || 1;\n const downloadTimeInMilliseconds = (httpRequest._tfinish.getTime() - httpRequest.tresponse.getTime()) || 1; //Make sure never 0 we divide by this value. Avoid infinity!\n const downloadBytes = httpRequest.trace.reduce((a, b) => a + b.b[0], 0);\n\n let throughputMeasureTime = 0, throughput = 0;\n if (settings.get().streaming.lowLatencyEnabled) {\n const calculationMode = settings.get().streaming.abr.fetchThroughputCalculationMode;\n if (calculationMode === Constants.ABR_FETCH_THROUGHPUT_CALCULATION_MOOF_PARSING) {\n const sumOfThroughputValues = httpRequest.trace.reduce((a, b) => a + b.t, 0);\n throughput = Math.round(sumOfThroughputValues / httpRequest.trace.length);\n }\n if (throughput === 0) {\n throughputMeasureTime = httpRequest.trace.reduce((a, b) => a + b.d, 0);\n }\n } else {\n throughputMeasureTime = useDeadTimeLatency ? downloadTimeInMilliseconds : latencyTimeInMilliseconds + downloadTimeInMilliseconds;\n }\n\n if (throughputMeasureTime !== 0) {\n throughput = Math.round((8 * downloadBytes) / throughputMeasureTime); // bits/ms = kbits/s\n }\n\n checkSettingsForMediaType(mediaType);\n\n if (isCachedResponse(mediaType, latencyTimeInMilliseconds, downloadTimeInMilliseconds)) {\n if (throughputDict[mediaType].length > 0 && !throughputDict[mediaType].hasCachedEntries) {\n // already have some entries which are not cached entries\n // prevent cached fragment loads from skewing the average values\n return;\n } else { // have no entries || have cached entries\n // no uncached entries yet, rely on cached entries because ABR rules need something to go by\n throughputDict[mediaType].hasCachedEntries = true;\n }\n } else if (throughputDict[mediaType] && throughputDict[mediaType].hasCachedEntries) {\n // if we are here then we have some entries already, but they are cached, and now we have a new uncached entry\n clearSettingsForMediaType(mediaType);\n }\n\n throughputDict[mediaType].push(throughput);\n if (throughputDict[mediaType].length > MAX_MEASUREMENTS_TO_KEEP) {\n throughputDict[mediaType].shift();\n }\n\n latencyDict[mediaType].push(latencyTimeInMilliseconds);\n if (latencyDict[mediaType].length > MAX_MEASUREMENTS_TO_KEEP) {\n latencyDict[mediaType].shift();\n }\n\n updateEwmaEstimate(ewmaThroughputDict[mediaType], throughput, 0.001 * downloadTimeInMilliseconds, ewmaHalfLife.throughputHalfLife);\n updateEwmaEstimate(ewmaLatencyDict[mediaType], latencyTimeInMilliseconds, 1, ewmaHalfLife.latencyHalfLife);\n }\n\n function updateEwmaEstimate(ewmaObj, value, weight, halfLife) {\n // Note about startup:\n // Estimates start at 0, so early values are underestimated.\n // This effect is countered in getAverageEwma() by dividing the estimates by:\n // 1 - Math.pow(0.5, ewmaObj.totalWeight / halfLife)\n\n const fastAlpha = Math.pow(0.5, weight / halfLife.fast);\n ewmaObj.fastEstimate = (1 - fastAlpha) * value + fastAlpha * ewmaObj.fastEstimate;\n\n const slowAlpha = Math.pow(0.5, weight / halfLife.slow);\n ewmaObj.slowEstimate = (1 - slowAlpha) * value + slowAlpha * ewmaObj.slowEstimate;\n\n ewmaObj.totalWeight += weight;\n }\n\n function getSampleSize(isThroughput, mediaType, isDynamic) {\n let arr,\n sampleSize;\n\n if (isThroughput) {\n arr = throughputDict[mediaType];\n sampleSize = isDynamic ? AVERAGE_THROUGHPUT_SAMPLE_AMOUNT_LIVE : AVERAGE_THROUGHPUT_SAMPLE_AMOUNT_VOD;\n } else {\n arr = latencyDict[mediaType];\n sampleSize = AVERAGE_LATENCY_SAMPLE_AMOUNT;\n }\n\n if (!arr) {\n sampleSize = 0;\n } else if (sampleSize >= arr.length) {\n sampleSize = arr.length;\n } else if (isThroughput) {\n // if throughput samples vary a lot, average over a wider sample\n for (let i = 1; i < sampleSize; ++i) {\n const ratio = arr[arr.length - i] / arr[arr.length - i - 1];\n if (ratio >= THROUGHPUT_INCREASE_SCALE || ratio <= 1 / THROUGHPUT_DECREASE_SCALE) {\n sampleSize += 1;\n if (sampleSize === arr.length) { // cannot increase sampleSize beyond arr.length\n break;\n }\n }\n }\n }\n\n return sampleSize;\n }\n\n function getAverage(isThroughput, mediaType, isDynamic) {\n // only two moving average methods defined at the moment\n return settings.get().streaming.abr.movingAverageMethod !== Constants.MOVING_AVERAGE_SLIDING_WINDOW ?\n getAverageEwma(isThroughput, mediaType) : getAverageSlidingWindow(isThroughput, mediaType, isDynamic);\n }\n\n function getAverageSlidingWindow(isThroughput, mediaType, isDynamic) {\n const sampleSize = getSampleSize(isThroughput, mediaType, isDynamic);\n const dict = isThroughput ? throughputDict : latencyDict;\n let arr = dict[mediaType];\n\n if (sampleSize === 0 || !arr || arr.length === 0) {\n return NaN;\n }\n\n arr = arr.slice(-sampleSize); // still works if sampleSize too large\n // arr.length >= 1\n return arr.reduce((total, elem) => total + elem) / arr.length;\n }\n\n function getAverageEwma(isThroughput, mediaType) {\n const halfLife = isThroughput ? ewmaHalfLife.throughputHalfLife : ewmaHalfLife.latencyHalfLife;\n const ewmaObj = isThroughput ? ewmaThroughputDict[mediaType] : ewmaLatencyDict[mediaType];\n\n if (!ewmaObj || ewmaObj.totalWeight <= 0) {\n return NaN;\n }\n\n // to correct for startup, divide by zero factor = 1 - Math.pow(0.5, ewmaObj.totalWeight / halfLife)\n const fastEstimate = ewmaObj.fastEstimate / (1 - Math.pow(0.5, ewmaObj.totalWeight / halfLife.fast));\n const slowEstimate = ewmaObj.slowEstimate / (1 - Math.pow(0.5, ewmaObj.totalWeight / halfLife.slow));\n return isThroughput ? Math.min(fastEstimate, slowEstimate) : Math.max(fastEstimate, slowEstimate);\n }\n\n function getAverageThroughput(mediaType, isDynamic) {\n return getAverage(true, mediaType, isDynamic);\n }\n\n function getSafeAverageThroughput(mediaType, isDynamic) {\n let average = getAverageThroughput(mediaType, isDynamic);\n if (!isNaN(average)) {\n average *= settings.get().streaming.abr.bandwidthSafetyFactor;\n }\n return average;\n }\n\n function getAverageLatency(mediaType) {\n return getAverage(false, mediaType);\n }\n\n function checkSettingsForMediaType(mediaType) {\n throughputDict[mediaType] = throughputDict[mediaType] || [];\n latencyDict[mediaType] = latencyDict[mediaType] || [];\n ewmaThroughputDict[mediaType] = ewmaThroughputDict[mediaType] || {\n fastEstimate: 0,\n slowEstimate: 0,\n totalWeight: 0\n };\n ewmaLatencyDict[mediaType] = ewmaLatencyDict[mediaType] || { fastEstimate: 0, slowEstimate: 0, totalWeight: 0 };\n }\n\n function clearSettingsForMediaType(mediaType) {\n delete throughputDict[mediaType];\n delete latencyDict[mediaType];\n delete ewmaThroughputDict[mediaType];\n delete ewmaLatencyDict[mediaType];\n checkSettingsForMediaType(mediaType);\n }\n\n function reset() {\n throughputDict = {};\n latencyDict = {};\n ewmaThroughputDict = {};\n ewmaLatencyDict = {};\n }\n\n const instance = {\n push,\n getAverageThroughput,\n getSafeAverageThroughput,\n getAverageLatency,\n reset\n };\n\n setup();\n return instance;\n}\n\nThroughputHistory.__dashjs_factory_name = 'ThroughputHistory';\nexport default FactoryMaker.getClassFactory(ThroughputHistory);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport ABRRulesCollection from '../rules/abr/ABRRulesCollection';\nimport Constants from '../constants/Constants';\nimport MetricsConstants from '../constants/MetricsConstants';\nimport BitrateInfo from '../vo/BitrateInfo';\nimport FragmentModel from '../models/FragmentModel';\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport RulesContext from '../rules/RulesContext';\nimport SwitchRequest from '../rules/SwitchRequest';\nimport SwitchRequestHistory from '../rules/SwitchRequestHistory';\nimport DroppedFramesHistory from '../rules/DroppedFramesHistory';\nimport ThroughputHistory from '../rules/ThroughputHistory';\nimport Debug from '../../core/Debug';\nimport {HTTPRequest} from '../vo/metrics/HTTPRequest';\nimport {checkInteger} from '../utils/SupervisorTools';\nimport MediaPlayerEvents from '../MediaPlayerEvents';\n\nconst DEFAULT_VIDEO_BITRATE = 1000;\nconst DEFAULT_AUDIO_BITRATE = 100;\nconst QUALITY_DEFAULT = 0;\n\nfunction AbrController() {\n\n const context = this.context;\n const debug = Debug(context).getInstance();\n const eventBus = EventBus(context).getInstance();\n\n let instance,\n logger,\n abrRulesCollection,\n streamController,\n topQualities,\n qualityDict,\n streamProcessorDict,\n abandonmentStateDict,\n abandonmentTimeout,\n windowResizeEventCalled,\n elementWidth,\n elementHeight,\n adapter,\n videoModel,\n mediaPlayerModel,\n domStorage,\n playbackIndex,\n switchHistoryDict,\n droppedFramesHistory,\n throughputHistory,\n isUsingBufferOccupancyAbrDict,\n isUsingL2AAbrDict,\n isUsingLoLPAbrDict,\n dashMetrics,\n settings;\n\n function setup() {\n logger = debug.getLogger(instance);\n resetInitialSettings();\n }\n\n /**\n * Initialize everything that is not Stream specific. We only have one instance of the ABR Controller for all periods.\n */\n function initialize() {\n droppedFramesHistory = DroppedFramesHistory(context).create();\n throughputHistory = ThroughputHistory(context).create({\n settings: settings\n });\n\n abrRulesCollection = ABRRulesCollection(context).create({\n dashMetrics: dashMetrics,\n mediaPlayerModel: mediaPlayerModel,\n settings: settings\n });\n\n abrRulesCollection.initialize();\n\n eventBus.on(MediaPlayerEvents.QUALITY_CHANGE_RENDERED, _onQualityChangeRendered, instance);\n eventBus.on(MediaPlayerEvents.METRIC_ADDED, _onMetricAdded, instance);\n eventBus.on(Events.LOADING_PROGRESS, _onFragmentLoadProgress, instance);\n }\n\n /**\n * Whenever a StreamProcessor is created it is added to the list of streamProcessorDict\n * In addition, the corresponding objects for this object and its stream id are created\n * @param {object} type\n * @param {object} streamProcessor\n */\n function registerStreamType(type, streamProcessor) {\n const streamId = streamProcessor.getStreamInfo().id;\n\n if (!streamProcessorDict[streamId]) {\n streamProcessorDict[streamId] = {};\n }\n\n if (!switchHistoryDict[streamId]) {\n switchHistoryDict[streamId] = {};\n }\n\n if (!abandonmentStateDict[streamId]) {\n abandonmentStateDict[streamId] = {};\n }\n\n switchHistoryDict[streamId][type] = SwitchRequestHistory(context).create();\n streamProcessorDict[streamId][type] = streamProcessor;\n\n abandonmentStateDict[streamId][type] = {};\n abandonmentStateDict[streamId][type].state = MetricsConstants.ALLOW_LOAD;\n\n _initializeAbrStrategy(type);\n\n if (type === Constants.VIDEO) {\n setElementSize();\n }\n }\n\n function _initializeAbrStrategy(type) {\n const strategy = settings.get().streaming.abr.ABRStrategy;\n\n if (strategy === Constants.ABR_STRATEGY_L2A) {\n isUsingBufferOccupancyAbrDict[type] = false;\n isUsingLoLPAbrDict[type] = false;\n isUsingL2AAbrDict[type] = true;\n } else if (strategy === Constants.ABR_STRATEGY_LoLP) {\n isUsingBufferOccupancyAbrDict[type] = false;\n isUsingLoLPAbrDict[type] = true;\n isUsingL2AAbrDict[type] = false;\n } else if (strategy === Constants.ABR_STRATEGY_BOLA) {\n isUsingBufferOccupancyAbrDict[type] = true;\n isUsingLoLPAbrDict[type] = false;\n isUsingL2AAbrDict[type] = false;\n } else if (strategy === Constants.ABR_STRATEGY_THROUGHPUT) {\n isUsingBufferOccupancyAbrDict[type] = false;\n isUsingLoLPAbrDict[type] = false;\n isUsingL2AAbrDict[type] = false;\n } else if (strategy === Constants.ABR_STRATEGY_DYNAMIC) {\n isUsingBufferOccupancyAbrDict[type] = isUsingBufferOccupancyAbrDict && isUsingBufferOccupancyAbrDict[type] ? isUsingBufferOccupancyAbrDict[type] : false;\n isUsingLoLPAbrDict[type] = false;\n isUsingL2AAbrDict[type] = false;\n }\n }\n\n function unRegisterStreamType(streamId, type) {\n try {\n if (streamProcessorDict[streamId] && streamProcessorDict[streamId][type]) {\n delete streamProcessorDict[streamId][type];\n }\n\n if (switchHistoryDict[streamId] && switchHistoryDict[streamId][type]) {\n delete switchHistoryDict[streamId][type];\n }\n\n if (abandonmentStateDict[streamId] && abandonmentStateDict[streamId][type]) {\n delete abandonmentStateDict[streamId][type];\n }\n\n } catch (e) {\n\n }\n }\n\n function resetInitialSettings() {\n topQualities = {};\n qualityDict = {};\n abandonmentStateDict = {};\n streamProcessorDict = {};\n switchHistoryDict = {};\n isUsingBufferOccupancyAbrDict = {};\n isUsingL2AAbrDict = {};\n isUsingLoLPAbrDict = {};\n\n if (windowResizeEventCalled === undefined) {\n windowResizeEventCalled = false;\n }\n if (droppedFramesHistory) {\n droppedFramesHistory.reset();\n }\n\n playbackIndex = undefined;\n droppedFramesHistory = undefined;\n throughputHistory = undefined;\n clearTimeout(abandonmentTimeout);\n abandonmentTimeout = null;\n }\n\n function reset() {\n\n resetInitialSettings();\n\n eventBus.off(Events.LOADING_PROGRESS, _onFragmentLoadProgress, instance);\n eventBus.off(MediaPlayerEvents.QUALITY_CHANGE_RENDERED, _onQualityChangeRendered, instance);\n eventBus.off(MediaPlayerEvents.METRIC_ADDED, _onMetricAdded, instance);\n\n if (abrRulesCollection) {\n abrRulesCollection.reset();\n }\n }\n\n function setConfig(config) {\n if (!config) return;\n\n if (config.streamController) {\n streamController = config.streamController;\n }\n if (config.domStorage) {\n domStorage = config.domStorage;\n }\n if (config.mediaPlayerModel) {\n mediaPlayerModel = config.mediaPlayerModel;\n }\n if (config.dashMetrics) {\n dashMetrics = config.dashMetrics;\n }\n if (config.adapter) {\n adapter = config.adapter;\n }\n if (config.videoModel) {\n videoModel = config.videoModel;\n }\n if (config.settings) {\n settings = config.settings;\n }\n }\n\n function checkConfig() {\n if (!domStorage || !domStorage.hasOwnProperty('getSavedBitrateSettings')) {\n throw new Error(Constants.MISSING_CONFIG_ERROR);\n }\n }\n\n /**\n * While fragment loading is in progress we check if we might need to abort the request\n * @param {object} e\n * @private\n */\n function _onFragmentLoadProgress(e) {\n const type = e.request.mediaType;\n const streamId = e.streamId;\n\n if (!type || !streamId || !streamProcessorDict[streamId] || !settings.get().streaming.abr.autoSwitchBitrate[type]) {\n return;\n }\n\n const streamProcessor = streamProcessorDict[streamId][type];\n if (!streamProcessor) {\n return;\n }\n\n const rulesContext = RulesContext(context).create({\n abrController: instance,\n streamProcessor: streamProcessor,\n currentRequest: e.request,\n useBufferOccupancyABR: isUsingBufferOccupancyAbrDict[type],\n useL2AABR: isUsingL2AAbrDict[type],\n useLoLPABR: isUsingLoLPAbrDict[type],\n videoModel\n });\n const switchRequest = abrRulesCollection.shouldAbandonFragment(rulesContext, streamId);\n\n if (switchRequest.quality > SwitchRequest.NO_CHANGE) {\n const fragmentModel = streamProcessor.getFragmentModel();\n const request = fragmentModel.getRequests({\n state: FragmentModel.FRAGMENT_MODEL_LOADING,\n index: e.request.index\n })[0];\n if (request) {\n fragmentModel.abortRequests();\n abandonmentStateDict[streamId][type].state = MetricsConstants.ABANDON_LOAD;\n switchHistoryDict[streamId][type].reset();\n switchHistoryDict[streamId][type].push({\n oldValue: getQualityFor(type, streamId),\n newValue: switchRequest.quality,\n confidence: 1,\n reason: switchRequest.reason\n });\n setPlaybackQuality(type, streamController.getActiveStreamInfo(), switchRequest.quality, switchRequest.reason);\n\n clearTimeout(abandonmentTimeout);\n abandonmentTimeout = setTimeout(\n () => {\n abandonmentStateDict[streamId][type].state = MetricsConstants.ALLOW_LOAD;\n abandonmentTimeout = null;\n },\n settings.get().streaming.abandonLoadTimeout\n );\n }\n }\n }\n\n /**\n * Update dropped frames history when the quality was changed\n * @param {object} e\n * @private\n */\n function _onQualityChangeRendered(e) {\n if (e.mediaType === Constants.VIDEO) {\n if (playbackIndex !== undefined) {\n droppedFramesHistory.push(e.streamId, playbackIndex, videoModel.getPlaybackQuality());\n }\n playbackIndex = e.newQuality;\n }\n }\n\n /**\n * When the buffer level is updated we check if we need to change the ABR strategy\n * @param e\n * @private\n */\n function _onMetricAdded(e) {\n if (e.metric === MetricsConstants.HTTP_REQUEST && e.value && e.value.type === HTTPRequest.MEDIA_SEGMENT_TYPE && (e.mediaType === Constants.AUDIO || e.mediaType === Constants.VIDEO)) {\n throughputHistory.push(e.mediaType, e.value, settings.get().streaming.abr.useDeadTimeLatency);\n }\n\n if (e.metric === MetricsConstants.BUFFER_LEVEL && (e.mediaType === Constants.AUDIO || e.mediaType === Constants.VIDEO)) {\n _updateAbrStrategy(e.mediaType, 0.001 * e.value.level);\n }\n }\n\n /**\n * Returns the highest possible index taking limitations like maxBitrate, representationRatio and portal size into account.\n * @param {string} type\n * @param {string} streamId\n * @return {number}\n */\n function getMaxAllowedIndexFor(type, streamId) {\n try {\n let idx;\n topQualities[streamId] = topQualities[streamId] || {};\n\n if (!topQualities[streamId].hasOwnProperty(type)) {\n topQualities[streamId][type] = 0;\n }\n\n idx = _checkMaxBitrate(type, streamId);\n idx = _checkMaxRepresentationRatio(idx, type, streamId);\n idx = _checkPortalSize(idx, type, streamId);\n return idx;\n } catch (e) {\n return undefined\n }\n }\n\n /**\n * Returns the minimum allowed index. We consider thresholds defined in the settings, i.e. minBitrate for the corresponding media type.\n * @param {string} type\n * @param {string} streamId\n * @return {undefined|number}\n */\n function getMinAllowedIndexFor(type, streamId) {\n try {\n return _getMinIndexBasedOnBitrateFor(type, streamId);\n } catch (e) {\n return undefined\n }\n }\n\n /**\n * Returns the maximum allowed index.\n * @param {string} type\n * @param {string} streamId\n * @return {undefined|number}\n */\n function _getMaxIndexBasedOnBitrateFor(type, streamId) {\n try {\n const maxBitrate = settings.get().streaming.abr.maxBitrate[type];\n if (maxBitrate > -1) {\n return getQualityForBitrate(streamProcessorDict[streamId][type].getMediaInfo(), maxBitrate, streamId);\n } else {\n return undefined;\n }\n } catch (e) {\n return undefined\n }\n }\n\n /**\n * Returns the minimum allowed index.\n * @param {string} type\n * @param {string} streamId\n * @return {undefined|number}\n */\n function _getMinIndexBasedOnBitrateFor(type, streamId) {\n try {\n const minBitrate = settings.get().streaming.abr.minBitrate[type];\n\n if (minBitrate > -1) {\n const mediaInfo = streamProcessorDict[streamId][type].getMediaInfo();\n const bitrateList = getBitrateList(mediaInfo);\n // This returns the quality index <= for the given bitrate\n let minIdx = getQualityForBitrate(mediaInfo, minBitrate, streamId);\n if (bitrateList[minIdx] && minIdx < bitrateList.length - 1 && bitrateList[minIdx].bitrate < minBitrate * 1000) {\n minIdx++; // Go to the next bitrate\n }\n return minIdx;\n } else {\n return undefined;\n }\n } catch (e) {\n return undefined;\n }\n }\n\n /**\n * Returns the maximum possible index\n * @param type\n * @param streamId\n * @return {number|*}\n */\n function _checkMaxBitrate(type, streamId) {\n let idx = topQualities[streamId][type];\n let newIdx = idx;\n\n if (!streamProcessorDict[streamId] || !streamProcessorDict[streamId][type]) {\n return newIdx;\n }\n\n const minIdx = getMinAllowedIndexFor(type, streamId);\n if (minIdx !== undefined) {\n newIdx = Math.max(idx, minIdx);\n }\n\n const maxIdx = _getMaxIndexBasedOnBitrateFor(type, streamId);\n if (maxIdx !== undefined) {\n newIdx = Math.min(newIdx, maxIdx);\n }\n\n return newIdx;\n }\n\n /**\n * Returns the maximum index according to maximum representation ratio\n * @param idx\n * @param type\n * @param streamId\n * @return {number|*}\n * @private\n */\n function _checkMaxRepresentationRatio(idx, type, streamId) {\n let maxIdx = topQualities[streamId][type]\n const maxRepresentationRatio = settings.get().streaming.abr.maxRepresentationRatio[type];\n\n if (isNaN(maxRepresentationRatio) || maxRepresentationRatio >= 1 || maxRepresentationRatio < 0) {\n return idx;\n }\n return Math.min(idx, Math.round(maxIdx * maxRepresentationRatio));\n }\n\n /**\n * Returns the maximum index according to the portal size\n * @param idx\n * @param type\n * @param streamId\n * @return {number|*}\n * @private\n */\n function _checkPortalSize(idx, type, streamId) {\n if (type !== Constants.VIDEO || !settings.get().streaming.abr.limitBitrateByPortal || !streamProcessorDict[streamId] || !streamProcessorDict[streamId][type]) {\n return idx;\n }\n\n if (!windowResizeEventCalled) {\n setElementSize();\n }\n const streamInfo = streamProcessorDict[streamId][type].getStreamInfo();\n const representation = adapter.getAdaptationForType(streamInfo.index, type, streamInfo).Representation;\n let newIdx = idx;\n\n if (elementWidth > 0 && elementHeight > 0) {\n while (\n newIdx > 0 &&\n representation[newIdx] &&\n elementWidth < representation[newIdx].width &&\n elementWidth - representation[newIdx - 1].width < representation[newIdx].width - elementWidth) {\n newIdx = newIdx - 1;\n }\n\n // Make sure that in case of multiple representation elements have same\n // resolution, every such element is included\n while (newIdx < representation.length - 1 && representation[newIdx].width === representation[newIdx + 1].width) {\n newIdx = newIdx + 1;\n }\n }\n\n return newIdx;\n }\n\n /**\n * Gets top BitrateInfo for the player\n * @param {string} type - 'video' or 'audio' are the type options.\n * @param {string} streamId - Id of the stream\n * @returns {BitrateInfo | null}\n */\n function getTopBitrateInfoFor(type, streamId = null) {\n if (!streamId) {\n streamId = streamController.getActiveStreamInfo().id;\n }\n if (type && streamProcessorDict && streamProcessorDict[streamId] && streamProcessorDict[streamId][type]) {\n const idx = getMaxAllowedIndexFor(type, streamId);\n const bitrates = getBitrateList(streamProcessorDict[streamId][type].getMediaInfo());\n return bitrates[idx] ? bitrates[idx] : null;\n }\n return null;\n }\n\n /**\n * Returns the initial bitrate for a specific media type and stream id\n * @param {string} type\n * @param {string} streamId\n * @returns {number} A value of the initial bitrate, kbps\n * @memberof AbrController#\n */\n function getInitialBitrateFor(type, streamId) {\n checkConfig();\n\n if (type === Constants.TEXT) {\n return NaN;\n }\n\n const savedBitrate = domStorage.getSavedBitrateSettings(type);\n let configBitrate = settings.get().streaming.abr.initialBitrate[type];\n let configRatio = settings.get().streaming.abr.initialRepresentationRatio[type];\n\n if (configBitrate === -1) {\n if (configRatio > -1) {\n const streamInfo = streamProcessorDict[streamId][type].getStreamInfo();\n const representation = adapter.getAdaptationForType(streamInfo.index, type, streamInfo).Representation;\n if (Array.isArray(representation)) {\n const repIdx = Math.max(Math.round(representation.length * configRatio) - 1, 0);\n configBitrate = representation[repIdx].bandwidth / 1000;\n } else {\n configBitrate = 0;\n }\n } else if (!isNaN(savedBitrate)) {\n configBitrate = savedBitrate;\n } else {\n configBitrate = (type === Constants.VIDEO) ? DEFAULT_VIDEO_BITRATE : DEFAULT_AUDIO_BITRATE;\n }\n }\n\n return configBitrate;\n }\n\n /**\n * This function is called by the scheduleControllers to check if the quality should be changed.\n * Consider this the main entry point for the ABR decision logic\n * @param {string} type\n * @param {string} streamId\n */\n function checkPlaybackQuality(type, streamId) {\n try {\n if (!type || !streamProcessorDict || !streamProcessorDict[streamId] || !streamProcessorDict[streamId][type]) {\n return false;\n }\n\n if (droppedFramesHistory) {\n const playbackQuality = videoModel.getPlaybackQuality();\n if (playbackQuality) {\n droppedFramesHistory.push(streamId, playbackIndex, playbackQuality);\n }\n }\n\n // ABR is turned off, do nothing\n if (!settings.get().streaming.abr.autoSwitchBitrate[type]) {\n return false;\n }\n\n const oldQuality = getQualityFor(type, streamId);\n const rulesContext = RulesContext(context).create({\n abrController: instance,\n switchHistory: switchHistoryDict[streamId][type],\n droppedFramesHistory: droppedFramesHistory,\n streamProcessor: streamProcessorDict[streamId][type],\n currentValue: oldQuality,\n useBufferOccupancyABR: isUsingBufferOccupancyAbrDict[type],\n useL2AABR: isUsingL2AAbrDict[type],\n useLoLPABR: isUsingLoLPAbrDict[type],\n videoModel\n });\n const minIdx = getMinAllowedIndexFor(type, streamId);\n const maxIdx = getMaxAllowedIndexFor(type, streamId);\n const switchRequest = abrRulesCollection.getMaxQuality(rulesContext);\n let newQuality = switchRequest.quality;\n\n if (minIdx !== undefined && ((newQuality > SwitchRequest.NO_CHANGE) ? newQuality : oldQuality) < minIdx) {\n newQuality = minIdx;\n }\n if (newQuality > maxIdx) {\n newQuality = maxIdx;\n }\n\n switchHistoryDict[streamId][type].push({ oldValue: oldQuality, newValue: newQuality });\n\n if (newQuality > SwitchRequest.NO_CHANGE && newQuality !== oldQuality && (abandonmentStateDict[streamId][type].state === MetricsConstants.ALLOW_LOAD || newQuality > oldQuality)) {\n _changeQuality(type, oldQuality, newQuality, maxIdx, switchRequest.reason, streamId);\n return true;\n }\n\n return false;\n } catch (e) {\n return false;\n }\n\n }\n\n /**\n * Returns the current quality for a specific media type and a specific streamId\n * @param {string} type\n * @param {string} streamId\n * @return {number|*}\n */\n function getQualityFor(type, streamId = null) {\n try {\n if (!streamId) {\n streamId = streamController.getActiveStreamInfo().id;\n }\n if (type && streamProcessorDict[streamId] && streamProcessorDict[streamId][type]) {\n let quality;\n\n if (streamId) {\n qualityDict[streamId] = qualityDict[streamId] || {};\n\n if (!qualityDict[streamId].hasOwnProperty(type)) {\n qualityDict[streamId][type] = QUALITY_DEFAULT;\n }\n\n quality = qualityDict[streamId][type];\n return quality;\n }\n }\n return QUALITY_DEFAULT;\n } catch (e) {\n return QUALITY_DEFAULT;\n }\n }\n\n /**\n * Sets the new playback quality. Starts from index 0.\n * If the index of the new quality is the same as the old one changeQuality will not be called.\n * @param {string} type\n * @param {object} streamInfo\n * @param {number} newQuality\n * @param {string} reason\n */\n function setPlaybackQuality(type, streamInfo, newQuality, reason = null) {\n if (!streamInfo || !streamInfo.id || !type) {\n return;\n }\n const streamId = streamInfo.id;\n const oldQuality = getQualityFor(type, streamId);\n\n checkInteger(newQuality);\n\n const topQualityIdx = getMaxAllowedIndexFor(type, streamId);\n\n if (newQuality !== oldQuality && newQuality >= 0 && newQuality <= topQualityIdx) {\n _changeQuality(type, oldQuality, newQuality, topQualityIdx, reason, streamId);\n }\n }\n\n /**\n *\n * @param {string} streamId\n * @param {type} type\n * @return {*|null}\n */\n function getAbandonmentStateFor(streamId, type) {\n return abandonmentStateDict[streamId] && abandonmentStateDict[streamId][type] ? abandonmentStateDict[streamId][type].state : null;\n }\n\n\n /**\n * Changes the internal qualityDict values according to the new quality\n * @param {string} type\n * @param {number} oldQuality\n * @param {number} newQuality\n * @param {number} maxIdx\n * @param {string} reason\n * @param {object} streamId\n * @private\n */\n function _changeQuality(type, oldQuality, newQuality, maxIdx, reason, streamId) {\n if (type && streamProcessorDict[streamId] && streamProcessorDict[streamId][type]) {\n const streamInfo = streamProcessorDict[streamId][type].getStreamInfo();\n const isDynamic = streamInfo && streamInfo.manifestInfo && streamInfo.manifestInfo.isDynamic;\n const bufferLevel = dashMetrics.getCurrentBufferLevel(type);\n logger.info('Stream ID: ' + streamId + ' [' + type + '] switch from ' + oldQuality + ' to ' + newQuality + '/' + maxIdx + ' (buffer: ' + bufferLevel + ') ' + (reason ? JSON.stringify(reason) : '.'));\n\n qualityDict[streamId] = qualityDict[streamId] || {};\n qualityDict[streamId][type] = newQuality;\n const bitrateInfo = _getBitrateInfoForQuality(streamId, type, newQuality);\n eventBus.trigger(Events.QUALITY_CHANGE_REQUESTED,\n {\n oldQuality,\n newQuality,\n reason,\n streamInfo,\n bitrateInfo,\n maxIdx,\n mediaType: type\n },\n { streamId: streamInfo.id, mediaType: type }\n );\n const bitrate = throughputHistory.getAverageThroughput(type, isDynamic);\n if (!isNaN(bitrate)) {\n domStorage.setSavedBitrateSettings(type, bitrate);\n }\n }\n }\n\n function _getBitrateInfoForQuality(streamId, type, idx) {\n if (type && streamProcessorDict && streamProcessorDict[streamId] && streamProcessorDict[streamId][type]) {\n const bitrates = getBitrateList(streamProcessorDict[streamId][type].getMediaInfo());\n return bitrates[idx] ? bitrates[idx] : null;\n }\n return null;\n }\n\n /**\n * @param {MediaInfo} mediaInfo\n * @param {number} bitrate A bitrate value, kbps\n * @param {String} streamId Period ID\n * @param {number|null} latency Expected latency of connection, ms\n * @returns {number} A quality index <= for the given bitrate\n * @memberof AbrController#\n */\n function getQualityForBitrate(mediaInfo, bitrate, streamId, latency = null) {\n const voRepresentation = mediaInfo && mediaInfo.type ? streamProcessorDict[streamId][mediaInfo.type].getRepresentationInfo() : null;\n\n if (settings.get().streaming.abr.useDeadTimeLatency && latency && voRepresentation && voRepresentation.fragmentDuration) {\n latency = latency / 1000;\n const fragmentDuration = voRepresentation.fragmentDuration;\n if (latency > fragmentDuration) {\n return 0;\n } else {\n const deadTimeRatio = latency / fragmentDuration;\n bitrate = bitrate * (1 - deadTimeRatio);\n }\n }\n\n const bitrateList = getBitrateList(mediaInfo);\n\n for (let i = bitrateList.length - 1; i >= 0; i--) {\n const bitrateInfo = bitrateList[i];\n if (bitrate * 1000 >= bitrateInfo.bitrate) {\n return i;\n }\n }\n return QUALITY_DEFAULT;\n }\n\n /**\n * @param {MediaInfo} mediaInfo\n * @returns {Array|null} A list of {@link BitrateInfo} objects\n * @memberof AbrController#\n */\n function getBitrateList(mediaInfo) {\n const infoList = [];\n if (!mediaInfo || !mediaInfo.bitrateList) return infoList;\n\n const bitrateList = mediaInfo.bitrateList;\n const type = mediaInfo.type;\n\n let bitrateInfo;\n\n for (let i = 0, ln = bitrateList.length; i < ln; i++) {\n bitrateInfo = new BitrateInfo();\n bitrateInfo.mediaType = type;\n bitrateInfo.qualityIndex = i;\n bitrateInfo.bitrate = bitrateList[i].bandwidth;\n bitrateInfo.width = bitrateList[i].width;\n bitrateInfo.height = bitrateList[i].height;\n bitrateInfo.scanType = bitrateList[i].scanType;\n infoList.push(bitrateInfo);\n }\n\n return infoList;\n }\n\n function _updateAbrStrategy(mediaType, bufferLevel) {\n // else ABR_STRATEGY_DYNAMIC\n const strategy = settings.get().streaming.abr.ABRStrategy;\n\n if (strategy === Constants.ABR_STRATEGY_DYNAMIC) {\n _updateDynamicAbrStrategy(mediaType, bufferLevel);\n }\n }\n\n function _updateDynamicAbrStrategy(mediaType, bufferLevel) {\n const stableBufferTime = mediaPlayerModel.getStableBufferTime();\n const switchOnThreshold = stableBufferTime;\n const switchOffThreshold = 0.5 * stableBufferTime;\n\n const useBufferABR = isUsingBufferOccupancyAbrDict[mediaType];\n const newUseBufferABR = bufferLevel > (useBufferABR ? switchOffThreshold : switchOnThreshold); // use hysteresis to avoid oscillating rules\n isUsingBufferOccupancyAbrDict[mediaType] = newUseBufferABR;\n\n if (newUseBufferABR !== useBufferABR) {\n if (newUseBufferABR) {\n logger.info('[' + mediaType + '] switching from throughput to buffer occupancy ABR rule (buffer: ' + bufferLevel.toFixed(3) + ').');\n } else {\n logger.info('[' + mediaType + '] switching from buffer occupancy to throughput ABR rule (buffer: ' + bufferLevel.toFixed(3) + ').');\n }\n }\n }\n\n function getThroughputHistory() {\n return throughputHistory;\n }\n\n function updateTopQualityIndex(mediaInfo) {\n const type = mediaInfo.type;\n const streamId = mediaInfo.streamInfo.id;\n const max = mediaInfo.representationCount - 1;\n\n topQualities[streamId] = topQualities[streamId] || {};\n topQualities[streamId][type] = max;\n\n return max;\n }\n\n function isPlayingAtTopQuality(streamInfo) {\n const streamId = streamInfo ? streamInfo.id : null;\n const audioQuality = getQualityFor(Constants.AUDIO, streamId);\n const videoQuality = getQualityFor(Constants.VIDEO, streamId);\n\n const isAtTop = (audioQuality === getMaxAllowedIndexFor(Constants.AUDIO, streamId)) &&\n (videoQuality === getMaxAllowedIndexFor(Constants.VIDEO, streamId));\n\n return isAtTop;\n }\n\n function setWindowResizeEventCalled(value) {\n windowResizeEventCalled = value;\n }\n\n function setElementSize() {\n if (videoModel) {\n const hasPixelRatio = settings.get().streaming.abr.usePixelRatioInLimitBitrateByPortal && window.hasOwnProperty('devicePixelRatio');\n const pixelRatio = hasPixelRatio ? window.devicePixelRatio : 1;\n elementWidth = videoModel.getClientWidth() * pixelRatio;\n elementHeight = videoModel.getClientHeight() * pixelRatio;\n }\n }\n\n function clearDataForStream(streamId) {\n if (droppedFramesHistory) {\n droppedFramesHistory.clearForStream(streamId);\n }\n if (streamProcessorDict[streamId]) {\n delete streamProcessorDict[streamId];\n }\n if (switchHistoryDict[streamId]) {\n delete switchHistoryDict[streamId];\n }\n\n if (abandonmentStateDict[streamId]) {\n delete abandonmentStateDict[streamId];\n }\n }\n\n instance = {\n initialize,\n isPlayingAtTopQuality,\n updateTopQualityIndex,\n clearDataForStream,\n getThroughputHistory,\n getBitrateList,\n getQualityForBitrate,\n getTopBitrateInfoFor,\n getMinAllowedIndexFor,\n getMaxAllowedIndexFor,\n getInitialBitrateFor,\n getQualityFor,\n getAbandonmentStateFor,\n setPlaybackQuality,\n checkPlaybackQuality,\n setElementSize,\n setWindowResizeEventCalled,\n registerStreamType,\n unRegisterStreamType,\n setConfig,\n reset\n };\n\n setup();\n\n return instance;\n}\n\nAbrController.__dashjs_factory_name = 'AbrController';\nconst factory = FactoryMaker.getSingletonFactory(AbrController);\nfactory.QUALITY_DEFAULT = QUALITY_DEFAULT;\nFactoryMaker.updateSingletonFactory(AbrController.__dashjs_factory_name, factory);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport FactoryMaker from '../../core/FactoryMaker';\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\nimport Debug from '../../core/Debug';\nimport Constants from '../constants/Constants';\n\n\nconst READY_STATES_TO_EVENT_NAMES = new Map([\n [Constants.VIDEO_ELEMENT_READY_STATES.HAVE_METADATA, 'loadedmetadata'],\n [Constants.VIDEO_ELEMENT_READY_STATES.HAVE_CURRENT_DATA, 'loadeddata'],\n [Constants.VIDEO_ELEMENT_READY_STATES.HAVE_FUTURE_DATA, 'canplay'],\n [Constants.VIDEO_ELEMENT_READY_STATES.HAVE_ENOUGH_DATA, 'canplaythrough']\n]);\n\nfunction VideoModel() {\n\n let instance,\n logger,\n element,\n TTMLRenderingDiv,\n previousPlaybackRate;\n\n const VIDEO_MODEL_WRONG_ELEMENT_TYPE = 'element is not video or audio DOM type!';\n\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n const stalledStreams = [];\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n }\n\n function initialize() {\n eventBus.on(Events.PLAYBACK_PLAYING, onPlaying, this);\n }\n\n function reset() {\n eventBus.off(Events.PLAYBACK_PLAYING, onPlaying, this);\n }\n\n function onPlaybackCanPlay() {\n if (element) {\n element.playbackRate = previousPlaybackRate || 1;\n element.removeEventListener('canplay', onPlaybackCanPlay);\n }\n }\n\n function setPlaybackRate(value, ignoreReadyState = false) {\n if (!element) return;\n if (!ignoreReadyState && element.readyState <= 2 && value > 0) {\n // If media element hasn't loaded enough data to play yet, wait until it has\n element.addEventListener('canplay', onPlaybackCanPlay);\n } else {\n element.playbackRate = value;\n }\n }\n\n //TODO Move the DVR window calculations from MediaPlayer to Here.\n function setCurrentTime(currentTime, stickToBuffered) {\n waitForReadyState(Constants.VIDEO_ELEMENT_READY_STATES.HAVE_METADATA, () => {\n if (element) {\n //_currentTime = currentTime;\n\n // We don't set the same currentTime because it can cause firing unexpected Pause event in IE11\n // providing playbackRate property equals to zero.\n if (element.currentTime === currentTime) {\n return;\n }\n\n // TODO Despite the fact that MediaSource 'open' event has been fired IE11 cannot set videoElement.currentTime\n // immediately (it throws InvalidStateError). It seems that this is related to videoElement.readyState property\n // Initially it is 0, but soon after 'open' event it goes to 1 and setting currentTime is allowed. Chrome allows to\n // set currentTime even if readyState = 0.\n // setTimeout is used to workaround InvalidStateError in IE11\n try {\n currentTime = stickToBuffered ? stickTimeToBuffered(currentTime) : currentTime;\n element.currentTime = currentTime;\n } catch (e) {\n if (element.readyState === 0 && e.code === e.INVALID_STATE_ERR) {\n setTimeout(function () {\n element.currentTime = currentTime;\n }, 400);\n }\n }\n }\n });\n }\n\n function stickTimeToBuffered(time) {\n const buffered = getBufferRange();\n let closestTime = time;\n let closestDistance = 9999999999;\n if (buffered) {\n for (let i = 0; i < buffered.length; i++) {\n const start = buffered.start(i);\n const end = buffered.end(i);\n const distanceToStart = Math.abs(start - time);\n const distanceToEnd = Math.abs(end - time);\n\n if (time >= start && time <= end) {\n return time;\n }\n\n if (distanceToStart < closestDistance) {\n closestDistance = distanceToStart;\n closestTime = start;\n }\n\n if (distanceToEnd < closestDistance) {\n closestDistance = distanceToEnd;\n closestTime = end;\n }\n }\n }\n return closestTime;\n }\n\n function getElement() {\n return element;\n }\n\n function setElement(value) {\n //add check of value type\n if (value === null || value === undefined || (value && (/^(VIDEO|AUDIO)$/i).test(value.nodeName))) {\n element = value;\n // Workaround to force Firefox to fire the canplay event.\n if (element) {\n element.preload = 'auto';\n }\n } else {\n throw VIDEO_MODEL_WRONG_ELEMENT_TYPE;\n }\n }\n\n function setSource(source) {\n if (element) {\n if (source) {\n element.src = source;\n } else {\n element.removeAttribute('src');\n element.load();\n }\n }\n }\n\n function getSource() {\n return element ? element.src : null;\n }\n\n function getTTMLRenderingDiv() {\n return TTMLRenderingDiv;\n }\n\n function setTTMLRenderingDiv(div) {\n TTMLRenderingDiv = div;\n // The styling will allow the captions to match the video window size and position.\n TTMLRenderingDiv.style.position = 'absolute';\n TTMLRenderingDiv.style.display = 'flex';\n TTMLRenderingDiv.style.overflow = 'hidden';\n TTMLRenderingDiv.style.pointerEvents = 'none';\n TTMLRenderingDiv.style.top = 0;\n TTMLRenderingDiv.style.left = 0;\n }\n\n function setStallState(type, state) {\n stallStream(type, state);\n }\n\n function isStalled() {\n return (stalledStreams.length > 0);\n }\n\n function addStalledStream(type) {\n\n if (type === null || !element || element.seeking || stalledStreams.indexOf(type) !== -1) {\n return;\n }\n\n stalledStreams.push(type);\n }\n\n function removeStalledStream(type) {\n let index = stalledStreams.indexOf(type);\n\n if (type === null) {\n return;\n }\n if (index !== -1) {\n stalledStreams.splice(index, 1);\n }\n\n }\n\n function stallStream(type, isStalled) {\n if (isStalled) {\n addStalledStream(type);\n } else {\n removeStalledStream(type);\n }\n }\n\n //Calling play on the element will emit playing - even if the stream is stalled. If the stream is stalled, emit a waiting event.\n function onPlaying() {\n if (element && isStalled() && element.playbackRate === 0) {\n const event = document.createEvent('Event');\n event.initEvent('waiting', true, false);\n element.dispatchEvent(event);\n }\n }\n\n function getPlaybackQuality() {\n if (!element) {\n return null;\n }\n let hasWebKit = ('webkitDroppedFrameCount' in element) && ('webkitDecodedFrameCount' in element);\n let hasQuality = ('getVideoPlaybackQuality' in element);\n let result = null;\n\n if (hasQuality) {\n result = element.getVideoPlaybackQuality();\n } else if (hasWebKit) {\n result = {\n droppedVideoFrames: element.webkitDroppedFrameCount,\n totalVideoFrames: element.webkitDroppedFrameCount + element.webkitDecodedFrameCount,\n creationTime: new Date()\n };\n }\n\n return result;\n }\n\n function play() {\n if (element) {\n element.autoplay = true;\n const p = element.play();\n if (p && p.catch && typeof Promise !== 'undefined') {\n p.catch((e) => {\n if (e.name === 'NotAllowedError') {\n eventBus.trigger(Events.PLAYBACK_NOT_ALLOWED);\n }\n logger.warn(`Caught pending play exception - continuing (${e})`);\n });\n }\n }\n }\n\n function isPaused() {\n return element ? element.paused : null;\n }\n\n function pause() {\n if (element) {\n element.pause();\n element.autoplay = false;\n }\n }\n\n function isSeeking() {\n return element ? element.seeking : null;\n }\n\n function getTime() {\n return element ? element.currentTime : null;\n }\n\n function getPlaybackRate() {\n return element ? element.playbackRate : null;\n }\n\n function getPlayedRanges() {\n return element ? element.played : null;\n }\n\n function getEnded() {\n return element ? element.ended : null;\n }\n\n function addEventListener(eventName, eventCallBack) {\n if (element) {\n element.addEventListener(eventName, eventCallBack);\n }\n }\n\n function removeEventListener(eventName, eventCallBack) {\n if (element) {\n element.removeEventListener(eventName, eventCallBack);\n }\n }\n\n function getReadyState() {\n return element ? element.readyState : NaN;\n }\n\n function getBufferRange() {\n return element ? element.buffered : null;\n }\n\n function getClientWidth() {\n return element ? element.clientWidth : NaN;\n }\n\n function getClientHeight() {\n return element ? element.clientHeight : NaN;\n }\n\n function getVideoWidth() {\n return element ? element.videoWidth : NaN;\n }\n\n function getVideoHeight() {\n return element ? element.videoHeight : NaN;\n }\n\n function getVideoRelativeOffsetTop() {\n const parentElement = element.parentNode.host || element.parentNode;\n return parentElement ? element.getBoundingClientRect().top - parentElement.getBoundingClientRect().top : NaN;\n }\n\n function getVideoRelativeOffsetLeft() {\n const parentElement = element.parentNode.host || element.parentNode;\n return parentElement ? element.getBoundingClientRect().left - parentElement.getBoundingClientRect().left : NaN;\n }\n\n function getTextTracks() {\n return element ? element.textTracks : [];\n }\n\n function getTextTrack(kind, label, lang, isTTML, isEmbedded) {\n if (element) {\n for (let i = 0; i < element.textTracks.length; i++) {\n //label parameter could be a number (due to adaptationSet), but label, the attribute of textTrack, is a string => to modify...\n //label could also be undefined (due to adaptationSet)\n if (element.textTracks[i].kind === kind && (label ? element.textTracks[i].label == label : true) &&\n element.textTracks[i].language === lang && element.textTracks[i].isTTML === isTTML && element.textTracks[i].isEmbedded === isEmbedded) {\n return element.textTracks[i];\n }\n }\n }\n\n return null;\n }\n\n function addTextTrack(kind, label, lang, isTTML, isEmbedded) {\n if (!element) {\n return null;\n }\n // check if track of same type has not been already created for previous stream\n // then use it (no way to remove existing text track from video element)\n let track = getTextTrack(kind, label, lang, isTTML, isEmbedded);\n if (!track) {\n track = element.addTextTrack(kind, label, lang);\n track.isEmbedded = isEmbedded;\n track.isTTML = isTTML;\n }\n return track;\n }\n\n function appendChild(childElement) {\n if (element) {\n element.appendChild(childElement);\n //in Chrome, we need to differenciate textTrack with same lang, kind and label but different format (vtt, ttml, etc...)\n if (childElement.isTTML !== undefined) {\n element.textTracks[element.textTracks.length - 1].isTTML = childElement.isTTML;\n element.textTracks[element.textTracks.length - 1].isEmbedded = childElement.isEmbedded;\n }\n }\n }\n\n function removeChild(childElement) {\n if (element) {\n element.removeChild(childElement);\n }\n }\n\n function waitForReadyState(targetReadyState, callback) {\n if (targetReadyState === Constants.VIDEO_ELEMENT_READY_STATES.HAVE_NOTHING ||\n getReadyState() >= targetReadyState) {\n callback();\n } else {\n // wait for the appropriate callback before checking again\n const event = READY_STATES_TO_EVENT_NAMES.get(targetReadyState);\n _listenOnce(event, callback);\n }\n }\n\n function _listenOnce(event, callback) {\n const func = () => {\n // Stop listening to this event.\n removeEventListener(event, func);\n // Call the original listener.\n callback(event);\n };\n addEventListener(event, func);\n }\n\n instance = {\n initialize,\n setCurrentTime,\n play,\n isPaused,\n pause,\n isStalled,\n isSeeking,\n getTime,\n getPlaybackRate,\n setPlaybackRate,\n getPlayedRanges,\n getEnded,\n setStallState,\n getElement,\n setElement,\n setSource,\n getSource,\n getTTMLRenderingDiv,\n setTTMLRenderingDiv,\n getPlaybackQuality,\n addEventListener,\n removeEventListener,\n getReadyState,\n getBufferRange,\n getClientWidth,\n getClientHeight,\n getTextTracks,\n getTextTrack,\n addTextTrack,\n appendChild,\n removeChild,\n getVideoWidth,\n getVideoHeight,\n getVideoRelativeOffsetTop,\n getVideoRelativeOffsetLeft,\n waitForReadyState,\n reset\n };\n\n setup();\n\n return instance;\n}\n\nVideoModel.__dashjs_factory_name = 'VideoModel';\nexport default FactoryMaker.getSingletonFactory(VideoModel);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Debug from '../../core/Debug';\nimport Constants from '../constants/Constants';\n\nconst legacyKeysAndReplacements = [\n { oldKey: 'dashjs_vbitrate', newKey: 'dashjs_video_bitrate' },\n { oldKey: 'dashjs_abitrate', newKey: 'dashjs_audio_bitrate' },\n { oldKey: 'dashjs_vsettings', newKey: 'dashjs_video_settings' },\n { oldKey: 'dashjs_asettings', newKey: 'dashjs_audio_settings' }\n];\n\nconst LOCAL_STORAGE_BITRATE_KEY_TEMPLATE = 'dashjs_?_bitrate';\nconst LOCAL_STORAGE_SETTINGS_KEY_TEMPLATE = 'dashjs_?_settings';\n\nconst STORAGE_TYPE_LOCAL = 'localStorage';\nconst STORAGE_TYPE_SESSION = 'sessionStorage';\nconst LAST_BITRATE = 'lastBitrate';\nconst LAST_MEDIA_SETTINGS = 'lastMediaSettings';\n\nfunction DOMStorage(config) {\n\n config = config || {};\n const context = this.context;\n const settings = config.settings;\n\n let instance,\n logger,\n supported;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n translateLegacyKeys();\n }\n\n //type can be local, session\n function isSupported(type) {\n if (supported !== undefined) return supported;\n\n supported = false;\n\n const testKey = '1';\n const testValue = '1';\n let storage;\n\n try {\n if (typeof window !== 'undefined') {\n storage = window[type];\n }\n } catch (error) {\n logger.warn('DOMStorage access denied: ' + error.message);\n return supported;\n }\n\n if (!storage || (type !== STORAGE_TYPE_LOCAL && type !== STORAGE_TYPE_SESSION)) {\n return supported;\n }\n\n /* When Safari (OS X or iOS) is in private browsing mode, it appears as though localStorage is available, but trying to call setItem throws an exception.\n http://stackoverflow.com/questions/14555347/html5-localstorage-error-with-safari-quota-exceeded-err-dom-exception-22-an\n\n Check if the storage can be used\n */\n try {\n storage.setItem(testKey, testValue);\n storage.removeItem(testKey);\n supported = true;\n } catch (error) {\n logger.warn('DOMStorage is supported, but cannot be used: ' + error.message);\n }\n\n return supported;\n }\n\n function translateLegacyKeys() {\n if (isSupported(STORAGE_TYPE_LOCAL)) {\n legacyKeysAndReplacements.forEach(entry => {\n const value = localStorage.getItem(entry.oldKey);\n\n if (value) {\n localStorage.removeItem(entry.oldKey);\n\n try {\n localStorage.setItem(entry.newKey, value);\n } catch (e) {\n logger.error(e.message);\n }\n }\n });\n }\n }\n\n // Return current epoch time, ms, rounded to the nearest 10m to avoid fingerprinting user\n function getTimestamp() {\n const ten_minutes_ms = 60 * 1000 * 10;\n return Math.round(new Date().getTime() / ten_minutes_ms) * ten_minutes_ms;\n }\n\n function canStore(storageType, key) {\n return isSupported(storageType) && settings.get().streaming[key + 'CachingInfo'].enabled;\n }\n\n function checkConfig() {\n if (!settings) {\n throw new Error(Constants.MISSING_CONFIG_ERROR);\n }\n }\n\n function getSavedMediaSettings(type) {\n let mediaSettings = null;\n\n checkConfig();\n //Checks local storage to see if there is valid, non-expired media settings\n if (canStore(STORAGE_TYPE_LOCAL, LAST_MEDIA_SETTINGS)) {\n const key = LOCAL_STORAGE_SETTINGS_KEY_TEMPLATE.replace(/\\?/, type);\n try {\n const obj = JSON.parse(localStorage.getItem(key)) || {};\n const isExpired = (new Date().getTime() - parseInt(obj.timestamp, 10)) >= settings.get().streaming.lastMediaSettingsCachingInfo.ttl || false;\n mediaSettings = obj.settings;\n\n if (isExpired) {\n localStorage.removeItem(key);\n mediaSettings = null;\n }\n } catch (e) {\n return null;\n }\n }\n return mediaSettings;\n }\n\n function getSavedBitrateSettings(type) {\n let savedBitrate = NaN;\n\n checkConfig();\n\n //Checks local storage to see if there is valid, non-expired bit rate\n //hinting from the last play session to use as a starting bit rate.\n if (canStore(STORAGE_TYPE_LOCAL, LAST_BITRATE)) {\n const key = LOCAL_STORAGE_BITRATE_KEY_TEMPLATE.replace(/\\?/, type);\n try {\n const obj = JSON.parse(localStorage.getItem(key)) || {};\n const isExpired = (new Date().getTime() - parseInt(obj.timestamp, 10)) >= settings.get().streaming.lastBitrateCachingInfo.ttl || false;\n const bitrate = parseFloat(obj.bitrate);\n\n if (!isNaN(bitrate) && !isExpired) {\n savedBitrate = bitrate;\n logger.debug('Last saved bitrate for ' + type + ' was ' + bitrate);\n } else if (isExpired) {\n localStorage.removeItem(key);\n }\n } catch (e) {\n return null;\n }\n }\n return savedBitrate;\n }\n\n function setSavedMediaSettings(type, value) {\n if (canStore(STORAGE_TYPE_LOCAL, LAST_MEDIA_SETTINGS)) {\n const key = LOCAL_STORAGE_SETTINGS_KEY_TEMPLATE.replace(/\\?/, type);\n try {\n localStorage.setItem(key, JSON.stringify({settings: value, timestamp: getTimestamp()}));\n } catch (e) {\n logger.error(e.message);\n }\n }\n }\n\n function setSavedBitrateSettings(type, bitrate) {\n if (canStore(STORAGE_TYPE_LOCAL, LAST_BITRATE) && bitrate) {\n const key = LOCAL_STORAGE_BITRATE_KEY_TEMPLATE.replace(/\\?/, type);\n try {\n localStorage.setItem(key, JSON.stringify({bitrate: bitrate.toFixed(3), timestamp: getTimestamp()}));\n } catch (e) {\n logger.error(e.message);\n }\n }\n }\n\n instance = {\n getSavedBitrateSettings: getSavedBitrateSettings,\n setSavedBitrateSettings: setSavedBitrateSettings,\n getSavedMediaSettings: getSavedMediaSettings,\n setSavedMediaSettings: setSavedMediaSettings\n };\n\n setup();\n return instance;\n}\n\nDOMStorage.__dashjs_factory_name = 'DOMStorage';\nconst factory = FactoryMaker.getSingletonFactory(DOMStorage);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Segment from './vo/Segment';\nimport DashJSError from '../streaming/vo/DashJSError';\nimport FactoryMaker from '../core/FactoryMaker';\nimport FragmentRequest from '../streaming/vo/FragmentRequest';\nimport URLLoader from '../streaming/net/URLLoader';\n\nfunction SegmentBaseLoader() {\n\n const context = this.context;\n\n let instance,\n logger,\n errHandler,\n boxParser,\n requestModifier,\n dashMetrics,\n mediaPlayerModel,\n urlLoader,\n errors,\n constants,\n dashConstants,\n urlUtils,\n baseURLController;\n\n function setup() {\n }\n\n function initialize() {\n urlLoader = URLLoader(context).create({\n errHandler: errHandler,\n dashMetrics: dashMetrics,\n mediaPlayerModel: mediaPlayerModel,\n requestModifier: requestModifier,\n boxParser: boxParser,\n errors: errors,\n urlUtils: urlUtils,\n constants: constants,\n dashConstants: dashConstants\n });\n }\n\n function setConfig(config) {\n if (config.baseURLController) {\n baseURLController = config.baseURLController;\n }\n\n if (config.dashMetrics) {\n dashMetrics = config.dashMetrics;\n }\n\n if (config.mediaPlayerModel) {\n mediaPlayerModel = config.mediaPlayerModel;\n }\n\n if (config.errHandler) {\n errHandler = config.errHandler;\n }\n\n if (config.boxParser) {\n boxParser = config.boxParser;\n }\n\n if (config.debug) {\n logger = config.debug.getLogger(instance);\n }\n\n if (config.requestModifier) {\n requestModifier = config.requestModifier;\n }\n\n if (config.errors) {\n errors = config.errors;\n }\n\n if (config.urlUtils) {\n urlUtils = config.urlUtils;\n }\n\n if (config.constants) {\n constants = config.constants;\n }\n\n if (config.dashConstants) {\n dashConstants = config.dashConstants;\n }\n }\n\n function loadInitialization(representation, mediaType) {\n return new Promise((resolve) => {\n _loadInitializationRecursively(representation, mediaType, resolve);\n });\n }\n\n function _loadInitializationRecursively(representation, mediaType, resolve, loadingInfo) {\n let initRange = null;\n const baseUrl = representation ? baseURLController.resolve(representation.path) : null;\n const info = loadingInfo || {\n init: true,\n url: baseUrl ? baseUrl.url : undefined,\n range: {\n start: 0,\n end: 1500\n },\n searching: false,\n bytesLoaded: 0,\n bytesToLoad: 1500,\n mediaType: mediaType\n };\n\n logger.debug('Start searching for initialization.');\n\n const request = getFragmentRequest(info);\n\n const onload = function (response) {\n info.bytesLoaded = info.range.end;\n initRange = boxParser.findInitRange(response);\n\n if (initRange) {\n representation.range = initRange;\n // note that we don't explicitly set rep.initialization as this\n // will be computed when all BaseURLs are resolved later\n resolve(representation);\n } else {\n info.range.end = info.bytesLoaded + info.bytesToLoad;\n return _loadInitializationRecursively(representation, mediaType, resolve, info);\n }\n };\n\n const onerror = function () {\n resolve(representation);\n };\n\n urlLoader.load({ request: request, success: onload, error: onerror });\n\n logger.debug('Perform init search: ' + info.url);\n }\n\n function loadSegments(representation, mediaType, range) {\n return new Promise((resolve) => {\n _loadSegmentsRecursively(representation, mediaType, range, resolve);\n });\n }\n\n function _loadSegmentsRecursively(representation, mediaType, range, resolve, callback, loadingInfo) {\n if (range && (range.start === undefined || range.end === undefined)) {\n const parts = range ? range.toString().split('-') : null;\n range = parts ? { start: parseFloat(parts[0]), end: parseFloat(parts[1]) } : null;\n }\n\n callback = !callback ? onLoaded : callback;\n let isoFile = null;\n let sidx = null;\n const hasRange = !!range;\n const baseUrl = representation ? baseURLController.resolve(representation.path) : null;\n const info = {\n init: false,\n url: baseUrl ? baseUrl.url : undefined,\n range: hasRange ? range : { start: 0, end: 1500 },\n searching: !hasRange,\n bytesLoaded: loadingInfo ? loadingInfo.bytesLoaded : 0,\n bytesToLoad: 1500,\n mediaType: mediaType\n };\n\n const request = getFragmentRequest(info);\n\n const onload = function (response) {\n const extraBytes = info.bytesToLoad;\n const loadedLength = response.byteLength;\n\n info.bytesLoaded = info.range.end - info.range.start;\n isoFile = boxParser.parse(response);\n sidx = isoFile.getBox('sidx');\n\n if (!sidx || !sidx.isComplete) {\n if (sidx) {\n info.range.start = sidx.offset || info.range.start;\n info.range.end = info.range.start + (sidx.size || extraBytes);\n } else if (loadedLength < info.bytesLoaded) {\n // if we have reached a search limit or if we have reached the end of the file we have to stop trying to find sidx\n callback(null, representation, resolve);\n return;\n } else {\n const lastBox = isoFile.getLastBox();\n\n if (lastBox && lastBox.size) {\n info.range.start = lastBox.offset + lastBox.size;\n info.range.end = info.range.start + extraBytes;\n } else {\n info.range.end += extraBytes;\n }\n }\n _loadSegmentsRecursively(representation, mediaType, info.range, resolve, null, info);\n } else {\n const ref = sidx.references;\n let loadMultiSidx,\n segments;\n\n if (ref !== null && ref !== undefined && ref.length > 0) {\n loadMultiSidx = (ref[0].reference_type === 1);\n }\n\n if (loadMultiSidx) {\n logger.debug('Initiate multiple SIDX load.');\n info.range.end = info.range.start + sidx.size;\n\n let j, len, ss, se, r;\n let segs = [];\n let count = 0;\n let offset = (sidx.offset || info.range.start) + sidx.size;\n const tmpCallback = function (result) {\n if (result) {\n segs = segs.concat(result);\n count++;\n\n if (count >= len) {\n // http requests can be processed in a wrong order, so, we have to reorder segments with an ascending start Time order\n segs.sort(function (a, b) {\n return a.startTime - b.startTime < 0 ? -1 : 0;\n });\n callback(segs, representation, resolve);\n }\n } else {\n callback(null, representation, resolve);\n }\n };\n\n for (j = 0, len = ref.length; j < len; j++) {\n ss = offset;\n se = offset + ref[j].referenced_size - 1;\n offset = offset + ref[j].referenced_size;\n r = { start: ss, end: se };\n _loadSegmentsRecursively(representation, mediaType, r, resolve, tmpCallback, info);\n }\n\n } else {\n logger.debug('Parsing segments from SIDX. representation ' + mediaType + ' - id: ' + representation.id + ' for range : ' + info.range.start + ' - ' + info.range.end);\n segments = getSegmentsForSidx(sidx, info);\n callback(segments, representation, resolve);\n }\n }\n };\n\n const onerror = function () {\n callback(null, representation, resolve);\n };\n\n urlLoader.load({ request: request, success: onload, error: onerror });\n logger.debug(`Perform SIDX load for type ${mediaType} : ${info.url} with range ${info.range.start} - ${info.range.end}`);\n }\n\n function onLoaded(segments, representation, resolve) {\n resolve({\n segments: segments,\n representation: representation,\n error: segments ? undefined : new DashJSError(errors.SEGMENT_BASE_LOADER_ERROR_CODE, errors.SEGMENT_BASE_LOADER_ERROR_MESSAGE)\n });\n }\n\n function reset() {\n if (urlLoader) {\n urlLoader.abort();\n urlLoader = null;\n }\n }\n\n function getSegmentsForSidx(sidx, info) {\n const refs = sidx.references;\n const len = refs.length;\n const timescale = sidx.timescale;\n let time = sidx.earliest_presentation_time;\n let start = info.range.start + sidx.offset + sidx.first_offset + sidx.size;\n const segments = [];\n let segment,\n end,\n duration,\n size;\n\n for (let i = 0; i < len; i++) {\n duration = refs[i].subsegment_duration;\n size = refs[i].referenced_size;\n\n segment = new Segment();\n // note that we don't explicitly set segment.media as this will be\n // computed when all BaseURLs are resolved later\n segment.duration = duration;\n segment.startTime = time;\n segment.timescale = timescale;\n end = start + size - 1;\n segment.mediaRange = start + '-' + end;\n segments.push(segment);\n time += duration;\n start += size;\n }\n\n return segments;\n }\n\n function getFragmentRequest(info) {\n if (!info.url) {\n return;\n }\n const request = new FragmentRequest();\n request.setInfo(info);\n return request;\n }\n\n instance = {\n setConfig,\n initialize,\n loadInitialization,\n loadSegments,\n reset\n };\n\n setup();\n\n return instance;\n}\n\nSegmentBaseLoader.__dashjs_factory_name = 'SegmentBaseLoader';\nexport default FactoryMaker.getSingletonFactory(SegmentBaseLoader);\n","import FactoryMaker from '../../core/FactoryMaker';\n\n/**\n * Creates an instance of an EBMLParser class which implements a large subset\n * of the functionality required to parse Matroska EBML\n *\n * @param {Object} config object with data member which is the buffer to parse\n * @ignore\n */\nfunction EBMLParser(config) {\n\n config = config || {};\n let instance;\n\n let data = new DataView(config.data);\n let pos = 0;\n\n function getPos() {\n return pos;\n }\n\n function setPos(value) {\n pos = value;\n }\n\n /**\n * Consumes an EBML tag from the data stream.\n *\n * @param {Object} tag to parse, A tag is an object with at least a {number} tag and\n * {boolean} required flag.\n * @param {boolean} test whether or not the function should throw if a required\n * tag is not found\n * @return {boolean} whether or not the tag was found\n * @throws will throw an exception if a required tag is not found and test\n * param is false or undefined, or if the stream is malformed.\n * @memberof EBMLParser\n */\n function consumeTag(tag, test) {\n let found = true;\n let bytesConsumed = 0;\n let p1,\n p2;\n\n if (test === undefined) {\n test = false;\n }\n\n if (tag.tag > 0xFFFFFF) {\n if (data.getUint32(pos) !== tag.tag) {\n found = false;\n }\n bytesConsumed = 4;\n } else if (tag.tag > 0xFFFF) {\n // 3 bytes\n p1 = data.getUint16(pos);\n p2 = data.getUint8(pos + 2);\n\n // shift p1 over a byte and add p2\n if (p1 * 256 + p2 !== tag.tag) {\n found = false;\n }\n bytesConsumed = 3;\n } else if (tag.tag > 0xFF) {\n if (data.getUint16(pos) !== tag.tag) {\n found = false;\n }\n bytesConsumed = 2;\n } else {\n if (data.getUint8(pos) !== tag.tag) {\n found = false;\n }\n bytesConsumed = 1;\n }\n\n if (!found && tag.required && !test) {\n throw new Error('required tag not found');\n }\n\n if (found) {\n pos += bytesConsumed;\n }\n\n return found;\n }\n\n /**\n * Consumes an EBML tag from the data stream. If the tag is found then this\n * function will also remove the size field which follows the tag from the\n * data stream.\n *\n * @param {Object} tag to parse, A tag is an object with at least a {number} tag and\n * {boolean} required flag.\n * @param {boolean} test whether or not the function should throw if a required\n * tag is not found\n * @return {boolean} whether or not the tag was found\n * @throws will throw an exception if a required tag is not found and test\n * param is false or undefined, or if the stream is malformedata.\n * @memberof EBMLParser\n */\n function consumeTagAndSize(tag, test) {\n let found = consumeTag(tag, test);\n\n if (found) {\n getMatroskaCodedNum();\n }\n\n return found;\n }\n\n /**\n * Consumes an EBML tag from the data stream. If the tag is found then this\n * function will also remove the size field which follows the tag from the\n * data stream. It will use the value of the size field to parse a binary\n * field, using a parser defined in the tag itself\n *\n * @param {Object} tag to parse, A tag is an object with at least a {number} tag,\n * {boolean} required flag, and a parse function which takes a size parameter\n * @return {boolean} whether or not the tag was found\n * @throws will throw an exception if a required tag is not found,\n * or if the stream is malformed\n * @memberof EBMLParser\n */\n function parseTag(tag) {\n let size;\n\n consumeTag(tag);\n size = getMatroskaCodedNum();\n return instance[tag.parse](size);\n }\n\n /**\n * Consumes an EBML tag from the data stream. If the tag is found then this\n * function will also remove the size field which follows the tag from the\n * data stream. It will use the value of the size field to skip over the\n * entire section of EBML encapsulated by the tag.\n *\n * @param {Object} tag to parse, A tag is an object with at least a {number} tag, and\n * {boolean} required flag\n * @param {boolean} test a flag to indicate if an exception should be thrown\n * if a required tag is not found\n * @return {boolean} whether or not the tag was found\n * @throws will throw an exception if a required tag is not found and test is\n * false or undefined or if the stream is malformed\n * @memberof EBMLParser\n */\n function skipOverElement(tag, test) {\n let found = consumeTag(tag, test);\n let headerSize;\n\n if (found) {\n headerSize = getMatroskaCodedNum();\n pos += headerSize;\n }\n\n return found;\n }\n\n /**\n * Returns and consumes a number encoded according to the Matroska EBML\n * specification from the bitstream.\n *\n * @param {boolean} retainMSB whether or not to retain the Most Significant Bit (the\n * first 1). this is usually true when reading Tag IDs.\n * @return {number} the decoded number\n * @throws will throw an exception if the bit stream is malformed or there is\n * not enough data\n * @memberof EBMLParser\n */\n function getMatroskaCodedNum(retainMSB) {\n let bytesUsed = 1;\n let mask = 0x80;\n let maxBytes = 8;\n let extraBytes = -1;\n let num = 0;\n let ch = data.getUint8(pos);\n let i = 0;\n\n for (i = 0; i < maxBytes; i += 1) {\n if ((ch & mask) === mask) {\n num = (retainMSB === undefined) ? ch & ~mask : ch;\n extraBytes = i;\n break;\n }\n mask >>= 1;\n }\n\n for (i = 0; i < extraBytes; i += 1, bytesUsed += 1) {\n num = (num << 8) | (0xff & data.getUint8(pos + bytesUsed));\n }\n\n pos += bytesUsed;\n\n return num;\n }\n\n /**\n * Returns and consumes a float from the bitstream.\n *\n * @param {number} size 4 or 8 byte floats are supported\n * @return {number} the decoded number\n * @throws will throw an exception if the bit stream is malformed or there is\n * not enough data\n * @memberof EBMLParser\n */\n function getMatroskaFloat(size) {\n let outFloat;\n\n switch (size) {\n case 4:\n outFloat = data.getFloat32(pos);\n pos += 4;\n break;\n case 8:\n outFloat = data.getFloat64(pos);\n pos += 8;\n break;\n }\n return outFloat;\n }\n\n /**\n * Consumes and returns an unsigned int from the bitstream.\n *\n * @param {number} size 1 to 8 bytes\n * @return {number} the decoded number\n * @throws will throw an exception if the bit stream is malformed or there is\n * not enough data\n * @memberof EBMLParser\n */\n function getMatroskaUint(size) {\n let val = 0;\n\n for (let i = 0; i < size; i += 1) {\n val <<= 8;\n val |= data.getUint8(pos + i) & 0xff;\n }\n\n pos += size;\n return val;\n }\n\n /**\n * Tests whether there is more data in the bitstream for parsing\n *\n * @return {boolean} whether there is more data to parse\n * @memberof EBMLParser\n */\n function moreData() {\n return pos < data.byteLength;\n }\n\n instance = {\n getPos: getPos,\n setPos: setPos,\n consumeTag: consumeTag,\n consumeTagAndSize: consumeTagAndSize,\n parseTag: parseTag,\n skipOverElement: skipOverElement,\n getMatroskaCodedNum: getMatroskaCodedNum,\n getMatroskaFloat: getMatroskaFloat,\n getMatroskaUint: getMatroskaUint,\n moreData: moreData\n };\n\n return instance;\n}\n\nEBMLParser.__dashjs_factory_name = 'EBMLParser';\nexport default FactoryMaker.getClassFactory(EBMLParser);","import EBMLParser from '../streaming/utils/EBMLParser';\nimport Constants from '../streaming/constants/Constants';\nimport FactoryMaker from '../core/FactoryMaker';\nimport Segment from './vo/Segment';\nimport FragmentRequest from '../streaming/vo/FragmentRequest';\nimport URLLoader from '../streaming/net/URLLoader';\nimport DashJSError from '../streaming/vo/DashJSError';\n\nfunction WebmSegmentBaseLoader() {\n\n const context = this.context;\n\n let instance,\n logger,\n WebM,\n errHandler,\n requestModifier,\n dashMetrics,\n mediaPlayerModel,\n urlLoader,\n errors,\n baseURLController;\n\n function setup() {\n WebM = {\n EBML: {\n tag: 0x1A45DFA3,\n required: true\n },\n Segment: {\n tag: 0x18538067,\n required: true,\n SeekHead: {\n tag: 0x114D9B74,\n required: true\n },\n Info: {\n tag: 0x1549A966,\n required: true,\n TimecodeScale: {\n tag: 0x2AD7B1,\n required: true,\n parse: 'getMatroskaUint'\n },\n Duration: {\n tag: 0x4489,\n required: true,\n parse: 'getMatroskaFloat'\n }\n },\n Tracks: {\n tag: 0x1654AE6B,\n required: true\n },\n Cues: {\n tag: 0x1C53BB6B,\n required: true,\n CuePoint: {\n tag: 0xBB,\n required: true,\n CueTime: {\n tag: 0xB3,\n required: true,\n parse: 'getMatroskaUint'\n },\n CueTrackPositions: {\n tag: 0xB7,\n required: true,\n CueTrack: {\n tag: 0xF7,\n required: true,\n parse: 'getMatroskaUint'\n },\n CueClusterPosition: {\n tag: 0xF1,\n required: true,\n parse: 'getMatroskaUint'\n }\n }\n }\n }\n },\n Void: {\n tag: 0xEC,\n required: true\n }\n };\n }\n\n function initialize() {\n urlLoader = URLLoader(context).create({\n errHandler: errHandler,\n dashMetrics: dashMetrics,\n mediaPlayerModel: mediaPlayerModel,\n requestModifier: requestModifier,\n errors: errors\n });\n }\n\n function setConfig(config) {\n if (!config.baseURLController || !config.dashMetrics || !config.mediaPlayerModel || !config.errHandler) {\n throw new Error(Constants.MISSING_CONFIG_ERROR);\n }\n baseURLController = config.baseURLController;\n dashMetrics = config.dashMetrics;\n mediaPlayerModel = config.mediaPlayerModel;\n errHandler = config.errHandler;\n errors = config.errors;\n logger = config.debug.getLogger(instance);\n requestModifier = config.requestModifier;\n }\n\n function parseCues(ab) {\n let cues = [];\n let ebmlParser = EBMLParser(context).create({\n data: ab\n });\n let cue,\n cueTrack;\n\n ebmlParser.consumeTagAndSize(WebM.Segment.Cues);\n\n while (ebmlParser.moreData() &&\n ebmlParser.consumeTagAndSize(WebM.Segment.Cues.CuePoint, true)) {\n cue = {};\n\n cue.CueTime = ebmlParser.parseTag(WebM.Segment.Cues.CuePoint.CueTime);\n\n cue.CueTracks = [];\n while (ebmlParser.moreData() &&\n ebmlParser.consumeTag(WebM.Segment.Cues.CuePoint.CueTrackPositions, true)) {\n const cueTrackPositionSize = ebmlParser.getMatroskaCodedNum();\n const startPos = ebmlParser.getPos();\n cueTrack = {};\n\n cueTrack.Track = ebmlParser.parseTag(WebM.Segment.Cues.CuePoint.CueTrackPositions.CueTrack);\n if (cueTrack.Track === 0) {\n throw new Error('Cue track cannot be 0');\n }\n\n cueTrack.ClusterPosition =\n ebmlParser.parseTag(WebM.Segment.Cues.CuePoint.CueTrackPositions.CueClusterPosition);\n\n cue.CueTracks.push(cueTrack);\n\n // we're not interested any other elements - skip remaining bytes\n ebmlParser.setPos(startPos + cueTrackPositionSize);\n }\n\n if (cue.CueTracks.length === 0) {\n throw new Error('Mandatory cuetrack not found');\n }\n cues.push(cue);\n }\n\n if (cues.length === 0) {\n throw new Error('mandatory cuepoint not found');\n }\n return cues;\n }\n\n function parseSegments(data, segmentStart, segmentEnd, segmentDuration) {\n let duration,\n parsed,\n segments,\n segment,\n i,\n len,\n start,\n end;\n\n parsed = parseCues(data);\n segments = [];\n\n // we are assuming one cue track per cue point\n // both duration and media range require the i + 1 segment\n // the final segment has to use global segment parameters\n for (i = 0, len = parsed.length; i < len; i += 1) {\n segment = new Segment();\n duration = 0;\n\n if (i < parsed.length - 1) {\n duration = parsed[i + 1].CueTime - parsed[i].CueTime;\n } else {\n duration = segmentDuration - parsed[i].CueTime;\n }\n\n // note that we don't explicitly set segment.media as this will be\n // computed when all BaseURLs are resolved later\n segment.duration = duration;\n segment.startTime = parsed[i].CueTime;\n segment.timescale = 1000; // hardcoded for ms\n start = parsed[i].CueTracks[0].ClusterPosition + segmentStart;\n\n if (i < parsed.length - 1) {\n end = parsed[i + 1].CueTracks[0].ClusterPosition + segmentStart - 1;\n } else {\n end = segmentEnd - 1;\n }\n\n segment.mediaRange = start + '-' + end;\n segments.push(segment);\n }\n\n logger.debug('Parsed cues: ' + segments.length + ' cues.');\n\n return segments;\n }\n\n function parseEbmlHeader(data, media, theRange, callback) {\n if (!data || data.byteLength === 0) {\n callback(null);\n return;\n }\n let ebmlParser = EBMLParser(context).create({\n data: data\n });\n let duration,\n segments,\n segmentEnd,\n segmentStart;\n let parts = theRange ? theRange.split('-') : null;\n let request = null;\n let info = {\n url: media,\n range: {\n start: parts ? parseFloat(parts[0]) : null,\n end: parts ? parseFloat(parts[1]) : null\n },\n request: request\n };\n\n logger.debug('Parse EBML header: ' + info.url);\n\n // skip over the header itself\n ebmlParser.skipOverElement(WebM.EBML);\n ebmlParser.consumeTag(WebM.Segment);\n\n // segments start here\n segmentEnd = ebmlParser.getMatroskaCodedNum();\n segmentEnd += ebmlParser.getPos();\n segmentStart = ebmlParser.getPos();\n\n // skip over any top level elements to get to the segment info\n while (ebmlParser.moreData() &&\n !ebmlParser.consumeTagAndSize(WebM.Segment.Info, true)) {\n if (!(ebmlParser.skipOverElement(WebM.Segment.SeekHead, true) ||\n ebmlParser.skipOverElement(WebM.Segment.Tracks, true) ||\n ebmlParser.skipOverElement(WebM.Segment.Cues, true) ||\n ebmlParser.skipOverElement(WebM.Void, true))) {\n throw new Error('no valid top level element found');\n }\n }\n\n // we only need one thing in segment info, duration\n while (duration === undefined) {\n let infoTag = ebmlParser.getMatroskaCodedNum(true);\n let infoElementSize = ebmlParser.getMatroskaCodedNum();\n\n switch (infoTag) {\n case WebM.Segment.Info.Duration.tag:\n duration = ebmlParser[WebM.Segment.Info.Duration.parse](infoElementSize);\n break;\n default:\n ebmlParser.setPos(ebmlParser.getPos() + infoElementSize);\n break;\n }\n }\n\n // once we have what we need from segment info, we jump right to the\n // cues\n\n request = _getFragmentRequest(info);\n\n const onload = function (response) {\n segments = parseSegments(response, segmentStart, segmentEnd, duration);\n callback(segments);\n };\n\n const onloadend = function () {\n logger.error('Download Error: Cues ' + info.url);\n callback(null);\n };\n\n urlLoader.load({\n request: request,\n success: onload,\n error: onloadend\n });\n\n logger.debug('Perform cues load: ' + info.url + ' bytes=' + info.range.start + '-' + info.range.end);\n }\n\n function loadInitialization(representation, mediaType) {\n return new Promise((resolve) => {\n let request = null;\n let baseUrl = representation ? baseURLController.resolve(representation.path) : null;\n let initRange = representation ? representation.range.split('-') : null;\n let info = {\n range: {\n start: initRange ? parseFloat(initRange[0]) : null,\n end: initRange ? parseFloat(initRange[1]) : null\n },\n request: request,\n url: baseUrl ? baseUrl.url : undefined,\n init: true,\n mediaType: mediaType\n };\n\n logger.info('Start loading initialization.');\n\n request = _getFragmentRequest(info);\n\n const onload = function () {\n // note that we don't explicitly set rep.initialization as this\n // will be computed when all BaseURLs are resolved later\n resolve(representation);\n };\n\n const onloadend = function () {\n resolve(representation);\n };\n\n urlLoader.load({\n request: request,\n success: onload,\n error: onloadend\n });\n\n logger.debug('Perform init load: ' + info.url);\n });\n }\n\n function loadSegments(representation, mediaType, theRange) {\n return new Promise((resolve) => {\n let request = null;\n let baseUrl = representation ? baseURLController.resolve(representation.path) : null;\n let media = baseUrl ? baseUrl.url : undefined;\n let bytesToLoad = 8192;\n let info = {\n bytesLoaded: 0,\n bytesToLoad: bytesToLoad,\n range: {\n start: 0,\n end: bytesToLoad\n },\n request: request,\n url: media,\n init: false,\n mediaType: mediaType\n };\n\n request = _getFragmentRequest(info);\n\n // first load the header, but preserve the manifest range so we can\n // load the cues after parsing the header\n // NOTE: we expect segment info to appear in the first 8192 bytes\n logger.debug('Parsing ebml header');\n\n const onload = function (response) {\n parseEbmlHeader(response, media, theRange, function (segments) {\n resolve({\n segments: segments,\n representation: representation,\n error: segments ? undefined : new DashJSError(errors.SEGMENT_BASE_LOADER_ERROR_CODE, errors.SEGMENT_BASE_LOADER_ERROR_MESSAGE)\n });\n });\n };\n\n const onloadend = function () {\n resolve({\n representation: representation,\n error: new DashJSError(errors.SEGMENT_BASE_LOADER_ERROR_CODE, errors.SEGMENT_BASE_LOADER_ERROR_MESSAGE)\n });\n };\n\n urlLoader.load({\n request: request,\n success: onload,\n error: onloadend\n });\n });\n\n }\n\n\n function _getFragmentRequest(info) {\n const request = new FragmentRequest();\n request.setInfo(info);\n return request;\n }\n\n function reset() {\n if (urlLoader) {\n urlLoader.abort();\n urlLoader = null;\n }\n }\n\n instance = {\n setConfig,\n initialize,\n loadInitialization,\n loadSegments,\n reset\n };\n\n setup();\n\n return instance;\n}\n\nWebmSegmentBaseLoader.__dashjs_factory_name = 'WebmSegmentBaseLoader';\nexport default FactoryMaker.getSingletonFactory(WebmSegmentBaseLoader);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport FactoryMaker from '../../core/FactoryMaker';\n\nimport SegmentBaseLoader from '../SegmentBaseLoader';\nimport WebmSegmentBaseLoader from '../WebmSegmentBaseLoader';\n\nfunction SegmentBaseController(config) {\n config = config || {};\n\n const context = this.context;\n const eventBus = config.eventBus;\n const events = config.events;\n const dashMetrics = config.dashMetrics;\n const mediaPlayerModel = config.mediaPlayerModel;\n const errHandler = config.errHandler;\n const baseURLController = config.baseURLController;\n const debug = config.debug;\n const boxParser = config.boxParser;\n const requestModifier = config.requestModifier;\n const errors = config.errors;\n\n let instance,\n segmentBaseLoader,\n webmSegmentBaseLoader;\n\n function setup() {\n segmentBaseLoader = SegmentBaseLoader(context).getInstance();\n webmSegmentBaseLoader = WebmSegmentBaseLoader(context).getInstance();\n\n segmentBaseLoader.setConfig({\n baseURLController: baseURLController,\n dashMetrics: dashMetrics,\n mediaPlayerModel: mediaPlayerModel,\n errHandler: errHandler,\n eventBus: eventBus,\n events: events,\n errors: errors,\n debug: debug,\n boxParser: boxParser,\n requestModifier: requestModifier\n });\n\n webmSegmentBaseLoader.setConfig({\n baseURLController: baseURLController,\n dashMetrics: dashMetrics,\n mediaPlayerModel: mediaPlayerModel,\n errHandler: errHandler,\n eventBus: eventBus,\n events: events,\n errors: errors,\n debug: debug,\n requestModifier: requestModifier\n });\n }\n\n function isWebM(mimeType) {\n const type = mimeType ? mimeType.split('/')[1] : '';\n return 'webm' === type.toLowerCase();\n }\n\n function initialize() {\n segmentBaseLoader.initialize();\n webmSegmentBaseLoader.initialize();\n }\n\n function getSegmentBaseInitSegment(data) {\n if (isWebM(data.representation.mimeType)) {\n return webmSegmentBaseLoader.loadInitialization(data.representation, data.mediaType);\n } else {\n return segmentBaseLoader.loadInitialization(data.representation, data.mediaType);\n }\n }\n\n function getSegmentList(e) {\n if (isWebM(e.mimeType)) {\n return webmSegmentBaseLoader.loadSegments(e.representation, e.mediaType, e.representation ? e.representation.indexRange : null);\n } else {\n return segmentBaseLoader.loadSegments(e.representation, e.mediaType, e.representation ? e.representation.indexRange : null);\n }\n }\n\n function reset() {\n segmentBaseLoader.reset();\n webmSegmentBaseLoader.reset();\n }\n\n\n instance = {\n initialize,\n getSegmentBaseInitSegment,\n getSegmentList,\n reset\n };\n\n setup();\n\n return instance;\n}\n\nSegmentBaseController.__dashjs_factory_name = 'SegmentBaseController';\nconst factory = FactoryMaker.getSingletonFactory(SegmentBaseController);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass RepresentationInfo {\n constructor() {\n this.id = null;\n this.quality = null;\n this.fragmentDuration = null;\n this.mediaInfo = null;\n this.MSETimeOffset = null;\n }\n}\n\nexport default RepresentationInfo;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass MediaInfo {\n constructor() {\n this.id = null;\n this.index = null;\n this.type = null;\n this.streamInfo = null;\n this.representationCount = 0;\n this.labels = null;\n this.lang = null;\n this.viewpoint = null;\n this.accessibility = null;\n this.audioChannelConfiguration = null;\n this.roles = null;\n this.codec = null;\n this.mimeType = null;\n this.contentProtection = null;\n this.KID = null;\n this.bitrateList = null;\n this.isFragmented = null;\n this.isEmbedded = null;\n this.selectionPriority = 1;\n }\n\n}\n\nexport default MediaInfo;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass StreamInfo {\n constructor() {\n this.id = null;\n this.index = null;\n this.start = NaN;\n this.duration = NaN;\n this.manifestInfo = null;\n this.isLast = true;\n }\n}\n\nexport default StreamInfo;","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass ManifestInfo {\n constructor() {\n this.dvrWindowSize = NaN;\n this.loadedTime = null;\n this.availableFrom = null;\n this.minBufferTime = NaN;\n this.duration = NaN;\n this.isDynamic = false;\n this.maxFragmentDuration = null;\n }\n}\n\nexport default ManifestInfo;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass SimpleXPath {\n constructor(selector) {\n // establish validation of the path, to catch unsupported cases\n this.valid = selector[0] == '/'; // first check, we only support absolute addressing\n\n // establish parsed path, example:\n // /MPD/Period[@id=\"foobar\"]/AdaptationSet[@id=\"2\"]/SegmentTemplate/SegmentTimeline\n this.path = selector.split('/')\n .filter((component) => component.length !== 0) // remove excess empty components\n .map((component) => {\n let parsed = {\n name: component\n };\n\n let qualifierPoint = component.indexOf('[');\n if (qualifierPoint != -1) {\n parsed.name = component.substring(0, qualifierPoint);\n\n let qualifier = component.substring(qualifierPoint + 1, component.length - 1);\n\n // quick sanity check are there additional qualifiers making this invalid\n this.valid = this.valid && qualifier.indexOf('[') == -1;\n\n let equalityPoint = qualifier.indexOf('=');\n if (equalityPoint != -1) {\n parsed.attribute = {\n name: qualifier.substring(1, equalityPoint), // skip the @\n value: qualifier.substring(equalityPoint + 1)\n };\n\n // check for single and double quoted attribute values\n if (['\\'', '\"'].indexOf(parsed.attribute.value[0]) != -1) {\n parsed.attribute.value = parsed.attribute.value.substring(1, parsed.attribute.value.length - 1);\n }\n } else {\n // positional access in xpath is 1-based index\n // internal processes will assume 0-based so we normalize that here\n parsed.position = parseInt(qualifier, 10) - 1;\n }\n }\n\n return parsed;\n });\n }\n\n isValid() {\n return this.valid;\n }\n\n findsElement() {\n return !this.findsAttribute();\n }\n\n findsAttribute() {\n return this.path[this.path.length - 1].name.startsWith('@');\n }\n\n getMpdTarget(root, isSiblingOperation) {\n let parent = null;\n let leaf = root;\n // assume root is MPD and we start at next level match\n let level = 1;\n let name = 'MPD';\n\n while ( level < this.path.length && leaf !== null) {\n // set parent to current\n parent = leaf;\n\n // select next leaf based on component\n let component = this.path[level];\n name = component.name;\n\n // stop one early if this is the last element and an attribute\n if (level !== this.path.length - 1 || !name.startsWith('@')) {\n let children = parent[name + '_asArray'] || [];\n if (children.length === 0 && parent[name]) {\n children.push(parent[name]);\n }\n\n if (component.position) {\n leaf = children[component.position] || null;\n } else if (component.attribute) {\n let attr = component.attribute;\n leaf = children.filter((elm) => elm[attr.name] == attr.value)[0] || null;\n } else {\n // default case, select first\n leaf = children[0] || null;\n }\n }\n\n level++;\n }\n\n if (leaf === null) {\n // given path not found in root\n return null;\n }\n\n // attributes the target is the leaf node, the name is the attribute\n if (name.startsWith('@')) {\n return {\n name: name.substring(1),\n leaf: leaf,\n target: leaf\n };\n }\n\n // otherwise we target the parent for sibling operations and leaf for child operations\n return {\n name: name,\n leaf: leaf,\n target: isSiblingOperation ? parent : leaf\n };\n }\n}\n\nexport default SimpleXPath;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass PatchOperation {\n constructor(action, xpath, value) {\n this.action = action;\n this.xpath = xpath;\n this.value = value;\n this.position = null;\n }\n\n getMpdTarget(root) {\n let isSiblingOperation = this.action === 'remove' || this.action === 'replace' || this.position === 'before' || this.position === 'after';\n return this.xpath.getMpdTarget(root, isSiblingOperation);\n }\n}\n\nexport default PatchOperation;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport DashConstants from '../constants/DashConstants';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Debug from '../../core/Debug';\nimport SimpleXPath from '../vo/SimpleXPath';\nimport PatchOperation from '../vo/PatchOperation';\n\nfunction PatchManifestModel() {\n let instance,\n logger;\n\n const context = this.context;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n }\n\n function getIsPatch(patch) {\n return patch && patch.hasOwnProperty(DashConstants.ORIGINAL_MPD_ID) || false;\n }\n\n function getPublishTime(patch) {\n return patch && patch.hasOwnProperty(DashConstants.PUBLISH_TIME) ? new Date(patch[DashConstants.PUBLISH_TIME]) : null;\n }\n\n function getOriginalPublishTime(patch) {\n return patch && patch.hasOwnProperty(DashConstants.ORIGINAL_PUBLISH_TIME) ? new Date(patch[DashConstants.ORIGINAL_PUBLISH_TIME]) : null;\n }\n\n function getMpdId(patch) {\n return (patch && patch[DashConstants.ORIGINAL_MPD_ID]) || null;\n }\n\n function getPatchOperations(patch) {\n if (!patch) {\n return [];\n }\n\n // Go through the patch operations in order and parse their actions out for usage\n return (patch.__children || []).map((nodeContainer) => {\n let action = Object.keys(nodeContainer)[0];\n\n // we only look add add/remove/replace actions\n if (action !== 'add' && action !== 'remove' && action !== 'replace') {\n logger.warn(`Ignoring node of invalid action: ${action}`);\n return null;\n }\n\n let node = nodeContainer[action];\n let selector = node.sel;\n\n // add action can have special targeting via the 'type' attribute\n if (action === 'add' && node.type) {\n if (!node.type.startsWith('@')) {\n logger.warn(`Ignoring add action for prefixed namespace declaration: ${node.type}=${node.__text}`);\n return null;\n }\n\n // for our purposes adding/replacing attribute are equivalent and we can normalize\n // our processing logic by appending the attribute to the selector path\n selector = `${selector}/${node.type}`;\n }\n\n let xpath = new SimpleXPath(selector);\n if (!xpath.isValid()) {\n logger.warn(`Ignoring action with invalid selector: ${action} - ${selector}`);\n return null;\n }\n\n let value = null;\n if (xpath.findsAttribute()) {\n value = node.__text || '';\n } else if (action !== 'remove') {\n value = node.__children.reduce((groups, child) => {\n // note that this is informed by xml2js parse structure for the __children array\n // which will be something like this for each child:\n // {\n // \"<node-name>\": { <xml2js-node-object> }\n // }\n let key = Object.keys(child)[0];\n // we also ignore\n if (key !== '#text') {\n groups[key] = groups[key] || [];\n groups[key].push(child[key]);\n }\n return groups;\n }, {});\n }\n\n let operation = new PatchOperation(action, xpath, value);\n\n if (action === 'add') {\n operation.position = node.pos;\n }\n\n return operation;\n }).filter((operation) => !!operation);\n }\n\n instance = {\n getIsPatch: getIsPatch,\n getPublishTime: getPublishTime,\n getOriginalPublishTime: getOriginalPublishTime,\n getMpdId: getMpdId,\n getPatchOperations: getPatchOperations\n };\n\n setup();\n\n return instance;\n}\n\nPatchManifestModel.__dashjs_factory_name = 'PatchManifestModel';\nexport default FactoryMaker.getSingletonFactory(PatchManifestModel);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport DashConstants from './constants/DashConstants';\nimport RepresentationInfo from './vo/RepresentationInfo';\nimport MediaInfo from './vo/MediaInfo';\nimport StreamInfo from './vo/StreamInfo';\nimport ManifestInfo from './vo/ManifestInfo';\nimport Event from './vo/Event';\nimport FactoryMaker from '../core/FactoryMaker';\nimport DashManifestModel from './models/DashManifestModel';\nimport PatchManifestModel from './models/PatchManifestModel';\n\n/**\n * @module DashAdapter\n * @description The DashAdapter module can be accessed using the MediaPlayer API getDashAdapter()\n */\n\nfunction DashAdapter() {\n let instance,\n dashManifestModel,\n patchManifestModel,\n voPeriods,\n currentMediaInfo,\n constants,\n cea608parser;\n\n const context = this.context;\n\n const PROFILE_DVB = 'urn:dvb:dash:profile:dvb-dash:2014';\n\n function setup() {\n dashManifestModel = DashManifestModel(context).getInstance();\n patchManifestModel = PatchManifestModel(context).getInstance();\n reset();\n }\n\n // #region PUBLIC FUNCTIONS\n // --------------------------------------------------\n function setConfig(config) {\n if (!config) return;\n\n if (config.constants) {\n constants = config.constants;\n }\n\n if (config.cea608parser) {\n cea608parser = config.cea608parser;\n }\n\n if (config.errHandler) {\n dashManifestModel.setConfig({ errHandler: config.errHandler });\n }\n\n if (config.BASE64) {\n dashManifestModel.setConfig({ BASE64: config.BASE64 });\n }\n }\n\n /**\n * Creates an instance of RepresentationInfo based on a representation value object\n * @param {object} voRepresentation\n * @returns {RepresentationInfo|null} representationInfo\n * @memberOf module:DashAdapter\n * @instance\n * @ignore\n */\n function convertRepresentationToRepresentationInfo(voRepresentation) {\n if (voRepresentation) {\n let representationInfo = new RepresentationInfo();\n const realAdaptation = voRepresentation.adaptation.period.mpd.manifest.Period_asArray[voRepresentation.adaptation.period.index].AdaptationSet_asArray[voRepresentation.adaptation.index];\n const realRepresentation = dashManifestModel.getRepresentationFor(voRepresentation.index, realAdaptation);\n\n representationInfo.id = voRepresentation.id;\n representationInfo.quality = voRepresentation.index;\n representationInfo.bandwidth = dashManifestModel.getBandwidth(realRepresentation);\n representationInfo.fragmentDuration = voRepresentation.segmentDuration || (voRepresentation.segments && voRepresentation.segments.length > 0 ? voRepresentation.segments[0].duration : NaN);\n representationInfo.MSETimeOffset = voRepresentation.MSETimeOffset;\n representationInfo.mediaInfo = convertAdaptationToMediaInfo(voRepresentation.adaptation);\n\n return representationInfo;\n } else {\n return null;\n }\n }\n\n /**\n * Returns a MediaInfo object for a given media type and the corresponding streamInfo.\n * @param {object} streamInfo\n * @param {MediaType }type\n * @returns {null|MediaInfo} mediaInfo\n * @memberOf module:DashAdapter\n * @instance\n */\n function getMediaInfoForType(streamInfo, type) {\n if (voPeriods.length === 0 || !streamInfo) {\n return null;\n }\n\n let selectedVoPeriod = getPeriodForStreamInfo(streamInfo, voPeriods);\n if (!selectedVoPeriod) return null;\n\n const voAdaptations = dashManifestModel.getAdaptationsForPeriod(selectedVoPeriod);\n\n let realAdaptation = getAdaptationForType(streamInfo.index, type, streamInfo);\n if (!realAdaptation) return null;\n let idx = dashManifestModel.getIndexForAdaptation(realAdaptation, voPeriods[0].mpd.manifest, streamInfo.index);\n\n return convertAdaptationToMediaInfo(voAdaptations[idx]);\n }\n\n /**\n * Checks if the role of the specified AdaptationSet is set to main\n * @param {object} adaptation\n * @returns {boolean}\n * @memberOf module:DashAdapter\n * @instance\n */\n function getIsMain(adaptation) {\n return dashManifestModel.getRolesForAdaptation(adaptation).filter(function (role) {\n return role.value === DashConstants.MAIN;\n })[0];\n }\n\n /**\n * Returns the AdaptationSet for a given period index and a given mediaType.\n * @param {number} periodIndex\n * @param {MediaType} type\n * @param {object} streamInfo\n * @returns {null|object} adaptation\n * @memberOf module:DashAdapter\n * @instance\n */\n function getAdaptationForType(periodIndex, type, streamInfo) {\n const adaptations = dashManifestModel.getAdaptationsForType(voPeriods[0].mpd.manifest, periodIndex, type);\n\n if (!adaptations || adaptations.length === 0) return null;\n\n if (adaptations.length > 1 && streamInfo) {\n const allMediaInfoForType = getAllMediaInfoForType(streamInfo, type);\n\n if (currentMediaInfo[streamInfo.id] && currentMediaInfo[streamInfo.id][type]) {\n for (let i = 0, ln = adaptations.length; i < ln; i++) {\n if (areMediaInfosEqual(currentMediaInfo[streamInfo.id][type], allMediaInfoForType[i])) {\n return adaptations[i];\n }\n }\n }\n\n for (let i = 0, ln = adaptations.length; i < ln; i++) {\n if (getIsMain(adaptations[i])) {\n return adaptations[i];\n }\n }\n }\n\n return adaptations[0];\n }\n\n /**\n * Compares two mediaInfo objects\n * @param {MediaInfo} mInfoOne\n * @param {MediaInfo} mInfoTwo\n * @returns {boolean}\n */\n function areMediaInfosEqual(mInfoOne, mInfoTwo) {\n if (!mInfoOne || !mInfoTwo) {\n return false;\n }\n\n const sameId = mInfoOne.id === mInfoTwo.id;\n const sameCodec = mInfoOne.codec === mInfoTwo.codec;\n const sameViewpoint = mInfoOne.viewpoint === mInfoTwo.viewpoint;\n const sameLang = mInfoOne.lang === mInfoTwo.lang;\n const sameRoles = mInfoOne.roles.toString() === mInfoTwo.roles.toString();\n const sameAccessibility = mInfoOne.accessibility.toString() === mInfoTwo.accessibility.toString();\n const sameAudioChannelConfiguration = mInfoOne.audioChannelConfiguration.toString() === mInfoTwo.audioChannelConfiguration.toString();\n\n return (sameId && sameCodec && sameViewpoint && sameLang && sameRoles && sameAccessibility && sameAudioChannelConfiguration);\n }\n\n function _getAllMediaInfo(manifest, period, streamInfo, adaptations, type, embeddedText) {\n let mediaArr = [];\n let data,\n media,\n idx,\n i,\n j,\n ln;\n\n if (!adaptations || adaptations.length === 0) {\n return [];\n }\n\n const voAdaptations = dashManifestModel.getAdaptationsForPeriod(period);\n\n for (i = 0, ln = adaptations.length; i < ln; i++) {\n data = adaptations[i];\n idx = dashManifestModel.getIndexForAdaptation(data, manifest, streamInfo.index);\n media = convertAdaptationToMediaInfo(voAdaptations[idx]);\n\n if (embeddedText) {\n let accessibilityLength = media.accessibility.length;\n for (j = 0; j < accessibilityLength; j++) {\n if (!media) {\n continue;\n }\n let accessibility = media.accessibility[j];\n if (accessibility.indexOf('cea-608:') === 0) {\n let value = accessibility.substring(8);\n let parts = value.split(';');\n if (parts[0].substring(0, 2) === 'CC') {\n for (j = 0; j < parts.length; j++) {\n if (!media) {\n media = convertAdaptationToMediaInfo.call(this, voAdaptations[idx]);\n }\n convertVideoInfoToEmbeddedTextInfo(media, parts[j].substring(0, 3), parts[j].substring(4));\n mediaArr.push(media);\n media = null;\n }\n } else {\n for (j = 0; j < parts.length; j++) { // Only languages for CC1, CC2, ...\n if (!media) {\n media = convertAdaptationToMediaInfo.call(this, voAdaptations[idx]);\n }\n convertVideoInfoToEmbeddedTextInfo(media, 'CC' + (j + 1), parts[j]);\n mediaArr.push(media);\n media = null;\n }\n }\n } else if (accessibility.indexOf('cea-608') === 0) { // Nothing known. We interpret it as CC1=eng\n convertVideoInfoToEmbeddedTextInfo(media, constants.CC1, 'eng');\n mediaArr.push(media);\n media = null;\n }\n }\n } else if (type === constants.IMAGE) {\n convertVideoInfoToThumbnailInfo(media);\n mediaArr.push(media);\n media = null;\n } else if (media) {\n mediaArr.push(media);\n }\n }\n\n return mediaArr;\n }\n\n /**\n * Returns all the mediaInfos for a given mediaType and the corresponding streamInfo.\n * @param {object} streamInfo\n * @param {MediaType} type\n * @param {object} externalManifest Set to null or undefined if no external manifest is to be used\n * @returns {Array} mediaArr\n * @memberOf module:DashAdapter\n * @instance\n */\n function getAllMediaInfoForType(streamInfo, type, externalManifest) {\n let voLocalPeriods = voPeriods;\n let manifest = externalManifest;\n let mediaArr = [];\n\n if (manifest) {\n checkConfig();\n\n voLocalPeriods = getRegularPeriods(manifest);\n } else {\n if (voPeriods.length > 0) {\n manifest = voPeriods[0].mpd.manifest;\n } else {\n return mediaArr;\n }\n }\n\n const selectedVoPeriod = getPeriodForStreamInfo(streamInfo, voLocalPeriods);\n let adaptationsForType = dashManifestModel.getAdaptationsForType(manifest, streamInfo ? streamInfo.index : null, type);\n\n mediaArr = _getAllMediaInfo(manifest, selectedVoPeriod, streamInfo, adaptationsForType, type);\n\n // Search for embedded text in video track\n if (type === constants.TEXT) {\n adaptationsForType = dashManifestModel.getAdaptationsForType(manifest, streamInfo ? streamInfo.index : null, constants.VIDEO);\n mediaArr = mediaArr.concat(_getAllMediaInfo(manifest, selectedVoPeriod, streamInfo, adaptationsForType, type, true));\n }\n\n return mediaArr;\n }\n\n /**\n * Update the internal voPeriods array with the information from the new manifest\n * @param {object} newManifest\n * @returns {*}\n * @memberOf module:DashAdapter\n * @instance\n * @ignore\n */\n function updatePeriods(newManifest) {\n if (!newManifest) return null;\n\n checkConfig();\n\n voPeriods = getRegularPeriods(newManifest);\n }\n\n /**\n * Returns an array of streamInfo objects\n * @param {object} externalManifest\n * @param {number} maxStreamsInfo\n * @returns {Array} streams\n * @memberOf module:DashAdapter\n * @instance\n * @ignore\n */\n function getStreamsInfo(externalManifest, maxStreamsInfo) {\n const streams = [];\n let voLocalPeriods = voPeriods;\n\n //if manifest is defined, getStreamsInfo is for an outside manifest, not the current one\n if (externalManifest) {\n checkConfig();\n voLocalPeriods = getRegularPeriods(externalManifest);\n }\n\n if (voLocalPeriods.length > 0) {\n if (!maxStreamsInfo || maxStreamsInfo > voLocalPeriods.length) {\n maxStreamsInfo = voLocalPeriods.length;\n }\n for (let i = 0; i < maxStreamsInfo; i++) {\n streams.push(convertPeriodToStreamInfo(voLocalPeriods[i]));\n }\n }\n\n return streams;\n }\n\n /**\n * Returns the AdaptationSet as saved in the DashManifestModel\n * @param {object} streamInfo\n * @param {object} mediaInfo\n * @returns {object} realAdaptation\n * @memberOf module:DashAdapter\n * @instance\n */\n function getRealAdaptation(streamInfo, mediaInfo) {\n let id,\n realAdaptation;\n\n const selectedVoPeriod = getPeriodForStreamInfo(streamInfo, voPeriods);\n\n id = mediaInfo ? mediaInfo.id : null;\n\n if (voPeriods.length > 0 && selectedVoPeriod) {\n realAdaptation = id ? dashManifestModel.getAdaptationForId(id, voPeriods[0].mpd.manifest, selectedVoPeriod.index) : dashManifestModel.getAdaptationForIndex(mediaInfo ? mediaInfo.index : null, voPeriods[0].mpd.manifest, selectedVoPeriod.index);\n }\n\n return realAdaptation;\n }\n\n /**\n * Return all EssentialProperties of a Representation\n * @param {object} representation\n * @return {array}\n */\n function getEssentialPropertiesForRepresentation(representation) {\n try {\n return dashManifestModel.getEssentialPropertiesForRepresentation(representation);\n } catch (e) {\n return [];\n }\n }\n\n /**\n * Returns the period as defined in the DashManifestModel for a given index\n * @param {number} index\n * @return {object}\n */\n function getRealPeriodByIndex(index) {\n return dashManifestModel.getRealPeriodForIndex(index, voPeriods[0].mpd.manifest);\n }\n\n /**\n * Returns all voRepresentations for a given mediaInfo\n * @param {object} mediaInfo\n * @returns {Array} voReps\n * @memberOf module:DashAdapter\n * @instance\n */\n function getVoRepresentations(mediaInfo) {\n let voReps;\n\n const voAdaptation = getAdaptationForMediaInfo(mediaInfo);\n voReps = dashManifestModel.getRepresentationsForAdaptation(voAdaptation);\n\n return voReps;\n }\n\n /**\n * Returns the event for the given parameters.\n * @param {object} eventBox\n * @param {object} eventStreams\n * @param {number} mediaStartTime\n * @param {object} voRepresentation\n * @returns {null|Event}\n * @memberOf module:DashAdapter\n * @instance\n * @ignore\n */\n function getEvent(eventBox, eventStreams, mediaStartTime, voRepresentation) {\n try {\n if (!eventBox || !eventStreams || isNaN(mediaStartTime) || !voRepresentation) {\n return null;\n }\n\n const schemeIdUri = eventBox.scheme_id_uri;\n const value = eventBox.value;\n\n if (!eventStreams[schemeIdUri + '/' + value]) {\n return null;\n }\n\n const event = new Event();\n const timescale = eventBox.timescale || 1;\n const periodStart = voRepresentation.adaptation.period.start;\n const eventStream = eventStreams[schemeIdUri + '/' + value];\n const presentationTimeOffset = !isNaN(voRepresentation.presentationTimeOffset) ? voRepresentation.presentationTimeOffset : !isNaN(eventStream.presentationTimeOffset) ? eventStream.presentationTimeOffset : 0;\n let presentationTimeDelta = eventBox.presentation_time_delta / timescale; // In case of version 1 events the presentation_time is parsed as presentation_time_delta\n let calculatedPresentationTime;\n\n if (eventBox.version === 0) {\n calculatedPresentationTime = periodStart + mediaStartTime - presentationTimeOffset + presentationTimeDelta;\n } else {\n calculatedPresentationTime = periodStart - presentationTimeOffset + presentationTimeDelta;\n }\n\n const duration = eventBox.event_duration;\n const id = eventBox.id;\n const messageData = eventBox.message_data;\n\n event.eventStream = eventStream;\n event.eventStream.value = value;\n event.eventStream.timescale = timescale;\n event.duration = duration;\n event.id = id;\n event.calculatedPresentationTime = calculatedPresentationTime;\n event.messageData = messageData;\n event.presentationTimeDelta = presentationTimeDelta;\n\n return event;\n } catch (e) {\n return null;\n }\n }\n\n /**\n * Returns the events for the given info object. info can either be an instance of StreamInfo, MediaInfo or RepresentationInfo\n * @param {object} info\n * @param {object} voRepresentation\n * @returns {Array}\n * @memberOf module:DashAdapter\n * @instance\n * @ignore\n */\n function getEventsFor(info, voRepresentation) {\n let events = [];\n\n if (voPeriods.length > 0) {\n const manifest = voPeriods[0].mpd.manifest;\n\n if (info instanceof StreamInfo) {\n events = dashManifestModel.getEventsForPeriod(getPeriodForStreamInfo(info, voPeriods));\n } else if (info instanceof MediaInfo) {\n events = dashManifestModel.getEventStreamForAdaptationSet(manifest, getAdaptationForMediaInfo(info));\n } else if (info instanceof RepresentationInfo) {\n events = dashManifestModel.getEventStreamForRepresentation(manifest, voRepresentation);\n }\n }\n\n return events;\n }\n\n /**\n * Sets the current active mediaInfo for a given streamId and a given mediaType\n * @param {number} streamId\n * @param {MediaType} type\n * @param {object} mediaInfo\n * @memberOf module:DashAdapter\n * @instance\n * @ignore\n */\n function setCurrentMediaInfo(streamId, type, mediaInfo) {\n currentMediaInfo[streamId] = currentMediaInfo[streamId] || {};\n currentMediaInfo[streamId][type] = currentMediaInfo[streamId][type] || {};\n currentMediaInfo[streamId][type] = mediaInfo;\n }\n\n /**\n * Check if the given type is a text track\n * @param {object} adaptation\n * @returns {boolean}\n * @memberOf module:DashAdapter\n * @instance\n * @ignore\n */\n function getIsTextTrack(adaptation) {\n return dashManifestModel.getIsText(adaptation);\n }\n\n /**\n * Returns the UTC Timing Sources specified in the manifest\n * @returns {Array} utcTimingSources\n * @memberOf module:DashAdapter\n * @instance\n */\n function getUTCTimingSources() {\n const manifest = getManifest();\n return dashManifestModel.getUTCTimingSources(manifest);\n }\n\n /**\n * Returns the suggestedPresentationDelay as specified in the manifest\n * @returns {String} suggestedPresentationDelay\n * @memberOf module:DashAdapter\n * @instance\n */\n function getSuggestedPresentationDelay() {\n const mpd = voPeriods.length > 0 ? voPeriods[0].mpd : null;\n return dashManifestModel.getSuggestedPresentationDelay(mpd);\n }\n\n /**\n * Returns the availabilityStartTime as specified in the manifest\n * @param {object} externalManifest Omit this value if no external manifest should be used\n * @returns {string} availabilityStartTime\n * @memberOf module:DashAdapter\n * @instance\n */\n function getAvailabilityStartTime(externalManifest) {\n const mpd = getMpd(externalManifest);\n return dashManifestModel.getAvailabilityStartTime(mpd);\n }\n\n /**\n * Returns a boolean indicating if the manifest is dynamic or not\n * @param {object} externalManifest Omit this value if no external manifest should be used\n * @returns {boolean}\n * @memberOf module:DashAdapter\n * @instance\n */\n function getIsDynamic(externalManifest) {\n const manifest = getManifest(externalManifest);\n return dashManifestModel.getIsDynamic(manifest);\n }\n\n /**\n * Returns the duration of the MPD\n * @param {object} externalManifest Omit this value if no external manifest should be used\n * @returns {number} duration\n * @memberOf module:DashAdapter\n * @instance\n */\n function getDuration(externalManifest) {\n const manifest = getManifest(externalManifest);\n return dashManifestModel.getDuration(manifest);\n }\n\n /**\n * Returns all periods of the MPD\n * @param {object} externalManifest Omit this value if no external manifest should be used\n * @returns {Array} periods\n * @memberOf module:DashAdapter\n * @instance\n */\n function getRegularPeriods(externalManifest) {\n const mpd = getMpd(externalManifest);\n return dashManifestModel.getRegularPeriods(mpd);\n }\n\n /**\n * Returns an MPD object\n * @param {object} externalManifest Omit this value if no external manifest should be used\n * @returns {object} MPD\n * @memberOf module:DashAdapter\n * @instance\n */\n function getMpd(externalManifest) {\n const manifest = getManifest(externalManifest);\n return dashManifestModel.getMpd(manifest);\n }\n\n /**\n * Returns the location element of the MPD\n * @param {object} manifest\n * @returns {String} location\n * @memberOf module:DashAdapter\n * @instance\n */\n function getLocation(manifest) {\n return dashManifestModel.getLocation(manifest);\n }\n\n /**\n * Returns the manifest update period used for dynamic manifests\n * @param {object} manifest\n * @param {number} latencyOfLastUpdate\n * @returns {NaN|number} manifestUpdatePeriod\n * @memberOf module:DashAdapter\n * @instance\n */\n function getManifestUpdatePeriod(manifest, latencyOfLastUpdate = 0) {\n return dashManifestModel.getManifestUpdatePeriod(manifest, latencyOfLastUpdate);\n }\n\n /**\n * Returns the publish time from the manifest\n * @param {object} manifest\n * @returns {Date|null} publishTime\n * @memberOf module:DashAdapter\n * @instance\n */\n function getPublishTime(manifest) {\n return dashManifestModel.getPublishTime(manifest);\n }\n\n /**\n * Returns the patch location of the MPD if one exists and it is still valid\n * @param {object} manifest\n * @returns {(String|null)} patch location\n * @memberOf module:DashAdapter\n * @instance\n */\n function getPatchLocation(manifest) {\n const patchLocation = dashManifestModel.getPatchLocation(manifest);\n const publishTime = dashManifestModel.getPublishTime(manifest);\n\n // short-circuit when no patch location or publish time exists\n if (!patchLocation || !publishTime) {\n return null;\n }\n\n // if a ttl is provided, ensure patch location has not expired\n if (patchLocation.hasOwnProperty('ttl') && publishTime) {\n // attribute describes number of seconds as a double\n const ttl = parseFloat(patchLocation.ttl) * 1000;\n\n // check if the patch location has expired, if so do not consider it\n if (publishTime.getTime() + ttl <= new Date().getTime()) {\n return null;\n }\n }\n\n // the patch location exists and, if a ttl applies, has not expired\n return patchLocation.__text;\n }\n\n /**\n * Checks if the manifest has a DVB profile\n * @param {object} manifest\n * @returns {boolean}\n * @memberOf module:DashAdapter\n * @instance\n * @ignore\n */\n function getIsDVB(manifest) {\n return dashManifestModel.hasProfile(manifest, PROFILE_DVB);\n }\n\n /**\n * Checks if the manifest is actually just a patch manifest\n * @param {object} manifest\n * @return {boolean}\n */\n function getIsPatch(manifest) {\n return patchManifestModel.getIsPatch(manifest);\n }\n\n /**\n * Returns the base urls for a given element\n * @param {object} node\n * @returns {Array}\n * @memberOf module:DashAdapter\n * @instance\n * @ignore\n */\n function getBaseURLsFromElement(node) {\n return dashManifestModel.getBaseURLsFromElement(node);\n }\n\n /**\n * Returns the function to sort the Representations\n * @returns {*}\n * @memberOf module:DashAdapter\n * @instance\n * @ignore\n */\n function getRepresentationSortFunction() {\n return dashManifestModel.getRepresentationSortFunction();\n }\n\n /**\n * Returns the codec for a given adaptation set and a given representation id.\n * @param {object} adaptation\n * @param {number} representationId\n * @param {boolean} addResolutionInfo Defines whether to include resolution information in the output\n * @returns {String} codec\n * @memberOf module:DashAdapter\n * @instance\n */\n function getCodec(adaptation, representationId, addResolutionInfo) {\n return dashManifestModel.getCodec(adaptation, representationId, addResolutionInfo);\n }\n\n /**\n * Returns the bandwidth for a given representation id and the corresponding period index\n * @param {number} representationId\n * @param {number} periodIdx\n * @returns {number} bandwidth\n * @memberOf module:DashAdapter\n * @instance\n */\n function getBandwidthForRepresentation(representationId, periodIdx) {\n let representation;\n let period = getPeriod(periodIdx);\n\n representation = findRepresentation(period, representationId);\n\n return representation ? representation.bandwidth : null;\n }\n\n /**\n * Returns the index for a given representation id\n * @param {string} representationId\n * @param {number} periodIdx\n * @returns {number} index\n * @memberOf module:DashAdapter\n * @instance\n */\n function getIndexForRepresentation(representationId, periodIdx) {\n let period = getPeriod(periodIdx);\n\n return findRepresentationIndex(period, representationId);\n }\n\n /**\n * This method returns the current max index based on what is defined in the MPD.\n * @param {string} bufferType - String 'audio' or 'video',\n * @param {number} periodIdx - Make sure this is the period index not id\n * @return {number}\n * @memberof module:DashAdapter\n * @instance\n */\n function getMaxIndexForBufferType(bufferType, periodIdx) {\n let period = getPeriod(periodIdx);\n\n return findMaxBufferIndex(period, bufferType);\n }\n\n /**\n * Returns the voPeriod object for a given id\n * @param {String} id\n * @returns {object|null}\n */\n function getPeriodById(id) {\n if (!id || voPeriods.length === 0) {\n return null;\n }\n const periods = voPeriods.filter((p) => {\n return p.id === id;\n });\n\n if (periods && periods.length > 0) {\n return periods[0];\n }\n\n return null;\n }\n\n /**\n * Checks if the given AdaptationSet is from the given media type\n * @param {object} adaptation\n * @param {string} type\n * @return {boolean}\n */\n function getIsTypeOf(adaptation, type) {\n return dashManifestModel.getIsTypeOf(adaptation, type);\n }\n\n function reset() {\n voPeriods = [];\n currentMediaInfo = {};\n }\n\n /**\n * Checks if the supplied manifest is compatible for application of the supplied patch\n * @param {object} manifest\n * @param {object} patch\n * @return {boolean}\n */\n function isPatchValid(manifest, patch) {\n let manifestId = dashManifestModel.getId(manifest);\n let patchManifestId = patchManifestModel.getMpdId(patch);\n let manifestPublishTime = dashManifestModel.getPublishTime(manifest);\n let patchPublishTime = patchManifestModel.getPublishTime(patch);\n let originalManifestPublishTime = patchManifestModel.getOriginalPublishTime(patch);\n\n // Patches are considered compatible if the following are true\n // - MPD@id == Patch@mpdId\n // - MPD@publishTime == Patch@originalPublishTime\n // - MPD@publishTime < Patch@publishTime\n // - All values in comparison exist\n return !!(manifestId && patchManifestId && (manifestId == patchManifestId) &&\n manifestPublishTime && originalManifestPublishTime && (manifestPublishTime.getTime() == originalManifestPublishTime.getTime()) &&\n patchPublishTime && (manifestPublishTime.getTime() < patchPublishTime.getTime()));\n }\n\n /**\n * Takes a given patch and applies it to the provided manifest, assumes patch is valid for manifest\n * @param {object} manifest\n * @param {object} patch\n */\n function applyPatchToManifest(manifest, patch) {\n // get all operations from the patch and apply them in document order\n patchManifestModel.getPatchOperations(patch)\n .forEach((operation) => {\n let result = operation.getMpdTarget(manifest);\n\n // operation supplies a path that doesn't match mpd, skip\n if (result === null) {\n return;\n }\n\n let { name, target, leaf } = result;\n\n // short circuit for attribute selectors\n if (operation.xpath.findsAttribute()) {\n switch (operation.action) {\n case 'add':\n case 'replace':\n // add and replace are just setting the value\n target[name] = operation.value;\n break;\n case 'remove':\n // remove is deleting the value\n delete target[name];\n break;\n }\n return;\n }\n\n // determine the relative insert position prior to possible removal\n let relativePosition = (target[name + '_asArray'] || []).indexOf(leaf);\n let insertBefore = (operation.position === 'prepend' || operation.position === 'before');\n\n // perform removal operation first, we have already capture the appropriate relative position\n if (operation.action === 'remove' || operation.action === 'replace') {\n // note that we ignore the 'ws' attribute of patch operations as it does not effect parsed mpd operations\n\n // purge the directly named entity\n delete target[name];\n\n // if we did have a positional reference we need to purge from array set and restore X2JS proper semantics\n if (relativePosition != -1) {\n let targetArray = target[name + '_asArray'];\n targetArray.splice(relativePosition, 1);\n if (targetArray.length > 1) {\n target[name] = targetArray;\n } else if (targetArray.length == 1) {\n // xml parsing semantics, singular asArray must be non-array in the unsuffixed key\n target[name] = targetArray[0];\n } else {\n // all nodes of this type deleted, remove entry\n delete target[name + '_asArray'];\n }\n }\n }\n\n // Perform any add/replace operations now, technically RFC5261 only allows a single element to take the\n // place of a replaced element while the add case allows an arbitrary number of children.\n // Due to the both operations requiring the same insertion logic they have been combined here and we will\n // not enforce single child operations for replace, assertions should be made at patch parse time if necessary\n if (operation.action === 'add' || operation.action === 'replace') {\n // value will be an object with element name keys pointing to arrays of objects\n Object.keys(operation.value).forEach((insert) => {\n let insertNodes = operation.value[insert];\n\n let updatedNodes = target[insert + '_asArray'] || [];\n if (updatedNodes.length === 0 && target[insert]) {\n updatedNodes.push(target[insert]);\n }\n\n if (updatedNodes.length === 0) {\n // no original nodes for this element type\n updatedNodes = insertNodes;\n } else {\n // compute the position we need to insert at, default to end of set\n let position = updatedNodes.length;\n if (insert == name && relativePosition != -1) {\n // if the inserted element matches the operation target (not leaf) and there is a relative position we\n // want the inserted position to be set such that our insertion is relative to original position\n // since replace has modified the array length we reduce the insert point by 1\n position = relativePosition + (insertBefore ? 0 : 1) + (operation.action == 'replace' ? -1 : 0);\n } else {\n // otherwise we are in an add append/prepend case or replace case that removed the target name completely\n position = insertBefore ? 0 : updatedNodes.length;\n }\n\n // we dont have to perform element removal for the replace case as that was done above\n updatedNodes.splice.apply(updatedNodes, [position, 0].concat(insertNodes));\n }\n\n // now we properly reset the element keys on the target to match parsing semantics\n target[insert + '_asArray'] = updatedNodes;\n target[insert] = updatedNodes.length == 1 ? updatedNodes[0] : updatedNodes;\n });\n }\n });\n }\n\n // #endregion PUBLIC FUNCTIONS\n\n // #region PRIVATE FUNCTIONS\n // --------------------------------------------------\n function getManifest(externalManifest) {\n return externalManifest ? externalManifest : voPeriods.length > 0 ? voPeriods[0].mpd.manifest : null;\n }\n\n function getAdaptationForMediaInfo(mediaInfo) {\n try {\n const selectedVoPeriod = getPeriodForStreamInfo(mediaInfo.streamInfo, voPeriods);\n const voAdaptations = dashManifestModel.getAdaptationsForPeriod(selectedVoPeriod);\n\n if (!mediaInfo || !mediaInfo.streamInfo || mediaInfo.streamInfo.id === undefined || !voAdaptations) return null;\n return voAdaptations[mediaInfo.index];\n } catch (e) {\n return null;\n }\n }\n\n function getPeriodForStreamInfo(streamInfo, voPeriodsArray) {\n const ln = voPeriodsArray.length;\n\n for (let i = 0; i < ln; i++) {\n let voPeriod = voPeriodsArray[i];\n\n if (streamInfo && streamInfo.id === voPeriod.id) return voPeriod;\n }\n\n return null;\n }\n\n function convertAdaptationToMediaInfo(adaptation) {\n if (!adaptation) {\n return null;\n }\n\n let mediaInfo = new MediaInfo();\n const realAdaptation = adaptation.period.mpd.manifest.Period_asArray[adaptation.period.index].AdaptationSet_asArray[adaptation.index];\n let viewpoint;\n\n mediaInfo.id = adaptation.id;\n mediaInfo.index = adaptation.index;\n mediaInfo.type = adaptation.type;\n mediaInfo.streamInfo = convertPeriodToStreamInfo(adaptation.period);\n mediaInfo.representationCount = dashManifestModel.getRepresentationCount(realAdaptation);\n mediaInfo.labels = dashManifestModel.getLabelsForAdaptation(realAdaptation);\n mediaInfo.lang = dashManifestModel.getLanguageForAdaptation(realAdaptation);\n viewpoint = dashManifestModel.getViewpointForAdaptation(realAdaptation);\n mediaInfo.viewpoint = viewpoint ? viewpoint.value : undefined;\n mediaInfo.accessibility = dashManifestModel.getAccessibilityForAdaptation(realAdaptation).map(function (accessibility) {\n let accessibilityValue = accessibility.value;\n let accessibilityData = accessibilityValue;\n if (accessibility.schemeIdUri && (accessibility.schemeIdUri.search('cea-608') >= 0) && typeof (cea608parser) !== 'undefined') {\n if (accessibilityValue) {\n accessibilityData = 'cea-608:' + accessibilityValue;\n } else {\n accessibilityData = 'cea-608';\n }\n mediaInfo.embeddedCaptions = true;\n }\n return accessibilityData;\n });\n\n mediaInfo.audioChannelConfiguration = dashManifestModel.getAudioChannelConfigurationForAdaptation(realAdaptation).map(function (audioChannelConfiguration) {\n return audioChannelConfiguration.value;\n });\n\n if (mediaInfo.audioChannelConfiguration.length === 0 && Array.isArray(realAdaptation.Representation_asArray) && realAdaptation.Representation_asArray.length > 0) {\n mediaInfo.audioChannelConfiguration = dashManifestModel.getAudioChannelConfigurationForRepresentation(realAdaptation.Representation_asArray[0]).map(function (audioChannelConfiguration) {\n return audioChannelConfiguration.value;\n });\n }\n mediaInfo.roles = dashManifestModel.getRolesForAdaptation(realAdaptation).map(function (role) {\n return role.value;\n });\n mediaInfo.codec = dashManifestModel.getCodec(realAdaptation);\n mediaInfo.mimeType = dashManifestModel.getMimeType(realAdaptation);\n mediaInfo.contentProtection = dashManifestModel.getContentProtectionData(realAdaptation);\n mediaInfo.bitrateList = dashManifestModel.getBitrateListForAdaptation(realAdaptation);\n mediaInfo.selectionPriority = dashManifestModel.getSelectionPriority(realAdaptation);\n\n if (mediaInfo.contentProtection) {\n // Get the default key ID and apply it to all key systems\n const keyIds = mediaInfo.contentProtection.map(cp => dashManifestModel.getKID(cp)).filter(kid => kid !== null);\n if (keyIds.length) {\n const keyId = keyIds[0];\n mediaInfo.contentProtection.forEach(cp => { cp.keyId = keyId; });\n }\n }\n\n mediaInfo.isText = dashManifestModel.getIsText(realAdaptation);\n mediaInfo.supplementalProperties = dashManifestModel.getSupplementalProperties(realAdaptation);\n\n mediaInfo.isFragmented = dashManifestModel.getIsFragmented(realAdaptation);\n mediaInfo.isEmbedded = false;\n\n return mediaInfo;\n }\n\n function convertVideoInfoToEmbeddedTextInfo(mediaInfo, channel, lang) {\n mediaInfo.id = channel; // CC1, CC2, CC3, or CC4\n mediaInfo.index = 100 + parseInt(channel.substring(2, 3));\n mediaInfo.type = constants.TEXT;\n mediaInfo.codec = 'cea-608-in-SEI';\n mediaInfo.isEmbedded = true;\n mediaInfo.isFragmented = false;\n mediaInfo.lang = lang;\n mediaInfo.roles = ['caption'];\n }\n\n function convertVideoInfoToThumbnailInfo(mediaInfo) {\n mediaInfo.type = constants.IMAGE;\n }\n\n function convertPeriodToStreamInfo(period) {\n let streamInfo = new StreamInfo();\n const THRESHOLD = 1;\n\n streamInfo.id = period.id;\n streamInfo.index = period.index;\n streamInfo.start = period.start;\n streamInfo.duration = period.duration;\n streamInfo.manifestInfo = convertMpdToManifestInfo(period.mpd);\n streamInfo.isLast = period.mpd.manifest.Period_asArray.length === 1 || Math.abs((streamInfo.start + streamInfo.duration) - streamInfo.manifestInfo.duration) < THRESHOLD;\n\n return streamInfo;\n }\n\n function convertMpdToManifestInfo(mpd) {\n let manifestInfo = new ManifestInfo();\n\n manifestInfo.dvrWindowSize = mpd.timeShiftBufferDepth;\n manifestInfo.loadedTime = mpd.manifest.loadedTime;\n manifestInfo.availableFrom = mpd.availabilityStartTime;\n manifestInfo.minBufferTime = mpd.manifest.minBufferTime;\n manifestInfo.maxFragmentDuration = mpd.maxSegmentDuration;\n manifestInfo.duration = dashManifestModel.getDuration(mpd.manifest);\n manifestInfo.isDynamic = dashManifestModel.getIsDynamic(mpd.manifest);\n manifestInfo.serviceDescriptions = dashManifestModel.getServiceDescriptions(mpd.manifest);\n manifestInfo.protocol = mpd.manifest.protocol;\n\n return manifestInfo;\n }\n\n function checkConfig() {\n if (!constants) {\n throw new Error('setConfig function has to be called previously');\n }\n }\n\n function getPeriod(periodIdx) {\n return voPeriods.length > 0 ? voPeriods[0].mpd.manifest.Period_asArray[periodIdx] : null;\n }\n\n function findRepresentationIndex(period, representationId) {\n const index = findRepresentation(period, representationId, true);\n\n return index !== null ? index : -1;\n }\n\n function findRepresentation(period, representationId, returnIndex) {\n let adaptationSet,\n adaptationSetArray,\n representation,\n representationArray,\n adaptationSetArrayIndex,\n representationArrayIndex;\n\n if (period) {\n adaptationSetArray = period.AdaptationSet_asArray;\n for (adaptationSetArrayIndex = 0; adaptationSetArrayIndex < adaptationSetArray.length; adaptationSetArrayIndex = adaptationSetArrayIndex + 1) {\n adaptationSet = adaptationSetArray[adaptationSetArrayIndex];\n representationArray = adaptationSet.Representation_asArray;\n for (representationArrayIndex = 0; representationArrayIndex < representationArray.length; representationArrayIndex = representationArrayIndex + 1) {\n representation = representationArray[representationArrayIndex];\n if (representationId === representation.id) {\n if (returnIndex) {\n return representationArrayIndex;\n } else {\n return representation;\n }\n }\n }\n }\n }\n\n return null;\n }\n\n function findMaxBufferIndex(period, bufferType) {\n let adaptationSet,\n adaptationSetArray,\n representationArray,\n adaptationSetArrayIndex;\n\n if (!period || !bufferType) return -1;\n\n adaptationSetArray = period.AdaptationSet_asArray;\n for (adaptationSetArrayIndex = 0; adaptationSetArrayIndex < adaptationSetArray.length; adaptationSetArrayIndex = adaptationSetArrayIndex + 1) {\n adaptationSet = adaptationSetArray[adaptationSetArrayIndex];\n representationArray = adaptationSet.Representation_asArray;\n if (dashManifestModel.getIsTypeOf(adaptationSet, bufferType)) {\n return representationArray.length;\n }\n }\n\n return -1;\n }\n\n // #endregion PRIVATE FUNCTIONS\n\n instance = {\n getBandwidthForRepresentation,\n getIndexForRepresentation,\n getMaxIndexForBufferType,\n convertRepresentationToRepresentationInfo,\n getStreamsInfo,\n getMediaInfoForType,\n getAllMediaInfoForType,\n getAdaptationForType,\n getRealAdaptation,\n getRealPeriodByIndex,\n getEssentialPropertiesForRepresentation,\n getVoRepresentations,\n getEventsFor,\n getEvent,\n getMpd,\n setConfig,\n updatePeriods,\n getIsTextTrack,\n getUTCTimingSources,\n getSuggestedPresentationDelay,\n getAvailabilityStartTime,\n getIsTypeOf,\n getIsDynamic,\n getDuration,\n getRegularPeriods,\n getLocation,\n getPatchLocation,\n getManifestUpdatePeriod,\n getPublishTime,\n getIsDVB,\n getIsPatch,\n getBaseURLsFromElement,\n getRepresentationSortFunction,\n getCodec,\n getPeriodById,\n setCurrentMediaInfo,\n isPatchValid,\n applyPatchToManifest,\n areMediaInfosEqual,\n reset\n };\n\n setup();\n return instance;\n}\n\nDashAdapter.__dashjs_factory_name = 'DashAdapter';\nexport default FactoryMaker.getSingletonFactory(DashAdapter);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * Static methods for rounding decimals\n *\n * Modified version of the CC0-licenced example at:\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round\n *\n * @export\n * @class Round10\n * @ignore\n */\nexport default class Round10 {\n /**\n * Decimal round.\n *\n * @param {Number} value The number.\n * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base).\n * @returns {Number} The adjusted value.\n * @ignore\n */\n static round10(value, exp) {\n return _decimalAdjust('round', value, exp);\n }\n}\n\n/**\n * Decimal adjustment of a number.\n *\n * @param {String} type The type of adjustment.\n * @param {Number} value The number.\n * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base).\n * @returns {Number} The adjusted value.\n * @ignore\n */\nfunction _decimalAdjust(type, value, exp) {\n // If the exp is undefined or zero...\n if (typeof exp === 'undefined' || +exp === 0) {\n return Math[type](value);\n }\n\n value = +value;\n exp = +exp;\n\n // If the value is not a number or the exp is not an integer...\n if (value === null || isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {\n return NaN;\n }\n\n // Shift\n value = value.toString().split('e');\n value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));\n\n // Shift back\n value = value.toString().split('e');\n return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));\n}","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass MetricsList {\n constructor() {\n this.TcpList = [];\n this.HttpList = [];\n this.RepSwitchList = [];\n this.BufferLevel = [];\n this.BufferState = [];\n this.PlayList = [];\n this.DroppedFrames = [];\n this.SchedulingInfo = [];\n this.DVRInfo = [];\n this.ManifestUpdate = [];\n this.RequestsQueue = null;\n this.DVBErrors = [];\n }\n}\n\nexport default MetricsList;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass RepresentationSwitch {\n /**\n * @description This Object holds reference to the info at quality switch between two representations.\n */\n constructor() {\n\n /**\n * Time of the switch event.\n * @public\n */\n this.t = null;\n /**\n * The media presentation time of the earliest access unit\n * (out of all media content components) played out from\n * the Representation.\n *\n * @public\n */\n this.mt = null;\n /**\n * Value of Representation@id identifying the switch-to Representation.\n * @public\n */\n this.to = null;\n /**\n * If not present, this metrics concerns the Representation as a whole.\n * If present, lto indicates the value of SubRepresentation@level within\n * Representation identifying the switch-to level of the Representation.\n *\n * @public\n */\n this.lto = null;\n\n }\n}\n\nexport default RepresentationSwitch;","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * @class\n * @ignore\n */\nclass BufferLevel {\n /**\n * @description This Object holds reference to the current buffer level and the time it was recorded.\n */\n constructor() {\n /**\n * Real-Time | Time of the measurement of the buffer level.\n * @public\n */\n this.t = null;\n /**\n * Level of the buffer in milliseconds. Indicates the playout duration for which\n * media data of all active media components is available starting from the\n * current playout time.\n * @public\n */\n this.level = null;\n }\n}\n\nexport default BufferLevel;","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport MetricsConstants from '../../constants/MetricsConstants';\n\n/**\n * @class\n * @ignore\n */\nclass BufferState {\n /**\n * @description This Object holds reference to the current buffer state of the video element.\n */\n constructor() {\n /**\n * The Buffer Level Target determined by the BufferLevelRule.\n * @public\n */\n this.target = null;\n /**\n * Current buffer state. Will be MetricsConstants.BUFFER_EMPTY or MetricsConstants.BUFFER_LOADED.\n * @public\n */\n this.state = MetricsConstants.BUFFER_EMPTY;\n }\n}\n\nexport default BufferState;","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * @class\n * @ignore\n */\nclass DVRInfo {\n /**\n * @description This Object holds reference to DVR availability window information.\n */\n constructor() {\n\n /**\n * The current time of the video element when this was created.\n * @public\n */\n this.time = null;\n /**\n * The current Segment Availability Range as an object with start and end properties.\n * It's delta defined by the timeShiftBufferDepth MPD attribute.\n * @public\n */\n this.range = null;\n /**\n * Reference to the internal ManifestInfo.js VO.\n * @public\n */\n this.manifestInfo = null;\n }\n}\n\nexport default DVRInfo;","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass DroppedFrames {\n /**\n * @description This Object holds reference to DroppedFrames count and the time it was recorded.\n */\n constructor()\n {\n /**\n * Real-Time | Time of the measurement of the dropped frames.\n * @public\n */\n this.time = null;\n /**\n * Number of dropped frames\n * @public\n */\n this.droppedFrames = null;\n }\n}\n\nexport default DroppedFrames;","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @classdesc This Object holds reference to the manifest update information.\n * @ignore\n */\nclass ManifestUpdate {\n /**\n * @class\n */\n constructor() {\n\n /**\n * Media Type Video | Audio | FragmentedText\n * @public\n */\n this.mediaType = null;\n /**\n * MPD Type static | dynamic\n * @public\n */\n this.type = null;\n /**\n * When this manifest update was requested\n * @public\n */\n this.requestTime = null;\n /**\n * When this manifest update was received\n * @public\n */\n this.fetchTime = null;\n /**\n * Calculated Availability Start time of the stream.\n * @public\n */\n this.availabilityStartTime = null;\n /**\n * the seek point (liveEdge for dynamic, Stream[0].startTime for static)\n * @public\n */\n this.presentationStartTime = 0;\n /**\n * The calculated difference between the server and client wall clock time\n * @public\n */\n this.clientTimeOffset = 0;\n /**\n * Actual element.currentTime\n * @public\n */\n this.currentTime = null;\n /**\n * Actual element.ranges\n * @public\n */\n this.buffered = null;\n /**\n * Static is fixed value of zero. dynamic should be ((Now-@availabilityStartTime) - elementCurrentTime)\n * @public\n */\n this.latency = 0;\n /**\n * Array holding list of StreamInfo VO Objects\n * @public\n */\n this.streamInfo = [];\n /**\n * Array holding list of RepresentationInfo VO Objects\n * @public\n */\n this.representationInfo = [];\n\n }\n}\n\n/**\n * @classdesc This Object holds reference to the current period's stream information when the manifest was updated.\n * @ignore\n */\nclass ManifestUpdateStreamInfo {\n /**\n * @class\n */\n constructor() {\n /**\n * Stream@id\n * @public\n */\n this.id = null;\n /**\n * Period Index\n * @public\n */\n this.index = null;\n /**\n * Stream@start\n * @public\n */\n this.start = null;\n /**\n * Stream@duration\n * @public\n */\n this.duration = null;\n }\n}\n\n/**\n * @classdesc This Object holds reference to the current representation's info when the manifest was updated.\n * @ignore\n */\nclass ManifestUpdateRepresentationInfo {\n /**\n * @class\n */\n constructor() {\n /**\n * Track@id\n * @public\n */\n this.id = null;\n /**\n * Representation Index\n * @public\n */\n this.index = null;\n /**\n * Media Type Video | Audio | FragmentedText\n * @public\n */\n this.mediaType = null;\n /**\n * Which representation\n * @public\n */\n this.streamIndex = null;\n /**\n * Holds reference to @presentationTimeOffset\n * @public\n */\n this.presentationTimeOffset = null;\n /**\n * Holds reference to @startNumber\n * @public\n */\n this.startNumber = null;\n /**\n * list|template|timeline\n * @public\n */\n this.fragmentInfoType = null;\n }\n}\n\nexport { ManifestUpdate, ManifestUpdateStreamInfo, ManifestUpdateRepresentationInfo };\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass SchedulingInfo {\n /**\n * @description This Object holds reference to the index handling of the current fragment being loaded or executed.\n */\n constructor() {\n\n /**\n * Type of stream Audio | Video | FragmentedText\n * @public\n */\n this.mediaType = null;\n /**\n * Time of the scheduling event.\n * @public\n */\n this.t = null;\n\n /**\n * Type of fragment (initialization | media)\n * @public\n */\n this.type = null;\n /**\n * Presentation start time of fragment\n * @public\n */\n this.startTime = null;\n /**\n * Availability start time of fragment\n * @public\n */\n this.availabilityStartTime = null;\n /**\n * Duration of fragment\n * @public\n */\n this.duration = null;\n /**\n * Bit Rate Quality of fragment\n * @public\n */\n this.quality = null;\n /**\n * Range of fragment\n * @public\n */\n this.range = null;\n\n /**\n * Current state of fragment\n * @public\n */\n this.state = null;\n }\n}\n\nexport default SchedulingInfo;","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass RequestsQueue {\n /**\n * @description This Object holds reference to Fragment Model's request queues\n */\n constructor() {\n\n /**\n * Array of all of the requests that have begun to load\n * This request may not make it into the executed queue if it is abandon due to ABR rules for example.\n * @public\n */\n this.loadingRequests = [];\n /**\n * Array of the The requests that have completed\n * @public\n */\n this.executedRequests = [];\n }\n}\n\nexport default RequestsQueue;","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Constants from '../constants/Constants';\nimport MetricsConstants from '../constants/MetricsConstants';\nimport MetricsList from '../vo/MetricsList';\nimport {HTTPRequest, HTTPRequestTrace} from '../vo/metrics/HTTPRequest';\nimport TrackSwitch from '../vo/metrics/RepresentationSwitch';\nimport BufferLevel from '../vo/metrics/BufferLevel';\nimport BufferState from '../vo/metrics/BufferState';\nimport DVRInfo from '../vo/metrics/DVRInfo';\nimport DroppedFrames from '../vo/metrics/DroppedFrames';\nimport {ManifestUpdate, ManifestUpdateStreamInfo, ManifestUpdateRepresentationInfo} from '../vo/metrics/ManifestUpdate';\nimport SchedulingInfo from '../vo/metrics/SchedulingInfo';\nimport EventBus from '../../core/EventBus';\nimport RequestsQueue from '../vo/metrics/RequestsQueue';\nimport Events from '../../core/events/Events';\nimport FactoryMaker from '../../core/FactoryMaker';\n\nfunction MetricsModel(config) {\n\n config = config || {};\n\n const settings = config.settings;\n\n let context = this.context;\n let eventBus = EventBus(context).getInstance();\n\n let instance,\n streamMetrics;\n\n function setup() {\n streamMetrics = {};\n }\n\n function metricsChanged() {\n eventBus.trigger(Events.METRICS_CHANGED);\n }\n\n function metricChanged(mediaType) {\n eventBus.trigger(Events.METRIC_CHANGED, { mediaType: mediaType });\n metricsChanged();\n }\n\n function metricUpdated(mediaType, metricType, vo) {\n eventBus.trigger(Events.METRIC_UPDATED, { mediaType: mediaType, metric: metricType, value: vo });\n metricChanged(mediaType);\n }\n\n function metricAdded(mediaType, metricType, vo) {\n eventBus.trigger(Events.METRIC_ADDED, { mediaType: mediaType, metric: metricType, value: vo });\n metricChanged(mediaType);\n }\n\n function clearCurrentMetricsForType(type) {\n delete streamMetrics[type];\n metricChanged(type);\n }\n\n function clearAllCurrentMetrics() {\n streamMetrics = {};\n metricsChanged();\n }\n\n function getMetricsFor(type, readOnly) {\n let metrics = null;\n\n if (!type) {\n return metrics;\n }\n\n if (streamMetrics.hasOwnProperty(type)) {\n metrics = streamMetrics[type];\n } else if (!readOnly) {\n metrics = new MetricsList();\n streamMetrics[type] = metrics;\n }\n\n return metrics;\n }\n\n function pushMetrics(type, list, value) {\n let metrics = getMetricsFor(type);\n if (metrics !== null) {\n metrics[list].push(value);\n if (metrics[list].length > settings.get().streaming.metrics.maxListDepth) {\n metrics[list].shift();\n }\n }\n }\n\n function appendHttpTrace(httpRequest, s, d, b, t) {\n let vo = new HTTPRequestTrace();\n\n vo.s = s;\n vo.d = d;\n vo.b = b;\n vo.t = t;\n\n httpRequest.trace.push(vo);\n\n if (!httpRequest.interval) {\n httpRequest.interval = 0;\n }\n\n httpRequest.interval += d;\n\n return vo;\n }\n\n function addHttpRequest(mediaType, tcpid, type, url, quality, actualurl, serviceLocation, range, trequest, tresponse, tfinish, responsecode, mediaduration, responseHeaders, traces) {\n let vo = new HTTPRequest();\n\n // ISO 23009-1 D.4.3 NOTE 2:\n // All entries for a given object will have the same URL and range\n // and so can easily be correlated. If there were redirects or\n // failures there will be one entry for each redirect/failure.\n // The redirect-to URL or alternative url (where multiple have been\n // provided in the MPD) will appear as the actualurl of the next\n // entry with the same url value.\n if (actualurl && (actualurl !== url)) {\n\n // given the above, add an entry for the original request\n addHttpRequest(\n mediaType,\n null,\n type,\n url,\n quality,\n null,\n null,\n range,\n trequest,\n null, // unknown\n null, // unknown\n null, // unknown, probably a 302\n mediaduration,\n null,\n null\n );\n\n vo.actualurl = actualurl;\n }\n\n vo.tcpid = tcpid;\n vo.type = type;\n vo.url = url;\n vo.range = range;\n vo.trequest = trequest;\n vo.tresponse = tresponse;\n vo.responsecode = responsecode;\n\n vo._tfinish = tfinish;\n vo._stream = mediaType;\n vo._mediaduration = mediaduration;\n vo._quality = quality;\n vo._responseHeaders = responseHeaders;\n vo._serviceLocation = serviceLocation;\n\n if (traces) {\n traces.forEach(trace => {\n appendHttpTrace(vo, trace.s, trace.d, trace.b, trace.t);\n });\n } else {\n // The interval and trace shall be absent for redirect and failure records.\n delete vo.interval;\n delete vo.trace;\n }\n\n pushAndNotify(mediaType, MetricsConstants.HTTP_REQUEST, vo);\n }\n\n function addRepresentationSwitch(mediaType, t, mt, to, lto) {\n let vo = new TrackSwitch();\n\n vo.t = t;\n vo.mt = mt;\n vo.to = to;\n\n if (lto) {\n vo.lto = lto;\n } else {\n delete vo.lto;\n }\n\n pushAndNotify(mediaType, MetricsConstants.TRACK_SWITCH, vo);\n }\n\n function pushAndNotify(mediaType, metricType, metricObject) {\n pushMetrics(mediaType, metricType, metricObject);\n metricAdded(mediaType, metricType, metricObject);\n }\n\n function addBufferLevel(mediaType, t, level) {\n let vo = new BufferLevel();\n vo.t = t;\n vo.level = level;\n\n pushAndNotify(mediaType, MetricsConstants.BUFFER_LEVEL, vo);\n }\n\n function addBufferState(mediaType, state, target) {\n let vo = new BufferState();\n vo.target = target;\n vo.state = state;\n\n pushAndNotify(mediaType, MetricsConstants.BUFFER_STATE, vo);\n }\n\n function addDVRInfo(mediaType, currentTime, mpd, range) {\n let vo = new DVRInfo();\n vo.time = currentTime;\n vo.range = range;\n vo.manifestInfo = mpd;\n\n pushAndNotify(mediaType, MetricsConstants.DVR_INFO, vo);\n }\n\n function addDroppedFrames(mediaType, quality) {\n let vo = new DroppedFrames();\n let list = getMetricsFor(mediaType).DroppedFrames;\n\n if (!quality) {\n return;\n }\n\n vo.time = quality.creationTime;\n vo.droppedFrames = quality.droppedVideoFrames;\n\n if (list.length > 0 && list[list.length - 1] == vo) {\n return;\n }\n\n pushAndNotify(mediaType, MetricsConstants.DROPPED_FRAMES, vo);\n }\n\n function addSchedulingInfo(mediaType, t, type, startTime, availabilityStartTime, duration, quality, range, state) {\n let vo = new SchedulingInfo();\n\n vo.mediaType = mediaType;\n vo.t = t;\n\n vo.type = type;\n vo.startTime = startTime;\n vo.availabilityStartTime = availabilityStartTime;\n vo.duration = duration;\n vo.quality = quality;\n vo.range = range;\n\n vo.state = state;\n\n pushAndNotify(mediaType, MetricsConstants.SCHEDULING_INFO, vo);\n }\n\n function addRequestsQueue(mediaType, loadingRequests, executedRequests) {\n let vo = new RequestsQueue();\n\n vo.loadingRequests = loadingRequests;\n vo.executedRequests = executedRequests;\n\n getMetricsFor(mediaType).RequestsQueue = vo;\n metricAdded(mediaType, MetricsConstants.REQUESTS_QUEUE, vo);\n }\n\n function addManifestUpdate(mediaType, type, requestTime, fetchTime, availabilityStartTime, presentationStartTime, clientTimeOffset, currentTime, buffered, latency) {\n let vo = new ManifestUpdate();\n\n vo.mediaType = mediaType;\n vo.type = type;\n vo.requestTime = requestTime; // when this manifest update was requested\n vo.fetchTime = fetchTime; // when this manifest update was received\n vo.availabilityStartTime = availabilityStartTime;\n vo.presentationStartTime = presentationStartTime; // the seek point (liveEdge for dynamic, Stream[0].startTime for static)\n vo.clientTimeOffset = clientTimeOffset; // the calculated difference between the server and client wall clock time\n vo.currentTime = currentTime; // actual element.currentTime\n vo.buffered = buffered; // actual element.ranges\n vo.latency = latency; // (static is fixed value of zero. dynamic should be ((Now-@availabilityStartTime) - currentTime)\n\n pushMetrics(Constants.STREAM, MetricsConstants.MANIFEST_UPDATE, vo);\n metricAdded(mediaType, MetricsConstants.MANIFEST_UPDATE, vo);\n }\n\n function updateManifestUpdateInfo(manifestUpdate, updatedFields) {\n if (manifestUpdate) {\n for (let field in updatedFields) {\n manifestUpdate[field] = updatedFields[field];\n }\n\n metricUpdated(manifestUpdate.mediaType, MetricsConstants.MANIFEST_UPDATE, manifestUpdate);\n }\n }\n\n function addManifestUpdateStreamInfo(manifestUpdate, id, index, start, duration) {\n if (manifestUpdate) {\n let vo = new ManifestUpdateStreamInfo();\n\n vo.id = id;\n vo.index = index;\n vo.start = start;\n vo.duration = duration;\n\n manifestUpdate.streamInfo.push(vo);\n metricUpdated(manifestUpdate.mediaType, MetricsConstants.MANIFEST_UPDATE_STREAM_INFO, manifestUpdate);\n }\n }\n\n function addManifestUpdateRepresentationInfo(manifestUpdate, id, index, streamIndex, mediaType, presentationTimeOffset, startNumber, fragmentInfoType) {\n if (manifestUpdate && manifestUpdate.representationInfo) {\n\n const vo = new ManifestUpdateRepresentationInfo();\n vo.id = id;\n vo.index = index;\n vo.streamIndex = streamIndex;\n vo.mediaType = mediaType;\n vo.startNumber = startNumber;\n vo.fragmentInfoType = fragmentInfoType;\n vo.presentationTimeOffset = presentationTimeOffset;\n\n manifestUpdate.representationInfo.push(vo);\n metricUpdated(manifestUpdate.mediaType, MetricsConstants.MANIFEST_UPDATE_TRACK_INFO, manifestUpdate);\n }\n }\n\n function addPlayList(vo) {\n if (vo.trace && Array.isArray(vo.trace)) {\n vo.trace.forEach(trace => {\n if (trace.hasOwnProperty('subreplevel') && !trace.subreplevel) {\n delete trace.subreplevel;\n }\n });\n } else {\n delete vo.trace;\n }\n\n pushAndNotify(Constants.STREAM, MetricsConstants.PLAY_LIST, vo);\n }\n\n function addDVBErrors(vo) {\n pushAndNotify(Constants.STREAM, MetricsConstants.DVB_ERRORS, vo);\n }\n\n instance = {\n clearCurrentMetricsForType: clearCurrentMetricsForType,\n clearAllCurrentMetrics: clearAllCurrentMetrics,\n getMetricsFor: getMetricsFor,\n addHttpRequest: addHttpRequest,\n addRepresentationSwitch: addRepresentationSwitch,\n addBufferLevel: addBufferLevel,\n addBufferState: addBufferState,\n addDVRInfo: addDVRInfo,\n addDroppedFrames: addDroppedFrames,\n addSchedulingInfo: addSchedulingInfo,\n addRequestsQueue: addRequestsQueue,\n addManifestUpdate: addManifestUpdate,\n updateManifestUpdateInfo: updateManifestUpdateInfo,\n addManifestUpdateStreamInfo: addManifestUpdateStreamInfo,\n addManifestUpdateRepresentationInfo: addManifestUpdateRepresentationInfo,\n addPlayList: addPlayList,\n addDVBErrors: addDVBErrors\n };\n\n setup();\n return instance;\n}\n\nMetricsModel.__dashjs_factory_name = 'MetricsModel';\nexport default FactoryMaker.getSingletonFactory(MetricsModel);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Constants from '../streaming/constants/Constants';\nimport { HTTPRequest } from '../streaming/vo/metrics/HTTPRequest';\nimport FactoryMaker from '../core/FactoryMaker';\nimport MetricsConstants from '../streaming/constants/MetricsConstants';\nimport Round10 from './utils/Round10';\nimport MetricsModel from '../streaming/models/MetricsModel';\nimport Utils from '../core/Utils';\nimport {\n PlayList,\n PlayListTrace\n} from '../streaming/vo/metrics/PlayList';\n\n/**\n * @module DashMetrics\n * @description The DashMetrics module can be accessed using the MediaPlayer API getDashMetrics()\n * @param {object} config\n */\n\nfunction DashMetrics(config) {\n\n config = config || {};\n\n const context = this.context;\n let instance,\n playListTraceMetricsClosed,\n playListTraceMetrics,\n playListMetrics;\n\n let metricsModel = config.metricsModel;\n\n function setup() {\n metricsModel = metricsModel || MetricsModel(context).getInstance({settings: config.settings});\n resetInitialSettings();\n }\n\n function resetInitialSettings() {\n playListTraceMetricsClosed = true;\n playListTraceMetrics = null;\n playListMetrics = null;\n }\n\n /**\n * Returns the latest Representation switch for a given media type\n * @param {MediaType} mediaType\n * @returns {*}\n * @memberof module:DashMetrics\n * @instance\n */\n function getCurrentRepresentationSwitch(mediaType) {\n const metrics = metricsModel.getMetricsFor(mediaType, true);\n return getCurrent(metrics, MetricsConstants.TRACK_SWITCH);\n }\n\n /**\n * @param {MediaType} mediaType\n * @param {Date} t time of the switch event\n * @param {Date} mt media presentation time\n * @param {string} to id of representation\n * @param {string} lto if present, subrepresentation reference\n * @memberof module:DashMetrics\n * @instance\n * @ignore\n */\n function addRepresentationSwitch(mediaType, t, mt, to, lto) {\n metricsModel.addRepresentationSwitch(mediaType, t, mt, to, lto);\n }\n\n /**\n * Returns the current buffer state for a given media type\n * @param {MediaType} mediaType\n * @returns {number}\n * @memberof module:DashMetrics\n * @instance\n */\n function getCurrentBufferState(mediaType) {\n const metrics = metricsModel.getMetricsFor(mediaType, true);\n return getCurrent(metrics, MetricsConstants.BUFFER_STATE);\n }\n\n /**\n * Returns the current buffer level for a given media type\n * @param {MediaType} mediaType\n * @returns {number}\n * @memberof module:DashMetrics\n * @instance\n */\n function getCurrentBufferLevel(mediaType) {\n const metrics = metricsModel.getMetricsFor(mediaType, true);\n const metric = getCurrent(metrics, MetricsConstants.BUFFER_LEVEL);\n\n if (metric) {\n return Round10.round10(metric.level / 1000, -3);\n }\n\n return 0;\n }\n\n /**\n * @param {MediaType} mediaType\n * @param {number} t\n * @param {number} level\n * @memberof module:DashMetrics\n * @instance\n * @ignore\n */\n function addBufferLevel(mediaType, t, level) {\n metricsModel.addBufferLevel(mediaType, t, level);\n }\n\n /**\n * @param {MediaType} mediaType\n * @param {string} state\n * @param {number} target\n * @memberof module:DashMetrics\n * @instance\n * @ignore\n */\n function addBufferState(mediaType, state, target) {\n metricsModel.addBufferState(mediaType, state, target);\n }\n\n /**\n * @memberof module:DashMetrics\n * @instance\n * @ignore\n */\n function clearAllCurrentMetrics () {\n metricsModel.clearAllCurrentMetrics();\n }\n\n /**\n * Returns the latest HTTP request for a given media type\n * @param {MediaType} mediaType\n * @returns {*}\n * @memberof module:DashMetrics\n * @instance\n */\n function getCurrentHttpRequest(mediaType) {\n const metrics = metricsModel.getMetricsFor(mediaType, true);\n\n if (!metrics) {\n return null;\n }\n\n const httpList = metrics.HttpList;\n let currentHttpList = null;\n\n let httpListLastIndex;\n\n if (!httpList || httpList.length <= 0) {\n return null;\n }\n\n httpListLastIndex = httpList.length - 1;\n\n while (httpListLastIndex >= 0) {\n if (httpList[httpListLastIndex].responsecode) {\n currentHttpList = httpList[httpListLastIndex];\n break;\n }\n httpListLastIndex--;\n }\n return currentHttpList;\n }\n\n /**\n * Returns all HTTP requests for a given media type\n * @param {MediaType} mediaType\n * @returns {*}\n * @memberof module:DashMetrics\n * @instance\n */\n function getHttpRequests(mediaType) {\n const metrics = metricsModel.getMetricsFor(mediaType, true);\n if (!metrics) {\n return [];\n }\n\n return !!metrics.HttpList ? metrics.HttpList : [];\n }\n\n /**\n * @param {MediaType} mediaType\n * @param {Array} loadingRequests\n * @param {Array} executedRequests\n * @memberof module:DashMetrics\n * @instance\n * @ignore\n */\n function addRequestsQueue(mediaType, loadingRequests, executedRequests) {\n metricsModel.addRequestsQueue(mediaType, loadingRequests, executedRequests);\n }\n\n /**\n * Returns the latest metrics for a given metric list and specific metric name\n * @param {MetricsList} metrics\n * @param {string} metricName\n * @returns {*}\n * @memberof module:DashMetrics\n * @instance\n */\n function getCurrent(metrics, metricName) {\n if (!metrics) {\n return null;\n }\n const list = metrics[metricName];\n return (!list || list.length === 0) ? null : list[list.length - 1];\n }\n\n /**\n * Returns the number of dropped frames\n * @returns {*}\n * @memberof module:DashMetrics\n * @instance\n */\n function getCurrentDroppedFrames() {\n const metrics = metricsModel.getMetricsFor(Constants.VIDEO, true);\n return getCurrent(metrics, MetricsConstants.DROPPED_FRAMES);\n }\n\n /**\n * @param {number} quality\n * @memberof module:DashMetrics\n * @instance\n * @ignore\n */\n function addDroppedFrames(quality) {\n metricsModel.addDroppedFrames(Constants.VIDEO, quality);\n }\n\n /**\n * Returns the current scheduling info for a given media type\n * @param {MediaType} mediaType\n * @returns {*}\n * @memberof module:DashMetrics\n * @instance\n */\n function getCurrentSchedulingInfo(mediaType) {\n const metrics = metricsModel.getMetricsFor(mediaType, true);\n return getCurrent(metrics, MetricsConstants.SCHEDULING_INFO);\n }\n\n /**\n * @param {object} request\n * @param {string} state\n * @memberof module:DashMetrics\n * @instance\n * @ignore\n */\n function addSchedulingInfo(request, state) {\n metricsModel.addSchedulingInfo(\n request.mediaType,\n new Date(),\n request.type,\n request.startTime,\n request.availabilityStartTime,\n request.duration,\n request.quality,\n request.range,\n state);\n }\n\n /**\n * Returns the current manifest update information\n * @returns {*}\n * @memberof module:DashMetrics\n * @instance\n */\n function getCurrentManifestUpdate() {\n const streamMetrics = metricsModel.getMetricsFor(Constants.STREAM);\n return getCurrent(streamMetrics, MetricsConstants.MANIFEST_UPDATE);\n }\n\n /**\n * @param {object} updatedFields fields to be updated\n * @memberof module:DashMetrics\n * @instance\n * @ignore\n */\n function updateManifestUpdateInfo(updatedFields) {\n const manifestUpdate = this.getCurrentManifestUpdate();\n metricsModel.updateManifestUpdateInfo(manifestUpdate, updatedFields);\n }\n\n /**\n * @param {object} streamInfo\n * @memberof module:DashMetrics\n * @instance\n * @ignore\n */\n function addManifestUpdateStreamInfo(streamInfo) {\n if (streamInfo) {\n const manifestUpdate = this.getCurrentManifestUpdate();\n metricsModel.addManifestUpdateStreamInfo(manifestUpdate, streamInfo.id, streamInfo.index, streamInfo.start, streamInfo.duration);\n }\n }\n\n /**\n * @param {object} request\n * @memberof module:DashMetrics\n * @instance\n * @ignore\n */\n function addManifestUpdate(request) {\n metricsModel.addManifestUpdate(Constants.STREAM, request.type, request.requestStartDate, request.requestEndDate);\n }\n\n /**\n * @param {object} request\n * @param {string} responseURL\n * @param {number} responseStatus\n * @param {object} responseHeaders\n * @param {object} traces\n * @memberof module:DashMetrics\n * @instance\n * @ignore\n */\n function addHttpRequest(request, responseURL, responseStatus, responseHeaders, traces) {\n metricsModel.addHttpRequest(request.mediaType,\n null,\n request.type,\n request.url,\n request.quality,\n responseURL,\n request.serviceLocation || null,\n request.range || null,\n request.requestStartDate,\n request.firstByteDate,\n request.requestEndDate,\n responseStatus,\n request.duration,\n responseHeaders,\n traces);\n }\n\n /**\n * @param {object} representation\n * @param {MediaType} mediaType\n * @memberof module:DashMetrics\n * @instance\n * @ignore\n */\n function addManifestUpdateRepresentationInfo(representation, mediaType) {\n if (representation) {\n const manifestUpdateInfo = this.getCurrentManifestUpdate();\n metricsModel.addManifestUpdateRepresentationInfo(manifestUpdateInfo, representation.id, representation.index, representation.streamIndex, mediaType, representation.presentationTimeOffset, representation.startNumber, representation.fragmentInfoType);\n }\n }\n\n /**\n * Returns the current DVR window\n * @param {MediaType} mediaType\n * @returns {*}\n * @memberof module:DashMetrics\n * @instance\n */\n function getCurrentDVRInfo(mediaType) {\n const metrics = mediaType ? metricsModel.getMetricsFor(mediaType, true) :\n metricsModel.getMetricsFor(Constants.VIDEO, true) || metricsModel.getMetricsFor(Constants.AUDIO, true);\n return getCurrent(metrics, MetricsConstants.DVR_INFO);\n }\n\n /**\n * @param {MediaType} mediaType\n * @param {Date} currentTime time of the switch event\n * @param {object} mpd mpd reference\n * @param {object} range range of the dvr info\n * @memberof module:DashMetrics\n * @instance\n * @ignore\n */\n function addDVRInfo(mediaType, currentTime, mpd, range) {\n metricsModel.addDVRInfo(mediaType, currentTime, mpd, range);\n }\n\n /**\n * Returns the value for a specific request headers used in the latest MPD request\n * @param {string} id\n * @returns {*}\n * @memberof module:DashMetrics\n * @instance\n */\n function getLatestMPDRequestHeaderValueByID(id) {\n if (!id) {\n return null;\n }\n\n let headers = {};\n let httpRequestList,\n httpRequest,\n i;\n\n httpRequestList = getHttpRequests(Constants.STREAM);\n\n for (i = httpRequestList.length - 1; i >= 0; i--) {\n httpRequest = httpRequestList[i];\n\n if (httpRequest.type === HTTPRequest.MPD_TYPE) {\n headers = Utils.parseHttpHeaders(httpRequest._responseHeaders);\n break;\n }\n }\n\n const value = headers[id.toLowerCase()];\n return value === undefined ? null : value;\n }\n\n /**\n * Returns the value for a specific request headers used in the latest fragment request\n * @param {MediaType} mediaType\n * @param {string} id\n * @returns {*}\n * @memberof module:DashMetrics\n * @instance\n */\n function getLatestFragmentRequestHeaderValueByID(mediaType, id) {\n if (!id) {\n return null;\n }\n\n let headers = {};\n let httpRequest = getCurrentHttpRequest(mediaType);\n if (httpRequest) {\n headers = Utils.parseHttpHeaders(httpRequest._responseHeaders);\n }\n\n const value = headers[id.toLowerCase()];\n return value === undefined ? null : value;\n }\n\n /**\n * @memberof module:DashMetrics\n * @instance\n * @ignore\n */\n function addPlayList() {\n if (playListMetrics) {\n metricsModel.addPlayList(playListMetrics);\n playListMetrics = null;\n }\n }\n\n /**\n * Create a new playlist metric\n * @param {number} mediaStartTime\n * @param {string} startReason\n * @ignore\n */\n function createPlaylistMetrics(mediaStartTime, startReason) {\n playListMetrics = new PlayList();\n\n playListMetrics.start = new Date();\n playListMetrics.mstart = mediaStartTime;\n playListMetrics.starttype = startReason;\n }\n\n /**\n * Create a playlist trace metric\n * @param {number} representationId\n * @param {number} mediaStartTime\n * @param {number} speed\n * @ignore\n */\n function createPlaylistTraceMetrics(representationId, mediaStartTime, speed) {\n if (playListTraceMetricsClosed === true ) {\n playListTraceMetricsClosed = false;\n playListTraceMetrics = new PlayListTrace();\n\n playListTraceMetrics.representationid = representationId;\n playListTraceMetrics.start = new Date();\n playListTraceMetrics.mstart = mediaStartTime;\n playListTraceMetrics.playbackspeed = speed !== null ? speed.toString() : null;\n }\n }\n\n /**\n * Update existing playlist trace metric\n * @param {object} traceToUpdate\n * @ignore\n */\n function updatePlayListTraceMetrics(traceToUpdate) {\n if (playListTraceMetrics) {\n for (let field in playListTraceMetrics) {\n playListTraceMetrics[field] = traceToUpdate[field];\n }\n }\n }\n\n /**\n * Push a new playlist trace metric\n * @param endTime\n * @param reason\n * @ignore\n */\n function pushPlayListTraceMetrics(endTime, reason) {\n if (playListTraceMetricsClosed === false && playListMetrics && playListTraceMetrics && playListTraceMetrics.start) {\n const startTime = playListTraceMetrics.start;\n const duration = endTime.getTime() - startTime.getTime();\n playListTraceMetrics.duration = duration;\n playListTraceMetrics.stopreason = reason;\n playListMetrics.trace.push(playListTraceMetrics);\n playListTraceMetricsClosed = true;\n }\n }\n\n /**\n * @param {object} errors\n * @memberof module:DashMetrics\n * @instance\n * @ignore\n */\n function addDVBErrors(errors) {\n metricsModel.addDVBErrors(errors);\n }\n\n instance = {\n getCurrentRepresentationSwitch,\n getCurrentBufferState,\n getCurrentBufferLevel,\n getCurrentHttpRequest,\n getHttpRequests,\n getCurrentDroppedFrames,\n getCurrentSchedulingInfo,\n getCurrentDVRInfo,\n getCurrentManifestUpdate,\n getLatestFragmentRequestHeaderValueByID,\n getLatestMPDRequestHeaderValueByID,\n addRepresentationSwitch,\n addDVRInfo,\n updateManifestUpdateInfo,\n addManifestUpdateStreamInfo,\n addManifestUpdateRepresentationInfo,\n addManifestUpdate,\n addHttpRequest,\n addSchedulingInfo,\n addRequestsQueue,\n addBufferLevel,\n addBufferState,\n addDroppedFrames,\n addPlayList,\n addDVBErrors,\n createPlaylistMetrics,\n createPlaylistTraceMetrics,\n updatePlayListTraceMetrics,\n pushPlayListTraceMetrics,\n clearAllCurrentMetrics\n };\n\n setup();\n\n return instance;\n}\n\nDashMetrics.__dashjs_factory_name = 'DashMetrics';\nexport default FactoryMaker.getSingletonFactory(DashMetrics);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport DashConstants from '../constants/DashConstants';\nimport DashManifestModel from '../models/DashManifestModel';\nimport Settings from '../../core/Settings';\nimport Constants from '../../streaming/constants/Constants';\nimport MediaPlayerEvents from '../../streaming/MediaPlayerEvents';\nimport ConformanceViolationConstants from '../../streaming/constants/ConformanceViolationConstants';\n\nfunction TimelineConverter() {\n\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n const settings = Settings(context).getInstance();\n\n let instance,\n dashManifestModel,\n timelineAnchorAvailabilityOffset, // In case we calculate the TSBD using _calcTimeShiftBufferWindowForDynamicTimelineManifest we use the segments as anchor times. We apply this offset when calculating if a segment is available or not.\n clientServerTimeShift;\n\n function setup() {\n dashManifestModel = DashManifestModel(context).getInstance();\n reset();\n }\n\n function initialize() {\n resetInitialSettings();\n eventBus.on(Events.UPDATE_TIME_SYNC_OFFSET, _onUpdateTimeSyncOffset, this);\n }\n\n function getClientTimeOffset() {\n return clientServerTimeShift;\n }\n\n function setClientTimeOffset(value) {\n clientServerTimeShift = value;\n }\n\n /**\n * Returns a \"now\" reference time for the client to compare the availability time of a segment against.\n * Takes the client/server drift into account\n */\n function getClientReferenceTime() {\n return Date.now() - (timelineAnchorAvailabilityOffset * 1000) + (clientServerTimeShift * 1000);\n }\n\n function _calcAvailabilityTimeFromPresentationTime(presentationEndTime, representation, isDynamic, calculateAvailabilityEndTime) {\n let availabilityTime;\n let mpd = representation.adaptation.period.mpd;\n const availabilityStartTime = mpd.availabilityStartTime;\n\n if (calculateAvailabilityEndTime) {\n //@timeShiftBufferDepth specifies the duration of the time shifting buffer that is guaranteed\n // to be available for a Media Presentation with type 'dynamic'.\n // When not present, the value is infinite.\n if (isDynamic && mpd.timeShiftBufferDepth !== Number.POSITIVE_INFINITY) {\n // SAET = SAST + TSBD + seg@duration\n availabilityTime = new Date(availabilityStartTime.getTime() + ((presentationEndTime + mpd.timeShiftBufferDepth) * 1000));\n } else {\n availabilityTime = mpd.availabilityEndTime;\n }\n } else {\n if (isDynamic) {\n // SAST = Period@start + seg@presentationStartTime + seg@duration\n // ASAST = SAST - ATO\n const availabilityTimeOffset = representation.availabilityTimeOffset;\n // presentationEndTime = Period@start + seg@presentationStartTime + Segment@duration\n availabilityTime = new Date(availabilityStartTime.getTime() + (presentationEndTime - availabilityTimeOffset) * 1000);\n } else {\n // in static mpd, all segments are available at the same time\n availabilityTime = availabilityStartTime;\n }\n }\n\n return availabilityTime;\n }\n\n function calcAvailabilityStartTimeFromPresentationTime(presentationEndTime, representation, isDynamic) {\n return _calcAvailabilityTimeFromPresentationTime(presentationEndTime, representation, isDynamic);\n }\n\n function calcAvailabilityEndTimeFromPresentationTime(presentationEndTime, representation, isDynamic) {\n return _calcAvailabilityTimeFromPresentationTime(presentationEndTime, representation, isDynamic, true);\n }\n\n function calcPresentationTimeFromWallTime(wallTime, period) {\n return ((wallTime.getTime() - period.mpd.availabilityStartTime.getTime() + clientServerTimeShift * 1000) / 1000);\n }\n\n function calcPresentationTimeFromMediaTime(mediaTime, representation) {\n const periodStart = representation.adaptation.period.start;\n const presentationOffset = representation.presentationTimeOffset;\n\n return mediaTime + (periodStart - presentationOffset);\n }\n\n function calcMediaTimeFromPresentationTime(presentationTime, representation) {\n const periodStart = representation.adaptation.period.start;\n const presentationOffset = representation.presentationTimeOffset;\n\n return presentationTime - periodStart + presentationOffset;\n }\n\n function calcWallTimeForSegment(segment, isDynamic) {\n let suggestedPresentationDelay,\n displayStartTime,\n wallTime;\n\n if (isDynamic) {\n suggestedPresentationDelay = segment.representation.adaptation.period.mpd.suggestedPresentationDelay;\n displayStartTime = segment.presentationStartTime + suggestedPresentationDelay;\n wallTime = new Date(segment.availabilityStartTime.getTime() + (displayStartTime * 1000));\n }\n\n return wallTime;\n }\n\n /**\n * Calculates the timeshiftbuffer range. This range might overlap multiple periods and is not limited to period boundaries. However, we make sure that the range is potentially covered by period.\n * @param {Array} streams\n * @param {boolean} isDynamic\n * @return {}\n */\n function calcTimeShiftBufferWindow(streams, isDynamic) {\n // Static manifests. The availability window is equal to the DVR window\n if (!isDynamic) {\n return _calcTimeshiftBufferForStaticManifest(streams);\n }\n\n // Specific use case of SegmentTimeline\n if (settings.get().streaming.timeShiftBuffer.calcFromSegmentTimeline) {\n const data = _calcTimeShiftBufferWindowForDynamicTimelineManifest(streams);\n _adjustTimelineAnchorAvailabilityOffset(data.now, data.range);\n\n return data.range;\n }\n\n return _calcTimeShiftBufferWindowForDynamicManifest(streams);\n }\n\n function _calcTimeshiftBufferForStaticManifest(streams) {\n // Static Range Finder. We iterate over all periods and return the total duration\n const range = { start: NaN, end: NaN };\n let duration = 0;\n let start = NaN;\n streams.forEach((stream) => {\n const streamInfo = stream.getStreamInfo();\n duration += streamInfo.duration;\n\n if (isNaN(start) || streamInfo.start < start) {\n start = streamInfo.start;\n }\n });\n\n range.start = start;\n range.end = start + duration;\n\n return range;\n }\n\n function _calcTimeShiftBufferWindowForDynamicManifest(streams) {\n const range = { start: NaN, end: NaN };\n\n if (!streams || streams.length === 0) {\n return range;\n }\n\n const voPeriod = streams[0].getAdapter().getRegularPeriods()[0];\n const now = calcPresentationTimeFromWallTime(new Date(), voPeriod);\n const timeShiftBufferDepth = voPeriod.mpd.timeShiftBufferDepth;\n const start = !isNaN(timeShiftBufferDepth) ? now - timeShiftBufferDepth : 0;\n // check if we find a suitable period for that starttime. Otherwise we use the time closest to that\n range.start = _adjustTimeBasedOnPeriodRanges(streams, start);\n range.end = !isNaN(range.start) && now < range.start ? now : _adjustTimeBasedOnPeriodRanges(streams, now, true);\n\n if (!isNaN(timeShiftBufferDepth) && range.end < now - timeShiftBufferDepth) {\n range.end = NaN;\n }\n\n // If we have SegmentTimeline as a reference we can verify that the calculated DVR window is at least partially included in the DVR window exposed by the timeline.\n // If that is not the case we stick to the DVR window defined by SegmentTimeline\n if (settings.get().streaming.timeShiftBuffer.fallbackToSegmentTimeline) {\n const timelineRefData = _calcTimeShiftBufferWindowForDynamicTimelineManifest(streams);\n if (timelineRefData.range.end < range.start) {\n eventBus.trigger(MediaPlayerEvents.CONFORMANCE_VIOLATION, {\n level: ConformanceViolationConstants.LEVELS.WARNING,\n event: ConformanceViolationConstants.EVENTS.INVALID_DVR_WINDOW\n });\n _adjustTimelineAnchorAvailabilityOffset(timelineRefData.now, timelineRefData.range);\n return timelineRefData.range;\n }\n }\n\n return range;\n }\n\n function _calcTimeShiftBufferWindowForDynamicTimelineManifest(streams) {\n const range = { start: NaN, end: NaN };\n const voPeriod = streams[0].getAdapter().getRegularPeriods()[0];\n const now = calcPresentationTimeFromWallTime(new Date(), voPeriod);\n\n if (!streams || streams.length === 0) {\n return { range, now };\n }\n\n streams.forEach((stream) => {\n const adapter = stream.getAdapter();\n const mediaInfo = adapter.getMediaInfoForType(stream.getStreamInfo(), Constants.VIDEO) || adapter.getMediaInfoForType(stream.getStreamInfo(), Constants.AUDIO);\n const voRepresentations = adapter.getVoRepresentations(mediaInfo);\n const voRepresentation = voRepresentations[0];\n let periodRange = { start: NaN, end: NaN };\n\n if (voRepresentation) {\n if (voRepresentation.segmentInfoType === DashConstants.SEGMENT_TIMELINE) {\n periodRange = _calcRangeForTimeline(voRepresentation);\n } else {\n const currentVoPeriod = voRepresentation.adaptation.period;\n periodRange.start = currentVoPeriod.start;\n periodRange.end = Math.max(now, currentVoPeriod.start + currentVoPeriod.duration);\n }\n }\n\n if (!isNaN(periodRange.start) && (isNaN(range.start) || range.start > periodRange.start)) {\n range.start = periodRange.start;\n }\n if (!isNaN(periodRange.end) && (isNaN(range.end) || range.end < periodRange.end)) {\n range.end = periodRange.end;\n }\n });\n\n\n range.end = Math.min(now, range.end);\n const adjustedEndTime = _adjustTimeBasedOnPeriodRanges(streams, range.end, true);\n\n // if range is NaN all periods are in the future. we should return range.start > range.end in this case\n range.end = isNaN(adjustedEndTime) ? range.end : adjustedEndTime;\n\n range.start = voPeriod && voPeriod.mpd && voPeriod.mpd.timeShiftBufferDepth && !isNaN(voPeriod.mpd.timeShiftBufferDepth) && !isNaN(range.end) ? Math.max(range.end - voPeriod.mpd.timeShiftBufferDepth, range.start) : range.start;\n range.start = _adjustTimeBasedOnPeriodRanges(streams, range.start);\n\n return { range, now };\n }\n\n function _adjustTimelineAnchorAvailabilityOffset(now, range) {\n timelineAnchorAvailabilityOffset = now - range.end;\n }\n\n function _adjustTimeBasedOnPeriodRanges(streams, time, isEndOfDvrWindow = false) {\n try {\n let i = 0;\n let found = false;\n let adjustedTime = NaN;\n\n while (!found && i < streams.length) {\n const streamInfo = streams[i].getStreamInfo();\n\n // We found a period which contains the target time.\n if (streamInfo.start <= time && (!isFinite(streamInfo.duration) || (streamInfo.start + streamInfo.duration >= time))) {\n adjustedTime = time;\n found = true;\n }\n\n // Adjust the time for the start of the DVR window. The current period starts after the target time. We use the starttime of this period as adjusted time\n else if (!isEndOfDvrWindow && (streamInfo.start > time && (isNaN(adjustedTime) || streamInfo.start < adjustedTime))) {\n adjustedTime = streamInfo.start;\n }\n\n // Adjust the time for the end of the DVR window. The current period ends before the targettime. We use the end time of this period as the adjusted time\n else if (isEndOfDvrWindow && ((streamInfo.start + streamInfo.duration) < time && (isNaN(adjustedTime) || (streamInfo.start + streamInfo.duration > adjustedTime)))) {\n adjustedTime = streamInfo.start + streamInfo.duration;\n }\n\n i += 1;\n }\n\n return adjustedTime;\n } catch (e) {\n return time;\n }\n }\n\n function _calcRangeForTimeline(voRepresentation) {\n const adaptation = voRepresentation.adaptation.period.mpd.manifest.Period_asArray[voRepresentation.adaptation.period.index].AdaptationSet_asArray[voRepresentation.adaptation.index];\n const representation = dashManifestModel.getRepresentationFor(voRepresentation.index, adaptation);\n const timeline = representation.SegmentTemplate.SegmentTimeline;\n const timescale = representation.SegmentTemplate.timescale;\n const segments = timeline.S_asArray;\n const range = { start: 0, end: 0 };\n let d = 0;\n let segment,\n repeat,\n i,\n len;\n\n range.start = calcPresentationTimeFromMediaTime(segments[0].t / timescale, voRepresentation);\n\n for (i = 0, len = segments.length; i < len; i++) {\n segment = segments[i];\n repeat = 0;\n if (segment.hasOwnProperty('r')) {\n repeat = segment.r;\n }\n d += (segment.d / timescale) * (1 + repeat);\n }\n\n range.end = range.start + d;\n\n return range;\n }\n\n function calcPeriodRelativeTimeFromMpdRelativeTime(representation, mpdRelativeTime) {\n const periodStartTime = representation.adaptation.period.start;\n return mpdRelativeTime - periodStartTime;\n }\n\n function _onUpdateTimeSyncOffset(e) {\n if (e.offset !== undefined && !isNaN(e.offset)) {\n setClientTimeOffset(e.offset / 1000);\n }\n }\n\n function resetInitialSettings() {\n clientServerTimeShift = 0;\n timelineAnchorAvailabilityOffset = 0;\n }\n\n function reset() {\n eventBus.off(Events.UPDATE_TIME_SYNC_OFFSET, _onUpdateTimeSyncOffset, this);\n resetInitialSettings();\n }\n\n instance = {\n initialize,\n getClientTimeOffset,\n setClientTimeOffset,\n getClientReferenceTime,\n calcAvailabilityStartTimeFromPresentationTime,\n calcAvailabilityEndTimeFromPresentationTime,\n calcPresentationTimeFromWallTime,\n calcPresentationTimeFromMediaTime,\n calcPeriodRelativeTimeFromMpdRelativeTime,\n calcMediaTimeFromPresentationTime,\n calcWallTimeForSegment,\n calcTimeShiftBufferWindow,\n reset\n };\n\n setup();\n return instance;\n}\n\nTimelineConverter.__dashjs_factory_name = 'TimelineConverter';\nexport default FactoryMaker.getSingletonFactory(TimelineConverter);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport MediaInfo from './../../dash/vo/MediaInfo';\n\n/**\n * @class\n * @ignore\n */\nclass TextTrackInfo extends MediaInfo {\n constructor () {\n super();\n this.captionData = null;\n this.label = null;\n this.defaultTrack = false;\n this.kind = null;\n this.isFragmented = false;\n this.isEmbedded = false;\n this.isTTML = null;\n }\n}\n\nexport default TextTrackInfo;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport FactoryMaker from '../../core/FactoryMaker';\n\nfunction EmbeddedTextHtmlRender() {\n\n let captionId = 0;\n let instance;\n\n /* HTML Rendering functions */\n function checkIndent(chars) {\n let line = '';\n\n for (let c = 0; c < chars.length; ++c) {\n const uc = chars[c];\n line += uc.uchar;\n }\n\n const l = line.length;\n const ll = line.replace(/^\\s+/,'').length;\n return l - ll;\n }\n\n function getRegionProperties(region) {\n return 'left: ' + (region.x * 3.125) + '%; top: ' + (region.y1 * 6.66) + '%; width: ' + (100 - (region.x * 3.125)) + '%; height: ' + (Math.max((region.y2 - 1) - region.y1, 1) * 6.66) + '%; align-items: flex-start; overflow: visible; -webkit-writing-mode: horizontal-tb;';\n }\n\n function createRGB(color) {\n if (color === 'red') {\n return 'rgb(255, 0, 0)';\n } else if (color === 'green') {\n return 'rgb(0, 255, 0)';\n } else if (color === 'blue') {\n return 'rgb(0, 0, 255)';\n } else if (color === 'cyan') {\n return 'rgb(0, 255, 255)';\n } else if (color === 'magenta') {\n return 'rgb(255, 0, 255)';\n } else if (color === 'yellow') {\n return 'rgb(255, 255, 0)';\n } else if (color === 'white') {\n return 'rgb(255, 255, 255)';\n } else if (color === 'black') {\n return 'rgb(0, 0, 0)';\n }\n return color;\n }\n\n function getStyle(videoElement, style) {\n const fontSize = videoElement.videoHeight / 15.0;\n if (style) {\n return 'font-size: ' + fontSize + 'px; font-family: Menlo, Consolas, \\'Cutive Mono\\', monospace; color: ' + ((style.foreground) ? createRGB(style.foreground) : 'rgb(255, 255, 255)') + '; font-style: ' + (style.italics ? 'italic' : 'normal') + '; text-decoration: ' + (style.underline ? 'underline' : 'none') + '; white-space: pre; background-color: ' + ((style.background) ? createRGB(style.background) : 'transparent') + ';';\n } else {\n return 'font-size: ' + fontSize + 'px; font-family: Menlo, Consolas, \\'Cutive Mono\\', monospace; justify-content: flex-start; text-align: left; color: rgb(255, 255, 255); font-style: normal; white-space: pre; line-height: normal; font-weight: normal; text-decoration: none; width: 100%; display: flex;';\n }\n }\n\n function ltrim(s) {\n return s.replace(/^\\s+/g, '');\n }\n\n function rtrim(s) {\n return s.replace(/\\s+$/g, '');\n }\n\n function createHTMLCaptionsFromScreen(videoElement, startTime, endTime, captionScreen) {\n let currRegion = null;\n let existingRegion = null;\n let lastRowHasText = false;\n let lastRowIndentL = -1;\n let currP = {start: startTime, end: endTime, spans: []};\n let currentStyle = 'style_cea608_white_black';\n const seenRegions = {};\n const styleStates = {};\n const regions = [];\n let r, s;\n\n for (r = 0; r < 15; ++r) {\n const row = captionScreen.rows[r];\n let line = '';\n let prevPenState = null;\n\n if (false === row.isEmpty()) {\n /* Row is not empty */\n\n /* Get indentation of this row */\n const rowIndent = checkIndent(row.chars);\n\n /* Create a new region is there is none */\n if (currRegion === null) {\n currRegion = { x: rowIndent, y1: r, y2: (r + 1), p: [] };\n }\n\n /* Check if indentation has changed and we had text of last row */\n if ((rowIndent !== lastRowIndentL) && lastRowHasText) {\n currRegion.p.push(currP);\n currP = { start: startTime, end: endTime, spans: [] };\n currRegion.y2 = r;\n currRegion.name = 'region_' + currRegion.x + '_' + currRegion.y1 + '_' + currRegion.y2;\n if (false === seenRegions.hasOwnProperty(currRegion.name)) {\n regions.push(currRegion);\n seenRegions[currRegion.name] = currRegion;\n } else {\n existingRegion = seenRegions[currRegion.name];\n existingRegion.p.contat(currRegion.p);\n }\n\n currRegion = { x: rowIndent, y1: r, y2: (r + 1), p: [] };\n }\n\n for (let c = 0; c < row.chars.length; ++c) {\n const uc = row.chars[c];\n const currPenState = uc.penState;\n if ((prevPenState === null) || (!currPenState.equals(prevPenState))) {\n if (line.trim().length > 0) {\n currP.spans.push({ name: currentStyle, line: line, row: r });\n line = '';\n }\n\n let currPenStateString = 'style_cea608_' + currPenState.foreground + '_' + currPenState.background;\n if (currPenState.underline) {\n currPenStateString += '_underline';\n }\n if (currPenState.italics) {\n currPenStateString += '_italics';\n }\n\n if (!styleStates.hasOwnProperty(currPenStateString)) {\n styleStates[currPenStateString] = JSON.parse(JSON.stringify(currPenState));\n }\n\n prevPenState = currPenState;\n\n currentStyle = currPenStateString;\n }\n\n line += uc.uchar;\n }\n\n if (line.trim().length > 0) {\n currP.spans.push({ name: currentStyle, line: line, row: r });\n }\n\n lastRowHasText = true;\n lastRowIndentL = rowIndent;\n } else {\n /* Row is empty */\n lastRowHasText = false;\n lastRowIndentL = -1;\n\n if (currRegion) {\n currRegion.p.push(currP);\n currP = { start: startTime, end: endTime, spans: [] };\n currRegion.y2 = r;\n currRegion.name = 'region_' + currRegion.x + '_' + currRegion.y1 + '_' + currRegion.y2;\n if (false === seenRegions.hasOwnProperty(currRegion.name)) {\n regions.push(currRegion);\n seenRegions[currRegion.name] = currRegion;\n } else {\n existingRegion = seenRegions[currRegion.name];\n existingRegion.p.contat(currRegion.p);\n }\n\n currRegion = null;\n }\n\n }\n }\n\n if (currRegion) {\n currRegion.p.push(currP);\n currRegion.y2 = r + 1;\n currRegion.name = 'region_' + currRegion.x + '_' + currRegion.y1 + '_' + currRegion.y2;\n if (false === seenRegions.hasOwnProperty(currRegion.name)) {\n regions.push(currRegion);\n seenRegions[currRegion.name] = currRegion;\n } else {\n existingRegion = seenRegions[currRegion.name];\n existingRegion.p.contat(currRegion.p);\n }\n\n currRegion = null;\n }\n\n const captionsArray = [];\n\n /* Loop thru regions */\n for (r = 0; r < regions.length; ++r) {\n const region = regions[r];\n\n const cueID = 'sub_cea608_' + (captionId++);\n const finalDiv = document.createElement('div');\n finalDiv.id = cueID;\n const cueRegionProperties = getRegionProperties(region);\n finalDiv.style.cssText = 'position: absolute; margin: 0; display: flex; box-sizing: border-box; pointer-events: none;' + cueRegionProperties;\n\n const bodyDiv = document.createElement('div');\n bodyDiv.className = 'paragraph bodyStyle';\n bodyDiv.style.cssText = getStyle(videoElement);\n\n const cueUniWrapper = document.createElement('div');\n cueUniWrapper.className = 'cueUniWrapper';\n cueUniWrapper.style.cssText = 'unicode-bidi: normal; direction: ltr;';\n\n for (let p = 0; p < region.p.length; ++p) {\n const ptag = region.p[p];\n let lastSpanRow = 0;\n for (s = 0; s < ptag.spans.length; ++s) {\n let span = ptag.spans[s];\n if (span.line.length > 0) {\n if ((s !== 0) && lastSpanRow != span.row) {\n const brElement = document.createElement('br');\n brElement.className = 'lineBreak';\n cueUniWrapper.appendChild(brElement);\n }\n let sameRow = false;\n if (lastSpanRow === span.row) {\n sameRow = true;\n }\n lastSpanRow = span.row;\n const spanStyle = styleStates[span.name];\n const spanElement = document.createElement('span');\n spanElement.className = 'spanPadding ' + span.name + ' customSpanColor';\n spanElement.style.cssText = getStyle(videoElement, spanStyle);\n /* If this is not the first span, and it's on the same\n * row as the last one */\n if ((s !== 0) && sameRow) {\n /* and it's the last span on this row */\n if (s === ptag.spans.length - 1) {\n /* trim only the right side */\n spanElement.textContent = rtrim(span.line);\n } else {\n /* don't trim at all */\n spanElement.textContent = span.line;\n }\n } else {\n /* if there is more than 1 span and this isn't the last span */\n if (ptag.spans.length > 1 && s < (ptag.spans.length - 1)) {\n /* Check if next text is on same row */\n if (span.row === ptag.spans[s + 1].row) {\n /* Next element on same row, trim start */\n spanElement.textContent = ltrim(span.line);\n } else {\n /* Different rows, trim both */\n spanElement.textContent = span.line.trim();\n }\n } else {\n spanElement.textContent = span.line.trim();\n }\n }\n cueUniWrapper.appendChild(spanElement);\n }\n }\n }\n\n bodyDiv.appendChild(cueUniWrapper);\n finalDiv.appendChild(bodyDiv);\n\n const fontSize = { 'bodyStyle': ['%', 90] };\n for (const s in styleStates) {\n if (styleStates.hasOwnProperty(s)) {\n fontSize[s] = ['%', 90];\n }\n }\n\n captionsArray.push({ type: 'html',\n start: startTime,\n end: endTime,\n cueHTMLElement: finalDiv,\n cueID: cueID,\n cellResolution: [32, 15],\n isFromCEA608: true,\n fontSize: fontSize,\n lineHeight: {},\n linePadding: {}\n });\n }\n return captionsArray;\n }\n\n instance = {\n createHTMLCaptionsFromScreen: createHTMLCaptionsFromScreen\n };\n return instance;\n}\n\nEmbeddedTextHtmlRender.__dashjs_factory_name = 'EmbeddedTextHtmlRender';\nexport default FactoryMaker.getSingletonFactory(EmbeddedTextHtmlRender);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Constants from '../constants/Constants';\nimport {HTTPRequest} from '../vo/metrics/HTTPRequest';\nimport TextTrackInfo from '../vo/TextTrackInfo';\nimport BoxParser from '../utils/BoxParser';\nimport CustomTimeRanges from '../utils/CustomTimeRanges';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Debug from '../../core/Debug';\nimport EmbeddedTextHtmlRender from './EmbeddedTextHtmlRender';\nimport ISOBoxer from 'codem-isoboxer';\nimport cea608parser from '../../../externals/cea608-parser';\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\nimport DashJSError from '../vo/DashJSError';\nimport Errors from '../../core/errors/Errors';\n\nfunction TextSourceBuffer(config) {\n const errHandler = config.errHandler;\n const manifestModel = config.manifestModel;\n const mediaController = config.mediaController;\n const videoModel = config.videoModel;\n const textTracks = config.textTracks;\n const vttParser = config.vttParser;\n const ttmlParser = config.ttmlParser;\n const streamInfo = config.streamInfo;\n\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n let embeddedInitialized = false;\n\n let instance,\n logger,\n boxParser,\n parser,\n mediaInfos,\n fragmentModel,\n initializationSegmentReceived,\n timescale,\n fragmentedTracks,\n firstFragmentedSubtitleStart,\n currFragmentedTrackIdx,\n embeddedTracks,\n embeddedTimescale,\n embeddedLastSequenceNumber,\n embeddedCea608FieldParsers,\n embeddedTextHtmlRender;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n boxParser = BoxParser(context).getInstance();\n\n resetInitialSettings();\n }\n\n function getStreamId() {\n return streamInfo.id;\n }\n\n function _resetFragmented() {\n fragmentModel = null;\n timescale = NaN;\n fragmentedTracks = [];\n firstFragmentedSubtitleStart = null;\n initializationSegmentReceived = false;\n }\n\n function resetInitialSettings() {\n _resetFragmented();\n\n mediaInfos = [];\n parser = null;\n }\n\n function initialize() {\n\n if (!embeddedInitialized) {\n _initEmbedded();\n }\n\n }\n\n /**\n * There might be media infos of different types. For instance text and fragmentedText.\n * @param {string} type\n * @param {array} mInfos\n * @param {object} fModel\n */\n function addMediaInfos(type, mInfos, fModel) {\n\n mediaInfos = mediaInfos.concat(mInfos);\n\n if (type === Constants.TEXT && mInfos[0].isFragmented && !mInfos[0].isEmbedded) {\n fragmentModel = fModel;\n instance.buffered = CustomTimeRanges(context).create();\n fragmentedTracks = mediaController.getTracksFor(Constants.TEXT, streamInfo.id).filter(track => track.isFragmented);\n const currFragTrack = mediaController.getCurrentTrackFor(Constants.TEXT, streamInfo.id);\n for (let i = 0; i < fragmentedTracks.length; i++) {\n if (fragmentedTracks[i] === currFragTrack) {\n setCurrentFragmentedTrackIdx(i);\n break;\n }\n }\n }\n\n for (let i = 0; i < mInfos.length; i++) {\n _createTextTrackFromMediaInfo(mInfos[i]);\n }\n\n }\n\n /**\n * Create a new track based on the mediaInfo information\n * @param {object} mediaInfo\n * @private\n */\n function _createTextTrackFromMediaInfo(mediaInfo) {\n const textTrackInfo = new TextTrackInfo();\n const trackKindMap = { subtitle: 'subtitles', caption: 'captions' }; //Dash Spec has no \"s\" on end of KIND but HTML needs plural.\n\n for (let key in mediaInfo) {\n textTrackInfo[key] = mediaInfo[key];\n }\n\n textTrackInfo.labels = mediaInfo.labels;\n textTrackInfo.defaultTrack = getIsDefault(mediaInfo);\n textTrackInfo.isFragmented = mediaInfo.isFragmented;\n textTrackInfo.isEmbedded = !!mediaInfo.isEmbedded;\n textTrackInfo.isTTML = _checkTtml(mediaInfo);\n textTrackInfo.kind = _getKind(mediaInfo, trackKindMap);\n\n textTracks.addTextTrack(textTrackInfo);\n }\n\n function abort() {\n }\n\n function reset() {\n resetInitialSettings();\n\n mediaInfos = [];\n boxParser = null;\n }\n\n function _onVideoChunkReceived(e) {\n const chunk = e.chunk;\n\n if (chunk.mediaInfo.embeddedCaptions) {\n append(chunk.bytes, chunk);\n }\n }\n\n function _initEmbedded() {\n embeddedTracks = [];\n currFragmentedTrackIdx = null;\n embeddedTimescale = 0;\n embeddedCea608FieldParsers = [];\n embeddedLastSequenceNumber = null;\n embeddedInitialized = true;\n embeddedTextHtmlRender = EmbeddedTextHtmlRender(context).getInstance();\n\n eventBus.on(Events.VIDEO_CHUNK_RECEIVED, _onVideoChunkReceived, instance);\n eventBus.on(Events.BUFFER_CLEARED, onVideoBufferCleared, instance);\n }\n\n function resetEmbedded() {\n eventBus.off(Events.VIDEO_CHUNK_RECEIVED, _onVideoChunkReceived, instance);\n eventBus.off(Events.BUFFER_CLEARED, onVideoBufferCleared, instance);\n if (textTracks) {\n textTracks.deleteAllTextTracks();\n }\n embeddedInitialized = false;\n embeddedTracks = [];\n embeddedCea608FieldParsers = [null, null];\n embeddedLastSequenceNumber = null;\n }\n\n function addEmbeddedTrack(mediaInfo) {\n\n if (!embeddedInitialized) {\n return;\n }\n\n if (mediaInfo) {\n if (mediaInfo.id === Constants.CC1 || mediaInfo.id === Constants.CC3) {\n for (let i = 0; i < embeddedTracks.length; i++) {\n if (embeddedTracks[i].id === mediaInfo.id) {\n return;\n }\n }\n embeddedTracks.push(mediaInfo);\n } else {\n logger.warn('Embedded track ' + mediaInfo.id + ' not supported!');\n }\n }\n }\n\n function getConfig() {\n const config = {\n fragmentModel: fragmentModel,\n fragmentedTracks: fragmentedTracks,\n videoModel: videoModel\n };\n\n return config;\n }\n\n function setCurrentFragmentedTrackIdx(idx) {\n currFragmentedTrackIdx = idx;\n }\n\n function _checkTtml(mediaInfo) {\n return (mediaInfo.codec && mediaInfo.codec.search(Constants.STPP) >= 0) || (mediaInfo.mimeType && mediaInfo.mimeType.search(Constants.TTML) >= 0);\n }\n\n function _getKind(mediaInfo, trackKindMap) {\n let kind = (mediaInfo.roles && mediaInfo.roles.length > 0) ? trackKindMap[mediaInfo.roles[0]] : trackKindMap.caption;\n\n kind = (kind === trackKindMap.caption || kind === trackKindMap.subtitle) ? kind : trackKindMap.caption;\n\n return kind;\n }\n\n function append(bytes, chunk) {\n const mediaInfo = chunk.mediaInfo;\n const mediaType = mediaInfo.type;\n const mimeType = mediaInfo.mimeType;\n const codecType = mediaInfo.codec || mimeType;\n\n if (!codecType) {\n logger.error('No text type defined');\n return;\n }\n\n if (mediaInfo.codec.indexOf('application/mp4') !== -1) {\n _appendFragmentedText(bytes, chunk, codecType);\n } else if (mediaType === Constants.VIDEO) {\n _appendEmbeddedText(bytes, chunk);\n } else {\n _appendText(bytes, chunk, codecType);\n }\n }\n\n function _appendFragmentedText(bytes, chunk, codecType) {\n let sampleList,\n samplesInfo;\n\n if (chunk.segmentType === 'InitializationSegment') {\n initializationSegmentReceived = true;\n timescale = boxParser.getMediaTimescaleFromMoov(bytes);\n } else {\n if (!initializationSegmentReceived) {\n return;\n }\n samplesInfo = boxParser.getSamplesInfo(bytes);\n sampleList = samplesInfo.sampleList;\n if (sampleList.length > 0) {\n firstFragmentedSubtitleStart = sampleList[0].cts - chunk.start * timescale;\n }\n if (codecType.search(Constants.STPP) >= 0) {\n _appendFragmentedSttp(bytes, sampleList, codecType);\n } else {\n _appendFragmentedWebVtt(bytes, sampleList);\n }\n }\n }\n\n function _appendFragmentedSttp(bytes, sampleList, codecType) {\n let i, j;\n\n parser = parser !== null ? parser : getParser(codecType);\n\n for (i = 0; i < sampleList.length; i++) {\n const sample = sampleList[i];\n const sampleStart = sample.cts;\n const timestampOffset = _getTimestampOffset();\n const start = timestampOffset + sampleStart / timescale;\n const end = start + sample.duration / timescale;\n instance.buffered.add(start, end);\n const dataView = new DataView(bytes, sample.offset, sample.subSizes[0]);\n let ccContent = ISOBoxer.Utils.dataViewToString(dataView, Constants.UTF8);\n const images = [];\n let subOffset = sample.offset + sample.subSizes[0];\n\n for (j = 1; j < sample.subSizes.length; j++) {\n const inData = new Uint8Array(bytes, subOffset, sample.subSizes[j]);\n const raw = String.fromCharCode.apply(null, inData);\n images.push(raw);\n subOffset += sample.subSizes[j];\n }\n\n try {\n const manifest = manifestModel.getValue();\n\n // Only used for Miscrosoft Smooth Streaming support - caption time is relative to sample time. In this case, we apply an offset.\n const offsetTime = manifest.ttmlTimeIsRelative ? sampleStart / timescale : 0;\n\n const result = parser.parse(ccContent, offsetTime, sampleStart / timescale, (sampleStart + sample.duration) / timescale, images);\n textTracks.addCaptions(currFragmentedTrackIdx, timestampOffset, result);\n } catch (e) {\n fragmentModel.removeExecutedRequestsBeforeTime();\n this.remove();\n logger.error('TTML parser error: ' + e.message);\n }\n }\n }\n\n function _appendFragmentedWebVtt(bytes, sampleList) {\n let i, j, k;\n\n const captionArray = [];\n for (i = 0; i < sampleList.length; i++) {\n const sample = sampleList[i];\n sample.cts -= firstFragmentedSubtitleStart;\n const timestampOffset = _getTimestampOffset();\n const start = timestampOffset + sample.cts / timescale;\n const end = start + sample.duration / timescale;\n instance.buffered.add(start, end);\n const sampleData = bytes.slice(sample.offset, sample.offset + sample.size);\n // There are boxes inside the sampleData, so we need a ISOBoxer to get at it.\n const sampleBoxes = ISOBoxer.parseBuffer(sampleData);\n\n for (j = 0; j < sampleBoxes.boxes.length; j++) {\n const box1 = sampleBoxes.boxes[j];\n logger.debug('VTT box1: ' + box1.type);\n if (box1.type === 'vtte') {\n continue; //Empty box\n }\n if (box1.type === 'vttc') {\n logger.debug('VTT vttc boxes.length = ' + box1.boxes.length);\n for (k = 0; k < box1.boxes.length; k++) {\n const box2 = box1.boxes[k];\n logger.debug('VTT box2: ' + box2.type);\n if (box2.type === 'payl') {\n const cue_text = box2.cue_text;\n logger.debug('VTT cue_text = ' + cue_text);\n const start_time = sample.cts / timescale;\n const end_time = (sample.cts + sample.duration) / timescale;\n captionArray.push({\n start: start_time,\n end: end_time,\n data: cue_text,\n styles: {}\n });\n logger.debug('VTT ' + start_time + '-' + end_time + ' : ' + cue_text);\n }\n }\n }\n }\n }\n if (captionArray.length > 0) {\n textTracks.addCaptions(currFragmentedTrackIdx, 0, captionArray);\n }\n }\n\n function _appendText(bytes, chunk, codecType) {\n let result,\n ccContent;\n\n const dataView = new DataView(bytes, 0, bytes.byteLength);\n ccContent = ISOBoxer.Utils.dataViewToString(dataView, Constants.UTF8);\n\n try {\n result = getParser(codecType).parse(ccContent, 0);\n textTracks.addCaptions(textTracks.getCurrentTrackIdx(), 0, result);\n if (instance.buffered) {\n instance.buffered.add(chunk.start, chunk.end);\n }\n } catch (e) {\n errHandler.error(new DashJSError(Errors.TIMED_TEXT_ERROR_ID_PARSE_CODE, Errors.TIMED_TEXT_ERROR_MESSAGE_PARSE + e.message, ccContent));\n }\n }\n\n function _appendEmbeddedText(bytes, chunk) {\n let i, samplesInfo;\n\n // Init segment\n if (chunk.segmentType === HTTPRequest.INIT_SEGMENT_TYPE) {\n if (embeddedTimescale === 0) {\n embeddedTimescale = boxParser.getMediaTimescaleFromMoov(bytes);\n }\n }\n\n // MediaSegment\n else if (chunk.segmentType === HTTPRequest.MEDIA_SEGMENT_TYPE) {\n\n if (embeddedTimescale === 0) {\n logger.warn('CEA-608: No timescale for embeddedTextTrack yet');\n return;\n }\n\n samplesInfo = boxParser.getSamplesInfo(bytes);\n\n const sequenceNumber = samplesInfo.lastSequenceNumber;\n if (!embeddedCea608FieldParsers[0] && !embeddedCea608FieldParsers[1]) {\n _setupCeaParser();\n }\n\n if (embeddedTimescale) {\n if (embeddedLastSequenceNumber !== null && sequenceNumber !== embeddedLastSequenceNumber + samplesInfo.numSequences) {\n for (i = 0; i < embeddedCea608FieldParsers.length; i++) {\n if (embeddedCea608FieldParsers[i]) {\n embeddedCea608FieldParsers[i].reset();\n }\n }\n }\n\n const allCcData = _extractCea608Data(bytes, samplesInfo.sampleList);\n\n for (let fieldNr = 0; fieldNr < embeddedCea608FieldParsers.length; fieldNr++) {\n const ccData = allCcData.fields[fieldNr];\n const fieldParser = embeddedCea608FieldParsers[fieldNr];\n if (fieldParser) {\n for (i = 0; i < ccData.length; i++) {\n fieldParser.addData(ccData[i][0] / embeddedTimescale, ccData[i][1]);\n }\n }\n }\n embeddedLastSequenceNumber = sequenceNumber;\n }\n }\n }\n\n function _setupCeaParser() {\n // Time to setup the CEA-608 parsing\n let trackIdx;\n for (let i = 0; i < embeddedTracks.length; i++) {\n trackIdx = textTracks.getTrackIdxForId(embeddedTracks[i].id);\n\n if (trackIdx === -1) {\n logger.warn('CEA-608: data before track is ready.');\n return;\n }\n\n const handler = _makeCueAdderForIndex(trackIdx);\n embeddedCea608FieldParsers[i] = new cea608parser.Cea608Parser(i + 1, {\n newCue: handler\n }, null);\n }\n }\n\n function _makeCueAdderForIndex(trackIndex) {\n function newCue(startTime, endTime, captionScreen) {\n let captionsArray;\n if (videoModel.getTTMLRenderingDiv()) {\n captionsArray = embeddedTextHtmlRender.createHTMLCaptionsFromScreen(videoModel.getElement(), startTime, endTime, captionScreen);\n } else {\n const text = captionScreen.getDisplayText();\n captionsArray = [{\n start: startTime,\n end: endTime,\n data: text,\n styles: {}\n }];\n }\n if (captionsArray) {\n textTracks.addCaptions(trackIndex, 0, captionsArray);\n }\n }\n return newCue;\n }\n\n /**\n * Extract CEA-608 data from a buffer of data.\n * @param {ArrayBuffer} data\n * @param {Array} samples cue information\n * @returns {Object|null} ccData corresponding to one segment.\n */\n function _extractCea608Data(data, samples) {\n if (samples.length === 0) {\n return null;\n }\n\n const allCcData = {\n splits: [],\n fields: [[], []]\n };\n const raw = new DataView(data);\n for (let i = 0; i < samples.length; i++) {\n const sample = samples[i];\n const cea608Ranges = cea608parser.findCea608Nalus(raw, sample.offset, sample.size);\n let lastSampleTime = null;\n let idx = 0;\n for (let j = 0; j < cea608Ranges.length; j++) {\n const ccData = cea608parser.extractCea608DataFromRange(raw, cea608Ranges[j]);\n for (let k = 0; k < 2; k++) {\n if (ccData[k].length > 0) {\n if (sample.cts !== lastSampleTime) {\n idx = 0;\n } else {\n idx += 1;\n }\n const timestampOffset = _getTimestampOffset();\n allCcData.fields[k].push([sample.cts + (timestampOffset * embeddedTimescale), ccData[k], idx]);\n lastSampleTime = sample.cts;\n }\n }\n }\n }\n\n // Sort by sampleTime ascending order\n // If two packets have the same sampleTime, use them in the order\n // they were received\n allCcData.fields.forEach(function sortField(field) {\n field.sort(function (a, b) {\n if (a[0] === b[0]) {\n return a[2] - b[2];\n }\n return a[0] - b[0];\n });\n });\n\n return allCcData;\n }\n\n function _getTimestampOffset() {\n return !isNaN(instance.timestampOffset) ? instance.timestampOffset : 0;\n }\n\n function getIsDefault(mediaInfo) {\n //TODO How to tag default. currently same order as listed in manifest.\n // Is there a way to mark a text adaptation set as the default one? DASHIF meeting talk about using role which is being used for track KIND\n // Eg subtitles etc. You can have multiple role tags per adaptation Not defined in the spec yet.\n let isDefault = false;\n if (embeddedTracks.length > 1 && mediaInfo.isEmbedded) {\n isDefault = (mediaInfo.id && mediaInfo.id === Constants.CC1); // CC1 if both CC1 and CC3 exist\n } else if (embeddedTracks.length === 1) {\n if (mediaInfo.id && typeof mediaInfo.id === 'string' && mediaInfo.id.substring(0, 2) === 'CC') { // Either CC1 or CC3\n isDefault = true;\n }\n } else if (embeddedTracks.length === 0) {\n isDefault = (mediaInfo.index === mediaInfos[0].index);\n }\n return isDefault;\n }\n\n function getParser(codecType) {\n let parser;\n if (codecType.search(Constants.VTT) >= 0) {\n parser = vttParser;\n } else if (codecType.search(Constants.TTML) >= 0 || codecType.search(Constants.STPP) >= 0) {\n parser = ttmlParser;\n }\n return parser;\n }\n\n function remove(start, end) {\n //if start and end are not defined, remove all\n if ((start === undefined) && (start === end)) {\n start = instance.buffered.start(0);\n end = instance.buffered.end(instance.buffered.length - 1);\n }\n instance.buffered.remove(start, end);\n textTracks.deleteCuesFromTrackIdx(currFragmentedTrackIdx, start, end);\n }\n\n function onVideoBufferCleared(e) {\n embeddedTracks.forEach(function (track) {\n const trackIdx = textTracks.getTrackIdxForId(track.id);\n if (trackIdx >= 0) {\n textTracks.deleteCuesFromTrackIdx(trackIdx, e.from, e.to);\n }\n });\n }\n\n function resetMediaInfos() {\n mediaInfos = [];\n }\n\n instance = {\n initialize,\n addMediaInfos,\n resetMediaInfos,\n getStreamId,\n append,\n abort,\n addEmbeddedTrack,\n resetEmbedded,\n getConfig,\n setCurrentFragmentedTrackIdx,\n remove,\n reset\n };\n\n setup();\n\n return instance;\n}\n\nTextSourceBuffer.__dashjs_factory_name = 'TextSourceBuffer';\nexport default FactoryMaker.getClassFactory(TextSourceBuffer);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Constants from '../constants/Constants';\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\nimport MediaPlayerEvents from '../../streaming/MediaPlayerEvents';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Debug from '../../core/Debug';\nimport {renderHTML} from 'imsc';\n\nfunction TextTracks(config) {\n\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n const videoModel = config.videoModel;\n const streamInfo = config.streamInfo;\n\n let instance,\n logger,\n Cue,\n textTrackQueue,\n nativeTrackElementArr,\n currentTrackIdx,\n actualVideoLeft,\n actualVideoTop,\n actualVideoWidth,\n actualVideoHeight,\n captionContainer,\n videoSizeCheckInterval,\n fullscreenAttribute,\n displayCCOnTop,\n previousISDState,\n topZIndex,\n resizeObserver;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n }\n\n function initialize() {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') {\n return;\n }\n\n Cue = window.VTTCue || window.TextTrackCue;\n textTrackQueue = [];\n nativeTrackElementArr = [];\n currentTrackIdx = -1;\n actualVideoLeft = 0;\n actualVideoTop = 0;\n actualVideoWidth = 0;\n actualVideoHeight = 0;\n captionContainer = null;\n videoSizeCheckInterval = null;\n displayCCOnTop = false;\n topZIndex = 2147483647;\n previousISDState = null;\n\n if (document.fullscreenElement !== undefined) {\n fullscreenAttribute = 'fullscreenElement'; // Standard and Edge\n } else if (document.webkitIsFullScreen !== undefined) {\n fullscreenAttribute = 'webkitIsFullScreen'; // Chrome and Safari (and Edge)\n } else if (document.msFullscreenElement) { // IE11\n fullscreenAttribute = 'msFullscreenElement';\n } else if (document.mozFullScreen) { // Firefox\n fullscreenAttribute = 'mozFullScreen';\n }\n }\n\n function getStreamId() {\n return streamInfo.id;\n }\n\n function _createTrackForUserAgent(element) {\n const kind = element.kind;\n const label = element.id !== undefined ? element.id : element.lang;\n const lang = element.lang;\n const isTTML = element.isTTML;\n const isEmbedded = element.isEmbedded;\n const track = videoModel.addTextTrack(kind, label, lang, isTTML, isEmbedded);\n\n return track;\n }\n\n function addTextTrack(textTrackInfoVO) {\n textTrackQueue.push(textTrackInfoVO);\n }\n\n function createTracks() {\n\n //Sort in same order as in manifest\n textTrackQueue.sort(function (a, b) {\n return a.index - b.index;\n });\n\n captionContainer = videoModel.getTTMLRenderingDiv();\n let defaultIndex = -1;\n for (let i = 0; i < textTrackQueue.length; i++) {\n const track = _createTrackForUserAgent(textTrackQueue[i]);\n\n //used to remove tracks from video element when added manually\n nativeTrackElementArr.push(track);\n\n if (textTrackQueue[i].defaultTrack) {\n // track.default is an object property identifier that is a reserved word\n // The following jshint directive is used to suppressed the warning \"Expected an identifier and instead saw 'default' (a reserved word)\"\n /*jshint -W024 */\n track.default = true;\n defaultIndex = i;\n }\n\n const textTrack = getTrackByIdx(i);\n if (textTrack) {\n //each time a track is created, its mode should be showing by default\n //sometime, it's not on Chrome\n textTrack.mode = Constants.TEXT_SHOWING;\n if (captionContainer && (textTrackQueue[i].isTTML || textTrackQueue[i].isEmbedded)) {\n textTrack.renderingType = 'html';\n } else {\n textTrack.renderingType = 'default';\n }\n }\n\n addCaptions(i, 0, textTrackQueue[i].captionData);\n eventBus.trigger(MediaPlayerEvents.TEXT_TRACK_ADDED);\n }\n\n //set current track index in textTrackQueue array\n setCurrentTrackIdx.call(this, defaultIndex);\n\n if (defaultIndex >= 0) {\n\n let onMetadataLoaded = function () {\n const track = getTrackByIdx(defaultIndex);\n if (track && track.renderingType === 'html') {\n checkVideoSize.call(this, track, true);\n }\n eventBus.off(MediaPlayerEvents.PLAYBACK_METADATA_LOADED, onMetadataLoaded, this);\n };\n\n eventBus.on(MediaPlayerEvents.PLAYBACK_METADATA_LOADED, onMetadataLoaded, this);\n\n for (let idx = 0; idx < textTrackQueue.length; idx++) {\n const videoTextTrack = getTrackByIdx(idx);\n if (videoTextTrack) {\n videoTextTrack.mode = (idx === defaultIndex) ? Constants.TEXT_SHOWING : Constants.TEXT_HIDDEN;\n }\n }\n }\n\n eventBus.trigger(Events.TEXT_TRACKS_QUEUE_INITIALIZED, {\n index: currentTrackIdx,\n tracks: textTrackQueue,\n streamId: streamInfo.id\n });\n }\n\n function getVideoVisibleVideoSize(viewWidth, viewHeight, videoWidth, videoHeight, aspectRatio, use80Percent) {\n const viewAspectRatio = viewWidth / viewHeight;\n const videoAspectRatio = videoWidth / videoHeight;\n\n let videoPictureWidth = 0;\n let videoPictureHeight = 0;\n\n if (viewAspectRatio > videoAspectRatio) {\n videoPictureHeight = viewHeight;\n videoPictureWidth = (videoPictureHeight / videoHeight) * videoWidth;\n } else {\n videoPictureWidth = viewWidth;\n videoPictureHeight = (videoPictureWidth / videoWidth) * videoHeight;\n }\n\n let videoPictureXAspect = 0;\n let videoPictureYAspect = 0;\n let videoPictureWidthAspect = 0;\n let videoPictureHeightAspect = 0;\n const videoPictureAspect = videoPictureWidth / videoPictureHeight;\n\n if (videoPictureAspect > aspectRatio) {\n videoPictureHeightAspect = videoPictureHeight;\n videoPictureWidthAspect = videoPictureHeight * aspectRatio;\n } else {\n videoPictureWidthAspect = videoPictureWidth;\n videoPictureHeightAspect = videoPictureWidth / aspectRatio;\n }\n videoPictureXAspect = (viewWidth - videoPictureWidthAspect) / 2;\n videoPictureYAspect = (viewHeight - videoPictureHeightAspect) / 2;\n\n if (use80Percent) {\n return {\n x: videoPictureXAspect + (videoPictureWidthAspect * 0.1),\n y: videoPictureYAspect + (videoPictureHeightAspect * 0.1),\n w: videoPictureWidthAspect * 0.8,\n h: videoPictureHeightAspect * 0.8\n }; /* Maximal picture size in videos aspect ratio */\n } else {\n return {\n x: videoPictureXAspect,\n y: videoPictureYAspect,\n w: videoPictureWidthAspect,\n h: videoPictureHeightAspect\n }; /* Maximal picture size in videos aspect ratio */\n }\n }\n\n function checkVideoSize(track, forceDrawing) {\n const clientWidth = videoModel.getClientWidth();\n const clientHeight = videoModel.getClientHeight();\n const videoWidth = videoModel.getVideoWidth();\n const videoHeight = videoModel.getVideoHeight();\n const videoOffsetTop = videoModel.getVideoRelativeOffsetTop();\n const videoOffsetLeft = videoModel.getVideoRelativeOffsetLeft();\n\n if (videoWidth !== 0 && videoHeight !== 0) {\n\n let aspectRatio = videoWidth / videoHeight;\n let use80Percent = false;\n if (track.isFromCEA608) {\n // If this is CEA608 then use predefined aspect ratio\n aspectRatio = 3.5 / 3.0;\n use80Percent = true;\n }\n\n const realVideoSize = getVideoVisibleVideoSize.call(this, clientWidth, clientHeight, videoWidth, videoHeight, aspectRatio, use80Percent);\n\n const newVideoWidth = realVideoSize.w;\n const newVideoHeight = realVideoSize.h;\n const newVideoLeft = realVideoSize.x;\n const newVideoTop = realVideoSize.y;\n\n if (newVideoWidth != actualVideoWidth || newVideoHeight != actualVideoHeight || newVideoLeft != actualVideoLeft || newVideoTop != actualVideoTop || forceDrawing) {\n actualVideoLeft = newVideoLeft + videoOffsetLeft;\n actualVideoTop = newVideoTop + videoOffsetTop;\n actualVideoWidth = newVideoWidth;\n actualVideoHeight = newVideoHeight;\n\n if (captionContainer) {\n const containerStyle = captionContainer.style;\n if (containerStyle) {\n containerStyle.left = actualVideoLeft + 'px';\n containerStyle.top = actualVideoTop + 'px';\n containerStyle.width = actualVideoWidth + 'px';\n containerStyle.height = actualVideoHeight + 'px';\n containerStyle.zIndex = (fullscreenAttribute && document[fullscreenAttribute]) || displayCCOnTop ? topZIndex : null;\n eventBus.trigger(MediaPlayerEvents.CAPTION_CONTAINER_RESIZE);\n }\n }\n\n // Video view has changed size, so resize any active cues\n const activeCues = track.activeCues;\n if (activeCues) {\n const len = activeCues.length;\n for (let i = 0; i < len; ++i) {\n const cue = activeCues[i];\n cue.scaleCue(cue);\n }\n }\n }\n }\n }\n\n function scaleCue(activeCue) {\n const videoWidth = actualVideoWidth;\n const videoHeight = actualVideoHeight;\n let key,\n replaceValue,\n valueFontSize,\n valueLineHeight,\n elements;\n\n if (activeCue.cellResolution) {\n const cellUnit = [videoWidth / activeCue.cellResolution[0], videoHeight / activeCue.cellResolution[1]];\n if (activeCue.linePadding) {\n for (key in activeCue.linePadding) {\n if (activeCue.linePadding.hasOwnProperty(key)) {\n const valueLinePadding = activeCue.linePadding[key];\n replaceValue = (valueLinePadding * cellUnit[0]).toString();\n // Compute the CellResolution unit in order to process properties using sizing (fontSize, linePadding, etc).\n const elementsSpan = document.getElementsByClassName('spanPadding');\n for (let i = 0; i < elementsSpan.length; i++) {\n elementsSpan[i].style.cssText = elementsSpan[i].style.cssText.replace(/(padding-left\\s*:\\s*)[\\d.,]+(?=\\s*px)/gi, '$1' + replaceValue);\n elementsSpan[i].style.cssText = elementsSpan[i].style.cssText.replace(/(padding-right\\s*:\\s*)[\\d.,]+(?=\\s*px)/gi, '$1' + replaceValue);\n }\n }\n }\n }\n\n if (activeCue.fontSize) {\n for (key in activeCue.fontSize) {\n if (activeCue.fontSize.hasOwnProperty(key)) {\n if (activeCue.fontSize[key][0] === '%') {\n valueFontSize = activeCue.fontSize[key][1] / 100;\n } else if (activeCue.fontSize[key][0] === 'c') {\n valueFontSize = activeCue.fontSize[key][1];\n }\n\n replaceValue = (valueFontSize * cellUnit[1]).toString();\n\n if (key !== 'defaultFontSize') {\n elements = document.getElementsByClassName(key);\n } else {\n elements = document.getElementsByClassName('paragraph');\n }\n\n for (let j = 0; j < elements.length; j++) {\n elements[j].style.cssText = elements[j].style.cssText.replace(/(font-size\\s*:\\s*)[\\d.,]+(?=\\s*px)/gi, '$1' + replaceValue);\n }\n }\n }\n\n if (activeCue.lineHeight) {\n for (key in activeCue.lineHeight) {\n if (activeCue.lineHeight.hasOwnProperty(key)) {\n if (activeCue.lineHeight[key][0] === '%') {\n valueLineHeight = activeCue.lineHeight[key][1] / 100;\n } else if (activeCue.fontSize[key][0] === 'c') {\n valueLineHeight = activeCue.lineHeight[key][1];\n }\n\n replaceValue = (valueLineHeight * cellUnit[1]).toString();\n elements = document.getElementsByClassName(key);\n for (let k = 0; k < elements.length; k++) {\n elements[k].style.cssText = elements[k].style.cssText.replace(/(line-height\\s*:\\s*)[\\d.,]+(?=\\s*px)/gi, '$1' + replaceValue);\n }\n }\n }\n }\n }\n }\n\n if (activeCue.isd) {\n let htmlCaptionDiv = document.getElementById(activeCue.cueID);\n if (htmlCaptionDiv) {\n captionContainer.removeChild(htmlCaptionDiv);\n }\n renderCaption(activeCue);\n }\n }\n\n function renderCaption(cue) {\n if (captionContainer) {\n const finalCue = document.createElement('div');\n captionContainer.appendChild(finalCue);\n previousISDState = renderHTML(cue.isd, finalCue, function (uri) {\n const imsc1ImgUrnTester = /^(urn:)(mpeg:[a-z0-9][a-z0-9-]{0,31}:)(subs:)([0-9]+)$/;\n const smpteImgUrnTester = /^#(.*)$/;\n if (imsc1ImgUrnTester.test(uri)) {\n const match = imsc1ImgUrnTester.exec(uri);\n const imageId = parseInt(match[4], 10) - 1;\n const imageData = btoa(cue.images[imageId]);\n const dataUrl = 'data:image/png;base64,' + imageData;\n return dataUrl;\n } else if (smpteImgUrnTester.test(uri)) {\n const match = smpteImgUrnTester.exec(uri);\n const imageId = match[1];\n const dataUrl = 'data:image/png;base64,' + cue.embeddedImages[imageId];\n return dataUrl;\n } else {\n return null;\n }\n }, captionContainer.clientHeight, captionContainer.clientWidth, false/*displayForcedOnlyMode*/, function (err) {\n logger.info('renderCaption :', err);\n //TODO add ErrorHandler management\n }, previousISDState, true /*enableRollUp*/);\n finalCue.id = cue.cueID;\n eventBus.trigger(MediaPlayerEvents.CAPTION_RENDERED, { captionDiv: finalCue, currentTrackIdx });\n }\n }\n\n /*\n * Add captions to track, store for later adding, or add captions added before\n */\n function addCaptions(trackIdx, timeOffset, captionData) {\n const track = getTrackByIdx(trackIdx);\n const self = this;\n\n if (!track) {\n return;\n }\n\n if (!Array.isArray(captionData) || captionData.length === 0) {\n return;\n }\n\n for (let item = 0; item < captionData.length; item++) {\n let cue;\n const currentItem = captionData[item];\n\n track.cellResolution = currentItem.cellResolution;\n track.isFromCEA608 = currentItem.isFromCEA608;\n\n if (currentItem.type === 'html' && captionContainer && !isNaN(currentItem.start) && !isNaN(currentItem.end)) {\n cue = new Cue(currentItem.start + timeOffset, currentItem.end + timeOffset, '');\n cue.cueHTMLElement = currentItem.cueHTMLElement;\n cue.isd = currentItem.isd;\n cue.images = currentItem.images;\n cue.embeddedImages = currentItem.embeddedImages;\n cue.cueID = currentItem.cueID;\n cue.scaleCue = scaleCue.bind(self);\n //useful parameters for cea608 subtitles, not for TTML one.\n cue.cellResolution = currentItem.cellResolution;\n cue.lineHeight = currentItem.lineHeight;\n cue.linePadding = currentItem.linePadding;\n cue.fontSize = currentItem.fontSize;\n\n captionContainer.style.left = actualVideoLeft + 'px';\n captionContainer.style.top = actualVideoTop + 'px';\n captionContainer.style.width = actualVideoWidth + 'px';\n captionContainer.style.height = actualVideoHeight + 'px';\n\n cue.onenter = function () {\n if (track.mode === Constants.TEXT_SHOWING) {\n if (this.isd) {\n renderCaption(this);\n logger.debug('Cue enter id:' + this.cueID);\n } else {\n captionContainer.appendChild(this.cueHTMLElement);\n scaleCue.call(self, this);\n eventBus.trigger(MediaPlayerEvents.CAPTION_RENDERED, {\n captionDiv: this.cueHTMLElement,\n currentTrackIdx\n });\n }\n }\n };\n\n cue.onexit = function () {\n if (captionContainer) {\n const divs = captionContainer.childNodes;\n for (let i = 0; i < divs.length; ++i) {\n if (divs[i].id === this.cueID) {\n logger.debug('Cue exit id:' + divs[i].id);\n captionContainer.removeChild(divs[i]);\n --i;\n }\n }\n }\n };\n } else {\n if (currentItem.data && !isNaN(currentItem.start) && !isNaN(currentItem.end)) {\n cue = new Cue(currentItem.start - timeOffset, currentItem.end - timeOffset, currentItem.data);\n if (currentItem.styles) {\n if (currentItem.styles.align !== undefined && 'align' in cue) {\n cue.align = currentItem.styles.align;\n }\n if (currentItem.styles.line !== undefined && 'line' in cue) {\n cue.line = currentItem.styles.line;\n }\n if (currentItem.styles.position !== undefined && 'position' in cue) {\n cue.position = currentItem.styles.position;\n }\n if (currentItem.styles.size !== undefined && 'size' in cue) {\n cue.size = currentItem.styles.size;\n }\n }\n cue.onenter = function () {\n if (track.mode === Constants.TEXT_SHOWING) {\n eventBus.trigger(MediaPlayerEvents.CAPTION_RENDERED, { currentTrackIdx });\n }\n };\n }\n }\n try {\n if (cue) {\n if (!cueInTrack(track, cue)) {\n track.addCue(cue);\n }\n } else {\n logger.error('impossible to display subtitles.');\n }\n } catch (e) {\n // Edge crash, delete everything and start adding again\n // @see https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/11979877/\n deleteTrackCues(track);\n track.addCue(cue);\n throw e;\n }\n }\n }\n\n function getTrackByIdx(idx) {\n return idx >= 0 && textTrackQueue[idx] ?\n videoModel.getTextTrack(textTrackQueue[idx].kind, textTrackQueue[idx].id, textTrackQueue[idx].lang, textTrackQueue[idx].isTTML, textTrackQueue[idx].isEmbedded) : null;\n }\n\n function getCurrentTrackIdx() {\n return currentTrackIdx;\n }\n\n function getTrackIdxForId(trackId) {\n let idx = -1;\n for (let i = 0; i < textTrackQueue.length; i++) {\n if (textTrackQueue[i].id === trackId) {\n idx = i;\n break;\n }\n }\n\n return idx;\n }\n\n function setCurrentTrackIdx(idx) {\n if (idx === currentTrackIdx) {\n return;\n }\n currentTrackIdx = idx;\n const track = getTrackByIdx(currentTrackIdx);\n setCueStyleOnTrack.call(this, track);\n\n if (videoSizeCheckInterval) {\n clearInterval(videoSizeCheckInterval);\n videoSizeCheckInterval = null;\n }\n\n if (track && track.renderingType === 'html') {\n checkVideoSize.call(this, track, true);\n if (window.ResizeObserver) {\n resizeObserver = new window.ResizeObserver(() => {\n checkVideoSize.call(this, track, true);\n });\n resizeObserver.observe(videoModel.getElement());\n } else {\n videoSizeCheckInterval = setInterval(checkVideoSize.bind(this, track), 500);\n }\n }\n }\n\n function setCueStyleOnTrack(track) {\n clearCaptionContainer.call(this);\n if (track) {\n if (track.renderingType === 'html') {\n setNativeCueStyle.call(this);\n } else {\n removeNativeCueStyle.call(this);\n }\n } else {\n removeNativeCueStyle.call(this);\n }\n }\n\n function cueInTrack(track, cue) {\n if (!track.cues) return false;\n for (let i = 0; i < track.cues.length; i++) {\n if ((track.cues[i].startTime === cue.startTime) &&\n (track.cues[i].endTime === cue.endTime)) {\n return true;\n }\n }\n return false;\n }\n\n function cueInRange(cue, start, end) {\n return (isNaN(start) || cue.startTime >= start) && (isNaN(end) || cue.endTime <= end);\n }\n\n function deleteTrackCues(track, start, end) {\n if (track.cues) {\n const cues = track.cues;\n const lastIdx = cues.length - 1;\n\n for (let r = lastIdx; r >= 0; r--) {\n if (cueInRange(cues[r], start, end)) {\n if (cues[r].onexit) {\n cues[r].onexit();\n }\n track.removeCue(cues[r]);\n }\n }\n }\n }\n\n function deleteCuesFromTrackIdx(trackIdx, start, end) {\n const track = getTrackByIdx(trackIdx);\n if (track) {\n deleteTrackCues(track, start, end);\n }\n }\n\n function deleteAllTextTracks() {\n const ln = nativeTrackElementArr ? nativeTrackElementArr.length : 0;\n for (let i = 0; i < ln; i++) {\n const track = getTrackByIdx(i);\n if (track) {\n deleteTrackCues.call(this, track, streamInfo.start, streamInfo.start + streamInfo.duration);\n }\n }\n nativeTrackElementArr = [];\n textTrackQueue = [];\n if (videoSizeCheckInterval) {\n clearInterval(videoSizeCheckInterval);\n videoSizeCheckInterval = null;\n }\n if (resizeObserver && videoModel) {\n resizeObserver.unobserve(videoModel.getElement());\n resizeObserver = null;\n }\n currentTrackIdx = -1;\n clearCaptionContainer.call(this);\n }\n\n function deleteTextTrack(idx) {\n videoModel.removeChild(nativeTrackElementArr[idx]);\n nativeTrackElementArr.splice(idx, 1);\n }\n\n /* Set native cue style to transparent background to avoid it being displayed. */\n function setNativeCueStyle() {\n let styleElement = document.getElementById('native-cue-style');\n if (styleElement) {\n return; //Already set\n }\n\n styleElement = document.createElement('style');\n styleElement.id = 'native-cue-style';\n document.head.appendChild(styleElement);\n const stylesheet = styleElement.sheet;\n const video = videoModel.getElement();\n try {\n if (video) {\n if (video.id) {\n stylesheet.insertRule('#' + video.id + '::cue {background: transparent}', 0);\n } else if (video.classList.length !== 0) {\n stylesheet.insertRule('.' + video.className + '::cue {background: transparent}', 0);\n } else {\n stylesheet.insertRule('video::cue {background: transparent}', 0);\n }\n }\n } catch (e) {\n logger.info('' + e.message);\n }\n }\n\n /* Remove the extra cue style with transparent background for native cues. */\n function removeNativeCueStyle() {\n const styleElement = document.getElementById('native-cue-style');\n if (styleElement) {\n document.head.removeChild(styleElement);\n }\n }\n\n function clearCaptionContainer() {\n if (captionContainer) {\n while (captionContainer.firstChild) {\n captionContainer.removeChild(captionContainer.firstChild);\n }\n }\n }\n\n function setModeForTrackIdx(idx, mode) {\n const track = getTrackByIdx(idx);\n if (track && track.mode !== mode) {\n track.mode = mode;\n }\n }\n\n function getCurrentTrackInfo() {\n return textTrackQueue[currentTrackIdx];\n }\n\n instance = {\n initialize,\n getStreamId,\n addTextTrack,\n addCaptions,\n createTracks,\n getCurrentTrackIdx,\n setCurrentTrackIdx,\n getTrackIdxForId,\n getCurrentTrackInfo,\n setModeForTrackIdx,\n deleteCuesFromTrackIdx,\n deleteAllTextTracks,\n deleteTextTrack\n };\n\n setup();\n\n return instance;\n}\n\nTextTracks.__dashjs_factory_name = 'TextTracks';\nexport default FactoryMaker.getClassFactory(TextTracks);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Debug from '../../core/Debug';\n\nconst WEBVTT = 'WEBVTT';\n\nfunction VTTParser() {\n const context = this.context;\n\n let instance,\n logger,\n regExNewLine,\n regExToken,\n regExWhiteSpace,\n regExWhiteSpaceWordBoundary;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n regExNewLine = /(?:\\r\\n|\\r|\\n)/gm;\n regExToken = /-->/;\n regExWhiteSpace = /(^[\\s]+|[\\s]+$)/g;\n regExWhiteSpaceWordBoundary = /\\s\\b/g;\n }\n\n function parse(data) {\n const captionArray = [];\n let len,\n lastStartTime;\n\n if (!data) {\n return captionArray;\n }\n\n data = data.split( regExNewLine );\n len = data.length;\n lastStartTime = -1;\n\n for (let i = 0 ; i < len; i++) {\n let item = data[i];\n\n if (item.length > 0 && item !== WEBVTT) {\n if (item.match(regExToken)) {\n const attributes = parseItemAttributes(item);\n const cuePoints = attributes.cuePoints;\n const styles = attributes.styles;\n const text = getSublines(data, i + 1);\n const startTime = convertCuePointTimes(cuePoints[0].replace(regExWhiteSpace, ''));\n const endTime = convertCuePointTimes(cuePoints[1].replace(regExWhiteSpace, ''));\n\n if ((!isNaN(startTime) && !isNaN(endTime)) && startTime >= lastStartTime && endTime > startTime) {\n if (text !== '') {\n lastStartTime = startTime;\n //TODO Make VO external so other parsers can use.\n captionArray.push({\n start: startTime,\n end: endTime,\n data: text,\n styles: styles\n });\n }\n else {\n logger.error('Skipping cue due to empty/malformed cue text');\n }\n }\n else {\n logger.error('Skipping cue due to incorrect cue timing');\n }\n }\n }\n }\n\n return captionArray;\n }\n\n function convertCuePointTimes(time) {\n const timeArray = time.split(':');\n const len = timeArray.length - 1;\n\n time = parseInt( timeArray[len - 1], 10 ) * 60 + parseFloat( timeArray[len]);\n\n if ( len === 2 ) {\n time += parseInt( timeArray[0], 10 ) * 3600;\n }\n\n return time;\n }\n\n function parseItemAttributes(data) {\n const vttCuePoints = data.split(regExToken);\n const arr = vttCuePoints[1].split(regExWhiteSpaceWordBoundary);\n arr.shift(); //remove first array index it is empty...\n vttCuePoints[1] = arr[0];\n arr.shift();\n return {cuePoints: vttCuePoints, styles: getCaptionStyles(arr)};\n }\n\n function getCaptionStyles(arr) {\n const styleObject = {};\n arr.forEach(function (element) {\n if (element.split(/:/).length > 1) {\n let val = element.split(/:/)[1];\n if (val && val.search(/%/) != -1) {\n val = parseInt(val.replace(/%/, ''), 10);\n }\n if (element.match(/align/) || element.match(/A/)) {\n styleObject.align = val;\n }\n if (element.match(/line/) || element.match(/L/) ) {\n styleObject.line = val;\n }\n if (element.match(/position/) || element.match(/P/) ) {\n styleObject.position = val;\n }\n if (element.match(/size/) || element.match(/S/)) {\n styleObject.size = val;\n }\n }\n });\n\n return styleObject;\n }\n\n /*\n * VTT can have multiple lines to display per cuepoint.\n */\n function getSublines(data, idx) {\n let i = idx;\n\n let subline = '';\n let lineData = '';\n let lineCount;\n\n while (data[i] !== '' && i < data.length) {\n i++;\n }\n\n lineCount = i - idx;\n if (lineCount > 1) {\n for (let j = 0; j < lineCount; j++) {\n lineData = data[(idx + j)];\n if (!lineData.match(regExToken)) {\n subline += lineData;\n if (j !== lineCount - 1) {\n subline += '\\n';\n }\n }\n else {\n // caption text should not have '-->' in it\n subline = '';\n break;\n }\n }\n } else {\n lineData = data[idx];\n if (!lineData.match(regExToken))\n subline = lineData;\n }\n return subline;\n }\n\n instance = {\n parse: parse\n };\n\n setup();\n return instance;\n}\nVTTParser.__dashjs_factory_name = 'VTTParser';\nexport default FactoryMaker.getSingletonFactory(VTTParser);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Debug from '../../core/Debug';\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\nimport {fromXML, generateISD} from 'imsc';\nimport MediaPlayerEvents from '../MediaPlayerEvents';\nimport ConformanceViolationConstants from '../constants/ConformanceViolationConstants';\n\nfunction TTMLParser() {\n\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n\n /*\n * This TTML parser follows \"EBU-TT-D SUBTITLING DISTRIBUTION FORMAT - tech3380\" spec - https://tech.ebu.ch/docs/tech/tech3380.pdf.\n * */\n let instance,\n logger;\n\n let cueCounter = 0; // Used to give every cue a unique ID.\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n }\n\n function getCueID() {\n const id = 'cue_TTML_' + cueCounter;\n cueCounter++;\n return id;\n }\n\n /**\n * Parse the raw data and process it to return the HTML element representing the cue.\n * Return the region to be processed and controlled (hide/show) by the caption controller.\n * @param {string} data - raw data received from the TextSourceBuffer\n * @param {number} offsetTime - offset time to apply to cue time\n * @param {integer} startTimeSegment - startTime for the current segment\n * @param {integer} endTimeSegment - endTime for the current segment\n * @param {Array} images - images array referenced by subs MP4 box\n */\n function parse(data, offsetTime, startTimeSegment, endTimeSegment, images) {\n let errorMsg = '';\n const captionArray = [];\n let startTime,\n endTime,\n i;\n\n const content = {};\n\n const embeddedImages = {};\n let currentImageId = '';\n let accumulated_image_data = '';\n let metadataHandler = {\n\n onOpenTag: function (ns, name, attrs) {\n // cope with existing non-compliant content\n if (attrs[' imagetype'] && !attrs[' imageType']) {\n eventBus.trigger(MediaPlayerEvents.CONFORMANCE_VIOLATION, {\n level: ConformanceViolationConstants.LEVELS.ERROR,\n event: ConformanceViolationConstants.EVENTS.NON_COMPLIANT_SMPTE_IMAGE_ATTRIBUTE\n });\n attrs[' imageType'] = attrs[' imagetype'];\n }\n\n if (name === 'image' &&\n (ns === 'http://www.smpte-ra.org/schemas/2052-1/2010/smpte-tt' ||\n ns === 'http://www.smpte-ra.org/schemas/2052-1/2013/smpte-tt')) {\n if (!attrs[' imageType'] || attrs[' imageType'].value !== 'PNG') {\n logger.warn('smpte-tt imageType != PNG. Discarded');\n return;\n }\n currentImageId = attrs['http://www.w3.org/XML/1998/namespace id'].value;\n }\n },\n\n onCloseTag: function () {\n if (currentImageId) {\n embeddedImages[currentImageId] = accumulated_image_data.trim();\n }\n accumulated_image_data = '';\n currentImageId = '';\n },\n\n onText: function (contents) {\n if (currentImageId) {\n accumulated_image_data = accumulated_image_data + contents;\n }\n }\n };\n\n if (!data) {\n errorMsg = 'no ttml data to parse';\n throw new Error(errorMsg);\n }\n\n content.data = data;\n\n eventBus.trigger(Events.TTML_TO_PARSE, content);\n\n const imsc1doc = fromXML(content.data, function (msg) {\n errorMsg = msg;\n }, metadataHandler);\n\n eventBus.trigger(Events.TTML_PARSED, { ttmlString: content.data, ttmlDoc: imsc1doc });\n\n const mediaTimeEvents = imsc1doc.getMediaTimeEvents();\n\n for (i = 0; i < mediaTimeEvents.length; i++) {\n let isd = generateISD(imsc1doc, mediaTimeEvents[i], function (error) {\n errorMsg = error;\n });\n\n if (isd.contents.some(topLevelContents => topLevelContents.contents.length)) {\n //be sure that mediaTimeEvents values are in the mp4 segment time ranges.\n startTime = (mediaTimeEvents[i] + offsetTime) < startTimeSegment ? startTimeSegment : (mediaTimeEvents[i] + offsetTime);\n endTime = (mediaTimeEvents[i + 1] + offsetTime) > endTimeSegment ? endTimeSegment : (mediaTimeEvents[i + 1] + offsetTime);\n\n if (startTime < endTime) {\n captionArray.push({\n start: startTime,\n end: endTime,\n type: 'html',\n cueID: getCueID(),\n isd: isd,\n images: images,\n embeddedImages: embeddedImages\n });\n }\n }\n }\n\n if (errorMsg !== '') {\n logger.error(errorMsg);\n throw new Error(errorMsg);\n }\n\n return captionArray;\n }\n\n instance = {\n parse: parse\n };\n\n setup();\n return instance;\n}\n\nTTMLParser.__dashjs_factory_name = 'TTMLParser';\nexport default FactoryMaker.getSingletonFactory(TTMLParser);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Constants from '../constants/Constants';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport TextSourceBuffer from './TextSourceBuffer';\nimport TextTracks from './TextTracks';\nimport VTTParser from '../utils/VTTParser';\nimport TTMLParser from '../utils/TTMLParser';\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\nimport MediaPlayerEvents from '../../streaming/MediaPlayerEvents';\nimport {checkParameterType} from '../utils/SupervisorTools';\n\nfunction TextController(config) {\n\n let context = this.context;\n\n const adapter = config.adapter;\n const errHandler = config.errHandler;\n const manifestModel = config.manifestModel;\n const mediaController = config.mediaController;\n const videoModel = config.videoModel;\n const settings = config.settings;\n\n let instance,\n streamData,\n textSourceBuffers,\n textTracks,\n vttParser,\n ttmlParser,\n eventBus,\n defaultSettings,\n initialSettingsSet,\n allTracksAreDisabled,\n forceTextStreaming,\n textTracksAdded,\n disableTextBeforeTextTracksAdded;\n\n function setup() {\n defaultSettings = null;\n forceTextStreaming = false;\n textTracksAdded = false;\n initialSettingsSet = false;\n disableTextBeforeTextTracksAdded = false;\n\n vttParser = VTTParser(context).getInstance();\n ttmlParser = TTMLParser(context).getInstance();\n eventBus = EventBus(context).getInstance();\n\n resetInitialSettings();\n }\n\n function initialize() {\n eventBus.on(Events.CURRENT_TRACK_CHANGED, _onCurrentTrackChanged, instance);\n eventBus.on(Events.TEXT_TRACKS_QUEUE_INITIALIZED, _onTextTracksAdded, instance);\n }\n\n function initializeForStream(streamInfo) {\n const streamId = streamInfo.id;\n const tracks = TextTracks(context).create({\n videoModel,\n streamInfo\n });\n tracks.initialize();\n textTracks[streamId] = tracks;\n\n const textSourceBuffer = TextSourceBuffer(context).create({\n errHandler,\n adapter,\n manifestModel,\n mediaController,\n videoModel,\n textTracks: tracks,\n vttParser,\n ttmlParser,\n streamInfo\n });\n textSourceBuffer.initialize();\n textSourceBuffers[streamId] = textSourceBuffer;\n\n streamData[streamId] = {};\n streamData[streamId].lastEnabledIndex = -1;\n }\n\n /**\n * All media infos have been added. Start creating the track objects\n * @param {object} streamInfo\n */\n function createTracks(streamInfo) {\n const streamId = streamInfo.id;\n\n if (!textTracks[streamId]) {\n return;\n }\n textTracks[streamId].createTracks();\n }\n\n /**\n * Adds the new mediaInfo objects to the textSourceBuffer.\n * @param {object} streamInfo\n * @param {array} mInfos\n * @param {string|null} mimeType\n * @param {object} fragmentModel\n */\n function addMediaInfosToBuffer(streamInfo, type, mInfos, fragmentModel = null) {\n const streamId = streamInfo.id;\n\n if (!textSourceBuffers[streamId]) {\n return;\n }\n textSourceBuffers[streamId].addMediaInfos(type, mInfos, fragmentModel);\n }\n\n function getTextSourceBuffer(streamInfo) {\n const streamId = streamInfo.id;\n\n if (textSourceBuffers && textSourceBuffers[streamId]) {\n return textSourceBuffers[streamId];\n }\n }\n\n function getAllTracksAreDisabled() {\n return allTracksAreDisabled;\n }\n\n function addEmbeddedTrack(streamInfo, mediaInfo) {\n const streamId = streamInfo.id;\n\n if (!textSourceBuffers[streamId]) {\n return;\n }\n\n textSourceBuffers[streamId].addEmbeddedTrack(mediaInfo);\n }\n\n function setInitialSettings(settings) {\n defaultSettings = settings;\n initialSettingsSet = true;\n }\n\n function _onTextTracksAdded(e) {\n let tracks = e.tracks;\n let index = e.index;\n const streamId = e.streamId;\n\n const textDefaultEnabled = settings.get().streaming.text.defaultEnabled;\n\n if ((textDefaultEnabled === false && !isTextEnabled()) || disableTextBeforeTextTracksAdded) {\n // disable text at startup if explicitly configured with setTextDefaultEnabled(false) or if there is no defaultSettings (configuration or from domStorage)\n setTextTrack(streamId, -1);\n } else {\n if (defaultSettings) {\n tracks.some((item, idx) => {\n // matchSettings is compatible with setTextDefaultLanguage and setInitialSettings\n if (mediaController.matchSettings(defaultSettings, item)) {\n setTextTrack(streamId, idx);\n index = idx;\n return true;\n }\n });\n }\n allTracksAreDisabled = false;\n }\n\n streamData[streamId].lastEnabledIndex = index;\n\n eventBus.trigger(MediaPlayerEvents.TEXT_TRACKS_ADDED, {\n enabled: isTextEnabled(),\n index: index,\n tracks: tracks,\n streamId\n });\n\n textTracksAdded = true;\n }\n\n function _onCurrentTrackChanged(event) {\n if (!initialSettingsSet && event && event.newMediaInfo) {\n let mediaInfo = event.newMediaInfo;\n if (mediaInfo.type === Constants.TEXT) {\n defaultSettings = {\n lang: mediaInfo.lang,\n role: mediaInfo.roles[0],\n index: mediaInfo.index,\n codec: mediaInfo.codec,\n accessibility: mediaInfo.accessibility[0]\n };\n }\n }\n }\n\n function enableText(streamId, enable) {\n checkParameterType(enable, 'boolean');\n if (isTextEnabled() !== enable) {\n // change track selection\n if (enable) {\n // apply last enabled track\n setTextTrack(streamId, streamData[streamId].lastEnabledIndex);\n }\n\n if (!enable) {\n // keep last index and disable text track\n streamData[streamId].lastEnabledIndex = getCurrentTrackIdx(streamId);\n if (!textTracksAdded) {\n disableTextBeforeTextTracksAdded = true;\n } else {\n setTextTrack(streamId, -1);\n }\n }\n }\n }\n\n function isTextEnabled() {\n let enabled = true;\n if (allTracksAreDisabled && !forceTextStreaming) {\n enabled = false;\n }\n return enabled;\n }\n\n // when set to true ScheduleController will allow schedule of chunks even if tracks are all disabled. Allowing streaming to hidden track for external players to work with.\n function enableForcedTextStreaming(enable) {\n checkParameterType(enable, 'boolean');\n forceTextStreaming = enable;\n }\n\n function setTextTrack(streamId, idx) {\n // For external time text file, the only action needed to change a track is marking the track mode to showing.\n // Fragmented text tracks need the additional step of calling TextController.setTextTrack();\n allTracksAreDisabled = idx === -1;\n\n if (allTracksAreDisabled && mediaController) {\n mediaController.saveTextSettingsDisabled();\n }\n\n let oldTrackIdx = getCurrentTrackIdx(streamId);\n\n // No change, no action required\n if (oldTrackIdx === idx || !textTracks[streamId]) {\n return;\n }\n\n textTracks[streamId].setModeForTrackIdx(oldTrackIdx, Constants.TEXT_HIDDEN);\n textTracks[streamId].setCurrentTrackIdx(idx);\n textTracks[streamId].setModeForTrackIdx(idx, Constants.TEXT_SHOWING);\n\n let currentTrackInfo = textTracks[streamId].getCurrentTrackInfo();\n\n if (currentTrackInfo && currentTrackInfo.isFragmented && !currentTrackInfo.isEmbedded) {\n _setFragmentedTextTrack(streamId, currentTrackInfo, oldTrackIdx);\n } else if (currentTrackInfo && !currentTrackInfo.isFragmented) {\n _setNonFragmentedTextTrack(streamId, currentTrackInfo);\n }\n\n mediaController.setTrack(currentTrackInfo);\n }\n\n function _setFragmentedTextTrack(streamId, currentTrackInfo, oldTrackIdx) {\n\n if (!textSourceBuffers[streamId]) {\n return;\n }\n\n let config = textSourceBuffers[streamId].getConfig();\n let fragmentedTracks = config.fragmentedTracks;\n\n for (let i = 0; i < fragmentedTracks.length; i++) {\n let mediaInfo = fragmentedTracks[i];\n if (currentTrackInfo.lang === mediaInfo.lang &&\n (mediaInfo.id ? currentTrackInfo.id === mediaInfo.id : currentTrackInfo.index === mediaInfo.index)) {\n let currentFragTrack = mediaController.getCurrentTrackFor(Constants.TEXT, streamId);\n if (mediaInfo.id ? currentFragTrack.id !== mediaInfo.id : currentFragTrack.index !== mediaInfo.index) {\n textTracks[streamId].deleteCuesFromTrackIdx(oldTrackIdx);\n textSourceBuffers[streamId].setCurrentFragmentedTrackIdx(i);\n } else if (oldTrackIdx === -1) {\n // in fragmented use case, if the user selects the older track (the one selected before disabled text track)\n // no CURRENT_TRACK_CHANGED event will be triggered because the mediaInfo in the StreamProcessor is equal to the one we are selecting\n // For that reason we reactivate the StreamProcessor and the ScheduleController\n eventBus.trigger(Events.SET_FRAGMENTED_TEXT_AFTER_DISABLED, {}, {\n streamId,\n mediaType: Constants.TEXT\n });\n }\n }\n }\n }\n\n function _setNonFragmentedTextTrack(streamId, currentTrackInfo) {\n eventBus.trigger(Events.SET_NON_FRAGMENTED_TEXT, {\n currentTrackInfo\n }, {\n streamId,\n mediaType: Constants.TEXT\n });\n }\n\n function getCurrentTrackIdx(streamId) {\n return textTracks[streamId].getCurrentTrackIdx();\n }\n\n function deactivateStream(streamInfo) {\n if (!streamInfo) {\n return;\n }\n const streamId = streamInfo.id;\n\n if (textSourceBuffers[streamId]) {\n textSourceBuffers[streamId].resetMediaInfos();\n }\n\n if (textTracks[streamId]) {\n textTracks[streamId].deleteAllTextTracks();\n }\n }\n\n function resetInitialSettings() {\n textSourceBuffers = {};\n textTracks = {};\n streamData = {};\n allTracksAreDisabled = true;\n textTracksAdded = false;\n disableTextBeforeTextTracksAdded = false;\n }\n\n function reset() {\n resetInitialSettings();\n eventBus.off(Events.CURRENT_TRACK_CHANGED, _onCurrentTrackChanged, instance);\n eventBus.off(Events.TEXT_TRACKS_QUEUE_INITIALIZED, _onTextTracksAdded, instance);\n\n Object.keys(textSourceBuffers).forEach((key) => {\n textSourceBuffers[key].resetEmbedded();\n textSourceBuffers[key].reset();\n });\n }\n\n instance = {\n deactivateStream,\n initialize,\n initializeForStream,\n createTracks,\n getTextSourceBuffer,\n getAllTracksAreDisabled,\n addEmbeddedTrack,\n setInitialSettings,\n enableText,\n isTextEnabled,\n setTextTrack,\n getCurrentTrackIdx,\n enableForcedTextStreaming,\n addMediaInfosToBuffer,\n reset\n };\n setup();\n return instance;\n}\n\nTextController.__dashjs_factory_name = 'TextController';\nexport default FactoryMaker.getClassFactory(TextController);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport cea608parser from '../../externals/cea608-parser';\nimport Constants from './constants/Constants';\nimport DashConstants from '../dash/constants/DashConstants';\nimport MetricsConstants from './constants/MetricsConstants';\nimport PlaybackController from './controllers/PlaybackController';\nimport StreamController from './controllers/StreamController';\nimport GapController from './controllers/GapController';\nimport MediaController from './controllers/MediaController';\nimport BaseURLController from './controllers/BaseURLController';\nimport ManifestLoader from './ManifestLoader';\nimport ErrorHandler from './utils/ErrorHandler';\nimport Capabilities from './utils/Capabilities';\nimport CapabilitiesFilter from './utils/CapabilitiesFilter';\nimport RequestModifier from './utils/RequestModifier';\nimport URIFragmentModel from './models/URIFragmentModel';\nimport ManifestModel from './models/ManifestModel';\nimport MediaPlayerModel from './models/MediaPlayerModel';\nimport AbrController from './controllers/AbrController';\nimport SchemeLoaderFactory from './net/SchemeLoaderFactory';\nimport VideoModel from './models/VideoModel';\nimport CmcdModel from './models/CmcdModel';\nimport DOMStorage from './utils/DOMStorage';\nimport Debug from './../core/Debug';\nimport Errors from './../core/errors/Errors';\nimport EventBus from './../core/EventBus';\nimport Events from './../core/events/Events';\nimport MediaPlayerEvents from './MediaPlayerEvents';\nimport FactoryMaker from '../core/FactoryMaker';\nimport Settings from '../core/Settings';\nimport {\n getVersionString\n}\n from '../core/Version';\n\n//Dash\nimport SegmentBaseController from '../dash/controllers/SegmentBaseController';\nimport DashAdapter from '../dash/DashAdapter';\nimport DashMetrics from '../dash/DashMetrics';\nimport TimelineConverter from '../dash/utils/TimelineConverter';\nimport {\n HTTPRequest\n} from './vo/metrics/HTTPRequest';\nimport BASE64 from '../../externals/base64';\nimport ISOBoxer from 'codem-isoboxer';\nimport DashJSError from './vo/DashJSError';\nimport {checkParameterType} from './utils/SupervisorTools';\nimport ManifestUpdater from './ManifestUpdater';\nimport URLUtils from '../streaming/utils/URLUtils';\nimport BoxParser from './utils/BoxParser';\nimport TextController from './text/TextController';\n\n/**\n * The media types\n * @typedef {(\"video\" | \"audio\" | \"text\" | \"image\")} MediaType\n */\n\n/**\n * @module MediaPlayer\n * @description The MediaPlayer is the primary dash.js Module and a Facade to build your player around.\n * It will allow you access to all the important dash.js properties/methods via the public API and all the\n * events to build a robust DASH media player.\n */\nfunction MediaPlayer() {\n /**\n * @constant {string} STREAMING_NOT_INITIALIZED_ERROR error string thrown when a function is called before the dash.js has been fully initialized\n * @inner\n */\n const STREAMING_NOT_INITIALIZED_ERROR = 'You must first call initialize() and set a source before calling this method';\n /**\n * @constant {string} PLAYBACK_NOT_INITIALIZED_ERROR error string thrown when a function is called before the dash.js has been fully initialized\n * @inner\n */\n const PLAYBACK_NOT_INITIALIZED_ERROR = 'You must first call initialize() and set a valid source and view before calling this method';\n /**\n * @constant {string} ELEMENT_NOT_ATTACHED_ERROR error string thrown when a function is called before the dash.js has received a reference of an HTML5 video element\n * @inner\n */\n const ELEMENT_NOT_ATTACHED_ERROR = 'You must first call attachView() to set the video element before calling this method';\n /**\n * @constant {string} SOURCE_NOT_ATTACHED_ERROR error string thrown when a function is called before the dash.js has received a valid source stream.\n * @inner\n */\n const SOURCE_NOT_ATTACHED_ERROR = 'You must first call attachSource() with a valid source before calling this method';\n /**\n * @constant {string} MEDIA_PLAYER_NOT_INITIALIZED_ERROR error string thrown when a function is called before the dash.js has been fully initialized.\n * @inner\n */\n const MEDIA_PLAYER_NOT_INITIALIZED_ERROR = 'MediaPlayer not initialized!';\n\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n let settings = Settings(context).getInstance();\n const debug = Debug(context).getInstance({ settings: settings });\n\n let instance,\n logger,\n source,\n protectionData,\n mediaPlayerInitialized,\n streamingInitialized,\n playbackInitialized,\n autoPlay,\n abrController,\n schemeLoaderFactory,\n timelineConverter,\n mediaController,\n protectionController,\n metricsReportingController,\n mssHandler,\n offlineController,\n adapter,\n mediaPlayerModel,\n errHandler,\n baseURLController,\n capabilities,\n capabilitiesFilter,\n streamController,\n textController,\n gapController,\n playbackController,\n dashMetrics,\n manifestModel,\n cmcdModel,\n videoModel,\n uriFragmentModel,\n domStorage,\n segmentBaseController,\n licenseRequestFilters,\n licenseResponseFilters,\n customCapabilitiesFilters;\n\n /*\n ---------------------------------------------------------------------------\n\n INIT FUNCTIONS\n\n ---------------------------------------------------------------------------\n */\n function setup() {\n logger = debug.getLogger(instance);\n mediaPlayerInitialized = false;\n playbackInitialized = false;\n streamingInitialized = false;\n autoPlay = true;\n protectionController = null;\n offlineController = null;\n protectionData = null;\n adapter = null;\n segmentBaseController = null;\n Events.extend(MediaPlayerEvents);\n mediaPlayerModel = MediaPlayerModel(context).getInstance();\n videoModel = VideoModel(context).getInstance();\n uriFragmentModel = URIFragmentModel(context).getInstance();\n licenseRequestFilters = [];\n licenseResponseFilters = [];\n customCapabilitiesFilters = [];\n }\n\n /**\n * Configure media player with customs controllers. Helpful for tests\n *\n * @param {object=} config controllers configuration\n * @memberof module:MediaPlayer\n * @instance\n */\n function setConfig(config) {\n if (!config) {\n return;\n }\n if (config.capabilities) {\n capabilities = config.capabilities;\n }\n if (config.capabilitiesFilter) {\n capabilitiesFilter = config.capabilitiesFilter;\n }\n if (config.streamController) {\n streamController = config.streamController;\n }\n if (config.textController) {\n textController = config.textController;\n }\n if (config.gapController) {\n gapController = config.gapController;\n }\n if (config.playbackController) {\n playbackController = config.playbackController;\n }\n if (config.mediaPlayerModel) {\n mediaPlayerModel = config.mediaPlayerModel;\n }\n if (config.abrController) {\n abrController = config.abrController;\n }\n if (config.schemeLoaderFactory) {\n schemeLoaderFactory = config.schemeLoaderFactory;\n }\n if (config.mediaController) {\n mediaController = config.mediaController;\n }\n if (config.settings) {\n settings = config.settings;\n }\n }\n\n /**\n * Upon creating the MediaPlayer you must call initialize before you call anything else.\n * There is one exception to this rule. It is crucial to call {@link module:MediaPlayer#extend extend()}\n * with all your extensions prior to calling initialize.\n *\n * ALL arguments are optional and there are individual methods to set each argument later on.\n * The args in this method are just for convenience and should only be used for a simple player setup.\n *\n * @param {HTML5MediaElement=} view - Optional arg to set the video element. {@link module:MediaPlayer#attachView attachView()}\n * @param {string=} source - Optional arg to set the media source. {@link module:MediaPlayer#attachSource attachSource()}\n * @param {boolean=} AutoPlay - Optional arg to set auto play. {@link module:MediaPlayer#setAutoPlay setAutoPlay()}\n * @see {@link module:MediaPlayer#attachView attachView()}\n * @see {@link module:MediaPlayer#attachSource attachSource()}\n * @see {@link module:MediaPlayer#setAutoPlay setAutoPlay()}\n * @memberof module:MediaPlayer\n * @instance\n */\n function initialize(view, source, AutoPlay) {\n if (!capabilities) {\n capabilities = Capabilities(context).getInstance();\n capabilities.setConfig({\n settings\n })\n }\n\n if (!errHandler) {\n errHandler = ErrorHandler(context).getInstance();\n }\n\n if (!capabilities.supportsMediaSource()) {\n errHandler.error(new DashJSError(Errors.CAPABILITY_MEDIASOURCE_ERROR_CODE, Errors.CAPABILITY_MEDIASOURCE_ERROR_MESSAGE));\n return;\n }\n\n if (!mediaPlayerInitialized) {\n mediaPlayerInitialized = true;\n\n // init some controllers and models\n timelineConverter = TimelineConverter(context).getInstance();\n if (!abrController) {\n abrController = AbrController(context).getInstance();\n abrController.setConfig({\n settings: settings\n });\n }\n\n if (!schemeLoaderFactory) {\n schemeLoaderFactory = SchemeLoaderFactory(context).getInstance();\n }\n\n if (!playbackController) {\n playbackController = PlaybackController(context).getInstance();\n }\n\n if (!mediaController) {\n mediaController = MediaController(context).getInstance();\n }\n\n if (!streamController) {\n streamController = StreamController(context).getInstance();\n }\n\n if (!gapController) {\n gapController = GapController(context).getInstance();\n }\n\n if (!capabilitiesFilter) {\n capabilitiesFilter = CapabilitiesFilter(context).getInstance();\n }\n\n adapter = DashAdapter(context).getInstance();\n\n manifestModel = ManifestModel(context).getInstance();\n\n cmcdModel = CmcdModel(context).getInstance();\n\n dashMetrics = DashMetrics(context).getInstance({\n settings: settings\n });\n\n domStorage = DOMStorage(context).getInstance({\n settings: settings\n });\n\n adapter.setConfig({\n constants: Constants,\n cea608parser: cea608parser,\n errHandler: errHandler,\n BASE64: BASE64\n });\n\n if (!baseURLController) {\n baseURLController = BaseURLController(context).create();\n }\n\n baseURLController.setConfig({\n adapter: adapter\n });\n\n if (!segmentBaseController) {\n segmentBaseController = SegmentBaseController(context).getInstance({\n dashMetrics: dashMetrics,\n mediaPlayerModel: mediaPlayerModel,\n errHandler: errHandler,\n baseURLController: baseURLController,\n events: Events,\n eventBus: eventBus,\n debug: debug,\n boxParser: BoxParser(context).getInstance(),\n requestModifier: RequestModifier(context).getInstance(),\n errors: Errors\n });\n }\n\n // configure controllers\n mediaController.setConfig({\n domStorage: domStorage,\n settings: settings\n });\n\n restoreDefaultUTCTimingSources();\n setAutoPlay(AutoPlay !== undefined ? AutoPlay : true);\n\n // Detect and initialize offline module to support offline contents playback\n _detectOffline();\n }\n\n if (view) {\n attachView(view);\n }\n\n if (source) {\n attachSource(source);\n }\n\n logger.info('[dash.js ' + getVersion() + '] ' + 'MediaPlayer has been initialized');\n }\n\n /**\n * Sets the MPD source and the video element to null. You can also reset the MediaPlayer by\n * calling attachSource with a new source file.\n *\n * This call does not destroy the MediaPlayer. To destroy the MediaPlayer and free all of its\n * memory, call destroy().\n *\n * @memberof module:MediaPlayer\n * @instance\n */\n function reset() {\n attachSource(null);\n attachView(null);\n protectionData = null;\n if (protectionController) {\n protectionController.reset();\n protectionController = null;\n }\n if (metricsReportingController) {\n metricsReportingController.reset();\n metricsReportingController = null;\n }\n\n settings.reset();\n\n if (offlineController) {\n offlineController.reset();\n offlineController = null;\n }\n }\n\n /**\n * Completely destroys the media player and frees all memory.\n *\n * @memberof module:MediaPlayer\n * @instance\n */\n function destroy() {\n reset();\n licenseRequestFilters = [];\n licenseResponseFilters = [];\n customCapabilitiesFilters = [];\n FactoryMaker.deleteSingletonInstances(context);\n }\n\n /**\n * The ready state of the MediaPlayer based on both the video element and MPD source being defined.\n *\n * @returns {boolean} The current ready state of the MediaPlayer\n * @see {@link module:MediaPlayer#attachView attachView()}\n * @see {@link module:MediaPlayer#attachSource attachSource()}\n * @memberof module:MediaPlayer\n * @instance\n */\n function isReady() {\n return (!!source && !!videoModel.getElement());\n }\n\n /**\n * Use the on method to listen for public events found in MediaPlayer.events. {@link MediaPlayerEvents}\n *\n * @param {string} type - {@link MediaPlayerEvents}\n * @param {Function} listener - callback method when the event fires.\n * @param {Object} scope - context of the listener so it can be removed properly.\n * @param {Object} options - object to define various options such as priority and mode\n * @memberof module:MediaPlayer\n * @instance\n */\n function on(type, listener, scope, options) {\n eventBus.on(type, listener, scope, options);\n }\n\n /**\n * Use the off method to remove listeners for public events found in MediaPlayer.events. {@link MediaPlayerEvents}\n *\n * @param {string} type - {@link MediaPlayerEvents}\n * @param {Function} listener - callback method when the event fires.\n * @param {Object} scope - context of the listener so it can be removed properly.\n * @memberof module:MediaPlayer\n * @instance\n */\n function off(type, listener, scope) {\n eventBus.off(type, listener, scope);\n }\n\n /**\n * Current version of Dash.js\n * @returns {string} the current dash.js version string.\n * @memberof module:MediaPlayer\n * @instance\n */\n function getVersion() {\n return getVersionString();\n }\n\n /**\n * Use this method to access the dash.js logging class.\n *\n * @returns {Debug}\n * @memberof module:MediaPlayer\n * @instance\n */\n function getDebug() {\n return debug;\n }\n\n /*\n ---------------------------------------------------------------------------\n\n PLAYBACK FUNCTIONS\n\n ---------------------------------------------------------------------------\n */\n\n /**\n * The play method initiates playback of the media defined by the {@link module:MediaPlayer#attachSource attachSource()} method.\n * This method will call play on the native Video Element.\n *\n * @see {@link module:MediaPlayer#attachSource attachSource()}\n * @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @memberof module:MediaPlayer\n * @instance\n */\n function play() {\n if (!playbackInitialized) {\n throw PLAYBACK_NOT_INITIALIZED_ERROR;\n }\n if (!autoPlay || (isPaused() && playbackInitialized)) {\n playbackController.play();\n }\n }\n\n /**\n * This method will call pause on the native Video Element.\n *\n * @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @memberof module:MediaPlayer\n * @instance\n */\n function pause() {\n if (!playbackInitialized) {\n throw PLAYBACK_NOT_INITIALIZED_ERROR;\n }\n playbackController.pause();\n }\n\n /**\n * Returns a Boolean that indicates whether the Video Element is paused.\n * @return {boolean}\n * @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @memberof module:MediaPlayer\n * @instance\n */\n function isPaused() {\n if (!playbackInitialized) {\n throw PLAYBACK_NOT_INITIALIZED_ERROR;\n }\n return playbackController.isPaused();\n }\n\n /**\n * Sets the currentTime property of the attached video element. If it is a live stream with a\n * timeShiftBufferLength, then the DVR window offset will be automatically calculated.\n *\n * @param {number} value - A relative time, in seconds, based on the return value of the {@link module:MediaPlayer#duration duration()} method is expected\n * @see {@link module:MediaPlayer#getDVRSeekOffset getDVRSeekOffset()}\n * @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @throws {@link Constants#BAD_ARGUMENT_ERROR BAD_ARGUMENT_ERROR} if called with an invalid argument, not number type or is NaN.\n * @memberof module:MediaPlayer\n * @instance\n */\n function seek(value) {\n if (!playbackInitialized) {\n throw PLAYBACK_NOT_INITIALIZED_ERROR;\n }\n\n checkParameterType(value, 'number');\n\n if (isNaN(value)) {\n throw Constants.BAD_ARGUMENT_ERROR;\n }\n\n let s = playbackController.getIsDynamic() ? getDVRSeekOffset(value) : value;\n playbackController.seek(s);\n }\n\n /**\n * Returns a Boolean that indicates whether the media is in the process of seeking to a new position.\n * @return {boolean}\n * @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @memberof module:MediaPlayer\n * @instance\n */\n function isSeeking() {\n if (!playbackInitialized) {\n throw PLAYBACK_NOT_INITIALIZED_ERROR;\n }\n return playbackController.isSeeking();\n }\n\n /**\n * Returns a Boolean that indicates whether the media is in the process of dynamic.\n * @return {boolean}\n * @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @memberof module:MediaPlayer\n * @instance\n */\n function isDynamic() {\n if (!playbackInitialized) {\n throw PLAYBACK_NOT_INITIALIZED_ERROR;\n }\n return playbackController.getIsDynamic();\n }\n\n /**\n * Use this method to set the native Video Element's playback rate.\n * @param {number} value\n * @memberof module:MediaPlayer\n * @instance\n */\n function setPlaybackRate(value) {\n getVideoElement().playbackRate = value;\n }\n\n /**\n * Returns the current playback rate.\n * @returns {number}\n * @memberof module:MediaPlayer\n * @instance\n */\n function getPlaybackRate() {\n return getVideoElement().playbackRate;\n }\n\n /**\n * Use this method to set the native Video Element's muted state. Takes a Boolean that determines whether audio is muted. true if the audio is muted and false otherwise.\n * @param {boolean} value\n * @memberof module:MediaPlayer\n * @throws {@link Constants#BAD_ARGUMENT_ERROR BAD_ARGUMENT_ERROR} if called with an invalid argument, not boolean type.\n * @instance\n */\n function setMute(value) {\n checkParameterType(value, 'boolean');\n getVideoElement().muted = value;\n }\n\n /**\n * A Boolean that determines whether audio is muted.\n * @returns {boolean}\n * @memberof module:MediaPlayer\n * @instance\n */\n function isMuted() {\n return getVideoElement().muted;\n }\n\n /**\n * A double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest).\n * @param {number} value\n * @memberof module:MediaPlayer\n * @throws {@link Constants#BAD_ARGUMENT_ERROR BAD_ARGUMENT_ERROR} if called with an invalid argument, not number type, or is NaN or not between 0 and 1.\n * @instance\n */\n function setVolume(value) {\n if (typeof value !== 'number' || isNaN(value) || value < 0.0 || value > 1.0) {\n throw Constants.BAD_ARGUMENT_ERROR;\n }\n getVideoElement().volume = value;\n }\n\n /**\n * Returns the current audio volume, from 0.0 (silent) to 1.0 (loudest).\n * @returns {number}\n * @memberof module:MediaPlayer\n * @instance\n */\n function getVolume() {\n return getVideoElement().volume;\n }\n\n /**\n * The length of the buffer for a given media type, in seconds. Valid media\n * types are \"video\", \"audio\" and \"text\". If no type is passed\n * in, then the minimum of video, audio and text buffer length is\n * returned. NaN is returned if an invalid type is requested, the\n * presentation does not contain that type, or if no arguments are passed\n * and the presentation does not include any adaption sets of valid media\n * type.\n *\n * @param {MediaType} type - 'video', 'audio' or 'text'\n * @returns {number} The length of the buffer for the given media type, in\n * seconds, or NaN\n * @memberof module:MediaPlayer\n * @instance\n */\n function getBufferLength(type) {\n const types = [Constants.VIDEO, Constants.AUDIO, Constants.TEXT];\n if (!type) {\n const buffer = types.map(\n t => getTracksFor(t).length > 0 ? getDashMetrics().getCurrentBufferLevel(t) : Number.MAX_VALUE\n ).reduce(\n (p, c) => Math.min(p, c)\n );\n return buffer === Number.MAX_VALUE ? NaN : buffer;\n } else {\n if (types.indexOf(type) !== -1) {\n const buffer = getDashMetrics().getCurrentBufferLevel(type);\n return buffer ? buffer : NaN;\n } else {\n logger.warn('getBufferLength requested for invalid type');\n return NaN;\n }\n }\n }\n\n /**\n * The timeShiftBufferLength (DVR Window), in seconds.\n *\n * @returns {number} The window of allowable play time behind the live point of a live stream as defined in the manifest.\n * @memberof module:MediaPlayer\n * @instance\n */\n function getDVRWindowSize() {\n const type = streamController && streamController.hasVideoTrack() ? Constants.VIDEO : Constants.AUDIO;\n let metric = dashMetrics.getCurrentDVRInfo(type);\n if (!metric) {\n return 0;\n }\n return metric.manifestInfo.dvrWindowSize;\n }\n\n /**\n * This method should only be used with a live stream that has a valid timeShiftBufferLength (DVR Window).\n * NOTE - If you do not need the raw offset value (i.e. media analytics, tracking, etc) consider using the {@link module:MediaPlayer#seek seek()} method\n * which will calculate this value for you and set the video element's currentTime property all in one simple call.\n *\n * @param {number} value - A relative time, in seconds, based on the return value of the {@link module:MediaPlayer#duration duration()} method is expected.\n * @returns {number} A value that is relative the available range within the timeShiftBufferLength (DVR Window).\n * @see {@link module:MediaPlayer#seek seek()}\n * @memberof module:MediaPlayer\n * @instance\n */\n function getDVRSeekOffset(value) {\n const type = streamController && streamController.hasVideoTrack() ? Constants.VIDEO : Constants.AUDIO;\n let metric = dashMetrics.getCurrentDVRInfo(type);\n if (!metric) {\n return 0;\n }\n\n let liveDelay = playbackController.getLiveDelay();\n\n let val = metric.range.start + value;\n\n if (val > (metric.range.end - liveDelay)) {\n val = metric.range.end - liveDelay;\n }\n\n return val;\n }\n\n /**\n * Current time of the playhead, in seconds.\n *\n * If called with no arguments then the returned time value is time elapsed since the start point of the first stream, or if it is a live stream, then the time will be based on the return value of the {@link module:MediaPlayer#duration duration()} method.\n * However if a stream ID is supplied then time is relative to the start of that stream, or is null if there is no such stream id in the manifest.\n *\n * @param {string} streamId - The ID of a stream that the returned playhead time must be relative to the start of. If undefined, then playhead time is relative to the first stream.\n * @returns {number} The current playhead time of the media, or null.\n * @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @memberof module:MediaPlayer\n * @instance\n */\n function time(streamId) {\n if (!playbackInitialized) {\n throw PLAYBACK_NOT_INITIALIZED_ERROR;\n }\n let t = getVideoElement().currentTime;\n\n if (streamId !== undefined) {\n t = streamController.getTimeRelativeToStreamId(t, streamId);\n } else if (playbackController.getIsDynamic()) {\n const type = streamController && streamController.hasVideoTrack() ? Constants.VIDEO : Constants.AUDIO;\n let metric = dashMetrics.getCurrentDVRInfo(type);\n t = (metric === null || t === 0) ? 0 : Math.max(0, (t - metric.range.start));\n }\n\n return t;\n }\n\n /**\n * Duration of the media's playback, in seconds.\n *\n * @returns {number} The current duration of the media. For a dynamic stream this will return DVRWindow.end - DVRWindow.start\n * @memberof module:MediaPlayer\n * @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @instance\n */\n function duration() {\n if (!playbackInitialized) {\n throw PLAYBACK_NOT_INITIALIZED_ERROR;\n }\n let d = getVideoElement().duration;\n\n if (playbackController.getIsDynamic()) {\n const type = streamController && streamController.hasVideoTrack() ? Constants.VIDEO : Constants.AUDIO;\n let metric = dashMetrics.getCurrentDVRInfo(type);\n d = metric ? (metric.range.end - metric.range.start) : 0;\n }\n return d;\n }\n\n /**\n * Use this method to get the current playhead time as an absolute value, the time in seconds since midnight UTC, Jan 1 1970.\n * Note - this property only has meaning for live streams. If called before play() has begun, it will return a value of NaN.\n *\n * @returns {number} The current playhead time as UTC timestamp.\n * @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @memberof module:MediaPlayer\n * @instance\n */\n function timeAsUTC() {\n if (!playbackInitialized) {\n throw PLAYBACK_NOT_INITIALIZED_ERROR;\n }\n if (time() < 0) {\n return NaN;\n }\n return _getAsUTC(time());\n }\n\n /**\n * Use this method to get the current duration as an absolute value, the time in seconds since midnight UTC, Jan 1 1970.\n * Note - this property only has meaning for live streams.\n *\n * @returns {number} The current duration as UTC timestamp.\n * @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @memberof module:MediaPlayer\n * @instance\n */\n function durationAsUTC() {\n if (!playbackInitialized) {\n throw PLAYBACK_NOT_INITIALIZED_ERROR;\n }\n return _getAsUTC(duration());\n }\n\n /*\n ---------------------------------------------------------------------------\n\n AUTO BITRATE\n\n ---------------------------------------------------------------------------\n */\n /**\n * Gets the top quality BitrateInfo checking portal limit and max allowed.\n * It calls getMaxAllowedIndexFor internally\n *\n * @param {MediaType} type - 'video' or 'audio'\n * @memberof module:MediaPlayer\n * @returns {BitrateInfo | null}\n * @throws {@link module:MediaPlayer~STREAMING_NOT_INITIALIZED_ERROR STREAMING_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @instance\n */\n function getTopBitrateInfoFor(type) {\n if (!streamingInitialized) {\n throw STREAMING_NOT_INITIALIZED_ERROR;\n }\n return abrController.getTopBitrateInfoFor(type);\n }\n\n /**\n * Gets the current download quality for media type video, audio or images. For video and audio types the ABR\n * rules update this value before every new download unless autoSwitchBitrate is set to false. For 'image'\n * type, thumbnails, there is no ABR algorithm and quality is set manually.\n *\n * @param {MediaType} type - 'video', 'audio' or 'image' (thumbnails)\n * @returns {number} the quality index, 0 corresponding to the lowest bitrate\n * @memberof module:MediaPlayer\n * @see {@link module:MediaPlayer#setQualityFor setQualityFor()}\n * @throws {@link module:MediaPlayer~STREAMING_NOT_INITIALIZED_ERROR STREAMING_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @instance\n */\n function getQualityFor(type) {\n if (!streamingInitialized) {\n throw STREAMING_NOT_INITIALIZED_ERROR;\n }\n if (type === Constants.IMAGE) {\n const activeStream = getActiveStream();\n if (!activeStream) {\n return -1;\n }\n const thumbnailController = activeStream.getThumbnailController();\n\n return !thumbnailController ? -1 : thumbnailController.getCurrentTrackIndex();\n }\n return abrController.getQualityFor(type);\n }\n\n /**\n * Sets the current quality for media type instead of letting the ABR Heuristics automatically selecting it.\n * This value will be overwritten by the ABR rules unless autoSwitchBitrate is set to false.\n *\n * @param {MediaType} type - 'video', 'audio' or 'image'\n * @param {number} value - the quality index, 0 corresponding to the lowest bitrate\n * @param {boolean} forceReplace - true if segments have to be replaced by segments of the new quality\n * @memberof module:MediaPlayer\n * @see {@link module:MediaPlayer#getQualityFor getQualityFor()}\n * @throws {@link module:MediaPlayer~STREAMING_NOT_INITIALIZED_ERROR STREAMING_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @instance\n */\n function setQualityFor(type, value, forceReplace = false) {\n if (!streamingInitialized) {\n throw STREAMING_NOT_INITIALIZED_ERROR;\n }\n if (type === Constants.IMAGE) {\n const activeStream = getActiveStream();\n if (!activeStream) {\n return;\n }\n const thumbnailController = activeStream.getThumbnailController();\n if (thumbnailController) {\n thumbnailController.setTrackByIndex(value);\n }\n }\n abrController.setPlaybackQuality(type, streamController.getActiveStreamInfo(), value, { forceReplace });\n }\n\n /**\n * Update the video element size variables\n * Should be called on window resize (or any other time player is resized). Fullscreen does trigger a window resize event.\n *\n * Once windowResizeEventCalled = true, abrController.checkPortalSize() will use element size variables rather than querying clientWidth every time.\n *\n * @memberof module:MediaPlayer\n * @instance\n */\n function updatePortalSize() {\n abrController.setElementSize();\n abrController.setWindowResizeEventCalled(true);\n }\n\n /*\n ---------------------------------------------------------------------------\n\n MEDIA PLAYER CONFIGURATION\n\n ---------------------------------------------------------------------------\n */\n /**\n * <p>Set to false to prevent stream from auto-playing when the view is attached.</p>\n *\n * @param {boolean} value\n * @default true\n * @memberof module:MediaPlayer\n * @see {@link module:MediaPlayer#attachView attachView()}\n * @throws {@link Constants#BAD_ARGUMENT_ERROR BAD_ARGUMENT_ERROR} if called with an invalid argument, not boolean type.\n * @instance\n *\n */\n function setAutoPlay(value) {\n checkParameterType(value, 'boolean');\n autoPlay = value;\n }\n\n /**\n * @returns {boolean} The current autoPlay state.\n * @memberof module:MediaPlayer\n * @instance\n */\n function getAutoPlay() {\n return autoPlay;\n }\n\n /**\n * @memberof module:MediaPlayer\n * @instance\n * @returns {number|NaN} Current live stream latency in seconds. It is the difference between now time and time position at the playback head.\n * @throws {@link module:MediaPlayer~MEDIA_PLAYER_NOT_INITIALIZED_ERROR MEDIA_PLAYER_NOT_INITIALIZED_ERROR} if called before initialize function\n */\n function getCurrentLiveLatency() {\n if (!mediaPlayerInitialized) {\n throw MEDIA_PLAYER_NOT_INITIALIZED_ERROR;\n }\n\n if (!playbackInitialized) {\n return NaN;\n }\n\n return playbackController.getCurrentLiveLatency();\n }\n\n /**\n * Add a custom ABR Rule\n * Rule will be apply on next stream if a stream is being played\n *\n * @param {string} type - rule type (one of ['qualitySwitchRules','abandonFragmentRules'])\n * @param {string} rulename - name of rule (used to identify custom rule). If one rule of same name has been added, then existing rule will be updated\n * @param {object} rule - the rule object instance\n * @memberof module:MediaPlayer\n * @throws {@link Constants#BAD_ARGUMENT_ERROR BAD_ARGUMENT_ERROR} if called with invalid arguments.\n * @instance\n */\n function addABRCustomRule(type, rulename, rule) {\n mediaPlayerModel.addABRCustomRule(type, rulename, rule);\n }\n\n /**\n * Remove a custom ABR Rule\n *\n * @param {string} rulename - name of the rule to be removed\n * @memberof module:MediaPlayer\n * @instance\n */\n function removeABRCustomRule(rulename) {\n mediaPlayerModel.removeABRCustomRule(rulename);\n }\n\n /**\n * Remove all custom rules\n * @memberof module:MediaPlayer\n * @instance\n */\n function removeAllABRCustomRule() {\n mediaPlayerModel.removeABRCustomRule();\n }\n\n /**\n * <p>Allows you to set a scheme and server source for UTC live edge detection for dynamic streams.\n * If UTCTiming is defined in the manifest, it will take precedence over any time source manually added.</p>\n * <p>If you have exposed the Date header, use the method {@link module:MediaPlayer#clearDefaultUTCTimingSources clearDefaultUTCTimingSources()}.\n * This will allow the date header on the manifest to be used instead of a time server</p>\n * @param {string} schemeIdUri - <ul>\n * <li>urn:mpeg:dash:utc:http-head:2014</li>\n * <li>urn:mpeg:dash:utc:http-xsdate:2014</li>\n * <li>urn:mpeg:dash:utc:http-iso:2014</li>\n * <li>urn:mpeg:dash:utc:direct:2014</li>\n * </ul>\n * <p>Some specs referencing early ISO23009-1 drafts incorrectly use\n * 2012 in the URI, rather than 2014. support these for now.</p>\n * <ul>\n * <li>urn:mpeg:dash:utc:http-head:2012</li>\n * <li>urn:mpeg:dash:utc:http-xsdate:2012</li>\n * <li>urn:mpeg:dash:utc:http-iso:2012</li>\n * <li>urn:mpeg:dash:utc:direct:2012</li>\n * </ul>\n * @param {string} value - Path to a time source.\n * @default\n * <ul>\n * <li>schemeIdUri:urn:mpeg:dash:utc:http-xsdate:2014</li>\n * <li>value:http://time.akamai.com/?iso&ms/li>\n * </ul>\n * @memberof module:MediaPlayer\n * @see {@link module:MediaPlayer#removeUTCTimingSource removeUTCTimingSource()}\n * @instance\n */\n function addUTCTimingSource(schemeIdUri, value) {\n mediaPlayerModel.addUTCTimingSource(schemeIdUri, value);\n }\n\n /**\n * <p>Allows you to remove a UTC time source. Both schemeIdUri and value need to match the Dash.vo.UTCTiming properties in order for the\n * entry to be removed from the array</p>\n * @param {string} schemeIdUri - see {@link module:MediaPlayer#addUTCTimingSource addUTCTimingSource()}\n * @param {string} value - see {@link module:MediaPlayer#addUTCTimingSource addUTCTimingSource()}\n * @memberof module:MediaPlayer\n * @see {@link module:MediaPlayer#clearDefaultUTCTimingSources clearDefaultUTCTimingSources()}\n * @throws {@link Constants#BAD_ARGUMENT_ERROR BAD_ARGUMENT_ERROR} if called with invalid arguments, schemeIdUri and value are not string type.\n * @instance\n */\n function removeUTCTimingSource(schemeIdUri, value) {\n mediaPlayerModel.removeUTCTimingSource(schemeIdUri, value);\n }\n\n /**\n * <p>Allows you to clear the stored array of time sources.</p>\n * <p>Example use: If you have exposed the Date header, calling this method\n * will allow the date header on the manifest to be used instead of the time server.</p>\n * <p>Example use: Calling this method, assuming there is not an exposed date header on the manifest, will default back\n * to using a binary search to discover the live edge</p>\n *\n * @memberof module:MediaPlayer\n * @see {@link module:MediaPlayer#restoreDefaultUTCTimingSources restoreDefaultUTCTimingSources()}\n * @instance\n */\n function clearDefaultUTCTimingSources() {\n mediaPlayerModel.clearDefaultUTCTimingSources();\n }\n\n /**\n * <p>Allows you to restore the default time sources after calling {@link module:MediaPlayer#clearDefaultUTCTimingSources clearDefaultUTCTimingSources()}</p>\n *\n * @default\n * <ul>\n * <li>schemeIdUri:urn:mpeg:dash:utc:http-xsdate:2014</li>\n * <li>value:http://time.akamai.com/?iso&ms</li>\n * </ul>\n *\n * @memberof module:MediaPlayer\n * @see {@link module:MediaPlayer#addUTCTimingSource addUTCTimingSource()}\n * @instance\n */\n function restoreDefaultUTCTimingSources() {\n mediaPlayerModel.restoreDefaultUTCTimingSources();\n }\n\n /**\n * Returns the average throughput computed in the ABR logic\n *\n * @param {MediaType} type\n * @return {number} value\n * @memberof module:MediaPlayer\n * @instance\n */\n function getAverageThroughput(type) {\n const throughputHistory = abrController.getThroughputHistory();\n const isDynamic = playbackController.getIsDynamic();\n\n return throughputHistory ? throughputHistory.getAverageThroughput(type, isDynamic) : 0;\n }\n\n /**\n * Sets whether withCredentials on XHR requests for a particular request\n * type is true or false\n *\n * @default false\n * @param {string} type - one of HTTPRequest.*_TYPE\n * @param {boolean} value\n * @memberof module:MediaPlayer\n * @instance\n */\n function setXHRWithCredentialsForType(type, value) {\n mediaPlayerModel.setXHRWithCredentialsForType(type, value);\n }\n\n /**\n * Gets whether withCredentials on XHR requests for a particular request\n * type is true or false\n *\n * @param {string} type - one of HTTPRequest.*_TYPE\n * @return {boolean}\n * @memberof module:MediaPlayer\n * @instance\n */\n function getXHRWithCredentialsForType(type) {\n return mediaPlayerModel.getXHRWithCredentialsForType(type);\n }\n\n /*\n ---------------------------------------------------------------------------\n\n OFFLINE\n\n ---------------------------------------------------------------------------\n */\n\n /**\n * Detects if Offline is included and returns an instance of OfflineController.js\n * @memberof module:MediaPlayer\n * @instance\n */\n function getOfflineController() {\n return _detectOffline();\n }\n\n /*\n ---------------------------------------------------------------------------\n\n METRICS\n\n ---------------------------------------------------------------------------\n */\n /**\n * Returns the DashMetrics.js Module. You use this Module to get access to all the public metrics\n * stored in dash.js\n *\n * @see {@link module:DashMetrics}\n * @returns {Object}\n * @memberof module:MediaPlayer\n * @instance\n */\n function getDashMetrics() {\n return dashMetrics;\n }\n\n /*\n ---------------------------------------------------------------------------\n\n TEXT MANAGEMENT\n\n ---------------------------------------------------------------------------\n */\n\n /**\n * Enable/disable text\n * When enabling text, dash will choose the previous selected text track\n *\n * @param {boolean} enable - true to enable text, false otherwise (same as setTextTrack(-1))\n * @memberof module:MediaPlayer\n * @instance\n */\n function enableText(enable) {\n const activeStreamInfo = streamController.getActiveStreamInfo();\n\n if (!activeStreamInfo || !textController) {\n return false;\n }\n\n return textController.enableText(activeStreamInfo.id, enable);\n }\n\n /**\n * Enable/disable text\n * When enabling dash will keep downloading and process fragmented text tracks even if all tracks are in mode \"hidden\"\n *\n * @param {boolean} enable - true to enable text streaming even if all text tracks are hidden.\n * @memberof module:MediaPlayer\n * @instance\n */\n function enableForcedTextStreaming(enable) {\n const activeStreamInfo = streamController.getActiveStreamInfo();\n\n if (!activeStreamInfo || !textController) {\n return false;\n }\n\n return textController.enableForcedTextStreaming(enable);\n }\n\n /**\n * Return if text is enabled\n *\n * @return {boolean} return true if text is enabled, false otherwise\n * @memberof module:MediaPlayer\n * @instance\n */\n function isTextEnabled() {\n const activeStreamInfo = streamController.getActiveStreamInfo();\n\n if (!activeStreamInfo || !textController) {\n return false;\n }\n\n return textController.isTextEnabled(activeStreamInfo);\n }\n\n /**\n * Use this method to change the current text track for both external time text files and fragmented text tracks. There is no need to\n * set the track mode on the video object to switch a track when using this method.\n * @param {number} idx - Index of track based on the order of the order the tracks are added Use -1 to disable all tracks. (turn captions off). Use module:MediaPlayer#dashjs.MediaPlayer.events.TEXT_TRACK_ADDED.\n * @see {@link MediaPlayerEvents#event:TEXT_TRACK_ADDED dashjs.MediaPlayer.events.TEXT_TRACK_ADDED}\n * @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @memberof module:MediaPlayer\n * @instance\n */\n function setTextTrack(idx) {\n if (!playbackInitialized) {\n throw PLAYBACK_NOT_INITIALIZED_ERROR;\n }\n\n const activeStreamInfo = streamController.getActiveStreamInfo();\n\n if (!activeStreamInfo || !textController) {\n return;\n }\n\n textController.setTextTrack(activeStreamInfo.id, idx);\n }\n\n function getCurrentTextTrackIndex() {\n let idx = NaN;\n\n const activeStreamInfo = streamController.getActiveStreamInfo();\n\n if (!activeStreamInfo || !textController) {\n return;\n }\n\n idx = textController.getCurrentTrackIdx(activeStreamInfo.id);\n\n return idx;\n }\n\n /*\n ---------------------------------------------------------------------------\n\n VIDEO ELEMENT MANAGEMENT\n\n ---------------------------------------------------------------------------\n */\n\n /**\n * Returns instance of Video Element that was attached by calling attachView()\n * @returns {Object}\n * @memberof module:MediaPlayer\n * @throws {@link module:MediaPlayer~ELEMENT_NOT_ATTACHED_ERROR ELEMENT_NOT_ATTACHED_ERROR} if called before attachView function\n * @instance\n */\n function getVideoElement() {\n if (!videoModel.getElement()) {\n throw ELEMENT_NOT_ATTACHED_ERROR;\n }\n return videoModel.getElement();\n }\n\n /**\n * Use this method to attach an HTML5 VideoElement for dash.js to operate upon.\n *\n * @param {Object} element - An HTMLMediaElement that has already been defined in the DOM (or equivalent stub).\n * @memberof module:MediaPlayer\n * @throws {@link module:MediaPlayer~MEDIA_PLAYER_NOT_INITIALIZED_ERROR MEDIA_PLAYER_NOT_INITIALIZED_ERROR} if called before initialize function\n * @instance\n */\n function attachView(element) {\n if (!mediaPlayerInitialized) {\n throw MEDIA_PLAYER_NOT_INITIALIZED_ERROR;\n }\n\n videoModel.setElement(element);\n\n if (element) {\n _detectProtection();\n _detectMetricsReporting();\n _detectMss();\n\n if (streamController) {\n streamController.switchToVideoElement();\n }\n }\n\n if (playbackInitialized) { //Reset if we have been playing before, so this is a new element.\n _resetPlaybackControllers();\n }\n\n _initializePlayback();\n }\n\n /**\n * Returns instance of Div that was attached by calling attachTTMLRenderingDiv()\n * @returns {Object}\n * @memberof module:MediaPlayer\n * @instance\n */\n function getTTMLRenderingDiv() {\n return videoModel ? videoModel.getTTMLRenderingDiv() : null;\n }\n\n /**\n * Use this method to attach an HTML5 div for dash.js to render rich TTML subtitles.\n *\n * @param {HTMLDivElement} div - An unstyled div placed after the video element. It will be styled to match the video size and overlay z-order.\n * @memberof module:MediaPlayer\n * @throws {@link module:MediaPlayer~ELEMENT_NOT_ATTACHED_ERROR ELEMENT_NOT_ATTACHED_ERROR} if called before attachView function\n * @instance\n */\n function attachTTMLRenderingDiv(div) {\n if (!videoModel.getElement()) {\n throw ELEMENT_NOT_ATTACHED_ERROR;\n }\n videoModel.setTTMLRenderingDiv(div);\n }\n\n /*\n ---------------------------------------------------------------------------\n\n STREAM AND TRACK MANAGEMENT\n\n ---------------------------------------------------------------------------\n */\n /**\n * @param {MediaType} type\n * @returns {Array}\n * @memberof module:MediaPlayer\n * @throws {@link module:MediaPlayer~STREAMING_NOT_INITIALIZED_ERROR STREAMING_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @instance\n */\n function getBitrateInfoListFor(type) {\n if (!streamingInitialized) {\n throw STREAMING_NOT_INITIALIZED_ERROR;\n }\n let stream = getActiveStream();\n return stream ? stream.getBitrateListFor(type) : [];\n }\n\n /**\n * This method returns the list of all available streams from a given manifest\n * @param {Object} manifest\n * @returns {Array} list of {@link StreamInfo}\n * @memberof module:MediaPlayer\n * @throws {@link module:MediaPlayer~STREAMING_NOT_INITIALIZED_ERROR STREAMING_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @instance\n */\n function getStreamsFromManifest(manifest) {\n if (!streamingInitialized) {\n throw STREAMING_NOT_INITIALIZED_ERROR;\n }\n return adapter.getStreamsInfo(manifest);\n }\n\n /**\n * This method returns the list of all available tracks for a given media type\n * @param {MediaType} type\n * @returns {Array} list of {@link MediaInfo}\n * @memberof module:MediaPlayer\n * @throws {@link module:MediaPlayer~STREAMING_NOT_INITIALIZED_ERROR STREAMING_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @instance\n */\n function getTracksFor(type) {\n if (!streamingInitialized) {\n throw STREAMING_NOT_INITIALIZED_ERROR;\n }\n let streamInfo = streamController.getActiveStreamInfo();\n\n if (!streamInfo) {\n return [];\n }\n\n return mediaController.getTracksFor(type, streamInfo.id);\n }\n\n /**\n * This method returns the list of all available tracks for a given media type and streamInfo from a given manifest\n * @param {MediaType} type\n * @param {Object} manifest\n * @param {Object} streamInfo\n * @returns {Array} list of {@link MediaInfo}\n * @memberof module:MediaPlayer\n * @throws {@link module:MediaPlayer~STREAMING_NOT_INITIALIZED_ERROR STREAMING_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @instance\n */\n function getTracksForTypeFromManifest(type, manifest, streamInfo) {\n if (!streamingInitialized) {\n throw STREAMING_NOT_INITIALIZED_ERROR;\n }\n\n streamInfo = streamInfo || adapter.getStreamsInfo(manifest, 1)[0];\n\n return streamInfo ? adapter.getAllMediaInfoForType(streamInfo, type, manifest) : [];\n }\n\n /**\n * @param {MediaType} type\n * @returns {Object|null} {@link MediaInfo}\n *\n * @memberof module:MediaPlayer\n * @throws {@link module:MediaPlayer~STREAMING_NOT_INITIALIZED_ERROR STREAMING_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @instance\n */\n function getCurrentTrackFor(type) {\n if (!streamingInitialized) {\n throw STREAMING_NOT_INITIALIZED_ERROR;\n }\n let streamInfo = streamController.getActiveStreamInfo();\n return mediaController.getCurrentTrackFor(type, streamInfo.id);\n }\n\n /**\n * This method allows to set media settings that will be used to pick the initial track. Format of the settings\n * is following: <br />\n * {lang: langValue (can be either a string or a regex to match),\n * index: indexValue,\n * viewpoint: viewpointValue,\n * audioChannelConfiguration: audioChannelConfigurationValue,\n * accessibility: accessibilityValue,\n * role: roleValue}\n *\n * @param {MediaType} type\n * @param {Object} value\n * @memberof module:MediaPlayer\n * @throws {@link module:MediaPlayer~MEDIA_PLAYER_NOT_INITIALIZED_ERROR MEDIA_PLAYER_NOT_INITIALIZED_ERROR} if called before initialize function\n * @instance\n */\n function setInitialMediaSettingsFor(type, value) {\n if (!mediaPlayerInitialized) {\n throw MEDIA_PLAYER_NOT_INITIALIZED_ERROR;\n }\n mediaController.setInitialSettings(type, value);\n }\n\n /**\n * This method returns media settings that is used to pick the initial track. Format of the settings\n * is following:\n * {lang: langValue,\n * index: indexValue,\n * viewpoint: viewpointValue,\n * audioChannelConfiguration: audioChannelConfigurationValue,\n * accessibility: accessibilityValue,\n * role: roleValue}\n * @param {MediaType} type\n * @returns {Object}\n * @memberof module:MediaPlayer\n * @throws {@link module:MediaPlayer~MEDIA_PLAYER_NOT_INITIALIZED_ERROR MEDIA_PLAYER_NOT_INITIALIZED_ERROR} if called before initialize function\n * @instance\n */\n function getInitialMediaSettingsFor(type) {\n if (!mediaPlayerInitialized) {\n throw MEDIA_PLAYER_NOT_INITIALIZED_ERROR;\n }\n return mediaController.getInitialSettings(type);\n }\n\n /**\n * @param {MediaInfo} track - instance of {@link MediaInfo}\n * @memberof module:MediaPlayer\n * @throws {@link module:MediaPlayer~STREAMING_NOT_INITIALIZED_ERROR STREAMING_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @instance\n */\n function setCurrentTrack(track) {\n if (!streamingInitialized) {\n throw STREAMING_NOT_INITIALIZED_ERROR;\n }\n mediaController.setTrack(track);\n }\n\n /*\n ---------------------------------------------------------------------------\n\n PROTECTION MANAGEMENT\n\n ---------------------------------------------------------------------------\n */\n\n /**\n * Detects if Protection is included and returns an instance of ProtectionController.js\n * @memberof module:MediaPlayer\n * @instance\n */\n function getProtectionController() {\n return _detectProtection();\n }\n\n /**\n * Will override dash.js protection controller.\n * @param {ProtectionController} value - valid protection controller instance.\n * @memberof module:MediaPlayer\n * @instance\n */\n function attachProtectionController(value) {\n protectionController = value;\n }\n\n /**\n * Sets Protection Data required to setup the Protection Module (DRM). Protection Data must\n * be set before initializing MediaPlayer or, once initialized, before PROTECTION_CREATED event is fired.\n * @see {@link module:MediaPlayer#initialize initialize()}\n * @see {@link ProtectionEvents#event:PROTECTION_CREATED dashjs.Protection.events.PROTECTION_CREATED}\n * @param {ProtectionDataSet} value - object containing\n * property names corresponding to key system name strings and associated\n * values being instances of.\n * @memberof module:MediaPlayer\n * @instance\n */\n function setProtectionData(value) {\n protectionData = value;\n\n // Propagate changes in case StreamController is already created\n if (streamController) {\n streamController.setProtectionData(protectionData);\n }\n }\n\n /**\n * Registers a license request filter. This enables application to manipulate/overwrite any request parameter and/or request data.\n * The provided callback function shall return a promise that shall be resolved once the filter process is completed.\n * The filters are applied in the order they are registered.\n * @param {function} filter - the license request filter callback\n * @memberof module:MediaPlayer\n * @instance\n */\n function registerLicenseRequestFilter(filter) {\n licenseRequestFilters.push(filter);\n if (protectionController) {\n protectionController.setLicenseRequestFilters(licenseRequestFilters);\n }\n }\n\n /**\n * Registers a license response filter. This enables application to manipulate/overwrite the response data\n * The provided callback function shall return a promise that shall be resolved once the filter process is completed.\n * The filters are applied in the order they are registered.\n * @param {function} filter - the license response filter callback\n * @memberof module:MediaPlayer\n * @instance\n */\n function registerLicenseResponseFilter(filter) {\n licenseResponseFilters.push(filter);\n if (protectionController) {\n protectionController.setLicenseResponseFilters(licenseResponseFilters);\n }\n }\n\n /**\n * Unregisters a license request filter.\n * @param {function} filter - the license request filter callback\n * @memberof module:MediaPlayer\n * @instance\n */\n function unregisterLicenseRequestFilter(filter) {\n unregisterFilter(licenseRequestFilters, filter);\n if (protectionController) {\n protectionController.setLicenseRequestFilters(licenseRequestFilters);\n }\n }\n\n /**\n * Unregisters a license response filter.\n * @param {function} filter - the license response filter callback\n * @memberof module:MediaPlayer\n * @instance\n */\n function unregisterLicenseResponseFilter(filter) {\n unregisterFilter(licenseResponseFilters, filter);\n if (protectionController) {\n protectionController.setLicenseResponseFilters(licenseResponseFilters);\n }\n }\n\n /**\n * Registers a custom capabilities filter. This enables application to filter representations to use.\n * The provided callback function shall return a boolean based on whether or not to use the representation.\n * The filters are applied in the order they are registered.\n * @param {function} filter - the custom capabilities filter callback\n * @memberof module:MediaPlayer\n * @instance\n */\n function registerCustomCapabilitiesFilter(filter) {\n customCapabilitiesFilters.push(filter);\n if (capabilitiesFilter) {\n capabilitiesFilter.setCustomCapabilitiesFilters(customCapabilitiesFilters);\n }\n }\n\n /**\n * Unregisters a custom capabilities filter.\n * @param {function} filter - the custom capabilities filter callback\n * @memberof module:MediaPlayer\n * @instance\n */\n function unregisterCustomCapabilitiesFilter(filter) {\n unregisterFilter(customCapabilitiesFilters, filter);\n if (capabilitiesFilter) {\n capabilitiesFilter.setCustomCapabilitiesFilters(customCapabilitiesFilters);\n }\n }\n\n function unregisterFilter(filters, filter) {\n let index = -1;\n filters.some((item, i) => {\n if (item === filter) {\n index = i;\n return true;\n }\n });\n if (index < 0) return;\n filters.splice(index, 1);\n }\n\n /**\n * Registers a custom initial track selection function. Only one function is allowed. Calling this method will overwrite a potentially existing function.\n * @param {function} customFunc - the custom function that returns the initial track\n */\n function setCustomInitialTrackSelectionFunction(customFunc) {\n if (mediaController) {\n mediaController.setCustomInitialTrackSelectionFunction(customFunc);\n }\n }\n\n /**\n * Resets the custom initial track selection\n */\n function resetCustomInitialTrackSelectionFunction() {\n if (mediaController) {\n mediaController.setCustomInitialTrackSelectionFunction(null);\n }\n }\n\n\n /*\n ---------------------------------------------------------------------------\n\n THUMBNAILS MANAGEMENT\n\n ---------------------------------------------------------------------------\n */\n\n /**\n * Provide the thumbnail at time position. This can be asynchronous, so you must provide a callback ro retrieve thumbnails informations\n * @param {number} time - A relative time, in seconds, based on the return value of the {@link module:MediaPlayer#duration duration()} method is expected\n * @param {function} callback - A Callback function provided when retrieving thumbnail the given time position. Thumbnail object is null in case there are is not a thumbnails representation or\n * if it doesn't contain a thumbnail for the given time position.\n * @memberof module:MediaPlayer\n * @instance\n */\n function provideThumbnail(time, callback) {\n if (typeof callback !== 'function') {\n return;\n }\n if (time < 0) {\n callback(null);\n return;\n }\n const s = playbackController.getIsDynamic() ? getDVRSeekOffset(time) : time;\n const stream = streamController.getStreamForTime(s);\n if (stream === null) {\n callback(null);\n return;\n }\n\n const thumbnailController = stream.getThumbnailController();\n if (!thumbnailController) {\n callback(null);\n return;\n }\n\n const timeInPeriod = streamController.getTimeRelativeToStreamId(s, stream.getId());\n return thumbnailController.provide(timeInPeriod, callback);\n }\n\n /*\n ---------------------------------------------------------------------------\n\n TOOLS AND OTHERS FUNCTIONS\n\n ---------------------------------------------------------------------------\n */\n /**\n * Allows application to retrieve a manifest. Manifest loading is asynchro\n * nous and\n * requires the app-provided callback function\n *\n * @param {string} url - url the manifest url\n * @param {function} callback - A Callback function provided when retrieving manifests\n * @memberof module:MediaPlayer\n * @instance\n */\n function retrieveManifest(url, callback) {\n let manifestLoader = _createManifestLoader();\n let self = this;\n\n const handler = function (e) {\n if (!e.error) {\n callback(e.manifest);\n } else {\n callback(null, e.error);\n }\n eventBus.off(Events.INTERNAL_MANIFEST_LOADED, handler, self);\n manifestLoader.reset();\n };\n\n eventBus.on(Events.INTERNAL_MANIFEST_LOADED, handler, self);\n\n uriFragmentModel.initialize(url);\n manifestLoader.load(url);\n }\n\n /**\n * Returns the source string or manifest that was attached by calling attachSource()\n * @returns {string | manifest}\n * @memberof module:MediaPlayer\n * @throws {@link module:MediaPlayer~SOURCE_NOT_ATTACHED_ERROR SOURCE_NOT_ATTACHED_ERROR} if called before attachSource function\n * @instance\n */\n function getSource() {\n if (!source) {\n throw SOURCE_NOT_ATTACHED_ERROR;\n }\n return source;\n }\n\n /**\n * Use this method to set a source URL to a valid MPD manifest file OR\n * a previously downloaded and parsed manifest object. Optionally, can\n * also provide protection information\n *\n * @param {string|Object} urlOrManifest - A URL to a valid MPD manifest file, or a\n * parsed manifest object.\n *\n *\n * @throws {@link module:MediaPlayer~MEDIA_PLAYER_NOT_INITIALIZED_ERROR MEDIA_PLAYER_NOT_INITIALIZED_ERROR} if called before initialize function\n *\n * @memberof module:MediaPlayer\n * @instance\n */\n function attachSource(urlOrManifest) {\n if (!mediaPlayerInitialized) {\n throw MEDIA_PLAYER_NOT_INITIALIZED_ERROR;\n }\n\n if (typeof urlOrManifest === 'string') {\n uriFragmentModel.initialize(urlOrManifest);\n }\n\n source = urlOrManifest;\n\n if (streamingInitialized || playbackInitialized) {\n _resetPlaybackControllers();\n }\n\n if (isReady()) {\n _initializePlayback();\n }\n }\n\n /**\n * Get the current settings object being used on the player.\n * @returns {PlayerSettings} The settings object being used.\n *\n * @memberof module:MediaPlayer\n * @instance\n */\n function getSettings() {\n return settings.get();\n }\n\n /**\n * @summary Update the current settings object being used on the player. Anything left unspecified is not modified.\n * @param {PlayerSettings} settingsObj - An object corresponding to the settings definition.\n * @description This function does not update the entire object, only properties in the passed in object are updated.\n *\n * This means that updateSettings({a: x}) and updateSettings({b: y}) are functionally equivalent to\n * updateSettings({a: x, b: y}). If the default values are required again, @see{@link resetSettings}.\n * @example\n * player.updateSettings({\n * streaming: {\n * lowLatencyEnabled: false,\n * abr: {\n * maxBitrate: { audio: 100, video: 1000 }\n * }\n * }\n * });\n * @memberof module:MediaPlayer\n * @instance\n */\n function updateSettings(settingsObj) {\n settings.update(settingsObj);\n }\n\n /**\n * Resets the settings object back to the default.\n *\n * @memberof module:MediaPlayer\n * @instance\n */\n function resetSettings() {\n settings.reset();\n }\n\n /**\n * A utility methods which converts UTC timestamp value into a valid time and date string.\n *\n * @param {number} time - UTC timestamp to be converted into date and time.\n * @param {string} locales - a region identifier (i.e. en_US).\n * @param {boolean} hour12 - 12 vs 24 hour. Set to true for 12 hour time formatting.\n * @param {boolean} withDate - default is false. Set to true to append current date to UTC time format.\n * @returns {string} A formatted time and date string.\n * @memberof module:MediaPlayer\n * @instance\n */\n function formatUTC(time, locales, hour12, withDate = false) {\n const dt = new Date(time * 1000);\n const d = dt.toLocaleDateString(locales);\n const t = dt.toLocaleTimeString(locales, {\n hour12: hour12\n });\n return withDate ? t + ' ' + d : t;\n }\n\n /**\n * A utility method which converts seconds into TimeCode (i.e. 300 --> 05:00).\n *\n * @param {number} value - A number in seconds to be converted into a formatted time code.\n * @returns {string} A formatted time code string.\n * @memberof module:MediaPlayer\n * @instance\n */\n function convertToTimeCode(value) {\n value = Math.max(value, 0);\n\n let h = Math.floor(value / 3600);\n let m = Math.floor((value % 3600) / 60);\n let s = Math.floor((value % 3600) % 60);\n return (h === 0 ? '' : (h < 10 ? '0' + h.toString() + ':' : h.toString() + ':')) + (m < 10 ? '0' + m.toString() : m.toString()) + ':' + (s < 10 ? '0' + s.toString() : s.toString());\n }\n\n /**\n * This method should be used to extend or replace internal dash.js objects.\n * There are two ways to extend dash.js (determined by the override argument):\n * <ol>\n * <li>If you set override to true any public method or property in your custom object will\n * override the dash.js parent object's property(ies) and will be used instead but the\n * dash.js parent module will still be created.</li>\n *\n * <li>If you set override to false your object will completely replace the dash.js object.\n * (Note: This is how it was in 1.x of Dash.js with Dijon).</li>\n * </ol>\n * <b>When you extend you get access to this.context, this.factory and this.parent to operate with in your custom object.</b>\n * <ul>\n * <li><b>this.context</b> - can be used to pass context for singleton access.</li>\n * <li><b>this.factory</b> - can be used to call factory.getSingletonInstance().</li>\n * <li><b>this.parent</b> - is the reference of the parent object to call other public methods. (this.parent is excluded if you extend with override set to false or option 2)</li>\n * </ul>\n * <b>You must call extend before you call initialize</b>\n * @see {@link module:MediaPlayer#initialize initialize()}\n * @param {string} parentNameString - name of parent module\n * @param {Object} childInstance - overriding object\n * @param {boolean} override - replace only some methods (true) or the whole object (false)\n * @memberof module:MediaPlayer\n * @instance\n */\n function extend(parentNameString, childInstance, override) {\n FactoryMaker.extend(parentNameString, childInstance, override, context);\n }\n\n /**\n * This method returns the active stream\n *\n * @throws {@link module:MediaPlayer~STREAMING_NOT_INITIALIZED_ERROR STREAMING_NOT_INITIALIZED_ERROR} if called before initializePlayback function\n * @memberof module:MediaPlayer\n * @instance\n */\n function getActiveStream() {\n if (!streamingInitialized) {\n throw STREAMING_NOT_INITIALIZED_ERROR;\n }\n let streamInfo = streamController.getActiveStreamInfo();\n return streamInfo ? streamController.getStreamById(streamInfo.id) : null;\n }\n\n /**\n * Returns the DashAdapter.js Module.\n *\n * @see {@link module:DashAdapter}\n * @returns {Object}\n * @memberof module:MediaPlayer\n * @instance\n */\n function getDashAdapter() {\n return adapter;\n }\n\n //***********************************\n // PRIVATE METHODS\n //***********************************\n\n function _resetPlaybackControllers() {\n playbackInitialized = false;\n streamingInitialized = false;\n adapter.reset();\n streamController.reset();\n gapController.reset();\n playbackController.reset();\n abrController.reset();\n mediaController.reset();\n segmentBaseController.reset();\n if (protectionController) {\n if (settings.get().streaming.protection.keepProtectionMediaKeys) {\n protectionController.stop();\n } else {\n protectionController.reset();\n protectionController = null;\n _detectProtection();\n }\n }\n textController.reset();\n cmcdModel.reset();\n }\n\n function _createPlaybackControllers() {\n // creates or get objects instances\n const manifestLoader = _createManifestLoader();\n\n if (!streamController) {\n streamController = StreamController(context).getInstance();\n }\n\n if (!textController) {\n textController = TextController(context).create({\n errHandler,\n manifestModel,\n adapter,\n mediaController,\n videoModel,\n settings\n });\n }\n\n capabilitiesFilter.setConfig({\n capabilities,\n adapter,\n settings,\n manifestModel,\n errHandler\n });\n capabilitiesFilter.setCustomCapabilitiesFilters(customCapabilitiesFilters);\n\n streamController.setConfig({\n capabilities,\n capabilitiesFilter,\n manifestLoader,\n manifestModel,\n mediaPlayerModel,\n protectionController,\n textController,\n adapter,\n dashMetrics,\n errHandler,\n timelineConverter,\n videoModel,\n playbackController,\n abrController,\n mediaController,\n settings,\n baseURLController,\n uriFragmentModel,\n segmentBaseController\n });\n\n gapController.setConfig({\n settings,\n playbackController,\n streamController,\n videoModel,\n timelineConverter,\n adapter\n });\n\n playbackController.setConfig({\n streamController,\n dashMetrics,\n mediaPlayerModel,\n adapter,\n videoModel,\n timelineConverter,\n settings\n });\n\n abrController.setConfig({\n streamController,\n domStorage,\n mediaPlayerModel,\n dashMetrics,\n adapter,\n videoModel,\n settings\n });\n\n cmcdModel.setConfig({\n abrController,\n dashMetrics,\n playbackController\n });\n\n // initialises controller\n abrController.initialize();\n streamController.initialize(autoPlay, protectionData);\n textController.initialize();\n gapController.initialize();\n cmcdModel.initialize();\n segmentBaseController.initialize();\n }\n\n function _createManifestLoader() {\n return ManifestLoader(context).create({\n debug: debug,\n errHandler: errHandler,\n dashMetrics: dashMetrics,\n mediaPlayerModel: mediaPlayerModel,\n requestModifier: RequestModifier(context).getInstance(),\n mssHandler: mssHandler,\n settings: settings\n });\n }\n\n function _detectProtection() {\n if (protectionController) {\n return protectionController;\n }\n // do not require Protection as dependencies as this is optional and intended to be loaded separately\n let Protection = dashjs.Protection; /* jshint ignore:line */\n if (typeof Protection === 'function') { //TODO need a better way to register/detect plugin components\n let protection = Protection(context).create();\n Events.extend(Protection.events);\n MediaPlayerEvents.extend(Protection.events, {\n publicOnly: true\n });\n Errors.extend(Protection.errors);\n if (!capabilities) {\n capabilities = Capabilities(context).getInstance();\n }\n protectionController = protection.createProtectionSystem({\n debug: debug,\n errHandler: errHandler,\n videoModel: videoModel,\n capabilities: capabilities,\n eventBus: eventBus,\n events: Events,\n BASE64: BASE64,\n constants: Constants,\n cmcdModel: cmcdModel,\n settings: settings\n });\n if (protectionController) {\n protectionController.setLicenseRequestFilters(licenseRequestFilters);\n protectionController.setLicenseResponseFilters(licenseResponseFilters);\n }\n return protectionController;\n }\n\n return null;\n }\n\n function _detectMetricsReporting() {\n if (metricsReportingController) {\n return;\n }\n // do not require MetricsReporting as dependencies as this is optional and intended to be loaded separately\n let MetricsReporting = dashjs.MetricsReporting; /* jshint ignore:line */\n if (typeof MetricsReporting === 'function') { //TODO need a better way to register/detect plugin components\n let metricsReporting = MetricsReporting(context).create();\n\n metricsReportingController = metricsReporting.createMetricsReporting({\n debug: debug,\n eventBus: eventBus,\n mediaElement: getVideoElement(),\n adapter: adapter,\n dashMetrics: dashMetrics,\n events: Events,\n constants: Constants,\n metricsConstants: MetricsConstants\n });\n }\n }\n\n function _detectMss() {\n if (mssHandler) {\n return;\n }\n // do not require MssHandler as dependencies as this is optional and intended to be loaded separately\n let MssHandler = dashjs.MssHandler; /* jshint ignore:line */\n if (typeof MssHandler === 'function') { //TODO need a better way to register/detect plugin components\n Errors.extend(MssHandler.errors);\n mssHandler = MssHandler(context).create({\n eventBus: eventBus,\n mediaPlayerModel: mediaPlayerModel,\n dashMetrics: dashMetrics,\n manifestModel: manifestModel,\n playbackController: playbackController,\n streamController: streamController,\n protectionController: protectionController,\n baseURLController: baseURLController,\n errHandler: errHandler,\n events: Events,\n constants: Constants,\n debug: debug,\n initSegmentType: HTTPRequest.INIT_SEGMENT_TYPE,\n BASE64: BASE64,\n ISOBoxer: ISOBoxer,\n settings: settings\n });\n }\n }\n\n function _detectOffline() {\n if (!mediaPlayerInitialized) {\n throw MEDIA_PLAYER_NOT_INITIALIZED_ERROR;\n }\n\n if (offlineController) {\n return offlineController;\n }\n\n // do not require Offline as dependencies as this is optional and intended to be loaded separately\n let OfflineController = dashjs.OfflineController; /* jshint ignore:line */\n\n if (typeof OfflineController === 'function') { //TODO need a better way to register/detect plugin components\n Events.extend(OfflineController.events);\n MediaPlayerEvents.extend(OfflineController.events, {\n publicOnly: true\n });\n Errors.extend(OfflineController.errors);\n\n const manifestLoader = _createManifestLoader();\n const manifestUpdater = ManifestUpdater(context).create();\n\n manifestUpdater.setConfig({\n manifestModel: manifestModel,\n adapter: adapter,\n manifestLoader: manifestLoader,\n errHandler: errHandler\n });\n\n offlineController = OfflineController(context).create({\n debug: debug,\n manifestUpdater: manifestUpdater,\n baseURLController: baseURLController,\n manifestLoader: manifestLoader,\n manifestModel: manifestModel,\n mediaPlayerModel: mediaPlayerModel,\n abrController: abrController,\n playbackController: playbackController,\n adapter: adapter,\n errHandler: errHandler,\n dashMetrics: dashMetrics,\n timelineConverter: timelineConverter,\n segmentBaseController: segmentBaseController,\n schemeLoaderFactory: schemeLoaderFactory,\n eventBus: eventBus,\n events: Events,\n errors: Errors,\n constants: Constants,\n settings: settings,\n dashConstants: DashConstants,\n urlUtils: URLUtils(context).getInstance()\n });\n return offlineController;\n }\n\n return null;\n }\n\n function _getAsUTC(valToConvert) {\n const type = streamController && streamController.hasVideoTrack() ? Constants.VIDEO : Constants.AUDIO;\n let metric = dashMetrics.getCurrentDVRInfo(type);\n let availableFrom,\n utcValue;\n\n if (!metric) {\n return 0;\n }\n availableFrom = metric.manifestInfo.availableFrom.getTime() / 1000;\n utcValue = valToConvert + (availableFrom + metric.range.start);\n return utcValue;\n }\n\n function _initializePlayback() {\n\n if (offlineController) {\n offlineController.resetRecords();\n }\n\n if (!streamingInitialized && source) {\n streamingInitialized = true;\n logger.info('Streaming Initialized');\n _createPlaybackControllers();\n\n if (typeof source === 'string') {\n streamController.load(source);\n } else {\n streamController.loadWithManifest(source);\n }\n }\n\n if (!playbackInitialized && isReady()) {\n playbackInitialized = true;\n logger.info('Playback Initialized');\n }\n }\n\n instance = {\n initialize,\n setConfig,\n on,\n off,\n extend,\n attachView,\n attachSource,\n isReady,\n play,\n isPaused,\n pause,\n isSeeking,\n isDynamic,\n seek,\n setPlaybackRate,\n getPlaybackRate,\n setMute,\n isMuted,\n setVolume,\n getVolume,\n time,\n duration,\n timeAsUTC,\n durationAsUTC,\n getActiveStream,\n getDVRWindowSize,\n getDVRSeekOffset,\n convertToTimeCode,\n formatUTC,\n getVersion,\n getDebug,\n getBufferLength,\n getTTMLRenderingDiv,\n getVideoElement,\n getSource,\n getCurrentLiveLatency,\n getTopBitrateInfoFor,\n setAutoPlay,\n getAutoPlay,\n getDashMetrics,\n getQualityFor,\n setQualityFor,\n updatePortalSize,\n enableText,\n enableForcedTextStreaming,\n isTextEnabled,\n setTextTrack,\n getBitrateInfoListFor,\n getStreamsFromManifest,\n getTracksFor,\n getTracksForTypeFromManifest,\n getCurrentTrackFor,\n setInitialMediaSettingsFor,\n getInitialMediaSettingsFor,\n setCurrentTrack,\n addABRCustomRule,\n removeABRCustomRule,\n removeAllABRCustomRule,\n getAverageThroughput,\n retrieveManifest,\n addUTCTimingSource,\n removeUTCTimingSource,\n clearDefaultUTCTimingSources,\n restoreDefaultUTCTimingSources,\n setXHRWithCredentialsForType,\n getXHRWithCredentialsForType,\n getProtectionController,\n attachProtectionController,\n setProtectionData,\n registerLicenseRequestFilter,\n registerLicenseResponseFilter,\n unregisterLicenseRequestFilter,\n unregisterLicenseResponseFilter,\n registerCustomCapabilitiesFilter,\n unregisterCustomCapabilitiesFilter,\n setCustomInitialTrackSelectionFunction,\n resetCustomInitialTrackSelectionFunction,\n attachTTMLRenderingDiv,\n getCurrentTextTrackIndex,\n provideThumbnail,\n getDashAdapter,\n getOfflineController,\n getSettings,\n updateSettings,\n resetSettings,\n reset,\n destroy\n };\n\n setup();\n\n return instance;\n}\n\nMediaPlayer.__dashjs_factory_name = 'MediaPlayer';\nconst factory = FactoryMaker.getClassFactory(MediaPlayer);\nfactory.events = MediaPlayerEvents;\nfactory.errors = Errors;\nFactoryMaker.updateClassFactory(MediaPlayer.__dashjs_factory_name, factory);\n\nexport default factory;\n","const VERSION = '__VERSION__';\nexport function getVersionString() {\n return VERSION;\n}\n","/* $Date: 2007-06-12 18:02:31 $ */\n\n// from: http://bannister.us/weblog/2007/06/09/simple-base64-encodedecode-javascript/\n// Handles encode/decode of ASCII and Unicode strings.\n\nvar UTF8 = {};\nUTF8.encode = function(s) {\n var u = [];\n for (var i = 0; i < s.length; ++i) {\n var c = s.charCodeAt(i);\n if (c < 0x80) {\n u.push(c);\n } else if (c < 0x800) {\n u.push(0xC0 | (c >> 6));\n u.push(0x80 | (63 & c));\n } else if (c < 0x10000) {\n u.push(0xE0 | (c >> 12));\n u.push(0x80 | (63 & (c >> 6)));\n u.push(0x80 | (63 & c));\n } else {\n u.push(0xF0 | (c >> 18));\n u.push(0x80 | (63 & (c >> 12)));\n u.push(0x80 | (63 & (c >> 6)));\n u.push(0x80 | (63 & c));\n }\n }\n return u;\n};\nUTF8.decode = function(u) {\n var a = [];\n var i = 0;\n while (i < u.length) {\n var v = u[i++];\n if (v < 0x80) {\n // no need to mask byte\n } else if (v < 0xE0) {\n v = (31 & v) << 6;\n v |= (63 & u[i++]);\n } else if (v < 0xF0) {\n v = (15 & v) << 12;\n v |= (63 & u[i++]) << 6;\n v |= (63 & u[i++]);\n } else {\n v = (7 & v) << 18;\n v |= (63 & u[i++]) << 12;\n v |= (63 & u[i++]) << 6;\n v |= (63 & u[i++]);\n }\n a.push(String.fromCharCode(v));\n }\n return a.join('');\n};\n\nvar BASE64 = {};\n(function(T){\n var encodeArray = function(u) {\n var i = 0;\n var a = [];\n var n = 0 | (u.length / 3);\n while (0 < n--) {\n var v = (u[i] << 16) + (u[i+1] << 8) + u[i+2];\n i += 3;\n a.push(T.charAt(63 & (v >> 18)));\n a.push(T.charAt(63 & (v >> 12)));\n a.push(T.charAt(63 & (v >> 6)));\n a.push(T.charAt(63 & v));\n }\n if (2 == (u.length - i)) {\n var v = (u[i] << 16) + (u[i+1] << 8);\n a.push(T.charAt(63 & (v >> 18)));\n a.push(T.charAt(63 & (v >> 12)));\n a.push(T.charAt(63 & (v >> 6)));\n a.push('=');\n } else if (1 == (u.length - i)) {\n var v = (u[i] << 16);\n a.push(T.charAt(63 & (v >> 18)));\n a.push(T.charAt(63 & (v >> 12)));\n a.push('==');\n }\n return a.join('');\n }\n var R = (function(){\n var a = [];\n for (var i=0; i<T.length; ++i) {\n a[T.charCodeAt(i)] = i;\n }\n a['='.charCodeAt(0)] = 0;\n return a;\n })();\n var decodeArray = function(s) {\n var i = 0;\n var u = [];\n var n = 0 | (s.length / 4);\n while (0 < n--) {\n var v = (R[s.charCodeAt(i)] << 18) + (R[s.charCodeAt(i+1)] << 12) + (R[s.charCodeAt(i+2)] << 6) + R[s.charCodeAt(i+3)];\n u.push(255 & (v >> 16));\n u.push(255 & (v >> 8));\n u.push(255 & v);\n i += 4;\n }\n if (u) {\n if ('=' == s.charAt(i-2)) {\n u.pop();\n u.pop();\n } else if ('=' == s.charAt(i-1)) {\n u.pop();\n }\n }\n return u;\n }\n var ASCII = {};\n ASCII.encode = function(s) {\n var u = [];\n for (var i = 0; i<s.length; ++i) {\n u.push(s.charCodeAt(i));\n }\n return u;\n };\n ASCII.decode = function(u) {\n for (var i = 0; i<s.length; ++i) {\n a[i] = String.fromCharCode(a[i]);\n }\n return a.join('');\n };\n BASE64.decodeArray = function(s) {\n var u = decodeArray(s);\n return new Uint8Array(u);\n };\n BASE64.encodeASCII = function(s) {\n var u = ASCII.encode(s);\n return encodeArray(u);\n };\n BASE64.decodeASCII = function(s) {\n var a = decodeArray(s);\n return ASCII.decode(a);\n };\n BASE64.encode = function(s) {\n var u = UTF8.encode(s);\n return encodeArray(u);\n };\n BASE64.decode = function(s) {\n var u = decodeArray(s);\n return UTF8.decode(u);\n };\n})(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\");\n\n/*The following polyfills are not used in dash.js but have caused multiplayer integration issues.\n Therefore commenting them out.\nif (undefined === btoa) {\n var btoa = BASE64.encode;\n}\nif (undefined === atob) {\n var atob = BASE64.decode;\n}\n*/\n\nif (typeof exports !== 'undefined') {\n exports.decode = BASE64.decode;\n exports.decodeArray = BASE64.decodeArray;\n exports.encode = BASE64.encode;\n exports.encodeASCII = BASE64.encodeASCII;\n}\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Constants from '../../streaming/constants/Constants';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport MediaPlayerEvents from '../../streaming/MediaPlayerEvents';\nimport {getTimeBasedSegment} from '../utils/SegmentsUtils';\n\nfunction RepresentationController(config) {\n\n config = config || {};\n const eventBus = config.eventBus;\n const events = config.events;\n const abrController = config.abrController;\n const dashMetrics = config.dashMetrics;\n const playbackController = config.playbackController;\n const timelineConverter = config.timelineConverter;\n const type = config.type;\n const streamInfo = config.streamInfo;\n const dashConstants = config.dashConstants;\n const segmentsController = config.segmentsController;\n const isDynamic = config.isDynamic;\n\n let instance,\n realAdaptation,\n updating,\n voAvailableRepresentations,\n currentVoRepresentation;\n\n function setup() {\n resetInitialSettings();\n\n eventBus.on(MediaPlayerEvents.MANIFEST_VALIDITY_CHANGED, onManifestValidityChanged, instance);\n }\n\n function getStreamId() {\n return streamInfo.id;\n }\n\n function getType() {\n return type;\n }\n\n function checkConfig() {\n if (!abrController || !dashMetrics || !playbackController || !timelineConverter) {\n throw new Error(Constants.MISSING_CONFIG_ERROR);\n }\n }\n\n function getData() {\n return realAdaptation;\n }\n\n function isUpdating() {\n return updating;\n }\n\n function getCurrentRepresentation() {\n return currentVoRepresentation;\n }\n\n function resetInitialSettings() {\n realAdaptation = null;\n updating = true;\n voAvailableRepresentations = [];\n }\n\n function reset() {\n eventBus.off(MediaPlayerEvents.MANIFEST_VALIDITY_CHANGED, onManifestValidityChanged, instance);\n\n resetInitialSettings();\n }\n\n function updateData(newRealAdaptation, availableRepresentations, type, isFragmented, quality) {\n checkConfig();\n\n updating = true;\n\n voAvailableRepresentations = availableRepresentations;\n\n const rep = getRepresentationForQuality(quality)\n _setCurrentVoRepresentation(rep);\n realAdaptation = newRealAdaptation;\n\n if (type !== Constants.VIDEO && type !== Constants.AUDIO && (type !== Constants.TEXT || !isFragmented)) {\n endDataUpdate();\n return Promise.resolve();\n }\n\n const promises = [];\n for (let i = 0, ln = voAvailableRepresentations.length; i < ln; i++) {\n const currentRep = voAvailableRepresentations[i];\n promises.push(_updateRepresentation(currentRep));\n }\n\n return Promise.all(promises);\n }\n\n function _updateRepresentation(currentRep) {\n return new Promise((resolve, reject) => {\n const hasInitialization = currentRep.hasInitialization();\n const hasSegments = currentRep.hasSegments();\n\n // If representation has initialization and segments information we are done\n // otherwise, it means that a request has to be made to get initialization and/or segments information\n const promises = [];\n\n promises.push(segmentsController.updateInitData(currentRep, hasInitialization));\n promises.push(segmentsController.updateSegmentData(currentRep, hasSegments));\n\n Promise.all(promises)\n .then((data) => {\n if (data[0] && !data[0].error) {\n currentRep = _onInitLoaded(currentRep, data[0]);\n }\n if (data[1] && !data[1].error) {\n currentRep = _onSegmentsLoaded(currentRep, data[1]);\n }\n _setMediaFinishedInformation(currentRep);\n _onRepresentationUpdated(currentRep);\n resolve();\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n function _setMediaFinishedInformation(representation) {\n representation.mediaFinishedInformation = segmentsController.getMediaFinishedInformation(representation);\n }\n\n function _onInitLoaded(representation, e) {\n if (!e || e.error || !e.representation) {\n return representation;\n }\n return e.representation;\n }\n\n function _onSegmentsLoaded(representation, e) {\n if (!e || e.error) return;\n\n const fragments = e.segments;\n const segments = [];\n let count = 0;\n\n let i,\n len,\n s,\n seg;\n\n for (i = 0, len = fragments ? fragments.length : 0; i < len; i++) {\n s = fragments[i];\n\n seg = getTimeBasedSegment(\n timelineConverter,\n isDynamic,\n representation,\n s.startTime,\n s.duration,\n s.timescale,\n s.media,\n s.mediaRange,\n count);\n\n if (seg) {\n segments.push(seg);\n seg = null;\n count++;\n }\n }\n\n if (segments.length > 0) {\n representation.segments = segments;\n }\n\n return representation;\n }\n\n function _addRepresentationSwitch() {\n checkConfig();\n const now = new Date();\n const currentRepresentation = getCurrentRepresentation();\n const currentVideoTimeMs = playbackController.getTime() * 1000;\n if (currentRepresentation) {\n dashMetrics.addRepresentationSwitch(currentRepresentation.adaptation.type, now, currentVideoTimeMs, currentRepresentation.id);\n }\n\n eventBus.trigger(MediaPlayerEvents.REPRESENTATION_SWITCH, {\n mediaType: type,\n streamId: streamInfo.id,\n currentRepresentation,\n numberOfRepresentations: voAvailableRepresentations.length\n }, { streamId: streamInfo.id, mediaType: type })\n }\n\n function getRepresentationForQuality(quality) {\n return quality === null || quality === undefined || quality >= voAvailableRepresentations.length ? null : voAvailableRepresentations[quality];\n }\n\n function getQualityForRepresentation(voRepresentation) {\n return voAvailableRepresentations.indexOf(voRepresentation);\n }\n\n function isAllRepresentationsUpdated() {\n for (let i = 0, ln = voAvailableRepresentations.length; i < ln; i++) {\n let segmentInfoType = voAvailableRepresentations[i].segmentInfoType;\n if (!voAvailableRepresentations[i].hasInitialization() ||\n ((segmentInfoType === dashConstants.SEGMENT_BASE || segmentInfoType === dashConstants.BASE_URL) && !voAvailableRepresentations[i].segments)\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n function endDataUpdate(error) {\n updating = false;\n eventBus.trigger(events.DATA_UPDATE_COMPLETED,\n {\n data: realAdaptation,\n currentRepresentation: currentVoRepresentation,\n error: error\n },\n { streamId: streamInfo.id, mediaType: type }\n );\n }\n\n function _onRepresentationUpdated(r) {\n if (!isUpdating()) return;\n\n let manifestUpdateInfo = dashMetrics.getCurrentManifestUpdate();\n let alreadyAdded = false;\n let repInfo,\n repSwitch;\n\n\n if (manifestUpdateInfo) {\n for (let i = 0; i < manifestUpdateInfo.representationInfo.length; i++) {\n repInfo = manifestUpdateInfo.representationInfo[i];\n if (repInfo.index === r.index && repInfo.mediaType === getType()) {\n alreadyAdded = true;\n break;\n }\n }\n\n if (!alreadyAdded) {\n dashMetrics.addManifestUpdateRepresentationInfo(r, getType());\n }\n }\n\n if (isAllRepresentationsUpdated()) {\n abrController.setPlaybackQuality(type, streamInfo, getQualityForRepresentation(currentVoRepresentation));\n const dvrInfo = dashMetrics.getCurrentDVRInfo(type);\n if (dvrInfo) {\n dashMetrics.updateManifestUpdateInfo({ latency: dvrInfo.range.end - playbackController.getTime() });\n }\n\n repSwitch = dashMetrics.getCurrentRepresentationSwitch(getCurrentRepresentation().adaptation.type);\n\n if (!repSwitch) {\n _addRepresentationSwitch();\n }\n endDataUpdate();\n }\n }\n\n function prepareQualityChange(newQuality) {\n const newRep = getRepresentationForQuality(newQuality)\n _setCurrentVoRepresentation(newRep);\n _addRepresentationSwitch();\n }\n\n function _setCurrentVoRepresentation(value) {\n currentVoRepresentation = value;\n }\n\n function onManifestValidityChanged(e) {\n if (e.newDuration) {\n const representation = getCurrentRepresentation();\n if (representation && representation.adaptation.period) {\n const period = representation.adaptation.period;\n period.duration = e.newDuration;\n }\n }\n }\n\n instance = {\n getStreamId,\n getType,\n getData,\n isUpdating,\n updateData,\n getCurrentRepresentation,\n getRepresentationForQuality,\n prepareQualityChange,\n reset\n };\n\n setup();\n return instance;\n}\n\nRepresentationController.__dashjs_factory_name = 'RepresentationController';\nexport default FactoryMaker.getClassFactory(RepresentationController);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * @class\n * @ignore\n */\nclass DataChunk {\n //Represents a data structure that keep all the necessary info about a single init/media segment\n constructor() {\n this.streamId = null;\n this.mediaInfo = null;\n this.segmentType = null;\n this.quality = NaN;\n this.index = NaN;\n this.bytes = null;\n this.start = NaN;\n this.end = NaN;\n this.duration = NaN;\n this.representationId = null;\n this.endFragment = null;\n }\n}\n\nexport default DataChunk;","'use strict';\n\nvar isArray = Array.isArray;\nvar keyList = Object.keys;\nvar hasProp = Object.prototype.hasOwnProperty;\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n var arrA = isArray(a)\n , arrB = isArray(b)\n , i\n , length\n , key;\n\n if (arrA && arrB) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n if (arrA != arrB) return false;\n\n var dateA = a instanceof Date\n , dateB = b instanceof Date;\n if (dateA != dateB) return false;\n if (dateA && dateB) return a.getTime() == b.getTime();\n\n var regexpA = a instanceof RegExp\n , regexpB = b instanceof RegExp;\n if (regexpA != regexpB) return false;\n if (regexpA && regexpB) return a.toString() == b.toString();\n\n var keys = keyList(a);\n length = keys.length;\n\n if (length !== keyList(b).length)\n return false;\n\n for (i = length; i-- !== 0;)\n if (!hasProp.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n key = keys[i];\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n return a!==a && b!==b;\n};\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport FactoryMaker from '../../core/FactoryMaker';\n\nfunction ObjectIron(mappers) {\n\n function mergeValues(parentItem, childItem) {\n for (let name in parentItem) {\n if (!childItem.hasOwnProperty(name)) {\n childItem[name] = parentItem[name];\n }\n }\n }\n\n function mapProperties(properties, parent, child) {\n for (let i = 0, len = properties.length; i < len; ++i) {\n const property = properties[i];\n\n if (parent[property.name]) {\n if (child[property.name]) {\n // check to see if we should merge\n if (property.merge) {\n const parentValue = parent[property.name];\n const childValue = child[property.name];\n\n // complex objects; merge properties\n if (typeof parentValue === 'object' && typeof childValue === 'object') {\n mergeValues(parentValue, childValue);\n }\n // simple objects; merge them together\n else {\n child[property.name] = parentValue + childValue;\n }\n }\n } else {\n // just add the property\n child[property.name] = parent[property.name];\n }\n }\n }\n }\n\n function mapItem(item, node) {\n for (let i = 0, len = item.children.length; i < len; ++i) {\n const childItem = item.children[i];\n\n const array = node[childItem.name + '_asArray'];\n if (array) {\n for (let v = 0, len2 = array.length; v < len2; ++v) {\n const childNode = array[v];\n mapProperties(item.properties, node, childNode);\n mapItem(childItem, childNode);\n }\n }\n }\n }\n\n function run(source) {\n\n if (source === null || typeof source !== 'object') {\n return source;\n }\n\n if (source.Period_asArray && 'period' in mappers) {\n const periodMapper = mappers.period;\n const periods = source.Period_asArray;\n for (let i = 0, len = periods.length; i < len; ++i) {\n const period = periods[i];\n mapItem(periodMapper, period);\n\n if ('adaptationset' in mappers) {\n const adaptationSets = period.AdaptationSet_asArray;\n if (adaptationSets) {\n const adaptationSetMapper = mappers.adaptationset;\n for (let i = 0, len = adaptationSets.length; i < len; ++i) {\n mapItem(adaptationSetMapper, adaptationSets[i]);\n }\n }\n }\n }\n }\n\n return source;\n }\n\n return {\n run: run\n };\n}\n\n\nObjectIron.__dashjs_factory_name = 'ObjectIron';\nconst factory = FactoryMaker.getClassFactory(ObjectIron);\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n\n/**\n * @classdesc a base type for matching and converting types in manifest to\n * something more useful\n * @ignore\n */\nclass BaseMatcher {\n constructor(test, converter) {\n this._test = test;\n this._converter = converter;\n }\n\n get test() {\n return this._test;\n }\n\n get converter() {\n return this._converter;\n }\n}\n\nexport default BaseMatcher;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @classdesc Matches and converts xs:string to string, but only for specific attributes on specific nodes\n */\nimport BaseMatcher from './BaseMatcher';\nimport DashConstants from '../../constants/DashConstants';\n\nclass StringMatcher extends BaseMatcher {\n constructor() {\n super(\n (attr, nodeName) => {\n const stringAttrsInElements = {\n [DashConstants.MPD]: [ DashConstants.ID, DashConstants.PROFILES ],\n [DashConstants.PERIOD]: [ DashConstants.ID ],\n [DashConstants.BASE_URL]: [ DashConstants.SERVICE_LOCATION, DashConstants.BYTE_RANGE ],\n [DashConstants.SEGMENT_BASE]: [ DashConstants.INDEX_RANGE ],\n [DashConstants.INITIALIZATION]: [ DashConstants.RANGE ],\n [DashConstants.REPRESENTATION_INDEX]: [ DashConstants.RANGE ],\n [DashConstants.SEGMENT_LIST]: [ DashConstants.INDEX_RANGE ],\n [DashConstants.BITSTREAM_SWITCHING]: [ DashConstants.RANGE ],\n [DashConstants.SEGMENT_URL]: [ DashConstants.MEDIA_RANGE, DashConstants.INDEX_RANGE ],\n [DashConstants.SEGMENT_TEMPLATE]: [ DashConstants.INDEX_RANGE, DashConstants.MEDIA, DashConstants.INDEX, DashConstants.INITIALIZATION_MINUS, DashConstants.BITSTREAM_SWITCHING_MINUS ],\n [DashConstants.ASSET_IDENTIFIER]: [ DashConstants.VALUE, DashConstants.ID ],\n [DashConstants.EVENT_STREAM]: [ DashConstants.VALUE ],\n [DashConstants.ADAPTATION_SET]: [ DashConstants.PROFILES, DashConstants.MIME_TYPE, DashConstants.SEGMENT_PROFILES, DashConstants.CODECS, DashConstants.CONTENT_TYPE ],\n [DashConstants.FRAME_PACKING]: [ DashConstants.VALUE, DashConstants.ID ],\n [DashConstants.AUDIO_CHANNEL_CONFIGURATION]: [ DashConstants.VALUE, DashConstants.ID ],\n [DashConstants.CONTENT_PROTECTION]: [ DashConstants.VALUE, DashConstants.ID ],\n [DashConstants.ESSENTIAL_PROPERTY]: [ DashConstants.VALUE, DashConstants.ID ],\n [DashConstants.SUPPLEMENTAL_PROPERTY]: [ DashConstants.VALUE, DashConstants.ID ],\n [DashConstants.INBAND_EVENT_STREAM]: [ DashConstants.VALUE, DashConstants.ID ],\n [DashConstants.ACCESSIBILITY]: [ DashConstants.VALUE, DashConstants.ID ],\n [DashConstants.ROLE]: [ DashConstants.VALUE, DashConstants.ID ],\n [DashConstants.RATING]: [ DashConstants.VALUE, DashConstants.ID ],\n [DashConstants.VIEWPOINT]: [ DashConstants.VALUE, DashConstants.ID ],\n [DashConstants.CONTENT_COMPONENT]: [ DashConstants.CONTENT_TYPE ],\n [DashConstants.REPRESENTATION]: [ DashConstants.ID, DashConstants.DEPENDENCY_ID, DashConstants.MEDIA_STREAM_STRUCTURE_ID ],\n [DashConstants.SUBSET]: [ DashConstants.ID ],\n [DashConstants.METRICS]: [ DashConstants.METRICS_MINUS ],\n [DashConstants.REPORTING]: [ DashConstants.VALUE, DashConstants.ID ]\n };\n if (stringAttrsInElements.hasOwnProperty(nodeName)) {\n let attrNames = stringAttrsInElements[nodeName];\n if (attrNames !== undefined) {\n return attrNames.indexOf(attr.name) >= 0;\n } else {\n return false;\n }\n }\n return false;\n },\n str => String(str)\n );\n }\n}\n\nexport default StringMatcher;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @classdesc matches and converts xs:duration to seconds\n */\nimport BaseMatcher from './BaseMatcher';\nimport Constants from '../../../streaming/constants/Constants';\nimport DashConstants from '../../constants/DashConstants';\n\nconst durationRegex = /^([-])?P(([\\d.]*)Y)?(([\\d.]*)M)?(([\\d.]*)D)?T?(([\\d.]*)H)?(([\\d.]*)M)?(([\\d.]*)S)?/;\n\nconst SECONDS_IN_YEAR = 365 * 24 * 60 * 60;\nconst SECONDS_IN_MONTH = 30 * 24 * 60 * 60;\nconst SECONDS_IN_DAY = 24 * 60 * 60;\nconst SECONDS_IN_HOUR = 60 * 60;\nconst SECONDS_IN_MIN = 60;\n\nclass DurationMatcher extends BaseMatcher {\n constructor() {\n super(\n attr => {\n const attributeList = [\n DashConstants.MIN_BUFFER_TIME, DashConstants.MEDIA_PRESENTATION_DURATION,\n DashConstants.MINIMUM_UPDATE_PERIOD, DashConstants.TIMESHIFT_BUFFER_DEPTH, DashConstants.MAX_SEGMENT_DURATION,\n DashConstants.MAX_SUBSEGMENT_DURATION, DashConstants.SUGGESTED_PRESENTATION_DELAY, DashConstants.START,\n Constants.START_TIME, DashConstants.DURATION\n ];\n const len = attributeList.length;\n\n for (let i = 0; i < len; i++) {\n if (attr.nodeName === attributeList[i]) {\n return durationRegex.test(attr.value);\n }\n }\n\n return false;\n },\n str => {\n //str = \"P10Y10M10DT10H10M10.1S\";\n const match = durationRegex.exec(str);\n let result = (parseFloat(match[3] || 0) * SECONDS_IN_YEAR +\n parseFloat(match[5] || 0) * SECONDS_IN_MONTH +\n parseFloat(match[7] || 0) * SECONDS_IN_DAY +\n parseFloat(match[9] || 0) * SECONDS_IN_HOUR +\n parseFloat(match[11] || 0) * SECONDS_IN_MIN +\n parseFloat(match[13] || 0));\n\n if (match[1] !== undefined) {\n result = -result;\n }\n\n return result;\n }\n );\n }\n}\n\nexport default DurationMatcher;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @classdesc matches and converts xs:datetime to Date\n */\nimport BaseMatcher from './BaseMatcher';\n\nconst SECONDS_IN_MIN = 60;\nconst MINUTES_IN_HOUR = 60;\nconst MILLISECONDS_IN_SECONDS = 1000;\n\nconst datetimeRegex = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2})(?::([0-9]*)(\\.[0-9]*)?)?(?:([+-])([0-9]{2})(?::?)([0-9]{2}))?/;\n\nclass DateTimeMatcher extends BaseMatcher {\n constructor() {\n super(\n attr => datetimeRegex.test(attr.value),\n str => {\n const match = datetimeRegex.exec(str);\n let utcDate;\n\n // If the string does not contain a timezone offset different browsers can interpret it either\n // as UTC or as a local time so we have to parse the string manually to normalize the given date value for\n // all browsers\n utcDate = Date.UTC(\n parseInt(match[1], 10),\n parseInt(match[2], 10) - 1, // months start from zero\n parseInt(match[3], 10),\n parseInt(match[4], 10),\n parseInt(match[5], 10),\n (match[6] && parseInt(match[6], 10) || 0),\n (match[7] && parseFloat(match[7]) * MILLISECONDS_IN_SECONDS) || 0);\n\n // If the date has timezone offset take it into account as well\n if (match[9] && match[10]) {\n const timezoneOffset = parseInt(match[9], 10) * MINUTES_IN_HOUR + parseInt(match[10], 10);\n utcDate += (match[8] === '+' ? -1 : +1) * timezoneOffset * SECONDS_IN_MIN * MILLISECONDS_IN_SECONDS;\n }\n\n return new Date(utcDate);\n }\n );\n }\n}\n\nexport default DateTimeMatcher;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @classdesc Matches and converts xs:numeric to float\n */\nimport BaseMatcher from './BaseMatcher';\n\nconst numericRegex = /^[-+]?[0-9]+[.]?[0-9]*([eE][-+]?[0-9]+)?$/;\n\nclass NumericMatcher extends BaseMatcher {\n constructor() {\n super(\n attr => numericRegex.test(attr.value),\n str => parseFloat(str)\n );\n }\n}\n\nexport default NumericMatcher;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @classdesc a property belonging to a MapNode\n * @ignore\n */\n\nclass CommonProperty {\n constructor(name) {\n const getDefaultMergeForName =\n (n) => n && n.length && n.charAt(0) === n.charAt(0).toUpperCase();\n\n this._name = name;\n this._merge = getDefaultMergeForName(name);\n }\n\n get name() {\n return this._name;\n }\n\n get merge() {\n return this._merge;\n }\n}\n\nexport default CommonProperty;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @classdesc a node at some level in a ValueMap\n */\nimport CommonProperty from './CommonProperty';\n\nclass MapNode {\n constructor(name, properties, children) {\n this._name = name || '';\n this._properties = [];\n this._children = children || [];\n\n if (Array.isArray(properties)) {\n properties.forEach(p => {\n this._properties.push(new CommonProperty(p));\n });\n }\n }\n\n get name() {\n return this._name;\n }\n\n get children() {\n return this._children;\n }\n\n get properties() {\n return this._properties;\n }\n}\n\nexport default MapNode;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @classdesc a RepresentationBaseValuesMap type for input to objectiron\n */\nimport MapNode from './MapNode';\nimport DashConstants from '../../constants/DashConstants';\n\nclass RepresentationBaseValuesMap extends MapNode {\n constructor() {\n const commonProperties = [\n DashConstants.PROFILES, DashConstants.WIDTH, DashConstants.HEIGHT, DashConstants.SAR, DashConstants.FRAMERATE, DashConstants.AUDIO_SAMPLING_RATE, DashConstants.MIME_TYPE, DashConstants.SEGMENT_PROFILES, DashConstants.CODECS, DashConstants.MAXIMUM_SAP_PERIOD, DashConstants.START_WITH_SAP, DashConstants.MAX_PLAYOUT_RATE, DashConstants.CODING_DEPENDENCY, DashConstants.SCAN_TYPE, DashConstants.FRAME_PACKING, DashConstants.AUDIO_CHANNEL_CONFIGURATION, DashConstants.CONTENT_PROTECTION, DashConstants.ESSENTIAL_PROPERTY, DashConstants.SUPPLEMENTAL_PROPERTY, DashConstants.INBAND_EVENT_STREAM\n ];\n\n super(DashConstants.ADAPTATION_SET, commonProperties, [\n new MapNode(DashConstants.REPRESENTATION, commonProperties, [\n new MapNode(DashConstants.SUB_REPRESENTATION, commonProperties)\n ])\n ]);\n }\n}\n\nexport default RepresentationBaseValuesMap;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @classdesc a SegmentValuesMap type for input to objectiron\n */\nimport MapNode from './MapNode';\nimport DashConstants from '../../constants/DashConstants';\n\nclass SegmentValuesMap extends MapNode {\n constructor() {\n const commonProperties = [\n DashConstants.SEGMENT_BASE, DashConstants.SEGMENT_TEMPLATE, DashConstants.SEGMENT_LIST\n ];\n\n super(DashConstants.PERIOD, commonProperties, [\n new MapNode(DashConstants.ADAPTATION_SET, commonProperties, [\n new MapNode(DashConstants.REPRESENTATION, commonProperties)\n ])\n ]);\n }\n}\n\nexport default SegmentValuesMap;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport FactoryMaker from '../../core/FactoryMaker';\nimport ObjectIron from './objectiron';\nimport X2JS from '../../../externals/xml2json';\nimport StringMatcher from './matchers/StringMatcher';\nimport DurationMatcher from './matchers/DurationMatcher';\nimport DateTimeMatcher from './matchers/DateTimeMatcher';\nimport NumericMatcher from './matchers/NumericMatcher';\nimport RepresentationBaseValuesMap from './maps/RepresentationBaseValuesMap';\nimport SegmentValuesMap from './maps/SegmentValuesMap';\n\nfunction DashParser(config) {\n\n config = config || {};\n const context = this.context;\n const debug = config.debug;\n\n let instance,\n logger,\n matchers,\n converter,\n objectIron;\n\n function setup() {\n logger = debug.getLogger(instance);\n matchers = [\n new DurationMatcher(),\n new DateTimeMatcher(),\n new NumericMatcher(),\n new StringMatcher() // last in list to take precedence over NumericMatcher\n ];\n\n converter = new X2JS({\n escapeMode: false,\n attributePrefix: '',\n arrayAccessForm: 'property',\n emptyNodeForm: 'object',\n stripWhitespaces: false,\n enableToStringFunc: true,\n ignoreRoot: false,\n matchers: matchers\n });\n\n objectIron = ObjectIron(context).create({\n adaptationset: new RepresentationBaseValuesMap(),\n period: new SegmentValuesMap()\n });\n }\n\n function getMatchers() {\n return matchers;\n }\n\n function getIron() {\n return objectIron;\n }\n\n function parse(data) {\n let manifest;\n const startTime = window.performance.now();\n\n manifest = converter.xml_str2json(data);\n\n if (!manifest) {\n throw new Error('parsing the manifest failed');\n }\n\n const jsonTime = window.performance.now();\n\n // handle full MPD and Patch ironing separately\n if (manifest.Patch) {\n manifest = manifest.Patch; // drop root reference\n // apply iron to patch operations individually\n if (manifest.add_asArray) {\n manifest.add_asArray.forEach((operand) => objectIron.run(operand));\n }\n if (manifest.replace_asArray) {\n manifest.replace_asArray.forEach((operand) => objectIron.run(operand));\n }\n // note that we don't need to iron remove as they contain no children\n } else {\n manifest = manifest.MPD; // drop root reference\n objectIron.run(manifest);\n }\n\n const ironedTime = window.performance.now();\n logger.info('Parsing complete: ( xml2json: ' + (jsonTime - startTime).toPrecision(3) + 'ms, objectiron: ' + (ironedTime - jsonTime).toPrecision(3) + 'ms, total: ' + ((ironedTime - startTime) / 1000).toPrecision(3) + 's)');\n\n manifest.protocol = 'DASH';\n\n return manifest;\n }\n\n instance = {\n parse: parse,\n getMatchers: getMatchers,\n getIron: getIron\n };\n\n setup();\n\n return instance;\n}\n\nDashParser.__dashjs_factory_name = 'DashParser';\nexport default FactoryMaker.getClassFactory(DashParser);\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nimport FragmentRequest from './FragmentRequest';\n\nclass HeadRequest extends FragmentRequest {\n constructor(url) {\n super(url);\n this.checkForExistenceOnly = true;\n }\n}\n\nexport default HeadRequest;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport Constants from './constants/Constants';\nimport URLLoader from './net/URLLoader';\nimport HeadRequest from './vo/HeadRequest';\nimport DashJSError from './vo/DashJSError';\nimport FactoryMaker from '../core/FactoryMaker';\n\nfunction FragmentLoader(config) {\n\n config = config || {};\n const context = this.context;\n const eventBus = config.eventBus;\n const events = config.events;\n const urlUtils = config.urlUtils;\n const errors = config.errors;\n const streamId = config.streamId;\n\n let instance,\n urlLoader;\n\n function setup() {\n urlLoader = URLLoader(context).create({\n errHandler: config.errHandler,\n errors: errors,\n dashMetrics: config.dashMetrics,\n mediaPlayerModel: config.mediaPlayerModel,\n requestModifier: config.requestModifier,\n urlUtils: urlUtils,\n constants: Constants,\n boxParser: config.boxParser,\n dashConstants: config.dashConstants,\n requestTimeout: config.settings.get().streaming.fragmentRequestTimeout\n });\n }\n\n function checkForExistence(request) {\n const report = function (success) {\n eventBus.trigger(events.CHECK_FOR_EXISTENCE_COMPLETED, {\n request: request,\n exists: success\n }\n );\n };\n\n if (request) {\n let headRequest = new HeadRequest(request.url);\n urlLoader.load({\n request: headRequest,\n success: function () {\n report(true);\n },\n error: function () {\n report(false);\n }\n });\n } else {\n report(false);\n }\n }\n\n function load(request) {\n const report = function (data, error) {\n eventBus.trigger(events.LOADING_COMPLETED, {\n request: request,\n response: data || null,\n error: error || null,\n sender: instance\n });\n };\n\n if (request) {\n urlLoader.load({\n request: request,\n progress: function (event) {\n eventBus.trigger(events.LOADING_PROGRESS, {\n request: request,\n stream: event.stream,\n streamId\n });\n if (event.data) {\n eventBus.trigger(events.LOADING_DATA_PROGRESS, {\n request: request,\n response: event.data || null,\n error: null,\n sender: instance\n });\n }\n },\n success: function (data) {\n report(data);\n },\n error: function (request, statusText, errorText) {\n report(\n undefined,\n new DashJSError(\n errors.FRAGMENT_LOADER_LOADING_FAILURE_ERROR_CODE,\n errorText,\n statusText\n )\n );\n },\n abort: function (request) {\n if (request) {\n eventBus.trigger(events.LOADING_ABANDONED, {\n mediaType: request.mediaType,\n request: request,\n sender: instance\n });\n }\n }\n });\n } else {\n report(\n undefined,\n new DashJSError(\n errors.FRAGMENT_LOADER_NULL_REQUEST_ERROR_CODE,\n errors.FRAGMENT_LOADER_NULL_REQUEST_ERROR_MESSAGE\n )\n );\n }\n }\n\n function abort() {\n if (urlLoader) {\n urlLoader.abort();\n }\n }\n\n function reset() {\n if (urlLoader) {\n urlLoader.abort();\n urlLoader = null;\n }\n }\n\n instance = {\n checkForExistence: checkForExistence,\n load: load,\n abort: abort,\n reset: reset\n };\n\n setup();\n\n return instance;\n}\n\nFragmentLoader.__dashjs_factory_name = 'FragmentLoader';\nexport default FactoryMaker.getClassFactory(FragmentLoader);\n","/* \r\n * Copyright (c) 2016, Pierre-Anthony Lemieux <pal@sandflow.com>\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *\r\n * * Redistributions of source code must retain the above copyright notice, this\r\n * list of conditions and the following disclaimer.\r\n * * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the documentation\r\n * and/or other materials provided with the distribution.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\r\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n * POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\n/**\r\n * @module imscStyles\r\n */\r\n\r\n;\r\n(function (imscStyles, imscNames, imscUtils) { // wrapper for non-node envs\r\n\r\n function StylingAttributeDefinition(ns, name, initialValue, appliesTo, isInherit, isAnimatable, parseFunc, computeFunc) {\r\n this.name = name;\r\n this.ns = ns;\r\n this.qname = ns + \" \" + name;\r\n this.inherit = isInherit;\r\n this.animatable = isAnimatable;\r\n this.initial = initialValue;\r\n this.applies = appliesTo;\r\n this.parse = parseFunc;\r\n this.compute = computeFunc;\r\n }\r\n\r\n imscStyles.all = [\r\n\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"backgroundColor\",\r\n \"transparent\",\r\n ['body', 'div', 'p', 'region', 'span'],\r\n false,\r\n true,\r\n imscUtils.parseColor,\r\n null\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"color\",\r\n \"white\",\r\n ['span'],\r\n true,\r\n true,\r\n imscUtils.parseColor,\r\n null\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"direction\",\r\n \"ltr\",\r\n ['p', 'span'],\r\n true,\r\n true,\r\n function (str) {\r\n return str;\r\n },\r\n null\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"display\",\r\n \"auto\",\r\n ['body', 'div', 'p', 'region', 'span'],\r\n false,\r\n true,\r\n function (str) {\r\n return str;\r\n },\r\n null\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"displayAlign\",\r\n \"before\",\r\n ['region'],\r\n false,\r\n true,\r\n function (str) {\r\n return str;\r\n },\r\n null\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"extent\",\r\n \"auto\",\r\n ['tt', 'region'],\r\n false,\r\n true,\r\n function (str) {\r\n\r\n if (str === \"auto\") {\r\n\r\n return str;\r\n\r\n } else {\r\n\r\n var s = str.split(\" \");\r\n if (s.length !== 2) return null;\r\n var w = imscUtils.parseLength(s[0]);\r\n var h = imscUtils.parseLength(s[1]);\r\n if (!h || !w) return null;\r\n return {'h': h, 'w': w};\r\n }\r\n\r\n },\r\n function (doc, parent, element, attr, context) {\r\n\r\n var h;\r\n var w;\r\n\r\n if (attr === \"auto\") {\r\n\r\n h = 1;\r\n\r\n } else if (attr.h.unit === \"%\") {\r\n\r\n h = attr.h.value / 100;\r\n\r\n } else if (attr.h.unit === \"px\") {\r\n\r\n h = attr.h.value / doc.pxDimensions.h;\r\n\r\n } else {\r\n\r\n return null;\r\n\r\n }\r\n\r\n if (attr === \"auto\") {\r\n\r\n w = 1;\r\n\r\n } else if (attr.w.unit === \"%\") {\r\n\r\n w = attr.w.value / 100;\r\n\r\n } else if (attr.w.unit === \"px\") {\r\n\r\n w = attr.w.value / doc.pxDimensions.w;\r\n\r\n } else {\r\n\r\n return null;\r\n\r\n }\r\n\r\n return {'h': h, 'w': w};\r\n }\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"fontFamily\",\r\n \"default\",\r\n ['span'],\r\n true,\r\n true,\r\n function (str) {\r\n var ffs = str.split(\",\");\r\n var rslt = [];\r\n\r\n for (var i in ffs) {\r\n\r\n if (ffs[i].charAt(0) !== \"'\" && ffs[i].charAt(0) !== '\"') {\r\n\r\n if (ffs[i] === \"default\") {\r\n\r\n /* per IMSC1 */\r\n\r\n rslt.push(\"monospaceSerif\");\r\n\r\n } else {\r\n\r\n rslt.push(ffs[i]);\r\n\r\n }\r\n\r\n } else {\r\n\r\n rslt.push(ffs[i]);\r\n\r\n }\r\n\r\n }\r\n\r\n return rslt;\r\n },\r\n null\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"fontSize\",\r\n \"1c\",\r\n ['span'],\r\n true,\r\n true,\r\n imscUtils.parseLength,\r\n function (doc, parent, element, attr, context) {\r\n\r\n var fs;\r\n\r\n if (attr.unit === \"%\") {\r\n\r\n if (parent !== null) {\r\n\r\n fs = parent.styleAttrs[imscStyles.byName.fontSize.qname] * attr.value / 100;\r\n\r\n } else {\r\n\r\n /* region, so percent of 1c */\r\n\r\n fs = attr.value / 100 / doc.cellResolution.h;\r\n\r\n }\r\n\r\n } else if (attr.unit === \"em\") {\r\n\r\n if (parent !== null) {\r\n\r\n fs = parent.styleAttrs[imscStyles.byName.fontSize.qname] * attr.value;\r\n\r\n } else {\r\n\r\n /* region, so percent of 1c */\r\n\r\n fs = attr.value / doc.cellResolution.h;\r\n\r\n }\r\n\r\n } else if (attr.unit === \"c\") {\r\n\r\n fs = attr.value / doc.cellResolution.h;\r\n\r\n } else if (attr.unit === \"px\") {\r\n\r\n fs = attr.value / doc.pxDimensions.h;\r\n\r\n } else {\r\n\r\n return null;\r\n\r\n }\r\n\r\n return fs;\r\n }\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"fontStyle\",\r\n \"normal\",\r\n ['span'],\r\n true,\r\n true,\r\n function (str) {\r\n /* TODO: handle font style */\r\n\r\n return str;\r\n },\r\n null\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"fontWeight\",\r\n \"normal\",\r\n ['span'],\r\n true,\r\n true,\r\n function (str) {\r\n /* TODO: handle font weight */\r\n\r\n return str;\r\n },\r\n null\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"lineHeight\",\r\n \"normal\",\r\n ['p'],\r\n true,\r\n true,\r\n function (str) {\r\n if (str === \"normal\") {\r\n return str;\r\n } else {\r\n return imscUtils.parseLength(str);\r\n }\r\n },\r\n function (doc, parent, element, attr, context) {\r\n\r\n var lh;\r\n\r\n if (attr === \"normal\") {\r\n\r\n /* inherit normal per https://github.com/w3c/ttml1/issues/220 */\r\n\r\n lh = attr;\r\n\r\n } else if (attr.unit === \"%\") {\r\n\r\n lh = element.styleAttrs[imscStyles.byName.fontSize.qname] * attr.value / 100;\r\n\r\n } else if (attr.unit === \"em\") {\r\n\r\n lh = element.styleAttrs[imscStyles.byName.fontSize.qname] * attr.value;\r\n\r\n } else if (attr.unit === \"c\") {\r\n\r\n lh = attr.value / doc.cellResolution.h;\r\n\r\n } else if (attr.unit === \"px\") {\r\n\r\n /* TODO: handle error if no px dimensions are provided */\r\n\r\n lh = attr.value / doc.pxDimensions.h;\r\n\r\n } else {\r\n\r\n return null;\r\n\r\n }\r\n\r\n /* TODO: create a Length constructor */\r\n\r\n return lh;\r\n }\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"opacity\",\r\n 1.0,\r\n ['region'],\r\n false,\r\n true,\r\n parseFloat,\r\n null\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"origin\",\r\n \"auto\",\r\n ['region'],\r\n false,\r\n true,\r\n function (str) {\r\n\r\n if (str === \"auto\") {\r\n\r\n return str;\r\n\r\n } else {\r\n\r\n var s = str.split(\" \");\r\n if (s.length !== 2) return null;\r\n var w = imscUtils.parseLength(s[0]);\r\n var h = imscUtils.parseLength(s[1]);\r\n if (!h || !w) return null;\r\n return {'h': h, 'w': w};\r\n }\r\n\r\n },\r\n function (doc, parent, element, attr, context) {\r\n\r\n var h;\r\n var w;\r\n\r\n if (attr === \"auto\") {\r\n\r\n h = 0;\r\n\r\n } else if (attr.h.unit === \"%\") {\r\n\r\n h = attr.h.value / 100;\r\n\r\n } else if (attr.h.unit === \"px\") {\r\n\r\n h = attr.h.value / doc.pxDimensions.h;\r\n\r\n } else {\r\n\r\n return null;\r\n\r\n }\r\n\r\n if (attr === \"auto\") {\r\n\r\n w = 0;\r\n\r\n } else if (attr.w.unit === \"%\") {\r\n\r\n w = attr.w.value / 100;\r\n\r\n } else if (attr.w.unit === \"px\") {\r\n\r\n w = attr.w.value / doc.pxDimensions.w;\r\n\r\n } else {\r\n\r\n return null;\r\n\r\n }\r\n\r\n return {'h': h, 'w': w};\r\n }\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"overflow\",\r\n \"hidden\",\r\n ['region'],\r\n false,\r\n true,\r\n function (str) {\r\n return str;\r\n },\r\n null\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"padding\",\r\n \"0px\",\r\n ['region'],\r\n false,\r\n true,\r\n function (str) {\r\n\r\n var s = str.split(\" \");\r\n if (s.length > 4) return null;\r\n var r = [];\r\n for (var i in s) {\r\n\r\n var l = imscUtils.parseLength(s[i]);\r\n if (!l) return null;\r\n r.push(l);\r\n }\r\n\r\n return r;\r\n },\r\n function (doc, parent, element, attr, context) {\r\n\r\n var padding;\r\n\r\n /* TODO: make sure we are in region */\r\n\r\n /*\r\n * expand padding shortcuts to \r\n * [before, end, after, start]\r\n * \r\n */\r\n\r\n if (attr.length === 1) {\r\n\r\n padding = [attr[0], attr[0], attr[0], attr[0]];\r\n\r\n } else if (attr.length === 2) {\r\n\r\n padding = [attr[0], attr[1], attr[0], attr[1]];\r\n\r\n } else if (attr.length === 3) {\r\n\r\n padding = [attr[0], attr[1], attr[2], attr[1]];\r\n\r\n } else if (attr.length === 4) {\r\n\r\n padding = [attr[0], attr[1], attr[2], attr[3]];\r\n\r\n } else {\r\n\r\n return null;\r\n\r\n }\r\n\r\n /* TODO: take into account tts:direction */\r\n\r\n /* \r\n * transform [before, end, after, start] according to writingMode to \r\n * [top,left,bottom,right]\r\n * \r\n */\r\n\r\n var dir = element.styleAttrs[imscStyles.byName.writingMode.qname];\r\n\r\n if (dir === \"lrtb\" || dir === \"lr\") {\r\n\r\n padding = [padding[0], padding[3], padding[2], padding[1]];\r\n\r\n } else if (dir === \"rltb\" || dir === \"rl\") {\r\n\r\n padding = [padding[0], padding[1], padding[2], padding[3]];\r\n\r\n } else if (dir === \"tblr\") {\r\n\r\n padding = [padding[3], padding[0], padding[1], padding[2]];\r\n\r\n } else if (dir === \"tbrl\" || dir === \"tb\") {\r\n\r\n padding = [padding[3], padding[2], padding[1], padding[0]];\r\n\r\n } else {\r\n\r\n return null;\r\n\r\n }\r\n\r\n var out = [];\r\n\r\n for (var i in padding) {\r\n\r\n if (padding[i].value === 0) {\r\n\r\n out[i] = 0;\r\n\r\n } else if (padding[i].unit === \"%\") {\r\n\r\n if (i === \"0\" || i === \"2\") {\r\n\r\n out[i] = element.styleAttrs[imscStyles.byName.extent.qname].h * padding[i].value / 100;\r\n\r\n } else {\r\n\r\n out[i] = element.styleAttrs[imscStyles.byName.extent.qname].w * padding[i].value / 100;\r\n }\r\n\r\n } else if (padding[i].unit === \"em\") {\r\n\r\n out[i] = element.styleAttrs[imscStyles.byName.fontSize.qname] * padding[i].value;\r\n\r\n } else if (padding[i].unit === \"c\") {\r\n\r\n out[i] = padding[i].value / doc.cellResolution.h;\r\n\r\n } else if (padding[i].unit === \"px\") {\r\n \r\n if (i === \"0\" || i === \"2\") {\r\n\r\n out[i] = padding[i].value / doc.pxDimensions.h;\r\n\r\n } else {\r\n\r\n out[i] = padding[i].value / doc.pxDimensions.w;\r\n }\r\n \r\n } else {\r\n\r\n return null;\r\n\r\n }\r\n }\r\n\r\n\r\n return out;\r\n }\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"showBackground\",\r\n \"always\",\r\n ['region'],\r\n false,\r\n true,\r\n function (str) {\r\n return str;\r\n },\r\n null\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"textAlign\",\r\n \"start\",\r\n ['p'],\r\n true,\r\n true,\r\n function (str) {\r\n return str;\r\n },\r\n function (doc, parent, element, attr, context) {\r\n \r\n /* Section 7.16.9 of XSL */\r\n \r\n if (attr === \"left\") {\r\n \r\n return \"start\";\r\n \r\n } else if (attr === \"right\") {\r\n \r\n return \"end\";\r\n \r\n } else {\r\n \r\n return attr;\r\n \r\n }\r\n }\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"textDecoration\",\r\n \"none\",\r\n ['span'],\r\n true,\r\n true,\r\n function (str) {\r\n return str.split(\" \");\r\n },\r\n null\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"textOutline\",\r\n \"none\",\r\n ['span'],\r\n true,\r\n true,\r\n function (str) {\r\n\r\n /*\r\n * returns {c: <color>?, thichness: <length>} | \"none\"\r\n * \r\n */\r\n\r\n if (str === \"none\") {\r\n\r\n return str;\r\n\r\n } else {\r\n\r\n var r = {};\r\n var s = str.split(\" \");\r\n if (s.length === 0 || s.length > 2) return null;\r\n var c = imscUtils.parseColor(s[0]);\r\n \r\n r.color = c;\r\n \r\n if (c !== null) s.shift();\r\n\r\n if (s.length !== 1) return null;\r\n\r\n var l = imscUtils.parseLength(s[0]);\r\n\r\n if (!l) return null;\r\n\r\n r.thickness = l;\r\n\r\n return r;\r\n }\r\n\r\n },\r\n function (doc, parent, element, attr, context) {\r\n\r\n /*\r\n * returns {color: <color>, thickness: <norm length>}\r\n * \r\n */\r\n\r\n if (attr === \"none\") return attr;\r\n\r\n var rslt = {};\r\n\r\n if (attr.color === null) {\r\n \r\n rslt.color = element.styleAttrs[imscStyles.byName.color.qname];\r\n \r\n } else {\r\n \r\n rslt.color = attr.color;\r\n\r\n }\r\n\r\n if (attr.thickness.unit === \"%\") {\r\n\r\n rslt.thickness = element.styleAttrs[imscStyles.byName.fontSize.qname] * attr.thickness.value / 100;\r\n\r\n } else if (attr.thickness.unit === \"em\") {\r\n\r\n rslt.thickness = element.styleAttrs[imscStyles.byName.fontSize.qname] * attr.thickness.value;\r\n\r\n } else if (attr.thickness.unit === \"c\") {\r\n\r\n rslt.thickness = attr.thickness.value / doc.cellResolution.h;\r\n\r\n } else if (attr.thickness.unit === \"px\") {\r\n\r\n rslt.thickness = attr.thickness.value / doc.pxDimensions.h;\r\n\r\n } else {\r\n\r\n return null;\r\n\r\n }\r\n\r\n\r\n return rslt;\r\n }\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"unicodeBidi\",\r\n \"normal\",\r\n ['span', 'p'],\r\n false,\r\n true,\r\n function (str) {\r\n return str;\r\n },\r\n null\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"visibility\",\r\n \"visible\",\r\n ['body', 'div', 'p', 'region', 'span'],\r\n true,\r\n true,\r\n function (str) {\r\n return str;\r\n },\r\n null\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"wrapOption\",\r\n \"wrap\",\r\n ['span'],\r\n true,\r\n true,\r\n function (str) {\r\n return str;\r\n },\r\n null\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"writingMode\",\r\n \"lrtb\",\r\n ['region'],\r\n false,\r\n true,\r\n function (str) {\r\n return str;\r\n },\r\n null\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_tts,\r\n \"zIndex\",\r\n \"auto\",\r\n ['region'],\r\n false,\r\n true,\r\n function (str) {\r\n \r\n var rslt;\r\n \r\n if (str === 'auto') {\r\n \r\n rslt = str;\r\n \r\n } else {\r\n \r\n rslt = parseInt(str);\r\n \r\n if (isNaN(rslt)) {\r\n rslt = null;\r\n }\r\n \r\n }\r\n \r\n return rslt;\r\n },\r\n null\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_ebutts,\r\n \"linePadding\",\r\n \"0c\",\r\n ['p'],\r\n true,\r\n false,\r\n imscUtils.parseLength,\r\n function (doc, parent, element, attr, context) {\r\n if (attr.unit === \"c\") {\r\n\r\n return attr.value / doc.cellResolution.h;\r\n\r\n } else {\r\n\r\n return null;\r\n\r\n }\r\n }\r\n ),\r\n new StylingAttributeDefinition(\r\n imscNames.ns_ebutts,\r\n \"multiRowAlign\",\r\n \"auto\",\r\n ['p'],\r\n true,\r\n false,\r\n function (str) {\r\n return str;\r\n },\r\n null\r\n ),\r\n\r\n new StylingAttributeDefinition(\r\n imscNames.ns_smpte,\r\n \"backgroundImage\",\r\n null,\r\n ['div'],\r\n false,\r\n false,\r\n function (str) {\r\n return str;\r\n },\r\n null\r\n ),\r\n\r\n new StylingAttributeDefinition(\r\n imscNames.ns_itts,\r\n \"forcedDisplay\",\r\n \"false\",\r\n ['body', 'div', 'p', 'region', 'span'],\r\n true,\r\n true,\r\n function (str) {\r\n return str === 'true' ? true : false;\r\n },\r\n null\r\n ),\r\n\r\n new StylingAttributeDefinition(\r\n imscNames.ns_itts,\r\n \"fillLineGap\",\r\n \"false\",\r\n ['p'],\r\n true,\r\n true,\r\n function (str) {\r\n return str === 'true' ? true : false;\r\n },\r\n null\r\n )\r\n ];\r\n\r\n /* TODO: allow null parse function */\r\n\r\n imscStyles.byQName = {};\r\n for (var i in imscStyles.all) {\r\n\r\n imscStyles.byQName[imscStyles.all[i].qname] = imscStyles.all[i];\r\n }\r\n\r\n imscStyles.byName = {};\r\n for (var j in imscStyles.all) {\r\n\r\n imscStyles.byName[imscStyles.all[j].name] = imscStyles.all[j];\r\n }\r\n\r\n})(typeof exports === 'undefined' ? this.imscStyles = {} : exports,\r\n typeof imscNames === 'undefined' ? require(\"./names\") : imscNames,\r\n typeof imscUtils === 'undefined' ? require(\"./utils\") : imscUtils);\r\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh <http://feross.org>\n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : typedArraySupport()\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nexports.kMaxLength = kMaxLength()\n\nfunction typedArraySupport () {\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42 && // typed array instances can be augmented\n typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n } catch (e) {\n return false\n }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true\n })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return '<Buffer ' + str + '>'\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction _getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n checkListener(listener);\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = _getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n checkListener(listener);\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function errorListener(err) {\n emitter.removeListener(name, resolver);\n reject(err);\n }\n\n function resolver() {\n if (typeof emitter.removeListener === 'function') {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n\n eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n if (name !== 'error') {\n addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n }\n });\n}\n\nfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n if (typeof emitter.on === 'function') {\n eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n }\n}\n\nfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n if (typeof emitter.on === 'function') {\n if (flags.once) {\n emitter.once(name, listener);\n } else {\n emitter.on(name, listener);\n }\n } else if (typeof emitter.addEventListener === 'function') {\n // EventTarget does not have `error` event semantics like Node\n // EventEmitters, we do not listen for `error` events here.\n emitter.addEventListener(name, function wrapListener(arg) {\n // IE does not have builtin `{ once: true }` support so we\n // have to do it manually.\n if (flags.once) {\n emitter.removeEventListener(name, wrapListener);\n }\n listener(arg);\n });\n } else {\n throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n }\n}\n","exports = module.exports = require('./lib/_stream_readable.js');\nexports.Stream = exports;\nexports.Readable = exports;\nexports.Writable = require('./lib/_stream_writable.js');\nexports.Duplex = require('./lib/_stream_duplex.js');\nexports.Transform = require('./lib/_stream_transform.js');\nexports.PassThrough = require('./lib/_stream_passthrough.js');\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n'use strict';\n\n/*<replacement>*/\n\nvar pna = require('process-nextick-args');\n/*</replacement>*/\n\nmodule.exports = Writable;\n\n/* <replacement> */\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n}\n\n// It seems a linked list but it is not\n// there will be only 2 of these for each stream\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* </replacement> */\n\n/*<replacement>*/\nvar asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;\n/*</replacement>*/\n\n/*<replacement>*/\nvar Duplex;\n/*</replacement>*/\n\nWritable.WritableState = WritableState;\n\n/*<replacement>*/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/*</replacement>*/\n\n/*<replacement>*/\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/*</replacement>*/\n\n/*<replacement>*/\nvar Stream = require('./internal/streams/stream');\n/*</replacement>*/\n\n/*<replacement>*/\n\nvar Buffer = require('safe-buffer').Buffer;\nvar OurUint8Array = global.Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/*</replacement>*/\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nutil.inherits(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n var hwm = options.highWaterMark;\n var writableHwm = options.writableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // if _final has been called\n this.finalCalled = false;\n\n // drain event flag.\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // when true all writes will be buffered until .uncork() call\n this.corked = 0;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function (er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n\n this.bufferedRequest = null;\n this.lastBufferedRequest = null;\n\n // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n this.pendingcb = 0;\n\n // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n this.prefinished = false;\n\n // True if the error was already emitted and should not be thrown again\n this.errorEmitted = false;\n\n // count buffered requests\n this.bufferedRequestCount = 0;\n\n // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n while (current) {\n out.push(current);\n current = current.next;\n }\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function () {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})();\n\n// Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\nvar realHasInstance;\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function (object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function (object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {\n return new Writable(options);\n }\n\n this._writableState = new WritableState(options, this);\n\n // legacy.\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n\n if (typeof options.writev === 'function') this._writev = options.writev;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n this.emit('error', new Error('Cannot pipe, not readable'));\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new Error('write after end');\n // TODO: defer error events consistently everywhere, not just the cb\n stream.emit('error', er);\n pna.nextTick(cb, er);\n}\n\n// Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\nfunction validChunk(stream, state, chunk, cb) {\n var valid = true;\n var er = false;\n\n if (chunk === null) {\n er = new TypeError('May not write null values to stream');\n } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n if (er) {\n stream.emit('error', er);\n pna.nextTick(cb, er);\n valid = false;\n }\n return valid;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n\n if (typeof cb !== 'function') cb = nop;\n\n if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n\n return ret;\n};\n\nWritable.prototype.cork = function () {\n var state = this._writableState;\n\n state.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n\n if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n var len = state.objectMode ? 1 : chunk.length;\n\n state.length += len;\n\n var ret = state.length < state.highWaterMark;\n // we must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n pna.nextTick(cb, er);\n // this can emit finish, and it will always happen\n // after error\n pna.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n // this can emit finish, but finish must\n // always follow error\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n\n onwriteStateUpdate(state);\n\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state);\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n /*<replacement>*/\n asyncWrite(afterWrite, stream, state, finished, cb);\n /*</replacement>*/\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n\n var count = 0;\n var allBuffers = true;\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n buffer.allBuffers = allBuffers;\n\n doWrite(stream, state, true, state.length, buffer, '', holder.finish);\n\n // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n state.pendingcb++;\n state.lastBufferedRequest = null;\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--;\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new Error('_write() is not implemented'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);\n\n // .end() fully uncorks\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n }\n\n // ignore unnecessary end() calls.\n if (!state.ending && !state.finished) endWritable(this, state, cb);\n};\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n if (err) {\n stream.emit('error', err);\n }\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function') {\n state.pendingcb++;\n state.finalCalled = true;\n pna.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n if (need) {\n prefinish(stream, state);\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n }\n }\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);\n }\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n }\n if (state.corkedRequestsFree) {\n state.corkedRequestsFree.next = corkReq;\n } else {\n state.corkedRequestsFree = corkReq;\n }\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n get: function () {\n if (this._writableState === undefined) {\n return false;\n }\n return this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._writableState.destroyed = value;\n }\n});\n\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\nWritable.prototype._destroy = function (err, cb) {\n this.end();\n cb(err);\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/*<replacement>*/\n\nvar Buffer = require('safe-buffer').Buffer;\n/*</replacement>*/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}","/* \r\n * Copyright (c) 2016, Pierre-Anthony Lemieux <pal@sandflow.com>\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *\r\n * * Redistributions of source code must retain the above copyright notice, this\r\n * list of conditions and the following disclaimer.\r\n * * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the documentation\r\n * and/or other materials provided with the distribution.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\r\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n * POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\n/**\r\n * @module imscUtils\r\n */\r\n\r\n;\r\n(function (imscUtils) { // wrapper for non-node envs\r\n \r\n /* Documents the error handler interface */\r\n \r\n /**\r\n * @classdesc Generic interface for handling events. The interface exposes four\r\n * methods:\r\n * * <pre>info</pre>: unusual event that does not result in an inconsistent state\r\n * * <pre>warn</pre>: unexpected event that should not result in an inconsistent state\r\n * * <pre>error</pre>: unexpected event that may result in an inconsistent state\r\n * * <pre>fatal</pre>: unexpected event that results in an inconsistent state\r\n * and termination of processing\r\n * Each method takes a single <pre>string</pre> describing the event as argument,\r\n * and returns a single <pre>boolean</pre>, which terminates processing if <pre>true</pre>.\r\n *\r\n * @name ErrorHandler\r\n * @class\r\n */\r\n\r\n\r\n /*\r\n * Parses a TTML color expression\r\n * \r\n */\r\n\r\n var HEX_COLOR_RE = /#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})?/;\r\n var DEC_COLOR_RE = /rgb\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)/;\r\n var DEC_COLORA_RE = /rgba\\(\\s*(\\d+),\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)/;\r\n var NAMED_COLOR = {\r\n transparent: [0, 0, 0, 0],\r\n black: [0, 0, 0, 255],\r\n silver: [192, 192, 192, 255],\r\n gray: [128, 128, 128, 255],\r\n white: [255, 255, 255, 255],\r\n maroon: [128, 0, 0, 255],\r\n red: [255, 0, 0, 255],\r\n purple: [128, 0, 128, 255],\r\n fuchsia: [255, 0, 255, 255],\r\n magenta: [255, 0, 255, 255],\r\n green: [0, 128, 0, 255],\r\n lime: [0, 255, 0, 255],\r\n olive: [128, 128, 0, 255],\r\n yellow: [255, 255, 0, 255],\r\n navy: [0, 0, 128, 255],\r\n blue: [0, 0, 255, 255],\r\n teal: [0, 128, 128, 255],\r\n aqua: [0, 255, 255, 255],\r\n cyan: [0, 255, 255, 255]\r\n };\r\n\r\n imscUtils.parseColor = function (str) {\r\n\r\n var m;\r\n \r\n var r = null;\r\n \r\n var nc = NAMED_COLOR[str.toLowerCase()];\r\n \r\n if (nc !== undefined) {\r\n\r\n r = nc;\r\n\r\n } else if ((m = HEX_COLOR_RE.exec(str)) !== null) {\r\n\r\n r = [parseInt(m[1], 16),\r\n parseInt(m[2], 16),\r\n parseInt(m[3], 16),\r\n (m[4] !== undefined ? parseInt(m[4], 16) : 255)];\r\n \r\n } else if ((m = DEC_COLOR_RE.exec(str)) !== null) {\r\n\r\n r = [parseInt(m[1]),\r\n parseInt(m[2]),\r\n parseInt(m[3]),\r\n 255];\r\n \r\n } else if ((m = DEC_COLORA_RE.exec(str)) !== null) {\r\n\r\n r = [parseInt(m[1]),\r\n parseInt(m[2]),\r\n parseInt(m[3]),\r\n parseInt(m[4])];\r\n \r\n }\r\n\r\n return r;\r\n };\r\n\r\n var LENGTH_RE = /^((?:\\+|\\-)?\\d*(?:\\.\\d+)?)(px|em|c|%)$/;\r\n\r\n imscUtils.parseLength = function (str) {\r\n\r\n var m;\r\n\r\n var r = null;\r\n\r\n if ((m = LENGTH_RE.exec(str)) !== null) {\r\n\r\n r = {value: parseFloat(m[1]), unit: m[2]};\r\n }\r\n\r\n return r;\r\n };\r\n\r\n})(typeof exports === 'undefined' ? this.imscUtils = {} : exports);\r\n","var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/*<replacement>*/\n\nvar pna = require('process-nextick-args');\n/*</replacement>*/\n\nmodule.exports = Readable;\n\n/*<replacement>*/\nvar isArray = require('isarray');\n/*</replacement>*/\n\n/*<replacement>*/\nvar Duplex;\n/*</replacement>*/\n\nReadable.ReadableState = ReadableState;\n\n/*<replacement>*/\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function (emitter, type) {\n return emitter.listeners(type).length;\n};\n/*</replacement>*/\n\n/*<replacement>*/\nvar Stream = require('./internal/streams/stream');\n/*</replacement>*/\n\n/*<replacement>*/\n\nvar Buffer = require('safe-buffer').Buffer;\nvar OurUint8Array = global.Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/*</replacement>*/\n\n/*<replacement>*/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/*</replacement>*/\n\n/*<replacement>*/\nvar debugUtil = require('util');\nvar debug = void 0;\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function () {};\n}\n/*</replacement>*/\n\nvar BufferList = require('./internal/streams/BufferList');\nvar destroyImpl = require('./internal/streams/destroy');\nvar StringDecoder;\n\nutil.inherits(Readable, Stream);\n\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);\n\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;\n\n // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n var hwm = options.highWaterMark;\n var readableHwm = options.readableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false;\n\n // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n this.sync = true;\n\n // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // the number of writers that are awaiting a drain event in .pipe()s\n this.awaitDrain = 0;\n\n // if true, a maybeReadMore has been scheduled\n this.readingMore = false;\n\n this.decoder = null;\n this.encoding = null;\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n if (!(this instanceof Readable)) return new Readable(options);\n\n this._readableState = new ReadableState(options, this);\n\n // legacy\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined) {\n return false;\n }\n return this._readableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n }\n});\n\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\nReadable.prototype._destroy = function (err, cb) {\n this.push(null);\n cb(err);\n};\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n};\n\n// Unshift should *always* be something directly out of read()\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n var state = stream._readableState;\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n if (er) {\n stream.emit('error', er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n stream.emit('error', new Error('stream.push() after EOF'));\n } else {\n state.reading = false;\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n }\n }\n\n return needMoreData(state);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n stream.emit('data', chunk);\n stream.read(0);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n\n if (state.needReadable) emitReadable(stream);\n }\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n return er;\n}\n\n// if it's past the high water mark, we can push in some more.\n// Also, if we have no data yet, we can stand some\n// more bytes. This is to work around cases where hwm=0,\n// such as the repl. Also, if the push() triggered a\n// readable event, and the user called read(largeNumber) such that\n// needReadable was set, then we ought to push more, so that another\n// 'readable' event will be triggered.\nfunction needMoreData(state) {\n return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n};\n\n// backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this._readableState.decoder = new StringDecoder(enc);\n this._readableState.encoding = enc;\n return this;\n};\n\n// Don't raise the hwm > 8MB\nvar MAX_HWM = 0x800000;\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n return n;\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n }\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n;\n // Don't have enough\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n return state.length;\n}\n\n// you can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n\n if (n !== 0) state.emittedReadable = false;\n\n // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state);\n\n // if we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n var doRead = state.needReadable;\n debug('need readable', doRead);\n\n // if we currently have less than the highWaterMark, then also read some\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n }\n\n // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true;\n // if the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.needReadable = true;\n // call internal read method\n this._read(state.highWaterMark);\n state.sync = false;\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = true;\n n = 0;\n } else {\n state.length -= n;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true;\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n if (state.ended) return;\n if (state.decoder) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n state.ended = true;\n\n // emit 'readable' now to make sure it gets picked up.\n emitReadable(stream);\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n var state = stream._readableState;\n state.needReadable = false;\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);\n }\n}\n\nfunction emitReadable_(stream) {\n debug('emit readable');\n stream.emit('readable');\n flow(stream);\n}\n\n// at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n pna.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n var len = state.length;\n while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length)\n // didn't get any data, stop spinning.\n break;else len = state.length;\n }\n state.readingMore = false;\n}\n\n// abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n this.emit('error', new Error('_read() is not implemented'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n default:\n state.pipes.push(dest);\n break;\n }\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);\n\n dest.on('unpipe', onunpipe);\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n }\n\n // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n\n var cleanedUp = false;\n function cleanup() {\n debug('cleanup');\n // cleanup event handlers once the pipe is broken\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n\n cleanedUp = true;\n\n // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n // If the user pushes more data while we're writing to dest then we'll end up\n // in ondata again. However, we only want to increase awaitDrain once because\n // dest will only emit one 'drain' event for the multiple writes.\n // => Introduce a guard on increasing awaitDrain.\n var increasedAwaitDrain = false;\n src.on('data', ondata);\n function ondata(chunk) {\n debug('ondata');\n increasedAwaitDrain = false;\n var ret = dest.write(chunk);\n if (false === ret && !increasedAwaitDrain) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', src._readableState.awaitDrain);\n src._readableState.awaitDrain++;\n increasedAwaitDrain = true;\n }\n src.pause();\n }\n }\n\n // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror);\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n dest.once('close', onclose);\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n }\n\n // tell the dest that it's being piped to\n dest.emit('pipe', src);\n\n // start the flow if it hasn't been started already.\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function () {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = { hasUnpiped: false };\n\n // if we're not piping anywhere, then do nothing.\n if (state.pipesCount === 0) return this;\n\n // just one destination. most common case.\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n\n if (!dest) dest = state.pipes;\n\n // got a match.\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n }\n\n // slow case. multiple pipe destinations.\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, unpipeInfo);\n }return this;\n }\n\n // try to find the right one.\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n\n dest.emit('unpipe', this, unpipeInfo);\n\n return this;\n};\n\n// set up data events if they are asked for\n// Ensure readable listeners eventually get something\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n\n if (ev === 'data') {\n // Start flowing on next tick if stream isn't explicitly paused\n if (this._readableState.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n var state = this._readableState;\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.emittedReadable = false;\n if (!state.reading) {\n pna.nextTick(nReadingNextTick, this);\n } else if (state.length) {\n emitReadable(this);\n }\n }\n }\n\n return res;\n};\nReadable.prototype.addListener = Readable.prototype.on;\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n var state = this._readableState;\n if (!state.flowing) {\n debug('resume');\n state.flowing = true;\n resume(this, state);\n }\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n pna.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n if (!state.reading) {\n debug('resume read 0');\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n state.awaitDrain = 0;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n if (false !== this._readableState.flowing) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n while (state.flowing && stream.read() !== null) {}\n}\n\n// wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n\n stream.on('end', function () {\n debug('wrapped end');\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk);\n\n // don't skip over falsy values in objectMode\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n if (!ret) {\n paused = true;\n stream.pause();\n }\n });\n\n // proxy all the other methods.\n // important when wrapping filters and duplexes.\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function (method) {\n return function () {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n }\n\n // proxy certain important events.\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n }\n\n // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n this._read = function (n) {\n debug('wrapped _read', n);\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._readableState.highWaterMark;\n }\n});\n\n// exposed for testing purposes only.\nReadable._fromList = fromList;\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = fromListPartial(n, state.buffer, state.decoder);\n }\n\n return ret;\n}\n\n// Extracts only enough buffered data to satisfy the amount requested.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromListPartial(n, list, hasStrings) {\n var ret;\n if (n < list.head.data.length) {\n // slice is the same for buffers and strings\n ret = list.head.data.slice(0, n);\n list.head.data = list.head.data.slice(n);\n } else if (n === list.head.data.length) {\n // first chunk is a perfect match\n ret = list.shift();\n } else {\n // result spans more than one buffer\n ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);\n }\n return ret;\n}\n\n// Copies a specified amount of characters from the list of buffered data\n// chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBufferString(n, list) {\n var p = list.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = str.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\n// Copies a specified amount of bytes from the list of buffered data chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n\n // If we get here before consuming all the bytes, then that is a\n // bug in node. Should never happen.\n if (state.length > 0) throw new Error('\"endReadable()\" called on non-empty stream');\n\n if (!state.endEmitted) {\n state.ended = true;\n pna.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n // Check that we didn't get one last unshift.\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n }\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n return -1;\n}","module.exports = require('events').EventEmitter;\n","'use strict';\n\n/*<replacement>*/\n\nvar pna = require('process-nextick-args');\n/*</replacement>*/\n\n// undocumented cb() API, needed for core, not for public API\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {\n pna.nextTick(emitErrorNT, this, err);\n }\n return this;\n }\n\n // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n }\n\n // if this is a duplex stream mark the writable part as destroyed as well\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n pna.nextTick(emitErrorNT, _this, err);\n if (_this._writableState) {\n _this._writableState.errorEmitted = true;\n }\n } else if (cb) {\n cb(err);\n }\n });\n\n return this;\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n'use strict';\n\nmodule.exports = Transform;\n\nvar Duplex = require('./_stream_duplex');\n\n/*<replacement>*/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/*</replacement>*/\n\nutil.inherits(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n\n var cb = ts.writecb;\n\n if (!cb) {\n return this.emit('error', new Error('write callback called multiple times'));\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n\n cb(er);\n\n var rs = this._readableState;\n rs.reading = false;\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n\n Duplex.call(this, options);\n\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n };\n\n // start out asking for a readable event once data is transformed.\n this._readableState.needReadable = true;\n\n // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n\n if (typeof options.flush === 'function') this._flush = options.flush;\n }\n\n // When the writable side finishes, then flush out anything remaining.\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function') {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n};\n\n// This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\nTransform.prototype._transform = function (chunk, encoding, cb) {\n throw new Error('_transform() is not implemented');\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n};\n\n// Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && ts.writecb && !ts.transforming) {\n ts.transforming = true;\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n var _this2 = this;\n\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n _this2.emit('close');\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data);\n\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');\n\n if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');\n\n return stream.push(null);\n}","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nconst LICENSE_SERVER_MANIFEST_CONFIGURATIONS = {\n attributes: ['Laurl','laurl'],\n prefixes: ['clearkey', 'dashif']\n};\n\n/**\n * @class\n * @ignore\n */\nclass CommonEncryption {\n /**\n * Find and return the ContentProtection element in the given array\n * that indicates support for MPEG Common Encryption\n *\n * @param {Array} cpArray array of content protection elements\n * @returns {Object|null} the Common Encryption content protection element or\n * null if one was not found\n */\n static findCencContentProtection(cpArray) {\n let retVal = null;\n for (let i = 0; i < cpArray.length; ++i) {\n let cp = cpArray[i];\n if (cp.schemeIdUri.toLowerCase() === 'urn:mpeg:dash:mp4protection:2011' &&\n (cp.value.toLowerCase() === 'cenc' || cp.value.toLowerCase() === 'cbcs'))\n retVal = cp;\n }\n return retVal;\n }\n\n /**\n * Returns just the data portion of a single PSSH\n *\n * @param {ArrayBuffer} pssh - the PSSH\n * @return {ArrayBuffer} data portion of the PSSH\n */\n static getPSSHData(pssh) {\n let offset = 8; // Box size and type fields\n let view = new DataView(pssh);\n\n // Read version\n let version = view.getUint8(offset);\n\n offset += 20; // Version (1), flags (3), system ID (16)\n\n if (version > 0) {\n offset += 4 + (16 * view.getUint32(offset)); // Key ID count (4) and All key IDs (16*count)\n }\n\n offset += 4; // Data size\n return pssh.slice(offset);\n }\n\n /**\n * Returns the PSSH associated with the given key system from the concatenated\n * list of PSSH boxes in the given initData\n *\n * @param {KeySystem} keySystem the desired\n * key system\n * @param {ArrayBuffer} initData 'cenc' initialization data. Concatenated list of PSSH.\n * @returns {ArrayBuffer|null} The PSSH box data corresponding to the given key system, null if not found\n * or null if a valid association could not be found.\n */\n static getPSSHForKeySystem(keySystem, initData) {\n let psshList = CommonEncryption.parsePSSHList(initData);\n if (keySystem && psshList.hasOwnProperty(keySystem.uuid.toLowerCase())) {\n return psshList[keySystem.uuid.toLowerCase()];\n }\n return null;\n }\n\n /**\n * Parse a standard common encryption PSSH which contains a simple\n * base64-encoding of the init data\n *\n * @param {Object} cpData the ContentProtection element\n * @param {BASE64} BASE64 reference\n * @returns {ArrayBuffer|null} the init data or null if not found\n */\n static parseInitDataFromContentProtection(cpData, BASE64) {\n if ('pssh' in cpData) {\n\n // Remove whitespaces and newlines from pssh text\n cpData.pssh.__text = cpData.pssh.__text.replace(/\\r?\\n|\\r/g, '').replace(/\\s+/g, '');\n\n return BASE64.decodeArray(cpData.pssh.__text).buffer;\n }\n return null;\n }\n\n /**\n * Parses list of PSSH boxes into keysystem-specific PSSH data\n *\n * @param {ArrayBuffer} data - the concatenated list of PSSH boxes as provided by\n * CDM as initialization data when CommonEncryption content is detected\n * @returns {Object|Array} an object that has a property named according to each of\n * the detected key system UUIDs (e.g. 00000000-0000-0000-0000-0000000000)\n * and a ArrayBuffer (the entire PSSH box) as the property value\n */\n static parsePSSHList(data) {\n\n if (data === null || data === undefined)\n return [];\n\n let dv = new DataView(data.buffer || data); // data.buffer first for Uint8Array support\n let done = false;\n let pssh = {};\n\n // TODO: Need to check every data read for end of buffer\n let byteCursor = 0;\n while (!done) {\n\n let size,\n nextBox,\n version,\n systemID;\n let boxStart = byteCursor;\n\n if (byteCursor >= dv.buffer.byteLength)\n break;\n\n /* Box size */\n size = dv.getUint32(byteCursor);\n nextBox = byteCursor + size;\n byteCursor += 4;\n\n /* Verify PSSH */\n if (dv.getUint32(byteCursor) !== 0x70737368) {\n byteCursor = nextBox;\n continue;\n }\n byteCursor += 4;\n\n /* Version must be 0 or 1 */\n version = dv.getUint8(byteCursor);\n if (version !== 0 && version !== 1) {\n byteCursor = nextBox;\n continue;\n }\n byteCursor++;\n\n byteCursor += 3; /* skip flags */\n\n // 16-byte UUID/SystemID\n systemID = '';\n let i, val;\n for (i = 0; i < 4; i++) {\n val = dv.getUint8(byteCursor + i).toString(16);\n systemID += (val.length === 1) ? '0' + val : val;\n }\n byteCursor += 4;\n systemID += '-';\n for (i = 0; i < 2; i++) {\n val = dv.getUint8(byteCursor + i).toString(16);\n systemID += (val.length === 1) ? '0' + val : val;\n }\n byteCursor += 2;\n systemID += '-';\n for (i = 0; i < 2; i++) {\n val = dv.getUint8(byteCursor + i).toString(16);\n systemID += (val.length === 1) ? '0' + val : val;\n }\n byteCursor += 2;\n systemID += '-';\n for (i = 0; i < 2; i++) {\n val = dv.getUint8(byteCursor + i).toString(16);\n systemID += (val.length === 1) ? '0' + val : val;\n }\n byteCursor += 2;\n systemID += '-';\n for (i = 0; i < 6; i++) {\n val = dv.getUint8(byteCursor + i).toString(16);\n systemID += (val.length === 1) ? '0' + val : val;\n }\n byteCursor += 6;\n\n systemID = systemID.toLowerCase();\n\n /* PSSH Data Size */\n byteCursor += 4;\n\n /* PSSH Data */\n pssh[systemID] = dv.buffer.slice(boxStart, nextBox);\n byteCursor = nextBox;\n }\n\n return pssh;\n }\n\n static getLicenseServerUrlFromMediaInfo(mediaInfo, schemeIdUri) {\n try {\n\n if (!mediaInfo || mediaInfo.length === 0) {\n return null;\n }\n\n let i = 0;\n let licenseServer = null;\n\n while (i < mediaInfo.length && !licenseServer) {\n const info = mediaInfo[i];\n\n if (info && info.contentProtection && info.contentProtection.length > 0) {\n const targetProtectionData = info.contentProtection.filter((cp) => {\n return cp.schemeIdUri && cp.schemeIdUri === schemeIdUri;\n });\n\n if (targetProtectionData && targetProtectionData.length > 0) {\n let j = 0;\n while (j < targetProtectionData.length && !licenseServer) {\n const ckData = targetProtectionData[j];\n let k = 0;\n while (k < LICENSE_SERVER_MANIFEST_CONFIGURATIONS.attributes.length && !licenseServer) {\n let l = 0;\n const attribute = LICENSE_SERVER_MANIFEST_CONFIGURATIONS.attributes[k];\n while (l < LICENSE_SERVER_MANIFEST_CONFIGURATIONS.prefixes.length && !licenseServer) {\n const prefix = LICENSE_SERVER_MANIFEST_CONFIGURATIONS.prefixes[l];\n if (ckData[attribute] && ckData[attribute].__prefix && ckData[attribute].__prefix === prefix && ckData[attribute].__text) {\n licenseServer = ckData[attribute].__text;\n }\n l += 1;\n }\n k += 1;\n }\n j += 1;\n }\n }\n }\n i += 1;\n }\n return licenseServer;\n } catch\n (e) {\n return null;\n }\n }\n}\n\nexport default CommonEncryption;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @classdesc A media capability\n * @ignore\n */\nclass MediaCapability {\n /**\n * @param {string} contentType MIME type and codecs (RFC6386)\n * @param {string} robustness\n * @class\n * @ignore\n */\n constructor(contentType, robustness) {\n this.contentType = contentType;\n this.robustness = robustness;\n }\n}\n\nexport default MediaCapability;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * @classdesc Represents a set of configurations that describe the capabilities desired for\n * support by a given CDM\n * @ignore\n */\nclass KeySystemConfiguration {\n /**\n * @param {Array.<MediaCapability>} audioCapabilities array of\n * desired audio capabilities. Higher preference capabilities should be placed earlier\n * in the array.\n * @param {Array.<MediaCapability>} videoCapabilities array of\n * desired video capabilities. Higher preference capabilities should be placed earlier\n * in the array.\n * @param {string} distinctiveIdentifier desired use of distinctive identifiers.\n * One of \"required\", \"optional\", or \"not-allowed\"\n * @param {string} persistentState desired support for persistent storage of\n * key systems. One of \"required\", \"optional\", or \"not-allowed\"\n * @param {Array.<string>} sessionTypes List of session types that must\n * be supported by the key system\n * @class\n */\n constructor(audioCapabilities, videoCapabilities, distinctiveIdentifier, persistentState, sessionTypes) {\n this.initDataTypes = [ 'cenc' ];\n if (audioCapabilities && audioCapabilities.length) {\n this.audioCapabilities = audioCapabilities;\n }\n if (videoCapabilities && videoCapabilities.length) {\n this.videoCapabilities = videoCapabilities;\n }\n this.distinctiveIdentifier = distinctiveIdentifier;\n this.persistentState = persistentState;\n this.sessionTypes = sessionTypes;\n }\n}\n\nexport default KeySystemConfiguration;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport ErrorsBase from '../../../core/errors/ErrorsBase';\n/**\n * @class\n */\nclass ProtectionErrors extends ErrorsBase {\n\tconstructor () {\n super();\n\n /**\n * Generid key Error code\n */\n this.MEDIA_KEYERR_CODE = 100;\n /**\n * Error code returned by keyerror api for ProtectionModel_01b\n */\n this.MEDIA_KEYERR_UNKNOWN_CODE = 101;\n /**\n * Error code returned by keyerror api for ProtectionModel_01b\n */\n this.MEDIA_KEYERR_CLIENT_CODE = 102;\n /**\n * Error code returned by keyerror api for ProtectionModel_01b\n */\n this.MEDIA_KEYERR_SERVICE_CODE = 103;\n /**\n * Error code returned by keyerror api for ProtectionModel_01b\n */\n this.MEDIA_KEYERR_OUTPUT_CODE = 104;\n /**\n * Error code returned by keyerror api for ProtectionModel_01b\n */\n this.MEDIA_KEYERR_HARDWARECHANGE_CODE = 105;\n /**\n * Error code returned by keyerror api for ProtectionModel_01b\n */\n this.MEDIA_KEYERR_DOMAIN_CODE = 106;\n\n /**\n * Error code returned when an error occured in keymessage event for ProtectionModel_01b\n */\n this.MEDIA_KEY_MESSAGE_ERROR_CODE = 107;\n /**\n * Error code returned when challenge is invalid in keymessage event (event triggered by CDM)\n */\n this.MEDIA_KEY_MESSAGE_NO_CHALLENGE_ERROR_CODE = 108;\n /**\n * Error code returned when License server certificate has not been successfully updated\n */\n this.SERVER_CERTIFICATE_UPDATED_ERROR_CODE = 109;\n /**\n * Error code returned when license validity has expired\n */\n this.KEY_STATUS_CHANGED_EXPIRED_ERROR_CODE = 110;\n /**\n * Error code returned when no licenser url is defined\n */\n this.MEDIA_KEY_MESSAGE_NO_LICENSE_SERVER_URL_ERROR_CODE = 111;\n /**\n * Error code returned when key system access is denied\n */\n this.KEY_SYSTEM_ACCESS_DENIED_ERROR_CODE = 112;\n /**\n * Error code returned when key session has not been successfully created\n */\n this.KEY_SESSION_CREATED_ERROR_CODE = 113;\n /**\n * Error code returned when license request failed after a keymessage event has been triggered\n */\n this.MEDIA_KEY_MESSAGE_LICENSER_ERROR_CODE = 114;\n\n this.MEDIA_KEYERR_UNKNOWN_MESSAGE = 'An unspecified error occurred. This value is used for errors that don\\'t match any of the other codes.';\n this.MEDIA_KEYERR_CLIENT_MESSAGE = 'The Key System could not be installed or updated.';\n this.MEDIA_KEYERR_SERVICE_MESSAGE = 'The message passed into update indicated an error from the license service.';\n this.MEDIA_KEYERR_OUTPUT_MESSAGE = 'There is no available output device with the required characteristics for the content protection system.';\n this.MEDIA_KEYERR_HARDWARECHANGE_MESSAGE = 'A hardware configuration change caused a content protection error.';\n this.MEDIA_KEYERR_DOMAIN_MESSAGE = 'An error occurred in a multi-device domain licensing configuration. The most common error is a failure to join the domain.';\n this.MEDIA_KEY_MESSAGE_ERROR_MESSAGE = 'Multiple key sessions were creates with a user-agent that does not support sessionIDs!! Unpredictable behavior ahead!';\n this.MEDIA_KEY_MESSAGE_NO_CHALLENGE_ERROR_MESSAGE = 'DRM: Empty key message from CDM';\n this.SERVER_CERTIFICATE_UPDATED_ERROR_MESSAGE = 'Error updating server certificate -- ';\n this.KEY_STATUS_CHANGED_EXPIRED_ERROR_MESSAGE = 'DRM: KeyStatusChange error! -- License has expired';\n this.MEDIA_KEY_MESSAGE_NO_LICENSE_SERVER_URL_ERROR_MESSAGE = 'DRM: No license server URL specified!';\n this.KEY_SYSTEM_ACCESS_DENIED_ERROR_MESSAGE = 'DRM: KeySystem Access Denied! -- ';\n this.KEY_SESSION_CREATED_ERROR_MESSAGE = 'DRM: unable to create session! --';\n this.MEDIA_KEY_MESSAGE_LICENSER_ERROR_MESSAGE = 'DRM: licenser error! --';\n }\n}\n\nlet protectionErrors = new ProtectionErrors();\nexport default protectionErrors;","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @classdesc Defines a license request\n * @ignore\n */\nclass LicenseRequest {\n /**\n * Defines a license request\n *\n * @class\n */\n constructor(url, method, responseType, headers, withCredentials, messageType, sessionId, data) {\n\n /**\n * The license request url\n */\n this.url = url;\n\n /**\n * The HTTP method\n */\n this.method = method;\n\n /**\n * The HTTP response type\n */\n this.responseType = responseType;\n\n /**\n * The HTP request headers\n */\n this.headers = headers;\n\n /**\n * Wether request is done using credentials (cross-site cookies)\n */\n this.withCredentials = withCredentials;\n\n /**\n * The license request message type (see https://www.w3.org/TR/encrypted-media/#dom-mediakeymessagetype)\n */\n this.messageType = messageType;\n\n /**\n * The corresponding EME session ID\n */\n this.sessionId = sessionId;\n\n /**\n * The license request data\n */\n this.data = data;\n }\n}\n\nexport default LicenseRequest;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @classdesc Defines a license response\n */\nclass LicenseResponse {\n /**\n * Defines a license request\n *\n * @class\n * @ignore\n */\n constructor(url, headers, data) {\n\n /**\n * The url that was loaded, that can be redirected from original request url\n */\n this.url = url;\n\n /**\n * The HTP response headers\n */\n this.headers = headers;\n\n /**\n * The license response data\n */\n this.data = data;\n }\n}\n\nexport default LicenseResponse;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport CommonEncryption from '../CommonEncryption';\nimport MediaCapability from '../vo/MediaCapability';\nimport KeySystemConfiguration from '../vo/KeySystemConfiguration';\nimport ProtectionErrors from '../errors/ProtectionErrors';\nimport DashJSError from '../../vo/DashJSError';\nimport LicenseRequest from '../vo/LicenseRequest';\nimport LicenseResponse from '../vo/LicenseResponse';\nimport {HTTPRequest} from '../../vo/metrics/HTTPRequest';\nimport Utils from '../../../core/Utils';\nimport Constants from '../../constants/Constants';\nimport FactoryMaker from '../../../core/FactoryMaker';\n\nconst NEEDKEY_BEFORE_INITIALIZE_RETRIES = 5;\nconst NEEDKEY_BEFORE_INITIALIZE_TIMEOUT = 500;\n\nconst LICENSE_SERVER_REQUEST_RETRIES = 3;\nconst LICENSE_SERVER_REQUEST_RETRY_INTERVAL = 1000;\nconst LICENSE_SERVER_REQUEST_DEFAULT_TIMEOUT = 8000;\n\n/**\n * @module ProtectionController\n * @description Provides access to media protection information and functionality. Each\n * ProtectionController manages a single {@link MediaPlayer.models.ProtectionModel}\n * which encapsulates a set of protection information (EME APIs, selected key system,\n * key sessions). The APIs of ProtectionController mostly align with the latest EME\n * APIs. Key system selection is mostly automated when combined with app-overrideable\n * functionality provided in {@link ProtectionKeyController}.\n * @todo ProtectionController does almost all of its tasks automatically after init() is\n * called. Applications might want more control over this process and want to go through\n * each step manually (key system selection, session creation, session maintenance).\n * This module can be accessed using the MediaPlayer API getProtectionController()\n * @param {Object} config\n */\n\nfunction ProtectionController(config) {\n\n config = config || {};\n const protectionKeyController = config.protectionKeyController;\n let protectionModel = config.protectionModel;\n const eventBus = config.eventBus;\n const events = config.events;\n const debug = config.debug;\n const BASE64 = config.BASE64;\n const constants = config.constants;\n let needkeyRetries = [];\n const cmcdModel = config.cmcdModel;\n const settings = config.settings;\n\n let instance,\n logger,\n pendingKeySystemData,\n mediaInfoArr,\n protDataSet,\n sessionType,\n robustnessLevel,\n selectedKeySystem,\n keySystemSelectionInProgress,\n licenseRequestFilters,\n licenseResponseFilters;\n\n function setup() {\n logger = debug.getLogger(instance);\n pendingKeySystemData = [];\n mediaInfoArr = [];\n sessionType = 'temporary';\n robustnessLevel = '';\n licenseRequestFilters = [];\n licenseResponseFilters = [];\n eventBus.on(events.INTERNAL_KEY_MESSAGE, _onKeyMessage, instance);\n eventBus.on(events.INTERNAL_KEY_STATUS_CHANGED, _onKeyStatusChanged, instance);\n }\n\n function checkConfig() {\n if (!eventBus || !eventBus.hasOwnProperty('on') || !protectionKeyController || !protectionKeyController.hasOwnProperty('getSupportedKeySystemsFromContentProtection')) {\n throw new Error('Missing config parameter(s)');\n }\n }\n\n /**\n * Initialize this protection system for a given media type.\n *\n * @param {StreamInfo} [mediaInfo] Media information\n * @memberof module:ProtectionController\n * @instance\n */\n function initializeForMedia(mediaInfo) {\n // Not checking here if a session for similar KS/KID combination is already created\n // because still don't know which keysystem will be selected.\n // Once Keysystem is selected and before creating the session, we will do that check\n // so we create the strictly necessary DRM sessions\n if (!mediaInfo) {\n throw new Error('mediaInfo can not be null or undefined');\n }\n\n checkConfig();\n\n mediaInfoArr.push(mediaInfo);\n\n // ContentProtection elements are specified at the AdaptationSet level, so the CP for audio\n // and video will be the same. Just use one valid MediaInfo object\n let supportedKS = protectionKeyController.getSupportedKeySystemsFromContentProtection(mediaInfo.contentProtection, protDataSet, sessionType);\n\n // Reorder key systems according to priority order provided in protectionData\n supportedKS = supportedKS.sort((ksA, ksB) => {\n let indexA = (protDataSet && protDataSet[ksA.ks.systemString] && protDataSet[ksA.ks.systemString].priority >= 0) ? protDataSet[ksA.ks.systemString].priority : supportedKS.length;\n let indexB = (protDataSet && protDataSet[ksB.ks.systemString] && protDataSet[ksB.ks.systemString].priority >= 0) ? protDataSet[ksB.ks.systemString].priority : supportedKS.length;\n return indexA - indexB;\n });\n\n if (supportedKS && supportedKS.length > 0) {\n _selectKeySystem(supportedKS, true);\n }\n }\n\n /**\n * Selects a key system if we dont have any one yet. Otherwise we use the existing key system and trigger a new license request if the initdata has changed\n * @param {array} supportedKS\n * @param {boolean} fromManifest\n * @private\n */\n function _selectKeySystem(supportedKS, fromManifest) {\n\n // We are in the process of selecting a key system, so just save the data which might be coming from additional AdaptationSets.\n if (keySystemSelectionInProgress) {\n pendingKeySystemData.push(supportedKS);\n }\n\n // First time, so we need to select a key system\n else if (!selectedKeySystem) {\n _selectInitialKeySystem(supportedKS, fromManifest);\n }\n\n // We already selected a key system. We only need to trigger a new license exchange if the init data has changed\n else if (selectedKeySystem) {\n _initiateWithExistingKeySystem(supportedKS);\n }\n }\n\n /**\n * We do not have a key system yet. Select one\n * @param {array} supportedKS\n * @param {boolean} fromManifest\n * @private\n */\n function _selectInitialKeySystem(supportedKS, fromManifest) {\n keySystemSelectionInProgress = true;\n const requestedKeySystems = [];\n\n pendingKeySystemData.push(supportedKS);\n\n // Add all key systems to our request list since we have yet to select a key system\n for (let i = 0; i < supportedKS.length; i++) {\n const keySystemConfiguration = _getKeySystemConfiguration(supportedKS[i]);\n requestedKeySystems.push({\n ks: supportedKS[i].ks,\n configs: [keySystemConfiguration],\n protData: supportedKS[i].protData\n });\n }\n\n let keySystemAccess;\n\n protectionModel.requestKeySystemAccess(requestedKeySystems)\n .then((event) => {\n keySystemAccess = event.data;\n let selectedSystemString = keySystemAccess.mksa && keySystemAccess.mksa.selectedSystemString ? keySystemAccess.mksa.selectedSystemString : keySystemAccess.keySystem.systemString;\n logger.info('DRM: KeySystem Access Granted for system string (' + selectedSystemString + ')! Selecting key system...');\n return protectionModel.selectKeySystem(keySystemAccess);\n })\n .then((keySystem) => {\n selectedKeySystem = keySystem;\n keySystemSelectionInProgress = false;\n\n if (!protectionModel) {\n return;\n }\n\n eventBus.trigger(events.KEY_SYSTEM_SELECTED, { data: keySystemAccess });\n\n // Set server certificate from protData\n const protData = _getProtDataForKeySystem(selectedKeySystem);\n if (protData && protData.serverCertificate && protData.serverCertificate.length > 0) {\n protectionModel.setServerCertificate(BASE64.decodeArray(protData.serverCertificate).buffer);\n }\n\n // Create key sessions for the different AdaptationSets\n let ksIdx;\n for (let i = 0; i < pendingKeySystemData.length; i++) {\n for (ksIdx = 0; ksIdx < pendingKeySystemData[i].length; ksIdx++) {\n if (selectedKeySystem === pendingKeySystemData[i][ksIdx].ks) {\n const current = pendingKeySystemData[i][ksIdx]\n _loadOrCreateKeySession(current)\n break;\n }\n }\n }\n })\n .catch((event) => {\n selectedKeySystem = null;\n keySystemSelectionInProgress = false;\n if (!fromManifest) {\n eventBus.trigger(events.KEY_SYSTEM_SELECTED, {\n data: null,\n error: new DashJSError(ProtectionErrors.KEY_SYSTEM_ACCESS_DENIED_ERROR_CODE, ProtectionErrors.KEY_SYSTEM_ACCESS_DENIED_ERROR_MESSAGE + 'Error selecting key system! -- ' + event.error)\n });\n }\n })\n }\n\n /**\n * If we have already selected a keysytem we only need to create a new key session and issue a new license request if the init data has changed.\n * @param {array} supportedKS\n * @private\n */\n function _initiateWithExistingKeySystem(supportedKS) {\n const ksIdx = supportedKS.findIndex((entry) => {\n return entry.ks === selectedKeySystem;\n });\n\n const current = supportedKS[ksIdx];\n if (ksIdx === -1 || !current.initData) {\n return;\n }\n\n _loadOrCreateKeySession(current);\n }\n\n /**\n * Loads an existing key session if we already have a session id. Otherwise we create a new key session\n * @param {object} keySystemInfo\n * @private\n */\n function _loadOrCreateKeySession(keySystemInfo) {\n // Clearkey\n if (protectionKeyController.isClearKey(selectedKeySystem)) {\n // For Clearkey: if parameters for generating init data was provided by the user, use them for generating\n // initData and overwrite possible initData indicated in encrypted event (EME)\n if (keySystemInfo.protData && keySystemInfo.protData.hasOwnProperty('clearkeys')) {\n const initData = { kids: Object.keys(keySystemInfo.protData.clearkeys) };\n keySystemInfo.initData = new TextEncoder().encode(JSON.stringify(initData));\n }\n }\n\n // Reuse existing KeySession\n if (keySystemInfo.sessionId) {\n // Load MediaKeySession with sessionId\n loadKeySession(keySystemInfo);\n }\n\n // Create a new KeySession\n else if (keySystemInfo.initData !== null) {\n // Create new MediaKeySession with initData\n createKeySession(keySystemInfo);\n }\n }\n\n /**\n * Loads a key session with the given session ID from persistent storage. This essentially creates a new key session\n *\n * @param {object} ksInfo\n * @memberof module:ProtectionController\n * @instance\n * @fires ProtectionController#KeySessionCreated\n * @ignore\n */\n function loadKeySession(keySystemInfo) {\n checkConfig();\n protectionModel.loadKeySession(keySystemInfo);\n }\n\n /**\n * Create a new key session associated with the given initialization data from the MPD or from the PSSH box in the media\n * For the latest version of the EME a request is generated. Once this request is ready we get notified via the INTERNAL_KEY_MESSAGE event\n * @param {ArrayBuffer} initData the initialization data\n * @param {Uint8Array} cdmData the custom data to provide to licenser\n * @memberof module:ProtectionController\n * @instance\n * @fires ProtectionController#KeySessionCreated\n * @ignore\n */\n function createKeySession(keySystemInfo) {\n const initDataForKS = CommonEncryption.getPSSHForKeySystem(selectedKeySystem, keySystemInfo ? keySystemInfo.initData : null);\n\n if (initDataForKS) {\n\n // Check for duplicate key id\n if (_isKeyIdDuplicate(keySystemInfo.keyId)) {\n return;\n }\n\n // Check for duplicate initData\n if (_isInitDataDuplicate(initDataForKS)) {\n return;\n }\n\n try {\n keySystemInfo.initData = initDataForKS;\n protectionModel.createKeySession(keySystemInfo);\n } catch (error) {\n eventBus.trigger(events.KEY_SESSION_CREATED, {\n data: null,\n error: new DashJSError(ProtectionErrors.KEY_SESSION_CREATED_ERROR_CODE, ProtectionErrors.KEY_SESSION_CREATED_ERROR_MESSAGE + error.message)\n });\n }\n } else if (keySystemInfo && keySystemInfo.initData) {\n protectionModel.createKeySession(keySystemInfo);\n } else {\n eventBus.trigger(events.KEY_SESSION_CREATED, {\n data: null,\n error: new DashJSError(ProtectionErrors.KEY_SESSION_CREATED_ERROR_CODE, ProtectionErrors.KEY_SESSION_CREATED_ERROR_MESSAGE + 'Selected key system is ' + (selectedKeySystem ? selectedKeySystem.systemString : null) + '. needkey/encrypted event contains no initData corresponding to that key system!')\n });\n }\n }\n\n /**\n * Returns the protectionData for a specific keysystem as specified by the application.\n * @param {object} keySystem\n * @return {object | null}\n * @private\n */\n function _getProtDataForKeySystem(keySystem) {\n if (keySystem) {\n const keySystemString = keySystem.systemString;\n\n if (protDataSet) {\n return (keySystemString in protDataSet) ? protDataSet[keySystemString] : null;\n }\n }\n return null;\n }\n\n /**\n * Removes all entries from the mediaInfoArr\n */\n function clearMediaInfoArray() {\n mediaInfoArr = [];\n }\n\n /**\n * Returns a set of supported key systems and CENC initialization data\n * from the given array of ContentProtection elements. Only\n * key systems that are supported by this player will be returned.\n * Key systems are returned in priority order (highest first).\n *\n * @param {Array.<Object>} cps - array of content protection elements parsed\n * from the manifest\n * @returns {Array.<Object>} array of objects indicating which supported key\n * systems were found. Empty array is returned if no\n * supported key systems were found\n * @memberof module:ProtectionKeyController\n * @instance\n * @ignore\n */\n function getSupportedKeySystemsFromContentProtection(cps) {\n checkConfig();\n return protectionKeyController.getSupportedKeySystemsFromContentProtection(cps, protDataSet, sessionType);\n }\n\n /**\n * Checks if a session has already created for the provided key id\n * @param {string} keyId\n * @return {boolean}\n * @private\n */\n function _isKeyIdDuplicate(keyId) {\n\n if (!keyId) {\n return false;\n }\n\n try {\n const sessions = protectionModel.getSessions();\n for (let i = 0; i < sessions.length; i++) {\n if (sessions[i].getKeyId() === keyId) {\n return true;\n }\n }\n return false;\n } catch (e) {\n return false;\n }\n }\n\n /**\n * Checks if the provided init data is equal to one of the existing init data values\n * @param {any} initDataForKS\n * @return {boolean}\n * @private\n */\n function _isInitDataDuplicate(initDataForKS) {\n\n if (!initDataForKS) {\n return false;\n }\n\n try {\n const currentInitData = protectionModel.getAllInitData();\n for (let i = 0; i < currentInitData.length; i++) {\n if (protectionKeyController.initDataEquals(initDataForKS, currentInitData[i])) {\n logger.debug('DRM: Ignoring initData because we have already seen it!');\n return true;\n }\n }\n\n return false;\n } catch (e) {\n return false;\n }\n }\n\n /**\n * Removes the given key session from persistent storage and closes the session\n * as if {@link ProtectionController#closeKeySession}\n * was called\n *\n * @param {SessionToken} sessionToken the session\n * token\n * @memberof module:ProtectionController\n * @instance\n * @fires ProtectionController#KeySessionRemoved\n * @fires ProtectionController#KeySessionClosed\n * @ignore\n */\n function removeKeySession(sessionToken) {\n checkConfig();\n protectionModel.removeKeySession(sessionToken);\n }\n\n /**\n * Closes the key session and releases all associated decryption keys. These\n * keys will no longer be available for decrypting media\n *\n * @param {SessionToken} sessionToken the session\n * token\n * @memberof module:ProtectionController\n * @instance\n * @fires ProtectionController#KeySessionClosed\n * @ignore\n */\n function closeKeySession(sessionToken) {\n checkConfig();\n protectionModel.closeKeySession(sessionToken);\n }\n\n /**\n * Sets a server certificate for use by the CDM when signing key messages\n * intended for a particular license server. This will fire\n * an error event if a key system has not yet been selected.\n *\n * @param {ArrayBuffer} serverCertificate a CDM-specific license server\n * certificate\n * @memberof module:ProtectionController\n * @instance\n * @fires ProtectionController#ServerCertificateUpdated\n */\n function setServerCertificate(serverCertificate) {\n checkConfig();\n protectionModel.setServerCertificate(serverCertificate);\n }\n\n /**\n * Associate this protection system with the given HTMLMediaElement. This\n * causes the system to register for needkey/encrypted events from the given\n * element and provides a destination for setting of MediaKeys\n *\n * @param {HTMLMediaElement} element the media element to which the protection\n * system should be associated\n * @memberof module:ProtectionController\n * @instance\n */\n function setMediaElement(element) {\n checkConfig();\n if (element) {\n protectionModel.setMediaElement(element);\n eventBus.on(events.NEED_KEY, _onNeedKey, instance);\n } else if (element === null) {\n protectionModel.setMediaElement(element);\n eventBus.off(events.NEED_KEY, _onNeedKey, instance);\n }\n }\n\n /**\n * Sets the session type to use when creating key sessions. Either \"temporary\" or\n * \"persistent-license\". Default is \"temporary\".\n *\n * @param {string} value the session type\n * @memberof module:ProtectionController\n * @instance\n */\n function setSessionType(value) {\n sessionType = value;\n }\n\n /**\n * Sets the robustness level for video and audio capabilities. Optional to remove Chrome warnings.\n * Possible values are SW_SECURE_CRYPTO, SW_SECURE_DECODE, HW_SECURE_CRYPTO, HW_SECURE_CRYPTO, HW_SECURE_DECODE, HW_SECURE_ALL.\n *\n * @param {string} level the robustness level\n * @memberof module:ProtectionController\n * @instance\n */\n function setRobustnessLevel(level) {\n robustnessLevel = level;\n }\n\n /**\n * Attach KeySystem-specific data to use for license acquisition with EME\n *\n * @param {Object} data an object containing property names corresponding to\n * key system name strings (e.g. \"org.w3.clearkey\") and associated values\n * being instances of {@link ProtectionData}\n * @memberof module:ProtectionController\n * @instance\n * @ignore\n */\n function setProtectionData(data) {\n protDataSet = data;\n protectionKeyController.setProtectionData(data);\n }\n\n /**\n * Stop method is called when current playback is stopped/resetted.\n *\n * @memberof module:ProtectionController\n * @instance\n */\n function stop() {\n if (protectionModel) {\n protectionModel.stop();\n }\n }\n\n\n /**\n * Destroys all protection data associated with this protection set. This includes\n * deleting all key sessions. In the case of persistent key sessions, the sessions\n * will simply be unloaded and not deleted. Additionally, if this protection set is\n * associated with a HTMLMediaElement, it will be detached from that element.\n *\n * @memberof module:ProtectionController\n * @instance\n * @ignore\n */\n function reset() {\n eventBus.off(events.INTERNAL_KEY_MESSAGE, _onKeyMessage, instance);\n eventBus.off(events.INTERNAL_KEY_STATUS_CHANGED, _onKeyStatusChanged, instance);\n\n checkConfig();\n\n licenseRequestFilters = [];\n licenseResponseFilters = [];\n\n setMediaElement(null);\n\n selectedKeySystem = null;\n keySystemSelectionInProgress = false;\n\n if (protectionModel) {\n protectionModel.reset();\n protectionModel = null;\n }\n\n needkeyRetries.forEach(retryTimeout => clearTimeout(retryTimeout));\n needkeyRetries = [];\n\n mediaInfoArr = [];\n pendingKeySystemData = [];\n }\n\n /**\n * Returns an object corresponding to the EME MediaKeySystemConfiguration dictionary\n * @param {object} keySystem\n * @return {KeySystemConfiguration}\n * @private\n */\n function _getKeySystemConfiguration(keySystemData) {\n const protData = keySystemData.protData;\n const audioCapabilities = [];\n const videoCapabilities = [];\n const audioRobustness = (protData && protData.audioRobustness && protData.audioRobustness.length > 0) ? protData.audioRobustness : robustnessLevel;\n const videoRobustness = (protData && protData.videoRobustness && protData.videoRobustness.length > 0) ? protData.videoRobustness : robustnessLevel;\n const ksSessionType = keySystemData.sessionType;\n const distinctiveIdentifier = (protData && protData.distinctiveIdentifier) ? protData.distinctiveIdentifier : 'optional';\n const persistentState = (protData && protData.persistentState) ? protData.persistentState : (ksSessionType === 'temporary') ? 'optional' : 'required';\n\n mediaInfoArr.forEach((media) => {\n if (media.type === constants.AUDIO) {\n audioCapabilities.push(new MediaCapability(media.codec, audioRobustness));\n } else if (media.type === constants.VIDEO) {\n videoCapabilities.push(new MediaCapability(media.codec, videoRobustness));\n }\n });\n\n return new KeySystemConfiguration(\n audioCapabilities, videoCapabilities, distinctiveIdentifier,\n persistentState,\n [ksSessionType]);\n }\n\n /**\n * Event handler for when the status of the key has changed\n * @param {object} e\n * @private\n */\n function _onKeyStatusChanged(e) {\n if (e.error) {\n eventBus.trigger(events.KEY_STATUSES_CHANGED, { data: null, error: e.error });\n } else {\n logger.debug('DRM: key status = ' + e.status);\n }\n }\n\n /**\n * Event handler for the key message event. Once we have a key message we can issue a license request\n * @param {object} e\n * @private\n */\n function _onKeyMessage(e) {\n logger.debug('DRM: onKeyMessage');\n\n // Dispatch event to applications indicating we received a key message\n const keyMessage = e.data;\n eventBus.trigger(events.KEY_MESSAGE, { data: keyMessage });\n const messageType = (keyMessage.messageType) ? keyMessage.messageType : 'license-request';\n const message = keyMessage.message;\n const sessionToken = keyMessage.sessionToken;\n const protData = _getProtDataForKeySystem(selectedKeySystem);\n const licenseServerModelInstance = protectionKeyController.getLicenseServerModelInstance(selectedKeySystem, protData, messageType);\n const eventData = { sessionToken: sessionToken, messageType: messageType };\n\n // Ensure message from CDM is not empty\n if (!message || message.byteLength === 0) {\n _sendLicenseRequestCompleteEvent(eventData, new DashJSError(ProtectionErrors.MEDIA_KEY_MESSAGE_NO_CHALLENGE_ERROR_CODE, ProtectionErrors.MEDIA_KEY_MESSAGE_NO_CHALLENGE_ERROR_MESSAGE));\n return;\n }\n\n // Message not destined for license server\n if (!licenseServerModelInstance) {\n logger.debug('DRM: License server request not required for this message (type = ' + e.data.messageType + '). Session ID = ' + sessionToken.getSessionId());\n _sendLicenseRequestCompleteEvent(eventData);\n return;\n }\n\n // Perform any special handling for ClearKey\n if (protectionKeyController.isClearKey(selectedKeySystem)) {\n const clearkeys = protectionKeyController.processClearKeyLicenseRequest(selectedKeySystem, protData, message);\n if (clearkeys) {\n logger.debug('DRM: ClearKey license request handled by application!');\n _sendLicenseRequestCompleteEvent(eventData);\n protectionModel.updateKeySession(sessionToken, clearkeys);\n return;\n }\n }\n\n // In all other cases we have to make a license request\n _issueLicenseRequest(keyMessage, licenseServerModelInstance, protData);\n }\n\n /**\n * Notify other classes that the license request was completed\n * @param {object} data\n * @param {object} error\n * @private\n */\n function _sendLicenseRequestCompleteEvent(data, error) {\n eventBus.trigger(events.LICENSE_REQUEST_COMPLETE, { data: data, error: error });\n }\n\n /**\n * Start issuing a license request\n * @param {object} keyMessage\n * @param {object} licenseServerData\n * @param {object} protData\n * @private\n */\n function _issueLicenseRequest(keyMessage, licenseServerData, protData) {\n const sessionToken = keyMessage.sessionToken;\n const messageType = (keyMessage.messageType) ? keyMessage.messageType : 'license-request';\n const eventData = { sessionToken: sessionToken, messageType: messageType };\n const keySystemString = selectedKeySystem ? selectedKeySystem.systemString : null;\n\n // Determine license server URL\n let url = _getLicenseServerUrl(protData, messageType, sessionToken, keyMessage, licenseServerData);\n\n // Ensure valid license server URL\n if (!url) {\n _sendLicenseRequestCompleteEvent(eventData, new DashJSError(ProtectionErrors.MEDIA_KEY_MESSAGE_NO_LICENSE_SERVER_URL_ERROR_CODE, ProtectionErrors.MEDIA_KEY_MESSAGE_NO_LICENSE_SERVER_URL_ERROR_MESSAGE));\n return;\n }\n\n // Set optional XMLHttpRequest headers from protection data and message\n const reqHeaders = {};\n let withCredentials = false;\n if (protData) {\n _updateHeaders(reqHeaders, protData.httpRequestHeaders);\n }\n const message = keyMessage.message;\n const headersFromMessage = selectedKeySystem.getRequestHeadersFromMessage(message);\n _updateHeaders(reqHeaders, headersFromMessage);\n\n Object.keys(reqHeaders).forEach((key) => {\n if ('authorization' === key.toLowerCase()) {\n withCredentials = true;\n }\n });\n\n // Overwrite withCredentials property from protData if present\n if (protData && typeof protData.withCredentials == 'boolean') {\n withCredentials = protData.withCredentials;\n }\n\n const onLoad = function (xhr) {\n if (!protectionModel) {\n return;\n }\n\n if (xhr.status >= 200 && xhr.status <= 299) {\n const responseHeaders = Utils.parseHttpHeaders(xhr.getAllResponseHeaders ? xhr.getAllResponseHeaders() : null);\n let licenseResponse = new LicenseResponse(xhr.responseURL, responseHeaders, xhr.response);\n _applyFilters(licenseResponseFilters, licenseResponse)\n .then(() => {\n const licenseMessage = licenseServerData.getLicenseMessage(licenseResponse.data, keySystemString, messageType);\n if (licenseMessage !== null) {\n _sendLicenseRequestCompleteEvent(eventData);\n protectionModel.updateKeySession(sessionToken, licenseMessage);\n } else {\n _reportError(xhr, eventData, keySystemString, messageType, licenseServerData);\n }\n });\n } else {\n _reportError(xhr, eventData, keySystemString, messageType, licenseServerData);\n }\n };\n\n const onAbort = function (xhr) {\n _sendLicenseRequestCompleteEvent(eventData, new DashJSError(ProtectionErrors.MEDIA_KEY_MESSAGE_LICENSER_ERROR_CODE,\n ProtectionErrors.MEDIA_KEY_MESSAGE_LICENSER_ERROR_MESSAGE + keySystemString + ' update, XHR aborted. status is \"' +\n xhr.statusText + '\" (' + xhr.status + '), readyState is ' + xhr.readyState));\n };\n\n const onError = function (xhr) {\n _sendLicenseRequestCompleteEvent(eventData, new DashJSError(ProtectionErrors.MEDIA_KEY_MESSAGE_LICENSER_ERROR_CODE,\n ProtectionErrors.MEDIA_KEY_MESSAGE_LICENSER_ERROR_MESSAGE + keySystemString + ' update, XHR error. status is \"' +\n xhr.statusText + '\" (' + xhr.status + '), readyState is ' + xhr.readyState));\n };\n\n const reqPayload = selectedKeySystem.getLicenseRequestFromMessage(message);\n const reqMethod = licenseServerData.getHTTPMethod(messageType);\n const responseType = licenseServerData.getResponseType(keySystemString, messageType);\n const timeout = protData && !isNaN(protData.httpTimeout) ? protData.httpTimeout : LICENSE_SERVER_REQUEST_DEFAULT_TIMEOUT;\n const sessionId = sessionToken.getSessionId() || null;\n\n let licenseRequest = new LicenseRequest(url, reqMethod, responseType, reqHeaders, withCredentials, messageType, sessionId, reqPayload);\n const retryAttempts = !isNaN(settings.get().streaming.retryAttempts[HTTPRequest.LICENSE]) ? settings.get().streaming.retryAttempts[HTTPRequest.LICENSE] : LICENSE_SERVER_REQUEST_RETRIES;\n _applyFilters(licenseRequestFilters, licenseRequest)\n .then(() => {\n _doLicenseRequest(licenseRequest, retryAttempts, timeout, onLoad, onAbort, onError);\n });\n }\n\n /**\n * Implement license requests with a retry mechanism to avoid temporary network issues to affect playback experience\n * @param {object} request\n * @param {number} retriesCount\n * @param {number} timeout\n * @param {function} onLoad\n * @param {function} onAbort\n * @param {function} onError\n * @private\n */\n function _doLicenseRequest(request, retriesCount, timeout, onLoad, onAbort, onError) {\n const xhr = new XMLHttpRequest();\n\n if (settings.get().streaming.cmcd && settings.get().streaming.cmcd.enabled) {\n const cmcdMode = settings.get().streaming.cmcd.mode;\n if (cmcdMode === Constants.CMCD_MODE_QUERY) {\n const cmcdParams = cmcdModel.getQueryParameter({\n url: request.url,\n type: HTTPRequest.LICENSE\n });\n\n if (cmcdParams) {\n request.url = Utils.addAditionalQueryParameterToUrl(request.url, [cmcdParams]);\n }\n }\n }\n\n xhr.open(request.method, request.url, true);\n xhr.responseType = request.responseType;\n xhr.withCredentials = request.withCredentials;\n if (timeout > 0) {\n xhr.timeout = timeout;\n }\n for (const key in request.headers) {\n xhr.setRequestHeader(key, request.headers[key]);\n }\n\n if (settings.get().streaming.cmcd && settings.get().streaming.cmcd.enabled) {\n const cmcdMode = settings.get().streaming.cmcd.mode;\n if (cmcdMode === Constants.CMCD_MODE_HEADER) {\n const cmcdHeaders = cmcdModel.getHeaderParameters({\n url: request.url,\n type: HTTPRequest.LICENSE\n });\n\n if (cmcdHeaders) {\n for (const header in cmcdHeaders) {\n let value = cmcdHeaders[header];\n if (value) {\n xhr.setRequestHeader(header, value);\n }\n }\n }\n }\n }\n\n const _retryRequest = function () {\n // fail silently and retry\n retriesCount--;\n const retryInterval = !isNaN(settings.get().streaming.retryIntervals[HTTPRequest.LICENSE]) ? settings.get().streaming.retryIntervals[HTTPRequest.LICENSE] : LICENSE_SERVER_REQUEST_RETRY_INTERVAL;\n setTimeout(function () {\n _doLicenseRequest(request, retriesCount, timeout, onLoad, onAbort, onError);\n }, retryInterval);\n };\n\n xhr.onload = function () {\n if (this.status >= 200 && this.status <= 299 || retriesCount <= 0) {\n onLoad(this);\n } else {\n logger.warn('License request failed (' + this.status + '). Retrying it... Pending retries: ' + retriesCount);\n _retryRequest();\n }\n };\n\n xhr.ontimeout = xhr.onerror = function () {\n if (retriesCount <= 0) {\n onError(this);\n } else {\n logger.warn('License request network request failed . Retrying it... Pending retries: ' + retriesCount);\n _retryRequest();\n }\n };\n\n xhr.onabort = function () {\n onAbort(this);\n };\n\n // deprecated, to be removed\n eventBus.trigger(events.LICENSE_REQUEST_SENDING, {\n url: request.url,\n headers: request.headers,\n payload: request.data,\n sessionId: request.sessionId\n });\n\n xhr.send(request.data);\n }\n\n /**\n * Returns the url of the license server\n * @param {object} protData\n * @param {string} messageType\n * @param {object} sessionToken\n * @param {object} keyMessage\n * @param {object} licenseServerData\n * @return {*}\n * @private\n */\n function _getLicenseServerUrl(protData, messageType, sessionToken, keyMessage, licenseServerData) {\n let url = null;\n const message = keyMessage.message;\n\n // Check if the url is defined by the application\n if (protData && protData.serverURL) {\n const serverURL = protData.serverURL;\n if (typeof serverURL === 'string' && serverURL !== '') {\n url = serverURL;\n } else if (typeof serverURL === 'object' && serverURL.hasOwnProperty(messageType)) {\n url = serverURL[messageType];\n }\n }\n\n // This is the old way of providing the url\n else if (protData && protData.laURL && protData.laURL !== '') {\n url = protData.laURL;\n }\n\n // No url provided by the app. Check the manifest and the pssh\n else {\n // Check for url defined in the manifest\n url = CommonEncryption.getLicenseServerUrlFromMediaInfo(mediaInfoArr, selectedKeySystem.schemeIdURI);\n\n // In case we are not using Clearky we can still get a url from the pssh.\n if (!url && !protectionKeyController.isClearKey(selectedKeySystem)) {\n const psshData = CommonEncryption.getPSSHData(sessionToken.initData);\n url = selectedKeySystem.getLicenseServerURLFromInitData(psshData);\n\n // Still no url, check the keymessage\n if (!url) {\n url = keyMessage.laURL;\n }\n }\n }\n // Possibly update or override the URL based on the message\n url = licenseServerData.getServerURLFromMessage(url, message, messageType);\n\n return url;\n }\n\n /**\n * Add new headers to the existing ones\n * @param {array} reqHeaders\n * @param {object} headers\n * @private\n */\n function _updateHeaders(reqHeaders, headers) {\n if (headers) {\n for (const key in headers) {\n reqHeaders[key] = headers[key];\n }\n }\n }\n\n /**\n * Reports an error that might have occured during the license request\n * @param {object} xhr\n * @param {object} eventData\n * @param {string} keySystemString\n * @param {string} messageType\n * @param {object} licenseServerData\n * @private\n */\n function _reportError(xhr, eventData, keySystemString, messageType, licenseServerData) {\n const errorMsg = ((xhr.response) ? licenseServerData.getErrorResponse(xhr.response, keySystemString, messageType) : 'NONE');\n _sendLicenseRequestCompleteEvent(eventData, new DashJSError(ProtectionErrors.MEDIA_KEY_MESSAGE_LICENSER_ERROR_CODE,\n ProtectionErrors.MEDIA_KEY_MESSAGE_LICENSER_ERROR_MESSAGE + keySystemString + ' update, XHR complete. status is \"' +\n xhr.statusText + '\" (' + xhr.status + '), readyState is ' + xhr.readyState + '. Response is ' + errorMsg));\n }\n\n /**\n * Applies custom filters defined by the application\n * @param {array} filters\n * @param {object} param\n * @return {Promise<void>|*}\n * @private\n */\n function _applyFilters(filters, param) {\n if (!filters) return Promise.resolve();\n return filters.reduce((prev, next) => {\n return prev.then(() => {\n return next(param);\n });\n }, Promise.resolve());\n }\n\n /**\n * Event handler for \"needkey\" and \"encrypted\" events\n * @param {object} event\n * @param {number} retry\n */\n function _onNeedKey(event, retry) {\n if (!settings.get().streaming.protection.ignoreEmeEncryptedEvent) {\n logger.debug('DRM: onNeedKey');\n\n // Ignore non-cenc initData\n if (event.key.initDataType !== 'cenc') {\n logger.warn('DRM: Only \\'cenc\\' initData is supported! Ignoring initData of type: ' + event.key.initDataType);\n return;\n }\n\n if (mediaInfoArr.length === 0) {\n logger.warn('DRM: onNeedKey called before initializeForMedia, wait until initialized');\n retry = typeof retry === 'undefined' ? 1 : retry + 1;\n if (retry < NEEDKEY_BEFORE_INITIALIZE_RETRIES) {\n needkeyRetries.push(setTimeout(() => {\n _onNeedKey(event, retry);\n }, NEEDKEY_BEFORE_INITIALIZE_TIMEOUT));\n return;\n }\n }\n\n // Some browsers return initData as Uint8Array (IE), some as ArrayBuffer (Chrome).\n // Convert to ArrayBuffer\n let abInitData = event.key.initData;\n if (ArrayBuffer.isView(abInitData)) {\n abInitData = abInitData.buffer;\n }\n\n // If key system has already been selected and initData already seen, then do nothing\n if (selectedKeySystem) {\n const initDataForKS = CommonEncryption.getPSSHForKeySystem(selectedKeySystem, abInitData);\n if (initDataForKS) {\n // Check for duplicate initData\n if (_isInitDataDuplicate(initDataForKS)) {\n return;\n }\n }\n }\n\n logger.debug('DRM: initData:', String.fromCharCode.apply(null, new Uint8Array(abInitData)));\n\n const supportedKS = protectionKeyController.getSupportedKeySystemsFromSegmentPssh(abInitData, protDataSet, sessionType);\n if (supportedKS.length === 0) {\n logger.debug('DRM: Received needkey event with initData, but we don\\'t support any of the key systems!');\n return;\n }\n\n _selectKeySystem(supportedKS, false);\n }\n }\n\n /**\n * Returns all available key systems\n * @return {array}\n */\n function getKeySystems() {\n return protectionKeyController ? protectionKeyController.getKeySystems() : [];\n }\n\n /**\n * Sets all available key systems\n * @param {array} keySystems\n */\n function setKeySystems(keySystems) {\n if (protectionKeyController) {\n protectionKeyController.setKeySystems(keySystems);\n }\n }\n\n /**\n * Sets the request filters to be applied before the license request is made\n * @param {array} filters\n */\n function setLicenseRequestFilters(filters) {\n licenseRequestFilters = filters;\n }\n\n /**\n * Sets the response filters to be applied after the license response has been received.\n * @param {array} filters\n */\n function setLicenseResponseFilters(filters) {\n licenseResponseFilters = filters;\n }\n\n instance = {\n initializeForMedia,\n clearMediaInfoArray,\n createKeySession,\n loadKeySession,\n removeKeySession,\n closeKeySession,\n setServerCertificate,\n setMediaElement,\n setSessionType,\n setRobustnessLevel,\n setProtectionData,\n getSupportedKeySystemsFromContentProtection,\n getKeySystems,\n setKeySystems,\n setLicenseRequestFilters,\n setLicenseResponseFilters,\n stop,\n reset\n };\n\n setup();\n return instance;\n}\n\nProtectionController.__dashjs_factory_name = 'ProtectionController';\nexport default FactoryMaker.getClassFactory(ProtectionController); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @classdesc Represents a 128-bit keyID and 128-bit encryption key\n * @ignore\n */\nclass KeyPair {\n /**\n * @param {string} keyID 128-bit key ID, base64 encoded, with no padding\n * @param {string} key 128-bit encryption key, base64 encoded, with no padding\n * @class\n * @ignore\n */\n constructor(keyID, key) {\n this.keyID = keyID;\n this.key = key;\n }\n}\n\nexport default KeyPair;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * @classdesc A collection of ClearKey encryption keys with an (optional) associated\n * type\n * @ignore\n */\nclass ClearKeyKeySet {\n /**\n * @param {Array.<KeyPair>} keyPairs\n * @param {string} type the type of keys in this set. One of either 'persistent'\n * or 'temporary'. Can also be null or undefined.\n * @class\n * @ignore\n */\n constructor(keyPairs, type) {\n if (type && type !== 'persistent' && type !== 'temporary')\n throw new Error('Invalid ClearKey key set type! Must be one of \\'persistent\\' or \\'temporary\\'');\n this.keyPairs = keyPairs;\n this.type = type;\n }\n\n /**\n * Convert this key set to its JSON Web Key (JWK) representation\n *\n * @return {ArrayBuffer} JWK object UTF-8 encoded as ArrayBuffer\n */\n toJWK() {\n let i;\n let numKeys = this.keyPairs.length;\n let jwk = {keys: []};\n\n for (i = 0; i < numKeys; i++) {\n let key = {\n kty: 'oct',\n alg: 'A128KW',\n kid: this.keyPairs[i].keyID,\n k: this.keyPairs[i].key\n };\n jwk.keys.push(key);\n }\n if (this.type) {\n jwk.type = this.type;\n }\n let jwkString = JSON.stringify(jwk);\n const len = jwkString.length;\n\n // Convert JSON string to ArrayBuffer\n let buf = new ArrayBuffer(len);\n let bView = new Uint8Array(buf);\n for (i = 0; i < len; i++)\n bView[i] = jwkString.charCodeAt(i);\n return buf;\n }\n}\n\nexport default ClearKeyKeySet;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * Protection Constants declaration\n * @class\n * @ignore\n */\nclass ProtectionConstants {\n\n init () {\n this.CLEARKEY_KEYSTEM_STRING = 'org.w3.clearkey';\n this.WIDEVINE_KEYSTEM_STRING = 'com.widevine.alpha';\n this.PLAYREADY_KEYSTEM_STRING = 'com.microsoft.playready';\n this.PLAYREADY_RECOMMENDATION_KEYSTEM_STRING = 'com.microsoft.playready.recommendation';\n this.INITIALIZATION_DATA_TYPE_CENC = 'cenc';\n this.INITIALIZATION_DATA_TYPE_KEYIDS = 'keyids'\n this.INITIALIZATION_DATA_TYPE_WEBM = 'webm'\n }\n\n constructor () {\n this.init();\n }\n}\n\nlet constants = new ProtectionConstants();\nexport default constants;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport KeyPair from '../vo/KeyPair';\nimport ClearKeyKeySet from '../vo/ClearKeyKeySet';\nimport CommonEncryption from '../CommonEncryption';\nimport ProtectionConstants from '../../constants/ProtectionConstants';\n\nconst uuid = 'e2719d58-a985-b3c9-781a-b030af78d30e';\nconst systemString = ProtectionConstants.CLEARKEY_KEYSTEM_STRING;\nconst schemeIdURI = 'urn:uuid:' + uuid;\n\nfunction KeySystemClearKey(config) {\n\n config = config || {};\n let instance;\n const BASE64 = config.BASE64;\n\n /**\n * Returns desired clearkeys (as specified in the CDM message) from protection data\n *\n * @param {ProtectionData} protectionData the protection data\n * @param {ArrayBuffer} message the ClearKey CDM message\n * @returns {ClearKeyKeySet} the key set or null if none found\n * @throws {Error} if a keyID specified in the CDM message was not found in the\n * protection data\n * @memberof KeySystemClearKey\n */\n function getClearKeysFromProtectionData(protectionData, message) {\n let clearkeySet = null;\n if (protectionData) {\n // ClearKey is the only system that does not require a license server URL, so we\n // handle it here when keys are specified in protection data\n const jsonMsg = JSON.parse(String.fromCharCode.apply(null, new Uint8Array(message)));\n const keyPairs = [];\n for (let i = 0; i < jsonMsg.kids.length; i++) {\n const clearkeyID = jsonMsg.kids[i];\n const clearkey = (protectionData.clearkeys && protectionData.clearkeys.hasOwnProperty(clearkeyID)) ? protectionData.clearkeys[clearkeyID] : null;\n if (!clearkey) {\n throw new Error('DRM: ClearKey keyID (' + clearkeyID + ') is not known!');\n }\n // KeyIDs from CDM are not base64 padded. Keys may or may not be padded\n keyPairs.push(new KeyPair(clearkeyID, clearkey));\n }\n clearkeySet = new ClearKeyKeySet(keyPairs);\n }\n return clearkeySet;\n }\n\n function getInitData(cp, cencContentProtection) {\n try {\n let initData = CommonEncryption.parseInitDataFromContentProtection(cp, BASE64);\n\n if (!initData && cencContentProtection) {\n const cencDefaultKid = cencDefaultKidToBase64Representation(cencContentProtection['cenc:default_KID']);\n const data = {kids: [cencDefaultKid]};\n initData = new TextEncoder().encode(JSON.stringify(data));\n }\n\n return initData;\n } catch (e) {\n return null;\n }\n }\n\n function cencDefaultKidToBase64Representation(cencDefaultKid) {\n try {\n let kid = cencDefaultKid.replace(/-/g, '');\n kid = btoa(kid.match(/\\w{2}/g).map((a) => {\n return String.fromCharCode(parseInt(a, 16));\n }).join(''));\n return kid.replace(/=/g, '');\n } catch (e) {\n return null;\n }\n }\n\n function getRequestHeadersFromMessage(/*message*/) {\n // Set content type to application/json by default\n return {\n 'Content-Type': 'application/json'\n };\n }\n\n function getLicenseRequestFromMessage(message) {\n return JSON.parse(String.fromCharCode.apply(null, new Uint8Array(message)));\n }\n\n function getLicenseServerURLFromInitData(/*initData*/) {\n return null;\n }\n\n function getCDMData(/*cdmData*/) {\n return null;\n }\n\n instance = {\n uuid,\n schemeIdURI,\n systemString,\n getInitData,\n getRequestHeadersFromMessage,\n getLicenseRequestFromMessage,\n getLicenseServerURLFromInitData,\n getCDMData,\n getClearKeysFromProtectionData\n };\n\n return instance;\n}\n\nKeySystemClearKey.__dashjs_factory_name = 'KeySystemClearKey';\nexport default dashjs.FactoryMaker.getSingletonFactory(KeySystemClearKey); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport KeyPair from '../vo/KeyPair';\nimport ClearKeyKeySet from '../vo/ClearKeyKeySet';\nimport CommonEncryption from '../CommonEncryption';\nimport ProtectionConstants from '../../constants/ProtectionConstants';\n\nconst uuid = '1077efec-c0b2-4d02-ace3-3c1e52e2fb4b';\nconst systemString = ProtectionConstants.CLEARKEY_KEYSTEM_STRING;\nconst schemeIdURI = 'urn:uuid:' + uuid;\n\nfunction KeySystemW3CClearKey(config) {\n let instance;\n const BASE64 = config.BASE64;\n const logger = config.debug.getLogger(instance);\n /**\n * Returns desired clearkeys (as specified in the CDM message) from protection data\n *\n * @param {ProtectionDataSet} protectionData the protection data\n * @param {ArrayBuffer} message the ClearKey CDM message\n * @returns {ClearKeyKeySet} the key set or null if none found\n * @throws {Error} if a keyID specified in the CDM message was not found in the\n * protection data\n * @memberof KeySystemClearKey\n */\n function getClearKeysFromProtectionData(protectionData, message) {\n let clearkeySet = null;\n if (protectionData) {\n // ClearKey is the only system that does not require a license server URL, so we\n // handle it here when keys are specified in protection data\n const jsonMsg = JSON.parse(String.fromCharCode.apply(null, new Uint8Array(message)));\n const keyPairs = [];\n for (let i = 0; i < jsonMsg.kids.length; i++) {\n const clearkeyID = jsonMsg.kids[i];\n const clearkey = (protectionData.clearkeys && protectionData.clearkeys.hasOwnProperty(clearkeyID)) ? protectionData.clearkeys[clearkeyID] : null;\n if (!clearkey) {\n throw new Error('DRM: ClearKey keyID (' + clearkeyID + ') is not known!');\n }\n // KeyIDs from CDM are not base64 padded. Keys may or may not be padded\n keyPairs.push(new KeyPair(clearkeyID, clearkey));\n }\n clearkeySet = new ClearKeyKeySet(keyPairs);\n\n logger.warn('ClearKey schemeIdURI is using W3C Common PSSH systemID (1077efec-c0b2-4d02-ace3-3c1e52e2fb4b) in Content Protection. See DASH-IF IOP v4.1 section 7.6.2.4');\n }\n return clearkeySet;\n }\n\n function getInitData(cp) {\n return CommonEncryption.parseInitDataFromContentProtection(cp, BASE64);\n }\n\n function getRequestHeadersFromMessage(/*message*/) {\n return null;\n }\n\n function getLicenseRequestFromMessage(message) {\n return new Uint8Array(message);\n }\n\n function getLicenseServerURLFromInitData(/*initData*/) {\n return null;\n }\n\n function getCDMData(/*cdmData*/) {\n return null;\n }\n\n instance = {\n uuid: uuid,\n schemeIdURI: schemeIdURI,\n systemString: systemString,\n getInitData: getInitData,\n getRequestHeadersFromMessage: getRequestHeadersFromMessage,\n getLicenseRequestFromMessage: getLicenseRequestFromMessage,\n getLicenseServerURLFromInitData: getLicenseServerURLFromInitData,\n getCDMData: getCDMData,\n getClearKeysFromProtectionData: getClearKeysFromProtectionData\n };\n\n return instance;\n}\n\nKeySystemW3CClearKey.__dashjs_factory_name = 'KeySystemW3CClearKey';\nexport default dashjs.FactoryMaker.getSingletonFactory(KeySystemW3CClearKey); /* jshint ignore:line */\n\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * Google Widevine DRM\n *\n * @class\n * @implements MediaPlayer.dependencies.protection.KeySystem\n */\n\nimport CommonEncryption from '../CommonEncryption';\nimport ProtectionConstants from '../../constants/ProtectionConstants';\n\nconst uuid = 'edef8ba9-79d6-4ace-a3c8-27dcd51d21ed';\nconst systemString = ProtectionConstants.WIDEVINE_KEYSTEM_STRING;\nconst schemeIdURI = 'urn:uuid:' + uuid;\n\nfunction KeySystemWidevine(config) {\n\n config = config || {};\n let instance;\n const BASE64 = config.BASE64;\n\n function getInitData(cp) {\n return CommonEncryption.parseInitDataFromContentProtection(cp, BASE64);\n }\n\n function getRequestHeadersFromMessage( /*message*/ ) {\n return null;\n }\n\n function getLicenseRequestFromMessage(message) {\n return new Uint8Array(message);\n }\n\n function getLicenseServerURLFromInitData( /*initData*/ ) {\n return null;\n }\n\n function getCDMData(/*cdmData*/) {\n return null;\n }\n\n instance = {\n uuid,\n schemeIdURI,\n systemString,\n getInitData,\n getRequestHeadersFromMessage,\n getLicenseRequestFromMessage,\n getLicenseServerURLFromInitData,\n getCDMData\n };\n\n return instance;\n}\n\nKeySystemWidevine.__dashjs_factory_name = 'KeySystemWidevine';\nexport default dashjs.FactoryMaker.getSingletonFactory(KeySystemWidevine); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * Microsoft PlayReady DRM\n *\n * @class\n * @implements KeySystem\n */\nimport CommonEncryption from '../CommonEncryption';\nimport ProtectionConstants from '../../constants/ProtectionConstants';\n\nconst uuid = '9a04f079-9840-4286-ab92-e65be0885f95';\nconst systemString = ProtectionConstants.PLAYREADY_KEYSTEM_STRING;\nconst schemeIdURI = 'urn:uuid:' + uuid;\nconst PRCDMData = '<PlayReadyCDMData type=\"LicenseAcquisition\"><LicenseAcquisition version=\"1.0\" Proactive=\"false\"><CustomData encoding=\"base64encoded\">%CUSTOMDATA%</CustomData></LicenseAcquisition></PlayReadyCDMData>';\n\nfunction KeySystemPlayReady(config) {\n\n config = config || {};\n let instance;\n let messageFormat = 'utf-16';\n const BASE64 = config.BASE64;\n\n function checkConfig() {\n if (!BASE64 || !BASE64.hasOwnProperty('decodeArray') || !BASE64.hasOwnProperty('decodeArray') ) {\n throw new Error('Missing config parameter(s)');\n }\n }\n\n function getRequestHeadersFromMessage(message) {\n let msg,\n xmlDoc;\n const headers = {};\n const parser = new DOMParser();\n const dataview = (messageFormat === 'utf-16') ? new Uint16Array(message) : new Uint8Array(message);\n\n msg = String.fromCharCode.apply(null, dataview);\n xmlDoc = parser.parseFromString(msg, 'application/xml');\n\n const headerNameList = xmlDoc.getElementsByTagName('name');\n const headerValueList = xmlDoc.getElementsByTagName('value');\n for (let i = 0; i < headerNameList.length; i++) {\n headers[headerNameList[i].childNodes[0].nodeValue] = headerValueList[i].childNodes[0].nodeValue;\n }\n // Some versions of the PlayReady CDM return 'Content' instead of 'Content-Type'.\n // this is NOT w3c conform and license servers may reject the request!\n // -> rename it to proper w3c definition!\n if (headers.hasOwnProperty('Content')) {\n headers['Content-Type'] = headers.Content;\n delete headers.Content;\n }\n // Set Content-Type header by default if not provided in the the CDM message (<PlayReadyKeyMessage/>)\n // or if the message contains directly the challenge itself (Ex: LG SmartTVs)\n if (!headers.hasOwnProperty('Content-Type')) {\n headers['Content-Type'] = 'text/xml; charset=utf-8';\n }\n return headers;\n }\n\n function getLicenseRequestFromMessage(message) {\n let licenseRequest = null;\n const parser = new DOMParser();\n const dataview = (messageFormat === 'utf-16') ? new Uint16Array(message) : new Uint8Array(message);\n\n checkConfig();\n const msg = String.fromCharCode.apply(null, dataview);\n const xmlDoc = parser.parseFromString(msg, 'application/xml');\n\n if (xmlDoc.getElementsByTagName('PlayReadyKeyMessage')[0]) {\n const Challenge = xmlDoc.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue;\n if (Challenge) {\n licenseRequest = BASE64.decode(Challenge);\n }\n } else {\n // The message from CDM is not a wrapped message as on IE11 and Edge,\n // thus it contains direclty the challenge itself\n // (note that the xmlDoc at this point may be unreadable since it may have been interpreted as UTF-16)\n return message;\n }\n\n return licenseRequest;\n }\n\n function getLicenseServerURLFromInitData(initData) {\n if (initData) {\n const data = new DataView(initData);\n const numRecords = data.getUint16(4, true);\n let offset = 6;\n const parser = new DOMParser();\n\n for (let i = 0; i < numRecords; i++) {\n // Parse the PlayReady Record header\n const recordType = data.getUint16(offset, true);\n offset += 2;\n const recordLength = data.getUint16(offset, true);\n offset += 2;\n if (recordType !== 0x0001) {\n offset += recordLength;\n continue;\n }\n\n const recordData = initData.slice(offset, offset + recordLength);\n const record = String.fromCharCode.apply(null, new Uint16Array(recordData));\n const xmlDoc = parser.parseFromString(record, 'application/xml');\n\n // First try <LA_URL>\n if (xmlDoc.getElementsByTagName('LA_URL')[0]) {\n const laurl = xmlDoc.getElementsByTagName('LA_URL')[0].childNodes[0].nodeValue;\n if (laurl) {\n return laurl;\n }\n }\n\n // Optionally, try <LUI_URL>\n if (xmlDoc.getElementsByTagName('LUI_URL')[0]) {\n const luiurl = xmlDoc.getElementsByTagName('LUI_URL')[0].childNodes[0].nodeValue;\n if (luiurl) {\n return luiurl;\n }\n }\n }\n }\n\n return null;\n }\n\n function getInitData(cpData) {\n // * desc@ getInitData\n // * generate PSSH data from PROHeader defined in MPD file\n // * PSSH format:\n // * size (4)\n // * box type(PSSH) (8)\n // * Protection SystemID (16)\n // * protection system data size (4) - length of decoded PROHeader\n // * decoded PROHeader data from MPD file\n const PSSHBoxType = new Uint8Array([0x70, 0x73, 0x73, 0x68, 0x00, 0x00, 0x00, 0x00]); //'PSSH' 8 bytes\n const playreadySystemID = new Uint8Array([0x9a, 0x04, 0xf0, 0x79, 0x98, 0x40, 0x42, 0x86, 0xab, 0x92, 0xe6, 0x5b, 0xe0, 0x88, 0x5f, 0x95]);\n\n let byteCursor = 0;\n let uint8arraydecodedPROHeader = null;\n\n let PROSize,\n PSSHSize,\n PSSHBoxBuffer,\n PSSHBox,\n PSSHData;\n\n checkConfig();\n if (!cpData) {\n return null;\n }\n // Handle common encryption PSSH\n if ('pssh' in cpData) {\n return CommonEncryption.parseInitDataFromContentProtection(cpData, BASE64);\n }\n // Handle native MS PlayReady ContentProtection elements\n if ('pro' in cpData) {\n uint8arraydecodedPROHeader = BASE64.decodeArray(cpData.pro.__text);\n }\n else if ('prheader' in cpData) {\n uint8arraydecodedPROHeader = BASE64.decodeArray(cpData.prheader.__text);\n }\n else {\n return null;\n }\n\n PROSize = uint8arraydecodedPROHeader.length;\n PSSHSize = 0x4 + PSSHBoxType.length + playreadySystemID.length + 0x4 + PROSize;\n\n PSSHBoxBuffer = new ArrayBuffer(PSSHSize);\n\n PSSHBox = new Uint8Array(PSSHBoxBuffer);\n PSSHData = new DataView(PSSHBoxBuffer);\n\n PSSHData.setUint32(byteCursor, PSSHSize);\n byteCursor += 0x4;\n\n PSSHBox.set(PSSHBoxType, byteCursor);\n byteCursor += PSSHBoxType.length;\n\n PSSHBox.set(playreadySystemID, byteCursor);\n byteCursor += playreadySystemID.length;\n\n PSSHData.setUint32(byteCursor, PROSize);\n byteCursor += 0x4;\n\n PSSHBox.set(uint8arraydecodedPROHeader, byteCursor);\n byteCursor += PROSize;\n\n return PSSHBox.buffer;\n }\n\n /**\n * It seems that some PlayReady implementations return their XML-based CDM\n * messages using UTF16, while others return them as UTF8. Use this function\n * to modify the message format to expect when parsing CDM messages.\n *\n * @param {string} format the expected message format. Either \"utf-8\" or \"utf-16\".\n * @throws {Error} Specified message format is not one of \"utf8\" or \"utf16\"\n */\n function setPlayReadyMessageFormat(format) {\n if (format !== 'utf-8' && format !== 'utf-16') {\n throw new Error('Specified message format is not one of \"utf-8\" or \"utf-16\"');\n }\n messageFormat = format;\n }\n\n /**\n * Get Playready Custom data\n */\n function getCDMData(_cdmData) {\n let customData,\n cdmData,\n cdmDataBytes,\n i;\n\n checkConfig();\n if (!_cdmData) return null;\n\n // Convert custom data into multibyte string\n customData = [];\n for (i = 0; i < _cdmData.length; ++i) {\n customData.push(_cdmData.charCodeAt(i));\n customData.push(0);\n }\n customData = String.fromCharCode.apply(null, customData);\n\n // Encode in Base 64 the custom data string\n customData = BASE64.encode(customData);\n\n // Initialize CDM data with Base 64 encoded custom data\n // (see https://msdn.microsoft.com/en-us/library/dn457361.aspx)\n cdmData = PRCDMData.replace('%CUSTOMDATA%', customData);\n\n // Convert CDM data into multibyte characters\n cdmDataBytes = [];\n for (i = 0; i < cdmData.length; ++i) {\n cdmDataBytes.push(cdmData.charCodeAt(i));\n cdmDataBytes.push(0);\n }\n\n return new Uint8Array(cdmDataBytes).buffer;\n }\n\n instance = {\n uuid,\n schemeIdURI,\n systemString,\n getInitData,\n getRequestHeadersFromMessage,\n getLicenseRequestFromMessage,\n getLicenseServerURLFromInitData,\n getCDMData,\n setPlayReadyMessageFormat\n };\n\n return instance;\n}\n\nKeySystemPlayReady.__dashjs_factory_name = 'KeySystemPlayReady';\nexport default dashjs.FactoryMaker.getSingletonFactory(KeySystemPlayReady); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * CastLabs DRMToday License Server implementation\n *\n * @implements LicenseServer\n * @class\n */\n\nimport ProtectionConstants from '../../constants/ProtectionConstants';\n\nfunction DRMToday(config) {\n\n config = config || {};\n const BASE64 = config.BASE64;\n\n const keySystems = {};\n keySystems[ProtectionConstants.WIDEVINE_KEYSTEM_STRING] = {\n responseType: 'json',\n getLicenseMessage: function (response) {\n return BASE64.decodeArray(response.license);\n },\n getErrorResponse: function (response) {\n return response;\n }\n };\n keySystems[ProtectionConstants.PLAYREADY_KEYSTEM_STRING] = {\n responseType: 'arraybuffer',\n getLicenseMessage: function (response) {\n return response;\n },\n getErrorResponse: function (response) {\n return String.fromCharCode.apply(null, new Uint8Array(response));\n }\n };\n\n let instance;\n\n function checkConfig() {\n if (!BASE64 || !BASE64.hasOwnProperty('decodeArray')) {\n throw new Error('Missing config parameter(s)');\n }\n }\n\n function getServerURLFromMessage(url /*, message, messageType*/) {\n return url;\n }\n\n function getHTTPMethod(/*messageType*/) {\n return 'POST';\n }\n\n function getResponseType(keySystemStr/*, messageType*/) {\n return keySystems[keySystemStr].responseType;\n }\n\n function getLicenseMessage(serverResponse, keySystemStr/*, messageType*/) {\n checkConfig();\n return keySystems[keySystemStr].getLicenseMessage(serverResponse);\n }\n\n function getErrorResponse(serverResponse, keySystemStr/*, messageType*/) {\n return keySystems[keySystemStr].getErrorResponse(serverResponse);\n }\n\n instance = {\n getServerURLFromMessage,\n getHTTPMethod,\n getResponseType,\n getLicenseMessage,\n getErrorResponse\n };\n\n return instance;\n}\n\nDRMToday.__dashjs_factory_name = 'DRMToday';\nexport default dashjs.FactoryMaker.getSingletonFactory(DRMToday); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/* global escape: true */\n\n/**\n * Microsoft PlayReady Test License Server\n *\n * For testing content that uses the PlayReady test server at\n *\n * @implements LicenseServer\n * @class\n * @ignore\n */\n\nfunction PlayReady() {\n\n let instance;\n\n const soap = 'http://schemas.xmlsoap.org/soap/envelope/';\n\n function uintToString(arrayBuffer) {\n const encodedString = String.fromCharCode.apply(null, new Uint8Array(arrayBuffer));\n const decodedString = decodeURIComponent(escape(encodedString));\n return decodedString;\n }\n\n function parseServerResponse(serverResponse) {\n if (window.DOMParser) {\n const stringResponse = uintToString(serverResponse);\n const parser = new window.DOMParser();\n const xmlDoc = parser.parseFromString(stringResponse, 'text/xml');\n const envelope = xmlDoc ? xmlDoc.getElementsByTagNameNS(soap, 'Envelope')[0] : null;\n const body = envelope ? envelope.getElementsByTagNameNS(soap, 'Body')[0] : null;\n const fault = body ? body.getElementsByTagNameNS(soap, 'Fault')[0] : null;\n\n if (fault) {\n return null;\n }\n }\n return serverResponse;\n }\n\n function parseErrorResponse(serverResponse) {\n let faultstring = '';\n let statusCode = '';\n let message = '';\n let idStart = -1;\n let idEnd = -1;\n\n if (window.DOMParser) {\n const stringResponse = uintToString(serverResponse);\n const parser = new window.DOMParser();\n const xmlDoc = parser.parseFromString(stringResponse, 'text/xml');\n const envelope = xmlDoc ? xmlDoc.getElementsByTagNameNS(soap, 'Envelope')[0] : null;\n const body = envelope ? envelope.getElementsByTagNameNS(soap, 'Body')[0] : null;\n const fault = body ? body.getElementsByTagNameNS(soap, 'Fault')[0] : null;\n const detail = fault ? fault.getElementsByTagName('detail')[0] : null;\n const exception = detail ? detail.getElementsByTagName('Exception')[0] : null;\n let node = null;\n\n if (fault === null) {\n return stringResponse;\n }\n\n node = fault.getElementsByTagName('faultstring')[0].firstChild;\n faultstring = node ? node.nodeValue : null;\n\n if (exception !== null) {\n node = exception.getElementsByTagName('StatusCode')[0];\n statusCode = node ? node.firstChild.nodeValue : null;\n node = exception.getElementsByTagName('Message')[0];\n message = node ? node.firstChild.nodeValue : null;\n idStart = message ? message.lastIndexOf('[') + 1 : -1;\n idEnd = message ? message.indexOf(']') : -1;\n message = message ? message.substring(idStart, idEnd) : '';\n }\n }\n\n let errorString = `code: ${statusCode}, name: ${faultstring}`;\n if (message) {\n errorString += `, message: ${message}`;\n }\n\n return errorString;\n }\n\n function getServerURLFromMessage(url /*, message, messageType*/) {\n return url;\n }\n\n function getHTTPMethod(/*messageType*/) {\n return 'POST';\n }\n\n function getResponseType(/*keySystemStr, messageType*/) {\n return 'arraybuffer';\n }\n\n function getLicenseMessage(serverResponse/*, keySystemStr, messageType*/) {\n return parseServerResponse.call(this, serverResponse);\n }\n\n function getErrorResponse(serverResponse/*, keySystemStr, messageType*/) {\n return parseErrorResponse.call(this, serverResponse);\n }\n\n instance = {\n getServerURLFromMessage,\n getHTTPMethod,\n getResponseType,\n getLicenseMessage,\n getErrorResponse\n };\n\n return instance;\n}\n\nPlayReady.__dashjs_factory_name = 'PlayReady';\nexport default dashjs.FactoryMaker.getSingletonFactory(PlayReady); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * @ignore\n */\nfunction Widevine() {\n\n let instance;\n\n function getServerURLFromMessage(url /*, message, messageType*/) {\n return url;\n }\n\n function getHTTPMethod(/*messageType*/) {\n return 'POST';\n }\n\n function getResponseType(/*keySystemStr, messageType*/) {\n return 'arraybuffer';\n }\n\n function getLicenseMessage(serverResponse/*, keySystemStr, messageType*/) {\n return serverResponse;\n }\n\n function getErrorResponse(serverResponse/*, keySystemStr, messageType*/) {\n return String.fromCharCode.apply(null, new Uint8Array(serverResponse));\n }\n\n instance = {\n getServerURLFromMessage,\n getHTTPMethod,\n getResponseType,\n getLicenseMessage,\n getErrorResponse\n };\n\n return instance;\n}\n\nWidevine.__dashjs_factory_name = 'Widevine';\nexport default dashjs.FactoryMaker.getSingletonFactory(Widevine); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * CableLabs ClearKey license server implementation\n *\n * For testing purposes and evaluating potential uses for ClearKey, we have developed\n * a dirt-simple API for requesting ClearKey licenses from a remote server.\n *\n * @implements LicenseServer\n * @class\n */\nimport KeyPair from '../vo/KeyPair';\nimport ClearKeyKeySet from '../vo/ClearKeyKeySet';\n\nfunction ClearKey() {\n\n let instance;\n\n function getServerURLFromMessage(url /* message, messageType*/) {\n return url;\n }\n\n function getHTTPMethod(/*messageType*/) {\n return 'POST';\n }\n\n function getResponseType(/*keySystemStr*/) {\n return 'json';\n }\n\n function getLicenseMessage(serverResponse/*, keySystemStr, messageType*/) {\n if (!serverResponse.hasOwnProperty('keys')) {\n return null;\n }\n let keyPairs = [];\n for (let i = 0; i < serverResponse.keys.length; i++) {\n let keypair = serverResponse.keys[i];\n let keyid = keypair.kid.replace(/=/g, '');\n let key = keypair.k.replace(/=/g, '');\n\n keyPairs.push(new KeyPair(keyid, key));\n }\n return new ClearKeyKeySet(keyPairs);\n }\n\n function getErrorResponse(serverResponse/*, keySystemStr, messageType*/) {\n return String.fromCharCode.apply(null, new Uint8Array(serverResponse));\n }\n\n instance = {\n getServerURLFromMessage,\n getHTTPMethod,\n getResponseType,\n getLicenseMessage,\n getErrorResponse\n };\n\n return instance;\n}\n\nClearKey.__dashjs_factory_name = 'ClearKey';\nexport default dashjs.FactoryMaker.getSingletonFactory(ClearKey); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport CommonEncryption from './../CommonEncryption';\nimport KeySystemClearKey from './../drm/KeySystemClearKey';\nimport KeySystemW3CClearKey from './../drm/KeySystemW3CClearKey';\nimport KeySystemWidevine from './../drm/KeySystemWidevine';\nimport KeySystemPlayReady from './../drm/KeySystemPlayReady';\nimport DRMToday from './../servers/DRMToday';\nimport PlayReady from './../servers/PlayReady';\nimport Widevine from './../servers/Widevine';\nimport ClearKey from './../servers/ClearKey';\nimport ProtectionConstants from '../../constants/ProtectionConstants';\n\n/**\n * @module ProtectionKeyController\n * @ignore\n * @description Media protection key system functionality that can be modified/overridden by applications\n */\nfunction ProtectionKeyController() {\n\n let context = this.context;\n\n let instance,\n debug,\n logger,\n keySystems,\n BASE64,\n clearkeyKeySystem,\n clearkeyW3CKeySystem;\n\n function setConfig(config) {\n if (!config) return;\n\n if (config.debug) {\n debug = config.debug;\n logger = debug.getLogger(instance);\n }\n\n if (config.BASE64) {\n BASE64 = config.BASE64;\n }\n }\n\n function initialize() {\n keySystems = [];\n\n let keySystem;\n\n // PlayReady\n keySystem = KeySystemPlayReady(context).getInstance({BASE64: BASE64});\n keySystems.push(keySystem);\n\n // Widevine\n keySystem = KeySystemWidevine(context).getInstance({BASE64: BASE64});\n keySystems.push(keySystem);\n\n // ClearKey\n keySystem = KeySystemClearKey(context).getInstance({BASE64: BASE64});\n keySystems.push(keySystem);\n clearkeyKeySystem = keySystem;\n\n // W3C ClearKey\n keySystem = KeySystemW3CClearKey(context).getInstance({BASE64: BASE64, debug: debug});\n keySystems.push(keySystem);\n clearkeyW3CKeySystem = keySystem;\n }\n\n /**\n * Returns a prioritized list of key systems supported\n * by this player (not necessarily those supported by the\n * user agent)\n *\n * @returns {Array.<KeySystem>} a prioritized\n * list of key systems\n * @memberof module:ProtectionKeyController\n * @instance\n */\n function getKeySystems() {\n return keySystems;\n }\n\n /**\n * Sets the prioritized list of key systems to be supported\n * by this player.\n *\n * @param {Array.<KeySystem>} newKeySystems the new prioritized\n * list of key systems\n * @memberof module:ProtectionKeyController\n * @instance\n */\n function setKeySystems(newKeySystems) {\n keySystems = newKeySystems;\n }\n\n /**\n * Returns the key system associated with the given key system string\n * name (i.e. 'org.w3.clearkey')\n *\n * @param {string} systemString the system string\n * @returns {KeySystem|null} the key system\n * or null if no supported key system is associated with the given key\n * system string\n * @memberof module:ProtectionKeyController\n * @instance\n */\n function getKeySystemBySystemString(systemString) {\n for (let i = 0; i < keySystems.length; i++) {\n if (keySystems[i].systemString === systemString) {\n return keySystems[i];\n }\n }\n return null;\n }\n\n /**\n * Determines whether the given key system is ClearKey. This is\n * necessary because the EME spec defines ClearKey and its method\n * for providing keys to the key session; and this method has changed\n * between the various API versions. Our EME-specific ProtectionModels\n * must know if the system is ClearKey so that it can format the keys\n * according to the particular spec version.\n *\n * @param {Object} keySystem the key\n * @returns {boolean} true if this is the ClearKey key system, false\n * otherwise\n * @memberof module:ProtectionKeyController\n * @instance\n */\n function isClearKey(keySystem) {\n return (keySystem === clearkeyKeySystem || keySystem === clearkeyW3CKeySystem);\n }\n\n /**\n * Check equality of initData array buffers.\n *\n * @param {ArrayBuffer} initData1 - first initData\n * @param {ArrayBuffer} initData2 - second initData\n * @returns {boolean} true if the initData arrays are equal in size and\n * contents, false otherwise\n * @memberof module:ProtectionKeyController\n * @instance\n */\n function initDataEquals(initData1, initData2) {\n if (initData1.byteLength === initData2.byteLength) {\n let data1 = new Uint8Array(initData1);\n let data2 = new Uint8Array(initData2);\n\n for (let j = 0; j < data1.length; j++) {\n if (data1[j] !== data2[j]) {\n return false;\n }\n }\n return true;\n }\n return false;\n }\n\n /**\n * Returns a set of supported key systems and CENC initialization data\n * from the given array of ContentProtection elements. Only\n * key systems that are supported by this player will be returned.\n * Key systems are returned in priority order (highest first).\n *\n * @param {Array.<Object>} cps - array of content protection elements parsed\n * from the manifest\n * @param {ProtectionData} protDataSet user specified protection data - license server url etc\n * supported by the content\n * @param {string} default session type\n * @returns {Array.<Object>} array of objects indicating which supported key\n * systems were found. Empty array is returned if no\n * supported key systems were found\n * @memberof module:ProtectionKeyController\n * @instance\n */\n function getSupportedKeySystemsFromContentProtection(cps, protDataSet, sessionType) {\n let cp, ks, ksIdx, cpIdx;\n let supportedKS = [];\n\n if (cps) {\n const cencContentProtection = CommonEncryption.findCencContentProtection(cps);\n for (ksIdx = 0; ksIdx < keySystems.length; ++ksIdx) {\n ks = keySystems[ksIdx];\n\n // Get protection data that applies for current key system\n const protData = _getProtDataForKeySystem(ks.systemString, protDataSet);\n\n for (cpIdx = 0; cpIdx < cps.length; ++cpIdx) {\n cp = cps[cpIdx];\n if (cp.schemeIdUri.toLowerCase() === ks.schemeIdURI) {\n // Look for DRM-specific ContentProtection\n let initData = ks.getInitData(cp, cencContentProtection);\n\n supportedKS.push({\n ks: keySystems[ksIdx],\n keyId: cp.keyId,\n initData: initData,\n protData: protData,\n cdmData: ks.getCDMData(protData ? protData.cdmData : null),\n sessionId: _getSessionId(protData, cp),\n sessionType: _getSessionType(protData, sessionType)\n });\n }\n }\n }\n }\n return supportedKS;\n }\n\n /**\n * Returns key systems supported by this player for the given PSSH\n * initializationData. Key systems are returned in priority order\n * (highest priority first)\n *\n * @param {ArrayBuffer} initData Concatenated PSSH data for all DRMs\n * supported by the content\n * @param {ProtectionData} protDataSet user specified protection data - license server url etc\n * supported by the content\n * @param {string} default session type\n * @returns {Array.<Object>} array of objects indicating which supported key\n * systems were found. Empty array is returned if no\n * supported key systems were found\n * @memberof module:ProtectionKeyController\n * @instance\n */\n function getSupportedKeySystemsFromSegmentPssh(initData, protDataSet, sessionType) {\n let supportedKS = [];\n let pssh = CommonEncryption.parsePSSHList(initData);\n let ks, keySystemString;\n\n for (let ksIdx = 0; ksIdx < keySystems.length; ++ksIdx) {\n ks = keySystems[ksIdx];\n keySystemString = ks.systemString;\n\n // Get protection data that applies for current key system\n const protData = _getProtDataForKeySystem(keySystemString, protDataSet);\n\n if (ks.uuid in pssh) {\n supportedKS.push({\n ks: ks,\n initData: pssh[ks.uuid],\n protData: protData,\n cdmData: ks.getCDMData(protData ? protData.cdmData : null),\n sessionId: _getSessionId(protData),\n sessionType: _getSessionType(protData, sessionType)\n });\n }\n }\n return supportedKS;\n }\n\n /**\n * Returns the license server implementation data that should be used for this request.\n *\n * @param {KeySystem} keySystem the key system\n * associated with this license request\n * @param {ProtectionData} protData protection data to use for the\n * request\n * @param {string} [messageType=\"license-request\"] the message type associated with this\n * request. Supported message types can be found\n * {@link https://w3c.github.io/encrypted-media/#idl-def-MediaKeyMessageType|here}.\n * @returns {LicenseServer|null} the license server\n * implementation that should be used for this request or null if the player should not\n * pass messages of the given type to a license server\n * @memberof module:ProtectionKeyController\n * @instance\n *\n */\n function getLicenseServerModelInstance(keySystem, protData, messageType) {\n\n // Our default server implementations do not do anything with \"license-release\" or\n // \"individualization-request\" messages, so we just send a success event\n if (messageType === 'license-release' || messageType === 'individualization-request') {\n return null;\n }\n\n let licenseServerData = null;\n if (protData && protData.hasOwnProperty('drmtoday')) {\n licenseServerData = DRMToday(context).getInstance({BASE64: BASE64});\n } else if (keySystem.systemString === ProtectionConstants.WIDEVINE_KEYSTEM_STRING) {\n licenseServerData = Widevine(context).getInstance();\n } else if (keySystem.systemString === ProtectionConstants.PLAYREADY_KEYSTEM_STRING) {\n licenseServerData = PlayReady(context).getInstance();\n } else if (keySystem.systemString === ProtectionConstants.CLEARKEY_KEYSTEM_STRING) {\n licenseServerData = ClearKey(context).getInstance();\n }\n\n return licenseServerData;\n }\n\n /**\n * Allows application-specific retrieval of ClearKey keys.\n *\n * @param {KeySystem} clearkeyKeySystem They exact ClearKey System to be used\n * @param {ProtectionData} protData protection data to use for the\n * request\n * @param {ArrayBuffer} message the key message from the CDM\n * @return {ClearKeyKeySet|null} the clear keys associated with\n * the request or null if no keys can be returned by this function\n * @memberof module:ProtectionKeyController\n * @instance\n */\n function processClearKeyLicenseRequest(clearkeyKeySystem, protData, message) {\n try {\n return clearkeyKeySystem.getClearKeysFromProtectionData(protData, message);\n } catch (error) {\n logger.error('Failed to retrieve clearkeys from ProtectionData');\n return null;\n }\n }\n\n function setProtectionData(protectionDataSet) {\n var getProtectionData = function (keySystemString) {\n var protData = null;\n if (protectionDataSet) {\n protData = (keySystemString in protectionDataSet) ? protectionDataSet[keySystemString] : null;\n }\n return protData;\n };\n\n for (var i = 0; i < keySystems.length; i++) {\n var keySystem = keySystems[i];\n if (keySystem.hasOwnProperty('init')) {\n keySystem.init(getProtectionData(keySystem.systemString));\n }\n }\n }\n\n function _getProtDataForKeySystem(systemString, protDataSet) {\n if (!protDataSet) return null;\n return (systemString in protDataSet) ? protDataSet[systemString] : null;\n }\n\n function _getSessionId(protData, cp) {\n // Get sessionId from protectionData or from manifest (ContentProtection)\n if (protData && protData.sessionId) {\n return protData.sessionId;\n } else if (cp && cp.sessionId) {\n return cp.sessionId;\n }\n return null;\n }\n\n function _getSessionType(protData, sessionType) {\n return (protData && protData.sessionType) ? protData.sessionType : sessionType;\n }\n\n instance = {\n initialize,\n setProtectionData,\n isClearKey,\n initDataEquals,\n getKeySystems,\n setKeySystems,\n getKeySystemBySystemString,\n getSupportedKeySystemsFromContentProtection,\n getSupportedKeySystemsFromSegmentPssh,\n getLicenseServerModelInstance,\n processClearKeyLicenseRequest,\n setConfig\n };\n\n return instance;\n}\n\nProtectionKeyController.__dashjs_factory_name = 'ProtectionKeyController';\nexport default dashjs.FactoryMaker.getSingletonFactory(ProtectionKeyController); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport EventsBase from '../../core/events/EventsBase';\n/**\n * @class\n */\nclass ProtectionEvents extends EventsBase {\n /**\n * @description Public facing external events to be used when including protection package.\n * All public events will be aggregated into the MediaPlayerEvents Class and can be accessed\n * via MediaPlayer.events. public_ is the prefix that we use to move event names to MediaPlayerEvents.\n */\n constructor () {\n super();\n\n /**\n * Event ID for events delivered when the protection set receives\n * a key message from the CDM\n *\n * @ignore\n */\n this.INTERNAL_KEY_MESSAGE = 'internalKeyMessage';\n\n /**\n * Event ID for events delivered when the status of one decryption keys has changed\n * @ignore\n */\n this.INTERNAL_KEY_STATUS_CHANGED = 'internalkeyStatusChanged';\n\n /**\n * Event ID for events delivered when a new key has been added\n *\n * @constant\n * @deprecated The latest versions of the EME specification no longer\n * use this event. {@MediaPlayer.models.protectionModel.eventList.KEY_STATUSES_CHANGED}\n * is preferred.\n * @event ProtectionEvents#KEY_ADDED\n */\n this.KEY_ADDED = 'public_keyAdded';\n /**\n * Event ID for events delivered when an error is encountered by the CDM\n * while processing a license server response message\n * @event ProtectionEvents#KEY_ERROR\n */\n this.KEY_ERROR = 'public_keyError';\n\n /**\n * Event ID for events delivered when the protection set receives\n * a key message from the CDM\n * @event ProtectionEvents#KEY_MESSAGE\n */\n this.KEY_MESSAGE = 'public_keyMessage';\n\n /**\n * Event ID for events delivered when a key session close\n * process has completed\n * @event ProtectionEvents#KEY_SESSION_CLOSED\n */\n this.KEY_SESSION_CLOSED = 'public_keySessionClosed';\n\n /**\n * Event ID for events delivered when a new key sessions creation\n * process has completed\n * @event ProtectionEvents#KEY_SESSION_CREATED\n */\n this.KEY_SESSION_CREATED = 'public_keySessionCreated';\n\n /**\n * Event ID for events delivered when a key session removal\n * process has completed\n * @event ProtectionEvents#KEY_SESSION_REMOVED\n */\n this.KEY_SESSION_REMOVED = 'public_keySessionRemoved';\n\n /**\n * Event ID for events delivered when the status of one or more\n * decryption keys has changed\n * @event ProtectionEvents#KEY_STATUSES_CHANGED\n */\n this.KEY_STATUSES_CHANGED = 'public_keyStatusesChanged';\n\n /**\n * Event ID for events delivered when a key system access procedure\n * has completed\n * @ignore\n */\n this.KEY_SYSTEM_ACCESS_COMPLETE = 'public_keySystemAccessComplete';\n\n /**\n * Event ID for events delivered when a key system selection procedure\n * completes\n * @event ProtectionEvents#KEY_SYSTEM_SELECTED\n */\n this.KEY_SYSTEM_SELECTED = 'public_keySystemSelected';\n\n /**\n * Event ID for events delivered when a license request procedure\n * has completed\n * @event ProtectionEvents#LICENSE_REQUEST_COMPLETE\n */\n this.LICENSE_REQUEST_COMPLETE = 'public_licenseRequestComplete';\n\n /**\n * Sending a license rquest\n * @event ProtectionEvents#LICENSE_REQUEST_SENDING\n */\n this.LICENSE_REQUEST_SENDING = 'public_licenseRequestSending';\n\n /**\n * Event ID for needkey/encrypted events\n * @ignore\n */\n this.NEED_KEY = 'needkey';\n\n /**\n * Event ID for events delivered when the Protection system is detected and created.\n * @event ProtectionEvents#PROTECTION_CREATED\n */\n this.PROTECTION_CREATED = 'public_protectioncreated';\n\n /**\n * Event ID for events delivered when the Protection system is destroyed.\n * @event ProtectionEvents#PROTECTION_DESTROYED\n */\n this.PROTECTION_DESTROYED = 'public_protectiondestroyed';\n\n /**\n * Event ID for events delivered when a new server certificate has\n * been delivered to the CDM\n * @ignore\n */\n this.SERVER_CERTIFICATE_UPDATED = 'serverCertificateUpdated';\n\n /**\n * Event ID for events delivered when the process of shutting down\n * a protection set has completed\n * @ignore\n */\n this.TEARDOWN_COMPLETE = 'protectionTeardownComplete';\n\n /**\n * Event ID for events delivered when a HTMLMediaElement has been\n * associated with the protection set\n * @ignore\n */\n this.VIDEO_ELEMENT_SELECTED = 'videoElementSelected';\n\n /**\n * Triggered when the key session has been updated successfully\n * @ignore\n */\n this.KEY_SESSION_UPDATED = 'public_keySessionUpdated';\n }\n}\n\nlet protectionEvents = new ProtectionEvents();\nexport default protectionEvents;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @classdesc NeedKey\n * @ignore\n */\nclass NeedKey {\n /**\n * @param {ArrayBuffer} initData the initialization data\n * @param {string} initDataType initialization data type\n * @class\n */\n constructor(initData, initDataType) {\n this.initData = initData;\n this.initDataType = initDataType;\n }\n}\n\nexport default NeedKey;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @classdesc EME-independent KeyMessage\n * @ignore\n */\nclass KeyMessage {\n /**\n * @param {SessionToken} sessionToken the session\n * to which the key message is associated\n * @param {ArrayBuffer} message the key message\n * @param {string} defaultURL license acquisition URL provided by the CDM\n * @param {string} messageType Supported message types can be found\n * {@link https://w3c.github.io/encrypted-media/#idl-def-MediaKeyMessageType|here}.\n * @class\n */\n constructor(sessionToken, message, defaultURL, messageType) {\n this.sessionToken = sessionToken;\n this.message = message;\n this.defaultURL = defaultURL;\n this.messageType = messageType ? messageType : 'license-request';\n }\n}\n\nexport default KeyMessage;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @classdesc Creates a new key system access token. Represents a valid key system for\n * given piece of content and key system requirements. Used to initialize license\n * acquisition operations.\n * @ignore\n */\nclass KeySystemAccess {\n /**\n * @param {MediaPlayer.dependencies.protection.KeySystem} keySystem the key system\n * @param {KeySystemConfiguration} ksConfiguration the\n * subset of configurations passed to the key system access request that are supported\n * by this user agent\n * @class\n * @ignore\n */\n constructor(keySystem, ksConfiguration) {\n this.keySystem = keySystem;\n this.ksConfiguration = ksConfiguration;\n }\n}\n\nexport default KeySystemAccess;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * Most recent EME implementation\n *\n * Implemented by Google Chrome v36+ (Windows, OSX, Linux)\n *\n * @implements ProtectionModel\n * @class\n */\nimport ProtectionKeyController from '../controllers/ProtectionKeyController';\nimport NeedKey from '../vo/NeedKey';\nimport ProtectionErrors from '../errors/ProtectionErrors';\nimport DashJSError from '../../vo/DashJSError';\nimport KeyMessage from '../vo/KeyMessage';\nimport KeySystemAccess from '../vo/KeySystemAccess';\nimport ProtectionConstants from '../../constants/ProtectionConstants';\n\nconst SYSTEM_STRING_PRIORITY = {};\nSYSTEM_STRING_PRIORITY[ProtectionConstants.PLAYREADY_KEYSTEM_STRING] = [ProtectionConstants.PLAYREADY_RECOMMENDATION_KEYSTEM_STRING, ProtectionConstants.PLAYREADY_KEYSTEM_STRING];\nSYSTEM_STRING_PRIORITY[ProtectionConstants.WIDEVINE_KEYSTEM_STRING] = [ProtectionConstants.WIDEVINE_KEYSTEM_STRING];\nSYSTEM_STRING_PRIORITY[ProtectionConstants.CLEARKEY_KEYSTEM_STRING] = [ProtectionConstants.CLEARKEY_KEYSTEM_STRING];\n\nfunction ProtectionModel_21Jan2015(config) {\n\n config = config || {};\n const context = this.context;\n const eventBus = config.eventBus;//Need to pass in here so we can use same instance since this is optional module\n const events = config.events;\n const debug = config.debug;\n\n let instance,\n logger,\n keySystem,\n videoElement,\n mediaKeys,\n sessions,\n eventHandler,\n protectionKeyController;\n\n function setup() {\n logger = debug.getLogger(instance);\n keySystem = null;\n videoElement = null;\n mediaKeys = null;\n sessions = [];\n protectionKeyController = ProtectionKeyController(context).getInstance();\n eventHandler = createEventHandler();\n }\n\n function reset() {\n const numSessions = sessions.length;\n let session;\n\n if (numSessions !== 0) {\n // Called when we are done closing a session. Success or fail\n const done = function (session) {\n removeSession(session);\n if (sessions.length === 0) {\n if (videoElement) {\n videoElement.removeEventListener('encrypted', eventHandler);\n videoElement.setMediaKeys(null).then(function () {\n eventBus.trigger(events.TEARDOWN_COMPLETE);\n });\n } else {\n eventBus.trigger(events.TEARDOWN_COMPLETE);\n }\n }\n };\n for (let i = 0; i < numSessions; i++) {\n session = sessions[i];\n (function (s) {\n // Override closed promise resolver\n session.session.closed.then(function () {\n done(s);\n });\n // Close the session and handle errors, otherwise promise\n // resolver above will be called\n _closeKeySessionInternal(session).catch(function () {\n done(s);\n });\n\n })(session);\n }\n } else {\n eventBus.trigger(events.TEARDOWN_COMPLETE);\n }\n }\n\n function stop() {\n // Close and remove not usable sessions\n let session;\n for (let i = 0; i < sessions.length; i++) {\n session = sessions[i];\n if (!session.getUsable()) {\n _closeKeySessionInternal(session).catch(function () {\n removeSession(session);\n });\n }\n }\n }\n\n function getAllInitData() {\n const retVal = [];\n for (let i = 0; i < sessions.length; i++) {\n if (sessions[i].initData) {\n retVal.push(sessions[i].initData);\n }\n }\n return retVal;\n }\n\n function getSessions() {\n return sessions;\n }\n\n function requestKeySystemAccess(ksConfigurations) {\n return new Promise((resolve, reject) => {\n _requestKeySystemAccessInternal(ksConfigurations, 0, resolve, reject);\n })\n }\n\n /**\n * Initializes access to a key system. Once we found a valid configuration we get a mediaKeySystemAccess object\n * @param ksConfigurations\n * @param idx\n * @param resolve\n * @param reject\n * @private\n */\n function _requestKeySystemAccessInternal(ksConfigurations, idx, resolve, reject) {\n\n // In case requestMediaKeySystemAccess is not available we can not proceed and dispatch an error\n if (navigator.requestMediaKeySystemAccess === undefined ||\n typeof navigator.requestMediaKeySystemAccess !== 'function') {\n const msg = 'Insecure origins are not allowed';\n eventBus.trigger(events.KEY_SYSTEM_ACCESS_COMPLETE, { error: msg });\n reject({ error: msg });\n return;\n }\n\n // If a systemStringPriority is defined by the application we use these values. Otherwise we use the default system string\n // This is useful for DRM systems such as Playready for which multiple system strings are possible for instance com.microsoft.playready and com.microsoft.playready.recommendation\n const protDataSystemStringPriority = ksConfigurations[idx].protData && ksConfigurations[idx].protData.systemStringPriority ? ksConfigurations[idx].protData.systemStringPriority : null;\n const configs = ksConfigurations[idx].configs;\n const currentKeySystem = ksConfigurations[idx].ks;\n let systemString = currentKeySystem.systemString;\n\n // Use the default values in case no values are provided by the application\n const systemStringsToApply = protDataSystemStringPriority ? protDataSystemStringPriority : SYSTEM_STRING_PRIORITY[systemString] ? SYSTEM_STRING_PRIORITY[systemString] : [systemString];\n\n // Check all the available system strings and the available configurations for support\n _checkAccessForKeySystem(systemStringsToApply, configs)\n .then((mediaKeySystemAccess) => {\n const configuration = (typeof mediaKeySystemAccess.getConfiguration === 'function') ?\n mediaKeySystemAccess.getConfiguration() : null;\n const keySystemAccess = new KeySystemAccess(currentKeySystem, configuration);\n\n keySystemAccess.mksa = mediaKeySystemAccess;\n eventBus.trigger(events.KEY_SYSTEM_ACCESS_COMPLETE, { data: keySystemAccess });\n resolve({ data: keySystemAccess });\n })\n .catch((e) => {\n if (idx + 1 < ksConfigurations.length) {\n _requestKeySystemAccessInternal(ksConfigurations, idx + 1, resolve, reject);\n } else {\n const errorMessage = 'Key system access denied! ';\n eventBus.trigger(events.KEY_SYSTEM_ACCESS_COMPLETE, { error: errorMessage + e.message });\n reject({ error: errorMessage + e.message });\n }\n })\n }\n\n /**\n * For a specific key system: Iterate over the possible system strings and resolve once a valid configuration was found\n * @param {array} systemStringsToApply\n * @param {object} configs\n * @return {Promise}\n * @private\n */\n function _checkAccessForKeySystem(systemStringsToApply, configs) {\n return new Promise((resolve, reject) => {\n _checkAccessForSystemStrings(systemStringsToApply, configs, 0, resolve, reject);\n })\n }\n\n /**\n * Recursively iterate over the possible system strings until a supported configuration is found or we ran out of options\n * @param {array} systemStringsToApply\n * @param {object} configs\n * @param {number} idx\n * @param {function} resolve\n * @param {function} reject\n * @private\n */\n function _checkAccessForSystemStrings(systemStringsToApply, configs, idx, resolve, reject) {\n const systemString = systemStringsToApply[idx];\n\n logger.debug(`Requesting key system access for system string ${systemString}`);\n\n navigator.requestMediaKeySystemAccess(systemString, configs)\n .then((mediaKeySystemAccess) => {\n mediaKeySystemAccess.selectedSystemString = systemString;\n resolve(mediaKeySystemAccess);\n })\n .catch((e) => {\n if (idx + 1 < systemStringsToApply.length) {\n _checkAccessForSystemStrings(systemStringsToApply, configs, idx + 1, resolve, reject);\n } else {\n reject(e);\n }\n });\n }\n\n /**\n * Selects a key system by creating the mediaKeys and adding them to the video element\n * @param keySystemAccess\n * @return {Promise<unknown>}\n */\n function selectKeySystem(keySystemAccess) {\n return new Promise((resolve, reject) => {\n keySystemAccess.mksa.createMediaKeys()\n .then((mkeys) => {\n keySystem = keySystemAccess.keySystem;\n mediaKeys = mkeys;\n if (videoElement) {\n return videoElement.setMediaKeys(mediaKeys)\n } else {\n return Promise.resolve();\n }\n })\n .then(() => {\n resolve(keySystem);\n })\n .catch(function () {\n reject({ error: 'Error selecting keys system (' + keySystemAccess.keySystem.systemString + ')! Could not create MediaKeys -- TODO' });\n });\n })\n }\n\n function setMediaElement(mediaElement) {\n if (videoElement === mediaElement)\n return;\n\n // Replacing the previous element\n if (videoElement) {\n videoElement.removeEventListener('encrypted', eventHandler);\n if (videoElement.setMediaKeys) {\n videoElement.setMediaKeys(null);\n }\n }\n\n videoElement = mediaElement;\n\n // Only if we are not detaching from the existing element\n if (videoElement) {\n videoElement.addEventListener('encrypted', eventHandler);\n if (videoElement.setMediaKeys && mediaKeys) {\n videoElement.setMediaKeys(mediaKeys);\n }\n }\n }\n\n function setServerCertificate(serverCertificate) {\n if (!keySystem || !mediaKeys) {\n throw new Error('Can not set server certificate until you have selected a key system');\n }\n mediaKeys.setServerCertificate(serverCertificate).then(function () {\n logger.info('DRM: License server certificate successfully updated.');\n eventBus.trigger(events.SERVER_CERTIFICATE_UPDATED);\n }).catch(function (error) {\n eventBus.trigger(events.SERVER_CERTIFICATE_UPDATED, { error: new DashJSError(ProtectionErrors.SERVER_CERTIFICATE_UPDATED_ERROR_CODE, ProtectionErrors.SERVER_CERTIFICATE_UPDATED_ERROR_MESSAGE + error.name) });\n });\n }\n\n /**\n * Create a key session, a session token and initialize a request by calling generateRequest\n * @param ksInfo\n */\n function createKeySession(ksInfo) {\n if (!keySystem || !mediaKeys) {\n throw new Error('Can not create sessions until you have selected a key system');\n }\n\n const session = mediaKeys.createSession(ksInfo.sessionType);\n const sessionToken = createSessionToken(session, ksInfo);\n\n\n // The \"keyids\" type is used for Clearkey when keys are provided directly in the protection data and a request to a license server is not needed\n const dataType = keySystem.systemString === ProtectionConstants.CLEARKEY_KEYSTEM_STRING && (ksInfo.initData || (ksInfo.protData && ksInfo.protData.clearkeys)) ? ProtectionConstants.INITIALIZATION_DATA_TYPE_KEYIDS : ProtectionConstants.INITIALIZATION_DATA_TYPE_CENC;\n\n session.generateRequest(dataType, ksInfo.initData).then(function () {\n logger.debug('DRM: Session created. SessionID = ' + sessionToken.getSessionId());\n eventBus.trigger(events.KEY_SESSION_CREATED, { data: sessionToken });\n }).catch(function (error) {\n removeSession(sessionToken);\n eventBus.trigger(events.KEY_SESSION_CREATED, {\n data: null,\n error: new DashJSError(ProtectionErrors.KEY_SESSION_CREATED_ERROR_CODE, ProtectionErrors.KEY_SESSION_CREATED_ERROR_MESSAGE + 'Error generating key request -- ' + error.name)\n });\n });\n }\n\n function updateKeySession(sessionToken, message) {\n const session = sessionToken.session;\n\n // Send our request to the key session\n if (protectionKeyController.isClearKey(keySystem)) {\n message = message.toJWK();\n }\n session.update(message)\n .then(() => {\n eventBus.trigger(events.KEY_SESSION_UPDATED);\n })\n .catch(function (error) {\n eventBus.trigger(events.KEY_ERROR, { error: new DashJSError(ProtectionErrors.MEDIA_KEYERR_CODE, 'Error sending update() message! ' + error.name, sessionToken) });\n });\n }\n\n function loadKeySession(ksInfo) {\n if (!keySystem || !mediaKeys) {\n throw new Error('Can not load sessions until you have selected a key system');\n }\n\n const sessionId = ksInfo.sessionId;\n\n // Check if session Id is not already loaded or loading\n for (let i = 0; i < sessions.length; i++) {\n if (sessionId === sessions[i].sessionId) {\n logger.warn('DRM: Ignoring session ID because we have already seen it!');\n return;\n }\n }\n\n const session = mediaKeys.createSession(ksInfo.sessionType);\n const sessionToken = createSessionToken(session, ksInfo);\n\n // Load persisted session data into our newly created session object\n session.load(sessionId).then(function (success) {\n if (success) {\n logger.debug('DRM: Session loaded. SessionID = ' + sessionToken.getSessionId());\n eventBus.trigger(events.KEY_SESSION_CREATED, { data: sessionToken });\n } else {\n removeSession(sessionToken);\n eventBus.trigger(events.KEY_SESSION_CREATED, {\n data: null,\n error: new DashJSError(ProtectionErrors.KEY_SESSION_CREATED_ERROR_CODE, ProtectionErrors.KEY_SESSION_CREATED_ERROR_MESSAGE + 'Could not load session! Invalid Session ID (' + sessionId + ')')\n });\n }\n }).catch(function (error) {\n removeSession(sessionToken);\n eventBus.trigger(events.KEY_SESSION_CREATED, {\n data: null,\n error: new DashJSError(ProtectionErrors.KEY_SESSION_CREATED_ERROR_CODE, ProtectionErrors.KEY_SESSION_CREATED_ERROR_MESSAGE + 'Could not load session (' + sessionId + ')! ' + error.name)\n });\n });\n }\n\n function removeKeySession(sessionToken) {\n const session = sessionToken.session;\n\n session.remove().then(function () {\n logger.debug('DRM: Session removed. SessionID = ' + sessionToken.getSessionId());\n eventBus.trigger(events.KEY_SESSION_REMOVED, { data: sessionToken.getSessionId() });\n }, function (error) {\n eventBus.trigger(events.KEY_SESSION_REMOVED, {\n data: null,\n error: 'Error removing session (' + sessionToken.getSessionId() + '). ' + error.name\n });\n\n });\n }\n\n function closeKeySession(sessionToken) {\n // Send our request to the key session\n _closeKeySessionInternal(sessionToken).catch(function (error) {\n removeSession(sessionToken);\n eventBus.trigger(events.KEY_SESSION_CLOSED, {\n data: null,\n error: 'Error closing session (' + sessionToken.getSessionId() + ') ' + error.name\n });\n });\n }\n\n function _closeKeySessionInternal(sessionToken) {\n const session = sessionToken.session;\n\n // Remove event listeners\n session.removeEventListener('keystatuseschange', sessionToken);\n session.removeEventListener('message', sessionToken);\n\n // Send our request to the key session\n return session.close();\n }\n\n // This is our main event handler for all desired HTMLMediaElement events\n // related to EME. These events are translated into our API-independent\n // versions of the same events\n function createEventHandler() {\n return {\n handleEvent: function (event) {\n switch (event.type) {\n case 'encrypted':\n if (event.initData) {\n let initData = ArrayBuffer.isView(event.initData) ? event.initData.buffer : event.initData;\n eventBus.trigger(events.NEED_KEY, { key: new NeedKey(initData, event.initDataType) });\n }\n break;\n }\n }\n };\n }\n\n function removeSession(token) {\n // Remove from our session list\n for (let i = 0; i < sessions.length; i++) {\n if (sessions[i] === token) {\n sessions.splice(i, 1);\n break;\n }\n }\n }\n\n function parseKeyStatus(args) {\n // Edge and Chrome implement different version of keystatues, param are not on same order\n let status, keyId;\n if (args && args.length > 0) {\n if (args[0]) {\n if (typeof args[0] === 'string') {\n status = args[0];\n } else {\n keyId = args[0];\n }\n }\n\n if (args[1]) {\n if (typeof args[1] === 'string') {\n status = args[1];\n } else {\n keyId = args[1];\n }\n }\n }\n return {\n status: status,\n keyId: keyId\n };\n }\n\n // Function to create our session token objects which manage the EME\n // MediaKeySession and session-specific event handler\n function createSessionToken(session, ksInfo) {\n const token = { // Implements SessionToken\n session: session,\n keyId: ksInfo.keyId,\n initData: ksInfo.initData,\n sessionId: ksInfo.sessionId,\n sessionType: ksInfo.sessionType,\n\n // This is our main event handler for all desired MediaKeySession events\n // These events are translated into our API-independent versions of the\n // same events\n handleEvent: function (event) {\n switch (event.type) {\n case 'keystatuseschange':\n eventBus.trigger(events.KEY_STATUSES_CHANGED, { data: this });\n event.target.keyStatuses.forEach(function () {\n let keyStatus = parseKeyStatus(arguments);\n switch (keyStatus.status) {\n case 'expired':\n eventBus.trigger(events.INTERNAL_KEY_STATUS_CHANGED, { error: new DashJSError(ProtectionErrors.KEY_STATUS_CHANGED_EXPIRED_ERROR_CODE, ProtectionErrors.KEY_STATUS_CHANGED_EXPIRED_ERROR_MESSAGE) });\n break;\n default:\n eventBus.trigger(events.INTERNAL_KEY_STATUS_CHANGED, keyStatus);\n break;\n }\n });\n break;\n\n case 'message':\n let message = ArrayBuffer.isView(event.message) ? event.message.buffer : event.message;\n eventBus.trigger(events.INTERNAL_KEY_MESSAGE, { data: new KeyMessage(this, message, undefined, event.messageType) });\n break;\n }\n },\n\n getKeyId: function () {\n return this.keyId;\n },\n\n getSessionId: function () {\n return session.sessionId;\n },\n\n getSessionType: function () {\n return this.sessionType;\n },\n\n getExpirationTime: function () {\n return session.expiration;\n },\n\n getKeyStatuses: function () {\n return session.keyStatuses;\n },\n\n getUsable: function () {\n let usable = false;\n session.keyStatuses.forEach(function () {\n let keyStatus = parseKeyStatus(arguments);\n if (keyStatus.status === 'usable') {\n usable = true;\n }\n });\n return usable;\n }\n };\n\n // Add all event listeners\n session.addEventListener('keystatuseschange', token);\n session.addEventListener('message', token);\n\n // Register callback for session closed Promise\n session.closed.then(() => {\n removeSession(token);\n logger.debug('DRM: Session closed. SessionID = ' + token.getSessionId());\n eventBus.trigger(events.KEY_SESSION_CLOSED, { data: token.getSessionId() });\n });\n\n // Add to our session list\n sessions.push(token);\n\n return token;\n }\n\n instance = {\n getAllInitData,\n getSessions,\n requestKeySystemAccess,\n selectKeySystem,\n setMediaElement,\n setServerCertificate,\n createKeySession,\n updateKeySession,\n loadKeySession,\n removeKeySession,\n closeKeySession,\n stop,\n reset\n };\n\n setup();\n\n return instance;\n}\n\nProtectionModel_21Jan2015.__dashjs_factory_name = 'ProtectionModel_21Jan2015';\nexport default dashjs.FactoryMaker.getClassFactory(ProtectionModel_21Jan2015); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * Implementation of the EME APIs as of the 3 Feb 2014 state of the specification.\n *\n * Implemented by Internet Explorer 11 (Windows 8.1)\n *\n * @implements ProtectionModel\n * @class\n */\n\nimport ProtectionKeyController from '../controllers/ProtectionKeyController';\nimport NeedKey from '../vo/NeedKey';\nimport DashJSError from '../../vo/DashJSError';\nimport ProtectionErrors from '../errors/ProtectionErrors';\nimport KeyMessage from '../vo/KeyMessage';\nimport KeySystemConfiguration from '../vo/KeySystemConfiguration';\nimport KeySystemAccess from '../vo/KeySystemAccess';\n\nfunction ProtectionModel_3Feb2014(config) {\n\n config = config || {};\n const context = this.context;\n const eventBus = config.eventBus;//Need to pass in here so we can use same instance since this is optional module\n const events = config.events;\n const debug = config.debug;\n const api = config.api;\n\n let instance,\n logger,\n videoElement,\n keySystem,\n mediaKeys,\n keySystemAccess,\n sessions,\n eventHandler,\n protectionKeyController;\n\n function setup() {\n logger = debug.getLogger(instance);\n videoElement = null;\n keySystem = null;\n mediaKeys = null;\n keySystemAccess = null;\n sessions = [];\n protectionKeyController = ProtectionKeyController(context).getInstance();\n eventHandler = createEventHandler();\n }\n\n function reset() {\n try {\n for (let i = 0; i < sessions.length; i++) {\n closeKeySession(sessions[i]);\n }\n if (videoElement) {\n videoElement.removeEventListener(api.needkey, eventHandler);\n }\n eventBus.trigger(events.TEARDOWN_COMPLETE);\n } catch (error) {\n eventBus.trigger(events.TEARDOWN_COMPLETE, { error: 'Error tearing down key sessions and MediaKeys! -- ' + error.message });\n }\n }\n\n function getAllInitData() {\n const retVal = [];\n for (let i = 0; i < sessions.length; i++) {\n retVal.push(sessions[i].initData);\n }\n return retVal;\n }\n\n function getSessions() {\n return sessions;\n }\n\n function requestKeySystemAccess(ksConfigurations) {\n return new Promise((resolve, reject) => {\n // Try key systems in order, first one with supported key system configuration\n // is used\n let found = false;\n for (let ksIdx = 0; ksIdx < ksConfigurations.length; ksIdx++) {\n const systemString = ksConfigurations[ksIdx].ks.systemString;\n const configs = ksConfigurations[ksIdx].configs;\n let supportedAudio = null;\n let supportedVideo = null;\n\n // Try key system configs in order, first one with supported audio/video\n // is used\n for (let configIdx = 0; configIdx < configs.length; configIdx++) {\n const audios = configs[configIdx].audioCapabilities;\n const videos = configs[configIdx].videoCapabilities;\n\n // Look for supported audio container/codecs\n if (audios && audios.length !== 0) {\n supportedAudio = []; // Indicates that we have a requested audio config\n for (let audioIdx = 0; audioIdx < audios.length; audioIdx++) {\n if (window[api.MediaKeys].isTypeSupported(systemString, audios[audioIdx].contentType)) {\n supportedAudio.push(audios[audioIdx]);\n }\n }\n }\n\n // Look for supported video container/codecs\n if (videos && videos.length !== 0) {\n supportedVideo = []; // Indicates that we have a requested video config\n for (let videoIdx = 0; videoIdx < videos.length; videoIdx++) {\n if (window[api.MediaKeys].isTypeSupported(systemString, videos[videoIdx].contentType)) {\n supportedVideo.push(videos[videoIdx]);\n }\n }\n }\n\n // No supported audio or video in this configuration OR we have\n // requested audio or video configuration that is not supported\n if ((!supportedAudio && !supportedVideo) ||\n (supportedAudio && supportedAudio.length === 0) ||\n (supportedVideo && supportedVideo.length === 0)) {\n continue;\n }\n\n // This configuration is supported\n found = true;\n const ksConfig = new KeySystemConfiguration(supportedAudio, supportedVideo);\n const ks = protectionKeyController.getKeySystemBySystemString(systemString);\n const keySystemAccess = new KeySystemAccess(ks, ksConfig);\n eventBus.trigger(events.KEY_SYSTEM_ACCESS_COMPLETE, { data: keySystemAccess });\n resolve({ data: keySystemAccess });\n break;\n }\n }\n if (!found) {\n const errorMessage = 'Key system access denied! -- No valid audio/video content configurations detected!';\n eventBus.trigger(events.KEY_SYSTEM_ACCESS_COMPLETE, { error: errorMessage });\n reject({ error: errorMessage });\n }\n })\n }\n\n function selectKeySystem(ksAccess) {\n return new Promise((resolve, reject) => {\n try {\n mediaKeys = ksAccess.mediaKeys = new window[api.MediaKeys](ksAccess.keySystem.systemString);\n keySystem = ksAccess.keySystem;\n keySystemAccess = ksAccess;\n if (videoElement) {\n setMediaKeys();\n }\n resolve(keySystem);\n } catch (error) {\n reject({ error: 'Error selecting keys system (' + keySystem.systemString + ')! Could not create MediaKeys -- TODO' });\n }\n })\n }\n\n function setMediaElement(mediaElement) {\n if (videoElement === mediaElement)\n return;\n\n // Replacing the previous element\n if (videoElement) {\n videoElement.removeEventListener(api.needkey, eventHandler);\n }\n\n videoElement = mediaElement;\n\n // Only if we are not detaching from the existing element\n if (videoElement) {\n videoElement.addEventListener(api.needkey, eventHandler);\n if (mediaKeys) {\n setMediaKeys();\n }\n }\n }\n\n function createKeySession(ksInfo) {\n if (!keySystem || !mediaKeys || !keySystemAccess) {\n throw new Error('Can not create sessions until you have selected a key system');\n }\n\n // Use the first video capability for the contentType.\n // TODO: Not sure if there is a way to concatenate all capability data into a RFC6386-compatible format\n\n // If player is trying to playback Audio only stream - don't error out.\n let capabilities = null;\n\n if (keySystemAccess.ksConfiguration.videoCapabilities && keySystemAccess.ksConfiguration.videoCapabilities.length > 0) {\n capabilities = keySystemAccess.ksConfiguration.videoCapabilities[0];\n }\n\n if (capabilities === null && keySystemAccess.ksConfiguration.audioCapabilities && keySystemAccess.ksConfiguration.audioCapabilities.length > 0) {\n capabilities = keySystemAccess.ksConfiguration.audioCapabilities[0];\n }\n\n if (capabilities === null) {\n throw new Error('Can not create sessions for unknown content types.');\n }\n\n const contentType = capabilities.contentType;\n const session = mediaKeys.createSession(contentType, new Uint8Array(ksInfo.initData), ksInfo.cdmData ? new Uint8Array(ksInfo.cdmData) : null);\n const sessionToken = createSessionToken(session, ksInfo);\n\n // Add all event listeners\n session.addEventListener(api.error, sessionToken);\n session.addEventListener(api.message, sessionToken);\n session.addEventListener(api.ready, sessionToken);\n session.addEventListener(api.close, sessionToken);\n\n // Add to our session list\n sessions.push(sessionToken);\n logger.debug('DRM: Session created. SessionID = ' + sessionToken.getSessionId());\n eventBus.trigger(events.KEY_SESSION_CREATED, { data: sessionToken });\n }\n\n function updateKeySession(sessionToken, message) {\n const session = sessionToken.session;\n\n if (!protectionKeyController.isClearKey(keySystem)) {\n // Send our request to the key session\n session.update(new Uint8Array(message));\n } else {\n // For clearkey, message is a ClearKeyKeySet\n session.update(new Uint8Array(message.toJWK()));\n }\n eventBus.trigger(events.KEY_SESSION_UPDATED);\n }\n\n /**\n * Close the given session and release all associated keys. Following\n * this call, the sessionToken becomes invalid\n *\n * @param {Object} sessionToken - the session token\n */\n function closeKeySession(sessionToken) {\n const session = sessionToken.session;\n\n // Remove event listeners\n session.removeEventListener(api.error, sessionToken);\n session.removeEventListener(api.message, sessionToken);\n session.removeEventListener(api.ready, sessionToken);\n session.removeEventListener(api.close, sessionToken);\n\n // Remove from our session list\n for (let i = 0; i < sessions.length; i++) {\n if (sessions[i] === sessionToken) {\n sessions.splice(i, 1);\n break;\n }\n }\n\n // Send our request to the key session\n session[api.release]();\n }\n\n function setServerCertificate(/*serverCertificate*/) { /* Not supported */\n }\n\n function loadKeySession(/*ksInfo*/) { /* Not supported */\n }\n\n function removeKeySession(/*sessionToken*/) { /* Not supported */\n }\n\n\n function createEventHandler() {\n return {\n handleEvent: function (event) {\n switch (event.type) {\n\n case api.needkey:\n if (event.initData) {\n const initData = ArrayBuffer.isView(event.initData) ? event.initData.buffer : event.initData;\n eventBus.trigger(events.NEED_KEY, { key: new NeedKey(initData, 'cenc') });\n }\n break;\n }\n }\n };\n }\n\n\n // IE11 does not let you set MediaKeys until it has entered a certain\n // readyState, so we need this logic to ensure we don't set the keys\n // too early\n function setMediaKeys() {\n let boundDoSetKeys = null;\n const doSetKeys = function () {\n videoElement.removeEventListener('loadedmetadata', boundDoSetKeys);\n videoElement[api.setMediaKeys](mediaKeys);\n eventBus.trigger(events.VIDEO_ELEMENT_SELECTED);\n };\n if (videoElement.readyState >= 1) {\n doSetKeys();\n } else {\n boundDoSetKeys = doSetKeys.bind(this);\n videoElement.addEventListener('loadedmetadata', boundDoSetKeys);\n }\n\n }\n\n // Function to create our session token objects which manage the EME\n // MediaKeySession and session-specific event handler\n function createSessionToken(keySession, ksInfo) {\n return {\n // Implements SessionToken\n session: keySession,\n keyId: ksInfo.keyId,\n initData: ksInfo.initData,\n\n getKeyId: function () {\n return this.keyId;\n },\n\n getSessionId: function () {\n return this.session.sessionId;\n },\n\n getExpirationTime: function () {\n return NaN;\n },\n\n getSessionType: function () {\n return 'temporary';\n },\n\n // This is our main event handler for all desired MediaKeySession events\n // These events are translated into our API-independent versions of the\n // same events\n handleEvent: function (event) {\n switch (event.type) {\n case api.error:\n let errorStr = 'KeyError'; // TODO: Make better string from event\n eventBus.trigger(events.KEY_ERROR, { error: new DashJSError(ProtectionErrors.MEDIA_KEYERR_CODE, errorStr, this) });\n break;\n case api.message:\n let message = ArrayBuffer.isView(event.message) ? event.message.buffer : event.message;\n eventBus.trigger(events.INTERNAL_KEY_MESSAGE, { data: new KeyMessage(this, message, event.destinationURL) });\n break;\n case api.ready:\n logger.debug('DRM: Key added.');\n eventBus.trigger(events.KEY_ADDED);\n break;\n\n case api.close:\n logger.debug('DRM: Session closed. SessionID = ' + this.getSessionId());\n eventBus.trigger(events.KEY_SESSION_CLOSED, { data: this.getSessionId() });\n break;\n }\n }\n };\n }\n\n instance = {\n getAllInitData,\n getSessions,\n requestKeySystemAccess,\n selectKeySystem,\n setMediaElement,\n createKeySession,\n updateKeySession,\n closeKeySession,\n setServerCertificate,\n loadKeySession,\n removeKeySession,\n stop: reset,\n reset\n };\n\n setup();\n\n return instance;\n}\n\nProtectionModel_3Feb2014.__dashjs_factory_name = 'ProtectionModel_3Feb2014';\nexport default dashjs.FactoryMaker.getClassFactory(ProtectionModel_3Feb2014); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * Initial implementation of EME\n *\n * Implemented by Google Chrome prior to v36\n *\n * @implements ProtectionModel\n * @class\n */\nimport ProtectionKeyController from '../controllers/ProtectionKeyController';\nimport NeedKey from '../vo/NeedKey';\nimport DashJSError from '../../vo/DashJSError';\nimport KeyMessage from '../vo/KeyMessage';\nimport KeySystemConfiguration from '../vo/KeySystemConfiguration';\nimport KeySystemAccess from '../vo/KeySystemAccess';\nimport ProtectionErrors from '../errors/ProtectionErrors';\n\nfunction ProtectionModel_01b(config) {\n\n config = config || {};\n const context = this.context;\n const eventBus = config.eventBus;//Need to pass in here so we can use same instance since this is optional module\n const events = config.events;\n const debug = config.debug;\n const api = config.api;\n const errHandler = config.errHandler;\n\n let instance,\n logger,\n videoElement,\n keySystem,\n protectionKeyController,\n\n // With this version of the EME APIs, sessionIds are not assigned to\n // sessions until the first key message is received. We are assuming\n // that in the case of multiple sessions, key messages will be received\n // in the order that generateKeyRequest() is called.\n // Holding spot for newly-created sessions until we determine whether or\n // not the CDM supports sessionIds\n pendingSessions,\n\n // List of sessions that have been initialized. Only the first position will\n // be used in the case that the CDM does not support sessionIds\n sessions,\n\n // Not all CDMs support the notion of sessionIds. Without sessionIds\n // there is no way for us to differentiate between sessions, therefore\n // we must only allow a single session. Once we receive the first key\n // message we can set this flag to determine if more sessions are allowed\n moreSessionsAllowed,\n\n // This is our main event handler for all desired HTMLMediaElement events\n // related to EME. These events are translated into our API-independent\n // versions of the same events\n eventHandler;\n\n function setup() {\n logger = debug.getLogger(instance);\n videoElement = null;\n keySystem = null;\n pendingSessions = [];\n sessions = [];\n protectionKeyController = ProtectionKeyController(context).getInstance();\n eventHandler = createEventHandler();\n }\n\n function reset() {\n if (videoElement) {\n removeEventListeners();\n }\n for (let i = 0; i < sessions.length; i++) {\n closeKeySession(sessions[i]);\n }\n eventBus.trigger(events.TEARDOWN_COMPLETE);\n }\n\n function getAllInitData() {\n const retVal = [];\n for (let i = 0; i < pendingSessions.length; i++) {\n retVal.push(pendingSessions[i].initData);\n }\n for (let i = 0; i < sessions.length; i++) {\n retVal.push(sessions[i].initData);\n }\n return retVal;\n }\n\n function getSessions() {\n return sessions.concat(pendingSessions);\n }\n\n function requestKeySystemAccess(ksConfigurations) {\n return new Promise((resolve, reject) => {\n let ve = videoElement;\n if (!ve) { // Must have a video element to do this capability tests\n ve = document.createElement('video');\n }\n\n // Try key systems in order, first one with supported key system configuration\n // is used\n let found = false;\n for (let ksIdx = 0; ksIdx < ksConfigurations.length; ksIdx++) {\n const systemString = ksConfigurations[ksIdx].ks.systemString;\n const configs = ksConfigurations[ksIdx].configs;\n let supportedAudio = null;\n let supportedVideo = null;\n\n // Try key system configs in order, first one with supported audio/video\n // is used\n for (let configIdx = 0; configIdx < configs.length; configIdx++) {\n //let audios = configs[configIdx].audioCapabilities;\n const videos = configs[configIdx].videoCapabilities;\n // Look for supported video container/codecs\n if (videos && videos.length !== 0) {\n supportedVideo = []; // Indicates that we have a requested video config\n for (let videoIdx = 0; videoIdx < videos.length; videoIdx++) {\n if (ve.canPlayType(videos[videoIdx].contentType, systemString) !== '') {\n supportedVideo.push(videos[videoIdx]);\n }\n }\n }\n\n // No supported audio or video in this configuration OR we have\n // requested audio or video configuration that is not supported\n if ((!supportedAudio && !supportedVideo) ||\n (supportedAudio && supportedAudio.length === 0) ||\n (supportedVideo && supportedVideo.length === 0)) {\n continue;\n }\n\n // This configuration is supported\n found = true;\n const ksConfig = new KeySystemConfiguration(supportedAudio, supportedVideo);\n const ks = protectionKeyController.getKeySystemBySystemString(systemString);\n const keySystemAccess = new KeySystemAccess(ks, ksConfig)\n eventBus.trigger(events.KEY_SYSTEM_ACCESS_COMPLETE, { data: keySystemAccess });\n resolve({ data: keySystemAccess });\n break;\n }\n }\n if (!found) {\n const errorMessage = 'Key system access denied! -- No valid audio/video content configurations detected!';\n eventBus.trigger(events.KEY_SYSTEM_ACCESS_COMPLETE, { error: errorMessage });\n reject({ error: errorMessage });\n }\n })\n\n }\n\n function selectKeySystem(keySystemAccess) {\n keySystem = keySystemAccess.keySystem;\n return Promise.resolve(keySystem);\n }\n\n function setMediaElement(mediaElement) {\n if (videoElement === mediaElement) {\n return;\n }\n\n // Replacing the previous element\n if (videoElement) {\n removeEventListeners();\n\n // Close any open sessions - avoids memory leak on LG webOS 2016/2017 TVs\n for (var i = 0; i < sessions.length; i++) {\n closeKeySession(sessions[i]);\n }\n sessions = [];\n }\n\n videoElement = mediaElement;\n\n // Only if we are not detaching from the existing element\n if (videoElement) {\n videoElement.addEventListener(api.keyerror, eventHandler);\n videoElement.addEventListener(api.needkey, eventHandler);\n videoElement.addEventListener(api.keymessage, eventHandler);\n videoElement.addEventListener(api.keyadded, eventHandler);\n eventBus.trigger(events.VIDEO_ELEMENT_SELECTED);\n }\n }\n\n function createKeySession(ksInfo) {\n if (!keySystem) {\n throw new Error('Can not create sessions until you have selected a key system');\n }\n\n // Determine if creating a new session is allowed\n if (moreSessionsAllowed || sessions.length === 0) {\n const newSession = { // Implements SessionToken\n sessionId: null,\n keyId: ksInfo.keyId,\n initData: ksInfo.initData,\n\n getKeyId: function () {\n return this.keyId;\n },\n\n getSessionId: function () {\n return this.sessionId;\n },\n\n getExpirationTime: function () {\n return NaN;\n },\n\n getSessionType: function () {\n return 'temporary';\n }\n };\n pendingSessions.push(newSession);\n\n // Send our request to the CDM\n videoElement[api.generateKeyRequest](keySystem.systemString, new Uint8Array(ksInfo.initData));\n\n return newSession;\n\n } else {\n throw new Error('Multiple sessions not allowed!');\n }\n\n }\n\n function updateKeySession(sessionToken, message) {\n const sessionId = sessionToken.sessionId;\n if (!protectionKeyController.isClearKey(keySystem)) {\n // Send our request to the CDM\n videoElement[api.addKey](keySystem.systemString,\n new Uint8Array(message), new Uint8Array(sessionToken.initData), sessionId);\n } else {\n // For clearkey, message is a ClearKeyKeySet\n for (let i = 0; i < message.keyPairs.length; i++) {\n videoElement[api.addKey](keySystem.systemString,\n message.keyPairs[i].key, message.keyPairs[i].keyID, sessionId);\n }\n }\n eventBus.trigger(events.KEY_SESSION_UPDATED);\n }\n\n function closeKeySession(sessionToken) {\n // Send our request to the CDM\n try {\n videoElement[api.cancelKeyRequest](keySystem.systemString, sessionToken.sessionId);\n } catch (error) {\n eventBus.trigger(events.KEY_SESSION_CLOSED, {\n data: null,\n error: 'Error closing session (' + sessionToken.sessionId + ') ' + error.message\n });\n }\n }\n\n function setServerCertificate(/*serverCertificate*/) { /* Not supported */\n }\n\n function loadKeySession(/*ksInfo*/) { /* Not supported */\n }\n\n function removeKeySession(/*sessionToken*/) { /* Not supported */\n }\n\n function createEventHandler() {\n return {\n handleEvent: function (event) {\n let sessionToken = null;\n switch (event.type) {\n case api.needkey:\n let initData = ArrayBuffer.isView(event.initData) ? event.initData.buffer : event.initData;\n eventBus.trigger(events.NEED_KEY, { key: new NeedKey(initData, 'cenc') });\n break;\n\n case api.keyerror:\n sessionToken = findSessionByID(sessions, event.sessionId);\n if (!sessionToken) {\n sessionToken = findSessionByID(pendingSessions, event.sessionId);\n }\n\n if (sessionToken) {\n let code = ProtectionErrors.MEDIA_KEYERR_CODE;\n let msg = '';\n switch (event.errorCode.code) {\n case 1:\n code = ProtectionErrors.MEDIA_KEYERR_UNKNOWN_CODE;\n msg += 'MEDIA_KEYERR_UNKNOWN - ' + ProtectionErrors.MEDIA_KEYERR_UNKNOWN_MESSAGE;\n break;\n case 2:\n code = ProtectionErrors.MEDIA_KEYERR_CLIENT_CODE;\n msg += 'MEDIA_KEYERR_CLIENT - ' + ProtectionErrors.MEDIA_KEYERR_CLIENT_MESSAGE;\n break;\n case 3:\n code = ProtectionErrors.MEDIA_KEYERR_SERVICE_CODE;\n msg += 'MEDIA_KEYERR_SERVICE - ' + ProtectionErrors.MEDIA_KEYERR_SERVICE_MESSAGE;\n break;\n case 4:\n code = ProtectionErrors.MEDIA_KEYERR_OUTPUT_CODE;\n msg += 'MEDIA_KEYERR_OUTPUT - ' + ProtectionErrors.MEDIA_KEYERR_OUTPUT_MESSAGE;\n break;\n case 5:\n code = ProtectionErrors.MEDIA_KEYERR_HARDWARECHANGE_CODE;\n msg += 'MEDIA_KEYERR_HARDWARECHANGE - ' + ProtectionErrors.MEDIA_KEYERR_HARDWARECHANGE_MESSAGE;\n break;\n case 6:\n code = ProtectionErrors.MEDIA_KEYERR_DOMAIN_CODE;\n msg += 'MEDIA_KEYERR_DOMAIN - ' + ProtectionErrors.MEDIA_KEYERR_DOMAIN_MESSAGE;\n break;\n }\n msg += ' System Code = ' + event.systemCode;\n // TODO: Build error string based on key error\n eventBus.trigger(events.KEY_ERROR, { error: new DashJSError(code, msg, sessionToken) });\n } else {\n logger.error('No session token found for key error');\n }\n break;\n\n case api.keyadded:\n sessionToken = findSessionByID(sessions, event.sessionId);\n if (!sessionToken) {\n sessionToken = findSessionByID(pendingSessions, event.sessionId);\n }\n\n if (sessionToken) {\n logger.debug('DRM: Key added.');\n eventBus.trigger(events.KEY_ADDED, { data: sessionToken });//TODO not sure anything is using sessionToken? why there?\n } else {\n logger.debug('No session token found for key added');\n }\n break;\n\n case api.keymessage:\n // If this CDM does not support session IDs, we will be limited\n // to a single session\n moreSessionsAllowed = (event.sessionId !== null) && (event.sessionId !== undefined);\n\n // SessionIDs supported\n if (moreSessionsAllowed) {\n // Attempt to find an uninitialized token with this sessionId\n sessionToken = findSessionByID(sessions, event.sessionId);\n if (!sessionToken && pendingSessions.length > 0) {\n\n // This is the first message for our latest session, so set the\n // sessionId and add it to our list\n sessionToken = pendingSessions.shift();\n sessions.push(sessionToken);\n sessionToken.sessionId = event.sessionId;\n\n eventBus.trigger(events.KEY_SESSION_CREATED, { data: sessionToken });\n }\n } else if (pendingSessions.length > 0) { // SessionIDs not supported\n sessionToken = pendingSessions.shift();\n sessions.push(sessionToken);\n\n if (pendingSessions.length !== 0) {\n errHandler.error(new DashJSError(ProtectionErrors.MEDIA_KEY_MESSAGE_ERROR_CODE, ProtectionErrors.MEDIA_KEY_MESSAGE_ERROR_MESSAGE));\n }\n }\n\n if (sessionToken) {\n let message = ArrayBuffer.isView(event.message) ? event.message.buffer : event.message;\n\n // For ClearKey, the spec mandates that you pass this message to the\n // addKey method, so we always save it to the token since there is no\n // way to tell which key system is in use\n sessionToken.keyMessage = message;\n eventBus.trigger(events.INTERNAL_KEY_MESSAGE, { data: new KeyMessage(sessionToken, message, event.defaultURL) });\n\n } else {\n logger.warn('No session token found for key message');\n }\n break;\n }\n }\n };\n }\n\n\n /**\n * Helper function to retrieve the stored session token based on a given\n * sessionId value\n *\n * @param {Array} sessionArray - the array of sessions to search\n * @param {*} sessionId - the sessionId to search for\n * @returns {*} the session token with the given sessionId\n */\n function findSessionByID(sessionArray, sessionId) {\n if (!sessionId || !sessionArray) {\n return null;\n } else {\n const len = sessionArray.length;\n for (let i = 0; i < len; i++) {\n if (sessionArray[i].sessionId == sessionId) {\n return sessionArray[i];\n }\n }\n return null;\n }\n }\n\n function removeEventListeners() {\n videoElement.removeEventListener(api.keyerror, eventHandler);\n videoElement.removeEventListener(api.needkey, eventHandler);\n videoElement.removeEventListener(api.keymessage, eventHandler);\n videoElement.removeEventListener(api.keyadded, eventHandler);\n }\n\n instance = {\n getAllInitData,\n getSessions,\n requestKeySystemAccess,\n selectKeySystem,\n setMediaElement,\n createKeySession,\n updateKeySession,\n closeKeySession,\n setServerCertificate,\n loadKeySession,\n removeKeySession,\n stop: reset,\n reset\n };\n\n setup();\n\n return instance;\n}\n\nProtectionModel_01b.__dashjs_factory_name = 'ProtectionModel_01b';\nexport default dashjs.FactoryMaker.getClassFactory(ProtectionModel_01b); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\nimport ProtectionController from './controllers/ProtectionController';\nimport ProtectionKeyController from './controllers/ProtectionKeyController';\nimport ProtectionEvents from './ProtectionEvents';\nimport ProtectionErrors from './errors/ProtectionErrors';\nimport ProtectionModel_21Jan2015 from './models/ProtectionModel_21Jan2015';\nimport ProtectionModel_3Feb2014 from './models/ProtectionModel_3Feb2014';\nimport ProtectionModel_01b from './models/ProtectionModel_01b';\n\nconst APIS_ProtectionModel_01b = [\n // Un-prefixed as per spec\n {\n // Video Element\n generateKeyRequest: 'generateKeyRequest',\n addKey: 'addKey',\n cancelKeyRequest: 'cancelKeyRequest',\n\n // Events\n needkey: 'needkey',\n keyerror: 'keyerror',\n keyadded: 'keyadded',\n keymessage: 'keymessage'\n },\n // Webkit-prefixed (early Chrome versions and Chrome with EME disabled in chrome://flags)\n {\n // Video Element\n generateKeyRequest: 'webkitGenerateKeyRequest',\n addKey: 'webkitAddKey',\n cancelKeyRequest: 'webkitCancelKeyRequest',\n\n // Events\n needkey: 'webkitneedkey',\n keyerror: 'webkitkeyerror',\n keyadded: 'webkitkeyadded',\n keymessage: 'webkitkeymessage'\n }\n];\n\nconst APIS_ProtectionModel_3Feb2014 = [\n // Un-prefixed as per spec\n // Chrome 38-39 (and some earlier versions) with chrome://flags -- Enable Encrypted Media Extensions\n {\n // Video Element\n setMediaKeys: 'setMediaKeys',\n // MediaKeys\n MediaKeys: 'MediaKeys',\n // MediaKeySession\n release: 'close',\n\n // Events\n needkey: 'needkey',\n error: 'keyerror',\n message: 'keymessage',\n ready: 'keyadded',\n close: 'keyclose'\n },\n // MS-prefixed (IE11, Windows 8.1)\n {\n // Video Element\n setMediaKeys: 'msSetMediaKeys',\n // MediaKeys\n MediaKeys: 'MSMediaKeys',\n // MediaKeySession\n release: 'close',\n // Events\n needkey: 'msneedkey',\n error: 'mskeyerror',\n message: 'mskeymessage',\n ready: 'mskeyadded',\n close: 'mskeyclose'\n }\n];\n\nfunction Protection() {\n let instance;\n const context = this.context;\n\n /**\n * Create a ProtectionController and associated ProtectionModel for use with\n * a single piece of content.\n *\n * @param {Object} config\n * @return {ProtectionController} protection controller\n *\n */\n function createProtectionSystem(config) {\n let controller = null;\n\n const protectionKeyController = ProtectionKeyController(context).getInstance();\n protectionKeyController.setConfig({ debug: config.debug, BASE64: config.BASE64 });\n protectionKeyController.initialize();\n\n let protectionModel = _getProtectionModel(config);\n\n if (!controller && protectionModel) {//TODO add ability to set external controller if still needed at all?\n controller = ProtectionController(context).create({\n protectionModel: protectionModel,\n protectionKeyController: protectionKeyController,\n eventBus: config.eventBus,\n debug: config.debug,\n events: config.events,\n BASE64: config.BASE64,\n constants: config.constants,\n cmcdModel: config.cmcdModel,\n settings: config.settings\n });\n config.capabilities.setEncryptedMediaSupported(true);\n }\n return controller;\n }\n\n function _getProtectionModel(config) {\n const debug = config.debug;\n const logger = debug.getLogger(instance);\n const eventBus = config.eventBus;\n const errHandler = config.errHandler;\n const videoElement = config.videoModel ? config.videoModel.getElement() : null;\n\n if ((!videoElement || videoElement.onencrypted !== undefined) &&\n (!videoElement || videoElement.mediaKeys !== undefined)) {\n logger.info('EME detected on this user agent! (ProtectionModel_21Jan2015)');\n return ProtectionModel_21Jan2015(context).create({ debug: debug, eventBus: eventBus, events: config.events });\n } else if (_getAPI(videoElement, APIS_ProtectionModel_3Feb2014)) {\n logger.info('EME detected on this user agent! (ProtectionModel_3Feb2014)');\n return ProtectionModel_3Feb2014(context).create({ debug: debug, eventBus: eventBus, events: config.events, api: _getAPI(videoElement, APIS_ProtectionModel_3Feb2014) });\n } else if (_getAPI(videoElement, APIS_ProtectionModel_01b)) {\n logger.info('EME detected on this user agent! (ProtectionModel_01b)');\n return ProtectionModel_01b(context).create({ debug: debug, eventBus: eventBus, errHandler: errHandler, events: config.events, api: _getAPI(videoElement, APIS_ProtectionModel_01b) });\n } else {\n logger.warn('No supported version of EME detected on this user agent! - Attempts to play encrypted content will fail!');\n return null;\n }\n }\n\n function _getAPI(videoElement, apis) {\n for (let i = 0; i < apis.length; i++) {\n const api = apis[i];\n // detect if api is supported by browser\n // check only first function in api -> should be fine\n if (typeof videoElement[api[Object.keys(api)[0]]] !== 'function') {\n continue;\n }\n\n return api;\n }\n\n return null;\n }\n\n instance = {\n createProtectionSystem\n };\n\n return instance;\n}\n\nProtection.__dashjs_factory_name = 'Protection';\nconst factory = dashjs.FactoryMaker.getClassFactory(Protection); /* jshint ignore:line */\nfactory.events = ProtectionEvents;\nfactory.errors = ProtectionErrors;\ndashjs.FactoryMaker.updateClassFactory(Protection.__dashjs_factory_name, factory); /* jshint ignore:line */\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass DVBErrors {\n constructor() {\n this.mpdurl = null;\n // String - Absolute URL from which the MPD was originally\n // retrieved (MPD updates will not change this value).\n\n this.errorcode = null;\n // String - The value of errorcode depends upon the type\n // of error being reported. For an error listed in the\n // ErrorType column below the value is as described in the\n // Value column.\n //\n // ErrorType Value\n // --------- -----\n // HTTP error status code HTTP status code\n // Unknown HTTP status code HTTP status code\n // SSL connection failed \"SSL\" followed by SSL alert value\n // DNS resolution failed \"C00\"\n // Host unreachable \"C01\"\n // Connection refused \"C02\"\n // Connection error – Not otherwise specified \"C03\"\n // Corrupt media – ISO BMFF container cannot be parsed \"M00\"\n // Corrupt media – Not otherwise specified \"M01\"\n // Changing Base URL in use due to errors \"F00\"\n // Becoming an error reporting Player \"S00\"\n\n this.terror = null;\n // Real-Time - Date and time at which error occurred in UTC,\n // formatted as a combined date and time according to ISO 8601.\n\n this.url = null;\n // String - Absolute URL from which data was being requested\n // when this error occurred. If the error report is in relation\n // to corrupt media or changing BaseURL, this may be a null\n // string if the URL from which the media was obtained or\n // which led to the change of BaseURL is no longer known.\n\n this.ipaddress = null;\n // String - IP Address which the host name in \"url\" resolved to.\n // If the error report is in relation to corrupt media or\n // changing BaseURL, this may be a null string if the URL\n // from which the media was obtained or which led to the\n // change of BaseURL is no longer known.\n\n this.servicelocation = null;\n // String - The value of the serviceLocation field in the\n // BaseURL being used. In the event of this report indicating\n // a change of BaseURL this is the value from the BaseURL\n // being moved from.\n }\n}\n\nDVBErrors.SSL_CONNECTION_FAILED_PREFIX = 'SSL';\nDVBErrors.DNS_RESOLUTION_FAILED = 'C00';\nDVBErrors.HOST_UNREACHABLE = 'C01';\nDVBErrors.CONNECTION_REFUSED = 'C02';\nDVBErrors.CONNECTION_ERROR = 'C03';\nDVBErrors.CORRUPT_MEDIA_ISOBMFF = 'M00';\nDVBErrors.CORRUPT_MEDIA_OTHER = 'M01';\nDVBErrors.BASE_URL_CHANGED = 'F00';\nDVBErrors.BECAME_REPORTER = 'S00';\n\nexport default DVBErrors;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport DVBErrors from '../vo/DVBErrors';\nimport MetricsReportingEvents from '../MetricsReportingEvents';\n\nfunction DVBErrorsTranslator(config) {\n\n config = config || {};\n let instance,\n mpd;\n const eventBus = config.eventBus;\n const dashMetrics = config.dashMetrics;\n const metricsConstants = config.metricsConstants;\n //MediaPlayerEvents have been added to Events in MediaPlayer class\n const Events = config.events;\n\n function report(vo) {\n let o = new DVBErrors();\n\n if (!mpd) {\n return;\n }\n\n for (const key in vo) {\n if (vo.hasOwnProperty(key)) {\n o[key] = vo[key];\n }\n }\n\n if (!o.mpdurl) {\n o.mpdurl = mpd.originalUrl || mpd.url;\n }\n\n if (!o.terror) {\n o.terror = new Date();\n }\n\n dashMetrics.addDVBErrors(o);\n }\n\n function onManifestUpdate(e) {\n if (e.error) {\n return;\n }\n\n mpd = e.manifest;\n }\n\n function onServiceLocationChanged(e) {\n report({\n errorcode: DVBErrors.BASE_URL_CHANGED,\n servicelocation: e.entry\n });\n }\n\n function onBecameReporter() {\n report({\n errorcode: DVBErrors.BECAME_REPORTER\n });\n }\n\n function handleHttpMetric(vo) {\n if ((vo.responsecode === 0) || // connection failure - unknown\n (vo.responsecode == null) || // Generated on .catch() and when uninitialised\n (vo.responsecode >= 400) || // HTTP error status code\n (vo.responsecode < 100) || // unknown status codes\n (vo.responsecode >= 600)) { // unknown status codes\n report({\n errorcode: vo.responsecode || DVBErrors.CONNECTION_ERROR,\n url: vo.url,\n terror: vo.tresponse,\n servicelocation: vo._serviceLocation\n });\n }\n }\n\n function onMetricEvent(e) {\n switch (e.metric) {\n case metricsConstants.HTTP_REQUEST:\n handleHttpMetric(e.value);\n break;\n default:\n break;\n }\n }\n\n function onPlaybackError(e) {\n let reason = e.error ? e.error.code : 0;\n let errorcode;\n\n switch (reason) {\n case MediaError.MEDIA_ERR_NETWORK:\n errorcode = DVBErrors.CONNECTION_ERROR;\n break;\n case MediaError.MEDIA_ERR_DECODE:\n errorcode = DVBErrors.CORRUPT_MEDIA_OTHER;\n break;\n default:\n return;\n }\n\n report({\n errorcode: errorcode\n });\n }\n\n function initialise() {\n eventBus.on(Events.MANIFEST_UPDATED, onManifestUpdate, instance);\n eventBus.on(\n Events.SERVICE_LOCATION_BLACKLIST_CHANGED,\n onServiceLocationChanged,\n instance\n );\n eventBus.on(Events.METRIC_ADDED, onMetricEvent, instance);\n eventBus.on(Events.METRIC_UPDATED, onMetricEvent, instance);\n eventBus.on(Events.PLAYBACK_ERROR, onPlaybackError, instance);\n eventBus.on(\n MetricsReportingEvents.BECAME_REPORTING_PLAYER,\n onBecameReporter,\n instance\n );\n }\n\n function reset() {\n eventBus.off(Events.MANIFEST_UPDATED, onManifestUpdate, instance);\n eventBus.off(\n Events.SERVICE_LOCATION_BLACKLIST_CHANGED,\n onServiceLocationChanged,\n instance\n );\n eventBus.off(Events.METRIC_ADDED, onMetricEvent, instance);\n eventBus.off(Events.METRIC_UPDATED, onMetricEvent, instance);\n eventBus.off(Events.PLAYBACK_ERROR, onPlaybackError, instance);\n eventBus.off(\n MetricsReportingEvents.BECAME_REPORTING_PLAYER,\n onBecameReporter,\n instance\n );\n }\n\n instance = {\n initialise,\n reset\n };\n\n return instance;\n}\n\nDVBErrorsTranslator.__dashjs_factory_name = 'DVBErrorsTranslator';\nexport default dashjs.FactoryMaker.getSingletonFactory(DVBErrorsTranslator); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport CustomTimeRanges from '../../utils/CustomTimeRanges';\n\nfunction RangeController(config) {\n\n config = config || {};\n let useWallClockTime = false;\n let context = this.context;\n let instance,\n ranges;\n\n let mediaElement = config.mediaElement;\n\n function initialize(rs) {\n if (rs && rs.length) {\n rs.forEach(r => {\n let start = r.starttime;\n let end = start + r.duration;\n\n ranges.add(start, end);\n });\n\n useWallClockTime = !!rs[0]._useWallClockTime;\n }\n }\n\n function reset() {\n ranges.clear();\n }\n\n function setup() {\n ranges = CustomTimeRanges(context).create();\n }\n\n function isEnabled() {\n let numRanges = ranges.length;\n let time;\n\n if (!numRanges) {\n return true;\n }\n\n // When not present, DASH Metrics reporting is requested\n // for the whole duration of the content.\n time = useWallClockTime ?\n (new Date().getTime() / 1000) :\n mediaElement.currentTime;\n\n for (let i = 0; i < numRanges; i += 1) {\n let start = ranges.start(i);\n let end = ranges.end(i);\n\n if ((start <= time) && (time < end)) {\n return true;\n }\n }\n\n return false;\n }\n\n instance = {\n initialize: initialize,\n reset: reset,\n isEnabled: isEnabled\n };\n\n setup();\n\n return instance;\n}\n\nRangeController.__dashjs_factory_name = 'RangeController';\nexport default dashjs.FactoryMaker.getClassFactory(RangeController); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * @ignore\n */\nfunction MetricSerialiser() {\n\n // For each entry in the top level list within the metric (in the case\n // of the DVBErrors metric each entry corresponds to an \"error event\"\n // described in clause 10.8.4) the Player shall:\n function serialise(metric) {\n let pairs = [];\n let obj = [];\n let key,\n value;\n\n // Take each (key, value) pair from the metric entry and create a\n // string consisting of the name of the key, followed by an equals\n // ('=') character, followed by the string representation of the\n // value. The string representation of the value is created based\n // on the type of the value following the instructions in Table 22.\n for (key in metric) {\n if (metric.hasOwnProperty(key) && (key.indexOf('_') !== 0)) {\n value = metric[key];\n\n // we want to ensure that keys still end up in the report\n // even if there is no value\n if ((value === undefined) || (value === null)) {\n value = '';\n }\n\n // DVB A168 10.12.4 Table 22\n if (Array.isArray(value)) {\n // if trace or similar is null, do not include in output\n if (!value.length) {\n continue;\n }\n\n obj = [];\n\n value.forEach(function (v) {\n let isBuiltIn = Object.prototype.toString.call(v).slice(8, -1) !== 'Object';\n\n obj.push(isBuiltIn ? v : serialise(v));\n });\n\n value = obj.map(encodeURIComponent).join(',');\n } else if (typeof value === 'string') {\n value = encodeURIComponent(value);\n } else if (value instanceof Date) {\n value = value.toISOString();\n } else if (typeof value === 'number') {\n value = Math.round(value);\n }\n\n pairs.push(key + '=' + value);\n }\n }\n\n // Concatenate the strings created in the previous step with an\n // ampersand ('&') character between each one.\n return pairs.join('&');\n }\n\n return {\n serialise: serialise\n };\n}\n\nMetricSerialiser.__dashjs_factory_name = 'MetricSerialiser';\nexport default dashjs.FactoryMaker.getSingletonFactory(MetricSerialiser); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n /**\n * @ignore\n */\nfunction RNG() {\n\n // check whether secure random numbers are available. if not, revert to\n // using Math.random\n let crypto = window.crypto || window.msCrypto;\n\n // could just as easily use any other array type by changing line below\n let ArrayType = Uint32Array;\n let MAX_VALUE = Math.pow(2, ArrayType.BYTES_PER_ELEMENT * 8) - 1;\n\n // currently there is only one client for this code, and that only uses\n // a single random number per initialisation. may want to increase this\n // number if more consumers in the future\n let NUM_RANDOM_NUMBERS = 10;\n\n let randomNumbers,\n index,\n instance;\n\n function initialise() {\n if (crypto) {\n if (!randomNumbers) {\n randomNumbers = new ArrayType(NUM_RANDOM_NUMBERS);\n }\n crypto.getRandomValues(randomNumbers);\n index = 0;\n }\n }\n\n function rand(min, max) {\n let r;\n\n if (!min) {\n min = 0;\n }\n\n if (!max) {\n max = 1;\n }\n\n if (crypto) {\n if (index === randomNumbers.length) {\n initialise();\n }\n\n r = randomNumbers[index] / MAX_VALUE;\n index += 1;\n } else {\n r = Math.random();\n }\n\n return (r * (max - min)) + min;\n }\n\n instance = {\n random: rand\n };\n\n initialise();\n\n return instance;\n}\n\nRNG.__dashjs_factory_name = 'RNG';\nexport default dashjs.FactoryMaker.getSingletonFactory(RNG); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport MetricSerialiser from '../../utils/MetricSerialiser';\nimport RNG from '../../utils/RNG';\n\nfunction DVBReporting(config) {\n config = config || {};\n let instance;\n\n let context = this.context;\n let metricSerialiser,\n randomNumberGenerator,\n reportingPlayerStatusDecided,\n isReportingPlayer,\n reportingUrl,\n rangeController;\n\n let USE_DRAFT_DVB_SPEC = true;\n let allowPendingRequestsToCompleteOnReset = true;\n let pendingRequests = [];\n\n const metricsConstants = config.metricsConstants;\n\n function setup() {\n metricSerialiser = MetricSerialiser(context).getInstance();\n randomNumberGenerator = RNG(context).getInstance();\n\n resetInitialSettings();\n }\n\n function doGetRequest(url, successCB, failureCB) {\n let req = new XMLHttpRequest();\n const oncomplete = function () {\n let reqIndex = pendingRequests.indexOf(req);\n\n if (reqIndex === -1) {\n return;\n } else {\n pendingRequests.splice(reqIndex, 1);\n }\n\n if ((req.status >= 200) && (req.status < 300)) {\n if (successCB) {\n successCB();\n }\n } else {\n if (failureCB) {\n failureCB();\n }\n }\n };\n\n pendingRequests.push(req);\n\n try {\n req.open('GET', url);\n req.onloadend = oncomplete;\n req.onerror = oncomplete;\n req.send();\n } catch (e) {\n req.onerror();\n }\n }\n\n function report(type, vos) {\n if (!Array.isArray(vos)) {\n vos = [vos];\n }\n\n // If the Player is not a reporting Player, then the Player shall\n // not report any errors.\n // ... In addition to any time restrictions specified by a Range\n // element within the Metrics element.\n if (isReportingPlayer && rangeController.isEnabled()) {\n\n // This reporting mechanism operates by creating one HTTP GET\n // request for every entry in the top level list of the metric.\n vos.forEach(function (vo) {\n let url = metricSerialiser.serialise(vo);\n\n // this has been proposed for errata\n if (USE_DRAFT_DVB_SPEC && (type !== metricsConstants.DVB_ERRORS)) {\n url = `metricname=${type}&${url}`;\n }\n\n // Take the value of the @reportingUrl attribute, append a\n // question mark ('?') character and then append the string\n // created in the previous step.\n url = `${reportingUrl}?${url}`;\n\n // Make an HTTP GET request to the URL contained within the\n // string created in the previous step.\n doGetRequest(url, null, function () {\n // If the Player is unable to make the report, for\n // example because the @reportingUrl is invalid, the\n // host cannot be reached, or an HTTP status code other\n // than one in the 200 series is received, the Player\n // shall cease being a reporting Player for the\n // duration of the MPD.\n isReportingPlayer = false;\n });\n });\n }\n }\n\n function initialize(entry, rc) {\n let probability;\n\n rangeController = rc;\n\n reportingUrl = entry.dvb_reportingUrl;\n\n // If a required attribute is missing, the Reporting descriptor may\n // be ignored by the Player\n if (!reportingUrl) {\n throw new Error(\n 'required parameter missing (dvb:reportingUrl)'\n );\n }\n\n // A Player's status, as a reporting Player or not, shall remain\n // static for the duration of the MPD, regardless of MPD updates.\n // (i.e. only calling reset (or failure) changes this state)\n if (!reportingPlayerStatusDecided) {\n probability = entry.dvb_probability;\n // TS 103 285 Clause 10.12.3.4\n // If the @probability attribute is set to 1000, it shall be a reporting Player.\n // If the @probability attribute is absent it will take the default value of 1000.\n // For any other value of the @probability attribute, it shall decide at random whether to be a\n // reporting Player, such that the probability of being one is @probability/1000.\n if (probability && (probability === 1000 || ((probability / 1000) >= randomNumberGenerator.random()))) {\n isReportingPlayer = true;\n }\n\n reportingPlayerStatusDecided = true;\n }\n }\n\n function resetInitialSettings() {\n reportingPlayerStatusDecided = false;\n isReportingPlayer = false;\n reportingUrl = null;\n rangeController = null;\n }\n\n function reset() {\n if (!allowPendingRequestsToCompleteOnReset) {\n pendingRequests.forEach(req => req.abort());\n pendingRequests = [];\n }\n\n resetInitialSettings();\n }\n\n instance = {\n report: report,\n initialize: initialize,\n reset: reset\n };\n\n setup();\n\n return instance;\n}\n\nDVBReporting.__dashjs_factory_name = 'DVBReporting';\nexport default dashjs.FactoryMaker.getClassFactory(DVBReporting); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport DVBReporting from './reporters/DVBReporting';\n\nfunction ReportingFactory(config) {\n config = config || {};\n\n const knownReportingSchemeIdUris = {\n 'urn:dvb:dash:reporting:2014': DVBReporting\n };\n\n const context = this.context;\n let instance;\n const logger = config.debug ? config.debug.getLogger(instance) : {};\n const metricsConstants = config.metricsConstants;\n\n function create(entry, rangeController) {\n let reporting;\n\n try {\n reporting = knownReportingSchemeIdUris[entry.schemeIdUri](context).create({\n metricsConstants: metricsConstants\n });\n\n reporting.initialize(entry, rangeController);\n } catch (e) {\n reporting = null;\n logger.error(`ReportingFactory: could not create Reporting with schemeIdUri ${entry.schemeIdUri} (${e.message})`);\n }\n\n return reporting;\n }\n\n function register(schemeIdUri, moduleName) {\n knownReportingSchemeIdUris[schemeIdUri] = moduleName;\n }\n\n function unregister(schemeIdUri) {\n delete knownReportingSchemeIdUris[schemeIdUri];\n }\n\n instance = {\n create: create,\n register: register,\n unregister: unregister\n };\n\n return instance;\n}\n\nReportingFactory.__dashjs_factory_name = 'ReportingFactory';\nexport default dashjs.FactoryMaker.getSingletonFactory(ReportingFactory); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport ReportingFactory from '../reporting/ReportingFactory';\n\nfunction ReportingController(config) {\n\n let reporters = [];\n let instance;\n\n const reportingFactory = ReportingFactory(this.context).getInstance(config);\n\n function initialize(reporting, rangeController) {\n // \"if multiple Reporting elements are present, it is expected that\n // the client processes one of the recognized reporting schemes.\"\n // to ignore this, and support multiple Reporting per Metric,\n // simply change the 'some' below to 'forEach'\n reporting.some(r => {\n let reporter = reportingFactory.create(r, rangeController);\n\n if (reporter) {\n reporters.push(reporter);\n return true;\n }\n });\n }\n\n function reset() {\n reporters.forEach(r => r.reset());\n reporters = [];\n }\n\n function report(type, vos) {\n reporters.forEach(r => r.report(type, vos));\n }\n\n instance = {\n initialize: initialize,\n reset: reset,\n report: report\n };\n\n return instance;\n}\n\nReportingController.__dashjs_factory_name = 'ReportingController';\nexport default dashjs.FactoryMaker.getClassFactory(ReportingController); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n /**\n * @ignore\n */\nfunction HandlerHelpers() {\n return {\n reconstructFullMetricName: function (key, n, type) {\n let mn = key;\n\n if (n) {\n mn += '(' + n;\n\n if (type && type.length) {\n mn += ',' + type;\n }\n\n mn += ')';\n }\n\n return mn;\n },\n\n validateN: function (n_ms) {\n if (!n_ms) {\n throw new Error('missing n');\n }\n\n if (isNaN(n_ms)) {\n throw new Error('n is NaN');\n }\n\n // n is a positive integer is defined to refer to the metric\n // in which the buffer level is recorded every n ms.\n if (n_ms < 0) {\n throw new Error('n must be positive');\n }\n\n return n_ms;\n }\n };\n}\n\nHandlerHelpers.__dashjs_factory_name = 'HandlerHelpers';\nexport default dashjs.FactoryMaker.getSingletonFactory(HandlerHelpers); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport HandlerHelpers from '../../utils/HandlerHelpers';\n\nfunction BufferLevelHandler(config) {\n\n config = config || {};\n let instance,\n reportingController,\n n,\n name,\n interval,\n lastReportedTime;\n\n let context = this.context;\n let handlerHelpers = HandlerHelpers(context).getInstance();\n\n let storedVOs = [];\n\n const metricsConstants = config.metricsConstants;\n\n function getLowestBufferLevelVO() {\n try {\n return Object.keys(storedVOs).map(\n key => storedVOs[key]\n ).reduce(\n (a, b) => {\n return (a.level < b.level) ? a : b;\n }\n );\n } catch (e) {\n return;\n }\n }\n\n function intervalCallback() {\n let vo = getLowestBufferLevelVO();\n\n if (vo) {\n if (lastReportedTime !== vo.t) {\n lastReportedTime = vo.t;\n reportingController.report(name, vo);\n }\n }\n }\n\n function initialize(basename, rc, n_ms) {\n if (rc) {\n // this will throw if n is invalid, to be\n // caught by the initialize caller.\n n = handlerHelpers.validateN(n_ms);\n reportingController = rc;\n name = handlerHelpers.reconstructFullMetricName(basename, n_ms);\n interval = setInterval(intervalCallback, n);\n }\n }\n\n function reset() {\n clearInterval(interval);\n interval = null;\n n = 0;\n reportingController = null;\n lastReportedTime = null;\n }\n\n function handleNewMetric(metric, vo, type) {\n if (metric === metricsConstants.BUFFER_LEVEL) {\n storedVOs[type] = vo;\n }\n }\n\n instance = {\n initialize: initialize,\n reset: reset,\n handleNewMetric: handleNewMetric\n };\n\n return instance;\n}\n\nBufferLevelHandler.__dashjs_factory_name = 'BufferLevelHandler';\nexport default dashjs.FactoryMaker.getClassFactory(BufferLevelHandler); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport MetricsReportingEvents from '../../MetricsReportingEvents';\n\nfunction DVBErrorsHandler(config) {\n\n config = config || {};\n let instance,\n reportingController;\n\n let eventBus = config.eventBus;\n const metricsConstants = config.metricsConstants;\n\n function onInitialisationComplete() {\n // we only want to report this once per call to initialize\n eventBus.off(\n MetricsReportingEvents.METRICS_INITIALISATION_COMPLETE,\n onInitialisationComplete,\n this\n );\n\n // Note: A Player becoming a reporting Player is itself\n // something which is recorded by the DVBErrors metric.\n eventBus.trigger(MetricsReportingEvents.BECAME_REPORTING_PLAYER);\n }\n\n function initialize(unused, rc) {\n if (rc) {\n reportingController = rc;\n\n eventBus.on(\n MetricsReportingEvents.METRICS_INITIALISATION_COMPLETE,\n onInitialisationComplete,\n this\n );\n }\n }\n\n function reset() {\n reportingController = null;\n }\n\n function handleNewMetric(metric, vo) {\n // simply pass metric straight through\n if (metric === metricsConstants.DVB_ERRORS) {\n if (reportingController) {\n reportingController.report(metric, vo);\n }\n }\n }\n\n instance = {\n initialize: initialize,\n reset: reset,\n handleNewMetric: handleNewMetric\n };\n\n return instance;\n}\n\nexport default dashjs.FactoryMaker.getClassFactory(DVBErrorsHandler); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport HandlerHelpers from '../../utils/HandlerHelpers';\n\nfunction HttpListHandler(config) {\n\n config = config || {};\n let instance,\n reportingController,\n n,\n type,\n name,\n interval;\n\n let storedVos = [];\n\n let handlerHelpers = HandlerHelpers(this.context).getInstance();\n\n const metricsConstants = config.metricsConstants;\n\n function intervalCallback() {\n var vos = storedVos;\n\n if (vos.length) {\n if (reportingController) {\n reportingController.report(name, vos);\n }\n }\n\n storedVos = [];\n }\n\n function initialize(basename, rc, n_ms, requestType) {\n if (rc) {\n\n // this will throw if n is invalid, to be\n // caught by the initialize caller.\n n = handlerHelpers.validateN(n_ms);\n\n reportingController = rc;\n\n if (requestType && requestType.length) {\n type = requestType;\n }\n\n name = handlerHelpers.reconstructFullMetricName(\n basename,\n n_ms,\n requestType\n );\n\n interval = setInterval(intervalCallback, n);\n }\n }\n\n function reset() {\n clearInterval(interval);\n interval = null;\n n = null;\n type = null;\n storedVos = [];\n reportingController = null;\n }\n\n function handleNewMetric(metric, vo) {\n if (metric === metricsConstants.HTTP_REQUEST) {\n if (!type || (type === vo.type)) {\n storedVos.push(vo);\n }\n }\n }\n\n instance = {\n initialize: initialize,\n reset: reset,\n handleNewMetric: handleNewMetric\n };\n\n return instance;\n}\n\nHttpListHandler.__dashjs_factory_name = 'HttpListHandler';\nexport default dashjs.FactoryMaker.getClassFactory(HttpListHandler); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n /**\n * @ignore\n */\nfunction GenericMetricHandler() {\n\n let instance,\n metricName,\n reportingController;\n\n function initialize(name, rc) {\n metricName = name;\n reportingController = rc;\n }\n\n function reset() {\n reportingController = null;\n metricName = undefined;\n }\n\n function handleNewMetric(metric, vo) {\n // simply pass metric straight through\n if (metric === metricName) {\n if (reportingController) {\n reportingController.report(metricName, vo);\n }\n }\n }\n\n instance = {\n initialize: initialize,\n reset: reset,\n handleNewMetric: handleNewMetric\n };\n\n return instance;\n}\n\nGenericMetricHandler.__dashjs_factory_name = 'GenericMetricHandler';\nexport default dashjs.FactoryMaker.getClassFactory(GenericMetricHandler); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport BufferLevel from './handlers/BufferLevelHandler';\nimport DVBErrors from './handlers/DVBErrorsHandler';\nimport HttpList from './handlers/HttpListHandler';\nimport GenericMetricHandler from './handlers/GenericMetricHandler';\n\nfunction MetricsHandlerFactory(config) {\n\n config = config || {};\n let instance;\n const logger = config.debug ? config.debug.getLogger(instance) : {};\n\n // group 1: key, [group 3: n [, group 5: type]]\n let keyRegex = /([a-zA-Z]*)(\\(([0-9]*)(\\,\\s*([a-zA-Z]*))?\\))?/;\n\n const context = this.context;\n let knownFactoryProducts = {\n BufferLevel: BufferLevel,\n DVBErrors: DVBErrors,\n HttpList: HttpList,\n PlayList: GenericMetricHandler,\n RepSwitchList: GenericMetricHandler,\n TcpList: GenericMetricHandler\n };\n\n function create(listType, reportingController) {\n var matches = listType.match(keyRegex);\n var handler;\n\n if (!matches) {\n return;\n }\n\n try {\n handler = knownFactoryProducts[matches[1]](context).create({\n eventBus: config.eventBus,\n metricsConstants: config.metricsConstants\n });\n\n handler.initialize(\n matches[1],\n reportingController,\n matches[3],\n matches[5]\n );\n } catch (e) {\n handler = null;\n logger.error(`MetricsHandlerFactory: Could not create handler for type ${matches[1]} with args ${matches[3]}, ${matches[5]} (${e.message})`);\n }\n\n return handler;\n }\n\n function register(key, handler) {\n knownFactoryProducts[key] = handler;\n }\n\n function unregister(key) {\n delete knownFactoryProducts[key];\n }\n\n instance = {\n create: create,\n register: register,\n unregister: unregister\n };\n\n return instance;\n}\n\nMetricsHandlerFactory.__dashjs_factory_name = 'MetricsHandlerFactory';\nexport default dashjs.FactoryMaker.getSingletonFactory(MetricsHandlerFactory); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport MetricsHandlerFactory from '../metrics/MetricsHandlerFactory';\n\nfunction MetricsHandlersController(config) {\n\n config = config || {};\n let handlers = [];\n\n let instance;\n const context = this.context;\n const eventBus = config.eventBus;\n const Events = config.events;\n\n let metricsHandlerFactory = MetricsHandlerFactory(context).getInstance({\n debug: config.debug,\n eventBus: config.eventBus,\n metricsConstants: config.metricsConstants\n });\n\n function handle(e) {\n handlers.forEach(handler => {\n handler.handleNewMetric(e.metric, e.value, e.mediaType);\n });\n }\n\n function initialize(metrics, reportingController) {\n metrics.split(',').forEach(\n (m, midx, ms) => {\n let handler;\n\n // there is a bug in ISO23009-1 where the metrics attribute\n // is a comma-separated list but HttpList key can contain a\n // comma enclosed by ().\n if ((m.indexOf('(') !== -1) && m.indexOf(')') === -1) {\n let nextm = ms[midx + 1];\n\n if (nextm &&\n (nextm.indexOf('(') === -1) &&\n (nextm.indexOf(')') !== -1)) {\n m += ',' + nextm;\n\n // delete the next metric so forEach does not visit.\n delete ms[midx + 1];\n }\n }\n\n handler = metricsHandlerFactory.create(\n m,\n reportingController\n );\n\n if (handler) {\n handlers.push(handler);\n }\n }\n );\n\n eventBus.on(\n Events.METRIC_ADDED,\n handle,\n instance\n );\n\n eventBus.on(\n Events.METRIC_UPDATED,\n handle,\n instance\n );\n }\n\n function reset() {\n eventBus.off(\n Events.METRIC_ADDED,\n handle,\n instance\n );\n\n eventBus.off(\n Events.METRIC_UPDATED,\n handle,\n instance\n );\n\n handlers.forEach(handler => handler.reset());\n\n handlers = [];\n }\n\n instance = {\n initialize: initialize,\n reset: reset\n };\n\n return instance;\n}\n\nMetricsHandlersController.__dashjs_factory_name = 'MetricsHandlersController';\nexport default dashjs.FactoryMaker.getClassFactory(MetricsHandlersController); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport RangeController from './RangeController';\nimport ReportingController from './ReportingController';\nimport MetricsHandlersController from './MetricsHandlersController';\n\nfunction MetricsController(config) {\n\n config = config || {};\n let metricsHandlersController,\n reportingController,\n rangeController,\n instance;\n\n let context = this.context;\n\n function initialize(metricsEntry) {\n try {\n rangeController = RangeController(context).create({\n mediaElement: config.mediaElement\n });\n\n rangeController.initialize(metricsEntry.Range);\n\n reportingController = ReportingController(context).create({\n debug: config.debug,\n metricsConstants: config.metricsConstants\n });\n\n reportingController.initialize(metricsEntry.Reporting, rangeController);\n\n metricsHandlersController = MetricsHandlersController(context).create({\n debug: config.debug,\n eventBus: config.eventBus,\n metricsConstants: config.metricsConstants,\n events: config.events\n });\n\n metricsHandlersController.initialize(metricsEntry.metrics, reportingController);\n } catch (e) {\n reset();\n throw e;\n }\n }\n\n function reset() {\n if (metricsHandlersController) {\n metricsHandlersController.reset();\n }\n\n if (reportingController) {\n reportingController.reset();\n }\n\n if (rangeController) {\n rangeController.reset();\n }\n }\n\n instance = {\n initialize: initialize,\n reset: reset\n };\n\n return instance;\n}\n\nMetricsController.__dashjs_factory_name = 'MetricsController';\nexport default dashjs.FactoryMaker.getClassFactory(MetricsController); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass Metrics {\n constructor() {\n\n this.metrics = '';\n this.Range = [];\n this.Reporting = [];\n }\n}\n\nexport default Metrics;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\nclass Range {\n constructor() {\n\n // as defined in ISO23009-1\n this.starttime = 0;\n this.duration = Infinity;\n\n // for internal use\n this._useWallClockTime = false;\n }\n}\n\nexport default Range;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @class\n * @ignore\n */\n\n// TS 103 285 Clause 10.12.3.3\nconst DEFAULT_DVB_PROBABILITY = 1000;\n\nclass Reporting {\n constructor() {\n\n this.schemeIdUri = '';\n this.value = '';\n\n // DVB Extensions\n this.dvb_reportingUrl = '';\n this.dvb_probability = DEFAULT_DVB_PROBABILITY;\n }\n}\n\nexport default Reporting;\n","import Metrics from '../vo/Metrics';\nimport Range from '../vo/Range';\nimport Reporting from '../vo/Reporting';\n\nfunction ManifestParsing (config) {\n config = config || {};\n let instance;\n let adapter = config.adapter;\n const constants = config.constants;\n\n function getMetricsRangeStartTime(manifest, dynamic, range) {\n let voPeriods,\n reportingStartTime;\n let presentationStartTime = 0;\n\n if (dynamic) {\n // For services with MPD@type='dynamic', the start time is\n // indicated in wall clock time by adding the value of this\n // attribute to the value of the MPD@availabilityStartTime\n // attribute.\n presentationStartTime = adapter.getAvailabilityStartTime(manifest) / 1000;\n } else {\n // For services with MPD@type='static', the start time is indicated\n // in Media Presentation time and is relative to the PeriodStart\n // time of the first Period in this MPD.\n voPeriods = adapter.getRegularPeriods(manifest);\n\n if (voPeriods.length) {\n presentationStartTime = voPeriods[0].start;\n }\n }\n\n // When not present, DASH Metrics collection is\n // requested from the beginning of content\n // consumption.\n reportingStartTime = presentationStartTime;\n\n if (range && range.hasOwnProperty(constants.START_TIME)) {\n reportingStartTime += range.starttime;\n }\n\n return reportingStartTime;\n }\n\n function getMetrics(manifest) {\n let metrics = [];\n\n if (manifest && manifest.Metrics_asArray) {\n manifest.Metrics_asArray.forEach(metric => {\n var metricEntry = new Metrics();\n var isDynamic = adapter.getIsDynamic(manifest);\n\n if (metric.hasOwnProperty('metrics')) {\n metricEntry.metrics = metric.metrics;\n } else {\n return;\n }\n\n if (metric.Range_asArray) {\n metric.Range_asArray.forEach(range => {\n var rangeEntry = new Range();\n\n rangeEntry.starttime =\n getMetricsRangeStartTime(manifest, isDynamic, range);\n\n if (range.hasOwnProperty('duration')) {\n rangeEntry.duration = range.duration;\n } else {\n // if not present, the value is identical to the\n // Media Presentation duration.\n rangeEntry.duration = adapter.getDuration(manifest);\n }\n\n rangeEntry._useWallClockTime = isDynamic;\n\n metricEntry.Range.push(rangeEntry);\n });\n }\n\n if (metric.Reporting_asArray) {\n metric.Reporting_asArray.forEach(reporting => {\n var reportingEntry = new Reporting();\n\n if (reporting.hasOwnProperty(constants.SCHEME_ID_URI)) {\n reportingEntry.schemeIdUri = reporting.schemeIdUri;\n } else {\n // Invalid Reporting. schemeIdUri must be set. Ignore.\n return;\n }\n\n if (reporting.hasOwnProperty('value')) {\n reportingEntry.value = reporting.value;\n }\n\n if (reporting.hasOwnProperty(constants.DVB_REPORTING_URL)) {\n reportingEntry.dvb_reportingUrl = reporting[constants.DVB_REPORTING_URL];\n }\n\n if (reporting.hasOwnProperty(constants.DVB_PROBABILITY)) {\n reportingEntry.dvb_probability = reporting[constants.DVB_PROBABILITY];\n }\n\n metricEntry.Reporting.push(reportingEntry);\n });\n } else {\n // Invalid Metrics. At least one reporting must be present. Ignore\n return;\n }\n\n metrics.push(metricEntry);\n });\n }\n\n return metrics;\n }\n\n instance = {\n getMetrics: getMetrics\n };\n\n return instance;\n}\n\nManifestParsing.__dashjs_factory_name = 'ManifestParsing';\nexport default dashjs.FactoryMaker.getSingletonFactory(ManifestParsing); /* jshint ignore:line */","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport MetricsController from './MetricsController';\nimport ManifestParsing from '../utils/ManifestParsing';\nimport MetricsReportingEvents from '../MetricsReportingEvents';\n\nfunction MetricsCollectionController(config) {\n\n config = config || {};\n let instance;\n let metricsControllers = {};\n let context = this.context;\n let eventBus = config.eventBus;\n const events = config.events;\n\n function update(e) {\n if (e.error) {\n return;\n }\n\n // start by assuming all existing controllers need removing\n let controllersToRemove = Object.keys(metricsControllers);\n\n const metrics = ManifestParsing(context).getInstance({\n adapter: config.adapter,\n constants: config.constants\n }).getMetrics(e.manifest);\n\n metrics.forEach(m => {\n const key = JSON.stringify(m);\n\n if (!metricsControllers.hasOwnProperty(key)) {\n try {\n let controller = MetricsController(context).create(config);\n controller.initialize(m);\n metricsControllers[key] = controller;\n } catch (e) {\n // fail quietly\n }\n } else {\n // we still need this controller - delete from removal list\n controllersToRemove.splice(key, 1);\n }\n });\n\n // now remove the unwanted controllers\n controllersToRemove.forEach(c => {\n metricsControllers[c].reset();\n delete metricsControllers[c];\n });\n\n eventBus.trigger(MetricsReportingEvents.METRICS_INITIALISATION_COMPLETE);\n }\n\n function resetMetricsControllers() {\n Object.keys(metricsControllers).forEach(key => {\n metricsControllers[key].reset();\n });\n\n metricsControllers = {};\n }\n\n function setup() {\n eventBus.on(events.MANIFEST_UPDATED, update, instance);\n eventBus.on(events.STREAM_TEARDOWN_COMPLETE, resetMetricsControllers, instance);\n }\n\n function reset() {\n eventBus.off(events.MANIFEST_UPDATED, update, instance);\n eventBus.off(events.STREAM_TEARDOWN_COMPLETE, resetMetricsControllers, instance);\n }\n\n instance = {\n reset: reset\n };\n\n setup();\n return instance;\n}\n\nMetricsCollectionController.__dashjs_factory_name = 'MetricsCollectionController';\nexport default dashjs.FactoryMaker.getClassFactory(MetricsCollectionController); /* jshint ignore:line */\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport DVBErrorsTranslator from './utils/DVBErrorsTranslator';\nimport MetricsReportingEvents from './MetricsReportingEvents';\nimport MetricsCollectionController from './controllers/MetricsCollectionController';\nimport MetricsHandlerFactory from './metrics/MetricsHandlerFactory';\nimport ReportingFactory from './reporting/ReportingFactory';\n\nfunction MetricsReporting() {\n\n let context = this.context;\n let instance,\n dvbErrorsTranslator;\n\n /**\n * Create a MetricsCollectionController, and a DVBErrorsTranslator\n * @param {Object} config - dependancies from owner\n * @return {MetricsCollectionController} Metrics Collection Controller\n */\n function createMetricsReporting(config) {\n dvbErrorsTranslator = DVBErrorsTranslator(context).getInstance({\n eventBus: config.eventBus,\n dashMetrics: config.dashMetrics,\n metricsConstants: config.metricsConstants,\n events: config.events\n });\n dvbErrorsTranslator.initialise();\n return MetricsCollectionController(context).create(config);\n }\n\n /**\n * Get the ReportingFactory to allow new reporters to be registered\n * @return {ReportingFactory} Reporting Factory\n */\n function getReportingFactory() {\n return ReportingFactory(context).getInstance();\n }\n\n /**\n * Get the MetricsHandlerFactory to allow new handlers to be registered\n * @return {MetricsHandlerFactory} Metrics Handler Factory\n */\n function getMetricsHandlerFactory() {\n return MetricsHandlerFactory(context).getInstance();\n }\n\n instance = {\n createMetricsReporting: createMetricsReporting,\n getReportingFactory: getReportingFactory,\n getMetricsHandlerFactory: getMetricsHandlerFactory\n };\n\n return instance;\n}\n\nMetricsReporting.__dashjs_factory_name = 'MetricsReporting';\nconst factory = dashjs.FactoryMaker.getClassFactory(MetricsReporting); /* jshint ignore:line */\nfactory.events = MetricsReportingEvents;\ndashjs.FactoryMaker.updateClassFactory(MetricsReporting.__dashjs_factory_name, factory); /* jshint ignore:line */\nexport default factory;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport MediaPlayer from './src/streaming/MediaPlayer';\nimport FactoryMaker from './src/core/FactoryMaker';\nimport Debug from './src/core/Debug';\nimport { getVersionString } from './src/core/Version';\n\nimport { } from 'es6-promise/auto';\n\n// Shove both of these into the global scope\nvar context = (typeof window !== 'undefined' && window) || global;\n\nvar dashjs = context.dashjs;\nif (!dashjs) {\n dashjs = context.dashjs = {};\n}\n\ndashjs.MediaPlayer = MediaPlayer;\ndashjs.FactoryMaker = FactoryMaker;\ndashjs.Debug = Debug;\ndashjs.Version = getVersionString();\n\nexport default dashjs;\nexport { MediaPlayer, FactoryMaker, Debug};\n","/* \r\n * Copyright (c) 2016, Pierre-Anthony Lemieux <pal@sandflow.com>\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *\r\n * * Redistributions of source code must retain the above copyright notice, this\r\n * list of conditions and the following disclaimer.\r\n * * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the documentation\r\n * and/or other materials provided with the distribution.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\r\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n * POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\n/**\r\n * @module imscISD\r\n */\r\n\r\n\r\n;\r\n(function (imscISD, imscNames, imscStyles) { // wrapper for non-node envs\r\n\r\n /** \r\n * Creates a canonical representation of an IMSC1 document returned by <pre>imscDoc.fromXML()</pre>\r\n * at a given absolute offset in seconds. This offset does not have to be one of the values returned\r\n * by <pre>getMediaTimeEvents()</pre>.\r\n * \r\n * @param {Object} tt IMSC1 document\r\n * @param {number} offset Absolute offset (in seconds)\r\n * @param {?module:imscUtils.ErrorHandler} errorHandler Error callback\r\n * @returns {Object} Opaque in-memory representation of an ISD\r\n */\r\n\r\n imscISD.generateISD = function (tt, offset, errorHandler) {\r\n\r\n /* TODO check for tt and offset validity */\r\n\r\n /* create the ISD object from the IMSC1 doc */\r\n\r\n var isd = new ISD(tt);\r\n \r\n /* context */\r\n \r\n var context = {\r\n \r\n /* empty for now */\r\n \r\n };\r\n\r\n /* process regions */\r\n\r\n for (var r in tt.head.layout.regions) {\r\n\r\n /* post-order traversal of the body tree per [construct intermediate document] */\r\n\r\n var c = isdProcessContentElement(tt, offset, tt.head.layout.regions[r], tt.body, null, '', tt.head.layout.regions[r], errorHandler, context);\r\n\r\n if (c !== null) {\r\n\r\n /* add the region to the ISD */\r\n\r\n isd.contents.push(c.element);\r\n }\r\n\r\n\r\n }\r\n\r\n return isd;\r\n };\r\n\r\n function isdProcessContentElement(doc, offset, region, body, parent, inherited_region_id, elem, errorHandler, context) {\r\n\r\n /* prune if temporally inactive */\r\n\r\n if (offset < elem.begin || offset >= elem.end) {\r\n return null;\r\n }\r\n\r\n /* \r\n * set the associated region as specified by the regionID attribute, or the \r\n * inherited associated region otherwise\r\n */\r\n\r\n var associated_region_id = 'regionID' in elem && elem.regionID !== '' ? elem.regionID : inherited_region_id;\r\n\r\n /* prune the element if either:\r\n * - the element is not terminal and the associated region is neither the default\r\n * region nor the parent region (this allows children to be associated with a \r\n * region later on)\r\n * - the element is terminal and the associated region is not the parent region\r\n */\r\n \r\n /* TODO: improve detection of terminal elements since <region> has no contents */\r\n\r\n if (parent !== null /* are we in the region element */ &&\r\n associated_region_id !== region.id &&\r\n (\r\n (! ('contents' in elem)) ||\r\n ('contents' in elem && elem.contents.length === 0) ||\r\n associated_region_id !== ''\r\n )\r\n )\r\n return null;\r\n\r\n /* create an ISD element, including applying specified styles */\r\n\r\n var isd_element = new ISDContentElement(elem);\r\n\r\n /* apply set (animation) styling */\r\n\r\n for (var i in elem.sets) {\r\n\r\n if (offset < elem.sets[i].begin || offset >= elem.sets[i].end)\r\n continue;\r\n\r\n isd_element.styleAttrs[elem.sets[i].qname] = elem.sets[i].value;\r\n\r\n }\r\n\r\n /* \r\n * keep track of specified styling attributes so that we\r\n * can compute them later\r\n */\r\n\r\n var spec_attr = {};\r\n\r\n for (var qname in isd_element.styleAttrs) {\r\n\r\n spec_attr[qname] = true;\r\n\r\n /* special rule for tts:writingMode (section 7.29.1 of XSL)\r\n * direction is set consistently with writingMode only\r\n * if writingMode sets inline-direction to LTR or RTL \r\n */\r\n\r\n if (qname === imscStyles.byName.writingMode.qname &&\r\n !(imscStyles.byName.direction.qname in isd_element.styleAttrs)) {\r\n\r\n var wm = isd_element.styleAttrs[qname];\r\n\r\n if (wm === \"lrtb\" || wm === \"lr\") {\r\n\r\n isd_element.styleAttrs[imscStyles.byName.direction.qname] = \"ltr\";\r\n\r\n } else if (wm === \"rltb\" || wm === \"rl\") {\r\n\r\n isd_element.styleAttrs[imscStyles.byName.direction.qname] = \"rtl\";\r\n\r\n }\r\n\r\n }\r\n }\r\n\r\n /* inherited styling */\r\n\r\n if (parent !== null) {\r\n\r\n for (var j in imscStyles.all) {\r\n\r\n var sa = imscStyles.all[j];\r\n\r\n /* textDecoration has special inheritance rules */\r\n\r\n if (sa.qname === imscStyles.byName.textDecoration.qname) {\r\n\r\n /* handle both textDecoration inheritance and specification */\r\n\r\n var ps = parent.styleAttrs[sa.qname];\r\n var es = isd_element.styleAttrs[sa.qname];\r\n var outs = [];\r\n\r\n if (es === undefined) {\r\n\r\n outs = ps;\r\n\r\n } else if (es.indexOf(\"none\") === -1) {\r\n\r\n if ((es.indexOf(\"noUnderline\") === -1 &&\r\n ps.indexOf(\"underline\") !== -1) ||\r\n es.indexOf(\"underline\") !== -1) {\r\n\r\n outs.push(\"underline\");\r\n\r\n }\r\n\r\n if ((es.indexOf(\"noLineThrough\") === -1 &&\r\n ps.indexOf(\"lineThrough\") !== -1) ||\r\n es.indexOf(\"lineThrough\") !== -1) {\r\n\r\n outs.push(\"lineThrough\");\r\n\r\n }\r\n\r\n if ((es.indexOf(\"noOverline\") === -1 &&\r\n ps.indexOf(\"overline\") !== -1) ||\r\n es.indexOf(\"overline\") !== -1) {\r\n\r\n outs.push(\"overline\");\r\n\r\n }\r\n\r\n } else {\r\n\r\n outs.push(\"none\");\r\n\r\n }\r\n\r\n isd_element.styleAttrs[sa.qname] = outs;\r\n\r\n } else if (sa.inherit &&\r\n (sa.qname in parent.styleAttrs) &&\r\n !(sa.qname in isd_element.styleAttrs)) {\r\n\r\n isd_element.styleAttrs[sa.qname] = parent.styleAttrs[sa.qname];\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n /* initial value styling */\r\n\r\n for (var k in imscStyles.all) {\r\n\r\n var ivs = imscStyles.all[k];\r\n\r\n /* skip if value is already specified */\r\n\r\n if (ivs.qname in isd_element.styleAttrs) continue;\r\n\r\n /* apply initial value to elements other than region only if non-inherited */\r\n\r\n if (isd_element.kind === 'region' || (ivs.inherit === false && ivs.initial !== null)) {\r\n\r\n isd_element.styleAttrs[ivs.qname] = ivs.parse(ivs.initial);\r\n\r\n /* keep track of the style as specified */\r\n\r\n spec_attr[ivs.qname] = true;\r\n\r\n }\r\n\r\n }\r\n\r\n /* compute styles (only for non-inherited styles) */\r\n /* TODO: get rid of spec_attr */\r\n\r\n for (var z in imscStyles.all) {\r\n\r\n var cs = imscStyles.all[z];\r\n\r\n if (!(cs.qname in spec_attr)) continue;\r\n\r\n if (cs.compute !== null) {\r\n\r\n var cstyle = cs.compute(\r\n /*doc, parent, element, attr, context*/\r\n doc,\r\n parent,\r\n isd_element,\r\n isd_element.styleAttrs[cs.qname],\r\n context\r\n );\r\n\r\n if (cstyle !== null) {\r\n isd_element.styleAttrs[cs.qname] = cstyle;\r\n } else {\r\n reportError(errorHandler, \"Style '\" + cs.qname + \"' on element '\" + isd_element.kind + \"' cannot be computed\");\r\n }\r\n }\r\n\r\n }\r\n\r\n /* prune if tts:display is none */\r\n\r\n if (isd_element.styleAttrs[imscStyles.byName.display.qname] === \"none\")\r\n return null;\r\n\r\n /* process contents of the element */\r\n\r\n var contents;\r\n\r\n if (parent === null) {\r\n\r\n /* we are processing the region */\r\n\r\n if (body === null) {\r\n\r\n /* if there is no body, still process the region but with empty content */\r\n\r\n contents = [];\r\n\r\n } else {\r\n\r\n /*use the body element as contents */\r\n\r\n contents = [body];\r\n\r\n }\r\n\r\n } else if ('contents' in elem) {\r\n\r\n contents = elem.contents;\r\n\r\n }\r\n\r\n for (var x in contents) {\r\n\r\n var c = isdProcessContentElement(doc, offset, region, body, isd_element, associated_region_id, contents[x], errorHandler, context);\r\n\r\n /* \r\n * keep child element only if they are non-null and their region match \r\n * the region of this element\r\n */\r\n\r\n if (c !== null) {\r\n\r\n isd_element.contents.push(c.element);\r\n\r\n }\r\n\r\n }\r\n\r\n /* compute used value of lineHeight=\"normal\" */\r\n\r\n /* if (isd_element.styleAttrs[imscStyles.byName.lineHeight.qname] === \"normal\" ) {\r\n \r\n isd_element.styleAttrs[imscStyles.byName.lineHeight.qname] =\r\n isd_element.styleAttrs[imscStyles.byName.fontSize.qname] * 1.2;\r\n \r\n }\r\n */\r\n\r\n /* remove styles that are not applicable */\r\n\r\n for (var qnameb in isd_element.styleAttrs) {\r\n var da = imscStyles.byQName[qnameb];\r\n\r\n if (da.applies.indexOf(isd_element.kind) === -1) {\r\n delete isd_element.styleAttrs[qnameb];\r\n }\r\n }\r\n\r\n /* collapse white space if space is \"default\" */\r\n\r\n if (isd_element.kind === 'span' && isd_element.text && isd_element.space === \"default\") {\r\n\r\n var trimmedspan = isd_element.text.replace(/\\s+/g, ' ');\r\n\r\n isd_element.text = trimmedspan;\r\n\r\n }\r\n\r\n /* trim whitespace around explicit line breaks */\r\n\r\n if (isd_element.kind === 'p') {\r\n\r\n var elist = [];\r\n\r\n constructSpanList(isd_element, elist);\r\n\r\n var l = 0;\r\n\r\n var state = \"after_br\";\r\n var br_pos = 0;\r\n\r\n while (true) {\r\n\r\n if (state === \"after_br\") {\r\n\r\n if (l >= elist.length || elist[l].kind === \"br\") {\r\n\r\n state = \"before_br\";\r\n br_pos = l;\r\n l--;\r\n\r\n } else {\r\n\r\n if (elist[l].space !== \"preserve\") {\r\n\r\n elist[l].text = elist[l].text.replace(/^\\s+/g, '');\r\n\r\n }\r\n\r\n if (elist[l].text.length > 0) {\r\n\r\n state = \"looking_br\";\r\n l++;\r\n\r\n } else {\r\n\r\n elist.splice(l, 1);\r\n\r\n }\r\n\r\n }\r\n\r\n } else if (state === \"before_br\") {\r\n\r\n if (l < 0 || elist[l].kind === \"br\") {\r\n\r\n state = \"after_br\";\r\n l = br_pos + 1;\r\n\r\n if (l >= elist.length) break;\r\n\r\n } else {\r\n\r\n if (elist[l].space !== \"preserve\") {\r\n\r\n elist[l].text = elist[l].text.replace(/\\s+$/g, '');\r\n\r\n }\r\n\r\n if (elist[l].text.length > 0) {\r\n\r\n state = \"after_br\";\r\n l = br_pos + 1;\r\n\r\n if (l >= elist.length) break;\r\n\r\n } else {\r\n\r\n elist.splice(l, 1);\r\n l--;\r\n\r\n }\r\n\r\n }\r\n\r\n } else {\r\n\r\n if (l >= elist.length || elist[l].kind === \"br\") {\r\n\r\n state = \"before_br\";\r\n br_pos = l;\r\n l--;\r\n\r\n } else {\r\n\r\n l++;\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n \r\n pruneEmptySpans(isd_element);\r\n\r\n }\r\n\r\n /* keep element if:\r\n * * contains a background image\r\n * * <br/>\r\n * * if there are children\r\n * * if <span> and has text\r\n * * if region and showBackground = always\r\n */\r\n\r\n if ((isd_element.kind === 'div' && imscStyles.byName.backgroundImage.qname in isd_element.styleAttrs) ||\r\n isd_element.kind === 'br' ||\r\n ('contents' in isd_element && isd_element.contents.length > 0) ||\r\n (isd_element.kind === 'span' && isd_element.text !== null) ||\r\n (isd_element.kind === 'region' &&\r\n isd_element.styleAttrs[imscStyles.byName.showBackground.qname] === 'always')) {\r\n\r\n return {\r\n region_id: associated_region_id,\r\n element: isd_element\r\n };\r\n }\r\n\r\n return null;\r\n }\r\n\r\n function constructSpanList(element, elist) {\r\n\r\n if ('contents' in element) {\r\n\r\n for (var i in element.contents) {\r\n constructSpanList(element.contents[i], elist);\r\n }\r\n\r\n } else {\r\n\r\n elist.push(element);\r\n\r\n }\r\n\r\n }\r\n\r\n function pruneEmptySpans(element) {\r\n\r\n if (element.kind === 'br') {\r\n \r\n return false;\r\n \r\n } else if ('text' in element) {\r\n \r\n return element.text.length === 0;\r\n \r\n } else if ('contents' in element) {\r\n \r\n var i = element.contents.length;\r\n\r\n while (i--) {\r\n \r\n if (pruneEmptySpans(element.contents[i])) {\r\n element.contents.splice(i, 1);\r\n }\r\n \r\n }\r\n \r\n return element.contents.length === 0;\r\n\r\n }\r\n }\r\n\r\n function ISD(tt) {\r\n this.contents = [];\r\n this.aspectRatio = tt.aspectRatio;\r\n }\r\n\r\n function ISDContentElement(ttelem) {\r\n\r\n /* assume the element is a region if it does not have a kind */\r\n\r\n this.kind = ttelem.kind || 'region';\r\n \r\n /* copy id */\r\n \r\n if (ttelem.id) {\r\n this.id = ttelem.id;\r\n }\r\n\r\n /* deep copy of style attributes */\r\n this.styleAttrs = {};\r\n\r\n for (var sname in ttelem.styleAttrs) {\r\n\r\n this.styleAttrs[sname] =\r\n ttelem.styleAttrs[sname];\r\n }\r\n\r\n /* TODO: clean this! */\r\n\r\n if ('text' in ttelem) {\r\n\r\n this.text = ttelem.text;\r\n\r\n } else if (ttelem.kind !== 'br') {\r\n \r\n this.contents = [];\r\n }\r\n\r\n if ('space' in ttelem) {\r\n\r\n this.space = ttelem.space;\r\n }\r\n }\r\n\r\n\r\n /*\r\n * ERROR HANDLING UTILITY FUNCTIONS\r\n * \r\n */\r\n\r\n function reportInfo(errorHandler, msg) {\r\n\r\n if (errorHandler && errorHandler.info && errorHandler.info(msg))\r\n throw msg;\r\n\r\n }\r\n\r\n function reportWarning(errorHandler, msg) {\r\n\r\n if (errorHandler && errorHandler.warn && errorHandler.warn(msg))\r\n throw msg;\r\n\r\n }\r\n\r\n function reportError(errorHandler, msg) {\r\n\r\n if (errorHandler && errorHandler.error && errorHandler.error(msg))\r\n throw msg;\r\n\r\n }\r\n\r\n function reportFatal(errorHandler, msg) {\r\n\r\n if (errorHandler && errorHandler.fatal)\r\n errorHandler.fatal(msg);\r\n\r\n throw msg;\r\n\r\n }\r\n\r\n\r\n})(typeof exports === 'undefined' ? this.imscISD = {} : exports,\r\n typeof imscNames === 'undefined' ? require(\"./names\") : imscNames,\r\n typeof imscStyles === 'undefined' ? require(\"./styles\") : imscStyles\r\n );\r\n","/* \r\n * Copyright (c) 2016, Pierre-Anthony Lemieux <pal@sandflow.com>\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *\r\n * * Redistributions of source code must retain the above copyright notice, this\r\n * list of conditions and the following disclaimer.\r\n * * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the documentation\r\n * and/or other materials provided with the distribution.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\r\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n * POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\n/**\r\n * @module imscDoc\r\n */\r\n\r\n;\r\n(function (imscDoc, sax, imscNames, imscStyles, imscUtils) {\r\n\r\n\r\n /**\r\n * Allows a client to provide callbacks to handle children of the <metadata> element\r\n * @typedef {Object} MetadataHandler\r\n * @property {?OpenTagCallBack} onOpenTag\r\n * @property {?CloseTagCallBack} onCloseTag\r\n * @property {?TextCallBack} onText\r\n */\r\n\r\n /**\r\n * Called when the opening tag of an element node is encountered.\r\n * @callback OpenTagCallBack\r\n * @param {string} ns Namespace URI of the element\r\n * @param {string} name Local name of the element\r\n * @param {Object[]} attributes List of attributes, each consisting of a\r\n * `uri`, `name` and `value`\r\n */\r\n\r\n /**\r\n * Called when the closing tag of an element node is encountered.\r\n * @callback CloseTagCallBack\r\n */\r\n\r\n /**\r\n * Called when a text node is encountered.\r\n * @callback TextCallBack\r\n * @param {string} contents Contents of the text node\r\n */\r\n\r\n /**\r\n * Parses an IMSC1 document into an opaque in-memory representation that exposes\r\n * a single method <pre>getMediaTimeEvents()</pre> that returns a list of time\r\n * offsets (in seconds) of the ISD, i.e. the points in time where the visual\r\n * representation of the document change. `metadataHandler` allows the caller to\r\n * be called back when nodes are present in <metadata> elements. \r\n * \r\n * @param {string} xmlstring XML document\r\n * @param {?module:imscUtils.ErrorHandler} errorHandler Error callback\r\n * @param {?MetadataHandler} metadataHandler Callback for <Metadata> elements\r\n * @returns {Object} Opaque in-memory representation of an IMSC1 document\r\n */\r\n\r\n imscDoc.fromXML = function (xmlstring, errorHandler, metadataHandler) {\r\n var p = sax.parser(true, {xmlns: true});\r\n var estack = [];\r\n var xmllangstack = [];\r\n var xmlspacestack = [];\r\n var metadata_depth = 0;\r\n var doc = null;\r\n\r\n p.onclosetag = function (node) {\r\n\r\n if (estack[0] instanceof Styling) {\r\n\r\n /* flatten chained referential styling */\r\n\r\n for (var sid in estack[0].styles) {\r\n\r\n mergeChainedStyles(estack[0], estack[0].styles[sid], errorHandler);\r\n\r\n }\r\n\r\n } else if (estack[0] instanceof P || estack[0] instanceof Span) {\r\n\r\n /* merge anonymous spans */\r\n\r\n if (estack[0].contents.length > 1) {\r\n\r\n var cs = [estack[0].contents[0]];\r\n\r\n var c;\r\n\r\n for (c = 1; c < estack[0].contents.length; c++) {\r\n\r\n if (estack[0].contents[c] instanceof AnonymousSpan &&\r\n cs[cs.length - 1] instanceof AnonymousSpan) {\r\n\r\n cs[cs.length - 1].text += estack[0].contents[c].text;\r\n\r\n } else {\r\n\r\n cs.push(estack[0].contents[c]);\r\n\r\n }\r\n\r\n }\r\n\r\n estack[0].contents = cs;\r\n\r\n }\r\n\r\n // remove redundant nested anonymous spans (9.3.3(1)(c))\r\n\r\n if (estack[0] instanceof Span &&\r\n estack[0].contents.length === 1 &&\r\n estack[0].contents[0] instanceof AnonymousSpan) {\r\n\r\n estack[0].text = estack[0].contents[0].text;\r\n delete estack[0].contents;\r\n\r\n }\r\n\r\n } else if (estack[0] instanceof ForeignElement) {\r\n\r\n if (estack[0].node.uri === imscNames.ns_tt &&\r\n estack[0].node.local === 'metadata') {\r\n\r\n /* leave the metadata element */\r\n\r\n metadata_depth--;\r\n\r\n } else if (metadata_depth > 0 &&\r\n metadataHandler &&\r\n 'onCloseTag' in metadataHandler) {\r\n\r\n /* end of child of metadata element */\r\n\r\n metadataHandler.onCloseTag();\r\n\r\n }\r\n\r\n }\r\n\r\n // TODO: delete stylerefs?\r\n\r\n // maintain the xml:space stack\r\n\r\n xmlspacestack.shift();\r\n\r\n // maintain the xml:lang stack\r\n\r\n xmllangstack.shift();\r\n\r\n // prepare for the next element\r\n\r\n estack.shift();\r\n };\r\n\r\n p.ontext = function (str) {\r\n\r\n if (estack[0] === undefined) {\r\n\r\n /* ignoring text outside of elements */\r\n\r\n } else if (estack[0] instanceof Span || estack[0] instanceof P) {\r\n\r\n /* create an anonymous span */\r\n\r\n var s = new AnonymousSpan();\r\n\r\n s.initFromText(doc, estack[0], str, xmlspacestack[0], errorHandler);\r\n\r\n estack[0].contents.push(s);\r\n\r\n } else if (estack[0] instanceof ForeignElement &&\r\n metadata_depth > 0 &&\r\n metadataHandler &&\r\n 'onText' in metadataHandler) {\r\n\r\n /* text node within a child of metadata element */\r\n\r\n metadataHandler.onText(str);\r\n\r\n }\r\n\r\n };\r\n\r\n\r\n p.onopentag = function (node) {\r\n\r\n // maintain the xml:space stack\r\n\r\n var xmlspace = node.attributes[\"xml:space\"];\r\n\r\n if (xmlspace) {\r\n\r\n xmlspacestack.unshift(xmlspace.value);\r\n\r\n } else {\r\n\r\n if (xmlspacestack.length === 0) {\r\n\r\n xmlspacestack.unshift(\"default\");\r\n\r\n } else {\r\n\r\n xmlspacestack.unshift(xmlspacestack[0]);\r\n\r\n }\r\n\r\n }\r\n\r\n /* maintain the xml:lang stack */\r\n\r\n\r\n var xmllang = node.attributes[\"xml:lang\"];\r\n\r\n if (xmllang) {\r\n\r\n xmllangstack.unshift(xmllang.value);\r\n\r\n } else {\r\n\r\n if (xmllangstack.length === 0) {\r\n\r\n xmllangstack.unshift(\"\");\r\n\r\n } else {\r\n\r\n xmllangstack.unshift(xmllangstack[0]);\r\n\r\n }\r\n\r\n }\r\n\r\n\r\n /* process the element */\r\n\r\n if (node.uri === imscNames.ns_tt) {\r\n\r\n if (node.local === 'tt') {\r\n\r\n if (doc !== null) {\r\n\r\n reportFatal(errorHandler, \"Two <tt> elements at (\" + this.line + \",\" + this.column + \")\");\r\n\r\n }\r\n\r\n doc = new TT();\r\n\r\n doc.initFromNode(node, errorHandler);\r\n\r\n estack.unshift(doc);\r\n\r\n } else if (node.local === 'head') {\r\n\r\n if (!(estack[0] instanceof TT)) {\r\n reportFatal(errorHandler, \"Parent of <head> element is not <tt> at (\" + this.line + \",\" + this.column + \")\");\r\n }\r\n\r\n if (doc.head !== null) {\r\n reportFatal(\"Second <head> element at (\" + this.line + \",\" + this.column + \")\");\r\n }\r\n\r\n doc.head = new Head();\r\n\r\n estack.unshift(doc.head);\r\n\r\n } else if (node.local === 'styling') {\r\n\r\n if (!(estack[0] instanceof Head)) {\r\n reportFatal(errorHandler, \"Parent of <styling> element is not <head> at (\" + this.line + \",\" + this.column + \")\");\r\n }\r\n\r\n if (doc.head.styling !== null) {\r\n reportFatal(\"Second <styling> element at (\" + this.line + \",\" + this.column + \")\");\r\n }\r\n\r\n doc.head.styling = new Styling();\r\n\r\n estack.unshift(doc.head.styling);\r\n\r\n } else if (node.local === 'style') {\r\n\r\n var s;\r\n\r\n if (estack[0] instanceof Styling) {\r\n\r\n s = new Style();\r\n\r\n s.initFromNode(node, errorHandler);\r\n\r\n /* ignore <style> element missing @id */\r\n\r\n if (!s.id) {\r\n\r\n reportError(errorHandler, \"<style> element missing @id attribute\");\r\n\r\n } else {\r\n\r\n doc.head.styling.styles[s.id] = s;\r\n\r\n }\r\n\r\n estack.unshift(s);\r\n\r\n } else if (estack[0] instanceof Region) {\r\n\r\n /* nested styles can be merged with specified styles\r\n * immediately, with lower priority\r\n * (see 8.4.4.2(3) at TTML1 )\r\n */\r\n\r\n s = new Style();\r\n\r\n s.initFromNode(node, errorHandler);\r\n\r\n mergeStylesIfNotPresent(s.styleAttrs, estack[0].styleAttrs);\r\n\r\n estack.unshift(s);\r\n\r\n } else {\r\n\r\n reportFatal(errorHandler, \"Parent of <style> element is not <styling> or <region> at (\" + this.line + \",\" + this.column + \")\");\r\n\r\n }\r\n\r\n } else if (node.local === 'layout') {\r\n\r\n if (!(estack[0] instanceof Head)) {\r\n\r\n reportFatal(errorHandler, \"Parent of <layout> element is not <head> at \" + this.line + \",\" + this.column + \")\");\r\n\r\n }\r\n\r\n if (doc.head.layout !== null) {\r\n\r\n reportFatal(errorHandler, \"Second <layout> element at \" + this.line + \",\" + this.column + \")\");\r\n\r\n }\r\n\r\n doc.head.layout = new Layout();\r\n\r\n estack.unshift(doc.head.layout);\r\n\r\n } else if (node.local === 'region') {\r\n\r\n if (!(estack[0] instanceof Layout)) {\r\n reportFatal(errorHandler, \"Parent of <region> element is not <layout> at \" + this.line + \",\" + this.column + \")\");\r\n }\r\n\r\n var r = new Region();\r\n\r\n r.initFromNode(doc, node, errorHandler);\r\n\r\n if (!r.id || r.id in doc.head.layout.regions) {\r\n\r\n reportError(errorHandler, \"Ignoring <region> with duplicate or missing @id at \" + this.line + \",\" + this.column + \")\");\r\n\r\n } else {\r\n\r\n doc.head.layout.regions[r.id] = r;\r\n\r\n }\r\n\r\n estack.unshift(r);\r\n\r\n } else if (node.local === 'body') {\r\n\r\n if (!(estack[0] instanceof TT)) {\r\n\r\n reportFatal(errorHandler, \"Parent of <body> element is not <tt> at \" + this.line + \",\" + this.column + \")\");\r\n\r\n }\r\n\r\n if (doc.body !== null) {\r\n\r\n reportFatal(errorHandler, \"Second <body> element at \" + this.line + \",\" + this.column + \")\");\r\n\r\n }\r\n\r\n var b = new Body();\r\n\r\n b.initFromNode(doc, node, errorHandler);\r\n\r\n doc.body = b;\r\n\r\n estack.unshift(b);\r\n\r\n } else if (node.local === 'div') {\r\n\r\n if (!(estack[0] instanceof Div || estack[0] instanceof Body)) {\r\n\r\n reportFatal(errorHandler, \"Parent of <div> element is not <body> or <div> at \" + this.line + \",\" + this.column + \")\");\r\n\r\n }\r\n\r\n var d = new Div();\r\n\r\n d.initFromNode(doc, estack[0], node, errorHandler);\r\n\r\n estack[0].contents.push(d);\r\n\r\n estack.unshift(d);\r\n\r\n } else if (node.local === 'p') {\r\n\r\n if (!(estack[0] instanceof Div)) {\r\n\r\n reportFatal(errorHandler, \"Parent of <p> element is not <div> at \" + this.line + \",\" + this.column + \")\");\r\n\r\n }\r\n\r\n var p = new P();\r\n\r\n p.initFromNode(doc, estack[0], node, errorHandler);\r\n\r\n estack[0].contents.push(p);\r\n\r\n estack.unshift(p);\r\n\r\n } else if (node.local === 'span') {\r\n\r\n if (!(estack[0] instanceof Span || estack[0] instanceof P)) {\r\n\r\n reportFatal(errorHandler, \"Parent of <span> element is not <span> or <p> at \" + this.line + \",\" + this.column + \")\");\r\n\r\n }\r\n\r\n var ns = new Span();\r\n\r\n ns.initFromNode(doc, estack[0], node, xmlspacestack[0], errorHandler);\r\n\r\n estack[0].contents.push(ns);\r\n\r\n estack.unshift(ns);\r\n\r\n } else if (node.local === 'br') {\r\n\r\n if (!(estack[0] instanceof Span || estack[0] instanceof P)) {\r\n\r\n reportFatal(errorHandler, \"Parent of <br> element is not <span> or <p> at \" + this.line + \",\" + this.column + \")\");\r\n\r\n }\r\n\r\n var nb = new Br();\r\n\r\n nb.initFromNode(doc, estack[0], node, errorHandler);\r\n\r\n estack[0].contents.push(nb);\r\n\r\n estack.unshift(nb);\r\n\r\n } else if (node.local === 'set') {\r\n\r\n if (!(estack[0] instanceof Span ||\r\n estack[0] instanceof P ||\r\n estack[0] instanceof Div ||\r\n estack[0] instanceof Body ||\r\n estack[0] instanceof Region ||\r\n estack[0] instanceof Br)) {\r\n\r\n reportFatal(errorHandler, \"Parent of <set> element is not a content element or a region at \" + this.line + \",\" + this.column + \")\");\r\n\r\n }\r\n\r\n var st = new Set();\r\n\r\n st.initFromNode(doc, estack[0], node, errorHandler);\r\n\r\n estack[0].sets.push(st);\r\n\r\n estack.unshift(st);\r\n\r\n } else {\r\n\r\n /* element in the TT namespace, but not a content element */\r\n\r\n estack.unshift(new ForeignElement(node));\r\n }\r\n\r\n } else {\r\n\r\n /* ignore elements not in the TTML namespace unless in metadata element */\r\n\r\n estack.unshift(new ForeignElement(node));\r\n\r\n }\r\n\r\n /* handle metadata callbacks */\r\n\r\n if (estack[0] instanceof ForeignElement) {\r\n\r\n if (node.uri === imscNames.ns_tt &&\r\n node.local === 'metadata') {\r\n\r\n /* enter the metadata element */\r\n\r\n metadata_depth++;\r\n\r\n } else if (\r\n metadata_depth > 0 &&\r\n metadataHandler &&\r\n 'onOpenTag' in metadataHandler\r\n ) {\r\n\r\n /* start of child of metadata element */\r\n\r\n var attrs = [];\r\n\r\n for (var a in node.attributes) {\r\n attrs[node.attributes[a].uri + \" \" + node.attributes[a].local] =\r\n {\r\n uri: node.attributes[a].uri,\r\n local: node.attributes[a].local,\r\n value: node.attributes[a].value\r\n };\r\n }\r\n\r\n metadataHandler.onOpenTag(node.uri, node.local, attrs);\r\n\r\n }\r\n\r\n }\r\n\r\n };\r\n\r\n // parse the document\r\n\r\n p.write(xmlstring).close();\r\n\r\n // all referential styling has been flatten, so delete the styling elements if there is a head\r\n // otherwise create an empty head\r\n\r\n if (doc.head !== null) {\r\n delete doc.head.styling;\r\n } else {\r\n doc.head = new Head();\r\n }\r\n\r\n // create default region if no regions specified\r\n\r\n if (doc.head.layout === null) {\r\n\r\n doc.head.layout = new Layout();\r\n\r\n }\r\n\r\n var hasRegions = false;\r\n\r\n /* AFAIK the only way to determine whether an object has members */\r\n\r\n for (var i in doc.head.layout.regions) {\r\n\r\n hasRegions = true;\r\n\r\n break;\r\n\r\n }\r\n\r\n if (!hasRegions) {\r\n\r\n /* create default region */\r\n\r\n var dr = Region.prototype.createDefaultRegion();\r\n\r\n doc.head.layout.regions[dr.id] = dr;\r\n\r\n }\r\n\r\n /* resolve desired timing for regions */\r\n\r\n for (var region_i in doc.head.layout.regions) {\r\n\r\n resolveTiming(doc, doc.head.layout.regions[region_i], null, null);\r\n\r\n }\r\n\r\n /* resolve desired timing for content elements */\r\n\r\n if (doc.body) {\r\n resolveTiming(doc, doc.body, null, null);\r\n }\r\n\r\n return doc;\r\n };\r\n\r\n function resolveTiming(doc, element, prev_sibling, parent) {\r\n\r\n /* are we in a seq container? */\r\n\r\n var isinseq = parent && parent.timeContainer === \"seq\";\r\n\r\n /* determine implicit begin */\r\n\r\n var implicit_begin = 0; /* default */\r\n\r\n if (parent) {\r\n\r\n if (isinseq && prev_sibling) {\r\n\r\n /*\r\n * if seq time container, offset from the previous sibling end\r\n */\r\n\r\n implicit_begin = prev_sibling.end;\r\n\r\n\r\n } else {\r\n\r\n implicit_begin = parent.begin;\r\n\r\n }\r\n\r\n }\r\n\r\n /* compute desired begin */\r\n\r\n element.begin = element.explicit_begin ? element.explicit_begin + implicit_begin : implicit_begin;\r\n\r\n\r\n /* determine implicit end */\r\n\r\n var implicit_end = element.begin;\r\n\r\n var s = null;\r\n\r\n for (var set_i in element.sets) {\r\n\r\n resolveTiming(doc, element.sets[set_i], s, element);\r\n\r\n if (element.timeContainer === \"seq\") {\r\n\r\n implicit_end = element.sets[set_i].end;\r\n\r\n } else {\r\n\r\n implicit_end = Math.max(implicit_end, element.sets[set_i].end);\r\n\r\n }\r\n\r\n s = element.sets[set_i];\r\n\r\n }\r\n\r\n if (!('contents' in element)) {\r\n\r\n /* anonymous spans and regions and <set> and <br>s and spans with only children text nodes */\r\n\r\n if (isinseq) {\r\n\r\n /* in seq container, implicit duration is zero */\r\n\r\n implicit_end = element.begin;\r\n\r\n } else {\r\n\r\n /* in par container, implicit duration is indefinite */\r\n\r\n implicit_end = Number.POSITIVE_INFINITY;\r\n\r\n }\r\n\r\n } else {\r\n\r\n for (var content_i in element.contents) {\r\n\r\n resolveTiming(doc, element.contents[content_i], s, element);\r\n\r\n if (element.timeContainer === \"seq\") {\r\n\r\n implicit_end = element.contents[content_i].end;\r\n\r\n } else {\r\n\r\n implicit_end = Math.max(implicit_end, element.contents[content_i].end);\r\n\r\n }\r\n\r\n s = element.contents[content_i];\r\n\r\n }\r\n\r\n }\r\n\r\n /* determine desired end */\r\n /* it is never made really clear in SMIL that the explicit end is offset by the implicit begin */\r\n\r\n if (element.explicit_end !== null && element.explicit_dur !== null) {\r\n\r\n element.end = Math.min(element.begin + element.explicit_dur, implicit_begin + element.explicit_end);\r\n\r\n } else if (element.explicit_end === null && element.explicit_dur !== null) {\r\n\r\n element.end = element.begin + element.explicit_dur;\r\n\r\n } else if (element.explicit_end !== null && element.explicit_dur === null) {\r\n\r\n element.end = implicit_begin + element.explicit_end;\r\n\r\n } else {\r\n\r\n element.end = implicit_end;\r\n }\r\n\r\n delete element.explicit_begin;\r\n delete element.explicit_dur;\r\n delete element.explicit_end;\r\n\r\n doc._registerEvent(element);\r\n\r\n }\r\n\r\n function ForeignElement(node) {\r\n this.node = node;\r\n }\r\n\r\n function TT() {\r\n this.events = [];\r\n this.head = null;\r\n this.body = null;\r\n }\r\n\r\n TT.prototype.initFromNode = function (node, errorHandler) {\r\n\r\n /* compute cell resolution */\r\n\r\n this.cellResolution = extractCellResolution(node, errorHandler);\r\n\r\n /* extract frame rate and tick rate */\r\n\r\n var frtr = extractFrameAndTickRate(node, errorHandler);\r\n\r\n this.effectiveFrameRate = frtr.effectiveFrameRate;\r\n\r\n this.tickRate = frtr.tickRate;\r\n\r\n /* extract aspect ratio */\r\n\r\n this.aspectRatio = extractAspectRatio(node, errorHandler);\r\n\r\n /* check timebase */\r\n\r\n var attr = findAttribute(node, imscNames.ns_ttp, \"timeBase\");\r\n\r\n if (attr !== null && attr !== \"media\") {\r\n\r\n reportFatal(errorHandler, \"Unsupported time base\");\r\n\r\n }\r\n\r\n /* retrieve extent */\r\n\r\n var e = extractExtent(node, errorHandler);\r\n\r\n if (e === null) {\r\n\r\n /* TODO: remove once unit tests are ready */\r\n\r\n this.pxDimensions = {'h': 480, 'w': 640};\r\n\r\n } else {\r\n\r\n if (e.h.unit !== \"px\" || e.w.unit !== \"px\") {\r\n reportFatal(errorHandler, \"Extent on TT must be in px or absent\");\r\n }\r\n\r\n this.pxDimensions = {'h': e.h.value, 'w': e.w.value};\r\n }\r\n\r\n };\r\n\r\n /* register a temporal events */\r\n TT.prototype._registerEvent = function (elem) {\r\n\r\n /* skip if begin is not < then end */\r\n\r\n if (elem.end <= elem.begin)\r\n return;\r\n\r\n /* index the begin time of the event */\r\n\r\n var b_i = indexOf(this.events, elem.begin);\r\n\r\n if (!b_i.found) {\r\n this.events.splice(b_i.index, 0, elem.begin);\r\n }\r\n\r\n /* index the end time of the event */\r\n\r\n if (elem.end !== Number.POSITIVE_INFINITY) {\r\n\r\n var e_i = indexOf(this.events, elem.end);\r\n\r\n if (!e_i.found) {\r\n this.events.splice(e_i.index, 0, elem.end);\r\n }\r\n\r\n }\r\n\r\n };\r\n\r\n\r\n /*\r\n * Retrieves the range of ISD times covered by the document\r\n * \r\n * @returns {Array} Array of two elements: min_begin_time and max_begin_time\r\n * \r\n */\r\n TT.prototype.getMediaTimeRange = function () {\r\n\r\n return [this.events[0], this.events[this.events.length - 1]];\r\n };\r\n\r\n /*\r\n * Returns list of ISD begin times \r\n * \r\n * @returns {Array}\r\n */\r\n TT.prototype.getMediaTimeEvents = function () {\r\n\r\n return this.events;\r\n };\r\n\r\n /*\r\n * Represents a TTML Head element\r\n */\r\n\r\n function Head() {\r\n this.styling = null;\r\n this.layout = null;\r\n }\r\n\r\n /*\r\n * Represents a TTML Styling element\r\n */\r\n\r\n function Styling() {\r\n this.styles = {};\r\n }\r\n\r\n /*\r\n * Represents a TTML Style element\r\n */\r\n\r\n function Style() {\r\n this.id = null;\r\n this.styleAttrs = null;\r\n this.styleRefs = null;\r\n }\r\n\r\n Style.prototype.initFromNode = function (node, errorHandler) {\r\n this.id = elementGetXMLID(node);\r\n this.styleAttrs = elementGetStyles(node, errorHandler);\r\n this.styleRefs = elementGetStyleRefs(node);\r\n };\r\n\r\n /*\r\n * Represents a TTML Layout element\r\n * \r\n */\r\n\r\n function Layout() {\r\n this.regions = {};\r\n }\r\n\r\n /*\r\n * TTML element utility functions\r\n * \r\n */\r\n\r\n function ContentElement(kind) {\r\n this.kind = kind;\r\n }\r\n\r\n function IdentifiedElement(id) {\r\n this.id = id;\r\n }\r\n\r\n IdentifiedElement.prototype.initFromNode = function (doc, parent, node, errorHandler) {\r\n this.id = elementGetXMLID(node);\r\n };\r\n\r\n function LayoutElement(id) {\r\n this.regionID = id;\r\n }\r\n\r\n LayoutElement.prototype.initFromNode = function (doc, parent, node, errorHandler) {\r\n this.regionID = elementGetRegionID(node);\r\n };\r\n\r\n function StyledElement(styleAttrs) {\r\n this.styleAttrs = styleAttrs;\r\n }\r\n\r\n StyledElement.prototype.initFromNode = function (doc, parent, node, errorHandler) {\r\n\r\n this.styleAttrs = elementGetStyles(node, errorHandler);\r\n\r\n if (doc.head !== null && doc.head.styling !== null) {\r\n mergeReferencedStyles(doc.head.styling, elementGetStyleRefs(node), this.styleAttrs, errorHandler);\r\n }\r\n\r\n };\r\n\r\n function AnimatedElement(sets) {\r\n this.sets = sets;\r\n }\r\n\r\n AnimatedElement.prototype.initFromNode = function (doc, parent, node, errorHandler) {\r\n this.sets = [];\r\n };\r\n\r\n function ContainerElement(contents) {\r\n this.contents = contents;\r\n }\r\n\r\n ContainerElement.prototype.initFromNode = function (doc, parent, node, errorHandler) {\r\n this.contents = [];\r\n };\r\n\r\n function TimedElement(explicit_begin, explicit_end, explicit_dur) {\r\n this.explicit_begin = explicit_begin;\r\n this.explicit_end = explicit_end;\r\n this.explicit_dur = explicit_dur;\r\n }\r\n\r\n TimedElement.prototype.initFromNode = function (doc, parent, node, errorHandler) {\r\n var t = processTiming(doc, parent, node, errorHandler);\r\n this.explicit_begin = t.explicit_begin;\r\n this.explicit_end = t.explicit_end;\r\n this.explicit_dur = t.explicit_dur;\r\n\r\n this.timeContainer = elementGetTimeContainer(node, errorHandler);\r\n };\r\n\r\n\r\n /*\r\n * Represents a TTML body element\r\n */\r\n\r\n\r\n\r\n function Body() {\r\n ContentElement.call(this, 'body');\r\n }\r\n\r\n\r\n Body.prototype.initFromNode = function (doc, node, errorHandler) {\r\n StyledElement.prototype.initFromNode.call(this, doc, null, node, errorHandler);\r\n TimedElement.prototype.initFromNode.call(this, doc, null, node, errorHandler);\r\n AnimatedElement.prototype.initFromNode.call(this, doc, null, node, errorHandler);\r\n LayoutElement.prototype.initFromNode.call(this, doc, null, node, errorHandler);\r\n ContainerElement.prototype.initFromNode.call(this, doc, null, node, errorHandler);\r\n };\r\n\r\n /*\r\n * Represents a TTML div element\r\n */\r\n\r\n function Div() {\r\n ContentElement.call(this, 'div');\r\n }\r\n\r\n Div.prototype.initFromNode = function (doc, parent, node, errorHandler) {\r\n StyledElement.prototype.initFromNode.call(this, doc, parent, node, errorHandler);\r\n TimedElement.prototype.initFromNode.call(this, doc, parent, node, errorHandler);\r\n AnimatedElement.prototype.initFromNode.call(this, doc, parent, node, errorHandler);\r\n LayoutElement.prototype.initFromNode.call(this, doc, parent, node, errorHandler);\r\n ContainerElement.prototype.initFromNode.call(this, doc, parent, node, errorHandler);\r\n };\r\n\r\n /*\r\n * Represents a TTML p element\r\n */\r\n\r\n function P() {\r\n ContentElement.call(this, 'p');\r\n }\r\n\r\n P.prototype.initFromNode = function (doc, parent, node, errorHandler) {\r\n StyledElement.prototype.initFromNode.call(this, doc, parent, node, errorHandler);\r\n TimedElement.prototype.initFromNode.call(this, doc, parent, node, errorHandler);\r\n AnimatedElement.prototype.initFromNode.call(this, doc, parent, node, errorHandler);\r\n LayoutElement.prototype.initFromNode.call(this, doc, parent, node, errorHandler);\r\n ContainerElement.prototype.initFromNode.call(this, doc, parent, node, errorHandler);\r\n };\r\n\r\n /*\r\n * Represents a TTML span element\r\n */\r\n\r\n function Span() {\r\n ContentElement.call(this, 'span');\r\n }\r\n\r\n Span.prototype.initFromNode = function (doc, parent, node, xmlspace, errorHandler) {\r\n StyledElement.prototype.initFromNode.call(this, doc, parent, node, errorHandler);\r\n TimedElement.prototype.initFromNode.call(this, doc, parent, node, errorHandler);\r\n AnimatedElement.prototype.initFromNode.call(this, doc, parent, node, errorHandler);\r\n LayoutElement.prototype.initFromNode.call(this, doc, parent, node, errorHandler);\r\n ContainerElement.prototype.initFromNode.call(this, doc, parent, node, errorHandler);\r\n\r\n this.space = xmlspace;\r\n };\r\n\r\n /*\r\n * Represents a TTML anonymous span element\r\n */\r\n\r\n function AnonymousSpan() {\r\n ContentElement.call(this, 'span');\r\n }\r\n\r\n AnonymousSpan.prototype.initFromText = function (doc, parent, text, xmlspace, errorHandler) {\r\n TimedElement.prototype.initFromNode.call(this, doc, parent, null, errorHandler);\r\n\r\n this.text = text;\r\n this.space = xmlspace;\r\n };\r\n\r\n /*\r\n * Represents a TTML br element\r\n */\r\n\r\n function Br() {\r\n ContentElement.call(this, 'br');\r\n }\r\n\r\n Br.prototype.initFromNode = function (doc, parent, node, errorHandler) {\r\n LayoutElement.prototype.initFromNode.call(this, doc, parent, node, errorHandler);\r\n TimedElement.prototype.initFromNode.call(this, doc, parent, node, errorHandler);\r\n };\r\n\r\n /*\r\n * Represents a TTML Region element\r\n * \r\n */\r\n\r\n function Region() {\r\n }\r\n\r\n Region.prototype.createDefaultRegion = function () {\r\n var r = new Region();\r\n\r\n IdentifiedElement.call(r, '');\r\n StyledElement.call(r, {});\r\n AnimatedElement.call(r, []);\r\n TimedElement.call(r, 0, Number.POSITIVE_INFINITY, null);\r\n\r\n return r;\r\n };\r\n\r\n Region.prototype.initFromNode = function (doc, node, errorHandler) {\r\n IdentifiedElement.prototype.initFromNode.call(this, doc, null, node, errorHandler);\r\n StyledElement.prototype.initFromNode.call(this, doc, null, node, errorHandler);\r\n TimedElement.prototype.initFromNode.call(this, doc, null, node, errorHandler);\r\n AnimatedElement.prototype.initFromNode.call(this, doc, null, node, errorHandler);\r\n\r\n /* immediately merge referenced styles */\r\n\r\n if (doc.head !== null && doc.head.styling !== null) {\r\n mergeReferencedStyles(doc.head.styling, elementGetStyleRefs(node), this.styleAttrs, errorHandler);\r\n }\r\n\r\n };\r\n\r\n /*\r\n * Represents a TTML Set element\r\n * \r\n */\r\n\r\n function Set() {\r\n }\r\n\r\n Set.prototype.initFromNode = function (doc, parent, node, errorHandler) {\r\n\r\n TimedElement.prototype.initFromNode.call(this, doc, parent, node, errorHandler);\r\n\r\n var styles = elementGetStyles(node, errorHandler);\r\n\r\n this.qname = null;\r\n this.value = null;\r\n\r\n for (var qname in styles) {\r\n\r\n if (this.qname) {\r\n\r\n reportError(errorHandler, \"More than one style specified on set\");\r\n break;\r\n\r\n }\r\n\r\n this.qname = qname;\r\n this.value = styles[qname];\r\n\r\n }\r\n\r\n };\r\n\r\n /*\r\n * Utility functions\r\n * \r\n */\r\n\r\n\r\n function elementGetXMLID(node) {\r\n return node && 'xml:id' in node.attributes ? node.attributes['xml:id'].value || null : null;\r\n }\r\n\r\n function elementGetRegionID(node) {\r\n return node && 'region' in node.attributes ? node.attributes.region.value : '';\r\n }\r\n\r\n function elementGetTimeContainer(node, errorHandler) {\r\n\r\n var tc = node && 'timeContainer' in node.attributes ? node.attributes.timeContainer.value : null;\r\n\r\n if ((!tc) || tc === \"par\") {\r\n\r\n return \"par\";\r\n\r\n } else if (tc === \"seq\") {\r\n\r\n return \"seq\";\r\n\r\n } else {\r\n\r\n reportError(errorHandler, \"Illegal value of timeContainer (assuming 'par')\");\r\n\r\n return \"par\";\r\n\r\n }\r\n\r\n }\r\n\r\n function elementGetStyleRefs(node) {\r\n\r\n return node && 'style' in node.attributes ? node.attributes.style.value.split(\" \") : [];\r\n\r\n }\r\n\r\n function elementGetStyles(node, errorHandler) {\r\n\r\n var s = {};\r\n\r\n if (node !== null) {\r\n\r\n for (var i in node.attributes) {\r\n\r\n var qname = node.attributes[i].uri + \" \" + node.attributes[i].local;\r\n\r\n var sa = imscStyles.byQName[qname];\r\n\r\n if (sa !== undefined) {\r\n\r\n var val = sa.parse(node.attributes[i].value);\r\n\r\n if (val !== null) {\r\n\r\n s[qname] = val;\r\n\r\n /* TODO: consider refactoring errorHandler into parse and compute routines */\r\n\r\n if (sa === imscStyles.byName.zIndex) {\r\n reportWarning(errorHandler, \"zIndex attribute present but not used by IMSC1 since regions do not overlap\");\r\n }\r\n\r\n } else {\r\n\r\n reportError(errorHandler, \"Cannot parse styling attribute \" + qname + \" --> \" + node.attributes[i].value);\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n return s;\r\n }\r\n\r\n function findAttribute(node, ns, name) {\r\n for (var i in node.attributes) {\r\n\r\n if (node.attributes[i].uri === ns &&\r\n node.attributes[i].local === name) {\r\n\r\n return node.attributes[i].value;\r\n }\r\n }\r\n\r\n return null;\r\n }\r\n\r\n function extractAspectRatio(node, errorHandler) {\r\n\r\n var ar = findAttribute(node, imscNames.ns_ittp, \"aspectRatio\");\r\n\r\n var rslt = null;\r\n\r\n if (ar !== null) {\r\n\r\n var ASPECT_RATIO_RE = /(\\d+) (\\d+)/;\r\n\r\n var m = ASPECT_RATIO_RE.exec(ar);\r\n\r\n if (m !== null) {\r\n\r\n var w = parseInt(m[1]);\r\n\r\n var h = parseInt(m[2]);\r\n\r\n if (w !== 0 && h !== 0) {\r\n\r\n rslt = w / h;\r\n\r\n } else {\r\n\r\n reportError(errorHandler, \"Illegal aspectRatio values (ignoring)\");\r\n }\r\n\r\n } else {\r\n\r\n reportError(errorHandler, \"Malformed aspectRatio attribute (ignoring)\");\r\n }\r\n\r\n }\r\n\r\n return rslt;\r\n\r\n }\r\n\r\n /*\r\n * Returns the cellResolution attribute from a node\r\n * \r\n */\r\n function extractCellResolution(node, errorHandler) {\r\n\r\n var cr = findAttribute(node, imscNames.ns_ttp, \"cellResolution\");\r\n\r\n // initial value\r\n\r\n var h = 15;\r\n var w = 32;\r\n\r\n if (cr !== null) {\r\n\r\n var CELL_RESOLUTION_RE = /(\\d+) (\\d+)/;\r\n\r\n var m = CELL_RESOLUTION_RE.exec(cr);\r\n\r\n if (m !== null) {\r\n\r\n w = parseInt(m[1]);\r\n\r\n h = parseInt(m[2]);\r\n\r\n } else {\r\n\r\n reportWarning(errorHandler, \"Malformed cellResolution value (using initial value instead)\");\r\n\r\n }\r\n\r\n }\r\n\r\n return {'w': w, 'h': h};\r\n\r\n }\r\n\r\n\r\n function extractFrameAndTickRate(node, errorHandler) {\r\n\r\n // subFrameRate is ignored per IMSC1 specification\r\n\r\n // extract frame rate\r\n\r\n var fps_attr = findAttribute(node, imscNames.ns_ttp, \"frameRate\");\r\n\r\n // initial value\r\n\r\n var fps = 30;\r\n\r\n // match variable\r\n\r\n var m;\r\n\r\n if (fps_attr !== null) {\r\n\r\n var FRAME_RATE_RE = /(\\d+)/;\r\n\r\n m = FRAME_RATE_RE.exec(fps_attr);\r\n\r\n if (m !== null) {\r\n\r\n fps = parseInt(m[1]);\r\n\r\n } else {\r\n\r\n reportWarning(errorHandler, \"Malformed frame rate attribute (using initial value instead)\");\r\n }\r\n\r\n }\r\n\r\n // extract frame rate multiplier\r\n\r\n var frm_attr = findAttribute(node, imscNames.ns_ttp, \"frameRateMultiplier\");\r\n\r\n // initial value\r\n\r\n var frm = 1;\r\n\r\n if (frm_attr !== null) {\r\n\r\n var FRAME_RATE_MULT_RE = /(\\d+) (\\d+)/;\r\n\r\n m = FRAME_RATE_MULT_RE.exec(frm_attr);\r\n\r\n if (m !== null) {\r\n\r\n frm = parseInt(m[1]) / parseInt(m[2]);\r\n\r\n } else {\r\n\r\n reportWarning(errorHandler, \"Malformed frame rate multiplier attribute (using initial value instead)\");\r\n }\r\n\r\n }\r\n\r\n var efps = frm * fps;\r\n\r\n // extract tick rate\r\n\r\n var tr = 1;\r\n\r\n var trattr = findAttribute(node, imscNames.ns_ttp, \"tickRate\");\r\n\r\n if (trattr === null) {\r\n\r\n if (fps_attr !== null)\r\n tr = efps;\r\n\r\n } else {\r\n\r\n var TICK_RATE_RE = /(\\d+)/;\r\n\r\n m = TICK_RATE_RE.exec(trattr);\r\n\r\n if (m !== null) {\r\n\r\n tr = parseInt(m[1]);\r\n\r\n } else {\r\n\r\n reportWarning(errorHandler, \"Malformed tick rate attribute (using initial value instead)\");\r\n }\r\n\r\n }\r\n\r\n return {effectiveFrameRate: efps, tickRate: tr};\r\n\r\n }\r\n\r\n function extractExtent(node, errorHandler) {\r\n\r\n var attr = findAttribute(node, imscNames.ns_tts, \"extent\");\r\n\r\n if (attr === null)\r\n return null;\r\n\r\n var s = attr.split(\" \");\r\n\r\n if (s.length !== 2) {\r\n\r\n reportWarning(errorHandler, \"Malformed extent (ignoring)\");\r\n\r\n return null;\r\n }\r\n\r\n var w = imscUtils.parseLength(s[0]);\r\n\r\n var h = imscUtils.parseLength(s[1]);\r\n\r\n if (!h || !w) {\r\n\r\n reportWarning(errorHandler, \"Malformed extent values (ignoring)\");\r\n\r\n return null;\r\n }\r\n\r\n return {'h': h, 'w': w};\r\n\r\n }\r\n\r\n function parseTimeExpression(tickRate, effectiveFrameRate, str) {\r\n\r\n var CLOCK_TIME_FRACTION_RE = /^(\\d{2,}):(\\d\\d):(\\d\\d(?:\\.\\d+)?)$/;\r\n var CLOCK_TIME_FRAMES_RE = /^(\\d{2,}):(\\d\\d):(\\d\\d)\\:(\\d{2,})$/;\r\n var OFFSET_FRAME_RE = /^(\\d+(?:\\.\\d+)?)f$/;\r\n var OFFSET_TICK_RE = /^(\\d+(?:\\.\\d+)?)t$/;\r\n var OFFSET_MS_RE = /^(\\d+(?:\\.\\d+)?)ms$/;\r\n var OFFSET_S_RE = /^(\\d+(?:\\.\\d+)?)s$/;\r\n var OFFSET_H_RE = /^(\\d+(?:\\.\\d+)?)h$/;\r\n var OFFSET_M_RE = /^(\\d+(?:\\.\\d+)?)m$/;\r\n var m;\r\n var r = null;\r\n if ((m = OFFSET_FRAME_RE.exec(str)) !== null) {\r\n\r\n if (effectiveFrameRate !== null) {\r\n\r\n r = parseFloat(m[1]) / effectiveFrameRate;\r\n }\r\n\r\n } else if ((m = OFFSET_TICK_RE.exec(str)) !== null) {\r\n\r\n if (tickRate !== null) {\r\n\r\n r = parseFloat(m[1]) / tickRate;\r\n }\r\n\r\n } else if ((m = OFFSET_MS_RE.exec(str)) !== null) {\r\n\r\n r = parseFloat(m[1]) / 1000.0;\r\n\r\n } else if ((m = OFFSET_S_RE.exec(str)) !== null) {\r\n\r\n r = parseFloat(m[1]);\r\n\r\n } else if ((m = OFFSET_H_RE.exec(str)) !== null) {\r\n\r\n r = parseFloat(m[1]) * 3600.0;\r\n\r\n } else if ((m = OFFSET_M_RE.exec(str)) !== null) {\r\n\r\n r = parseFloat(m[1]) * 60.0;\r\n\r\n } else if ((m = CLOCK_TIME_FRACTION_RE.exec(str)) !== null) {\r\n\r\n r = parseInt(m[1]) * 3600 +\r\n parseInt(m[2]) * 60 +\r\n parseFloat(m[3]);\r\n\r\n } else if ((m = CLOCK_TIME_FRAMES_RE.exec(str)) !== null) {\r\n\r\n /* this assumes that HH:MM:SS is a clock-time-with-fraction */\r\n\r\n if (effectiveFrameRate !== null) {\r\n\r\n r = parseInt(m[1]) * 3600 +\r\n parseInt(m[2]) * 60 +\r\n parseInt(m[3]) +\r\n (m[4] === null ? 0 : parseInt(m[4]) / effectiveFrameRate);\r\n }\r\n\r\n }\r\n\r\n return r;\r\n }\r\n\r\n function processTiming(doc, parent, node, errorHandler) {\r\n\r\n /* determine explicit begin */\r\n\r\n var explicit_begin = null;\r\n\r\n if (node && 'begin' in node.attributes) {\r\n\r\n explicit_begin = parseTimeExpression(doc.tickRate, doc.effectiveFrameRate, node.attributes.begin.value);\r\n\r\n if (explicit_begin === null) {\r\n\r\n reportWarning(errorHandler, \"Malformed begin value \" + node.attributes.begin.value + \" (using 0)\");\r\n\r\n }\r\n\r\n }\r\n\r\n /* determine explicit duration */\r\n\r\n var explicit_dur = null;\r\n\r\n if (node && 'dur' in node.attributes) {\r\n\r\n explicit_dur = parseTimeExpression(doc.tickRate, doc.effectiveFrameRate, node.attributes.dur.value);\r\n\r\n if (explicit_dur === null) {\r\n\r\n reportWarning(errorHandler, \"Malformed dur value \" + node.attributes.dur.value + \" (ignoring)\");\r\n\r\n }\r\n\r\n }\r\n\r\n /* determine explicit end */\r\n\r\n var explicit_end = null;\r\n\r\n if (node && 'end' in node.attributes) {\r\n\r\n explicit_end = parseTimeExpression(doc.tickRate, doc.effectiveFrameRate, node.attributes.end.value);\r\n\r\n if (explicit_end === null) {\r\n\r\n reportWarning(errorHandler, \"Malformed end value (ignoring)\");\r\n\r\n }\r\n\r\n }\r\n\r\n return {explicit_begin: explicit_begin,\r\n explicit_end: explicit_end,\r\n explicit_dur: explicit_dur};\r\n\r\n }\r\n\r\n\r\n\r\n function mergeChainedStyles(styling, style, errorHandler) {\r\n\r\n while (style.styleRefs.length > 0) {\r\n\r\n var sref = style.styleRefs.pop();\r\n\r\n if (!(sref in styling.styles)) {\r\n reportError(errorHandler, \"Non-existant style id referenced\");\r\n continue;\r\n }\r\n\r\n mergeChainedStyles(styling, styling.styles[sref], errorHandler);\r\n\r\n mergeStylesIfNotPresent(styling.styles[sref].styleAttrs, style.styleAttrs);\r\n\r\n }\r\n\r\n }\r\n\r\n function mergeReferencedStyles(styling, stylerefs, styleattrs, errorHandler) {\r\n\r\n for (var i = stylerefs.length - 1; i >= 0; i--) {\r\n\r\n var sref = stylerefs[i];\r\n\r\n if (!(sref in styling.styles)) {\r\n reportError(errorHandler, \"Non-existant style id referenced\");\r\n continue;\r\n }\r\n\r\n mergeStylesIfNotPresent(styling.styles[sref].styleAttrs, styleattrs);\r\n\r\n }\r\n\r\n }\r\n\r\n function mergeStylesIfNotPresent(from_styles, into_styles) {\r\n\r\n for (var sname in from_styles) {\r\n\r\n if (sname in into_styles)\r\n continue;\r\n\r\n into_styles[sname] = from_styles[sname];\r\n\r\n }\r\n\r\n }\r\n\r\n /* TODO: validate style format at parsing */\r\n\r\n\r\n /*\r\n * ERROR HANDLING UTILITY FUNCTIONS\r\n * \r\n */\r\n\r\n function reportInfo(errorHandler, msg) {\r\n\r\n if (errorHandler && errorHandler.info && errorHandler.info(msg))\r\n throw msg;\r\n\r\n }\r\n\r\n function reportWarning(errorHandler, msg) {\r\n\r\n if (errorHandler && errorHandler.warn && errorHandler.warn(msg))\r\n throw msg;\r\n\r\n }\r\n\r\n function reportError(errorHandler, msg) {\r\n\r\n if (errorHandler && errorHandler.error && errorHandler.error(msg))\r\n throw msg;\r\n\r\n }\r\n\r\n function reportFatal(errorHandler, msg) {\r\n\r\n if (errorHandler && errorHandler.fatal)\r\n errorHandler.fatal(msg);\r\n\r\n throw msg;\r\n\r\n }\r\n\r\n /*\r\n * Binary search utility function\r\n * \r\n * @typedef {Object} BinarySearchResult\r\n * @property {boolean} found Was an exact match found?\r\n * @property {number} index Position of the exact match or insert position\r\n * \r\n * @returns {BinarySearchResult}\r\n */\r\n\r\n function indexOf(arr, searchval) {\r\n\r\n var min = 0;\r\n var max = arr.length - 1;\r\n var cur;\r\n\r\n while (min <= max) {\r\n\r\n cur = Math.floor((min + max) / 2);\r\n\r\n var curval = arr[cur];\r\n\r\n if (curval < searchval) {\r\n\r\n min = cur + 1;\r\n\r\n } else if (curval > searchval) {\r\n\r\n max = cur - 1;\r\n\r\n } else {\r\n\r\n return {found: true, index: cur};\r\n\r\n }\r\n\r\n }\r\n\r\n return {found: false, index: min};\r\n }\r\n\r\n\r\n})(typeof exports === 'undefined' ? this.imscDoc = {} : exports,\r\n typeof sax === 'undefined' ? require(\"sax\") : sax,\r\n typeof imscNames === 'undefined' ? require(\"./names\") : imscNames,\r\n typeof imscStyles === 'undefined' ? require(\"./styles\") : imscStyles,\r\n typeof imscUtils === 'undefined' ? require(\"./utils\") : imscUtils);\r\n",";(function (sax) { // wrapper for non-node envs\n sax.parser = function (strict, opt) { return new SAXParser(strict, opt) }\n sax.SAXParser = SAXParser\n sax.SAXStream = SAXStream\n sax.createStream = createStream\n\n // When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns.\n // When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)),\n // since that's the earliest that a buffer overrun could occur. This way, checks are\n // as rare as required, but as often as necessary to ensure never crossing this bound.\n // Furthermore, buffers are only tested at most once per write(), so passing a very\n // large string into write() might have undesirable effects, but this is manageable by\n // the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme\n // edge case, result in creating at most one complete copy of the string passed in.\n // Set to Infinity to have unlimited buffers.\n sax.MAX_BUFFER_LENGTH = 64 * 1024\n\n var buffers = [\n 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype',\n 'procInstName', 'procInstBody', 'entity', 'attribName',\n 'attribValue', 'cdata', 'script'\n ]\n\n sax.EVENTS = [\n 'text',\n 'processinginstruction',\n 'sgmldeclaration',\n 'doctype',\n 'comment',\n 'opentagstart',\n 'attribute',\n 'opentag',\n 'closetag',\n 'opencdata',\n 'cdata',\n 'closecdata',\n 'error',\n 'end',\n 'ready',\n 'script',\n 'opennamespace',\n 'closenamespace'\n ]\n\n function SAXParser (strict, opt) {\n if (!(this instanceof SAXParser)) {\n return new SAXParser(strict, opt)\n }\n\n var parser = this\n clearBuffers(parser)\n parser.q = parser.c = ''\n parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH\n parser.opt = opt || {}\n parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags\n parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase'\n parser.tags = []\n parser.closed = parser.closedRoot = parser.sawRoot = false\n parser.tag = parser.error = null\n parser.strict = !!strict\n parser.noscript = !!(strict || parser.opt.noscript)\n parser.state = S.BEGIN\n parser.strictEntities = parser.opt.strictEntities\n parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES)\n parser.attribList = []\n\n // namespaces form a prototype chain.\n // it always points at the current tag,\n // which protos to its parent tag.\n if (parser.opt.xmlns) {\n parser.ns = Object.create(rootNS)\n }\n\n // mostly just for error reporting\n parser.trackPosition = parser.opt.position !== false\n if (parser.trackPosition) {\n parser.position = parser.line = parser.column = 0\n }\n emit(parser, 'onready')\n }\n\n if (!Object.create) {\n Object.create = function (o) {\n function F () {}\n F.prototype = o\n var newf = new F()\n return newf\n }\n }\n\n if (!Object.keys) {\n Object.keys = function (o) {\n var a = []\n for (var i in o) if (o.hasOwnProperty(i)) a.push(i)\n return a\n }\n }\n\n function checkBufferLength (parser) {\n var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10)\n var maxActual = 0\n for (var i = 0, l = buffers.length; i < l; i++) {\n var len = parser[buffers[i]].length\n if (len > maxAllowed) {\n // Text/cdata nodes can get big, and since they're buffered,\n // we can get here under normal conditions.\n // Avoid issues by emitting the text node now,\n // so at least it won't get any bigger.\n switch (buffers[i]) {\n case 'textNode':\n closeText(parser)\n break\n\n case 'cdata':\n emitNode(parser, 'oncdata', parser.cdata)\n parser.cdata = ''\n break\n\n case 'script':\n emitNode(parser, 'onscript', parser.script)\n parser.script = ''\n break\n\n default:\n error(parser, 'Max buffer length exceeded: ' + buffers[i])\n }\n }\n maxActual = Math.max(maxActual, len)\n }\n // schedule the next check for the earliest possible buffer overrun.\n var m = sax.MAX_BUFFER_LENGTH - maxActual\n parser.bufferCheckPosition = m + parser.position\n }\n\n function clearBuffers (parser) {\n for (var i = 0, l = buffers.length; i < l; i++) {\n parser[buffers[i]] = ''\n }\n }\n\n function flushBuffers (parser) {\n closeText(parser)\n if (parser.cdata !== '') {\n emitNode(parser, 'oncdata', parser.cdata)\n parser.cdata = ''\n }\n if (parser.script !== '') {\n emitNode(parser, 'onscript', parser.script)\n parser.script = ''\n }\n }\n\n SAXParser.prototype = {\n end: function () { end(this) },\n write: write,\n resume: function () { this.error = null; return this },\n close: function () { return this.write(null) },\n flush: function () { flushBuffers(this) }\n }\n\n var Stream\n try {\n Stream = require('stream').Stream\n } catch (ex) {\n Stream = function () {}\n }\n\n var streamWraps = sax.EVENTS.filter(function (ev) {\n return ev !== 'error' && ev !== 'end'\n })\n\n function createStream (strict, opt) {\n return new SAXStream(strict, opt)\n }\n\n function SAXStream (strict, opt) {\n if (!(this instanceof SAXStream)) {\n return new SAXStream(strict, opt)\n }\n\n Stream.apply(this)\n\n this._parser = new SAXParser(strict, opt)\n this.writable = true\n this.readable = true\n\n var me = this\n\n this._parser.onend = function () {\n me.emit('end')\n }\n\n this._parser.onerror = function (er) {\n me.emit('error', er)\n\n // if didn't throw, then means error was handled.\n // go ahead and clear error, so we can write again.\n me._parser.error = null\n }\n\n this._decoder = null\n\n streamWraps.forEach(function (ev) {\n Object.defineProperty(me, 'on' + ev, {\n get: function () {\n return me._parser['on' + ev]\n },\n set: function (h) {\n if (!h) {\n me.removeAllListeners(ev)\n me._parser['on' + ev] = h\n return h\n }\n me.on(ev, h)\n },\n enumerable: true,\n configurable: false\n })\n })\n }\n\n SAXStream.prototype = Object.create(Stream.prototype, {\n constructor: {\n value: SAXStream\n }\n })\n\n SAXStream.prototype.write = function (data) {\n if (typeof Buffer === 'function' &&\n typeof Buffer.isBuffer === 'function' &&\n Buffer.isBuffer(data)) {\n if (!this._decoder) {\n var SD = require('string_decoder').StringDecoder\n this._decoder = new SD('utf8')\n }\n data = this._decoder.write(data)\n }\n\n this._parser.write(data.toString())\n this.emit('data', data)\n return true\n }\n\n SAXStream.prototype.end = function (chunk) {\n if (chunk && chunk.length) {\n this.write(chunk)\n }\n this._parser.end()\n return true\n }\n\n SAXStream.prototype.on = function (ev, handler) {\n var me = this\n if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) {\n me._parser['on' + ev] = function () {\n var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments)\n args.splice(0, 0, ev)\n me.emit.apply(me, args)\n }\n }\n\n return Stream.prototype.on.call(me, ev, handler)\n }\n\n // character classes and tokens\n var whitespace = '\\r\\n\\t '\n\n // this really needs to be replaced with character classes.\n // XML allows all manner of ridiculous numbers and digits.\n var number = '0124356789'\n var letter = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\n // (Letter | \"_\" | \":\")\n var quote = '\\'\"'\n var attribEnd = whitespace + '>'\n var CDATA = '[CDATA['\n var DOCTYPE = 'DOCTYPE'\n var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'\n var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/'\n var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE }\n\n // turn all the string character sets into character class objects.\n whitespace = charClass(whitespace)\n number = charClass(number)\n letter = charClass(letter)\n\n // http://www.w3.org/TR/REC-xml/#NT-NameStartChar\n // This implementation works on strings, a single character at a time\n // as such, it cannot ever support astral-plane characters (10000-EFFFF)\n // without a significant breaking change to either this parser, or the\n // JavaScript language. Implementation of an emoji-capable xml parser\n // is left as an exercise for the reader.\n var nameStart = /[:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]/\n\n var nameBody = /[:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u00B7\\u0300-\\u036F\\u203F-\\u2040\\.\\d-]/\n\n var entityStart = /[#:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]/\n var entityBody = /[#:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u00B7\\u0300-\\u036F\\u203F-\\u2040\\.\\d-]/\n\n quote = charClass(quote)\n attribEnd = charClass(attribEnd)\n\n function charClass (str) {\n return str.split('').reduce(function (s, c) {\n s[c] = true\n return s\n }, {})\n }\n\n function isRegExp (c) {\n return Object.prototype.toString.call(c) === '[object RegExp]'\n }\n\n function is (charclass, c) {\n return isRegExp(charclass) ? !!c.match(charclass) : charclass[c]\n }\n\n function not (charclass, c) {\n return !is(charclass, c)\n }\n\n var S = 0\n sax.STATE = {\n BEGIN: S++, // leading byte order mark or whitespace\n BEGIN_WHITESPACE: S++, // leading whitespace\n TEXT: S++, // general stuff\n TEXT_ENTITY: S++, // & and such.\n OPEN_WAKA: S++, // <\n SGML_DECL: S++, // <!BLARG\n SGML_DECL_QUOTED: S++, // <!BLARG foo \"bar\n DOCTYPE: S++, // <!DOCTYPE\n DOCTYPE_QUOTED: S++, // <!DOCTYPE \"//blah\n DOCTYPE_DTD: S++, // <!DOCTYPE \"//blah\" [ ...\n DOCTYPE_DTD_QUOTED: S++, // <!DOCTYPE \"//blah\" [ \"foo\n COMMENT_STARTING: S++, // <!-\n COMMENT: S++, // <!--\n COMMENT_ENDING: S++, // <!-- blah -\n COMMENT_ENDED: S++, // <!-- blah --\n CDATA: S++, // <![CDATA[ something\n CDATA_ENDING: S++, // ]\n CDATA_ENDING_2: S++, // ]]\n PROC_INST: S++, // <?hi\n PROC_INST_BODY: S++, // <?hi there\n PROC_INST_ENDING: S++, // <?hi \"there\" ?\n OPEN_TAG: S++, // <strong\n OPEN_TAG_SLASH: S++, // <strong /\n ATTRIB: S++, // <a\n ATTRIB_NAME: S++, // <a foo\n ATTRIB_NAME_SAW_WHITE: S++, // <a foo _\n ATTRIB_VALUE: S++, // <a foo=\n ATTRIB_VALUE_QUOTED: S++, // <a foo=\"bar\n ATTRIB_VALUE_CLOSED: S++, // <a foo=\"bar\"\n ATTRIB_VALUE_UNQUOTED: S++, // <a foo=bar\n ATTRIB_VALUE_ENTITY_Q: S++, // <foo bar=\""\"\n ATTRIB_VALUE_ENTITY_U: S++, // <foo bar="\n CLOSE_TAG: S++, // </a\n CLOSE_TAG_SAW_WHITE: S++, // </a >\n SCRIPT: S++, // <script> ...\n SCRIPT_ENDING: S++ // <script> ... <\n }\n\n sax.XML_ENTITIES = {\n 'amp': '&',\n 'gt': '>',\n 'lt': '<',\n 'quot': '\"',\n 'apos': \"'\"\n }\n\n sax.ENTITIES = {\n 'amp': '&',\n 'gt': '>',\n 'lt': '<',\n 'quot': '\"',\n 'apos': \"'\",\n 'AElig': 198,\n 'Aacute': 193,\n 'Acirc': 194,\n 'Agrave': 192,\n 'Aring': 197,\n 'Atilde': 195,\n 'Auml': 196,\n 'Ccedil': 199,\n 'ETH': 208,\n 'Eacute': 201,\n 'Ecirc': 202,\n 'Egrave': 200,\n 'Euml': 203,\n 'Iacute': 205,\n 'Icirc': 206,\n 'Igrave': 204,\n 'Iuml': 207,\n 'Ntilde': 209,\n 'Oacute': 211,\n 'Ocirc': 212,\n 'Ograve': 210,\n 'Oslash': 216,\n 'Otilde': 213,\n 'Ouml': 214,\n 'THORN': 222,\n 'Uacute': 218,\n 'Ucirc': 219,\n 'Ugrave': 217,\n 'Uuml': 220,\n 'Yacute': 221,\n 'aacute': 225,\n 'acirc': 226,\n 'aelig': 230,\n 'agrave': 224,\n 'aring': 229,\n 'atilde': 227,\n 'auml': 228,\n 'ccedil': 231,\n 'eacute': 233,\n 'ecirc': 234,\n 'egrave': 232,\n 'eth': 240,\n 'euml': 235,\n 'iacute': 237,\n 'icirc': 238,\n 'igrave': 236,\n 'iuml': 239,\n 'ntilde': 241,\n 'oacute': 243,\n 'ocirc': 244,\n 'ograve': 242,\n 'oslash': 248,\n 'otilde': 245,\n 'ouml': 246,\n 'szlig': 223,\n 'thorn': 254,\n 'uacute': 250,\n 'ucirc': 251,\n 'ugrave': 249,\n 'uuml': 252,\n 'yacute': 253,\n 'yuml': 255,\n 'copy': 169,\n 'reg': 174,\n 'nbsp': 160,\n 'iexcl': 161,\n 'cent': 162,\n 'pound': 163,\n 'curren': 164,\n 'yen': 165,\n 'brvbar': 166,\n 'sect': 167,\n 'uml': 168,\n 'ordf': 170,\n 'laquo': 171,\n 'not': 172,\n 'shy': 173,\n 'macr': 175,\n 'deg': 176,\n 'plusmn': 177,\n 'sup1': 185,\n 'sup2': 178,\n 'sup3': 179,\n 'acute': 180,\n 'micro': 181,\n 'para': 182,\n 'middot': 183,\n 'cedil': 184,\n 'ordm': 186,\n 'raquo': 187,\n 'frac14': 188,\n 'frac12': 189,\n 'frac34': 190,\n 'iquest': 191,\n 'times': 215,\n 'divide': 247,\n 'OElig': 338,\n 'oelig': 339,\n 'Scaron': 352,\n 'scaron': 353,\n 'Yuml': 376,\n 'fnof': 402,\n 'circ': 710,\n 'tilde': 732,\n 'Alpha': 913,\n 'Beta': 914,\n 'Gamma': 915,\n 'Delta': 916,\n 'Epsilon': 917,\n 'Zeta': 918,\n 'Eta': 919,\n 'Theta': 920,\n 'Iota': 921,\n 'Kappa': 922,\n 'Lambda': 923,\n 'Mu': 924,\n 'Nu': 925,\n 'Xi': 926,\n 'Omicron': 927,\n 'Pi': 928,\n 'Rho': 929,\n 'Sigma': 931,\n 'Tau': 932,\n 'Upsilon': 933,\n 'Phi': 934,\n 'Chi': 935,\n 'Psi': 936,\n 'Omega': 937,\n 'alpha': 945,\n 'beta': 946,\n 'gamma': 947,\n 'delta': 948,\n 'epsilon': 949,\n 'zeta': 950,\n 'eta': 951,\n 'theta': 952,\n 'iota': 953,\n 'kappa': 954,\n 'lambda': 955,\n 'mu': 956,\n 'nu': 957,\n 'xi': 958,\n 'omicron': 959,\n 'pi': 960,\n 'rho': 961,\n 'sigmaf': 962,\n 'sigma': 963,\n 'tau': 964,\n 'upsilon': 965,\n 'phi': 966,\n 'chi': 967,\n 'psi': 968,\n 'omega': 969,\n 'thetasym': 977,\n 'upsih': 978,\n 'piv': 982,\n 'ensp': 8194,\n 'emsp': 8195,\n 'thinsp': 8201,\n 'zwnj': 8204,\n 'zwj': 8205,\n 'lrm': 8206,\n 'rlm': 8207,\n 'ndash': 8211,\n 'mdash': 8212,\n 'lsquo': 8216,\n 'rsquo': 8217,\n 'sbquo': 8218,\n 'ldquo': 8220,\n 'rdquo': 8221,\n 'bdquo': 8222,\n 'dagger': 8224,\n 'Dagger': 8225,\n 'bull': 8226,\n 'hellip': 8230,\n 'permil': 8240,\n 'prime': 8242,\n 'Prime': 8243,\n 'lsaquo': 8249,\n 'rsaquo': 8250,\n 'oline': 8254,\n 'frasl': 8260,\n 'euro': 8364,\n 'image': 8465,\n 'weierp': 8472,\n 'real': 8476,\n 'trade': 8482,\n 'alefsym': 8501,\n 'larr': 8592,\n 'uarr': 8593,\n 'rarr': 8594,\n 'darr': 8595,\n 'harr': 8596,\n 'crarr': 8629,\n 'lArr': 8656,\n 'uArr': 8657,\n 'rArr': 8658,\n 'dArr': 8659,\n 'hArr': 8660,\n 'forall': 8704,\n 'part': 8706,\n 'exist': 8707,\n 'empty': 8709,\n 'nabla': 8711,\n 'isin': 8712,\n 'notin': 8713,\n 'ni': 8715,\n 'prod': 8719,\n 'sum': 8721,\n 'minus': 8722,\n 'lowast': 8727,\n 'radic': 8730,\n 'prop': 8733,\n 'infin': 8734,\n 'ang': 8736,\n 'and': 8743,\n 'or': 8744,\n 'cap': 8745,\n 'cup': 8746,\n 'int': 8747,\n 'there4': 8756,\n 'sim': 8764,\n 'cong': 8773,\n 'asymp': 8776,\n 'ne': 8800,\n 'equiv': 8801,\n 'le': 8804,\n 'ge': 8805,\n 'sub': 8834,\n 'sup': 8835,\n 'nsub': 8836,\n 'sube': 8838,\n 'supe': 8839,\n 'oplus': 8853,\n 'otimes': 8855,\n 'perp': 8869,\n 'sdot': 8901,\n 'lceil': 8968,\n 'rceil': 8969,\n 'lfloor': 8970,\n 'rfloor': 8971,\n 'lang': 9001,\n 'rang': 9002,\n 'loz': 9674,\n 'spades': 9824,\n 'clubs': 9827,\n 'hearts': 9829,\n 'diams': 9830\n }\n\n Object.keys(sax.ENTITIES).forEach(function (key) {\n var e = sax.ENTITIES[key]\n var s = typeof e === 'number' ? String.fromCharCode(e) : e\n sax.ENTITIES[key] = s\n })\n\n for (var s in sax.STATE) {\n sax.STATE[sax.STATE[s]] = s\n }\n\n // shorthand\n S = sax.STATE\n\n function emit (parser, event, data) {\n parser[event] && parser[event](data)\n }\n\n function emitNode (parser, nodeType, data) {\n if (parser.textNode) closeText(parser)\n emit(parser, nodeType, data)\n }\n\n function closeText (parser) {\n parser.textNode = textopts(parser.opt, parser.textNode)\n if (parser.textNode) emit(parser, 'ontext', parser.textNode)\n parser.textNode = ''\n }\n\n function textopts (opt, text) {\n if (opt.trim) text = text.trim()\n if (opt.normalize) text = text.replace(/\\s+/g, ' ')\n return text\n }\n\n function error (parser, er) {\n closeText(parser)\n if (parser.trackPosition) {\n er += '\\nLine: ' + parser.line +\n '\\nColumn: ' + parser.column +\n '\\nChar: ' + parser.c\n }\n er = new Error(er)\n parser.error = er\n emit(parser, 'onerror', er)\n return parser\n }\n\n function end (parser) {\n if (parser.sawRoot && !parser.closedRoot) strictFail(parser, 'Unclosed root tag')\n if ((parser.state !== S.BEGIN) &&\n (parser.state !== S.BEGIN_WHITESPACE) &&\n (parser.state !== S.TEXT)) {\n error(parser, 'Unexpected end')\n }\n closeText(parser)\n parser.c = ''\n parser.closed = true\n emit(parser, 'onend')\n SAXParser.call(parser, parser.strict, parser.opt)\n return parser\n }\n\n function strictFail (parser, message) {\n if (typeof parser !== 'object' || !(parser instanceof SAXParser)) {\n throw new Error('bad call to strictFail')\n }\n if (parser.strict) {\n error(parser, message)\n }\n }\n\n function newTag (parser) {\n if (!parser.strict) parser.tagName = parser.tagName[parser.looseCase]()\n var parent = parser.tags[parser.tags.length - 1] || parser\n var tag = parser.tag = { name: parser.tagName, attributes: {} }\n\n // will be overridden if tag contails an xmlns=\"foo\" or xmlns:foo=\"bar\"\n if (parser.opt.xmlns) {\n tag.ns = parent.ns\n }\n parser.attribList.length = 0\n emitNode(parser, 'onopentagstart', tag)\n }\n\n function qname (name, attribute) {\n var i = name.indexOf(':')\n var qualName = i < 0 ? [ '', name ] : name.split(':')\n var prefix = qualName[0]\n var local = qualName[1]\n\n // <x \"xmlns\"=\"http://foo\">\n if (attribute && name === 'xmlns') {\n prefix = 'xmlns'\n local = ''\n }\n\n return { prefix: prefix, local: local }\n }\n\n function attrib (parser) {\n if (!parser.strict) {\n parser.attribName = parser.attribName[parser.looseCase]()\n }\n\n if (parser.attribList.indexOf(parser.attribName) !== -1 ||\n parser.tag.attributes.hasOwnProperty(parser.attribName)) {\n parser.attribName = parser.attribValue = ''\n return\n }\n\n if (parser.opt.xmlns) {\n var qn = qname(parser.attribName, true)\n var prefix = qn.prefix\n var local = qn.local\n\n if (prefix === 'xmlns') {\n // namespace binding attribute. push the binding into scope\n if (local === 'xml' && parser.attribValue !== XML_NAMESPACE) {\n strictFail(parser,\n 'xml: prefix must be bound to ' + XML_NAMESPACE + '\\n' +\n 'Actual: ' + parser.attribValue)\n } else if (local === 'xmlns' && parser.attribValue !== XMLNS_NAMESPACE) {\n strictFail(parser,\n 'xmlns: prefix must be bound to ' + XMLNS_NAMESPACE + '\\n' +\n 'Actual: ' + parser.attribValue)\n } else {\n var tag = parser.tag\n var parent = parser.tags[parser.tags.length - 1] || parser\n if (tag.ns === parent.ns) {\n tag.ns = Object.create(parent.ns)\n }\n tag.ns[local] = parser.attribValue\n }\n }\n\n // defer onattribute events until all attributes have been seen\n // so any new bindings can take effect. preserve attribute order\n // so deferred events can be emitted in document order\n parser.attribList.push([parser.attribName, parser.attribValue])\n } else {\n // in non-xmlns mode, we can emit the event right away\n parser.tag.attributes[parser.attribName] = parser.attribValue\n emitNode(parser, 'onattribute', {\n name: parser.attribName,\n value: parser.attribValue\n })\n }\n\n parser.attribName = parser.attribValue = ''\n }\n\n function openTag (parser, selfClosing) {\n if (parser.opt.xmlns) {\n // emit namespace binding events\n var tag = parser.tag\n\n // add namespace info to tag\n var qn = qname(parser.tagName)\n tag.prefix = qn.prefix\n tag.local = qn.local\n tag.uri = tag.ns[qn.prefix] || ''\n\n if (tag.prefix && !tag.uri) {\n strictFail(parser, 'Unbound namespace prefix: ' +\n JSON.stringify(parser.tagName))\n tag.uri = qn.prefix\n }\n\n var parent = parser.tags[parser.tags.length - 1] || parser\n if (tag.ns && parent.ns !== tag.ns) {\n Object.keys(tag.ns).forEach(function (p) {\n emitNode(parser, 'onopennamespace', {\n prefix: p,\n uri: tag.ns[p]\n })\n })\n }\n\n // handle deferred onattribute events\n // Note: do not apply default ns to attributes:\n // http://www.w3.org/TR/REC-xml-names/#defaulting\n for (var i = 0, l = parser.attribList.length; i < l; i++) {\n var nv = parser.attribList[i]\n var name = nv[0]\n var value = nv[1]\n var qualName = qname(name, true)\n var prefix = qualName.prefix\n var local = qualName.local\n var uri = prefix === '' ? '' : (tag.ns[prefix] || '')\n var a = {\n name: name,\n value: value,\n prefix: prefix,\n local: local,\n uri: uri\n }\n\n // if there's any attributes with an undefined namespace,\n // then fail on them now.\n if (prefix && prefix !== 'xmlns' && !uri) {\n strictFail(parser, 'Unbound namespace prefix: ' +\n JSON.stringify(prefix))\n a.uri = prefix\n }\n parser.tag.attributes[name] = a\n emitNode(parser, 'onattribute', a)\n }\n parser.attribList.length = 0\n }\n\n parser.tag.isSelfClosing = !!selfClosing\n\n // process the tag\n parser.sawRoot = true\n parser.tags.push(parser.tag)\n emitNode(parser, 'onopentag', parser.tag)\n if (!selfClosing) {\n // special case for <script> in non-strict mode.\n if (!parser.noscript && parser.tagName.toLowerCase() === 'script') {\n parser.state = S.SCRIPT\n } else {\n parser.state = S.TEXT\n }\n parser.tag = null\n parser.tagName = ''\n }\n parser.attribName = parser.attribValue = ''\n parser.attribList.length = 0\n }\n\n function closeTag (parser) {\n if (!parser.tagName) {\n strictFail(parser, 'Weird empty close tag.')\n parser.textNode += '</>'\n parser.state = S.TEXT\n return\n }\n\n if (parser.script) {\n if (parser.tagName !== 'script') {\n parser.script += '</' + parser.tagName + '>'\n parser.tagName = ''\n parser.state = S.SCRIPT\n return\n }\n emitNode(parser, 'onscript', parser.script)\n parser.script = ''\n }\n\n // first make sure that the closing tag actually exists.\n // <a><b></c></b></a> will close everything, otherwise.\n var t = parser.tags.length\n var tagName = parser.tagName\n if (!parser.strict) {\n tagName = tagName[parser.looseCase]()\n }\n var closeTo = tagName\n while (t--) {\n var close = parser.tags[t]\n if (close.name !== closeTo) {\n // fail the first time in strict mode\n strictFail(parser, 'Unexpected close tag')\n } else {\n break\n }\n }\n\n // didn't find it. we already failed for strict, so just abort.\n if (t < 0) {\n strictFail(parser, 'Unmatched closing tag: ' + parser.tagName)\n parser.textNode += '</' + parser.tagName + '>'\n parser.state = S.TEXT\n return\n }\n parser.tagName = tagName\n var s = parser.tags.length\n while (s-- > t) {\n var tag = parser.tag = parser.tags.pop()\n parser.tagName = parser.tag.name\n emitNode(parser, 'onclosetag', parser.tagName)\n\n var x = {}\n for (var i in tag.ns) {\n x[i] = tag.ns[i]\n }\n\n var parent = parser.tags[parser.tags.length - 1] || parser\n if (parser.opt.xmlns && tag.ns !== parent.ns) {\n // remove namespace bindings introduced by tag\n Object.keys(tag.ns).forEach(function (p) {\n var n = tag.ns[p]\n emitNode(parser, 'onclosenamespace', { prefix: p, uri: n })\n })\n }\n }\n if (t === 0) parser.closedRoot = true\n parser.tagName = parser.attribValue = parser.attribName = ''\n parser.attribList.length = 0\n parser.state = S.TEXT\n }\n\n function parseEntity (parser) {\n var entity = parser.entity\n var entityLC = entity.toLowerCase()\n var num\n var numStr = ''\n\n if (parser.ENTITIES[entity]) {\n return parser.ENTITIES[entity]\n }\n if (parser.ENTITIES[entityLC]) {\n return parser.ENTITIES[entityLC]\n }\n entity = entityLC\n if (entity.charAt(0) === '#') {\n if (entity.charAt(1) === 'x') {\n entity = entity.slice(2)\n num = parseInt(entity, 16)\n numStr = num.toString(16)\n } else {\n entity = entity.slice(1)\n num = parseInt(entity, 10)\n numStr = num.toString(10)\n }\n }\n entity = entity.replace(/^0+/, '')\n if (numStr.toLowerCase() !== entity) {\n strictFail(parser, 'Invalid character entity')\n return '&' + parser.entity + ';'\n }\n\n return String.fromCodePoint(num)\n }\n\n function beginWhiteSpace (parser, c) {\n if (c === '<') {\n parser.state = S.OPEN_WAKA\n parser.startTagPosition = parser.position\n } else if (not(whitespace, c)) {\n // have to process this as a text node.\n // weird, but happens.\n strictFail(parser, 'Non-whitespace before first tag.')\n parser.textNode = c\n parser.state = S.TEXT\n }\n }\n\n function charAt (chunk, i) {\n var result = ''\n if (i < chunk.length) {\n result = chunk.charAt(i)\n }\n return result\n }\n\n function write (chunk) {\n var parser = this\n if (this.error) {\n throw this.error\n }\n if (parser.closed) {\n return error(parser,\n 'Cannot write after close. Assign an onready handler.')\n }\n if (chunk === null) {\n return end(parser)\n }\n if (typeof chunk === 'object') {\n chunk = chunk.toString()\n }\n var i = 0\n var c = ''\n while (true) {\n c = charAt(chunk, i++)\n parser.c = c\n if (!c) {\n break\n }\n if (parser.trackPosition) {\n parser.position++\n if (c === '\\n') {\n parser.line++\n parser.column = 0\n } else {\n parser.column++\n }\n }\n switch (parser.state) {\n case S.BEGIN:\n parser.state = S.BEGIN_WHITESPACE\n if (c === '\\uFEFF') {\n continue\n }\n beginWhiteSpace(parser, c)\n continue\n\n case S.BEGIN_WHITESPACE:\n beginWhiteSpace(parser, c)\n continue\n\n case S.TEXT:\n if (parser.sawRoot && !parser.closedRoot) {\n var starti = i - 1\n while (c && c !== '<' && c !== '&') {\n c = charAt(chunk, i++)\n if (c && parser.trackPosition) {\n parser.position++\n if (c === '\\n') {\n parser.line++\n parser.column = 0\n } else {\n parser.column++\n }\n }\n }\n parser.textNode += chunk.substring(starti, i - 1)\n }\n if (c === '<' && !(parser.sawRoot && parser.closedRoot && !parser.strict)) {\n parser.state = S.OPEN_WAKA\n parser.startTagPosition = parser.position\n } else {\n if (not(whitespace, c) && (!parser.sawRoot || parser.closedRoot)) {\n strictFail(parser, 'Text data outside of root node.')\n }\n if (c === '&') {\n parser.state = S.TEXT_ENTITY\n } else {\n parser.textNode += c\n }\n }\n continue\n\n case S.SCRIPT:\n // only non-strict\n if (c === '<') {\n parser.state = S.SCRIPT_ENDING\n } else {\n parser.script += c\n }\n continue\n\n case S.SCRIPT_ENDING:\n if (c === '/') {\n parser.state = S.CLOSE_TAG\n } else {\n parser.script += '<' + c\n parser.state = S.SCRIPT\n }\n continue\n\n case S.OPEN_WAKA:\n // either a /, ?, !, or text is coming next.\n if (c === '!') {\n parser.state = S.SGML_DECL\n parser.sgmlDecl = ''\n } else if (is(whitespace, c)) {\n // wait for it...\n } else if (is(nameStart, c)) {\n parser.state = S.OPEN_TAG\n parser.tagName = c\n } else if (c === '/') {\n parser.state = S.CLOSE_TAG\n parser.tagName = ''\n } else if (c === '?') {\n parser.state = S.PROC_INST\n parser.procInstName = parser.procInstBody = ''\n } else {\n strictFail(parser, 'Unencoded <')\n // if there was some whitespace, then add that in.\n if (parser.startTagPosition + 1 < parser.position) {\n var pad = parser.position - parser.startTagPosition\n c = new Array(pad).join(' ') + c\n }\n parser.textNode += '<' + c\n parser.state = S.TEXT\n }\n continue\n\n case S.SGML_DECL:\n if ((parser.sgmlDecl + c).toUpperCase() === CDATA) {\n emitNode(parser, 'onopencdata')\n parser.state = S.CDATA\n parser.sgmlDecl = ''\n parser.cdata = ''\n } else if (parser.sgmlDecl + c === '--') {\n parser.state = S.COMMENT\n parser.comment = ''\n parser.sgmlDecl = ''\n } else if ((parser.sgmlDecl + c).toUpperCase() === DOCTYPE) {\n parser.state = S.DOCTYPE\n if (parser.doctype || parser.sawRoot) {\n strictFail(parser,\n 'Inappropriately located doctype declaration')\n }\n parser.doctype = ''\n parser.sgmlDecl = ''\n } else if (c === '>') {\n emitNode(parser, 'onsgmldeclaration', parser.sgmlDecl)\n parser.sgmlDecl = ''\n parser.state = S.TEXT\n } else if (is(quote, c)) {\n parser.state = S.SGML_DECL_QUOTED\n parser.sgmlDecl += c\n } else {\n parser.sgmlDecl += c\n }\n continue\n\n case S.SGML_DECL_QUOTED:\n if (c === parser.q) {\n parser.state = S.SGML_DECL\n parser.q = ''\n }\n parser.sgmlDecl += c\n continue\n\n case S.DOCTYPE:\n if (c === '>') {\n parser.state = S.TEXT\n emitNode(parser, 'ondoctype', parser.doctype)\n parser.doctype = true // just remember that we saw it.\n } else {\n parser.doctype += c\n if (c === '[') {\n parser.state = S.DOCTYPE_DTD\n } else if (is(quote, c)) {\n parser.state = S.DOCTYPE_QUOTED\n parser.q = c\n }\n }\n continue\n\n case S.DOCTYPE_QUOTED:\n parser.doctype += c\n if (c === parser.q) {\n parser.q = ''\n parser.state = S.DOCTYPE\n }\n continue\n\n case S.DOCTYPE_DTD:\n parser.doctype += c\n if (c === ']') {\n parser.state = S.DOCTYPE\n } else if (is(quote, c)) {\n parser.state = S.DOCTYPE_DTD_QUOTED\n parser.q = c\n }\n continue\n\n case S.DOCTYPE_DTD_QUOTED:\n parser.doctype += c\n if (c === parser.q) {\n parser.state = S.DOCTYPE_DTD\n parser.q = ''\n }\n continue\n\n case S.COMMENT:\n if (c === '-') {\n parser.state = S.COMMENT_ENDING\n } else {\n parser.comment += c\n }\n continue\n\n case S.COMMENT_ENDING:\n if (c === '-') {\n parser.state = S.COMMENT_ENDED\n parser.comment = textopts(parser.opt, parser.comment)\n if (parser.comment) {\n emitNode(parser, 'oncomment', parser.comment)\n }\n parser.comment = ''\n } else {\n parser.comment += '-' + c\n parser.state = S.COMMENT\n }\n continue\n\n case S.COMMENT_ENDED:\n if (c !== '>') {\n strictFail(parser, 'Malformed comment')\n // allow <!-- blah -- bloo --> in non-strict mode,\n // which is a comment of \" blah -- bloo \"\n parser.comment += '--' + c\n parser.state = S.COMMENT\n } else {\n parser.state = S.TEXT\n }\n continue\n\n case S.CDATA:\n if (c === ']') {\n parser.state = S.CDATA_ENDING\n } else {\n parser.cdata += c\n }\n continue\n\n case S.CDATA_ENDING:\n if (c === ']') {\n parser.state = S.CDATA_ENDING_2\n } else {\n parser.cdata += ']' + c\n parser.state = S.CDATA\n }\n continue\n\n case S.CDATA_ENDING_2:\n if (c === '>') {\n if (parser.cdata) {\n emitNode(parser, 'oncdata', parser.cdata)\n }\n emitNode(parser, 'onclosecdata')\n parser.cdata = ''\n parser.state = S.TEXT\n } else if (c === ']') {\n parser.cdata += ']'\n } else {\n parser.cdata += ']]' + c\n parser.state = S.CDATA\n }\n continue\n\n case S.PROC_INST:\n if (c === '?') {\n parser.state = S.PROC_INST_ENDING\n } else if (is(whitespace, c)) {\n parser.state = S.PROC_INST_BODY\n } else {\n parser.procInstName += c\n }\n continue\n\n case S.PROC_INST_BODY:\n if (!parser.procInstBody && is(whitespace, c)) {\n continue\n } else if (c === '?') {\n parser.state = S.PROC_INST_ENDING\n } else {\n parser.procInstBody += c\n }\n continue\n\n case S.PROC_INST_ENDING:\n if (c === '>') {\n emitNode(parser, 'onprocessinginstruction', {\n name: parser.procInstName,\n body: parser.procInstBody\n })\n parser.procInstName = parser.procInstBody = ''\n parser.state = S.TEXT\n } else {\n parser.procInstBody += '?' + c\n parser.state = S.PROC_INST_BODY\n }\n continue\n\n case S.OPEN_TAG:\n if (is(nameBody, c)) {\n parser.tagName += c\n } else {\n newTag(parser)\n if (c === '>') {\n openTag(parser)\n } else if (c === '/') {\n parser.state = S.OPEN_TAG_SLASH\n } else {\n if (not(whitespace, c)) {\n strictFail(parser, 'Invalid character in tag name')\n }\n parser.state = S.ATTRIB\n }\n }\n continue\n\n case S.OPEN_TAG_SLASH:\n if (c === '>') {\n openTag(parser, true)\n closeTag(parser)\n } else {\n strictFail(parser, 'Forward-slash in opening tag not followed by >')\n parser.state = S.ATTRIB\n }\n continue\n\n case S.ATTRIB:\n // haven't read the attribute name yet.\n if (is(whitespace, c)) {\n continue\n } else if (c === '>') {\n openTag(parser)\n } else if (c === '/') {\n parser.state = S.OPEN_TAG_SLASH\n } else if (is(nameStart, c)) {\n parser.attribName = c\n parser.attribValue = ''\n parser.state = S.ATTRIB_NAME\n } else {\n strictFail(parser, 'Invalid attribute name')\n }\n continue\n\n case S.ATTRIB_NAME:\n if (c === '=') {\n parser.state = S.ATTRIB_VALUE\n } else if (c === '>') {\n strictFail(parser, 'Attribute without value')\n parser.attribValue = parser.attribName\n attrib(parser)\n openTag(parser)\n } else if (is(whitespace, c)) {\n parser.state = S.ATTRIB_NAME_SAW_WHITE\n } else if (is(nameBody, c)) {\n parser.attribName += c\n } else {\n strictFail(parser, 'Invalid attribute name')\n }\n continue\n\n case S.ATTRIB_NAME_SAW_WHITE:\n if (c === '=') {\n parser.state = S.ATTRIB_VALUE\n } else if (is(whitespace, c)) {\n continue\n } else {\n strictFail(parser, 'Attribute without value')\n parser.tag.attributes[parser.attribName] = ''\n parser.attribValue = ''\n emitNode(parser, 'onattribute', {\n name: parser.attribName,\n value: ''\n })\n parser.attribName = ''\n if (c === '>') {\n openTag(parser)\n } else if (is(nameStart, c)) {\n parser.attribName = c\n parser.state = S.ATTRIB_NAME\n } else {\n strictFail(parser, 'Invalid attribute name')\n parser.state = S.ATTRIB\n }\n }\n continue\n\n case S.ATTRIB_VALUE:\n if (is(whitespace, c)) {\n continue\n } else if (is(quote, c)) {\n parser.q = c\n parser.state = S.ATTRIB_VALUE_QUOTED\n } else {\n strictFail(parser, 'Unquoted attribute value')\n parser.state = S.ATTRIB_VALUE_UNQUOTED\n parser.attribValue = c\n }\n continue\n\n case S.ATTRIB_VALUE_QUOTED:\n if (c !== parser.q) {\n if (c === '&') {\n parser.state = S.ATTRIB_VALUE_ENTITY_Q\n } else {\n parser.attribValue += c\n }\n continue\n }\n attrib(parser)\n parser.q = ''\n parser.state = S.ATTRIB_VALUE_CLOSED\n continue\n\n case S.ATTRIB_VALUE_CLOSED:\n if (is(whitespace, c)) {\n parser.state = S.ATTRIB\n } else if (c === '>') {\n openTag(parser)\n } else if (c === '/') {\n parser.state = S.OPEN_TAG_SLASH\n } else if (is(nameStart, c)) {\n strictFail(parser, 'No whitespace between attributes')\n parser.attribName = c\n parser.attribValue = ''\n parser.state = S.ATTRIB_NAME\n } else {\n strictFail(parser, 'Invalid attribute name')\n }\n continue\n\n case S.ATTRIB_VALUE_UNQUOTED:\n if (not(attribEnd, c)) {\n if (c === '&') {\n parser.state = S.ATTRIB_VALUE_ENTITY_U\n } else {\n parser.attribValue += c\n }\n continue\n }\n attrib(parser)\n if (c === '>') {\n openTag(parser)\n } else {\n parser.state = S.ATTRIB\n }\n continue\n\n case S.CLOSE_TAG:\n if (!parser.tagName) {\n if (is(whitespace, c)) {\n continue\n } else if (not(nameStart, c)) {\n if (parser.script) {\n parser.script += '</' + c\n parser.state = S.SCRIPT\n } else {\n strictFail(parser, 'Invalid tagname in closing tag.')\n }\n } else {\n parser.tagName = c\n }\n } else if (c === '>') {\n closeTag(parser)\n } else if (is(nameBody, c)) {\n parser.tagName += c\n } else if (parser.script) {\n parser.script += '</' + parser.tagName\n parser.tagName = ''\n parser.state = S.SCRIPT\n } else {\n if (not(whitespace, c)) {\n strictFail(parser, 'Invalid tagname in closing tag')\n }\n parser.state = S.CLOSE_TAG_SAW_WHITE\n }\n continue\n\n case S.CLOSE_TAG_SAW_WHITE:\n if (is(whitespace, c)) {\n continue\n }\n if (c === '>') {\n closeTag(parser)\n } else {\n strictFail(parser, 'Invalid characters in closing tag')\n }\n continue\n\n case S.TEXT_ENTITY:\n case S.ATTRIB_VALUE_ENTITY_Q:\n case S.ATTRIB_VALUE_ENTITY_U:\n var returnState\n var buffer\n switch (parser.state) {\n case S.TEXT_ENTITY:\n returnState = S.TEXT\n buffer = 'textNode'\n break\n\n case S.ATTRIB_VALUE_ENTITY_Q:\n returnState = S.ATTRIB_VALUE_QUOTED\n buffer = 'attribValue'\n break\n\n case S.ATTRIB_VALUE_ENTITY_U:\n returnState = S.ATTRIB_VALUE_UNQUOTED\n buffer = 'attribValue'\n break\n }\n\n if (c === ';') {\n parser[buffer] += parseEntity(parser)\n parser.entity = ''\n parser.state = returnState\n } else if (is(parser.entity.length ? entityBody : entityStart, c)) {\n parser.entity += c\n } else {\n strictFail(parser, 'Invalid character in entity name')\n parser[buffer] += '&' + parser.entity + c\n parser.entity = ''\n parser.state = returnState\n }\n\n continue\n\n default:\n throw new Error(parser, 'Unknown state: ' + parser.state)\n }\n } // while\n\n if (parser.position >= parser.bufferCheckPosition) {\n checkBufferLength(parser)\n }\n return parser\n }\n\n /*! http://mths.be/fromcodepoint v0.1.0 by @mathias */\n if (!String.fromCodePoint) {\n (function () {\n var stringFromCharCode = String.fromCharCode\n var floor = Math.floor\n var fromCodePoint = function () {\n var MAX_SIZE = 0x4000\n var codeUnits = []\n var highSurrogate\n var lowSurrogate\n var index = -1\n var length = arguments.length\n if (!length) {\n return ''\n }\n var result = ''\n while (++index < length) {\n var codePoint = Number(arguments[index])\n if (\n !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`\n codePoint < 0 || // not a valid Unicode code point\n codePoint > 0x10FFFF || // not a valid Unicode code point\n floor(codePoint) !== codePoint // not an integer\n ) {\n throw RangeError('Invalid code point: ' + codePoint)\n }\n if (codePoint <= 0xFFFF) { // BMP code point\n codeUnits.push(codePoint)\n } else { // Astral code point; split in surrogate halves\n // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae\n codePoint -= 0x10000\n highSurrogate = (codePoint >> 10) + 0xD800\n lowSurrogate = (codePoint % 0x400) + 0xDC00\n codeUnits.push(highSurrogate, lowSurrogate)\n }\n if (index + 1 === length || codeUnits.length > MAX_SIZE) {\n result += stringFromCharCode.apply(null, codeUnits)\n codeUnits.length = 0\n }\n }\n return result\n }\n if (Object.defineProperty) {\n Object.defineProperty(String, 'fromCodePoint', {\n value: fromCodePoint,\n configurable: true,\n writable: true\n })\n } else {\n String.fromCodePoint = fromCodePoint\n }\n }())\n }\n})(typeof exports === 'undefined' ? this.sax = {} : exports)\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n for (var i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(\n uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)\n ))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","exports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nmodule.exports = Stream;\n\nvar EE = require('events').EventEmitter;\nvar inherits = require('inherits');\n\ninherits(Stream, EE);\nStream.Readable = require('readable-stream/readable.js');\nStream.Writable = require('readable-stream/writable.js');\nStream.Duplex = require('readable-stream/duplex.js');\nStream.Transform = require('readable-stream/transform.js');\nStream.PassThrough = require('readable-stream/passthrough.js');\n\n// Backwards-compat with node 0.4.x\nStream.Stream = Stream;\n\n\n\n// old-style streams. Note that the pipe method (the only relevant\n// part of this class) is overridden in the Readable class.\n\nfunction Stream() {\n EE.call(this);\n}\n\nStream.prototype.pipe = function(dest, options) {\n var source = this;\n\n function ondata(chunk) {\n if (dest.writable) {\n if (false === dest.write(chunk) && source.pause) {\n source.pause();\n }\n }\n }\n\n source.on('data', ondata);\n\n function ondrain() {\n if (source.readable && source.resume) {\n source.resume();\n }\n }\n\n dest.on('drain', ondrain);\n\n // If the 'end' option is not supplied, dest.end() will be called when\n // source gets the 'end' or 'close' events. Only dest.end() once.\n if (!dest._isStdio && (!options || options.end !== false)) {\n source.on('end', onend);\n source.on('close', onclose);\n }\n\n var didOnEnd = false;\n function onend() {\n if (didOnEnd) return;\n didOnEnd = true;\n\n dest.end();\n }\n\n\n function onclose() {\n if (didOnEnd) return;\n didOnEnd = true;\n\n if (typeof dest.destroy === 'function') dest.destroy();\n }\n\n // don't leave dangling pipes when there are errors.\n function onerror(er) {\n cleanup();\n if (EE.listenerCount(this, 'error') === 0) {\n throw er; // Unhandled stream error in pipe.\n }\n }\n\n source.on('error', onerror);\n dest.on('error', onerror);\n\n // remove all the event listeners that were added.\n function cleanup() {\n source.removeListener('data', ondata);\n dest.removeListener('drain', ondrain);\n\n source.removeListener('end', onend);\n source.removeListener('close', onclose);\n\n source.removeListener('error', onerror);\n dest.removeListener('error', onerror);\n\n source.removeListener('end', cleanup);\n source.removeListener('close', cleanup);\n\n dest.removeListener('close', cleanup);\n }\n\n source.on('end', cleanup);\n source.on('close', cleanup);\n\n dest.on('close', cleanup);\n\n dest.emit('pipe', source);\n\n // Allow for unix-like usage: A.pipe(B).pipe(C)\n return dest;\n};\n","'use strict';\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar Buffer = require('safe-buffer').Buffer;\nvar util = require('util');\n\nfunction copyBuffer(src, target, offset) {\n src.copy(target, offset);\n}\n\nmodule.exports = function () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n BufferList.prototype.push = function push(v) {\n var entry = { data: v, next: null };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n };\n\n BufferList.prototype.unshift = function unshift(v) {\n var entry = { data: v, next: this.head };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n };\n\n BufferList.prototype.shift = function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n };\n\n BufferList.prototype.clear = function clear() {\n this.head = this.tail = null;\n this.length = 0;\n };\n\n BufferList.prototype.join = function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n while (p = p.next) {\n ret += s + p.data;\n }return ret;\n };\n\n BufferList.prototype.concat = function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n if (this.length === 1) return this.head.data;\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n return ret;\n };\n\n return BufferList;\n}();\n\nif (util && util.inspect && util.inspect.custom) {\n module.exports.prototype[util.inspect.custom] = function () {\n var obj = util.inspect({ length: this.length });\n return this.constructor.name + ' ' + obj;\n };\n}","var scope = (typeof global !== \"undefined\" && global) ||\n (typeof self !== \"undefined\" && self) ||\n window;\nvar apply = Function.prototype.apply;\n\n// DOM APIs, for completeness\n\nexports.setTimeout = function() {\n return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);\n};\nexports.setInterval = function() {\n return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);\n};\nexports.clearTimeout =\nexports.clearInterval = function(timeout) {\n if (timeout) {\n timeout.close();\n }\n};\n\nfunction Timeout(id, clearFn) {\n this._id = id;\n this._clearFn = clearFn;\n}\nTimeout.prototype.unref = Timeout.prototype.ref = function() {};\nTimeout.prototype.close = function() {\n this._clearFn.call(scope, this._id);\n};\n\n// Does not start the time, just sets up the members needed.\nexports.enroll = function(item, msecs) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = msecs;\n};\n\nexports.unenroll = function(item) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = -1;\n};\n\nexports._unrefActive = exports.active = function(item) {\n clearTimeout(item._idleTimeoutId);\n\n var msecs = item._idleTimeout;\n if (msecs >= 0) {\n item._idleTimeoutId = setTimeout(function onTimeout() {\n if (item._onTimeout)\n item._onTimeout();\n }, msecs);\n }\n};\n\n// setimmediate attaches itself to the global object\nrequire(\"setimmediate\");\n// On some exotic environments, it's not clear which object `setimmediate` was\n// able to install onto. Search each possibility in the same order as the\n// `setimmediate` library.\nexports.setImmediate = (typeof self !== \"undefined\" && self.setImmediate) ||\n (typeof global !== \"undefined\" && global.setImmediate) ||\n (this && this.setImmediate);\nexports.clearImmediate = (typeof self !== \"undefined\" && self.clearImmediate) ||\n (typeof global !== \"undefined\" && global.clearImmediate) ||\n (this && this.clearImmediate);\n","(function (global, undefined) {\n \"use strict\";\n\n if (global.setImmediate) {\n return;\n }\n\n var nextHandle = 1; // Spec says greater than zero\n var tasksByHandle = {};\n var currentlyRunningATask = false;\n var doc = global.document;\n var registerImmediate;\n\n function setImmediate(callback) {\n // Callback can either be a function or a string\n if (typeof callback !== \"function\") {\n callback = new Function(\"\" + callback);\n }\n // Copy function arguments\n var args = new Array(arguments.length - 1);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i + 1];\n }\n // Store and register the task\n var task = { callback: callback, args: args };\n tasksByHandle[nextHandle] = task;\n registerImmediate(nextHandle);\n return nextHandle++;\n }\n\n function clearImmediate(handle) {\n delete tasksByHandle[handle];\n }\n\n function run(task) {\n var callback = task.callback;\n var args = task.args;\n switch (args.length) {\n case 0:\n callback();\n break;\n case 1:\n callback(args[0]);\n break;\n case 2:\n callback(args[0], args[1]);\n break;\n case 3:\n callback(args[0], args[1], args[2]);\n break;\n default:\n callback.apply(undefined, args);\n break;\n }\n }\n\n function runIfPresent(handle) {\n // From the spec: \"Wait until any invocations of this algorithm started before this one have completed.\"\n // So if we're currently running a task, we'll need to delay this invocation.\n if (currentlyRunningATask) {\n // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a\n // \"too much recursion\" error.\n setTimeout(runIfPresent, 0, handle);\n } else {\n var task = tasksByHandle[handle];\n if (task) {\n currentlyRunningATask = true;\n try {\n run(task);\n } finally {\n clearImmediate(handle);\n currentlyRunningATask = false;\n }\n }\n }\n }\n\n function installNextTickImplementation() {\n registerImmediate = function(handle) {\n process.nextTick(function () { runIfPresent(handle); });\n };\n }\n\n function canUsePostMessage() {\n // The test against `importScripts` prevents this implementation from being installed inside a web worker,\n // where `global.postMessage` means something completely different and can't be used for this purpose.\n if (global.postMessage && !global.importScripts) {\n var postMessageIsAsynchronous = true;\n var oldOnMessage = global.onmessage;\n global.onmessage = function() {\n postMessageIsAsynchronous = false;\n };\n global.postMessage(\"\", \"*\");\n global.onmessage = oldOnMessage;\n return postMessageIsAsynchronous;\n }\n }\n\n function installPostMessageImplementation() {\n // Installs an event handler on `global` for the `message` event: see\n // * https://developer.mozilla.org/en/DOM/window.postMessage\n // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages\n\n var messagePrefix = \"setImmediate$\" + Math.random() + \"$\";\n var onGlobalMessage = function(event) {\n if (event.source === global &&\n typeof event.data === \"string\" &&\n event.data.indexOf(messagePrefix) === 0) {\n runIfPresent(+event.data.slice(messagePrefix.length));\n }\n };\n\n if (global.addEventListener) {\n global.addEventListener(\"message\", onGlobalMessage, false);\n } else {\n global.attachEvent(\"onmessage\", onGlobalMessage);\n }\n\n registerImmediate = function(handle) {\n global.postMessage(messagePrefix + handle, \"*\");\n };\n }\n\n function installMessageChannelImplementation() {\n var channel = new MessageChannel();\n channel.port1.onmessage = function(event) {\n var handle = event.data;\n runIfPresent(handle);\n };\n\n registerImmediate = function(handle) {\n channel.port2.postMessage(handle);\n };\n }\n\n function installReadyStateChangeImplementation() {\n var html = doc.documentElement;\n registerImmediate = function(handle) {\n // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted\n // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.\n var script = doc.createElement(\"script\");\n script.onreadystatechange = function () {\n runIfPresent(handle);\n script.onreadystatechange = null;\n html.removeChild(script);\n script = null;\n };\n html.appendChild(script);\n };\n }\n\n function installSetTimeoutImplementation() {\n registerImmediate = function(handle) {\n setTimeout(runIfPresent, 0, handle);\n };\n }\n\n // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.\n var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);\n attachTo = attachTo && attachTo.setTimeout ? attachTo : global;\n\n // Don't get fooled by e.g. browserify environments.\n if ({}.toString.call(global.process) === \"[object process]\") {\n // For Node.js before 0.9\n installNextTickImplementation();\n\n } else if (canUsePostMessage()) {\n // For non-IE10 modern browsers\n installPostMessageImplementation();\n\n } else if (global.MessageChannel) {\n // For web workers, where supported\n installMessageChannelImplementation();\n\n } else if (doc && \"onreadystatechange\" in doc.createElement(\"script\")) {\n // For IE 6–8\n installReadyStateChangeImplementation();\n\n } else {\n // For older browsers\n installSetTimeoutImplementation();\n }\n\n attachTo.setImmediate = setImmediate;\n attachTo.clearImmediate = clearImmediate;\n}(typeof self === \"undefined\" ? typeof global === \"undefined\" ? this : global : self));\n","\n/**\n * Module exports.\n */\n\nmodule.exports = deprecate;\n\n/**\n * Mark that a method should not be used.\n * Returns a modified function which warns once by default.\n *\n * If `localStorage.noDeprecation = true` is set, then it is a no-op.\n *\n * If `localStorage.throwDeprecation = true` is set, then deprecated functions\n * will throw an Error when invoked.\n *\n * If `localStorage.traceDeprecation = true` is set, then deprecated functions\n * will invoke `console.trace()` instead of `console.error()`.\n *\n * @param {Function} fn - the function to deprecate\n * @param {String} msg - the string to print to the console when `fn` is invoked\n * @returns {Function} a new \"deprecated\" version of `fn`\n * @api public\n */\n\nfunction deprecate (fn, msg) {\n if (config('noDeprecation')) {\n return fn;\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (config('throwDeprecation')) {\n throw new Error(msg);\n } else if (config('traceDeprecation')) {\n console.trace(msg);\n } else {\n console.warn(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n}\n\n/**\n * Checks `localStorage` for boolean values for the given `name`.\n *\n * @param {String} name\n * @returns {Boolean}\n * @api private\n */\n\nfunction config (name) {\n // accessing global.localStorage can trigger a DOMException in sandboxed iframes\n try {\n if (!global.localStorage) return false;\n } catch (_) {\n return false;\n }\n var val = global.localStorage[name];\n if (null == val) return false;\n return String(val).toLowerCase() === 'true';\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\n/*<replacement>*/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/*</replacement>*/\n\nutil.inherits(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};","module.exports = require('./lib/_stream_writable.js');\n","module.exports = require('./lib/_stream_duplex.js');\n","module.exports = require('./readable').Transform\n","module.exports = require('./readable').PassThrough\n","/* \r\n * Copyright (c) 2016, Pierre-Anthony Lemieux <pal@sandflow.com>\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *\r\n * * Redistributions of source code must retain the above copyright notice, this\r\n * list of conditions and the following disclaimer.\r\n * * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the documentation\r\n * and/or other materials provided with the distribution.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\r\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n * POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\n/**\r\n * @module imscHTML\r\n */\r\n\r\n;\r\n(function (imscHTML, imscNames, imscStyles) {\r\n\r\n /**\r\n * Function that maps <pre>smpte:background</pre> URIs to URLs resolving to image resource\r\n * @callback IMGResolver\r\n * @param {string} <pre>smpte:background</pre> URI\r\n * @return {string} PNG resource URL\r\n */\r\n\r\n\r\n /**\r\n * Renders an ISD object (returned by <pre>generateISD()</pre>) into a \r\n * parent element, that must be attached to the DOM. The ISD will be rendered\r\n * into a child <pre>div</pre>\r\n * with heigh and width equal to the clientHeight and clientWidth of the element,\r\n * unless explicitly specified otherwise by the caller. Images URIs specified \r\n * by <pre>smpte:background</pre> attributes are mapped to image resource URLs\r\n * by an <pre>imgResolver</pre> function. The latter takes the value of <code>smpte:background</code>\r\n * attribute and an <code>img</code> DOM element as input, and is expected to\r\n * set the <code>src</code> attribute of the <code>img</code> to the absolute URI of the image.\r\n * <pre>displayForcedOnlyMode</pre> sets the (boolean)\r\n * value of the IMSC1 displayForcedOnlyMode parameter. The function returns\r\n * an opaque object that should passed in <code>previousISDState</code> when this function\r\n * is called for the next ISD, otherwise <code>previousISDState</code> should be set to \r\n * <code>null</code>.\r\n * \r\n * @param {Object} isd ISD to be rendered\r\n * @param {Object} element Element into which the ISD is rendered\r\n * @param {?IMGResolver} imgResolver Resolve <pre>smpte:background</pre> URIs into URLs.\r\n * @param {?number} eheight Height (in pixel) of the child <div>div</div> or null \r\n * to use clientHeight of the parent element\r\n * @param {?number} ewidth Width (in pixel) of the child <div>div</div> or null\r\n * to use clientWidth of the parent element\r\n * @param {?boolean} displayForcedOnlyMode Value of the IMSC1 displayForcedOnlyMode parameter,\r\n * or false if null \r\n * @param {?module:imscUtils.ErrorHandler} errorHandler Error callback\r\n * @param {Object} previousISDState State saved during processing of the previous ISD, or null if initial call\r\n * @param {?boolean} enableRollUp Enables roll-up animations (see CEA 708)\r\n * @return {Object} ISD state to be provided when this funtion is called for the next ISD\r\n */\r\n\r\n imscHTML.render = function (isd,\r\n element,\r\n imgResolver,\r\n eheight,\r\n ewidth,\r\n displayForcedOnlyMode,\r\n errorHandler,\r\n previousISDState,\r\n enableRollUp\r\n ) {\r\n\r\n /* maintain aspect ratio if specified */\r\n\r\n var height = eheight || element.clientHeight;\r\n var width = ewidth || element.clientWidth;\r\n\r\n if (isd.aspectRatio !== null) {\r\n\r\n var twidth = height * isd.aspectRatio;\r\n\r\n if (twidth > width) {\r\n\r\n height = Math.round(width / isd.aspectRatio);\r\n\r\n } else {\r\n\r\n width = twidth;\r\n\r\n }\r\n\r\n }\r\n\r\n var rootcontainer = document.createElement(\"div\");\r\n\r\n rootcontainer.style.position = \"relative\";\r\n rootcontainer.style.width = width + \"px\";\r\n rootcontainer.style.height = height + \"px\";\r\n rootcontainer.style.margin = \"auto\";\r\n rootcontainer.style.top = 0;\r\n rootcontainer.style.bottom = 0;\r\n rootcontainer.style.left = 0;\r\n rootcontainer.style.right = 0;\r\n rootcontainer.style.zIndex = 0;\r\n\r\n var context = {\r\n h: height,\r\n w: width,\r\n regionH: null,\r\n regionW: null,\r\n imgResolver: imgResolver,\r\n displayForcedOnlyMode: displayForcedOnlyMode || false,\r\n isd: isd,\r\n errorHandler: errorHandler,\r\n previousISDState: previousISDState,\r\n enableRollUp: enableRollUp || false,\r\n currentISDState: {},\r\n flg: null, /* current fillLineGap value if active, null otherwise */\r\n lp: null, /* current linePadding value if active, null otherwise */\r\n mra: null, /* current multiRowAlign value if active, null otherwise */\r\n ipd: null, /* inline progression direction (lr, rl, tb) */\r\n bpd: null /* block progression direction (lr, rl, tb) */\r\n };\r\n\r\n element.appendChild(rootcontainer);\r\n\r\n for (var i in isd.contents) {\r\n\r\n processElement(context, rootcontainer, isd.contents[i]);\r\n\r\n }\r\n\r\n return context.currentISDState;\r\n\r\n };\r\n\r\n function processElement(context, dom_parent, isd_element) {\r\n\r\n var e;\r\n\r\n if (isd_element.kind === 'region') {\r\n\r\n e = document.createElement(\"div\");\r\n e.style.position = \"absolute\";\r\n\r\n } else if (isd_element.kind === 'body') {\r\n\r\n e = document.createElement(\"div\");\r\n\r\n } else if (isd_element.kind === 'div') {\r\n\r\n e = document.createElement(\"div\");\r\n\r\n } else if (isd_element.kind === 'p') {\r\n\r\n e = document.createElement(\"p\");\r\n\r\n } else if (isd_element.kind === 'span') {\r\n\r\n e = document.createElement(\"span\");\r\n\r\n //e.textContent = isd_element.text;\r\n\r\n } else if (isd_element.kind === 'br') {\r\n\r\n e = document.createElement(\"br\");\r\n\r\n }\r\n\r\n if (!e) {\r\n\r\n reportError(context.errorHandler, \"Error processing ISD element kind: \" + isd_element.kind);\r\n\r\n return;\r\n\r\n }\r\n\r\n /* override UA default margin */\r\n /* TODO: should apply to <p> only */\r\n\r\n e.style.margin = \"0\";\r\n\r\n /* tranform TTML styles to CSS styles */\r\n\r\n for (var i in STYLING_MAP_DEFS) {\r\n\r\n var sm = STYLING_MAP_DEFS[i];\r\n\r\n var attr = isd_element.styleAttrs[sm.qname];\r\n\r\n if (attr !== undefined && sm.map !== null) {\r\n\r\n sm.map(context, e, isd_element, attr);\r\n\r\n }\r\n\r\n }\r\n\r\n var proc_e = e;\r\n\r\n /* remember writing direction */\r\n\r\n if (isd_element.kind === \"region\") {\r\n\r\n var wdir = isd_element.styleAttrs[imscStyles.byName.writingMode.qname];\r\n\r\n if (wdir === \"lrtb\" || wdir === \"lr\") {\r\n\r\n context.ipd = \"lr\";\r\n context.bpd = \"tb\";\r\n\r\n } else if (wdir === \"rltb\" || wdir === \"rl\") {\r\n\r\n context.ipd = \"rl\";\r\n context.bpd = \"tb\";\r\n\r\n } else if (wdir === \"tblr\") {\r\n\r\n context.ipd = \"tb\";\r\n context.bpd = \"lr\";\r\n\r\n } else if (wdir === \"tbrl\" || wdir === \"tb\") {\r\n\r\n context.ipd = \"tb\";\r\n context.bpd = \"rl\";\r\n\r\n }\r\n\r\n }\r\n\r\n /* do we have linePadding ? */\r\n\r\n var lp = isd_element.styleAttrs[imscStyles.byName.linePadding.qname];\r\n\r\n if (lp && lp > 0) {\r\n\r\n /* apply padding to the <p> so that line padding does not cause line wraps */\r\n\r\n var padmeasure = Math.ceil(lp * context.h) + \"px\";\r\n\r\n if (context.bpd === \"tb\") {\r\n\r\n proc_e.style.paddingLeft = padmeasure;\r\n proc_e.style.paddingRight = padmeasure;\r\n\r\n } else {\r\n\r\n proc_e.style.paddingTop = padmeasure;\r\n proc_e.style.paddingBottom = padmeasure;\r\n\r\n }\r\n\r\n context.lp = lp;\r\n }\r\n\r\n // do we have multiRowAlign?\r\n\r\n var mra = isd_element.styleAttrs[imscStyles.byName.multiRowAlign.qname];\r\n\r\n if (mra && mra !== \"auto\") {\r\n\r\n /* create inline block to handle multirowAlign */\r\n\r\n var s = document.createElement(\"span\");\r\n\r\n s.style.display = \"inline-block\";\r\n\r\n s.style.textAlign = mra;\r\n\r\n e.appendChild(s);\r\n\r\n proc_e = s;\r\n\r\n context.mra = mra;\r\n\r\n }\r\n\r\n /* remember we are filling line gaps */\r\n\r\n if (isd_element.styleAttrs[imscStyles.byName.fillLineGap.qname]) {\r\n context.flg = true;\r\n }\r\n\r\n\r\n if (isd_element.kind === \"span\" && isd_element.text) {\r\n\r\n if (context.lp || context.mra || context.flg) {\r\n\r\n // wrap characters in spans to find the line wrap locations\r\n\r\n var cbuf = '';\r\n\r\n for (var j = 0; j < isd_element.text.length; j++) {\r\n\r\n cbuf += isd_element.text.charAt(j);\r\n\r\n var cc = isd_element.text.charCodeAt(j);\r\n\r\n if (cc < 0xD800 || cc > 0xDBFF || j === isd_element.text.length) {\r\n\r\n /* wrap the character(s) in a span unless it is a high surrogate */\r\n\r\n var span = document.createElement(\"span\");\r\n\r\n span.textContent = cbuf;\r\n \r\n e.appendChild(span);\r\n\r\n cbuf = '';\r\n\r\n }\r\n\r\n }\r\n\r\n } else {\r\n\r\n e.textContent = isd_element.text;\r\n\r\n }\r\n }\r\n\r\n dom_parent.appendChild(e);\r\n\r\n /* process the children of the ISD element */\r\n\r\n for (var k in isd_element.contents) {\r\n\r\n processElement(context, proc_e, isd_element.contents[k]);\r\n\r\n }\r\n\r\n /* list of lines */\r\n\r\n var linelist = [];\r\n\r\n\r\n /* paragraph processing */\r\n /* TODO: linePadding only supported for horizontal scripts */\r\n\r\n if ((context.lp || context.mra || context.flg) && isd_element.kind === \"p\") {\r\n\r\n constructLineList(context, proc_e, linelist, null);\r\n\r\n /* insert line breaks for multirowalign */\r\n\r\n if (context.mra) {\r\n\r\n applyMultiRowAlign(linelist);\r\n\r\n context.mra = null;\r\n\r\n }\r\n\r\n /* add linepadding */\r\n\r\n if (context.lp) {\r\n\r\n applyLinePadding(linelist, context.lp * context.h, context);\r\n\r\n context.lp = null;\r\n\r\n }\r\n\r\n /* fill line gaps linepadding */\r\n\r\n if (context.flg) {\r\n\r\n var par_edges = rect2edges(proc_e.getBoundingClientRect(), context);\r\n\r\n applyFillLineGap(linelist, par_edges.before, par_edges.after, context);\r\n\r\n context.flg = null;\r\n\r\n }\r\n\r\n }\r\n\r\n\r\n /* region processing */\r\n\r\n if (isd_element.kind === \"region\") {\r\n\r\n /* build line list */\r\n\r\n constructLineList(context, proc_e, linelist);\r\n\r\n /* perform roll up if needed */\r\n\r\n if ((context.bpd === \"tb\") &&\r\n context.enableRollUp &&\r\n isd_element.contents.length > 0 &&\r\n isd_element.styleAttrs[imscStyles.byName.displayAlign.qname] === 'after') {\r\n\r\n /* horrible hack, perhaps default region id should be underscore everywhere? */\r\n\r\n var rid = isd_element.id === '' ? '_' : isd_element.id;\r\n\r\n var rb = new RegionPBuffer(rid, linelist);\r\n\r\n context.currentISDState[rb.id] = rb;\r\n\r\n if (context.previousISDState &&\r\n rb.id in context.previousISDState &&\r\n context.previousISDState[rb.id].plist.length > 0 &&\r\n rb.plist.length > 1 &&\r\n rb.plist[rb.plist.length - 2].text ===\r\n context.previousISDState[rb.id].plist[context.previousISDState[rb.id].plist.length - 1].text) {\r\n\r\n var body_elem = e.firstElementChild;\r\n \r\n var h = rb.plist[rb.plist.length - 1].after - rb.plist[rb.plist.length - 1].before;\r\n\r\n body_elem.style.bottom = \"-\" + h + \"px\";\r\n body_elem.style.transition = \"transform 0.4s\";\r\n body_elem.style.position = \"relative\";\r\n body_elem.style.transform = \"translateY(-\" + h + \"px)\";\r\n\r\n }\r\n\r\n }\r\n\r\n /* TODO: clean-up the spans ? */\r\n\r\n }\r\n }\r\n\r\n function applyLinePadding(lineList, lp, context) {\r\n\r\n for (var i in lineList) {\r\n\r\n var l = lineList[i].elements.length;\r\n\r\n var se = lineList[i].elements[lineList[i].start_elem];\r\n\r\n var ee = lineList[i].elements[lineList[i].end_elem];\r\n\r\n var pospadpxlen = Math.ceil(lp) + \"px\";\r\n\r\n var negpadpxlen = \"-\" + Math.ceil(lp) + \"px\";\r\n\r\n if (l !== 0) {\r\n\r\n if (context.ipd === \"lr\") {\r\n\r\n se.node.style.borderLeftColor = se.bgcolor || \"#00000000\";\r\n se.node.style.borderLeftStyle = \"solid\";\r\n se.node.style.borderLeftWidth = pospadpxlen;\r\n se.node.style.marginLeft = negpadpxlen;\r\n\r\n } else if (context.ipd === \"rl\") {\r\n\r\n se.node.style.borderRightColor = se.bgcolor || \"#00000000\";\r\n se.node.style.borderRightStyle = \"solid\";\r\n se.node.style.borderRightWidth = pospadpxlen;\r\n se.node.style.marginRight = negpadpxlen;\r\n\r\n } else if (context.ipd === \"tb\") {\r\n\r\n se.node.style.borderTopColor = se.bgcolor || \"#00000000\";\r\n se.node.style.borderTopStyle = \"solid\";\r\n se.node.style.borderTopWidth = pospadpxlen;\r\n se.node.style.marginTop = negpadpxlen;\r\n\r\n }\r\n\r\n if (context.ipd === \"lr\") {\r\n\r\n ee.node.style.borderRightColor = ee.bgcolor || \"#00000000\";\r\n ee.node.style.borderRightStyle = \"solid\";\r\n ee.node.style.borderRightWidth = pospadpxlen;\r\n ee.node.style.marginRight = negpadpxlen;\r\n\r\n } else if (context.ipd === \"rl\") {\r\n\r\n ee.node.style.borderLeftColor = ee.bgcolor || \"#00000000\";\r\n ee.node.style.borderLeftStyle = \"solid\";\r\n ee.node.style.borderLeftWidth = pospadpxlen;\r\n ee.node.style.marginLeft = negpadpxlen;\r\n\r\n } else if (context.ipd === \"tb\") {\r\n\r\n ee.node.style.borderBottomColor = ee.bgcolor || \"#00000000\";\r\n ee.node.style.borderBottomStyle = \"solid\";\r\n ee.node.style.borderBottomWidth = pospadpxlen;\r\n ee.node.style.marginBottom = negpadpxlen;\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n function applyMultiRowAlign(lineList) {\r\n\r\n /* apply an explicit br to all but the last line */\r\n\r\n for (var i = 0; i < lineList.length - 1; i++) {\r\n\r\n var l = lineList[i].elements.length;\r\n\r\n if (l !== 0 && lineList[i].br === false) {\r\n var br = document.createElement(\"br\");\r\n\r\n var lastnode = lineList[i].elements[l - 1].node;\r\n\r\n lastnode.parentElement.insertBefore(br, lastnode.nextSibling);\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n function applyFillLineGap(lineList, par_before, par_after, context) {\r\n\r\n /* positive for BPD = lr and tb, negative for BPD = rl */\r\n var s = Math.sign(par_after - par_before);\r\n\r\n for (var i = 0; i <= lineList.length; i++) {\r\n\r\n /* compute frontier between lines */\r\n\r\n var frontier;\r\n\r\n if (i === 0) {\r\n\r\n frontier = par_before;\r\n\r\n } else if (i === lineList.length) {\r\n\r\n frontier = par_after;\r\n\r\n } else {\r\n\r\n frontier = (lineList[i].before + lineList[i - 1].after) / 2;\r\n\r\n }\r\n\r\n /* padding amount */\r\n\r\n var pad;\r\n\r\n /* current element */\r\n\r\n var e;\r\n\r\n /* before line */\r\n\r\n if (i > 0) {\r\n\r\n for (var j = 0; j < lineList[i - 1].elements.length; j++) {\r\n\r\n if (lineList[i - 1].elements[j].bgcolor === null) continue;\r\n\r\n e = lineList[i - 1].elements[j];\r\n\r\n if (s * (e.after - frontier) < 0) {\r\n\r\n pad = Math.ceil(Math.abs(frontier - e.after)) + \"px\";\r\n\r\n e.node.style.backgroundColor = e.bgcolor;\r\n\r\n if (context.bpd === \"lr\") {\r\n\r\n e.node.style.paddingRight = pad;\r\n\r\n\r\n } else if (context.bpd === \"rl\") {\r\n\r\n e.node.style.paddingLeft = pad;\r\n\r\n } else if (context.bpd === \"tb\") {\r\n\r\n e.node.style.paddingBottom = pad;\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n /* after line */\r\n\r\n if (i < lineList.length) {\r\n\r\n for (var k = 0; k < lineList[i].elements.length; k++) {\r\n\r\n e = lineList[i].elements[k];\r\n\r\n if (e.bgcolor === null) continue;\r\n\r\n if (s * (e.before - frontier) > 0) {\r\n\r\n pad = Math.ceil(Math.abs(e.before - frontier)) + \"px\";\r\n\r\n e.node.style.backgroundColor = e.bgcolor;\r\n\r\n if (context.bpd === \"lr\") {\r\n\r\n e.node.style.paddingLeft = pad;\r\n\r\n\r\n } else if (context.bpd === \"rl\") {\r\n\r\n e.node.style.paddingRight = pad;\r\n\r\n\r\n } else if (context.bpd === \"tb\") {\r\n\r\n e.node.style.paddingTop = pad;\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n function RegionPBuffer(id, lineList) {\r\n\r\n this.id = id;\r\n\r\n this.plist = lineList;\r\n\r\n }\r\n\r\n function pruneEmptySpans(element) {\r\n\r\n var child = element.firstChild;\r\n\r\n while (child) {\r\n\r\n var nchild = child.nextSibling;\r\n\r\n if (child.nodeType === Node.ELEMENT_NODE &&\r\n child.localName === 'span') {\r\n\r\n pruneEmptySpans(child);\r\n\r\n if (child.childElementCount === 0 &&\r\n child.textContent.length === 0) {\r\n\r\n element.removeChild(child);\r\n\r\n }\r\n }\r\n\r\n child = nchild;\r\n }\r\n\r\n }\r\n\r\n function rect2edges(rect, context) {\r\n\r\n var edges = {before: null, after: null, start: null, end: null};\r\n\r\n if (context.bpd === \"tb\") {\r\n\r\n edges.before = rect.top;\r\n edges.after = rect.bottom;\r\n\r\n if (context.ipd === \"lr\") {\r\n\r\n edges.start = rect.left;\r\n edges.end = rect.right;\r\n\r\n } else {\r\n\r\n edges.start = rect.right;\r\n edges.end = rect.left;\r\n }\r\n\r\n } else if (context.bpd === \"lr\") {\r\n\r\n edges.before = rect.left;\r\n edges.after = rect.right;\r\n edges.start = rect.top;\r\n edges.end = rect.bottom;\r\n\r\n } else if (context.bpd === \"rl\") {\r\n\r\n edges.before = rect.right;\r\n edges.after = rect.left;\r\n edges.start = rect.top;\r\n edges.end = rect.bottom;\r\n\r\n }\r\n\r\n return edges;\r\n\r\n }\r\n\r\n function constructLineList(context, element, llist, bgcolor) {\r\n\r\n var curbgcolor = element.style.backgroundColor || bgcolor;\r\n\r\n if (element.childElementCount === 0) {\r\n\r\n if (element.localName === 'span') {\r\n\r\n var r = element.getBoundingClientRect();\r\n\r\n /* skip if span is not displayed */\r\n\r\n if (r.height === 0 || r.width === 0) return;\r\n\r\n var edges = rect2edges(r, context);\r\n\r\n if (llist.length === 0 ||\r\n (!isSameLine(edges.before, edges.after, llist[llist.length - 1].before, llist[llist.length - 1].after))\r\n ) {\r\n\r\n llist.push({\r\n before: edges.before,\r\n after: edges.after,\r\n start: edges.start,\r\n end: edges.end,\r\n start_elem: 0,\r\n end_elem: 0,\r\n elements: [],\r\n text: \"\",\r\n br: false\r\n });\r\n\r\n } else {\r\n\r\n /* positive for BPD = lr and tb, negative for BPD = rl */\r\n var bpd_dir = Math.sign(edges.after - edges.before);\r\n\r\n /* positive for IPD = lr and tb, negative for IPD = rl */\r\n var ipd_dir = Math.sign(edges.end - edges.start);\r\n\r\n /* check if the line height has increased */\r\n\r\n if (bpd_dir * (edges.before - llist[llist.length - 1].before) < 0) {\r\n llist[llist.length - 1].before = edges.before;\r\n }\r\n\r\n if (bpd_dir * (edges.after - llist[llist.length - 1].after) > 0) {\r\n llist[llist.length - 1].after = edges.after;\r\n }\r\n\r\n if (ipd_dir * (edges.start - llist[llist.length - 1].start) < 0) {\r\n llist[llist.length - 1].start = edges.start;\r\n llist[llist.length - 1].start_elem = llist[llist.length - 1].elements.length;\r\n }\r\n\r\n if (ipd_dir * (edges.end - llist[llist.length - 1].end) > 0) {\r\n llist[llist.length - 1].end = edges.end;\r\n llist[llist.length - 1].end_elem = llist[llist.length - 1].elements.length;\r\n }\r\n\r\n }\r\n\r\n llist[llist.length - 1].text += element.textContent;\r\n\r\n llist[llist.length - 1].elements.push(\r\n {\r\n node: element,\r\n bgcolor: curbgcolor,\r\n before: edges.before,\r\n after: edges.after\r\n }\r\n );\r\n\r\n } else if (element.localName === 'br' && llist.length !== 0) {\r\n\r\n llist[llist.length - 1].br = true;\r\n\r\n }\r\n\r\n } else {\r\n\r\n var child = element.firstChild;\r\n\r\n while (child) {\r\n\r\n if (child.nodeType === Node.ELEMENT_NODE) {\r\n\r\n constructLineList(context, child, llist, curbgcolor);\r\n\r\n }\r\n\r\n child = child.nextSibling;\r\n }\r\n }\r\n\r\n }\r\n\r\n function isSameLine(before1, after1, before2, after2) {\r\n\r\n return ((after1 < after2) && (before1 > before2)) || ((after2 <= after1) && (before2 >= before1));\r\n\r\n }\r\n\r\n function HTMLStylingMapDefintion(qName, mapFunc) {\r\n this.qname = qName;\r\n this.map = mapFunc;\r\n }\r\n\r\n var STYLING_MAP_DEFS = [\r\n\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling backgroundColor\",\r\n function (context, dom_element, isd_element, attr) {\r\n\r\n /* skip if transparent */\r\n if (attr[3] === 0) return;\r\n\r\n dom_element.style.backgroundColor = \"rgba(\" +\r\n attr[0].toString() + \",\" +\r\n attr[1].toString() + \",\" +\r\n attr[2].toString() + \",\" +\r\n (attr[3] / 255).toString() +\r\n \")\";\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling color\",\r\n function (context, dom_element, isd_element, attr) {\r\n dom_element.style.color = \"rgba(\" +\r\n attr[0].toString() + \",\" +\r\n attr[1].toString() + \",\" +\r\n attr[2].toString() + \",\" +\r\n (attr[3] / 255).toString() +\r\n \")\";\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling direction\",\r\n function (context, dom_element, isd_element, attr) {\r\n dom_element.style.direction = attr;\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling display\",\r\n function (context, dom_element, isd_element, attr) {}\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling displayAlign\",\r\n function (context, dom_element, isd_element, attr) {\r\n\r\n /* see https://css-tricks.com/snippets/css/a-guide-to-flexbox/ */\r\n\r\n /* TODO: is this affected by writing direction? */\r\n\r\n dom_element.style.display = \"flex\";\r\n dom_element.style.flexDirection = \"column\";\r\n\r\n\r\n if (attr === \"before\") {\r\n\r\n dom_element.style.justifyContent = \"flex-start\";\r\n\r\n } else if (attr === \"center\") {\r\n\r\n dom_element.style.justifyContent = \"center\";\r\n\r\n } else if (attr === \"after\") {\r\n\r\n dom_element.style.justifyContent = \"flex-end\";\r\n }\r\n\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling extent\",\r\n function (context, dom_element, isd_element, attr) {\r\n /* TODO: this is super ugly */\r\n\r\n context.regionH = (attr.h * context.h);\r\n context.regionW = (attr.w * context.w);\r\n\r\n /* \r\n * CSS height/width are measured against the content rectangle,\r\n * whereas TTML height/width include padding\r\n */\r\n\r\n var hdelta = 0;\r\n var wdelta = 0;\r\n\r\n var p = isd_element.styleAttrs[\"http://www.w3.org/ns/ttml#styling padding\"];\r\n\r\n if (!p) {\r\n\r\n /* error */\r\n\r\n } else {\r\n\r\n hdelta = (p[0] + p[2]) * context.h;\r\n wdelta = (p[1] + p[3]) * context.w;\r\n\r\n }\r\n\r\n dom_element.style.height = (context.regionH - hdelta) + \"px\";\r\n dom_element.style.width = (context.regionW - wdelta) + \"px\";\r\n\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling fontFamily\",\r\n function (context, dom_element, isd_element, attr) {\r\n\r\n var rslt = [];\r\n\r\n /* per IMSC1 */\r\n\r\n for (var i in attr) {\r\n\r\n if (attr[i] === \"monospaceSerif\") {\r\n\r\n rslt.push(\"Courier New\");\r\n rslt.push('\"Liberation Mono\"');\r\n rslt.push(\"Courier\");\r\n rslt.push(\"monospace\");\r\n\r\n } else if (attr[i] === \"proportionalSansSerif\") {\r\n\r\n rslt.push(\"Arial\");\r\n rslt.push(\"Helvetica\");\r\n rslt.push('\"Liberation Sans\"');\r\n rslt.push(\"sans-serif\");\r\n\r\n } else if (attr[i] === \"monospace\") {\r\n\r\n rslt.push(\"monospace\");\r\n\r\n } else if (attr[i] === \"sansSerif\") {\r\n\r\n rslt.push(\"sans-serif\");\r\n\r\n } else if (attr[i] === \"serif\") {\r\n\r\n rslt.push(\"serif\");\r\n\r\n } else if (attr[i] === \"monospaceSansSerif\") {\r\n\r\n rslt.push(\"Consolas\");\r\n rslt.push(\"monospace\");\r\n\r\n } else if (attr[i] === \"proportionalSerif\") {\r\n\r\n rslt.push(\"serif\");\r\n\r\n } else {\r\n\r\n rslt.push(attr[i]);\r\n\r\n }\r\n\r\n }\r\n\r\n dom_element.style.fontFamily = rslt.join(\",\");\r\n }\r\n ),\r\n\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling fontSize\",\r\n function (context, dom_element, isd_element, attr) {\r\n dom_element.style.fontSize = (attr * context.h) + \"px\";\r\n }\r\n ),\r\n\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling fontStyle\",\r\n function (context, dom_element, isd_element, attr) {\r\n dom_element.style.fontStyle = attr;\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling fontWeight\",\r\n function (context, dom_element, isd_element, attr) {\r\n dom_element.style.fontWeight = attr;\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling lineHeight\",\r\n function (context, dom_element, isd_element, attr) {\r\n if (attr === \"normal\") {\r\n\r\n dom_element.style.lineHeight = \"normal\";\r\n\r\n } else {\r\n\r\n dom_element.style.lineHeight = (attr * context.h) + \"px\";\r\n }\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling opacity\",\r\n function (context, dom_element, isd_element, attr) {\r\n dom_element.style.opacity = attr;\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling origin\",\r\n function (context, dom_element, isd_element, attr) {\r\n dom_element.style.top = (attr.h * context.h) + \"px\";\r\n dom_element.style.left = (attr.w * context.w) + \"px\";\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling overflow\",\r\n function (context, dom_element, isd_element, attr) {\r\n dom_element.style.overflow = attr;\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling padding\",\r\n function (context, dom_element, isd_element, attr) {\r\n\r\n /* attr: top,left,bottom,right*/\r\n\r\n /* style: top right bottom left*/\r\n\r\n var rslt = [];\r\n\r\n rslt[0] = (attr[0] * context.h) + \"px\";\r\n rslt[1] = (attr[3] * context.w) + \"px\";\r\n rslt[2] = (attr[2] * context.h) + \"px\";\r\n rslt[3] = (attr[1] * context.w) + \"px\";\r\n\r\n dom_element.style.padding = rslt.join(\" \");\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling showBackground\",\r\n null\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling textAlign\",\r\n function (context, dom_element, isd_element, attr) {\r\n\r\n var ta;\r\n var dir = isd_element.styleAttrs[imscStyles.byName.direction.qname];\r\n\r\n /* handle UAs that do not understand start or end */\r\n\r\n if (attr === \"start\") {\r\n\r\n ta = (dir === \"rtl\") ? \"right\" : \"left\";\r\n\r\n } else if (attr === \"end\") {\r\n\r\n ta = (dir === \"rtl\") ? \"left\" : \"right\";\r\n\r\n } else {\r\n\r\n ta = attr;\r\n\r\n }\r\n\r\n dom_element.style.textAlign = ta;\r\n\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling textDecoration\",\r\n function (context, dom_element, isd_element, attr) {\r\n dom_element.style.textDecoration = attr.join(\" \").replace(\"lineThrough\", \"line-through\");\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling textOutline\",\r\n function (context, dom_element, isd_element, attr) {\r\n\r\n if (attr === \"none\") {\r\n\r\n dom_element.style.textShadow = \"\";\r\n\r\n } else {\r\n\r\n dom_element.style.textShadow = \"rgba(\" +\r\n attr.color[0].toString() + \",\" +\r\n attr.color[1].toString() + \",\" +\r\n attr.color[2].toString() + \",\" +\r\n (attr.color[3] / 255).toString() +\r\n \")\" + \" 0px 0px \" +\r\n (attr.thickness * context.h) + \"px\";\r\n\r\n }\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling unicodeBidi\",\r\n function (context, dom_element, isd_element, attr) {\r\n\r\n var ub;\r\n\r\n if (attr === 'bidiOverride') {\r\n ub = \"bidi-override\";\r\n } else {\r\n ub = attr;\r\n }\r\n\r\n dom_element.style.unicodeBidi = ub;\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling visibility\",\r\n function (context, dom_element, isd_element, attr) {\r\n dom_element.style.visibility = attr;\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling wrapOption\",\r\n function (context, dom_element, isd_element, attr) {\r\n\r\n if (attr === \"wrap\") {\r\n\r\n if (isd_element.space === \"preserve\") {\r\n dom_element.style.whiteSpace = \"pre-wrap\";\r\n } else {\r\n dom_element.style.whiteSpace = \"normal\";\r\n }\r\n\r\n } else {\r\n\r\n if (isd_element.space === \"preserve\") {\r\n\r\n dom_element.style.whiteSpace = \"pre\";\r\n\r\n } else {\r\n dom_element.style.whiteSpace = \"noWrap\";\r\n }\r\n\r\n }\r\n\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling writingMode\",\r\n function (context, dom_element, isd_element, attr) {\r\n if (attr === \"lrtb\" || attr === \"lr\") {\r\n\r\n dom_element.style.writingMode = \"horizontal-tb\";\r\n\r\n } else if (attr === \"rltb\" || attr === \"rl\") {\r\n\r\n dom_element.style.writingMode = \"horizontal-tb\";\r\n\r\n } else if (attr === \"tblr\") {\r\n\r\n dom_element.style.writingMode = \"vertical-lr\";\r\n\r\n } else if (attr === \"tbrl\" || attr === \"tb\") {\r\n\r\n dom_element.style.writingMode = \"vertical-rl\";\r\n\r\n }\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml#styling zIndex\",\r\n function (context, dom_element, isd_element, attr) {\r\n dom_element.style.zIndex = attr;\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.smpte-ra.org/schemas/2052-1/2010/smpte-tt backgroundImage\",\r\n function (context, dom_element, isd_element, attr) {\r\n\r\n if (context.imgResolver !== null && attr !== null) {\r\n\r\n var img = document.createElement(\"img\");\r\n\r\n var uri = context.imgResolver(attr, img);\r\n\r\n if (uri)\r\n img.src = uri;\r\n\r\n img.height = context.regionH;\r\n img.width = context.regionW;\r\n\r\n dom_element.appendChild(img);\r\n }\r\n }\r\n ),\r\n new HTMLStylingMapDefintion(\r\n \"http://www.w3.org/ns/ttml/profile/imsc1#styling forcedDisplay\",\r\n function (context, dom_element, isd_element, attr) {\r\n\r\n if (context.displayForcedOnlyMode && attr === false) {\r\n dom_element.style.visibility = \"hidden\";\r\n }\r\n\r\n }\r\n )\r\n ];\r\n\r\n var STYLMAP_BY_QNAME = {};\r\n\r\n for (var i in STYLING_MAP_DEFS) {\r\n\r\n STYLMAP_BY_QNAME[STYLING_MAP_DEFS[i].qname] = STYLING_MAP_DEFS[i];\r\n }\r\n\r\n function reportError(errorHandler, msg) {\r\n\r\n if (errorHandler && errorHandler.error && errorHandler.error(msg))\r\n throw msg;\r\n\r\n }\r\n\r\n})(typeof exports === 'undefined' ? this.imscHTML = {} : exports,\r\n typeof imscNames === 'undefined' ? require(\"./names\") : imscNames,\r\n typeof imscStyles === 'undefined' ? require(\"./styles\") : imscStyles);","// This file can be required in Browserify and Node.js for automatic polyfill\n// To use it: require('es6-promise/auto');\n'use strict';\nmodule.exports = require('./').polyfill();\n","/*!\n * @overview es6-promise - a tiny implementation of Promises/A+.\n * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)\n * @license Licensed under MIT license\n * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE\n * @version v4.2.8+1e68dce6\n */\n\n(function (global, factory) {\n\ttypeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n\ttypeof define === 'function' && define.amd ? define(factory) :\n\t(global.ES6Promise = factory());\n}(this, (function () { 'use strict';\n\nfunction objectOrFunction(x) {\n var type = typeof x;\n return x !== null && (type === 'object' || type === 'function');\n}\n\nfunction isFunction(x) {\n return typeof x === 'function';\n}\n\n\n\nvar _isArray = void 0;\nif (Array.isArray) {\n _isArray = Array.isArray;\n} else {\n _isArray = function (x) {\n return Object.prototype.toString.call(x) === '[object Array]';\n };\n}\n\nvar isArray = _isArray;\n\nvar len = 0;\nvar vertxNext = void 0;\nvar customSchedulerFn = void 0;\n\nvar asap = function asap(callback, arg) {\n queue[len] = callback;\n queue[len + 1] = arg;\n len += 2;\n if (len === 2) {\n // If len is 2, that means that we need to schedule an async flush.\n // If additional callbacks are queued before the queue is flushed, they\n // will be processed by this flush that we are scheduling.\n if (customSchedulerFn) {\n customSchedulerFn(flush);\n } else {\n scheduleFlush();\n }\n }\n};\n\nfunction setScheduler(scheduleFn) {\n customSchedulerFn = scheduleFn;\n}\n\nfunction setAsap(asapFn) {\n asap = asapFn;\n}\n\nvar browserWindow = typeof window !== 'undefined' ? window : undefined;\nvar browserGlobal = browserWindow || {};\nvar BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;\nvar isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';\n\n// test for web worker but not in IE10\nvar isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';\n\n// node\nfunction useNextTick() {\n // node version 0.10.x displays a deprecation warning when nextTick is used recursively\n // see https://github.com/cujojs/when/issues/410 for details\n return function () {\n return process.nextTick(flush);\n };\n}\n\n// vertx\nfunction useVertxTimer() {\n if (typeof vertxNext !== 'undefined') {\n return function () {\n vertxNext(flush);\n };\n }\n\n return useSetTimeout();\n}\n\nfunction useMutationObserver() {\n var iterations = 0;\n var observer = new BrowserMutationObserver(flush);\n var node = document.createTextNode('');\n observer.observe(node, { characterData: true });\n\n return function () {\n node.data = iterations = ++iterations % 2;\n };\n}\n\n// web worker\nfunction useMessageChannel() {\n var channel = new MessageChannel();\n channel.port1.onmessage = flush;\n return function () {\n return channel.port2.postMessage(0);\n };\n}\n\nfunction useSetTimeout() {\n // Store setTimeout reference so es6-promise will be unaffected by\n // other code modifying setTimeout (like sinon.useFakeTimers())\n var globalSetTimeout = setTimeout;\n return function () {\n return globalSetTimeout(flush, 1);\n };\n}\n\nvar queue = new Array(1000);\nfunction flush() {\n for (var i = 0; i < len; i += 2) {\n var callback = queue[i];\n var arg = queue[i + 1];\n\n callback(arg);\n\n queue[i] = undefined;\n queue[i + 1] = undefined;\n }\n\n len = 0;\n}\n\nfunction attemptVertx() {\n try {\n var vertx = Function('return this')().require('vertx');\n vertxNext = vertx.runOnLoop || vertx.runOnContext;\n return useVertxTimer();\n } catch (e) {\n return useSetTimeout();\n }\n}\n\nvar scheduleFlush = void 0;\n// Decide what async method to use to triggering processing of queued callbacks:\nif (isNode) {\n scheduleFlush = useNextTick();\n} else if (BrowserMutationObserver) {\n scheduleFlush = useMutationObserver();\n} else if (isWorker) {\n scheduleFlush = useMessageChannel();\n} else if (browserWindow === undefined && typeof require === 'function') {\n scheduleFlush = attemptVertx();\n} else {\n scheduleFlush = useSetTimeout();\n}\n\nfunction then(onFulfillment, onRejection) {\n var parent = this;\n\n var child = new this.constructor(noop);\n\n if (child[PROMISE_ID] === undefined) {\n makePromise(child);\n }\n\n var _state = parent._state;\n\n\n if (_state) {\n var callback = arguments[_state - 1];\n asap(function () {\n return invokeCallback(_state, child, callback, parent._result);\n });\n } else {\n subscribe(parent, child, onFulfillment, onRejection);\n }\n\n return child;\n}\n\n/**\n `Promise.resolve` returns a promise that will become resolved with the\n passed `value`. It is shorthand for the following:\n\n ```javascript\n let promise = new Promise(function(resolve, reject){\n resolve(1);\n });\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = Promise.resolve(1);\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n @method resolve\n @static\n @param {Any} value value that the returned promise will be resolved with\n Useful for tooling.\n @return {Promise} a promise that will become fulfilled with the given\n `value`\n*/\nfunction resolve$1(object) {\n /*jshint validthis:true */\n var Constructor = this;\n\n if (object && typeof object === 'object' && object.constructor === Constructor) {\n return object;\n }\n\n var promise = new Constructor(noop);\n resolve(promise, object);\n return promise;\n}\n\nvar PROMISE_ID = Math.random().toString(36).substring(2);\n\nfunction noop() {}\n\nvar PENDING = void 0;\nvar FULFILLED = 1;\nvar REJECTED = 2;\n\nfunction selfFulfillment() {\n return new TypeError(\"You cannot resolve a promise with itself\");\n}\n\nfunction cannotReturnOwn() {\n return new TypeError('A promises callback cannot return that same promise.');\n}\n\nfunction tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {\n try {\n then$$1.call(value, fulfillmentHandler, rejectionHandler);\n } catch (e) {\n return e;\n }\n}\n\nfunction handleForeignThenable(promise, thenable, then$$1) {\n asap(function (promise) {\n var sealed = false;\n var error = tryThen(then$$1, thenable, function (value) {\n if (sealed) {\n return;\n }\n sealed = true;\n if (thenable !== value) {\n resolve(promise, value);\n } else {\n fulfill(promise, value);\n }\n }, function (reason) {\n if (sealed) {\n return;\n }\n sealed = true;\n\n reject(promise, reason);\n }, 'Settle: ' + (promise._label || ' unknown promise'));\n\n if (!sealed && error) {\n sealed = true;\n reject(promise, error);\n }\n }, promise);\n}\n\nfunction handleOwnThenable(promise, thenable) {\n if (thenable._state === FULFILLED) {\n fulfill(promise, thenable._result);\n } else if (thenable._state === REJECTED) {\n reject(promise, thenable._result);\n } else {\n subscribe(thenable, undefined, function (value) {\n return resolve(promise, value);\n }, function (reason) {\n return reject(promise, reason);\n });\n }\n}\n\nfunction handleMaybeThenable(promise, maybeThenable, then$$1) {\n if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {\n handleOwnThenable(promise, maybeThenable);\n } else {\n if (then$$1 === undefined) {\n fulfill(promise, maybeThenable);\n } else if (isFunction(then$$1)) {\n handleForeignThenable(promise, maybeThenable, then$$1);\n } else {\n fulfill(promise, maybeThenable);\n }\n }\n}\n\nfunction resolve(promise, value) {\n if (promise === value) {\n reject(promise, selfFulfillment());\n } else if (objectOrFunction(value)) {\n var then$$1 = void 0;\n try {\n then$$1 = value.then;\n } catch (error) {\n reject(promise, error);\n return;\n }\n handleMaybeThenable(promise, value, then$$1);\n } else {\n fulfill(promise, value);\n }\n}\n\nfunction publishRejection(promise) {\n if (promise._onerror) {\n promise._onerror(promise._result);\n }\n\n publish(promise);\n}\n\nfunction fulfill(promise, value) {\n if (promise._state !== PENDING) {\n return;\n }\n\n promise._result = value;\n promise._state = FULFILLED;\n\n if (promise._subscribers.length !== 0) {\n asap(publish, promise);\n }\n}\n\nfunction reject(promise, reason) {\n if (promise._state !== PENDING) {\n return;\n }\n promise._state = REJECTED;\n promise._result = reason;\n\n asap(publishRejection, promise);\n}\n\nfunction subscribe(parent, child, onFulfillment, onRejection) {\n var _subscribers = parent._subscribers;\n var length = _subscribers.length;\n\n\n parent._onerror = null;\n\n _subscribers[length] = child;\n _subscribers[length + FULFILLED] = onFulfillment;\n _subscribers[length + REJECTED] = onRejection;\n\n if (length === 0 && parent._state) {\n asap(publish, parent);\n }\n}\n\nfunction publish(promise) {\n var subscribers = promise._subscribers;\n var settled = promise._state;\n\n if (subscribers.length === 0) {\n return;\n }\n\n var child = void 0,\n callback = void 0,\n detail = promise._result;\n\n for (var i = 0; i < subscribers.length; i += 3) {\n child = subscribers[i];\n callback = subscribers[i + settled];\n\n if (child) {\n invokeCallback(settled, child, callback, detail);\n } else {\n callback(detail);\n }\n }\n\n promise._subscribers.length = 0;\n}\n\nfunction invokeCallback(settled, promise, callback, detail) {\n var hasCallback = isFunction(callback),\n value = void 0,\n error = void 0,\n succeeded = true;\n\n if (hasCallback) {\n try {\n value = callback(detail);\n } catch (e) {\n succeeded = false;\n error = e;\n }\n\n if (promise === value) {\n reject(promise, cannotReturnOwn());\n return;\n }\n } else {\n value = detail;\n }\n\n if (promise._state !== PENDING) {\n // noop\n } else if (hasCallback && succeeded) {\n resolve(promise, value);\n } else if (succeeded === false) {\n reject(promise, error);\n } else if (settled === FULFILLED) {\n fulfill(promise, value);\n } else if (settled === REJECTED) {\n reject(promise, value);\n }\n}\n\nfunction initializePromise(promise, resolver) {\n try {\n resolver(function resolvePromise(value) {\n resolve(promise, value);\n }, function rejectPromise(reason) {\n reject(promise, reason);\n });\n } catch (e) {\n reject(promise, e);\n }\n}\n\nvar id = 0;\nfunction nextId() {\n return id++;\n}\n\nfunction makePromise(promise) {\n promise[PROMISE_ID] = id++;\n promise._state = undefined;\n promise._result = undefined;\n promise._subscribers = [];\n}\n\nfunction validationError() {\n return new Error('Array Methods must be provided an Array');\n}\n\nvar Enumerator = function () {\n function Enumerator(Constructor, input) {\n this._instanceConstructor = Constructor;\n this.promise = new Constructor(noop);\n\n if (!this.promise[PROMISE_ID]) {\n makePromise(this.promise);\n }\n\n if (isArray(input)) {\n this.length = input.length;\n this._remaining = input.length;\n\n this._result = new Array(this.length);\n\n if (this.length === 0) {\n fulfill(this.promise, this._result);\n } else {\n this.length = this.length || 0;\n this._enumerate(input);\n if (this._remaining === 0) {\n fulfill(this.promise, this._result);\n }\n }\n } else {\n reject(this.promise, validationError());\n }\n }\n\n Enumerator.prototype._enumerate = function _enumerate(input) {\n for (var i = 0; this._state === PENDING && i < input.length; i++) {\n this._eachEntry(input[i], i);\n }\n };\n\n Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {\n var c = this._instanceConstructor;\n var resolve$$1 = c.resolve;\n\n\n if (resolve$$1 === resolve$1) {\n var _then = void 0;\n var error = void 0;\n var didError = false;\n try {\n _then = entry.then;\n } catch (e) {\n didError = true;\n error = e;\n }\n\n if (_then === then && entry._state !== PENDING) {\n this._settledAt(entry._state, i, entry._result);\n } else if (typeof _then !== 'function') {\n this._remaining--;\n this._result[i] = entry;\n } else if (c === Promise$1) {\n var promise = new c(noop);\n if (didError) {\n reject(promise, error);\n } else {\n handleMaybeThenable(promise, entry, _then);\n }\n this._willSettleAt(promise, i);\n } else {\n this._willSettleAt(new c(function (resolve$$1) {\n return resolve$$1(entry);\n }), i);\n }\n } else {\n this._willSettleAt(resolve$$1(entry), i);\n }\n };\n\n Enumerator.prototype._settledAt = function _settledAt(state, i, value) {\n var promise = this.promise;\n\n\n if (promise._state === PENDING) {\n this._remaining--;\n\n if (state === REJECTED) {\n reject(promise, value);\n } else {\n this._result[i] = value;\n }\n }\n\n if (this._remaining === 0) {\n fulfill(promise, this._result);\n }\n };\n\n Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {\n var enumerator = this;\n\n subscribe(promise, undefined, function (value) {\n return enumerator._settledAt(FULFILLED, i, value);\n }, function (reason) {\n return enumerator._settledAt(REJECTED, i, reason);\n });\n };\n\n return Enumerator;\n}();\n\n/**\n `Promise.all` accepts an array of promises, and returns a new promise which\n is fulfilled with an array of fulfillment values for the passed promises, or\n rejected with the reason of the first passed promise to be rejected. It casts all\n elements of the passed iterable to promises as it runs this algorithm.\n\n Example:\n\n ```javascript\n let promise1 = resolve(1);\n let promise2 = resolve(2);\n let promise3 = resolve(3);\n let promises = [ promise1, promise2, promise3 ];\n\n Promise.all(promises).then(function(array){\n // The array here would be [ 1, 2, 3 ];\n });\n ```\n\n If any of the `promises` given to `all` are rejected, the first promise\n that is rejected will be given as an argument to the returned promises's\n rejection handler. For example:\n\n Example:\n\n ```javascript\n let promise1 = resolve(1);\n let promise2 = reject(new Error(\"2\"));\n let promise3 = reject(new Error(\"3\"));\n let promises = [ promise1, promise2, promise3 ];\n\n Promise.all(promises).then(function(array){\n // Code here never runs because there are rejected promises!\n }, function(error) {\n // error.message === \"2\"\n });\n ```\n\n @method all\n @static\n @param {Array} entries array of promises\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled when all `promises` have been\n fulfilled, or rejected if any of them become rejected.\n @static\n*/\nfunction all(entries) {\n return new Enumerator(this, entries).promise;\n}\n\n/**\n `Promise.race` returns a new promise which is settled in the same way as the\n first passed promise to settle.\n\n Example:\n\n ```javascript\n let promise1 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 2');\n }, 100);\n });\n\n Promise.race([promise1, promise2]).then(function(result){\n // result === 'promise 2' because it was resolved before promise1\n // was resolved.\n });\n ```\n\n `Promise.race` is deterministic in that only the state of the first\n settled promise matters. For example, even if other promises given to the\n `promises` array argument are resolved, but the first settled promise has\n become rejected before the other promises became fulfilled, the returned\n promise will become rejected:\n\n ```javascript\n let promise1 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new Promise(function(resolve, reject){\n setTimeout(function(){\n reject(new Error('promise 2'));\n }, 100);\n });\n\n Promise.race([promise1, promise2]).then(function(result){\n // Code here never runs\n }, function(reason){\n // reason.message === 'promise 2' because promise 2 became rejected before\n // promise 1 became fulfilled\n });\n ```\n\n An example real-world use case is implementing timeouts:\n\n ```javascript\n Promise.race([ajax('foo.json'), timeout(5000)])\n ```\n\n @method race\n @static\n @param {Array} promises array of promises to observe\n Useful for tooling.\n @return {Promise} a promise which settles in the same way as the first passed\n promise to settle.\n*/\nfunction race(entries) {\n /*jshint validthis:true */\n var Constructor = this;\n\n if (!isArray(entries)) {\n return new Constructor(function (_, reject) {\n return reject(new TypeError('You must pass an array to race.'));\n });\n } else {\n return new Constructor(function (resolve, reject) {\n var length = entries.length;\n for (var i = 0; i < length; i++) {\n Constructor.resolve(entries[i]).then(resolve, reject);\n }\n });\n }\n}\n\n/**\n `Promise.reject` returns a promise rejected with the passed `reason`.\n It is shorthand for the following:\n\n ```javascript\n let promise = new Promise(function(resolve, reject){\n reject(new Error('WHOOPS'));\n });\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = Promise.reject(new Error('WHOOPS'));\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n @method reject\n @static\n @param {Any} reason value that the returned promise will be rejected with.\n Useful for tooling.\n @return {Promise} a promise rejected with the given `reason`.\n*/\nfunction reject$1(reason) {\n /*jshint validthis:true */\n var Constructor = this;\n var promise = new Constructor(noop);\n reject(promise, reason);\n return promise;\n}\n\nfunction needsResolver() {\n throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');\n}\n\nfunction needsNew() {\n throw new TypeError(\"Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.\");\n}\n\n/**\n Promise objects represent the eventual result of an asynchronous operation. The\n primary way of interacting with a promise is through its `then` method, which\n registers callbacks to receive either a promise's eventual value or the reason\n why the promise cannot be fulfilled.\n\n Terminology\n -----------\n\n - `promise` is an object or function with a `then` method whose behavior conforms to this specification.\n - `thenable` is an object or function that defines a `then` method.\n - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).\n - `exception` is a value that is thrown using the throw statement.\n - `reason` is a value that indicates why a promise was rejected.\n - `settled` the final resting state of a promise, fulfilled or rejected.\n\n A promise can be in one of three states: pending, fulfilled, or rejected.\n\n Promises that are fulfilled have a fulfillment value and are in the fulfilled\n state. Promises that are rejected have a rejection reason and are in the\n rejected state. A fulfillment value is never a thenable.\n\n Promises can also be said to *resolve* a value. If this value is also a\n promise, then the original promise's settled state will match the value's\n settled state. So a promise that *resolves* a promise that rejects will\n itself reject, and a promise that *resolves* a promise that fulfills will\n itself fulfill.\n\n\n Basic Usage:\n ------------\n\n ```js\n let promise = new Promise(function(resolve, reject) {\n // on success\n resolve(value);\n\n // on failure\n reject(reason);\n });\n\n promise.then(function(value) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Advanced Usage:\n ---------------\n\n Promises shine when abstracting away asynchronous interactions such as\n `XMLHttpRequest`s.\n\n ```js\n function getJSON(url) {\n return new Promise(function(resolve, reject){\n let xhr = new XMLHttpRequest();\n\n xhr.open('GET', url);\n xhr.onreadystatechange = handler;\n xhr.responseType = 'json';\n xhr.setRequestHeader('Accept', 'application/json');\n xhr.send();\n\n function handler() {\n if (this.readyState === this.DONE) {\n if (this.status === 200) {\n resolve(this.response);\n } else {\n reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));\n }\n }\n };\n });\n }\n\n getJSON('/posts.json').then(function(json) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Unlike callbacks, promises are great composable primitives.\n\n ```js\n Promise.all([\n getJSON('/posts'),\n getJSON('/comments')\n ]).then(function(values){\n values[0] // => postsJSON\n values[1] // => commentsJSON\n\n return values;\n });\n ```\n\n @class Promise\n @param {Function} resolver\n Useful for tooling.\n @constructor\n*/\n\nvar Promise$1 = function () {\n function Promise(resolver) {\n this[PROMISE_ID] = nextId();\n this._result = this._state = undefined;\n this._subscribers = [];\n\n if (noop !== resolver) {\n typeof resolver !== 'function' && needsResolver();\n this instanceof Promise ? initializePromise(this, resolver) : needsNew();\n }\n }\n\n /**\n The primary way of interacting with a promise is through its `then` method,\n which registers callbacks to receive either a promise's eventual value or the\n reason why the promise cannot be fulfilled.\n ```js\n findUser().then(function(user){\n // user is available\n }, function(reason){\n // user is unavailable, and you are given the reason why\n });\n ```\n Chaining\n --------\n The return value of `then` is itself a promise. This second, 'downstream'\n promise is resolved with the return value of the first promise's fulfillment\n or rejection handler, or rejected if the handler throws an exception.\n ```js\n findUser().then(function (user) {\n return user.name;\n }, function (reason) {\n return 'default name';\n }).then(function (userName) {\n // If `findUser` fulfilled, `userName` will be the user's name, otherwise it\n // will be `'default name'`\n });\n findUser().then(function (user) {\n throw new Error('Found user, but still unhappy');\n }, function (reason) {\n throw new Error('`findUser` rejected and we're unhappy');\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.\n // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.\n });\n ```\n If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.\n ```js\n findUser().then(function (user) {\n throw new PedagogicalException('Upstream error');\n }).then(function (value) {\n // never reached\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // The `PedgagocialException` is propagated all the way down to here\n });\n ```\n Assimilation\n ------------\n Sometimes the value you want to propagate to a downstream promise can only be\n retrieved asynchronously. This can be achieved by returning a promise in the\n fulfillment or rejection handler. The downstream promise will then be pending\n until the returned promise is settled. This is called *assimilation*.\n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // The user's comments are now available\n });\n ```\n If the assimliated promise rejects, then the downstream promise will also reject.\n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // If `findCommentsByAuthor` fulfills, we'll have the value here\n }, function (reason) {\n // If `findCommentsByAuthor` rejects, we'll have the reason here\n });\n ```\n Simple Example\n --------------\n Synchronous Example\n ```javascript\n let result;\n try {\n result = findResult();\n // success\n } catch(reason) {\n // failure\n }\n ```\n Errback Example\n ```js\n findResult(function(result, err){\n if (err) {\n // failure\n } else {\n // success\n }\n });\n ```\n Promise Example;\n ```javascript\n findResult().then(function(result){\n // success\n }, function(reason){\n // failure\n });\n ```\n Advanced Example\n --------------\n Synchronous Example\n ```javascript\n let author, books;\n try {\n author = findAuthor();\n books = findBooksByAuthor(author);\n // success\n } catch(reason) {\n // failure\n }\n ```\n Errback Example\n ```js\n function foundBooks(books) {\n }\n function failure(reason) {\n }\n findAuthor(function(author, err){\n if (err) {\n failure(err);\n // failure\n } else {\n try {\n findBoooksByAuthor(author, function(books, err) {\n if (err) {\n failure(err);\n } else {\n try {\n foundBooks(books);\n } catch(reason) {\n failure(reason);\n }\n }\n });\n } catch(error) {\n failure(err);\n }\n // success\n }\n });\n ```\n Promise Example;\n ```javascript\n findAuthor().\n then(findBooksByAuthor).\n then(function(books){\n // found books\n }).catch(function(reason){\n // something went wrong\n });\n ```\n @method then\n @param {Function} onFulfilled\n @param {Function} onRejected\n Useful for tooling.\n @return {Promise}\n */\n\n /**\n `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same\n as the catch block of a try/catch statement.\n ```js\n function findAuthor(){\n throw new Error('couldn't find that author');\n }\n // synchronous\n try {\n findAuthor();\n } catch(reason) {\n // something went wrong\n }\n // async with promises\n findAuthor().catch(function(reason){\n // something went wrong\n });\n ```\n @method catch\n @param {Function} onRejection\n Useful for tooling.\n @return {Promise}\n */\n\n\n Promise.prototype.catch = function _catch(onRejection) {\n return this.then(null, onRejection);\n };\n\n /**\n `finally` will be invoked regardless of the promise's fate just as native\n try/catch/finally behaves\n \n Synchronous example:\n \n ```js\n findAuthor() {\n if (Math.random() > 0.5) {\n throw new Error();\n }\n return new Author();\n }\n \n try {\n return findAuthor(); // succeed or fail\n } catch(error) {\n return findOtherAuther();\n } finally {\n // always runs\n // doesn't affect the return value\n }\n ```\n \n Asynchronous example:\n \n ```js\n findAuthor().catch(function(reason){\n return findOtherAuther();\n }).finally(function(){\n // author was either found, or not\n });\n ```\n \n @method finally\n @param {Function} callback\n @return {Promise}\n */\n\n\n Promise.prototype.finally = function _finally(callback) {\n var promise = this;\n var constructor = promise.constructor;\n\n if (isFunction(callback)) {\n return promise.then(function (value) {\n return constructor.resolve(callback()).then(function () {\n return value;\n });\n }, function (reason) {\n return constructor.resolve(callback()).then(function () {\n throw reason;\n });\n });\n }\n\n return promise.then(callback, callback);\n };\n\n return Promise;\n}();\n\nPromise$1.prototype.then = then;\nPromise$1.all = all;\nPromise$1.race = race;\nPromise$1.resolve = resolve$1;\nPromise$1.reject = reject$1;\nPromise$1._setScheduler = setScheduler;\nPromise$1._setAsap = setAsap;\nPromise$1._asap = asap;\n\n/*global self*/\nfunction polyfill() {\n var local = void 0;\n\n if (typeof global !== 'undefined') {\n local = global;\n } else if (typeof self !== 'undefined') {\n local = self;\n } else {\n try {\n local = Function('return this')();\n } catch (e) {\n throw new Error('polyfill failed because global object is unavailable in this environment');\n }\n }\n\n var P = local.Promise;\n\n if (P) {\n var promiseToString = null;\n try {\n promiseToString = Object.prototype.toString.call(P.resolve());\n } catch (e) {\n // silently ignored\n }\n\n if (promiseToString === '[object Promise]' && !P.cast) {\n return;\n }\n }\n\n local.Promise = Promise$1;\n}\n\n// Strange compat..\nPromise$1.polyfill = polyfill;\nPromise$1.Promise = Promise$1;\n\nreturn Promise$1;\n\n})));\n\n\n\n//# sourceMappingURL=es6-promise.map\n","import MediaPlayer from './MediaPlayer';\n\nfunction MediaPlayerFactory() {\n /**\n * mime-type identifier for any source content to be accepted as a dash manifest by the create() method.\n * @type {string}\n */\n const SUPPORTED_MIME_TYPE = 'application/dash+xml';\n\n let logger;\n\n /**\n * A new MediaPlayer is instantiated for the supplied videoElement and optional source and context. If no context is provided,\n * a default DashContext is used. If no source is provided, the videoElement is interrogated to extract the first source whose\n * type is application/dash+xml.\n * The autoplay property of the videoElement is preserved. Any preload attribute is ignored. This method should be called after the page onLoad event is dispatched.\n * @param {HTMLMediaElement} video\n * @param {HTMLSourceElement} source\n * @param {Object} context\n * @returns {MediaPlayer|null}\n */\n function create(video, source, context) {\n if (!video || !(/^VIDEO$/i).test(video.nodeName)) return null;\n\n if (video._dashjs_player) return video._dashjs_player;\n\n let player;\n let videoID = (video.id || video.name || 'video element');\n\n source = source || [].slice.call(video.querySelectorAll('source')).filter(function (s) {\n return s.type == SUPPORTED_MIME_TYPE;\n })[0];\n if (!source && video.src) {\n source = document.createElement('source');\n source.src = video.src;\n } else if (!source && !video.src) {\n return null;\n }\n\n context = context || {};\n player = MediaPlayer(context).create();\n player.initialize(video, source.src, video.autoplay);\n\n if (!logger) {\n logger = player.getDebug().getLogger();\n }\n logger.debug('Converted ' + videoID + ' to dash.js player and added content: ' + source.src);\n\n // Store a reference to the player on the video element so it can be gotten at for debugging and so we know its\n // already been setup.\n video._dashjs_player = player;\n\n return player;\n }\n\n /**\n * Searches the provided scope for all instances of the indicated selector. If no scope is provided, document is used. If no selector is\n * specified, [data-dashjs-player] is used. The declarative setup also looks for source elements with the type attribute set to 'application/dash+xml'.\n * It then looks for those video elements which have a source element defined with a type matching 'application/dash+xml'.\n * A new MediaPlayer is instantiated for each matching video element and the appropriate source is assigned.\n * The autoplay property of the video element is preserved. Any preload attribute is ignored. This method should be called after the page onLoad event is dispatched.\n * Returns an array holding all the MediaPlayer instances that were added by this method.\n * @param {string} selector - CSS selector\n * @param {Object} scope\n * @returns {Array} an array of MediaPlayer objects\n */\n function createAll(selector, scope) {\n let aPlayers = [];\n selector = selector || '[data-dashjs-player]';\n scope = scope || document;\n let videos = scope.querySelectorAll(selector);\n for (let i = 0; i < videos.length; i++) {\n let player = create(videos[i], null);\n aPlayers.push(player);\n }\n\n let sources = scope.querySelectorAll('source[type=\"' + SUPPORTED_MIME_TYPE + '\"]');\n for (let i = 0; i < sources.length; i++) {\n let video = findVideo(sources[i]);\n let player = create(video, null);\n aPlayers.push(player);\n }\n\n return aPlayers;\n }\n\n function findVideo(el) {\n if ((/^VIDEO$/i).test(el.nodeName)) {\n return el;\n } else {\n return findVideo(el.parentNode);\n }\n }\n\n return {\n create: create,\n createAll: createAll\n };\n}\n\nlet instance = MediaPlayerFactory();\nlet loadInterval;\n\nfunction loadHandler() {\n window.removeEventListener('load', loadHandler);\n instance.createAll();\n}\n\nfunction loadIntervalHandler() {\n if (window.dashjs) {\n window.clearInterval(loadInterval);\n instance.createAll();\n }\n}\n\nlet avoidAutoCreate = typeof window !== 'undefined' && window && window.dashjs && window.dashjs.skipAutoCreate;\n\nif (!avoidAutoCreate && typeof window !== 'undefined' && window && window.addEventListener) {\n if (window.document.readyState === 'complete') {\n if (window.dashjs) {\n instance.createAll();\n } else {\n // If loaded asynchronously, window.readyState may be 'complete' even if dashjs hasn't loaded yet\n loadInterval = window.setInterval(loadIntervalHandler, 500);\n }\n } else {\n window.addEventListener('load', loadHandler);\n }\n}\n\nexport default instance;\n","/**\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2013, Dash Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * * Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport { MediaPlayer } from './index_mediaplayerOnly';\n\nimport { supportsMediaSource } from './src/streaming/utils/Capabilities';\nimport MetricsReporting from './src/streaming/metrics/MetricsReporting';\nimport Protection from './src/streaming/protection/Protection';\nimport MediaPlayerFactory from './src/streaming/MediaPlayerFactory';\nimport Debug from './src/core/Debug';\n\ndashjs.Protection = Protection;\ndashjs.MetricsReporting = MetricsReporting;\ndashjs.MediaPlayerFactory = MediaPlayerFactory;\ndashjs.Debug = Debug;\ndashjs.supportsMediaSource = supportsMediaSource;\n\nexport default dashjs;\nexport { MediaPlayer, Protection, MetricsReporting, MediaPlayerFactory, Debug, supportsMediaSource };\n"],"sourceRoot":""} |