dash.all.min.js.map 3.4 MB

1
  1. {"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/rules/SwitchRequest.js","webpack://dashjs/./src/streaming/constants/MetricsConstants.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/core/Utils.js","webpack://dashjs/./src/streaming/utils/SupervisorTools.js","webpack://dashjs/./src/core/Settings.js","webpack://dashjs/./src/streaming/vo/FragmentRequest.js","webpack://dashjs/./src/core/events/EventsBase.js","webpack://dashjs/./src/streaming/metrics/MetricsReportingEvents.js","webpack://dashjs/./src/streaming/utils/RequestModifier.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/./node_modules/process/browser.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/core/errors/ErrorsBase.js","webpack://dashjs/./src/streaming/net/XHRLoader.js","webpack://dashjs/./node_modules/bcp-47-normalize/index.js","webpack://dashjs/./src/dash/vo/UTCTiming.js","webpack://dashjs/./src/streaming/models/CustomParametersModel.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/vo/ProducerReferenceTime.js","webpack://dashjs/./src/dash/vo/ContentSteering.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/./node_modules/path-browserify/index.js","webpack://dashjs/./node_modules/ua-parser-js/src/ua-parser.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/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/bcp-47-match/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/(webpack)/buildin/amd-options.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/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/CatchupController.js","webpack://dashjs/./src/dash/controllers/ServiceDescriptionController.js","webpack://dashjs/./src/dash/vo/ContentSteeringRequest.js","webpack://dashjs/./src/dash/vo/ContentSteeringResponse.js","webpack://dashjs/./src/dash/controllers/ContentSteeringController.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/baseUrlResolution/ContentSteeringSelector.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/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/./node_modules/is-alphabetical/index.js","webpack://dashjs/./node_modules/is-decimal/index.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/matchers/LangMatcher.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/bcp-47-normalize/lib/index.js","webpack://dashjs/./node_modules/bcp-47/index.js","webpack://dashjs/./node_modules/bcp-47/lib/parse.js","webpack://dashjs/./node_modules/is-alphanumerical/index.js","webpack://dashjs/./node_modules/bcp-47/lib/stringify.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","PRODUCER_REFERENCE_TIME","ACCESSIBILITY","ROLE","RATING","CONTENT_COMPONENT","SUBSET","LANG","VIEWPOINT","ROLE_ASARRAY","REPRESENTATION_ASARRAY","PRODUCERREFERENCETIME_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","SERVICE_DESCRIPTION_OPERATING_QUALITY","SERVICE_DESCRIPTION_OPERATING_BANDWIDTH","PATCH_LOCATION","PUBLISH_TIME","ORIGINAL_PUBLISH_TIME","ORIGINAL_MPD_ID","WALL_CLOCK_TIME","LABEL","GROUP_LABEL","CONTENT_STEERING","CONTENT_STEERING_AS_ARRAY","DEFAULT_SERVICE_LOCATION","QUERY_BEFORE_START","PROXY_SERVER_URL","CONTENT_STEERING_RESPONSE","VERSION","TTL","RELOAD_URI","SERVICE_LOCATION_PRIORITY","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_DVB_LL_SCHEME","SUPPLEMENTAL_PROPERTY_DVB_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","FILE_LOADER_TYPES","FETCH","XHR","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","SETTING_UPDATED_LIVE_DELAY","SETTING_UPDATED_LIVE_DELAY_FRAGMENT_COUNT","SETTING_UPDATED_CATCHUP_ENABLED","SETTING_UPDATED_PLAYBACK_RATE_MIN","SETTING_UPDATED_PLAYBACK_RATE_MAX","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_STALLED","PLAYBACK_STARTED","PLAYBACK_TIME_UPDATED","PLAYBACK_VOLUME_CHANGED","PLAYBACK_WAITING","MANIFEST_VALIDITY_CHANGED","EVENT_MODE_ON_START","EVENT_MODE_ON_RECEIVE","CONFORMANCE_VIOLATION","REPRESENTATION_SWITCH","ADAPTATION_SET_REMOVED_NO_CAPABILITIES","CONTENT_STEERING_REQUEST_COMPLETED","HTTPRequest","tcpid","type","url","actualurl","range","trequest","tresponse","responsecode","interval","trace","_stream","_tfinish","_mediaduration","_quality","_responseHeaders","_serviceLocation","_fileLoaderType","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","DVB_REPORTING_TYPE","LICENSE","CONTENT_STEERING_TYPE","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","PRIORITY","DEFAULT","STRONG","WEAK","SwitchRequest","q","quality","reason","ret","getPriority","NO_CHANGE","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","HTTP_REQUEST_DVB_REPORTING_TYPE","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","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","ua","uaString","navigator","userAgent","toLowerCase","UAParser","checkParameterType","parameter","Constants","checkInteger","Settings","DISPATCH_KEY_MAP","defaultSettings","streaming","abandonLoadTimeout","wallclockTimeUpdateInterval","manifestUpdateRetryInterval","cacheInitSegments","applyServiceDescription","applyProducerReferenceTime","applyContentSteering","eventControllerRefreshDelay","enableManifestDurationMismatchFix","capabilities","filterUnsupportedEssentialProperties","useMediaCapabilitiesApi","timeShiftBuffer","calcFromSegmentTimeline","fallbackToSegmentTimeline","metrics","maxListDepth","delay","liveDelayFragmentCount","NaN","liveDelay","useSuggestedPresentationDelay","protection","keepProtectionMediaKeys","ignoreEmeEncryptedEvent","detectPlayreadyMessageFormat","buffer","enableSeekDecorrelationFix","fastSwitchEnabled","flushBufferAtTrackSwitch","reuseExistingSourceBuffers","bufferPruningInterval","bufferToKeep","bufferTimeAtTopQuality","bufferTimeAtTopQualityLongForm","initialBufferLevel","stableBufferTime","longFormContentDurationThreshold","stallThreshold","useAppendWindow","setStallState","avoidCurrentTimeRangePruning","useChangeTypeForTrackSwitch","gaps","jumpGaps","jumpLargeGaps","smallGapLimit","threshold","enableSeekFix","enableStallFix","stallSeek","utcSynchronization","enabled","useManifestDateHeaderTimeSource","backgroundAttempts","timeBetweenSyncAttempts","maximumTimeBetweenSyncAttempts","minimumTimeBetweenSyncAttempts","timeBetweenSyncAttemptsAdjustmentFactor","maximumAllowedDrift","enableBackgroundSyncAfterSegmentDownloadError","defaultTimingSource","scheme","scheduling","defaultTimeout","lowLatencyTimeout","scheduleWhilePaused","text","defaultEnabled","liveCatchup","maxDrift","playbackRate","min","max","playbackBufferMin","lastBitrateCachingInfo","ttl","lastMediaSettingsCachingInfo","cacheLoadThresholds","video","audio","trackSwitchMode","selectionModeForInitialTrack","fragmentRequestTimeout","manifestRequestTimeout","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","enabledKeys","recoverAttempts","mediaErrorDecode","update","settingsObj","mixinSettings","slice","FragmentRequest","action","ACTION_DOWNLOAD","mediaInfo","timescale","serviceLocation","requestStartDate","firstByteDate","requestEndDate","bytesLoaded","bytesTotal","delayLoadingTime","responseType","representationId","end","ACTION_COMPLETE","publicOnly","evt","metricsReportingEvents","METRICS_INITIALISATION_COMPLETE","BECAME_REPORTING_PLAYER","CMCD_DATA_GENERATED","modifyRequest","httpRequest","requestModifier","request","method","assign","credentials","withCredentials","Promise","then","RequestModifier","modifyRequestURL","modifyRequestHeader","FragmentModel","logger","executedRequests","loadingRequests","dashMetrics","fragmentLoader","streamInfo","isFragmentLoaded","isLoaded","req","req1","req2","adaptationIndex","isEqualInit","isEqualComplete","getRequestThreshold","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","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","cachedSetTimeout","cachedClearTimeout","process","defaultSetTimout","defaultClearTimeout","runTimeout","fun","setTimeout","clearTimeout","currentQueue","queue","draining","queueIndex","cleanUpNextTick","drainQueue","timeout","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","ThroughputRule","getMaxIndex","rulesContext","switchRequest","checkConfig","getMediaInfo","getMediaType","currentBufferState","getCurrentBufferState","scheduleController","getScheduleController","abrController","getAbrController","getStreamInfo","manifestInfo","throughputHistory","getThroughputHistory","throughput","getSafeAverageThroughput","latency","getAverageLatency","useBufferOccupancyABR","getAbandonmentStateFor","MetricsConstants","getQualityForBitrate","setTimeToLoadDelay","InsufficientBufferRule","bufferStateDict","ignoreCount","_onPlaybackSeeking","_onBytesAppended","fragmentDuration","getRepresentationInfo","lowLatencyEnabled","shouldIgnore","getPlaybackController","getLowLatencyModeEnabled","bufferLevel","getCurrentBufferLevel","getAverageThroughput","bitrate","AbandonRequestsRule","fragmentDict","abandonDict","throughputArray","shouldAbandon","getCurrentRequest","getStableBufferTime","fragmentInfo","firstByteTime","elapsedTime","storeLastRequestThroughputByType","round","totalSampledValue","reduce","measuredBandwidthInKbps","estimatedTimeOfDownload","bytesRemaining","bitrateList","getBitrateList","minQuality","getMinAllowedIndexFor","newQuality","getQualityFor","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","map","bandwidth","utilitiesFromBitrates","lastQuality","clearBolaStateOnSeek","bolaState","placeholderBuffer","mostAdvancedSegmentStart","lastSegmentWasReplacement","lastSegmentStart","lastSegmentDurationS","lastSegmentRequestTimeMs","lastSegmentFinishTimeMs","checkBolaStateStableBufferTime","effectiveBufferLevel","maxBufferLevelForQuality","minBufferLevelForQuality","qBitrate","qUtility","iBitrate","iUtility","onBufferEmpty","stateDict","onPlaybackSeeking","onMediaFragmentLoaded","chunk","checkNewSegment","onMetricAdded","metric","bufferAtLastSegmentRequest","maxEffectiveBufferForLastSegment","maxPlaceholderBuffer","onQualityChangeRequested","abrQuality","onFragmentLoadingAbandoned","wantEffectiveBufferLevel","getBolaState","safeThroughput","nowMs","now","lastCallTimeMs","updatePlaceholderBuffer","bitrateCount","score","getQualityFromBufferLevel","qualityForThroughput","delayS","getMaxAllowedIndexFor","L2ARule","l2AStateDict","l2AParameterDict","_getInitialL2AState","w","prev_w","Q","segment_request_start_s","segment_download_finish_s","B_target","_initializeL2AParameters","_clearL2AStateOnSeek","l2AState","l2aState","_onMediaFragmentLoaded","l2AParameters","_checkNewSegment","_onMetricAdded","L2AState","_onQualityChangeRequested","_dotmultiplication","arr1","arr2","sumdot","_resetInitialSettings","vl","alpha","sqrt","useL2AABR","currentPlaybackRate","getVideoModel","getPlaybackRate","_getL2AState","l2AParameter","diff1","throughputMeasureTime","getCurrentHttpRequest","downloadBytes","lastthroughput","V","sign","bget","ii","sort","tmpsum","tmax","euclideanProjection","temp","abs","WEIGHT_SELECTION_MODES","LearningAbrController","somBitrateNeurons","bitrateNormalizationFactor","latencyNormalizationFactor","weights","sortedCenters","weightSelectionMode","_getMaxThroughput","maxThroughput","neuron","_getDistance","sum","_getNeuronDistance","rebuffer","_updateNeurons","winnerNeuron","somElements","somNeuron","neuronDistance","_updateNeuronState","exp","neighbourHood","_dynamicWeightSelection","dynamicWeightsSelector","currentLatency","currentBuffer","currentThroughput","weightVector","findWeightVector","getNextQuality","bufferSize","currentQualityIndex","bitrateVector","element","magnitude","qualityIndex","switch","centers","randomDataSet","dataArray","_getRandomData","distanceWeights","nextPoint","maxDistance","currentPoint","minDistance","distance","leastSimilarIndex","minIndex","_getInitialKmeansPlusPlusCenters","_getSomBitrateNeurons","throughputNormalized","currentNeuron","downloadTime","getSegmentDuration","getMinBuffer","maxSuitableBitrate","_getDownShiftNeuron","neuronCount","weightCount","W","upperBound","_getXavierWeights","_randomWeightSelection","somNeuronState","somData","nextBuffer","getNextBufferWithBitrate","isBufferLow","bitrateSwitch","QoeInfo","lastBitrate","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","list","targetLatency","bufferMin","qoeEvaluator","getNextBuffer","bitrateToDownload","neurons","currentRebuffer","maxQoE","winnerWeights","winnerBitrate","deltaLatency","weightsObj","weightedRebuffer","weightedLatency","totalQoE","nextLatency","_checkConstraints","generate","perm","currLen","currPerm","shift","val","LoLPRule","learningController","currentQuality","bufferStateVO","currentBufferLevel","playbackController","getCurrentLiveLatency","useLoLPABR","currentBitrateKbps","lastFragmentDownloadTime","ABRRulesCollection","qualitySwitchRules","abandonFragmentRules","customParametersModel","_getRulesWithChange","srArray","sr","getMinSwitchRequest","values","newSwitchReq","initialize","getAbrCustomRules","rule","rules","getMaxQuality","shouldAbandonFragment","getQualitySwitchRules","QUALITY_SWITCH_RULES","ABANDON_FRAGMENT_RULES","err","XHRLoader","requestStartTime","xhr","XMLHttpRequest","open","setRequestHeader","header","onload","onloadend","onend","onerror","onprogress","progress","onabort","ontimeout","send","UTCTiming","schemeIdUri","CustomParametersModel","utcTimingSources","xhrWithCredentials","licenseRequestFilters","licenseResponseFilters","customCapabilitiesFilters","customInitialTrackSelectionFunction","customAbrRules","_unregisterFilter","_findAbrCustomRuleIndex","rulename","addUTCTimingSource","removeUTCTimingSource","vo","getCustomInitialTrackSelectionFunction","setCustomInitialTrackSelectionFunction","customFunc","resetCustomInitialTrackSelectionFunction","getLicenseResponseFilters","getLicenseRequestFilters","getCustomCapabilitiesFilters","registerCustomCapabilitiesFilter","registerLicenseResponseFilter","registerLicenseRequestFilter","unregisterCustomCapabilitiesFilter","unregisterLicenseResponseFilter","unregisterLicenseRequestFilter","addAbrCustomRule","removeAllAbrCustomRule","removeAbrCustomRule","getUTCTimingSources","clearDefaultUTCTimingSources","restoreDefaultUTCTimingSources","defaultUtcTimingSource","setXHRWithCredentialsForType","keys","getXHRWithCredentialsForType","useCreds","setConfig","default","indexRange","Representation","segmentInfoType","initialization","codecs","mimeType","codecPrivateData","presentationTimeOffset","MSETimeOffset","mediaFinishedInformation","numberOfSegments","mediaTimeOfLastSignaledSegment","height","scanType","maxPlayoutRate","availabilityTimeComplete","DashConstants","AdaptationSet","Period","mpd","nextPeriodId","DEFAULT_ID","Mpd","manifest","suggestedPresentationDelay","Number","POSITIVE_INFINITY","timeShiftBufferDepth","maxSegmentDuration","publishTime","minimumUpdatePeriod","mediaPresentationDuration","EventStream","adaptionSet","ProducerReferenceTime","inband","applicationScheme","wallClockTime","presentationTime","ContentSteering","defaultServiceLocation","queryBeforeStart","proxyServerUrl","serverUrl","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","getRealAdaptations","periodIndex","Period_asArray","AdaptationSet_asArray","getRealPeriods","getIsDynamic","realRepresentation","EssentialProperty_asArray","calcSegmentDuration","segmentTimeline","S_asArray","s0","getPeriodId","realPeriod","getEventStreams","inbandStreams","eventStreams","eventStream","getBaseURLsFromElement","node","baseUrls","BaseURL_asArray","baseUri","earlyReturn","BaseURL","__text","dvb_priority","dvb_weight","getProducerReferenceTimesForAdaptation","prtArray","rep","prtsForAdaptation","prt","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","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","periodEnd","Errors","getEndTimeForLastPeriod","getMpd","loadedTime","getEventsForPeriod","EventStream_asArray","Event_asArray","currentMpdEvent","event","Event","calculatedPresentationTime","Signal","Binary","messageData","decodeArray","__cdata","getEventStreamForAdaptationSet","adaptationArray","InbandEventStream_asArray","getEventStreamForRepresentation","representationArray","hasAST","utcTimingsArray","UTCTiming_asArray","utcTimingEntries","utcTiming","getContentSteering","getLocation","Location","Location_asArray","getPatchLocation","PatchLocation","PatchLocation_asArray","getSuggestedPresentationDelay","getAvailabilityStartTime","getServiceDescriptions","serviceDescriptions","ServiceDescription_asArray","sd","operatingQuality","operatingBandwidth","referenceId","maxQualityDifference","getSupplementalProperties","supplementalProperties","SupplementalProperty_asArray","sp","ThumbnailTrackInfo","tilesHor","tilesVert","widthPerTile","heightPerTile","templateUrl","ThumbnailTracks","tracks","dashHandler","currentTrackIndex","segmentsController","adapter","baseURLController","_createTrack","useSegmentBase","track","vars","updateSegmentData","cache","segments","count","_normalizeSegments","readThumbnail","cached","el","ss","baseURL","blob","Blob","imageUrl","createObjectURL","_handleUpdatedSegmentData","buildTemplateUrl","getTracks","addTracks","getMediaInfoForType","voReps","getVoRepresentations","setTrackByIndex","getCurrentTrack","getCurrentTrackIndex","getThumbnailRequestForTime","currentVoRep","getSegmentRequestForTime","SegmentsController","segmentBaseController","DashHandler","pna","objectKeys","Duplex","util","inherits","Readable","Writable","readable","writable","allowHalfOpen","_writableState","ended","onEndNT","self","highWaterMark","_readableState","destroyed","_destroy","cb","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","MODEL","NAME","TYPE","VENDOR","MOBILE","TABLET","SMARTTV","enumerize","enums","str1","str2","lowerize","rgxMapper","arrays","props","strMapper","windowsVersionMap","regexes","OPERA","FIREFOX","CHROME","cpu","device","APPLE","engine","EDGE","os","extensions","getResult","_ua","_rgxmap","mergedRegexes","getBrowser","_browser","major","getCPU","_cpu","getDevice","_device","getEngine","_engine","getOS","_os","getUA","setUA","BROWSER","CPU","DEVICE","ENGINE","OS","$","jQuery","Zepto","lastSegment","isDynamicManifest","mediaHasFinished","_setRequestUrl","destination","_getRequestForSegment","getSegmentByTime","_onDynamicToStatic","getInitRequest","_generateInitRequest","getCurrentIndex","getNextSegmentRequest","indexToRequest","getSegmentByIndex","isLastSegmentRequested","bufferingTime","getNextSegmentRequestIdempotent","getValidTimeCloseToTargetTime","targetThreshold","currentUpperTime","currentLowerTime","adjustedTime","targetRequest","upperRequest","lowerRequest","requestEndTime","getValidTimeAheadOfTargetTime","TimelineSegmentsGetter","iterateSegments","iterFunc","fragments","frag","repeat","timeline","SegmentURL_asArray","relativeIdx","breakIterator","_calculateRepeatCountForNegativeR","nextFrag","repeatEndTime","availabilityEnd","dvrWindow","getCurrentDVRInfo","ceil","lastSegmentTime","requestedTime","requiredMediaTime","scaledMediaTime","toPrecision","getMediaFinishedInformation","availableSegments","TemplateSegmentsGetter","template","periodTime","calcPeriodRelativeTimeFromMpdRelativeTime","ListSegmentsGetter","offsetToSubtract","relativeIndex","SegmentBaseGetter","epsilon","ft","fd","getIndexByTime","getters","getSegmentsGetter","updateInitData","hasInitialization","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","streamProcessors","_isStartup","_bufferLevelStarved","_initialMediaRequestsDone","pr","nor","st","sf","generateUuid","_updateStreamProcessors","_onPeriodSwitchComplete","streamController","getStreamController","getActiveStream","activeStream","getProcessors","_copyParameters","parameterNames","copiedData","_applyWhitelistByKeys","enabledCMCDKeys","includes","_getCmcdData","_getGenericCmcdData","ot","_initForMediaType","encodedBitrate","_getBitrateByRequest","_getObjectDurationByRequest","mtp","_getMeasuredThroughputByType","dl","_getDeadlineByType","bl","_getBufferLevelByType","tb","getTopBitrateInfoFor","_getTopBitrateByType","nextRequest","streamProcessor","probeNextRequest","_probeNextRequest","minBandwidth","_calculateRtp","encodeURIComponent","getRelativeUrl","nrr","br","bs","su","_getCmcdDataForMediaSegment","_getCmcdDataForInitSegment","_getCmcdDataForOther","_getCmcdDataForLicense","_onPlaybackRateChanged","_onManifestLoaded","_onBufferLevelStateChanged","_onPlaybackSeeked","_buildFinalString","cmcdData","localeCompare","cmcdString","acc","getQueryParameter","finalPayloadString","_applyWhitelist","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","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","abortController","Headers","AbortController","signal","reqOptions","calculationMode","requestTime","throughputCapacityDelayMS","getThroughputCapacityDelayMS","markBeforeFetch","status","statusText","responseURL","ok","responseHeaders","body","loaded","total","stream","reader","measurement","totalBytes","bytesReceived","signaledFirstByte","remaining","markA","markB","tee","forMeasure","forConsumer","getReader","read","processFetch","done","chunkDownloadDurationMS","chunkBytes","chunkDownloadTimeRelativeMS","kbps","fetchDuration","bytesAllChunks","prev","curr","addMeasurement","lengthComputable","getEstimatedDownloadDurationMS","downloadedData","startTimeData","endTimeData","lastChunkWasFinished","processResult","calculatedThroughput","calculatedTime","datum","datumE","dataE","chunkThroughputs","shortDurationBytesReceived","shortDurationStartTime","chunkDownloadTime","ts","cumulatedChunkDownloadTime","calculateThroughputByChunkData","calculateDownloadedTime","concatTypedArray","performance","boxesInfo","subarray","noTrace","avgTimeDistance","next","cancel","LowLatencyThroughputModel","measurements","createBufferLevelTrendFunction","chunkMeasurements","sumX","sumY","sumXY","sumXSq","N","isBufferSafeAndStable","lastMeasurements","aveBufferLevelLastSegements","bufferLevelAtSegmentEnd","bufferLevelAtSegmentStart","fetchDownloadDurationMS","requestTimeMS","bitrateEntry","find","repId","adjustedAvailabilityStartTimeMS","segDurationMS","chunksDurationMS","segmentBytes","getEstimatedBufferLevel","currentBufferLevelMS","lastThreeMeasurements","lastMeasurement","pop","lastChunkRelativeTimeMS","isBufferStable","selectedOptimisticFactor","chunkAvailablePeriod","chunkBytesBBLE","chunkDownloadtimeMSBBLE","chunkCount","downloadThroughput","estimatedDownloadtimeMS","nextHigherBitrate","HTTPLoader","delayedRequests","retryRequests","downloadErrorToRequestTypeMap","cmcdModel","internalLoad","remainingAttempts","traces","firstProgress","needFailureReport","lastTraceTime","lastTraceReceivedCount","fileLoaderType","handleLoaded","success","checkExistenceOnly","responseUrl","responseStatus","getAllResponseHeaders","addHttpRequest","addManifestUpdate","getRetryAttemptsForType","retryRequest","getRetryIntervalsForType","complete","cmcdMode","additionalQueryParameter","cmcdQueryParameter","_getAdditionalQueryParameter","addAditionalQueryParameterToUrl","verb","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","check","tags","ranges","leftIndex","left","cast","right","rightIndex","basicFilter","tag","extendedFilter","lookup","generateISD","fromXML","renderHTML","render","CustomTimeRanges","customTimeRangeArray","add","mergeRanges","remove","rangeIndex1","rangeIndex2","range1","range2","codecCompatibilityTable","supportsMediaSource","hasWebKit","hasMediaSource","Capabilities","encryptedMediaSupported","supportsEncryptedMedia","supportsCodec","mediaCapabilities","decodingInfo","framerate","_canUseMediaCapabilitiesApi","configuration","supported","_checkCodecWithMediaCapabilities","MediaSource","isTypeSupported","WebKitMediaSource","_checkCodecWithMse","setEncryptedMediaSupported","supportsEssentialProperty","ep","codecRootCompatibleWithCodec","codec1","codec2","compatTableCodec","codecRoot","rootCompatible","compatibleCodecs","compatibleCodec","__webpack_amd_options__","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","PlaybackController","serviceDescriptionController","videoModel","wallclockTimeIntervalId","originalLiveDelay","playOnceInitialized","lastLivePlaybackTime","lowLatencyModeEnabled","seekTarget","internalSeek","playbackStalled","manifestUpdateInProgress","initialCatchupModeActivated","pause","_onDataUpdateCompleted","_onFragmentLoadProgress","_onManifestUpdated","_onStreamsComposed","_onPlaybackEnded","_onStreamInitializing","_onRepresentationSwitch","stopUpdatingWallclockTime","removeEventListener","_onCanPlay","_onCanPlayThrough","_onPlaybackStart","_onPlaybackWaiting","_onPlaybackPlaying","_onPlaybackPaused","_onPlaybackError","_onPlaybackTimeUpdated","_onPlaybackProgress","_onPlaybackMetaDataLoaded","_onPlaybackLoadedData","onPlaybackStalled","_onNativePlaybackEnded","_onVolumeChanged","getTimeToStreamEnd","sInfo","getStreamEndTime","refInfo","play","adjustLiveDelay","getElement","_adjustLiveDelayAfterUserInteraction","seek","stickToBuffered","internal","setCurrentTime","_getDvrWindowEnd","hasVideoTrack","dvrInfo","nowAsPresentationTime","calcPresentationTimeFromWallTime","isPaused","isSeeking","isStalled","getEnded","updateCurrentTime","getReadyState","actualTime","_getAdjustedPresentationTime","timeChanged","mediatype","DVRMetrics","DVRWindow","startUpdatingWallclockTime","setInterval","addDVRMetric","clearInterval","representationInfo","convertRepresentationToRepresentationInfo","currentRepresentation","getActiveStreamInfo","playingTime","seekTime","timeToEnd","rate","isLast","srcElement","minDelay","activeStreamInfo","periodSwitch","addEventListener","getBufferLevel","filterList","getActiveStreamProcessors","getPlaybackStalled","getInitialCatchupModeActivated","getIsManifestUpdateInProgress","getPlayedRanges","computeAndSetLiveDelay","adjustedFragmentDuration","serviceDescriptionSettings","getServiceDescriptionSettings","minBufferTime","dvrWindowSize","getLiveDelay","getOriginalLiveDelay","getClientTimeOffset","seekToOriginalLive","dvrWindowEnd","seektime","seekToCurrentLive","SourceBufferSink","intervalId","textController","callbacks","appendQueue","isAppendingInProgress","mediaSource","lastRequestAppended","changeType","_waitForUpdateEnd","_initializeForText","getTextSourceBuffer","_addEventListeners","_updateEndHandler","_errHandler","updateAppendWindow","appendWindowEnd","appendWindowStart","updateTimestampOffset","timestampOffset","_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","_onAppended","_triggerEvent","_showBufferRanges","getTotalBufferedTime","bufferAhead","_handleQuotaExceededError","hasEnoughSpaceToAppend","quotaExceededTime","clearBuffers","getClearRanges","_updateBufferLevel","endFragment","_checkIfBufferingCompleted","_onPlaybackProgression","rangeAtCurrenTime","getRangeAt","rangeAtSeekTarget","getCurrentRepresentation","_adjustSeekTarget","pruneAllSafely","getAllRangesWithSafetyFactor","clearRanges","behindPruningRange","targetTime","bufferToKeepBehind","startOfBuffer","rangeEnd","currentTimeRequest","_getRangeBehindForPruning","aheadPruningRange","endOfBuffer","continuousBufferTime","getContinuousBufferTimeForTargetTime","bufferToKeepAhead","rangeStart","oldRangeStart","_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","getMediaSource","appendInitSegmentFromCache","getIsBufferingCompleted","getIsPruningInProgress","prepareForPlaybackSeek","prepareForReplacementTrackSwitch","prepareForNonReplacementTrackSwitch","prepareForReplacementQualitySwitch","setSeekTarget","segmentRequestingCompleted","NotFragmentedTextBufferController","initialized","ScheduleController","currentRepresentationInfo","timeToLoadDelay","scheduleTimeout","lastFragmentRequest","topQualityIndex","lastInitializedQuality","switchTrack","initSegmentRequired","checkPlaybackQuality","bufferController","startScheduleTimer","clearScheduleTimer","timeoutValue","schedule","getInitialPlayback","getAutoPlay","_shouldClearScheduleTimer","newTopQualityIndex","getBufferTarget","_shouldBuffer","_shouldScheduleNextRequest","qualityChange","bufferTarget","schedulingInfo","getCurrentSchedulingInfo","_getBufferTargetForFragmentedText","videoBufferLevel","_getBufferTargetForAudio","isPlayingAtTopQuality","_getGenericBufferTarget","_completeQualityChange","oldMediaInfo","newMediaInfo","oldQuality","_onURLResolutionFailed","_onPlaybackStarted","updatePlayListTraceMetrics","playbackspeed","_hasVideoTrack","setCurrentRepresentation","getTimeToLoadDelay","setSwitchTrack","getSwitchStrack","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","shouldUseExplicitTimeForRequest","qualityChangeInProgress","manifestModel","mediaController","segmentBlacklistController","getIsTextTrack","getData","_onInitFragmentNeeded","rescheduleIfNoRequest","_noValidRequest","_onMediaFragmentNeeded","_getFragmentRequest","_mediaRequestGenerated","_noMediaRequestGenerated","blacklistUrl","contains","_shouldIgnoreRequest","setExplicitBufferingTime","useTime","addBufferState","pushPlayListTraceMetrics","_onBufferCleared","_onSourceBufferError","_prepareForDefaultQualitySwitch","_bufferClearedForNonReplacement","_onFragmentLoadingAbandoned","isInitializationRequest","_onFragmentLoadingCompleted","_handleFragmentLoadingError","_onSetFragmentedTextAfterDisabled","_onSetNonFragmentedText","currentTrackInfo","selectMediaInfo","_onQuotaExceeded","newRealAdaptation","getRealAdaptation","maxQuality","minIdx","getInitialBitrateFor","eventStreamMedia","getEventsFor","eventStreamTrack","mediaInbandEvents","trackInbandEvents","inbandEvents","eventBoxes","sidx","mediaAnchorTime","fragmentMediaStartTime","getEvent","_handleInbandEvents","_bufferClearedForReplacement","_onSeekTarget","registerStreamType","RepresentationController","controller","_createBufferControllerForType","isUpdating","getBufferController","getFragmentModel","getRepresentationController","createBufferSinks","previousBufferSinks","updateStreamInfo","newStreamInfo","clearMediaInfoArray","addMediaInfo","prepareTrackSwitch","shouldReplace","prepareQualityChange","forceReplace","safeBufferLevel","abandonmentState","_prepareForFastQualitySwitch","createPlaylistTraceMetrics","finalisePlayList","prepareInnerPeriodPlaybackSeeking","prepareOuterPeriodPlaybackSeeking","unRegisterStreamType","FragmentController","fragmentModels","model","onFragmentLoadingCompleted","isInit","strInfo","DataChunk","createDataChunk","getModel","FragmentLoader","Thumbnail","y","BitrateInfo","ThumbnailController","thumbnailTracks","provide","thumbIndex","thumbnail","seq","seqIdx","_buildUrlFromTemplate","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","addMediaInfosToBuffer","_createStreamProcessor","getCurrentTrackFor","updateTopQualityIndex","_initializeMediaForType","buffers","bufferSinks","sink","getValue","_checkIfInitializationCompleted","createTracks","contentProtection","deactivate","deactivateStream","setPreloaded","setIsEndedEventSignaled","getStartTime","onProtectionError","addInlineEvents","initializeForMedia","handleKeySystemFromManifest","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","_onEventTimer","currentVideoTime","presentationTimeThreshold","_triggerEvents","_removeOutdatedEventObjects","_iterateAndTriggerCallback","_startEvent","_eventHasExpired","periodEndTime","_eventIsInvalid","periodId","_removeEvent","_addOrUpdateEvent","shouldOverwriteExistingEvents","eventState","indexOfExistingEvent","findIndex","triggeredReceivedEvent","triggeredStartEvent","oldEvent","_handleManifestReloadEvent","newDuration","validUntil","newManifestValidAfter","periodDuration","calculatedPresentationTimeInSeconds","periodIds","currentPeriod","schemeIdUris","eventId","_refreshManifest","_sendCallbackRequest","getInbandEvents","getInlineEvents","LEVELS","SUGGESTION","WARNING","EVENTS","NO_UTC_TIMING_ELEMENT","NON_COMPLIANT_SMPTE_IMAGE_ATTRIBUTE","INVALID_DVR_WINDOW","StreamController","capabilitiesFilter","mediaSourceController","timeSyncController","contentSteeringController","uriFragmentModel","streams","protectionData","autoPlay","isStreamSwitchingInProgress","hasMediaError","hasInitialisationError","initialPlayback","initialSteeringRequest","playbackEndedTimerInterval","preloadingStreams","supportsChangeType","firstLicenseIsFetched","waitForPlaybackStartTimeout","providedStartTime","errorInformation","_checkConfig","_checkInitialize","_onTimeSyncCompleted","streamsInfo","getStreamsInfo","updateManifestUpdateInfo","getBufferRange","clientTimeOffset","shouldKeepStream","_filterOutdatedStreams","_initializeOrUpdateStream","addManifestUpdateStreamInfo","shouldQueryBeforeStart","loadSteeringData","_initializeForFirstStream","dvrRange","waitingTime","calculateProducerReferenceTimeOffsets","_getFragmentDurationForLiveDelayCalculation","liveEdge","startTimeFromUri","_getStartTimeFromUriParameters","providedStartTimeAsPresentationTime","_getStartTimeFromProvidedData","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","_onLiveDelaySettingUpdated","playbackQuality","getPlaybackQuality","addDroppedFrames","_onStreamBufferingCompleted","upcomingStreams","refStream","refStreamInfo","_getNextStreams","_stopPlaybackEndedTimerInterval","targetIndex","lastDiff","diff","_getNextStream","stopSteeringRequestTimer","manifestDuration","fragData","getURIFragmentData","referenceTime","_getStartTimeFromString","targetValue","targetString","posix","streamInfos","maxFragmentDuration","fragmentDurations","updatePeriods","manifestUTCTimingSources","ConformanceViolationConstants","allUTCTimingSources","filterUnsupportedFeatures","addPlayList","startReason","createPlaylistMetrics","counts","_handleMediaErrorDecode","msExtendedCode","_onManifestValidityChanged","KEY_SESSION_UPDATED","clearAllCurrentMetrics","PROTECTION_DESTROYED","targetMediaType","autoPl","protData","PROTECTION_CREATED","setMediaElement","setProtectionData","registerEvents","getTimeRelativeToStreamId","baseStart","streamStart","streamDur","loadWithManifest","getIsStreamSwitchInProgress","switchToVideoElement","getHasMediaOrInitialisationError","GapController","lastPlaybackTime","gapHandlerInterval","lastGapJumpPosition","jumpTimeoutHandler","trackSwitchByMediaType","_onInitialStreamSwitch","_onBufferReplacementStarted","_onBufferReplacementEnded","_unregisterEvents","_shouldCheckForGaps","_jumpGap","_startGapHandler","checkSeekingState","trackSwitchInProgress","shouldIgnoreSeekingState","_shouldIgnoreSeekingState","streamEnd","_getNextRangeIndex","nextRangeIndex","_isTimeBuffered","seekToPosition","jumpToStreamEnd","timeToStreamEnd","timeUntilGapEnd","timeToWait","_registerEvents","CatchupController","isCatchupSeekInProgress","isSafari","parseUserAgent","_onCatchupSettingUpdated","getCatchupModeEnabled","setPlaybackRate","getCatchupPlaybackRates","_getCatchupMode","_getLatencyDrift","_lolpNeedToCatchUpCustom","_defaultNeedToCatchUp","_shouldStartCatchUp","newRate","liveCatchupPlaybackRates","getCatchupMaxDrift","currentLiveLatency","targetLiveDelay","liveCatchUpPlaybackRates","cpr","E","_calculateNewPlaybackRateLolP","_calculateNewPlaybackRateDefault","minPlaybackRateChange","_startPlaybackCatchUp","_checkPlaybackRates","SUPPORTED_SCHEMES","ServiceDescriptionController","prftOffsets","_updateBandwidthSetting","getProducerReferenceTimeOffsets","timeOffsets","mediaTypes","astInSeconds","offsets","getProducerReferenceTimes","voRep","prt0","supportedServiceDescriptions","allClientsServiceDescriptions","_getDvbServiceDescriptionLatencyParameters","_getStandardServiceDescriptionLatencyParameters","sdLatency","_calculateTimeOffset","_applyServiceDescriptionLatency","_applyServiceDescriptionPlaybackRate","maxBandwidth","targetBandwidth","mediaTypesToApply","_applyServiceDescriptionOperatingBandwidth","ContentSteeringRequest","ContentSteeringResponse","reloadUri","serviceLocationPriority","QUERY_PARAMETER_KEYS","ContentSteeringController","currentSteeringResponseData","currentSelectedServiceLocation","nextRequestTimer","urlLoader","_onPeriodSwitchCompleted","_onFragmentLoadingStarted","getSteeringDataFromManifest","steeringDataFromManifest","encodeURI","_getSteeringServerUrl","_startSteeringRequestTimer","_handleSteeringResponse","_handleSteeringResponseError","getCurrentSteeringResponseData","MediaController","initialSettings","lastSelectedTracks","domStorage","getTracksFor","current","setTrack","noSettingsSave","isTracksEqual","switchMode","extractSettings","storeLastSettings","roles","role","accessibility","audioChannelConfiguration","setSavedMediaSettings","setInitialSettings","getInitialSettings","t1","t2","sameId","sameViewpoint","viewpoint","sameLang","sameCodec","sameRoles","sameAccessibility","sameAudioChannelConfiguration","filterTracksBySettings","filterFn","tracksAfterMatcher","matchSettingsLang","bcp47Normalize","matchSettingsIndex","matchSettingsViewPoint","matchSettingsRole","isTrackActive","matchRole","matchSettingsAccessibility","matchSettingsAudioChannelConfig","getTracksWithHighestBitrate","trackArr","getTracksWithHighestEfficiency","Infinity","resolution","getTracksWithWidestRange","representationCount","selectInitialTrack","tmpArr","_trackSelectionModeHighestSelectionPriority","_trackSelectionModeHighestBitrate","_trackSelectionModeFirstTrack","_trackSelectionModeHighestEfficiency","_trackSelectionModeWidestRange","tracksForType","getSavedMediaSettings","image","mediaTracks","isCurrentTrack","matchSettings","matchLang","normalizedSettingsLang","matchIndex","matchViewPoint","matchAccessibility","matchAudioChannelConfiguration","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","ContentSteeringSelector","_findexIndexOfServiceLocation","serviceLocationPriorities","steeringIndex","elem","selectBaseUrlIndex","steeringDataFromMpd","BaseURLSelector","serviceLocationBlacklistController","basicSelector","dvbSelector","contentSteeringSelector","selector","chooseSelector","isDVB","BaseURLController","baseURLTreeModel","baseURLSelector","onBlackListChanged","getIsDVB","TextRequest","XlinkLoader","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","sumPeriodDurations","originalManifest","errorText","ErrorHandler","CapabilitiesFilter","_filterUnsupportedCodecs","as","configurations","frameRate","_createVideoConfiguration","samplerate","audioSamplingRate","_createAudioConfiguration","_createConfiguration","_","_filterUnsupportedRepresentationsOfAdaptation","adaptationSet","_filterUnsupportedAdaptationSetsOfPeriod","_filterUnsupportedEssentialProperties","customFilter","_applyCustomFilters","URIFragmentData","xywh","URIFragmentModel","URIFragmentDataVO","uri","hashIndex","fragment","equalIndex","ManifestModel","MediaPlayerModel","_checkMinPlaybackRate","CATCHUP_PLAYBACK_RATE_MIN_LIMIT","_checkMaxPlaybackRate","lowLatencyMultiplyFactor","lowLatencyReductionFactor","settingsPlaybackRate","sdPlaybackRate","getAbrBitrateParameter","setting","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","getAverageSlidingWindow","checkSettingsForMediaType","latencyTimeInMilliseconds","downloadTimeInMilliseconds","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","_currentTime","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","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","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","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","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","timeOffset","getTrackByIdx","currentItem","align","onenter","onexit","divs","cueInTrack","addCue","deleteTrackCues","setCurrentTrackIdx","setCueStyleOnTrack","renderingType","ResizeObserver","observe","clearCaptionContainer","setNativeCueStyle","removeNativeCueStyle","cueInRange","strict","lastIdx","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","allTracksAreDisabled","forceTextStreaming","textTracksAdded","disableTextBeforeTextTracksAdded","_onTextTracksAdded","currentTrack","lastEnabledIndex","oldTrackIdx","currentFragTrack","_setFragmentedTextTrack","_setNonFragmentedTextTrack","textSourceBuffer","getAllTracksAreDisabled","enableText","enable","enableForcedTextStreaming","MediaPlayer","mediaPlayerInitialized","streamingInitialized","playbackInitialized","metricsReportingController","offlineController","gapController","catchupController","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","urlOrManifest","stop","_createPlaybackControllers","_createManifestLoader","Protection","createProtectionSystem","_detectOffline","OfflineController","_getAsUTC","valToConvert","resetRecords","view","parentNameString","setMute","muted","isMuted","setVolume","volume","getVolume","timeAsUTC","durationAsUTC","getDVRWindowSize","getTargetLiveDelay","convertToTimeCode","formatUTC","locales","hour12","withDate","toLocaleDateString","toLocaleTimeString","getDebug","updateSource","setQualityFor","updatePortalSize","getBitrateInfoListFor","getStreamsFromManifest","getTracksForTypeFromManifest","setInitialMediaSettingsFor","getInitialMediaSettingsFor","setCurrentTrack","addABRCustomRule","removeABRCustomRule","removeAllABRCustomRule","getABRCustomRules","retrieveManifest","getProtectionController","attachProtectionController","attachTTMLRenderingDiv","getCurrentTextTrackIndex","provideThumbnail","getDashAdapter","getOfflineController","triggerSteeringRequest","getSettings","updateSettings","resetSettings","destroy","T","encodeArray","R","ASCII","encodeASCII","decodeASCII","character","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","LangMatcher","CommonProperty","_name","_merge","MapNode","_properties","_children","RepresentationBaseValuesMap","commonProperties","SegmentValuesMap","objectIron","jsonTime","Patch","add_asArray","operand","replace_asArray","ironedTime","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","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","bcp47","defaults","many","schema","emptyExtraFields","compareSingleton","own","script","collator","Intl","Collator","variants","privateuse","irregular","regular","removed","singleton","alphanumeric","alphabetical","decimal","normal","extendedLanguageSubtags","fail","forgiving","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","pendingKeySessionsToHandle","protDataSet","sessionType","robustnessLevel","selectedKeySystem","keySystemSelectionInProgress","licenseXhrRequest","licenseRequestRetryTimeout","protectionKeyController","protectionModel","needkeyRetries","_selectKeySystemOrUpdateKeySessions","supportedKs","fromManifest","_handleKeySessions","keySystemAccess","requestedKeySystems","ksA","ksB","ks","systemString","keySystemConfiguration","_getKeySystemConfiguration","configs","requestKeySystemAccess","selectedSystemString","mksa","selectKeySystem","_getProtDataForKeySystem","serverCertificate","setServerCertificate","ProtectionErrors","_selectInitialKeySystem","ksIdx","_loadOrCreateKeySession","keySystemInfo","isClearKey","clearkeys","kids","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","keyPairs","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","_abortLicenseRequest","getErrorResponse","serverResponse","responseCode","responseText","retry","initDataType","abInitData","getSupportedKeySystemsFromSegmentPssh","_handleKeySystemFromPssh","supportedKeySystems","currentKs","getSupportedKeySystemsFromContentProtection","removeKeySession","closeKeySession","setSessionType","setRobustnessLevel","cps","getKeySystems","setKeySystems","keySystems","INTERNAL_KEY_MESSAGE","INTERNAL_KEY_STATUS_CHANGED","retryTimeout","KeyPair","keyID","ClearKeyKeySet","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","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","supportedKS","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","opt","SAXParser","SAXStream","createStream","MAX_BUFFER_LENGTH","bufferCheckPosition","lowercase","lowercasetags","looseCase","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","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","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","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","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,EA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AY,CAChC,+BACG,CAACpuD,EAAS,CAACouD,EAAM,SAAU,CAG9B,4BACA,mDACA,2CACG,CAACA,EAAMpuD,GAAU,CACpB,yBACG,CAACA,EAAS,CAACouD,EAAMiB,eAAiB,CACrC,qBACG,CAACrvD,EAAS,CAACouD,EAxKR,UAwKuB,CAG7B,uBACA,8DAEA,qDACA,kCACA,2BAGA,oLAEA,uBACG,CAACA,EAAMpuD,GAAU,CACpB,qDACG,CAACA,EAAS,CAACouD,EAAM,cAAgB,CACpC,wBACG,CAACpuD,EAAS,CAACouD,EAAM,wBAAyB,CAC7C,8BACG,CAACpuD,EAAS,CAACouD,EAAM,WAAY,CAChC,yBACG,CAACpuD,EAAS,CAACouD,EAAM,cAAe,CACnC,+CACG,CAACpuD,EAAS,CAACouD,EAAM,OAAQ,CAC5B,yBACG,CAACpuD,EAAS,CAACouD,EAAM,WAAY,CAChC,2BACG,CAAC,CAACA,EAAM,OAAQ,qBAAuBpuD,GAAU,CACpD,uBACG,CAACA,EAAS,CAACouD,EAAMkB,kBAAoB,CACxC,qBACG,CAACtvD,EAAS,CAACouD,EAAMiB,gBAAkB,CACtC,0BACG,CAACrvD,EAAS,CAACouD,EAAM,YAAa,CACjC,sBACG,CAACpuD,EAAS,CAACouD,EAAM,YAAa,CACjC,qBACG,CAACpuD,EAAS,CAACouD,EAAMiB,gBAAkB,CACtC,2BACG,CAACrvD,EAAS,CAACouD,EAAM,iBAAmB,CACvC,sBACG,CAACpuD,EAAS,CAACouD,EAxNR,YAwNyB,CAC/B,iCACG,CAAC,CAACA,EAAM,gBAAkB,CAC7B,gDACG,CAAC,CAACA,EAAM,OAAQ,cAAgBpuD,GAAU,CAC7C,+BACG,CAAC,CAACouD,EAAM,KAAM,KAAMpuD,GAAU,CACjC,gCACA,iDACA,0DACG,CAACouD,EAAMpuD,GAAU,CACpB,2BACA,gBACG,CAACouD,GAAO,CAGX,+DACG,CAAC,CAACA,EA9NI,YA8NapuD,GAAU,CAChC,4BACA,4BACA,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QACfmiE,EAAUniE,QAGd,SAASwgI,KAEL,IAAMn0C,EAAiBo0C,KAElBlxE,IACDA,EAAmB8lC,GAAiBthG,IAAS2B,eAG5Cw7E,IACDA,EAAiBisD,GAAeppI,IAAShP,OAAO,CAC5Cs3B,aACAuiE,gBACArpC,UACAspC,kBACAnU,aACAhuE,eAIR44F,EAAmBvuD,UAAU,CACzBx3B,eACA+yB,wBACAiT,UACA74C,YACAkiF,gBACAviE,eAGJkzC,EAAiBxoB,UAAU,CACvBx3B,eACA+lF,qBACAjJ,iBACAzN,gBACAtiE,mBACAgmB,wBACA6jD,uBACAjV,iBACA37B,UACA38B,cACAyD,aACA7V,oBACAkkE,aACA5oC,qBACA2oC,+BACAgrB,4BACA5nE,gBACAgxD,kBACAniF,YACA84C,oBACAkgD,mBACAj+C,2BAGJmnF,EAAc73F,UAAU,CACpBrqC,YACAolC,qBACAytB,mBACAmb,aACAlkE,oBACA+uC,YAGJzT,EAAmBiF,UAAU,CACzBwoB,mBACAkb,+BACA7xD,cACA28B,UACAm1B,aACAlkE,oBACA9J,cAGJmiI,EAAkB93F,UAAU,CACxBwoB,mBACAztB,qBACAxlB,mBACAouD,aACAhuE,cAGJmxB,EAAckZ,UAAU,CACpBwoB,mBACAg1C,aACAjoF,mBACAgmB,wBACA1pB,cACA28B,UACAm1B,aACAhuE,cAGJylE,EAAUp7B,UAAU,CAChBlZ,gBACAjV,cACAkpB,uBAGJ2zD,EAA0B1uD,UAAU,CAChCwO,UACAl5B,aACAzD,cACA0D,mBACAsiE,gBACA/wD,gBACArxB,YACAqb,gBAAiBQ,YAAgBtkB,IAAS2B,gBAI9Cm4B,EAAcgV,aACd0sB,EAAiB1sB,WAAWgzD,EAAUD,GACtC1kB,EAAeruC,aACf+7F,EAAc/7F,aACdg8F,EAAkBh8F,aAClBs/B,EAAUt/B,aACV4yD,EAA0B5yD,aAC1B4U,GAAsB5U,aAG1B,SAAS49F,KACL,OAAOpzB,GAAet5G,IAAShP,OAAO,CAClCu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OAAOs8I,QAAUt8I,OAAOs8I,OAAOylD,iBAEtD,oBAAX/hM,QAA0BA,QAAUA,OAAOssF,mBACnC,aAA/BtsF,OAAOm0H,SAAStkC,WACZ7vF,OAAOs8I,OACPjsI,EAASsxL,YAGTN,EAAerhM,OAAOsrF,aAflC,WACQtrF,OAAOs8I,SACPt8I,OAAOwrF,cAAc61G,GACrBhxL,EAASsxL,eAYkD,KAG3D3hM,OAAOssF,iBAAiB,QAvBhC,SAAS01G,IACLhiM,OAAOyoF,oBAAoB,OAAQu5G,GACnC3xL,EAASsxL,gBAyBEtxL,Q,OC3FfisI,OAAOe,WAAaA,UACpBf,OAAOD,iBAAmBA,UAC1BC,OAAOwlD,mBAAqBA,EAC5BxlD,OAAOxjI,MAAQA,IACfwjI,OAAOv4D,oBAAsBA,IAEdu4D,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 = 125);\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.PRODUCER_REFERENCE_TIME = 'ProducerReferenceTime';\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.REPRESENTATION_ASARRAY = 'Representation_asArray';\n this.PRODUCERREFERENCETIME_ASARRAY = 'ProducerReferenceTime_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.SERVICE_DESCRIPTION_OPERATING_QUALITY = 'OperatingQuality';\n this.SERVICE_DESCRIPTION_OPERATING_BANDWIDTH = 'OperatingBandwidth';\n this.PATCH_LOCATION = 'PatchLocation';\n this.PUBLISH_TIME = 'publishTime';\n this.ORIGINAL_PUBLISH_TIME = 'originalPublishTime';\n this.ORIGINAL_MPD_ID = 'mpdId';\n this.WALL_CLOCK_TIME = 'wallClockTime';\n this.PRESENTATION_TIME = 'presentationTime';\n this.LABEL = 'Label';\n this.GROUP_LABEL = 'GroupLabel';\n this.CONTENT_STEERING = 'ContentSteering';\n this.CONTENT_STEERING_AS_ARRAY = 'ContentSteering_asArray';\n this.DEFAULT_SERVICE_LOCATION = 'defaultServiceLocation';\n this.QUERY_BEFORE_START = 'queryBeforeStart';\n this.PROXY_SERVER_URL = 'proxyServerURL';\n this.CONTENT_STEERING_RESPONSE = {\n VERSION: 'VERSION',\n TTL: 'TTL',\n RELOAD_URI: 'RELOAD-URI',\n SERVICE_LOCATION_PRIORITY : 'SERVICE-LOCATION-PRIORITY'\n }\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} Content Steering\n * @memberof Constants#\n * @static\n */\n this.CONTENT_STEERING = 'contentSteering';\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_DVB_LL_SCHEME = 'urn:dvb:dash:lowlatency:scope:2019';\n this.SUPPLEMENTAL_PROPERTY_DVB_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 this.FILE_LOADER_TYPES = {\n FETCH: 'fetch_loader',\n XHR: 'xhr_loader'\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 this.SETTING_UPDATED_LIVE_DELAY = 'settingUpdatedLiveDelay';\n this.SETTING_UPDATED_LIVE_DELAY_FRAGMENT_COUNT = 'settingUpdatedLiveDelayFragmentCount';\n this.SETTING_UPDATED_CATCHUP_ENABLED = 'settingUpdatedCatchupEnabled';\n this.SETTING_UPDATED_PLAYBACK_RATE_MIN = 'settingUpdatedPlaybackRateMin';\n this.SETTING_UPDATED_PLAYBACK_RATE_MAX = 'settingUpdatedPlaybackRateMax';\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 event is fired when the frame at the current playback position of the media has finished loading;\n * often the first frame\n * @event MediaPlayerEvents#PLAYBACK_LOADED_DATA\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 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 video element reports that the volume has changed\n * @event MediaPlayerEvents#PLAYBACK_VOLUME_CHANGED\n */\n this.PLAYBACK_VOLUME_CHANGED = 'playbackVolumeChanged';\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 * Event that is dispatched whenever an adaptation set is removed due to all representations not being supported.\n * @event MediaPlayerEvents#ADAPTATION_SET_REMOVED_NO_CAPABILITIES\n */\n this.ADAPTATION_SET_REMOVED_NO_CAPABILITIES = 'adaptationSetRemovedNoCapabilities';\n /**\n * Triggered when a content steering request has completed.\n * @event MediaPlayerEvents#CONTENT_STEERING_REQUEST_COMPLETED\n */\n this.CONTENT_STEERING_REQUEST_COMPLETED = 'contentSteeringRequestCompleted';\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 * The type of the loader that was used. Distinguish between fetch loader and xhr loader\n */\n this._fileLoaderType = 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}\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.DVB_REPORTING_TYPE = 'DVBReporting';\nHTTPRequest.LICENSE = 'license';\nHTTPRequest.CONTENT_STEERING_TYPE = 'ContentSteering';\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\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 */\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 this.HTTP_REQUEST_DVB_REPORTING_TYPE = 'DVBReporting';\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 */\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, 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\n/**\n * @class\n * @ignore\n */\n\nimport path from 'path-browserify'\nimport { UAParser } from 'ua-parser-js'\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 static parseUserAgent(ua = null) {\n try {\n const uaString = ua === null ? typeof navigator !== 'undefined' ? navigator.userAgent.toLowerCase() : '' : '';\n\n return UAParser(uaString);\n }\n catch(e) {\n return {};\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 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 */\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';\nimport EventBus from './EventBus';\nimport Events from './events/Events';\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 * manifestUpdateRetryInterval: 100,\n * cacheInitSegments: true,\n * applyServiceDescription: true,\n * applyProducerReferenceTime: true,\n * applyContentSteering: true,\n * eventControllerRefreshDelay: 100,\n * enableManifestDurationMismatchFix: true,\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 * },\n * protection: {\n * keepProtectionMediaKeys: false,\n * ignoreEmeEncryptedEvent: false,\n * detectPlayreadyMessageFormat: true,\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: true,\n * avoidCurrentTimeRangePruning: false,\n * useChangeTypeForTrackSwitch: true\n * },\n * gaps: {\n * jumpGaps: true,\n * jumpLargeGaps: true,\n * smallGapLimit: 1.5,\n * threshold: 0.3,\n * enableSeekFix: true,\n * enableStallFix: false,\n * stallSeek: 0.1\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 * maxDrift: NaN,\n * playbackRate: {min: NaN, max: NaN},\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: 20000,\n * manifestRequestTimeout: 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: 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 * enabledKeys: ['br', 'd', 'ot', 'tb' , 'bl', 'dl', 'mtp', 'nor', 'nrr', 'su' , 'bs', 'rtp' , 'cid', 'pr', 'sf', 'sid', 'st', 'v']\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 */\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=true]\n * Specifies if we fire manual waiting events once the stall threshold is reached\n * @property {boolean} [avoidCurrentTimeRangePruning=false]\n * Avoids pruning of the buffered range that contains the current playback time.\n *\n * That buffered range is likely to have been enqueued for playback. Pruning it causes a flush and reenqueue in WPE and WebKitGTK based browsers. This stresses the video decoder and can cause stuttering on embedded platforms.\n * @property {boolean} [useChangeTypeForTrackSwitch=true]\n * If this flag is set to true then dash.js will use the MSE v.2 API call \"changeType()\" before switching to a different track.\n * Note that some platforms might not implement the changeType functio. dash.js is checking for the availability before trying to call it.\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=true]\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 * @property {boolean} [enableStallFix=false]\n * If playback stalled in a buffered range this fix will perform a seek by the value defined in stallSeek to trigger playback again.\n * @property {number} [stallSeek=0.1]\n * Value to be used in case enableStallFix is set to true\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} [maxDrift=NaN]\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={min: NaN, max: NaN}]\n * Use this parameter to set the minimum and maximum catch up rates, as percentages, 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 min catch up rate are in the range -0.5 to 0 (-50% to 0% playback rate decrease)\n *\n * Valid values for max catch up rate are in the range 0 to 1 (0% to 100% playback rate increase).\n *\n * Set min and max to NaN to turn off live catch up feature.\n *\n * These playback rate limits take precedence over any PlaybackRate values in ServiceDescription elements in an MPD. If only one of the min/max properties is given a value, the property without a value will not fall back to a ServiceDescription value. Its default value of NaN will be used.\n *\n * Note: Catch-up mechanism is only applied when playing low latency live streams.\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 * @property {boolean} detectPlayreadyMessageFormat\n * If set to true the player will use the raw unwrapped message from the Playready CDM\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. This value is specified in kbps.\n *\n * Use -1 for no limit.\n * @property {module:Settings~AudioVideoSettings} [minBitrate={audio: -1, video: -1}]\n * The minimum bitrate that the ABR algorithms will choose. This value is specified in kbps.\n *\n * Use -1 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. This value is specified in kbps.\n *\n * Use -1 to let the player decide.\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 * @property {Array.<string>} [enabledKeys]\n * This value is used to specify the desired CMCD parameters. Parameters not included in this list are not reported.\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 {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 {boolean} [applyServiceDescription=true]\n * Set to true if dash.js should use the parameters defined in ServiceDescription elements\n * @property {boolean} [applyProducerReferenceTime=true]\n * Set to true if dash.js should use the parameters defined in ProducerReferenceTime elements in combination with ServiceDescription elements.\n * @property {boolean} [applyContentSteering=true]\n * Set to true if dash.js should apply content steering during playback.\n * @property {number} [eventControllerRefreshDelay=100]\n * For multi-period streams, overwrite the manifest mediaPresentationDuration attribute with the sum of period durations if the manifest mediaPresentationDuration is greater than the sum of period durations\n * @property {boolean} [enableManifestDurationMismatchFix=true]\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=20000]\n * Time in milliseconds before timing out on loading a media fragment.\n *\n * @property {number} [manifestRequestTimeout=10000]\n * Time in milliseconds before timing out on loading a manifest.\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 const context = this.context;\n const eventBus = EventBus(context).getInstance();\n const DISPATCH_KEY_MAP = {\n 'streaming.delay.liveDelay': Events.SETTING_UPDATED_LIVE_DELAY,\n 'streaming.delay.liveDelayFragmentCount': Events.SETTING_UPDATED_LIVE_DELAY_FRAGMENT_COUNT,\n 'streaming.liveCatchup.enabled': Events.SETTING_UPDATED_CATCHUP_ENABLED,\n 'streaming.liveCatchup.playbackRate.min': Events.SETTING_UPDATED_PLAYBACK_RATE_MIN,\n 'streaming.liveCatchup.playbackRate.max': Events.SETTING_UPDATED_PLAYBACK_RATE_MAX\n };\n\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 manifestUpdateRetryInterval: 100,\n cacheInitSegments: false,\n applyServiceDescription: true,\n applyProducerReferenceTime: true,\n applyContentSteering: true,\n eventControllerRefreshDelay: 100,\n enableManifestDurationMismatchFix: true,\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 },\n protection: {\n keepProtectionMediaKeys: false,\n ignoreEmeEncryptedEvent: false,\n detectPlayreadyMessageFormat: true,\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 avoidCurrentTimeRangePruning: false,\n useChangeTypeForTrackSwitch: true\n },\n gaps: {\n jumpGaps: true,\n jumpLargeGaps: true,\n smallGapLimit: 1.5,\n threshold: 0.3,\n enableSeekFix: true,\n enableStallFix: false,\n stallSeek: 0.1\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 maxDrift: NaN,\n playbackRate: {\n min: NaN,\n max: NaN\n },\n playbackBufferMin: 0.5,\n enabled: null,\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: 20000,\n manifestRequestTimeout: 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: true\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 enabledKeys: ['br', 'd', 'ot', 'tb' , 'bl', 'dl', 'mtp', 'nor', 'nrr', 'su' , 'bs', 'rtp' , 'cid', 'pr', 'sf', 'sid', 'st', 'v']\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] instanceof Array) && source[n] !== null) {\n mixinSettings(source[n], dest[n], path.slice() + n + '.');\n } else {\n dest[n] = Utils.clone(source[n]);\n if (DISPATCH_KEY_MAP[path + n]) {\n eventBus.trigger(DISPATCH_KEY_MAP[path + n]);\n }\n }\n } else {\n console.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,\n update,\n 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 */\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 */\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 */\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\nimport FactoryMaker from '../../core/FactoryMaker';\n\nexport function modifyRequest(httpRequest, requestModifier) {\n const request = {\n url: httpRequest.url,\n method: httpRequest.method,\n headers: Object.assign({}, httpRequest.headers),\n credentials: httpRequest.withCredentials ? 'include' : undefined,\n };\n\n return Promise.resolve(requestModifier.modifyRequest(request))\n .then(() =>\n Object.assign(httpRequest, request, { withCredentials: request.credentials === 'include' })\n );\n}\n\nfunction RequestModifier() {\n\n let instance;\n\n function modifyRequestURL(url) {\n return url;\n }\n\n // eslint-disable-next-line no-unused-vars\n function modifyRequestHeader(request, { url }) {\n return request;\n }\n\n instance = {\n modifyRequest: null,\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\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 depending on URL\n * @param {Object} cfg - dependencies\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","// 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 */\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\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 scheduleController = rulesContext.getScheduleController();\n const isDynamic = streamInfo && streamInfo.manifestInfo && streamInfo.manifestInfo.isDynamic;\n const playbackController = scheduleController.getPlaybackController();\n\n\n // Don't ask for a bitrate change if there is not info about buffer state or if fragmentDuration is not defined\n const lowLatencyEnabled = playbackController.getLowLatencyModeEnabled();\n if (shouldIgnore(lowLatencyEnabled, 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(lowLatencyEnabled, mediaType) {\n return !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';\nimport Constants from '../../constants/Constants';\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(e) {\n // if we rebuffer, we don't want the placeholder buffer to artificially raise BOLA quality\n const mediaType = e.mediaType;\n // if audio buffer runs empty (due to track switch for example) then reset placeholder buffer only for audio (to avoid decrease video BOLA quality)\n const stateDict = mediaType === Constants.AUDIO ? [Constants.AUDIO] : bolaStateDict;\n for (const mediaType in stateDict) {\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 customParametersModel = config.customParametersModel;\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 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 = customParametersModel.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 */\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';\nimport { modifyRequest } from '../utils/RequestModifier';\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 if (requestModifier && requestModifier.modifyRequest) {\n modifyRequest(httpRequest, requestModifier)\n .then(() => request(httpRequest));\n }\n else {\n request(httpRequest);\n }\n }\n\n function request(httpRequest) {\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 && requestModifier.modifyRequestHeader) {\n xhr = requestModifier.modifyRequestHeader(xhr, {\n url: httpRequest.url\n });\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","'use strict'\n\nmodule.exports = require('./lib')\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 */\nimport UTCTiming from '../../dash/vo/UTCTiming';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Settings from '../../core/Settings';\nimport {checkParameterType} from '../utils/SupervisorTools';\nimport ABRRulesCollection from '../rules/abr/ABRRulesCollection';\nimport Constants from '../constants/Constants';\n\nconst DEFAULT_XHR_WITH_CREDENTIALS = false;\n\nfunction CustomParametersModel() {\n\n let instance,\n utcTimingSources,\n xhrWithCredentials,\n licenseRequestFilters,\n licenseResponseFilters,\n customCapabilitiesFilters,\n customInitialTrackSelectionFunction,\n customAbrRules;\n\n const context = this.context;\n const settings = Settings(context).getInstance();\n\n function setup() {\n xhrWithCredentials = {\n default: DEFAULT_XHR_WITH_CREDENTIALS\n };\n _resetInitialSettings();\n }\n\n function _resetInitialSettings() {\n licenseRequestFilters = [];\n licenseResponseFilters = [];\n customCapabilitiesFilters = [];\n customAbrRules = [];\n customInitialTrackSelectionFunction = null;\n utcTimingSources = [];\n }\n\n\n function reset() {\n _resetInitialSettings();\n }\n\n function setConfig() {\n\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 customInitialTrackSelectionFunction = customFunc;\n }\n\n /**\n * Resets the custom initial track selection\n */\n function resetCustomInitialTrackSelectionFunction() {\n customInitialTrackSelectionFunction = null;\n }\n\n /**\n * Returns the initial track selection function\n * @return {function}\n */\n function getCustomInitialTrackSelectionFunction() {\n return customInitialTrackSelectionFunction;\n }\n\n /**\n * Returns all license request filters\n * @return {array}\n */\n function getLicenseRequestFilters() {\n return licenseRequestFilters;\n }\n\n /**\n * Returns all license response filters\n * @return {array}\n */\n function getLicenseResponseFilters() {\n return licenseResponseFilters;\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 */\n function registerLicenseRequestFilter(filter) {\n licenseRequestFilters.push(filter);\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 */\n function registerLicenseResponseFilter(filter) {\n licenseResponseFilters.push(filter);\n }\n\n /**\n * Unregisters a license request filter.\n * @param {function} filter - the license request filter callback\n */\n function unregisterLicenseRequestFilter(filter) {\n _unregisterFilter(licenseRequestFilters, filter);\n }\n\n /**\n * Unregisters a license response filter.\n * @param {function} filter - the license response filter callback\n */\n function unregisterLicenseResponseFilter(filter) {\n _unregisterFilter(licenseResponseFilters, filter);\n }\n\n /**\n * Returns all custom capabilities filter\n * @return {array}\n */\n function getCustomCapabilitiesFilters() {\n return customCapabilitiesFilters;\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 */\n function registerCustomCapabilitiesFilter(filter) {\n customCapabilitiesFilters.push(filter);\n }\n\n /**\n * Unregisters a custom capabilities filter.\n * @param {function} filter - the custom capabilities filter callback\n */\n function unregisterCustomCapabilitiesFilter(filter) {\n _unregisterFilter(customCapabilitiesFilters, filter);\n }\n\n /**\n * Unregister a filter from the list of existing filers.\n * @param {array} filters\n * @param {function} filter\n * @private\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 * Iterate through the list of custom ABR rules and find the right rule by name\n * @param {string} rulename\n * @return {number} rule number\n */\n function _findAbrCustomRuleIndex(rulename) {\n let i;\n for (i = 0; i < customAbrRules.length; i++) {\n if (customAbrRules[i].rulename === rulename) {\n return i;\n }\n }\n return -1;\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 * @throws {@link Constants#BAD_ARGUMENT_ERROR BAD_ARGUMENT_ERROR} if called with invalid arguments.\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 customAbrRules.push({\n type: type,\n rulename: rulename,\n rule: rule\n });\n } else {\n // update rule\n customAbrRules[index].type = type;\n customAbrRules[index].rule = rule;\n }\n }\n\n /**\n * Remove a custom ABR Rule\n *\n * @param {string} rulename - name of the rule to be removed\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 customAbrRules.splice(index, 1);\n }\n } else {\n //if no rulename is defined, remove all ABR custome rules\n customAbrRules = [];\n }\n }\n\n /**\n * Remove all custom rules\n */\n function removeAllAbrCustomRule() {\n customAbrRules = [];\n }\n\n /**\n * Return all ABR custom rules\n * @return {array}\n */\n function getAbrCustomRules() {\n return customAbrRules;\n }\n\n\n /**\n * Add a UTC timing source at the top of the list\n * @param {string} schemeIdUri\n * @param {string} value\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 /**\n * Return all UTC timing sources\n * @return {array}\n */\n function getUTCTimingSources() {\n return utcTimingSources;\n }\n\n /**\n * Remove a specific timing source from the array\n * @param {string} schemeIdUri\n * @param {string} value\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 /**\n * Remove all timing sources\n */\n function clearDefaultUTCTimingSources() {\n utcTimingSources = [];\n }\n\n /**\n * Add the default timing source to the list\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 instance = {\n getCustomInitialTrackSelectionFunction,\n setCustomInitialTrackSelectionFunction,\n resetCustomInitialTrackSelectionFunction,\n getLicenseResponseFilters,\n getLicenseRequestFilters,\n getCustomCapabilitiesFilters,\n registerCustomCapabilitiesFilter,\n registerLicenseResponseFilter,\n registerLicenseRequestFilter,\n unregisterCustomCapabilitiesFilter,\n unregisterLicenseResponseFilter,\n unregisterLicenseRequestFilter,\n addAbrCustomRule,\n removeAllAbrCustomRule,\n removeAbrCustomRule,\n getAbrCustomRules,\n addUTCTimingSource,\n removeUTCTimingSource,\n getUTCTimingSources,\n clearDefaultUTCTimingSources,\n restoreDefaultUTCTimingSources,\n setXHRWithCredentialsForType,\n getXHRWithCredentialsForType,\n setConfig,\n reset\n };\n\n setup();\n\n return instance;\n}\n\nCustomParametersModel.__dashjs_factory_name = 'CustomParametersModel';\nexport default FactoryMaker.getSingletonFactory(CustomParametersModel);\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 */\n/**\n * @class\n * @ignore\n */\nclass ProducerReferenceTime {\n constructor() {\n this.id = null;\n this.inband = false;\n this.type = 'encoder';\n this.applicationScheme = null;\n this.wallClockTime = null;\n this.presentationTime = NaN;\n this.UTCTiming = null;\n }\n}\n\nexport default ProducerReferenceTime;\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 ContentSteering {\n constructor() {\n this.defaultServiceLocation = null;\n this.queryBeforeStart = false;\n this.proxyServerUrl = null;\n this.serverUrl = null;\n }\n}\n\nexport default ContentSteering;\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 ProducerReferenceTime from '../vo/ProducerReferenceTime';\nimport ContentSteering from '../vo/ContentSteering';\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 getProducerReferenceTimesForAdaptation(adaptation) {\n const prtArray = adaptation && adaptation.hasOwnProperty(DashConstants.PRODUCERREFERENCETIME_ASARRAY) ? adaptation[DashConstants.PRODUCERREFERENCETIME_ASARRAY] : [];\n\n // ProducerReferenceTime elements can also be contained in Representations\n const representationsArray = adaptation && adaptation.hasOwnProperty(DashConstants.REPRESENTATION_ASARRAY) ? adaptation[DashConstants.REPRESENTATION_ASARRAY] : [];\n\n representationsArray.forEach((rep) => {\n if (rep.hasOwnProperty(DashConstants.PRODUCERREFERENCETIME_ASARRAY)) {\n prtArray.push(...rep[DashConstants.PRODUCERREFERENCETIME_ASARRAY]);\n }\n });\n\n const prtsForAdaptation = [];\n\n // Unlikely to have multiple ProducerReferenceTimes.\n prtArray.forEach((prt) => {\n const entry = new ProducerReferenceTime();\n\n if (prt.hasOwnProperty(DashConstants.ID)) {\n entry[DashConstants.ID] = prt[DashConstants.ID];\n } else {\n // Ignore. Missing mandatory attribute\n return;\n }\n\n if (prt.hasOwnProperty(DashConstants.WALL_CLOCK_TIME)) {\n entry[DashConstants.WALL_CLOCK_TIME] = prt[DashConstants.WALL_CLOCK_TIME];\n } else {\n // Ignore. Missing mandatory attribute\n return;\n }\n\n if (prt.hasOwnProperty(DashConstants.PRESENTATION_TIME)) {\n entry[DashConstants.PRESENTATION_TIME] = prt[DashConstants.PRESENTATION_TIME];\n } else {\n // Ignore. Missing mandatory attribute\n return;\n }\n\n // Not interested in other attributes for now\n // UTC element contained must be same as that in the MPD\n prtsForAdaptation.push(entry);\n })\n\n return prtsForAdaptation;\n }\n\n function getLanguageForAdaptation(adaptation) {\n let lang = '';\n\n if (adaptation && adaptation.hasOwnProperty(DashConstants.LANG)) {\n lang = adaptation.lang;\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, period) {\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 eventStream.period = period;\n }\n\n return eventStreams;\n }\n\n function getEventStreamForAdaptationSet(manifest, adaptation, period) {\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, period);\n }\n\n function getEventStreamForRepresentation(manifest, representation, period) {\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, period);\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 getContentSteering(manifest) {\n if (manifest && manifest.hasOwnProperty(DashConstants.CONTENT_STEERING_AS_ARRAY)) {\n // Only one ContentSteering element is supported on MPD level\n const element = manifest[DashConstants.CONTENT_STEERING_AS_ARRAY][0];\n const entry = new ContentSteering();\n\n entry.serverUrl = element.__text;\n\n if (element.hasOwnProperty(DashConstants.DEFAULT_SERVICE_LOCATION)) {\n entry.defaultServiceLocation = element[DashConstants.DEFAULT_SERVICE_LOCATION];\n }\n\n if (element.hasOwnProperty(DashConstants.QUERY_BEFORE_START)) {\n entry.queryBeforeStart = element[DashConstants.QUERY_BEFORE_START].toLowerCase() === 'true';\n }\n\n if (element.hasOwnProperty(DashConstants.PROXY_SERVER_URL)) {\n entry.proxyServerUrl = element[DashConstants.PROXY_SERVER_URL];\n }\n\n return entry;\n }\n\n return undefined;\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 = null,\n schemeIdUri = null,\n latency = null,\n playbackRate = null,\n operatingQuality = null,\n operatingBandwidth = null;\n\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: parseInt(sd[prop].target),\n max: parseInt(sd[prop].max),\n min: parseInt(sd[prop].min),\n referenceId: parseInt(sd[prop].referenceId)\n };\n } else if (prop === DashConstants.SERVICE_DESCRIPTION_PLAYBACK_RATE) {\n playbackRate = {\n max: parseFloat(sd[prop].max),\n min: parseFloat(sd[prop].min)\n };\n } else if (prop === DashConstants.SERVICE_DESCRIPTION_OPERATING_QUALITY) {\n operatingQuality = {\n mediaType: sd[prop].mediaType,\n max: parseInt(sd[prop].max),\n min: parseInt(sd[prop].min),\n target: parseInt(sd[prop].target),\n type: sd[prop].type,\n maxQualityDifference: parseInt(sd[prop].maxQualityDifference)\n }\n } else if (prop === DashConstants.SERVICE_DESCRIPTION_OPERATING_BANDWIDTH) {\n operatingBandwidth = {\n mediaType: sd[prop].mediaType,\n max: parseInt(sd[prop].max),\n min: parseInt(sd[prop].min),\n target: parseInt(sd[prop].target)\n }\n }\n }\n }\n\n serviceDescriptions.push({\n id,\n schemeIdUri,\n latency,\n playbackRate,\n operatingQuality,\n operatingBandwidth\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 getProducerReferenceTimesForAdaptation,\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 getContentSteering,\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};","// .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","/////////////////////////////////////////////////////////////////////////////////\n/* UAParser.js v1.0.2\n Copyright © 2012-2021 Faisal Salman <f@faisalman.com>\n MIT License *//*\n Detect Browser, Engine, OS, CPU, and Device type/model from User-Agent data.\n Supports browser & node.js environment. \n Demo : https://faisalman.github.io/ua-parser-js\n Source : https://github.com/faisalman/ua-parser-js */\n/////////////////////////////////////////////////////////////////////////////////\n\n(function (window, undefined) {\n\n 'use strict';\n\n //////////////\n // Constants\n /////////////\n\n\n var LIBVERSION = '1.0.2',\n EMPTY = '',\n UNKNOWN = '?',\n FUNC_TYPE = 'function',\n UNDEF_TYPE = 'undefined',\n OBJ_TYPE = 'object',\n STR_TYPE = 'string',\n MAJOR = 'major',\n MODEL = 'model',\n NAME = 'name',\n TYPE = 'type',\n VENDOR = 'vendor',\n VERSION = 'version',\n ARCHITECTURE= 'architecture',\n CONSOLE = 'console',\n MOBILE = 'mobile',\n TABLET = 'tablet',\n SMARTTV = 'smarttv',\n WEARABLE = 'wearable',\n EMBEDDED = 'embedded',\n UA_MAX_LENGTH = 255;\n\n var AMAZON = 'Amazon',\n APPLE = 'Apple',\n ASUS = 'ASUS',\n BLACKBERRY = 'BlackBerry',\n BROWSER = 'Browser',\n CHROME = 'Chrome',\n EDGE = 'Edge',\n FIREFOX = 'Firefox',\n GOOGLE = 'Google',\n HUAWEI = 'Huawei',\n LG = 'LG',\n MICROSOFT = 'Microsoft',\n MOTOROLA = 'Motorola',\n OPERA = 'Opera',\n SAMSUNG = 'Samsung',\n SONY = 'Sony',\n XIAOMI = 'Xiaomi',\n ZEBRA = 'Zebra',\n FACEBOOK = 'Facebook';\n\n ///////////\n // Helper\n //////////\n\n var extend = function (regexes, extensions) {\n var mergedRegexes = {};\n for (var i in regexes) {\n if (extensions[i] && extensions[i].length % 2 === 0) {\n mergedRegexes[i] = extensions[i].concat(regexes[i]);\n } else {\n mergedRegexes[i] = regexes[i];\n }\n }\n return mergedRegexes;\n },\n enumerize = function (arr) {\n var enums = {};\n for (var i=0; i<arr.length; i++) {\n enums[arr[i].toUpperCase()] = arr[i];\n }\n return enums;\n },\n has = function (str1, str2) {\n return typeof str1 === STR_TYPE ? lowerize(str2).indexOf(lowerize(str1)) !== -1 : false;\n },\n lowerize = function (str) {\n return str.toLowerCase();\n },\n majorize = function (version) {\n return typeof(version) === STR_TYPE ? version.replace(/[^\\d\\.]/g, EMPTY).split('.')[0] : undefined;\n },\n trim = function (str, len) {\n if (typeof(str) === STR_TYPE) {\n str = str.replace(/^\\s\\s*/, EMPTY).replace(/\\s\\s*$/, EMPTY);\n return typeof(len) === UNDEF_TYPE ? str : str.substring(0, UA_MAX_LENGTH);\n }\n };\n\n ///////////////\n // Map helper\n //////////////\n\n var rgxMapper = function (ua, arrays) {\n\n var i = 0, j, k, p, q, matches, match;\n\n // loop through all regexes maps\n while (i < arrays.length && !matches) {\n\n var regex = arrays[i], // even sequence (0,2,4,..)\n props = arrays[i + 1]; // odd sequence (1,3,5,..)\n j = k = 0;\n\n // try matching uastring with regexes\n while (j < regex.length && !matches) {\n\n matches = regex[j++].exec(ua);\n\n if (!!matches) {\n for (p = 0; p < props.length; p++) {\n match = matches[++k];\n q = props[p];\n // check if given property is actually array\n if (typeof q === OBJ_TYPE && q.length > 0) {\n if (q.length === 2) {\n if (typeof q[1] == FUNC_TYPE) {\n // assign modified match\n this[q[0]] = q[1].call(this, match);\n } else {\n // assign given value, ignore regex match\n this[q[0]] = q[1];\n }\n } else if (q.length === 3) {\n // check whether function or regex\n if (typeof q[1] === FUNC_TYPE && !(q[1].exec && q[1].test)) {\n // call function (usually string mapper)\n this[q[0]] = match ? q[1].call(this, match, q[2]) : undefined;\n } else {\n // sanitize match using given regex\n this[q[0]] = match ? match.replace(q[1], q[2]) : undefined;\n }\n } else if (q.length === 4) {\n this[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined;\n }\n } else {\n this[q] = match ? match : undefined;\n }\n }\n }\n }\n i += 2;\n }\n },\n\n strMapper = function (str, map) {\n\n for (var i in map) {\n // check if current value is array\n if (typeof map[i] === OBJ_TYPE && map[i].length > 0) {\n for (var j = 0; j < map[i].length; j++) {\n if (has(map[i][j], str)) {\n return (i === UNKNOWN) ? undefined : i;\n }\n }\n } else if (has(map[i], str)) {\n return (i === UNKNOWN) ? undefined : i;\n }\n }\n return str;\n };\n\n ///////////////\n // String map\n //////////////\n\n // Safari < 3.0\n var oldSafariMap = {\n '1.0' : '/8',\n '1.2' : '/1',\n '1.3' : '/3',\n '2.0' : '/412',\n '2.0.2' : '/416',\n '2.0.3' : '/417',\n '2.0.4' : '/419',\n '?' : '/'\n },\n windowsVersionMap = {\n 'ME' : '4.90',\n 'NT 3.11' : 'NT3.51',\n 'NT 4.0' : 'NT4.0',\n '2000' : 'NT 5.0',\n 'XP' : ['NT 5.1', 'NT 5.2'],\n 'Vista' : 'NT 6.0',\n '7' : 'NT 6.1',\n '8' : 'NT 6.2',\n '8.1' : 'NT 6.3',\n '10' : ['NT 6.4', 'NT 10.0'],\n 'RT' : 'ARM'\n };\n\n //////////////\n // Regex map\n /////////////\n\n var regexes = {\n\n browser : [[\n\n /\\b(?:crmo|crios)\\/([\\w\\.]+)/i // Chrome for Android/iOS\n ], [VERSION, [NAME, 'Chrome']], [\n /edg(?:e|ios|a)?\\/([\\w\\.]+)/i // Microsoft Edge\n ], [VERSION, [NAME, 'Edge']], [\n\n // Presto based\n /(opera mini)\\/([-\\w\\.]+)/i, // Opera Mini\n /(opera [mobiletab]{3,6})\\b.+version\\/([-\\w\\.]+)/i, // Opera Mobi/Tablet\n /(opera)(?:.+version\\/|[\\/ ]+)([\\w\\.]+)/i // Opera\n ], [NAME, VERSION], [\n /opios[\\/ ]+([\\w\\.]+)/i // Opera mini on iphone >= 8.0\n ], [VERSION, [NAME, OPERA+' Mini']], [\n /\\bopr\\/([\\w\\.]+)/i // Opera Webkit\n ], [VERSION, [NAME, OPERA]], [\n\n // Mixed\n /(kindle)\\/([\\w\\.]+)/i, // Kindle\n /(lunascape|maxthon|netfront|jasmine|blazer)[\\/ ]?([\\w\\.]*)/i, // Lunascape/Maxthon/Netfront/Jasmine/Blazer\n // Trident based\n /(avant |iemobile|slim)(?:browser)?[\\/ ]?([\\w\\.]*)/i, // Avant/IEMobile/SlimBrowser\n /(ba?idubrowser)[\\/ ]?([\\w\\.]+)/i, // Baidu Browser\n /(?:ms|\\()(ie) ([\\w\\.]+)/i, // Internet Explorer\n\n // Webkit/KHTML based // Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron/Iridium/PhantomJS/Bowser/QupZilla/Falkon\n /(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale|qqbrowserlite|qq)\\/([-\\w\\.]+)/i,\n // Rekonq/Puffin/Brave/Whale/QQBrowserLite/QQ, aka ShouQ\n /(weibo)__([\\d\\.]+)/i // Weibo\n ], [NAME, VERSION], [\n /(?:\\buc? ?browser|(?:juc.+)ucweb)[\\/ ]?([\\w\\.]+)/i // UCBrowser\n ], [VERSION, [NAME, 'UC'+BROWSER]], [\n /\\bqbcore\\/([\\w\\.]+)/i // WeChat Desktop for Windows Built-in Browser\n ], [VERSION, [NAME, 'WeChat(Win) Desktop']], [\n /micromessenger\\/([\\w\\.]+)/i // WeChat\n ], [VERSION, [NAME, 'WeChat']], [\n /konqueror\\/([\\w\\.]+)/i // Konqueror\n ], [VERSION, [NAME, 'Konqueror']], [\n /trident.+rv[: ]([\\w\\.]{1,9})\\b.+like gecko/i // IE11\n ], [VERSION, [NAME, 'IE']], [\n /yabrowser\\/([\\w\\.]+)/i // Yandex\n ], [VERSION, [NAME, 'Yandex']], [\n /(avast|avg)\\/([\\w\\.]+)/i // Avast/AVG Secure Browser\n ], [[NAME, /(.+)/, '$1 Secure '+BROWSER], VERSION], [\n /\\bfocus\\/([\\w\\.]+)/i // Firefox Focus\n ], [VERSION, [NAME, FIREFOX+' Focus']], [\n /\\bopt\\/([\\w\\.]+)/i // Opera Touch\n ], [VERSION, [NAME, OPERA+' Touch']], [\n /coc_coc\\w+\\/([\\w\\.]+)/i // Coc Coc Browser\n ], [VERSION, [NAME, 'Coc Coc']], [\n /dolfin\\/([\\w\\.]+)/i // Dolphin\n ], [VERSION, [NAME, 'Dolphin']], [\n /coast\\/([\\w\\.]+)/i // Opera Coast\n ], [VERSION, [NAME, OPERA+' Coast']], [\n /miuibrowser\\/([\\w\\.]+)/i // MIUI Browser\n ], [VERSION, [NAME, 'MIUI '+BROWSER]], [\n /fxios\\/([-\\w\\.]+)/i // Firefox for iOS\n ], [VERSION, [NAME, FIREFOX]], [\n /\\bqihu|(qi?ho?o?|360)browser/i // 360\n ], [[NAME, '360 '+BROWSER]], [\n /(oculus|samsung|sailfish)browser\\/([\\w\\.]+)/i\n ], [[NAME, /(.+)/, '$1 '+BROWSER], VERSION], [ // Oculus/Samsung/Sailfish Browser\n /(comodo_dragon)\\/([\\w\\.]+)/i // Comodo Dragon\n ], [[NAME, /_/g, ' '], VERSION], [\n /(electron)\\/([\\w\\.]+) safari/i, // Electron-based App\n /(tesla)(?: qtcarbrowser|\\/(20\\d\\d\\.[-\\w\\.]+))/i, // Tesla\n /m?(qqbrowser|baiduboxapp|2345Explorer)[\\/ ]?([\\w\\.]+)/i // QQBrowser/Baidu App/2345 Browser\n ], [NAME, VERSION], [\n /(metasr)[\\/ ]?([\\w\\.]+)/i, // SouGouBrowser\n /(lbbrowser)/i // LieBao Browser\n ], [NAME], [\n\n // WebView\n /((?:fban\\/fbios|fb_iab\\/fb4a)(?!.+fbav)|;fbav\\/([\\w\\.]+);)/i // Facebook App for iOS & Android\n ], [[NAME, FACEBOOK], VERSION], [\n /safari (line)\\/([\\w\\.]+)/i, // Line App for iOS\n /\\b(line)\\/([\\w\\.]+)\\/iab/i, // Line App for Android\n /(chromium|instagram)[\\/ ]([-\\w\\.]+)/i // Chromium/Instagram\n ], [NAME, VERSION], [\n /\\bgsa\\/([\\w\\.]+) .*safari\\//i // Google Search Appliance on iOS\n ], [VERSION, [NAME, 'GSA']], [\n\n /headlesschrome(?:\\/([\\w\\.]+)| )/i // Chrome Headless\n ], [VERSION, [NAME, CHROME+' Headless']], [\n\n / wv\\).+(chrome)\\/([\\w\\.]+)/i // Chrome WebView\n ], [[NAME, CHROME+' WebView'], VERSION], [\n\n /droid.+ version\\/([\\w\\.]+)\\b.+(?:mobile safari|safari)/i // Android Browser\n ], [VERSION, [NAME, 'Android '+BROWSER]], [\n\n /(chrome|omniweb|arora|[tizenoka]{5} ?browser)\\/v?([\\w\\.]+)/i // Chrome/OmniWeb/Arora/Tizen/Nokia\n ], [NAME, VERSION], [\n\n /version\\/([\\w\\.]+) .*mobile\\/\\w+ (safari)/i // Mobile Safari\n ], [VERSION, [NAME, 'Mobile Safari']], [\n /version\\/([\\w\\.]+) .*(mobile ?safari|safari)/i // Safari & Safari Mobile\n ], [VERSION, NAME], [\n /webkit.+?(mobile ?safari|safari)(\\/[\\w\\.]+)/i // Safari < 3.0\n ], [NAME, [VERSION, strMapper, oldSafariMap]], [\n\n /(webkit|khtml)\\/([\\w\\.]+)/i\n ], [NAME, VERSION], [\n\n // Gecko based\n /(navigator|netscape\\d?)\\/([-\\w\\.]+)/i // Netscape\n ], [[NAME, 'Netscape'], VERSION], [\n /mobile vr; rv:([\\w\\.]+)\\).+firefox/i // Firefox Reality\n ], [VERSION, [NAME, FIREFOX+' Reality']], [\n /ekiohf.+(flow)\\/([\\w\\.]+)/i, // Flow\n /(swiftfox)/i, // Swiftfox\n /(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\\/ ]?([\\w\\.\\+]+)/i,\n // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror/Klar\n /(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\\/([-\\w\\.]+)$/i,\n // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix\n /(firefox)\\/([\\w\\.]+)/i, // Other Firefox-based\n /(mozilla)\\/([\\w\\.]+) .+rv\\:.+gecko\\/\\d+/i, // Mozilla\n\n // Other\n /(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\\. ]?browser)[-\\/ ]?v?([\\w\\.]+)/i,\n // Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/Sleipnir/Obigo/Mosaic/Go/ICE/UP.Browser\n /(links) \\(([\\w\\.]+)/i // Links\n ], [NAME, VERSION]\n ],\n\n cpu : [[\n\n /(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\\)]/i // AMD64 (x64)\n ], [[ARCHITECTURE, 'amd64']], [\n\n /(ia32(?=;))/i // IA32 (quicktime)\n ], [[ARCHITECTURE, lowerize]], [\n\n /((?:i[346]|x)86)[;\\)]/i // IA32 (x86)\n ], [[ARCHITECTURE, 'ia32']], [\n\n /\\b(aarch64|arm(v?8e?l?|_?64))\\b/i // ARM64\n ], [[ARCHITECTURE, 'arm64']], [\n\n /\\b(arm(?:v[67])?ht?n?[fl]p?)\\b/i // ARMHF\n ], [[ARCHITECTURE, 'armhf']], [\n\n // PocketPC mistakenly identified as PowerPC\n /windows (ce|mobile); ppc;/i\n ], [[ARCHITECTURE, 'arm']], [\n\n /((?:ppc|powerpc)(?:64)?)(?: mac|;|\\))/i // PowerPC\n ], [[ARCHITECTURE, /ower/, EMPTY, lowerize]], [\n\n /(sun4\\w)[;\\)]/i // SPARC\n ], [[ARCHITECTURE, 'sparc']], [\n\n /((?:avr32|ia64(?=;))|68k(?=\\))|\\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\\b|pa-risc)/i\n // IA64, 68K, ARM/64, AVR/32, IRIX/64, MIPS/64, SPARC/64, PA-RISC\n ], [[ARCHITECTURE, lowerize]]\n ],\n\n device : [[\n\n //////////////////////////\n // MOBILES & TABLETS\n // Ordered by popularity\n /////////////////////////\n\n // Samsung\n /\\b(sch-i[89]0\\d|shw-m380s|sm-[pt]\\w{2,4}|gt-[pn]\\d{2,4}|sgh-t8[56]9|nexus 10)/i\n ], [MODEL, [VENDOR, SAMSUNG], [TYPE, TABLET]], [\n /\\b((?:s[cgp]h|gt|sm)-\\w+|galaxy nexus)/i,\n /samsung[- ]([-\\w]+)/i,\n /sec-(sgh\\w+)/i\n ], [MODEL, [VENDOR, SAMSUNG], [TYPE, MOBILE]], [\n\n // Apple\n /\\((ip(?:hone|od)[\\w ]*);/i // iPod/iPhone\n ], [MODEL, [VENDOR, APPLE], [TYPE, MOBILE]], [\n /\\((ipad);[-\\w\\),; ]+apple/i, // iPad\n /applecoremedia\\/[\\w\\.]+ \\((ipad)/i,\n /\\b(ipad)\\d\\d?,\\d\\d?[;\\]].+ios/i\n ], [MODEL, [VENDOR, APPLE], [TYPE, TABLET]], [\n\n // Huawei\n /\\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\\d{2})\\b(?!.+d\\/s)/i\n ], [MODEL, [VENDOR, HUAWEI], [TYPE, TABLET]], [\n /(?:huawei|honor)([-\\w ]+)[;\\)]/i,\n /\\b(nexus 6p|\\w{2,4}-[atu]?[ln][01259x][012359][an]?)\\b(?!.+d\\/s)/i\n ], [MODEL, [VENDOR, HUAWEI], [TYPE, MOBILE]], [\n\n // Xiaomi\n /\\b(poco[\\w ]+)(?: bui|\\))/i, // Xiaomi POCO\n /\\b; (\\w+) build\\/hm\\1/i, // Xiaomi Hongmi 'numeric' models\n /\\b(hm[-_ ]?note?[_ ]?(?:\\d\\w)?) bui/i, // Xiaomi Hongmi\n /\\b(redmi[\\-_ ]?(?:note|k)?[\\w_ ]+)(?: bui|\\))/i, // Xiaomi Redmi\n /\\b(mi[-_ ]?(?:a\\d|one|one[_ ]plus|note lte|max)?[_ ]?(?:\\d?\\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\\))/i // Xiaomi Mi\n ], [[MODEL, /_/g, ' '], [VENDOR, XIAOMI], [TYPE, MOBILE]], [\n /\\b(mi[-_ ]?(?:pad)(?:[\\w_ ]+))(?: bui|\\))/i // Mi Pad tablets\n ],[[MODEL, /_/g, ' '], [VENDOR, XIAOMI], [TYPE, TABLET]], [\n\n // OPPO\n /; (\\w+) bui.+ oppo/i,\n /\\b(cph[12]\\d{3}|p(?:af|c[al]|d\\w|e[ar])[mt]\\d0|x9007|a101op)\\b/i\n ], [MODEL, [VENDOR, 'OPPO'], [TYPE, MOBILE]], [\n\n // Vivo\n /vivo (\\w+)(?: bui|\\))/i,\n /\\b(v[12]\\d{3}\\w?[at])(?: bui|;)/i\n ], [MODEL, [VENDOR, 'Vivo'], [TYPE, MOBILE]], [\n\n // Realme\n /\\b(rmx[12]\\d{3})(?: bui|;|\\))/i\n ], [MODEL, [VENDOR, 'Realme'], [TYPE, MOBILE]], [\n\n // Motorola\n /\\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\\b[\\w ]+build\\//i,\n /\\bmot(?:orola)?[- ](\\w*)/i,\n /((?:moto[\\w\\(\\) ]+|xt\\d{3,4}|nexus 6)(?= bui|\\)))/i\n ], [MODEL, [VENDOR, MOTOROLA], [TYPE, MOBILE]], [\n /\\b(mz60\\d|xoom[2 ]{0,2}) build\\//i\n ], [MODEL, [VENDOR, MOTOROLA], [TYPE, TABLET]], [\n\n // LG\n /((?=lg)?[vl]k\\-?\\d{3}) bui| 3\\.[-\\w; ]{10}lg?-([06cv9]{3,4})/i\n ], [MODEL, [VENDOR, LG], [TYPE, TABLET]], [\n /(lm(?:-?f100[nv]?|-[\\w\\.]+)(?= bui|\\))|nexus [45])/i,\n /\\blg[-e;\\/ ]+((?!browser|netcast|android tv)\\w+)/i,\n /\\blg-?([\\d\\w]+) bui/i\n ], [MODEL, [VENDOR, LG], [TYPE, MOBILE]], [\n\n // Lenovo\n /(ideatab[-\\w ]+)/i,\n /lenovo ?(s[56]000[-\\w]+|tab(?:[\\w ]+)|yt[-\\d\\w]{6}|tb[-\\d\\w]{6})/i\n ], [MODEL, [VENDOR, 'Lenovo'], [TYPE, TABLET]], [\n\n // Nokia\n /(?:maemo|nokia).*(n900|lumia \\d+)/i,\n /nokia[-_ ]?([-\\w\\.]*)/i\n ], [[MODEL, /_/g, ' '], [VENDOR, 'Nokia'], [TYPE, MOBILE]], [\n\n // Google\n /(pixel c)\\b/i // Google Pixel C\n ], [MODEL, [VENDOR, GOOGLE], [TYPE, TABLET]], [\n /droid.+; (pixel[\\daxl ]{0,6})(?: bui|\\))/i // Google Pixel\n ], [MODEL, [VENDOR, GOOGLE], [TYPE, MOBILE]], [\n\n // Sony\n /droid.+ ([c-g]\\d{4}|so[-gl]\\w+|xq-a\\w[4-7][12])(?= bui|\\).+chrome\\/(?![1-6]{0,1}\\d\\.))/i\n ], [MODEL, [VENDOR, SONY], [TYPE, MOBILE]], [\n /sony tablet [ps]/i,\n /\\b(?:sony)?sgp\\w+(?: bui|\\))/i\n ], [[MODEL, 'Xperia Tablet'], [VENDOR, SONY], [TYPE, TABLET]], [\n\n // OnePlus\n / (kb2005|in20[12]5|be20[12][59])\\b/i,\n /(?:one)?(?:plus)? (a\\d0\\d\\d)(?: b|\\))/i\n ], [MODEL, [VENDOR, 'OnePlus'], [TYPE, MOBILE]], [\n\n // Amazon\n /(alexa)webm/i,\n /(kf[a-z]{2}wi)( bui|\\))/i, // Kindle Fire without Silk\n /(kf[a-z]+)( bui|\\)).+silk\\//i // Kindle Fire HD\n ], [MODEL, [VENDOR, AMAZON], [TYPE, TABLET]], [\n /((?:sd|kf)[0349hijorstuw]+)( bui|\\)).+silk\\//i // Fire Phone\n ], [[MODEL, /(.+)/g, 'Fire Phone $1'], [VENDOR, AMAZON], [TYPE, MOBILE]], [\n\n // BlackBerry\n /(playbook);[-\\w\\),; ]+(rim)/i // BlackBerry PlayBook\n ], [MODEL, VENDOR, [TYPE, TABLET]], [\n /\\b((?:bb[a-f]|st[hv])100-\\d)/i,\n /\\(bb10; (\\w+)/i // BlackBerry 10\n ], [MODEL, [VENDOR, BLACKBERRY], [TYPE, MOBILE]], [\n\n // Asus\n /(?:\\b|asus_)(transfo[prime ]{4,10} \\w+|eeepc|slider \\w+|nexus 7|padfone|p00[cj])/i\n ], [MODEL, [VENDOR, ASUS], [TYPE, TABLET]], [\n / (z[bes]6[027][012][km][ls]|zenfone \\d\\w?)\\b/i\n ], [MODEL, [VENDOR, ASUS], [TYPE, MOBILE]], [\n\n // HTC\n /(nexus 9)/i // HTC Nexus 9\n ], [MODEL, [VENDOR, 'HTC'], [TYPE, TABLET]], [\n /(htc)[-;_ ]{1,2}([\\w ]+(?=\\)| bui)|\\w+)/i, // HTC\n\n // ZTE\n /(zte)[- ]([\\w ]+?)(?: bui|\\/|\\))/i,\n /(alcatel|geeksphone|nexian|panasonic|sony)[-_ ]?([-\\w]*)/i // Alcatel/GeeksPhone/Nexian/Panasonic/Sony\n ], [VENDOR, [MODEL, /_/g, ' '], [TYPE, MOBILE]], [\n\n // Acer\n /droid.+; ([ab][1-7]-?[0178a]\\d\\d?)/i\n ], [MODEL, [VENDOR, 'Acer'], [TYPE, TABLET]], [\n\n // Meizu\n /droid.+; (m[1-5] note) bui/i,\n /\\bmz-([-\\w]{2,})/i\n ], [MODEL, [VENDOR, 'Meizu'], [TYPE, MOBILE]], [\n\n // Sharp\n /\\b(sh-?[altvz]?\\d\\d[a-ekm]?)/i\n ], [MODEL, [VENDOR, 'Sharp'], [TYPE, MOBILE]], [\n\n // MIXED\n /(blackberry|benq|palm(?=\\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\\w]*)/i,\n // BlackBerry/BenQ/Palm/Sony-Ericsson/Acer/Asus/Dell/Meizu/Motorola/Polytron\n /(hp) ([\\w ]+\\w)/i, // HP iPAQ\n /(asus)-?(\\w+)/i, // Asus\n /(microsoft); (lumia[\\w ]+)/i, // Microsoft Lumia\n /(lenovo)[-_ ]?([-\\w]+)/i, // Lenovo\n /(jolla)/i, // Jolla\n /(oppo) ?([\\w ]+) bui/i // OPPO\n ], [VENDOR, MODEL, [TYPE, MOBILE]], [\n\n /(archos) (gamepad2?)/i, // Archos\n /(hp).+(touchpad(?!.+tablet)|tablet)/i, // HP TouchPad\n /(kindle)\\/([\\w\\.]+)/i, // Kindle\n /(nook)[\\w ]+build\\/(\\w+)/i, // Nook\n /(dell) (strea[kpr\\d ]*[\\dko])/i, // Dell Streak\n /(le[- ]+pan)[- ]+(\\w{1,9}) bui/i, // Le Pan Tablets\n /(trinity)[- ]*(t\\d{3}) bui/i, // Trinity Tablets\n /(gigaset)[- ]+(q\\w{1,9}) bui/i, // Gigaset Tablets\n /(vodafone) ([\\w ]+)(?:\\)| bui)/i // Vodafone\n ], [VENDOR, MODEL, [TYPE, TABLET]], [\n\n /(surface duo)/i // Surface Duo\n ], [MODEL, [VENDOR, MICROSOFT], [TYPE, TABLET]], [\n /droid [\\d\\.]+; (fp\\du?)(?: b|\\))/i // Fairphone\n ], [MODEL, [VENDOR, 'Fairphone'], [TYPE, MOBILE]], [\n /(u304aa)/i // AT&T\n ], [MODEL, [VENDOR, 'AT&T'], [TYPE, MOBILE]], [\n /\\bsie-(\\w*)/i // Siemens\n ], [MODEL, [VENDOR, 'Siemens'], [TYPE, MOBILE]], [\n /\\b(rct\\w+) b/i // RCA Tablets\n ], [MODEL, [VENDOR, 'RCA'], [TYPE, TABLET]], [\n /\\b(venue[\\d ]{2,7}) b/i // Dell Venue Tablets\n ], [MODEL, [VENDOR, 'Dell'], [TYPE, TABLET]], [\n /\\b(q(?:mv|ta)\\w+) b/i // Verizon Tablet\n ], [MODEL, [VENDOR, 'Verizon'], [TYPE, TABLET]], [\n /\\b(?:barnes[& ]+noble |bn[rt])([\\w\\+ ]*) b/i // Barnes & Noble Tablet\n ], [MODEL, [VENDOR, 'Barnes & Noble'], [TYPE, TABLET]], [\n /\\b(tm\\d{3}\\w+) b/i\n ], [MODEL, [VENDOR, 'NuVision'], [TYPE, TABLET]], [\n /\\b(k88) b/i // ZTE K Series Tablet\n ], [MODEL, [VENDOR, 'ZTE'], [TYPE, TABLET]], [\n /\\b(nx\\d{3}j) b/i // ZTE Nubia\n ], [MODEL, [VENDOR, 'ZTE'], [TYPE, MOBILE]], [\n /\\b(gen\\d{3}) b.+49h/i // Swiss GEN Mobile\n ], [MODEL, [VENDOR, 'Swiss'], [TYPE, MOBILE]], [\n /\\b(zur\\d{3}) b/i // Swiss ZUR Tablet\n ], [MODEL, [VENDOR, 'Swiss'], [TYPE, TABLET]], [\n /\\b((zeki)?tb.*\\b) b/i // Zeki Tablets\n ], [MODEL, [VENDOR, 'Zeki'], [TYPE, TABLET]], [\n /\\b([yr]\\d{2}) b/i,\n /\\b(dragon[- ]+touch |dt)(\\w{5}) b/i // Dragon Touch Tablet\n ], [[VENDOR, 'Dragon Touch'], MODEL, [TYPE, TABLET]], [\n /\\b(ns-?\\w{0,9}) b/i // Insignia Tablets\n ], [MODEL, [VENDOR, 'Insignia'], [TYPE, TABLET]], [\n /\\b((nxa|next)-?\\w{0,9}) b/i // NextBook Tablets\n ], [MODEL, [VENDOR, 'NextBook'], [TYPE, TABLET]], [\n /\\b(xtreme\\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i // Voice Xtreme Phones\n ], [[VENDOR, 'Voice'], MODEL, [TYPE, MOBILE]], [\n /\\b(lvtel\\-)?(v1[12]) b/i // LvTel Phones\n ], [[VENDOR, 'LvTel'], MODEL, [TYPE, MOBILE]], [\n /\\b(ph-1) /i // Essential PH-1\n ], [MODEL, [VENDOR, 'Essential'], [TYPE, MOBILE]], [\n /\\b(v(100md|700na|7011|917g).*\\b) b/i // Envizen Tablets\n ], [MODEL, [VENDOR, 'Envizen'], [TYPE, TABLET]], [\n /\\b(trio[-\\w\\. ]+) b/i // MachSpeed Tablets\n ], [MODEL, [VENDOR, 'MachSpeed'], [TYPE, TABLET]], [\n /\\btu_(1491) b/i // Rotor Tablets\n ], [MODEL, [VENDOR, 'Rotor'], [TYPE, TABLET]], [\n /(shield[\\w ]+) b/i // Nvidia Shield Tablets\n ], [MODEL, [VENDOR, 'Nvidia'], [TYPE, TABLET]], [\n /(sprint) (\\w+)/i // Sprint Phones\n ], [VENDOR, MODEL, [TYPE, MOBILE]], [\n /(kin\\.[onetw]{3})/i // Microsoft Kin\n ], [[MODEL, /\\./g, ' '], [VENDOR, MICROSOFT], [TYPE, MOBILE]], [\n /droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\\)/i // Zebra\n ], [MODEL, [VENDOR, ZEBRA], [TYPE, TABLET]], [\n /droid.+; (ec30|ps20|tc[2-8]\\d[kx])\\)/i\n ], [MODEL, [VENDOR, ZEBRA], [TYPE, MOBILE]], [\n\n ///////////////////\n // CONSOLES\n ///////////////////\n\n /(ouya)/i, // Ouya\n /(nintendo) ([wids3utch]+)/i // Nintendo\n ], [VENDOR, MODEL, [TYPE, CONSOLE]], [\n /droid.+; (shield) bui/i // Nvidia\n ], [MODEL, [VENDOR, 'Nvidia'], [TYPE, CONSOLE]], [\n /(playstation [345portablevi]+)/i // Playstation\n ], [MODEL, [VENDOR, SONY], [TYPE, CONSOLE]], [\n /\\b(xbox(?: one)?(?!; xbox))[\\); ]/i // Microsoft Xbox\n ], [MODEL, [VENDOR, MICROSOFT], [TYPE, CONSOLE]], [\n\n ///////////////////\n // SMARTTVS\n ///////////////////\n\n /smart-tv.+(samsung)/i // Samsung\n ], [VENDOR, [TYPE, SMARTTV]], [\n /hbbtv.+maple;(\\d+)/i\n ], [[MODEL, /^/, 'SmartTV'], [VENDOR, SAMSUNG], [TYPE, SMARTTV]], [\n /(nux; netcast.+smarttv|lg (netcast\\.tv-201\\d|android tv))/i // LG SmartTV\n ], [[VENDOR, LG], [TYPE, SMARTTV]], [\n /(apple) ?tv/i // Apple TV\n ], [VENDOR, [MODEL, APPLE+' TV'], [TYPE, SMARTTV]], [\n /crkey/i // Google Chromecast\n ], [[MODEL, CHROME+'cast'], [VENDOR, GOOGLE], [TYPE, SMARTTV]], [\n /droid.+aft(\\w)( bui|\\))/i // Fire TV\n ], [MODEL, [VENDOR, AMAZON], [TYPE, SMARTTV]], [\n /\\(dtv[\\);].+(aquos)/i // Sharp\n ], [MODEL, [VENDOR, 'Sharp'], [TYPE, SMARTTV]], [\n /\\b(roku)[\\dx]*[\\)\\/]((?:dvp-)?[\\d\\.]*)/i, // Roku\n /hbbtv\\/\\d+\\.\\d+\\.\\d+ +\\([\\w ]*; *(\\w[^;]*);([^;]*)/i // HbbTV devices\n ], [[VENDOR, trim], [MODEL, trim], [TYPE, SMARTTV]], [\n /\\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\\b/i // SmartTV from Unidentified Vendors\n ], [[TYPE, SMARTTV]], [\n\n ///////////////////\n // WEARABLES\n ///////////////////\n\n /((pebble))app/i // Pebble\n ], [VENDOR, MODEL, [TYPE, WEARABLE]], [\n /droid.+; (glass) \\d/i // Google Glass\n ], [MODEL, [VENDOR, GOOGLE], [TYPE, WEARABLE]], [\n /droid.+; (wt63?0{2,3})\\)/i\n ], [MODEL, [VENDOR, ZEBRA], [TYPE, WEARABLE]], [\n /(quest( 2)?)/i // Oculus Quest\n ], [MODEL, [VENDOR, FACEBOOK], [TYPE, WEARABLE]], [\n\n ///////////////////\n // EMBEDDED\n ///////////////////\n\n /(tesla)(?: qtcarbrowser|\\/[-\\w\\.]+)/i // Tesla\n ], [VENDOR, [TYPE, EMBEDDED]], [\n\n ////////////////////\n // MIXED (GENERIC)\n ///////////////////\n\n /droid .+?; ([^;]+?)(?: bui|\\) applew).+? mobile safari/i // Android Phones from Unidentified Vendors\n ], [MODEL, [TYPE, MOBILE]], [\n /droid .+?; ([^;]+?)(?: bui|\\) applew).+?(?! mobile) safari/i // Android Tablets from Unidentified Vendors\n ], [MODEL, [TYPE, TABLET]], [\n /\\b((tablet|tab)[;\\/]|focus\\/\\d(?!.+mobile))/i // Unidentifiable Tablet\n ], [[TYPE, TABLET]], [\n /(phone|mobile(?:[;\\/]| safari)|pda(?=.+windows ce))/i // Unidentifiable Mobile\n ], [[TYPE, MOBILE]], [\n /(android[-\\w\\. ]{0,9});.+buil/i // Generic Android Device\n ], [MODEL, [VENDOR, 'Generic']]\n ],\n\n engine : [[\n\n /windows.+ edge\\/([\\w\\.]+)/i // EdgeHTML\n ], [VERSION, [NAME, EDGE+'HTML']], [\n\n /webkit\\/537\\.36.+chrome\\/(?!27)([\\w\\.]+)/i // Blink\n ], [VERSION, [NAME, 'Blink']], [\n\n /(presto)\\/([\\w\\.]+)/i, // Presto\n /(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\\/([\\w\\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m/Goanna\n /ekioh(flow)\\/([\\w\\.]+)/i, // Flow\n /(khtml|tasman|links)[\\/ ]\\(?([\\w\\.]+)/i, // KHTML/Tasman/Links\n /(icab)[\\/ ]([23]\\.[\\d\\.]+)/i // iCab\n ], [NAME, VERSION], [\n\n /rv\\:([\\w\\.]{1,9})\\b.+(gecko)/i // Gecko\n ], [VERSION, NAME]\n ],\n\n os : [[\n\n // Windows\n /microsoft (windows) (vista|xp)/i // Windows (iTunes)\n ], [NAME, VERSION], [\n /(windows) nt 6\\.2; (arm)/i, // Windows RT\n /(windows (?:phone(?: os)?|mobile))[\\/ ]?([\\d\\.\\w ]*)/i, // Windows Phone\n /(windows)[\\/ ]?([ntce\\d\\. ]+\\w)(?!.+xbox)/i\n ], [NAME, [VERSION, strMapper, windowsVersionMap]], [\n /(win(?=3|9|n)|win 9x )([nt\\d\\.]+)/i\n ], [[NAME, 'Windows'], [VERSION, strMapper, windowsVersionMap]], [\n\n // iOS/macOS\n /ip[honead]{2,4}\\b(?:.*os ([\\w]+) like mac|; opera)/i, // iOS\n /cfnetwork\\/.+darwin/i\n ], [[VERSION, /_/g, '.'], [NAME, 'iOS']], [\n /(mac os x) ?([\\w\\. ]*)/i,\n /(macintosh|mac_powerpc\\b)(?!.+haiku)/i // Mac OS\n ], [[NAME, 'Mac OS'], [VERSION, /_/g, '.']], [\n\n // Mobile OSes\n /droid ([\\w\\.]+)\\b.+(android[- ]x86)/i // Android-x86\n ], [VERSION, NAME], [ // Android/WebOS/QNX/Bada/RIM/Maemo/MeeGo/Sailfish OS\n /(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\\/ ]?([\\w\\.]*)/i,\n /(blackberry)\\w*\\/([\\w\\.]*)/i, // Blackberry\n /(tizen|kaios)[\\/ ]([\\w\\.]+)/i, // Tizen/KaiOS\n /\\((series40);/i // Series 40\n ], [NAME, VERSION], [\n /\\(bb(10);/i // BlackBerry 10\n ], [VERSION, [NAME, BLACKBERRY]], [\n /(?:symbian ?os|symbos|s60(?=;)|series60)[-\\/ ]?([\\w\\.]*)/i // Symbian\n ], [VERSION, [NAME, 'Symbian']], [\n /mozilla\\/[\\d\\.]+ \\((?:mobile|tablet|tv|mobile; [\\w ]+); rv:.+ gecko\\/([\\w\\.]+)/i // Firefox OS\n ], [VERSION, [NAME, FIREFOX+' OS']], [\n /web0s;.+rt(tv)/i,\n /\\b(?:hp)?wos(?:browser)?\\/([\\w\\.]+)/i // WebOS\n ], [VERSION, [NAME, 'webOS']], [\n\n // Google Chromecast\n /crkey\\/([\\d\\.]+)/i // Google Chromecast\n ], [VERSION, [NAME, CHROME+'cast']], [\n /(cros) [\\w]+ ([\\w\\.]+\\w)/i // Chromium OS\n ], [[NAME, 'Chromium OS'], VERSION],[\n\n // Console\n /(nintendo|playstation) ([wids345portablevuch]+)/i, // Nintendo/Playstation\n /(xbox); +xbox ([^\\);]+)/i, // Microsoft Xbox (360, One, X, S, Series X, Series S)\n\n // Other\n /\\b(joli|palm)\\b ?(?:os)?\\/?([\\w\\.]*)/i, // Joli/Palm\n /(mint)[\\/\\(\\) ]?(\\w*)/i, // Mint\n /(mageia|vectorlinux)[; ]/i, // Mageia/VectorLinux\n /([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\\/ ]?(?!chrom|package)([-\\w\\.]*)/i,\n // Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware/Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk/Linpus/Raspbian/Plan9/Minix/RISCOS/Contiki/Deepin/Manjaro/elementary/Sabayon/Linspire\n /(hurd|linux) ?([\\w\\.]*)/i, // Hurd/Linux\n /(gnu) ?([\\w\\.]*)/i, // GNU\n /\\b([-frentopcghs]{0,5}bsd|dragonfly)[\\/ ]?(?!amd|[ix346]{1,2}86)([\\w\\.]*)/i, // FreeBSD/NetBSD/OpenBSD/PC-BSD/GhostBSD/DragonFly\n /(haiku) (\\w+)/i // Haiku\n ], [NAME, VERSION], [\n /(sunos) ?([\\w\\.\\d]*)/i // Solaris\n ], [[NAME, 'Solaris'], VERSION], [\n /((?:open)?solaris)[-\\/ ]?([\\w\\.]*)/i, // Solaris\n /(aix) ((\\d)(?=\\.|\\)| )[\\w\\.])*/i, // AIX\n /\\b(beos|os\\/2|amigaos|morphos|openvms|fuchsia|hp-ux)/i, // BeOS/OS2/AmigaOS/MorphOS/OpenVMS/Fuchsia/HP-UX\n /(unix) ?([\\w\\.]*)/i // UNIX\n ], [NAME, VERSION]\n ]\n };\n\n /////////////////\n // Constructor\n ////////////////\n\n var UAParser = function (ua, extensions) {\n\n if (typeof ua === OBJ_TYPE) {\n extensions = ua;\n ua = undefined;\n }\n\n if (!(this instanceof UAParser)) {\n return new UAParser(ua, extensions).getResult();\n }\n\n var _ua = ua || ((typeof window !== UNDEF_TYPE && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY);\n var _rgxmap = extensions ? extend(regexes, extensions) : regexes;\n\n this.getBrowser = function () {\n var _browser = {};\n _browser[NAME] = undefined;\n _browser[VERSION] = undefined;\n rgxMapper.call(_browser, _ua, _rgxmap.browser);\n _browser.major = majorize(_browser.version);\n return _browser;\n };\n this.getCPU = function () {\n var _cpu = {};\n _cpu[ARCHITECTURE] = undefined;\n rgxMapper.call(_cpu, _ua, _rgxmap.cpu);\n return _cpu;\n };\n this.getDevice = function () {\n var _device = {};\n _device[VENDOR] = undefined;\n _device[MODEL] = undefined;\n _device[TYPE] = undefined;\n rgxMapper.call(_device, _ua, _rgxmap.device);\n return _device;\n };\n this.getEngine = function () {\n var _engine = {};\n _engine[NAME] = undefined;\n _engine[VERSION] = undefined;\n rgxMapper.call(_engine, _ua, _rgxmap.engine);\n return _engine;\n };\n this.getOS = function () {\n var _os = {};\n _os[NAME] = undefined;\n _os[VERSION] = undefined;\n rgxMapper.call(_os, _ua, _rgxmap.os);\n return _os;\n };\n this.getResult = function () {\n return {\n ua : this.getUA(),\n browser : this.getBrowser(),\n engine : this.getEngine(),\n os : this.getOS(),\n device : this.getDevice(),\n cpu : this.getCPU()\n };\n };\n this.getUA = function () {\n return _ua;\n };\n this.setUA = function (ua) {\n _ua = (typeof ua === STR_TYPE && ua.length > UA_MAX_LENGTH) ? trim(ua, UA_MAX_LENGTH) : ua;\n return this;\n };\n this.setUA(_ua);\n return this;\n };\n\n UAParser.VERSION = LIBVERSION;\n UAParser.BROWSER = enumerize([NAME, VERSION, MAJOR]);\n UAParser.CPU = enumerize([ARCHITECTURE]);\n UAParser.DEVICE = enumerize([MODEL, VENDOR, TYPE, CONSOLE, MOBILE, SMARTTV, TABLET, WEARABLE, EMBEDDED]);\n UAParser.ENGINE = UAParser.OS = enumerize([NAME, VERSION]);\n\n ///////////\n // Export\n //////////\n\n // check js environment\n if (typeof(exports) !== UNDEF_TYPE) {\n // nodejs env\n if (typeof module !== UNDEF_TYPE && module.exports) {\n exports = module.exports = UAParser;\n }\n exports.UAParser = UAParser;\n } else {\n // requirejs env (optional)\n if (typeof(define) === FUNC_TYPE && define.amd) {\n define(function () {\n return UAParser;\n });\n } else if (typeof window !== UNDEF_TYPE) {\n // browser env\n window.UAParser = UAParser;\n }\n }\n\n // jQuery/Zepto specific (optional)\n // Note:\n // In AMD env the global scope should be kept clean, but jQuery is an exception.\n // jQuery always exports to global scope, unless jQuery.noConflict(true) is used,\n // and we should catch that.\n var $ = typeof window !== UNDEF_TYPE && (window.jQuery || window.Zepto);\n if ($ && !$.ua) {\n var parser = new UAParser();\n $.ua = parser.getResult();\n $.ua.get = function () {\n return parser.getUA();\n };\n $.ua.set = function (ua) {\n parser.setUA(ua);\n var result = parser.getResult();\n for (var prop in result) {\n $.ua[prop] = result[prop];\n }\n };\n }\n\n})(typeof window === 'object' ? window : this);\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;\nconst SEGMENT_START_TIME_DELTA = 0.001;\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.availabilityTimeComplete = representation.availabilityTimeComplete;\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 getValidTimeCloseToTargetTime(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 // Apply delta to segment start time to get around rounding issues\n return targetRequest.startTime + SEGMENT_START_TIME_DELTA;\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 /**\n * This function returns a time larger than the current time for which we can generate a request.\n * This is useful in scenarios in which the user seeks into a gap in a dynamic Timeline manifest. 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 getValidTimeAheadOfTargetTime(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 if (representation.adaptation.period.start + representation.adaptation.period.duration < time) {\n return NaN;\n }\n\n // Only look 30 seconds ahead\n const end = Math.min(representation.adaptation.period.start + representation.adaptation.period.duration, time + 30);\n let currentUpperTime = Math.min(time + targetThreshold, end);\n let adjustedTime = NaN;\n let targetRequest = null;\n\n while (currentUpperTime <= end) {\n let upperRequest = null;\n\n if (currentUpperTime <= end) {\n upperRequest = getSegmentRequestForTime(mediaInfo, representation, currentUpperTime);\n }\n\n if (upperRequest) {\n adjustedTime = currentUpperTime;\n targetRequest = upperRequest;\n break;\n }\n\n currentUpperTime += 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 (!isNaN(targetRequest.startTime) && time < targetRequest.startTime && adjustedTime > targetRequest.startTime) {\n // Apply delta to segment start time to get around rounding issues\n return targetRequest.startTime + SEGMENT_START_TIME_DELTA;\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 getValidTimeCloseToTargetTime,\n getValidTimeAheadOfTargetTime\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 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 }\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, time / fTimescale);\n }\n\n for (j = 0; j <= repeat && !breakIterator; j++) {\n relativeIdx++;\n\n breakIterator = iterFunc(time, base, list, frag, fTimescale, relativeIdx, i);\n\n if (breakIterator) {\n representation.segmentDuration = frag.d / fTimescale;\n }\n\n time += frag.d;\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, 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 (time >= (lastSegmentTime * fTimescale) - (frag.d * 0.5)) { // same logic, if deviation is\n // 50% of segment duration, segment is found if time 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, 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 const scaledMediaTime = precisionRound(requiredMediaTime * fTimescale);\n if (scaledMediaTime < (time + frag.d) && scaledMediaTime >= time) {\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 function precisionRound(number) {\n return parseFloat(number.toPrecision(15));\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 filteredCmcdData = _applyWhitelist(cmcdData);\n const finalPayloadString = _buildFinalString(filteredCmcdData);\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 _applyWhitelist(cmcdData) {\n try {\n const enabledCMCDKeys = settings.get().streaming.cmcd.enabledKeys;\n\n return Object.keys(cmcdData)\n .filter(key => enabledCMCDKeys.includes(key))\n .reduce((obj, key) => {\n obj[key] = cmcdData[key];\n\n return obj;\n }, {});\n } catch (e) {\n return cmcdData;\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, _applyWhitelistByKeys(['br', 'd', 'ot', 'tb']));\n const cmcdRequestHeader = _copyParameters(cmcdData, _applyWhitelistByKeys(['bl', 'dl', 'mtp', 'nor', 'nrr', 'su']));\n const cmcdStatusHeader = _copyParameters(cmcdData, _applyWhitelistByKeys(['bs', 'rtp']));\n const cmcdSessionHeader = _copyParameters(cmcdData, _applyWhitelistByKeys(['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 _applyWhitelistByKeys(keys) {\n const enabledCMCDKeys = settings.get().streaming.cmcd.enabledKeys;\n\n return keys.filter(key => enabledCMCDKeys.includes(key));\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 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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/g, '&apos;');\n else\n return str;\n }\n\n function unescapeXmlChars(str) {\n return str.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '\"').replace(/&apos;/g, \"'\").replace(/&amp;/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';\nimport { modifyRequest } from '../utils/RequestModifier';\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 if (requestModifier && requestModifier.modifyRequest) {\n modifyRequest(httpRequest, requestModifier)\n .then(() => request(httpRequest));\n }\n else {\n request(httpRequest);\n }\n }\n\n function request(httpRequest) {\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 && requestModifier.modifyRequestHeader) {\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 url: httpRequest.url\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 let calculatedTime = null;\n if (calculationMode === Constants.ABR_FETCH_THROUGHPUT_CALCULATION_MOOF_PARSING) {\n calculatedThroughput = calculateThroughputByChunkData(startTimeData, endTimeData);\n if (calculatedThroughput) {\n calculatedTime = bytesReceived * 8 / calculatedThroughput;\n }\n }\n else if (calculationMode === Constants.ABR_FETCH_THROUGHPUT_CALCULATION_DOWNLOADED_DATA) {\n calculatedTime = calculateDownloadedTime(downloadedData, bytesReceived);\n }\n\n httpRequest.progress({\n loaded: bytesReceived,\n total: isNaN(totalBytes) ? bytesReceived : totalBytes,\n lengthComputable: true,\n time: calculatedTime,\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';\nimport CustomParametersModel from '../models/CustomParametersModel';\n\n/**\n * @module HTTPLoader\n * @ignore\n * @description Manages download of resources via HTTP.\n * @param {Object} cfg - dependencies 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 customParametersModel,\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 customParametersModel = CustomParametersModel(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 fileLoaderType = null;\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 request.fileLoaderType = fileLoaderType;\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 });\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\n let loader;\n if (request.hasOwnProperty('availabilityTimeComplete') && request.availabilityTimeComplete === false && 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 fileLoaderType = Constants.FILE_LOADER_TYPES.FETCH;\n } else {\n loader = XHRLoader(context).create({\n requestModifier: requestModifier\n });\n fileLoaderType = Constants.FILE_LOADER_TYPES.XHR;\n }\n\n let headers = null;\n let modifiedUrl = requestModifier.modifyRequestURL ? requestModifier.modifyRequestURL(request.url) : 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 = customParametersModel.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","'use strict'\n\n// See https://tools.ietf.org/html/rfc4647#section-3.1\n// for more information on the algorithms.\n\nexports.basicFilter = factory(basic, true)\nexports.extendedFilter = factory(extended, true)\nexports.lookup = factory(lookup)\n\n// Basic Filtering (Section 3.3.1) matches a language priority list consisting\n// of basic language ranges (Section 2.1) to sets of language tags.\nfunction basic(tag, range) {\n return range === '*' || tag === range || tag.indexOf(range + '-') > -1\n}\n\n// Extended Filtering (Section 3.3.2) matches a language priority list\n// consisting of extended language ranges (Section 2.2) to sets of language\n// tags.\nfunction extended(tag, range) {\n // 3.3.2.1\n var left = tag.split('-')\n var right = range.split('-')\n var leftIndex = 0\n var rightIndex = 0\n\n // 3.3.2.2\n if (right[rightIndex] !== '*' && left[leftIndex] !== right[rightIndex]) {\n return false\n }\n\n leftIndex++\n rightIndex++\n\n // 3.3.2.3\n while (rightIndex < right.length) {\n // 3.3.2.3.A\n if (right[rightIndex] === '*') {\n rightIndex++\n continue\n }\n\n // 3.3.2.3.B\n if (!left[leftIndex]) return false\n\n // 3.3.2.3.C\n if (left[leftIndex] === right[rightIndex]) {\n leftIndex++\n rightIndex++\n continue\n }\n\n // 3.3.2.3.D\n if (left[leftIndex].length === 1) return false\n\n // 3.3.2.3.E\n leftIndex++\n }\n\n // 3.3.2.4\n return true\n}\n\n// Lookup (Section 3.4) matches a language priority list consisting of basic\n// language ranges to sets of language tags to find the one exact language tag\n// that best matches the range.\nfunction lookup(tag, range) {\n var right = range\n var index\n\n /* eslint-disable-next-line no-constant-condition */\n while (true) {\n if (right === '*' || tag === right) return true\n\n index = right.lastIndexOf('-')\n\n if (index < 0) return false\n\n if (right.charAt(index - 2) === '-') index -= 2\n\n right = right.slice(0, index)\n }\n}\n\n// Factory to perform a filter or a lookup.\n// This factory creates a function that accepts a list of tags and a list of\n// ranges, and contains logic to exit early for lookups.\n// `check` just has to deal with one tag and one range.\n// This match function iterates over ranges, and for each range,\n// iterates over tags. That way, earlier ranges matching any tag have\n// precedence over later ranges.\nfunction factory(check, filter) {\n return match\n\n function match(tags, ranges) {\n var left = cast(tags, 'tag')\n var right = cast(ranges == null ? '*' : ranges, 'range')\n var matches = []\n var rightIndex = -1\n var range\n var leftIndex\n var next\n\n while (++rightIndex < right.length) {\n range = right[rightIndex].toLowerCase()\n\n // Ignore wildcards in lookup mode.\n if (!filter && range === '*') continue\n\n leftIndex = -1\n next = []\n\n while (++leftIndex < left.length) {\n if (check(left[leftIndex].toLowerCase(), range)) {\n // Exit if this is a lookup and we have a match.\n if (!filter) return left[leftIndex]\n matches.push(left[leftIndex])\n } else {\n next.push(left[leftIndex])\n }\n }\n\n left = next\n }\n\n // If this is a filter, return the list. If it’s a lookup, we didn’t find\n // a match, so return `undefined`.\n return filter ? matches : undefined\n }\n}\n\n// Validate tags or ranges, and cast them to arrays.\nfunction cast(values, name) {\n var value = values && typeof values === 'string' ? [values] : values\n\n if (!value || typeof value !== 'object' || !('length' in value)) {\n throw new Error(\n 'Invalid ' + name + ' `' + value + '`, expected non-empty string'\n )\n }\n\n return value\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","/* globals __webpack_amd_options__ */\nmodule.exports = __webpack_amd_options__;\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 */\nimport Constants from '../constants/Constants';\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';\nimport MetricsConstants from '../constants/MetricsConstants';\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 serviceDescriptionController,\n dashMetrics,\n adapter,\n videoModel,\n timelineConverter,\n wallclockTimeIntervalId,\n liveDelay,\n originalLiveDelay,\n streamInfo,\n isDynamic,\n playOnceInitialized,\n lastLivePlaybackTime,\n availabilityStartTime,\n availabilityTimeComplete,\n lowLatencyModeEnabled,\n seekTarget,\n internalSeek,\n playbackStalled,\n manifestUpdateInProgress,\n initialCatchupModeActivated,\n settings;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n\n reset();\n }\n\n /**\n * Reset all settings\n */\n function reset() {\n pause();\n playOnceInitialized = false;\n liveDelay = 0;\n originalLiveDelay = 0;\n availabilityStartTime = 0;\n manifestUpdateInProgress = false;\n availabilityTimeComplete = true;\n lowLatencyModeEnabled = false;\n initialCatchupModeActivated = false;\n seekTarget = NaN;\n\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.PLAYBACK_ENDED, _onPlaybackEnded, instance);\n eventBus.off(MediaPlayerEvents.STREAM_INITIALIZING, _onStreamInitializing, instance);\n eventBus.off(MediaPlayerEvents.REPRESENTATION_SWITCH, _onRepresentationSwitch, instance);\n eventBus.off(MediaPlayerEvents.BUFFER_LEVEL_STATE_CHANGED, _onBufferLevelStateChanged, instance);\n stopUpdatingWallclockTime();\n removeAllListeners();\n }\n\n wallclockTimeIntervalId = null;\n videoModel = null;\n streamInfo = null;\n isDynamic = null;\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 }\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\n playbackStalled = false;\n internalSeek = false;\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.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 eventBus.on(MediaPlayerEvents.BUFFER_LEVEL_STATE_CHANGED, _onBufferLevelStateChanged, instance);\n\n if (playOnceInitialized) {\n playOnceInitialized = false;\n play();\n }\n }\n\n /**\n * Returns stalled state\n * @return {boolean}\n */\n function getPlaybackStalled() {\n return playbackStalled\n }\n\n /**\n * Returns remaining duration of a period\n * @param {object} sInfo\n * @return {number}\n */\n function getTimeToStreamEnd(sInfo = null) {\n return parseFloat((getStreamEndTime(sInfo) - getTime()).toFixed(5));\n }\n\n /**\n * Returns end time of a period\n * @param {object} sInfo\n * @return {number}\n */\n function getStreamEndTime(sInfo) {\n const refInfo = sInfo ? sInfo : streamInfo;\n return refInfo.start + refInfo.duration;\n }\n\n /**\n * Triggers play() on the video element\n */\n function play(adjustLiveDelay = false) {\n if (streamInfo && videoModel && videoModel.getElement()) {\n if (adjustLiveDelay && isDynamic) {\n _adjustLiveDelayAfterUserInteraction(getTime());\n }\n videoModel.play();\n } else {\n playOnceInitialized = true;\n }\n }\n\n /**\n * Triggers pause() on the video element\n */\n function pause() {\n if (streamInfo && videoModel) {\n videoModel.pause();\n }\n }\n\n /**\n * Triggers a seek to the specified media time. If internal is enabled there will be now \"seeked\" event dispatched\n * @param {number} time\n * @param {boolean} stickToBuffered\n * @param {boolean} internal\n * @param {boolean} adjustLiveDelay\n */\n function seek(time, stickToBuffered = false, internal = false, adjustLiveDelay = false) {\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 }\n logger.info('Requesting seek to time: ' + time + (internalSeek ? ' (internal)' : ''));\n\n // We adjust the current latency. If catchup is enabled we will maintain this new latency\n if (isDynamic && adjustLiveDelay) {\n _adjustLiveDelayAfterUserInteraction(time);\n }\n\n videoModel.setCurrentTime(time, stickToBuffered);\n }\n\n /**\n * Seeks back to the live edge as defined by the originally calculated live delay\n * @param {boolean} stickToBuffered\n * @param {boolean} internal\n * @param {boolean} adjustLiveDelay\n */\n function seekToOriginalLive(stickToBuffered = false, internal = false, adjustLiveDelay = false) {\n const dvrWindowEnd = _getDvrWindowEnd();\n\n if (dvrWindowEnd === 0) {\n return;\n }\n\n liveDelay = originalLiveDelay;\n const seektime = dvrWindowEnd - liveDelay;\n\n seek(seektime, stickToBuffered, internal, adjustLiveDelay);\n }\n\n /**\n * Seeks to the live edge as currently defined by liveDelay\n * @param {boolean} stickToBuffered\n * @param {boolean} internal\n * @param {boolean} adjustLiveDelay\n */\n function seekToCurrentLive(stickToBuffered = false, internal = false, adjustLiveDelay = false) {\n const dvrWindowEnd = _getDvrWindowEnd();\n\n if (dvrWindowEnd === 0) {\n return;\n }\n\n const seektime = dvrWindowEnd - liveDelay;\n\n seek(seektime, stickToBuffered, internal, adjustLiveDelay);\n }\n\n function _getDvrWindowEnd() {\n if (!streamInfo || !videoModel || !isDynamic) {\n return;\n }\n\n const type = streamController && streamController.hasVideoTrack() ? Constants.VIDEO : Constants.AUDIO;\n const dvrInfo = dashMetrics.getCurrentDVRInfo(type);\n\n return dvrInfo && dvrInfo.range ? dvrInfo.range.end : 0;\n }\n\n\n function _adjustLiveDelayAfterUserInteraction(time) {\n const now = new Date(timelineConverter.getClientReferenceTime());\n const period = adapter.getRegularPeriods()[0];\n const nowAsPresentationTime = timelineConverter.calcPresentationTimeFromWallTime(now, period);\n\n liveDelay = nowAsPresentationTime - time;\n }\n\n /**\n * Returns current time of video element\n * @return {number|null}\n */\n function getTime() {\n return streamInfo && videoModel ? videoModel.getTime() : null;\n }\n\n /**\n * Returns paused state of the video element\n * @return {boolean|null}\n */\n function isPaused() {\n return streamInfo && videoModel ? videoModel.isPaused() : null;\n }\n\n /**\n * Returns seeking state of the video element\n * @return {boolean|null}\n */\n function isSeeking() {\n return streamInfo && videoModel ? videoModel.isSeeking() : null;\n }\n\n /**\n * Returns stalled state of the video element\n * @return {boolean|null}\n */\n function isStalled() {\n return streamInfo && videoModel ? videoModel.isStalled() : null;\n }\n\n /**\n * Returns current playback rate of the video element\n * @return {number|null}\n */\n function getPlaybackRate() {\n return streamInfo && videoModel ? videoModel.getPlaybackRate() : null;\n }\n\n /**\n * Returns the played ranges of the video element\n * @return {array}\n */\n function getPlayedRanges() {\n return streamInfo && videoModel ? videoModel.getPlayedRanges() : null;\n }\n\n /**\n * Returns ended attribute of the video element\n * @return {boolean|null}\n */\n function getEnded() {\n return streamInfo && videoModel ? videoModel.getEnded() : null;\n }\n\n /**\n * Returns whether a stream is type dynamic or not\n * @return {boolean}\n */\n function getIsDynamic() {\n return isDynamic;\n }\n\n /**\n * Returns the StreamController\n * @return {object}\n */\n function getStreamController() {\n return streamController;\n }\n\n /**\n * Returns whether a manifest update is in progress\n * @return {boolean}\n */\n function getIsManifestUpdateInProgress() {\n return manifestUpdateInProgress;\n }\n\n /**\n * Returns the availabilityStartTime\n * @return {number}\n */\n function getAvailabilityStartTime() {\n return availabilityStartTime;\n }\n\n /**\n * Returns the current live delay. A seek triggered by the user adjusts this value.\n * @return {number}\n */\n function getLiveDelay() {\n return liveDelay;\n }\n\n /**\n * Returns the original live delay as calculated at playback start\n */\n function getOriginalLiveDelay() {\n return originalLiveDelay;\n }\n\n /**\n * Returns the current live latency\n * @return {number}\n */\n function getCurrentLiveLatency() {\n if (!isDynamic || isNaN(availabilityStartTime)) {\n return NaN;\n }\n let currentTime = getTime();\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 /**\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 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 const serviceDescriptionSettings = serviceDescriptionController.getServiceDescriptionSettings();\n\n // Live delay specified by the user\n if (!isNaN(settings.get().streaming.delay.liveDelay)) {\n delay = settings.get().streaming.delay.liveDelay;\n }\n\n // Live delay fragment count specified by the user\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 }\n\n // Live delay set via ServiceDescription element\n else if (serviceDescriptionSettings && !isNaN(serviceDescriptionSettings.liveDelay) && serviceDescriptionSettings.liveDelay > 0) {\n delay = serviceDescriptionSettings.liveDelay;\n }\n // Live delay set in the manifest using @suggestedPresentation Delay\n else if (settings.get().streaming.delay.useSuggestedPresentationDelay === true && suggestedPresentationDelay !== null && !isNaN(suggestedPresentationDelay) && suggestedPresentationDelay > 0) {\n delay = suggestedPresentationDelay;\n }\n\n // We found a fragment duration, use that to calculcate live delay\n else if (!isNaN(adjustedFragmentDuration)) {\n delay = adjustedFragmentDuration * FRAGMENT_DURATION_FACTOR;\n }\n\n // Fall back to @minBufferTime to calculate the live delay\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 if (startTime !== null) {\n availabilityStartTime = startTime;\n }\n\n if (manifestInfo && manifestInfo.dvrWindowSize > 0) {\n // Latency can not be higher than DVR window size\n ret = Math.min(delay, manifestInfo.dvrWindowSize);\n } else {\n ret = delay;\n }\n liveDelay = ret;\n originalLiveDelay = ret;\n\n return ret;\n }\n\n function setConfig(config) {\n if (!config) return;\n\n if (config.streamController) {\n streamController = config.streamController;\n }\n if (config.serviceDescriptionController) {\n serviceDescriptionController = config.serviceDescriptionController;\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.timelineConverter) {\n timelineConverter = config.timelineConverter;\n }\n if (config.settings) {\n settings = config.settings;\n }\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 = getTime();\n const actualTime = _getAdjustedPresentationTime(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, false, false);\n }\n }\n\n /**\n * Adjust the presentation time based on the DVR window. If we are out of the DVR window we return a corrected time\n * @param {number} currentTime\n * @param {string} mediatype\n * @return {number}\n * @private\n */\n function _getAdjustedPresentationTime(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 (lowLatencyModeEnabled) {\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 /**\n * Start interval handler for wallclock time update\n */\n function startUpdatingWallclockTime() {\n if (wallclockTimeIntervalId !== null) return;\n\n wallclockTimeIntervalId = setInterval(() => {\n _onWallclockTime();\n }, settings.get().streaming.wallclockTimeUpdateInterval);\n }\n\n /**\n * Stop the interval handler for the wallclock time update\n */\n function stopUpdatingWallclockTime() {\n clearInterval(wallclockTimeIntervalId);\n wallclockTimeIntervalId = null;\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 _onBufferLevelStateChanged(e) {\n // do not stall playback when get an event from Stream that is not active\n if (e.streamId !== streamController.getActiveStreamInfo().id) {\n return;\n }\n\n playbackStalled = e.state === MetricsConstants.BUFFER_EMPTY;\n\n if (settings.get().streaming.buffer.setStallState) {\n videoModel.setStallState(e.mediaType, e.state === MetricsConstants.BUFFER_EMPTY);\n }\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 internalSeek = false;\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 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 internalSeek = false;\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 function _onVolumeChanged() {\n eventBus.trigger(Events.PLAYBACK_VOLUME_CHANGED);\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 * 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 value of lowLatencyModeEnabled\n * @return {boolean} lowLatencyModeEnabled\n */\n function getLowLatencyModeEnabled() {\n return lowLatencyModeEnabled\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 && lowLatencyModeEnabled && !isNaN(e.request.duration)) {\n const minDelay = 1.2 * e.request.duration;\n if (minDelay > liveDelay) {\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 liveDelay = minDelay;\n originalLiveDelay = minDelay;\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 (!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 availabilityTimeComplete = e.currentRepresentation.availabilityTimeComplete;\n lowLatencyModeEnabled = !availabilityTimeComplete;\n\n // If we enable low latency mode for the first time we also enable the catchup mechanism. This can be deactivated again for instance if the user seeks within the DVR window. We leave deactivation up to the application but also do not activate automatically again.\n if (lowLatencyModeEnabled && !initialCatchupModeActivated) {\n initialCatchupModeActivated = true;\n }\n }\n\n function getInitialCatchupModeActivated() {\n return initialCatchupModeActivated;\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 function _checkEnableLowLatency(mediaInfo) {\n if (mediaInfo && mediaInfo.supplementalProperties &&\n mediaInfo.supplementalProperties[Constants.SUPPLEMENTAL_PROPERTY_DVB_LL_SCHEME] === 'true') {\n logger.debug('Low Latency critical SupplementalProperty set: Enabling low Latency');\n lowLatencyModeEnabled = true;\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 videoModel.addEventListener('volumechange', _onVolumeChanged);\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 videoModel.removeEventListener('volumechange', _onVolumeChanged);\n }\n\n instance = {\n initialize,\n setConfig,\n getTimeToStreamEnd,\n getBufferLevel,\n getPlaybackStalled,\n getTime,\n getLowLatencyModeEnabled,\n getInitialCatchupModeActivated,\n getIsManifestUpdateInProgress,\n getPlaybackRate,\n getPlayedRanges,\n getEnded,\n getIsDynamic,\n getStreamController,\n computeAndSetLiveDelay,\n getLiveDelay,\n getOriginalLiveDelay,\n getCurrentLiveLatency,\n play,\n isPaused,\n isStalled,\n pause,\n isSeeking,\n getStreamEndTime,\n seek,\n seekToOriginalLive,\n seekToCurrentLive,\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 const rangeAtCurrenTime = getRangeAt(currentTime, 0);\n const rangeAtSeekTarget = getRangeAt(seekTarget, 0);\n if (rangeAtCurrenTime && rangeAtSeekTarget && rangeAtCurrenTime.start === rangeAtSeekTarget.start) {\n seekTarget = NaN;\n return;\n }\n\n // Get buffered range corresponding to the seek target\n const segmentDuration = representationController.getCurrentRepresentation().segmentDuration;\n const 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 if (settings.get().streaming.buffer.useChangeTypeForTrackSwitch) {\n return sourceBufferSink.changeType(codec);\n }\n\n return Promise.resolve();\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 if (settings.get().streaming.buffer.useChangeTypeForTrackSwitch) {\n return sourceBufferSink.changeType(codec);\n }\n\n return Promise.resolve();\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 // we keep everything that is within bufferToKeepAhead but only if the buffer is continuous.\n // Otherwise we have gaps once the seek is done which might trigger an unintentional gap jump\n const endOfBuffer = ranges.end(ranges.length - 1) + BUFFER_END_THRESHOLD;\n const continuousBufferTime = getContinuousBufferTimeForTargetTime(targetTime);\n\n // This is the maximum range we keep ahead\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\n // Define the start time from which we will prune. If there is no continuous range from the targettime we start immediately at the target time\n // Otherwise we set the start point to the end of the continuous range taking the maximum buffer to keep ahead into account\n let rangeStart = !isNaN(continuousBufferTime) ? Math.min(continuousBufferTime, targetTime + bufferToKeepAhead) : targetTime;\n\n // Check if we are done buffering, no need to prune then\n if (rangeStart >= ranges.end(ranges.length - 1)) {\n return null\n }\n\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\n // Never remove the contiguous range of targetTime in order to avoid flushes & reenqueues when the user doesn't want it\n const avoidCurrentTimeRangePruning = settings.get().streaming.buffer.avoidCurrentTimeRangePruning;\n if (avoidCurrentTimeRangePruning) {\n for (let i = 0; i < ranges.length; i++) {\n if (ranges.start(i) <= targetTime && targetTime <= ranges.end(i)\n && ranges.start(i) <= rangeStart && rangeStart <= ranges.end(i)) {\n let oldRangeStart = rangeStart;\n if (i + 1 < ranges.length) {\n rangeStart = ranges.start(i + 1);\n } else {\n rangeStart = ranges.end(i) + 1;\n }\n logger.debug('Buffered range [' + ranges.start(i) + ', ' + ranges.end(i) + '] overlaps with targetTime ' + targetTime + ' and range to be pruned [' + oldRangeStart + ', ' + endOfBuffer + '], using [' + rangeStart + ', ' + endOfBuffer + '] instead' + ((rangeStart < endOfBuffer) ? '' : ' (no actual pruning)'));\n break;\n }\n }\n }\n\n if (rangeStart < ranges.end(ranges.length - 1)) {\n return {\n start: rangeStart,\n end: endOfBuffer\n };\n }\n return null;\n }\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 // To avoid rounding error when comparing, the stream time and buffer level only must be within 5 decimal places\n const periodBuffered = playbackController.getTimeToStreamEnd(streamInfo) - bufferLevel < 0.00001;\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 (((!playbackController.getLowLatencyModeEnabled() && 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 || (playbackController.getLowLatencyModeEnabled() && 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(playbackController.getLowLatencyModeEnabled() ? settings.get().streaming.scheduling.lowLatencyTimeout : settings.get().streaming.scheduling.defaultTimeout);\n }\n } catch (e) {\n startScheduleTimer(playbackController.getLowLatencyModeEnabled() ? 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 might be 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 // For dynamic manifests this can also happen especially if we jump over the gap in the previous period and are using SegmentTimeline and in case there is a positive eptDelta at the beginning of the period we are stuck.\n if (settings.get().streaming.gaps.enableSeekFix && (shouldUseExplicitTimeForRequest || playbackController.getTime() === 0)) {\n let adjustedTime;\n if (!isDynamic) {\n adjustedTime = dashHandler.getValidTimeAheadOfTargetTime(bufferingTime, mediaInfo, representation, settings.get().streaming.gaps.threshold);\n } else if (isDynamic && representation.segmentInfoType === DashConstants.SEGMENT_TIMELINE) {\n // If we find a valid request ahead of the current time then we are in a gap. Segments are only added at the end of the timeline\n adjustedTime = dashHandler.getValidTimeAheadOfTargetTime(bufferingTime, mediaInfo, representation, settings.get().streaming.gaps.threshold,);\n }\n if (!isNaN(adjustedTime) && adjustedTime !== bufferingTime) {\n if (playbackController.isSeeking() || playbackController.getTime() === 0) {\n // If we are seeking then playback is stalled. Do a seek to get out of this situation\n logger.warn(`Adjusting playback time ${adjustedTime} because of gap in the manifest. Seeking by ${adjustedTime - bufferingTime}`);\n playbackController.seek(adjustedTime, false, false);\n } else {\n // If we are not seeking we should still be playing but we cant find anything to buffer. So we adjust the buffering time and leave the gap jump to the GapController\n logger.warn(`Adjusting buffering time ${adjustedTime} because of gap in the manifest. Adjusting time by ${adjustedTime - bufferingTime}`);\n setExplicitBufferingTime(adjustedTime)\n\n if (rescheduleIfNoRequest) {\n _noValidRequest();\n }\n }\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(playbackController.getLowLatencyModeEnabled() ? 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 and in case a rule such as AbandonRequestRule has forced a quality switch. 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 * (!isNaN(representationInfo.fragmentDuration) ? representationInfo.fragmentDuration : 1);\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 // The quality we originally requested was lower than the new quality\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, null, streamInfo);\n const eventStreamTrack = adapter.getEventsFor(currentRepresentation, voRepresentation, streamInfo);\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.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 if (events && events.length > 0) {\n eventController.addInlineEvents(events, streamInfo.id);\n }\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 protectionController.handleKeySystemFromManifest();\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, streamInfo.id);\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[periodID][schemeIdUri]\n inbandEvents = {}; // Format inbandEvents[periodID][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 * 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 _removeOutdatedEventObjects(inbandEvents);\n _removeOutdatedEventObjects(inlineEvents);\n\n lastEventTimerCall = currentVideoTime;\n eventHandlingInProgress = false;\n }\n } catch (e) {\n eventHandlingInProgress = false;\n logger.error(e);\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, MediaPlayerEvents.EVENT_MODE_ON_START);\n } else if (_eventHasExpired(currentVideoTime, duration + presentationTimeThreshold, event.calculatedPresentationTime) || _eventIsInvalid(event)) {\n logger.debug(`Removing event ${event.id} from period ${event.eventStream.period.id} as it is expired or invalid`);\n _removeEvent(events, event);\n }\n }\n };\n\n _iterateAndTriggerCallback(events, callback);\n } catch (e) {\n logger.error(e);\n }\n }\n\n /**\n * Iterates over the entries of the events object and deletes the entries for which no events are present\n * @param {object} events\n * @private\n */\n function _removeOutdatedEventObjects(events) {\n try {\n for (const key in events) {\n if (events.hasOwnProperty(key)) {\n if (Object.keys(events[key]).length === 0)\n delete events[key];\n }\n }\n } catch (e) {\n logger.error(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 * @param {string} periodId\n */\n function addInlineEvents(values, periodId) {\n try {\n checkConfig();\n\n if (!inlineEvents[periodId]) {\n inlineEvents[periodId] = {};\n }\n\n if (values) {\n for (let i = 0; i < values.length; i++) {\n let event = values[i];\n const currentTime = playbackController.getTime();\n const duration = !isNaN(event.duration) ? event.duration : 0;\n if (!_eventHasExpired(currentTime, duration, event.calculatedPresentationTime)) {\n let result = _addOrUpdateEvent(event, inlineEvents[periodId], true);\n\n if (result === EVENT_HANDLED_STATES.ADDED) {\n logger.debug(`Added inline event with id ${event.id} from period ${periodId}`);\n // If we see the event for the first time we trigger it in onReceive mode\n _startEvent(event, MediaPlayerEvents.EVENT_MODE_ON_RECEIVE);\n } else if (result === EVENT_HANDLED_STATES.UPDATED) {\n logger.debug(`Updated inline event with id ${event.id} from period ${periodId}`);\n }\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 * @param {string} periodId\n */\n function addInbandEvents(values, periodId) {\n try {\n checkConfig();\n\n if (!inbandEvents[periodId]) {\n inbandEvents[periodId] = {};\n }\n\n for (let i = 0; i < values.length; i++) {\n let event = values[i];\n const currentTime = playbackController.getTime();\n const duration = !isNaN(event.duration) ? event.duration : 0;\n if (!_eventHasExpired(currentTime, duration, event.calculatedPresentationTime)) {\n let result = _addOrUpdateEvent(event, inbandEvents[periodId], false);\n\n if (result === EVENT_HANDLED_STATES.ADDED) {\n if (event.eventStream.schemeIdUri === MPD_RELOAD_SCHEME) {\n _handleManifestReloadEvent(event);\n }\n logger.debug(`Added inband event with id ${event.id} from period ${periodId}`);\n _startEvent(event, MediaPlayerEvents.EVENT_MODE_ON_RECEIVE);\n } else {\n logger.debug(`Inband event with scheme_id_uri ${event.eventStream.schemeIdUri}, value ${event.eventStream.value}, period id ${periodId} and event id ${event.id} was ignored because it has been added before.`);\n }\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 // New event, we add it to our list of events\n if (indexOfExistingEvent === -1) {\n events[schemeIdUri].push(event);\n event.triggeredReceivedEvent = false;\n event.triggeredStartEvent = false;\n eventState = EVENT_HANDLED_STATES.ADDED;\n }\n\n // We have a similar event for this period with the same schemeIdUri, value and id. Overwrite it or ignore it\n else if (shouldOverwriteExistingEvents) {\n const oldEvent = events[schemeIdUri][indexOfExistingEvent];\n event.triggeredReceivedEvent = oldEvent.triggeredReceivedEvent;\n event.triggeredStartEvent = oldEvent.triggeredStartEvent;\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 logger.error(e);\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 logger.error(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, MediaPlayerEvents.EVENT_MODE_ON_START);\n }\n\n };\n\n _iterateAndTriggerCallback(events, callback);\n\n } catch (e) {\n logger.error(e);\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 periodIds = Object.keys(events);\n for (let i = 0; i < periodIds.length; i++) {\n const currentPeriod = events[periodIds[i]];\n const schemeIdUris = Object.keys(currentPeriod);\n for (let j = 0; j < schemeIdUris.length; j++) {\n const schemeIdEvents = currentPeriod[schemeIdUris[j]];\n schemeIdEvents.forEach((event) => {\n if (event !== undefined) {\n callback(event);\n }\n });\n }\n }\n }\n } catch (e) {\n logger.error(e);\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 logger.error(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 logger.error(e);\n return false;\n }\n }\n\n /**\n * Starts an event. Depending on the schemeIdUri we distinguish between\n * - MPD Reload events\n * - MPD Callback events\n * - Events to be dispatched to the application\n * @param {object} event\n * @param {String} mode\n * @private\n */\n function _startEvent(event, mode) {\n try {\n const currentVideoTime = playbackController.getTime();\n const eventId = event.id;\n\n if (mode === MediaPlayerEvents.EVENT_MODE_ON_RECEIVE && !event.triggeredReceivedEvent) {\n logger.debug(`Received event ${eventId}`);\n event.triggeredReceivedEvent = true;\n eventBus.trigger(event.eventStream.schemeIdUri, { event: event }, { mode });\n return;\n }\n\n if (!event.triggeredStartEvent) {\n if (event.eventStream.schemeIdUri === MPD_RELOAD_SCHEME && event.eventStream.value == MPD_RELOAD_VALUE) {\n //If both are set to zero, it indicates the media is over at this point. Don't reload the manifest.\n if (event.duration !== 0 || event.presentationTimeDelta !== 0) {\n logger.debug(`Starting manifest refresh event ${eventId} at ${currentVideoTime}`);\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 _sendCallbackRequest(event.messageData);\n } else {\n logger.debug(`Starting event ${eventId} from period ${event.eventStream.period.id} at ${currentVideoTime}`);\n eventBus.trigger(event.eventStream.schemeIdUri, { event: event }, { mode });\n }\n event.triggeredStartEvent = true;\n }\n } catch (e) {\n logger.error(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 try {\n const schemeIdUri = event.eventStream.schemeIdUri;\n const periodId = event.eventStream.period.id;\n const value = event.eventStream.value;\n const id = event.id;\n\n events[periodId][schemeIdUri] = events[periodId][schemeIdUri].filter((e) => {\n return (value && e.eventStream.value && e.eventStream.value !== value) || e.id !== id;\n });\n\n if (events[periodId][schemeIdUri].length === 0) {\n delete events[periodId][schemeIdUri];\n }\n } catch (e) {\n logger.error(e);\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 logger.error(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 logger.error(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, 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, logger, capabilities, capabilitiesFilter, manifestUpdater, manifestLoader, manifestModel, adapter,\n dashMetrics, mediaSourceController, timeSyncController, contentSteeringController, baseURLController,\n segmentBaseController, uriFragmentModel, abrController, mediaController, eventController, initCache, urlUtils,\n errHandler, timelineConverter, streams, activeStream, protectionController, textController, protectionData,\n autoPlay, isStreamSwitchingInProgress, hasMediaError, hasInitialisationError, mediaSource, videoModel,\n playbackController, serviceDescriptionController, mediaPlayerModel, customParametersModel, isPaused,\n initialPlayback, initialSteeringRequest, playbackEndedTimerInterval, bufferSinks, preloadingStreams,\n supportsChangeType, settings,\n firstLicenseIsFetched, waitForPlaybackStartTimeout, providedStartTime, 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, playbackController: playbackController, settings\n });\n eventController.start();\n\n\n timeSyncController.setConfig({\n dashMetrics, baseURLController, errHandler, 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 eventBus.on(Events.SETTING_UPDATED_LIVE_DELAY, _onLiveDelaySettingUpdated, instance);\n eventBus.on(Events.SETTING_UPDATED_LIVE_DELAY_FRAGMENT_COUNT, _onLiveDelaySettingUpdated, 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 eventBus.off(Events.SETTING_UPDATED_LIVE_DELAY, _onLiveDelaySettingUpdated, instance);\n eventBus.off(Events.SETTING_UPDATED_LIVE_DELAY_FRAGMENT_COUNT, _onLiveDelaySettingUpdated, instance);\n }\n\n function _checkConfig() {\n if (!manifestLoader || !manifestLoader.hasOwnProperty('load') || !timelineConverter || !timelineConverter.hasOwnProperty('initialize') || !timelineConverter.hasOwnProperty('reset') || !timelineConverter.hasOwnProperty('getClientTimeOffset') || !manifestModel || !errHandler || !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 /**\n * Start the streaming session by loading the target manifest\n * @param {string} url\n * @param {number} startTime\n */\n function load(url, startTime = NaN) {\n _checkConfig();\n providedStartTime = startTime;\n manifestLoader.load(url);\n }\n\n /**\n * Start the streaming session by using the provided manifest object\n * @param {object} manifest\n * @param {number} startTime\n */\n function loadWithManifest(manifest, startTime = NaN) {\n _checkInitialize();\n providedStartTime = startTime;\n manifestUpdater.setManifest(manifest);\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 periods in the MPD');\n }\n\n if (activeStream && streamsInfo.length > 0) {\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 (settings.get().streaming.applyContentSteering && !activeStream && contentSteeringController.shouldQueryBeforeStart()) {\n return contentSteeringController.loadSteeringData();\n }\n return Promise.resolve();\n })\n .then(() => {\n if (!activeStream) {\n _initializeForFirstStream(streamsInfo);\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 {array} streamsInfo\n * @private\n */\n function _initializeForFirstStream(streamsInfo) {\n\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\n // Calculate the producer reference time offsets if given\n if (settings.get().streaming.applyProducerReferenceTime) {\n serviceDescriptionController.calculateProducerReferenceTimeOffsets(streamsInfo);\n }\n\n // Apply Service description parameters.\n const manifestInfo = streamsInfo[0].manifestInfo;\n if (settings.get().streaming.applyServiceDescription) {\n serviceDescriptionController.applyServiceDescription(manifestInfo);\n }\n\n // Compute and set the live delay\n if (adapter.getIsDynamic()) {\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 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 * A setting related to the live delay was updated. Check if one of the latency values changed. If so, recalculate the live delay.\n * @private\n */\n function _onLiveDelaySettingUpdated() {\n if (adapter.getIsDynamic() && playbackController.getOriginalLiveDelay() !== 0) {\n const streamsInfo = adapter.getStreamsInfo()\n if (streamsInfo.length > 0) {\n const manifestInfo = streamsInfo[0].manifestInfo;\n const fragmentDuration = _getFragmentDurationForLiveDelayCalculation(streamsInfo, manifestInfo);\n\n playbackController.computeAndSetLiveDelay(fragmentDuration, manifestInfo);\n }\n }\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 if (initialSteeringRequest) {\n initialSteeringRequest = false;\n // If this is the initial playback attempt and we have not yet triggered content steering now is the time\n if (settings.get().streaming.applyContentSteering && !contentSteeringController.shouldQueryBeforeStart()) {\n contentSteeringController.loadSteeringData();\n }\n\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 contentSteeringController.stopSteeringRequestTimer();\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 via the application\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 const isDynamic = adapter.getIsDynamic();\n if (isDynamic) {\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.getOriginalLiveDelay();\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 // If start time was provided by the application as part of the call to initialize() or attachSource() use this value\n if (!isNaN(providedStartTime) || providedStartTime.toString().indexOf('posix:') !== -1) {\n logger.info(`Start time provided by the app: ${providedStartTime}`);\n const providedStartTimeAsPresentationTime = _getStartTimeFromProvidedData(true, providedStartTime)\n if (!isNaN(providedStartTimeAsPresentationTime)) {\n // Do not move closer to the live edge as defined by live delay\n startTime = Math.min(startTime, providedStartTimeAsPresentationTime);\n }\n } else {\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 // Do not move closer to the live edge as defined by live delay\n startTime = Math.min(startTime, startTimeFromUri);\n }\n }\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(startTime, dvrWindow.start + offset);\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\n // If start time was provided by the application as part of the call to initialize() or attachSource() use this value\n if (!isNaN(providedStartTime)) {\n logger.info(`Start time provided by the app: ${providedStartTime}`);\n const providedStartTimeAsPresentationTime = _getStartTimeFromProvidedData(false, providedStartTime)\n if (!isNaN(providedStartTimeAsPresentationTime)) {\n // Do not play earlier than the start of the first period\n startTime = Math.max(startTime, providedStartTimeAsPresentationTime);\n }\n } else {\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 // Do not play earlier than the start of the first period\n startTime = Math.max(startTime, startTimeFromUri);\n }\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 referenceTime = refStream.getStreamInfo().start;\n fragData.t = fragData.t.split(',')[0];\n\n return _getStartTimeFromString(isDynamic, fragData.t, referenceTime);\n }\n\n /**\n * Calculate start time using the value that was provided via the application as part of attachSource() or initialize()\n * @param {boolean} isDynamic\n * @param {number | string} providedStartTime\n * @return {number}\n * @private\n */\n function _getStartTimeFromProvidedData(isDynamic, providedStartTime) {\n let referenceTime = 0;\n\n if (!isDynamic) {\n const refStream = getStreams()[0];\n referenceTime = refStream.getStreamInfo().start;\n }\n\n return _getStartTimeFromString(isDynamic, providedStartTime, referenceTime);\n }\n\n\n function _getStartTimeFromString(isDynamic, targetValue, referenceTime) {\n // Consider only start time of MediaRange\n // TODO: consider end time of MediaRange to stop playback at provided end time\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 period = adapter.getRegularPeriods()[0];\n const targetString = targetValue.toString();\n const posix = targetString.indexOf('posix:') !== -1 ? targetString.substring(6) === 'now' ? Date.now() / 1000 : parseFloat(targetString.substring(6)) : NaN;\n let startTime = (isDynamic && !isNaN(posix)) ? timelineConverter.calcPresentationTimeFromWallTime(new Date(posix * 1000), period) : parseFloat(targetString) + referenceTime;\n\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 if (streamsInfo.length === 0) {\n logger.warn(`No periods included in the current manifest. Skipping the filtering of outdated stream objects.`);\n return;\n }\n\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(customParametersModel.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, '') === settings.get().streaming.utcSynchronization.defaultTimingSource.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 _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.customParametersModel) {\n customParametersModel = config.customParametersModel;\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.serviceDescriptionController) {\n serviceDescriptionController = config.serviceDescriptionController;\n }\n if (config.contentSteeringController) {\n contentSteeringController = config.contentSteeringController;\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 providedStartTime = NaN;\n protectionController = null;\n isStreamSwitchingInProgress = false;\n activeStream = null;\n hasMediaError = false;\n hasInitialisationError = false;\n initialPlayback = true;\n initialSteeringRequest = 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(hasMediaError || hasInitialisationError ? PlayListTrace.FAILURE_STOP_REASON : PlayListTrace.USER_REQUEST_STOP_REASON);\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';\nimport Constants from '../constants/Constants';\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 !== Constants.VIDEO && e.mediaType !== Constants.AUDIO)) {\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 * Check if the currentTime exist within the buffered range\n * @param {object} ranges\n * @param {number} currentTime\n * @private\n * @return {boolean}\n */\n function _isTimeBuffered(ranges, currentTime) {\n for(let i = 0, len = ranges.length; i < len; i++) {\n if (currentTime >= ranges.start(i) && currentTime <= ranges.end(i)) {\n return true;\n }\n }\n return false;\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 enableStallFix = settings.get().streaming.gaps.enableStallFix;\n const stallSeek = settings.get().streaming.gaps.stallSeek;\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(enableStallFix && isNaN(seekToPosition) && playbackStalled && isNaN(nextRangeIndex) && _isTimeBuffered(ranges, currentTime)) {\n if (stallSeek === 0) {\n logger.warn(`Toggle play pause to break stall`);\n videoModel.pause();\n videoModel.play();\n } else {\n logger.warn(`Jumping ${stallSeek}s to break stall`);\n seekToPosition = currentTime + stallSeek;\n }\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: ${seekToPosition - start}`);\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 FactoryMaker from '../../core/FactoryMaker';\nimport Debug from '../../core/Debug';\nimport EventBus from '../../core/EventBus';\nimport Constants from '../constants/Constants';\nimport MediaPlayerEvents from '../MediaPlayerEvents';\nimport Events from '../../core/events/Events';\nimport MetricsConstants from '../constants/MetricsConstants';\nimport Utils from '../../core/Utils';\n\nfunction CatchupController() {\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n\n let instance,\n isCatchupSeekInProgress,\n isSafari,\n videoModel,\n settings,\n streamController,\n playbackController,\n mediaPlayerModel,\n playbackStalled,\n logger;\n\n function initialize() {\n _registerEvents();\n _checkPlaybackRates();\n }\n\n function setConfig(config) {\n if (!config) {\n return;\n }\n\n if (config.settings) {\n settings = config.settings;\n }\n\n if (config.videoModel) {\n videoModel = config.videoModel;\n }\n\n if (config.streamController) {\n streamController = config.streamController;\n }\n\n if (config.playbackController) {\n playbackController = config.playbackController;\n }\n\n if (config.mediaPlayerModel) {\n mediaPlayerModel = config.mediaPlayerModel;\n }\n }\n\n function _registerEvents() {\n eventBus.on(MediaPlayerEvents.BUFFER_LEVEL_UPDATED, _onBufferLevelUpdated, 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_SEEKED, _onPlaybackSeeked, instance);\n eventBus.on(Events.SETTING_UPDATED_CATCHUP_ENABLED, _onCatchupSettingUpdated, instance);\n eventBus.on(Events.SETTING_UPDATED_PLAYBACK_RATE_MIN, _checkPlaybackRates, instance);\n eventBus.on(Events.SETTING_UPDATED_PLAYBACK_RATE_MAX, _checkPlaybackRates, instance);\n eventBus.on(MediaPlayerEvents.STREAM_INITIALIZED, _checkPlaybackRates, instance);\n }\n\n function _unregisterEvents() {\n eventBus.off(MediaPlayerEvents.BUFFER_LEVEL_UPDATED, _onBufferLevelUpdated, 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_SEEKED, _onPlaybackProgression, instance);\n eventBus.off(Events.SETTING_UPDATED_CATCHUP_ENABLED, _onCatchupSettingUpdated, instance);\n eventBus.off(Events.SETTING_UPDATED_PLAYBACK_RATE_MIN, _checkPlaybackRates, instance);\n eventBus.off(Events.SETTING_UPDATED_PLAYBACK_RATE_MAX, _checkPlaybackRates, instance);\n eventBus.off(MediaPlayerEvents.STREAM_INITIALIZED, _checkPlaybackRates, instance);\n }\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n\n _resetInitialSettings();\n }\n\n function reset() {\n _unregisterEvents();\n _resetInitialSettings();\n videoModel.setPlaybackRate(1.0, true);\n }\n\n function _resetInitialSettings() {\n isCatchupSeekInProgress = false;\n const ua = Utils.parseUserAgent();\n isSafari = ua && ua.browser && ua.browser.name && ua.browser.name.toLowerCase() === 'safari';\n }\n\n\n function _onPlaybackSeeked() {\n isCatchupSeekInProgress = false;\n }\n\n /**\n * When the buffer level updated we check if we can remove the stalled state\n * @param {object} e\n * @private\n */\n function _onBufferLevelUpdated(e) {\n // do not stop when getting an event from Stream that is not active\n if (e.streamId !== streamController.getActiveStreamInfo().id || !playbackStalled) {\n return;\n }\n\n // we remove the stalled state once we reach a certain buffer level\n const liveDelay = playbackController.getLiveDelay();\n const bufferLevel = playbackController.getBufferLevel();\n if (bufferLevel > liveDelay / 2) {\n playbackStalled = false;\n }\n }\n\n /**\n * When the buffer state changed to BUFFER_EMPTY we update the stalled state\n * @param {object} e\n * @private\n */\n function _onBufferLevelStateChanged(e) {\n // do not stop when getting an event from Stream that is not active\n if (e.streamId !== streamController.getActiveStreamInfo().id) {\n return;\n }\n\n playbackStalled = e.state === MetricsConstants.BUFFER_EMPTY;\n }\n\n /**\n * If the catchup mode is disabled in the settings we reset playback rate to 1.0\n * @private\n */\n function _onCatchupSettingUpdated() {\n if (!mediaPlayerModel.getCatchupModeEnabled()) {\n videoModel.setPlaybackRate(1.0);\n }\n }\n\n /**\n * While playback is progressing we check if we need to start or stop the catchup mechanism to reach the target latency\n * @private\n */\n function _onPlaybackProgression() {\n if (\n playbackController.getIsDynamic() && \n mediaPlayerModel.getCatchupModeEnabled() && \n ((mediaPlayerModel.getCatchupPlaybackRates().max > 0) || (mediaPlayerModel.getCatchupPlaybackRates().min < 0)) && \n !playbackController.isPaused() && \n !playbackController.isSeeking() && _shouldStartCatchUp()\n ) {\n _startPlaybackCatchUp();\n }\n }\n\n /**\n * Apply catchup mode. We either seek back to the target live edge or increase the playback rate.\n */\n function _startPlaybackCatchUp() {\n\n // we are seeking dont do anything for now\n if (isCatchupSeekInProgress) {\n return;\n }\n\n if (videoModel) {\n let newRate;\n const currentPlaybackRate = videoModel.getPlaybackRate();\n const liveCatchupPlaybackRates = mediaPlayerModel.getCatchupPlaybackRates();\n const bufferLevel = playbackController.getBufferLevel();\n const deltaLatency = _getLatencyDrift();\n\n // we reached the maxDrift. Do a seek\n const maxDrift = mediaPlayerModel.getCatchupMaxDrift();\n if (!isNaN(maxDrift) && maxDrift > 0 &&\n deltaLatency > maxDrift) {\n logger.info('[CatchupController]: Low Latency catchup mechanism. Latency too high, doing a seek to live point');\n isCatchupSeekInProgress = true;\n playbackController.seekToCurrentLive(true, false);\n }\n\n // try to reach the target latency by adjusting the playback rate\n else {\n const currentLiveLatency = playbackController.getCurrentLiveLatency();\n const targetLiveDelay = playbackController.getLiveDelay();\n\n if (_getCatchupMode() === Constants.LIVE_CATCHUP_MODE_LOLP) {\n // Custom playback control: Based on buffer level\n const playbackBufferMin = settings.get().streaming.liveCatchup.playbackBufferMin;\n newRate = _calculateNewPlaybackRateLolP(liveCatchupPlaybackRates, currentLiveLatency, targetLiveDelay, playbackBufferMin, bufferLevel);\n } else {\n // Default playback control: Based on target and current latency\n newRate = _calculateNewPlaybackRateDefault(liveCatchupPlaybackRates, currentLiveLatency, targetLiveDelay, bufferLevel);\n }\n\n // We adjust the min change linear, depending on the maximum catchup rate. Default is 0.02 for rate 0.5.\n // For Safari we stick to a fixed value because of https://bugs.webkit.org/show_bug.cgi?id=208142\n const minPlaybackRateChange = isSafari ? 0.25 : 0.02 / (0.5 / liveCatchupPlaybackRates.max);\n\n // Obtain newRate and apply to video model. Don't change playbackrate for small variations (don't overload element with playbackrate changes)\n if (newRate && Math.abs(currentPlaybackRate - newRate) >= minPlaybackRateChange) { // non-null\n logger.debug(`[CatchupController]: Setting playback rate to ${newRate}`);\n videoModel.setPlaybackRate(newRate);\n }\n }\n }\n }\n\n /**\n * Calculates the drift between the current latency and the target latency\n * @return {number}\n * @private\n */\n function _getLatencyDrift() {\n const currentLiveLatency = playbackController.getCurrentLiveLatency();\n const targetLiveDelay = playbackController.getLiveDelay();\n\n return currentLiveLatency - targetLiveDelay;\n }\n\n /**\n * Checks whether the catchup mechanism should be enabled. We use different subfunctions here depending on the catchup mode.\n * @return {boolean}\n */\n function _shouldStartCatchUp() {\n try {\n if (!playbackController.getTime() > 0 || isCatchupSeekInProgress) {\n return false;\n }\n\n const catchupMode = _getCatchupMode();\n\n if (catchupMode === Constants.LIVE_CATCHUP_MODE_LOLP) {\n const currentBuffer = playbackController.getBufferLevel();\n const playbackBufferMin = settings.get().streaming.liveCatchup.playbackBufferMin;\n\n return _lolpNeedToCatchUpCustom(currentBuffer, playbackBufferMin);\n } else {\n return _defaultNeedToCatchUp();\n }\n\n } catch (e) {\n return false;\n }\n }\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 * Default algorithm to determine if catchup mode should be enabled\n * @return {boolean}\n * @private\n */\n function _defaultNeedToCatchUp() {\n try {\n const latencyDrift = Math.abs(_getLatencyDrift());\n\n return latencyDrift > 0;\n } catch (e) {\n return false;\n }\n }\n\n /**\n * LoL+ logic to determine if catchup mode should be enabled\n * @param {number} currentBuffer\n * @param {number} playbackBufferMin\n * @return {boolean}\n * @private\n */\n function _lolpNeedToCatchUpCustom(currentBuffer, playbackBufferMin) {\n try {\n const latencyDrift = Math.abs(_getLatencyDrift());\n\n return latencyDrift > 0 || currentBuffer < playbackBufferMin;\n } catch (e) {\n return false;\n }\n }\n\n /**\n * Default algorithm to calculate the new playback rate\n * @param {object} liveCatchUpPlaybackRates\n * @param {number} liveCatchUpPlaybackRates.min - minimum playback rate decrease limit\n * @param {number} liveCatchUpPlaybackRates.max - maximum playback rate increase limit\n * @param {number} currentLiveLatency\n * @param {number} liveDelay\n * @param {number} bufferLevel\n * @param {number} currentPlaybackRate\n * @return {number}\n * @private\n */\n function _calculateNewPlaybackRateDefault(liveCatchUpPlaybackRates, currentLiveLatency, liveDelay, bufferLevel) {\n // if we recently ran into an empty buffer we wait for the buffer to recover before applying a new rate\n if (playbackStalled) {\n return 1.0;\n }\n\n const deltaLatency = currentLiveLatency - liveDelay;\n const cpr = (deltaLatency < 0) ? Math.abs(liveCatchUpPlaybackRates.min) : liveCatchUpPlaybackRates.max;\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 (playbackController.getPlaybackStalled()) {\n if (bufferLevel <= liveDelay / 2 && deltaLatency > 0) {\n newRate = 1.0;\n }\n }\n\n return newRate;\n }\n\n /**\n * Lol+ algorithm to calculate the new playback rate\n * @param {object} liveCatchUpPlaybackRates\n * @param {number} liveCatchUpPlaybackRates.min - minimum playback rate decrease limit\n * @param {number} liveCatchUpPlaybackRates.max - maximum playback rate increase limit\n * @param {number} currentLiveLatency\n * @param {number} liveDelay\n * @param {number} playbackBufferMin\n * @param {number} bufferLevel\n * @param {number} currentPlaybackRate\n * @return {number}\n * @private\n */\n function _calculateNewPlaybackRateLolP(liveCatchUpPlaybackRates, currentLiveLatency, liveDelay, playbackBufferMin, bufferLevel) {\n let newRate;\n\n // Hybrid: Buffer-based\n if (bufferLevel < playbackBufferMin) {\n // Buffer in danger, slow down\n const cpr = Math.abs(liveCatchUpPlaybackRates.min); // Absolute value as negative delta value will be used.\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 const cpr = liveCatchUpPlaybackRates.max;\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 return newRate\n }\n\n function _checkPlaybackRates() {\n mediaPlayerModel.getCatchupPlaybackRates(true);\n }\n\n instance = {\n reset,\n setConfig,\n initialize\n };\n\n setup();\n\n return instance;\n}\n\nCatchupController.__dashjs_factory_name = 'CatchupController';\nexport default FactoryMaker.getSingletonFactory(CatchupController);\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 '../../streaming/constants/Constants';\nimport DashConstants from '../constants/DashConstants';\n\nconst SUPPORTED_SCHEMES = [Constants.SERVICE_DESCRIPTION_DVB_LL_SCHEME];\nconst MEDIA_TYPES = {\n VIDEO: 'video',\n AUDIO: 'audio',\n ANY: 'any',\n ALL: 'all'\n}\n\nfunction ServiceDescriptionController() {\n const context = this.context;\n\n let instance,\n serviceDescriptionSettings,\n prftOffsets,\n logger,\n adapter;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n _resetInitialSettings();\n }\n\n function setConfig(config) {\n if (!config) return;\n\n if (config.adapter) {\n adapter = config.adapter;\n }\n }\n\n function reset() {\n _resetInitialSettings();\n }\n\n function _resetInitialSettings() {\n serviceDescriptionSettings = {\n liveDelay: NaN,\n liveCatchup: {\n maxDrift: NaN,\n playbackRate: {\n min: NaN,\n max: NaN\n },\n },\n minBitrate: {},\n maxBitrate: {},\n initialBitrate: {}\n };\n prftOffsets = [];\n }\n\n /**\n * Returns the service description settings for latency, catchup and bandwidth\n */\n function getServiceDescriptionSettings() {\n return serviceDescriptionSettings\n }\n\n /**\n * Check for potential ServiceDescriptor elements in the MPD and update the settings accordingly\n * @param {object} manifestInfo\n * @private\n */\n function applyServiceDescription(manifestInfo) {\n if (!manifestInfo || !manifestInfo.serviceDescriptions) {\n return;\n }\n\n const supportedServiceDescriptions = manifestInfo.serviceDescriptions.filter(sd => SUPPORTED_SCHEMES.includes(sd.schemeIdUri));\n const allClientsServiceDescriptions = manifestInfo.serviceDescriptions.filter(sd => sd.schemeIdUri == null);\n let sd = (supportedServiceDescriptions.length > 0)\n ? supportedServiceDescriptions[supportedServiceDescriptions.length - 1]\n : allClientsServiceDescriptions[allClientsServiceDescriptions.length - 1];\n if (!sd) return;\n\n if (sd.latency && sd.latency.target > 0) {\n _applyServiceDescriptionLatency(sd);\n }\n\n if (sd.playbackRate) {\n _applyServiceDescriptionPlaybackRate(sd);\n }\n\n if (sd.operatingQuality) {\n _applyServiceDescriptionOperatingQuality(sd);\n }\n\n if (sd.operatingBandwidth) {\n _applyServiceDescriptionOperatingBandwidth(sd);\n }\n }\n\n /**\n * Adjust the latency targets for the service.\n * @param {object} sd - service description element\n * @private\n */\n function _applyServiceDescriptionLatency(sd) {\n let params;\n\n if (sd.schemeIdUri === Constants.SERVICE_DESCRIPTION_DVB_LL_SCHEME) {\n params = _getDvbServiceDescriptionLatencyParameters(sd);\n } else {\n params = _getStandardServiceDescriptionLatencyParameters(sd);\n }\n\n if (prftOffsets.length > 0) {\n let { to, id } = _calculateTimeOffset(params);\n\n // TS 103 285 Clause 10.20.4. 3) Subtract calculated offset from Latency@target converted from milliseconds\n // liveLatency does not consider ST@availabilityTimeOffset so leave out that step\n // Since maxDrift is a difference rather than absolute it does not need offset applied\n serviceDescriptionSettings.liveDelay = params.liveDelay - to;\n serviceDescriptionSettings.liveCatchup.maxDrift = params.maxDrift;\n\n logger.debug(`\n Found latency properties coming from service description. Applied time offset of ${to} from ProducerReferenceTime element with id ${id}.\n Live Delay: ${params.liveDelay - to}, Live catchup max drift: ${params.maxDrift}\n `);\n } else {\n serviceDescriptionSettings.liveDelay = params.liveDelay;\n serviceDescriptionSettings.liveCatchup.maxDrift = params.maxDrift;\n\n logger.debug(`Found latency properties coming from service description: Live Delay: ${params.liveDelay}, Live catchup max drift: ${params.maxDrift}`);\n }\n }\n\n /**\n * Get default parameters for liveDelay,maxDrift\n * @param {object} sd\n * @return {{maxDrift: (number|undefined), liveDelay: number, referenceId: (number|undefined)}}\n * @private\n */\n function _getStandardServiceDescriptionLatencyParameters(sd) {\n const liveDelay = sd.latency.target / 1000;\n let maxDrift = !isNaN(sd.latency.max) && sd.latency.max > sd.latency.target ? (sd.latency.max - sd.latency.target + 500) / 1000 : NaN;\n const referenceId = sd.latency.referenceId || NaN;\n\n return {\n liveDelay,\n maxDrift,\n referenceId\n }\n }\n\n /**\n * Get DVB DASH parameters for liveDelay,maxDrift\n * @param sd\n * @return {{maxDrift: (number|undefined), liveDelay: number, referenceId: (number|undefined)}}\n * @private\n */\n function _getDvbServiceDescriptionLatencyParameters(sd) {\n const liveDelay = sd.latency.target / 1000;\n let maxDrift = !isNaN(sd.latency.max) && sd.latency.max > sd.latency.target ? (sd.latency.max - sd.latency.target + 500) / 1000 : NaN;\n const referenceId = sd.latency.referenceId || NaN;\n\n return {\n liveDelay,\n maxDrift,\n referenceId\n }\n }\n\n /**\n * Adjust the playback rate targets for the service\n * @param {object} sd\n * @private\n */\n function _applyServiceDescriptionPlaybackRate(sd) {\n // Convert each playback rate into a difference from 1. i.e 0.8 becomes -0.2.\n const min = sd.playbackRate.min ? (Math.round((sd.playbackRate.min - 1.0) * 1000) / 1000) : NaN;\n const max = sd.playbackRate.max ? (Math.round((sd.playbackRate.max - 1.0) * 1000) / 1000) : NaN;\n serviceDescriptionSettings.liveCatchup.playbackRate.min = min;\n serviceDescriptionSettings.liveCatchup.playbackRate.max = max;\n\n logger.debug(`Found latency properties coming from service description: Live catchup min playback rate: ${min}`);\n logger.debug(`Found latency properties coming from service description: Live catchup max playback rate: ${max}`);\n }\n\n /**\n * Used to specify a quality ranking. We do not support this yet.\n * @private\n */\n function _applyServiceDescriptionOperatingQuality() {\n return;\n }\n\n /**\n * Adjust the operating quality targets for the service\n * @param {object} sd\n * @private\n */\n function _applyServiceDescriptionOperatingBandwidth(sd) {\n\n // Aggregation of media types is not supported yet\n if (!sd || !sd.operatingBandwidth || !sd.operatingBandwidth.mediaType || sd.operatingBandwidth.mediaType === MEDIA_TYPES.ALL) {\n return;\n }\n\n const params = {};\n\n params.minBandwidth = sd.operatingBandwidth.min;\n params.maxBandwidth = sd.operatingBandwidth.max;\n params.targetBandwidth = sd.operatingBandwidth.target;\n\n const mediaTypesToApply = [];\n\n if (sd.operatingBandwidth.mediaType === MEDIA_TYPES.VIDEO || sd.operatingBandwidth.mediaType === MEDIA_TYPES.AUDIO) {\n mediaTypesToApply.push(sd.operatingBandwidth.mediaType);\n } else if (sd.operatingBandwidth.mediaType === MEDIA_TYPES.ANY) {\n mediaTypesToApply.push(MEDIA_TYPES.AUDIO);\n mediaTypesToApply.push(MEDIA_TYPES.VIDEO);\n }\n\n mediaTypesToApply.forEach((mediaType) => {\n\n if (!isNaN(params.minBandwidth)) {\n _updateBandwidthSetting('minBitrate', mediaType, params.minBandwidth);\n }\n\n if (!isNaN(params.maxBandwidth)) {\n _updateBandwidthSetting('maxBitrate', mediaType, params.maxBandwidth);\n }\n\n if (!isNaN(params.targetBandwidth)) {\n _updateBandwidthSetting('initialBitrate', mediaType, params.targetBandwidth);\n }\n })\n }\n\n /**\n * Update the bandwidth settings vor a specific field and media type\n * @param {string} field\n * @param {string} mediaType\n * @param {number} value\n * @private\n */\n function _updateBandwidthSetting(field, mediaType, value) {\n try {\n // Service description values are specified in bps. Settings expect the value in kbps\n serviceDescriptionSettings[field][mediaType] = value / 1000;\n } catch (e) {\n logger.error(e);\n }\n }\n\n /**\n * Returns the current calculated time offsets based on ProducerReferenceTime elements\n * @returns {array}\n */\n function getProducerReferenceTimeOffsets() {\n return prftOffsets;\n }\n\n /**\n * Calculates an array of time offsets each with matching ProducerReferenceTime id.\n * Call before applyServiceDescription if producer reference time elements should be considered.\n * @param {array} streamInfos\n * @returns {array}\n * @private\n */\n function calculateProducerReferenceTimeOffsets(streamInfos) {\n try {\n let timeOffsets = [];\n if (streamInfos && streamInfos.length > 0) {\n const mediaTypes = [Constants.VIDEO, Constants.AUDIO, Constants.TEXT];\n const astInSeconds = adapter.getAvailabilityStartTime() / 1000;\n\n streamInfos.forEach((streamInfo) => {\n const offsets = mediaTypes\n .reduce((acc, mediaType) => {\n acc = acc.concat(adapter.getAllMediaInfoForType(streamInfo, mediaType));\n return acc;\n }, [])\n .reduce((acc, mediaInfo) => {\n const prts = adapter.getProducerReferenceTimes(streamInfo, mediaInfo);\n prts.forEach((prt) => {\n const voRepresentations = adapter.getVoRepresentations(mediaInfo);\n if (voRepresentations && voRepresentations.length > 0 && voRepresentations[0].adaptation && voRepresentations[0].segmentInfoType === DashConstants.SEGMENT_TEMPLATE) {\n const voRep = voRepresentations[0];\n const d = new Date(prt[DashConstants.WALL_CLOCK_TIME]);\n const wallClockTime = d.getTime() / 1000;\n // TS 103 285 Clause 10.20.4\n // 1) Calculate PRT0\n // i) take the PRT@presentationTime and subtract any ST@presentationTimeOffset\n // ii) convert this time to seconds by dividing by ST@timescale\n // iii) Add this to start time of period that contains PRT.\n // N.B presentationTimeOffset is already divided by timescale at this point\n const prt0 = wallClockTime - (((prt[DashConstants.PRESENTATION_TIME] / voRep[DashConstants.TIMESCALE]) - voRep[DashConstants.PRESENTATION_TIME_OFFSET]) + streamInfo.start);\n // 2) Calculate TO between PRT at the start of MPD timeline and the AST\n const to = astInSeconds - prt0;\n // 3) Not applicable as liveLatency does not consider ST@availabilityTimeOffset\n acc.push({ id: prt[DashConstants.ID], to });\n }\n });\n return acc;\n }, [])\n\n timeOffsets = timeOffsets.concat(offsets);\n })\n }\n prftOffsets = timeOffsets;\n } catch (e) {\n logger.error(e);\n prftOffsets = [];\n }\n };\n\n /**\n * Calculates offset to apply to live delay as described in TS 103 285 Clause 10.20.4\n * @param {object} sdLatency - service description latency element\n * @returns {number}\n * @private\n */\n function _calculateTimeOffset(sdLatency) {\n let to = 0, id;\n let offset = prftOffsets.filter(prt => {\n return prt.id === sdLatency.referenceId;\n });\n\n // If only one ProducerReferenceTime to generate one TO, then use that regardless of matching ids\n if (offset.length === 0) {\n to = (prftOffsets.length > 0) ? prftOffsets[0].to : 0;\n id = prftOffsets[0].id || NaN;\n } else {\n // If multiple id matches, use the first but this should be invalid\n to = offset[0].to || 0;\n id = offset[0].id || NaN;\n }\n\n return { to, id }\n }\n\n instance = {\n getServiceDescriptionSettings,\n getProducerReferenceTimeOffsets,\n calculateProducerReferenceTimeOffsets,\n applyServiceDescription,\n reset,\n setConfig\n };\n\n setup();\n\n return instance;\n}\n\nServiceDescriptionController.__dashjs_factory_name = 'ServiceDescriptionController';\nexport default FactoryMaker.getSingletonFactory(ServiceDescriptionController);\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 {HTTPRequest} from '../../streaming/vo/metrics/HTTPRequest';\n\nclass ContentSteeringRequest {\n constructor(url) {\n this.url = url || null;\n this.type = HTTPRequest.CONTENT_STEERING_TYPE;\n this.responseType = 'json';\n }\n}\n\nexport default ContentSteeringRequest;\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 ContentSteeringResponse {\n constructor() {\n this.version = null;\n this.ttl = 300;\n this.reloadUri = null;\n this.serviceLocationPriority = [];\n }\n}\n\nexport default ContentSteeringResponse;\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 URLLoader from '../../streaming/net/URLLoader';\nimport Errors from '../../core/errors/Errors';\nimport ContentSteeringRequest from '../vo/ContentSteeringRequest';\nimport ContentSteeringResponse from '../vo/ContentSteeringResponse';\nimport DashConstants from '../constants/DashConstants';\nimport MediaPlayerEvents from '../../streaming/MediaPlayerEvents';\nimport Events from '../../core/events/Events';\nimport Constants from '../../streaming/constants/Constants';\nimport Utils from '../../core/Utils';\nimport URLUtils from '../../streaming/utils/URLUtils';\n\nconst QUERY_PARAMETER_KEYS = {\n THROUGHPUT: '_DASH_throughput',\n PATHWAY: '_DASH_pathway',\n URL: 'url'\n}\n\nfunction ContentSteeringController() {\n const context = this.context;\n const urlUtils = URLUtils(context).getInstance();\n\n let instance,\n logger,\n currentSteeringResponseData,\n activeStreamInfo,\n currentSelectedServiceLocation,\n nextRequestTimer,\n urlLoader,\n errHandler,\n dashMetrics,\n mediaPlayerModel,\n manifestModel,\n requestModifier,\n abrController,\n eventBus,\n adapter;\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n _resetInitialSettings();\n }\n\n function setConfig(config) {\n if (!config) return;\n\n if (config.adapter) {\n adapter = config.adapter;\n }\n if (config.errHandler) {\n errHandler = config.errHandler;\n }\n if (config.dashMetrics) {\n dashMetrics = config.dashMetrics;\n }\n if (config.mediaPlayerModel) {\n mediaPlayerModel = config.mediaPlayerModel;\n }\n if (config.requestModifier) {\n requestModifier = config.requestModifier;\n }\n if (config.manifestModel) {\n manifestModel = config.manifestModel;\n }\n if (config.abrController) {\n abrController = config.abrController;\n }\n if (config.eventBus) {\n eventBus = config.eventBus;\n }\n }\n\n function initialize() {\n urlLoader = URLLoader(context).create({\n errHandler,\n dashMetrics,\n mediaPlayerModel,\n requestModifier,\n errors: Errors\n });\n eventBus.on(MediaPlayerEvents.PERIOD_SWITCH_COMPLETED, _onPeriodSwitchCompleted, instance);\n eventBus.on(Events.FRAGMENT_LOADING_STARTED, _onFragmentLoadingStarted, instance);\n }\n\n function _onPeriodSwitchCompleted(e) {\n if (e && e.toStreamInfo) {\n activeStreamInfo = e.toStreamInfo;\n }\n }\n\n function _onFragmentLoadingStarted(e) {\n if (e && e.request && e.request.serviceLocation) {\n currentSelectedServiceLocation = e.request.serviceLocation;\n }\n }\n\n function getSteeringDataFromManifest() {\n const manifest = manifestModel.getValue()\n return adapter.getContentSteering(manifest);\n }\n\n function shouldQueryBeforeStart() {\n const steeringDataFromManifest = getSteeringDataFromManifest();\n return steeringDataFromManifest && steeringDataFromManifest.queryBeforeStart;\n }\n\n function loadSteeringData() {\n return new Promise((resolve) => {\n try {\n const steeringDataFromManifest = getSteeringDataFromManifest();\n if (!steeringDataFromManifest || !steeringDataFromManifest.serverUrl) {\n resolve();\n return;\n }\n\n const url = _getSteeringServerUrl(steeringDataFromManifest);\n const request = new ContentSteeringRequest(url);\n urlLoader.load({\n request: request,\n success: (data) => {\n _handleSteeringResponse(data);\n eventBus.trigger(MediaPlayerEvents.CONTENT_STEERING_REQUEST_COMPLETED, {\n currentSteeringResponseData,\n url\n });\n resolve();\n },\n error: (e) => {\n _handleSteeringResponseError(e);\n resolve(e);\n }\n });\n } catch (e) {\n resolve(e);\n }\n })\n }\n\n function _getSteeringServerUrl(steeringDataFromManifest) {\n let url = steeringDataFromManifest.proxyServerUrl ? steeringDataFromManifest.proxyServerUrl : steeringDataFromManifest.serverUrl;\n if (currentSteeringResponseData && currentSteeringResponseData.reloadUri) {\n if (urlUtils.isRelative(currentSteeringResponseData.reloadUri)) {\n url = urlUtils.resolve(currentSteeringResponseData.reloadUri, steeringDataFromManifest.serverUrl);\n } else {\n url = currentSteeringResponseData.reloadUri;\n }\n }\n\n const additionalQueryParameter = [];\n\n // Add throughput value to list of query parameters\n if (activeStreamInfo) {\n const isDynamic = adapter.getIsDynamic();\n const mediaType = adapter.getAllMediaInfoForType(activeStreamInfo, Constants.VIDEO).length > 0 ? Constants.VIDEO : Constants.AUDIO;\n const throughputHistory = abrController.getThroughputHistory();\n const throughput = throughputHistory ? throughputHistory.getAverageThroughput(mediaType, isDynamic) : NaN;\n if (!isNaN(throughput)) {\n additionalQueryParameter.push({ key: QUERY_PARAMETER_KEYS.THROUGHPUT, value: throughput * 1000 });\n }\n }\n\n // Ass pathway parameter/currently selected service location to list of query parameters\n if (currentSelectedServiceLocation) {\n additionalQueryParameter.push({ key: QUERY_PARAMETER_KEYS.PATHWAY, value: currentSelectedServiceLocation });\n }\n\n // If we use the value in proxyServerUrl we add the original url as query parameter\n if (steeringDataFromManifest.proxyServerUrl && steeringDataFromManifest.proxyServerUrl === url && steeringDataFromManifest.serverUrl) {\n additionalQueryParameter.push({\n key: QUERY_PARAMETER_KEYS.URL,\n value: encodeURI(steeringDataFromManifest.serverUrl)\n })\n }\n\n url = Utils.addAditionalQueryParameterToUrl(url, additionalQueryParameter);\n return url;\n }\n\n\n function _handleSteeringResponse(data) {\n if (!data || !data[DashConstants.CONTENT_STEERING_RESPONSE.VERSION] || parseInt(data[DashConstants.CONTENT_STEERING_RESPONSE.VERSION]) !== 1) {\n return;\n }\n\n // Update the data for other classes to use\n currentSteeringResponseData = new ContentSteeringResponse();\n currentSteeringResponseData.version = data[DashConstants.CONTENT_STEERING_RESPONSE.VERSION];\n\n if (data[DashConstants.CONTENT_STEERING_RESPONSE.TTL] && !isNaN(data[DashConstants.CONTENT_STEERING_RESPONSE.TTL])) {\n currentSteeringResponseData.ttl = data[DashConstants.CONTENT_STEERING_RESPONSE.TTL];\n }\n if (data[DashConstants.CONTENT_STEERING_RESPONSE.RELOAD_URI]) {\n currentSteeringResponseData.reloadUri = data[DashConstants.CONTENT_STEERING_RESPONSE.RELOAD_URI]\n }\n if (data[DashConstants.CONTENT_STEERING_RESPONSE.SERVICE_LOCATION_PRIORITY]) {\n currentSteeringResponseData.serviceLocationPriority = data[DashConstants.CONTENT_STEERING_RESPONSE.SERVICE_LOCATION_PRIORITY]\n }\n\n _startSteeringRequestTimer();\n }\n\n function _startSteeringRequestTimer() {\n // Start timer for next request\n if (currentSteeringResponseData && currentSteeringResponseData.ttl && !isNaN(currentSteeringResponseData.ttl)) {\n if (nextRequestTimer) {\n clearTimeout(nextRequestTimer);\n }\n nextRequestTimer = setTimeout(() => {\n loadSteeringData();\n }, currentSteeringResponseData.ttl * 1000);\n }\n }\n\n function stopSteeringRequestTimer() {\n if (nextRequestTimer) {\n clearTimeout(nextRequestTimer);\n }\n nextRequestTimer = null;\n }\n\n function _handleSteeringResponseError(e) {\n logger.warn(`Error fetching data from content steering server`, e);\n _startSteeringRequestTimer();\n }\n\n function getCurrentSteeringResponseData() {\n return currentSteeringResponseData;\n }\n\n function reset() {\n _resetInitialSettings();\n eventBus.off(MediaPlayerEvents.PERIOD_SWITCH_COMPLETED, _onPeriodSwitchCompleted, instance);\n eventBus.off(Events.FRAGMENT_LOADING_STARTED, _onFragmentLoadingStarted, instance);\n }\n\n function _resetInitialSettings() {\n currentSteeringResponseData = null;\n activeStreamInfo = null;\n currentSelectedServiceLocation = null;\n stopSteeringRequestTimer()\n }\n\n\n instance = {\n reset,\n setConfig,\n loadSteeringData,\n getCurrentSteeringResponseData,\n shouldQueryBeforeStart,\n getSteeringDataFromManifest,\n stopSteeringRequestTimer,\n initialize\n };\n\n setup();\n\n return instance;\n}\n\nContentSteeringController.__dashjs_factory_name = 'ContentSteeringController';\nexport default FactoryMaker.getSingletonFactory(ContentSteeringController);\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';\nimport bcp47Normalize from 'bcp-47-normalize';\nimport {extendedFilter} from 'bcp-47-match';\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 customParametersModel,\n domStorage;\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 let 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 tracks = Array.from(tracksForType);\n\n tracks = filterTracksBySettings(tracks, matchSettingsLang, settings);\n tracks = filterTracksBySettings(tracks, matchSettingsIndex, settings);\n tracks = filterTracksBySettings(tracks, matchSettingsViewPoint, settings);\n if (!(type === Constants.AUDIO && !!lastSelectedTracks[type])) {\n tracks = filterTracksBySettings(tracks, matchSettingsRole, settings);\n }\n tracks = filterTracksBySettings(tracks, matchSettingsAccessibility, settings);\n tracks = filterTracksBySettings(tracks, matchSettingsAudioChannelConfig, settings);\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]) return;\n\n tracks[id][type].current = track;\n\n if (tracks[id][type].current && ((type !== Constants.TEXT && !isTracksEqual(track, current)) || (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 if (config.customParametersModel) {\n customParametersModel = config.customParametersModel;\n }\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 filterTracksBySettings(tracks, filterFn, settings) {\n let tracksAfterMatcher = [];\n tracks.forEach(function (track) {\n if (filterFn(settings, track)) {\n tracksAfterMatcher.push(track);\n }\n });\n if (tracksAfterMatcher.length !== 0) {\n return tracksAfterMatcher;\n }\n return tracks;\n }\n\n function matchSettingsLang(settings, track) {\n return !settings.lang ||\n (settings.lang instanceof RegExp) ?\n (track.lang.match(settings.lang)) : track.lang !== '' ?\n (extendedFilter(track.lang, bcp47Normalize(settings.lang)).length > 0) : false;\n }\n\n function matchSettingsIndex(settings, track) {\n return (settings.index === undefined) || (settings.index === null) || (track.index === settings.index);\n }\n\n function matchSettingsViewPoint(settings, track) {\n return !settings.viewpoint || (settings.viewpoint === track.viewpoint);\n }\n\n function matchSettingsRole(settings, track, isTrackActive = false) {\n const matchRole = !settings.role || !!track.roles.filter(function (item) {\n return item === settings.role;\n })[0];\n return (matchRole || (track.type === Constants.AUDIO && isTrackActive));\n }\n\n function matchSettingsAccessibility(settings, track) {\n let matchAccessibility;\n\n if (!settings.accessibility) {\n // if no accessibility is requested (or request is empty string),\n // match only those tracks having no accessibility element present\n matchAccessibility = !track.accessibility.length;\n } else {\n matchAccessibility = !!track.accessibility.filter(function (item) {\n return item === settings.accessibility;\n })[0];\n }\n\n return matchAccessibility;\n }\n\n function matchSettingsAudioChannelConfig(settings, track) {\n let matchAudioChannelConfiguration = !settings.audioChannelConfiguration || !!track.audioChannelConfiguration.filter(function (item) {\n return item === settings.audioChannelConfiguration;\n })[0];\n\n return matchAudioChannelConfiguration;\n }\n\n function matchSettings(settings, track, isTrackActive = false) {\n try {\n let matchLang = false;\n\n // If there is no language defined in the target settings we got a match\n if (!settings.lang) {\n matchLang = true;\n }\n\n // If the target language is provided as a RegExp apply match function\n else if (settings.lang instanceof RegExp) {\n matchLang = track.lang.match(settings.lang);\n }\n\n // If the track has a language and we can normalize the target language check if we got a match\n else if (track.lang !== '') {\n const normalizedSettingsLang = bcp47Normalize(settings.lang);\n if (normalizedSettingsLang) {\n matchLang = extendedFilter(track.lang, normalizedSettingsLang).length > 0\n }\n }\n\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 } catch (e) {\n return false;\n logger.error(e);\n }\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 selectInitialTrack(type, tracks) {\n if (type === Constants.TEXT) return tracks[0];\n\n let mode = settings.get().streaming.selectionModeForInitialTrack;\n let tmpArr;\n const customInitialTrackSelectionFunction = customParametersModel.getCustomInitialTrackSelectionFunction();\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 setInitialSettings,\n getInitialSettings,\n getTracksWithHighestBitrate,\n getTracksWithHighestEfficiency,\n getTracksWithWidestRange,\n isTracksEqual,\n matchSettings,\n matchSettingsLang,\n matchSettingsIndex,\n matchSettingsViewPoint,\n matchSettingsRole,\n matchSettingsAccessibility,\n matchSettingsAudioChannelConfig,\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 FactoryMaker from '../../../core/FactoryMaker';\nimport ContentSteeringController from '../../../dash/controllers/ContentSteeringController';\n\nfunction ContentSteeringSelector() {\n\n const context = this.context;\n let instance,\n contentSteeringController,\n blacklistController;\n\n function setup() {\n contentSteeringController = ContentSteeringController(context).getInstance();\n }\n\n function setConfig(config) {\n if (config.blacklistController) {\n blacklistController = config.blacklistController;\n }\n if (config.contentSteeringController) {\n contentSteeringController = config.contentSteeringController;\n }\n }\n\n function selectBaseUrlIndex(data) {\n let steeringIndex = NaN;\n\n // In case we dont have a selected idx yet we consider the defaultServiceLocation\n if (isNaN(data.selectedIdx)) {\n const steeringDataFromMpd = contentSteeringController.getSteeringDataFromManifest();\n if (steeringDataFromMpd && steeringDataFromMpd.defaultServiceLocation) {\n steeringIndex = _findexIndexOfServiceLocation([steeringDataFromMpd.defaultServiceLocation], data.baseUrls);\n }\n }\n\n // Search in the response data of the steering server\n const currentSteeringResponseData = contentSteeringController.getCurrentSteeringResponseData();\n if (data.baseUrls && data.baseUrls.length && currentSteeringResponseData &&\n currentSteeringResponseData.serviceLocationPriority && currentSteeringResponseData.serviceLocationPriority.length) {\n steeringIndex = _findexIndexOfServiceLocation(currentSteeringResponseData.serviceLocationPriority, data.baseUrls);\n }\n\n return steeringIndex;\n }\n\n function _findexIndexOfServiceLocation(serviceLocationPriorities = [], baseUrls = []) {\n let i = 0;\n let steeringIndex = NaN;\n while (i < serviceLocationPriorities.length) {\n const curr = serviceLocationPriorities[i];\n const idx = baseUrls.findIndex((elem) => {\n return elem.serviceLocation && elem.serviceLocation === curr;\n })\n if (idx !== -1 && !blacklistController.contains(baseUrls[idx].serviceLocation)) {\n steeringIndex = idx;\n break;\n }\n i += 1;\n }\n return steeringIndex;\n }\n\n instance = {\n selectBaseUrlIndex,\n setConfig\n };\n\n setup();\n\n return instance;\n}\n\nContentSteeringSelector.__dashjs_factory_name = 'ContentSteeringSelector';\nexport default FactoryMaker.getClassFactory(ContentSteeringSelector);\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';\nimport ContentSteeringSelector from './baseUrlResolution/ContentSteeringSelector';\nimport Settings from '../../core/Settings';\n\nfunction BaseURLSelector() {\n\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n const settings = Settings(context).getInstance();\n\n let instance,\n serviceLocationBlacklistController,\n basicSelector,\n dvbSelector,\n contentSteeringSelector,\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 contentSteeringSelector = ContentSteeringSelector(context).create();\n contentSteeringSelector.setConfig({\n blacklistController: serviceLocationBlacklistController\n })\n\n selector = basicSelector;\n }\n\n function setConfig(config) {\n if (config.selector) {\n selector = config.selector;\n }\n if (config.contentSteeringSelector) {\n contentSteeringSelector = config.contentSteeringSelector;\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\n // Check if we got any instructions from the content steering element in the MPD or from the content steering server\n if(settings.get().streaming.applyContentSteering) {\n const steeringIndex = contentSteeringSelector.selectBaseUrlIndex(data);\n if (!isNaN(steeringIndex) && steeringIndex !== -1) {\n data.selectedIdx = steeringIndex;\n }\n }\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(data.selectedIdx)) {\n return data.baseUrls[data.selectedIdx];\n }\n\n let selectedBaseUrl = selector.select(data.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 = data.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 settings = config.settings;\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 requestTimeout: config.settings.get().streaming.manifestRequestTimeout\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 // If there is a mismatch between the manifest's specified duration and the total duration of all periods,\n // and the specified duration is greater than the total duration of all periods,\n // overwrite the manifest's duration attribute. This is a patch for if a manifest is generated incorrectly.\n if (settings &&\n settings.get().streaming.enableManifestDurationMismatchFix &&\n manifest.mediaPresentationDuration &&\n manifest.Period_asArray.length > 1) {\n const sumPeriodDurations = manifest.Period_asArray.reduce((totalDuration, period) => totalDuration + period.duration, 0);\n if (!isNaN(sumPeriodDurations) && manifest.mediaPresentationDuration > sumPeriodDurations) {\n logger.warn('Media presentation duration greater than duration of all periods. Setting duration to total period duration');\n manifest.mediaPresentationDuration = sumPeriodDurations;\n }\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';\nimport EventBus from '../../core/EventBus';\nimport Events from '../../core/events/Events';\n\nfunction CapabilitiesFilter() {\n\n const context = this.context;\n const eventBus = EventBus(context).getInstance();\n\n let instance,\n adapter,\n capabilities,\n settings,\n customParametersModel,\n logger;\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 if (config.customParametersModel) {\n customParametersModel = config.customParametersModel;\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 eventBus.trigger(Events.ADAPTATION_SET_REMOVED_NO_CAPABILITIES, {\n adaptationSet: as\n });\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 const customCapabilitiesFilters = customParametersModel.getCustomCapabilitiesFilters();\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 instance = {\n setConfig,\n filterUnsupportedFeatures\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 */\nimport Debug from '../../core/Debug';\nimport FactoryMaker from '../../core/FactoryMaker';\nimport Settings from '../../core/Settings';\n\nconst DEFAULT_MIN_BUFFER_TIME = 12;\nconst DEFAULT_MIN_BUFFER_TIME_FAST_SWITCH = 20;\nconst LOW_LATENCY_REDUCTION_FACTOR = 10;\nconst LOW_LATENCY_MULTIPLY_FACTOR = 5;\nconst DEFAULT_CATCHUP_MAX_DRIFT = 12;\nconst DEFAULT_CATCHUP_PLAYBACK_RATE_MIN = -0.5;\nconst DEFAULT_CATCHUP_PLAYBACK_RATE_MAX = 0.5;\nconst CATCHUP_PLAYBACK_RATE_MIN_LIMIT = -0.5;\nconst CATCHUP_PLAYBACK_RATE_MAX_LIMIT = 1;\n\n/**\n * We use this model as a wrapper/proxy between Settings.js and classes that are using parameters from Settings.js.\n * In some cases we require additional logic to be applied and the settings might need to be adjusted before being used.\n * @class\n * @constructor\n */\nfunction MediaPlayerModel() {\n\n let instance,\n logger,\n playbackController,\n serviceDescriptionController;\n\n const context = this.context;\n const settings = Settings(context).getInstance();\n\n function setup() {\n logger = Debug(context).getInstance().getLogger(instance);\n }\n\n function setConfig(config) {\n if (config.playbackController) {\n playbackController = config.playbackController;\n }\n if (config.serviceDescriptionController) {\n serviceDescriptionController = config.serviceDescriptionController;\n }\n }\n\n /**\n * Checks the supplied min playback rate is a valid vlaue and within supported limits\n * @param {number} rate - Supplied min playback rate \n * @param {boolean} log - wether to shown warning or not \n * @returns {number} corrected min playback rate\n */\n function _checkMinPlaybackRate (rate, log) {\n if (isNaN(rate)) return 0;\n if (rate > 0) {\n if (log) {\n logger.warn(`Supplied minimum playback rate is a positive value when it should be negative or 0. The supplied rate will not be applied and set to 0: 100% playback speed.`)\n }\n return 0;\n } \n if (rate < CATCHUP_PLAYBACK_RATE_MIN_LIMIT) {\n if (log) {\n logger.warn(`Supplied minimum playback rate is out of range and will be limited to ${CATCHUP_PLAYBACK_RATE_MIN_LIMIT}: ${CATCHUP_PLAYBACK_RATE_MIN_LIMIT * 100}% playback speed.`);\n }\n return CATCHUP_PLAYBACK_RATE_MIN_LIMIT;\n }\n return rate;\n };\n\n /**\n * Checks the supplied max playback rate is a valid vlaue and within supported limits\n * @param {number} rate - Supplied max playback rate \n * @param {boolean} log - wether to shown warning or not \n * @returns {number} corrected max playback rate\n */\n function _checkMaxPlaybackRate (rate, log) {\n if (isNaN(rate)) return 0;\n if (rate < 0) {\n if (log) {\n logger.warn(`Supplied maximum playback rate is a negative value when it should be negative or 0. The supplied rate will not be applied and set to 0: 100% playback speed.`)\n }\n return 0;\n } \n if (rate > CATCHUP_PLAYBACK_RATE_MAX_LIMIT) {\n if (log) {\n logger.warn(`Supplied maximum playback rate is out of range and will be limited to ${CATCHUP_PLAYBACK_RATE_MAX_LIMIT}: ${(1 + CATCHUP_PLAYBACK_RATE_MAX_LIMIT) * 100}% playback speed.`);\n }\n return CATCHUP_PLAYBACK_RATE_MAX_LIMIT;\n }\n return rate;\n };\n\n /**\n * Returns the maximum drift allowed before applying a seek back to the live edge when the catchup mode is enabled\n * @return {number}\n */\n function getCatchupMaxDrift() {\n if (!isNaN(settings.get().streaming.liveCatchup.maxDrift) && settings.get().streaming.liveCatchup.maxDrift > 0) {\n return settings.get().streaming.liveCatchup.maxDrift;\n }\n\n const serviceDescriptionSettings = serviceDescriptionController.getServiceDescriptionSettings();\n if (serviceDescriptionSettings && serviceDescriptionSettings.liveCatchup && !isNaN(serviceDescriptionSettings.liveCatchup.maxDrift) && serviceDescriptionSettings.liveCatchup.maxDrift > 0) {\n return serviceDescriptionSettings.liveCatchup.maxDrift;\n }\n\n return DEFAULT_CATCHUP_MAX_DRIFT;\n }\n\n /**\n * Returns the minimum and maximum playback rates to be used when applying the catchup mechanism\n * If only one of the min/max values has been set then the other will default to 0 (no playback rate change).\n * @return {number}\n */\n function getCatchupPlaybackRates(log) {\n const settingsPlaybackRate = settings.get().streaming.liveCatchup.playbackRate;\n \n if(!isNaN(settingsPlaybackRate.min) || !isNaN(settingsPlaybackRate.max)) {\n return {\n min: _checkMinPlaybackRate(settingsPlaybackRate.min, log),\n max: _checkMaxPlaybackRate(settingsPlaybackRate.max, log),\n }\n }\n\n const serviceDescriptionSettings = serviceDescriptionController.getServiceDescriptionSettings();\n if (serviceDescriptionSettings && serviceDescriptionSettings.liveCatchup && (!isNaN(serviceDescriptionSettings.liveCatchup.playbackRate.min) || !isNaN(serviceDescriptionSettings.liveCatchup.playbackRate.max))) {\n const sdPlaybackRate = serviceDescriptionSettings.liveCatchup.playbackRate;\n return {\n min: _checkMinPlaybackRate(sdPlaybackRate.min, log),\n max: _checkMaxPlaybackRate(sdPlaybackRate.max, log),\n }\n }\n\n return {\n min: DEFAULT_CATCHUP_PLAYBACK_RATE_MIN,\n max: DEFAULT_CATCHUP_PLAYBACK_RATE_MAX\n }\n }\n\n /**\n * Returns whether the catchup mode is activated via the settings or internally in the PlaybackController\n * @return {boolean}\n */\n function getCatchupModeEnabled() {\n if (settings.get().streaming.liveCatchup.enabled !== null) {\n return settings.get().streaming.liveCatchup.enabled;\n }\n\n return playbackController.getInitialCatchupModeActivated();\n }\n\n /**\n * Returns the min,max or initial bitrate for a specific media type.\n * @param {string} field\n * @param {string} mediaType\n */\n function getAbrBitrateParameter(field, mediaType) {\n try {\n const setting = settings.get().streaming.abr[field][mediaType];\n if(!isNaN(setting) && setting !== -1) {\n return setting;\n }\n\n const serviceDescriptionSettings = serviceDescriptionController.getServiceDescriptionSettings();\n if(serviceDescriptionSettings && serviceDescriptionSettings[field] && !isNaN(serviceDescriptionSettings[field][mediaType])) {\n return serviceDescriptionSettings[field][mediaType];\n }\n\n return -1;\n }\n catch(e) {\n return -1;\n }\n }\n\n /**\n * Returns the initial buffer level taking the stable buffer time into account\n * @return {number}\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 /**\n * Returns the stable buffer time taking the live delay into account\n * @return {number}\n */\n function getStableBufferTime() {\n let stableBufferTime = settings.get().streaming.buffer.stableBufferTime > 0 ? settings.get().streaming.buffer.stableBufferTime : settings.get().streaming.buffer.fastSwitchEnabled ? DEFAULT_MIN_BUFFER_TIME_FAST_SWITCH : DEFAULT_MIN_BUFFER_TIME;\n const liveDelay = playbackController.getLiveDelay();\n\n return !isNaN(liveDelay) && liveDelay > 0 ? Math.min(stableBufferTime, liveDelay) : stableBufferTime;\n }\n\n /**\n * Returns the number of retry attempts for a specific media type\n * @param type\n * @return {number}\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 playbackController.getLowLatencyModeEnabled() ? settings.get().streaming.retryAttempts[type] * lowLatencyMultiplyFactor : settings.get().streaming.retryAttempts[type];\n }\n\n /**\n * Returns the retry interval for a specific media type\n * @param type\n * @return {number}\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 playbackController.getLowLatencyModeEnabled() ? settings.get().streaming.retryIntervals[type] / lowLatencyReductionFactor : settings.get().streaming.retryIntervals[type];\n }\n\n function reset() {\n }\n\n instance = {\n getCatchupMaxDrift,\n getCatchupModeEnabled,\n getStableBufferTime,\n getInitialBufferLevel,\n getRetryAttemptsForType,\n getRetryIntervalsForType,\n getCatchupPlaybackRates,\n getAbrBitrateParameter,\n setConfig,\n reset\n };\n\n setup();\n\n return instance;\n}\n\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[streamId];\n lastDroppedFrames[streamId] = droppedVideoFrames;\n\n let intervalTotalFrames = totalVideoFrames - lastTotalFrames[streamId];\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 let throughputMeasureTime = 0, throughput = 0;\n\n if (httpRequest._fileLoaderType && httpRequest._fileLoaderType === Constants.FILE_LOADER_TYPES.FETCH) {\n throughputMeasureTime = httpRequest.trace.reduce((a, b) => a + b.d, 0);\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 customParametersModel,\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\n });\n\n abrRulesCollection = ABRRulesCollection(context).create({\n dashMetrics,\n customParametersModel,\n mediaPlayerModel,\n 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.customParametersModel) {\n customParametersModel = config.customParametersModel;\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 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 = mediaPlayerModel.getAbrBitrateParameter('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 = mediaPlayerModel.getAbrBitrateParameter('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_asArray;\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 = mediaPlayerModel.getAbrBitrateParameter('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_asArray;\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 try {\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 } catch (e) {\n logger.error(e);\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 _currentTime,\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 _currentTime = NaN;\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 _currentTime = currentTime;\n waitForReadyState(Constants.VIDEO_ELEMENT_READY_STATES.HAVE_METADATA, () => {\n if (element) {\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 _currentTime = NaN;\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 _currentTime = NaN;\n } catch (e) {\n if (element.readyState === 0 && e.code === e.INVALID_STATE_ERR) {\n setTimeout(function () {\n element.currentTime = _currentTime;\n _currentTime = NaN;\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 || !isNaN(_currentTime)) : null;\n }\n\n function getTime() {\n return element ? (!isNaN(_currentTime) ? _currentTime : 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 checkConfig();\n\n if (!settings.get().streaming.lastMediaSettingsCachingInfo.enabled) {\n return null;\n }\n\n let mediaSettings = null;\n\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 checkConfig();\n\n if (!settings.get().streaming.lastBitrateCachingInfo.enabled) {\n return NaN;\n }\n\n let savedBitrate = NaN;\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,\n setSavedBitrateSettings,\n getSavedMediaSettings,\n 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);\n","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 this.supplementalProperties = {};\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';\nimport bcp47Normalize from 'bcp-47-normalize';\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 * Returns the ProducerReferenceTimes as saved in the DashManifestModel if present\n * @param {object} streamInfo\n * @param {object} mediaInfo\n * @returns {object} producerReferenceTimes\n * @memberOf module:DashAdapter\n * @instance\n */\n function getProducerReferenceTimes(streamInfo, mediaInfo) {\n let id, realAdaptation;\n\n const selectedVoPeriod = getPeriodForStreamInfo(streamInfo, voPeriods);\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 if (!realAdaptation) return [];\n return dashManifestModel.getProducerReferenceTimesForAdaptation(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 - Specified in seconds\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 // The PTO in voRepresentation is already specified in seconds\n const presentationTimeOffset = !isNaN(voRepresentation.presentationTimeOffset) ? voRepresentation.presentationTimeOffset : !isNaN(eventStream.presentationTimeOffset) ? eventStream.presentationTimeOffset : 0;\n // In case of version 1 events the presentation_time is parsed as presentation_time_delta\n let presentationTimeDelta = eventBox.presentation_time_delta / timescale;\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 / timescale;\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, streamInfo) {\n let events = [];\n\n if (voPeriods.length > 0) {\n const manifest = voPeriods[0].mpd.manifest;\n\n if (info instanceof StreamInfo) {\n const period = getPeriodForStreamInfo(info, voPeriods)\n events = dashManifestModel.getEventsForPeriod(period);\n } else if (info instanceof MediaInfo) {\n const period = getPeriodForStreamInfo(streamInfo, voPeriods)\n events = dashManifestModel.getEventStreamForAdaptationSet(manifest, getAdaptationForMediaInfo(info), period);\n } else if (info instanceof RepresentationInfo) {\n const period = getPeriodForStreamInfo(streamInfo, voPeriods)\n events = dashManifestModel.getEventStreamForRepresentation(manifest, voRepresentation, period);\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 ContentSteering element of the MPD\n * @param {object} manifest\n * @returns {object} contentSteering\n * @memberOf module:DashAdapter\n * @instance\n */\n function getContentSteering(manifest) {\n return dashManifestModel.getContentSteering(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 => {\n cp.keyId = keyId;\n });\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 = bcp47Normalize(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 getProducerReferenceTimes,\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 getContentSteering,\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) {\n let vo = new HTTPRequestTrace();\n\n vo.s = s;\n vo.d = d;\n vo.b = b;\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, fileLoaderType) {\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 fileLoaderType\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 vo._fileLoaderType = fileLoaderType;\n\n if (traces) {\n traces.forEach(trace => {\n appendHttpTrace(vo, trace.s, trace.d, trace.b);\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 request.fileLoaderType);\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 * (1 + repeat);\n }\n\n range.end = calcPresentationTimeFromMediaTime((segments[0].t + d) / timescale, voRepresentation);\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({\n 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 try {\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 catch(e) {\n logger.error(e);\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, strict = true) {\n return (isNaN(start) || (strict ? cue.startTime : cue.endTime) >= start) && (isNaN(end) || (strict ? cue.endTime : cue.startTime) <= end);\n }\n\n function deleteTrackCues(track, start, end, strict = true) {\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, strict)) {\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, false);\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 allTracksAreDisabled,\n forceTextStreaming,\n textTracksAdded,\n disableTextBeforeTextTracksAdded;\n\n function setup() {\n forceTextStreaming = false;\n textTracksAdded = 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.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 _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 const currentTrack = mediaController.getCurrentTrackFor(Constants.TEXT, streamId);\n if (currentTrack) {\n const defaultSettings = {\n lang: currentTrack.lang,\n role: currentTrack.roles[0],\n index: currentTrack.index,\n codec: currentTrack.codec,\n accessibility: currentTrack.accessibility[0]\n };\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 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.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 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 CatchupController from './controllers/CatchupController';\nimport ServiceDescriptionController from '../dash/controllers/ServiceDescriptionController';\nimport ContentSteeringController from '../dash/controllers/ContentSteeringController';\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';\nimport CustomParametersModel from './models/CustomParametersModel';\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 customParametersModel,\n errHandler,\n baseURLController,\n capabilities,\n capabilitiesFilter,\n streamController,\n textController,\n gapController,\n playbackController,\n serviceDescriptionController,\n contentSteeringController,\n catchupController,\n dashMetrics,\n manifestModel,\n cmcdModel,\n videoModel,\n uriFragmentModel,\n domStorage,\n segmentBaseController;\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 customParametersModel = CustomParametersModel(context).getInstance();\n videoModel = VideoModel(context).getInstance();\n uriFragmentModel = URIFragmentModel(context).getInstance();\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.serviceDescriptionController) {\n serviceDescriptionController = config.serviceDescriptionController\n }\n if (config.contentSteeringController) {\n contentSteeringController = config.contentSteeringController;\n }\n if (config.catchupController) {\n catchupController = config.catchupController;\n }\n if (config.mediaPlayerModel) {\n mediaPlayerModel = config.mediaPlayerModel;\n }\n if (config.customParametersModel) {\n customParametersModel = config.customParametersModel;\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 * @param {number|string} startTime - For VoD content the start time is relative to the start time of the first period.\n * For live content\n * If the parameter starts from prefix posix: it signifies the absolute time range defined in seconds of Coordinated Universal Time (ITU-R TF.460-6). This is the number of seconds since 01-01-1970 00:00:00 UTC. Fractions of seconds may be optionally specified down to the millisecond level.\n * If no posix prefix is used the starttime is relative to MPD@availabilityStartTime\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, startTime = NaN) {\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 (!catchupController) {\n catchupController = CatchupController(context).getInstance();\n }\n\n if (!serviceDescriptionController) {\n serviceDescriptionController = ServiceDescriptionController(context).getInstance();\n }\n\n if (!contentSteeringController) {\n contentSteeringController = ContentSteeringController(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\n });\n\n serviceDescriptionController.setConfig({\n 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,\n settings,\n customParametersModel\n });\n\n mediaPlayerModel.setConfig({\n playbackController,\n serviceDescriptionController\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, startTime);\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 if (customParametersModel) {\n customParametersModel.reset();\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 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(true);\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 * For dynamic streams duration() returns DVRWindow.end - DVRWindow.start. Consequently, the value provided to this function should be relative to DVRWindow.start.\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\n // For VoD limit the seek to the duration of the content\n const videoElement = getVideoElement();\n if (!playbackController.getIsDynamic() && videoElement.duration) {\n s = Math.min(videoElement.duration, s);\n }\n\n playbackController.seek(s, false, false, true);\n }\n\n /**\n * Seeks back to the original live edge (live edge as calculated at playback start). Only applies to live streams, for VoD streams this call will be ignored.\n */\n function seekToOriginalLive() {\n if (!playbackInitialized || !isDynamic()) {\n return;\n }\n\n playbackController.seekToOriginalLive();\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 * Returns a boolean that indicates whether the player is operating in low latency mode.\n * @return {boolean}\n * @memberof module:MediaPlayer\n * @instance\n */\n function getLowLatencyModeEnabled() {\n if (!playbackInitialized) {\n throw PLAYBACK_NOT_INITIALIZED_ERROR;\n }\n return playbackController.getLowLatencyModeEnabled();\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.getOriginalLiveDelay();\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 * Returns the target live delay\n * @returns {number} The target live delay\n * @memberof module:MediaPlayer\n * @instance\n */\n function getTargetLiveDelay() {\n if (!playbackInitialized) {\n throw PLAYBACK_NOT_INITIALIZED_ERROR;\n }\n\n return playbackController.getOriginalLiveDelay();\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 customParametersModel.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 customParametersModel.removeAbrCustomRule(rulename);\n }\n\n /**\n * Remove all ABR custom rules\n * @memberof module:MediaPlayer\n * @instance\n */\n function removeAllABRCustomRule() {\n customParametersModel.removeAllAbrCustomRule();\n }\n\n /**\n * Returns all ABR custom rules\n * @return {Array}\n */\n function getABRCustomRules() {\n return customParametersModel.getAbrCustomRules();\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 customParametersModel.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 customParametersModel.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 customParametersModel.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 customParametersModel.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 customParametersModel.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 customParametersModel.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 primitive, a string object, or a RegExp object 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 Custom filter and callback functions\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 customParametersModel.registerCustomCapabilitiesFilter(filter);\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 customParametersModel.unregisterCustomCapabilitiesFilter(filter);\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 customParametersModel.setCustomInitialTrackSelectionFunction(customFunc);\n }\n\n /**\n * Resets the custom initial track selection\n */\n function resetCustomInitialTrackSelectionFunction() {\n customParametersModel.resetCustomInitialTrackSelectionFunction(null);\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 customParametersModel.registerLicenseRequestFilter(filter);\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 customParametersModel.registerLicenseResponseFilter(filter);\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 customParametersModel.unregisterLicenseRequestFilter(filter);\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 customParametersModel.unregisterLicenseResponseFilter(filter);\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 ---------------------------------------------------------------------------\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 return thumbnailController.provide(s, 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 * Sets the source to a new manifest URL or object without reloading\n * Useful for updating CDN tokens\n * @param urlOrManifest\n */\n function updateSource(urlOrManifest) {\n source = urlOrManifest\n streamController.load(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 * @param {number|string} startTime - For VoD content the start time is relative to the start time of the first period.\n * For live content\n * If the parameter starts from prefix posix: it signifies the absolute time range defined in seconds of Coordinated Universal Time (ITU-R TF.460-6). This is the number of seconds since 01-01-1970 00:00:00 UTC. Fractions of seconds may be optionally specified down to the millisecond level.\n * If no posix prefix is used the starttime is relative to MPD@availabilityStartTime\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, startTime = NaN) {\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(startTime);\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 * Triggers a request to the content steering server to update the steering information.\n * @return {Promise<any>}\n */\n function triggerSteeringRequest() {\n if (contentSteeringController) {\n return contentSteeringController.loadSteeringData();\n }\n }\n\n /**\n * Returns the current response data of the content steering server\n * @return {object}\n */\n function getCurrentSteeringResponseData() {\n if (contentSteeringController) {\n return contentSteeringController.getCurrentSteeringResponseData();\n }\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 catchupController.reset();\n playbackController.reset();\n serviceDescriptionController.reset();\n contentSteeringController.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 customParametersModel,\n adapter,\n settings,\n manifestModel,\n errHandler\n });\n\n streamController.setConfig({\n capabilities,\n capabilitiesFilter,\n manifestLoader,\n manifestModel,\n mediaPlayerModel,\n customParametersModel,\n protectionController,\n textController,\n adapter,\n dashMetrics,\n errHandler,\n timelineConverter,\n videoModel,\n playbackController,\n serviceDescriptionController,\n contentSteeringController,\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 serviceDescriptionController,\n dashMetrics,\n adapter,\n videoModel,\n timelineConverter,\n settings\n });\n\n catchupController.setConfig({\n streamController,\n playbackController,\n mediaPlayerModel,\n videoModel,\n settings\n })\n\n abrController.setConfig({\n streamController,\n domStorage,\n mediaPlayerModel,\n customParametersModel,\n dashMetrics,\n adapter,\n videoModel,\n settings\n });\n\n cmcdModel.setConfig({\n abrController,\n dashMetrics,\n playbackController\n });\n\n contentSteeringController.setConfig({\n adapter,\n errHandler,\n dashMetrics,\n mediaPlayerModel,\n manifestModel,\n abrController,\n eventBus,\n requestModifier: RequestModifier(context).getInstance()\n })\n\n // initialises controller\n abrController.initialize();\n streamController.initialize(autoPlay, protectionData);\n textController.initialize();\n gapController.initialize();\n catchupController.initialize();\n cmcdModel.initialize();\n contentSteeringController.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,\n errHandler,\n videoModel,\n customParametersModel,\n capabilities,\n eventBus,\n events: Events,\n BASE64,\n constants: Constants,\n cmcdModel,\n settings\n });\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 mediaPlayerModel: mediaPlayerModel,\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 /**\n *\n * @private\n */\n function _initializePlayback(startTime = NaN) {\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, startTime);\n } else {\n streamController.loadWithManifest(source, startTime);\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 getLowLatencyModeEnabled,\n seek,\n seekToOriginalLive,\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 getTargetLiveDelay,\n convertToTimeCode,\n formatUTC,\n getVersion,\n getDebug,\n getBufferLength,\n getTTMLRenderingDiv,\n getVideoElement,\n getSource,\n updateSource,\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 getABRCustomRules,\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 triggerSteeringRequest,\n getCurrentSteeringResponseData,\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","'use strict'\n\nmodule.exports = alphabetical\n\n// Check if the given character code, or the character code at the first\n// character, is alphabetical.\nfunction alphabetical(character) {\n var code = typeof character === 'string' ? character.charCodeAt(0) : character\n\n return (\n (code >= 97 && code <= 122) /* a-z */ ||\n (code >= 65 && code <= 90) /* A-Z */\n )\n}\n","'use strict'\n\nmodule.exports = decimal\n\n// Check if the given character code, or the character code at the first\n// character, is decimal.\nfunction decimal(character) {\n var code = typeof character === 'string' ? character.charCodeAt(0) : character\n\n return code >= 48 && code <= 57 /* 0-9 */\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 Matches and converts any ISO 639 language tag to BCP-47 language tags\n */\nimport BaseMatcher from './BaseMatcher';\nimport DashConstants from '../../constants/DashConstants';\nimport bcp47Normalize from 'bcp-47-normalize';\n\nclass LangMatcher extends BaseMatcher {\n constructor() {\n super(\n (attr, nodeName) => {\n const stringAttrsInElements = {\n [DashConstants.ADAPTATION_SET]: [ DashConstants.LANG ],\n [DashConstants.REPRESENTATION]: [ DashConstants.LANG ],\n [DashConstants.CONTENT_COMPONENT]: [ DashConstants.LANG ],\n [DashConstants.LABEL]: [ DashConstants.LANG ],\n [DashConstants.GROUP_LABEL]: [ DashConstants.LANG ]\n // still missing from 23009-1: Preselection@lang, ProgramInformation@lang\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 => {\n let lang = bcp47Normalize(str);\n if (lang !== undefined) {\n return lang;\n }\n return String(str);\n }\n );\n }\n}\n\nexport default LangMatcher;\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 LangMatcher from './matchers/LangMatcher';\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 LangMatcher(),\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, { request: request, exists: success }\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}","'use strict'\n\nvar bcp47 = require('bcp-47')\nvar match = require('bcp-47-match')\nvar matches = require('./matches.json')\nvar fields = require('./fields.json')\nvar defaults = require('./defaults.json')\nvar many = require('./many.json')\n\nmodule.exports = normalize\n\nvar own = {}.hasOwnProperty\n\nvar collator = new Intl.Collator()\n\nvar emptyExtraFields = {\n variants: [],\n extensions: [],\n privateuse: [],\n irregular: null,\n regular: null\n}\n\nfunction normalize(value, options) {\n var settings = options || {}\n // 1. normalize and lowercase the tag (`sgn-be-fr` -> `sfb`).\n var schema = bcp47.parse(String(value || '').toLowerCase(), settings)\n var tag = bcp47.stringify(schema)\n var index = -1\n var key\n\n if (!tag) {\n return tag\n }\n\n // 2. Do fancy, expensive replaces (`ha-latn-gh` -> `ha-gh`).\n while (++index < matches.length) {\n if (match.extendedFilter(tag, matches[index].from).length) {\n replace(schema, matches[index].from, matches[index].to)\n tag = bcp47.stringify(schema)\n }\n }\n\n // 3. Do basic field replaces (`en-840` -> `en-us`).\n index = -1\n\n while (++index < fields.length) {\n if (remove(schema, fields[index].from.field, fields[index].from.value)) {\n add(schema, fields[index].to.field, fields[index].to.value)\n }\n }\n\n // 4. Remove defaults (`nl-nl` -> `nl`).\n tag = bcp47.stringify(Object.assign({}, schema, emptyExtraFields))\n index = -1\n\n while (++index < defaults.length) {\n if (tag === defaults[index]) {\n replace(\n schema,\n defaults[index],\n defaults[index].split('-').slice(0, -1).join('-')\n )\n tag = bcp47.stringify(Object.assign({}, schema, emptyExtraFields))\n }\n }\n\n // 5. Sort extensions on singleton.\n schema.extensions.sort(compareSingleton)\n\n // 6. Warn if fields (currently only regions) should be updated but have\n // multiple choices.\n if (settings.warning) {\n for (key in many) {\n if (own.call(many[key], schema[key])) {\n settings.warning(\n 'Deprecated ' +\n key +\n ' `' +\n schema[key] +\n '`, expected one of `' +\n many[key][schema[key]].join('`, `') +\n '`',\n null,\n 7\n )\n }\n }\n }\n\n // 7. Add proper casing back.\n // Format script (ISO 15924) as titlecase (example: `Latn`):\n if (schema.script) {\n schema.script =\n schema.script.charAt(0).toUpperCase() + schema.script.slice(1)\n }\n\n // Format region (ISO 3166) as uppercase (note: this doesn’t affect numeric\n // codes, which is fine):\n if (schema.region) {\n schema.region = schema.region.toUpperCase()\n }\n\n return bcp47.stringify(schema)\n}\n\nfunction replace(schema, from, to) {\n var left = bcp47.parse(from)\n var right = bcp47.parse(to)\n var removed = []\n var key\n\n // Remove values from `from`:\n for (key in left) {\n if (left[key] && left[key].length && remove(schema, key, left[key])) {\n removed.push(key)\n }\n }\n\n // Add values from `to`:\n for (key in right) {\n // Only add values that are defined on `to`, and that were either removed by\n // `from` or are currently empty.\n if (\n right[key] &&\n right[key].length &&\n (removed.indexOf(key) > -1 || !schema[key] || !schema[key].length)\n ) {\n add(schema, key, right[key])\n }\n }\n}\n\nfunction remove(object, key, value) {\n var removed = false\n var current\n var result\n var index\n var item\n\n /* istanbul ignore else - this is currently done by wrapping code, so else is\n * never reached.\n * However, that could change in the future, so leave this guard here. */\n if (value) {\n current = object[key]\n result = current\n\n if (current && typeof current === 'object') {\n result = []\n index = -1\n\n while (++index < current.length) {\n item = current[index]\n\n if (value.indexOf(item) < 0) {\n result.push(item)\n } else {\n removed = true\n }\n }\n } else if (current === value) {\n result = null\n removed = true\n }\n\n object[key] = result\n }\n\n return removed\n}\n\nfunction add(object, key, value) {\n var current = object[key]\n var list\n var index\n var item\n\n if (current && typeof current === 'object') {\n list = [].concat(value)\n index = -1\n\n while (++index < list.length) {\n item = list[index]\n\n /* istanbul ignore else - this currently can’t happen, but guard for the\n * future. */\n if (current.indexOf(item) < 0) {\n current.push(item)\n }\n }\n } else {\n object[key] = value\n }\n}\n\nfunction compareSingleton(left, right) {\n return collator.compare(left.singleton, right.singleton)\n}\n","'use strict'\n\nexports.parse = require('./lib/parse')\nexports.stringify = require('./lib/stringify')\n","'use strict'\n\nvar alphanumeric = require('is-alphanumerical')\nvar alphabetical = require('is-alphabetical')\nvar decimal = require('is-decimal')\nvar regular = require('./regular.json')\nvar normal = require('./normalize.json')\n\nmodule.exports = parse\n\nvar own = {}.hasOwnProperty\n\n// Parse a BCP 47 language tag.\n/* eslint-disable-next-line complexity */\nfunction parse(tag, options) {\n var settings = options || {}\n var result = empty()\n var source = String(tag)\n var value = source.toLowerCase()\n var index = 0\n var start\n var groups\n var offset\n\n // Check input.\n if (tag == null) {\n throw new Error('Expected string, got `' + tag + '`')\n }\n\n // Let’s start.\n // First: the edge cases.\n if (own.call(normal, value)) {\n if ((settings.normalize == null || settings.normalize) && normal[value]) {\n return parse(normal[value])\n }\n\n result[regular.indexOf(value) === -1 ? 'irregular' : 'regular'] = source\n\n return result\n }\n\n // Now, to actually parse, eat what could be a language.\n while (alphabetical(value.charCodeAt(index)) && index < 9) index++\n\n // A language.\n if (index > 1 /* Min 639. */ && index < 9 /* Max subtag. */) {\n // 5 and up is a subtag.\n // 4 is the size of reserved languages.\n // 3 an ISO 639-2 or ISO 639-3.\n // 2 is an ISO 639-1.\n // <https://github.com/wooorm/iso-639-2>\n // <https://github.com/wooorm/iso-639-3>\n result.language = source.slice(0, index)\n\n if (index < 4 /* Max 639. */) {\n groups = 0\n\n while (\n value.charCodeAt(index) === 45 /* `-` */ &&\n alphabetical(value.charCodeAt(index + 1)) &&\n alphabetical(value.charCodeAt(index + 2)) &&\n alphabetical(value.charCodeAt(index + 3)) &&\n !alphabetical(value.charCodeAt(index + 4))\n ) {\n if (groups > 2 /* Max extended language subtag count. */) {\n return fail(\n index,\n 3,\n 'Too many extended language subtags, expected at most 3 subtags'\n )\n }\n\n // Extended language subtag.\n result.extendedLanguageSubtags.push(source.slice(index + 1, index + 4))\n index += 4\n groups++\n }\n }\n\n // ISO 15924 script.\n // <https://github.com/wooorm/iso-15924>\n if (\n value.charCodeAt(index) === 45 /* `-` */ &&\n alphabetical(value.charCodeAt(index + 1)) &&\n alphabetical(value.charCodeAt(index + 2)) &&\n alphabetical(value.charCodeAt(index + 3)) &&\n alphabetical(value.charCodeAt(index + 4)) &&\n !alphabetical(value.charCodeAt(index + 5))\n ) {\n result.script = source.slice(index + 1, index + 5)\n index += 5\n }\n\n if (value.charCodeAt(index) === 45 /* `-` */) {\n // ISO 3166-1 region.\n // <https://github.com/wooorm/iso-3166>\n if (\n alphabetical(value.charCodeAt(index + 1)) &&\n alphabetical(value.charCodeAt(index + 2)) &&\n !alphabetical(value.charCodeAt(index + 3))\n ) {\n result.region = source.slice(index + 1, index + 3)\n index += 3\n }\n // UN M49 region.\n // <https://github.com/wooorm/un-m49>\n else if (\n decimal(value.charCodeAt(index + 1)) &&\n decimal(value.charCodeAt(index + 2)) &&\n decimal(value.charCodeAt(index + 3)) &&\n !decimal(value.charCodeAt(index + 4))\n ) {\n result.region = source.slice(index + 1, index + 4)\n index += 4\n }\n }\n\n while (value.charCodeAt(index) === 45 /* `-` */) {\n offset = start = index + 1\n\n while (alphanumeric(value.charCodeAt(offset))) {\n if (offset - start > 7 /* Max variant. */) {\n return fail(\n offset,\n 1,\n 'Too long variant, expected at most 8 characters'\n )\n }\n\n offset++\n }\n\n if (\n // Long variant.\n offset - start > 4 /* Min alpha numeric variant. */ ||\n // Short variant.\n (offset - start > 3 /* Min variant. */ &&\n decimal(value.charCodeAt(start)))\n ) {\n result.variants.push(source.slice(start, offset))\n index = offset\n }\n // Something else.\n else {\n break\n }\n }\n\n // Extensions.\n while (value.charCodeAt(index) === 45 /* `-` */) {\n // Exit if this isn’t an extension.\n if (\n value.charCodeAt(index + 1) === 120 /* `x` */ ||\n !alphanumeric(value.charCodeAt(index + 1)) ||\n value.charCodeAt(index + 2) !== 45 /* `-` */ ||\n !alphanumeric(value.charCodeAt(index + 3))\n ) {\n break\n }\n\n offset = index + 2\n groups = 0\n\n while (\n value.charCodeAt(offset) === 45 /* `-` */ &&\n alphanumeric(value.charCodeAt(offset + 1)) &&\n alphanumeric(value.charCodeAt(offset + 2))\n ) {\n start = offset + 1\n offset = start + 2\n groups++\n\n while (alphanumeric(value.charCodeAt(offset))) {\n if (offset - start > 7 /* Max extension. */) {\n return fail(\n offset,\n 2,\n 'Too long extension, expected at most 8 characters'\n )\n }\n\n offset++\n }\n }\n\n if (!groups) {\n return fail(\n offset,\n 4,\n 'Empty extension, extensions must have at least 2 characters of content'\n )\n }\n\n result.extensions.push({\n singleton: source.charAt(index + 1),\n extensions: source.slice(index + 3, offset).split('-')\n })\n\n index = offset\n }\n }\n // Not a language.\n else {\n index = 0\n }\n\n // Private use.\n if (\n (index === 0 && value.charCodeAt(index) === 120) /* `x` */ ||\n (value.charCodeAt(index) === 45 /* `-` */ &&\n value.charCodeAt(index + 1) === 120) /* `x` */\n ) {\n offset = index = index ? index + 2 : 1\n\n while (\n value.charCodeAt(offset) === 45 /* `-` */ &&\n alphanumeric(value.charCodeAt(offset + 1))\n ) {\n offset = start = index + 1\n\n while (alphanumeric(value.charCodeAt(offset))) {\n if (offset - start > 7 /* Max private use. */) {\n return fail(\n offset,\n 5,\n 'Too long private-use area, expected at most 8 characters'\n )\n }\n\n offset++\n }\n\n result.privateuse.push(source.slice(index + 1, offset))\n index = offset\n }\n }\n\n if (index !== source.length) {\n return fail(index, 6, 'Found superfluous content after tag')\n }\n\n return result\n\n function fail(offset, code, reason) {\n if (settings.warning) settings.warning(reason, code, offset)\n return settings.forgiving ? result : empty()\n }\n}\n\n// Create an empty results object.\nfunction empty() {\n return {\n language: null,\n extendedLanguageSubtags: [],\n script: null,\n region: null,\n variants: [],\n extensions: [],\n privateuse: [],\n irregular: null,\n regular: null\n }\n}\n","'use strict'\n\nvar alphabetical = require('is-alphabetical')\nvar decimal = require('is-decimal')\n\nmodule.exports = alphanumerical\n\n// Check if the given character code, or the character code at the first\n// character, is alphanumerical.\nfunction alphanumerical(character) {\n return alphabetical(character) || decimal(character)\n}\n","'use strict'\n\nmodule.exports = stringify\n\n// Compile a language schema to a BCP 47 language tag.\nfunction stringify(schema) {\n var fields = schema || {}\n var result = []\n var values\n var index\n var value\n\n if (fields.irregular || fields.regular) {\n return fields.irregular || fields.regular\n }\n\n if (fields.language) {\n result = result.concat(\n fields.language,\n fields.extendedLanguageSubtags || [],\n fields.script || [],\n fields.region || [],\n fields.variants || []\n )\n\n values = fields.extensions || []\n index = -1\n\n while (++index < values.length) {\n value = values[index]\n\n if (value.singleton && value.extensions && value.extensions.length) {\n result = result.concat(value.singleton, value.extensions)\n }\n }\n }\n\n if (fields.privateuse && fields.privateuse.length) {\n result = result.concat('x', fields.privateuse)\n }\n\n return result.join('-')\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\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 (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/**\n * @class\n */\nclass ProtectionErrors extends ErrorsBase {\n constructor() {\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","/**\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 const customParametersModel = config.customParametersModel;\n\n let instance,\n logger,\n pendingKeySessionsToHandle,\n mediaInfoArr,\n protDataSet,\n sessionType,\n robustnessLevel,\n selectedKeySystem,\n keySystemSelectionInProgress,\n licenseXhrRequest,\n licenseRequestRetryTimeout;\n\n function setup() {\n logger = debug.getLogger(instance);\n pendingKeySessionsToHandle = [];\n mediaInfoArr = [];\n sessionType = 'temporary';\n robustnessLevel = '';\n licenseXhrRequest = null;\n licenseRequestRetryTimeout = null;\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\n /**\n * Once all mediaInfo objects have been added to our mediaInfoArray we can select a key system or check if the kid has changed and we need to trigger a new license request\n * @memberof module:ProtectionController\n * @instance\n */\n function handleKeySystemFromManifest() {\n if (!mediaInfoArr || mediaInfoArr.length === 0) {\n return;\n }\n\n let supportedKeySystems = [];\n mediaInfoArr.forEach((mInfo) => {\n const currentKs = protectionKeyController.getSupportedKeySystemsFromContentProtection(mInfo.contentProtection, protDataSet, sessionType);\n // We assume that the same key systems are signaled for each AS. We can use the first entry we found\n if (currentKs.length > 0) {\n if (supportedKeySystems.length === 0) {\n supportedKeySystems = currentKs;\n }\n // Save config for creating key session once we selected a key system\n pendingKeySessionsToHandle.push(currentKs);\n }\n })\n\n if (supportedKeySystems && supportedKeySystems.length > 0) {\n _selectKeySystemOrUpdateKeySessions(supportedKeySystems, 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 * @private\n */\n function _handleKeySystemFromPssh(supportedKs) {\n pendingKeySessionsToHandle.push(supportedKs);\n _selectKeySystemOrUpdateKeySessions(supportedKs, false);\n }\n\n /**\n * Select the key system or update one of our existing key sessions\n * @param {array} supportedKs\n * @param {boolean} fromManifest\n * @private\n */\n function _selectKeySystemOrUpdateKeySessions(supportedKs, fromManifest) {\n // First time, so we need to select a key system\n if (!selectedKeySystem && !keySystemSelectionInProgress) {\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 _handleKeySessions();\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 if (!keySystemSelectionInProgress) {\n keySystemSelectionInProgress = true;\n const requestedKeySystems = [];\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 // 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 _handleKeySessions();\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 /**\n * If we have already selected a key system we only need to create a new key session and issue a new license request if the init data has changed.\n * @private\n */\n function _handleKeySessions() {\n // Create key sessions for the different AdaptationSets\n let ksIdx;\n for (let i = 0; i < pendingKeySessionsToHandle.length; i++) {\n for (ksIdx = 0; ksIdx < pendingKeySessionsToHandle[i].length; ksIdx++) {\n if (selectedKeySystem === pendingKeySessionsToHandle[i][ksIdx].ks) {\n const current = pendingKeySessionsToHandle[i][ksIdx]\n _loadOrCreateKeySession(current)\n break;\n }\n }\n }\n pendingKeySessionsToHandle = [];\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') && Object.keys(keySystemInfo.protData.clearkeys).length !== 0) {\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 _abortLicenseRequest();\n if (protectionModel) {\n protectionModel.stop();\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 _abortLicenseRequest();\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 pendingKeySessionsToHandle = [];\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 && clearkeys.keyPairs && clearkeys.keyPairs.length > 0) {\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 const licenseResponseFilters = customParametersModel.getLicenseResponseFilters();\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 const licenseRequestFilters = customParametersModel.getLicenseRequestFilters();\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 licenseRequestRetryTimeout = setTimeout(function () {\n _doLicenseRequest(request, retriesCount, timeout, onLoad, onAbort, onError);\n }, retryInterval);\n };\n\n xhr.onload = function () {\n licenseXhrRequest = null;\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 licenseXhrRequest = null;\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 licenseXhrRequest = xhr;\n xhr.send(request.data);\n }\n\n /**\n * Aborts license request\n * @private\n */\n function _abortLicenseRequest() {\n if (licenseXhrRequest) {\n licenseXhrRequest.onloadend = licenseXhrRequest.onerror = licenseXhrRequest.onprogress = undefined; //Ignore events from aborted requests.\n licenseXhrRequest.abort();\n licenseXhrRequest = null;\n }\n\n if (licenseRequestRetryTimeout) {\n clearTimeout(licenseRequestRetryTimeout);\n licenseRequestRetryTimeout = null;\n }\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 let errorMsg = 'NONE';\n let data = null;\n\n if (xhr.response) {\n errorMsg = licenseServerData.getErrorResponse(xhr.response, keySystemString, messageType);\n data = {\n serverResponse: xhr.response || null,\n responseCode: xhr.status || null,\n responseText: xhr.statusText || null\n }\n }\n\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 data\n ));\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 _handleKeySystemFromPssh(supportedKs);\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 instance = {\n initializeForMedia,\n clearMediaInfoArray,\n handleKeySystemFromManifest,\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 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 .replace(/\\//g, '_')\n .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.stringify(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 const settings = config.settings;\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\n if (settings && settings.get().streaming.protection.detectPlayreadyMessageFormat) {\n // If message format configured/defaulted to utf-16 AND number of bytes is odd, assume 'unwrapped' raw CDM message.\n if (messageFormat === 'utf-16' && message && message.byteLength % 2 === 1) {\n headers['Content-Type'] = 'text/xml; charset=utf-8';\n return headers;\n }\n }\n\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\n if (settings && settings.get().streaming.protection.detectPlayreadyMessageFormat) {\n // If message format configured/defaulted to utf-16 AND number of bytes is odd, assume 'unwrapped' raw CDM message.\n if (messageFormat === 'utf-16' && message && message.byteLength % 2 === 1) {\n return message;\n }\n }\n\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 settings,\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 if(config.settings) {\n settings = config.settings\n }\n }\n\n function initialize() {\n keySystems = [];\n\n let keySystem;\n\n // PlayReady\n keySystem = KeySystemPlayReady(context).getInstance({BASE64: BASE64, settings: settings});\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_KEYSTEM_STRING, ProtectionConstants.PLAYREADY_RECOMMENDATION_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, settings: config.settings });\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 customParametersModel : config.customParametersModel,\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';\nimport CustomParametersModel from '../../../models/CustomParametersModel';\n\nfunction DVBReporting(config) {\n config = config || {};\n let instance;\n\n let context = this.context;\n let metricSerialiser,\n customParametersModel,\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 customParametersModel = CustomParametersModel(context).getInstance();\n\n resetInitialSettings();\n }\n\n function doGetRequest(url, successCB, failureCB) {\n let req = new XMLHttpRequest();\n req.withCredentials = customParametersModel.getXHRWithCredentialsForType(metricsConstants.HTTP_REQUEST_DVB_REPORTING_TYPE);\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 const mediaPlayerModel = config.mediaPlayerModel || {};\n\n function create(entry, rangeController) {\n let reporting;\n\n try {\n reporting = knownReportingSchemeIdUris[entry.schemeIdUri](context).create({\n metricsConstants: metricsConstants,\n mediaPlayerModel: mediaPlayerModel\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 mediaPlayerModel: config.mediaPlayerModel\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++, // &amp 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=\"&quot;\"\n ATTRIB_VALUE_ENTITY_U: S++, // <foo bar=&quot\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":""}