{"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/errors.ts","webpack://Hls/./src/polyfills/number.js","webpack://Hls/./src/demux/id3.js","webpack://Hls/./src/utils/get-self-scope.js","webpack://Hls/./src/empty.js","webpack://Hls/./node_modules/url-toolkit/src/url-toolkit.js","webpack://Hls/./node_modules/eventemitter3/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/crypt/decrypter.js","webpack://Hls/./src/demux/adts.js","webpack://Hls/./src/demux/aacdemuxer.js","webpack://Hls/./src/demux/mpegaudio.js","webpack://Hls/./src/demux/exp-golomb.js","webpack://Hls/./src/demux/sample-aes.js","webpack://Hls/./src/demux/tsdemuxer.js","webpack://Hls/./src/demux/mp3demuxer.js","webpack://Hls/./src/remux/aac-helper.js","webpack://Hls/./src/remux/mp4-generator.js","webpack://Hls/./src/utils/timescale-conversion.ts","webpack://Hls/./src/remux/mp4-remuxer.js","webpack://Hls/./src/demux/demuxer-inline.js","webpack://Hls/./src/remux/passthrough-remuxer.js","webpack://Hls/./src/demux/mp4demuxer.js","webpack://Hls/./node_modules/webworkify-webpack/index.js","webpack://Hls/./src/demux/demuxer-worker.js","webpack://Hls/./src/types/loader.ts","webpack://Hls/./src/event-handler.ts","webpack://Hls/./src/loader/fragment.ts","webpack://Hls/./src/loader/level-key.ts","webpack://Hls/./src/loader/level.js","webpack://Hls/./src/utils/attr-list.js","webpack://Hls/./src/utils/codecs.ts","webpack://Hls/./src/loader/m3u8-parser.ts","webpack://Hls/./src/loader/playlist-loader.ts","webpack://Hls/./src/loader/fragment-loader.js","webpack://Hls/./src/loader/key-loader.ts","webpack://Hls/./src/controller/fragment-tracker.js","webpack://Hls/./src/utils/binary-search.ts","webpack://Hls/./src/utils/buffer-helper.ts","webpack://Hls/./src/utils/mediasource-helper.ts","webpack://Hls/./src/observer.ts","webpack://Hls/./src/demux/demuxer.js","webpack://Hls/./src/controller/level-helper.js","webpack://Hls/./src/utils/time-ranges.ts","webpack://Hls/./src/utils/discontinuities.js","webpack://Hls/./src/controller/fragment-finders.ts","webpack://Hls/./src/controller/gap-controller.js","webpack://Hls/./src/controller/base-stream-controller.js","webpack://Hls/./src/controller/stream-controller.js","webpack://Hls/./src/controller/level-controller.js","webpack://Hls/./src/task-loop.ts","webpack://Hls/./src/utils/texttrack-utils.ts","webpack://Hls/./src/controller/id3-track-controller.js","webpack://Hls/./src/utils/ewma.ts","webpack://Hls/./src/utils/ewma-bandwidth-estimator.ts","webpack://Hls/./src/controller/abr-controller.js","webpack://Hls/./src/controller/buffer-controller.ts","webpack://Hls/./src/controller/cap-level-controller.js","webpack://Hls/./src/utils/mediakeys-helper.ts","webpack://Hls/./src/controller/fps-controller.js","webpack://Hls/./src/utils/xhr-loader.js","webpack://Hls/./src/config.ts","webpack://Hls/./src/hls.ts","webpack://Hls/./src/is-supported.ts"],"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","noop","fakeLogger","trace","debug","log","warn","info","error","exportedLogger","formatMsg","type","msg","global","getSelfScope","consolePrintFn","func","console","args","apply","enableLogs","debugConfig","functions","forEach","exportLoggerFunctions","e","logger","HlsEvents","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","LEVELS_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","CUES_PARSED","NON_NATIVE_TEXT_TRACKS_FOUND","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","LIVE_BACK_BUFFER_REACHED","ErrorTypes","ErrorDetails","isFiniteNumber","Number","isFinite","MAX_SAFE_INTEGER","decoder","ID3","isHeader","data","offset","length","isFooter","getID3Data","front","_readSize","subarray","size","getTimeStamp","frames","getID3Frames","frame","isTimeStampFrame","_readTimeStamp","_getFrameData","String","fromCharCode","id3Data","end","frameData","_decodeFrame","push","_decodePrivFrame","_decodeTextFrame","_decodeURLFrame","timeStampFrame","byteLength","Uint8Array","pts33Bit","timestamp","Math","round","owner","_utf8ArrayToStr","privateData","buffer","index","description","text","url","array","exitOnNull","getTextDecoder","decoded","decode","idx","indexOf","substring","replace","char2","char3","len","out","TextDecoder","utf8ArrayToStr","window","self","URL_REGEX","FIRST_SEGMENT_REGEX","SLASH_DOT_REGEX","SLASH_DOT_DOT_REGEX","URLToolkit","buildAbsoluteURL","baseURL","relativeURL","opts","trim","alwaysNormalize","basePartsForNormalise","parseURL","Error","path","normalizePath","buildURLFromParts","relativeParts","scheme","baseParts","netLoc","pathParts","exec","builtParts","params","query","fragment","baseURLPath","newPath","lastIndexOf","parts","split","reverse","join","has","prefix","Events","EE","fn","context","once","addListener","emitter","event","TypeError","listener","evt","_events","_eventsCount","clearEvent","EventEmitter","__proto__","eventNames","events","names","slice","getOwnPropertySymbols","concat","listeners","handlers","ee","Array","listenerCount","emit","a1","a2","a3","a4","a5","arguments","removeListener","undefined","j","on","removeAllListeners","off","prefixed","AESCrypto","subtle","iv","aesIV","decrypt","FastAESKey","expandKey","importKey","AESDecryptor","rcon","subMix","Uint32Array","invSubMix","sBox","invSBox","initTable","uint8ArrayToUint32Array_","arrayBuffer","view","DataView","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","removePKCS7Padding","t0","t1","t2","t3","s0","s1","s2","s3","inputWords0","inputWords1","inputWords2","inputWords3","outputBytes","paddingBytes","nRounds","invSBOX","initVector","initVector0","initVector1","initVector2","initVector3","inputInt32","Int32Array","outputInt32","swapWord","getUint8","destroy","Decrypter","observer","config","logEnabled","browserCrypto","crypto","webkitSubtle","disableWebCrypto","isSync","enableSoftwareAES","callback","decryptor","fastAesKey","then","aesKey","catch","err","onWebCryptoError","result","message","trigger","Event","MEDIA_ERROR","details","FRAG_DECRYPT_ERROR","fatal","reason","isHeaderPattern","getHeaderLength","getFullFrameLength","probe","headerLength","frameLength","newOffset","initTrackConfig","track","audioCodec","samplerate","adtsObjectType","adtsSampleingIndex","adtsExtensionSampleingIndex","adtsChanelConfig","userAgent","navigator","toLowerCase","manifestCodec","adtsSampleingRates","test","channelCount","codec","FRAG_PARSING_ERROR","getAudioConfig","getFrameDuration","appendFrame","pts","frameIndex","header","frameDuration","stamp","parseFrameHeader","aacSample","unit","dts","samples","sample","AACDemuxer","remuxer","resetInitSegment","initSegment","videoCodec","duration","_audioTrack","container","id","sequenceNumber","isAAC","inputTimeScale","resetTimeStamp","ADTS","append","timeOffset","contiguous","accurateTimeOffset","id3Samples","remux","MpegAudio","BitratesMap","SamplingRateMap","SamplesCoefficients","BytesInSlot","parseHeader","samplesPerFrame","sampleRate","headerB","headerC","headerE","headerF","headerG","columnInBitrates","bitRate","columnInSampleRates","sampleCoefficient","bytesInSlot","parseInt","ExpGolomb","bytesAvailable","bitsAvailable","loadWord","position","workingBytes","availableBytes","min","set","skipBits","count","skipBytes","readBits","bits","valu","skipLZ","leadingZeroCount","skipUEG","skipEG","readUEG","clz","readEG","readBoolean","readUByte","readUShort","readUInt","skipScalingList","lastScale","nextScale","readSPS","profileIdc","numRefFramesInPicOrderCntCycle","picWidthInMbsMinus1","picHeightInMapUnitsMinus1","frameMbsOnlyFlag","scalingListCount","frameCropLeftOffset","frameCropRightOffset","frameCropTopOffset","frameCropBottomOffset","chromaFormatIdc","picOrderCntType","pixelRatio","width","ceil","height","readSliceType","SampleAesDecrypter","decryptdata","discardEPB","decrypter","decryptBuffer","encryptedData","decryptAacSample","sampleIndex","sync","curUnit","encryptedBuffer","byteOffset","localthis","decryptedData","decryptAacSamples","getAvcEncryptedData","decodedData","encryptedDataLen","floor","Int8Array","outputPos","inputPos","getAvcDecryptedUnit","decryptAvcSample","unitIndex","decryptAvcSamples","curUnits","units","RemuxerTrackIdConfig","video","audio","id3","TSDemuxer","typeSupported","sampleAes","pmtUnknownTypes","setDecryptData","method","syncOffset","_syncOffset","scanwindow","createTrack","pid","dropped","pmtParsed","_pmtId","_avcTrack","_id3Track","_txtTrack","aacOverFlow","aacLastPTS","avcSample","_duration","start","stt","pes","unknownPIDs","avcTrack","audioTrack","id3Track","avcId","audioId","id3Id","pmtId","avcData","pesData","audioData","parsePAT","_parsePAT","parsePMT","_parsePMT","parsePES","_parsePES","parseAVCPES","_parseAVCPES","parseAACPES","_parseAACPES","parseMPEGPES","_parseMPEGPES","parseID3PES","_parseID3PES","parsedPIDs","mpeg","mp3","avc","decryptAndRemux","videoTrack","textTrack","decryptAndRemuxAvc","_initPTS","_initDTS","_trackUnknownPmt","logLevel","mpegSupported","isSampleAes","tableEnd","stream","frag","pesFlags","pesLen","pesHdrLen","pesPts","pesDts","payloadStartOffset","newData","splice","dataLen","pushAccesUnit","nbSamples","isNaN","lastSample","forceKeyFrameOnDiscontinuity","sps","last","expGolombDecoder","_parseAVCNALu","spsfound","createAVCSample","audFound","sliceType","payloadType","payloadSize","endOfCaptions","b","firstByte","totalCCs","byteArray","_insertSampleInOrder","bytes","uuidStrArray","toString","userDataPayloadBytes","uuid","userDataBytes","userData","codecarray","codecstring","h","pps","arr","pos","_getLastNalUnit","lastUnit","overflow","lastUnitType","state","naluState","lastState","lastUnitStart","tmp","newLength","EPBPositions","sourceIndex","shift","newPTS","abs","MP3Demuxer","AAC","getSilentFrame","UINT32_MAX","pow","MP4","init","types","avc1","avcC","btrt","dinf","dref","esds","ftyp","hdlr","mdat","mdhd","mdia","mfhd","minf","moof","moov","mp4a","mvex","mvhd","pasp","sdtp","stbl","stco","stsc","stsd","stsz","stts","tfdt","tfhd","traf","trak","trun","trex","tkhd","vmhd","smhd","charCodeAt","videoHdlr","audioHdlr","HDLR_TYPES","STTS","STSC","STCO","STSZ","VMHD","SMHD","STSD","majorBrand","avc1Brand","minorVersion","FTYP","box","DINF","payload","timescale","upperWordDuration","lowerWordDuration","sn","baseMediaDecodeTime","tracks","boxes","flags","dependsOn","isDependedOn","hasRedundancy","avcc","hSpacing","vSpacing","configlen","sampleDependencyTable","upperWordBaseMediaDecodeTime","lowerWordBaseMediaDecodeTime","cts","arraylen","isLeading","paddingValue","isNonSync","degradPrio","movie","toTimescaleFromBase","destScale","srcBase","toMsFromMpegTsClock","toMpegTsClockFromTimescale","srcScale","MAX_SILENT_FRAME_DURATION_90KHZ","PTS_DTS_SHIFT_TOLERANCE_90KHZ","chromeVersion","PTSNormalize","reference","MP4Remuxer","now","vendor","ISGenerated","match","defaultTimeStamp","getVideoStartPts","videoSamples","rolloverDetected","startPTS","reduce","minPTS","delta","generateIS","nbAudioSamples","nbVideoSamples","audioTimeOffset","videoTimeOffset","audiovideoTimestampDelta","max","audioTrackLength","remuxAudio","endPTS","remuxVideo","videoData","remuxEmptyAudio","remuxID3","remuxText","initPTS","initDTS","audioSamples","computePTSDTS","Infinity","metadata","startOffset","keys","mp4SampleDuration","firstDTS","lastDTS","timeScale","inputSamples","outputSamples","POSITIVE_INFINITY","maxPTS","NEGATIVE_INFINITY","ptsDtsShift","sortSamples","nextAvcDts","sort","a","deltadts","deltapts","averageSampleDuration","foundHole","firstPTS","nbNalu","naluLen","nbUnits","sampleLen","mdatSize","MUX_ERROR","REMUX_ALLOC_ERROR","setUint32","compositionTimeOffset","avcSampleUnits","mp4SampleLength","unitData","unitDataLen","lastFrameDuration","stretchShortVideoTrack","maxBufferHole","gapTolerance","deltaToFrameEnd","nextAudioPts","data1","data2","startDTS","endDTS","hasAudio","hasVideo","nb","mp4Sample","fillFrame","lastPTS","mp4timeScale","scaleFactor","inputSampleDuration","rawMPEG","filter","maxAudioFramesDrift","nextPts","missing","newStamp","audioSample","numMissingFrames","unitLen","lastSampleDuration","silentFrame","PassThroughRemuxer","rawData","streamType","performance","Date","DemuxerInline","demuxer","discontinuity","trackSwitch","defaultInitPTS","startTime","endTime","stats","tstart","tdecrypt","pushDecrypted","mux","muxConfig","demux","MP4Demuxer","initData","parseInitSegment","audiovideo","findBox","bin2str","readUint16","val","readUint32","writeUint32","subresults","endbox","results","parseSegmentIndex","references","moovEndOffset","sidx","version","startByte","referencesCount","referenceIndex","referenceInfo","referenceSize","subsegmentDuration","earliestPresentationTime","trackId","codecBox","codecType","getStartDTS","trafs","baseTimes","map","scale","offsetStartDTS","upper","lower","webpackBootstrapFunc","configurable","oe","f","ENTRY_MODULE","default","quoteRegExp","str","getModuleDependencies","sources","queueName","retval","fnString","wrapperSignature","webpackRequireName","re","RegExp","hasValuesInQueues","queues","hasValues","options","main","requiredModules","all","modulesQueue","seenModules","moduleToCheck","pop","newModules","newModulesKeys","getRequiredModules","src","entryModule","JSON","stringify","blob","Blob","bare","workerUrl","URL","webkitURL","mozURL","msURL","createObjectURL","worker","Worker","objectURL","DemuxerWorker","forwardMessage","ev","postMessage","addEventListener","cmd","parse","transferable","PlaylistContextType","PlaylistLevelType","FORBIDDEN_EVENT_NAMES","EventHandler","hls","handledEvents","useGenericHandler","onEvent","registerListeners","onHandlerDestroying","unregisterListeners","onHandlerDestroyed","isEventHandler","onEventGeneric","funcName","constructor","OTHER_ERROR","INTERNAL_EXCEPTION","ElementaryStreamTypes","LevelKey","baseURI","relativeURI","_uri","baseuri","reluri","Fragment","_url","_byteRange","_decryptdata","_elementaryStreams","AUDIO","VIDEO","deltaPTS","rawProgramDateTime","programDateTime","title","tagList","cc","relurl","baseurl","urlId","level","levelkey","loader","setByteRange","previousFrag","byteRange","byteRangeEndOffset","addElementaryStream","hasElementaryStream","createInitializationVector","segmentNumber","uint8View","setDecryptDataFromLevelKey","uri","Level","baseUrl","endCC","endSN","fragments","live","needSidxRanges","startCC","startSN","startTimeOffset","targetduration","totalduration","DECIMAL_RESOLUTION_REGEX","ATTR_LIST_REGEX","AttrList","attrs","attr","parseAttrList","decimalInteger","attrName","intValue","hexadecimalInteger","stringValue","hexadecimalIntegerAsNumber","decimalFloatingPoint","parseFloat","enumeratedString","decimalResolution","res","input","lastIndex","sampleEntryCodesISO","isCodecSupportedInMp4","MediaSource","isTypeSupported","MASTER_PLAYLIST_REGEX","MASTER_PLAYLIST_MEDIA_REGEX","LEVEL_PLAYLIST_REGEX_FAST","source","LEVEL_PLAYLIST_REGEX_SLOW","MP4_REGEX_SUFFIX","M3U8Parser","findGroup","groups","mediaGroupId","group","convertAVC1ToAVCOTI","avcdata","substr","resolve","parseMasterPlaylist","string","levels","sessionData","hasSessionData","setCodecs","codecs","filtered","typeCodes","isCodecType","preferred","unknownCodecs","resolution","bitrate","NAME","CODECS","sessionAttrs","parseMasterPlaylistMedia","audioGroups","medias","TYPE","media","groupId","instreamId","LANGUAGE","DEFAULT","autoselect","AUTOSELECT","forced","FORCED","lang","URI","groupCodec","parseLevelPlaylist","levelUrlId","currentSN","discontinuityCounter","prevFrag","firstPdtIndex","assignProgramDateTime","value1","value2","toUpperCase","keyAttrs","decryptmethod","decrypturi","decryptiv","KEYFORMAT","mapAttrs","BYTERANGE","averagetargetduration","every","startIndex","fragPrev","backfillProgramDateTimes","endProgramDateTime","PlaylistLoader","loaders","canHaveQualityLevels","AUDIO_TRACK","SUBTITLE_TRACK","mapContextToLevelType","SUBTITLE","MAIN","getResponseUrl","response","createInternalLoader","PLoader","pLoader","Loader","getInternalLoader","resetInternalLoader","contextType","destroyInternalLoaders","onManifestLoading","load","MANIFEST","responseType","onLevelLoading","LEVEL","onAudioTrackLoading","onSubtitleTrackLoading","maxRetry","timeout","retryDelay","maxRetryDelay","loaderContext","abort","manifestLoadingMaxRetry","manifestLoadingTimeOut","manifestLoadingRetryDelay","manifestLoadingMaxRetryTimeout","levelLoadingTimeOut","levelLoadingMaxRetry","levelLoadingRetryDelay","levelLoadingMaxRetryTimeout","loaderConfig","loaderCallbacks","onSuccess","loadsuccess","onError","loaderror","onTimeout","loadtimeout","networkDetails","isSidxRequest","_handleSidxRequest","_handlePlaylistLoaded","tload","_handleTrackOrLevelPlaylist","_handleMasterPlaylist","_handleManifestParsingError","_handleNetworkError","audioTracks","subtitles","captions","embeddedAudioFound","unshift","levelId","levelType","levelDetails","singleLevel","tparsed","sidxUrl","rangeStart","rangeEnd","NETWORK_ERROR","LEVEL_EMPTY_ERROR","sidxInfo","sidxReferences","segmentRef","segRefInfo","MANIFEST_PARSING_ERROR","MANIFEST_LOAD_TIMEOUT","MANIFEST_LOAD_ERROR","LEVEL_LOAD_TIMEOUT","LEVEL_LOAD_ERROR","AUDIO_TRACK_LOAD_TIMEOUT","AUDIO_TRACK_LOAD_ERROR","errorData","FragmentLoader","loaderName","onFragLoading","FragmentILoader","fLoader","DefaultILoader","loaded","progressData","byteRangeStartOffset","fragLoadingTimeOut","fragLoadingMaxRetryTimeout","onProgress","loadprogress","FRAG_LOAD_ERROR","FRAG_LOAD_TIMEOUT","KeyLoader","decryptkey","decrypturl","onKeyLoading","fragLoadingRetryDelay","KEY_LOAD_ERROR","KEY_LOAD_TIMEOUT","FragmentState","FragmentTracker","bufferPadding","timeRanges","getBufferedFrag","bufferedFrags","fragmentEntity","body","buffered","bufferedFragKey","detectEvictedFragments","elementaryStream","timeRange","esData","range","fragmentTimes","time","isTimeBuffered","removeFragment","detectPartialFragments","fragKey","getFragmentKey","getBufferedTimes","fragmentPartial","partial","getPartialFragment","timePadding","bestFragment","bestOverlap","isPartial","getState","onFragLoaded","bitrateTest","onBufferAppended","onFragBuffered","hasFragment","removeAllFragments","BinarySearch","search","list","comparisonFn","minIndex","maxIndex","currentIndex","currentElement","comparisonResult","BufferHelper","isBuffered","bufferInfo","maxHoleDuration","vbuffered","bufferedInfo","nextStart","diff","buffered2","buf2len","buf2end","bufferStartNext","bufferLen","bufferStart","bufferEnd","getMediaSource","WebKitMediaSource","Observer","Demuxer","mp4","enableWorker","w","work","onwmsg","onWorkerMessage","onerror","filename","lineno","revokeObjectURL","removeEventListener","terminate","lastFrag","nextSN","ArrayBuffer","addGroupId","audioGroupIds","textGroupIds","updatePTS","fromIdx","toIdx","fragFrom","fragTo","fragToPTS","minEndPTS","updateFragPTSDTS","maxStartPTS","drift","fragIdx","PTSKnown","mapFragmentIntersection","oldPlaylist","newPlaylist","intersectionFn","oldFrag","newFrag","TimeRanges","toFixed","adjustPts","sliding","alignStream","lastLevel","shouldAlign","shouldAlignOnDiscontinuities","referenceFrag","prevDetails","curDetails","prevFrags","curFrags","prevStartFrag","firstFrag","currentFrag","findFirstFragWithCC","findDiscontinuousReferenceFrag","alignDiscontinuities","lastDetails","hasProgramDateTime","lastPDT","alignPDT","fragmentWithinToleranceTest","maxFragLookUpTolerance","candidate","candidateLookupTolerance","pdtWithinToleranceTest","pdtBufferEnd","GapController","fragmentTracker","nudgeRetry","stallReported","stalled","moved","seeking","poll","lastCurrentTime","currentTime","seeked","beginSeek","paused","ended","playbackRate","hasEnoughBuffer","noBufferGap","startJump","currentLevel","maxStartGapJump","_trySkipBufferHole","tnow","stalledDuration","_reportStall","bufferedWithHoles","_tryFixBufferStall","stalledDurationMs","highBufferWatchdogPeriod","_tryNudgeBuffer","BUFFER_STALLED_ERROR","lastEndTime","targetTime","BUFFER_SEEK_OVER_HOLE","nudgeMaxRetry","nudgeOffset","BUFFER_NUDGE_ON_STALL","State","chromeOrFirefox","StreamController","audioCodecSwap","_state","gapController","altAudio","audioOnly","startLoad","startPosition","stopLoad","setInterval","fragLoadError","startFragRequested","startLevel","testBandwidth","nextAutoLevel","nextLoadLevel","loadedmetadata","nextLoadPosition","tick","forceStartLoad","doTick","_doTickIdle","levelLastLoaded","retryDate","_checkBuffer","_checkFragmentChanged","startFragPrefetch","levelInfo","maxBufLen","levelBitrate","maxBufferSize","maxBufferLength","maxMaxBufferLength","mediaBuffer","_streamEnded","_fetchPayloadOrEos","fragPrevious","fragLen","initialLiveManifestSize","_ensureFragmentAtLivePoint","_findFragment","encrypted","_loadKey","_loadFragment","maxLatency","liveMaxLatencyDuration","liveMaxLatencyDurationCount","liveSyncPosition","computeLivePosition","readyState","PDTValue","isArray","seg","findFragmentByPDT","targetSN","fragNext","fragPreviousLoad","fragmentIndexRange","fragNextLoad","foundFragment","findFragmentByPTS","curSNIdx","sameLevel","prevSnFrag","nextSnFrag","backtracked","fragState","fragCurrent","autoLevel","autoLevelEnabled","_reduceMaxBufferLength","followingBufferedFrag","fragPlayingCurrent","fragPlaying","fragPlayingLevel","immediateLevelSwitch","immediateSwitch","previouslyPaused","pause","flushMainBuffer","immediateLevelSwitchEnd","play","nextLevelSwitch","fetchdelay","nextLevelId","nextLevel","fragLastKbps","bufferedFrag","nextBufferedFrag","startPts","endOffset","flushScope","onMediaAttached","onvseeking","onMediaSeeking","onvseeked","onMediaSeeked","onvended","onMediaEnded","autoStartLoad","onMediaDetaching","onManifestParsed","aac","heaac","audioCodecSwitch","onLevelLoaded","newDetails","newLevelId","curLevel","oldDetails","PTSFrag","ccOffset","newFragments","oldFragments","adjustSliding","LevelHelper","onKeyLoaded","fragLoaded","tbuffered","pendingBuffering","appended","initSegmentData","_getAudioCodec","onFragParsingInitSegment","fragNew","trackName","ua","levelCodec","parent","content","onFragParsingData","onFragParsed","_checkAppendedParsed","onAudioTrackSwitching","fromAltAudio","onAudioTrackSwitched","videoBuffer","onBufferCreated","mediaTrack","alternate","pending","total","tfirst","mediaBuffered","fragLoadingMaxRetry","delay","levelRetry","BUFFER_FULL_ERROR","minLength","_seekToStartPos","onFragLoadEmergencyAborted","onBufferFlushed","elementaryStreamType","onLevelsUpdated","swapAudioCodec","defaultAudioCodec","nextState","previousState","_liveSyncPosition","clearInterval","clearNextTick","tolerance","fragStartOffset","fragEndOffset","targetLatency","liveSyncDuration","liveSyncDurationCount","_boundTick","_tickTimer","_tickInterval","_tickCallCount","hasInterval","hasNextTick","millis","clearTimeout","setTimeout","LevelController","canload","currentLevelIndex","manualLevelIndex","timer","clearTimer","_levels","levelRetryCount","loadError","loadLevel","onManifestLoaded","bitrateStart","levelSet","levelFromSet","videoCodecFound","audioCodecFound","attributes","fragmentError","SUBTITLES","_firstLevel","firstLevel","some","MANIFEST_INCOMPATIBLE_CODECS_ERROR","setLevelInternal","newLevel","levelProperties","LEVEL_SWITCH_ERROR","levelIndex","levelError","recoverLevel","errorEvent","redundantLevels","errorDetails","reloadInterval","currentPlaylist","lastRequestTime","minReloadInterval","computeReloadInterval","trequest","audioGroupId","levelObject","removeLevel","_startLevel","configStartLevel","sendAddTrackEvent","videoEl","document","createEvent","initEvent","dispatchEvent","ID3TrackController","cues","removeCue","clearCurrentCues","getID3Track","textTracks","kind","label","addTextTrack","onFragParsingMetadata","Cue","WebKitDataCue","VTTCue","TextTrackCue","cue","addCue","onLiveBackBufferReached","foundCue","left","right","mid","getClosestCue","EWMA","halfLife","alpha_","estimate_","totalWeight_","exp","weight","adjAlpha","getTotalWeight","getEstimate","zeroFactor","EwmaBandWidthEstimator","slow","fast","defaultEstimate","defaultEstimate_","minWeight_","minDelayMs_","slow_","fast_","durationMs","numBytes","durationS","bandwidthInBps","canEstimate","AbrController","lastLoadedFragLevel","_nextAutoLevel","_bwEstimator","onCheck","_abandonRulesCheck","ewmaFast","ewmaSlow","abrEwmaFastLive","abrEwmaSlowLive","abrEwmaFastVoD","abrEwmaSlowVoD","abrEwmaDefaultEstimate","aborted","requestDelay","loadRate","bw","realBitrate","expectedLen","fragLoadedDelay","bufferStarvationDelay","minAutoLevel","levelNextBitrate","fragLevelNextLoadedDelay","abrMaxWithRealBitrate","loadedBytes","loadedDuration","fragLoadingProcessingMs","bwEstimate","bitrateTestDelay","_findBestLevel","currentFragDuration","currentBw","maxAutoLevel","maxFetchDuration","bwFactor","bwUpFactor","avgDuration","adjustedbw","fetchDuration","forcedAutoLevel","bwEstimator","nextABRAutoLevel","_nextABRAutoLevel","avgbw","bestLevel","abrBandWidthFactor","abrBandWidthUpFactor","maxStarvationDelay","maxLoadingDelay","BufferController","_msDuration","_levelDuration","_levelTargetDuration","_live","_objectUrl","_needsFlush","_needsEos","audioTimestampOffset","bufferCodecEventsExpected","_bufferCodecEventsTotal","mediaSource","segments","appending","appendError","flushBufferCounter","pendingTracks","sourceBuffer","flushRange","_onMediaSourceOpen","checkPendingTracks","_onMediaSourceClose","_onMediaSourceEnded","_onSBUpdateEnd","audioBuffer","timestampOffset","doFlush","checkEos","counter","segment","sbSet","sb","doAppending","updateMediaElementDuration","flushLiveBackBuffer","_onSBUpdateError","BUFFER_APPENDING_ERROR","onLevelPtsUpdated","updating","liveDurationInfinity","updateSeekableRange","codecEvents","onMediaAttaching","ms","endOfStream","removeAttribute","pendingTracksCount","createSourceBuffers","onBufferReset","removeSourceBuffer","onBufferCodecs","mimeType","addSourceBuffer","BUFFER_ADD_CODEC_ERROR","onBufferAppending","onBufferEos","onBufferFlushing","liveBackBufferLength","bufferTypes","targetBackBufferPosition","bufferType","removeBufferRange","onLevelUpdated","setLiveSeekableRange","flushBuffer","appendBuffer","code","BUFFER_APPEND_ERROR","appendErrorMaxRetry","sbType","bufStart","bufEnd","removeStart","removeEnd","remove","CapLevelController","autoLevelCapping","restrictedLevels","clientRect","capLevelToPlayerSize","stopCapping","onFpsDropLevelCapping","isLevelAllowed","droppedLevel","HTMLVideoElement","startCapping","detectPlayerSize","levelsLength","getMaxLevel","streamController","capLevelIndex","validLevels","getMaxLevelByMediaSize","mediaWidth","mediaHeight","getDimensions","boundsRect","getBoundingClientRect","bottom","top","maxLevelIndex","devicePixelRatio","contentScaleFactor","KeySystems","FPSController","isVideoPlaybackQualityAvailable","capLevelOnFPSDrop","getVideoPlaybackQuality","checkFPSInterval","fpsDroppedMonitoringPeriod","checkFPS","decodedFrames","droppedFrames","lastTime","currentPeriod","currentDropped","lastDroppedFrames","currentDecoded","lastDecodedFrames","droppedFPS","totalDroppedFrames","fpsDroppedMonitoringThreshold","videoPlaybackQuality","totalVideoFrames","droppedVideoFrames","webkitDecodedFrameCount","webkitDroppedFrameCount","XhrLoader","xhrSetup","requestTimeout","retryTimeout","callbacks","retry","loadInternal","xhr","XMLHttpRequest","open","status","setRequestHeader","onreadystatechange","readystatechange","onprogress","send","currentTarget","responseText","responseURL","statusText","lengthComputable","hlsDefaultConfig","lowBufferWatchdogPeriod","licenseXhrSetup","abrController","bufferController","capLevelController","fpsController","minAutoBitrate","emeEnabled","widevineLicenseUrl","drmSystemOptions","requestMediaKeySystemAccessFunc","requestMediaKeySystemAccess","cueHandler","Cues","enableCEA708Captions","__USE_SUBTITLES__","enableWebVTT","captionsTextTrack1Label","captionsTextTrack1LanguageCode","captionsTextTrack2Label","captionsTextTrack2LanguageCode","captionsTextTrack3Label","captionsTextTrack3LanguageCode","captionsTextTrack4Label","captionsTextTrack4LanguageCode","renderTextTracksNatively","subtitleStreamController","subtitleTrackController","timelineController","audioStreamController","audioTrackController","emeController","Hls","userConfig","_autoLevelCapping","levelController","networkControllers","coreComponents","defaultConfig","DefaultConfig","playListLoader","fragmentLoader","keyLoader","id3TrackController","Controller","isSupported","SourceBuffer","WebKitSourceBuffer","sourceBufferValidAPI","__VERSION__","detachMedia","component","attachMedia","loadSource","location","href","controller","recoverMediaError","manualLevel","shouldStartCapping","newCapLevelToPlayerSize","NaN","audioTrackId","subtitleTracks","subtitleTrack","subtitleTrackId","subtitleDisplay"],"mappings":"4BAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAa,IAAID,IAEjBD,EAAU,IAAIC,IARhB,CASGK,MAAM,WACT,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUP,QAGnC,IAAIC,EAASI,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GAAG,EACHT,QAAS,IAUV,OANAU,EAAQH,GAAUI,KAAKV,EAAOD,QAASC,EAAQA,EAAOD,QAASM,GAG/DL,EAAOQ,GAAI,EAGJR,EAAOD,QA0Df,OArDAM,EAAoBM,EAAIF,EAGxBJ,EAAoBO,EAAIR,EAGxBC,EAAoBQ,EAAI,SAASd,EAASe,EAAMC,GAC3CV,EAAoBW,EAAEjB,EAASe,IAClCG,OAAOC,eAAenB,EAASe,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEV,EAAoBgB,EAAI,SAAStB,GACX,oBAAXuB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAenB,EAASuB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAenB,EAAS,aAAc,CAAEyB,OAAO,KAQvDnB,EAAoBoB,EAAI,SAASD,EAAOE,GAEvC,GADU,EAAPA,IAAUF,EAAQnB,EAAoBmB,IA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AAGwoD,YAAa1mB,EAAO9hC,GAAGyiC,SAC1CX,EAAO9hC,GAAGyiC,SAES2xB,EACrB,OAAOp0D,EAIX,OAAO,I,mCAOmB,IAClB8hC,EAA6BliC,KAA7BkiC,OAAQutB,EAAqBzvD,KAArByvD,iBAShB,OAN0B,IAAtBA,GAA2BvtB,GAAUA,EAAOj6B,OAC/Bi6B,EAAOj6B,OAAS,EAEhBwnD,I,oCAYjB,OAAO3lD,KAAKoS,IAAIpS,KAAK4lB,IAAI1vB,KAAKo0D,cAAc5c,cAAex3C,KAAKgpD,cAAehpD,KAAK4pD,e,aAWnE7N,GACjB/7C,KAAKo0D,cAAc5c,cAAgB1tC,KAAK4lB,IAAI1vB,KAAKgpD,aAAcjN,K,kCAQ/D,IAAMia,EAAuBh2D,KAAKg2D,qBAClC,OAAOA,EAAuBA,EAAqB/sB,YAAc,K,iCAQjE,IAAM+sB,EAAuBh2D,KAAKg2D,qBAClC,OAAOA,EAAuBA,EAAqB5zC,YAAc,G,aAOnD41C,GACd,IAAMhC,EAAuBh2D,KAAKg2D,qBAC9BA,IACFA,EAAqB5zC,WAAa41C,K,uCAQpC,OAAOh4D,KAAKswD,iBAAiB7W,mB,qCAS7B,IAAMoc,EAA0B71D,KAAK61D,wBACrC,OAAOA,EAA0BA,EAAwBoC,eAAiB,K,oCAQ1E,IAAMpC,EAA0B71D,KAAK61D,wBACrC,OAAOA,EAA0BA,EAAwBqC,eAAiB,G,aAOzDC,GACjB,IAAMtC,EAA0B71D,KAAK61D,wBACjCA,IACFA,EAAwBqC,cAAgBC,K,sCAQ1C,IAAMtC,EAA0B71D,KAAK61D,wBACrC,QAAOA,GAA0BA,EAAwBuC,iB,aAOtC/2D,GACnB,IAAMw0D,EAA0B71D,KAAK61D,wBACjCA,IACFA,EAAwBuC,gBAAkB/2D,O,GAnpBf4uC,GAAZimB,GACLM,mB","file":"hls.light.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 = 13);\n","import { getSelfScope } from './get-self-scope';\n\nfunction noop (...args) {}\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 const enableLogs = function (debugConfig) {\n // check that console is available\n if ((global.console && 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 const 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 levels have changed after removing a level - data: { levels : [available quality levels] }\n LEVELS_UPDATED: 'hlsLevelsUpdated',\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 a set of VTTCues to be managed externally has been parsed - data: { type: string, track: string, cues: [ VTTCue ] }\n CUES_PARSED: 'hlsCuesParsed',\n // fired when a text track to be managed externally is found - data: { tracks: [ { label: string, kind: string, default: boolean } ] }\n NON_NATIVE_TEXT_TRACKS_FOUND: 'hlsNonNativeTextTracksFound',\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 // fired when the live back buffer is reached defined by the liveBackBufferLength config option - data : { bufferEnd: number }\n LIVE_BACK_BUFFER_REACHED: 'hlsLiveBackBufferReached'\n};\n\nexport default HlsEvents;\n","export enum 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 enum 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 KEY_SYSTEM_NO_INIT_DATA = 'keySystemNoInitData',\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 which contains no fragments - data: { url: faulty URL, reason: \"no fragments found in level\", level: index of the bad level }\n LEVEL_EMPTY_ERROR = 'levelEmptyError',\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","export const isFiniteNumber = Number.isFinite || function (value) {\n return typeof value === 'number' && isFinite(value);\n};\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;\n","import { getSelfScope } from '../utils/get-self-scope';\n\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: \\0\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), true);\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), true);\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 \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 decoder = getTextDecoder();\n if (decoder) {\n const decoded = decoder.decode(array);\n\n if (exitOnNull) {\n // grab up to the first null\n const idx = decoded.indexOf('\\0');\n return idx !== -1 ? decoded.substring(0, idx) : decoded;\n }\n\n // remove any null characters\n return decoded.replace(/\\0/g, '');\n }\n\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\nlet decoder;\n\nfunction getTextDecoder () {\n const global = getSelfScope(); // safeguard for code that might run both on worker and main thread\n if (!decoder && typeof global.TextDecoder !== 'undefined') {\n decoder = new global.TextDecoder('utf-8');\n }\n\n return decoder;\n}\n\nconst utf8ArrayToStr = ID3._utf8ArrayToStr;\n\nexport default ID3;\n\nexport { utf8ArrayToStr };\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","// This file is inserted as a shim for modules which we do not want to include into the distro.\n// This replacement is done in the \"resolve\" section of the webpack config.\nmodule.exports = void 0;\n","// see https://tools.ietf.org/html/rfc1808\n\n(function (root) {\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 = {\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(\n basePartsForNormalise.path\n );\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 is non-empty, we skip to\n // Step 7. Otherwise, the embedded URL inherits the \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 is non-empty, we skip to\n // step 7; otherwise, it inherits the of the base\n // URL (if any) and\n if (!relativeParts.params) {\n builtParts.params = baseParts.params;\n // 5b) if the embedded URL's is non-empty, we skip to\n // step 7; otherwise, it inherits the 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 =\n baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +\n relativeParts.path;\n builtParts.path = URLToolkit.normalizePath(newPath);\n }\n }\n }\n if (builtParts.path === null) {\n builtParts.path = opts.alwaysNormalize\n ? URLToolkit.normalizePath(relativeParts.path)\n : 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 \"/../\", where 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 \"/..\", where is a\n // complete path segment not equal to \"..\", that\n // \"/..\" is removed.\n while (\n path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length\n ) {}\n return path.split('').reverse().join('');\n },\n buildURLFromParts: function (parts) {\n return (\n parts.scheme +\n parts.netLoc +\n parts.path +\n parts.params +\n parts.query +\n parts.fragment\n );\n },\n };\n\n if (typeof exports === 'object' && typeof module === 'object')\n module.exports = URLToolkit;\n else if (typeof define === 'function' && define.amd)\n define([], function () {\n return URLToolkit;\n });\n else if (typeof exports === 'object') exports['URLToolkit'] = URLToolkit;\n else root['URLToolkit'] = URLToolkit;\n})(this);\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","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","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 * ADTS parser helper\n * @link https://wiki.multimedia.cx/index.php?title=ADTS\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 (isHeader(data, offset)) {\n // ADTS header Length\n let headerLength = getHeaderLength(data, offset);\n if (offset + headerLength >= data.length) {\n return false;\n }\n // ADTS frame Length\n let frameLength = getFullFrameLength(data, offset);\n if (frameLength <= headerLength) {\n return false;\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 return { sample: aacSample, length: frameLength + headerLength };\n }\n\n return undefined;\n}\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 * 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\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","/**\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 * 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';\nimport { utf8ArrayToStr } from './id3';\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 this.pmtUnknownTypes = {};\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 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 this.pmtUnknownTypes = {};\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.pmtUnknownTypes = {};\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.bind(this),\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))) {\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))) {\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))) {\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))) {\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))) {\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))) {\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 _trackUnknownPmt (type, logLevel, message) {\n // Only log unknown and unsupported stream types once per append or stream (by resetting this.pmtUnknownTypes)\n // For more information on elementary stream types see:\n // https://en.wikipedia.org/wiki/Program-specific_information#Elementary_stream_types\n const result = this.pmtUnknownTypes[type] || 0;\n if (result === 0) {\n this.pmtUnknownTypes[type] = 0;\n logLevel.call(logger, message);\n }\n this.pmtUnknownTypes[type]++;\n return result;\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 this._trackUnknownPmt(data[offset], logger.warn, 'ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream');\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 this._trackUnknownPmt(data[offset], logger.warn, 'H.264 with AES-128-CBC slice encryption found in unencrypted stream');\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 this._trackUnknownPmt(data[offset], logger.warn, 'MPEG audio found, not supported in this browser');\n } else if (result.audio === -1) {\n result.audio = pid;\n result.isAAC = false;\n }\n break;\n\n case 0x24:\n this._trackUnknownPmt(data[offset], logger.warn, 'Unsupported HEVC stream type found');\n break;\n\n default:\n this._trackUnknownPmt(data[offset], logger.log, 'Unknown 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\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\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 if (stream.size <= payloadStartOffset) {\n return null;\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 // if sample does not have PTS/DTS, patch with last sample PTS/DTS\n if (isNaN(avcSample.pts)) {\n if (nbSamples) {\n const lastSample = samples[nbSamples - 1];\n avcSample.pts = lastSample.pts;\n avcSample.dts = lastSample.dts;\n } else {\n // dropping samples, no timestamp found\n avcTrack.dropped++;\n return;\n }\n }\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 (payloadType === 5 && expGolombDecoder.bytesAvailable !== 0) {\n endOfCaptions = true;\n\n if (payloadSize > 16) {\n const uuidStrArray = [];\n for (i = 0; i < 16; i++) {\n uuidStrArray.push(expGolombDecoder.readUByte().toString(16));\n\n if (i === 3 || i === 5 || i === 7 || i === 9) {\n uuidStrArray.push('-');\n }\n }\n const length = payloadSize - 16;\n const userDataPayloadBytes = new Uint8Array(length);\n for (i = 0; i < length; i++) {\n userDataPayloadBytes[i] = expGolombDecoder.readUByte();\n }\n\n this._insertSampleInOrder(this._txtTrack.samples, {\n pts: pes.pts,\n payloadType: payloadType,\n uuid: uuidStrArray.join(''),\n userDataBytes: userDataPayloadBytes,\n userData: utf8ArrayToStr(userDataPayloadBytes.buffer)\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)) {\n if ((offset + 5) < len) {\n const frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n stamp = frame.sample.pts;\n frameIndex++;\n continue;\n }\n }\n // We are at an ADTS header, but do not have enough data for a frame\n // Remaining data will be added to aacOverFlow\n break;\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 * 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 !== undefined ? 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 * 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","const MPEG_TS_CLOCK_FREQ_HZ = 90000;\n\nexport function toTimescaleFromScale (value, destScale: number, srcScale: number = 1, round: boolean = false): number {\n return toTimescaleFromBase(value, destScale, 1 / srcScale);\n}\n\nexport function toTimescaleFromBase (value, destScale: number, srcBase: number = 1, round: boolean = false): number {\n const result = value * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`\n return round ? Math.round(result) : result;\n}\n\nexport function toMsFromMpegTsClock (value: number, round: boolean = false): number {\n return toTimescaleFromBase(value, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);\n}\n\nexport function toMpegTsClockFromTimescale (value: number, srcScale: number = 1): number {\n return toTimescaleFromBase(value, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);\n}\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 { toMsFromMpegTsClock, toMpegTsClockFromTimescale } from '../utils/timescale-conversion';\n\nimport { logger } from '../utils/logger';\n\nconst MAX_SILENT_FRAME_DURATION_90KHZ = toMpegTsClockFromTimescale(10);\nconst PTS_DTS_SHIFT_TOLERANCE_90KHZ = toMpegTsClockFromTimescale(0.2);\n\nlet chromeVersion = null;\n\nclass MP4Remuxer {\n constructor (observer, config, typeSupported, vendor) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n this.ISGenerated = false;\n if (chromeVersion === null) {\n const result = navigator.userAgent.match(/Chrome\\/(\\d+)/i);\n chromeVersion = result ? parseInt(result[1]) : 0;\n }\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 getVideoStartPts (videoSamples) {\n let rolloverDetected = false;\n const startPTS = videoSamples.reduce((minPTS, sample) => {\n const delta = sample.pts - minPTS;\n if (delta < -4294967296) { // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation\n rolloverDetected = true;\n return minPTS;\n } else if (delta > 0) {\n return minPTS;\n } else {\n return sample.pts;\n }\n }, videoSamples[0].pts);\n if (rolloverDetected) {\n logger.debug('PTS rollover detected');\n }\n return startPTS;\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 const startPTS = this.getVideoStartPts(videoTrack.samples);\n const tsDelta = audioTrack.samples[0].pts - startPTS;\n const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;\n audioTimeOffset += Math.max(0, audiovideoTimestampDelta);\n videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);\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, videoTimeOffset);\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);\n }\n } else {\n // logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (nbVideoSamples) {\n let videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0);\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 },\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 - Math.round(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 const startPTS = this.getVideoStartPts(videoSamples);\n const startOffset = Math.round(inputTimeScale * timeOffset);\n initDTS = Math.min(initDTS, videoSamples[0].dts - startOffset);\n initPTS = Math.min(initPTS, startPTS - startOffset);\n this.observer.trigger(Event.INIT_PTS_FOUND, { initPTS });\n }\n } else if (computePTSDTS && tracks.audio) {\n // initPTS found for audio-only stream with main and alt audio\n this.observer.trigger(Event.INIT_PTS_FOUND, { initPTS });\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) {\n const timeScale = track.timescale;\n const inputSamples = track.samples;\n const outputSamples = [];\n const nbSamples = inputSamples.length;\n const initPTS = this._initPTS;\n\n let offset = 8;\n let mp4SampleDuration;\n let mdat;\n let moof;\n let firstDTS;\n let lastDTS;\n let minPTS = Number.POSITIVE_INFINITY;\n let maxPTS = Number.NEGATIVE_INFINITY;\n let ptsDtsShift = 0;\n let sortSamples = false;\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 if (nbSamples === 0) {\n return;\n }\n\n if (!contiguous) {\n const pts = timeOffset * timeScale;\n const cts = inputSamples[0].pts - PTSNormalize(inputSamples[0].dts, inputSamples[0].pts);\n // if not contiguous, let's use target timeOffset\n nextAvcDts = pts - cts;\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 for (let i = 0; i < nbSamples; i++) {\n const sample = inputSamples[i];\n sample.pts = PTSNormalize(sample.pts - initPTS, nextAvcDts);\n sample.dts = PTSNormalize(sample.dts - initPTS, nextAvcDts);\n if (sample.dts > sample.pts) {\n ptsDtsShift = Math.max(Math.min(ptsDtsShift, sample.pts - sample.dts), -1 * PTS_DTS_SHIFT_TOLERANCE_90KHZ);\n }\n if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {\n sortSamples = true;\n }\n }\n\n // sort video samples by DTS then PTS then demux id order\n if (sortSamples) {\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\n // Get first/last DTS\n firstDTS = inputSamples[0].dts;\n lastDTS = inputSamples[nbSamples - 1].dts;\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 const averageSampleDuration = Math.round((lastDTS - firstDTS) / (nbSamples - 1));\n\n // handle broken streams with PTS < DTS, tolerance up 0.2 seconds\n if (ptsDtsShift < 0) {\n if (ptsDtsShift < averageSampleDuration * -2) {\n // Fix for \"CNN special report, with CC\" in test-streams (including Safari browser)\n logger.warn(`PTS < DTS detected in video samples, offsetting DTS to PTS ${toMsFromMpegTsClock(-averageSampleDuration, true)} ms`);\n for (let i = 0; i < nbSamples; i++) {\n inputSamples[i].dts = inputSamples[i].pts - averageSampleDuration;\n }\n } else {\n // Fix for \"Custom IV with bad PTS DTS\" in test-streams\n logger.warn(`PTS < DTS detected in video samples, shifting DTS by ${toMsFromMpegTsClock(ptsDtsShift, true)} ms to overcome this issue`);\n for (let i = 0; i < nbSamples; i++) {\n inputSamples[i].dts = inputSamples[i].dts + ptsDtsShift;\n }\n }\n firstDTS = inputSamples[0].dts;\n lastDTS = inputSamples[nbSamples - 1].dts;\n }\n\n // if fragment are contiguous, detect hole/overlapping between fragments\n if (contiguous) {\n // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)\n const delta = firstDTS - nextAvcDts;\n const foundHole = delta > averageSampleDuration;\n const foundOverlap = delta < -1;\n if (foundHole || foundOverlap) {\n if (foundHole) {\n logger.warn(`AVC: ${toMsFromMpegTsClock(delta, true)} ms (${delta}dts) hole between fragments detected, filling it`);\n } else {\n logger.warn(`AVC: ${toMsFromMpegTsClock(-delta, true)} ms (${delta}dts) overlapping between fragments detected`);\n }\n firstDTS = nextAvcDts;\n const firstPTS = inputSamples[0].pts - delta;\n inputSamples[0].dts = firstDTS;\n inputSamples[0].pts = firstPTS;\n logger.log(`Video: First PTS/DTS adjusted: ${toMsFromMpegTsClock(firstPTS, true)}/${toMsFromMpegTsClock(firstDTS, true)}, delta: ${toMsFromMpegTsClock(delta, true)} ms`);\n }\n }\n\n if (chromeVersion && chromeVersion < 75) {\n firstDTS = Math.max(0, firstDTS);\n }\n let nbNalu = 0;\n let naluLen = 0;\n for (let i = 0; i < nbSamples; i++) {\n // compute total/avc sample length and nb of NAL units\n const sample = inputSamples[i];\n const units = sample.units;\n const nbUnits = units.length;\n let 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 // ensure sample monotonic DTS\n sample.dts = Math.max(sample.dts, firstDTS);\n // ensure that computed value is greater or equal than sample DTS\n sample.pts = Math.max(sample.pts, sample.dts, 0);\n minPTS = Math.min(sample.pts, minPTS);\n maxPTS = Math.max(sample.pts, maxPTS);\n }\n lastDTS = inputSamples[nbSamples - 1].dts;\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 const avcSample = inputSamples[i];\n const avcSampleUnits = avcSample.units;\n let mp4SampleLength = 0;\n let 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 const unit = avcSampleUnits[j];\n const unitData = unit.data;\n const 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 // 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 const config = this.config;\n const 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 const maxBufferHole = config.maxBufferHole;\n const gapTolerance = Math.floor(maxBufferHole * timeScale);\n const deltaToFrameEnd = (audioTrackLength ? minPTS + 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 ${toMsFromMpegTsClock(deltaToFrameEnd, false)} ms to the next segment; using duration ${toMsFromMpegTsClock(mp4SampleDuration, false)} 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\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 const dropped = track.dropped;\n track.nbNalu = 0;\n track.dropped = 0;\n if (outputSamples.length && chromeVersion && chromeVersion < 70) {\n const 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 const data = {\n data1: moof,\n data2: mdat,\n startPTS: minPTS / timeScale,\n endPTS: (maxPTS + 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, videoTimeOffset) {\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 initPTS = this._initPTS;\n const rawMPEG = !track.isAAC && this.typeSupported.mpeg;\n\n let mp4Sample;\n let fillFrame;\n let mdat;\n let moof;\n let firstPTS;\n let lastPTS;\n let offset = (rawMPEG ? 0 : 8);\n let inputSamples = track.samples;\n let outputSamples = [];\n let 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((sample) => sample.pts >= 0);\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 (videoTimeOffset === 0) {\n // Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence\n nextAudioPts = 0;\n } else if (accurateTimeOffset) {\n // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS\n nextAudioPts = Math.max(0, timeOffset * inputTimeScale);\n } else {\n // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS\n nextAudioPts = inputSamples[0].pts;\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 const sample = inputSamples[i];\n let pts = sample.pts;\n let delta = pts - nextPts;\n\n // If we're overlapping by more than a duration, drop this sample\n if (delta <= -maxAudioFramesDrift * inputSampleDuration) {\n if (contiguous || i > 0) {\n logger.warn(`Dropping 1 audio frame @ ${toMsFromMpegTsClock(nextPts, true) / 1000}s due to ${toMsFromMpegTsClock(delta, true)} ms overlap.`);\n inputSamples.splice(i, 1);\n // Don't touch nextPtsNorm or i\n } else {\n // When changing qualities we can't trust that audio has been appended up to nextAudioPts\n // Warn about the overlap but do not drop samples as that can introduce buffer gaps\n logger.warn(`Audio frame @ ${toMsFromMpegTsClock(pts, true) / 1000}s overlaps nextAudioPts by ${toMsFromMpegTsClock(delta, true)} ms.`);\n nextPts = pts + inputSampleDuration;\n i++;\n }\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 else if (delta >= maxAudioFramesDrift * inputSampleDuration && delta < MAX_SILENT_FRAME_DURATION_90KHZ) {\n const missing = Math.floor(delta / inputSampleDuration);\n // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from\n // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.\n nextPts = pts - missing * inputSampleDuration;\n logger.warn(`Injecting ${missing} audio frames @ ${toMsFromMpegTsClock(nextPts, true) / 1000}s due to ${toMsFromMpegTsClock(delta, true)} 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 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 // compute mdat size, as we eventually filtered/added some samples\n let nbSamples = inputSamples.length;\n let mdatSize = 0;\n while (nbSamples--) {\n mdatSize += inputSamples[nbSamples].unit.byteLength;\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\n // logger.log(`Audio/PTS:${toMsFromMpegTsClock(pts, true)}`);\n // if not first sample\n\n if (lastPTS !== undefined && mp4Sample) {\n mp4Sample.duration = Math.round((pts - lastPTS) / scaleFactor);\n } else {\n let delta = pts - nextAudioPts;\n let numMissingFrames = 0;\n\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_90KHZ) {\n // Q: why do we have to round here, shouldn't this always result in an integer if timestamps are correct,\n // and if not, shouldn't we actually Math.ceil() instead?\n numMissingFrames = Math.round((pts - nextAudioPts) / inputSampleDuration);\n\n logger.log(`${toMsFromMpegTsClock(delta, true)} 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 mdatSize += 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: ${toMsFromMpegTsClock(nextAudioPts, true)} ms / ${toMsFromMpegTsClock(pts, true)} ms / ${toMsFromMpegTsClock(-delta, true)} ms`);\n mdatSize -= 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 (mdatSize > 0) {\n mdatSize += offset;\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 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.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 let mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;\n let scaleFactor = inputTimeScale / mp4timeScale;\n let nextAudioPts = this.nextAudioPts;\n\n // sync with video's timestamp\n let startDTS = (nextAudioPts !== undefined ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS;\n let endDTS = videoData.endDTS * inputTimeScale + this._initDTS;\n // one sample's duration value\n let sampleDuration = 1024;\n let frameDuration = scaleFactor * sampleDuration;\n\n // samples count of this segment's duration\n let nbSamples = Math.ceil((endDTS - startDTS) / frameDuration);\n\n // silent frame\n let 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 }\n track.samples = samples;\n\n this.remuxAudio(track, timeOffset, contiguous);\n }\n\n remuxID3 (track, timeOffset) {\n const length = track.samples.length;\n if (!length) {\n return;\n }\n const inputTimeScale = track.inputTimeScale;\n const initPTS = this._initPTS;\n const initDTS = this._initDTS;\n // consume samples\n for (let index = 0; index < length; index++) {\n const 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 = PTSNormalize(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;\n sample.dts = PTSNormalize(sample.dts - initDTS, timeOffset * inputTimeScale) / inputTimeScale;\n }\n this.observer.trigger(Event.FRAG_PARSING_METADATA, {\n samples: track.samples\n });\n\n track.samples = [];\n }\n\n remuxText (track, timeOffset) {\n const length = track.samples.length;\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 const 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 = PTSNormalize(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;\n }\n track.samples.sort(function (a, b) {\n return (a.pts - b.pts);\n });\n this.observer.trigger(Event.FRAG_PARSING_USERDATA, {\n samples: track.samples\n });\n }\n\n track.samples = [];\n }\n}\n\nfunction 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\nexport default MP4Remuxer;\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 let remuxer = this.remuxer;\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 (discontinuity || trackSwitch)) {\n const observer = this.observer;\n const typeSupported = this.typeSupported;\n const config = this.config;\n // probing order is TS/MP4/AAC/MP3\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 let mux;\n for (let i = 0, len = muxConfig.length; i < len; i++) {\n mux = muxConfig[i];\n if (mux.demux.probe(data)) {\n break;\n }\n }\n if (!mux) {\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 // so let's check that current remuxer and demuxer are still valid\n if (!remuxer || !(remuxer instanceof mux.remux)) {\n remuxer = new mux.remux(observer, config, typeSupported, this.vendor);\n }\n if (!demuxer || !(demuxer instanceof mux.demux)) {\n demuxer = new mux.demux(observer, remuxer, config, typeSupported);\n this.probe = mux.demux.probe;\n }\n this.demuxer = demuxer;\n this.remuxer = remuxer;\n }\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 * 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","/**\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","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*(\\/\\\\*.*?\\\\*\\/)?\\\\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*\\(\\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","/* 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 'eventemitter3';\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","import Level from '../loader/level';\n\nexport interface LoaderContext {\n // target URL\n url: string\n // loader response type (arraybuffer or default response type for playlist)\n responseType: string\n // start byte range offset\n rangeStart?: number\n // end byte range offset\n rangeEnd?: number\n // true if onProgress should report partial chunk of loaded content\n progressData?: boolean\n}\n\nexport interface LoaderConfiguration {\n // Max number of load retries\n maxRetry: number\n // Timeout after which `onTimeOut` callback will be triggered\n // (if loading is still not finished after that delay)\n timeout: number\n // Delay between an I/O error and following connection retry (ms).\n // This to avoid spamming the server\n retryDelay: number\n // max connection retry delay (ms)\n maxRetryDelay: number\n}\n\nexport interface LoaderResponse {\n url: string,\n // TODO(jstackhouse): SharedArrayBuffer, es2017 extension to TS\n data: string | ArrayBuffer\n}\n\nexport interface LoaderStats {\n // performance.now() just after load() has been called\n trequest: number\n // performance.now() of first received byte\n tfirst: number\n // performance.now() on load complete\n tload: number\n // performance.now() on parse completion\n tparsed: number\n // number of loaded bytes\n loaded: number\n // total number of bytes\n total: number\n}\n\ntype LoaderOnSuccess < T extends LoaderContext > = (\n response: LoaderResponse,\n stats: LoaderStats,\n context: T,\n networkDetails: any\n) => void;\n\ntype LoaderOnProgress < T extends LoaderContext > = (\n stats: LoaderStats,\n context: T,\n data: string | ArrayBuffer,\n networkDetails: any,\n) => void;\n\ntype LoaderOnError < T extends LoaderContext > = (\n error: {\n // error status code\n code: number,\n // error description\n text: string,\n },\n context: T,\n networkDetails: any,\n) => void;\n\ntype LoaderOnTimeout < T extends LoaderContext > = (\n stats: LoaderStats,\n context: T,\n) => void;\n\nexport interface LoaderCallbacks{\n onSuccess: LoaderOnSuccess,\n onError: LoaderOnError,\n onTimeout: LoaderOnTimeout,\n onProgress?: LoaderOnProgress,\n}\n\nexport interface Loader {\n destroy(): void\n abort(): void\n load(\n context: LoaderContext,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks,\n ): void\n\n context: T\n}\n\n/**\n * `type` property values for this loaders' context object\n * @enum\n *\n */\nexport enum PlaylistContextType {\n MANIFEST = 'manifest',\n LEVEL = 'level',\n AUDIO_TRACK = 'audioTrack',\n SUBTITLE_TRACK= 'subtitleTrack'\n}\n\n/**\n * @enum {string}\n */\nexport enum PlaylistLevelType {\n MAIN = 'main',\n AUDIO = 'audio',\n SUBTITLE = 'subtitle'\n}\n\nexport interface PlaylistLoaderContext extends LoaderContext {\n loader?: Loader\n\n type: PlaylistContextType\n // the level index to load\n level: number | null\n // TODO: what is id?\n id: number | null\n // defines if the loader is handling a sidx request for the playlist\n isSidxRequest?: boolean\n // internal reprsentation of a parsed m3u8 level playlist\n levelDetails?: Level\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';\nimport Hls from './hls';\n\nconst FORBIDDEN_EVENT_NAMES = {\n 'hlsEventGeneric': true,\n 'hlsHandlerDestroying': true,\n 'hlsHandlerDestroyed': true\n};\n\nclass EventHandler {\n hls: Hls;\n handledEvents: any[];\n useGenericHandler: boolean;\n\n constructor (hls: Hls, ...events: any[]) {\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 protected onHandlerDestroying () {}\n protected 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: string, data: any) {\n this.onEventGeneric(event, data);\n }\n\n onEventGeneric (event: string, data: any) {\n let eventToFunction = function (event: string, data: any) {\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","\nimport { buildAbsoluteURL } from 'url-toolkit';\nimport { logger } from '../utils/logger';\nimport LevelKey from './level-key';\nimport { PlaylistLevelType } from '../types/loader';\n\nexport enum ElementaryStreamTypes {\n AUDIO = 'audio',\n VIDEO = 'video',\n}\n\nexport default class Fragment {\n private _url: string | null = null;\n private _byteRange: number[] | null = null;\n private _decryptdata: LevelKey | null = null;\n\n // Holds the types of data this fragment supports\n private _elementaryStreams: Record = {\n [ElementaryStreamTypes.AUDIO]: false,\n [ElementaryStreamTypes.VIDEO]: false\n };\n\n // deltaPTS tracks the change in presentation timestamp between fragments\n public deltaPTS: number = 0;\n\n public rawProgramDateTime: string | null = null;\n public programDateTime: number | null = null;\n public title: string | null = null;\n public tagList: Array = [];\n\n // TODO: Move at least baseurl to constructor.\n // Currently we do a two-pass construction as use the Fragment class almost like a object for holding parsing state.\n // It may make more sense to just use a POJO to keep state during the parsing phase.\n // Have Fragment be the representation once we have a known state?\n // Something to think on.\n\n // Discontinuity Counter\n public cc!: number;\n\n public type!: PlaylistLevelType;\n // relurl is the portion of the URL that comes from inside the playlist.\n public relurl!: string;\n // baseurl is the URL to the playlist\n public baseurl!: string;\n // EXTINF has to be present for a m3u8 to be considered valid\n public duration!: number;\n // When this segment starts in the timeline\n public start!: number;\n // sn notates the sequence number for a segment, and if set to a string can be 'initSegment'\n public sn: number | 'initSegment' = 0;\n\n public urlId: number = 0;\n // level matches this fragment to a index playlist\n public level: number = 0;\n // levelkey is the EXT-X-KEY that applies to this segment for decryption\n // core difference from the private field _decryptdata is the lack of the initialized IV\n // _decryptdata will set the IV for this segment based on the segment number in the fragment\n public levelkey?: LevelKey;\n\n // TODO(typescript-xhrloader)\n public loader: any;\n\n // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array\n setByteRange (value: string, previousFrag?: Fragment) {\n const params = value.split('@', 2);\n const byteRange: number[] = [];\n if (params.length === 1) {\n byteRange[0] = previousFrag ? previousFrag.byteRangeEndOffset : 0;\n } else {\n byteRange[0] = parseInt(params[1]);\n }\n byteRange[1] = parseInt(params[0]) + byteRange[0];\n this._byteRange = byteRange;\n }\n\n get url () {\n if (!this._url && this.relurl) {\n this._url = 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 (): number[] {\n if (!this._byteRange) {\n return [];\n }\n\n return this._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 (): LevelKey | null {\n if (!this.levelkey && !this._decryptdata) {\n return null;\n }\n\n if (!this._decryptdata && this.levelkey) {\n let sn = this.sn;\n if (typeof sn !== 'number') {\n // We are fetching decryption data for a initialization segment\n // If the segment was encrypted with AES-128\n // It must have an IV defined. We cannot substitute the Segment Number in.\n if (this.levelkey && this.levelkey.method === 'AES-128' && !this.levelkey.iv) {\n logger.warn(`missing IV for initialization segment with method=\"${this.levelkey.method}\" - compliance issue`);\n }\n\n /*\n Be converted to a Number.\n 'initSegment' will become NaN.\n NaN, which when converted through ToInt32() -> +0.\n ---\n Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.\n */\n sn = 0;\n }\n this._decryptdata = this.setDecryptDataFromLevelKey(this.levelkey, sn);\n }\n\n return this._decryptdata;\n }\n\n get endProgramDateTime () {\n if (this.programDateTime === null) {\n return null;\n }\n\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 {ElementaryStreamTypes} type\n */\n addElementaryStream (type: ElementaryStreamTypes) {\n this._elementaryStreams[type] = true;\n }\n\n /**\n * @param {ElementaryStreamTypes} type\n */\n hasElementaryStream (type: ElementaryStreamTypes) {\n return this._elementaryStreams[type] === true;\n }\n\n /**\n * Utility method for parseLevelPlaylist to create an initialization vector for a given segment\n * @param {number} segmentNumber - segment number to generate IV with\n * @returns {Uint8Array}\n */\n createInitializationVector (segmentNumber: number): Uint8Array {\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 {LevelKey} - an object to be applied as a fragment's decryptdata\n */\n setDecryptDataFromLevelKey (levelkey: LevelKey, segmentNumber: number): LevelKey {\n let decryptdata = levelkey;\n\n if (levelkey?.method && levelkey.uri && !levelkey.iv) {\n decryptdata = new LevelKey(levelkey.baseuri, levelkey.reluri);\n decryptdata.method = levelkey.method;\n decryptdata.iv = this.createInitializationVector(segmentNumber);\n }\n\n return decryptdata;\n }\n}\n","import { buildAbsoluteURL } from 'url-toolkit';\n\nexport default class LevelKey {\n private _uri: string | null = null;\n\n public baseuri: string;\n public reluri: string;\n public method: string | null = null;\n public key: Uint8Array | null = null;\n public iv: Uint8Array | null = null;\n\n constructor (baseURI: string, relativeURI: string) {\n this.baseuri = baseURI;\n this.reluri = relativeURI;\n }\n\n get uri () {\n if (!this._uri && this.reluri) {\n this._uri = buildAbsoluteURL(this.baseuri, this.reluri, { alwaysNormalize: true });\n }\n\n return this._uri;\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","// 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\nexport type CodecType = 'audio' | 'video';\n\nfunction isCodecType (codec: string, type: CodecType): boolean {\n const typeCodes = sampleEntryCodesISO[type];\n return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;\n}\n\nfunction isCodecSupportedInMp4 (codec: string, type: CodecType): boolean {\n return MediaSource.isTypeSupported(`${type || 'video'}/mp4;codecs=\"${codec}\"`);\n}\n\nexport { isCodecType, isCodecSupportedInMp4 };\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, CodecType } from '../utils/codecs';\nimport { MediaPlaylist, AudioGroup, MediaPlaylistType } from '../types/media-playlist';\nimport { PlaylistLevelType } from '../types/loader';\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]+)|#EXT-X-SESSION-DATA:([^\\n\\r]*)[\\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:,), 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: Array<AudioGroup>, mediaGroupId: string): AudioGroup | undefined {\n for (let i = 0; i < groups.length; i++) {\n const group = groups[i];\n if (group.id === mediaGroupId) {\n return group;\n }\n }\n }\n\n static convertAVC1ToAVCOTI (codec) {\n let avcdata = codec.split('.');\n let result;\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: string, baseurl: string) {\n // TODO(typescript-level)\n let levels: Array<any> = [];\n let sessionData: Record<string, AttrList> = {};\n let hasSessionData = false;\n MASTER_PLAYLIST_REGEX.lastIndex = 0;\n\n // TODO(typescript-level)\n function setCodecs (codecs: Array<string>, level: any) {\n ['video', 'audio'].forEach((type: CodecType) => {\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 let result: RegExpExecArray | null;\n while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {\n if (result[1]) {\n // '#EXT-X-STREAM-INF' is found, parse level tag in group 1\n\n // TODO(typescript-level)\n const level: any = {};\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 } else if (result[3]) {\n // '#EXT-X-SESSION-DATA' is found, parse session data in group 3\n let sessionAttrs = new AttrList(result[3]);\n if (sessionAttrs['DATA-ID']) {\n hasSessionData = true;\n sessionData[sessionAttrs['DATA-ID']] = sessionAttrs;\n }\n }\n }\n return {\n levels,\n sessionData: hasSessionData ? sessionData : null\n };\n }\n\n static parseMasterPlaylistMedia (string: string, baseurl: string, type: MediaPlaylistType, audioGroups: Array<AudioGroup> = []): Array<MediaPlaylist> {\n let result: RegExpExecArray | null;\n let medias: Array<MediaPlaylist> = [];\n let id = 0;\n MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;\n while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {\n const attrs = new AttrList(result[1]);\n if (attrs.TYPE === type) {\n const media: MediaPlaylist = {\n attrs,\n id: id++,\n groupId: attrs['GROUP-ID'],\n instreamId: attrs['INSTREAM-ID'],\n name: attrs.NAME || attrs.LANGUAGE,\n type,\n default: (attrs.DEFAULT === 'YES'),\n autoselect: (attrs.AUTOSELECT === 'YES'),\n forced: (attrs.FORCED === 'YES'),\n lang: attrs.LANGUAGE\n };\n\n if (attrs.URI) {\n media.url = M3U8Parser.resolve(attrs.URI, baseurl);\n }\n\n if (audioGroups.length) {\n // If there are audio groups signalled in the manifest, let's look for a matching codec string for this track\n const groupCodec = M3U8Parser.findGroup(audioGroups, media.groupId as string);\n\n // If we don't find the track signalled, lets use the first audio groups codec we have\n // Acting as a best guess\n media.audioCodec = groupCodec ? groupCodec.codec : audioGroups[0].codec;\n }\n\n medias.push(media);\n }\n }\n return medias;\n }\n\n static parseLevelPlaylist (string: string, baseurl: string, id: number, type: PlaylistLevelType, levelUrlId: number) {\n let currentSN = 0;\n let totalduration = 0;\n let level = new Level(baseurl);\n let discontinuityCounter = 0;\n let prevFrag: Fragment | null = null;\n let frag: Fragment | null = new Fragment();\n let result: RegExpExecArray | RegExpMatchArray | null;\n let i: number;\n let levelkey: LevelKey | undefined;\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 if (levelkey) {\n frag.levelkey = levelkey;\n }\n frag.sn = sn;\n frag.level = id;\n frag.cc = discontinuityCounter;\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 const data = (' ' + result[4]).slice(1);\n if (prevFrag) {\n frag.setByteRange(data, prevFrag);\n } else {\n frag.setByteRange(data);\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 if (!result) {\n logger.warn('No matches on slow regex match for level playlist!');\n continue;\n }\n for (i = 1; i < result.length; i++) {\n if (typeof 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 discontinuityCounter++;\n frag.tagList.push(['DIS']);\n break;\n case 'DISCONTINUITY-SEQ':\n discontinuityCounter = parseInt(value1);\n break;\n case 'KEY': {\n // https://tools.ietf.org/html/rfc8216#section-4.3.2.4\n const decryptparams = value1;\n const keyAttrs = new AttrList(decryptparams);\n const decryptmethod = keyAttrs.enumeratedString('METHOD');\n const decrypturi = keyAttrs.URI;\n const decryptiv = keyAttrs.hexadecimalInteger('IV');\n // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of \"identity\".\n const decryptkeyformat = keyAttrs.KEYFORMAT || 'identity';\n\n if (decryptkeyformat === 'com.apple.streamingkeydelivery') {\n logger.warn('Keyformat com.apple.streamingkeydelivery is not supported');\n continue;\n }\n\n if (decryptmethod) {\n levelkey = new LevelKey(baseurl, decrypturi);\n if ((decrypturi) && (['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0)) {\n levelkey.method = decryptmethod;\n levelkey.key = null;\n // Initialization Vector (IV)\n levelkey.iv = decryptiv;\n }\n }\n break;\n }\n case 'START': {\n const startAttrs = new AttrList(value1);\n const startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');\n // TIME-OFFSET can be 0\n if (Number.isFinite(startTimeOffset)) {\n level.startTimeOffset = startTimeOffset;\n }\n break;\n }\n case 'MAP': {\n const mapAttrs = new AttrList(value1);\n frag.relurl = mapAttrs.URI;\n if (mapAttrs.BYTERANGE) {\n frag.setByteRange(mapAttrs.BYTERANGE);\n }\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 }\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 = discontinuityCounter;\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?.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","/**\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';\nimport { logger } from '../utils/logger';\nimport { Loader, PlaylistContextType, PlaylistLoaderContext, PlaylistLevelType, LoaderCallbacks, LoaderResponse, LoaderStats, LoaderConfiguration } from '../types/loader';\nimport MP4Demuxer from '../demux/mp4demuxer';\nimport M3U8Parser from './m3u8-parser';\nimport { AudioGroup } from '../types/media-playlist';\n\nconst { performance } = window;\n\n/**\n * @constructor\n */\nclass PlaylistLoader extends EventHandler {\n private loaders: Partial<Record<PlaylistContextType, Loader<PlaylistLoaderContext>>> = {};\n\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\n /**\n * @param {PlaylistContextType} type\n * @returns {boolean}\n */\n static canHaveQualityLevels (type: PlaylistContextType): boolean {\n return (type !== PlaylistContextType.AUDIO_TRACK &&\n type !== PlaylistContextType.SUBTITLE_TRACK);\n }\n\n /**\n * Map context.type to LevelType\n * @param {PlaylistLoaderContext} context\n * @returns {LevelType}\n */\n static mapContextToLevelType (context: PlaylistLoaderContext): PlaylistLevelType {\n const { type } = context;\n\n switch (type) {\n case PlaylistContextType.AUDIO_TRACK:\n return PlaylistLevelType.AUDIO;\n case PlaylistContextType.SUBTITLE_TRACK:\n return PlaylistLevelType.SUBTITLE;\n default:\n return PlaylistLevelType.MAIN;\n }\n }\n\n static getResponseUrl (response: LoaderResponse, context: PlaylistLoaderContext): string {\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 {PlaylistLoaderContext} context\n * @returns {Loader} or other compatible configured overload\n */\n createInternalLoader (context: PlaylistLoaderContext): Loader<PlaylistLoaderContext> {\n const config = this.hls.config;\n const PLoader = config.pLoader;\n const Loader = config.loader;\n // TODO(typescript-config): Verify once config is typed that InternalLoader always returns a Loader\n const InternalLoader = PLoader || Loader;\n\n const loader = new InternalLoader(config);\n\n // TODO - Do we really need to assign the instance or if the dep has been lost\n context.loader = loader;\n this.loaders[context.type] = loader;\n\n return loader;\n }\n\n getInternalLoader (context: PlaylistLoaderContext): Loader<PlaylistLoaderContext> | undefined {\n return this.loaders[context.type];\n }\n\n resetInternalLoader (contextType: PlaylistContextType) {\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 as PlaylistContextType);\n }\n }\n\n destroy () {\n this.destroyInternalLoaders();\n\n super.destroy();\n }\n\n onManifestLoading (data: { url: string; }) {\n this.load({\n url: data.url,\n type: PlaylistContextType.MANIFEST,\n level: 0,\n id: null,\n responseType: 'text'\n });\n }\n\n onLevelLoading (data: { url: string; level: number | null; id: number | null; }) {\n this.load({\n url: data.url,\n type: PlaylistContextType.LEVEL,\n level: data.level,\n id: data.id,\n responseType: 'text'\n });\n }\n\n onAudioTrackLoading (data: { url: string; id: number | null; }) {\n this.load({\n url: data.url,\n type: PlaylistContextType.AUDIO_TRACK,\n level: null,\n id: data.id,\n responseType: 'text'\n });\n }\n\n onSubtitleTrackLoading (data: { url: string; id: number | null; }) {\n this.load({\n url: data.url,\n type: PlaylistContextType.SUBTITLE_TRACK,\n level: null,\n id: data.id,\n responseType: 'text'\n });\n }\n\n load (context: PlaylistLoaderContext): boolean {\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 === context.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: number;\n let timeout: number;\n let retryDelay: number;\n let maxRetryDelay: number;\n\n // apply different configs for retries depending on\n // context (manifest, level, audio/subs playlist)\n switch (context.type) {\n case PlaylistContextType.MANIFEST:\n maxRetry = config.manifestLoadingMaxRetry;\n timeout = config.manifestLoadingTimeOut;\n retryDelay = config.manifestLoadingRetryDelay;\n maxRetryDelay = config.manifestLoadingMaxRetryTimeout;\n break;\n case PlaylistContextType.LEVEL:\n // Disable internal loader retry logic, since we are managing retries in Level Controller\n maxRetry = 0;\n maxRetryDelay = 0;\n retryDelay = 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 const loaderConfig: LoaderConfiguration = {\n timeout,\n maxRetry,\n retryDelay,\n maxRetryDelay\n };\n\n const loaderCallbacks: LoaderCallbacks<PlaylistLoaderContext> = {\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: ${context.url}`);\n loader.load(context, loaderConfig, loaderCallbacks);\n\n return true;\n }\n\n loadsuccess (response: LoaderResponse, stats: LoaderStats, context: PlaylistLoaderContext, networkDetails: unknown = 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 if (typeof response.data !== 'string') {\n throw new Error('expected responseType of \"text\" for PlaylistLoader');\n }\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: LoaderResponse, context: PlaylistLoaderContext, networkDetails = null) {\n this._handleNetworkError(context, networkDetails, false, response);\n }\n\n loadtimeout (stats: LoaderStats, context: PlaylistLoaderContext, networkDetails = null) {\n this._handleNetworkError(context, networkDetails, true);\n }\n\n // TODO(typescript-config): networkDetails can currently be a XHR or Fetch impl,\n // but with custom loaders it could be generic investigate this further when config is typed\n _handleMasterPlaylist (response: LoaderResponse, stats: LoaderStats, context: PlaylistLoaderContext, networkDetails: unknown) {\n const hls = this.hls;\n const string = response.data as string;\n\n const url = PlaylistLoader.getResponseUrl(response, context);\n const { levels, sessionData } = 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 const audioGroups: Array<AudioGroup> = levels.map(level => ({\n id: level.attrs.AUDIO,\n codec: level.audioCodec\n }));\n\n const audioTracks = M3U8Parser.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);\n const subtitles = M3U8Parser.parseMasterPlaylistMedia(string, url, 'SUBTITLES');\n const captions = M3U8Parser.parseMasterPlaylistMedia(string, url, 'CLOSED-CAPTIONS');\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 default: false,\n autoselect: false,\n forced: false,\n id: -1,\n attrs: {},\n url: ''\n });\n }\n }\n\n hls.trigger(Event.MANIFEST_LOADED, {\n levels,\n audioTracks,\n subtitles,\n captions,\n url,\n stats,\n networkDetails,\n sessionData\n });\n }\n\n _handleTrackOrLevelPlaylist (response: LoaderResponse, stats: LoaderStats, context: PlaylistLoaderContext, networkDetails: unknown) {\n const hls = this.hls;\n\n const { id, level, type } = context;\n\n const url = PlaylistLoader.getResponseUrl(response, context);\n\n // if the values are null, they will result in the else conditional\n const levelUrlId = Number.isFinite(id as number) ? id as number : 0;\n const levelId = Number.isFinite(level as number) ? level as number : levelUrlId;\n\n const levelType = PlaylistLoader.mapContextToLevelType(context);\n const levelDetails = M3U8Parser.parseLevelPlaylist(response.data as string, url, levelId, levelType, levelUrlId);\n\n // set stats on level structure\n // TODO(jstackhouse): why? mixing concerns, is it just treated as value bag?\n (levelDetails as any).tload = stats.tload;\n\n if (!levelDetails.fragments.length) {\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.LEVEL_EMPTY_ERROR,\n fatal: false,\n url: url,\n reason: 'no fragments found in level',\n level: typeof context.level === 'number' ? context.level : undefined\n });\n return;\n }\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 === PlaylistContextType.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 sessionData: null\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({\n url: 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: LoaderResponse, context: PlaylistLoaderContext) {\n if (typeof response.data === 'string') {\n throw new Error('sidx request must be made with responseType of array buffer');\n }\n\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 if (!levelDetails) {\n return;\n }\n const frag = levelDetails.fragments[index];\n if (frag.byteRange.length === 0) {\n frag.setByteRange(String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start));\n }\n });\n\n if (levelDetails) {\n levelDetails.initSegment.setByteRange(String(sidxInfo.moovEndOffset) + '@0');\n }\n }\n\n _handleManifestParsingError (response: LoaderResponse, context: PlaylistLoaderContext, reason: string, networkDetails: unknown) {\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: PlaylistLoaderContext, networkDetails: unknown, timeout: boolean = false, response: LoaderResponse | null = 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 PlaylistContextType.MANIFEST:\n details = (timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR);\n fatal = true;\n break;\n case PlaylistContextType.LEVEL:\n details = (timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR);\n fatal = false;\n break;\n case PlaylistContextType.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 // TODO(typescript-events): when error events are handled, type this\n let errorData: any = {\n type: ErrorTypes.NETWORK_ERROR,\n details,\n fatal,\n url: context.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: LoaderResponse, stats: LoaderStats, context: PlaylistLoaderContext, networkDetails: unknown) {\n const { type, level, id, levelDetails } = context;\n\n if (!levelDetails || !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 PlaylistContextType.AUDIO_TRACK:\n this.hls.trigger(Event.AUDIO_TRACK_LOADED, {\n details: levelDetails,\n id,\n stats,\n networkDetails\n });\n break;\n case PlaylistContextType.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 * 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';\nimport Hls from '../hls';\nimport Fragment from './fragment';\nimport { LoaderStats, LoaderResponse, LoaderContext, LoaderConfiguration, LoaderCallbacks } from '../types/loader';\n\ninterface OnKeyLoadingPayload {\n frag: Fragment\n}\n\ninterface KeyLoaderContext extends LoaderContext {\n frag: Fragment\n}\n\nclass KeyLoader extends EventHandler {\n public loaders = {};\n public decryptkey: Uint8Array | null = null;\n public decrypturl: string | null = null;\n\n constructor (hls: Hls) {\n super(hls, Event.KEY_LOADING);\n }\n\n destroy (): void {\n for (const loaderName in this.loaders) {\n let loader = this.loaders[loaderName];\n if (loader) {\n loader.destroy();\n }\n }\n this.loaders = {};\n\n super.destroy();\n }\n\n onKeyLoading (data: OnKeyLoadingPayload) {\n const { frag } = data;\n const type = frag.type;\n const loader = this.loaders[type];\n if (!frag.decryptdata) {\n logger.warn('Missing decryption data on fragment in onKeyLoading');\n return;\n }\n\n // Load the key if the uri is different from previous one, or if the decrypt key has not yet been retrieved\n const uri = frag.decryptdata.uri;\n if (uri !== this.decrypturl || this.decryptkey === null) {\n let config = this.hls.config;\n if (loader) {\n logger.warn(`abort previous key loader for type:${type}`);\n loader.abort();\n }\n if (!uri) {\n logger.warn('key uri is falsy');\n return;\n }\n\n frag.loader = this.loaders[type] = new config.loader(config);\n this.decrypturl = uri;\n this.decryptkey = null;\n\n const loaderContext: KeyLoaderContext = {\n url: uri,\n frag: frag,\n responseType: 'arraybuffer'\n };\n\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 const loaderConfig: LoaderConfiguration = {\n timeout: config.fragLoadingTimeOut,\n maxRetry: 0,\n retryDelay: config.fragLoadingRetryDelay,\n maxRetryDelay: config.fragLoadingMaxRetryTimeout\n };\n\n const loaderCallbacks: LoaderCallbacks<KeyLoaderContext> = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this)\n };\n\n frag.loader.load(loaderContext, loaderConfig, loaderCallbacks);\n } else if (this.decryptkey) {\n // Return the key if it's already been loaded\n frag.decryptdata.key = this.decryptkey;\n this.hls.trigger(Event.KEY_LOADED, { frag: frag });\n }\n }\n\n loadsuccess (response: LoaderResponse, stats: LoaderStats, context: KeyLoaderContext) {\n let frag = context.frag;\n if (!frag.decryptdata) {\n logger.error('after key load, decryptdata unset');\n return;\n }\n this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data as ArrayBuffer);\n\n // detach fragment loader on load success\n frag.loader = undefined;\n delete this.loaders[frag.type];\n this.hls.trigger(Event.KEY_LOADED, { frag: frag });\n }\n\n loaderror (response: LoaderResponse, context: KeyLoaderContext) {\n let frag = context.frag;\n let loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n\n delete this.loaders[frag.type];\n this.hls.trigger(Event.ERROR, { type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag, response });\n }\n\n loadtimeout (stats: LoaderStats, context: KeyLoaderContext) {\n let frag = context.frag;\n let loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n\n delete this.loaders[frag.type];\n this.hls.trigger(Event.ERROR, { type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.KEY_LOAD_TIMEOUT, fatal: false, frag });\n }\n}\n\nexport default KeyLoader;\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 // Check if any flagged fragments have been unloaded\n Object.keys(this.fragments).forEach(key => {\n const fragmentEntity = this.fragments[key];\n if (!fragmentEntity || !fragmentEntity.buffered) {\n return;\n }\n const esData = fragmentEntity.range[elementaryStream];\n if (!esData) {\n return;\n }\n const fragmentTimes = esData.time;\n for (let i = 0; i < fragmentTimes.length; i++) {\n const time = fragmentTimes[i];\n if (!this.isTimeBuffered(time.startPTS, time.endPTS, timeRange)) {\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 * 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","type BinarySearchComparison < T > = (candidate: T) => -1 | 0 | 1;\n\nconst BinarySearch = {\n\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<T>} list The array to search.\n * @param {BinarySearchComparison<T>} comparisonFn\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 {T | null} The object if it is found or null otherwise.\n */\n search: function<T> (list: T[], comparisonFn: BinarySearchComparison<T>): T | null {\n let minIndex: number = 0;\n let maxIndex: number = list.length - 1;\n let currentIndex: number | null = null;\n let currentElement: T | null = null;\n\n while (minIndex <= maxIndex) {\n currentIndex = (minIndex + maxIndex) / 2 | 0;\n currentElement = list[currentIndex];\n\n let comparisonResult = comparisonFn(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 * @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\ntype BufferTimeRange = {\n start: number\n end: number\n};\n\ntype Bufferable = {\n buffered: TimeRanges\n};\n\nexport class BufferHelper {\n /**\n * Return true if `media`'s buffered include `position`\n * @param {Bufferable} media\n * @param {number} position\n * @returns {boolean}\n */\n static isBuffered (media: Bufferable, position: number): boolean {\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 (\n media: Bufferable,\n pos: number,\n maxHoleDuration: number\n ): {\n len: number,\n start: number,\n end: number,\n nextStart?: number,\n } {\n try {\n if (media) {\n let vbuffered = media.buffered;\n let buffered: BufferTimeRange[] = [];\n let i: number;\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 (\n buffered: BufferTimeRange[],\n pos: number,\n maxHoleDuration: number\n ): {\n len: number,\n start: number,\n end: number,\n nextStart?: number,\n } {\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\n let buffered2: BufferTimeRange[] = [];\n if (maxHoleDuration) {\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 (let 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 } else {\n buffered2 = buffered;\n }\n\n let bufferLen = 0;\n\n // bufferStartNext can possibly be undefined based on the conditional logic below\n let bufferStartNext: number | undefined;\n\n // bufferStart and bufferEnd are buffer boundaries around current video position\n let bufferStart: number = pos;\n let bufferEnd: number = pos;\n for (let i = 0; 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","/**\n * MediaSource helper\n */\n\nexport function getMediaSource (): typeof MediaSource | undefined {\n return (window as any).MediaSource || (window as any).WebKitMediaSource;\n}\n","import { EventEmitter } from 'eventemitter3';\n\n/**\n * Simple adapter sub-class of Nodejs-like EventEmitter.\n */\nexport class Observer extends 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 trigger (event: string, ...data: Array<any>): void {\n this.emit(event, event, ...data);\n }\n}\n","import { EventEmitter } from 'eventemitter3';\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() || { isTypeSupported: () => false };\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 * @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 const contiguous = fragFrom.cc === fragTo.cc;\n fragTo.start = fragFrom.start + ((contiguous && fragFrom.minEndPTS) ? fragFrom.minEndPTS - 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 let minEndPTS = endPTS;\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 minEndPTS = Math.min(endPTS, frag.endPTS);\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.minEndPTS = minEndPTS;\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","/**\n * TimeRanges to string helper\n */\n\nconst TimeRanges = {\n toString: function (r: TimeRanges) {\n let log = '';\n let 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';\nimport Fragment from '../loader/fragment';\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: Array<Fragment>, PDTValue: number | null, maxFragLookUpTolerance: number): Fragment | null {\n if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !Number.isFinite(PDTValue)) {\n return null;\n }\n\n // if less than start\n const startPDT = fragments[0].programDateTime;\n if (PDTValue < (startPDT || 0)) {\n return null;\n }\n\n const endPDT = fragments[fragments.length - 1].endProgramDateTime;\n if (PDTValue >= (endPDT || 0)) {\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: Fragment, fragments: Array<Fragment>, bufferEnd: number = 0, maxFragLookUpTolerance: number = 0): Fragment | null {\n let fragNext: Fragment | null = null;\n if (fragPrevious) {\n fragNext = fragments[fragPrevious.sn as number - (fragments[0].sn as number) + 1];\n } else if (bufferEnd === 0 && fragments[0].start === 0) {\n fragNext = fragments[0];\n }\n // Prefer the next fragment if it's within tolerance\n if (fragNext && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0) {\n return fragNext;\n }\n // We might be seeking past the tolerance so find the best match\n const foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));\n if (foundFragment) {\n return foundFragment;\n }\n // If no match was found return the next fragment after fragPrevious, or null\n return fragNext;\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: Fragment) {\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: number, maxFragLookUpTolerance: number, candidate: Fragment): boolean {\n let candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000;\n\n // endProgramDateTime can be null, default to zero\n const endProgramDateTime = candidate.endProgramDateTime || 0;\n return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;\n}\n","import { BufferHelper } from '../utils/buffer-helper';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport Event from '../events';\nimport { logger } from '../utils/logger';\n\nexport const STALL_MINIMUM_DURATION_MS = 250;\nexport const MAX_START_GAP_JUMP = 2.0;\nexport const SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;\nexport const SKIP_BUFFER_RANGE_START = 0.05;\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.nudgeRetry = 0;\n this.stallReported = false;\n this.stalled = null;\n this.moved = false;\n this.seeking = 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 *\n * @param {number} lastCurrentTime Previously read playhead position\n */\n poll (lastCurrentTime) {\n const { config, media, stalled } = this;\n const { currentTime, seeking } = media;\n const seeked = this.seeking && !seeking;\n const beginSeek = !this.seeking && seeking;\n\n this.seeking = seeking;\n\n // The playhead is moving, no-op\n if (currentTime !== lastCurrentTime) {\n this.moved = true;\n if (stalled !== null) {\n // The playhead is now moving, but was previously stalled\n if (this.stallReported) {\n const stalledDuration = self.performance.now() - stalled;\n logger.warn(`playback not stuck anymore @${currentTime}, after ${Math.round(stalledDuration)}ms`);\n this.stallReported = false;\n }\n this.stalled = null;\n this.nudgeRetry = 0;\n }\n return;\n }\n\n // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek\n if (beginSeek || seeked) {\n this.stalled = null;\n }\n\n // The playhead should not be moving\n if (media.paused || media.ended || media.playbackRate === 0 || !media.buffered.length) {\n return;\n }\n\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);\n const isBuffered = bufferInfo.len > 0;\n const nextStart = bufferInfo.nextStart || 0;\n\n // There is no playable buffer (waiting for buffer append)\n if (!isBuffered && !nextStart) {\n return;\n }\n\n if (seeking) {\n // Waiting for seeking in a buffered range to complete\n const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;\n // Next buffered range is too far ahead to jump to while still seeking\n const noBufferGap = !nextStart ||\n (nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime));\n if (hasEnoughBuffer || noBufferGap) {\n return;\n }\n // Reset moved state when seeking to a point in or before a gap\n this.moved = false;\n }\n\n // Skip start gaps if we haven't played, but the last poll detected the start of a stall\n // The addition poll gives the browser a chance to jump the gap for us\n if (!this.moved && this.stalled) {\n // Jump start gaps within jump threshold\n const startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;\n\n // When joining a live stream with audio tracks, account for live playlist window sliding by allowing\n // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment\n // that begins over 1 target duration after the video start position.\n const level = this.hls.levels ? this.hls.levels[this.hls.currentLevel] : null;\n const isLive = level?.details?.live;\n const maxStartGapJump = isLive ? level.details.targetduration * 2 : MAX_START_GAP_JUMP;\n if (startJump > 0 && startJump <= maxStartGapJump) {\n this._trySkipBufferHole(null);\n return;\n }\n }\n\n // Start tracking stall time\n const tnow = self.performance.now();\n if (stalled === null) {\n this.stalled = tnow;\n return;\n }\n\n const stalledDuration = tnow - stalled;\n if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {\n // Report stalling after trying to fix\n this._reportStall(bufferInfo.len);\n }\n\n const bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);\n this._tryFixBufferStall(bufferedWithHoles, 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 stalledDurationMs - The amount of time Hls.js has been stalling for.\n * @private\n */\n _tryFixBufferStall (bufferInfo, stalledDurationMs) {\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 const targetTime = this._trySkipBufferHole(partial);\n // we return here in this case, meaning\n // the branch below only executes when we don't handle a partial fragment\n if (targetTime) {\n return;\n }\n }\n\n // if we haven't had to skip over a buffer hole of a partial fragment\n // we may just have to \"nudge\" the playlist as the browser decoding/rendering engine\n // needs to cross some sort of threshold covering all source-buffers content\n // to start playing properly.\n if (bufferInfo.len > config.maxBufferHole &&\n stalledDurationMs > config.highBufferWatchdogPeriod * 1000) {\n logger.warn('Trying to nudge playhead over buffer-hole');\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 (buffer=${bufferLen})`);\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 { config, 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 const startTime = media.buffered.start(i);\n if (currentTime + config.maxBufferHole >= lastEndTime && currentTime < startTime) {\n const targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, media.currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);\n logger.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}`);\n this.moved = true;\n this.stalled = null;\n media.currentTime = targetTime;\n if (partial) {\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 ${targetTime}`,\n frag: partial\n });\n }\n return targetTime;\n }\n lastEndTime = media.buffered.end(i);\n }\n return 0;\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 // playback stalled in buffered area ... let's nudge currentTime to try to overcome this\n logger.warn(`Nudging 'currentTime' from ${currentTime} to ${targetTime}`);\n media.currentTime = targetTime;\n\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(`Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`);\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: true\n });\n }\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 logger.log(`media seeking to ${Number.isFinite(currentTime) ? currentTime.toFixed(3) : currentTime}`);\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 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 * 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 { ElementaryStreamTypes } from '../loader/fragment';\nimport { PlaylistLevelType } from '../types/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, { MAX_START_GAP_JUMP } 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.LEVELS_UPDATED,\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 this.altAudio = false;\n this.audioOnly = false;\n this.bitrateTest = false;\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 if (hls.config.testBandwidth) {\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 } else {\n startLevel = hls.nextAutoLevel;\n }\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 details = this.levels[this.level]?.details;\n // check if playlist is already loaded (must be current level for live)\n if (details && (!details.live || this.levelLastLoaded === this.level)) {\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 the \"main\" level is audio-only but we are loading an alternate track in the same group, do not load anything\n if (this.altAudio && this.audioOnly) {\n // Clear audio demuxer state so when switching back to main audio we're not still appending where we left off\n this.demuxer.frag = null;\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.\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 maxBufferHole = pos < config.maxBufferHole ? Math.max(MAX_START_GAP_JUMP, config.maxBufferHole) : config.maxBufferHole;\n const bufferInfo = BufferHelper.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, maxBufferHole);\n const 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 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);\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 this._loadKey(frag, levelDetails);\n } else {\n this._loadFragment(frag, levelDetails, pos, bufferEnd);\n }\n }\n }\n\n _ensureFragmentAtLivePoint (levelDetails, bufferEnd, start, end, fragPrevious, fragments) {\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 = Infinity;\n\n if (config.liveMaxLatencyDuration !== undefined) {\n maxLatency = config.liveMaxLatencyDuration;\n } else if (Number.isFinite(config.liveMaxLatencyDurationCount)) {\n maxLatency = config.liveMaxLatencyDurationCount * levelDetails.targetduration;\n }\n\n if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {\n let liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);\n bufferEnd = liveSyncPosition;\n if (media && !media.paused && media.readyState && media.duration > liveSyncPosition && liveSyncPosition > media.currentTime) {\n logger.warn(`buffer end: ${bufferEnd.toFixed(3)} is located too far from the end of live sliding playlist, reset currentTime to : ${liveSyncPosition.toFixed(3)}`);\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 }\n\n return frag;\n }\n\n _findFragment (start, fragPreviousLoad, fragmentIndexRange, fragments, bufferEnd, end, levelDetails) {\n const config = this.hls.config;\n let fragNextLoad;\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 fragNextLoad = findFragmentByPTS(fragPreviousLoad, fragments, bufferEnd, lookupTolerance);\n } else {\n // reach end of playlist\n fragNextLoad = fragments[fragmentIndexRange - 1];\n }\n\n if (fragNextLoad) {\n const curSNIdx = fragNextLoad.sn - levelDetails.startSN;\n const sameLevel = fragPreviousLoad && fragNextLoad.level === fragPreviousLoad.level;\n const prevSnFrag = fragments[curSNIdx - 1];\n const nextSnFrag = fragments[curSNIdx + 1];\n\n // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);\n if (fragPreviousLoad && fragNextLoad.sn === fragPreviousLoad.sn) {\n if (sameLevel && !fragNextLoad.backtracked) {\n if (fragNextLoad.sn < levelDetails.endSN) {\n let deltaPTS = fragPreviousLoad.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 && fragPreviousLoad.dropped && curSNIdx) {\n fragNextLoad = prevSnFrag;\n logger.warn('Previous fragment was dropped with large PTS gap between audio and video. Maybe fragment is not starting with a keyframe? Loading previous one to try to overcome this');\n } else {\n fragNextLoad = nextSnFrag;\n if (this.fragmentTracker.getState(fragNextLoad) !== FragmentState.OK) {\n logger.log(`Re-loading fragment with SN: ${fragNextLoad.sn}`);\n }\n }\n } else {\n fragNextLoad = null;\n }\n } else if (fragNextLoad.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 (nextSnFrag && nextSnFrag.backtracked) {\n logger.warn(`Already backtracked from fragment ${nextSnFrag.sn}, will not backtrack to fragment ${fragNextLoad.sn}. Loading fragment ${nextSnFrag.sn}`);\n fragNextLoad = nextSnFrag;\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 fragNextLoad.dropped = 0;\n if (prevSnFrag) {\n fragNextLoad = prevSnFrag;\n fragNextLoad.backtracked = true;\n } else if (curSNIdx) {\n // can't backtrack on very first fragment\n fragNextLoad = null;\n }\n }\n }\n }\n }\n\n return fragNextLoad;\n }\n\n _loadKey (frag, levelDetails) {\n logger.log(`Loading key for ${frag.sn} of [${levelDetails.startSN}-${levelDetails.endSN}], level ${this.level}`);\n this.state = State.KEY_LOADING;\n this.hls.trigger(Event.KEY_LOADING, { frag });\n }\n\n _loadFragment (frag, levelDetails, pos, bufferEnd) {\n // Check if fragment is not loaded\n let fragState = this.fragmentTracker.getState(frag);\n\n this.fragCurrent = frag;\n if (frag.sn !== 'initSegment') {\n this.startFragRequested = true;\n }\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 logger.log(`Loading ${frag.sn} of [${levelDetails.startSN}-${levelDetails.endSN}], level ${this.level}, ${\n this.loadedmetadata ? 'currentTime' : 'nextLoadPosition'\n }: ${parseFloat(pos.toFixed(3))}, bufferEnd: ${parseFloat(bufferEnd.toFixed(3))}`);\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-controller: ${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, PlaylistLevelType.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 if (!previouslyPaused) {\n media.pause();\n }\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 (media.currentTime > 0 && 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;\n const 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 const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);\n if (bufferedFrag) {\n // we can flush buffer range following this one without stalling playback\n const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);\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 const startPts = Math.max(bufferedFrag.endPTS, nextBufferedFrag.maxStartPTS + Math.min(this.config.maxFragLookUpTolerance, nextBufferedFrag.duration));\n this.flushMainBuffer(startPts, 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\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\n this.fragmentTracker.removeAllFragments();\n this.media = this.mediaBuffer = null;\n this.loadedmetadata = false;\n this.stopLoad();\n }\n\n onMediaSeeked () {\n const media = this.media;\n const 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.altAudio = data.altAudio;\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 back 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 this.audioOnly = tracks.audio && !tracks.video;\n\n // if audio track is expected to come from audio stream controller, discard any coming from main\n if (this.altAudio && !this.audioOnly) {\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(ElementaryStreamTypes.AUDIO);\n }\n\n if (data.hasVideo === true) {\n frag.addElementaryStream(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 if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\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 const fromAltAudio = this.altAudio;\n const altAudio = !!data.url;\n const 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 // If switching from alt to main audio, flush all audio and trigger track switched\n if (fromAltAudio) {\n hls.trigger(Event.BUFFER_FLUSHING, {\n startOffset: 0,\n endOffset: Number.POSITIVE_INFINITY,\n type: 'audio'\n });\n }\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, {\n id: trackId\n });\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 // Do not tick when _seekToStartPos needs to be called as seeking to the start can fail on live streams at this point\n if (this.loadedmetadata || this.startPosition <= 0) {\n this.tick();\n }\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 buffered anything yet (readyState 0)\n return;\n }\n\n // Check combined buffer\n const buffered = media.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 const elementaryStreamType = this.audioOnly ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;\n this.fragmentTracker.detectEvictedFragments(elementaryStreamType, media.buffered);\n }\n // reset reference to frag\n this.fragPrevious = null;\n // move to IDLE once flush complete. this should trigger new fragment loading\n this.state = State.IDLE;\n }\n\n onLevelsUpdated (data) {\n this.levels = data.levels;\n }\n\n swapAudioCodec () {\n this.audioCodecSwap = !this.audioCodecSwap;\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 let startPosition = this.startPosition;\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 if (currentTime !== startPosition && startPosition >= 0) {\n if (media.seeking) {\n logger.log(`could not seek to ${startPosition}, already seeking at ${currentTime}`);\n return;\n }\n const bufferStart = media.buffered.length ? media.buffered.start(0) : 0;\n const delta = bufferStart - startPosition;\n if (delta > 0 && delta < this.config.maxBufferHole) {\n logger.log(`adjusting start position by ${delta} to match buffer start`);\n startPosition += delta;\n this.startPosition = startPosition;\n }\n logger.log(`seek to target start position ${startPosition} from current time ${currentTime}. ready state ${media.readyState}`);\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","/*\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\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 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 // and this is not an audio-only stream where levels contain audio-only\n const audioOnly = audioCodecFound && !videoCodecFound;\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: !audioOnly && 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 removeLevel (levelIndex, urlId) {\n const levels = this.levels.filter((level, index) => {\n if (index !== levelIndex) {\n return true;\n }\n\n if (level.url.length > 1 && urlId !== undefined) {\n level.url = level.url.filter((url, id) => id !== urlId);\n level.urlId = 0;\n return true;\n }\n return false;\n }).map((level, index) => {\n const { details } = level;\n if (details && details.fragments) {\n details.fragments.forEach((fragment) => {\n fragment.level = index;\n });\n }\n return level;\n });\n\n this._levels = levels;\n\n this.hls.trigger(Event.LEVELS_UPDATED, { levels });\n }\n}\n","import EventHandler from './event-handler';\nimport Hls from './hls';\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 private readonly _boundTick: () => void;\n private _tickTimer: number | null = null;\n private _tickInterval: number | null = null;\n private _tickCallCount = 0;\n\n constructor (hls: Hls, ...events: string[]) {\n super(hls, ...events);\n this._boundTick = this.tick.bind(this);\n }\n\n /**\n * @override\n */\n protected onHandlerDestroying () {\n // clear all timers before unregistering from event bus\n this.clearNextTick();\n this.clearInterval();\n }\n\n /**\n * @returns {boolean}\n */\n public hasInterval (): boolean {\n return !!this._tickInterval;\n }\n\n /**\n * @returns {boolean}\n */\n public hasNextTick (): boolean {\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 public setInterval (millis: number): boolean {\n if (!this._tickInterval) {\n this._tickInterval = self.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 public clearInterval (): boolean {\n if (this._tickInterval) {\n self.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 public clearNextTick (): boolean {\n if (this._tickTimer) {\n self.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 public tick (): void {\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 = self.setTimeout(this._boundTick, 0);\n }\n this._tickCallCount = 0;\n }\n }\n\n /**\n * For subclass to implement task logic\n * @abstract\n */\n protected doTick (): void {}\n}\n","\nexport function sendAddTrackEvent (track: TextTrack, videoEl: HTMLMediaElement) {\n let event: Event;\n try {\n event = new Event('addtrack');\n } catch (err) {\n // for IE11\n event = document.createEvent('Event');\n event.initEvent('addtrack', false, false);\n }\n (event as any).track = track;\n videoEl.dispatchEvent(event);\n}\n\nexport function clearCurrentCues (track: TextTrack) {\n if (track?.cues) {\n while (track.cues.length > 0) {\n track.removeCue(track.cues[0]);\n }\n }\n}\n\n/**\n * Given a list of Cues, finds the closest cue matching the given time.\n * Modified verison of binary search O(log(n)).\n *\n * @export\n * @param {(TextTrackCueList | TextTrackCue[])} cues - List of cues.\n * @param {number} time - Target time, to find closest cue to.\n * @returns {TextTrackCue}\n */\nexport function getClosestCue (cues: TextTrackCueList | TextTrackCue[], time: number): TextTrackCue {\n // If the offset is less than the first element, the first element is the closest.\n if (time < cues[0].endTime) {\n return cues[0];\n }\n // If the offset is greater than the last cue, the last is the closest.\n if (time > cues[cues.length - 1].endTime) {\n return cues[cues.length - 1];\n }\n\n let left = 0;\n let right = cues.length - 1;\n\n while (left <= right) {\n const mid = Math.floor((right + left) / 2);\n\n if (time < cues[mid].endTime) {\n right = mid - 1;\n } else if (time > cues[mid].endTime) {\n left = mid + 1;\n } else {\n // If it's not lower or higher, it must be equal.\n return cues[mid];\n }\n }\n // At this point, left and right have swapped.\n // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.\n return (cues[left].endTime - time) < (time - cues[right].endTime) ? cues[left] : cues[right];\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, getClosestCue } from '../utils/texttrack-utils';\n\nconst MIN_CUE_DURATION = 0.25;\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 Event.LIVE_BACK_BUFFER_REACHED\n );\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 // Ensure the pts is positive - sometimes it's reported as a small negative number\n let startTime = Math.max(samples[i].pts, 0);\n let endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.endPTS;\n if (!endTime) {\n endTime = fragment.start + fragment.duration;\n }\n\n const timeDiff = endTime - startTime;\n if (timeDiff <= 0) {\n endTime = startTime + MIN_CUE_DURATION;\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 onLiveBackBufferReached ({ bufferEnd }) {\n const { id3Track } = this;\n if (!id3Track || !id3Track.cues || !id3Track.cues.length) {\n return;\n }\n const foundCue = getClosestCue(id3Track.cues, bufferEnd);\n if (!foundCue) {\n return;\n }\n while (id3Track.cues[0] !== foundCue) {\n id3Track.removeCue(id3Track.cues[0]);\n }\n }\n}\n\nexport default ID3TrackController;\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 private alpha_: number;\n private estimate_: number;\n private totalWeight_: number;\n\n // About half of the estimated value will be from the last |halfLife| samples by weight.\n constructor (halfLife: number) {\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: number, value: number) {\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 (): number {\n return this.totalWeight_;\n }\n\n getEstimate (): number {\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 * 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 hls: any;\n\n private defaultEstimate_: number;\n private minWeight_: number;\n private minDelayMs_: number;\n private slow_: EWMA;\n private fast_: EWMA;\n\n // TODO(typescript-hls)\n constructor (hls: any, slow: number, fast: number, defaultEstimate: number) {\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: number, numBytes: number) {\n durationMs = Math.max(durationMs, this.minDelayMs_);\n let numBits = 8 * numBytes,\n // weight is duration in seconds\n durationS = durationMs / 1000,\n // value is bandwidth in bits/s\n bandwidthInBps = numBits / durationS;\n this.fast_.sample(durationS, bandwidthInBps);\n this.slow_.sample(durationS, bandwidthInBps);\n }\n\n canEstimate (): boolean {\n let fast = this.fast_;\n return (fast && fast.getTotalWeight() >= this.minWeight_);\n }\n\n getEstimate (): number {\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 * 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;\n let 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\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 const requestDelay = performance.now() - stats.trequest;\n const playbackRate = Math.abs(video.playbackRate);\n\n // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate\n if (requestDelay > (500 * frag.duration / playbackRate)) {\n const levels = hls.levels;\n const 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\n // compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size\n const level = levels[frag.level];\n if (!level) {\n return;\n }\n const levelBitrate = level.realBitrate ? Math.max(level.realBitrate, level.bitrate) : level.bitrate;\n const expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levelBitrate / 8));\n const pos = video.currentTime;\n const fragLoadedDelay = (expectedLen - stats.loaded) / loadRate;\n const bufferStarvationDelay = (BufferHelper.bufferInfo(video, pos, hls.config.maxBufferHole).end - pos) / playbackRate;\n\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 const minAutoLevel = hls.minAutoLevel;\n let fragLevelNextLoadedDelay;\n let 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 const levelNextBitrate = levels[nextLoadLevel].realBitrate\n ? Math.max(levels[nextLoadLevel].realBitrate, levels[nextLoadLevel].bitrate)\n : levels[nextLoadLevel].bitrate;\n\n const fragLevelNextLoadedDelay = frag.duration * levelNextBitrate / (8 * 0.8 * loadRate);\n\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;\n const { maxAutoLevel, levels, config, minAutoLevel } = hls;\n const video = hls.media;\n const currentLevel = this.lastLoadedFragLevel;\n const currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0;\n const pos = (video ? video.currentTime : 0);\n\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 const playbackRate = ((video && (video.playbackRate !== 0)) ? Math.abs(video.playbackRate) : 1.0);\n const avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate;\n // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.\n const 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 let bwFactor = config.abrBandWidthFactor;\n let bwUpFactor = config.abrBandWidthUpFactor;\n\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 const levelDetails = levelInfo.details;\n const avgDuration = levelDetails ? levelDetails.totalduration / levelDetails.fragments.length : currentFragDuration;\n const live = levelDetails ? levelDetails.live : false;\n\n let 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 const 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 * Buffer Controller\n */\n\nimport Events from '../events';\nimport EventHandler from '../event-handler';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { getMediaSource } from '../utils/mediasource-helper';\n\nimport { TrackSet } from '../types/track';\nimport { Segment } from '../types/segment';\nimport { BufferControllerConfig } from '../config';\n\n// Add extension properties to SourceBuffers from the DOM API.\ntype ExtendedSourceBuffer = SourceBuffer & {\n ended?: boolean\n};\n\ntype SourceBufferName = 'video' | 'audio';\ntype SourceBuffers = Partial<Record<SourceBufferName, ExtendedSourceBuffer>>;\n\ninterface SourceBufferFlushRange {\n start: number;\n end: number;\n type: SourceBufferName\n}\n\nconst MediaSource = getMediaSource();\n\nclass BufferController extends EventHandler {\n // the value that we have set mediasource.duration to\n // (the actual duration may be tweaked slighly by the browser)\n private _msDuration: number | null = null;\n // the value that we want to set mediaSource.duration to\n private _levelDuration: number | null = null;\n // the target duration of the current media playlist\n private _levelTargetDuration: number = 10;\n // current stream state: true - for live broadcast, false - for VoD content\n private _live: boolean | null = null;\n // cache the self generated object url to detect hijack of video tag\n private _objectUrl: string | null = null;\n\n // signals that the sourceBuffers need to be flushed\n private _needsFlush: boolean = false;\n\n // signals that mediaSource should have endOfStream called\n private _needsEos: boolean = false;\n\n private config: BufferControllerConfig;\n\n // this is optional because this property is removed from the class sometimes\n public audioTimestampOffset?: number;\n\n // The number of BUFFER_CODEC events received before any sourceBuffers are created\n public bufferCodecEventsExpected: number = 0;\n\n // The total number of BUFFER_CODEC events received\n private _bufferCodecEventsTotal: number = 0;\n\n // A reference to the attached media element\n public media: HTMLMediaElement | null = null;\n\n // A reference to the active media source\n public mediaSource: MediaSource | null = null;\n\n // List of pending segments to be appended to source buffer\n public segments: Segment[] = [];\n\n public parent?: string;\n\n // A guard to see if we are currently appending to the source buffer\n public appending: boolean = false;\n\n // counters\n public appended: number = 0;\n public appendError: number = 0;\n public flushBufferCounter: number = 0;\n\n public tracks: TrackSet = {};\n public pendingTracks: TrackSet = {};\n public sourceBuffer: SourceBuffers = {};\n public flushRange: SourceBufferFlushRange[] = [];\n\n constructor (hls: any) {\n super(hls,\n Events.MEDIA_ATTACHING,\n Events.MEDIA_DETACHING,\n Events.MANIFEST_PARSED,\n Events.BUFFER_RESET,\n Events.BUFFER_APPENDING,\n Events.BUFFER_CODECS,\n Events.BUFFER_EOS,\n Events.BUFFER_FLUSHING,\n Events.LEVEL_PTS_UPDATED,\n Events.LEVEL_UPDATED);\n\n this.config = hls.config;\n }\n\n destroy () {\n EventHandler.prototype.destroy.call(this);\n }\n\n onLevelPtsUpdated (data: { details, type: SourceBufferName, start: number }) {\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 if (!audioBuffer) {\n throw Error('Level PTS Updated and source buffer for audio uninitalized');\n }\n\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 if (this.config.liveDurationInfinity) {\n this.updateSeekableRange(data.details);\n }\n }\n\n onManifestParsed (data: { altAudio: boolean, audio: boolean, video: boolean }) {\n // in case of alt audio (where all tracks have urls) 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 let codecEvents: number = 2;\n if (data.audio && !data.video || !data.altAudio) {\n codecEvents = 1;\n }\n this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;\n\n logger.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`);\n }\n\n onMediaAttaching (data: { media: HTMLMediaElement }) {\n let media = this.media = data.media;\n if (media && MediaSource) {\n // setup the media source\n let ms = this.mediaSource = new MediaSource();\n // Media Source listeners\n ms.addEventListener('sourceopen', this._onMediaSourceOpen);\n ms.addEventListener('sourceended', this._onMediaSourceEnded);\n ms.addEventListener('sourceclose', this._onMediaSourceClose);\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._onMediaSourceOpen);\n ms.removeEventListener('sourceended', this._onMediaSourceEnded);\n ms.removeEventListener('sourceclose', this._onMediaSourceClose);\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 if (this._objectUrl) {\n window.URL.revokeObjectURL(this._objectUrl);\n }\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.bufferCodecEventsExpected = this._bufferCodecEventsTotal;\n this.pendingTracks = {};\n this.tracks = {};\n this.sourceBuffer = {};\n this.flushRange = [];\n this.segments = [];\n this.appended = 0;\n }\n\n this.hls.trigger(Events.MEDIA_DETACHED);\n }\n\n checkPendingTracks () {\n let { bufferCodecEventsExpected, pendingTracks } = this;\n\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 private _onMediaSourceOpen = () => {\n logger.log('media source opened');\n this.hls.trigger(Events.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._onMediaSourceOpen);\n }\n this.checkPendingTracks();\n }\n\n private _onMediaSourceClose = () => {\n logger.log('media source closed');\n }\n\n private _onMediaSourceEnded = () => {\n logger.log('media source ended');\n }\n\n private _onSBUpdateEnd = () => {\n // update timestampOffset\n if (this.audioTimestampOffset && this.sourceBuffer.audio) {\n let audioBuffer = this.sourceBuffer.audio;\n\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 const timeRanges: Partial<Record<SourceBufferName, TimeRanges>> = {};\n const sbSet = this.sourceBuffer;\n for (let streamType in sbSet) {\n const sb = sbSet[streamType as SourceBufferName];\n if (!sb) {\n throw Error(`handling source buffer update end error: source buffer for ${streamType} uninitilized and unable to update buffered TimeRanges.`);\n }\n timeRanges[streamType as SourceBufferName] = sb.buffered;\n }\n\n this.hls.trigger(Events.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 private _onSBUpdateError = (event: 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(Events.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 const sourceBuffer = this.sourceBuffer;\n for (let type in sourceBuffer) {\n const sb = sourceBuffer[type];\n try {\n if (sb) {\n if (this.mediaSource) {\n this.mediaSource.removeSourceBuffer(sb);\n }\n sb.removeEventListener('updateend', this._onSBUpdateEnd);\n sb.removeEventListener('error', this._onSBUpdateError);\n }\n } catch (err) {\n }\n }\n this.sourceBuffer = {};\n this.flushRange = [];\n this.segments = [];\n this.appended = 0;\n }\n\n onBufferCodecs (tracks: TrackSet) {\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 this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);\n if (this.mediaSource && this.mediaSource.readyState === 'open') {\n this.checkPendingTracks();\n }\n }\n\n createSourceBuffers (tracks: TrackSet) {\n const { sourceBuffer, mediaSource } = this;\n if (!mediaSource) {\n throw Error('createSourceBuffers called when mediaSource was null');\n }\n\n for (let trackName in tracks) {\n if (!sourceBuffer[trackName]) {\n let track = tracks[trackName as keyof TrackSet];\n if (!track) {\n throw Error(`source buffer exists for track ${trackName}, however track does not`);\n }\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._onSBUpdateEnd);\n sb.addEventListener('error', this._onSBUpdateError);\n this.tracks[trackName] = {\n buffer: sb,\n codec: codec,\n id: track.id,\n container: track.container,\n levelCodec: track.levelCodec\n };\n } catch (err) {\n logger.error(`error while trying to add sourceBuffer:${err.message}`);\n this.hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType: mimeType });\n }\n }\n }\n this.hls.trigger(Events.BUFFER_CREATED, { tracks: this.tracks });\n }\n\n onBufferAppending (data: Segment) {\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 // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()\n // an undefined data.type will mark all buffers as EOS.\n onBufferEos (data: { type?: SourceBufferName }) {\n for (const type in this.sourceBuffer) {\n if (!data.type || data.type === type) {\n const sb = this.sourceBuffer[type as SourceBufferName];\n if (sb && !sb.ended) {\n sb.ended = true;\n logger.log(`${type} sourceBuffer now EOS`);\n }\n }\n }\n\n this.checkEos();\n }\n\n // if all source buffers are marked as ended, signal endOfStream() to MediaSource.\n checkEos () {\n const { sourceBuffer, mediaSource } = this;\n if (!mediaSource || mediaSource.readyState !== 'open') {\n this._needsEos = false;\n return;\n }\n\n for (let type in sourceBuffer) {\n const sb = sourceBuffer[type as SourceBufferName];\n if (!sb) continue;\n\n if (!sb.ended) {\n return;\n }\n\n if (sb.updating) {\n this._needsEos = true;\n return;\n }\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: { startOffset: number, endOffset: number, type?: SourceBufferName }) {\n if (data.type) {\n this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type });\n } else {\n this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: 'video' });\n this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: 'audio' });\n }\n\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.config.liveBackBufferLength;\n if (!isFinite(liveBackBufferLength) || liveBackBufferLength < 0) {\n return;\n }\n\n if (!this.media) {\n logger.error('flushLiveBackBuffer called without attaching media');\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];\n const sb = sourceBuffer[bufferType as SourceBufferName];\n if (sb) {\n const buffered = sb.buffered;\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 if (this.removeBufferRange(bufferType, sb, 0, targetBackBufferPosition)) {\n this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, { bufferEnd: targetBackBufferPosition });\n }\n }\n }\n }\n }\n\n onLevelUpdated ({ details }: { details: { totalduration: number, targetduration?: number, averagetargetduration?: number, live: boolean, fragments: any[] } }) {\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 if (this.config.liveDurationInfinity) {\n this.updateSeekableRange(details);\n }\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;\n let duration: number;\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 const sb = this.sourceBuffer[type];\n if (sb && sb.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) {\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 updateSeekableRange (levelDetails) {\n const mediaSource = this.mediaSource;\n const fragments = levelDetails.fragments;\n const len = fragments.length;\n if (len && mediaSource?.setLiveSeekableRange) {\n const start = fragments[0]?.start;\n const end = fragments[len - 1].start + fragments[len - 1].duration;\n mediaSource.setLiveSeekableRange(start, end);\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 const sb = sourceBuffer[type];\n if (sb) {\n appended += sb.buffered.length;\n }\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(Events.BUFFER_FLUSHED);\n }\n }\n\n doAppending () {\n let { config, hls, segments, sourceBuffer } = this;\n if (!Object.keys(sourceBuffer).length) {\n // early exit if no source buffers have been initialized yet\n return;\n }\n\n if (!this.media || 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\n if (this.appending) {\n // logger.log(`sb appending in progress`);\n return;\n }\n\n const segment = segments.shift();\n if (!segment) { // handle undefined shift\n return;\n }\n\n try {\n const sb = sourceBuffer[segment.type];\n if (!sb) {\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 return;\n }\n\n if (sb.updating) {\n // if we are still updating the source buffer from the last segment, place this back at the front of the queue\n segments.unshift(segment);\n return;\n }\n\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 } 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, details: '', fatal: false };\n if (err.code === 22) {\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 } else {\n this.appendError++;\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 > config.appendErrorMaxRetry) {\n logger.log(`fail ${config.appendErrorMaxRetry} times to append segment in sourceBuffer`);\n this.segments = [];\n event.fatal = true;\n }\n }\n hls.trigger(Events.ERROR, event);\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: number, endOffset: number, sbType: SourceBufferName): boolean {\n const sourceBuffer = this.sourceBuffer;\n // exit if no sourceBuffers are initialized\n if (!Object.keys(sourceBuffer).length) {\n return true;\n }\n\n let currentTime: string = 'null';\n if (this.media) {\n currentTime = this.media.currentTime.toFixed(3);\n }\n logger.log(`flushBuffer,pos/start/end: ${currentTime}/${startOffset}/${endOffset}`);\n\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 logger.warn('abort flushing too many retries');\n return true;\n }\n\n const sb = sourceBuffer[sbType];\n // we are going to flush buffer, mark source buffer as 'not ended'\n if (sb) {\n sb.ended = false;\n if (!sb.updating) {\n if (this.removeBufferRange(sbType, 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\n logger.log('buffer flushed');\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 {string} type Type of the source buffer, logging purposes only.\n * @param {SourceBuffer} sb Target SourceBuffer instance.\n * @param {number} startOffset\n * @param {number} endOffset\n *\n * @returns {boolean} True when source buffer remove requested.\n */\n removeBufferRange (type: string, sb: ExtendedSourceBuffer, startOffset: number, endOffset: number): boolean {\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 let currentTime: string = 'null';\n if (this.media) {\n currentTime = this.media.currentTime.toString();\n }\n\n logger.log(`sb remove ${type} [${removeStart},${removeEnd}], of [${bufStart},${bufEnd}], pos:${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.LEVELS_UPDATED,\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 this.clientRect = null;\n }\n\n destroy () {\n if (this.hls.config.capLevelToPlayerSize) {\n this.media = null;\n this.clientRect = 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 this.clientRect = null;\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 getDimensions () {\n if (this.clientRect) {\n return this.clientRect;\n }\n const media = this.media;\n const boundsRect = {\n width: 0,\n height: 0\n };\n\n if (media) {\n const clientRect = media.getBoundingClientRect();\n boundsRect.width = clientRect.width;\n boundsRect.height = clientRect.height;\n if (!boundsRect.width && !boundsRect.height) {\n // When the media element has no width or height (equivalent to not being in the DOM),\n // then use its width and height attributes (media.width, media.height)\n boundsRect.width = clientRect.right - clientRect.left || media.width || 0;\n boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;\n }\n }\n this.clientRect = boundsRect;\n return boundsRect;\n }\n\n get mediaWidth () {\n return this.getDimensions().width * CapLevelController.contentScaleFactor;\n }\n\n get mediaHeight () {\n return this.getDimensions().height * CapLevelController.contentScaleFactor;\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 * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess\n */\nexport enum KeySystems {\n WIDEVINE = 'com.widevine.alpha',\n PLAYREADY = 'com.microsoft.playready',\n}\n\nexport type MediaKeyFunc = (keySystem: KeySystems, supportedConfigurations: MediaKeySystemConfiguration[]) => Promise<MediaKeySystemAccess>;\nconst requestMediaKeySystemAccess = (function (): MediaKeyFunc | null {\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","/*\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\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: window.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 window.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(window.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, window.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","/**\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';\nimport { requestMediaKeySystemAccess, MediaKeyFunc } from './utils/mediakeys-helper';\n\ntype ABRControllerConfig = {\n abrEwmaFastLive: number,\n abrEwmaSlowLive: number,\n abrEwmaFastVoD: number,\n abrEwmaSlowVoD: number,\n abrEwmaDefaultEstimate: number,\n abrBandWidthFactor: number,\n abrBandWidthUpFactor: number,\n abrMaxWithRealBitrate: boolean,\n maxStarvationDelay: number,\n maxLoadingDelay: number,\n};\n\nexport type BufferControllerConfig = {\n appendErrorMaxRetry: number,\n liveDurationInfinity: boolean,\n liveBackBufferLength: number,\n};\n\ntype CapLevelControllerConfig = {\n capLevelToPlayerSize: boolean\n};\n\nexport type DRMSystemOptions = {\n audioRobustness?: string,\n videoRobustness?: string,\n}\n\nexport type EMEControllerConfig = {\n licenseXhrSetup?: (xhr: XMLHttpRequest, url: string) => void,\n emeEnabled: boolean,\n widevineLicenseUrl?: string,\n drmSystemOptions: DRMSystemOptions,\n requestMediaKeySystemAccessFunc: MediaKeyFunc | null,\n};\n\ntype FragmentLoaderConfig = {\n fLoader: any, // TODO(typescript-loader): Once Loader is typed fill this in\n\n fragLoadingTimeOut: number,\n fragLoadingMaxRetry: number,\n fragLoadingRetryDelay: number,\n fragLoadingMaxRetryTimeout: number,\n};\n\ntype FPSControllerConfig = {\n capLevelOnFPSDrop: boolean,\n fpsDroppedMonitoringPeriod: number,\n fpsDroppedMonitoringThreshold: number,\n};\n\ntype LevelControllerConfig = {\n startLevel?: number\n};\n\ntype MP4RemuxerConfig = {\n stretchShortVideoTrack: boolean,\n maxAudioFramesDrift: number,\n};\n\ntype PlaylistLoaderConfig = {\n pLoader: any, // TODO(typescript-loader): Once Loader is typed fill this in\n\n manifestLoadingTimeOut: number,\n manifestLoadingMaxRetry: number,\n manifestLoadingRetryDelay: number,\n manifestLoadingMaxRetryTimeout: number,\n\n levelLoadingTimeOut: number,\n levelLoadingMaxRetry: number,\n levelLoadingRetryDelay: number,\n levelLoadingMaxRetryTimeout: number\n};\n\ntype StreamControllerConfig = {\n autoStartLoad: boolean,\n startPosition: number,\n defaultAudioCodec?: string,\n initialLiveManifestSize: number,\n maxBufferLength: number,\n maxBufferSize: number,\n maxBufferHole: number,\n\n lowBufferWatchdogPeriod: number,\n highBufferWatchdogPeriod: number,\n nudgeOffset: number,\n nudgeMaxRetry: number,\n maxFragLookUpTolerance: number,\n liveSyncDurationCount: number,\n liveMaxLatencyDurationCount: number,\n liveSyncDuration?: number,\n liveMaxLatencyDuration?: number,\n maxMaxBufferLength: number,\n\n startFragPrefetch: boolean,\n testBandwidth: boolean\n};\n\ntype TimelineControllerConfig = {\n cueHandler: Cues.CuesInterface,\n enableCEA708Captions: boolean,\n enableWebVTT: boolean,\n captionsTextTrack1Label: string,\n captionsTextTrack1LanguageCode: string,\n captionsTextTrack2Label: string,\n captionsTextTrack2LanguageCode: string,\n captionsTextTrack3Label: string,\n captionsTextTrack3LanguageCode: string,\n captionsTextTrack4Label: string,\n captionsTextTrack4LanguageCode: string,\n renderTextTracksNatively: boolean,\n};\n\ntype TSDemuxerConfig = {\n forceKeyFrameOnDiscontinuity: boolean,\n};\n\nexport type HlsConfig =\n {\n debug: boolean,\n enableWorker: boolean,\n enableSoftwareAES: boolean,\n minAutoBitrate: number,\n loader: any, // TODO(typescript-xhrloader): Type once XHR is done\n xhrSetup?: (xhr: XMLHttpRequest, url: string) => void,\n\n // Alt Audio\n audioStreamController?: any, // TODO(typescript-audiostreamcontroller): Type once file is done\n audioTrackController?: any, // TODO(typescript-audiotrackcontroller): Type once file is done\n // Subtitle\n subtitleStreamController?: any, // TODO(typescript-subtitlestreamcontroller): Type once file is done\n subtitleTrackController?: any, // TODO(typescript-subtitletrackcontroller): Type once file is done\n timelineController?: any, // TODO(typescript-timelinecontroller): Type once file is done\n // EME\n emeController?: typeof EMEController,\n\n abrController: any, // TODO(typescript-abrcontroller): Type once file is done\n bufferController: typeof BufferController,\n capLevelController: any, // TODO(typescript-caplevelcontroller): Type once file is done\n fpsController: any, // TODO(typescript-fpscontroller): Type once file is done\n } &\n ABRControllerConfig &\n BufferControllerConfig &\n CapLevelControllerConfig &\n EMEControllerConfig &\n FPSControllerConfig &\n FragmentLoaderConfig &\n LevelControllerConfig &\n MP4RemuxerConfig &\n PlaylistLoaderConfig &\n StreamControllerConfig &\n TimelineControllerConfig &\n TSDemuxerConfig;\n\n// If possible, keep hlsDefaultConfig shallow\n// It is cloned whenever a new Hls instance is created, by keeping the config\n// shallow the properties are cloned, and we don't end up manipulating the default\nexport const hlsDefaultConfig: HlsConfig = {\n autoStartLoad: true, // used by stream-controller\n startPosition: -1, // used by stream-controller\n defaultAudioCodec: void 0, // 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: void 0, // used by stream-controller\n liveMaxLatencyDuration: void 0, // 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: void 0, // 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: void 0, // used by fragment-loader\n pLoader: void 0, // used by playlist-loader\n xhrSetup: void 0, // used by xhr-loader\n licenseXhrSetup: void 0, // used by eme-controller\n // fetchSetup: void 0,\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: void 0, // used by eme-controller\n drmSystemOptions: {}, // used by eme-controller\n requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess, // used by eme-controller\n testBandwidth: true,\n\n // Dynamic Modules\n ...timelineConfig(),\n subtitleStreamController: (__USE_SUBTITLES__) ? SubtitleStreamController : void 0,\n subtitleTrackController: (__USE_SUBTITLES__) ? SubtitleTrackController : void 0,\n timelineController: (__USE_SUBTITLES__) ? TimelineController : void 0,\n audioStreamController: (__USE_ALT_AUDIO__) ? AudioStreamController : void 0,\n audioTrackController: (__USE_ALT_AUDIO__) ? AudioTrackController : void 0,\n emeController: (__USE_EME_DRM__) ? EMEController : void 0\n};\n\nfunction timelineConfig (): TimelineControllerConfig {\n return {\n cueHandler: Cues, // used by timeline-controller\n enableCEA708Captions: __USE_SUBTITLES__, // used by timeline-controller\n enableWebVTT: __USE_SUBTITLES__, // used by timeline-controller\n captionsTextTrack1Label: 'English', // used by timeline-controller\n captionsTextTrack1LanguageCode: 'en', // used by timeline-controller\n captionsTextTrack2Label: 'Spanish', // used by timeline-controller\n captionsTextTrack2LanguageCode: 'es', // used by timeline-controller\n captionsTextTrack3Label: 'Unknown CC', // used by timeline-controller\n captionsTextTrack3LanguageCode: '', // used by timeline-controller\n captionsTextTrack4Label: 'Unknown CC', // used by timeline-controller\n captionsTextTrack4LanguageCode: '', // used by timeline-controller\n renderTextTracksNatively: true\n };\n}\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, HlsConfig } 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 public static defaultConfig?: HlsConfig;\n public config: HlsConfig;\n\n private _autoLevelCapping: number;\n private abrController: any;\n private capLevelController: any;\n private levelController: LevelController;\n private streamController: StreamController;\n private networkControllers: any[];\n private audioTrackController: any;\n private subtitleTrackController: any;\n private emeController: any;\n private coreComponents: any[];\n private media: HTMLMediaElement | null = null;\n private url: string | null = null;\n\n /**\n * @type {string}\n */\n static get version (): string {\n return __VERSION__;\n }\n\n /**\n * @type {boolean}\n */\n static isSupported (): boolean {\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 (): HlsConfig {\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: HlsConfig) {\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 (userConfig: Partial<HlsConfig> = {}) {\n super();\n\n const defaultConfig = Hls.DefaultConfig;\n\n if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {\n throw new Error('Illegal hls.js config: don\\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');\n }\n\n // Shallow clone\n this.config = {\n ...defaultConfig,\n ...userConfig\n };\n\n const { config } = this;\n\n if (config.liveMaxLatencyDurationCount !== void 0 && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {\n throw new Error('Illegal hls.js config: \"liveMaxLatencyDurationCount\" must be gt \"liveSyncDurationCount\"');\n }\n\n if (config.liveMaxLatencyDuration !== void 0 && (config.liveSyncDuration === void 0 || config.liveMaxLatencyDuration <= config.liveSyncDuration)) {\n throw new Error('Illegal hls.js config: \"liveMaxLatencyDuration\" must be gt \"liveSyncDuration\"');\n }\n\n enableLogs(config.debug);\n\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); // eslint-disable-line new-cap\n const bufferController = new config.bufferController(this); // eslint-disable-line new-cap\n const capLevelController = this.capLevelController = new config.capLevelController(this); // eslint-disable-line new-cap\n const fpsController = new config.fpsController(this); // eslint-disable-line new-cap\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: HTMLMediaElement) {\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: string) {\n this.stopLoad();\n const media = this.media;\n if (media && this.url) {\n this.detachMedia();\n this.attachMedia(media);\n }\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: number = -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 if (media) {\n this.attachMedia(media);\n }\n }\n\n /**\n * Remove a loaded level from the list of levels, or a level url in from a list of redundant level urls.\n * This can be used to remove a rendition or playlist url that errors frequently from the list of levels that a user\n * or hls.js can choose from.\n *\n * @param levelIndex {number} The quality level index to of the level to remove\n * @param urlId {number} The quality level url index in the case that fallback levels are available. Defaults to 0.\n */\n removeLevel (levelIndex, urlId = 0) {\n this.levelController.removeLevel(levelIndex, urlId);\n }\n\n /**\n * @type {QualityLevel[]}\n */\n // todo(typescript-levelController)\n get levels (): any[] {\n return this.levelController.levels;\n }\n\n /**\n * Index of quality level currently played\n * @type {number}\n */\n get currentLevel (): number {\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 * @param newLevel {number} -1 for automatic level selection\n */\n set currentLevel (newLevel: number) {\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 (): number {\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: number) {\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 (): number {\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: number) {\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 (): number {\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: number) {\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 (): number {\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: number) {\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 (): number {\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: number) {\n logger.log(`set startLevel:${newLevel}`);\n // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel\n if (newLevel !== -1) {\n newLevel = Math.max(newLevel, this.minAutoLevel);\n }\n\n this.levelController.startLevel = newLevel;\n }\n\n /**\n * set dynamically set capLevelToPlayerSize against (`CapLevelController`)\n *\n * @type {boolean}\n */\n set capLevelToPlayerSize (shouldStartCapping: boolean) {\n const newCapLevelToPlayerSize = !!shouldStartCapping;\n\n if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {\n if (newCapLevelToPlayerSize) {\n this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.\n } else {\n this.capLevelController.stopCapping();\n this.autoLevelCapping = -1;\n this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.\n }\n\n this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;\n }\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 (): number {\n return this._autoLevelCapping;\n }\n\n /**\n * get bandwidth estimate\n * @type {number}\n */\n get bandwidthEstimate (): number {\n const bwEstimator = this.abrController._bwEstimator;\n return bwEstimator ? bwEstimator.getEstimate() : NaN;\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: number) {\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 (): boolean {\n return (this.levelController.manualLevel === -1);\n }\n\n /**\n * Level set manually (if any)\n * @type {number}\n */\n get manualLevel (): number {\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 (): number {\n const { levels, config: { minAutoBitrate } } = this;\n const len = levels ? levels.length : 0;\n\n for (let i = 0; i < len; i++) {\n const levelNextBitrate = levels[i].realBitrate\n ? Math.max(levels[i].realBitrate, levels[i].bitrate)\n : levels[i].bitrate;\n\n if (levelNextBitrate > minAutoBitrate) {\n return i;\n }\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 (): number {\n const { levels, autoLevelCapping } = this;\n\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 (): number {\n // ensure next auto level is between min and max auto level\n return Math.min(Math.max(this.abrController.nextAutoLevel, this.minAutoLevel), this.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: number) {\n this.abrController.nextAutoLevel = Math.max(this.minAutoLevel, nextLevel);\n }\n\n /**\n * @type {AudioTrack[]}\n */\n // todo(typescript-audioTrackController)\n get audioTracks (): any[] {\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 (): number {\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: number) {\n const audioTrackController = this.audioTrackController;\n if (audioTrackController) {\n audioTrackController.audioTrack = audioTrackId;\n }\n }\n\n /**\n * @type {Seconds}\n */\n get liveSyncPosition (): number {\n return this.streamController.liveSyncPosition;\n }\n\n /**\n * get alternate subtitle tracks list from playlist\n * @type {SubtitleTrack[]}\n */\n // todo(typescript-subtitleTrackController)\n get subtitleTracks (): any[] {\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 (): number {\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: number) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleTrack = subtitleTrackId;\n }\n }\n\n /**\n * @type {boolean}\n */\n get subtitleDisplay (): boolean {\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: boolean) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleDisplay = value;\n }\n }\n}\n","import { getMediaSource } from './utils/mediasource-helper';\n\nexport function isSupported (): boolean {\n const mediaSource = getMediaSource();\n if (!mediaSource) {\n return false;\n }\n const sourceBuffer = self.SourceBuffer || (self as any).WebKitSourceBuffer as SourceBuffer;\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"],"sourceRoot":""}