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.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","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","noop","fakeLogger","trace","debug","log","warn","info","error","exportedLogger","formatMsg","type","msg","global","getSelfScope","consolePrintFn","func","console","args","apply","enableLogs","debugConfig","functions","forEach","exportLoggerFunctions","e","logger","HlsEvents","MEDIA_ATTACHING","MEDIA_ATTACHED","MEDIA_DETACHING","MEDIA_DETACHED","BUFFER_RESET","BUFFER_CODECS","BUFFER_CREATED","BUFFER_APPENDING","BUFFER_APPENDED","BUFFER_EOS","BUFFER_FLUSHING","BUFFER_FLUSHED","MANIFEST_LOADING","MANIFEST_LOADED","MANIFEST_PARSED","LEVEL_SWITCHING","LEVEL_SWITCHED","LEVEL_LOADING","LEVEL_LOADED","LEVEL_UPDATED","LEVEL_PTS_UPDATED","LEVELS_UPDATED","AUDIO_TRACKS_UPDATED","AUDIO_TRACK_SWITCHING","AUDIO_TRACK_SWITCHED","AUDIO_TRACK_LOADING","AUDIO_TRACK_LOADED","SUBTITLE_TRACKS_UPDATED","SUBTITLE_TRACK_SWITCH","SUBTITLE_TRACK_LOADING","SUBTITLE_TRACK_LOADED","SUBTITLE_FRAG_PROCESSED","CUES_PARSED","NON_NATIVE_TEXT_TRACKS_FOUND","INIT_PTS_FOUND","FRAG_LOADING","FRAG_LOAD_PROGRESS","FRAG_LOAD_EMERGENCY_ABORTED","FRAG_LOADED","FRAG_DECRYPTED","FRAG_PARSING_INIT_SEGMENT","FRAG_PARSING_USERDATA","FRAG_PARSING_METADATA","FRAG_PARSING_DATA","FRAG_PARSED","FRAG_BUFFERED","FRAG_CHANGED","FPS_DROP","FPS_DROP_LEVEL_CAPPING","ERROR","DESTROYING","KEY_LOADING","KEY_LOADED","STREAM_STATE_TRANSITION","LIVE_BACK_BUFFER_REACHED","ErrorTypes","ErrorDetails","isFiniteNumber","Number","isFinite","MAX_SAFE_INTEGER","decoder","ID3","isHeader","data","offset","length","isFooter","getID3Data","front","_readSize","subarray","size","getTimeStamp","frames","getID3Frames","frame","isTimeStampFrame","_readTimeStamp","_getFrameData","String","fromCharCode","id3Data","end","frameData","_decodeFrame","push","_decodePrivFrame","_decodeURLFrame","_decodeTextFrame","timeStampFrame","byteLength","Uint8Array","pts33Bit","timestamp","Math","round","owner","_utf8ArrayToStr","privateData","buffer","index","description","text","url","array","exitOnNull","getTextDecoder","decoded","decode","idx","indexOf","substring","replace","char2","char3","len","out","TextDecoder","utf8ArrayToStr","window","self","URL_REGEX","FIRST_SEGMENT_REGEX","SLASH_DOT_REGEX","SLASH_DOT_DOT_REGEX","URLToolkit","buildAbsoluteURL","baseURL","relativeURL","opts","trim","alwaysNormalize","basePartsForNormalise","parseURL","Error","path","normalizePath","buildURLFromParts","relativeParts","scheme","baseParts","netLoc","pathParts","exec","builtParts","params","query","fragment","baseURLPath","newPath","lastIndexOf","parts","split","reverse","join","AESCrypto","subtle","iv","aesIV","decrypt","FastAESKey","expandKey","importKey","AESDecryptor","rcon","subMix","Uint32Array","invSubMix","sBox","invSBox","initTable","uint8ArrayToUint32Array_","arrayBuffer","view","DataView","newArray","getUint32","subMix0","subMix1","subMix2","subMix3","invSubMix0","invSubMix1","invSubMix2","invSubMix3","x","xi","sx","x2","x4","x8","keyBuffer","sameKey","keySize","ksRow","invKsRow","prev","ksRows","keySchedule","invKeySchedule","sbox","networkToHostOrderSwap","word","inputArrayBuffer","removePKCS7Padding","t0","t1","t2","t3","s0","s1","s2","s3","inputWords0","inputWords1","inputWords2","inputWords3","outputBytes","paddingBytes","nRounds","invSBOX","initVector","initVector0","initVector1","initVector2","initVector3","inputInt32","Int32Array","outputInt32","swapWord","getUint8","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","__proto__","eventNames","events","names","getOwnPropertySymbols","concat","listeners","handlers","ee","Array","listenerCount","emit","a1","a2","a3","a4","a5","arguments","removeListener","j","on","removeAllListeners","off","prefixed","isHeaderPattern","getHeaderLength","getFullFrameLength","probe","headerLength","frameLength","newOffset","initTrackConfig","track","audioCodec","samplerate","adtsObjectType","adtsSampleingIndex","adtsExtensionSampleingIndex","adtsChanelConfig","userAgent","navigator","toLowerCase","manifestCodec","adtsSampleingRates","test","channelCount","codec","FRAG_PARSING_ERROR","getAudioConfig","getFrameDuration","appendFrame","pts","frameIndex","header","frameDuration","stamp","parseFrameHeader","aacSample","unit","dts","samples","sample","AACDemuxer","remuxer","resetInitSegment","initSegment","videoCodec","duration","_audioTrack","container","id","sequenceNumber","isAAC","inputTimeScale","resetTimeStamp","ADTS","append","timeOffset","contiguous","accurateTimeOffset","id3Samples","remux","MpegAudio","BitratesMap","SamplingRateMap","SamplesCoefficients","BytesInSlot","parseHeader","samplesPerFrame","sampleRate","headerB","headerC","headerE","headerF","headerG","columnInBitrates","bitRate","columnInSampleRates","sampleCoefficient","bytesInSlot","parseInt","ExpGolomb","bytesAvailable","bitsAvailable","loadWord","position","workingBytes","availableBytes","min","set","skipBits","count","skipBytes","readBits","bits","valu","skipLZ","leadingZeroCount","skipUEG","skipEG","readUEG","clz","readEG","readBoolean","readUByte","readUShort","readUInt","skipScalingList","lastScale","nextScale","readSPS","profileIdc","numRefFramesInPicOrderCntCycle","picWidthInMbsMinus1","picHeightInMapUnitsMinus1","frameMbsOnlyFlag","scalingListCount","frameCropLeftOffset","frameCropRightOffset","frameCropTopOffset","frameCropBottomOffset","chromaFormatIdc","picOrderCntType","pixelRatio","width","ceil","height","readSliceType","SampleAesDecrypter","decryptdata","discardEPB","decrypter","decryptBuffer","encryptedData","decryptAacSample","sampleIndex","sync","curUnit","encryptedBuffer","byteOffset","localthis","decryptedData","decryptAacSamples","getAvcEncryptedData","decodedData","encryptedDataLen","floor","Int8Array","outputPos","inputPos","getAvcDecryptedUnit","decryptAvcSample","unitIndex","decryptAvcSamples","curUnits","units","RemuxerTrackIdConfig","video","audio","id3","TSDemuxer","typeSupported","sampleAes","pmtUnknownTypes","setDecryptData","method","syncOffset","_syncOffset","scanwindow","createTrack","pid","dropped","pmtParsed","_pmtId","_avcTrack","_id3Track","_txtTrack","aacOverFlow","aacLastPTS","avcSample","_duration","start","stt","pes","unknownPIDs","avcTrack","audioTrack","id3Track","avcId","audioId","id3Id","pmtId","avcData","pesData","audioData","parsePAT","_parsePAT","parsePMT","_parsePMT","parsePES","_parsePES","parseAVCPES","_parseAVCPES","parseAACPES","_parseAACPES","parseMPEGPES","_parseMPEGPES","parseID3PES","_parseID3PES","parsedPIDs","mpeg","mp3","avc","decryptAndRemux","videoTrack","textTrack","decryptAndRemuxAvc","_initPTS","_initDTS","_trackUnknownPmt","logLevel","mpegSupported","isSampleAes","tableEnd","stream","frag","pesFlags","pesLen","pesHdrLen","pesPts","pesDts","payloadStartOffset","newData","splice","dataLen","pushAccesUnit","nbSamples","isNaN","lastSample","forceKeyFrameOnDiscontinuity","sps","last","expGolombDecoder","_parseAVCNALu","spsfound","createAVCSample","audFound","sliceType","payloadType","payloadSize","endOfCaptions","b","firstByte","totalCCs","byteArray","_insertSampleInOrder","bytes","uuidStrArray","toString","userDataPayloadBytes","uuid","userDataBytes","userData","codecarray","codecstring","h","pps","arr","pos","_getLastNalUnit","lastUnit","overflow","lastUnitType","state","naluState","lastState","lastUnitStart","tmp","newLength","EPBPositions","sourceIndex","shift","newPTS","abs","MP3Demuxer","AAC","getSilentFrame","UINT32_MAX","pow","MP4","init","types","avc1","avcC","btrt","dinf","dref","esds","ftyp","hdlr","mdat","mdhd","mdia","mfhd","minf","moof","moov","mp4a","mvex","mvhd","pasp","sdtp","stbl","stco","stsc","stsd","stsz","stts","tfdt","tfhd","traf","trak","trun","trex","tkhd","vmhd","smhd","charCodeAt","videoHdlr","audioHdlr","HDLR_TYPES","STTS","STSC","STCO","STSZ","VMHD","SMHD","STSD","majorBrand","avc1Brand","minorVersion","FTYP","box","DINF","payload","timescale","upperWordDuration","lowerWordDuration","sn","baseMediaDecodeTime","tracks","boxes","flags","dependsOn","isDependedOn","hasRedundancy","avcc","hSpacing","vSpacing","configlen","sampleDependencyTable","upperWordBaseMediaDecodeTime","lowerWordBaseMediaDecodeTime","cts","arraylen","isLeading","paddingValue","isNonSync","degradPrio","movie","toTimescaleFromBase","destScale","srcBase","toMsFromMpegTsClock","toMpegTsClockFromTimescale","srcScale","MAX_SILENT_FRAME_DURATION_90KHZ","PTS_DTS_SHIFT_TOLERANCE_90KHZ","chromeVersion","PTSNormalize","reference","MP4Remuxer","now","vendor","ISGenerated","match","defaultTimeStamp","getVideoStartPts","videoSamples","rolloverDetected","startPTS","reduce","minPTS","delta","generateIS","nbAudioSamples","nbVideoSamples","audioTimeOffset","videoTimeOffset","audiovideoTimestampDelta","max","audioTrackLength","remuxAudio","endPTS","remuxVideo","videoData","remuxEmptyAudio","remuxID3","remuxText","initPTS","initDTS","audioSamples","computePTSDTS","Infinity","metadata","startOffset","keys","mp4SampleDuration","firstDTS","lastDTS","timeScale","inputSamples","outputSamples","POSITIVE_INFINITY","maxPTS","NEGATIVE_INFINITY","ptsDtsShift","sortSamples","nextAvcDts","sort","a","deltadts","deltapts","averageSampleDuration","lastDts","foundHole","firstPTS","nbNalu","naluLen","nbUnits","sampleLen","mdatSize","MUX_ERROR","REMUX_ALLOC_ERROR","setUint32","compositionTimeOffset","avcSampleUnits","mp4SampleLength","unitData","unitDataLen","lastFrameDuration","stretchShortVideoTrack","maxBufferHole","gapTolerance","deltaToFrameEnd","nextAudioPts","data1","data2","startDTS","endDTS","hasAudio","hasVideo","nb","mp4Sample","fillFrame","lastPTS","mp4timeScale","scaleFactor","inputSampleDuration","rawMPEG","filter","maxAudioFramesDrift","nextPts","missing","newStamp","audioSample","numMissingFrames","unitLen","lastSampleDuration","silentFrame","PassThroughRemuxer","rawData","streamType","performance","Date","DemuxerInline","demuxer","discontinuity","trackSwitch","defaultInitPTS","startTime","endTime","stats","tstart","tdecrypt","pushDecrypted","mux","muxConfig","demux","MP4Demuxer","initData","parseInitSegment","audiovideo","findBox","bin2str","readUint16","val","readUint32","writeUint32","subresults","endbox","results","parseSegmentIndex","references","moovEndOffset","sidx","version","startByte","referencesCount","referenceIndex","referenceInfo","referenceSize","subsegmentDuration","earliestPresentationTime","trackId","codecBox","codecType","getStartDTS","trafs","baseTimes","map","scale","offsetStartDTS","upper","lower","webpackBootstrapFunc","configurable","oe","f","ENTRY_MODULE","default","quoteRegExp","str","getModuleDependencies","sources","queueName","retval","fnString","wrapperSignature","webpackRequireName","re","RegExp","hasValuesInQueues","queues","hasValues","options","main","requiredModules","all","modulesQueue","seenModules","moduleToCheck","pop","newModules","newModulesKeys","getRequiredModules","src","entryModule","JSON","stringify","blob","Blob","bare","workerUrl","URL","webkitURL","mozURL","msURL","createObjectURL","worker","Worker","objectURL","DemuxerWorker","forwardMessage","ev","postMessage","addEventListener","cmd","parse","transferable","PlaylistContextType","PlaylistLevelType","FORBIDDEN_EVENT_NAMES","EventHandler","hls","handledEvents","useGenericHandler","onEvent","registerListeners","onHandlerDestroying","unregisterListeners","onHandlerDestroyed","isEventHandler","onEventGeneric","funcName","constructor","OTHER_ERROR","INTERNAL_EXCEPTION","ElementaryStreamTypes","LevelKey","baseURI","relativeURI","_uri","baseuri","reluri","Fragment","_url","_byteRange","_decryptdata","_elementaryStreams","AUDIO","VIDEO","deltaPTS","rawProgramDateTime","programDateTime","title","tagList","cc","relurl","baseurl","urlId","level","levelkey","loader","setByteRange","previousFrag","byteRange","byteRangeEndOffset","addElementaryStream","hasElementaryStream","createInitializationVector","segmentNumber","uint8View","setDecryptDataFromLevelKey","uri","Level","baseUrl","endCC","endSN","fragments","live","needSidxRanges","startCC","startSN","startTimeOffset","targetduration","totalduration","DECIMAL_RESOLUTION_REGEX","ATTR_LIST_REGEX","AttrList","attrs","attr","parseAttrList","decimalInteger","attrName","intValue","hexadecimalInteger","stringValue","hexadecimalIntegerAsNumber","decimalFloatingPoint","parseFloat","enumeratedString","decimalResolution","res","input","lastIndex","sampleEntryCodesISO","isCodecSupportedInMp4","MediaSource","isTypeSupported","MASTER_PLAYLIST_REGEX","MASTER_PLAYLIST_MEDIA_REGEX","LEVEL_PLAYLIST_REGEX_FAST","source","LEVEL_PLAYLIST_REGEX_SLOW","MP4_REGEX_SUFFIX","M3U8Parser","findGroup","groups","mediaGroupId","group","convertAVC1ToAVCOTI","avcdata","substr","resolve","parseMasterPlaylist","string","levels","sessionData","hasSessionData","setCodecs","codecs","filtered","typeCodes","isCodecType","preferred","unknownCodecs","resolution","bitrate","NAME","CODECS","sessionAttrs","parseMasterPlaylistMedia","audioGroups","medias","TYPE","media","groupId","instreamId","LANGUAGE","DEFAULT","autoselect","AUTOSELECT","forced","FORCED","lang","URI","groupCodec","parseLevelPlaylist","levelUrlId","currentSN","discontinuityCounter","prevFrag","firstPdtIndex","assignProgramDateTime","value1","value2","toUpperCase","keyAttrs","decryptmethod","decrypturi","decryptiv","KEYFORMAT","mapAttrs","BYTERANGE","averagetargetduration","every","startIndex","fragPrev","backfillProgramDateTimes","endProgramDateTime","PlaylistLoader","loaders","canHaveQualityLevels","AUDIO_TRACK","SUBTITLE_TRACK","mapContextToLevelType","SUBTITLE","MAIN","getResponseUrl","response","createInternalLoader","PLoader","pLoader","Loader","getInternalLoader","resetInternalLoader","contextType","destroyInternalLoaders","onManifestLoading","load","MANIFEST","responseType","onLevelLoading","LEVEL","onAudioTrackLoading","onSubtitleTrackLoading","maxRetry","timeout","retryDelay","maxRetryDelay","loaderContext","abort","manifestLoadingMaxRetry","manifestLoadingTimeOut","manifestLoadingRetryDelay","manifestLoadingMaxRetryTimeout","levelLoadingTimeOut","levelLoadingMaxRetry","levelLoadingRetryDelay","levelLoadingMaxRetryTimeout","loaderConfig","loaderCallbacks","onSuccess","loadsuccess","onError","loaderror","onTimeout","loadtimeout","networkDetails","isSidxRequest","_handleSidxRequest","_handlePlaylistLoaded","tload","_handleTrackOrLevelPlaylist","_handleMasterPlaylist","_handleManifestParsingError","_handleNetworkError","audioTracks","subtitles","captions","embeddedAudioFound","unshift","levelId","levelType","levelDetails","singleLevel","tparsed","sidxUrl","rangeStart","rangeEnd","NETWORK_ERROR","LEVEL_EMPTY_ERROR","sidxInfo","sidxReferences","segmentRef","segRefInfo","MANIFEST_PARSING_ERROR","MANIFEST_LOAD_TIMEOUT","MANIFEST_LOAD_ERROR","LEVEL_LOAD_TIMEOUT","LEVEL_LOAD_ERROR","AUDIO_TRACK_LOAD_TIMEOUT","AUDIO_TRACK_LOAD_ERROR","errorData","FragmentLoader","loaderName","onFragLoading","FragmentILoader","fLoader","DefaultILoader","loaded","progressData","byteRangeStartOffset","fragLoadingTimeOut","fragLoadingMaxRetryTimeout","onProgress","loadprogress","FRAG_LOAD_ERROR","FRAG_LOAD_TIMEOUT","KeyLoader","decryptkey","decrypturl","onKeyLoading","fragLoadingRetryDelay","KEY_LOAD_ERROR","KEY_LOAD_TIMEOUT","FragmentState","FragmentTracker","bufferPadding","timeRanges","getBufferedFrag","bufferedFrags","fragmentEntity","body","buffered","bufferedFragKey","detectEvictedFragments","elementaryStream","timeRange","esData","range","fragmentTimes","time","isTimeBuffered","removeFragment","detectPartialFragments","fragKey","getFragmentKey","getBufferedTimes","fragmentPartial","partial","getPartialFragment","timePadding","bestFragment","bestOverlap","isPartial","getState","onFragLoaded","bitrateTest","onBufferAppended","onFragBuffered","hasFragment","removeAllFragments","BinarySearch","search","list","comparisonFn","minIndex","maxIndex","currentIndex","currentElement","comparisonResult","BufferHelper","isBuffered","bufferInfo","maxHoleDuration","vbuffered","bufferedInfo","nextStart","diff","buffered2","buf2len","buf2end","bufferStartNext","bufferLen","bufferStart","bufferEnd","getMediaSource","WebKitMediaSource","Observer","Demuxer","mp4","enableWorker","w","work","onwmsg","onWorkerMessage","onerror","filename","lineno","revokeObjectURL","removeEventListener","terminate","lastFrag","nextSN","ArrayBuffer","addGroupId","audioGroupIds","textGroupIds","updatePTS","fromIdx","toIdx","fragFrom","fragTo","fragToPTS","minEndPTS","updateFragPTSDTS","maxStartPTS","drift","fragIdx","PTSKnown","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","foundFragment","candidate","candidateLookupTolerance","pdtBufferEnd","GapController","fragmentTracker","nudgeRetry","stallReported","stalled","moved","seeking","poll","lastCurrentTime","currentTime","seeked","beginSeek","paused","ended","playbackRate","hasEnoughBuffer","noBufferGap","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","chromeOrFirefox","StreamController","audioCodecSwap","_state","gapController","altAudio","audioOnly","fragLoadError","startFragRequested","startLevel","testBandwidth","nextAutoLevel","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","immediateLevelSwitchEnd","play","nextLevelSwitch","fetchdelay","nextLevelId","nextLevel","fragLastKbps","bufferedFrag","nextBufferedFrag","startPts","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","fromAltAudio","onAudioTrackSwitched","videoBuffer","onBufferCreated","mediaTrack","alternate","pending","total","tfirst","mediaBuffered","fragLoadingMaxRetry","delay","levelRetry","BUFFER_FULL_ERROR","minLength","_seekToStartPos","onFragLoadEmergencyAborted","onBufferFlushed","elementaryStreamType","onLevelsUpdated","swapAudioCodec","defaultAudioCodec","nextState","previousState","_liveSyncPosition","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","trequest","audioGroupId","levelObject","removeLevel","_startLevel","configStartLevel","sendAddTrackEvent","videoEl","document","createEvent","initEvent","dispatchEvent","clearCurrentCues","cues","removeCue","ID3TrackController","getID3Track","textTracks","kind","label","addTextTrack","onFragParsingMetadata","Cue","WebKitDataCue","VTTCue","TextTrackCue","cue","addCue","onLiveBackBufferReached","foundCue","left","right","mid","getClosestCue","EWMA","halfLife","alpha_","estimate_","totalWeight_","exp","weight","adjAlpha","getTotalWeight","getEstimate","zeroFactor","EwmaBandWidthEstimator","slow","fast","defaultEstimate","defaultEstimate_","minWeight_","minDelayMs_","slow_","fast_","durationMs","numBytes","durationS","bandwidthInBps","canEstimate","AbrController","lastLoadedFragLevel","_nextAutoLevel","_bwEstimator","onCheck","_abandonRulesCheck","ewmaFast","ewmaSlow","abrEwmaFastLive","abrEwmaSlowLive","abrEwmaFastVoD","abrEwmaSlowVoD","abrEwmaDefaultEstimate","aborted","requestDelay","loadRate","bw","realBitrate","expectedLen","fragLoadedDelay","bufferStarvationDelay","minAutoLevel","levelNextBitrate","fragLevelNextLoadedDelay","abrMaxWithRealBitrate","loadedBytes","loadedDuration","fragLoadingProcessingMs","bwEstimate","bitrateTestDelay","_findBestLevel","currentFragDuration","currentBw","maxAutoLevel","maxFetchDuration","bwFactor","bwUpFactor","avgDuration","adjustedbw","fetchDuration","forcedAutoLevel","bwEstimator","nextABRAutoLevel","_nextABRAutoLevel","avgbw","bestLevel","abrBandWidthFactor","abrBandWidthUpFactor","maxStarvationDelay","maxLoadingDelay","BufferController","_msDuration","_levelDuration","_levelTargetDuration","_live","_objectUrl","_needsFlush","_needsEos","audioTimestampOffset","bufferCodecEventsExpected","_bufferCodecEventsTotal","mediaSource","segments","appending","appendError","flushBufferCounter","pendingTracks","sourceBuffer","flushRange","_onMediaSourceOpen","checkPendingTracks","_onMediaSourceClose","_onMediaSourceEnded","_onSBUpdateEnd","audioBuffer","timestampOffset","doFlush","checkEos","counter","segment","sbSet","sb","doAppending","updateMediaElementDuration","flushLiveBackBuffer","_onSBUpdateError","BUFFER_APPENDING_ERROR","onLevelPtsUpdated","updating","codecEvents","onMediaAttaching","ms","endOfStream","removeAttribute","pendingTracksCount","createSourceBuffers","onBufferReset","removeSourceBuffer","onBufferCodecs","mimeType","addSourceBuffer","BUFFER_ADD_CODEC_ERROR","onBufferAppending","onBufferEos","onBufferFlushing","liveBackBufferLength","bufferTypes","targetBackBufferPosition","bufferType","removeBufferRange","onLevelUpdated","liveDurationInfinity","flushBuffer","appendBuffer","code","BUFFER_APPEND_ERROR","appendErrorMaxRetry","sbType","bufStart","bufEnd","removeStart","removeEnd","remove","CapLevelController","autoLevelCapping","restrictedLevels","clientRect","capLevelToPlayerSize","stopCapping","onFpsDropLevelCapping","isLevelAllowed","droppedLevel","HTMLVideoElement","startCapping","detectPlayerSize","levelsLength","getMaxLevel","streamController","capLevelIndex","validLevels","getMaxLevelByMediaSize","mediaWidth","mediaHeight","getDimensions","boundsRect","getBoundingClientRect","bottom","top","maxLevelIndex","devicePixelRatio","contentScaleFactor","FPSController","isVideoPlaybackQualityAvailable","capLevelOnFPSDrop","getVideoPlaybackQuality","checkFPSInterval","fpsDroppedMonitoringPeriod","checkFPS","decodedFrames","droppedFrames","lastTime","currentPeriod","currentDropped","lastDroppedFrames","currentDecoded","lastDecodedFrames","droppedFPS","totalDroppedFrames","fpsDroppedMonitoringThreshold","videoPlaybackQuality","totalVideoFrames","droppedVideoFrames","webkitDecodedFrameCount","webkitDroppedFrameCount","XhrLoader","xhrSetup","requestTimeout","retryTimeout","callbacks","retry","loadInternal","xhr","XMLHttpRequest","open","status","setRequestHeader","onreadystatechange","readystatechange","onprogress","send","currentTarget","responseText","responseURL","statusText","lengthComputable","AudioTrackController","_trackId","_selectDefaultTrack","trackIdBlacklist","_selectAudioGroup","onAudioTrackLoaded","updatePeriodMs","_handleLoadError","_setAudioTrack","newId","_loadTrackDetailsIfNeeded","_updateTrack","_selectInitialAudioTrack","currentAudioTrack","defaultTracks","trackFound","traverseTracks","_needsTrackLoading","previousId","language","AudioStreamController","waitingFragment","videoTrackCC","waitingVideoCC","onInitPtsFound","demuxerId","trackDetails","mainBufferInfo","maxConfigBuffer","audioSwitch","CC","findFragWithCC","loadIdx","fragLoadIdx","nextBuffered","foundFrag","isSeeking","waitingFrag","waitingFragCC","clearWaitingFragment","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","VerboseLevel","specialCea608CharsCodes","getCharForByte","byte","charCode","rowsLowCh1","rowsHighCh1","rowsLowCh2","rowsHighCh2","backgroundColors","CaptionsLogger","verboseLevel","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","DEBUG","moveCursor","relPos","newPos","backSpace","insertChar","char","clearFromPos","startPos","clear","clearToEndOfRow","getTextString","setPenStyles","CaptionScreen","currRow","nrRollUpRows","lastOutputScreen","NR_ROWS","setPen","INFO","setPAC","pacData","newRow","topRowIndex","prevLineTime","prevPos","color","setBkgData","bkgData","setRollUpRows","nrRows","rollUp","TEXT","getDisplayText","topRow","asOneRow","displayText","rowNr","rowText","getTextAndFormat","Cea608Channel","channelNumber","outputFilter","chNr","verbose","displayedMemory","nonDisplayedMemory","currRollUpRow","writeScreen","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","setLastCmd","cmdHistory","hasCmdRepeated","Cea608Parser","field","out1","out2","channels","currentChannel","channel","addData","byteList","cmdFound","charsFound","DATA","parseCmd","parseMidrow","parsePAC","parseBackgroundAttributes","parseChars","currChNr","WARNING","interpretPAC","pacIndex","channelNr","charCodes","charCode1","oneCode","hexCodes","OutputFilter","timelineController","cueRanges","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","captionsTracks","nonNativeCaptionsTracks","captionsProperties","cea608Parser1","cea608Parser2","lastSn","0","cueHandler","captionsTextTrack1Label","languageCode","captionsTextTrack1LanguageCode","captionsTextTrack2Label","captionsTextTrack2LanguageCode","textTrack3","captionsTextTrack3Label","captionsTextTrack3LanguageCode","textTrack4","captionsTextTrack4Label","captionsTextTrack4LanguageCode","enableCEA708Captions","channel1","channel2","channel3","channel4","x1","y1","y2","merged","cueRange","overlap","renderTextTracksNatively","getExistingTrack","createNativeTrack","createNonNativeTrack","existingTrack","createTextTrack","trackProperties","closedCaptions","_cleanTracks","enableWebVTT","sameTracks","inUseTracks","subtitleDisplay","tracksList","subtitleTrack","captionsTrack","instreamIdMatch","success","decryptData","_parseVTTs","currentTrack","getCueById","textTrackCue","onFragDecrypted","onFragParsingUserdata","ccBytes","ccdatas","extractCea608Data","actualCCBytes","tmpByte","ccbyte1","ccbyte2","ccType","filterSubtitleTracks","textTrackList","SubtitleTrackController","stopped","queuedDefaultTrack","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","_drmSystemOptions","_config","_mediaKeysList","_media","_hasSetMediaKeys","_requestLicenseFailureCount","mediaKeysPromise","_onMediaEncrypted","initDataType","KEY_SYSTEM_ERROR","KEY_SYSTEM_NO_KEYS","finallySetKeyAndStartSession","mediaKeys","_attemptSetMediaKeys","_generateRequestWithPreferredKeySession","widevineLicenseUrl","licenseXhrSetup","emeEnabled","requestMediaKeySystemAccessFunc","drmSystemOptions","getLicenseServerUrl","keySystem","WIDEVINE","_attemptKeySystemAccess","audioCodecs","videoCodecs","mediaKeySystemConfigs","baseConfig","audioCapabilities","videoCapabilities","contentType","robustness","audioRobustness","videoRobustness","createWidevineMediaKeySystemConfigurations","getSupportedMediaKeySystemConfigurations","keySystemAccessPromise","mediaKeySystemAccess","_onMediaKeySystemAccessObtained","mediaKeysListItem","mediaKeysSessionInitialized","mediaKeySystemDomain","Promise","createMediaKeys","_onMediaKeysCreated","mediaKeysSession","createSession","_onNewMediaKeySession","keySession","sessionId","_onKeySessionMessage","_requestLicense","update","keysListItem","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","mediaKeysList","close","hlsDefaultConfig","lowBufferWatchdogPeriod","abrController","bufferController","capLevelController","fpsController","minAutoBitrate","__USE_SUBTITLES__","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","audioTrackId"],"mappings":"4BAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAa,IAAID,IAEjBD,EAAU,IAAIC,IARhB,CASGK,MAAM,WACT,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUP,QAGnC,IAAIC,EAASI,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GAAG,EACHT,QAAS,IAUV,OANAU,EAAQH,GAAUI,KAAKV,EAAOD,QAASC,EAAQA,EAAOD,QAASM,GAG/DL,EAAOQ,GAAI,EAGJR,EAAOD,QA0Df,OArDAM,EAAoBM,EAAIF,EAGxBJ,EAAoBO,E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S,EAEhBynD,I,oCAYjB,OAAO5lD,KAAKoS,IAAIpS,KAAK4lB,IAAI1vB,KAAKozE,cAAcz4B,cAAe36C,KAAKmpD,cAAenpD,KAAK+pD,e,aAWnE/L,GACjBh+C,KAAKozE,cAAcz4B,cAAgB7wC,KAAK4lB,IAAI1vB,KAAKmpD,aAAcnL,K,kCAQ/D,IAAM61B,EAAuB7zE,KAAK6zE,qBAClC,OAAOA,EAAuBA,EAAqB3qC,YAAc,K,iCAQjE,IAAM2qC,EAAuB7zE,KAAK6zE,qBAClC,OAAOA,EAAuBA,EAAqBzxD,YAAc,G,aAOnDyzD,GACd,IAAMhC,EAAuB7zE,KAAK6zE,qBAC9BA,IACFA,EAAqBzxD,WAAayzD,K,uCAQpC,OAAO71E,KAAKuwD,iBAAiBlU,mB,qCAS7B,IAAMs3B,EAA0B3zE,KAAK2zE,wBACrC,OAAOA,EAA0BA,EAAwB5G,eAAiB,K,oCAQ1E,IAAM4G,EAA0B3zE,KAAK2zE,wBACrC,OAAOA,EAA0BA,EAAwBxI,eAAiB,G,aAOzDoC,GACjB,IAAMoG,EAA0B3zE,KAAK2zE,wBACjCA,IACFA,EAAwBxI,cAAgBoC,K,sCAQ1C,IAAMoG,EAA0B3zE,KAAK2zE,wBACrC,QAAOA,GAA0BA,EAAwB1I,iB,aAOtC5pE,GACnB,IAAMsyE,EAA0B3zE,KAAK2zE,wBACjCA,IACFA,EAAwB1I,gBAAkB5pE,O,GA7oBf6uC,GAAZ6jC,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 levels have changed after removing a level - data: { levels : [available quality levels] }\n LEVELS_UPDATED: 'hlsLevelsUpdated',\n // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }\n AUDIO_TRACKS_UPDATED: 'hlsAudioTracksUpdated',\n // fired when an audio track switching is requested - data: { id : audio track id }\n AUDIO_TRACK_SWITCHING: 'hlsAudioTrackSwitching',\n // fired when an audio track switch actually occurs - data: { id : audio track id }\n AUDIO_TRACK_SWITCHED: 'hlsAudioTrackSwitched',\n // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }\n AUDIO_TRACK_LOADING: 'hlsAudioTrackLoading',\n // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } }\n AUDIO_TRACK_LOADED: 'hlsAudioTrackLoaded',\n // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }\n SUBTITLE_TRACKS_UPDATED: 'hlsSubtitleTracksUpdated',\n // fired when an subtitle track switch occurs - data: { id : subtitle track id }\n SUBTITLE_TRACK_SWITCH: 'hlsSubtitleTrackSwitch',\n // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }\n SUBTITLE_TRACK_LOADING: 'hlsSubtitleTrackLoading',\n // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } }\n SUBTITLE_TRACK_LOADED: 'hlsSubtitleTrackLoaded',\n // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }\n SUBTITLE_FRAG_PROCESSED: 'hlsSubtitleFragProcessed',\n // fired when a set of VTTCues to be managed externally has been parsed - data: { type: string, track: string, cues: [ VTTCue ] }\n CUES_PARSED: 'hlsCuesParsed',\n // fired when a text track to be managed externally is found - data: { tracks: [ { label: string, kind: string, default: boolean } ] }\n NON_NATIVE_TEXT_TRACKS_FOUND: 'hlsNonNativeTextTracksFound',\n // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, frag : fragment object }\n INIT_PTS_FOUND: 'hlsInitPtsFound',\n // fired when a fragment loading starts - data: { frag : fragment object }\n FRAG_LOADING: 'hlsFragLoading',\n // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }\n FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',\n // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }\n FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',\n // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length } }\n FRAG_LOADED: 'hlsFragLoaded',\n // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }\n FRAG_DECRYPTED: 'hlsFragDecrypted',\n // fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment }\n FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',\n // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }\n FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',\n // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }\n FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',\n // fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}\n FRAG_PARSING_DATA: 'hlsFragParsingData',\n // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }\n FRAG_PARSED: 'hlsFragParsed',\n // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length, bwEstimate } }\n FRAG_BUFFERED: 'hlsFragBuffered',\n // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }\n FRAG_CHANGED: 'hlsFragChanged',\n // Identifier for a FPS drop event - data: { curentDropped, currentDecoded, totalDroppedFrames }\n FPS_DROP: 'hlsFpsDrop',\n // triggered when FPS drop triggers auto level capping - data: { level, droppedlevel }\n FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping',\n // Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data }\n ERROR: 'hlsError',\n // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }\n DESTROYING: 'hlsDestroying',\n // fired when a decrypt key loading starts - data: { frag : fragment object }\n KEY_LOADING: 'hlsKeyLoading',\n // fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length } }\n KEY_LOADED: 'hlsKeyLoaded',\n // fired upon stream controller state transitions - data: { previousState, nextState }\n STREAM_STATE_TRANSITION: 'hlsStreamStateTransition',\n // fired when the live back buffer is reached defined by the liveBackBufferLength config option - data : { bufferEnd: number }\n LIVE_BACK_BUFFER_REACHED: 'hlsLiveBackBufferReached'\n};\n\nexport default HlsEvents;\n","export enum ErrorTypes {\n // Identifier for a network error (loading error / timeout ...)\n NETWORK_ERROR = 'networkError',\n // Identifier for a media Error (video/parsing/mediasource error)\n MEDIA_ERROR = 'mediaError',\n // EME (encrypted media extensions) errors\n KEY_SYSTEM_ERROR = 'keySystemError',\n // Identifier for a mux Error (demuxing/remuxing)\n MUX_ERROR = 'muxError',\n // Identifier for all other errors\n OTHER_ERROR = 'otherError'\n}\n\n/**\n * @enum {ErrorDetails}\n * @typedef {string} ErrorDetail\n */\nexport enum ErrorDetails {\n KEY_SYSTEM_NO_KEYS = 'keySystemNoKeys',\n KEY_SYSTEM_NO_ACCESS = 'keySystemNoAccess',\n KEY_SYSTEM_NO_SESSION = 'keySystemNoSession',\n KEY_SYSTEM_LICENSE_REQUEST_FAILED = 'keySystemLicenseRequestFailed',\n KEY_SYSTEM_NO_INIT_DATA = 'keySystemNoInitData',\n // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n MANIFEST_LOAD_ERROR = 'manifestLoadError',\n // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n MANIFEST_LOAD_TIMEOUT = 'manifestLoadTimeOut',\n // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}\n MANIFEST_PARSING_ERROR = 'manifestParsingError',\n // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}\n MANIFEST_INCOMPATIBLE_CODECS_ERROR = 'manifestIncompatibleCodecsError',\n // Identifier for a level which contains no fragments - data: { url: faulty URL, reason: \"no fragments found in level\", level: index of the bad level }\n LEVEL_EMPTY_ERROR = 'levelEmptyError',\n // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n LEVEL_LOAD_ERROR = 'levelLoadError',\n // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n LEVEL_LOAD_TIMEOUT = 'levelLoadTimeOut',\n // Identifier for a level switch error - data: { level : faulty level Id, event : error description}\n LEVEL_SWITCH_ERROR = 'levelSwitchError',\n // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n AUDIO_TRACK_LOAD_ERROR = 'audioTrackLoadError',\n // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n AUDIO_TRACK_LOAD_TIMEOUT = 'audioTrackLoadTimeOut',\n // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}\n FRAG_LOAD_ERROR = 'fragLoadError',\n // Identifier for fragment load timeout error - data: { frag : fragment object}\n FRAG_LOAD_TIMEOUT = 'fragLoadTimeOut',\n // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }\n FRAG_DECRYPT_ERROR = 'fragDecryptError',\n // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }\n // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release\n FRAG_PARSING_ERROR = 'fragParsingError',\n // Identifier for a remux alloc error event - data: { id : demuxer Id, frag : fragment object, bytes : nb of bytes on which allocation failed , reason : error text }\n REMUX_ALLOC_ERROR = 'remuxAllocError',\n // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}\n KEY_LOAD_ERROR = 'keyLoadError',\n // Identifier for decrypt key load timeout error - data: { frag : fragment object}\n KEY_LOAD_TIMEOUT = 'keyLoadTimeOut',\n // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { err : exception , mimeType : mimeType }\n BUFFER_ADD_CODEC_ERROR = 'bufferAddCodecError',\n // Identifier for a buffer append error - data: append error description\n BUFFER_APPEND_ERROR = 'bufferAppendError',\n // Identifier for a buffer appending error event - data: appending error description\n BUFFER_APPENDING_ERROR = 'bufferAppendingError',\n // Identifier for a buffer stalled error event\n BUFFER_STALLED_ERROR = 'bufferStalledError',\n // Identifier for a buffer full event\n BUFFER_FULL_ERROR = 'bufferFullError',\n // Identifier for a buffer seek over hole event\n BUFFER_SEEK_OVER_HOLE = 'bufferSeekOverHole',\n // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)\n BUFFER_NUDGE_ON_STALL = 'bufferNudgeOnStall',\n // Identifier for an internal exception happening inside hls.js while handling an event\n INTERNAL_EXCEPTION = 'internalException'\n}\n","export const isFiniteNumber = Number.isFinite || function (value) {\n return typeof value === 'number' && isFinite(value);\n};\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;\n","import { getSelfScope } from '../utils/get-self-scope';\n\n/**\n * ID3 parser\n */\nclass ID3 {\n /**\n * Returns true if an ID3 header can be found at offset in data\n * @param {Uint8Array} data - The data to search in\n * @param {number} offset - The offset at which to start searching\n * @return {boolean} - True if an ID3 header is found\n */\n static isHeader (data, offset) {\n /*\n * http://id3.org/id3v2.3.0\n * [0] = 'I'\n * [1] = 'D'\n * [2] = '3'\n * [3,4] = {Version}\n * [5] = {Flags}\n * [6-9] = {ID3 Size}\n *\n * An ID3v2 tag can be detected with the following pattern:\n * $49 44 33 yy yy xx zz zz zz zz\n * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80\n */\n if (offset + 10 <= data.length) {\n // look for 'ID3' identifier\n if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {\n // check version is within range\n if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {\n // check size is within range\n if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {\n return true;\n }\n }\n }\n }\n\n return false;\n }\n\n /**\n * Returns true if an ID3 footer can be found at offset in data\n * @param {Uint8Array} data - The data to search in\n * @param {number} offset - The offset at which to start searching\n * @return {boolean} - True if an ID3 footer is found\n */\n static isFooter (data, offset) {\n /*\n * The footer is a copy of the header, but with a different identifier\n */\n if (offset + 10 <= data.length) {\n // look for '3DI' identifier\n if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {\n // check version is within range\n if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {\n // check size is within range\n if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {\n return true;\n }\n }\n }\n }\n\n return false;\n }\n\n /**\n * Returns any adjacent ID3 tags found in data starting at offset, as one block of data\n * @param {Uint8Array} data - The data to search in\n * @param {number} offset - The offset at which to start searching\n * @return {Uint8Array} - The block of data containing any ID3 tags found\n */\n static getID3Data (data, offset) {\n const front = offset;\n let length = 0;\n\n while (ID3.isHeader(data, offset)) {\n // ID3 header is 10 bytes\n length += 10;\n\n const size = ID3._readSize(data, offset + 6);\n length += size;\n\n if (ID3.isFooter(data, offset + 10)) {\n // ID3 footer is 10 bytes\n length += 10;\n }\n\n offset += length;\n }\n\n if (length > 0) {\n return data.subarray(front, front + length);\n }\n\n return undefined;\n }\n\n static _readSize (data, offset) {\n let size = 0;\n size = ((data[offset] & 0x7f) << 21);\n size |= ((data[offset + 1] & 0x7f) << 14);\n size |= ((data[offset + 2] & 0x7f) << 7);\n size |= (data[offset + 3] & 0x7f);\n return size;\n }\n\n /**\n * Searches for the Elementary Stream timestamp found in the ID3 data chunk\n * @param {Uint8Array} data - Block of data containing one or more ID3 tags\n * @return {number} - The timestamp\n */\n static getTimeStamp (data) {\n const frames = ID3.getID3Frames(data);\n for (let i = 0; i < frames.length; i++) {\n const frame = frames[i];\n if (ID3.isTimeStampFrame(frame)) {\n return ID3._readTimeStamp(frame);\n }\n }\n\n return undefined;\n }\n\n /**\n * Returns true if the ID3 frame is an Elementary Stream timestamp frame\n * @param {ID3 frame} frame\n */\n static isTimeStampFrame (frame) {\n return (frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp');\n }\n\n static _getFrameData (data) {\n /*\n Frame ID $xx xx xx xx (four characters)\n Size $xx xx xx xx\n Flags $xx xx\n */\n const type = String.fromCharCode(data[0], data[1], data[2], data[3]);\n const size = ID3._readSize(data, 4);\n\n // skip frame id, size, and flags\n let offset = 10;\n\n return { type, size, data: data.subarray(offset, offset + size) };\n }\n\n /**\n * Returns an array of ID3 frames found in all the ID3 tags in the id3Data\n * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags\n * @return {ID3 frame[]} - Array of ID3 frame objects\n */\n static getID3Frames (id3Data) {\n let offset = 0;\n const frames = [];\n\n while (ID3.isHeader(id3Data, offset)) {\n const size = ID3._readSize(id3Data, offset + 6);\n // skip past ID3 header\n offset += 10;\n const end = offset + size;\n // loop through frames in the ID3 tag\n while (offset + 8 < end) {\n const frameData = ID3._getFrameData(id3Data.subarray(offset));\n const frame = ID3._decodeFrame(frameData);\n if (frame) {\n frames.push(frame);\n }\n\n // skip frame header and frame data\n offset += frameData.size + 10;\n }\n\n if (ID3.isFooter(id3Data, offset)) {\n offset += 10;\n }\n }\n\n return frames;\n }\n\n static _decodeFrame (frame) {\n if (frame.type === 'PRIV') {\n return ID3._decodePrivFrame(frame);\n } else if (frame.type[0] === 'W') {\n return ID3._decodeURLFrame(frame);\n }\n\n return ID3._decodeTextFrame(frame);\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), true);\n\n index += description.length + 1;\n const value = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n return { key: frame.type, info: description, data: value };\n } else {\n /*\n Format:\n [0-?] = {URL}\n */\n const url = ID3._utf8ArrayToStr(frame.data);\n return { key: frame.type, data: url };\n }\n }\n\n // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197\n // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt\n /* utf.js - UTF-8 <=> UTF-16 convertion\n *\n * Copyright (C) 1999 Masanao Izumo <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(function (root) {\n var URL_REGEX = /^((?:[a-zA-Z0-9+\\-.]+:)?)(\\/\\/[^\\/?#]*)?((?:[^\\/?#]*\\/)*[^;?#]*)?(;[^?#]*)?(\\?[^#]*)?(#.*)?$/;\n var FIRST_SEGMENT_REGEX = /^([^\\/?#]*)(.*)$/;\n var SLASH_DOT_REGEX = /(?:\\/|^)\\.(?=\\/)/g;\n var SLASH_DOT_DOT_REGEX = /(?:\\/|^)\\.\\.\\/(?!\\.\\.\\/)[^\\/]*(?=\\/)/g;\n\n var URLToolkit = {\n // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //\n // E.g\n // With opts.alwaysNormalize = false (default, spec compliant)\n // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g\n // With opts.alwaysNormalize = true (not spec compliant)\n // http://a.com/b/cd + /e/f/../g => http://a.com/e/g\n buildAbsoluteURL: function (baseURL, relativeURL, opts) {\n opts = opts || {};\n // remove any remaining space and CRLF\n baseURL = baseURL.trim();\n relativeURL = relativeURL.trim();\n if (!relativeURL) {\n // 2a) If the embedded URL is entirely empty, it inherits the\n // entire base URL (i.e., is set equal to the base URL)\n // and we are done.\n if (!opts.alwaysNormalize) {\n return baseURL;\n }\n var basePartsForNormalise = URLToolkit.parseURL(baseURL);\n if (!basePartsForNormalise) {\n throw new Error('Error trying to parse base URL.');\n }\n basePartsForNormalise.path = URLToolkit.normalizePath(\n basePartsForNormalise.path\n );\n return URLToolkit.buildURLFromParts(basePartsForNormalise);\n }\n var relativeParts = URLToolkit.parseURL(relativeURL);\n if (!relativeParts) {\n throw new Error('Error trying to parse relative URL.');\n }\n if (relativeParts.scheme) {\n // 2b) If the embedded URL starts with a scheme name, it is\n // interpreted as an absolute URL and we are done.\n if (!opts.alwaysNormalize) {\n return relativeURL;\n }\n relativeParts.path = URLToolkit.normalizePath(relativeParts.path);\n return URLToolkit.buildURLFromParts(relativeParts);\n }\n var baseParts = URLToolkit.parseURL(baseURL);\n if (!baseParts) {\n throw new Error('Error trying to parse base URL.');\n }\n if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {\n // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc\n // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'\n var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);\n baseParts.netLoc = pathParts[1];\n baseParts.path = pathParts[2];\n }\n if (baseParts.netLoc && !baseParts.path) {\n baseParts.path = '/';\n }\n var builtParts = {\n // 2c) Otherwise, the embedded URL inherits the scheme of\n // the base URL.\n scheme: baseParts.scheme,\n netLoc: relativeParts.netLoc,\n path: null,\n params: relativeParts.params,\n query: relativeParts.query,\n fragment: relativeParts.fragment,\n };\n if (!relativeParts.netLoc) {\n // 3) If the embedded URL's <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 =\n baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +\n relativeParts.path;\n builtParts.path = URLToolkit.normalizePath(newPath);\n }\n }\n }\n if (builtParts.path === null) {\n builtParts.path = opts.alwaysNormalize\n ? URLToolkit.normalizePath(relativeParts.path)\n : relativeParts.path;\n }\n return URLToolkit.buildURLFromParts(builtParts);\n },\n parseURL: function (url) {\n var parts = URL_REGEX.exec(url);\n if (!parts) {\n return null;\n }\n return {\n scheme: parts[1] || '',\n netLoc: parts[2] || '',\n path: parts[3] || '',\n params: parts[4] || '',\n query: parts[5] || '',\n fragment: parts[6] || '',\n };\n },\n normalizePath: function (path) {\n // The following operations are\n // then applied, in order, to the new path:\n // 6a) All occurrences of \"./\", where \".\" is a complete path\n // segment, are removed.\n // 6b) If the path ends with \".\" as a complete path segment,\n // that \".\" is removed.\n path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');\n // 6c) All occurrences of \"<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 (\n path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length\n ) {}\n return path.split('').reverse().join('');\n },\n buildURLFromParts: function (parts) {\n return (\n parts.scheme +\n parts.netLoc +\n parts.path +\n parts.params +\n parts.query +\n parts.fragment\n );\n },\n };\n\n if (typeof exports === 'object' && typeof module === 'object')\n module.exports = URLToolkit;\n else if (typeof define === 'function' && define.amd)\n define([], function () {\n return URLToolkit;\n });\n else if (typeof exports === 'object') exports['URLToolkit'] = URLToolkit;\n else root['URLToolkit'] = URLToolkit;\n})(this);\n","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 if (offset + headerLength >= data.length) {\n return false;\n }\n // ADTS frame Length\n let frameLength = getFullFrameLength(data, offset);\n if (frameLength <= headerLength) {\n return false;\n }\n\n let newOffset = offset + frameLength;\n if (newOffset === data.length || (newOffset + 1 < data.length && isHeaderPattern(data, newOffset))) {\n return true;\n }\n }\n return false;\n}\n\nexport function initTrackConfig (track, observer, data, offset, audioCodec) {\n if (!track.samplerate) {\n let config = getAudioConfig(observer, data, offset, audioCodec);\n track.config = config.config;\n track.samplerate = config.samplerate;\n track.channelCount = config.channelCount;\n track.codec = config.codec;\n track.manifestCodec = config.manifestCodec;\n logger.log(`parsed codec:${track.codec},rate:${config.samplerate},nb channel:${config.channelCount}`);\n }\n}\n\nexport function getFrameDuration (samplerate) {\n return 1024 * 90000 / samplerate;\n}\n\nexport function parseFrameHeader (data, offset, pts, frameIndex, frameDuration) {\n let headerLength, frameLength, stamp;\n let length = data.length;\n\n // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header\n headerLength = getHeaderLength(data, offset);\n // retrieve frame size\n frameLength = getFullFrameLength(data, offset);\n frameLength -= headerLength;\n\n if ((frameLength > 0) && ((offset + headerLength + frameLength) <= length)) {\n stamp = pts + frameIndex * frameDuration;\n // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);\n return { headerLength, frameLength, stamp };\n }\n\n return undefined;\n}\n\nexport function appendFrame (track, data, offset, pts, frameIndex) {\n let frameDuration = getFrameDuration(track.samplerate);\n let header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);\n if (header) {\n let stamp = header.stamp;\n let headerLength = header.headerLength;\n let frameLength = header.frameLength;\n\n // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);\n let aacSample = {\n unit: data.subarray(offset + headerLength, offset + headerLength + frameLength),\n pts: stamp,\n dts: stamp\n };\n\n track.samples.push(aacSample);\n return { sample: aacSample, length: frameLength + headerLength };\n }\n\n return undefined;\n}\n","/**\n * AAC demuxer\n */\nimport * as ADTS from './adts';\nimport { logger } from '../utils/logger';\nimport ID3 from '../demux/id3';\n\nclass AACDemuxer {\n constructor (observer, remuxer, config) {\n this.observer = observer;\n this.config = config;\n this.remuxer = remuxer;\n }\n\n resetInitSegment (initSegment, audioCodec, videoCodec, duration) {\n this._audioTrack = { container: 'audio/adts', type: 'audio', id: 0, sequenceNumber: 0, isAAC: true, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };\n }\n\n resetTimeStamp () {\n }\n\n static probe (data) {\n if (!data) {\n return false;\n }\n\n // Check for the ADTS sync word\n // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n // More info https://wiki.multimedia.cx/index.php?title=ADTS\n const id3Data = ID3.getID3Data(data, 0) || [];\n let offset = id3Data.length;\n\n for (let length = data.length; offset < length; offset++) {\n if (ADTS.probe(data, offset)) {\n logger.log('ADTS sync word found !');\n return true;\n }\n }\n return false;\n }\n\n // feed incoming data to the front of the parsing pipeline\n append (data, timeOffset, contiguous, accurateTimeOffset) {\n let track = this._audioTrack;\n let id3Data = ID3.getID3Data(data, 0) || [];\n let timestamp = ID3.getTimeStamp(id3Data);\n let pts = Number.isFinite(timestamp) ? timestamp * 90 : timeOffset * 90000;\n let frameIndex = 0;\n let stamp = pts;\n let length = data.length;\n let offset = id3Data.length;\n\n let id3Samples = [{ pts: stamp, dts: stamp, data: id3Data }];\n\n while (offset < length - 1) {\n if (ADTS.isHeader(data, offset) && (offset + 5) < length) {\n ADTS.initTrackConfig(track, this.observer, data, offset, track.manifestCodec);\n let frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n stamp = frame.sample.pts;\n frameIndex++;\n } else {\n logger.log('Unable to parse AAC frame');\n break;\n }\n } else if (ID3.isHeader(data, offset)) {\n id3Data = ID3.getID3Data(data, offset);\n id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });\n offset += id3Data.length;\n } else {\n // nothing found, keep looking\n offset++;\n }\n }\n\n this.remuxer.remux(track,\n { samples: [] },\n { samples: id3Samples, inputTimeScale: 90000 },\n { samples: [] },\n timeOffset,\n contiguous,\n accurateTimeOffset);\n }\n\n destroy () {\n }\n}\n\nexport default AACDemuxer;\n","/**\n * MPEG parser helper\n */\n\nconst MpegAudio = {\n\n BitratesMap: [\n 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448,\n 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384,\n 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,\n 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256,\n 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],\n\n SamplingRateMap: [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000],\n\n SamplesCoefficients: [\n // MPEG 2.5\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12 // Layer1\n ],\n // Reserved\n [\n 0, // Reserved\n 0, // Layer3\n 0, // Layer2\n 0 // Layer1\n ],\n // MPEG 2\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12 // Layer1\n ],\n // MPEG 1\n [\n 0, // Reserved\n 144, // Layer3\n 144, // Layer2\n 12 // Layer1\n ]\n ],\n\n BytesInSlot: [\n 0, // Reserved\n 1, // Layer3\n 1, // Layer2\n 4 // Layer1\n ],\n\n appendFrame: function (track, data, offset, pts, frameIndex) {\n // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference\n if (offset + 24 > data.length) {\n return undefined;\n }\n\n let header = this.parseHeader(data, offset);\n if (header && offset + header.frameLength <= data.length) {\n let frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;\n let stamp = pts + frameIndex * frameDuration;\n let sample = { unit: data.subarray(offset, offset + header.frameLength), pts: stamp, dts: stamp };\n\n track.config = [];\n track.channelCount = header.channelCount;\n track.samplerate = header.sampleRate;\n track.samples.push(sample);\n\n return { sample, length: header.frameLength };\n }\n\n return undefined;\n },\n\n parseHeader: function (data, offset) {\n let headerB = (data[offset + 1] >> 3) & 3;\n let headerC = (data[offset + 1] >> 1) & 3;\n let headerE = (data[offset + 2] >> 4) & 15;\n let headerF = (data[offset + 2] >> 2) & 3;\n let headerG = (data[offset + 2] >> 1) & 1;\n if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {\n let columnInBitrates = headerB === 3 ? (3 - headerC) : (headerC === 3 ? 3 : 4);\n let bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;\n let columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;\n let sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF];\n let channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)\n let sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC];\n let bytesInSlot = MpegAudio.BytesInSlot[headerC];\n let samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;\n let frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot;\n\n return { sampleRate, channelCount, frameLength, samplesPerFrame };\n }\n\n return undefined;\n },\n\n isHeaderPattern: function (data, offset) {\n return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;\n },\n\n isHeader: function (data, offset) {\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {\n return true;\n }\n\n return false;\n },\n\n probe: function (data, offset) {\n // same as isHeader but we also check that MPEG frame follows last MPEG frame\n // or end of data is reached\n if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {\n // MPEG header Length\n let headerLength = 4;\n // MPEG frame Length\n let header = this.parseHeader(data, offset);\n let frameLength = headerLength;\n if (header && header.frameLength) {\n frameLength = header.frameLength;\n }\n\n let newOffset = offset + frameLength;\n if (newOffset === data.length || (newOffset + 1 < data.length && this.isHeaderPattern(data, newOffset))) {\n return true;\n }\n }\n return false;\n }\n};\n\nexport default MpegAudio;\n","/**\n * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.\n*/\n\nimport { logger } from '../utils/logger';\n\nclass ExpGolomb {\n constructor (data) {\n this.data = data;\n // the number of bytes left to examine in this.data\n this.bytesAvailable = data.byteLength;\n // the current word being examined\n this.word = 0; // :uint\n // the number of bits left to examine in the current word\n this.bitsAvailable = 0; // :uint\n }\n\n // ():void\n loadWord () {\n let\n data = this.data,\n bytesAvailable = this.bytesAvailable,\n position = data.byteLength - bytesAvailable,\n workingBytes = new Uint8Array(4),\n availableBytes = Math.min(4, bytesAvailable);\n if (availableBytes === 0) {\n throw new Error('no bytes available');\n }\n\n workingBytes.set(data.subarray(position, position + availableBytes));\n this.word = new DataView(workingBytes.buffer).getUint32(0);\n // track the amount of this.data that has been processed\n this.bitsAvailable = availableBytes * 8;\n this.bytesAvailable -= availableBytes;\n }\n\n // (count:int):void\n skipBits (count) {\n let skipBytes; // :int\n if (this.bitsAvailable > count) {\n this.word <<= count;\n this.bitsAvailable -= count;\n } else {\n count -= this.bitsAvailable;\n skipBytes = count >> 3;\n count -= (skipBytes >> 3);\n this.bytesAvailable -= skipBytes;\n this.loadWord();\n this.word <<= count;\n this.bitsAvailable -= count;\n }\n }\n\n // (size:int):uint\n readBits (size) {\n let\n bits = Math.min(this.bitsAvailable, size), // :uint\n valu = this.word >>> (32 - bits); // :uint\n if (size > 32) {\n logger.error('Cannot read more than 32 bits at a time');\n }\n\n this.bitsAvailable -= bits;\n if (this.bitsAvailable > 0) {\n this.word <<= bits;\n } else if (this.bytesAvailable > 0) {\n this.loadWord();\n }\n\n bits = size - bits;\n if (bits > 0 && this.bitsAvailable) {\n return valu << bits | this.readBits(bits);\n } else {\n return valu;\n }\n }\n\n // ():uint\n skipLZ () {\n let leadingZeroCount; // :uint\n for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {\n if ((this.word & (0x80000000 >>> leadingZeroCount)) !== 0) {\n // the first bit of working word is 1\n this.word <<= leadingZeroCount;\n this.bitsAvailable -= leadingZeroCount;\n return leadingZeroCount;\n }\n }\n // we exhausted word and still have not found a 1\n this.loadWord();\n return leadingZeroCount + this.skipLZ();\n }\n\n // ():void\n skipUEG () {\n this.skipBits(1 + this.skipLZ());\n }\n\n // ():void\n skipEG () {\n this.skipBits(1 + this.skipLZ());\n }\n\n // ():uint\n readUEG () {\n let clz = this.skipLZ(); // :uint\n return this.readBits(clz + 1) - 1;\n }\n\n // ():int\n readEG () {\n let valu = this.readUEG(); // :int\n if (0x01 & valu) {\n // the number is odd if the low order bit is set\n return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2\n } else {\n return -1 * (valu >>> 1); // divide by two then make it negative\n }\n }\n\n // Some convenience functions\n // :Boolean\n readBoolean () {\n return this.readBits(1) === 1;\n }\n\n // ():int\n readUByte () {\n return this.readBits(8);\n }\n\n // ():int\n readUShort () {\n return this.readBits(16);\n }\n // ():int\n readUInt () {\n return this.readBits(32);\n }\n\n /**\n * Advance the ExpGolomb decoder past a scaling list. The scaling\n * list is optionally transmitted as part of a sequence parameter\n * set and is not relevant to transmuxing.\n * @param count {number} the number of entries in this scaling list\n * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1\n */\n skipScalingList (count) {\n let\n lastScale = 8,\n nextScale = 8,\n j,\n deltaScale;\n for (j = 0; j < count; j++) {\n if (nextScale !== 0) {\n deltaScale = this.readEG();\n nextScale = (lastScale + deltaScale + 256) % 256;\n }\n lastScale = (nextScale === 0) ? lastScale : nextScale;\n }\n }\n\n /**\n * Read a sequence parameter set and return some interesting video\n * properties. A sequence parameter set is the H264 metadata that\n * describes the properties of upcoming video frames.\n * @param data {Uint8Array} the bytes of a sequence parameter set\n * @return {object} an object with configuration parsed from the\n * sequence parameter set, including the dimensions of the\n * associated video frames.\n */\n readSPS () {\n let\n frameCropLeftOffset = 0,\n frameCropRightOffset = 0,\n frameCropTopOffset = 0,\n frameCropBottomOffset = 0,\n profileIdc, profileCompat, levelIdc,\n numRefFramesInPicOrderCntCycle, picWidthInMbsMinus1,\n picHeightInMapUnitsMinus1,\n frameMbsOnlyFlag,\n scalingListCount,\n i,\n readUByte = this.readUByte.bind(this),\n readBits = this.readBits.bind(this),\n readUEG = this.readUEG.bind(this),\n readBoolean = this.readBoolean.bind(this),\n skipBits = this.skipBits.bind(this),\n skipEG = this.skipEG.bind(this),\n skipUEG = this.skipUEG.bind(this),\n skipScalingList = this.skipScalingList.bind(this);\n\n readUByte();\n profileIdc = readUByte(); // profile_idc\n profileCompat = readBits(5); // constraint_set[0-4]_flag, u(5)\n skipBits(3); // reserved_zero_3bits u(3),\n levelIdc = readUByte(); // level_idc u(8)\n skipUEG(); // seq_parameter_set_id\n // some profiles have more optional data we don't need\n if (profileIdc === 100 ||\n profileIdc === 110 ||\n profileIdc === 122 ||\n profileIdc === 244 ||\n profileIdc === 44 ||\n profileIdc === 83 ||\n profileIdc === 86 ||\n profileIdc === 118 ||\n profileIdc === 128) {\n let chromaFormatIdc = readUEG();\n if (chromaFormatIdc === 3) {\n skipBits(1);\n } // separate_colour_plane_flag\n\n skipUEG(); // bit_depth_luma_minus8\n skipUEG(); // bit_depth_chroma_minus8\n skipBits(1); // qpprime_y_zero_transform_bypass_flag\n if (readBoolean()) { // seq_scaling_matrix_present_flag\n scalingListCount = (chromaFormatIdc !== 3) ? 8 : 12;\n for (i = 0; i < scalingListCount; i++) {\n if (readBoolean()) { // seq_scaling_list_present_flag[ i ]\n if (i < 6) {\n skipScalingList(16);\n } else {\n skipScalingList(64);\n }\n }\n }\n }\n }\n skipUEG(); // log2_max_frame_num_minus4\n let picOrderCntType = readUEG();\n if (picOrderCntType === 0) {\n readUEG(); // log2_max_pic_order_cnt_lsb_minus4\n } else if (picOrderCntType === 1) {\n skipBits(1); // delta_pic_order_always_zero_flag\n skipEG(); // offset_for_non_ref_pic\n skipEG(); // offset_for_top_to_bottom_field\n numRefFramesInPicOrderCntCycle = readUEG();\n for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {\n skipEG();\n } // offset_for_ref_frame[ i ]\n }\n skipUEG(); // max_num_ref_frames\n skipBits(1); // gaps_in_frame_num_value_allowed_flag\n picWidthInMbsMinus1 = readUEG();\n picHeightInMapUnitsMinus1 = readUEG();\n frameMbsOnlyFlag = readBits(1);\n if (frameMbsOnlyFlag === 0) {\n skipBits(1);\n } // mb_adaptive_frame_field_flag\n\n skipBits(1); // direct_8x8_inference_flag\n if (readBoolean()) { // frame_cropping_flag\n frameCropLeftOffset = readUEG();\n frameCropRightOffset = readUEG();\n frameCropTopOffset = readUEG();\n frameCropBottomOffset = readUEG();\n }\n let pixelRatio = [1, 1];\n if (readBoolean()) {\n // vui_parameters_present_flag\n if (readBoolean()) {\n // aspect_ratio_info_present_flag\n const aspectRatioIdc = readUByte();\n switch (aspectRatioIdc) {\n case 1: pixelRatio = [1, 1]; break;\n case 2: pixelRatio = [12, 11]; break;\n case 3: pixelRatio = [10, 11]; break;\n case 4: pixelRatio = [16, 11]; break;\n case 5: pixelRatio = [40, 33]; break;\n case 6: pixelRatio = [24, 11]; break;\n case 7: pixelRatio = [20, 11]; break;\n case 8: pixelRatio = [32, 11]; break;\n case 9: pixelRatio = [80, 33]; break;\n case 10: pixelRatio = [18, 11]; break;\n case 11: pixelRatio = [15, 11]; break;\n case 12: pixelRatio = [64, 33]; break;\n case 13: pixelRatio = [160, 99]; break;\n case 14: pixelRatio = [4, 3]; break;\n case 15: pixelRatio = [3, 2]; break;\n case 16: pixelRatio = [2, 1]; break;\n case 255: {\n pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];\n break;\n }\n }\n }\n }\n return {\n width: Math.ceil((((picWidthInMbsMinus1 + 1) * 16) - frameCropLeftOffset * 2 - frameCropRightOffset * 2)),\n height: ((2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16) - ((frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset)),\n pixelRatio: pixelRatio\n };\n }\n\n readSliceType () {\n // skip NALu type\n this.readUByte();\n // discard first_mb_in_slice\n this.readUEG();\n // return slice_type\n return this.readUEG();\n }\n}\n\nexport default ExpGolomb;\n","/**\n * SAMPLE-AES decrypter\n*/\n\nimport Decrypter from '../crypt/decrypter';\n\nclass SampleAesDecrypter {\n constructor (observer, config, decryptdata, discardEPB) {\n this.decryptdata = decryptdata;\n this.discardEPB = discardEPB;\n this.decrypter = new Decrypter(observer, config, { removePKCS7Padding: false });\n }\n\n decryptBuffer (encryptedData, callback) {\n this.decrypter.decrypt(encryptedData, this.decryptdata.key.buffer, this.decryptdata.iv.buffer, callback);\n }\n\n // AAC - encrypt all full 16 bytes blocks starting from offset 16\n decryptAacSample (samples, sampleIndex, callback, sync) {\n let curUnit = samples[sampleIndex].unit;\n let encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);\n let encryptedBuffer = encryptedData.buffer.slice(\n encryptedData.byteOffset,\n encryptedData.byteOffset + encryptedData.length);\n\n let localthis = this;\n this.decryptBuffer(encryptedBuffer, function (decryptedData) {\n decryptedData = new Uint8Array(decryptedData);\n curUnit.set(decryptedData, 16);\n\n if (!sync) {\n localthis.decryptAacSamples(samples, sampleIndex + 1, callback);\n }\n });\n }\n\n decryptAacSamples (samples, sampleIndex, callback) {\n for (;; sampleIndex++) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n if (samples[sampleIndex].unit.length < 32) {\n continue;\n }\n\n let sync = this.decrypter.isSync();\n\n this.decryptAacSample(samples, sampleIndex, callback, sync);\n\n if (!sync) {\n return;\n }\n }\n }\n\n // AVC - encrypt one 16 bytes block out of ten, starting from offset 32\n getAvcEncryptedData (decodedData) {\n let encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;\n let encryptedData = new Int8Array(encryptedDataLen);\n let outputPos = 0;\n for (let inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {\n encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);\n }\n\n return encryptedData;\n }\n\n getAvcDecryptedUnit (decodedData, decryptedData) {\n decryptedData = new Uint8Array(decryptedData);\n let inputPos = 0;\n for (let outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {\n decodedData.set(decryptedData.subarray(inputPos, inputPos + 16), outputPos);\n }\n\n return decodedData;\n }\n\n decryptAvcSample (samples, sampleIndex, unitIndex, callback, curUnit, sync) {\n let decodedData = this.discardEPB(curUnit.data);\n let encryptedData = this.getAvcEncryptedData(decodedData);\n let localthis = this;\n\n this.decryptBuffer(encryptedData.buffer, function (decryptedData) {\n curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedData);\n\n if (!sync) {\n localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);\n }\n });\n }\n\n decryptAvcSamples (samples, sampleIndex, unitIndex, callback) {\n for (;; sampleIndex++, unitIndex = 0) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n let curUnits = samples[sampleIndex].units;\n for (;; unitIndex++) {\n if (unitIndex >= curUnits.length) {\n break;\n }\n\n let curUnit = curUnits[unitIndex];\n if (curUnit.data.length <= 48 || (curUnit.type !== 1 && curUnit.type !== 5)) {\n continue;\n }\n\n let sync = this.decrypter.isSync();\n\n this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);\n\n if (!sync) {\n return;\n }\n }\n }\n }\n}\n\nexport default SampleAesDecrypter;\n","/**\n * highly optimized TS demuxer:\n * parse PAT, PMT\n * extract PES packet from audio and video PIDs\n * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet\n * trigger the remuxer upon parsing completion\n * it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.\n * it also controls the remuxing process :\n * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.\n*/\n\nimport * as ADTS from './adts';\nimport MpegAudio from './mpegaudio';\nimport Event from '../events';\nimport ExpGolomb from './exp-golomb';\nimport SampleAesDecrypter from './sample-aes';\n// import Hex from '../utils/hex';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { utf8ArrayToStr } from './id3';\n\n// We are using fixed track IDs for driving the MP4 remuxer\n// instead of following the TS PIDs.\n// There is no reason not to do this and some browsers/SourceBuffer-demuxers\n// may not like if there are TrackID \"switches\"\n// See https://github.com/video-dev/hls.js/issues/1331\n// Here we are mapping our internal track types to constant MP4 track IDs\n// With MSE currently one can only have one track of each, and we are muxing\n// whatever video/audio rendition in them.\nconst RemuxerTrackIdConfig = {\n video: 1,\n audio: 2,\n id3: 3,\n text: 4\n};\n\nclass TSDemuxer {\n constructor (observer, remuxer, config, typeSupported) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n this.remuxer = remuxer;\n this.sampleAes = null;\n this.pmtUnknownTypes = {};\n }\n\n setDecryptData (decryptdata) {\n if ((decryptdata != null) && (decryptdata.key != null) && (decryptdata.method === 'SAMPLE-AES')) {\n this.sampleAes = new SampleAesDecrypter(this.observer, this.config, decryptdata, this.discardEPB);\n } else {\n this.sampleAes = null;\n }\n }\n\n static probe (data) {\n const syncOffset = TSDemuxer._syncOffset(data);\n if (syncOffset < 0) {\n return false;\n } else {\n if (syncOffset) {\n logger.warn(`MPEG2-TS detected but first sync word found @ offset ${syncOffset}, junk ahead ?`);\n }\n\n return true;\n }\n }\n\n static _syncOffset (data) {\n // scan 1000 first bytes\n const scanwindow = Math.min(1000, data.length - 3 * 188);\n let i = 0;\n while (i < scanwindow) {\n // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47\n if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) {\n return i;\n } else {\n i++;\n }\n }\n return -1;\n }\n\n /**\n * Creates a track model internal to demuxer used to drive remuxing input\n *\n * @param {string} type 'audio' | 'video' | 'id3' | 'text'\n * @param {number} duration\n * @return {object} TSDemuxer's internal track model\n */\n static createTrack (type, duration) {\n return {\n container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,\n type,\n id: RemuxerTrackIdConfig[type],\n pid: -1,\n inputTimeScale: 90000,\n sequenceNumber: 0,\n samples: [],\n dropped: type === 'video' ? 0 : undefined,\n isAAC: type === 'audio' ? true : undefined,\n duration: type === 'audio' ? duration : undefined\n };\n }\n\n /**\n * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)\n * Resets all internal track instances of the demuxer.\n *\n * @override Implements generic demuxing/remuxing interface (see DemuxerInline)\n * @param {object} initSegment\n * @param {string} audioCodec\n * @param {string} videoCodec\n * @param {number} duration (in TS timescale = 90kHz)\n */\n resetInitSegment (initSegment, audioCodec, videoCodec, duration) {\n this.pmtParsed = false;\n this._pmtId = -1;\n this.pmtUnknownTypes = {};\n\n this._avcTrack = TSDemuxer.createTrack('video', duration);\n this._audioTrack = TSDemuxer.createTrack('audio', duration);\n this._id3Track = TSDemuxer.createTrack('id3', duration);\n this._txtTrack = TSDemuxer.createTrack('text', duration);\n\n // flush any partial content\n this.aacOverFlow = null;\n this.aacLastPTS = null;\n this.avcSample = null;\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this._duration = duration;\n }\n\n /**\n *\n * @override\n */\n resetTimeStamp () {}\n\n // feed incoming data to the front of the parsing pipeline\n append (data, timeOffset, contiguous, accurateTimeOffset) {\n let start, len = data.length, stt, pid, atf, offset, pes,\n unknownPIDs = false;\n this.pmtUnknownTypes = {};\n this.contiguous = contiguous;\n let pmtParsed = this.pmtParsed,\n avcTrack = this._avcTrack,\n audioTrack = this._audioTrack,\n id3Track = this._id3Track,\n avcId = avcTrack.pid,\n audioId = audioTrack.pid,\n id3Id = id3Track.pid,\n pmtId = this._pmtId,\n avcData = avcTrack.pesData,\n audioData = audioTrack.pesData,\n id3Data = id3Track.pesData,\n parsePAT = this._parsePAT,\n parsePMT = this._parsePMT.bind(this),\n parsePES = this._parsePES,\n parseAVCPES = this._parseAVCPES.bind(this),\n parseAACPES = this._parseAACPES.bind(this),\n parseMPEGPES = this._parseMPEGPES.bind(this),\n parseID3PES = this._parseID3PES.bind(this);\n\n const syncOffset = TSDemuxer._syncOffset(data);\n\n // don't parse last TS packet if incomplete\n len -= (len + syncOffset) % 188;\n\n // loop through TS packets\n for (start = syncOffset; start < len; start += 188) {\n if (data[start] === 0x47) {\n stt = !!(data[start + 1] & 0x40);\n // pid is a 13-bit field starting at the last bit of TS[1]\n pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];\n atf = (data[start + 3] & 0x30) >> 4;\n // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.\n if (atf > 1) {\n offset = start + 5 + data[start + 4];\n // continue if there is only adaptation field\n if (offset === (start + 188)) {\n continue;\n }\n } else {\n offset = start + 4;\n }\n switch (pid) {\n case avcId:\n if (stt) {\n if (avcData && (pes = parsePES(avcData))) {\n parseAVCPES(pes, false);\n }\n\n avcData = { data: [], size: 0 };\n }\n if (avcData) {\n avcData.data.push(data.subarray(offset, start + 188));\n avcData.size += start + 188 - offset;\n }\n break;\n case audioId:\n if (stt) {\n if (audioData && (pes = parsePES(audioData))) {\n if (audioTrack.isAAC) {\n parseAACPES(pes);\n } else {\n parseMPEGPES(pes);\n }\n }\n audioData = { data: [], size: 0 };\n }\n if (audioData) {\n audioData.data.push(data.subarray(offset, start + 188));\n audioData.size += start + 188 - offset;\n }\n break;\n case id3Id:\n if (stt) {\n if (id3Data && (pes = parsePES(id3Data))) {\n parseID3PES(pes);\n }\n\n id3Data = { data: [], size: 0 };\n }\n if (id3Data) {\n id3Data.data.push(data.subarray(offset, start + 188));\n id3Data.size += start + 188 - offset;\n }\n break;\n case 0:\n if (stt) {\n offset += data[offset] + 1;\n }\n\n pmtId = this._pmtId = parsePAT(data, offset);\n break;\n case pmtId:\n if (stt) {\n offset += data[offset] + 1;\n }\n\n let parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, this.sampleAes != null);\n\n // only update track id if track PID found while parsing PMT\n // this is to avoid resetting the PID to -1 in case\n // track PID transiently disappears from the stream\n // this could happen in case of transient missing audio samples for example\n // NOTE this is only the PID of the track as found in TS,\n // but we are not using this for MP4 track IDs.\n avcId = parsedPIDs.avc;\n if (avcId > 0) {\n avcTrack.pid = avcId;\n }\n\n audioId = parsedPIDs.audio;\n if (audioId > 0) {\n audioTrack.pid = audioId;\n audioTrack.isAAC = parsedPIDs.isAAC;\n }\n id3Id = parsedPIDs.id3;\n if (id3Id > 0) {\n id3Track.pid = id3Id;\n }\n\n if (unknownPIDs && !pmtParsed) {\n logger.log('reparse from beginning');\n unknownPIDs = false;\n // we set it to -188, the += 188 in the for loop will reset start to 0\n start = syncOffset - 188;\n }\n pmtParsed = this.pmtParsed = true;\n break;\n case 17:\n case 0x1fff:\n break;\n default:\n unknownPIDs = true;\n break;\n }\n } else {\n this.observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'TS packet did not start with 0x47' });\n }\n }\n // try to parse last PES packets\n if (avcData && (pes = parsePES(avcData))) {\n parseAVCPES(pes, true);\n avcTrack.pesData = null;\n } else {\n // either avcData null or PES truncated, keep it for next frag parsing\n avcTrack.pesData = avcData;\n }\n\n if (audioData && (pes = parsePES(audioData))) {\n if (audioTrack.isAAC) {\n parseAACPES(pes);\n } else {\n parseMPEGPES(pes);\n }\n\n audioTrack.pesData = null;\n } else {\n if (audioData && audioData.size) {\n logger.log('last AAC PES packet truncated,might overlap between fragments');\n }\n\n // either audioData null or PES truncated, keep it for next frag parsing\n audioTrack.pesData = audioData;\n }\n\n if (id3Data && (pes = parsePES(id3Data))) {\n parseID3PES(pes);\n id3Track.pesData = null;\n } else {\n // either id3Data null or PES truncated, keep it for next frag parsing\n id3Track.pesData = id3Data;\n }\n\n if (this.sampleAes == null) {\n this.remuxer.remux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);\n } else {\n this.decryptAndRemux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);\n }\n }\n\n decryptAndRemux (audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {\n if (audioTrack.samples && audioTrack.isAAC) {\n let localthis = this;\n this.sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {\n localthis.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n });\n } else {\n this.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n }\n }\n\n decryptAndRemuxAvc (audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {\n if (videoTrack.samples) {\n let localthis = this;\n this.sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {\n localthis.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n });\n } else {\n this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n }\n }\n\n destroy () {\n this._initPTS = this._initDTS = undefined;\n this._duration = 0;\n }\n\n _parsePAT (data, offset) {\n // skip the PSI header and parse the first PMT entry\n return (data[offset + 10] & 0x1F) << 8 | data[offset + 11];\n // logger.log('PMT PID:' + this._pmtId);\n }\n\n _trackUnknownPmt (type, logLevel, message) {\n // Only log unknown and unsupported stream types once per append or stream (by resetting this.pmtUnknownTypes)\n // For more information on elementary stream types see:\n // https://en.wikipedia.org/wiki/Program-specific_information#Elementary_stream_types\n const result = this.pmtUnknownTypes[type] || 0;\n if (result === 0) {\n this.pmtUnknownTypes[type] = 0;\n logLevel.call(logger, message);\n }\n this.pmtUnknownTypes[type]++;\n return result;\n }\n\n _parsePMT (data, offset, mpegSupported, isSampleAes) {\n let sectionLength, tableEnd, programInfoLength, pid, result = { audio: -1, avc: -1, id3: -1, isAAC: true };\n sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];\n tableEnd = offset + 3 + sectionLength - 4;\n // to determine where the table is, we have to figure out how\n // long the program info descriptors are\n programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];\n // advance the offset to the first entry in the mapping table\n offset += 12 + programInfoLength;\n while (offset < tableEnd) {\n pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];\n switch (data[offset]) {\n case 0xcf: // SAMPLE-AES AAC\n if (!isSampleAes) {\n this._trackUnknownPmt(data[offset], logger.warn, 'ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream');\n break;\n }\n /* falls through */\n\n // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)\n case 0x0f:\n // logger.log('AAC PID:' + pid);\n if (result.audio === -1) {\n result.audio = pid;\n }\n\n break;\n\n // Packetized metadata (ID3)\n case 0x15:\n // logger.log('ID3 PID:' + pid);\n if (result.id3 === -1) {\n result.id3 = pid;\n }\n\n break;\n\n case 0xdb: // SAMPLE-AES AVC\n if (!isSampleAes) {\n this._trackUnknownPmt(data[offset], logger.warn, 'H.264 with AES-128-CBC slice encryption found in unencrypted stream');\n break;\n }\n /* falls through */\n\n // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)\n case 0x1b:\n // logger.log('AVC PID:' + pid);\n if (result.avc === -1) {\n result.avc = pid;\n }\n\n break;\n\n // ISO/IEC 11172-3 (MPEG-1 audio)\n // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)\n case 0x03:\n case 0x04:\n // logger.log('MPEG PID:' + pid);\n if (!mpegSupported) {\n this._trackUnknownPmt(data[offset], logger.warn, 'MPEG audio found, not supported in this browser');\n } else if (result.audio === -1) {\n result.audio = pid;\n result.isAAC = false;\n }\n break;\n\n case 0x24:\n this._trackUnknownPmt(data[offset], logger.warn, 'Unsupported HEVC stream type found');\n break;\n\n default:\n this._trackUnknownPmt(data[offset], logger.log, 'Unknown stream type:' + data[offset]);\n break;\n }\n // move to the next table entry\n // skip past the elementary stream descriptors, if present\n offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5;\n }\n return result;\n }\n\n _parsePES (stream) {\n let i = 0, frag, pesFlags, pesPrefix, pesLen, pesHdrLen, pesData, pesPts, pesDts, payloadStartOffset, data = stream.data;\n // safety check\n if (!stream || stream.size === 0) {\n return null;\n }\n\n // we might need up to 19 bytes to read PES header\n // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes\n // usually only one merge is needed (and this is rare ...)\n while (data[0].length < 19 && data.length > 1) {\n let newData = new Uint8Array(data[0].length + data[1].length);\n newData.set(data[0]);\n newData.set(data[1], data[0].length);\n data[0] = newData;\n data.splice(1, 1);\n }\n // retrieve PTS/DTS from first fragment\n frag = data[0];\n pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];\n if (pesPrefix === 1) {\n pesLen = (frag[4] << 8) + frag[5];\n // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated\n // minus 6 : PES header size\n if (pesLen && pesLen > stream.size - 6) {\n return null;\n }\n\n pesFlags = frag[7];\n if (pesFlags & 0xC0) {\n /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html\n as PTS / DTS is 33 bit we cannot use bitwise operator in JS,\n as Bitwise operators treat their operands as a sequence of 32 bits */\n pesPts = (frag[9] & 0x0E) * 536870912 +// 1 << 29\n (frag[10] & 0xFF) * 4194304 +// 1 << 22\n (frag[11] & 0xFE) * 16384 +// 1 << 14\n (frag[12] & 0xFF) * 128 +// 1 << 7\n (frag[13] & 0xFE) / 2;\n\n if (pesFlags & 0x40) {\n pesDts = (frag[14] & 0x0E) * 536870912 +// 1 << 29\n (frag[15] & 0xFF) * 4194304 +// 1 << 22\n (frag[16] & 0xFE) * 16384 +// 1 << 14\n (frag[17] & 0xFF) * 128 +// 1 << 7\n (frag[18] & 0xFE) / 2;\n\n if (pesPts - pesDts > 60 * 90000) {\n logger.warn(`${Math.round((pesPts - pesDts) / 90000)}s delta between PTS and DTS, align them`);\n pesPts = pesDts;\n }\n } else {\n pesDts = pesPts;\n }\n }\n pesHdrLen = frag[8];\n // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension\n payloadStartOffset = pesHdrLen + 9;\n\n if (stream.size <= payloadStartOffset) {\n return null;\n }\n stream.size -= payloadStartOffset;\n // reassemble PES packet\n pesData = new Uint8Array(stream.size);\n for (let j = 0, dataLen = data.length; j < dataLen; j++) {\n frag = data[j];\n let len = frag.byteLength;\n if (payloadStartOffset) {\n if (payloadStartOffset > len) {\n // trim full frag if PES header bigger than frag\n payloadStartOffset -= len;\n continue;\n } else {\n // trim partial frag if PES header smaller than frag\n frag = frag.subarray(payloadStartOffset);\n len -= payloadStartOffset;\n payloadStartOffset = 0;\n }\n }\n pesData.set(frag, i);\n i += len;\n }\n if (pesLen) {\n // payload size : remove PES header + PES extension\n pesLen -= pesHdrLen + 3;\n }\n return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen };\n } else {\n return null;\n }\n }\n\n pushAccesUnit (avcSample, avcTrack) {\n if (avcSample.units.length && avcSample.frame) {\n const samples = avcTrack.samples;\n const nbSamples = samples.length;\n // if sample does not have PTS/DTS, patch with last sample PTS/DTS\n if (isNaN(avcSample.pts)) {\n if (nbSamples) {\n const lastSample = samples[nbSamples - 1];\n avcSample.pts = lastSample.pts;\n avcSample.dts = lastSample.dts;\n } else {\n // dropping samples, no timestamp found\n avcTrack.dropped++;\n return;\n }\n }\n // only push AVC sample if starting with a keyframe is not mandatory OR\n // if keyframe already found in this fragment OR\n // keyframe found in last fragment (track.sps) AND\n // samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous\n if (!this.config.forceKeyFrameOnDiscontinuity ||\n avcSample.key === true ||\n (avcTrack.sps && (nbSamples || this.contiguous))) {\n avcSample.id = nbSamples;\n samples.push(avcSample);\n } else {\n // dropped samples, track it\n avcTrack.dropped++;\n }\n }\n if (avcSample.debug.length) {\n logger.log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);\n }\n }\n\n _parseAVCPES (pes, last) {\n // logger.log('parse new PES');\n let track = this._avcTrack,\n units = this._parseAVCNALu(pes.data),\n debug = false,\n expGolombDecoder,\n avcSample = this.avcSample,\n push,\n spsfound = false,\n i,\n pushAccesUnit = this.pushAccesUnit.bind(this),\n createAVCSample = function (key, pts, dts, debug) {\n return { key: key, pts: pts, dts: dts, units: [], debug: debug };\n };\n // free pes.data to save up some memory\n pes.data = null;\n\n // if new NAL units found and last sample still there, let's push ...\n // this helps parsing streams with missing AUD (only do this if AUD never found)\n if (avcSample && units.length && !track.audFound) {\n pushAccesUnit(avcSample, track);\n avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');\n }\n\n units.forEach(unit => {\n switch (unit.type) {\n // NDR\n case 1:\n push = true;\n if (!avcSample) {\n avcSample = this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');\n }\n\n if (debug) {\n avcSample.debug += 'NDR ';\n }\n\n avcSample.frame = true;\n let data = unit.data;\n // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)\n if (spsfound && data.length > 4) {\n // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR\n let sliceType = new ExpGolomb(data).readSliceType();\n // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice\n // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.\n // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.\n // I slice: A slice that is not an SI slice that is decoded using intra prediction only.\n // if (sliceType === 2 || sliceType === 7) {\n if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {\n avcSample.key = true;\n }\n }\n break;\n // IDR\n case 5:\n push = true;\n // handle PES not starting with AUD\n if (!avcSample) {\n avcSample = this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');\n }\n\n if (debug) {\n avcSample.debug += 'IDR ';\n }\n\n avcSample.key = true;\n avcSample.frame = true;\n break;\n // SEI\n case 6:\n push = true;\n if (debug && avcSample) {\n avcSample.debug += 'SEI ';\n }\n\n expGolombDecoder = new ExpGolomb(this.discardEPB(unit.data));\n\n // skip frameType\n expGolombDecoder.readUByte();\n\n var payloadType = 0;\n var payloadSize = 0;\n var endOfCaptions = false;\n var b = 0;\n\n while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {\n payloadType = 0;\n do {\n b = expGolombDecoder.readUByte();\n payloadType += b;\n } while (b === 0xFF);\n\n // Parse payload size.\n payloadSize = 0;\n do {\n b = expGolombDecoder.readUByte();\n payloadSize += b;\n } while (b === 0xFF);\n\n // TODO: there can be more than one payload in an SEI packet...\n // TODO: need to read type and size in a while loop to get them all\n if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {\n endOfCaptions = true;\n\n let countryCode = expGolombDecoder.readUByte();\n\n if (countryCode === 181) {\n let providerCode = expGolombDecoder.readUShort();\n\n if (providerCode === 49) {\n let userStructure = expGolombDecoder.readUInt();\n\n if (userStructure === 0x47413934) {\n let userDataType = expGolombDecoder.readUByte();\n\n // Raw CEA-608 bytes wrapped in CEA-708 packet\n if (userDataType === 3) {\n let firstByte = expGolombDecoder.readUByte();\n let secondByte = expGolombDecoder.readUByte();\n\n let totalCCs = 31 & firstByte;\n let byteArray = [firstByte, secondByte];\n\n for (i = 0; i < totalCCs; i++) {\n // 3 bytes per CC\n byteArray.push(expGolombDecoder.readUByte());\n byteArray.push(expGolombDecoder.readUByte());\n byteArray.push(expGolombDecoder.readUByte());\n }\n\n this._insertSampleInOrder(this._txtTrack.samples, { type: 3, pts: pes.pts, bytes: byteArray });\n }\n }\n }\n }\n } else if (payloadType === 5 && expGolombDecoder.bytesAvailable !== 0) {\n endOfCaptions = true;\n\n if (payloadSize > 16) {\n const uuidStrArray = [];\n for (i = 0; i < 16; i++) {\n uuidStrArray.push(expGolombDecoder.readUByte().toString(16));\n\n if (i === 3 || i === 5 || i === 7 || i === 9) {\n uuidStrArray.push('-');\n }\n }\n const length = payloadSize - 16;\n const userDataPayloadBytes = new Uint8Array(length);\n for (i = 0; i < length; i++) {\n userDataPayloadBytes[i] = expGolombDecoder.readUByte();\n }\n\n this._insertSampleInOrder(this._txtTrack.samples, {\n pts: pes.pts,\n payloadType: payloadType,\n uuid: uuidStrArray.join(''),\n userDataBytes: userDataPayloadBytes,\n userData: utf8ArrayToStr(userDataPayloadBytes.buffer)\n });\n }\n } else if (payloadSize < expGolombDecoder.bytesAvailable) {\n for (i = 0; i < payloadSize; i++) {\n expGolombDecoder.readUByte();\n }\n }\n }\n break;\n // SPS\n case 7:\n push = true;\n spsfound = true;\n if (debug && avcSample) {\n avcSample.debug += 'SPS ';\n }\n\n if (!track.sps) {\n expGolombDecoder = new ExpGolomb(unit.data);\n let config = expGolombDecoder.readSPS();\n track.width = config.width;\n track.height = config.height;\n track.pixelRatio = config.pixelRatio;\n track.sps = [unit.data];\n track.duration = this._duration;\n let codecarray = unit.data.subarray(1, 4);\n let codecstring = 'avc1.';\n for (i = 0; i < 3; i++) {\n let h = codecarray[i].toString(16);\n if (h.length < 2) {\n h = '0' + h;\n }\n\n codecstring += h;\n }\n track.codec = codecstring;\n }\n break;\n // PPS\n case 8:\n push = true;\n if (debug && avcSample) {\n avcSample.debug += 'PPS ';\n }\n\n if (!track.pps) {\n track.pps = [unit.data];\n }\n\n break;\n // AUD\n case 9:\n push = false;\n track.audFound = true;\n if (avcSample) {\n pushAccesUnit(avcSample, track);\n }\n\n avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : '');\n break;\n // Filler Data\n case 12:\n push = false;\n break;\n default:\n push = false;\n if (avcSample) {\n avcSample.debug += 'unknown NAL ' + unit.type + ' ';\n }\n\n break;\n }\n if (avcSample && push) {\n let units = avcSample.units;\n units.push(unit);\n }\n });\n // if last PES packet, push samples\n if (last && avcSample) {\n pushAccesUnit(avcSample, track);\n this.avcSample = null;\n }\n }\n\n _insertSampleInOrder (arr, data) {\n let len = arr.length;\n if (len > 0) {\n if (data.pts >= arr[len - 1].pts) {\n arr.push(data);\n } else {\n for (let pos = len - 1; pos >= 0; pos--) {\n if (data.pts < arr[pos].pts) {\n arr.splice(pos, 0, data);\n break;\n }\n }\n }\n } else {\n arr.push(data);\n }\n }\n\n _getLastNalUnit () {\n let avcSample = this.avcSample, lastUnit;\n // try to fallback to previous sample if current one is empty\n if (!avcSample || avcSample.units.length === 0) {\n let track = this._avcTrack, samples = track.samples;\n avcSample = samples[samples.length - 1];\n }\n if (avcSample) {\n let units = avcSample.units;\n lastUnit = units[units.length - 1];\n }\n return lastUnit;\n }\n\n _parseAVCNALu (array) {\n let i = 0, len = array.byteLength, value, overflow, track = this._avcTrack, state = track.naluState || 0, lastState = state;\n let units = [], unit, unitType, lastUnitStart = -1, lastUnitType;\n // logger.log('PES:' + Hex.hexDump(array));\n\n if (state === -1) {\n // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet\n lastUnitStart = 0;\n // NALu type is value read from offset 0\n lastUnitType = array[0] & 0x1f;\n state = 0;\n i = 1;\n }\n\n while (i < len) {\n value = array[i++];\n // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case\n if (!state) {\n state = value ? 0 : 1;\n continue;\n }\n if (state === 1) {\n state = value ? 0 : 2;\n continue;\n }\n // here we have state either equal to 2 or 3\n if (!value) {\n state = 3;\n } else if (value === 1) {\n if (lastUnitStart >= 0) {\n unit = { data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType };\n // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);\n units.push(unit);\n } else {\n // lastUnitStart is undefined => this is the first start code found in this PES packet\n // first check if start code delimiter is overlapping between 2 PES packets,\n // ie it started in last packet (lastState not zero)\n // and ended at the beginning of this PES packet (i <= 4 - lastState)\n let lastUnit = this._getLastNalUnit();\n if (lastUnit) {\n if (lastState && (i <= 4 - lastState)) {\n // start delimiter overlapping between PES packets\n // strip start delimiter bytes from the end of last NAL unit\n // check if lastUnit had a state different from zero\n if (lastUnit.state) {\n // strip last bytes\n lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);\n }\n }\n // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.\n overflow = i - state - 1;\n if (overflow > 0) {\n // logger.log('first NALU found with overflow:' + overflow);\n let tmp = new Uint8Array(lastUnit.data.byteLength + overflow);\n tmp.set(lastUnit.data, 0);\n tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);\n lastUnit.data = tmp;\n }\n }\n }\n // check if we can read unit type\n if (i < len) {\n unitType = array[i] & 0x1f;\n // logger.log('find NALU @ offset:' + i + ',type:' + unitType);\n lastUnitStart = i;\n lastUnitType = unitType;\n state = 0;\n } else {\n // not enough byte to read unit type. let's read it on next PES parsing\n state = -1;\n }\n } else {\n state = 0;\n }\n }\n if (lastUnitStart >= 0 && state >= 0) {\n unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType, state: state };\n units.push(unit);\n // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);\n }\n // no NALu found\n if (units.length === 0) {\n // append pes.data to previous NAL unit\n let lastUnit = this._getLastNalUnit();\n if (lastUnit) {\n let tmp = new Uint8Array(lastUnit.data.byteLength + array.byteLength);\n tmp.set(lastUnit.data, 0);\n tmp.set(array, lastUnit.data.byteLength);\n lastUnit.data = tmp;\n }\n }\n track.naluState = state;\n return units;\n }\n\n /**\n * remove Emulation Prevention bytes from a RBSP\n */\n discardEPB (data) {\n let length = data.byteLength,\n EPBPositions = [],\n i = 1,\n newLength, newData;\n\n // Find all `Emulation Prevention Bytes`\n while (i < length - 2) {\n if (data[i] === 0 &&\n data[i + 1] === 0 &&\n data[i + 2] === 0x03) {\n EPBPositions.push(i + 2);\n i += 2;\n } else {\n i++;\n }\n }\n\n // If no Emulation Prevention Bytes were found just return the original\n // array\n if (EPBPositions.length === 0) {\n return data;\n }\n\n // Create a new array to hold the NAL unit data\n newLength = length - EPBPositions.length;\n newData = new Uint8Array(newLength);\n let sourceIndex = 0;\n\n for (i = 0; i < newLength; sourceIndex++, i++) {\n if (sourceIndex === EPBPositions[0]) {\n // Skip this byte\n sourceIndex++;\n // Remove this position index\n EPBPositions.shift();\n }\n newData[i] = data[sourceIndex];\n }\n return newData;\n }\n\n _parseAACPES (pes) {\n let track = this._audioTrack,\n data = pes.data,\n pts = pes.pts,\n startOffset = 0,\n aacOverFlow = this.aacOverFlow,\n aacLastPTS = this.aacLastPTS,\n frameDuration, frameIndex, offset, stamp, len;\n if (aacOverFlow) {\n let tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);\n tmp.set(aacOverFlow, 0);\n tmp.set(data, aacOverFlow.byteLength);\n // logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);\n data = tmp;\n }\n // look for ADTS header (0xFFFx)\n for (offset = startOffset, len = data.length; offset < len - 1; offset++) {\n if (ADTS.isHeader(data, offset)) {\n break;\n }\n }\n // if ADTS header does not start straight from the beginning of the PES payload, raise an error\n if (offset) {\n let reason, fatal;\n if (offset < len - 1) {\n reason = `AAC PES did not start with ADTS header,offset:${offset}`;\n fatal = false;\n } else {\n reason = 'no ADTS header found in AAC PES';\n fatal = true;\n }\n logger.warn(`parsing error:${reason}`);\n this.observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: fatal, reason: reason });\n if (fatal) {\n return;\n }\n }\n\n ADTS.initTrackConfig(track, this.observer, data, offset, this.audioCodec);\n frameIndex = 0;\n frameDuration = ADTS.getFrameDuration(track.samplerate);\n\n // if last AAC frame is overflowing, we should ensure timestamps are contiguous:\n // first sample PTS should be equal to last sample PTS + frameDuration\n if (aacOverFlow && aacLastPTS) {\n let newPTS = aacLastPTS + frameDuration;\n if (Math.abs(newPTS - pts) > 1) {\n logger.log(`AAC: align PTS for overlapping frames by ${Math.round((newPTS - pts) / 90)}`);\n pts = newPTS;\n }\n }\n\n // scan for aac samples\n while (offset < len) {\n if (ADTS.isHeader(data, offset)) {\n if ((offset + 5) < len) {\n const frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n stamp = frame.sample.pts;\n frameIndex++;\n continue;\n }\n }\n // We are at an ADTS header, but do not have enough data for a frame\n // Remaining data will be added to aacOverFlow\n break;\n } else {\n // nothing found, keep looking\n offset++;\n }\n }\n\n if (offset < len) {\n aacOverFlow = data.subarray(offset, len);\n // logger.log(`AAC: overflow detected:${len-offset}`);\n } else {\n aacOverFlow = null;\n }\n\n this.aacOverFlow = aacOverFlow;\n this.aacLastPTS = stamp;\n }\n\n _parseMPEGPES (pes) {\n let data = pes.data;\n let length = data.length;\n let frameIndex = 0;\n let offset = 0;\n let pts = pes.pts;\n\n while (offset < length) {\n if (MpegAudio.isHeader(data, offset)) {\n let frame = MpegAudio.appendFrame(this._audioTrack, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n frameIndex++;\n } else {\n // logger.log('Unable to parse Mpeg audio frame');\n break;\n }\n } else {\n // nothing found, keep looking\n offset++;\n }\n }\n }\n\n _parseID3PES (pes) {\n this._id3Track.samples.push(pes);\n }\n}\n\nexport default TSDemuxer;\n","/**\n * MP3 demuxer\n */\nimport ID3 from '../demux/id3';\nimport { logger } from '../utils/logger';\nimport MpegAudio from './mpegaudio';\n\nclass MP3Demuxer {\n constructor (observer, remuxer, config) {\n this.observer = observer;\n this.config = config;\n this.remuxer = remuxer;\n }\n\n resetInitSegment (initSegment, audioCodec, videoCodec, duration) {\n this._audioTrack = { container: 'audio/mpeg', type: 'audio', id: -1, sequenceNumber: 0, isAAC: false, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };\n }\n\n resetTimeStamp () {\n }\n\n static probe (data) {\n // check if data contains ID3 timestamp and MPEG sync word\n let offset, length;\n let id3Data = ID3.getID3Data(data, 0);\n if (id3Data && ID3.getTimeStamp(id3Data) !== undefined) {\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n for (offset = id3Data.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) {\n if (MpegAudio.probe(data, offset)) {\n logger.log('MPEG Audio sync word found !');\n return true;\n }\n }\n }\n return false;\n }\n\n // feed incoming data to the front of the parsing pipeline\n append (data, timeOffset, contiguous, accurateTimeOffset) {\n let id3Data = ID3.getID3Data(data, 0) || [];\n let timestamp = ID3.getTimeStamp(id3Data);\n let pts = timestamp !== undefined ? 90 * timestamp : timeOffset * 90000;\n let offset = id3Data.length;\n let length = data.length;\n let frameIndex = 0, stamp = 0;\n let track = this._audioTrack;\n\n let id3Samples = [{ pts: pts, dts: pts, data: id3Data }];\n\n while (offset < length) {\n if (MpegAudio.isHeader(data, offset)) {\n let frame = MpegAudio.appendFrame(track, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n stamp = frame.sample.pts;\n frameIndex++;\n } else {\n // logger.log('Unable to parse Mpeg audio frame');\n break;\n }\n } else if (ID3.isHeader(data, offset)) {\n id3Data = ID3.getID3Data(data, offset);\n id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });\n offset += id3Data.length;\n } else {\n // nothing found, keep looking\n offset++;\n }\n }\n\n this.remuxer.remux(track,\n { samples: [] },\n { samples: id3Samples, inputTimeScale: 90000 },\n { samples: [] },\n timeOffset,\n contiguous,\n accurateTimeOffset);\n }\n\n destroy () {\n }\n}\n\nexport default MP3Demuxer;\n","/**\n * AAC helper\n */\n\nclass AAC {\n static getSilentFrame (codec, channelCount) {\n switch (codec) {\n case 'mp4a.40.2':\n if (channelCount === 1) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);\n } else if (channelCount === 2) {\n return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);\n } else if (channelCount === 3) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);\n } else if (channelCount === 4) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);\n } else if (channelCount === 5) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);\n } else if (channelCount === 6) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]);\n }\n\n break;\n // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)\n default:\n if (channelCount === 1) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0:d=0.05\" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);\n } else if (channelCount === 2) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);\n } else if (channelCount === 3) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0|0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);\n }\n break;\n }\n return null;\n }\n}\n\nexport default AAC;\n","/**\n * Generate MP4 Box\n*/\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\n\nclass MP4 {\n static init () {\n MP4.types = {\n avc1: [], // codingname\n avcC: [],\n btrt: [],\n dinf: [],\n dref: [],\n esds: [],\n ftyp: [],\n hdlr: [],\n mdat: [],\n mdhd: [],\n mdia: [],\n mfhd: [],\n minf: [],\n moof: [],\n moov: [],\n mp4a: [],\n '.mp3': [],\n mvex: [],\n mvhd: [],\n pasp: [],\n sdtp: [],\n stbl: [],\n stco: [],\n stsc: [],\n stsd: [],\n stsz: [],\n stts: [],\n tfdt: [],\n tfhd: [],\n traf: [],\n trak: [],\n trun: [],\n trex: [],\n tkhd: [],\n vmhd: [],\n smhd: []\n };\n\n let i;\n for (i in MP4.types) {\n if (MP4.types.hasOwnProperty(i)) {\n MP4.types[i] = [\n i.charCodeAt(0),\n i.charCodeAt(1),\n i.charCodeAt(2),\n i.charCodeAt(3)\n ];\n }\n }\n\n let videoHdlr = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x56, 0x69, 0x64, 0x65,\n 0x6f, 0x48, 0x61, 0x6e,\n 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'\n ]);\n\n let audioHdlr = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x53, 0x6f, 0x75, 0x6e,\n 0x64, 0x48, 0x61, 0x6e,\n 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'\n ]);\n\n MP4.HDLR_TYPES = {\n 'video': videoHdlr,\n 'audio': audioHdlr\n };\n\n let dref = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x01, // entry_count\n 0x00, 0x00, 0x00, 0x0c, // entry_size\n 0x75, 0x72, 0x6c, 0x20, // 'url' type\n 0x00, // version 0\n 0x00, 0x00, 0x01 // entry_flags\n ]);\n\n let stco = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00 // entry_count\n ]);\n\n MP4.STTS = MP4.STSC = MP4.STCO = stco;\n\n MP4.STSZ = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, // sample_size\n 0x00, 0x00, 0x00, 0x00 // sample_count\n ]);\n MP4.VMHD = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x01, // flags\n 0x00, 0x00, // graphicsmode\n 0x00, 0x00,\n 0x00, 0x00,\n 0x00, 0x00 // opcolor\n ]);\n MP4.SMHD = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, // balance\n 0x00, 0x00 // reserved\n ]);\n\n MP4.STSD = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x01]);// entry_count\n\n let majorBrand = new Uint8Array([105, 115, 111, 109]); // isom\n let avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1\n let minorVersion = new Uint8Array([0, 0, 0, 1]);\n\n MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);\n MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));\n }\n\n static box (type) {\n let\n payload = Array.prototype.slice.call(arguments, 1),\n size = 8,\n i = payload.length,\n len = i,\n result;\n // calculate the total size we need to allocate\n while (i--) {\n size += payload[i].byteLength;\n }\n\n result = new Uint8Array(size);\n result[0] = (size >> 24) & 0xff;\n result[1] = (size >> 16) & 0xff;\n result[2] = (size >> 8) & 0xff;\n result[3] = size & 0xff;\n result.set(type, 4);\n // copy the payload into the result\n for (i = 0, size = 8; i < len; i++) {\n // copy payload[i] array @ offset size\n result.set(payload[i], size);\n size += payload[i].byteLength;\n }\n return result;\n }\n\n static hdlr (type) {\n return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);\n }\n\n static mdat (data) {\n return MP4.box(MP4.types.mdat, data);\n }\n\n static mdhd (timescale, duration) {\n duration *= timescale;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(MP4.types.mdhd, new Uint8Array([\n 0x01, // version 1\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time\n (timescale >> 24) & 0xFF,\n (timescale >> 16) & 0xFF,\n (timescale >> 8) & 0xFF,\n timescale & 0xFF, // timescale\n (upperWordDuration >> 24),\n (upperWordDuration >> 16) & 0xFF,\n (upperWordDuration >> 8) & 0xFF,\n upperWordDuration & 0xFF,\n (lowerWordDuration >> 24),\n (lowerWordDuration >> 16) & 0xFF,\n (lowerWordDuration >> 8) & 0xFF,\n lowerWordDuration & 0xFF,\n 0x55, 0xc4, // 'und' language (undetermined)\n 0x00, 0x00\n ]));\n }\n\n static mdia (track) {\n return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));\n }\n\n static mfhd (sequenceNumber) {\n return MP4.box(MP4.types.mfhd, new Uint8Array([\n 0x00,\n 0x00, 0x00, 0x00, // flags\n (sequenceNumber >> 24),\n (sequenceNumber >> 16) & 0xFF,\n (sequenceNumber >> 8) & 0xFF,\n sequenceNumber & 0xFF // sequence_number\n ]));\n }\n\n static minf (track) {\n if (track.type === 'audio') {\n return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));\n } else {\n return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));\n }\n }\n\n static moof (sn, baseMediaDecodeTime, track) {\n return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));\n }\n /**\n * @param tracks... (optional) {array} the tracks associated with this movie\n */\n static moov (tracks) {\n let\n i = tracks.length,\n boxes = [];\n\n while (i--) {\n boxes[i] = MP4.trak(tracks[i]);\n }\n\n return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));\n }\n\n static mvex (tracks) {\n let\n i = tracks.length,\n boxes = [];\n\n while (i--) {\n boxes[i] = MP4.trex(tracks[i]);\n }\n\n return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));\n }\n\n static mvhd (timescale, duration) {\n duration *= timescale;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n let\n bytes = new Uint8Array([\n 0x01, // version 1\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time\n (timescale >> 24) & 0xFF,\n (timescale >> 16) & 0xFF,\n (timescale >> 8) & 0xFF,\n timescale & 0xFF, // timescale\n (upperWordDuration >> 24),\n (upperWordDuration >> 16) & 0xFF,\n (upperWordDuration >> 8) & 0xFF,\n upperWordDuration & 0xFF,\n (lowerWordDuration >> 24),\n (lowerWordDuration >> 16) & 0xFF,\n (lowerWordDuration >> 8) & 0xFF,\n lowerWordDuration & 0xFF,\n 0x00, 0x01, 0x00, 0x00, // 1.0 rate\n 0x01, 0x00, // 1.0 volume\n 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n 0xff, 0xff, 0xff, 0xff // next_track_ID\n ]);\n return MP4.box(MP4.types.mvhd, bytes);\n }\n\n static sdtp (track) {\n let\n samples = track.samples || [],\n bytes = new Uint8Array(4 + samples.length),\n flags,\n i;\n // leave the full box header (4 bytes) all zero\n // write the sample table\n for (i = 0; i < samples.length; i++) {\n flags = samples[i].flags;\n bytes[i + 4] = (flags.dependsOn << 4) |\n (flags.isDependedOn << 2) |\n (flags.hasRedundancy);\n }\n\n return MP4.box(MP4.types.sdtp, bytes);\n }\n\n static stbl (track) {\n return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO));\n }\n\n static avc1 (track) {\n let sps = [], pps = [], i, data, len;\n // assemble the SPSs\n\n for (i = 0; i < track.sps.length; i++) {\n data = track.sps[i];\n len = data.byteLength;\n sps.push((len >>> 8) & 0xFF);\n sps.push((len & 0xFF));\n\n // SPS\n sps = sps.concat(Array.prototype.slice.call(data));\n }\n\n // assemble the PPSs\n for (i = 0; i < track.pps.length; i++) {\n data = track.pps[i];\n len = data.byteLength;\n pps.push((len >>> 8) & 0xFF);\n pps.push((len & 0xFF));\n\n pps = pps.concat(Array.prototype.slice.call(data));\n }\n\n let avcc = MP4.box(MP4.types.avcC, new Uint8Array([\n 0x01, // version\n sps[3], // profile\n sps[4], // profile compat\n sps[5], // level\n 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes\n 0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets\n ].concat(sps).concat([\n track.pps.length // numOfPictureParameterSets\n ]).concat(pps))), // \"PPS\"\n width = track.width,\n height = track.height,\n hSpacing = track.pixelRatio[0],\n vSpacing = track.pixelRatio[1];\n\n return MP4.box(MP4.types.avc1, new Uint8Array([\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // data_reference_index\n 0x00, 0x00, // pre_defined\n 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n (width >> 8) & 0xFF,\n width & 0xff, // width\n (height >> 8) & 0xFF,\n height & 0xff, // height\n 0x00, 0x48, 0x00, 0x00, // horizresolution\n 0x00, 0x48, 0x00, 0x00, // vertresolution\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // frame_count\n 0x12,\n 0x64, 0x61, 0x69, 0x6C, // dailymotion/hls.js\n 0x79, 0x6D, 0x6F, 0x74,\n 0x69, 0x6F, 0x6E, 0x2F,\n 0x68, 0x6C, 0x73, 0x2E,\n 0x6A, 0x73, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, // compressorname\n 0x00, 0x18, // depth = 24\n 0x11, 0x11]), // pre_defined = -1\n avcc,\n MP4.box(MP4.types.btrt, new Uint8Array([\n 0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB\n 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate\n 0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate\n MP4.box(MP4.types.pasp, new Uint8Array([\n (hSpacing >> 24), // hSpacing\n (hSpacing >> 16) & 0xFF,\n (hSpacing >> 8) & 0xFF,\n hSpacing & 0xFF,\n (vSpacing >> 24), // vSpacing\n (vSpacing >> 16) & 0xFF,\n (vSpacing >> 8) & 0xFF,\n vSpacing & 0xFF]))\n );\n }\n\n static esds (track) {\n let configlen = track.config.length;\n return new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n\n 0x03, // descriptor_type\n 0x17 + configlen, // length\n 0x00, 0x01, // es_id\n 0x00, // stream_priority\n\n 0x04, // descriptor_type\n 0x0f + configlen, // length\n 0x40, // codec : mpeg4_audio\n 0x15, // stream_type\n 0x00, 0x00, 0x00, // buffer_size\n 0x00, 0x00, 0x00, 0x00, // maxBitrate\n 0x00, 0x00, 0x00, 0x00, // avgBitrate\n\n 0x05 // descriptor_type\n ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor\n }\n\n static mp4a (track) {\n let samplerate = track.samplerate;\n return MP4.box(MP4.types.mp4a, new Uint8Array([\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // data_reference_index\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, track.channelCount, // channelcount\n 0x00, 0x10, // sampleSize:16bits\n 0x00, 0x00, 0x00, 0x00, // reserved2\n (samplerate >> 8) & 0xFF,\n samplerate & 0xff, //\n 0x00, 0x00]),\n MP4.box(MP4.types.esds, MP4.esds(track)));\n }\n\n static mp3 (track) {\n let samplerate = track.samplerate;\n return MP4.box(MP4.types['.mp3'], new Uint8Array([\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // data_reference_index\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, track.channelCount, // channelcount\n 0x00, 0x10, // sampleSize:16bits\n 0x00, 0x00, 0x00, 0x00, // reserved2\n (samplerate >> 8) & 0xFF,\n samplerate & 0xff, //\n 0x00, 0x00]));\n }\n\n static stsd (track) {\n if (track.type === 'audio') {\n if (!track.isAAC && track.codec === 'mp3') {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));\n }\n\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));\n } else {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));\n }\n }\n\n static tkhd (track) {\n let id = track.id,\n duration = track.duration * track.timescale,\n width = track.width,\n height = track.height,\n upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)),\n lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(MP4.types.tkhd, new Uint8Array([\n 0x01, // version 1\n 0x00, 0x00, 0x07, // flags\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time\n (id >> 24) & 0xFF,\n (id >> 16) & 0xFF,\n (id >> 8) & 0xFF,\n id & 0xFF, // track_ID\n 0x00, 0x00, 0x00, 0x00, // reserved\n (upperWordDuration >> 24),\n (upperWordDuration >> 16) & 0xFF,\n (upperWordDuration >> 8) & 0xFF,\n upperWordDuration & 0xFF,\n (lowerWordDuration >> 24),\n (lowerWordDuration >> 16) & 0xFF,\n (lowerWordDuration >> 8) & 0xFF,\n lowerWordDuration & 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, // layer\n 0x00, 0x00, // alternate_group\n 0x00, 0x00, // non-audio track volume\n 0x00, 0x00, // reserved\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix\n (width >> 8) & 0xFF,\n width & 0xFF,\n 0x00, 0x00, // width\n (height >> 8) & 0xFF,\n height & 0xFF,\n 0x00, 0x00 // height\n ]));\n }\n\n static traf (track, baseMediaDecodeTime) {\n let sampleDependencyTable = MP4.sdtp(track),\n id = track.id,\n upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)),\n lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));\n return MP4.box(MP4.types.traf,\n MP4.box(MP4.types.tfhd, new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n (id >> 24),\n (id >> 16) & 0XFF,\n (id >> 8) & 0XFF,\n (id & 0xFF) // track_ID\n ])),\n MP4.box(MP4.types.tfdt, new Uint8Array([\n 0x01, // version 1\n 0x00, 0x00, 0x00, // flags\n (upperWordBaseMediaDecodeTime >> 24),\n (upperWordBaseMediaDecodeTime >> 16) & 0XFF,\n (upperWordBaseMediaDecodeTime >> 8) & 0XFF,\n (upperWordBaseMediaDecodeTime & 0xFF),\n (lowerWordBaseMediaDecodeTime >> 24),\n (lowerWordBaseMediaDecodeTime >> 16) & 0XFF,\n (lowerWordBaseMediaDecodeTime >> 8) & 0XFF,\n (lowerWordBaseMediaDecodeTime & 0xFF)\n ])),\n MP4.trun(track,\n sampleDependencyTable.length +\n 16 + // tfhd\n 20 + // tfdt\n 8 + // traf header\n 16 + // mfhd\n 8 + // moof header\n 8), // mdat header\n sampleDependencyTable);\n }\n\n /**\n * Generate a track box.\n * @param track {object} a track definition\n * @return {Uint8Array} the track box\n */\n static trak (track) {\n track.duration = track.duration || 0xffffffff;\n return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));\n }\n\n static trex (track) {\n let id = track.id;\n return MP4.box(MP4.types.trex, new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n (id >> 24),\n (id >> 16) & 0XFF,\n (id >> 8) & 0XFF,\n (id & 0xFF), // track_ID\n 0x00, 0x00, 0x00, 0x01, // default_sample_description_index\n 0x00, 0x00, 0x00, 0x00, // default_sample_duration\n 0x00, 0x00, 0x00, 0x00, // default_sample_size\n 0x00, 0x01, 0x00, 0x01 // default_sample_flags\n ]));\n }\n\n static trun (track, offset) {\n let samples = track.samples || [],\n len = samples.length,\n arraylen = 12 + (16 * len),\n array = new Uint8Array(arraylen),\n i, sample, duration, size, flags, cts;\n offset += 8 + arraylen;\n array.set([\n 0x00, // version 0\n 0x00, 0x0f, 0x01, // flags\n (len >>> 24) & 0xFF,\n (len >>> 16) & 0xFF,\n (len >>> 8) & 0xFF,\n len & 0xFF, // sample_count\n (offset >>> 24) & 0xFF,\n (offset >>> 16) & 0xFF,\n (offset >>> 8) & 0xFF,\n offset & 0xFF // data_offset\n ], 0);\n for (i = 0; i < len; i++) {\n sample = samples[i];\n duration = sample.duration;\n size = sample.size;\n flags = sample.flags;\n cts = sample.cts;\n array.set([\n (duration >>> 24) & 0xFF,\n (duration >>> 16) & 0xFF,\n (duration >>> 8) & 0xFF,\n duration & 0xFF, // sample_duration\n (size >>> 24) & 0xFF,\n (size >>> 16) & 0xFF,\n (size >>> 8) & 0xFF,\n size & 0xFF, // sample_size\n (flags.isLeading << 2) | flags.dependsOn,\n (flags.isDependedOn << 6) |\n (flags.hasRedundancy << 4) |\n (flags.paddingValue << 1) |\n flags.isNonSync,\n flags.degradPrio & 0xF0 << 8,\n flags.degradPrio & 0x0F, // sample_flags\n (cts >>> 24) & 0xFF,\n (cts >>> 16) & 0xFF,\n (cts >>> 8) & 0xFF,\n cts & 0xFF // sample_composition_time_offset\n ], 12 + 16 * i);\n }\n return MP4.box(MP4.types.trun, array);\n }\n\n static initSegment (tracks) {\n if (!MP4.types) {\n MP4.init();\n }\n\n let movie = MP4.moov(tracks), result;\n result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);\n result.set(MP4.FTYP);\n result.set(movie, MP4.FTYP.byteLength);\n return result;\n }\n}\n\nexport default MP4;\n","const MPEG_TS_CLOCK_FREQ_HZ = 90000;\n\nexport function toTimescaleFromScale (value, destScale: number, srcScale: number = 1, round: boolean = false): number {\n return toTimescaleFromBase(value, destScale, 1 / srcScale);\n}\n\nexport function toTimescaleFromBase (value, destScale: number, srcBase: number = 1, round: boolean = false): number {\n const result = value * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`\n return round ? Math.round(result) : result;\n}\n\nexport function toMsFromMpegTsClock (value: number, round: boolean = false): number {\n return toTimescaleFromBase(value, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);\n}\n\nexport function toMpegTsClockFromTimescale (value: number, srcScale: number = 1): number {\n return toTimescaleFromBase(value, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);\n}\n","/**\n * fMP4 remuxer\n*/\n\nimport AAC from './aac-helper';\nimport MP4 from './mp4-generator';\n\nimport Event from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport { toMsFromMpegTsClock, toMpegTsClockFromTimescale } from '../utils/timescale-conversion';\n\nimport { logger } from '../utils/logger';\n\nconst MAX_SILENT_FRAME_DURATION_90KHZ = toMpegTsClockFromTimescale(10);\nconst PTS_DTS_SHIFT_TOLERANCE_90KHZ = toMpegTsClockFromTimescale(0.2);\n\nlet chromeVersion = null;\n\nclass MP4Remuxer {\n constructor (observer, config, typeSupported, vendor) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n this.ISGenerated = false;\n if (chromeVersion === null) {\n const result = navigator.userAgent.match(/Chrome\\/(\\d+)/i);\n chromeVersion = result ? parseInt(result[1]) : 0;\n }\n }\n\n destroy () {\n }\n\n resetTimeStamp (defaultTimeStamp) {\n this._initPTS = this._initDTS = defaultTimeStamp;\n }\n\n resetInitSegment () {\n this.ISGenerated = false;\n }\n\n getVideoStartPts (videoSamples) {\n let rolloverDetected = false;\n const startPTS = videoSamples.reduce((minPTS, sample) => {\n const delta = sample.pts - minPTS;\n if (delta < -4294967296) { // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation\n rolloverDetected = true;\n return PTSNormalize(minPTS, sample.pts);\n } else if (delta > 0) {\n return minPTS;\n } else {\n return sample.pts;\n }\n }, videoSamples[0].pts);\n if (rolloverDetected) {\n logger.debug('PTS rollover detected');\n }\n return startPTS;\n }\n\n remux (audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {\n // generate Init Segment if needed\n if (!this.ISGenerated) {\n this.generateIS(audioTrack, videoTrack, timeOffset);\n }\n\n if (this.ISGenerated) {\n const nbAudioSamples = audioTrack.samples.length;\n const nbVideoSamples = videoTrack.samples.length;\n let audioTimeOffset = timeOffset;\n let videoTimeOffset = timeOffset;\n if (nbAudioSamples && nbVideoSamples) {\n // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)\n // if first audio DTS is not aligned with first video DTS then we need to take that into account\n // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small\n // drift between audio and video streams\n const startPTS = this.getVideoStartPts(videoTrack.samples);\n const tsDelta = PTSNormalize(audioTrack.samples[0].pts, startPTS) - startPTS;\n const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;\n audioTimeOffset += Math.max(0, audiovideoTimestampDelta);\n videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);\n }\n // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is\n // calculated in remuxAudio.\n // logger.log('nb AAC samples:' + audioTrack.samples.length);\n if (nbAudioSamples) {\n // if initSegment was generated without video samples, regenerate it again\n if (!audioTrack.timescale) {\n logger.warn('regenerate InitSegment as audio detected');\n this.generateIS(audioTrack, videoTrack, timeOffset);\n }\n let audioData = this.remuxAudio(audioTrack, audioTimeOffset, contiguous, accurateTimeOffset);\n // logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (nbVideoSamples) {\n let audioTrackLength;\n if (audioData) {\n audioTrackLength = audioData.endPTS - audioData.startPTS;\n }\n\n // if initSegment was generated without video samples, regenerate it again\n if (!videoTrack.timescale) {\n logger.warn('regenerate InitSegment as video detected');\n this.generateIS(audioTrack, videoTrack, timeOffset);\n }\n this.remuxVideo(videoTrack, videoTimeOffset, contiguous, audioTrackLength);\n }\n } else {\n // logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (nbVideoSamples) {\n let videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0, 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 },\n computePTSDTS = (this._initPTS === undefined),\n initPTS, initDTS;\n\n if (computePTSDTS) {\n initPTS = initDTS = Infinity;\n }\n\n if (audioTrack.config && audioSamples.length) {\n // let's use audio sampling rate as MP4 time scale.\n // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)\n // using audio sampling rate here helps having an integer MP4 frame duration\n // this avoids potential rounding issue and AV sync issue\n audioTrack.timescale = audioTrack.samplerate;\n logger.log(`audio sampling rate : ${audioTrack.samplerate}`);\n if (!audioTrack.isAAC) {\n if (typeSupported.mpeg) { // Chrome and Safari\n container = 'audio/mpeg';\n audioTrack.codec = '';\n } else if (typeSupported.mp3) { // Firefox\n audioTrack.codec = 'mp3';\n }\n }\n tracks.audio = {\n container: container,\n codec: audioTrack.codec,\n initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array() : MP4.initSegment([audioTrack]),\n metadata: {\n channelCount: audioTrack.channelCount\n }\n };\n if (computePTSDTS) {\n // remember first PTS of this demuxing context. for audio, PTS = DTS\n initPTS = initDTS = audioSamples[0].pts - Math.round(audioTrack.inputTimeScale * timeOffset);\n }\n }\n\n if (videoTrack.sps && videoTrack.pps && videoSamples.length) {\n // let's use input time scale as MP4 video timescale\n // we use input time scale straight away to avoid rounding issues on frame duration / cts computation\n const inputTimeScale = videoTrack.inputTimeScale;\n videoTrack.timescale = inputTimeScale;\n tracks.video = {\n container: 'video/mp4',\n codec: videoTrack.codec,\n initSegment: MP4.initSegment([videoTrack]),\n metadata: {\n width: videoTrack.width,\n height: videoTrack.height\n }\n };\n if (computePTSDTS) {\n const startPTS = this.getVideoStartPts(videoSamples);\n const startOffset = Math.round(inputTimeScale * timeOffset);\n initDTS = Math.min(initDTS, PTSNormalize(videoSamples[0].dts, startPTS) - startOffset);\n initPTS = Math.min(initPTS, startPTS - startOffset);\n this.observer.trigger(Event.INIT_PTS_FOUND, { initPTS });\n }\n } else if (computePTSDTS && tracks.audio) {\n // initPTS found for audio-only stream with main and alt audio\n this.observer.trigger(Event.INIT_PTS_FOUND, { initPTS });\n }\n\n if (Object.keys(tracks).length) {\n observer.trigger(Event.FRAG_PARSING_INIT_SEGMENT, data);\n this.ISGenerated = true;\n if (computePTSDTS) {\n this._initPTS = initPTS;\n this._initDTS = initDTS;\n }\n } else {\n observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' });\n }\n }\n\n remuxVideo (track, timeOffset, contiguous, audioTrackLength) {\n const timeScale = track.timescale;\n const inputSamples = track.samples;\n const outputSamples = [];\n const nbSamples = inputSamples.length;\n const initPTS = this._initPTS;\n\n let offset = 8;\n let mp4SampleDuration;\n let mdat;\n let moof;\n let firstDTS;\n let lastDTS;\n let minPTS = Number.POSITIVE_INFINITY;\n let maxPTS = Number.NEGATIVE_INFINITY;\n let ptsDtsShift = 0;\n let sortSamples = false;\n\n // if parsed fragment is contiguous with last one, let's use last DTS value as reference\n let nextAvcDts = this.nextAvcDts;\n\n if (nbSamples === 0) {\n return;\n }\n\n if (!contiguous) {\n const pts = timeOffset * timeScale;\n const cts = inputSamples[0].pts - PTSNormalize(inputSamples[0].dts, inputSamples[0].pts);\n // if not contiguous, let's use target timeOffset\n nextAvcDts = pts - cts;\n }\n\n // PTS is coded on 33bits, and can loop from -2^32 to 2^32\n // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value\n for (let i = 0; i < nbSamples; i++) {\n const sample = inputSamples[i];\n sample.pts = PTSNormalize(sample.pts - initPTS, nextAvcDts);\n sample.dts = PTSNormalize(sample.dts - initPTS, nextAvcDts);\n if (sample.dts > sample.pts) {\n ptsDtsShift = Math.max(Math.min(ptsDtsShift, sample.pts - sample.dts), -1 * PTS_DTS_SHIFT_TOLERANCE_90KHZ);\n }\n if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {\n sortSamples = true;\n }\n }\n\n // sort video samples by DTS then PTS then demux id order\n if (sortSamples) {\n inputSamples.sort(function (a, b) {\n const deltadts = a.dts - b.dts;\n const deltapts = a.pts - b.pts;\n return deltadts || (deltapts || (a.id - b.id));\n });\n }\n\n // Get first/last DTS\n firstDTS = inputSamples[0].dts;\n lastDTS = inputSamples[nbSamples - 1].dts;\n\n // on Safari let's signal the same sample duration for all samples\n // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS\n // set this constant duration as being the avg delta between consecutive DTS.\n const averageSampleDuration = Math.round((lastDTS - firstDTS) / (nbSamples - 1));\n\n // handle broken streams with PTS < DTS, tolerance up 0.2 seconds\n if (ptsDtsShift < 0) {\n if (ptsDtsShift < averageSampleDuration * -2) {\n // Fix for \"CNN special report, with CC\" in test-streams (including Safari browser)\n // With large PTS < DTS errors such as this, we want to correct CTS while maintaining increasing DTS values\n logger.warn(`PTS < DTS detected in video samples, offsetting DTS from PTS by ${toMsFromMpegTsClock(-averageSampleDuration, true)} ms`);\n let lastDts = ptsDtsShift;\n for (let i = 0; i < nbSamples; i++) {\n inputSamples[i].dts = lastDts = Math.max(lastDts, inputSamples[i].pts - averageSampleDuration);\n inputSamples[i].pts = Math.max(lastDts, inputSamples[i].pts);\n }\n } else {\n // Fix for \"Custom IV with bad PTS DTS\" in test-streams\n // With smaller PTS < DTS errors we can simply move all DTS back. This increases CTS without causing buffer gaps or decode errors in Safari\n logger.warn(`PTS < DTS detected in video samples, shifting DTS by ${toMsFromMpegTsClock(ptsDtsShift, true)} ms to overcome this issue`);\n for (let i = 0; i < nbSamples; i++) {\n inputSamples[i].dts = inputSamples[i].dts + ptsDtsShift;\n }\n }\n firstDTS = inputSamples[0].dts;\n lastDTS = inputSamples[nbSamples - 1].dts;\n }\n\n // if fragment are contiguous, detect hole/overlapping between fragments\n if (contiguous) {\n // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)\n const delta = firstDTS - nextAvcDts;\n const foundHole = delta > averageSampleDuration;\n const foundOverlap = delta < -1;\n if (foundHole || foundOverlap) {\n if (foundHole) {\n logger.warn(`AVC: ${toMsFromMpegTsClock(delta, true)} ms (${delta}dts) hole between fragments detected, filling it`);\n } else {\n logger.warn(`AVC: ${toMsFromMpegTsClock(-delta, true)} ms (${delta}dts) overlapping between fragments detected`);\n }\n firstDTS = nextAvcDts;\n const firstPTS = inputSamples[0].pts - delta;\n inputSamples[0].dts = firstDTS;\n inputSamples[0].pts = firstPTS;\n logger.log(`Video: First PTS/DTS adjusted: ${toMsFromMpegTsClock(firstPTS, true)}/${toMsFromMpegTsClock(firstDTS, true)}, delta: ${toMsFromMpegTsClock(delta, true)} ms`);\n }\n }\n\n if (chromeVersion && chromeVersion < 75) {\n firstDTS = Math.max(0, firstDTS);\n }\n let nbNalu = 0;\n let naluLen = 0;\n for (let i = 0; i < nbSamples; i++) {\n // compute total/avc sample length and nb of NAL units\n const sample = inputSamples[i];\n const units = sample.units;\n const nbUnits = units.length;\n let sampleLen = 0;\n for (let j = 0; j < nbUnits; j++) {\n sampleLen += units[j].data.length;\n }\n\n naluLen += sampleLen;\n nbNalu += nbUnits;\n sample.length = sampleLen;\n\n // normalize PTS/DTS\n // ensure sample monotonic DTS\n sample.dts = Math.max(sample.dts, firstDTS);\n // ensure that computed value is greater or equal than sample DTS\n sample.pts = Math.max(sample.pts, sample.dts, 0);\n minPTS = Math.min(sample.pts, minPTS);\n maxPTS = Math.max(sample.pts, maxPTS);\n }\n lastDTS = inputSamples[nbSamples - 1].dts;\n\n /* concatenate the video data and construct the mdat in place\n (need 8 more bytes to fill length and mpdat type) */\n let mdatSize = naluLen + (4 * nbNalu) + 8;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch (err) {\n this.observer.trigger(Event.ERROR, { type: ErrorTypes.MUX_ERROR, details: ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: `fail allocating video mdat ${mdatSize}` });\n return;\n }\n let view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n\n for (let i = 0; i < nbSamples; i++) {\n const avcSample = inputSamples[i];\n const avcSampleUnits = avcSample.units;\n let mp4SampleLength = 0;\n let compositionTimeOffset;\n // convert NALU bitstream to MP4 format (prepend NALU with size field)\n for (let j = 0, nbUnits = avcSampleUnits.length; j < nbUnits; j++) {\n const unit = avcSampleUnits[j];\n const unitData = unit.data;\n const unitDataLen = unit.data.byteLength;\n view.setUint32(offset, unitDataLen);\n offset += 4;\n mdat.set(unitData, offset);\n offset += unitDataLen;\n mp4SampleLength += 4 + unitDataLen;\n }\n\n // expected sample duration is the Decoding Timestamp diff of consecutive samples\n if (i < nbSamples - 1) {\n mp4SampleDuration = inputSamples[i + 1].dts - avcSample.dts;\n } else {\n const config = this.config;\n const lastFrameDuration = avcSample.dts - inputSamples[i > 0 ? i - 1 : i].dts;\n if (config.stretchShortVideoTrack) {\n // In some cases, a segment's audio track duration may exceed the video track duration.\n // Since we've already remuxed audio, and we know how long the audio track is, we look to\n // see if the delta to the next segment is longer than maxBufferHole.\n // If so, playback would potentially get stuck, so we artificially inflate\n // the duration of the last frame to minimize any potential gap between segments.\n const maxBufferHole = config.maxBufferHole;\n const gapTolerance = Math.floor(maxBufferHole * timeScale);\n const deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;\n if (deltaToFrameEnd > gapTolerance) {\n // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video\n // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.\n mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;\n if (mp4SampleDuration < 0) {\n mp4SampleDuration = lastFrameDuration;\n }\n\n logger.log(`It is approximately ${toMsFromMpegTsClock(deltaToFrameEnd, false)} ms to the next segment; using duration ${toMsFromMpegTsClock(mp4SampleDuration, false)} ms for the last video frame.`);\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n }\n compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);\n\n // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}');\n outputSamples.push({\n size: mp4SampleLength,\n // constant duration\n duration: mp4SampleDuration,\n cts: compositionTimeOffset,\n flags: {\n isLeading: 0,\n isDependedOn: 0,\n hasRedundancy: 0,\n degradPrio: 0,\n dependsOn: avcSample.key ? 2 : 1,\n isNonSync: avcSample.key ? 0 : 1\n }\n });\n }\n // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)\n this.nextAvcDts = lastDTS + mp4SampleDuration;\n const dropped = track.dropped;\n track.nbNalu = 0;\n track.dropped = 0;\n if (outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {\n const flags = outputSamples[0].flags;\n // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue\n // https://code.google.com/p/chromium/issues/detail?id=229412\n flags.dependsOn = 2;\n flags.isNonSync = 0;\n }\n track.samples = outputSamples;\n moof = MP4.moof(track.sequenceNumber++, firstDTS, track);\n track.samples = [];\n\n const data = {\n data1: moof,\n data2: mdat,\n startPTS: minPTS / timeScale,\n endPTS: (maxPTS + mp4SampleDuration) / timeScale,\n startDTS: firstDTS / timeScale,\n endDTS: this.nextAvcDts / timeScale,\n type: 'video',\n hasAudio: false,\n hasVideo: true,\n nb: outputSamples.length,\n dropped: dropped\n };\n this.observer.trigger(Event.FRAG_PARSING_DATA, data);\n return data;\n }\n\n remuxAudio (track, timeOffset, contiguous, accurateTimeOffset) {\n const inputTimeScale = track.inputTimeScale;\n const mp4timeScale = track.timescale;\n const scaleFactor = inputTimeScale / mp4timeScale;\n const mp4SampleDuration = track.isAAC ? 1024 : 1152;\n const inputSampleDuration = mp4SampleDuration * scaleFactor;\n const initPTS = this._initPTS;\n const rawMPEG = !track.isAAC && this.typeSupported.mpeg;\n\n let mp4Sample;\n let fillFrame;\n let mdat;\n let moof;\n let firstPTS;\n let lastPTS;\n let offset = (rawMPEG ? 0 : 8);\n let inputSamples = track.samples;\n let outputSamples = [];\n let nextAudioPts = this.nextAudioPts;\n\n // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),\n // for sake of clarity:\n // consecutive fragments are frags with\n // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR\n // - less than 20 audio frames distance\n // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)\n // this helps ensuring audio continuity\n // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame\n contiguous |= (inputSamples.length && nextAudioPts &&\n ((accurateTimeOffset && Math.abs(timeOffset - nextAudioPts / inputTimeScale) < 0.1) ||\n Math.abs((inputSamples[0].pts - nextAudioPts - initPTS)) < 20 * inputSampleDuration)\n );\n\n // compute normalized PTS\n inputSamples.forEach(function (sample) {\n sample.pts = sample.dts = PTSNormalize(sample.pts - initPTS, timeOffset * inputTimeScale);\n });\n\n // filter out sample with negative PTS that are not playable anyway\n // if we don't remove these negative samples, they will shift all audio samples forward.\n // leading to audio overlap between current / next fragment\n inputSamples = inputSamples.filter((sample) => sample.pts >= 0);\n\n // in case all samples have negative PTS, and have been filtered out, return now\n if (inputSamples.length === 0) {\n return;\n }\n\n if (!contiguous) {\n if (!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 = Math.max(0, 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 const sample = inputSamples[i];\n let pts = sample.pts;\n let delta = pts - nextPts;\n\n // If we're overlapping by more than a duration, drop this sample\n if (delta <= -maxAudioFramesDrift * inputSampleDuration) {\n if (contiguous || i > 0) {\n logger.warn(`Dropping 1 audio frame @ ${toMsFromMpegTsClock(nextPts, true) / 1000}s due to ${toMsFromMpegTsClock(delta, true)} ms overlap.`);\n inputSamples.splice(i, 1);\n // Don't touch nextPtsNorm or i\n } else {\n // When changing qualities we can't trust that audio has been appended up to nextAudioPts\n // Warn about the overlap but do not drop samples as that can introduce buffer gaps\n logger.warn(`Audio frame @ ${toMsFromMpegTsClock(pts, true) / 1000}s overlaps nextAudioPts by ${toMsFromMpegTsClock(delta, true)} ms.`);\n nextPts = pts + inputSampleDuration;\n i++;\n }\n } // eslint-disable-line brace-style\n\n // Insert missing frames if:\n // 1: We're more than maxAudioFramesDrift frame away\n // 2: Not more than MAX_SILENT_FRAME_DURATION away\n // 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) / 1000}s due to ${toMsFromMpegTsClock(delta, true)} ms gap.`);\n for (let j = 0; j < missing; j++) {\n let newStamp = Math.max(nextPts, 0);\n fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n if (!fillFrame) {\n logger.log('Unable to get silent frame for given audio codec; duplicating last frame instead.');\n fillFrame = sample.unit.subarray();\n }\n inputSamples.splice(i, 0, { unit: fillFrame, pts: newStamp, dts: newStamp });\n nextPts += inputSampleDuration;\n i++;\n }\n\n // Adjust sample to next expected pts\n sample.pts = sample.dts = nextPts;\n nextPts += inputSampleDuration;\n i++;\n } else {\n // Otherwise, just adjust pts\n if (Math.abs(delta) > (0.1 * inputSampleDuration)) {\n // logger.log(`Invalid frame delta ${Math.round(delta + inputSampleDuration)} at PTS ${Math.round(pts / 90)} (should be ${Math.round(inputSampleDuration)}).`);\n }\n sample.pts = sample.dts = nextPts;\n nextPts += inputSampleDuration;\n i++;\n }\n }\n }\n\n // compute mdat size, as we eventually filtered/added some samples\n let nbSamples = inputSamples.length;\n let mdatSize = 0;\n while (nbSamples--) {\n mdatSize += inputSamples[nbSamples].unit.byteLength;\n }\n\n for (let j = 0, nbSamples = inputSamples.length; j < nbSamples; j++) {\n let audioSample = inputSamples[j];\n let unit = audioSample.unit;\n let pts = audioSample.pts;\n\n // logger.log(`Audio/PTS:${toMsFromMpegTsClock(pts, true)}`);\n // if not first sample\n\n if (lastPTS !== undefined && mp4Sample) {\n mp4Sample.duration = Math.round((pts - lastPTS) / scaleFactor);\n } else {\n let delta = pts - nextAudioPts;\n let numMissingFrames = 0;\n\n // if fragment are contiguous, detect hole/overlapping between fragments\n // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)\n if (contiguous && track.isAAC) {\n // log delta\n if (delta) {\n if (delta > 0 && delta < MAX_SILENT_FRAME_DURATION_90KHZ) {\n // Q: why do we have to round here, shouldn't this always result in an integer if timestamps are correct,\n // and if not, shouldn't we actually Math.ceil() instead?\n numMissingFrames = Math.round((pts - nextAudioPts) / inputSampleDuration);\n\n logger.log(`${toMsFromMpegTsClock(delta, true)} ms hole between AAC samples detected,filling it`);\n if (numMissingFrames > 0) {\n fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n if (!fillFrame) {\n fillFrame = unit.subarray();\n }\n\n mdatSize += numMissingFrames * fillFrame.length;\n }\n // if we have frame overlap, overlapping for more than half a frame duraion\n } else if (delta < -12) {\n // drop overlapping audio frames... browser will deal with it\n logger.log(`drop overlapping AAC sample, expected/parsed/delta: ${toMsFromMpegTsClock(nextAudioPts, true)} ms / ${toMsFromMpegTsClock(pts, true)} ms / ${toMsFromMpegTsClock(-delta, true)} ms`);\n mdatSize -= unit.byteLength;\n continue;\n }\n // set PTS/DTS to expected PTS/DTS\n pts = nextAudioPts;\n }\n }\n // remember first PTS of our audioSamples\n firstPTS = pts;\n if (mdatSize > 0) {\n mdatSize += offset;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch (err) {\n this.observer.trigger(Event.ERROR, { type: ErrorTypes.MUX_ERROR, details: ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: `fail allocating audio mdat ${mdatSize}` });\n return;\n }\n if (!rawMPEG) {\n const view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n }\n } else {\n // no audio samples\n return;\n }\n for (let i = 0; i < numMissingFrames; i++) {\n fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n if (!fillFrame) {\n logger.log('Unable to get silent frame for given audio codec; duplicating this frame instead.');\n fillFrame = unit.subarray();\n }\n mdat.set(fillFrame, offset);\n offset += fillFrame.byteLength;\n mp4Sample = {\n size: fillFrame.byteLength,\n cts: 0,\n duration: 1024,\n flags: {\n isLeading: 0,\n isDependedOn: 0,\n hasRedundancy: 0,\n degradPrio: 0,\n dependsOn: 1\n }\n };\n outputSamples.push(mp4Sample);\n }\n }\n mdat.set(unit, offset);\n let unitLen = unit.byteLength;\n offset += unitLen;\n // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${audioSample.pts}/${audioSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(audioSample.pts/4294967296).toFixed(3)}');\n mp4Sample = {\n size: unitLen,\n cts: 0,\n duration: 0,\n flags: {\n isLeading: 0,\n isDependedOn: 0,\n hasRedundancy: 0,\n degradPrio: 0,\n dependsOn: 1\n }\n };\n outputSamples.push(mp4Sample);\n lastPTS = pts;\n }\n let lastSampleDuration = 0;\n nbSamples = outputSamples.length;\n // set last sample duration as being identical to previous sample\n if (nbSamples >= 2) {\n lastSampleDuration = outputSamples[nbSamples - 2].duration;\n mp4Sample.duration = lastSampleDuration;\n }\n if (nbSamples) {\n // next audio sample PTS should be equal to last sample PTS + duration\n this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSampleDuration;\n // logger.log('Audio/PTS/PTSend:' + audioSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0));\n track.samples = outputSamples;\n if (rawMPEG) {\n moof = new Uint8Array();\n } else {\n moof = MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, track);\n }\n\n track.samples = [];\n const start = firstPTS / inputTimeScale;\n const end = nextAudioPts / inputTimeScale;\n const audioData = {\n data1: moof,\n data2: mdat,\n startPTS: start,\n endPTS: end,\n startDTS: start,\n endDTS: end,\n type: 'audio',\n hasAudio: true,\n hasVideo: false,\n nb: nbSamples\n };\n this.observer.trigger(Event.FRAG_PARSING_DATA, audioData);\n return audioData;\n }\n return null;\n }\n\n remuxEmptyAudio (track, timeOffset, contiguous, videoData) {\n let inputTimeScale = track.inputTimeScale;\n let mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;\n let scaleFactor = inputTimeScale / mp4timeScale;\n let nextAudioPts = this.nextAudioPts;\n\n // sync with video's timestamp\n let startDTS = (nextAudioPts !== undefined ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS;\n let endDTS = videoData.endDTS * inputTimeScale + this._initDTS;\n // one sample's duration value\n let sampleDuration = 1024;\n let frameDuration = scaleFactor * sampleDuration;\n\n // samples count of this segment's duration\n let nbSamples = Math.ceil((endDTS - startDTS) / frameDuration);\n\n // silent frame\n let silentFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n\n logger.warn('remux empty Audio');\n // Can't remux if we can't generate a silent frame...\n if (!silentFrame) {\n logger.trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!');\n return;\n }\n\n let samples = [];\n for (let i = 0; i < nbSamples; i++) {\n let stamp = startDTS + i * frameDuration;\n samples.push({ unit: silentFrame, pts: stamp, dts: stamp });\n }\n track.samples = samples;\n\n this.remuxAudio(track, timeOffset, contiguous);\n }\n\n remuxID3 (track, timeOffset) {\n const length = track.samples.length;\n if (!length) {\n return;\n }\n const inputTimeScale = track.inputTimeScale;\n const initPTS = this._initPTS;\n const initDTS = this._initDTS;\n // consume samples\n for (let index = 0; index < length; index++) {\n const sample = track.samples[index];\n // setting id3 pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts = PTSNormalize(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;\n sample.dts = PTSNormalize(sample.dts - initDTS, timeOffset * inputTimeScale) / inputTimeScale;\n }\n this.observer.trigger(Event.FRAG_PARSING_METADATA, {\n samples: track.samples\n });\n\n track.samples = [];\n }\n\n remuxText (track, timeOffset) {\n const length = track.samples.length;\n const inputTimeScale = track.inputTimeScale;\n const initPTS = this._initPTS;\n // consume samples\n if (length) {\n for (let index = 0; index < length; index++) {\n const sample = track.samples[index];\n // setting text pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts = PTSNormalize(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;\n }\n track.samples.sort(function (a, b) {\n return (a.pts - b.pts);\n });\n this.observer.trigger(Event.FRAG_PARSING_USERDATA, {\n samples: track.samples\n });\n }\n\n track.samples = [];\n }\n}\n\nfunction PTSNormalize (value, reference) {\n let offset;\n if (reference === undefined) {\n return value;\n }\n\n if (reference < value) {\n // - 2^33\n offset = -8589934592;\n } else {\n // + 2^33\n offset = 8589934592;\n }\n /* PTS is 33bit (from 0 to 2^33 -1)\n if diff between value and reference is bigger than half of the amplitude (2^32) then it means that\n PTS looping occured. fill the gap */\n while (Math.abs(value - reference) > 4294967296) {\n value += offset;\n }\n\n return value;\n}\n\nexport default MP4Remuxer;\n","/**\n *\n * inline demuxer: probe fragments and instantiate\n * appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)\n *\n */\n\nimport Event from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport Decrypter from '../crypt/decrypter';\nimport AACDemuxer from '../demux/aacdemuxer';\nimport MP4Demuxer from '../demux/mp4demuxer';\nimport TSDemuxer from '../demux/tsdemuxer';\nimport MP3Demuxer from '../demux/mp3demuxer';\nimport MP4Remuxer from '../remux/mp4-remuxer';\nimport PassThroughRemuxer from '../remux/passthrough-remuxer';\n\nimport { getSelfScope } from '../utils/get-self-scope';\nimport { logger } from '../utils/logger';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\n\nlet now;\n// performance.now() not available on WebWorker, at least on Safari Desktop\ntry {\n now = global.performance.now.bind(global.performance);\n} catch (err) {\n logger.debug('Unable to use Performance API on this environment');\n now = global.Date.now;\n}\n\nclass DemuxerInline {\n constructor (observer, typeSupported, config, vendor) {\n this.observer = observer;\n this.typeSupported = typeSupported;\n this.config = config;\n this.vendor = vendor;\n }\n\n destroy () {\n let demuxer = this.demuxer;\n if (demuxer) {\n demuxer.destroy();\n }\n }\n\n push (data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {\n if ((data.byteLength > 0) && (decryptdata != null) && (decryptdata.key != null) && (decryptdata.method === 'AES-128')) {\n let decrypter = this.decrypter;\n if (decrypter == null) {\n decrypter = this.decrypter = new Decrypter(this.observer, this.config);\n }\n\n const startTime = now();\n decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, (decryptedData) => {\n const endTime = now();\n this.observer.trigger(Event.FRAG_DECRYPTED, { stats: { tstart: startTime, tdecrypt: endTime } });\n this.pushDecrypted(new Uint8Array(decryptedData), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);\n });\n } else {\n this.pushDecrypted(new Uint8Array(data), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);\n }\n }\n\n pushDecrypted (data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {\n let demuxer = this.demuxer;\n let remuxer = this.remuxer;\n if (!demuxer ||\n // in case of continuity change, or track switch\n // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)\n (discontinuity || trackSwitch)) {\n const observer = this.observer;\n const typeSupported = this.typeSupported;\n const config = this.config;\n // probing order is TS/MP4/AAC/MP3\n const muxConfig = [\n { demux: TSDemuxer, remux: MP4Remuxer },\n { demux: MP4Demuxer, remux: PassThroughRemuxer },\n { demux: AACDemuxer, remux: MP4Remuxer },\n { demux: MP3Demuxer, remux: MP4Remuxer }\n ];\n\n // probe for content type\n let mux;\n for (let i = 0, len = muxConfig.length; i < len; i++) {\n mux = muxConfig[i];\n if (mux.demux.probe(data)) {\n break;\n }\n }\n if (!mux) {\n observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found' });\n return;\n }\n // so let's check that current remuxer and demuxer are still valid\n if (!remuxer || !(remuxer instanceof mux.remux)) {\n remuxer = new mux.remux(observer, config, typeSupported, this.vendor);\n }\n if (!demuxer || !(demuxer instanceof mux.demux)) {\n demuxer = new mux.demux(observer, remuxer, config, typeSupported);\n this.probe = mux.demux.probe;\n }\n this.demuxer = demuxer;\n this.remuxer = remuxer;\n }\n\n if (discontinuity || trackSwitch) {\n demuxer.resetInitSegment(initSegment, audioCodec, videoCodec, duration);\n remuxer.resetInitSegment();\n }\n if (discontinuity) {\n demuxer.resetTimeStamp(defaultInitPTS);\n remuxer.resetTimeStamp(defaultInitPTS);\n }\n if (typeof demuxer.setDecryptData === 'function') {\n demuxer.setDecryptData(decryptdata);\n }\n\n demuxer.append(data, timeOffset, contiguous, accurateTimeOffset);\n }\n}\n\nexport default DemuxerInline;\n","/**\n * passthrough remuxer\n*/\nimport Event from '../events';\n\nclass PassThroughRemuxer {\n constructor (observer) {\n this.observer = observer;\n }\n\n destroy () {\n }\n\n resetTimeStamp () {\n }\n\n resetInitSegment () {\n }\n\n remux (audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset, rawData) {\n let observer = this.observer;\n let streamType = '';\n if (audioTrack) {\n streamType += 'audio';\n }\n\n if (videoTrack) {\n streamType += 'video';\n }\n\n observer.trigger(Event.FRAG_PARSING_DATA, {\n data1: rawData,\n startPTS: timeOffset,\n startDTS: timeOffset,\n type: streamType,\n hasAudio: !!audioTrack,\n hasVideo: !!videoTrack,\n nb: 1,\n dropped: 0\n });\n // notify end of parsing\n observer.trigger(Event.FRAG_PARSED);\n }\n}\n\nexport default PassThroughRemuxer;\n","/**\n * MP4 demuxer\n */\nimport { logger } from '../utils/logger';\nimport Event from '../events';\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\n\nclass MP4Demuxer {\n constructor (observer, remuxer) {\n this.observer = observer;\n this.remuxer = remuxer;\n }\n\n resetTimeStamp (initPTS) {\n this.initPTS = initPTS;\n }\n\n resetInitSegment (initSegment, audioCodec, videoCodec, duration) {\n // jshint unused:false\n if (initSegment && initSegment.byteLength) {\n const initData = this.initData = MP4Demuxer.parseInitSegment(initSegment);\n\n // default audio codec if nothing specified\n // TODO : extract that from initsegment\n if (audioCodec == null) {\n audioCodec = 'mp4a.40.5';\n }\n\n if (videoCodec == null) {\n videoCodec = 'avc1.42e01e';\n }\n\n const tracks = {};\n if (initData.audio && initData.video) {\n tracks.audiovideo = { container: 'video/mp4', codec: audioCodec + ',' + videoCodec, initSegment: duration ? initSegment : null };\n } else {\n if (initData.audio) {\n tracks.audio = { container: 'audio/mp4', codec: audioCodec, initSegment: duration ? initSegment : null };\n }\n\n if (initData.video) {\n tracks.video = { container: 'video/mp4', codec: videoCodec, initSegment: duration ? initSegment : null };\n }\n }\n this.observer.trigger(Event.FRAG_PARSING_INIT_SEGMENT, { tracks });\n } else {\n if (audioCodec) {\n this.audioCodec = audioCodec;\n }\n\n if (videoCodec) {\n this.videoCodec = videoCodec;\n }\n }\n }\n\n static probe (data) {\n // ensure we find a moof box in the first 16 kB\n return MP4Demuxer.findBox({ data: data, start: 0, end: Math.min(data.length, 16384) }, ['moof']).length > 0;\n }\n\n static bin2str (buffer) {\n return String.fromCharCode.apply(null, buffer);\n }\n\n static readUint16 (buffer, offset) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n\n const val = buffer[offset] << 8 |\n buffer[offset + 1];\n\n return val < 0 ? 65536 + val : val;\n }\n\n static readUint32 (buffer, offset) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n\n const val = buffer[offset] << 24 |\n buffer[offset + 1] << 16 |\n buffer[offset + 2] << 8 |\n buffer[offset + 3];\n return val < 0 ? 4294967296 + val : val;\n }\n\n static writeUint32 (buffer, offset, value) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n buffer[offset] = value >> 24;\n buffer[offset + 1] = (value >> 16) & 0xff;\n buffer[offset + 2] = (value >> 8) & 0xff;\n buffer[offset + 3] = value & 0xff;\n }\n\n // Find the data for a box specified by its path\n static findBox (data, path) {\n let results = [],\n i, size, type, end, subresults, start, endbox;\n\n if (data.data) {\n start = data.start;\n end = data.end;\n data = data.data;\n } else {\n start = 0;\n end = data.byteLength;\n }\n\n if (!path.length) {\n // short-circuit the search for empty paths\n return null;\n }\n\n for (i = start; i < end;) {\n size = MP4Demuxer.readUint32(data, i);\n type = MP4Demuxer.bin2str(data.subarray(i + 4, i + 8));\n endbox = size > 1 ? i + size : end;\n\n if (type === path[0]) {\n if (path.length === 1) {\n // this is the end of the path and we've found the box we were\n // looking for\n results.push({ data: data, start: i + 8, end: endbox });\n } else {\n // recursively search for the next box along the path\n subresults = MP4Demuxer.findBox({ data: data, start: i + 8, end: endbox }, path.slice(1));\n if (subresults.length) {\n results = results.concat(subresults);\n }\n }\n }\n i = endbox;\n }\n\n // we've finished searching all of data\n return results;\n }\n\n static parseSegmentIndex (initSegment) {\n const moov = MP4Demuxer.findBox(initSegment, ['moov'])[0];\n const moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data\n\n let index = 0;\n let sidx = MP4Demuxer.findBox(initSegment, ['sidx']);\n let references;\n\n if (!sidx || !sidx[0]) {\n return null;\n }\n\n references = [];\n sidx = sidx[0];\n\n const version = sidx.data[0];\n\n // set initial offset, we skip the reference ID (not needed)\n index = version === 0 ? 8 : 16;\n\n const timescale = MP4Demuxer.readUint32(sidx, index);\n index += 4;\n\n // TODO: parse earliestPresentationTime and firstOffset\n // usually zero in our case\n let earliestPresentationTime = 0;\n let firstOffset = 0;\n\n if (version === 0) {\n index += 8;\n } else {\n index += 16;\n }\n\n // skip reserved\n index += 2;\n\n let startByte = sidx.end + firstOffset;\n\n const referencesCount = MP4Demuxer.readUint16(sidx, index);\n index += 2;\n\n for (let i = 0; i < referencesCount; i++) {\n let referenceIndex = index;\n\n const referenceInfo = MP4Demuxer.readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n const referenceSize = referenceInfo & 0x7FFFFFFF;\n const referenceType = (referenceInfo & 0x80000000) >>> 31;\n\n if (referenceType === 1) {\n console.warn('SIDX has hierarchical references (not supported)');\n return;\n }\n\n const subsegmentDuration = MP4Demuxer.readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n references.push({\n referenceSize,\n subsegmentDuration, // unscaled\n info: {\n duration: subsegmentDuration / timescale,\n start: startByte,\n end: startByte + referenceSize - 1\n }\n });\n\n startByte += referenceSize;\n\n // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits\n // for |sapDelta|.\n referenceIndex += 4;\n\n // skip to next ref\n index = referenceIndex;\n }\n\n return {\n earliestPresentationTime,\n timescale,\n version,\n referencesCount,\n references,\n moovEndOffset\n };\n }\n\n /**\n * Parses an MP4 initialization segment and extracts stream type and\n * timescale values for any declared tracks. Timescale values indicate the\n * number of clock ticks per second to assume for time-based values\n * elsewhere in the MP4.\n *\n * To determine the start time of an MP4, you need two pieces of\n * information: the timescale unit and the earliest base media decode\n * time. Multiple timescales can be specified within an MP4 but the\n * base media decode time is always expressed in the timescale from\n * the media header box for the track:\n * ```\n * moov > trak > mdia > mdhd.timescale\n * moov > trak > mdia > hdlr\n * ```\n * @param init {Uint8Array} the bytes of the init segment\n * @return {object} a hash of track type to timescale values or null if\n * the init segment is malformed.\n */\n static parseInitSegment (initSegment) {\n let result = [];\n let traks = MP4Demuxer.findBox(initSegment, ['moov', 'trak']);\n\n traks.forEach(trak => {\n const tkhd = MP4Demuxer.findBox(trak, ['tkhd'])[0];\n if (tkhd) {\n let version = tkhd.data[tkhd.start];\n let index = version === 0 ? 12 : 20;\n let trackId = MP4Demuxer.readUint32(tkhd, index);\n\n const mdhd = MP4Demuxer.findBox(trak, ['mdia', 'mdhd'])[0];\n if (mdhd) {\n version = mdhd.data[mdhd.start];\n index = version === 0 ? 12 : 20;\n const timescale = MP4Demuxer.readUint32(mdhd, index);\n\n const hdlr = MP4Demuxer.findBox(trak, ['mdia', 'hdlr'])[0];\n if (hdlr) {\n const hdlrType = MP4Demuxer.bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));\n let type = { 'soun': 'audio', 'vide': 'video' }[hdlrType];\n if (type) {\n // extract codec info. TODO : parse codec details to be able to build MIME type\n let codecBox = MP4Demuxer.findBox(trak, ['mdia', 'minf', 'stbl', 'stsd']);\n if (codecBox.length) {\n codecBox = codecBox[0];\n let codecType = MP4Demuxer.bin2str(codecBox.data.subarray(codecBox.start + 12, codecBox.start + 16));\n logger.log(`MP4Demuxer:${type}:${codecType} found`);\n }\n result[trackId] = { timescale: timescale, type: type };\n result[type] = { timescale: timescale, id: trackId };\n }\n }\n }\n }\n });\n return result;\n }\n\n /**\n * Determine the base media decode start time, in seconds, for an MP4\n * fragment. If multiple fragments are specified, the earliest time is\n * returned.\n *\n * The base media decode time can be parsed from track fragment\n * metadata:\n * ```\n * moof > traf > tfdt.baseMediaDecodeTime\n * ```\n * It requires the timescale value from the mdhd to interpret.\n *\n * @param timescale {object} a hash of track ids to timescale values.\n * @return {number} the earliest base media decode start time for the\n * fragment, in seconds\n */\n static getStartDTS (initData, fragment) {\n let trafs, baseTimes, result;\n\n // we need info from two childrend of each track fragment box\n trafs = MP4Demuxer.findBox(fragment, ['moof', 'traf']);\n\n // determine the start times for each track\n baseTimes = [].concat.apply([], trafs.map(function (traf) {\n return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {\n let id, scale, baseTime;\n\n // get the track id from the tfhd\n id = MP4Demuxer.readUint32(tfhd, 4);\n // assume a 90kHz clock if no timescale was specified\n scale = initData[id].timescale || 90e3;\n\n // get the base media decode time from the tfdt\n baseTime = MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {\n let version, result;\n\n version = tfdt.data[tfdt.start];\n result = MP4Demuxer.readUint32(tfdt, 4);\n if (version === 1) {\n result *= Math.pow(2, 32);\n\n result += MP4Demuxer.readUint32(tfdt, 8);\n }\n return result;\n })[0];\n // convert base time to seconds\n return baseTime / scale;\n });\n }));\n\n // return the minimum\n result = Math.min.apply(null, baseTimes);\n return isFinite(result) ? result : 0;\n }\n\n static offsetStartDTS (initData, fragment, timeOffset) {\n MP4Demuxer.findBox(fragment, ['moof', 'traf']).map(function (traf) {\n return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {\n // get the track id from the tfhd\n let id = MP4Demuxer.readUint32(tfhd, 4);\n // assume a 90kHz clock if no timescale was specified\n let timescale = initData[id].timescale || 90e3;\n\n // get the base media decode time from the tfdt\n MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {\n let version = tfdt.data[tfdt.start];\n let baseMediaDecodeTime = MP4Demuxer.readUint32(tfdt, 4);\n if (version === 0) {\n MP4Demuxer.writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale);\n } else {\n baseMediaDecodeTime *= Math.pow(2, 32);\n baseMediaDecodeTime += MP4Demuxer.readUint32(tfdt, 8);\n baseMediaDecodeTime -= timeOffset * timescale;\n baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);\n const upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));\n const lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));\n MP4Demuxer.writeUint32(tfdt, 4, upper);\n MP4Demuxer.writeUint32(tfdt, 8, lower);\n }\n });\n });\n });\n }\n\n // feed incoming data to the front of the parsing pipeline\n append (data, timeOffset, contiguous, accurateTimeOffset) {\n let initData = this.initData;\n if (!initData) {\n this.resetInitSegment(data, this.audioCodec, this.videoCodec, false);\n initData = this.initData;\n }\n let startDTS, initPTS = this.initPTS;\n if (initPTS === undefined) {\n let startDTS = MP4Demuxer.getStartDTS(initData, data);\n this.initPTS = initPTS = startDTS - timeOffset;\n this.observer.trigger(Event.INIT_PTS_FOUND, { initPTS: initPTS });\n }\n MP4Demuxer.offsetStartDTS(initData, data, initPTS);\n startDTS = MP4Demuxer.getStartDTS(initData, data);\n this.remuxer.remux(initData.audio, initData.video, null, null, startDTS, contiguous, accurateTimeOffset, data);\n }\n\n destroy () {}\n}\n\nexport default MP4Demuxer;\n","function webpackBootstrapFunc (modules) {\n/******/ // The module cache\n/******/ var installedModules = {};\n\n/******/ // The require function\n/******/ function __webpack_require__(moduleId) {\n\n/******/ // Check if module is in cache\n/******/ if(installedModules[moduleId])\n/******/ return installedModules[moduleId].exports;\n\n/******/ // Create a new module (and put it into the cache)\n/******/ var module = installedModules[moduleId] = {\n/******/ i: moduleId,\n/******/ l: false,\n/******/ exports: {}\n/******/ };\n\n/******/ // Execute the module function\n/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n/******/ // Flag the module as loaded\n/******/ module.l = true;\n\n/******/ // Return the exports of the module\n/******/ return module.exports;\n/******/ }\n\n/******/ // expose the modules object (__webpack_modules__)\n/******/ __webpack_require__.m = modules;\n\n/******/ // expose the module cache\n/******/ __webpack_require__.c = installedModules;\n\n/******/ // identity function for calling harmony imports with the correct context\n/******/ __webpack_require__.i = function(value) { return value; };\n\n/******/ // define getter function for harmony exports\n/******/ __webpack_require__.d = function(exports, name, getter) {\n/******/ if(!__webpack_require__.o(exports, name)) {\n/******/ Object.defineProperty(exports, name, {\n/******/ configurable: false,\n/******/ enumerable: true,\n/******/ get: getter\n/******/ });\n/******/ }\n/******/ };\n\n/******/ // define __esModule on exports\n/******/ __webpack_require__.r = function(exports) {\n/******/ Object.defineProperty(exports, '__esModule', { value: true });\n/******/ };\n\n/******/ // getDefaultExport function for compatibility with non-harmony modules\n/******/ __webpack_require__.n = function(module) {\n/******/ var getter = module && module.__esModule ?\n/******/ function getDefault() { return module['default']; } :\n/******/ function getModuleExports() { return module; };\n/******/ __webpack_require__.d(getter, 'a', getter);\n/******/ return getter;\n/******/ };\n\n/******/ // Object.prototype.hasOwnProperty.call\n/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n/******/ // __webpack_public_path__\n/******/ __webpack_require__.p = \"/\";\n\n/******/ // on error function for async loading\n/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; };\n\n var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE)\n return f.default || f // try to call default if defined to also support babel esmodule exports\n}\n\nvar moduleNameReqExp = '[\\\\.|\\\\-|\\\\+|\\\\w|\\/|@]+'\nvar dependencyRegExp = '\\\\(\\\\s*(\\/\\\\*.*?\\\\*\\/)?\\\\s*.*?(' + moduleNameReqExp + ').*?\\\\)' // additional chars when output.pathinfo is true\n\n// http://stackoverflow.com/a/2593661/130442\nfunction quoteRegExp (str) {\n return (str + '').replace(/[.?*+^$[\\]\\\\(){}|-]/g, '\\\\$&')\n}\n\nfunction isNumeric(n) {\n return !isNaN(1 * n); // 1 * n converts integers, integers as string (\"123\"), 1e3 and \"1e3\" to integers and strings to NaN\n}\n\nfunction getModuleDependencies (sources, module, queueName) {\n var retval = {}\n retval[queueName] = []\n\n var fnString = module.toString()\n var wrapperSignature = fnString.match(/^function\\s?\\w*\\(\\w+,\\s*\\w+,\\s*(\\w+)\\)/)\n if (!wrapperSignature) return retval\n var webpackRequireName = wrapperSignature[1]\n\n // main bundle deps\n var re = new RegExp('(\\\\\\\\n|\\\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')\n var match\n while ((match = re.exec(fnString))) {\n if (match[3] === 'dll-reference') continue\n retval[queueName].push(match[3])\n }\n\n // dll deps\n re = new RegExp('\\\\(' + quoteRegExp(webpackRequireName) + '\\\\(\"(dll-reference\\\\s(' + moduleNameReqExp + '))\"\\\\)\\\\)' + dependencyRegExp, 'g')\n while ((match = re.exec(fnString))) {\n if (!sources[match[2]]) {\n retval[queueName].push(match[1])\n sources[match[2]] = __webpack_require__(match[1]).m\n }\n retval[match[2]] = retval[match[2]] || []\n retval[match[2]].push(match[4])\n }\n\n // convert 1e3 back to 1000 - this can be important after uglify-js converted 1000 to 1e3\n var keys = Object.keys(retval);\n for (var i = 0; i < keys.length; i++) {\n for (var j = 0; j < retval[keys[i]].length; j++) {\n if (isNumeric(retval[keys[i]][j])) {\n retval[keys[i]][j] = 1 * retval[keys[i]][j];\n }\n }\n }\n\n return retval\n}\n\nfunction hasValuesInQueues (queues) {\n var keys = Object.keys(queues)\n return keys.reduce(function (hasValues, key) {\n return hasValues || queues[key].length > 0\n }, false)\n}\n\nfunction getRequiredModules (sources, moduleId) {\n var modulesQueue = {\n main: [moduleId]\n }\n var requiredModules = {\n main: []\n }\n var seenModules = {\n main: {}\n }\n\n while (hasValuesInQueues(modulesQueue)) {\n var queues = Object.keys(modulesQueue)\n for (var i = 0; i < queues.length; i++) {\n var queueName = queues[i]\n var queue = modulesQueue[queueName]\n var moduleToCheck = queue.pop()\n seenModules[queueName] = seenModules[queueName] || {}\n if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue\n seenModules[queueName][moduleToCheck] = true\n requiredModules[queueName] = requiredModules[queueName] || []\n requiredModules[queueName].push(moduleToCheck)\n var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)\n var newModulesKeys = Object.keys(newModules)\n for (var j = 0; j < newModulesKeys.length; j++) {\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])\n }\n }\n }\n\n return requiredModules\n}\n\nmodule.exports = function (moduleId, options) {\n options = options || {}\n var sources = {\n main: __webpack_modules__\n }\n\n var requiredModules = options.all ? { main: Object.keys(sources.main) } : getRequiredModules(sources, moduleId)\n\n var src = ''\n\n Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {\n var entryModule = 0\n while (requiredModules[module][entryModule]) {\n entryModule++\n }\n requiredModules[module].push(entryModule)\n sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'\n src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\\n'\n })\n\n src = src + 'new ((' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[id].toString() }).join(',') + '}))(self);'\n\n var blob = new window.Blob([src], { type: 'text/javascript' })\n if (options.bare) { return blob }\n\n var URL = window.URL || window.webkitURL || window.mozURL || window.msURL\n\n var workerUrl = URL.createObjectURL(blob)\n var worker = new window.Worker(workerUrl)\n worker.objectURL = workerUrl\n\n return worker\n}\n","/* demuxer web worker.\n * - listen to worker message, and trigger DemuxerInline upon reception of Fragments.\n * - provides MP4 Boxes back to main thread using [transferable objects](https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast) in order to minimize message passing overhead.\n */\n\nimport DemuxerInline from '../demux/demuxer-inline';\nimport Event from '../events';\nimport { enableLogs } from '../utils/logger';\n\nimport { EventEmitter } from 'eventemitter3';\n\nlet DemuxerWorker = function (self) {\n // observer setup\n let observer = new EventEmitter();\n observer.trigger = function trigger (event, ...data) {\n observer.emit(event, event, ...data);\n };\n\n observer.off = function off (event, ...data) {\n observer.removeListener(event, ...data);\n };\n\n let forwardMessage = function (ev, data) {\n self.postMessage({ event: ev, data: data });\n };\n\n self.addEventListener('message', function (ev) {\n let data = ev.data;\n // console.log('demuxer cmd:' + data.cmd);\n switch (data.cmd) {\n case 'init':\n const config = JSON.parse(data.config);\n self.demuxer = new DemuxerInline(observer, data.typeSupported, config, data.vendor);\n\n enableLogs(config.debug);\n\n // signal end of worker init\n forwardMessage('init', null);\n break;\n case 'demux':\n self.demuxer.push(data.data, data.decryptdata, data.initSegment, data.audioCodec, data.videoCodec, data.timeOffset, data.discontinuity, data.trackSwitch, data.contiguous, data.duration, data.accurateTimeOffset, data.defaultInitPTS);\n break;\n default:\n break;\n }\n });\n\n // forward events to main thread\n observer.on(Event.FRAG_DECRYPTED, forwardMessage);\n observer.on(Event.FRAG_PARSING_INIT_SEGMENT, forwardMessage);\n observer.on(Event.FRAG_PARSED, forwardMessage);\n observer.on(Event.ERROR, forwardMessage);\n observer.on(Event.FRAG_PARSING_METADATA, forwardMessage);\n observer.on(Event.FRAG_PARSING_USERDATA, forwardMessage);\n observer.on(Event.INIT_PTS_FOUND, forwardMessage);\n\n // special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy)\n observer.on(Event.FRAG_PARSING_DATA, function (ev, data) {\n let transferable = [];\n let message = { event: ev, data: data };\n if (data.data1) {\n message.data1 = data.data1.buffer;\n transferable.push(data.data1.buffer);\n delete data.data1;\n }\n if (data.data2) {\n message.data2 = data.data2.buffer;\n transferable.push(data.data2.buffer);\n delete data.data2;\n }\n self.postMessage(message, transferable);\n });\n};\n\nexport default DemuxerWorker;\n","import Level from '../loader/level';\n\nexport interface LoaderContext {\n // target URL\n url: string\n // loader response type (arraybuffer or default response type for playlist)\n responseType: string\n // start byte range offset\n rangeStart?: number\n // end byte range offset\n rangeEnd?: number\n // true if onProgress should report partial chunk of loaded content\n progressData?: boolean\n}\n\nexport interface LoaderConfiguration {\n // Max number of load retries\n maxRetry: number\n // Timeout after which `onTimeOut` callback will be triggered\n // (if loading is still not finished after that delay)\n timeout: number\n // Delay between an I/O error and following connection retry (ms).\n // This to avoid spamming the server\n retryDelay: number\n // max connection retry delay (ms)\n maxRetryDelay: number\n}\n\nexport interface LoaderResponse {\n url: string,\n // TODO(jstackhouse): SharedArrayBuffer, es2017 extension to TS\n data: string | ArrayBuffer\n}\n\nexport interface LoaderStats {\n // performance.now() just after load() has been called\n trequest: number\n // performance.now() of first received byte\n tfirst: number\n // performance.now() on load complete\n tload: number\n // performance.now() on parse completion\n tparsed: number\n // number of loaded bytes\n loaded: number\n // total number of bytes\n total: number\n}\n\ntype LoaderOnSuccess < T extends LoaderContext > = (\n response: LoaderResponse,\n stats: LoaderStats,\n context: T,\n networkDetails: any\n) => void;\n\ntype LoaderOnProgress < T extends LoaderContext > = (\n stats: LoaderStats,\n context: T,\n data: string | ArrayBuffer,\n networkDetails: any,\n) => void;\n\ntype LoaderOnError < T extends LoaderContext > = (\n error: {\n // error status code\n code: number,\n // error description\n text: string,\n },\n context: T,\n networkDetails: any,\n) => void;\n\ntype LoaderOnTimeout < T extends LoaderContext > = (\n stats: LoaderStats,\n context: T,\n) => void;\n\nexport interface LoaderCallbacks<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?.method && levelkey.uri && !levelkey.iv) {\n decryptdata = new LevelKey(levelkey.baseuri, levelkey.reluri);\n decryptdata.method = levelkey.method;\n decryptdata.iv = this.createInitializationVector(segmentNumber);\n }\n\n return decryptdata;\n }\n}\n","import { buildAbsoluteURL } from 'url-toolkit';\n\nexport default class LevelKey {\n private _uri: string | null = null;\n\n public baseuri: string;\n public reluri: string;\n public method: string | null = null;\n public key: Uint8Array | null = null;\n public iv: Uint8Array | null = null;\n\n constructor (baseURI: string, relativeURI: string) {\n this.baseuri = baseURI;\n this.reluri = relativeURI;\n }\n\n get uri () {\n if (!this._uri && this.reluri) {\n this._uri = buildAbsoluteURL(this.baseuri, this.reluri, { alwaysNormalize: true });\n }\n\n return this._uri;\n }\n}\n","export default class Level {\n constructor (baseUrl) {\n // Please keep properties in alphabetical order\n this.endCC = 0;\n this.endSN = 0;\n this.fragments = [];\n this.initSegment = null;\n this.live = true;\n this.needSidxRanges = false;\n this.startCC = 0;\n this.startSN = 0;\n this.startTimeOffset = null;\n this.targetduration = 0;\n this.totalduration = 0;\n this.type = null;\n this.url = baseUrl;\n this.version = null;\n }\n\n get hasProgramDateTime () {\n return !!(this.fragments[0] && Number.isFinite(this.fragments[0].programDateTime));\n }\n}\n","const DECIMAL_RESOLUTION_REGEX = /^(\\d+)x(\\d+)$/; // eslint-disable-line no-useless-escape\nconst ATTR_LIST_REGEX = /\\s*(.+?)\\s*=((?:\\\".*?\\\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape\n\n// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js\nclass AttrList {\n constructor (attrs) {\n if (typeof attrs === 'string') {\n attrs = AttrList.parseAttrList(attrs);\n }\n\n for (let attr in attrs) {\n if (attrs.hasOwnProperty(attr)) {\n this[attr] = attrs[attr];\n }\n }\n }\n\n decimalInteger (attrName) {\n const intValue = parseInt(this[attrName], 10);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n\n return intValue;\n }\n\n hexadecimalInteger (attrName) {\n if (this[attrName]) {\n let stringValue = (this[attrName] || '0x').slice(2);\n stringValue = ((stringValue.length & 1) ? '0' : '') + stringValue;\n\n const value = new Uint8Array(stringValue.length / 2);\n for (let i = 0; i < stringValue.length / 2; i++) {\n value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);\n }\n\n return value;\n } else {\n return null;\n }\n }\n\n hexadecimalIntegerAsNumber (attrName) {\n const intValue = parseInt(this[attrName], 16);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n\n return intValue;\n }\n\n decimalFloatingPoint (attrName) {\n return parseFloat(this[attrName]);\n }\n\n enumeratedString (attrName) {\n return this[attrName];\n }\n\n decimalResolution (attrName) {\n const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);\n if (res === null) {\n return undefined;\n }\n\n return {\n width: parseInt(res[1], 10),\n height: parseInt(res[2], 10)\n };\n }\n\n static parseAttrList (input) {\n let match, attrs = {};\n ATTR_LIST_REGEX.lastIndex = 0;\n while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {\n let value = match[2], quote = '\"';\n\n if (value.indexOf(quote) === 0 &&\n value.lastIndexOf(quote) === (value.length - 1)) {\n value = value.slice(1, -1);\n }\n\n attrs[match[1]] = value;\n }\n return attrs;\n }\n}\n\nexport default AttrList;\n","// from http://mp4ra.org/codecs.html\nconst sampleEntryCodesISO = {\n audio: {\n 'a3ds': true,\n 'ac-3': true,\n 'ac-4': true,\n 'alac': true,\n 'alaw': true,\n 'dra1': true,\n 'dts+': true,\n 'dts-': true,\n 'dtsc': true,\n 'dtse': true,\n 'dtsh': true,\n 'ec-3': true,\n 'enca': true,\n 'g719': true,\n 'g726': true,\n 'm4ae': true,\n 'mha1': true,\n 'mha2': true,\n 'mhm1': true,\n 'mhm2': true,\n 'mlpa': true,\n 'mp4a': true,\n 'raw ': true,\n 'Opus': true,\n 'samr': true,\n 'sawb': true,\n 'sawp': true,\n 'sevc': true,\n 'sqcp': true,\n 'ssmv': true,\n 'twos': true,\n 'ulaw': true\n },\n video: {\n 'avc1': true,\n 'avc2': true,\n 'avc3': true,\n 'avc4': true,\n 'avcp': true,\n 'drac': true,\n 'dvav': true,\n 'dvhe': true,\n 'encv': true,\n 'hev1': true,\n 'hvc1': true,\n 'mjp2': true,\n 'mp4v': true,\n 'mvc1': true,\n 'mvc2': true,\n 'mvc3': true,\n 'mvc4': true,\n 'resv': true,\n 'rv60': true,\n 's263': true,\n 'svc1': true,\n 'svc2': true,\n 'vc-1': true,\n 'vp08': true,\n 'vp09': true\n }\n};\n\nexport type CodecType = 'audio' | 'video';\n\nfunction isCodecType (codec: string, type: CodecType): boolean {\n const typeCodes = sampleEntryCodesISO[type];\n return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;\n}\n\nfunction isCodecSupportedInMp4 (codec: string, type: CodecType): boolean {\n return MediaSource.isTypeSupported(`${type || 'video'}/mp4;codecs=\"${codec}\"`);\n}\n\nexport { isCodecType, isCodecSupportedInMp4 };\n","import * as URLToolkit from 'url-toolkit';\n\nimport Fragment from './fragment';\nimport Level from './level';\nimport LevelKey from './level-key';\n\nimport AttrList from '../utils/attr-list';\nimport { logger } from '../utils/logger';\nimport { isCodecType, CodecType } from '../utils/codecs';\nimport { MediaPlaylist, AudioGroup, MediaPlaylistType } from '../types/media-playlist';\nimport { PlaylistLevelType } from '../types/loader';\n\n/**\n * M3U8 parser\n * @module\n */\n\n// https://regex101.com is your friend\nconst MASTER_PLAYLIST_REGEX = /(?:#EXT-X-STREAM-INF:([^\\n\\r]*)[\\r\\n]+([^\\r\\n]+)|#EXT-X-SESSION-DATA:([^\\n\\r]*)[\\r\\n]+)/g;\nconst MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;\n\nconst LEVEL_PLAYLIST_REGEX_FAST = new RegExp([\n /#EXTINF:\\s*(\\d*(?:\\.\\d+)?)(?:,(.*)\\s+)?/.source, // duration (#EXTINF:<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 let sessionData: Record<string, AttrList> = {};\n let hasSessionData = false;\n MASTER_PLAYLIST_REGEX.lastIndex = 0;\n\n // TODO(typescript-level)\n function setCodecs (codecs: Array<string>, level: any) {\n ['video', 'audio'].forEach((type: CodecType) => {\n const filtered = codecs.filter((codec) => isCodecType(codec, type));\n if (filtered.length) {\n const preferred = filtered.filter((codec) => {\n return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0;\n });\n level[`${type}Codec`] = preferred.length > 0 ? preferred[0] : filtered[0];\n\n // remove from list\n codecs = codecs.filter((codec) => filtered.indexOf(codec) === -1);\n }\n });\n\n level.unknownCodecs = codecs;\n }\n\n let result: RegExpExecArray | null;\n while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {\n if (result[1]) {\n // '#EXT-X-STREAM-INF' is found, parse level tag in group 1\n\n // TODO(typescript-level)\n const level: any = {};\n\n const attrs = level.attrs = new AttrList(result[1]);\n level.url = M3U8Parser.resolve(result[2], baseurl);\n\n const resolution = attrs.decimalResolution('RESOLUTION');\n if (resolution) {\n level.width = resolution.width;\n level.height = resolution.height;\n }\n level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');\n level.name = attrs.NAME;\n\n setCodecs([].concat((attrs.CODECS || '').split(/[ ,]+/)), level);\n\n if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {\n level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);\n }\n\n levels.push(level);\n } else if (result[3]) {\n // '#EXT-X-SESSION-DATA' is found, parse session data in group 3\n let sessionAttrs = new AttrList(result[3]);\n if (sessionAttrs['DATA-ID']) {\n hasSessionData = true;\n sessionData[sessionAttrs['DATA-ID']] = sessionAttrs;\n }\n }\n }\n return {\n levels,\n sessionData: hasSessionData ? sessionData : null\n };\n }\n\n static parseMasterPlaylistMedia (string: string, baseurl: string, type: MediaPlaylistType, audioGroups: Array<AudioGroup> = []): Array<MediaPlaylist> {\n let result: RegExpExecArray | null;\n let medias: Array<MediaPlaylist> = [];\n let id = 0;\n MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;\n while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {\n const attrs = new AttrList(result[1]);\n if (attrs.TYPE === type) {\n const media: MediaPlaylist = {\n attrs,\n id: id++,\n groupId: attrs['GROUP-ID'],\n instreamId: attrs['INSTREAM-ID'],\n name: attrs.NAME || attrs.LANGUAGE,\n type,\n default: (attrs.DEFAULT === 'YES'),\n autoselect: (attrs.AUTOSELECT === 'YES'),\n forced: (attrs.FORCED === 'YES'),\n lang: attrs.LANGUAGE\n };\n\n if (attrs.URI) {\n media.url = M3U8Parser.resolve(attrs.URI, baseurl);\n }\n\n if (audioGroups.length) {\n // If there are audio groups signalled in the manifest, let's look for a matching codec string for this track\n const groupCodec = M3U8Parser.findGroup(audioGroups, media.groupId as string);\n\n // If we don't find the track signalled, lets use the first audio groups codec we have\n // Acting as a best guess\n media.audioCodec = groupCodec ? groupCodec.codec : audioGroups[0].codec;\n }\n\n medias.push(media);\n }\n }\n return medias;\n }\n\n static parseLevelPlaylist (string: string, baseurl: string, id: number, type: PlaylistLevelType, levelUrlId: number) {\n let currentSN = 0;\n let totalduration = 0;\n let level = new Level(baseurl);\n let discontinuityCounter = 0;\n let prevFrag: Fragment | null = null;\n let frag: Fragment | null = new Fragment();\n let result: RegExpExecArray | RegExpMatchArray | null;\n let i: number;\n let levelkey: LevelKey | undefined;\n\n let firstPdtIndex = null;\n\n LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;\n\n while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {\n const duration = result[1];\n if (duration) { // INF\n frag.duration = parseFloat(duration);\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const title = (' ' + result[2]).slice(1);\n frag.title = title || null;\n frag.tagList.push(title ? [ 'INF', duration, title ] : [ 'INF', duration ]);\n } else if (result[3]) { // url\n if (Number.isFinite(frag.duration)) {\n const sn = currentSN++;\n frag.type = type;\n frag.start = totalduration;\n if (levelkey) {\n frag.levelkey = levelkey;\n }\n frag.sn = sn;\n frag.level = id;\n frag.cc = discontinuityCounter;\n frag.urlId = levelUrlId;\n frag.baseurl = baseurl;\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n frag.relurl = (' ' + result[3]).slice(1);\n assignProgramDateTime(frag, prevFrag);\n\n level.fragments.push(frag);\n prevFrag = frag;\n totalduration += frag.duration;\n\n frag = new Fragment();\n }\n } else if (result[4]) { // X-BYTERANGE\n const data = (' ' + result[4]).slice(1);\n if (prevFrag) {\n frag.setByteRange(data, prevFrag);\n } else {\n frag.setByteRange(data);\n }\n } else if (result[5]) { // PROGRAM-DATE-TIME\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n frag.rawProgramDateTime = (' ' + result[5]).slice(1);\n frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);\n if (firstPdtIndex === null) {\n firstPdtIndex = level.fragments.length;\n }\n } else {\n result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);\n if (!result) {\n logger.warn('No matches on slow regex match for level playlist!');\n continue;\n }\n for (i = 1; i < result.length; i++) {\n if (typeof result[i] !== 'undefined') {\n break;\n }\n }\n\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const value1 = (' ' + result[i + 1]).slice(1);\n const value2 = (' ' + result[i + 2]).slice(1);\n\n switch (result[i]) {\n case '#':\n frag.tagList.push(value2 ? [ value1, value2 ] : [ value1 ]);\n break;\n case 'PLAYLIST-TYPE':\n level.type = value1.toUpperCase();\n break;\n case 'MEDIA-SEQUENCE':\n currentSN = level.startSN = parseInt(value1);\n break;\n case 'TARGETDURATION':\n level.targetduration = parseFloat(value1);\n break;\n case 'VERSION':\n level.version = parseInt(value1);\n break;\n case 'EXTM3U':\n break;\n case 'ENDLIST':\n level.live = false;\n break;\n case 'DIS':\n discontinuityCounter++;\n frag.tagList.push(['DIS']);\n break;\n case 'DISCONTINUITY-SEQ':\n discontinuityCounter = parseInt(value1);\n break;\n case 'KEY': {\n // https://tools.ietf.org/html/rfc8216#section-4.3.2.4\n const decryptparams = value1;\n const keyAttrs = new AttrList(decryptparams);\n const decryptmethod = keyAttrs.enumeratedString('METHOD');\n const decrypturi = keyAttrs.URI;\n const decryptiv = keyAttrs.hexadecimalInteger('IV');\n // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of \"identity\".\n const decryptkeyformat = keyAttrs.KEYFORMAT || 'identity';\n\n if (decryptkeyformat === 'com.apple.streamingkeydelivery') {\n logger.warn('Keyformat com.apple.streamingkeydelivery is not supported');\n continue;\n }\n\n if (decryptmethod) {\n levelkey = new LevelKey(baseurl, decrypturi);\n if ((decrypturi) && (['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0)) {\n levelkey.method = decryptmethod;\n levelkey.key = null;\n // Initialization Vector (IV)\n levelkey.iv = decryptiv;\n }\n }\n break;\n }\n case 'START': {\n const startAttrs = new AttrList(value1);\n const startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');\n // TIME-OFFSET can be 0\n if (Number.isFinite(startTimeOffset)) {\n level.startTimeOffset = startTimeOffset;\n }\n break;\n }\n case 'MAP': {\n const mapAttrs = new AttrList(value1);\n frag.relurl = mapAttrs.URI;\n if (mapAttrs.BYTERANGE) {\n frag.setByteRange(mapAttrs.BYTERANGE);\n }\n frag.baseurl = baseurl;\n frag.level = id;\n frag.type = type;\n frag.sn = 'initSegment';\n level.initSegment = frag;\n frag = new Fragment();\n frag.rawProgramDateTime = level.initSegment.rawProgramDateTime;\n break;\n }\n default:\n logger.warn(`line parsed but not handled: ${result}`);\n break;\n }\n }\n }\n frag = prevFrag;\n // logger.log('found ' + level.fragments.length + ' fragments');\n if (frag && !frag.relurl) {\n level.fragments.pop();\n totalduration -= frag.duration;\n }\n level.totalduration = totalduration;\n level.averagetargetduration = totalduration / level.fragments.length;\n level.endSN = currentSN - 1;\n level.startCC = level.fragments[0] ? level.fragments[0].cc : 0;\n level.endCC = discontinuityCounter;\n\n if (!level.initSegment && level.fragments.length) {\n // this is a bit lurky but HLS really has no other way to tell us\n // if the fragments are TS or MP4, except if we download them :/\n // but this is to be able to handle SIDX.\n if (level.fragments.every((frag) => MP4_REGEX_SUFFIX.test(frag.relurl))) {\n logger.warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');\n\n frag = new Fragment();\n frag.relurl = level.fragments[0].relurl;\n frag.baseurl = baseurl;\n frag.level = id;\n frag.type = type;\n frag.sn = 'initSegment';\n\n level.initSegment = frag;\n level.needSidxRanges = true;\n }\n }\n\n /**\n * Backfill any missing PDT values\n \"If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after\n one or more Media Segment URIs, the client SHOULD extrapolate\n backward from that tag (using EXTINF durations and/or media\n timestamps) to associate dates with those segments.\"\n * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs\n * computed.\n */\n if (firstPdtIndex) {\n backfillProgramDateTimes(level.fragments, firstPdtIndex);\n }\n\n return level;\n }\n}\n\nfunction backfillProgramDateTimes (fragments, startIndex) {\n let fragPrev = fragments[startIndex];\n for (let i = startIndex - 1; i >= 0; i--) {\n const frag = fragments[i];\n frag.programDateTime = fragPrev.programDateTime - (frag.duration * 1000);\n fragPrev = frag;\n }\n}\n\nfunction assignProgramDateTime (frag, prevFrag) {\n if (frag.rawProgramDateTime) {\n frag.programDateTime = Date.parse(frag.rawProgramDateTime);\n } else if (prevFrag?.programDateTime) {\n frag.programDateTime = prevFrag.endProgramDateTime;\n }\n\n if (!Number.isFinite(frag.programDateTime)) {\n frag.programDateTime = null;\n frag.rawProgramDateTime = null;\n }\n}\n","/**\n * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.\n *\n * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.\n *\n * Uses loader(s) set in config to do actual internal loading of resource tasks.\n *\n * @module\n *\n */\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport { Loader, PlaylistContextType, PlaylistLoaderContext, PlaylistLevelType, LoaderCallbacks, LoaderResponse, LoaderStats, LoaderConfiguration } from '../types/loader';\nimport MP4Demuxer from '../demux/mp4demuxer';\nimport M3U8Parser from './m3u8-parser';\nimport { AudioGroup } from '../types/media-playlist';\n\nconst { performance } = window;\n\n/**\n * @constructor\n */\nclass PlaylistLoader extends EventHandler {\n private loaders: Partial<Record<PlaylistContextType, Loader<PlaylistLoaderContext>>> = {};\n\n /**\n * @constructs\n * @param {Hls} hls\n */\n constructor (hls) {\n super(hls,\n Event.MANIFEST_LOADING,\n Event.LEVEL_LOADING,\n Event.AUDIO_TRACK_LOADING,\n Event.SUBTITLE_TRACK_LOADING);\n }\n\n /**\n * @param {PlaylistContextType} type\n * @returns {boolean}\n */\n static canHaveQualityLevels (type: PlaylistContextType): boolean {\n return (type !== PlaylistContextType.AUDIO_TRACK &&\n type !== PlaylistContextType.SUBTITLE_TRACK);\n }\n\n /**\n * Map context.type to LevelType\n * @param {PlaylistLoaderContext} context\n * @returns {LevelType}\n */\n static mapContextToLevelType (context: PlaylistLoaderContext): PlaylistLevelType {\n const { type } = context;\n\n switch (type) {\n case PlaylistContextType.AUDIO_TRACK:\n return PlaylistLevelType.AUDIO;\n case PlaylistContextType.SUBTITLE_TRACK:\n return PlaylistLevelType.SUBTITLE;\n default:\n return PlaylistLevelType.MAIN;\n }\n }\n\n static getResponseUrl (response: LoaderResponse, context: PlaylistLoaderContext): string {\n let url = response.url;\n // responseURL not supported on some browsers (it is used to detect URL redirection)\n // data-uri mode also not supported (but no need to detect redirection)\n if (url === undefined || url.indexOf('data:') === 0) {\n // fallback to initial URL\n url = context.url;\n }\n return url;\n }\n\n /**\n * Returns defaults or configured loader-type overloads (pLoader and loader config params)\n * Default loader is XHRLoader (see utils)\n * @param {PlaylistLoaderContext} context\n * @returns {Loader} or other compatible configured overload\n */\n createInternalLoader (context: PlaylistLoaderContext): Loader<PlaylistLoaderContext> {\n const config = this.hls.config;\n const PLoader = config.pLoader;\n const Loader = config.loader;\n // TODO(typescript-config): Verify once config is typed that InternalLoader always returns a Loader\n const InternalLoader = PLoader || Loader;\n\n const loader = new InternalLoader(config);\n\n // TODO - Do we really need to assign the instance or if the dep has been lost\n context.loader = loader;\n this.loaders[context.type] = loader;\n\n return loader;\n }\n\n getInternalLoader (context: PlaylistLoaderContext): Loader<PlaylistLoaderContext> | undefined {\n return this.loaders[context.type];\n }\n\n resetInternalLoader (contextType: PlaylistContextType) {\n if (this.loaders[contextType]) {\n delete this.loaders[contextType];\n }\n }\n\n /**\n * Call `destroy` on all internal loader instances mapped (one per context type)\n */\n destroyInternalLoaders () {\n for (let contextType in this.loaders) {\n let loader = this.loaders[contextType];\n if (loader) {\n loader.destroy();\n }\n\n this.resetInternalLoader(contextType as PlaylistContextType);\n }\n }\n\n destroy () {\n this.destroyInternalLoaders();\n\n super.destroy();\n }\n\n onManifestLoading (data: { url: string; }) {\n this.load({\n url: data.url,\n type: PlaylistContextType.MANIFEST,\n level: 0,\n id: null,\n responseType: 'text'\n });\n }\n\n onLevelLoading (data: { url: string; level: number | null; id: number | null; }) {\n this.load({\n url: data.url,\n type: PlaylistContextType.LEVEL,\n level: data.level,\n id: data.id,\n responseType: 'text'\n });\n }\n\n onAudioTrackLoading (data: { url: string; id: number | null; }) {\n this.load({\n url: data.url,\n type: PlaylistContextType.AUDIO_TRACK,\n level: null,\n id: data.id,\n responseType: 'text'\n });\n }\n\n onSubtitleTrackLoading (data: { url: string; id: number | null; }) {\n this.load({\n url: data.url,\n type: PlaylistContextType.SUBTITLE_TRACK,\n level: null,\n id: data.id,\n responseType: 'text'\n });\n }\n\n load (context: PlaylistLoaderContext): boolean {\n const config = this.hls.config;\n\n logger.debug(`Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);\n\n // Check if a loader for this context already exists\n let loader = this.getInternalLoader(context);\n if (loader) {\n const loaderContext = loader.context;\n if (loaderContext && loaderContext.url === context.url) { // same URL can't overlap\n logger.trace('playlist request ongoing');\n return false;\n } else {\n logger.warn(`aborting previous loader for type: ${context.type}`);\n loader.abort();\n }\n }\n\n let maxRetry: number;\n let timeout: number;\n let retryDelay: number;\n let maxRetryDelay: number;\n\n // apply different configs for retries depending on\n // context (manifest, level, audio/subs playlist)\n switch (context.type) {\n case PlaylistContextType.MANIFEST:\n maxRetry = config.manifestLoadingMaxRetry;\n timeout = config.manifestLoadingTimeOut;\n retryDelay = config.manifestLoadingRetryDelay;\n maxRetryDelay = config.manifestLoadingMaxRetryTimeout;\n break;\n case PlaylistContextType.LEVEL:\n // Disable internal loader retry logic, since we are managing retries in Level Controller\n maxRetry = 0;\n maxRetryDelay = 0;\n retryDelay = 0;\n timeout = config.levelLoadingTimeOut;\n // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config\n break;\n default:\n maxRetry = config.levelLoadingMaxRetry;\n timeout = config.levelLoadingTimeOut;\n retryDelay = config.levelLoadingRetryDelay;\n maxRetryDelay = config.levelLoadingMaxRetryTimeout;\n break;\n }\n\n loader = this.createInternalLoader(context);\n\n const loaderConfig: LoaderConfiguration = {\n timeout,\n maxRetry,\n retryDelay,\n maxRetryDelay\n };\n\n const loaderCallbacks: LoaderCallbacks<PlaylistLoaderContext> = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this)\n };\n\n logger.debug(`Calling internal loader delegate for URL: ${context.url}`);\n loader.load(context, loaderConfig, loaderCallbacks);\n\n return true;\n }\n\n loadsuccess (response: LoaderResponse, stats: LoaderStats, context: PlaylistLoaderContext, networkDetails: unknown = null) {\n if (context.isSidxRequest) {\n this._handleSidxRequest(response, context);\n this._handlePlaylistLoaded(response, stats, context, networkDetails);\n return;\n }\n\n this.resetInternalLoader(context.type);\n if (typeof response.data !== 'string') {\n throw new Error('expected responseType of \"text\" for PlaylistLoader');\n }\n\n const string = response.data;\n\n stats.tload = performance.now();\n // stats.mtime = new Date(target.getResponseHeader('Last-Modified'));\n\n // Validate if it is an M3U8 at all\n if (string.indexOf('#EXTM3U') !== 0) {\n this._handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);\n return;\n }\n\n // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)\n if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {\n this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails);\n } else {\n this._handleMasterPlaylist(response, stats, context, networkDetails);\n }\n }\n\n loaderror (response: LoaderResponse, context: PlaylistLoaderContext, networkDetails = null) {\n this._handleNetworkError(context, networkDetails, false, response);\n }\n\n loadtimeout (stats: LoaderStats, context: PlaylistLoaderContext, networkDetails = null) {\n this._handleNetworkError(context, networkDetails, true);\n }\n\n // TODO(typescript-config): networkDetails can currently be a XHR or Fetch impl,\n // but with custom loaders it could be generic investigate this further when config is typed\n _handleMasterPlaylist (response: LoaderResponse, stats: LoaderStats, context: PlaylistLoaderContext, networkDetails: unknown) {\n const hls = this.hls;\n const string = response.data as string;\n\n const url = PlaylistLoader.getResponseUrl(response, context);\n const { levels, sessionData } = M3U8Parser.parseMasterPlaylist(string, url);\n if (!levels.length) {\n this._handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);\n return;\n }\n\n // multi level playlist, parse level info\n const audioGroups: Array<AudioGroup> = levels.map(level => ({\n id: level.attrs.AUDIO,\n codec: level.audioCodec\n }));\n\n const audioTracks = M3U8Parser.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);\n const subtitles = M3U8Parser.parseMasterPlaylistMedia(string, url, 'SUBTITLES');\n const captions = M3U8Parser.parseMasterPlaylistMedia(string, url, 'CLOSED-CAPTIONS');\n\n if (audioTracks.length) {\n // check if we have found an audio track embedded in main playlist (audio track without URI attribute)\n let embeddedAudioFound = false;\n audioTracks.forEach(audioTrack => {\n if (!audioTrack.url) {\n embeddedAudioFound = true;\n }\n });\n\n // if no embedded audio track defined, but audio codec signaled in quality level,\n // we need to signal this main audio track this could happen with playlists with\n // alt audio rendition in which quality levels (main)\n // contains both audio+video. but with mixed audio track not signaled\n if (embeddedAudioFound === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) {\n logger.log('audio codec signaled in quality level, but no embedded audio track signaled, create one');\n audioTracks.unshift({\n type: 'main',\n name: 'main',\n default: false,\n autoselect: false,\n forced: false,\n id: -1,\n attrs: {},\n url: ''\n });\n }\n }\n\n hls.trigger(Event.MANIFEST_LOADED, {\n levels,\n audioTracks,\n subtitles,\n captions,\n url,\n stats,\n networkDetails,\n sessionData\n });\n }\n\n _handleTrackOrLevelPlaylist (response: LoaderResponse, stats: LoaderStats, context: PlaylistLoaderContext, networkDetails: unknown) {\n const hls = this.hls;\n\n const { id, level, type } = context;\n\n const url = PlaylistLoader.getResponseUrl(response, context);\n\n // if the values are null, they will result in the else conditional\n const levelUrlId = Number.isFinite(id as number) ? id as number : 0;\n const levelId = Number.isFinite(level as number) ? level as number : levelUrlId;\n\n const levelType = PlaylistLoader.mapContextToLevelType(context);\n const levelDetails = M3U8Parser.parseLevelPlaylist(response.data as string, url, levelId, levelType, levelUrlId);\n\n // set stats on level structure\n // TODO(jstackhouse): why? mixing concerns, is it just treated as value bag?\n (levelDetails as any).tload = stats.tload;\n\n if (!levelDetails.fragments.length) {\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.LEVEL_EMPTY_ERROR,\n fatal: false,\n url: url,\n reason: 'no fragments found in level',\n level: typeof context.level === 'number' ? context.level : undefined\n });\n return;\n }\n\n // We have done our first request (Manifest-type) and receive\n // not a master playlist but a chunk-list (track/level)\n // We fire the manifest-loaded event anyway with the parsed level-details\n // by creating a single-level structure for it.\n if (type === PlaylistContextType.MANIFEST) {\n const singleLevel = {\n url,\n details: levelDetails\n };\n\n hls.trigger(Event.MANIFEST_LOADED, {\n levels: [singleLevel],\n audioTracks: [],\n url,\n stats,\n networkDetails,\n sessionData: null\n });\n }\n\n // save parsing time\n stats.tparsed = performance.now();\n\n // in case we need SIDX ranges\n // return early after calling load for\n // the SIDX box.\n if (levelDetails.needSidxRanges) {\n const sidxUrl = levelDetails.initSegment.url;\n this.load({\n url: sidxUrl,\n isSidxRequest: true,\n type,\n level,\n levelDetails,\n id,\n rangeStart: 0,\n rangeEnd: 2048,\n responseType: 'arraybuffer'\n });\n return;\n }\n\n // extend the context with the new levelDetails property\n context.levelDetails = levelDetails;\n\n this._handlePlaylistLoaded(response, stats, context, networkDetails);\n }\n\n _handleSidxRequest (response: LoaderResponse, context: PlaylistLoaderContext) {\n if (typeof response.data === 'string') {\n throw new Error('sidx request must be made with responseType of array buffer');\n }\n\n const sidxInfo = MP4Demuxer.parseSegmentIndex(new Uint8Array(response.data));\n // if provided fragment does not contain sidx, early return\n if (!sidxInfo) {\n return;\n }\n const sidxReferences = sidxInfo.references;\n const levelDetails = context.levelDetails;\n sidxReferences.forEach((segmentRef, index) => {\n const segRefInfo = segmentRef.info;\n if (!levelDetails) {\n return;\n }\n const frag = levelDetails.fragments[index];\n if (frag.byteRange.length === 0) {\n frag.setByteRange(String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start));\n }\n });\n\n if (levelDetails) {\n levelDetails.initSegment.setByteRange(String(sidxInfo.moovEndOffset) + '@0');\n }\n }\n\n _handleManifestParsingError (response: LoaderResponse, context: PlaylistLoaderContext, reason: string, networkDetails: unknown) {\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.MANIFEST_PARSING_ERROR,\n fatal: true,\n url: response.url,\n reason,\n networkDetails\n });\n }\n\n _handleNetworkError (context: PlaylistLoaderContext, networkDetails: unknown, timeout: boolean = false, response: LoaderResponse | null = null) {\n logger.info(`A network error occured while loading a ${context.type}-type playlist`);\n\n let details;\n let fatal;\n\n const loader = this.getInternalLoader(context);\n\n switch (context.type) {\n case PlaylistContextType.MANIFEST:\n details = (timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR);\n fatal = true;\n break;\n case PlaylistContextType.LEVEL:\n details = (timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR);\n fatal = false;\n break;\n case PlaylistContextType.AUDIO_TRACK:\n details = (timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR);\n fatal = false;\n break;\n default:\n // details = ...?\n fatal = false;\n }\n\n if (loader) {\n loader.abort();\n this.resetInternalLoader(context.type);\n }\n\n // TODO(typescript-events): when error events are handled, type this\n let errorData: any = {\n type: ErrorTypes.NETWORK_ERROR,\n details,\n fatal,\n url: context.url,\n loader,\n context,\n networkDetails\n };\n\n if (response) {\n errorData.response = response;\n }\n\n this.hls.trigger(Event.ERROR, errorData);\n }\n\n _handlePlaylistLoaded (response: LoaderResponse, stats: LoaderStats, context: PlaylistLoaderContext, networkDetails: unknown) {\n const { type, level, id, levelDetails } = context;\n\n if (!levelDetails || !levelDetails.targetduration) {\n this._handleManifestParsingError(response, context, 'invalid target duration', networkDetails);\n return;\n }\n\n const canHaveLevels = PlaylistLoader.canHaveQualityLevels(context.type);\n if (canHaveLevels) {\n this.hls.trigger(Event.LEVEL_LOADED, {\n details: levelDetails,\n level: level || 0,\n id: id || 0,\n stats,\n networkDetails\n });\n } else {\n switch (type) {\n case PlaylistContextType.AUDIO_TRACK:\n this.hls.trigger(Event.AUDIO_TRACK_LOADED, {\n details: levelDetails,\n id,\n stats,\n networkDetails\n });\n break;\n case PlaylistContextType.SUBTITLE_TRACK:\n this.hls.trigger(Event.SUBTITLE_TRACK_LOADED, {\n details: levelDetails,\n id,\n stats,\n networkDetails\n });\n break;\n }\n }\n }\n}\n\nexport default PlaylistLoader;\n","/*\n * Fragment Loader\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\n\nclass FragmentLoader extends EventHandler {\n constructor (hls) {\n super(hls, Event.FRAG_LOADING);\n this.loaders = {};\n }\n\n destroy () {\n let loaders = this.loaders;\n for (let loaderName in loaders) {\n let loader = loaders[loaderName];\n if (loader) {\n loader.destroy();\n }\n }\n this.loaders = {};\n\n super.destroy();\n }\n\n onFragLoading (data) {\n const frag = data.frag,\n type = frag.type,\n loaders = this.loaders,\n config = this.hls.config,\n FragmentILoader = config.fLoader,\n DefaultILoader = config.loader;\n\n // reset fragment state\n frag.loaded = 0;\n\n let loader = loaders[type];\n if (loader) {\n logger.warn(`abort previous fragment loader for type: ${type}`);\n loader.abort();\n }\n\n loader = loaders[type] = frag.loader =\n config.fLoader ? new FragmentILoader(config) : new DefaultILoader(config);\n\n let loaderContext, loaderConfig, loaderCallbacks;\n\n loaderContext = { url: frag.url, frag: frag, responseType: 'arraybuffer', progressData: false };\n\n let start = frag.byteRangeStartOffset,\n end = frag.byteRangeEndOffset;\n\n if (Number.isFinite(start) && Number.isFinite(end)) {\n loaderContext.rangeStart = start;\n loaderContext.rangeEnd = end;\n }\n\n loaderConfig = {\n timeout: config.fragLoadingTimeOut,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: config.fragLoadingMaxRetryTimeout\n };\n\n loaderCallbacks = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this),\n onProgress: this.loadprogress.bind(this)\n };\n\n loader.load(loaderContext, loaderConfig, loaderCallbacks);\n }\n\n loadsuccess (response, stats, context, networkDetails = null) {\n let payload = response.data, frag = context.frag;\n // detach fragment loader on load success\n frag.loader = undefined;\n this.loaders[frag.type] = undefined;\n this.hls.trigger(Event.FRAG_LOADED, { payload: payload, frag: frag, stats: stats, networkDetails: networkDetails });\n }\n\n loaderror (response, context, networkDetails = null) {\n const frag = context.frag;\n let loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n\n this.loaders[frag.type] = undefined;\n this.hls.trigger(Event.ERROR, { type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.FRAG_LOAD_ERROR, fatal: false, frag: context.frag, response: response, networkDetails: networkDetails });\n }\n\n loadtimeout (stats, context, networkDetails = null) {\n const frag = context.frag;\n let loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n\n this.loaders[frag.type] = undefined;\n this.hls.trigger(Event.ERROR, { type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.FRAG_LOAD_TIMEOUT, fatal: false, frag: context.frag, networkDetails: networkDetails });\n }\n\n // data will be used for progressive parsing\n loadprogress (stats, context, data, networkDetails = null) { // jshint ignore:line\n let frag = context.frag;\n frag.loaded = stats.loaded;\n this.hls.trigger(Event.FRAG_LOAD_PROGRESS, { frag: frag, stats: stats, networkDetails: networkDetails });\n }\n}\n\nexport default FragmentLoader;\n","/*\n * Decrypt key Loader\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport Hls from '../hls';\nimport Fragment from './fragment';\nimport { LoaderStats, LoaderResponse, LoaderContext, LoaderConfiguration, LoaderCallbacks } from '../types/loader';\n\ninterface OnKeyLoadingPayload {\n frag: Fragment\n}\n\ninterface KeyLoaderContext extends LoaderContext {\n frag: Fragment\n}\n\nclass KeyLoader extends EventHandler {\n public loaders = {};\n public decryptkey: Uint8Array | null = null;\n public decrypturl: string | null = null;\n\n constructor (hls: Hls) {\n super(hls, Event.KEY_LOADING);\n }\n\n destroy (): void {\n for (const loaderName in this.loaders) {\n let loader = this.loaders[loaderName];\n if (loader) {\n loader.destroy();\n }\n }\n this.loaders = {};\n\n super.destroy();\n }\n\n onKeyLoading (data: OnKeyLoadingPayload) {\n const { frag } = data;\n const type = frag.type;\n const loader = this.loaders[type];\n if (!frag.decryptdata) {\n logger.warn('Missing decryption data on fragment in onKeyLoading');\n return;\n }\n\n // Load the key if the uri is different from previous one, or if the decrypt key has not yet been retrieved\n const uri = frag.decryptdata.uri;\n if (uri !== this.decrypturl || this.decryptkey === null) {\n let config = this.hls.config;\n if (loader) {\n logger.warn(`abort previous key loader for type:${type}`);\n loader.abort();\n }\n if (!uri) {\n logger.warn('key uri is falsy');\n return;\n }\n\n frag.loader = this.loaders[type] = new config.loader(config);\n this.decrypturl = uri;\n this.decryptkey = null;\n\n const loaderContext: KeyLoaderContext = {\n url: uri,\n frag: frag,\n responseType: 'arraybuffer'\n };\n\n // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,\n // key-loader will trigger an error and rely on stream-controller to handle retry logic.\n // this will also align retry logic with fragment-loader\n const loaderConfig: LoaderConfiguration = {\n timeout: config.fragLoadingTimeOut,\n maxRetry: 0,\n retryDelay: config.fragLoadingRetryDelay,\n maxRetryDelay: config.fragLoadingMaxRetryTimeout\n };\n\n const loaderCallbacks: LoaderCallbacks<KeyLoaderContext> = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this)\n };\n\n frag.loader.load(loaderContext, loaderConfig, loaderCallbacks);\n } else if (this.decryptkey) {\n // Return the key if it's already been loaded\n frag.decryptdata.key = this.decryptkey;\n this.hls.trigger(Event.KEY_LOADED, { frag: frag });\n }\n }\n\n loadsuccess (response: LoaderResponse, stats: LoaderStats, context: KeyLoaderContext) {\n let frag = context.frag;\n if (!frag.decryptdata) {\n logger.error('after key load, decryptdata unset');\n return;\n }\n this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data as ArrayBuffer);\n\n // detach fragment loader on load success\n frag.loader = undefined;\n delete this.loaders[frag.type];\n this.hls.trigger(Event.KEY_LOADED, { frag: frag });\n }\n\n loaderror (response: LoaderResponse, context: KeyLoaderContext) {\n let frag = context.frag;\n let loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n\n delete this.loaders[frag.type];\n this.hls.trigger(Event.ERROR, { type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag, response });\n }\n\n loadtimeout (stats: LoaderStats, context: KeyLoaderContext) {\n let frag = context.frag;\n let loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n\n delete this.loaders[frag.type];\n this.hls.trigger(Event.ERROR, { type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.KEY_LOAD_TIMEOUT, fatal: false, frag });\n }\n}\n\nexport default KeyLoader;\n","import EventHandler from '../event-handler';\nimport Event from '../events';\n\nexport const FragmentState = {\n NOT_LOADED: 'NOT_LOADED',\n APPENDING: 'APPENDING',\n PARTIAL: 'PARTIAL',\n OK: 'OK'\n};\n\nexport class FragmentTracker extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.BUFFER_APPENDED,\n Event.FRAG_BUFFERED,\n Event.FRAG_LOADED\n );\n\n this.bufferPadding = 0.2;\n\n this.fragments = Object.create(null);\n this.timeRanges = Object.create(null);\n\n this.config = hls.config;\n }\n\n destroy () {\n this.fragments = Object.create(null);\n this.timeRanges = Object.create(null);\n this.config = null;\n EventHandler.prototype.destroy.call(this);\n super.destroy();\n }\n\n /**\n * Return a Fragment that match the position and levelType.\n * If not found any Fragment, return null\n * @param {number} position\n * @param {LevelType} levelType\n * @returns {Fragment|null}\n */\n getBufferedFrag (position, levelType) {\n const fragments = this.fragments;\n const bufferedFrags = Object.keys(fragments).filter(key => {\n const fragmentEntity = fragments[key];\n if (fragmentEntity.body.type !== levelType) {\n return false;\n }\n\n if (!fragmentEntity.buffered) {\n return false;\n }\n\n const frag = fragmentEntity.body;\n return frag.startPTS <= position && position <= frag.endPTS;\n });\n if (bufferedFrags.length === 0) {\n return null;\n } else {\n // https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566\n const bufferedFragKey = bufferedFrags.pop();\n return fragments[bufferedFragKey].body;\n }\n }\n\n /**\n * Partial fragments effected by coded frame eviction will be removed\n * The browser will unload parts of the buffer to free up memory for new buffer data\n * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)\n * @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio)\n * @param {TimeRanges} timeRange TimeRange object from a sourceBuffer\n */\n detectEvictedFragments (elementaryStream, timeRange) {\n // Check if any flagged fragments have been unloaded\n Object.keys(this.fragments).forEach(key => {\n const fragmentEntity = this.fragments[key];\n if (!fragmentEntity || !fragmentEntity.buffered) {\n return;\n }\n const esData = fragmentEntity.range[elementaryStream];\n if (!esData) {\n return;\n }\n const fragmentTimes = esData.time;\n for (let i = 0; i < fragmentTimes.length; i++) {\n const time = fragmentTimes[i];\n if (!this.isTimeBuffered(time.startPTS, time.endPTS, timeRange)) {\n // Unregister partial fragment as it needs to load again to be reused\n this.removeFragment(fragmentEntity.body);\n break;\n }\n }\n });\n }\n\n /**\n * Checks if the fragment passed in is loaded in the buffer properly\n * Partially loaded fragments will be registered as a partial fragment\n * @param {Object} fragment Check the fragment against all sourceBuffers loaded\n */\n detectPartialFragments (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = this.fragments[fragKey];\n if (fragmentEntity) {\n fragmentEntity.buffered = true;\n\n Object.keys(this.timeRanges).forEach(elementaryStream => {\n if (fragment.hasElementaryStream(elementaryStream)) {\n let timeRange = this.timeRanges[elementaryStream];\n // Check for malformed fragments\n // Gaps need to be calculated for each elementaryStream\n fragmentEntity.range[elementaryStream] = this.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange);\n }\n });\n }\n }\n\n getBufferedTimes (startPTS, endPTS, timeRange) {\n let fragmentTimes = [];\n let startTime, endTime;\n let fragmentPartial = false;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n // Fragment is entirely contained in buffer\n // No need to check the other timeRange times since it's completely playable\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n break;\n } else if (startPTS < endTime && endPTS > startTime) {\n // Check for intersection with buffer\n // Get playable sections of the fragment\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n fragmentPartial = true;\n } else if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n break;\n }\n }\n\n return {\n time: fragmentTimes,\n partial: fragmentPartial\n };\n }\n\n getFragmentKey (fragment) {\n return `${fragment.type}_${fragment.level}_${fragment.urlId}_${fragment.sn}`;\n }\n\n /**\n * Gets the partial fragment for a certain time\n * @param {Number} time\n * @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment\n */\n getPartialFragment (time) {\n let timePadding, startTime, endTime;\n let bestFragment = null;\n let bestOverlap = 0;\n Object.keys(this.fragments).forEach(key => {\n const fragmentEntity = this.fragments[key];\n if (this.isPartial(fragmentEntity)) {\n startTime = fragmentEntity.body.startPTS - this.bufferPadding;\n endTime = fragmentEntity.body.endPTS + this.bufferPadding;\n if (time >= startTime && time <= endTime) {\n // Use the fragment that has the most padding from start and end time\n timePadding = Math.min(time - startTime, endTime - time);\n if (bestOverlap <= timePadding) {\n bestFragment = fragmentEntity.body;\n bestOverlap = timePadding;\n }\n }\n }\n });\n return bestFragment;\n }\n\n /**\n * @param {Object} fragment The fragment to check\n * @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded\n */\n getState (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = this.fragments[fragKey];\n let state = FragmentState.NOT_LOADED;\n\n if (fragmentEntity !== undefined) {\n if (!fragmentEntity.buffered) {\n state = FragmentState.APPENDING;\n } else if (this.isPartial(fragmentEntity) === true) {\n state = FragmentState.PARTIAL;\n } else {\n state = FragmentState.OK;\n }\n }\n\n return state;\n }\n\n isPartial (fragmentEntity) {\n return fragmentEntity.buffered === true &&\n ((fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true) ||\n (fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true));\n }\n\n isTimeBuffered (startPTS, endPTS, timeRange) {\n let startTime, endTime;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n return true;\n }\n\n if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n return false;\n }\n }\n\n return false;\n }\n\n /**\n * Fires when a fragment loading is completed\n */\n onFragLoaded (e) {\n const fragment = e.frag;\n // don't track initsegment (for which sn is not a number)\n // don't track frags used for bitrateTest, they're irrelevant.\n if (!Number.isFinite(fragment.sn) || fragment.bitrateTest) {\n return;\n }\n\n this.fragments[this.getFragmentKey(fragment)] = {\n body: fragment,\n range: Object.create(null),\n buffered: false\n };\n }\n\n /**\n * Fires when the buffer is updated\n */\n onBufferAppended (e) {\n // Store the latest timeRanges loaded in the buffer\n this.timeRanges = e.timeRanges;\n Object.keys(this.timeRanges).forEach(elementaryStream => {\n let timeRange = this.timeRanges[elementaryStream];\n this.detectEvictedFragments(elementaryStream, timeRange);\n });\n }\n\n /**\n * Fires after a fragment has been loaded into the source buffer\n */\n onFragBuffered (e) {\n this.detectPartialFragments(e.frag);\n }\n\n /**\n * Return true if fragment tracker has the fragment.\n * @param {Object} fragment\n * @returns {boolean}\n */\n hasFragment (fragment) {\n const fragKey = this.getFragmentKey(fragment);\n return this.fragments[fragKey] !== undefined;\n }\n\n /**\n * Remove a fragment from fragment tracker until it is loaded again\n * @param {Object} fragment The fragment to remove\n */\n removeFragment (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n delete this.fragments[fragKey];\n }\n\n /**\n * Remove all fragments from fragment tracker.\n */\n removeAllFragments () {\n this.fragments = Object.create(null);\n }\n}\n","type BinarySearchComparison < T > = (candidate: T) => -1 | 0 | 1;\n\nconst BinarySearch = {\n\n /**\n * Searches for an item in an array which matches a certain condition.\n * This requires the condition to only match one item in the array,\n * and for the array to be ordered.\n *\n * @param {Array<T>} list The array to search.\n * @param {BinarySearchComparison<T>} comparisonFn\n * Called and provided a candidate item as the first argument.\n * Should return:\n * > -1 if the item should be located at a lower index than the provided item.\n * > 1 if the item should be located at a higher index than the provided item.\n * > 0 if the item is the item you're looking for.\n *\n * @return {T | null} The object if it is found or null otherwise.\n */\n search: function<T> (list: T[], comparisonFn: BinarySearchComparison<T>): T | null {\n let minIndex: number = 0;\n let maxIndex: number = list.length - 1;\n let currentIndex: number | null = null;\n let currentElement: T | null = null;\n\n while (minIndex <= maxIndex) {\n currentIndex = (minIndex + maxIndex) / 2 | 0;\n currentElement = list[currentIndex];\n\n let comparisonResult = comparisonFn(currentElement);\n if (comparisonResult > 0) {\n minIndex = currentIndex + 1;\n } else if (comparisonResult < 0) {\n maxIndex = currentIndex - 1;\n } else {\n return currentElement;\n }\n }\n\n return null;\n }\n};\n\nexport default BinarySearch;\n","/**\n * @module BufferHelper\n *\n * Providing methods dealing with buffer length retrieval for example.\n *\n * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.\n *\n * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered\n*/\n\ntype BufferTimeRange = {\n start: number\n end: number\n};\n\ntype Bufferable = {\n buffered: TimeRanges\n};\n\nexport class BufferHelper {\n /**\n * Return true if `media`'s buffered include `position`\n * @param {Bufferable} media\n * @param {number} position\n * @returns {boolean}\n */\n static isBuffered (media: Bufferable, position: number): boolean {\n try {\n if (media) {\n let buffered = media.buffered;\n for (let i = 0; i < buffered.length; i++) {\n if (position >= buffered.start(i) && position <= buffered.end(i)) {\n return true;\n }\n }\n }\n } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return false;\n }\n\n static bufferInfo (\n media: Bufferable,\n pos: number,\n maxHoleDuration: number\n ): {\n len: number,\n start: number,\n end: number,\n nextStart?: number,\n } {\n try {\n if (media) {\n let vbuffered = media.buffered;\n let buffered: BufferTimeRange[] = [];\n let i: number;\n for (i = 0; i < vbuffered.length; i++) {\n buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) });\n }\n\n return this.bufferedInfo(buffered, pos, maxHoleDuration);\n }\n } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return { len: 0, start: pos, end: pos, nextStart: undefined };\n }\n\n static bufferedInfo (\n buffered: BufferTimeRange[],\n pos: number,\n maxHoleDuration: number\n ): {\n len: number,\n start: number,\n end: number,\n nextStart?: number,\n } {\n // sort on buffer.start/smaller end (IE does not always return sorted buffered range)\n buffered.sort(function (a, b) {\n let diff = a.start - b.start;\n if (diff) {\n return diff;\n } else {\n return b.end - a.end;\n }\n });\n\n let buffered2: BufferTimeRange[] = [];\n if (maxHoleDuration) {\n // there might be some small holes between buffer time range\n // consider that holes smaller than maxHoleDuration are irrelevant and build another\n // buffer time range representations that discards those holes\n for (let i = 0; i < buffered.length; i++) {\n let buf2len = buffered2.length;\n if (buf2len) {\n let buf2end = buffered2[buf2len - 1].end;\n // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)\n if ((buffered[i].start - buf2end) < maxHoleDuration) {\n // merge overlapping time ranges\n // update lastRange.end only if smaller than item.end\n // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)\n // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])\n if (buffered[i].end > buf2end) {\n buffered2[buf2len - 1].end = buffered[i].end;\n }\n } else {\n // big hole\n buffered2.push(buffered[i]);\n }\n } else {\n // first value\n buffered2.push(buffered[i]);\n }\n }\n } else {\n buffered2 = buffered;\n }\n\n let bufferLen = 0;\n\n // bufferStartNext can possibly be undefined based on the conditional logic below\n let bufferStartNext: number | undefined;\n\n // bufferStart and bufferEnd are buffer boundaries around current video position\n let bufferStart: number = pos;\n let bufferEnd: number = pos;\n for (let i = 0; i < buffered2.length; i++) {\n let start = buffered2[i].start,\n end = buffered2[i].end;\n // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));\n if ((pos + maxHoleDuration) >= start && pos < end) {\n // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length\n bufferStart = start;\n bufferEnd = end;\n bufferLen = bufferEnd - pos;\n } else if ((pos + maxHoleDuration) < start) {\n bufferStartNext = start;\n break;\n }\n }\n return { len: bufferLen, start: bufferStart, end: bufferEnd, nextStart: bufferStartNext };\n }\n}\n","/**\n * MediaSource helper\n */\n\nexport function getMediaSource (): typeof MediaSource | undefined {\n return (window as any).MediaSource || (window as any).WebKitMediaSource;\n}\n","import { EventEmitter } from 'eventemitter3';\n\n/**\n * Simple adapter sub-class of Nodejs-like EventEmitter.\n */\nexport class Observer extends EventEmitter {\n /**\n * We simply want to pass along the event-name itself\n * in every call to a handler, which is the purpose of our `trigger` method\n * extending the standard API.\n */\n trigger (event: string, ...data: Array<any>): void {\n this.emit(event, event, ...data);\n }\n}\n","import { EventEmitter } from 'eventemitter3';\nimport * as work from 'webworkify-webpack';\n\nimport Event from '../events';\nimport DemuxerInline from '../demux/demuxer-inline';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { getMediaSource } from '../utils/mediasource-helper';\nimport { getSelfScope } from '../utils/get-self-scope';\n\nimport { Observer } from '../observer';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\nconst MediaSource = getMediaSource() || { isTypeSupported: () => false };\n\nclass Demuxer {\n constructor (hls, id) {\n this.hls = hls;\n this.id = id;\n\n const observer = this.observer = new Observer();\n const config = hls.config;\n\n const forwardMessage = (ev, data) => {\n data = data || {};\n data.frag = this.frag;\n data.id = this.id;\n hls.trigger(ev, data);\n };\n\n // forward events to main thread\n observer.on(Event.FRAG_DECRYPTED, forwardMessage);\n observer.on(Event.FRAG_PARSING_INIT_SEGMENT, forwardMessage);\n observer.on(Event.FRAG_PARSING_DATA, forwardMessage);\n observer.on(Event.FRAG_PARSED, forwardMessage);\n observer.on(Event.ERROR, forwardMessage);\n observer.on(Event.FRAG_PARSING_METADATA, forwardMessage);\n observer.on(Event.FRAG_PARSING_USERDATA, forwardMessage);\n observer.on(Event.INIT_PTS_FOUND, forwardMessage);\n\n const typeSupported = {\n mp4: MediaSource.isTypeSupported('video/mp4'),\n mpeg: MediaSource.isTypeSupported('audio/mpeg'),\n mp3: MediaSource.isTypeSupported('audio/mp4; codecs=\"mp3\"')\n };\n // navigator.vendor is not always available in Web Worker\n // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator\n const vendor = navigator.vendor;\n if (config.enableWorker && (typeof (Worker) !== 'undefined')) {\n logger.log('demuxing in webworker');\n let w;\n try {\n w = this.w = work(require.resolve('../demux/demuxer-worker.js'));\n this.onwmsg = this.onWorkerMessage.bind(this);\n w.addEventListener('message', this.onwmsg);\n w.onerror = function (event) {\n hls.trigger(Event.ERROR, { type: ErrorTypes.OTHER_ERROR, details: ErrorDetails.INTERNAL_EXCEPTION, fatal: true, event: 'demuxerWorker', err: { message: event.message + ' (' + event.filename + ':' + event.lineno + ')' } });\n };\n w.postMessage({ cmd: 'init', typeSupported: typeSupported, vendor: vendor, id: id, config: JSON.stringify(config) });\n } catch (err) {\n logger.warn('Error in worker:', err);\n logger.error('Error while initializing DemuxerWorker, fallback on DemuxerInline');\n if (w) {\n // revoke the Object URL that was used to create demuxer worker, so as not to leak it\n global.URL.revokeObjectURL(w.objectURL);\n }\n this.demuxer = new DemuxerInline(observer, typeSupported, config, vendor);\n this.w = undefined;\n }\n } else {\n this.demuxer = new DemuxerInline(observer, typeSupported, config, vendor);\n }\n }\n\n destroy () {\n let w = this.w;\n if (w) {\n w.removeEventListener('message', this.onwmsg);\n w.terminate();\n this.w = null;\n } else {\n let demuxer = this.demuxer;\n if (demuxer) {\n demuxer.destroy();\n this.demuxer = null;\n }\n }\n const observer = this.observer;\n if (observer) {\n observer.removeAllListeners();\n this.observer = null;\n }\n }\n\n push (data, initSegment, audioCodec, videoCodec, frag, duration, accurateTimeOffset, defaultInitPTS) {\n const w = this.w;\n const timeOffset = Number.isFinite(frag.startPTS) ? frag.startPTS : frag.start;\n const decryptdata = frag.decryptdata;\n const lastFrag = this.frag;\n const discontinuity = !(lastFrag && (frag.cc === lastFrag.cc));\n const trackSwitch = !(lastFrag && (frag.level === lastFrag.level));\n const nextSN = lastFrag && (frag.sn === (lastFrag.sn + 1));\n const contiguous = !trackSwitch && nextSN;\n if (discontinuity) {\n logger.log(`${this.id}:discontinuity detected`);\n }\n\n if (trackSwitch) {\n logger.log(`${this.id}:switch detected`);\n }\n\n this.frag = frag;\n if (w) {\n // post fragment payload as transferable objects for ArrayBuffer (no copy)\n w.postMessage({ cmd: 'demux', data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS }, data instanceof ArrayBuffer ? [data] : []);\n } else {\n let demuxer = this.demuxer;\n if (demuxer) {\n demuxer.push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);\n }\n }\n }\n\n onWorkerMessage (ev) {\n let data = ev.data,\n hls = this.hls;\n switch (data.event) {\n case 'init':\n // revoke the Object URL that was used to create demuxer worker, so as not to leak it\n global.URL.revokeObjectURL(this.w.objectURL);\n break;\n // special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects\n case Event.FRAG_PARSING_DATA:\n data.data.data1 = new Uint8Array(data.data1);\n if (data.data2) {\n data.data.data2 = new Uint8Array(data.data2);\n }\n\n /* falls through */\n default:\n data.data = data.data || {};\n data.data.frag = this.frag;\n data.data.id = this.id;\n hls.trigger(data.event, data.data);\n break;\n }\n }\n}\n\nexport default Demuxer;\n","/**\n * @module LevelHelper\n *\n * Providing methods dealing with playlist sliding and drift\n *\n * TODO: Create an actual `Level` class/model that deals with all this logic in an object-oriented-manner.\n *\n * */\n\nimport { logger } from '../utils/logger';\n\nexport function addGroupId (level, type, id) {\n switch (type) {\n case 'audio':\n if (!level.audioGroupIds) {\n level.audioGroupIds = [];\n }\n level.audioGroupIds.push(id);\n break;\n case 'text':\n if (!level.textGroupIds) {\n level.textGroupIds = [];\n }\n level.textGroupIds.push(id);\n break;\n }\n}\n\nexport function updatePTS (fragments, fromIdx, toIdx) {\n let fragFrom = fragments[fromIdx], fragTo = fragments[toIdx], fragToPTS = fragTo.startPTS;\n // if we know startPTS[toIdx]\n if (Number.isFinite(fragToPTS)) {\n // update fragment duration.\n // it helps to fix drifts between playlist reported duration and fragment real duration\n if (toIdx > fromIdx) {\n fragFrom.duration = fragToPTS - fragFrom.start;\n if (fragFrom.duration < 0) {\n logger.warn(`negative duration computed for frag ${fragFrom.sn},level ${fragFrom.level}, there should be some duration drift between playlist and fragment!`);\n }\n } else {\n fragTo.duration = fragFrom.start - fragToPTS;\n if (fragTo.duration < 0) {\n logger.warn(`negative duration computed for frag ${fragTo.sn},level ${fragTo.level}, there should be some duration drift between playlist and fragment!`);\n }\n }\n } else {\n // we dont know startPTS[toIdx]\n if (toIdx > fromIdx) {\n const contiguous = fragFrom.cc === fragTo.cc;\n fragTo.start = fragFrom.start + ((contiguous && fragFrom.minEndPTS) ? fragFrom.minEndPTS - fragFrom.start : fragFrom.duration);\n } else {\n fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);\n }\n }\n}\n\nexport function updateFragPTSDTS (details, frag, startPTS, endPTS, startDTS, endDTS) {\n // update frag PTS/DTS\n let maxStartPTS = startPTS;\n let minEndPTS = endPTS;\n if (Number.isFinite(frag.startPTS)) {\n // delta PTS between audio and video\n let deltaPTS = Math.abs(frag.startPTS - startPTS);\n if (!Number.isFinite(frag.deltaPTS)) {\n frag.deltaPTS = deltaPTS;\n } else {\n frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);\n }\n\n maxStartPTS = Math.max(startPTS, frag.startPTS);\n startPTS = Math.min(startPTS, frag.startPTS);\n minEndPTS = Math.min(endPTS, frag.endPTS);\n endPTS = Math.max(endPTS, frag.endPTS);\n startDTS = Math.min(startDTS, frag.startDTS);\n endDTS = Math.max(endDTS, frag.endDTS);\n }\n\n const drift = startPTS - frag.start;\n frag.start = frag.startPTS = startPTS;\n frag.maxStartPTS = maxStartPTS;\n frag.endPTS = endPTS;\n frag.minEndPTS = minEndPTS;\n frag.startDTS = startDTS;\n frag.endDTS = endDTS;\n frag.duration = endPTS - startPTS;\n\n const sn = frag.sn;\n // exit if sn out of range\n if (!details || sn < details.startSN || sn > details.endSN) {\n return 0;\n }\n\n let fragIdx, fragments, i;\n fragIdx = sn - details.startSN;\n fragments = details.fragments;\n // update frag reference in fragments array\n // rationale is that fragments array might not contain this frag object.\n // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()\n // if we don't update frag, we won't be able to propagate PTS info on the playlist\n // resulting in invalid sliding computation\n fragments[fragIdx] = frag;\n // adjust fragment PTS/duration from seqnum-1 to frag 0\n for (i = fragIdx; i > 0; i--) {\n updatePTS(fragments, i, i - 1);\n }\n\n // adjust fragment PTS/duration from seqnum to last frag\n for (i = fragIdx; i < fragments.length - 1; i++) {\n updatePTS(fragments, i, i + 1);\n }\n\n details.PTSKnown = true;\n return drift;\n}\n\nexport function mergeDetails (oldDetails, newDetails) {\n // potentially retrieve cached initsegment\n if (newDetails.initSegment && oldDetails.initSegment) {\n newDetails.initSegment = oldDetails.initSegment;\n }\n\n // check if old/new playlists have fragments in common\n // loop through overlapping SN and update startPTS , cc, and duration if any found\n let ccOffset = 0;\n let PTSFrag;\n mapFragmentIntersection(oldDetails, newDetails, (oldFrag, newFrag) => {\n ccOffset = oldFrag.cc - newFrag.cc;\n if (Number.isFinite(oldFrag.startPTS)) {\n newFrag.start = newFrag.startPTS = oldFrag.startPTS;\n newFrag.endPTS = oldFrag.endPTS;\n newFrag.duration = oldFrag.duration;\n newFrag.backtracked = oldFrag.backtracked;\n newFrag.dropped = oldFrag.dropped;\n PTSFrag = newFrag;\n }\n // PTS is known when there are overlapping segments\n newDetails.PTSKnown = true;\n });\n\n if (!newDetails.PTSKnown) {\n return;\n }\n\n if (ccOffset) {\n logger.log('discontinuity sliding from playlist, take drift into account');\n const newFragments = newDetails.fragments;\n for (let i = 0; i < newFragments.length; i++) {\n newFragments[i].cc += ccOffset;\n }\n }\n\n // if at least one fragment contains PTS info, recompute PTS information for all fragments\n if (PTSFrag) {\n updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);\n } else {\n // ensure that delta is within oldFragments range\n // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])\n // in that case we also need to adjust start offset of all fragments\n adjustSliding(oldDetails, newDetails);\n }\n // if we are here, it means we have fragments overlapping between\n // old and new level. reliable PTS info is thus relying on old level\n newDetails.PTSKnown = oldDetails.PTSKnown;\n}\n\nexport function mergeSubtitlePlaylists (oldPlaylist, newPlaylist, referenceStart = 0) {\n let lastIndex = -1;\n mapFragmentIntersection(oldPlaylist, newPlaylist, (oldFrag, newFrag, index) => {\n newFrag.start = oldFrag.start;\n lastIndex = index;\n });\n\n const frags = newPlaylist.fragments;\n if (lastIndex < 0) {\n frags.forEach(frag => {\n frag.start += referenceStart;\n });\n return;\n }\n\n for (let i = lastIndex + 1; i < frags.length; i++) {\n frags[i].start = (frags[i - 1].start + frags[i - 1].duration);\n }\n}\n\nexport function mapFragmentIntersection (oldPlaylist, newPlaylist, intersectionFn) {\n if (!oldPlaylist || !newPlaylist) {\n return;\n }\n\n const start = Math.max(oldPlaylist.startSN, newPlaylist.startSN) - newPlaylist.startSN;\n const end = Math.min(oldPlaylist.endSN, newPlaylist.endSN) - newPlaylist.startSN;\n const delta = newPlaylist.startSN - oldPlaylist.startSN;\n\n for (let i = start; i <= end; i++) {\n const oldFrag = oldPlaylist.fragments[delta + i];\n const newFrag = newPlaylist.fragments[i];\n if (!oldFrag || !newFrag) {\n break;\n }\n intersectionFn(oldFrag, newFrag, i);\n }\n}\n\nexport function adjustSliding (oldPlaylist, newPlaylist) {\n const delta = newPlaylist.startSN - oldPlaylist.startSN;\n const oldFragments = oldPlaylist.fragments;\n const newFragments = newPlaylist.fragments;\n\n if (delta < 0 || delta > oldFragments.length) {\n return;\n }\n for (let i = 0; i < newFragments.length; i++) {\n newFragments[i].start += oldFragments[delta].start;\n }\n}\n\nexport function computeReloadInterval (currentPlaylist, newPlaylist, lastRequestTime) {\n let reloadInterval = 1000 * (newPlaylist.averagetargetduration ? newPlaylist.averagetargetduration : newPlaylist.targetduration);\n const minReloadInterval = reloadInterval / 2;\n if (currentPlaylist && newPlaylist.endSN === currentPlaylist.endSN) {\n // follow HLS Spec, If the client reloads a Playlist file and finds that it has not\n // changed then it MUST wait for a period of one-half the target\n // duration before retrying.\n reloadInterval = minReloadInterval;\n }\n\n if (lastRequestTime) {\n reloadInterval = Math.max(minReloadInterval, reloadInterval - (window.performance.now() - lastRequestTime));\n }\n // in any case, don't reload more than half of target duration\n return Math.round(reloadInterval);\n}\n","/**\n * TimeRanges to string helper\n */\n\nconst TimeRanges = {\n toString: function (r: TimeRanges) {\n let log = '';\n let len = r.length;\n for (let i = 0; i < len; i++) {\n log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';\n }\n\n return log;\n }\n};\n\nexport default TimeRanges;\n","import BinarySearch from './binary-search';\nimport { logger } from '../utils/logger';\n\nexport function findFirstFragWithCC (fragments, cc) {\n let firstFrag = null;\n\n for (let i = 0; i < fragments.length; i += 1) {\n const currentFrag = fragments[i];\n if (currentFrag && currentFrag.cc === cc) {\n firstFrag = currentFrag;\n break;\n }\n }\n\n return firstFrag;\n}\n\nexport function findFragWithCC (fragments, CC) {\n return BinarySearch.search(fragments, (candidate) => {\n if (candidate.cc < CC) {\n return 1;\n } else if (candidate.cc > CC) {\n return -1;\n } else {\n return 0;\n }\n });\n}\n\nexport function shouldAlignOnDiscontinuities (lastFrag, lastLevel, details) {\n let shouldAlign = false;\n if (lastLevel && lastLevel.details && details) {\n if (details.endCC > details.startCC || (lastFrag && lastFrag.cc < details.startCC)) {\n shouldAlign = true;\n }\n }\n return shouldAlign;\n}\n\n// Find the first frag in the previous level which matches the CC of the first frag of the new level\nexport function findDiscontinuousReferenceFrag (prevDetails, curDetails) {\n const prevFrags = prevDetails.fragments;\n const curFrags = curDetails.fragments;\n\n if (!curFrags.length || !prevFrags.length) {\n logger.log('No fragments to align');\n return;\n }\n\n const prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);\n\n if (!prevStartFrag || (prevStartFrag && !prevStartFrag.startPTS)) {\n logger.log('No frag in previous level to align on');\n return;\n }\n\n return prevStartFrag;\n}\n\nexport function adjustPts (sliding, details) {\n details.fragments.forEach((frag) => {\n if (frag) {\n let start = frag.start + sliding;\n frag.start = frag.startPTS = start;\n frag.endPTS = start + frag.duration;\n }\n });\n details.PTSKnown = true;\n}\n\n/**\n * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a\n * contiguous stream with the last fragments.\n * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to\n * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time\n * and an extra download.\n * @param lastFrag\n * @param lastLevel\n * @param details\n */\nexport function alignStream (lastFrag, lastLevel, details) {\n alignDiscontinuities(lastFrag, details, lastLevel);\n if (!details.PTSKnown && lastLevel) {\n // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.\n // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same\n // discontinuity sequence.\n alignPDT(details, lastLevel.details);\n }\n}\n\n/**\n * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same\n * discontinuity sequence.\n * @param lastLevel - The details of the last loaded level\n * @param details - The details of the new level\n */\nexport function alignDiscontinuities (lastFrag, details, lastLevel) {\n if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {\n const referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);\n if (referenceFrag) {\n logger.log('Adjusting PTS using last level due to CC increase within current level');\n adjustPts(referenceFrag.start, details);\n }\n }\n}\n\n/**\n * Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.\n * @param details - The details of the new level\n * @param lastDetails - The details of the last loaded level\n */\nexport function alignPDT (details, lastDetails) {\n if (lastDetails && lastDetails.fragments.length) {\n if (!details.hasProgramDateTime || !lastDetails.hasProgramDateTime) {\n return;\n }\n // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM\n // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM\n // then we can deduce that playlist B sliding is 1000+8 = 1008s\n let lastPDT = lastDetails.fragments[0].programDateTime;\n let newPDT = details.fragments[0].programDateTime;\n // date diff is in ms. frag.start is in seconds\n let sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;\n if (Number.isFinite(sliding)) {\n logger.log(`adjusting PTS using programDateTime delta, sliding:${sliding.toFixed(3)}`);\n adjustPts(sliding, details);\n }\n }\n}\n","import BinarySearch from '../utils/binary-search';\nimport Fragment from '../loader/fragment';\n\n/**\n * Returns first fragment whose endPdt value exceeds the given PDT.\n * @param {Array<Fragment>} fragments - The array of candidate fragments\n * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded\n * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous\n * @returns {*|null} fragment - The best matching fragment\n */\nexport function findFragmentByPDT (fragments: Array<Fragment>, PDTValue: number | null, maxFragLookUpTolerance: number): Fragment | null {\n if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !Number.isFinite(PDTValue)) {\n return null;\n }\n\n // if less than start\n const startPDT = fragments[0].programDateTime;\n if (PDTValue < (startPDT || 0)) {\n return null;\n }\n\n const endPDT = fragments[fragments.length - 1].endProgramDateTime;\n if (PDTValue >= (endPDT || 0)) {\n return null;\n }\n\n maxFragLookUpTolerance = maxFragLookUpTolerance || 0;\n for (let seg = 0; seg < fragments.length; ++seg) {\n let frag = fragments[seg];\n if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {\n return frag;\n }\n }\n\n return null;\n}\n\n/**\n * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.\n * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus\n * breaking any traps which would cause the same fragment to be continuously selected within a small range.\n * @param {*} fragPrevious - The last frag successfully appended\n * @param {Array<Fragment>} fragments - The array of candidate fragments\n * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within\n * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous\n * @returns {*} foundFrag - The best matching fragment\n */\nexport function findFragmentByPTS (fragPrevious: Fragment, fragments: Array<Fragment>, bufferEnd: number = 0, maxFragLookUpTolerance: number = 0): Fragment | null {\n let fragNext: Fragment | null = null;\n if (fragPrevious) {\n fragNext = fragments[fragPrevious.sn as number - (fragments[0].sn as number) + 1];\n } else if (bufferEnd === 0 && fragments[0].start === 0) {\n fragNext = fragments[0];\n }\n // Prefer the next fragment if it's within tolerance\n if (fragNext && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0) {\n return fragNext;\n }\n // We might be seeking past the tolerance so find the best match\n const foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));\n if (foundFragment) {\n return foundFragment;\n }\n // If no match was found return the next fragment after fragPrevious, or null\n return fragNext;\n}\n\n/**\n * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.\n * @param {*} candidate - The fragment to test\n * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within\n * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {number} - 0 if it matches, 1 if too low, -1 if too high\n */\nexport function fragmentWithinToleranceTest (bufferEnd = 0, maxFragLookUpTolerance = 0, candidate: Fragment) {\n // offset should be within fragment boundary - config.maxFragLookUpTolerance\n // this is to cope with situations like\n // bufferEnd = 9.991\n // frag[Ø] : [0,10]\n // frag[1] : [10,20]\n // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here\n // frag start frag start+duration\n // |-----------------------------|\n // <---> <--->\n // ...--------><-----------------------------><---------....\n // previous frag matching fragment next frag\n // return -1 return 0 return 1\n // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);\n // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments\n let candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));\n if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {\n return 1;\n } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n return -1;\n }\n\n return 0;\n}\n\n/**\n * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.\n * This function tests the candidate's program date time values, as represented in Unix time\n * @param {*} candidate - The fragment to test\n * @param {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range\n * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {boolean} True if contiguous, false otherwise\n */\nexport function pdtWithinToleranceTest (pdtBufferEnd: number, maxFragLookUpTolerance: number, candidate: Fragment): boolean {\n let candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000;\n\n // endProgramDateTime can be null, default to zero\n const endProgramDateTime = candidate.endProgramDateTime || 0;\n return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;\n}\n","import { BufferHelper } from '../utils/buffer-helper';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport Event from '../events';\nimport { logger } from '../utils/logger';\n\nexport const STALL_MINIMUM_DURATION_MS = 250;\nexport const MAX_START_GAP_JUMP = 2.0;\nexport const SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;\nexport const SKIP_BUFFER_RANGE_START = 0.05;\n\nexport default class GapController {\n constructor (config, media, fragmentTracker, hls) {\n this.config = config;\n this.media = media;\n this.fragmentTracker = fragmentTracker;\n this.hls = hls;\n this.nudgeRetry = 0;\n this.stallReported = false;\n this.stalled = null;\n this.moved = false;\n this.seeking = false;\n }\n\n /**\n * Checks if the playhead is stuck within a gap, and if so, attempts to free it.\n * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).\n *\n * @param {number} lastCurrentTime Previously read playhead position\n */\n poll (lastCurrentTime) {\n const { config, media, stalled } = this;\n const { currentTime, seeking } = media;\n const seeked = this.seeking && !seeking;\n const beginSeek = !this.seeking && seeking;\n\n this.seeking = seeking;\n\n // The playhead is moving, no-op\n if (currentTime !== lastCurrentTime) {\n this.moved = true;\n if (stalled !== null) {\n // The playhead is now moving, but was previously stalled\n if (this.stallReported) {\n const stalledDuration = self.performance.now() - stalled;\n logger.warn(`playback not stuck anymore @${currentTime}, after ${Math.round(stalledDuration)}ms`);\n this.stallReported = false;\n }\n this.stalled = null;\n this.nudgeRetry = 0;\n }\n return;\n }\n\n // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek\n if (beginSeek || seeked) {\n this.stalled = null;\n }\n\n // The playhead should not be moving\n if (media.paused || media.ended || media.playbackRate === 0 || !media.buffered.length) {\n return;\n }\n\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);\n const isBuffered = bufferInfo.len > 0;\n const nextStart = bufferInfo.nextStart || 0;\n\n // There is no playable buffer (waiting for buffer append)\n if (!isBuffered && !nextStart) {\n return;\n }\n\n if (seeking) {\n // Waiting for seeking in a buffered range to complete\n const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;\n // Next buffered range is too far ahead to jump to while still seeking\n const noBufferGap = !nextStart ||\n (nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime));\n if (hasEnoughBuffer || noBufferGap) {\n return;\n }\n // Reset moved state when seeking to a point in or before a gap\n this.moved = false;\n }\n\n // Skip start gaps if we haven't played, but the last poll detected the start of a stall\n // The addition poll gives the browser a chance to jump the gap for us\n if (!this.moved && this.stalled) {\n // Jump start gaps within jump threshold\n const startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;\n 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 (buffer=${bufferLen})`);\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: false,\n buffer: bufferLen\n });\n }\n }\n\n /**\n * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments\n * @param partial - The partial fragment found at the current time (where playback is stalling).\n * @private\n */\n _trySkipBufferHole (partial) {\n const { config, hls, media } = this;\n const currentTime = media.currentTime;\n let lastEndTime = 0;\n // Check if currentTime is between unbuffered regions of partial fragments\n for (let i = 0; i < media.buffered.length; i++) {\n const startTime = media.buffered.start(i);\n if (currentTime + config.maxBufferHole >= lastEndTime && currentTime < startTime) {\n const targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, media.currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);\n logger.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}`);\n this.moved = true;\n this.stalled = null;\n media.currentTime = targetTime;\n if (partial) {\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,\n fatal: false,\n reason: `fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`,\n frag: partial\n });\n }\n return targetTime;\n }\n lastEndTime = media.buffered.end(i);\n }\n return 0;\n }\n\n /**\n * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.\n * @private\n */\n _tryNudgeBuffer () {\n const { config, hls, media } = this;\n const currentTime = media.currentTime;\n const nudgeRetry = (this.nudgeRetry || 0) + 1;\n this.nudgeRetry = nudgeRetry;\n\n if (nudgeRetry < config.nudgeMaxRetry) {\n const targetTime = currentTime + nudgeRetry * config.nudgeOffset;\n // playback stalled in buffered area ... let's nudge currentTime to try to overcome this\n logger.warn(`Nudging 'currentTime' from ${currentTime} to ${targetTime}`);\n media.currentTime = targetTime;\n\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_NUDGE_ON_STALL,\n fatal: false\n });\n } else {\n logger.error(`Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`);\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: true\n });\n }\n }\n}\n","import 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 logger.log(`media seeking to ${Number.isFinite(currentTime) ? currentTime.toFixed(3) : currentTime}`);\n\n if (state === State.FRAG_LOADING) {\n let fragCurrent = this.fragCurrent;\n // check if we are seeking to a unbuffered area AND if frag loading is in progress\n if (bufferInfo.len === 0 && fragCurrent) {\n const tolerance = config.maxFragLookUpTolerance;\n const fragStartOffset = fragCurrent.start - tolerance;\n const fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;\n // check if we seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything\n if (currentTime < fragStartOffset || currentTime > fragEndOffset) {\n if (fragCurrent.loader) {\n logger.log('seeking outside of buffer while fragment load in progress, cancel fragment load');\n fragCurrent.loader.abort();\n }\n this.fragCurrent = null;\n this.fragPrevious = null;\n // switch to IDLE state to load new fragment\n this.state = State.IDLE;\n } else {\n logger.log('seeking outside of buffer but within currently loaded fragment range');\n }\n }\n } else if (state === State.ENDED) {\n // if seeking to unbuffered area, clean up fragPrevious\n if (bufferInfo.len === 0) {\n this.fragPrevious = null;\n this.fragCurrent = null;\n }\n\n // switch to IDLE state to check for potential new fragment\n this.state = State.IDLE;\n }\n if (media) {\n this.lastCurrentTime = currentTime;\n }\n\n // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target\n if (!this.loadedmetadata) {\n this.nextLoadPosition = this.startPosition = currentTime;\n }\n\n // tick to speed up processing\n this.tick();\n }\n\n onMediaEnded () {\n // reset startPosition and lastCurrentTime to restart playback @ stream beginning\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n onHandlerDestroying () {\n this.stopLoad();\n super.onHandlerDestroying();\n }\n\n onHandlerDestroyed () {\n this.state = State.STOPPED;\n this.fragmentTracker = null;\n }\n\n computeLivePosition (sliding, levelDetails) {\n let targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration;\n return sliding + Math.max(0, levelDetails.totalduration - targetLatency);\n }\n}\n","/*\n * Stream Controller\n*/\n\nimport BinarySearch from '../utils/binary-search';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport Demuxer from '../demux/demuxer';\nimport Event from '../events';\nimport { FragmentState } from './fragment-tracker';\nimport { ElementaryStreamTypes } from '../loader/fragment';\nimport { PlaylistLevelType } from '../types/loader';\nimport * as LevelHelper from './level-helper';\nimport TimeRanges from '../utils/time-ranges';\nimport { ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport { alignStream } from '../utils/discontinuities';\nimport { findFragmentByPDT, findFragmentByPTS } from './fragment-finders';\nimport GapController, { MAX_START_GAP_JUMP } from './gap-controller';\nimport BaseStreamController, { State } from './base-stream-controller';\n\nconst TICK_INTERVAL = 100; // how often to tick in ms\n\nclass StreamController extends BaseStreamController {\n constructor (hls, fragmentTracker) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.MANIFEST_LOADING,\n Event.MANIFEST_PARSED,\n Event.LEVEL_LOADED,\n Event.LEVELS_UPDATED,\n Event.KEY_LOADED,\n Event.FRAG_LOADED,\n Event.FRAG_LOAD_EMERGENCY_ABORTED,\n Event.FRAG_PARSING_INIT_SEGMENT,\n Event.FRAG_PARSING_DATA,\n Event.FRAG_PARSED,\n Event.ERROR,\n Event.AUDIO_TRACK_SWITCHING,\n Event.AUDIO_TRACK_SWITCHED,\n Event.BUFFER_CREATED,\n Event.BUFFER_APPENDED,\n Event.BUFFER_FLUSHED);\n\n this.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.audioCodecSwap = false;\n this._state = State.STOPPED;\n this.stallReported = false;\n this.gapController = null;\n this.altAudio = false;\n this.audioOnly = false;\n this.bitrateTest = false;\n }\n\n startLoad (startPosition) {\n if (this.levels) {\n let lastCurrentTime = this.lastCurrentTime, hls = this.hls;\n this.stopLoad();\n this.setInterval(TICK_INTERVAL);\n this.level = -1;\n this.fragLoadError = 0;\n if (!this.startFragRequested) {\n // determine load level\n let startLevel = hls.startLevel;\n if (startLevel === -1) {\n if (hls.config.testBandwidth) {\n // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level\n startLevel = 0;\n this.bitrateTest = true;\n } else {\n startLevel = hls.nextAutoLevel;\n }\n }\n // set new level to playlist loader : this will trigger start level load\n // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded\n this.level = hls.nextLoadLevel = startLevel;\n this.loadedmetadata = false;\n }\n // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime\n if (lastCurrentTime > 0 && startPosition === -1) {\n logger.log(`override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);\n startPosition = lastCurrentTime;\n }\n this.state = State.IDLE;\n this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;\n this.tick();\n } else {\n this.forceStartLoad = true;\n this.state = State.STOPPED;\n }\n }\n\n stopLoad () {\n this.forceStartLoad = false;\n super.stopLoad();\n }\n\n doTick () {\n switch (this.state) {\n case State.BUFFER_FLUSHING:\n // in buffer flushing state, reset fragLoadError counter\n this.fragLoadError = 0;\n break;\n case State.IDLE:\n this._doTickIdle();\n break;\n case State.WAITING_LEVEL:\n var 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 the \"main\" level is audio-only but we are loading an alternate track in the same group, do not load anything\n if (this.altAudio && this.audioOnly) {\n // Clear audio demuxer state so when switching back to main audio we're not still appending where we left off\n this.demuxer.frag = null;\n return;\n }\n\n // if we have not yet loaded any fragment, start loading from start position\n let pos;\n if (this.loadedmetadata) {\n pos = media.currentTime;\n } else {\n pos = this.nextLoadPosition;\n }\n\n // determine next load level\n let level = hls.nextLoadLevel,\n levelInfo = this.levels[level];\n\n if (!levelInfo) {\n return;\n }\n\n let levelBitrate = levelInfo.bitrate,\n maxBufLen;\n\n // compute max Buffer Length that we could get from this load level, based on level bitrate.\n if (levelBitrate) {\n maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);\n } else {\n maxBufLen = config.maxBufferLength;\n }\n\n maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength);\n\n // determine next candidate fragment to be loaded, based on current position and end of buffer position\n // ensure up to `config.maxMaxBufferLength` of buffer upfront\n\n const maxBufferHole = pos < config.maxBufferHole ? Math.max(MAX_START_GAP_JUMP, config.maxBufferHole) : config.maxBufferHole;\n const bufferInfo = BufferHelper.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, maxBufferHole);\n const bufferLen = bufferInfo.len;\n // Stay idle if we are still with buffer margins\n if (bufferLen >= maxBufLen) {\n return;\n }\n\n // if buffer length is less than maxBufLen try to load a new fragment ...\n logger.trace(`buffer length of ${bufferLen.toFixed(3)} is below max of ${maxBufLen.toFixed(3)}. checking for more payload ...`);\n\n // set next load level : this will trigger a playlist load if needed\n this.level = hls.nextLoadLevel = level;\n\n const levelDetails = levelInfo.details;\n // if level info not retrieved yet, switch state and wait for level retrieval\n // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load\n // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)\n if (!levelDetails || (levelDetails.live && this.levelLastLoaded !== level)) {\n this.state = State.WAITING_LEVEL;\n return;\n }\n\n if (this._streamEnded(bufferInfo, levelDetails)) {\n const data = {};\n if (this.altAudio) {\n data.type = 'video';\n }\n\n this.hls.trigger(Event.BUFFER_EOS, data);\n this.state = State.ENDED;\n return;\n }\n // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)\n this._fetchPayloadOrEos(pos, bufferInfo, levelDetails);\n }\n\n _fetchPayloadOrEos (pos, bufferInfo, levelDetails) {\n const fragPrevious = this.fragPrevious,\n 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);\n // if it explicitely returns null don't load any fragment and exit function now\n if (frag === null) {\n return;\n }\n } else {\n // VoD playlist: if bufferEnd before start of playlist, load first fragment\n if (bufferEnd < start) {\n frag = fragments[0];\n }\n }\n }\n if (!frag) {\n frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails);\n }\n\n if (frag) {\n if (frag.encrypted) {\n this._loadKey(frag, levelDetails);\n } else {\n this._loadFragment(frag, levelDetails, pos, bufferEnd);\n }\n }\n }\n\n _ensureFragmentAtLivePoint (levelDetails, bufferEnd, start, end, fragPrevious, fragments) {\n const config = this.hls.config, media = this.media;\n\n let frag;\n\n // check if requested position is within seekable boundaries :\n // logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);\n let maxLatency = Infinity;\n\n if (config.liveMaxLatencyDuration !== undefined) {\n maxLatency = config.liveMaxLatencyDuration;\n } else if (Number.isFinite(config.liveMaxLatencyDurationCount)) {\n maxLatency = config.liveMaxLatencyDurationCount * levelDetails.targetduration;\n }\n\n if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {\n let liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);\n bufferEnd = liveSyncPosition;\n if (media && !media.paused && media.readyState && media.duration > liveSyncPosition && liveSyncPosition > media.currentTime) {\n logger.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 }\n\n return frag;\n }\n\n _findFragment (start, fragPreviousLoad, fragmentIndexRange, fragments, bufferEnd, end, levelDetails) {\n const config = this.hls.config;\n let fragNextLoad;\n\n if (bufferEnd < end) {\n const lookupTolerance = (bufferEnd > end - config.maxFragLookUpTolerance) ? 0 : config.maxFragLookUpTolerance;\n // Remove the tolerance if it would put the bufferEnd past the actual end of stream\n // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n fragNextLoad = findFragmentByPTS(fragPreviousLoad, fragments, bufferEnd, lookupTolerance);\n } else {\n // reach end of playlist\n fragNextLoad = fragments[fragmentIndexRange - 1];\n }\n\n if (fragNextLoad) {\n const curSNIdx = fragNextLoad.sn - levelDetails.startSN;\n const sameLevel = fragPreviousLoad && fragNextLoad.level === fragPreviousLoad.level;\n const prevSnFrag = fragments[curSNIdx - 1];\n const nextSnFrag = fragments[curSNIdx + 1];\n\n // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);\n if (fragPreviousLoad && fragNextLoad.sn === fragPreviousLoad.sn) {\n if (sameLevel && !fragNextLoad.backtracked) {\n if (fragNextLoad.sn < levelDetails.endSN) {\n let deltaPTS = fragPreviousLoad.deltaPTS;\n // if there is a significant delta between audio and video, larger than max allowed hole,\n // and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped)\n // let's try to load previous fragment again to get last keyframe\n // then we will reload again current fragment (that way we should be able to fill the buffer hole ...)\n if (deltaPTS && deltaPTS > config.maxBufferHole && fragPreviousLoad.dropped && curSNIdx) {\n fragNextLoad = prevSnFrag;\n logger.warn('Previous fragment was dropped with large PTS gap between audio and video. Maybe fragment is not starting with a keyframe? Loading previous one to try to overcome this');\n } else {\n fragNextLoad = nextSnFrag;\n if (this.fragmentTracker.getState(fragNextLoad) !== FragmentState.OK) {\n logger.log(`Re-loading fragment with SN: ${fragNextLoad.sn}`);\n }\n }\n } else {\n fragNextLoad = null;\n }\n } else if (fragNextLoad.backtracked) {\n // Only backtrack a max of 1 consecutive fragment to prevent sliding back too far when little or no frags start with keyframes\n if (nextSnFrag && nextSnFrag.backtracked) {\n logger.warn(`Already backtracked from fragment ${nextSnFrag.sn}, will not backtrack to fragment ${fragNextLoad.sn}. Loading fragment ${nextSnFrag.sn}`);\n fragNextLoad = nextSnFrag;\n } else {\n // If a fragment has dropped frames and it's in a same level/sequence, load the previous fragment to try and find the keyframe\n // Reset the dropped count now since it won't be reset until we parse the fragment again, which prevents infinite backtracking on the same segment\n logger.warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe');\n fragNextLoad.dropped = 0;\n if (prevSnFrag) {\n fragNextLoad = prevSnFrag;\n fragNextLoad.backtracked = true;\n } else if (curSNIdx) {\n // can't backtrack on very first fragment\n fragNextLoad = null;\n }\n }\n }\n }\n }\n\n return fragNextLoad;\n }\n\n _loadKey (frag, levelDetails) {\n logger.log(`Loading key for ${frag.sn} of [${levelDetails.startSN}-${levelDetails.endSN}], level ${this.level}`);\n this.state = State.KEY_LOADING;\n this.hls.trigger(Event.KEY_LOADING, { frag });\n }\n\n _loadFragment (frag, levelDetails, pos, bufferEnd) {\n // Check if fragment is not loaded\n let fragState = this.fragmentTracker.getState(frag);\n\n this.fragCurrent = frag;\n if (frag.sn !== 'initSegment') {\n this.startFragRequested = true;\n }\n // Don't update nextLoadPosition for fragments which are not buffered\n if (Number.isFinite(frag.sn) && !frag.bitrateTest) {\n this.nextLoadPosition = frag.start + frag.duration;\n }\n\n // Allow backtracked fragments to load\n if (frag.backtracked || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {\n frag.autoLevel = this.hls.autoLevelEnabled;\n frag.bitrateTest = this.bitrateTest;\n\n logger.log(`Loading ${frag.sn} of [${levelDetails.startSN}-${levelDetails.endSN}], level ${this.level}, ${\n this.loadedmetadata ? 'currentTime' : 'nextLoadPosition'\n }: ${parseFloat(pos.toFixed(3))}, bufferEnd: ${parseFloat(bufferEnd.toFixed(3))}`);\n\n this.hls.trigger(Event.FRAG_LOADING, { frag });\n // lazy demuxer init, as this could take some time ... do it during frag loading\n if (!this.demuxer) {\n this.demuxer = new Demuxer(this.hls, 'main');\n }\n\n this.state = State.FRAG_LOADING;\n } else if (fragState === FragmentState.APPENDING) {\n // Lower the buffer size and try again\n if (this._reduceMaxBufferLength(frag.duration)) {\n this.fragmentTracker.removeFragment(frag);\n }\n }\n }\n\n set state (nextState) {\n if (this.state !== nextState) {\n const previousState = this.state;\n this._state = nextState;\n logger.log(`main stream-controller: ${previousState}->${nextState}`);\n this.hls.trigger(Event.STREAM_STATE_TRANSITION, { previousState, nextState });\n }\n }\n\n get state () {\n return this._state;\n }\n\n getBufferedFrag (position) {\n return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);\n }\n\n get currentLevel () {\n let media = this.media;\n if (media) {\n const frag = this.getBufferedFrag(media.currentTime);\n if (frag) {\n return frag.level;\n }\n }\n return -1;\n }\n\n get nextBufferedFrag () {\n let media = this.media;\n if (media) {\n // first get end range of current fragment\n return this.followingBufferedFrag(this.getBufferedFrag(media.currentTime));\n } else {\n return null;\n }\n }\n\n followingBufferedFrag (frag) {\n if (frag) {\n // try to get range of next fragment (500ms after this range)\n return this.getBufferedFrag(frag.endPTS + 0.5);\n }\n return null;\n }\n\n get nextLevel () {\n const frag = this.nextBufferedFrag;\n if (frag) {\n return frag.level;\n } else {\n return -1;\n }\n }\n\n _checkFragmentChanged () {\n let fragPlayingCurrent, currentTime, video = this.media;\n if (video && video.readyState && video.seeking === false) {\n currentTime = video.currentTime;\n /* if video element is in seeked state, currentTime can only increase.\n (assuming that playback rate is positive ...)\n As sometimes currentTime jumps back to zero after a\n media decode error, check this, to avoid seeking back to\n wrong position after a media decode error\n */\n if (currentTime > this.lastCurrentTime) {\n this.lastCurrentTime = currentTime;\n }\n\n if (BufferHelper.isBuffered(video, currentTime)) {\n fragPlayingCurrent = this.getBufferedFrag(currentTime);\n } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {\n /* ensure that FRAG_CHANGED event is triggered at startup,\n when first video frame is displayed and playback is paused.\n add a tolerance of 100ms, in case current position is not buffered,\n check if current pos+100ms is buffered and use that buffer range\n for FRAG_CHANGED event reporting */\n fragPlayingCurrent = this.getBufferedFrag(currentTime + 0.1);\n }\n if (fragPlayingCurrent) {\n let fragPlaying = fragPlayingCurrent;\n if (fragPlaying !== this.fragPlaying) {\n this.hls.trigger(Event.FRAG_CHANGED, { frag: fragPlaying });\n const fragPlayingLevel = fragPlaying.level;\n if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) {\n this.hls.trigger(Event.LEVEL_SWITCHED, { level: fragPlayingLevel });\n }\n\n this.fragPlaying = fragPlaying;\n }\n }\n }\n }\n\n /*\n on immediate level switch :\n - pause playback if playing\n - cancel any pending load request\n - and trigger a buffer flush\n */\n immediateLevelSwitch () {\n logger.log('immediateLevelSwitch');\n if (!this.immediateSwitch) {\n this.immediateSwitch = true;\n let media = this.media, previouslyPaused;\n if (media) {\n previouslyPaused = media.paused;\n if (!previouslyPaused) {\n media.pause();\n }\n } else {\n // don't restart playback after instant level switch in case media not attached\n previouslyPaused = true;\n }\n this.previouslyPaused = previouslyPaused;\n }\n let fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\n\n this.fragCurrent = null;\n // flush everything\n this.flushMainBuffer(0, Number.POSITIVE_INFINITY);\n }\n\n /**\n * on immediate level switch end, after new fragment has been buffered:\n * - nudge video decoder by slightly adjusting video currentTime (if currentTime buffered)\n * - resume the playback if needed\n */\n immediateLevelSwitchEnd () {\n const media = this.media;\n if (media && media.buffered.length) {\n this.immediateSwitch = false;\n if (media.currentTime > 0 && BufferHelper.isBuffered(media, media.currentTime)) {\n // only nudge if currentTime is buffered\n media.currentTime -= 0.0001;\n }\n if (!this.previouslyPaused) {\n media.play();\n }\n }\n }\n\n /**\n * try to switch ASAP without breaking video playback:\n * in order to ensure smooth but quick level switching,\n * we need to find the next flushable buffer range\n * we should take into account new segment fetch time\n */\n nextLevelSwitch () {\n const media = this.media;\n // ensure that media is defined and that metadata are available (to retrieve currentTime)\n if (media && media.readyState) {\n let fetchdelay;\n const fragPlayingCurrent = this.getBufferedFrag(media.currentTime);\n if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 1) {\n // flush buffer preceding current fragment (flush until current fragment start offset)\n // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...\n this.flushMainBuffer(0, fragPlayingCurrent.startPTS - 1);\n }\n if (!media.paused) {\n // add a safety delay of 1s\n let nextLevelId = this.hls.nextLoadLevel, nextLevel = this.levels[nextLevelId], fragLastKbps = this.fragLastKbps;\n if (fragLastKbps && this.fragCurrent) {\n fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;\n } else {\n fetchdelay = 0;\n }\n } else {\n fetchdelay = 0;\n }\n // logger.log('fetchdelay:'+fetchdelay);\n // find buffer range that will be reached once new fragment will be fetched\n const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);\n if (bufferedFrag) {\n // we can flush buffer range following this one without stalling playback\n const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);\n if (nextBufferedFrag) {\n // if we are here, we can also cancel any loading/demuxing in progress, as they are useless\n let fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\n\n this.fragCurrent = null;\n // start flush position is the start PTS of next buffered frag.\n // we use frag.naxStartPTS which is max(audio startPTS, video startPTS).\n // in case there is a small PTS Delta between audio and video, using maxStartPTS avoids flushing last samples from current fragment\n const startPts = Math.max(bufferedFrag.endPTS, nextBufferedFrag.maxStartPTS + Math.min(this.config.maxFragLookUpTolerance, nextBufferedFrag.duration));\n this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);\n }\n }\n }\n }\n\n flushMainBuffer (startOffset, endOffset) {\n this.state = State.BUFFER_FLUSHING;\n let flushScope = { startOffset: startOffset, endOffset: endOffset };\n // if alternate audio tracks are used, only flush video, otherwise flush everything\n if (this.altAudio) {\n flushScope.type = 'video';\n }\n\n this.hls.trigger(Event.BUFFER_FLUSHING, flushScope);\n }\n\n onMediaAttached (data) {\n let media = this.media = this.mediaBuffer = data.media;\n this.onvseeking = this.onMediaSeeking.bind(this);\n this.onvseeked = this.onMediaSeeked.bind(this);\n this.onvended = this.onMediaEnded.bind(this);\n media.addEventListener('seeking', this.onvseeking);\n media.addEventListener('seeked', this.onvseeked);\n media.addEventListener('ended', this.onvended);\n let config = this.config;\n if (this.levels && config.autoStartLoad) {\n this.hls.startLoad(config.startPosition);\n }\n\n this.gapController = new GapController(config, media, this.fragmentTracker, this.hls);\n }\n\n onMediaDetaching () {\n let media = this.media;\n if (media && media.ended) {\n logger.log('MSE detaching and video ended, reset startPosition');\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n // reset fragment backtracked flag\n let levels = this.levels;\n if (levels) {\n levels.forEach(level => {\n if (level.details) {\n level.details.fragments.forEach(fragment => {\n fragment.backtracked = undefined;\n });\n }\n });\n }\n\n // remove video listeners\n if (media) {\n media.removeEventListener('seeking', this.onvseeking);\n media.removeEventListener('seeked', this.onvseeked);\n media.removeEventListener('ended', this.onvended);\n this.onvseeking = this.onvseeked = this.onvended = null;\n }\n\n this.fragmentTracker.removeAllFragments();\n this.media = this.mediaBuffer = null;\n this.loadedmetadata = false;\n this.stopLoad();\n }\n\n onMediaSeeked () {\n const media = this.media;\n const currentTime = media ? media.currentTime : undefined;\n if (Number.isFinite(currentTime)) {\n logger.log(`media seeked to ${currentTime.toFixed(3)}`);\n }\n\n // tick to speed up FRAGMENT_PLAYING triggering\n this.tick();\n }\n\n onManifestLoading () {\n // reset buffer on manifest loading\n logger.log('trigger BUFFER_RESET');\n this.hls.trigger(Event.BUFFER_RESET);\n this.fragmentTracker.removeAllFragments();\n this.stalled = false;\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n onManifestParsed (data) {\n let aac = false, heaac = false, codec;\n data.levels.forEach(level => {\n // detect if we have different kind of audio codecs used amongst playlists\n codec = level.audioCodec;\n if (codec) {\n if (codec.indexOf('mp4a.40.2') !== -1) {\n aac = true;\n }\n\n if (codec.indexOf('mp4a.40.5') !== -1) {\n heaac = true;\n }\n }\n });\n this.audioCodecSwitch = (aac && heaac);\n if (this.audioCodecSwitch) {\n logger.log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');\n }\n\n this.altAudio = data.altAudio;\n this.levels = data.levels;\n this.startFragRequested = false;\n let config = this.config;\n if (config.autoStartLoad || this.forceStartLoad) {\n this.hls.startLoad(config.startPosition);\n }\n }\n\n onLevelLoaded (data) {\n const newDetails = data.details;\n const newLevelId = data.level;\n const lastLevel = this.levels[this.levelLastLoaded];\n const curLevel = this.levels[newLevelId];\n const duration = newDetails.totalduration;\n let sliding = 0;\n\n logger.log(`level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}],duration:${duration}`);\n\n if (newDetails.live || (curLevel.details && curLevel.details.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 this.audioOnly = tracks.audio && !tracks.video;\n\n // if audio track is expected to come from audio stream controller, discard any coming from main\n if (this.altAudio && !this.audioOnly) {\n delete tracks.audio;\n }\n\n // include levelCodec in audio and video tracks\n track = tracks.audio;\n if (track) {\n let audioCodec = this.levels[this.level].audioCodec,\n ua = navigator.userAgent.toLowerCase();\n if (audioCodec && this.audioCodecSwap) {\n logger.log('swapping playlist audio codec');\n if (audioCodec.indexOf('mp4a.40.5') !== -1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n // in case AAC and HE-AAC audio codecs are signalled in manifest\n // force HE-AAC , as it seems that most browsers prefers that way,\n // except for mono streams OR on FF\n // these conditions might need to be reviewed ...\n if (this.audioCodecSwitch) {\n // don't force HE-AAC if mono stream\n if (track.metadata.channelCount !== 1 &&\n // don't force HE-AAC if firefox\n ua.indexOf('firefox') === -1) {\n audioCodec = 'mp4a.40.5';\n }\n }\n // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise\n if (ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') { // Exclude mpeg audio\n audioCodec = 'mp4a.40.2';\n logger.log(`Android: force audio codec to ${audioCodec}`);\n }\n track.levelCodec = audioCodec;\n track.id = data.id;\n }\n track = tracks.video;\n if (track) {\n track.levelCodec = this.levels[this.level].videoCodec;\n track.id = data.id;\n }\n this.hls.trigger(Event.BUFFER_CODECS, tracks);\n // loop through tracks that are going to be provided to bufferController\n for (trackName in tracks) {\n track = tracks[trackName];\n logger.log(`main track:${trackName},container:${track.container},codecs[level/parsed]=[${track.levelCodec}/${track.codec}]`);\n let initSegment = track.initSegment;\n if (initSegment) {\n this.appended = true;\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n this.hls.trigger(Event.BUFFER_APPENDING, { type: trackName, data: initSegment, parent: 'main', content: 'initSegment' });\n }\n }\n // trigger handler right now\n this.tick();\n }\n }\n\n onFragParsingData (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n !(data.type === 'audio' && this.altAudio) && // filter out main audio if audio track is loaded through audio stream controller\n this.state === State.PARSING) {\n let level = this.levels[this.level],\n frag = fragCurrent;\n if (!Number.isFinite(data.endPTS)) {\n data.endPTS = data.startPTS + fragCurrent.duration;\n data.endDTS = data.startDTS + fragCurrent.duration;\n }\n\n if (data.hasAudio === true) {\n frag.addElementaryStream(ElementaryStreamTypes.AUDIO);\n }\n\n if (data.hasVideo === true) {\n frag.addElementaryStream(ElementaryStreamTypes.VIDEO);\n }\n\n logger.log(`Parsed ${data.type},PTS:[${data.startPTS.toFixed(3)},${data.endPTS.toFixed(3)}],DTS:[${data.startDTS.toFixed(3)}/${data.endDTS.toFixed(3)}],nb:${data.nb},dropped:${data.dropped || 0}`);\n\n // Detect gaps in a fragment and try to fix it by finding a keyframe in the previous fragment (see _findFragments)\n if (data.type === 'video') {\n frag.dropped = data.dropped;\n if (frag.dropped) {\n if (!frag.backtracked) {\n const levelDetails = level.details;\n if (levelDetails && frag.sn === levelDetails.startSN) {\n logger.warn('missing video frame(s) on first frag, appending with gap', frag.sn);\n } else {\n logger.warn('missing video frame(s), backtracking fragment', frag.sn);\n // Return back to the IDLE state without appending to buffer\n // Causes findFragments to backtrack a segment and find the keyframe\n // Audio fragments arriving before video sets the nextLoadPosition, causing _findFragments to skip the backtracked fragment\n this.fragmentTracker.removeFragment(frag);\n frag.backtracked = true;\n this.nextLoadPosition = data.startPTS;\n this.state = State.IDLE;\n this.fragPrevious = frag;\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n this.tick();\n return;\n }\n } else {\n logger.warn('Already backtracked on this fragment, appending with the gap', frag.sn);\n }\n } else {\n // Only reset the backtracked flag if we've loaded the frag without any dropped frames\n frag.backtracked = false;\n }\n }\n\n let drift = LevelHelper.updateFragPTSDTS(level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS),\n hls = this.hls;\n hls.trigger(Event.LEVEL_PTS_UPDATED, { details: level.details, level: this.level, drift: drift, type: data.type, start: data.startPTS, end: data.endPTS });\n // has remuxer dropped video frames located before first keyframe ?\n [data.data1, data.data2].forEach(buffer => {\n // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)\n // in that case it is useless to append following segments\n if (buffer && buffer.length && this.state === State.PARSING) {\n this.appended = true;\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n hls.trigger(Event.BUFFER_APPENDING, { type: data.type, data: buffer, parent: 'main', content: 'data' });\n }\n });\n // trigger handler right now\n this.tick();\n }\n }\n\n onFragParsed (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n this.stats.tparsed = window.performance.now();\n this.state = State.PARSED;\n this._checkAppendedParsed();\n }\n }\n\n onAudioTrackSwitching (data) {\n // if any URL found on new audio track, it is an alternate audio track\n const fromAltAudio = this.altAudio;\n const altAudio = !!data.url;\n const trackId = data.id;\n // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered\n // don't do anything if we switch to alt audio: audio stream controller is handling it.\n // we will just have to change buffer scheduling on audioTrackSwitched\n if (!altAudio) {\n if (this.mediaBuffer !== this.media) {\n logger.log('switching on main audio, use media.buffered to schedule main fragment loading');\n this.mediaBuffer = this.media;\n let fragCurrent = this.fragCurrent;\n // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch\n if (fragCurrent.loader) {\n logger.log('switching to main audio track, cancel main fragment load');\n fragCurrent.loader.abort();\n }\n this.fragCurrent = null;\n this.fragPrevious = null;\n // destroy demuxer to force init segment generation (following audio switch)\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n // switch to IDLE state to load new fragment\n this.state = State.IDLE;\n }\n let hls = this.hls;\n // If switching from alt to main audio, flush all audio and trigger track switched\n if (fromAltAudio) {\n hls.trigger(Event.BUFFER_FLUSHING, {\n startOffset: 0,\n endOffset: Number.POSITIVE_INFINITY,\n type: 'audio'\n });\n }\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, {\n id: trackId\n });\n }\n }\n\n onAudioTrackSwitched (data) {\n let trackId = data.id,\n altAudio = !!this.hls.audioTracks[trackId].url;\n if (altAudio) {\n let videoBuffer = this.videoBuffer;\n // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered\n if (videoBuffer && this.mediaBuffer !== videoBuffer) {\n logger.log('switching on alternate audio, use video.buffered to schedule main fragment loading');\n this.mediaBuffer = videoBuffer;\n }\n }\n this.altAudio = altAudio;\n this.tick();\n }\n\n onBufferCreated (data) {\n let tracks = data.tracks, mediaTrack, name, alternate = false;\n for (let type in tracks) {\n let track = tracks[type];\n if (track.id === 'main') {\n name = type;\n mediaTrack = track;\n // keep video source buffer reference\n if (type === 'video') {\n this.videoBuffer = tracks[type].buffer;\n }\n } else {\n alternate = true;\n }\n }\n if (alternate && mediaTrack) {\n logger.log(`alternate track found, use ${name}.buffered to schedule main fragment loading`);\n this.mediaBuffer = mediaTrack.buffer;\n } else {\n this.mediaBuffer = this.media;\n }\n }\n\n onBufferAppended (data) {\n if (data.parent === 'main') {\n const state = this.state;\n if (state === State.PARSING || state === State.PARSED) {\n // check if all buffers have been appended\n this.pendingBuffering = (data.pending > 0);\n this._checkAppendedParsed();\n }\n }\n }\n\n _checkAppendedParsed () {\n // trigger handler right now\n if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {\n const frag = this.fragCurrent;\n if (frag) {\n const media = this.mediaBuffer ? this.mediaBuffer : this.media;\n logger.log(`main buffered : ${TimeRanges.toString(media.buffered)}`);\n this.fragPrevious = frag;\n const stats = this.stats;\n stats.tbuffered = window.performance.now();\n // we should get rid of this.fragLastKbps\n this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst));\n this.hls.trigger(Event.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'main' });\n this.state = State.IDLE;\n }\n // Do not tick when _seekToStartPos needs to be called as seeking to the start can fail on live streams at this point\n if (this.loadedmetadata || this.startPosition <= 0) {\n this.tick();\n }\n }\n }\n\n onError (data) {\n let frag = data.frag || this.fragCurrent;\n // don't handle frag error not related to main fragment\n if (frag && frag.type !== 'main') {\n return;\n }\n\n // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end\n let mediaBuffered = !!this.media && BufferHelper.isBuffered(this.media, this.media.currentTime) && BufferHelper.isBuffered(this.media, this.media.currentTime + 0.5);\n\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n if (!data.fatal) {\n // keep retrying until the limit will be reached\n if ((this.fragLoadError + 1) <= this.config.fragLoadingMaxRetry) {\n // exponential backoff capped to config.fragLoadingMaxRetryTimeout\n let delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout);\n logger.warn(`mediaController: frag loading failed, retry in ${delay} ms`);\n this.retryDate = window.performance.now() + delay;\n // retry loading state\n // if loadedmetadata is not set, it means that we are emergency switch down on first frag\n // in that case, reset startFragRequested flag\n if (!this.loadedmetadata) {\n this.startFragRequested = false;\n this.nextLoadPosition = this.startPosition;\n }\n this.fragLoadError++;\n this.state = State.FRAG_LOADING_WAITING_RETRY;\n } else {\n logger.error(`mediaController: ${data.details} reaches max retry, redispatch as fatal ...`);\n // switch error to fatal\n data.fatal = true;\n this.state = State.ERROR;\n }\n }\n break;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n if (this.state !== State.ERROR) {\n if (data.fatal) {\n // if fatal error, stop processing\n this.state = State.ERROR;\n logger.warn(`streamController: ${data.details},switch to ${this.state} state ...`);\n } else {\n // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE\n if (!data.levelRetry && this.state === State.WAITING_LEVEL) {\n this.state = State.IDLE;\n }\n }\n }\n break;\n case ErrorDetails.BUFFER_FULL_ERROR:\n // if in appending state\n if (data.parent === 'main' && (this.state === State.PARSING || this.state === State.PARSED)) {\n // reduce max buf len if current position is buffered\n if (mediaBuffered) {\n this._reduceMaxBufferLength(this.config.maxBufferLength);\n this.state = State.IDLE;\n } else {\n // current position is not buffered, but browser is still complaining about buffer full error\n // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708\n // in that case flush the whole buffer to recover\n logger.warn('buffer full error also media.currentTime is not buffered, flush everything');\n this.fragCurrent = null;\n // flush everything\n this.flushMainBuffer(0, Number.POSITIVE_INFINITY);\n }\n }\n break;\n default:\n break;\n }\n }\n\n _reduceMaxBufferLength (minLength) {\n let config = this.config;\n if (config.maxMaxBufferLength >= minLength) {\n // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...\n config.maxMaxBufferLength /= 2;\n logger.warn(`main:reduce max buffer length to ${config.maxMaxBufferLength}s`);\n return true;\n }\n return false;\n }\n\n /**\n * Checks the health of the buffer and attempts to resolve playback stalls.\n * @private\n */\n _checkBuffer () {\n const { media } = this;\n if (!media || media.readyState === 0) {\n // Exit early if we don't have media or if the media hasn't 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 const elementaryStreamType = this.audioOnly ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;\n this.fragmentTracker.detectEvictedFragments(elementaryStreamType, 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 onLevelsUpdated (data) {\n this.levels = data.levels;\n }\n\n swapAudioCodec () {\n this.audioCodecSwap = !this.audioCodecSwap;\n }\n /**\n * Seeks to the set startPosition if not equal to the mediaElement's current time.\n * @private\n */\n _seekToStartPos () {\n const { media } = this;\n const currentTime = media.currentTime;\n let startPosition = this.startPosition;\n // only adjust currentTime if different from startPosition or if startPosition not buffered\n // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered\n if (currentTime !== startPosition && startPosition >= 0) {\n if (media.seeking) {\n logger.log(`could not seek to ${startPosition}, already seeking at ${currentTime}`);\n return;\n }\n const bufferStart = media.buffered.length ? media.buffered.start(0) : 0;\n const delta = bufferStart - startPosition;\n if (delta > 0 && delta < this.config.maxBufferHole) {\n logger.log(`adjusting start position by ${delta} to match buffer start`);\n startPosition += delta;\n this.startPosition = startPosition;\n }\n logger.log(`seek to target start position ${startPosition} from current time ${currentTime}. ready state ${media.readyState}`);\n media.currentTime = startPosition;\n }\n }\n\n _getAudioCodec (currentLevel) {\n let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;\n if (this.audioCodecSwap) {\n logger.log('swapping playlist audio codec');\n if (audioCodec) {\n if (audioCodec.indexOf('mp4a.40.5') !== -1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n }\n\n return audioCodec;\n }\n\n get liveSyncPosition () {\n return this._liveSyncPosition;\n }\n\n set liveSyncPosition (value) {\n this._liveSyncPosition = value;\n }\n}\nexport default StreamController;\n","/*\n * Level Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { isCodecSupportedInMp4 } from '../utils/codecs';\nimport { addGroupId, computeReloadInterval } from './level-helper';\n\nlet chromeOrFirefox;\n\nexport default class LevelController extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.MANIFEST_LOADED,\n Event.LEVEL_LOADED,\n Event.AUDIO_TRACK_SWITCHED,\n Event.FRAG_LOADED,\n Event.ERROR);\n\n this.canload = false;\n this.currentLevelIndex = null;\n this.manualLevelIndex = -1;\n this.timer = null;\n\n chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());\n }\n\n onHandlerDestroying () {\n this.clearTimer();\n this.manualLevelIndex = -1;\n }\n\n clearTimer () {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n startLoad () {\n let levels = this._levels;\n\n this.canload = true;\n this.levelRetryCount = 0;\n\n // clean up live level details to force reload them, and reset load errors\n if (levels) {\n levels.forEach(level => {\n level.loadError = 0;\n const levelDetails = level.details;\n if (levelDetails && levelDetails.live) {\n level.details = undefined;\n }\n });\n }\n // speed up live playlist refresh if timer exists\n if (this.timer !== null) {\n this.loadLevel();\n }\n }\n\n stopLoad () {\n this.canload = false;\n }\n\n onManifestLoaded (data) {\n let levels = [];\n let audioTracks = [];\n let bitrateStart;\n let levelSet = {};\n let levelFromSet = null;\n let videoCodecFound = false;\n let audioCodecFound = false;\n\n // regroup redundant levels together\n data.levels.forEach(level => {\n const attributes = level.attrs;\n level.loadError = 0;\n level.fragmentError = false;\n\n videoCodecFound = videoCodecFound || !!level.videoCodec;\n audioCodecFound = audioCodecFound || !!level.audioCodec;\n\n // erase audio codec info if browser does not support mp4a.40.34.\n // demuxer will autodetect codec and fallback to mpeg/audio\n if (chromeOrFirefox && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {\n level.audioCodec = undefined;\n }\n\n levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here\n\n if (!levelFromSet) {\n level.url = [level.url];\n level.urlId = 0;\n levelSet[level.bitrate] = level;\n levels.push(level);\n } else {\n levelFromSet.url.push(level.url);\n }\n\n if (attributes) {\n if (attributes.AUDIO) {\n addGroupId(levelFromSet || level, 'audio', attributes.AUDIO);\n }\n if (attributes.SUBTITLES) {\n addGroupId(levelFromSet || level, 'text', attributes.SUBTITLES);\n }\n }\n });\n\n // remove audio-only level if we also have levels with audio+video codecs signalled\n if (videoCodecFound && audioCodecFound) {\n levels = levels.filter(({ videoCodec }) => !!videoCodec);\n }\n\n // only keep levels with supported audio/video codecs\n levels = levels.filter(({ audioCodec, videoCodec }) => {\n return (!audioCodec || isCodecSupportedInMp4(audioCodec, 'audio')) && (!videoCodec || isCodecSupportedInMp4(videoCodec, 'video'));\n });\n\n if (data.audioTracks) {\n audioTracks = data.audioTracks.filter(track => !track.audioCodec || isCodecSupportedInMp4(track.audioCodec, 'audio'));\n // Reassign id's after filtering since they're used as array indices\n audioTracks.forEach((track, index) => {\n track.id = index;\n });\n }\n\n if (levels.length > 0) {\n // start bitrate is the first bitrate of the manifest\n bitrateStart = levels[0].bitrate;\n // sort level on bitrate\n levels.sort((a, b) => a.bitrate - b.bitrate);\n this._levels = levels;\n // find index of first level in sorted levels\n for (let i = 0; i < levels.length; i++) {\n if (levels[i].bitrate === bitrateStart) {\n this._firstLevel = i;\n logger.log(`manifest loaded,${levels.length} level(s) found, first bitrate:${bitrateStart}`);\n break;\n }\n }\n\n // Audio is only alternate if manifest include a URI along with the audio group tag,\n // and this is not an audio-only stream where levels contain audio-only\n const audioOnly = audioCodecFound && !videoCodecFound;\n this.hls.trigger(Event.MANIFEST_PARSED, {\n levels,\n audioTracks,\n firstLevel: this._firstLevel,\n stats: data.stats,\n audio: audioCodecFound,\n video: videoCodecFound,\n altAudio: !audioOnly && audioTracks.some(t => !!t.url)\n });\n } else {\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,\n fatal: true,\n url: this.hls.url,\n reason: 'no level with compatible codecs found in manifest'\n });\n }\n }\n\n get levels () {\n return this._levels;\n }\n\n get level () {\n return this.currentLevelIndex;\n }\n\n set level (newLevel) {\n let levels = this._levels;\n if (levels) {\n newLevel = Math.min(newLevel, levels.length - 1);\n if (this.currentLevelIndex !== newLevel || !levels[newLevel].details) {\n this.setLevelInternal(newLevel);\n }\n }\n }\n\n setLevelInternal (newLevel) {\n const levels = this._levels;\n const hls = this.hls;\n // check if level idx is valid\n if (newLevel >= 0 && newLevel < levels.length) {\n // stopping live reloading timer if any\n this.clearTimer();\n if (this.currentLevelIndex !== newLevel) {\n logger.log(`switching to level ${newLevel}`);\n this.currentLevelIndex = newLevel;\n const levelProperties = levels[newLevel];\n levelProperties.level = newLevel;\n hls.trigger(Event.LEVEL_SWITCHING, levelProperties);\n }\n const level = levels[newLevel];\n const levelDetails = level.details;\n\n // check if we need to load playlist for this level\n if (!levelDetails || levelDetails.live) {\n // level not retrieved yet, or live playlist we need to (re)load it\n let urlId = level.urlId;\n hls.trigger(Event.LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId });\n }\n } else {\n // invalid level id given, trigger error\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.LEVEL_SWITCH_ERROR,\n level: newLevel,\n fatal: false,\n reason: 'invalid level idx'\n });\n }\n }\n\n get manualLevel () {\n return this.manualLevelIndex;\n }\n\n set manualLevel (newLevel) {\n this.manualLevelIndex = newLevel;\n if (this._startLevel === undefined) {\n this._startLevel = newLevel;\n }\n\n if (newLevel !== -1) {\n this.level = newLevel;\n }\n }\n\n get firstLevel () {\n return this._firstLevel;\n }\n\n set firstLevel (newLevel) {\n this._firstLevel = newLevel;\n }\n\n get startLevel () {\n // hls.startLevel takes precedence over config.startLevel\n // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)\n if (this._startLevel === undefined) {\n let configStartLevel = this.hls.config.startLevel;\n if (configStartLevel !== undefined) {\n return configStartLevel;\n } else {\n return this._firstLevel;\n }\n } else {\n return this._startLevel;\n }\n }\n\n set startLevel (newLevel) {\n this._startLevel = newLevel;\n }\n\n onError (data) {\n if (data.fatal) {\n if (data.type === ErrorTypes.NETWORK_ERROR) {\n this.clearTimer();\n }\n\n return;\n }\n\n let levelError = false, fragmentError = false;\n let levelIndex;\n\n // try to recover not fatal errors\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n levelIndex = data.frag.level;\n fragmentError = true;\n break;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n levelIndex = data.context.level;\n levelError = true;\n break;\n case ErrorDetails.REMUX_ALLOC_ERROR:\n levelIndex = data.level;\n levelError = true;\n break;\n }\n\n if (levelIndex !== undefined) {\n this.recoverLevel(data, levelIndex, levelError, fragmentError);\n }\n }\n\n /**\n * Switch to a redundant stream if any available.\n * If redundant stream is not available, emergency switch down if ABR mode is enabled.\n *\n * @param {Object} errorEvent\n * @param {Number} levelIndex current level index\n * @param {Boolean} levelError\n * @param {Boolean} fragmentError\n */\n // FIXME Find a better abstraction where fragment/level retry management is well decoupled\n recoverLevel (errorEvent, levelIndex, levelError, fragmentError) {\n let { config } = this.hls;\n let { details: errorDetails } = errorEvent;\n let level = this._levels[levelIndex];\n let redundantLevels, delay, nextLevel;\n\n level.loadError++;\n level.fragmentError = fragmentError;\n\n if (levelError) {\n if ((this.levelRetryCount + 1) <= config.levelLoadingMaxRetry) {\n // exponential backoff capped to max retry timeout\n delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);\n // Schedule level reload\n this.timer = setTimeout(() => this.loadLevel(), delay);\n // boolean used to inform stream controller not to switch back to IDLE on non fatal error\n errorEvent.levelRetry = true;\n this.levelRetryCount++;\n logger.warn(`level controller, ${errorDetails}, retry in ${delay} ms, current retry count is ${this.levelRetryCount}`);\n } else {\n logger.error(`level controller, cannot recover from ${errorDetails} error`);\n this.currentLevelIndex = null;\n // stopping live reloading timer if any\n this.clearTimer();\n // switch error to fatal\n errorEvent.fatal = true;\n return;\n }\n }\n\n // Try any redundant streams if available for both errors: level and fragment\n // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down\n if (levelError || fragmentError) {\n redundantLevels = level.url.length;\n\n if (redundantLevels > 1 && level.loadError < redundantLevels) {\n level.urlId = (level.urlId + 1) % redundantLevels;\n level.details = undefined;\n\n logger.warn(`level controller, ${errorDetails} for level ${levelIndex}: switching to redundant URL-id ${level.urlId}`);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', level.attrs.AUDIO);\n } else {\n // Search for available level\n if (this.manualLevelIndex === -1) {\n // When lowest level has been reached, let's start hunt from the top\n nextLevel = (levelIndex === 0) ? this._levels.length - 1 : levelIndex - 1;\n logger.warn(`level controller, ${errorDetails}: switch to ${nextLevel}`);\n this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;\n } else if (fragmentError) {\n // Allow fragment retry as long as configuration allows.\n // reset this._level so that another call to set level() will trigger again a frag load\n logger.warn(`level controller, ${errorDetails}: reload a fragment`);\n this.currentLevelIndex = null;\n }\n }\n }\n }\n\n // reset errors on the successful load of a fragment\n onFragLoaded ({ frag }) {\n if (frag !== undefined && frag.type === 'main') {\n const level = this._levels[frag.level];\n if (level !== undefined) {\n level.fragmentError = false;\n level.loadError = 0;\n this.levelRetryCount = 0;\n }\n }\n }\n\n onLevelLoaded (data) {\n const { level, details } = data;\n // only process level loaded events matching with expected level\n if (level !== this.currentLevelIndex) {\n return;\n }\n\n const curLevel = this._levels[level];\n // reset level load error counter on successful level loaded only if there is no issues with fragments\n if (!curLevel.fragmentError) {\n curLevel.loadError = 0;\n this.levelRetryCount = 0;\n }\n // if current playlist is a live playlist, arm a timer to reload it\n if (details.live) {\n const reloadInterval = computeReloadInterval(curLevel.details, details, data.stats.trequest);\n logger.log(`live playlist, reload in ${Math.round(reloadInterval)} ms`);\n this.timer = setTimeout(() => this.loadLevel(), reloadInterval);\n } else {\n this.clearTimer();\n }\n }\n\n onAudioTrackSwitched (data) {\n const audioGroupId = this.hls.audioTracks[data.id].groupId;\n\n const currentLevel = this.hls.levels[this.currentLevelIndex];\n if (!currentLevel) {\n return;\n }\n\n if (currentLevel.audioGroupIds) {\n let urlId = -1;\n\n for (let i = 0; i < currentLevel.audioGroupIds.length; i++) {\n if (currentLevel.audioGroupIds[i] === audioGroupId) {\n urlId = i;\n break;\n }\n }\n\n if (urlId !== currentLevel.urlId) {\n currentLevel.urlId = urlId;\n this.startLoad();\n }\n }\n }\n\n loadLevel () {\n logger.debug('call to loadLevel');\n\n if (this.currentLevelIndex !== null && this.canload) {\n const levelObject = this._levels[this.currentLevelIndex];\n\n if (typeof levelObject === 'object' &&\n levelObject.url.length > 0) {\n const level = this.currentLevelIndex;\n const id = levelObject.urlId;\n const url = levelObject.url[id];\n\n logger.log(`Attempt loading level index ${level} with URL-id ${id}`);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);\n\n this.hls.trigger(Event.LEVEL_LOADING, { url, level, id });\n }\n }\n }\n\n get nextLoadLevel () {\n if (this.manualLevelIndex !== -1) {\n return this.manualLevelIndex;\n } else {\n return this.hls.nextAutoLevel;\n }\n }\n\n set nextLoadLevel (nextLevel) {\n this.level = nextLevel;\n if (this.manualLevelIndex === -1) {\n this.hls.nextAutoLevel = nextLevel;\n }\n }\n\n removeLevel (levelIndex, urlId) {\n const levels = this.levels.filter((level, index) => {\n if (index !== levelIndex) {\n return true;\n }\n\n if (level.url.length > 1 && urlId !== undefined) {\n level.url = level.url.filter((url, id) => id !== urlId);\n level.urlId = 0;\n return true;\n }\n return false;\n }).map((level, index) => {\n const { details } = level;\n if (details && details.fragments) {\n details.fragments.forEach((fragment) => {\n fragment.level = index;\n });\n }\n return level;\n });\n\n this._levels = levels;\n\n this.hls.trigger(Event.LEVELS_UPDATED, { levels });\n }\n}\n","\nexport function sendAddTrackEvent (track: TextTrack, videoEl: HTMLMediaElement) {\n let event: Event;\n try {\n event = new Event('addtrack');\n } catch (err) {\n // for IE11\n event = document.createEvent('Event');\n event.initEvent('addtrack', false, false);\n }\n (event as any).track = track;\n videoEl.dispatchEvent(event);\n}\n\nexport function clearCurrentCues (track: TextTrack) {\n if (track?.cues) {\n while (track.cues.length > 0) {\n track.removeCue(track.cues[0]);\n }\n }\n}\n\n/**\n * Given a list of Cues, finds the closest cue matching the given time.\n * Modified verison of binary search O(log(n)).\n *\n * @export\n * @param {(TextTrackCueList | TextTrackCue[])} cues - List of cues.\n * @param {number} time - Target time, to find closest cue to.\n * @returns {TextTrackCue}\n */\nexport function getClosestCue (cues: TextTrackCueList | TextTrackCue[], time: number): TextTrackCue {\n // If the offset is less than the first element, the first element is the closest.\n if (time < cues[0].endTime) {\n return cues[0];\n }\n // If the offset is greater than the last cue, the last is the closest.\n if (time > cues[cues.length - 1].endTime) {\n return cues[cues.length - 1];\n }\n\n let left = 0;\n let right = cues.length - 1;\n\n while (left <= right) {\n const mid = Math.floor((right + left) / 2);\n\n if (time < cues[mid].endTime) {\n right = mid - 1;\n } else if (time > cues[mid].endTime) {\n left = mid + 1;\n } else {\n // If it's not lower or higher, it must be equal.\n return cues[mid];\n }\n }\n // At this point, left and right have swapped.\n // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.\n return (cues[left].endTime - time) < (time - cues[right].endTime) ? cues[left] : cues[right];\n}\n","/*\n * id3 metadata track controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport ID3 from '../demux/id3';\nimport { sendAddTrackEvent, clearCurrentCues, getClosestCue } from '../utils/texttrack-utils';\n\nconst MIN_CUE_DURATION = 0.25;\n\nclass ID3TrackController extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.FRAG_PARSING_METADATA,\n Event.LIVE_BACK_BUFFER_REACHED\n );\n this.id3Track = undefined;\n this.media = undefined;\n }\n\n destroy () {\n EventHandler.prototype.destroy.call(this);\n }\n\n // Add ID3 metatadata text track.\n onMediaAttached (data) {\n this.media = data.media;\n if (!this.media) {\n\n }\n }\n\n onMediaDetaching () {\n clearCurrentCues(this.id3Track);\n this.id3Track = undefined;\n this.media = undefined;\n }\n\n getID3Track (textTracks) {\n for (let i = 0; i < textTracks.length; i++) {\n let textTrack = textTracks[i];\n if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {\n // send 'addtrack' when reusing the textTrack for metadata,\n // same as what we do for captions\n sendAddTrackEvent(textTrack, this.media);\n\n return textTrack;\n }\n }\n return this.media.addTextTrack('metadata', 'id3');\n }\n\n onFragParsingMetadata (data) {\n const fragment = data.frag;\n const samples = data.samples;\n\n // create track dynamically\n if (!this.id3Track) {\n this.id3Track = this.getID3Track(this.media.textTracks);\n this.id3Track.mode = 'hidden';\n }\n\n // Attempt to recreate Safari functionality by creating\n // WebKitDataCue objects when available and store the decoded\n // ID3 data in the value property of the cue\n let Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue;\n\n for (let i = 0; i < samples.length; i++) {\n const frames = ID3.getID3Frames(samples[i].data);\n if (frames) {\n // Ensure the pts is positive - sometimes it's reported as a small negative number\n let startTime = Math.max(samples[i].pts, 0);\n let endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.endPTS;\n if (!endTime) {\n endTime = fragment.start + fragment.duration;\n }\n\n const timeDiff = endTime - startTime;\n if (timeDiff <= 0) {\n endTime = startTime + MIN_CUE_DURATION;\n }\n\n for (let j = 0; j < frames.length; j++) {\n const frame = frames[j];\n // Safari doesn't put the timestamp frame in the TextTrack\n if (!ID3.isTimeStampFrame(frame)) {\n const cue = new Cue(startTime, endTime, '');\n cue.value = frame;\n this.id3Track.addCue(cue);\n }\n }\n }\n }\n }\n\n onLiveBackBufferReached ({ bufferEnd }) {\n const { id3Track } = this;\n if (!id3Track || !id3Track.cues || !id3Track.cues.length) {\n return;\n }\n const foundCue = getClosestCue(id3Track.cues, bufferEnd);\n if (!foundCue) {\n return;\n }\n while (id3Track.cues[0] !== foundCue) {\n id3Track.removeCue(id3Track.cues[0]);\n }\n }\n}\n\nexport default ID3TrackController;\n","/*\n * compute an Exponential Weighted moving average\n * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\n * - heavily inspired from shaka-player\n */\n\nclass EWMA {\n private alpha_: number;\n private estimate_: number;\n private totalWeight_: number;\n\n // About half of the estimated value will be from the last |halfLife| samples by weight.\n constructor (halfLife: number) {\n // Larger values of alpha expire historical data more slowly.\n this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;\n this.estimate_ = 0;\n this.totalWeight_ = 0;\n }\n\n sample (weight: number, value: number) {\n let adjAlpha = Math.pow(this.alpha_, weight);\n this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;\n this.totalWeight_ += weight;\n }\n\n getTotalWeight (): number {\n return this.totalWeight_;\n }\n\n getEstimate (): number {\n if (this.alpha_) {\n let zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);\n return this.estimate_ / zeroFactor;\n } else {\n return this.estimate_;\n }\n }\n}\n\nexport default EWMA;\n","/*\n * EWMA Bandwidth Estimator\n * - heavily inspired from shaka-player\n * Tracks bandwidth samples and estimates available bandwidth.\n * Based on the minimum of two exponentially-weighted moving averages with\n * different half-lives.\n */\n\nimport EWMA from '../utils/ewma';\n\nclass EwmaBandWidthEstimator {\n hls: any;\n\n private defaultEstimate_: number;\n private minWeight_: number;\n private minDelayMs_: number;\n private slow_: EWMA;\n private fast_: EWMA;\n\n // TODO(typescript-hls)\n constructor (hls: any, slow: number, fast: number, defaultEstimate: number) {\n this.hls = hls;\n this.defaultEstimate_ = defaultEstimate;\n this.minWeight_ = 0.001;\n this.minDelayMs_ = 50;\n this.slow_ = new EWMA(slow);\n this.fast_ = new EWMA(fast);\n }\n\n sample (durationMs: number, numBytes: number) {\n durationMs = Math.max(durationMs, this.minDelayMs_);\n let numBits = 8 * numBytes,\n // weight is duration in seconds\n durationS = durationMs / 1000,\n // value is bandwidth in bits/s\n bandwidthInBps = numBits / durationS;\n this.fast_.sample(durationS, bandwidthInBps);\n this.slow_.sample(durationS, bandwidthInBps);\n }\n\n canEstimate (): boolean {\n let fast = this.fast_;\n return (fast && fast.getTotalWeight() >= this.minWeight_);\n }\n\n getEstimate (): number {\n if (this.canEstimate()) {\n // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));\n // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));\n // Take the minimum of these two estimates. This should have the effect of\n // adapting down quickly, but up more slowly.\n return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());\n } else {\n return this.defaultEstimate_;\n }\n }\n\n destroy () {\n }\n}\nexport default EwmaBandWidthEstimator;\n","/*\n * simple ABR Controller\n * - compute next level based on last fragment bw heuristics\n * - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling\n */\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport { ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport EwmaBandWidthEstimator from '../utils/ewma-bandwidth-estimator';\n\nconst { performance } = window;\n\nclass AbrController extends EventHandler {\n constructor (hls) {\n super(hls, Event.FRAG_LOADING,\n Event.FRAG_LOADED,\n Event.FRAG_BUFFERED,\n Event.ERROR);\n this.lastLoadedFragLevel = 0;\n this._nextAutoLevel = -1;\n this.hls = hls;\n this.timer = null;\n this._bwEstimator = null;\n this.onCheck = this._abandonRulesCheck.bind(this);\n }\n\n destroy () {\n this.clearTimer();\n EventHandler.prototype.destroy.call(this);\n }\n\n onFragLoading (data) {\n const frag = data.frag;\n if (frag.type === 'main') {\n if (!this.timer) {\n this.fragCurrent = frag;\n this.timer = setInterval(this.onCheck, 100);\n }\n\n // lazy init of BwEstimator, rationale is that we use different params for Live/VoD\n // so we need to wait for stream manifest / playlist type to instantiate it.\n if (!this._bwEstimator) {\n const hls = this.hls;\n const config = hls.config;\n const level = frag.level;\n const isLive = hls.levels[level].details.live;\n\n let ewmaFast;\n let ewmaSlow;\n if (isLive) {\n ewmaFast = config.abrEwmaFastLive;\n ewmaSlow = config.abrEwmaSlowLive;\n } else {\n ewmaFast = config.abrEwmaFastVoD;\n ewmaSlow = config.abrEwmaSlowVoD;\n }\n this._bwEstimator = new EwmaBandWidthEstimator(hls, ewmaSlow, ewmaFast, config.abrEwmaDefaultEstimate);\n }\n }\n }\n\n _abandonRulesCheck () {\n /*\n monitor fragment retrieval time...\n we compute expected time of arrival of the complete fragment.\n we compare it to expected time of buffer starvation\n */\n const hls = this.hls;\n const video = hls.media;\n const frag = this.fragCurrent;\n\n if (!frag) {\n return;\n }\n\n const loader = frag.loader;\n\n // if loader has been destroyed or loading has been aborted, stop timer and return\n if (!loader || (loader.stats && loader.stats.aborted)) {\n logger.warn('frag loader destroy or aborted, disarm abandonRules');\n this.clearTimer();\n // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\n return;\n }\n let stats = loader.stats;\n /* only monitor frag retrieval time if\n (video not paused OR first fragment being loaded(ready state === HAVE_NOTHING = 0)) AND autoswitching enabled AND not lowest level (=> means that we have several levels) */\n if (video && stats && ((!video.paused && (video.playbackRate !== 0)) || !video.readyState) && frag.autoLevel && frag.level) {\n const requestDelay = performance.now() - stats.trequest;\n const playbackRate = Math.abs(video.playbackRate);\n\n // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate\n if (requestDelay > (500 * frag.duration / playbackRate)) {\n const levels = hls.levels;\n const loadRate = Math.max(1, stats.bw ? stats.bw / 8 : stats.loaded * 1000 / requestDelay); // byte/s; at least 1 byte/s to avoid division by zero\n\n // compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size\n const level = levels[frag.level];\n if (!level) {\n return;\n }\n const levelBitrate = level.realBitrate ? Math.max(level.realBitrate, level.bitrate) : level.bitrate;\n const expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levelBitrate / 8));\n const pos = video.currentTime;\n const fragLoadedDelay = (expectedLen - stats.loaded) / loadRate;\n const bufferStarvationDelay = (BufferHelper.bufferInfo(video, pos, hls.config.maxBufferHole).end - pos) / playbackRate;\n\n // consider emergency switch down only if we have less than 2 frag buffered AND\n // time to finish loading current fragment is bigger than buffer starvation delay\n // ie if we risk buffer starvation if bw does not increase quickly\n if ((bufferStarvationDelay < (2 * frag.duration / playbackRate)) && (fragLoadedDelay > bufferStarvationDelay)) {\n const minAutoLevel = hls.minAutoLevel;\n let fragLevelNextLoadedDelay;\n let nextLoadLevel;\n // lets iterate through lower level and try to find the biggest one that could avoid rebuffering\n // we start from current level - 1 and we step down , until we find a matching level\n for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {\n // compute time to load next fragment at lower level\n // 0.8 : consider only 80% of current bw to be conservative\n // 8 = bits per byte (bps/Bps)\n const levelNextBitrate = levels[nextLoadLevel].realBitrate\n ? Math.max(levels[nextLoadLevel].realBitrate, levels[nextLoadLevel].bitrate)\n : levels[nextLoadLevel].bitrate;\n\n const fragLevelNextLoadedDelay = frag.duration * levelNextBitrate / (8 * 0.8 * loadRate);\n\n if (fragLevelNextLoadedDelay < bufferStarvationDelay) {\n // we found a lower level that be rebuffering free with current estimated bw !\n break;\n }\n }\n // only emergency switch down if it takes less time to load new fragment at lowest level instead\n // of finishing loading current one ...\n if (fragLevelNextLoadedDelay < fragLoadedDelay) {\n logger.warn(`loading too slow, abort fragment loading and switch to level ${nextLoadLevel}:fragLoadedDelay[${nextLoadLevel}]<fragLoadedDelay[${frag.level - 1}];bufferStarvationDelay:${fragLevelNextLoadedDelay.toFixed(1)}<${fragLoadedDelay.toFixed(1)}:${bufferStarvationDelay.toFixed(1)}`);\n // force next load level in auto mode\n hls.nextLoadLevel = nextLoadLevel;\n // update bw estimate for this fragment before cancelling load (this will help reducing the bw)\n this._bwEstimator.sample(requestDelay, stats.loaded);\n // abort fragment loading\n loader.abort();\n // stop abandon rules timer\n this.clearTimer();\n hls.trigger(Event.FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag, stats: stats });\n }\n }\n }\n }\n }\n\n onFragLoaded (data) {\n const frag = data.frag;\n if (frag.type === 'main' && Number.isFinite(frag.sn)) {\n // stop monitoring bw once frag loaded\n this.clearTimer();\n // store level id after successful fragment load\n this.lastLoadedFragLevel = frag.level;\n // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\n\n // compute level average bitrate\n if (this.hls.config.abrMaxWithRealBitrate) {\n const level = this.hls.levels[frag.level];\n let loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded;\n let loadedDuration = (level.loaded ? level.loaded.duration : 0) + data.frag.duration;\n level.loaded = { bytes: loadedBytes, duration: loadedDuration };\n level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);\n }\n // if fragment has been loaded to perform a bitrate test,\n if (data.frag.bitrateTest) {\n let stats = data.stats;\n stats.tparsed = stats.tbuffered = stats.tload;\n this.onFragBuffered(data);\n }\n }\n }\n\n onFragBuffered (data) {\n const stats = data.stats;\n const frag = data.frag;\n // only update stats on first frag buffering\n // if same frag is loaded multiple times, it might be in browser cache, and loaded quickly\n // and leading to wrong bw estimation\n // on bitrate test, also only update stats once (if tload = tbuffered == on FRAG_LOADED)\n if (stats.aborted !== true && frag.type === 'main' && Number.isFinite(frag.sn) && ((!frag.bitrateTest || stats.tload === stats.tbuffered))) {\n // use tparsed-trequest instead of tbuffered-trequest to compute fragLoadingProcessing; rationale is that buffer appending only happens once media is attached\n // in case we use config.startFragPrefetch while media is not attached yet, fragment might be parsed while media not attached yet, but it will only be buffered on media attached\n // as a consequence it could happen really late in the process. meaning that appending duration might appears huge ... leading to underestimated throughput estimation\n let fragLoadingProcessingMs = stats.tparsed - stats.trequest;\n logger.log(`latency/loading/parsing/append/kbps:${Math.round(stats.tfirst - stats.trequest)}/${Math.round(stats.tload - stats.tfirst)}/${Math.round(stats.tparsed - stats.tload)}/${Math.round(stats.tbuffered - stats.tparsed)}/${Math.round(8 * stats.loaded / (stats.tbuffered - stats.trequest))}`);\n this._bwEstimator.sample(fragLoadingProcessingMs, stats.loaded);\n stats.bwEstimate = this._bwEstimator.getEstimate();\n // if fragment has been loaded to perform a bitrate test, (hls.startLevel = -1), store bitrate test delay duration\n if (frag.bitrateTest) {\n this.bitrateTestDelay = fragLoadingProcessingMs / 1000;\n } else {\n this.bitrateTestDelay = 0;\n }\n }\n }\n\n onError (data) {\n // stop timer in case of frag loading error\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n this.clearTimer();\n break;\n default:\n break;\n }\n }\n\n clearTimer () {\n clearInterval(this.timer);\n this.timer = null;\n }\n\n // return next auto level\n get nextAutoLevel () {\n const forcedAutoLevel = this._nextAutoLevel;\n const bwEstimator = this._bwEstimator;\n // in case next auto level has been forced, and bw not available or not reliable, return forced value\n if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {\n return forcedAutoLevel;\n }\n\n // compute next level using ABR logic\n let nextABRAutoLevel = this._nextABRAutoLevel;\n // if forced auto level has been defined, use it to cap ABR computed quality level\n if (forcedAutoLevel !== -1) {\n nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);\n }\n\n return nextABRAutoLevel;\n }\n get _nextABRAutoLevel () {\n let hls = this.hls;\n const { maxAutoLevel, levels, config, minAutoLevel } = hls;\n const video = hls.media;\n const currentLevel = this.lastLoadedFragLevel;\n const currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0;\n const pos = (video ? video.currentTime : 0);\n\n // playbackRate is the absolute value of the playback rate; if video.playbackRate is 0, we use 1 to load as\n // if we're playing back at the normal rate.\n const playbackRate = ((video && (video.playbackRate !== 0)) ? Math.abs(video.playbackRate) : 1.0);\n const avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate;\n // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.\n const bufferStarvationDelay = (BufferHelper.bufferInfo(video, pos, config.maxBufferHole).end - pos) / playbackRate;\n\n // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all\n let bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor, levels);\n if (bestLevel >= 0) {\n return bestLevel;\n } else {\n logger.trace('rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering');\n // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering\n // if no matching level found, logic will return 0\n let maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;\n let bwFactor = config.abrBandWidthFactor;\n let bwUpFactor = config.abrBandWidthUpFactor;\n\n if (bufferStarvationDelay === 0) {\n // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test\n let bitrateTestDelay = this.bitrateTestDelay;\n if (bitrateTestDelay) {\n // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value\n // max video loading delay used in automatic start level selection :\n // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +\n // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )\n // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration\n const maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;\n maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;\n logger.trace(`bitrate test took ${Math.round(1000 * bitrateTestDelay)}ms, set first fragment max fetchDuration to ${Math.round(1000 * maxStarvationDelay)} ms`);\n // don't use conservative factor on bitrate test\n bwFactor = bwUpFactor = 1;\n }\n }\n bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor, levels);\n return Math.max(bestLevel, 0);\n }\n }\n\n _findBestLevel (currentLevel, currentFragDuration, currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor, levels) {\n for (let i = maxAutoLevel; i >= minAutoLevel; i--) {\n let levelInfo = levels[i];\n\n if (!levelInfo) {\n continue;\n }\n\n const levelDetails = levelInfo.details;\n const avgDuration = levelDetails ? levelDetails.totalduration / levelDetails.fragments.length : currentFragDuration;\n const live = levelDetails ? levelDetails.live : false;\n\n let adjustedbw;\n // follow algorithm captured from stagefright :\n // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp\n // Pick the highest bandwidth stream below or equal to estimated bandwidth.\n // consider only 80% of the available bandwidth, but if we are switching up,\n // be even more conservative (70%) to avoid overestimating and immediately\n // switching back.\n if (i <= currentLevel) {\n adjustedbw = bwFactor * currentBw;\n } else {\n adjustedbw = bwUpFactor * currentBw;\n }\n\n const bitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate;\n const fetchDuration = bitrate * avgDuration / adjustedbw;\n\n logger.trace(`level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: ${i}/${Math.round(adjustedbw)}/${bitrate}/${avgDuration}/${maxFetchDuration}/${fetchDuration}`);\n // if adjusted bw is greater than level bitrate AND\n if (adjustedbw > bitrate &&\n // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches\n // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...\n // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that _findBestLevel will return -1\n (!fetchDuration || (live && !this.bitrateTestDelay) || fetchDuration < maxFetchDuration)) {\n // as we are looping from highest to lowest, this will return the best achievable quality level\n return i;\n }\n }\n // not enough time budget even with quality level 0 ... rebuffering might happen\n return -1;\n }\n\n set nextAutoLevel (nextLevel) {\n this._nextAutoLevel = nextLevel;\n }\n}\n\nexport default AbrController;\n","/*\n * Buffer Controller\n */\n\nimport Events from '../events';\nimport EventHandler from '../event-handler';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { getMediaSource } from '../utils/mediasource-helper';\n\nimport { TrackSet } from '../types/track';\nimport { Segment } from '../types/segment';\nimport { BufferControllerConfig } from '../config';\n\n// Add extension properties to SourceBuffers from the DOM API.\ntype ExtendedSourceBuffer = SourceBuffer & {\n ended?: boolean\n};\n\ntype SourceBufferName = 'video' | 'audio';\ntype SourceBuffers = Partial<Record<SourceBufferName, ExtendedSourceBuffer>>;\n\ninterface SourceBufferFlushRange {\n start: number;\n end: number;\n type: SourceBufferName\n}\n\nconst MediaSource = getMediaSource();\n\nclass BufferController extends EventHandler {\n // the value that we have set mediasource.duration to\n // (the actual duration may be tweaked slighly by the browser)\n private _msDuration: number | null = null;\n // the value that we want to set mediaSource.duration to\n private _levelDuration: number | null = null;\n // the target duration of the current media playlist\n private _levelTargetDuration: number = 10;\n // current stream state: true - for live broadcast, false - for VoD content\n private _live: boolean | null = null;\n // cache the self generated object url to detect hijack of video tag\n private _objectUrl: string | null = null;\n\n // signals that the sourceBuffers need to be flushed\n private _needsFlush: boolean = false;\n\n // signals that mediaSource should have endOfStream called\n private _needsEos: boolean = false;\n\n private config: BufferControllerConfig;\n\n // this is optional because this property is removed from the class sometimes\n public audioTimestampOffset?: number;\n\n // The number of BUFFER_CODEC events received before any sourceBuffers are created\n public bufferCodecEventsExpected: number = 0;\n\n // The total number of BUFFER_CODEC events received\n private _bufferCodecEventsTotal: number = 0;\n\n // A reference to the attached media element\n public media: HTMLMediaElement | null = null;\n\n // A reference to the active media source\n public mediaSource: MediaSource | null = null;\n\n // List of pending segments to be appended to source buffer\n public segments: Segment[] = [];\n\n public parent?: string;\n\n // A guard to see if we are currently appending to the source buffer\n public appending: boolean = false;\n\n // counters\n public appended: number = 0;\n public appendError: number = 0;\n public flushBufferCounter: number = 0;\n\n public tracks: TrackSet = {};\n public pendingTracks: TrackSet = {};\n public sourceBuffer: SourceBuffers = {};\n public flushRange: SourceBufferFlushRange[] = [];\n\n constructor (hls: any) {\n super(hls,\n Events.MEDIA_ATTACHING,\n Events.MEDIA_DETACHING,\n Events.MANIFEST_PARSED,\n Events.BUFFER_RESET,\n Events.BUFFER_APPENDING,\n Events.BUFFER_CODECS,\n Events.BUFFER_EOS,\n Events.BUFFER_FLUSHING,\n Events.LEVEL_PTS_UPDATED,\n Events.LEVEL_UPDATED);\n\n this.config = hls.config;\n }\n\n destroy () {\n EventHandler.prototype.destroy.call(this);\n }\n\n onLevelPtsUpdated (data: { 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, audio: boolean, video: boolean }) {\n // in case of alt audio (where all tracks have urls) 2 BUFFER_CODECS events will be triggered, one per stream controller\n // sourcebuffers will be created all at once when the expected nb of tracks will be reached\n // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller\n // it will contain the expected nb of source buffers, no need to compute it\n let codecEvents: number = 2;\n if (data.audio && !data.video || !data.altAudio) {\n codecEvents = 1;\n }\n this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;\n\n logger.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`);\n }\n\n onMediaAttaching (data: { media: HTMLMediaElement }) {\n let media = this.media = data.media;\n if (media && MediaSource) {\n // setup the media source\n let ms = this.mediaSource = new MediaSource();\n // Media Source listeners\n ms.addEventListener('sourceopen', this._onMediaSourceOpen);\n ms.addEventListener('sourceended', this._onMediaSourceEnded);\n ms.addEventListener('sourceclose', this._onMediaSourceClose);\n // link video and media Source\n media.src = window.URL.createObjectURL(ms);\n // cache the locally generated object url\n this._objectUrl = media.src;\n }\n }\n\n onMediaDetaching () {\n logger.log('media source detaching');\n let ms = this.mediaSource;\n if (ms) {\n if (ms.readyState === 'open') {\n try {\n // endOfStream could trigger exception if any sourcebuffer is in updating state\n // we don't really care about checking sourcebuffer state here,\n // as we are anyway detaching the MediaSource\n // let's just avoid this exception to propagate\n ms.endOfStream();\n } catch (err) {\n logger.warn(`onMediaDetaching:${err.message} while calling endOfStream`);\n }\n }\n ms.removeEventListener('sourceopen', this._onMediaSourceOpen);\n ms.removeEventListener('sourceended', this._onMediaSourceEnded);\n ms.removeEventListener('sourceclose', this._onMediaSourceClose);\n\n // Detach properly the MediaSource from the HTMLMediaElement as\n // suggested in https://github.com/w3c/media-source/issues/53.\n if (this.media) {\n if (this._objectUrl) {\n window.URL.revokeObjectURL(this._objectUrl);\n }\n\n // clean up video tag src only if it's our own url. some external libraries might\n // hijack the video tag and change its 'src' without destroying the Hls instance first\n if (this.media.src === this._objectUrl) {\n this.media.removeAttribute('src');\n this.media.load();\n } else {\n logger.warn('media.src was changed by a third party - skip cleanup');\n }\n }\n\n this.mediaSource = null;\n this.media = null;\n this._objectUrl = null;\n this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;\n this.pendingTracks = {};\n this.tracks = {};\n this.sourceBuffer = {};\n this.flushRange = [];\n this.segments = [];\n this.appended = 0;\n }\n\n this.hls.trigger(Events.MEDIA_DETACHED);\n }\n\n checkPendingTracks () {\n let { bufferCodecEventsExpected, pendingTracks } = this;\n\n // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.\n // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after\n // data has been appended to existing ones.\n // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.\n const pendingTracksCount = Object.keys(pendingTracks).length;\n if ((pendingTracksCount && !bufferCodecEventsExpected) || pendingTracksCount === 2) {\n // ok, let's create them now !\n this.createSourceBuffers(pendingTracks);\n this.pendingTracks = {};\n // append any pending segments now !\n this.doAppending();\n }\n }\n\n private _onMediaSourceOpen = () => {\n logger.log('media source opened');\n this.hls.trigger(Events.MEDIA_ATTACHED, { media: this.media });\n let mediaSource = this.mediaSource;\n if (mediaSource) {\n // once received, don't listen anymore to sourceopen event\n mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);\n }\n this.checkPendingTracks();\n }\n\n private _onMediaSourceClose = () => {\n logger.log('media source closed');\n }\n\n private _onMediaSourceEnded = () => {\n logger.log('media source ended');\n }\n\n private _onSBUpdateEnd = () => {\n // update timestampOffset\n if (this.audioTimestampOffset && this.sourceBuffer.audio) {\n let audioBuffer = this.sourceBuffer.audio;\n\n logger.warn(`change mpeg audio timestamp offset from ${audioBuffer.timestampOffset} to ${this.audioTimestampOffset}`);\n audioBuffer.timestampOffset = this.audioTimestampOffset;\n delete this.audioTimestampOffset;\n }\n\n if (this._needsFlush) {\n this.doFlush();\n }\n\n if (this._needsEos) {\n this.checkEos();\n }\n\n this.appending = false;\n let parent = this.parent;\n // count nb of pending segments waiting for appending on this sourcebuffer\n let pending = this.segments.reduce((counter, segment) => (segment.parent === parent) ? counter + 1 : counter, 0);\n\n // this.sourceBuffer is better to use than media.buffered as it is closer to the PTS data from the fragments\n const timeRanges: Partial<Record<SourceBufferName, TimeRanges>> = {};\n const sbSet = this.sourceBuffer;\n for (let streamType in sbSet) {\n const sb = sbSet[streamType as SourceBufferName];\n if (!sb) {\n throw Error(`handling source buffer update end error: source buffer for ${streamType} uninitilized and unable to update buffered TimeRanges.`);\n }\n timeRanges[streamType as SourceBufferName] = sb.buffered;\n }\n\n this.hls.trigger(Events.BUFFER_APPENDED, { parent, pending, timeRanges });\n // don't append in flushing mode\n if (!this._needsFlush) {\n this.doAppending();\n }\n\n this.updateMediaElementDuration();\n\n // appending goes first\n if (pending === 0) {\n this.flushLiveBackBuffer();\n }\n }\n\n private _onSBUpdateError = (event: Event) => {\n logger.error('sourceBuffer error:', event);\n // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error\n // this error might not always be fatal (it is fatal if decode error is set, in that case\n // it will be followed by a mediaElement error ...)\n this.hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false });\n // we don't need to do more than that, as accordin to the spec, updateend will be fired just after\n }\n\n onBufferReset () {\n const sourceBuffer = this.sourceBuffer;\n for (let type in sourceBuffer) {\n const sb = sourceBuffer[type];\n try {\n if (sb) {\n if (this.mediaSource) {\n this.mediaSource.removeSourceBuffer(sb);\n }\n sb.removeEventListener('updateend', this._onSBUpdateEnd);\n sb.removeEventListener('error', this._onSBUpdateError);\n }\n } catch (err) {\n }\n }\n this.sourceBuffer = {};\n this.flushRange = [];\n this.segments = [];\n this.appended = 0;\n }\n\n onBufferCodecs (tracks: TrackSet) {\n // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks\n // if sourcebuffers already created, do nothing ...\n if (Object.keys(this.sourceBuffer).length) {\n return;\n }\n\n Object.keys(tracks).forEach(trackName => {\n this.pendingTracks[trackName] = tracks[trackName];\n });\n\n this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);\n if (this.mediaSource && this.mediaSource.readyState === 'open') {\n this.checkPendingTracks();\n }\n }\n\n createSourceBuffers (tracks: TrackSet) {\n const { sourceBuffer, mediaSource } = this;\n if (!mediaSource) {\n throw Error('createSourceBuffers called when mediaSource was null');\n }\n\n for (let trackName in tracks) {\n if (!sourceBuffer[trackName]) {\n let track = tracks[trackName as keyof TrackSet];\n if (!track) {\n throw Error(`source buffer exists for track ${trackName}, however track does not`);\n }\n // use levelCodec as first priority\n let codec = track.levelCodec || track.codec;\n let mimeType = `${track.container};codecs=${codec}`;\n logger.log(`creating sourceBuffer(${mimeType})`);\n try {\n let sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);\n sb.addEventListener('updateend', this._onSBUpdateEnd);\n sb.addEventListener('error', this._onSBUpdateError);\n this.tracks[trackName] = {\n buffer: sb,\n codec: codec,\n id: track.id,\n container: track.container,\n levelCodec: track.levelCodec\n };\n } catch (err) {\n logger.error(`error while trying to add sourceBuffer:${err.message}`);\n this.hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType: mimeType });\n }\n }\n }\n this.hls.trigger(Events.BUFFER_CREATED, { tracks: this.tracks });\n }\n\n onBufferAppending (data: Segment) {\n if (!this._needsFlush) {\n if (!this.segments) {\n this.segments = [ data ];\n } else {\n this.segments.push(data);\n }\n\n this.doAppending();\n }\n }\n\n // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()\n // an undefined data.type will mark all buffers as EOS.\n onBufferEos (data: { type?: SourceBufferName }) {\n for (const type in this.sourceBuffer) {\n if (!data.type || data.type === type) {\n const sb = this.sourceBuffer[type as SourceBufferName];\n if (sb && !sb.ended) {\n sb.ended = true;\n logger.log(`${type} sourceBuffer now EOS`);\n }\n }\n }\n\n this.checkEos();\n }\n\n // if all source buffers are marked as ended, signal endOfStream() to MediaSource.\n checkEos () {\n const { sourceBuffer, mediaSource } = this;\n if (!mediaSource || mediaSource.readyState !== 'open') {\n this._needsEos = false;\n return;\n }\n\n for (let type in sourceBuffer) {\n const sb = sourceBuffer[type as SourceBufferName];\n if (!sb) continue;\n\n if (!sb.ended) {\n return;\n }\n\n if (sb.updating) {\n this._needsEos = true;\n return;\n }\n }\n\n logger.log('all media data are available, signal endOfStream() to MediaSource and stop loading fragment');\n // Notify the media element that it now has all of the media data\n try {\n mediaSource.endOfStream();\n } catch (e) {\n logger.warn('exception while calling mediaSource.endOfStream()');\n }\n this._needsEos = false;\n }\n\n onBufferFlushing (data: { startOffset: number, endOffset: number, type?: SourceBufferName }) {\n if (data.type) {\n this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type });\n } else {\n this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: 'video' });\n this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: 'audio' });\n }\n\n // attempt flush immediately\n this.flushBufferCounter = 0;\n this.doFlush();\n }\n\n flushLiveBackBuffer () {\n // clear back buffer for live only\n if (!this._live) {\n return;\n }\n\n const liveBackBufferLength = this.config.liveBackBufferLength;\n if (!isFinite(liveBackBufferLength) || liveBackBufferLength < 0) {\n return;\n }\n\n if (!this.media) {\n logger.error('flushLiveBackBuffer called without attaching media');\n return;\n }\n\n const currentTime = this.media.currentTime;\n const sourceBuffer = this.sourceBuffer;\n const bufferTypes = Object.keys(sourceBuffer);\n const targetBackBufferPosition = currentTime - Math.max(liveBackBufferLength, this._levelTargetDuration);\n\n for (let index = bufferTypes.length - 1; index >= 0; index--) {\n const bufferType = bufferTypes[index];\n const sb = sourceBuffer[bufferType as SourceBufferName];\n if (sb) {\n const buffered = sb.buffered;\n // when target buffer start exceeds actual buffer start\n if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {\n // remove buffer up until current time minus minimum back buffer length (removing buffer too close to current\n // time will lead to playback freezing)\n // credits for level target duration - https://github.com/videojs/http-streaming/blob/3132933b6aa99ddefab29c10447624efd6fd6e52/src/segment-loader.js#L91\n if (this.removeBufferRange(bufferType, sb, 0, targetBackBufferPosition)) {\n this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, { bufferEnd: targetBackBufferPosition });\n }\n }\n }\n }\n }\n\n onLevelUpdated ({ details }: { details: { totalduration: number, targetduration?: number, averagetargetduration?: number, live: boolean, fragments: any[] } }) {\n if (details.fragments.length > 0) {\n this._levelDuration = details.totalduration + details.fragments[0].start;\n this._levelTargetDuration = details.averagetargetduration || details.targetduration || 10;\n this._live = details.live;\n this.updateMediaElementDuration();\n }\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.LEVELS_UPDATED,\n Event.BUFFER_CODECS,\n Event.MEDIA_DETACHING);\n\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.firstLevel = null;\n this.levels = [];\n this.media = null;\n this.restrictedLevels = [];\n this.timer = null;\n this.clientRect = null;\n }\n\n destroy () {\n if (this.hls.config.capLevelToPlayerSize) {\n this.media = null;\n this.clientRect = null;\n this.stopCapping();\n }\n }\n\n onFpsDropLevelCapping (data) {\n // Don't add a restricted level more than once\n if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {\n this.restrictedLevels.push(data.droppedLevel);\n }\n }\n\n onMediaAttaching (data) {\n this.media = data.media instanceof window.HTMLVideoElement ? data.media : null;\n }\n\n onManifestParsed (data) {\n const hls = this.hls;\n this.restrictedLevels = [];\n this.levels = data.levels;\n this.firstLevel = data.firstLevel;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // Start capping immediately if the manifest has signaled video codecs\n this.startCapping();\n }\n }\n\n // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted\n // to the first level\n onBufferCodecs (data) {\n const hls = this.hls;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // If the manifest did not signal a video codec capping has been deferred until we're certain video is present\n this.startCapping();\n }\n }\n\n onLevelsUpdated (data) {\n this.levels = data.levels;\n }\n\n onMediaDetaching () {\n this.stopCapping();\n }\n\n detectPlayerSize () {\n if (this.media) {\n let levelsLength = this.levels ? this.levels.length : 0;\n if (levelsLength) {\n const hls = this.hls;\n hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1);\n if (hls.autoLevelCapping > this.autoLevelCapping) {\n // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch\n // usually happen when the user go to the fullscreen mode.\n hls.streamController.nextLevelSwitch();\n }\n this.autoLevelCapping = hls.autoLevelCapping;\n }\n }\n }\n\n /*\n * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)\n */\n getMaxLevel (capLevelIndex) {\n if (!this.levels) {\n return -1;\n }\n\n const validLevels = this.levels.filter((level, index) =>\n CapLevelController.isLevelAllowed(index, this.restrictedLevels) && index <= capLevelIndex\n );\n\n this.clientRect = null;\n return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);\n }\n\n startCapping () {\n if (this.timer) {\n // Don't reset capping if started twice; this can happen if the manifest signals a video codec\n return;\n }\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.hls.firstLevel = this.getMaxLevel(this.firstLevel);\n clearInterval(this.timer);\n this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);\n this.detectPlayerSize();\n }\n\n stopCapping () {\n this.restrictedLevels = [];\n this.firstLevel = null;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n if (this.timer) {\n this.timer = clearInterval(this.timer);\n this.timer = null;\n }\n }\n\n getDimensions () {\n if (this.clientRect) {\n return this.clientRect;\n }\n const media = this.media;\n const boundsRect = {\n width: 0,\n height: 0\n };\n\n if (media) {\n const clientRect = media.getBoundingClientRect();\n boundsRect.width = clientRect.width;\n boundsRect.height = clientRect.height;\n if (!boundsRect.width && !boundsRect.height) {\n // When the media element has no width or height (equivalent to not being in the DOM),\n // then use its width and height attributes (media.width, media.height)\n boundsRect.width = clientRect.right - clientRect.left || media.width || 0;\n boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;\n }\n }\n this.clientRect = boundsRect;\n return boundsRect;\n }\n\n get mediaWidth () {\n return this.getDimensions().width * CapLevelController.contentScaleFactor;\n }\n\n get mediaHeight () {\n return this.getDimensions().height * CapLevelController.contentScaleFactor;\n }\n\n static get contentScaleFactor () {\n let pixelRatio = 1;\n try {\n pixelRatio = window.devicePixelRatio;\n } catch (e) {}\n return pixelRatio;\n }\n\n static isLevelAllowed (level, restrictedLevels = []) {\n return restrictedLevels.indexOf(level) === -1;\n }\n\n static getMaxLevelByMediaSize (levels, width, height) {\n if (!levels || (levels && !levels.length)) {\n return -1;\n }\n\n // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next\n // to determine whether we've chosen the greatest bandwidth for the media's dimensions\n const atGreatestBandiwdth = (curLevel, nextLevel) => {\n if (!nextLevel) {\n return true;\n }\n\n return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;\n };\n\n // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to\n // the max level\n let maxLevelIndex = levels.length - 1;\n\n for (let i = 0; i < levels.length; i += 1) {\n const level = levels[i];\n if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {\n maxLevelIndex = i;\n break;\n }\n }\n\n return maxLevelIndex;\n }\n}\n\nexport default CapLevelController;\n","/*\n * FPS Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { logger } from '../utils/logger';\n\nconst { performance } = window;\n\nclass FPSController extends EventHandler {\n constructor (hls) {\n super(hls, Event.MEDIA_ATTACHING);\n }\n\n destroy () {\n if (this.timer) {\n clearInterval(this.timer);\n }\n\n this.isVideoPlaybackQualityAvailable = false;\n }\n\n onMediaAttaching (data) {\n const config = this.hls.config;\n if (config.capLevelOnFPSDrop) {\n const video = this.video = data.media instanceof window.HTMLVideoElement ? data.media : null;\n if (typeof video.getVideoPlaybackQuality === 'function') {\n this.isVideoPlaybackQualityAvailable = true;\n }\n\n clearInterval(this.timer);\n this.timer = setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);\n }\n }\n\n checkFPS (video, decodedFrames, droppedFrames) {\n let currentTime = performance.now();\n if (decodedFrames) {\n if (this.lastTime) {\n let currentPeriod = currentTime - this.lastTime,\n currentDropped = droppedFrames - this.lastDroppedFrames,\n currentDecoded = decodedFrames - this.lastDecodedFrames,\n droppedFPS = 1000 * currentDropped / currentPeriod,\n hls = this.hls;\n hls.trigger(Event.FPS_DROP, { currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames });\n if (droppedFPS > 0) {\n // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));\n if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {\n let currentLevel = hls.currentLevel;\n logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);\n if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {\n currentLevel = currentLevel - 1;\n hls.trigger(Event.FPS_DROP_LEVEL_CAPPING, { level: currentLevel, droppedLevel: hls.currentLevel });\n hls.autoLevelCapping = currentLevel;\n hls.streamController.nextLevelSwitch();\n }\n }\n }\n }\n this.lastTime = currentTime;\n this.lastDroppedFrames = droppedFrames;\n this.lastDecodedFrames = decodedFrames;\n }\n }\n\n checkFPSInterval () {\n const video = this.video;\n if (video) {\n if (this.isVideoPlaybackQualityAvailable) {\n let videoPlaybackQuality = video.getVideoPlaybackQuality();\n this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);\n } else {\n this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);\n }\n }\n }\n}\n\nexport default FPSController;\n","/**\n * XHR based logger\n*/\n\nimport { logger } from '../utils/logger';\n\nclass XhrLoader {\n constructor (config) {\n if (config && config.xhrSetup) {\n this.xhrSetup = config.xhrSetup;\n }\n }\n\n destroy () {\n this.abort();\n this.loader = null;\n }\n\n abort () {\n let loader = this.loader;\n if (loader && loader.readyState !== 4) {\n this.stats.aborted = true;\n loader.abort();\n }\n\n window.clearTimeout(this.requestTimeout);\n this.requestTimeout = null;\n window.clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n }\n\n load (context, config, callbacks) {\n this.context = context;\n this.config = config;\n this.callbacks = callbacks;\n this.stats = { trequest: window.performance.now(), retry: 0 };\n this.retryDelay = config.retryDelay;\n this.loadInternal();\n }\n\n loadInternal () {\n let xhr, context = this.context;\n xhr = this.loader = new window.XMLHttpRequest();\n\n let stats = this.stats;\n stats.tfirst = 0;\n stats.loaded = 0;\n const xhrSetup = this.xhrSetup;\n\n try {\n if (xhrSetup) {\n try {\n xhrSetup(xhr, context.url);\n } catch (e) {\n // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader(\"Content-Language\", \"test\");}\n // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN\n xhr.open('GET', context.url, true);\n xhrSetup(xhr, context.url);\n }\n }\n if (!xhr.readyState) {\n xhr.open('GET', context.url, true);\n }\n } catch (e) {\n // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n this.callbacks.onError({ code: xhr.status, text: e.message }, context, xhr);\n return;\n }\n\n if (context.rangeEnd) {\n xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));\n }\n\n xhr.onreadystatechange = this.readystatechange.bind(this);\n xhr.onprogress = this.loadprogress.bind(this);\n xhr.responseType = context.responseType;\n\n // setup timeout before we perform request\n this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), this.config.timeout);\n xhr.send();\n }\n\n readystatechange (event) {\n let xhr = event.currentTarget,\n readyState = xhr.readyState,\n stats = this.stats,\n context = this.context,\n config = this.config;\n\n // don't proceed if xhr has been aborted\n if (stats.aborted) {\n return;\n }\n\n // >= HEADERS_RECEIVED\n if (readyState >= 2) {\n // clear xhr timeout and rearm it if readyState less than 4\n window.clearTimeout(this.requestTimeout);\n if (stats.tfirst === 0) {\n stats.tfirst = Math.max(window.performance.now(), stats.trequest);\n }\n\n if (readyState === 4) {\n let status = xhr.status;\n // http status between 200 to 299 are all successful\n if (status >= 200 && status < 300) {\n stats.tload = Math.max(stats.tfirst, window.performance.now());\n let data, len;\n if (context.responseType === 'arraybuffer') {\n data = xhr.response;\n len = data.byteLength;\n } else {\n data = xhr.responseText;\n len = data.length;\n }\n stats.loaded = stats.total = len;\n let response = { url: xhr.responseURL, data: data };\n this.callbacks.onSuccess(response, stats, context, xhr);\n } else {\n // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error\n if (stats.retry >= config.maxRetry || (status >= 400 && status < 499)) {\n logger.error(`${status} while loading ${context.url}`);\n this.callbacks.onError({ code: status, text: xhr.statusText }, context, xhr);\n } else {\n // retry\n logger.warn(`${status} while loading ${context.url}, retrying in ${this.retryDelay}...`);\n // aborts and resets internal state\n this.destroy();\n // schedule retry\n this.retryTimeout = window.setTimeout(this.loadInternal.bind(this), this.retryDelay);\n // set exponential backoff\n this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);\n stats.retry++;\n }\n }\n } else {\n // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet\n this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), config.timeout);\n }\n }\n }\n\n loadtimeout () {\n logger.warn(`timeout while loading ${this.context.url}`);\n this.callbacks.onTimeout(this.stats, this.context, null);\n }\n\n loadprogress (event) {\n let xhr = event.currentTarget,\n stats = this.stats;\n\n stats.loaded = event.loaded;\n if (event.lengthComputable) {\n stats.total = event.total;\n }\n\n let onProgress = this.callbacks.onProgress;\n if (onProgress) {\n // third arg is to provide on progress data\n onProgress(stats, this.context, null, xhr);\n }\n }\n}\n\nexport default XhrLoader;\n","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 { ElementaryStreamTypes } from '../loader/fragment';\nimport BaseStreamController, { State } from './base-stream-controller';\nimport { MAX_START_GAP_JUMP } from './gap-controller';\nimport { fragmentWithinToleranceTest } from './fragment-finders';\n\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 this.waitingVideoCC = 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 main: ${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 const videoBuffer = this.videoBuffer ? this.videoBuffer : this.media;\n const maxBufferHole = pos < config.maxBufferHole ? Math.max(MAX_START_GAP_JUMP, config.maxBufferHole) : config.maxBufferHole;\n const bufferInfo = BufferHelper.bufferInfo(media, pos, maxBufferHole);\n const mainBufferInfo = BufferHelper.bufferInfo(videoBuffer, pos, maxBufferHole);\n const bufferLen = bufferInfo.len;\n let bufferEnd = bufferInfo.end;\n const 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 const maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength);\n const maxBufLen = Math.max(maxConfigBuffer, mainBufferInfo.len);\n const audioSwitch = this.audioSwitch;\n const 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\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(bufferEnd, maxFragLookUpTolerance, fragNext)) {\n foundFrag = fragNext;\n } else {\n foundFrag = BinarySearch.search(fragments, (frag) => fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, frag));\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 if (this.fragmentTracker.getState(frag) !== FragmentState.OK) {\n logger.log(`SN just loaded, load next one: ${frag.sn}`);\n }\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 // 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 logger.log(`Loading ${frag.sn}, cc: ${frag.cc} of [${trackDetails.startSN} ,${trackDetails.endSN}],track ${trackId}, ${\n this.loadedmetadata ? 'currentTime' : 'nextLoadPosition'\n }: ${pos}, bufferEnd: ${bufferEnd.toFixed(3)}`);\n\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 // 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 (this.initPTS[waitingFragCC] !== undefined) {\n this.waitingFragment = null;\n this.state = State.FRAG_LOADING;\n this.onFragLoaded(waitingFrag);\n } else if (this.videoTrackCC !== this.waitingVideoCC) {\n // Drop waiting fragment if videoTrackCC has changed since waitingFragment was set and initPTS was not found\n logger.log(`Waiting fragment cc (${waitingFragCC}) cancelled because video is at cc ${this.videoTrackCC}`);\n this.clearWaitingFragment();\n } else {\n // Drop waiting fragment if an earlier fragment is needed\n const bufferInfo = BufferHelper.bufferInfo(this.mediaBuffer, this.media.currentTime, config.maxBufferHole);\n const waitingFragmentAtPosition = fragmentWithinToleranceTest(bufferInfo.end, config.maxFragLookUpTolerance, waitingFrag.frag);\n if (waitingFragmentAtPosition < 0) {\n logger.log(`Waiting fragment cc (${waitingFragCC}) @ ${waitingFrag.frag.start} cancelled because another fragment at ${bufferInfo.end} is needed`);\n this.clearWaitingFragment();\n }\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 clearWaitingFragment () {\n const waitingFrag = this.waitingFragment;\n if (waitingFrag) {\n this.fragmentTracker.removeFragment(waitingFrag.frag);\n this.waitingFragment = null;\n this.waitingVideoCC = null;\n this.state = State.IDLE;\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.clearWaitingFragment();\n this.state = State.PAUSED;\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 curDetails = track.details,\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 || (curDetails && curDetails.live)) {\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 (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 cc ${cc}, waiting for video PTS before demuxing audio frag ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);\n this.waitingFragment = data;\n this.waitingVideoCC = this.videoTrackCC;\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 const media = this.media;\n let appendOnBufferFlush = false;\n // Only flush audio from old audio tracks when PTS is known on new audio track\n if (this.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\nexport interface CuesInterface {\n newCue (track: TextTrack | null, startTime: number, endTime: number, captionScreen: CaptionScreen): VTTCue[]\n}\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 | null, startTime: number, endTime: number, captionScreen: CaptionScreen): VTTCue[] {\n const result: VTTCue[] = [];\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 result.push(cue);\n if (track) {\n track.addCue(cue);\n }\n }\n }\n return result;\n}\n","import OutputFilter from './output-filter';\nimport { logger } from '../utils/logger';\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\nconst 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 */\nconst 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\nconst NR_ROWS = 15;\nconst NR_COLS = 100;\n// Tables to look up row from PAC data\nconst rowsLowCh1 = { 0x11: 1, 0x12: 3, 0x15: 5, 0x16: 7, 0x17: 9, 0x10: 11, 0x13: 12, 0x14: 14 };\nconst rowsHighCh1 = { 0x11: 2, 0x12: 4, 0x15: 6, 0x16: 8, 0x17: 10, 0x13: 13, 0x14: 15 };\nconst rowsLowCh2 = { 0x19: 1, 0x1A: 3, 0x1D: 5, 0x1E: 7, 0x1F: 9, 0x18: 11, 0x1B: 12, 0x1C: 14 };\nconst rowsHighCh2 = { 0x19: 2, 0x1A: 4, 0x1D: 6, 0x1E: 8, 0x1F: 10, 0x1B: 13, 0x1C: 15 };\n\nconst backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];\n\nenum VerboseLevel {\n ERROR = 0,\n TEXT = 1,\n WARNING = 2,\n INFO = 2,\n DEBUG = 3,\n DATA = 3,\n}\n\nclass CaptionsLogger {\n public time: number | null = null;\n public verboseLevel: VerboseLevel = VerboseLevel.ERROR;\n\n log (severity: VerboseLevel, msg: string): void {\n if (this.verboseLevel >= severity) {\n logger.log(`${this.time} [${severity}] ${msg}`);\n }\n }\n}\n\nconst numArrayToHexArray = function (numArray: number[]): string[] {\n const 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 const attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];\n for (let i = 0; i < attribs.length; i++) {\n const 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\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 logger: CaptionsLogger;\n\n constructor (logger: CaptionsLogger) {\n this.chars = [];\n for (let i = 0; i < NR_COLS; i++) {\n this.chars.push(new StyledUnicodeChar());\n }\n\n this.logger = logger;\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 this.logger.log(VerboseLevel.DEBUG, 'Negative cursor position ' + this.pos);\n this.pos = 0;\n } else if (this.pos > NR_COLS) {\n this.logger.log(VerboseLevel.DEBUG, '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 const 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 const char = getCharForByte(byte);\n if (this.pos >= NR_COLS) {\n this.logger.log(VerboseLevel.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 const chars: string[] = [];\n let empty = true;\n for (let i = 0; i < NR_COLS; i++) {\n const 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 const 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: CaptionScreen | null;\n logger: CaptionsLogger;\n\n constructor (logger: CaptionsLogger) {\n this.rows = [];\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows.push(new Row(logger));\n } // Note that we use zero-based numbering (0-14)\n\n this.logger = logger;\n this.currRow = NR_ROWS - 1;\n this.nrRollUpRows = null;\n this.lastOutputScreen = 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 const row = this.rows[this.currRow];\n row.backSpace();\n }\n\n clearToEndOfRow () {\n const 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 const row = this.rows[this.currRow];\n row.insertChar(char);\n }\n\n setPen (styles: Partial<PenStyles>) {\n const row = this.rows[this.currRow];\n row.setPenStyles(styles);\n }\n\n moveCursor (relPos: number) {\n const row = this.rows[this.currRow];\n row.moveCursor(relPos);\n }\n\n setCursor (absPos: number) {\n this.logger.log(VerboseLevel.INFO, 'setCursor: ' + absPos);\n const row = this.rows[this.currRow];\n row.setCursor(absPos);\n }\n\n setPAC (pacData: PACData) {\n this.logger.log(VerboseLevel.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 const topRowIndex = this.currRow + 1 - (this.nrRollUpRows);\n // We only copy if the last position was already shown.\n // We use the cueStartTime value to check this.\n const lastOutputScreen = this.lastOutputScreen;\n if (lastOutputScreen) {\n const prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;\n const time = this.logger.time;\n if (prevLineTime && time !== null && prevLineTime < 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 const row = this.rows[this.currRow];\n if (pacData.indent !== null) {\n const indent = pacData.indent;\n const prevPos = Math.max(indent - 1, 0);\n row.setCursor(pacData.indent);\n pacData.color = row.chars[prevPos].penState.foreground;\n }\n const 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 this.logger.log(VerboseLevel.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 this.logger.log(VerboseLevel.DEBUG, 'roll_up but nrRollUpRows not set yet');\n return; // Not properly setup\n }\n this.logger.log(VerboseLevel.TEXT, this.getDisplayText());\n const topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n const topRow = this.rows.splice(topRowIndex, 1)[0];\n topRow.clear();\n this.rows.splice(this.currRow, 0, topRow);\n this.logger.log(VerboseLevel.INFO, 'Rolling up');\n // this.logger.log(VerboseLevel.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 const displayText: string[] = [];\n let text = '';\n let rowNr = -1;\n for (let i = 0; i < NR_ROWS; i++) {\n const 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 logger: CaptionsLogger;\n\n constructor (channelNumber: number, outputFilter: OutputFilter, logger: CaptionsLogger) {\n this.chNr = channelNumber;\n this.outputFilter = outputFilter;\n this.mode = null;\n this.verbose = 0;\n this.displayedMemory = new CaptionScreen(logger);\n this.nonDisplayedMemory = new CaptionScreen(logger);\n this.lastOutputScreen = new CaptionScreen(logger);\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 this.logger = logger;\n }\n\n reset () {\n this.mode = null;\n this.displayedMemory.reset();\n this.nonDisplayedMemory.reset();\n this.lastOutputScreen.reset();\n this.outputFilter.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 this.logger.log(VerboseLevel.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 const screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';\n this.logger.log(VerboseLevel.INFO, screen + ': ' + this.writeScreen.getDisplayText(true));\n if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {\n this.logger.log(VerboseLevel.TEXT, 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));\n this.outputDataUpdate();\n }\n }\n\n ccRCL () { // Resume Caption Loading (switch mode to Pop On)\n this.logger.log(VerboseLevel.INFO, 'RCL - Resume Caption Loading');\n this.setMode('MODE_POP-ON');\n }\n\n ccBS () { // BackSpace\n this.logger.log(VerboseLevel.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 this.logger.log(VerboseLevel.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 this.logger.log(VerboseLevel.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 this.logger.log(VerboseLevel.INFO, 'FON - Flash On');\n this.writeScreen.setPen({ flash: true });\n }\n\n ccRDC () { // Resume Direct Captioning (switch mode to PaintOn)\n this.logger.log(VerboseLevel.INFO, 'RDC - Resume Direct Captioning');\n this.setMode('MODE_PAINT-ON');\n }\n\n ccTR () { // Text Restart in text mode (not supported, however)\n this.logger.log(VerboseLevel.INFO, 'TR');\n this.setMode('MODE_TEXT');\n }\n\n ccRTD () { // Resume Text Display in Text mode (not supported, however)\n this.logger.log(VerboseLevel.INFO, 'RTD');\n this.setMode('MODE_TEXT');\n }\n\n ccEDM () { // Erase Displayed Memory\n this.logger.log(VerboseLevel.INFO, 'EDM - Erase Displayed Memory');\n this.displayedMemory.reset();\n this.outputDataUpdate(true);\n }\n\n ccCR () { // Carriage Return\n this.logger.log(VerboseLevel.INFO, 'CR - Carriage Return');\n this.writeScreen.rollUp();\n this.outputDataUpdate(true);\n }\n\n ccENM () { // Erase Non-Displayed Memory\n this.logger.log(VerboseLevel.INFO, 'ENM - Erase Non-displayed Memory');\n this.nonDisplayedMemory.reset();\n }\n\n ccEOC () { // End of Caption (Flip Memories)\n this.logger.log(VerboseLevel.INFO, 'EOC - End Of Caption');\n if (this.mode === 'MODE_POP-ON') {\n const tmp = this.displayedMemory;\n this.displayedMemory = this.nonDisplayedMemory;\n this.nonDisplayedMemory = tmp;\n this.writeScreen = this.nonDisplayedMemory;\n this.logger.log(VerboseLevel.TEXT, 'DISP: ' + this.displayedMemory.getDisplayText());\n }\n this.outputDataUpdate(true);\n }\n\n ccTO (nrCols: number) { // Tab Offset 1,2, or 3 columns\n this.logger.log(VerboseLevel.INFO, 'TO(' + nrCols + ') - Tab Offset');\n this.writeScreen.moveCursor(nrCols);\n }\n\n ccMIDROW (secondByte: number) { // Parse MIDROW command\n const styles: Partial<PenStyles> = { flash: false };\n styles.underline = secondByte % 2 === 1;\n styles.italics = secondByte >= 0x2e;\n if (!styles.italics) {\n const colorIndex = Math.floor(secondByte / 2) - 0x10;\n const colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];\n styles.foreground = colors[colorIndex];\n } else {\n styles.foreground = 'white';\n }\n this.logger.log(VerboseLevel.INFO, 'MIDROW: ' + JSON.stringify(styles));\n this.writeScreen.setPen(styles);\n }\n\n outputDataUpdate (dispatch: boolean = false) {\n const time = this.logger.time;\n if (time === 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 = time;\n } else {\n if (!this.displayedMemory.equals(this.lastOutputScreen)) {\n this.outputFilter.newCue(this.cueStartTime!, time, this.lastOutputScreen);\n if (dispatch && this.outputFilter.dispatchCue) {\n this.outputFilter.dispatchCue();\n }\n\n this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;\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\ntype SupportedField = 1 | 3;\n\ntype Channels = 0 | 1 | 2; // Will be 1 or 2 when parsing captions\n\ntype CmdHistory = {\n a: number | null,\n b: number | null\n};\n\nclass Cea608Parser {\n channels: Array<Cea608Channel | null>;\n currentChannel: Channels = 0;\n cmdHistory: CmdHistory;\n logger: CaptionsLogger;\n\n constructor (field: SupportedField, out1: OutputFilter, out2: OutputFilter) {\n const logger = new CaptionsLogger();\n this.channels = [\n null,\n new Cea608Channel(field, out1, logger),\n new Cea608Channel(field + 1, out2, logger)\n ];\n this.cmdHistory = createCmdHistory();\n this.logger = logger;\n }\n\n getHandler (channel: number) {\n return (this.channels[channel] as Cea608Channel).getHandler();\n }\n\n setHandler (channel: number, newHandler: OutputFilter) {\n (this.channels[channel] as Cea608Channel).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 (time: number | null, byteList: number[]) {\n let cmdFound: boolean;\n let a: number;\n let b: number;\n let charsFound: number[] | boolean | null = false;\n\n this.logger.time = time;\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 continue;\n } else {\n this.logger.log(VerboseLevel.DATA, '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');\n }\n\n cmdFound = this.parseCmd(a, b);\n\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 const currChNr = this.currentChannel;\n if (currChNr && currChNr > 0) {\n const channel = this.channels[currChNr] as Cea608Channel;\n channel.insertChars(charsFound);\n } else {\n this.logger.log(VerboseLevel.WARNING, 'No channel found yet. TEXT-MODE?');\n }\n }\n }\n if (!cmdFound && !charsFound) {\n this.logger.log(VerboseLevel.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) {\n const { cmdHistory } = this;\n const cond1 = (a === 0x14 || a === 0x1C || a === 0x15 || a === 0x1D) && (b >= 0x20 && b <= 0x2F);\n const cond2 = (a === 0x17 || a === 0x1F) && (b >= 0x21 && b <= 0x23);\n if (!(cond1 || cond2)) {\n return false;\n }\n\n if (hasCmdRepeated(a, b, cmdHistory)) {\n setLastCmd(null, null, cmdHistory);\n this.logger.log(VerboseLevel.DEBUG, 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');\n return true;\n }\n\n const chNr = (a === 0x14 || a === 0x15 || a === 0x17) ? 1 : 2;\n const channel = this.channels[chNr] as Cea608Channel;\n\n if (a === 0x14 || a === 0x15 || a === 0x1C || a === 0x1D) {\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 setLastCmd(a, b, cmdHistory);\n this.currentChannel = chNr;\n return true;\n }\n\n /**\n * Parse midrow styling command\n * @returns {Boolean}\n */\n parseMidrow (a: number, b: number) {\n let chNr: number = 0;\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.currentChannel) {\n this.logger.log(VerboseLevel.ERROR, 'Mismatch channel in midrow parsing');\n return false;\n }\n const channel = this.channels[chNr];\n if (!channel) {\n return false;\n }\n channel.ccMIDROW(b);\n this.logger.log(VerboseLevel.DEBUG, 'MIDROW (' + numArrayToHexArray([a, b]) + ')');\n return true;\n }\n return false;\n }\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 row: number;\n const cmdHistory = this.cmdHistory;\n\n const case1 = ((a >= 0x11 && a <= 0x17) || (a >= 0x19 && a <= 0x1F)) && (b >= 0x40 && b <= 0x7F);\n const case2 = (a === 0x10 || a === 0x18) && (b >= 0x40 && b <= 0x5F);\n if (!(case1 || case2)) {\n return false;\n }\n\n if (hasCmdRepeated(a, b, cmdHistory)) {\n setLastCmd(null, null, cmdHistory);\n return true; // Repeated commands are dropped (once)\n }\n\n const chNr: Channels = (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 const channel = this.channels[chNr];\n if (!channel) {\n return false;\n }\n channel.setPAC(this.interpretPAC(row, b));\n setLastCmd(a, b, cmdHistory);\n this.currentChannel = 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 const 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: Channels;\n let charCodes: number[] | null = null;\n let 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 this.logger.log(VerboseLevel.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 const hexCodes = numArrayToHexArray(charCodes);\n this.logger.log(VerboseLevel.DEBUG, 'Char codes = ' + hexCodes.join(','));\n setLastCmd(a, b, this.cmdHistory);\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 const case1 = (a === 0x10 || a === 0x18) && (b >= 0x20 && b <= 0x2f);\n const case2 = (a === 0x17 || a === 0x1f) && (b >= 0x2d && b <= 0x2f);\n if (!(case1 || case2)) {\n return false;\n }\n let index: number;\n const bkgData: Partial<PenStyles> = {};\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 const chNr: Channels = (a <= 0x17) ? 1 : 2;\n const channel: Cea608Channel = this.channels[chNr] as Cea608Channel;\n channel.setBkgData(bkgData);\n setLastCmd(a, b, this.cmdHistory);\n return true;\n }\n\n /**\n * Reset state of parser and its channels.\n */\n reset () {\n for (let i = 0; i < Object.keys(this.channels).length; i++) {\n const channel = this.channels[i];\n if (channel) {\n channel.reset();\n }\n }\n this.cmdHistory = createCmdHistory();\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 const channel = this.channels[i];\n if (channel) {\n channel.cueSplitAtTime(t);\n }\n }\n }\n}\n\nfunction setLastCmd (a: number | null, b: number | null, cmdHistory: CmdHistory) {\n cmdHistory.a = a;\n cmdHistory.b = b;\n}\n\nfunction hasCmdRepeated (a: number, b: number, cmdHistory: CmdHistory) {\n return cmdHistory.a === a && cmdHistory.b === b;\n}\n\nfunction createCmdHistory (): CmdHistory {\n return {\n a: null,\n b: null\n };\n}\n\nexport default Cea608Parser;\n","import { CaptionScreen } from './cea-608-parser';\nimport type TimelineController from '../controller/timeline-controller';\n\nexport default class OutputFilter {\n private timelineController: TimelineController;\n private cueRanges: Array<[number, number]> = [];\n private trackName: string;\n private startTime: number | null = null;\n private endTime: number | null = null;\n private screen: CaptionScreen | null = null;\n\n constructor (timelineController: TimelineController, trackName: string) {\n this.timelineController = timelineController;\n this.trackName = trackName;\n }\n\n dispatchCue () {\n if (this.startTime === null) {\n return;\n }\n\n this.timelineController.addCues(this.trackName, this.startTime, this.endTime as number, this.screen as CaptionScreen, this.cueRanges);\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 reset () {\n this.cueRanges = [];\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';\nimport { CuesInterface } from '../utils/cues';\nimport { MediaPlaylist } from '../types/media-playlist';\n\ntype TrackProperties = {\n label: string,\n languageCode: string,\n media?: MediaPlaylist\n};\n\ntype NonNativeCaptionsTrack = {\n _id?: string,\n label: string,\n kind: string,\n default: boolean,\n closedCaptions?: MediaPlaylist,\n subtitleTrack?: MediaPlaylist\n};\n\ntype VTTCCs = {\n ccOffset: number,\n presentationOffset: number,\n [key: number]: {\n start: number,\n prevCC: number,\n new: boolean\n }\n};\n\nclass TimelineController extends EventHandler {\n private media: HTMLMediaElement | null = null;\n private config: HlsConfig;\n private enabled: boolean = true;\n private Cues: CuesInterface;\n private textTracks: Array<TextTrack> = [];\n private tracks: Array<MediaPlaylist> = [];\n private initPTS: Array<number> = [];\n private unparsedVttFrags: Array<{ frag: Fragment, payload: ArrayBuffer }> = [];\n private captionsTracks: Record<string, TextTrack> = {};\n private nonNativeCaptionsTracks: Record<string, NonNativeCaptionsTrack> = {};\n private captionsProperties: {\n textTrack1: TrackProperties\n textTrack2: TrackProperties\n textTrack3: TrackProperties\n textTrack4: TrackProperties\n };\n private readonly cea608Parser1!: Cea608Parser;\n private readonly cea608Parser2!: Cea608Parser;\n private lastSn: number = -1;\n private prevCC: number = -1;\n private vttCCs: VTTCCs = newVTTCCs();\n\n constructor (hls) {\n super(hls,\n 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 textTrack3: {\n label: this.config.captionsTextTrack3Label,\n languageCode: this.config.captionsTextTrack3LanguageCode\n },\n textTrack4: {\n label: this.config.captionsTextTrack4Label,\n languageCode: this.config.captionsTextTrack4LanguageCode\n }\n };\n\n if (this.config.enableCEA708Captions) {\n const channel1 = new OutputFilter(this, 'textTrack1');\n const channel2 = new OutputFilter(this, 'textTrack2');\n const channel3 = new OutputFilter(this, 'textTrack3');\n const channel4 = new OutputFilter(this, 'textTrack4');\n this.cea608Parser1 = new Cea608Parser(1, channel1, channel2);\n this.cea608Parser2 = new Cea608Parser(3, channel3, channel4);\n }\n }\n\n addCues (trackName: string, startTime: number, endTime: number, screen: CaptionScreen, cueRanges: Array<[number, number]>) {\n // skip cues which overlap more than 50% with previously parsed time ranges\n let merged = false;\n for (let i = cueRanges.length; i--;) {\n let cueRange = cueRanges[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 cueRanges.push([startTime, endTime]);\n }\n\n if (this.config.renderTextTracksNatively) {\n this.Cues.newCue(this.captionsTracks[trackName], startTime, endTime, screen);\n } else {\n const cues = this.Cues.newCue(null, startTime, endTime, screen);\n this.hls.trigger(Event.CUES_PARSED, { type: 'captions', cues, track: trackName });\n }\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 if (this.config.renderTextTracksNatively) {\n this.createNativeTrack(trackName);\n } else {\n this.createNonNativeTrack(trackName);\n }\n }\n\n createNativeTrack (trackName: string) {\n if (this.captionsTracks[trackName]) {\n return;\n }\n const { captionsProperties, captionsTracks, media } = this;\n const { label, languageCode } = captionsProperties[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 createNonNativeTrack (trackName: string) {\n if (this.nonNativeCaptionsTracks[trackName]) {\n return;\n }\n // Create a list of a single track for the provider to consume\n const trackProperties: TrackProperties = this.captionsProperties[trackName];\n if (!trackProperties) {\n return;\n }\n const label = trackProperties.label as string;\n const track = {\n _id: trackName,\n label,\n kind: 'captions',\n default: trackProperties.media ? !!trackProperties.media.default : false,\n closedCaptions: trackProperties.media\n };\n this.nonNativeCaptionsTracks[trackName] = track;\n this.hls.trigger(Event.NON_NATIVE_TEXT_TRACKS_FOUND, { tracks: [track] });\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 this.nonNativeCaptionsTracks = {};\n }\n\n onManifestLoading () {\n this.lastSn = -1; // Detect discontiguity in fragment parsing\n this.prevCC = -1;\n this.vttCCs = newVTTCCs(); // Detect discontinuity in subtitle manifests\n this._cleanTracks();\n this.tracks = [];\n this.captionsTracks = {};\n this.nonNativeCaptionsTracks = {};\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<MediaPlaylist>, captions: Array<MediaPlaylist> }) {\n this.textTracks = [];\n this.unparsedVttFrags = this.unparsedVttFrags || [];\n this.initPTS = [];\n if (this.cea608Parser1 && this.cea608Parser2) {\n this.cea608Parser1.reset();\n this.cea608Parser2.reset();\n }\n\n if (this.config.enableWebVTT) {\n const tracks = data.subtitles || [];\n const sameTracks = this.tracks && tracks && this.tracks.length === tracks.length;\n this.tracks = data.subtitles || [];\n\n if (this.config.renderTextTracksNatively) {\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 } else if (!sameTracks && this.tracks && this.tracks.length) {\n // Create a list of tracks for the provider to consume\n const tracksList = this.tracks.map((track) => {\n return {\n label: track.name,\n kind: track.type.toLowerCase(),\n default: track.default,\n subtitleTrack: track\n };\n });\n this.hls.trigger(Event.NON_NATIVE_TEXT_TRACKS_FOUND, { tracks: tracksList });\n }\n }\n\n if (this.config.enableCEA708Captions && data.captions) {\n data.captions.forEach(captionsTrack => {\n const instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId as string);\n if (!instreamIdMatch) {\n return;\n }\n const trackName = `textTrack${instreamIdMatch[1]}`;\n const trackProperties: TrackProperties = this.captionsProperties[trackName];\n if (!trackProperties) {\n return;\n }\n trackProperties.label = captionsTrack.name;\n if (captionsTrack.lang) { // optional attribute\n trackProperties.languageCode = captionsTrack.lang;\n }\n trackProperties.media = captionsTrack;\n });\n }\n }\n\n onFragLoaded (data: { frag: Fragment, payload: ArrayBuffer }) {\n const { frag, payload } = data;\n const { cea608Parser1, cea608Parser2, 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 (cea608Parser1 && cea608Parser2) {\n cea608Parser1.reset();\n cea608Parser2.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: ArrayBuffer) {\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, (cues) => {\n if (this.config.renderTextTracksNatively) {\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 // Because we check if the mode is diabled, we can force check `cues` below. They can't be null.\n if (currentTrack.mode === 'disabled') {\n hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });\n return;\n }\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 } else {\n let trackId = this.tracks[frag.level].default ? 'default' : 'subtitles' + frag.level;\n hls.trigger(Event.CUES_PARSED, { type: 'subtitles', cues: cues, track: trackId });\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 const { cea608Parser1, cea608Parser2 } = this;\n if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {\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 cea608Parser1.addData(data.samples[i].pts, ccdatas[0]);\n cea608Parser2.addData(data.samples[i].pts, ccdatas[1]);\n }\n }\n }\n\n extractCea608Data (byteArray: Uint8Array): number[][] {\n const count = byteArray[0] & 31;\n let position = 2;\n const actualCCBytes: number[][] = [[], []];\n\n for (let j = 0; j < count; j++) {\n const tmpByte = byteArray[position++];\n const ccbyte1 = 0x7F & byteArray[position++];\n const ccbyte2 = 0x7F & byteArray[position++];\n const ccValid = (4 & tmpByte) !== 0;\n const 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[ccType].push(ccbyte1);\n actualCCBytes[ccType].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\nfunction newVTTCCs (): VTTCCs {\n return {\n ccOffset: 0,\n presentationOffset: 0,\n 0: {\n start: 0,\n prevCC: -1,\n new: false\n }\n };\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 || !this.hls.config.renderTextTracksNatively) {\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 startLoad () {\n this.stopLoad();\n this.state = State.IDLE;\n\n // Check if we already have a track with necessary details to load fragments\n const currentTrack = this.tracks[this.currentTrackId];\n if (currentTrack && currentTrack.details) {\n this.setInterval(TICK_INTERVAL);\n this.tick();\n }\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\n if (this.fragCurrent && this.fragCurrent.loader) {\n this.fragCurrent.loader.abort();\n }\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 this.fragPrevious = null;\n super.stopLoad();\n }\n\n _getBuffered () {\n return this.tracksBuffered[this.currentTrackId] || [];\n }\n\n onMediaSeeking () {\n if (this.fragCurrent) {\n const currentTime = this.media ? this.media.currentTime : 0;\n const tolerance = this.config.maxFragLookUpTolerance;\n const fragStartOffset = this.fragCurrent.start - tolerance;\n const fragEndOffset = this.fragCurrent.start + this.fragCurrent.duration + tolerance;\n\n // check if position will be out of currently loaded frag range after seeking : if out, cancel frag load, if in, don't do anything\n if (currentTime < fragStartOffset || currentTime > fragEndOffset) {\n if (this.fragCurrent.loader) {\n this.fragCurrent.loader.abort();\n }\n\n this.fragmentTracker.removeFragment(this.fragCurrent);\n this.fragCurrent = null;\n this.fragPrevious = null;\n\n // switch to IDLE state to load new fragment\n this.state = State.IDLE;\n\n // speed up things\n this.tick();\n }\n }\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 { DRMSystemOptions, 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 (\n audioCodecs: string[],\n videoCodecs: string[],\n drmSystemOptions: DRMSystemOptions\n): 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 audioCapabilities: [], // { contentType: 'audio/mp4; codecs=\"mp4a.40.2\"' }\n videoCapabilities: [] // { contentType: 'video/mp4; codecs=\"avc1.42E01E\"' }\n };\n\n audioCodecs.forEach((codec) => {\n baseConfig.audioCapabilities!.push({\n contentType: `audio/mp4; codecs=\"${codec}\"`,\n robustness: drmSystemOptions.audioRobustness || ''\n });\n });\n videoCodecs.forEach((codec) => {\n baseConfig.videoCapabilities!.push({\n contentType: `video/mp4; codecs=\"${codec}\"`,\n robustness: drmSystemOptions.videoRobustness || ''\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 (\n keySystem: KeySystems,\n audioCodecs: string[],\n videoCodecs: string[],\n drmSystemOptions: DRMSystemOptions\n): MediaKeySystemConfiguration[] {\n switch (keySystem) {\n case KeySystems.WIDEVINE:\n return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions);\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 private _drmSystemOptions: DRMSystemOptions;\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 private mediaKeysPromise: Promise<MediaKeys> | null = null;\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 this._drmSystemOptions = hls.config.drmSystemOptions;\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 // This can throw, but is caught in event handler callpath\n const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this._drmSystemOptions);\n\n logger.log('Requesting encrypted media key-system access');\n\n // expecting interface like window.navigator.requestMediaKeySystemAccess\n const keySystemAccessPromise = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);\n\n this.mediaKeysPromise = keySystemAccessPromise.then((mediaKeySystemAccess) =>\n this._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess));\n\n keySystemAccessPromise.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): Promise<MediaKeys> {\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 const mediaKeysPromise = Promise.resolve().then(() => 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 return mediaKeys;\n });\n\n mediaKeysPromise.catch((err) => {\n logger.error('Failed to create media-keys:', err);\n });\n\n return mediaKeysPromise;\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 e {MediaEncryptedEvent}\n */\n private _onMediaEncrypted = (e: MediaEncryptedEvent) => {\n logger.log(`Media is encrypted using \"${e.initDataType}\" init data type`);\n\n if (!this.mediaKeysPromise) {\n logger.error('Fatal: Media is encrypted but no CDM access or no keys have been requested');\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 const finallySetKeyAndStartSession = (mediaKeys) => {\n if (!this._media) {\n return;\n }\n this._attemptSetMediaKeys(mediaKeys);\n this._generateRequestWithPreferredKeySession(e.initDataType, e.initData);\n };\n\n // Could use `Promise.finally` but some Promise polyfills are missing it\n this.mediaKeysPromise.then(finallySetKeyAndStartSession).catch(finallySetKeyAndStartSession);\n }\n\n /**\n * @private\n */\n private _attemptSetMediaKeys (mediaKeys?: MediaKeys) {\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 const media = this._media;\n const mediaKeysList = this._mediaKeysList;\n if (!media) {\n return;\n }\n media.removeEventListener('encrypted', this._onMediaEncrypted);\n this._media = null;\n this._mediaKeysList = [];\n // Close all sessions and remove media keys from the video element.\n Promise.all(mediaKeysList.map((mediaKeysListItem) => {\n if (mediaKeysListItem.mediaKeysSession) {\n return mediaKeysListItem.mediaKeysSession.close().catch(() => {\n // Ignore errors when closing the sessions. Closing a session that\n // generated no key requests will throw an error.\n });\n }\n })).then(() => {\n return media.setMediaKeys(null);\n }).catch(() => {\n // Ignore any failures while removing media keys from the video element.\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 DRMSystemOptions = {\n audioRobustness?: string,\n videoRobustness?: string,\n}\n\nexport type EMEControllerConfig = {\n licenseXhrSetup?: (xhr: XMLHttpRequest, url: string) => void,\n emeEnabled: boolean,\n widevineLicenseUrl?: string,\n drmSystemOptions: DRMSystemOptions,\n requestMediaKeySystemAccessFunc: MediaKeyFunc | null,\n};\n\ntype FragmentLoaderConfig = {\n fLoader: any, // TODO(typescript-loader): Once Loader is typed fill this in\n\n fragLoadingTimeOut: number,\n fragLoadingMaxRetry: number,\n fragLoadingRetryDelay: number,\n fragLoadingMaxRetryTimeout: number,\n};\n\ntype FPSControllerConfig = {\n capLevelOnFPSDrop: boolean,\n fpsDroppedMonitoringPeriod: number,\n fpsDroppedMonitoringThreshold: number,\n};\n\ntype LevelControllerConfig = {\n startLevel?: number\n};\n\ntype MP4RemuxerConfig = {\n stretchShortVideoTrack: boolean,\n maxAudioFramesDrift: number,\n};\n\ntype PlaylistLoaderConfig = {\n pLoader: any, // TODO(typescript-loader): Once Loader is typed fill this in\n\n manifestLoadingTimeOut: number,\n manifestLoadingMaxRetry: number,\n manifestLoadingRetryDelay: number,\n manifestLoadingMaxRetryTimeout: number,\n\n levelLoadingTimeOut: number,\n levelLoadingMaxRetry: number,\n levelLoadingRetryDelay: number,\n levelLoadingMaxRetryTimeout: number\n};\n\ntype StreamControllerConfig = {\n autoStartLoad: boolean,\n startPosition: number,\n defaultAudioCodec?: string,\n initialLiveManifestSize: number,\n maxBufferLength: number,\n maxBufferSize: number,\n maxBufferHole: number,\n\n lowBufferWatchdogPeriod: number,\n highBufferWatchdogPeriod: number,\n nudgeOffset: number,\n nudgeMaxRetry: number,\n maxFragLookUpTolerance: number,\n liveSyncDurationCount: number,\n liveMaxLatencyDurationCount: number,\n liveSyncDuration?: number,\n liveMaxLatencyDuration?: number,\n maxMaxBufferLength: number,\n\n startFragPrefetch: boolean,\n testBandwidth: boolean\n};\n\ntype TimelineControllerConfig = {\n cueHandler: Cues.CuesInterface,\n enableCEA708Captions: boolean,\n enableWebVTT: boolean,\n captionsTextTrack1Label: string,\n captionsTextTrack1LanguageCode: string,\n captionsTextTrack2Label: string,\n captionsTextTrack2LanguageCode: string,\n captionsTextTrack3Label: string,\n captionsTextTrack3LanguageCode: string,\n captionsTextTrack4Label: string,\n captionsTextTrack4LanguageCode: string,\n renderTextTracksNatively: boolean,\n};\n\ntype TSDemuxerConfig = {\n forceKeyFrameOnDiscontinuity: boolean,\n};\n\nexport type HlsConfig =\n {\n debug: boolean,\n enableWorker: boolean,\n enableSoftwareAES: boolean,\n minAutoBitrate: number,\n loader: any, // TODO(typescript-xhrloader): Type once XHR is done\n xhrSetup?: (xhr: XMLHttpRequest, url: string) => void,\n\n // Alt Audio\n audioStreamController?: any, // TODO(typescript-audiostreamcontroller): Type once file is done\n audioTrackController?: any, // TODO(typescript-audiotrackcontroller): Type once file is done\n // Subtitle\n subtitleStreamController?: any, // TODO(typescript-subtitlestreamcontroller): Type once file is done\n subtitleTrackController?: any, // TODO(typescript-subtitletrackcontroller): Type once file is done\n timelineController?: any, // TODO(typescript-timelinecontroller): Type once file is done\n // EME\n emeController?: typeof EMEController,\n\n abrController: any, // TODO(typescript-abrcontroller): Type once file is done\n bufferController: typeof BufferController,\n capLevelController: any, // TODO(typescript-caplevelcontroller): Type once file is done\n fpsController: any, // TODO(typescript-fpscontroller): Type once file is done\n } &\n ABRControllerConfig &\n BufferControllerConfig &\n CapLevelControllerConfig &\n EMEControllerConfig &\n FPSControllerConfig &\n FragmentLoaderConfig &\n LevelControllerConfig &\n MP4RemuxerConfig &\n PlaylistLoaderConfig &\n StreamControllerConfig &\n TimelineControllerConfig &\n TSDemuxerConfig;\n\n// If possible, keep hlsDefaultConfig shallow\n// It is cloned whenever a new Hls instance is created, by keeping the config\n// shallow the properties are cloned, and we don't end up manipulating the default\nexport const hlsDefaultConfig: HlsConfig = {\n autoStartLoad: true, // used by stream-controller\n startPosition: -1, // used by stream-controller\n defaultAudioCodec: void 0, // used by stream-controller\n debug: false, // used by logger\n capLevelOnFPSDrop: false, // used by fps-controller\n capLevelToPlayerSize: false, // used by cap-level-controller\n initialLiveManifestSize: 1, // used by stream-controller\n maxBufferLength: 30, // used by stream-controller\n maxBufferSize: 60 * 1000 * 1000, // used by stream-controller\n maxBufferHole: 0.5, // used by stream-controller\n\n lowBufferWatchdogPeriod: 0.5, // used by stream-controller\n highBufferWatchdogPeriod: 3, // used by stream-controller\n nudgeOffset: 0.1, // used by stream-controller\n nudgeMaxRetry: 3, // used by stream-controller\n maxFragLookUpTolerance: 0.25, // used by stream-controller\n liveSyncDurationCount: 3, // used by stream-controller\n liveMaxLatencyDurationCount: Infinity, // used by stream-controller\n liveSyncDuration: void 0, // used by stream-controller\n liveMaxLatencyDuration: void 0, // used by stream-controller\n liveDurationInfinity: false, // used by buffer-controller\n liveBackBufferLength: Infinity, // used by buffer-controller\n maxMaxBufferLength: 600, // used by stream-controller\n enableWorker: true, // used by demuxer\n enableSoftwareAES: true, // used by decrypter\n manifestLoadingTimeOut: 10000, // used by playlist-loader\n manifestLoadingMaxRetry: 1, // used by playlist-loader\n manifestLoadingRetryDelay: 1000, // used by playlist-loader\n manifestLoadingMaxRetryTimeout: 64000, // used by playlist-loader\n startLevel: void 0, // used by level-controller\n levelLoadingTimeOut: 10000, // used by playlist-loader\n levelLoadingMaxRetry: 4, // used by playlist-loader\n levelLoadingRetryDelay: 1000, // used by playlist-loader\n levelLoadingMaxRetryTimeout: 64000, // used by playlist-loader\n fragLoadingTimeOut: 20000, // used by fragment-loader\n fragLoadingMaxRetry: 6, // used by fragment-loader\n fragLoadingRetryDelay: 1000, // used by fragment-loader\n fragLoadingMaxRetryTimeout: 64000, // used by fragment-loader\n startFragPrefetch: false, // used by stream-controller\n fpsDroppedMonitoringPeriod: 5000, // used by fps-controller\n fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller\n appendErrorMaxRetry: 3, // used by buffer-controller\n loader: XhrLoader,\n // loader: FetchLoader,\n fLoader: void 0, // used by fragment-loader\n pLoader: void 0, // used by playlist-loader\n xhrSetup: void 0, // used by xhr-loader\n licenseXhrSetup: void 0, // used by eme-controller\n // fetchSetup: void 0,\n abrController: AbrController,\n bufferController: BufferController,\n capLevelController: CapLevelController,\n fpsController: FPSController,\n stretchShortVideoTrack: false, // used by mp4-remuxer\n maxAudioFramesDrift: 1, // used by mp4-remuxer\n forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer\n abrEwmaFastLive: 3, // used by abr-controller\n abrEwmaSlowLive: 9, // used by abr-controller\n abrEwmaFastVoD: 3, // used by abr-controller\n abrEwmaSlowVoD: 9, // used by abr-controller\n abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller\n abrBandWidthFactor: 0.95, // used by abr-controller\n abrBandWidthUpFactor: 0.7, // used by abr-controller\n abrMaxWithRealBitrate: false, // used by abr-controller\n maxStarvationDelay: 4, // used by abr-controller\n maxLoadingDelay: 4, // used by abr-controller\n minAutoBitrate: 0, // used by hls\n emeEnabled: false, // used by eme-controller\n widevineLicenseUrl: void 0, // used by eme-controller\n drmSystemOptions: {}, // used by eme-controller\n requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess, // used by eme-controller\n testBandwidth: true,\n\n // Dynamic Modules\n ...timelineConfig(),\n subtitleStreamController: (__USE_SUBTITLES__) ? SubtitleStreamController : void 0,\n subtitleTrackController: (__USE_SUBTITLES__) ? SubtitleTrackController : void 0,\n timelineController: (__USE_SUBTITLES__) ? TimelineController : void 0,\n audioStreamController: (__USE_ALT_AUDIO__) ? AudioStreamController : void 0,\n audioTrackController: (__USE_ALT_AUDIO__) ? AudioTrackController : void 0,\n emeController: (__USE_EME_DRM__) ? EMEController : void 0\n};\n\nfunction timelineConfig (): TimelineControllerConfig {\n return {\n cueHandler: Cues, // used by timeline-controller\n enableCEA708Captions: __USE_SUBTITLES__, // used by timeline-controller\n enableWebVTT: __USE_SUBTITLES__, // used by timeline-controller\n captionsTextTrack1Label: 'English', // used by timeline-controller\n captionsTextTrack1LanguageCode: 'en', // used by timeline-controller\n captionsTextTrack2Label: 'Spanish', // used by timeline-controller\n captionsTextTrack2LanguageCode: 'es', // used by timeline-controller\n captionsTextTrack3Label: 'Unknown CC', // used by timeline-controller\n captionsTextTrack3LanguageCode: '', // used by timeline-controller\n captionsTextTrack4Label: 'Unknown CC', // used by timeline-controller\n captionsTextTrack4LanguageCode: '', // used by timeline-controller\n renderTextTracksNatively: true\n };\n}\n","import * as URLToolkit from 'url-toolkit';\n\nimport {\n ErrorTypes,\n ErrorDetails\n} from './errors';\n\nimport PlaylistLoader from './loader/playlist-loader';\nimport FragmentLoader from './loader/fragment-loader';\nimport KeyLoader from './loader/key-loader';\n\nimport { FragmentTracker } from './controller/fragment-tracker';\nimport StreamController from './controller/stream-controller';\nimport LevelController from './controller/level-controller';\nimport ID3TrackController from './controller/id3-track-controller';\n\nimport { isSupported } from './is-supported';\nimport { logger, enableLogs } from './utils/logger';\nimport { hlsDefaultConfig, HlsConfig } from './config';\n\nimport HlsEvents from './events';\n\nimport { Observer } from './observer';\n\n/**\n * @module Hls\n * @class\n * @constructor\n */\nexport default class Hls extends Observer {\n public static defaultConfig?: HlsConfig;\n public config: HlsConfig;\n\n private _autoLevelCapping: number;\n private abrController: any;\n private capLevelController: any;\n private levelController: LevelController;\n private streamController: StreamController;\n private networkControllers: any[];\n private audioTrackController: any;\n private subtitleTrackController: any;\n private emeController: any;\n private coreComponents: any[];\n private media: HTMLMediaElement | null = null;\n private url: string | null = null;\n\n /**\n * @type {string}\n */\n static get version (): string {\n return __VERSION__;\n }\n\n /**\n * @type {boolean}\n */\n static isSupported (): boolean {\n return isSupported();\n }\n\n /**\n * @type {HlsEvents}\n */\n static get Events () {\n return HlsEvents;\n }\n\n /**\n * @type {HlsErrorTypes}\n */\n static get ErrorTypes () {\n return ErrorTypes;\n }\n\n /**\n * @type {HlsErrorDetails}\n */\n static get ErrorDetails () {\n return ErrorDetails;\n }\n\n /**\n * @type {HlsConfig}\n */\n static get DefaultConfig (): HlsConfig {\n if (!Hls.defaultConfig) {\n return hlsDefaultConfig;\n }\n\n return Hls.defaultConfig;\n }\n\n /**\n * @type {HlsConfig}\n */\n static set DefaultConfig (defaultConfig: HlsConfig) {\n Hls.defaultConfig = defaultConfig;\n }\n\n /**\n * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.\n *\n * @constructs Hls\n * @param {HlsConfig} config\n */\n constructor (userConfig: Partial<HlsConfig> = {}) {\n super();\n\n const defaultConfig = Hls.DefaultConfig;\n\n if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {\n throw new Error('Illegal hls.js config: don\\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');\n }\n\n // Shallow clone\n this.config = {\n ...defaultConfig,\n ...userConfig\n };\n\n const { config } = this;\n\n if (config.liveMaxLatencyDurationCount !== void 0 && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {\n throw new Error('Illegal hls.js config: \"liveMaxLatencyDurationCount\" must be gt \"liveSyncDurationCount\"');\n }\n\n if (config.liveMaxLatencyDuration !== void 0 && (config.liveSyncDuration === void 0 || config.liveMaxLatencyDuration <= config.liveSyncDuration)) {\n throw new Error('Illegal hls.js config: \"liveMaxLatencyDuration\" must be gt \"liveSyncDuration\"');\n }\n\n enableLogs(config.debug);\n\n this._autoLevelCapping = -1;\n\n // core controllers and network loaders\n\n /**\n * @member {AbrController} abrController\n */\n const abrController = this.abrController = new config.abrController(this); // eslint-disable-line new-cap\n const bufferController = new config.bufferController(this); // eslint-disable-line new-cap\n const capLevelController = this.capLevelController = new config.capLevelController(this); // eslint-disable-line new-cap\n const fpsController = new config.fpsController(this); // eslint-disable-line new-cap\n const playListLoader = new PlaylistLoader(this);\n const fragmentLoader = new FragmentLoader(this);\n const keyLoader = new KeyLoader(this);\n const id3TrackController = new ID3TrackController(this);\n\n // network controllers\n\n /**\n * @member {LevelController} levelController\n */\n const levelController = this.levelController = new LevelController(this);\n\n // FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important\n const fragmentTracker = new FragmentTracker(this);\n\n /**\n * @member {StreamController} streamController\n */\n const streamController = this.streamController = new StreamController(this, fragmentTracker);\n\n let networkControllers = [levelController, streamController];\n\n // optional audio stream controller\n /**\n * @var {ICoreComponent | Controller}\n */\n let Controller = config.audioStreamController;\n if (Controller) {\n networkControllers.push(new Controller(this, fragmentTracker));\n }\n\n /**\n * @member {INetworkController[]} networkControllers\n */\n this.networkControllers = networkControllers;\n\n /**\n * @var {ICoreComponent[]}\n */\n const coreComponents = [\n playListLoader,\n fragmentLoader,\n keyLoader,\n abrController,\n bufferController,\n capLevelController,\n fpsController,\n id3TrackController,\n fragmentTracker\n ];\n\n // optional audio track and subtitle controller\n Controller = config.audioTrackController;\n if (Controller) {\n const audioTrackController = new Controller(this);\n\n /**\n * @member {AudioTrackController} audioTrackController\n */\n this.audioTrackController = audioTrackController;\n coreComponents.push(audioTrackController);\n }\n\n Controller = config.subtitleTrackController;\n if (Controller) {\n const subtitleTrackController = new Controller(this);\n\n /**\n * @member {SubtitleTrackController} subtitleTrackController\n */\n this.subtitleTrackController = subtitleTrackController;\n networkControllers.push(subtitleTrackController);\n }\n\n Controller = config.emeController;\n if (Controller) {\n const emeController = new Controller(this);\n\n /**\n * @member {EMEController} emeController\n */\n this.emeController = emeController;\n coreComponents.push(emeController);\n }\n\n // optional subtitle controllers\n Controller = config.subtitleStreamController;\n if (Controller) {\n networkControllers.push(new Controller(this, fragmentTracker));\n }\n Controller = config.timelineController;\n if (Controller) {\n coreComponents.push(new Controller(this));\n }\n\n /**\n * @member {ICoreComponent[]}\n */\n this.coreComponents = coreComponents;\n }\n\n /**\n * Dispose of the instance\n */\n destroy () {\n logger.log('destroy');\n this.trigger(HlsEvents.DESTROYING);\n this.detachMedia();\n this.coreComponents.concat(this.networkControllers).forEach(component => {\n component.destroy();\n });\n this.url = null;\n this.removeAllListeners();\n this._autoLevelCapping = -1;\n }\n\n /**\n * Attach a media element\n * @param {HTMLMediaElement} media\n */\n attachMedia (media: HTMLMediaElement) {\n logger.log('attachMedia');\n this.media = media;\n this.trigger(HlsEvents.MEDIA_ATTACHING, { media: media });\n }\n\n /**\n * Detach from the media\n */\n detachMedia () {\n logger.log('detachMedia');\n this.trigger(HlsEvents.MEDIA_DETACHING);\n this.media = null;\n }\n\n /**\n * Set the source URL. Can be relative or absolute.\n * @param {string} url\n */\n loadSource (url: string) {\n url = URLToolkit.buildAbsoluteURL(window.location.href, url, { alwaysNormalize: true });\n logger.log(`loadSource:${url}`);\n this.url = url;\n // when attaching to a source URL, trigger a playlist load\n this.trigger(HlsEvents.MANIFEST_LOADING, { url: url });\n }\n\n /**\n * Start loading data from the stream source.\n * Depending on default config, client starts loading automatically when a source is set.\n *\n * @param {number} startPosition Set the start position to stream from\n * @default -1 None (from earliest point)\n */\n startLoad (startPosition: number = -1) {\n logger.log(`startLoad(${startPosition})`);\n this.networkControllers.forEach(controller => {\n controller.startLoad(startPosition);\n });\n }\n\n /**\n * Stop loading of any stream data.\n */\n stopLoad () {\n logger.log('stopLoad');\n this.networkControllers.forEach(controller => {\n controller.stopLoad();\n });\n }\n\n /**\n * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)\n */\n swapAudioCodec () {\n logger.log('swapAudioCodec');\n this.streamController.swapAudioCodec();\n }\n\n /**\n * When the media-element fails, this allows to detach and then re-attach it\n * as one call (convenience method).\n *\n * Automatic recovery of media-errors by this process is configurable.\n */\n recoverMediaError () {\n logger.log('recoverMediaError');\n let media = this.media;\n this.detachMedia();\n if (media) {\n this.attachMedia(media);\n }\n }\n\n /**\n * Remove a loaded level from the list of levels, or a level url in from a list of redundant level urls.\n * This can be used to remove a rendition or playlist url that errors frequently from the list of levels that a user\n * or hls.js can choose from.\n *\n * @param levelIndex {number} The quality level index to of the level to remove\n * @param urlId {number} The quality level url index in the case that fallback levels are available. Defaults to 0.\n */\n removeLevel (levelIndex, urlId = 0) {\n this.levelController.removeLevel(levelIndex, urlId);\n }\n\n /**\n * @type {QualityLevel[]}\n */\n // todo(typescript-levelController)\n get levels (): any[] {\n return this.levelController.levels;\n }\n\n /**\n * Index of quality level currently played\n * @type {number}\n */\n get currentLevel (): number {\n return this.streamController.currentLevel;\n }\n\n /**\n * Set quality level index immediately .\n * This will flush the current buffer to replace the quality asap.\n * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.\n * @param newLevel {number} -1 for automatic level selection\n */\n set currentLevel (newLevel: number) {\n logger.log(`set currentLevel:${newLevel}`);\n this.loadLevel = newLevel;\n this.streamController.immediateLevelSwitch();\n }\n\n /**\n * Index of next quality level loaded as scheduled by stream controller.\n * @type {number}\n */\n get nextLevel (): number {\n return this.streamController.nextLevel;\n }\n\n /**\n * Set quality level index for next loaded data.\n * This will switch the video quality asap, without interrupting playback.\n * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).\n * @type {number} -1 for automatic level selection\n */\n set nextLevel (newLevel: number) {\n logger.log(`set nextLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n this.streamController.nextLevelSwitch();\n }\n\n /**\n * Return the quality level of the currently or last (of none is loaded currently) segment\n * @type {number}\n */\n get loadLevel (): number {\n return this.levelController.level;\n }\n\n /**\n * Set quality level index for next loaded data in a conservative way.\n * This will switch the quality without flushing, but interrupt current loading.\n * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.\n * @type {number} newLevel -1 for automatic level selection\n */\n set loadLevel (newLevel: number) {\n logger.log(`set loadLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n }\n\n /**\n * get next quality level loaded\n * @type {number}\n */\n get nextLoadLevel (): number {\n return this.levelController.nextLoadLevel;\n }\n\n /**\n * Set quality level of next loaded segment in a fully \"non-destructive\" way.\n * Same as `loadLevel` but will wait for next switch (until current loading is done).\n * @type {number} level\n */\n set nextLoadLevel (level: number) {\n this.levelController.nextLoadLevel = level;\n }\n\n /**\n * Return \"first level\": like a default level, if not set,\n * falls back to index of first level referenced in manifest\n * @type {number}\n */\n get firstLevel (): number {\n return Math.max(this.levelController.firstLevel, this.minAutoLevel);\n }\n\n /**\n * Sets \"first-level\", see getter.\n * @type {number}\n */\n set firstLevel (newLevel: number) {\n logger.log(`set firstLevel:${newLevel}`);\n this.levelController.firstLevel = newLevel;\n }\n\n /**\n * Return start level (level of first fragment that will be played back)\n * if not overrided by user, first level appearing in manifest will be used as start level\n * if -1 : automatic start level selection, playback will start from level matching download bandwidth\n * (determined from download of first segment)\n * @type {number}\n */\n get startLevel (): number {\n return this.levelController.startLevel;\n }\n\n /**\n * set start level (level of first fragment that will be played back)\n * if not overrided by user, first level appearing in manifest will be used as start level\n * if -1 : automatic start level selection, playback will start from level matching download bandwidth\n * (determined from download of first segment)\n * @type {number} newLevel\n */\n set startLevel (newLevel: number) {\n logger.log(`set startLevel:${newLevel}`);\n // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel\n if (newLevel !== -1) {\n newLevel = Math.max(newLevel, this.minAutoLevel);\n }\n\n this.levelController.startLevel = newLevel;\n }\n\n /**\n * set dynamically set capLevelToPlayerSize against (`CapLevelController`)\n *\n * @type {boolean}\n */\n set capLevelToPlayerSize (shouldStartCapping: boolean) {\n const newCapLevelToPlayerSize = !!shouldStartCapping;\n\n if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {\n if (newCapLevelToPlayerSize) {\n this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.\n } else {\n this.capLevelController.stopCapping();\n this.autoLevelCapping = -1;\n this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.\n }\n\n this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;\n }\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n * @type {number}\n */\n get autoLevelCapping (): number {\n return this._autoLevelCapping;\n }\n\n /**\n * get bandwidth estimate\n * @type {number}\n */\n get bandwidthEstimate (): number {\n const bwEstimator = this.abrController._bwEstimator;\n return bwEstimator ? bwEstimator.getEstimate() : NaN;\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n * @type {number}\n */\n set autoLevelCapping (newLevel: number) {\n logger.log(`set autoLevelCapping:${newLevel}`);\n this._autoLevelCapping = newLevel;\n }\n\n /**\n * True when automatic level selection enabled\n * @type {boolean}\n */\n get autoLevelEnabled (): boolean {\n return (this.levelController.manualLevel === -1);\n }\n\n /**\n * Level set manually (if any)\n * @type {number}\n */\n get manualLevel (): number {\n return this.levelController.manualLevel;\n }\n\n /**\n * min level selectable in auto mode according to config.minAutoBitrate\n * @type {number}\n */\n get minAutoLevel (): number {\n const { levels, config: { minAutoBitrate } } = this;\n const len = levels ? levels.length : 0;\n\n for (let i = 0; i < len; i++) {\n const levelNextBitrate = levels[i].realBitrate\n ? Math.max(levels[i].realBitrate, levels[i].bitrate)\n : levels[i].bitrate;\n\n if (levelNextBitrate > minAutoBitrate) {\n return i;\n }\n }\n\n return 0;\n }\n\n /**\n * max level selectable in auto mode according to autoLevelCapping\n * @type {number}\n */\n get maxAutoLevel (): number {\n const { levels, autoLevelCapping } = this;\n\n let maxAutoLevel;\n if (autoLevelCapping === -1 && levels && levels.length) {\n maxAutoLevel = levels.length - 1;\n } else {\n maxAutoLevel = autoLevelCapping;\n }\n\n return maxAutoLevel;\n }\n\n /**\n * next automatically selected quality level\n * @type {number}\n */\n get nextAutoLevel (): number {\n // ensure next auto level is between min and max auto level\n return Math.min(Math.max(this.abrController.nextAutoLevel, this.minAutoLevel), this.maxAutoLevel);\n }\n\n /**\n * this setter is used to force next auto level.\n * this is useful to force a switch down in auto mode:\n * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)\n * forced value is valid for one fragment. upon succesful frag loading at forced level,\n * this value will be resetted to -1 by ABR controller.\n * @type {number}\n */\n set nextAutoLevel (nextLevel: number) {\n this.abrController.nextAutoLevel = Math.max(this.minAutoLevel, nextLevel);\n }\n\n /**\n * @type {AudioTrack[]}\n */\n // todo(typescript-audioTrackController)\n get audioTracks (): any[] {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTracks : [];\n }\n\n /**\n * index of the selected audio track (index in audio track lists)\n * @type {number}\n */\n get audioTrack (): number {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTrack : -1;\n }\n\n /**\n * selects an audio track, based on its index in audio track lists\n * @type {number}\n */\n set audioTrack (audioTrackId: number) {\n const audioTrackController = this.audioTrackController;\n if (audioTrackController) {\n audioTrackController.audioTrack = audioTrackId;\n }\n }\n\n /**\n * @type {Seconds}\n */\n get liveSyncPosition (): number {\n return this.streamController.liveSyncPosition;\n }\n\n /**\n * get alternate subtitle tracks list from playlist\n * @type {SubtitleTrack[]}\n */\n // todo(typescript-subtitleTrackController)\n get subtitleTracks (): any[] {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];\n }\n\n /**\n * index of the selected subtitle track (index in subtitle track lists)\n * @type {number}\n */\n get subtitleTrack (): number {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;\n }\n\n /**\n * select an subtitle track, based on its index in subtitle track lists\n * @type {number}\n */\n set subtitleTrack (subtitleTrackId: number) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleTrack = subtitleTrackId;\n }\n }\n\n /**\n * @type {boolean}\n */\n get subtitleDisplay (): boolean {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;\n }\n\n /**\n * Enable/disable subtitle display rendering\n * @type {boolean}\n */\n set subtitleDisplay (value: boolean) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleDisplay = value;\n }\n }\n}\n","import { getMediaSource } from './utils/mediasource-helper';\n\nexport function isSupported (): boolean {\n const mediaSource = getMediaSource();\n if (!mediaSource) {\n return false;\n }\n const sourceBuffer = self.SourceBuffer || (self as any).WebKitSourceBuffer as SourceBuffer;\n const isTypeSupported = mediaSource &&\n typeof mediaSource.isTypeSupported === 'function' &&\n mediaSource.isTypeSupported('video/mp4; codecs=\"avc1.42E01E,mp4a.40.2\"');\n\n // if SourceBuffer is exposed ensure its API is valid\n // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible\n const sourceBufferValidAPI = !sourceBuffer ||\n (sourceBuffer.prototype &&\n typeof sourceBuffer.prototype.appendBuffer === 'function' &&\n typeof sourceBuffer.prototype.remove === 'function');\n return !!isTypeSupported && !!sourceBufferValidAPI;\n}\n"],"sourceRoot":""}
|