数字孪生Web 后台dt( digital twin)2.0版本 统一命名格式
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

1 lines
932 KiB

{"version":3,"sources":["webpack://Hls/webpack/universalModuleDefinition","webpack://Hls/webpack/bootstrap","webpack://Hls/./src/utils/logger.js","webpack://Hls/./src/events.js","webpack://Hls/./src/polyfills/number.js","webpack://Hls/./src/errors.js","webpack://Hls/./src/event-handler.js","webpack://Hls/./src/utils/buffer-helper.js","webpack://Hls/./src/utils/get-self-scope.js","webpack://Hls/./src/controller/fragment-tracker.js","webpack://Hls/./src/controller/level-helper.js","webpack://Hls/./node_modules/url-toolkit/src/url-toolkit.js","webpack://Hls/./src/utils/binary-search.js","webpack://Hls/./src/demux/id3.js","webpack://Hls/./src/loader/fragment.js","webpack://Hls/./src/crypt/decrypter.js","webpack://Hls/./src/utils/mediasource-helper.js","webpack://Hls/./src/controller/base-stream-controller.js","webpack://Hls/./src/loader/playlist-loader.js","webpack://Hls/./src/demux/mp4demuxer.js","webpack://Hls/./src/loader/level-key.js","webpack://Hls/./src/utils/codecs.js","webpack://Hls/./src/demux/demuxer.js","webpack://Hls/./src/demux/demuxer-inline.js","webpack://Hls/./src/demux/adts.js","webpack://Hls/./src/demux/mpegaudio.js","webpack://Hls/./src/observer.js","webpack://Hls/./src/utils/time-ranges.js","webpack://Hls/./src/utils/discontinuities.js","webpack://Hls/./src/controller/fragment-finders.js","webpack://Hls/./src/task-loop.js","webpack://Hls/./src/utils/texttrack-utils.js","webpack://Hls/./src/utils/vttparser.js","webpack://Hls/./src/hls.js","webpack://Hls/./src/loader/m3u8-parser.js","webpack://Hls/./src/loader/level.js","webpack://Hls/./src/utils/attr-list.js","webpack://Hls/./src/loader/fragment-loader.js","webpack://Hls/./src/loader/key-loader.js","webpack://Hls/./src/controller/stream-controller.js","webpack://Hls/./node_modules/webworkify-webpack/index.js","webpack://Hls/./src/crypt/aes-crypto.js","webpack://Hls/./src/crypt/fast-aes-key.js","webpack://Hls/./src/crypt/aes-decryptor.js","webpack://Hls/./src/demux/aacdemuxer.js","webpack://Hls/./src/demux/tsdemuxer.js","webpack://Hls/./src/demux/exp-golomb.js","webpack://Hls/./src/demux/sample-aes.js","webpack://Hls/./src/demux/mp3demuxer.js","webpack://Hls/./src/remux/mp4-remuxer.js","webpack://Hls/./src/remux/aac-helper.js","webpack://Hls/./src/remux/mp4-generator.js","webpack://Hls/./src/remux/passthrough-remuxer.js","webpack://Hls/./node_modules/eventemitter3/index.js","webpack://Hls/./src/demux/demuxer-worker.js","webpack://Hls/./node_modules/node-libs-browser/node_modules/events/events.js","webpack://Hls/./src/controller/gap-controller.js","webpack://Hls/./src/controller/level-controller.js","webpack://Hls/./src/controller/id3-track-controller.js","webpack://Hls/./src/is-supported.js","webpack://Hls/./src/config.js","webpack://Hls/./src/controller/abr-controller.js","webpack://Hls/./src/utils/ewma-bandwidth-estimator.js","webpack://Hls/./src/utils/ewma.js","webpack://Hls/./src/controller/buffer-controller.js","webpack://Hls/./src/controller/cap-level-controller.js","webpack://Hls/./src/controller/fps-controller.js","webpack://Hls/./src/utils/xhr-loader.js","webpack://Hls/./src/controller/audio-track-controller.js","webpack://Hls/./src/controller/audio-stream-controller.js","webpack://Hls/./src/utils/cues.js","webpack://Hls/./src/utils/vttcue.js","webpack://Hls/./src/controller/timeline-controller.js","webpack://Hls/./src/utils/cea-608-parser.js","webpack://Hls/./src/utils/output-filter.js","webpack://Hls/./src/utils/webvtt-parser.js","webpack://Hls/./src/controller/subtitle-track-controller.js","webpack://Hls/./src/controller/subtitle-stream-controller.js","webpack://Hls/./src/controller/eme-controller.js","webpack://Hls/./src/utils/mediakeys-helper.js"],"names":["root","factory","exports","module","define","amd","this","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","get_self_scope_1","noop","fakeLogger","trace","debug","log","warn","info","error","exportedLogger","global","getSelfScope","exportLoggerFunctions","debugConfig","functions","_i","arguments","length","forEach","type","func","console","args","msg","formatMsg","apply","consolePrintFn","enableLogs","e","logger","default","MEDIA_ATTACHING","MEDIA_ATTACHED","MEDIA_DETACHING","MEDIA_DETACHED","BUFFER_RESET","BUFFER_CODECS","BUFFER_CREATED","BUFFER_APPENDING","BUFFER_APPENDED","BUFFER_EOS","BUFFER_FLUSHING","BUFFER_FLUSHED","MANIFEST_LOADING","MANIFEST_LOADED","MANIFEST_PARSED","LEVEL_SWITCHING","LEVEL_SWITCHED","LEVEL_LOADING","LEVEL_LOADED","LEVEL_UPDATED","LEVEL_PTS_UPDATED","AUDIO_TRACKS_UPDATED","AUDIO_TRACK_SWITCHING","AUDIO_TRACK_SWITCHED","AUDIO_TRACK_LOADING","AUDIO_TRACK_LOADED","SUBTITLE_TRACKS_UPDATED","SUBTITLE_TRACK_SWITCH","SUBTITLE_TRACK_LOADING","SUBTITLE_TRACK_LOADED","SUBTITLE_FRAG_PROCESSED","INIT_PTS_FOUND","FRAG_LOADING","FRAG_LOAD_PROGRESS","FRAG_LOAD_EMERGENCY_ABORTED","FRAG_LOADED","FRAG_DECRYPTED","FRAG_PARSING_INIT_SEGMENT","FRAG_PARSING_USERDATA","FRAG_PARSING_METADATA","FRAG_PARSING_DATA","FRAG_PARSED","FRAG_BUFFERED","FRAG_CHANGED","FPS_DROP","FPS_DROP_LEVEL_CAPPING","ERROR","DESTROYING","KEY_LOADING","KEY_LOADED","STREAM_STATE_TRANSITION","Number","isFinite","ErrorTypes","NETWORK_ERROR","MEDIA_ERROR","KEY_SYSTEM_ERROR","MUX_ERROR","OTHER_ERROR","ErrorDetails","KEY_SYSTEM_NO_KEYS","KEY_SYSTEM_NO_ACCESS","KEY_SYSTEM_NO_SESSION","KEY_SYSTEM_LICENSE_REQUEST_FAILED","MANIFEST_LOAD_ERROR","MANIFEST_LOAD_TIMEOUT","MANIFEST_PARSING_ERROR","MANIFEST_INCOMPATIBLE_CODECS_ERROR","LEVEL_LOAD_ERROR","LEVEL_LOAD_TIMEOUT","LEVEL_SWITCH_ERROR","AUDIO_TRACK_LOAD_ERROR","AUDIO_TRACK_LOAD_TIMEOUT","FRAG_LOAD_ERROR","FRAG_LOAD_TIMEOUT","FRAG_DECRYPT_ERROR","FRAG_PARSING_ERROR","REMUX_ALLOC_ERROR","KEY_LOAD_ERROR","KEY_LOAD_TIMEOUT","BUFFER_ADD_CODEC_ERROR","BUFFER_APPEND_ERROR","BUFFER_APPENDING_ERROR","BUFFER_STALLED_ERROR","BUFFER_FULL_ERROR","BUFFER_SEEK_OVER_HOLE","BUFFER_NUDGE_ON_STALL","INTERNAL_EXCEPTION","logger_1","errors_1","events_1","FORBIDDEN_EVENT_NAMES","hlsEventGeneric","hlsHandlerDestroying","hlsHandlerDestroyed","EventHandler","hls","events","onEvent","handledEvents","useGenericHandler","registerListeners","destroy","onHandlerDestroying","unregisterListeners","onHandlerDestroyed","isEventHandler","event","Error","on","off","data","onEventGeneric","funcName","replace","constructor","err","message","trigger","details","fatal","BufferHelper","isBuffered","media","position","buffered","start","end","bufferInfo","pos","maxHoleDuration","vbuffered","push","bufferedInfo","len","nextStart","undefined","bufferLen","bufferStart","bufferEnd","bufferStartNext","buffered2","sort","a","b","diff","buf2len","buf2end","window","self","event_handler_1","FragmentState","NOT_LOADED","APPENDING","PARTIAL","OK","FragmentTracker","_super","_this","bufferPadding","fragments","timeRanges","config","__extends","getBufferedFrag","levelType","bufferedFrags","keys","filter","fragmentEntity","body","frag","startPTS","endPTS","bufferedFragKey","pop","detectEvictedFragments","elementaryStream","timeRange","fragmentTimes","time","esData","range","isTimeBuffered","removeFragment","detectPartialFragments","fragment","fragKey","getFragmentKey","hasElementaryStream","getBufferedTimes","startTime","endTime","fragmentPartial","Math","max","min","partial","level","urlId","sn","getPartialFragment","timePadding","bestFragment","bestOverlap","isPartial","getState","state","video","audio","onFragLoaded","bitrateTest","onBufferAppended","onFragBuffered","hasFragment","removeAllFragments","updatePTS","fromIdx","toIdx","fragFrom","fragTo","fragToPTS","duration","updateFragPTSDTS","startDTS","endDTS","maxStartPTS","deltaPTS","abs","drift","fragIdx","startSN","endSN","PTSKnown","mapFragmentIntersection","oldPlaylist","newPlaylist","intersectionFn","delta","oldFrag","newFrag","adjustSliding","oldFragments","newFragments","addGroupId","id","audioGroupIds","textGroupIds","mergeDetails","oldDetails","newDetails","initSegment","PTSFrag","ccOffset","cc","backtracked","dropped","mergeSubtitlePlaylists","referenceStart","lastIndex","index","frags","computeReloadInterval","currentPlaylist","lastRequestTime","reloadInterval","averagetargetduration","targetduration","minReloadInterval","performance","now","round","URL_REGEX","FIRST_SEGMENT_REGEX","SLASH_DOT_REGEX","SLASH_DOT_DOT_REGEX","URLToolkit","buildAbsoluteURL","baseURL","relativeURL","opts","trim","alwaysNormalize","basePartsForNormalise","parseURL","path","normalizePath","buildURLFromParts","relativeParts","scheme","baseParts","netLoc","pathParts","exec","builtParts","params","query","baseURLPath","newPath","substring","lastIndexOf","url","parts","split","reverse","join","search","list","comparisonFunction","minIndex","maxIndex","currentIndex","currentElement","comparisonResult","ID3","isHeader","offset","isFooter","getID3Data","front","_readSize","subarray","size","getTimeStamp","frames","getID3Frames","frame","isTimeStampFrame","_readTimeStamp","_getFrameData","String","fromCharCode","id3Data","frameData","_decodeFrame","_decodePrivFrame","_decodeTextFrame","_decodeURLFrame","timeStampFrame","byteLength","Uint8Array","pts33Bit","timestamp","owner","_utf8ArrayToStr","privateData","buffer","description","text","array","exitOnNull","char2","char3","out","utf8ArrayToStr","level_key_1","Fragment","_url","_byteRange","_decryptdata","tagList","programDateTime","rawProgramDateTime","_elementaryStreams","_a","ElementaryStreamTypes","AUDIO","VIDEO","relurl","baseurl","rawByteRange","byteRange","lastByteRangeEndOffset","parseInt","fragmentDecryptdataFromLevelkey","levelkey","decryptdata","uri","addElementaryStream","createInitializationVector","segmentNumber","uint8View","method","iv","baseuri","reluri","aes_crypto_1","fast_aes_key_1","aes_decryptor_1","Decrypter","observer","_b","removePKCS7Padding","logEnabled","browserCrypto","crypto","subtle","webkitSubtle","disableWebCrypto","isSync","enableSoftwareAES","decrypt","callback","decryptor","expandKey","subtle_1","fastAesKey","then","aesKey","catch","onWebCryptoError","result","reason","getMediaSource","MediaSource","WebKitMediaSource","task_loop_1","fragment_tracker_1","buffer_helper_1","State","STOPPED","STARTING","IDLE","PAUSED","FRAG_LOADING_WAITING_RETRY","WAITING_TRACK","PARSING","PARSED","ENDED","WAITING_INIT_PTS","WAITING_LEVEL","BaseStreamController","doTick","startLoad","stopLoad","fragCurrent","loader","abort","fragmentTracker","demuxer","fragPrevious","clearInterval","clearNextTick","_streamEnded","levelDetails","live","fragState","onMediaSeeking","mediaBuffer","currentTime","maxBufferHole","toFixed","tolerance","maxFragLookUpTolerance","fragStartOffset","fragEndOffset","lastCurrentTime","loadedmetadata","nextLoadPosition","startPosition","tick","onMediaEnded","mp4demuxer_1","m3u8_parser_1","ContextType","MANIFEST","LEVEL","AUDIO_TRACK","SUBTITLE_TRACK","LevelType","MAIN","SUBTITLE","PlaylistLoader","loaders","canHaveQualityLevels","mapContextToLevelType","context","getResponseUrl","response","indexOf","createInternalLoader","PLoader","pLoader","Loader","getInternalLoader","resetInternalLoader","contextType","destroyInternalLoaders","onManifestLoading","load","onLevelLoading","onAudioTrackLoading","onSubtitleTrackLoading","maxRetry","timeout","retryDelay","maxRetryDelay","loaderContext","manifestLoadingMaxRetry","manifestLoadingTimeOut","manifestLoadingRetryDelay","manifestLoadingMaxRetryTimeout","levelLoadingTimeOut","levelLoadingMaxRetry","levelLoadingRetryDelay","levelLoadingMaxRetryTimeout","responseType","loaderConfig","loaderCallbacks","onSuccess","loadsuccess","onError","loaderror","onTimeout","loadtimeout","stats","networkDetails","isSidxRequest","_handleSidxRequest","_handlePlaylistLoaded","string","tload","_handleTrackOrLevelPlaylist","_handleMasterPlaylist","_handleManifestParsingError","_handleNetworkError","levels","parseMasterPlaylist","audioGroups","map","attrs","codec","audioCodec","audioTracks","parseMasterPlaylistMedia","subtitles","embeddedAudioFound_1","audioTrack","unshift","levelUrlId","levelId","parseLevelPlaylist","singleLevel","tparsed","needSidxRanges","sidxUrl","rangeStart","rangeEnd","sidxInfo","parseSegmentIndex","sidxReferences","references","segmentRef","segRefInfo","moovEndOffset","errorData","UINT32_MAX","pow","MP4Demuxer","remuxer","resetTimeStamp","initPTS","resetInitSegment","videoCodec","initData","parseInitSegment","tracks","audiovideo","container","probe","findBox","bin2str","readUint16","val","readUint32","writeUint32","subresults","endbox","results","slice","concat","moov","sidx","version","timescale","startByte","referencesCount","referenceIndex","referenceInfo","referenceSize","subsegmentDuration","earliestPresentationTime","trak","tkhd","trackId","mdhd","hdlr","soun","vide","codecBox","codecType","getStartDTS","trafs","baseTimes","traf","tfhd","scale","tfdt","offsetStartDTS","timeOffset","baseMediaDecodeTime","upper","floor","lower","append","contiguous","accurateTimeOffset","startDTS_1","remux","LevelKey","_uri","sampleEntryCodesISO","a3ds","ac-3","ac-4","alac","alaw","dra1","dts+","dts-","dtsc","dtse","dtsh","ec-3","enca","g719","g726","m4ae","mha1","mha2","mhm1","mhm2","mlpa","mp4a","raw ","Opus","samr","sawb","sawp","sevc","sqcp","ssmv","twos","ulaw","avc1","avc2","avc3","avc4","avcp","drac","dvav","dvhe","encv","hev1","hvc1","mjp2","mp4v","mvc1","mvc2","mvc3","mvc4","resv","rv60","s263","svc1","svc2","vc-1","vp08","vp09","isCodecType","typeCodes","isCodecSupportedInMp4","isTypeSupported","work","demuxer_inline_1","mediasource_helper_1","observer_1","Demuxer","Observer","forwardMessage","ev","typeSupported","mp4","mpeg","mp3","vendor","navigator","enableWorker","w","onwmsg","onWorkerMessage","addEventListener","onerror","filename","lineno","postMessage","cmd","JSON","stringify","URL","revokeObjectURL","objectURL","removeEventListener","terminate","removeAllListeners","defaultInitPTS","lastFrag","discontinuity","trackSwitch","nextSN","ArrayBuffer","data1","data2","decrypter_1","aacdemuxer_1","tsdemuxer_1","mp3demuxer_1","mp4_remuxer_1","passthrough_remuxer_1","Date","DemuxerInline","decrypter","startTime_1","decryptedData","tstart","tdecrypt","pushDecrypted","muxConfig","demux","mux","remuxer_1","setDecryptData","getAudioConfig","adtsObjectType","adtsSampleingIndex","adtsExtensionSampleingIndex","adtsChanelConfig","userAgent","toLowerCase","manifestCodec","adtsSampleingRates","test","Array","samplerate","channelCount","isHeaderPattern","getHeaderLength","getFullFrameLength","getFrameDuration","parseFrameHeader","pts","frameIndex","frameDuration","headerLength","frameLength","stamp","newOffset","initTrackConfig","track","appendFrame","header","aacSample","unit","dts","samples","sample","MpegAudio","BitratesMap","SamplingRateMap","SamplesCoefficients","BytesInSlot","parseHeader","samplesPerFrame","sampleRate","headerB","headerC","headerE","headerF","headerG","columnInBitrates","bitRate","columnInSampleRates","sampleCoefficient","bytesInSlot","emit","EventEmitter","toString","binary_search_1","findFirstFragWithCC","firstFrag","currentFrag","shouldAlignOnDiscontinuities","lastLevel","shouldAlign","endCC","startCC","findDiscontinuousReferenceFrag","prevDetails","curDetails","prevFrags","curFrags","prevStartFrag","adjustPts","sliding","alignDiscontinuities","referenceFrag","alignPDT","lastDetails","hasProgramDateTime","lastPDT","findFragWithCC","CC","candidate","alignStream","fragmentWithinToleranceTest","candidateLookupTolerance","pdtWithinToleranceTest","pdtBufferEnd","endProgramDateTime","findFragmentByPDT","PDTValue","isArray","seg","findFragmentByPTS","fragNext","TaskLoop","_tickInterval","_tickTimer","_tickCallCount","_boundTick","hasInterval","hasNextTick","setInterval","millis","clearTimeout","setTimeout","sendAddTrackEvent","videoEl","Event","document","createEvent","initEvent","dispatchEvent","clearCurrentCues","cues","removeCue","vttcue_1","StringDecoder","decode","decodeURIComponent","encodeURIComponent","VTTParser","decoder","regionList","Settings","values","parseOptions","input","keyValueDelim","groupDelim","groups","kv","set","k","v","dflt","defaultKey","has","alt","integer","percent","match","parseFloat","defaults","center","align","parseCue","cue","oInput","consumeTimeStamp","ts","computeSeconds","h","f","parseTimeStamp","skipWhitespace","substr","settings","region","vals","vals0","vertical","line","lineAlign","snapToLines","consumeCueSettings","fixLineBreaks","parse","collectNextLine","stream","alreadyCollectedLine","hasSubstring","oncue","flush","onflush","playlist_loader_1","fragment_loader_1","key_loader_1","stream_controller_1","level_controller_1","id3_track_controller_1","is_supported_1","config_1","Hls","defaultConfig","DefaultConfig","liveSyncDurationCount","liveMaxLatencyDurationCount","liveSyncDuration","liveMaxLatencyDuration","prop","_autoLevelCapping","abrController","bufferController","capLevelController","fpsController","playListLoader","fragmentLoader","keyLoader","id3TrackController","levelController","networkControllers","streamController","Controller","audioStreamController","coreComponents","audioTrackController","subtitleTrackController","emeController","subtitleStreamController","timelineController","isSupported","hlsDefaultConfig","detachMedia","component","attachMedia","loadSource","location","href","controller","swapAudioCodec","recoverMediaError","currentLevel","newLevel","loadLevel","immediateLevelSwitch","nextLevel","manualLevel","nextLevelSwitch","nextLoadLevel","firstLevel","minAutoLevel","startLevel","minAutoBitrate","realBitrate","bitrate","autoLevelCapping","nextAutoLevel","maxAutoLevel","audioTrackId","liveSyncPosition","subtitleTracks","subtitleTrack","subtitleTrackId","subtitleDisplay","fragment_1","level_1","attr_list_1","codecs_1","MASTER_PLAYLIST_REGEX","MASTER_PLAYLIST_MEDIA_REGEX","LEVEL_PLAYLIST_REGEX_FAST","RegExp","source","LEVEL_PLAYLIST_REGEX_SLOW","MP4_REGEX_SUFFIX","M3U8Parser","findGroup","mediaGroupId","matchingGroup","group","convertAVC1ToAVCOTI","avcdata","shift","resolve","baseUrl","setCodecs","codecs","filtered","preferred","unknownCodecs","resolution","decimalResolution","width","height","decimalInteger","NAME","CODECS","medias","TYPE","groupId","DEFAULT","autoselect","AUTOSELECT","forced","FORCED","URI","lang","LANGUAGE","groupCodec","currentSN","totalduration","prevFrag","firstPdtIndex","title","assignProgramDateTime","byteRangeEndOffset","value1","value2","toUpperCase","decryptparams","keyAttrs","decryptmethod","enumeratedString","decrypturi","decryptiv","hexadecimalInteger","startParams","startTimeOffset","decimalFloatingPoint","mapAttrs","BYTERANGE","every","startIndex","fragPrev","backfillProgramDateTimes","Level","DECIMAL_RESOLUTION_REGEX","ATTR_LIST_REGEX","AttrList","attr","parseAttrList","attrName","intValue","MAX_SAFE_INTEGER","Infinity","stringValue","hexadecimalIntegerAsNumber","res","FragmentLoader","loaderName","onFragLoading","FragmentILoader","fLoader","DefaultILoader","loaded","progressData","byteRangeStartOffset","fragLoadingTimeOut","fragLoadingMaxRetryTimeout","onProgress","loadprogress","payload","KeyLoader","decryptkey","decrypturl","onKeyLoading","fragLoadingRetryDelay","demuxer_1","LevelHelper","time_ranges_1","discontinuities_1","fragment_finders_1","gap_controller_1","base_stream_controller_1","StreamController","audioCodecSwap","_state","stallReported","gapController","hls_1","fragLoadError","startFragRequested","forceStartLoad","_doTickIdle","retryDate","seeking","_checkBuffer","_checkFragmentChanged","levelLastLoaded","startFragPrefetch","levelInfo","maxBufLen","levelBitrate","maxBufferSize","maxBufferLength","maxMaxBufferLength","altAudio","_fetchPayloadOrEos","fragLen","initialLiveManifestSize","_ensureFragmentAtLivePoint","_findFragment","encrypted","_loadKey","_loadFragment","maxLatency","computeLivePosition","readyState","targetSN","lookupTolerance","curSNIdx","sameLevel","nextFrag","autoLevel","autoLevelEnabled","_reduceMaxBufferLength","nextState","previousState","followingBufferedFrag","nextBufferedFrag","fragPlayingCurrent","fragPlaying","fragPlayingLevel","immediateSwitch","previouslyPaused","paused","pause","flushMainBuffer","POSITIVE_INFINITY","immediateLevelSwitchEnd","play","fetchdelay","nextLevelId","fragLastKbps","startOffset","endOffset","flushScope","onMediaAttached","onvseeking","onvseeked","onMediaSeeked","onvended","autoStartLoad","onMediaDetaching","ended","stalled","onManifestParsed","aac","heaac","audioCodecSwitch","onLevelLoaded","newLevelId","curLevel","onKeyLoaded","fragLoaded","tbuffered","pendingBuffering","appended","initSegmentData","_getAudioCodec","onFragParsingInitSegment","fragNew","trackName","ua","metadata","levelCodec","parent","content","onFragParsingData","hasAudio","hasVideo","nb","hls_2","onFragParsed","_checkAppendedParsed","onAudioTrackSwitching","hls_3","onAudioTrackSwitched","videoBuffer","onBufferCreated","mediaTrack","alternate","pending","total","tfirst","mediaBuffered","fragLoadingMaxRetry","delay","levelRetry","minLength","_seekToStartPos","poll","onFragLoadEmergencyAborted","onBufferFlushed","targetLatency","defaultAudioCodec","_liveSyncPosition","webpackBootstrapFunc","configurable","oe","ENTRY_MODULE","moduleNameReqExp","dependencyRegExp","quoteRegExp","str","isNumeric","isNaN","getModuleDependencies","sources","queueName","retval","fnString","wrapperSignature","webpackRequireName","re","j","hasValuesInQueues","queues","reduce","hasValues","options","main","requiredModules","all","modulesQueue","seenModules","moduleToCheck","newModules","newModulesKeys","getRequiredModules","src","entryModule","blob","Blob","bare","workerUrl","webkitURL","mozURL","msURL","createObjectURL","worker","Worker","AESCrypto","aesIV","FastAESKey","importKey","removePadding","outputBytes","paddingBytes","DataView","getUint8","AESDecryptor","rcon","subMix","Uint32Array","invSubMix","sBox","invSBox","initTable","uint8ArrayToUint32Array_","arrayBuffer","view","newArray","getUint32","subMix0","subMix1","subMix2","subMix3","invSubMix0","invSubMix1","invSubMix2","invSubMix3","x","xi","sx","x2","x4","x8","keyBuffer","sameKey","keySize","ksRow","invKsRow","prev","ksRows","keySchedule","invKeySchedule","sbox","networkToHostOrderSwap","word","inputArrayBuffer","t0","t1","t2","t3","s0","s1","s2","s3","inputWords0","inputWords1","inputWords2","inputWords3","nRounds","invSBOX","initVector","initVector0","initVector1","initVector2","initVector3","inputInt32","Int32Array","outputInt32","swapWord","ADTS","id3_1","AACDemuxer","_audioTrack","sequenceNumber","isAAC","inputTimeScale","length_1","id3Samples","mpegaudio_1","exp_golomb_1","sample_aes_1","RemuxerTrackIdConfig","id3","TSDemuxer","sampleAes","discardEPB","syncOffset","_syncOffset","scanwindow","createTrack","pid","pmtParsed","_pmtId","_avcTrack","_id3Track","_txtTrack","aacOverFlow","aacLastPTS","avcSample","_duration","stt","pes","unknownPIDs","avcTrack","id3Track","avcId","audioId","id3Id","pmtId","avcData","pesData","audioData","parsePAT","_parsePAT","parsePMT","_parsePMT","parsePES","_parsePES","parseAVCPES","_parseAVCPES","parseAACPES","_parseAACPES","parseMPEGPES","_parseMPEGPES","parseID3PES","_parseID3PES","parsedPIDs","avc","decryptAndRemux","videoTrack","textTrack","localthis_1","decryptAacSamples","decryptAndRemuxAvc","localthis_2","decryptAvcSamples","_initPTS","_initDTS","mpegSupported","isSampleAes","tableEnd","pesFlags","pesLen","pesHdrLen","pesPts","pesDts","payloadStartOffset","newData","splice","dataLen","pushAccesUnit","units","nbSamples","forceKeyFrameOnDiscontinuity","sps","last","expGolombDecoder","_parseAVCNALu","spsfound","createAVCSample","audFound","sliceType","readSliceType","readUByte","payloadType","payloadSize","endOfCaptions","bytesAvailable","readUShort","readUInt","firstByte","totalCCs","byteArray","_insertSampleInOrder","bytes","readSPS","pixelRatio","codecarray","codecstring","pps","arr","_getLastNalUnit","lastUnit","overflow","lastUnitType","naluState","lastState","lastUnitStart","tmp","newLength","EPBPositions","sourceIndex","newPTS","ExpGolomb","bitsAvailable","loadWord","workingBytes","availableBytes","skipBits","count","skipBytes","readBits","bits","valu","skipLZ","leadingZeroCount","skipUEG","skipEG","readUEG","clz","readEG","readBoolean","skipScalingList","lastScale","nextScale","profileIdc","numRefFramesInPicOrderCntCycle","picWidthInMbsMinus1","picHeightInMapUnitsMinus1","frameMbsOnlyFlag","scalingListCount","frameCropLeftOffset","frameCropRightOffset","frameCropTopOffset","frameCropBottomOffset","chromaFormatIdc","picOrderCntType","ceil","SampleAesDecrypter","decryptBuffer","encryptedData","decryptAacSample","sampleIndex","sync","curUnit","encryptedBuffer","byteOffset","localthis","getAvcEncryptedData","decodedData","encryptedDataLen","Int8Array","outputPos","inputPos","getAvcDecryptedUnit","decryptAvcSample","unitIndex","curUnits","MP3Demuxer","aac_helper_1","mp4_generator_1","MP4Remuxer","isSafari","ISGenerated","defaultTimeStamp","generateIS","nbAudioSamples","nbVideoSamples","audioTimeOffset","videoTimeOffset","audiovideoDeltaDts","remuxAudio","audioTrackLength","remuxVideo","videoData","remuxEmptyAudio","remuxID3","remuxText","initDTS","audioSamples","videoSamples","computePTSDTS","mp4SampleDuration","mdat","moof","firstPTS","firstDTS","lastPTS","lastDTS","timeScale","inputSamples","outputSamples","ptsNormalize","_PTSNormalize","nextAvcDts","deltadts","deltapts","PTSDTSshift","curr","nbNalu","naluLen","sample_1","nbUnits","sampleLen","mdatSize","setUint32","types","avcSampleUnits","mp4SampleLength","compositionTimeOffset","unitData","unitDataLen","lastFrameDuration","stretchShortVideoTrack","gapTolerance","deltaToFrameEnd","nextAudioPts","cts","flags","isLeading","isDependedOn","hasRedundancy","degradPrio","dependsOn","isNonSync","mp4Sample","fillFrame","mp4timeScale","scaleFactor","inputSampleDuration","rawMPEG","maxAudioFramesDrift","nextPts","missing","newStamp","getSilentFrame","nbSamples_1","audioSample","delta_1","numMissingFrames","unitLen","lastSampleDuration","silentFrame","reference","AAC","MP4","init","avcC","btrt","dinf","dref","esds","ftyp","mdia","mfhd","minf",".mp3","mvex","mvhd","pasp","sdtp","stbl","stco","stsc","stsd","stsz","stts","trun","trex","vmhd","smhd","charCodeAt","videoHdlr","audioHdlr","HDLR_TYPES","STTS","STSC","STCO","STSZ","VMHD","SMHD","STSD","majorBrand","avc1Brand","minorVersion","FTYP","box","DINF","upperWordDuration","lowerWordDuration","boxes","avcc","hSpacing","vSpacing","configlen","sampleDependencyTable","upperWordBaseMediaDecodeTime","lowerWordBaseMediaDecodeTime","arraylen","paddingValue","movie","PassThroughRemuxer","rawData","streamType","prefix","Events","addListener","emitter","fn","once","TypeError","listener","evt","_events","_eventsCount","clearEvent","__proto__","eventNames","names","getOwnPropertySymbols","listeners","handlers","ee","listenerCount","a1","a2","a3","a4","a5","removeListener","prefixed","events_2","transferable","_maxListeners","isFunction","arg","isObject","isUndefined","defaultMaxListeners","setMaxListeners","isNumber","er","handler","newListener","warned","fired","g","evlistener","GapController","tnow","nudgeRetry","stalledDuration","_reportStall","_tryFixBufferStall","_trySkipBufferHole","highBufferWatchdogPeriod","_tryNudgeBuffer","lastEndTime","nudgeMaxRetry","targetTime","nudgeOffset","chromeOrFirefox","level_helper_1","LevelController","canload","currentLevelIndex","manualLevelIndex","timer","clearTimer","_levels","levelRetryCount","loadError","onManifestLoaded","bitrateStart","levelSet","levelFromSet","videoCodecFound","audioCodecFound","attributes","fragmentError","SUBTITLES","_firstLevel","some","setLevelInternal","levelProperties","_startLevel","configStartLevel","levelIndex","levelError","recoverLevel","errorEvent","redundantLevels","errorDetails","trequest","audioGroupId","levelObject","texttrack_utils_1","ID3TrackController","getID3Track","textTracks","kind","label","addTextTrack","onFragParsingMetadata","Cue","WebKitDataCue","VTTCue","TextTrackCue","frames_1","addCue","mediaSource","sourceBuffer","SourceBuffer","WebKitSourceBuffer","sourceBufferValidAPI","appendBuffer","remove","abr_controller_1","buffer_controller_1","cap_level_controller_1","fps_controller_1","xhr_loader_1","audio_track_controller_1","audio_stream_controller_1","Cues","timeline_controller_1","subtitle_track_controller_1","subtitle_stream_controller_1","eme_controller_1","mediakeys_helper_1","capLevelOnFPSDrop","capLevelToPlayerSize","lowBufferWatchdogPeriod","liveDurationInfinity","liveBackBufferLength","fpsDroppedMonitoringPeriod","fpsDroppedMonitoringThreshold","appendErrorMaxRetry","xhrSetup","licenseXhrSetup","abrEwmaFastLive","abrEwmaSlowLive","abrEwmaFastVoD","abrEwmaSlowVoD","abrEwmaDefaultEstimate","abrBandWidthFactor","abrBandWidthUpFactor","abrMaxWithRealBitrate","maxStarvationDelay","maxLoadingDelay","emeEnabled","widevineLicenseUrl","requestMediaKeySystemAccessFunc","requestMediaKeySystemAccess","SubtitleStreamController","cueHandler","enableCEA708Captions","enableWebVTT","captionsTextTrack1Label","captionsTextTrack1LanguageCode","captionsTextTrack2Label","captionsTextTrack2LanguageCode","ewma_bandwidth_estimator_1","AbrController","lastLoadedFragLevel","_nextAutoLevel","_bwEstimator","onCheck","_abandonRulesCheck","ewmaFast","ewmaSlow","aborted","playbackRate","requestDelay","loadRate","bw","expectedLen","fragLoadedDelay","bufferStarvationDelay","fragLevelNextLoadedDelay","levelNextBitrate","loadedBytes","loadedDuration","fragLoadingProcessingMs","bwEstimate","getEstimate","bitrateTestDelay","forcedAutoLevel","bwEstimator","canEstimate","nextABRAutoLevel","_nextABRAutoLevel","currentFragDuration","avgbw","bestLevel","_findBestLevel","bwFactor","bwUpFactor","currentBw","maxFetchDuration","avgDuration","adjustedbw","fetchDuration","ewma_1","EwmaBandWidthEstimator","slow","fast","defaultEstimate","defaultEstimate_","minWeight_","minDelayMs_","slow_","fast_","durationMs","numBytes","bandwidth","weight","getTotalWeight","EWMA","halfLife","alpha_","exp","estimate_","totalWeight_","adjAlpha","zeroFactor","BufferController","_msDuration","_levelDuration","_levelTargetDuration","_live","_objectUrl","bufferCodecEventsExpected","onsbue","onSBUpdateEnd","onsbe","onSBUpdateError","pendingTracks","onLevelPtsUpdated","audioBuffer","timestampOffset","updating","audioTimestampOffset","onMediaAttaching","ms","onmso","onMediaSourceOpen","onmse","onMediaSourceEnded","onmsc","onMediaSourceClose","endOfStream","removeAttribute","flushRange","segments","checkPendingTracks","pendingTracksCount","createSourceBuffers","doAppending","_needsFlush","doFlush","_needsEos","checkEos","appending","counter","segment","updateMediaElementDuration","flushLiveBackBuffer","onBufferReset","sb","removeSourceBuffer","onBufferCodecs","mimeType","addSourceBuffer","onBufferAppending","onBufferAppendFail","onBufferEos","dataType","sbobj","onBufferFlushing","flushBufferCounter","bufferTypes","targetBackBufferPosition","bufferType","removeBufferRange","onLevelUpdated","flushBuffer","appendError","event_1","code","typeIn","bufStart","bufEnd","removeStart","removeEnd","CapLevelController","restrictedLevels","_stopCapping","onFpsDropLevelCapping","isLevelAllowed","droppedLevel","HTMLVideoElement","_startCapping","onLevelsUpdated","detectPlayerSize","levelsLength","getMaxLevel","capLevelIndex","validLevels","getMaxLevelByMediaSize","mediaWidth","mediaHeight","clientWidth","offsetWidth","contentScaleFactor","clientHeight","offsetHeight","devicePixelRatio","atGreatestBandiwdth","maxLevelIndex","FPSController","isVideoPlaybackQualityAvailable","getVideoPlaybackQuality","checkFPSInterval","checkFPS","decodedFrames","droppedFrames","lastTime","currentPeriod","currentDropped","lastDroppedFrames","currentDecoded","lastDecodedFrames","droppedFPS","totalDroppedFrames","videoPlaybackQuality","totalVideoFrames","droppedVideoFrames","webkitDecodedFrameCount","webkitDroppedFrameCount","XMLHttpRequest","XhrLoader","requestTimeout","retryTimeout","callbacks","retry","loadInternal","xhr","open","status","setRequestHeader","onreadystatechange","readystatechange","onprogress","send","currentTarget","status_1","responseText","responseURL","statusText","lengthComputable","AudioTrackController","_trackId","_selectDefaultTrack","trackIdBlacklist","onAudioTrackLoaded","updatePeriodMs","_selectInitialAudioTrack","_handleLoadError","newId","_setAudioTrack","_loadTrackDetailsIfNeeded","_updateTrack","currentAudioTrack","defaultTracks","trackFound","traverseTracks","_needsTrackLoading","previousId","language","AudioStreamController","waitingFragment","videoTrackCC","onInitPtsFound","demuxerId","trackDetails","mainBufferInfo","bufferEnd_1","maxConfigBuffer","audioSwitch","loadIdx","fragLoadIdx","nextBuffered","foundFrag","maxFragLookUpTolerance_1","isSeeking","waitingFrag","waitingFragCC","onAudioTracksUpdated","appendObj","pendingData","appendOnBufferFlush","pendingData_1","frag_1","vttparser_1","newCue","captionScreen","row","indenting","indent","rows","isEmpty","chars","uchar","cueStartTime","autoKeyword","directionSetting","","lr","rl","alignSetting","middle","left","right","findAlignSetting","extend","obj","cobj","isIE8","baseObj","createElement","hasBeenReset","_id","_pauseOnExit","_startTime","_endTime","_text","_region","_vertical","_snapToLines","_line","_lineAlign","_position","_positionAlign","_size","_align","setting","findDirectionSetting","SyntaxError","displayState","getCueAsHTML","WebVTT","convertCueToDOMTree","cea_608_parser_1","output_filter_1","webvtt_parser_1","canReuseVttTextTrack","inUseTrack","manifestTrack","textTrack1","textTrack2","intersection","x1","y1","y2","TimelineController","enabled","unparsedVttFrags","cueRanges","captionsTracks","captionsProperties","languageCode","channel1","channel2","cea608Parser","addCues","screen","ranges","merged","cueRange","overlap","getExistingTrack","createCaptionsTrack","existingTrack","createTextTrack","_cleanTracks","lastSn","prevCC","vttCCs","presentationOffset","0","new","inUseTracks_1","onLevelSwitching","closedCaptions","reset","success","decryptData","_parseVTTs","currentTrack","getCueById","textTrackCue","onFragDecrypted","onFragParsingUserdata","ccdatas","extractCea608Data","addData","tmpByte","ccbyte1","ccbyte2","actualCCBytes","specialCea608CharsCodes","42","92","94","95","96","123","124","125","126","127","128","129","130","131","132","133","134","135","136","137","138","139","140","141","142","143","144","145","146","147","148","149","150","151","152","153","154","155","156","157","158","159","160","161","162","163","164","165","166","167","168","169","170","171","172","173","174","175","176","177","178","179","180","181","182","183","184","185","186","187","188","189","190","191","192","193","194","195","196","197","198","199","200","201","202","203","204","205","206","207","getCharForByte","byte","charCode","NR_ROWS","NR_COLS","rowsLowCh1","17","18","21","22","23","16","19","20","rowsHighCh1","rowsLowCh2","25","26","29","30","31","24","27","28","rowsHighCh2","backgroundColors","verboseFilter","DATA","DEBUG","INFO","WARNING","TEXT","verboseLevel","setTime","newTime","severity","numArrayToHexArray","numArray","hexArray","PenState","foreground","underline","italics","background","flash","setStyles","styles","attribs","style","isDefault","equals","other","copy","newPenState","StyledUnicodeChar","penState","setChar","setPenState","newChar","Row","currPenState","equal","empty","setCursor","absPos","moveCursor","relPos","newPos","backSpace","insertChar","char","clearFromPos","startPos","clear","clearToEndOfRow","getTextString","setPenStyles","CaptionScreen","currRow","nrRollUpRows","setPen","setPAC","pacData","newRow","topRowIndex","lastOutputScreen","prevLineTime","prevPos","color","setBkgData","bkgData","setRollUpRows","nrRows","rollUp","getDisplayText","topRow","asOneRow","displayText","rowNr","rowText","getTextAndFormat","Cea608Channel","channelNumber","outputFilter","chNr","verbose","displayedMemory","nonDisplayedMemory","currRollUpRow","writeScreen","lastCueEndTime","getHandler","setHandler","newHandler","setMode","newMode","insertChars","outputDataUpdate","ccRCL","ccBS","ccAOF","ccAON","ccDER","ccRU","ccFON","ccRDC","ccTR","ccRTD","ccEDM","ccCR","ccENM","ccEOC","ccTO","nrCols","ccMIDROW","secondByte","colorIndex","dispatch","dispatchCue","cueSplitAtTime","Cea608Parser","field","out1","out2","outputs","channels","currChNr","lastCmdA","lastCmdB","bufferedData","dataCounters","padding","byteList","cmdFound","charsFound","parseCmd","parseMidrow","parsePAC","parseBackgroundAttributes","parseChars","channel","interpretPAC","pacIndex","channelNr","charCodes","charCode1","oneCode","hexCodes","OutputFilter","startsWith","inputString","searchString","hash","WebVTTParser","vttByteArray","syncPTS","callBack","errorCallBack","parsingError","vttLines","cueTime","mpegTs","localTime","presentationTime","inHeader","parser","currCC","cueOffset","calculateOffset","onparsingerror","timeString","secs","mins","hours","cueString2millis","SubtitleTrackController","stopped","queuedDefaultTrack","trackChangeListener","_onTextTracksChanged","useTextTrackPolling","subtitlePollingInterval","onSubtitleTrackLoaded","_clearReloadTimer","_loadCurrentTrack","_toggleTrackModes","_setSubtitleTrackInternal","filterSubtitleTracks","oldTrack","nextTrack","textTrackList","tracksBuffered","currentTrackId","lastAVStart","_onMediaSeeking","onSubtitleFragProcessed","fragStart","fragEnd","onSubtitleTracksUpdated","onSubtitleTrackSwitch","_getBuffered","KeySystems","EMEController","_widevineLicenseUrl","_licenseXhrSetup","_emeEnabled","_requestMediaKeySystemAccess","_mediaKeysList","_media","_hasSetMediaKeys","_isMediaEncrypted","_requestLicenseFailureCount","getLicenseServerUrl","keySystem","_attemptKeySystemAccess","audioCodecs","videoCodecs","mediaKeySystemConfigs","drmSystemOptions","baseConfig","videoCapabilities","contentType","createWidevineMediaKeySystemConfigurations","getSupportedMediaKeySystemConfigurations","mediaKeySystemAccess","_onMediaKeySystemAccessObtained","mediaKeysListItem","mediaKeys","mediaKeysSession","mediaKeysSessionInitialized","mediaKeySystemDomain","createMediaKeys","_onMediaKeysCreated","createSession","_onNewMediaKeySession","keySession","sessionId","_onKeySessionMessage","_requestLicense","update","_onMediaEncrypted","initDataType","_mediaEncryptionInitDataType","_mediaEncryptionInitData","_attemptSetMediaKeys","_generateRequestWithPreferredKeySession","keysListItem","setMediaKeys","generateRequest","_createLicenseXhr","keyMessage","_onLicenseRequestReadyStageChange","attemptsLeft","_generateLicenseRequestChallenge","challenge"],"mappings":"4BAAA,SAAAA,EAAAC,GACA,iBAAAC,SAAA,iBAAAC,OACAA,OAAAD,QAAAD,IACA,mBAAAG,eAAAC,IACAD,UAAAH,GACA,iBAAAC,QACAA,QAAA,IAAAD,IAEAD,EAAA,IAAAC,IARA,CASCK,KAAA,WACD,mBCTA,IAAAC,KAGA,SAAAC,EAAAC,GAGA,GAAAF,EAAAE,GACA,OAAAF,EAAAE,GAAAP,QAGA,IAAAC,EAAAI,EAAAE,IACAC,EAAAD,EACAE,GAAA,EACAT,YAUA,OANAU,EAAAH,GAAAI,KAAAV,EAAAD,QAAAC,IAAAD,QAAAM,GAGAL,EAAAQ,GAAA,EAGAR,EAAAD,QA0DA,OArDAM,EAAAM,EAAAF,EAGAJ,EAAAO,EAAAR,EAGAC,EAAAQ,EAAA,SAAAd,EAAAe,EAAAC,GACAV,EAAAW,EAAAjB,EAAAe,IACAG,OAAAC,eAAAnB,EAAAe,GAA0CK,YAAA,EAAAC,IAAAL,KAK1CV,EAAAgB,EAAA,SAAAtB,GACA,oBAAAuB,eAAAC,aACAN,OAAAC,eAAAnB,EAAAuB,OAAAC,aAAwDC,MAAA,WAExDP,OAAAC,eAAAnB,EAAA,cAAiDyB,OAAA,KAQjDnB,EAAAoB,EAAA,SAAAD,EAAAE,GAEA,GADA,EAAAA,IAAAF,EAAAnB,EAAAmB,IACA,EAAAE,EAAA,OAAAF,EACA,KAAAE,GAAA,iBAAAF,QAAAG,WAAA,OAAAH,EACA,IAAAI,EAAAX,OAAAY,OAAA,MAGA,GAFAxB,EAAAgB,EAAAO,GACAX,OAAAC,eAAAU,EAAA,WAAyCT,YA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BtE,EAAAsE,QAAei7E,iFCzef,IAAM/pB,EACkB,oBAAX7nD,QAA0BA,OAAOoiB,WAAapiB,OAAOoiB,UAAUylC,4BACjE7nD,OAAOoiB,UAAUylC,4BAA4BxzD,KAAK2L,OAAOoiB,WAEzD,KAKT/vB,EAAAw1D","file":"hls.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[\"Hls\"] = factory();\n\telse\n\t\troot[\"Hls\"] = factory();\n})(this, 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 = 31);\n","import { getSelfScope } from './get-self-scope';\n\nfunction noop () {}\n\nconst fakeLogger = {\n trace: noop,\n debug: noop,\n log: noop,\n warn: noop,\n info: noop,\n error: noop\n};\n\nlet exportedLogger = fakeLogger;\n\n// let lastCallTime;\n// function formatMsgWithTimeInfo(type, msg) {\n// const now = Date.now();\n// const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';\n// lastCallTime = now;\n// msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';\n// return msg;\n// }\n\nfunction formatMsg (type, msg) {\n msg = '[' + type + '] > ' + msg;\n return msg;\n}\n\nconst global = getSelfScope();\n\nfunction consolePrintFn (type) {\n const func = global.console[type];\n if (func) {\n return function (...args) {\n if (args[0]) {\n args[0] = formatMsg(type, args[0]);\n }\n\n func.apply(global.console, args);\n };\n }\n return noop;\n}\n\nfunction exportLoggerFunctions (debugConfig, ...functions) {\n functions.forEach(function (type) {\n exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);\n });\n}\n\nexport var enableLogs = function (debugConfig) {\n if (debugConfig === true || typeof debugConfig === 'object') {\n exportLoggerFunctions(debugConfig,\n // Remove out from list here to hard-disable a log-level\n // 'trace',\n 'debug',\n 'log',\n 'info',\n 'warn',\n 'error'\n );\n // Some browsers don't allow to use bind on console object anyway\n // fallback to default if needed\n try {\n exportedLogger.log();\n } catch (e) {\n exportedLogger = fakeLogger;\n }\n } else {\n exportedLogger = fakeLogger;\n }\n};\n\nexport var logger = exportedLogger;\n","/**\n * @readonly\n * @enum {string}\n */\nconst HlsEvents = {\n // fired before MediaSource is attaching to media element - data: { media }\n MEDIA_ATTACHING: 'hlsMediaAttaching',\n // fired when MediaSource has been succesfully attached to media element - data: { }\n MEDIA_ATTACHED: 'hlsMediaAttached',\n // fired before detaching MediaSource from media element - data: { }\n MEDIA_DETACHING: 'hlsMediaDetaching',\n // fired when MediaSource has been detached from media element - data: { }\n MEDIA_DETACHED: 'hlsMediaDetached',\n // fired when we buffer is going to be reset - data: { }\n BUFFER_RESET: 'hlsBufferReset',\n // fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}\n BUFFER_CODECS: 'hlsBufferCodecs',\n // fired when sourcebuffers have been created - data: { tracks : tracks }\n BUFFER_CREATED: 'hlsBufferCreated',\n // fired when we append a segment to the buffer - data: { segment: segment object }\n BUFFER_APPENDING: 'hlsBufferAppending',\n // fired when we are done with appending a media segment to the buffer - data : { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent}\n BUFFER_APPENDED: 'hlsBufferAppended',\n // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }\n BUFFER_EOS: 'hlsBufferEos',\n // fired when the media buffer should be flushed - data { startOffset, endOffset }\n BUFFER_FLUSHING: 'hlsBufferFlushing',\n // fired when the media buffer has been flushed - data: { }\n BUFFER_FLUSHED: 'hlsBufferFlushed',\n // fired to signal that a manifest loading starts - data: { url : manifestURL}\n MANIFEST_LOADING: 'hlsManifestLoading',\n // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}}\n MANIFEST_LOADED: 'hlsManifestLoaded',\n // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}\n MANIFEST_PARSED: 'hlsManifestParsed',\n // fired when a level switch is requested - data: { level : id of new level }\n LEVEL_SWITCHING: 'hlsLevelSwitching',\n // fired when a level switch is effective - data: { level : id of new level }\n LEVEL_SWITCHED: 'hlsLevelSwitched',\n // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}\n LEVEL_LOADING: 'hlsLevelLoading',\n // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} }\n LEVEL_LOADED: 'hlsLevelLoaded',\n // fired when a level's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, level : id of updated level }\n LEVEL_UPDATED: 'hlsLevelUpdated',\n // fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment }\n LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated',\n // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }\n AUDIO_TRACKS_UPDATED: 'hlsAudioTracksUpdated',\n // fired when an audio track switching is requested - data: { id : audio track id }\n AUDIO_TRACK_SWITCHING: 'hlsAudioTrackSwitching',\n // fired when an audio track switch actually occurs - data: { id : audio track id }\n AUDIO_TRACK_SWITCHED: 'hlsAudioTrackSwitched',\n // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }\n AUDIO_TRACK_LOADING: 'hlsAudioTrackLoading',\n // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } }\n AUDIO_TRACK_LOADED: 'hlsAudioTrackLoaded',\n // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }\n SUBTITLE_TRACKS_UPDATED: 'hlsSubtitleTracksUpdated',\n // fired when an subtitle track switch occurs - data: { id : subtitle track id }\n SUBTITLE_TRACK_SWITCH: 'hlsSubtitleTrackSwitch',\n // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }\n SUBTITLE_TRACK_LOADING: 'hlsSubtitleTrackLoading',\n // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } }\n SUBTITLE_TRACK_LOADED: 'hlsSubtitleTrackLoaded',\n // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }\n SUBTITLE_FRAG_PROCESSED: 'hlsSubtitleFragProcessed',\n // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, frag : fragment object }\n INIT_PTS_FOUND: 'hlsInitPtsFound',\n // fired when a fragment loading starts - data: { frag : fragment object }\n FRAG_LOADING: 'hlsFragLoading',\n // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }\n FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',\n // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }\n FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',\n // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length } }\n FRAG_LOADED: 'hlsFragLoaded',\n // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }\n FRAG_DECRYPTED: 'hlsFragDecrypted',\n // fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment }\n FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',\n // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }\n FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',\n // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }\n FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',\n // fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}\n FRAG_PARSING_DATA: 'hlsFragParsingData',\n // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }\n FRAG_PARSED: 'hlsFragParsed',\n // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length, bwEstimate } }\n FRAG_BUFFERED: 'hlsFragBuffered',\n // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }\n FRAG_CHANGED: 'hlsFragChanged',\n // Identifier for a FPS drop event - data: { curentDropped, currentDecoded, totalDroppedFrames }\n FPS_DROP: 'hlsFpsDrop',\n // triggered when FPS drop triggers auto level capping - data: { level, droppedlevel }\n FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping',\n // Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data }\n ERROR: 'hlsError',\n // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }\n DESTROYING: 'hlsDestroying',\n // fired when a decrypt key loading starts - data: { frag : fragment object }\n KEY_LOADING: 'hlsKeyLoading',\n // fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length } }\n KEY_LOADED: 'hlsKeyLoaded',\n // fired upon stream controller state transitions - data: { previousState, nextState }\n STREAM_STATE_TRANSITION: 'hlsStreamStateTransition'\n};\n\nexport default HlsEvents;\n","import { getSelfScope } from '../utils/get-self-scope';\n\nconst self = getSelfScope();\nconst Number = self.Number;\n\n// TODO: get rid of global polyfills and replace them with wrappers (\"ponyfills\")\nNumber.isFinite = Number.isFinite || function (value) {\n return typeof value === 'number' && isFinite(value);\n};\n\nexport { Number };\n","export const ErrorTypes = {\n // Identifier for a network error (loading error / timeout ...)\n NETWORK_ERROR: 'networkError',\n // Identifier for a media Error (video/parsing/mediasource error)\n MEDIA_ERROR: 'mediaError',\n // EME (encrypted media extensions) errors\n KEY_SYSTEM_ERROR: 'keySystemError',\n // Identifier for a mux Error (demuxing/remuxing)\n MUX_ERROR: 'muxError',\n // Identifier for all other errors\n OTHER_ERROR: 'otherError'\n};\n\n/**\n * @enum {ErrorDetails}\n * @typedef {string} ErrorDetail\n */\nexport const ErrorDetails = {\n KEY_SYSTEM_NO_KEYS: 'keySystemNoKeys',\n KEY_SYSTEM_NO_ACCESS: 'keySystemNoAccess',\n KEY_SYSTEM_NO_SESSION: 'keySystemNoSession',\n KEY_SYSTEM_LICENSE_REQUEST_FAILED: 'keySystemLicenseRequestFailed',\n // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n MANIFEST_LOAD_ERROR: 'manifestLoadError',\n // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n MANIFEST_LOAD_TIMEOUT: 'manifestLoadTimeOut',\n // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}\n MANIFEST_PARSING_ERROR: 'manifestParsingError',\n // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}\n MANIFEST_INCOMPATIBLE_CODECS_ERROR: 'manifestIncompatibleCodecsError',\n // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n LEVEL_LOAD_ERROR: 'levelLoadError',\n // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n LEVEL_LOAD_TIMEOUT: 'levelLoadTimeOut',\n // Identifier for a level switch error - data: { level : faulty level Id, event : error description}\n LEVEL_SWITCH_ERROR: 'levelSwitchError',\n // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n AUDIO_TRACK_LOAD_ERROR: 'audioTrackLoadError',\n // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n AUDIO_TRACK_LOAD_TIMEOUT: 'audioTrackLoadTimeOut',\n // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}\n FRAG_LOAD_ERROR: 'fragLoadError',\n // Identifier for fragment load timeout error - data: { frag : fragment object}\n FRAG_LOAD_TIMEOUT: 'fragLoadTimeOut',\n // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }\n FRAG_DECRYPT_ERROR: 'fragDecryptError',\n // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }\n // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release\n FRAG_PARSING_ERROR: 'fragParsingError',\n // Identifier for a remux alloc error event - data: { id : demuxer Id, frag : fragment object, bytes : nb of bytes on which allocation failed , reason : error text }\n REMUX_ALLOC_ERROR: 'remuxAllocError',\n // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}\n KEY_LOAD_ERROR: 'keyLoadError',\n // Identifier for decrypt key load timeout error - data: { frag : fragment object}\n KEY_LOAD_TIMEOUT: 'keyLoadTimeOut',\n // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { err : exception , mimeType : mimeType }\n BUFFER_ADD_CODEC_ERROR: 'bufferAddCodecError',\n // Identifier for a buffer append error - data: append error description\n BUFFER_APPEND_ERROR: 'bufferAppendError',\n // Identifier for a buffer appending error event - data: appending error description\n BUFFER_APPENDING_ERROR: 'bufferAppendingError',\n // Identifier for a buffer stalled error event\n BUFFER_STALLED_ERROR: 'bufferStalledError',\n // Identifier for a buffer full event\n BUFFER_FULL_ERROR: 'bufferFullError',\n // Identifier for a buffer seek over hole event\n BUFFER_SEEK_OVER_HOLE: 'bufferSeekOverHole',\n // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)\n BUFFER_NUDGE_ON_STALL: 'bufferNudgeOnStall',\n // Identifier for an internal exception happening inside hls.js while handling an event\n INTERNAL_EXCEPTION: 'internalException'\n};\n","/*\n*\n* All objects in the event handling chain should inherit from this class\n*\n*/\n\nimport { logger } from './utils/logger';\nimport { ErrorTypes, ErrorDetails } from './errors';\nimport Event from './events';\n\nconst FORBIDDEN_EVENT_NAMES = {\n 'hlsEventGeneric': true,\n 'hlsHandlerDestroying': true,\n 'hlsHandlerDestroyed': true\n};\n\nclass EventHandler {\n constructor (hls, ...events) {\n this.hls = hls;\n this.onEvent = this.onEvent.bind(this);\n this.handledEvents = events;\n this.useGenericHandler = true;\n\n this.registerListeners();\n }\n\n destroy () {\n this.onHandlerDestroying();\n this.unregisterListeners();\n this.onHandlerDestroyed();\n }\n\n onHandlerDestroying () {}\n onHandlerDestroyed () {}\n\n isEventHandler () {\n return typeof this.handledEvents === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';\n }\n\n registerListeners () {\n if (this.isEventHandler()) {\n this.handledEvents.forEach(function (event) {\n if (FORBIDDEN_EVENT_NAMES[event]) {\n throw new Error('Forbidden event-name: ' + event);\n }\n\n this.hls.on(event, this.onEvent);\n }, this);\n }\n }\n\n unregisterListeners () {\n if (this.isEventHandler()) {\n this.handledEvents.forEach(function (event) {\n this.hls.off(event, this.onEvent);\n }, this);\n }\n }\n\n /**\n * arguments: event (string), data (any)\n */\n onEvent (event, data) {\n this.onEventGeneric(event, data);\n }\n\n onEventGeneric (event, data) {\n let eventToFunction = function (event, data) {\n let funcName = 'on' + event.replace('hls', '');\n if (typeof this[funcName] !== 'function') {\n throw new Error(`Event ${event} has no generic handler in this ${this.constructor.name} class (tried ${funcName})`);\n }\n\n return this[funcName].bind(this, data);\n };\n try {\n eventToFunction.call(this, event, data).call();\n } catch (err) {\n logger.error(`An internal error happened while handling event ${event}. Error message: \"${err.message}\". Here is a stacktrace:`, err);\n this.hls.trigger(Event.ERROR, { type: ErrorTypes.OTHER_ERROR, details: ErrorDetails.INTERNAL_EXCEPTION, fatal: false, event: event, err: err });\n }\n }\n}\n\nexport default EventHandler;\n","/**\n * @module BufferHelper\n *\n * Providing methods dealing with buffer length retrieval for example.\n *\n * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.\n *\n * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered\n*/\n\nexport class BufferHelper {\n /**\n * Return true if `media`'s buffered include `position`\n * @param {HTMLMediaElement|SourceBuffer} media\n * @param {number} position\n * @returns {boolean}\n */\n static isBuffered (media, position) {\n try {\n if (media) {\n let buffered = media.buffered;\n for (let i = 0; i < buffered.length; i++) {\n if (position >= buffered.start(i) && position <= buffered.end(i)) {\n return true;\n }\n }\n }\n } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return false;\n }\n\n static bufferInfo (media, pos, maxHoleDuration) {\n try {\n if (media) {\n let vbuffered = media.buffered, buffered = [], i;\n for (i = 0; i < vbuffered.length; i++) {\n buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) });\n }\n\n return this.bufferedInfo(buffered, pos, maxHoleDuration);\n }\n } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return { len: 0, start: pos, end: pos, nextStart: undefined };\n }\n\n static bufferedInfo (buffered, pos, maxHoleDuration) {\n let buffered2 = [],\n // bufferStart and bufferEnd are buffer boundaries around current video position\n bufferLen, bufferStart, bufferEnd, bufferStartNext, i;\n // sort on buffer.start/smaller end (IE does not always return sorted buffered range)\n buffered.sort(function (a, b) {\n let diff = a.start - b.start;\n if (diff) {\n return diff;\n } else {\n return b.end - a.end;\n }\n });\n // there might be some small holes between buffer time range\n // consider that holes smaller than maxHoleDuration are irrelevant and build another\n // buffer time range representations that discards those holes\n for (i = 0; i < buffered.length; i++) {\n let buf2len = buffered2.length;\n if (buf2len) {\n let buf2end = buffered2[buf2len - 1].end;\n // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)\n if ((buffered[i].start - buf2end) < maxHoleDuration) {\n // merge overlapping time ranges\n // update lastRange.end only if smaller than item.end\n // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)\n // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])\n if (buffered[i].end > buf2end) {\n buffered2[buf2len - 1].end = buffered[i].end;\n }\n } else {\n // big hole\n buffered2.push(buffered[i]);\n }\n } else {\n // first value\n buffered2.push(buffered[i]);\n }\n }\n for (i = 0, bufferLen = 0, bufferStart = bufferEnd = pos; i < buffered2.length; i++) {\n let start = buffered2[i].start,\n end = buffered2[i].end;\n // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));\n if ((pos + maxHoleDuration) >= start && pos < end) {\n // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length\n bufferStart = start;\n bufferEnd = end;\n bufferLen = bufferEnd - pos;\n } else if ((pos + maxHoleDuration) < start) {\n bufferStartNext = start;\n break;\n }\n }\n return { len: bufferLen, start: bufferStart, end: bufferEnd, nextStart: bufferStartNext };\n }\n}\n","export function getSelfScope () {\n // see https://stackoverflow.com/a/11237259/589493\n if (typeof window === 'undefined') {\n /* eslint-disable-next-line no-undef */\n return self;\n } else {\n return window;\n }\n}\n","import EventHandler from '../event-handler';\nimport Event from '../events';\n\nexport const FragmentState = {\n NOT_LOADED: 'NOT_LOADED',\n APPENDING: 'APPENDING',\n PARTIAL: 'PARTIAL',\n OK: 'OK'\n};\n\nexport class FragmentTracker extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.BUFFER_APPENDED,\n Event.FRAG_BUFFERED,\n Event.FRAG_LOADED\n );\n\n this.bufferPadding = 0.2;\n\n this.fragments = Object.create(null);\n this.timeRanges = Object.create(null);\n\n this.config = hls.config;\n }\n\n destroy () {\n this.fragments = Object.create(null);\n this.timeRanges = Object.create(null);\n this.config = null;\n EventHandler.prototype.destroy.call(this);\n super.destroy();\n }\n\n /**\n * Return a Fragment that match the position and levelType.\n * If not found any Fragment, return null\n * @param {number} position\n * @param {LevelType} levelType\n * @returns {Fragment|null}\n */\n getBufferedFrag (position, levelType) {\n const fragments = this.fragments;\n const bufferedFrags = Object.keys(fragments).filter(key => {\n const fragmentEntity = fragments[key];\n if (fragmentEntity.body.type !== levelType) {\n return false;\n }\n\n if (!fragmentEntity.buffered) {\n return false;\n }\n\n const frag = fragmentEntity.body;\n return frag.startPTS <= position && position <= frag.endPTS;\n });\n if (bufferedFrags.length === 0) {\n return null;\n } else {\n // https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566\n const bufferedFragKey = bufferedFrags.pop();\n return fragments[bufferedFragKey].body;\n }\n }\n\n /**\n * Partial fragments effected by coded frame eviction will be removed\n * The browser will unload parts of the buffer to free up memory for new buffer data\n * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)\n * @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio)\n * @param {TimeRanges} timeRange TimeRange object from a sourceBuffer\n */\n detectEvictedFragments (elementaryStream, timeRange) {\n let fragmentTimes, time;\n // Check if any flagged fragments have been unloaded\n Object.keys(this.fragments).forEach(key => {\n const fragmentEntity = this.fragments[key];\n if (fragmentEntity.buffered === true) {\n const esData = fragmentEntity.range[elementaryStream];\n if (esData) {\n fragmentTimes = esData.time;\n for (let i = 0; i < fragmentTimes.length; i++) {\n time = fragmentTimes[i];\n\n if (this.isTimeBuffered(time.startPTS, time.endPTS, timeRange) === false) {\n // Unregister partial fragment as it needs to load again to be reused\n this.removeFragment(fragmentEntity.body);\n break;\n }\n }\n }\n }\n });\n }\n\n /**\n * Checks if the fragment passed in is loaded in the buffer properly\n * Partially loaded fragments will be registered as a partial fragment\n * @param {Object} fragment Check the fragment against all sourceBuffers loaded\n */\n detectPartialFragments (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = this.fragments[fragKey];\n if (fragmentEntity) {\n fragmentEntity.buffered = true;\n\n Object.keys(this.timeRanges).forEach(elementaryStream => {\n if (fragment.hasElementaryStream(elementaryStream)) {\n let timeRange = this.timeRanges[elementaryStream];\n // Check for malformed fragments\n // Gaps need to be calculated for each elementaryStream\n fragmentEntity.range[elementaryStream] = this.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange);\n }\n });\n }\n }\n\n getBufferedTimes (startPTS, endPTS, timeRange) {\n let fragmentTimes = [];\n let startTime, endTime;\n let fragmentPartial = false;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n // Fragment is entirely contained in buffer\n // No need to check the other timeRange times since it's completely playable\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n break;\n } else if (startPTS < endTime && endPTS > startTime) {\n // Check for intersection with buffer\n // Get playable sections of the fragment\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n fragmentPartial = true;\n } else if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n break;\n }\n }\n\n return {\n time: fragmentTimes,\n partial: fragmentPartial\n };\n }\n\n getFragmentKey (fragment) {\n return `${fragment.type}_${fragment.level}_${fragment.urlId}_${fragment.sn}`;\n }\n\n /**\n * Gets the partial fragment for a certain time\n * @param {Number} time\n * @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment\n */\n getPartialFragment (time) {\n let timePadding, startTime, endTime;\n let bestFragment = null;\n let bestOverlap = 0;\n Object.keys(this.fragments).forEach(key => {\n const fragmentEntity = this.fragments[key];\n if (this.isPartial(fragmentEntity)) {\n startTime = fragmentEntity.body.startPTS - this.bufferPadding;\n endTime = fragmentEntity.body.endPTS + this.bufferPadding;\n if (time >= startTime && time <= endTime) {\n // Use the fragment that has the most padding from start and end time\n timePadding = Math.min(time - startTime, endTime - time);\n if (bestOverlap <= timePadding) {\n bestFragment = fragmentEntity.body;\n bestOverlap = timePadding;\n }\n }\n }\n });\n return bestFragment;\n }\n\n /**\n * @param {Object} fragment The fragment to check\n * @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded\n */\n getState (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = this.fragments[fragKey];\n let state = FragmentState.NOT_LOADED;\n\n if (fragmentEntity !== undefined) {\n if (!fragmentEntity.buffered) {\n state = FragmentState.APPENDING;\n } else if (this.isPartial(fragmentEntity) === true) {\n state = FragmentState.PARTIAL;\n } else {\n state = FragmentState.OK;\n }\n }\n\n return state;\n }\n\n isPartial (fragmentEntity) {\n return fragmentEntity.buffered === true &&\n ((fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true) ||\n (fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true));\n }\n\n isTimeBuffered (startPTS, endPTS, timeRange) {\n let startTime, endTime;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n return true;\n }\n\n if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n return false;\n }\n }\n\n return false;\n }\n\n /**\n * Fires when a fragment loading is completed\n */\n onFragLoaded (e) {\n const fragment = e.frag;\n // don't track initsegment (for which sn is not a number)\n // don't track frags used for bitrateTest, they're irrelevant.\n if (!Number.isFinite(fragment.sn) || fragment.bitrateTest) {\n return;\n }\n\n this.fragments[this.getFragmentKey(fragment)] = {\n body: fragment,\n range: Object.create(null),\n buffered: false\n };\n }\n\n /**\n * Fires when the buffer is updated\n */\n onBufferAppended (e) {\n // Store the latest timeRanges loaded in the buffer\n this.timeRanges = e.timeRanges;\n Object.keys(this.timeRanges).forEach(elementaryStream => {\n let timeRange = this.timeRanges[elementaryStream];\n this.detectEvictedFragments(elementaryStream, timeRange);\n });\n }\n\n /**\n * Fires after a fragment has been loaded into the source buffer\n */\n onFragBuffered (e) {\n this.detectPartialFragments(e.frag);\n }\n\n /**\n * Return true if fragment tracker has the fragment.\n * @param {Object} fragment\n * @returns {boolean}\n */\n hasFragment (fragment) {\n const fragKey = this.getFragmentKey(fragment);\n return this.fragments[fragKey] !== undefined;\n }\n\n /**\n * Remove a fragment from fragment tracker until it is loaded again\n * @param {Object} fragment The fragment to remove\n */\n removeFragment (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n delete this.fragments[fragKey];\n }\n\n /**\n * Remove all fragments from fragment tracker.\n */\n removeAllFragments () {\n this.fragments = Object.create(null);\n }\n}\n","/**\n * @module LevelHelper\n *\n * Providing methods dealing with playlist sliding and drift\n *\n * TODO: Create an actual `Level` class/model that deals with all this logic in an object-oriented-manner.\n *\n * */\n\nimport { logger } from '../utils/logger';\n\nexport function addGroupId (level, type, id) {\n switch (type) {\n case 'audio':\n if (!level.audioGroupIds) {\n level.audioGroupIds = [];\n }\n level.audioGroupIds.push(id);\n break;\n case 'text':\n if (!level.textGroupIds) {\n level.textGroupIds = [];\n }\n level.textGroupIds.push(id);\n break;\n }\n}\n\nexport function updatePTS (fragments, fromIdx, toIdx) {\n let fragFrom = fragments[fromIdx], fragTo = fragments[toIdx], fragToPTS = fragTo.startPTS;\n // if we know startPTS[toIdx]\n if (Number.isFinite(fragToPTS)) {\n // update fragment duration.\n // it helps to fix drifts between playlist reported duration and fragment real duration\n if (toIdx > fromIdx) {\n fragFrom.duration = fragToPTS - fragFrom.start;\n if (fragFrom.duration < 0) {\n logger.warn(`negative duration computed for frag ${fragFrom.sn},level ${fragFrom.level}, there should be some duration drift between playlist and fragment!`);\n }\n } else {\n fragTo.duration = fragFrom.start - fragToPTS;\n if (fragTo.duration < 0) {\n logger.warn(`negative duration computed for frag ${fragTo.sn},level ${fragTo.level}, there should be some duration drift between playlist and fragment!`);\n }\n }\n } else {\n // we dont know startPTS[toIdx]\n if (toIdx > fromIdx) {\n fragTo.start = fragFrom.start + fragFrom.duration;\n } else {\n fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);\n }\n }\n}\n\nexport function updateFragPTSDTS (details, frag, startPTS, endPTS, startDTS, endDTS) {\n // update frag PTS/DTS\n let maxStartPTS = startPTS;\n if (Number.isFinite(frag.startPTS)) {\n // delta PTS between audio and video\n let deltaPTS = Math.abs(frag.startPTS - startPTS);\n if (!Number.isFinite(frag.deltaPTS)) {\n frag.deltaPTS = deltaPTS;\n } else {\n frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);\n }\n\n maxStartPTS = Math.max(startPTS, frag.startPTS);\n startPTS = Math.min(startPTS, frag.startPTS);\n endPTS = Math.max(endPTS, frag.endPTS);\n startDTS = Math.min(startDTS, frag.startDTS);\n endDTS = Math.max(endDTS, frag.endDTS);\n }\n\n const drift = startPTS - frag.start;\n frag.start = frag.startPTS = startPTS;\n frag.maxStartPTS = maxStartPTS;\n frag.endPTS = endPTS;\n frag.startDTS = startDTS;\n frag.endDTS = endDTS;\n frag.duration = endPTS - startPTS;\n\n const sn = frag.sn;\n // exit if sn out of range\n if (!details || sn < details.startSN || sn > details.endSN) {\n return 0;\n }\n\n let fragIdx, fragments, i;\n fragIdx = sn - details.startSN;\n fragments = details.fragments;\n // update frag reference in fragments array\n // rationale is that fragments array might not contain this frag object.\n // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()\n // if we don't update frag, we won't be able to propagate PTS info on the playlist\n // resulting in invalid sliding computation\n fragments[fragIdx] = frag;\n // adjust fragment PTS/duration from seqnum-1 to frag 0\n for (i = fragIdx; i > 0; i--) {\n updatePTS(fragments, i, i - 1);\n }\n\n // adjust fragment PTS/duration from seqnum to last frag\n for (i = fragIdx; i < fragments.length - 1; i++) {\n updatePTS(fragments, i, i + 1);\n }\n\n details.PTSKnown = true;\n return drift;\n}\n\nexport function mergeDetails (oldDetails, newDetails) {\n // potentially retrieve cached initsegment\n if (newDetails.initSegment && oldDetails.initSegment) {\n newDetails.initSegment = oldDetails.initSegment;\n }\n\n // check if old/new playlists have fragments in common\n // loop through overlapping SN and update startPTS , cc, and duration if any found\n let ccOffset = 0;\n let PTSFrag;\n mapFragmentIntersection(oldDetails, newDetails, (oldFrag, newFrag) => {\n ccOffset = oldFrag.cc - newFrag.cc;\n if (Number.isFinite(oldFrag.startPTS)) {\n newFrag.start = newFrag.startPTS = oldFrag.startPTS;\n newFrag.endPTS = oldFrag.endPTS;\n newFrag.duration = oldFrag.duration;\n newFrag.backtracked = oldFrag.backtracked;\n newFrag.dropped = oldFrag.dropped;\n PTSFrag = newFrag;\n }\n // PTS is known when there are overlapping segments\n newDetails.PTSKnown = true;\n });\n\n if (!newDetails.PTSKnown) {\n return;\n }\n\n if (ccOffset) {\n logger.log('discontinuity sliding from playlist, take drift into account');\n const newFragments = newDetails.fragments;\n for (let i = 0; i < newFragments.length; i++) {\n newFragments[i].cc += ccOffset;\n }\n }\n\n // if at least one fragment contains PTS info, recompute PTS information for all fragments\n if (PTSFrag) {\n updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);\n } else {\n // ensure that delta is within oldFragments range\n // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])\n // in that case we also need to adjust start offset of all fragments\n adjustSliding(oldDetails, newDetails);\n }\n // if we are here, it means we have fragments overlapping between\n // old and new level. reliable PTS info is thus relying on old level\n newDetails.PTSKnown = oldDetails.PTSKnown;\n}\n\nexport function mergeSubtitlePlaylists (oldPlaylist, newPlaylist, referenceStart = 0) {\n let lastIndex = -1;\n mapFragmentIntersection(oldPlaylist, newPlaylist, (oldFrag, newFrag, index) => {\n newFrag.start = oldFrag.start;\n lastIndex = index;\n });\n\n const frags = newPlaylist.fragments;\n if (lastIndex < 0) {\n frags.forEach(frag => {\n frag.start += referenceStart;\n });\n return;\n }\n\n for (let i = lastIndex + 1; i < frags.length; i++) {\n frags[i].start = (frags[i - 1].start + frags[i - 1].duration);\n }\n}\n\nexport function mapFragmentIntersection (oldPlaylist, newPlaylist, intersectionFn) {\n if (!oldPlaylist || !newPlaylist) {\n return;\n }\n\n const start = Math.max(oldPlaylist.startSN, newPlaylist.startSN) - newPlaylist.startSN;\n const end = Math.min(oldPlaylist.endSN, newPlaylist.endSN) - newPlaylist.startSN;\n const delta = newPlaylist.startSN - oldPlaylist.startSN;\n\n for (let i = start; i <= end; i++) {\n const oldFrag = oldPlaylist.fragments[delta + i];\n const newFrag = newPlaylist.fragments[i];\n if (!oldFrag || !newFrag) {\n break;\n }\n intersectionFn(oldFrag, newFrag, i);\n }\n}\n\nexport function adjustSliding (oldPlaylist, newPlaylist) {\n const delta = newPlaylist.startSN - oldPlaylist.startSN;\n const oldFragments = oldPlaylist.fragments;\n const newFragments = newPlaylist.fragments;\n\n if (delta < 0 || delta > oldFragments.length) {\n return;\n }\n for (let i = 0; i < newFragments.length; i++) {\n newFragments[i].start += oldFragments[delta].start;\n }\n}\n\nexport function computeReloadInterval (currentPlaylist, newPlaylist, lastRequestTime) {\n let reloadInterval = 1000 * (newPlaylist.averagetargetduration ? newPlaylist.averagetargetduration : newPlaylist.targetduration);\n const minReloadInterval = reloadInterval / 2;\n if (currentPlaylist && newPlaylist.endSN === currentPlaylist.endSN) {\n // follow HLS Spec, If the client reloads a Playlist file and finds that it has not\n // changed then it MUST wait for a period of one-half the target\n // duration before retrying.\n reloadInterval = minReloadInterval;\n }\n\n if (lastRequestTime) {\n reloadInterval = Math.max(minReloadInterval, reloadInterval - (window.performance.now() - lastRequestTime));\n }\n // in any case, don't reload more than half of target duration\n return Math.round(reloadInterval);\n}\n","// see https://tools.ietf.org/html/rfc1808\n\n/* jshint ignore:start */\n(function(root) { \n/* jshint ignore:end */\n\n var URL_REGEX = /^((?:[a-zA-Z0-9+\\-.]+:)?)(\\/\\/[^\\/?#]*)?((?:[^\\/\\?#]*\\/)*.*?)??(;.*?)?(\\?.*?)?(#.*?)?$/;\n var FIRST_SEGMENT_REGEX = /^([^\\/?#]*)(.*)$/;\n var SLASH_DOT_REGEX = /(?:\\/|^)\\.(?=\\/)/g;\n var SLASH_DOT_DOT_REGEX = /(?:\\/|^)\\.\\.\\/(?!\\.\\.\\/).*?(?=\\/)/g;\n\n var URLToolkit = { // jshint ignore:line\n // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //\n // E.g\n // With opts.alwaysNormalize = false (default, spec compliant)\n // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g\n // With opts.alwaysNormalize = true (not spec compliant)\n // http://a.com/b/cd + /e/f/../g => http://a.com/e/g\n buildAbsoluteURL: function(baseURL, relativeURL, opts) {\n opts = opts || {};\n // remove any remaining space and CRLF\n baseURL = baseURL.trim();\n relativeURL = relativeURL.trim();\n if (!relativeURL) {\n // 2a) If the embedded URL is entirely empty, it inherits the\n // entire base URL (i.e., is set equal to the base URL)\n // and we are done.\n if (!opts.alwaysNormalize) {\n return baseURL;\n }\n var basePartsForNormalise = URLToolkit.parseURL(baseURL);\n if (!basePartsForNormalise) {\n throw new Error('Error trying to parse base URL.');\n }\n basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);\n return URLToolkit.buildURLFromParts(basePartsForNormalise);\n }\n var relativeParts = URLToolkit.parseURL(relativeURL);\n if (!relativeParts) {\n throw new Error('Error trying to parse relative URL.');\n }\n if (relativeParts.scheme) {\n // 2b) If the embedded URL starts with a scheme name, it is\n // interpreted as an absolute URL and we are done.\n if (!opts.alwaysNormalize) {\n return relativeURL;\n }\n relativeParts.path = URLToolkit.normalizePath(relativeParts.path);\n return URLToolkit.buildURLFromParts(relativeParts);\n }\n var baseParts = URLToolkit.parseURL(baseURL);\n if (!baseParts) {\n throw new Error('Error trying to parse base URL.');\n }\n if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {\n // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc\n // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'\n var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);\n baseParts.netLoc = pathParts[1];\n baseParts.path = pathParts[2];\n }\n if (baseParts.netLoc && !baseParts.path) {\n baseParts.path = '/';\n }\n var builtParts = {\n // 2c) Otherwise, the embedded URL inherits the scheme of\n // the base URL.\n scheme: baseParts.scheme,\n netLoc: relativeParts.netLoc,\n path: null,\n params: relativeParts.params,\n query: relativeParts.query,\n fragment: relativeParts.fragment\n };\n if (!relativeParts.netLoc) {\n // 3) If the embedded URL's <net_loc> is non-empty, we skip to\n // Step 7. Otherwise, the embedded URL inherits the <net_loc>\n // (if any) of the base URL.\n builtParts.netLoc = baseParts.netLoc;\n // 4) If the embedded URL path is preceded by a slash \"/\", the\n // path is not relative and we skip to Step 7.\n if (relativeParts.path[0] !== '/') {\n if (!relativeParts.path) {\n // 5) If the embedded URL path is empty (and not preceded by a\n // slash), then the embedded URL inherits the base URL path\n builtParts.path = baseParts.path;\n // 5a) if the embedded URL's <params> is non-empty, we skip to\n // step 7; otherwise, it inherits the <params> of the base\n // URL (if any) and\n if (!relativeParts.params) {\n builtParts.params = baseParts.params;\n // 5b) if the embedded URL's <query> is non-empty, we skip to\n // step 7; otherwise, it inherits the <query> of the base\n // URL (if any) and we skip to step 7.\n if (!relativeParts.query) {\n builtParts.query = baseParts.query;\n }\n }\n } else {\n // 6) The last segment of the base URL's path (anything\n // following the rightmost slash \"/\", or the entire path if no\n // slash is present) is removed and the embedded URL's path is\n // appended in its place.\n var baseURLPath = baseParts.path;\n var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;\n builtParts.path = URLToolkit.normalizePath(newPath);\n }\n }\n }\n if (builtParts.path === null) {\n builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;\n }\n return URLToolkit.buildURLFromParts(builtParts);\n },\n parseURL: function(url) {\n var parts = URL_REGEX.exec(url);\n if (!parts) {\n return null;\n }\n return {\n scheme: parts[1] || '',\n netLoc: parts[2] || '',\n path: parts[3] || '',\n params: parts[4] || '',\n query: parts[5] || '',\n fragment: parts[6] || ''\n };\n },\n normalizePath: function(path) {\n // The following operations are\n // then applied, in order, to the new path:\n // 6a) All occurrences of \"./\", where \".\" is a complete path\n // segment, are removed.\n // 6b) If the path ends with \".\" as a complete path segment,\n // that \".\" is removed.\n path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');\n // 6c) All occurrences of \"<segment>/../\", where <segment> is a\n // complete path segment not equal to \"..\", are removed.\n // Removal of these path segments is performed iteratively,\n // removing the leftmost matching pattern on each iteration,\n // until no matching pattern remains.\n // 6d) If the path ends with \"<segment>/..\", where <segment> is a\n // complete path segment not equal to \"..\", that\n // \"<segment>/..\" is removed.\n while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {} // jshint ignore:line\n return path.split('').reverse().join('');\n },\n buildURLFromParts: function(parts) {\n return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;\n }\n };\n\n/* jshint ignore:start */\n if(typeof exports === 'object' && typeof module === 'object')\n module.exports = URLToolkit;\n else if(typeof define === 'function' && define.amd)\n define([], function() { return URLToolkit; });\n else if(typeof exports === 'object')\n exports[\"URLToolkit\"] = URLToolkit;\n else\n root[\"URLToolkit\"] = URLToolkit;\n})(this);\n/* jshint ignore:end */\n","let BinarySearch = {\n /**\n * Searches for an item in an array which matches a certain condition.\n * This requires the condition to only match one item in the array,\n * and for the array to be ordered.\n *\n * @param {Array} list The array to search.\n * @param {Function} comparisonFunction\n * Called and provided a candidate item as the first argument.\n * Should return:\n * > -1 if the item should be located at a lower index than the provided item.\n * > 1 if the item should be located at a higher index than the provided item.\n * > 0 if the item is the item you're looking for.\n *\n * @return {*} The object if it is found or null otherwise.\n */\n search: function (list, comparisonFunction) {\n let minIndex = 0;\n let maxIndex = list.length - 1;\n let currentIndex = null;\n let currentElement = null;\n\n while (minIndex <= maxIndex) {\n currentIndex = (minIndex + maxIndex) / 2 | 0;\n currentElement = list[currentIndex];\n\n let comparisonResult = comparisonFunction(currentElement);\n if (comparisonResult > 0) {\n minIndex = currentIndex + 1;\n } else if (comparisonResult < 0) {\n maxIndex = currentIndex - 1;\n } else {\n return currentElement;\n }\n }\n\n return null;\n }\n};\n\nexport default BinarySearch;\n","/**\n * ID3 parser\n */\nclass ID3 {\n /**\n * Returns true if an ID3 header can be found at offset in data\n * @param {Uint8Array} data - The data to search in\n * @param {number} offset - The offset at which to start searching\n * @return {boolean} - True if an ID3 header is found\n */\n static isHeader (data, offset) {\n /*\n * http://id3.org/id3v2.3.0\n * [0] = 'I'\n * [1] = 'D'\n * [2] = '3'\n * [3,4] = {Version}\n * [5] = {Flags}\n * [6-9] = {ID3 Size}\n *\n * An ID3v2 tag can be detected with the following pattern:\n * $49 44 33 yy yy xx zz zz zz zz\n * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80\n */\n if (offset + 10 <= data.length) {\n // look for 'ID3' identifier\n if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {\n // check version is within range\n if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {\n // check size is within range\n if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {\n return true;\n }\n }\n }\n }\n\n return false;\n }\n\n /**\n * Returns true if an ID3 footer can be found at offset in data\n * @param {Uint8Array} data - The data to search in\n * @param {number} offset - The offset at which to start searching\n * @return {boolean} - True if an ID3 footer is found\n */\n static isFooter (data, offset) {\n /*\n * The footer is a copy of the header, but with a different identifier\n */\n if (offset + 10 <= data.length) {\n // look for '3DI' identifier\n if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {\n // check version is within range\n if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {\n // check size is within range\n if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {\n return true;\n }\n }\n }\n }\n\n return false;\n }\n\n /**\n * Returns any adjacent ID3 tags found in data starting at offset, as one block of data\n * @param {Uint8Array} data - The data to search in\n * @param {number} offset - The offset at which to start searching\n * @return {Uint8Array} - The block of data containing any ID3 tags found\n */\n static getID3Data (data, offset) {\n const front = offset;\n let length = 0;\n\n while (ID3.isHeader(data, offset)) {\n // ID3 header is 10 bytes\n length += 10;\n\n const size = ID3._readSize(data, offset + 6);\n length += size;\n\n if (ID3.isFooter(data, offset + 10)) {\n // ID3 footer is 10 bytes\n length += 10;\n }\n\n offset += length;\n }\n\n if (length > 0) {\n return data.subarray(front, front + length);\n }\n\n return undefined;\n }\n\n static _readSize (data, offset) {\n let size = 0;\n size = ((data[offset] & 0x7f) << 21);\n size |= ((data[offset + 1] & 0x7f) << 14);\n size |= ((data[offset + 2] & 0x7f) << 7);\n size |= (data[offset + 3] & 0x7f);\n return size;\n }\n\n /**\n * Searches for the Elementary Stream timestamp found in the ID3 data chunk\n * @param {Uint8Array} data - Block of data containing one or more ID3 tags\n * @return {number} - The timestamp\n */\n static getTimeStamp (data) {\n const frames = ID3.getID3Frames(data);\n for (let i = 0; i < frames.length; i++) {\n const frame = frames[i];\n if (ID3.isTimeStampFrame(frame)) {\n return ID3._readTimeStamp(frame);\n }\n }\n\n return undefined;\n }\n\n /**\n * Returns true if the ID3 frame is an Elementary Stream timestamp frame\n * @param {ID3 frame} frame\n */\n static isTimeStampFrame (frame) {\n return (frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp');\n }\n\n static _getFrameData (data) {\n /*\n Frame ID $xx xx xx xx (four characters)\n Size $xx xx xx xx\n Flags $xx xx\n */\n const type = String.fromCharCode(data[0], data[1], data[2], data[3]);\n const size = ID3._readSize(data, 4);\n\n // skip frame id, size, and flags\n let offset = 10;\n\n return { type, size, data: data.subarray(offset, offset + size) };\n }\n\n /**\n * Returns an array of ID3 frames found in all the ID3 tags in the id3Data\n * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags\n * @return {ID3 frame[]} - Array of ID3 frame objects\n */\n static getID3Frames (id3Data) {\n let offset = 0;\n const frames = [];\n\n while (ID3.isHeader(id3Data, offset)) {\n const size = ID3._readSize(id3Data, offset + 6);\n // skip past ID3 header\n offset += 10;\n const end = offset + size;\n // loop through frames in the ID3 tag\n while (offset + 8 < end) {\n const frameData = ID3._getFrameData(id3Data.subarray(offset));\n const frame = ID3._decodeFrame(frameData);\n if (frame) {\n frames.push(frame);\n }\n\n // skip frame header and frame data\n offset += frameData.size + 10;\n }\n\n if (ID3.isFooter(id3Data, offset)) {\n offset += 10;\n }\n }\n\n return frames;\n }\n\n static _decodeFrame (frame) {\n if (frame.type === 'PRIV') {\n return ID3._decodePrivFrame(frame);\n } else if (frame.type[0] === 'T') {\n return ID3._decodeTextFrame(frame);\n } else if (frame.type[0] === 'W') {\n return ID3._decodeURLFrame(frame);\n }\n\n return undefined;\n }\n\n static _readTimeStamp (timeStampFrame) {\n if (timeStampFrame.data.byteLength === 8) {\n const data = new Uint8Array(timeStampFrame.data);\n // timestamp is 33 bit expressed as a big-endian eight-octet number,\n // with the upper 31 bits set to zero.\n const pts33Bit = data[3] & 0x1;\n let timestamp = (data[4] << 23) +\n (data[5] << 15) +\n (data[6] << 7) +\n data[7];\n timestamp /= 45;\n\n if (pts33Bit) {\n timestamp += 47721858.84;\n } // 2^32 / 90\n\n return Math.round(timestamp);\n }\n\n return undefined;\n }\n\n static _decodePrivFrame (frame) {\n /*\n Format: <text string>\\0<binary data>\n */\n if (frame.size < 2) {\n return undefined;\n }\n\n const owner = ID3._utf8ArrayToStr(frame.data, true);\n const privateData = new Uint8Array(frame.data.subarray(owner.length + 1));\n\n return { key: frame.type, info: owner, data: privateData.buffer };\n }\n\n static _decodeTextFrame (frame) {\n if (frame.size < 2) {\n return undefined;\n }\n\n if (frame.type === 'TXXX') {\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Description}\\0{Value}\n */\n let index = 1;\n const description = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n index += description.length + 1;\n const value = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n return { key: frame.type, info: description, data: value };\n } else {\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Value}\n */\n const text = ID3._utf8ArrayToStr(frame.data.subarray(1));\n return { key: frame.type, data: text };\n }\n }\n\n static _decodeURLFrame (frame) {\n if (frame.type === 'WXXX') {\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Description}\\0{URL}\n */\n if (frame.size < 2) {\n return undefined;\n }\n\n let index = 1;\n const description = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n index += description.length + 1;\n const value = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n return { key: frame.type, info: description, data: value };\n } else {\n /*\n Format:\n [0-?] = {URL}\n */\n const url = ID3._utf8ArrayToStr(frame.data);\n return { key: frame.type, data: url };\n }\n }\n\n // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197\n // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt\n /* utf.js - UTF-8 <=> UTF-16 convertion\n *\n * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>\n * Version: 1.0\n * LastModified: Dec 25 1999\n * This library is free. You can redistribute it and/or modify it.\n */\n static _utf8ArrayToStr (array, exitOnNull = false) {\n const len = array.length;\n let c;\n let char2;\n let char3;\n let out = '';\n let i = 0;\n while (i < len) {\n c = array[i++];\n if (c === 0x00 && exitOnNull) {\n return out;\n } else if (c === 0x00 || c === 0x03) {\n // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it\n continue;\n }\n switch (c >> 4) {\n case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:\n // 0xxxxxxx\n out += String.fromCharCode(c);\n break;\n case 12: case 13:\n // 110x xxxx 10xx xxxx\n char2 = array[i++];\n out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));\n break;\n case 14:\n // 1110 xxxx 10xx xxxx 10xx xxxx\n char2 = array[i++];\n char3 = array[i++];\n out += String.fromCharCode(((c & 0x0F) << 12) |\n ((char2 & 0x3F) << 6) |\n ((char3 & 0x3F) << 0));\n break;\n default:\n }\n }\n return out;\n }\n}\n\nconst utf8ArrayToStr = ID3._utf8ArrayToStr;\n\nexport default ID3;\n\nexport { utf8ArrayToStr };\n","\nimport * as URLToolkit from 'url-toolkit';\n\nimport LevelKey from './level-key';\n\nexport default class Fragment {\n constructor () {\n this._url = null;\n this._byteRange = null;\n this._decryptdata = null;\n this.tagList = [];\n this.programDateTime = null;\n this.rawProgramDateTime = null;\n\n // Holds the types of data this fragment supports\n this._elementaryStreams = {\n [Fragment.ElementaryStreamTypes.AUDIO]: false,\n [Fragment.ElementaryStreamTypes.VIDEO]: false\n };\n }\n\n /**\n * `type` property for this._elementaryStreams\n *\n * @enum\n */\n static get ElementaryStreamTypes () {\n return {\n AUDIO: 'audio',\n VIDEO: 'video'\n };\n }\n\n get url () {\n if (!this._url && this.relurl) {\n this._url = URLToolkit.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true });\n }\n\n return this._url;\n }\n\n set url (value) {\n this._url = value;\n }\n\n get byteRange () {\n if (!this._byteRange && !this.rawByteRange) {\n return [];\n }\n\n if (this._byteRange) {\n return this._byteRange;\n }\n\n let byteRange = [];\n if (this.rawByteRange) {\n const params = this.rawByteRange.split('@', 2);\n if (params.length === 1) {\n const lastByteRangeEndOffset = this.lastByteRangeEndOffset;\n byteRange[0] = lastByteRangeEndOffset || 0;\n } else {\n byteRange[0] = parseInt(params[1]);\n }\n byteRange[1] = parseInt(params[0]) + byteRange[0];\n this._byteRange = byteRange;\n }\n return byteRange;\n }\n\n /**\n * @type {number}\n */\n get byteRangeStartOffset () {\n return this.byteRange[0];\n }\n\n get byteRangeEndOffset () {\n return this.byteRange[1];\n }\n\n get decryptdata () {\n if (!this._decryptdata) {\n this._decryptdata = this.fragmentDecryptdataFromLevelkey(this.levelkey, this.sn);\n }\n\n return this._decryptdata;\n }\n\n get endProgramDateTime () {\n if (!Number.isFinite(this.programDateTime)) {\n return null;\n }\n\n let duration = !Number.isFinite(this.duration) ? 0 : this.duration;\n\n return this.programDateTime + (duration * 1000);\n }\n\n get encrypted () {\n return !!((this.decryptdata && this.decryptdata.uri !== null) && (this.decryptdata.key === null));\n }\n\n /**\n * @param {ElementaryStreamType} type\n */\n addElementaryStream (type) {\n this._elementaryStreams[type] = true;\n }\n\n /**\n * @param {ElementaryStreamType} type\n */\n hasElementaryStream (type) {\n return this._elementaryStreams[type] === true;\n }\n\n /**\n * Utility method for parseLevelPlaylist to create an initialization vector for a given segment\n * @returns {Uint8Array}\n */\n createInitializationVector (segmentNumber) {\n let uint8View = new Uint8Array(16);\n\n for (let i = 12; i < 16; i++) {\n uint8View[i] = (segmentNumber >> 8 * (15 - i)) & 0xff;\n }\n\n return uint8View;\n }\n\n /**\n * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data\n * @param levelkey - a playlist's encryption info\n * @param segmentNumber - the fragment's segment number\n * @returns {*} - an object to be applied as a fragment's decryptdata\n */\n fragmentDecryptdataFromLevelkey (levelkey, segmentNumber) {\n let decryptdata = levelkey;\n\n if (levelkey && levelkey.method && levelkey.uri && !levelkey.iv) {\n decryptdata = new LevelKey();\n decryptdata.method = levelkey.method;\n decryptdata.baseuri = levelkey.baseuri;\n decryptdata.reluri = levelkey.reluri;\n decryptdata.iv = this.createInitializationVector(segmentNumber);\n }\n\n return decryptdata;\n }\n}\n","import AESCrypto from './aes-crypto';\nimport FastAESKey from './fast-aes-key';\nimport AESDecryptor from './aes-decryptor';\n\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\n\nimport Event from '../events';\n\nimport { getSelfScope } from '../utils/get-self-scope';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\n\nclass Decrypter {\n constructor (observer, config, { removePKCS7Padding = true } = {}) {\n this.logEnabled = true;\n this.observer = observer;\n this.config = config;\n this.removePKCS7Padding = removePKCS7Padding;\n // built in decryptor expects PKCS7 padding\n if (removePKCS7Padding) {\n try {\n const browserCrypto = global.crypto;\n if (browserCrypto) {\n this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;\n }\n } catch (e) {}\n }\n this.disableWebCrypto = !this.subtle;\n }\n\n isSync () {\n return (this.disableWebCrypto && this.config.enableSoftwareAES);\n }\n\n decrypt (data, key, iv, callback) {\n if (this.disableWebCrypto && this.config.enableSoftwareAES) {\n if (this.logEnabled) {\n logger.log('JS AES decrypt');\n this.logEnabled = false;\n }\n let decryptor = this.decryptor;\n if (!decryptor) {\n this.decryptor = decryptor = new AESDecryptor();\n }\n\n decryptor.expandKey(key);\n callback(decryptor.decrypt(data, 0, iv, this.removePKCS7Padding));\n } else {\n if (this.logEnabled) {\n logger.log('WebCrypto AES decrypt');\n this.logEnabled = false;\n }\n const subtle = this.subtle;\n if (this.key !== key) {\n this.key = key;\n this.fastAesKey = new FastAESKey(subtle, key);\n }\n\n this.fastAesKey.expandKey()\n .then((aesKey) => {\n // decrypt using web crypto\n let crypto = new AESCrypto(subtle, iv);\n crypto.decrypt(data, aesKey)\n .catch((err) => {\n this.onWebCryptoError(err, data, key, iv, callback);\n })\n .then((result) => {\n callback(result);\n });\n })\n .catch((err) => {\n this.onWebCryptoError(err, data, key, iv, callback);\n });\n }\n }\n\n onWebCryptoError (err, data, key, iv, callback) {\n if (this.config.enableSoftwareAES) {\n logger.log('WebCrypto Error, disable WebCrypto API');\n this.disableWebCrypto = true;\n this.logEnabled = true;\n this.decrypt(data, key, iv, callback);\n } else {\n logger.error(`decrypting error : ${err.message}`);\n this.observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_DECRYPT_ERROR, fatal: true, reason: err.message });\n }\n }\n\n destroy () {\n let decryptor = this.decryptor;\n if (decryptor) {\n decryptor.destroy();\n this.decryptor = undefined;\n }\n }\n}\n\nexport default Decrypter;\n","/**\n * MediaSource helper\n */\n\nexport function getMediaSource () {\n if (typeof window !== 'undefined') {\n return window.MediaSource || window.WebKitMediaSource;\n }\n}\n","import TaskLoop from '../task-loop';\nimport { FragmentState } from './fragment-tracker';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport { logger } from '../utils/logger';\n\nexport const State = {\n STOPPED: 'STOPPED',\n STARTING: 'STARTING',\n IDLE: 'IDLE',\n PAUSED: 'PAUSED',\n KEY_LOADING: 'KEY_LOADING',\n FRAG_LOADING: 'FRAG_LOADING',\n FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',\n WAITING_TRACK: 'WAITING_TRACK',\n PARSING: 'PARSING',\n PARSED: 'PARSED',\n BUFFER_FLUSHING: 'BUFFER_FLUSHING',\n ENDED: 'ENDED',\n ERROR: 'ERROR',\n WAITING_INIT_PTS: 'WAITING_INIT_PTS',\n WAITING_LEVEL: 'WAITING_LEVEL'\n};\n\nexport default class BaseStreamController extends TaskLoop {\n doTick () {}\n\n startLoad () {}\n\n stopLoad () {\n let frag = this.fragCurrent;\n if (frag) {\n if (frag.loader) {\n frag.loader.abort();\n }\n this.fragmentTracker.removeFragment(frag);\n }\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n this.fragCurrent = null;\n this.fragPrevious = null;\n this.clearInterval();\n this.clearNextTick();\n this.state = State.STOPPED;\n }\n\n _streamEnded (bufferInfo, levelDetails) {\n const { fragCurrent, fragmentTracker } = this;\n // we just got done loading the final fragment and there is no other buffered range after ...\n // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between\n // so we should not switch to ENDED in that case, to be able to buffer them\n // dont switch to ENDED if we need to backtrack last fragment\n if (!levelDetails.live && fragCurrent && !fragCurrent.backtracked && fragCurrent.sn === levelDetails.endSN && !bufferInfo.nextStart) {\n const fragState = fragmentTracker.getState(fragCurrent);\n return fragState === FragmentState.PARTIAL || fragState === FragmentState.OK;\n }\n return false;\n }\n\n onMediaSeeking () {\n const { config, media, mediaBuffer, state } = this;\n const currentTime = media ? media.currentTime : null;\n const bufferInfo = BufferHelper.bufferInfo(mediaBuffer || media, currentTime, this.config.maxBufferHole);\n\n if (Number.isFinite(currentTime)) {\n logger.log(`media seeking to ${currentTime.toFixed(3)}`);\n }\n\n if (state === State.FRAG_LOADING) {\n let fragCurrent = this.fragCurrent;\n // check if we are seeking to a unbuffered area AND if frag loading is in progress\n if (bufferInfo.len === 0 && fragCurrent) {\n const tolerance = config.maxFragLookUpTolerance;\n const fragStartOffset = fragCurrent.start - tolerance;\n const fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;\n // check if we seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything\n if (currentTime < fragStartOffset || currentTime > fragEndOffset) {\n if (fragCurrent.loader) {\n logger.log('seeking outside of buffer while fragment load in progress, cancel fragment load');\n fragCurrent.loader.abort();\n }\n this.fragCurrent = null;\n this.fragPrevious = null;\n // switch to IDLE state to load new fragment\n this.state = State.IDLE;\n } else {\n logger.log('seeking outside of buffer but within currently loaded fragment range');\n }\n }\n } else if (state === State.ENDED) {\n // if seeking to unbuffered area, clean up fragPrevious\n if (bufferInfo.len === 0) {\n this.fragPrevious = null;\n this.fragCurrent = null;\n }\n\n // switch to IDLE state to check for potential new fragment\n this.state = State.IDLE;\n }\n if (media) {\n this.lastCurrentTime = currentTime;\n }\n\n // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target\n if (!this.loadedmetadata) {\n this.nextLoadPosition = this.startPosition = currentTime;\n }\n\n // tick to speed up processing\n this.tick();\n }\n\n onMediaEnded () {\n // reset startPosition and lastCurrentTime to restart playback @ stream beginning\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n onHandlerDestroying () {\n this.stopLoad();\n super.onHandlerDestroying();\n }\n\n onHandlerDestroyed () {\n this.state = State.STOPPED;\n this.fragmentTracker = null;\n }\n}\n","/**\n * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.\n *\n * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.\n *\n * Uses loader(s) set in config to do actual internal loading of resource tasks.\n *\n * @module\n *\n */\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport { logger } from '../utils/logger';\n\nimport MP4Demuxer from '../demux/mp4demuxer';\nimport M3U8Parser from './m3u8-parser';\n\nconst { performance } = window;\n\n/**\n * `type` property values for this loaders' context object\n * @enum\n *\n */\nconst ContextType = {\n MANIFEST: 'manifest',\n LEVEL: 'level',\n AUDIO_TRACK: 'audioTrack',\n SUBTITLE_TRACK: 'subtitleTrack'\n};\n\n/**\n * @enum {string}\n */\nconst LevelType = {\n MAIN: 'main',\n AUDIO: 'audio',\n SUBTITLE: 'subtitle'\n};\n\n/**\n * @constructor\n */\nclass PlaylistLoader extends EventHandler {\n /**\n * @constructs\n * @param {Hls} hls\n */\n constructor (hls) {\n super(hls,\n Event.MANIFEST_LOADING,\n Event.LEVEL_LOADING,\n Event.AUDIO_TRACK_LOADING,\n Event.SUBTITLE_TRACK_LOADING);\n\n this.loaders = {};\n }\n\n static get ContextType () {\n return ContextType;\n }\n\n static get LevelType () {\n return LevelType;\n }\n\n /**\n * @param {ContextType} type\n * @returns {boolean}\n */\n static canHaveQualityLevels (type) {\n return (type !== ContextType.AUDIO_TRACK &&\n type !== ContextType.SUBTITLE_TRACK);\n }\n\n /**\n * Map context.type to LevelType\n * @param {{type: ContextType}} context\n * @returns {LevelType}\n */\n static mapContextToLevelType (context) {\n const { type } = context;\n\n switch (type) {\n case ContextType.AUDIO_TRACK:\n return LevelType.AUDIO;\n case ContextType.SUBTITLE_TRACK:\n return LevelType.SUBTITLE;\n default:\n return LevelType.MAIN;\n }\n }\n\n static getResponseUrl (response, context) {\n let url = response.url;\n // responseURL not supported on some browsers (it is used to detect URL redirection)\n // data-uri mode also not supported (but no need to detect redirection)\n if (url === undefined || url.indexOf('data:') === 0) {\n // fallback to initial URL\n url = context.url;\n }\n return url;\n }\n\n /**\n * Returns defaults or configured loader-type overloads (pLoader and loader config params)\n * Default loader is XHRLoader (see utils)\n * @param {object} context\n * @returns {XHRLoader} or other compatible configured overload\n */\n createInternalLoader (context) {\n const config = this.hls.config;\n const PLoader = config.pLoader;\n const Loader = config.loader;\n const InternalLoader = PLoader || Loader;\n\n const loader = new InternalLoader(config);\n\n context.loader = loader;\n this.loaders[context.type] = loader;\n\n return loader;\n }\n\n getInternalLoader (context) {\n return this.loaders[context.type];\n }\n\n resetInternalLoader (contextType) {\n if (this.loaders[contextType]) {\n delete this.loaders[contextType];\n }\n }\n\n /**\n * Call `destroy` on all internal loader instances mapped (one per context type)\n */\n destroyInternalLoaders () {\n for (let contextType in this.loaders) {\n let loader = this.loaders[contextType];\n if (loader) {\n loader.destroy();\n }\n\n this.resetInternalLoader(contextType);\n }\n }\n\n destroy () {\n this.destroyInternalLoaders();\n\n super.destroy();\n }\n\n onManifestLoading (data) {\n this.load(data.url, { type: ContextType.MANIFEST, level: 0, id: null });\n }\n\n onLevelLoading (data) {\n this.load(data.url, { type: ContextType.LEVEL, level: data.level, id: data.id });\n }\n\n onAudioTrackLoading (data) {\n this.load(data.url, { type: ContextType.AUDIO_TRACK, level: null, id: data.id });\n }\n\n onSubtitleTrackLoading (data) {\n this.load(data.url, { type: ContextType.SUBTITLE_TRACK, level: null, id: data.id });\n }\n\n load (url, context) {\n const config = this.hls.config;\n\n logger.debug(`Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);\n\n // Check if a loader for this context already exists\n let loader = this.getInternalLoader(context);\n if (loader) {\n const loaderContext = loader.context;\n if (loaderContext && loaderContext.url === url) { // same URL can't overlap\n logger.trace('playlist request ongoing');\n return false;\n } else {\n logger.warn(`aborting previous loader for type: ${context.type}`);\n loader.abort();\n }\n }\n\n let maxRetry,\n timeout,\n retryDelay,\n maxRetryDelay;\n\n // apply different configs for retries depending on\n // context (manifest, level, audio/subs playlist)\n switch (context.type) {\n case ContextType.MANIFEST:\n maxRetry = config.manifestLoadingMaxRetry;\n timeout = config.manifestLoadingTimeOut;\n retryDelay = config.manifestLoadingRetryDelay;\n maxRetryDelay = config.manifestLoadingMaxRetryTimeout;\n break;\n case ContextType.LEVEL:\n // Disable internal loader retry logic, since we are managing retries in Level Controller\n maxRetry = 0;\n timeout = config.levelLoadingTimeOut;\n // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config\n break;\n default:\n maxRetry = config.levelLoadingMaxRetry;\n timeout = config.levelLoadingTimeOut;\n retryDelay = config.levelLoadingRetryDelay;\n maxRetryDelay = config.levelLoadingMaxRetryTimeout;\n break;\n }\n\n loader = this.createInternalLoader(context);\n\n context.url = url;\n context.responseType = context.responseType || ''; // FIXME: (should not be necessary to do this)\n\n const loaderConfig = {\n timeout,\n maxRetry,\n retryDelay,\n maxRetryDelay\n };\n\n const loaderCallbacks = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this)\n };\n\n logger.debug(`Calling internal loader delegate for URL: ${url}`);\n\n loader.load(context, loaderConfig, loaderCallbacks);\n\n return true;\n }\n\n loadsuccess (response, stats, context, networkDetails = null) {\n if (context.isSidxRequest) {\n this._handleSidxRequest(response, context);\n this._handlePlaylistLoaded(response, stats, context, networkDetails);\n return;\n }\n\n this.resetInternalLoader(context.type);\n\n const string = response.data;\n\n stats.tload = performance.now();\n // stats.mtime = new Date(target.getResponseHeader('Last-Modified'));\n\n // Validate if it is an M3U8 at all\n if (string.indexOf('#EXTM3U') !== 0) {\n this._handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);\n return;\n }\n\n // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)\n if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {\n this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails);\n } else {\n this._handleMasterPlaylist(response, stats, context, networkDetails);\n }\n }\n\n loaderror (response, context, networkDetails = null) {\n this._handleNetworkError(context, networkDetails, false, response);\n }\n\n loadtimeout (stats, context, networkDetails = null) {\n this._handleNetworkError(context, networkDetails, true);\n }\n\n _handleMasterPlaylist (response, stats, context, networkDetails) {\n const hls = this.hls;\n const string = response.data;\n\n const url = PlaylistLoader.getResponseUrl(response, context);\n\n const levels = M3U8Parser.parseMasterPlaylist(string, url);\n if (!levels.length) {\n this._handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);\n return;\n }\n\n // multi level playlist, parse level info\n\n const audioGroups = levels.map(level => ({\n id: level.attrs.AUDIO,\n codec: level.audioCodec\n }));\n\n let audioTracks = M3U8Parser.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);\n let subtitles = M3U8Parser.parseMasterPlaylistMedia(string, url, 'SUBTITLES');\n\n if (audioTracks.length) {\n // check if we have found an audio track embedded in main playlist (audio track without URI attribute)\n let embeddedAudioFound = false;\n audioTracks.forEach(audioTrack => {\n if (!audioTrack.url) {\n embeddedAudioFound = true;\n }\n });\n\n // if no embedded audio track defined, but audio codec signaled in quality level,\n // we need to signal this main audio track this could happen with playlists with\n // alt audio rendition in which quality levels (main)\n // contains both audio+video. but with mixed audio track not signaled\n if (embeddedAudioFound === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) {\n logger.log('audio codec signaled in quality level, but no embedded audio track signaled, create one');\n audioTracks.unshift({\n type: 'main',\n name: 'main'\n });\n }\n }\n\n hls.trigger(Event.MANIFEST_LOADED, {\n levels,\n audioTracks,\n subtitles,\n url,\n stats,\n networkDetails\n });\n }\n\n _handleTrackOrLevelPlaylist (response, stats, context, networkDetails) {\n const hls = this.hls;\n\n const { id, level, type } = context;\n\n const url = PlaylistLoader.getResponseUrl(response, context);\n\n const levelUrlId = Number.isFinite(id) ? id : 0;\n const levelId = Number.isFinite(level) ? level : levelUrlId;\n const levelType = PlaylistLoader.mapContextToLevelType(context);\n\n const levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId);\n\n // set stats on level structure\n levelDetails.tload = stats.tload;\n\n // We have done our first request (Manifest-type) and receive\n // not a master playlist but a chunk-list (track/level)\n // We fire the manifest-loaded event anyway with the parsed level-details\n // by creating a single-level structure for it.\n if (type === ContextType.MANIFEST) {\n const singleLevel = {\n url,\n details: levelDetails\n };\n\n hls.trigger(Event.MANIFEST_LOADED, {\n levels: [singleLevel],\n audioTracks: [],\n url,\n stats,\n networkDetails\n });\n }\n\n // save parsing time\n stats.tparsed = performance.now();\n\n // in case we need SIDX ranges\n // return early after calling load for\n // the SIDX box.\n if (levelDetails.needSidxRanges) {\n const sidxUrl = levelDetails.initSegment.url;\n this.load(sidxUrl, {\n isSidxRequest: true,\n type,\n level,\n levelDetails,\n id,\n rangeStart: 0,\n rangeEnd: 2048,\n responseType: 'arraybuffer'\n });\n return;\n }\n\n // extend the context with the new levelDetails property\n context.levelDetails = levelDetails;\n\n this._handlePlaylistLoaded(response, stats, context, networkDetails);\n }\n\n _handleSidxRequest (response, context) {\n const sidxInfo = MP4Demuxer.parseSegmentIndex(new Uint8Array(response.data));\n // if provided fragment does not contain sidx, early return\n if (!sidxInfo) {\n return;\n }\n const sidxReferences = sidxInfo.references;\n const levelDetails = context.levelDetails;\n sidxReferences.forEach((segmentRef, index) => {\n const segRefInfo = segmentRef.info;\n const frag = levelDetails.fragments[index];\n\n if (frag.byteRange.length === 0) {\n frag.rawByteRange = String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start);\n }\n });\n levelDetails.initSegment.rawByteRange = String(sidxInfo.moovEndOffset) + '@0';\n }\n\n _handleManifestParsingError (response, context, reason, networkDetails) {\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.MANIFEST_PARSING_ERROR,\n fatal: true,\n url: response.url,\n reason,\n networkDetails\n });\n }\n\n _handleNetworkError (context, networkDetails, timeout = false, response = null) {\n logger.info(`A network error occured while loading a ${context.type}-type playlist`);\n\n let details;\n let fatal;\n\n const loader = this.getInternalLoader(context);\n\n switch (context.type) {\n case ContextType.MANIFEST:\n details = (timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR);\n fatal = true;\n break;\n case ContextType.LEVEL:\n details = (timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR);\n fatal = false;\n break;\n case ContextType.AUDIO_TRACK:\n details = (timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR);\n fatal = false;\n break;\n default:\n // details = ...?\n fatal = false;\n }\n\n if (loader) {\n loader.abort();\n this.resetInternalLoader(context.type);\n }\n\n let errorData = {\n type: ErrorTypes.NETWORK_ERROR,\n details,\n fatal,\n url: loader.url,\n loader,\n context,\n networkDetails\n };\n\n if (response) {\n errorData.response = response;\n }\n\n this.hls.trigger(Event.ERROR, errorData);\n }\n\n _handlePlaylistLoaded (response, stats, context, networkDetails) {\n const { type, level, id, levelDetails } = context;\n\n if (!levelDetails.targetduration) {\n this._handleManifestParsingError(response, context, 'invalid target duration', networkDetails);\n return;\n }\n\n const canHaveLevels = PlaylistLoader.canHaveQualityLevels(context.type);\n if (canHaveLevels) {\n this.hls.trigger(Event.LEVEL_LOADED, {\n details: levelDetails,\n level: level || 0,\n id: id || 0,\n stats,\n networkDetails\n });\n } else {\n switch (type) {\n case ContextType.AUDIO_TRACK:\n this.hls.trigger(Event.AUDIO_TRACK_LOADED, {\n details: levelDetails,\n id,\n stats,\n networkDetails\n });\n break;\n case ContextType.SUBTITLE_TRACK:\n this.hls.trigger(Event.SUBTITLE_TRACK_LOADED, {\n details: levelDetails,\n id,\n stats,\n networkDetails\n });\n break;\n }\n }\n }\n}\n\nexport default PlaylistLoader;\n","/**\n * MP4 demuxer\n */\nimport { logger } from '../utils/logger';\nimport Event from '../events';\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\n\nclass MP4Demuxer {\n constructor (observer, remuxer) {\n this.observer = observer;\n this.remuxer = remuxer;\n }\n\n resetTimeStamp (initPTS) {\n this.initPTS = initPTS;\n }\n\n resetInitSegment (initSegment, audioCodec, videoCodec, duration) {\n // jshint unused:false\n if (initSegment && initSegment.byteLength) {\n const initData = this.initData = MP4Demuxer.parseInitSegment(initSegment);\n\n // default audio codec if nothing specified\n // TODO : extract that from initsegment\n if (audioCodec == null) {\n audioCodec = 'mp4a.40.5';\n }\n\n if (videoCodec == null) {\n videoCodec = 'avc1.42e01e';\n }\n\n const tracks = {};\n if (initData.audio && initData.video) {\n tracks.audiovideo = { container: 'video/mp4', codec: audioCodec + ',' + videoCodec, initSegment: duration ? initSegment : null };\n } else {\n if (initData.audio) {\n tracks.audio = { container: 'audio/mp4', codec: audioCodec, initSegment: duration ? initSegment : null };\n }\n\n if (initData.video) {\n tracks.video = { container: 'video/mp4', codec: videoCodec, initSegment: duration ? initSegment : null };\n }\n }\n this.observer.trigger(Event.FRAG_PARSING_INIT_SEGMENT, { tracks });\n } else {\n if (audioCodec) {\n this.audioCodec = audioCodec;\n }\n\n if (videoCodec) {\n this.videoCodec = videoCodec;\n }\n }\n }\n\n static probe (data) {\n // ensure we find a moof box in the first 16 kB\n return MP4Demuxer.findBox({ data: data, start: 0, end: Math.min(data.length, 16384) }, ['moof']).length > 0;\n }\n\n static bin2str (buffer) {\n return String.fromCharCode.apply(null, buffer);\n }\n\n static readUint16 (buffer, offset) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n\n const val = buffer[offset] << 8 |\n buffer[offset + 1];\n\n return val < 0 ? 65536 + val : val;\n }\n\n static readUint32 (buffer, offset) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n\n const val = buffer[offset] << 24 |\n buffer[offset + 1] << 16 |\n buffer[offset + 2] << 8 |\n buffer[offset + 3];\n return val < 0 ? 4294967296 + val : val;\n }\n\n static writeUint32 (buffer, offset, value) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n buffer[offset] = value >> 24;\n buffer[offset + 1] = (value >> 16) & 0xff;\n buffer[offset + 2] = (value >> 8) & 0xff;\n buffer[offset + 3] = value & 0xff;\n }\n\n // Find the data for a box specified by its path\n static findBox (data, path) {\n let results = [],\n i, size, type, end, subresults, start, endbox;\n\n if (data.data) {\n start = data.start;\n end = data.end;\n data = data.data;\n } else {\n start = 0;\n end = data.byteLength;\n }\n\n if (!path.length) {\n // short-circuit the search for empty paths\n return null;\n }\n\n for (i = start; i < end;) {\n size = MP4Demuxer.readUint32(data, i);\n type = MP4Demuxer.bin2str(data.subarray(i + 4, i + 8));\n endbox = size > 1 ? i + size : end;\n\n if (type === path[0]) {\n if (path.length === 1) {\n // this is the end of the path and we've found the box we were\n // looking for\n results.push({ data: data, start: i + 8, end: endbox });\n } else {\n // recursively search for the next box along the path\n subresults = MP4Demuxer.findBox({ data: data, start: i + 8, end: endbox }, path.slice(1));\n if (subresults.length) {\n results = results.concat(subresults);\n }\n }\n }\n i = endbox;\n }\n\n // we've finished searching all of data\n return results;\n }\n\n static parseSegmentIndex (initSegment) {\n const moov = MP4Demuxer.findBox(initSegment, ['moov'])[0];\n const moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data\n\n let index = 0;\n let sidx = MP4Demuxer.findBox(initSegment, ['sidx']);\n let references;\n\n if (!sidx || !sidx[0]) {\n return null;\n }\n\n references = [];\n sidx = sidx[0];\n\n const version = sidx.data[0];\n\n // set initial offset, we skip the reference ID (not needed)\n index = version === 0 ? 8 : 16;\n\n const timescale = MP4Demuxer.readUint32(sidx, index);\n index += 4;\n\n // TODO: parse earliestPresentationTime and firstOffset\n // usually zero in our case\n let earliestPresentationTime = 0;\n let firstOffset = 0;\n\n if (version === 0) {\n index += 8;\n } else {\n index += 16;\n }\n\n // skip reserved\n index += 2;\n\n let startByte = sidx.end + firstOffset;\n\n const referencesCount = MP4Demuxer.readUint16(sidx, index);\n index += 2;\n\n for (let i = 0; i < referencesCount; i++) {\n let referenceIndex = index;\n\n const referenceInfo = MP4Demuxer.readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n const referenceSize = referenceInfo & 0x7FFFFFFF;\n const referenceType = (referenceInfo & 0x80000000) >>> 31;\n\n if (referenceType === 1) {\n console.warn('SIDX has hierarchical references (not supported)');\n return;\n }\n\n const subsegmentDuration = MP4Demuxer.readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n references.push({\n referenceSize,\n subsegmentDuration, // unscaled\n info: {\n duration: subsegmentDuration / timescale,\n start: startByte,\n end: startByte + referenceSize - 1\n }\n });\n\n startByte += referenceSize;\n\n // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits\n // for |sapDelta|.\n referenceIndex += 4;\n\n // skip to next ref\n index = referenceIndex;\n }\n\n return {\n earliestPresentationTime,\n timescale,\n version,\n referencesCount,\n references,\n moovEndOffset\n };\n }\n\n /**\n * Parses an MP4 initialization segment and extracts stream type and\n * timescale values for any declared tracks. Timescale values indicate the\n * number of clock ticks per second to assume for time-based values\n * elsewhere in the MP4.\n *\n * To determine the start time of an MP4, you need two pieces of\n * information: the timescale unit and the earliest base media decode\n * time. Multiple timescales can be specified within an MP4 but the\n * base media decode time is always expressed in the timescale from\n * the media header box for the track:\n * ```\n * moov > trak > mdia > mdhd.timescale\n * moov > trak > mdia > hdlr\n * ```\n * @param init {Uint8Array} the bytes of the init segment\n * @return {object} a hash of track type to timescale values or null if\n * the init segment is malformed.\n */\n static parseInitSegment (initSegment) {\n let result = [];\n let traks = MP4Demuxer.findBox(initSegment, ['moov', 'trak']);\n\n traks.forEach(trak => {\n const tkhd = MP4Demuxer.findBox(trak, ['tkhd'])[0];\n if (tkhd) {\n let version = tkhd.data[tkhd.start];\n let index = version === 0 ? 12 : 20;\n let trackId = MP4Demuxer.readUint32(tkhd, index);\n\n const mdhd = MP4Demuxer.findBox(trak, ['mdia', 'mdhd'])[0];\n if (mdhd) {\n version = mdhd.data[mdhd.start];\n index = version === 0 ? 12 : 20;\n const timescale = MP4Demuxer.readUint32(mdhd, index);\n\n const hdlr = MP4Demuxer.findBox(trak, ['mdia', 'hdlr'])[0];\n if (hdlr) {\n const hdlrType = MP4Demuxer.bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));\n let type = { 'soun': 'audio', 'vide': 'video' }[hdlrType];\n if (type) {\n // extract codec info. TODO : parse codec details to be able to build MIME type\n let codecBox = MP4Demuxer.findBox(trak, ['mdia', 'minf', 'stbl', 'stsd']);\n if (codecBox.length) {\n codecBox = codecBox[0];\n let codecType = MP4Demuxer.bin2str(codecBox.data.subarray(codecBox.start + 12, codecBox.start + 16));\n logger.log(`MP4Demuxer:${type}:${codecType} found`);\n }\n result[trackId] = { timescale: timescale, type: type };\n result[type] = { timescale: timescale, id: trackId };\n }\n }\n }\n }\n });\n return result;\n }\n\n /**\n * Determine the base media decode start time, in seconds, for an MP4\n * fragment. If multiple fragments are specified, the earliest time is\n * returned.\n *\n * The base media decode time can be parsed from track fragment\n * metadata:\n * ```\n * moof > traf > tfdt.baseMediaDecodeTime\n * ```\n * It requires the timescale value from the mdhd to interpret.\n *\n * @param timescale {object} a hash of track ids to timescale values.\n * @return {number} the earliest base media decode start time for the\n * fragment, in seconds\n */\n static getStartDTS (initData, fragment) {\n let trafs, baseTimes, result;\n\n // we need info from two childrend of each track fragment box\n trafs = MP4Demuxer.findBox(fragment, ['moof', 'traf']);\n\n // determine the start times for each track\n baseTimes = [].concat.apply([], trafs.map(function (traf) {\n return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {\n let id, scale, baseTime;\n\n // get the track id from the tfhd\n id = MP4Demuxer.readUint32(tfhd, 4);\n // assume a 90kHz clock if no timescale was specified\n scale = initData[id].timescale || 90e3;\n\n // get the base media decode time from the tfdt\n baseTime = MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {\n let version, result;\n\n version = tfdt.data[tfdt.start];\n result = MP4Demuxer.readUint32(tfdt, 4);\n if (version === 1) {\n result *= Math.pow(2, 32);\n\n result += MP4Demuxer.readUint32(tfdt, 8);\n }\n return result;\n })[0];\n // convert base time to seconds\n return baseTime / scale;\n });\n }));\n\n // return the minimum\n result = Math.min.apply(null, baseTimes);\n return isFinite(result) ? result : 0;\n }\n\n static offsetStartDTS (initData, fragment, timeOffset) {\n MP4Demuxer.findBox(fragment, ['moof', 'traf']).map(function (traf) {\n return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {\n // get the track id from the tfhd\n let id = MP4Demuxer.readUint32(tfhd, 4);\n // assume a 90kHz clock if no timescale was specified\n let timescale = initData[id].timescale || 90e3;\n\n // get the base media decode time from the tfdt\n MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {\n let version = tfdt.data[tfdt.start];\n let baseMediaDecodeTime = MP4Demuxer.readUint32(tfdt, 4);\n if (version === 0) {\n MP4Demuxer.writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale);\n } else {\n baseMediaDecodeTime *= Math.pow(2, 32);\n baseMediaDecodeTime += MP4Demuxer.readUint32(tfdt, 8);\n baseMediaDecodeTime -= timeOffset * timescale;\n baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);\n const upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));\n const lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));\n MP4Demuxer.writeUint32(tfdt, 4, upper);\n MP4Demuxer.writeUint32(tfdt, 8, lower);\n }\n });\n });\n });\n }\n\n // feed incoming data to the front of the parsing pipeline\n append (data, timeOffset, contiguous, accurateTimeOffset) {\n let initData = this.initData;\n if (!initData) {\n this.resetInitSegment(data, this.audioCodec, this.videoCodec, false);\n initData = this.initData;\n }\n let startDTS, initPTS = this.initPTS;\n if (initPTS === undefined) {\n let startDTS = MP4Demuxer.getStartDTS(initData, data);\n this.initPTS = initPTS = startDTS - timeOffset;\n this.observer.trigger(Event.INIT_PTS_FOUND, { initPTS: initPTS });\n }\n MP4Demuxer.offsetStartDTS(initData, data, initPTS);\n startDTS = MP4Demuxer.getStartDTS(initData, data);\n this.remuxer.remux(initData.audio, initData.video, null, null, startDTS, contiguous, accurateTimeOffset, data);\n }\n\n destroy () {}\n}\n\nexport default MP4Demuxer;\n","import * as URLToolkit from 'url-toolkit';\n\nexport default class LevelKey {\n constructor () {\n this.method = null;\n this.key = null;\n this.iv = null;\n this._uri = null;\n }\n\n get uri () {\n if (!this._uri && this.reluri) {\n this._uri = URLToolkit.buildAbsoluteURL(this.baseuri, this.reluri, { alwaysNormalize: true });\n }\n\n return this._uri;\n }\n}\n","// from http://mp4ra.org/codecs.html\nconst sampleEntryCodesISO = {\n audio: {\n 'a3ds': true,\n 'ac-3': true,\n 'ac-4': true,\n 'alac': true,\n 'alaw': true,\n 'dra1': true,\n 'dts+': true,\n 'dts-': true,\n 'dtsc': true,\n 'dtse': true,\n 'dtsh': true,\n 'ec-3': true,\n 'enca': true,\n 'g719': true,\n 'g726': true,\n 'm4ae': true,\n 'mha1': true,\n 'mha2': true,\n 'mhm1': true,\n 'mhm2': true,\n 'mlpa': true,\n 'mp4a': true,\n 'raw ': true,\n 'Opus': true,\n 'samr': true,\n 'sawb': true,\n 'sawp': true,\n 'sevc': true,\n 'sqcp': true,\n 'ssmv': true,\n 'twos': true,\n 'ulaw': true\n },\n video: {\n 'avc1': true,\n 'avc2': true,\n 'avc3': true,\n 'avc4': true,\n 'avcp': true,\n 'drac': true,\n 'dvav': true,\n 'dvhe': true,\n 'encv': true,\n 'hev1': true,\n 'hvc1': true,\n 'mjp2': true,\n 'mp4v': true,\n 'mvc1': true,\n 'mvc2': true,\n 'mvc3': true,\n 'mvc4': true,\n 'resv': true,\n 'rv60': true,\n 's263': true,\n 'svc1': true,\n 'svc2': true,\n 'vc-1': true,\n 'vp08': true,\n 'vp09': true\n }\n};\n\nfunction isCodecType (codec, type) {\n const typeCodes = sampleEntryCodesISO[type];\n return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;\n}\n\nfunction isCodecSupportedInMp4 (codec, type) {\n return window.MediaSource.isTypeSupported(`${type || 'video'}/mp4;codecs=\"${codec}\"`);\n}\n\nexport { isCodecType, isCodecSupportedInMp4 };\n","import { EventEmitter } from 'events';\nimport * as work from 'webworkify-webpack';\n\nimport Event from '../events';\nimport DemuxerInline from '../demux/demuxer-inline';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { getMediaSource } from '../utils/mediasource-helper';\nimport { getSelfScope } from '../utils/get-self-scope';\n\nimport { Observer } from '../observer';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\nconst MediaSource = getMediaSource();\n\nclass Demuxer {\n constructor (hls, id) {\n this.hls = hls;\n this.id = id;\n\n const observer = this.observer = new Observer();\n const config = hls.config;\n\n const forwardMessage = (ev, data) => {\n data = data || {};\n data.frag = this.frag;\n data.id = this.id;\n hls.trigger(ev, data);\n };\n\n // forward events to main thread\n observer.on(Event.FRAG_DECRYPTED, forwardMessage);\n observer.on(Event.FRAG_PARSING_INIT_SEGMENT, forwardMessage);\n observer.on(Event.FRAG_PARSING_DATA, forwardMessage);\n observer.on(Event.FRAG_PARSED, forwardMessage);\n observer.on(Event.ERROR, forwardMessage);\n observer.on(Event.FRAG_PARSING_METADATA, forwardMessage);\n observer.on(Event.FRAG_PARSING_USERDATA, forwardMessage);\n observer.on(Event.INIT_PTS_FOUND, forwardMessage);\n\n const typeSupported = {\n mp4: MediaSource.isTypeSupported('video/mp4'),\n mpeg: MediaSource.isTypeSupported('audio/mpeg'),\n mp3: MediaSource.isTypeSupported('audio/mp4; codecs=\"mp3\"')\n };\n // navigator.vendor is not always available in Web Worker\n // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator\n const vendor = navigator.vendor;\n if (config.enableWorker && (typeof (Worker) !== 'undefined')) {\n logger.log('demuxing in webworker');\n let w;\n try {\n w = this.w = work(require.resolve('../demux/demuxer-worker.js'));\n this.onwmsg = this.onWorkerMessage.bind(this);\n w.addEventListener('message', this.onwmsg);\n w.onerror = function (event) {\n hls.trigger(Event.ERROR, { type: ErrorTypes.OTHER_ERROR, details: ErrorDetails.INTERNAL_EXCEPTION, fatal: true, event: 'demuxerWorker', err: { message: event.message + ' (' + event.filename + ':' + event.lineno + ')' } });\n };\n w.postMessage({ cmd: 'init', typeSupported: typeSupported, vendor: vendor, id: id, config: JSON.stringify(config) });\n } catch (err) {\n logger.warn('Error in worker:', err);\n logger.error('Error while initializing DemuxerWorker, fallback on DemuxerInline');\n if (w) {\n // revoke the Object URL that was used to create demuxer worker, so as not to leak it\n global.URL.revokeObjectURL(w.objectURL);\n }\n this.demuxer = new DemuxerInline(observer, typeSupported, config, vendor);\n this.w = undefined;\n }\n } else {\n this.demuxer = new DemuxerInline(observer, typeSupported, config, vendor);\n }\n }\n\n destroy () {\n let w = this.w;\n if (w) {\n w.removeEventListener('message', this.onwmsg);\n w.terminate();\n this.w = null;\n } else {\n let demuxer = this.demuxer;\n if (demuxer) {\n demuxer.destroy();\n this.demuxer = null;\n }\n }\n const observer = this.observer;\n if (observer) {\n observer.removeAllListeners();\n this.observer = null;\n }\n }\n\n push (data, initSegment, audioCodec, videoCodec, frag, duration, accurateTimeOffset, defaultInitPTS) {\n const w = this.w;\n const timeOffset = Number.isFinite(frag.startPTS) ? frag.startPTS : frag.start;\n const decryptdata = frag.decryptdata;\n const lastFrag = this.frag;\n const discontinuity = !(lastFrag && (frag.cc === lastFrag.cc));\n const trackSwitch = !(lastFrag && (frag.level === lastFrag.level));\n const nextSN = lastFrag && (frag.sn === (lastFrag.sn + 1));\n const contiguous = !trackSwitch && nextSN;\n if (discontinuity) {\n logger.log(`${this.id}:discontinuity detected`);\n }\n\n if (trackSwitch) {\n logger.log(`${this.id}:switch detected`);\n }\n\n this.frag = frag;\n if (w) {\n // post fragment payload as transferable objects for ArrayBuffer (no copy)\n w.postMessage({ cmd: 'demux', data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS }, data instanceof ArrayBuffer ? [data] : []);\n } else {\n let demuxer = this.demuxer;\n if (demuxer) {\n demuxer.push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);\n }\n }\n }\n\n onWorkerMessage (ev) {\n let data = ev.data,\n hls = this.hls;\n switch (data.event) {\n case 'init':\n // revoke the Object URL that was used to create demuxer worker, so as not to leak it\n global.URL.revokeObjectURL(this.w.objectURL);\n break;\n // special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects\n case Event.FRAG_PARSING_DATA:\n data.data.data1 = new Uint8Array(data.data1);\n if (data.data2) {\n data.data.data2 = new Uint8Array(data.data2);\n }\n\n /* falls through */\n default:\n data.data = data.data || {};\n data.data.frag = this.frag;\n data.data.id = this.id;\n hls.trigger(data.event, data.data);\n break;\n }\n }\n}\n\nexport default Demuxer;\n","/**\n *\n * inline demuxer: probe fragments and instantiate\n * appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)\n *\n */\n\nimport Event from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport Decrypter from '../crypt/decrypter';\nimport AACDemuxer from '../demux/aacdemuxer';\nimport MP4Demuxer from '../demux/mp4demuxer';\nimport TSDemuxer from '../demux/tsdemuxer';\nimport MP3Demuxer from '../demux/mp3demuxer';\nimport MP4Remuxer from '../remux/mp4-remuxer';\nimport PassThroughRemuxer from '../remux/passthrough-remuxer';\n\nimport { getSelfScope } from '../utils/get-self-scope';\nimport { logger } from '../utils/logger';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\n\nlet now;\n// performance.now() not available on WebWorker, at least on Safari Desktop\ntry {\n now = global.performance.now.bind(global.performance);\n} catch (err) {\n logger.debug('Unable to use Performance API on this environment');\n now = global.Date.now;\n}\n\nclass DemuxerInline {\n constructor (observer, typeSupported, config, vendor) {\n this.observer = observer;\n this.typeSupported = typeSupported;\n this.config = config;\n this.vendor = vendor;\n }\n\n destroy () {\n let demuxer = this.demuxer;\n if (demuxer) {\n demuxer.destroy();\n }\n }\n\n push (data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {\n if ((data.byteLength > 0) && (decryptdata != null) && (decryptdata.key != null) && (decryptdata.method === 'AES-128')) {\n let decrypter = this.decrypter;\n if (decrypter == null) {\n decrypter = this.decrypter = new Decrypter(this.observer, this.config);\n }\n\n const startTime = now();\n decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, (decryptedData) => {\n const endTime = now();\n this.observer.trigger(Event.FRAG_DECRYPTED, { stats: { tstart: startTime, tdecrypt: endTime } });\n this.pushDecrypted(new Uint8Array(decryptedData), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);\n });\n } else {\n this.pushDecrypted(new Uint8Array(data), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);\n }\n }\n\n pushDecrypted (data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {\n let demuxer = this.demuxer;\n if (!demuxer ||\n // in case of continuity change, or track switch\n // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)\n // so let's check that current demuxer is still valid\n ((discontinuity || trackSwitch) && !this.probe(data))) {\n const observer = this.observer;\n const typeSupported = this.typeSupported;\n const config = this.config;\n // probing order is TS/AAC/MP3/MP4\n const muxConfig = [\n { demux: TSDemuxer, remux: MP4Remuxer },\n { demux: MP4Demuxer, remux: PassThroughRemuxer },\n { demux: AACDemuxer, remux: MP4Remuxer },\n { demux: MP3Demuxer, remux: MP4Remuxer }\n ];\n\n // probe for content type\n for (let i = 0, len = muxConfig.length; i < len; i++) {\n const mux = muxConfig[i];\n const probe = mux.demux.probe;\n if (probe(data)) {\n const remuxer = this.remuxer = new mux.remux(observer, config, typeSupported, this.vendor);\n demuxer = new mux.demux(observer, remuxer, config, typeSupported);\n this.probe = probe;\n break;\n }\n }\n if (!demuxer) {\n observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found' });\n return;\n }\n this.demuxer = demuxer;\n }\n const remuxer = this.remuxer;\n\n if (discontinuity || trackSwitch) {\n demuxer.resetInitSegment(initSegment, audioCodec, videoCodec, duration);\n remuxer.resetInitSegment();\n }\n if (discontinuity) {\n demuxer.resetTimeStamp(defaultInitPTS);\n remuxer.resetTimeStamp(defaultInitPTS);\n }\n if (typeof demuxer.setDecryptData === 'function') {\n demuxer.setDecryptData(decryptdata);\n }\n\n demuxer.append(data, timeOffset, contiguous, accurateTimeOffset);\n }\n}\n\nexport default DemuxerInline;\n","/**\n * ADTS parser helper\n */\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport Event from '../events';\n\nimport { getSelfScope } from '../utils/get-self-scope';\n\nexport function getAudioConfig (observer, data, offset, audioCodec) {\n let adtsObjectType, // :int\n adtsSampleingIndex, // :int\n adtsExtensionSampleingIndex, // :int\n adtsChanelConfig, // :int\n config,\n userAgent = navigator.userAgent.toLowerCase(),\n manifestCodec = audioCodec,\n adtsSampleingRates = [\n 96000, 88200,\n 64000, 48000,\n 44100, 32000,\n 24000, 22050,\n 16000, 12000,\n 11025, 8000,\n 7350];\n // byte 2\n adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1;\n adtsSampleingIndex = ((data[offset + 2] & 0x3C) >>> 2);\n if (adtsSampleingIndex > adtsSampleingRates.length - 1) {\n observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: `invalid ADTS sampling index:${adtsSampleingIndex}` });\n return;\n }\n adtsChanelConfig = ((data[offset + 2] & 0x01) << 2);\n // byte 3\n adtsChanelConfig |= ((data[offset + 3] & 0xC0) >>> 6);\n logger.log(`manifest codec:${audioCodec},ADTS data:type:${adtsObjectType},sampleingIndex:${adtsSampleingIndex}[${adtsSampleingRates[adtsSampleingIndex]}Hz],channelConfig:${adtsChanelConfig}`);\n // firefox: freq less than 24kHz = AAC SBR (HE-AAC)\n if (/firefox/i.test(userAgent)) {\n if (adtsSampleingIndex >= 6) {\n adtsObjectType = 5;\n config = new Array(4);\n // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n // there is a factor 2 between frame sample rate and output sample rate\n // multiply frequency by 2 (see table below, equivalent to substract 3)\n adtsExtensionSampleingIndex = adtsSampleingIndex - 3;\n } else {\n adtsObjectType = 2;\n config = new Array(2);\n adtsExtensionSampleingIndex = adtsSampleingIndex;\n }\n // Android : always use AAC\n } else if (userAgent.indexOf('android') !== -1) {\n adtsObjectType = 2;\n config = new Array(2);\n adtsExtensionSampleingIndex = adtsSampleingIndex;\n } else {\n /* for other browsers (Chrome/Vivaldi/Opera ...)\n always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)\n */\n adtsObjectType = 5;\n config = new Array(4);\n // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)\n if ((audioCodec && ((audioCodec.indexOf('mp4a.40.29') !== -1) ||\n (audioCodec.indexOf('mp4a.40.5') !== -1))) ||\n (!audioCodec && adtsSampleingIndex >= 6)) {\n // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n // there is a factor 2 between frame sample rate and output sample rate\n // multiply frequency by 2 (see table below, equivalent to substract 3)\n adtsExtensionSampleingIndex = adtsSampleingIndex - 3;\n } else {\n // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)\n // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.\n if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && ((adtsSampleingIndex >= 6 && adtsChanelConfig === 1) ||\n /vivaldi/i.test(userAgent)) ||\n (!audioCodec && adtsChanelConfig === 1)) {\n adtsObjectType = 2;\n config = new Array(2);\n }\n adtsExtensionSampleingIndex = adtsSampleingIndex;\n }\n }\n /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config\n ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()\n Audio Profile / Audio Object Type\n 0: Null\n 1: AAC Main\n 2: AAC LC (Low Complexity)\n 3: AAC SSR (Scalable Sample Rate)\n 4: AAC LTP (Long Term Prediction)\n 5: SBR (Spectral Band Replication)\n 6: AAC Scalable\n sampling freq\n 0: 96000 Hz\n 1: 88200 Hz\n 2: 64000 Hz\n 3: 48000 Hz\n 4: 44100 Hz\n 5: 32000 Hz\n 6: 24000 Hz\n 7: 22050 Hz\n 8: 16000 Hz\n 9: 12000 Hz\n 10: 11025 Hz\n 11: 8000 Hz\n 12: 7350 Hz\n 13: Reserved\n 14: Reserved\n 15: frequency is written explictly\n Channel Configurations\n These are the channel configurations:\n 0: Defined in AOT Specifc Config\n 1: 1 channel: front-center\n 2: 2 channels: front-left, front-right\n */\n // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1\n config[0] = adtsObjectType << 3;\n // samplingFrequencyIndex\n config[0] |= (adtsSampleingIndex & 0x0E) >> 1;\n config[1] |= (adtsSampleingIndex & 0x01) << 7;\n // channelConfiguration\n config[1] |= adtsChanelConfig << 3;\n if (adtsObjectType === 5) {\n // adtsExtensionSampleingIndex\n config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1;\n config[2] = (adtsExtensionSampleingIndex & 0x01) << 7;\n // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???\n // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc\n config[2] |= 2 << 2;\n config[3] = 0;\n }\n return { config: config, samplerate: adtsSampleingRates[adtsSampleingIndex], channelCount: adtsChanelConfig, codec: ('mp4a.40.' + adtsObjectType), manifestCodec: manifestCodec };\n}\n\nexport function isHeaderPattern (data, offset) {\n return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;\n}\n\nexport function getHeaderLength (data, offset) {\n return (data[offset + 1] & 0x01 ? 7 : 9);\n}\n\nexport function getFullFrameLength (data, offset) {\n return ((data[offset + 3] & 0x03) << 11) |\n (data[offset + 4] << 3) |\n ((data[offset + 5] & 0xE0) >>> 5);\n}\n\nexport function isHeader (data, offset) {\n // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n // More info https://wiki.multimedia.cx/index.php?title=ADTS\n if (offset + 1 < data.length && isHeaderPattern(data, offset)) {\n return true;\n }\n\n return false;\n}\n\nexport function probe (data, offset) {\n // same as isHeader but we also check that ADTS frame follows last ADTS frame\n // or end of data is reached\n if (offset + 1 < data.length && isHeaderPattern(data, offset)) {\n // ADTS header Length\n let headerLength = getHeaderLength(data, offset);\n // ADTS frame Length\n let frameLength = headerLength;\n if (offset + 5 < data.length) {\n frameLength = getFullFrameLength(data, offset);\n }\n\n let newOffset = offset + frameLength;\n if (newOffset === data.length || (newOffset + 1 < data.length && isHeaderPattern(data, newOffset))) {\n return true;\n }\n }\n return false;\n}\n\nexport function initTrackConfig (track, observer, data, offset, audioCodec) {\n if (!track.samplerate) {\n let config = getAudioConfig(observer, data, offset, audioCodec);\n track.config = config.config;\n track.samplerate = config.samplerate;\n track.channelCount = config.channelCount;\n track.codec = config.codec;\n track.manifestCodec = config.manifestCodec;\n logger.log(`parsed codec:${track.codec},rate:${config.samplerate},nb channel:${config.channelCount}`);\n }\n}\n\nexport function getFrameDuration (samplerate) {\n return 1024 * 90000 / samplerate;\n}\n\nexport function parseFrameHeader (data, offset, pts, frameIndex, frameDuration) {\n let headerLength, frameLength, stamp;\n let length = data.length;\n\n // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header\n headerLength = getHeaderLength(data, offset);\n // retrieve frame size\n frameLength = getFullFrameLength(data, offset);\n frameLength -= headerLength;\n\n if ((frameLength > 0) && ((offset + headerLength + frameLength) <= length)) {\n stamp = pts + frameIndex * frameDuration;\n // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);\n return { headerLength, frameLength, stamp };\n }\n\n return undefined;\n}\n\nexport function appendFrame (track, data, offset, pts, frameIndex) {\n let frameDuration = getFrameDuration(track.samplerate);\n let header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);\n if (header) {\n let stamp = header.stamp;\n let headerLength = header.headerLength;\n let frameLength = header.frameLength;\n\n // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);\n let aacSample = {\n unit: data.subarray(offset + headerLength, offset + headerLength + frameLength),\n pts: stamp,\n dts: stamp\n };\n\n track.samples.push(aacSample);\n track.len += frameLength;\n\n return { sample: aacSample, length: frameLength + headerLength };\n }\n\n return undefined;\n}\n","/**\n * MPEG parser helper\n */\n\nconst MpegAudio = {\n\n BitratesMap: [\n 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448,\n 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384,\n 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,\n 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256,\n 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],\n\n SamplingRateMap: [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000],\n\n SamplesCoefficients: [\n // MPEG 2.5\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12 // Layer1\n ],\n // Reserved\n [\n 0, // Reserved\n 0, // Layer3\n 0, // Layer2\n 0 // Layer1\n ],\n // MPEG 2\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12 // Layer1\n ],\n // MPEG 1\n [\n 0, // Reserved\n 144, // Layer3\n 144, // Layer2\n 12 // Layer1\n ]\n ],\n\n BytesInSlot: [\n 0, // Reserved\n 1, // Layer3\n 1, // Layer2\n 4 // Layer1\n ],\n\n appendFrame: function (track, data, offset, pts, frameIndex) {\n // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference\n if (offset + 24 > data.length) {\n return undefined;\n }\n\n let header = this.parseHeader(data, offset);\n if (header && offset + header.frameLength <= data.length) {\n let frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;\n let stamp = pts + frameIndex * frameDuration;\n let sample = { unit: data.subarray(offset, offset + header.frameLength), pts: stamp, dts: stamp };\n\n track.config = [];\n track.channelCount = header.channelCount;\n track.samplerate = header.sampleRate;\n track.samples.push(sample);\n track.len += header.frameLength;\n\n return { sample, length: header.frameLength };\n }\n\n return undefined;\n },\n\n parseHeader: function (data, offset) {\n let headerB = (data[offset + 1] >> 3) & 3;\n let headerC = (data[offset + 1] >> 1) & 3;\n let headerE = (data[offset + 2] >> 4) & 15;\n let headerF = (data[offset + 2] >> 2) & 3;\n let headerG = (data[offset + 2] >> 1) & 1;\n if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {\n let columnInBitrates = headerB === 3 ? (3 - headerC) : (headerC === 3 ? 3 : 4);\n let bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;\n let columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;\n let sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF];\n let channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)\n let sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC];\n let bytesInSlot = MpegAudio.BytesInSlot[headerC];\n let samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;\n let frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot;\n\n return { sampleRate, channelCount, frameLength, samplesPerFrame };\n }\n\n return undefined;\n },\n\n isHeaderPattern: function (data, offset) {\n return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;\n },\n\n isHeader: function (data, offset) {\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {\n return true;\n }\n\n return false;\n },\n\n probe: function (data, offset) {\n // same as isHeader but we also check that MPEG frame follows last MPEG frame\n // or end of data is reached\n if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {\n // MPEG header Length\n let headerLength = 4;\n // MPEG frame Length\n let header = this.parseHeader(data, offset);\n let frameLength = headerLength;\n if (header && header.frameLength) {\n frameLength = header.frameLength;\n }\n\n let newOffset = offset + frameLength;\n if (newOffset === data.length || (newOffset + 1 < data.length && this.isHeaderPattern(data, newOffset))) {\n return true;\n }\n }\n return false;\n }\n};\n\nexport default MpegAudio;\n","import { EventEmitter } from 'eventemitter3';\n\n/**\n * @class\n *\n * Simple adapter sub-class of Nodejs-like EventEmitter.\n *\n * We simply want to pass along the event-name itself\n * in every call to a handler, which is the purpose of our `trigger` method\n * extending the standard API.\n *\n */\nexport class Observer extends EventEmitter {\n /**\n *\n * @param {string} event\n * @param {any} data\n */\n trigger (event, ...data) {\n this.emit(event, event, ...data);\n }\n}\n","/**\n * TimeRanges to string helper\n */\n\nconst TimeRanges = {\n toString: function (r) {\n let log = '', len = r.length;\n for (let i = 0; i < len; i++) {\n log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';\n }\n\n return log;\n }\n};\n\nexport default TimeRanges;\n","import BinarySearch from './binary-search';\nimport { logger } from '../utils/logger';\n\nexport function findFirstFragWithCC (fragments, cc) {\n let firstFrag = null;\n\n for (let i = 0; i < fragments.length; i += 1) {\n const currentFrag = fragments[i];\n if (currentFrag && currentFrag.cc === cc) {\n firstFrag = currentFrag;\n break;\n }\n }\n\n return firstFrag;\n}\n\nexport function findFragWithCC (fragments, CC) {\n return BinarySearch.search(fragments, (candidate) => {\n if (candidate.cc < CC) {\n return 1;\n } else if (candidate.cc > CC) {\n return -1;\n } else {\n return 0;\n }\n });\n}\n\nexport function shouldAlignOnDiscontinuities (lastFrag, lastLevel, details) {\n let shouldAlign = false;\n if (lastLevel && lastLevel.details && details) {\n if (details.endCC > details.startCC || (lastFrag && lastFrag.cc < details.startCC)) {\n shouldAlign = true;\n }\n }\n return shouldAlign;\n}\n\n// Find the first frag in the previous level which matches the CC of the first frag of the new level\nexport function findDiscontinuousReferenceFrag (prevDetails, curDetails) {\n const prevFrags = prevDetails.fragments;\n const curFrags = curDetails.fragments;\n\n if (!curFrags.length || !prevFrags.length) {\n logger.log('No fragments to align');\n return;\n }\n\n const prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);\n\n if (!prevStartFrag || (prevStartFrag && !prevStartFrag.startPTS)) {\n logger.log('No frag in previous level to align on');\n return;\n }\n\n return prevStartFrag;\n}\n\nexport function adjustPts (sliding, details) {\n details.fragments.forEach((frag) => {\n if (frag) {\n let start = frag.start + sliding;\n frag.start = frag.startPTS = start;\n frag.endPTS = start + frag.duration;\n }\n });\n details.PTSKnown = true;\n}\n\n/**\n * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a\n * contiguous stream with the last fragments.\n * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to\n * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time\n * and an extra download.\n * @param lastFrag\n * @param lastLevel\n * @param details\n */\nexport function alignStream (lastFrag, lastLevel, details) {\n alignDiscontinuities(lastFrag, details, lastLevel);\n if (!details.PTSKnown && lastLevel) {\n // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.\n // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same\n // discontinuity sequence.\n alignPDT(details, lastLevel.details);\n }\n}\n\n/**\n * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same\n * discontinuity sequence.\n * @param lastLevel - The details of the last loaded level\n * @param details - The details of the new level\n */\nexport function alignDiscontinuities (lastFrag, details, lastLevel) {\n if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {\n const referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);\n if (referenceFrag) {\n logger.log('Adjusting PTS using last level due to CC increase within current level');\n adjustPts(referenceFrag.start, details);\n }\n }\n}\n\n/**\n * Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.\n * @param details - The details of the new level\n * @param lastDetails - The details of the last loaded level\n */\nexport function alignPDT (details, lastDetails) {\n if (lastDetails && lastDetails.fragments.length) {\n if (!details.hasProgramDateTime || !lastDetails.hasProgramDateTime) {\n return;\n }\n // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM\n // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM\n // then we can deduce that playlist B sliding is 1000+8 = 1008s\n let lastPDT = lastDetails.fragments[0].programDateTime;\n let newPDT = details.fragments[0].programDateTime;\n // date diff is in ms. frag.start is in seconds\n let sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;\n if (Number.isFinite(sliding)) {\n logger.log(`adjusting PTS using programDateTime delta, sliding:${sliding.toFixed(3)}`);\n adjustPts(sliding, details);\n }\n }\n}\n","import BinarySearch from '../utils/binary-search';\n\n/**\n * Returns first fragment whose endPdt value exceeds the given PDT.\n * @param {Array<Fragment>} fragments - The array of candidate fragments\n * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded\n * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous\n * @returns {*|null} fragment - The best matching fragment\n */\nexport function findFragmentByPDT (fragments, PDTValue, maxFragLookUpTolerance) {\n if (!Array.isArray(fragments) || !fragments.length || !Number.isFinite(PDTValue)) {\n return null;\n }\n\n // if less than start\n if (PDTValue < fragments[0].programDateTime) {\n return null;\n }\n\n if (PDTValue >= fragments[fragments.length - 1].endProgramDateTime) {\n return null;\n }\n\n maxFragLookUpTolerance = maxFragLookUpTolerance || 0;\n for (let seg = 0; seg < fragments.length; ++seg) {\n let frag = fragments[seg];\n if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {\n return frag;\n }\n }\n\n return null;\n}\n\n/**\n * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.\n * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus\n * breaking any traps which would cause the same fragment to be continuously selected within a small range.\n * @param {*} fragPrevious - The last frag successfully appended\n * @param {Array<Fragment>} fragments - The array of candidate fragments\n * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within\n * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous\n * @returns {*} foundFrag - The best matching fragment\n */\nexport function findFragmentByPTS (fragPrevious, fragments, bufferEnd = 0, maxFragLookUpTolerance = 0) {\n const fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : null;\n // Prefer the next fragment if it's within tolerance\n if (fragNext && !fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext)) {\n return fragNext;\n }\n return BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));\n}\n\n/**\n * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.\n * @param {*} candidate - The fragment to test\n * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within\n * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {number} - 0 if it matches, 1 if too low, -1 if too high\n */\nexport function fragmentWithinToleranceTest (bufferEnd = 0, maxFragLookUpTolerance = 0, candidate) {\n // offset should be within fragment boundary - config.maxFragLookUpTolerance\n // this is to cope with situations like\n // bufferEnd = 9.991\n // frag[Ø] : [0,10]\n // frag[1] : [10,20]\n // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here\n // frag start frag start+duration\n // |-----------------------------|\n // <---> <--->\n // ...--------><-----------------------------><---------....\n // previous frag matching fragment next frag\n // return -1 return 0 return 1\n // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);\n // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments\n let candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));\n if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {\n return 1;\n } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n return -1;\n }\n\n return 0;\n}\n\n/**\n * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.\n * This function tests the candidate's program date time values, as represented in Unix time\n * @param {*} candidate - The fragment to test\n * @param {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range\n * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {boolean} True if contiguous, false otherwise\n */\nexport function pdtWithinToleranceTest (pdtBufferEnd, maxFragLookUpTolerance, candidate) {\n let candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000;\n return candidate.endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;\n}\n","import EventHandler from './event-handler';\n\n/**\n * Sub-class specialization of EventHandler base class.\n *\n * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,\n * scheduled asynchroneously, avoiding recursive calls in the same tick.\n *\n * The task itself is implemented in `doTick`. It can be requested and called for single execution\n * using the `tick` method.\n *\n * It will be assured that the task execution method (`tick`) only gets called once per main loop \"tick\",\n * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.\n *\n * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,\n * and cancelled with `clearNextTick`.\n *\n * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).\n *\n * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.\n *\n * Further explanations:\n *\n * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously\n * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.\n *\n * When the task execution (`tick` method) is called in re-entrant way this is detected and\n * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further\n * task processing on the next main loop iteration (also known as \"next tick\" in the Node/JS runtime lingo).\n */\n\nexport default class TaskLoop extends EventHandler {\n constructor (hls, ...events) {\n super(hls, ...events);\n\n this._tickInterval = null;\n this._tickTimer = null;\n this._tickCallCount = 0;\n this._boundTick = this.tick.bind(this);\n }\n\n /**\n * @override\n */\n onHandlerDestroying () {\n // clear all timers before unregistering from event bus\n this.clearNextTick();\n this.clearInterval();\n }\n\n /**\n * @returns {boolean}\n */\n hasInterval () {\n return !!this._tickInterval;\n }\n\n /**\n * @returns {boolean}\n */\n hasNextTick () {\n return !!this._tickTimer;\n }\n\n /**\n * @param {number} millis Interval time (ms)\n * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)\n */\n setInterval (millis) {\n if (!this._tickInterval) {\n this._tickInterval = setInterval(this._boundTick, millis);\n return true;\n }\n return false;\n }\n\n /**\n * @returns {boolean} True when interval was cleared, false when none was set (no effect)\n */\n clearInterval () {\n if (this._tickInterval) {\n clearInterval(this._tickInterval);\n this._tickInterval = null;\n return true;\n }\n return false;\n }\n\n /**\n * @returns {boolean} True when timeout was cleared, false when none was set (no effect)\n */\n clearNextTick () {\n if (this._tickTimer) {\n clearTimeout(this._tickTimer);\n this._tickTimer = null;\n return true;\n }\n return false;\n }\n\n /**\n * Will call the subclass doTick implementation in this main loop tick\n * or in the next one (via setTimeout(,0)) in case it has already been called\n * in this tick (in case this is a re-entrant call).\n */\n tick () {\n this._tickCallCount++;\n if (this._tickCallCount === 1) {\n this.doTick();\n // re-entrant call to tick from previous doTick call stack\n // -> schedule a call on the next main loop iteration to process this task processing request\n if (this._tickCallCount > 1) {\n // make sure only one timer exists at any time at max\n this.clearNextTick();\n this._tickTimer = setTimeout(this._boundTick, 0);\n }\n this._tickCallCount = 0;\n }\n }\n\n /**\n * For subclass to implement task logic\n * @abstract\n */\n doTick () {}\n}\n","\nexport function sendAddTrackEvent (track, videoEl) {\n let event = null;\n try {\n event = new window.Event('addtrack');\n } catch (err) {\n // for IE11\n event = document.createEvent('Event');\n event.initEvent('addtrack', false, false);\n }\n event.track = track;\n videoEl.dispatchEvent(event);\n}\n\nexport function clearCurrentCues (track) {\n if (track && track.cues) {\n while (track.cues.length > 0) {\n track.removeCue(track.cues[0]);\n }\n }\n}\n","/*\n * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js#L1716\n */\n\nimport VTTCue from './vttcue';\n\nconst StringDecoder = function StringDecoder () {\n return {\n decode: function (data) {\n if (!data) {\n return '';\n }\n\n if (typeof data !== 'string') {\n throw new Error('Error - expected string data.');\n }\n\n return decodeURIComponent(encodeURIComponent(data));\n }\n };\n};\n\nfunction VTTParser () {\n this.window = window;\n this.state = 'INITIAL';\n this.buffer = '';\n this.decoder = new StringDecoder();\n this.regionList = [];\n}\n\n// Try to parse input as a time stamp.\nfunction parseTimeStamp (input) {\n function computeSeconds (h, m, s, f) {\n return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;\n }\n\n let m = input.match(/^(\\d+):(\\d{2})(:\\d{2})?\\.(\\d{3})/);\n if (!m) {\n return null;\n }\n\n if (m[3]) {\n // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]\n return computeSeconds(m[1], m[2], m[3].replace(':', ''), m[4]);\n } else if (m[1] > 59) {\n // Timestamp takes the form of [hours]:[minutes].[milliseconds]\n // First position is hours as it's over 59.\n return computeSeconds(m[1], m[2], 0, m[4]);\n } else {\n // Timestamp takes the form of [minutes]:[seconds].[milliseconds]\n return computeSeconds(0, m[1], m[2], m[4]);\n }\n}\n\n// A settings object holds key/value pairs and will ignore anything but the first\n// assignment to a specific key.\nfunction Settings () {\n this.values = Object.create(null);\n}\n\nSettings.prototype = {\n // Only accept the first assignment to any key.\n set: function (k, v) {\n if (!this.get(k) && v !== '') {\n this.values[k] = v;\n }\n },\n // Return the value for a key, or a default value.\n // If 'defaultKey' is passed then 'dflt' is assumed to be an object with\n // a number of possible default values as properties where 'defaultKey' is\n // the key of the property that will be chosen; otherwise it's assumed to be\n // a single value.\n get: function (k, dflt, defaultKey) {\n if (defaultKey) {\n return this.has(k) ? this.values[k] : dflt[defaultKey];\n }\n\n return this.has(k) ? this.values[k] : dflt;\n },\n // Check whether we have a value for a key.\n has: function (k) {\n return k in this.values;\n },\n // Accept a setting if its one of the given alternatives.\n alt: function (k, v, a) {\n for (let n = 0; n < a.length; ++n) {\n if (v === a[n]) {\n this.set(k, v);\n break;\n }\n }\n },\n // Accept a setting if its a valid (signed) integer.\n integer: function (k, v) {\n if (/^-?\\d+$/.test(v)) { // integer\n this.set(k, parseInt(v, 10));\n }\n },\n // Accept a setting if its a valid percentage.\n percent: function (k, v) {\n let m;\n if ((m = v.match(/^([\\d]{1,3})(\\.[\\d]*)?%$/))) {\n v = parseFloat(v);\n if (v >= 0 && v <= 100) {\n this.set(k, v);\n return true;\n }\n }\n return false;\n }\n};\n\n// Helper function to parse input into groups separated by 'groupDelim', and\n// interprete each group as a key/value pair separated by 'keyValueDelim'.\nfunction parseOptions (input, callback, keyValueDelim, groupDelim) {\n let groups = groupDelim ? input.split(groupDelim) : [input];\n for (let i in groups) {\n if (typeof groups[i] !== 'string') {\n continue;\n }\n\n let kv = groups[i].split(keyValueDelim);\n if (kv.length !== 2) {\n continue;\n }\n\n let k = kv[0];\n let v = kv[1];\n callback(k, v);\n }\n}\n\nlet defaults = new VTTCue(0, 0, 0);\n// 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244\n// Safari doesn't yet support this change, but FF and Chrome do.\nlet center = defaults.align === 'middle' ? 'middle' : 'center';\n\nfunction parseCue (input, cue, regionList) {\n // Remember the original input if we need to throw an error.\n let oInput = input;\n // 4.1 WebVTT timestamp\n function consumeTimeStamp () {\n let ts = parseTimeStamp(input);\n if (ts === null) {\n throw new Error('Malformed timestamp: ' + oInput);\n }\n\n // Remove time stamp from input.\n input = input.replace(/^[^\\sa-zA-Z-]+/, '');\n return ts;\n }\n\n // 4.4.2 WebVTT cue settings\n function consumeCueSettings (input, cue) {\n let settings = new Settings();\n\n parseOptions(input, function (k, v) {\n switch (k) {\n case 'region':\n // Find the last region we parsed with the same region id.\n for (let i = regionList.length - 1; i >= 0; i--) {\n if (regionList[i].id === v) {\n settings.set(k, regionList[i].region);\n break;\n }\n }\n break;\n case 'vertical':\n settings.alt(k, v, ['rl', 'lr']);\n break;\n case 'line':\n var vals = v.split(','),\n vals0 = vals[0];\n settings.integer(k, vals0);\n if (settings.percent(k, vals0)) {\n settings.set('snapToLines', false);\n }\n\n settings.alt(k, vals0, ['auto']);\n if (vals.length === 2) {\n settings.alt('lineAlign', vals[1], ['start', center, 'end']);\n }\n\n break;\n case 'position':\n vals = v.split(',');\n settings.percent(k, vals[0]);\n if (vals.length === 2) {\n settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);\n }\n\n break;\n case 'size':\n settings.percent(k, v);\n break;\n case 'align':\n settings.alt(k, v, ['start', center, 'end', 'left', 'right']);\n break;\n }\n }, /:/, /\\s/);\n\n // Apply default values for any missing fields.\n cue.region = settings.get('region', null);\n cue.vertical = settings.get('vertical', '');\n let line = settings.get('line', 'auto');\n if (line === 'auto' && defaults.line === -1) {\n // set numeric line number for Safari\n line = -1;\n }\n cue.line = line;\n cue.lineAlign = settings.get('lineAlign', 'start');\n cue.snapToLines = settings.get('snapToLines', true);\n cue.size = settings.get('size', 100);\n cue.align = settings.get('align', center);\n let position = settings.get('position', 'auto');\n if (position === 'auto' && defaults.position === 50) {\n // set numeric position for Safari\n position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;\n }\n cue.position = position;\n }\n\n function skipWhitespace () {\n input = input.replace(/^\\s+/, '');\n }\n\n // 4.1 WebVTT cue timings.\n skipWhitespace();\n cue.startTime = consumeTimeStamp(); // (1) collect cue start time\n skipWhitespace();\n if (input.substr(0, 3) !== '-->') { // (3) next characters must match '-->'\n throw new Error('Malformed time stamp (time stamps must be separated by \\'-->\\'): ' +\n oInput);\n }\n input = input.substr(3);\n skipWhitespace();\n cue.endTime = consumeTimeStamp(); // (5) collect cue end time\n\n // 4.1 WebVTT cue settings list.\n skipWhitespace();\n consumeCueSettings(input, cue);\n}\n\nfunction fixLineBreaks (input) {\n return input.replace(/<br(?: \\/)?>/gi, '\\n');\n}\n\nVTTParser.prototype = {\n parse: function (data) {\n let self = this;\n\n // If there is no data then we won't decode it, but will just try to parse\n // whatever is in buffer already. This may occur in circumstances, for\n // example when flush() is called.\n if (data) {\n // Try to decode the data that we received.\n self.buffer += self.decoder.decode(data, { stream: true });\n }\n\n function collectNextLine () {\n let buffer = self.buffer;\n let pos = 0;\n\n buffer = fixLineBreaks(buffer);\n\n while (pos < buffer.length && buffer[pos] !== '\\r' && buffer[pos] !== '\\n') {\n ++pos;\n }\n\n let line = buffer.substr(0, pos);\n // Advance the buffer early in case we fail below.\n if (buffer[pos] === '\\r') {\n ++pos;\n }\n\n if (buffer[pos] === '\\n') {\n ++pos;\n }\n\n self.buffer = buffer.substr(pos);\n return line;\n }\n\n // 3.2 WebVTT metadata header syntax\n function parseHeader (input) {\n parseOptions(input, function (k, v) {\n switch (k) {\n case 'Region':\n // 3.3 WebVTT region metadata header syntax\n // console.log('parse region', v);\n // parseRegion(v);\n break;\n }\n }, /:/);\n }\n\n // 5.1 WebVTT file parsing.\n try {\n let line;\n if (self.state === 'INITIAL') {\n // We can't start parsing until we have the first line.\n if (!/\\r\\n|\\n/.test(self.buffer)) {\n return this;\n }\n\n line = collectNextLine();\n // strip of UTF-8 BOM if any\n // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8\n let m = line.match(/^()?WEBVTT([ \\t].*)?$/);\n if (!m || !m[0]) {\n throw new Error('Malformed WebVTT signature.');\n }\n\n self.state = 'HEADER';\n }\n\n let alreadyCollectedLine = false;\n while (self.buffer) {\n // We can't parse a line until we have the full line.\n if (!/\\r\\n|\\n/.test(self.buffer)) {\n return this;\n }\n\n if (!alreadyCollectedLine) {\n line = collectNextLine();\n } else {\n alreadyCollectedLine = false;\n }\n\n switch (self.state) {\n case 'HEADER':\n // 13-18 - Allow a header (metadata) under the WEBVTT line.\n if (/:/.test(line)) {\n parseHeader(line);\n } else if (!line) {\n // An empty line terminates the header and starts the body (cues).\n self.state = 'ID';\n }\n continue;\n case 'NOTE':\n // Ignore NOTE blocks.\n if (!line) {\n self.state = 'ID';\n }\n\n continue;\n case 'ID':\n // Check for the start of NOTE blocks.\n if (/^NOTE($|[ \\t])/.test(line)) {\n self.state = 'NOTE';\n break;\n }\n // 19-29 - Allow any number of line terminators, then initialize new cue values.\n if (!line) {\n continue;\n }\n\n self.cue = new VTTCue(0, 0, '');\n self.state = 'CUE';\n // 30-39 - Check if self line contains an optional identifier or timing data.\n if (line.indexOf('-->') === -1) {\n self.cue.id = line;\n continue;\n }\n // Process line as start of a cue.\n /* falls through */\n case 'CUE':\n // 40 - Collect cue timings and settings.\n try {\n parseCue(line, self.cue, self.regionList);\n } catch (e) {\n // In case of an error ignore rest of the cue.\n self.cue = null;\n self.state = 'BADCUE';\n continue;\n }\n self.state = 'CUETEXT';\n continue;\n case 'CUETEXT':\n var hasSubstring = line.indexOf('-->') !== -1;\n // 34 - If we have an empty line then report the cue.\n // 35 - If we have the special substring '-->' then report the cue,\n // but do not collect the line as we need to process the current\n // one as a new cue.\n if (!line || hasSubstring && (alreadyCollectedLine = true)) {\n // We are done parsing self cue.\n if (self.oncue) {\n self.oncue(self.cue);\n }\n\n self.cue = null;\n self.state = 'ID';\n continue;\n }\n if (self.cue.text) {\n self.cue.text += '\\n';\n }\n\n self.cue.text += line;\n continue;\n case 'BADCUE': // BADCUE\n // 54-62 - Collect and discard the remaining cue.\n if (!line) {\n self.state = 'ID';\n }\n\n continue;\n }\n }\n } catch (e) {\n // If we are currently parsing a cue, report what we have.\n if (self.state === 'CUETEXT' && self.cue && self.oncue) {\n self.oncue(self.cue);\n }\n\n self.cue = null;\n // Enter BADWEBVTT state if header was not parsed correctly otherwise\n // another exception occurred so enter BADCUE state.\n self.state = self.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';\n }\n return this;\n },\n flush: function () {\n let self = this;\n try {\n // Finish decoding the stream.\n self.buffer += self.decoder.decode();\n // Synthesize the end of the current cue or region.\n if (self.cue || self.state === 'HEADER') {\n self.buffer += '\\n\\n';\n self.parse();\n }\n // If we've flushed, parsed, and we're still on the INITIAL state then\n // that means we don't have enough of the stream to parse the first\n // line.\n if (self.state === 'INITIAL') {\n throw new Error('Malformed WebVTT signature.');\n }\n } catch (e) {\n throw e;\n }\n if (self.onflush) {\n self.onflush();\n }\n\n return this;\n }\n};\n\nexport { fixLineBreaks };\n\nexport default VTTParser;\n","import * as URLToolkit from 'url-toolkit';\n\nimport {\n ErrorTypes,\n ErrorDetails\n} from './errors';\n\nimport PlaylistLoader from './loader/playlist-loader';\nimport FragmentLoader from './loader/fragment-loader';\nimport KeyLoader from './loader/key-loader';\n\nimport { FragmentTracker } from './controller/fragment-tracker';\nimport StreamController from './controller/stream-controller';\nimport LevelController from './controller/level-controller';\nimport ID3TrackController from './controller/id3-track-controller';\n\nimport { isSupported } from './is-supported';\nimport { logger, enableLogs } from './utils/logger';\nimport { hlsDefaultConfig } from './config';\n\nimport HlsEvents from './events';\n\nimport { Observer } from './observer';\n\n/**\n * @module Hls\n * @class\n * @constructor\n */\nexport default class Hls extends Observer {\n /**\n * @type {string}\n */\n static get version () {\n return __VERSION__;\n }\n\n /**\n * @type {boolean}\n */\n static isSupported () {\n return isSupported();\n }\n\n /**\n * @type {HlsEvents}\n */\n static get Events () {\n return HlsEvents;\n }\n\n /**\n * @type {HlsErrorTypes}\n */\n static get ErrorTypes () {\n return ErrorTypes;\n }\n\n /**\n * @type {HlsErrorDetails}\n */\n static get ErrorDetails () {\n return ErrorDetails;\n }\n\n /**\n * @type {HlsConfig}\n */\n static get DefaultConfig () {\n if (!Hls.defaultConfig) {\n return hlsDefaultConfig;\n }\n\n return Hls.defaultConfig;\n }\n\n /**\n * @type {HlsConfig}\n */\n static set DefaultConfig (defaultConfig) {\n Hls.defaultConfig = defaultConfig;\n }\n\n /**\n * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.\n *\n * @constructs Hls\n * @param {HlsConfig} config\n */\n constructor (config = {}) {\n super();\n\n const defaultConfig = Hls.DefaultConfig;\n\n if ((config.liveSyncDurationCount || config.liveMaxLatencyDurationCount) && (config.liveSyncDuration || config.liveMaxLatencyDuration)) {\n throw new Error('Illegal hls.js config: don\\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');\n }\n\n for (let prop in defaultConfig) {\n if (prop in config) continue;\n config[prop] = defaultConfig[prop];\n }\n\n if (config.liveMaxLatencyDurationCount !== undefined && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {\n throw new Error('Illegal hls.js config: \"liveMaxLatencyDurationCount\" must be gt \"liveSyncDurationCount\"');\n }\n\n if (config.liveMaxLatencyDuration !== undefined && (config.liveMaxLatencyDuration <= config.liveSyncDuration || config.liveSyncDuration === undefined)) {\n throw new Error('Illegal hls.js config: \"liveMaxLatencyDuration\" must be gt \"liveSyncDuration\"');\n }\n\n enableLogs(config.debug);\n this.config = config;\n this._autoLevelCapping = -1;\n\n // core controllers and network loaders\n\n /**\n * @member {AbrController} abrController\n */\n const abrController = this.abrController = new config.abrController(this);\n\n const bufferController = new config.bufferController(this);\n const capLevelController = new config.capLevelController(this);\n const fpsController = new config.fpsController(this);\n const playListLoader = new PlaylistLoader(this);\n const fragmentLoader = new FragmentLoader(this);\n const keyLoader = new KeyLoader(this);\n const id3TrackController = new ID3TrackController(this);\n\n // network controllers\n\n /**\n * @member {LevelController} levelController\n */\n const levelController = this.levelController = new LevelController(this);\n\n // FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important\n const fragmentTracker = new FragmentTracker(this);\n\n /**\n * @member {StreamController} streamController\n */\n const streamController = this.streamController = new StreamController(this, fragmentTracker);\n\n let networkControllers = [levelController, streamController];\n\n // optional audio stream controller\n /**\n * @var {ICoreComponent | Controller}\n */\n let Controller = config.audioStreamController;\n if (Controller) {\n networkControllers.push(new Controller(this, fragmentTracker));\n }\n\n /**\n * @member {INetworkController[]} networkControllers\n */\n this.networkControllers = networkControllers;\n\n /**\n * @var {ICoreComponent[]}\n */\n const coreComponents = [\n playListLoader,\n fragmentLoader,\n keyLoader,\n abrController,\n bufferController,\n capLevelController,\n fpsController,\n id3TrackController,\n fragmentTracker\n ];\n\n // optional audio track and subtitle controller\n Controller = config.audioTrackController;\n if (Controller) {\n const audioTrackController = new Controller(this);\n\n /**\n * @member {AudioTrackController} audioTrackController\n */\n this.audioTrackController = audioTrackController;\n coreComponents.push(audioTrackController);\n }\n\n Controller = config.subtitleTrackController;\n if (Controller) {\n const subtitleTrackController = new Controller(this);\n\n /**\n * @member {SubtitleTrackController} subtitleTrackController\n */\n this.subtitleTrackController = subtitleTrackController;\n networkControllers.push(subtitleTrackController);\n }\n\n Controller = config.emeController;\n if (Controller) {\n const emeController = new Controller(this);\n\n /**\n * @member {EMEController} emeController\n */\n this.emeController = emeController;\n coreComponents.push(emeController);\n }\n\n // optional subtitle controllers\n Controller = config.subtitleStreamController;\n if (Controller) {\n networkControllers.push(new Controller(this, fragmentTracker));\n }\n Controller = config.timelineController;\n if (Controller) {\n coreComponents.push(new Controller(this));\n }\n\n /**\n * @member {ICoreComponent[]}\n */\n this.coreComponents = coreComponents;\n }\n\n /**\n * Dispose of the instance\n */\n destroy () {\n logger.log('destroy');\n this.trigger(HlsEvents.DESTROYING);\n this.detachMedia();\n this.coreComponents.concat(this.networkControllers).forEach(component => {\n component.destroy();\n });\n this.url = null;\n this.removeAllListeners();\n this._autoLevelCapping = -1;\n }\n\n /**\n * Attach a media element\n * @param {HTMLMediaElement} media\n */\n attachMedia (media) {\n logger.log('attachMedia');\n this.media = media;\n this.trigger(HlsEvents.MEDIA_ATTACHING, { media: media });\n }\n\n /**\n * Detach from the media\n */\n detachMedia () {\n logger.log('detachMedia');\n this.trigger(HlsEvents.MEDIA_DETACHING);\n this.media = null;\n }\n\n /**\n * Set the source URL. Can be relative or absolute.\n * @param {string} url\n */\n loadSource (url) {\n url = URLToolkit.buildAbsoluteURL(window.location.href, url, { alwaysNormalize: true });\n logger.log(`loadSource:${url}`);\n this.url = url;\n // when attaching to a source URL, trigger a playlist load\n this.trigger(HlsEvents.MANIFEST_LOADING, { url: url });\n }\n\n /**\n * Start loading data from the stream source.\n * Depending on default config, client starts loading automatically when a source is set.\n *\n * @param {number} startPosition Set the start position to stream from\n * @default -1 None (from earliest point)\n */\n startLoad (startPosition = -1) {\n logger.log(`startLoad(${startPosition})`);\n this.networkControllers.forEach(controller => {\n controller.startLoad(startPosition);\n });\n }\n\n /**\n * Stop loading of any stream data.\n */\n stopLoad () {\n logger.log('stopLoad');\n this.networkControllers.forEach(controller => {\n controller.stopLoad();\n });\n }\n\n /**\n * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)\n */\n swapAudioCodec () {\n logger.log('swapAudioCodec');\n this.streamController.swapAudioCodec();\n }\n\n /**\n * When the media-element fails, this allows to detach and then re-attach it\n * as one call (convenience method).\n *\n * Automatic recovery of media-errors by this process is configurable.\n */\n recoverMediaError () {\n logger.log('recoverMediaError');\n let media = this.media;\n this.detachMedia();\n this.attachMedia(media);\n }\n\n /**\n * @type {QualityLevel[]}\n */\n get levels () {\n return this.levelController.levels;\n }\n\n /**\n * Index of quality level currently played\n * @type {number}\n */\n get currentLevel () {\n return this.streamController.currentLevel;\n }\n\n /**\n * Set quality level index immediately .\n * This will flush the current buffer to replace the quality asap.\n * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.\n * @type {number} -1 for automatic level selection\n */\n set currentLevel (newLevel) {\n logger.log(`set currentLevel:${newLevel}`);\n this.loadLevel = newLevel;\n this.streamController.immediateLevelSwitch();\n }\n\n /**\n * Index of next quality level loaded as scheduled by stream controller.\n * @type {number}\n */\n get nextLevel () {\n return this.streamController.nextLevel;\n }\n\n /**\n * Set quality level index for next loaded data.\n * This will switch the video quality asap, without interrupting playback.\n * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).\n * @type {number} -1 for automatic level selection\n */\n set nextLevel (newLevel) {\n logger.log(`set nextLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n this.streamController.nextLevelSwitch();\n }\n\n /**\n * Return the quality level of the currently or last (of none is loaded currently) segment\n * @type {number}\n */\n get loadLevel () {\n return this.levelController.level;\n }\n\n /**\n * Set quality level index for next loaded data in a conservative way.\n * This will switch the quality without flushing, but interrupt current loading.\n * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.\n * @type {number} newLevel -1 for automatic level selection\n */\n set loadLevel (newLevel) {\n logger.log(`set loadLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n }\n\n /**\n * get next quality level loaded\n * @type {number}\n */\n get nextLoadLevel () {\n return this.levelController.nextLoadLevel;\n }\n\n /**\n * Set quality level of next loaded segment in a fully \"non-destructive\" way.\n * Same as `loadLevel` but will wait for next switch (until current loading is done).\n * @type {number} level\n */\n set nextLoadLevel (level) {\n this.levelController.nextLoadLevel = level;\n }\n\n /**\n * Return \"first level\": like a default level, if not set,\n * falls back to index of first level referenced in manifest\n * @type {number}\n */\n get firstLevel () {\n return Math.max(this.levelController.firstLevel, this.minAutoLevel);\n }\n\n /**\n * Sets \"first-level\", see getter.\n * @type {number}\n */\n set firstLevel (newLevel) {\n logger.log(`set firstLevel:${newLevel}`);\n this.levelController.firstLevel = newLevel;\n }\n\n /**\n * Return start level (level of first fragment that will be played back)\n * if not overrided by user, first level appearing in manifest will be used as start level\n * if -1 : automatic start level selection, playback will start from level matching download bandwidth\n * (determined from download of first segment)\n * @type {number}\n */\n get startLevel () {\n return this.levelController.startLevel;\n }\n\n /**\n * set start level (level of first fragment that will be played back)\n * if not overrided by user, first level appearing in manifest will be used as start level\n * if -1 : automatic start level selection, playback will start from level matching download bandwidth\n * (determined from download of first segment)\n * @type {number} newLevel\n */\n set startLevel (newLevel) {\n logger.log(`set startLevel:${newLevel}`);\n const hls = this;\n // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel\n if (newLevel !== -1) {\n newLevel = Math.max(newLevel, hls.minAutoLevel);\n }\n\n hls.levelController.startLevel = newLevel;\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n * @type {number}\n */\n get autoLevelCapping () {\n return this._autoLevelCapping;\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n * @type {number}\n */\n set autoLevelCapping (newLevel) {\n logger.log(`set autoLevelCapping:${newLevel}`);\n this._autoLevelCapping = newLevel;\n }\n\n /**\n * True when automatic level selection enabled\n * @type {boolean}\n */\n get autoLevelEnabled () {\n return (this.levelController.manualLevel === -1);\n }\n\n /**\n * Level set manually (if any)\n * @type {number}\n */\n get manualLevel () {\n return this.levelController.manualLevel;\n }\n\n /**\n * min level selectable in auto mode according to config.minAutoBitrate\n * @type {number}\n */\n get minAutoLevel () {\n let hls = this, levels = hls.levels, minAutoBitrate = hls.config.minAutoBitrate, len = levels ? levels.length : 0;\n for (let i = 0; i < len; i++) {\n const levelNextBitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate;\n if (levelNextBitrate > minAutoBitrate) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n * max level selectable in auto mode according to autoLevelCapping\n * @type {number}\n */\n get maxAutoLevel () {\n const hls = this;\n const levels = hls.levels;\n const autoLevelCapping = hls.autoLevelCapping;\n let maxAutoLevel;\n if (autoLevelCapping === -1 && levels && levels.length) {\n maxAutoLevel = levels.length - 1;\n } else {\n maxAutoLevel = autoLevelCapping;\n }\n\n return maxAutoLevel;\n }\n\n /**\n * next automatically selected quality level\n * @type {number}\n */\n get nextAutoLevel () {\n const hls = this;\n // ensure next auto level is between min and max auto level\n return Math.min(Math.max(hls.abrController.nextAutoLevel, hls.minAutoLevel), hls.maxAutoLevel);\n }\n\n /**\n * this setter is used to force next auto level.\n * this is useful to force a switch down in auto mode:\n * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)\n * forced value is valid for one fragment. upon succesful frag loading at forced level,\n * this value will be resetted to -1 by ABR controller.\n * @type {number}\n */\n set nextAutoLevel (nextLevel) {\n const hls = this;\n hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel, nextLevel);\n }\n\n /**\n * @type {AudioTrack[]}\n */\n get audioTracks () {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTracks : [];\n }\n\n /**\n * index of the selected audio track (index in audio track lists)\n * @type {number}\n */\n get audioTrack () {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTrack : -1;\n }\n\n /**\n * selects an audio track, based on its index in audio track lists\n * @type {number}\n */\n set audioTrack (audioTrackId) {\n const audioTrackController = this.audioTrackController;\n if (audioTrackController) {\n audioTrackController.audioTrack = audioTrackId;\n }\n }\n\n /**\n * @type {Seconds}\n */\n get liveSyncPosition () {\n return this.streamController.liveSyncPosition;\n }\n\n /**\n * get alternate subtitle tracks list from playlist\n * @type {SubtitleTrack[]}\n */\n get subtitleTracks () {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];\n }\n\n /**\n * index of the selected subtitle track (index in subtitle track lists)\n * @type {number}\n */\n get subtitleTrack () {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;\n }\n\n /**\n * select an subtitle track, based on its index in subtitle track lists\n * @type{number}\n */\n set subtitleTrack (subtitleTrackId) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleTrack = subtitleTrackId;\n }\n }\n\n /**\n * @type {boolean}\n */\n get subtitleDisplay () {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;\n }\n\n /**\n * Enable/disable subtitle display rendering\n * @type {boolean}\n */\n set subtitleDisplay (value) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleDisplay = value;\n }\n }\n}\n","import * as URLToolkit from 'url-toolkit';\n\nimport Fragment from './fragment';\nimport Level from './level';\nimport LevelKey from './level-key';\n\nimport AttrList from '../utils/attr-list';\nimport { logger } from '../utils/logger';\nimport { isCodecType } from '../utils/codecs';\n\n/**\n * M3U8 parser\n * @module\n */\n\n// https://regex101.com is your friend\nconst MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\\n\\r]*)[\\r\\n]+([^\\r\\n]+)/g;\nconst MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;\n\nconst LEVEL_PLAYLIST_REGEX_FAST = new RegExp([\n /#EXTINF:\\s*(\\d*(?:\\.\\d+)?)(?:,(.*)\\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title\n /|(?!#)([\\S+ ?]+)/.source, // segment URI, group 3 => the URI (note newline is not eaten)\n /|#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)\n /|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec\n /|#.*/.source // All other non-segment oriented tags will match with all groups empty\n].join(''), 'g');\n\nconst LEVEL_PLAYLIST_REGEX_SLOW = /(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\\d+))|(?:#EXT-X-(TARGETDURATION): *(\\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)([^:]*):(.*))|(?:(#)(.*))(?:.*)\\r?\\n?/;\n\nconst MP4_REGEX_SUFFIX = /\\.(mp4|m4s|m4v|m4a)$/i;\n\nexport default class M3U8Parser {\n static findGroup (groups, mediaGroupId) {\n if (!groups) {\n return null;\n }\n\n let matchingGroup = null;\n\n for (let i = 0; i < groups.length; i++) {\n const group = groups[i];\n if (group.id === mediaGroupId) {\n matchingGroup = group;\n }\n }\n\n return matchingGroup;\n }\n\n static convertAVC1ToAVCOTI (codec) {\n let result, avcdata = codec.split('.');\n if (avcdata.length > 2) {\n result = avcdata.shift() + '.';\n result += parseInt(avcdata.shift()).toString(16);\n result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);\n } else {\n result = codec;\n }\n return result;\n }\n\n static resolve (url, baseUrl) {\n return URLToolkit.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });\n }\n\n static parseMasterPlaylist (string, baseurl) {\n let levels = [], result;\n MASTER_PLAYLIST_REGEX.lastIndex = 0;\n\n function setCodecs (codecs, level) {\n ['video', 'audio'].forEach((type) => {\n const filtered = codecs.filter((codec) => isCodecType(codec, type));\n if (filtered.length) {\n const preferred = filtered.filter((codec) => {\n return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0;\n });\n level[`${type}Codec`] = preferred.length > 0 ? preferred[0] : filtered[0];\n\n // remove from list\n codecs = codecs.filter((codec) => filtered.indexOf(codec) === -1);\n }\n });\n\n level.unknownCodecs = codecs;\n }\n\n while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {\n const level = {};\n\n const attrs = level.attrs = new AttrList(result[1]);\n level.url = M3U8Parser.resolve(result[2], baseurl);\n\n const resolution = attrs.decimalResolution('RESOLUTION');\n if (resolution) {\n level.width = resolution.width;\n level.height = resolution.height;\n }\n level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');\n level.name = attrs.NAME;\n\n setCodecs([].concat((attrs.CODECS || '').split(/[ ,]+/)), level);\n\n if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {\n level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);\n }\n\n levels.push(level);\n }\n return levels;\n }\n\n static parseMasterPlaylistMedia (string, baseurl, type, audioGroups = []) {\n let result;\n let medias = [];\n let id = 0;\n MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;\n while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {\n const media = {};\n const attrs = new AttrList(result[1]);\n if (attrs.TYPE === type) {\n media.groupId = attrs['GROUP-ID'];\n media.name = attrs.NAME;\n media.type = type;\n media.default = (attrs.DEFAULT === 'YES');\n media.autoselect = (attrs.AUTOSELECT === 'YES');\n media.forced = (attrs.FORCED === 'YES');\n if (attrs.URI) {\n media.url = M3U8Parser.resolve(attrs.URI, baseurl);\n }\n\n media.lang = attrs.LANGUAGE;\n if (!media.name) {\n media.name = media.lang;\n }\n\n if (audioGroups.length) {\n const groupCodec = M3U8Parser.findGroup(audioGroups, media.groupId);\n media.audioCodec = groupCodec ? groupCodec.codec : audioGroups[0].codec;\n }\n media.id = id++;\n medias.push(media);\n }\n }\n return medias;\n }\n\n static parseLevelPlaylist (string, baseurl, id, type, levelUrlId) {\n let currentSN = 0;\n let totalduration = 0;\n let level = new Level(baseurl);\n let levelkey = new LevelKey();\n let cc = 0;\n let prevFrag = null;\n let frag = new Fragment();\n let result;\n let i;\n\n let firstPdtIndex = null;\n\n LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;\n\n while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {\n const duration = result[1];\n if (duration) { // INF\n frag.duration = parseFloat(duration);\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const title = (' ' + result[2]).slice(1);\n frag.title = title || null;\n frag.tagList.push(title ? [ 'INF', duration, title ] : [ 'INF', duration ]);\n } else if (result[3]) { // url\n if (Number.isFinite(frag.duration)) {\n const sn = currentSN++;\n frag.type = type;\n frag.start = totalduration;\n frag.levelkey = levelkey;\n frag.sn = sn;\n frag.level = id;\n frag.cc = cc;\n frag.urlId = levelUrlId;\n frag.baseurl = baseurl;\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n frag.relurl = (' ' + result[3]).slice(1);\n assignProgramDateTime(frag, prevFrag);\n\n level.fragments.push(frag);\n prevFrag = frag;\n totalduration += frag.duration;\n\n frag = new Fragment();\n }\n } else if (result[4]) { // X-BYTERANGE\n frag.rawByteRange = (' ' + result[4]).slice(1);\n if (prevFrag) {\n const lastByteRangeEndOffset = prevFrag.byteRangeEndOffset;\n if (lastByteRangeEndOffset) {\n frag.lastByteRangeEndOffset = lastByteRangeEndOffset;\n }\n }\n } else if (result[5]) { // PROGRAM-DATE-TIME\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n frag.rawProgramDateTime = (' ' + result[5]).slice(1);\n frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);\n if (firstPdtIndex === null) {\n firstPdtIndex = level.fragments.length;\n }\n } else {\n result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);\n for (i = 1; i < result.length; i++) {\n if (result[i] !== undefined) {\n break;\n }\n }\n\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const value1 = (' ' + result[i + 1]).slice(1);\n const value2 = (' ' + result[i + 2]).slice(1);\n\n switch (result[i]) {\n case '#':\n frag.tagList.push(value2 ? [ value1, value2 ] : [ value1 ]);\n break;\n case 'PLAYLIST-TYPE':\n level.type = value1.toUpperCase();\n break;\n case 'MEDIA-SEQUENCE':\n currentSN = level.startSN = parseInt(value1);\n break;\n case 'TARGETDURATION':\n level.targetduration = parseFloat(value1);\n break;\n case 'VERSION':\n level.version = parseInt(value1);\n break;\n case 'EXTM3U':\n break;\n case 'ENDLIST':\n level.live = false;\n break;\n case 'DIS':\n cc++;\n frag.tagList.push(['DIS']);\n break;\n case 'DISCONTINUITY-SEQ':\n cc = parseInt(value1);\n break;\n case 'KEY':\n // https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4\n var decryptparams = value1;\n var keyAttrs = new AttrList(decryptparams);\n var decryptmethod = keyAttrs.enumeratedString('METHOD'),\n decrypturi = keyAttrs.URI,\n decryptiv = keyAttrs.hexadecimalInteger('IV');\n if (decryptmethod) {\n levelkey = new LevelKey();\n if ((decrypturi) && (['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0)) {\n levelkey.method = decryptmethod;\n // URI to get the key\n levelkey.baseuri = baseurl;\n levelkey.reluri = decrypturi;\n levelkey.key = null;\n // Initialization Vector (IV)\n levelkey.iv = decryptiv;\n }\n }\n break;\n case 'START':\n let startParams = value1;\n let startAttrs = new AttrList(startParams);\n let startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');\n // TIME-OFFSET can be 0\n if (Number.isFinite(startTimeOffset)) {\n level.startTimeOffset = startTimeOffset;\n }\n\n break;\n case 'MAP':\n let mapAttrs = new AttrList(value1);\n frag.relurl = mapAttrs.URI;\n frag.rawByteRange = mapAttrs.BYTERANGE;\n frag.baseurl = baseurl;\n frag.level = id;\n frag.type = type;\n frag.sn = 'initSegment';\n level.initSegment = frag;\n frag = new Fragment();\n frag.rawProgramDateTime = level.initSegment.rawProgramDateTime;\n break;\n default:\n logger.warn(`line parsed but not handled: ${result}`);\n break;\n }\n }\n }\n frag = prevFrag;\n // logger.log('found ' + level.fragments.length + ' fragments');\n if (frag && !frag.relurl) {\n level.fragments.pop();\n totalduration -= frag.duration;\n }\n level.totalduration = totalduration;\n level.averagetargetduration = totalduration / level.fragments.length;\n level.endSN = currentSN - 1;\n level.startCC = level.fragments[0] ? level.fragments[0].cc : 0;\n level.endCC = cc;\n\n if (!level.initSegment && level.fragments.length) {\n // this is a bit lurky but HLS really has no other way to tell us\n // if the fragments are TS or MP4, except if we download them :/\n // but this is to be able to handle SIDX.\n if (level.fragments.every((frag) => MP4_REGEX_SUFFIX.test(frag.relurl))) {\n logger.warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');\n\n frag = new Fragment();\n frag.relurl = level.fragments[0].relurl;\n frag.baseurl = baseurl;\n frag.level = id;\n frag.type = type;\n frag.sn = 'initSegment';\n\n level.initSegment = frag;\n level.needSidxRanges = true;\n }\n }\n\n /**\n * Backfill any missing PDT values\n \"If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after\n one or more Media Segment URIs, the client SHOULD extrapolate\n backward from that tag (using EXTINF durations and/or media\n timestamps) to associate dates with those segments.\"\n * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs\n * computed.\n */\n if (firstPdtIndex) {\n backfillProgramDateTimes(level.fragments, firstPdtIndex);\n }\n\n return level;\n }\n}\n\nfunction backfillProgramDateTimes (fragments, startIndex) {\n let fragPrev = fragments[startIndex];\n for (let i = startIndex - 1; i >= 0; i--) {\n const frag = fragments[i];\n frag.programDateTime = fragPrev.programDateTime - (frag.duration * 1000);\n fragPrev = frag;\n }\n}\n\nfunction assignProgramDateTime (frag, prevFrag) {\n if (frag.rawProgramDateTime) {\n frag.programDateTime = Date.parse(frag.rawProgramDateTime);\n } else if (prevFrag && prevFrag.programDateTime) {\n frag.programDateTime = prevFrag.endProgramDateTime;\n }\n\n if (!Number.isFinite(frag.programDateTime)) {\n frag.programDateTime = null;\n frag.rawProgramDateTime = null;\n }\n}\n","export default class Level {\n constructor (baseUrl) {\n // Please keep properties in alphabetical order\n this.endCC = 0;\n this.endSN = 0;\n this.fragments = [];\n this.initSegment = null;\n this.live = true;\n this.needSidxRanges = false;\n this.startCC = 0;\n this.startSN = 0;\n this.startTimeOffset = null;\n this.targetduration = 0;\n this.totalduration = 0;\n this.type = null;\n this.url = baseUrl;\n this.version = null;\n }\n\n get hasProgramDateTime () {\n return !!(this.fragments[0] && Number.isFinite(this.fragments[0].programDateTime));\n }\n}\n","const DECIMAL_RESOLUTION_REGEX = /^(\\d+)x(\\d+)$/; // eslint-disable-line no-useless-escape\nconst ATTR_LIST_REGEX = /\\s*(.+?)\\s*=((?:\\\".*?\\\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape\n\n// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js\nclass AttrList {\n constructor (attrs) {\n if (typeof attrs === 'string') {\n attrs = AttrList.parseAttrList(attrs);\n }\n\n for (let attr in attrs) {\n if (attrs.hasOwnProperty(attr)) {\n this[attr] = attrs[attr];\n }\n }\n }\n\n decimalInteger (attrName) {\n const intValue = parseInt(this[attrName], 10);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n\n return intValue;\n }\n\n hexadecimalInteger (attrName) {\n if (this[attrName]) {\n let stringValue = (this[attrName] || '0x').slice(2);\n stringValue = ((stringValue.length & 1) ? '0' : '') + stringValue;\n\n const value = new Uint8Array(stringValue.length / 2);\n for (let i = 0; i < stringValue.length / 2; i++) {\n value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);\n }\n\n return value;\n } else {\n return null;\n }\n }\n\n hexadecimalIntegerAsNumber (attrName) {\n const intValue = parseInt(this[attrName], 16);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n\n return intValue;\n }\n\n decimalFloatingPoint (attrName) {\n return parseFloat(this[attrName]);\n }\n\n enumeratedString (attrName) {\n return this[attrName];\n }\n\n decimalResolution (attrName) {\n const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);\n if (res === null) {\n return undefined;\n }\n\n return {\n width: parseInt(res[1], 10),\n height: parseInt(res[2], 10)\n };\n }\n\n static parseAttrList (input) {\n let match, attrs = {};\n ATTR_LIST_REGEX.lastIndex = 0;\n while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {\n let value = match[2], quote = '\"';\n\n if (value.indexOf(quote) === 0 &&\n value.lastIndexOf(quote) === (value.length - 1)) {\n value = value.slice(1, -1);\n }\n\n attrs[match[1]] = value;\n }\n return attrs;\n }\n}\n\nexport default AttrList;\n","/*\n * Fragment Loader\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\n\nclass FragmentLoader extends EventHandler {\n constructor (hls) {\n super(hls, Event.FRAG_LOADING);\n this.loaders = {};\n }\n\n destroy () {\n let loaders = this.loaders;\n for (let loaderName in loaders) {\n let loader = loaders[loaderName];\n if (loader) {\n loader.destroy();\n }\n }\n this.loaders = {};\n\n super.destroy();\n }\n\n onFragLoading (data) {\n const frag = data.frag,\n type = frag.type,\n loaders = this.loaders,\n config = this.hls.config,\n FragmentILoader = config.fLoader,\n DefaultILoader = config.loader;\n\n // reset fragment state\n frag.loaded = 0;\n\n let loader = loaders[type];\n if (loader) {\n logger.warn(`abort previous fragment loader for type: ${type}`);\n loader.abort();\n }\n\n loader = loaders[type] = frag.loader =\n config.fLoader ? new FragmentILoader(config) : new DefaultILoader(config);\n\n let loaderContext, loaderConfig, loaderCallbacks;\n\n loaderContext = { url: frag.url, frag: frag, responseType: 'arraybuffer', progressData: false };\n\n let start = frag.byteRangeStartOffset,\n end = frag.byteRangeEndOffset;\n\n if (Number.isFinite(start) && Number.isFinite(end)) {\n loaderContext.rangeStart = start;\n loaderContext.rangeEnd = end;\n }\n\n loaderConfig = {\n timeout: config.fragLoadingTimeOut,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: config.fragLoadingMaxRetryTimeout\n };\n\n loaderCallbacks = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this),\n onProgress: this.loadprogress.bind(this)\n };\n\n loader.load(loaderContext, loaderConfig, loaderCallbacks);\n }\n\n loadsuccess (response, stats, context, networkDetails = null) {\n let payload = response.data, frag = context.frag;\n // detach fragment loader on load success\n frag.loader = undefined;\n this.loaders[frag.type] = undefined;\n this.hls.trigger(Event.FRAG_LOADED, { payload: payload, frag: frag, stats: stats, networkDetails: networkDetails });\n }\n\n loaderror (response, context, networkDetails = null) {\n const frag = context.frag;\n let loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n\n this.loaders[frag.type] = undefined;\n this.hls.trigger(Event.ERROR, { type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.FRAG_LOAD_ERROR, fatal: false, frag: context.frag, response: response, networkDetails: networkDetails });\n }\n\n loadtimeout (stats, context, networkDetails = null) {\n const frag = context.frag;\n let loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n\n this.loaders[frag.type] = undefined;\n this.hls.trigger(Event.ERROR, { type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.FRAG_LOAD_TIMEOUT, fatal: false, frag: context.frag, networkDetails: networkDetails });\n }\n\n // data will be used for progressive parsing\n loadprogress (stats, context, data, networkDetails = null) { // jshint ignore:line\n let frag = context.frag;\n frag.loaded = stats.loaded;\n this.hls.trigger(Event.FRAG_LOAD_PROGRESS, { frag: frag, stats: stats, networkDetails: networkDetails });\n }\n}\n\nexport default FragmentLoader;\n","/*\n * Decrypt key Loader\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\n\nclass KeyLoader extends EventHandler {\n constructor (hls) {\n super(hls, Event.KEY_LOADING);\n this.loaders = {};\n this.decryptkey = null;\n this.decrypturl = null;\n }\n\n destroy () {\n for (let loaderName in this.loaders) {\n let loader = this.loaders[loaderName];\n if (loader) {\n loader.destroy();\n }\n }\n this.loaders = {};\n EventHandler.prototype.destroy.call(this);\n }\n\n onKeyLoading (data) {\n let frag = data.frag,\n type = frag.type,\n loader = this.loaders[type],\n decryptdata = frag.decryptdata,\n uri = decryptdata.uri;\n // if uri is different from previous one or if decrypt key not retrieved yet\n if (uri !== this.decrypturl || this.decryptkey === null) {\n let config = this.hls.config;\n\n if (loader) {\n logger.warn(`abort previous key loader for type:${type}`);\n loader.abort();\n }\n frag.loader = this.loaders[type] = new config.loader(config);\n this.decrypturl = uri;\n this.decryptkey = null;\n\n let loaderContext, loaderConfig, loaderCallbacks;\n loaderContext = { url: uri, frag: frag, responseType: 'arraybuffer' };\n // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,\n // key-loader will trigger an error and rely on stream-controller to handle retry logic.\n // this will also align retry logic with fragment-loader\n loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: 0, retryDelay: config.fragLoadingRetryDelay, maxRetryDelay: config.fragLoadingMaxRetryTimeout };\n loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this) };\n frag.loader.load(loaderContext, loaderConfig, loaderCallbacks);\n } else if (this.decryptkey) {\n // we already loaded this key, return it\n decryptdata.key = this.decryptkey;\n this.hls.trigger(Event.KEY_LOADED, { frag: frag });\n }\n }\n\n loadsuccess (response, stats, context) {\n let frag = context.frag;\n this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data);\n // detach fragment loader on load success\n frag.loader = undefined;\n this.loaders[frag.type] = undefined;\n this.hls.trigger(Event.KEY_LOADED, { frag: frag });\n }\n\n loaderror (response, context) {\n let frag = context.frag,\n loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n\n this.loaders[context.type] = undefined;\n this.hls.trigger(Event.ERROR, { type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag: frag, response: response });\n }\n\n loadtimeout (stats, context) {\n let frag = context.frag,\n loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n\n this.loaders[context.type] = undefined;\n this.hls.trigger(Event.ERROR, { type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.KEY_LOAD_TIMEOUT, fatal: false, frag: frag });\n }\n}\n\nexport default KeyLoader;\n","/*\n * Stream Controller\n*/\n\nimport BinarySearch from '../utils/binary-search';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport Demuxer from '../demux/demuxer';\nimport Event from '../events';\nimport { FragmentState } from './fragment-tracker';\nimport Fragment from '../loader/fragment';\nimport PlaylistLoader from '../loader/playlist-loader';\nimport * as LevelHelper from './level-helper';\nimport TimeRanges from '../utils/time-ranges';\nimport { ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport { alignStream } from '../utils/discontinuities';\nimport { findFragmentByPDT, findFragmentByPTS } from './fragment-finders';\nimport GapController from './gap-controller';\nimport BaseStreamController, { State } from './base-stream-controller';\n\nconst TICK_INTERVAL = 100; // how often to tick in ms\n\nclass StreamController extends BaseStreamController {\n constructor (hls, fragmentTracker) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.MANIFEST_LOADING,\n Event.MANIFEST_PARSED,\n Event.LEVEL_LOADED,\n Event.KEY_LOADED,\n Event.FRAG_LOADED,\n Event.FRAG_LOAD_EMERGENCY_ABORTED,\n Event.FRAG_PARSING_INIT_SEGMENT,\n Event.FRAG_PARSING_DATA,\n Event.FRAG_PARSED,\n Event.ERROR,\n Event.AUDIO_TRACK_SWITCHING,\n Event.AUDIO_TRACK_SWITCHED,\n Event.BUFFER_CREATED,\n Event.BUFFER_APPENDED,\n Event.BUFFER_FLUSHED);\n\n this.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.audioCodecSwap = false;\n this._state = State.STOPPED;\n this.stallReported = false;\n this.gapController = null;\n }\n\n startLoad (startPosition) {\n if (this.levels) {\n let lastCurrentTime = this.lastCurrentTime, hls = this.hls;\n this.stopLoad();\n this.setInterval(TICK_INTERVAL);\n this.level = -1;\n this.fragLoadError = 0;\n if (!this.startFragRequested) {\n // determine load level\n let startLevel = hls.startLevel;\n if (startLevel === -1) {\n // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level\n startLevel = 0;\n this.bitrateTest = true;\n }\n // set new level to playlist loader : this will trigger start level load\n // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded\n this.level = hls.nextLoadLevel = startLevel;\n this.loadedmetadata = false;\n }\n // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime\n if (lastCurrentTime > 0 && startPosition === -1) {\n logger.log(`override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);\n startPosition = lastCurrentTime;\n }\n this.state = State.IDLE;\n this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;\n this.tick();\n } else {\n this.forceStartLoad = true;\n this.state = State.STOPPED;\n }\n }\n\n stopLoad () {\n this.forceStartLoad = false;\n super.stopLoad();\n }\n\n doTick () {\n switch (this.state) {\n case State.BUFFER_FLUSHING:\n // in buffer flushing state, reset fragLoadError counter\n this.fragLoadError = 0;\n break;\n case State.IDLE:\n this._doTickIdle();\n break;\n case State.WAITING_LEVEL:\n var level = this.levels[this.level];\n // check if playlist is already loaded\n if (level && level.details) {\n this.state = State.IDLE;\n }\n\n break;\n case State.FRAG_LOADING_WAITING_RETRY:\n var now = window.performance.now();\n var retryDate = this.retryDate;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if (!retryDate || (now >= retryDate) || (this.media && this.media.seeking)) {\n logger.log('mediaController: retryDate reached, switch back to IDLE state');\n this.state = State.IDLE;\n }\n break;\n case State.ERROR:\n case State.STOPPED:\n case State.FRAG_LOADING:\n case State.PARSING:\n case State.PARSED:\n case State.ENDED:\n break;\n default:\n break;\n }\n // check buffer\n this._checkBuffer();\n // check/update current fragment\n this._checkFragmentChanged();\n }\n\n // Ironically the \"idle\" state is the on we do the most logic in it seems ....\n // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently\n // played segment, or on pause/play/seek instead of naively checking every 100ms?\n _doTickIdle () {\n const hls = this.hls,\n config = hls.config,\n media = this.media;\n\n // if start level not parsed yet OR\n // if video not attached AND start fragment already requested OR start frag prefetch disable\n // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment\n if (this.levelLastLoaded === undefined || (\n !media && (this.startFragRequested || !config.startFragPrefetch))) {\n return;\n }\n\n // if we have not yet loaded any fragment, start loading from start position\n let pos;\n if (this.loadedmetadata) {\n pos = media.currentTime;\n } else {\n pos = this.nextLoadPosition;\n }\n\n // determine next load level\n let level = hls.nextLoadLevel,\n levelInfo = this.levels[level];\n\n if (!levelInfo) {\n return;\n }\n\n let levelBitrate = levelInfo.bitrate,\n maxBufLen;\n\n // compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s\n if (levelBitrate) {\n maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);\n } else {\n maxBufLen = config.maxBufferLength;\n }\n\n maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength);\n\n // determine next candidate fragment to be loaded, based on current position and end of buffer position\n // ensure up to `config.maxMaxBufferLength` of buffer upfront\n\n const bufferInfo = BufferHelper.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, config.maxBufferHole),\n bufferLen = bufferInfo.len;\n // Stay idle if we are still with buffer margins\n if (bufferLen >= maxBufLen) {\n return;\n }\n\n // if buffer length is less than maxBufLen try to load a new fragment ...\n logger.trace(`buffer length of ${bufferLen.toFixed(3)} is below max of ${maxBufLen.toFixed(3)}. checking for more payload ...`);\n\n // set next load level : this will trigger a playlist load if needed\n this.level = hls.nextLoadLevel = level;\n\n const levelDetails = levelInfo.details;\n // if level info not retrieved yet, switch state and wait for level retrieval\n // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load\n // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)\n if (!levelDetails || (levelDetails.live && this.levelLastLoaded !== level)) {\n this.state = State.WAITING_LEVEL;\n return;\n }\n\n if (this._streamEnded(bufferInfo, levelDetails)) {\n const data = {};\n if (this.altAudio) {\n data.type = 'video';\n }\n\n this.hls.trigger(Event.BUFFER_EOS, data);\n this.state = State.ENDED;\n return;\n }\n // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)\n this._fetchPayloadOrEos(pos, bufferInfo, levelDetails);\n }\n\n _fetchPayloadOrEos (pos, bufferInfo, levelDetails) {\n const fragPrevious = this.fragPrevious,\n level = this.level,\n fragments = levelDetails.fragments,\n fragLen = fragments.length;\n\n // empty playlist\n if (fragLen === 0) {\n return;\n }\n\n // find fragment index, contiguous with end of buffer position\n let start = fragments[0].start,\n end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,\n bufferEnd = bufferInfo.end,\n frag;\n\n if (levelDetails.initSegment && !levelDetails.initSegment.data) {\n frag = levelDetails.initSegment;\n } else {\n // in case of live playlist we need to ensure that requested position is not located before playlist start\n if (levelDetails.live) {\n let initialLiveManifestSize = this.config.initialLiveManifestSize;\n if (fragLen < initialLiveManifestSize) {\n logger.warn(`Can not start playback of a level, reason: not enough fragments ${fragLen} < ${initialLiveManifestSize}`);\n return;\n }\n\n frag = this._ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen);\n // if it explicitely returns null don't load any fragment and exit function now\n if (frag === null) {\n return;\n }\n } else {\n // VoD playlist: if bufferEnd before start of playlist, load first fragment\n if (bufferEnd < start) {\n frag = fragments[0];\n }\n }\n }\n if (!frag) {\n frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails);\n }\n\n if (frag) {\n if (frag.encrypted) {\n logger.log(`Loading key for ${frag.sn} of [${levelDetails.startSN} ,${levelDetails.endSN}],level ${level}`);\n this._loadKey(frag);\n } else {\n logger.log(`Loading ${frag.sn} of [${levelDetails.startSN} ,${levelDetails.endSN}],level ${level}, currentTime:${pos.toFixed(3)},bufferEnd:${bufferEnd.toFixed(3)}`);\n this._loadFragment(frag);\n }\n }\n }\n\n _ensureFragmentAtLivePoint (levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen) {\n const config = this.hls.config, media = this.media;\n\n let frag;\n\n // check if requested position is within seekable boundaries :\n // logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);\n let maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;\n\n if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {\n let liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);\n logger.log(`buffer end: ${bufferEnd.toFixed(3)} is located too far from the end of live sliding playlist, reset currentTime to : ${liveSyncPosition.toFixed(3)}`);\n bufferEnd = liveSyncPosition;\n if (media && media.readyState && media.duration > liveSyncPosition) {\n media.currentTime = liveSyncPosition;\n }\n\n this.nextLoadPosition = liveSyncPosition;\n }\n\n // if end of buffer greater than live edge, don't load any fragment\n // this could happen if live playlist intermittently slides in the past.\n // level 1 loaded [182580161,182580167]\n // level 1 loaded [182580162,182580169]\n // Loading 182580168 of [182580162 ,182580169],level 1 ..\n // Loading 182580169 of [182580162 ,182580169],level 1 ..\n // level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168\n // level 1 loaded [182580164,182580171]\n //\n // don't return null in case media not loaded yet (readystate === 0)\n if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) {\n return null;\n }\n\n if (this.startFragRequested && !levelDetails.PTSKnown) {\n /* we are switching level on live playlist, but we don't have any PTS info for that quality level ...\n try to load frag matching with next SN.\n even if SN are not synchronized between playlists, loading this frag will help us\n compute playlist sliding and find the right one after in case it was not the right consecutive one */\n if (fragPrevious) {\n if (levelDetails.hasProgramDateTime) {\n // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)\n logger.log(`live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`);\n frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, config.maxFragLookUpTolerance);\n } else {\n // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n const targetSN = fragPrevious.sn + 1;\n if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {\n const fragNext = fragments[targetSN - levelDetails.startSN];\n if (fragPrevious.cc === fragNext.cc) {\n frag = fragNext;\n logger.log(`live playlist, switching playlist, load frag with next SN: ${frag.sn}`);\n }\n }\n // next frag SN not available (or not with same continuity counter)\n // look for a frag sharing the same CC\n if (!frag) {\n frag = BinarySearch.search(fragments, function (frag) {\n return fragPrevious.cc - frag.cc;\n });\n if (frag) {\n logger.log(`live playlist, switching playlist, load frag with same CC: ${frag.sn}`);\n }\n }\n }\n }\n if (!frag) {\n /* we have no idea about which fragment should be loaded.\n so let's load mid fragment. it will help computing playlist sliding and find the right one\n */\n frag = fragments[Math.min(fragLen - 1, Math.round(fragLen / 2))];\n logger.log(`live playlist, switching playlist, unknown, load middle frag : ${frag.sn}`);\n }\n }\n\n return frag;\n }\n\n _findFragment (start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails) {\n const config = this.hls.config;\n let frag;\n\n if (bufferEnd < end) {\n const lookupTolerance = (bufferEnd > end - config.maxFragLookUpTolerance) ? 0 : config.maxFragLookUpTolerance;\n // Remove the tolerance if it would put the bufferEnd past the actual end of stream\n // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n frag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, lookupTolerance);\n } else {\n // reach end of playlist\n frag = fragments[fragLen - 1];\n }\n if (frag) {\n const curSNIdx = frag.sn - levelDetails.startSN;\n const sameLevel = fragPrevious && frag.level === fragPrevious.level;\n const prevFrag = fragments[curSNIdx - 1];\n const nextFrag = fragments[curSNIdx + 1];\n // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);\n if (fragPrevious && frag.sn === fragPrevious.sn) {\n if (sameLevel && !frag.backtracked) {\n if (frag.sn < levelDetails.endSN) {\n let deltaPTS = fragPrevious.deltaPTS;\n // if there is a significant delta between audio and video, larger than max allowed hole,\n // and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped)\n // let's try to load previous fragment again to get last keyframe\n // then we will reload again current fragment (that way we should be able to fill the buffer hole ...)\n if (deltaPTS && deltaPTS > config.maxBufferHole && fragPrevious.dropped && curSNIdx) {\n frag = prevFrag;\n logger.warn('SN just loaded, with large PTS gap between audio and video, maybe frag is not starting with a keyframe ? load previous one to try to overcome this');\n } else {\n frag = nextFrag;\n logger.log(`SN just loaded, load next one: ${frag.sn}`, frag);\n }\n } else {\n frag = null;\n }\n } else if (frag.backtracked) {\n // Only backtrack a max of 1 consecutive fragment to prevent sliding back too far when little or no frags start with keyframes\n if (nextFrag && nextFrag.backtracked) {\n logger.warn(`Already backtracked from fragment ${nextFrag.sn}, will not backtrack to fragment ${frag.sn}. Loading fragment ${nextFrag.sn}`);\n frag = nextFrag;\n } else {\n // If a fragment has dropped frames and it's in a same level/sequence, load the previous fragment to try and find the keyframe\n // Reset the dropped count now since it won't be reset until we parse the fragment again, which prevents infinite backtracking on the same segment\n logger.warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe');\n frag.dropped = 0;\n if (prevFrag) {\n frag = prevFrag;\n frag.backtracked = true;\n } else if (curSNIdx) {\n // can't backtrack on very first fragment\n frag = null;\n }\n }\n }\n }\n }\n return frag;\n }\n\n _loadKey (frag) {\n this.state = State.KEY_LOADING;\n this.hls.trigger(Event.KEY_LOADING, { frag });\n }\n\n _loadFragment (frag) {\n // Check if fragment is not loaded\n let fragState = this.fragmentTracker.getState(frag);\n\n this.fragCurrent = frag;\n this.startFragRequested = true;\n // Don't update nextLoadPosition for fragments which are not buffered\n if (Number.isFinite(frag.sn) && !frag.bitrateTest) {\n this.nextLoadPosition = frag.start + frag.duration;\n }\n\n // Allow backtracked fragments to load\n if (frag.backtracked || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {\n frag.autoLevel = this.hls.autoLevelEnabled;\n frag.bitrateTest = this.bitrateTest;\n\n this.hls.trigger(Event.FRAG_LOADING, { frag });\n // lazy demuxer init, as this could take some time ... do it during frag loading\n if (!this.demuxer) {\n this.demuxer = new Demuxer(this.hls, 'main');\n }\n\n this.state = State.FRAG_LOADING;\n } else if (fragState === FragmentState.APPENDING) {\n // Lower the buffer size and try again\n if (this._reduceMaxBufferLength(frag.duration)) {\n this.fragmentTracker.removeFragment(frag);\n }\n }\n }\n\n set state (nextState) {\n if (this.state !== nextState) {\n const previousState = this.state;\n this._state = nextState;\n logger.log(`main stream:${previousState}->${nextState}`);\n this.hls.trigger(Event.STREAM_STATE_TRANSITION, { previousState, nextState });\n }\n }\n\n get state () {\n return this._state;\n }\n\n getBufferedFrag (position) {\n return this.fragmentTracker.getBufferedFrag(position, PlaylistLoader.LevelType.MAIN);\n }\n\n get currentLevel () {\n let media = this.media;\n if (media) {\n const frag = this.getBufferedFrag(media.currentTime);\n if (frag) {\n return frag.level;\n }\n }\n return -1;\n }\n\n get nextBufferedFrag () {\n let media = this.media;\n if (media) {\n // first get end range of current fragment\n return this.followingBufferedFrag(this.getBufferedFrag(media.currentTime));\n } else {\n return null;\n }\n }\n\n followingBufferedFrag (frag) {\n if (frag) {\n // try to get range of next fragment (500ms after this range)\n return this.getBufferedFrag(frag.endPTS + 0.5);\n }\n return null;\n }\n\n get nextLevel () {\n const frag = this.nextBufferedFrag;\n if (frag) {\n return frag.level;\n } else {\n return -1;\n }\n }\n\n _checkFragmentChanged () {\n let fragPlayingCurrent, currentTime, video = this.media;\n if (video && video.readyState && video.seeking === false) {\n currentTime = video.currentTime;\n /* if video element is in seeked state, currentTime can only increase.\n (assuming that playback rate is positive ...)\n As sometimes currentTime jumps back to zero after a\n media decode error, check this, to avoid seeking back to\n wrong position after a media decode error\n */\n if (currentTime > this.lastCurrentTime) {\n this.lastCurrentTime = currentTime;\n }\n\n if (BufferHelper.isBuffered(video, currentTime)) {\n fragPlayingCurrent = this.getBufferedFrag(currentTime);\n } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {\n /* ensure that FRAG_CHANGED event is triggered at startup,\n when first video frame is displayed and playback is paused.\n add a tolerance of 100ms, in case current position is not buffered,\n check if current pos+100ms is buffered and use that buffer range\n for FRAG_CHANGED event reporting */\n fragPlayingCurrent = this.getBufferedFrag(currentTime + 0.1);\n }\n if (fragPlayingCurrent) {\n let fragPlaying = fragPlayingCurrent;\n if (fragPlaying !== this.fragPlaying) {\n this.hls.trigger(Event.FRAG_CHANGED, { frag: fragPlaying });\n const fragPlayingLevel = fragPlaying.level;\n if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) {\n this.hls.trigger(Event.LEVEL_SWITCHED, { level: fragPlayingLevel });\n }\n\n this.fragPlaying = fragPlaying;\n }\n }\n }\n }\n\n /*\n on immediate level switch :\n - pause playback if playing\n - cancel any pending load request\n - and trigger a buffer flush\n */\n immediateLevelSwitch () {\n logger.log('immediateLevelSwitch');\n if (!this.immediateSwitch) {\n this.immediateSwitch = true;\n let media = this.media, previouslyPaused;\n if (media) {\n previouslyPaused = media.paused;\n media.pause();\n } else {\n // don't restart playback after instant level switch in case media not attached\n previouslyPaused = true;\n }\n this.previouslyPaused = previouslyPaused;\n }\n let fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\n\n this.fragCurrent = null;\n // flush everything\n this.flushMainBuffer(0, Number.POSITIVE_INFINITY);\n }\n\n /**\n * on immediate level switch end, after new fragment has been buffered:\n * - nudge video decoder by slightly adjusting video currentTime (if currentTime buffered)\n * - resume the playback if needed\n */\n immediateLevelSwitchEnd () {\n const media = this.media;\n if (media && media.buffered.length) {\n this.immediateSwitch = false;\n if (BufferHelper.isBuffered(media, media.currentTime)) {\n // only nudge if currentTime is buffered\n media.currentTime -= 0.0001;\n }\n if (!this.previouslyPaused) {\n media.play();\n }\n }\n }\n\n /**\n * try to switch ASAP without breaking video playback:\n * in order to ensure smooth but quick level switching,\n * we need to find the next flushable buffer range\n * we should take into account new segment fetch time\n */\n nextLevelSwitch () {\n const media = this.media;\n // ensure that media is defined and that metadata are available (to retrieve currentTime)\n if (media && media.readyState) {\n let fetchdelay, fragPlayingCurrent, nextBufferedFrag;\n fragPlayingCurrent = this.getBufferedFrag(media.currentTime);\n if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 1) {\n // flush buffer preceding current fragment (flush until current fragment start offset)\n // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...\n this.flushMainBuffer(0, fragPlayingCurrent.startPTS - 1);\n }\n if (!media.paused) {\n // add a safety delay of 1s\n let nextLevelId = this.hls.nextLoadLevel, nextLevel = this.levels[nextLevelId], fragLastKbps = this.fragLastKbps;\n if (fragLastKbps && this.fragCurrent) {\n fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;\n } else {\n fetchdelay = 0;\n }\n } else {\n fetchdelay = 0;\n }\n // logger.log('fetchdelay:'+fetchdelay);\n // find buffer range that will be reached once new fragment will be fetched\n nextBufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);\n if (nextBufferedFrag) {\n // we can flush buffer range following this one without stalling playback\n nextBufferedFrag = this.followingBufferedFrag(nextBufferedFrag);\n if (nextBufferedFrag) {\n // if we are here, we can also cancel any loading/demuxing in progress, as they are useless\n let fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\n\n this.fragCurrent = null;\n // start flush position is the start PTS of next buffered frag.\n // we use frag.naxStartPTS which is max(audio startPTS, video startPTS).\n // in case there is a small PTS Delta between audio and video, using maxStartPTS avoids flushing last samples from current fragment\n this.flushMainBuffer(nextBufferedFrag.maxStartPTS, Number.POSITIVE_INFINITY);\n }\n }\n }\n }\n\n flushMainBuffer (startOffset, endOffset) {\n this.state = State.BUFFER_FLUSHING;\n let flushScope = { startOffset: startOffset, endOffset: endOffset };\n // if alternate audio tracks are used, only flush video, otherwise flush everything\n if (this.altAudio) {\n flushScope.type = 'video';\n }\n\n this.hls.trigger(Event.BUFFER_FLUSHING, flushScope);\n }\n\n onMediaAttached (data) {\n let media = this.media = this.mediaBuffer = data.media;\n this.onvseeking = this.onMediaSeeking.bind(this);\n this.onvseeked = this.onMediaSeeked.bind(this);\n this.onvended = this.onMediaEnded.bind(this);\n media.addEventListener('seeking', this.onvseeking);\n media.addEventListener('seeked', this.onvseeked);\n media.addEventListener('ended', this.onvended);\n let config = this.config;\n if (this.levels && config.autoStartLoad) {\n this.hls.startLoad(config.startPosition);\n }\n\n this.gapController = new GapController(config, media, this.fragmentTracker, this.hls);\n }\n\n onMediaDetaching () {\n let media = this.media;\n if (media && media.ended) {\n logger.log('MSE detaching and video ended, reset startPosition');\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n // reset fragment backtracked flag\n let levels = this.levels;\n if (levels) {\n levels.forEach(level => {\n if (level.details) {\n level.details.fragments.forEach(fragment => {\n fragment.backtracked = undefined;\n });\n }\n });\n }\n // remove video listeners\n if (media) {\n media.removeEventListener('seeking', this.onvseeking);\n media.removeEventListener('seeked', this.onvseeked);\n media.removeEventListener('ended', this.onvended);\n this.onvseeking = this.onvseeked = this.onvended = null;\n }\n this.media = this.mediaBuffer = null;\n this.loadedmetadata = false;\n this.stopLoad();\n }\n\n onMediaSeeked () {\n const media = this.media, currentTime = media ? media.currentTime : undefined;\n if (Number.isFinite(currentTime)) {\n logger.log(`media seeked to ${currentTime.toFixed(3)}`);\n }\n\n // tick to speed up FRAGMENT_PLAYING triggering\n this.tick();\n }\n\n onManifestLoading () {\n // reset buffer on manifest loading\n logger.log('trigger BUFFER_RESET');\n this.hls.trigger(Event.BUFFER_RESET);\n this.fragmentTracker.removeAllFragments();\n this.stalled = false;\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n onManifestParsed (data) {\n let aac = false, heaac = false, codec;\n data.levels.forEach(level => {\n // detect if we have different kind of audio codecs used amongst playlists\n codec = level.audioCodec;\n if (codec) {\n if (codec.indexOf('mp4a.40.2') !== -1) {\n aac = true;\n }\n\n if (codec.indexOf('mp4a.40.5') !== -1) {\n heaac = true;\n }\n }\n });\n this.audioCodecSwitch = (aac && heaac);\n if (this.audioCodecSwitch) {\n logger.log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');\n }\n\n this.levels = data.levels;\n this.startFragRequested = false;\n let config = this.config;\n if (config.autoStartLoad || this.forceStartLoad) {\n this.hls.startLoad(config.startPosition);\n }\n }\n\n onLevelLoaded (data) {\n const newDetails = data.details;\n const newLevelId = data.level;\n const lastLevel = this.levels[this.levelLastLoaded];\n const curLevel = this.levels[newLevelId];\n const duration = newDetails.totalduration;\n let sliding = 0;\n\n logger.log(`level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}],duration:${duration}`);\n\n if (newDetails.live) {\n let curDetails = curLevel.details;\n if (curDetails && newDetails.fragments.length > 0) {\n // we already have details for that level, merge them\n LevelHelper.mergeDetails(curDetails, newDetails);\n sliding = newDetails.fragments[0].start;\n this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);\n if (newDetails.PTSKnown && Number.isFinite(sliding)) {\n logger.log(`live playlist sliding:${sliding.toFixed(3)}`);\n } else {\n logger.log('live playlist - outdated PTS, unknown sliding');\n alignStream(this.fragPrevious, lastLevel, newDetails);\n }\n } else {\n logger.log('live playlist - first load, unknown sliding');\n newDetails.PTSKnown = false;\n alignStream(this.fragPrevious, lastLevel, newDetails);\n }\n } else {\n newDetails.PTSKnown = false;\n }\n // override level info\n curLevel.details = newDetails;\n this.levelLastLoaded = newLevelId;\n this.hls.trigger(Event.LEVEL_UPDATED, { details: newDetails, level: newLevelId });\n\n if (this.startFragRequested === false) {\n // compute start position if set to -1. use it straight away if value is defined\n if (this.startPosition === -1 || this.lastCurrentTime === -1) {\n // first, check if start time offset has been set in playlist, if yes, use this value\n let startTimeOffset = newDetails.startTimeOffset;\n if (Number.isFinite(startTimeOffset)) {\n if (startTimeOffset < 0) {\n logger.log(`negative start time offset ${startTimeOffset}, count from end of last fragment`);\n startTimeOffset = sliding + duration + startTimeOffset;\n }\n logger.log(`start time offset found in playlist, adjust startPosition to ${startTimeOffset}`);\n this.startPosition = startTimeOffset;\n } else {\n // if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3)\n if (newDetails.live) {\n this.startPosition = this.computeLivePosition(sliding, newDetails);\n logger.log(`configure startPosition to ${this.startPosition}`);\n } else {\n this.startPosition = 0;\n }\n }\n this.lastCurrentTime = this.startPosition;\n }\n this.nextLoadPosition = this.startPosition;\n }\n // only switch batck to IDLE state if we were waiting for level to start downloading a new fragment\n if (this.state === State.WAITING_LEVEL) {\n this.state = State.IDLE;\n }\n\n // trigger handler right now\n this.tick();\n }\n\n onKeyLoaded () {\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n this.tick();\n }\n }\n\n onFragLoaded (data) {\n const { fragCurrent, hls, levels, media } = this;\n const fragLoaded = data.frag;\n if (this.state === State.FRAG_LOADING &&\n fragCurrent &&\n fragLoaded.type === 'main' &&\n fragLoaded.level === fragCurrent.level &&\n fragLoaded.sn === fragCurrent.sn) {\n const stats = data.stats;\n const currentLevel = levels[fragCurrent.level];\n const details = currentLevel.details;\n // reset frag bitrate test in any case after frag loaded event\n // if this frag was loaded to perform a bitrate test AND if hls.nextLoadLevel is greater than 0\n // then this means that we should be able to load a fragment at a higher quality level\n this.bitrateTest = false;\n this.stats = stats;\n\n logger.log(`Loaded ${fragCurrent.sn} of [${details.startSN} ,${details.endSN}],level ${fragCurrent.level}`);\n if (fragLoaded.bitrateTest && hls.nextLoadLevel) {\n // switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo\n this.state = State.IDLE;\n this.startFragRequested = false;\n stats.tparsed = stats.tbuffered = window.performance.now();\n hls.trigger(Event.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });\n this.tick();\n } else if (fragLoaded.sn === 'initSegment') {\n this.state = State.IDLE;\n stats.tparsed = stats.tbuffered = window.performance.now();\n details.initSegment.data = data.payload;\n hls.trigger(Event.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });\n this.tick();\n } else {\n logger.log(`Parsing ${fragCurrent.sn} of [${details.startSN} ,${details.endSN}],level ${fragCurrent.level}, cc ${fragCurrent.cc}`);\n this.state = State.PARSING;\n this.pendingBuffering = true;\n this.appended = false;\n\n // Bitrate test frags are not usually buffered so the fragment tracker ignores them. If Hls.js decides to buffer\n // it (and therefore ends up at this line), then the fragment tracker needs to be manually informed.\n if (fragLoaded.bitrateTest) {\n fragLoaded.bitrateTest = false;\n this.fragmentTracker.onFragLoaded({\n frag: fragLoaded\n });\n }\n\n // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) and if media is not seeking (this is to overcome potential timestamp drifts between playlists and fragments)\n const accurateTimeOffset = !(media && media.seeking) && (details.PTSKnown || !details.live);\n const initSegmentData = details.initSegment ? details.initSegment.data : [];\n const audioCodec = this._getAudioCodec(currentLevel);\n\n // transmux the MPEG-TS data to ISO-BMFF segments\n const demuxer = this.demuxer = this.demuxer || new Demuxer(this.hls, 'main');\n demuxer.push(\n data.payload,\n initSegmentData,\n audioCodec,\n currentLevel.videoCodec,\n fragCurrent,\n details.totalduration,\n accurateTimeOffset\n );\n }\n }\n this.fragLoadError = 0;\n }\n\n onFragParsingInitSegment (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n let tracks = data.tracks, trackName, track;\n\n // if audio track is expected to come from audio stream controller, discard any coming from main\n if (tracks.audio && this.altAudio) {\n delete tracks.audio;\n }\n\n // include levelCodec in audio and video tracks\n track = tracks.audio;\n if (track) {\n let audioCodec = this.levels[this.level].audioCodec,\n ua = navigator.userAgent.toLowerCase();\n if (audioCodec && this.audioCodecSwap) {\n logger.log('swapping playlist audio codec');\n if (audioCodec.indexOf('mp4a.40.5') !== -1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n // in case AAC and HE-AAC audio codecs are signalled in manifest\n // force HE-AAC , as it seems that most browsers prefers that way,\n // except for mono streams OR on FF\n // these conditions might need to be reviewed ...\n if (this.audioCodecSwitch) {\n // don't force HE-AAC if mono stream\n if (track.metadata.channelCount !== 1 &&\n // don't force HE-AAC if firefox\n ua.indexOf('firefox') === -1) {\n audioCodec = 'mp4a.40.5';\n }\n }\n // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise\n if (ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') { // Exclude mpeg audio\n audioCodec = 'mp4a.40.2';\n logger.log(`Android: force audio codec to ${audioCodec}`);\n }\n track.levelCodec = audioCodec;\n track.id = data.id;\n }\n track = tracks.video;\n if (track) {\n track.levelCodec = this.levels[this.level].videoCodec;\n track.id = data.id;\n }\n this.hls.trigger(Event.BUFFER_CODECS, tracks);\n // loop through tracks that are going to be provided to bufferController\n for (trackName in tracks) {\n track = tracks[trackName];\n logger.log(`main track:${trackName},container:${track.container},codecs[level/parsed]=[${track.levelCodec}/${track.codec}]`);\n let initSegment = track.initSegment;\n if (initSegment) {\n this.appended = true;\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n this.hls.trigger(Event.BUFFER_APPENDING, { type: trackName, data: initSegment, parent: 'main', content: 'initSegment' });\n }\n }\n // trigger handler right now\n this.tick();\n }\n }\n\n onFragParsingData (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n !(data.type === 'audio' && this.altAudio) && // filter out main audio if audio track is loaded through audio stream controller\n this.state === State.PARSING) {\n let level = this.levels[this.level],\n frag = fragCurrent;\n if (!Number.isFinite(data.endPTS)) {\n data.endPTS = data.startPTS + fragCurrent.duration;\n data.endDTS = data.startDTS + fragCurrent.duration;\n }\n\n if (data.hasAudio === true) {\n frag.addElementaryStream(Fragment.ElementaryStreamTypes.AUDIO);\n }\n\n if (data.hasVideo === true) {\n frag.addElementaryStream(Fragment.ElementaryStreamTypes.VIDEO);\n }\n\n logger.log(`Parsed ${data.type},PTS:[${data.startPTS.toFixed(3)},${data.endPTS.toFixed(3)}],DTS:[${data.startDTS.toFixed(3)}/${data.endDTS.toFixed(3)}],nb:${data.nb},dropped:${data.dropped || 0}`);\n\n // Detect gaps in a fragment and try to fix it by finding a keyframe in the previous fragment (see _findFragments)\n if (data.type === 'video') {\n frag.dropped = data.dropped;\n if (frag.dropped) {\n if (!frag.backtracked) {\n const levelDetails = level.details;\n if (levelDetails && frag.sn === levelDetails.startSN) {\n logger.warn('missing video frame(s) on first frag, appending with gap', frag.sn);\n } else {\n logger.warn('missing video frame(s), backtracking fragment', frag.sn);\n // Return back to the IDLE state without appending to buffer\n // Causes findFragments to backtrack a segment and find the keyframe\n // Audio fragments arriving before video sets the nextLoadPosition, causing _findFragments to skip the backtracked fragment\n this.fragmentTracker.removeFragment(frag);\n frag.backtracked = true;\n this.nextLoadPosition = data.startPTS;\n this.state = State.IDLE;\n this.fragPrevious = frag;\n this.tick();\n return;\n }\n } else {\n logger.warn('Already backtracked on this fragment, appending with the gap', frag.sn);\n }\n } else {\n // Only reset the backtracked flag if we've loaded the frag without any dropped frames\n frag.backtracked = false;\n }\n }\n\n let drift = LevelHelper.updateFragPTSDTS(level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS),\n hls = this.hls;\n hls.trigger(Event.LEVEL_PTS_UPDATED, { details: level.details, level: this.level, drift: drift, type: data.type, start: data.startPTS, end: data.endPTS });\n // has remuxer dropped video frames located before first keyframe ?\n [data.data1, data.data2].forEach(buffer => {\n // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)\n // in that case it is useless to append following segments\n if (buffer && buffer.length && this.state === State.PARSING) {\n this.appended = true;\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n hls.trigger(Event.BUFFER_APPENDING, { type: data.type, data: buffer, parent: 'main', content: 'data' });\n }\n });\n // trigger handler right now\n this.tick();\n }\n }\n\n onFragParsed (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n this.stats.tparsed = window.performance.now();\n this.state = State.PARSED;\n this._checkAppendedParsed();\n }\n }\n\n onAudioTrackSwitching (data) {\n // if any URL found on new audio track, it is an alternate audio track\n let altAudio = !!data.url,\n trackId = data.id;\n // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered\n // don't do anything if we switch to alt audio: audio stream controller is handling it.\n // we will just have to change buffer scheduling on audioTrackSwitched\n if (!altAudio) {\n if (this.mediaBuffer !== this.media) {\n logger.log('switching on main audio, use media.buffered to schedule main fragment loading');\n this.mediaBuffer = this.media;\n let fragCurrent = this.fragCurrent;\n // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch\n if (fragCurrent.loader) {\n logger.log('switching to main audio track, cancel main fragment load');\n fragCurrent.loader.abort();\n }\n this.fragCurrent = null;\n this.fragPrevious = null;\n // destroy demuxer to force init segment generation (following audio switch)\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n // switch to IDLE state to load new fragment\n this.state = State.IDLE;\n }\n let hls = this.hls;\n // switching to main audio, flush all audio and trigger track switched\n hls.trigger(Event.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, { id: trackId });\n this.altAudio = false;\n }\n }\n\n onAudioTrackSwitched (data) {\n let trackId = data.id,\n altAudio = !!this.hls.audioTracks[trackId].url;\n if (altAudio) {\n let videoBuffer = this.videoBuffer;\n // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered\n if (videoBuffer && this.mediaBuffer !== videoBuffer) {\n logger.log('switching on alternate audio, use video.buffered to schedule main fragment loading');\n this.mediaBuffer = videoBuffer;\n }\n }\n this.altAudio = altAudio;\n this.tick();\n }\n\n onBufferCreated (data) {\n let tracks = data.tracks, mediaTrack, name, alternate = false;\n for (let type in tracks) {\n let track = tracks[type];\n if (track.id === 'main') {\n name = type;\n mediaTrack = track;\n // keep video source buffer reference\n if (type === 'video') {\n this.videoBuffer = tracks[type].buffer;\n }\n } else {\n alternate = true;\n }\n }\n if (alternate && mediaTrack) {\n logger.log(`alternate track found, use ${name}.buffered to schedule main fragment loading`);\n this.mediaBuffer = mediaTrack.buffer;\n } else {\n this.mediaBuffer = this.media;\n }\n }\n\n onBufferAppended (data) {\n if (data.parent === 'main') {\n const state = this.state;\n if (state === State.PARSING || state === State.PARSED) {\n // check if all buffers have been appended\n this.pendingBuffering = (data.pending > 0);\n this._checkAppendedParsed();\n }\n }\n }\n\n _checkAppendedParsed () {\n // trigger handler right now\n if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {\n const frag = this.fragCurrent;\n if (frag) {\n const media = this.mediaBuffer ? this.mediaBuffer : this.media;\n logger.log(`main buffered : ${TimeRanges.toString(media.buffered)}`);\n this.fragPrevious = frag;\n const stats = this.stats;\n stats.tbuffered = window.performance.now();\n // we should get rid of this.fragLastKbps\n this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst));\n this.hls.trigger(Event.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'main' });\n this.state = State.IDLE;\n }\n this.tick();\n }\n }\n\n onError (data) {\n let frag = data.frag || this.fragCurrent;\n // don't handle frag error not related to main fragment\n if (frag && frag.type !== 'main') {\n return;\n }\n\n // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end\n let mediaBuffered = !!this.media && BufferHelper.isBuffered(this.media, this.media.currentTime) && BufferHelper.isBuffered(this.media, this.media.currentTime + 0.5);\n\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n if (!data.fatal) {\n // keep retrying until the limit will be reached\n if ((this.fragLoadError + 1) <= this.config.fragLoadingMaxRetry) {\n // exponential backoff capped to config.fragLoadingMaxRetryTimeout\n let delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout);\n logger.warn(`mediaController: frag loading failed, retry in ${delay} ms`);\n this.retryDate = window.performance.now() + delay;\n // retry loading state\n // if loadedmetadata is not set, it means that we are emergency switch down on first frag\n // in that case, reset startFragRequested flag\n if (!this.loadedmetadata) {\n this.startFragRequested = false;\n this.nextLoadPosition = this.startPosition;\n }\n this.fragLoadError++;\n this.state = State.FRAG_LOADING_WAITING_RETRY;\n } else {\n logger.error(`mediaController: ${data.details} reaches max retry, redispatch as fatal ...`);\n // switch error to fatal\n data.fatal = true;\n this.state = State.ERROR;\n }\n }\n break;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n if (this.state !== State.ERROR) {\n if (data.fatal) {\n // if fatal error, stop processing\n this.state = State.ERROR;\n logger.warn(`streamController: ${data.details},switch to ${this.state} state ...`);\n } else {\n // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE\n if (!data.levelRetry && this.state === State.WAITING_LEVEL) {\n this.state = State.IDLE;\n }\n }\n }\n break;\n case ErrorDetails.BUFFER_FULL_ERROR:\n // if in appending state\n if (data.parent === 'main' && (this.state === State.PARSING || this.state === State.PARSED)) {\n // reduce max buf len if current position is buffered\n if (mediaBuffered) {\n this._reduceMaxBufferLength(this.config.maxBufferLength);\n this.state = State.IDLE;\n } else {\n // current position is not buffered, but browser is still complaining about buffer full error\n // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708\n // in that case flush the whole buffer to recover\n logger.warn('buffer full error also media.currentTime is not buffered, flush everything');\n this.fragCurrent = null;\n // flush everything\n this.flushMainBuffer(0, Number.POSITIVE_INFINITY);\n }\n }\n break;\n default:\n break;\n }\n }\n\n _reduceMaxBufferLength (minLength) {\n let config = this.config;\n if (config.maxMaxBufferLength >= minLength) {\n // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...\n config.maxMaxBufferLength /= 2;\n logger.warn(`main:reduce max buffer length to ${config.maxMaxBufferLength}s`);\n return true;\n }\n return false;\n }\n\n /**\n * Checks the health of the buffer and attempts to resolve playback stalls.\n * @private\n */\n _checkBuffer () {\n const { media } = this;\n if (!media || media.readyState === 0) {\n // Exit early if we don't have media or if the media hasn't bufferd anything yet (readyState 0)\n return;\n }\n\n const mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;\n const buffered = mediaBuffer.buffered;\n\n if (!this.loadedmetadata && buffered.length) {\n this.loadedmetadata = true;\n this._seekToStartPos();\n } else if (this.immediateSwitch) {\n this.immediateLevelSwitchEnd();\n } else {\n this.gapController.poll(this.lastCurrentTime, buffered);\n }\n }\n\n onFragLoadEmergencyAborted () {\n this.state = State.IDLE;\n // if loadedmetadata is not set, it means that we are emergency switch down on first frag\n // in that case, reset startFragRequested flag\n if (!this.loadedmetadata) {\n this.startFragRequested = false;\n this.nextLoadPosition = this.startPosition;\n }\n this.tick();\n }\n\n onBufferFlushed () {\n /* after successful buffer flushing, filter flushed fragments from bufferedFrags\n use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track)\n */\n const media = this.mediaBuffer ? this.mediaBuffer : this.media;\n if (media) {\n // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams\n this.fragmentTracker.detectEvictedFragments(Fragment.ElementaryStreamTypes.VIDEO, media.buffered);\n }\n // move to IDLE once flush complete. this should trigger new fragment loading\n this.state = State.IDLE;\n // reset reference to frag\n this.fragPrevious = null;\n }\n\n swapAudioCodec () {\n this.audioCodecSwap = !this.audioCodecSwap;\n }\n\n computeLivePosition (sliding, levelDetails) {\n let targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration;\n return sliding + Math.max(0, levelDetails.totalduration - targetLatency);\n }\n\n /**\n * Seeks to the set startPosition if not equal to the mediaElement's current time.\n * @private\n */\n _seekToStartPos () {\n const { media } = this;\n const currentTime = media.currentTime;\n // only adjust currentTime if different from startPosition or if startPosition not buffered\n // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered\n const startPosition = media.seeking ? currentTime : this.startPosition;\n // if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered\n if (currentTime !== startPosition) {\n // if startPosition not buffered, let's seek to buffered.start(0)\n logger.log(`target start position not buffered, seek to buffered.start(0) ${startPosition} from current time ${currentTime} `);\n media.currentTime = startPosition;\n }\n }\n\n _getAudioCodec (currentLevel) {\n let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;\n if (this.audioCodecSwap) {\n logger.log('swapping playlist audio codec');\n if (audioCodec) {\n if (audioCodec.indexOf('mp4a.40.5') !== -1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n }\n\n return audioCodec;\n }\n\n get liveSyncPosition () {\n return this._liveSyncPosition;\n }\n\n set liveSyncPosition (value) {\n this._liveSyncPosition = value;\n }\n}\nexport default StreamController;\n","function webpackBootstrapFunc (modules) {\n/******/ // The module cache\n/******/ var installedModules = {};\n\n/******/ // The require function\n/******/ function __webpack_require__(moduleId) {\n\n/******/ // Check if module is in cache\n/******/ if(installedModules[moduleId])\n/******/ return installedModules[moduleId].exports;\n\n/******/ // Create a new module (and put it into the cache)\n/******/ var module = installedModules[moduleId] = {\n/******/ i: moduleId,\n/******/ l: false,\n/******/ exports: {}\n/******/ };\n\n/******/ // Execute the module function\n/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n/******/ // Flag the module as loaded\n/******/ module.l = true;\n\n/******/ // Return the exports of the module\n/******/ return module.exports;\n/******/ }\n\n/******/ // expose the modules object (__webpack_modules__)\n/******/ __webpack_require__.m = modules;\n\n/******/ // expose the module cache\n/******/ __webpack_require__.c = installedModules;\n\n/******/ // identity function for calling harmony imports with the correct context\n/******/ __webpack_require__.i = function(value) { return value; };\n\n/******/ // define getter function for harmony exports\n/******/ __webpack_require__.d = function(exports, name, getter) {\n/******/ if(!__webpack_require__.o(exports, name)) {\n/******/ Object.defineProperty(exports, name, {\n/******/ configurable: false,\n/******/ enumerable: true,\n/******/ get: getter\n/******/ });\n/******/ }\n/******/ };\n\n/******/ // define __esModule on exports\n/******/ __webpack_require__.r = function(exports) {\n/******/ Object.defineProperty(exports, '__esModule', { value: true });\n/******/ };\n\n/******/ // getDefaultExport function for compatibility with non-harmony modules\n/******/ __webpack_require__.n = function(module) {\n/******/ var getter = module && module.__esModule ?\n/******/ function getDefault() { return module['default']; } :\n/******/ function getModuleExports() { return module; };\n/******/ __webpack_require__.d(getter, 'a', getter);\n/******/ return getter;\n/******/ };\n\n/******/ // Object.prototype.hasOwnProperty.call\n/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n/******/ // __webpack_public_path__\n/******/ __webpack_require__.p = \"/\";\n\n/******/ // on error function for async loading\n/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; };\n\n var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE)\n return f.default || f // try to call default if defined to also support babel esmodule exports\n}\n\nvar moduleNameReqExp = '[\\\\.|\\\\-|\\\\+|\\\\w|\\/|@]+'\nvar dependencyRegExp = '\\\\((\\/\\\\*.*?\\\\*\\/)?\\s?.*?(' + moduleNameReqExp + ').*?\\\\)' // additional chars when output.pathinfo is true\n\n// http://stackoverflow.com/a/2593661/130442\nfunction quoteRegExp (str) {\n return (str + '').replace(/[.?*+^$[\\]\\\\(){}|-]/g, '\\\\$&')\n}\n\nfunction isNumeric(n) {\n return !isNaN(1 * n); // 1 * n converts integers, integers as string (\"123\"), 1e3 and \"1e3\" to integers and strings to NaN\n}\n\nfunction getModuleDependencies (sources, module, queueName) {\n var retval = {}\n retval[queueName] = []\n\n var fnString = module.toString()\n var wrapperSignature = fnString.match(/^function\\s?\\(\\w+,\\s*\\w+,\\s*(\\w+)\\)/)\n if (!wrapperSignature) return retval\n var webpackRequireName = wrapperSignature[1]\n\n // main bundle deps\n var re = new RegExp('(\\\\\\\\n|\\\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')\n var match\n while ((match = re.exec(fnString))) {\n if (match[3] === 'dll-reference') continue\n retval[queueName].push(match[3])\n }\n\n // dll deps\n re = new RegExp('\\\\(' + quoteRegExp(webpackRequireName) + '\\\\(\"(dll-reference\\\\s(' + moduleNameReqExp + '))\"\\\\)\\\\)' + dependencyRegExp, 'g')\n while ((match = re.exec(fnString))) {\n if (!sources[match[2]]) {\n retval[queueName].push(match[1])\n sources[match[2]] = __webpack_require__(match[1]).m\n }\n retval[match[2]] = retval[match[2]] || []\n retval[match[2]].push(match[4])\n }\n\n // convert 1e3 back to 1000 - this can be important after uglify-js converted 1000 to 1e3\n var keys = Object.keys(retval);\n for (var i = 0; i < keys.length; i++) {\n for (var j = 0; j < retval[keys[i]].length; j++) {\n if (isNumeric(retval[keys[i]][j])) {\n retval[keys[i]][j] = 1 * retval[keys[i]][j];\n }\n }\n }\n\n return retval\n}\n\nfunction hasValuesInQueues (queues) {\n var keys = Object.keys(queues)\n return keys.reduce(function (hasValues, key) {\n return hasValues || queues[key].length > 0\n }, false)\n}\n\nfunction getRequiredModules (sources, moduleId) {\n var modulesQueue = {\n main: [moduleId]\n }\n var requiredModules = {\n main: []\n }\n var seenModules = {\n main: {}\n }\n\n while (hasValuesInQueues(modulesQueue)) {\n var queues = Object.keys(modulesQueue)\n for (var i = 0; i < queues.length; i++) {\n var queueName = queues[i]\n var queue = modulesQueue[queueName]\n var moduleToCheck = queue.pop()\n seenModules[queueName] = seenModules[queueName] || {}\n if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue\n seenModules[queueName][moduleToCheck] = true\n requiredModules[queueName] = requiredModules[queueName] || []\n requiredModules[queueName].push(moduleToCheck)\n var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)\n var newModulesKeys = Object.keys(newModules)\n for (var j = 0; j < newModulesKeys.length; j++) {\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])\n }\n }\n }\n\n return requiredModules\n}\n\nmodule.exports = function (moduleId, options) {\n options = options || {}\n var sources = {\n main: __webpack_modules__\n }\n\n var requiredModules = options.all ? { main: Object.keys(sources.main) } : getRequiredModules(sources, moduleId)\n\n var src = ''\n\n Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {\n var entryModule = 0\n while (requiredModules[module][entryModule]) {\n entryModule++\n }\n requiredModules[module].push(entryModule)\n sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'\n src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\\n'\n })\n\n src = src + 'new ((' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[id].toString() }).join(',') + '}))(self);'\n\n var blob = new window.Blob([src], { type: 'text/javascript' })\n if (options.bare) { return blob }\n\n var URL = window.URL || window.webkitURL || window.mozURL || window.msURL\n\n var workerUrl = URL.createObjectURL(blob)\n var worker = new window.Worker(workerUrl)\n worker.objectURL = workerUrl\n\n return worker\n}\n","export default class AESCrypto {\n constructor (subtle, iv) {\n this.subtle = subtle;\n this.aesIV = iv;\n }\n\n decrypt (data, key) {\n return this.subtle.decrypt({ name: 'AES-CBC', iv: this.aesIV }, key, data);\n }\n}\n","class FastAESKey {\n constructor (subtle, key) {\n this.subtle = subtle;\n this.key = key;\n }\n\n expandKey () {\n return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, ['encrypt', 'decrypt']);\n }\n}\n\nexport default FastAESKey;\n","// PKCS7\nexport function removePadding (buffer) {\n const outputBytes = buffer.byteLength;\n const paddingBytes = outputBytes && (new DataView(buffer)).getUint8(outputBytes - 1);\n if (paddingBytes) {\n return buffer.slice(0, outputBytes - paddingBytes);\n } else {\n return buffer;\n }\n}\n\nclass AESDecryptor {\n constructor () {\n // Static after running initTable\n this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];\n this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];\n this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];\n this.sBox = new Uint32Array(256);\n this.invSBox = new Uint32Array(256);\n\n // Changes during runtime\n this.key = new Uint32Array(0);\n\n this.initTable();\n }\n\n // Using view.getUint32() also swaps the byte order.\n uint8ArrayToUint32Array_ (arrayBuffer) {\n let view = new DataView(arrayBuffer);\n let newArray = new Uint32Array(4);\n for (let i = 0; i < 4; i++) {\n newArray[i] = view.getUint32(i * 4);\n }\n\n return newArray;\n }\n\n initTable () {\n let sBox = this.sBox;\n let invSBox = this.invSBox;\n let subMix = this.subMix;\n let subMix0 = subMix[0];\n let subMix1 = subMix[1];\n let subMix2 = subMix[2];\n let subMix3 = subMix[3];\n let invSubMix = this.invSubMix;\n let invSubMix0 = invSubMix[0];\n let invSubMix1 = invSubMix[1];\n let invSubMix2 = invSubMix[2];\n let invSubMix3 = invSubMix[3];\n\n let d = new Uint32Array(256);\n let x = 0;\n let xi = 0;\n let i = 0;\n for (i = 0; i < 256; i++) {\n if (i < 128) {\n d[i] = i << 1;\n } else {\n d[i] = (i << 1) ^ 0x11b;\n }\n }\n\n for (i = 0; i < 256; i++) {\n let sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);\n sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;\n sBox[x] = sx;\n invSBox[sx] = x;\n\n // Compute multiplication\n let x2 = d[x];\n let x4 = d[x2];\n let x8 = d[x4];\n\n // Compute sub/invSub bytes, mix columns tables\n let t = (d[sx] * 0x101) ^ (sx * 0x1010100);\n subMix0[x] = (t << 24) | (t >>> 8);\n subMix1[x] = (t << 16) | (t >>> 16);\n subMix2[x] = (t << 8) | (t >>> 24);\n subMix3[x] = t;\n\n // Compute inv sub bytes, inv mix columns tables\n t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);\n invSubMix0[sx] = (t << 24) | (t >>> 8);\n invSubMix1[sx] = (t << 16) | (t >>> 16);\n invSubMix2[sx] = (t << 8) | (t >>> 24);\n invSubMix3[sx] = t;\n\n // Compute next counter\n if (!x) {\n x = xi = 1;\n } else {\n x = x2 ^ d[d[d[x8 ^ x2]]];\n xi ^= d[d[xi]];\n }\n }\n }\n\n expandKey (keyBuffer) {\n // convert keyBuffer to Uint32Array\n let key = this.uint8ArrayToUint32Array_(keyBuffer);\n let sameKey = true;\n let offset = 0;\n\n while (offset < key.length && sameKey) {\n sameKey = (key[offset] === this.key[offset]);\n offset++;\n }\n\n if (sameKey) {\n return;\n }\n\n this.key = key;\n let keySize = this.keySize = key.length;\n\n if (keySize !== 4 && keySize !== 6 && keySize !== 8) {\n throw new Error('Invalid aes key size=' + keySize);\n }\n\n let ksRows = this.ksRows = (keySize + 6 + 1) * 4;\n let ksRow;\n let invKsRow;\n\n let keySchedule = this.keySchedule = new Uint32Array(ksRows);\n let invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);\n let sbox = this.sBox;\n let rcon = this.rcon;\n\n let invSubMix = this.invSubMix;\n let invSubMix0 = invSubMix[0];\n let invSubMix1 = invSubMix[1];\n let invSubMix2 = invSubMix[2];\n let invSubMix3 = invSubMix[3];\n\n let prev;\n let t;\n\n for (ksRow = 0; ksRow < ksRows; ksRow++) {\n if (ksRow < keySize) {\n prev = keySchedule[ksRow] = key[ksRow];\n continue;\n }\n t = prev;\n\n if (ksRow % keySize === 0) {\n // Rot word\n t = (t << 8) | (t >>> 24);\n\n // Sub word\n t = (sbox[t >>> 24] << 24) | (sbox[(t >>> 16) & 0xff] << 16) | (sbox[(t >>> 8) & 0xff] << 8) | sbox[t & 0xff];\n\n // Mix Rcon\n t ^= rcon[(ksRow / keySize) | 0] << 24;\n } else if (keySize > 6 && ksRow % keySize === 4) {\n // Sub word\n t = (sbox[t >>> 24] << 24) | (sbox[(t >>> 16) & 0xff] << 16) | (sbox[(t >>> 8) & 0xff] << 8) | sbox[t & 0xff];\n }\n\n keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;\n }\n\n for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {\n ksRow = ksRows - invKsRow;\n if (invKsRow & 3) {\n t = keySchedule[ksRow];\n } else {\n t = keySchedule[ksRow - 4];\n }\n\n if (invKsRow < 4 || ksRow <= 4) {\n invKeySchedule[invKsRow] = t;\n } else {\n invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[(t >>> 16) & 0xff]] ^ invSubMix2[sbox[(t >>> 8) & 0xff]] ^ invSubMix3[sbox[t & 0xff]];\n }\n\n invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;\n }\n }\n\n // Adding this as a method greatly improves performance.\n networkToHostOrderSwap (word) {\n return (word << 24) | ((word & 0xff00) << 8) | ((word & 0xff0000) >> 8) | (word >>> 24);\n }\n\n decrypt (inputArrayBuffer, offset, aesIV, removePKCS7Padding) {\n let nRounds = this.keySize + 6;\n let invKeySchedule = this.invKeySchedule;\n let invSBOX = this.invSBox;\n\n let invSubMix = this.invSubMix;\n let invSubMix0 = invSubMix[0];\n let invSubMix1 = invSubMix[1];\n let invSubMix2 = invSubMix[2];\n let invSubMix3 = invSubMix[3];\n\n let initVector = this.uint8ArrayToUint32Array_(aesIV);\n let initVector0 = initVector[0];\n let initVector1 = initVector[1];\n let initVector2 = initVector[2];\n let initVector3 = initVector[3];\n\n let inputInt32 = new Int32Array(inputArrayBuffer);\n let outputInt32 = new Int32Array(inputInt32.length);\n\n let t0, t1, t2, t3;\n let s0, s1, s2, s3;\n let inputWords0, inputWords1, inputWords2, inputWords3;\n\n let ksRow, i;\n let swapWord = this.networkToHostOrderSwap;\n\n while (offset < inputInt32.length) {\n inputWords0 = swapWord(inputInt32[offset]);\n inputWords1 = swapWord(inputInt32[offset + 1]);\n inputWords2 = swapWord(inputInt32[offset + 2]);\n inputWords3 = swapWord(inputInt32[offset + 3]);\n\n s0 = inputWords0 ^ invKeySchedule[0];\n s1 = inputWords3 ^ invKeySchedule[1];\n s2 = inputWords2 ^ invKeySchedule[2];\n s3 = inputWords1 ^ invKeySchedule[3];\n\n ksRow = 4;\n\n // Iterate through the rounds of decryption\n for (i = 1; i < nRounds; i++) {\n t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[(s1 >> 16) & 0xff] ^ invSubMix2[(s2 >> 8) & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];\n t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[(s2 >> 16) & 0xff] ^ invSubMix2[(s3 >> 8) & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];\n t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[(s3 >> 16) & 0xff] ^ invSubMix2[(s0 >> 8) & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];\n t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[(s0 >> 16) & 0xff] ^ invSubMix2[(s1 >> 8) & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];\n // Update state\n s0 = t0;\n s1 = t1;\n s2 = t2;\n s3 = t3;\n\n ksRow = ksRow + 4;\n }\n\n // Shift rows, sub bytes, add round key\n t0 = ((invSBOX[s0 >>> 24] << 24) ^ (invSBOX[(s1 >> 16) & 0xff] << 16) ^ (invSBOX[(s2 >> 8) & 0xff] << 8) ^ invSBOX[s3 & 0xff]) ^ invKeySchedule[ksRow];\n t1 = ((invSBOX[s1 >>> 24] << 24) ^ (invSBOX[(s2 >> 16) & 0xff] << 16) ^ (invSBOX[(s3 >> 8) & 0xff] << 8) ^ invSBOX[s0 & 0xff]) ^ invKeySchedule[ksRow + 1];\n t2 = ((invSBOX[s2 >>> 24] << 24) ^ (invSBOX[(s3 >> 16) & 0xff] << 16) ^ (invSBOX[(s0 >> 8) & 0xff] << 8) ^ invSBOX[s1 & 0xff]) ^ invKeySchedule[ksRow + 2];\n t3 = ((invSBOX[s3 >>> 24] << 24) ^ (invSBOX[(s0 >> 16) & 0xff] << 16) ^ (invSBOX[(s1 >> 8) & 0xff] << 8) ^ invSBOX[s2 & 0xff]) ^ invKeySchedule[ksRow + 3];\n ksRow = ksRow + 3;\n\n // Write\n outputInt32[offset] = swapWord(t0 ^ initVector0);\n outputInt32[offset + 1] = swapWord(t3 ^ initVector1);\n outputInt32[offset + 2] = swapWord(t2 ^ initVector2);\n outputInt32[offset + 3] = swapWord(t1 ^ initVector3);\n\n // reset initVector to last 4 unsigned int\n initVector0 = inputWords0;\n initVector1 = inputWords1;\n initVector2 = inputWords2;\n initVector3 = inputWords3;\n\n offset = offset + 4;\n }\n\n return removePKCS7Padding ? removePadding(outputInt32.buffer) : outputInt32.buffer;\n }\n\n destroy () {\n this.key = undefined;\n this.keySize = undefined;\n this.ksRows = undefined;\n\n this.sBox = undefined;\n this.invSBox = undefined;\n this.subMix = undefined;\n this.invSubMix = undefined;\n this.keySchedule = undefined;\n this.invKeySchedule = undefined;\n\n this.rcon = undefined;\n }\n}\n\nexport default AESDecryptor;\n","/**\n * AAC demuxer\n */\nimport * as ADTS from './adts';\nimport { logger } from '../utils/logger';\nimport ID3 from '../demux/id3';\n\nclass AACDemuxer {\n constructor (observer, remuxer, config) {\n this.observer = observer;\n this.config = config;\n this.remuxer = remuxer;\n }\n\n resetInitSegment (initSegment, audioCodec, videoCodec, duration) {\n this._audioTrack = { container: 'audio/adts', type: 'audio', id: 0, sequenceNumber: 0, isAAC: true, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };\n }\n\n resetTimeStamp () {\n }\n\n static probe (data) {\n if (!data) {\n return false;\n }\n\n // Check for the ADTS sync word\n // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n // More info https://wiki.multimedia.cx/index.php?title=ADTS\n const id3Data = ID3.getID3Data(data, 0) || [];\n let offset = id3Data.length;\n\n for (let length = data.length; offset < length; offset++) {\n if (ADTS.probe(data, offset)) {\n logger.log('ADTS sync word found !');\n return true;\n }\n }\n return false;\n }\n\n // feed incoming data to the front of the parsing pipeline\n append (data, timeOffset, contiguous, accurateTimeOffset) {\n let track = this._audioTrack;\n let id3Data = ID3.getID3Data(data, 0) || [];\n let timestamp = ID3.getTimeStamp(id3Data);\n let pts = Number.isFinite(timestamp) ? timestamp * 90 : timeOffset * 90000;\n let frameIndex = 0;\n let stamp = pts;\n let length = data.length;\n let offset = id3Data.length;\n\n let id3Samples = [{ pts: stamp, dts: stamp, data: id3Data }];\n\n while (offset < length - 1) {\n if (ADTS.isHeader(data, offset) && (offset + 5) < length) {\n ADTS.initTrackConfig(track, this.observer, data, offset, track.manifestCodec);\n let frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n stamp = frame.sample.pts;\n frameIndex++;\n } else {\n logger.log('Unable to parse AAC frame');\n break;\n }\n } else if (ID3.isHeader(data, offset)) {\n id3Data = ID3.getID3Data(data, offset);\n id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });\n offset += id3Data.length;\n } else {\n // nothing found, keep looking\n offset++;\n }\n }\n\n this.remuxer.remux(track,\n { samples: [] },\n { samples: id3Samples, inputTimeScale: 90000 },\n { samples: [] },\n timeOffset,\n contiguous,\n accurateTimeOffset);\n }\n\n destroy () {\n }\n}\n\nexport default AACDemuxer;\n","/**\n * highly optimized TS demuxer:\n * parse PAT, PMT\n * extract PES packet from audio and video PIDs\n * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet\n * trigger the remuxer upon parsing completion\n * it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.\n * it also controls the remuxing process :\n * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.\n*/\n\nimport * as ADTS from './adts';\nimport MpegAudio from './mpegaudio';\nimport Event from '../events';\nimport ExpGolomb from './exp-golomb';\nimport SampleAesDecrypter from './sample-aes';\n// import Hex from '../utils/hex';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\n// We are using fixed track IDs for driving the MP4 remuxer\n// instead of following the TS PIDs.\n// There is no reason not to do this and some browsers/SourceBuffer-demuxers\n// may not like if there are TrackID \"switches\"\n// See https://github.com/video-dev/hls.js/issues/1331\n// Here we are mapping our internal track types to constant MP4 track IDs\n// With MSE currently one can only have one track of each, and we are muxing\n// whatever video/audio rendition in them.\nconst RemuxerTrackIdConfig = {\n video: 1,\n audio: 2,\n id3: 3,\n text: 4\n};\n\nclass TSDemuxer {\n constructor (observer, remuxer, config, typeSupported) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n this.remuxer = remuxer;\n this.sampleAes = null;\n }\n\n setDecryptData (decryptdata) {\n if ((decryptdata != null) && (decryptdata.key != null) && (decryptdata.method === 'SAMPLE-AES')) {\n this.sampleAes = new SampleAesDecrypter(this.observer, this.config, decryptdata, this.discardEPB);\n } else {\n this.sampleAes = null;\n }\n }\n\n static probe (data) {\n const syncOffset = TSDemuxer._syncOffset(data);\n if (syncOffset < 0) {\n return false;\n } else {\n if (syncOffset) {\n logger.warn(`MPEG2-TS detected but first sync word found @ offset ${syncOffset}, junk ahead ?`);\n }\n\n return true;\n }\n }\n\n static _syncOffset (data) {\n // scan 1000 first bytes\n const scanwindow = Math.min(1000, data.length - 3 * 188);\n let i = 0;\n while (i < scanwindow) {\n // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47\n if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) {\n return i;\n } else {\n i++;\n }\n }\n return -1;\n }\n\n /**\n * Creates a track model internal to demuxer used to drive remuxing input\n *\n * @param {string} type 'audio' | 'video' | 'id3' | 'text'\n * @param {number} duration\n * @return {object} TSDemuxer's internal track model\n */\n static createTrack (type, duration) {\n return {\n container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,\n type,\n id: RemuxerTrackIdConfig[type],\n pid: -1,\n inputTimeScale: 90000,\n sequenceNumber: 0,\n samples: [],\n len: 0,\n dropped: type === 'video' ? 0 : undefined,\n isAAC: type === 'audio' ? true : undefined,\n duration: type === 'audio' ? duration : undefined\n };\n }\n\n /**\n * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)\n * Resets all internal track instances of the demuxer.\n *\n * @override Implements generic demuxing/remuxing interface (see DemuxerInline)\n * @param {object} initSegment\n * @param {string} audioCodec\n * @param {string} videoCodec\n * @param {number} duration (in TS timescale = 90kHz)\n */\n resetInitSegment (initSegment, audioCodec, videoCodec, duration) {\n this.pmtParsed = false;\n this._pmtId = -1;\n\n this._avcTrack = TSDemuxer.createTrack('video', duration);\n this._audioTrack = TSDemuxer.createTrack('audio', duration);\n this._id3Track = TSDemuxer.createTrack('id3', duration);\n this._txtTrack = TSDemuxer.createTrack('text', duration);\n\n // flush any partial content\n this.aacOverFlow = null;\n this.aacLastPTS = null;\n this.avcSample = null;\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this._duration = duration;\n }\n\n /**\n *\n * @override\n */\n resetTimeStamp () {}\n\n // feed incoming data to the front of the parsing pipeline\n append (data, timeOffset, contiguous, accurateTimeOffset) {\n let start, len = data.length, stt, pid, atf, offset, pes,\n unknownPIDs = false;\n this.contiguous = contiguous;\n let pmtParsed = this.pmtParsed,\n avcTrack = this._avcTrack,\n audioTrack = this._audioTrack,\n id3Track = this._id3Track,\n avcId = avcTrack.pid,\n audioId = audioTrack.pid,\n id3Id = id3Track.pid,\n pmtId = this._pmtId,\n avcData = avcTrack.pesData,\n audioData = audioTrack.pesData,\n id3Data = id3Track.pesData,\n parsePAT = this._parsePAT,\n parsePMT = this._parsePMT,\n parsePES = this._parsePES,\n parseAVCPES = this._parseAVCPES.bind(this),\n parseAACPES = this._parseAACPES.bind(this),\n parseMPEGPES = this._parseMPEGPES.bind(this),\n parseID3PES = this._parseID3PES.bind(this);\n\n const syncOffset = TSDemuxer._syncOffset(data);\n\n // don't parse last TS packet if incomplete\n len -= (len + syncOffset) % 188;\n\n // loop through TS packets\n for (start = syncOffset; start < len; start += 188) {\n if (data[start] === 0x47) {\n stt = !!(data[start + 1] & 0x40);\n // pid is a 13-bit field starting at the last bit of TS[1]\n pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];\n atf = (data[start + 3] & 0x30) >> 4;\n // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.\n if (atf > 1) {\n offset = start + 5 + data[start + 4];\n // continue if there is only adaptation field\n if (offset === (start + 188)) {\n continue;\n }\n } else {\n offset = start + 4;\n }\n switch (pid) {\n case avcId:\n if (stt) {\n if (avcData && (pes = parsePES(avcData)) && pes.pts !== undefined) {\n parseAVCPES(pes, false);\n }\n\n avcData = { data: [], size: 0 };\n }\n if (avcData) {\n avcData.data.push(data.subarray(offset, start + 188));\n avcData.size += start + 188 - offset;\n }\n break;\n case audioId:\n if (stt) {\n if (audioData && (pes = parsePES(audioData)) && pes.pts !== undefined) {\n if (audioTrack.isAAC) {\n parseAACPES(pes);\n } else {\n parseMPEGPES(pes);\n }\n }\n audioData = { data: [], size: 0 };\n }\n if (audioData) {\n audioData.data.push(data.subarray(offset, start + 188));\n audioData.size += start + 188 - offset;\n }\n break;\n case id3Id:\n if (stt) {\n if (id3Data && (pes = parsePES(id3Data)) && pes.pts !== undefined) {\n parseID3PES(pes);\n }\n\n id3Data = { data: [], size: 0 };\n }\n if (id3Data) {\n id3Data.data.push(data.subarray(offset, start + 188));\n id3Data.size += start + 188 - offset;\n }\n break;\n case 0:\n if (stt) {\n offset += data[offset] + 1;\n }\n\n pmtId = this._pmtId = parsePAT(data, offset);\n break;\n case pmtId:\n if (stt) {\n offset += data[offset] + 1;\n }\n\n let parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, this.sampleAes != null);\n\n // only update track id if track PID found while parsing PMT\n // this is to avoid resetting the PID to -1 in case\n // track PID transiently disappears from the stream\n // this could happen in case of transient missing audio samples for example\n // NOTE this is only the PID of the track as found in TS,\n // but we are not using this for MP4 track IDs.\n avcId = parsedPIDs.avc;\n if (avcId > 0) {\n avcTrack.pid = avcId;\n }\n\n audioId = parsedPIDs.audio;\n if (audioId > 0) {\n audioTrack.pid = audioId;\n audioTrack.isAAC = parsedPIDs.isAAC;\n }\n id3Id = parsedPIDs.id3;\n if (id3Id > 0) {\n id3Track.pid = id3Id;\n }\n\n if (unknownPIDs && !pmtParsed) {\n logger.log('reparse from beginning');\n unknownPIDs = false;\n // we set it to -188, the += 188 in the for loop will reset start to 0\n start = syncOffset - 188;\n }\n pmtParsed = this.pmtParsed = true;\n break;\n case 17:\n case 0x1fff:\n break;\n default:\n unknownPIDs = true;\n break;\n }\n } else {\n this.observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'TS packet did not start with 0x47' });\n }\n }\n // try to parse last PES packets\n if (avcData && (pes = parsePES(avcData)) && pes.pts !== undefined) {\n parseAVCPES(pes, true);\n avcTrack.pesData = null;\n } else {\n // either avcData null or PES truncated, keep it for next frag parsing\n avcTrack.pesData = avcData;\n }\n\n if (audioData && (pes = parsePES(audioData)) && pes.pts !== undefined) {\n if (audioTrack.isAAC) {\n parseAACPES(pes);\n } else {\n parseMPEGPES(pes);\n }\n\n audioTrack.pesData = null;\n } else {\n if (audioData && audioData.size) {\n logger.log('last AAC PES packet truncated,might overlap between fragments');\n }\n\n // either audioData null or PES truncated, keep it for next frag parsing\n audioTrack.pesData = audioData;\n }\n\n if (id3Data && (pes = parsePES(id3Data)) && pes.pts !== undefined) {\n parseID3PES(pes);\n id3Track.pesData = null;\n } else {\n // either id3Data null or PES truncated, keep it for next frag parsing\n id3Track.pesData = id3Data;\n }\n\n if (this.sampleAes == null) {\n this.remuxer.remux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);\n } else {\n this.decryptAndRemux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);\n }\n }\n\n decryptAndRemux (audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {\n if (audioTrack.samples && audioTrack.isAAC) {\n let localthis = this;\n this.sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {\n localthis.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n });\n } else {\n this.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n }\n }\n\n decryptAndRemuxAvc (audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {\n if (videoTrack.samples) {\n let localthis = this;\n this.sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {\n localthis.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n });\n } else {\n this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n }\n }\n\n destroy () {\n this._initPTS = this._initDTS = undefined;\n this._duration = 0;\n }\n\n _parsePAT (data, offset) {\n // skip the PSI header and parse the first PMT entry\n return (data[offset + 10] & 0x1F) << 8 | data[offset + 11];\n // logger.log('PMT PID:' + this._pmtId);\n }\n\n _parsePMT (data, offset, mpegSupported, isSampleAes) {\n let sectionLength, tableEnd, programInfoLength, pid, result = { audio: -1, avc: -1, id3: -1, isAAC: true };\n sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];\n tableEnd = offset + 3 + sectionLength - 4;\n // to determine where the table is, we have to figure out how\n // long the program info descriptors are\n programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];\n // advance the offset to the first entry in the mapping table\n offset += 12 + programInfoLength;\n while (offset < tableEnd) {\n pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];\n switch (data[offset]) {\n case 0xcf: // SAMPLE-AES AAC\n if (!isSampleAes) {\n logger.log('unkown stream type:' + data[offset]);\n break;\n }\n /* falls through */\n\n // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)\n case 0x0f:\n // logger.log('AAC PID:' + pid);\n if (result.audio === -1) {\n result.audio = pid;\n }\n\n break;\n\n // Packetized metadata (ID3)\n case 0x15:\n // logger.log('ID3 PID:' + pid);\n if (result.id3 === -1) {\n result.id3 = pid;\n }\n\n break;\n\n case 0xdb: // SAMPLE-AES AVC\n if (!isSampleAes) {\n logger.log('unkown stream type:' + data[offset]);\n break;\n }\n /* falls through */\n\n // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)\n case 0x1b:\n // logger.log('AVC PID:' + pid);\n if (result.avc === -1) {\n result.avc = pid;\n }\n\n break;\n\n // ISO/IEC 11172-3 (MPEG-1 audio)\n // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)\n case 0x03:\n case 0x04:\n // logger.log('MPEG PID:' + pid);\n if (!mpegSupported) {\n logger.log('MPEG audio found, not supported in this browser for now');\n } else if (result.audio === -1) {\n result.audio = pid;\n result.isAAC = false;\n }\n break;\n\n case 0x24:\n logger.warn('HEVC stream type found, not supported for now');\n break;\n\n default:\n logger.log('unkown stream type:' + data[offset]);\n break;\n }\n // move to the next table entry\n // skip past the elementary stream descriptors, if present\n offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5;\n }\n return result;\n }\n\n _parsePES (stream) {\n let i = 0, frag, pesFlags, pesPrefix, pesLen, pesHdrLen, pesData, pesPts, pesDts, payloadStartOffset, data = stream.data;\n // safety check\n if (!stream || stream.size === 0) {\n return null;\n }\n\n // we might need up to 19 bytes to read PES header\n // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes\n // usually only one merge is needed (and this is rare ...)\n while (data[0].length < 19 && data.length > 1) {\n let newData = new Uint8Array(data[0].length + data[1].length);\n newData.set(data[0]);\n newData.set(data[1], data[0].length);\n data[0] = newData;\n data.splice(1, 1);\n }\n // retrieve PTS/DTS from first fragment\n frag = data[0];\n pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];\n if (pesPrefix === 1) {\n pesLen = (frag[4] << 8) + frag[5];\n // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated\n // minus 6 : PES header size\n if (pesLen && pesLen > stream.size - 6) {\n return null;\n }\n\n pesFlags = frag[7];\n if (pesFlags & 0xC0) {\n /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html\n as PTS / DTS is 33 bit we cannot use bitwise operator in JS,\n as Bitwise operators treat their operands as a sequence of 32 bits */\n pesPts = (frag[9] & 0x0E) * 536870912 +// 1 << 29\n (frag[10] & 0xFF) * 4194304 +// 1 << 22\n (frag[11] & 0xFE) * 16384 +// 1 << 14\n (frag[12] & 0xFF) * 128 +// 1 << 7\n (frag[13] & 0xFE) / 2;\n // check if greater than 2^32 -1\n if (pesPts > 4294967295) {\n // decrement 2^33\n pesPts -= 8589934592;\n }\n if (pesFlags & 0x40) {\n pesDts = (frag[14] & 0x0E) * 536870912 +// 1 << 29\n (frag[15] & 0xFF) * 4194304 +// 1 << 22\n (frag[16] & 0xFE) * 16384 +// 1 << 14\n (frag[17] & 0xFF) * 128 +// 1 << 7\n (frag[18] & 0xFE) / 2;\n // check if greater than 2^32 -1\n if (pesDts > 4294967295) {\n // decrement 2^33\n pesDts -= 8589934592;\n }\n if (pesPts - pesDts > 60 * 90000) {\n logger.warn(`${Math.round((pesPts - pesDts) / 90000)}s delta between PTS and DTS, align them`);\n pesPts = pesDts;\n }\n } else {\n pesDts = pesPts;\n }\n }\n pesHdrLen = frag[8];\n // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension\n payloadStartOffset = pesHdrLen + 9;\n\n stream.size -= payloadStartOffset;\n // reassemble PES packet\n pesData = new Uint8Array(stream.size);\n for (let j = 0, dataLen = data.length; j < dataLen; j++) {\n frag = data[j];\n let len = frag.byteLength;\n if (payloadStartOffset) {\n if (payloadStartOffset > len) {\n // trim full frag if PES header bigger than frag\n payloadStartOffset -= len;\n continue;\n } else {\n // trim partial frag if PES header smaller than frag\n frag = frag.subarray(payloadStartOffset);\n len -= payloadStartOffset;\n payloadStartOffset = 0;\n }\n }\n pesData.set(frag, i);\n i += len;\n }\n if (pesLen) {\n // payload size : remove PES header + PES extension\n pesLen -= pesHdrLen + 3;\n }\n return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen };\n } else {\n return null;\n }\n }\n\n pushAccesUnit (avcSample, avcTrack) {\n if (avcSample.units.length && avcSample.frame) {\n const samples = avcTrack.samples;\n const nbSamples = samples.length;\n // only push AVC sample if starting with a keyframe is not mandatory OR\n // if keyframe already found in this fragment OR\n // keyframe found in last fragment (track.sps) AND\n // samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous\n if (!this.config.forceKeyFrameOnDiscontinuity ||\n avcSample.key === true ||\n (avcTrack.sps && (nbSamples || this.contiguous))) {\n avcSample.id = nbSamples;\n samples.push(avcSample);\n } else {\n // dropped samples, track it\n avcTrack.dropped++;\n }\n }\n if (avcSample.debug.length) {\n logger.log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);\n }\n }\n\n _parseAVCPES (pes, last) {\n // logger.log('parse new PES');\n let track = this._avcTrack,\n units = this._parseAVCNALu(pes.data),\n debug = false,\n expGolombDecoder,\n avcSample = this.avcSample,\n push,\n spsfound = false,\n i,\n pushAccesUnit = this.pushAccesUnit.bind(this),\n createAVCSample = function (key, pts, dts, debug) {\n return { key: key, pts: pts, dts: dts, units: [], debug: debug };\n };\n // free pes.data to save up some memory\n pes.data = null;\n\n // if new NAL units found and last sample still there, let's push ...\n // this helps parsing streams with missing AUD (only do this if AUD never found)\n if (avcSample && units.length && !track.audFound) {\n pushAccesUnit(avcSample, track);\n avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');\n }\n\n units.forEach(unit => {\n switch (unit.type) {\n // NDR\n case 1:\n push = true;\n if (!avcSample) {\n avcSample = this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');\n }\n\n if (debug) {\n avcSample.debug += 'NDR ';\n }\n\n avcSample.frame = true;\n let data = unit.data;\n // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)\n if (spsfound && data.length > 4) {\n // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR\n let sliceType = new ExpGolomb(data).readSliceType();\n // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice\n // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.\n // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.\n // I slice: A slice that is not an SI slice that is decoded using intra prediction only.\n // if (sliceType === 2 || sliceType === 7) {\n if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {\n avcSample.key = true;\n }\n }\n break;\n // IDR\n case 5:\n push = true;\n // handle PES not starting with AUD\n if (!avcSample) {\n avcSample = this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');\n }\n\n if (debug) {\n avcSample.debug += 'IDR ';\n }\n\n avcSample.key = true;\n avcSample.frame = true;\n break;\n // SEI\n case 6:\n push = true;\n if (debug && avcSample) {\n avcSample.debug += 'SEI ';\n }\n\n expGolombDecoder = new ExpGolomb(this.discardEPB(unit.data));\n\n // skip frameType\n expGolombDecoder.readUByte();\n\n var payloadType = 0;\n var payloadSize = 0;\n var endOfCaptions = false;\n var b = 0;\n\n while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {\n payloadType = 0;\n do {\n b = expGolombDecoder.readUByte();\n payloadType += b;\n } while (b === 0xFF);\n\n // Parse payload size.\n payloadSize = 0;\n do {\n b = expGolombDecoder.readUByte();\n payloadSize += b;\n } while (b === 0xFF);\n\n // TODO: there can be more than one payload in an SEI packet...\n // TODO: need to read type and size in a while loop to get them all\n if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {\n endOfCaptions = true;\n\n let countryCode = expGolombDecoder.readUByte();\n\n if (countryCode === 181) {\n let providerCode = expGolombDecoder.readUShort();\n\n if (providerCode === 49) {\n let userStructure = expGolombDecoder.readUInt();\n\n if (userStructure === 0x47413934) {\n let userDataType = expGolombDecoder.readUByte();\n\n // Raw CEA-608 bytes wrapped in CEA-708 packet\n if (userDataType === 3) {\n let firstByte = expGolombDecoder.readUByte();\n let secondByte = expGolombDecoder.readUByte();\n\n let totalCCs = 31 & firstByte;\n let byteArray = [firstByte, secondByte];\n\n for (i = 0; i < totalCCs; i++) {\n // 3 bytes per CC\n byteArray.push(expGolombDecoder.readUByte());\n byteArray.push(expGolombDecoder.readUByte());\n byteArray.push(expGolombDecoder.readUByte());\n }\n\n this._insertSampleInOrder(this._txtTrack.samples, { type: 3, pts: pes.pts, bytes: byteArray });\n }\n }\n }\n }\n } else if (payloadSize < expGolombDecoder.bytesAvailable) {\n for (i = 0; i < payloadSize; i++) {\n expGolombDecoder.readUByte();\n }\n }\n }\n break;\n // SPS\n case 7:\n push = true;\n spsfound = true;\n if (debug && avcSample) {\n avcSample.debug += 'SPS ';\n }\n\n if (!track.sps) {\n expGolombDecoder = new ExpGolomb(unit.data);\n let config = expGolombDecoder.readSPS();\n track.width = config.width;\n track.height = config.height;\n track.pixelRatio = config.pixelRatio;\n track.sps = [unit.data];\n track.duration = this._duration;\n let codecarray = unit.data.subarray(1, 4);\n let codecstring = 'avc1.';\n for (i = 0; i < 3; i++) {\n let h = codecarray[i].toString(16);\n if (h.length < 2) {\n h = '0' + h;\n }\n\n codecstring += h;\n }\n track.codec = codecstring;\n }\n break;\n // PPS\n case 8:\n push = true;\n if (debug && avcSample) {\n avcSample.debug += 'PPS ';\n }\n\n if (!track.pps) {\n track.pps = [unit.data];\n }\n\n break;\n // AUD\n case 9:\n push = false;\n track.audFound = true;\n if (avcSample) {\n pushAccesUnit(avcSample, track);\n }\n\n avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : '');\n break;\n // Filler Data\n case 12:\n push = false;\n break;\n default:\n push = false;\n if (avcSample) {\n avcSample.debug += 'unknown NAL ' + unit.type + ' ';\n }\n\n break;\n }\n if (avcSample && push) {\n let units = avcSample.units;\n units.push(unit);\n }\n });\n // if last PES packet, push samples\n if (last && avcSample) {\n pushAccesUnit(avcSample, track);\n this.avcSample = null;\n }\n }\n\n _insertSampleInOrder (arr, data) {\n let len = arr.length;\n if (len > 0) {\n if (data.pts >= arr[len - 1].pts) {\n arr.push(data);\n } else {\n for (let pos = len - 1; pos >= 0; pos--) {\n if (data.pts < arr[pos].pts) {\n arr.splice(pos, 0, data);\n break;\n }\n }\n }\n } else {\n arr.push(data);\n }\n }\n\n _getLastNalUnit () {\n let avcSample = this.avcSample, lastUnit;\n // try to fallback to previous sample if current one is empty\n if (!avcSample || avcSample.units.length === 0) {\n let track = this._avcTrack, samples = track.samples;\n avcSample = samples[samples.length - 1];\n }\n if (avcSample) {\n let units = avcSample.units;\n lastUnit = units[units.length - 1];\n }\n return lastUnit;\n }\n\n _parseAVCNALu (array) {\n let i = 0, len = array.byteLength, value, overflow, track = this._avcTrack, state = track.naluState || 0, lastState = state;\n let units = [], unit, unitType, lastUnitStart = -1, lastUnitType;\n // logger.log('PES:' + Hex.hexDump(array));\n\n if (state === -1) {\n // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet\n lastUnitStart = 0;\n // NALu type is value read from offset 0\n lastUnitType = array[0] & 0x1f;\n state = 0;\n i = 1;\n }\n\n while (i < len) {\n value = array[i++];\n // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case\n if (!state) {\n state = value ? 0 : 1;\n continue;\n }\n if (state === 1) {\n state = value ? 0 : 2;\n continue;\n }\n // here we have state either equal to 2 or 3\n if (!value) {\n state = 3;\n } else if (value === 1) {\n if (lastUnitStart >= 0) {\n unit = { data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType };\n // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);\n units.push(unit);\n } else {\n // lastUnitStart is undefined => this is the first start code found in this PES packet\n // first check if start code delimiter is overlapping between 2 PES packets,\n // ie it started in last packet (lastState not zero)\n // and ended at the beginning of this PES packet (i <= 4 - lastState)\n let lastUnit = this._getLastNalUnit();\n if (lastUnit) {\n if (lastState && (i <= 4 - lastState)) {\n // start delimiter overlapping between PES packets\n // strip start delimiter bytes from the end of last NAL unit\n // check if lastUnit had a state different from zero\n if (lastUnit.state) {\n // strip last bytes\n lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);\n }\n }\n // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.\n overflow = i - state - 1;\n if (overflow > 0) {\n // logger.log('first NALU found with overflow:' + overflow);\n let tmp = new Uint8Array(lastUnit.data.byteLength + overflow);\n tmp.set(lastUnit.data, 0);\n tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);\n lastUnit.data = tmp;\n }\n }\n }\n // check if we can read unit type\n if (i < len) {\n unitType = array[i] & 0x1f;\n // logger.log('find NALU @ offset:' + i + ',type:' + unitType);\n lastUnitStart = i;\n lastUnitType = unitType;\n state = 0;\n } else {\n // not enough byte to read unit type. let's read it on next PES parsing\n state = -1;\n }\n } else {\n state = 0;\n }\n }\n if (lastUnitStart >= 0 && state >= 0) {\n unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType, state: state };\n units.push(unit);\n // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);\n }\n // no NALu found\n if (units.length === 0) {\n // append pes.data to previous NAL unit\n let lastUnit = this._getLastNalUnit();\n if (lastUnit) {\n let tmp = new Uint8Array(lastUnit.data.byteLength + array.byteLength);\n tmp.set(lastUnit.data, 0);\n tmp.set(array, lastUnit.data.byteLength);\n lastUnit.data = tmp;\n }\n }\n track.naluState = state;\n return units;\n }\n\n /**\n * remove Emulation Prevention bytes from a RBSP\n */\n discardEPB (data) {\n let length = data.byteLength,\n EPBPositions = [],\n i = 1,\n newLength, newData;\n\n // Find all `Emulation Prevention Bytes`\n while (i < length - 2) {\n if (data[i] === 0 &&\n data[i + 1] === 0 &&\n data[i + 2] === 0x03) {\n EPBPositions.push(i + 2);\n i += 2;\n } else {\n i++;\n }\n }\n\n // If no Emulation Prevention Bytes were found just return the original\n // array\n if (EPBPositions.length === 0) {\n return data;\n }\n\n // Create a new array to hold the NAL unit data\n newLength = length - EPBPositions.length;\n newData = new Uint8Array(newLength);\n let sourceIndex = 0;\n\n for (i = 0; i < newLength; sourceIndex++, i++) {\n if (sourceIndex === EPBPositions[0]) {\n // Skip this byte\n sourceIndex++;\n // Remove this position index\n EPBPositions.shift();\n }\n newData[i] = data[sourceIndex];\n }\n return newData;\n }\n\n _parseAACPES (pes) {\n let track = this._audioTrack,\n data = pes.data,\n pts = pes.pts,\n startOffset = 0,\n aacOverFlow = this.aacOverFlow,\n aacLastPTS = this.aacLastPTS,\n frameDuration, frameIndex, offset, stamp, len;\n if (aacOverFlow) {\n let tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);\n tmp.set(aacOverFlow, 0);\n tmp.set(data, aacOverFlow.byteLength);\n // logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);\n data = tmp;\n }\n // look for ADTS header (0xFFFx)\n for (offset = startOffset, len = data.length; offset < len - 1; offset++) {\n if (ADTS.isHeader(data, offset)) {\n break;\n }\n }\n // if ADTS header does not start straight from the beginning of the PES payload, raise an error\n if (offset) {\n let reason, fatal;\n if (offset < len - 1) {\n reason = `AAC PES did not start with ADTS header,offset:${offset}`;\n fatal = false;\n } else {\n reason = 'no ADTS header found in AAC PES';\n fatal = true;\n }\n logger.warn(`parsing error:${reason}`);\n this.observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: fatal, reason: reason });\n if (fatal) {\n return;\n }\n }\n\n ADTS.initTrackConfig(track, this.observer, data, offset, this.audioCodec);\n frameIndex = 0;\n frameDuration = ADTS.getFrameDuration(track.samplerate);\n\n // if last AAC frame is overflowing, we should ensure timestamps are contiguous:\n // first sample PTS should be equal to last sample PTS + frameDuration\n if (aacOverFlow && aacLastPTS) {\n let newPTS = aacLastPTS + frameDuration;\n if (Math.abs(newPTS - pts) > 1) {\n logger.log(`AAC: align PTS for overlapping frames by ${Math.round((newPTS - pts) / 90)}`);\n pts = newPTS;\n }\n }\n\n // scan for aac samples\n while (offset < len) {\n if (ADTS.isHeader(data, offset) && (offset + 5) < len) {\n let frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);\n if (frame) {\n // logger.log(`${Math.round(frame.sample.pts)} : AAC`);\n offset += frame.length;\n stamp = frame.sample.pts;\n frameIndex++;\n } else {\n // logger.log('Unable to parse AAC frame');\n break;\n }\n } else {\n // nothing found, keep looking\n offset++;\n }\n }\n\n if (offset < len) {\n aacOverFlow = data.subarray(offset, len);\n // logger.log(`AAC: overflow detected:${len-offset}`);\n } else {\n aacOverFlow = null;\n }\n\n this.aacOverFlow = aacOverFlow;\n this.aacLastPTS = stamp;\n }\n\n _parseMPEGPES (pes) {\n let data = pes.data;\n let length = data.length;\n let frameIndex = 0;\n let offset = 0;\n let pts = pes.pts;\n\n while (offset < length) {\n if (MpegAudio.isHeader(data, offset)) {\n let frame = MpegAudio.appendFrame(this._audioTrack, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n frameIndex++;\n } else {\n // logger.log('Unable to parse Mpeg audio frame');\n break;\n }\n } else {\n // nothing found, keep looking\n offset++;\n }\n }\n }\n\n _parseID3PES (pes) {\n this._id3Track.samples.push(pes);\n }\n}\n\nexport default TSDemuxer;\n","/**\n * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.\n*/\n\nimport { logger } from '../utils/logger';\n\nclass ExpGolomb {\n constructor (data) {\n this.data = data;\n // the number of bytes left to examine in this.data\n this.bytesAvailable = data.byteLength;\n // the current word being examined\n this.word = 0; // :uint\n // the number of bits left to examine in the current word\n this.bitsAvailable = 0; // :uint\n }\n\n // ():void\n loadWord () {\n let\n data = this.data,\n bytesAvailable = this.bytesAvailable,\n position = data.byteLength - bytesAvailable,\n workingBytes = new Uint8Array(4),\n availableBytes = Math.min(4, bytesAvailable);\n if (availableBytes === 0) {\n throw new Error('no bytes available');\n }\n\n workingBytes.set(data.subarray(position, position + availableBytes));\n this.word = new DataView(workingBytes.buffer).getUint32(0);\n // track the amount of this.data that has been processed\n this.bitsAvailable = availableBytes * 8;\n this.bytesAvailable -= availableBytes;\n }\n\n // (count:int):void\n skipBits (count) {\n let skipBytes; // :int\n if (this.bitsAvailable > count) {\n this.word <<= count;\n this.bitsAvailable -= count;\n } else {\n count -= this.bitsAvailable;\n skipBytes = count >> 3;\n count -= (skipBytes >> 3);\n this.bytesAvailable -= skipBytes;\n this.loadWord();\n this.word <<= count;\n this.bitsAvailable -= count;\n }\n }\n\n // (size:int):uint\n readBits (size) {\n let\n bits = Math.min(this.bitsAvailable, size), // :uint\n valu = this.word >>> (32 - bits); // :uint\n if (size > 32) {\n logger.error('Cannot read more than 32 bits at a time');\n }\n\n this.bitsAvailable -= bits;\n if (this.bitsAvailable > 0) {\n this.word <<= bits;\n } else if (this.bytesAvailable > 0) {\n this.loadWord();\n }\n\n bits = size - bits;\n if (bits > 0 && this.bitsAvailable) {\n return valu << bits | this.readBits(bits);\n } else {\n return valu;\n }\n }\n\n // ():uint\n skipLZ () {\n let leadingZeroCount; // :uint\n for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {\n if ((this.word & (0x80000000 >>> leadingZeroCount)) !== 0) {\n // the first bit of working word is 1\n this.word <<= leadingZeroCount;\n this.bitsAvailable -= leadingZeroCount;\n return leadingZeroCount;\n }\n }\n // we exhausted word and still have not found a 1\n this.loadWord();\n return leadingZeroCount + this.skipLZ();\n }\n\n // ():void\n skipUEG () {\n this.skipBits(1 + this.skipLZ());\n }\n\n // ():void\n skipEG () {\n this.skipBits(1 + this.skipLZ());\n }\n\n // ():uint\n readUEG () {\n let clz = this.skipLZ(); // :uint\n return this.readBits(clz + 1) - 1;\n }\n\n // ():int\n readEG () {\n let valu = this.readUEG(); // :int\n if (0x01 & valu) {\n // the number is odd if the low order bit is set\n return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2\n } else {\n return -1 * (valu >>> 1); // divide by two then make it negative\n }\n }\n\n // Some convenience functions\n // :Boolean\n readBoolean () {\n return this.readBits(1) === 1;\n }\n\n // ():int\n readUByte () {\n return this.readBits(8);\n }\n\n // ():int\n readUShort () {\n return this.readBits(16);\n }\n // ():int\n readUInt () {\n return this.readBits(32);\n }\n\n /**\n * Advance the ExpGolomb decoder past a scaling list. The scaling\n * list is optionally transmitted as part of a sequence parameter\n * set and is not relevant to transmuxing.\n * @param count {number} the number of entries in this scaling list\n * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1\n */\n skipScalingList (count) {\n let\n lastScale = 8,\n nextScale = 8,\n j,\n deltaScale;\n for (j = 0; j < count; j++) {\n if (nextScale !== 0) {\n deltaScale = this.readEG();\n nextScale = (lastScale + deltaScale + 256) % 256;\n }\n lastScale = (nextScale === 0) ? lastScale : nextScale;\n }\n }\n\n /**\n * Read a sequence parameter set and return some interesting video\n * properties. A sequence parameter set is the H264 metadata that\n * describes the properties of upcoming video frames.\n * @param data {Uint8Array} the bytes of a sequence parameter set\n * @return {object} an object with configuration parsed from the\n * sequence parameter set, including the dimensions of the\n * associated video frames.\n */\n readSPS () {\n let\n frameCropLeftOffset = 0,\n frameCropRightOffset = 0,\n frameCropTopOffset = 0,\n frameCropBottomOffset = 0,\n profileIdc, profileCompat, levelIdc,\n numRefFramesInPicOrderCntCycle, picWidthInMbsMinus1,\n picHeightInMapUnitsMinus1,\n frameMbsOnlyFlag,\n scalingListCount,\n i,\n readUByte = this.readUByte.bind(this),\n readBits = this.readBits.bind(this),\n readUEG = this.readUEG.bind(this),\n readBoolean = this.readBoolean.bind(this),\n skipBits = this.skipBits.bind(this),\n skipEG = this.skipEG.bind(this),\n skipUEG = this.skipUEG.bind(this),\n skipScalingList = this.skipScalingList.bind(this);\n\n readUByte();\n profileIdc = readUByte(); // profile_idc\n profileCompat = readBits(5); // constraint_set[0-4]_flag, u(5)\n skipBits(3); // reserved_zero_3bits u(3),\n levelIdc = readUByte(); // level_idc u(8)\n skipUEG(); // seq_parameter_set_id\n // some profiles have more optional data we don't need\n if (profileIdc === 100 ||\n profileIdc === 110 ||\n profileIdc === 122 ||\n profileIdc === 244 ||\n profileIdc === 44 ||\n profileIdc === 83 ||\n profileIdc === 86 ||\n profileIdc === 118 ||\n profileIdc === 128) {\n let chromaFormatIdc = readUEG();\n if (chromaFormatIdc === 3) {\n skipBits(1);\n } // separate_colour_plane_flag\n\n skipUEG(); // bit_depth_luma_minus8\n skipUEG(); // bit_depth_chroma_minus8\n skipBits(1); // qpprime_y_zero_transform_bypass_flag\n if (readBoolean()) { // seq_scaling_matrix_present_flag\n scalingListCount = (chromaFormatIdc !== 3) ? 8 : 12;\n for (i = 0; i < scalingListCount; i++) {\n if (readBoolean()) { // seq_scaling_list_present_flag[ i ]\n if (i < 6) {\n skipScalingList(16);\n } else {\n skipScalingList(64);\n }\n }\n }\n }\n }\n skipUEG(); // log2_max_frame_num_minus4\n let picOrderCntType = readUEG();\n if (picOrderCntType === 0) {\n readUEG(); // log2_max_pic_order_cnt_lsb_minus4\n } else if (picOrderCntType === 1) {\n skipBits(1); // delta_pic_order_always_zero_flag\n skipEG(); // offset_for_non_ref_pic\n skipEG(); // offset_for_top_to_bottom_field\n numRefFramesInPicOrderCntCycle = readUEG();\n for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {\n skipEG();\n } // offset_for_ref_frame[ i ]\n }\n skipUEG(); // max_num_ref_frames\n skipBits(1); // gaps_in_frame_num_value_allowed_flag\n picWidthInMbsMinus1 = readUEG();\n picHeightInMapUnitsMinus1 = readUEG();\n frameMbsOnlyFlag = readBits(1);\n if (frameMbsOnlyFlag === 0) {\n skipBits(1);\n } // mb_adaptive_frame_field_flag\n\n skipBits(1); // direct_8x8_inference_flag\n if (readBoolean()) { // frame_cropping_flag\n frameCropLeftOffset = readUEG();\n frameCropRightOffset = readUEG();\n frameCropTopOffset = readUEG();\n frameCropBottomOffset = readUEG();\n }\n let pixelRatio = [1, 1];\n if (readBoolean()) {\n // vui_parameters_present_flag\n if (readBoolean()) {\n // aspect_ratio_info_present_flag\n const aspectRatioIdc = readUByte();\n switch (aspectRatioIdc) {\n case 1: pixelRatio = [1, 1]; break;\n case 2: pixelRatio = [12, 11]; break;\n case 3: pixelRatio = [10, 11]; break;\n case 4: pixelRatio = [16, 11]; break;\n case 5: pixelRatio = [40, 33]; break;\n case 6: pixelRatio = [24, 11]; break;\n case 7: pixelRatio = [20, 11]; break;\n case 8: pixelRatio = [32, 11]; break;\n case 9: pixelRatio = [80, 33]; break;\n case 10: pixelRatio = [18, 11]; break;\n case 11: pixelRatio = [15, 11]; break;\n case 12: pixelRatio = [64, 33]; break;\n case 13: pixelRatio = [160, 99]; break;\n case 14: pixelRatio = [4, 3]; break;\n case 15: pixelRatio = [3, 2]; break;\n case 16: pixelRatio = [2, 1]; break;\n case 255: {\n pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];\n break;\n }\n }\n }\n }\n return {\n width: Math.ceil((((picWidthInMbsMinus1 + 1) * 16) - frameCropLeftOffset * 2 - frameCropRightOffset * 2)),\n height: ((2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16) - ((frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset)),\n pixelRatio: pixelRatio\n };\n }\n\n readSliceType () {\n // skip NALu type\n this.readUByte();\n // discard first_mb_in_slice\n this.readUEG();\n // return slice_type\n return this.readUEG();\n }\n}\n\nexport default ExpGolomb;\n","/**\n * SAMPLE-AES decrypter\n*/\n\nimport Decrypter from '../crypt/decrypter';\n\nclass SampleAesDecrypter {\n constructor (observer, config, decryptdata, discardEPB) {\n this.decryptdata = decryptdata;\n this.discardEPB = discardEPB;\n this.decrypter = new Decrypter(observer, config, { removePKCS7Padding: false });\n }\n\n decryptBuffer (encryptedData, callback) {\n this.decrypter.decrypt(encryptedData, this.decryptdata.key.buffer, this.decryptdata.iv.buffer, callback);\n }\n\n // AAC - encrypt all full 16 bytes blocks starting from offset 16\n decryptAacSample (samples, sampleIndex, callback, sync) {\n let curUnit = samples[sampleIndex].unit;\n let encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);\n let encryptedBuffer = encryptedData.buffer.slice(\n encryptedData.byteOffset,\n encryptedData.byteOffset + encryptedData.length);\n\n let localthis = this;\n this.decryptBuffer(encryptedBuffer, function (decryptedData) {\n decryptedData = new Uint8Array(decryptedData);\n curUnit.set(decryptedData, 16);\n\n if (!sync) {\n localthis.decryptAacSamples(samples, sampleIndex + 1, callback);\n }\n });\n }\n\n decryptAacSamples (samples, sampleIndex, callback) {\n for (;; sampleIndex++) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n if (samples[sampleIndex].unit.length < 32) {\n continue;\n }\n\n let sync = this.decrypter.isSync();\n\n this.decryptAacSample(samples, sampleIndex, callback, sync);\n\n if (!sync) {\n return;\n }\n }\n }\n\n // AVC - encrypt one 16 bytes block out of ten, starting from offset 32\n getAvcEncryptedData (decodedData) {\n let encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;\n let encryptedData = new Int8Array(encryptedDataLen);\n let outputPos = 0;\n for (let inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {\n encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);\n }\n\n return encryptedData;\n }\n\n getAvcDecryptedUnit (decodedData, decryptedData) {\n decryptedData = new Uint8Array(decryptedData);\n let inputPos = 0;\n for (let outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {\n decodedData.set(decryptedData.subarray(inputPos, inputPos + 16), outputPos);\n }\n\n return decodedData;\n }\n\n decryptAvcSample (samples, sampleIndex, unitIndex, callback, curUnit, sync) {\n let decodedData = this.discardEPB(curUnit.data);\n let encryptedData = this.getAvcEncryptedData(decodedData);\n let localthis = this;\n\n this.decryptBuffer(encryptedData.buffer, function (decryptedData) {\n curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedData);\n\n if (!sync) {\n localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);\n }\n });\n }\n\n decryptAvcSamples (samples, sampleIndex, unitIndex, callback) {\n for (;; sampleIndex++, unitIndex = 0) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n let curUnits = samples[sampleIndex].units;\n for (;; unitIndex++) {\n if (unitIndex >= curUnits.length) {\n break;\n }\n\n let curUnit = curUnits[unitIndex];\n if (curUnit.length <= 48 || (curUnit.type !== 1 && curUnit.type !== 5)) {\n continue;\n }\n\n let sync = this.decrypter.isSync();\n\n this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);\n\n if (!sync) {\n return;\n }\n }\n }\n }\n}\n\nexport default SampleAesDecrypter;\n","/**\n * MP3 demuxer\n */\nimport ID3 from '../demux/id3';\nimport { logger } from '../utils/logger';\nimport MpegAudio from './mpegaudio';\n\nclass MP3Demuxer {\n constructor (observer, remuxer, config) {\n this.observer = observer;\n this.config = config;\n this.remuxer = remuxer;\n }\n\n resetInitSegment (initSegment, audioCodec, videoCodec, duration) {\n this._audioTrack = { container: 'audio/mpeg', type: 'audio', id: -1, sequenceNumber: 0, isAAC: false, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };\n }\n\n resetTimeStamp () {\n }\n\n static probe (data) {\n // check if data contains ID3 timestamp and MPEG sync word\n let offset, length;\n let id3Data = ID3.getID3Data(data, 0);\n if (id3Data && ID3.getTimeStamp(id3Data) !== undefined) {\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n for (offset = id3Data.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) {\n if (MpegAudio.probe(data, offset)) {\n logger.log('MPEG Audio sync word found !');\n return true;\n }\n }\n }\n return false;\n }\n\n // feed incoming data to the front of the parsing pipeline\n append (data, timeOffset, contiguous, accurateTimeOffset) {\n let id3Data = ID3.getID3Data(data, 0);\n let timestamp = ID3.getTimeStamp(id3Data);\n let pts = timestamp ? 90 * timestamp : timeOffset * 90000;\n let offset = id3Data.length;\n let length = data.length;\n let frameIndex = 0, stamp = 0;\n let track = this._audioTrack;\n\n let id3Samples = [{ pts: pts, dts: pts, data: id3Data }];\n\n while (offset < length) {\n if (MpegAudio.isHeader(data, offset)) {\n let frame = MpegAudio.appendFrame(track, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n stamp = frame.sample.pts;\n frameIndex++;\n } else {\n // logger.log('Unable to parse Mpeg audio frame');\n break;\n }\n } else if (ID3.isHeader(data, offset)) {\n id3Data = ID3.getID3Data(data, offset);\n id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });\n offset += id3Data.length;\n } else {\n // nothing found, keep looking\n offset++;\n }\n }\n\n this.remuxer.remux(track,\n { samples: [] },\n { samples: id3Samples, inputTimeScale: 90000 },\n { samples: [] },\n timeOffset,\n contiguous,\n accurateTimeOffset);\n }\n\n destroy () {\n }\n}\n\nexport default MP3Demuxer;\n","/**\n * fMP4 remuxer\n*/\n\nimport AAC from './aac-helper';\nimport MP4 from './mp4-generator';\n\nimport Event from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport { logger } from '../utils/logger';\n\n// 10 seconds\nconst MAX_SILENT_FRAME_DURATION = 10 * 1000;\n\nclass MP4Remuxer {\n constructor (observer, config, typeSupported, vendor) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n const userAgent = navigator.userAgent;\n this.isSafari = vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS');\n this.ISGenerated = false;\n }\n\n destroy () {\n }\n\n resetTimeStamp (defaultTimeStamp) {\n this._initPTS = this._initDTS = defaultTimeStamp;\n }\n\n resetInitSegment () {\n this.ISGenerated = false;\n }\n\n remux (audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {\n // generate Init Segment if needed\n if (!this.ISGenerated) {\n this.generateIS(audioTrack, videoTrack, timeOffset);\n }\n\n if (this.ISGenerated) {\n const nbAudioSamples = audioTrack.samples.length;\n const nbVideoSamples = videoTrack.samples.length;\n let audioTimeOffset = timeOffset;\n let videoTimeOffset = timeOffset;\n if (nbAudioSamples && nbVideoSamples) {\n // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)\n // if first audio DTS is not aligned with first video DTS then we need to take that into account\n // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small\n // drift between audio and video streams\n let audiovideoDeltaDts = (audioTrack.samples[0].pts - videoTrack.samples[0].pts) / videoTrack.inputTimeScale;\n audioTimeOffset += Math.max(0, audiovideoDeltaDts);\n videoTimeOffset += Math.max(0, -audiovideoDeltaDts);\n }\n // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is\n // calculated in remuxAudio.\n // logger.log('nb AAC samples:' + audioTrack.samples.length);\n if (nbAudioSamples) {\n // if initSegment was generated without video samples, regenerate it again\n if (!audioTrack.timescale) {\n logger.warn('regenerate InitSegment as audio detected');\n this.generateIS(audioTrack, videoTrack, timeOffset);\n }\n let audioData = this.remuxAudio(audioTrack, audioTimeOffset, contiguous, accurateTimeOffset);\n // logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (nbVideoSamples) {\n let audioTrackLength;\n if (audioData) {\n audioTrackLength = audioData.endPTS - audioData.startPTS;\n }\n\n // if initSegment was generated without video samples, regenerate it again\n if (!videoTrack.timescale) {\n logger.warn('regenerate InitSegment as video detected');\n this.generateIS(audioTrack, videoTrack, timeOffset);\n }\n this.remuxVideo(videoTrack, videoTimeOffset, contiguous, audioTrackLength, accurateTimeOffset);\n }\n } else {\n // logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (nbVideoSamples) {\n let videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0, accurateTimeOffset);\n if (videoData && audioTrack.codec) {\n this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData);\n }\n }\n }\n }\n // logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (id3Track.samples.length) {\n this.remuxID3(id3Track, timeOffset);\n }\n\n // logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (textTrack.samples.length) {\n this.remuxText(textTrack, timeOffset);\n }\n\n // notify end of parsing\n this.observer.trigger(Event.FRAG_PARSED);\n }\n\n generateIS (audioTrack, videoTrack, timeOffset) {\n let observer = this.observer,\n audioSamples = audioTrack.samples,\n videoSamples = videoTrack.samples,\n typeSupported = this.typeSupported,\n container = 'audio/mp4',\n tracks = {},\n data = { tracks: tracks },\n computePTSDTS = (this._initPTS === undefined),\n initPTS, initDTS;\n\n if (computePTSDTS) {\n initPTS = initDTS = Infinity;\n }\n\n if (audioTrack.config && audioSamples.length) {\n // let's use audio sampling rate as MP4 time scale.\n // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)\n // using audio sampling rate here helps having an integer MP4 frame duration\n // this avoids potential rounding issue and AV sync issue\n audioTrack.timescale = audioTrack.samplerate;\n logger.log(`audio sampling rate : ${audioTrack.samplerate}`);\n if (!audioTrack.isAAC) {\n if (typeSupported.mpeg) { // Chrome and Safari\n container = 'audio/mpeg';\n audioTrack.codec = '';\n } else if (typeSupported.mp3) { // Firefox\n audioTrack.codec = 'mp3';\n }\n }\n tracks.audio = {\n container: container,\n codec: audioTrack.codec,\n initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array() : MP4.initSegment([audioTrack]),\n metadata: {\n channelCount: audioTrack.channelCount\n }\n };\n if (computePTSDTS) {\n // remember first PTS of this demuxing context. for audio, PTS = DTS\n initPTS = initDTS = audioSamples[0].pts - audioTrack.inputTimeScale * timeOffset;\n }\n }\n\n if (videoTrack.sps && videoTrack.pps && videoSamples.length) {\n // let's use input time scale as MP4 video timescale\n // we use input time scale straight away to avoid rounding issues on frame duration / cts computation\n const inputTimeScale = videoTrack.inputTimeScale;\n videoTrack.timescale = inputTimeScale;\n tracks.video = {\n container: 'video/mp4',\n codec: videoTrack.codec,\n initSegment: MP4.initSegment([videoTrack]),\n metadata: {\n width: videoTrack.width,\n height: videoTrack.height\n }\n };\n if (computePTSDTS) {\n initPTS = Math.min(initPTS, videoSamples[0].pts - inputTimeScale * timeOffset);\n initDTS = Math.min(initDTS, videoSamples[0].dts - inputTimeScale * timeOffset);\n this.observer.trigger(Event.INIT_PTS_FOUND, { initPTS: initPTS });\n }\n }\n\n if (Object.keys(tracks).length) {\n observer.trigger(Event.FRAG_PARSING_INIT_SEGMENT, data);\n this.ISGenerated = true;\n if (computePTSDTS) {\n this._initPTS = initPTS;\n this._initDTS = initDTS;\n }\n } else {\n observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' });\n }\n }\n\n remuxVideo (track, timeOffset, contiguous, audioTrackLength, accurateTimeOffset) {\n let offset = 8;\n let mp4SampleDuration;\n let mdat;\n let moof;\n let firstPTS;\n let firstDTS;\n let lastPTS;\n let lastDTS;\n const timeScale = track.timescale;\n const inputSamples = track.samples;\n const outputSamples = [];\n const nbSamples = inputSamples.length;\n const ptsNormalize = this._PTSNormalize;\n const initPTS = this._initPTS;\n\n // if parsed fragment is contiguous with last one, let's use last DTS value as reference\n let nextAvcDts = this.nextAvcDts;\n\n const isSafari = this.isSafari;\n\n if (nbSamples === 0) {\n return;\n }\n\n // Safari does not like overlapping DTS on consecutive fragments. let's use nextAvcDts to overcome this if fragments are consecutive\n if (isSafari) {\n // also consider consecutive fragments as being contiguous (even if a level switch occurs),\n // for sake of clarity:\n // consecutive fragments are frags with\n // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR\n // - less than 200 ms PTS gaps (timeScale/5)\n contiguous |= (inputSamples.length && nextAvcDts &&\n ((accurateTimeOffset && Math.abs(timeOffset - nextAvcDts / timeScale) < 0.1) ||\n Math.abs((inputSamples[0].pts - nextAvcDts - initPTS)) < timeScale / 5)\n );\n }\n\n if (!contiguous) {\n // if not contiguous, let's use target timeOffset\n nextAvcDts = timeOffset * timeScale;\n }\n\n // PTS is coded on 33bits, and can loop from -2^32 to 2^32\n // ptsNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value\n inputSamples.forEach(function (sample) {\n sample.pts = ptsNormalize(sample.pts - initPTS, nextAvcDts);\n sample.dts = ptsNormalize(sample.dts - initPTS, nextAvcDts);\n });\n\n // sort video samples by DTS then PTS then demux id order\n inputSamples.sort(function (a, b) {\n const deltadts = a.dts - b.dts;\n const deltapts = a.pts - b.pts;\n return deltadts || (deltapts || (a.id - b.id));\n });\n\n // handle broken streams with PTS < DTS, tolerance up 200ms (18000 in 90kHz timescale)\n let PTSDTSshift = inputSamples.reduce((prev, curr) => Math.max(Math.min(prev, curr.pts - curr.dts), -18000), 0);\n if (PTSDTSshift < 0) {\n logger.warn(`PTS < DTS detected in video samples, shifting DTS by ${Math.round(PTSDTSshift / 90)} ms to overcome this issue`);\n for (let i = 0; i < inputSamples.length; i++) {\n inputSamples[i].dts += PTSDTSshift;\n }\n }\n\n // compute first DTS and last DTS, normalize them against reference value\n let sample = inputSamples[0];\n firstDTS = Math.max(sample.dts, 0);\n firstPTS = Math.max(sample.pts, 0);\n\n // check timestamp continuity accross consecutive fragments (this is to remove inter-fragment gap/hole)\n let delta = Math.round((firstDTS - nextAvcDts) / 90);\n // if fragment are contiguous, detect hole/overlapping between fragments\n if (contiguous) {\n if (delta) {\n if (delta > 1) {\n logger.log(`AVC:${delta} ms hole between fragments detected,filling it`);\n } else if (delta < -1) {\n logger.log(`AVC:${(-delta)} ms overlapping between fragments detected`);\n }\n\n // remove hole/gap : set DTS to next expected DTS\n firstDTS = nextAvcDts;\n inputSamples[0].dts = firstDTS;\n // offset PTS as well, ensure that PTS is smaller or equal than new DTS\n firstPTS = Math.max(firstPTS - delta, nextAvcDts);\n inputSamples[0].pts = firstPTS;\n logger.log(`Video/PTS/DTS adjusted: ${Math.round(firstPTS / 90)}/${Math.round(firstDTS / 90)},delta:${delta} ms`);\n }\n }\n\n // compute lastPTS/lastDTS\n sample = inputSamples[inputSamples.length - 1];\n lastDTS = Math.max(sample.dts, 0);\n lastPTS = Math.max(sample.pts, 0, lastDTS);\n\n // on Safari let's signal the same sample duration for all samples\n // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS\n // set this constant duration as being the avg delta between consecutive DTS.\n if (isSafari) {\n mp4SampleDuration = Math.round((lastDTS - firstDTS) / (inputSamples.length - 1));\n }\n\n let nbNalu = 0, naluLen = 0;\n for (let i = 0; i < nbSamples; i++) {\n // compute total/avc sample length and nb of NAL units\n let sample = inputSamples[i], units = sample.units, nbUnits = units.length, sampleLen = 0;\n for (let j = 0; j < nbUnits; j++) {\n sampleLen += units[j].data.length;\n }\n\n naluLen += sampleLen;\n nbNalu += nbUnits;\n sample.length = sampleLen;\n\n // normalize PTS/DTS\n if (isSafari) {\n // sample DTS is computed using a constant decoding offset (mp4SampleDuration) between samples\n sample.dts = firstDTS + i * mp4SampleDuration;\n } else {\n // ensure sample monotonic DTS\n sample.dts = Math.max(sample.dts, firstDTS);\n }\n // ensure that computed value is greater or equal than sample DTS\n sample.pts = Math.max(sample.pts, sample.dts);\n }\n\n /* concatenate the video data and construct the mdat in place\n (need 8 more bytes to fill length and mpdat type) */\n let mdatSize = naluLen + (4 * nbNalu) + 8;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch (err) {\n this.observer.trigger(Event.ERROR, { type: ErrorTypes.MUX_ERROR, details: ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: `fail allocating video mdat ${mdatSize}` });\n return;\n }\n let view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n\n for (let i = 0; i < nbSamples; i++) {\n let avcSample = inputSamples[i],\n avcSampleUnits = avcSample.units,\n mp4SampleLength = 0,\n compositionTimeOffset;\n // convert NALU bitstream to MP4 format (prepend NALU with size field)\n for (let j = 0, nbUnits = avcSampleUnits.length; j < nbUnits; j++) {\n let unit = avcSampleUnits[j],\n unitData = unit.data,\n unitDataLen = unit.data.byteLength;\n view.setUint32(offset, unitDataLen);\n offset += 4;\n mdat.set(unitData, offset);\n offset += unitDataLen;\n mp4SampleLength += 4 + unitDataLen;\n }\n\n if (!isSafari) {\n // expected sample duration is the Decoding Timestamp diff of consecutive samples\n if (i < nbSamples - 1) {\n mp4SampleDuration = inputSamples[i + 1].dts - avcSample.dts;\n } else {\n let config = this.config,\n lastFrameDuration = avcSample.dts - inputSamples[i > 0 ? i - 1 : i].dts;\n if (config.stretchShortVideoTrack) {\n // In some cases, a segment's audio track duration may exceed the video track duration.\n // Since we've already remuxed audio, and we know how long the audio track is, we look to\n // see if the delta to the next segment is longer than maxBufferHole.\n // If so, playback would potentially get stuck, so we artificially inflate\n // the duration of the last frame to minimize any potential gap between segments.\n let maxBufferHole = config.maxBufferHole,\n gapTolerance = Math.floor(maxBufferHole * timeScale),\n deltaToFrameEnd = (audioTrackLength ? firstPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;\n if (deltaToFrameEnd > gapTolerance) {\n // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video\n // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.\n mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;\n if (mp4SampleDuration < 0) {\n mp4SampleDuration = lastFrameDuration;\n }\n\n logger.log(`It is approximately ${deltaToFrameEnd / 90} ms to the next segment; using duration ${mp4SampleDuration / 90} ms for the last video frame.`);\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n }\n compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);\n } else {\n compositionTimeOffset = Math.max(0, mp4SampleDuration * Math.round((avcSample.pts - avcSample.dts) / mp4SampleDuration));\n }\n\n // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}');\n outputSamples.push({\n size: mp4SampleLength,\n // constant duration\n duration: mp4SampleDuration,\n cts: compositionTimeOffset,\n flags: {\n isLeading: 0,\n isDependedOn: 0,\n hasRedundancy: 0,\n degradPrio: 0,\n dependsOn: avcSample.key ? 2 : 1,\n isNonSync: avcSample.key ? 0 : 1\n }\n });\n }\n // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)\n this.nextAvcDts = lastDTS + mp4SampleDuration;\n let dropped = track.dropped;\n track.len = 0;\n track.nbNalu = 0;\n track.dropped = 0;\n if (outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {\n let flags = outputSamples[0].flags;\n // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue\n // https://code.google.com/p/chromium/issues/detail?id=229412\n flags.dependsOn = 2;\n flags.isNonSync = 0;\n }\n track.samples = outputSamples;\n moof = MP4.moof(track.sequenceNumber++, firstDTS, track);\n track.samples = [];\n\n let data = {\n data1: moof,\n data2: mdat,\n startPTS: firstPTS / timeScale,\n endPTS: (lastPTS + mp4SampleDuration) / timeScale,\n startDTS: firstDTS / timeScale,\n endDTS: this.nextAvcDts / timeScale,\n type: 'video',\n hasAudio: false,\n hasVideo: true,\n nb: outputSamples.length,\n dropped: dropped\n };\n this.observer.trigger(Event.FRAG_PARSING_DATA, data);\n return data;\n }\n\n remuxAudio (track, timeOffset, contiguous, accurateTimeOffset) {\n const inputTimeScale = track.inputTimeScale;\n const mp4timeScale = track.timescale;\n const scaleFactor = inputTimeScale / mp4timeScale;\n const mp4SampleDuration = track.isAAC ? 1024 : 1152;\n const inputSampleDuration = mp4SampleDuration * scaleFactor;\n const ptsNormalize = this._PTSNormalize;\n const initPTS = this._initPTS;\n const rawMPEG = !track.isAAC && this.typeSupported.mpeg;\n\n let offset,\n mp4Sample,\n fillFrame,\n mdat, moof,\n firstPTS, lastPTS,\n inputSamples = track.samples,\n outputSamples = [],\n nextAudioPts = this.nextAudioPts;\n\n // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),\n // for sake of clarity:\n // consecutive fragments are frags with\n // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR\n // - less than 20 audio frames distance\n // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)\n // this helps ensuring audio continuity\n // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame\n contiguous |= (inputSamples.length && nextAudioPts &&\n ((accurateTimeOffset && Math.abs(timeOffset - nextAudioPts / inputTimeScale) < 0.1) ||\n Math.abs((inputSamples[0].pts - nextAudioPts - initPTS)) < 20 * inputSampleDuration)\n );\n\n // compute normalized PTS\n inputSamples.forEach(function (sample) {\n sample.pts = sample.dts = ptsNormalize(sample.pts - initPTS, timeOffset * inputTimeScale);\n });\n\n // filter out sample with negative PTS that are not playable anyway\n // if we don't remove these negative samples, they will shift all audio samples forward.\n // leading to audio overlap between current / next fragment\n inputSamples = inputSamples.filter(function (sample) {\n return sample.pts >= 0;\n });\n\n // in case all samples have negative PTS, and have been filtered out, return now\n if (inputSamples.length === 0) {\n return;\n }\n\n if (!contiguous) {\n if (!accurateTimeOffset) {\n // if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS\n nextAudioPts = inputSamples[0].pts;\n } else {\n // if timeOffset is accurate, let's use it as predicted next audio PTS\n nextAudioPts = timeOffset * inputTimeScale;\n }\n }\n\n // If the audio track is missing samples, the frames seem to get \"left-shifted\" within the\n // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.\n // In an effort to prevent this from happening, we inject frames here where there are gaps.\n // When possible, we inject a silent frame; when that's not possible, we duplicate the last\n // frame.\n\n if (track.isAAC) {\n const maxAudioFramesDrift = this.config.maxAudioFramesDrift;\n for (let i = 0, nextPts = nextAudioPts; i < inputSamples.length;) {\n // First, let's see how far off this frame is from where we expect it to be\n var sample = inputSamples[i], delta;\n let pts = sample.pts;\n delta = pts - nextPts;\n\n const duration = Math.abs(1000 * delta / inputTimeScale);\n\n // If we're overlapping by more than a duration, drop this sample\n if (delta <= -maxAudioFramesDrift * inputSampleDuration) {\n logger.warn(`Dropping 1 audio frame @ ${(nextPts / inputTimeScale).toFixed(3)}s due to ${Math.round(duration)} ms overlap.`);\n inputSamples.splice(i, 1);\n track.len -= sample.unit.length;\n // Don't touch nextPtsNorm or i\n } // eslint-disable-line brace-style\n\n // Insert missing frames if:\n // 1: We're more than maxAudioFramesDrift frame away\n // 2: Not more than MAX_SILENT_FRAME_DURATION away\n // 3: currentTime (aka nextPtsNorm) is not 0\n else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && nextPts) {\n let missing = Math.round(delta / inputSampleDuration);\n logger.warn(`Injecting ${missing} audio frame @ ${(nextPts / inputTimeScale).toFixed(3)}s due to ${Math.round(1000 * delta / inputTimeScale)} ms gap.`);\n for (let j = 0; j < missing; j++) {\n let newStamp = Math.max(nextPts, 0);\n fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n if (!fillFrame) {\n logger.log('Unable to get silent frame for given audio codec; duplicating last frame instead.');\n fillFrame = sample.unit.subarray();\n }\n inputSamples.splice(i, 0, { unit: fillFrame, pts: newStamp, dts: newStamp });\n track.len += fillFrame.length;\n nextPts += inputSampleDuration;\n i++;\n }\n\n // Adjust sample to next expected pts\n sample.pts = sample.dts = nextPts;\n nextPts += inputSampleDuration;\n i++;\n } else {\n // Otherwise, just adjust pts\n if (Math.abs(delta) > (0.1 * inputSampleDuration)) {\n // logger.log(`Invalid frame delta ${Math.round(delta + inputSampleDuration)} at PTS ${Math.round(pts / 90)} (should be ${Math.round(inputSampleDuration)}).`);\n }\n sample.pts = sample.dts = nextPts;\n nextPts += inputSampleDuration;\n i++;\n }\n }\n }\n\n for (let j = 0, nbSamples = inputSamples.length; j < nbSamples; j++) {\n let audioSample = inputSamples[j];\n let unit = audioSample.unit;\n let pts = audioSample.pts;\n // logger.log(`Audio/PTS:${Math.round(pts/90)}`);\n // if not first sample\n if (lastPTS !== undefined) {\n mp4Sample.duration = Math.round((pts - lastPTS) / scaleFactor);\n } else {\n let delta = Math.round(1000 * (pts - nextAudioPts) / inputTimeScale),\n numMissingFrames = 0;\n // if fragment are contiguous, detect hole/overlapping between fragments\n // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)\n if (contiguous && track.isAAC) {\n // log delta\n if (delta) {\n if (delta > 0 && delta < MAX_SILENT_FRAME_DURATION) {\n numMissingFrames = Math.round((pts - nextAudioPts) / inputSampleDuration);\n logger.log(`${delta} ms hole between AAC samples detected,filling it`);\n if (numMissingFrames > 0) {\n fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n if (!fillFrame) {\n fillFrame = unit.subarray();\n }\n\n track.len += numMissingFrames * fillFrame.length;\n }\n // if we have frame overlap, overlapping for more than half a frame duraion\n } else if (delta < -12) {\n // drop overlapping audio frames... browser will deal with it\n logger.log(`drop overlapping AAC sample, expected/parsed/delta:${(nextAudioPts / inputTimeScale).toFixed(3)}s/${(pts / inputTimeScale).toFixed(3)}s/${(-delta)}ms`);\n track.len -= unit.byteLength;\n continue;\n }\n // set PTS/DTS to expected PTS/DTS\n pts = nextAudioPts;\n }\n }\n // remember first PTS of our audioSamples\n firstPTS = pts;\n if (track.len > 0) {\n /* concatenate the audio data and construct the mdat in place\n (need 8 more bytes to fill length and mdat type) */\n let mdatSize = rawMPEG ? track.len : track.len + 8;\n offset = rawMPEG ? 0 : 8;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch (err) {\n this.observer.trigger(Event.ERROR, { type: ErrorTypes.MUX_ERROR, details: ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: `fail allocating audio mdat ${mdatSize}` });\n return;\n }\n if (!rawMPEG) {\n const view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n }\n } else {\n // no audio samples\n return;\n }\n for (let i = 0; i < numMissingFrames; i++) {\n fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n if (!fillFrame) {\n logger.log('Unable to get silent frame for given audio codec; duplicating this frame instead.');\n fillFrame = unit.subarray();\n }\n mdat.set(fillFrame, offset);\n offset += fillFrame.byteLength;\n mp4Sample = {\n size: fillFrame.byteLength,\n cts: 0,\n duration: 1024,\n flags: {\n isLeading: 0,\n isDependedOn: 0,\n hasRedundancy: 0,\n degradPrio: 0,\n dependsOn: 1\n }\n };\n outputSamples.push(mp4Sample);\n }\n }\n mdat.set(unit, offset);\n let unitLen = unit.byteLength;\n offset += unitLen;\n // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${audioSample.pts}/${audioSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(audioSample.pts/4294967296).toFixed(3)}');\n mp4Sample = {\n size: unitLen,\n cts: 0,\n duration: 0,\n flags: {\n isLeading: 0,\n isDependedOn: 0,\n hasRedundancy: 0,\n degradPrio: 0,\n dependsOn: 1\n }\n };\n outputSamples.push(mp4Sample);\n lastPTS = pts;\n }\n let lastSampleDuration = 0;\n let nbSamples = outputSamples.length;\n // set last sample duration as being identical to previous sample\n if (nbSamples >= 2) {\n lastSampleDuration = outputSamples[nbSamples - 2].duration;\n mp4Sample.duration = lastSampleDuration;\n }\n if (nbSamples) {\n // next audio sample PTS should be equal to last sample PTS + duration\n this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSampleDuration;\n // logger.log('Audio/PTS/PTSend:' + audioSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0));\n track.len = 0;\n track.samples = outputSamples;\n if (rawMPEG) {\n moof = new Uint8Array();\n } else {\n moof = MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, track);\n }\n\n track.samples = [];\n const start = firstPTS / inputTimeScale;\n const end = nextAudioPts / inputTimeScale;\n const audioData = {\n data1: moof,\n data2: mdat,\n startPTS: start,\n endPTS: end,\n startDTS: start,\n endDTS: end,\n type: 'audio',\n hasAudio: true,\n hasVideo: false,\n nb: nbSamples\n };\n this.observer.trigger(Event.FRAG_PARSING_DATA, audioData);\n return audioData;\n }\n return null;\n }\n\n remuxEmptyAudio (track, timeOffset, contiguous, videoData) {\n let inputTimeScale = track.inputTimeScale,\n mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale,\n scaleFactor = inputTimeScale / mp4timeScale,\n nextAudioPts = this.nextAudioPts,\n\n // sync with video's timestamp\n startDTS = (nextAudioPts !== undefined ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS,\n endDTS = videoData.endDTS * inputTimeScale + this._initDTS,\n // one sample's duration value\n sampleDuration = 1024,\n frameDuration = scaleFactor * sampleDuration,\n\n // samples count of this segment's duration\n nbSamples = Math.ceil((endDTS - startDTS) / frameDuration),\n\n // silent frame\n silentFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n\n logger.warn('remux empty Audio');\n // Can't remux if we can't generate a silent frame...\n if (!silentFrame) {\n logger.trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!');\n return;\n }\n\n let samples = [];\n for (let i = 0; i < nbSamples; i++) {\n let stamp = startDTS + i * frameDuration;\n samples.push({ unit: silentFrame, pts: stamp, dts: stamp });\n track.len += silentFrame.length;\n }\n track.samples = samples;\n\n this.remuxAudio(track, timeOffset, contiguous);\n }\n\n remuxID3 (track) {\n let length = track.samples.length, sample;\n const inputTimeScale = track.inputTimeScale;\n const initPTS = this._initPTS;\n const initDTS = this._initDTS;\n // consume samples\n if (length) {\n for (let index = 0; index < length; index++) {\n sample = track.samples[index];\n // setting id3 pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts = ((sample.pts - initPTS) / inputTimeScale);\n sample.dts = ((sample.dts - initDTS) / inputTimeScale);\n }\n this.observer.trigger(Event.FRAG_PARSING_METADATA, {\n samples: track.samples\n });\n }\n\n track.samples = [];\n }\n\n remuxText (track) {\n track.samples.sort(function (a, b) {\n return (a.pts - b.pts);\n });\n\n let length = track.samples.length, sample;\n const inputTimeScale = track.inputTimeScale;\n const initPTS = this._initPTS;\n // consume samples\n if (length) {\n for (let index = 0; index < length; index++) {\n sample = track.samples[index];\n // setting text pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts = ((sample.pts - initPTS) / inputTimeScale);\n }\n this.observer.trigger(Event.FRAG_PARSING_USERDATA, {\n samples: track.samples\n });\n }\n\n track.samples = [];\n }\n\n _PTSNormalize (value, reference) {\n let offset;\n if (reference === undefined) {\n return value;\n }\n\n if (reference < value) {\n // - 2^33\n offset = -8589934592;\n } else {\n // + 2^33\n offset = 8589934592;\n }\n /* PTS is 33bit (from 0 to 2^33 -1)\n if diff between value and reference is bigger than half of the amplitude (2^32) then it means that\n PTS looping occured. fill the gap */\n while (Math.abs(value - reference) > 4294967296) {\n value += offset;\n }\n\n return value;\n }\n}\n\nexport default MP4Remuxer;\n","/**\n * AAC helper\n */\n\nclass AAC {\n static getSilentFrame (codec, channelCount) {\n switch (codec) {\n case 'mp4a.40.2':\n if (channelCount === 1) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);\n } else if (channelCount === 2) {\n return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);\n } else if (channelCount === 3) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);\n } else if (channelCount === 4) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);\n } else if (channelCount === 5) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);\n } else if (channelCount === 6) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]);\n }\n\n break;\n // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)\n default:\n if (channelCount === 1) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0:d=0.05\" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);\n } else if (channelCount === 2) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);\n } else if (channelCount === 3) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0|0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);\n }\n break;\n }\n return null;\n }\n}\n\nexport default AAC;\n","/**\n * Generate MP4 Box\n*/\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\n\nclass MP4 {\n static init () {\n MP4.types = {\n avc1: [], // codingname\n avcC: [],\n btrt: [],\n dinf: [],\n dref: [],\n esds: [],\n ftyp: [],\n hdlr: [],\n mdat: [],\n mdhd: [],\n mdia: [],\n mfhd: [],\n minf: [],\n moof: [],\n moov: [],\n mp4a: [],\n '.mp3': [],\n mvex: [],\n mvhd: [],\n pasp: [],\n sdtp: [],\n stbl: [],\n stco: [],\n stsc: [],\n stsd: [],\n stsz: [],\n stts: [],\n tfdt: [],\n tfhd: [],\n traf: [],\n trak: [],\n trun: [],\n trex: [],\n tkhd: [],\n vmhd: [],\n smhd: []\n };\n\n let i;\n for (i in MP4.types) {\n if (MP4.types.hasOwnProperty(i)) {\n MP4.types[i] = [\n i.charCodeAt(0),\n i.charCodeAt(1),\n i.charCodeAt(2),\n i.charCodeAt(3)\n ];\n }\n }\n\n let videoHdlr = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x56, 0x69, 0x64, 0x65,\n 0x6f, 0x48, 0x61, 0x6e,\n 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'\n ]);\n\n let audioHdlr = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x53, 0x6f, 0x75, 0x6e,\n 0x64, 0x48, 0x61, 0x6e,\n 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'\n ]);\n\n MP4.HDLR_TYPES = {\n 'video': videoHdlr,\n 'audio': audioHdlr\n };\n\n let dref = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x01, // entry_count\n 0x00, 0x00, 0x00, 0x0c, // entry_size\n 0x75, 0x72, 0x6c, 0x20, // 'url' type\n 0x00, // version 0\n 0x00, 0x00, 0x01 // entry_flags\n ]);\n\n let stco = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00 // entry_count\n ]);\n\n MP4.STTS = MP4.STSC = MP4.STCO = stco;\n\n MP4.STSZ = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, // sample_size\n 0x00, 0x00, 0x00, 0x00 // sample_count\n ]);\n MP4.VMHD = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x01, // flags\n 0x00, 0x00, // graphicsmode\n 0x00, 0x00,\n 0x00, 0x00,\n 0x00, 0x00 // opcolor\n ]);\n MP4.SMHD = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, // balance\n 0x00, 0x00 // reserved\n ]);\n\n MP4.STSD = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x01]);// entry_count\n\n let majorBrand = new Uint8Array([105, 115, 111, 109]); // isom\n let avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1\n let minorVersion = new Uint8Array([0, 0, 0, 1]);\n\n MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);\n MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));\n }\n\n static box (type) {\n let\n payload = Array.prototype.slice.call(arguments, 1),\n size = 8,\n i = payload.length,\n len = i,\n result;\n // calculate the total size we need to allocate\n while (i--) {\n size += payload[i].byteLength;\n }\n\n result = new Uint8Array(size);\n result[0] = (size >> 24) & 0xff;\n result[1] = (size >> 16) & 0xff;\n result[2] = (size >> 8) & 0xff;\n result[3] = size & 0xff;\n result.set(type, 4);\n // copy the payload into the result\n for (i = 0, size = 8; i < len; i++) {\n // copy payload[i] array @ offset size\n result.set(payload[i], size);\n size += payload[i].byteLength;\n }\n return result;\n }\n\n static hdlr (type) {\n return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);\n }\n\n static mdat (data) {\n return MP4.box(MP4.types.mdat, data);\n }\n\n static mdhd (timescale, duration) {\n duration *= timescale;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(MP4.types.mdhd, new Uint8Array([\n 0x01, // version 1\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time\n (timescale >> 24) & 0xFF,\n (timescale >> 16) & 0xFF,\n (timescale >> 8) & 0xFF,\n timescale & 0xFF, // timescale\n (upperWordDuration >> 24),\n (upperWordDuration >> 16) & 0xFF,\n (upperWordDuration >> 8) & 0xFF,\n upperWordDuration & 0xFF,\n (lowerWordDuration >> 24),\n (lowerWordDuration >> 16) & 0xFF,\n (lowerWordDuration >> 8) & 0xFF,\n lowerWordDuration & 0xFF,\n 0x55, 0xc4, // 'und' language (undetermined)\n 0x00, 0x00\n ]));\n }\n\n static mdia (track) {\n return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));\n }\n\n static mfhd (sequenceNumber) {\n return MP4.box(MP4.types.mfhd, new Uint8Array([\n 0x00,\n 0x00, 0x00, 0x00, // flags\n (sequenceNumber >> 24),\n (sequenceNumber >> 16) & 0xFF,\n (sequenceNumber >> 8) & 0xFF,\n sequenceNumber & 0xFF // sequence_number\n ]));\n }\n\n static minf (track) {\n if (track.type === 'audio') {\n return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));\n } else {\n return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));\n }\n }\n\n static moof (sn, baseMediaDecodeTime, track) {\n return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));\n }\n /**\n * @param tracks... (optional) {array} the tracks associated with this movie\n */\n static moov (tracks) {\n let\n i = tracks.length,\n boxes = [];\n\n while (i--) {\n boxes[i] = MP4.trak(tracks[i]);\n }\n\n return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));\n }\n\n static mvex (tracks) {\n let\n i = tracks.length,\n boxes = [];\n\n while (i--) {\n boxes[i] = MP4.trex(tracks[i]);\n }\n\n return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));\n }\n\n static mvhd (timescale, duration) {\n duration *= timescale;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n let\n bytes = new Uint8Array([\n 0x01, // version 1\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time\n (timescale >> 24) & 0xFF,\n (timescale >> 16) & 0xFF,\n (timescale >> 8) & 0xFF,\n timescale & 0xFF, // timescale\n (upperWordDuration >> 24),\n (upperWordDuration >> 16) & 0xFF,\n (upperWordDuration >> 8) & 0xFF,\n upperWordDuration & 0xFF,\n (lowerWordDuration >> 24),\n (lowerWordDuration >> 16) & 0xFF,\n (lowerWordDuration >> 8) & 0xFF,\n lowerWordDuration & 0xFF,\n 0x00, 0x01, 0x00, 0x00, // 1.0 rate\n 0x01, 0x00, // 1.0 volume\n 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n 0xff, 0xff, 0xff, 0xff // next_track_ID\n ]);\n return MP4.box(MP4.types.mvhd, bytes);\n }\n\n static sdtp (track) {\n let\n samples = track.samples || [],\n bytes = new Uint8Array(4 + samples.length),\n flags,\n i;\n // leave the full box header (4 bytes) all zero\n // write the sample table\n for (i = 0; i < samples.length; i++) {\n flags = samples[i].flags;\n bytes[i + 4] = (flags.dependsOn << 4) |\n (flags.isDependedOn << 2) |\n (flags.hasRedundancy);\n }\n\n return MP4.box(MP4.types.sdtp, bytes);\n }\n\n static stbl (track) {\n return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO));\n }\n\n static avc1 (track) {\n let sps = [], pps = [], i, data, len;\n // assemble the SPSs\n\n for (i = 0; i < track.sps.length; i++) {\n data = track.sps[i];\n len = data.byteLength;\n sps.push((len >>> 8) & 0xFF);\n sps.push((len & 0xFF));\n\n // SPS\n sps = sps.concat(Array.prototype.slice.call(data));\n }\n\n // assemble the PPSs\n for (i = 0; i < track.pps.length; i++) {\n data = track.pps[i];\n len = data.byteLength;\n pps.push((len >>> 8) & 0xFF);\n pps.push((len & 0xFF));\n\n pps = pps.concat(Array.prototype.slice.call(data));\n }\n\n let avcc = MP4.box(MP4.types.avcC, new Uint8Array([\n 0x01, // version\n sps[3], // profile\n sps[4], // profile compat\n sps[5], // level\n 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes\n 0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets\n ].concat(sps).concat([\n track.pps.length // numOfPictureParameterSets\n ]).concat(pps))), // \"PPS\"\n width = track.width,\n height = track.height,\n hSpacing = track.pixelRatio[0],\n vSpacing = track.pixelRatio[1];\n\n return MP4.box(MP4.types.avc1, new Uint8Array([\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // data_reference_index\n 0x00, 0x00, // pre_defined\n 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n (width >> 8) & 0xFF,\n width & 0xff, // width\n (height >> 8) & 0xFF,\n height & 0xff, // height\n 0x00, 0x48, 0x00, 0x00, // horizresolution\n 0x00, 0x48, 0x00, 0x00, // vertresolution\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // frame_count\n 0x12,\n 0x64, 0x61, 0x69, 0x6C, // dailymotion/hls.js\n 0x79, 0x6D, 0x6F, 0x74,\n 0x69, 0x6F, 0x6E, 0x2F,\n 0x68, 0x6C, 0x73, 0x2E,\n 0x6A, 0x73, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, // compressorname\n 0x00, 0x18, // depth = 24\n 0x11, 0x11]), // pre_defined = -1\n avcc,\n MP4.box(MP4.types.btrt, new Uint8Array([\n 0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB\n 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate\n 0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate\n MP4.box(MP4.types.pasp, new Uint8Array([\n (hSpacing >> 24), // hSpacing\n (hSpacing >> 16) & 0xFF,\n (hSpacing >> 8) & 0xFF,\n hSpacing & 0xFF,\n (vSpacing >> 24), // vSpacing\n (vSpacing >> 16) & 0xFF,\n (vSpacing >> 8) & 0xFF,\n vSpacing & 0xFF]))\n );\n }\n\n static esds (track) {\n let configlen = track.config.length;\n return new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n\n 0x03, // descriptor_type\n 0x17 + configlen, // length\n 0x00, 0x01, // es_id\n 0x00, // stream_priority\n\n 0x04, // descriptor_type\n 0x0f + configlen, // length\n 0x40, // codec : mpeg4_audio\n 0x15, // stream_type\n 0x00, 0x00, 0x00, // buffer_size\n 0x00, 0x00, 0x00, 0x00, // maxBitrate\n 0x00, 0x00, 0x00, 0x00, // avgBitrate\n\n 0x05 // descriptor_type\n ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor\n }\n\n static mp4a (track) {\n let samplerate = track.samplerate;\n return MP4.box(MP4.types.mp4a, new Uint8Array([\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // data_reference_index\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, track.channelCount, // channelcount\n 0x00, 0x10, // sampleSize:16bits\n 0x00, 0x00, 0x00, 0x00, // reserved2\n (samplerate >> 8) & 0xFF,\n samplerate & 0xff, //\n 0x00, 0x00]),\n MP4.box(MP4.types.esds, MP4.esds(track)));\n }\n\n static mp3 (track) {\n let samplerate = track.samplerate;\n return MP4.box(MP4.types['.mp3'], new Uint8Array([\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // data_reference_index\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, track.channelCount, // channelcount\n 0x00, 0x10, // sampleSize:16bits\n 0x00, 0x00, 0x00, 0x00, // reserved2\n (samplerate >> 8) & 0xFF,\n samplerate & 0xff, //\n 0x00, 0x00]));\n }\n\n static stsd (track) {\n if (track.type === 'audio') {\n if (!track.isAAC && track.codec === 'mp3') {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));\n }\n\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));\n } else {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));\n }\n }\n\n static tkhd (track) {\n let id = track.id,\n duration = track.duration * track.timescale,\n width = track.width,\n height = track.height,\n upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)),\n lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(MP4.types.tkhd, new Uint8Array([\n 0x01, // version 1\n 0x00, 0x00, 0x07, // flags\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time\n (id >> 24) & 0xFF,\n (id >> 16) & 0xFF,\n (id >> 8) & 0xFF,\n id & 0xFF, // track_ID\n 0x00, 0x00, 0x00, 0x00, // reserved\n (upperWordDuration >> 24),\n (upperWordDuration >> 16) & 0xFF,\n (upperWordDuration >> 8) & 0xFF,\n upperWordDuration & 0xFF,\n (lowerWordDuration >> 24),\n (lowerWordDuration >> 16) & 0xFF,\n (lowerWordDuration >> 8) & 0xFF,\n lowerWordDuration & 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, // layer\n 0x00, 0x00, // alternate_group\n 0x00, 0x00, // non-audio track volume\n 0x00, 0x00, // reserved\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix\n (width >> 8) & 0xFF,\n width & 0xFF,\n 0x00, 0x00, // width\n (height >> 8) & 0xFF,\n height & 0xFF,\n 0x00, 0x00 // height\n ]));\n }\n\n static traf (track, baseMediaDecodeTime) {\n let sampleDependencyTable = MP4.sdtp(track),\n id = track.id,\n upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)),\n lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));\n return MP4.box(MP4.types.traf,\n MP4.box(MP4.types.tfhd, new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n (id >> 24),\n (id >> 16) & 0XFF,\n (id >> 8) & 0XFF,\n (id & 0xFF) // track_ID\n ])),\n MP4.box(MP4.types.tfdt, new Uint8Array([\n 0x01, // version 1\n 0x00, 0x00, 0x00, // flags\n (upperWordBaseMediaDecodeTime >> 24),\n (upperWordBaseMediaDecodeTime >> 16) & 0XFF,\n (upperWordBaseMediaDecodeTime >> 8) & 0XFF,\n (upperWordBaseMediaDecodeTime & 0xFF),\n (lowerWordBaseMediaDecodeTime >> 24),\n (lowerWordBaseMediaDecodeTime >> 16) & 0XFF,\n (lowerWordBaseMediaDecodeTime >> 8) & 0XFF,\n (lowerWordBaseMediaDecodeTime & 0xFF)\n ])),\n MP4.trun(track,\n sampleDependencyTable.length +\n 16 + // tfhd\n 20 + // tfdt\n 8 + // traf header\n 16 + // mfhd\n 8 + // moof header\n 8), // mdat header\n sampleDependencyTable);\n }\n\n /**\n * Generate a track box.\n * @param track {object} a track definition\n * @return {Uint8Array} the track box\n */\n static trak (track) {\n track.duration = track.duration || 0xffffffff;\n return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));\n }\n\n static trex (track) {\n let id = track.id;\n return MP4.box(MP4.types.trex, new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n (id >> 24),\n (id >> 16) & 0XFF,\n (id >> 8) & 0XFF,\n (id & 0xFF), // track_ID\n 0x00, 0x00, 0x00, 0x01, // default_sample_description_index\n 0x00, 0x00, 0x00, 0x00, // default_sample_duration\n 0x00, 0x00, 0x00, 0x00, // default_sample_size\n 0x00, 0x01, 0x00, 0x01 // default_sample_flags\n ]));\n }\n\n static trun (track, offset) {\n let samples = track.samples || [],\n len = samples.length,\n arraylen = 12 + (16 * len),\n array = new Uint8Array(arraylen),\n i, sample, duration, size, flags, cts;\n offset += 8 + arraylen;\n array.set([\n 0x00, // version 0\n 0x00, 0x0f, 0x01, // flags\n (len >>> 24) & 0xFF,\n (len >>> 16) & 0xFF,\n (len >>> 8) & 0xFF,\n len & 0xFF, // sample_count\n (offset >>> 24) & 0xFF,\n (offset >>> 16) & 0xFF,\n (offset >>> 8) & 0xFF,\n offset & 0xFF // data_offset\n ], 0);\n for (i = 0; i < len; i++) {\n sample = samples[i];\n duration = sample.duration;\n size = sample.size;\n flags = sample.flags;\n cts = sample.cts;\n array.set([\n (duration >>> 24) & 0xFF,\n (duration >>> 16) & 0xFF,\n (duration >>> 8) & 0xFF,\n duration & 0xFF, // sample_duration\n (size >>> 24) & 0xFF,\n (size >>> 16) & 0xFF,\n (size >>> 8) & 0xFF,\n size & 0xFF, // sample_size\n (flags.isLeading << 2) | flags.dependsOn,\n (flags.isDependedOn << 6) |\n (flags.hasRedundancy << 4) |\n (flags.paddingValue << 1) |\n flags.isNonSync,\n flags.degradPrio & 0xF0 << 8,\n flags.degradPrio & 0x0F, // sample_flags\n (cts >>> 24) & 0xFF,\n (cts >>> 16) & 0xFF,\n (cts >>> 8) & 0xFF,\n cts & 0xFF // sample_composition_time_offset\n ], 12 + 16 * i);\n }\n return MP4.box(MP4.types.trun, array);\n }\n\n static initSegment (tracks) {\n if (!MP4.types) {\n MP4.init();\n }\n\n let movie = MP4.moov(tracks), result;\n result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);\n result.set(MP4.FTYP);\n result.set(movie, MP4.FTYP.byteLength);\n return result;\n }\n}\n\nexport default MP4;\n","/**\n * passthrough remuxer\n*/\nimport Event from '../events';\n\nclass PassThroughRemuxer {\n constructor (observer) {\n this.observer = observer;\n }\n\n destroy () {\n }\n\n resetTimeStamp () {\n }\n\n resetInitSegment () {\n }\n\n remux (audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset, rawData) {\n let observer = this.observer;\n let streamType = '';\n if (audioTrack) {\n streamType += 'audio';\n }\n\n if (videoTrack) {\n streamType += 'video';\n }\n\n observer.trigger(Event.FRAG_PARSING_DATA, {\n data1: rawData,\n startPTS: timeOffset,\n startDTS: timeOffset,\n type: streamType,\n hasAudio: !!audioTrack,\n hasVideo: !!videoTrack,\n nb: 1,\n dropped: 0\n });\n // notify end of parsing\n observer.trigger(Event.FRAG_PARSED);\n }\n}\n\nexport default PassThroughRemuxer;\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","/* demuxer web worker.\n * - listen to worker message, and trigger DemuxerInline upon reception of Fragments.\n * - provides MP4 Boxes back to main thread using [transferable objects](https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast) in order to minimize message passing overhead.\n */\n\nimport DemuxerInline from '../demux/demuxer-inline';\nimport Event from '../events';\nimport { enableLogs } from '../utils/logger';\n\nimport { EventEmitter } from 'events';\n\nlet DemuxerWorker = function (self) {\n // observer setup\n let observer = new EventEmitter();\n observer.trigger = function trigger (event, ...data) {\n observer.emit(event, event, ...data);\n };\n\n observer.off = function off (event, ...data) {\n observer.removeListener(event, ...data);\n };\n\n let forwardMessage = function (ev, data) {\n self.postMessage({ event: ev, data: data });\n };\n\n self.addEventListener('message', function (ev) {\n let data = ev.data;\n // console.log('demuxer cmd:' + data.cmd);\n switch (data.cmd) {\n case 'init':\n const config = JSON.parse(data.config);\n self.demuxer = new DemuxerInline(observer, data.typeSupported, config, data.vendor);\n\n enableLogs(config.debug);\n\n // signal end of worker init\n forwardMessage('init', null);\n break;\n case 'demux':\n self.demuxer.push(data.data, data.decryptdata, data.initSegment, data.audioCodec, data.videoCodec, data.timeOffset, data.discontinuity, data.trackSwitch, data.contiguous, data.duration, data.accurateTimeOffset, data.defaultInitPTS);\n break;\n default:\n break;\n }\n });\n\n // forward events to main thread\n observer.on(Event.FRAG_DECRYPTED, forwardMessage);\n observer.on(Event.FRAG_PARSING_INIT_SEGMENT, forwardMessage);\n observer.on(Event.FRAG_PARSED, forwardMessage);\n observer.on(Event.ERROR, forwardMessage);\n observer.on(Event.FRAG_PARSING_METADATA, forwardMessage);\n observer.on(Event.FRAG_PARSING_USERDATA, forwardMessage);\n observer.on(Event.INIT_PTS_FOUND, forwardMessage);\n\n // special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy)\n observer.on(Event.FRAG_PARSING_DATA, function (ev, data) {\n let transferable = [];\n let message = { event: ev, data: data };\n if (data.data1) {\n message.data1 = data.data1.buffer;\n transferable.push(data.data1.buffer);\n delete data.data1;\n }\n if (data.data2) {\n message.data2 = data.data2.buffer;\n transferable.push(data.data2.buffer);\n delete data.data2;\n }\n self.postMessage(message, transferable);\n });\n};\n\nexport default DemuxerWorker;\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\nfunction EventEmitter() {\n this._events = this._events || {};\n this._maxListeners = this._maxListeners || undefined;\n}\nmodule.exports = EventEmitter;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\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.\nEventEmitter.defaultMaxListeners = 10;\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(n) {\n if (!isNumber(n) || n < 0 || isNaN(n))\n throw TypeError('n must be a positive number');\n this._maxListeners = n;\n return this;\n};\n\nEventEmitter.prototype.emit = function(type) {\n var er, handler, len, args, i, listeners;\n\n if (!this._events)\n this._events = {};\n\n // If there is no 'error' event listener then throw.\n if (type === 'error') {\n if (!this._events.error ||\n (isObject(this._events.error) && !this._events.error.length)) {\n er = arguments[1];\n if (er instanceof Error) {\n throw er; // Unhandled 'error' event\n } else {\n // At least give some kind of context to the user\n var err = new Error('Uncaught, unspecified \"error\" event. (' + er + ')');\n err.context = er;\n throw err;\n }\n }\n }\n\n handler = this._events[type];\n\n if (isUndefined(handler))\n return false;\n\n if (isFunction(handler)) {\n switch (arguments.length) {\n // fast cases\n case 1:\n handler.call(this);\n break;\n case 2:\n handler.call(this, arguments[1]);\n break;\n case 3:\n handler.call(this, arguments[1], arguments[2]);\n break;\n // slower\n default:\n args = Array.prototype.slice.call(arguments, 1);\n handler.apply(this, args);\n }\n } else if (isObject(handler)) {\n args = Array.prototype.slice.call(arguments, 1);\n listeners = handler.slice();\n len = listeners.length;\n for (i = 0; i < len; i++)\n listeners[i].apply(this, args);\n }\n\n return true;\n};\n\nEventEmitter.prototype.addListener = function(type, listener) {\n var m;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events)\n this._events = {};\n\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (this._events.newListener)\n this.emit('newListener', type,\n isFunction(listener.listener) ?\n listener.listener : listener);\n\n if (!this._events[type])\n // Optimize the case of one listener. Don't need the extra array object.\n this._events[type] = listener;\n else if (isObject(this._events[type]))\n // If we've already got an array, just append.\n this._events[type].push(listener);\n else\n // Adding the second element, need to change to array.\n this._events[type] = [this._events[type], listener];\n\n // Check for listener leak\n if (isObject(this._events[type]) && !this._events[type].warned) {\n if (!isUndefined(this._maxListeners)) {\n m = this._maxListeners;\n } else {\n m = EventEmitter.defaultMaxListeners;\n }\n\n if (m && m > 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(node) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n if (typeof console.trace === 'function') {\n // not supported in IE 10\n console.trace();\n }\n }\n }\n\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n var fired = false;\n\n function g() {\n this.removeListener(type, g);\n\n if (!fired) {\n fired = true;\n listener.apply(this, arguments);\n }\n }\n\n g.listener = listener;\n this.on(type, g);\n\n return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n var list, position, length, i;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events || !this._events[type])\n return this;\n\n list = this._events[type];\n length = list.length;\n position = -1;\n\n if (list === listener ||\n (isFunction(list.listener) && list.listener === listener)) {\n delete this._events[type];\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n\n } else if (isObject(list)) {\n for (i = length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list.length = 0;\n delete this._events[type];\n } else {\n list.splice(position, 1);\n }\n\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n var key, listeners;\n\n if (!this._events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!this._events.removeListener) {\n if (arguments.length === 0)\n this._events = {};\n else if (this._events[type])\n delete this._events[type];\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n for (key in this._events) {\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = {};\n return this;\n }\n\n listeners = this._events[type];\n\n if (isFunction(listeners)) {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n while (listeners.length)\n this.removeListener(type, listeners[listeners.length - 1]);\n }\n delete this._events[type];\n\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n var ret;\n if (!this._events || !this._events[type])\n ret = [];\n else if (isFunction(this._events[type]))\n ret = [this._events[type]];\n else\n ret = this._events[type].slice();\n return ret;\n};\n\nEventEmitter.prototype.listenerCount = function(type) {\n if (this._events) {\n var evlistener = this._events[type];\n\n if (isFunction(evlistener))\n return 1;\n else if (evlistener)\n return evlistener.length;\n }\n return 0;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n return emitter.listenerCount(type);\n};\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\n","import { BufferHelper } from '../utils/buffer-helper';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport Event from '../events';\nimport { logger } from '../utils/logger';\n\nconst stallDebounceInterval = 1000;\nconst jumpThreshold = 0.5; // tolerance needed as some browsers stalls playback before reaching buffered range end\n\nexport default class GapController {\n constructor (config, media, fragmentTracker, hls) {\n this.config = config;\n this.media = media;\n this.fragmentTracker = fragmentTracker;\n this.hls = hls;\n this.stallReported = false;\n }\n\n /**\n * Checks if the playhead is stuck within a gap, and if so, attempts to free it.\n * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).\n * @param lastCurrentTime\n * @param buffered\n */\n poll (lastCurrentTime, buffered) {\n const { config, media } = this;\n const currentTime = media.currentTime;\n const tnow = window.performance.now();\n\n if (currentTime !== lastCurrentTime) {\n // The playhead is now moving, but was previously stalled\n if (this.stallReported) {\n logger.warn(`playback not stuck anymore @${currentTime}, after ${Math.round(tnow - this.stalled)}ms`);\n this.stallReported = false;\n }\n this.stalled = null;\n this.nudgeRetry = 0;\n return;\n }\n\n if (media.ended || !media.buffered.length || media.readyState > 2) {\n return;\n }\n\n if (media.seeking && BufferHelper.isBuffered(media, currentTime)) {\n return;\n }\n\n // The playhead isn't moving but it should be\n // Allow some slack time to for small stalls to resolve themselves\n const stalledDuration = tnow - this.stalled;\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);\n if (!this.stalled) {\n this.stalled = tnow;\n return;\n } else if (stalledDuration >= stallDebounceInterval) {\n // Report stalling after trying to fix\n this._reportStall(bufferInfo.len);\n }\n\n this._tryFixBufferStall(bufferInfo, stalledDuration);\n }\n\n /**\n * Detects and attempts to fix known buffer stalling issues.\n * @param bufferInfo - The properties of the current buffer.\n * @param stalledDuration - The amount of time Hls.js has been stalling for.\n * @private\n */\n _tryFixBufferStall (bufferInfo, stalledDuration) {\n const { config, fragmentTracker, media } = this;\n const currentTime = media.currentTime;\n\n const partial = fragmentTracker.getPartialFragment(currentTime);\n if (partial) {\n // Try to skip over the buffer hole caused by a partial fragment\n // This method isn't limited by the size of the gap between buffered ranges\n this._trySkipBufferHole(partial);\n }\n\n if (bufferInfo.len > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) {\n // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds\n // We only try to jump the hole if it's under the configured size\n // Reset stalled so to rearm watchdog timer\n this.stalled = null;\n this._tryNudgeBuffer();\n }\n }\n\n /**\n * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.\n * @param bufferLen - The playhead distance from the end of the current buffer segment.\n * @private\n */\n _reportStall (bufferLen) {\n const { hls, media, stallReported } = this;\n if (!stallReported) {\n // Report stalled error once\n this.stallReported = true;\n logger.warn(`Playback stalling at @${media.currentTime} due to low buffer`);\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: false,\n buffer: bufferLen\n });\n }\n }\n\n /**\n * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments\n * @param partial - The partial fragment found at the current time (where playback is stalling).\n * @private\n */\n _trySkipBufferHole (partial) {\n const { hls, media } = this;\n const currentTime = media.currentTime;\n let lastEndTime = 0;\n // Check if currentTime is between unbuffered regions of partial fragments\n for (let i = 0; i < media.buffered.length; i++) {\n let startTime = media.buffered.start(i);\n if (currentTime >= lastEndTime && currentTime < startTime) {\n media.currentTime = Math.max(startTime, media.currentTime + 0.1);\n logger.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${media.currentTime}`);\n this.stalled = null;\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,\n fatal: false,\n reason: `fragment loaded with buffer holes, seeking from ${currentTime} to ${media.currentTime}`,\n frag: partial\n });\n return;\n }\n lastEndTime = media.buffered.end(i);\n }\n }\n\n /**\n * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.\n * @private\n */\n _tryNudgeBuffer () {\n const { config, hls, media } = this;\n const currentTime = media.currentTime;\n const nudgeRetry = (this.nudgeRetry || 0) + 1;\n this.nudgeRetry = nudgeRetry;\n\n if (nudgeRetry < config.nudgeMaxRetry) {\n const targetTime = currentTime + nudgeRetry * config.nudgeOffset;\n logger.log(`adjust currentTime from ${currentTime} to ${targetTime}`);\n // playback stalled in buffered area ... let's nudge currentTime to try to overcome this\n media.currentTime = targetTime;\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_NUDGE_ON_STALL,\n fatal: false\n });\n } else {\n logger.error(`still stuck in high buffer @${currentTime} after ${config.nudgeMaxRetry}, raise fatal error`);\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: true\n });\n }\n }\n}\n","/*\n * Level Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { isCodecSupportedInMp4 } from '../utils/codecs';\nimport { addGroupId, computeReloadInterval } from './level-helper';\n\nconst { performance } = window;\nlet chromeOrFirefox;\n\nexport default class LevelController extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.MANIFEST_LOADED,\n Event.LEVEL_LOADED,\n Event.AUDIO_TRACK_SWITCHED,\n Event.FRAG_LOADED,\n Event.ERROR);\n\n this.canload = false;\n this.currentLevelIndex = null;\n this.manualLevelIndex = -1;\n this.timer = null;\n\n chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());\n }\n\n onHandlerDestroying () {\n this.clearTimer();\n this.manualLevelIndex = -1;\n }\n\n clearTimer () {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n startLoad () {\n let levels = this._levels;\n\n this.canload = true;\n this.levelRetryCount = 0;\n\n // clean up live level details to force reload them, and reset load errors\n if (levels) {\n levels.forEach(level => {\n level.loadError = 0;\n const levelDetails = level.details;\n if (levelDetails && levelDetails.live) {\n level.details = undefined;\n }\n });\n }\n // speed up live playlist refresh if timer exists\n if (this.timer !== null) {\n this.loadLevel();\n }\n }\n\n stopLoad () {\n this.canload = false;\n }\n\n onManifestLoaded (data) {\n let levels = [];\n let audioTracks = [];\n let bitrateStart;\n let levelSet = {};\n let levelFromSet = null;\n let videoCodecFound = false;\n let audioCodecFound = false;\n\n // regroup redundant levels together\n data.levels.forEach(level => {\n const attributes = level.attrs;\n level.loadError = 0;\n level.fragmentError = false;\n\n videoCodecFound = videoCodecFound || !!level.videoCodec;\n audioCodecFound = audioCodecFound || !!level.audioCodec;\n\n // erase audio codec info if browser does not support mp4a.40.34.\n // demuxer will autodetect codec and fallback to mpeg/audio\n if (chromeOrFirefox && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {\n level.audioCodec = undefined;\n }\n\n levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here\n\n if (!levelFromSet) {\n level.url = [level.url];\n level.urlId = 0;\n levelSet[level.bitrate] = level;\n levels.push(level);\n } else {\n levelFromSet.url.push(level.url);\n }\n\n if (attributes) {\n if (attributes.AUDIO) {\n audioCodecFound = true;\n addGroupId(levelFromSet || level, 'audio', attributes.AUDIO);\n }\n if (attributes.SUBTITLES) {\n addGroupId(levelFromSet || level, 'text', attributes.SUBTITLES);\n }\n }\n });\n\n // remove audio-only level if we also have levels with audio+video codecs signalled\n if (videoCodecFound && audioCodecFound) {\n levels = levels.filter(({ videoCodec }) => !!videoCodec);\n }\n\n // only keep levels with supported audio/video codecs\n levels = levels.filter(({ audioCodec, videoCodec }) => {\n return (!audioCodec || isCodecSupportedInMp4(audioCodec, 'audio')) && (!videoCodec || isCodecSupportedInMp4(videoCodec, 'video'));\n });\n\n if (data.audioTracks) {\n audioTracks = data.audioTracks.filter(track => !track.audioCodec || isCodecSupportedInMp4(track.audioCodec, 'audio'));\n // Reassign id's after filtering since they're used as array indices\n audioTracks.forEach((track, index) => {\n track.id = index;\n });\n }\n\n if (levels.length > 0) {\n // start bitrate is the first bitrate of the manifest\n bitrateStart = levels[0].bitrate;\n // sort level on bitrate\n levels.sort((a, b) => a.bitrate - b.bitrate);\n this._levels = levels;\n // find index of first level in sorted levels\n for (let i = 0; i < levels.length; i++) {\n if (levels[i].bitrate === bitrateStart) {\n this._firstLevel = i;\n logger.log(`manifest loaded,${levels.length} level(s) found, first bitrate:${bitrateStart}`);\n break;\n }\n }\n\n // Audio is only alternate if manifest include a URI along with the audio group tag\n this.hls.trigger(Event.MANIFEST_PARSED, {\n levels,\n audioTracks,\n firstLevel: this._firstLevel,\n stats: data.stats,\n audio: audioCodecFound,\n video: videoCodecFound,\n altAudio: audioTracks.some(t => !!t.url)\n });\n } else {\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,\n fatal: true,\n url: this.hls.url,\n reason: 'no level with compatible codecs found in manifest'\n });\n }\n }\n\n get levels () {\n return this._levels;\n }\n\n get level () {\n return this.currentLevelIndex;\n }\n\n set level (newLevel) {\n let levels = this._levels;\n if (levels) {\n newLevel = Math.min(newLevel, levels.length - 1);\n if (this.currentLevelIndex !== newLevel || !levels[newLevel].details) {\n this.setLevelInternal(newLevel);\n }\n }\n }\n\n setLevelInternal (newLevel) {\n const levels = this._levels;\n const hls = this.hls;\n // check if level idx is valid\n if (newLevel >= 0 && newLevel < levels.length) {\n // stopping live reloading timer if any\n this.clearTimer();\n if (this.currentLevelIndex !== newLevel) {\n logger.log(`switching to level ${newLevel}`);\n this.currentLevelIndex = newLevel;\n const levelProperties = levels[newLevel];\n levelProperties.level = newLevel;\n hls.trigger(Event.LEVEL_SWITCHING, levelProperties);\n }\n const level = levels[newLevel];\n const levelDetails = level.details;\n\n // check if we need to load playlist for this level\n if (!levelDetails || levelDetails.live) {\n // level not retrieved yet, or live playlist we need to (re)load it\n let urlId = level.urlId;\n hls.trigger(Event.LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId });\n }\n } else {\n // invalid level id given, trigger error\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.LEVEL_SWITCH_ERROR,\n level: newLevel,\n fatal: false,\n reason: 'invalid level idx'\n });\n }\n }\n\n get manualLevel () {\n return this.manualLevelIndex;\n }\n\n set manualLevel (newLevel) {\n this.manualLevelIndex = newLevel;\n if (this._startLevel === undefined) {\n this._startLevel = newLevel;\n }\n\n if (newLevel !== -1) {\n this.level = newLevel;\n }\n }\n\n get firstLevel () {\n return this._firstLevel;\n }\n\n set firstLevel (newLevel) {\n this._firstLevel = newLevel;\n }\n\n get startLevel () {\n // hls.startLevel takes precedence over config.startLevel\n // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)\n if (this._startLevel === undefined) {\n let configStartLevel = this.hls.config.startLevel;\n if (configStartLevel !== undefined) {\n return configStartLevel;\n } else {\n return this._firstLevel;\n }\n } else {\n return this._startLevel;\n }\n }\n\n set startLevel (newLevel) {\n this._startLevel = newLevel;\n }\n\n onError (data) {\n if (data.fatal) {\n if (data.type === ErrorTypes.NETWORK_ERROR) {\n this.clearTimer();\n }\n\n return;\n }\n\n let levelError = false, fragmentError = false;\n let levelIndex;\n\n // try to recover not fatal errors\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n levelIndex = data.frag.level;\n fragmentError = true;\n break;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n levelIndex = data.context.level;\n levelError = true;\n break;\n case ErrorDetails.REMUX_ALLOC_ERROR:\n levelIndex = data.level;\n levelError = true;\n break;\n }\n\n if (levelIndex !== undefined) {\n this.recoverLevel(data, levelIndex, levelError, fragmentError);\n }\n }\n\n /**\n * Switch to a redundant stream if any available.\n * If redundant stream is not available, emergency switch down if ABR mode is enabled.\n *\n * @param {Object} errorEvent\n * @param {Number} levelIndex current level index\n * @param {Boolean} levelError\n * @param {Boolean} fragmentError\n */\n // FIXME Find a better abstraction where fragment/level retry management is well decoupled\n recoverLevel (errorEvent, levelIndex, levelError, fragmentError) {\n let { config } = this.hls;\n let { details: errorDetails } = errorEvent;\n let level = this._levels[levelIndex];\n let redundantLevels, delay, nextLevel;\n\n level.loadError++;\n level.fragmentError = fragmentError;\n\n if (levelError) {\n if ((this.levelRetryCount + 1) <= config.levelLoadingMaxRetry) {\n // exponential backoff capped to max retry timeout\n delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);\n // Schedule level reload\n this.timer = setTimeout(() => this.loadLevel(), delay);\n // boolean used to inform stream controller not to switch back to IDLE on non fatal error\n errorEvent.levelRetry = true;\n this.levelRetryCount++;\n logger.warn(`level controller, ${errorDetails}, retry in ${delay} ms, current retry count is ${this.levelRetryCount}`);\n } else {\n logger.error(`level controller, cannot recover from ${errorDetails} error`);\n this.currentLevelIndex = null;\n // stopping live reloading timer if any\n this.clearTimer();\n // switch error to fatal\n errorEvent.fatal = true;\n return;\n }\n }\n\n // Try any redundant streams if available for both errors: level and fragment\n // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down\n if (levelError || fragmentError) {\n redundantLevels = level.url.length;\n\n if (redundantLevels > 1 && level.loadError < redundantLevels) {\n level.urlId = (level.urlId + 1) % redundantLevels;\n level.details = undefined;\n\n logger.warn(`level controller, ${errorDetails} for level ${levelIndex}: switching to redundant URL-id ${level.urlId}`);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', level.attrs.AUDIO);\n } else {\n // Search for available level\n if (this.manualLevelIndex === -1) {\n // When lowest level has been reached, let's start hunt from the top\n nextLevel = (levelIndex === 0) ? this._levels.length - 1 : levelIndex - 1;\n logger.warn(`level controller, ${errorDetails}: switch to ${nextLevel}`);\n this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;\n } else if (fragmentError) {\n // Allow fragment retry as long as configuration allows.\n // reset this._level so that another call to set level() will trigger again a frag load\n logger.warn(`level controller, ${errorDetails}: reload a fragment`);\n this.currentLevelIndex = null;\n }\n }\n }\n }\n\n // reset errors on the successful load of a fragment\n onFragLoaded ({ frag }) {\n if (frag !== undefined && frag.type === 'main') {\n const level = this._levels[frag.level];\n if (level !== undefined) {\n level.fragmentError = false;\n level.loadError = 0;\n this.levelRetryCount = 0;\n }\n }\n }\n\n onLevelLoaded (data) {\n const { level, details } = data;\n // only process level loaded events matching with expected level\n if (level !== this.currentLevelIndex) {\n return;\n }\n\n const curLevel = this._levels[level];\n // reset level load error counter on successful level loaded only if there is no issues with fragments\n if (!curLevel.fragmentError) {\n curLevel.loadError = 0;\n this.levelRetryCount = 0;\n }\n // if current playlist is a live playlist, arm a timer to reload it\n if (details.live) {\n const reloadInterval = computeReloadInterval(curLevel.details, details, data.stats.trequest);\n logger.log(`live playlist, reload in ${Math.round(reloadInterval)} ms`);\n this.timer = setTimeout(() => this.loadLevel(), reloadInterval);\n } else {\n this.clearTimer();\n }\n }\n\n onAudioTrackSwitched (data) {\n const audioGroupId = this.hls.audioTracks[data.id].groupId;\n\n const currentLevel = this.hls.levels[this.currentLevelIndex];\n if (!currentLevel) {\n return;\n }\n\n if (currentLevel.audioGroupIds) {\n let urlId = -1;\n\n for (let i = 0; i < currentLevel.audioGroupIds.length; i++) {\n if (currentLevel.audioGroupIds[i] === audioGroupId) {\n urlId = i;\n break;\n }\n }\n\n if (urlId !== currentLevel.urlId) {\n currentLevel.urlId = urlId;\n this.startLoad();\n }\n }\n }\n\n loadLevel () {\n logger.debug('call to loadLevel');\n\n if (this.currentLevelIndex !== null && this.canload) {\n const levelObject = this._levels[this.currentLevelIndex];\n\n if (typeof levelObject === 'object' &&\n levelObject.url.length > 0) {\n const level = this.currentLevelIndex;\n const id = levelObject.urlId;\n const url = levelObject.url[id];\n\n logger.log(`Attempt loading level index ${level} with URL-id ${id}`);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);\n\n this.hls.trigger(Event.LEVEL_LOADING, { url, level, id });\n }\n }\n }\n\n get nextLoadLevel () {\n if (this.manualLevelIndex !== -1) {\n return this.manualLevelIndex;\n } else {\n return this.hls.nextAutoLevel;\n }\n }\n\n set nextLoadLevel (nextLevel) {\n this.level = nextLevel;\n if (this.manualLevelIndex === -1) {\n this.hls.nextAutoLevel = nextLevel;\n }\n }\n}\n","/*\n * id3 metadata track controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport ID3 from '../demux/id3';\nimport { sendAddTrackEvent, clearCurrentCues } from '../utils/texttrack-utils';\n\nclass ID3TrackController extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.FRAG_PARSING_METADATA);\n this.id3Track = undefined;\n this.media = undefined;\n }\n\n destroy () {\n EventHandler.prototype.destroy.call(this);\n }\n\n // Add ID3 metatadata text track.\n onMediaAttached (data) {\n this.media = data.media;\n if (!this.media) {\n\n }\n }\n\n onMediaDetaching () {\n clearCurrentCues(this.id3Track);\n this.id3Track = undefined;\n this.media = undefined;\n }\n\n getID3Track (textTracks) {\n for (let i = 0; i < textTracks.length; i++) {\n let textTrack = textTracks[i];\n if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {\n // send 'addtrack' when reusing the textTrack for metadata,\n // same as what we do for captions\n sendAddTrackEvent(textTrack, this.media);\n\n return textTrack;\n }\n }\n return this.media.addTextTrack('metadata', 'id3');\n }\n\n onFragParsingMetadata (data) {\n const fragment = data.frag;\n const samples = data.samples;\n\n // create track dynamically\n if (!this.id3Track) {\n this.id3Track = this.getID3Track(this.media.textTracks);\n this.id3Track.mode = 'hidden';\n }\n\n // Attempt to recreate Safari functionality by creating\n // WebKitDataCue objects when available and store the decoded\n // ID3 data in the value property of the cue\n let Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue;\n\n for (let i = 0; i < samples.length; i++) {\n const frames = ID3.getID3Frames(samples[i].data);\n if (frames) {\n const startTime = samples[i].pts;\n let endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.endPTS;\n\n // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE\n if (startTime === endTime) {\n endTime += 0.0001;\n }\n\n for (let j = 0; j < frames.length; j++) {\n const frame = frames[j];\n // Safari doesn't put the timestamp frame in the TextTrack\n if (!ID3.isTimeStampFrame(frame)) {\n const cue = new Cue(startTime, endTime, '');\n cue.value = frame;\n this.id3Track.addCue(cue);\n }\n }\n }\n }\n }\n}\n\nexport default ID3TrackController;\n","import { getMediaSource } from './utils/mediasource-helper';\n\nexport function isSupported () {\n const mediaSource = getMediaSource();\n const sourceBuffer = window.SourceBuffer || window.WebKitSourceBuffer;\n const isTypeSupported = mediaSource &&\n typeof mediaSource.isTypeSupported === 'function' &&\n mediaSource.isTypeSupported('video/mp4; codecs=\"avc1.42E01E,mp4a.40.2\"');\n\n // if SourceBuffer is exposed ensure its API is valid\n // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible\n const sourceBufferValidAPI = !sourceBuffer ||\n (sourceBuffer.prototype &&\n typeof sourceBuffer.prototype.appendBuffer === 'function' &&\n typeof sourceBuffer.prototype.remove === 'function');\n return !!isTypeSupported && !!sourceBufferValidAPI;\n}\n","/**\n * HLS config\n */\n\nimport AbrController from './controller/abr-controller';\nimport BufferController from './controller/buffer-controller';\nimport CapLevelController from './controller/cap-level-controller';\nimport FPSController from './controller/fps-controller';\nimport XhrLoader from './utils/xhr-loader';\n// import FetchLoader from './utils/fetch-loader';\n\nimport AudioTrackController from './controller/audio-track-controller';\nimport AudioStreamController from './controller/audio-stream-controller';\n\nimport * as Cues from './utils/cues';\nimport TimelineController from './controller/timeline-controller';\nimport SubtitleTrackController from './controller/subtitle-track-controller';\nimport { SubtitleStreamController } from './controller/subtitle-stream-controller';\nimport EMEController from './controller/eme-controller';\n\nimport { requestMediaKeySystemAccess } from './utils/mediakeys-helper';\n\nexport var hlsDefaultConfig = {\n autoStartLoad: true, // used by stream-controller\n startPosition: -1, // used by stream-controller\n defaultAudioCodec: undefined, // used by stream-controller\n debug: false, // used by logger\n capLevelOnFPSDrop: false, // used by fps-controller\n capLevelToPlayerSize: false, // used by cap-level-controller\n initialLiveManifestSize: 1, // used by stream-controller\n maxBufferLength: 30, // used by stream-controller\n maxBufferSize: 60 * 1000 * 1000, // used by stream-controller\n maxBufferHole: 0.5, // used by stream-controller\n\n lowBufferWatchdogPeriod: 0.5, // used by stream-controller\n highBufferWatchdogPeriod: 3, // used by stream-controller\n nudgeOffset: 0.1, // used by stream-controller\n nudgeMaxRetry: 3, // used by stream-controller\n maxFragLookUpTolerance: 0.25, // used by stream-controller\n liveSyncDurationCount: 3, // used by stream-controller\n liveMaxLatencyDurationCount: Infinity, // used by stream-controller\n liveSyncDuration: undefined, // used by stream-controller\n liveMaxLatencyDuration: undefined, // used by stream-controller\n liveDurationInfinity: false, // used by buffer-controller\n liveBackBufferLength: Infinity, // used by buffer-controller\n maxMaxBufferLength: 600, // used by stream-controller\n enableWorker: true, // used by demuxer\n enableSoftwareAES: true, // used by decrypter\n manifestLoadingTimeOut: 10000, // used by playlist-loader\n manifestLoadingMaxRetry: 1, // used by playlist-loader\n manifestLoadingRetryDelay: 1000, // used by playlist-loader\n manifestLoadingMaxRetryTimeout: 64000, // used by playlist-loader\n startLevel: undefined, // used by level-controller\n levelLoadingTimeOut: 10000, // used by playlist-loader\n levelLoadingMaxRetry: 4, // used by playlist-loader\n levelLoadingRetryDelay: 1000, // used by playlist-loader\n levelLoadingMaxRetryTimeout: 64000, // used by playlist-loader\n fragLoadingTimeOut: 20000, // used by fragment-loader\n fragLoadingMaxRetry: 6, // used by fragment-loader\n fragLoadingRetryDelay: 1000, // used by fragment-loader\n fragLoadingMaxRetryTimeout: 64000, // used by fragment-loader\n startFragPrefetch: false, // used by stream-controller\n fpsDroppedMonitoringPeriod: 5000, // used by fps-controller\n fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller\n appendErrorMaxRetry: 3, // used by buffer-controller\n loader: XhrLoader,\n // loader: FetchLoader,\n fLoader: undefined, // used by fragment-loader\n pLoader: undefined, // used by playlist-loader\n xhrSetup: undefined, // used by xhr-loader\n licenseXhrSetup: undefined, // used by eme-controller\n // fetchSetup: undefined,\n abrController: AbrController,\n bufferController: BufferController,\n capLevelController: CapLevelController,\n fpsController: FPSController,\n stretchShortVideoTrack: false, // used by mp4-remuxer\n maxAudioFramesDrift: 1, // used by mp4-remuxer\n forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer\n abrEwmaFastLive: 3, // used by abr-controller\n abrEwmaSlowLive: 9, // used by abr-controller\n abrEwmaFastVoD: 3, // used by abr-controller\n abrEwmaSlowVoD: 9, // used by abr-controller\n abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller\n abrBandWidthFactor: 0.95, // used by abr-controller\n abrBandWidthUpFactor: 0.7, // used by abr-controller\n abrMaxWithRealBitrate: false, // used by abr-controller\n maxStarvationDelay: 4, // used by abr-controller\n maxLoadingDelay: 4, // used by abr-controller\n minAutoBitrate: 0, // used by hls\n emeEnabled: false, // used by eme-controller\n widevineLicenseUrl: undefined, // used by eme-controller\n requestMediaKeySystemAccessFunc:\n requestMediaKeySystemAccess // used by eme-controller\n};\n\nif (__USE_SUBTITLES__) {\n hlsDefaultConfig.subtitleStreamController = SubtitleStreamController;\n hlsDefaultConfig.subtitleTrackController = SubtitleTrackController;\n hlsDefaultConfig.timelineController = TimelineController;\n hlsDefaultConfig.cueHandler = Cues; // used by timeline-controller\n hlsDefaultConfig.enableCEA708Captions = true; // used by timeline-controller\n hlsDefaultConfig.enableWebVTT = true; // used by timeline-controller\n hlsDefaultConfig.captionsTextTrack1Label = 'English'; // used by timeline-controller\n hlsDefaultConfig.captionsTextTrack1LanguageCode = 'en'; // used by timeline-controller\n hlsDefaultConfig.captionsTextTrack2Label = 'Spanish'; // used by timeline-controller\n hlsDefaultConfig.captionsTextTrack2LanguageCode = 'es'; // used by timeline-controller\n}\n\nif (__USE_ALT_AUDIO__) {\n hlsDefaultConfig.audioStreamController = AudioStreamController;\n hlsDefaultConfig.audioTrackController = AudioTrackController;\n}\n\nif (__USE_EME_DRM__) {\n hlsDefaultConfig.emeController = EMEController;\n}\n","/*\n * simple ABR Controller\n * - compute next level based on last fragment bw heuristics\n * - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling\n */\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport { ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport EwmaBandWidthEstimator from '../utils/ewma-bandwidth-estimator';\n\nconst { performance } = window;\n\nclass AbrController extends EventHandler {\n constructor (hls) {\n super(hls, Event.FRAG_LOADING,\n Event.FRAG_LOADED,\n Event.FRAG_BUFFERED,\n Event.ERROR);\n this.lastLoadedFragLevel = 0;\n this._nextAutoLevel = -1;\n this.hls = hls;\n this.timer = null;\n this._bwEstimator = null;\n this.onCheck = this._abandonRulesCheck.bind(this);\n }\n\n destroy () {\n this.clearTimer();\n EventHandler.prototype.destroy.call(this);\n }\n\n onFragLoading (data) {\n const frag = data.frag;\n if (frag.type === 'main') {\n if (!this.timer) {\n this.fragCurrent = frag;\n this.timer = setInterval(this.onCheck, 100);\n }\n\n // lazy init of BwEstimator, rationale is that we use different params for Live/VoD\n // so we need to wait for stream manifest / playlist type to instantiate it.\n if (!this._bwEstimator) {\n const hls = this.hls;\n const config = hls.config;\n const level = frag.level;\n const isLive = hls.levels[level].details.live;\n\n let ewmaFast, ewmaSlow;\n if (isLive) {\n ewmaFast = config.abrEwmaFastLive;\n ewmaSlow = config.abrEwmaSlowLive;\n } else {\n ewmaFast = config.abrEwmaFastVoD;\n ewmaSlow = config.abrEwmaSlowVoD;\n }\n this._bwEstimator = new EwmaBandWidthEstimator(hls, ewmaSlow, ewmaFast, config.abrEwmaDefaultEstimate);\n }\n }\n }\n\n _abandonRulesCheck () {\n /*\n monitor fragment retrieval time...\n we compute expected time of arrival of the complete fragment.\n we compare it to expected time of buffer starvation\n */\n const hls = this.hls;\n const video = hls.media;\n const frag = this.fragCurrent;\n\n if (!frag) {\n return;\n }\n\n const loader = frag.loader;\n const minAutoLevel = hls.minAutoLevel;\n\n // if loader has been destroyed or loading has been aborted, stop timer and return\n if (!loader || (loader.stats && loader.stats.aborted)) {\n logger.warn('frag loader destroy or aborted, disarm abandonRules');\n this.clearTimer();\n // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\n return;\n }\n let stats = loader.stats;\n /* only monitor frag retrieval time if\n (video not paused OR first fragment being loaded(ready state === HAVE_NOTHING = 0)) AND autoswitching enabled AND not lowest level (=> means that we have several levels) */\n if (video && stats && ((!video.paused && (video.playbackRate !== 0)) || !video.readyState) && frag.autoLevel && frag.level) {\n let requestDelay = performance.now() - stats.trequest,\n playbackRate = Math.abs(video.playbackRate);\n // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate\n if (requestDelay > (500 * frag.duration / playbackRate)) {\n let levels = hls.levels,\n loadRate = Math.max(1, stats.bw ? stats.bw / 8 : stats.loaded * 1000 / requestDelay), // byte/s; at least 1 byte/s to avoid division by zero\n // compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size\n level = levels[frag.level],\n levelBitrate = level.realBitrate ? Math.max(level.realBitrate, level.bitrate) : level.bitrate,\n expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levelBitrate / 8)),\n pos = video.currentTime,\n fragLoadedDelay = (expectedLen - stats.loaded) / loadRate,\n bufferStarvationDelay = (BufferHelper.bufferInfo(video, pos, hls.config.maxBufferHole).end - pos) / playbackRate;\n // consider emergency switch down only if we have less than 2 frag buffered AND\n // time to finish loading current fragment is bigger than buffer starvation delay\n // ie if we risk buffer starvation if bw does not increase quickly\n if ((bufferStarvationDelay < (2 * frag.duration / playbackRate)) && (fragLoadedDelay > bufferStarvationDelay)) {\n let fragLevelNextLoadedDelay, nextLoadLevel;\n // lets iterate through lower level and try to find the biggest one that could avoid rebuffering\n // we start from current level - 1 and we step down , until we find a matching level\n for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {\n // compute time to load next fragment at lower level\n // 0.8 : consider only 80% of current bw to be conservative\n // 8 = bits per byte (bps/Bps)\n let levelNextBitrate = levels[nextLoadLevel].realBitrate ? Math.max(levels[nextLoadLevel].realBitrate, levels[nextLoadLevel].bitrate) : levels[nextLoadLevel].bitrate;\n fragLevelNextLoadedDelay = frag.duration * levelNextBitrate / (8 * 0.8 * loadRate);\n if (fragLevelNextLoadedDelay < bufferStarvationDelay) {\n // we found a lower level that be rebuffering free with current estimated bw !\n break;\n }\n }\n // only emergency switch down if it takes less time to load new fragment at lowest level instead\n // of finishing loading current one ...\n if (fragLevelNextLoadedDelay < fragLoadedDelay) {\n logger.warn(`loading too slow, abort fragment loading and switch to level ${nextLoadLevel}:fragLoadedDelay[${nextLoadLevel}]<fragLoadedDelay[${frag.level - 1}];bufferStarvationDelay:${fragLevelNextLoadedDelay.toFixed(1)}<${fragLoadedDelay.toFixed(1)}:${bufferStarvationDelay.toFixed(1)}`);\n // force next load level in auto mode\n hls.nextLoadLevel = nextLoadLevel;\n // update bw estimate for this fragment before cancelling load (this will help reducing the bw)\n this._bwEstimator.sample(requestDelay, stats.loaded);\n // abort fragment loading\n loader.abort();\n // stop abandon rules timer\n this.clearTimer();\n hls.trigger(Event.FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag, stats: stats });\n }\n }\n }\n }\n }\n\n onFragLoaded (data) {\n const frag = data.frag;\n if (frag.type === 'main' && Number.isFinite(frag.sn)) {\n // stop monitoring bw once frag loaded\n this.clearTimer();\n // store level id after successful fragment load\n this.lastLoadedFragLevel = frag.level;\n // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\n\n // compute level average bitrate\n if (this.hls.config.abrMaxWithRealBitrate) {\n const level = this.hls.levels[frag.level];\n let loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded;\n let loadedDuration = (level.loaded ? level.loaded.duration : 0) + data.frag.duration;\n level.loaded = { bytes: loadedBytes, duration: loadedDuration };\n level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);\n }\n // if fragment has been loaded to perform a bitrate test,\n if (data.frag.bitrateTest) {\n let stats = data.stats;\n stats.tparsed = stats.tbuffered = stats.tload;\n this.onFragBuffered(data);\n }\n }\n }\n\n onFragBuffered (data) {\n const stats = data.stats;\n const frag = data.frag;\n // only update stats on first frag buffering\n // if same frag is loaded multiple times, it might be in browser cache, and loaded quickly\n // and leading to wrong bw estimation\n // on bitrate test, also only update stats once (if tload = tbuffered == on FRAG_LOADED)\n if (stats.aborted !== true && frag.type === 'main' && Number.isFinite(frag.sn) && ((!frag.bitrateTest || stats.tload === stats.tbuffered))) {\n // use tparsed-trequest instead of tbuffered-trequest to compute fragLoadingProcessing; rationale is that buffer appending only happens once media is attached\n // in case we use config.startFragPrefetch while media is not attached yet, fragment might be parsed while media not attached yet, but it will only be buffered on media attached\n // as a consequence it could happen really late in the process. meaning that appending duration might appears huge ... leading to underestimated throughput estimation\n let fragLoadingProcessingMs = stats.tparsed - stats.trequest;\n logger.log(`latency/loading/parsing/append/kbps:${Math.round(stats.tfirst - stats.trequest)}/${Math.round(stats.tload - stats.tfirst)}/${Math.round(stats.tparsed - stats.tload)}/${Math.round(stats.tbuffered - stats.tparsed)}/${Math.round(8 * stats.loaded / (stats.tbuffered - stats.trequest))}`);\n this._bwEstimator.sample(fragLoadingProcessingMs, stats.loaded);\n stats.bwEstimate = this._bwEstimator.getEstimate();\n // if fragment has been loaded to perform a bitrate test, (hls.startLevel = -1), store bitrate test delay duration\n if (frag.bitrateTest) {\n this.bitrateTestDelay = fragLoadingProcessingMs / 1000;\n } else {\n this.bitrateTestDelay = 0;\n }\n }\n }\n\n onError (data) {\n // stop timer in case of frag loading error\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n this.clearTimer();\n break;\n default:\n break;\n }\n }\n\n clearTimer () {\n clearInterval(this.timer);\n this.timer = null;\n }\n\n // return next auto level\n get nextAutoLevel () {\n const forcedAutoLevel = this._nextAutoLevel;\n const bwEstimator = this._bwEstimator;\n // in case next auto level has been forced, and bw not available or not reliable, return forced value\n if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {\n return forcedAutoLevel;\n }\n\n // compute next level using ABR logic\n let nextABRAutoLevel = this._nextABRAutoLevel;\n // if forced auto level has been defined, use it to cap ABR computed quality level\n if (forcedAutoLevel !== -1) {\n nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);\n }\n\n return nextABRAutoLevel;\n }\n get _nextABRAutoLevel () {\n let hls = this.hls, maxAutoLevel = hls.maxAutoLevel, levels = hls.levels, config = hls.config, minAutoLevel = hls.minAutoLevel;\n const video = hls.media,\n currentLevel = this.lastLoadedFragLevel,\n currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0,\n pos = (video ? video.currentTime : 0),\n // playbackRate is the absolute value of the playback rate; if video.playbackRate is 0, we use 1 to load as\n // if we're playing back at the normal rate.\n playbackRate = ((video && (video.playbackRate !== 0)) ? Math.abs(video.playbackRate) : 1.0),\n avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate,\n // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.\n bufferStarvationDelay = (BufferHelper.bufferInfo(video, pos, config.maxBufferHole).end - pos) / playbackRate;\n\n // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all\n let bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor, levels);\n if (bestLevel >= 0) {\n return bestLevel;\n } else {\n logger.trace('rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering');\n // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering\n // if no matching level found, logic will return 0\n let maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay,\n bwFactor = config.abrBandWidthFactor,\n bwUpFactor = config.abrBandWidthUpFactor;\n if (bufferStarvationDelay === 0) {\n // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test\n let bitrateTestDelay = this.bitrateTestDelay;\n if (bitrateTestDelay) {\n // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value\n // max video loading delay used in automatic start level selection :\n // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +\n // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )\n // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration\n const maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;\n maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;\n logger.trace(`bitrate test took ${Math.round(1000 * bitrateTestDelay)}ms, set first fragment max fetchDuration to ${Math.round(1000 * maxStarvationDelay)} ms`);\n // don't use conservative factor on bitrate test\n bwFactor = bwUpFactor = 1;\n }\n }\n bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor, levels);\n return Math.max(bestLevel, 0);\n }\n }\n\n _findBestLevel (currentLevel, currentFragDuration, currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor, levels) {\n for (let i = maxAutoLevel; i >= minAutoLevel; i--) {\n let levelInfo = levels[i];\n\n if (!levelInfo) {\n continue;\n }\n\n let levelDetails = levelInfo.details,\n avgDuration = levelDetails ? levelDetails.totalduration / levelDetails.fragments.length : currentFragDuration,\n live = levelDetails ? levelDetails.live : false,\n adjustedbw;\n // follow algorithm captured from stagefright :\n // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp\n // Pick the highest bandwidth stream below or equal to estimated bandwidth.\n // consider only 80% of the available bandwidth, but if we are switching up,\n // be even more conservative (70%) to avoid overestimating and immediately\n // switching back.\n if (i <= currentLevel) {\n adjustedbw = bwFactor * currentBw;\n } else {\n adjustedbw = bwUpFactor * currentBw;\n }\n\n const bitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate,\n fetchDuration = bitrate * avgDuration / adjustedbw;\n\n logger.trace(`level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: ${i}/${Math.round(adjustedbw)}/${bitrate}/${avgDuration}/${maxFetchDuration}/${fetchDuration}`);\n // if adjusted bw is greater than level bitrate AND\n if (adjustedbw > bitrate &&\n // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches\n // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...\n // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that _findBestLevel will return -1\n (!fetchDuration || (live && !this.bitrateTestDelay) || fetchDuration < maxFetchDuration)) {\n // as we are looping from highest to lowest, this will return the best achievable quality level\n return i;\n }\n }\n // not enough time budget even with quality level 0 ... rebuffering might happen\n return -1;\n }\n\n set nextAutoLevel (nextLevel) {\n this._nextAutoLevel = nextLevel;\n }\n}\n\nexport default AbrController;\n","/*\n * EWMA Bandwidth Estimator\n * - heavily inspired from shaka-player\n * Tracks bandwidth samples and estimates available bandwidth.\n * Based on the minimum of two exponentially-weighted moving averages with\n * different half-lives.\n */\n\nimport EWMA from '../utils/ewma';\n\nclass EwmaBandWidthEstimator {\n constructor (hls, slow, fast, defaultEstimate) {\n this.hls = hls;\n this.defaultEstimate_ = defaultEstimate;\n this.minWeight_ = 0.001;\n this.minDelayMs_ = 50;\n this.slow_ = new EWMA(slow);\n this.fast_ = new EWMA(fast);\n }\n\n sample (durationMs, numBytes) {\n durationMs = Math.max(durationMs, this.minDelayMs_);\n let bandwidth = 8000 * numBytes / durationMs,\n // console.log('instant bw:'+ Math.round(bandwidth));\n // we weight sample using loading duration....\n weight = durationMs / 1000;\n this.fast_.sample(weight, bandwidth);\n this.slow_.sample(weight, bandwidth);\n }\n\n canEstimate () {\n let fast = this.fast_;\n return (fast && fast.getTotalWeight() >= this.minWeight_);\n }\n\n getEstimate () {\n if (this.canEstimate()) {\n // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));\n // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));\n // Take the minimum of these two estimates. This should have the effect of\n // adapting down quickly, but up more slowly.\n return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());\n } else {\n return this.defaultEstimate_;\n }\n }\n\n destroy () {\n }\n}\nexport default EwmaBandWidthEstimator;\n","/*\n * compute an Exponential Weighted moving average\n * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\n * - heavily inspired from shaka-player\n */\n\nclass EWMA {\n // About half of the estimated value will be from the last |halfLife| samples by weight.\n constructor (halfLife) {\n // Larger values of alpha expire historical data more slowly.\n this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;\n this.estimate_ = 0;\n this.totalWeight_ = 0;\n }\n\n sample (weight, value) {\n let adjAlpha = Math.pow(this.alpha_, weight);\n this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;\n this.totalWeight_ += weight;\n }\n\n getTotalWeight () {\n return this.totalWeight_;\n }\n\n getEstimate () {\n if (this.alpha_) {\n let zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);\n return this.estimate_ / zeroFactor;\n } else {\n return this.estimate_;\n }\n }\n}\n\nexport default EWMA;\n","/*\n * Buffer Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { getMediaSource } from '../utils/mediasource-helper';\n\nconst MediaSource = getMediaSource();\n\nclass BufferController extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.MEDIA_ATTACHING,\n Event.MEDIA_DETACHING,\n Event.MANIFEST_PARSED,\n Event.BUFFER_RESET,\n Event.BUFFER_APPENDING,\n Event.BUFFER_CODECS,\n Event.BUFFER_EOS,\n Event.BUFFER_FLUSHING,\n Event.LEVEL_PTS_UPDATED,\n Event.LEVEL_UPDATED);\n\n // the value that we have set mediasource.duration to\n // (the actual duration may be tweaked slighly by the browser)\n this._msDuration = null;\n // the value that we want to set mediaSource.duration to\n this._levelDuration = null;\n // the target duration of the current media playlist\n this._levelTargetDuration = 10;\n // current stream state: true - for live broadcast, false - for VoD content\n this._live = null;\n // cache the self generated object url to detect hijack of video tag\n this._objectUrl = null;\n // The number of BUFFER_CODEC events received before any sourceBuffers are created\n this.bufferCodecEventsExpected = 0;\n\n // Source Buffer listeners\n this.onsbue = this.onSBUpdateEnd.bind(this);\n this.onsbe = this.onSBUpdateError.bind(this);\n this.pendingTracks = {};\n this.tracks = {};\n }\n\n destroy () {\n EventHandler.prototype.destroy.call(this);\n }\n\n onLevelPtsUpdated (data) {\n let type = data.type;\n let audioTrack = this.tracks.audio;\n\n // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)\n // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`\n // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos). At the time of change we issue\n // `SourceBuffer.abort()` and adjusting `SourceBuffer.timestampOffset` if `SourceBuffer.updating` is false or awaiting `updateend`\n // event if SB is in updating state.\n // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486\n\n if (type === 'audio' && audioTrack && audioTrack.container === 'audio/mpeg') { // Chrome audio mp3 track\n let audioBuffer = this.sourceBuffer.audio;\n let delta = Math.abs(audioBuffer.timestampOffset - data.start);\n\n // adjust timestamp offset if time delta is greater than 100ms\n if (delta > 0.1) {\n let updating = audioBuffer.updating;\n\n try {\n audioBuffer.abort();\n } catch (err) {\n logger.warn('can not abort audio buffer: ' + err);\n }\n\n if (!updating) {\n logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + data.start);\n audioBuffer.timestampOffset = data.start;\n } else {\n this.audioTimestampOffset = data.start;\n }\n }\n }\n }\n\n onManifestParsed (data) {\n // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller\n // sourcebuffers will be created all at once when the expected nb of tracks will be reached\n // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller\n // it will contain the expected nb of source buffers, no need to compute it\n this.bufferCodecEventsExpected = data.altAudio ? 2 : 1;\n logger.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`);\n }\n\n onMediaAttaching (data) {\n let media = this.media = data.media;\n if (media) {\n // setup the media source\n let ms = this.mediaSource = new MediaSource();\n // Media Source listeners\n this.onmso = this.onMediaSourceOpen.bind(this);\n this.onmse = this.onMediaSourceEnded.bind(this);\n this.onmsc = this.onMediaSourceClose.bind(this);\n ms.addEventListener('sourceopen', this.onmso);\n ms.addEventListener('sourceended', this.onmse);\n ms.addEventListener('sourceclose', this.onmsc);\n // link video and media Source\n media.src = window.URL.createObjectURL(ms);\n // cache the locally generated object url\n this._objectUrl = media.src;\n }\n }\n\n onMediaDetaching () {\n logger.log('media source detaching');\n let ms = this.mediaSource;\n if (ms) {\n if (ms.readyState === 'open') {\n try {\n // endOfStream could trigger exception if any sourcebuffer is in updating state\n // we don't really care about checking sourcebuffer state here,\n // as we are anyway detaching the MediaSource\n // let's just avoid this exception to propagate\n ms.endOfStream();\n } catch (err) {\n logger.warn(`onMediaDetaching:${err.message} while calling endOfStream`);\n }\n }\n ms.removeEventListener('sourceopen', this.onmso);\n ms.removeEventListener('sourceended', this.onmse);\n ms.removeEventListener('sourceclose', this.onmsc);\n\n // Detach properly the MediaSource from the HTMLMediaElement as\n // suggested in https://github.com/w3c/media-source/issues/53.\n if (this.media) {\n window.URL.revokeObjectURL(this._objectUrl);\n\n // clean up video tag src only if it's our own url. some external libraries might\n // hijack the video tag and change its 'src' without destroying the Hls instance first\n if (this.media.src === this._objectUrl) {\n this.media.removeAttribute('src');\n this.media.load();\n } else {\n logger.warn('media.src was changed by a third party - skip cleanup');\n }\n }\n\n this.mediaSource = null;\n this.media = null;\n this._objectUrl = null;\n this.pendingTracks = {};\n this.tracks = {};\n this.sourceBuffer = {};\n this.flushRange = [];\n this.segments = [];\n this.appended = 0;\n }\n this.onmso = this.onmse = this.onmsc = null;\n this.hls.trigger(Event.MEDIA_DETACHED);\n }\n\n onMediaSourceOpen () {\n logger.log('media source opened');\n this.hls.trigger(Event.MEDIA_ATTACHED, { media: this.media });\n let mediaSource = this.mediaSource;\n if (mediaSource) {\n // once received, don't listen anymore to sourceopen event\n mediaSource.removeEventListener('sourceopen', this.onmso);\n }\n this.checkPendingTracks();\n }\n\n checkPendingTracks () {\n let { bufferCodecEventsExpected, pendingTracks } = this;\n // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.\n // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after\n // data has been appended to existing ones.\n // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.\n const pendingTracksCount = Object.keys(pendingTracks).length;\n if ((pendingTracksCount && !bufferCodecEventsExpected) || pendingTracksCount === 2) {\n // ok, let's create them now !\n this.createSourceBuffers(pendingTracks);\n this.pendingTracks = {};\n // append any pending segments now !\n this.doAppending();\n }\n }\n\n onMediaSourceClose () {\n logger.log('media source closed');\n }\n\n onMediaSourceEnded () {\n logger.log('media source ended');\n }\n\n onSBUpdateEnd () {\n // update timestampOffset\n if (this.audioTimestampOffset) {\n let audioBuffer = this.sourceBuffer.audio;\n logger.warn(`change mpeg audio timestamp offset from ${audioBuffer.timestampOffset} to ${this.audioTimestampOffset}`);\n audioBuffer.timestampOffset = this.audioTimestampOffset;\n delete this.audioTimestampOffset;\n }\n\n if (this._needsFlush) {\n this.doFlush();\n }\n\n if (this._needsEos) {\n this.checkEos();\n }\n\n this.appending = false;\n let parent = this.parent;\n // count nb of pending segments waiting for appending on this sourcebuffer\n let pending = this.segments.reduce((counter, segment) => (segment.parent === parent) ? counter + 1 : counter, 0);\n\n // this.sourceBuffer is better to use than media.buffered as it is closer to the PTS data from the fragments\n let timeRanges = {};\n const sourceBuffer = this.sourceBuffer;\n for (let streamType in sourceBuffer) {\n timeRanges[streamType] = sourceBuffer[streamType].buffered;\n }\n\n this.hls.trigger(Event.BUFFER_APPENDED, { parent, pending, timeRanges });\n // don't append in flushing mode\n if (!this._needsFlush) {\n this.doAppending();\n }\n\n this.updateMediaElementDuration();\n\n // appending goes first\n if (pending === 0) {\n this.flushLiveBackBuffer();\n }\n }\n\n onSBUpdateError (event) {\n logger.error('sourceBuffer error:', event);\n // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error\n // this error might not always be fatal (it is fatal if decode error is set, in that case\n // it will be followed by a mediaElement error ...)\n this.hls.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false });\n // we don't need to do more than that, as accordin to the spec, updateend will be fired just after\n }\n\n onBufferReset () {\n let sourceBuffer = this.sourceBuffer;\n for (let type in sourceBuffer) {\n let sb = sourceBuffer[type];\n try {\n this.mediaSource.removeSourceBuffer(sb);\n sb.removeEventListener('updateend', this.onsbue);\n sb.removeEventListener('error', this.onsbe);\n } catch (err) {\n }\n }\n this.sourceBuffer = {};\n this.flushRange = [];\n this.segments = [];\n this.appended = 0;\n }\n\n onBufferCodecs (tracks) {\n // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks\n // if sourcebuffers already created, do nothing ...\n if (Object.keys(this.sourceBuffer).length) {\n return;\n }\n\n Object.keys(tracks).forEach(trackName => {\n this.pendingTracks[trackName] = tracks[trackName];\n });\n\n const { mediaSource } = this;\n this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);\n if (mediaSource && mediaSource.readyState === 'open') {\n this.checkPendingTracks();\n }\n }\n\n createSourceBuffers (tracks) {\n let sourceBuffer = this.sourceBuffer, mediaSource = this.mediaSource;\n\n for (let trackName in tracks) {\n if (!sourceBuffer[trackName]) {\n let track = tracks[trackName];\n // use levelCodec as first priority\n let codec = track.levelCodec || track.codec;\n let mimeType = `${track.container};codecs=${codec}`;\n logger.log(`creating sourceBuffer(${mimeType})`);\n try {\n let sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);\n sb.addEventListener('updateend', this.onsbue);\n sb.addEventListener('error', this.onsbe);\n this.tracks[trackName] = { codec: codec, container: track.container };\n track.buffer = sb;\n } catch (err) {\n logger.error(`error while trying to add sourceBuffer:${err.message}`);\n this.hls.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType: mimeType });\n }\n }\n }\n this.hls.trigger(Event.BUFFER_CREATED, { tracks: tracks });\n }\n\n onBufferAppending (data) {\n if (!this._needsFlush) {\n if (!this.segments) {\n this.segments = [ data ];\n } else {\n this.segments.push(data);\n }\n\n this.doAppending();\n }\n }\n\n onBufferAppendFail (data) {\n logger.error('sourceBuffer error:', data.event);\n // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error\n // this error might not always be fatal (it is fatal if decode error is set, in that case\n // it will be followed by a mediaElement error ...)\n this.hls.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false });\n }\n\n // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()\n onBufferEos (data) {\n let sb = this.sourceBuffer;\n let dataType = data.type;\n for (let type in sb) {\n if (!dataType || type === dataType) {\n if (!sb[type].ended) {\n sb[type].ended = true;\n logger.log(`${type} sourceBuffer now EOS`);\n }\n }\n }\n this.checkEos();\n }\n\n // if all source buffers are marked as ended, signal endOfStream() to MediaSource.\n checkEos () {\n let sb = this.sourceBuffer, mediaSource = this.mediaSource;\n if (!mediaSource || mediaSource.readyState !== 'open') {\n this._needsEos = false;\n return;\n }\n for (let type in sb) {\n let sbobj = sb[type];\n if (!sbobj.ended) {\n return;\n }\n\n if (sbobj.updating) {\n this._needsEos = true;\n return;\n }\n }\n logger.log('all media data are available, signal endOfStream() to MediaSource and stop loading fragment');\n // Notify the media element that it now has all of the media data\n try {\n mediaSource.endOfStream();\n } catch (e) {\n logger.warn('exception while calling mediaSource.endOfStream()');\n }\n this._needsEos = false;\n }\n\n onBufferFlushing (data) {\n this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type });\n // attempt flush immediately\n this.flushBufferCounter = 0;\n this.doFlush();\n }\n\n flushLiveBackBuffer () {\n // clear back buffer for live only\n if (!this._live) {\n return;\n }\n\n const liveBackBufferLength = this.hls.config.liveBackBufferLength;\n if (!isFinite(liveBackBufferLength) || liveBackBufferLength < 0) {\n return;\n }\n\n const currentTime = this.media.currentTime;\n const sourceBuffer = this.sourceBuffer;\n const bufferTypes = Object.keys(sourceBuffer);\n const targetBackBufferPosition = currentTime - Math.max(liveBackBufferLength, this._levelTargetDuration);\n\n for (let index = bufferTypes.length - 1; index >= 0; index--) {\n const bufferType = bufferTypes[index], buffered = sourceBuffer[bufferType].buffered;\n\n // when target buffer start exceeds actual buffer start\n if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {\n // remove buffer up until current time minus minimum back buffer length (removing buffer too close to current\n // time will lead to playback freezing)\n // credits for level target duration - https://github.com/videojs/http-streaming/blob/3132933b6aa99ddefab29c10447624efd6fd6e52/src/segment-loader.js#L91\n this.removeBufferRange(bufferType, sourceBuffer[bufferType], 0, targetBackBufferPosition);\n }\n }\n }\n\n onLevelUpdated ({ details }) {\n if (details.fragments.length > 0) {\n this._levelDuration = details.totalduration + details.fragments[0].start;\n this._levelTargetDuration = details.averagetargetduration || details.targetduration || 10;\n this._live = details.live;\n this.updateMediaElementDuration();\n }\n }\n\n /**\n * Update Media Source duration to current level duration or override to Infinity if configuration parameter\n * 'liveDurationInfinity` is set to `true`\n * More details: https://github.com/video-dev/hls.js/issues/355\n */\n updateMediaElementDuration () {\n let { config } = this.hls;\n let duration;\n\n if (this._levelDuration === null ||\n !this.media ||\n !this.mediaSource ||\n !this.sourceBuffer ||\n this.media.readyState === 0 ||\n this.mediaSource.readyState !== 'open') {\n return;\n }\n\n for (let type in this.sourceBuffer) {\n if (this.sourceBuffer[type].updating === true) {\n // can't set duration whilst a buffer is updating\n return;\n }\n }\n\n duration = this.media.duration;\n // initialise to the value that the media source is reporting\n if (this._msDuration === null) {\n this._msDuration = this.mediaSource.duration;\n }\n\n if (this._live === true && config.liveDurationInfinity === true) {\n // Override duration to Infinity\n logger.log('Media Source duration is set to Infinity');\n this._msDuration = this.mediaSource.duration = Infinity;\n } else if ((this._levelDuration > this._msDuration && this._levelDuration > duration) || !Number.isFinite(duration)) {\n // levelDuration was the last value we set.\n // not using mediaSource.duration as the browser may tweak this value\n // only update Media Source duration if its value increase, this is to avoid\n // flushing already buffered portion when switching between quality level\n logger.log(`Updating Media Source duration to ${this._levelDuration.toFixed(3)}`);\n this._msDuration = this.mediaSource.duration = this._levelDuration;\n }\n }\n\n doFlush () {\n // loop through all buffer ranges to flush\n while (this.flushRange.length) {\n let range = this.flushRange[0];\n // flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer\n if (this.flushBuffer(range.start, range.end, range.type)) {\n // range flushed, remove from flush array\n this.flushRange.shift();\n this.flushBufferCounter = 0;\n } else {\n this._needsFlush = true;\n // avoid looping, wait for SB update end to retrigger a flush\n return;\n }\n }\n if (this.flushRange.length === 0) {\n // everything flushed\n this._needsFlush = false;\n\n // let's recompute this.appended, which is used to avoid flush looping\n let appended = 0;\n let sourceBuffer = this.sourceBuffer;\n try {\n for (let type in sourceBuffer) {\n appended += sourceBuffer[type].buffered.length;\n }\n } catch (error) {\n // error could be thrown while accessing buffered, in case sourcebuffer has already been removed from MediaSource\n // this is harmess at this stage, catch this to avoid reporting an internal exception\n logger.error('error while accessing sourceBuffer.buffered');\n }\n this.appended = appended;\n this.hls.trigger(Event.BUFFER_FLUSHED);\n }\n }\n\n doAppending () {\n let { hls, segments, sourceBuffer } = this;\n if (Object.keys(sourceBuffer).length) {\n if (this.media.error) {\n this.segments = [];\n logger.error('trying to append although a media error occured, flush segment and abort');\n return;\n }\n if (this.appending) {\n // logger.log(`sb appending in progress`);\n return;\n }\n if (segments && segments.length) {\n let segment = segments.shift();\n try {\n let type = segment.type, sb = sourceBuffer[type];\n if (sb) {\n if (!sb.updating) {\n // reset sourceBuffer ended flag before appending segment\n sb.ended = false;\n // logger.log(`appending ${segment.content} ${type} SB, size:${segment.data.length}, ${segment.parent}`);\n this.parent = segment.parent;\n sb.appendBuffer(segment.data);\n this.appendError = 0;\n this.appended++;\n this.appending = true;\n } else {\n segments.unshift(segment);\n }\n } else {\n // in case we don't have any source buffer matching with this segment type,\n // it means that Mediasource fails to create sourcebuffer\n // discard this segment, and trigger update end\n this.onSBUpdateEnd();\n }\n } catch (err) {\n // in case any error occured while appending, put back segment in segments table\n logger.error(`error while trying to append buffer:${err.message}`);\n segments.unshift(segment);\n let event = { type: ErrorTypes.MEDIA_ERROR, parent: segment.parent };\n if (err.code !== 22) {\n if (this.appendError) {\n this.appendError++;\n } else {\n this.appendError = 1;\n }\n\n event.details = ErrorDetails.BUFFER_APPEND_ERROR;\n /* with UHD content, we could get loop of quota exceeded error until\n browser is able to evict some data from sourcebuffer. retrying help recovering this\n */\n if (this.appendError > hls.config.appendErrorMaxRetry) {\n logger.log(`fail ${hls.config.appendErrorMaxRetry} times to append segment in sourceBuffer`);\n this.segments = [];\n event.fatal = true;\n hls.trigger(Event.ERROR, event);\n } else {\n event.fatal = false;\n hls.trigger(Event.ERROR, event);\n }\n } else {\n // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror\n // let's stop appending any segments, and report BUFFER_FULL_ERROR error\n this.segments = [];\n event.details = ErrorDetails.BUFFER_FULL_ERROR;\n event.fatal = false;\n hls.trigger(Event.ERROR, event);\n }\n }\n }\n }\n }\n\n /*\n flush specified buffered range,\n return true once range has been flushed.\n as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end\n */\n flushBuffer (startOffset, endOffset, typeIn) {\n let sb;\n const sourceBuffer = this.sourceBuffer;\n if (Object.keys(sourceBuffer).length) {\n logger.log(`flushBuffer,pos/start/end: ${this.media.currentTime.toFixed(3)}/${startOffset}/${endOffset}`);\n // safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments\n if (this.flushBufferCounter < this.appended) {\n for (let type in sourceBuffer) {\n // check if sourcebuffer type is defined (typeIn): if yes, let's only flush this one\n // if no, let's flush all sourcebuffers\n if (typeIn && type !== typeIn) {\n continue;\n }\n\n sb = sourceBuffer[type];\n // we are going to flush buffer, mark source buffer as 'not ended'\n sb.ended = false;\n if (!sb.updating) {\n if (this.removeBufferRange(type, sb, startOffset, endOffset)) {\n this.flushBufferCounter++;\n return false;\n }\n } else {\n logger.warn('cannot flush, sb updating in progress');\n return false;\n }\n }\n } else {\n logger.warn('abort flushing too many retries');\n }\n logger.log('buffer flushed');\n }\n // everything flushed !\n return true;\n }\n\n /**\n * Removes first buffered range from provided source buffer that lies within given start and end offsets.\n *\n * @param type Type of the source buffer, logging purposes only.\n * @param sb Target SourceBuffer instance.\n * @param startOffset\n * @param endOffset\n *\n * @returns {boolean} True when source buffer remove requested.\n */\n removeBufferRange (type, sb, startOffset, endOffset) {\n try {\n for (let i = 0; i < sb.buffered.length; i++) {\n let bufStart = sb.buffered.start(i);\n let bufEnd = sb.buffered.end(i);\n let removeStart = Math.max(bufStart, startOffset);\n let removeEnd = Math.min(bufEnd, endOffset);\n\n /* sometimes sourcebuffer.remove() does not flush\n the exact expected time range.\n to avoid rounding issues/infinite loop,\n only flush buffer range of length greater than 500ms.\n */\n if (Math.min(removeEnd, bufEnd) - removeStart > 0.5) {\n logger.log(`sb remove ${type} [${removeStart},${removeEnd}], of [${bufStart},${bufEnd}], pos:${this.media.currentTime}`);\n sb.remove(removeStart, removeEnd);\n return true;\n }\n }\n } catch (error) {\n logger.warn('removeBufferRange failed', error);\n }\n\n return false;\n }\n}\n\nexport default BufferController;\n","/*\n * cap stream level to media size dimension controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\n\nclass CapLevelController extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.FPS_DROP_LEVEL_CAPPING,\n Event.MEDIA_ATTACHING,\n Event.MANIFEST_PARSED,\n Event.BUFFER_CODECS,\n Event.MEDIA_DETACHING);\n\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.firstLevel = null;\n this.levels = [];\n this.media = null;\n this.restrictedLevels = [];\n this.timer = null;\n }\n\n destroy () {\n if (this.hls.config.capLevelToPlayerSize) {\n this.media = null;\n this._stopCapping();\n }\n }\n\n onFpsDropLevelCapping (data) {\n // Don't add a restricted level more than once\n if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {\n this.restrictedLevels.push(data.droppedLevel);\n }\n }\n\n onMediaAttaching (data) {\n this.media = data.media instanceof window.HTMLVideoElement ? data.media : null;\n }\n\n onManifestParsed (data) {\n const hls = this.hls;\n this.restrictedLevels = [];\n this.levels = data.levels;\n this.firstLevel = data.firstLevel;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // Start capping immediately if the manifest has signaled video codecs\n this._startCapping();\n }\n }\n\n // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted\n // to the first level\n onBufferCodecs (data) {\n const hls = this.hls;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // If the manifest did not signal a video codec capping has been deferred until we're certain video is present\n this._startCapping();\n }\n }\n\n onLevelsUpdated (data) {\n this.levels = data.levels;\n }\n\n onMediaDetaching () {\n this._stopCapping();\n }\n\n detectPlayerSize () {\n if (this.media) {\n let levelsLength = this.levels ? this.levels.length : 0;\n if (levelsLength) {\n const hls = this.hls;\n hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1);\n if (hls.autoLevelCapping > this.autoLevelCapping) {\n // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch\n // usually happen when the user go to the fullscreen mode.\n hls.streamController.nextLevelSwitch();\n }\n this.autoLevelCapping = hls.autoLevelCapping;\n }\n }\n }\n\n /*\n * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)\n */\n getMaxLevel (capLevelIndex) {\n if (!this.levels) {\n return -1;\n }\n\n const validLevels = this.levels.filter((level, index) =>\n CapLevelController.isLevelAllowed(index, this.restrictedLevels) && index <= capLevelIndex\n );\n\n return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);\n }\n\n _startCapping () {\n if (this.timer) {\n // Don't reset capping if started twice; this can happen if the manifest signals a video codec\n return;\n }\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.hls.firstLevel = this.getMaxLevel(this.firstLevel);\n clearInterval(this.timer);\n this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);\n this.detectPlayerSize();\n }\n\n _stopCapping () {\n this.restrictedLevels = [];\n this.firstLevel = null;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n if (this.timer) {\n this.timer = clearInterval(this.timer);\n this.timer = null;\n }\n }\n\n get mediaWidth () {\n let width;\n const media = this.media;\n if (media) {\n width = media.width || media.clientWidth || media.offsetWidth;\n width *= CapLevelController.contentScaleFactor;\n }\n return width;\n }\n\n get mediaHeight () {\n let height;\n const media = this.media;\n if (media) {\n height = media.height || media.clientHeight || media.offsetHeight;\n height *= CapLevelController.contentScaleFactor;\n }\n return height;\n }\n\n static get contentScaleFactor () {\n let pixelRatio = 1;\n try {\n pixelRatio = window.devicePixelRatio;\n } catch (e) {}\n return pixelRatio;\n }\n\n static isLevelAllowed (level, restrictedLevels = []) {\n return restrictedLevels.indexOf(level) === -1;\n }\n\n static getMaxLevelByMediaSize (levels, width, height) {\n if (!levels || (levels && !levels.length)) {\n return -1;\n }\n\n // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next\n // to determine whether we've chosen the greatest bandwidth for the media's dimensions\n const atGreatestBandiwdth = (curLevel, nextLevel) => {\n if (!nextLevel) {\n return true;\n }\n\n return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;\n };\n\n // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to\n // the max level\n let maxLevelIndex = levels.length - 1;\n\n for (let i = 0; i < levels.length; i += 1) {\n const level = levels[i];\n if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {\n maxLevelIndex = i;\n break;\n }\n }\n\n return maxLevelIndex;\n }\n}\n\nexport default CapLevelController;\n","/*\n * FPS Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { logger } from '../utils/logger';\n\nconst { performance } = window;\n\nclass FPSController extends EventHandler {\n constructor (hls) {\n super(hls, Event.MEDIA_ATTACHING);\n }\n\n destroy () {\n if (this.timer) {\n clearInterval(this.timer);\n }\n\n this.isVideoPlaybackQualityAvailable = false;\n }\n\n onMediaAttaching (data) {\n const config = this.hls.config;\n if (config.capLevelOnFPSDrop) {\n const video = this.video = data.media instanceof window.HTMLVideoElement ? data.media : null;\n if (typeof video.getVideoPlaybackQuality === 'function') {\n this.isVideoPlaybackQualityAvailable = true;\n }\n\n clearInterval(this.timer);\n this.timer = setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);\n }\n }\n\n checkFPS (video, decodedFrames, droppedFrames) {\n let currentTime = performance.now();\n if (decodedFrames) {\n if (this.lastTime) {\n let currentPeriod = currentTime - this.lastTime,\n currentDropped = droppedFrames - this.lastDroppedFrames,\n currentDecoded = decodedFrames - this.lastDecodedFrames,\n droppedFPS = 1000 * currentDropped / currentPeriod,\n hls = this.hls;\n hls.trigger(Event.FPS_DROP, { currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames });\n if (droppedFPS > 0) {\n // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));\n if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {\n let currentLevel = hls.currentLevel;\n logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);\n if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {\n currentLevel = currentLevel - 1;\n hls.trigger(Event.FPS_DROP_LEVEL_CAPPING, { level: currentLevel, droppedLevel: hls.currentLevel });\n hls.autoLevelCapping = currentLevel;\n hls.streamController.nextLevelSwitch();\n }\n }\n }\n }\n this.lastTime = currentTime;\n this.lastDroppedFrames = droppedFrames;\n this.lastDecodedFrames = decodedFrames;\n }\n }\n\n checkFPSInterval () {\n const video = this.video;\n if (video) {\n if (this.isVideoPlaybackQualityAvailable) {\n let videoPlaybackQuality = video.getVideoPlaybackQuality();\n this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);\n } else {\n this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);\n }\n }\n }\n}\n\nexport default FPSController;\n","/**\n * XHR based logger\n*/\n\nimport { logger } from '../utils/logger';\n\nconst { performance, XMLHttpRequest } = window;\n\nclass XhrLoader {\n constructor (config) {\n if (config && config.xhrSetup) {\n this.xhrSetup = config.xhrSetup;\n }\n }\n\n destroy () {\n this.abort();\n this.loader = null;\n }\n\n abort () {\n let loader = this.loader;\n if (loader && loader.readyState !== 4) {\n this.stats.aborted = true;\n loader.abort();\n }\n\n window.clearTimeout(this.requestTimeout);\n this.requestTimeout = null;\n window.clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n }\n\n load (context, config, callbacks) {\n this.context = context;\n this.config = config;\n this.callbacks = callbacks;\n this.stats = { trequest: performance.now(), retry: 0 };\n this.retryDelay = config.retryDelay;\n this.loadInternal();\n }\n\n loadInternal () {\n let xhr, context = this.context;\n xhr = this.loader = new XMLHttpRequest();\n\n let stats = this.stats;\n stats.tfirst = 0;\n stats.loaded = 0;\n const xhrSetup = this.xhrSetup;\n\n try {\n if (xhrSetup) {\n try {\n xhrSetup(xhr, context.url);\n } catch (e) {\n // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader(\"Content-Language\", \"test\");}\n // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN\n xhr.open('GET', context.url, true);\n xhrSetup(xhr, context.url);\n }\n }\n if (!xhr.readyState) {\n xhr.open('GET', context.url, true);\n }\n } catch (e) {\n // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n this.callbacks.onError({ code: xhr.status, text: e.message }, context, xhr);\n return;\n }\n\n if (context.rangeEnd) {\n xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));\n }\n\n xhr.onreadystatechange = this.readystatechange.bind(this);\n xhr.onprogress = this.loadprogress.bind(this);\n xhr.responseType = context.responseType;\n\n // setup timeout before we perform request\n this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), this.config.timeout);\n xhr.send();\n }\n\n readystatechange (event) {\n let xhr = event.currentTarget,\n readyState = xhr.readyState,\n stats = this.stats,\n context = this.context,\n config = this.config;\n\n // don't proceed if xhr has been aborted\n if (stats.aborted) {\n return;\n }\n\n // >= HEADERS_RECEIVED\n if (readyState >= 2) {\n // clear xhr timeout and rearm it if readyState less than 4\n window.clearTimeout(this.requestTimeout);\n if (stats.tfirst === 0) {\n stats.tfirst = Math.max(performance.now(), stats.trequest);\n }\n\n if (readyState === 4) {\n let status = xhr.status;\n // http status between 200 to 299 are all successful\n if (status >= 200 && status < 300) {\n stats.tload = Math.max(stats.tfirst, performance.now());\n let data, len;\n if (context.responseType === 'arraybuffer') {\n data = xhr.response;\n len = data.byteLength;\n } else {\n data = xhr.responseText;\n len = data.length;\n }\n stats.loaded = stats.total = len;\n let response = { url: xhr.responseURL, data: data };\n this.callbacks.onSuccess(response, stats, context, xhr);\n } else {\n // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error\n if (stats.retry >= config.maxRetry || (status >= 400 && status < 499)) {\n logger.error(`${status} while loading ${context.url}`);\n this.callbacks.onError({ code: status, text: xhr.statusText }, context, xhr);\n } else {\n // retry\n logger.warn(`${status} while loading ${context.url}, retrying in ${this.retryDelay}...`);\n // aborts and resets internal state\n this.destroy();\n // schedule retry\n this.retryTimeout = window.setTimeout(this.loadInternal.bind(this), this.retryDelay);\n // set exponential backoff\n this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);\n stats.retry++;\n }\n }\n } else {\n // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet\n this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), config.timeout);\n }\n }\n }\n\n loadtimeout () {\n logger.warn(`timeout while loading ${this.context.url}`);\n this.callbacks.onTimeout(this.stats, this.context, null);\n }\n\n loadprogress (event) {\n let xhr = event.currentTarget,\n stats = this.stats;\n\n stats.loaded = event.loaded;\n if (event.lengthComputable) {\n stats.total = event.total;\n }\n\n let onProgress = this.callbacks.onProgress;\n if (onProgress) {\n // third arg is to provide on progress data\n onProgress(stats, this.context, null, xhr);\n }\n }\n}\n\nexport default XhrLoader;\n","import Event from '../events';\nimport TaskLoop from '../task-loop';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\n/**\n * @class AudioTrackController\n * @implements {EventHandler}\n *\n * Handles main manifest and audio-track metadata loaded,\n * owns and exposes the selectable audio-tracks data-models.\n *\n * Exposes internal interface to select available audio-tracks.\n *\n * Handles errors on loading audio-track playlists. Manages fallback mechanism\n * with redundants tracks (group-IDs).\n *\n * Handles level-loading and group-ID switches for video (fallback on video levels),\n * and eventually adapts the audio-track group-ID to match.\n *\n * @fires AUDIO_TRACK_LOADING\n * @fires AUDIO_TRACK_SWITCHING\n * @fires AUDIO_TRACKS_UPDATED\n * @fires ERROR\n *\n */\nclass AudioTrackController extends TaskLoop {\n constructor (hls) {\n super(hls,\n Event.MANIFEST_LOADING,\n Event.MANIFEST_PARSED,\n Event.AUDIO_TRACK_LOADED,\n Event.AUDIO_TRACK_SWITCHED,\n Event.LEVEL_LOADED,\n Event.ERROR\n );\n\n /**\n * @private\n * Currently selected index in `tracks`\n * @member {number} trackId\n */\n this._trackId = -1;\n\n /**\n * @private\n * If should select tracks according to default track attribute\n * @member {boolean} _selectDefaultTrack\n */\n this._selectDefaultTrack = true;\n\n /**\n * @public\n * All tracks available\n * @member {AudioTrack[]}\n */\n this.tracks = [];\n\n /**\n * @public\n * List of blacklisted audio track IDs (that have caused failure)\n * @member {number[]}\n */\n this.trackIdBlacklist = Object.create(null);\n\n /**\n * @public\n * The currently running group ID for audio\n * (we grab this on manifest-parsed and new level-loaded)\n * @member {string}\n */\n this.audioGroupId = null;\n }\n\n /**\n * Reset audio tracks on new manifest loading.\n */\n onManifestLoading () {\n this.tracks = [];\n this._trackId = -1;\n this._selectDefaultTrack = true;\n }\n\n /**\n * Store tracks data from manifest parsed data.\n *\n * Trigger AUDIO_TRACKS_UPDATED event.\n *\n * @param {*} data\n */\n onManifestParsed (data) {\n const tracks = this.tracks = data.audioTracks || [];\n this.hls.trigger(Event.AUDIO_TRACKS_UPDATED, { audioTracks: tracks });\n }\n\n /**\n * Store track details of loaded track in our data-model.\n *\n * Set-up metadata update interval task for live-mode streams.\n *\n * @param {} data\n */\n onAudioTrackLoaded (data) {\n if (data.id >= this.tracks.length) {\n logger.warn('Invalid audio track id:', data.id);\n return;\n }\n\n logger.log(`audioTrack ${data.id} loaded`);\n\n this.tracks[data.id].details = data.details;\n\n // check if current playlist is a live playlist\n // and if we have already our reload interval setup\n if (data.details.live && !this.hasInterval()) {\n // if live playlist we will have to reload it periodically\n // set reload period to playlist target duration\n const updatePeriodMs = data.details.targetduration * 1000;\n this.setInterval(updatePeriodMs);\n }\n\n if (!data.details.live && this.hasInterval()) {\n // playlist is not live and timer is scheduled: cancel it\n this.clearInterval();\n }\n }\n\n /**\n * Update the internal group ID to any audio-track we may have set manually\n * or because of a failure-handling fallback.\n *\n * Quality-levels should update to that group ID in this case.\n *\n * @param {*} data\n */\n onAudioTrackSwitched (data) {\n const audioGroupId = this.tracks[data.id].groupId;\n if (audioGroupId && (this.audioGroupId !== audioGroupId)) {\n this.audioGroupId = audioGroupId;\n }\n }\n\n /**\n * When a level gets loaded, if it has redundant audioGroupIds (in the same ordinality as it's redundant URLs)\n * we are setting our audio-group ID internally to the one set, if it is different from the group ID currently set.\n *\n * If group-ID got update, we re-select the appropriate audio-track with this group-ID matching the currently\n * selected one (based on NAME property).\n *\n * @param {*} data\n */\n onLevelLoaded (data) {\n // FIXME: crashes because currentLevel is undefined\n // const levelInfo = this.hls.levels[this.hls.currentLevel];\n\n const levelInfo = this.hls.levels[data.level];\n\n if (!levelInfo.audioGroupIds) {\n return;\n }\n\n const audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];\n if (this.audioGroupId !== audioGroupId) {\n this.audioGroupId = audioGroupId;\n this._selectInitialAudioTrack();\n }\n }\n\n /**\n * Handle network errors loading audio track manifests\n * and also pausing on any netwok errors.\n *\n * @param {ErrorEventData} data\n */\n onError (data) {\n // Only handle network errors\n if (data.type !== ErrorTypes.NETWORK_ERROR) {\n return;\n }\n\n // If fatal network error, cancel update task\n if (data.fatal) {\n this.clearInterval();\n }\n\n // If not an audio-track loading error don't handle further\n if (data.details !== ErrorDetails.AUDIO_TRACK_LOAD_ERROR) {\n return;\n }\n\n logger.warn('Network failure on audio-track id:', data.context.id);\n this._handleLoadError();\n }\n\n /**\n * @type {AudioTrack[]} Audio-track list we own\n */\n get audioTracks () {\n return this.tracks;\n }\n\n /**\n * @type {number} Index into audio-tracks list of currently selected track.\n */\n get audioTrack () {\n return this._trackId;\n }\n\n /**\n * Select current track by index\n */\n set audioTrack (newId) {\n this._setAudioTrack(newId);\n // If audio track is selected from API then don't choose from the manifest default track\n this._selectDefaultTrack = false;\n }\n\n /**\n * @private\n * @param {number} newId\n */\n _setAudioTrack (newId) {\n // noop on same audio track id as already set\n if (this._trackId === newId && this.tracks[this._trackId].details) {\n logger.debug('Same id as current audio-track passed, and track details available -> no-op');\n return;\n }\n\n // check if level idx is valid\n if (newId < 0 || newId >= this.tracks.length) {\n logger.warn('Invalid id passed to audio-track controller');\n return;\n }\n\n const audioTrack = this.tracks[newId];\n\n logger.log(`Now switching to audio-track index ${newId}`);\n\n // stopping live reloading timer if any\n this.clearInterval();\n this._trackId = newId;\n\n const { url, type, id } = audioTrack;\n this.hls.trigger(Event.AUDIO_TRACK_SWITCHING, { id, type, url });\n this._loadTrackDetailsIfNeeded(audioTrack);\n }\n\n /**\n * @override\n */\n doTick () {\n this._updateTrack(this._trackId);\n }\n\n /**\n * Select initial track\n * @private\n */\n _selectInitialAudioTrack () {\n let tracks = this.tracks;\n if (!tracks.length) {\n return;\n }\n\n const currentAudioTrack = this.tracks[this._trackId];\n\n let name = null;\n if (currentAudioTrack) {\n name = currentAudioTrack.name;\n }\n\n // Pre-select default tracks if there are any\n if (this._selectDefaultTrack) {\n const defaultTracks = tracks.filter((track) => track.default);\n if (defaultTracks.length) {\n tracks = defaultTracks;\n } else {\n logger.warn('No default audio tracks defined');\n }\n }\n\n let trackFound = false;\n\n const traverseTracks = () => {\n // Select track with right group ID\n tracks.forEach((track) => {\n if (trackFound) {\n return;\n }\n // We need to match the (pre-)selected group ID\n // and the NAME of the current track.\n if ((!this.audioGroupId || track.groupId === this.audioGroupId) &&\n (!name || name === track.name)) {\n // If there was a previous track try to stay with the same `NAME`.\n // It should be unique across tracks of same group, and consistent through redundant track groups.\n this._setAudioTrack(track.id);\n trackFound = true;\n }\n });\n };\n\n traverseTracks();\n\n if (!trackFound) {\n name = null;\n traverseTracks();\n }\n\n if (!trackFound) {\n logger.error(`No track found for running audio group-ID: ${this.audioGroupId}`);\n\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR,\n fatal: true\n });\n }\n }\n\n /**\n * @private\n * @param {AudioTrack} audioTrack\n * @returns {boolean}\n */\n _needsTrackLoading (audioTrack) {\n const { details, url } = audioTrack;\n\n if (!details || details.live) {\n // check if we face an audio track embedded in main playlist (audio track without URI attribute)\n return !!url;\n }\n\n return false;\n }\n\n /**\n * @private\n * @param {AudioTrack} audioTrack\n */\n _loadTrackDetailsIfNeeded (audioTrack) {\n if (this._needsTrackLoading(audioTrack)) {\n const { url, id } = audioTrack;\n // track not retrieved yet, or live playlist we need to (re)load it\n logger.log(`loading audio-track playlist for id: ${id}`);\n this.hls.trigger(Event.AUDIO_TRACK_LOADING, { url, id });\n }\n }\n\n /**\n * @private\n * @param {number} newId\n */\n _updateTrack (newId) {\n // check if level idx is valid\n if (newId < 0 || newId >= this.tracks.length) {\n return;\n }\n\n // stopping live reloading timer if any\n this.clearInterval();\n this._trackId = newId;\n logger.log(`trying to update audio-track ${newId}`);\n const audioTrack = this.tracks[newId];\n this._loadTrackDetailsIfNeeded(audioTrack);\n }\n\n /**\n * @private\n */\n _handleLoadError () {\n // First, let's black list current track id\n this.trackIdBlacklist[this._trackId] = true;\n\n // Let's try to fall back on a functional audio-track with the same group ID\n const previousId = this._trackId;\n const { name, language, groupId } = this.tracks[previousId];\n\n logger.warn(`Loading failed on audio track id: ${previousId}, group-id: ${groupId}, name/language: \"${name}\" / \"${language}\"`);\n\n // Find a non-blacklisted track ID with the same NAME\n // At least a track that is not blacklisted, thus on another group-ID.\n let newId = previousId;\n for (let i = 0; i < this.tracks.length; i++) {\n if (this.trackIdBlacklist[i]) {\n continue;\n }\n const newTrack = this.tracks[i];\n if (newTrack.name === name) {\n newId = i;\n break;\n }\n }\n\n if (newId === previousId) {\n logger.warn(`No fallback audio-track found for name/language: \"${name}\" / \"${language}\"`);\n return;\n }\n\n logger.log('Attempting audio-track fallback id:', newId, 'group-id:', this.tracks[newId].groupId);\n\n this._setAudioTrack(newId);\n }\n}\n\nexport default AudioTrackController;\n","/*\n * Audio Stream Controller\n*/\n\nimport BinarySearch from '../utils/binary-search';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport Demuxer from '../demux/demuxer';\nimport Event from '../events';\nimport * as LevelHelper from './level-helper';\nimport TimeRanges from '../utils/time-ranges';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport { findFragWithCC } from '../utils/discontinuities';\nimport { FragmentState } from './fragment-tracker';\nimport Fragment from '../loader/fragment';\nimport BaseStreamController, { State } from './base-stream-controller';\nconst { performance } = window;\n\nconst TICK_INTERVAL = 100; // how often to tick in ms\n\nclass AudioStreamController extends BaseStreamController {\n constructor (hls, fragmentTracker) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.AUDIO_TRACKS_UPDATED,\n Event.AUDIO_TRACK_SWITCHING,\n Event.AUDIO_TRACK_LOADED,\n Event.KEY_LOADED,\n Event.FRAG_LOADED,\n Event.FRAG_PARSING_INIT_SEGMENT,\n Event.FRAG_PARSING_DATA,\n Event.FRAG_PARSED,\n Event.ERROR,\n Event.BUFFER_RESET,\n Event.BUFFER_CREATED,\n Event.BUFFER_APPENDED,\n Event.BUFFER_FLUSHED,\n Event.INIT_PTS_FOUND);\n this.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.audioCodecSwap = false;\n this._state = State.STOPPED;\n this.initPTS = [];\n this.waitingFragment = null;\n this.videoTrackCC = null;\n }\n\n // Signal that video PTS was found\n onInitPtsFound (data) {\n let demuxerId = data.id, cc = data.frag.cc, initPTS = data.initPTS;\n if (demuxerId === 'main') {\n // Always update the new INIT PTS\n // Can change due level switch\n this.initPTS[cc] = initPTS;\n this.videoTrackCC = cc;\n logger.log(`InitPTS for cc: ${cc} found from video track: ${initPTS}`);\n\n // If we are waiting we need to demux/remux the waiting frag\n // With the new initPTS\n if (this.state === State.WAITING_INIT_PTS) {\n this.tick();\n }\n }\n }\n\n startLoad (startPosition) {\n if (this.tracks) {\n let lastCurrentTime = this.lastCurrentTime;\n this.stopLoad();\n this.setInterval(TICK_INTERVAL);\n this.fragLoadError = 0;\n if (lastCurrentTime > 0 && startPosition === -1) {\n logger.log(`audio:override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);\n this.state = State.IDLE;\n } else {\n this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition;\n this.state = State.STARTING;\n }\n this.nextLoadPosition = this.startPosition = this.lastCurrentTime;\n this.tick();\n } else {\n this.startPosition = startPosition;\n this.state = State.STOPPED;\n }\n }\n\n set state (nextState) {\n if (this.state !== nextState) {\n const previousState = this.state;\n this._state = nextState;\n logger.log(`audio stream:${previousState}->${nextState}`);\n }\n }\n\n get state () {\n return this._state;\n }\n\n doTick () {\n let pos, track, trackDetails, hls = this.hls, config = hls.config;\n // logger.log('audioStream:' + this.state);\n switch (this.state) {\n case State.ERROR:\n // don't do anything in error state to avoid breaking further ...\n case State.PAUSED:\n // don't do anything in paused state either ...\n case State.BUFFER_FLUSHING:\n break;\n case State.STARTING:\n this.state = State.WAITING_TRACK;\n this.loadedmetadata = false;\n break;\n case State.IDLE:\n const tracks = this.tracks;\n // audio tracks not received => exit loop\n if (!tracks) {\n break;\n }\n\n // if video not attached AND\n // start fragment already requested OR start frag prefetch disable\n // exit loop\n // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop\n if (!this.media &&\n (this.startFragRequested || !config.startFragPrefetch)) {\n break;\n }\n\n // determine next candidate fragment to be loaded, based on current position and\n // end of buffer position\n // if we have not yet loaded any fragment, start loading from start position\n if (this.loadedmetadata) {\n pos = this.media.currentTime;\n } else {\n pos = this.nextLoadPosition;\n if (pos === undefined) {\n break;\n }\n }\n let media = this.mediaBuffer ? this.mediaBuffer : this.media,\n videoBuffer = this.videoBuffer ? this.videoBuffer : this.media,\n bufferInfo = BufferHelper.bufferInfo(media, pos, config.maxBufferHole),\n mainBufferInfo = BufferHelper.bufferInfo(videoBuffer, pos, config.maxBufferHole),\n bufferLen = bufferInfo.len,\n bufferEnd = bufferInfo.end,\n fragPrevious = this.fragPrevious,\n // ensure we buffer at least config.maxBufferLength (default 30s) or config.maxMaxBufferLength (default: 600s)\n // whichever is smaller.\n // once we reach that threshold, don't buffer more than video (mainBufferInfo.len)\n maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength),\n maxBufLen = Math.max(maxConfigBuffer, mainBufferInfo.len),\n audioSwitch = this.audioSwitch,\n trackId = this.trackId;\n\n // if buffer length is less than maxBufLen try to load a new fragment\n if ((bufferLen < maxBufLen || audioSwitch) && trackId < tracks.length) {\n trackDetails = tracks[trackId].details;\n // if track info not retrieved yet, switch state and wait for track retrieval\n if (typeof trackDetails === 'undefined') {\n this.state = State.WAITING_TRACK;\n break;\n }\n\n if (!audioSwitch && this._streamEnded(bufferInfo, trackDetails)) {\n this.hls.trigger(Event.BUFFER_EOS, { type: 'audio' });\n this.state = State.ENDED;\n return;\n }\n\n // find fragment index, contiguous with end of buffer position\n let fragments = trackDetails.fragments,\n fragLen = fragments.length,\n start = fragments[0].start,\n end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,\n frag;\n\n // When switching audio track, reload audio as close as possible to currentTime\n if (audioSwitch) {\n if (trackDetails.live && !trackDetails.PTSKnown) {\n logger.log('switching audiotrack, live stream, unknown PTS,load first fragment');\n bufferEnd = 0;\n } else {\n bufferEnd = pos;\n // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime\n if (trackDetails.PTSKnown && pos < start) {\n // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start\n if (bufferInfo.end > start || bufferInfo.nextStart) {\n logger.log('alt audio track ahead of main track, seek to start of alt audio track');\n this.media.currentTime = start + 0.05;\n } else {\n return;\n }\n }\n }\n }\n if (trackDetails.initSegment && !trackDetails.initSegment.data) {\n frag = trackDetails.initSegment;\n } // eslint-disable-line brace-style\n // if bufferEnd before start of playlist, load first fragment\n else if (bufferEnd <= start) {\n frag = fragments[0];\n if (this.videoTrackCC !== null && frag.cc !== this.videoTrackCC) {\n // Ensure we find a fragment which matches the continuity of the video track\n frag = findFragWithCC(fragments, this.videoTrackCC);\n }\n if (trackDetails.live && frag.loadIdx && frag.loadIdx === this.fragLoadIdx) {\n // we just loaded this first fragment, and we are still lagging behind the start of the live playlist\n // let's force seek to start\n const nextBuffered = bufferInfo.nextStart ? bufferInfo.nextStart : start;\n logger.log(`no alt audio available @currentTime:${this.media.currentTime}, seeking @${nextBuffered + 0.05}`);\n this.media.currentTime = nextBuffered + 0.05;\n return;\n }\n } else {\n let foundFrag;\n let maxFragLookUpTolerance = config.maxFragLookUpTolerance;\n const fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;\n let fragmentWithinToleranceTest = (candidate) => {\n // offset should be within fragment boundary - config.maxFragLookUpTolerance\n // this is to cope with situations like\n // bufferEnd = 9.991\n // frag[Ø] : [0,10]\n // frag[1] : [10,20]\n // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here\n // frag start frag start+duration\n // |-----------------------------|\n // <---> <--->\n // ...--------><-----------------------------><---------....\n // previous frag matching fragment next frag\n // return -1 return 0 return 1\n // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);\n // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments\n let candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration);\n if ((candidate.start + candidate.duration - candidateLookupTolerance) <= bufferEnd) {\n return 1;\n } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n return -1;\n }\n\n return 0;\n };\n\n if (bufferEnd < end) {\n if (bufferEnd > end - maxFragLookUpTolerance) {\n maxFragLookUpTolerance = 0;\n }\n\n // Prefer the next fragment if it's within tolerance\n if (fragNext && !fragmentWithinToleranceTest(fragNext)) {\n foundFrag = fragNext;\n } else {\n foundFrag = BinarySearch.search(fragments, fragmentWithinToleranceTest);\n }\n } else {\n // reach end of playlist\n foundFrag = fragments[fragLen - 1];\n }\n if (foundFrag) {\n frag = foundFrag;\n start = foundFrag.start;\n // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);\n if (fragPrevious && frag.level === fragPrevious.level && frag.sn === fragPrevious.sn) {\n if (frag.sn < trackDetails.endSN) {\n frag = fragments[frag.sn + 1 - trackDetails.startSN];\n logger.log(`SN just loaded, load next one: ${frag.sn}`);\n } else {\n frag = null;\n }\n }\n }\n }\n if (frag) {\n // logger.log(' loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));\n if (frag.encrypted) {\n logger.log(`Loading key for ${frag.sn} of [${trackDetails.startSN} ,${trackDetails.endSN}],track ${trackId}`);\n this.state = State.KEY_LOADING;\n hls.trigger(Event.KEY_LOADING, { frag: frag });\n } else {\n logger.log(`Loading ${frag.sn}, cc: ${frag.cc} of [${trackDetails.startSN} ,${trackDetails.endSN}],track ${trackId}, currentTime:${pos},bufferEnd:${bufferEnd.toFixed(3)}`);\n // only load if fragment is not loaded or if in audio switch\n // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch\n this.fragCurrent = frag;\n if (audioSwitch || this.fragmentTracker.getState(frag) === FragmentState.NOT_LOADED) {\n this.startFragRequested = true;\n if (Number.isFinite(frag.sn)) {\n this.nextLoadPosition = frag.start + frag.duration;\n }\n\n hls.trigger(Event.FRAG_LOADING, { frag });\n this.state = State.FRAG_LOADING;\n }\n }\n }\n }\n break;\n case State.WAITING_TRACK:\n track = this.tracks[this.trackId];\n // check if playlist is already loaded\n if (track && track.details) {\n this.state = State.IDLE;\n }\n\n break;\n case State.FRAG_LOADING_WAITING_RETRY:\n var now = performance.now();\n var retryDate = this.retryDate;\n media = this.media;\n var isSeeking = media && media.seeking;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if (!retryDate || (now >= retryDate) || isSeeking) {\n logger.log('audioStreamController: retryDate reached, switch back to IDLE state');\n this.state = State.IDLE;\n }\n break;\n case State.WAITING_INIT_PTS:\n const videoTrackCC = this.videoTrackCC;\n if (this.initPTS[videoTrackCC] === undefined) {\n break;\n }\n\n // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS\n const waitingFrag = this.waitingFragment;\n if (waitingFrag) {\n const waitingFragCC = waitingFrag.frag.cc;\n if (videoTrackCC !== waitingFragCC) {\n track = this.tracks[this.trackId];\n if (track.details && track.details.live) {\n logger.warn(`Waiting fragment CC (${waitingFragCC}) does not match video track CC (${videoTrackCC})`);\n this.waitingFragment = null;\n this.state = State.IDLE;\n }\n } else {\n this.state = State.FRAG_LOADING;\n this.onFragLoaded(this.waitingFragment);\n this.waitingFragment = null;\n }\n } else {\n this.state = State.IDLE;\n }\n\n break;\n case State.STOPPED:\n case State.FRAG_LOADING:\n case State.PARSING:\n case State.PARSED:\n case State.ENDED:\n break;\n default:\n break;\n }\n }\n\n onMediaAttached (data) {\n let media = this.media = this.mediaBuffer = data.media;\n this.onvseeking = this.onMediaSeeking.bind(this);\n this.onvended = this.onMediaEnded.bind(this);\n media.addEventListener('seeking', this.onvseeking);\n media.addEventListener('ended', this.onvended);\n let config = this.config;\n if (this.tracks && config.autoStartLoad) {\n this.startLoad(config.startPosition);\n }\n }\n\n onMediaDetaching () {\n let media = this.media;\n if (media && media.ended) {\n logger.log('MSE detaching and video ended, reset startPosition');\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n // remove video listeners\n if (media) {\n media.removeEventListener('seeking', this.onvseeking);\n media.removeEventListener('ended', this.onvended);\n this.onvseeking = this.onvseeked = this.onvended = null;\n }\n this.media = this.mediaBuffer = this.videoBuffer = null;\n this.loadedmetadata = false;\n this.stopLoad();\n }\n\n onAudioTracksUpdated (data) {\n logger.log('audio tracks updated');\n this.tracks = data.audioTracks;\n }\n\n onAudioTrackSwitching (data) {\n // if any URL found on new audio track, it is an alternate audio track\n let altAudio = !!data.url;\n this.trackId = data.id;\n\n this.fragCurrent = null;\n this.state = State.PAUSED;\n this.waitingFragment = null;\n // destroy useless demuxer when switching audio to main\n if (!altAudio) {\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n } else {\n // switching to audio track, start timer if not already started\n this.setInterval(TICK_INTERVAL);\n }\n\n // should we switch tracks ?\n if (altAudio) {\n this.audioSwitch = true;\n // main audio track are handled by stream-controller, just do something if switching to alt audio track\n this.state = State.IDLE;\n }\n this.tick();\n }\n\n onAudioTrackLoaded (data) {\n let newDetails = data.details,\n trackId = data.id,\n track = this.tracks[trackId],\n duration = newDetails.totalduration,\n sliding = 0;\n\n logger.log(`track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}],duration:${duration}`);\n\n if (newDetails.live) {\n let curDetails = track.details;\n if (curDetails && newDetails.fragments.length > 0) {\n // we already have details for that level, merge them\n LevelHelper.mergeDetails(curDetails, newDetails);\n sliding = newDetails.fragments[0].start;\n // TODO\n // this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);\n if (newDetails.PTSKnown) {\n logger.log(`live audio playlist sliding:${sliding.toFixed(3)}`);\n } else {\n logger.log('live audio playlist - outdated PTS, unknown sliding');\n }\n } else {\n newDetails.PTSKnown = false;\n logger.log('live audio playlist - first load, unknown sliding');\n }\n } else {\n newDetails.PTSKnown = false;\n }\n track.details = newDetails;\n\n // compute start position\n if (!this.startFragRequested) {\n // compute start position if set to -1. use it straight away if value is defined\n if (this.startPosition === -1) {\n // first, check if start time offset has been set in playlist, if yes, use this value\n let startTimeOffset = newDetails.startTimeOffset;\n if (Number.isFinite(startTimeOffset)) {\n logger.log(`start time offset found in playlist, adjust startPosition to ${startTimeOffset}`);\n this.startPosition = startTimeOffset;\n } else {\n this.startPosition = 0;\n }\n }\n this.nextLoadPosition = this.startPosition;\n }\n // only switch batck to IDLE state if we were waiting for track to start downloading a new fragment\n if (this.state === State.WAITING_TRACK) {\n this.state = State.IDLE;\n }\n\n // trigger handler right now\n this.tick();\n }\n\n onKeyLoaded () {\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n this.tick();\n }\n }\n\n onFragLoaded (data) {\n let fragCurrent = this.fragCurrent,\n fragLoaded = data.frag;\n if (this.state === State.FRAG_LOADING &&\n fragCurrent &&\n fragLoaded.type === 'audio' &&\n fragLoaded.level === fragCurrent.level &&\n fragLoaded.sn === fragCurrent.sn) {\n let track = this.tracks[this.trackId],\n details = track.details,\n duration = details.totalduration,\n trackId = fragCurrent.level,\n sn = fragCurrent.sn,\n cc = fragCurrent.cc,\n audioCodec = this.config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2',\n stats = this.stats = data.stats;\n if (sn === 'initSegment') {\n this.state = State.IDLE;\n\n stats.tparsed = stats.tbuffered = performance.now();\n details.initSegment.data = data.payload;\n this.hls.trigger(Event.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'audio' });\n this.tick();\n } else {\n this.state = State.PARSING;\n // transmux the MPEG-TS data to ISO-BMFF segments\n this.appended = false;\n if (!this.demuxer) {\n this.demuxer = new Demuxer(this.hls, 'audio');\n }\n\n // Check if we have video initPTS\n // If not we need to wait for it\n let initPTS = this.initPTS[cc];\n let initSegmentData = details.initSegment ? details.initSegment.data : [];\n if (details.initSegment || initPTS !== undefined) {\n this.pendingBuffering = true;\n logger.log(`Demuxing ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);\n // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)\n let accurateTimeOffset = false; // details.PTSKnown || !details.live;\n this.demuxer.push(data.payload, initSegmentData, audioCodec, null, fragCurrent, duration, accurateTimeOffset, initPTS);\n } else {\n logger.log(`unknown video PTS for continuity counter ${cc}, waiting for video PTS before demuxing audio frag ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);\n this.waitingFragment = data;\n this.state = State.WAITING_INIT_PTS;\n }\n }\n }\n this.fragLoadError = 0;\n }\n\n onFragParsingInitSegment (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'audio' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n let tracks = data.tracks, track;\n\n // delete any video track found on audio demuxer\n if (tracks.video) {\n delete tracks.video;\n }\n\n // include levelCodec in audio and video tracks\n track = tracks.audio;\n if (track) {\n track.levelCodec = track.codec;\n track.id = data.id;\n this.hls.trigger(Event.BUFFER_CODECS, tracks);\n logger.log(`audio track:audio,container:${track.container},codecs[level/parsed]=[${track.levelCodec}/${track.codec}]`);\n let initSegment = track.initSegment;\n if (initSegment) {\n let appendObj = { type: 'audio', data: initSegment, parent: 'audio', content: 'initSegment' };\n if (this.audioSwitch) {\n this.pendingData = [appendObj];\n } else {\n this.appended = true;\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n this.hls.trigger(Event.BUFFER_APPENDING, appendObj);\n }\n }\n // trigger handler right now\n this.tick();\n }\n }\n }\n\n onFragParsingData (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'audio' &&\n data.type === 'audio' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n let trackId = this.trackId,\n track = this.tracks[trackId],\n hls = this.hls;\n\n if (!Number.isFinite(data.endPTS)) {\n data.endPTS = data.startPTS + fragCurrent.duration;\n data.endDTS = data.startDTS + fragCurrent.duration;\n }\n\n fragCurrent.addElementaryStream(Fragment.ElementaryStreamTypes.AUDIO);\n\n logger.log(`parsed ${data.type},PTS:[${data.startPTS.toFixed(3)},${data.endPTS.toFixed(3)}],DTS:[${data.startDTS.toFixed(3)}/${data.endDTS.toFixed(3)}],nb:${data.nb}`);\n LevelHelper.updateFragPTSDTS(track.details, fragCurrent, data.startPTS, data.endPTS);\n\n let audioSwitch = this.audioSwitch, media = this.media, appendOnBufferFlush = false;\n // Only flush audio from old audio tracks when PTS is known on new audio track\n if (audioSwitch && media) {\n if (media.readyState) {\n let currentTime = media.currentTime;\n logger.log('switching audio track : currentTime:' + currentTime);\n if (currentTime >= data.startPTS) {\n logger.log('switching audio track : flushing all audio');\n this.state = State.BUFFER_FLUSHING;\n hls.trigger(Event.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });\n appendOnBufferFlush = true;\n // Lets announce that the initial audio track switch flush occur\n this.audioSwitch = false;\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, { id: trackId });\n }\n } else {\n // Lets announce that the initial audio track switch flush occur\n this.audioSwitch = false;\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, { id: trackId });\n }\n }\n\n let pendingData = this.pendingData;\n\n if (!pendingData) {\n logger.warn('Apparently attempt to enqueue media payload without codec initialization data upfront');\n hls.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: null, fatal: true });\n return;\n }\n\n if (!this.audioSwitch) {\n [data.data1, data.data2].forEach(buffer => {\n if (buffer && buffer.length) {\n pendingData.push({ type: data.type, data: buffer, parent: 'audio', content: 'data' });\n }\n });\n if (!appendOnBufferFlush && pendingData.length) {\n pendingData.forEach(appendObj => {\n // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)\n // in that case it is useless to append following segments\n if (this.state === State.PARSING) {\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n this.hls.trigger(Event.BUFFER_APPENDING, appendObj);\n }\n });\n this.pendingData = [];\n this.appended = true;\n }\n }\n // trigger handler right now\n this.tick();\n }\n }\n\n onFragParsed (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'audio' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n this.stats.tparsed = performance.now();\n this.state = State.PARSED;\n this._checkAppendedParsed();\n }\n }\n\n onBufferReset () {\n // reset reference to sourcebuffers\n this.mediaBuffer = this.videoBuffer = null;\n this.loadedmetadata = false;\n }\n\n onBufferCreated (data) {\n let audioTrack = data.tracks.audio;\n if (audioTrack) {\n this.mediaBuffer = audioTrack.buffer;\n this.loadedmetadata = true;\n }\n if (data.tracks.video) {\n this.videoBuffer = data.tracks.video.buffer;\n }\n }\n\n onBufferAppended (data) {\n if (data.parent === 'audio') {\n const state = this.state;\n if (state === State.PARSING || state === State.PARSED) {\n // check if all buffers have been appended\n this.pendingBuffering = (data.pending > 0);\n this._checkAppendedParsed();\n }\n }\n }\n\n _checkAppendedParsed () {\n // trigger handler right now\n if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {\n let frag = this.fragCurrent, stats = this.stats, hls = this.hls;\n if (frag) {\n this.fragPrevious = frag;\n stats.tbuffered = performance.now();\n hls.trigger(Event.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'audio' });\n let media = this.mediaBuffer ? this.mediaBuffer : this.media;\n logger.log(`audio buffered : ${TimeRanges.toString(media.buffered)}`);\n if (this.audioSwitch && this.appended) {\n this.audioSwitch = false;\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, { id: this.trackId });\n }\n this.state = State.IDLE;\n }\n this.tick();\n }\n }\n\n onError (data) {\n let frag = data.frag;\n // don't handle frag error not related to audio fragment\n if (frag && frag.type !== 'audio') {\n return;\n }\n\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n const frag = data.frag;\n // don't handle frag error not related to audio fragment\n if (frag && frag.type !== 'audio') {\n break;\n }\n\n if (!data.fatal) {\n let loadError = this.fragLoadError;\n if (loadError) {\n loadError++;\n } else {\n loadError = 1;\n }\n\n const config = this.config;\n if (loadError <= config.fragLoadingMaxRetry) {\n this.fragLoadError = loadError;\n // exponential backoff capped to config.fragLoadingMaxRetryTimeout\n const delay = Math.min(Math.pow(2, loadError - 1) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);\n logger.warn(`AudioStreamController: frag loading failed, retry in ${delay} ms`);\n this.retryDate = performance.now() + delay;\n // retry loading state\n this.state = State.FRAG_LOADING_WAITING_RETRY;\n } else {\n logger.error(`AudioStreamController: ${data.details} reaches max retry, redispatch as fatal ...`);\n // switch error to fatal\n data.fatal = true;\n this.state = State.ERROR;\n }\n }\n break;\n case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:\n case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n // when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received\n if (this.state !== State.ERROR) {\n // if fatal error, stop processing, otherwise move to IDLE to retry loading\n this.state = data.fatal ? State.ERROR : State.IDLE;\n logger.warn(`AudioStreamController: ${data.details} while loading frag, now switching to ${this.state} state ...`);\n }\n break;\n case ErrorDetails.BUFFER_FULL_ERROR:\n // if in appending state\n if (data.parent === 'audio' && (this.state === State.PARSING || this.state === State.PARSED)) {\n const media = this.mediaBuffer,\n currentTime = this.media.currentTime,\n mediaBuffered = media && BufferHelper.isBuffered(media, currentTime) && BufferHelper.isBuffered(media, currentTime + 0.5);\n // reduce max buf len if current position is buffered\n if (mediaBuffered) {\n const config = this.config;\n if (config.maxMaxBufferLength >= config.maxBufferLength) {\n // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...\n config.maxMaxBufferLength /= 2;\n logger.warn(`AudioStreamController: reduce max buffer length to ${config.maxMaxBufferLength}s`);\n }\n this.state = State.IDLE;\n } else {\n // current position is not buffered, but browser is still complaining about buffer full error\n // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708\n // in that case flush the whole audio buffer to recover\n logger.warn('AudioStreamController: buffer full error also media.currentTime is not buffered, flush audio buffer');\n this.fragCurrent = null;\n // flush everything\n this.state = State.BUFFER_FLUSHING;\n this.hls.trigger(Event.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });\n }\n }\n break;\n default:\n break;\n }\n }\n\n onBufferFlushed () {\n let pendingData = this.pendingData;\n if (pendingData && pendingData.length) {\n logger.log('AudioStreamController: appending pending audio data after buffer flushed');\n pendingData.forEach(appendObj => {\n this.hls.trigger(Event.BUFFER_APPENDING, appendObj);\n });\n this.appended = true;\n this.pendingData = [];\n this.state = State.PARSED;\n } else {\n // move to IDLE once flush complete. this should trigger new fragment loading\n this.state = State.IDLE;\n // reset reference to frag\n this.fragPrevious = null;\n this.tick();\n }\n }\n}\nexport default AudioStreamController;\n","import { fixLineBreaks } from './vttparser';\n\nexport function newCue (track, startTime, endTime, captionScreen) {\n let row;\n let cue;\n let indenting;\n let indent;\n let text;\n let VTTCue = window.VTTCue || window.TextTrackCue;\n\n for (let r = 0; r < captionScreen.rows.length; r++) {\n row = captionScreen.rows[r];\n indenting = true;\n indent = 0;\n text = '';\n\n if (!row.isEmpty()) {\n for (let c = 0; c < row.chars.length; c++) {\n if (row.chars[c].uchar.match(/\\s/) && indenting) {\n indent++;\n } else {\n text += row.chars[c].uchar;\n indenting = false;\n }\n }\n // To be used for cleaning-up orphaned roll-up captions\n row.cueStartTime = startTime;\n\n // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE\n if (startTime === endTime) {\n endTime += 0.0001;\n }\n\n cue = new VTTCue(startTime, endTime, fixLineBreaks(text.trim()));\n\n if (indent >= 16) {\n indent--;\n } else {\n indent++;\n }\n\n // VTTCue.line get's flakey when using controls, so let's now include line 13&14\n // also, drop line 1 since it's to close to the top\n if (navigator.userAgent.match(/Firefox\\//)) {\n cue.line = r + 1;\n } else {\n cue.line = (r > 7 ? r - 2 : r + 1);\n }\n\n cue.align = 'left';\n // Clamp the position between 0 and 100 - if out of these bounds, Firefox throws an exception and captions break\n cue.position = Math.max(0, Math.min(100, 100 * (indent / 32) + (navigator.userAgent.match(/Firefox\\//) ? 50 : 0)));\n track.addCue(cue);\n }\n }\n}\n","/**\n * Copyright 2013 vtt.js Contributors\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\nexport default (function () {\n if (typeof window !== 'undefined' && window.VTTCue) {\n return window.VTTCue;\n }\n\n let autoKeyword = 'auto';\n let directionSetting = {\n '': true,\n lr: true,\n rl: true\n };\n let alignSetting = {\n start: true,\n middle: true,\n end: true,\n left: true,\n right: true\n };\n\n function findDirectionSetting (value) {\n if (typeof value !== 'string') {\n return false;\n }\n\n let dir = directionSetting[value.toLowerCase()];\n return dir ? value.toLowerCase() : false;\n }\n\n function findAlignSetting (value) {\n if (typeof value !== 'string') {\n return false;\n }\n\n let align = alignSetting[value.toLowerCase()];\n return align ? value.toLowerCase() : false;\n }\n\n function extend (obj) {\n let i = 1;\n for (; i < arguments.length; i++) {\n let cobj = arguments[i];\n for (let p in cobj) {\n obj[p] = cobj[p];\n }\n }\n\n return obj;\n }\n\n function VTTCue (startTime, endTime, text) {\n let cue = this;\n let isIE8 = (function () {\n if (typeof navigator === 'undefined') {\n return;\n }\n\n return (/MSIE\\s8\\.0/).test(navigator.userAgent);\n })();\n let baseObj = {};\n\n if (isIE8) {\n cue = document.createElement('custom');\n } else {\n baseObj.enumerable = true;\n }\n\n /**\n * Shim implementation specific properties. These properties are not in\n * the spec.\n */\n\n // Lets us know when the VTTCue's data has changed in such a way that we need\n // to recompute its display state. This lets us compute its display state\n // lazily.\n cue.hasBeenReset = false;\n\n /**\n * VTTCue and TextTrackCue properties\n * http://dev.w3.org/html5/webvtt/#vttcue-interface\n */\n\n let _id = '';\n let _pauseOnExit = false;\n let _startTime = startTime;\n let _endTime = endTime;\n let _text = text;\n let _region = null;\n let _vertical = '';\n let _snapToLines = true;\n let _line = 'auto';\n let _lineAlign = 'start';\n let _position = 50;\n let _positionAlign = 'middle';\n let _size = 50;\n let _align = 'middle';\n\n Object.defineProperty(cue, 'id', extend({}, baseObj, {\n get: function () {\n return _id;\n },\n set: function (value) {\n _id = '' + value;\n }\n }));\n\n Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {\n get: function () {\n return _pauseOnExit;\n },\n set: function (value) {\n _pauseOnExit = !!value;\n }\n }));\n\n Object.defineProperty(cue, 'startTime', extend({}, baseObj, {\n get: function () {\n return _startTime;\n },\n set: function (value) {\n if (typeof value !== 'number') {\n throw new TypeError('Start time must be set to a number.');\n }\n\n _startTime = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'endTime', extend({}, baseObj, {\n get: function () {\n return _endTime;\n },\n set: function (value) {\n if (typeof value !== 'number') {\n throw new TypeError('End time must be set to a number.');\n }\n\n _endTime = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'text', extend({}, baseObj, {\n get: function () {\n return _text;\n },\n set: function (value) {\n _text = '' + value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'region', extend({}, baseObj, {\n get: function () {\n return _region;\n },\n set: function (value) {\n _region = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'vertical', extend({}, baseObj, {\n get: function () {\n return _vertical;\n },\n set: function (value) {\n let setting = findDirectionSetting(value);\n // Have to check for false because the setting an be an empty string.\n if (setting === false) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n\n _vertical = setting;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {\n get: function () {\n return _snapToLines;\n },\n set: function (value) {\n _snapToLines = !!value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'line', extend({}, baseObj, {\n get: function () {\n return _line;\n },\n set: function (value) {\n if (typeof value !== 'number' && value !== autoKeyword) {\n throw new SyntaxError('An invalid number or illegal string was specified.');\n }\n\n _line = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {\n get: function () {\n return _lineAlign;\n },\n set: function (value) {\n let setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n\n _lineAlign = setting;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'position', extend({}, baseObj, {\n get: function () {\n return _position;\n },\n set: function (value) {\n if (value < 0 || value > 100) {\n throw new Error('Position must be between 0 and 100.');\n }\n\n _position = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {\n get: function () {\n return _positionAlign;\n },\n set: function (value) {\n let setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n\n _positionAlign = setting;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'size', extend({}, baseObj, {\n get: function () {\n return _size;\n },\n set: function (value) {\n if (value < 0 || value > 100) {\n throw new Error('Size must be between 0 and 100.');\n }\n\n _size = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'align', extend({}, baseObj, {\n get: function () {\n return _align;\n },\n set: function (value) {\n let setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n\n _align = setting;\n this.hasBeenReset = true;\n }\n }));\n\n /**\n * Other <track> spec defined properties\n */\n\n // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state\n cue.displayState = undefined;\n\n if (isIE8) {\n return cue;\n }\n }\n\n /**\n * VTTCue methods\n */\n\n VTTCue.prototype.getCueAsHTML = function () {\n // Assume WebVTT.convertCueToDOMTree is on the global.\n let WebVTT = window.WebVTT;\n return WebVTT.convertCueToDOMTree(window, this.text);\n };\n\n return VTTCue;\n})();\n","/*\n * Timeline Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport Cea608Parser from '../utils/cea-608-parser';\nimport OutputFilter from '../utils/output-filter';\nimport WebVTTParser from '../utils/webvtt-parser';\nimport { logger } from '../utils/logger';\nimport { sendAddTrackEvent, clearCurrentCues } from '../utils/texttrack-utils';\n\nfunction canReuseVttTextTrack (inUseTrack, manifestTrack) {\n return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2);\n}\n\nfunction intersection (x1, x2, y1, y2) {\n return Math.min(x2, y2) - Math.max(x1, y1);\n}\n\nclass TimelineController extends EventHandler {\n constructor (hls) {\n super(hls, Event.MEDIA_ATTACHING,\n Event.MEDIA_DETACHING,\n Event.FRAG_PARSING_USERDATA,\n Event.FRAG_DECRYPTED,\n Event.MANIFEST_LOADING,\n Event.MANIFEST_LOADED,\n Event.FRAG_LOADED,\n Event.LEVEL_SWITCHING,\n Event.INIT_PTS_FOUND);\n\n this.hls = hls;\n this.config = hls.config;\n this.enabled = true;\n this.Cues = hls.config.cueHandler;\n this.textTracks = [];\n this.tracks = [];\n this.unparsedVttFrags = [];\n this.initPTS = [];\n this.cueRanges = [];\n this.captionsTracks = {};\n\n this.captionsProperties = {\n textTrack1: {\n label: this.config.captionsTextTrack1Label,\n languageCode: this.config.captionsTextTrack1LanguageCode\n },\n textTrack2: {\n label: this.config.captionsTextTrack2Label,\n languageCode: this.config.captionsTextTrack2LanguageCode\n }\n };\n\n if (this.config.enableCEA708Captions) {\n let channel1 = new OutputFilter(this, 'textTrack1');\n let channel2 = new OutputFilter(this, 'textTrack2');\n\n this.cea608Parser = new Cea608Parser(0, channel1, channel2);\n }\n }\n\n addCues (trackName, startTime, endTime, screen) {\n // skip cues which overlap more than 50% with previously parsed time ranges\n const ranges = this.cueRanges;\n let merged = false;\n for (let i = ranges.length; i--;) {\n let cueRange = ranges[i];\n let overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);\n if (overlap >= 0) {\n cueRange[0] = Math.min(cueRange[0], startTime);\n cueRange[1] = Math.max(cueRange[1], endTime);\n merged = true;\n if ((overlap / (endTime - startTime)) > 0.5) {\n return;\n }\n }\n }\n if (!merged) {\n ranges.push([startTime, endTime]);\n }\n\n this.Cues.newCue(this.captionsTracks[trackName], startTime, endTime, screen);\n }\n\n // Triggered when an initial PTS is found; used for synchronisation of WebVTT.\n onInitPtsFound (data) {\n if (data.id === 'main') {\n this.initPTS[data.frag.cc] = data.initPTS;\n }\n\n // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.\n // Parse any unparsed fragments upon receiving the initial PTS.\n if (this.unparsedVttFrags.length) {\n const unparsedVttFrags = this.unparsedVttFrags;\n this.unparsedVttFrags = [];\n unparsedVttFrags.forEach(frag => {\n this.onFragLoaded(frag);\n });\n }\n }\n\n getExistingTrack (trackName) {\n const { media } = this;\n if (media) {\n for (let i = 0; i < media.textTracks.length; i++) {\n let textTrack = media.textTracks[i];\n if (textTrack[trackName]) {\n return textTrack;\n }\n }\n }\n return null;\n }\n\n createCaptionsTrack (trackName) {\n const { label, languageCode } = this.captionsProperties[trackName];\n const captionsTracks = this.captionsTracks;\n if (!captionsTracks[trackName]) {\n // Enable reuse of existing text track.\n const existingTrack = this.getExistingTrack(trackName);\n if (!existingTrack) {\n const textTrack = this.createTextTrack('captions', label, languageCode);\n if (textTrack) {\n // Set a special property on the track so we know it's managed by Hls.js\n textTrack[trackName] = true;\n captionsTracks[trackName] = textTrack;\n }\n } else {\n captionsTracks[trackName] = existingTrack;\n clearCurrentCues(captionsTracks[trackName]);\n sendAddTrackEvent(captionsTracks[trackName], this.media);\n }\n }\n }\n\n createTextTrack (kind, label, lang) {\n const media = this.media;\n if (media) {\n return media.addTextTrack(kind, label, lang);\n }\n }\n\n destroy () {\n EventHandler.prototype.destroy.call(this);\n }\n\n onMediaAttaching (data) {\n this.media = data.media;\n this._cleanTracks();\n }\n\n onMediaDetaching () {\n const { captionsTracks } = this;\n Object.keys(captionsTracks).forEach(trackName => {\n clearCurrentCues(captionsTracks[trackName]);\n delete captionsTracks[trackName];\n });\n }\n\n onManifestLoading () {\n this.lastSn = -1; // Detect discontiguity in fragment parsing\n this.prevCC = -1;\n this.vttCCs = { // Detect discontinuity in subtitle manifests\n ccOffset: 0,\n presentationOffset: 0,\n 0: {\n start: 0, prevCC: -1, new: false\n }\n };\n this._cleanTracks();\n }\n\n _cleanTracks () {\n // clear outdated subtitles\n const media = this.media;\n if (media) {\n const textTracks = media.textTracks;\n if (textTracks) {\n for (let i = 0; i < textTracks.length; i++) {\n clearCurrentCues(textTracks[i]);\n }\n }\n }\n }\n\n onManifestLoaded (data) {\n this.textTracks = [];\n this.unparsedVttFrags = this.unparsedVttFrags || [];\n this.initPTS = [];\n this.cueRanges = [];\n\n if (this.config.enableWebVTT) {\n this.tracks = data.subtitles || [];\n const inUseTracks = this.media ? this.media.textTracks : [];\n\n this.tracks.forEach((track, index) => {\n let textTrack;\n if (index < inUseTracks.length) {\n let inUseTrack = null;\n\n for (let i = 0; i < inUseTracks.length; i++) {\n if (canReuseVttTextTrack(inUseTracks[i], track)) {\n inUseTrack = inUseTracks[i];\n break;\n }\n }\n\n // Reuse tracks with the same label, but do not reuse 608/708 tracks\n if (inUseTrack) {\n textTrack = inUseTrack;\n }\n }\n if (!textTrack) {\n textTrack = this.createTextTrack('subtitles', track.name, track.lang);\n }\n\n if (track.default) {\n textTrack.mode = this.hls.subtitleDisplay ? 'showing' : 'hidden';\n } else {\n textTrack.mode = 'disabled';\n }\n\n this.textTracks.push(textTrack);\n });\n }\n }\n\n onLevelSwitching () {\n this.enabled = this.hls.currentLevel.closedCaptions !== 'NONE';\n }\n\n onFragLoaded (data) {\n let frag = data.frag,\n payload = data.payload;\n if (frag.type === 'main') {\n let sn = frag.sn;\n // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack\n if (sn !== this.lastSn + 1) {\n const cea608Parser = this.cea608Parser;\n if (cea608Parser) {\n cea608Parser.reset();\n }\n }\n this.lastSn = sn;\n } // eslint-disable-line brace-style\n // If fragment is subtitle type, parse as WebVTT.\n else if (frag.type === 'subtitle') {\n if (payload.byteLength) {\n // We need an initial synchronisation PTS. Store fragments as long as none has arrived.\n if (!Number.isFinite(this.initPTS[frag.cc])) {\n this.unparsedVttFrags.push(data);\n if (this.initPTS.length) {\n // finish unsuccessfully, otherwise the subtitle-stream-controller could be blocked from loading new frags.\n this.hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });\n }\n return;\n }\n\n let decryptData = frag.decryptdata;\n // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.\n if ((decryptData == null) || (decryptData.key == null) || (decryptData.method !== 'AES-128')) {\n this._parseVTTs(frag, payload);\n }\n } else {\n // In case there is no payload, finish unsuccessfully.\n this.hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });\n }\n }\n }\n\n _parseVTTs (frag, payload) {\n let vttCCs = this.vttCCs;\n if (!vttCCs[frag.cc]) {\n vttCCs[frag.cc] = { start: frag.start, prevCC: this.prevCC, new: true };\n this.prevCC = frag.cc;\n }\n let textTracks = this.textTracks,\n hls = this.hls;\n\n // Parse the WebVTT file contents.\n WebVTTParser.parse(payload, this.initPTS[frag.cc], vttCCs, frag.cc, function (cues) {\n const currentTrack = textTracks[frag.level];\n // WebVTTParser.parse is an async method and if the currently selected text track mode is set to \"disabled\"\n // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null\n // and trying to access getCueById method of cues will throw an exception\n if (currentTrack.mode === 'disabled') {\n hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });\n return;\n }\n // Add cues and trigger event with success true.\n cues.forEach(cue => {\n // Sometimes there are cue overlaps on segmented vtts so the same\n // cue can appear more than once in different vtt files.\n // This avoid showing duplicated cues with same timecode and text.\n if (!currentTrack.cues.getCueById(cue.id)) {\n try {\n currentTrack.addCue(cue);\n } catch (err) {\n const textTrackCue = new window.TextTrackCue(cue.startTime, cue.endTime, cue.text);\n textTrackCue.id = cue.id;\n currentTrack.addCue(textTrackCue);\n }\n }\n }\n );\n hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: true, frag: frag });\n },\n function (e) {\n // Something went wrong while parsing. Trigger event with success false.\n logger.log(`Failed to parse VTT cue: ${e}`);\n hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });\n });\n }\n\n onFragDecrypted (data) {\n let decryptedData = data.payload,\n frag = data.frag;\n\n if (frag.type === 'subtitle') {\n if (!Number.isFinite(this.initPTS[frag.cc])) {\n this.unparsedVttFrags.push(data);\n return;\n }\n\n this._parseVTTs(frag, decryptedData);\n }\n }\n\n onFragParsingUserdata (data) {\n // push all of the CEA-708 messages into the interpreter\n // immediately. It will create the proper timestamps based on our PTS value\n if (this.enabled && this.config.enableCEA708Captions) {\n for (let i = 0; i < data.samples.length; i++) {\n let ccdatas = this.extractCea608Data(data.samples[i].bytes);\n this.cea608Parser.addData(data.samples[i].pts, ccdatas);\n }\n }\n }\n\n extractCea608Data (byteArray) {\n let count = byteArray[0] & 31;\n let position = 2;\n let tmpByte, ccbyte1, ccbyte2, ccValid, ccType;\n let actualCCBytes = [];\n\n for (let j = 0; j < count; j++) {\n tmpByte = byteArray[position++];\n ccbyte1 = 0x7F & byteArray[position++];\n ccbyte2 = 0x7F & byteArray[position++];\n ccValid = (4 & tmpByte) !== 0;\n ccType = 3 & tmpByte;\n\n if (ccbyte1 === 0 && ccbyte2 === 0) {\n continue;\n }\n\n if (ccValid) {\n if (ccType === 0) { // || ccType === 1\n actualCCBytes.push(ccbyte1);\n actualCCBytes.push(ccbyte2);\n }\n }\n }\n return actualCCBytes;\n }\n}\n\nexport default TimelineController;\n","/**\n *\n * This code was ported from the dash.js project at:\n * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js\n * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2\n *\n * The original copyright appears below:\n *\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject 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/**\n * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes\n */\n\nlet 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 * Utils\n */\nlet getCharForByte = function (byte) {\n let charCode = byte;\n if (specialCea608CharsCodes.hasOwnProperty(byte)) {\n charCode = specialCea608CharsCodes[byte];\n }\n\n return String.fromCharCode(charCode);\n};\n\nlet NR_ROWS = 15,\n NR_COLS = 100;\n// Tables to look up row from PAC data\nlet rowsLowCh1 = { 0x11: 1, 0x12: 3, 0x15: 5, 0x16: 7, 0x17: 9, 0x10: 11, 0x13: 12, 0x14: 14 };\nlet rowsHighCh1 = { 0x11: 2, 0x12: 4, 0x15: 6, 0x16: 8, 0x17: 10, 0x13: 13, 0x14: 15 };\nlet rowsLowCh2 = { 0x19: 1, 0x1A: 3, 0x1D: 5, 0x1E: 7, 0x1F: 9, 0x18: 11, 0x1B: 12, 0x1C: 14 };\nlet rowsHighCh2 = { 0x19: 2, 0x1A: 4, 0x1D: 6, 0x1E: 8, 0x1F: 10, 0x1B: 13, 0x1C: 15 };\n\nlet 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 */\nlet 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 let minLevel = this.verboseFilter[severity];\n if (this.verboseLevel >= minLevel) {\n // console.log(this.time + ' [' + severity + '] ' + msg);\n }\n }\n};\n\nlet numArrayToHexArray = function (numArray) {\n let hexArray = [];\n for (let j = 0; j < numArray.length; j++) {\n hexArray.push(numArray[j].toString(16));\n }\n\n return hexArray;\n};\n\nclass PenState {\n constructor (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 reset () {\n this.foreground = 'white';\n this.underline = false;\n this.italics = false;\n this.background = 'black';\n this.flash = false;\n }\n\n setStyles (styles) {\n let attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];\n for (let i = 0; i < attribs.length; i++) {\n let style = attribs[i];\n if (styles.hasOwnProperty(style)) {\n this[style] = styles[style];\n }\n }\n }\n\n isDefault () {\n return (this.foreground === 'white' && !this.underline && !this.italics &&\n this.background === 'black' && !this.flash);\n }\n\n equals (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 (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 () {\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 */\nclass StyledUnicodeChar {\n constructor (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 reset () {\n this.uchar = ' ';\n this.penState.reset();\n }\n\n setChar (uchar, newPenState) {\n this.uchar = uchar;\n this.penState.copy(newPenState);\n }\n\n setPenState (newPenState) {\n this.penState.copy(newPenState);\n }\n\n equals (other) {\n return this.uchar === other.uchar && this.penState.equals(other.penState);\n }\n\n copy (newChar) {\n this.uchar = newChar.uchar;\n this.penState.copy(newChar.penState);\n }\n\n isEmpty () {\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 */\nclass Row {\n constructor () {\n this.chars = [];\n for (let i = 0; i < NR_COLS; i++) {\n this.chars.push(new StyledUnicodeChar());\n }\n\n this.pos = 0;\n this.currPenState = new PenState();\n }\n\n equals (other) {\n let equal = true;\n for (let 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 (other) {\n for (let i = 0; i < NR_COLS; i++) {\n this.chars[i].copy(other.chars[i]);\n }\n }\n\n isEmpty () {\n let empty = true;\n for (let 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 (absPos) {\n if (this.pos !== absPos) {\n this.pos = absPos;\n }\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 (relPos) {\n let newPos = this.pos + relPos;\n if (relPos > 1) {\n for (let 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 () {\n this.moveCursor(-1);\n this.chars[this.pos].setChar(' ', this.currPenState);\n }\n\n insertChar (byte) {\n if (byte >= 0x90) { // Extended char\n this.backSpace();\n }\n let 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 (startPos) {\n let i;\n for (i = startPos; i < NR_COLS; i++) {\n this.chars[i].reset();\n }\n }\n\n clear () {\n this.clearFromPos(0);\n this.pos = 0;\n this.currPenState.reset();\n }\n\n clearToEndOfRow () {\n this.clearFromPos(this.pos);\n }\n\n getTextString () {\n let chars = [];\n let empty = true;\n for (let i = 0; i < NR_COLS; i++) {\n let char = this.chars[i].uchar;\n if (char !== ' ') {\n empty = false;\n }\n\n chars.push(char);\n }\n if (empty) {\n return '';\n } else {\n return chars.join('');\n }\n }\n\n setPenStyles (styles) {\n this.currPenState.setStyles(styles);\n let 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*/\nclass CaptionScreen {\n constructor () {\n this.rows = [];\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows.push(new Row());\n } // 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 reset () {\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n\n this.currRow = NR_ROWS - 1;\n }\n\n equals (other) {\n let equal = true;\n for (let 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 (other) {\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].copy(other.rows[i]);\n }\n }\n\n isEmpty () {\n let empty = true;\n for (let 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 () {\n let row = this.rows[this.currRow];\n row.backSpace();\n }\n\n clearToEndOfRow () {\n let row = this.rows[this.currRow];\n row.clearToEndOfRow();\n }\n\n /**\n * Insert a character (without styling) in the current row.\n */\n insertChar (char) {\n let row = this.rows[this.currRow];\n row.insertChar(char);\n }\n\n setPen (styles) {\n let row = this.rows[this.currRow];\n row.setPenStyles(styles);\n }\n\n moveCursor (relPos) {\n let row = this.rows[this.currRow];\n row.moveCursor(relPos);\n }\n\n setCursor (absPos) {\n logger.log('INFO', 'setCursor: ' + absPos);\n let row = this.rows[this.currRow];\n row.setCursor(absPos);\n }\n\n setPAC (pacData) {\n logger.log('INFO', 'pacData = ' + JSON.stringify(pacData));\n let newRow = pacData.row - 1;\n if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {\n newRow = this.nrRollUpRows - 1;\n }\n\n // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows\n if (this.nrRollUpRows && this.currRow !== newRow) {\n // clear all rows first\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n\n // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location\n // topRowIndex - the start of rows to copy (inclusive index)\n let topRowIndex = this.currRow + 1 - (this.nrRollUpRows);\n // We only copy if the last position was already shown.\n // We use the cueStartTime value to check this.\n const lastOutputScreen = this.lastOutputScreen;\n if (lastOutputScreen) {\n let prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;\n if (prevLineTime && prevLineTime < logger.time) {\n for (let i = 0; i < this.nrRollUpRows; i++) {\n this.rows[newRow - this.nrRollUpRows + i + 1].copy(lastOutputScreen.rows[topRowIndex + i]);\n }\n }\n }\n }\n\n this.currRow = newRow;\n let row = this.rows[this.currRow];\n if (pacData.indent !== null) {\n let indent = pacData.indent;\n let prevPos = Math.max(indent - 1, 0);\n row.setCursor(pacData.indent);\n pacData.color = row.chars[prevPos].penState.foreground;\n }\n let 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 (bkgData) {\n logger.log('INFO', 'bkgData = ' + JSON.stringify(bkgData));\n this.backSpace();\n this.setPen(bkgData);\n this.insertChar(0x20); // Space\n }\n\n setRollUpRows (nrRows) {\n this.nrRollUpRows = nrRows;\n }\n\n rollUp () {\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 let topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n let 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 (asOneRow) {\n asOneRow = asOneRow || false;\n let displayText = [];\n let text = '';\n let rowNr = -1;\n for (let i = 0; i < NR_ROWS; i++) {\n let 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 () {\n return this.rows;\n }\n}\n\n// var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];\n\nclass Cea608Channel {\n constructor (channelNumber, outputFilter) {\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 reset () {\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 () {\n return this.outputFilter;\n }\n\n setHandler (newHandler) {\n this.outputFilter = newHandler;\n }\n\n setPAC (pacData) {\n this.writeScreen.setPAC(pacData);\n }\n\n setBkgData (bkgData) {\n this.writeScreen.setBkgData(bkgData);\n }\n\n setMode (newMode) {\n if (newMode === this.mode) {\n return;\n }\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 (chars) {\n for (let i = 0; i < chars.length; i++) {\n this.writeScreen.insertChar(chars[i]);\n }\n\n let 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 ccRCL () { // Resume Caption Loading (switch mode to Pop On)\n logger.log('INFO', 'RCL - Resume Caption Loading');\n this.setMode('MODE_POP-ON');\n }\n\n ccBS () { // BackSpace\n logger.log('INFO', 'BS - BackSpace');\n if (this.mode === 'MODE_TEXT') {\n return;\n }\n\n this.writeScreen.backSpace();\n if (this.writeScreen === this.displayedMemory) {\n this.outputDataUpdate();\n }\n }\n\n ccAOF () { // Reserved (formerly Alarm Off)\n\n }\n\n ccAON () { // Reserved (formerly Alarm On)\n\n }\n\n ccDER () { // Delete to End of Row\n logger.log('INFO', 'DER- Delete to End of Row');\n this.writeScreen.clearToEndOfRow();\n this.outputDataUpdate();\n }\n\n ccRU (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\n ccFON () { // Flash On\n logger.log('INFO', 'FON - Flash On');\n this.writeScreen.setPen({ flash: true });\n }\n\n ccRDC () { // Resume Direct Captioning (switch mode to PaintOn)\n logger.log('INFO', 'RDC - Resume Direct Captioning');\n this.setMode('MODE_PAINT-ON');\n }\n\n ccTR () { // Text Restart in text mode (not supported, however)\n logger.log('INFO', 'TR');\n this.setMode('MODE_TEXT');\n }\n\n ccRTD () { // Resume Text Display in Text mode (not supported, however)\n logger.log('INFO', 'RTD');\n this.setMode('MODE_TEXT');\n }\n\n ccEDM () { // Erase Displayed Memory\n logger.log('INFO', 'EDM - Erase Displayed Memory');\n this.displayedMemory.reset();\n this.outputDataUpdate(true);\n }\n\n ccCR () { // Carriage Return\n logger.log('CR - Carriage Return');\n this.writeScreen.rollUp();\n this.outputDataUpdate(true);\n }\n\n ccENM () { // Erase Non-Displayed Memory\n logger.log('INFO', 'ENM - Erase Non-displayed Memory');\n this.nonDisplayedMemory.reset();\n }\n\n ccEOC () { // End of Caption (Flip Memories)\n logger.log('INFO', 'EOC - End Of Caption');\n if (this.mode === 'MODE_POP-ON') {\n let 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(true);\n }\n\n ccTO (nrCols) { // Tab Offset 1,2, or 3 columns\n logger.log('INFO', 'TO(' + nrCols + ') - Tab Offset');\n this.writeScreen.moveCursor(nrCols);\n }\n\n ccMIDROW (secondByte) { // Parse MIDROW command\n let styles = { flash: false };\n styles.underline = secondByte % 2 === 1;\n styles.italics = secondByte >= 0x2e;\n if (!styles.italics) {\n let colorIndex = Math.floor(secondByte / 2) - 0x10;\n let 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 (dispatch = false) {\n let t = logger.time;\n if (t === null) {\n return;\n }\n\n if (this.outputFilter) {\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 if (dispatch === true && this.outputFilter.dispatchCue) {\n this.outputFilter.dispatchCue();\n }\n }\n this.cueStartTime = this.displayedMemory.isEmpty() ? null : t;\n }\n }\n this.lastOutputScreen.copy(this.displayedMemory);\n }\n }\n\n cueSplitAtTime (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\n this.cueStartTime = t;\n }\n }\n }\n}\n\nclass Cea608Parser {\n constructor (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 getHandler (index) {\n return this.channels[index].getHandler();\n }\n\n setHandler (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 (t, byteList) {\n let cmdFound, a, b,\n charsFound = false;\n\n this.lastTime = t;\n logger.setTime(t);\n\n for (let i = 0; i < byteList.length; i += 2) {\n a = byteList[i] & 0x7f;\n b = byteList[i + 1] & 0x7f;\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\n if (!cmdFound) {\n cmdFound = this.parsePAC(a, b);\n }\n\n if (!cmdFound) {\n cmdFound = this.parseBackgroundAttributes(a, b);\n }\n\n if (!cmdFound) {\n charsFound = this.parseChars(a, b);\n if (charsFound) {\n if (this.currChNr && this.currChNr >= 0) {\n let 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 (a, b) {\n let chNr = null;\n\n let cond1 = (a === 0x14 || a === 0x1C) && (b >= 0x20 && b <= 0x2F);\n let cond2 = (a === 0x17 || a === 0x1F) && (b >= 0x21 && b <= 0x23);\n if (!(cond1 || cond2)) {\n return false;\n }\n\n if (a === this.lastCmdA && b === this.lastCmdB) {\n this.lastCmdA = null;\n this.lastCmdB = null; // Repeated commands are dropped (once)\n logger.log('DEBUG', 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');\n return true;\n }\n\n if (a === 0x14 || a === 0x17) {\n chNr = 1;\n } else {\n chNr = 2;\n } // (a === 0x1C || a=== 0x1f)\n\n let channel = this.channels[chNr - 1];\n\n if (a === 0x14 || a === 0x1C) {\n if (b === 0x20) {\n channel.ccRCL();\n } else if (b === 0x21) {\n channel.ccBS();\n } else if (b === 0x22) {\n channel.ccAOF();\n } else if (b === 0x23) {\n channel.ccAON();\n } else if (b === 0x24) {\n channel.ccDER();\n } else if (b === 0x25) {\n channel.ccRU(2);\n } else if (b === 0x26) {\n channel.ccRU(3);\n } else if (b === 0x27) {\n channel.ccRU(4);\n } else if (b === 0x28) {\n channel.ccFON();\n } else if (b === 0x29) {\n channel.ccRDC();\n } else if (b === 0x2A) {\n channel.ccTR();\n } else if (b === 0x2B) {\n channel.ccRTD();\n } else if (b === 0x2C) {\n channel.ccEDM();\n } else if (b === 0x2D) {\n channel.ccCR();\n } else if (b === 0x2E) {\n channel.ccENM();\n } else if (b === 0x2F) {\n channel.ccEOC();\n }\n } else { // a == 0x17 || a == 0x1F\n channel.ccTO(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 (a, b) {\n let chNr = null;\n\n if (((a === 0x11) || (a === 0x19)) && b >= 0x20 && b <= 0x2f) {\n if (a === 0x11) {\n chNr = 1;\n } else {\n chNr = 2;\n }\n\n if (chNr !== this.currChNr) {\n logger.log('ERROR', 'Mismatch channel in midrow parsing');\n return false;\n }\n let channel = this.channels[chNr - 1];\n channel.ccMIDROW(b);\n logger.log('DEBUG', 'MIDROW (' + numArrayToHexArray([a, 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 (a, b) {\n let chNr = null;\n let row = null;\n\n let case1 = ((a >= 0x11 && a <= 0x17) || (a >= 0x19 && a <= 0x1F)) && (b >= 0x40 && b <= 0x7F);\n let case2 = (a === 0x10 || a === 0x18) && (b >= 0x40 && b <= 0x5F);\n if (!(case1 || case2)) {\n return false;\n }\n\n if (a === this.lastCmdA && b === this.lastCmdB) {\n this.lastCmdA = null;\n this.lastCmdB = null;\n return true; // Repeated commands are dropped (once)\n }\n\n chNr = (a <= 0x17) ? 1 : 2;\n\n if (b >= 0x40 && 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 let pacData = this.interpretPAC(row, b);\n let 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 (row, byte) {\n let pacIndex = byte;\n let 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\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 (a, b) {\n let channelNr = null,\n charCodes = null,\n charCode1 = null;\n\n if (a >= 0x19) {\n channelNr = 2;\n charCode1 = a - 8;\n } else {\n channelNr = 1;\n charCode1 = a;\n }\n if (charCode1 >= 0x11 && charCode1 <= 0x13) {\n // Special character\n let 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\n logger.log('INFO', 'Special char \\'' + getCharForByte(oneCode) + '\\' in channel ' + channelNr);\n charCodes = [oneCode];\n } else if (a >= 0x20 && a <= 0x7f) {\n charCodes = (b === 0) ? [a] : [a, b];\n }\n if (charCodes) {\n let hexCodes = numArrayToHexArray(charCodes);\n logger.log('DEBUG', 'Char codes = ' + hexCodes.join(','));\n this.lastCmdA = null;\n this.lastCmdB = null;\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 (a, b) {\n let bkgData,\n index,\n chNr,\n channel;\n\n let case1 = (a === 0x10 || a === 0x18) && (b >= 0x20 && b <= 0x2f);\n let case2 = (a === 0x17 || a === 0x1f) && (b >= 0x2d && b <= 0x2f);\n if (!(case1 || case2)) {\n return false;\n }\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 = null;\n this.lastCmdB = null;\n return true;\n }\n\n /**\n * Reset state of parser and its channels.\n */\n reset () {\n for (let 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 (t) {\n for (let i = 0; i < this.channels.length; i++) {\n if (this.channels[i]) {\n this.channels[i].cueSplitAtTime(t);\n }\n }\n }\n}\n\nexport default Cea608Parser;\n","export default class OutputFilter {\n constructor (timelineController, trackName) {\n this.timelineController = timelineController;\n this.trackName = trackName;\n this.startTime = null;\n this.endTime = null;\n this.screen = null;\n }\n\n dispatchCue () {\n if (this.startTime === null) {\n return;\n }\n\n this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen);\n this.startTime = null;\n }\n\n newCue (startTime, endTime, screen) {\n if (this.startTime === null || this.startTime > startTime) {\n this.startTime = startTime;\n }\n\n this.endTime = endTime;\n this.screen = screen;\n this.timelineController.createCaptionsTrack(this.trackName);\n }\n}\n","import VTTParser from './vttparser';\nimport { utf8ArrayToStr } from '../demux/id3';\n\n// String.prototype.startsWith is not supported in IE11\nconst startsWith = function (inputString, searchString, position) {\n return inputString.substr(position || 0, searchString.length) === searchString;\n};\n\nconst cueString2millis = function (timeString) {\n let ts = parseInt(timeString.substr(-3));\n let secs = parseInt(timeString.substr(-6, 2));\n let mins = parseInt(timeString.substr(-9, 2));\n let hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0;\n\n if (!Number.isFinite(ts) || !Number.isFinite(secs) || !Number.isFinite(mins) || !Number.isFinite(hours)) {\n return -1;\n }\n\n ts += 1000 * secs;\n ts += 60 * 1000 * mins;\n ts += 60 * 60 * 1000 * hours;\n\n return ts;\n};\n\n// From https://github.com/darkskyapp/string-hash\nconst hash = function (text) {\n let hash = 5381;\n let i = text.length;\n while (i) {\n hash = (hash * 33) ^ text.charCodeAt(--i);\n }\n\n return (hash >>> 0).toString();\n};\n\nconst calculateOffset = function (vttCCs, cc, presentationTime) {\n let currCC = vttCCs[cc];\n let prevCC = vttCCs[currCC.prevCC];\n\n // This is the first discontinuity or cues have been processed since the last discontinuity\n // Offset = current discontinuity time\n if (!prevCC || (!prevCC.new && currCC.new)) {\n vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;\n currCC.new = false;\n return;\n }\n\n // There have been discontinuities since cues were last parsed.\n // Offset = time elapsed\n while (prevCC && prevCC.new) {\n vttCCs.ccOffset += currCC.start - prevCC.start;\n currCC.new = false;\n currCC = prevCC;\n prevCC = vttCCs[currCC.prevCC];\n }\n\n vttCCs.presentationOffset = presentationTime;\n};\n\nconst WebVTTParser = {\n parse: function (vttByteArray, syncPTS, vttCCs, cc, callBack, errorCallBack) {\n // Convert byteArray into string, replacing any somewhat exotic linefeeds with \"\\n\", then split on that character.\n let re = /\\r\\n|\\n\\r|\\n|\\r/g;\n // Uint8Array.prototype.reduce is not implemented in IE11\n let vttLines = utf8ArrayToStr(new Uint8Array(vttByteArray)).trim().replace(re, '\\n').split('\\n');\n\n let cueTime = '00:00.000';\n let mpegTs = 0;\n let localTime = 0;\n let presentationTime = 0;\n let cues = [];\n let parsingError;\n let inHeader = true;\n // let VTTCue = VTTCue || window.TextTrackCue;\n\n // Create parser object using VTTCue with TextTrackCue fallback on certain browsers.\n let parser = new VTTParser();\n\n parser.oncue = function (cue) {\n // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.\n let currCC = vttCCs[cc];\n let cueOffset = vttCCs.ccOffset;\n\n // Update offsets for new discontinuities\n if (currCC && currCC.new) {\n if (localTime !== undefined) {\n // When local time is provided, offset = discontinuity start time - local time\n cueOffset = vttCCs.ccOffset = currCC.start;\n } else {\n calculateOffset(vttCCs, cc, presentationTime);\n }\n }\n\n if (presentationTime) {\n // If we have MPEGTS, offset = presentation time + discontinuity offset\n cueOffset = presentationTime - vttCCs.presentationOffset;\n }\n\n cue.startTime += cueOffset - localTime;\n cue.endTime += cueOffset - localTime;\n\n // Create a unique hash id for a cue based on start/end times and text.\n // This helps timeline-controller to avoid showing repeated captions.\n cue.id = hash(cue.startTime.toString()) + hash(cue.endTime.toString()) + hash(cue.text);\n\n // Fix encoding of special characters. TODO: Test with all sorts of weird characters.\n cue.text = decodeURIComponent(encodeURIComponent(cue.text));\n if (cue.endTime > 0) {\n cues.push(cue);\n }\n };\n\n parser.onparsingerror = function (e) {\n parsingError = e;\n };\n\n parser.onflush = function () {\n if (parsingError && errorCallBack) {\n errorCallBack(parsingError);\n return;\n }\n callBack(cues);\n };\n\n // Go through contents line by line.\n vttLines.forEach(line => {\n if (inHeader) {\n // Look for X-TIMESTAMP-MAP in header.\n if (startsWith(line, 'X-TIMESTAMP-MAP=')) {\n // Once found, no more are allowed anyway, so stop searching.\n inHeader = false;\n // Extract LOCAL and MPEGTS.\n line.substr(16).split(',').forEach(timestamp => {\n if (startsWith(timestamp, 'LOCAL:')) {\n cueTime = timestamp.substr(6);\n } else if (startsWith(timestamp, 'MPEGTS:')) {\n mpegTs = parseInt(timestamp.substr(7));\n }\n });\n try {\n // Calculate subtitle offset in milliseconds.\n if (syncPTS + ((vttCCs[cc].start * 90000) || 0) < 0) {\n syncPTS += 8589934592;\n }\n // Adjust MPEGTS by sync PTS.\n mpegTs -= syncPTS;\n // Convert cue time to seconds\n localTime = cueString2millis(cueTime) / 1000;\n // Convert MPEGTS to seconds from 90kHz.\n presentationTime = mpegTs / 90000;\n\n if (localTime === -1) {\n parsingError = new Error(`Malformed X-TIMESTAMP-MAP: ${line}`);\n }\n } catch (e) {\n parsingError = new Error(`Malformed X-TIMESTAMP-MAP: ${line}`);\n }\n // Return without parsing X-TIMESTAMP-MAP line.\n return;\n } else if (line === '') {\n inHeader = false;\n }\n }\n // Parse line by default.\n parser.parse(line + '\\n');\n });\n\n parser.flush();\n }\n};\n\nexport default WebVTTParser;\n","import Event from '../events';\nimport EventHandler from '../event-handler';\nimport { logger } from '../utils/logger';\nimport { computeReloadInterval } from './level-helper';\n\nclass SubtitleTrackController extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.MANIFEST_LOADED,\n Event.SUBTITLE_TRACK_LOADED);\n this.tracks = [];\n this.trackId = -1;\n this.media = null;\n this.stopped = true;\n\n /**\n * @member {boolean} subtitleDisplay Enable/disable subtitle display rendering\n */\n this.subtitleDisplay = true;\n }\n\n destroy () {\n EventHandler.prototype.destroy.call(this);\n }\n\n // Listen for subtitle track change, then extract the current track ID.\n onMediaAttached (data) {\n this.media = data.media;\n if (!this.media) {\n return;\n }\n\n if (this.queuedDefaultTrack) {\n this.subtitleTrack = this.queuedDefaultTrack;\n delete this.queuedDefaultTrack;\n }\n\n this.trackChangeListener = this._onTextTracksChanged.bind(this);\n\n this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);\n if (this.useTextTrackPolling) {\n this.subtitlePollingInterval = setInterval(() => {\n this.trackChangeListener();\n }, 500);\n } else {\n this.media.textTracks.addEventListener('change', this.trackChangeListener);\n }\n }\n\n onMediaDetaching () {\n if (!this.media) {\n return;\n }\n\n if (this.useTextTrackPolling) {\n clearInterval(this.subtitlePollingInterval);\n } else {\n this.media.textTracks.removeEventListener('change', this.trackChangeListener);\n }\n\n this.media = null;\n }\n\n // Fired whenever a new manifest is loaded.\n onManifestLoaded (data) {\n let tracks = data.subtitles || [];\n this.tracks = tracks;\n this.hls.trigger(Event.SUBTITLE_TRACKS_UPDATED, { subtitleTracks: tracks });\n\n // loop through available subtitle tracks and autoselect default if needed\n // TODO: improve selection logic to handle forced, etc\n tracks.forEach(track => {\n if (track.default) {\n // setting this.subtitleTrack will trigger internal logic\n // if media has not been attached yet, it will fail\n // we keep a reference to the default track id\n // and we'll set subtitleTrack when onMediaAttached is triggered\n if (this.media) {\n this.subtitleTrack = track.id;\n } else {\n this.queuedDefaultTrack = track.id;\n }\n }\n });\n }\n\n onSubtitleTrackLoaded (data) {\n const { id, details } = data;\n const { trackId, tracks } = this;\n const currentTrack = tracks[trackId];\n if (id >= tracks.length || id !== trackId || !currentTrack || this.stopped) {\n this._clearReloadTimer();\n return;\n }\n\n logger.log(`subtitle track ${id} loaded`);\n if (details.live) {\n const reloadInterval = computeReloadInterval(currentTrack.details, details, data.stats.trequest);\n logger.log(`Reloading live subtitle playlist in ${reloadInterval}ms`);\n this.timer = setTimeout(() => {\n this._loadCurrentTrack();\n }, reloadInterval);\n } else {\n this._clearReloadTimer();\n }\n }\n\n startLoad () {\n this.stopped = false;\n this._loadCurrentTrack();\n }\n\n stopLoad () {\n this.stopped = true;\n this._clearReloadTimer();\n }\n\n /** get alternate subtitle tracks list from playlist **/\n get subtitleTracks () {\n return this.tracks;\n }\n\n /** get index of the selected subtitle track (index in subtitle track lists) **/\n get subtitleTrack () {\n return this.trackId;\n }\n\n /** select a subtitle track, based on its index in subtitle track lists**/\n set subtitleTrack (subtitleTrackId) {\n if (this.trackId !== subtitleTrackId) {\n this._toggleTrackModes(subtitleTrackId);\n this._setSubtitleTrackInternal(subtitleTrackId);\n }\n }\n\n _clearReloadTimer () {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n _loadCurrentTrack () {\n const { trackId, tracks, hls } = this;\n const currentTrack = tracks[trackId];\n if (trackId < 0 || !currentTrack || (currentTrack.details && !currentTrack.details.live)) {\n return;\n }\n logger.log(`Loading subtitle track ${trackId}`);\n hls.trigger(Event.SUBTITLE_TRACK_LOADING, { url: currentTrack.url, id: trackId });\n }\n\n /**\n * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.\n * This operates on the DOM textTracks.\n * A value of -1 will disable all subtitle tracks.\n * @param newId - The id of the next track to enable\n * @private\n */\n _toggleTrackModes (newId) {\n const { media, subtitleDisplay, trackId } = this;\n if (!media) {\n return;\n }\n\n const textTracks = filterSubtitleTracks(media.textTracks);\n if (newId === -1) {\n [].slice.call(textTracks).forEach(track => {\n track.mode = 'disabled';\n });\n } else {\n const oldTrack = textTracks[trackId];\n if (oldTrack) {\n oldTrack.mode = 'disabled';\n }\n }\n\n const nextTrack = textTracks[newId];\n if (nextTrack) {\n nextTrack.mode = subtitleDisplay ? 'showing' : 'hidden';\n }\n }\n\n /**\n * This method is responsible for validating the subtitle index and periodically reloading if live.\n * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.\n * @param newId - The id of the subtitle track to activate.\n */\n _setSubtitleTrackInternal (newId) {\n const { hls, tracks } = this;\n if (!Number.isFinite(newId) || newId < -1 || newId >= tracks.length) {\n return;\n }\n\n this.trackId = newId;\n logger.log(`Switching to subtitle track ${newId}`);\n hls.trigger(Event.SUBTITLE_TRACK_SWITCH, { id: newId });\n this._loadCurrentTrack();\n }\n\n _onTextTracksChanged () {\n // Media is undefined when switching streams via loadSource()\n if (!this.media) {\n return;\n }\n\n let trackId = -1;\n let tracks = filterSubtitleTracks(this.media.textTracks);\n for (let id = 0; id < tracks.length; id++) {\n if (tracks[id].mode === 'hidden') {\n // Do not break in case there is a following track with showing.\n trackId = id;\n } else if (tracks[id].mode === 'showing') {\n trackId = id;\n break;\n }\n }\n\n // Setting current subtitleTrack will invoke code.\n this.subtitleTrack = trackId;\n }\n}\n\nfunction filterSubtitleTracks (textTrackList) {\n let tracks = [];\n for (let i = 0; i < textTrackList.length; i++) {\n const track = textTrackList[i];\n // Edge adds a track without a label; we don't want to use it\n if (track.kind === 'subtitles' && track.label) {\n tracks.push(textTrackList[i]);\n }\n }\n return tracks;\n}\n\nexport default SubtitleTrackController;\n","/**\n * @class SubtitleStreamController\n */\n\nimport Event from '../events';\nimport { logger } from '../utils/logger';\nimport Decrypter from '../crypt/decrypter';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport { findFragmentByPDT, findFragmentByPTS } from './fragment-finders';\nimport { FragmentState } from './fragment-tracker';\nimport BaseStreamController, { State } from './base-stream-controller';\nimport { mergeSubtitlePlaylists } from './level-helper';\n\nconst { performance } = window;\nconst TICK_INTERVAL = 500; // how often to tick in ms\n\nexport class SubtitleStreamController extends BaseStreamController {\n constructor (hls, fragmentTracker) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.ERROR,\n Event.KEY_LOADED,\n Event.FRAG_LOADED,\n Event.SUBTITLE_TRACKS_UPDATED,\n Event.SUBTITLE_TRACK_SWITCH,\n Event.SUBTITLE_TRACK_LOADED,\n Event.SUBTITLE_FRAG_PROCESSED,\n Event.LEVEL_UPDATED);\n\n this.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.state = State.STOPPED;\n this.tracks = [];\n this.tracksBuffered = [];\n this.currentTrackId = -1;\n this.decrypter = new Decrypter(hls, hls.config);\n // lastAVStart stores the time in seconds for the start time of a level load\n this.lastAVStart = 0;\n this._onMediaSeeking = this.onMediaSeeking.bind(this);\n }\n\n onSubtitleFragProcessed (data) {\n const { frag, success } = data;\n this.fragPrevious = frag;\n this.state = State.IDLE;\n if (!success) {\n return;\n }\n\n const buffered = this.tracksBuffered[this.currentTrackId];\n if (!buffered) {\n return;\n }\n\n // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo\n // so we can re-use the logic used to detect how much have been buffered\n let timeRange;\n const fragStart = frag.start;\n for (let i = 0; i < buffered.length; i++) {\n if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {\n timeRange = buffered[i];\n break;\n }\n }\n\n const fragEnd = frag.start + frag.duration;\n if (timeRange) {\n timeRange.end = fragEnd;\n } else {\n timeRange = {\n start: fragStart,\n end: fragEnd\n };\n buffered.push(timeRange);\n }\n }\n\n onMediaAttached ({ media }) {\n this.media = media;\n media.addEventListener('seeking', this._onMediaSeeking);\n this.state = State.IDLE;\n }\n\n onMediaDetaching () {\n this.media.removeEventListener('seeking', this._onMediaSeeking);\n this.media = null;\n this.state = State.STOPPED;\n }\n\n // If something goes wrong, proceed to next frag, if we were processing one.\n onError (data) {\n let frag = data.frag;\n // don't handle error not related to subtitle fragment\n if (!frag || frag.type !== 'subtitle') {\n return;\n }\n this.state = State.IDLE;\n }\n\n // Got all new subtitle tracks.\n onSubtitleTracksUpdated (data) {\n logger.log('subtitle tracks updated');\n this.tracksBuffered = [];\n this.tracks = data.subtitleTracks;\n this.tracks.forEach((track) => {\n this.tracksBuffered[track.id] = [];\n });\n }\n\n onSubtitleTrackSwitch (data) {\n this.currentTrackId = data.id;\n\n if (!this.tracks || this.currentTrackId === -1) {\n this.clearInterval();\n return;\n }\n\n // Check if track has the necessary details to load fragments\n const currentTrack = this.tracks[this.currentTrackId];\n if (currentTrack && currentTrack.details) {\n this.setInterval(TICK_INTERVAL);\n }\n }\n\n // Got a new set of subtitle fragments.\n onSubtitleTrackLoaded (data) {\n const { id, details } = data;\n const { currentTrackId, tracks } = this;\n const currentTrack = tracks[currentTrackId];\n if (id >= tracks.length || id !== currentTrackId || !currentTrack) {\n return;\n }\n\n if (details.live) {\n mergeSubtitlePlaylists(currentTrack.details, details, this.lastAVStart);\n }\n currentTrack.details = details;\n this.setInterval(TICK_INTERVAL);\n }\n\n onKeyLoaded () {\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n }\n }\n\n onFragLoaded (data) {\n const fragCurrent = this.fragCurrent;\n const decryptData = data.frag.decryptdata;\n const fragLoaded = data.frag;\n const hls = this.hls;\n\n if (this.state === State.FRAG_LOADING &&\n fragCurrent &&\n data.frag.type === 'subtitle' &&\n fragCurrent.sn === data.frag.sn) {\n // check to see if the payload needs to be decrypted\n if (data.payload.byteLength > 0 && (decryptData && decryptData.key && decryptData.method === 'AES-128')) {\n let startTime = performance.now();\n\n // decrypt the subtitles\n this.decrypter.decrypt(data.payload, decryptData.key.buffer, decryptData.iv.buffer, function (decryptedData) {\n let endTime = performance.now();\n hls.trigger(Event.FRAG_DECRYPTED, { frag: fragLoaded, payload: decryptedData, stats: { tstart: startTime, tdecrypt: endTime } });\n });\n }\n }\n }\n\n onLevelUpdated ({ details }) {\n const frags = details.fragments;\n this.lastAVStart = frags.length ? frags[0].start : 0;\n }\n\n doTick () {\n if (!this.media) {\n this.state = State.IDLE;\n return;\n }\n\n switch (this.state) {\n case State.IDLE: {\n const { config, currentTrackId, fragmentTracker, media, tracks } = this;\n if (!tracks || !tracks[currentTrackId] || !tracks[currentTrackId].details) {\n break;\n }\n\n const { maxBufferHole, maxFragLookUpTolerance } = config;\n const maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength);\n const bufferedInfo = BufferHelper.bufferedInfo(this._getBuffered(), media.currentTime, maxBufferHole);\n const { end: bufferEnd, len: bufferLen } = bufferedInfo;\n\n const trackDetails = tracks[currentTrackId].details;\n const fragments = trackDetails.fragments;\n const fragLen = fragments.length;\n const end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration;\n\n if (bufferLen > maxConfigBuffer) {\n return;\n }\n\n let foundFrag;\n const fragPrevious = this.fragPrevious;\n if (bufferEnd < end) {\n if (fragPrevious && trackDetails.hasProgramDateTime) {\n foundFrag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, maxFragLookUpTolerance);\n }\n if (!foundFrag) {\n foundFrag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance);\n }\n } else {\n foundFrag = fragments[fragLen - 1];\n }\n\n if (foundFrag && foundFrag.encrypted) {\n logger.log(`Loading key for ${foundFrag.sn}`);\n this.state = State.KEY_LOADING;\n this.hls.trigger(Event.KEY_LOADING, { frag: foundFrag });\n } else if (foundFrag && fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED) {\n // only load if fragment is not loaded\n this.fragCurrent = foundFrag;\n this.state = State.FRAG_LOADING;\n this.hls.trigger(Event.FRAG_LOADING, { frag: foundFrag });\n }\n }\n }\n }\n\n stopLoad () {\n this.lastAVStart = 0;\n super.stopLoad();\n }\n\n _getBuffered () {\n return this.tracksBuffered[this.currentTrackId] || [];\n }\n\n onMediaSeeking () {\n this.fragPrevious = null;\n }\n}\n","/**\n * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>\n *\n * DRM support for Hls.js\n */\n\nimport EventHandler from '../event-handler';\nimport Event from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport { logger } from '../utils/logger';\n\nconst { XMLHttpRequest } = window;\n\nconst MAX_LICENSE_REQUEST_FAILURES = 3;\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess\n */\nconst KeySystems = {\n WIDEVINE: 'com.widevine.alpha',\n PLAYREADY: 'com.microsoft.playready'\n};\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n * @param {object} drmSystemOptions Optional parameters/requirements for the key-system\n * @returns {Array<MediaSystemConfiguration>} An array of supported configurations\n */\n\nconst createWidevineMediaKeySystemConfigurations = function (audioCodecs, videoCodecs, drmSystemOptions) { /* jshint ignore:line */\n const baseConfig = {\n // initDataTypes: ['keyids', 'mp4'],\n // label: \"\",\n // persistentState: \"not-allowed\", // or \"required\" ?\n // distinctiveIdentifier: \"not-allowed\", // or \"required\" ?\n // sessionTypes: ['temporary'],\n videoCapabilities: [\n // { contentType: 'video/mp4; codecs=\"avc1.42E01E\"' }\n ]\n };\n\n videoCodecs.forEach((codec) => {\n baseConfig.videoCapabilities.push({\n contentType: `video/mp4; codecs=\"${codec}\"`\n });\n });\n\n return [\n baseConfig\n ];\n};\n\n/**\n * The idea here is to handle key-system (and their respective platforms) specific configuration differences\n * in order to work with the local requestMediaKeySystemAccess method.\n *\n * We can also rule-out platform-related key-system support at this point by throwing an error or returning null.\n *\n * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n * @returns {Array<MediaSystemConfiguration> | null} A non-empty Array of MediaKeySystemConfiguration objects or `null`\n */\nconst getSupportedMediaKeySystemConfigurations = function (keySystem, audioCodecs, videoCodecs) {\n switch (keySystem) {\n case KeySystems.WIDEVINE:\n return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs);\n default:\n throw Error('Unknown key-system: ' + keySystem);\n }\n};\n\n/**\n * Controller to deal with encrypted media extensions (EME)\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API\n *\n * @class\n * @constructor\n */\nclass EMEController extends EventHandler {\n /**\n * @constructs\n * @param {Hls} hls Our Hls.js instance\n */\n constructor (hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MANIFEST_PARSED\n );\n\n this._widevineLicenseUrl = hls.config.widevineLicenseUrl;\n this._licenseXhrSetup = hls.config.licenseXhrSetup;\n this._emeEnabled = hls.config.emeEnabled;\n\n this._requestMediaKeySystemAccess = hls.config.requestMediaKeySystemAccessFunc;\n\n this._mediaKeysList = [];\n this._media = null;\n\n this._hasSetMediaKeys = false;\n this._isMediaEncrypted = false;\n\n this._requestLicenseFailureCount = 0;\n }\n\n /**\n *\n * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum\n * @returns {string} License server URL for key-system (if any configured, otherwise causes error)\n */\n getLicenseServerUrl (keySystem) {\n let url;\n switch (keySystem) {\n case KeySystems.WIDEVINE:\n url = this._widevineLicenseUrl;\n break;\n default:\n url = null;\n break;\n }\n\n if (!url) {\n logger.error(`No license server URL configured for key-system \"${keySystem}\"`);\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true\n });\n }\n\n return url;\n }\n\n /**\n * Requests access object and adds it to our list upon success\n * @private\n * @param {string} keySystem System ID (see `KeySystems`)\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n */\n _attemptKeySystemAccess (keySystem, audioCodecs, videoCodecs) {\n // TODO: add other DRM \"options\"\n\n const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs);\n\n if (!mediaKeySystemConfigs) {\n logger.warn('Can not create config for key-system (maybe because platform is not supported):', keySystem);\n return;\n }\n\n logger.log('Requesting encrypted media key-system access');\n\n // expecting interface like window.navigator.requestMediaKeySystemAccess\n this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs)\n .then((mediaKeySystemAccess) => {\n this._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess);\n })\n .catch((err) => {\n logger.error(`Failed to obtain key-system \"${keySystem}\" access:`, err);\n });\n }\n\n get requestMediaKeySystemAccess () {\n if (!this._requestMediaKeySystemAccess) {\n throw new Error('No requestMediaKeySystemAccess function configured');\n }\n\n return this._requestMediaKeySystemAccess;\n }\n\n /**\n * Handles obtaining access to a key-system\n *\n * @param {string} keySystem\n * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess\n */\n _onMediaKeySystemAccessObtained (keySystem, mediaKeySystemAccess) {\n logger.log(`Access for key-system \"${keySystem}\" obtained`);\n\n const mediaKeysListItem = {\n mediaKeys: null,\n mediaKeysSession: null,\n mediaKeysSessionInitialized: false,\n mediaKeySystemAccess: mediaKeySystemAccess,\n mediaKeySystemDomain: keySystem\n };\n\n this._mediaKeysList.push(mediaKeysListItem);\n\n mediaKeySystemAccess.createMediaKeys()\n .then((mediaKeys) => {\n mediaKeysListItem.mediaKeys = mediaKeys;\n\n logger.log(`Media-keys created for key-system \"${keySystem}\"`);\n\n this._onMediaKeysCreated();\n })\n .catch((err) => {\n logger.error('Failed to create media-keys:', err);\n });\n }\n\n /**\n * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this\n * for all existing keys where no session exists yet.\n */\n _onMediaKeysCreated () {\n // check for all key-list items if a session exists, otherwise, create one\n this._mediaKeysList.forEach((mediaKeysListItem) => {\n if (!mediaKeysListItem.mediaKeysSession) {\n mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys.createSession();\n this._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);\n }\n });\n }\n\n /**\n *\n * @param {*} keySession\n */\n _onNewMediaKeySession (keySession) {\n logger.log(`New key-system session ${keySession.sessionId}`);\n\n keySession.addEventListener('message', (event) => {\n this._onKeySessionMessage(keySession, event.message);\n }, false);\n }\n\n _onKeySessionMessage (keySession, message) {\n logger.log('Got EME message event, creating license request');\n\n this._requestLicense(message, (data) => {\n logger.log('Received license data, updating key-session');\n keySession.update(data);\n });\n }\n\n _onMediaEncrypted (initDataType, initData) {\n logger.log(`Media is encrypted using \"${initDataType}\" init data type`);\n\n this._isMediaEncrypted = true;\n this._mediaEncryptionInitDataType = initDataType;\n this._mediaEncryptionInitData = initData;\n\n this._attemptSetMediaKeys();\n this._generateRequestWithPreferredKeySession();\n }\n\n _attemptSetMediaKeys () {\n if (!this._hasSetMediaKeys) {\n // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?\n const keysListItem = this._mediaKeysList[0];\n if (!keysListItem || !keysListItem.mediaKeys) {\n logger.error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_KEYS,\n fatal: true\n });\n return;\n }\n\n logger.log('Setting keys for encrypted media');\n\n this._media.setMediaKeys(keysListItem.mediaKeys);\n this._hasSetMediaKeys = true;\n }\n }\n\n _generateRequestWithPreferredKeySession () {\n // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?\n const keysListItem = this._mediaKeysList[0];\n if (!keysListItem) {\n logger.error('Fatal: Media is encrypted but not any key-system access has been obtained yet');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,\n fatal: true\n });\n return;\n }\n\n if (keysListItem.mediaKeysSessionInitialized) {\n logger.warn('Key-Session already initialized but requested again');\n return;\n }\n\n const keySession = keysListItem.mediaKeysSession;\n if (!keySession) {\n logger.error('Fatal: Media is encrypted but no key-session existing');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_SESSION,\n fatal: true\n });\n }\n\n const initDataType = this._mediaEncryptionInitDataType;\n const initData = this._mediaEncryptionInitData;\n\n logger.log(`Generating key-session request for \"${initDataType}\" init data type`);\n\n keysListItem.mediaKeysSessionInitialized = true;\n\n keySession.generateRequest(initDataType, initData)\n .then(() => {\n logger.debug('Key-session generation succeeded');\n })\n .catch((err) => {\n logger.error('Error generating key-session request:', err);\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_SESSION,\n fatal: false\n });\n });\n }\n\n /**\n * @param {string} url License server URL\n * @param {ArrayBuffer} keyMessage Message data issued by key-system\n * @param {function} callback Called when XHR has succeeded\n * @returns {XMLHttpRequest} Unsent (but opened state) XHR object\n */\n _createLicenseXhr (url, keyMessage, callback) {\n const xhr = new XMLHttpRequest();\n const licenseXhrSetup = this._licenseXhrSetup;\n\n try {\n if (licenseXhrSetup) {\n try {\n licenseXhrSetup(xhr, url);\n } catch (e) {\n // let's try to open before running setup\n xhr.open('POST', url, true);\n licenseXhrSetup(xhr, url);\n }\n }\n // if licenseXhrSetup did not yet call open, let's do it now\n if (!xhr.readyState) {\n xhr.open('POST', url, true);\n }\n } catch (e) {\n // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n logger.error('Error setting up key-system license XHR', e);\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true\n });\n return;\n }\n\n xhr.responseType = 'arraybuffer';\n xhr.onreadystatechange =\n this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback);\n return xhr;\n }\n\n /**\n * @param {XMLHttpRequest} xhr\n * @param {string} url License server URL\n * @param {ArrayBuffer} keyMessage Message data issued by key-system\n * @param {function} callback Called when XHR has succeeded\n *\n */\n _onLicenseRequestReadyStageChange (xhr, url, keyMessage, callback) {\n switch (xhr.readyState) {\n case 4:\n if (xhr.status === 200) {\n this._requestLicenseFailureCount = 0;\n logger.log('License request succeeded');\n callback(xhr.response);\n } else {\n logger.error(`License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`);\n\n this._requestLicenseFailureCount++;\n if (this._requestLicenseFailureCount <= MAX_LICENSE_REQUEST_FAILURES) {\n const attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;\n logger.warn(`Retrying license request, ${attemptsLeft} attempts left`);\n this._requestLicense(keyMessage, callback);\n return;\n }\n\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true\n });\n }\n break;\n }\n }\n\n /**\n * @param {object} keysListItem\n * @param {ArrayBuffer} keyMessage\n * @returns {ArrayBuffer} Challenge data posted to license server\n */\n _generateLicenseRequestChallenge (keysListItem, keyMessage) {\n let challenge;\n\n if (keysListItem.mediaKeySystemDomain === KeySystems.PLAYREADY) {\n logger.error('PlayReady is not supported (yet)');\n\n // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js\n /*\n if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {\n // For PlayReady CDMs, we need to dig the Challenge out of the XML.\n var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');\n if (keyMessageXml.getElementsByTagName('Challenge')[0]) {\n challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);\n } else {\n throw 'Cannot find <Challenge> in key message';\n }\n var headerNames = keyMessageXml.getElementsByTagName('name');\n var headerValues = keyMessageXml.getElementsByTagName('value');\n if (headerNames.length !== headerValues.length) {\n throw 'Mismatched header <name>/<value> pair in key message';\n }\n for (var i = 0; i < headerNames.length; i++) {\n xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);\n }\n }\n */\n } else if (keysListItem.mediaKeySystemDomain === KeySystems.WIDEVINE) {\n // For Widevine CDMs, the challenge is the keyMessage.\n challenge = keyMessage;\n } else {\n logger.error('Unsupported key-system:', keysListItem.mediaKeySystemDomain);\n }\n\n return challenge;\n }\n\n _requestLicense (keyMessage, callback) {\n logger.log('Requesting content license for key-system');\n\n const keysListItem = this._mediaKeysList[0];\n if (!keysListItem) {\n logger.error('Fatal error: Media is encrypted but no key-system access has been obtained yet');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,\n fatal: true\n });\n return;\n }\n\n const url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);\n const xhr = this._createLicenseXhr(url, keyMessage, callback);\n\n logger.log(`Sending license request to URL: ${url}`);\n\n xhr.send(this._generateLicenseRequestChallenge(keysListItem, keyMessage));\n }\n\n onMediaAttached (data) {\n if (!this._emeEnabled) {\n return;\n }\n\n const media = data.media;\n\n // keep reference of media\n this._media = media;\n\n // FIXME: also handle detaching media !\n\n media.addEventListener('encrypted', (e) => {\n this._onMediaEncrypted(e.initDataType, e.initData);\n });\n }\n\n onManifestParsed (data) {\n if (!this._emeEnabled) {\n return;\n }\n\n const audioCodecs = data.levels.map((level) => level.audioCodec);\n const videoCodecs = data.levels.map((level) => level.videoCodec);\n\n this._attemptKeySystemAccess(KeySystems.WIDEVINE, audioCodecs, videoCodecs);\n }\n}\n\nexport default EMEController;\n","const requestMediaKeySystemAccess = (function () {\n if (typeof window !== 'undefined' && window.navigator && window.navigator.requestMediaKeySystemAccess) {\n return window.navigator.requestMediaKeySystemAccess.bind(window.navigator);\n } else {\n return null;\n }\n})();\n\nexport {\n requestMediaKeySystemAccess\n};\n"],"sourceRoot":""}