1
|
{"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-isFinite.js","webpack://Hls/./src/demux/id3.js","webpack://Hls/./src/utils/get-self-scope.js","webpack://Hls/./node_modules/url-toolkit/src/url-toolkit.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/./node_modules/eventemitter3/index.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/task-loop.ts","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/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/controller/fps-controller.js","webpack://Hls/./src/utils/xhr-loader.js","webpack://Hls/./src/controller/audio-track-controller.js","webpack://Hls/./src/controller/audio-stream-controller.js","webpack://Hls/./src/utils/vttcue.js","webpack://Hls/./src/utils/vttparser.js","webpack://Hls/./src/utils/cues.ts","webpack://Hls/./src/utils/cea-608-parser.ts","webpack://Hls/./src/utils/output-filter.ts","webpack://Hls/./src/utils/webvtt-parser.js","webpack://Hls/./src/controller/timeline-controller.ts","webpack://Hls/./src/controller/subtitle-track-controller.js","webpack://Hls/./src/utils/mediakeys-helper.ts","webpack://Hls/./src/controller/subtitle-stream-controller.js","webpack://Hls/./src/controller/eme-controller.ts","webpack://Hls/./src/config.ts","webpack://Hls/./src/hls.ts","webpack://Hls/./src/is-supported.ts"],"names":["root","factory","exports","module","define","amd","this","enumerable","get","getter","value","key","bind","Object","prototype","hasOwnProperty","call","object","property","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","AUDIO_TRACKS_UPDATED","AUDIO_TRACK_SWITCHING","AUDIO_TRACK_SWITCHED","AUDIO_TRACK_LOADING","AUDIO_TRACK_LOADED","SUBTITLE_TRACKS_UPDATED","SUBTITLE_TRACK_SWITCH","SUBTITLE_TRACK_LOADING","SUBTITLE_TRACK_LOADED","SUBTITLE_FRAG_PROCESSED","INIT_PTS_FOUND","FRAG_LOADING","FRAG_LOAD_PROGRESS","FRAG_LOAD_EMERGENCY_ABORTED","FRAG_LOADED","FRAG_DECRYPTED","FRAG_PARSING_INIT_SEGMENT","FRAG_PARSING_USERDATA","FRAG_PARSING_METADATA","FRAG_PARSING_DATA","FRAG_PARSED","FRAG_BUFFERED","FRAG_CHANGED","FPS_DROP","FPS_DROP_LEVEL_CAPPING","ERROR","DESTROYING","KEY_LOADING","KEY_LOADED","STREAM_STATE_TRANSITION","LIVE_BACK_BUFFER_REACHED","ErrorTypes","ErrorDetails","isFiniteNumber","Number","isFinite","decoder","ID3","isHeader","data","offset","length","isFooter","getID3Data","front","_readSize","subarray","size","getTimeStamp","frames","getID3Frames","i","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","c","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","AESCrypto","subtle","iv","aesIV","decrypt","name","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","d","x","xi","sx","x2","x4","x8","t","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","slice","destroy","undefined","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","has","prefix","Events","EE","fn","context","once","addListener","emitter","event","TypeError","listener","evt","_events","_eventsCount","clearEvent","EventEmitter","create","__proto__","eventNames","events","names","getOwnPropertySymbols","concat","listeners","handlers","l","ee","Array","listenerCount","emit","a1","a2","a3","a4","a5","arguments","removeListener","j","on","removeAllListeners","off","prefixed","isHeaderPattern","getHeaderLength","getFullFrameLength","probe","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","headerLength","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","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","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","now","MAX_SILENT_FRAME_DURATION_90KHZ","PTS_DTS_SHIFT_TOLERANCE_90KHZ","MP4Remuxer","vendor","isSafari","match","ISGenerated","defaultTimeStamp","generateIS","nbAudioSamples","nbVideoSamples","audioTimeOffset","videoTimeOffset","audiovideoDeltaDts","max","audioTrackLength","remuxAudio","endPTS","startPTS","remuxVideo","videoData","remuxEmptyAudio","remuxID3","remuxText","initPTS","initDTS","audioSamples","videoSamples","computePTSDTS","Infinity","metadata","keys","mp4SampleDuration","firstPTS","firstDTS","lastPTS","lastDTS","timeScale","inputSamples","outputSamples","ptsNormalize","_PTSNormalize","nextAvcDts","sort","a","deltadts","deltapts","PTSDTSshift","reduce","curr","delta","nbNalu","naluLen","nbUnits","sampleLen","mdatSize","MUX_ERROR","REMUX_ALLOC_ERROR","setUint32","avcSampleUnits","mp4SampleLength","compositionTimeOffset","unitData","unitDataLen","lastFrameDuration","stretchShortVideoTrack","maxBufferHole","gapTolerance","deltaToFrameEnd","nextAudioPts","data1","data2","startDTS","endDTS","hasAudio","hasVideo","nb","mp4Sample","fillFrame","mp4timeScale","scaleFactor","inputSampleDuration","rawMPEG","filter","maxAudioFramesDrift","nextPts","missing","newStamp","audioSample","numMissingFrames","unitLen","lastSampleDuration","silentFrame","reference","PassThroughRemuxer","rawData","streamType","performance","Date","DemuxerInline","demuxer","discontinuity","trackSwitch","defaultInitPTS","startTime","endTime","stats","tstart","tdecrypt","pushDecrypted","muxConfig","demux","MP4Demuxer","mux","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","modules","installedModules","__webpack_require__","moduleId","m","o","defineProperty","configurable","r","n","__esModule","p","oe","f","s","ENTRY_MODULE","default","dependencyRegExp","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","MAX_SAFE_INTEGER","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","setCodecs","codecs","filtered","typeCodes","isCodecType","preferred","unknownCodecs","resolution","bitrate","NAME","CODECS","parseMasterPlaylistMedia","audioGroups","medias","TYPE","media","groupId","LANGUAGE","DEFAULT","autoselect","AUTOSELECT","forced","FORCED","lang","URI","groupCodec","parseLevelPlaylist","levelUrlId","currentSN","discontinuityCounter","prevFrag","firstPdtIndex","assignProgramDateTime","value1","value2","toUpperCase","keyAttrs","decryptmethod","decrypturi","decryptiv","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","embeddedAudioFound","unshift","levelId","levelType","levelDetails","singleLevel","tparsed","sidxUrl","rangeStart","rangeEnd","sidxInfo","sidxReferences","segmentRef","segRefInfo","NETWORK_ERROR","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","fragmentTimes","time","esData","range","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","updateFragPTSDTS","maxStartPTS","drift","fragIdx","PTSKnown","mergeDetails","oldDetails","newDetails","PTSFrag","ccOffset","mapFragmentIntersection","oldFrag","newFrag","backtracked","newFragments","oldPlaylist","newPlaylist","oldFragments","adjustSliding","intersectionFn","computeReloadInterval","currentPlaylist","lastRequestTime","reloadInterval","minReloadInterval","TimeRanges","toFixed","adjustPts","sliding","alignStream","lastLevel","shouldAlign","shouldAlignOnDiscontinuities","referenceFrag","prevDetails","curDetails","prevFrags","curFrags","prevStartFrag","firstFrag","currentFrag","findFirstFragWithCC","findDiscontinuousReferenceFrag","alignDiscontinuities","lastDetails","hasProgramDateTime","lastPDT","alignPDT","findFragmentByPDT","PDTValue","maxFragLookUpTolerance","isArray","seg","pdtWithinToleranceTest","findFragmentByPTS","fragPrevious","fragNext","fragmentWithinToleranceTest","candidate","candidateLookupTolerance","pdtBufferEnd","GapController","fragmentTracker","nudgeRetry","stallReported","stalled","moved","seeking","poll","lastCurrentTime","currentTime","seeked","beginSeek","paused","ended","playbackRate","startJump","_trySkipBufferHole","tnow","stalledDuration","_reportStall","bufferedWithHoles","_tryFixBufferStall","stalledDurationMs","highBufferWatchdogPeriod","_tryNudgeBuffer","BUFFER_STALLED_ERROR","lastEndTime","targetTime","BUFFER_SEEK_OVER_HOLE","nudgeMaxRetry","nudgeOffset","BUFFER_NUDGE_ON_STALL","TaskLoop","_boundTick","_tickTimer","_tickInterval","_tickCallCount","tick","clearNextTick","clearInterval","hasInterval","hasNextTick","setInterval","millis","clearTimeout","doTick","setTimeout","State","BaseStreamController","startLoad","stopLoad","fragCurrent","_streamEnded","fragState","onMediaSeeking","mediaBuffer","tolerance","fragStartOffset","fragEndOffset","loadedmetadata","nextLoadPosition","startPosition","onMediaEnded","computeLivePosition","targetLatency","liveSyncDuration","liveSyncDurationCount","StreamController","audioCodecSwap","_state","gapController","altAudio","fragLoadError","startFragRequested","startLevel","nextLoadLevel","forceStartLoad","_doTickIdle","retryDate","_checkBuffer","_checkFragmentChanged","levelLastLoaded","startFragPrefetch","levelInfo","maxBufLen","levelBitrate","maxBufferSize","maxBufferLength","maxMaxBufferLength","_fetchPayloadOrEos","fragLen","initialLiveManifestSize","_ensureFragmentAtLivePoint","_findFragment","encrypted","_loadKey","_loadFragment","maxLatency","liveMaxLatencyDuration","liveMaxLatencyDurationCount","liveSyncPosition","readyState","targetSN","fragPreviousLoad","fragmentIndexRange","fragNextLoad","curSNIdx","sameLevel","prevSnFrag","nextSnFrag","autoLevel","autoLevelEnabled","_reduceMaxBufferLength","followingBufferedFrag","fragPlayingCurrent","fragPlaying","fragPlayingLevel","immediateLevelSwitch","immediateSwitch","previouslyPaused","pause","flushMainBuffer","POSITIVE_INFINITY","immediateLevelSwitchEnd","play","nextLevelSwitch","fetchdelay","nextBufferedFrag","nextLevelId","nextLevel","fragLastKbps","startOffset","endOffset","flushScope","onMediaAttached","onvseeking","onvseeked","onMediaSeeked","onvended","autoStartLoad","onMediaDetaching","onManifestParsed","aac","heaac","audioCodecSwitch","onLevelLoaded","newLevelId","curLevel","LevelHelper","onKeyLoaded","fragLoaded","currentLevel","tbuffered","pendingBuffering","appended","initSegmentData","_getAudioCodec","onFragParsingInitSegment","fragNew","trackName","ua","levelCodec","parent","content","onFragParsingData","onFragParsed","_checkAppendedParsed","onAudioTrackSwitching","onAudioTrackSwitched","videoBuffer","onBufferCreated","mediaTrack","alternate","pending","total","tfirst","mediaBuffered","fragLoadingMaxRetry","delay","levelRetry","BUFFER_FULL_ERROR","minLength","_seekToStartPos","onFragLoadEmergencyAborted","onBufferFlushed","swapAudioCodec","defaultAudioCodec","nextState","previousState","_liveSyncPosition","chromeOrFirefox","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","nextAutoLevel","trequest","audioGroupId","levelObject","_startLevel","configStartLevel","sendAddTrackEvent","videoEl","document","createEvent","initEvent","dispatchEvent","clearCurrentCues","cues","removeCue","ID3TrackController","getID3Track","textTracks","kind","label","addTextTrack","onFragParsingMetadata","mode","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","minAutoLevel","aborted","requestDelay","loadRate","bw","realBitrate","expectedLen","fragLoadedDelay","bufferStarvationDelay","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","onMediaAttaching","ms","endOfStream","removeAttribute","pendingTracksCount","createSourceBuffers","onBufferReset","removeSourceBuffer","onBufferCodecs","mimeType","addSourceBuffer","BUFFER_ADD_CODEC_ERROR","onBufferAppending","onBufferEos","onBufferFlushing","liveBackBufferLength","bufferTypes","targetBackBufferPosition","bufferType","removeBufferRange","onLevelUpdated","liveDurationInfinity","flushBuffer","appendBuffer","code","BUFFER_APPEND_ERROR","appendErrorMaxRetry","sbType","bufStart","bufEnd","removeStart","removeEnd","remove","CapLevelController","autoLevelCapping","restrictedLevels","capLevelToPlayerSize","stopCapping","onFpsDropLevelCapping","isLevelAllowed","droppedLevel","HTMLVideoElement","startCapping","onLevelsUpdated","detectPlayerSize","levelsLength","getMaxLevel","streamController","capLevelIndex","validLevels","getMaxLevelByMediaSize","mediaWidth","mediaHeight","maxLevelIndex","devicePixelRatio","clientWidth","offsetWidth","contentScaleFactor","clientHeight","offsetHeight","FPSController","isVideoPlaybackQualityAvailable","capLevelOnFPSDrop","getVideoPlaybackQuality","checkFPSInterval","fpsDroppedMonitoringPeriod","checkFPS","decodedFrames","droppedFrames","lastTime","currentPeriod","currentDropped","lastDroppedFrames","currentDecoded","lastDecodedFrames","droppedFPS","totalDroppedFrames","fpsDroppedMonitoringThreshold","videoPlaybackQuality","totalVideoFrames","droppedVideoFrames","webkitDecodedFrameCount","webkitDroppedFrameCount","XMLHttpRequest","XhrLoader","xhrSetup","requestTimeout","retryTimeout","callbacks","retry","loadInternal","xhr","open","status","setRequestHeader","onreadystatechange","readystatechange","onprogress","send","currentTarget","responseText","responseURL","statusText","lengthComputable","AudioTrackController","_trackId","_selectDefaultTrack","trackIdBlacklist","_selectAudioGroup","onAudioTrackLoaded","updatePeriodMs","_handleLoadError","_setAudioTrack","newId","_loadTrackDetailsIfNeeded","_updateTrack","_selectInitialAudioTrack","currentAudioTrack","defaultTracks","trackFound","traverseTracks","_needsTrackLoading","previousId","language","AudioStreamController","waitingFragment","videoTrackCC","onInitPtsFound","demuxerId","trackDetails","mainBufferInfo","maxConfigBuffer","audioSwitch","CC","findFragWithCC","loadIdx","fragLoadIdx","nextBuffered","foundFrag","isSeeking","waitingFrag","waitingFragCC","onAudioTracksUpdated","appendObj","pendingData","appendOnBufferFlush","directionSetting","lr","rl","alignSetting","middle","findAlignSetting","extend","obj","cobj","baseObj","hasBeenReset","_id","_pauseOnExit","_startTime","_endTime","_text","_region","_vertical","_snapToLines","_line","_lineAlign","_position","_positionAlign","_size","_align","setting","findDirectionSetting","SyntaxError","displayState","getCueAsHTML","WebVTT","convertCueToDOMTree","StringDecoder","decodeURIComponent","encodeURIComponent","VTTParser","regionList","Settings","values","parseOptions","keyValueDelim","groupDelim","kv","k","v","dflt","defaultKey","alt","integer","percent","defaults","center","align","parseCue","oInput","consumeTimeStamp","ts","computeSeconds","parseTimeStamp","skipWhitespace","settings","region","vals","vals0","vertical","line","lineAlign","snapToLines","consumeCueSettings","fixLineBreaks","collectNextLine","alreadyCollectedLine","hasSubstring","oncue","flush","onflush","newCue","captionScreen","row","indenting","indent","rows","isEmpty","chars","uchar","cueStartTime","VerboseFilter","specialCea608CharsCodes","getCharForByte","byte","charCode","rowsLowCh1","rowsHighCh1","rowsLowCh2","rowsHighCh2","backgroundColors","verboseFilter","verboseLevel","setTime","newTime","severity","numArrayToHexArray","numArray","hexArray","PenState","foreground","underline","italics","background","flash","reset","setStyles","styles","attribs","style","isDefault","equals","other","copy","newPenState","StyledUnicodeChar","penState","setChar","setPenState","newChar","Row","currPenState","equal","empty","setCursor","absPos","moveCursor","relPos","newPos","backSpace","insertChar","char","clearFromPos","startPos","clear","clearToEndOfRow","getTextString","setPenStyles","CaptionScreen","currRow","nrRollUpRows","lastOutputScreen","NR_ROWS","setPen","setPAC","pacData","newRow","topRowIndex","prevLineTime","prevPos","color","setBkgData","bkgData","setRollUpRows","nrRows","rollUp","getDisplayText","topRow","asOneRow","displayText","rowNr","rowText","getTextAndFormat","Cea608Channel","channelNumber","outputFilter","chNr","verbose","displayedMemory","nonDisplayedMemory","currRollUpRow","writeScreen","lastCueEndTime","getHandler","setHandler","newHandler","setMode","newMode","insertChars","screen","outputDataUpdate","ccRCL","ccBS","ccAOF","ccAON","ccDER","ccRU","ccFON","ccRDC","ccTR","ccRTD","ccEDM","ccCR","ccENM","ccEOC","ccTO","nrCols","ccMIDROW","secondByte","colorIndex","dispatch","dispatchCue","cueSplitAtTime","Cea608Parser","field","out1","out2","outputs","channels","currChNr","lastCmdA","lastCmdB","dataCounters","addData","byteList","cmdFound","charsFound","parseCmd","parseMidrow","parsePAC","parseBackgroundAttributes","parseChars","padding","channel","interpretPAC","pacIndex","channelNr","charCodes","charCode1","oneCode","hexCodes","OutputFilter","timelineController","addCues","createCaptionsTrack","startsWith","inputString","searchString","hash","WebVTTParser","vttByteArray","syncPTS","vttCCs","callBack","errorCallBack","parsingError","vttLines","cueTime","mpegTs","localTime","presentationTime","inHeader","timestampMap","parser","currCC","cueOffset","new","prevCC","presentationOffset","calculateOffset","onparsingerror","timeString","secs","mins","hours","cueString2millis","canReuseVttTextTrack","inUseTrack","manifestTrack","textTrack1","textTrack2","TimelineController","enabled","Cues","unparsedVttFrags","cueRanges","captionsTracks","captionsProperties","cea608Parser","lastSn","cueHandler","captionsTextTrack1Label","languageCode","captionsTextTrack1LanguageCode","captionsTextTrack2Label","captionsTextTrack2LanguageCode","enableCEA708Captions","channel1","channel2","x1","y1","y2","ranges","merged","cueRange","overlap","getExistingTrack","existingTrack","createTextTrack","_cleanTracks","0","enableWebVTT","inUseTracks","subtitleDisplay","success","decryptData","_parseVTTs","currentTrack","getCueById","textTrackCue","onFragDecrypted","onFragParsingUserdata","ccBytes","ccdatas","extractCea608Data","tmpByte","ccbyte1","ccbyte2","actualCCBytes","filterSubtitleTracks","textTrackList","SubtitleTrackController","stopped","queuedDefaultTrack","subtitleTrack","trackChangeListener","_onTextTracksChanged","useTextTrackPolling","subtitlePollingInterval","subtitleTracks","onSubtitleTrackLoaded","_clearReloadTimer","_loadCurrentTrack","_toggleTrackModes","oldTrack","nextTrack","_setSubtitleTrackInternal","subtitleTrackId","KeySystems","SubtitleStreamController","tracksBuffered","currentTrackId","lastAVStart","_onMediaSeeking","onSubtitleFragProcessed","fragStart","fragEnd","onSubtitleTracksUpdated","onSubtitleTrackSwitch","referenceStart","frags","mergeSubtitlePlaylists","_getBuffered","requestMediaKeySystemAccess","EMEController","_widevineLicenseUrl","_licenseXhrSetup","_emeEnabled","_requestMediaKeySystemAccess","_config","_mediaKeysList","_media","_hasSetMediaKeys","_requestLicenseFailureCount","_onMediaEncrypted","initDataType","_attemptSetMediaKeys","_generateRequestWithPreferredKeySession","widevineLicenseUrl","licenseXhrSetup","emeEnabled","requestMediaKeySystemAccessFunc","getLicenseServerUrl","keySystem","WIDEVINE","_attemptKeySystemAccess","audioCodecs","videoCodecs","mediaKeySystemConfigs","baseConfig","videoCapabilities","contentType","createWidevineMediaKeySystemConfigurations","getSupportedMediaKeySystemConfigurations","mediaKeySystemAccess","_onMediaKeySystemAccessObtained","mediaKeysListItem","mediaKeysSessionInitialized","mediaKeySystemDomain","createMediaKeys","mediaKeys","_onMediaKeysCreated","mediaKeysSession","createSession","_onNewMediaKeySession","keySession","sessionId","_onKeySessionMessage","_requestLicense","update","keysListItem","KEY_SYSTEM_ERROR","KEY_SYSTEM_NO_KEYS","setMediaKeys","KEY_SYSTEM_NO_ACCESS","KEY_SYSTEM_NO_SESSION","KEY_SYSTEM_NO_INIT_DATA","generateRequest","_createLicenseXhr","keyMessage","_onLicenseRequestReadyStageChange","KEY_SYSTEM_LICENSE_REQUEST_FAILED","attemptsLeft","_generateLicenseRequestChallenge","challenge","onMediaDetached","hlsDefaultConfig","lowBufferWatchdogPeriod","abrController","bufferController","capLevelController","fpsController","minAutoBitrate","timelineConfig","subtitleStreamController","subtitleTrackController","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","audioTrack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AKslB,IAAI1tB,KAAKymD,aAAcxK,K,kCAQ/D,IAAMszB,EAAuBvvE,KAAKuvE,qBAClC,OAAOA,EAAuBA,EAAqB5nC,YAAc,K,iCAQjE,IAAM4nC,EAAuBvvE,KAAKuvE,qBAClC,OAAOA,EAAuBA,EAAqBxuD,YAAc,G,aAOnDwwD,GACd,IAAMhC,EAAuBvvE,KAAKuvE,qBAC9BA,IACFA,EAAqBxuD,WAAawwD,K,uCAQpC,OAAOvxE,KAAKouD,iBAAiBhU,mB,qCAS7B,IAAMi1B,EAA0BrvE,KAAKqvE,wBACrC,OAAOA,EAA0BA,EAAwBhG,eAAiB,K,oCAQ1E,IAAMgG,EAA0BrvE,KAAKqvE,wBACrC,OAAOA,EAA0BA,EAAwBrG,eAAiB,G,aAOzDa,GACjB,IAAMwF,EAA0BrvE,KAAKqvE,wBACjCA,IACFA,EAAwBrG,cAAgBa,K,sCAQ1C,IAAMwF,EAA0BrvE,KAAKqvE,wBACrC,QAAOA,GAA0BA,EAAwB1H,iB,aAOtCvnE,GACnB,IAAMivE,EAA0BrvE,KAAKqvE,wBACjCA,IACFA,EAAwB1H,gBAAkBvnE,O,GAjoBfquC,GAAZghC,GACLM,mB","file":"hls.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"Hls\"] = factory();\n\telse\n\t\troot[\"Hls\"] = factory();\n})(this, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"/dist/\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 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 audio track lists has been updated - data: { audioTracks : audioTracks }\n AUDIO_TRACKS_UPDATED: 'hlsAudioTracksUpdated',\n // fired when an audio track switching is requested - data: { id : audio track id }\n AUDIO_TRACK_SWITCHING: 'hlsAudioTrackSwitching',\n // fired when an audio track switch actually occurs - data: { id : audio track id }\n AUDIO_TRACK_SWITCHED: 'hlsAudioTrackSwitched',\n // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }\n AUDIO_TRACK_LOADING: 'hlsAudioTrackLoading',\n // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } }\n AUDIO_TRACK_LOADED: 'hlsAudioTrackLoaded',\n // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }\n SUBTITLE_TRACKS_UPDATED: 'hlsSubtitleTracksUpdated',\n // fired when an subtitle track switch occurs - data: { id : subtitle track id }\n SUBTITLE_TRACK_SWITCH: 'hlsSubtitleTrackSwitch',\n // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }\n SUBTITLE_TRACK_LOADING: 'hlsSubtitleTrackLoading',\n // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } }\n SUBTITLE_TRACK_LOADED: 'hlsSubtitleTrackLoaded',\n // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }\n SUBTITLE_FRAG_PROCESSED: 'hlsSubtitleFragProcessed',\n // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, frag : fragment object }\n INIT_PTS_FOUND: 'hlsInitPtsFound',\n // fired when a fragment loading starts - data: { frag : fragment object }\n FRAG_LOADING: 'hlsFragLoading',\n // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }\n FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',\n // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }\n FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',\n // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length } }\n FRAG_LOADED: 'hlsFragLoaded',\n // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }\n FRAG_DECRYPTED: 'hlsFragDecrypted',\n // fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment }\n FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',\n // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }\n FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',\n // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }\n FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',\n // fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}\n FRAG_PARSING_DATA: 'hlsFragParsingData',\n // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }\n FRAG_PARSED: 'hlsFragParsed',\n // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length, bwEstimate } }\n FRAG_BUFFERED: 'hlsFragBuffered',\n // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }\n FRAG_CHANGED: 'hlsFragChanged',\n // Identifier for a FPS drop event - data: { curentDropped, currentDecoded, totalDroppedFrames }\n FPS_DROP: 'hlsFpsDrop',\n // triggered when FPS drop triggers auto level capping - data: { level, droppedlevel }\n FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping',\n // Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data }\n ERROR: 'hlsError',\n // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }\n DESTROYING: 'hlsDestroying',\n // fired when a decrypt key loading starts - data: { frag : fragment object }\n KEY_LOADING: 'hlsKeyLoading',\n // fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length } }\n KEY_LOADED: 'hlsKeyLoaded',\n // fired upon stream controller state transitions - data: { previousState, nextState }\n STREAM_STATE_TRANSITION: 'hlsStreamStateTransition',\n // 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 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","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: <text string>\\0<binary data>\n */\n if (frame.size < 2) {\n return undefined;\n }\n\n const owner = ID3._utf8ArrayToStr(frame.data, true);\n const privateData = new Uint8Array(frame.data.subarray(owner.length + 1));\n\n return { key: frame.type, info: owner, data: privateData.buffer };\n }\n\n static _decodeTextFrame (frame) {\n if (frame.size < 2) {\n return undefined;\n }\n\n if (frame.type === 'TXXX') {\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Description}\\0{Value}\n */\n let index = 1;\n const description = ID3._utf8ArrayToStr(frame.data.subarray(index), 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));\n\n index += description.length + 1;\n const value = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n return { key: frame.type, info: description, data: value };\n } else {\n /*\n Format:\n [0-?] = {URL}\n */\n const url = ID3._utf8ArrayToStr(frame.data);\n return { key: frame.type, data: url };\n }\n }\n\n // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197\n // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt\n /* utf.js - UTF-8 <=> UTF-16 convertion\n *\n * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>\n * Version: 1.0\n * LastModified: Dec 25 1999\n * This library is free. You can redistribute it and/or modify it.\n */\n static _utf8ArrayToStr (array, exitOnNull = false) {\n const 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","// see https://tools.ietf.org/html/rfc1808\n\n/* jshint ignore:start */\n(function(root) { \n/* jshint ignore:end */\n\n var URL_REGEX = /^((?:[a-zA-Z0-9+\\-.]+:)?)(\\/\\/[^\\/?#]*)?((?:[^\\/\\?#]*\\/)*.*?)??(;.*?)?(\\?.*?)?(#.*?)?$/;\n var FIRST_SEGMENT_REGEX = /^([^\\/?#]*)(.*)$/;\n var SLASH_DOT_REGEX = /(?:\\/|^)\\.(?=\\/)/g;\n var SLASH_DOT_DOT_REGEX = /(?:\\/|^)\\.\\.\\/(?!\\.\\.\\/).*?(?=\\/)/g;\n\n var URLToolkit = { // jshint ignore:line\n // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //\n // E.g\n // With opts.alwaysNormalize = false (default, spec compliant)\n // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g\n // With opts.alwaysNormalize = true (not spec compliant)\n // http://a.com/b/cd + /e/f/../g => http://a.com/e/g\n buildAbsoluteURL: function(baseURL, relativeURL, opts) {\n opts = opts || {};\n // remove any remaining space and CRLF\n baseURL = baseURL.trim();\n relativeURL = relativeURL.trim();\n if (!relativeURL) {\n // 2a) If the embedded URL is entirely empty, it inherits the\n // entire base URL (i.e., is set equal to the base URL)\n // and we are done.\n if (!opts.alwaysNormalize) {\n return baseURL;\n }\n var basePartsForNormalise = URLToolkit.parseURL(baseURL);\n if (!basePartsForNormalise) {\n throw new Error('Error trying to parse base URL.');\n }\n basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);\n return URLToolkit.buildURLFromParts(basePartsForNormalise);\n }\n var relativeParts = URLToolkit.parseURL(relativeURL);\n if (!relativeParts) {\n throw new Error('Error trying to parse relative URL.');\n }\n if (relativeParts.scheme) {\n // 2b) If the embedded URL starts with a scheme name, it is\n // interpreted as an absolute URL and we are done.\n if (!opts.alwaysNormalize) {\n return relativeURL;\n }\n relativeParts.path = URLToolkit.normalizePath(relativeParts.path);\n return URLToolkit.buildURLFromParts(relativeParts);\n }\n var baseParts = URLToolkit.parseURL(baseURL);\n if (!baseParts) {\n throw new Error('Error trying to parse base URL.');\n }\n if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {\n // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc\n // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'\n var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);\n baseParts.netLoc = pathParts[1];\n baseParts.path = pathParts[2];\n }\n if (baseParts.netLoc && !baseParts.path) {\n baseParts.path = '/';\n }\n var builtParts = {\n // 2c) Otherwise, the embedded URL inherits the scheme of\n // the base URL.\n scheme: baseParts.scheme,\n netLoc: relativeParts.netLoc,\n path: null,\n params: relativeParts.params,\n query: relativeParts.query,\n fragment: relativeParts.fragment\n };\n if (!relativeParts.netLoc) {\n // 3) If the embedded URL's <net_loc> is non-empty, we skip to\n // Step 7. Otherwise, the embedded URL inherits the <net_loc>\n // (if any) of the base URL.\n builtParts.netLoc = baseParts.netLoc;\n // 4) If the embedded URL path is preceded by a slash \"/\", the\n // path is not relative and we skip to Step 7.\n if (relativeParts.path[0] !== '/') {\n if (!relativeParts.path) {\n // 5) If the embedded URL path is empty (and not preceded by a\n // slash), then the embedded URL inherits the base URL path\n builtParts.path = baseParts.path;\n // 5a) if the embedded URL's <params> is non-empty, we skip to\n // step 7; otherwise, it inherits the <params> of the base\n // URL (if any) and\n if (!relativeParts.params) {\n builtParts.params = baseParts.params;\n // 5b) if the embedded URL's <query> is non-empty, we skip to\n // step 7; otherwise, it inherits the <query> of the base\n // URL (if any) and we skip to step 7.\n if (!relativeParts.query) {\n builtParts.query = baseParts.query;\n }\n }\n } else {\n // 6) The last segment of the base URL's path (anything\n // following the rightmost slash \"/\", or the entire path if no\n // slash is present) is removed and the embedded URL's path is\n // appended in its place.\n var baseURLPath = baseParts.path;\n var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;\n builtParts.path = URLToolkit.normalizePath(newPath);\n }\n }\n }\n if (builtParts.path === null) {\n builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;\n }\n return URLToolkit.buildURLFromParts(builtParts);\n },\n parseURL: function(url) {\n var parts = URL_REGEX.exec(url);\n if (!parts) {\n return null;\n }\n return {\n scheme: parts[1] || '',\n netLoc: parts[2] || '',\n path: parts[3] || '',\n params: parts[4] || '',\n query: parts[5] || '',\n fragment: parts[6] || ''\n };\n },\n normalizePath: function(path) {\n // The following operations are\n // then applied, in order, to the new path:\n // 6a) All occurrences of \"./\", where \".\" is a complete path\n // segment, are removed.\n // 6b) If the path ends with \".\" as a complete path segment,\n // that \".\" is removed.\n path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');\n // 6c) All occurrences of \"<segment>/../\", where <segment> is a\n // complete path segment not equal to \"..\", are removed.\n // Removal of these path segments is performed iteratively,\n // removing the leftmost matching pattern on each iteration,\n // until no matching pattern remains.\n // 6d) If the path ends with \"<segment>/..\", where <segment> is a\n // complete path segment not equal to \"..\", that\n // \"<segment>/..\" is removed.\n while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {} // jshint ignore:line\n return path.split('').reverse().join('');\n },\n buildURLFromParts: function(parts) {\n return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;\n }\n };\n\n/* jshint ignore:start */\n if(typeof exports === 'object' && typeof module === 'object')\n module.exports = URLToolkit;\n else if(typeof define === 'function' && define.amd)\n define([], function() { return URLToolkit; });\n else if(typeof exports === 'object')\n exports[\"URLToolkit\"] = URLToolkit;\n else\n root[\"URLToolkit\"] = URLToolkit;\n})(this);\n/* jshint ignore:end */\n","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","'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","/**\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 // ADTS frame Length\n let frameLength = headerLength;\n if (offset + 5 < data.length) {\n frameLength = getFullFrameLength(data, offset);\n }\n\n let newOffset = offset + frameLength;\n if (newOffset === data.length || (newOffset + 1 < data.length && isHeaderPattern(data, newOffset))) {\n return true;\n }\n }\n return false;\n}\n\nexport function initTrackConfig (track, observer, data, offset, audioCodec) {\n if (!track.samplerate) {\n let config = getAudioConfig(observer, data, offset, audioCodec);\n track.config = config.config;\n track.samplerate = config.samplerate;\n track.channelCount = config.channelCount;\n track.codec = config.codec;\n track.manifestCodec = config.manifestCodec;\n logger.log(`parsed codec:${track.codec},rate:${config.samplerate},nb channel:${config.channelCount}`);\n }\n}\n\nexport function getFrameDuration (samplerate) {\n return 1024 * 90000 / samplerate;\n}\n\nexport function parseFrameHeader (data, offset, pts, frameIndex, frameDuration) {\n let headerLength, frameLength, stamp;\n let length = data.length;\n\n // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header\n headerLength = getHeaderLength(data, offset);\n // retrieve frame size\n frameLength = getFullFrameLength(data, offset);\n frameLength -= headerLength;\n\n if ((frameLength > 0) && ((offset + headerLength + frameLength) <= length)) {\n stamp = pts + frameIndex * frameDuration;\n // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);\n return { headerLength, frameLength, stamp };\n }\n\n return undefined;\n}\n\nexport function appendFrame (track, data, offset, pts, frameIndex) {\n let frameDuration = getFrameDuration(track.samplerate);\n let header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);\n if (header) {\n let stamp = header.stamp;\n let headerLength = header.headerLength;\n let frameLength = header.frameLength;\n\n // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);\n let aacSample = {\n unit: data.subarray(offset + headerLength, offset + headerLength + frameLength),\n pts: stamp,\n dts: stamp\n };\n\n track.samples.push(aacSample);\n 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 }\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\n this._avcTrack = TSDemuxer.createTrack('video', duration);\n this._audioTrack = TSDemuxer.createTrack('audio', duration);\n this._id3Track = TSDemuxer.createTrack('id3', duration);\n this._txtTrack = TSDemuxer.createTrack('text', duration);\n\n // flush any partial content\n this.aacOverFlow = null;\n this.aacLastPTS = null;\n this.avcSample = null;\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this._duration = duration;\n }\n\n /**\n *\n * @override\n */\n resetTimeStamp () {}\n\n // feed incoming data to the front of the parsing pipeline\n append (data, timeOffset, contiguous, accurateTimeOffset) {\n let start, len = data.length, stt, pid, atf, offset, pes,\n unknownPIDs = false;\n this.contiguous = contiguous;\n let pmtParsed = this.pmtParsed,\n avcTrack = this._avcTrack,\n audioTrack = this._audioTrack,\n id3Track = this._id3Track,\n avcId = avcTrack.pid,\n audioId = audioTrack.pid,\n id3Id = id3Track.pid,\n pmtId = this._pmtId,\n avcData = avcTrack.pesData,\n audioData = audioTrack.pesData,\n id3Data = id3Track.pesData,\n parsePAT = this._parsePAT,\n parsePMT = this._parsePMT,\n parsePES = this._parsePES,\n parseAVCPES = this._parseAVCPES.bind(this),\n parseAACPES = this._parseAACPES.bind(this),\n parseMPEGPES = this._parseMPEGPES.bind(this),\n parseID3PES = this._parseID3PES.bind(this);\n\n const syncOffset = TSDemuxer._syncOffset(data);\n\n // don't parse last TS packet if incomplete\n len -= (len + syncOffset) % 188;\n\n // loop through TS packets\n for (start = syncOffset; start < len; start += 188) {\n if (data[start] === 0x47) {\n stt = !!(data[start + 1] & 0x40);\n // pid is a 13-bit field starting at the last bit of TS[1]\n pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];\n atf = (data[start + 3] & 0x30) >> 4;\n // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.\n if (atf > 1) {\n offset = start + 5 + data[start + 4];\n // continue if there is only adaptation field\n if (offset === (start + 188)) {\n continue;\n }\n } else {\n offset = start + 4;\n }\n switch (pid) {\n case avcId:\n if (stt) {\n if (avcData && (pes = parsePES(avcData))) {\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 _parsePMT (data, offset, mpegSupported, isSampleAes) {\n let sectionLength, tableEnd, programInfoLength, pid, result = { audio: -1, avc: -1, id3: -1, isAAC: true };\n sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];\n tableEnd = offset + 3 + sectionLength - 4;\n // to determine where the table is, we have to figure out how\n // long the program info descriptors are\n programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];\n // advance the offset to the first entry in the mapping table\n offset += 12 + programInfoLength;\n while (offset < tableEnd) {\n pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];\n switch (data[offset]) {\n case 0xcf: // SAMPLE-AES AAC\n if (!isSampleAes) {\n logger.log('unknown stream type:' + data[offset]);\n break;\n }\n /* falls through */\n\n // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)\n case 0x0f:\n // logger.log('AAC PID:' + pid);\n if (result.audio === -1) {\n result.audio = pid;\n }\n\n break;\n\n // Packetized metadata (ID3)\n case 0x15:\n // logger.log('ID3 PID:' + pid);\n if (result.id3 === -1) {\n result.id3 = pid;\n }\n\n break;\n\n case 0xdb: // SAMPLE-AES AVC\n if (!isSampleAes) {\n logger.log('unknown stream type:' + data[offset]);\n break;\n }\n /* falls through */\n\n // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)\n case 0x1b:\n // logger.log('AVC PID:' + pid);\n if (result.avc === -1) {\n result.avc = pid;\n }\n\n break;\n\n // ISO/IEC 11172-3 (MPEG-1 audio)\n // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)\n case 0x03:\n case 0x04:\n // logger.log('MPEG PID:' + pid);\n if (!mpegSupported) {\n logger.log('MPEG audio found, not supported in this browser for now');\n } else if (result.audio === -1) {\n result.audio = pid;\n result.isAAC = false;\n }\n break;\n\n case 0x24:\n logger.warn('HEVC stream type found, not supported for now');\n break;\n\n default:\n logger.log('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 // check if greater than 2^32 -1\n if (pesPts > 4294967295) {\n // decrement 2^33\n pesPts -= 8589934592;\n }\n if (pesFlags & 0x40) {\n pesDts = (frag[14] & 0x0E) * 536870912 +// 1 << 29\n (frag[15] & 0xFF) * 4194304 +// 1 << 22\n (frag[16] & 0xFE) * 16384 +// 1 << 14\n (frag[17] & 0xFF) * 128 +// 1 << 7\n (frag[18] & 0xFE) / 2;\n // check if greater than 2^32 -1\n if (pesDts > 4294967295) {\n // decrement 2^33\n pesDts -= 8589934592;\n }\n if (pesPts - pesDts > 60 * 90000) {\n logger.warn(`${Math.round((pesPts - pesDts) / 90000)}s delta between PTS and DTS, align them`);\n pesPts = pesDts;\n }\n } else {\n pesDts = pesPts;\n }\n }\n pesHdrLen = frag[8];\n // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension\n payloadStartOffset = pesHdrLen + 9;\n\n 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 ? 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, toTimescaleFromScale } 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\nclass MP4Remuxer {\n constructor (observer, config, typeSupported, vendor) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n const userAgent = navigator.userAgent;\n this.isSafari = vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS');\n this.ISGenerated = false;\n }\n\n destroy () {\n }\n\n resetTimeStamp (defaultTimeStamp) {\n this._initPTS = this._initDTS = defaultTimeStamp;\n }\n\n resetInitSegment () {\n this.ISGenerated = false;\n }\n\n remux (audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {\n // generate Init Segment if needed\n if (!this.ISGenerated) {\n this.generateIS(audioTrack, videoTrack, timeOffset);\n }\n\n if (this.ISGenerated) {\n const nbAudioSamples = audioTrack.samples.length;\n const nbVideoSamples = videoTrack.samples.length;\n let audioTimeOffset = timeOffset;\n let videoTimeOffset = timeOffset;\n if (nbAudioSamples && nbVideoSamples) {\n // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)\n // if first audio DTS is not aligned with first video DTS then we need to take that into account\n // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small\n // drift between audio and video streams\n let audiovideoDeltaDts = (audioTrack.samples[0].pts - videoTrack.samples[0].pts) / videoTrack.inputTimeScale;\n audioTimeOffset += Math.max(0, audiovideoDeltaDts);\n videoTimeOffset += Math.max(0, -audiovideoDeltaDts);\n }\n // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is\n // calculated in remuxAudio.\n // logger.log('nb AAC samples:' + audioTrack.samples.length);\n if (nbAudioSamples) {\n // if initSegment was generated without video samples, regenerate it again\n if (!audioTrack.timescale) {\n logger.warn('regenerate InitSegment as audio detected');\n this.generateIS(audioTrack, videoTrack, timeOffset);\n }\n let audioData = this.remuxAudio(audioTrack, audioTimeOffset, contiguous, accurateTimeOffset);\n // logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (nbVideoSamples) {\n let audioTrackLength;\n if (audioData) {\n audioTrackLength = audioData.endPTS - audioData.startPTS;\n }\n\n // if initSegment was generated without video samples, regenerate it again\n if (!videoTrack.timescale) {\n logger.warn('regenerate InitSegment as video detected');\n this.generateIS(audioTrack, videoTrack, timeOffset);\n }\n this.remuxVideo(videoTrack, videoTimeOffset, contiguous, audioTrackLength, accurateTimeOffset);\n }\n } else {\n // logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (nbVideoSamples) {\n let videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0, accurateTimeOffset);\n if (videoData && audioTrack.codec) {\n this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData);\n }\n }\n }\n }\n // logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (id3Track.samples.length) {\n this.remuxID3(id3Track, timeOffset);\n }\n\n // logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (textTrack.samples.length) {\n this.remuxText(textTrack, timeOffset);\n }\n\n // notify end of parsing\n this.observer.trigger(Event.FRAG_PARSED);\n }\n\n generateIS (audioTrack, videoTrack, timeOffset) {\n let observer = this.observer,\n audioSamples = audioTrack.samples,\n videoSamples = videoTrack.samples,\n typeSupported = this.typeSupported,\n container = 'audio/mp4',\n tracks = {},\n data = { tracks: tracks },\n computePTSDTS = (this._initPTS === undefined),\n initPTS, initDTS;\n\n if (computePTSDTS) {\n initPTS = initDTS = Infinity;\n }\n\n if (audioTrack.config && audioSamples.length) {\n // let's use audio sampling rate as MP4 time scale.\n // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)\n // using audio sampling rate here helps having an integer MP4 frame duration\n // this avoids potential rounding issue and AV sync issue\n audioTrack.timescale = audioTrack.samplerate;\n logger.log(`audio sampling rate : ${audioTrack.samplerate}`);\n if (!audioTrack.isAAC) {\n if (typeSupported.mpeg) { // Chrome and Safari\n container = 'audio/mpeg';\n audioTrack.codec = '';\n } else if (typeSupported.mp3) { // Firefox\n audioTrack.codec = 'mp3';\n }\n }\n tracks.audio = {\n container: container,\n codec: audioTrack.codec,\n initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array() : MP4.initSegment([audioTrack]),\n metadata: {\n channelCount: audioTrack.channelCount\n }\n };\n if (computePTSDTS) {\n // remember first PTS of this demuxing context. for audio, PTS = DTS\n initPTS = initDTS = audioSamples[0].pts - audioTrack.inputTimeScale * timeOffset;\n }\n }\n\n if (videoTrack.sps && videoTrack.pps && videoSamples.length) {\n // let's use input time scale as MP4 video timescale\n // we use input time scale straight away to avoid rounding issues on frame duration / cts computation\n const inputTimeScale = videoTrack.inputTimeScale;\n videoTrack.timescale = inputTimeScale;\n tracks.video = {\n container: 'video/mp4',\n codec: videoTrack.codec,\n initSegment: MP4.initSegment([videoTrack]),\n metadata: {\n width: videoTrack.width,\n height: videoTrack.height\n }\n };\n if (computePTSDTS) {\n initPTS = Math.min(initPTS, videoSamples[0].pts - inputTimeScale * timeOffset);\n initDTS = Math.min(initDTS, videoSamples[0].dts - inputTimeScale * timeOffset);\n this.observer.trigger(Event.INIT_PTS_FOUND, { initPTS: initPTS });\n }\n }\n\n if (Object.keys(tracks).length) {\n observer.trigger(Event.FRAG_PARSING_INIT_SEGMENT, data);\n this.ISGenerated = true;\n if (computePTSDTS) {\n this._initPTS = initPTS;\n this._initDTS = initDTS;\n }\n } else {\n observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' });\n }\n }\n\n remuxVideo (track, timeOffset, contiguous, audioTrackLength, accurateTimeOffset) {\n let offset = 8;\n let mp4SampleDuration;\n let mdat;\n let moof;\n let firstPTS;\n let firstDTS;\n let lastPTS;\n let lastDTS;\n const timeScale = track.timescale;\n const inputSamples = track.samples;\n const outputSamples = [];\n const nbSamples = inputSamples.length;\n const ptsNormalize = this._PTSNormalize;\n const initPTS = this._initPTS;\n\n // if parsed fragment is contiguous with last one, let's use last DTS value as reference\n let nextAvcDts = this.nextAvcDts;\n\n const isSafari = this.isSafari;\n\n if (nbSamples === 0) {\n return;\n }\n\n // Safari does not like overlapping DTS on consecutive fragments. let's use nextAvcDts to overcome this if fragments are consecutive\n if (isSafari) {\n // also consider consecutive fragments as being contiguous (even if a level switch occurs),\n // for sake of clarity:\n // consecutive fragments are frags with\n // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR\n // - less than 200 ms PTS gaps (timeScale/5)\n contiguous |= (inputSamples.length && nextAvcDts &&\n ((accurateTimeOffset && Math.abs(timeOffset - nextAvcDts / timeScale) < 0.1) ||\n Math.abs((inputSamples[0].pts - nextAvcDts - initPTS)) < timeScale / 5)\n );\n }\n\n if (!contiguous) {\n // if not contiguous, let's use target timeOffset\n nextAvcDts = timeOffset * timeScale;\n }\n\n // PTS is coded on 33bits, and can loop from -2^32 to 2^32\n // ptsNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value\n inputSamples.forEach(function (sample) {\n sample.pts = ptsNormalize(sample.pts - initPTS, nextAvcDts);\n sample.dts = ptsNormalize(sample.dts - initPTS, nextAvcDts);\n });\n\n // sort video samples by DTS then PTS then demux id order\n inputSamples.sort(function (a, b) {\n const deltadts = a.dts - b.dts;\n const deltapts = a.pts - b.pts;\n return deltadts || (deltapts || (a.id - b.id));\n });\n\n // handle broken streams with PTS < DTS, tolerance up 0.2 seconds\n let PTSDTSshift = inputSamples.reduce((prev, curr) => Math.max(Math.min(prev, curr.pts - curr.dts), -1 * PTS_DTS_SHIFT_TOLERANCE_90KHZ), 0);\n if (PTSDTSshift < 0) {\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 < inputSamples.length; i++) {\n inputSamples[i].dts += PTSDTSshift;\n }\n }\n\n // compute first DTS and last DTS, normalize them against reference value\n let sample = inputSamples[0];\n firstDTS = Math.max(sample.dts, 0);\n firstPTS = Math.max(sample.pts, 0);\n\n // check timestamp continuity accross consecutive fragments (this is to remove inter-fragment gap/hole)\n let delta = firstDTS - nextAvcDts;\n // if fragment are contiguous, detect hole/overlapping between fragments\n if (contiguous) {\n if (delta) {\n if (delta > 1) {\n logger.log(`AVC: ${toMsFromMpegTsClock(delta, true)} ms hole between fragments detected,filling it`);\n } else if (delta < -1) {\n logger.log(`AVC: ${toMsFromMpegTsClock(-delta, true)} ms overlapping between fragments detected`);\n }\n\n // remove hole/gap : set DTS to next expected DTS\n firstDTS = nextAvcDts;\n inputSamples[0].dts = firstDTS;\n // offset PTS as well, ensure that PTS is smaller or equal than new DTS\n firstPTS = Math.max(firstPTS - delta, nextAvcDts);\n inputSamples[0].pts = firstPTS;\n logger.log(`Video: PTS/DTS adjusted: ${toMsFromMpegTsClock(firstPTS, true)}/${toMsFromMpegTsClock(firstDTS, true)}, delta: ${toMsFromMpegTsClock(delta, true)} ms`);\n }\n }\n\n // compute lastPTS/lastDTS\n sample = inputSamples[inputSamples.length - 1];\n lastDTS = Math.max(sample.dts, 0);\n lastPTS = Math.max(sample.pts, 0, lastDTS);\n\n // on Safari let's signal the same sample duration for all samples\n // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS\n // set this constant duration as being the avg delta between consecutive DTS.\n if (isSafari) {\n mp4SampleDuration = Math.round((lastDTS - firstDTS) / (inputSamples.length - 1));\n }\n\n let nbNalu = 0, naluLen = 0;\n for (let i = 0; i < nbSamples; i++) {\n // compute total/avc sample length and nb of NAL units\n let sample = inputSamples[i], units = sample.units, nbUnits = units.length, sampleLen = 0;\n for (let j = 0; j < nbUnits; j++) {\n sampleLen += units[j].data.length;\n }\n\n naluLen += sampleLen;\n nbNalu += nbUnits;\n sample.length = sampleLen;\n\n // normalize PTS/DTS\n if (isSafari) {\n // sample DTS is computed using a constant decoding offset (mp4SampleDuration) between samples\n sample.dts = firstDTS + i * mp4SampleDuration;\n } else {\n // ensure sample monotonic DTS\n sample.dts = Math.max(sample.dts, firstDTS);\n }\n // ensure that computed value is greater or equal than sample DTS\n sample.pts = Math.max(sample.pts, sample.dts);\n }\n\n /* concatenate the video data and construct the mdat in place\n (need 8 more bytes to fill length and mpdat type) */\n let mdatSize = naluLen + (4 * nbNalu) + 8;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch (err) {\n this.observer.trigger(Event.ERROR, { type: ErrorTypes.MUX_ERROR, details: ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: `fail allocating video mdat ${mdatSize}` });\n return;\n }\n let view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n\n for (let i = 0; i < nbSamples; i++) {\n let avcSample = inputSamples[i],\n avcSampleUnits = avcSample.units,\n mp4SampleLength = 0,\n compositionTimeOffset;\n // convert NALU bitstream to MP4 format (prepend NALU with size field)\n for (let j = 0, nbUnits = avcSampleUnits.length; j < nbUnits; j++) {\n let unit = avcSampleUnits[j],\n unitData = unit.data,\n unitDataLen = unit.data.byteLength;\n view.setUint32(offset, unitDataLen);\n offset += 4;\n mdat.set(unitData, offset);\n offset += unitDataLen;\n mp4SampleLength += 4 + unitDataLen;\n }\n\n if (!isSafari) {\n // expected sample duration is the Decoding Timestamp diff of consecutive samples\n if (i < nbSamples - 1) {\n mp4SampleDuration = inputSamples[i + 1].dts - avcSample.dts;\n } else {\n let config = this.config,\n lastFrameDuration = avcSample.dts - inputSamples[i > 0 ? i - 1 : i].dts;\n if (config.stretchShortVideoTrack) {\n // In some cases, a segment's audio track duration may exceed the video track duration.\n // Since we've already remuxed audio, and we know how long the audio track is, we look to\n // see if the delta to the next segment is longer than maxBufferHole.\n // If so, playback would potentially get stuck, so we artificially inflate\n // the duration of the last frame to minimize any potential gap between segments.\n let maxBufferHole = config.maxBufferHole,\n gapTolerance = Math.floor(maxBufferHole * timeScale),\n deltaToFrameEnd = (audioTrackLength ? firstPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;\n if (deltaToFrameEnd > gapTolerance) {\n // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video\n // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.\n mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;\n if (mp4SampleDuration < 0) {\n mp4SampleDuration = lastFrameDuration;\n }\n\n logger.log(`It is approximately ${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 } else {\n compositionTimeOffset = Math.max(0, mp4SampleDuration * Math.round((avcSample.pts - avcSample.dts) / mp4SampleDuration));\n }\n\n // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}');\n outputSamples.push({\n size: mp4SampleLength,\n // constant duration\n duration: mp4SampleDuration,\n cts: compositionTimeOffset,\n flags: {\n isLeading: 0,\n isDependedOn: 0,\n hasRedundancy: 0,\n degradPrio: 0,\n dependsOn: avcSample.key ? 2 : 1,\n isNonSync: avcSample.key ? 0 : 1\n }\n });\n }\n // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)\n this.nextAvcDts = lastDTS + mp4SampleDuration;\n let dropped = track.dropped;\n track.nbNalu = 0;\n track.dropped = 0;\n if (outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {\n let flags = outputSamples[0].flags;\n // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue\n // https://code.google.com/p/chromium/issues/detail?id=229412\n flags.dependsOn = 2;\n flags.isNonSync = 0;\n }\n track.samples = outputSamples;\n moof = MP4.moof(track.sequenceNumber++, firstDTS, track);\n track.samples = [];\n\n let data = {\n data1: moof,\n data2: mdat,\n startPTS: firstPTS / timeScale,\n endPTS: (lastPTS + mp4SampleDuration) / timeScale,\n startDTS: firstDTS / timeScale,\n endDTS: this.nextAvcDts / timeScale,\n type: 'video',\n hasAudio: false,\n hasVideo: true,\n nb: outputSamples.length,\n dropped: dropped\n };\n this.observer.trigger(Event.FRAG_PARSING_DATA, data);\n return data;\n }\n\n remuxAudio (track, timeOffset, contiguous, accurateTimeOffset) {\n const inputTimeScale = track.inputTimeScale;\n const mp4timeScale = track.timescale;\n const scaleFactor = inputTimeScale / mp4timeScale;\n const mp4SampleDuration = track.isAAC ? 1024 : 1152;\n const inputSampleDuration = mp4SampleDuration * scaleFactor;\n const ptsNormalize = this._PTSNormalize;\n const initPTS = this._initPTS;\n const rawMPEG = !track.isAAC && this.typeSupported.mpeg;\n\n let 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(function (sample) {\n return sample.pts >= 0;\n });\n\n // in case all samples have negative PTS, and have been filtered out, return now\n if (inputSamples.length === 0) {\n return;\n }\n\n if (!contiguous) {\n if (!accurateTimeOffset) {\n // if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS\n nextAudioPts = inputSamples[0].pts;\n } else {\n // if timeOffset is accurate, let's use it as predicted next audio PTS\n nextAudioPts = timeOffset * inputTimeScale;\n }\n }\n\n // If the audio track is missing samples, the frames seem to get \"left-shifted\" within the\n // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.\n // In an effort to prevent this from happening, we inject frames here where there are gaps.\n // When possible, we inject a silent frame; when that's not possible, we duplicate the last\n // frame.\n\n if (track.isAAC) {\n const maxAudioFramesDrift = this.config.maxAudioFramesDrift;\n for (let i = 0, nextPts = nextAudioPts; i < inputSamples.length;) {\n // First, let's see how far off this frame is from where we expect it to be\n var sample = inputSamples[i], delta;\n let pts = sample.pts;\n delta = pts - nextPts;\n\n // If we're overlapping by more than a duration, drop this sample\n if (delta <= -maxAudioFramesDrift * inputSampleDuration) {\n logger.warn(`Dropping 1 audio frame @ ${toMsFromMpegTsClock(nextPts, true)} ms due to ${toMsFromMpegTsClock(delta, true)} ms overlap.`);\n inputSamples.splice(i, 1);\n // Don't touch nextPtsNorm or i\n } // eslint-disable-line brace-style\n\n // Insert missing frames if:\n // 1: We're more than maxAudioFramesDrift frame away\n // 2: Not more than MAX_SILENT_FRAME_DURATION away\n // 3: currentTime (aka nextPtsNorm) is not 0\n else if (delta >= maxAudioFramesDrift * inputSampleDuration && delta < MAX_SILENT_FRAME_DURATION_90KHZ && nextPts) {\n let missing = Math.round(delta / inputSampleDuration);\n logger.warn(`Injecting ${missing} audio frames @ ${toMsFromMpegTsClock(nextPts, true)} ms due to ${toMsFromMpegTsClock(nextPts, 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) {\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) {\n let length = track.samples.length, sample;\n const inputTimeScale = track.inputTimeScale;\n const initPTS = this._initPTS;\n const initDTS = this._initDTS;\n // consume samples\n if (length) {\n for (let index = 0; index < length; index++) {\n sample = track.samples[index];\n // setting id3 pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts = ((sample.pts - initPTS) / inputTimeScale);\n sample.dts = ((sample.dts - initDTS) / inputTimeScale);\n }\n this.observer.trigger(Event.FRAG_PARSING_METADATA, {\n samples: track.samples\n });\n }\n\n track.samples = [];\n }\n\n remuxText (track) {\n track.samples.sort(function (a, b) {\n return (a.pts - b.pts);\n });\n\n let length = track.samples.length, sample;\n const inputTimeScale = track.inputTimeScale;\n const initPTS = this._initPTS;\n // consume samples\n if (length) {\n for (let index = 0; index < length; index++) {\n sample = track.samples[index];\n // setting text pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts = ((sample.pts - initPTS) / inputTimeScale);\n }\n this.observer.trigger(Event.FRAG_PARSING_USERDATA, {\n samples: track.samples\n });\n }\n\n track.samples = [];\n }\n\n _PTSNormalize (value, reference) {\n let offset;\n if (reference === undefined) {\n return value;\n }\n\n if (reference < value) {\n // - 2^33\n offset = -8589934592;\n } else {\n // + 2^33\n offset = 8589934592;\n }\n /* PTS is 33bit (from 0 to 2^33 -1)\n if diff between value and reference is bigger than half of the amplitude (2^32) then it means that\n PTS looping occured. fill the gap */\n while (Math.abs(value - reference) > 4294967296) {\n value += offset;\n }\n\n return value;\n }\n}\n\nexport default MP4Remuxer;\n","/**\n *\n * inline demuxer: probe fragments and instantiate\n * appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)\n *\n */\n\nimport Event from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport Decrypter from '../crypt/decrypter';\nimport AACDemuxer from '../demux/aacdemuxer';\nimport MP4Demuxer from '../demux/mp4demuxer';\nimport TSDemuxer from '../demux/tsdemuxer';\nimport MP3Demuxer from '../demux/mp3demuxer';\nimport MP4Remuxer from '../remux/mp4-remuxer';\nimport PassThroughRemuxer from '../remux/passthrough-remuxer';\n\nimport { getSelfScope } from '../utils/get-self-scope';\nimport { logger } from '../utils/logger';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\n\nlet now;\n// performance.now() not available on WebWorker, at least on Safari Desktop\ntry {\n now = global.performance.now.bind(global.performance);\n} catch (err) {\n logger.debug('Unable to use Performance API on this environment');\n now = global.Date.now;\n}\n\nclass DemuxerInline {\n constructor (observer, typeSupported, config, vendor) {\n this.observer = observer;\n this.typeSupported = typeSupported;\n this.config = config;\n this.vendor = vendor;\n }\n\n destroy () {\n let demuxer = this.demuxer;\n if (demuxer) {\n demuxer.destroy();\n }\n }\n\n push (data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {\n if ((data.byteLength > 0) && (decryptdata != null) && (decryptdata.key != null) && (decryptdata.method === 'AES-128')) {\n let decrypter = this.decrypter;\n if (decrypter == null) {\n decrypter = this.decrypter = new Decrypter(this.observer, this.config);\n }\n\n const startTime = now();\n decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, (decryptedData) => {\n const endTime = now();\n this.observer.trigger(Event.FRAG_DECRYPTED, { stats: { tstart: startTime, tdecrypt: endTime } });\n this.pushDecrypted(new Uint8Array(decryptedData), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);\n });\n } else {\n this.pushDecrypted(new Uint8Array(data), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);\n }\n }\n\n pushDecrypted (data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {\n let demuxer = this.demuxer;\n if (!demuxer ||\n // in case of continuity change, or track switch\n // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)\n // so let's check that current demuxer is still valid\n ((discontinuity || trackSwitch) && !this.probe(data))) {\n const observer = this.observer;\n const typeSupported = this.typeSupported;\n const config = this.config;\n // probing order is TS/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 for (let i = 0, len = muxConfig.length; i < len; i++) {\n const mux = muxConfig[i];\n const probe = mux.demux.probe;\n if (probe(data)) {\n const remuxer = this.remuxer = new mux.remux(observer, config, typeSupported, this.vendor);\n demuxer = new mux.demux(observer, remuxer, config, typeSupported);\n this.probe = probe;\n break;\n }\n }\n if (!demuxer) {\n observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found' });\n return;\n }\n this.demuxer = demuxer;\n }\n const remuxer = this.remuxer;\n\n if (discontinuity || trackSwitch) {\n demuxer.resetInitSegment(initSegment, audioCodec, videoCodec, duration);\n remuxer.resetInitSegment();\n }\n if (discontinuity) {\n demuxer.resetTimeStamp(defaultInitPTS);\n remuxer.resetTimeStamp(defaultInitPTS);\n }\n if (typeof demuxer.setDecryptData === 'function') {\n demuxer.setDecryptData(decryptdata);\n }\n\n demuxer.append(data, timeOffset, contiguous, accurateTimeOffset);\n }\n}\n\nexport default DemuxerInline;\n","/**\n * 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<T extends LoaderContext>{\n onSuccess: LoaderOnSuccess<T>,\n onError: LoaderOnError<T>,\n onTimeout: LoaderOnTimeout<T>,\n onProgress?: LoaderOnProgress<T>,\n}\n\nexport interface Loader<T extends LoaderContext> {\n destroy(): void\n abort(): void\n load(\n context: LoaderContext,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks<T>,\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<PlaylistLoaderContext>\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<ElementaryStreamTypes, boolean> = {\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<string[]> = [];\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 && 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]+)/g;\nconst MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;\n\nconst LEVEL_PLAYLIST_REGEX_FAST = new RegExp([\n /#EXTINF:\\s*(\\d*(?:\\.\\d+)?)(?:,(.*)\\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title\n /|(?!#)([\\S+ ?]+)/.source, // segment URI, group 3 => the URI (note newline is not eaten)\n /|#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)\n /|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec\n /|#.*/.source // All other non-segment oriented tags will match with all groups empty\n].join(''), 'g');\n\nconst LEVEL_PLAYLIST_REGEX_SLOW = /(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\\d+))|(?:#EXT-X-(TARGETDURATION): *(\\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)([^:]*):(.*))|(?:(#)(.*))(?:.*)\\r?\\n?/;\n\nconst MP4_REGEX_SUFFIX = /\\.(mp4|m4s|m4v|m4a)$/i;\n\nexport default class M3U8Parser {\n static findGroup (groups: 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 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 // 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 }\n return levels;\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 id: id++,\n groupId: attrs['GROUP-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/draft-pantos-http-live-streaming-08#section-3.4.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\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 && 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 = 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\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 });\n }\n }\n\n hls.trigger(Event.MANIFEST_LOADED, {\n levels,\n audioTracks,\n subtitles,\n url,\n stats,\n networkDetails\n });\n }\n\n _handleTrackOrLevelPlaylist (response: 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 // 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 });\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 let fragmentTimes, time;\n // Check if any flagged fragments have been unloaded\n Object.keys(this.fragments).forEach(key => {\n const fragmentEntity = this.fragments[key];\n if (fragmentEntity.buffered === true) {\n const esData = fragmentEntity.range[elementaryStream];\n if (esData) {\n fragmentTimes = esData.time;\n for (let i = 0; i < fragmentTimes.length; i++) {\n time = fragmentTimes[i];\n\n if (this.isTimeBuffered(time.startPTS, time.endPTS, timeRange) === false) {\n // Unregister partial fragment as it needs to load again to be reused\n this.removeFragment(fragmentEntity.body);\n break;\n }\n }\n }\n }\n });\n }\n\n /**\n * Checks if the fragment passed in is loaded in the buffer properly\n * Partially loaded fragments will be registered as a partial fragment\n * @param {Object} fragment Check the fragment against all sourceBuffers loaded\n */\n detectPartialFragments (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = this.fragments[fragKey];\n if (fragmentEntity) {\n fragmentEntity.buffered = true;\n\n Object.keys(this.timeRanges).forEach(elementaryStream => {\n if (fragment.hasElementaryStream(elementaryStream)) {\n let timeRange = this.timeRanges[elementaryStream];\n // Check for malformed fragments\n // Gaps need to be calculated for each elementaryStream\n fragmentEntity.range[elementaryStream] = this.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange);\n }\n });\n }\n }\n\n getBufferedTimes (startPTS, endPTS, timeRange) {\n let fragmentTimes = [];\n let startTime, endTime;\n let fragmentPartial = false;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n // Fragment is entirely contained in buffer\n // No need to check the other timeRange times since it's completely playable\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n break;\n } else if (startPTS < endTime && endPTS > startTime) {\n // Check for intersection with buffer\n // Get playable sections of the fragment\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n fragmentPartial = true;\n } else if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n break;\n }\n }\n\n return {\n time: fragmentTimes,\n partial: fragmentPartial\n };\n }\n\n getFragmentKey (fragment) {\n return `${fragment.type}_${fragment.level}_${fragment.urlId}_${fragment.sn}`;\n }\n\n /**\n * Gets the partial fragment for a certain time\n * @param {Number} time\n * @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment\n */\n getPartialFragment (time) {\n let timePadding, startTime, endTime;\n let bestFragment = null;\n let bestOverlap = 0;\n Object.keys(this.fragments).forEach(key => {\n const fragmentEntity = this.fragments[key];\n if (this.isPartial(fragmentEntity)) {\n startTime = fragmentEntity.body.startPTS - this.bufferPadding;\n endTime = fragmentEntity.body.endPTS + this.bufferPadding;\n if (time >= startTime && time <= endTime) {\n // Use the fragment that has the most padding from start and end time\n timePadding = Math.min(time - startTime, endTime - time);\n if (bestOverlap <= timePadding) {\n bestFragment = fragmentEntity.body;\n bestOverlap = timePadding;\n }\n }\n }\n });\n return bestFragment;\n }\n\n /**\n * @param {Object} fragment The fragment to check\n * @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded\n */\n getState (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = this.fragments[fragKey];\n let state = FragmentState.NOT_LOADED;\n\n if (fragmentEntity !== undefined) {\n if (!fragmentEntity.buffered) {\n state = FragmentState.APPENDING;\n } else if (this.isPartial(fragmentEntity) === true) {\n state = FragmentState.PARTIAL;\n } else {\n state = FragmentState.OK;\n }\n }\n\n return state;\n }\n\n isPartial (fragmentEntity) {\n return fragmentEntity.buffered === true &&\n ((fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true) ||\n (fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true));\n }\n\n isTimeBuffered (startPTS, endPTS, timeRange) {\n let startTime, endTime;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n return true;\n }\n\n if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n return false;\n }\n }\n\n return false;\n }\n\n /**\n * Fires when a fragment loading is completed\n */\n onFragLoaded (e) {\n const fragment = e.frag;\n // don't track initsegment (for which sn is not a number)\n // don't track frags used for bitrateTest, they're irrelevant.\n if (!Number.isFinite(fragment.sn) || fragment.bitrateTest) {\n return;\n }\n\n this.fragments[this.getFragmentKey(fragment)] = {\n body: fragment,\n range: Object.create(null),\n buffered: false\n };\n }\n\n /**\n * Fires when the buffer is updated\n */\n onBufferAppended (e) {\n // Store the latest timeRanges loaded in the buffer\n this.timeRanges = e.timeRanges;\n Object.keys(this.timeRanges).forEach(elementaryStream => {\n let timeRange = this.timeRanges[elementaryStream];\n this.detectEvictedFragments(elementaryStream, timeRange);\n });\n }\n\n /**\n * Fires after a fragment has been loaded into the source buffer\n */\n onFragBuffered (e) {\n this.detectPartialFragments(e.frag);\n }\n\n /**\n * Return true if fragment tracker has the fragment.\n * @param {Object} fragment\n * @returns {boolean}\n */\n hasFragment (fragment) {\n const fragKey = this.getFragmentKey(fragment);\n return this.fragments[fragKey] !== undefined;\n }\n\n /**\n * Remove a fragment from fragment tracker until it is loaded again\n * @param {Object} fragment The fragment to remove\n */\n removeFragment (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n delete this.fragments[fragKey];\n }\n\n /**\n * Remove all fragments from fragment tracker.\n */\n removeAllFragments () {\n this.fragments = Object.create(null);\n }\n}\n","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 fragTo.start = fragFrom.start + fragFrom.duration;\n } else {\n fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);\n }\n }\n}\n\nexport function updateFragPTSDTS (details, frag, startPTS, endPTS, startDTS, endDTS) {\n // update frag PTS/DTS\n let maxStartPTS = startPTS;\n if (Number.isFinite(frag.startPTS)) {\n // delta PTS between audio and video\n let deltaPTS = Math.abs(frag.startPTS - startPTS);\n if (!Number.isFinite(frag.deltaPTS)) {\n frag.deltaPTS = deltaPTS;\n } else {\n frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);\n }\n\n maxStartPTS = Math.max(startPTS, frag.startPTS);\n startPTS = Math.min(startPTS, frag.startPTS);\n endPTS = Math.max(endPTS, frag.endPTS);\n startDTS = Math.min(startDTS, frag.startDTS);\n endDTS = Math.max(endDTS, frag.endDTS);\n }\n\n const drift = startPTS - frag.start;\n frag.start = frag.startPTS = startPTS;\n frag.maxStartPTS = maxStartPTS;\n frag.endPTS = endPTS;\n frag.startDTS = startDTS;\n frag.endDTS = endDTS;\n frag.duration = endPTS - startPTS;\n\n const sn = frag.sn;\n // exit if sn out of range\n if (!details || sn < details.startSN || sn > details.endSN) {\n return 0;\n }\n\n let fragIdx, fragments, i;\n fragIdx = sn - details.startSN;\n fragments = details.fragments;\n // update frag reference in fragments array\n // rationale is that fragments array might not contain this frag object.\n // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()\n // if we don't update frag, we won't be able to propagate PTS info on the playlist\n // resulting in invalid sliding computation\n fragments[fragIdx] = frag;\n // adjust fragment PTS/duration from seqnum-1 to frag 0\n for (i = fragIdx; i > 0; i--) {\n updatePTS(fragments, i, i - 1);\n }\n\n // adjust fragment PTS/duration from seqnum to last frag\n for (i = fragIdx; i < fragments.length - 1; i++) {\n updatePTS(fragments, i, i + 1);\n }\n\n details.PTSKnown = true;\n return drift;\n}\n\nexport function mergeDetails (oldDetails, newDetails) {\n // potentially retrieve cached initsegment\n if (newDetails.initSegment && oldDetails.initSegment) {\n newDetails.initSegment = oldDetails.initSegment;\n }\n\n // check if old/new playlists have fragments in common\n // loop through overlapping SN and update startPTS , cc, and duration if any found\n let ccOffset = 0;\n let PTSFrag;\n mapFragmentIntersection(oldDetails, newDetails, (oldFrag, newFrag) => {\n ccOffset = oldFrag.cc - newFrag.cc;\n if (Number.isFinite(oldFrag.startPTS)) {\n newFrag.start = newFrag.startPTS = oldFrag.startPTS;\n newFrag.endPTS = oldFrag.endPTS;\n newFrag.duration = oldFrag.duration;\n newFrag.backtracked = oldFrag.backtracked;\n newFrag.dropped = oldFrag.dropped;\n PTSFrag = newFrag;\n }\n // PTS is known when there are overlapping segments\n newDetails.PTSKnown = true;\n });\n\n if (!newDetails.PTSKnown) {\n return;\n }\n\n if (ccOffset) {\n logger.log('discontinuity sliding from playlist, take drift into account');\n const newFragments = newDetails.fragments;\n for (let i = 0; i < newFragments.length; i++) {\n newFragments[i].cc += ccOffset;\n }\n }\n\n // if at least one fragment contains PTS info, recompute PTS information for all fragments\n if (PTSFrag) {\n updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);\n } else {\n // ensure that delta is within oldFragments range\n // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])\n // in that case we also need to adjust start offset of all fragments\n adjustSliding(oldDetails, newDetails);\n }\n // if we are here, it means we have fragments overlapping between\n // old and new level. reliable PTS info is thus relying on old level\n newDetails.PTSKnown = oldDetails.PTSKnown;\n}\n\nexport function mergeSubtitlePlaylists (oldPlaylist, newPlaylist, referenceStart = 0) {\n let lastIndex = -1;\n mapFragmentIntersection(oldPlaylist, newPlaylist, (oldFrag, newFrag, index) => {\n newFrag.start = oldFrag.start;\n lastIndex = index;\n });\n\n const frags = newPlaylist.fragments;\n if (lastIndex < 0) {\n frags.forEach(frag => {\n frag.start += referenceStart;\n });\n return;\n }\n\n for (let i = lastIndex + 1; i < frags.length; i++) {\n frags[i].start = (frags[i - 1].start + frags[i - 1].duration);\n }\n}\n\nexport function mapFragmentIntersection (oldPlaylist, newPlaylist, intersectionFn) {\n if (!oldPlaylist || !newPlaylist) {\n return;\n }\n\n const start = Math.max(oldPlaylist.startSN, newPlaylist.startSN) - newPlaylist.startSN;\n const end = Math.min(oldPlaylist.endSN, newPlaylist.endSN) - newPlaylist.startSN;\n const delta = newPlaylist.startSN - oldPlaylist.startSN;\n\n for (let i = start; i <= end; i++) {\n const oldFrag = oldPlaylist.fragments[delta + i];\n const newFrag = newPlaylist.fragments[i];\n if (!oldFrag || !newFrag) {\n break;\n }\n intersectionFn(oldFrag, newFrag, i);\n }\n}\n\nexport function adjustSliding (oldPlaylist, newPlaylist) {\n const delta = newPlaylist.startSN - oldPlaylist.startSN;\n const oldFragments = oldPlaylist.fragments;\n const newFragments = newPlaylist.fragments;\n\n if (delta < 0 || delta > oldFragments.length) {\n return;\n }\n for (let i = 0; i < newFragments.length; i++) {\n newFragments[i].start += oldFragments[delta].start;\n }\n}\n\nexport function computeReloadInterval (currentPlaylist, newPlaylist, lastRequestTime) {\n let reloadInterval = 1000 * (newPlaylist.averagetargetduration ? newPlaylist.averagetargetduration : newPlaylist.targetduration);\n const minReloadInterval = reloadInterval / 2;\n if (currentPlaylist && newPlaylist.endSN === currentPlaylist.endSN) {\n // follow HLS Spec, If the client reloads a Playlist file and finds that it has not\n // changed then it MUST wait for a period of one-half the target\n // duration before retrying.\n reloadInterval = minReloadInterval;\n }\n\n if (lastRequestTime) {\n reloadInterval = Math.max(minReloadInterval, reloadInterval - (window.performance.now() - lastRequestTime));\n }\n // in any case, don't reload more than half of target duration\n return Math.round(reloadInterval);\n}\n","/**\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 const fragNext = fragPrevious ? fragments[fragPrevious.sn as number - (fragments[0].sn as number) + 1] : null;\n // Prefer the next fragment if it's within tolerance\n if (fragNext && !fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext)) {\n return fragNext;\n }\n return BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));\n}\n\n/**\n * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.\n * @param {*} candidate - The fragment to test\n * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within\n * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {number} - 0 if it matches, 1 if too low, -1 if too high\n */\nexport function fragmentWithinToleranceTest (bufferEnd = 0, maxFragLookUpTolerance = 0, candidate: 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 || nextStart - currentTime > MAX_START_GAP_JUMP;\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 if (startJump > 0 && startJump <= MAX_START_GAP_JUMP) {\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`);\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 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","import TaskLoop from '../task-loop';\nimport { FragmentState } from './fragment-tracker';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport { logger } from '../utils/logger';\n\nexport const State = {\n STOPPED: 'STOPPED',\n STARTING: 'STARTING',\n IDLE: 'IDLE',\n PAUSED: 'PAUSED',\n KEY_LOADING: 'KEY_LOADING',\n FRAG_LOADING: 'FRAG_LOADING',\n FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',\n WAITING_TRACK: 'WAITING_TRACK',\n PARSING: 'PARSING',\n PARSED: 'PARSED',\n BUFFER_FLUSHING: 'BUFFER_FLUSHING',\n ENDED: 'ENDED',\n ERROR: 'ERROR',\n WAITING_INIT_PTS: 'WAITING_INIT_PTS',\n WAITING_LEVEL: 'WAITING_LEVEL'\n};\n\nexport default class BaseStreamController extends TaskLoop {\n doTick () {}\n\n startLoad () {}\n\n stopLoad () {\n let frag = this.fragCurrent;\n if (frag) {\n if (frag.loader) {\n frag.loader.abort();\n }\n this.fragmentTracker.removeFragment(frag);\n }\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n this.fragCurrent = null;\n this.fragPrevious = null;\n this.clearInterval();\n this.clearNextTick();\n this.state = State.STOPPED;\n }\n\n _streamEnded (bufferInfo, levelDetails) {\n const { fragCurrent, fragmentTracker } = this;\n // we just got done loading the final fragment and there is no other buffered range after ...\n // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between\n // so we should not switch to ENDED in that case, to be able to buffer them\n // dont switch to ENDED if we need to backtrack last fragment\n if (!levelDetails.live && fragCurrent && !fragCurrent.backtracked && fragCurrent.sn === levelDetails.endSN && !bufferInfo.nextStart) {\n const fragState = fragmentTracker.getState(fragCurrent);\n return fragState === FragmentState.PARTIAL || fragState === FragmentState.OK;\n }\n return false;\n }\n\n onMediaSeeking () {\n const { config, media, mediaBuffer, state } = this;\n const currentTime = media ? media.currentTime : null;\n const bufferInfo = BufferHelper.bufferInfo(mediaBuffer || media, currentTime, this.config.maxBufferHole);\n\n if (Number.isFinite(currentTime)) {\n logger.log(`media seeking to ${currentTime.toFixed(3)}`);\n }\n\n if (state === State.FRAG_LOADING) {\n let fragCurrent = this.fragCurrent;\n // check if we are seeking to a unbuffered area AND if frag loading is in progress\n if (bufferInfo.len === 0 && fragCurrent) {\n const tolerance = config.maxFragLookUpTolerance;\n const fragStartOffset = fragCurrent.start - tolerance;\n const fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;\n // check if we seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything\n if (currentTime < fragStartOffset || currentTime > fragEndOffset) {\n if (fragCurrent.loader) {\n logger.log('seeking outside of buffer while fragment load in progress, cancel fragment load');\n fragCurrent.loader.abort();\n }\n this.fragCurrent = null;\n this.fragPrevious = null;\n // switch to IDLE state to load new fragment\n this.state = State.IDLE;\n } else {\n logger.log('seeking outside of buffer but within currently loaded fragment range');\n }\n }\n } else if (state === State.ENDED) {\n // if seeking to unbuffered area, clean up fragPrevious\n if (bufferInfo.len === 0) {\n this.fragPrevious = null;\n this.fragCurrent = null;\n }\n\n // switch to IDLE state to check for potential new fragment\n this.state = State.IDLE;\n }\n if (media) {\n this.lastCurrentTime = currentTime;\n }\n\n // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target\n if (!this.loadedmetadata) {\n this.nextLoadPosition = this.startPosition = currentTime;\n }\n\n // tick to speed up processing\n this.tick();\n }\n\n onMediaEnded () {\n // reset startPosition and lastCurrentTime to restart playback @ stream beginning\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n onHandlerDestroying () {\n this.stopLoad();\n super.onHandlerDestroying();\n }\n\n onHandlerDestroyed () {\n this.state = State.STOPPED;\n this.fragmentTracker = null;\n }\n\n 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 from './gap-controller';\nimport BaseStreamController, { State } from './base-stream-controller';\n\nconst TICK_INTERVAL = 100; // how often to tick in ms\n\nclass StreamController extends BaseStreamController {\n constructor (hls, fragmentTracker) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.MANIFEST_LOADING,\n Event.MANIFEST_PARSED,\n Event.LEVEL_LOADED,\n Event.KEY_LOADED,\n Event.FRAG_LOADED,\n Event.FRAG_LOAD_EMERGENCY_ABORTED,\n Event.FRAG_PARSING_INIT_SEGMENT,\n Event.FRAG_PARSING_DATA,\n Event.FRAG_PARSED,\n Event.ERROR,\n Event.AUDIO_TRACK_SWITCHING,\n Event.AUDIO_TRACK_SWITCHED,\n Event.BUFFER_CREATED,\n Event.BUFFER_APPENDED,\n Event.BUFFER_FLUSHED);\n\n this.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.audioCodecSwap = false;\n this._state = State.STOPPED;\n this.stallReported = false;\n this.gapController = null;\n this.altAudio = 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 // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level\n startLevel = 0;\n this.bitrateTest = true;\n }\n // set new level to playlist loader : this will trigger start level load\n // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded\n this.level = hls.nextLoadLevel = startLevel;\n this.loadedmetadata = false;\n }\n // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime\n if (lastCurrentTime > 0 && startPosition === -1) {\n logger.log(`override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);\n startPosition = lastCurrentTime;\n }\n this.state = State.IDLE;\n this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;\n this.tick();\n } else {\n this.forceStartLoad = true;\n this.state = State.STOPPED;\n }\n }\n\n stopLoad () {\n this.forceStartLoad = false;\n super.stopLoad();\n }\n\n doTick () {\n switch (this.state) {\n case State.BUFFER_FLUSHING:\n // in buffer flushing state, reset fragLoadError counter\n this.fragLoadError = 0;\n break;\n case State.IDLE:\n this._doTickIdle();\n break;\n case State.WAITING_LEVEL:\n var level = this.levels[this.level];\n // check if playlist is already loaded\n if (level && level.details) {\n this.state = State.IDLE;\n }\n\n break;\n case State.FRAG_LOADING_WAITING_RETRY:\n var now = window.performance.now();\n var retryDate = this.retryDate;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if (!retryDate || (now >= retryDate) || (this.media && this.media.seeking)) {\n logger.log('mediaController: retryDate reached, switch back to IDLE state');\n this.state = State.IDLE;\n }\n break;\n case State.ERROR:\n case State.STOPPED:\n case State.FRAG_LOADING:\n case State.PARSING:\n case State.PARSED:\n case State.ENDED:\n break;\n default:\n break;\n }\n // check buffer\n this._checkBuffer();\n // check/update current fragment\n this._checkFragmentChanged();\n }\n\n // Ironically the \"idle\" state is the on we do the most logic in it seems ....\n // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently\n // played segment, or on pause/play/seek instead of naively checking every 100ms?\n _doTickIdle () {\n const hls = this.hls,\n config = hls.config,\n media = this.media;\n\n // if start level not parsed yet OR\n // if video not attached AND start fragment already requested OR start frag prefetch disable\n // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment\n if (this.levelLastLoaded === undefined || (\n !media && (this.startFragRequested || !config.startFragPrefetch))) {\n return;\n }\n\n // if we have not yet loaded any fragment, start loading from start position\n let pos;\n if (this.loadedmetadata) {\n pos = media.currentTime;\n } else {\n pos = this.nextLoadPosition;\n }\n\n // determine next load level\n let level = hls.nextLoadLevel,\n levelInfo = this.levels[level];\n\n if (!levelInfo) {\n return;\n }\n\n let levelBitrate = levelInfo.bitrate,\n maxBufLen;\n\n // compute max Buffer Length that we could get from this load level, based on level bitrate.\n if (levelBitrate) {\n maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);\n } else {\n maxBufLen = config.maxBufferLength;\n }\n\n maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength);\n\n // determine next candidate fragment to be loaded, based on current position and end of buffer position\n // ensure up to `config.maxMaxBufferLength` of buffer upfront\n\n const bufferInfo = BufferHelper.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, config.maxBufferHole),\n bufferLen = bufferInfo.len;\n // Stay idle if we are still with buffer margins\n if (bufferLen >= maxBufLen) {\n return;\n }\n\n // if buffer length is less than maxBufLen try to load a new fragment ...\n logger.trace(`buffer length of ${bufferLen.toFixed(3)} is below max of ${maxBufLen.toFixed(3)}. checking for more payload ...`);\n\n // set next load level : this will trigger a playlist load if needed\n this.level = hls.nextLoadLevel = level;\n\n const levelDetails = levelInfo.details;\n // if level info not retrieved yet, switch state and wait for level retrieval\n // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load\n // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)\n if (!levelDetails || (levelDetails.live && this.levelLastLoaded !== level)) {\n this.state = State.WAITING_LEVEL;\n return;\n }\n\n if (this._streamEnded(bufferInfo, levelDetails)) {\n const data = {};\n if (this.altAudio) {\n data.type = 'video';\n }\n\n this.hls.trigger(Event.BUFFER_EOS, data);\n this.state = State.ENDED;\n return;\n }\n // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)\n this._fetchPayloadOrEos(pos, bufferInfo, levelDetails);\n }\n\n _fetchPayloadOrEos (pos, bufferInfo, levelDetails) {\n const fragPrevious = this.fragPrevious,\n level = this.level,\n fragments = levelDetails.fragments,\n fragLen = fragments.length;\n\n // empty playlist\n if (fragLen === 0) {\n return;\n }\n\n // find fragment index, contiguous with end of buffer position\n let start = fragments[0].start,\n end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,\n bufferEnd = bufferInfo.end,\n frag;\n\n if (levelDetails.initSegment && !levelDetails.initSegment.data) {\n frag = levelDetails.initSegment;\n } else {\n // in case of live playlist we need to ensure that requested position is not located before playlist start\n if (levelDetails.live) {\n let initialLiveManifestSize = this.config.initialLiveManifestSize;\n if (fragLen < initialLiveManifestSize) {\n logger.warn(`Can not start playback of a level, reason: not enough fragments ${fragLen} < ${initialLiveManifestSize}`);\n return;\n }\n\n frag = this._ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen);\n // if it explicitely returns null don't load any fragment and exit function now\n if (frag === null) {\n return;\n }\n } else {\n // VoD playlist: if bufferEnd before start of playlist, load first fragment\n if (bufferEnd < start) {\n frag = fragments[0];\n }\n }\n }\n if (!frag) {\n frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails);\n }\n\n if (frag) {\n if (frag.encrypted) {\n logger.log(`Loading key for ${frag.sn} of [${levelDetails.startSN} ,${levelDetails.endSN}],level ${level}`);\n this._loadKey(frag);\n } else {\n logger.log(`Loading ${frag.sn} of [${levelDetails.startSN} ,${levelDetails.endSN}],level ${level}, currentTime:${pos.toFixed(3)},bufferEnd:${bufferEnd.toFixed(3)}`);\n this._loadFragment(frag);\n }\n }\n }\n\n _ensureFragmentAtLivePoint (levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen) {\n const config = this.hls.config, media = this.media;\n\n let frag;\n\n // check if requested position is within seekable boundaries :\n // logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);\n let maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;\n\n if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {\n let liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);\n bufferEnd = liveSyncPosition;\n if (media && !media.paused && media.readyState && media.duration > liveSyncPosition && liveSyncPosition > media.currentTime) {\n logger.log(`buffer end: ${bufferEnd.toFixed(3)} is located too far from the end of live sliding playlist, reset currentTime to : ${liveSyncPosition.toFixed(3)}`);\n media.currentTime = liveSyncPosition;\n }\n\n this.nextLoadPosition = liveSyncPosition;\n }\n\n // if end of buffer greater than live edge, don't load any fragment\n // this could happen if live playlist intermittently slides in the past.\n // level 1 loaded [182580161,182580167]\n // level 1 loaded [182580162,182580169]\n // Loading 182580168 of [182580162 ,182580169],level 1 ..\n // Loading 182580169 of [182580162 ,182580169],level 1 ..\n // level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168\n // level 1 loaded [182580164,182580171]\n //\n // don't return null in case media not loaded yet (readystate === 0)\n if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) {\n return null;\n }\n\n if (this.startFragRequested && !levelDetails.PTSKnown) {\n /* we are switching level on live playlist, but we don't have any PTS info for that quality level ...\n try to load frag matching with next SN.\n even if SN are not synchronized between playlists, loading this frag will help us\n compute playlist sliding and find the right one after in case it was not the right consecutive one */\n if (fragPrevious) {\n if (levelDetails.hasProgramDateTime) {\n // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)\n logger.log(`live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`);\n frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, config.maxFragLookUpTolerance);\n } else {\n // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n const targetSN = fragPrevious.sn + 1;\n if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {\n const fragNext = fragments[targetSN - levelDetails.startSN];\n if (fragPrevious.cc === fragNext.cc) {\n frag = fragNext;\n logger.log(`live playlist, switching playlist, load frag with next SN: ${frag.sn}`);\n }\n }\n // next frag SN not available (or not with same continuity counter)\n // look for a frag sharing the same CC\n if (!frag) {\n frag = BinarySearch.search(fragments, function (frag) {\n return fragPrevious.cc - frag.cc;\n });\n if (frag) {\n logger.log(`live playlist, switching playlist, load frag with same CC: ${frag.sn}`);\n }\n }\n }\n }\n if (!frag) {\n /* we have no idea about which fragment should be loaded.\n so let's load mid fragment. it will help computing playlist sliding and find the right one\n */\n frag = fragments[Math.min(fragLen - 1, Math.round(fragLen / 2))];\n logger.log(`live playlist, switching playlist, unknown, load middle frag : ${frag.sn}`);\n }\n }\n\n return frag;\n }\n\n _findFragment (start, 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 logger.log(`Re-loading fragment with SN: ${fragNextLoad.sn}`);\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) {\n this.state = State.KEY_LOADING;\n this.hls.trigger(Event.KEY_LOADING, { frag });\n }\n\n _loadFragment (frag) {\n // Check if fragment is not loaded\n let fragState = this.fragmentTracker.getState(frag);\n\n this.fragCurrent = frag;\n 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 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 media.pause();\n } else {\n // don't restart playback after instant level switch in case media not attached\n previouslyPaused = true;\n }\n this.previouslyPaused = previouslyPaused;\n }\n let fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\n\n this.fragCurrent = null;\n // flush everything\n this.flushMainBuffer(0, Number.POSITIVE_INFINITY);\n }\n\n /**\n * on immediate level switch end, after new fragment has been buffered:\n * - nudge video decoder by slightly adjusting video currentTime (if currentTime buffered)\n * - resume the playback if needed\n */\n immediateLevelSwitchEnd () {\n const media = this.media;\n if (media && media.buffered.length) {\n this.immediateSwitch = false;\n if (BufferHelper.isBuffered(media, media.currentTime)) {\n // only nudge if currentTime is buffered\n media.currentTime -= 0.0001;\n }\n if (!this.previouslyPaused) {\n media.play();\n }\n }\n }\n\n /**\n * try to switch ASAP without breaking video playback:\n * in order to ensure smooth but quick level switching,\n * we need to find the next flushable buffer range\n * we should take into account new segment fetch time\n */\n nextLevelSwitch () {\n const media = this.media;\n // ensure that media is defined and that metadata are available (to retrieve currentTime)\n if (media && media.readyState) {\n let fetchdelay, fragPlayingCurrent, nextBufferedFrag;\n fragPlayingCurrent = this.getBufferedFrag(media.currentTime);\n if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 1) {\n // flush buffer preceding current fragment (flush until current fragment start offset)\n // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...\n this.flushMainBuffer(0, fragPlayingCurrent.startPTS - 1);\n }\n if (!media.paused) {\n // add a safety delay of 1s\n let nextLevelId = this.hls.nextLoadLevel, nextLevel = this.levels[nextLevelId], fragLastKbps = this.fragLastKbps;\n if (fragLastKbps && this.fragCurrent) {\n fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;\n } else {\n fetchdelay = 0;\n }\n } else {\n fetchdelay = 0;\n }\n // logger.log('fetchdelay:'+fetchdelay);\n // find buffer range that will be reached once new fragment will be fetched\n nextBufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);\n if (nextBufferedFrag) {\n // we can flush buffer range following this one without stalling playback\n nextBufferedFrag = this.followingBufferedFrag(nextBufferedFrag);\n if (nextBufferedFrag) {\n // if we are here, we can also cancel any loading/demuxing in progress, as they are useless\n let fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\n\n this.fragCurrent = null;\n // start flush position is the start PTS of next buffered frag.\n // we use frag.naxStartPTS which is max(audio startPTS, video startPTS).\n // in case there is a small PTS Delta between audio and video, using maxStartPTS avoids flushing last samples from current fragment\n this.flushMainBuffer(nextBufferedFrag.maxStartPTS, Number.POSITIVE_INFINITY);\n }\n }\n }\n }\n\n flushMainBuffer (startOffset, endOffset) {\n this.state = State.BUFFER_FLUSHING;\n let flushScope = { startOffset: startOffset, endOffset: endOffset };\n // if alternate audio tracks are used, only flush video, otherwise flush everything\n if (this.altAudio) {\n flushScope.type = 'video';\n }\n\n this.hls.trigger(Event.BUFFER_FLUSHING, flushScope);\n }\n\n onMediaAttached (data) {\n let media = this.media = this.mediaBuffer = data.media;\n this.onvseeking = this.onMediaSeeking.bind(this);\n this.onvseeked = this.onMediaSeeked.bind(this);\n this.onvended = this.onMediaEnded.bind(this);\n media.addEventListener('seeking', this.onvseeking);\n media.addEventListener('seeked', this.onvseeked);\n media.addEventListener('ended', this.onvended);\n let config = this.config;\n if (this.levels && config.autoStartLoad) {\n this.hls.startLoad(config.startPosition);\n }\n\n this.gapController = new GapController(config, media, this.fragmentTracker, this.hls);\n }\n\n onMediaDetaching () {\n let media = this.media;\n if (media && media.ended) {\n logger.log('MSE detaching and video ended, reset startPosition');\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n // reset fragment backtracked flag\n let levels = this.levels;\n if (levels) {\n levels.forEach(level => {\n if (level.details) {\n level.details.fragments.forEach(fragment => {\n fragment.backtracked = undefined;\n });\n }\n });\n }\n\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 batck to IDLE state if we were waiting for level to start downloading a new fragment\n if (this.state === State.WAITING_LEVEL) {\n this.state = State.IDLE;\n }\n\n // trigger handler right now\n this.tick();\n }\n\n onKeyLoaded () {\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n this.tick();\n }\n }\n\n onFragLoaded (data) {\n const { fragCurrent, hls, levels, media } = this;\n const fragLoaded = data.frag;\n if (this.state === State.FRAG_LOADING &&\n fragCurrent &&\n fragLoaded.type === 'main' &&\n fragLoaded.level === fragCurrent.level &&\n fragLoaded.sn === fragCurrent.sn) {\n const stats = data.stats;\n const currentLevel = levels[fragCurrent.level];\n const details = currentLevel.details;\n // reset frag bitrate test in any case after frag loaded event\n // if this frag was loaded to perform a bitrate test AND if hls.nextLoadLevel is greater than 0\n // then this means that we should be able to load a fragment at a higher quality level\n this.bitrateTest = false;\n this.stats = stats;\n\n logger.log(`Loaded ${fragCurrent.sn} of [${details.startSN} ,${details.endSN}],level ${fragCurrent.level}`);\n if (fragLoaded.bitrateTest && hls.nextLoadLevel) {\n // switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo\n this.state = State.IDLE;\n this.startFragRequested = false;\n stats.tparsed = stats.tbuffered = window.performance.now();\n hls.trigger(Event.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });\n this.tick();\n } else if (fragLoaded.sn === 'initSegment') {\n this.state = State.IDLE;\n stats.tparsed = stats.tbuffered = window.performance.now();\n details.initSegment.data = data.payload;\n hls.trigger(Event.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });\n this.tick();\n } else {\n logger.log(`Parsing ${fragCurrent.sn} of [${details.startSN} ,${details.endSN}],level ${fragCurrent.level}, cc ${fragCurrent.cc}`);\n this.state = State.PARSING;\n this.pendingBuffering = true;\n this.appended = false;\n\n // Bitrate test frags are not usually buffered so the fragment tracker ignores them. If Hls.js decides to buffer\n // it (and therefore ends up at this line), then the fragment tracker needs to be manually informed.\n if (fragLoaded.bitrateTest) {\n fragLoaded.bitrateTest = false;\n this.fragmentTracker.onFragLoaded({\n frag: fragLoaded\n });\n }\n\n // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) and if media is not seeking (this is to overcome potential timestamp drifts between playlists and fragments)\n const accurateTimeOffset = !(media && media.seeking) && (details.PTSKnown || !details.live);\n const initSegmentData = details.initSegment ? details.initSegment.data : [];\n const audioCodec = this._getAudioCodec(currentLevel);\n\n // transmux the MPEG-TS data to ISO-BMFF segments\n const demuxer = this.demuxer = this.demuxer || new Demuxer(this.hls, 'main');\n demuxer.push(\n data.payload,\n initSegmentData,\n audioCodec,\n currentLevel.videoCodec,\n fragCurrent,\n details.totalduration,\n accurateTimeOffset\n );\n }\n }\n this.fragLoadError = 0;\n }\n\n onFragParsingInitSegment (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n let tracks = data.tracks, trackName, track;\n\n // if audio track is expected to come from audio stream controller, discard any coming from main\n if (tracks.audio && this.altAudio) {\n delete tracks.audio;\n }\n\n // include levelCodec in audio and video tracks\n track = tracks.audio;\n if (track) {\n let audioCodec = this.levels[this.level].audioCodec,\n ua = navigator.userAgent.toLowerCase();\n if (audioCodec && this.audioCodecSwap) {\n logger.log('swapping playlist audio codec');\n if (audioCodec.indexOf('mp4a.40.5') !== -1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n // in case AAC and HE-AAC audio codecs are signalled in manifest\n // force HE-AAC , as it seems that most browsers prefers that way,\n // except for mono streams OR on FF\n // these conditions might need to be reviewed ...\n if (this.audioCodecSwitch) {\n // don't force HE-AAC if mono stream\n if (track.metadata.channelCount !== 1 &&\n // don't force HE-AAC if firefox\n ua.indexOf('firefox') === -1) {\n audioCodec = 'mp4a.40.5';\n }\n }\n // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise\n if (ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') { // Exclude mpeg audio\n audioCodec = 'mp4a.40.2';\n logger.log(`Android: force audio codec to ${audioCodec}`);\n }\n track.levelCodec = audioCodec;\n track.id = data.id;\n }\n track = tracks.video;\n if (track) {\n track.levelCodec = this.levels[this.level].videoCodec;\n track.id = data.id;\n }\n this.hls.trigger(Event.BUFFER_CODECS, tracks);\n // loop through tracks that are going to be provided to bufferController\n for (trackName in tracks) {\n track = tracks[trackName];\n logger.log(`main track:${trackName},container:${track.container},codecs[level/parsed]=[${track.levelCodec}/${track.codec}]`);\n let initSegment = track.initSegment;\n if (initSegment) {\n this.appended = true;\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n this.hls.trigger(Event.BUFFER_APPENDING, { type: trackName, data: initSegment, parent: 'main', content: 'initSegment' });\n }\n }\n // trigger handler right now\n this.tick();\n }\n }\n\n onFragParsingData (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n !(data.type === 'audio' && this.altAudio) && // filter out main audio if audio track is loaded through audio stream controller\n this.state === State.PARSING) {\n let level = this.levels[this.level],\n frag = fragCurrent;\n if (!Number.isFinite(data.endPTS)) {\n data.endPTS = data.startPTS + fragCurrent.duration;\n data.endDTS = data.startDTS + fragCurrent.duration;\n }\n\n if (data.hasAudio === true) {\n frag.addElementaryStream(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 this.tick();\n return;\n }\n } else {\n logger.warn('Already backtracked on this fragment, appending with the gap', frag.sn);\n }\n } else {\n // Only reset the backtracked flag if we've loaded the frag without any dropped frames\n frag.backtracked = false;\n }\n }\n\n let drift = LevelHelper.updateFragPTSDTS(level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS),\n hls = this.hls;\n hls.trigger(Event.LEVEL_PTS_UPDATED, { details: level.details, level: this.level, drift: drift, type: data.type, start: data.startPTS, end: data.endPTS });\n // has remuxer dropped video frames located before first keyframe ?\n [data.data1, data.data2].forEach(buffer => {\n // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)\n // in that case it is useless to append following segments\n if (buffer && buffer.length && this.state === State.PARSING) {\n this.appended = true;\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n hls.trigger(Event.BUFFER_APPENDING, { type: data.type, data: buffer, parent: 'main', content: 'data' });\n }\n });\n // trigger handler right now\n this.tick();\n }\n }\n\n onFragParsed (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n this.stats.tparsed = window.performance.now();\n this.state = State.PARSED;\n this._checkAppendedParsed();\n }\n }\n\n onAudioTrackSwitching (data) {\n // if any URL found on new audio track, it is an alternate audio track\n let altAudio = !!data.url,\n trackId = data.id;\n // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered\n // don't do anything if we switch to alt audio: audio stream controller is handling it.\n // we will just have to change buffer scheduling on audioTrackSwitched\n if (!altAudio) {\n if (this.mediaBuffer !== this.media) {\n logger.log('switching on main audio, use media.buffered to schedule main fragment loading');\n this.mediaBuffer = this.media;\n let fragCurrent = this.fragCurrent;\n // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch\n if (fragCurrent.loader) {\n logger.log('switching to main audio track, cancel main fragment load');\n fragCurrent.loader.abort();\n }\n this.fragCurrent = null;\n this.fragPrevious = null;\n // destroy demuxer to force init segment generation (following audio switch)\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n // switch to IDLE state to load new fragment\n this.state = State.IDLE;\n }\n let hls = this.hls;\n // switching to main audio, flush all audio and trigger track switched\n hls.trigger(Event.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, { id: trackId });\n this.altAudio = false;\n }\n }\n\n onAudioTrackSwitched (data) {\n let trackId = data.id,\n altAudio = !!this.hls.audioTracks[trackId].url;\n if (altAudio) {\n let videoBuffer = this.videoBuffer;\n // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered\n if (videoBuffer && this.mediaBuffer !== videoBuffer) {\n logger.log('switching on alternate audio, use video.buffered to schedule main fragment loading');\n this.mediaBuffer = videoBuffer;\n }\n }\n this.altAudio = altAudio;\n this.tick();\n }\n\n onBufferCreated (data) {\n let tracks = data.tracks, mediaTrack, name, alternate = false;\n for (let type in tracks) {\n let track = tracks[type];\n if (track.id === 'main') {\n name = type;\n mediaTrack = track;\n // keep video source buffer reference\n if (type === 'video') {\n this.videoBuffer = tracks[type].buffer;\n }\n } else {\n alternate = true;\n }\n }\n if (alternate && mediaTrack) {\n logger.log(`alternate track found, use ${name}.buffered to schedule main fragment loading`);\n this.mediaBuffer = mediaTrack.buffer;\n } else {\n this.mediaBuffer = this.media;\n }\n }\n\n onBufferAppended (data) {\n if (data.parent === 'main') {\n const state = this.state;\n if (state === State.PARSING || state === State.PARSED) {\n // check if all buffers have been appended\n this.pendingBuffering = (data.pending > 0);\n this._checkAppendedParsed();\n }\n }\n }\n\n _checkAppendedParsed () {\n // trigger handler right now\n if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {\n const frag = this.fragCurrent;\n if (frag) {\n const media = this.mediaBuffer ? this.mediaBuffer : this.media;\n logger.log(`main buffered : ${TimeRanges.toString(media.buffered)}`);\n this.fragPrevious = frag;\n const stats = this.stats;\n stats.tbuffered = window.performance.now();\n // we should get rid of this.fragLastKbps\n this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst));\n this.hls.trigger(Event.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'main' });\n this.state = State.IDLE;\n }\n this.tick();\n }\n }\n\n onError (data) {\n let frag = data.frag || this.fragCurrent;\n // don't handle frag error not related to main fragment\n if (frag && frag.type !== 'main') {\n return;\n }\n\n // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end\n let mediaBuffered = !!this.media && BufferHelper.isBuffered(this.media, this.media.currentTime) && BufferHelper.isBuffered(this.media, this.media.currentTime + 0.5);\n\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n if (!data.fatal) {\n // keep retrying until the limit will be reached\n if ((this.fragLoadError + 1) <= this.config.fragLoadingMaxRetry) {\n // exponential backoff capped to config.fragLoadingMaxRetryTimeout\n let delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout);\n logger.warn(`mediaController: frag loading failed, retry in ${delay} ms`);\n this.retryDate = window.performance.now() + delay;\n // retry loading state\n // if loadedmetadata is not set, it means that we are emergency switch down on first frag\n // in that case, reset startFragRequested flag\n if (!this.loadedmetadata) {\n this.startFragRequested = false;\n this.nextLoadPosition = this.startPosition;\n }\n this.fragLoadError++;\n this.state = State.FRAG_LOADING_WAITING_RETRY;\n } else {\n logger.error(`mediaController: ${data.details} reaches max retry, redispatch as fatal ...`);\n // switch error to fatal\n data.fatal = true;\n this.state = State.ERROR;\n }\n }\n break;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n if (this.state !== State.ERROR) {\n if (data.fatal) {\n // if fatal error, stop processing\n this.state = State.ERROR;\n logger.warn(`streamController: ${data.details},switch to ${this.state} state ...`);\n } else {\n // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE\n if (!data.levelRetry && this.state === State.WAITING_LEVEL) {\n this.state = State.IDLE;\n }\n }\n }\n break;\n case ErrorDetails.BUFFER_FULL_ERROR:\n // if in appending state\n if (data.parent === 'main' && (this.state === State.PARSING || this.state === State.PARSED)) {\n // reduce max buf len if current position is buffered\n if (mediaBuffered) {\n this._reduceMaxBufferLength(this.config.maxBufferLength);\n this.state = State.IDLE;\n } else {\n // current position is not buffered, but browser is still complaining about buffer full error\n // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708\n // in that case flush the whole buffer to recover\n logger.warn('buffer full error also media.currentTime is not buffered, flush everything');\n this.fragCurrent = null;\n // flush everything\n this.flushMainBuffer(0, Number.POSITIVE_INFINITY);\n }\n }\n break;\n default:\n break;\n }\n }\n\n _reduceMaxBufferLength (minLength) {\n let config = this.config;\n if (config.maxMaxBufferLength >= minLength) {\n // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...\n config.maxMaxBufferLength /= 2;\n logger.warn(`main:reduce max buffer length to ${config.maxMaxBufferLength}s`);\n return true;\n }\n return false;\n }\n\n /**\n * Checks the health of the buffer and attempts to resolve playback stalls.\n * @private\n */\n _checkBuffer () {\n const { media } = this;\n if (!media || media.readyState === 0) {\n // Exit early if we don't have media or if the media hasn't bufferd anything yet (readyState 0)\n return;\n }\n\n const mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;\n const buffered = mediaBuffer.buffered;\n\n if (!this.loadedmetadata && buffered.length) {\n this.loadedmetadata = true;\n this._seekToStartPos();\n } else if (this.immediateSwitch) {\n this.immediateLevelSwitchEnd();\n } else {\n this.gapController.poll(this.lastCurrentTime, buffered);\n }\n }\n\n onFragLoadEmergencyAborted () {\n this.state = State.IDLE;\n // if loadedmetadata is not set, it means that we are emergency switch down on first frag\n // in that case, reset startFragRequested flag\n if (!this.loadedmetadata) {\n this.startFragRequested = false;\n this.nextLoadPosition = this.startPosition;\n }\n this.tick();\n }\n\n onBufferFlushed () {\n /* after successful buffer flushing, filter flushed fragments from bufferedFrags\n use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track)\n */\n const media = this.mediaBuffer ? this.mediaBuffer : this.media;\n if (media) {\n // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams\n this.fragmentTracker.detectEvictedFragments(ElementaryStreamTypes.VIDEO, media.buffered);\n }\n // move to IDLE once flush complete. this should trigger new fragment loading\n this.state = State.IDLE;\n // reset reference to frag\n this.fragPrevious = null;\n }\n\n swapAudioCodec () {\n this.audioCodecSwap = !this.audioCodecSwap;\n }\n /**\n * Seeks to the set startPosition if not equal to the mediaElement's current time.\n * @private\n */\n _seekToStartPos () {\n const { media } = this;\n const currentTime = media.currentTime;\n // only adjust currentTime if different from startPosition or if startPosition not buffered\n // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered\n const startPosition = media.seeking ? currentTime : this.startPosition;\n // if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered\n if (currentTime !== startPosition && startPosition >= 0) {\n // if startPosition not buffered, let's seek to buffered.start(0)\n logger.log(`target start position not buffered, seek to buffered.start(0) ${startPosition} from current time ${currentTime} `);\n media.currentTime = startPosition;\n }\n }\n\n _getAudioCodec (currentLevel) {\n let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;\n if (this.audioCodecSwap) {\n logger.log('swapping playlist audio codec');\n if (audioCodec) {\n if (audioCodec.indexOf('mp4a.40.5') !== -1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n }\n\n return audioCodec;\n }\n\n get liveSyncPosition () {\n return this._liveSyncPosition;\n }\n\n set liveSyncPosition (value) {\n this._liveSyncPosition = value;\n }\n}\nexport default StreamController;\n","/*\n * Level Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { isCodecSupportedInMp4 } from '../utils/codecs';\nimport { addGroupId, computeReloadInterval } from './level-helper';\n\nconst { performance } = window;\nlet chromeOrFirefox;\n\nexport default class LevelController extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.MANIFEST_LOADED,\n Event.LEVEL_LOADED,\n Event.AUDIO_TRACK_SWITCHED,\n Event.FRAG_LOADED,\n Event.ERROR);\n\n this.canload = false;\n this.currentLevelIndex = null;\n this.manualLevelIndex = -1;\n this.timer = null;\n\n chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());\n }\n\n onHandlerDestroying () {\n this.clearTimer();\n this.manualLevelIndex = -1;\n }\n\n clearTimer () {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n startLoad () {\n let levels = this._levels;\n\n this.canload = true;\n this.levelRetryCount = 0;\n\n // clean up live level details to force reload them, and reset load errors\n if (levels) {\n levels.forEach(level => {\n level.loadError = 0;\n const levelDetails = level.details;\n if (levelDetails && levelDetails.live) {\n level.details = undefined;\n }\n });\n }\n // speed up live playlist refresh if timer exists\n if (this.timer !== null) {\n this.loadLevel();\n }\n }\n\n stopLoad () {\n this.canload = false;\n }\n\n onManifestLoaded (data) {\n let levels = [];\n let audioTracks = [];\n let bitrateStart;\n let levelSet = {};\n let levelFromSet = null;\n let videoCodecFound = false;\n let audioCodecFound = false;\n\n // regroup redundant levels together\n data.levels.forEach(level => {\n const attributes = level.attrs;\n level.loadError = 0;\n level.fragmentError = false;\n\n videoCodecFound = videoCodecFound || !!level.videoCodec;\n audioCodecFound = audioCodecFound || !!level.audioCodec;\n\n // erase audio codec info if browser does not support mp4a.40.34.\n // demuxer will autodetect codec and fallback to mpeg/audio\n if (chromeOrFirefox && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {\n level.audioCodec = undefined;\n }\n\n levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here\n\n if (!levelFromSet) {\n level.url = [level.url];\n level.urlId = 0;\n levelSet[level.bitrate] = level;\n levels.push(level);\n } else {\n levelFromSet.url.push(level.url);\n }\n\n if (attributes) {\n if (attributes.AUDIO) {\n audioCodecFound = true;\n addGroupId(levelFromSet || level, 'audio', attributes.AUDIO);\n }\n if (attributes.SUBTITLES) {\n addGroupId(levelFromSet || level, 'text', attributes.SUBTITLES);\n }\n }\n });\n\n // remove audio-only level if we also have levels with audio+video codecs signalled\n if (videoCodecFound && audioCodecFound) {\n levels = levels.filter(({ videoCodec }) => !!videoCodec);\n }\n\n // only keep levels with supported audio/video codecs\n levels = levels.filter(({ audioCodec, videoCodec }) => {\n return (!audioCodec || isCodecSupportedInMp4(audioCodec, 'audio')) && (!videoCodec || isCodecSupportedInMp4(videoCodec, 'video'));\n });\n\n if (data.audioTracks) {\n audioTracks = data.audioTracks.filter(track => !track.audioCodec || isCodecSupportedInMp4(track.audioCodec, 'audio'));\n // Reassign id's after filtering since they're used as array indices\n audioTracks.forEach((track, index) => {\n track.id = index;\n });\n }\n\n if (levels.length > 0) {\n // start bitrate is the first bitrate of the manifest\n bitrateStart = levels[0].bitrate;\n // sort level on bitrate\n levels.sort((a, b) => a.bitrate - b.bitrate);\n this._levels = levels;\n // find index of first level in sorted levels\n for (let i = 0; i < levels.length; i++) {\n if (levels[i].bitrate === bitrateStart) {\n this._firstLevel = i;\n logger.log(`manifest loaded,${levels.length} level(s) found, first bitrate:${bitrateStart}`);\n break;\n }\n }\n\n // Audio is only alternate if manifest include a URI along with the audio group tag\n this.hls.trigger(Event.MANIFEST_PARSED, {\n levels,\n audioTracks,\n firstLevel: this._firstLevel,\n stats: data.stats,\n audio: audioCodecFound,\n video: videoCodecFound,\n altAudio: audioTracks.some(t => !!t.url)\n });\n } else {\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,\n fatal: true,\n url: this.hls.url,\n reason: 'no level with compatible codecs found in manifest'\n });\n }\n }\n\n get levels () {\n return this._levels;\n }\n\n get level () {\n return this.currentLevelIndex;\n }\n\n set level (newLevel) {\n let levels = this._levels;\n if (levels) {\n newLevel = Math.min(newLevel, levels.length - 1);\n if (this.currentLevelIndex !== newLevel || !levels[newLevel].details) {\n this.setLevelInternal(newLevel);\n }\n }\n }\n\n setLevelInternal (newLevel) {\n const levels = this._levels;\n const hls = this.hls;\n // check if level idx is valid\n if (newLevel >= 0 && newLevel < levels.length) {\n // stopping live reloading timer if any\n this.clearTimer();\n if (this.currentLevelIndex !== newLevel) {\n logger.log(`switching to level ${newLevel}`);\n this.currentLevelIndex = newLevel;\n const levelProperties = levels[newLevel];\n levelProperties.level = newLevel;\n hls.trigger(Event.LEVEL_SWITCHING, levelProperties);\n }\n const level = levels[newLevel];\n const levelDetails = level.details;\n\n // check if we need to load playlist for this level\n if (!levelDetails || levelDetails.live) {\n // level not retrieved yet, or live playlist we need to (re)load it\n let urlId = level.urlId;\n hls.trigger(Event.LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId });\n }\n } else {\n // invalid level id given, trigger error\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.LEVEL_SWITCH_ERROR,\n level: newLevel,\n fatal: false,\n reason: 'invalid level idx'\n });\n }\n }\n\n get manualLevel () {\n return this.manualLevelIndex;\n }\n\n set manualLevel (newLevel) {\n this.manualLevelIndex = newLevel;\n if (this._startLevel === undefined) {\n this._startLevel = newLevel;\n }\n\n if (newLevel !== -1) {\n this.level = newLevel;\n }\n }\n\n get firstLevel () {\n return this._firstLevel;\n }\n\n set firstLevel (newLevel) {\n this._firstLevel = newLevel;\n }\n\n get startLevel () {\n // hls.startLevel takes precedence over config.startLevel\n // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)\n if (this._startLevel === undefined) {\n let configStartLevel = this.hls.config.startLevel;\n if (configStartLevel !== undefined) {\n return configStartLevel;\n } else {\n return this._firstLevel;\n }\n } else {\n return this._startLevel;\n }\n }\n\n set startLevel (newLevel) {\n this._startLevel = newLevel;\n }\n\n onError (data) {\n if (data.fatal) {\n if (data.type === ErrorTypes.NETWORK_ERROR) {\n this.clearTimer();\n }\n\n return;\n }\n\n let levelError = false, fragmentError = false;\n let levelIndex;\n\n // try to recover not fatal errors\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n levelIndex = data.frag.level;\n fragmentError = true;\n break;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n levelIndex = data.context.level;\n levelError = true;\n break;\n case ErrorDetails.REMUX_ALLOC_ERROR:\n levelIndex = data.level;\n levelError = true;\n break;\n }\n\n if (levelIndex !== undefined) {\n this.recoverLevel(data, levelIndex, levelError, fragmentError);\n }\n }\n\n /**\n * Switch to a redundant stream if any available.\n * If redundant stream is not available, emergency switch down if ABR mode is enabled.\n *\n * @param {Object} errorEvent\n * @param {Number} levelIndex current level index\n * @param {Boolean} levelError\n * @param {Boolean} fragmentError\n */\n // FIXME Find a better abstraction where fragment/level retry management is well decoupled\n recoverLevel (errorEvent, levelIndex, levelError, fragmentError) {\n let { config } = this.hls;\n let { details: errorDetails } = errorEvent;\n let level = this._levels[levelIndex];\n let redundantLevels, delay, nextLevel;\n\n level.loadError++;\n level.fragmentError = fragmentError;\n\n if (levelError) {\n if ((this.levelRetryCount + 1) <= config.levelLoadingMaxRetry) {\n // exponential backoff capped to max retry timeout\n delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);\n // Schedule level reload\n this.timer = setTimeout(() => this.loadLevel(), delay);\n // boolean used to inform stream controller not to switch back to IDLE on non fatal error\n errorEvent.levelRetry = true;\n this.levelRetryCount++;\n logger.warn(`level controller, ${errorDetails}, retry in ${delay} ms, current retry count is ${this.levelRetryCount}`);\n } else {\n logger.error(`level controller, cannot recover from ${errorDetails} error`);\n this.currentLevelIndex = null;\n // stopping live reloading timer if any\n this.clearTimer();\n // switch error to fatal\n errorEvent.fatal = true;\n return;\n }\n }\n\n // Try any redundant streams if available for both errors: level and fragment\n // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down\n if (levelError || fragmentError) {\n redundantLevels = level.url.length;\n\n if (redundantLevels > 1 && level.loadError < redundantLevels) {\n level.urlId = (level.urlId + 1) % redundantLevels;\n level.details = undefined;\n\n logger.warn(`level controller, ${errorDetails} for level ${levelIndex}: switching to redundant URL-id ${level.urlId}`);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', level.attrs.AUDIO);\n } else {\n // Search for available level\n if (this.manualLevelIndex === -1) {\n // When lowest level has been reached, let's start hunt from the top\n nextLevel = (levelIndex === 0) ? this._levels.length - 1 : levelIndex - 1;\n logger.warn(`level controller, ${errorDetails}: switch to ${nextLevel}`);\n this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;\n } else if (fragmentError) {\n // Allow fragment retry as long as configuration allows.\n // reset this._level so that another call to set level() will trigger again a frag load\n logger.warn(`level controller, ${errorDetails}: reload a fragment`);\n this.currentLevelIndex = null;\n }\n }\n }\n }\n\n // reset errors on the successful load of a fragment\n onFragLoaded ({ frag }) {\n if (frag !== undefined && frag.type === 'main') {\n const level = this._levels[frag.level];\n if (level !== undefined) {\n level.fragmentError = false;\n level.loadError = 0;\n this.levelRetryCount = 0;\n }\n }\n }\n\n onLevelLoaded (data) {\n const { level, details } = data;\n // only process level loaded events matching with expected level\n if (level !== this.currentLevelIndex) {\n return;\n }\n\n const curLevel = this._levels[level];\n // reset level load error counter on successful level loaded only if there is no issues with fragments\n if (!curLevel.fragmentError) {\n curLevel.loadError = 0;\n this.levelRetryCount = 0;\n }\n // if current playlist is a live playlist, arm a timer to reload it\n if (details.live) {\n const reloadInterval = computeReloadInterval(curLevel.details, details, data.stats.trequest);\n logger.log(`live playlist, reload in ${Math.round(reloadInterval)} ms`);\n this.timer = setTimeout(() => this.loadLevel(), reloadInterval);\n } else {\n this.clearTimer();\n }\n }\n\n onAudioTrackSwitched (data) {\n const audioGroupId = this.hls.audioTracks[data.id].groupId;\n\n const currentLevel = this.hls.levels[this.currentLevelIndex];\n if (!currentLevel) {\n return;\n }\n\n if (currentLevel.audioGroupIds) {\n let urlId = -1;\n\n for (let i = 0; i < currentLevel.audioGroupIds.length; i++) {\n if (currentLevel.audioGroupIds[i] === audioGroupId) {\n urlId = i;\n break;\n }\n }\n\n if (urlId !== currentLevel.urlId) {\n currentLevel.urlId = urlId;\n this.startLoad();\n }\n }\n }\n\n loadLevel () {\n logger.debug('call to loadLevel');\n\n if (this.currentLevelIndex !== null && this.canload) {\n const levelObject = this._levels[this.currentLevelIndex];\n\n if (typeof levelObject === 'object' &&\n levelObject.url.length > 0) {\n const level = this.currentLevelIndex;\n const id = levelObject.urlId;\n const url = levelObject.url[id];\n\n logger.log(`Attempt loading level index ${level} with URL-id ${id}`);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);\n\n this.hls.trigger(Event.LEVEL_LOADING, { url, level, id });\n }\n }\n }\n\n get nextLoadLevel () {\n if (this.manualLevelIndex !== -1) {\n return this.manualLevelIndex;\n } else {\n return this.hls.nextAutoLevel;\n }\n }\n\n set nextLoadLevel (nextLevel) {\n this.level = nextLevel;\n if (this.manualLevelIndex === -1) {\n this.hls.nextAutoLevel = nextLevel;\n }\n }\n}\n","\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 && 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 { logger } from '../utils/logger';\nimport { sendAddTrackEvent, clearCurrentCues, getClosestCue } from '../utils/texttrack-utils';\n\nclass ID3TrackController extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.FRAG_PARSING_METADATA,\n 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 const startTime = samples[i].pts;\n let endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.endPTS;\n\n if (startTime === endTime) {\n // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE\n endTime += 0.0001;\n } else if (startTime > endTime) {\n logger.warn('detected an id3 sample with endTime < startTime, adjusting endTime to (startTime + 0.25)');\n endTime = startTime + 0.25;\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 const minAutoLevel = hls.minAutoLevel;\n\n // if loader has been destroyed or loading has been aborted, stop timer and return\n if (!loader || (loader.stats && loader.stats.aborted)) {\n logger.warn('frag loader destroy or aborted, disarm abandonRules');\n this.clearTimer();\n // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\n return;\n }\n let stats = loader.stats;\n /* only monitor frag retrieval time if\n (video not paused OR first fragment being loaded(ready state === HAVE_NOTHING = 0)) AND autoswitching enabled AND not lowest level (=> means that we have several levels) */\n if (video && stats && ((!video.paused && (video.playbackRate !== 0)) || !video.readyState) && frag.autoLevel && frag.level) {\n 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 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 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: { 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\n onManifestParsed (data: { altAudio: boolean }) {\n // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller\n // sourcebuffers will be created all at once when the expected nb of tracks will be reached\n // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller\n // it will contain the expected nb of source buffers, no need to compute it\n this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = data.altAudio ? 2 : 1;\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 }\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 === true) {\n // Override duration to Infinity\n logger.log('Media Source duration is set to Infinity');\n this._msDuration = this.mediaSource.duration = Infinity;\n } else if ((this._levelDuration > this._msDuration && this._levelDuration > duration) || !Number.isFinite(duration)) {\n // levelDuration was the last value we set.\n // not using mediaSource.duration as the browser may tweak this value\n // only update Media Source duration if its value increase, this is to avoid\n // flushing already buffered portion when switching between quality level\n logger.log(`Updating Media Source duration to ${this._levelDuration.toFixed(3)}`);\n this._msDuration = this.mediaSource.duration = this._levelDuration;\n }\n }\n\n doFlush () {\n // loop through all buffer ranges to flush\n while (this.flushRange.length) {\n let range = this.flushRange[0];\n // flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer\n if (this.flushBuffer(range.start, range.end, range.type)) {\n // range flushed, remove from flush array\n this.flushRange.shift();\n this.flushBufferCounter = 0;\n } else {\n this._needsFlush = true;\n // avoid looping, wait for SB update end to retrigger a flush\n return;\n }\n }\n if (this.flushRange.length === 0) {\n // everything flushed\n this._needsFlush = false;\n\n // let's recompute this.appended, which is used to avoid flush looping\n let appended = 0;\n let sourceBuffer = this.sourceBuffer;\n try {\n for (let type in sourceBuffer) {\n 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.BUFFER_CODECS,\n Event.MEDIA_DETACHING);\n\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.firstLevel = null;\n this.levels = [];\n this.media = null;\n this.restrictedLevels = [];\n this.timer = null;\n }\n\n destroy () {\n if (this.hls.config.capLevelToPlayerSize) {\n this.media = null;\n this.stopCapping();\n }\n }\n\n onFpsDropLevelCapping (data) {\n // Don't add a restricted level more than once\n if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {\n this.restrictedLevels.push(data.droppedLevel);\n }\n }\n\n onMediaAttaching (data) {\n this.media = data.media instanceof window.HTMLVideoElement ? data.media : null;\n }\n\n onManifestParsed (data) {\n const hls = this.hls;\n this.restrictedLevels = [];\n this.levels = data.levels;\n this.firstLevel = data.firstLevel;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // Start capping immediately if the manifest has signaled video codecs\n this.startCapping();\n }\n }\n\n // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted\n // to the first level\n onBufferCodecs (data) {\n const hls = this.hls;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // If the manifest did not signal a video codec capping has been deferred until we're certain video is present\n this.startCapping();\n }\n }\n\n onLevelsUpdated (data) {\n this.levels = data.levels;\n }\n\n onMediaDetaching () {\n this.stopCapping();\n }\n\n detectPlayerSize () {\n if (this.media) {\n let levelsLength = this.levels ? this.levels.length : 0;\n if (levelsLength) {\n const hls = this.hls;\n hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1);\n if (hls.autoLevelCapping > this.autoLevelCapping) {\n // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch\n // usually happen when the user go to the fullscreen mode.\n hls.streamController.nextLevelSwitch();\n }\n this.autoLevelCapping = hls.autoLevelCapping;\n }\n }\n }\n\n /*\n * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)\n */\n getMaxLevel (capLevelIndex) {\n if (!this.levels) {\n return -1;\n }\n\n const validLevels = this.levels.filter((level, index) =>\n CapLevelController.isLevelAllowed(index, this.restrictedLevels) && index <= capLevelIndex\n );\n\n return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);\n }\n\n startCapping () {\n if (this.timer) {\n // Don't reset capping if started twice; this can happen if the manifest signals a video codec\n return;\n }\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.hls.firstLevel = this.getMaxLevel(this.firstLevel);\n clearInterval(this.timer);\n this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);\n this.detectPlayerSize();\n }\n\n stopCapping () {\n this.restrictedLevels = [];\n this.firstLevel = null;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n if (this.timer) {\n this.timer = clearInterval(this.timer);\n this.timer = null;\n }\n }\n\n get mediaWidth () {\n let width;\n const media = this.media;\n if (media) {\n width = media.width || media.clientWidth || media.offsetWidth;\n width *= CapLevelController.contentScaleFactor;\n }\n return width;\n }\n\n get mediaHeight () {\n let height;\n const media = this.media;\n if (media) {\n height = media.height || media.clientHeight || media.offsetHeight;\n height *= CapLevelController.contentScaleFactor;\n }\n return height;\n }\n\n static get contentScaleFactor () {\n let pixelRatio = 1;\n try {\n pixelRatio = window.devicePixelRatio;\n } catch (e) {}\n return pixelRatio;\n }\n\n static isLevelAllowed (level, restrictedLevels = []) {\n return restrictedLevels.indexOf(level) === -1;\n }\n\n static getMaxLevelByMediaSize (levels, width, height) {\n if (!levels || (levels && !levels.length)) {\n return -1;\n }\n\n // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next\n // to determine whether we've chosen the greatest bandwidth for the media's dimensions\n const atGreatestBandiwdth = (curLevel, nextLevel) => {\n if (!nextLevel) {\n return true;\n }\n\n return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;\n };\n\n // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to\n // the max level\n let maxLevelIndex = levels.length - 1;\n\n for (let i = 0; i < levels.length; i += 1) {\n const level = levels[i];\n if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {\n maxLevelIndex = i;\n break;\n }\n }\n\n return maxLevelIndex;\n }\n}\n\nexport default CapLevelController;\n","/*\n * FPS Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { logger } from '../utils/logger';\n\nconst { performance } = window;\n\nclass FPSController extends EventHandler {\n constructor (hls) {\n super(hls, Event.MEDIA_ATTACHING);\n }\n\n destroy () {\n if (this.timer) {\n clearInterval(this.timer);\n }\n\n this.isVideoPlaybackQualityAvailable = false;\n }\n\n onMediaAttaching (data) {\n const config = this.hls.config;\n if (config.capLevelOnFPSDrop) {\n const video = this.video = data.media instanceof window.HTMLVideoElement ? data.media : null;\n if (typeof video.getVideoPlaybackQuality === 'function') {\n this.isVideoPlaybackQualityAvailable = true;\n }\n\n clearInterval(this.timer);\n this.timer = setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);\n }\n }\n\n checkFPS (video, decodedFrames, droppedFrames) {\n let currentTime = performance.now();\n if (decodedFrames) {\n if (this.lastTime) {\n let currentPeriod = currentTime - this.lastTime,\n currentDropped = droppedFrames - this.lastDroppedFrames,\n currentDecoded = decodedFrames - this.lastDecodedFrames,\n droppedFPS = 1000 * currentDropped / currentPeriod,\n hls = this.hls;\n hls.trigger(Event.FPS_DROP, { currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames });\n if (droppedFPS > 0) {\n // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));\n if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {\n let currentLevel = hls.currentLevel;\n logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);\n if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {\n currentLevel = currentLevel - 1;\n hls.trigger(Event.FPS_DROP_LEVEL_CAPPING, { level: currentLevel, droppedLevel: hls.currentLevel });\n hls.autoLevelCapping = currentLevel;\n hls.streamController.nextLevelSwitch();\n }\n }\n }\n }\n this.lastTime = currentTime;\n this.lastDroppedFrames = droppedFrames;\n this.lastDecodedFrames = decodedFrames;\n }\n }\n\n checkFPSInterval () {\n const video = this.video;\n if (video) {\n if (this.isVideoPlaybackQualityAvailable) {\n let videoPlaybackQuality = video.getVideoPlaybackQuality();\n this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);\n } else {\n this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);\n }\n }\n }\n}\n\nexport default FPSController;\n","/**\n * XHR based logger\n*/\n\nimport { logger } from '../utils/logger';\n\nconst { performance, XMLHttpRequest } = window;\n\nclass XhrLoader {\n constructor (config) {\n if (config && config.xhrSetup) {\n this.xhrSetup = config.xhrSetup;\n }\n }\n\n destroy () {\n this.abort();\n this.loader = null;\n }\n\n abort () {\n let loader = this.loader;\n if (loader && loader.readyState !== 4) {\n this.stats.aborted = true;\n loader.abort();\n }\n\n window.clearTimeout(this.requestTimeout);\n this.requestTimeout = null;\n window.clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n }\n\n load (context, config, callbacks) {\n this.context = context;\n this.config = config;\n this.callbacks = callbacks;\n this.stats = { trequest: performance.now(), retry: 0 };\n this.retryDelay = config.retryDelay;\n this.loadInternal();\n }\n\n loadInternal () {\n let xhr, context = this.context;\n xhr = this.loader = new XMLHttpRequest();\n\n let stats = this.stats;\n stats.tfirst = 0;\n stats.loaded = 0;\n const xhrSetup = this.xhrSetup;\n\n try {\n if (xhrSetup) {\n try {\n xhrSetup(xhr, context.url);\n } catch (e) {\n // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader(\"Content-Language\", \"test\");}\n // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN\n xhr.open('GET', context.url, true);\n xhrSetup(xhr, context.url);\n }\n }\n if (!xhr.readyState) {\n xhr.open('GET', context.url, true);\n }\n } catch (e) {\n // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n this.callbacks.onError({ code: xhr.status, text: e.message }, context, xhr);\n return;\n }\n\n if (context.rangeEnd) {\n xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));\n }\n\n xhr.onreadystatechange = this.readystatechange.bind(this);\n xhr.onprogress = this.loadprogress.bind(this);\n xhr.responseType = context.responseType;\n\n // setup timeout before we perform request\n this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), this.config.timeout);\n xhr.send();\n }\n\n readystatechange (event) {\n let xhr = event.currentTarget,\n readyState = xhr.readyState,\n stats = this.stats,\n context = this.context,\n config = this.config;\n\n // don't proceed if xhr has been aborted\n if (stats.aborted) {\n return;\n }\n\n // >= HEADERS_RECEIVED\n if (readyState >= 2) {\n // clear xhr timeout and rearm it if readyState less than 4\n window.clearTimeout(this.requestTimeout);\n if (stats.tfirst === 0) {\n stats.tfirst = Math.max(performance.now(), stats.trequest);\n }\n\n if (readyState === 4) {\n let status = xhr.status;\n // http status between 200 to 299 are all successful\n if (status >= 200 && status < 300) {\n stats.tload = Math.max(stats.tfirst, performance.now());\n let data, len;\n if (context.responseType === 'arraybuffer') {\n data = xhr.response;\n len = data.byteLength;\n } else {\n data = xhr.responseText;\n len = data.length;\n }\n stats.loaded = stats.total = len;\n let response = { url: xhr.responseURL, data: data };\n this.callbacks.onSuccess(response, stats, context, xhr);\n } else {\n // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error\n if (stats.retry >= config.maxRetry || (status >= 400 && status < 499)) {\n logger.error(`${status} while loading ${context.url}`);\n this.callbacks.onError({ code: status, text: xhr.statusText }, context, xhr);\n } else {\n // retry\n logger.warn(`${status} while loading ${context.url}, retrying in ${this.retryDelay}...`);\n // aborts and resets internal state\n this.destroy();\n // schedule retry\n this.retryTimeout = window.setTimeout(this.loadInternal.bind(this), this.retryDelay);\n // set exponential backoff\n this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);\n stats.retry++;\n }\n }\n } else {\n // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet\n this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), config.timeout);\n }\n }\n }\n\n loadtimeout () {\n logger.warn(`timeout while loading ${this.context.url}`);\n this.callbacks.onTimeout(this.stats, this.context, null);\n }\n\n loadprogress (event) {\n let xhr = event.currentTarget,\n stats = this.stats;\n\n stats.loaded = event.loaded;\n if (event.lengthComputable) {\n stats.total = event.total;\n }\n\n let onProgress = this.callbacks.onProgress;\n if (onProgress) {\n // third arg is to provide on progress data\n onProgress(stats, this.context, null, xhr);\n }\n }\n}\n\nexport default XhrLoader;\n","import Event from '../events';\nimport TaskLoop from '../task-loop';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\n/**\n * @class AudioTrackController\n * @implements {EventHandler}\n *\n * Handles main manifest and audio-track metadata loaded,\n * owns and exposes the selectable audio-tracks data-models.\n *\n * Exposes internal interface to select available audio-tracks.\n *\n * Handles errors on loading audio-track playlists. Manages fallback mechanism\n * with redundants tracks (group-IDs).\n *\n * Handles level-loading and group-ID switches for video (fallback on video levels),\n * and eventually adapts the audio-track group-ID to match.\n *\n * @fires AUDIO_TRACK_LOADING\n * @fires AUDIO_TRACK_SWITCHING\n * @fires AUDIO_TRACKS_UPDATED\n * @fires ERROR\n *\n */\nclass AudioTrackController extends TaskLoop {\n constructor (hls) {\n super(hls,\n Event.MANIFEST_LOADING,\n Event.MANIFEST_PARSED,\n Event.AUDIO_TRACK_LOADED,\n Event.AUDIO_TRACK_SWITCHED,\n Event.LEVEL_LOADED,\n Event.ERROR\n );\n\n /**\n * @private\n * Currently selected index in `tracks`\n * @member {number} trackId\n */\n this._trackId = -1;\n\n /**\n * @private\n * If should select tracks according to default track attribute\n * @member {boolean} _selectDefaultTrack\n */\n this._selectDefaultTrack = true;\n\n /**\n * @public\n * All tracks available\n * @member {AudioTrack[]}\n */\n this.tracks = [];\n\n /**\n * @public\n * List of blacklisted audio track IDs (that have caused failure)\n * @member {number[]}\n */\n this.trackIdBlacklist = Object.create(null);\n\n /**\n * @public\n * The currently running group ID for audio\n * (we grab this on manifest-parsed and new level-loaded)\n * @member {string}\n */\n this.audioGroupId = null;\n }\n\n /**\n * Reset audio tracks on new manifest loading.\n */\n onManifestLoading () {\n this.tracks = [];\n this._trackId = -1;\n this._selectDefaultTrack = true;\n }\n\n /**\n * Store tracks data from manifest parsed data.\n *\n * Trigger AUDIO_TRACKS_UPDATED event.\n *\n * @param {*} data\n */\n onManifestParsed (data) {\n const tracks = this.tracks = data.audioTracks || [];\n this.hls.trigger(Event.AUDIO_TRACKS_UPDATED, { audioTracks: tracks });\n\n this._selectAudioGroup(this.hls.nextLoadLevel);\n }\n\n /**\n * Store track details of loaded track in our data-model.\n *\n * Set-up metadata update interval task for live-mode streams.\n *\n * @param {*} data\n */\n onAudioTrackLoaded (data) {\n if (data.id >= this.tracks.length) {\n logger.warn('Invalid audio track id:', data.id);\n return;\n }\n\n logger.log(`audioTrack ${data.id} loaded`);\n\n this.tracks[data.id].details = data.details;\n\n // check if current playlist is a live playlist\n // and if we have already our reload interval setup\n if (data.details.live && !this.hasInterval()) {\n // if live playlist we will have to reload it periodically\n // set reload period to playlist target duration\n const updatePeriodMs = data.details.targetduration * 1000;\n this.setInterval(updatePeriodMs);\n }\n\n if (!data.details.live && this.hasInterval()) {\n // playlist is not live and timer is scheduled: cancel it\n this.clearInterval();\n }\n }\n\n /**\n * Update the internal group ID to any audio-track we may have set manually\n * or because of a failure-handling fallback.\n *\n * Quality-levels should update to that group ID in this case.\n *\n * @param {*} data\n */\n onAudioTrackSwitched (data) {\n const audioGroupId = this.tracks[data.id].groupId;\n if (audioGroupId && (this.audioGroupId !== audioGroupId)) {\n this.audioGroupId = audioGroupId;\n }\n }\n\n /**\n * When a level gets loaded, if it has redundant audioGroupIds (in the same ordinality as it's redundant URLs)\n * we are setting our audio-group ID internally to the one set, if it is different from the group ID currently set.\n *\n * If group-ID got update, we re-select the appropriate audio-track with this group-ID matching the currently\n * selected one (based on NAME property).\n *\n * @param {*} data\n */\n onLevelLoaded (data) {\n this._selectAudioGroup(data.level);\n }\n\n /**\n * Handle network errors loading audio track manifests\n * and also pausing on any netwok errors.\n *\n * @param {ErrorEventData} data\n */\n onError (data) {\n // Only handle network errors\n if (data.type !== ErrorTypes.NETWORK_ERROR) {\n return;\n }\n\n // If fatal network error, cancel update task\n if (data.fatal) {\n this.clearInterval();\n }\n\n // If not an audio-track loading error don't handle further\n if (data.details !== ErrorDetails.AUDIO_TRACK_LOAD_ERROR) {\n return;\n }\n\n logger.warn('Network failure on audio-track id:', data.context.id);\n this._handleLoadError();\n }\n\n /**\n * @type {AudioTrack[]} Audio-track list we own\n */\n get audioTracks () {\n return this.tracks;\n }\n\n /**\n * @type {number} Index into audio-tracks list of currently selected track.\n */\n get audioTrack () {\n return this._trackId;\n }\n\n /**\n * Select current track by index\n */\n set audioTrack (newId) {\n this._setAudioTrack(newId);\n // If audio track is selected from API then don't choose from the manifest default track\n this._selectDefaultTrack = false;\n }\n\n /**\n * @private\n * @param {number} newId\n */\n _setAudioTrack (newId) {\n // noop on same audio track id as already set\n if (this._trackId === newId && this.tracks[this._trackId].details) {\n logger.debug('Same id as current audio-track passed, and track details available -> no-op');\n return;\n }\n\n // check if level idx is valid\n if (newId < 0 || newId >= this.tracks.length) {\n logger.warn('Invalid id passed to audio-track controller');\n return;\n }\n\n const audioTrack = this.tracks[newId];\n\n logger.log(`Now switching to audio-track index ${newId}`);\n\n // stopping live reloading timer if any\n this.clearInterval();\n this._trackId = newId;\n\n const { url, type, id } = audioTrack;\n this.hls.trigger(Event.AUDIO_TRACK_SWITCHING, { id, type, url });\n this._loadTrackDetailsIfNeeded(audioTrack);\n }\n\n /**\n * @override\n */\n doTick () {\n this._updateTrack(this._trackId);\n }\n\n /**\n * @param levelId\n * @private\n */\n _selectAudioGroup (levelId) {\n const levelInfo = this.hls.levels[levelId];\n\n if (!levelInfo || !levelInfo.audioGroupIds) {\n return;\n }\n\n const audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];\n if (this.audioGroupId !== audioGroupId) {\n this.audioGroupId = audioGroupId;\n this._selectInitialAudioTrack();\n }\n }\n\n /**\n * Select initial track\n * @private\n */\n _selectInitialAudioTrack () {\n let tracks = this.tracks;\n if (!tracks.length) {\n return;\n }\n\n const currentAudioTrack = this.tracks[this._trackId];\n\n let name = null;\n if (currentAudioTrack) {\n name = currentAudioTrack.name;\n }\n\n // Pre-select default tracks if there are any\n if (this._selectDefaultTrack) {\n const defaultTracks = tracks.filter((track) => track.default);\n if (defaultTracks.length) {\n tracks = defaultTracks;\n } else {\n logger.warn('No default audio tracks defined');\n }\n }\n\n let trackFound = false;\n\n const traverseTracks = () => {\n // Select track with right group ID\n tracks.forEach((track) => {\n if (trackFound) {\n return;\n }\n // We need to match the (pre-)selected group ID\n // and the NAME of the current track.\n if ((!this.audioGroupId || track.groupId === this.audioGroupId) &&\n (!name || name === track.name)) {\n // If there was a previous track try to stay with the same `NAME`.\n // It should be unique across tracks of same group, and consistent through redundant track groups.\n this._setAudioTrack(track.id);\n trackFound = true;\n }\n });\n };\n\n traverseTracks();\n\n if (!trackFound) {\n name = null;\n traverseTracks();\n }\n\n if (!trackFound) {\n logger.error(`No track found for running audio group-ID: ${this.audioGroupId}`);\n\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR,\n fatal: true\n });\n }\n }\n\n /**\n * @private\n * @param {AudioTrack} audioTrack\n * @returns {boolean}\n */\n _needsTrackLoading (audioTrack) {\n const { details, url } = audioTrack;\n\n if (!details || details.live) {\n // check if we face an audio track embedded in main playlist (audio track without URI attribute)\n return !!url;\n }\n\n return false;\n }\n\n /**\n * @private\n * @param {AudioTrack} audioTrack\n */\n _loadTrackDetailsIfNeeded (audioTrack) {\n if (this._needsTrackLoading(audioTrack)) {\n const { url, id } = audioTrack;\n // track not retrieved yet, or live playlist we need to (re)load it\n logger.log(`loading audio-track playlist for id: ${id}`);\n this.hls.trigger(Event.AUDIO_TRACK_LOADING, { url, id });\n }\n }\n\n /**\n * @private\n * @param {number} newId\n */\n _updateTrack (newId) {\n // check if level idx is valid\n if (newId < 0 || newId >= this.tracks.length) {\n return;\n }\n\n // stopping live reloading timer if any\n this.clearInterval();\n this._trackId = newId;\n logger.log(`trying to update audio-track ${newId}`);\n const audioTrack = this.tracks[newId];\n this._loadTrackDetailsIfNeeded(audioTrack);\n }\n\n /**\n * @private\n */\n _handleLoadError () {\n // First, let's black list current track id\n this.trackIdBlacklist[this._trackId] = true;\n\n // Let's try to fall back on a functional audio-track with the same group ID\n const previousId = this._trackId;\n const { name, language, groupId } = this.tracks[previousId];\n\n logger.warn(`Loading failed on audio track id: ${previousId}, group-id: ${groupId}, name/language: \"${name}\" / \"${language}\"`);\n\n // Find a non-blacklisted track ID with the same NAME\n // At least a track that is not blacklisted, thus on another group-ID.\n let newId = previousId;\n for (let i = 0; i < this.tracks.length; i++) {\n if (this.trackIdBlacklist[i]) {\n continue;\n }\n const newTrack = this.tracks[i];\n if (newTrack.name === name) {\n newId = i;\n break;\n }\n }\n\n if (newId === previousId) {\n logger.warn(`No fallback audio-track found for name/language: \"${name}\" / \"${language}\"`);\n return;\n }\n\n logger.log('Attempting audio-track fallback id:', newId, 'group-id:', this.tracks[newId].groupId);\n\n this._setAudioTrack(newId);\n }\n}\n\nexport default AudioTrackController;\n","/*\n * Audio Stream Controller\n*/\n\nimport BinarySearch from '../utils/binary-search';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport Demuxer from '../demux/demuxer';\nimport Event from '../events';\nimport * as LevelHelper from './level-helper';\nimport TimeRanges from '../utils/time-ranges';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport { findFragWithCC } from '../utils/discontinuities';\nimport { FragmentState } from './fragment-tracker';\nimport Fragment, { ElementaryStreamTypes } from '../loader/fragment';\nimport BaseStreamController, { State } from './base-stream-controller';\nconst { performance } = window;\n\nconst TICK_INTERVAL = 100; // how often to tick in ms\n\nclass AudioStreamController extends BaseStreamController {\n constructor (hls, fragmentTracker) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.AUDIO_TRACKS_UPDATED,\n Event.AUDIO_TRACK_SWITCHING,\n Event.AUDIO_TRACK_LOADED,\n Event.KEY_LOADED,\n Event.FRAG_LOADED,\n Event.FRAG_PARSING_INIT_SEGMENT,\n Event.FRAG_PARSING_DATA,\n Event.FRAG_PARSED,\n Event.ERROR,\n Event.BUFFER_RESET,\n Event.BUFFER_CREATED,\n Event.BUFFER_APPENDED,\n Event.BUFFER_FLUSHED,\n Event.INIT_PTS_FOUND);\n this.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.audioCodecSwap = false;\n this._state = State.STOPPED;\n this.initPTS = [];\n this.waitingFragment = null;\n this.videoTrackCC = null;\n }\n\n // Signal that video PTS was found\n onInitPtsFound (data) {\n let demuxerId = data.id, cc = data.frag.cc, initPTS = data.initPTS;\n if (demuxerId === 'main') {\n // Always update the new INIT PTS\n // Can change due level switch\n this.initPTS[cc] = initPTS;\n this.videoTrackCC = cc;\n logger.log(`InitPTS for cc: ${cc} found from video track: ${initPTS}`);\n\n // If we are waiting we need to demux/remux the waiting frag\n // With the new initPTS\n if (this.state === State.WAITING_INIT_PTS) {\n this.tick();\n }\n }\n }\n\n startLoad (startPosition) {\n if (this.tracks) {\n let lastCurrentTime = this.lastCurrentTime;\n this.stopLoad();\n this.setInterval(TICK_INTERVAL);\n this.fragLoadError = 0;\n if (lastCurrentTime > 0 && startPosition === -1) {\n logger.log(`audio:override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);\n this.state = State.IDLE;\n } else {\n this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition;\n this.state = State.STARTING;\n }\n this.nextLoadPosition = this.startPosition = this.lastCurrentTime;\n this.tick();\n } else {\n this.startPosition = startPosition;\n this.state = State.STOPPED;\n }\n }\n\n set state (nextState) {\n if (this.state !== nextState) {\n const previousState = this.state;\n this._state = nextState;\n logger.log(`audio stream:${previousState}->${nextState}`);\n }\n }\n\n get state () {\n return this._state;\n }\n\n doTick () {\n let pos, track, trackDetails, hls = this.hls, config = hls.config;\n // logger.log('audioStream:' + this.state);\n switch (this.state) {\n case State.ERROR:\n // don't do anything in error state to avoid breaking further ...\n case State.PAUSED:\n // don't do anything in paused state either ...\n case State.BUFFER_FLUSHING:\n break;\n case State.STARTING:\n this.state = State.WAITING_TRACK;\n this.loadedmetadata = false;\n break;\n case State.IDLE:\n const tracks = this.tracks;\n // audio tracks not received => exit loop\n if (!tracks) {\n break;\n }\n\n // if video not attached AND\n // start fragment already requested OR start frag prefetch disable\n // exit loop\n // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop\n if (!this.media &&\n (this.startFragRequested || !config.startFragPrefetch)) {\n break;\n }\n\n // determine next candidate fragment to be loaded, based on current position and\n // end of buffer position\n // if we have not yet loaded any fragment, start loading from start position\n if (this.loadedmetadata) {\n pos = this.media.currentTime;\n } else {\n pos = this.nextLoadPosition;\n if (pos === undefined) {\n break;\n }\n }\n let media = this.mediaBuffer ? this.mediaBuffer : this.media,\n videoBuffer = this.videoBuffer ? this.videoBuffer : this.media,\n bufferInfo = BufferHelper.bufferInfo(media, pos, config.maxBufferHole),\n mainBufferInfo = BufferHelper.bufferInfo(videoBuffer, pos, config.maxBufferHole),\n bufferLen = bufferInfo.len,\n bufferEnd = bufferInfo.end,\n fragPrevious = this.fragPrevious,\n // ensure we buffer at least config.maxBufferLength (default 30s) or config.maxMaxBufferLength (default: 600s)\n // whichever is smaller.\n // once we reach that threshold, don't buffer more than video (mainBufferInfo.len)\n maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength),\n maxBufLen = Math.max(maxConfigBuffer, mainBufferInfo.len),\n audioSwitch = this.audioSwitch,\n trackId = this.trackId;\n\n // if buffer length is less than maxBufLen try to load a new fragment\n if ((bufferLen < maxBufLen || audioSwitch) && trackId < tracks.length) {\n trackDetails = tracks[trackId].details;\n // if track info not retrieved yet, switch state and wait for track retrieval\n if (typeof trackDetails === 'undefined') {\n this.state = State.WAITING_TRACK;\n break;\n }\n\n if (!audioSwitch && this._streamEnded(bufferInfo, trackDetails)) {\n this.hls.trigger(Event.BUFFER_EOS, { type: 'audio' });\n this.state = State.ENDED;\n return;\n }\n\n // find fragment index, contiguous with end of buffer position\n let fragments = trackDetails.fragments,\n fragLen = fragments.length,\n start = fragments[0].start,\n end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,\n frag;\n\n // When switching audio track, reload audio as close as possible to currentTime\n if (audioSwitch) {\n if (trackDetails.live && !trackDetails.PTSKnown) {\n logger.log('switching audiotrack, live stream, unknown PTS,load first fragment');\n bufferEnd = 0;\n } else {\n bufferEnd = pos;\n // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime\n if (trackDetails.PTSKnown && pos < start) {\n // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start\n if (bufferInfo.end > start || bufferInfo.nextStart) {\n logger.log('alt audio track ahead of main track, seek to start of alt audio track');\n this.media.currentTime = start + 0.05;\n } else {\n return;\n }\n }\n }\n }\n if (trackDetails.initSegment && !trackDetails.initSegment.data) {\n frag = trackDetails.initSegment;\n } // eslint-disable-line brace-style\n // if bufferEnd before start of playlist, load first fragment\n else if (bufferEnd <= start) {\n frag = fragments[0];\n if (this.videoTrackCC !== null && frag.cc !== this.videoTrackCC) {\n // Ensure we find a fragment which matches the continuity of the video track\n frag = findFragWithCC(fragments, this.videoTrackCC);\n }\n if (trackDetails.live && frag.loadIdx && frag.loadIdx === this.fragLoadIdx) {\n // we just loaded this first fragment, and we are still lagging behind the start of the live playlist\n // let's force seek to start\n const nextBuffered = bufferInfo.nextStart ? bufferInfo.nextStart : start;\n logger.log(`no alt audio available @currentTime:${this.media.currentTime}, seeking @${nextBuffered + 0.05}`);\n this.media.currentTime = nextBuffered + 0.05;\n return;\n }\n } else {\n let foundFrag;\n let maxFragLookUpTolerance = config.maxFragLookUpTolerance;\n const fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;\n let fragmentWithinToleranceTest = (candidate) => {\n // offset should be within fragment boundary - config.maxFragLookUpTolerance\n // this is to cope with situations like\n // bufferEnd = 9.991\n // frag[Ø] : [0,10]\n // frag[1] : [10,20]\n // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here\n // frag start frag start+duration\n // |-----------------------------|\n // <---> <--->\n // ...--------><-----------------------------><---------....\n // previous frag matching fragment next frag\n // return -1 return 0 return 1\n // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);\n // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments\n let candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration);\n if ((candidate.start + candidate.duration - candidateLookupTolerance) <= bufferEnd) {\n return 1;\n } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n return -1;\n }\n\n return 0;\n };\n\n if (bufferEnd < end) {\n if (bufferEnd > end - maxFragLookUpTolerance) {\n maxFragLookUpTolerance = 0;\n }\n\n // Prefer the next fragment if it's within tolerance\n if (fragNext && !fragmentWithinToleranceTest(fragNext)) {\n foundFrag = fragNext;\n } else {\n foundFrag = BinarySearch.search(fragments, fragmentWithinToleranceTest);\n }\n } else {\n // reach end of playlist\n foundFrag = fragments[fragLen - 1];\n }\n if (foundFrag) {\n frag = foundFrag;\n start = foundFrag.start;\n // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);\n if (fragPrevious && frag.level === fragPrevious.level && frag.sn === fragPrevious.sn) {\n if (frag.sn < trackDetails.endSN) {\n frag = fragments[frag.sn + 1 - trackDetails.startSN];\n logger.log(`SN just loaded, load next one: ${frag.sn}`);\n } else {\n frag = null;\n }\n }\n }\n }\n if (frag) {\n // logger.log(' loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));\n if (frag.encrypted) {\n logger.log(`Loading key for ${frag.sn} of [${trackDetails.startSN} ,${trackDetails.endSN}],track ${trackId}`);\n this.state = State.KEY_LOADING;\n hls.trigger(Event.KEY_LOADING, { frag: frag });\n } else {\n logger.log(`Loading ${frag.sn}, cc: ${frag.cc} of [${trackDetails.startSN} ,${trackDetails.endSN}],track ${trackId}, currentTime:${pos},bufferEnd:${bufferEnd.toFixed(3)}`);\n // only load if fragment is not loaded or if in audio switch\n // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch\n this.fragCurrent = frag;\n if (audioSwitch || this.fragmentTracker.getState(frag) === FragmentState.NOT_LOADED) {\n if (frag.sn !== 'initSegment') {\n this.startFragRequested = true;\n }\n if (Number.isFinite(frag.sn)) {\n this.nextLoadPosition = frag.start + frag.duration;\n }\n\n hls.trigger(Event.FRAG_LOADING, { frag });\n this.state = State.FRAG_LOADING;\n }\n }\n }\n }\n break;\n case State.WAITING_TRACK:\n track = this.tracks[this.trackId];\n // check if playlist is already loaded\n if (track && track.details) {\n this.state = State.IDLE;\n }\n\n break;\n case State.FRAG_LOADING_WAITING_RETRY:\n var now = performance.now();\n var retryDate = this.retryDate;\n media = this.media;\n var isSeeking = media && media.seeking;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if (!retryDate || (now >= retryDate) || isSeeking) {\n logger.log('audioStreamController: retryDate reached, switch back to IDLE state');\n this.state = State.IDLE;\n }\n break;\n case State.WAITING_INIT_PTS:\n const videoTrackCC = this.videoTrackCC;\n if (this.initPTS[videoTrackCC] === undefined) {\n break;\n }\n\n // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS\n const waitingFrag = this.waitingFragment;\n if (waitingFrag) {\n const waitingFragCC = waitingFrag.frag.cc;\n if (videoTrackCC !== waitingFragCC) {\n track = this.tracks[this.trackId];\n if (track.details && track.details.live) {\n logger.warn(`Waiting fragment CC (${waitingFragCC}) does not match video track CC (${videoTrackCC})`);\n this.waitingFragment = null;\n this.state = State.IDLE;\n }\n } else {\n this.state = State.FRAG_LOADING;\n this.onFragLoaded(this.waitingFragment);\n this.waitingFragment = null;\n }\n } else {\n this.state = State.IDLE;\n }\n\n break;\n case State.STOPPED:\n case State.FRAG_LOADING:\n case State.PARSING:\n case State.PARSED:\n case State.ENDED:\n break;\n default:\n break;\n }\n }\n\n onMediaAttached (data) {\n let media = this.media = this.mediaBuffer = data.media;\n this.onvseeking = this.onMediaSeeking.bind(this);\n this.onvended = this.onMediaEnded.bind(this);\n media.addEventListener('seeking', this.onvseeking);\n media.addEventListener('ended', this.onvended);\n let config = this.config;\n if (this.tracks && config.autoStartLoad) {\n this.startLoad(config.startPosition);\n }\n }\n\n onMediaDetaching () {\n let media = this.media;\n if (media && media.ended) {\n logger.log('MSE detaching and video ended, reset startPosition');\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n // remove video listeners\n if (media) {\n media.removeEventListener('seeking', this.onvseeking);\n media.removeEventListener('ended', this.onvended);\n this.onvseeking = this.onvseeked = this.onvended = null;\n }\n this.media = this.mediaBuffer = this.videoBuffer = null;\n this.loadedmetadata = false;\n this.fragmentTracker.removeAllFragments();\n this.stopLoad();\n }\n\n onAudioTracksUpdated (data) {\n logger.log('audio tracks updated');\n this.tracks = data.audioTracks;\n }\n\n onAudioTrackSwitching (data) {\n // if any URL found on new audio track, it is an alternate audio track\n let altAudio = !!data.url;\n this.trackId = data.id;\n\n this.fragCurrent = null;\n this.state = State.PAUSED;\n this.waitingFragment = null;\n // destroy useless demuxer when switching audio to main\n if (!altAudio) {\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n } else {\n // switching to audio track, start timer if not already started\n this.setInterval(TICK_INTERVAL);\n }\n\n // should we switch tracks ?\n if (altAudio) {\n this.audioSwitch = true;\n // main audio track are handled by stream-controller, just do something if switching to alt audio track\n this.state = State.IDLE;\n }\n this.tick();\n }\n\n onAudioTrackLoaded (data) {\n let newDetails = data.details,\n trackId = data.id,\n track = this.tracks[trackId],\n duration = newDetails.totalduration,\n sliding = 0;\n\n logger.log(`track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}],duration:${duration}`);\n\n if (newDetails.live) {\n let curDetails = track.details;\n if (curDetails && newDetails.fragments.length > 0) {\n // we already have details for that level, merge them\n LevelHelper.mergeDetails(curDetails, newDetails);\n sliding = newDetails.fragments[0].start;\n // TODO\n // this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);\n if (newDetails.PTSKnown) {\n logger.log(`live audio playlist sliding:${sliding.toFixed(3)}`);\n } else {\n logger.log('live audio playlist - outdated PTS, unknown sliding');\n }\n } else {\n newDetails.PTSKnown = false;\n logger.log('live audio playlist - first load, unknown sliding');\n }\n } else {\n newDetails.PTSKnown = false;\n }\n track.details = newDetails;\n\n // compute start position\n if (!this.startFragRequested) {\n // compute start position if set to -1. use it straight away if value is defined\n if (this.startPosition === -1) {\n // first, check if start time offset has been set in playlist, if yes, use this value\n let startTimeOffset = newDetails.startTimeOffset;\n if (Number.isFinite(startTimeOffset)) {\n logger.log(`start time offset found in playlist, adjust startPosition to ${startTimeOffset}`);\n this.startPosition = startTimeOffset;\n } else {\n if (newDetails.live) {\n this.startPosition = this.computeLivePosition(sliding, newDetails);\n logger.log(`compute startPosition for audio-track to ${this.startPosition}`);\n } else {\n this.startPosition = 0;\n }\n }\n }\n this.nextLoadPosition = this.startPosition;\n }\n // only switch batck to IDLE state if we were waiting for track to start downloading a new fragment\n if (this.state === State.WAITING_TRACK) {\n this.state = State.IDLE;\n }\n\n // trigger handler right now\n this.tick();\n }\n\n onKeyLoaded () {\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n this.tick();\n }\n }\n\n onFragLoaded (data) {\n let fragCurrent = this.fragCurrent,\n fragLoaded = data.frag;\n if (this.state === State.FRAG_LOADING &&\n fragCurrent &&\n fragLoaded.type === 'audio' &&\n fragLoaded.level === fragCurrent.level &&\n fragLoaded.sn === fragCurrent.sn) {\n let track = this.tracks[this.trackId],\n details = track.details,\n duration = details.totalduration,\n trackId = fragCurrent.level,\n sn = fragCurrent.sn,\n cc = fragCurrent.cc,\n audioCodec = this.config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2',\n stats = this.stats = data.stats;\n if (sn === 'initSegment') {\n this.state = State.IDLE;\n\n stats.tparsed = stats.tbuffered = performance.now();\n details.initSegment.data = data.payload;\n this.hls.trigger(Event.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'audio' });\n this.tick();\n } else {\n this.state = State.PARSING;\n // transmux the MPEG-TS data to ISO-BMFF segments\n this.appended = false;\n if (!this.demuxer) {\n this.demuxer = new Demuxer(this.hls, 'audio');\n }\n\n // Check if we have video initPTS\n // If not we need to wait for it\n let initPTS = this.initPTS[cc];\n let initSegmentData = details.initSegment ? details.initSegment.data : [];\n if (details.initSegment || initPTS !== undefined) {\n this.pendingBuffering = true;\n logger.log(`Demuxing ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);\n // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)\n let accurateTimeOffset = false; // details.PTSKnown || !details.live;\n this.demuxer.push(data.payload, initSegmentData, audioCodec, null, fragCurrent, duration, accurateTimeOffset, initPTS);\n } else {\n logger.log(`unknown video PTS for continuity counter ${cc}, waiting for video PTS before demuxing audio frag ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);\n this.waitingFragment = data;\n this.state = State.WAITING_INIT_PTS;\n }\n }\n }\n this.fragLoadError = 0;\n }\n\n onFragParsingInitSegment (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'audio' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n let tracks = data.tracks, track;\n\n // delete any video track found on audio demuxer\n if (tracks.video) {\n delete tracks.video;\n }\n\n // include levelCodec in audio and video tracks\n track = tracks.audio;\n if (track) {\n track.levelCodec = track.codec;\n track.id = data.id;\n this.hls.trigger(Event.BUFFER_CODECS, tracks);\n logger.log(`audio track:audio,container:${track.container},codecs[level/parsed]=[${track.levelCodec}/${track.codec}]`);\n let initSegment = track.initSegment;\n if (initSegment) {\n let appendObj = { type: 'audio', data: initSegment, parent: 'audio', content: 'initSegment' };\n if (this.audioSwitch) {\n this.pendingData = [appendObj];\n } else {\n this.appended = true;\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n this.hls.trigger(Event.BUFFER_APPENDING, appendObj);\n }\n }\n // trigger handler right now\n this.tick();\n }\n }\n }\n\n onFragParsingData (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'audio' &&\n data.type === 'audio' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n let trackId = this.trackId,\n track = this.tracks[trackId],\n hls = this.hls;\n\n if (!Number.isFinite(data.endPTS)) {\n data.endPTS = data.startPTS + fragCurrent.duration;\n data.endDTS = data.startDTS + fragCurrent.duration;\n }\n\n fragCurrent.addElementaryStream(ElementaryStreamTypes.AUDIO);\n\n logger.log(`parsed ${data.type},PTS:[${data.startPTS.toFixed(3)},${data.endPTS.toFixed(3)}],DTS:[${data.startDTS.toFixed(3)}/${data.endDTS.toFixed(3)}],nb:${data.nb}`);\n LevelHelper.updateFragPTSDTS(track.details, fragCurrent, data.startPTS, data.endPTS);\n\n let audioSwitch = this.audioSwitch, media = this.media, appendOnBufferFlush = false;\n // Only flush audio from old audio tracks when PTS is known on new audio track\n if (audioSwitch) {\n if (media && media.readyState) {\n let currentTime = media.currentTime;\n logger.log('switching audio track : currentTime:' + currentTime);\n if (currentTime >= data.startPTS) {\n logger.log('switching audio track : flushing all audio');\n this.state = State.BUFFER_FLUSHING;\n hls.trigger(Event.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });\n appendOnBufferFlush = true;\n // Lets announce that the initial audio track switch flush occur\n this.audioSwitch = false;\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, { id: trackId });\n }\n } else {\n // Lets announce that the initial audio track switch flush occur\n this.audioSwitch = false;\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, { id: trackId });\n }\n }\n\n let pendingData = this.pendingData;\n\n if (!pendingData) {\n logger.warn('Apparently attempt to enqueue media payload without codec initialization data upfront');\n hls.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: null, fatal: true });\n return;\n }\n\n if (!this.audioSwitch) {\n [data.data1, data.data2].forEach(buffer => {\n if (buffer && buffer.length) {\n pendingData.push({ type: data.type, data: buffer, parent: 'audio', content: 'data' });\n }\n });\n if (!appendOnBufferFlush && pendingData.length) {\n pendingData.forEach(appendObj => {\n // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)\n // in that case it is useless to append following segments\n if (this.state === State.PARSING) {\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n this.hls.trigger(Event.BUFFER_APPENDING, appendObj);\n }\n });\n this.pendingData = [];\n this.appended = true;\n }\n }\n // trigger handler right now\n this.tick();\n }\n }\n\n onFragParsed (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'audio' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n this.stats.tparsed = performance.now();\n this.state = State.PARSED;\n this._checkAppendedParsed();\n }\n }\n\n onBufferReset () {\n // reset reference to sourcebuffers\n this.mediaBuffer = this.videoBuffer = null;\n this.loadedmetadata = false;\n }\n\n onBufferCreated (data) {\n let audioTrack = data.tracks.audio;\n if (audioTrack) {\n this.mediaBuffer = audioTrack.buffer;\n this.loadedmetadata = true;\n }\n if (data.tracks.video) {\n this.videoBuffer = data.tracks.video.buffer;\n }\n }\n\n onBufferAppended (data) {\n if (data.parent === 'audio') {\n const state = this.state;\n if (state === State.PARSING || state === State.PARSED) {\n // check if all buffers have been appended\n this.pendingBuffering = (data.pending > 0);\n this._checkAppendedParsed();\n }\n }\n }\n\n _checkAppendedParsed () {\n // trigger handler right now\n if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {\n let frag = this.fragCurrent, stats = this.stats, hls = this.hls;\n if (frag) {\n this.fragPrevious = frag;\n stats.tbuffered = performance.now();\n hls.trigger(Event.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'audio' });\n let media = this.mediaBuffer ? this.mediaBuffer : this.media;\n if (media) {\n logger.log(`audio buffered : ${TimeRanges.toString(media.buffered)}`);\n }\n if (this.audioSwitch && this.appended) {\n this.audioSwitch = false;\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, { id: this.trackId });\n }\n this.state = State.IDLE;\n }\n this.tick();\n }\n }\n\n onError (data) {\n let frag = data.frag;\n // don't handle frag error not related to audio fragment\n if (frag && frag.type !== 'audio') {\n return;\n }\n\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n const frag = data.frag;\n // don't handle frag error not related to audio fragment\n if (frag && frag.type !== 'audio') {\n break;\n }\n\n if (!data.fatal) {\n let loadError = this.fragLoadError;\n if (loadError) {\n loadError++;\n } else {\n loadError = 1;\n }\n\n const config = this.config;\n if (loadError <= config.fragLoadingMaxRetry) {\n this.fragLoadError = loadError;\n // exponential backoff capped to config.fragLoadingMaxRetryTimeout\n const delay = Math.min(Math.pow(2, loadError - 1) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);\n logger.warn(`AudioStreamController: frag loading failed, retry in ${delay} ms`);\n this.retryDate = performance.now() + delay;\n // retry loading state\n this.state = State.FRAG_LOADING_WAITING_RETRY;\n } else {\n logger.error(`AudioStreamController: ${data.details} reaches max retry, redispatch as fatal ...`);\n // switch error to fatal\n data.fatal = true;\n this.state = State.ERROR;\n }\n }\n break;\n case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:\n case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n // when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received\n if (this.state !== State.ERROR) {\n // if fatal error, stop processing, otherwise move to IDLE to retry loading\n this.state = data.fatal ? State.ERROR : State.IDLE;\n logger.warn(`AudioStreamController: ${data.details} while loading frag, now switching to ${this.state} state ...`);\n }\n break;\n case ErrorDetails.BUFFER_FULL_ERROR:\n // if in appending state\n if (data.parent === 'audio' && (this.state === State.PARSING || this.state === State.PARSED)) {\n const media = this.mediaBuffer,\n currentTime = this.media.currentTime,\n mediaBuffered = media && BufferHelper.isBuffered(media, currentTime) && BufferHelper.isBuffered(media, currentTime + 0.5);\n // reduce max buf len if current position is buffered\n if (mediaBuffered) {\n const config = this.config;\n if (config.maxMaxBufferLength >= config.maxBufferLength) {\n // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...\n config.maxMaxBufferLength /= 2;\n logger.warn(`AudioStreamController: reduce max buffer length to ${config.maxMaxBufferLength}s`);\n }\n this.state = State.IDLE;\n } else {\n // current position is not buffered, but browser is still complaining about buffer full error\n // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708\n // in that case flush the whole audio buffer to recover\n logger.warn('AudioStreamController: buffer full error also media.currentTime is not buffered, flush audio buffer');\n this.fragCurrent = null;\n // flush everything\n this.state = State.BUFFER_FLUSHING;\n this.hls.trigger(Event.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });\n }\n }\n break;\n default:\n break;\n }\n }\n\n onBufferFlushed () {\n let pendingData = this.pendingData;\n if (pendingData && pendingData.length) {\n logger.log('AudioStreamController: appending pending audio data after buffer flushed');\n pendingData.forEach(appendObj => {\n this.hls.trigger(Event.BUFFER_APPENDING, appendObj);\n });\n this.appended = true;\n this.pendingData = [];\n this.state = State.PARSED;\n } else {\n // move to IDLE once flush complete. this should trigger new fragment loading\n this.state = State.IDLE;\n // reset reference to frag\n this.fragPrevious = null;\n this.tick();\n }\n }\n}\nexport default AudioStreamController;\n","/**\n * Copyright 2013 vtt.js Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport default (function () {\n if (typeof window !== 'undefined' && window.VTTCue) {\n return window.VTTCue;\n }\n\n let autoKeyword = 'auto';\n let directionSetting = {\n '': true,\n lr: true,\n rl: true\n };\n let alignSetting = {\n start: true,\n middle: true,\n end: true,\n left: true,\n right: true\n };\n\n function findDirectionSetting (value) {\n if (typeof value !== 'string') {\n return false;\n }\n\n let dir = directionSetting[value.toLowerCase()];\n return dir ? value.toLowerCase() : false;\n }\n\n function findAlignSetting (value) {\n if (typeof value !== 'string') {\n return false;\n }\n\n let align = alignSetting[value.toLowerCase()];\n return align ? value.toLowerCase() : false;\n }\n\n function extend (obj) {\n let i = 1;\n for (; i < arguments.length; i++) {\n let cobj = arguments[i];\n for (let p in cobj) {\n obj[p] = cobj[p];\n }\n }\n\n return obj;\n }\n\n function VTTCue (startTime, endTime, text) {\n let cue = this;\n let baseObj = {};\n\n baseObj.enumerable = true;\n\n /**\n * Shim implementation specific properties. These properties are not in\n * the spec.\n */\n\n // Lets us know when the VTTCue's data has changed in such a way that we need\n // to recompute its display state. This lets us compute its display state\n // lazily.\n cue.hasBeenReset = false;\n\n /**\n * VTTCue and TextTrackCue properties\n * http://dev.w3.org/html5/webvtt/#vttcue-interface\n */\n\n let _id = '';\n let _pauseOnExit = false;\n let _startTime = startTime;\n let _endTime = endTime;\n let _text = text;\n let _region = null;\n let _vertical = '';\n let _snapToLines = true;\n let _line = 'auto';\n let _lineAlign = 'start';\n let _position = 50;\n let _positionAlign = 'middle';\n let _size = 50;\n let _align = 'middle';\n\n Object.defineProperty(cue, 'id', extend({}, baseObj, {\n get: function () {\n return _id;\n },\n set: function (value) {\n _id = '' + value;\n }\n }));\n\n Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {\n get: function () {\n return _pauseOnExit;\n },\n set: function (value) {\n _pauseOnExit = !!value;\n }\n }));\n\n Object.defineProperty(cue, 'startTime', extend({}, baseObj, {\n get: function () {\n return _startTime;\n },\n set: function (value) {\n if (typeof value !== 'number') {\n throw new TypeError('Start time must be set to a number.');\n }\n\n _startTime = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'endTime', extend({}, baseObj, {\n get: function () {\n return _endTime;\n },\n set: function (value) {\n if (typeof value !== 'number') {\n throw new TypeError('End time must be set to a number.');\n }\n\n _endTime = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'text', extend({}, baseObj, {\n get: function () {\n return _text;\n },\n set: function (value) {\n _text = '' + value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'region', extend({}, baseObj, {\n get: function () {\n return _region;\n },\n set: function (value) {\n _region = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'vertical', extend({}, baseObj, {\n get: function () {\n return _vertical;\n },\n set: function (value) {\n let setting = findDirectionSetting(value);\n // Have to check for false because the setting an be an empty string.\n if (setting === false) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n\n _vertical = setting;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {\n get: function () {\n return _snapToLines;\n },\n set: function (value) {\n _snapToLines = !!value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'line', extend({}, baseObj, {\n get: function () {\n return _line;\n },\n set: function (value) {\n if (typeof value !== 'number' && value !== autoKeyword) {\n throw new SyntaxError('An invalid number or illegal string was specified.');\n }\n\n _line = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {\n get: function () {\n return _lineAlign;\n },\n set: function (value) {\n let setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n\n _lineAlign = setting;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'position', extend({}, baseObj, {\n get: function () {\n return _position;\n },\n set: function (value) {\n if (value < 0 || value > 100) {\n throw new Error('Position must be between 0 and 100.');\n }\n\n _position = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {\n get: function () {\n return _positionAlign;\n },\n set: function (value) {\n let setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n\n _positionAlign = setting;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'size', extend({}, baseObj, {\n get: function () {\n return _size;\n },\n set: function (value) {\n if (value < 0 || value > 100) {\n throw new Error('Size must be between 0 and 100.');\n }\n\n _size = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'align', extend({}, baseObj, {\n get: function () {\n return _align;\n },\n set: function (value) {\n let setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n\n _align = setting;\n this.hasBeenReset = true;\n }\n }));\n\n /**\n * Other <track> spec defined properties\n */\n\n // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state\n cue.displayState = void 0;\n }\n\n /**\n * VTTCue methods\n */\n\n VTTCue.prototype.getCueAsHTML = function () {\n // Assume WebVTT.convertCueToDOMTree is on the global.\n let WebVTT = window.WebVTT;\n return WebVTT.convertCueToDOMTree(window, this.text);\n };\n\n return VTTCue;\n})();\n","/*\n * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js#L1716\n */\n\nimport VTTCue from './vttcue';\n\nconst StringDecoder = function StringDecoder () {\n return {\n decode: function (data) {\n if (!data) {\n return '';\n }\n\n if (typeof data !== 'string') {\n throw new Error('Error - expected string data.');\n }\n\n return decodeURIComponent(encodeURIComponent(data));\n }\n };\n};\n\nfunction VTTParser () {\n this.window = window;\n this.state = 'INITIAL';\n this.buffer = '';\n this.decoder = new StringDecoder();\n this.regionList = [];\n}\n\n// Try to parse input as a time stamp.\nfunction parseTimeStamp (input) {\n function computeSeconds (h, m, s, f) {\n return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;\n }\n\n let m = input.match(/^(\\d+):(\\d{2})(:\\d{2})?\\.(\\d{3})/);\n if (!m) {\n return null;\n }\n\n if (m[3]) {\n // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]\n return computeSeconds(m[1], m[2], m[3].replace(':', ''), m[4]);\n } else if (m[1] > 59) {\n // Timestamp takes the form of [hours]:[minutes].[milliseconds]\n // First position is hours as it's over 59.\n return computeSeconds(m[1], m[2], 0, m[4]);\n } else {\n // Timestamp takes the form of [minutes]:[seconds].[milliseconds]\n return computeSeconds(0, m[1], m[2], m[4]);\n }\n}\n\n// A settings object holds key/value pairs and will ignore anything but the first\n// assignment to a specific key.\nfunction Settings () {\n this.values = Object.create(null);\n}\n\nSettings.prototype = {\n // Only accept the first assignment to any key.\n set: function (k, v) {\n if (!this.get(k) && v !== '') {\n this.values[k] = v;\n }\n },\n // Return the value for a key, or a default value.\n // If 'defaultKey' is passed then 'dflt' is assumed to be an object with\n // a number of possible default values as properties where 'defaultKey' is\n // the key of the property that will be chosen; otherwise it's assumed to be\n // a single value.\n get: function (k, dflt, defaultKey) {\n if (defaultKey) {\n return this.has(k) ? this.values[k] : dflt[defaultKey];\n }\n\n return this.has(k) ? this.values[k] : dflt;\n },\n // Check whether we have a value for a key.\n has: function (k) {\n return k in this.values;\n },\n // Accept a setting if its one of the given alternatives.\n alt: function (k, v, a) {\n for (let n = 0; n < a.length; ++n) {\n if (v === a[n]) {\n this.set(k, v);\n break;\n }\n }\n },\n // Accept a setting if its a valid (signed) integer.\n integer: function (k, v) {\n if (/^-?\\d+$/.test(v)) { // integer\n this.set(k, parseInt(v, 10));\n }\n },\n // Accept a setting if its a valid percentage.\n percent: function (k, v) {\n let m;\n if ((m = v.match(/^([\\d]{1,3})(\\.[\\d]*)?%$/))) {\n v = parseFloat(v);\n if (v >= 0 && v <= 100) {\n this.set(k, v);\n return true;\n }\n }\n return false;\n }\n};\n\n// Helper function to parse input into groups separated by 'groupDelim', and\n// interprete each group as a key/value pair separated by 'keyValueDelim'.\nfunction parseOptions (input, callback, keyValueDelim, groupDelim) {\n let groups = groupDelim ? input.split(groupDelim) : [input];\n for (let i in groups) {\n if (typeof groups[i] !== 'string') {\n continue;\n }\n\n let kv = groups[i].split(keyValueDelim);\n if (kv.length !== 2) {\n continue;\n }\n\n let k = kv[0];\n let v = kv[1];\n callback(k, v);\n }\n}\n\nlet defaults = new VTTCue(0, 0, 0);\n// 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244\n// Safari doesn't yet support this change, but FF and Chrome do.\nlet center = defaults.align === 'middle' ? 'middle' : 'center';\n\nfunction parseCue (input, cue, regionList) {\n // Remember the original input if we need to throw an error.\n let oInput = input;\n // 4.1 WebVTT timestamp\n function consumeTimeStamp () {\n let ts = parseTimeStamp(input);\n if (ts === null) {\n throw new Error('Malformed timestamp: ' + oInput);\n }\n\n // Remove time stamp from input.\n input = input.replace(/^[^\\sa-zA-Z-]+/, '');\n return ts;\n }\n\n // 4.4.2 WebVTT cue settings\n function consumeCueSettings (input, cue) {\n let settings = new Settings();\n\n parseOptions(input, function (k, v) {\n switch (k) {\n case 'region':\n // Find the last region we parsed with the same region id.\n for (let i = regionList.length - 1; i >= 0; i--) {\n if (regionList[i].id === v) {\n settings.set(k, regionList[i].region);\n break;\n }\n }\n break;\n case 'vertical':\n settings.alt(k, v, ['rl', 'lr']);\n break;\n case 'line':\n var vals = v.split(','),\n vals0 = vals[0];\n settings.integer(k, vals0);\n if (settings.percent(k, vals0)) {\n settings.set('snapToLines', false);\n }\n\n settings.alt(k, vals0, ['auto']);\n if (vals.length === 2) {\n settings.alt('lineAlign', vals[1], ['start', center, 'end']);\n }\n\n break;\n case 'position':\n vals = v.split(',');\n settings.percent(k, vals[0]);\n if (vals.length === 2) {\n settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);\n }\n\n break;\n case 'size':\n settings.percent(k, v);\n break;\n case 'align':\n settings.alt(k, v, ['start', center, 'end', 'left', 'right']);\n break;\n }\n }, /:/, /\\s/);\n\n // Apply default values for any missing fields.\n cue.region = settings.get('region', null);\n cue.vertical = settings.get('vertical', '');\n let line = settings.get('line', 'auto');\n if (line === 'auto' && defaults.line === -1) {\n // set numeric line number for Safari\n line = -1;\n }\n cue.line = line;\n cue.lineAlign = settings.get('lineAlign', 'start');\n cue.snapToLines = settings.get('snapToLines', true);\n cue.size = settings.get('size', 100);\n cue.align = settings.get('align', center);\n let position = settings.get('position', 'auto');\n if (position === 'auto' && defaults.position === 50) {\n // set numeric position for Safari\n position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;\n }\n cue.position = position;\n }\n\n function skipWhitespace () {\n input = input.replace(/^\\s+/, '');\n }\n\n // 4.1 WebVTT cue timings.\n skipWhitespace();\n cue.startTime = consumeTimeStamp(); // (1) collect cue start time\n skipWhitespace();\n if (input.substr(0, 3) !== '-->') { // (3) next characters must match '-->'\n throw new Error('Malformed time stamp (time stamps must be separated by \\'-->\\'): ' +\n oInput);\n }\n input = input.substr(3);\n skipWhitespace();\n cue.endTime = consumeTimeStamp(); // (5) collect cue end time\n\n // 4.1 WebVTT cue settings list.\n skipWhitespace();\n consumeCueSettings(input, cue);\n}\n\nfunction fixLineBreaks (input) {\n return input.replace(/<br(?: \\/)?>/gi, '\\n');\n}\n\nVTTParser.prototype = {\n parse: function (data) {\n let self = this;\n\n // If there is no data then we won't decode it, but will just try to parse\n // whatever is in buffer already. This may occur in circumstances, for\n // example when flush() is called.\n if (data) {\n // Try to decode the data that we received.\n self.buffer += self.decoder.decode(data, { stream: true });\n }\n\n function collectNextLine () {\n let buffer = self.buffer;\n let pos = 0;\n\n buffer = fixLineBreaks(buffer);\n\n while (pos < buffer.length && buffer[pos] !== '\\r' && buffer[pos] !== '\\n') {\n ++pos;\n }\n\n let line = buffer.substr(0, pos);\n // Advance the buffer early in case we fail below.\n if (buffer[pos] === '\\r') {\n ++pos;\n }\n\n if (buffer[pos] === '\\n') {\n ++pos;\n }\n\n self.buffer = buffer.substr(pos);\n return line;\n }\n\n // 3.2 WebVTT metadata header syntax\n function parseHeader (input) {\n parseOptions(input, function (k, v) {\n switch (k) {\n case 'Region':\n // 3.3 WebVTT region metadata header syntax\n // console.log('parse region', v);\n // parseRegion(v);\n break;\n }\n }, /:/);\n }\n\n // 5.1 WebVTT file parsing.\n try {\n let line;\n if (self.state === 'INITIAL') {\n // We can't start parsing until we have the first line.\n if (!/\\r\\n|\\n/.test(self.buffer)) {\n return this;\n }\n\n line = collectNextLine();\n // strip of UTF-8 BOM if any\n // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8\n let m = line.match(/^()?WEBVTT([ \\t].*)?$/);\n if (!m || !m[0]) {\n throw new Error('Malformed WebVTT signature.');\n }\n\n self.state = 'HEADER';\n }\n\n let alreadyCollectedLine = false;\n while (self.buffer) {\n // We can't parse a line until we have the full line.\n if (!/\\r\\n|\\n/.test(self.buffer)) {\n return this;\n }\n\n if (!alreadyCollectedLine) {\n line = collectNextLine();\n } else {\n alreadyCollectedLine = false;\n }\n\n switch (self.state) {\n case 'HEADER':\n // 13-18 - Allow a header (metadata) under the WEBVTT line.\n if (/:/.test(line)) {\n parseHeader(line);\n } else if (!line) {\n // An empty line terminates the header and starts the body (cues).\n self.state = 'ID';\n }\n continue;\n case 'NOTE':\n // Ignore NOTE blocks.\n if (!line) {\n self.state = 'ID';\n }\n\n continue;\n case 'ID':\n // Check for the start of NOTE blocks.\n if (/^NOTE($|[ \\t])/.test(line)) {\n self.state = 'NOTE';\n break;\n }\n // 19-29 - Allow any number of line terminators, then initialize new cue values.\n if (!line) {\n continue;\n }\n\n self.cue = new VTTCue(0, 0, '');\n self.state = 'CUE';\n // 30-39 - Check if self line contains an optional identifier or timing data.\n if (line.indexOf('-->') === -1) {\n self.cue.id = line;\n continue;\n }\n // Process line as start of a cue.\n /* falls through */\n case 'CUE':\n // 40 - Collect cue timings and settings.\n try {\n parseCue(line, self.cue, self.regionList);\n } catch (e) {\n // In case of an error ignore rest of the cue.\n self.cue = null;\n self.state = 'BADCUE';\n continue;\n }\n self.state = 'CUETEXT';\n continue;\n case 'CUETEXT':\n var hasSubstring = line.indexOf('-->') !== -1;\n // 34 - If we have an empty line then report the cue.\n // 35 - If we have the special substring '-->' then report the cue,\n // but do not collect the line as we need to process the current\n // one as a new cue.\n if (!line || hasSubstring && (alreadyCollectedLine = true)) {\n // We are done parsing self cue.\n if (self.oncue) {\n self.oncue(self.cue);\n }\n\n self.cue = null;\n self.state = 'ID';\n continue;\n }\n if (self.cue.text) {\n self.cue.text += '\\n';\n }\n\n self.cue.text += line;\n continue;\n case 'BADCUE': // BADCUE\n // 54-62 - Collect and discard the remaining cue.\n if (!line) {\n self.state = 'ID';\n }\n\n continue;\n }\n }\n } catch (e) {\n // If we are currently parsing a cue, report what we have.\n if (self.state === 'CUETEXT' && self.cue && self.oncue) {\n self.oncue(self.cue);\n }\n\n self.cue = null;\n // Enter BADWEBVTT state if header was not parsed correctly otherwise\n // another exception occurred so enter BADCUE state.\n self.state = self.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';\n }\n return this;\n },\n flush: function () {\n let self = this;\n try {\n // Finish decoding the stream.\n self.buffer += self.decoder.decode();\n // Synthesize the end of the current cue or region.\n if (self.cue || self.state === 'HEADER') {\n self.buffer += '\\n\\n';\n self.parse();\n }\n // If we've flushed, parsed, and we're still on the INITIAL state then\n // that means we don't have enough of the stream to parse the first\n // line.\n if (self.state === 'INITIAL') {\n throw new Error('Malformed WebVTT signature.');\n }\n } catch (e) {\n throw e;\n }\n if (self.onflush) {\n self.onflush();\n }\n\n return this;\n }\n};\n\nexport { fixLineBreaks };\n\nexport default VTTParser;\n","import { fixLineBreaks } from './vttparser';\nimport { CaptionScreen, Row } from './cea-608-parser';\n\ninterface VTTCue extends TextTrackCue {\n new(start: number, end: number, cueText: string): VTTCue\n line: number\n align: string\n position: number\n}\n\nexport function newCue (track: TextTrack, startTime: number, endTime: number, captionScreen: CaptionScreen) {\n let row: Row;\n // the type data states this is VTTCue, but it can potentially be a TextTrackCue on old browsers\n let cue: VTTCue;\n let indenting: boolean;\n let indent: number;\n let text: string;\n let VTTCue: VTTCue = (window as any).VTTCue as VTTCue || TextTrackCue;\n\n for (let r = 0; r < captionScreen.rows.length; r++) {\n row = captionScreen.rows[r];\n indenting = true;\n indent = 0;\n text = '';\n\n if (!row.isEmpty()) {\n for (let c = 0; c < row.chars.length; c++) {\n if (row.chars[c].uchar.match(/\\s/) && indenting) {\n indent++;\n } else {\n text += row.chars[c].uchar;\n indenting = false;\n }\n }\n // To be used for cleaning-up orphaned roll-up captions\n row.cueStartTime = startTime;\n\n // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE\n if (startTime === endTime) {\n endTime += 0.0001;\n }\n\n cue = new VTTCue(startTime, endTime, fixLineBreaks(text.trim()));\n\n if (indent >= 16) {\n indent--;\n } else {\n indent++;\n }\n\n // VTTCue.line get's flakey when using controls, so let's now include line 13&14\n // also, drop line 1 since it's to close to the top\n if (navigator.userAgent.match(/Firefox\\//)) {\n cue.line = r + 1;\n } else {\n cue.line = (r > 7 ? r - 2 : r + 1);\n }\n\n cue.align = 'left';\n // Clamp the position between 0 and 100 - if out of these bounds, Firefox throws an exception and captions break\n cue.position = Math.max(0, Math.min(100, 100 * (indent / 32)));\n track.addCue(cue);\n }\n }\n}\n","import OutputFilter from './output-filter';\n\n/**\n *\n * This code was ported from the dash.js project at:\n * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js\n * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2\n *\n * The original copyright appears below:\n *\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2015-2016, DASH Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * 2. Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes\n */\n\nlet specialCea608CharsCodes = {\n 0x2a: 0xe1, // lowercase a, acute accent\n 0x5c: 0xe9, // lowercase e, acute accent\n 0x5e: 0xed, // lowercase i, acute accent\n 0x5f: 0xf3, // lowercase o, acute accent\n 0x60: 0xfa, // lowercase u, acute accent\n 0x7b: 0xe7, // lowercase c with cedilla\n 0x7c: 0xf7, // division symbol\n 0x7d: 0xd1, // uppercase N tilde\n 0x7e: 0xf1, // lowercase n tilde\n 0x7f: 0x2588, // Full block\n // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F\n // THIS MEANS THAT \\x50 MUST BE ADDED TO THE VALUES\n 0x80: 0xae, // Registered symbol (R)\n 0x81: 0xb0, // degree sign\n 0x82: 0xbd, // 1/2 symbol\n 0x83: 0xbf, // Inverted (open) question mark\n 0x84: 0x2122, // Trademark symbol (TM)\n 0x85: 0xa2, // Cents symbol\n 0x86: 0xa3, // Pounds sterling\n 0x87: 0x266a, // Music 8'th note\n 0x88: 0xe0, // lowercase a, grave accent\n 0x89: 0x20, // transparent space (regular)\n 0x8a: 0xe8, // lowercase e, grave accent\n 0x8b: 0xe2, // lowercase a, circumflex accent\n 0x8c: 0xea, // lowercase e, circumflex accent\n 0x8d: 0xee, // lowercase i, circumflex accent\n 0x8e: 0xf4, // lowercase o, circumflex accent\n 0x8f: 0xfb, // lowercase u, circumflex accent\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F\n 0x90: 0xc1, // capital letter A with acute\n 0x91: 0xc9, // capital letter E with acute\n 0x92: 0xd3, // capital letter O with acute\n 0x93: 0xda, // capital letter U with acute\n 0x94: 0xdc, // capital letter U with diaresis\n 0x95: 0xfc, // lowercase letter U with diaeresis\n 0x96: 0x2018, // opening single quote\n 0x97: 0xa1, // inverted exclamation mark\n 0x98: 0x2a, // asterisk\n 0x99: 0x2019, // closing single quote\n 0x9a: 0x2501, // box drawings heavy horizontal\n 0x9b: 0xa9, // copyright sign\n 0x9c: 0x2120, // Service mark\n 0x9d: 0x2022, // (round) bullet\n 0x9e: 0x201c, // Left double quotation mark\n 0x9f: 0x201d, // Right double quotation mark\n 0xa0: 0xc0, // uppercase A, grave accent\n 0xa1: 0xc2, // uppercase A, circumflex\n 0xa2: 0xc7, // uppercase C with cedilla\n 0xa3: 0xc8, // uppercase E, grave accent\n 0xa4: 0xca, // uppercase E, circumflex\n 0xa5: 0xcb, // capital letter E with diaresis\n 0xa6: 0xeb, // lowercase letter e with diaresis\n 0xa7: 0xce, // uppercase I, circumflex\n 0xa8: 0xcf, // uppercase I, with diaresis\n 0xa9: 0xef, // lowercase i, with diaresis\n 0xaa: 0xd4, // uppercase O, circumflex\n 0xab: 0xd9, // uppercase U, grave accent\n 0xac: 0xf9, // lowercase u, grave accent\n 0xad: 0xdb, // uppercase U, circumflex\n 0xae: 0xab, // left-pointing double angle quotation mark\n 0xaf: 0xbb, // right-pointing double angle quotation mark\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F\n 0xb0: 0xc3, // Uppercase A, tilde\n 0xb1: 0xe3, // Lowercase a, tilde\n 0xb2: 0xcd, // Uppercase I, acute accent\n 0xb3: 0xcc, // Uppercase I, grave accent\n 0xb4: 0xec, // Lowercase i, grave accent\n 0xb5: 0xd2, // Uppercase O, grave accent\n 0xb6: 0xf2, // Lowercase o, grave accent\n 0xb7: 0xd5, // Uppercase O, tilde\n 0xb8: 0xf5, // Lowercase o, tilde\n 0xb9: 0x7b, // Open curly brace\n 0xba: 0x7d, // Closing curly brace\n 0xbb: 0x5c, // Backslash\n 0xbc: 0x5e, // Caret\n 0xbd: 0x5f, // Underscore\n 0xbe: 0x7c, // Pipe (vertical line)\n 0xbf: 0x223c, // Tilde operator\n 0xc0: 0xc4, // Uppercase A, umlaut\n 0xc1: 0xe4, // Lowercase A, umlaut\n 0xc2: 0xd6, // Uppercase O, umlaut\n 0xc3: 0xf6, // Lowercase o, umlaut\n 0xc4: 0xdf, // Esszett (sharp S)\n 0xc5: 0xa5, // Yen symbol\n 0xc6: 0xa4, // Generic currency sign\n 0xc7: 0x2503, // Box drawings heavy vertical\n 0xc8: 0xc5, // Uppercase A, ring\n 0xc9: 0xe5, // Lowercase A, ring\n 0xca: 0xd8, // Uppercase O, stroke\n 0xcb: 0xf8, // Lowercase o, strok\n 0xcc: 0x250f, // Box drawings heavy down and right\n 0xcd: 0x2513, // Box drawings heavy down and left\n 0xce: 0x2517, // Box drawings heavy up and right\n 0xcf: 0x251b // Box drawings heavy up and left\n};\n\n/**\n * Utils\n */\nlet getCharForByte = function (byte: number) {\n let charCode = byte;\n if (specialCea608CharsCodes.hasOwnProperty(byte)) {\n charCode = specialCea608CharsCodes[byte];\n }\n\n return String.fromCharCode(charCode);\n};\n\nlet NR_ROWS = 15,\n NR_COLS = 100;\n// Tables to look up row from PAC data\nlet rowsLowCh1 = { 0x11: 1, 0x12: 3, 0x15: 5, 0x16: 7, 0x17: 9, 0x10: 11, 0x13: 12, 0x14: 14 };\nlet rowsHighCh1 = { 0x11: 2, 0x12: 4, 0x15: 6, 0x16: 8, 0x17: 10, 0x13: 13, 0x14: 15 };\nlet rowsLowCh2 = { 0x19: 1, 0x1A: 3, 0x1D: 5, 0x1E: 7, 0x1F: 9, 0x18: 11, 0x1B: 12, 0x1C: 14 };\nlet rowsHighCh2 = { 0x19: 2, 0x1A: 4, 0x1D: 6, 0x1E: 8, 0x1F: 10, 0x1B: 13, 0x1C: 15 };\n\nlet backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];\n\nenum VerboseFilter {\n ERROR = 0,\n TEXT = 1,\n WARNING = 2,\n INFO = 2,\n DEBUG = 3,\n DATA = 3,\n}\n\n/**\n * Simple logger class to be able to write with time-stamps and filter on level.\n */\nlet logger: {\n verboseFilter: {\n 'DATA': VerboseFilter.DATA;\n 'DEBUG': VerboseFilter.DEBUG;\n 'INFO': VerboseFilter.INFO;\n 'WARNING': VerboseFilter.WARNING;\n 'TEXT': VerboseFilter.TEXT;\n 'ERROR': VerboseFilter.ERROR;\n },\n time: number | null\n verboseLevel: VerboseFilter,\n setTime: (newTime: number | null) => void,\n log: (severity: keyof typeof VerboseFilter, msg: string) => void,\n} = {\n verboseFilter: { 'DATA': 3, 'DEBUG': 3, 'INFO': 2, 'WARNING': 2, 'TEXT': 1, 'ERROR': 0 },\n time: null,\n verboseLevel: 0, // Only write errors\n setTime: function (newTime) {\n this.time = newTime;\n },\n log: function (severity, msg) {\n let minLevel = this.verboseFilter[severity];\n if (this.verboseLevel >= minLevel) {\n // console.log(this.time + ' [' + severity + '] ' + msg);\n }\n }\n};\n\nlet numArrayToHexArray = function (numArray: number[]): string[] {\n let hexArray: string[] = [];\n for (let j = 0; j < numArray.length; j++) {\n hexArray.push(numArray[j].toString(16));\n }\n\n return hexArray;\n};\n\ntype PenStyles = {\n foreground: string | null,\n underline: boolean,\n italics: boolean,\n background: string,\n flash: boolean,\n};\n\nclass PenState {\n public foreground: string;\n public underline: boolean;\n public italics: boolean;\n public background: string;\n public flash: boolean;\n\n constructor (foreground?: string, underline?: boolean, italics?: boolean, background?: string, flash?: boolean) {\n this.foreground = foreground || 'white';\n this.underline = underline || false;\n this.italics = italics || false;\n this.background = background || 'black';\n this.flash = flash || false;\n }\n\n reset () {\n this.foreground = 'white';\n this.underline = false;\n this.italics = false;\n this.background = 'black';\n this.flash = false;\n }\n\n setStyles (styles: Partial<PenStyles>) {\n let attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];\n for (let i = 0; i < attribs.length; i++) {\n let style = attribs[i];\n if (styles.hasOwnProperty(style)) {\n this[style] = styles[style];\n }\n }\n }\n\n isDefault () {\n return (this.foreground === 'white' && !this.underline && !this.italics &&\n this.background === 'black' && !this.flash);\n }\n\n equals (other: PenState) {\n return ((this.foreground === other.foreground) &&\n (this.underline === other.underline) &&\n (this.italics === other.italics) &&\n (this.background === other.background) &&\n (this.flash === other.flash));\n }\n\n copy (newPenState: PenState) {\n this.foreground = newPenState.foreground;\n this.underline = newPenState.underline;\n this.italics = newPenState.italics;\n this.background = newPenState.background;\n this.flash = newPenState.flash;\n }\n\n toString (): string {\n return ('color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics +\n ', background=' + this.background + ', flash=' + this.flash);\n }\n}\n\n/**\n * Unicode character with styling and background.\n * @constructor\n */\nclass StyledUnicodeChar {\n uchar: string;\n penState: PenState;\n constructor (uchar?: string, foreground?: string, underline?: boolean, italics?: boolean, background?: string, flash?: boolean) {\n this.uchar = uchar || ' '; // unicode character\n this.penState = new PenState(foreground, underline, italics, background, flash);\n }\n\n reset () {\n this.uchar = ' ';\n this.penState.reset();\n }\n\n setChar (uchar: string, newPenState: PenState) {\n this.uchar = uchar;\n this.penState.copy(newPenState);\n }\n\n setPenState (newPenState: PenState) {\n this.penState.copy(newPenState);\n }\n\n equals (other: StyledUnicodeChar) {\n return this.uchar === other.uchar && this.penState.equals(other.penState);\n }\n\n copy (newChar: StyledUnicodeChar) {\n this.uchar = newChar.uchar;\n this.penState.copy(newChar.penState);\n }\n\n isEmpty (): boolean {\n return this.uchar === ' ' && this.penState.isDefault();\n }\n}\n\n/**\n * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.\n * @constructor\n */\nexport class Row {\n public chars: StyledUnicodeChar[];\n public pos: number;\n public currPenState: PenState;\n public cueStartTime?: number;\n constructor () {\n this.chars = [];\n for (let i = 0; i < NR_COLS; i++) {\n this.chars.push(new StyledUnicodeChar());\n }\n\n this.pos = 0;\n this.currPenState = new PenState();\n }\n\n equals (other: Row) {\n let equal = true;\n for (let i = 0; i < NR_COLS; i++) {\n if (!this.chars[i].equals(other.chars[i])) {\n equal = false;\n break;\n }\n }\n return equal;\n }\n\n copy (other: Row) {\n for (let i = 0; i < NR_COLS; i++) {\n this.chars[i].copy(other.chars[i]);\n }\n }\n\n isEmpty (): boolean {\n let empty = true;\n for (let i = 0; i < NR_COLS; i++) {\n if (!this.chars[i].isEmpty()) {\n empty = false;\n break;\n }\n }\n return empty;\n }\n\n /**\n * Set the cursor to a valid column.\n */\n setCursor (absPos: number) {\n if (this.pos !== absPos) {\n this.pos = absPos;\n }\n\n if (this.pos < 0) {\n logger.log('ERROR', 'Negative cursor position ' + this.pos);\n this.pos = 0;\n } else if (this.pos > NR_COLS) {\n logger.log('ERROR', 'Too large cursor position ' + this.pos);\n this.pos = NR_COLS;\n }\n }\n\n /**\n * Move the cursor relative to current position.\n */\n moveCursor (relPos: number) {\n let newPos = this.pos + relPos;\n if (relPos > 1) {\n for (let i = this.pos + 1; i < newPos + 1; i++) {\n this.chars[i].setPenState(this.currPenState);\n }\n }\n this.setCursor(newPos);\n }\n\n /**\n * Backspace, move one step back and clear character.\n */\n backSpace () {\n this.moveCursor(-1);\n this.chars[this.pos].setChar(' ', this.currPenState);\n }\n\n insertChar (byte: number) {\n if (byte >= 0x90) { // Extended char\n this.backSpace();\n }\n let char = getCharForByte(byte);\n if (this.pos >= NR_COLS) {\n logger.log('ERROR', 'Cannot insert ' + byte.toString(16) +\n ' (' + char + ') at position ' + this.pos + '. Skipping it!');\n return;\n }\n this.chars[this.pos].setChar(char, this.currPenState);\n this.moveCursor(1);\n }\n\n clearFromPos (startPos: number) {\n let i: number;\n for (i = startPos; i < NR_COLS; i++) {\n this.chars[i].reset();\n }\n }\n\n clear () {\n this.clearFromPos(0);\n this.pos = 0;\n this.currPenState.reset();\n }\n\n clearToEndOfRow () {\n this.clearFromPos(this.pos);\n }\n\n getTextString () {\n let chars: string[] = [];\n let empty = true;\n for (let i = 0; i < NR_COLS; i++) {\n let char = this.chars[i].uchar;\n if (char !== ' ') {\n empty = false;\n }\n\n chars.push(char);\n }\n if (empty) {\n return '';\n } else {\n return chars.join('');\n }\n }\n\n setPenStyles (styles: Partial<PenStyles>) {\n this.currPenState.setStyles(styles);\n let currChar = this.chars[this.pos];\n currChar.setPenState(this.currPenState);\n }\n}\n\n/**\n * Keep a CEA-608 screen of 32x15 styled characters\n * @constructor\n*/\nexport class CaptionScreen {\n rows: Row[];\n currRow: number;\n nrRollUpRows: number | null;\n lastOutputScreen: any;\n constructor () {\n this.rows = [];\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows.push(new Row());\n } // Note that we use zero-based numbering (0-14)\n\n this.currRow = NR_ROWS - 1;\n this.nrRollUpRows = null;\n this.reset();\n }\n\n reset () {\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n\n this.currRow = NR_ROWS - 1;\n }\n\n equals (other: CaptionScreen): boolean {\n let equal = true;\n for (let i = 0; i < NR_ROWS; i++) {\n if (!this.rows[i].equals(other.rows[i])) {\n equal = false;\n break;\n }\n }\n return equal;\n }\n\n copy (other: CaptionScreen) {\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].copy(other.rows[i]);\n }\n }\n\n isEmpty (): boolean {\n let empty = true;\n for (let i = 0; i < NR_ROWS; i++) {\n if (!this.rows[i].isEmpty()) {\n empty = false;\n break;\n }\n }\n return empty;\n }\n\n backSpace () {\n let row = this.rows[this.currRow];\n row.backSpace();\n }\n\n clearToEndOfRow () {\n let row = this.rows[this.currRow];\n row.clearToEndOfRow();\n }\n\n /**\n * Insert a character (without styling) in the current row.\n */\n insertChar (char: number) {\n let row = this.rows[this.currRow];\n row.insertChar(char);\n }\n\n setPen (styles: Partial<PenStyles>) {\n let row = this.rows[this.currRow];\n row.setPenStyles(styles);\n }\n\n moveCursor (relPos: number) {\n let row = this.rows[this.currRow];\n row.moveCursor(relPos);\n }\n\n setCursor (absPos: number) {\n logger.log('INFO', 'setCursor: ' + absPos);\n let row = this.rows[this.currRow];\n row.setCursor(absPos);\n }\n\n setPAC (pacData: PACData) {\n logger.log('INFO', 'pacData = ' + JSON.stringify(pacData));\n let newRow = pacData.row - 1;\n if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {\n newRow = this.nrRollUpRows - 1;\n }\n\n // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows\n if (this.nrRollUpRows && this.currRow !== newRow) {\n // clear all rows first\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n\n // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location\n // topRowIndex - the start of rows to copy (inclusive index)\n let topRowIndex = this.currRow + 1 - (this.nrRollUpRows);\n // We only copy if the last position was already shown.\n // We use the cueStartTime value to check this.\n const lastOutputScreen = this.lastOutputScreen as any;\n if (lastOutputScreen) {\n let prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;\n if (prevLineTime && logger.time && prevLineTime < logger.time) {\n for (let i = 0; i < this.nrRollUpRows; i++) {\n this.rows[newRow - this.nrRollUpRows + i + 1].copy(lastOutputScreen.rows[topRowIndex + i]);\n }\n }\n }\n }\n\n this.currRow = newRow;\n let row = this.rows[this.currRow];\n if (pacData.indent !== null) {\n let indent = pacData.indent;\n let prevPos = Math.max(indent - 1, 0);\n row.setCursor(pacData.indent);\n pacData.color = row.chars[prevPos].penState.foreground;\n }\n let styles: PenStyles = { foreground: pacData.color, underline: pacData.underline, italics: pacData.italics, background: 'black', flash: false };\n this.setPen(styles);\n }\n\n /**\n * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).\n */\n setBkgData (bkgData: Partial<PenStyles>) {\n logger.log('INFO', 'bkgData = ' + JSON.stringify(bkgData));\n this.backSpace();\n this.setPen(bkgData);\n this.insertChar(0x20); // Space\n }\n\n setRollUpRows (nrRows: number | null) {\n this.nrRollUpRows = nrRows;\n }\n\n rollUp () {\n if (this.nrRollUpRows === null) {\n logger.log('DEBUG', 'roll_up but nrRollUpRows not set yet');\n return; // Not properly setup\n }\n logger.log('TEXT', this.getDisplayText());\n let topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n let topRow = this.rows.splice(topRowIndex, 1)[0];\n topRow.clear();\n this.rows.splice(this.currRow, 0, topRow);\n logger.log('INFO', 'Rolling up');\n // logger.log('TEXT', this.get_display_text())\n }\n\n /**\n * Get all non-empty rows with as unicode text.\n */\n getDisplayText (asOneRow?: boolean) {\n asOneRow = asOneRow || false;\n let displayText: string[] = [];\n let text = '';\n let rowNr = -1;\n for (let i = 0; i < NR_ROWS; i++) {\n let rowText = this.rows[i].getTextString();\n if (rowText) {\n rowNr = i + 1;\n if (asOneRow) {\n displayText.push('Row ' + rowNr + ': \\'' + rowText + '\\'');\n } else {\n displayText.push(rowText.trim());\n }\n }\n }\n if (displayText.length > 0) {\n if (asOneRow) {\n text = '[' + displayText.join(' | ') + ']';\n } else {\n text = displayText.join('\\n');\n }\n }\n return text;\n }\n\n getTextAndFormat () {\n return this.rows;\n }\n}\n\n// var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];\n\ntype CaptionModes = 'MODE_ROLL-UP' | 'MODE_POP-ON' | 'MODE_PAINT-ON' | 'MODE_TEXT' | null;\n\nclass Cea608Channel {\n chNr: number;\n outputFilter: OutputFilter;\n mode: CaptionModes;\n verbose: number;\n displayedMemory: CaptionScreen;\n nonDisplayedMemory: CaptionScreen;\n lastOutputScreen: CaptionScreen;\n currRollUpRow: Row;\n writeScreen: CaptionScreen;\n cueStartTime: number | null;\n lastCueEndTime: null;\n constructor (channelNumber: number, outputFilter: OutputFilter) {\n this.chNr = channelNumber;\n this.outputFilter = outputFilter;\n this.mode = null;\n this.verbose = 0;\n this.displayedMemory = new CaptionScreen();\n this.nonDisplayedMemory = new CaptionScreen();\n this.lastOutputScreen = new CaptionScreen();\n this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];\n this.writeScreen = this.displayedMemory;\n this.mode = null;\n this.cueStartTime = null; // Keeps track of where a cue started.\n }\n\n reset () {\n this.mode = null;\n this.displayedMemory.reset();\n this.nonDisplayedMemory.reset();\n this.lastOutputScreen.reset();\n this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];\n this.writeScreen = this.displayedMemory;\n this.mode = null;\n this.cueStartTime = null;\n }\n\n getHandler (): OutputFilter {\n return this.outputFilter;\n }\n\n setHandler (newHandler: OutputFilter) {\n this.outputFilter = newHandler;\n }\n\n setPAC (pacData: PACData) {\n this.writeScreen.setPAC(pacData);\n }\n\n setBkgData (bkgData: Partial<PenStyles>) {\n this.writeScreen.setBkgData(bkgData);\n }\n\n setMode (newMode: CaptionModes) {\n if (newMode === this.mode) {\n return;\n }\n\n this.mode = newMode;\n logger.log('INFO', 'MODE=' + newMode);\n if (this.mode === 'MODE_POP-ON') {\n this.writeScreen = this.nonDisplayedMemory;\n } else {\n this.writeScreen = this.displayedMemory;\n this.writeScreen.reset();\n }\n if (this.mode !== 'MODE_ROLL-UP') {\n this.displayedMemory.nrRollUpRows = null;\n this.nonDisplayedMemory.nrRollUpRows = null;\n }\n this.mode = newMode;\n }\n\n insertChars (chars: number[]) {\n for (let i = 0; i < chars.length; i++) {\n this.writeScreen.insertChar(chars[i]);\n }\n\n let screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';\n logger.log('INFO', screen + ': ' + this.writeScreen.getDisplayText(true));\n if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {\n logger.log('TEXT', 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));\n this.outputDataUpdate();\n }\n }\n\n ccRCL () { // Resume Caption Loading (switch mode to Pop On)\n logger.log('INFO', 'RCL - Resume Caption Loading');\n this.setMode('MODE_POP-ON');\n }\n\n ccBS () { // BackSpace\n logger.log('INFO', 'BS - BackSpace');\n if (this.mode === 'MODE_TEXT') {\n return;\n }\n\n this.writeScreen.backSpace();\n if (this.writeScreen === this.displayedMemory) {\n this.outputDataUpdate();\n }\n }\n\n ccAOF () { // Reserved (formerly Alarm Off)\n\n }\n\n ccAON () { // Reserved (formerly Alarm On)\n\n }\n\n ccDER () { // Delete to End of Row\n logger.log('INFO', 'DER- Delete to End of Row');\n this.writeScreen.clearToEndOfRow();\n this.outputDataUpdate();\n }\n\n ccRU (nrRows: number | null) { // Roll-Up Captions-2,3,or 4 Rows\n logger.log('INFO', 'RU(' + nrRows + ') - Roll Up');\n this.writeScreen = this.displayedMemory;\n this.setMode('MODE_ROLL-UP');\n this.writeScreen.setRollUpRows(nrRows);\n }\n\n ccFON () { // Flash On\n logger.log('INFO', 'FON - Flash On');\n this.writeScreen.setPen({ flash: true });\n }\n\n ccRDC () { // Resume Direct Captioning (switch mode to PaintOn)\n logger.log('INFO', 'RDC - Resume Direct Captioning');\n this.setMode('MODE_PAINT-ON');\n }\n\n ccTR () { // Text Restart in text mode (not supported, however)\n logger.log('INFO', 'TR');\n this.setMode('MODE_TEXT');\n }\n\n ccRTD () { // Resume Text Display in Text mode (not supported, however)\n logger.log('INFO', 'RTD');\n this.setMode('MODE_TEXT');\n }\n\n ccEDM () { // Erase Displayed Memory\n logger.log('INFO', 'EDM - Erase Displayed Memory');\n this.displayedMemory.reset();\n this.outputDataUpdate(true);\n }\n\n ccCR () { // Carriage Return\n logger.log('INFO', 'CR - Carriage Return');\n this.writeScreen.rollUp();\n this.outputDataUpdate(true);\n }\n\n ccENM () { // Erase Non-Displayed Memory\n logger.log('INFO', 'ENM - Erase Non-displayed Memory');\n this.nonDisplayedMemory.reset();\n }\n\n ccEOC () { // End of Caption (Flip Memories)\n logger.log('INFO', 'EOC - End Of Caption');\n if (this.mode === 'MODE_POP-ON') {\n let tmp = this.displayedMemory;\n this.displayedMemory = this.nonDisplayedMemory;\n this.nonDisplayedMemory = tmp;\n this.writeScreen = this.nonDisplayedMemory;\n logger.log('TEXT', 'DISP: ' + this.displayedMemory.getDisplayText());\n }\n this.outputDataUpdate(true);\n }\n\n ccTO (nrCols: number) { // Tab Offset 1,2, or 3 columns\n logger.log('INFO', 'TO(' + nrCols + ') - Tab Offset');\n this.writeScreen.moveCursor(nrCols);\n }\n\n ccMIDROW (secondByte: number) { // Parse MIDROW command\n let styles: Partial<PenStyles> = { flash: false };\n styles.underline = secondByte % 2 === 1;\n styles.italics = secondByte >= 0x2e;\n if (!styles.italics) {\n let colorIndex = Math.floor(secondByte / 2) - 0x10;\n let colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];\n styles.foreground = colors[colorIndex];\n } else {\n styles.foreground = 'white';\n }\n logger.log('INFO', 'MIDROW: ' + JSON.stringify(styles));\n this.writeScreen.setPen(styles);\n }\n\n outputDataUpdate (dispatch = false) {\n let t = logger.time;\n if (t === null) {\n return;\n }\n\n if (this.outputFilter) {\n if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) { // Start of a new cue\n this.cueStartTime = t;\n } else {\n if (!this.displayedMemory.equals(this.lastOutputScreen)) {\n this.outputFilter.newCue(this.cueStartTime!, t, this.lastOutputScreen);\n if (dispatch && this.outputFilter.dispatchCue) {\n this.outputFilter.dispatchCue();\n }\n\n this.cueStartTime = this.displayedMemory.isEmpty() ? null : t;\n }\n }\n this.lastOutputScreen.copy(this.displayedMemory);\n }\n }\n\n cueSplitAtTime (t: number) {\n if (this.outputFilter) {\n if (!this.displayedMemory.isEmpty()) {\n if (this.outputFilter.newCue) {\n this.outputFilter.newCue(this.cueStartTime!, t, this.displayedMemory);\n }\n\n this.cueStartTime = t;\n }\n }\n }\n}\n\ninterface PACData {\n row: number;\n indent: number | null;\n color: string | null;\n underline: boolean;\n italics: boolean;\n}\n\nclass Cea608Parser {\n field: number;\n outputs: OutputFilter[];\n channels: Cea608Channel[];\n currChNr: number;\n lastCmdA: number | null;\n lastCmdB: number | null;\n lastTime: number | null;\n dataCounters: { 'padding': number; 'char': number; 'cmd': number; 'other': number; };\n constructor (field: number, out1: OutputFilter, out2: OutputFilter) {\n this.field = field || 1;\n this.outputs = [out1, out2];\n this.channels = [new Cea608Channel(1, out1), new Cea608Channel(2, out2)];\n this.currChNr = -1; // Will be 1 or 2\n this.lastCmdA = null; // First byte of last command\n this.lastCmdB = null; // Second byte of last command\n this.lastTime = null;\n this.dataCounters = { 'padding': 0, 'char': 0, 'cmd': 0, 'other': 0 };\n }\n\n getHandler (index: number) {\n return this.channels[index].getHandler();\n }\n\n setHandler (index: number, newHandler: OutputFilter) {\n this.channels[index].setHandler(newHandler);\n }\n\n /**\n * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.\n */\n addData (t: number | null, byteList: number[]) {\n let cmdFound: boolean, a: number, b: number,\n charsFound: number[] | boolean | null = false;\n\n this.lastTime = t;\n logger.setTime(t);\n\n for (let i = 0; i < byteList.length; i += 2) {\n a = byteList[i] & 0x7f;\n b = byteList[i + 1] & 0x7f;\n if (a === 0 && b === 0) {\n this.dataCounters.padding += 2;\n continue;\n } else {\n logger.log('DATA', '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');\n }\n cmdFound = this.parseCmd(a, b);\n if (!cmdFound) {\n cmdFound = this.parseMidrow(a, b);\n }\n\n if (!cmdFound) {\n cmdFound = this.parsePAC(a, b);\n }\n\n if (!cmdFound) {\n cmdFound = this.parseBackgroundAttributes(a, b);\n }\n\n if (!cmdFound) {\n charsFound = this.parseChars(a, b);\n if (charsFound) {\n if (this.currChNr && this.currChNr >= 0) {\n let channel = this.channels[this.currChNr - 1];\n channel.insertChars(charsFound);\n } else {\n logger.log('WARNING', 'No channel found yet. TEXT-MODE?');\n }\n }\n }\n if (cmdFound) {\n this.dataCounters.cmd += 2;\n } else if (charsFound) {\n this.dataCounters.char += 2;\n } else {\n this.dataCounters.other += 2;\n logger.log('WARNING', 'Couldn\\'t parse cleaned data ' + numArrayToHexArray([a, b]) +\n ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));\n }\n }\n }\n\n /**\n * Parse Command.\n * @returns {Boolean} Tells if a command was found\n */\n parseCmd (a: number, b: number): boolean {\n let chNr: number | null = null;\n\n let cond1 = (a === 0x14 || a === 0x1C) && (b >= 0x20 && b <= 0x2F);\n let cond2 = (a === 0x17 || a === 0x1F) && (b >= 0x21 && b <= 0x23);\n if (!(cond1 || cond2)) {\n return false;\n }\n\n if (a === this.lastCmdA && b === this.lastCmdB) {\n this.lastCmdA = null;\n this.lastCmdB = null; // Repeated commands are dropped (once)\n logger.log('DEBUG', 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');\n return true;\n }\n\n if (a === 0x14 || a === 0x17) {\n chNr = 1;\n } else {\n chNr = 2;\n } // (a === 0x1C || a=== 0x1f)\n\n let channel = this.channels[chNr - 1];\n\n if (a === 0x14 || a === 0x1C) {\n if (b === 0x20) {\n channel.ccRCL();\n } else if (b === 0x21) {\n channel.ccBS();\n } else if (b === 0x22) {\n channel.ccAOF();\n } else if (b === 0x23) {\n channel.ccAON();\n } else if (b === 0x24) {\n channel.ccDER();\n } else if (b === 0x25) {\n channel.ccRU(2);\n } else if (b === 0x26) {\n channel.ccRU(3);\n } else if (b === 0x27) {\n channel.ccRU(4);\n } else if (b === 0x28) {\n channel.ccFON();\n } else if (b === 0x29) {\n channel.ccRDC();\n } else if (b === 0x2A) {\n channel.ccTR();\n } else if (b === 0x2B) {\n channel.ccRTD();\n } else if (b === 0x2C) {\n channel.ccEDM();\n } else if (b === 0x2D) {\n channel.ccCR();\n } else if (b === 0x2E) {\n channel.ccENM();\n } else if (b === 0x2F) {\n channel.ccEOC();\n }\n } else { // a == 0x17 || a == 0x1F\n channel.ccTO(b - 0x20);\n }\n this.lastCmdA = a;\n this.lastCmdB = b;\n this.currChNr = chNr;\n return true;\n }\n\n /**\n * Parse midrow styling command\n * @returns {Boolean}\n */\n parseMidrow (a: number, b: number): boolean {\n let chNr: number | null = null;\n\n if (((a === 0x11) || (a === 0x19)) && b >= 0x20 && b <= 0x2f) {\n if (a === 0x11) {\n chNr = 1;\n } else {\n chNr = 2;\n }\n\n if (chNr !== this.currChNr) {\n logger.log('ERROR', 'Mismatch channel in midrow parsing');\n return false;\n }\n let channel = this.channels[chNr - 1];\n channel.ccMIDROW(b);\n logger.log('DEBUG', 'MIDROW (' + numArrayToHexArray([a, b]) + ')');\n return true;\n }\n return false;\n }\n /**\n * Parse Preable Access Codes (Table 53).\n * @returns {Boolean} Tells if PAC found\n */\n parsePAC (a: number, b: number): boolean {\n let chNr: number | null = null;\n let row: number | null = null;\n\n let case1 = ((a >= 0x11 && a <= 0x17) || (a >= 0x19 && a <= 0x1F)) && (b >= 0x40 && b <= 0x7F);\n let case2 = (a === 0x10 || a === 0x18) && (b >= 0x40 && b <= 0x5F);\n if (!(case1 || case2)) {\n return false;\n }\n\n if (a === this.lastCmdA && b === this.lastCmdB) {\n this.lastCmdA = null;\n this.lastCmdB = null;\n return true; // Repeated commands are dropped (once)\n }\n\n chNr = (a <= 0x17) ? 1 : 2;\n\n if (b >= 0x40 && b <= 0x5F) {\n row = (chNr === 1) ? rowsLowCh1[a] : rowsLowCh2[a];\n } else { // 0x60 <= b <= 0x7F\n row = (chNr === 1) ? rowsHighCh1[a] : rowsHighCh2[a];\n }\n let pacData = this.interpretPAC(row!, b);\n let channel = this.channels[chNr - 1];\n channel.setPAC(pacData);\n this.lastCmdA = a;\n this.lastCmdB = b;\n this.currChNr = chNr;\n return true;\n }\n\n /**\n * Interpret the second byte of the pac, and return the information.\n * @returns {Object} pacData with style parameters.\n */\n interpretPAC (row: number, byte: number): PACData {\n let pacIndex = byte;\n let pacData: PACData = { color: null, italics: false, indent: null, underline: false, row: row };\n\n if (byte > 0x5F) {\n pacIndex = byte - 0x60;\n } else {\n pacIndex = byte - 0x40;\n }\n\n pacData.underline = (pacIndex & 1) === 1;\n if (pacIndex <= 0xd) {\n pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];\n } else if (pacIndex <= 0xf) {\n pacData.italics = true;\n pacData.color = 'white';\n } else {\n pacData.indent = (Math.floor((pacIndex - 0x10) / 2)) * 4;\n }\n return pacData; // Note that row has zero offset. The spec uses 1.\n }\n\n /**\n * Parse characters.\n * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.\n */\n parseChars (a: number, b: number): number[] | null {\n let channelNr: number | null = null,\n charCodes: number[] | null = null,\n charCode1: number | null = null;\n\n if (a >= 0x19) {\n channelNr = 2;\n charCode1 = a - 8;\n } else {\n channelNr = 1;\n charCode1 = a;\n }\n if (charCode1 >= 0x11 && charCode1 <= 0x13) {\n // Special character\n let oneCode = b;\n if (charCode1 === 0x11) {\n oneCode = b + 0x50;\n } else if (charCode1 === 0x12) {\n oneCode = b + 0x70;\n } else {\n oneCode = b + 0x90;\n }\n\n logger.log('INFO', 'Special char \\'' + getCharForByte(oneCode) + '\\' in channel ' + channelNr);\n charCodes = [oneCode];\n } else if (a >= 0x20 && a <= 0x7f) {\n charCodes = (b === 0) ? [a] : [a, b];\n }\n if (charCodes) {\n let hexCodes = numArrayToHexArray(charCodes);\n logger.log('DEBUG', 'Char codes = ' + hexCodes.join(','));\n this.lastCmdA = null;\n this.lastCmdB = null;\n }\n return charCodes;\n }\n\n /**\n * Parse extended background attributes as well as new foreground color black.\n * @returns {Boolean} Tells if background attributes are found\n */\n parseBackgroundAttributes (a: number, b: number): boolean {\n let bkgData: Partial<PenStyles>,\n index: number,\n chNr: number,\n channel: Cea608Channel;\n\n let case1 = (a === 0x10 || a === 0x18) && (b >= 0x20 && b <= 0x2f);\n let case2 = (a === 0x17 || a === 0x1f) && (b >= 0x2d && b <= 0x2f);\n if (!(case1 || case2)) {\n return false;\n }\n\n bkgData = {};\n if (a === 0x10 || a === 0x18) {\n index = Math.floor((b - 0x20) / 2);\n bkgData.background = backgroundColors[index];\n if (b % 2 === 1) {\n bkgData.background = bkgData.background + '_semi';\n }\n } else if (b === 0x2d) {\n bkgData.background = 'transparent';\n } else {\n bkgData.foreground = 'black';\n if (b === 0x2f) {\n bkgData.underline = true;\n }\n }\n chNr = (a < 0x18) ? 1 : 2;\n channel = this.channels[chNr - 1];\n channel.setBkgData(bkgData);\n this.lastCmdA = null;\n this.lastCmdB = null;\n return true;\n }\n\n /**\n * Reset state of parser and its channels.\n */\n reset () {\n for (let i = 0; i < this.channels.length; i++) {\n if (this.channels[i]) {\n this.channels[i].reset();\n }\n }\n this.lastCmdA = null;\n this.lastCmdB = null;\n }\n\n /**\n * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.\n */\n cueSplitAtTime (t: number) {\n for (let i = 0; i < this.channels.length; i++) {\n if (this.channels[i]) {\n this.channels[i].cueSplitAtTime(t);\n }\n }\n }\n}\n\nexport default Cea608Parser;\n","import { CaptionScreen } from './cea-608-parser';\n\nexport default class OutputFilter {\n timelineController: any;\n trackName: string;\n startTime: number | null;\n endTime: number | null;\n screen: CaptionScreen | null;\n\n // TODO(typescript-timelineController)\n constructor (timelineController: any, trackName: string) {\n this.timelineController = timelineController;\n this.trackName = trackName;\n this.startTime = null;\n this.endTime = null;\n this.screen = null;\n }\n\n dispatchCue () {\n if (this.startTime === null) {\n return;\n }\n\n this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen);\n this.startTime = null;\n }\n\n newCue (startTime: number, endTime: number, screen: CaptionScreen) {\n if (this.startTime === null || this.startTime > startTime) {\n this.startTime = startTime;\n }\n\n this.endTime = endTime;\n this.screen = screen;\n this.timelineController.createCaptionsTrack(this.trackName);\n }\n}\n","import VTTParser from './vttparser';\nimport { utf8ArrayToStr } from '../demux/id3';\n\n// String.prototype.startsWith is not supported in IE11\nconst startsWith = function (inputString, searchString, position) {\n return inputString.substr(position || 0, searchString.length) === searchString;\n};\n\nconst cueString2millis = function (timeString) {\n let ts = parseInt(timeString.substr(-3));\n let secs = parseInt(timeString.substr(-6, 2));\n let mins = parseInt(timeString.substr(-9, 2));\n let hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0;\n\n if (!Number.isFinite(ts) || !Number.isFinite(secs) || !Number.isFinite(mins) || !Number.isFinite(hours)) {\n throw Error(`Malformed X-TIMESTAMP-MAP: Local:${timeString}`);\n }\n\n ts += 1000 * secs;\n ts += 60 * 1000 * mins;\n ts += 60 * 60 * 1000 * hours;\n\n return ts;\n};\n\n// From https://github.com/darkskyapp/string-hash\nconst hash = function (text) {\n let hash = 5381;\n let i = text.length;\n while (i) {\n hash = (hash * 33) ^ text.charCodeAt(--i);\n }\n\n return (hash >>> 0).toString();\n};\n\nconst calculateOffset = function (vttCCs, cc, presentationTime) {\n let currCC = vttCCs[cc];\n let prevCC = vttCCs[currCC.prevCC];\n\n // This is the first discontinuity or cues have been processed since the last discontinuity\n // Offset = current discontinuity time\n if (!prevCC || (!prevCC.new && currCC.new)) {\n vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;\n currCC.new = false;\n return;\n }\n\n // There have been discontinuities since cues were last parsed.\n // Offset = time elapsed\n while (prevCC && prevCC.new) {\n vttCCs.ccOffset += currCC.start - prevCC.start;\n currCC.new = false;\n currCC = prevCC;\n prevCC = vttCCs[currCC.prevCC];\n }\n\n vttCCs.presentationOffset = presentationTime;\n};\n\nconst WebVTTParser = {\n parse: function (vttByteArray, syncPTS, vttCCs, cc, callBack, errorCallBack) {\n // Convert byteArray into string, replacing any somewhat exotic linefeeds with \"\\n\", then split on that character.\n let re = /\\r\\n|\\n\\r|\\n|\\r/g;\n // Uint8Array.prototype.reduce is not implemented in IE11\n let vttLines = utf8ArrayToStr(new Uint8Array(vttByteArray)).trim().replace(re, '\\n').split('\\n');\n\n let cueTime = '00:00.000';\n let mpegTs = 0;\n let localTime = 0;\n let presentationTime = 0;\n let cues = [];\n let parsingError;\n let inHeader = true;\n let timestampMap = false;\n // let VTTCue = VTTCue || window.TextTrackCue;\n\n // Create parser object using VTTCue with TextTrackCue fallback on certain browsers.\n let parser = new VTTParser();\n\n parser.oncue = function (cue) {\n // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.\n let currCC = vttCCs[cc];\n let cueOffset = vttCCs.ccOffset;\n\n // Update offsets for new discontinuities\n if (currCC && currCC.new) {\n if (localTime !== undefined) {\n // When local time is provided, offset = discontinuity start time - local time\n cueOffset = vttCCs.ccOffset = currCC.start;\n } else {\n calculateOffset(vttCCs, cc, presentationTime);\n }\n }\n\n if (presentationTime) {\n // If we have MPEGTS, offset = presentation time + discontinuity offset\n cueOffset = presentationTime - vttCCs.presentationOffset;\n }\n\n if (timestampMap) {\n cue.startTime += cueOffset - localTime;\n cue.endTime += cueOffset - localTime;\n }\n\n // Create a unique hash id for a cue based on start/end times and text.\n // This helps timeline-controller to avoid showing repeated captions.\n cue.id = hash(cue.startTime.toString()) + hash(cue.endTime.toString()) + hash(cue.text);\n\n // Fix encoding of special characters. TODO: Test with all sorts of weird characters.\n cue.text = decodeURIComponent(encodeURIComponent(cue.text));\n if (cue.endTime > 0) {\n cues.push(cue);\n }\n };\n\n parser.onparsingerror = function (e) {\n parsingError = e;\n };\n\n parser.onflush = function () {\n if (parsingError && errorCallBack) {\n errorCallBack(parsingError);\n return;\n }\n callBack(cues);\n };\n\n // Go through contents line by line.\n vttLines.forEach(line => {\n if (inHeader) {\n // Look for X-TIMESTAMP-MAP in header.\n if (startsWith(line, 'X-TIMESTAMP-MAP=')) {\n // Once found, no more are allowed anyway, so stop searching.\n inHeader = false;\n timestampMap = true;\n // Extract LOCAL and MPEGTS.\n line.substr(16).split(',').forEach(timestamp => {\n if (startsWith(timestamp, 'LOCAL:')) {\n cueTime = timestamp.substr(6);\n } else if (startsWith(timestamp, 'MPEGTS:')) {\n mpegTs = parseInt(timestamp.substr(7));\n }\n });\n try {\n // Calculate subtitle offset in milliseconds.\n if (syncPTS + ((vttCCs[cc].start * 90000) || 0) < 0) {\n syncPTS += 8589934592;\n }\n // Adjust MPEGTS by sync PTS.\n mpegTs -= syncPTS;\n // Convert cue time to seconds\n localTime = cueString2millis(cueTime) / 1000;\n // Convert MPEGTS to seconds from 90kHz.\n presentationTime = mpegTs / 90000;\n } catch (e) {\n timestampMap = false;\n parsingError = e;\n }\n // Return without parsing X-TIMESTAMP-MAP line.\n return;\n } else if (line === '') {\n inHeader = false;\n }\n }\n // Parse line by default.\n parser.parse(line + '\\n');\n });\n\n parser.flush();\n }\n};\n\nexport default WebVTTParser;\n","import Event from '../events';\nimport EventHandler from '../event-handler';\nimport Cea608Parser, { CaptionScreen } from '../utils/cea-608-parser';\nimport OutputFilter from '../utils/output-filter';\nimport WebVTTParser from '../utils/webvtt-parser';\nimport { logger } from '../utils/logger';\nimport { sendAddTrackEvent, clearCurrentCues } from '../utils/texttrack-utils';\nimport Fragment from '../loader/fragment';\nimport { HlsConfig } from '../config';\n\n// TS todo: Reduce usage of any\nclass TimelineController extends EventHandler {\n private media: HTMLMediaElement | null = null;\n private config: HlsConfig;\n private enabled: boolean = true;\n private Cues: any;\n private textTracks: Array<TextTrack> = [];\n private tracks: Array<any> = [];\n private initPTS: Array<number> = [];\n private unparsedVttFrags: Array<{frag: Fragment, payload: any}> = [];\n private cueRanges: Array<any> = [];\n private captionsTracks: any = {};\n private captionsProperties: any;\n private cea608Parser!: Cea608Parser;\n private lastSn: number = -1;\n private prevCC: number = -1;\n private vttCCs: any = null;\n\n constructor (hls) {\n super(hls, Event.MEDIA_ATTACHING,\n Event.MEDIA_DETACHING,\n Event.FRAG_PARSING_USERDATA,\n Event.FRAG_DECRYPTED,\n Event.MANIFEST_LOADING,\n Event.MANIFEST_LOADED,\n Event.FRAG_LOADED,\n Event.INIT_PTS_FOUND);\n\n this.hls = hls;\n this.config = hls.config;\n this.Cues = hls.config.cueHandler;\n\n this.captionsProperties = {\n textTrack1: {\n label: this.config.captionsTextTrack1Label,\n languageCode: this.config.captionsTextTrack1LanguageCode\n },\n textTrack2: {\n label: this.config.captionsTextTrack2Label,\n languageCode: this.config.captionsTextTrack2LanguageCode\n }\n };\n\n if (this.config.enableCEA708Captions) {\n const channel1 = new OutputFilter(this, 'textTrack1');\n const channel2 = new OutputFilter(this, 'textTrack2');\n this.cea608Parser = new Cea608Parser(0, channel1, channel2);\n }\n }\n\n addCues (trackName: string, startTime: number, endTime: number, screen: CaptionScreen) {\n // skip cues which overlap more than 50% with previously parsed time ranges\n const ranges = this.cueRanges;\n let merged = false;\n for (let i = ranges.length; i--;) {\n let cueRange = ranges[i];\n let overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);\n if (overlap >= 0) {\n cueRange[0] = Math.min(cueRange[0], startTime);\n cueRange[1] = Math.max(cueRange[1], endTime);\n merged = true;\n if ((overlap / (endTime - startTime)) > 0.5) {\n return;\n }\n }\n }\n if (!merged) {\n ranges.push([startTime, endTime]);\n }\n\n this.Cues.newCue(this.captionsTracks[trackName], startTime, endTime, screen);\n }\n\n // Triggered when an initial PTS is found; used for synchronisation of WebVTT.\n onInitPtsFound (data: { id: string, frag: Fragment, initPTS: number}) {\n const { frag, id, initPTS } = data;\n const { unparsedVttFrags } = this;\n if (id === 'main') {\n this.initPTS[frag.cc] = initPTS;\n }\n\n // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.\n // Parse any unparsed fragments upon receiving the initial PTS.\n if (unparsedVttFrags.length) {\n this.unparsedVttFrags = [];\n unparsedVttFrags.forEach(frag => {\n this.onFragLoaded(frag);\n });\n }\n }\n\n getExistingTrack (trackName: string): TextTrack | null {\n const { media } = this;\n if (media) {\n for (let i = 0; i < media.textTracks.length; i++) {\n let textTrack = media.textTracks[i];\n if (textTrack[trackName]) {\n return textTrack;\n }\n }\n }\n return null;\n }\n\n createCaptionsTrack (trackName: string) {\n const { captionsProperties, captionsTracks, media } = this;\n const { label, languageCode } = captionsProperties[trackName];\n if (!captionsTracks[trackName]) {\n // Enable reuse of existing text track.\n const existingTrack = this.getExistingTrack(trackName);\n if (!existingTrack) {\n const textTrack = this.createTextTrack('captions', label, languageCode);\n if (textTrack) {\n // Set a special property on the track so we know it's managed by Hls.js\n textTrack[trackName] = true;\n captionsTracks[trackName] = textTrack;\n }\n } else {\n captionsTracks[trackName] = existingTrack;\n clearCurrentCues(captionsTracks[trackName]);\n sendAddTrackEvent(captionsTracks[trackName], media as HTMLMediaElement);\n }\n }\n }\n\n createTextTrack (kind: TextTrackKind, label: string, lang: string): TextTrack | undefined {\n const media = this.media;\n if (!media) {\n return;\n }\n return media.addTextTrack(kind, label, lang);\n }\n\n destroy () {\n super.destroy();\n }\n\n onMediaAttaching (data: { media: HTMLMediaElement }) {\n this.media = data.media;\n this._cleanTracks();\n }\n\n onMediaDetaching () {\n const { captionsTracks } = this;\n Object.keys(captionsTracks).forEach(trackName => {\n clearCurrentCues(captionsTracks[trackName]);\n delete captionsTracks[trackName];\n });\n }\n\n onManifestLoading () {\n this.lastSn = -1; // Detect discontiguity in fragment parsing\n this.prevCC = -1;\n this.vttCCs = { // Detect discontinuity in subtitle manifests\n ccOffset: 0,\n presentationOffset: 0,\n 0: {\n start: 0, prevCC: -1, new: false\n }\n };\n this._cleanTracks();\n }\n\n _cleanTracks () {\n // clear outdated subtitles\n const { media } = this;\n if (!media) {\n return;\n }\n const textTracks = media.textTracks;\n if (textTracks) {\n for (let i = 0; i < textTracks.length; i++) {\n clearCurrentCues(textTracks[i]);\n }\n }\n }\n\n onManifestLoaded (data: { subtitles: Array<any> }) {\n this.textTracks = [];\n this.unparsedVttFrags = this.unparsedVttFrags || [];\n this.initPTS = [];\n this.cueRanges = [];\n\n if (this.config.enableWebVTT) {\n this.tracks = data.subtitles || [];\n const inUseTracks = this.media ? this.media.textTracks : [];\n\n this.tracks.forEach((track, index) => {\n let textTrack;\n if (index < inUseTracks.length) {\n let inUseTrack: TextTrack | null = null;\n\n for (let i = 0; i < inUseTracks.length; i++) {\n if (canReuseVttTextTrack(inUseTracks[i], track)) {\n inUseTrack = inUseTracks[i];\n break;\n }\n }\n\n // Reuse tracks with the same label, but do not reuse 608/708 tracks\n if (inUseTrack) {\n textTrack = inUseTrack;\n }\n }\n if (!textTrack) {\n textTrack = this.createTextTrack('subtitles', track.name, track.lang);\n }\n\n if (track.default) {\n textTrack.mode = this.hls.subtitleDisplay ? 'showing' : 'hidden';\n } else {\n textTrack.mode = 'disabled';\n }\n\n this.textTracks.push(textTrack);\n });\n }\n }\n\n onFragLoaded (data: { frag: Fragment, payload: any }) {\n const { frag, payload } = data;\n const { cea608Parser, initPTS, lastSn, unparsedVttFrags } = this;\n if (frag.type === 'main') {\n const sn = frag.sn;\n // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack\n if (frag.sn !== lastSn + 1) {\n if (cea608Parser) {\n cea608Parser.reset();\n }\n }\n this.lastSn = sn as number;\n } // eslint-disable-line brace-style\n // If fragment is subtitle type, parse as WebVTT.\n else if (frag.type === 'subtitle') {\n if (payload.byteLength) {\n // We need an initial synchronisation PTS. Store fragments as long as none has arrived.\n if (!Number.isFinite(initPTS[frag.cc])) {\n unparsedVttFrags.push(data);\n if (initPTS.length) {\n // finish unsuccessfully, otherwise the subtitle-stream-controller could be blocked from loading new frags.\n this.hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: false, frag });\n }\n return;\n }\n\n let decryptData = frag.decryptdata;\n // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.\n if ((decryptData == null) || (decryptData.key == null) || (decryptData.method !== 'AES-128')) {\n this._parseVTTs(frag, payload);\n }\n } else {\n // In case there is no payload, finish unsuccessfully.\n this.hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: false, frag });\n }\n }\n }\n\n _parseVTTs (frag: Fragment, payload) {\n const { hls, prevCC, textTracks, vttCCs } = this;\n if (!vttCCs[frag.cc]) {\n vttCCs[frag.cc] = { start: frag.start, prevCC, new: true };\n this.prevCC = frag.cc;\n }\n // Parse the WebVTT file contents.\n WebVTTParser.parse(payload, this.initPTS[frag.cc], vttCCs, frag.cc, function (cues) {\n const currentTrack = textTracks[frag.level];\n // WebVTTParser.parse is an async method and if the currently selected text track mode is set to \"disabled\"\n // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null\n // and trying to access getCueById method of cues will throw an exception\n if (currentTrack.mode === 'disabled') {\n hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });\n return;\n }\n // Add cues and trigger event with success true.\n cues.forEach(cue => {\n // Sometimes there are cue overlaps on segmented vtts so the same\n // cue can appear more than once in different vtt files.\n // This avoid showing duplicated cues with same timecode and text.\n if (!currentTrack.cues.getCueById(cue.id)) {\n try {\n currentTrack.addCue(cue);\n if (!currentTrack.cues.getCueById(cue.id)) {\n throw new Error(`addCue is failed for: ${cue}`);\n }\n } catch (err) {\n logger.debug(`Failed occurred on adding cues: ${err}`);\n const textTrackCue = new (window as any).TextTrackCue(cue.startTime, cue.endTime, cue.text);\n textTrackCue.id = cue.id;\n currentTrack.addCue(textTrackCue);\n }\n }\n }\n );\n hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: true, frag: frag });\n },\n function (e) {\n // Something went wrong while parsing. Trigger event with success false.\n logger.log(`Failed to parse VTT cue: ${e}`);\n hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });\n });\n }\n\n onFragDecrypted (data: { frag: Fragment, payload: any}) {\n const { frag, payload } = data;\n if (frag.type === 'subtitle') {\n if (!Number.isFinite(this.initPTS[frag.cc])) {\n this.unparsedVttFrags.push(data);\n return;\n }\n\n this._parseVTTs(frag, payload);\n }\n }\n\n onFragParsingUserdata (data: { samples: Array<any> }) {\n if (!this.enabled || !this.cea608Parser) {\n return;\n }\n\n // If the event contains captions (found in the bytes property), push all bytes into the parser immediately\n // It will create the proper timestamps based on the PTS value\n for (let i = 0; i < data.samples.length; i++) {\n const ccBytes = data.samples[i].bytes;\n if (ccBytes) {\n const ccdatas = this.extractCea608Data(ccBytes);\n this.cea608Parser.addData(data.samples[i].pts, ccdatas);\n }\n }\n }\n\n extractCea608Data (byteArray: Uint8Array): Array<number> {\n let count = byteArray[0] & 31;\n let position = 2;\n let tmpByte, ccbyte1, ccbyte2, ccValid, ccType;\n let actualCCBytes: number[] = [];\n\n for (let j = 0; j < count; j++) {\n tmpByte = byteArray[position++];\n ccbyte1 = 0x7F & byteArray[position++];\n ccbyte2 = 0x7F & byteArray[position++];\n ccValid = (4 & tmpByte) !== 0;\n ccType = 3 & tmpByte;\n\n if (ccbyte1 === 0 && ccbyte2 === 0) {\n continue;\n }\n\n if (ccValid) {\n if (ccType === 0) { // || ccType === 1\n actualCCBytes.push(ccbyte1);\n actualCCBytes.push(ccbyte2);\n }\n }\n }\n return actualCCBytes;\n }\n}\n\nfunction canReuseVttTextTrack (inUseTrack, manifestTrack): boolean {\n return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2);\n}\n\nfunction intersection (x1: number, x2: number, y1: number, y2: number): number {\n return Math.min(x2, y2) - Math.max(x1, y1);\n}\n\nexport default TimelineController;\n","import Event from '../events';\nimport EventHandler from '../event-handler';\nimport { logger } from '../utils/logger';\nimport { computeReloadInterval } from './level-helper';\nimport { clearCurrentCues } from '../utils/texttrack-utils';\n\nclass SubtitleTrackController extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.MANIFEST_LOADED,\n Event.SUBTITLE_TRACK_LOADED);\n this.tracks = [];\n this.trackId = -1;\n this.media = null;\n this.stopped = true;\n\n /**\n * @member {boolean} subtitleDisplay Enable/disable subtitle display rendering\n */\n this.subtitleDisplay = true;\n\n /**\n * Keeps reference to a default track id when media has not been attached yet\n * @member {number}\n */\n this.queuedDefaultTrack = null;\n }\n\n destroy () {\n EventHandler.prototype.destroy.call(this);\n }\n\n // Listen for subtitle track change, then extract the current track ID.\n onMediaAttached (data) {\n this.media = data.media;\n if (!this.media) {\n return;\n }\n\n if (Number.isFinite(this.queuedDefaultTrack)) {\n this.subtitleTrack = this.queuedDefaultTrack;\n this.queuedDefaultTrack = null;\n }\n\n this.trackChangeListener = this._onTextTracksChanged.bind(this);\n\n this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);\n if (this.useTextTrackPolling) {\n this.subtitlePollingInterval = setInterval(() => {\n this.trackChangeListener();\n }, 500);\n } else {\n this.media.textTracks.addEventListener('change', this.trackChangeListener);\n }\n }\n\n onMediaDetaching () {\n if (!this.media) {\n return;\n }\n\n if (this.useTextTrackPolling) {\n clearInterval(this.subtitlePollingInterval);\n } else {\n this.media.textTracks.removeEventListener('change', this.trackChangeListener);\n }\n\n if (Number.isFinite(this.subtitleTrack)) {\n this.queuedDefaultTrack = this.subtitleTrack;\n }\n\n const textTracks = filterSubtitleTracks(this.media.textTracks);\n // Clear loaded cues on media detachment from tracks\n textTracks.forEach((track) => {\n clearCurrentCues(track);\n });\n // Disable all subtitle tracks before detachment so when reattached only tracks in that content are enabled.\n this.subtitleTrack = -1;\n this.media = null;\n }\n\n // Fired whenever a new manifest is loaded.\n onManifestLoaded (data) {\n let tracks = data.subtitles || [];\n this.tracks = tracks;\n this.hls.trigger(Event.SUBTITLE_TRACKS_UPDATED, { subtitleTracks: tracks });\n\n // loop through available subtitle tracks and autoselect default if needed\n // TODO: improve selection logic to handle forced, etc\n tracks.forEach(track => {\n if (track.default) {\n // setting this.subtitleTrack will trigger internal logic\n // if media has not been attached yet, it will fail\n // we keep a reference to the default track id\n // and we'll set subtitleTrack when onMediaAttached is triggered\n if (this.media) {\n this.subtitleTrack = track.id;\n } else {\n this.queuedDefaultTrack = track.id;\n }\n }\n });\n }\n\n onSubtitleTrackLoaded (data) {\n const { id, details } = data;\n const { trackId, tracks } = this;\n const currentTrack = tracks[trackId];\n if (id >= tracks.length || id !== trackId || !currentTrack || this.stopped) {\n this._clearReloadTimer();\n return;\n }\n\n logger.log(`subtitle track ${id} loaded`);\n if (details.live) {\n const reloadInterval = computeReloadInterval(currentTrack.details, details, data.stats.trequest);\n logger.log(`Reloading live subtitle playlist in ${reloadInterval}ms`);\n this.timer = setTimeout(() => {\n this._loadCurrentTrack();\n }, reloadInterval);\n } else {\n this._clearReloadTimer();\n }\n }\n\n startLoad () {\n this.stopped = false;\n this._loadCurrentTrack();\n }\n\n stopLoad () {\n this.stopped = true;\n this._clearReloadTimer();\n }\n\n /** get alternate subtitle tracks list from playlist **/\n get subtitleTracks () {\n return this.tracks;\n }\n\n /** get index of the selected subtitle track (index in subtitle track lists) **/\n get subtitleTrack () {\n return this.trackId;\n }\n\n /** select a subtitle track, based on its index in subtitle track lists**/\n set subtitleTrack (subtitleTrackId) {\n if (this.trackId !== subtitleTrackId) {\n this._toggleTrackModes(subtitleTrackId);\n this._setSubtitleTrackInternal(subtitleTrackId);\n }\n }\n\n _clearReloadTimer () {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n _loadCurrentTrack () {\n const { trackId, tracks, hls } = this;\n const currentTrack = tracks[trackId];\n if (trackId < 0 || !currentTrack || (currentTrack.details && !currentTrack.details.live)) {\n return;\n }\n logger.log(`Loading subtitle track ${trackId}`);\n hls.trigger(Event.SUBTITLE_TRACK_LOADING, { url: currentTrack.url, id: trackId });\n }\n\n /**\n * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.\n * This operates on the DOM textTracks.\n * A value of -1 will disable all subtitle tracks.\n * @param newId - The id of the next track to enable\n * @private\n */\n _toggleTrackModes (newId) {\n const { media, subtitleDisplay, trackId } = this;\n if (!media) {\n return;\n }\n\n const textTracks = filterSubtitleTracks(media.textTracks);\n if (newId === -1) {\n [].slice.call(textTracks).forEach(track => {\n track.mode = 'disabled';\n });\n } else {\n const oldTrack = textTracks[trackId];\n if (oldTrack) {\n oldTrack.mode = 'disabled';\n }\n }\n\n const nextTrack = textTracks[newId];\n if (nextTrack) {\n nextTrack.mode = subtitleDisplay ? 'showing' : 'hidden';\n }\n }\n\n /**\n * This method is responsible for validating the subtitle index and periodically reloading if live.\n * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.\n * @param newId - The id of the subtitle track to activate.\n */\n _setSubtitleTrackInternal (newId) {\n const { hls, tracks } = this;\n if (!Number.isFinite(newId) || newId < -1 || newId >= tracks.length) {\n return;\n }\n\n this.trackId = newId;\n logger.log(`Switching to subtitle track ${newId}`);\n hls.trigger(Event.SUBTITLE_TRACK_SWITCH, { id: newId });\n this._loadCurrentTrack();\n }\n\n _onTextTracksChanged () {\n // Media is undefined when switching streams via loadSource()\n if (!this.media) {\n return;\n }\n\n let trackId = -1;\n let tracks = filterSubtitleTracks(this.media.textTracks);\n for (let id = 0; id < tracks.length; id++) {\n if (tracks[id].mode === 'hidden') {\n // Do not break in case there is a following track with showing.\n trackId = id;\n } else if (tracks[id].mode === 'showing') {\n trackId = id;\n break;\n }\n }\n\n // Setting current subtitleTrack will invoke code.\n this.subtitleTrack = trackId;\n }\n}\n\nfunction filterSubtitleTracks (textTrackList) {\n let tracks = [];\n for (let i = 0; i < textTrackList.length; i++) {\n const track = textTrackList[i];\n // Edge adds a track without a label; we don't want to use it\n if (track.kind === 'subtitles' && track.label) {\n tracks.push(textTrackList[i]);\n }\n }\n return tracks;\n}\n\nexport default SubtitleTrackController;\n","/**\n * @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 * @class SubtitleStreamController\n */\n\nimport Event from '../events';\nimport { logger } from '../utils/logger';\nimport Decrypter from '../crypt/decrypter';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport { findFragmentByPDT, findFragmentByPTS } from './fragment-finders';\nimport { FragmentState } from './fragment-tracker';\nimport BaseStreamController, { State } from './base-stream-controller';\nimport { mergeSubtitlePlaylists } from './level-helper';\n\nconst { performance } = window;\nconst TICK_INTERVAL = 500; // how often to tick in ms\n\nexport class SubtitleStreamController extends BaseStreamController {\n constructor (hls, fragmentTracker) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.ERROR,\n Event.KEY_LOADED,\n Event.FRAG_LOADED,\n Event.SUBTITLE_TRACKS_UPDATED,\n Event.SUBTITLE_TRACK_SWITCH,\n Event.SUBTITLE_TRACK_LOADED,\n Event.SUBTITLE_FRAG_PROCESSED,\n Event.LEVEL_UPDATED);\n\n this.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.state = State.STOPPED;\n this.tracks = [];\n this.tracksBuffered = [];\n this.currentTrackId = -1;\n this.decrypter = new Decrypter(hls, hls.config);\n // lastAVStart stores the time in seconds for the start time of a level load\n this.lastAVStart = 0;\n this._onMediaSeeking = this.onMediaSeeking.bind(this);\n }\n\n onSubtitleFragProcessed (data) {\n const { frag, success } = data;\n this.fragPrevious = frag;\n this.state = State.IDLE;\n if (!success) {\n return;\n }\n\n const buffered = this.tracksBuffered[this.currentTrackId];\n if (!buffered) {\n return;\n }\n\n // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo\n // so we can re-use the logic used to detect how much have been buffered\n let timeRange;\n const fragStart = frag.start;\n for (let i = 0; i < buffered.length; i++) {\n if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {\n timeRange = buffered[i];\n break;\n }\n }\n\n const fragEnd = frag.start + frag.duration;\n if (timeRange) {\n timeRange.end = fragEnd;\n } else {\n timeRange = {\n start: fragStart,\n end: fragEnd\n };\n buffered.push(timeRange);\n }\n }\n\n onMediaAttached ({ media }) {\n this.media = media;\n media.addEventListener('seeking', this._onMediaSeeking);\n this.state = State.IDLE;\n }\n\n onMediaDetaching () {\n if (!this.media) {\n return;\n }\n this.media.removeEventListener('seeking', this._onMediaSeeking);\n this.fragmentTracker.removeAllFragments();\n this.currentTrackId = -1;\n this.tracks.forEach((track) => {\n this.tracksBuffered[track.id] = [];\n });\n this.media = null;\n this.state = State.STOPPED;\n }\n\n // If something goes wrong, proceed to next frag, if we were processing one.\n onError (data) {\n let frag = data.frag;\n // don't handle error not related to subtitle fragment\n if (!frag || frag.type !== 'subtitle') {\n return;\n }\n this.state = State.IDLE;\n }\n\n // Got all new subtitle tracks.\n onSubtitleTracksUpdated (data) {\n logger.log('subtitle tracks updated');\n this.tracksBuffered = [];\n this.tracks = data.subtitleTracks;\n this.tracks.forEach((track) => {\n this.tracksBuffered[track.id] = [];\n });\n }\n\n onSubtitleTrackSwitch (data) {\n this.currentTrackId = data.id;\n\n if (!this.tracks || !this.tracks.length || this.currentTrackId === -1) {\n this.clearInterval();\n return;\n }\n\n // Check if track has the necessary details to load fragments\n const currentTrack = this.tracks[this.currentTrackId];\n if (currentTrack && currentTrack.details) {\n this.setInterval(TICK_INTERVAL);\n }\n }\n\n // Got a new set of subtitle fragments.\n onSubtitleTrackLoaded (data) {\n const { id, details } = data;\n const { currentTrackId, tracks } = this;\n const currentTrack = tracks[currentTrackId];\n if (id >= tracks.length || id !== currentTrackId || !currentTrack) {\n return;\n }\n\n if (details.live) {\n mergeSubtitlePlaylists(currentTrack.details, details, this.lastAVStart);\n }\n currentTrack.details = details;\n this.setInterval(TICK_INTERVAL);\n }\n\n onKeyLoaded () {\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n }\n }\n\n onFragLoaded (data) {\n const fragCurrent = this.fragCurrent;\n const decryptData = data.frag.decryptdata;\n const fragLoaded = data.frag;\n const hls = this.hls;\n\n if (this.state === State.FRAG_LOADING &&\n fragCurrent &&\n data.frag.type === 'subtitle' &&\n fragCurrent.sn === data.frag.sn) {\n // check to see if the payload needs to be decrypted\n if (data.payload.byteLength > 0 && (decryptData && decryptData.key && decryptData.method === 'AES-128')) {\n let startTime = performance.now();\n\n // decrypt the subtitles\n this.decrypter.decrypt(data.payload, decryptData.key.buffer, decryptData.iv.buffer, function (decryptedData) {\n let endTime = performance.now();\n hls.trigger(Event.FRAG_DECRYPTED, { frag: fragLoaded, payload: decryptedData, stats: { tstart: startTime, tdecrypt: endTime } });\n });\n }\n }\n }\n\n onLevelUpdated ({ details }) {\n const frags = details.fragments;\n this.lastAVStart = frags.length ? frags[0].start : 0;\n }\n\n doTick () {\n if (!this.media) {\n this.state = State.IDLE;\n return;\n }\n\n switch (this.state) {\n case State.IDLE: {\n const { config, currentTrackId, fragmentTracker, media, tracks } = this;\n if (!tracks || !tracks[currentTrackId] || !tracks[currentTrackId].details) {\n break;\n }\n\n const { maxBufferHole, maxFragLookUpTolerance } = config;\n const maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength);\n const bufferedInfo = BufferHelper.bufferedInfo(this._getBuffered(), media.currentTime, maxBufferHole);\n const { end: bufferEnd, len: bufferLen } = bufferedInfo;\n\n const trackDetails = tracks[currentTrackId].details;\n const fragments = trackDetails.fragments;\n const fragLen = fragments.length;\n const end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration;\n\n if (bufferLen > maxConfigBuffer) {\n return;\n }\n\n let foundFrag;\n const fragPrevious = this.fragPrevious;\n if (bufferEnd < end) {\n if (fragPrevious && trackDetails.hasProgramDateTime) {\n foundFrag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, maxFragLookUpTolerance);\n }\n if (!foundFrag) {\n foundFrag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance);\n }\n } else {\n foundFrag = fragments[fragLen - 1];\n }\n\n if (foundFrag && foundFrag.encrypted) {\n logger.log(`Loading key for ${foundFrag.sn}`);\n this.state = State.KEY_LOADING;\n this.hls.trigger(Event.KEY_LOADING, { frag: foundFrag });\n } else if (foundFrag && fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED) {\n // only load if fragment is not loaded\n this.fragCurrent = foundFrag;\n this.state = State.FRAG_LOADING;\n this.hls.trigger(Event.FRAG_LOADING, { frag: foundFrag });\n }\n }\n }\n }\n\n stopLoad () {\n this.lastAVStart = 0;\n super.stopLoad();\n }\n\n _getBuffered () {\n return this.tracksBuffered[this.currentTrackId] || [];\n }\n\n onMediaSeeking () {\n this.fragPrevious = null;\n }\n}\n","/**\n * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>\n *\n * DRM support for Hls.js\n */\n\nimport EventHandler from '../event-handler';\nimport Event from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport { logger } from '../utils/logger';\nimport { EMEControllerConfig } from '../config';\nimport { KeySystems, MediaKeyFunc } from '../utils/mediakeys-helper';\n\nconst MAX_LICENSE_REQUEST_FAILURES = 3;\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n * @param {object} drmSystemOptions Optional parameters/requirements for the key-system\n * @returns {Array<MediaSystemConfiguration>} An array of supported configurations\n */\n\nconst createWidevineMediaKeySystemConfigurations = function (audioCodecs: string[], videoCodecs: string[]): MediaKeySystemConfiguration[] { /* jshint ignore:line */\n const baseConfig: MediaKeySystemConfiguration = {\n // initDataTypes: ['keyids', 'mp4'],\n // label: \"\",\n // persistentState: \"not-allowed\", // or \"required\" ?\n // distinctiveIdentifier: \"not-allowed\", // or \"required\" ?\n // sessionTypes: ['temporary'],\n videoCapabilities: [] // { contentType: 'video/mp4; codecs=\"avc1.42E01E\"' }\n };\n\n videoCodecs.forEach((codec) => {\n baseConfig.videoCapabilities!.push({\n contentType: `video/mp4; codecs=\"${codec}\"`\n });\n });\n\n return [\n baseConfig\n ];\n};\n\n/**\n * The idea here is to handle key-system (and their respective platforms) specific configuration differences\n * in order to work with the local requestMediaKeySystemAccess method.\n *\n * We can also rule-out platform-related key-system support at this point by throwing an error.\n *\n * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n * @throws will throw an error if a unknown key system is passed\n * @returns {Array<MediaSystemConfiguration>} A non-empty Array of MediaKeySystemConfiguration objects\n */\nconst getSupportedMediaKeySystemConfigurations = function (keySystem: KeySystems, audioCodecs: string[], videoCodecs: string[]): MediaKeySystemConfiguration[] {\n switch (keySystem) {\n case KeySystems.WIDEVINE:\n return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs);\n default:\n throw new Error(`Unknown key-system: ${keySystem}`);\n }\n};\n\ninterface MediaKeysListItem {\n mediaKeys?: MediaKeys,\n mediaKeysSession?: MediaKeySession,\n mediaKeysSessionInitialized: boolean;\n mediaKeySystemAccess: MediaKeySystemAccess;\n mediaKeySystemDomain: KeySystems;\n}\n\n/**\n * Controller to deal with encrypted media extensions (EME)\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API\n *\n * @class\n * @constructor\n */\nclass EMEController extends EventHandler {\n private _widevineLicenseUrl?: string;\n private _licenseXhrSetup?: (xhr: XMLHttpRequest, url: string) => void;\n private _emeEnabled: boolean;\n private _requestMediaKeySystemAccess: MediaKeyFunc | null\n\n private _config: EMEControllerConfig;\n private _mediaKeysList: MediaKeysListItem[] = [];\n private _media: HTMLMediaElement | null = null;\n private _hasSetMediaKeys: boolean = false;\n private _requestLicenseFailureCount: number = 0;\n\n /**\n * @constructs\n * @param {Hls} hls Our Hls.js instance\n */\n constructor (hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHED,\n Event.MANIFEST_PARSED\n );\n this._config = hls.config;\n\n this._widevineLicenseUrl = this._config.widevineLicenseUrl;\n this._licenseXhrSetup = this._config.licenseXhrSetup;\n this._emeEnabled = this._config.emeEnabled;\n this._requestMediaKeySystemAccess = this._config.requestMediaKeySystemAccessFunc;\n }\n\n /**\n * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum\n * @returns {string} License server URL for key-system (if any configured, otherwise causes error)\n * @throws if a unsupported keysystem is passed\n */\n getLicenseServerUrl (keySystem: KeySystems): string {\n switch (keySystem) {\n case KeySystems.WIDEVINE:\n if (!this._widevineLicenseUrl) {\n break;\n }\n return this._widevineLicenseUrl;\n }\n\n throw new Error(`no license server URL configured for key-system \"${keySystem}\"`);\n }\n\n /**\n * Requests access object and adds it to our list upon success\n * @private\n * @param {string} keySystem System ID (see `KeySystems`)\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n * @throws When a unsupported KeySystem is passed\n */\n private _attemptKeySystemAccess (keySystem: KeySystems, audioCodecs: string[], videoCodecs: string[]) {\n // TODO: add other DRM \"options\"\n\n // This can throw, but is caught in event handler callpath\n const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs);\n\n logger.log('Requesting encrypted media key-system access');\n\n // expecting interface like window.navigator.requestMediaKeySystemAccess\n this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs)\n .then((mediaKeySystemAccess) => {\n this._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess);\n })\n .catch((err) => {\n logger.error(`Failed to obtain key-system \"${keySystem}\" access:`, err);\n });\n }\n\n get requestMediaKeySystemAccess () {\n if (!this._requestMediaKeySystemAccess) {\n throw new Error('No requestMediaKeySystemAccess function configured');\n }\n\n return this._requestMediaKeySystemAccess;\n }\n\n /**\n * Handles obtaining access to a key-system\n * @private\n * @param {string} keySystem\n * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess\n */\n private _onMediaKeySystemAccessObtained (keySystem: KeySystems, mediaKeySystemAccess: MediaKeySystemAccess) {\n logger.log(`Access for key-system \"${keySystem}\" obtained`);\n\n const mediaKeysListItem: MediaKeysListItem = {\n mediaKeysSessionInitialized: false,\n mediaKeySystemAccess: mediaKeySystemAccess,\n mediaKeySystemDomain: keySystem\n };\n\n this._mediaKeysList.push(mediaKeysListItem);\n\n mediaKeySystemAccess.createMediaKeys()\n .then((mediaKeys) => {\n mediaKeysListItem.mediaKeys = mediaKeys;\n\n logger.log(`Media-keys created for key-system \"${keySystem}\"`);\n\n this._onMediaKeysCreated();\n })\n .catch((err) => {\n logger.error('Failed to create media-keys:', err);\n });\n }\n\n /**\n * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this\n * for all existing keys where no session exists yet.\n *\n * @private\n */\n private _onMediaKeysCreated () {\n // check for all key-list items if a session exists, otherwise, create one\n this._mediaKeysList.forEach((mediaKeysListItem) => {\n if (!mediaKeysListItem.mediaKeysSession) {\n // mediaKeys is definitely initialized here\n mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys!.createSession();\n this._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);\n }\n });\n }\n\n /**\n * @private\n * @param {*} keySession\n */\n private _onNewMediaKeySession (keySession: MediaKeySession) {\n logger.log(`New key-system session ${keySession.sessionId}`);\n\n keySession.addEventListener('message', (event: MediaKeyMessageEvent) => {\n this._onKeySessionMessage(keySession, event.message);\n }, false);\n }\n\n /**\n * @private\n * @param {MediaKeySession} keySession\n * @param {ArrayBuffer} message\n */\n private _onKeySessionMessage (keySession: MediaKeySession, message: ArrayBuffer) {\n logger.log('Got EME message event, creating license request');\n\n this._requestLicense(message, (data: ArrayBuffer) => {\n logger.log(`Received license data (length: ${data ? data.byteLength : data}), updating key-session`);\n keySession.update(data);\n });\n }\n\n /**\n * @private\n * @param {string} initDataType\n * @param {ArrayBuffer|null} initData\n */\n private _onMediaEncrypted = (e: MediaEncryptedEvent) => {\n logger.log(`Media is encrypted using \"${e.initDataType}\" init data type`);\n\n this._attemptSetMediaKeys();\n this._generateRequestWithPreferredKeySession(e.initDataType, e.initData);\n }\n\n /**\n * @private\n */\n private _attemptSetMediaKeys () {\n if (!this._media) {\n throw new Error('Attempted to set mediaKeys without first attaching a media element');\n }\n\n if (!this._hasSetMediaKeys) {\n // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?\n const keysListItem = this._mediaKeysList[0];\n if (!keysListItem || !keysListItem.mediaKeys) {\n logger.error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_KEYS,\n fatal: true\n });\n return;\n }\n\n logger.log('Setting keys for encrypted media');\n\n this._media.setMediaKeys(keysListItem.mediaKeys);\n this._hasSetMediaKeys = true;\n }\n }\n\n /**\n * @private\n */\n private _generateRequestWithPreferredKeySession (initDataType: string, initData: ArrayBuffer | null) {\n // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?\n const keysListItem = this._mediaKeysList[0];\n if (!keysListItem) {\n logger.error('Fatal: Media is encrypted but not any key-system access has been obtained yet');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,\n fatal: true\n });\n return;\n }\n\n if (keysListItem.mediaKeysSessionInitialized) {\n logger.warn('Key-Session already initialized but requested again');\n return;\n }\n\n const keySession = keysListItem.mediaKeysSession;\n if (!keySession) {\n logger.error('Fatal: Media is encrypted but no key-session existing');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_SESSION,\n fatal: true\n });\n return;\n }\n\n // initData is null if the media is not CORS-same-origin\n if (!initData) {\n logger.warn('Fatal: initData required for generating a key session is null');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_INIT_DATA,\n fatal: true\n });\n return;\n }\n\n logger.log(`Generating key-session request for \"${initDataType}\" init data type`);\n keysListItem.mediaKeysSessionInitialized = true;\n\n keySession.generateRequest(initDataType, initData)\n .then(() => {\n logger.debug('Key-session generation succeeded');\n })\n .catch((err) => {\n logger.error('Error generating key-session request:', err);\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_SESSION,\n fatal: false\n });\n });\n }\n\n /**\n * @private\n * @param {string} url License server URL\n * @param {ArrayBuffer} keyMessage Message data issued by key-system\n * @param {function} callback Called when XHR has succeeded\n * @returns {XMLHttpRequest} Unsent (but opened state) XHR object\n * @throws if XMLHttpRequest construction failed\n */\n private _createLicenseXhr (url: string, keyMessage: ArrayBuffer, callback: (data: ArrayBuffer) => void): XMLHttpRequest {\n const xhr = new XMLHttpRequest();\n const licenseXhrSetup = this._licenseXhrSetup;\n\n try {\n if (licenseXhrSetup) {\n try {\n licenseXhrSetup(xhr, url);\n } catch (e) {\n // let's try to open before running setup\n xhr.open('POST', url, true);\n licenseXhrSetup(xhr, url);\n }\n }\n // if licenseXhrSetup did not yet call open, let's do it now\n if (!xhr.readyState) {\n xhr.open('POST', url, true);\n }\n } catch (e) {\n // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n throw new Error(`issue setting up KeySystem license XHR ${e}`);\n }\n\n // Because we set responseType to ArrayBuffer here, callback is typed as handling only array buffers\n xhr.responseType = 'arraybuffer';\n xhr.onreadystatechange =\n this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback);\n return xhr;\n }\n\n /**\n * @private\n * @param {XMLHttpRequest} xhr\n * @param {string} url License server URL\n * @param {ArrayBuffer} keyMessage Message data issued by key-system\n * @param {function} callback Called when XHR has succeeded\n */\n private _onLicenseRequestReadyStageChange (xhr: XMLHttpRequest, url: string, keyMessage: ArrayBuffer, callback: (data: ArrayBuffer) => void) {\n switch (xhr.readyState) {\n case 4:\n if (xhr.status === 200) {\n this._requestLicenseFailureCount = 0;\n logger.log('License request succeeded');\n\n if (xhr.responseType !== 'arraybuffer') {\n logger.warn('xhr response type was not set to the expected arraybuffer for license request');\n }\n callback(xhr.response);\n } else {\n logger.error(`License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`);\n this._requestLicenseFailureCount++;\n if (this._requestLicenseFailureCount > MAX_LICENSE_REQUEST_FAILURES) {\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true\n });\n return;\n }\n\n const attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;\n logger.warn(`Retrying license request, ${attemptsLeft} attempts left`);\n this._requestLicense(keyMessage, callback);\n }\n break;\n }\n }\n\n /**\n * @private\n * @param {MediaKeysListItem} keysListItem\n * @param {ArrayBuffer} keyMessage\n * @returns {ArrayBuffer} Challenge data posted to license server\n * @throws if KeySystem is unsupported\n */\n private _generateLicenseRequestChallenge (keysListItem: MediaKeysListItem, keyMessage: ArrayBuffer): ArrayBuffer {\n switch (keysListItem.mediaKeySystemDomain) {\n // case KeySystems.PLAYREADY:\n // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js\n /*\n if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {\n // For PlayReady CDMs, we need to dig the Challenge out of the XML.\n var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');\n if (keyMessageXml.getElementsByTagName('Challenge')[0]) {\n challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);\n } else {\n throw 'Cannot find <Challenge> in key message';\n }\n var headerNames = keyMessageXml.getElementsByTagName('name');\n var headerValues = keyMessageXml.getElementsByTagName('value');\n if (headerNames.length !== headerValues.length) {\n throw 'Mismatched header <name>/<value> pair in key message';\n }\n for (var i = 0; i < headerNames.length; i++) {\n xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);\n }\n }\n break;\n */\n case KeySystems.WIDEVINE:\n // For Widevine CDMs, the challenge is the keyMessage.\n return keyMessage;\n }\n\n throw new Error(`unsupported key-system: ${keysListItem.mediaKeySystemDomain}`);\n }\n\n /**\n * @private\n * @param keyMessage\n * @param callback\n */\n private _requestLicense (keyMessage: ArrayBuffer, callback: (data: ArrayBuffer) => void) {\n logger.log('Requesting content license for key-system');\n\n const keysListItem = this._mediaKeysList[0];\n if (!keysListItem) {\n logger.error('Fatal error: Media is encrypted but no key-system access has been obtained yet');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,\n fatal: true\n });\n return;\n }\n\n try {\n const url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);\n const xhr = this._createLicenseXhr(url, keyMessage, callback);\n logger.log(`Sending license request to URL: ${url}`);\n const challenge = this._generateLicenseRequestChallenge(keysListItem, keyMessage);\n xhr.send(challenge);\n } catch (e) {\n logger.error(`Failure requesting DRM license: ${e}`);\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true\n });\n }\n }\n\n onMediaAttached (data: { media: HTMLMediaElement; }) {\n if (!this._emeEnabled) {\n return;\n }\n\n const media = data.media;\n\n // keep reference of media\n this._media = media;\n\n media.addEventListener('encrypted', this._onMediaEncrypted);\n }\n\n onMediaDetached () {\n if (this._media) {\n this._media.removeEventListener('encrypted', this._onMediaEncrypted);\n this._media = null; // release reference\n }\n }\n\n // TODO: Use manifest types here when they are defined\n onManifestParsed (data: any) {\n if (!this._emeEnabled) {\n return;\n }\n\n const audioCodecs = data.levels.map((level) => level.audioCodec);\n const videoCodecs = data.levels.map((level) => level.videoCodec);\n\n this._attemptKeySystemAccess(KeySystems.WIDEVINE, audioCodecs, videoCodecs);\n }\n}\n\nexport default EMEController;\n","/**\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 EMEControllerConfig = {\n licenseXhrSetup?: (xhr: XMLHttpRequest, url: string) => void,\n emeEnabled: boolean,\n widevineLicenseUrl?: string,\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};\n\ntype TimelineControllerConfig = {\n cueHandler: any, // TODO(typescript-cues): Type once file is done\n enableCEA708Captions: boolean,\n enableWebVTT: boolean,\n captionsTextTrack1Label: string,\n captionsTextTrack1LanguageCode: string,\n captionsTextTrack2Label: string,\n captionsTextTrack2LanguageCode: string,\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 Partial<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 requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess, // used by eme-controller\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 if (!__USE_SUBTITLES__) {\n // intentionally doing this over returning Partial<TimelineControllerConfig> above\n // this has the added nice property of still requiring the object below to completely define all props.\n return {} as any;\n }\n return {\n cueHandler: Cues, // used by timeline-controller\n enableCEA708Captions: true, // used by timeline-controller\n enableWebVTT: true, // 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 };\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: any;\n private streamController: any;\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 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 * @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 * @type {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":""}
|