Files
xin-school-taro/build/chunk/842.js
T
2026-07-10 20:14:43 +08:00

1 line
416 KiB
JavaScript

"use strict";(self.webpackJsonp=self.webpackJsonp||[]).push([[842],{"8842":function(t,r,a){var i=a(766),o=a(7453),l=a(1760),u=a(1729),c=a(610),d=a(76),h=a(5935),g=a(6014),v=a(7038),m=a(6830),y=a(8652);function getDefaultExportFromCjs(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var p,T,E,k,S,L={"exports":{}};p=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,T=/^(?=([^\/?#]*))\1([^]*)$/,E=/(?:\/|^)\.(?=\/)/g,k=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,L.exports=S={"buildAbsoluteURL":function buildAbsoluteURL(t,r,a){if(a=a||{},t=t.trim(),!(r=r.trim())){if(!a.alwaysNormalize)return t;var i=S.parseURL(t);if(!i)throw new Error("Error trying to parse base URL.");return i.path=S.normalizePath(i.path),S.buildURLFromParts(i)}var o=S.parseURL(r);if(!o)throw new Error("Error trying to parse relative URL.");if(o.scheme)return a.alwaysNormalize?(o.path=S.normalizePath(o.path),S.buildURLFromParts(o)):r;var l=S.parseURL(t);if(!l)throw new Error("Error trying to parse base URL.");if(!l.netLoc&&l.path&&"/"!==l.path[0]){var u=T.exec(l.path);l.netLoc=u[1],l.path=u[2]}l.netLoc&&!l.path&&(l.path="/");var c={"scheme":l.scheme,"netLoc":o.netLoc,"path":null,"params":o.params,"query":o.query,"fragment":o.fragment};if(!o.netLoc&&(c.netLoc=l.netLoc,"/"!==o.path[0]))if(o.path){var d=l.path,h=d.substring(0,d.lastIndexOf("/")+1)+o.path;c.path=S.normalizePath(h)}else c.path=l.path,o.params||(c.params=l.params,o.query||(c.query=l.query));return null===c.path&&(c.path=a.alwaysNormalize?S.normalizePath(o.path):o.path),S.buildURLFromParts(c)},"parseURL":function parseURL(t){var r=p.exec(t);return r?{"scheme":r[1]||"","netLoc":r[2]||"","path":r[3]||"","params":r[4]||"","query":r[5]||"","fragment":r[6]||""}:null},"normalizePath":function normalizePath(t){for(t=t.split("").reverse().join("").replace(E,"");t.length!==(t=t.replace(k,"")).length;);return t.split("").reverse().join("")},"buildURLFromParts":function buildURLFromParts(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}};var A=L.exports;function ownKeys(t,r){var a=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);r&&(i=i.filter((function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable}))),a.push.apply(a,i)}return a}function _objectSpread2(t){for(var r=1;r<arguments.length;r++){var a=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(a),!0).forEach((function(r){_defineProperty(t,r,a[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):ownKeys(Object(a)).forEach((function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(a,r))}))}return t}function _defineProperty(t,r,a){return(r=function _toPropertyKey(t){var r=function _toPrimitive(t,r){if("object"!=typeof t||null===t)return t;var a=t[Symbol.toPrimitive];if(void 0!==a){var i=a.call(t,r||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}(t,"string");return"symbol"==typeof r?r:String(r)}(r))in t?Object.defineProperty(t,r,{"value":a,"enumerable":!0,"configurable":!0,"writable":!0}):t[r]=a,t}function _extends(){return _extends=Object.assign?Object.assign.bind():function(t){for(var r=1;r<arguments.length;r++){var a=arguments[r];for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(t[i]=a[i])}return t},_extends.apply(this,arguments)}var R=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},I=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t}({}),D=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),b=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.UNKNOWN="unknown",t}({}),C=function noop(){},P={"trace":C,"debug":C,"log":C,"warn":C,"info":C,"error":C},_=P;function exportLoggerFunctions(t){for(var r=arguments.length,a=new Array(r>1?r-1:0),i=1;i<r;i++)a[i-1]=arguments[i];a.forEach((function(r){_[r]=t[r]?t[r].bind(t):function consolePrintFn(t){var r=self.console[t];return r?r.bind(self.console,"[".concat(t,"] >")):C}(r)}))}var w=_,M=/^(\d+)x(\d+)$/,x=/(.+?)=(".*?"|.*?)(?:,|$)/g,O=function(){function AttrList(t){for(var r in(0,m.Z)(this,AttrList),"string"==typeof t&&(t=AttrList.parseAttrList(t)),t)t.hasOwnProperty(r)&&("X-"===r.substring(0,2)&&(this.clientAttrs=this.clientAttrs||[],this.clientAttrs.push(r)),this[r]=t[r])}return(0,y.Z)(AttrList,[{"key":"decimalInteger","value":function decimalInteger(t){var r=parseInt(this[t],10);return r>Number.MAX_SAFE_INTEGER?1/0:r}},{"key":"hexadecimalInteger","value":function hexadecimalInteger(t){if(this[t]){var r=(this[t]||"0x").slice(2);r=(1&r.length?"0":"")+r;for(var a=new Uint8Array(r.length/2),i=0;i<r.length/2;i++)a[i]=parseInt(r.slice(2*i,2*i+2),16);return a}return null}},{"key":"hexadecimalIntegerAsNumber","value":function hexadecimalIntegerAsNumber(t){var r=parseInt(this[t],16);return r>Number.MAX_SAFE_INTEGER?1/0:r}},{"key":"decimalFloatingPoint","value":function decimalFloatingPoint(t){return parseFloat(this[t])}},{"key":"optionalFloat","value":function optionalFloat(t,r){var a=this[t];return a?parseFloat(a):r}},{"key":"enumeratedString","value":function enumeratedString(t){return this[t]}},{"key":"bool","value":function bool(t){return"YES"===this[t]}},{"key":"decimalResolution","value":function decimalResolution(t){var r=M.exec(this[t]);if(null!==r)return{"width":parseInt(r[1],10),"height":parseInt(r[2],10)}}}],[{"key":"parseAttrList","value":function parseAttrList(t){var r,a={};for(x.lastIndex=0;null!==(r=x.exec(t));){var i=r[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),a[r[1].trim()]=i}return a}}]),AttrList}();function isSCTE35Attribute(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t}var N=function(){function DateRange(t,r){if((0,m.Z)(this,DateRange),this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,r){var a=r.attr;for(var i in a)if(Object.prototype.hasOwnProperty.call(t,i)&&t[i]!==a[i]){w.warn('DATERANGE tag attribute: "'.concat(i,'" does not match for tags with ID: "').concat(t.ID,'"')),this._badValueForSameId=i;break}t=_extends(new O({}),a,t)}if(this.attr=t,this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){var o=new Date(this.attr["END-DATE"]);R(o.getTime())&&(this._endDate=o)}}return(0,y.Z)(DateRange,[{"key":"id","get":function get(){return this.attr.ID}},{"key":"class","get":function get(){return this.attr.CLASS}},{"key":"startDate","get":function get(){return this._startDate}},{"key":"endDate","get":function get(){if(this._endDate)return this._endDate;var t=this.duration;return null!==t?new Date(this._startDate.getTime()+1e3*t):null}},{"key":"duration","get":function get(){if("DURATION"in this.attr){var t=this.attr.decimalFloatingPoint("DURATION");if(R(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}},{"key":"plannedDuration","get":function get(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}},{"key":"endOnNext","get":function get(){return this.attr.bool("END-ON-NEXT")}},{"key":"isValid","get":function get(){return!!this.id&&!this._badValueForSameId&&R(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}]),DateRange}(),U=(0,y.Z)((function LoadStats(){(0,m.Z)(this,LoadStats),this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={"start":0,"first":0,"end":0},this.parsing={"start":0,"end":0},this.buffering={"start":0,"first":0,"end":0}})),B={"AUDIO":"audio","VIDEO":"video","AUDIOVIDEO":"audiovideo"},G=function(){function BaseSegment(t){(0,m.Z)(this,BaseSegment),this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[B.AUDIO]:null,[B.VIDEO]:null,[B.AUDIOVIDEO]:null},this.baseurl=t}return(0,y.Z)(BaseSegment,[{"key":"setByteRange","value":function setByteRange(t,r){var a=t.split("@",2),i=[];1===a.length?i[0]=r?r.byteRangeEndOffset:0:i[0]=parseInt(a[1]),i[1]=parseInt(a[0])+i[0],this._byteRange=i}},{"key":"byteRange","get":function get(){return this._byteRange?this._byteRange:[]}},{"key":"byteRangeStartOffset","get":function get(){return this.byteRange[0]}},{"key":"byteRangeEndOffset","get":function get(){return this.byteRange[1]}},{"key":"url","get":function get(){return!this._url&&this.baseurl&&this.relurl&&(this._url=A.buildAbsoluteURL(this.baseurl,this.relurl,{"alwaysNormalize":!0})),this._url||""},"set":function set(t){this._url=t}}]),BaseSegment}(),K=function(t){(0,g.Z)(Fragment,t);var r=(0,v.Z)(Fragment);function Fragment(t,a){var i;return(0,m.Z)(this,Fragment),(i=r.call(this,a))._decryptdata=null,i.rawProgramDateTime=null,i.programDateTime=null,i.tagList=[],i.duration=0,i.sn=0,i.levelkeys=void 0,i.type=void 0,i.loader=null,i.keyLoader=null,i.level=-1,i.cc=0,i.startPTS=void 0,i.endPTS=void 0,i.startDTS=void 0,i.endDTS=void 0,i.start=0,i.deltaPTS=void 0,i.maxStartPTS=void 0,i.minEndPTS=void 0,i.stats=new U,i.urlId=0,i.data=void 0,i.bitrateTest=!1,i.title=null,i.initSegment=null,i.endList=void 0,i.gap=void 0,i.type=t,i}return(0,y.Z)(Fragment,[{"key":"decryptdata","get":function get(){if(!this.levelkeys&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){var t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{var r=Object.keys(this.levelkeys);if(1===r.length)return this._decryptdata=this.levelkeys[r[0]].getDecryptData(this.sn)}}return this._decryptdata}},{"key":"end","get":function get(){return this.start+this.duration}},{"key":"endProgramDateTime","get":function get(){if(null===this.programDateTime)return null;if(!R(this.programDateTime))return null;var t=R(this.duration)?this.duration:0;return this.programDateTime+1e3*t}},{"key":"encrypted","get":function get(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){var r=Object.keys(this.levelkeys),a=r.length;if(a>1||1===a&&this.levelkeys[r[0]].encrypted)return!0}return!1}},{"key":"setKeyFormat","value":function setKeyFormat(t){if(this.levelkeys){var r=this.levelkeys[t];r&&!this._decryptdata&&(this._decryptdata=r.getDecryptData(this.sn))}}},{"key":"abortRequests","value":function abortRequests(){var t,r;null==(t=this.loader)||t.abort(),null==(r=this.keyLoader)||r.abort()}},{"key":"setElementaryStreamInfo","value":function setElementaryStreamInfo(t,r,a,i,o){var l=arguments.length>5&&void 0!==arguments[5]&&arguments[5],u=this.elementaryStreams,c=u[t];c?(c.startPTS=Math.min(c.startPTS,r),c.endPTS=Math.max(c.endPTS,a),c.startDTS=Math.min(c.startDTS,i),c.endDTS=Math.max(c.endDTS,o)):u[t]={"startPTS":r,"endPTS":a,"startDTS":i,"endDTS":o,"partial":l}}},{"key":"clearElementaryStreamInfo","value":function clearElementaryStreamInfo(){var t=this.elementaryStreams;t[B.AUDIO]=null,t[B.VIDEO]=null,t[B.AUDIOVIDEO]=null}}]),Fragment}(G),H=function(t){(0,g.Z)(Part,t);var r=(0,v.Z)(Part);function Part(t,a,i,o,l){var u;(0,m.Z)(this,Part),(u=r.call(this,i)).fragOffset=0,u.duration=0,u.gap=!1,u.independent=!1,u.relurl=void 0,u.fragment=void 0,u.index=void 0,u.stats=new U,u.duration=t.decimalFloatingPoint("DURATION"),u.gap=t.bool("GAP"),u.independent=t.bool("INDEPENDENT"),u.relurl=t.enumeratedString("URI"),u.fragment=a,u.index=o;var c=t.enumeratedString("BYTERANGE");return c&&u.setByteRange(c,l),l&&(u.fragOffset=l.fragOffset+l.duration),u}return(0,y.Z)(Part,[{"key":"start","get":function get(){return this.fragment.start+this.fragOffset}},{"key":"end","get":function get(){return this.start+this.duration}},{"key":"loaded","get":function get(){var t=this.elementaryStreams;return!!(t.audio||t.video||t.audiovideo)}}]),Part}(G),V=function(){function LevelDetails(t){(0,m.Z)(this,LevelDetails),this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}return(0,y.Z)(LevelDetails,[{"key":"reloaded","value":function reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);var r=this.lastPartSn-t.lastPartSn,a=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!a||!!r,this.advanced=this.endSN>t.endSN||r>0||0===r&&a>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay}},{"key":"hasProgramDateTime","get":function get(){return!!this.fragments.length&&R(this.fragments[this.fragments.length-1].programDateTime)}},{"key":"levelTargetDuration","get":function get(){return this.averagetargetduration||this.targetduration||10}},{"key":"drift","get":function get(){var t=this.driftEndTime-this.driftStartTime;return t>0?1e3*(this.driftEnd-this.driftStart)/t:1}},{"key":"edge","get":function get(){return this.partEnd||this.fragmentEnd}},{"key":"partEnd","get":function get(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{"key":"fragmentEnd","get":function get(){var t;return null!=(t=this.fragments)&&t.length?this.fragments[this.fragments.length-1].end:0}},{"key":"age","get":function get(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{"key":"lastPartIndex","get":function get(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}},{"key":"lastPartSn","get":function get(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}]),LevelDetails}();function base64Decode(t){return Uint8Array.from(atob(t),(function(t){return t.charCodeAt(0)}))}function convertDataUriToArrayBytes(t){var r=t.split(":"),a=null;if("data"===r[0]&&2===r.length){var i=r[1].split(";"),o=i[i.length-1].split(",");if(2===o.length){var l="base64"===o[0],u=o[1];l?(i.splice(-1,1),a=base64Decode(u)):a=function getKeyIdBytes(t){var r=strToUtf8array(t).subarray(0,16),a=new Uint8Array(16);return a.set(r,16-r.length),a}(u)}}return a}function strToUtf8array(t){return Uint8Array.from(unescape(encodeURIComponent(t)),(function(t){return t.charCodeAt(0)}))}var W={"CLEARKEY":"org.w3.clearkey","FAIRPLAY":"com.apple.fps","PLAYREADY":"com.microsoft.playready","WIDEVINE":"com.widevine.alpha"},Z={"CLEARKEY":"org.w3.clearkey","FAIRPLAY":"com.apple.streamingkeydelivery","PLAYREADY":"com.microsoft.playready","WIDEVINE":"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function keySystemFormatToKeySystemDomain(t){switch(t){case Z.FAIRPLAY:return W.FAIRPLAY;case Z.PLAYREADY:return W.PLAYREADY;case Z.WIDEVINE:return W.WIDEVINE;case Z.CLEARKEY:return W.CLEARKEY}}var Y={"WIDEVINE":"edef8ba979d64acea3c827dcd51d21ed"};function keySystemDomainToKeySystemFormat(t){switch(t){case W.FAIRPLAY:return Z.FAIRPLAY;case W.PLAYREADY:return Z.PLAYREADY;case W.WIDEVINE:return Z.WIDEVINE;case W.CLEARKEY:return Z.CLEARKEY}}function getKeySystemsForConfig(t){var r=t.drmSystems,a=t.widevineLicenseUrl,i=r?[W.FAIRPLAY,W.WIDEVINE,W.PLAYREADY,W.CLEARKEY].filter((function(t){return!!r[t]})):[];return!i[W.WIDEVINE]&&a&&i.push(W.WIDEVINE),i}var j="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function sliceUint8(t,r,a){return Uint8Array.prototype.slice?t.slice(r,a):new Uint8Array(Array.prototype.slice.call(t,r,a))}var q,z=function isHeader$2(t,r){return r+10<=t.length&&73===t[r]&&68===t[r+1]&&51===t[r+2]&&t[r+3]<255&&t[r+4]<255&&t[r+6]<128&&t[r+7]<128&&t[r+8]<128&&t[r+9]<128},X=function isFooter(t,r){return r+10<=t.length&&51===t[r]&&68===t[r+1]&&73===t[r+2]&&t[r+3]<255&&t[r+4]<255&&t[r+6]<128&&t[r+7]<128&&t[r+8]<128&&t[r+9]<128},Q=function getID3Data(t,r){for(var a=r,i=0;z(t,r);){i+=10,i+=$(t,r+6),X(t,r+10)&&(i+=10),r+=i}if(i>0)return t.subarray(a,a+i)},$=function readSize(t,r){var a=0;return a=(127&t[r])<<21,a|=(127&t[r+1])<<14,a|=(127&t[r+2])<<7,a|=127&t[r+3]},J=function canParse$2(t,r){return z(t,r)&&$(t,r+6)+10<=t.length-r},ee=function isTimeStampFrame(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info},te=function getFrameData(t){var r=String.fromCharCode(t[0],t[1],t[2],t[3]),a=$(t,4);return{"type":r,"size":a,"data":t.subarray(10,10+a)}},re=function getID3Frames(t){for(var r=0,a=[];z(t,r);){for(var i=$(t,r+6),o=(r+=10)+i;r+8<o;){var l=te(t.subarray(r)),u=ae(l);u&&a.push(u),r+=l.size+10}X(t,r)&&(r+=10)}return a},ae=function decodeFrame(t){return"PRIV"===t.type?ie(t):"W"===t.type[0]?se(t):ne(t)},ie=function decodePrivFrame(t){if(!(t.size<2)){var r=le(t.data,!0),a=new Uint8Array(t.data.subarray(r.length+1));return{"key":t.type,"info":r,"data":a.buffer}}},ne=function decodeTextFrame(t){if(!(t.size<2)){if("TXXX"===t.type){var r=1,a=le(t.data.subarray(r),!0);r+=a.length+1;var i=le(t.data.subarray(r));return{"key":t.type,"info":a,"data":i}}var o=le(t.data.subarray(1));return{"key":t.type,"data":o}}},se=function decodeURLFrame(t){if("WXXX"===t.type){if(t.size<2)return;var r=1,a=le(t.data.subarray(r),!0);r+=a.length+1;var i=le(t.data.subarray(r));return{"key":t.type,"info":a,"data":i}}var o=le(t.data);return{"key":t.type,"data":o}},oe=function readTimeStamp(t){if(8===t.data.byteLength){var r=new Uint8Array(t.data),a=1&r[3],i=(r[4]<<23)+(r[5]<<15)+(r[6]<<7)+r[7];return i/=45,a&&(i+=47721858.84),Math.round(i)}},le=function utf8ArrayToStr(t){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],a=getTextDecoder();if(a){var i=a.decode(t);if(r){var o=i.indexOf("\0");return-1!==o?i.substring(0,o):i}return i.replace(/\0/g,"")}for(var l,u,c,d=t.length,h="",g=0;g<d;){if(0===(l=t[g++])&&r)return h;if(0!==l&&3!==l)switch(l>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:h+=String.fromCharCode(l);break;case 12:case 13:u=t[g++],h+=String.fromCharCode((31&l)<<6|63&u);break;case 14:u=t[g++],c=t[g++],h+=String.fromCharCode((15&l)<<12|(63&u)<<6|(63&c)<<0)}}return h};function getTextDecoder(){return q||void 0===self.TextDecoder||(q=new self.TextDecoder("utf-8")),q}var ue={"hexDump":function hexDump(t){for(var r="",a=0;a<t.length;a++){var i=t[a].toString(16);i.length<2&&(i="0"+i),r+=i}return r}},ce=Math.pow(2,32)-1,de=[].push,he={"video":1,"audio":2,"id3":3,"text":4};function bin2str(t){return String.fromCharCode.apply(null,t)}function readUint16(t,r){var a=t[r]<<8|t[r+1];return a<0?65536+a:a}function readUint32(t,r){var a=readSint32(t,r);return a<0?4294967296+a:a}function readSint32(t,r){return t[r]<<24|t[r+1]<<16|t[r+2]<<8|t[r+3]}function writeUint32(t,r,a){t[r]=a>>24,t[r+1]=a>>16&255,t[r+2]=a>>8&255,t[r+3]=255&a}function findBox(t,r){var a=[];if(!r.length)return a;for(var i=t.byteLength,o=0;o<i;){var l=readUint32(t,o),u=l>1?o+l:i;if(bin2str(t.subarray(o+4,o+8))===r[0])if(1===r.length)a.push(t.subarray(o+8,u));else{var c=findBox(t.subarray(o+8,u),r.slice(1));c.length&&de.apply(a,c)}o=u}return a}function parseSegmentIndex(t){var r=[],a=t[0],i=8,o=readUint32(t,i);i+=4;i+=0===a?8:16,i+=2;var l=t.length+0,u=readUint16(t,i);i+=2;for(var c=0;c<u;c++){var d=i,h=readUint32(t,d);d+=4;var g=2147483647&h;if(1===(2147483648&h)>>>31)return w.warn("SIDX has hierarchical references (not supported)"),null;var v=readUint32(t,d);d+=4,r.push({"referenceSize":g,"subsegmentDuration":v,"info":{"duration":v/o,"start":l,"end":l+g-1}}),l+=g,i=d+=4}return{"earliestPresentationTime":0,"timescale":o,"version":a,"referencesCount":u,"references":r}}function parseInitSegment(t){for(var r=[],a=findBox(t,["moov","trak"]),i=0;i<a.length;i++){var o=a[i],l=findBox(o,["tkhd"])[0];if(l){var u=l[0],c=0===u?12:20,d=readUint32(l,c),h=findBox(o,["mdia","mdhd"])[0];if(h){var g=readUint32(h,c=0===(u=h[0])?12:20),v=findBox(o,["mdia","hdlr"])[0];if(v){var m=bin2str(v.subarray(8,12)),y={"soun":B.AUDIO,"vide":B.VIDEO}[m];if(y){var p=findBox(o,["mdia","minf","stbl","stsd"])[0],T=void 0;p&&(T=bin2str(p.subarray(12,16))),r[d]={"timescale":g,"type":y},r[y]={"timescale":g,"id":d,"codec":T}}}}}}return findBox(t,["moov","mvex","trex"]).forEach((function(t){var a=readUint32(t,4),i=r[a];i&&(i.default={"duration":readUint32(t,12),"flags":readUint32(t,20)})})),r}function parseSinf(t){var r=findBox(t,["schm"])[0];if(r){var a=bin2str(r.subarray(4,8));if("cbcs"===a||"cenc"===a)return findBox(t,["schi","tenc"])[0]}return w.error("[eme] missing 'schm' box"),null}function computeRawDurationFromSamples(t){var r=readUint32(t,0),a=8;1&r&&(a+=4),4&r&&(a+=4);for(var i=0,o=readUint32(t,4),l=0;l<o;l++){if(256&r)i+=readUint32(t,a),a+=4;512&r&&(a+=4),1024&r&&(a+=4),2048&r&&(a+=4)}return i}function appendUint8Array(t,r){var a=new Uint8Array(t.length+r.length);return a.set(t),a.set(r,t.length),a}function parseSamples(t,r){var a=[],i=r.samples,o=r.timescale,l=r.id,u=!1;return findBox(i,["moof"]).map((function(c){var d=c.byteOffset-8;findBox(c,["traf"]).map((function(c){var h=findBox(c,["tfdt"]).map((function(t){var r=t[0],a=readUint32(t,4);return 1===r&&(a*=Math.pow(2,32),a+=readUint32(t,8)),a/o}))[0];return void 0!==h&&(t=h),findBox(c,["tfhd"]).map((function(h){var g=readUint32(h,4),v=16777215&readUint32(h,0),m=0,y=0!=(16&v),p=0,T=0!=(32&v),E=8;g===l&&(0!=(1&v)&&(E+=8),0!=(2&v)&&(E+=4),0!=(8&v)&&(m=readUint32(h,E),E+=4),y&&(p=readUint32(h,E),E+=4),T&&(E+=4),"video"===r.type&&(u=function isHEVC(t){if(!t)return!1;var r=t.indexOf("."),a=r<0?t:t.substring(0,r);return"hvc1"===a||"hev1"===a||"dvh1"===a||"dvhe"===a}(r.codec)),findBox(c,["trun"]).map((function(l){var c=l[0],h=16777215&readUint32(l,0),g=0!=(1&h),v=0,y=0!=(4&h),T=0!=(256&h),E=0,k=0!=(512&h),S=0,L=0!=(1024&h),A=0!=(2048&h),R=0,I=readUint32(l,4),D=8;g&&(v=readUint32(l,D),D+=4),y&&(D+=4);for(var b=v+d,C=0;C<I;C++){if(T?(E=readUint32(l,D),D+=4):E=m,k?(S=readUint32(l,D),D+=4):S=p,L&&(D+=4),A&&(R=0===c?readUint32(l,D):readSint32(l,D),D+=4),r.type===B.VIDEO)for(var P=0;P<S;){var _=readUint32(i,b);if(isSEIMessage(u,i[b+=4]))parseSEIMessageFromNALu(i.subarray(b,b+_),u?2:1,t+R/o,a);b+=_,P+=_+4}t+=E/o}})))}))}))})),a}function isSEIMessage(t,r){if(t){var a=r>>1&63;return 39===a||40===a}return 6===(31&r)}function parseSEIMessageFromNALu(t,r,a,i){var o=discardEPB(t),l=0;l+=r;for(var u=0,c=0,d=!1,h=0;l<o.length;){u=0;do{if(l>=o.length)break;u+=h=o[l++]}while(255===h);c=0;do{if(l>=o.length)break;c+=h=o[l++]}while(255===h);var g=o.length-l;if(!d&&4===u&&l<o.length){if(d=!0,181===o[l++]){var v=readUint16(o,l);if(l+=2,49===v){var m=readUint32(o,l);if(l+=4,1195456820===m){var y=o[l++];if(3===y){var p=o[l++],T=64&p,E=T?2+3*(31&p):0,k=new Uint8Array(E);if(T){k[0]=p;for(var S=1;S<E;S++)k[S]=o[l++]}i.push({"type":y,"payloadType":u,"pts":a,"bytes":k})}}}}}else if(5===u&&c<g){if(d=!0,c>16){for(var L=[],A=0;A<16;A++){var R=o[l++].toString(16);L.push(1==R.length?"0"+R:R),3!==A&&5!==A&&7!==A&&9!==A||L.push("-")}for(var I=c-16,D=new Uint8Array(I),b=0;b<I;b++)D[b]=o[l++];i.push({"payloadType":u,"pts":a,"uuid":L.join(""),"userData":le(D),"userDataBytes":D})}}else if(c<g)l+=c;else if(c>g)break}}function discardEPB(t){for(var r=t.byteLength,a=[],i=1;i<r-2;)0===t[i]&&0===t[i+1]&&3===t[i+2]?(a.push(i+2),i+=2):i++;if(0===a.length)return t;var o=r-a.length,l=new Uint8Array(o),u=0;for(i=0;i<o;u++,i++)u===a[0]&&(u++,a.shift()),l[i]=t[u];return l}function mp4pssh(t,r,a){if(16!==t.byteLength)throw new RangeError("Invalid system id");var i,o,l;if(r){i=1,o=new Uint8Array(16*r.length);for(var u=0;u<r.length;u++){var c=r[u];if(16!==c.byteLength)throw new RangeError("Invalid key");o.set(c,16*u)}}else i=0,o=new Uint8Array;i>0?(l=new Uint8Array(4),r.length>0&&new DataView(l.buffer).setUint32(0,r.length,!1)):l=new Uint8Array;var d=new Uint8Array(4);return a&&a.byteLength>0&&new DataView(d.buffer).setUint32(0,a.byteLength,!1),function mp4Box(t){for(var r=arguments.length,a=new Array(r>1?r-1:0),i=1;i<r;i++)a[i-1]=arguments[i];for(var o=a.length,l=8,u=o;u--;)l+=a[u].byteLength;var c=new Uint8Array(l);for(c[0]=l>>24&255,c[1]=l>>16&255,c[2]=l>>8&255,c[3]=255&l,c.set(t,4),u=0,l=8;u<o;u++)c.set(a[u],l),l+=a[u].byteLength;return c}([112,115,115,104],new Uint8Array([i,0,0,0]),t,l,o,d,a||new Uint8Array)}var fe={},ge=function(){function LevelKey(t,r,a){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[1],o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;(0,m.Z)(this,LevelKey),this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=r,this.keyFormat=a,this.keyFormatVersions=i,this.iv=o,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&"AES-128"!==t}return(0,y.Z)(LevelKey,[{"key":"isSupported","value":function isSupported(){if(this.method){if("AES-128"===this.method||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Z.FAIRPLAY:case Z.WIDEVINE:case Z.PLAYREADY:case Z.CLEARKEY:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}},{"key":"getDecryptData","value":function getDecryptData(t){if(!this.encrypted||!this.uri)return null;if("AES-128"===this.method&&this.uri&&!this.iv){"number"!=typeof t&&("AES-128"!==this.method||this.iv||w.warn('missing IV for initialization segment with method="'.concat(this.method,'" - compliance issue')),t=0);var r=function createInitializationVector(t){for(var r=new Uint8Array(16),a=12;a<16;a++)r[a]=t>>8*(15-a)&255;return r}(t);return new LevelKey(this.method,this.uri,"identity",this.keyFormatVersions,r)}var a=convertDataUriToArrayBytes(this.uri);if(a)switch(this.keyFormat){case Z.WIDEVINE:this.pssh=a,a.length>=22&&(this.keyId=a.subarray(a.length-22,a.length-6));break;case Z.PLAYREADY:var i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=mp4pssh(i,null,a);var o=new Uint16Array(a.buffer,a.byteOffset,a.byteLength/2),l=String.fromCharCode.apply(null,Array.from(o)),u=l.substring(l.indexOf("<"),l.length),c=(new DOMParser).parseFromString(u,"text/xml").getElementsByTagName("KID")[0];if(c){var d=c.childNodes[0]?c.childNodes[0].nodeValue:c.getAttribute("VALUE");if(d){var h=base64Decode(d).subarray(0,16);!function changeEndianness(t){var r=function swap(t,r,a){var i=t[r];t[r]=t[a],t[a]=i};r(t,0,3),r(t,1,2),r(t,4,5),r(t,6,7)}(h),this.keyId=h}}break;default:var g=a.subarray(0,16);if(16!==g.length){var v=new Uint8Array(16);v.set(g,16-g.length),g=v}this.keyId=g}if(!this.keyId||16!==this.keyId.byteLength){var m=fe[this.uri];if(!m){var y=Object.keys(fe).length%Number.MAX_SAFE_INTEGER;m=new Uint8Array(16),new DataView(m.buffer,12,4).setUint32(0,y),fe[this.uri]=m}this.keyId=m}return this}}],[{"key":"clearKeyUriToKeyIdMap","value":function clearKeyUriToKeyIdMap(){fe={}}}]),LevelKey}();var ve=/\{\$([a-zA-Z0-9-_]+)\}/g;function hasVariableReferences(t){return ve.test(t)}function substituteVariablesInAttributes(t,r,a){if(null!==t.variableList||t.hasVariableRefs)for(var i=a.length;i--;){var o=a[i],l=r[o];l&&(r[o]=substituteVariables(t,l))}}function substituteVariables(t,r){if(null!==t.variableList||t.hasVariableRefs){var a=t.variableList;return r.replace(ve,(function(r){var i=r.substring(2,r.length-1),o=null==a?void 0:a[i];return void 0===o?(t.playlistParsingError||(t.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'.concat(i,'"'))),r):o}))}return r}function addVariableDefinition(t,r,a){var i,o,l=t.variableList;if(l||(t.variableList=l={}),"QUERYPARAM"in r){i=r.QUERYPARAM;try{var u=new self.URL(a).searchParams;if(!u.has(i))throw new Error('"'.concat(i,'" does not match any query parameter in URI: "').concat(a,'"'));o=u.get(i)}catch(r){t.playlistParsingError||(t.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: ".concat(r.message)))}}else i=r.NAME,o=r.VALUE;i in l?t.playlistParsingError||(t.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'.concat(i,'"'))):l[i]=o||""}function importVariableDefinition(t,r,a){var i=r.IMPORT;if(a&&i in a){var o=t.variableList;o||(t.variableList=o={}),o[i]=a[i]}else t.playlistParsingError||(t.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'.concat(i,'"')))}function getMediaSource(){if("undefined"!=typeof self)return self.MediaSource||self.WebKitMediaSource}var me={"audio":{"a3ds":!0,"ac-3":!0,"ac-4":!0,"alac":!0,"alaw":!0,"dra1":!0,"dts+":!0,"dts-":!0,"dtsc":!0,"dtse":!0,"dtsh":!0,"ec-3":!0,"enca":!0,"g719":!0,"g726":!0,"m4ae":!0,"mha1":!0,"mha2":!0,"mhm1":!0,"mhm2":!0,"mlpa":!0,"mp4a":!0,"raw ":!0,"Opus":!0,"opus":!0,"samr":!0,"sawb":!0,"sawp":!0,"sevc":!0,"sqcp":!0,"ssmv":!0,"twos":!0,"ulaw":!0},"video":{"avc1":!0,"avc2":!0,"avc3":!0,"avc4":!0,"avcp":!0,"av01":!0,"drac":!0,"dva1":!0,"dvav":!0,"dvh1":!0,"dvhe":!0,"encv":!0,"hev1":!0,"hvc1":!0,"mjp2":!0,"mp4v":!0,"mvc1":!0,"mvc2":!0,"mvc3":!0,"mvc4":!0,"resv":!0,"rv60":!0,"s263":!0,"svc1":!0,"svc2":!0,"vc-1":!0,"vp08":!0,"vp09":!0},"text":{"stpp":!0,"wvtt":!0}},ye=getMediaSource();function isCodecSupportedInMp4(t,r){var a;return null!=(a=null==ye?void 0:ye.isTypeSupported("".concat(r||"video",'/mp4;codecs="').concat(t,'"')))&&a}var pe=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Te=/#EXT-X-MEDIA:(.*)/g,Ee=/^#EXT(?:INF|-X-TARGETDURATION):/m,ke=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Se=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),Le=function(){function M3U8Parser(){(0,m.Z)(this,M3U8Parser)}return(0,y.Z)(M3U8Parser,null,[{"key":"findGroup","value":function findGroup(t,r){for(var a=0;a<t.length;a++){var i=t[a];if(i.id===r)return i}}},{"key":"convertAVC1ToAVCOTI","value":function convertAVC1ToAVCOTI(t){var r=t.split(".");if(r.length>2){var a=r.shift()+".";return a+=parseInt(r.shift()).toString(16),a+=("000"+parseInt(r.shift()).toString(16)).slice(-4)}return t}},{"key":"resolve","value":function resolve(t,r){return A.buildAbsoluteURL(r,t,{"alwaysNormalize":!0})}},{"key":"isMediaPlaylist","value":function isMediaPlaylist(t){return Ee.test(t)}},{"key":"parseMasterPlaylist","value":function parseMasterPlaylist(t,r){var a,i={"contentSteering":null,"levels":[],"playlistParsingError":null,"sessionData":null,"sessionKeys":null,"startTimeOffset":null,"variableList":null,"hasVariableRefs":hasVariableReferences(t)},o=[];for(pe.lastIndex=0;null!=(a=pe.exec(t));)if(a[1]){var l,u=new O(a[1]);substituteVariablesInAttributes(i,u,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);var c=substituteVariables(i,a[2]),d={"attrs":u,"bitrate":u.decimalInteger("AVERAGE-BANDWIDTH")||u.decimalInteger("BANDWIDTH"),"name":u.NAME,"url":M3U8Parser.resolve(c,r)},h=u.decimalResolution("RESOLUTION");h&&(d.width=h.width,d.height=h.height),setCodecs((u.CODECS||"").split(/[ ,]+/).filter((function(t){return t})),d),d.videoCodec&&-1!==d.videoCodec.indexOf("avc1")&&(d.videoCodec=M3U8Parser.convertAVC1ToAVCOTI(d.videoCodec)),null!=(l=d.unknownCodecs)&&l.length||o.push(d),i.levels.push(d)}else if(a[3]){var g=a[3],v=a[4];switch(g){case"SESSION-DATA":var m=new O(v);substituteVariablesInAttributes(i,m,["DATA-ID","LANGUAGE","VALUE","URI"]);var y=m["DATA-ID"];y&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[y]=m);break;case"SESSION-KEY":var p=parseKey(v,r,i);p.encrypted&&p.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(p)):w.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'.concat(v,'"'));break;case"DEFINE":var T=new O(v);substituteVariablesInAttributes(i,T,["NAME","VALUE","QUERYPARAM"]),addVariableDefinition(i,T,r);break;case"CONTENT-STEERING":var E=new O(v);substituteVariablesInAttributes(i,E,["SERVER-URI","PATHWAY-ID"]),i.contentSteering={"uri":M3U8Parser.resolve(E["SERVER-URI"],r),"pathwayId":E["PATHWAY-ID"]||"."};break;case"START":i.startTimeOffset=parseStartTimeOffset(v)}}var k=o.length>0&&o.length<i.levels.length;return i.levels=k?o:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}},{"key":"parseMasterPlaylistMedia","value":function parseMasterPlaylistMedia(t,r,a){var i,o={},l=a.levels,u={"AUDIO":l.map((function(t){return{"id":t.attrs.AUDIO,"audioCodec":t.audioCodec}})),"SUBTITLES":l.map((function(t){return{"id":t.attrs.SUBTITLES,"textCodec":t.textCodec}})),"CLOSED-CAPTIONS":[]},c=0;for(Te.lastIndex=0;null!==(i=Te.exec(t));){var d=new O(i[1]),h=d.TYPE;if(h){var g=u[h],v=o[h]||[];o[h]=v,substituteVariablesInAttributes(a,d,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);var m={"attrs":d,"bitrate":0,"id":c++,"groupId":d["GROUP-ID"]||"","instreamId":d["INSTREAM-ID"],"name":d.NAME||d.LANGUAGE||"","type":h,"default":d.bool("DEFAULT"),"autoselect":d.bool("AUTOSELECT"),"forced":d.bool("FORCED"),"lang":d.LANGUAGE,"url":d.URI?M3U8Parser.resolve(d.URI,r):""};if(null!=g&&g.length){var y=M3U8Parser.findGroup(g,m.groupId)||g[0];assignCodec(m,y,"audioCodec"),assignCodec(m,y,"textCodec")}v.push(m)}}return o}},{"key":"parseLevelPlaylist","value":function parseLevelPlaylist(t,r,a,i,o,l){var u,c,d,h=new V(r),g=h.fragments,v=null,m=0,y=0,p=0,T=0,E=null,k=new K(i,r),S=-1,L=!1;for(ke.lastIndex=0,h.m3u8=t,h.hasVariableRefs=hasVariableReferences(t);null!==(u=ke.exec(t));){L&&(L=!1,(k=new K(i,r)).start=p,k.sn=m,k.cc=T,k.level=a,v&&(k.initSegment=v,k.rawProgramDateTime=v.rawProgramDateTime,v.rawProgramDateTime=null));var A=u[1];if(A){k.duration=parseFloat(A);var I=(" "+u[2]).slice(1);k.title=I||null,k.tagList.push(I?["INF",A,I]:["INF",A])}else if(u[3]){if(R(k.duration)){k.start=p,d&&setFragLevelKeys(k,d,h),k.sn=m,k.level=a,k.cc=T,k.urlId=o,g.push(k);var D=(" "+u[3]).slice(1);k.relurl=substituteVariables(h,D),assignProgramDateTime(k,E),E=k,p+=k.duration,m++,y=0,L=!0}}else if(u[4]){var b=(" "+u[4]).slice(1);E?k.setByteRange(b,E):k.setByteRange(b)}else if(u[5])k.rawProgramDateTime=(" "+u[5]).slice(1),k.tagList.push(["PROGRAM-DATE-TIME",k.rawProgramDateTime]),-1===S&&(S=g.length);else{if(!(u=u[0].match(Se))){w.warn("No matches on slow regex match for level playlist!");continue}for(c=1;c<u.length&&void 0===u[c];c++);var C=(" "+u[c]).slice(1),P=(" "+u[c+1]).slice(1),_=u[c+2]?(" "+u[c+2]).slice(1):"";switch(C){case"PLAYLIST-TYPE":h.type=P.toUpperCase();break;case"MEDIA-SEQUENCE":m=h.startSN=parseInt(P);break;case"SKIP":var M=new O(P);substituteVariablesInAttributes(h,M,["RECENTLY-REMOVED-DATERANGES"]);var x=M.decimalInteger("SKIPPED-SEGMENTS");if(R(x)){h.skippedSegments=x;for(var U=x;U--;)g.unshift(null);m+=x}var B=M.enumeratedString("RECENTLY-REMOVED-DATERANGES");B&&(h.recentlyRemovedDateranges=B.split("\t"));break;case"TARGETDURATION":h.targetduration=Math.max(parseInt(P),1);break;case"VERSION":h.version=parseInt(P);break;case"EXTM3U":break;case"ENDLIST":h.live=!1;break;case"#":(P||_)&&k.tagList.push(_?[P,_]:[P]);break;case"DISCONTINUITY":T++,k.tagList.push(["DIS"]);break;case"GAP":k.gap=!0,k.tagList.push([C]);break;case"BITRATE":k.tagList.push([C,P]);break;case"DATERANGE":var G=new O(P);substituteVariablesInAttributes(h,G,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),substituteVariablesInAttributes(h,G,G.clientAttrs);var W=new N(G,h.dateRanges[G.ID]);W.isValid||h.skippedSegments?h.dateRanges[W.id]=W:w.warn('Ignoring invalid DATERANGE tag: "'.concat(P,'"')),k.tagList.push(["EXT-X-DATERANGE",P]);break;case"DEFINE":var Z=new O(P);substituteVariablesInAttributes(h,Z,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in Z?importVariableDefinition(h,Z,l):addVariableDefinition(h,Z,r);break;case"DISCONTINUITY-SEQUENCE":T=parseInt(P);break;case"KEY":var Y=parseKey(P,r,h);if(Y.isSupported()){if("NONE"===Y.method){d=void 0;break}d||(d={}),d[Y.keyFormat]&&(d=_extends({},d)),d[Y.keyFormat]=Y}else w.warn('[Keys] Ignoring invalid EXT-X-KEY tag: "'.concat(P,'"'));break;case"START":h.startTimeOffset=parseStartTimeOffset(P);break;case"MAP":var j=new O(P);if(substituteVariablesInAttributes(h,j,["BYTERANGE","URI"]),k.duration){var q=new K(i,r);setInitSegment(q,j,a,d),v=q,k.initSegment=v,v.rawProgramDateTime&&!k.rawProgramDateTime&&(k.rawProgramDateTime=v.rawProgramDateTime)}else setInitSegment(k,j,a,d),v=k,L=!0;break;case"SERVER-CONTROL":var z=new O(P);h.canBlockReload=z.bool("CAN-BLOCK-RELOAD"),h.canSkipUntil=z.optionalFloat("CAN-SKIP-UNTIL",0),h.canSkipDateRanges=h.canSkipUntil>0&&z.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=z.optionalFloat("PART-HOLD-BACK",0),h.holdBack=z.optionalFloat("HOLD-BACK",0);break;case"PART-INF":var X=new O(P);h.partTarget=X.decimalFloatingPoint("PART-TARGET");break;case"PART":var Q=h.partList;Q||(Q=h.partList=[]);var $=y>0?Q[Q.length-1]:void 0,J=y++,ee=new O(P);substituteVariablesInAttributes(h,ee,["BYTERANGE","URI"]);var te=new H(ee,k,r,J,$);Q.push(te),k.duration+=te.duration;break;case"PRELOAD-HINT":var re=new O(P);substituteVariablesInAttributes(h,re,["URI"]),h.preloadHint=re;break;case"RENDITION-REPORT":var ae=new O(P);substituteVariablesInAttributes(h,ae,["URI"]),h.renditionReports=h.renditionReports||[],h.renditionReports.push(ae);break;default:w.warn("line parsed but not handled: ".concat(u))}}}E&&!E.relurl?(g.pop(),p-=E.duration,h.partList&&(h.fragmentHint=E)):h.partList&&(assignProgramDateTime(k,E),k.cc=T,h.fragmentHint=k,d&&setFragLevelKeys(k,d,h));var ie=g.length,ne=g[0],se=g[ie-1];if((p+=h.skippedSegments*h.targetduration)>0&&ie&&se){h.averagetargetduration=p/ie;var oe=se.sn;h.endSN="initSegment"!==oe?oe:0,h.live||(se.endList=!0),ne&&(h.startCC=ne.cc)}else h.endSN=0,h.startCC=0;return h.fragmentHint&&(p+=h.fragmentHint.duration),h.totalduration=p,h.endCC=T,S>0&&function backfillProgramDateTimes(t,r){for(var a=t[r],i=r;i--;){var o=t[i];if(!o)return;o.programDateTime=a.programDateTime-1e3*o.duration,a=o}}(g,S),h}}]),M3U8Parser}();function parseKey(t,r,a){var i,o,l=new O(t);substituteVariablesInAttributes(a,l,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);var u=null!=(i=l.METHOD)?i:"",c=l.URI,d=l.hexadecimalInteger("IV"),h=l.KEYFORMATVERSIONS,g=null!=(o=l.KEYFORMAT)?o:"identity";c&&l.IV&&!d&&w.error("Invalid IV: ".concat(l.IV));var v=c?Le.resolve(c,r):"",m=(h||"1").split("/").map(Number).filter(Number.isFinite);return new ge(u,v,g,m,d)}function parseStartTimeOffset(t){var r=new O(t).decimalFloatingPoint("TIME-OFFSET");return R(r)?r:null}function setCodecs(t,r){["video","audio","text"].forEach((function(a){var i=t.filter((function(t){return function isCodecType(t,r){var a=me[r];return!!a&&!0===a[t.slice(0,4)]}(t,a)}));if(i.length){var o=i.filter((function(t){return 0===t.lastIndexOf("avc1",0)||0===t.lastIndexOf("mp4a",0)}));r["".concat(a,"Codec")]=o.length>0?o[0]:i[0],t=t.filter((function(t){return-1===i.indexOf(t)}))}})),r.unknownCodecs=t}function assignCodec(t,r,a){var i=r[a];i&&(t[a]=i)}function assignProgramDateTime(t,r){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=r&&r.programDateTime&&(t.programDateTime=r.endProgramDateTime),R(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function setInitSegment(t,r,a,i){t.relurl=r.URI,r.BYTERANGE&&t.setByteRange(r.BYTERANGE),t.level=a,t.sn="initSegment",i&&(t.levelkeys=i),t.initSegment=null}function setFragLevelKeys(t,r,a){t.levelkeys=r;var i=a.encryptedFragments;i.length&&i[i.length-1].levelkeys===r||!Object.keys(r).some((function(t){return r[t].isCommonEncryption}))||i.push(t)}var Ae={"MANIFEST":"manifest","LEVEL":"level","AUDIO_TRACK":"audioTrack","SUBTITLE_TRACK":"subtitleTrack"},Re={"MAIN":"main","AUDIO":"audio","SUBTITLE":"subtitle"};function mapContextToLevelType(t){switch(t.type){case Ae.AUDIO_TRACK:return Re.AUDIO;case Ae.SUBTITLE_TRACK:return Re.SUBTITLE;default:return Re.MAIN}}function getResponseUrl(t,r){var a=t.url;return void 0!==a&&0!==a.indexOf("data:")||(a=r.url),a}var Ie=function(){function PlaylistLoader(t){(0,m.Z)(this,PlaylistLoader),this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=t,this.registerListeners()}return(0,y.Z)(PlaylistLoader,[{"key":"startLoad","value":function startLoad(t){}},{"key":"stopLoad","value":function stopLoad(){this.destroyInternalLoaders()}},{"key":"registerListeners","value":function registerListeners(){var t=this.hls;t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.LEVEL_LOADING,this.onLevelLoading,this),t.on(I.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(I.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}},{"key":"unregisterListeners","value":function unregisterListeners(){var t=this.hls;t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.LEVEL_LOADING,this.onLevelLoading,this),t.off(I.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(I.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}},{"key":"createInternalLoader","value":function createInternalLoader(t){var r=this.hls.config,a=r.pLoader,i=r.loader,o=new(a||i)(r);return this.loaders[t.type]=o,o}},{"key":"getInternalLoader","value":function getInternalLoader(t){return this.loaders[t.type]}},{"key":"resetInternalLoader","value":function resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}},{"key":"destroyInternalLoaders","value":function destroyInternalLoaders(){for(var t in this.loaders){var r=this.loaders[t];r&&r.destroy(),this.resetInternalLoader(t)}}},{"key":"destroy","value":function destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}},{"key":"onManifestLoading","value":function onManifestLoading(t,r){var a=r.url;this.variableList=null,this.load({"id":null,"level":0,"responseType":"text","type":Ae.MANIFEST,"url":a,"deliveryDirectives":null})}},{"key":"onLevelLoading","value":function onLevelLoading(t,r){var a=r.id,i=r.level,o=r.url,l=r.deliveryDirectives;this.load({"id":a,"level":i,"responseType":"text","type":Ae.LEVEL,"url":o,"deliveryDirectives":l})}},{"key":"onAudioTrackLoading","value":function onAudioTrackLoading(t,r){var a=r.id,i=r.groupId,o=r.url,l=r.deliveryDirectives;this.load({"id":a,"groupId":i,"level":null,"responseType":"text","type":Ae.AUDIO_TRACK,"url":o,"deliveryDirectives":l})}},{"key":"onSubtitleTrackLoading","value":function onSubtitleTrackLoading(t,r){var a=r.id,i=r.groupId,o=r.url,l=r.deliveryDirectives;this.load({"id":a,"groupId":i,"level":null,"responseType":"text","type":Ae.SUBTITLE_TRACK,"url":o,"deliveryDirectives":l})}},{"key":"load","value":function load(t){var r,a,i,o=this,l=this.hls.config,u=this.getInternalLoader(t);if(u){var c=u.context;if(c&&c.url===t.url)return void w.trace("[playlist-loader]: playlist request ongoing");w.log("[playlist-loader]: aborting previous loader for type: ".concat(t.type)),u.abort()}if((a=t.type===Ae.MANIFEST?l.manifestLoadPolicy.default:_extends({},l.playlistLoadPolicy.default,{"timeoutRetry":null,"errorRetry":null}),u=this.createInternalLoader(t),null!=(r=t.deliveryDirectives)&&r.part)&&(t.type===Ae.LEVEL&&null!==t.level?i=this.hls.levels[t.level].details:t.type===Ae.AUDIO_TRACK&&null!==t.id?i=this.hls.audioTracks[t.id].details:t.type===Ae.SUBTITLE_TRACK&&null!==t.id&&(i=this.hls.subtitleTracks[t.id].details),i)){var d=i.partTarget,h=i.targetduration;if(d&&h){var g=1e3*Math.max(3*d,.8*h);a=_extends({},a,{"maxTimeToFirstByteMs":Math.min(g,a.maxTimeToFirstByteMs),"maxLoadTimeMs":Math.min(g,a.maxTimeToFirstByteMs)})}}var v=a.errorRetry||a.timeoutRetry||{},m={"loadPolicy":a,"timeout":a.maxLoadTimeMs,"maxRetry":v.maxNumRetry||0,"retryDelay":v.retryDelayMs||0,"maxRetryDelay":v.maxRetryDelayMs||0},y={"onSuccess":function onSuccess(t,r,a,i){var l=o.getInternalLoader(a);o.resetInternalLoader(a.type);var u=t.data;0===u.indexOf("#EXTM3U")?(r.parsing.start=performance.now(),Le.isMediaPlaylist(u)?o.handleTrackOrLevelPlaylist(t,r,a,i||null,l):o.handleMasterPlaylist(t,r,a,i)):o.handleManifestParsingError(t,a,new Error("no EXTM3U delimiter"),i||null,r)},"onError":function onError(t,r,a,i){o.handleNetworkError(r,a,!1,t,i)},"onTimeout":function onTimeout(t,r,a){o.handleNetworkError(r,a,!0,void 0,t)}};u.load(t,m,y)}},{"key":"handleMasterPlaylist","value":function handleMasterPlaylist(t,r,a,i){var o=this.hls,l=t.data,u=getResponseUrl(t,a),c=Le.parseMasterPlaylist(l,u);if(c.playlistParsingError)this.handleManifestParsingError(t,a,c.playlistParsingError,i,r);else{var d=c.contentSteering,h=c.levels,g=c.sessionData,v=c.sessionKeys,m=c.startTimeOffset,y=c.variableList;this.variableList=y;var p=Le.parseMasterPlaylistMedia(l,u,c),T=p.AUDIO,E=void 0===T?[]:T,k=p.SUBTITLES,S=p["CLOSED-CAPTIONS"];if(E.length)E.some((function(t){return!t.url}))||!h[0].audioCodec||h[0].attrs.AUDIO||(w.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),E.unshift({"type":"main","name":"main","groupId":"main","default":!1,"autoselect":!1,"forced":!1,"id":-1,"attrs":new O({}),"bitrate":0,"url":""}));o.trigger(I.MANIFEST_LOADED,{"levels":h,"audioTracks":E,"subtitles":k,"captions":S,"contentSteering":d,"url":u,"stats":r,"networkDetails":i,"sessionData":g,"sessionKeys":v,"startTimeOffset":m,"variableList":y})}}},{"key":"handleTrackOrLevelPlaylist","value":function handleTrackOrLevelPlaylist(t,r,a,i,o){var l=this.hls,u=a.id,c=a.level,d=a.type,h=getResponseUrl(t,a),g=R(u)?u:0,v=R(c)?c:g,m=mapContextToLevelType(a),y=Le.parseLevelPlaylist(t.data,h,v,m,g,this.variableList);if(d===Ae.MANIFEST){var p={"attrs":new O({}),"bitrate":0,"details":y,"name":"","url":h};l.trigger(I.MANIFEST_LOADED,{"levels":[p],"audioTracks":[],"url":h,"stats":r,"networkDetails":i,"sessionData":null,"sessionKeys":null,"contentSteering":null,"startTimeOffset":null,"variableList":null})}r.parsing.end=performance.now(),a.levelDetails=y,this.handlePlaylistLoaded(y,t,r,a,i,o)}},{"key":"handleManifestParsingError","value":function handleManifestParsingError(t,r,a,i,o){this.hls.trigger(I.ERROR,{"type":D.NETWORK_ERROR,"details":b.MANIFEST_PARSING_ERROR,"fatal":r.type===Ae.MANIFEST,"url":t.url,"err":a,"error":a,"reason":a.message,"response":t,"context":r,"networkDetails":i,"stats":o})}},{"key":"handleNetworkError","value":function handleNetworkError(t,r){var a=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0,l="A network ".concat(a?"timeout":"error"+(i?" (status "+i.code+")":"")," occurred while loading ").concat(t.type);t.type===Ae.LEVEL?l+=": ".concat(t.level," id: ").concat(t.id):t.type!==Ae.AUDIO_TRACK&&t.type!==Ae.SUBTITLE_TRACK||(l+=" id: ".concat(t.id,' group-id: "').concat(t.groupId,'"'));var u=new Error(l);w.warn("[playlist-loader]: ".concat(l));var c=b.UNKNOWN,d=!1,h=this.getInternalLoader(t);switch(t.type){case Ae.MANIFEST:c=a?b.MANIFEST_LOAD_TIMEOUT:b.MANIFEST_LOAD_ERROR,d=!0;break;case Ae.LEVEL:c=a?b.LEVEL_LOAD_TIMEOUT:b.LEVEL_LOAD_ERROR,d=!1;break;case Ae.AUDIO_TRACK:c=a?b.AUDIO_TRACK_LOAD_TIMEOUT:b.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case Ae.SUBTITLE_TRACK:c=a?b.SUBTITLE_TRACK_LOAD_TIMEOUT:b.SUBTITLE_LOAD_ERROR,d=!1}h&&this.resetInternalLoader(t.type);var g={"type":D.NETWORK_ERROR,"details":c,"fatal":d,"url":t.url,"loader":h,"context":t,"error":u,"networkDetails":r,"stats":o};if(i){var v=(null==r?void 0:r.url)||t.url;g.response=_objectSpread2({"url":v,"data":void 0},i)}this.hls.trigger(I.ERROR,g)}},{"key":"handlePlaylistLoaded","value":function handlePlaylistLoaded(t,r,a,i,o,l){var u=this.hls,c=i.type,d=i.level,h=i.id,g=i.groupId,v=i.deliveryDirectives,m=getResponseUrl(r,i),y=mapContextToLevelType(i),p="number"==typeof i.level&&y===Re.MAIN?d:void 0;if(t.fragments.length){t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));var T=t.playlistParsingError;if(T)u.trigger(I.ERROR,{"type":D.NETWORK_ERROR,"details":b.LEVEL_PARSING_ERROR,"fatal":!1,"url":m,"error":T,"reason":T.message,"response":r,"context":i,"level":p,"parent":y,"networkDetails":o,"stats":a});else switch(t.live&&l&&(l.getCacheAge&&(t.ageHeader=l.getCacheAge()||0),l.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),c){case Ae.MANIFEST:case Ae.LEVEL:u.trigger(I.LEVEL_LOADED,{"details":t,"level":p||0,"id":h||0,"stats":a,"networkDetails":o,"deliveryDirectives":v});break;case Ae.AUDIO_TRACK:u.trigger(I.AUDIO_TRACK_LOADED,{"details":t,"id":h||0,"groupId":g||"","stats":a,"networkDetails":o,"deliveryDirectives":v});break;case Ae.SUBTITLE_TRACK:u.trigger(I.SUBTITLE_TRACK_LOADED,{"details":t,"id":h||0,"groupId":g||"","stats":a,"networkDetails":o,"deliveryDirectives":v})}}else{var E=new Error("No Segments found in Playlist");u.trigger(I.ERROR,{"type":D.NETWORK_ERROR,"details":b.LEVEL_EMPTY_ERROR,"fatal":!1,"url":m,"error":E,"reason":E.message,"response":r,"context":i,"level":p,"parent":y,"networkDetails":o,"stats":a})}}}]),PlaylistLoader}();function sendAddTrackEvent(t,r){var a;try{a=new Event("addtrack")}catch(t){(a=document.createEvent("Event")).initEvent("addtrack",!1,!1)}a.track=t,r.dispatchEvent(a)}function addCueToTrack(t,r){var a=t.mode;if("disabled"===a&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(r.id))try{if(t.addCue(r),!t.cues.getCueById(r.id))throw new Error("addCue is failed for: ".concat(r))}catch(a){w.debug("[texttrack-utils]: ".concat(a));var i=new self.TextTrackCue(r.startTime,r.endTime,r.text);i.id=r.id,t.addCue(i)}"disabled"===a&&(t.mode=a)}function clearCurrentCues(t){var r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues)for(var a=t.cues.length;a--;)t.removeCue(t.cues[a]);"disabled"===r&&(t.mode=r)}function removeCuesInRange(t,r,a,i){var o=t.mode;if("disabled"===o&&(t.mode="hidden"),t.cues&&t.cues.length>0)for(var l=function getCuesInRange(t,r,a){var i=[],o=function getFirstCueIndexAfterTime(t,r){if(r<t[0].startTime)return 0;var a=t.length-1;if(r>t[a].endTime)return-1;var i=0,o=a;for(;i<=o;){var l=Math.floor((o+i)/2);if(r<t[l].startTime)o=l-1;else{if(!(r>t[l].startTime&&i<a))return l;i=l+1}}return t[i].startTime-r<r-t[o].startTime?i:o}(t,r);if(o>-1)for(var l=o,u=t.length;l<u;l++){var c=t[l];if(c.startTime>=r&&c.endTime<=a)i.push(c);else if(c.startTime>a)return i}return i}(t.cues,r,a),u=0;u<l.length;u++)i&&!i(l[u])||t.removeCue(l[u]);"disabled"===o&&(t.mode=o)}var De="org.id3",be="com.apple.quicktime.HLS",Ce="https://aomedia.org/emsg/ID3";function getCueClass(){if("undefined"!=typeof self)return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}var Pe=function(){var t=getCueClass();try{new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}();function dateRangeDateToTimelineSeconds(t,r){return t.getTime()/1e3-r}var _e=function(){function ID3TrackController(t){(0,m.Z)(this,ID3TrackController),this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=t,this._registerListeners()}return(0,y.Z)(ID3TrackController,[{"key":"destroy","value":function destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}},{"key":"_registerListeners","value":function _registerListeners(){var t=this.hls;t.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(I.LEVEL_UPDATED,this.onLevelUpdated,this)}},{"key":"_unregisterListeners","value":function _unregisterListeners(){var t=this.hls;t.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(I.LEVEL_UPDATED,this.onLevelUpdated,this)}},{"key":"onMediaAttached","value":function onMediaAttached(t,r){this.media=r.media}},{"key":"onMediaDetaching","value":function onMediaDetaching(){this.id3Track&&(clearCurrentCues(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}},{"key":"onManifestLoading","value":function onManifestLoading(){this.dateRangeCuesAppended={}}},{"key":"createTrack","value":function createTrack(t){var r=this.getID3Track(t.textTracks);return r.mode="hidden",r}},{"key":"getID3Track","value":function getID3Track(t){if(this.media){for(var r=0;r<t.length;r++){var a=t[r];if("metadata"===a.kind&&"id3"===a.label)return sendAddTrackEvent(a,this.media),a}return this.media.addTextTrack("metadata","id3")}}},{"key":"onFragParsingMetadata","value":function onFragParsingMetadata(t,r){if(this.media){var a=this.hls.config,i=a.enableEmsgMetadataCues,o=a.enableID3MetadataCues;if(i||o){var l=r.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));for(var u=getCueClass(),c=0;c<l.length;c++){var d=l[c].type;if((d!==Ce||i)&&o){var h=re(l[c].data);if(h){var g=l[c].pts,v=g+l[c].duration;v>Pe&&(v=Pe),v-g<=0&&(v=g+.25);for(var m=0;m<h.length;m++){var y=h[m];if(!ee(y)){this.updateId3CueEnds(g);var p=new u(g,v,"");p.value=y,d&&(p.type=d),this.id3Track.addCue(p)}}}}}}}}},{"key":"updateId3CueEnds","value":function updateId3CueEnds(t){var r,a=null==(r=this.id3Track)?void 0:r.cues;if(a)for(var i=a.length;i--;){var o=a[i];o.startTime<t&&o.endTime===Pe&&(o.endTime=t)}}},{"key":"onBufferFlushing","value":function onBufferFlushing(t,r){var a=r.startOffset,i=r.endOffset,o=r.type,l=this.id3Track,u=this.hls;if(u){var c=u.config,d=c.enableEmsgMetadataCues,h=c.enableID3MetadataCues;if(l&&(d||h))removeCuesInRange(l,a,i,"audio"===o?function predicate(t){return t.type===De&&h}:"video"===o?function predicate(t){return t.type===Ce&&d}:function predicate(t){return t.type===De&&h||t.type===Ce&&d})}}},{"key":"onLevelUpdated","value":function onLevelUpdated(t,r){var a=this,i=r.details;if(this.media&&i.hasProgramDateTime&&this.hls.config.enableDateRangeMetadataCues){var o=this.dateRangeCuesAppended,l=this.id3Track,u=i.dateRanges,c=Object.keys(u);if(l)for(var d=Object.keys(o).filter((function(t){return!c.includes(t)})),h=function _loop(){var t=d[g];Object.keys(o[t].cues).forEach((function(r){l.removeCue(o[t].cues[r])})),delete o[t]},g=d.length;g--;)h();var v=i.fragments[i.fragments.length-1];if(0!==c.length&&R(null==v?void 0:v.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var m=v.programDateTime/1e3-v.start,y=getCueClass(),p=function _loop2(){var t=c[T],r=u[t],i=o[t],l=(null==i?void 0:i.cues)||{},d=(null==i?void 0:i.durationKnown)||!1,h=dateRangeDateToTimelineSeconds(r.startDate,m),g=Pe,v=r.endDate;if(v)g=dateRangeDateToTimelineSeconds(v,m),d=!0;else if(r.endOnNext&&!d){var p=c.reduce((function(t,a){var i=u[a];return i.class===r.class&&i.id!==a&&i.startDate>r.startDate&&t.push(i),t}),[]).sort((function(t,r){return t.startDate.getTime()-r.startDate.getTime()}))[0];p&&(g=dateRangeDateToTimelineSeconds(p.startDate,m),d=!0)}for(var E,k,S=Object.keys(r.attr),L=0;L<S.length;L++){var A=S[L];if("ID"!==(k=A)&&"CLASS"!==k&&"START-DATE"!==k&&"DURATION"!==k&&"END-DATE"!==k&&"END-ON-NEXT"!==k){var R=l[A];if(R)d&&!i.durationKnown&&(R.endTime=g);else{var I=r.attr[A];R=new y(h,g,""),isSCTE35Attribute(A)&&(E=I,I=Uint8Array.from(E.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer),R.value={"key":A,"data":I},R.type=be,R.id=t,a.id3Track.addCue(R),l[A]=R}}}o[t]={"cues":l,"dateRange":r,"durationKnown":d}},T=0;T<c.length;T++)p()}}}}]),ID3TrackController}(),we=function(){function LatencyController(t){var r=this;(0,m.Z)(this,LatencyController),this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=function(){return r.timeupdate()},this.hls=t,this.config=t.config,this.registerListeners()}return(0,y.Z)(LatencyController,[{"key":"latency","get":function get(){return this._latency||0}},{"key":"maxLatency","get":function get(){var t=this.config,r=this.levelDetails;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:r?t.liveMaxLatencyDurationCount*r.targetduration:0}},{"key":"targetLatency","get":function get(){var t=this.levelDetails;if(null===t)return null;var r=t.holdBack,a=t.partHoldBack,i=t.targetduration,o=this.config,l=o.liveSyncDuration,u=o.liveSyncDurationCount,c=o.lowLatencyMode,d=this.hls.userConfig,h=c&&a||r;(d.liveSyncDuration||d.liveSyncDurationCount||0===h)&&(h=void 0!==l?l:u*i);var g=i;return h+Math.min(1*this.stallCount,g)}},{"key":"liveSyncPosition","get":function get(){var t=this.estimateLiveEdge(),r=this.targetLatency,a=this.levelDetails;if(null===t||null===r||null===a)return null;var i=a.edge,o=t-r-this.edgeStalled,l=i-a.totalduration,u=i-(this.config.lowLatencyMode&&a.partTarget||a.targetduration);return Math.min(Math.max(l,o),u)}},{"key":"drift","get":function get(){var t=this.levelDetails;return null===t?1:t.drift}},{"key":"edgeStalled","get":function get(){var t=this.levelDetails;if(null===t)return 0;var r=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-r,0)}},{"key":"forwardBufferLength","get":function get(){var t=this.media,r=this.levelDetails;if(!t||!r)return 0;var a=t.buffered.length;return(a?t.buffered.end(a-1):r.edge)-this.currentTime}},{"key":"destroy","value":function destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}},{"key":"registerListeners","value":function registerListeners(){this.hls.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(I.ERROR,this.onError,this)}},{"key":"unregisterListeners","value":function unregisterListeners(){this.hls.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(I.ERROR,this.onError,this)}},{"key":"onMediaAttached","value":function onMediaAttached(t,r){this.media=r.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}},{"key":"onMediaDetaching","value":function onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}},{"key":"onManifestLoading","value":function onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}},{"key":"onLevelUpdated","value":function onLevelUpdated(t,r){var a=r.details;this.levelDetails=a,a.advanced&&this.timeupdate(),!a.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}},{"key":"onError","value":function onError(t,r){var a;r.details===b.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(a=this.levelDetails)&&a.live&&w.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}},{"key":"timeupdate","value":function timeupdate(){var t=this.media,r=this.levelDetails;if(t&&r){this.currentTime=t.currentTime;var a=this.computeLatency();if(null!==a){this._latency=a;var i=this.config,o=i.lowLatencyMode,l=i.maxLiveSyncPlaybackRate;if(o&&1!==l){var u=this.targetLatency;if(null!==u){var c=a-u,d=c<Math.min(this.maxLatency,u+r.targetduration);if(r.live&&d&&c>.05&&this.forwardBufferLength>1){var h=Math.min(2,Math.max(1,l)),g=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20;t.playbackRate=Math.min(h,Math.max(1,g))}else 1!==t.playbackRate&&0!==t.playbackRate&&(t.playbackRate=1)}}}}}},{"key":"estimateLiveEdge","value":function estimateLiveEdge(){var t=this.levelDetails;return null===t?null:t.edge+t.age}},{"key":"computeLatency","value":function computeLatency(){var t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}]),LatencyController}(),Me=["NONE","TYPE-0","TYPE-1",null],xe={"No":"","Yes":"YES","v2":"v2"};var Fe=function(){function HlsUrlParameters(t,r,a){(0,m.Z)(this,HlsUrlParameters),this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=r,this.skip=a}return(0,y.Z)(HlsUrlParameters,[{"key":"addDirectives","value":function addDirectives(t){var r=new self.URL(t);return void 0!==this.msn&&r.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&r.searchParams.set("_HLS_part",this.part.toString()),this.skip&&r.searchParams.set("_HLS_skip",this.skip),r.href}}]),HlsUrlParameters}(),Oe=function(){function Level(t){(0,m.Z)(this,Level),this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.unknownCodecs=void 0,this.audioGroupIds=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.textGroupIds=void 0,this.url=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.unknownCodecs=t.unknownCodecs,this.codecSet=[t.videoCodec,t.audioCodec].filter((function(t){return t})).join(",").replace(/\.[^.,]+/g,"")}return(0,y.Z)(Level,[{"key":"maxBitrate","get":function get(){return Math.max(this.realBitrate,this.bitrate)}},{"key":"attrs","get":function get(){return this._attrs[this._urlId]}},{"key":"pathwayId","get":function get(){return this.attrs["PATHWAY-ID"]||"."}},{"key":"uri","get":function get(){return this.url[this._urlId]||""}},{"key":"urlId","get":function get(){return this._urlId},"set":function set(t){var r=t%this.url.length;this._urlId!==r&&(this.fragmentError=0,this.loadError=0,this.details=void 0,this._urlId=r)}},{"key":"audioGroupId","get":function get(){var t;return null==(t=this.audioGroupIds)?void 0:t[this.urlId]}},{"key":"textGroupId","get":function get(){var t;return null==(t=this.textGroupIds)?void 0:t[this.urlId]}},{"key":"addFallback","value":function addFallback(t){this.url.push(t.url),this._attrs.push(t.attrs)}}]),Level}();function updateFromToPTS(t,r){var a=r.startPTS;if(R(a)){var i,o=0;r.sn>t.sn?(o=a-t.start,i=t):(o=t.start-a,i=r),i.duration!==o&&(i.duration=o)}else if(r.sn>t.sn){t.cc===r.cc&&t.minEndPTS?r.start=t.start+(t.minEndPTS-t.start):r.start=t.start+t.duration}else r.start=Math.max(t.start-r.duration,0)}function updateFragPTSDTS(t,r,a,i,o,l){i-a<=0&&(w.warn("Fragment should have a positive duration",r),i=a+r.duration,l=o+r.duration);var u=a,c=i,d=r.startPTS,h=r.endPTS;if(R(d)){var g=Math.abs(d-a);R(r.deltaPTS)?r.deltaPTS=Math.max(g,r.deltaPTS):r.deltaPTS=g,u=Math.max(a,d),a=Math.min(a,d),o=Math.min(o,r.startDTS),c=Math.min(i,h),i=Math.max(i,h),l=Math.max(l,r.endDTS)}var v=a-r.start;0!==r.start&&(r.start=a),r.duration=i-r.start,r.startPTS=a,r.maxStartPTS=u,r.startDTS=o,r.endPTS=i,r.minEndPTS=c,r.endDTS=l;var m,y=r.sn;if(!t||y<t.startSN||y>t.endSN)return 0;var p=y-t.startSN,T=t.fragments;for(T[p]=r,m=p;m>0;m--)updateFromToPTS(T[m],T[m-1]);for(m=p;m<T.length-1;m++)updateFromToPTS(T[m],T[m+1]);return t.fragmentHint&&updateFromToPTS(T[T.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,v}function mergeDetails(t,r){for(var a=null,i=t.fragments,o=i.length-1;o>=0;o--){var l=i[o].initSegment;if(l){a=l;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;var u,c=0;(function mapFragmentIntersection(t,r,a){for(var i=r.skippedSegments,o=Math.max(t.startSN,r.startSN)-r.startSN,l=(t.fragmentHint?1:0)+(i?r.endSN:Math.min(t.endSN,r.endSN))-r.startSN,u=r.startSN-t.startSN,c=r.fragmentHint?r.fragments.concat(r.fragmentHint):r.fragments,d=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,h=o;h<=l;h++){var g=d[u+h],v=c[h];i&&!v&&h<i&&(v=r.fragments[h]=g),g&&v&&a(g,v)}}(t,r,(function(t,i){t.relurl&&(c=t.cc-i.cc),R(t.startPTS)&&R(t.endPTS)&&(i.start=i.startPTS=t.startPTS,i.startDTS=t.startDTS,i.maxStartPTS=t.maxStartPTS,i.endPTS=t.endPTS,i.endDTS=t.endDTS,i.minEndPTS=t.minEndPTS,i.duration=t.endPTS-t.startPTS,i.duration&&(u=i),r.PTSKnown=r.alignedSliding=!0),i.elementaryStreams=t.elementaryStreams,i.loader=t.loader,i.stats=t.stats,i.urlId=t.urlId,t.initSegment&&(i.initSegment=t.initSegment,a=t.initSegment)})),a)&&(r.fragmentHint?r.fragments.concat(r.fragmentHint):r.fragments).forEach((function(t){var r;t.initSegment&&t.initSegment.relurl!==(null==(r=a)?void 0:r.relurl)||(t.initSegment=a)}));if(r.skippedSegments)if(r.deltaUpdateFailed=r.fragments.some((function(t){return!t})),r.deltaUpdateFailed){w.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var d=r.skippedSegments;d--;)r.fragments.shift();r.startSN=r.fragments[0].sn,r.startCC=r.fragments[0].cc}else r.canSkipDateRanges&&(r.dateRanges=function mergeDateRanges(t,r,a){var i=_extends({},t);a&&a.forEach((function(t){delete i[t]}));return Object.keys(r).forEach((function(t){var a=new N(r[t].attr,i[t]);a.isValid?i[t]=a:w.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'.concat(JSON.stringify(r[t].attr),'"'))})),i}(t.dateRanges,r.dateRanges,r.recentlyRemovedDateranges));var h=r.fragments;if(c){w.warn("discontinuity sliding from playlist, take drift into account");for(var g=0;g<h.length;g++)h[g].cc+=c}r.skippedSegments&&(r.startCC=r.fragments[0].cc),function mapPartIntersection(t,r,a){if(t&&r)for(var i=0,o=0,l=t.length;o<=l;o++){var u=t[o],c=r[o+i];u&&c&&u.index===c.index&&u.fragment.sn===c.fragment.sn?a(u,c):i--}}(t.partList,r.partList,(function(t,r){r.elementaryStreams=t.elementaryStreams,r.stats=t.stats})),u?updateFragPTSDTS(r,u,u.startPTS,u.endPTS,u.startDTS,u.endDTS):adjustSliding(t,r),h.length&&(r.totalduration=r.edge-h[0].start),r.driftStartTime=t.driftStartTime,r.driftStart=t.driftStart;var v=r.advancedDateTime;if(r.advanced&&v){var m=r.edge;r.driftStart||(r.driftStartTime=v,r.driftStart=m),r.driftEndTime=v,r.driftEnd=m}else r.driftEndTime=t.driftEndTime,r.driftEnd=t.driftEnd,r.advancedDateTime=t.advancedDateTime}function adjustSliding(t,r){var a=r.startSN+r.skippedSegments-t.startSN,i=t.fragments;a<0||a>=i.length||addSliding(r,i[a].start)}function addSliding(t,r){if(r){for(var a=t.fragments,i=t.skippedSegments;i<a.length;i++)a[i].start+=r;t.fragmentHint&&(t.fragmentHint.start+=r)}}function getPartWith(t,r,a){var i;return null!=t&&t.details?findPart(null==(i=t.details)?void 0:i.partList,r,a):null}function findPart(t,r,a){if(t)for(var i=t.length;i--;){var o=t[i];if(o.index===a&&o.fragment.sn===r)return o}return null}function isTimeoutError(t){switch(t.details){case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_TIMEOUT:case b.LEVEL_LOAD_TIMEOUT:case b.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function getRetryConfig(t,r){var a=isTimeoutError(r);return t.default["".concat(a?"timeout":"error","Retry")]}function getRetryDelay(t,r){var a="linear"===t.backoff?1:Math.pow(2,r);return Math.min(a*t.retryDelayMs,t.maxRetryDelayMs)}function getLoaderConfigWithoutReties(t){return _objectSpread2(_objectSpread2({},t),{"errorRetry":null,"timeoutRetry":null})}function shouldRetry(t,r,a,i){return!!t&&r<t.maxNumRetry&&(function retryForHttpStatus(t){return 0===t&&!1===navigator.onLine||!!t&&(t<400||t>499)}(i)||!!a)}var Ne={"search":function search(t,r){for(var a=0,i=t.length-1,o=null,l=null;a<=i;){var u=r(l=t[o=(a+i)/2|0]);if(u>0)a=o+1;else{if(!(u<0))return l;i=o-1}}return null}};function findFragmentByPTS(t,r){var a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,o=null;if(t?o=r[t.sn-r[0].sn+1]||null:0===a&&0===r[0].start&&(o=r[0]),o&&0===fragmentWithinToleranceTest(a,i,o))return o;var l=Ne.search(r,fragmentWithinToleranceTest.bind(null,a,i));return!l||l===t&&o?o:l}function fragmentWithinToleranceTest(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,a=arguments.length>2?arguments[2]:void 0;if(a.start<=t&&a.start+a.duration>t)return 0;var i=Math.min(r,a.duration+(a.deltaPTS?a.deltaPTS:0));return a.start+a.duration-i<=t?1:a.start-i>t&&a.start?-1:0}function pdtWithinToleranceTest(t,r,a){var i=1e3*Math.min(r,a.duration+(a.deltaPTS?a.deltaPTS:0));return(a.endProgramDateTime||0)-i>t}var Ue=3e5,Be=0,Ge=2,Ke=5,He=0,Ve=1,We=2,Ze=function(){function ErrorController(t){(0,m.Z)(this,ErrorController),this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=t,this.log=w.log.bind(w,"[info]:"),this.warn=w.warn.bind(w,"[warning]:"),this.error=w.error.bind(w,"[error]:"),this.registerListeners()}return(0,y.Z)(ErrorController,[{"key":"registerListeners","value":function registerListeners(){var t=this.hls;t.on(I.ERROR,this.onError,this),t.on(I.MANIFEST_LOADING,this.onManifestLoading,this)}},{"key":"unregisterListeners","value":function unregisterListeners(){var t=this.hls;t&&(t.off(I.ERROR,this.onError,this),t.off(I.ERROR,this.onErrorOut,this),t.off(I.MANIFEST_LOADING,this.onManifestLoading,this))}},{"key":"destroy","value":function destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}},{"key":"startLoad","value":function startLoad(t){this.playlistError=0}},{"key":"stopLoad","value":function stopLoad(){}},{"key":"getVariantLevelIndex","value":function getVariantLevelIndex(t){return(null==t?void 0:t.type)===Re.MAIN?t.level:this.hls.loadLevel}},{"key":"onManifestLoading","value":function onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}},{"key":"onError","value":function onError(t,r){var a;if(!r.fatal){var i=this.hls,o=r.context;switch(r.details){case b.FRAG_LOAD_ERROR:case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_ERROR:case b.KEY_LOAD_TIMEOUT:return void(r.errorAction=this.getFragRetryOrSwitchAction(r));case b.FRAG_GAP:case b.FRAG_PARSING_ERROR:case b.FRAG_DECRYPT_ERROR:return r.errorAction=this.getFragRetryOrSwitchAction(r),void(r.errorAction.action=Ge);case b.LEVEL_EMPTY_ERROR:case b.LEVEL_PARSING_ERROR:var l,u,c=r.parent===Re.MAIN?r.level:i.loadLevel;return void(r.details===b.LEVEL_EMPTY_ERROR&&null!=(l=r.context)&&null!=(u=l.levelDetails)&&u.live?r.errorAction=this.getPlaylistRetryOrSwitchAction(r,c):(r.levelRetry=!1,r.errorAction=this.getLevelSwitchAction(r,c)));case b.LEVEL_LOAD_ERROR:case b.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==o?void 0:o.level)&&(r.errorAction=this.getPlaylistRetryOrSwitchAction(r,o.level)));case b.AUDIO_TRACK_LOAD_ERROR:case b.AUDIO_TRACK_LOAD_TIMEOUT:case b.SUBTITLE_LOAD_ERROR:case b.SUBTITLE_TRACK_LOAD_TIMEOUT:if(o){var d=i.levels[i.loadLevel];if(d&&(o.type===Ae.AUDIO_TRACK&&o.groupId===d.audioGroupId||o.type===Ae.SUBTITLE_TRACK&&o.groupId===d.textGroupId))return r.errorAction=this.getPlaylistRetryOrSwitchAction(r,i.loadLevel),r.errorAction.action=Ge,void(r.errorAction.flags=Ve)}return;case b.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:var h=i.levels[i.loadLevel],g=null==h?void 0:h.attrs["HDCP-LEVEL"];return void(g&&(r.errorAction={"action":Ge,"flags":We,"hdcpLevel":g}));case b.BUFFER_ADD_CODEC_ERROR:case b.REMUX_ALLOC_ERROR:return void(r.errorAction=this.getLevelSwitchAction(r,null!=(a=r.level)?a:i.loadLevel));case b.INTERNAL_EXCEPTION:case b.BUFFER_APPENDING_ERROR:case b.BUFFER_APPEND_ERROR:case b.BUFFER_FULL_ERROR:case b.LEVEL_SWITCH_ERROR:case b.BUFFER_STALLED_ERROR:case b.BUFFER_SEEK_OVER_HOLE:case b.BUFFER_NUDGE_ON_STALL:return void(r.errorAction={"action":Be,"flags":He})}if(r.type===D.KEY_SYSTEM_ERROR){var v=this.getVariantLevelIndex(r.frag);return r.levelRetry=!1,void(r.errorAction=this.getLevelSwitchAction(r,v))}}}},{"key":"getPlaylistRetryOrSwitchAction","value":function getPlaylistRetryOrSwitchAction(t,r){var a,i,o=getRetryConfig(this.hls.config.playlistLoadPolicy,t),l=this.playlistError++,u=null==(a=t.response)?void 0:a.code;return shouldRetry(o,l,isTimeoutError(t),u)?{"action":Ke,"flags":He,"retryConfig":o,"retryCount":l}:null!=(i=t.context)&&i.deliveryDirectives?{"action":Be,"flags":He,"retryConfig":o||{"maxNumRetry":0,"retryDelayMs":0,"maxRetryDelayMs":0},"retryCount":l}:this.getLevelSwitchAction(t,r)}},{"key":"getFragRetryOrSwitchAction","value":function getFragRetryOrSwitchAction(t){var r=this.hls,a=this.getVariantLevelIndex(t.frag),i=r.levels[a],o=r.config,l=o.fragLoadPolicy,u=o.keyLoadPolicy,c=getRetryConfig(t.details.startsWith("key")?u:l,t),d=r.levels.reduce((function(t,r){return t+r.fragmentError}),0);if(i){var h;t.details!==b.FRAG_GAP&&i.fragmentError++;var g=null==(h=t.response)?void 0:h.code;if(shouldRetry(c,d,isTimeoutError(t),g))return{"action":Ke,"flags":He,"retryConfig":c,"retryCount":d}}var v=this.getLevelSwitchAction(t,a);return c&&(v.retryConfig=c,v.retryCount=d),v}},{"key":"getLevelSwitchAction","value":function getLevelSwitchAction(t,r){var a=this.hls;null==r&&(r=a.loadLevel);var i=this.hls.levels[r];if(i&&(i.loadError++,a.autoLevelEnabled)){for(var o,l,u=-1,c=a.levels,d=null==(o=t.frag)?void 0:o.type,h=null!=(l=t.context)?l:{},g=h.type,v=h.groupId,m=c.length;m--;){var y=(m+a.loadLevel)%c.length;if(y!==a.loadLevel&&0===c[y].loadError){var p=c[y];if(t.details===b.FRAG_GAP&&t.frag){var T=c[y].details;if(T){var E=findFragmentByPTS(t.frag,T.fragments,t.frag.start);if(null!=E&&E.gap)continue}}else{if(g===Ae.AUDIO_TRACK&&v===p.audioGroupId||g===Ae.SUBTITLE_TRACK&&v===p.textGroupId)continue;if(d===Re.AUDIO&&i.audioGroupId===p.audioGroupId||d===Re.SUBTITLE&&i.textGroupId===p.textGroupId)continue}u=y;break}}if(u>-1&&a.loadLevel!==u)return t.levelRetry=!0,{"action":Ge,"flags":He,"nextAutoLevel":u}}return{"action":Ge,"flags":Ve}}},{"key":"onErrorOut","value":function onErrorOut(t,r){var a;switch(null==(a=r.errorAction)?void 0:a.action){case Be:break;case Ge:this.sendAlternateToPenaltyBox(r),r.errorAction.resolved||r.details===b.FRAG_GAP||(r.fatal=!0)}r.fatal&&this.hls.stopLoad()}},{"key":"sendAlternateToPenaltyBox","value":function sendAlternateToPenaltyBox(t){var r=this.hls,a=t.errorAction;if(a){var i=a.flags,o=a.hdcpLevel,l=a.nextAutoLevel;switch(i){case He:this.switchLevel(t,l);break;case Ve:a.resolved||(a.resolved=this.redundantFailover(t));break;case We:o&&(r.maxHdcpLevel=Me[Me.indexOf(o)-1],a.resolved=!0),this.warn('Restricting playback to HDCP-LEVEL of "'.concat(r.maxHdcpLevel,'" or lower'))}a.resolved||this.switchLevel(t,l)}}},{"key":"switchLevel","value":function switchLevel(t,r){void 0!==r&&t.errorAction&&(this.warn("switching to level ".concat(r," after ").concat(t.details)),this.hls.nextAutoLevel=r,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}},{"key":"redundantFailover","value":function redundantFailover(t){var r=this,a=this.hls,i=this.penalizedRenditions,o=t.parent===Re.MAIN?t.level:a.loadLevel,l=a.levels[o],u=l.url.length,c=t.frag?t.frag.urlId:l.urlId;l.urlId!==c||t.frag&&!l.details||this.penalizeRendition(l,t);for(var d=function _loop3(){var d=(c+h)%u,g=i[d];if(!g||function checkExpired(t,r,a){if(performance.now()-t.lastErrorPerfMs>Ue)return!0;var i=t.details;if(r.details===b.FRAG_GAP&&i&&r.frag){var o=r.frag.start,l=findFragmentByPTS(null,i.fragments,o);if(l&&!l.gap)return!0}if(a&&t.errors.length<a.errors.length){var u=t.errors[t.errors.length-1];if(i&&u.frag&&r.frag&&Math.abs(u.frag.start-r.frag.start)>3*i.targetduration)return!0}return!1}(g,t,i[c]))return r.warn("Switching to Redundant Stream ".concat(d+1,"/").concat(u,': "').concat(l.url[d],'" after ').concat(t.details)),r.playlistError=0,a.levels.forEach((function(t){t.urlId=d})),a.nextLoadLevel=o,{"v":!0}},h=1;h<u;h++){var g=d();if("object"==typeof g)return g.v}return!1}},{"key":"penalizeRendition","value":function penalizeRendition(t,r){var a=this.penalizedRenditions,i=a[t.urlId]||{"lastErrorPerfMs":0,"errors":[],"details":void 0};i.lastErrorPerfMs=performance.now(),i.errors.push(r),i.details=t.details,a[t.urlId]=i}}]),ErrorController}();var Ye,je=function(){function BasePlaylistController(t,r){(0,m.Z)(this,BasePlaylistController),this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=w.log.bind(w,"".concat(r,":")),this.warn=w.warn.bind(w,"".concat(r,":")),this.hls=t}return(0,y.Z)(BasePlaylistController,[{"key":"destroy","value":function destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}},{"key":"clearTimer","value":function clearTimer(){clearTimeout(this.timer),this.timer=-1}},{"key":"startLoad","value":function startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}},{"key":"stopLoad","value":function stopLoad(){this.canLoad=!1,this.clearTimer()}},{"key":"switchParams","value":function switchParams(t,r){var a=null==r?void 0:r.renditionReports;if(a){for(var i=-1,o=0;o<a.length;o++){var l=a[o],u=void 0;try{u=new self.URL(l.URI,r.url).href}catch(t){w.warn("Could not construct new URL for Rendition Report: ".concat(t)),u=l.URI||""}if(u===t){i=o;break}u===t.substring(0,u.length)&&(i=o)}if(-1!==i){var c=a[i],d=parseInt(c["LAST-MSN"])||(null==r?void 0:r.lastPartSn),h=parseInt(c["LAST-PART"])||(null==r?void 0:r.lastPartIndex);if(this.hls.config.lowLatencyMode){var g=Math.min(r.age-r.partTarget,r.targetduration);h>=0&&g>r.partTarget&&(h+=1)}return new Fe(d,h>=0?h:void 0,xe.No)}}}},{"key":"loadPlaylist","value":function loadPlaylist(t){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}},{"key":"shouldLoadPlaylist","value":function shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}},{"key":"shouldReloadPlaylist","value":function shouldReloadPlaylist(t){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(t)}},{"key":"playlistLoaded","value":function playlistLoaded(t,r,a){var i=this,o=r.details,l=r.stats,u=self.performance.now(),c=l.loading.first?Math.max(0,u-l.loading.first):0;if(o.advancedDateTime=Date.now()-c,o.live||null!=a&&a.live){if(o.reloaded(a),a&&this.log("live playlist ".concat(t," ").concat(o.advanced?"REFRESHED "+o.lastPartSn+"-"+o.lastPartIndex:"MISSED")),a&&o.fragments.length>0&&mergeDetails(a,o),!this.canLoad||!o.live)return;var d,h=void 0,g=void 0;if(o.canBlockReload&&o.endSN&&o.advanced){var v=this.hls.config.lowLatencyMode,m=o.lastPartSn,y=o.endSN,p=o.lastPartIndex,T=m===y;-1!==p?(h=T?y+1:m,g=T?v?0:p:p+1):h=y+1;var E=o.age,k=E+o.ageHeader,S=Math.min(k-o.partTarget,1.5*o.targetduration);if(S>0){if(a&&S>a.tuneInGoal)this.warn("CDN Tune-in goal increased from: ".concat(a.tuneInGoal," to: ").concat(S," with playlist age: ").concat(o.age)),S=0;else{var L=Math.floor(S/o.targetduration);if(h+=L,void 0!==g)g+=Math.round(S%o.targetduration/o.partTarget);this.log("CDN Tune-in age: ".concat(o.ageHeader,"s last advanced ").concat(E.toFixed(2),"s goal: ").concat(S," skip sn ").concat(L," to part ").concat(g))}o.tuneInGoal=S}if(d=this.getDeliveryDirectives(o,r.deliveryDirectives,h,g),v||!T)return void this.loadPlaylist(d)}else o.canBlockReload&&(d=this.getDeliveryDirectives(o,r.deliveryDirectives,h,g));var A=this.hls.mainForwardBufferInfo,R=A?A.end-A.len:0,I=function computeReloadInterval(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,a=1e3*t.targetduration;if(t.updated){var i=t.fragments;if(i.length&&4*a>r){var o=1e3*i[i.length-1].duration;o<a&&(a=o)}}else a/=2;return Math.round(a)}(o,1e3*(o.edge-R));o.updated&&u>this.requestScheduled+I&&(this.requestScheduled=l.loading.start),void 0!==h&&o.canBlockReload?this.requestScheduled=l.loading.first+I-(1e3*o.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+I<u?this.requestScheduled=u:this.requestScheduled-u<=0&&(this.requestScheduled+=I);var D=this.requestScheduled-u;D=Math.max(0,D),this.log("reload live playlist ".concat(t," in ").concat(Math.round(D)," ms")),this.timer=self.setTimeout((function(){return i.loadPlaylist(d)}),D)}else this.clearTimer()}},{"key":"getDeliveryDirectives","value":function getDeliveryDirectives(t,r,a,i){var o=function getSkipValue(t,r){var a=t.canSkipUntil,i=t.canSkipDateRanges,o=t.endSN;return a&&(void 0!==r?r-o:0)<a?i?xe.v2:xe.Yes:xe.No}(t,a);return null!=r&&r.skip&&t.deltaUpdateFailed&&(a=r.msn,i=r.part,o=xe.No),new Fe(a,i,o)}},{"key":"checkRetry","value":function checkRetry(t){var r=this,a=t.details,i=isTimeoutError(t),o=t.errorAction,l=o||{},u=l.action,c=l.retryCount,d=void 0===c?0:c,h=l.retryConfig,g=!!o&&!!h&&(u===Ke||!o.resolved&&u===Ge);if(g){var v;if(this.requestScheduled=-1,i&&null!=(v=t.context)&&v.deliveryDirectives)this.warn("Retrying playlist loading ".concat(d+1,"/").concat(h.maxNumRetry,' after "').concat(a,'" without delivery-directives')),this.loadPlaylist();else{var m=getRetryDelay(h,d);this.timer=self.setTimeout((function(){return r.loadPlaylist()}),m),this.warn("Retrying playlist loading ".concat(d+1,"/").concat(h.maxNumRetry,' after "').concat(a,'" in ').concat(m,"ms"))}t.levelRetry=!0,o.resolved=!0}return g}}]),BasePlaylistController}(),qe=function(t){(0,g.Z)(LevelController,t);var r=(0,v.Z)(LevelController);function LevelController(t,a){var i;return(0,m.Z)(this,LevelController),(i=r.call(this,t,"[level-controller]"))._levels=[],i._firstLevel=-1,i._startLevel=void 0,i.currentLevel=null,i.currentLevelIndex=-1,i.manualLevelIndex=-1,i.steering=void 0,i.onParsedComplete=void 0,i.steering=a,i._registerListeners(),i}return(0,y.Z)(LevelController,[{"key":"_registerListeners","value":function _registerListeners(){var t=this.hls;t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(I.LEVEL_LOADED,this.onLevelLoaded,this),t.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(I.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(I.FRAG_LOADED,this.onFragLoaded,this),t.on(I.ERROR,this.onError,this)}},{"key":"_unregisterListeners","value":function _unregisterListeners(){var t=this.hls;t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(I.LEVEL_LOADED,this.onLevelLoaded,this),t.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(I.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(I.FRAG_LOADED,this.onFragLoaded,this),t.off(I.ERROR,this.onError,this)}},{"key":"destroy","value":function destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),(0,d.Z)((0,h.Z)(LevelController.prototype),"destroy",this).call(this)}},{"key":"startLoad","value":function startLoad(){this._levels.forEach((function(t){t.loadError=0,t.fragmentError=0})),(0,d.Z)((0,h.Z)(LevelController.prototype),"startLoad",this).call(this)}},{"key":"resetLevels","value":function resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[]}},{"key":"onManifestLoading","value":function onManifestLoading(t,r){this.resetLevels()}},{"key":"onManifestLoaded","value":function onManifestLoaded(t,r){var a,i=[],o={};r.levels.forEach((function(t){var r,l=t.attrs;-1!==(null==(r=t.audioCodec)?void 0:r.indexOf("mp4a.40.34"))&&(Ye||(Ye=/chrome|firefox/i.test(navigator.userAgent)),Ye&&(t.audioCodec=void 0));var u=l.AUDIO,c=l.CODECS,d=l["FRAME-RATE"],h=l["PATHWAY-ID"],g=l.RESOLUTION,v=l.SUBTITLES,m="".concat(h||".","-"),y="".concat(m).concat(t.bitrate,"-").concat(g,"-").concat(d,"-").concat(c);(a=o[y])?a.addFallback(t):(a=new Oe(t),o[y]=a,i.push(a)),addGroupId(a,"audio",u),addGroupId(a,"text",v)})),this.filterAndSortMediaOptions(i,r)}},{"key":"filterAndSortMediaOptions","value":function filterAndSortMediaOptions(t,r){var a=this,i=[],o=[],l=!1,u=!1,c=!1,d=t.filter((function(t){var r=t.audioCodec,a=t.videoCodec,i=t.width,o=t.height,d=t.unknownCodecs;return l||(l=!(!i||!o)),u||(u=!!a),c||(c=!!r),!(null!=d&&d.length)&&(!r||isCodecSupportedInMp4(r,"audio"))&&(!a||isCodecSupportedInMp4(a,"video"))}));if((l||u)&&c&&(d=d.filter((function(t){var r=t.videoCodec,a=t.width,i=t.height;return!!r||!(!a||!i)}))),0!==d.length){r.audioTracks&&assignTrackIdsByGroup(i=r.audioTracks.filter((function(t){return!t.audioCodec||isCodecSupportedInMp4(t.audioCodec,"audio")}))),r.subtitles&&assignTrackIdsByGroup(o=r.subtitles);var h=d.slice(0);d.sort((function(t,r){return t.attrs["HDCP-LEVEL"]!==r.attrs["HDCP-LEVEL"]?(t.attrs["HDCP-LEVEL"]||"")>(r.attrs["HDCP-LEVEL"]||"")?1:-1:t.bitrate!==r.bitrate?t.bitrate-r.bitrate:t.attrs["FRAME-RATE"]!==r.attrs["FRAME-RATE"]?t.attrs.decimalFloatingPoint("FRAME-RATE")-r.attrs.decimalFloatingPoint("FRAME-RATE"):t.attrs.SCORE!==r.attrs.SCORE?t.attrs.decimalFloatingPoint("SCORE")-r.attrs.decimalFloatingPoint("SCORE"):l&&t.height!==r.height?t.height-r.height:0}));var g=h[0];if(this.steering&&(d=this.steering.filterParsedLevels(d)).length!==h.length)for(var v=0;v<h.length;v++)if(h[v].pathwayId===d[0].pathwayId){g=h[v];break}this._levels=d;for(var m=0;m<d.length;m++)if(d[m]===g){this._firstLevel=m,this.log("manifest loaded, ".concat(d.length," level(s) found, first bitrate: ").concat(g.bitrate));break}var y=c&&!u,p={"levels":d,"audioTracks":i,"subtitleTracks":o,"sessionData":r.sessionData,"sessionKeys":r.sessionKeys,"firstLevel":this._firstLevel,"stats":r.stats,"audio":c,"video":u,"altAudio":!y&&i.some((function(t){return!!t.url}))};this.hls.trigger(I.MANIFEST_PARSED,p),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}else Promise.resolve().then((function(){if(a.hls){var t=new Error("no level with compatible codecs found in manifest");a.hls.trigger(I.ERROR,{"type":D.MEDIA_ERROR,"details":b.MANIFEST_INCOMPATIBLE_CODECS_ERROR,"fatal":!0,"url":r.url,"error":t,"reason":t.message})}}))}},{"key":"levels","get":function get(){return 0===this._levels.length?null:this._levels}},{"key":"level","get":function get(){return this.currentLevelIndex},"set":function set(t){var r=this._levels;if(0!==r.length){if(t<0||t>=r.length){var a=new Error("invalid level idx"),i=t<0;if(this.hls.trigger(I.ERROR,{"type":D.OTHER_ERROR,"details":b.LEVEL_SWITCH_ERROR,"level":t,"fatal":i,"error":a,"reason":a.message}),i)return;t=Math.min(t,r.length-1)}var o=this.currentLevelIndex,l=this.currentLevel,u=l?l.attrs["PATHWAY-ID"]:void 0,c=r[t],d=c.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=c,o!==t||!c.details||!l||u!==d){this.log("Switching to level ".concat(t).concat(d?" with Pathway "+d:""," from level ").concat(o).concat(u?" with Pathway "+u:""));var h=_extends({},c,{"level":t,"maxBitrate":c.maxBitrate,"attrs":c.attrs,"uri":c.uri,"urlId":c.urlId});delete h._attrs,delete h._urlId,this.hls.trigger(I.LEVEL_SWITCHING,h);var g=c.details;if(!g||g.live){var v=this.switchParams(c.uri,null==l?void 0:l.details);this.loadPlaylist(v)}}}}},{"key":"manualLevel","get":function get(){return this.manualLevelIndex},"set":function set(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}},{"key":"firstLevel","get":function get(){return this._firstLevel},"set":function set(t){this._firstLevel=t}},{"key":"startLevel","get":function get(){if(void 0===this._startLevel){var t=this.hls.config.startLevel;return void 0!==t?t:this._firstLevel}return this._startLevel},"set":function set(t){this._startLevel=t}},{"key":"onError","value":function onError(t,r){!r.fatal&&r.context&&r.context.type===Ae.LEVEL&&r.context.level===this.level&&this.checkRetry(r)}},{"key":"onFragLoaded","value":function onFragLoaded(t,r){var a=r.frag;if(void 0!==a&&a.type===Re.MAIN){var i=this._levels[a.level];void 0!==i&&(i.loadError=0)}}},{"key":"onLevelLoaded","value":function onLevelLoaded(t,r){var a,i,o=r.level,l=r.details,u=this._levels[o];if(!u)return this.warn("Invalid level index ".concat(o)),void(null!=(i=r.deliveryDirectives)&&i.skip&&(l.deltaUpdateFailed=!0));o===this.currentLevelIndex?(0===u.fragmentError&&(u.loadError=0),this.playlistLoaded(o,r,u.details)):null!=(a=r.deliveryDirectives)&&a.skip&&(l.deltaUpdateFailed=!0)}},{"key":"onAudioTrackSwitched","value":function onAudioTrackSwitched(t,r){var a=this.currentLevel;if(a){var i=this.hls.audioTracks[r.id].groupId;if(a.audioGroupIds&&a.audioGroupId!==i){for(var o=-1,l=0;l<a.audioGroupIds.length;l++)if(a.audioGroupIds[l]===i){o=l;break}-1!==o&&o!==a.urlId&&(a.urlId=o,this.canLoad&&this.startLoad())}}}},{"key":"loadPlaylist","value":function loadPlaylist(t){(0,d.Z)((0,h.Z)(LevelController.prototype),"loadPlaylist",this).call(this);var r=this.currentLevelIndex,a=this.currentLevel;if(a&&this.shouldLoadPlaylist(a)){var i=a.urlId,o=a.uri;if(t)try{o=t.addDirectives(o)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: ".concat(t))}var l=a.attrs["PATHWAY-ID"];this.log("Loading level index ".concat(r).concat(void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""," with").concat(l?" Pathway "+l:""," URI ").concat(i+1,"/").concat(a.url.length," ").concat(o)),this.clearTimer(),this.hls.trigger(I.LEVEL_LOADING,{"url":o,"level":r,"id":i,"deliveryDirectives":t||null})}}},{"key":"nextLoadLevel","get":function get(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},"set":function set(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}},{"key":"removeLevel","value":function removeLevel(t,r){var a=this,i=function filterLevelAndGroupByIdIndex(t,a){return a!==r},o=this._levels.filter((function(o,l){return l!==t||(o.url.length>1&&void 0!==r?(o.url=o.url.filter(i),o.audioGroupIds&&(o.audioGroupIds=o.audioGroupIds.filter(i)),o.textGroupIds&&(o.textGroupIds=o.textGroupIds.filter(i)),o.urlId=0,!0):(a.steering&&a.steering.removeLevel(o),!1))}));this.hls.trigger(I.LEVELS_UPDATED,{"levels":o})}},{"key":"onLevelsUpdated","value":function onLevelsUpdated(t,r){var a=r.levels;a.forEach((function(t,r){var a=t.details;null!=a&&a.fragments&&a.fragments.forEach((function(t){t.level=r}))})),this._levels=a}}]),LevelController}(je);function addGroupId(t,r,a){a&&("audio"===r?(t.audioGroupIds||(t.audioGroupIds=[]),t.audioGroupIds[t.url.length-1]=a):"text"===r&&(t.textGroupIds||(t.textGroupIds=[]),t.textGroupIds[t.url.length-1]=a))}function assignTrackIdsByGroup(t){var r={};t.forEach((function(t){var a=t.groupId||"";t.id=r[a]=r[a]||0,r[a]++}))}var ze="NOT_LOADED",Xe="APPENDING",Qe="PARTIAL",$e="OK",Je=function(){function FragmentTracker(t){(0,m.Z)(this,FragmentTracker),this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}return(0,y.Z)(FragmentTracker,[{"key":"_registerListeners","value":function _registerListeners(){var t=this.hls;t.on(I.BUFFER_APPENDED,this.onBufferAppended,this),t.on(I.FRAG_BUFFERED,this.onFragBuffered,this),t.on(I.FRAG_LOADED,this.onFragLoaded,this)}},{"key":"_unregisterListeners","value":function _unregisterListeners(){var t=this.hls;t.off(I.BUFFER_APPENDED,this.onBufferAppended,this),t.off(I.FRAG_BUFFERED,this.onFragBuffered,this),t.off(I.FRAG_LOADED,this.onFragLoaded,this)}},{"key":"destroy","value":function destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}},{"key":"getAppendedFrag","value":function getAppendedFrag(t,r){var a=this.activePartLists[r];if(a)for(var i=a.length;i--;){var o=a[i];if(!o)break;var l=o.end;if(o.start<=t&&null!==l&&t<=l)return o}return this.getBufferedFrag(t,r)}},{"key":"getBufferedFrag","value":function getBufferedFrag(t,r){for(var a=this.fragments,i=Object.keys(a),o=i.length;o--;){var l=a[i[o]];if((null==l?void 0:l.body.type)===r&&l.buffered){var u=l.body;if(u.start<=t&&t<=u.end)return u}}return null}},{"key":"detectEvictedFragments","value":function detectEvictedFragments(t,r,a,i){var o=this;this.timeRanges&&(this.timeRanges[t]=r);var l=(null==i?void 0:i.fragment.sn)||0;Object.keys(this.fragments).forEach((function(i){var u=o.fragments[i];if(u&&!(l>=u.body.sn))if(u.buffered||u.loaded){var c=u.range[t];c&&c.time.some((function(t){var a=!o.isTimeBuffered(t.startPTS,t.endPTS,r);return a&&o.removeFragment(u.body),a}))}else u.body.type===a&&o.removeFragment(u.body)}))}},{"key":"detectPartialFragments","value":function detectPartialFragments(t){var r=this,a=this.timeRanges,i=t.frag,o=t.part;if(a&&"initSegment"!==i.sn){var l=getFragmentKey(i),u=this.fragments[l];if(u){var c=!i.relurl;Object.keys(a).forEach((function(t){var l=i.elementaryStreams[t];if(l){var d=a[t],h=c||!0===l.partial;u.range[t]=r.getBufferedTimes(i,o,h,d)}})),u.loaded=null,Object.keys(u.range).length?(u.buffered=!0,u.body.endList&&(this.endListFragments[u.body.type]=u),isPartial(u)||this.removeParts(i.sn-1,i.type)):this.removeFragment(u.body)}}}},{"key":"removeParts","value":function removeParts(t,r){var a=this.activePartLists[r];a&&(this.activePartLists[r]=a.filter((function(r){return r.fragment.sn>=t})))}},{"key":"fragBuffered","value":function fragBuffered(t,r){var a=getFragmentKey(t),i=this.fragments[a];!i&&r&&(i=this.fragments[a]={"body":t,"appendedPTS":null,"loaded":null,"buffered":!1,"range":Object.create(null)},t.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)}},{"key":"getBufferedTimes","value":function getBufferedTimes(t,r,a,i){for(var o={"time":[],"partial":a},l=t.start,u=t.end,c=t.minEndPTS||u,d=t.maxStartPTS||l,h=0;h<i.length;h++){var g=i.start(h)-this.bufferPadding,v=i.end(h)+this.bufferPadding;if(d>=g&&c<=v){o.time.push({"startPTS":Math.max(l,i.start(h)),"endPTS":Math.min(u,i.end(h))});break}if(l<v&&u>g)o.partial=!0,o.time.push({"startPTS":Math.max(l,i.start(h)),"endPTS":Math.min(u,i.end(h))});else if(u<=g)break}return o}},{"key":"getPartialFragment","value":function getPartialFragment(t){var r,a,i,o=null,l=0,u=this.bufferPadding,c=this.fragments;return Object.keys(c).forEach((function(d){var h=c[d];h&&isPartial(h)&&(a=h.body.start-u,i=h.body.end+u,t>=a&&t<=i&&(r=Math.min(t-a,i-t),l<=r&&(o=h.body,l=r)))})),o}},{"key":"isEndListAppended","value":function isEndListAppended(t){var r=this.endListFragments[t];return void 0!==r&&(r.buffered||isPartial(r))}},{"key":"getState","value":function getState(t){var r=getFragmentKey(t),a=this.fragments[r];return a?a.buffered?isPartial(a)?Qe:$e:Xe:ze}},{"key":"isTimeBuffered","value":function isTimeBuffered(t,r,a){for(var i,o,l=0;l<a.length;l++){if(i=a.start(l)-this.bufferPadding,o=a.end(l)+this.bufferPadding,t>=i&&r<=o)return!0;if(r<=i)return!1}return!1}},{"key":"onFragLoaded","value":function onFragLoaded(t,r){var a=r.frag,i=r.part;if("initSegment"!==a.sn&&!a.bitrateTest){var o=i?null:r,l=getFragmentKey(a);this.fragments[l]={"body":a,"appendedPTS":null,"loaded":o,"buffered":!1,"range":Object.create(null)}}}},{"key":"onBufferAppended","value":function onBufferAppended(t,r){var a=this,i=r.frag,o=r.part,l=r.timeRanges;if("initSegment"!==i.sn){var u=i.type;if(o){var c=this.activePartLists[u];c||(this.activePartLists[u]=c=[]),c.push(o)}this.timeRanges=l,Object.keys(l).forEach((function(t){var r=l[t];a.detectEvictedFragments(t,r,u,o)}))}}},{"key":"onFragBuffered","value":function onFragBuffered(t,r){this.detectPartialFragments(r)}},{"key":"hasFragment","value":function hasFragment(t){var r=getFragmentKey(t);return!!this.fragments[r]}},{"key":"hasParts","value":function hasParts(t){var r;return!(null==(r=this.activePartLists[t])||!r.length)}},{"key":"removeFragmentsInRange","value":function removeFragmentsInRange(t,r,a,i,o){var l=this;i&&!this.hasGaps||Object.keys(this.fragments).forEach((function(u){var c=l.fragments[u];if(c){var d=c.body;d.type!==a||i&&!d.gap||d.start<r&&d.end>t&&(c.buffered||o)&&l.removeFragment(d)}}))}},{"key":"removeFragment","value":function removeFragment(t){var r=getFragmentKey(t);t.stats.loaded=0,t.clearElementaryStreamInfo();var a=this.activePartLists[t.type];if(a){var i=t.sn;this.activePartLists[t.type]=a.filter((function(t){return t.fragment.sn!==i}))}delete this.fragments[r],t.endList&&delete this.endListFragments[t.type]}},{"key":"removeAllFragments","value":function removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}]),FragmentTracker}();function isPartial(t){var r,a;return t.buffered&&(t.body.gap||(null==(r=t.range.video)?void 0:r.partial)||(null==(a=t.range.audio)?void 0:a.partial))}function getFragmentKey(t){return"".concat(t.type,"_").concat(t.level,"_").concat(t.urlId,"_").concat(t.sn)}var et=Math.pow(2,17),tt=function(){function FragmentLoader(t){(0,m.Z)(this,FragmentLoader),this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}return(0,y.Z)(FragmentLoader,[{"key":"destroy","value":function destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}},{"key":"abort","value":function abort(){this.loader&&this.loader.abort()}},{"key":"load","value":function load(t,r){var a=this,i=t.url;if(!i)return Promise.reject(new rt({"type":D.NETWORK_ERROR,"details":b.FRAG_LOAD_ERROR,"fatal":!1,"frag":t,"error":new Error("Fragment does not have a ".concat(i?"part list":"url")),"networkDetails":null}));this.abort();var o=this.config,l=o.fLoader,u=o.loader;return new Promise((function(c,d){if(a.loader&&a.loader.destroy(),t.gap)d(createGapLoadError(t));else{var h=a.loader=t.loader=l?new l(o):new u(o),g=createLoaderContext(t),v=getLoaderConfigWithoutReties(o.fragLoadPolicy.default),m={"loadPolicy":v,"timeout":v.maxLoadTimeMs,"maxRetry":0,"retryDelay":0,"maxRetryDelay":0,"highWaterMark":"initSegment"===t.sn?1/0:et};t.stats=h.stats,h.load(g,m,{"onSuccess":function onSuccess(r,i,o,l){a.resetLoader(t,h);var u=r.data;o.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(u.slice(0,16)),u=u.slice(16)),c({"frag":t,"part":null,"payload":u,"networkDetails":l})},"onError":function onError(r,o,l,u){a.resetLoader(t,h),d(new rt({"type":D.NETWORK_ERROR,"details":b.FRAG_LOAD_ERROR,"fatal":!1,"frag":t,"response":_objectSpread2({"url":i,"data":void 0},r),"error":new Error("HTTP Error ".concat(r.code," ").concat(r.text)),"networkDetails":l,"stats":u}))},"onAbort":function onAbort(r,i,o){a.resetLoader(t,h),d(new rt({"type":D.NETWORK_ERROR,"details":b.INTERNAL_ABORTED,"fatal":!1,"frag":t,"error":new Error("Aborted"),"networkDetails":o,"stats":r}))},"onTimeout":function onTimeout(r,i,o){a.resetLoader(t,h),d(new rt({"type":D.NETWORK_ERROR,"details":b.FRAG_LOAD_TIMEOUT,"fatal":!1,"frag":t,"error":new Error("Timeout after ".concat(m.timeout,"ms")),"networkDetails":o,"stats":r}))},"onProgress":function onProgress(a,i,o,l){r&&r({"frag":t,"part":null,"payload":o,"networkDetails":l})}})}}))}},{"key":"loadPart","value":function loadPart(t,r,a){var i=this;this.abort();var o=this.config,l=o.fLoader,u=o.loader;return new Promise((function(c,d){if(i.loader&&i.loader.destroy(),t.gap||r.gap)d(createGapLoadError(t,r));else{var h=i.loader=t.loader=l?new l(o):new u(o),g=createLoaderContext(t,r),v=getLoaderConfigWithoutReties(o.fragLoadPolicy.default),m={"loadPolicy":v,"timeout":v.maxLoadTimeMs,"maxRetry":0,"retryDelay":0,"maxRetryDelay":0,"highWaterMark":et};r.stats=h.stats,h.load(g,m,{"onSuccess":function onSuccess(o,l,u,d){i.resetLoader(t,h),i.updateStatsFromPart(t,r);var g={"frag":t,"part":r,"payload":o.data,"networkDetails":d};a(g),c(g)},"onError":function onError(a,o,l,u){i.resetLoader(t,h),d(new rt({"type":D.NETWORK_ERROR,"details":b.FRAG_LOAD_ERROR,"fatal":!1,"frag":t,"part":r,"response":_objectSpread2({"url":g.url,"data":void 0},a),"error":new Error("HTTP Error ".concat(a.code," ").concat(a.text)),"networkDetails":l,"stats":u}))},"onAbort":function onAbort(a,o,l){t.stats.aborted=r.stats.aborted,i.resetLoader(t,h),d(new rt({"type":D.NETWORK_ERROR,"details":b.INTERNAL_ABORTED,"fatal":!1,"frag":t,"part":r,"error":new Error("Aborted"),"networkDetails":l,"stats":a}))},"onTimeout":function onTimeout(a,o,l){i.resetLoader(t,h),d(new rt({"type":D.NETWORK_ERROR,"details":b.FRAG_LOAD_TIMEOUT,"fatal":!1,"frag":t,"part":r,"error":new Error("Timeout after ".concat(m.timeout,"ms")),"networkDetails":l,"stats":a}))}})}}))}},{"key":"updateStatsFromPart","value":function updateStatsFromPart(t,r){var a=t.stats,i=r.stats,o=i.total;if(a.loaded+=i.loaded,o){var l=Math.round(t.duration/r.duration),u=Math.min(Math.round(a.loaded/o),l),c=(l-u)*Math.round(a.loaded/u);a.total=a.loaded+c}else a.total=Math.max(a.loaded,a.total);var d=a.loading,h=i.loading;d.start?d.first+=h.first-h.start:(d.start=h.start,d.first=h.first),d.end=h.end}},{"key":"resetLoader","value":function resetLoader(t,r){t.loader=null,this.loader===r&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),r.destroy()}}]),FragmentLoader}();function createLoaderContext(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,a=r||t,i={"frag":t,"part":r,"responseType":"arraybuffer","url":a.url,"headers":{},"rangeStart":0,"rangeEnd":0},o=a.byteRangeStartOffset,l=a.byteRangeEndOffset;if(R(o)&&R(l)){var u,c=o,d=l;if("initSegment"===t.sn&&"AES-128"===(null==(u=t.decryptdata)?void 0:u.method)){var h=l-o;h%16&&(d=l+(16-h%16)),0!==o&&(i.resetIV=!0,c=o-16)}i.rangeStart=c,i.rangeEnd=d}return i}function createGapLoadError(t,r){var a=new Error("GAP ".concat(t.gap?"tag":"attribute"," found")),i={"type":D.MEDIA_ERROR,"details":b.FRAG_GAP,"fatal":!1,"frag":t,"error":a,"networkDetails":null};return r&&(i.part=r),(r||t).stats.aborted=!0,new rt(i)}var rt=function(t){(0,g.Z)(LoadError,t);var r=(0,v.Z)(LoadError);function LoadError(t){var a;return(0,m.Z)(this,LoadError),(a=r.call(this,t.error.message)).data=void 0,a.data=t,a}return(0,y.Z)(LoadError)}((0,c.Z)(Error)),at=function(){function KeyLoader(t){(0,m.Z)(this,KeyLoader),this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}return(0,y.Z)(KeyLoader,[{"key":"abort","value":function abort(t){for(var r in this.keyUriToKeyInfo){var a=this.keyUriToKeyInfo[r].loader;if(a){if(t&&t!==a.context.frag.type)return;a.abort()}}}},{"key":"detach","value":function detach(){for(var t in this.keyUriToKeyInfo){var r=this.keyUriToKeyInfo[t];(r.mediaKeySessionContext||r.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}}},{"key":"destroy","value":function destroy(){for(var t in this.detach(),this.keyUriToKeyInfo){var r=this.keyUriToKeyInfo[t].loader;r&&r.destroy()}this.keyUriToKeyInfo={}}},{"key":"createKeyLoadError","value":function createKeyLoadError(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:b.KEY_LOAD_ERROR,a=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0;return new rt({"type":D.NETWORK_ERROR,"details":r,"fatal":!1,"frag":t,"response":o,"error":a,"networkDetails":i})}},{"key":"loadClear","value":function loadClear(t,r){var a=this;if(this.emeController&&this.config.emeEnabled)for(var i=t.sn,o=t.cc,l=function _loop4(){var t=r[u];if(o<=t.cc&&("initSegment"===i||"initSegment"===t.sn||i<t.sn))return a.emeController.selectKeySystemFormat(t).then((function(r){t.setKeyFormat(r)})),"break"},u=0;u<r.length;u++){if("break"===l())break}}},{"key":"load","value":function load(t){var r=this;return!t.decryptdata&&t.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(t).then((function(a){return r.loadInternal(t,a)})):this.loadInternal(t)}},{"key":"loadInternal","value":function loadInternal(t,r){var a,i;r&&t.setKeyFormat(r);var o=t.decryptdata;if(!o){var l=new Error(r?"Expected frag.decryptdata to be defined after setting format ".concat(r):"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(t,b.KEY_LOAD_ERROR,l))}var u=o.uri;if(!u)return Promise.reject(this.createKeyLoadError(t,b.KEY_LOAD_ERROR,new Error('Invalid key URI: "'.concat(u,'"'))));var c,d=this.keyUriToKeyInfo[u];if(null!=(a=d)&&a.decryptdata.key)return o.key=d.decryptdata.key,Promise.resolve({"frag":t,"keyInfo":d});if(null!=(i=d)&&i.keyLoadPromise)switch(null==(c=d.mediaKeySessionContext)?void 0:c.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return d.keyLoadPromise.then((function(r){return o.key=r.keyInfo.decryptdata.key,{"frag":t,"keyInfo":d}}))}switch(d=this.keyUriToKeyInfo[u]={"decryptdata":o,"keyLoadPromise":null,"loader":null,"mediaKeySessionContext":null},o.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===o.keyFormat?this.loadKeyHTTP(d,t):this.loadKeyEME(d,t);case"AES-128":return this.loadKeyHTTP(d,t);default:return Promise.reject(this.createKeyLoadError(t,b.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'.concat(o.method,'"'))))}}},{"key":"loadKeyEME","value":function loadKeyEME(t,r){var a={"frag":r,"keyInfo":t};if(this.emeController&&this.config.emeEnabled){var i=this.emeController.loadKey(a);if(i)return(t.keyLoadPromise=i.then((function(r){return t.mediaKeySessionContext=r,a}))).catch((function(r){throw t.keyLoadPromise=null,r}))}return Promise.resolve(a)}},{"key":"loadKeyHTTP","value":function loadKeyHTTP(t,r){var a=this,i=this.config,o=new(0,i.loader)(i);return r.keyLoader=t.loader=o,t.keyLoadPromise=new Promise((function(l,u){var c={"keyInfo":t,"frag":r,"responseType":"arraybuffer","url":t.decryptdata.uri},d=i.keyLoadPolicy.default,h={"loadPolicy":d,"timeout":d.maxLoadTimeMs,"maxRetry":0,"retryDelay":0,"maxRetryDelay":0},g={"onSuccess":function onSuccess(t,r,i,o){var c=i.frag,d=i.keyInfo,h=i.url;if(!c.decryptdata||d!==a.keyUriToKeyInfo[h])return u(a.createKeyLoadError(c,b.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),o));d.decryptdata.key=c.decryptdata.key=new Uint8Array(t.data),c.keyLoader=null,d.loader=null,l({"frag":c,"keyInfo":d})},"onError":function onError(t,i,o,l){a.resetLoader(i),u(a.createKeyLoadError(r,b.KEY_LOAD_ERROR,new Error("HTTP Error ".concat(t.code," loading key ").concat(t.text)),o,_objectSpread2({"url":c.url,"data":void 0},t)))},"onTimeout":function onTimeout(t,i,o){a.resetLoader(i),u(a.createKeyLoadError(r,b.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),o))},"onAbort":function onAbort(t,i,o){a.resetLoader(i),u(a.createKeyLoadError(r,b.INTERNAL_ABORTED,new Error("key loading aborted"),o))}};o.load(c,h,g)}))}},{"key":"resetLoader","value":function resetLoader(t){var r=t.frag,a=t.keyInfo,i=t.url,o=a.loader;r.keyLoader===o&&(r.keyLoader=null,a.loader=null),delete this.keyUriToKeyInfo[i],o&&o.destroy()}}]),KeyLoader}(),it=function(){function TaskLoop(){(0,m.Z)(this,TaskLoop),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}return(0,y.Z)(TaskLoop,[{"key":"destroy","value":function destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}},{"key":"onHandlerDestroying","value":function onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}},{"key":"onHandlerDestroyed","value":function onHandlerDestroyed(){}},{"key":"hasInterval","value":function hasInterval(){return!!this._tickInterval}},{"key":"hasNextTick","value":function hasNextTick(){return!!this._tickTimer}},{"key":"setInterval","value":function setInterval(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}},{"key":"clearInterval","value":function clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}},{"key":"clearNextTick","value":function clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}},{"key":"tick","value":function tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}},{"key":"tickImmediate","value":function tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}},{"key":"doTick","value":function doTick(){}}]),TaskLoop}(),nt={"length":0,"start":function start(){return 0},"end":function end(){return 0}},st=function(){function BufferHelper(){(0,m.Z)(this,BufferHelper)}return(0,y.Z)(BufferHelper,null,[{"key":"isBuffered","value":function isBuffered(t,r){try{if(t)for(var a=BufferHelper.getBuffered(t),i=0;i<a.length;i++)if(r>=a.start(i)&&r<=a.end(i))return!0}catch(t){}return!1}},{"key":"bufferInfo","value":function bufferInfo(t,r,a){try{if(t){var i,o=BufferHelper.getBuffered(t),l=[];for(i=0;i<o.length;i++)l.push({"start":o.start(i),"end":o.end(i)});return this.bufferedInfo(l,r,a)}}catch(t){}return{"len":0,"start":r,"end":r,"nextStart":void 0}}},{"key":"bufferedInfo","value":function bufferedInfo(t,r,a){r=Math.max(0,r),t.sort((function(t,r){var a=t.start-r.start;return a||r.end-t.end}));var i=[];if(a)for(var o=0;o<t.length;o++){var l=i.length;if(l){var u=i[l-1].end;t[o].start-u<a?t[o].end>u&&(i[l-1].end=t[o].end):i.push(t[o])}else i.push(t[o])}else i=t;for(var c,d=0,h=r,g=r,v=0;v<i.length;v++){var m=i[v].start,y=i[v].end;if(r+a>=m&&r<y)h=m,d=(g=y)-r;else if(r+a<m){c=m;break}}return{"len":d,"start":h||0,"end":g||0,"nextStart":c}}},{"key":"getBuffered","value":function getBuffered(t){try{return t.buffered}catch(t){return w.log("failed to get media.buffered",t),nt}}}]),BufferHelper}(),ot=(0,y.Z)((function ChunkMetadata(t,r,a){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:-1,l=arguments.length>5&&void 0!==arguments[5]&&arguments[5];(0,m.Z)(this,ChunkMetadata),this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={"start":0,"executeStart":0,"executeEnd":0,"end":0},this.buffering={"audio":{"start":0,"executeStart":0,"executeEnd":0,"end":0},"video":{"start":0,"executeStart":0,"executeEnd":0,"end":0},"audiovideo":{"start":0,"executeStart":0,"executeEnd":0,"end":0}},this.level=t,this.sn=r,this.id=a,this.size=i,this.part=o,this.partial=l}));function findFirstFragWithCC(t,r){for(var a=null,i=0,o=t.length;i<o;i++){var l=t[i];if(l&&l.cc===r){a=l;break}}return a}function adjustFragmentStart(t,r){if(t){var a=t.start+r;t.start=t.startPTS=a,t.endPTS=a+t.duration}}function adjustSlidingStart(t,r){for(var a=r.fragments,i=0,o=a.length;i<o;i++)adjustFragmentStart(a[i],t);r.fragmentHint&&adjustFragmentStart(r.fragmentHint,t),r.alignedSliding=!0}function alignStream(t,r,a){r&&(!function alignDiscontinuities(t,r,a){if(function shouldAlignOnDiscontinuities(t,r,a){return!(!r.details||!(a.endCC>a.startCC||t&&t.cc<a.startCC))}(t,a,r)){var i=function findDiscontinuousReferenceFrag(t,r){var a=t.fragments,i=r.fragments;if(i.length&&a.length){var o=findFirstFragWithCC(a,i[0].cc);if(o&&(!o||o.startPTS))return o;w.log("No frag in previous level to align on")}else w.log("No fragments to align")}(a.details,r);i&&R(i.start)&&(w.log("Adjusting PTS using last level due to CC increase within current level ".concat(r.url)),adjustSlidingStart(i.start,r))}}(t,a,r),!a.alignedSliding&&r.details&&function alignPDT(t,r){if(!r.fragments.length||!t.hasProgramDateTime||!r.hasProgramDateTime)return;var a=r.fragments[0].programDateTime,i=t.fragments[0].programDateTime,o=(i-a)/1e3+r.fragments[0].start;o&&R(o)&&(w.log("Adjusting PTS using programDateTime delta ".concat(i-a,"ms, sliding:").concat(o.toFixed(3)," ").concat(t.url," ")),adjustSlidingStart(o,t))}(a,r.details),a.alignedSliding||!r.details||a.skippedSegments||adjustSliding(r.details,a))}function alignMediaPlaylistByPDT(t,r){if(t.hasProgramDateTime&&r.hasProgramDateTime){var a=t.fragments,i=r.fragments;if(a.length&&i.length){var o=i[Math.round(i.length/2)-1],l=findFirstFragWithCC(a,o.cc)||a[Math.round(a.length/2)-1],u=o.programDateTime,c=l.programDateTime;if(null!==u&&null!==c)adjustSlidingStart((c-u)/1e3-(l.start-o.start),t)}}}var lt=function(){function AESCrypto(t,r){(0,m.Z)(this,AESCrypto),this.subtle=void 0,this.aesIV=void 0,this.subtle=t,this.aesIV=r}return(0,y.Z)(AESCrypto,[{"key":"decrypt","value":function decrypt(t,r){return this.subtle.decrypt({"name":"AES-CBC","iv":this.aesIV},r,t)}}]),AESCrypto}(),ut=function(){function FastAESKey(t,r){(0,m.Z)(this,FastAESKey),this.subtle=void 0,this.key=void 0,this.subtle=t,this.key=r}return(0,y.Z)(FastAESKey,[{"key":"expandKey","value":function expandKey(){return this.subtle.importKey("raw",this.key,{"name":"AES-CBC"},!1,["encrypt","decrypt"])}}]),FastAESKey}();var ct=function(){function AESDecryptor(){(0,m.Z)(this,AESDecryptor),this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}return(0,y.Z)(AESDecryptor,[{"key":"uint8ArrayToUint32Array_","value":function uint8ArrayToUint32Array_(t){for(var r=new DataView(t),a=new Uint32Array(4),i=0;i<4;i++)a[i]=r.getUint32(4*i);return a}},{"key":"initTable","value":function initTable(){var t=this.sBox,r=this.invSBox,a=this.subMix,i=a[0],o=a[1],l=a[2],u=a[3],c=this.invSubMix,d=c[0],h=c[1],g=c[2],v=c[3],m=new Uint32Array(256),y=0,p=0,T=0;for(T=0;T<256;T++)m[T]=T<128?T<<1:T<<1^283;for(T=0;T<256;T++){var E=p^p<<1^p<<2^p<<3^p<<4;E=E>>>8^255&E^99,t[y]=E,r[E]=y;var k=m[y],S=m[k],L=m[S],A=257*m[E]^16843008*E;i[y]=A<<24|A>>>8,o[y]=A<<16|A>>>16,l[y]=A<<8|A>>>24,u[y]=A,A=16843009*L^65537*S^257*k^16843008*y,d[E]=A<<24|A>>>8,h[E]=A<<16|A>>>16,g[E]=A<<8|A>>>24,v[E]=A,y?(y=k^m[m[m[L^k]]],p^=m[m[p]]):y=p=1}}},{"key":"expandKey","value":function expandKey(t){for(var r=this.uint8ArrayToUint32Array_(t),a=!0,i=0;i<r.length&&a;)a=r[i]===this.key[i],i++;if(!a){this.key=r;var o=this.keySize=r.length;if(4!==o&&6!==o&&8!==o)throw new Error("Invalid aes key size="+o);var l,u,c,d,h=this.ksRows=4*(o+6+1),g=this.keySchedule=new Uint32Array(h),v=this.invKeySchedule=new Uint32Array(h),m=this.sBox,y=this.rcon,p=this.invSubMix,T=p[0],E=p[1],k=p[2],S=p[3];for(l=0;l<h;l++)l<o?c=g[l]=r[l]:(d=c,l%o==0?(d=m[(d=d<<8|d>>>24)>>>24]<<24|m[d>>>16&255]<<16|m[d>>>8&255]<<8|m[255&d],d^=y[l/o|0]<<24):o>6&&l%o==4&&(d=m[d>>>24]<<24|m[d>>>16&255]<<16|m[d>>>8&255]<<8|m[255&d]),g[l]=c=(g[l-o]^d)>>>0);for(u=0;u<h;u++)l=h-u,d=3&u?g[l]:g[l-4],v[u]=u<4||l<=4?d:T[m[d>>>24]]^E[m[d>>>16&255]]^k[m[d>>>8&255]]^S[m[255&d]],v[u]=v[u]>>>0}}},{"key":"networkToHostOrderSwap","value":function networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}},{"key":"decrypt","value":function decrypt(t,r,a){for(var i,o,l,u,c,d,h,g,v,m,y,p,T,E,k=this.keySize+6,S=this.invKeySchedule,L=this.invSBox,A=this.invSubMix,R=A[0],I=A[1],D=A[2],b=A[3],C=this.uint8ArrayToUint32Array_(a),P=C[0],_=C[1],w=C[2],M=C[3],x=new Int32Array(t),O=new Int32Array(x.length),N=this.networkToHostOrderSwap;r<x.length;){for(v=N(x[r]),m=N(x[r+1]),y=N(x[r+2]),p=N(x[r+3]),c=v^S[0],d=p^S[1],h=y^S[2],g=m^S[3],T=4,E=1;E<k;E++)i=R[c>>>24]^I[d>>16&255]^D[h>>8&255]^b[255&g]^S[T],o=R[d>>>24]^I[h>>16&255]^D[g>>8&255]^b[255&c]^S[T+1],l=R[h>>>24]^I[g>>16&255]^D[c>>8&255]^b[255&d]^S[T+2],u=R[g>>>24]^I[c>>16&255]^D[d>>8&255]^b[255&h]^S[T+3],c=i,d=o,h=l,g=u,T+=4;i=L[c>>>24]<<24^L[d>>16&255]<<16^L[h>>8&255]<<8^L[255&g]^S[T],o=L[d>>>24]<<24^L[h>>16&255]<<16^L[g>>8&255]<<8^L[255&c]^S[T+1],l=L[h>>>24]<<24^L[g>>16&255]<<16^L[c>>8&255]<<8^L[255&d]^S[T+2],u=L[g>>>24]<<24^L[c>>16&255]<<16^L[d>>8&255]<<8^L[255&h]^S[T+3],O[r]=N(i^P),O[r+1]=N(u^_),O[r+2]=N(l^w),O[r+3]=N(o^M),P=v,_=m,w=y,M=p,r+=4}return O.buffer}}]),AESDecryptor}(),dt=function(){function Decrypter(t){var r=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).removePKCS7Padding,a=void 0===r||r;if((0,m.Z)(this,Decrypter),this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=t.enableSoftwareAES,this.removePKCS7Padding=a,a)try{var i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch(t){}null===this.subtle&&(this.useSoftware=!0)}return(0,y.Z)(Decrypter,[{"key":"destroy","value":function destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}},{"key":"isSync","value":function isSync(){return this.useSoftware}},{"key":"flush","value":function flush(){var t=this.currentResult,r=this.remainderData;if(!t||r)return this.reset(),null;var a=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function removePadding(t){var r=t.byteLength,a=r&&new DataView(t.buffer).getUint8(r-1);return a?sliceUint8(t,0,r-a):t}(a):a}},{"key":"reset","value":function reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}},{"key":"decrypt","value":function decrypt(t,r,a){var i=this;return this.useSoftware?new Promise((function(o,l){i.softwareDecrypt(new Uint8Array(t),r,a);var u=i.flush();u?o(u.buffer):l(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(t),r,a)}},{"key":"softwareDecrypt","value":function softwareDecrypt(t,r,a){var i=this.currentIV,o=this.currentResult,l=this.remainderData;this.logOnce("JS AES decrypt"),l&&(t=appendUint8Array(l,t),this.remainderData=null);var u=this.getValidChunk(t);if(!u.length)return null;i&&(a=i);var c=this.softwareDecrypter;c||(c=this.softwareDecrypter=new ct),c.expandKey(r);var d=o;return this.currentResult=c.decrypt(u.buffer,0,a),this.currentIV=sliceUint8(u,-16).buffer,d||null}},{"key":"webCryptoDecrypt","value":function webCryptoDecrypt(t,r,a){var i=this,o=this.subtle;return this.key===r&&this.fastAesKey||(this.key=r,this.fastAesKey=new ut(o,r)),this.fastAesKey.expandKey().then((function(r){return o?(i.logOnce("WebCrypto AES decrypt"),new lt(o,new Uint8Array(a)).decrypt(t.buffer,r)):Promise.reject(new Error("web crypto not initialized"))})).catch((function(o){return w.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, ".concat(o.name,": ").concat(o.message)),i.onWebCryptoError(t,r,a)}))}},{"key":"onWebCryptoError","value":function onWebCryptoError(t,r,a){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,r,a);var i=this.flush();if(i)return i.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}},{"key":"getValidChunk","value":function getValidChunk(t){var r=t,a=t.length-t.length%16;return a!==t.length&&(r=sliceUint8(t,0,a),this.remainderData=sliceUint8(t,a)),r}},{"key":"logOnce","value":function logOnce(t){this.logEnabled&&(w.log("[decrypter]: ".concat(t)),this.logEnabled=!1)}}]),Decrypter}(),ht=function toString(t){for(var r="",a=t.length,i=0;i<a;i++)r+="[".concat(t.start(i).toFixed(3),"-").concat(t.end(i).toFixed(3),"]");return r},ft={"STOPPED":"STOPPED","IDLE":"IDLE","KEY_LOADING":"KEY_LOADING","FRAG_LOADING":"FRAG_LOADING","FRAG_LOADING_WAITING_RETRY":"FRAG_LOADING_WAITING_RETRY","WAITING_TRACK":"WAITING_TRACK","PARSING":"PARSING","PARSED":"PARSED","ENDED":"ENDED","ERROR":"ERROR","WAITING_INIT_PTS":"WAITING_INIT_PTS","WAITING_LEVEL":"WAITING_LEVEL"},gt=function(t){(0,g.Z)(BaseStreamController,t);var r=(0,v.Z)(BaseStreamController);function BaseStreamController(t,a,i,o,l){var c;return(0,m.Z)(this,BaseStreamController),(c=r.call(this)).hls=void 0,c.fragPrevious=null,c.fragCurrent=null,c.fragmentTracker=void 0,c.transmuxer=null,c._state=ft.STOPPED,c.playlistType=void 0,c.media=null,c.mediaBuffer=null,c.config=void 0,c.bitrateTest=!1,c.lastCurrentTime=0,c.nextLoadPosition=0,c.startPosition=0,c.startTimeOffset=null,c.loadedmetadata=!1,c.retryDate=0,c.levels=null,c.fragmentLoader=void 0,c.keyLoader=void 0,c.levelLastLoaded=null,c.startFragRequested=!1,c.decrypter=void 0,c.initPTS=[],c.onvseeking=null,c.onvended=null,c.logPrefix="",c.log=void 0,c.warn=void 0,c.playlistType=l,c.logPrefix=o,c.log=w.log.bind(w,"".concat(o,":")),c.warn=w.warn.bind(w,"".concat(o,":")),c.hls=t,c.fragmentLoader=new tt(t.config),c.keyLoader=i,c.fragmentTracker=a,c.config=t.config,c.decrypter=new dt(t.config),t.on(I.MANIFEST_LOADED,c.onManifestLoaded,(0,u.Z)(c)),c}return(0,y.Z)(BaseStreamController,[{"key":"doTick","value":function doTick(){this.onTickEnd()}},{"key":"onTickEnd","value":function onTickEnd(){}},{"key":"startLoad","value":function startLoad(t){}},{"key":"stopLoad","value":function stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);var t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=ft.STOPPED}},{"key":"_streamEnded","value":function _streamEnded(t,r){if(r.live||t.nextStart||!t.end||!this.media)return!1;var a=r.partList;if(null!=a&&a.length){var i=a[a.length-1];return st.isBuffered(this.media,i.start+i.duration/2)}var o=r.fragments[r.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}},{"key":"getLevelDetails","value":function getLevelDetails(){var t;if(this.levels&&null!==this.levelLastLoaded)return null==(t=this.levels[this.levelLastLoaded])?void 0:t.details}},{"key":"onMediaAttached","value":function onMediaAttached(t,r){var a=this.media=this.mediaBuffer=r.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),a.addEventListener("seeking",this.onvseeking),a.addEventListener("ended",this.onvended);var i=this.config;this.levels&&i.autoStartLoad&&this.state===ft.STOPPED&&this.startLoad(i.startPosition)}},{"key":"onMediaDetaching","value":function onMediaDetaching(){var t=this.media;null!=t&&t.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),t&&this.onvseeking&&this.onvended&&(t.removeEventListener("seeking",this.onvseeking),t.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}},{"key":"onMediaSeeking","value":function onMediaSeeking(){var t=this.config,r=this.fragCurrent,a=this.media,i=this.mediaBuffer,o=this.state,l=a?a.currentTime:0,u=st.bufferInfo(i||a,l,t.maxBufferHole);if(this.log("media seeking to ".concat(R(l)?l.toFixed(3):l,", state: ").concat(o)),this.state===ft.ENDED)this.resetLoadingState();else if(r){var c=t.maxFragLookUpTolerance,d=r.start-c,h=r.start+r.duration+c;if(!u.len||h<u.start||d>u.end){var g=l>h;(l<d||g)&&(g&&r.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),r.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}a&&(this.fragmentTracker.removeFragmentsInRange(l,1/0,this.playlistType,!0),this.lastCurrentTime=l),this.loadedmetadata||u.len||(this.nextLoadPosition=this.startPosition=l),this.tickImmediate()}},{"key":"onMediaEnded","value":function onMediaEnded(){this.startPosition=this.lastCurrentTime=0}},{"key":"onManifestLoaded","value":function onManifestLoaded(t,r){this.startTimeOffset=r.startTimeOffset,this.initPTS=[]}},{"key":"onHandlerDestroying","value":function onHandlerDestroying(){this.stopLoad(),(0,d.Z)((0,h.Z)(BaseStreamController.prototype),"onHandlerDestroying",this).call(this)}},{"key":"onHandlerDestroyed","value":function onHandlerDestroyed(){this.state=ft.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,(0,d.Z)((0,h.Z)(BaseStreamController.prototype),"onHandlerDestroyed",this).call(this)}},{"key":"loadFragment","value":function loadFragment(t,r,a){this._loadFragForPlayback(t,r,a)}},{"key":"_loadFragForPlayback","value":function _loadFragForPlayback(t,r,a){var i=this;this._doFragLoad(t,r,a,(function progressCallback(r){if(i.fragContextChanged(t))return i.warn("Fragment ".concat(t.sn).concat(r.part?" p: "+r.part.index:""," of level ").concat(t.level," was dropped during download.")),void i.fragmentTracker.removeFragment(t);t.stats.chunkCount++,i._handleFragmentLoadProgress(r)})).then((function(r){if(r){var a=i.state;i.fragContextChanged(t)?(a===ft.FRAG_LOADING||!i.fragCurrent&&a===ft.PARSING)&&(i.fragmentTracker.removeFragment(t),i.state=ft.IDLE):("payload"in r&&(i.log("Loaded fragment ".concat(t.sn," of level ").concat(t.level)),i.hls.trigger(I.FRAG_LOADED,r)),i._handleFragmentLoadComplete(r))}})).catch((function(r){i.state!==ft.STOPPED&&i.state!==ft.ERROR&&(i.warn(r),i.resetFragmentLoading(t))}))}},{"key":"clearTrackerIfNeeded","value":function clearTrackerIfNeeded(t){var r,a=this.fragmentTracker;if(a.getState(t)===Xe){var i=t.type,o=this.getFwdBufferInfo(this.mediaBuffer,i),l=Math.max(t.duration,o?o.len:this.config.maxBufferLength);this.reduceMaxBufferLength(l)&&a.removeFragment(t)}else 0===(null==(r=this.mediaBuffer)?void 0:r.buffered.length)?a.removeAllFragments():a.hasParts(t.type)&&(a.detectPartialFragments({"frag":t,"part":null,"stats":t.stats,"id":t.type}),a.getState(t)===Qe&&a.removeFragment(t))}},{"key":"flushMainBuffer","value":function flushMainBuffer(t,r){if(t-r){var a={"startOffset":t,"endOffset":r,"type":arguments.length>2&&void 0!==arguments[2]?arguments[2]:null};this.hls.trigger(I.BUFFER_FLUSHING,a)}}},{"key":"_loadInitSegment","value":function _loadInitSegment(t,r){var a=this;this._doFragLoad(t,r).then((function(r){if(!r||a.fragContextChanged(t)||!a.levels)throw new Error("init load aborted");return r})).then((function(r){var i=a.hls,o=r.payload,l=t.decryptdata;if(o&&o.byteLength>0&&l&&l.key&&l.iv&&"AES-128"===l.method){var u=self.performance.now();return a.decrypter.decrypt(new Uint8Array(o),l.key.buffer,l.iv.buffer).catch((function(r){throw i.trigger(I.ERROR,{"type":D.MEDIA_ERROR,"details":b.FRAG_DECRYPT_ERROR,"fatal":!1,"error":r,"reason":r.message,"frag":t}),r})).then((function(a){var o=self.performance.now();return i.trigger(I.FRAG_DECRYPTED,{"frag":t,"payload":a,"stats":{"tstart":u,"tdecrypt":o}}),r.payload=a,r}))}return r})).then((function(i){var o=a.fragCurrent,l=a.hls;if(!a.levels)throw new Error("init load aborted, missing levels");var u=t.stats;a.state=ft.IDLE,r.fragmentError=0,t.data=new Uint8Array(i.payload),u.parsing.start=u.buffering.start=self.performance.now(),u.parsing.end=u.buffering.end=self.performance.now(),i.frag===o&&l.trigger(I.FRAG_BUFFERED,{"stats":u,"frag":o,"part":null,"id":t.type}),a.tick()})).catch((function(r){a.state!==ft.STOPPED&&a.state!==ft.ERROR&&(a.warn(r),a.resetFragmentLoading(t))}))}},{"key":"fragContextChanged","value":function fragContextChanged(t){var r=this.fragCurrent;return!t||!r||t.level!==r.level||t.sn!==r.sn||t.urlId!==r.urlId}},{"key":"fragBufferedComplete","value":function fragBufferedComplete(t,r){var a,i,o,l,u=this.mediaBuffer?this.mediaBuffer:this.media;this.log("Buffered ".concat(t.type," sn: ").concat(t.sn).concat(r?" part: "+r.index:""," of ").concat(this.playlistType===Re.MAIN?"level":"track"," ").concat(t.level," (frag:[").concat((null!=(a=t.startPTS)?a:NaN).toFixed(3),"-").concat((null!=(i=t.endPTS)?i:NaN).toFixed(3),"] > buffer:").concat(u?ht(st.getBuffered(u)):"(detached)",")")),this.state=ft.IDLE,u&&(!this.loadedmetadata&&t.type==Re.MAIN&&u.buffered.length&&(null==(o=this.fragCurrent)?void 0:o.sn)===(null==(l=this.fragPrevious)?void 0:l.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}},{"key":"seekToStartPos","value":function seekToStartPos(){}},{"key":"_handleFragmentLoadComplete","value":function _handleFragmentLoadComplete(t){var r=this.transmuxer;if(r){var a=t.frag,i=t.part,o=t.partsLoaded,l=!o||0===o.length||o.some((function(t){return!t})),u=new ot(a.level,a.sn,a.stats.chunkCount+1,0,i?i.index:-1,!l);r.flush(u)}}},{"key":"_handleFragmentLoadProgress","value":function _handleFragmentLoadProgress(t){}},{"key":"_doFragLoad","value":function _doFragLoad(t,r){var a,i=this,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,u=arguments.length>3?arguments[3]:void 0,c=null==r?void 0:r.details;if(!this.levels||!c)throw new Error("frag load aborted, missing level".concat(c?"":" detail","s"));var d=null;if(!t.encrypted||null!=(a=t.decryptdata)&&a.key?!t.encrypted&&c.encryptedFragments.length&&this.keyLoader.loadClear(t,c.encryptedFragments):(this.log("Loading key for ".concat(t.sn," of [").concat(c.startSN,"-").concat(c.endSN,"], ").concat("[stream-controller]"===this.logPrefix?"level":"track"," ").concat(t.level)),this.state=ft.KEY_LOADING,this.fragCurrent=t,d=this.keyLoader.load(t).then((function(t){if(!i.fragContextChanged(t.frag))return i.hls.trigger(I.KEY_LOADED,t),i.state===ft.KEY_LOADING&&(i.state=ft.IDLE),t})),this.hls.trigger(I.KEY_LOADING,{"frag":t}),null===this.fragCurrent&&(d=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),o=Math.max(t.start,o||0),this.config.lowLatencyMode&&"initSegment"!==t.sn){var h=c.partList;if(h&&u){o>t.end&&c.fragmentHint&&(t=c.fragmentHint);var g=this.getNextPart(h,t,o);if(g>-1){var v,m=h[g];return this.log("Loading part sn: ".concat(t.sn," p: ").concat(m.index," cc: ").concat(t.cc," of playlist [").concat(c.startSN,"-").concat(c.endSN,"] parts [0-").concat(g,"-").concat(h.length-1,"] ").concat("[stream-controller]"===this.logPrefix?"level":"track",": ").concat(t.level,", target: ").concat(parseFloat(o.toFixed(3)))),this.nextLoadPosition=m.start+m.duration,this.state=ft.FRAG_LOADING,v=d?d.then((function(a){return!a||i.fragContextChanged(a.frag)?null:i.doFragPartsLoad(t,m,r,u)})).catch((function(t){return i.handleFragLoadError(t)})):this.doFragPartsLoad(t,m,r,u).catch((function(t){return i.handleFragLoadError(t)})),this.hls.trigger(I.FRAG_LOADING,{"frag":t,"part":m,"targetBufferTime":o}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):v}if(!t.url||this.loadedEndOfParts(h,o))return Promise.resolve(null)}}this.log("Loading fragment ".concat(t.sn," cc: ").concat(t.cc," ").concat(c?"of ["+c.startSN+"-"+c.endSN+"] ":"").concat("[stream-controller]"===this.logPrefix?"level":"track",": ").concat(t.level,", target: ").concat(parseFloat(o.toFixed(3)))),R(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=ft.FRAG_LOADING;var y,p=this.config.progressive;return y=p&&d?d.then((function(r){return!r||i.fragContextChanged(null==r?void 0:r.frag)?null:i.fragmentLoader.load(t,u)})).catch((function(t){return i.handleFragLoadError(t)})):Promise.all([this.fragmentLoader.load(t,p?u:void 0),d]).then((function(t){var r=(0,l.Z)(t,1)[0];return!p&&r&&u&&u(r),r})).catch((function(t){return i.handleFragLoadError(t)})),this.hls.trigger(I.FRAG_LOADING,{"frag":t,"targetBufferTime":o}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):y}},{"key":"doFragPartsLoad","value":function doFragPartsLoad(t,r,a,i){var o=this;return new Promise((function(l,u){var c,d=[],h=null==(c=a.details)?void 0:c.partList;!function loadPart(r){o.fragmentLoader.loadPart(t,r,i).then((function(i){d[r.index]=i;var u=i.part;o.hls.trigger(I.FRAG_LOADED,i);var c=getPartWith(a,t.sn,r.index+1)||findPart(h,t.sn,r.index+1);if(!c)return l({"frag":t,"part":u,"partsLoaded":d});loadPart(c)})).catch(u)}(r)}))}},{"key":"handleFragLoadError","value":function handleFragLoadError(t){if("data"in t){var r=t.data;t.data&&r.details===b.INTERNAL_ABORTED?this.handleFragLoadAborted(r.frag,r.part):this.hls.trigger(I.ERROR,r)}else this.hls.trigger(I.ERROR,{"type":D.OTHER_ERROR,"details":b.INTERNAL_EXCEPTION,"err":t,"error":t,"fatal":!0});return null}},{"key":"_handleTransmuxerFlush","value":function _handleTransmuxerFlush(t){var r=this.getCurrentContext(t);if(r&&this.state===ft.PARSING){var a=r.frag,i=r.part,o=r.level,l=self.performance.now();a.stats.parsing.end=l,i&&(i.stats.parsing.end=l),this.updateLevelTiming(a,i,o,t.partial)}else this.fragCurrent||this.state===ft.STOPPED||this.state===ft.ERROR||(this.state=ft.IDLE)}},{"key":"getCurrentContext","value":function getCurrentContext(t){var r=this.levels,a=this.fragCurrent,i=t.level,o=t.sn,l=t.part;if(null==r||!r[i])return this.warn("Levels object was unset while buffering fragment ".concat(o," of level ").concat(i,". The current chunk will not be buffered.")),null;var u=r[i],c=l>-1?getPartWith(u,o,l):null,d=c?c.fragment:function getFragmentWithSN(t,r,a){if(null==t||!t.details)return null;var i=t.details,o=i.fragments[r-i.startSN];return o||((o=i.fragmentHint)&&o.sn===r?o:r<i.startSN&&a&&a.sn===r?a:null)}(u,o,a);return d?(a&&a!==d&&(d.stats=a.stats),{"frag":d,"part":c,"level":u}):null}},{"key":"bufferFragmentData","value":function bufferFragmentData(t,r,a,i){var o;if(t&&this.state===ft.PARSING){var l=t.data1,u=t.data2,c=l;if(l&&u&&(c=appendUint8Array(l,u)),null!=(o=c)&&o.length){var d={"type":t.type,"frag":r,"part":a,"chunkMeta":i,"parent":r.type,"data":c};this.hls.trigger(I.BUFFER_APPENDING,d),t.dropped&&t.independent&&!a&&this.flushBufferGap(r)}}}},{"key":"flushBufferGap","value":function flushBufferGap(t){var r=this.media;if(r)if(st.isBuffered(r,r.currentTime)){var a=r.currentTime,i=st.bufferInfo(r,a,0),o=t.duration,l=Math.min(2*this.config.maxFragLookUpTolerance,.25*o),u=Math.max(Math.min(t.start-l,i.end-l),a+l);t.start-u>l&&this.flushMainBuffer(u,t.start)}else this.flushMainBuffer(0,t.start)}},{"key":"getFwdBufferInfo","value":function getFwdBufferInfo(t,r){var a=this.getLoadPosition();return R(a)?this.getFwdBufferInfoAtPos(t,a,r):null}},{"key":"getFwdBufferInfoAtPos","value":function getFwdBufferInfoAtPos(t,r,a){var i=this.config.maxBufferHole,o=st.bufferInfo(t,r,i);if(0===o.len&&void 0!==o.nextStart){var l=this.fragmentTracker.getBufferedFrag(r,a);if(l&&o.nextStart<l.end)return st.bufferInfo(t,r,Math.max(o.nextStart,i))}return o}},{"key":"getMaxBufferLength","value":function getMaxBufferLength(t){var r,a=this.config;return r=t?Math.max(8*a.maxBufferSize/t,a.maxBufferLength):a.maxBufferLength,Math.min(r,a.maxMaxBufferLength)}},{"key":"reduceMaxBufferLength","value":function reduceMaxBufferLength(t){var r=this.config,a=t||r.maxBufferLength;return r.maxMaxBufferLength>=a&&(r.maxMaxBufferLength/=2,this.warn("Reduce max buffer length to ".concat(r.maxMaxBufferLength,"s")),!0)}},{"key":"getAppendedFrag","value":function getAppendedFrag(t){arguments.length>1&&void 0!==arguments[1]||Re.MAIN;var r=this.fragmentTracker.getAppendedFrag(t,Re.MAIN);return r&&"fragment"in r?r.fragment:r}},{"key":"getNextFragment","value":function getNextFragment(t,r){var a=r.fragments,i=a.length;if(!i)return null;var o,l=this.config,u=a[0].start;if(r.live){var c=l.initialLiveManifestSize;if(i<c)return this.warn("Not enough fragments to start playback (have: ".concat(i,", need: ").concat(c,")")),null;r.PTSKnown||this.startFragRequested||-1!==this.startPosition||(o=this.getInitialLiveFragment(r,a),this.startPosition=o?this.hls.liveSyncPosition||o.start:t)}else t<=u&&(o=a[0]);if(!o){var d=l.lowLatencyMode?r.partEnd:r.fragmentEnd;o=this.getFragmentAtPosition(t,d,r)}return this.mapToInitFragWhenRequired(o)}},{"key":"isLoopLoading","value":function isLoopLoading(t,r){var a=this.fragmentTracker.getState(t);return(a===$e||a===Qe&&!!t.gap)&&this.nextLoadPosition>r}},{"key":"getNextFragmentLoopLoading","value":function getNextFragmentLoopLoading(t,r,a,i,o){var l=t.gap,u=this.getNextFragment(this.nextLoadPosition,r);if(null===u)return u;if(t=u,l&&t&&!t.gap&&a.nextStart){var c=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,a.nextStart,i);if(null!==c&&a.len+c.len>=o)return this.log('buffer full after gaps in "'.concat(i,'" playlist starting at sn: ').concat(t.sn)),null}return t}},{"key":"mapToInitFragWhenRequired","value":function mapToInitFragWhenRequired(t){return null==t||!t.initSegment||null!=t&&t.initSegment.data||this.bitrateTest?t:t.initSegment}},{"key":"getNextPart","value":function getNextPart(t,r,a){for(var i=-1,o=!1,l=!0,u=0,c=t.length;u<c;u++){var d=t[u];if(l=l&&!d.independent,i>-1&&a<d.start)break;var h=d.loaded;h?i=-1:(o||d.independent||l)&&d.fragment===r&&(i=u),o=h}return i}},{"key":"loadedEndOfParts","value":function loadedEndOfParts(t,r){var a=t[t.length-1];return a&&r>a.start&&a.loaded}},{"key":"getInitialLiveFragment","value":function getInitialLiveFragment(t,r){var a=this.fragPrevious,i=null;if(a){if(t.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: ".concat(a.programDateTime)),i=function findFragmentByPDT(t,r,a){if(null===r||!Array.isArray(t)||!t.length||!R(r))return null;if(r<(t[0].programDateTime||0))return null;if(r>=(t[t.length-1].endProgramDateTime||0))return null;a=a||0;for(var i=0;i<t.length;++i){var o=t[i];if(pdtWithinToleranceTest(r,a,o))return o}return null}(r,a.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){var o=a.sn+1;if(o>=t.startSN&&o<=t.endSN){var l=r[o-t.startSN];a.cc===l.cc&&(i=l,this.log("Live playlist, switching playlist, load frag with next SN: ".concat(i.sn)))}i||(i=function findFragWithCC(t,r){return Ne.search(t,(function(t){return t.cc<r?1:t.cc>r?-1:0}))}(r,a.cc),i&&this.log("Live playlist, switching playlist, load frag with same CC: ".concat(i.sn)))}}else{var u=this.hls.liveSyncPosition;null!==u&&(i=this.getFragmentAtPosition(u,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i}},{"key":"getFragmentAtPosition","value":function getFragmentAtPosition(t,r,a){var i,o=this.config,l=this.fragPrevious,u=a.fragments,c=a.endSN,d=a.fragmentHint,h=o.maxFragLookUpTolerance,g=a.partList,v=!!(o.lowLatencyMode&&null!=g&&g.length&&d);(v&&d&&!this.bitrateTest&&(u=u.concat(d),c=d.sn),t<r)?i=findFragmentByPTS(l,u,t,t>r-h?0:h):i=u[u.length-1];if(i){var m=i.sn-a.startSN,y=this.fragmentTracker.getState(i);if((y===$e||y===Qe&&i.gap)&&(l=i),l&&i.sn===l.sn&&(!v||g[0].fragment.sn>i.sn))if(l&&i.level===l.level){var p=u[m+1];i=i.sn<c&&this.fragmentTracker.getState(p)!==$e?p:null}}return i}},{"key":"synchronizeToLiveEdge","value":function synchronizeToLiveEdge(t){var r=this.config,a=this.media;if(a){var i=this.hls.liveSyncPosition,o=a.currentTime,l=t.fragments[0].start,u=t.edge,c=o>=l-r.maxFragLookUpTolerance&&o<=u;if(null!==i&&a.duration>i&&(o<i||!c)){var d=void 0!==r.liveMaxLatencyDuration?r.liveMaxLatencyDuration:r.liveMaxLatencyDurationCount*t.targetduration;(!c&&a.readyState<4||o<u-d)&&(this.loadedmetadata||(this.nextLoadPosition=i),a.readyState&&(this.warn("Playback: ".concat(o.toFixed(3)," is located too far from the end of live sliding playlist: ").concat(u,", reset currentTime to : ").concat(i.toFixed(3))),a.currentTime=i))}}}},{"key":"alignPlaylists","value":function alignPlaylists(t,r){var a=this.levels,i=this.levelLastLoaded,o=this.fragPrevious,l=null!==i?a[i]:null,u=t.fragments.length;if(!u)return this.warn("No fragments in live playlist"),0;var c=t.fragments[0].start,d=!r,h=t.alignedSliding&&R(c);if(d||!h&&!c){alignStream(o,l,t);var g=t.fragments[0].start;return this.log("Live playlist sliding: ".concat(g.toFixed(2)," start-sn: ").concat(r?r.startSN:"na","->").concat(t.startSN," prev-sn: ").concat(o?o.sn:"na"," fragments: ").concat(u)),g}return c}},{"key":"waitForCdnTuneIn","value":function waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}},{"key":"setStartPosition","value":function setStartPosition(t,r){var a=this.startPosition;if(a<r&&(a=-1),-1===a||-1===this.lastCurrentTime){var i=null!==this.startTimeOffset,o=i?this.startTimeOffset:t.startTimeOffset;null!==o&&R(o)?(a=r+o,o<0&&(a+=t.totalduration),a=Math.min(Math.max(r,a),r+t.totalduration),this.log("Start time offset ".concat(o," found in ").concat(i?"multivariant":"media"," playlist, adjust startPosition to ").concat(a)),this.startPosition=a):t.live?a=this.hls.liveSyncPosition||r:this.startPosition=a=0,this.lastCurrentTime=a}this.nextLoadPosition=a}},{"key":"getLoadPosition","value":function getLoadPosition(){var t=this.media,r=0;return this.loadedmetadata&&t?r=t.currentTime:this.nextLoadPosition&&(r=this.nextLoadPosition),r}},{"key":"handleFragLoadAborted","value":function handleFragLoadAborted(t,r){this.transmuxer&&"initSegment"!==t.sn&&t.stats.aborted&&(this.warn("Fragment ".concat(t.sn).concat(r?" part "+r.index:""," of level ").concat(t.level," was aborted")),this.resetFragmentLoading(t))}},{"key":"resetFragmentLoading","value":function resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===ft.FRAG_LOADING_WAITING_RETRY)||(this.state=ft.IDLE)}},{"key":"onFragmentOrKeyLoadError","value":function onFragmentOrKeyLoadError(t,r){if(r.chunkMeta&&!r.frag){var a=this.getCurrentContext(r.chunkMeta);a&&(r.frag=a.frag)}var i=r.frag;if(i&&i.type===t&&this.levels)if(this.fragContextChanged(i)){var o;this.warn("Frag load error must match current frag to retry ".concat(i.url," > ").concat(null==(o=this.fragCurrent)?void 0:o.url))}else{var l=r.details===b.FRAG_GAP;l&&this.fragmentTracker.fragBuffered(i,!0);var u=r.errorAction,c=u||{},d=c.action,h=c.retryCount,g=void 0===h?0:h,v=c.retryConfig;if(u&&d===Ke&&v){this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition);var m=getRetryDelay(v,g);this.warn("Fragment ".concat(i.sn," of ").concat(t," ").concat(i.level," errored with ").concat(r.details,", retrying loading ").concat(g+1,"/").concat(v.maxNumRetry," in ").concat(m,"ms")),u.resolved=!0,this.retryDate=self.performance.now()+m,this.state=ft.FRAG_LOADING_WAITING_RETRY}else v&&u?(this.resetFragmentErrors(t),g<v.maxNumRetry?l||(u.resolved=!0):w.warn("".concat(r.details," reached or exceeded max retry (").concat(g,")"))):this.state=ft.ERROR;this.tickImmediate()}}},{"key":"reduceLengthAndFlushBuffer","value":function reduceLengthAndFlushBuffer(t){if(this.state===ft.PARSING||this.state===ft.PARSED){var r=t.parent,a=this.getFwdBufferInfo(this.mediaBuffer,r),i=a&&a.len>.5;i&&this.reduceMaxBufferLength(a.len);var o=!i;return o&&this.warn("Buffer full error while media.currentTime is not buffered, flush ".concat(r," buffer")),t.frag&&(this.fragmentTracker.removeFragment(t.frag),this.nextLoadPosition=t.frag.start),this.resetLoadingState(),o}return!1}},{"key":"resetFragmentErrors","value":function resetFragmentErrors(t){t===Re.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==ft.STOPPED&&(this.state=ft.IDLE)}},{"key":"afterBufferFlushed","value":function afterBufferFlushed(t,r,a){if(t){var i=st.getBuffered(t);this.fragmentTracker.detectEvictedFragments(r,i,a),this.state===ft.ENDED&&this.resetLoadingState()}}},{"key":"resetLoadingState","value":function resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=ft.IDLE}},{"key":"resetStartWhenNotLoaded","value":function resetStartWhenNotLoaded(t){if(!this.loadedmetadata){this.startFragRequested=!1;var r=this.levels?this.levels[t].details:null;null!=r&&r.live?(this.startPosition=-1,this.setStartPosition(r,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}},{"key":"resetWhenMissingContext","value":function resetWhenMissingContext(t){this.warn("The loading context changed while buffering fragment ".concat(t.sn," of level ").concat(t.level,". This chunk will not be buffered.")),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(t.level),this.resetLoadingState()}},{"key":"removeUnbufferedFrags","value":function removeUnbufferedFrags(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}},{"key":"updateLevelTiming","value":function updateLevelTiming(t,r,a,i){var o,l=this,u=a.details;if(u){if(Object.keys(t.elementaryStreams).reduce((function(r,o){var c=t.elementaryStreams[o];if(c){var d=c.endPTS-c.startPTS;if(d<=0)return l.warn("Could not parse fragment ".concat(t.sn," ").concat(o," duration reliably (").concat(d,")")),r||!1;var h=i?0:updateFragPTSDTS(u,t,c.startPTS,c.endPTS,c.startDTS,c.endDTS);return l.hls.trigger(I.LEVEL_PTS_UPDATED,{"details":u,"level":a,"drift":h,"type":o,"frag":t,"start":c.startPTS,"end":c.endPTS}),!0}return r}),!1))a.fragmentError=0;else if(null===(null==(o=this.transmuxer)?void 0:o.error)){var c=new Error("Found no media in fragment ".concat(t.sn," of level ").concat(a.id," resetting transmuxer to fallback to playlist timing"));if(this.warn(c.message),this.hls.trigger(I.ERROR,{"type":D.MEDIA_ERROR,"details":b.FRAG_PARSING_ERROR,"fatal":!1,"error":c,"frag":t,"reason":"Found no media in msn ".concat(t.sn,' of level "').concat(a.url,'"')}),!this.hls)return;this.resetTransmuxer()}this.state=ft.PARSED,this.hls.trigger(I.FRAG_PARSED,{"frag":t,"part":r})}else this.warn("level.details undefined")}},{"key":"resetTransmuxer","value":function resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}},{"key":"recoverWorkerError","value":function recoverWorkerError(t){"demuxerWorker"===t.event&&(this.resetTransmuxer(),this.resetLoadingState())}},{"key":"state","get":function get(){return this._state},"set":function set(t){var r=this._state;r!==t&&(this._state=t,this.log("".concat(r,"->").concat(t)))}}]),BaseStreamController}(it);function getSourceBuffer(){return self.SourceBuffer||self.WebKitSourceBuffer}function dummyTrack(){return{"type":arguments.length>0&&void 0!==arguments[0]?arguments[0]:"","id":-1,"pid":-1,"inputTimeScale":arguments.length>1&&void 0!==arguments[1]?arguments[1]:9e4,"sequenceNumber":-1,"samples":[],"dropped":0}}var vt=function(){function BaseAudioDemuxer(){(0,m.Z)(this,BaseAudioDemuxer),this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}return(0,y.Z)(BaseAudioDemuxer,[{"key":"resetInitSegment","value":function resetInitSegment(t,r,a,i){this._id3Track={"type":"id3","id":3,"pid":-1,"inputTimeScale":9e4,"sequenceNumber":0,"samples":[],"dropped":0}}},{"key":"resetTimeStamp","value":function resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}},{"key":"resetContiguity","value":function resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}},{"key":"canParse","value":function canParse(t,r){return!1}},{"key":"appendFrame","value":function appendFrame(t,r,a){}},{"key":"demux","value":function demux(t,r){this.cachedData&&(t=appendUint8Array(this.cachedData,t),this.cachedData=null);var a,i=Q(t,0),o=i?i.length:0,l=this._audioTrack,u=this._id3Track,c=i?function getTimeStamp(t){for(var r=re(t),a=0;a<r.length;a++){var i=r[a];if(ee(i))return oe(i)}}(i):void 0,d=t.length;for((null===this.basePTS||0===this.frameIndex&&R(c))&&(this.basePTS=mt(c,r,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&u.samples.push({"pts":this.lastPTS,"dts":this.lastPTS,"data":i,"type":De,"duration":Number.POSITIVE_INFINITY});o<d;){if(this.canParse(t,o)){var h=this.appendFrame(l,t,o);h?(this.frameIndex++,this.lastPTS=h.sample.pts,a=o+=h.length):o=d}else J(t,o)?(i=Q(t,o),u.samples.push({"pts":this.lastPTS,"dts":this.lastPTS,"data":i,"type":De,"duration":Number.POSITIVE_INFINITY}),a=o+=i.length):o++;if(o===d&&a!==d){var g=sliceUint8(t,a);this.cachedData?this.cachedData=appendUint8Array(this.cachedData,g):this.cachedData=g}}return{"audioTrack":l,"videoTrack":dummyTrack(),"id3Track":u,"textTrack":dummyTrack()}}},{"key":"demuxSampleAes","value":function demuxSampleAes(t,r,a){return Promise.reject(new Error("[".concat(this,"] This demuxer does not support Sample-AES decryption")))}},{"key":"flush","value":function flush(t){var r=this.cachedData;return r&&(this.cachedData=null,this.demux(r,0)),{"audioTrack":this._audioTrack,"videoTrack":dummyTrack(),"id3Track":this._id3Track,"textTrack":dummyTrack()}}},{"key":"destroy","value":function destroy(){}}]),BaseAudioDemuxer}(),mt=function initPTSFn(t,r,a){return R(t)?90*t:9e4*r+(a?9e4*a.baseTime/a.timescale:0)};function isHeaderPattern$1(t,r){return 255===t[r]&&240==(246&t[r+1])}function getHeaderLength(t,r){return 1&t[r+1]?7:9}function getFullFrameLength(t,r){return(3&t[r+3])<<11|t[r+4]<<3|(224&t[r+5])>>>5}function isHeader$1(t,r){return r+1<t.length&&isHeaderPattern$1(t,r)}function probe$1(t,r){if(isHeader$1(t,r)){var a=getHeaderLength(t,r);if(r+a>=t.length)return!1;var i=getFullFrameLength(t,r);if(i<=a)return!1;var o=r+i;return o===t.length||isHeader$1(t,o)}return!1}function initTrackConfig(t,r,a,i,o){if(!t.samplerate){var l=function getAudioConfig(t,r,a,i){var o,l,u,c,d=navigator.userAgent.toLowerCase(),h=i,g=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];o=1+((192&r[a+2])>>>6);var v=(60&r[a+2])>>>2;if(!(v>g.length-1))return u=(1&r[a+2])<<2,u|=(192&r[a+3])>>>6,w.log("manifest codec:".concat(i,", ADTS type:").concat(o,", samplingIndex:").concat(v)),/firefox/i.test(d)?v>=6?(o=5,c=new Array(4),l=v-3):(o=2,c=new Array(2),l=v):-1!==d.indexOf("android")?(o=2,c=new Array(2),l=v):(o=5,c=new Array(4),i&&(-1!==i.indexOf("mp4a.40.29")||-1!==i.indexOf("mp4a.40.5"))||!i&&v>=6?l=v-3:((i&&-1!==i.indexOf("mp4a.40.2")&&(v>=6&&1===u||/vivaldi/i.test(d))||!i&&1===u)&&(o=2,c=new Array(2)),l=v)),c[0]=o<<3,c[0]|=(14&v)>>1,c[1]|=(1&v)<<7,c[1]|=u<<3,5===o&&(c[1]|=(14&l)>>1,c[2]=(1&l)<<7,c[2]|=8,c[3]=0),{"config":c,"samplerate":g[v],"channelCount":u,"codec":"mp4a.40."+o,"manifestCodec":h};t.trigger(I.ERROR,{"type":D.MEDIA_ERROR,"details":b.FRAG_PARSING_ERROR,"fatal":!0,"reason":"invalid ADTS sampling index:".concat(v)})}(r,a,i,o);if(!l)return;t.config=l.config,t.samplerate=l.samplerate,t.channelCount=l.channelCount,t.codec=l.codec,t.manifestCodec=l.manifestCodec,w.log("parsed codec:".concat(t.codec,", rate:").concat(l.samplerate,", channels:").concat(l.channelCount))}}function getFrameDuration(t){return 9216e4/t}function appendFrame$1(t,r,a,i,o){var l,u=i+o*getFrameDuration(t.samplerate),c=function parseFrameHeader(t,r){var a=getHeaderLength(t,r);if(r+a<=t.length){var i=getFullFrameLength(t,r)-a;if(i>0)return{"headerLength":a,"frameLength":i}}}(r,a);if(c){var d=c.frameLength,h=c.headerLength,g=h+d,v=Math.max(0,a+g-r.length);v?(l=new Uint8Array(g-h)).set(r.subarray(a+h,r.length),0):l=r.subarray(a+h,a+g);var m={"unit":l,"pts":u};return v||t.samples.push(m),{"sample":m,"length":g,"missing":v}}var y=r.length-a;return(l=new Uint8Array(y)).set(r.subarray(a,r.length),0),{"sample":{"unit":l,"pts":u},"length":y,"missing":-1}}var yt=function(t){(0,g.Z)(AACDemuxer,t);var r=(0,v.Z)(AACDemuxer);function AACDemuxer(t,a){var i;return(0,m.Z)(this,AACDemuxer),(i=r.call(this)).observer=void 0,i.config=void 0,i.observer=t,i.config=a,i}return(0,y.Z)(AACDemuxer,[{"key":"resetInitSegment","value":function resetInitSegment(t,r,a,i){(0,d.Z)((0,h.Z)(AACDemuxer.prototype),"resetInitSegment",this).call(this,t,r,a,i),this._audioTrack={"container":"audio/adts","type":"audio","id":2,"pid":-1,"sequenceNumber":0,"segmentCodec":"aac","samples":[],"manifestCodec":r,"duration":i,"inputTimeScale":9e4,"dropped":0}}},{"key":"canParse","value":function canParse(t,r){return function canParse$1(t,r){return function canGetFrameLength(t,r){return r+5<t.length}(t,r)&&isHeaderPattern$1(t,r)&&getFullFrameLength(t,r)<=t.length-r}(t,r)}},{"key":"appendFrame","value":function appendFrame(t,r,a){initTrackConfig(t,this.observer,r,a,t.manifestCodec);var i=appendFrame$1(t,r,a,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i}}],[{"key":"probe","value":function probe(t){if(!t)return!1;for(var r=(Q(t,0)||[]).length,a=t.length;r<a;r++)if(probe$1(t,r))return w.log("ADTS sync word found !"),!0;return!1}}]),AACDemuxer}(vt),pt=/\/emsg[-/]ID3/i,Tt=function(){function MP4Demuxer(t,r){(0,m.Z)(this,MP4Demuxer),this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=r}return(0,y.Z)(MP4Demuxer,[{"key":"resetTimeStamp","value":function resetTimeStamp(){}},{"key":"resetInitSegment","value":function resetInitSegment(t,r,a,i){var o=this.videoTrack=dummyTrack("video",1),l=this.audioTrack=dummyTrack("audio",1),u=this.txtTrack=dummyTrack("text",1);if(this.id3Track=dummyTrack("id3",1),this.timeOffset=0,null!=t&&t.byteLength){var c=parseInitSegment(t);if(c.video){var d=c.video,h=d.id,g=d.timescale,v=d.codec;o.id=h,o.timescale=u.timescale=g,o.codec=v}if(c.audio){var m=c.audio,y=m.id,p=m.timescale,T=m.codec;l.id=y,l.timescale=p,l.codec=T}u.id=he.text,o.sampleDuration=0,o.duration=l.duration=i}}},{"key":"resetContiguity","value":function resetContiguity(){this.remainderData=null}},{"key":"demux","value":function demux(t,r){this.timeOffset=r;var a=t,i=this.videoTrack,o=this.txtTrack;if(this.config.progressive){this.remainderData&&(a=appendUint8Array(this.remainderData,t));var l=function segmentValidRange(t){var r={"valid":null,"remainder":null},a=findBox(t,["moof"]);if(!a)return r;if(a.length<2)return r.remainder=t,r;var i=a[a.length-1];return r.valid=sliceUint8(t,0,i.byteOffset-8),r.remainder=sliceUint8(t,i.byteOffset-8),r}(a);this.remainderData=l.remainder,i.samples=l.valid||new Uint8Array}else i.samples=a;var u=this.extractID3Track(i,r);return o.samples=parseSamples(r,i),{"videoTrack":i,"audioTrack":this.audioTrack,"id3Track":u,"textTrack":this.txtTrack}}},{"key":"flush","value":function flush(){var t=this.timeOffset,r=this.videoTrack,a=this.txtTrack;r.samples=this.remainderData||new Uint8Array,this.remainderData=null;var i=this.extractID3Track(r,this.timeOffset);return a.samples=parseSamples(t,r),{"videoTrack":r,"audioTrack":dummyTrack(),"id3Track":i,"textTrack":dummyTrack()}}},{"key":"extractID3Track","value":function extractID3Track(t,r){var a=this.id3Track;if(t.samples.length){var i=findBox(t.samples,["emsg"]);i&&i.forEach((function(t){var i=function parseEmsg(t){var r=t[0],a="",i="",o=0,l=0,u=0,c=0,d=0,h=0;if(0===r){for(;"\0"!==bin2str(t.subarray(h,h+1));)a+=bin2str(t.subarray(h,h+1)),h+=1;for(a+=bin2str(t.subarray(h,h+1)),h+=1;"\0"!==bin2str(t.subarray(h,h+1));)i+=bin2str(t.subarray(h,h+1)),h+=1;i+=bin2str(t.subarray(h,h+1)),h+=1,o=readUint32(t,12),l=readUint32(t,16),c=readUint32(t,20),d=readUint32(t,24),h=28}else if(1===r){o=readUint32(t,h+=4);var g=readUint32(t,h+=4),v=readUint32(t,h+=4);for(h+=4,u=Math.pow(2,32)*g+v,Number.isSafeInteger(u)||(u=Number.MAX_SAFE_INTEGER,w.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),c=readUint32(t,h),d=readUint32(t,h+=4),h+=4;"\0"!==bin2str(t.subarray(h,h+1));)a+=bin2str(t.subarray(h,h+1)),h+=1;for(a+=bin2str(t.subarray(h,h+1)),h+=1;"\0"!==bin2str(t.subarray(h,h+1));)i+=bin2str(t.subarray(h,h+1)),h+=1;i+=bin2str(t.subarray(h,h+1)),h+=1}return{"schemeIdUri":a,"value":i,"timeScale":o,"presentationTime":u,"presentationTimeDelta":l,"eventDuration":c,"id":d,"payload":t.subarray(h,t.byteLength)}}(t);if(pt.test(i.schemeIdUri)){var o=R(i.presentationTime)?i.presentationTime/i.timeScale:r+i.presentationTimeDelta/i.timeScale,l=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);var u=i.payload;a.samples.push({"data":u,"len":u.byteLength,"dts":o,"pts":o,"type":Ce,"duration":l})}}))}return a}},{"key":"demuxSampleAes","value":function demuxSampleAes(t,r,a){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}},{"key":"destroy","value":function destroy(){}}],[{"key":"probe","value":function probe(t){return findBox(t=t.length>16384?t.subarray(0,16384):t,["moof"]).length>0}}]),MP4Demuxer}(),Et=null,kt=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],St=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Lt=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],At=[0,1,1,4];function _appendFrame(t,r,a,i,o){if(!(a+24>r.length)){var l=parseHeader(r,a);if(l&&a+l.frameLength<=r.length){var u=i+o*(9e4*l.samplesPerFrame/l.sampleRate),c={"unit":r.subarray(a,a+l.frameLength),"pts":u,"dts":u};return t.config=[],t.channelCount=l.channelCount,t.samplerate=l.sampleRate,t.samples.push(c),{"sample":c,"length":l.frameLength,"missing":0}}}}function parseHeader(t,r){var a=t[r+1]>>3&3,i=t[r+1]>>1&3,o=t[r+2]>>4&15,l=t[r+2]>>2&3;if(1!==a&&0!==o&&15!==o&&3!==l){var u=t[r+2]>>1&1,c=t[r+3]>>6,d=1e3*kt[14*(3===a?3-i:3===i?3:4)+o-1],h=St[3*(3===a?0:2===a?1:2)+l],g=3===c?1:2,v=Lt[a][i],m=At[i],y=8*v*m,p=Math.floor(v*d/h+u)*m;if(null===Et){var T=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Et=T?parseInt(T[1]):0}return!!Et&&Et<=87&&2===i&&d>=224e3&&0===c&&(t[r+3]=128|t[r+3]),{"sampleRate":h,"channelCount":g,"frameLength":p,"samplesPerFrame":y}}}function isHeaderPattern(t,r){return 255===t[r]&&224==(224&t[r+1])&&0!=(6&t[r+1])}function isHeader(t,r){return r+1<t.length&&isHeaderPattern(t,r)}function _probe(t,r){if(r+1<t.length&&isHeaderPattern(t,r)){var a=parseHeader(t,r),i=4;null!=a&&a.frameLength&&(i=a.frameLength);var o=r+i;return o===t.length||isHeader(t,o)}return!1}var Rt=function(){function ExpGolomb(t){(0,m.Z)(this,ExpGolomb),this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}return(0,y.Z)(ExpGolomb,[{"key":"loadWord","value":function loadWord(){var t=this.data,r=this.bytesAvailable,a=t.byteLength-r,i=new Uint8Array(4),o=Math.min(4,r);if(0===o)throw new Error("no bytes available");i.set(t.subarray(a,a+o)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*o,this.bytesAvailable-=o}},{"key":"skipBits","value":function skipBits(t){var r;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,t-=(r=t>>3)<<3,this.bytesAvailable-=r,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}},{"key":"readBits","value":function readBits(t){var r=Math.min(this.bitsAvailable,t),a=this.word>>>32-r;if(t>32&&w.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=r,this.bitsAvailable>0)this.word<<=r;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return(r=t-r)>0&&this.bitsAvailable?a<<r|this.readBits(r):a}},{"key":"skipLZ","value":function skipLZ(){var t;for(t=0;t<this.bitsAvailable;++t)if(0!=(this.word&2147483648>>>t))return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}},{"key":"skipUEG","value":function skipUEG(){this.skipBits(1+this.skipLZ())}},{"key":"skipEG","value":function skipEG(){this.skipBits(1+this.skipLZ())}},{"key":"readUEG","value":function readUEG(){var t=this.skipLZ();return this.readBits(t+1)-1}},{"key":"readEG","value":function readEG(){var t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}},{"key":"readBoolean","value":function readBoolean(){return 1===this.readBits(1)}},{"key":"readUByte","value":function readUByte(){return this.readBits(8)}},{"key":"readUShort","value":function readUShort(){return this.readBits(16)}},{"key":"readUInt","value":function readUInt(){return this.readBits(32)}},{"key":"skipScalingList","value":function skipScalingList(t){for(var r=8,a=8,i=0;i<t;i++)0!==a&&(a=(r+this.readEG()+256)%256),r=0===a?r:a}},{"key":"readSPS","value":function readSPS(){var t,r,a,i=0,o=0,l=0,u=0,c=this.readUByte.bind(this),d=this.readBits.bind(this),h=this.readUEG.bind(this),g=this.readBoolean.bind(this),v=this.skipBits.bind(this),m=this.skipEG.bind(this),y=this.skipUEG.bind(this),p=this.skipScalingList.bind(this);c();var T=c();if(d(5),v(3),c(),y(),100===T||110===T||122===T||244===T||44===T||83===T||86===T||118===T||128===T){var E=h();if(3===E&&v(1),y(),y(),v(1),g())for(r=3!==E?8:12,a=0;a<r;a++)g()&&p(a<6?16:64)}y();var k=h();if(0===k)h();else if(1===k)for(v(1),m(),m(),t=h(),a=0;a<t;a++)m();y(),v(1);var S=h(),L=h(),A=d(1);0===A&&v(1),v(1),g()&&(i=h(),o=h(),l=h(),u=h());var R=[1,1];if(g()&&g())switch(c()){case 1:R=[1,1];break;case 2:R=[12,11];break;case 3:R=[10,11];break;case 4:R=[16,11];break;case 5:R=[40,33];break;case 6:R=[24,11];break;case 7:R=[20,11];break;case 8:R=[32,11];break;case 9:R=[80,33];break;case 10:R=[18,11];break;case 11:R=[15,11];break;case 12:R=[64,33];break;case 13:R=[160,99];break;case 14:R=[4,3];break;case 15:R=[3,2];break;case 16:R=[2,1];break;case 255:R=[c()<<8|c(),c()<<8|c()]}return{"width":Math.ceil(16*(S+1)-2*i-2*o),"height":(2-A)*(L+1)*16-(A?2:4)*(l+u),"pixelRatio":R}}},{"key":"readSliceType","value":function readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}]),ExpGolomb}(),It=function(){function SampleAesDecrypter(t,r,a){(0,m.Z)(this,SampleAesDecrypter),this.keyData=void 0,this.decrypter=void 0,this.keyData=a,this.decrypter=new dt(r,{"removePKCS7Padding":!1})}return(0,y.Z)(SampleAesDecrypter,[{"key":"decryptBuffer","value":function decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer)}},{"key":"decryptAacSample","value":function decryptAacSample(t,r,a){var i=this,o=t[r].unit;if(!(o.length<=16)){var l=o.subarray(16,o.length-o.length%16),u=l.buffer.slice(l.byteOffset,l.byteOffset+l.length);this.decryptBuffer(u).then((function(l){var u=new Uint8Array(l);o.set(u,16),i.decrypter.isSync()||i.decryptAacSamples(t,r+1,a)}))}}},{"key":"decryptAacSamples","value":function decryptAacSamples(t,r,a){for(;;r++){if(r>=t.length)return void a();if(!(t[r].unit.length<32)&&(this.decryptAacSample(t,r,a),!this.decrypter.isSync()))return}}},{"key":"getAvcEncryptedData","value":function getAvcEncryptedData(t){for(var r=16*Math.floor((t.length-48)/160)+16,a=new Int8Array(r),i=0,o=32;o<t.length-16;o+=160,i+=16)a.set(t.subarray(o,o+16),i);return a}},{"key":"getAvcDecryptedUnit","value":function getAvcDecryptedUnit(t,r){for(var a=new Uint8Array(r),i=0,o=32;o<t.length-16;o+=160,i+=16)t.set(a.subarray(i,i+16),o);return t}},{"key":"decryptAvcSample","value":function decryptAvcSample(t,r,a,i,o){var l=this,u=discardEPB(o.data),c=this.getAvcEncryptedData(u);this.decryptBuffer(c.buffer).then((function(c){o.data=l.getAvcDecryptedUnit(u,c),l.decrypter.isSync()||l.decryptAvcSamples(t,r,a+1,i)}))}},{"key":"decryptAvcSamples","value":function decryptAvcSamples(t,r,a,i){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;r++,a=0){if(r>=t.length)return void i();for(var o=t[r].units;!(a>=o.length);a++){var l=o[a];if(!(l.data.length<=48||1!==l.type&&5!==l.type||(this.decryptAvcSample(t,r,a,i,l),this.decrypter.isSync())))return}}}}]),SampleAesDecrypter}(),Dt=188,bt=function(){function TSDemuxer(t,r,a){(0,m.Z)(this,TSDemuxer),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=t,this.config=r,this.typeSupported=a}return(0,y.Z)(TSDemuxer,[{"key":"resetInitSegment","value":function resetInitSegment(t,r,a,i){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=TSDemuxer.createTrack("video"),this._audioTrack=TSDemuxer.createTrack("audio",i),this._id3Track=TSDemuxer.createTrack("id3"),this._txtTrack=TSDemuxer.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=a,this._duration=i}},{"key":"resetTimeStamp","value":function resetTimeStamp(){}},{"key":"resetContiguity","value":function resetContiguity(){var t=this._audioTrack,r=this._avcTrack,a=this._id3Track;t&&(t.pesData=null),r&&(r.pesData=null),a&&(a.pesData=null),this.aacOverFlow=null,this.avcSample=null,this.remainderData=null}},{"key":"demux","value":function demux(t,r){var a,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];i||(this.sampleAes=null);var l=this._avcTrack,u=this._audioTrack,c=this._id3Track,d=this._txtTrack,h=l.pid,g=l.pesData,v=u.pid,m=c.pid,y=u.pesData,p=c.pesData,T=null,E=this.pmtParsed,k=this._pmtId,S=t.length;if(this.remainderData&&(S=(t=appendUint8Array(this.remainderData,t)).length,this.remainderData=null),S<Dt&&!o)return this.remainderData=t,{"audioTrack":u,"videoTrack":l,"id3Track":c,"textTrack":d};var L=Math.max(0,TSDemuxer.syncOffset(t));(S-=(S-L)%Dt)<t.byteLength&&!o&&(this.remainderData=new Uint8Array(t.buffer,S,t.buffer.byteLength-S));for(var A=0,R=L;R<S;R+=Dt)if(71===t[R]){var C=!!(64&t[R+1]),P=parsePID(t,R),_=void 0;if((48&t[R+3])>>4>1){if((_=R+5+t[R+4])===R+Dt)continue}else _=R+4;switch(P){case h:C&&(g&&(a=parsePES(g))&&this.parseAVCPES(l,d,a,!1),g={"data":[],"size":0}),g&&(g.data.push(t.subarray(_,R+Dt)),g.size+=R+Dt-_);break;case v:if(C){if(y&&(a=parsePES(y)))switch(u.segmentCodec){case"aac":this.parseAACPES(u,a);break;case"mp3":this.parseMPEGPES(u,a)}y={"data":[],"size":0}}y&&(y.data.push(t.subarray(_,R+Dt)),y.size+=R+Dt-_);break;case m:C&&(p&&(a=parsePES(p))&&this.parseID3PES(c,a),p={"data":[],"size":0}),p&&(p.data.push(t.subarray(_,R+Dt)),p.size+=R+Dt-_);break;case 0:C&&(_+=t[_]+1),k=this._pmtId=parsePAT(t,_);break;case k:C&&(_+=t[_]+1);var M=parsePMT(t,_,this.typeSupported,i);(h=M.avc)>0&&(l.pid=h),(v=M.audio)>0&&(u.pid=v,u.segmentCodec=M.segmentCodec),(m=M.id3)>0&&(c.pid=m),null===T||E||(w.warn("MPEG-TS PMT found at ".concat(R," after unknown PID '").concat(T,"'. Backtracking to sync byte @").concat(L," to parse all TS packets.")),T=null,R=L-188),E=this.pmtParsed=!0;break;case 17:case 8191:break;default:T=P}}else A++;if(A>0){var x=new Error("Found ".concat(A," TS packet/s that do not start with 0x47"));this.observer.emit(I.ERROR,I.ERROR,{"type":D.MEDIA_ERROR,"details":b.FRAG_PARSING_ERROR,"fatal":!1,"error":x,"reason":x.message})}l.pesData=g,u.pesData=y,c.pesData=p;var O={"audioTrack":u,"videoTrack":l,"id3Track":c,"textTrack":d};return o&&this.extractRemainingSamples(O),O}},{"key":"flush","value":function flush(){var t,r=this.remainderData;return this.remainderData=null,t=r?this.demux(r,-1,!1,!0):{"videoTrack":this._avcTrack,"audioTrack":this._audioTrack,"id3Track":this._id3Track,"textTrack":this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}},{"key":"extractRemainingSamples","value":function extractRemainingSamples(t){var r,a=t.audioTrack,i=t.videoTrack,o=t.id3Track,l=t.textTrack,u=i.pesData,c=a.pesData,d=o.pesData;if(u&&(r=parsePES(u))?(this.parseAVCPES(i,l,r,!0),i.pesData=null):i.pesData=u,c&&(r=parsePES(c))){switch(a.segmentCodec){case"aac":this.parseAACPES(a,r);break;case"mp3":this.parseMPEGPES(a,r)}a.pesData=null}else null!=c&&c.size&&w.log("last AAC PES packet truncated,might overlap between fragments"),a.pesData=c;d&&(r=parsePES(d))?(this.parseID3PES(o,r),o.pesData=null):o.pesData=d}},{"key":"demuxSampleAes","value":function demuxSampleAes(t,r,a){var i=this.demux(t,a,!0,!this.config.progressive),o=this.sampleAes=new It(this.observer,this.config,r);return this.decrypt(i,o)}},{"key":"decrypt","value":function decrypt(t,r){return new Promise((function(a){var i=t.audioTrack,o=t.videoTrack;i.samples&&"aac"===i.segmentCodec?r.decryptAacSamples(i.samples,0,(function(){o.samples?r.decryptAvcSamples(o.samples,0,0,(function(){a(t)})):a(t)})):o.samples&&r.decryptAvcSamples(o.samples,0,0,(function(){a(t)}))}))}},{"key":"destroy","value":function destroy(){this._duration=0}},{"key":"parseAVCPES","value":function parseAVCPES(t,r,a,i){var o,l=this,u=this.parseAVCNALu(t,a.data),c=this.avcSample,d=!1;a.data=null,c&&u.length&&!t.audFound&&(pushAccessUnit(c,t),c=this.avcSample=createAVCSample(!1,a.pts,a.dts,"")),u.forEach((function(i){switch(i.type){case 1:o=!0,c||(c=l.avcSample=createAVCSample(!0,a.pts,a.dts,"")),c.frame=!0;var u=i.data;if(d&&u.length>4){var h=new Rt(u).readSliceType();2!==h&&4!==h&&7!==h&&9!==h||(c.key=!0)}break;case 5:o=!0,c||(c=l.avcSample=createAVCSample(!0,a.pts,a.dts,"")),c.key=!0,c.frame=!0;break;case 6:o=!0,parseSEIMessageFromNALu(i.data,1,a.pts,r.samples);break;case 7:if(o=!0,d=!0,!t.sps){var g=i.data,v=new Rt(g).readSPS();t.width=v.width,t.height=v.height,t.pixelRatio=v.pixelRatio,t.sps=[g],t.duration=l._duration;for(var m=g.subarray(1,4),y="avc1.",p=0;p<3;p++){var T=m[p].toString(16);T.length<2&&(T="0"+T),y+=T}t.codec=y}break;case 8:o=!0,t.pps||(t.pps=[i.data]);break;case 9:o=!1,t.audFound=!0,c&&pushAccessUnit(c,t),c=l.avcSample=createAVCSample(!1,a.pts,a.dts,"");break;case 12:o=!0;break;default:o=!1,c&&(c.debug+="unknown NAL "+i.type+" ")}c&&o&&c.units.push(i)})),i&&c&&(pushAccessUnit(c,t),this.avcSample=null)}},{"key":"getLastNalUnit","value":function getLastNalUnit(t){var r,a,i=this.avcSample;if(i&&0!==i.units.length||(i=t[t.length-1]),null!=(r=i)&&r.units){var o=i.units;a=o[o.length-1]}return a}},{"key":"parseAVCNALu","value":function parseAVCNALu(t,r){var a,i,o=r.byteLength,l=t.naluState||0,u=l,c=[],d=0,h=-1,g=0;for(-1===l&&(h=0,g=31&r[0],l=0,d=1);d<o;)if(a=r[d++],l)if(1!==l)if(a)if(1===a){if(h>=0){var v={"data":r.subarray(h,d-l-1),"type":g};c.push(v)}else{var m=this.getLastNalUnit(t.samples);if(m&&(u&&d<=4-u&&m.state&&(m.data=m.data.subarray(0,m.data.byteLength-u)),(i=d-l-1)>0)){var y=new Uint8Array(m.data.byteLength+i);y.set(m.data,0),y.set(r.subarray(0,i),m.data.byteLength),m.data=y,m.state=0}}d<o?(h=d,g=31&r[d],l=0):l=-1}else l=0;else l=3;else l=a?0:2;else l=a?0:1;if(h>=0&&l>=0){var p={"data":r.subarray(h,o),"type":g,"state":l};c.push(p)}if(0===c.length){var T=this.getLastNalUnit(t.samples);if(T){var E=new Uint8Array(T.data.byteLength+r.byteLength);E.set(T.data,0),E.set(r,T.data.byteLength),T.data=E}}return t.naluState=l,c}},{"key":"parseAACPES","value":function parseAACPES(t,r){var a,i,o,l=0,u=this.aacOverFlow,c=r.data;if(u){this.aacOverFlow=null;var d=u.missing,h=u.sample.unit.byteLength;if(-1===d){var g=new Uint8Array(h+c.byteLength);g.set(u.sample.unit,0),g.set(c,h),c=g}else{var v=h-d;u.sample.unit.set(c.subarray(0,d),v),t.samples.push(u.sample),l=u.missing}}for(a=l,i=c.length;a<i-1&&!isHeader$1(c,a);a++);if(a!==l){var m,y=a<i-1;m=y?"AAC PES did not start with ADTS header,offset:".concat(a):"No ADTS header found in AAC PES";var p=new Error(m);if(w.warn("parsing error: ".concat(m)),this.observer.emit(I.ERROR,I.ERROR,{"type":D.MEDIA_ERROR,"details":b.FRAG_PARSING_ERROR,"fatal":!1,"levelRetry":y,"error":p,"reason":m}),!y)return}if(initTrackConfig(t,this.observer,c,a,this.audioCodec),void 0!==r.pts)o=r.pts;else{if(!u)return void w.warn("[tsdemuxer]: AAC PES unknown PTS");var T=getFrameDuration(t.samplerate);o=u.sample.pts+T}for(var E,k=0;a<i;){if(a+=(E=appendFrame$1(t,c,a,o,k)).length,E.missing){this.aacOverFlow=E;break}for(k++;a<i-1&&!isHeader$1(c,a);a++);}}},{"key":"parseMPEGPES","value":function parseMPEGPES(t,r){var a=r.data,i=a.length,o=0,l=0,u=r.pts;if(void 0!==u)for(;l<i;)if(isHeader(a,l)){var c=_appendFrame(t,a,l,u,o);if(!c)break;l+=c.length,o++}else l++;else w.warn("[tsdemuxer]: MPEG PES unknown PTS")}},{"key":"parseID3PES","value":function parseID3PES(t,r){if(void 0!==r.pts){var a=_extends({},r,{"type":this._avcTrack?Ce:De,"duration":Number.POSITIVE_INFINITY});t.samples.push(a)}else w.warn("[tsdemuxer]: ID3 PES unknown PTS")}}],[{"key":"probe","value":function probe(t){var r=TSDemuxer.syncOffset(t);return r>0&&w.warn("MPEG2-TS detected but first sync word found @ offset ".concat(r)),-1!==r}},{"key":"syncOffset","value":function syncOffset(t){for(var r=t.length,a=Math.min(5*Dt,t.length-Dt)+1,i=0;i<a;){for(var o=!1,l=i;l<r&&71===t[l];l+=Dt)if(o||0!==parsePID(t,l)||(o=!0),o&&l+Dt>a)return i;i++}return-1}},{"key":"createTrack","value":function createTrack(t,r){return{"container":"video"===t||"audio"===t?"video/mp2t":void 0,"type":t,"id":he[t],"pid":-1,"inputTimeScale":9e4,"sequenceNumber":0,"samples":[],"dropped":0,"duration":"audio"===t?r:void 0}}}]),TSDemuxer}();function createAVCSample(t,r,a,i){return{"key":t,"frame":!1,"pts":r,"dts":a,"units":[],"debug":i,"length":0}}function parsePID(t,r){return((31&t[r+1])<<8)+t[r+2]}function parsePAT(t,r){return(31&t[r+10])<<8|t[r+11]}function parsePMT(t,r,a,i){var o={"audio":-1,"avc":-1,"id3":-1,"segmentCodec":"aac"},l=r+3+((15&t[r+1])<<8|t[r+2])-4;for(r+=12+((15&t[r+10])<<8|t[r+11]);r<l;){var u=parsePID(t,r);switch(t[r]){case 207:if(!i){w.log("ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream");break}case 15:-1===o.audio&&(o.audio=u);break;case 21:-1===o.id3&&(o.id3=u);break;case 219:if(!i){w.log("H.264 with AES-128-CBC slice encryption found in unencrypted stream");break}case 27:-1===o.avc&&(o.avc=u);break;case 3:case 4:!0!==a.mpeg&&!0!==a.mp3?w.log("MPEG audio found, not supported in this browser"):-1===o.audio&&(o.audio=u,o.segmentCodec="mp3");break;case 36:w.warn("Unsupported HEVC stream type found")}r+=5+((15&t[r+3])<<8|t[r+4])}return o}function parsePES(t){var r,a,i,o,l,u=0,c=t.data;if(!t||0===t.size)return null;for(;c[0].length<19&&c.length>1;){var d=new Uint8Array(c[0].length+c[1].length);d.set(c[0]),d.set(c[1],c[0].length),c[0]=d,c.splice(1,1)}if(1===((r=c[0])[0]<<16)+(r[1]<<8)+r[2]){if((a=(r[4]<<8)+r[5])&&a>t.size-6)return null;var h=r[7];192&h&&(o=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,64&h?o-(l=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[18])/2)>54e5&&(w.warn("".concat(Math.round((o-l)/9e4),"s delta between PTS and DTS, align them")),o=l):l=o);var g=(i=r[8])+9;if(t.size<=g)return null;t.size-=g;for(var v=new Uint8Array(t.size),m=0,y=c.length;m<y;m++){var p=(r=c[m]).byteLength;if(g){if(g>p){g-=p;continue}r=r.subarray(g),p-=g,g=0}v.set(r,u),u+=p}return a&&(a-=i+3),{"data":v,"pts":o,"dts":l,"len":a}}return null}function pushAccessUnit(t,r){if(t.units.length&&t.frame){if(void 0===t.pts){var a=r.samples,i=a.length;if(!i)return void r.dropped++;var o=a[i-1];t.pts=o.pts,t.dts=o.dts}r.samples.push(t)}t.debug.length&&w.log(t.pts+"/"+t.dts+":"+t.debug)}var Ct=function(t){(0,g.Z)(MP3Demuxer,t);var r=(0,v.Z)(MP3Demuxer);function MP3Demuxer(){return(0,m.Z)(this,MP3Demuxer),r.apply(this,arguments)}return(0,y.Z)(MP3Demuxer,[{"key":"resetInitSegment","value":function resetInitSegment(t,r,a,i){(0,d.Z)((0,h.Z)(MP3Demuxer.prototype),"resetInitSegment",this).call(this,t,r,a,i),this._audioTrack={"container":"audio/mpeg","type":"audio","id":2,"pid":-1,"sequenceNumber":0,"segmentCodec":"mp3","samples":[],"manifestCodec":r,"duration":i,"inputTimeScale":9e4,"dropped":0}}},{"key":"canParse","value":function canParse(t,r){return function _canParse(t,r){return isHeaderPattern(t,r)&&4<=t.length-r}(t,r)}},{"key":"appendFrame","value":function appendFrame(t,r,a){if(null!==this.basePTS)return _appendFrame(t,r,a,this.basePTS,this.frameIndex)}}],[{"key":"probe","value":function probe(t){if(!t)return!1;for(var r=(Q(t,0)||[]).length,a=t.length;r<a;r++)if(_probe(t,r))return w.log("MPEG Audio sync word found !"),!0;return!1}}]),MP3Demuxer}(vt),Pt=function(){function AAC(){(0,m.Z)(this,AAC)}return(0,y.Z)(AAC,null,[{"key":"getSilentFrame","value":function getSilentFrame(t,r){if("mp4a.40.2"===t){if(1===r)return new Uint8Array([0,200,0,128,35,128]);if(2===r)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===r)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===r)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===r)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===r)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===r)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===r)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===r)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}]),AAC}(),_t=Math.pow(2,32)-1,wt=function(){function MP4(){(0,m.Z)(this,MP4)}return(0,y.Z)(MP4,null,[{"key":"init","value":function init(){var t;for(t in MP4.types={"avc1":[],"avcC":[],"btrt":[],"dinf":[],"dref":[],"esds":[],"ftyp":[],"hdlr":[],"mdat":[],"mdhd":[],"mdia":[],"mfhd":[],"minf":[],"moof":[],"moov":[],"mp4a":[],".mp3":[],"mvex":[],"mvhd":[],"pasp":[],"sdtp":[],"stbl":[],"stco":[],"stsc":[],"stsd":[],"stsz":[],"stts":[],"tfdt":[],"tfhd":[],"traf":[],"trak":[],"trun":[],"trex":[],"tkhd":[],"vmhd":[],"smhd":[]},MP4.types)MP4.types.hasOwnProperty(t)&&(MP4.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);var r=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),a=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);MP4.HDLR_TYPES={"video":r,"audio":a};var i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),o=new Uint8Array([0,0,0,0,0,0,0,0]);MP4.STTS=MP4.STSC=MP4.STCO=o,MP4.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),MP4.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),MP4.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),MP4.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var l=new Uint8Array([105,115,111,109]),u=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);MP4.FTYP=MP4.box(MP4.types.ftyp,l,c,l,u),MP4.DINF=MP4.box(MP4.types.dinf,MP4.box(MP4.types.dref,i))}},{"key":"box","value":function box(t){for(var r=8,a=arguments.length,i=new Array(a>1?a-1:0),o=1;o<a;o++)i[o-1]=arguments[o];for(var l=i.length,u=l;l--;)r+=i[l].byteLength;var c=new Uint8Array(r);for(c[0]=r>>24&255,c[1]=r>>16&255,c[2]=r>>8&255,c[3]=255&r,c.set(t,4),l=0,r=8;l<u;l++)c.set(i[l],r),r+=i[l].byteLength;return c}},{"key":"hdlr","value":function hdlr(t){return MP4.box(MP4.types.hdlr,MP4.HDLR_TYPES[t])}},{"key":"mdat","value":function mdat(t){return MP4.box(MP4.types.mdat,t)}},{"key":"mdhd","value":function mdhd(t,r){r*=t;var a=Math.floor(r/(_t+1)),i=Math.floor(r%(_t+1));return MP4.box(MP4.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,a>>24,a>>16&255,a>>8&255,255&a,i>>24,i>>16&255,i>>8&255,255&i,85,196,0,0]))}},{"key":"mdia","value":function mdia(t){return MP4.box(MP4.types.mdia,MP4.mdhd(t.timescale,t.duration),MP4.hdlr(t.type),MP4.minf(t))}},{"key":"mfhd","value":function mfhd(t){return MP4.box(MP4.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}},{"key":"minf","value":function minf(t){return"audio"===t.type?MP4.box(MP4.types.minf,MP4.box(MP4.types.smhd,MP4.SMHD),MP4.DINF,MP4.stbl(t)):MP4.box(MP4.types.minf,MP4.box(MP4.types.vmhd,MP4.VMHD),MP4.DINF,MP4.stbl(t))}},{"key":"moof","value":function moof(t,r,a){return MP4.box(MP4.types.moof,MP4.mfhd(t),MP4.traf(a,r))}},{"key":"moov","value":function moov(t){for(var r=t.length,a=[];r--;)a[r]=MP4.trak(t[r]);return MP4.box.apply(null,[MP4.types.moov,MP4.mvhd(t[0].timescale,t[0].duration)].concat(a).concat(MP4.mvex(t)))}},{"key":"mvex","value":function mvex(t){for(var r=t.length,a=[];r--;)a[r]=MP4.trex(t[r]);return MP4.box.apply(null,[MP4.types.mvex].concat(a))}},{"key":"mvhd","value":function mvhd(t,r){r*=t;var a=Math.floor(r/(_t+1)),i=Math.floor(r%(_t+1)),o=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,a>>24,a>>16&255,a>>8&255,255&a,i>>24,i>>16&255,i>>8&255,255&i,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return MP4.box(MP4.types.mvhd,o)}},{"key":"sdtp","value":function sdtp(t){var r,a,i=t.samples||[],o=new Uint8Array(4+i.length);for(r=0;r<i.length;r++)a=i[r].flags,o[r+4]=a.dependsOn<<4|a.isDependedOn<<2|a.hasRedundancy;return MP4.box(MP4.types.sdtp,o)}},{"key":"stbl","value":function stbl(t){return MP4.box(MP4.types.stbl,MP4.stsd(t),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))}},{"key":"avc1","value":function avc1(t){var r,a,i,o=[],l=[];for(r=0;r<t.sps.length;r++)i=(a=t.sps[r]).byteLength,o.push(i>>>8&255),o.push(255&i),o=o.concat(Array.prototype.slice.call(a));for(r=0;r<t.pps.length;r++)i=(a=t.pps[r]).byteLength,l.push(i>>>8&255),l.push(255&i),l=l.concat(Array.prototype.slice.call(a));var u=MP4.box(MP4.types.avcC,new Uint8Array([1,o[3],o[4],o[5],255,224|t.sps.length].concat(o).concat([t.pps.length]).concat(l))),c=t.width,d=t.height,h=t.pixelRatio[0],g=t.pixelRatio[1];return MP4.box(MP4.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,255&c,d>>8&255,255&d,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),u,MP4.box(MP4.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),MP4.box(MP4.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,g>>24,g>>16&255,g>>8&255,255&g])))}},{"key":"esds","value":function esds(t){var r=t.config.length;return new Uint8Array([0,0,0,0,3,23+r,0,1,0,4,15+r,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([r]).concat(t.config).concat([6,1,2]))}},{"key":"mp4a","value":function mp4a(t){var r=t.samplerate;return MP4.box(MP4.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]),MP4.box(MP4.types.esds,MP4.esds(t)))}},{"key":"mp3","value":function mp3(t){var r=t.samplerate;return MP4.box(MP4.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]))}},{"key":"stsd","value":function stsd(t){return"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp3(t)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp4a(t)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.avc1(t))}},{"key":"tkhd","value":function tkhd(t){var r=t.id,a=t.duration*t.timescale,i=t.width,o=t.height,l=Math.floor(a/(_t+1)),u=Math.floor(a%(_t+1));return MP4.box(MP4.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,l>>24,l>>16&255,l>>8&255,255&l,u>>24,u>>16&255,u>>8&255,255&u,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,255&i,0,0,o>>8&255,255&o,0,0]))}},{"key":"traf","value":function traf(t,r){var a=MP4.sdtp(t),i=t.id,o=Math.floor(r/(_t+1)),l=Math.floor(r%(_t+1));return MP4.box(MP4.types.traf,MP4.box(MP4.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),MP4.box(MP4.types.tfdt,new Uint8Array([1,0,0,0,o>>24,o>>16&255,o>>8&255,255&o,l>>24,l>>16&255,l>>8&255,255&l])),MP4.trun(t,a.length+16+20+8+16+8+8),a)}},{"key":"trak","value":function trak(t){return t.duration=t.duration||4294967295,MP4.box(MP4.types.trak,MP4.tkhd(t),MP4.mdia(t))}},{"key":"trex","value":function trex(t){var r=t.id;return MP4.box(MP4.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}},{"key":"trun","value":function trun(t,r){var a,i,o,l,u,c,d=t.samples||[],h=d.length,g=12+16*h,v=new Uint8Array(g);for(r+=8+g,v.set(["video"===t.type?1:0,0,15,1,h>>>24&255,h>>>16&255,h>>>8&255,255&h,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),a=0;a<h;a++)o=(i=d[a]).duration,l=i.size,u=i.flags,c=i.cts,v.set([o>>>24&255,o>>>16&255,o>>>8&255,255&o,l>>>24&255,l>>>16&255,l>>>8&255,255&l,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,61440&u.degradPrio,15&u.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return MP4.box(MP4.types.trun,v)}},{"key":"initSegment","value":function initSegment(t){MP4.types||MP4.init();var r=MP4.moov(t),a=new Uint8Array(MP4.FTYP.byteLength+r.byteLength);return a.set(MP4.FTYP),a.set(r,MP4.FTYP.byteLength),a}}]),MP4}();wt.types=void 0,wt.HDLR_TYPES=void 0,wt.STTS=void 0,wt.STSC=void 0,wt.STCO=void 0,wt.STSZ=void 0,wt.VMHD=void 0,wt.SMHD=void 0,wt.STSD=void 0,wt.FTYP=void 0,wt.DINF=void 0;var Mt=9e4;function toTimescaleFromBase(t,r){var a=t*r*(arguments.length>2&&void 0!==arguments[2]?arguments[2]:1);return arguments.length>3&&void 0!==arguments[3]&&arguments[3]?Math.round(a):a}function toMsFromMpegTsClock(t){return toTimescaleFromBase(t,1e3,1/Mt,arguments.length>1&&void 0!==arguments[1]&&arguments[1])}var xt=null,Ft=null,Ot=function(){function MP4Remuxer(t,r,a){if((0,m.Z)(this,MP4Remuxer),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.observer=t,this.config=r,this.typeSupported=a,this.ISGenerated=!1,null===xt){var i=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);xt=i?parseInt(i[1]):0}if(null===Ft){var o=navigator.userAgent.match(/Safari\/(\d+)/i);Ft=o?parseInt(o[1]):0}}return(0,y.Z)(MP4Remuxer,[{"key":"destroy","value":function destroy(){}},{"key":"resetTimeStamp","value":function resetTimeStamp(t){w.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}},{"key":"resetNextTimestamp","value":function resetNextTimestamp(){w.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}},{"key":"resetInitSegment","value":function resetInitSegment(){w.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1}},{"key":"getVideoStartPts","value":function getVideoStartPts(t){var r=!1,a=t.reduce((function(t,a){var i=a.pts-t;return i<-4294967296?(r=!0,normalizePts(t,a.pts)):i>0?t:a.pts}),t[0].pts);return r&&w.debug("PTS rollover detected"),a}},{"key":"remux","value":function remux(t,r,a,i,o,l,u,c){var d,h,g,v,m,y,p=o,T=o,E=t.pid>-1,k=r.pid>-1,S=r.samples.length,L=t.samples.length>0,A=u&&S>0||S>1;if((!E||L)&&(!k||A)||this.ISGenerated||u){this.ISGenerated||(g=this.generateIS(t,r,o,l));var R,I=this.isVideoContiguous,D=-1;if(A&&(D=function findKeyframeIndex(t){for(var r=0;r<t.length;r++)if(t[r].key)return r;return-1}(r.samples),!I&&this.config.forceKeyFrameOnDiscontinuity))if(y=!0,D>0){w.warn("[mp4-remuxer]: Dropped ".concat(D," out of ").concat(S," video samples due to a missing keyframe"));var b=this.getVideoStartPts(r.samples);r.samples=r.samples.slice(D),r.dropped+=D,R=T+=(r.samples[0].pts-b)/r.inputTimeScale}else-1===D&&(w.warn("[mp4-remuxer]: No keyframe found out of ".concat(S," video samples")),y=!1);if(this.ISGenerated){if(L&&A){var C=this.getVideoStartPts(r.samples),P=(normalizePts(t.samples[0].pts,C)-C)/r.inputTimeScale;p+=Math.max(0,P),T+=Math.max(0,-P)}if(L){if(t.samplerate||(w.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),g=this.generateIS(t,r,o,l)),h=this.remuxAudio(t,p,this.isAudioContiguous,l,k||A||c===Re.AUDIO?T:void 0),A){var _=h?h.endPTS-h.startPTS:0;r.inputTimeScale||(w.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),g=this.generateIS(t,r,o,l)),d=this.remuxVideo(r,T,I,_)}}else A&&(d=this.remuxVideo(r,T,I,0));d&&(d.firstKeyFrame=D,d.independent=-1!==D,d.firstKeyFramePTS=R)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(a.samples.length&&(m=flushTextTrackMetadataCueSamples(a,o,this._initPTS,this._initDTS)),i.samples.length&&(v=flushTextTrackUserdataCueSamples(i,o,this._initPTS))),{"audio":h,"video":d,"initSegment":g,"independent":y,"text":v,"id3":m}}},{"key":"generateIS","value":function generateIS(t,r,a,i){var o,l,u,c=t.samples,d=r.samples,h=this.typeSupported,g={},v=this._initPTS,m=!v||i,y="audio/mp4";if(m&&(o=l=1/0),t.config&&c.length){if(t.timescale=t.samplerate,"mp3"===t.segmentCodec)h.mpeg?(y="audio/mpeg",t.codec=""):h.mp3&&(t.codec="mp3");g.audio={"id":"audio","container":y,"codec":t.codec,"initSegment":"mp3"===t.segmentCodec&&h.mpeg?new Uint8Array(0):wt.initSegment([t]),"metadata":{"channelCount":t.channelCount}},m&&(u=t.inputTimeScale,v&&u===v.timescale?m=!1:o=l=c[0].pts-Math.round(u*a))}if(r.sps&&r.pps&&d.length&&(r.timescale=r.inputTimeScale,g.video={"id":"main","container":"video/mp4","codec":r.codec,"initSegment":wt.initSegment([r]),"metadata":{"width":r.width,"height":r.height}},m))if(u=r.inputTimeScale,v&&u===v.timescale)m=!1;else{var p=this.getVideoStartPts(d),T=Math.round(u*a);l=Math.min(l,normalizePts(d[0].dts,p)-T),o=Math.min(o,p-T)}if(Object.keys(g).length)return this.ISGenerated=!0,m?(this._initPTS={"baseTime":o,"timescale":u},this._initDTS={"baseTime":l,"timescale":u}):o=u=void 0,{"tracks":g,"initPTS":o,"timescale":u}}},{"key":"remuxVideo","value":function remuxVideo(t,r,a,i){var o,l,u=t.inputTimeScale,c=t.samples,d=[],h=c.length,g=this._initPTS,v=this.nextAvcDts,m=8,y=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,T=Number.NEGATIVE_INFINITY,E=!1;a&&null!==v||(v=r*u-(c[0].pts-normalizePts(c[0].dts,c[0].pts)));for(var k=g.baseTime*u/g.timescale,S=0;S<h;S++){var L=c[S];L.pts=normalizePts(L.pts-k,v),L.dts=normalizePts(L.dts-k,v),L.dts<c[S>0?S-1:S].dts&&(E=!0)}E&&c.sort((function(t,r){var a=t.dts-r.dts,i=t.pts-r.pts;return a||i})),o=c[0].dts;var A=(l=c[c.length-1].dts)-o,R=A?Math.round(A/(h-1)):y||t.inputTimeScale/30;if(a){var C=o-v,P=C>R,_=C<-1;if((P||_)&&(P?w.warn("AVC: ".concat(toMsFromMpegTsClock(C,!0)," ms (").concat(C,"dts) hole between fragments detected, filling it")):w.warn("AVC: ".concat(toMsFromMpegTsClock(-C,!0)," ms (").concat(C,"dts) overlapping between fragments detected")),!_||v>c[0].pts)){o=v;var M=c[0].pts-C;c[0].dts=o,c[0].pts=M,w.log("Video: First PTS/DTS adjusted: ".concat(toMsFromMpegTsClock(M,!0),"/").concat(toMsFromMpegTsClock(o,!0),", delta: ").concat(toMsFromMpegTsClock(C,!0)," ms"))}}o=Math.max(0,o);for(var x=0,O=0,N=0;N<h;N++){for(var U=c[N],B=U.units,G=B.length,K=0,H=0;H<G;H++)K+=B[H].data.length;O+=K,x+=G,U.length=K,U.dts=Math.max(U.dts,o),p=Math.min(U.pts,p),T=Math.max(U.pts,T)}l=c[h-1].dts;var V,W=O+4*x+8;try{V=new Uint8Array(W)}catch(t){return void this.observer.emit(I.ERROR,I.ERROR,{"type":D.MUX_ERROR,"details":b.REMUX_ALLOC_ERROR,"fatal":!1,"error":t,"bytes":W,"reason":"fail allocating video mdat ".concat(W)})}var Z=new DataView(V.buffer);Z.setUint32(0,W),V.set(wt.types.mdat,4);for(var Y=!1,j=Number.POSITIVE_INFINITY,q=Number.POSITIVE_INFINITY,z=Number.NEGATIVE_INFINITY,X=Number.NEGATIVE_INFINITY,Q=0;Q<h;Q++){for(var $=c[Q],J=$.units,ee=0,te=0,re=J.length;te<re;te++){var ae=J[te],ie=ae.data,ne=ae.data.byteLength;Z.setUint32(m,ne),m+=4,V.set(ie,m),m+=ne,ee+=4+ne}var se=void 0;if(Q<h-1)y=c[Q+1].dts-$.dts,se=c[Q+1].pts-$.pts;else{var oe=this.config,le=Q>0?$.dts-c[Q-1].dts:R;if(se=Q>0?$.pts-c[Q-1].pts:R,oe.stretchShortVideoTrack&&null!==this.nextAudioPts){var ue=Math.floor(oe.maxBufferHole*u),ce=(i?p+i*u:this.nextAudioPts)-$.pts;ce>ue?((y=ce-le)<0?y=le:Y=!0,w.log("[mp4-remuxer]: It is approximately ".concat(ce/90," ms to the next segment; using duration ").concat(y/90," ms for the last video frame."))):y=le}else y=le}var de=Math.round($.pts-$.dts);j=Math.min(j,y),z=Math.max(z,y),q=Math.min(q,se),X=Math.max(X,se),d.push(new Ut($.key,y,ee,de))}if(d.length)if(xt){if(xt<70){var he=d[0].flags;he.dependsOn=2,he.isNonSync=0}}else if(Ft&&X-q<z-j&&R/z<.025&&0===d[0].cts){w.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");for(var fe=o,ge=0,ve=d.length;ge<ve;ge++){var me=fe+d[ge].duration,ye=fe+d[ge].cts;if(ge<ve-1){var pe=me+d[ge+1].cts;d[ge].duration=pe-ye}else d[ge].duration=ge?d[ge-1].duration:R;d[ge].cts=0,fe=me}}y=Y||!y?R:y,this.nextAvcDts=v=l+y,this.videoSampleDuration=y,this.isVideoContiguous=!0;var Te={"data1":wt.moof(t.sequenceNumber++,o,_extends({},t,{"samples":d})),"data2":V,"startPTS":p/u,"endPTS":(T+y)/u,"startDTS":o/u,"endDTS":v/u,"type":"video","hasAudio":!1,"hasVideo":!0,"nb":d.length,"dropped":t.dropped};return t.samples=[],t.dropped=0,Te}},{"key":"remuxAudio","value":function remuxAudio(t,r,a,i,o){var l=t.inputTimeScale,u=l/(t.samplerate?t.samplerate:l),c="aac"===t.segmentCodec?1024:1152,d=c*u,h=this._initPTS,g="mp3"===t.segmentCodec&&this.typeSupported.mpeg,v=[],m=void 0!==o,y=t.samples,p=g?0:8,T=this.nextAudioPts||-1,E=r*l,k=h.baseTime*l/h.timescale;if(this.isAudioContiguous=a=a||y.length&&T>0&&(i&&Math.abs(E-T)<9e3||Math.abs(normalizePts(y[0].pts-k,E)-T)<20*d),y.forEach((function(t){t.pts=normalizePts(t.pts-k,E)})),!a||T<0){if(y=y.filter((function(t){return t.pts>=0})),!y.length)return;T=0===o?0:i&&!m?Math.max(0,E):y[0].pts}if("aac"===t.segmentCodec)for(var S=this.config.maxAudioFramesDrift,L=0,A=T;L<y.length;L++){var R=y[L],C=R.pts,P=C-A,_=Math.abs(1e3*P/l);if(P<=-S*d&&m)0===L&&(w.warn("Audio frame @ ".concat((C/l).toFixed(3),"s overlaps nextAudioPts by ").concat(Math.round(1e3*P/l)," ms.")),this.nextAudioPts=T=A=C);else if(P>=S*d&&_<1e4&&m){var M=Math.round(P/d);(A=C-M*d)<0&&(M--,A+=d),0===L&&(this.nextAudioPts=T=A),w.warn("[mp4-remuxer]: Injecting ".concat(M," audio frame @ ").concat((A/l).toFixed(3),"s due to ").concat(Math.round(1e3*P/l)," ms gap."));for(var x=0;x<M;x++){var O=Math.max(A,0),N=Pt.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);N||(w.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),N=R.unit.subarray()),y.splice(L,0,{"unit":N,"pts":O}),A+=d,L++}}R.pts=A,A+=d}for(var U,B=null,G=null,K=0,H=y.length;H--;)K+=y[H].unit.byteLength;for(var V=0,W=y.length;V<W;V++){var Z=y[V],Y=Z.unit,j=Z.pts;if(null!==G){v[V-1].duration=Math.round((j-G)/u)}else{if(a&&"aac"===t.segmentCodec&&(j=T),B=j,!(K>0))return;K+=p;try{U=new Uint8Array(K)}catch(t){return void this.observer.emit(I.ERROR,I.ERROR,{"type":D.MUX_ERROR,"details":b.REMUX_ALLOC_ERROR,"fatal":!1,"error":t,"bytes":K,"reason":"fail allocating audio mdat ".concat(K)})}g||(new DataView(U.buffer).setUint32(0,K),U.set(wt.types.mdat,4))}U.set(Y,p);var q=Y.byteLength;p+=q,v.push(new Ut(!0,c,q,0)),G=j}var z=v.length;if(z){var X=v[v.length-1];this.nextAudioPts=T=G+u*X.duration;var Q=g?new Uint8Array(0):wt.moof(t.sequenceNumber++,B/u,_extends({},t,{"samples":v}));t.samples=[];var $=B/l,J=T/l,ee={"data1":Q,"data2":U,"startPTS":$,"endPTS":J,"startDTS":$,"endDTS":J,"type":"audio","hasAudio":!0,"hasVideo":!1,"nb":z};return this.isAudioContiguous=!0,ee}}},{"key":"remuxEmptyAudio","value":function remuxEmptyAudio(t,r,a,i){var o=t.inputTimeScale,l=o/(t.samplerate?t.samplerate:o),u=this.nextAudioPts,c=this._initDTS,d=9e4*c.baseTime/c.timescale,h=(null!==u?u:i.startDTS*o)+d,g=i.endDTS*o+d,v=1024*l,m=Math.ceil((g-h)/v),y=Pt.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(w.warn("[mp4-remuxer]: remux empty Audio"),y){for(var p=[],T=0;T<m;T++){var E=h+T*v;p.push({"unit":y,"pts":E,"dts":E})}return t.samples=p,this.remuxAudio(t,r,a,!1)}w.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec")}}]),MP4Remuxer}();function normalizePts(t,r){var a;if(null===r)return t;for(a=r<t?-8589934592:8589934592;Math.abs(t-r)>4294967296;)t+=a;return t}function flushTextTrackMetadataCueSamples(t,r,a,i){var o=t.samples.length;if(o){for(var l=t.inputTimeScale,u=0;u<o;u++){var c=t.samples[u];c.pts=normalizePts(c.pts-9e4*a.baseTime/a.timescale,r*l)/l,c.dts=normalizePts(c.dts-9e4*i.baseTime/i.timescale,r*l)/l}var d=t.samples;return t.samples=[],{"samples":d}}}function flushTextTrackUserdataCueSamples(t,r,a){var i=t.samples.length;if(i){for(var o=t.inputTimeScale,l=0;l<i;l++){var u=t.samples[l];u.pts=normalizePts(u.pts-9e4*a.baseTime/a.timescale,r*o)/o}t.samples.sort((function(t,r){return t.pts-r.pts}));var c=t.samples;return t.samples=[],{"samples":c}}}var Nt,Ut=(0,y.Z)((function Mp4Sample(t,r,a,i){(0,m.Z)(this,Mp4Sample),this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=r,this.size=a,this.cts=i,this.flags=new Bt(t)})),Bt=(0,y.Z)((function Mp4SampleFlags(t){(0,m.Z)(this,Mp4SampleFlags),this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=t?2:1,this.isNonSync=t?0:1})),Gt=function(){function PassThroughRemuxer(){(0,m.Z)(this,PassThroughRemuxer),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}return(0,y.Z)(PassThroughRemuxer,[{"key":"destroy","value":function destroy(){}},{"key":"resetTimeStamp","value":function resetTimeStamp(t){this.initPTS=t,this.lastEndTime=null}},{"key":"resetNextTimestamp","value":function resetNextTimestamp(){this.lastEndTime=null}},{"key":"resetInitSegment","value":function resetInitSegment(t,r,a,i){this.audioCodec=r,this.videoCodec=a,this.generateInitSegment(function patchEncyptionData(t,r){if(!t||!r)return t;var a=r.keyId;return a&&r.isCommonEncryption&&findBox(t,["moov","trak"]).forEach((function(t){var r=findBox(t,["mdia","minf","stbl","stsd"])[0].subarray(8),i=findBox(r,["enca"]),o=i.length>0;o||(i=findBox(r,["encv"])),i.forEach((function(t){findBox(o?t.subarray(28):t.subarray(78),["sinf"]).forEach((function(t){var r=parseSinf(t);if(r){var i=r.subarray(8,24);i.some((function(t){return 0!==t}))||(w.log("[eme] Patching keyId in 'enc".concat(o?"a":"v",">sinf>>tenc' box: ").concat(ue.hexDump(i)," -> ").concat(ue.hexDump(a))),r.set(a,8))}}))}))})),t}(t,i)),this.emitInitSegment=!0}},{"key":"generateInitSegment","value":function generateInitSegment(t){var r=this.audioCodec,a=this.videoCodec;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var i=this.initData=parseInitSegment(t);r||(r=getParsedTrackCodec(i.audio,B.AUDIO)),a||(a=getParsedTrackCodec(i.video,B.VIDEO));var o={};i.audio&&i.video?o.audiovideo={"container":"video/mp4","codec":r+","+a,"initSegment":t,"id":"main"}:i.audio?o.audio={"container":"audio/mp4","codec":r,"initSegment":t,"id":"audio"}:i.video?o.video={"container":"video/mp4","codec":a,"initSegment":t,"id":"main"}:w.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=o}},{"key":"remux","value":function remux(t,r,a,i,o,l){var u,c,d=this.initPTS,h=this.lastEndTime,g={"audio":void 0,"video":void 0,"text":i,"id3":a,"initSegment":void 0};R(h)||(h=this.lastEndTime=o||0);var v=r.samples;if(null==v||!v.length)return g;var m={"initPTS":void 0,"timescale":1},y=this.initData;if(null!=(u=y)&&u.length||(this.generateInitSegment(v),y=this.initData),null==(c=y)||!c.length)return w.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),g;this.emitInitSegment&&(m.tracks=this.initTracks,this.emitInitSegment=!1);var p=function getStartDTS(t,r){return findBox(r,["moof","traf"]).reduce((function(r,a){var i=findBox(a,["tfdt"])[0],o=i[0],l=findBox(a,["tfhd"]).reduce((function(r,a){var l=readUint32(a,4),u=t[l];if(u){var c=readUint32(i,4);if(1===o){if(c===ce)return w.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),r;c*=ce+1,c+=readUint32(i,8)}var d=c/(u.timescale||9e4);if(isFinite(d)&&(null===r||d<r))return d}return r}),null);return null!==l&&isFinite(l)&&(null===r||l<r)?l:r}),null)}(y,v),T=null===p?o:p;(function isInvalidInitPts(t,r,a){if(null===t)return!0;var i=r-t.baseTime/t.timescale;return i<0&&Math.abs(i-a)>1}(d,T,o)||m.timescale!==d.timescale&&l)&&(m.initPTS=T-o,this.initPTS=d={"baseTime":m.initPTS,"timescale":1});var E=function getDuration(t,r){for(var a=0,i=0,o=0,l=findBox(t,["moof","traf"]),u=0;u<l.length;u++){var c=l[u],d=findBox(c,["tfhd"])[0],h=r[readUint32(d,4)];if(h){var g=h.default,v=readUint32(d,0)|(null==g?void 0:g.flags),m=null==g?void 0:g.duration;8&v&&(m=readUint32(d,2&v?12:8));for(var y=h.timescale||9e4,p=findBox(c,["trun"]),T=0;T<p.length;T++)!(a=computeRawDurationFromSamples(p[T]))&&m&&(a=m*readUint32(p[T],4)),h.type===B.VIDEO?i+=a/y:h.type===B.AUDIO&&(o+=a/y)}}if(0===i&&0===o){for(var E=0,k=findBox(t,["sidx"]),S=0;S<k.length;S++){var L=parseSegmentIndex(k[S]);null!=L&&L.references&&(E+=L.references.reduce((function(t,r){return t+r.info.duration||0}),0))}return E}return i||o}(v,y),k=t?T-d.baseTime/d.timescale:h,S=k+E;!function offsetStartDTS(t,r,a){findBox(r,["moof","traf"]).forEach((function(r){findBox(r,["tfhd"]).forEach((function(i){var o=readUint32(i,4),l=t[o];if(l){var u=l.timescale||9e4;findBox(r,["tfdt"]).forEach((function(t){var r=t[0],i=readUint32(t,4);if(0===r)i-=a*u,writeUint32(t,4,i=Math.max(i,0));else{i*=Math.pow(2,32),i+=readUint32(t,8),i-=a*u,i=Math.max(i,0);var o=Math.floor(i/(ce+1)),l=Math.floor(i%(ce+1));writeUint32(t,4,o),writeUint32(t,8,l)}}))}}))}))}(y,v,d.baseTime/d.timescale),E>0?this.lastEndTime=S:(w.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var L=!!y.audio,A=!!y.video,I="";L&&(I+="audio"),A&&(I+="video");var D={"data1":v,"startPTS":k,"startDTS":k,"endPTS":S,"endDTS":S,"type":I,"hasAudio":L,"hasVideo":A,"nb":1,"dropped":0};return g.audio="audio"===D.type?D:void 0,g.video="audio"!==D.type?D:void 0,g.initSegment=m,g.id3=flushTextTrackMetadataCueSamples(a,o,d,d),i.samples.length&&(g.text=flushTextTrackUserdataCueSamples(i,o,d)),g}}]),PassThroughRemuxer}();function getParsedTrackCodec(t,r){var a=null==t?void 0:t.codec;return a&&a.length>4?a:"hvc1"===a||"hev1"===a?"hvc1.1.6.L120.90":"av01"===a?"av01.0.04M.08":"avc1"===a||r===B.VIDEO?"avc1.42e01e":"mp4a.40.5"}try{Nt=self.performance.now.bind(self.performance)}catch(t){w.debug("Unable to use Performance API on this environment"),Nt="undefined"!=typeof self&&self.Date.now}var Kt=[{"demux":Tt,"remux":Gt},{"demux":bt,"remux":Ot},{"demux":yt,"remux":Ot},{"demux":Ct,"remux":Ot}],Ht=function(){function Transmuxer(t,r,a,i,o){(0,m.Z)(this,Transmuxer),this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=r,this.config=a,this.vendor=i,this.id=o}return(0,y.Z)(Transmuxer,[{"key":"configure","value":function configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}},{"key":"push","value":function push(t,r,a,i){var o=this,l=a.transmuxing;l.executeStart=Nt();var u=new Uint8Array(t),c=this.currentTransmuxState,d=this.transmuxConfig;i&&(this.currentTransmuxState=i);var h=i||c,g=h.contiguous,v=h.discontinuity,m=h.trackSwitch,y=h.accurateTimeOffset,p=h.timeOffset,T=h.initSegmentChange,E=d.audioCodec,k=d.videoCodec,S=d.defaultInitPts,L=d.duration,A=d.initSegmentData,R=function getEncryptionType(t,r){var a=null;t.byteLength>0&&null!=r&&null!=r.key&&null!==r.iv&&null!=r.method&&(a=r);return a}(u,r);if(R&&"AES-128"===R.method){var C=this.getDecrypter();if(!C.isSync())return this.decryptionPromise=C.webCryptoDecrypt(u,R.key.buffer,R.iv.buffer).then((function(t){var r=o.push(t,null,a);return o.decryptionPromise=null,r})),this.decryptionPromise;var P=C.softwareDecrypt(u,R.key.buffer,R.iv.buffer);if(a.part>-1&&(P=C.flush()),!P)return l.executeEnd=Nt(),Vt(a);u=new Uint8Array(P)}var _=this.needsProbing(v,m);if(_){var M=this.configureTransmuxer(u);if(M)return w.warn("[transmuxer] ".concat(M.message)),this.observer.emit(I.ERROR,I.ERROR,{"type":D.MEDIA_ERROR,"details":b.FRAG_PARSING_ERROR,"fatal":!1,"error":M,"reason":M.message}),l.executeEnd=Nt(),Vt(a)}(v||m||T||_)&&this.resetInitSegment(A,E,k,L,r),(v||T||_)&&this.resetInitialTimestamp(S),g||this.resetContiguity();var x=this.transmux(u,R,p,y,a),O=this.currentTransmuxState;return O.contiguous=!0,O.discontinuity=!1,O.trackSwitch=!1,l.executeEnd=Nt(),x}},{"key":"flush","value":function flush(t){var r=this,a=t.transmuxing;a.executeStart=Nt();var i=this.decrypter,o=this.currentTransmuxState,l=this.decryptionPromise;if(l)return l.then((function(){return r.flush(t)}));var u=[],c=o.timeOffset;if(i){var d=i.flush();d&&u.push(this.push(d,null,t))}var h=this.demuxer,g=this.remuxer;if(!h||!g)return a.executeEnd=Nt(),[Vt(t)];var v=h.flush(c);return isPromise(v)?v.then((function(a){return r.flushRemux(u,a,t),u})):(this.flushRemux(u,v,t),u)}},{"key":"flushRemux","value":function flushRemux(t,r,a){var i=r.audioTrack,o=r.videoTrack,l=r.id3Track,u=r.textTrack,c=this.currentTransmuxState,d=c.accurateTimeOffset,h=c.timeOffset;w.log("[transmuxer.ts]: Flushed fragment ".concat(a.sn).concat(a.part>-1?" p: "+a.part:""," of level ").concat(a.level));var g=this.remuxer.remux(i,o,l,u,h,d,!0,this.id);t.push({"remuxResult":g,"chunkMeta":a}),a.transmuxing.executeEnd=Nt()}},{"key":"resetInitialTimestamp","value":function resetInitialTimestamp(t){var r=this.demuxer,a=this.remuxer;r&&a&&(r.resetTimeStamp(t),a.resetTimeStamp(t))}},{"key":"resetContiguity","value":function resetContiguity(){var t=this.demuxer,r=this.remuxer;t&&r&&(t.resetContiguity(),r.resetNextTimestamp())}},{"key":"resetInitSegment","value":function resetInitSegment(t,r,a,i,o){var l=this.demuxer,u=this.remuxer;l&&u&&(l.resetInitSegment(t,r,a,i),u.resetInitSegment(t,r,a,o))}},{"key":"destroy","value":function destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}},{"key":"transmux","value":function transmux(t,r,a,i,o){return r&&"SAMPLE-AES"===r.method?this.transmuxSampleAes(t,r,a,i,o):this.transmuxUnencrypted(t,a,i,o)}},{"key":"transmuxUnencrypted","value":function transmuxUnencrypted(t,r,a,i){var o=this.demuxer.demux(t,r,!1,!this.config.progressive),l=o.audioTrack,u=o.videoTrack,c=o.id3Track,d=o.textTrack;return{"remuxResult":this.remuxer.remux(l,u,c,d,r,a,!1,this.id),"chunkMeta":i}}},{"key":"transmuxSampleAes","value":function transmuxSampleAes(t,r,a,i,o){var l=this;return this.demuxer.demuxSampleAes(t,r,a).then((function(t){return{"remuxResult":l.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,a,i,!1,l.id),"chunkMeta":o}}))}},{"key":"configureTransmuxer","value":function configureTransmuxer(t){for(var r,a=this.config,i=this.observer,o=this.typeSupported,l=this.vendor,u=0,c=Kt.length;u<c;u++)if(Kt[u].demux.probe(t)){r=Kt[u];break}if(!r)return new Error("Failed to find demuxer by probing fragment data");var d=this.demuxer,h=this.remuxer,g=r.remux,v=r.demux;h&&h instanceof g||(this.remuxer=new g(i,a,o,l)),d&&d instanceof v||(this.demuxer=new v(i,a,o),this.probe=v.probe)}},{"key":"needsProbing","value":function needsProbing(t,r){return!this.demuxer||!this.remuxer||t||r}},{"key":"getDecrypter","value":function getDecrypter(){var t=this.decrypter;return t||(t=this.decrypter=new dt(this.config)),t}}]),Transmuxer}();var Vt=function emptyResult(t){return{"remuxResult":{},"chunkMeta":t}};function isPromise(t){return"then"in t&&t.then instanceof Function}var Wt=(0,y.Z)((function TransmuxConfig(t,r,a,i,o){(0,m.Z)(this,TransmuxConfig),this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=r,this.initSegmentData=a,this.duration=i,this.defaultInitPts=o||null})),Zt=(0,y.Z)((function TransmuxState(t,r,a,i,o,l){(0,m.Z)(this,TransmuxState),this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=r,this.accurateTimeOffset=a,this.trackSwitch=i,this.timeOffset=o,this.initSegmentChange=l})),Yt={"exports":{}};!function(t){var r=Object.prototype.hasOwnProperty,a="~";function Events(){}function EE(t,r,a){this.fn=t,this.context=r,this.once=a||!1}function addListener(t,r,i,o,l){if("function"!=typeof i)throw new TypeError("The listener must be a function");var u=new EE(i,o||t,l),c=a?a+r:r;return t._events[c]?t._events[c].fn?t._events[c]=[t._events[c],u]:t._events[c].push(u):(t._events[c]=u,t._eventsCount++),t}function clearEvent(t,r){0==--t._eventsCount?t._events=new Events:delete t._events[r]}function EventEmitter(){this._events=new Events,this._eventsCount=0}Object.create&&(Events.prototype=Object.create(null),(new Events).__proto__||(a=!1)),EventEmitter.prototype.eventNames=function eventNames(){var t,i,o=[];if(0===this._eventsCount)return o;for(i in t=this._events)r.call(t,i)&&o.push(a?i.slice(1):i);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(t)):o},EventEmitter.prototype.listeners=function listeners(t){var r=a?a+t:t,i=this._events[r];if(!i)return[];if(i.fn)return[i.fn];for(var o=0,l=i.length,u=new Array(l);o<l;o++)u[o]=i[o].fn;return u},EventEmitter.prototype.listenerCount=function listenerCount(t){var r=a?a+t:t,i=this._events[r];return i?i.fn?1:i.length:0},EventEmitter.prototype.emit=function emit(t,r,i,o,l,u){var c=a?a+t:t;if(!this._events[c])return!1;var d,h,g=this._events[c],v=arguments.length;if(g.fn){switch(g.once&&this.removeListener(t,g.fn,void 0,!0),v){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,r),!0;case 3:return g.fn.call(g.context,r,i),!0;case 4:return g.fn.call(g.context,r,i,o),!0;case 5:return g.fn.call(g.context,r,i,o,l),!0;case 6:return g.fn.call(g.context,r,i,o,l,u),!0}for(h=1,d=new Array(v-1);h<v;h++)d[h-1]=arguments[h];g.fn.apply(g.context,d)}else{var m,y=g.length;for(h=0;h<y;h++)switch(g[h].once&&this.removeListener(t,g[h].fn,void 0,!0),v){case 1:g[h].fn.call(g[h].context);break;case 2:g[h].fn.call(g[h].context,r);break;case 3:g[h].fn.call(g[h].context,r,i);break;case 4:g[h].fn.call(g[h].context,r,i,o);break;default:if(!d)for(m=1,d=new Array(v-1);m<v;m++)d[m-1]=arguments[m];g[h].fn.apply(g[h].context,d)}}return!0},EventEmitter.prototype.on=function on(t,r,a){return addListener(this,t,r,a,!1)},EventEmitter.prototype.once=function once(t,r,a){return addListener(this,t,r,a,!0)},EventEmitter.prototype.removeListener=function removeListener(t,r,i,o){var l=a?a+t:t;if(!this._events[l])return this;if(!r)return clearEvent(this,l),this;var u=this._events[l];if(u.fn)u.fn!==r||o&&!u.once||i&&u.context!==i||clearEvent(this,l);else{for(var c=0,d=[],h=u.length;c<h;c++)(u[c].fn!==r||o&&!u[c].once||i&&u[c].context!==i)&&d.push(u[c]);d.length?this._events[l]=1===d.length?d[0]:d:clearEvent(this,l)}return this},EventEmitter.prototype.removeAllListeners=function removeAllListeners(t){var r;return t?(r=a?a+t:t,this._events[r]&&clearEvent(this,r)):(this._events=new Events,this._eventsCount=0),this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.addListener=EventEmitter.prototype.on,EventEmitter.prefixed=a,EventEmitter.EventEmitter=EventEmitter,t.exports=EventEmitter}(Yt);var jt=getDefaultExportFromCjs(Yt.exports),qt=getMediaSource()||{"isTypeSupported":function isTypeSupported(){return!1}},zt=function(){function TransmuxerInterface(t,r,a,i){var o=this;(0,m.Z)(this,TransmuxerInterface),this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;var l=t.config;this.hls=t,this.id=r,this.useWorker=!!l.enableWorker,this.onTransmuxComplete=a,this.onFlush=i;var u=function forwardMessage(t,r){(r=r||{}).frag=o.frag,r.id=o.id,t===I.ERROR&&(o.error=r.error),o.hls.trigger(t,r)};this.observer=new jt,this.observer.on(I.FRAG_DECRYPTED,u),this.observer.on(I.ERROR,u);var c={"mp4":qt.isTypeSupported("video/mp4"),"mpeg":qt.isTypeSupported("audio/mpeg"),"mp3":qt.isTypeSupported('audio/mp4; codecs="mp3"')},d=navigator.vendor;if(this.useWorker&&"undefined"!=typeof Worker&&(l.workerPath||function hasUMDWorker(){return"function"==typeof __HLS_WORKER_BUNDLE__}())){try{l.workerPath?(w.log("loading Web Worker ".concat(l.workerPath,' for "').concat(r,'"')),this.workerContext=function loadWorker(t){var r=new self.URL(t,self.location.href).href;return{"worker":new self.Worker(r),"scriptURL":r}}(l.workerPath)):(w.log('injecting Web Worker for "'.concat(r,'"')),this.workerContext=function injectWorker(){var t=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(".concat(__HLS_WORKER_BUNDLE__.toString(),")(true);")],{"type":"text/javascript"}),r=self.URL.createObjectURL(t);return{"worker":new self.Worker(r),"objectURL":r}}()),this.onwmsg=function(t){return o.onWorkerMessage(t)};var h=this.workerContext.worker;h.addEventListener("message",this.onwmsg),h.onerror=function(t){var a=new Error("".concat(t.message," (").concat(t.filename,":").concat(t.lineno,")"));l.enableWorker=!1,w.warn('Error in "'.concat(r,'" Web Worker, fallback to inline')),o.hls.trigger(I.ERROR,{"type":D.OTHER_ERROR,"details":b.INTERNAL_EXCEPTION,"fatal":!1,"event":"demuxerWorker","error":a})},h.postMessage({"cmd":"init","typeSupported":c,"vendor":d,"id":r,"config":JSON.stringify(l)})}catch(t){w.warn('Error setting up "'.concat(r,'" Web Worker, fallback to inline'),t),this.resetWorker(),this.error=null,this.transmuxer=new Ht(this.observer,c,l,d,r)}return}this.transmuxer=new Ht(this.observer,c,l,d,r)}return(0,y.Z)(TransmuxerInterface,[{"key":"resetWorker","value":function resetWorker(){if(this.workerContext){var t=this.workerContext,r=t.worker,a=t.objectURL;a&&self.URL.revokeObjectURL(a),r.removeEventListener("message",this.onwmsg),r.onerror=null,r.terminate(),this.workerContext=null}}},{"key":"destroy","value":function destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{var t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}var r=this.observer;r&&r.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}},{"key":"push","value":function push(t,r,a,i,o,l,u,c,d,h){var g,v,m=this;d.transmuxing.start=self.performance.now();var y=this.transmuxer,p=l?l.start:o.start,T=o.decryptdata,E=this.frag,k=!(E&&o.cc===E.cc),S=!(E&&d.level===E.level),L=E?d.sn-E.sn:-1,A=this.part?d.part-this.part.index:-1,R=0===L&&d.id>1&&d.id===(null==E?void 0:E.stats.chunkCount),I=!S&&(1===L||0===L&&(1===A||R&&A<=0)),D=self.performance.now();(S||L||0===o.stats.parsing.start)&&(o.stats.parsing.start=D),!l||!A&&I||(l.stats.parsing.start=D);var b=!(E&&(null==(g=o.initSegment)?void 0:g.url)===(null==(v=E.initSegment)?void 0:v.url)),C=new Zt(k,I,c,S,p,b);if(!I||k||b){w.log("[transmuxer-interface, ".concat(o.type,"]: Starting new transmux session for sn: ").concat(d.sn," p: ").concat(d.part," level: ").concat(d.level," id: ").concat(d.id,"\n discontinuity: ").concat(k,"\n trackSwitch: ").concat(S,"\n contiguous: ").concat(I,"\n accurateTimeOffset: ").concat(c,"\n timeOffset: ").concat(p,"\n initSegmentChange: ").concat(b));var P=new Wt(a,i,r,u,h);this.configureTransmuxer(P)}if(this.frag=o,this.part=l,this.workerContext)this.workerContext.worker.postMessage({"cmd":"demux","data":t,"decryptdata":T,"chunkMeta":d,"state":C},t instanceof ArrayBuffer?[t]:[]);else if(y){var _=y.push(t,T,d,C);isPromise(_)?(y.async=!0,_.then((function(t){m.handleTransmuxComplete(t)})).catch((function(t){m.transmuxerError(t,d,"transmuxer-interface push error")}))):(y.async=!1,this.handleTransmuxComplete(_))}}},{"key":"flush","value":function flush(t){var r=this;t.transmuxing.start=self.performance.now();var a=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({"cmd":"flush","chunkMeta":t});else if(a){var i=a.flush(t);isPromise(i)||a.async?(isPromise(i)||(i=Promise.resolve(i)),i.then((function(a){r.handleFlushResult(a,t)})).catch((function(a){r.transmuxerError(a,t,"transmuxer-interface flush error")}))):this.handleFlushResult(i,t)}}},{"key":"transmuxerError","value":function transmuxerError(t,r,a){this.hls&&(this.error=t,this.hls.trigger(I.ERROR,{"type":D.MEDIA_ERROR,"details":b.FRAG_PARSING_ERROR,"chunkMeta":r,"fatal":!1,"error":t,"err":t,"reason":a}))}},{"key":"handleFlushResult","value":function handleFlushResult(t,r){var a=this;t.forEach((function(t){a.handleTransmuxComplete(t)})),this.onFlush(r)}},{"key":"onWorkerMessage","value":function onWorkerMessage(t){var r=t.data,a=this.hls;switch(r.event){case"init":var i,o=null==(i=this.workerContext)?void 0:i.objectURL;o&&self.URL.revokeObjectURL(o);break;case"transmuxComplete":this.handleTransmuxComplete(r.data);break;case"flush":this.onFlush(r.data);break;case"workerLog":w[r.data.logType]&&w[r.data.logType](r.data.message);break;default:r.data=r.data||{},r.data.frag=this.frag,r.data.id=this.id,a.trigger(r.event,r.data)}}},{"key":"configureTransmuxer","value":function configureTransmuxer(t){var r=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({"cmd":"configure","config":t}):r&&r.configure(t)}},{"key":"handleTransmuxComplete","value":function handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}]),TransmuxerInterface}(),Xt=function(){function GapController(t,r,a,i){(0,m.Z)(this,GapController),this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=t,this.media=r,this.fragmentTracker=a,this.hls=i}return(0,y.Z)(GapController,[{"key":"destroy","value":function destroy(){this.media=null,this.hls=this.fragmentTracker=null}},{"key":"poll","value":function poll(t,r){var a=this.config,i=this.media,o=this.stalled;if(null!==i){var l=i.currentTime,u=i.seeking,c=this.seeking&&!u,d=!this.seeking&&u;if(this.seeking=u,l===t){if(d||c)this.stalled=null;else if(!(i.paused&&!u||i.ended||0===i.playbackRate)&&st.getBuffered(i).length){var h=st.bufferInfo(i,l,0),g=h.len>0,v=h.nextStart||0;if(g||v){if(u){var m=h.len>2,y=!v||r&&r.start<=l||v-l>2&&!this.fragmentTracker.getPartialFragment(l);if(m||y)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var p,T=Math.max(v,h.start||0)-l,E=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,k=(null==E||null==(p=E.details)?void 0:p.live)?2*E.details.targetduration:2,S=this.fragmentTracker.getPartialFragment(l);if(T>0&&(T<=k||S))return void this._trySkipBufferHole(S)}var L=self.performance.now();if(null!==o){var A=L-o;if(u||!(A>=250)||(this._reportStall(h),this.media)){var R=st.bufferInfo(i,l,a.maxBufferHole);this._tryFixBufferStall(R,A)}}else this.stalled=L}}}else if(this.moved=!0,null!==o){if(this.stallReported){var I=self.performance.now()-o;w.warn("playback not stuck anymore @".concat(l,", after ").concat(Math.round(I),"ms")),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}}}},{"key":"_tryFixBufferStall","value":function _tryFixBufferStall(t,r){var a=this.config,i=this.fragmentTracker,o=this.media;if(null!==o){var l=o.currentTime,u=i.getPartialFragment(l);if(u)if(this._trySkipBufferHole(u)||!this.media)return;(t.len>a.maxBufferHole||t.nextStart&&t.nextStart-l<a.maxBufferHole)&&r>1e3*a.highBufferWatchdogPeriod&&(w.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}}},{"key":"_reportStall","value":function _reportStall(t){var r=this.hls,a=this.media;if(!this.stallReported&&a){this.stallReported=!0;var i=new Error("Playback stalling at @".concat(a.currentTime," due to low buffer (").concat(JSON.stringify(t),")"));w.warn(i.message),r.trigger(I.ERROR,{"type":D.MEDIA_ERROR,"details":b.BUFFER_STALLED_ERROR,"fatal":!1,"error":i,"buffer":t.len})}}},{"key":"_trySkipBufferHole","value":function _trySkipBufferHole(t){var r=this.config,a=this.hls,i=this.media;if(null===i)return 0;var o=i.currentTime,l=st.bufferInfo(i,o,0),u=o<l.start?l.start:l.nextStart;if(u){var c=l.len<=r.maxBufferHole,d=l.len>0&&l.len<1&&i.readyState<3,h=u-o;if(h>0&&(c||d)){if(h>r.maxBufferHole){var g=this.fragmentTracker,v=!1;if(0===o){var m=g.getAppendedFrag(0,Re.MAIN);m&&u<m.end&&(v=!0)}if(!v){var y=t||g.getAppendedFrag(o,Re.MAIN);if(y){for(var p=!1,T=y.end;T<u;){var E=g.getPartialFragment(T);if(!E){p=!0;break}T+=E.duration}if(p)return 0}}}var k=Math.max(u+.05,o+.1);if(w.warn("skipping hole, adjusting currentTime from ".concat(o," to ").concat(k)),this.moved=!0,this.stalled=null,i.currentTime=k,t&&!t.gap){var S=new Error("fragment loaded with buffer holes, seeking from ".concat(o," to ").concat(k));a.trigger(I.ERROR,{"type":D.MEDIA_ERROR,"details":b.BUFFER_SEEK_OVER_HOLE,"fatal":!1,"error":S,"reason":S.message,"frag":t})}return k}}return 0}},{"key":"_tryNudgeBuffer","value":function _tryNudgeBuffer(){var t=this.config,r=this.hls,a=this.media,i=this.nudgeRetry;if(null!==a){var o=a.currentTime;if(this.nudgeRetry++,i<t.nudgeMaxRetry){var l=o+(i+1)*t.nudgeOffset,u=new Error("Nudging 'currentTime' from ".concat(o," to ").concat(l));w.warn(u.message),a.currentTime=l,r.trigger(I.ERROR,{"type":D.MEDIA_ERROR,"details":b.BUFFER_NUDGE_ON_STALL,"error":u,"fatal":!1})}else{var c=new Error("Playhead still not moving while enough data buffered @".concat(o," after ").concat(t.nudgeMaxRetry," nudges"));w.error(c.message),r.trigger(I.ERROR,{"type":D.MEDIA_ERROR,"details":b.BUFFER_STALLED_ERROR,"error":c,"fatal":!0})}}}}]),GapController}(),Qt=function(t){(0,g.Z)(StreamController,t);var r=(0,v.Z)(StreamController);function StreamController(t,a,i){var o;return(0,m.Z)(this,StreamController),(o=r.call(this,t,a,i,"[stream-controller]",Re.MAIN)).audioCodecSwap=!1,o.gapController=null,o.level=-1,o._forceStartLoad=!1,o.altAudio=!1,o.audioOnly=!1,o.fragPlaying=null,o.onvplaying=null,o.onvseeked=null,o.fragLastKbps=0,o.couldBacktrack=!1,o.backtrackFragment=null,o.audioCodecSwitch=!1,o.videoBuffer=null,o._registerListeners(),o}return(0,y.Z)(StreamController,[{"key":"_registerListeners","value":function _registerListeners(){var t=this.hls;t.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.MANIFEST_PARSED,this.onManifestParsed,this),t.on(I.LEVEL_LOADING,this.onLevelLoading,this),t.on(I.LEVEL_LOADED,this.onLevelLoaded,this),t.on(I.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(I.ERROR,this.onError,this),t.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(I.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(I.BUFFER_CREATED,this.onBufferCreated,this),t.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(I.FRAG_BUFFERED,this.onFragBuffered,this)}},{"key":"_unregisterListeners","value":function _unregisterListeners(){var t=this.hls;t.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.MANIFEST_PARSED,this.onManifestParsed,this),t.off(I.LEVEL_LOADED,this.onLevelLoaded,this),t.off(I.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(I.ERROR,this.onError,this),t.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(I.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(I.BUFFER_CREATED,this.onBufferCreated,this),t.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(I.FRAG_BUFFERED,this.onFragBuffered,this)}},{"key":"onHandlerDestroying","value":function onHandlerDestroying(){this._unregisterListeners(),this.onMediaDetaching()}},{"key":"startLoad","value":function startLoad(t){if(this.levels){var r=this.lastCurrentTime,a=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){var i=a.startLevel;-1===i&&(a.config.testBandwidth&&this.levels.length>1?(i=0,this.bitrateTest=!0):i=a.nextAutoLevel),this.level=a.nextLoadLevel=i,this.loadedmetadata=!1}r>0&&-1===t&&(this.log("Override startPosition with lastCurrentTime @".concat(r.toFixed(3))),t=r),this.state=ft.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=ft.STOPPED}},{"key":"stopLoad","value":function stopLoad(){this._forceStartLoad=!1,(0,d.Z)((0,h.Z)(StreamController.prototype),"stopLoad",this).call(this)}},{"key":"doTick","value":function doTick(){switch(this.state){case ft.WAITING_LEVEL:var t,r=this.levels,a=this.level,i=null==r||null==(t=r[a])?void 0:t.details;if(i&&(!i.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(i))break;this.state=ft.IDLE;break}break;case ft.FRAG_LOADING_WAITING_RETRY:var o,l=self.performance.now(),u=this.retryDate;(!u||l>=u||null!=(o=this.media)&&o.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=ft.IDLE)}this.state===ft.IDLE&&this.doTickIdle(),this.onTickEnd()}},{"key":"onTickEnd","value":function onTickEnd(){(0,d.Z)((0,h.Z)(StreamController.prototype),"onTickEnd",this).call(this),this.checkBuffer(),this.checkFragmentChanged()}},{"key":"doTickIdle","value":function doTickIdle(){var t=this.hls,r=this.levelLastLoaded,a=this.levels,i=this.media,o=t.config,l=t.nextLoadLevel;if(null!==r&&(i||!this.startFragRequested&&o.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)&&null!=a&&a[l]){var u=a[l],c=this.getMainFwdBufferInfo();if(null!==c){var d=this.getLevelDetails();if(d&&this._streamEnded(c,d)){var h={};return this.altAudio&&(h.type="video"),this.hls.trigger(I.BUFFER_EOS,h),void(this.state=ft.ENDED)}t.loadLevel!==l&&-1===t.manualLevel&&this.log("Adapting to level ".concat(l," from level ").concat(this.level)),this.level=t.nextLoadLevel=l;var g=u.details;if(!g||this.state===ft.WAITING_LEVEL||g.live&&this.levelLastLoaded!==l)return this.level=l,void(this.state=ft.WAITING_LEVEL);var v=c.len,m=this.getMaxBufferLength(u.maxBitrate);if(!(v>=m)){this.backtrackFragment&&this.backtrackFragment.start>c.end&&(this.backtrackFragment=null);var y=this.backtrackFragment?this.backtrackFragment.start:c.end,p=this.getNextFragment(y,g);if(this.couldBacktrack&&!this.fragPrevious&&p&&"initSegment"!==p.sn&&this.fragmentTracker.getState(p)!==$e){var T,E=(null!=(T=this.backtrackFragment)?T:p).sn-g.startSN,k=g.fragments[E-1];k&&p.cc===k.cc&&(p=k,this.fragmentTracker.removeFragment(k))}else this.backtrackFragment&&c.len&&(this.backtrackFragment=null);if(p&&this.isLoopLoading(p,y)){if(!p.gap){var S=this.audioOnly&&!this.altAudio?B.AUDIO:B.VIDEO,L=(S===B.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;L&&this.afterBufferFlushed(L,S,Re.MAIN)}p=this.getNextFragmentLoopLoading(p,g,c,Re.MAIN,m)}p&&(!p.initSegment||p.initSegment.data||this.bitrateTest||(p=p.initSegment),this.loadFragment(p,u,y))}}}}},{"key":"loadFragment","value":function loadFragment(t,r,a){var i=this.fragmentTracker.getState(t);this.fragCurrent=t,i===ze||i===Qe?"initSegment"===t.sn?this._loadInitSegment(t,r):this.bitrateTest?(this.log("Fragment ".concat(t.sn," of level ").concat(t.level," is being downloaded to test bitrate and will not be buffered")),this._loadBitrateTestFrag(t,r)):(this.startFragRequested=!0,(0,d.Z)((0,h.Z)(StreamController.prototype),"loadFragment",this).call(this,t,r,a)):this.clearTrackerIfNeeded(t)}},{"key":"getBufferedFrag","value":function getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,Re.MAIN)}},{"key":"followingBufferedFrag","value":function followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}},{"key":"immediateLevelSwitch","value":function immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}},{"key":"nextLevelSwitch","value":function nextLevelSwitch(){var t=this.levels,r=this.media;if(null!=r&&r.readyState){var a,i=this.getAppendedFrag(r.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);var o=this.getLevelDetails();if(null!=o&&o.live){var l=this.getMainFwdBufferInfo();if(!l||l.len<2*o.targetduration)return}if(!r.paused&&t){var u=t[this.hls.nextLoadLevel],c=this.fragLastKbps;a=c&&this.fragCurrent?this.fragCurrent.duration*u.maxBitrate/(1e3*c)+1:0}else a=0;var d=this.getBufferedFrag(r.currentTime+a);if(d){var h=this.followingBufferedFrag(d);if(h){this.abortCurrentFrag();var g=h.maxStartPTS?h.maxStartPTS:h.start,v=h.duration,m=Math.max(d.end,g+Math.min(Math.max(v-this.config.maxFragLookUpTolerance,.5*v),.75*v));this.flushMainBuffer(m,Number.POSITIVE_INFINITY)}}}}},{"key":"abortCurrentFrag","value":function abortCurrentFrag(){var t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case ft.KEY_LOADING:case ft.FRAG_LOADING:case ft.FRAG_LOADING_WAITING_RETRY:case ft.PARSING:case ft.PARSED:this.state=ft.IDLE}this.nextLoadPosition=this.getLoadPosition()}},{"key":"flushMainBuffer","value":function flushMainBuffer(t,r){(0,d.Z)((0,h.Z)(StreamController.prototype),"flushMainBuffer",this).call(this,t,r,this.altAudio?"video":null)}},{"key":"onMediaAttached","value":function onMediaAttached(t,r){(0,d.Z)((0,h.Z)(StreamController.prototype),"onMediaAttached",this).call(this,t,r);var a=r.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),a.addEventListener("playing",this.onvplaying),a.addEventListener("seeked",this.onvseeked),this.gapController=new Xt(this.config,a,this.fragmentTracker,this.hls)}},{"key":"onMediaDetaching","value":function onMediaDetaching(){var t=this.media;t&&this.onvplaying&&this.onvseeked&&(t.removeEventListener("playing",this.onvplaying),t.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),(0,d.Z)((0,h.Z)(StreamController.prototype),"onMediaDetaching",this).call(this)}},{"key":"onMediaPlaying","value":function onMediaPlaying(){this.tick()}},{"key":"onMediaSeeked","value":function onMediaSeeked(){var t=this.media,r=t?t.currentTime:null;R(r)&&this.log("Media seeked to ".concat(r.toFixed(3)));var a=this.getMainFwdBufferInfo();null!==a&&0!==a.len?this.tick():this.warn('Main forward buffer length on "seeked" event '.concat(a?a.len:"empty",")"))}},{"key":"onManifestLoading","value":function onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(I.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.levels=this.fragPlaying=this.backtrackFragment=null,this.altAudio=this.audioOnly=!1}},{"key":"onManifestParsed","value":function onManifestParsed(t,r){var a,i=!1,o=!1;r.levels.forEach((function(t){(a=t.audioCodec)&&(-1!==a.indexOf("mp4a.40.2")&&(i=!0),-1!==a.indexOf("mp4a.40.5")&&(o=!0))})),this.audioCodecSwitch=i&&o&&!function changeTypeSupported(){var t,r=getSourceBuffer();return"function"==typeof(null==r||null==(t=r.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=r.levels,this.startFragRequested=!1}},{"key":"onLevelLoading","value":function onLevelLoading(t,r){var a=this.levels;if(a&&this.state===ft.IDLE){var i=a[r.level];(!i.details||i.details.live&&this.levelLastLoaded!==r.level||this.waitForCdnTuneIn(i.details))&&(this.state=ft.WAITING_LEVEL)}}},{"key":"onLevelLoaded","value":function onLevelLoaded(t,r){var a,i=this.levels,o=r.level,l=r.details,u=l.totalduration;if(i){this.log("Level ".concat(o," loaded [").concat(l.startSN,",").concat(l.endSN,"]").concat(l.lastPartSn?"[part-".concat(l.lastPartSn,"-").concat(l.lastPartIndex,"]"):"",", cc [").concat(l.startCC,", ").concat(l.endCC,"] duration:").concat(u));var c=i[o],d=this.fragCurrent;!d||this.state!==ft.FRAG_LOADING&&this.state!==ft.FRAG_LOADING_WAITING_RETRY||d.level===r.level&&d.urlId===c.urlId||!d.loader||this.abortCurrentFrag();var h=0;if(l.live||null!=(a=c.details)&&a.live){if(l.fragments[0]||(l.deltaUpdateFailed=!0),l.deltaUpdateFailed)return;h=this.alignPlaylists(l,c.details)}if(c.details=l,this.levelLastLoaded=o,this.hls.trigger(I.LEVEL_UPDATED,{"details":l,"level":o}),this.state===ft.WAITING_LEVEL){if(this.waitForCdnTuneIn(l))return;this.state=ft.IDLE}this.startFragRequested?l.live&&this.synchronizeToLiveEdge(l):this.setStartPosition(l,h),this.tick()}else this.warn("Levels were reset while loading level ".concat(o))}},{"key":"_handleFragmentLoadProgress","value":function _handleFragmentLoadProgress(t){var r,a=t.frag,i=t.part,o=t.payload,l=this.levels;if(l){var u=l[a.level],c=u.details;if(!c)return this.warn("Dropping fragment ".concat(a.sn," of level ").concat(a.level," after level details were reset")),void this.fragmentTracker.removeFragment(a);var d=u.videoCodec,h=c.PTSKnown||!c.live,g=null==(r=a.initSegment)?void 0:r.data,v=this._getAudioCodec(u),m=this.transmuxer=this.transmuxer||new zt(this.hls,Re.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),y=i?i.index:-1,p=-1!==y,T=new ot(a.level,a.sn,a.stats.chunkCount,o.byteLength,y,p),E=this.initPTS[a.cc];m.push(o,g,v,d,a,i,c.totalduration,h,T,E)}else this.warn("Levels were reset while fragment load was in progress. Fragment ".concat(a.sn," of level ").concat(a.level," will not be buffered"))}},{"key":"onAudioTrackSwitching","value":function onAudioTrackSwitching(t,r){var a=this.altAudio;if(!!!r.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var i=this.fragCurrent;i&&(this.log("Switching to main audio track, cancel main fragment load"),i.abortRequests(),this.fragmentTracker.removeFragment(i)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();var o=this.hls;a&&(o.trigger(I.BUFFER_FLUSHING,{"startOffset":0,"endOffset":Number.POSITIVE_INFINITY,"type":null}),this.fragmentTracker.removeAllFragments()),o.trigger(I.AUDIO_TRACK_SWITCHED,r)}}},{"key":"onAudioTrackSwitched","value":function onAudioTrackSwitched(t,r){var a=r.id,i=!!this.hls.audioTracks[a].url;if(i){var o=this.videoBuffer;o&&this.mediaBuffer!==o&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=o)}this.altAudio=i,this.tick()}},{"key":"onBufferCreated","value":function onBufferCreated(t,r){var a,i,o=r.tracks,l=!1;for(var u in o){var c=o[u];if("main"===c.id){if(i=u,a=c,"video"===u){var d=o[u];d&&(this.videoBuffer=d.buffer)}}else l=!0}l&&a?(this.log("Alternate track found, use ".concat(i,".buffered to schedule main fragment loading")),this.mediaBuffer=a.buffer):this.mediaBuffer=this.media}},{"key":"onFragBuffered","value":function onFragBuffered(t,r){var a=r.frag,i=r.part;if(!a||a.type===Re.MAIN){if(this.fragContextChanged(a))return this.warn("Fragment ".concat(a.sn).concat(i?" p: "+i.index:""," of level ").concat(a.level," finished buffering, but was aborted. state: ").concat(this.state)),void(this.state===ft.PARSED&&(this.state=ft.IDLE));var o=i?i.stats:a.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),"initSegment"!==a.sn&&(this.fragPrevious=a),this.fragBufferedComplete(a,i)}}},{"key":"onError","value":function onError(t,r){var a;if(r.fatal)this.state=ft.ERROR;else switch(r.details){case b.FRAG_GAP:case b.FRAG_PARSING_ERROR:case b.FRAG_DECRYPT_ERROR:case b.FRAG_LOAD_ERROR:case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_ERROR:case b.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Re.MAIN,r);break;case b.LEVEL_LOAD_ERROR:case b.LEVEL_LOAD_TIMEOUT:case b.LEVEL_PARSING_ERROR:r.levelRetry||this.state!==ft.WAITING_LEVEL||(null==(a=r.context)?void 0:a.type)!==Ae.LEVEL||(this.state=ft.IDLE);break;case b.BUFFER_FULL_ERROR:if(!r.parent||"main"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case b.INTERNAL_EXCEPTION:this.recoverWorkerError(r)}}},{"key":"checkBuffer","value":function checkBuffer(){var t=this.media,r=this.gapController;if(t&&r&&t.readyState){if(this.loadedmetadata||!st.getBuffered(t).length){var a=this.state!==ft.IDLE?this.fragCurrent:null;r.poll(this.lastCurrentTime,a)}this.lastCurrentTime=t.currentTime}}},{"key":"onFragLoadEmergencyAborted","value":function onFragLoadEmergencyAborted(){this.state=ft.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}},{"key":"onBufferFlushed","value":function onBufferFlushed(t,r){var a=r.type;if(a!==B.AUDIO||this.audioOnly&&!this.altAudio){var i=(a===B.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,a,Re.MAIN)}}},{"key":"onLevelsUpdated","value":function onLevelsUpdated(t,r){this.levels=r.levels}},{"key":"swapAudioCodec","value":function swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}},{"key":"seekToStartPos","value":function seekToStartPos(){var t=this.media;if(t){var r=t.currentTime,a=this.startPosition;if(a>=0&&r<a){if(t.seeking)return void this.log("could not seek to ".concat(a,", already seeking at ").concat(r));var i=st.getBuffered(t),o=(i.length?i.start(0):0)-a;o>0&&(o<this.config.maxBufferHole||o<this.config.maxFragLookUpTolerance)&&(this.log("adjusting start position by ".concat(o," to match buffer start")),a+=o,this.startPosition=a),this.log("seek to target start position ".concat(a," from current time ").concat(r)),t.currentTime=a}}}},{"key":"_getAudioCodec","value":function _getAudioCodec(t){var r=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&r&&(this.log("Swapping audio codec"),r=-1!==r.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),r}},{"key":"_loadBitrateTestFrag","value":function _loadBitrateTestFrag(t,r){var a=this;t.bitrateTest=!0,this._doFragLoad(t,r).then((function(i){var o=a.hls;if(i&&!a.fragContextChanged(t)){r.fragmentError=0,a.state=ft.IDLE,a.startFragRequested=!1,a.bitrateTest=!1;var l=t.stats;l.parsing.start=l.parsing.end=l.buffering.start=l.buffering.end=self.performance.now(),o.trigger(I.FRAG_LOADED,i),t.bitrateTest=!1}}))}},{"key":"_handleTransmuxComplete","value":function _handleTransmuxComplete(t){var r,a="main",i=this.hls,o=t.remuxResult,l=t.chunkMeta,u=this.getCurrentContext(l);if(u){var c=u.frag,d=u.part,h=u.level,g=o.video,v=o.text,m=o.id3,y=o.initSegment,p=h.details,T=this.altAudio?void 0:o.audio;if(this.fragContextChanged(c))this.fragmentTracker.removeFragment(c);else{if(this.state=ft.PARSING,y){if(null!=y&&y.tracks){var E=c.initSegment||c;this._bufferInitSegment(h,y.tracks,E,l),i.trigger(I.FRAG_PARSING_INIT_SEGMENT,{"frag":E,"id":a,"tracks":y.tracks})}var k=y.initPTS,S=y.timescale;R(k)&&(this.initPTS[c.cc]={"baseTime":k,"timescale":S},i.trigger(I.INIT_PTS_FOUND,{"frag":c,"id":a,"initPTS":k,"timescale":S}))}if(g&&!1!==o.independent){if(p){var L=g.startPTS,A=g.endPTS,D=g.startDTS,b=g.endDTS;if(d)d.elementaryStreams[g.type]={"startPTS":L,"endPTS":A,"startDTS":D,"endDTS":b};else if(g.firstKeyFrame&&g.independent&&1===l.id&&(this.couldBacktrack=!0),g.dropped&&g.independent){var C=this.getMainFwdBufferInfo();if((C?C.end:this.getLoadPosition())+this.config.maxBufferHole<(g.firstKeyFramePTS?g.firstKeyFramePTS:L)-this.config.maxBufferHole)return void this.backtrack(c);c.setElementaryStreamInfo(g.type,c.start,A,c.start,b,!0)}c.setElementaryStreamInfo(g.type,L,A,D,b),this.backtrackFragment&&(this.backtrackFragment=c),this.bufferFragmentData(g,c,d,l)}}else if(!1===o.independent)return void this.backtrack(c);if(T){var P=T.startPTS,_=T.endPTS,w=T.startDTS,M=T.endDTS;d&&(d.elementaryStreams[B.AUDIO]={"startPTS":P,"endPTS":_,"startDTS":w,"endDTS":M}),c.setElementaryStreamInfo(B.AUDIO,P,_,w,M),this.bufferFragmentData(T,c,d,l)}if(p&&null!=m&&null!=(r=m.samples)&&r.length){var x={"id":a,"frag":c,"details":p,"samples":m.samples};i.trigger(I.FRAG_PARSING_METADATA,x)}if(p&&v){var O={"id":a,"frag":c,"details":p,"samples":v.samples};i.trigger(I.FRAG_PARSING_USERDATA,O)}}}else this.resetWhenMissingContext(l)}},{"key":"_bufferInitSegment","value":function _bufferInitSegment(t,r,a,i){var o=this;if(this.state===ft.PARSING){this.audioOnly=!!r.audio&&!r.video,this.altAudio&&!this.audioOnly&&delete r.audio;var l=r.audio,u=r.video,c=r.audiovideo;if(l){var d=t.audioCodec,h=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(d&&(d=-1!==d.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),1!==l.metadata.channelCount&&-1===h.indexOf("firefox")&&(d="mp4a.40.5")),-1!==h.indexOf("android")&&"audio/mpeg"!==l.container&&(d="mp4a.40.2",this.log("Android: force audio codec to ".concat(d))),t.audioCodec&&t.audioCodec!==d&&this.log('Swapping manifest audio codec "'.concat(t.audioCodec,'" for "').concat(d,'"')),l.levelCodec=d,l.id="main",this.log("Init audio buffer, container:".concat(l.container,", codecs[selected/level/parsed]=[").concat(d||"","/").concat(t.audioCodec||"","/").concat(l.codec,"]"))}u&&(u.levelCodec=t.videoCodec,u.id="main",this.log("Init video buffer, container:".concat(u.container,", codecs[level/parsed]=[").concat(t.videoCodec||"","/").concat(u.codec,"]"))),c&&this.log("Init audiovideo buffer, container:".concat(c.container,", codecs[level/parsed]=[").concat(t.attrs.CODECS||"","/").concat(c.codec,"]")),this.hls.trigger(I.BUFFER_CODECS,r),Object.keys(r).forEach((function(t){var l=r[t].initSegment;null!=l&&l.byteLength&&o.hls.trigger(I.BUFFER_APPENDING,{"type":t,"data":l,"frag":a,"part":null,"chunkMeta":i,"parent":a.type})})),this.tick()}}},{"key":"getMainFwdBufferInfo","value":function getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,Re.MAIN)}},{"key":"backtrack","value":function backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=ft.IDLE}},{"key":"checkFragmentChanged","value":function checkFragmentChanged(){var t=this.media,r=null;if(t&&t.readyState>1&&!1===t.seeking){var a=t.currentTime;if(st.isBuffered(t,a)?r=this.getAppendedFrag(a):st.isBuffered(t,a+.1)&&(r=this.getAppendedFrag(a+.1)),r){this.backtrackFragment=null;var i=this.fragPlaying,o=r.level;i&&r.sn===i.sn&&i.level===o&&r.urlId===i.urlId||(this.fragPlaying=r,this.hls.trigger(I.FRAG_CHANGED,{"frag":r}),i&&i.level===o||this.hls.trigger(I.LEVEL_SWITCHED,{"level":o}))}}}},{"key":"nextLevel","get":function get(){var t=this.nextBufferedFrag;return t?t.level:-1}},{"key":"currentFrag","get":function get(){var t=this.media;return t?this.fragPlaying||this.getAppendedFrag(t.currentTime):null}},{"key":"currentProgramDateTime","get":function get(){var t=this.media;if(t){var r=t.currentTime,a=this.currentFrag;if(a&&R(r)&&R(a.programDateTime)){var i=a.programDateTime+1e3*(r-a.start);return new Date(i)}}return null}},{"key":"currentLevel","get":function get(){var t=this.currentFrag;return t?t.level:-1}},{"key":"nextBufferedFrag","get":function get(){var t=this.currentFrag;return t?this.followingBufferedFrag(t):null}},{"key":"forceStartLoad","get":function get(){return this._forceStartLoad}}]),StreamController}(gt),$t=function(){function EWMA(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;(0,m.Z)(this,EWMA),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=r,this.totalWeight_=a}return(0,y.Z)(EWMA,[{"key":"sample","value":function sample(t,r){var a=Math.pow(this.alpha_,t);this.estimate_=r*(1-a)+a*this.estimate_,this.totalWeight_+=t}},{"key":"getTotalWeight","value":function getTotalWeight(){return this.totalWeight_}},{"key":"getEstimate","value":function getEstimate(){if(this.alpha_){var t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}]),EWMA}(),Jt=function(){function EwmaBandWidthEstimator(t,r,a){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:100;(0,m.Z)(this,EwmaBandWidthEstimator),this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=a,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new $t(t),this.fast_=new $t(r),this.defaultTTFB_=i,this.ttfb_=new $t(t)}return(0,y.Z)(EwmaBandWidthEstimator,[{"key":"update","value":function update(t,r){var a=this.slow_,i=this.fast_,o=this.ttfb_;a.halfLife!==t&&(this.slow_=new $t(t,a.getEstimate(),a.getTotalWeight())),i.halfLife!==r&&(this.fast_=new $t(r,i.getEstimate(),i.getTotalWeight())),o.halfLife!==t&&(this.ttfb_=new $t(t,o.getEstimate(),o.getTotalWeight()))}},{"key":"sample","value":function sample(t,r){var a=(t=Math.max(t,this.minDelayMs_))/1e3,i=8*r/a;this.fast_.sample(a,i),this.slow_.sample(a,i)}},{"key":"sampleTTFB","value":function sampleTTFB(t){var r=t/1e3,a=Math.sqrt(2)*Math.exp(-Math.pow(r,2)/2);this.ttfb_.sample(a,Math.max(t,5))}},{"key":"canEstimate","value":function canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}},{"key":"getEstimate","value":function getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}},{"key":"getEstimateTTFB","value":function getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}},{"key":"destroy","value":function destroy(){}}]),EwmaBandWidthEstimator}(),er=function(){function AbrController(t){(0,m.Z)(this,AbrController),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=0,this._nextAutoLevel=-1,this.timer=-1,this.onCheck=this._abandonRulesCheck.bind(this),this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this.hls=t;var r=t.config;this.bwEstimator=new Jt(r.abrEwmaSlowVoD,r.abrEwmaFastVoD,r.abrEwmaDefaultEstimate),this.registerListeners()}return(0,y.Z)(AbrController,[{"key":"registerListeners","value":function registerListeners(){var t=this.hls;t.on(I.FRAG_LOADING,this.onFragLoading,this),t.on(I.FRAG_LOADED,this.onFragLoaded,this),t.on(I.FRAG_BUFFERED,this.onFragBuffered,this),t.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(I.LEVEL_LOADED,this.onLevelLoaded,this)}},{"key":"unregisterListeners","value":function unregisterListeners(){var t=this.hls;t.off(I.FRAG_LOADING,this.onFragLoading,this),t.off(I.FRAG_LOADED,this.onFragLoaded,this),t.off(I.FRAG_BUFFERED,this.onFragBuffered,this),t.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(I.LEVEL_LOADED,this.onLevelLoaded,this)}},{"key":"destroy","value":function destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null}},{"key":"onFragLoading","value":function onFragLoading(t,r){var a,i=r.frag;this.ignoreFragment(i)||(this.fragCurrent=i,this.partCurrent=null!=(a=r.part)?a:null,this.clearTimer(),this.timer=self.setInterval(this.onCheck,100))}},{"key":"onLevelSwitching","value":function onLevelSwitching(t,r){this.clearTimer()}},{"key":"getTimeToLoadFrag","value":function getTimeToLoadFrag(t,r,a,i){return t+a/r+(i?this.lastLevelLoadSec:0)}},{"key":"onLevelLoaded","value":function onLevelLoaded(t,r){var a=this.hls.config,i=r.stats,o=i.total,l=i.bwEstimate;R(o)&&R(l)&&(this.lastLevelLoadSec=8*o/l),r.details.live?this.bwEstimator.update(a.abrEwmaSlowLive,a.abrEwmaFastLive):this.bwEstimator.update(a.abrEwmaSlowVoD,a.abrEwmaFastVoD)}},{"key":"_abandonRulesCheck","value":function _abandonRulesCheck(){var t=this.fragCurrent,r=this.partCurrent,a=this.hls,i=a.autoLevelEnabled,o=a.media;if(t&&o){var l=performance.now(),u=r?r.stats:t.stats,c=r?r.duration:t.duration,d=l-u.loading.start;if(u.aborted||u.loaded&&u.loaded===u.total||0===t.level)return this.clearTimer(),void(this._nextAutoLevel=-1);if(i&&!o.paused&&o.playbackRate&&o.readyState){var h=a.mainForwardBufferInfo;if(null!==h){var g=this.bwEstimator.getEstimateTTFB(),v=Math.abs(o.playbackRate);if(!(d<=Math.max(g,c/(2*v)*1e3))){var m=h.len/v;if(!(m>=2*c/v)){var y=u.loading.first?u.loading.first-u.loading.start:-1,p=u.loaded&&y>-1,T=this.bwEstimator.getEstimate(),E=a.levels,k=a.minAutoLevel,S=E[t.level],L=u.total||Math.max(u.loaded,Math.round(c*S.maxBitrate/8)),A=d-y;A<1&&p&&(A=Math.min(d,8*u.loaded/T));var D=p?1e3*u.loaded/A:0,b=D?(L-u.loaded)/D:8*L/T+g/1e3;if(!(b<=m)){var C,P=D?8*D:T,_=Number.POSITIVE_INFINITY;for(C=t.level-1;C>k;C--){var M=E[C].maxBitrate;if((_=this.getTimeToLoadFrag(g/1e3,P,c*M,!E[C].details))<m)break}_>=b||_>10*c||(a.nextLoadLevel=C,p?this.bwEstimator.sample(d-Math.min(g,y),u.loaded):this.bwEstimator.sampleTTFB(d),this.clearTimer(),w.warn("[abr] Fragment ".concat(t.sn).concat(r?" part "+r.index:""," of level ").concat(t.level," is loading too slowly;\n Time to underbuffer: ").concat(m.toFixed(3)," s\n Estimated load time for current fragment: ").concat(b.toFixed(3)," s\n Estimated load time for down switch fragment: ").concat(_.toFixed(3)," s\n TTFB estimate: ").concat(y,"\n Current BW estimate: ").concat(R(T)?(T/1024).toFixed(3):"Unknown"," Kb/s\n New BW estimate: ").concat((this.bwEstimator.getEstimate()/1024).toFixed(3)," Kb/s\n Aborting and switching to level ").concat(C)),t.loader&&(this.fragCurrent=this.partCurrent=null,t.abortRequests()),a.trigger(I.FRAG_LOAD_EMERGENCY_ABORTED,{"frag":t,"part":r,"stats":u}))}}}}}}}},{"key":"onFragLoaded","value":function onFragLoaded(t,r){var a=r.frag,i=r.part,o=i?i.stats:a.stats;if(a.type===Re.MAIN&&this.bwEstimator.sampleTTFB(o.loading.first-o.loading.start),!this.ignoreFragment(a)){if(this.clearTimer(),this.lastLoadedFragLevel=a.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){var l=i?i.duration:a.duration,u=this.hls.levels[a.level],c=(u.loaded?u.loaded.bytes:0)+o.loaded,d=(u.loaded?u.loaded.duration:0)+l;u.loaded={"bytes":c,"duration":d},u.realBitrate=Math.round(8*c/d)}if(a.bitrateTest){var h={"stats":o,"frag":a,"part":i,"id":a.type};this.onFragBuffered(I.FRAG_BUFFERED,h),a.bitrateTest=!1}}}},{"key":"onFragBuffered","value":function onFragBuffered(t,r){var a=r.frag,i=r.part,o=null!=i&&i.stats.loaded?i.stats:a.stats;if(!o.aborted&&!this.ignoreFragment(a)){var l=o.parsing.end-o.loading.start-Math.min(o.loading.first-o.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(l,o.loaded),o.bwEstimate=this.bwEstimator.getEstimate(),a.bitrateTest?this.bitrateTestDelay=l/1e3:this.bitrateTestDelay=0}}},{"key":"ignoreFragment","value":function ignoreFragment(t){return t.type!==Re.MAIN||"initSegment"===t.sn}},{"key":"clearTimer","value":function clearTimer(){self.clearInterval(this.timer)}},{"key":"nextAutoLevel","get":function get(){var t=this._nextAutoLevel,r=this.bwEstimator;if(-1!==t&&!r.canEstimate())return t;var a=this.getNextABRAutoLevel();if(-1!==t){var i=this.hls.levels;if(i.length>Math.max(t,a)&&i[t].loadError<=i[a].loadError)return t}return-1!==t&&(a=Math.min(t,a)),a},"set":function set(t){this._nextAutoLevel=t}},{"key":"getNextABRAutoLevel","value":function getNextABRAutoLevel(){var t=this.fragCurrent,r=this.partCurrent,a=this.hls,i=a.maxAutoLevel,o=a.config,l=a.minAutoLevel,u=a.media,c=r?r.duration:t?t.duration:0,d=u&&0!==u.playbackRate?Math.abs(u.playbackRate):1,h=this.bwEstimator?this.bwEstimator.getEstimate():o.abrEwmaDefaultEstimate,g=a.mainForwardBufferInfo,v=(g?g.len:0)/d,m=this.findBestLevel(h,l,i,v,o.abrBandWidthFactor,o.abrBandWidthUpFactor);if(m>=0)return m;w.trace("[abr] ".concat(v?"rebuffering expected":"buffer is empty",", finding optimal quality level"));var y=c?Math.min(c,o.maxStarvationDelay):o.maxStarvationDelay,p=o.abrBandWidthFactor,T=o.abrBandWidthUpFactor;if(!v){var E=this.bitrateTestDelay;if(E)y=(c?Math.min(c,o.maxLoadingDelay):o.maxLoadingDelay)-E,w.trace("[abr] bitrate test took ".concat(Math.round(1e3*E),"ms, set first fragment max fetchDuration to ").concat(Math.round(1e3*y)," ms")),p=T=1}return m=this.findBestLevel(h,l,i,v+y,p,T),Math.max(m,0)}},{"key":"findBestLevel","value":function findBestLevel(t,r,a,i,o,l){for(var u,c=this.fragCurrent,d=this.partCurrent,h=this.lastLoadedFragLevel,g=this.hls.levels,v=g[h],m=!(null==v||null==(u=v.details)||!u.live),y=null==v?void 0:v.codecSet,p=d?d.duration:c?c.duration:0,T=this.bwEstimator.getEstimateTTFB()/1e3,E=r,k=-1,S=a;S>=r;S--){var L=g[S];if(!L||y&&L.codecSet!==y)L&&(E=Math.min(S,E),k=Math.max(S,k));else{-1!==k&&w.trace("[abr] Skipped level(s) ".concat(E,"-").concat(k,' with CODECS:"').concat(g[k].attrs.CODECS,'"; not compatible with "').concat(v.attrs.CODECS,'"'));var A=L.details,I=(d?null==A?void 0:A.partTarget:null==A?void 0:A.averagetargetduration)||p,D=void 0;D=S<=h?o*t:l*t;var b=g[S].maxBitrate,C=this.getTimeToLoadFrag(T,D,b*I,void 0===A);if(w.trace("[abr] level:".concat(S," adjustedbw-bitrate:").concat(Math.round(D-b)," avgDuration:").concat(I.toFixed(1)," maxFetchDuration:").concat(i.toFixed(1)," fetchDuration:").concat(C.toFixed(1))),D>b&&(0===C||!R(C)||m&&!this.bitrateTestDelay||C<i))return S}}return-1}}]),AbrController}(),tr=function(){function ChunkCache(){(0,m.Z)(this,ChunkCache),this.chunks=[],this.dataLength=0}return(0,y.Z)(ChunkCache,[{"key":"push","value":function push(t){this.chunks.push(t),this.dataLength+=t.length}},{"key":"flush","value":function flush(){var t,r=this.chunks,a=this.dataLength;return r.length?(t=1===r.length?r[0]:function concatUint8Arrays(t,r){for(var a=new Uint8Array(r),i=0,o=0;o<t.length;o++){var l=t[o];a.set(l,i),i+=l.length}return a}(r,a),this.reset(),t):new Uint8Array(0)}},{"key":"reset","value":function reset(){this.chunks.length=0,this.dataLength=0}}]),ChunkCache}();var rr=function(t){(0,g.Z)(AudioStreamController,t);var r=(0,v.Z)(AudioStreamController);function AudioStreamController(t,a,i){var o;return(0,m.Z)(this,AudioStreamController),(o=r.call(this,t,a,i,"[audio-stream-controller]",Re.AUDIO)).videoBuffer=null,o.videoTrackCC=-1,o.waitingVideoCC=-1,o.bufferedTrack=null,o.switchingTrack=null,o.trackId=-1,o.waitingData=null,o.mainDetails=null,o.bufferFlushed=!1,o.cachedTrackLoadedData=null,o._registerListeners(),o}return(0,y.Z)(AudioStreamController,[{"key":"onHandlerDestroying","value":function onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}},{"key":"_registerListeners","value":function _registerListeners(){var t=this.hls;t.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.LEVEL_LOADED,this.onLevelLoaded,this),t.on(I.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(I.ERROR,this.onError,this),t.on(I.BUFFER_RESET,this.onBufferReset,this),t.on(I.BUFFER_CREATED,this.onBufferCreated,this),t.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(I.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(I.FRAG_BUFFERED,this.onFragBuffered,this)}},{"key":"_unregisterListeners","value":function _unregisterListeners(){var t=this.hls;t.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.LEVEL_LOADED,this.onLevelLoaded,this),t.off(I.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(I.ERROR,this.onError,this),t.off(I.BUFFER_RESET,this.onBufferReset,this),t.off(I.BUFFER_CREATED,this.onBufferCreated,this),t.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(I.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(I.FRAG_BUFFERED,this.onFragBuffered,this)}},{"key":"onInitPtsFound","value":function onInitPtsFound(t,r){var a=r.frag,i=r.id,o=r.initPTS,l=r.timescale;if("main"===i){var u=a.cc;this.initPTS[a.cc]={"baseTime":o,"timescale":l},this.log("InitPTS for cc: ".concat(u," found from main: ").concat(o)),this.videoTrackCC=u,this.state===ft.WAITING_INIT_PTS&&this.tick()}}},{"key":"startLoad","value":function startLoad(t){if(!this.levels)return this.startPosition=t,void(this.state=ft.STOPPED);var r=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),r>0&&-1===t?(this.log("Override startPosition with lastCurrentTime @".concat(r.toFixed(3))),t=r,this.state=ft.IDLE):(this.loadedmetadata=!1,this.state=ft.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}},{"key":"doTick","value":function doTick(){switch(this.state){case ft.IDLE:this.doTickIdle();break;case ft.WAITING_TRACK:var t,r=this.levels,a=this.trackId,i=null==r||null==(t=r[a])?void 0:t.details;if(i){if(this.waitForCdnTuneIn(i))break;this.state=ft.WAITING_INIT_PTS}break;case ft.FRAG_LOADING_WAITING_RETRY:var o,l=performance.now(),u=this.retryDate;(!u||l>=u||null!=(o=this.media)&&o.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.trackId),this.state=ft.IDLE);break;case ft.WAITING_INIT_PTS:var c=this.waitingData;if(c){var g=c.frag,v=c.part,m=c.cache,y=c.complete;if(void 0!==this.initPTS[g.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=ft.FRAG_LOADING;var p={"frag":g,"part":v,"payload":m.flush(),"networkDetails":null};this._handleFragmentLoadProgress(p),y&&(0,d.Z)((0,h.Z)(AudioStreamController.prototype),"_handleFragmentLoadComplete",this).call(this,p)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log("Waiting fragment cc (".concat(g.cc,") cancelled because video is at cc ").concat(this.videoTrackCC)),this.clearWaitingFragment();else{var T=this.getLoadPosition(),E=st.bufferInfo(this.mediaBuffer,T,this.config.maxBufferHole);fragmentWithinToleranceTest(E.end,this.config.maxFragLookUpTolerance,g)<0&&(this.log("Waiting fragment cc (".concat(g.cc,") @ ").concat(g.start," cancelled because another fragment at ").concat(E.end," is needed")),this.clearWaitingFragment())}}else this.state=ft.IDLE}this.onTickEnd()}},{"key":"clearWaitingFragment","value":function clearWaitingFragment(){var t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=ft.IDLE)}},{"key":"resetLoadingState","value":function resetLoadingState(){this.clearWaitingFragment(),(0,d.Z)((0,h.Z)(AudioStreamController.prototype),"resetLoadingState",this).call(this)}},{"key":"onTickEnd","value":function onTickEnd(){var t=this.media;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}},{"key":"doTickIdle","value":function doTickIdle(){var t=this.hls,r=this.levels,a=this.media,i=this.trackId,o=t.config;if(null!=r&&r[i]&&(a||!this.startFragRequested&&o.startFragPrefetch)){var l=r[i],u=l.details;if(!u||u.live&&this.levelLastLoaded!==i||this.waitForCdnTuneIn(u))this.state=ft.WAITING_TRACK;else{var c=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&c&&(this.bufferFlushed=!1,this.afterBufferFlushed(c,B.AUDIO,Re.AUDIO));var d=this.getFwdBufferInfo(c,Re.AUDIO);if(null!==d){var h=this.bufferedTrack,g=this.switchingTrack;if(!g&&this._streamEnded(d,u))return t.trigger(I.BUFFER_EOS,{"type":"audio"}),void(this.state=ft.ENDED);var v=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Re.MAIN),m=d.len,y=this.getMaxBufferLength(null==v?void 0:v.len);if(!(m>=y)||g){var p=u.fragments[0].start,T=d.end;if(g&&a){var E=this.getLoadPosition();h&&g.attrs!==h.attrs&&(T=E),u.PTSKnown&&E<p&&(d.end>p||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),a.currentTime=p+.05)}var k=this.getNextFragment(T,u),S=!1;if(k&&this.isLoopLoading(k,T)&&(S=!!k.gap,k=this.getNextFragmentLoopLoading(k,u,d,Re.MAIN,y)),k){var L=v&&k.start>v.end+u.targetduration;if(L||(null==v||!v.len)&&d.len){var A=this.getAppendedFrag(k.start,Re.MAIN);if(null===A)return;if(S||(S=!!A.gap||!!L&&0===v.len),L&&!S||S&&d.nextStart&&d.nextStart<A.end)return}this.loadFragment(k,l,T)}else this.bufferFlushed=!0}}}}}},{"key":"getMaxBufferLength","value":function getMaxBufferLength(t){var r=(0,d.Z)((0,h.Z)(AudioStreamController.prototype),"getMaxBufferLength",this).call(this);return t?Math.min(Math.max(r,t),this.config.maxMaxBufferLength):r}},{"key":"onMediaDetaching","value":function onMediaDetaching(){this.videoBuffer=null,(0,d.Z)((0,h.Z)(AudioStreamController.prototype),"onMediaDetaching",this).call(this)}},{"key":"onAudioTracksUpdated","value":function onAudioTracksUpdated(t,r){var a=r.audioTracks;this.resetTransmuxer(),this.levels=a.map((function(t){return new Oe(t)}))}},{"key":"onAudioTrackSwitching","value":function onAudioTrackSwitching(t,r){var a=!!r.url;this.trackId=r.id;var i=this.fragCurrent;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),a?this.setInterval(100):this.resetTransmuxer(),a?(this.switchingTrack=r,this.state=ft.IDLE):(this.switchingTrack=null,this.bufferedTrack=r,this.state=ft.STOPPED),this.tick()}},{"key":"onManifestLoading","value":function onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}},{"key":"onLevelLoaded","value":function onLevelLoaded(t,r){this.mainDetails=r.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(I.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}},{"key":"onAudioTrackLoaded","value":function onAudioTrackLoaded(t,r){var a;if(null!=this.mainDetails){var i=this.levels,o=r.details,l=r.id;if(i){this.log("Track ".concat(l," loaded [").concat(o.startSN,",").concat(o.endSN,"]").concat(o.lastPartSn?"[part-".concat(o.lastPartSn,"-").concat(o.lastPartIndex,"]"):"",",duration:").concat(o.totalduration));var u=i[l],c=0;if(o.live||null!=(a=u.details)&&a.live){var d=this.mainDetails;if(o.fragments[0]||(o.deltaUpdateFailed=!0),o.deltaUpdateFailed||!d)return;!u.details&&o.hasProgramDateTime&&d.hasProgramDateTime?(alignMediaPlaylistByPDT(o,d),c=o.fragments[0].start):c=this.alignPlaylists(o,u.details)}u.details=o,this.levelLastLoaded=l,this.startFragRequested||!this.mainDetails&&o.live||this.setStartPosition(u.details,c),this.state!==ft.WAITING_TRACK||this.waitForCdnTuneIn(o)||(this.state=ft.IDLE),this.tick()}else this.warn("Audio tracks were reset while loading level ".concat(l))}else this.cachedTrackLoadedData=r}},{"key":"_handleFragmentLoadProgress","value":function _handleFragmentLoadProgress(t){var r,a=t.frag,i=t.part,o=t.payload,l=this.config,u=this.trackId,c=this.levels;if(c){var d=c[u];if(d){var h=d.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(a.start);var g=l.defaultAudioCodec||d.audioCodec||"mp4a.40.2",v=this.transmuxer;v||(v=this.transmuxer=new zt(this.hls,Re.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var m=this.initPTS[a.cc],y=null==(r=a.initSegment)?void 0:r.data;if(void 0!==m){var p=i?i.index:-1,T=-1!==p,E=new ot(a.level,a.sn,a.stats.chunkCount,o.byteLength,p,T);v.push(o,y,g,"",a,i,h.totalduration,!1,E,m)}else{this.log("Unknown video PTS for cc ".concat(a.cc,", waiting for video PTS before demuxing audio frag ").concat(a.sn," of [").concat(h.startSN," ,").concat(h.endSN,"],track ").concat(u)),(this.waitingData=this.waitingData||{"frag":a,"part":i,"cache":new tr,"complete":!1}).cache.push(new Uint8Array(o)),this.waitingVideoCC=this.videoTrackCC,this.state=ft.WAITING_INIT_PTS}}else this.warn("Audio track is undefined on fragment load progress")}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment ".concat(a.sn," of level ").concat(a.level," will not be buffered"))}},{"key":"_handleFragmentLoadComplete","value":function _handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:(0,d.Z)((0,h.Z)(AudioStreamController.prototype),"_handleFragmentLoadComplete",this).call(this,t)}},{"key":"onBufferReset","value":function onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}},{"key":"onBufferCreated","value":function onBufferCreated(t,r){var a=r.tracks.audio;a&&(this.mediaBuffer=a.buffer||null),r.tracks.video&&(this.videoBuffer=r.tracks.video.buffer||null)}},{"key":"onFragBuffered","value":function onFragBuffered(t,r){var a,i=r.frag,o=r.part;if(i.type===Re.AUDIO)if(this.fragContextChanged(i))this.warn("Fragment ".concat(i.sn).concat(o?" p: "+o.index:""," of level ").concat(i.level," finished buffering, but was aborted. state: ").concat(this.state,", audioSwitch: ").concat(this.switchingTrack?this.switchingTrack.name:"false"));else{if("initSegment"!==i.sn){this.fragPrevious=i;var l=this.switchingTrack;l&&(this.bufferedTrack=l,this.switchingTrack=null,this.hls.trigger(I.AUDIO_TRACK_SWITCHED,_objectSpread2({},l)))}this.fragBufferedComplete(i,o)}else this.loadedmetadata||i.type!==Re.MAIN||null!=(a=this.videoBuffer||this.media)&&a.buffered.length&&(this.loadedmetadata=!0)}},{"key":"onError","value":function onError(t,r){var a;if(r.fatal)this.state=ft.ERROR;else switch(r.details){case b.FRAG_GAP:case b.FRAG_PARSING_ERROR:case b.FRAG_DECRYPT_ERROR:case b.FRAG_LOAD_ERROR:case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_ERROR:case b.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Re.AUDIO,r);break;case b.AUDIO_TRACK_LOAD_ERROR:case b.AUDIO_TRACK_LOAD_TIMEOUT:case b.LEVEL_PARSING_ERROR:r.levelRetry||this.state!==ft.WAITING_TRACK||(null==(a=r.context)?void 0:a.type)!==Ae.AUDIO_TRACK||(this.state=ft.IDLE);break;case b.BUFFER_FULL_ERROR:if(!r.parent||"audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,(0,d.Z)((0,h.Z)(AudioStreamController.prototype),"flushMainBuffer",this).call(this,0,Number.POSITIVE_INFINITY,"audio"));break;case b.INTERNAL_EXCEPTION:this.recoverWorkerError(r)}}},{"key":"onBufferFlushed","value":function onBufferFlushed(t,r){r.type===B.AUDIO&&(this.bufferFlushed=!0,this.state===ft.ENDED&&(this.state=ft.IDLE))}},{"key":"_handleTransmuxComplete","value":function _handleTransmuxComplete(t){var r,a="audio",i=this.hls,o=t.remuxResult,l=t.chunkMeta,u=this.getCurrentContext(l);if(u){var c=u.frag,d=u.part,h=u.level.details,g=o.audio,v=o.text,m=o.id3,y=o.initSegment;if(!this.fragContextChanged(c)&&h){if(this.state=ft.PARSING,this.switchingTrack&&g&&this.completeAudioSwitch(this.switchingTrack),null!=y&&y.tracks){var p=c.initSegment||c;this._bufferInitSegment(y.tracks,p,l),i.trigger(I.FRAG_PARSING_INIT_SEGMENT,{"frag":p,"id":a,"tracks":y.tracks})}if(g){var T=g.startPTS,E=g.endPTS,k=g.startDTS,S=g.endDTS;d&&(d.elementaryStreams[B.AUDIO]={"startPTS":T,"endPTS":E,"startDTS":k,"endDTS":S}),c.setElementaryStreamInfo(B.AUDIO,T,E,k,S),this.bufferFragmentData(g,c,d,l)}if(null!=m&&null!=(r=m.samples)&&r.length){var L=_extends({"id":a,"frag":c,"details":h},m);i.trigger(I.FRAG_PARSING_METADATA,L)}if(v){var A=_extends({"id":a,"frag":c,"details":h},v);i.trigger(I.FRAG_PARSING_USERDATA,A)}}else this.fragmentTracker.removeFragment(c)}else this.resetWhenMissingContext(l)}},{"key":"_bufferInitSegment","value":function _bufferInitSegment(t,r,a){if(this.state===ft.PARSING){t.video&&delete t.video;var i=t.audio;if(i){i.levelCodec=i.codec,i.id="audio",this.log("Init audio buffer, container:".concat(i.container,", codecs[parsed]=[").concat(i.codec,"]")),this.hls.trigger(I.BUFFER_CODECS,t);var o=i.initSegment;if(null!=o&&o.byteLength){var l={"type":"audio","frag":r,"part":null,"chunkMeta":a,"parent":r.type,"data":o};this.hls.trigger(I.BUFFER_APPENDING,l)}this.tick()}}}},{"key":"loadFragment","value":function loadFragment(t,r,a){var i,o=this.fragmentTracker.getState(t);(this.fragCurrent=t,this.switchingTrack||o===ze||o===Qe)?"initSegment"===t.sn?this._loadInitSegment(t,r):null!=(i=r.details)&&i.live&&!this.initPTS[t.cc]?(this.log("Waiting for video PTS in continuity counter ".concat(t.cc," of live stream before loading audio fragment ").concat(t.sn," of level ").concat(this.trackId)),this.state=ft.WAITING_INIT_PTS):(this.startFragRequested=!0,(0,d.Z)((0,h.Z)(AudioStreamController.prototype),"loadFragment",this).call(this,t,r,a)):this.clearTrackerIfNeeded(t)}},{"key":"completeAudioSwitch","value":function completeAudioSwitch(t){var r=this.hls,a=this.media,i=this.bufferedTrack,o=null==i?void 0:i.attrs,l=t.attrs;a&&o&&(o.CHANNELS!==l.CHANNELS||o.NAME!==l.NAME||o.LANGUAGE!==l.LANGUAGE)&&(this.log("Switching audio track : flushing all audio"),(0,d.Z)((0,h.Z)(AudioStreamController.prototype),"flushMainBuffer",this).call(this,0,Number.POSITIVE_INFINITY,"audio")),this.bufferedTrack=t,this.switchingTrack=null,r.trigger(I.AUDIO_TRACK_SWITCHED,_objectSpread2({},t))}}]),AudioStreamController}(gt),ar=function(t){(0,g.Z)(AudioTrackController,t);var r=(0,v.Z)(AudioTrackController);function AudioTrackController(t){var a;return(0,m.Z)(this,AudioTrackController),(a=r.call(this,t,"[audio-track-controller]")).tracks=[],a.groupId=null,a.tracksInGroup=[],a.trackId=-1,a.currentTrack=null,a.selectDefaultTrack=!0,a.registerListeners(),a}return(0,y.Z)(AudioTrackController,[{"key":"registerListeners","value":function registerListeners(){var t=this.hls;t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.MANIFEST_PARSED,this.onManifestParsed,this),t.on(I.LEVEL_LOADING,this.onLevelLoading,this),t.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(I.ERROR,this.onError,this)}},{"key":"unregisterListeners","value":function unregisterListeners(){var t=this.hls;t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.MANIFEST_PARSED,this.onManifestParsed,this),t.off(I.LEVEL_LOADING,this.onLevelLoading,this),t.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(I.ERROR,this.onError,this)}},{"key":"destroy","value":function destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,(0,d.Z)((0,h.Z)(AudioTrackController.prototype),"destroy",this).call(this)}},{"key":"onManifestLoading","value":function onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}},{"key":"onManifestParsed","value":function onManifestParsed(t,r){this.tracks=r.audioTracks||[]}},{"key":"onAudioTrackLoaded","value":function onAudioTrackLoaded(t,r){var a=r.id,i=r.groupId,o=r.details,l=this.tracksInGroup[a];if(l&&l.groupId===i){var u=l.details;l.details=r.details,this.log("audio-track ".concat(a,' "').concat(l.name,'" lang:').concat(l.lang," group:").concat(i," loaded [").concat(o.startSN,"-").concat(o.endSN,"]")),a===this.trackId&&this.playlistLoaded(a,r,u)}else this.warn("Track with id:".concat(a," and group:").concat(i," not found in active group ").concat(l.groupId))}},{"key":"onLevelLoading","value":function onLevelLoading(t,r){this.switchLevel(r.level)}},{"key":"onLevelSwitching","value":function onLevelSwitching(t,r){this.switchLevel(r.level)}},{"key":"switchLevel","value":function switchLevel(t){var r=this.hls.levels[t];if(null!=r&&r.audioGroupIds){var a=r.audioGroupIds[r.urlId];if(this.groupId!==a){this.groupId=a||null;var i=this.tracks.filter((function(t){return!a||t.groupId===a}));this.selectDefaultTrack&&!i.some((function(t){return t.default}))&&(this.selectDefaultTrack=!1),this.tracksInGroup=i;var o={"audioTracks":i};this.log("Updating audio tracks, ".concat(i.length," track(s) found in group:").concat(a)),this.hls.trigger(I.AUDIO_TRACKS_UPDATED,o),this.selectInitialTrack()}else this.shouldReloadPlaylist(this.currentTrack)&&this.setAudioTrack(this.trackId)}}},{"key":"onError","value":function onError(t,r){!r.fatal&&r.context&&r.context.type===Ae.AUDIO_TRACK&&r.context.id===this.trackId&&r.context.groupId===this.groupId&&(this.requestScheduled=-1,this.checkRetry(r))}},{"key":"audioTracks","get":function get(){return this.tracksInGroup}},{"key":"audioTrack","get":function get(){return this.trackId},"set":function set(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}},{"key":"setAudioTrack","value":function setAudioTrack(t){var r=this.tracksInGroup;if(t<0||t>=r.length)this.warn("Invalid id passed to audio-track controller");else{this.clearTimer();var a=this.currentTrack,i=r[t],o=i.groupId,l=i.name;if(this.log("Switching to audio-track ".concat(t,' "').concat(l,'" lang:').concat(i.lang," group:").concat(o)),this.trackId=t,this.currentTrack=i,this.selectDefaultTrack=!1,this.hls.trigger(I.AUDIO_TRACK_SWITCHING,_objectSpread2({},i)),!i.details||i.details.live){var u=this.switchParams(i.url,null==a?void 0:a.details);this.loadPlaylist(u)}}}},{"key":"selectInitialTrack","value":function selectInitialTrack(){var t=this.tracksInGroup,r=this.findTrackId(this.currentTrack)|this.findTrackId(null);if(-1!==r)this.setAudioTrack(r);else{var a=new Error("No track found for running audio group-ID: ".concat(this.groupId," track count: ").concat(t.length));this.warn(a.message),this.hls.trigger(I.ERROR,{"type":D.MEDIA_ERROR,"details":b.AUDIO_TRACK_LOAD_ERROR,"fatal":!0,"error":a})}}},{"key":"findTrackId","value":function findTrackId(t){for(var r=this.tracksInGroup,a=0;a<r.length;a++){var i=r[a];if(!this.selectDefaultTrack||i.default){if(!t||void 0!==t.attrs["STABLE-RENDITION-ID"]&&t.attrs["STABLE-RENDITION-ID"]===i.attrs["STABLE-RENDITION-ID"])return i.id;if(t.name===i.name&&t.lang===i.lang)return i.id}}return-1}},{"key":"loadPlaylist","value":function loadPlaylist(t){(0,d.Z)((0,h.Z)(AudioTrackController.prototype),"loadPlaylist",this).call(this);var r=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(r)){var a=r.id,i=r.groupId,o=r.url;if(t)try{o=t.addDirectives(o)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: ".concat(t))}this.log("loading audio-track playlist ".concat(a,' "').concat(r.name,'" lang:').concat(r.lang," group:").concat(i)),this.clearTimer(),this.hls.trigger(I.AUDIO_TRACK_LOADING,{"url":o,"id":a,"groupId":i,"deliveryDirectives":t||null})}}}]),AudioTrackController}(je);function subtitleOptionsIdentical(t,r){if(t.length!==r.length)return!1;for(var a=0;a<t.length;a++)if(!subtitleAttributesIdentical(t[a].attrs,r[a].attrs))return!1;return!0}function subtitleAttributesIdentical(t,r){var a=t["STABLE-RENDITION-ID"];return a?a===r["STABLE-RENDITION-ID"]:!["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED"].some((function(a){return t[a]!==r[a]}))}var ir=function(t){(0,g.Z)(SubtitleStreamController,t);var r=(0,v.Z)(SubtitleStreamController);function SubtitleStreamController(t,a,i){var o;return(0,m.Z)(this,SubtitleStreamController),(o=r.call(this,t,a,i,"[subtitle-stream-controller]",Re.SUBTITLE)).levels=[],o.currentTrackId=-1,o.tracksBuffered=[],o.mainDetails=null,o._registerListeners(),o}return(0,y.Z)(SubtitleStreamController,[{"key":"onHandlerDestroying","value":function onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null}},{"key":"_registerListeners","value":function _registerListeners(){var t=this.hls;t.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.LEVEL_LOADED,this.onLevelLoaded,this),t.on(I.ERROR,this.onError,this),t.on(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(I.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(I.FRAG_BUFFERED,this.onFragBuffered,this)}},{"key":"_unregisterListeners","value":function _unregisterListeners(){var t=this.hls;t.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.LEVEL_LOADED,this.onLevelLoaded,this),t.off(I.ERROR,this.onError,this),t.off(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(I.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(I.FRAG_BUFFERED,this.onFragBuffered,this)}},{"key":"startLoad","value":function startLoad(t){this.stopLoad(),this.state=ft.IDLE,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}},{"key":"onManifestLoading","value":function onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}},{"key":"onMediaDetaching","value":function onMediaDetaching(){this.tracksBuffered=[],(0,d.Z)((0,h.Z)(SubtitleStreamController.prototype),"onMediaDetaching",this).call(this)}},{"key":"onLevelLoaded","value":function onLevelLoaded(t,r){this.mainDetails=r.details}},{"key":"onSubtitleFragProcessed","value":function onSubtitleFragProcessed(t,r){var a=r.frag,i=r.success;if(this.fragPrevious=a,this.state=ft.IDLE,i){var o=this.tracksBuffered[this.currentTrackId];if(o){for(var l,u=a.start,c=0;c<o.length;c++)if(u>=o[c].start&&u<=o[c].end){l=o[c];break}var d=a.start+a.duration;l?l.end=d:(l={"start":u,"end":d},o.push(l)),this.fragmentTracker.fragBuffered(a)}}}},{"key":"onBufferFlushing","value":function onBufferFlushing(t,r){var a=r.startOffset,i=r.endOffset;if(0===a&&i!==Number.POSITIVE_INFINITY){var o=this.currentTrackId,l=this.levels;if(!l.length||!l[o]||!l[o].details)return;var u=i-l[o].details.targetduration;if(u<=0)return;r.endOffsetSubtitles=Math.max(0,u),this.tracksBuffered.forEach((function(t){for(var r=0;r<t.length;)if(t[r].end<=u)t.shift();else{if(!(t[r].start<u))break;t[r].start=u,r++}})),this.fragmentTracker.removeFragmentsInRange(a,u,Re.SUBTITLE)}}},{"key":"onFragBuffered","value":function onFragBuffered(t,r){var a;this.loadedmetadata||r.frag.type!==Re.MAIN||null!=(a=this.media)&&a.buffered.length&&(this.loadedmetadata=!0)}},{"key":"onError","value":function onError(t,r){var a=r.frag;(null==a?void 0:a.type)===Re.SUBTITLE&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==ft.STOPPED&&(this.state=ft.IDLE))}},{"key":"onSubtitleTracksUpdated","value":function onSubtitleTracksUpdated(t,r){var a=this,i=r.subtitleTracks;subtitleOptionsIdentical(this.levels,i)?this.levels=i.map((function(t){return new Oe(t)})):(this.tracksBuffered=[],this.levels=i.map((function(t){var r=new Oe(t);return a.tracksBuffered[r.id]=[],r})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Re.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)}},{"key":"onSubtitleTrackSwitch","value":function onSubtitleTrackSwitch(t,r){if(this.currentTrackId=r.id,this.levels.length&&-1!==this.currentTrackId){var a=this.levels[this.currentTrackId];null!=a&&a.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,a&&this.setInterval(500)}else this.clearInterval()}},{"key":"onSubtitleTrackLoaded","value":function onSubtitleTrackLoaded(t,r){var a,i=r.details,o=r.id,l=this.currentTrackId,u=this.levels;if(u.length){var c=u[l];if(!(o>=u.length||o!==l)&&c){this.mediaBuffer=this.mediaBufferTimeRanges;var d=0;if(i.live||null!=(a=c.details)&&a.live){var h=this.mainDetails;if(i.deltaUpdateFailed||!h)return;var g=h.fragments[0];c.details?0===(d=this.alignPlaylists(i,c.details))&&g&&addSliding(i,d=g.start):i.hasProgramDateTime&&h.hasProgramDateTime?(alignMediaPlaylistByPDT(i,h),d=i.fragments[0].start):g&&addSliding(i,d=g.start)}if(c.details=i,this.levelLastLoaded=o,this.startFragRequested||!this.mainDetails&&i.live||this.setStartPosition(c.details,d),this.tick(),i.live&&!this.fragCurrent&&this.media&&this.state===ft.IDLE)findFragmentByPTS(null,i.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)}}}},{"key":"_handleFragmentLoadComplete","value":function _handleFragmentLoadComplete(t){var r=this,a=t.frag,i=t.payload,o=a.decryptdata,l=this.hls;if(!this.fragContextChanged(a)&&i&&i.byteLength>0&&o&&o.key&&o.iv&&"AES-128"===o.method){var u=performance.now();this.decrypter.decrypt(new Uint8Array(i),o.key.buffer,o.iv.buffer).catch((function(t){throw l.trigger(I.ERROR,{"type":D.MEDIA_ERROR,"details":b.FRAG_DECRYPT_ERROR,"fatal":!1,"error":t,"reason":t.message,"frag":a}),t})).then((function(t){var r=performance.now();l.trigger(I.FRAG_DECRYPTED,{"frag":a,"payload":t,"stats":{"tstart":u,"tdecrypt":r}})})).catch((function(t){r.warn("".concat(t.name,": ").concat(t.message)),r.state=ft.IDLE}))}}},{"key":"doTick","value":function doTick(){if(this.media){if(this.state===ft.IDLE){var t=this.currentTrackId,r=this.levels,a=r[t];if(!r.length||!a||!a.details)return;var i=a.details,o=i.targetduration,l=this.config,u=this.getLoadPosition(),c=st.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],u-o,l.maxBufferHole),d=c.end,h=c.len,g=this.getFwdBufferInfo(this.media,Re.MAIN);if(h>this.getMaxBufferLength(null==g?void 0:g.len)+o)return;var v=i.fragments,m=v.length,y=i.edge,p=null,T=this.fragPrevious;if(d<y){var E=l.maxFragLookUpTolerance;!(p=findFragmentByPTS(T,v,Math.max(v[0].start,d),E))&&T&&T.start<v[0].start&&(p=v[0])}else p=v[m-1];if(!p)return;p=this.mapToInitFragWhenRequired(p),this.fragmentTracker.getState(p)===ze&&this.loadFragment(p,a,d)}}else this.state=ft.IDLE}},{"key":"getMaxBufferLength","value":function getMaxBufferLength(t){var r=(0,d.Z)((0,h.Z)(SubtitleStreamController.prototype),"getMaxBufferLength",this).call(this);return t?Math.max(r,t):r}},{"key":"loadFragment","value":function loadFragment(t,r,a){this.fragCurrent=t,"initSegment"===t.sn?this._loadInitSegment(t,r):(this.startFragRequested=!0,(0,d.Z)((0,h.Z)(SubtitleStreamController.prototype),"loadFragment",this).call(this,t,r,a))}},{"key":"mediaBufferTimeRanges","get":function get(){return new nr(this.tracksBuffered[this.currentTrackId]||[])}}]),SubtitleStreamController}(gt),nr=(0,y.Z)((function BufferableInstance(t){(0,m.Z)(this,BufferableInstance),this.buffered=void 0;var r=function getRange(r,a,i){if((a>>>=0)>i-1)throw new DOMException("Failed to execute '".concat(r,"' on 'TimeRanges': The index provided (").concat(a,") is greater than the maximum bound (").concat(i,")"));return t[a][r]};this.buffered={get"length"(){return t.length},"end"(a){return r("end",a,t.length)},"start"(a){return r("start",a,t.length)}}})),sr=function(t){(0,g.Z)(SubtitleTrackController,t);var r=(0,v.Z)(SubtitleTrackController);function SubtitleTrackController(t){var a;return(0,m.Z)(this,SubtitleTrackController),(a=r.call(this,t,"[subtitle-track-controller]")).media=null,a.tracks=[],a.groupId=null,a.tracksInGroup=[],a.trackId=-1,a.selectDefaultTrack=!0,a.queuedDefaultTrack=-1,a.trackChangeListener=function(){return a.onTextTracksChanged()},a.asyncPollTrackChange=function(){return a.pollTrackChange(0)},a.useTextTrackPolling=!1,a.subtitlePollingInterval=-1,a._subtitleDisplay=!0,a.registerListeners(),a}return(0,y.Z)(SubtitleTrackController,[{"key":"destroy","value":function destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.trackChangeListener=this.asyncPollTrackChange=null,(0,d.Z)((0,h.Z)(SubtitleTrackController.prototype),"destroy",this).call(this)}},{"key":"subtitleDisplay","get":function get(){return this._subtitleDisplay},"set":function set(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes(this.trackId)}},{"key":"registerListeners","value":function registerListeners(){var t=this.hls;t.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.MANIFEST_PARSED,this.onManifestParsed,this),t.on(I.LEVEL_LOADING,this.onLevelLoading,this),t.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(I.ERROR,this.onError,this)}},{"key":"unregisterListeners","value":function unregisterListeners(){var t=this.hls;t.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.MANIFEST_PARSED,this.onManifestParsed,this),t.off(I.LEVEL_LOADING,this.onLevelLoading,this),t.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(I.ERROR,this.onError,this)}},{"key":"onMediaAttached","value":function onMediaAttached(t,r){this.media=r.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}},{"key":"pollTrackChange","value":function pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,t)}},{"key":"onMediaDetaching","value":function onMediaDetaching(){this.media&&(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),filterSubtitleTracks(this.media.textTracks).forEach((function(t){clearCurrentCues(t)})),this.subtitleTrack=-1,this.media=null)}},{"key":"onManifestLoading","value":function onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0}},{"key":"onManifestParsed","value":function onManifestParsed(t,r){this.tracks=r.subtitleTracks}},{"key":"onSubtitleTrackLoaded","value":function onSubtitleTrackLoaded(t,r){var a=r.id,i=r.details,o=this.trackId,l=this.tracksInGroup[o];if(l){var u=l.details;l.details=r.details,this.log("subtitle track ".concat(a," loaded [").concat(i.startSN,"-").concat(i.endSN,"]")),a===this.trackId&&this.playlistLoaded(a,r,u)}else this.warn("Invalid subtitle track id ".concat(a))}},{"key":"onLevelLoading","value":function onLevelLoading(t,r){this.switchLevel(r.level)}},{"key":"onLevelSwitching","value":function onLevelSwitching(t,r){this.switchLevel(r.level)}},{"key":"switchLevel","value":function switchLevel(t){var r=this.hls.levels[t];if(null!=r&&r.textGroupIds){var a=r.textGroupIds[r.urlId],i=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;if(this.groupId!==a){var o=this.tracks.filter((function(t){return!a||t.groupId===a}));this.tracksInGroup=o;var l=this.findTrackId(null==i?void 0:i.name)||this.findTrackId();this.groupId=a||null;var u={"subtitleTracks":o};this.log("Updating subtitle tracks, ".concat(o.length,' track(s) found in "').concat(a,'" group-id')),this.hls.trigger(I.SUBTITLE_TRACKS_UPDATED,u),-1!==l&&this.setSubtitleTrack(l,i)}else this.shouldReloadPlaylist(i)&&this.setSubtitleTrack(this.trackId,i)}}},{"key":"findTrackId","value":function findTrackId(t){for(var r=this.tracksInGroup,a=0;a<r.length;a++){var i=r[a];if((!this.selectDefaultTrack||i.default)&&(!t||t===i.name))return i.id}return-1}},{"key":"onError","value":function onError(t,r){!r.fatal&&r.context&&r.context.type===Ae.SUBTITLE_TRACK&&r.context.id===this.trackId&&r.context.groupId===this.groupId&&this.checkRetry(r)}},{"key":"subtitleTracks","get":function get(){return this.tracksInGroup}},{"key":"subtitleTrack","get":function get(){return this.trackId},"set":function set(t){this.selectDefaultTrack=!1;var r=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;this.setSubtitleTrack(t,r)}},{"key":"loadPlaylist","value":function loadPlaylist(t){(0,d.Z)((0,h.Z)(SubtitleTrackController.prototype),"loadPlaylist",this).call(this);var r=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(r)){var a=r.id,i=r.groupId,o=r.url;if(t)try{o=t.addDirectives(o)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: ".concat(t))}this.log("Loading subtitle playlist for id ".concat(a)),this.hls.trigger(I.SUBTITLE_TRACK_LOADING,{"url":o,"id":a,"groupId":i,"deliveryDirectives":t||null})}}},{"key":"toggleTrackModes","value":function toggleTrackModes(t){var r=this,a=this.media,i=this.trackId;if(a){var o=filterSubtitleTracks(a.textTracks),l=o.filter((function(t){return t.groupId===r.groupId}));if(-1===t)[].slice.call(o).forEach((function(t){t.mode="disabled"}));else{var u=l[i];u&&(u.mode="disabled")}var c=l[t];c&&(c.mode=this.subtitleDisplay?"showing":"hidden")}}},{"key":"setSubtitleTrack","value":function setSubtitleTrack(t,r){var a,i=this.tracksInGroup;if(this.media){if(this.trackId!==t&&this.toggleTrackModes(t),!(this.trackId===t&&(-1===t||null!=(a=i[t])&&a.details)||t<-1||t>=i.length)){this.clearTimer();var o=i[t];if(this.log("Switching to subtitle-track ".concat(t)+(o?' "'.concat(o.name,'" lang:').concat(o.lang," group:").concat(o.groupId):"")),this.trackId=t,o){var l=o.id,u=o.groupId,c=void 0===u?"":u,d=o.name,h=o.type,g=o.url;this.hls.trigger(I.SUBTITLE_TRACK_SWITCH,{"id":l,"groupId":c,"name":d,"type":h,"url":g});var v=this.switchParams(o.url,null==r?void 0:r.details);this.loadPlaylist(v)}else this.hls.trigger(I.SUBTITLE_TRACK_SWITCH,{"id":t})}}else this.queuedDefaultTrack=t}},{"key":"onTextTracksChanged","value":function onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),this.media&&this.hls.config.renderTextTracksNatively){for(var t=-1,r=filterSubtitleTracks(this.media.textTracks),a=0;a<r.length;a++)if("hidden"===r[a].mode)t=a;else if("showing"===r[a].mode){t=a;break}this.subtitleTrack!==t&&(this.subtitleTrack=t)}}}]),SubtitleTrackController}(je);function filterSubtitleTracks(t){for(var r=[],a=0;a<t.length;a++){var i=t[a];"subtitles"!==i.kind&&"captions"!==i.kind||!i.label||r.push(t[a])}return r}var or=function(){function BufferOperationQueue(t){(0,m.Z)(this,BufferOperationQueue),this.buffers=void 0,this.queues={"video":[],"audio":[],"audiovideo":[]},this.buffers=t}return(0,y.Z)(BufferOperationQueue,[{"key":"append","value":function append(t,r){var a=this.queues[r];a.push(t),1===a.length&&this.buffers[r]&&this.executeNext(r)}},{"key":"insertAbort","value":function insertAbort(t,r){this.queues[r].unshift(t),this.executeNext(r)}},{"key":"appendBlocker","value":function appendBlocker(t){var r,a=new Promise((function(t){r=t})),i={"execute":r,"onStart":function onStart(){},"onComplete":function onComplete(){},"onError":function onError(){}};return this.append(i,t),a}},{"key":"executeNext","value":function executeNext(t){var r=this.buffers,a=this.queues,i=r[t],o=a[t];if(o.length){var l=o[0];try{l.execute()}catch(r){w.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),l.onError(r),null!=i&&i.updating||(o.shift(),this.executeNext(t))}}}},{"key":"shiftAndExecuteNext","value":function shiftAndExecuteNext(t){this.queues[t].shift(),this.executeNext(t)}},{"key":"current","value":function current(t){return this.queues[t][0]}}]),BufferOperationQueue}(),lr=getMediaSource(),ur=/([ha]vc.)(?:\.[^.,]+)+/,cr=function(){function BufferController(t){var r=this;(0,m.Z)(this,BufferController),this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendError=0,this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this._onMediaSourceOpen=function(){var t=r.media,a=r.mediaSource;w.log("[buffer-controller]: Media source opened"),t&&(t.removeEventListener("emptied",r._onMediaEmptied),r.updateMediaElementDuration(),r.hls.trigger(I.MEDIA_ATTACHED,{"media":t})),a&&a.removeEventListener("sourceopen",r._onMediaSourceOpen),r.checkPendingTracks()},this._onMediaSourceClose=function(){w.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=function(){w.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=function(){var t=r.media,a=r._objectUrl;t&&t.src!==a&&w.error("Media element src was set while attaching MediaSource (".concat(a," > ").concat(t.src,")"))},this.hls=t,this._initSourceBuffer(),this.registerListeners()}return(0,y.Z)(BufferController,[{"key":"hasSourceTypes","value":function hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}},{"key":"destroy","value":function destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null}},{"key":"registerListeners","value":function registerListeners(){var t=this.hls;t.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.MANIFEST_PARSED,this.onManifestParsed,this),t.on(I.BUFFER_RESET,this.onBufferReset,this),t.on(I.BUFFER_APPENDING,this.onBufferAppending,this),t.on(I.BUFFER_CODECS,this.onBufferCodecs,this),t.on(I.BUFFER_EOS,this.onBufferEos,this),t.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(I.FRAG_PARSED,this.onFragParsed,this),t.on(I.FRAG_CHANGED,this.onFragChanged,this)}},{"key":"unregisterListeners","value":function unregisterListeners(){var t=this.hls;t.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.MANIFEST_PARSED,this.onManifestParsed,this),t.off(I.BUFFER_RESET,this.onBufferReset,this),t.off(I.BUFFER_APPENDING,this.onBufferAppending,this),t.off(I.BUFFER_CODECS,this.onBufferCodecs,this),t.off(I.BUFFER_EOS,this.onBufferEos,this),t.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(I.FRAG_PARSED,this.onFragParsed,this),t.off(I.FRAG_CHANGED,this.onFragChanged,this)}},{"key":"_initSourceBuffer","value":function _initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new or(this.sourceBuffer),this.listeners={"audio":[],"video":[],"audiovideo":[]},this.lastMpegAudioChunk=null}},{"key":"onManifestLoading","value":function onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}},{"key":"onManifestParsed","value":function onManifestParsed(t,r){var a=2;(r.audio&&!r.video||!r.altAudio)&&(a=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=a,w.log("".concat(this.bufferCodecEventsExpected," bufferCodec event(s) expected"))}},{"key":"onMediaAttaching","value":function onMediaAttaching(t,r){var a=this.media=r.media;if(a&&lr){var i=this.mediaSource=new lr;i.addEventListener("sourceopen",this._onMediaSourceOpen),i.addEventListener("sourceended",this._onMediaSourceEnded),i.addEventListener("sourceclose",this._onMediaSourceClose),a.src=self.URL.createObjectURL(i),this._objectUrl=a.src,a.addEventListener("emptied",this._onMediaEmptied)}}},{"key":"onMediaDetaching","value":function onMediaDetaching(){var t=this.media,r=this.mediaSource,a=this._objectUrl;if(r){if(w.log("[buffer-controller]: media source detaching"),"open"===r.readyState)try{r.endOfStream()}catch(t){w.warn("[buffer-controller]: onMediaDetaching: ".concat(t.message," while calling endOfStream"))}this.onBufferReset(),r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),t&&(t.removeEventListener("emptied",this._onMediaEmptied),a&&self.URL.revokeObjectURL(a),t.src===a?(t.removeAttribute("src"),t.load()):w.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(I.MEDIA_DETACHED,void 0)}},{"key":"onBufferReset","value":function onBufferReset(){var t=this;this.getSourceBufferTypes().forEach((function(r){var a=t.sourceBuffer[r];try{a&&(t.removeBufferListeners(r),t.mediaSource&&t.mediaSource.removeSourceBuffer(a),t.sourceBuffer[r]=void 0)}catch(t){w.warn("[buffer-controller]: Failed to reset the ".concat(r," buffer"),t)}})),this._initSourceBuffer()}},{"key":"onBufferCodecs","value":function onBufferCodecs(t,r){var a=this,i=this.getSourceBufferTypes().length;Object.keys(r).forEach((function(t){if(i){var o=a.tracks[t];if(o&&"function"==typeof o.buffer.changeType){var l=r[t],u=l.id,c=l.codec,d=l.levelCodec,h=l.container,g=l.metadata,v=(o.levelCodec||o.codec).replace(ur,"$1"),m=(d||c).replace(ur,"$1");if(v!==m){var y="".concat(h,";codecs=").concat(d||c);a.appendChangeType(t,y),w.log("[buffer-controller]: switching codec ".concat(v," to ").concat(m)),a.tracks[t]={"buffer":o.buffer,"codec":c,"container":h,"levelCodec":d,"metadata":g,"id":u}}}}else a.pendingTracks[t]=r[t]})),i||(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())}},{"key":"appendChangeType","value":function appendChangeType(t,r){var a=this,i=this.operationQueue,o={"execute":function execute(){var o=a.sourceBuffer[t];o&&(w.log("[buffer-controller]: changing ".concat(t," sourceBuffer type to ").concat(r)),o.changeType(r)),i.shiftAndExecuteNext(t)},"onStart":function onStart(){},"onComplete":function onComplete(){},"onError":function onError(r){w.warn("[buffer-controller]: Failed to change ".concat(t," SourceBuffer type"),r)}};i.append(o,t)}},{"key":"onBufferAppending","value":function onBufferAppending(t,r){var a=this,i=this.hls,o=this.operationQueue,l=this.tracks,u=r.data,c=r.type,d=r.frag,h=r.part,g=r.chunkMeta,v=g.buffering[c],m=self.performance.now();v.start=m;var y=d.stats.buffering,p=h?h.stats.buffering:null;0===y.start&&(y.start=m),p&&0===p.start&&(p.start=m);var T=l.audio,E=!1;"audio"===c&&"audio/mpeg"===(null==T?void 0:T.container)&&(E=!this.lastMpegAudioChunk||1===g.id||this.lastMpegAudioChunk.sn!==g.sn,this.lastMpegAudioChunk=g);var k=d.start,S={"execute":function execute(){if(v.executeStart=self.performance.now(),E){var t=a.sourceBuffer[c];if(t){var r=k-t.timestampOffset;Math.abs(r)>=.1&&(w.log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to ".concat(k," (delta: ").concat(r,") sn: ").concat(d.sn,")")),t.timestampOffset=k)}}a.appendExecutor(u,c)},"onStart":function onStart(){},"onComplete":function onComplete(){var t=self.performance.now();v.executeEnd=v.end=t,0===y.first&&(y.first=t),p&&0===p.first&&(p.first=t);var r=a.sourceBuffer,i={};for(var o in r)i[o]=st.getBuffered(r[o]);a.appendError=0,a.hls.trigger(I.BUFFER_APPENDED,{"type":c,"frag":d,"part":h,"chunkMeta":g,"parent":d.type,"timeRanges":i})},"onError":function onError(t){w.error("[buffer-controller]: Error encountered while trying to append to the ".concat(c," SourceBuffer"),t);var r={"type":D.MEDIA_ERROR,"parent":d.type,"details":b.BUFFER_APPEND_ERROR,"frag":d,"part":h,"chunkMeta":g,"error":t,"err":t,"fatal":!1};t.code===DOMException.QUOTA_EXCEEDED_ERR?r.details=b.BUFFER_FULL_ERROR:(a.appendError++,r.details=b.BUFFER_APPEND_ERROR,a.appendError>i.config.appendErrorMaxRetry&&(w.error("[buffer-controller]: Failed ".concat(i.config.appendErrorMaxRetry," times to append segment in sourceBuffer")),r.fatal=!0)),i.trigger(I.ERROR,r)}};o.append(S,c)}},{"key":"onBufferFlushing","value":function onBufferFlushing(t,r){var a=this,i=this.operationQueue,o=function flushOperation(t){return{"execute":a.removeExecutor.bind(a,t,r.startOffset,r.endOffset),"onStart":function onStart(){},"onComplete":function onComplete(){a.hls.trigger(I.BUFFER_FLUSHED,{"type":t})},"onError":function onError(r){w.warn("[buffer-controller]: Failed to remove from ".concat(t," SourceBuffer"),r)}}};r.type?i.append(o(r.type),r.type):this.getSourceBufferTypes().forEach((function(t){i.append(o(t),t)}))}},{"key":"onFragParsed","value":function onFragParsed(t,r){var a=this,i=r.frag,o=r.part,l=[],u=o?o.elementaryStreams:i.elementaryStreams;u[B.AUDIOVIDEO]?l.push("audiovideo"):(u[B.AUDIO]&&l.push("audio"),u[B.VIDEO]&&l.push("video"));0===l.length&&w.warn("Fragments must have at least one ElementaryStreamType set. type: ".concat(i.type," level: ").concat(i.level," sn: ").concat(i.sn)),this.blockBuffers((function onUnblocked(){var t=self.performance.now();i.stats.buffering.end=t,o&&(o.stats.buffering.end=t);var r=o?o.stats:i.stats;a.hls.trigger(I.FRAG_BUFFERED,{"frag":i,"part":o,"stats":r,"id":i.type})}),l)}},{"key":"onFragChanged","value":function onFragChanged(t,r){this.flushBackBuffer()}},{"key":"onBufferEos","value":function onBufferEos(t,r){var a=this;this.getSourceBufferTypes().reduce((function(t,i){var o=a.sourceBuffer[i];return!o||r.type&&r.type!==i||(o.ending=!0,o.ended||(o.ended=!0,w.log("[buffer-controller]: ".concat(i," sourceBuffer now EOS")))),t&&!(o&&!o.ended)}),!0)&&(w.log("[buffer-controller]: Queueing mediaSource.endOfStream()"),this.blockBuffers((function(){a.getSourceBufferTypes().forEach((function(t){var r=a.sourceBuffer[t];r&&(r.ending=!1)}));var t=a.mediaSource;t&&"open"===t.readyState?(w.log("[buffer-controller]: Calling mediaSource.endOfStream()"),t.endOfStream()):t&&w.info("[buffer-controller]: Could not call mediaSource.endOfStream(). mediaSource.readyState: ".concat(t.readyState))})))}},{"key":"onLevelUpdated","value":function onLevelUpdated(t,r){var a=r.details;a.fragments.length&&(this.details=a,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}},{"key":"flushBackBuffer","value":function flushBackBuffer(){var t=this.hls,r=this.details,a=this.media,i=this.sourceBuffer;if(a&&null!==r){var o=this.getSourceBufferTypes();if(o.length){var l=r.live&&null!==t.config.liveBackBufferLength?t.config.liveBackBufferLength:t.config.backBufferLength;if(R(l)&&!(l<0)){var u=a.currentTime,c=r.levelTargetDuration,d=Math.max(l,c),h=Math.floor(u/c)*c-d;o.forEach((function(a){var o=i[a];if(o){var l=st.getBuffered(o);if(l.length>0&&h>l.start(0)){if(t.trigger(I.BACK_BUFFER_REACHED,{"bufferEnd":h}),r.live)t.trigger(I.LIVE_BACK_BUFFER_REACHED,{"bufferEnd":h});else if(o.ended&&l.end(l.length-1)-u<2*c)return void w.info("[buffer-controller]: Cannot flush ".concat(a," back buffer while SourceBuffer is in ended state"));t.trigger(I.BUFFER_FLUSHING,{"startOffset":0,"endOffset":h,"type":a})}}}))}}}}},{"key":"updateMediaElementDuration","value":function updateMediaElementDuration(){if(this.details&&this.media&&this.mediaSource&&"open"===this.mediaSource.readyState){var t=this.details,r=this.hls,a=this.media,i=this.mediaSource,o=t.fragments[0].start+t.totalduration,l=a.duration,u=R(i.duration)?i.duration:0;t.live&&r.config.liveDurationInfinity?(w.log("[buffer-controller]: Media Source duration is set to Infinity"),i.duration=1/0,this.updateSeekableRange(t)):(o>u&&o>l||!R(l))&&(w.log("[buffer-controller]: Updating Media Source duration to ".concat(o.toFixed(3))),i.duration=o)}}},{"key":"updateSeekableRange","value":function updateSeekableRange(t){var r=this.mediaSource,a=t.fragments;if(a.length&&t.live&&null!=r&&r.setLiveSeekableRange){var i=Math.max(0,a[0].start),o=Math.max(i,i+t.totalduration);r.setLiveSeekableRange(i,o)}}},{"key":"checkPendingTracks","value":function checkPendingTracks(){var t=this.bufferCodecEventsExpected,r=this.operationQueue,a=this.pendingTracks,i=Object.keys(a).length;if(i&&!t||2===i){this.createSourceBuffers(a),this.pendingTracks={};var o=this.getSourceBufferTypes();if(o.length)this.hls.trigger(I.BUFFER_CREATED,{"tracks":this.tracks}),o.forEach((function(t){r.executeNext(t)}));else{var l=new Error("could not create source buffer for media codec(s)");this.hls.trigger(I.ERROR,{"type":D.MEDIA_ERROR,"details":b.BUFFER_INCOMPATIBLE_CODECS_ERROR,"fatal":!0,"error":l,"reason":l.message})}}}},{"key":"createSourceBuffers","value":function createSourceBuffers(t){var r=this.sourceBuffer,a=this.mediaSource;if(!a)throw Error("createSourceBuffers called when mediaSource was null");for(var i in t)if(!r[i]){var o=t[i];if(!o)throw Error("source buffer exists for track ".concat(i,", however track does not"));var l=o.levelCodec||o.codec,u="".concat(o.container,";codecs=").concat(l);w.log("[buffer-controller]: creating sourceBuffer(".concat(u,")"));try{var c=r[i]=a.addSourceBuffer(u),d=i;this.addBufferListener(d,"updatestart",this._onSBUpdateStart),this.addBufferListener(d,"updateend",this._onSBUpdateEnd),this.addBufferListener(d,"error",this._onSBUpdateError),this.tracks[i]={"buffer":c,"codec":l,"container":o.container,"levelCodec":o.levelCodec,"metadata":o.metadata,"id":o.id}}catch(t){w.error("[buffer-controller]: error while trying to add sourceBuffer: ".concat(t.message)),this.hls.trigger(I.ERROR,{"type":D.MEDIA_ERROR,"details":b.BUFFER_ADD_CODEC_ERROR,"fatal":!1,"error":t,"mimeType":u})}}}},{"key":"_onSBUpdateStart","value":function _onSBUpdateStart(t){this.operationQueue.current(t).onStart()}},{"key":"_onSBUpdateEnd","value":function _onSBUpdateEnd(t){var r=this.operationQueue;r.current(t).onComplete(),r.shiftAndExecuteNext(t)}},{"key":"_onSBUpdateError","value":function _onSBUpdateError(t,r){var a=new Error("".concat(t," SourceBuffer error"));w.error("[buffer-controller]: ".concat(a),r),this.hls.trigger(I.ERROR,{"type":D.MEDIA_ERROR,"details":b.BUFFER_APPENDING_ERROR,"error":a,"fatal":!1});var i=this.operationQueue.current(t);i&&i.onError(r)}},{"key":"removeExecutor","value":function removeExecutor(t,r,a){var i=this.media,o=this.mediaSource,l=this.operationQueue,u=this.sourceBuffer[t];if(!i||!o||!u)return w.warn("[buffer-controller]: Attempting to remove from the ".concat(t," SourceBuffer, but it does not exist")),void l.shiftAndExecuteNext(t);var c=R(i.duration)?i.duration:1/0,d=R(o.duration)?o.duration:1/0,h=Math.max(0,r),g=Math.min(a,c,d);g>h&&!u.ending?(u.ended=!1,w.log("[buffer-controller]: Removing [".concat(h,",").concat(g,"] from the ").concat(t," SourceBuffer")),u.remove(h,g)):l.shiftAndExecuteNext(t)}},{"key":"appendExecutor","value":function appendExecutor(t,r){var a=this.operationQueue,i=this.sourceBuffer[r];if(!i)return w.warn("[buffer-controller]: Attempting to append to the ".concat(r," SourceBuffer, but it does not exist")),void a.shiftAndExecuteNext(r);i.ended=!1,i.appendBuffer(t)}},{"key":"blockBuffers","value":function blockBuffers(t){var r=this,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.getSourceBufferTypes();if(!a.length)return w.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(t);var i=this.operationQueue,o=a.map((function(t){return i.appendBlocker(t)}));Promise.all(o).then((function(){t(),a.forEach((function(t){var a=r.sourceBuffer[t];null!=a&&a.updating||i.shiftAndExecuteNext(t)}))}))}},{"key":"getSourceBufferTypes","value":function getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}},{"key":"addBufferListener","value":function addBufferListener(t,r,a){var i=this.sourceBuffer[t];if(i){var o=a.bind(this,t);this.listeners[t].push({"event":r,"listener":o}),i.addEventListener(r,o)}}},{"key":"removeBufferListeners","value":function removeBufferListeners(t){var r=this.sourceBuffer[t];r&&this.listeners[t].forEach((function(t){r.removeEventListener(t.event,t.listener)}))}}]),BufferController}(),dr={"42":225,"92":233,"94":237,"95":243,"96":250,"123":231,"124":247,"125":209,"126":241,"127":9608,"128":174,"129":176,"130":189,"131":191,"132":8482,"133":162,"134":163,"135":9834,"136":224,"137":32,"138":232,"139":226,"140":234,"141":238,"142":244,"143":251,"144":193,"145":201,"146":211,"147":218,"148":220,"149":252,"150":8216,"151":161,"152":42,"153":8217,"154":9473,"155":169,"156":8480,"157":8226,"158":8220,"159":8221,"160":192,"161":194,"162":199,"163":200,"164":202,"165":203,"166":235,"167":206,"168":207,"169":239,"170":212,"171":217,"172":249,"173":219,"174":171,"175":187,"176":195,"177":227,"178":205,"179":204,"180":236,"181":210,"182":242,"183":213,"184":245,"185":123,"186":125,"187":92,"188":94,"189":95,"190":124,"191":8764,"192":196,"193":228,"194":214,"195":246,"196":223,"197":165,"198":164,"199":9475,"200":197,"201":229,"202":216,"203":248,"204":9487,"205":9491,"206":9495,"207":9499},hr=function getCharForByte(t){var r=t;return dr.hasOwnProperty(t)&&(r=dr[t]),String.fromCharCode(r)},fr=15,gr=100,vr={"17":1,"18":3,"21":5,"22":7,"23":9,"16":11,"19":12,"20":14},mr={"17":2,"18":4,"21":6,"22":8,"23":10,"19":13,"20":15},yr={"25":1,"26":3,"29":5,"30":7,"31":9,"24":11,"27":12,"28":14},pr={"25":2,"26":4,"29":6,"30":8,"31":10,"27":13,"28":15},Tr=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Er=function(){function CaptionsLogger(){(0,m.Z)(this,CaptionsLogger),this.time=null,this.verboseLevel=0}return(0,y.Z)(CaptionsLogger,[{"key":"log","value":function log(t,r){if(this.verboseLevel>=t){var a="function"==typeof r?r():r;w.log("".concat(this.time," [").concat(t,"] ").concat(a))}}}]),CaptionsLogger}(),kr=function numArrayToHexArray(t){for(var r=[],a=0;a<t.length;a++)r.push(t[a].toString(16));return r},Sr=function(){function PenState(t,r,a,i,o){(0,m.Z)(this,PenState),this.foreground=void 0,this.underline=void 0,this.italics=void 0,this.background=void 0,this.flash=void 0,this.foreground=t||"white",this.underline=r||!1,this.italics=a||!1,this.background=i||"black",this.flash=o||!1}return(0,y.Z)(PenState,[{"key":"reset","value":function reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}},{"key":"setStyles","value":function setStyles(t){for(var r=["foreground","underline","italics","background","flash"],a=0;a<r.length;a++){var i=r[a];t.hasOwnProperty(i)&&(this[i]=t[i])}}},{"key":"isDefault","value":function isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}},{"key":"equals","value":function equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}},{"key":"copy","value":function copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}},{"key":"toString","value":function toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}]),PenState}(),Lr=function(){function StyledUnicodeChar(t,r,a,i,o,l){(0,m.Z)(this,StyledUnicodeChar),this.uchar=void 0,this.penState=void 0,this.uchar=t||" ",this.penState=new Sr(r,a,i,o,l)}return(0,y.Z)(StyledUnicodeChar,[{"key":"reset","value":function reset(){this.uchar=" ",this.penState.reset()}},{"key":"setChar","value":function setChar(t,r){this.uchar=t,this.penState.copy(r)}},{"key":"setPenState","value":function setPenState(t){this.penState.copy(t)}},{"key":"equals","value":function equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}},{"key":"copy","value":function copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}},{"key":"isEmpty","value":function isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}]),StyledUnicodeChar}(),Ar=function(){function Row(t){(0,m.Z)(this,Row),this.chars=void 0,this.pos=void 0,this.currPenState=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chars=[];for(var r=0;r<gr;r++)this.chars.push(new Lr);this.logger=t,this.pos=0,this.currPenState=new Sr}return(0,y.Z)(Row,[{"key":"equals","value":function equals(t){for(var r=!0,a=0;a<gr;a++)if(!this.chars[a].equals(t.chars[a])){r=!1;break}return r}},{"key":"copy","value":function copy(t){for(var r=0;r<gr;r++)this.chars[r].copy(t.chars[r])}},{"key":"isEmpty","value":function isEmpty(){for(var t=!0,r=0;r<gr;r++)if(!this.chars[r].isEmpty()){t=!1;break}return t}},{"key":"setCursor","value":function setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>gr&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=gr)}},{"key":"moveCursor","value":function moveCursor(t){var r=this.pos+t;if(t>1)for(var a=this.pos+1;a<r+1;a++)this.chars[a].setPenState(this.currPenState);this.setCursor(r)}},{"key":"backSpace","value":function backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}},{"key":"insertChar","value":function insertChar(t){var r=this;t>=144&&this.backSpace();var a=hr(t);this.pos>=gr?this.logger.log(0,(function(){return"Cannot insert "+t.toString(16)+" ("+a+") at position "+r.pos+". Skipping it!"})):(this.chars[this.pos].setChar(a,this.currPenState),this.moveCursor(1))}},{"key":"clearFromPos","value":function clearFromPos(t){var r;for(r=t;r<gr;r++)this.chars[r].reset()}},{"key":"clear","value":function clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}},{"key":"clearToEndOfRow","value":function clearToEndOfRow(){this.clearFromPos(this.pos)}},{"key":"getTextString","value":function getTextString(){for(var t=[],r=!0,a=0;a<gr;a++){var i=this.chars[a].uchar;" "!==i&&(r=!1),t.push(i)}return r?"":t.join("")}},{"key":"setPenStyles","value":function setPenStyles(t){this.currPenState.setStyles(t),this.chars[this.pos].setPenState(this.currPenState)}}]),Row}(),Rr=function(){function CaptionScreen(t){(0,m.Z)(this,CaptionScreen),this.rows=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(var r=0;r<fr;r++)this.rows.push(new Ar(t));this.logger=t,this.currRow=fr-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}return(0,y.Z)(CaptionScreen,[{"key":"reset","value":function reset(){for(var t=0;t<fr;t++)this.rows[t].clear();this.currRow=fr-1}},{"key":"equals","value":function equals(t){for(var r=!0,a=0;a<fr;a++)if(!this.rows[a].equals(t.rows[a])){r=!1;break}return r}},{"key":"copy","value":function copy(t){for(var r=0;r<fr;r++)this.rows[r].copy(t.rows[r])}},{"key":"isEmpty","value":function isEmpty(){for(var t=!0,r=0;r<fr;r++)if(!this.rows[r].isEmpty()){t=!1;break}return t}},{"key":"backSpace","value":function backSpace(){this.rows[this.currRow].backSpace()}},{"key":"clearToEndOfRow","value":function clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}},{"key":"insertChar","value":function insertChar(t){this.rows[this.currRow].insertChar(t)}},{"key":"setPen","value":function setPen(t){this.rows[this.currRow].setPenStyles(t)}},{"key":"moveCursor","value":function moveCursor(t){this.rows[this.currRow].moveCursor(t)}},{"key":"setCursor","value":function setCursor(t){this.logger.log(2,"setCursor: "+t),this.rows[this.currRow].setCursor(t)}},{"key":"setPAC","value":function setPAC(t){this.logger.log(2,(function(){return"pacData = "+JSON.stringify(t)}));var r=t.row-1;if(this.nrRollUpRows&&r<this.nrRollUpRows-1&&(r=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==r){for(var a=0;a<fr;a++)this.rows[a].clear();var i=this.currRow+1-this.nrRollUpRows,o=this.lastOutputScreen;if(o){var l=o.rows[i].cueStartTime,u=this.logger.time;if(l&&null!==u&&l<u)for(var c=0;c<this.nrRollUpRows;c++)this.rows[r-this.nrRollUpRows+c+1].copy(o.rows[i+c])}}this.currRow=r;var d=this.rows[this.currRow];if(null!==t.indent){var h=t.indent,g=Math.max(h-1,0);d.setCursor(t.indent),t.color=d.chars[g].penState.foreground}var v={"foreground":t.color,"underline":t.underline,"italics":t.italics,"background":"black","flash":!1};this.setPen(v)}},{"key":"setBkgData","value":function setBkgData(t){this.logger.log(2,(function(){return"bkgData = "+JSON.stringify(t)})),this.backSpace(),this.setPen(t),this.insertChar(32)}},{"key":"setRollUpRows","value":function setRollUpRows(t){this.nrRollUpRows=t}},{"key":"rollUp","value":function rollUp(){var t=this;if(null!==this.nrRollUpRows){this.logger.log(1,(function(){return t.getDisplayText()}));var r=this.currRow+1-this.nrRollUpRows,a=this.rows.splice(r,1)[0];a.clear(),this.rows.splice(this.currRow,0,a),this.logger.log(2,"Rolling up")}else this.logger.log(3,"roll_up but nrRollUpRows not set yet")}},{"key":"getDisplayText","value":function getDisplayText(t){t=t||!1;for(var r=[],a="",i=-1,o=0;o<fr;o++){var l=this.rows[o].getTextString();l&&(i=o+1,t?r.push("Row "+i+": '"+l+"'"):r.push(l.trim()))}return r.length>0&&(a=t?"["+r.join(" | ")+"]":r.join("\n")),a}},{"key":"getTextAndFormat","value":function getTextAndFormat(){return this.rows}}]),CaptionScreen}(),Ir=function(){function Cea608Channel(t,r,a){(0,m.Z)(this,Cea608Channel),this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new Rr(a),this.nonDisplayedMemory=new Rr(a),this.lastOutputScreen=new Rr(a),this.currRollUpRow=this.displayedMemory.rows[fr-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=a}return(0,y.Z)(Cea608Channel,[{"key":"reset","value":function reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[fr-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}},{"key":"getHandler","value":function getHandler(){return this.outputFilter}},{"key":"setHandler","value":function setHandler(t){this.outputFilter=t}},{"key":"setPAC","value":function setPAC(t){this.writeScreen.setPAC(t)}},{"key":"setBkgData","value":function setBkgData(t){this.writeScreen.setBkgData(t)}},{"key":"setMode","value":function setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,(function(){return"MODE="+t})),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}},{"key":"insertChars","value":function insertChars(t){for(var r=this,a=0;a<t.length;a++)this.writeScreen.insertChar(t[a]);var i=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(function(){return i+": "+r.writeScreen.getDisplayText(!0)})),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(function(){return"DISPLAYED: "+r.displayedMemory.getDisplayText(!0)})),this.outputDataUpdate())}},{"key":"ccRCL","value":function ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}},{"key":"ccBS","value":function ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}},{"key":"ccAOF","value":function ccAOF(){}},{"key":"ccAON","value":function ccAON(){}},{"key":"ccDER","value":function ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}},{"key":"ccRU","value":function ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}},{"key":"ccFON","value":function ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({"flash":!0})}},{"key":"ccRDC","value":function ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}},{"key":"ccTR","value":function ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}},{"key":"ccRTD","value":function ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}},{"key":"ccEDM","value":function ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}},{"key":"ccCR","value":function ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}},{"key":"ccENM","value":function ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}},{"key":"ccEOC","value":function ccEOC(){var t=this;if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var r=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=r,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(function(){return"DISP: "+t.displayedMemory.getDisplayText()}))}this.outputDataUpdate(!0)}},{"key":"ccTO","value":function ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}},{"key":"ccMIDROW","value":function ccMIDROW(t){var r={"flash":!1};if(r.underline=t%2==1,r.italics=t>=46,r.italics)r.foreground="white";else{var a=Math.floor(t/2)-16;r.foreground=["white","green","blue","cyan","red","yellow","magenta"][a]}this.logger.log(2,"MIDROW: "+JSON.stringify(r)),this.writeScreen.setPen(r)}},{"key":"outputDataUpdate","value":function outputDataUpdate(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],r=this.logger.time;null!==r&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,r,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:r):this.cueStartTime=r,this.lastOutputScreen.copy(this.displayedMemory))}},{"key":"cueSplitAtTime","value":function cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}]),Cea608Channel}(),Dr=function(){function Cea608Parser(t,r,a){(0,m.Z)(this,Cea608Parser),this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;var i=new Er;this.channels=[null,new Ir(t,r,i),new Ir(t+1,a,i)],this.cmdHistory={"a":null,"b":null},this.logger=i}return(0,y.Z)(Cea608Parser,[{"key":"getHandler","value":function getHandler(t){return this.channels[t].getHandler()}},{"key":"setHandler","value":function setHandler(t,r){this.channels[t].setHandler(r)}},{"key":"addData","value":function addData(t,r){var a,i,o,l=!1;this.logger.time=t;for(var u=0;u<r.length;u+=2)if(i=127&r[u],o=127&r[u+1],0!==i||0!==o){if(this.logger.log(3,"["+kr([r[u],r[u+1]])+"] -> ("+kr([i,o])+")"),(a=this.parseCmd(i,o))||(a=this.parseMidrow(i,o)),a||(a=this.parsePAC(i,o)),a||(a=this.parseBackgroundAttributes(i,o)),!a&&(l=this.parseChars(i,o))){var c=this.currentChannel;if(c&&c>0)this.channels[c].insertChars(l);else this.logger.log(2,"No channel found yet. TEXT-MODE?")}a||l||this.logger.log(2,"Couldn't parse cleaned data "+kr([i,o])+" orig: "+kr([r[u],r[u+1]]))}}},{"key":"parseCmd","value":function parseCmd(t,r){var a=this.cmdHistory;if(!((20===t||28===t||21===t||29===t)&&r>=32&&r<=47)&&!((23===t||31===t)&&r>=33&&r<=35))return!1;if(hasCmdRepeated(t,r,a))return setLastCmd(null,null,a),this.logger.log(3,"Repeated command ("+kr([t,r])+") is dropped"),!0;var i=20===t||21===t||23===t?1:2,o=this.channels[i];return 20===t||21===t||28===t||29===t?32===r?o.ccRCL():33===r?o.ccBS():34===r?o.ccAOF():35===r?o.ccAON():36===r?o.ccDER():37===r?o.ccRU(2):38===r?o.ccRU(3):39===r?o.ccRU(4):40===r?o.ccFON():41===r?o.ccRDC():42===r?o.ccTR():43===r?o.ccRTD():44===r?o.ccEDM():45===r?o.ccCR():46===r?o.ccENM():47===r&&o.ccEOC():o.ccTO(r-32),setLastCmd(t,r,a),this.currentChannel=i,!0}},{"key":"parseMidrow","value":function parseMidrow(t,r){var a=0;if((17===t||25===t)&&r>=32&&r<=47){if((a=17===t?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var i=this.channels[a];return!!i&&(i.ccMIDROW(r),this.logger.log(3,"MIDROW ("+kr([t,r])+")"),!0)}return!1}},{"key":"parsePAC","value":function parsePAC(t,r){var a,i=this.cmdHistory;if(!((t>=17&&t<=23||t>=25&&t<=31)&&r>=64&&r<=127)&&!((16===t||24===t)&&r>=64&&r<=95))return!1;if(hasCmdRepeated(t,r,i))return setLastCmd(null,null,i),!0;var o=t<=23?1:2;a=r>=64&&r<=95?1===o?vr[t]:yr[t]:1===o?mr[t]:pr[t];var l=this.channels[o];return!!l&&(l.setPAC(this.interpretPAC(a,r)),setLastCmd(t,r,i),this.currentChannel=o,!0)}},{"key":"interpretPAC","value":function interpretPAC(t,r){var a,i={"color":null,"italics":!1,"indent":null,"underline":!1,"row":t};return a=r>95?r-96:r-64,i.underline=1==(1&a),a<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(a/2)]:a<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((a-16)/2),i}},{"key":"parseChars","value":function parseChars(t,r){var a,i,o=null,l=null;(t>=25?(a=2,l=t-8):(a=1,l=t),l>=17&&l<=19)?(i=17===l?r+80:18===l?r+112:r+144,this.logger.log(2,"Special char '"+hr(i)+"' in channel "+a),o=[i]):t>=32&&t<=127&&(o=0===r?[t]:[t,r]);if(o){var u=kr(o);this.logger.log(3,"Char codes = "+u.join(",")),setLastCmd(t,r,this.cmdHistory)}return o}},{"key":"parseBackgroundAttributes","value":function parseBackgroundAttributes(t,r){var a;if(!((16===t||24===t)&&r>=32&&r<=47)&&!((23===t||31===t)&&r>=45&&r<=47))return!1;var i={};16===t||24===t?(a=Math.floor((r-32)/2),i.background=Tr[a],r%2==1&&(i.background=i.background+"_semi")):45===r?i.background="transparent":(i.foreground="black",47===r&&(i.underline=!0));var o=t<=23?1:2;return this.channels[o].setBkgData(i),setLastCmd(t,r,this.cmdHistory),!0}},{"key":"reset","value":function reset(){for(var t=0;t<Object.keys(this.channels).length;t++){var r=this.channels[t];r&&r.reset()}this.cmdHistory={"a":null,"b":null}}},{"key":"cueSplitAtTime","value":function cueSplitAtTime(t){for(var r=0;r<this.channels.length;r++){var a=this.channels[r];a&&a.cueSplitAtTime(t)}}}]),Cea608Parser}();function setLastCmd(t,r,a){a.a=t,a.b=r}function hasCmdRepeated(t,r,a){return a.a===t&&a.b===r}var br=function(){function OutputFilter(t,r){(0,m.Z)(this,OutputFilter),this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=r}return(0,y.Z)(OutputFilter,[{"key":"dispatchCue","value":function dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}},{"key":"newCue","value":function newCue(t,r,a){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=r,this.screen=a,this.timelineController.createCaptionsTrack(this.trackName)}},{"key":"reset","value":function reset(){this.cueRanges=[],this.startTime=null}}]),OutputFilter}(),Cr=function(){if("undefined"!=typeof self&&self.VTTCue)return self.VTTCue;var t=["","lr","rl"],r=["start","middle","end","left","right"];function isAllowedValue(t,r){if("string"!=typeof r)return!1;if(!Array.isArray(t))return!1;var a=r.toLowerCase();return!!~t.indexOf(a)&&a}function findAlignSetting(t){return isAllowedValue(r,t)}function extend(t){for(var r=arguments.length,a=new Array(r>1?r-1:0),i=1;i<r;i++)a[i-1]=arguments[i];for(var o=1;o<arguments.length;o++){var l=arguments[o];for(var u in l)t[u]=l[u]}return t}function VTTCue(r,a,i){var o=this,l={"enumerable":!0};o.hasBeenReset=!1;var u="",c=!1,d=r,h=a,g=i,v=null,m="",y=!0,p="auto",T="start",E=50,k="middle",S=50,L="middle";Object.defineProperty(o,"id",extend({},l,{"get":function get(){return u},"set":function set(t){u=""+t}})),Object.defineProperty(o,"pauseOnExit",extend({},l,{"get":function get(){return c},"set":function set(t){c=!!t}})),Object.defineProperty(o,"startTime",extend({},l,{"get":function get(){return d},"set":function set(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");d=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",extend({},l,{"get":function get(){return h},"set":function set(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");h=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",extend({},l,{"get":function get(){return g},"set":function set(t){g=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",extend({},l,{"get":function get(){return v},"set":function set(t){v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",extend({},l,{"get":function get(){return m},"set":function set(r){var a=function findDirectionSetting(r){return isAllowedValue(t,r)}(r);if(!1===a)throw new SyntaxError("An invalid or illegal string was specified.");m=a,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",extend({},l,{"get":function get(){return y},"set":function set(t){y=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",extend({},l,{"get":function get(){return p},"set":function set(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");p=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",extend({},l,{"get":function get(){return T},"set":function set(t){var r=findAlignSetting(t);if(!r)throw new SyntaxError("An invalid or illegal string was specified.");T=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",extend({},l,{"get":function get(){return E},"set":function set(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",extend({},l,{"get":function get(){return k},"set":function set(t){var r=findAlignSetting(t);if(!r)throw new SyntaxError("An invalid or illegal string was specified.");k=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",extend({},l,{"get":function get(){return S},"set":function set(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",extend({},l,{"get":function get(){return L},"set":function set(t){var r=findAlignSetting(t);if(!r)throw new SyntaxError("An invalid or illegal string was specified.");L=r,this.hasBeenReset=!0}})),o.displayState=void 0}return VTTCue.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},VTTCue}(),Pr=function(){function StringDecoder(){(0,m.Z)(this,StringDecoder)}return(0,y.Z)(StringDecoder,[{"key":"decode","value":function decode(t,r){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}]),StringDecoder}();function parseTimeStamp(t){function computeSeconds(t,r,a,i){return 3600*(0|t)+60*(0|r)+(0|a)+parseFloat(i||0)}var r=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?computeSeconds(r[2],r[3],0,r[4]):computeSeconds(r[1],r[2],r[3],r[4]):null}var _r=function(){function Settings(){(0,m.Z)(this,Settings),this.values=Object.create(null)}return(0,y.Z)(Settings,[{"key":"set","value":function set(t,r){this.get(t)||""===r||(this.values[t]=r)}},{"key":"get","value":function get(t,r,a){return a?this.has(t)?this.values[t]:r[a]:this.has(t)?this.values[t]:r}},{"key":"has","value":function has(t){return t in this.values}},{"key":"alt","value":function alt(t,r,a){for(var i=0;i<a.length;++i)if(r===a[i]){this.set(t,r);break}}},{"key":"integer","value":function integer(t,r){/^-?\d+$/.test(r)&&this.set(t,parseInt(r,10))}},{"key":"percent","value":function percent(t,r){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(r)){var percent=parseFloat(r);if(percent>=0&&percent<=100)return this.set(t,percent),!0}return!1}}]),Settings}();function parseOptions(t,r,a,i){var o=i?t.split(i):[t];for(var l in o)if("string"==typeof o[l]){var u=o[l].split(a);if(2===u.length)r(u[0],u[1])}}var wr=new Cr(0,0,""),Mr="middle"===wr.align?"middle":"center";function parseCue(t,r,a){var i=t;function consumeTimeStamp(){var r=parseTimeStamp(t);if(null===r)throw new Error("Malformed timestamp: "+i);return t=t.replace(/^[^\sa-zA-Z-]+/,""),r}function skipWhitespace(){t=t.replace(/^\s+/,"")}if(skipWhitespace(),r.startTime=consumeTimeStamp(),skipWhitespace(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);t=t.slice(3),skipWhitespace(),r.endTime=consumeTimeStamp(),skipWhitespace(),function consumeCueSettings(t,r){var i=new _r;parseOptions(t,(function(t,r){var o;switch(t){case"region":for(var l=a.length-1;l>=0;l--)if(a[l].id===r){i.set(t,a[l].region);break}break;case"vertical":i.alt(t,r,["rl","lr"]);break;case"line":o=r.split(","),i.integer(t,o[0]),i.percent(t,o[0])&&i.set("snapToLines",!1),i.alt(t,o[0],["auto"]),2===o.length&&i.alt("lineAlign",o[1],["start",Mr,"end"]);break;case"position":o=r.split(","),i.percent(t,o[0]),2===o.length&&i.alt("positionAlign",o[1],["start",Mr,"end","line-left","line-right","auto"]);break;case"size":i.percent(t,r);break;case"align":i.alt(t,r,["start",Mr,"end","left","right"])}}),/:/,/\s/),r.region=i.get("region",null),r.vertical=i.get("vertical","");var o=i.get("line","auto");"auto"===o&&-1===wr.line&&(o=-1),r.line=o,r.lineAlign=i.get("lineAlign","start"),r.snapToLines=i.get("snapToLines",!0),r.size=i.get("size",100),r.align=i.get("align",Mr);var l=i.get("position","auto");"auto"===l&&50===wr.position&&(l="start"===r.align||"left"===r.align?0:"end"===r.align||"right"===r.align?100:50),r.position=l}(t,r)}function fixLineBreaks(t){return t.replace(/<br(?: \/)?>/gi,"\n")}var xr=function(){function VTTParser(){(0,m.Z)(this,VTTParser),this.state="INITIAL",this.buffer="",this.decoder=new Pr,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}return(0,y.Z)(VTTParser,[{"key":"parse","value":function parse(t){var r=this;function collectNextLine(){var t=r.buffer,a=0;for(t=fixLineBreaks(t);a<t.length&&"\r"!==t[a]&&"\n"!==t[a];)++a;var i=t.slice(0,a);return"\r"===t[a]&&++a,"\n"===t[a]&&++a,r.buffer=t.slice(a),i}t&&(r.buffer+=r.decoder.decode(t,{"stream":!0}));try{var a="";if("INITIAL"===r.state){if(!/\r\n|\n/.test(r.buffer))return this;var i=(a=collectNextLine()).match(/^()?WEBVTT([ \t].*)?$/);if(null==i||!i[0])throw new Error("Malformed WebVTT signature.");r.state="HEADER"}for(var o=!1;r.buffer;){if(!/\r\n|\n/.test(r.buffer))return this;switch(o?o=!1:a=collectNextLine(),r.state){case"HEADER":/:/.test(a)?parseOptions(a,(function(t,r){}),/:/):a||(r.state="ID");continue;case"NOTE":a||(r.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(a)){r.state="NOTE";break}if(!a)continue;if(r.cue=new Cr(0,0,""),r.state="CUE",-1===a.indexOf("--\x3e")){r.cue.id=a;continue}case"CUE":if(!r.cue){r.state="BADCUE";continue}try{parseCue(a,r.cue,r.regionList)}catch(t){r.cue=null,r.state="BADCUE";continue}r.state="CUETEXT";continue;case"CUETEXT":var l=-1!==a.indexOf("--\x3e");if(!a||l&&(o=!0)){r.oncue&&r.cue&&r.oncue(r.cue),r.cue=null,r.state="ID";continue}if(null===r.cue)continue;r.cue.text&&(r.cue.text+="\n"),r.cue.text+=a;continue;case"BADCUE":a||(r.state="ID")}}}catch(t){"CUETEXT"===r.state&&r.cue&&r.oncue&&r.oncue(r.cue),r.cue=null,r.state="INITIAL"===r.state?"BADWEBVTT":"BADCUE"}return this}},{"key":"flush","value":function flush(){var t=this;try{if((t.cue||"HEADER"===t.state)&&(t.buffer+="\n\n",t.parse()),"INITIAL"===t.state||"BADWEBVTT"===t.state)throw new Error("Malformed WebVTT signature.")}catch(r){t.onparsingerror&&t.onparsingerror(r)}return t.onflush&&t.onflush(),this}}]),VTTParser}(),Fr=/\r\n|\n\r|\n|\r/g,Or=function startsWith(t,r){var a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return t.slice(a,a+r.length)===r},Nr=function cueString2millis(t){var r=parseInt(t.slice(-3)),a=parseInt(t.slice(-6,-4)),i=parseInt(t.slice(-9,-7)),o=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(R(r)&&R(a)&&R(i)&&R(o)))throw Error("Malformed X-TIMESTAMP-MAP: Local:".concat(t));return r+=1e3*a,r+=6e4*i,r+=36e5*o},Ur=function hash(t){for(var r=5381,a=t.length;a;)r=33*r^t.charCodeAt(--a);return(r>>>0).toString()};function generateCueId(t,r,a){return Ur(t.toString())+Ur(r.toString())+Ur(a)}var Br=function calculateOffset(t,r,a){var i=t[r],o=t[i.prevCC];if(!o||!o.new&&i.new)return t.ccOffset=t.presentationOffset=i.start,void(i.new=!1);for(;null!=(l=o)&&l.new;){var l;t.ccOffset+=i.start-o.start,i.new=!1,o=t[(i=o).prevCC]}t.presentationOffset=a};function parseWebVTT(t,r,a,i,o,l,u){var c,d=new xr,h=le(new Uint8Array(t)).trim().replace(Fr,"\n").split("\n"),g=[],v=function toMpegTsClockFromTimescale(t){return toTimescaleFromBase(t,Mt,1/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1))}(r.baseTime,r.timescale),m="00:00.000",y=0,p=0,T=!0;d.oncue=function(t){var r=a[i],l=a.ccOffset,u=(y-v)/9e4;null!=r&&r.new&&(void 0!==p?l=a.ccOffset=r.start:Br(a,i,u)),u&&(l=u-a.presentationOffset);var c=t.endTime-t.startTime,d=normalizePts(9e4*(t.startTime+l-p),9e4*o)/9e4;t.startTime=Math.max(d,0),t.endTime=Math.max(d+c,0);var h=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(h)),t.id||(t.id=generateCueId(t.startTime,t.endTime,h)),t.endTime>0&&g.push(t)},d.onparsingerror=function(t){c=t},d.onflush=function(){c?u(c):l(g)},h.forEach((function(t){if(T){if(Or(t,"X-TIMESTAMP-MAP=")){T=!1,t.slice(16).split(",").forEach((function(t){Or(t,"LOCAL:")?m=t.slice(6):Or(t,"MPEGTS:")&&(y=parseInt(t.slice(7)))}));try{p=Nr(m)/1e3}catch(t){c=t}return}""===t&&(T=!1)}d.parse(t+"\n")})),d.flush()}var Gr="stpp.ttml.im1t",Kr=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Hr=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Vr={"left":"start","center":"center","right":"end","start":"start","end":"end"};function parseIMSC1(t,r,a,i){var o=findBox(new Uint8Array(t),["mdat"]);if(0!==o.length){var l=o.map((function(t){return le(t)})),u=function toTimescaleFromScale(t,r){return toTimescaleFromBase(t,r,1/(arguments.length>2&&void 0!==arguments[2]?arguments[2]:1),arguments.length>3&&void 0!==arguments[3]&&arguments[3])}(r.baseTime,1,r.timescale);try{l.forEach((function(t){return a(function parseTTML(t,r){var a=(new DOMParser).parseFromString(t,"text/xml"),i=a.getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");var o={"frameRate":30,"subFrameRate":1,"frameRateMultiplier":0,"tickRate":0},l=Object.keys(o).reduce((function(t,r){return t[r]=i.getAttribute("ttp:".concat(r))||o[r],t}),{}),u="preserve"!==i.getAttribute("xml:space"),c=collectionToDictionary(getElementCollection(i,"styling","style")),d=collectionToDictionary(getElementCollection(i,"layout","region")),h=getElementCollection(i,"body","[begin]");return[].map.call(h,(function(t){var a=getTextContent(t,u);if(!a||!t.hasAttribute("begin"))return null;var i=parseTtmlTime(t.getAttribute("begin"),l),o=parseTtmlTime(t.getAttribute("dur"),l),h=parseTtmlTime(t.getAttribute("end"),l);if(null===i)throw timestampParsingError(t);if(null===h){if(null===o)throw timestampParsingError(t);h=i+o}var g=new Cr(i-r,h-r,a);g.id=generateCueId(g.startTime,g.endTime,g.text);var v=function getTtmlStyles(t,r,a){var i="http://www.w3.org/ns/ttml#styling",o=null,l=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],u=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;u&&a.hasOwnProperty(u)&&(o=a[u]);return l.reduce((function(a,l){var u=getAttributeNS(r,i,l)||getAttributeNS(t,i,l)||getAttributeNS(o,i,l);return u&&(a[l]=u),a}),{})}(d[t.getAttribute("region")],c[t.getAttribute("style")],c),m=v.textAlign;if(m){var y=Vr[m];y&&(g.lineAlign=y),g.align=m}return _extends(g,v),g})).filter((function(t){return null!==t}))}(t,u))}))}catch(t){i(t)}}else i(new Error("Could not parse IMSC1 mdat"))}function getElementCollection(t,r,a){var i=t.getElementsByTagName(r)[0];return i?[].slice.call(i.querySelectorAll(a)):[]}function collectionToDictionary(t){return t.reduce((function(t,r){var a=r.getAttribute("xml:id");return a&&(t[a]=r),t}),{})}function getTextContent(t,r){return[].slice.call(t.childNodes).reduce((function(t,a,i){var o;return"br"===a.nodeName&&i?t+"\n":null!=(o=a.childNodes)&&o.length?getTextContent(a,r):r?t+a.textContent.trim().replace(/\s+/g," "):t+a.textContent}),"")}function getAttributeNS(t,r,a){return t&&t.hasAttributeNS(r,a)?t.getAttributeNS(r,a):null}function timestampParsingError(t){return new Error("Could not parse ttml timestamp ".concat(t))}function parseTtmlTime(t,r){if(!t)return null;var a=parseTimeStamp(t);return null===a&&(Kr.test(t)?a=function parseHoursMinutesSecondsFrames(t,r){var a=Kr.exec(t),i=(0|a[4])+(0|a[5])/r.subFrameRate;return 3600*(0|a[1])+60*(0|a[2])+(0|a[3])+i/r.frameRate}(t,r):Hr.test(t)&&(a=function parseTimeUnits(t,r){var a=Hr.exec(t),i=Number(a[1]);switch(a[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/r.frameRate;case"t":return i/r.tickRate}return i}(t,r))),a}var Wr=function(){function TimelineController(t){if((0,m.Z)(this,TimelineController),this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={"ccOffset":0,"presentationOffset":0,"0":{"start":0,"prevCC":-1,"new":!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={"textTrack1":{"label":this.config.captionsTextTrack1Label,"languageCode":this.config.captionsTextTrack1LanguageCode},"textTrack2":{"label":this.config.captionsTextTrack2Label,"languageCode":this.config.captionsTextTrack2LanguageCode},"textTrack3":{"label":this.config.captionsTextTrack3Label,"languageCode":this.config.captionsTextTrack3LanguageCode},"textTrack4":{"label":this.config.captionsTextTrack4Label,"languageCode":this.config.captionsTextTrack4LanguageCode}},this.config.enableCEA708Captions){var r=new br(this,"textTrack1"),a=new br(this,"textTrack2"),i=new br(this,"textTrack3"),o=new br(this,"textTrack4");this.cea608Parser1=new Dr(1,r,a),this.cea608Parser2=new Dr(3,i,o)}t.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(I.FRAG_LOADING,this.onFragLoading,this),t.on(I.FRAG_LOADED,this.onFragLoaded,this),t.on(I.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(I.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(I.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(I.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this)}return(0,y.Z)(TimelineController,[{"key":"destroy","value":function destroy(){var t=this.hls;t.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(I.FRAG_LOADING,this.onFragLoading,this),t.off(I.FRAG_LOADED,this.onFragLoaded,this),t.off(I.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(I.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(I.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(I.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null}},{"key":"addCues","value":function addCues(t,r,a,i,o){for(var l,u,c,d,h=!1,g=o.length;g--;){var v=o[g],m=(l=v[0],u=v[1],c=r,d=a,Math.min(u,d)-Math.max(l,c));if(m>=0&&(v[0]=Math.min(v[0],r),v[1]=Math.max(v[1],a),h=!0,m/(a-r)>.5))return}if(h||o.push([r,a]),this.config.renderTextTracksNatively){var y=this.captionsTracks[t];this.Cues.newCue(y,r,a,i)}else{var p=this.Cues.newCue(null,r,a,i);this.hls.trigger(I.CUES_PARSED,{"type":"captions","cues":p,"track":t})}}},{"key":"onInitPtsFound","value":function onInitPtsFound(t,r){var a=this,i=r.frag,o=r.id,l=r.initPTS,u=r.timescale,c=this.unparsedVttFrags;"main"===o&&(this.initPTS[i.cc]={"baseTime":l,"timescale":u}),c.length&&(this.unparsedVttFrags=[],c.forEach((function(t){a.onFragLoaded(I.FRAG_LOADED,t)})))}},{"key":"getExistingTrack","value":function getExistingTrack(t){var r=this.media;if(r)for(var a=0;a<r.textTracks.length;a++){var i=r.textTracks[a];if(i[t])return i}return null}},{"key":"createCaptionsTrack","value":function createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}},{"key":"createNativeTrack","value":function createNativeTrack(t){if(!this.captionsTracks[t]){var r=this.captionsProperties,a=this.captionsTracks,i=this.media,o=r[t],l=o.label,u=o.languageCode,c=this.getExistingTrack(t);if(c)a[t]=c,clearCurrentCues(a[t]),sendAddTrackEvent(a[t],i);else{var d=this.createTextTrack("captions",l,u);d&&(d[t]=!0,a[t]=d)}}}},{"key":"createNonNativeTrack","value":function createNonNativeTrack(t){if(!this.nonNativeCaptionsTracks[t]){var r=this.captionsProperties[t];if(r){var a={"_id":t,"label":r.label,"kind":"captions","default":!!r.media&&!!r.media.default,"closedCaptions":r.media};this.nonNativeCaptionsTracks[t]=a,this.hls.trigger(I.NON_NATIVE_TEXT_TRACKS_FOUND,{"tracks":[a]})}}}},{"key":"createTextTrack","value":function createTextTrack(t,r,a){var i=this.media;if(i)return i.addTextTrack(t,r,a)}},{"key":"onMediaAttaching","value":function onMediaAttaching(t,r){this.media=r.media,this._cleanTracks()}},{"key":"onMediaDetaching","value":function onMediaDetaching(){var t=this.captionsTracks;Object.keys(t).forEach((function(r){clearCurrentCues(t[r]),delete t[r]})),this.nonNativeCaptionsTracks={}}},{"key":"onManifestLoading","value":function onManifestLoading(){this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={"ccOffset":0,"presentationOffset":0,"0":{"start":0,"prevCC":-1,"new":!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=this.unparsedVttFrags||[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}},{"key":"_cleanTracks","value":function _cleanTracks(){var t=this.media;if(t){var r=t.textTracks;if(r)for(var a=0;a<r.length;a++)clearCurrentCues(r[a])}}},{"key":"onSubtitleTracksUpdated","value":function onSubtitleTracksUpdated(t,r){var a=this,i=r.subtitleTracks||[],o=i.some((function(t){return t.textCodec===Gr}));if(this.config.enableWebVTT||o&&this.config.enableIMSC1){if(subtitleOptionsIdentical(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){var l=this.media?this.media.textTracks:null;this.tracks.forEach((function(t,r){var i;if(l&&r<l.length){for(var o=null,u=0;u<l.length;u++)if(canReuseVttTextTrack(l[u],t)){o=l[u];break}o&&(i=o)}if(i)clearCurrentCues(i);else{var c=a._captionsOrSubtitlesFromCharacteristics(t);(i=a.createTextTrack(c,t.name,t.lang))&&(i.mode="disabled")}i&&(i.groupId=t.groupId,a.textTracks.push(i))}))}else if(this.tracks.length){var u=this.tracks.map((function(t){return{"label":t.name,"kind":t.type.toLowerCase(),"default":t.default,"subtitleTrack":t}}));this.hls.trigger(I.NON_NATIVE_TEXT_TRACKS_FOUND,{"tracks":u})}}}},{"key":"_captionsOrSubtitlesFromCharacteristics","value":function _captionsOrSubtitlesFromCharacteristics(t){if(t.attrs.CHARACTERISTICS){var r=/transcribes-spoken-dialog/gi.test(t.attrs.CHARACTERISTICS),a=/describes-music-and-sound/gi.test(t.attrs.CHARACTERISTICS);if(r&&a)return"captions"}return"subtitles"}},{"key":"onManifestLoaded","value":function onManifestLoaded(t,r){var a=this;this.config.enableCEA708Captions&&r.captions&&r.captions.forEach((function(t){var r=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(r){var i="textTrack".concat(r[1]),o=a.captionsProperties[i];o&&(o.label=t.name,t.lang&&(o.languageCode=t.lang),o.media=t)}}))}},{"key":"closedCaptionsForLevel","value":function closedCaptionsForLevel(t){var r=this.hls.levels[t.level];return null==r?void 0:r.attrs["CLOSED-CAPTIONS"]}},{"key":"onFragLoading","value":function onFragLoading(t,r){var a=this.cea608Parser1,i=this.cea608Parser2,o=this.lastSn,l=this.lastPartIndex;if(this.enabled&&a&&i&&r.frag.type===Re.MAIN){var u,c,d=r.frag.sn,h=null!=(u=null==r||null==(c=r.part)?void 0:c.index)?u:-1;d===o+1||d===o&&h===l+1||(a.reset(),i.reset()),this.lastSn=d,this.lastPartIndex=h}}},{"key":"onFragLoaded","value":function onFragLoaded(t,r){var a=r.frag,i=r.payload,o=this.initPTS,l=this.unparsedVttFrags;if(a.type===Re.SUBTITLE)if(i.byteLength){if(!o[a.cc])return l.push(r),void(o.length&&this.hls.trigger(I.SUBTITLE_FRAG_PROCESSED,{"success":!1,"frag":a,"error":new Error("Missing initial subtitle PTS")}));var u=a.decryptdata,c="stats"in r;if(null==u||!u.encrypted||c){var d=this.tracks[a.level],h=this.vttCCs;h[a.cc]||(h[a.cc]={"start":a.start,"prevCC":this.prevCC,"new":!0},this.prevCC=a.cc),d&&d.textCodec===Gr?this._parseIMSC1(a,i):this._parseVTTs(a,i,h)}}else this.hls.trigger(I.SUBTITLE_FRAG_PROCESSED,{"success":!1,"frag":a,"error":new Error("Empty subtitle payload")})}},{"key":"_parseIMSC1","value":function _parseIMSC1(t,r){var a=this,i=this.hls;parseIMSC1(r,this.initPTS[t.cc],(function(r){a._appendCues(r,t.level),i.trigger(I.SUBTITLE_FRAG_PROCESSED,{"success":!0,"frag":t})}),(function(r){w.log("Failed to parse IMSC1: ".concat(r)),i.trigger(I.SUBTITLE_FRAG_PROCESSED,{"success":!1,"frag":t,"error":r})}))}},{"key":"_parseVTTs","value":function _parseVTTs(t,r,a){var i,o=this,l=this.hls;parseWebVTT(null!=(i=t.initSegment)&&i.data?appendUint8Array(t.initSegment.data,new Uint8Array(r)):r,this.initPTS[t.cc],a,t.cc,t.start,(function(r){o._appendCues(r,t.level),l.trigger(I.SUBTITLE_FRAG_PROCESSED,{"success":!0,"frag":t})}),(function(a){o._fallbackToIMSC1(t,r),w.log("Failed to parse VTT cue: ".concat(a)),l.trigger(I.SUBTITLE_FRAG_PROCESSED,{"success":!1,"frag":t,"error":a})}))}},{"key":"_fallbackToIMSC1","value":function _fallbackToIMSC1(t,r){var a=this,i=this.tracks[t.level];i.textCodec||parseIMSC1(r,this.initPTS[t.cc],(function(){i.textCodec=Gr,a._parseIMSC1(t,r)}),(function(){i.textCodec="wvtt"}))}},{"key":"_appendCues","value":function _appendCues(t,r){var a=this.hls;if(this.config.renderTextTracksNatively){var i=this.textTracks[r];if(!i||"disabled"===i.mode)return;t.forEach((function(t){return addCueToTrack(i,t)}))}else{var o=this.tracks[r];if(!o)return;var l=o.default?"default":"subtitles"+r;a.trigger(I.CUES_PARSED,{"type":"subtitles","cues":t,"track":l})}}},{"key":"onFragDecrypted","value":function onFragDecrypted(t,r){var a=r.frag;if(a.type===Re.SUBTITLE){if(!this.initPTS[a.cc])return void this.unparsedVttFrags.push(r);this.onFragLoaded(I.FRAG_LOADED,r)}}},{"key":"onSubtitleTracksCleared","value":function onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}},{"key":"onFragParsingUserdata","value":function onFragParsingUserdata(t,r){var a=this.cea608Parser1,i=this.cea608Parser2;if(this.enabled&&a&&i){var o=r.frag,l=r.samples;if(o.type!==Re.MAIN||"NONE"!==this.closedCaptionsForLevel(o))for(var u=0;u<l.length;u++){var c=l[u].bytes;if(c){var d=this.extractCea608Data(c);a.addData(l[u].pts,d[0]),i.addData(l[u].pts,d[1])}}}}},{"key":"onBufferFlushing","value":function onBufferFlushing(t,r){var a=r.startOffset,i=r.endOffset,o=r.endOffsetSubtitles,l=r.type,u=this.media;if(u&&!(u.currentTime<i)){if(!l||"video"===l){var c=this.captionsTracks;Object.keys(c).forEach((function(t){return removeCuesInRange(c[t],a,i)}))}if(this.config.renderTextTracksNatively&&0===a&&void 0!==o){var d=this.textTracks;Object.keys(d).forEach((function(t){return removeCuesInRange(d[t],a,o)}))}}}},{"key":"extractCea608Data","value":function extractCea608Data(t){for(var r=[[],[]],a=31&t[0],i=2,o=0;o<a;o++){var l=t[i++],u=127&t[i++],c=127&t[i++];if(0!==u||0!==c)if(0!=(4&l)){var d=3&l;0!==d&&1!==d||(r[d].push(u),r[d].push(c))}}return r}}]),TimelineController}();function canReuseVttTextTrack(t,r){return!!t&&t.label===r.name&&!(t.textTrack1||t.textTrack2)}var Zr=function(){function CapLevelController(t){(0,m.Z)(this,CapLevelController),this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}return(0,y.Z)(CapLevelController,[{"key":"setStreamController","value":function setStreamController(t){this.streamController=t}},{"key":"destroy","value":function destroy(){this.unregisterListener(),this.hls.config.capLevelToPlayerSize&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}},{"key":"registerListeners","value":function registerListeners(){var t=this.hls;t.on(I.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(I.MANIFEST_PARSED,this.onManifestParsed,this),t.on(I.BUFFER_CODECS,this.onBufferCodecs,this),t.on(I.MEDIA_DETACHING,this.onMediaDetaching,this)}},{"key":"unregisterListener","value":function unregisterListener(){var t=this.hls;t.off(I.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(I.MANIFEST_PARSED,this.onManifestParsed,this),t.off(I.BUFFER_CODECS,this.onBufferCodecs,this),t.off(I.MEDIA_DETACHING,this.onMediaDetaching,this)}},{"key":"onFpsDropLevelCapping","value":function onFpsDropLevelCapping(t,r){var a=this.hls.levels[r.droppedLevel];this.isLevelAllowed(a)&&this.restrictedLevels.push({"bitrate":a.bitrate,"height":a.height,"width":a.width})}},{"key":"onMediaAttaching","value":function onMediaAttaching(t,r){this.media=r.media instanceof HTMLVideoElement?r.media:null,this.clientRect=null}},{"key":"onManifestParsed","value":function onManifestParsed(t,r){var a=this.hls;this.restrictedLevels=[],this.firstLevel=r.firstLevel,a.config.capLevelToPlayerSize&&r.video&&this.startCapping()}},{"key":"onBufferCodecs","value":function onBufferCodecs(t,r){this.hls.config.capLevelToPlayerSize&&r.video&&this.startCapping()}},{"key":"onMediaDetaching","value":function onMediaDetaching(){this.stopCapping()}},{"key":"detectPlayerSize","value":function detectPlayerSize(){if(this.media&&this.mediaHeight>0&&this.mediaWidth>0){var t=this.hls.levels;if(t.length){var r=this.hls;r.autoLevelCapping=this.getMaxLevel(t.length-1),r.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=r.autoLevelCapping}}}},{"key":"getMaxLevel","value":function getMaxLevel(t){var r=this,a=this.hls.levels;if(!a.length)return-1;var i=a.filter((function(a,i){return r.isLevelAllowed(a)&&i<=t}));return this.clientRect=null,CapLevelController.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}},{"key":"startCapping","value":function startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}},{"key":"stopCapping","value":function stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}},{"key":"getDimensions","value":function getDimensions(){if(this.clientRect)return this.clientRect;var t=this.media,r={"width":0,"height":0};if(t){var a=t.getBoundingClientRect();r.width=a.width,r.height=a.height,r.width||r.height||(r.width=a.right-a.left||t.width||0,r.height=a.bottom-a.top||t.height||0)}return this.clientRect=r,r}},{"key":"mediaWidth","get":function get(){return this.getDimensions().width*this.contentScaleFactor}},{"key":"mediaHeight","get":function get(){return this.getDimensions().height*this.contentScaleFactor}},{"key":"contentScaleFactor","get":function get(){var t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return t}},{"key":"isLevelAllowed","value":function isLevelAllowed(t){return!this.restrictedLevels.some((function(r){return t.bitrate===r.bitrate&&t.width===r.width&&t.height===r.height}))}}],[{"key":"getMaxLevelByMediaSize","value":function getMaxLevelByMediaSize(t,r,a){if(null==t||!t.length)return-1;for(var i=function atGreatestBandwidth(t,r){return!r||(t.width!==r.width||t.height!==r.height)},o=t.length-1,l=0;l<t.length;l+=1){var u=t[l];if((u.width>=r||u.height>=a)&&i(u,t[l+1])){o=l;break}}return o}}]),CapLevelController}(),Yr=function(){function FPSController(t){(0,m.Z)(this,FPSController),this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}return(0,y.Z)(FPSController,[{"key":"setStreamController","value":function setStreamController(t){this.streamController=t}},{"key":"registerListeners","value":function registerListeners(){this.hls.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this)}},{"key":"unregisterListeners","value":function unregisterListeners(){this.hls.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this)}},{"key":"destroy","value":function destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}},{"key":"onMediaAttaching","value":function onMediaAttaching(t,r){var a=this.hls.config;if(a.capLevelOnFPSDrop){var i=r.media instanceof self.HTMLVideoElement?r.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),a.fpsDroppedMonitoringPeriod)}}},{"key":"checkFPS","value":function checkFPS(t,r,a){var i=performance.now();if(r){if(this.lastTime){var o=i-this.lastTime,l=a-this.lastDroppedFrames,u=r-this.lastDecodedFrames,c=1e3*l/o,d=this.hls;if(d.trigger(I.FPS_DROP,{"currentDropped":l,"currentDecoded":u,"totalDroppedFrames":a}),c>0&&l>d.config.fpsDroppedMonitoringThreshold*u){var h=d.currentLevel;w.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(-1===d.autoLevelCapping||d.autoLevelCapping>=h)&&(h-=1,d.trigger(I.FPS_DROP_LEVEL_CAPPING,{"level":h,"droppedLevel":d.currentLevel}),d.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=a,this.lastDecodedFrames=r}}},{"key":"checkFPSInterval","value":function checkFPSInterval(){var t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){var r=t.getVideoPlaybackQuality();this.checkFPS(t,r.totalVideoFrames,r.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}}]),FPSController}(),jr="[eme]",qr=function(){function EMEController(t){(0,m.Z)(this,EMEController),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=EMEController.CDMCleanupPromise?[EMEController.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=w.debug.bind(w,jr),this.log=w.log.bind(w,jr),this.warn=w.warn.bind(w,jr),this.error=w.error.bind(w,jr),this.hls=t,this.config=t.config,this.registerListeners()}return(0,y.Z)(EMEController,[{"key":"destroy","value":function destroy(){this.unregisterListeners(),this.onMediaDetached();var t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}},{"key":"registerListeners","value":function registerListeners(){this.hls.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(I.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(I.MANIFEST_LOADED,this.onManifestLoaded,this)}},{"key":"unregisterListeners","value":function unregisterListeners(){this.hls.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(I.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(I.MANIFEST_LOADED,this.onManifestLoaded,this)}},{"key":"getLicenseServerUrl","value":function getLicenseServerUrl(t){var r=this.config,a=r.drmSystems,i=r.widevineLicenseUrl,o=a[t];if(o)return o.licenseUrl;if(t===W.WIDEVINE&&i)return i;throw new Error('no license server URL configured for key-system "'.concat(t,'"'))}},{"key":"getServerCertificateUrl","value":function getServerCertificateUrl(t){var r=this.config.drmSystems[t];if(r)return r.serverCertificateUrl;this.log('No Server Certificate in config.drmSystems["'.concat(t,'"]'))}},{"key":"attemptKeySystemAccess","value":function attemptKeySystemAccess(t){var r=this,a=this.hls.levels,i=function uniqueCodec(t,r,a){return!!t&&a.indexOf(t)===r},o=a.map((function(t){return t.audioCodec})).filter(i),l=a.map((function(t){return t.videoCodec})).filter(i);return o.length+l.length===0&&l.push("avc1.42e01e"),new Promise((function(a,i){!function attempt(t){var u=t.shift();r.getMediaKeysPromise(u,o,l).then((function(t){return a({"keySystem":u,"mediaKeys":t})})).catch((function(r){t.length?attempt(t):i(r instanceof zr?r:new zr({"type":D.KEY_SYSTEM_ERROR,"details":b.KEY_SYSTEM_NO_ACCESS,"error":r,"fatal":!0},r.message))}))}(t)}))}},{"key":"requestMediaKeySystemAccess","value":function requestMediaKeySystemAccess(t,r){var a=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof a){var i="Configured requestMediaKeySystemAccess is not a function ".concat(a);return null===j&&"http:"===self.location.protocol&&(i="navigator.requestMediaKeySystemAccess is not available over insecure protocol ".concat(location.protocol)),Promise.reject(new Error(i))}return a(t,r)}},{"key":"getMediaKeysPromise","value":function getMediaKeysPromise(t,r,a){var i=this,o=function getSupportedMediaKeySystemConfigurations(t,r,a,i){var o;switch(t){case W.FAIRPLAY:o=["cenc","sinf"];break;case W.WIDEVINE:case W.PLAYREADY:o=["cenc"];break;case W.CLEARKEY:o=["cenc","keyids"];break;default:throw new Error("Unknown key-system: ".concat(t))}return function createMediaKeySystemConfigurations(t,r,a,i){return[{"initDataTypes":t,"persistentState":i.persistentState||"not-allowed","distinctiveIdentifier":i.distinctiveIdentifier||"not-allowed","sessionTypes":i.sessionTypes||[i.sessionType||"temporary"],"audioCapabilities":r.map((function(t){return{"contentType":'audio/mp4; codecs="'.concat(t,'"'),"robustness":i.audioRobustness||"","encryptionScheme":i.audioEncryptionScheme||null}})),"videoCapabilities":a.map((function(t){return{"contentType":'video/mp4; codecs="'.concat(t,'"'),"robustness":i.videoRobustness||"","encryptionScheme":i.videoEncryptionScheme||null}}))}]}(o,r,a,i)}(t,r,a,this.config.drmSystemOptions),l=this.keySystemAccessPromises[t],u=null==l?void 0:l.keySystemAccess;if(!u){this.log('Requesting encrypted media "'.concat(t,'" key-system access with config: ').concat(JSON.stringify(o))),u=this.requestMediaKeySystemAccess(t,o);var c=this.keySystemAccessPromises[t]={"keySystemAccess":u};return u.catch((function(r){i.log('Failed to obtain access to key-system "'.concat(t,'": ').concat(r))})),u.then((function(r){i.log('Access for key-system "'.concat(r.keySystem,'" obtained'));var a=i.fetchServerCertificate(t);return i.log('Create media-keys for "'.concat(t,'"')),c.mediaKeys=r.createMediaKeys().then((function(r){return i.log('Media-keys created for "'.concat(t,'"')),a.then((function(a){return a?i.setMediaKeysServerCertificate(r,t,a):r}))})),c.mediaKeys.catch((function(r){i.error('Failed to create media-keys for "'.concat(t,'"}: ').concat(r))})),c.mediaKeys}))}return u.then((function(){return l.mediaKeys}))}},{"key":"createMediaKeySessionContext","value":function createMediaKeySessionContext(t){var r=t.decryptdata,a=t.keySystem,i=t.mediaKeys;this.log('Creating key-system session "'.concat(a,'" keyId: ').concat(ue.hexDump(r.keyId||[])));var o=i.createSession(),l={"decryptdata":r,"keySystem":a,"mediaKeys":i,"mediaKeysSession":o,"keyStatus":"status-pending"};return this.mediaKeySessions.push(l),l}},{"key":"renewKeySession","value":function renewKeySession(t){var r=t.decryptdata;if(r.pssh){var a=this.createMediaKeySessionContext(t),i=this.getKeyIdString(r);this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(a,"cenc",r.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}},{"key":"getKeyIdString","value":function getKeyIdString(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return ue.hexDump(t.keyId)}},{"key":"updateKeySession","value":function updateKeySession(t,r){var a,i=t.mediaKeysSession;return this.log('Updating key-session "'.concat(i.sessionId,'" for keyID ').concat(ue.hexDump((null==(a=t.decryptdata)?void 0:a.keyId)||[]),"\n } (data length: ").concat(r?r.byteLength:r,")")),i.update(r)}},{"key":"selectKeySystemFormat","value":function selectKeySystemFormat(t){var r=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log("Selecting key-system from fragment (sn: ".concat(t.sn," ").concat(t.type,": ").concat(t.level,") key formats ").concat(r.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(r)),this.keyFormatPromise}},{"key":"getKeyFormatPromise","value":function getKeyFormatPromise(t){var r=this;return new Promise((function(a,i){var o=getKeySystemsForConfig(r.config),l=t.map(keySystemFormatToKeySystemDomain).filter((function(t){return!!t&&-1!==o.indexOf(t)}));return r.getKeySystemSelectionPromise(l).then((function(t){var r=t.keySystem,o=keySystemDomainToKeySystemFormat(r);o?a(o):i(new Error('Unable to find format for key-system "'.concat(r,'"')))})).catch(i)}))}},{"key":"loadKey","value":function loadKey(t){var r=this,a=t.keyInfo.decryptdata,i=this.getKeyIdString(a),o="(keyId: ".concat(i,' format: "').concat(a.keyFormat,'" method: ').concat(a.method," uri: ").concat(a.uri,")");this.log("Starting session for key ".concat(o));var l=this.keyIdToKeySessionPromise[i];return l||(l=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(a).then((function(i){var l=i.keySystem,u=i.mediaKeys;return r.throwIfDestroyed(),r.log("Handle encrypted media sn: ".concat(t.frag.sn," ").concat(t.frag.type,": ").concat(t.frag.level," using key ").concat(o)),r.attemptSetMediaKeys(l,u).then((function(){r.throwIfDestroyed();var t=r.createMediaKeySessionContext({"keySystem":l,"mediaKeys":u,"decryptdata":a});return r.generateRequestWithPreferredKeySession(t,"cenc",a.pssh,"playlist-key")}))}))).catch((function(t){return r.handleError(t)})),l}},{"key":"throwIfDestroyed","value":function throwIfDestroyed(){if(!this.hls)throw new Error("invalid state")}},{"key":"handleError","value":function handleError(t){this.hls&&(this.error(t.message),t instanceof zr?this.hls.trigger(I.ERROR,t.data):this.hls.trigger(I.ERROR,{"type":D.KEY_SYSTEM_ERROR,"details":b.KEY_SYSTEM_NO_KEYS,"error":t,"fatal":!0}))}},{"key":"getKeySystemForKeyPromise","value":function getKeySystemForKeyPromise(t){var r=this.getKeyIdString(t),a=this.keyIdToKeySessionPromise[r];if(!a){var i=keySystemFormatToKeySystemDomain(t.keyFormat),o=i?[i]:getKeySystemsForConfig(this.config);return this.attemptKeySystemAccess(o)}return a}},{"key":"getKeySystemSelectionPromise","value":function getKeySystemSelectionPromise(t){if(t.length||(t=getKeySystemsForConfig(this.config)),0===t.length)throw new zr({"type":D.KEY_SYSTEM_ERROR,"details":b.KEY_SYSTEM_NO_CONFIGURED_LICENSE,"fatal":!0},"Missing key-system license configuration options ".concat(JSON.stringify({"drmSystems":this.config.drmSystems})));return this.attemptKeySystemAccess(t)}},{"key":"_onMediaEncrypted","value":function _onMediaEncrypted(t){var r=this,a=t.initDataType,i=t.initData;if(this.debug('"'.concat(t.type,'" event: init data type: "').concat(a,'"')),null!==i){var o,l;if("sinf"===a&&this.config.drmSystems[W.FAIRPLAY]){var u=bin2str(new Uint8Array(i));try{var c=base64Decode(JSON.parse(u).sinf),d=parseSinf(new Uint8Array(c));if(!d)return;o=d.subarray(8,24),l=W.FAIRPLAY}catch(t){return void this.warn('Failed to parse sinf "encrypted" event message initData')}}else{var h=function parsePssh(t){if(!(t instanceof ArrayBuffer)||t.byteLength<32)return null;var r={"version":0,"systemId":"","kids":null,"data":null},a=new DataView(t),i=a.getUint32(0);if(t.byteLength!==i&&i>44)return null;if(1886614376!==a.getUint32(4))return null;if(r.version=a.getUint32(8)>>>24,r.version>1)return null;r.systemId=ue.hexDump(new Uint8Array(t,12,16));var o=a.getUint32(28);if(0===r.version){if(i-32<o)return null;r.data=new Uint8Array(t,32,o)}else if(1===r.version){r.kids=[];for(var l=0;l<o;l++)r.kids.push(new Uint8Array(t,32+16*l,16))}return r}(i);if(null===h)return;0===h.version&&h.systemId===Y.WIDEVINE&&h.data&&(o=h.data.subarray(8,24)),l=function keySystemIdToKeySystemDomain(t){if(t===Y.WIDEVINE)return W.WIDEVINE}(h.systemId)}if(l&&o){for(var g=ue.hexDump(o),v=this.keyIdToKeySessionPromise,m=this.mediaKeySessions,y=v[g],p=function _loop5(){var t=m[T],l=t.decryptdata;if(l.pssh||!l.keyId)return"continue";var u=ue.hexDump(l.keyId);return g===u||-1!==l.uri.replace(/-/g,"").indexOf(g)?(y=v[u],delete v[u],l.pssh=new Uint8Array(i),l.keyId=o,y=v[g]=y.then((function(){return r.generateRequestWithPreferredKeySession(t,a,i,"encrypted-event-key-match")})),"break"):void 0},T=0;T<m.length;T++){var E=p();if("continue"!==E&&"break"===E)break}y||(y=v[g]=this.getKeySystemSelectionPromise([l]).then((function(t){var l,u=t.keySystem,c=t.mediaKeys;r.throwIfDestroyed();var d=new ge("ISO-23001-7",g,null!=(l=keySystemDomainToKeySystemFormat(u))?l:"");return d.pssh=new Uint8Array(i),d.keyId=o,r.attemptSetMediaKeys(u,c).then((function(){r.throwIfDestroyed();var t=r.createMediaKeySessionContext({"decryptdata":d,"keySystem":u,"mediaKeys":c});return r.generateRequestWithPreferredKeySession(t,a,i,"encrypted-event-no-match")}))}))),y.catch((function(t){return r.handleError(t)}))}}}},{"key":"_onWaitingForKey","value":function _onWaitingForKey(t){this.log('"'.concat(t.type,'" event'))}},{"key":"attemptSetMediaKeys","value":function attemptSetMediaKeys(t,r){var a=this,i=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'.concat(t,'"'));var o=Promise.all(i).then((function(){if(!a.media)throw new Error("Attempted to set mediaKeys without media element attached");return a.media.setMediaKeys(r)}));return this.setMediaKeysQueue.push(o),o.then((function(){a.log('Media-keys set for "'.concat(t,'"')),i.push(o),a.setMediaKeysQueue=a.setMediaKeysQueue.filter((function(t){return-1===i.indexOf(t)}))}))}},{"key":"generateRequestWithPreferredKeySession","value":function generateRequestWithPreferredKeySession(t,r,a,i){var o,l,u=this,c=null==(o=this.config.drmSystems)||null==(l=o[t.keySystem])?void 0:l.generateRequest;if(c)try{var d=c.call(this.hls,r,a,t);if(!d)throw new Error("Invalid response from configured generateRequest filter");r=d.initDataType,a=t.decryptdata.pssh=d.initData?new Uint8Array(d.initData):null}catch(t){var h;if(this.warn(t.message),null!=(h=this.hls)&&h.config.debug)throw t}if(null===a)return this.log('Skipping key-session request for "'.concat(i,'" (no initData)')),Promise.resolve(t);var g=this.getKeyIdString(t.decryptdata);this.log('Generating key-session request for "'.concat(i,'": ').concat(g," (init data type: ").concat(r," length: ").concat(a?a.byteLength:null,")"));var v=new jt;t.mediaKeysSession.onmessage=function(r){var a=t.mediaKeysSession;if(a){var i=r.messageType,o=r.message;u.log('"'.concat(i,'" message event for session "').concat(a.sessionId,'" message size: ').concat(o.byteLength)),"license-request"===i||"license-renewal"===i?u.renewLicense(t,o).catch((function(t){u.handleError(t),v.emit("error",t)})):"license-release"===i?t.keySystem===W.FAIRPLAY&&(u.updateKeySession(t,strToUtf8array("acknowledged")),u.removeSession(t)):u.warn('unhandled media key message type "'.concat(i,'"'))}else v.emit("error",new Error("invalid state"))},t.mediaKeysSession.onkeystatuseschange=function(r){if(t.mediaKeysSession){u.onKeyStatusChange(t);var a=t.keyStatus;v.emit("keyStatus",a),"expired"===a&&(u.warn("".concat(t.keySystem," expired for key ").concat(g)),u.renewKeySession(t))}else v.emit("error",new Error("invalid state"))};var m=new Promise((function(t,r){v.on("error",r),v.on("keyStatus",(function(a){a.startsWith("usable")?t():"output-restricted"===a?r(new zr({"type":D.KEY_SYSTEM_ERROR,"details":b.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,"fatal":!1},"HDCP level output restricted")):"internal-error"===a?r(new zr({"type":D.KEY_SYSTEM_ERROR,"details":b.KEY_SYSTEM_STATUS_INTERNAL_ERROR,"fatal":!0},'key status changed to "'.concat(a,'"'))):"expired"===a?r(new Error("key expired while generating request")):u.warn('unhandled key status change "'.concat(a,'"'))}))}));return t.mediaKeysSession.generateRequest(r,a).then((function(){var r;u.log('Request generated for key-session "'.concat(null==(r=t.mediaKeysSession)?void 0:r.sessionId,'" keyId: ').concat(g))})).catch((function(t){throw new zr({"type":D.KEY_SYSTEM_ERROR,"details":b.KEY_SYSTEM_NO_SESSION,"error":t,"fatal":!1},"Error generating key-session request: ".concat(t))})).then((function(){return m})).catch((function(r){throw v.removeAllListeners(),u.removeSession(t),r})).then((function(){return v.removeAllListeners(),t}))}},{"key":"onKeyStatusChange","value":function onKeyStatusChange(t){var r=this;t.mediaKeysSession.keyStatuses.forEach((function(a,i){r.log('key status change "'.concat(a,'" for keyStatuses keyId: ').concat(ue.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))," session keyId: ").concat(ue.hexDump(new Uint8Array(t.decryptdata.keyId||[]))," uri: ").concat(t.decryptdata.uri)),t.keyStatus=a}))}},{"key":"fetchServerCertificate","value":function fetchServerCertificate(t){var r=this.config,a=new(0,r.loader)(r),i=this.getServerCertificateUrl(t);return i?(this.log('Fetching serverCertificate for "'.concat(t,'"')),new Promise((function(o,l){var u={"responseType":"arraybuffer","url":i},c=r.certLoadPolicy.default,d={"loadPolicy":c,"timeout":c.maxLoadTimeMs,"maxRetry":0,"retryDelay":0,"maxRetryDelay":0},h={"onSuccess":function onSuccess(t,r,a,i){o(t.data)},"onError":function onError(r,a,o,c){l(new zr({"type":D.KEY_SYSTEM_ERROR,"details":b.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,"fatal":!0,"networkDetails":o,"response":_objectSpread2({"url":u.url,"data":void 0},r)},'"'.concat(t,'" certificate request failed (').concat(i,"). Status: ").concat(r.code," (").concat(r.text,")")))},"onTimeout":function onTimeout(r,a,o){l(new zr({"type":D.KEY_SYSTEM_ERROR,"details":b.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,"fatal":!0,"networkDetails":o,"response":{"url":u.url,"data":void 0}},'"'.concat(t,'" certificate request timed out (').concat(i,")")))},"onAbort":function onAbort(t,r,a){l(new Error("aborted"))}};a.load(u,d,h)}))):Promise.resolve()}},{"key":"setMediaKeysServerCertificate","value":function setMediaKeysServerCertificate(t,r,a){var i=this;return new Promise((function(o,l){t.setServerCertificate(a).then((function(l){i.log("setServerCertificate ".concat(l?"success":"not supported by CDM"," (").concat(null==a?void 0:a.byteLength,') on "').concat(r,'"')),o(t)})).catch((function(t){l(new zr({"type":D.KEY_SYSTEM_ERROR,"details":b.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,"error":t,"fatal":!0},t.message))}))}))}},{"key":"renewLicense","value":function renewLicense(t,r){var a=this;return this.requestLicense(t,new Uint8Array(r)).then((function(r){return a.updateKeySession(t,new Uint8Array(r)).catch((function(t){throw new zr({"type":D.KEY_SYSTEM_ERROR,"details":b.KEY_SYSTEM_SESSION_UPDATE_FAILED,"error":t,"fatal":!0},t.message)}))}))}},{"key":"setupLicenseXHR","value":function setupLicenseXHR(t,r,a,i){var o=this,l=this.config.licenseXhrSetup;return l?Promise.resolve().then((function(){if(!a.decryptdata)throw new Error("Key removed");return l.call(o.hls,t,r,a,i)})).catch((function(u){if(!a.decryptdata)throw u;return t.open("POST",r,!0),l.call(o.hls,t,r,a,i)})).then((function(a){return t.readyState||t.open("POST",r,!0),{"xhr":t,"licenseChallenge":a||i}})):(t.open("POST",r,!0),Promise.resolve({"xhr":t,"licenseChallenge":i}))}},{"key":"requestLicense","value":function requestLicense(t,r){var a=this,i=this.config.keyLoadPolicy.default;return new Promise((function(o,l){var u=a.getLicenseServerUrl(t.keySystem);a.log("Sending license request to URL: ".concat(u));var c=new XMLHttpRequest;c.responseType="arraybuffer",c.onreadystatechange=function(){if(!a.hls||!t.mediaKeysSession)return l(new Error("invalid state"));if(4===c.readyState)if(200===c.status){a._requestLicenseFailureCount=0;var d=c.response;a.log("License received ".concat(d instanceof ArrayBuffer?d.byteLength:d));var h=a.config.licenseResponseCallback;if(h)try{d=h.call(a.hls,c,u,t)}catch(t){a.error(t)}o(d)}else{var g=i.errorRetry,v=g?g.maxNumRetry:0;if(a._requestLicenseFailureCount++,a._requestLicenseFailureCount>v||c.status>=400&&c.status<500)l(new zr({"type":D.KEY_SYSTEM_ERROR,"details":b.KEY_SYSTEM_LICENSE_REQUEST_FAILED,"fatal":!0,"networkDetails":c,"response":{"url":u,"data":void 0,"code":c.status,"text":c.statusText}},"License Request XHR failed (".concat(u,"). Status: ").concat(c.status," (").concat(c.statusText,")")));else{var m=v-a._requestLicenseFailureCount+1;a.warn("Retrying license request, ".concat(m," attempts left")),a.requestLicense(t,r).then(o,l)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=c,a.setupLicenseXHR(c,u,t,r).then((function(t){var r=t.xhr,a=t.licenseChallenge;r.send(a)}))}))}},{"key":"onMediaAttached","value":function onMediaAttached(t,r){if(this.config.emeEnabled){var a=r.media;this.media=a,a.addEventListener("encrypted",this.onMediaEncrypted),a.addEventListener("waitingforkey",this.onWaitingForKey)}}},{"key":"onMediaDetached","value":function onMediaDetached(){var t=this,r=this.media,a=this.mediaKeySessions;r&&(r.removeEventListener("encrypted",this.onMediaEncrypted),r.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},ge.clearKeyUriToKeyIdMap();var i=a.length;EMEController.CDMCleanupPromise=Promise.all(a.map((function(r){return t.removeSession(r)})).concat(null==r?void 0:r.setMediaKeys(null).catch((function(a){t.log("Could not clear media keys: ".concat(a,". media.src: ").concat(null==r?void 0:r.src))})))).then((function(){i&&(t.log("finished closing key sessions and clearing media keys"),a.length=0)})).catch((function(a){t.log("Could not close sessions and clear media keys: ".concat(a,". media.src: ").concat(null==r?void 0:r.src))}))}},{"key":"onManifestLoading","value":function onManifestLoading(){this.keyFormatPromise=null}},{"key":"onManifestLoaded","value":function onManifestLoaded(t,r){var a=r.sessionKeys;if(a&&this.config.emeEnabled&&!this.keyFormatPromise){var i=a.reduce((function(t,r){return-1===t.indexOf(r.keyFormat)&&t.push(r.keyFormat),t}),[]);this.log("Selecting key-system from session-keys ".concat(i.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(i)}}},{"key":"removeSession","value":function removeSession(t){var r=this,a=t.mediaKeysSession,i=t.licenseXhr;if(a){this.log("Remove licenses and keys and close session ".concat(a.sessionId)),a.onmessage=null,a.onkeystatuseschange=null,i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;var o=this.mediaKeySessions.indexOf(t);return o>-1&&this.mediaKeySessions.splice(o,1),a.remove().catch((function(t){r.log("Could not remove session: ".concat(t))})).then((function(){return a.close()})).catch((function(t){r.log("Could not close session: ".concat(t))}))}}}]),EMEController}();qr.CDMCleanupPromise=void 0;var zr=function(t){(0,g.Z)(EMEKeyError,t);var r=(0,v.Z)(EMEKeyError);function EMEKeyError(t,a){var i;return(0,m.Z)(this,EMEKeyError),(i=r.call(this,a)).data=void 0,t.error||(t.error=new Error(a)),i.data=t,t.err=t.error,i}return(0,y.Z)(EMEKeyError)}((0,c.Z)(Error)),Xr={"MANIFEST":"m","AUDIO":"a","VIDEO":"v","MUXED":"av","INIT":"i","CAPTION":"c","TIMED_TEXT":"tt","KEY":"k","OTHER":"o"},Qr=function(){function CMCDController(t){var r=this;(0,m.Z)(this,CMCDController),this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=function(){r.initialized&&(r.starved=!0),r.buffering=!0},this.onPlaying=function(){r.initialized||(r.initialized=!0),r.buffering=!1},this.applyPlaylistData=function(t){try{r.apply(t,{"ot":Xr.MANIFEST,"su":!r.initialized})}catch(t){w.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=function(t){try{var a=t.frag,i=r.hls.levels[a.level],o=r.getObjectType(a),l={"d":1e3*a.duration,"ot":o};o!==Xr.VIDEO&&o!==Xr.AUDIO&&o!=Xr.MUXED||(l.br=i.bitrate/1e3,l.tb=r.getTopBandwidth(o)/1e3,l.bl=r.getBufferLength(o)),r.apply(t,l)}catch(t){w.warn("Could not generate segment CMCD data.",t)}},this.hls=t;var a=this.config=t.config,i=a.cmcd;null!=i&&(a.pLoader=this.createPlaylistLoader(),a.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||CMCDController.uuid(),this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.registerListeners())}return(0,y.Z)(CMCDController,[{"key":"registerListeners","value":function registerListeners(){var t=this.hls;t.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(I.MEDIA_DETACHED,this.onMediaDetached,this),t.on(I.BUFFER_CREATED,this.onBufferCreated,this)}},{"key":"unregisterListeners","value":function unregisterListeners(){var t=this.hls;t.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(I.MEDIA_DETACHED,this.onMediaDetached,this),t.off(I.BUFFER_CREATED,this.onBufferCreated,this)}},{"key":"destroy","value":function destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null}},{"key":"onMediaAttached","value":function onMediaAttached(t,r){this.media=r.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}},{"key":"onMediaDetached","value":function onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}},{"key":"onBufferCreated","value":function onBufferCreated(t,r){var a,i;this.audioBuffer=null==(a=r.tracks.audio)?void 0:a.buffer,this.videoBuffer=null==(i=r.tracks.video)?void 0:i.buffer}},{"key":"createData","value":function createData(){var t;return{"v":1,"sf":"h","sid":this.sid,"cid":this.cid,"pr":null==(t=this.media)?void 0:t.playbackRate,"mtp":this.hls.bandwidthEstimate/1e3}}},{"key":"apply","value":function apply(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};_extends(r,this.createData());var a=r.ot===Xr.INIT||r.ot===Xr.VIDEO||r.ot===Xr.MUXED;if(this.starved&&a&&(r.bs=!0,r.su=!0,this.starved=!1),null==r.su&&(r.su=this.buffering),this.useHeaders){var i=CMCDController.toHeaders(r);if(!Object.keys(i).length)return;t.headers||(t.headers={}),_extends(t.headers,i)}else{var o=CMCDController.toQuery(r);if(!o)return;t.url=CMCDController.appendQueryToUri(t.url,o)}}},{"key":"getObjectType","value":function getObjectType(t){var r=t.type;return"subtitle"===r?Xr.TIMED_TEXT:"initSegment"===t.sn?Xr.INIT:"audio"===r?Xr.AUDIO:"main"===r?this.hls.audioTracks.length?Xr.VIDEO:Xr.MUXED:void 0}},{"key":"getTopBandwidth","value":function getTopBandwidth(t){var r,a=0,i=this.hls;if(t===Xr.AUDIO)r=i.audioTracks;else{var l=i.maxAutoLevel,u=l>-1?l+1:i.levels.length;r=i.levels.slice(0,u)}var c,d=(0,o.Z)(r);try{for(d.s();!(c=d.n()).done;){var h=c.value;h.bitrate>a&&(a=h.bitrate)}}catch(t){d.e(t)}finally{d.f()}return a>0?a:NaN}},{"key":"getBufferLength","value":function getBufferLength(t){var r=this.hls.media,a=t===Xr.AUDIO?this.audioBuffer:this.videoBuffer;return a&&r?1e3*st.bufferInfo(a,r.currentTime,this.config.maxBufferHole).len:NaN}},{"key":"createPlaylistLoader","value":function createPlaylistLoader(){var t=this.config.pLoader,r=this.applyPlaylistData,a=t||this.config.loader;return function(){function CmcdPlaylistLoader(t){(0,m.Z)(this,CmcdPlaylistLoader),this.loader=void 0,this.loader=new a(t)}return(0,y.Z)(CmcdPlaylistLoader,[{"key":"stats","get":function get(){return this.loader.stats}},{"key":"context","get":function get(){return this.loader.context}},{"key":"destroy","value":function destroy(){this.loader.destroy()}},{"key":"abort","value":function abort(){this.loader.abort()}},{"key":"load","value":function load(t,a,i){r(t),this.loader.load(t,a,i)}}]),CmcdPlaylistLoader}()}},{"key":"createFragmentLoader","value":function createFragmentLoader(){var t=this.config.fLoader,r=this.applyFragmentData,a=t||this.config.loader;return function(){function CmcdFragmentLoader(t){(0,m.Z)(this,CmcdFragmentLoader),this.loader=void 0,this.loader=new a(t)}return(0,y.Z)(CmcdFragmentLoader,[{"key":"stats","get":function get(){return this.loader.stats}},{"key":"context","get":function get(){return this.loader.context}},{"key":"destroy","value":function destroy(){this.loader.destroy()}},{"key":"abort","value":function abort(){this.loader.abort()}},{"key":"load","value":function load(t,a,i){r(t),this.loader.load(t,a,i)}}]),CmcdFragmentLoader}()}}],[{"key":"uuid","value":function uuid(){var t=URL.createObjectURL(new Blob),uuid=t.toString();return URL.revokeObjectURL(t),uuid.slice(uuid.lastIndexOf("/")+1)}},{"key":"serialize","value":function serialize(t){var r,a=[],i=function isValid(t){return!Number.isNaN(t)&&null!=t&&""!==t&&!1!==t},l=function toRounded(t){return Math.round(t)},u=function toHundred(t){return 100*l(t/100)},c={"br":l,"d":l,"bl":u,"dl":u,"mtp":u,"nor":function toUrlSafe(t){return encodeURIComponent(t)},"rtp":u,"tb":l},d=Object.keys(t||{}).sort(),h=(0,o.Z)(d);try{for(h.s();!(r=h.n()).done;){var g=r.value,v=t[g];if(i(v)&&!("v"===g&&1===v||"pr"==g&&1===v)){var m=c[g];m&&(v=m(v));var y=typeof v,p=void 0;p="ot"===g||"sf"===g||"st"===g?"".concat(g,"=").concat(v):"boolean"===y?g:"number"===y?"".concat(g,"=").concat(v):"".concat(g,"=").concat(JSON.stringify(v)),a.push(p)}}}catch(t){h.e(t)}finally{h.f()}return a.join(",")}},{"key":"toHeaders","value":function toHeaders(t){for(var r={},a=["Object","Request","Session","Status"],i=[{},{},{},{}],o={"br":0,"d":0,"ot":0,"tb":0,"bl":1,"dl":1,"mtp":1,"nor":1,"nrr":1,"su":1,"cid":2,"pr":2,"sf":2,"sid":2,"st":2,"v":2,"bs":3,"rtp":3},l=0,u=Object.keys(t);l<u.length;l++){var c=u[l];i[null!=o[c]?o[c]:1][c]=t[c]}for(var d=0;d<i.length;d++){var h=CMCDController.serialize(i[d]);h&&(r["CMCD-".concat(a[d])]=h)}return r}},{"key":"toQuery","value":function toQuery(t){return"CMCD=".concat(encodeURIComponent(CMCDController.serialize(t)))}},{"key":"appendQueryToUri","value":function appendQueryToUri(t,r){if(!r)return t;var a=t.includes("?")?"&":"?";return"".concat(t).concat(a).concat(r)}}]),CMCDController}(),$r=function(){function ContentSteeringController(t){(0,m.Z)(this,ContentSteeringController),this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.log=w.log.bind(w,"[content-steering]:"),this.registerListeners()}return(0,y.Z)(ContentSteeringController,[{"key":"registerListeners","value":function registerListeners(){var t=this.hls;t.on(I.MANIFEST_LOADING,this.onManifestLoading,this),t.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(I.MANIFEST_PARSED,this.onManifestParsed,this),t.on(I.ERROR,this.onError,this)}},{"key":"unregisterListeners","value":function unregisterListeners(){var t=this.hls;t&&(t.off(I.MANIFEST_LOADING,this.onManifestLoading,this),t.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(I.MANIFEST_PARSED,this.onManifestParsed,this),t.off(I.ERROR,this.onError,this))}},{"key":"startLoad","value":function startLoad(){if(this.started=!0,self.clearTimeout(this.reloadTimer),this.enabled&&this.uri)if(this.updated){var t=Math.max(1e3*this.timeToLoad-(performance.now()-this.updated),0);this.scheduleRefresh(this.uri,t)}else this.loadSteeringManifest(this.uri)}},{"key":"stopLoad","value":function stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),self.clearTimeout(this.reloadTimer)}},{"key":"destroy","value":function destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}},{"key":"removeLevel","value":function removeLevel(t){var r=this.levels;r&&(this.levels=r.filter((function(r){return r!==t})))}},{"key":"onManifestLoading","value":function onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}},{"key":"onManifestLoaded","value":function onManifestLoaded(t,r){var a=r.contentSteering;null!==a&&(this.pathwayId=a.pathwayId,this.uri=a.uri,this.started&&this.startLoad())}},{"key":"onManifestParsed","value":function onManifestParsed(t,r){this.audioTracks=r.audioTracks,this.subtitleTracks=r.subtitleTracks}},{"key":"onError","value":function onError(t,r){var a=r.errorAction;if((null==a?void 0:a.action)===Ge&&a.flags===Ve){var i=this.pathwayPriority,o=this.pathwayId;this.penalizedPathways[o]||(this.penalizedPathways[o]=performance.now()),!i&&this.levels&&(i=this.levels.reduce((function(t,r){return-1===t.indexOf(r.pathwayId)&&t.push(r.pathwayId),t}),[])),i&&i.length>1&&(this.updatePathwayPriority(i),a.resolved=this.pathwayId!==o)}}},{"key":"filterParsedLevels","value":function filterParsedLevels(t){this.levels=t;var r=this.getLevelsForPathway(this.pathwayId);if(0===r.length){var a=t[0].pathwayId;this.log("No levels found in Pathway ".concat(this.pathwayId,'. Setting initial Pathway to "').concat(a,'"')),r=this.getLevelsForPathway(a),this.pathwayId=a}return r.length!==t.length?(this.log("Found ".concat(r.length,"/").concat(t.length,' levels in Pathway "').concat(this.pathwayId,'"')),r):t}},{"key":"getLevelsForPathway","value":function getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter((function(r){return t===r.pathwayId}))}},{"key":"updatePathwayPriority","value":function updatePathwayPriority(t){var r;this.pathwayPriority=t;var a=this.penalizedPathways,i=performance.now();Object.keys(a).forEach((function(t){i-a[t]>3e5&&delete a[t]}));for(var o=0;o<t.length;o++){var l=t[o];if(!a[l]){if(l===this.pathwayId)return;var u=this.hls.nextLoadLevel,c=this.hls.levels[u];if((r=this.getLevelsForPathway(l)).length>0){this.log('Setting Pathway to "'.concat(l,'"')),this.pathwayId=l,this.hls.trigger(I.LEVELS_UPDATED,{"levels":r});var d=this.hls.levels[u];c&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==c.bitrate&&this.log("Unstable Pathways change from bitrate ".concat(c.bitrate," to ").concat(d.bitrate)),this.hls.nextLoadLevel=u);break}}}}},{"key":"clonePathways","value":function clonePathways(t){var r=this,a=this.levels;if(a){var o={},l={};t.forEach((function(t){var u=t.ID,c=t["BASE-ID"],d=t["URI-REPLACEMENT"];if(!a.some((function(t){return t.pathwayId===u}))){var h=r.getLevelsForPathway(c).map((function(t){var r=_extends({},t);r.details=void 0,r.url=performUriReplacement(t.uri,t.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",d);var a=new O(t.attrs);a["PATHWAY-ID"]=u;var i=a.AUDIO&&"".concat(a.AUDIO,"_clone_").concat(u),c=a.SUBTITLES&&"".concat(a.SUBTITLES,"_clone_").concat(u);i&&(o[a.AUDIO]=i,a.AUDIO=i),c&&(l[a.SUBTITLES]=c,a.SUBTITLES=c),r.attrs=a;var h=new Oe(r);return addGroupId(h,"audio",i),addGroupId(h,"text",c),h}));a.push.apply(a,(0,i.Z)(h)),cloneRenditionGroups(r.audioTracks,o,d,u),cloneRenditionGroups(r.subtitleTracks,l,d,u)}}))}}},{"key":"loadSteeringManifest","value":function loadSteeringManifest(t){var r,a=this,i=this.hls.config,o=i.loader;this.loader&&this.loader.destroy(),this.loader=new o(i);try{r=new self.URL(t)}catch(r){return this.enabled=!1,void this.log("Failed to parse Steering Manifest URI: ".concat(t))}if("data:"!==r.protocol){var l=0|(this.hls.bandwidthEstimate||i.abrEwmaDefaultEstimate);r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+l)}var u={"responseType":"json","url":r.href},c=i.steeringManifestLoadPolicy.default,d=c.errorRetry||c.timeoutRetry||{},h={"loadPolicy":c,"timeout":c.maxLoadTimeMs,"maxRetry":d.maxNumRetry||0,"retryDelay":d.retryDelayMs||0,"maxRetryDelay":d.maxRetryDelayMs||0},g={"onSuccess":function onSuccess(t,i,o,l){a.log('Loaded steering manifest: "'.concat(r,'"'));var u=t.data;if(1===u.VERSION){a.updated=performance.now(),a.timeToLoad=u.TTL;var c=u["RELOAD-URI"],d=u["PATHWAY-CLONES"],h=u["PATHWAY-PRIORITY"];if(c)try{a.uri=new self.URL(c,r).href}catch(t){return a.enabled=!1,void a.log("Failed to parse Steering Manifest RELOAD-URI: ".concat(c))}a.scheduleRefresh(a.uri||o.url),d&&a.clonePathways(d),h&&a.updatePathwayPriority(h)}else a.log("Steering VERSION ".concat(u.VERSION," not supported!"))},"onError":function onError(t,r,i,o){if(a.log("Error loading steering manifest: ".concat(t.code," ").concat(t.text," (").concat(r.url,")")),a.stopLoad(),410===t.code)return a.enabled=!1,void a.log("Steering manifest ".concat(r.url," no longer available"));var l=1e3*a.timeToLoad;if(429!==t.code)a.scheduleRefresh(a.uri||r.url,l);else{var u=a.loader;if("function"==typeof(null==u?void 0:u.getResponseHeader)){var c=u.getResponseHeader("Retry-After");c&&(l=1e3*parseFloat(c))}a.log("Steering manifest ".concat(r.url," rate limited"))}},"onTimeout":function onTimeout(t,r,i){a.log("Timeout loading steering manifest (".concat(r.url,")")),a.scheduleRefresh(a.uri||r.url)}};this.log("Requesting steering manifest: ".concat(r)),this.loader.load(u,h,g)}},{"key":"scheduleRefresh","value":function scheduleRefresh(t){var r=this,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3*this.timeToLoad;self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout((function(){r.loadSteeringManifest(t)}),a)}}]),ContentSteeringController}();function cloneRenditionGroups(t,r,a,o){t&&Object.keys(r).forEach((function(l){var u=t.filter((function(t){return t.groupId===l})).map((function(t){var i=_extends({},t);return i.details=void 0,i.attrs=new O(i.attrs),i.url=i.attrs.URI=performUriReplacement(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",a),i.groupId=i.attrs["GROUP-ID"]=r[l],i.attrs["PATHWAY-ID"]=o,i}));t.push.apply(t,(0,i.Z)(u))}))}function performUriReplacement(t,r,a,i){var o,l=i.HOST,u=i.PARAMS,c=i[a];r&&(o=null==c?void 0:c[r])&&(t=o);var d=new self.URL(t);return l&&!o&&(d.host=l),u&&Object.keys(u).sort().forEach((function(t){t&&d.searchParams.set(t,u[t])})),d.href}var Jr=/^age:\s*[\d.]+\s*$/im,ea=function(){function XhrLoader(t){(0,m.Z)(this,XhrLoader),this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new U,this.retryDelay=0}return(0,y.Z)(XhrLoader,[{"key":"destroy","value":function destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null}},{"key":"abortInternal","value":function abortInternal(){var t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}},{"key":"abort","value":function abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}},{"key":"load","value":function load(t,r,a){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=r,this.callbacks=a,this.loadInternal()}},{"key":"loadInternal","value":function loadInternal(){var t=this,r=this.config,a=this.context;if(r){var i=this.loader=new self.XMLHttpRequest,o=this.stats;o.loading.first=0,o.loaded=0;var l=this.xhrSetup;l?Promise.resolve().then((function(){if(!t.stats.aborted)return l(i,a.url)})).catch((function(t){return i.open("GET",a.url,!0),l(i,a.url)})).then((function(){t.stats.aborted||t.openAndSendXhr(i,a,r)})).catch((function(r){t.callbacks.onError({"code":i.status,"text":r.message},a,i,o)})):this.openAndSendXhr(i,a,r)}}},{"key":"openAndSendXhr","value":function openAndSendXhr(t,r,a){t.readyState||t.open("GET",r.url,!0);var i=this.context.headers,o=a.loadPolicy,l=o.maxTimeToFirstByteMs,u=o.maxLoadTimeMs;if(i)for(var c in i)t.setRequestHeader(c,i[c]);r.rangeEnd&&t.setRequestHeader("Range","bytes="+r.rangeStart+"-"+(r.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=r.responseType,self.clearTimeout(this.requestTimeout),a.timeout=l&&R(l)?l:u,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),a.timeout),t.send()}},{"key":"readystatechange","value":function readystatechange(){var t=this.context,r=this.loader,a=this.stats;if(t&&r){var i=r.readyState,o=this.config;if(!a.aborted&&i>=2&&(0===a.loading.first&&(a.loading.first=Math.max(self.performance.now(),a.loading.start),o.timeout!==o.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),o.timeout=o.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),o.loadPolicy.maxLoadTimeMs-(a.loading.first-a.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),r.onreadystatechange=null,r.onprogress=null;var l=r.status,u="text"!==r.responseType;if(l>=200&&l<300&&(u&&r.response||null!==r.responseText)){a.loading.end=Math.max(self.performance.now(),a.loading.first);var c=u?r.response:r.responseText,d="arraybuffer"===r.responseType?c.byteLength:c.length;if(a.loaded=a.total=d,a.bwEstimate=8e3*a.total/(a.loading.end-a.loading.first),!this.callbacks)return;var h=this.callbacks.onProgress;if(h&&h(a,t,c,r),!this.callbacks)return;var g={"url":r.responseURL,"data":c,"code":l};this.callbacks.onSuccess(g,a,t,r)}else{var v=o.loadPolicy.errorRetry;shouldRetry(v,a.retry,!1,l)?this.retry(v):(w.error("".concat(l," while loading ").concat(t.url)),this.callbacks.onError({"code":l,"text":r.statusText},t,r,a))}}}}},{"key":"loadtimeout","value":function loadtimeout(){var t,r=null==(t=this.config)?void 0:t.loadPolicy.timeoutRetry;if(shouldRetry(r,this.stats.retry,!0))this.retry(r);else{w.warn("timeout while loading ".concat(this.context.url));var a=this.callbacks;a&&(this.abortInternal(),a.onTimeout(this.stats,this.context,this.loader))}}},{"key":"retry","value":function retry(t){var r=this.context,a=this.stats;this.retryDelay=getRetryDelay(t,a.retry),a.retry++,w.warn("".concat(status?"HTTP Status "+status:"Timeout"," while loading ").concat(r.url,", retrying ").concat(a.retry,"/").concat(t.maxNumRetry," in ").concat(this.retryDelay,"ms")),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}},{"key":"loadprogress","value":function loadprogress(t){var r=this.stats;r.loaded=t.loaded,t.lengthComputable&&(r.total=t.total)}},{"key":"getCacheAge","value":function getCacheAge(){var t=null;if(this.loader&&Jr.test(this.loader.getAllResponseHeaders())){var r=this.loader.getResponseHeader("age");t=r?parseFloat(r):null}return t}},{"key":"getResponseHeader","value":function getResponseHeader(t){return this.loader&&new RegExp("^".concat(t,":\\s*[\\d.]+\\s*$"),"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}]),XhrLoader}();var ta=/(\d+)-(\d+)\/(\d+)/,ra=function(){function FetchLoader(t){(0,m.Z)(this,FetchLoader),this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||getRequest,this.controller=new self.AbortController,this.stats=new U}return(0,y.Z)(FetchLoader,[{"key":"destroy","value":function destroy(){this.loader=this.callbacks=null,this.abortInternal()}},{"key":"abortInternal","value":function abortInternal(){var t=this.response;null!=t&&t.ok||(this.stats.aborted=!0,this.controller.abort())}},{"key":"abort","value":function abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}},{"key":"load","value":function load(t,r,a){var i=this,o=this.stats;if(o.loading.start)throw new Error("Loader can only be used once.");o.loading.start=self.performance.now();var l=function getRequestParameters(t,r){var a={"method":"GET","mode":"cors","credentials":"same-origin","signal":r,"headers":new self.Headers(_extends({},t.headers))};t.rangeEnd&&a.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return a}(t,this.controller.signal),u=a.onProgress,c="arraybuffer"===t.responseType,d=c?"byteLength":"length",h=r.loadPolicy,g=h.maxTimeToFirstByteMs,v=h.maxLoadTimeMs;this.context=t,this.config=r,this.callbacks=a,this.request=this.fetchSetup(t,l),self.clearTimeout(this.requestTimeout),r.timeout=g&&R(g)?g:v,this.requestTimeout=self.setTimeout((function(){i.abortInternal(),a.onTimeout(o,t,i.response)}),r.timeout),self.fetch(this.request).then((function(l){i.response=i.loader=l;var d=Math.max(self.performance.now(),o.loading.start);if(self.clearTimeout(i.requestTimeout),r.timeout=v,i.requestTimeout=self.setTimeout((function(){i.abortInternal(),a.onTimeout(o,t,i.response)}),v-(d-o.loading.start)),!l.ok){var h=l.status,g=l.statusText;throw new aa(g||"fetch, bad network response",h,l)}return o.loading.first=d,o.total=function getContentLength(t){var r=t.get("Content-Range");if(r){var a=function getByteRangeLength(t){var r=ta.exec(t);if(r)return parseInt(r[2])-parseInt(r[1])+1}(r);if(R(a))return a}var i=t.get("Content-Length");if(i)return parseInt(i)}(l.headers)||o.total,u&&R(r.highWaterMark)?i.loadProgressively(l,o,t,r.highWaterMark,u):c?l.arrayBuffer():"json"===t.responseType?l.json():l.text()})).then((function(l){var c=i.response;self.clearTimeout(i.requestTimeout),o.loading.end=Math.max(self.performance.now(),o.loading.first);var h=l[d];h&&(o.loaded=o.total=h);var g={"url":c.url,"data":l,"code":c.status};u&&!R(r.highWaterMark)&&u(o,t,l,c),a.onSuccess(g,o,t,c)})).catch((function(r){if(self.clearTimeout(i.requestTimeout),!o.aborted){var l=r&&r.code||0,u=r?r.message:null;a.onError({"code":l,"text":u},t,r?r.details:null,o)}}))}},{"key":"getCacheAge","value":function getCacheAge(){var t=null;if(this.response){var r=this.response.headers.get("age");t=r?parseFloat(r):null}return t}},{"key":"getResponseHeader","value":function getResponseHeader(t){return this.response?this.response.headers.get(t):null}},{"key":"loadProgressively","value":function loadProgressively(t,r,a){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,o=arguments.length>4?arguments[4]:void 0,l=new tr,u=t.body.getReader();return function pump(){return u.read().then((function(u){if(u.done)return l.dataLength&&o(r,a,l.flush(),t),Promise.resolve(new ArrayBuffer(0));var c=u.value,d=c.length;return r.loaded+=d,d<i||l.dataLength?(l.push(c),l.dataLength>=i&&o(r,a,l.flush(),t)):o(r,a,c,t),pump()})).catch((function(){return Promise.reject()}))}()}}]),FetchLoader}();function getRequest(t,r){return new self.Request(t.url,r)}var aa=function(t){(0,g.Z)(FetchError,t);var r=(0,v.Z)(FetchError);function FetchError(t,a,i){var o;return(0,m.Z)(this,FetchError),(o=r.call(this,t)).code=void 0,o.details=void 0,o.code=a,o.details=i,o}return(0,y.Z)(FetchError)}((0,c.Z)(Error)),ia=/\s/,na={"newCue"(t,r,a,i){for(var o,l,u,c,d,h=[],g=self.VTTCue||self.TextTrackCue,v=0;v<i.rows.length;v++)if(u=!0,c=0,d="",!(o=i.rows[v]).isEmpty()){for(var m,y=0;y<o.chars.length;y++)ia.test(o.chars[y].uchar)&&u?c++:(d+=o.chars[y].uchar,u=!1);o.cueStartTime=r,r===a&&(a+=1e-4),c>=16?c--:c++;var p=fixLineBreaks(d.trim()),T=generateCueId(r,a,p);null!=t&&null!=(m=t.cues)&&m.getCueById(T)||((l=new g(r,a,p)).id=T,l.line=v+1,l.align="left",l.position=10+Math.min(80,10*Math.floor(8*c/32)),h.push(l))}return t&&h.length&&(h.sort((function(t,r){return"auto"===t.line||"auto"===r.line?0:t.line>8&&r.line>8?r.line-t.line:t.line-r.line})),h.forEach((function(r){return addCueToTrack(t,r)}))),h}},sa=_objectSpread2(_objectSpread2({"autoStartLoad":!0,"startPosition":-1,"defaultAudioCodec":void 0,"debug":!1,"capLevelOnFPSDrop":!1,"capLevelToPlayerSize":!1,"ignoreDevicePixelRatio":!1,"initialLiveManifestSize":1,"maxBufferLength":30,"backBufferLength":1/0,"maxBufferSize":6e7,"maxBufferHole":.1,"highBufferWatchdogPeriod":2,"nudgeOffset":.1,"nudgeMaxRetry":3,"maxFragLookUpTolerance":.25,"liveSyncDurationCount":3,"liveMaxLatencyDurationCount":1/0,"liveSyncDuration":void 0,"liveMaxLatencyDuration":void 0,"maxLiveSyncPlaybackRate":1,"liveDurationInfinity":!1,"liveBackBufferLength":null,"maxMaxBufferLength":600,"enableWorker":!0,"workerPath":null,"enableSoftwareAES":!0,"startLevel":void 0,"startFragPrefetch":!1,"fpsDroppedMonitoringPeriod":5e3,"fpsDroppedMonitoringThreshold":.2,"appendErrorMaxRetry":3,"loader":ea,"fLoader":void 0,"pLoader":void 0,"xhrSetup":void 0,"licenseXhrSetup":void 0,"licenseResponseCallback":void 0,"abrController":er,"bufferController":cr,"capLevelController":Zr,"errorController":Ze,"fpsController":Yr,"stretchShortVideoTrack":!1,"maxAudioFramesDrift":1,"forceKeyFrameOnDiscontinuity":!0,"abrEwmaFastLive":3,"abrEwmaSlowLive":9,"abrEwmaFastVoD":3,"abrEwmaSlowVoD":9,"abrEwmaDefaultEstimate":5e5,"abrBandWidthFactor":.95,"abrBandWidthUpFactor":.7,"abrMaxWithRealBitrate":!1,"maxStarvationDelay":4,"maxLoadingDelay":4,"minAutoBitrate":0,"emeEnabled":!1,"widevineLicenseUrl":void 0,"drmSystems":{},"drmSystemOptions":{},"requestMediaKeySystemAccessFunc":j,"testBandwidth":!0,"progressive":!1,"lowLatencyMode":!0,"cmcd":void 0,"enableDateRangeMetadataCues":!0,"enableEmsgMetadataCues":!0,"enableID3MetadataCues":!0,"certLoadPolicy":{"default":{"maxTimeToFirstByteMs":8e3,"maxLoadTimeMs":2e4,"timeoutRetry":null,"errorRetry":null}},"keyLoadPolicy":{"default":{"maxTimeToFirstByteMs":8e3,"maxLoadTimeMs":2e4,"timeoutRetry":{"maxNumRetry":1,"retryDelayMs":1e3,"maxRetryDelayMs":2e4,"backoff":"linear"},"errorRetry":{"maxNumRetry":8,"retryDelayMs":1e3,"maxRetryDelayMs":2e4,"backoff":"linear"}}},"manifestLoadPolicy":{"default":{"maxTimeToFirstByteMs":1/0,"maxLoadTimeMs":2e4,"timeoutRetry":{"maxNumRetry":2,"retryDelayMs":0,"maxRetryDelayMs":0},"errorRetry":{"maxNumRetry":1,"retryDelayMs":1e3,"maxRetryDelayMs":8e3}}},"playlistLoadPolicy":{"default":{"maxTimeToFirstByteMs":1e4,"maxLoadTimeMs":2e4,"timeoutRetry":{"maxNumRetry":2,"retryDelayMs":0,"maxRetryDelayMs":0},"errorRetry":{"maxNumRetry":2,"retryDelayMs":1e3,"maxRetryDelayMs":8e3}}},"fragLoadPolicy":{"default":{"maxTimeToFirstByteMs":1e4,"maxLoadTimeMs":12e4,"timeoutRetry":{"maxNumRetry":4,"retryDelayMs":0,"maxRetryDelayMs":0},"errorRetry":{"maxNumRetry":6,"retryDelayMs":1e3,"maxRetryDelayMs":8e3}}},"steeringManifestLoadPolicy":{"default":{"maxTimeToFirstByteMs":1e4,"maxLoadTimeMs":2e4,"timeoutRetry":{"maxNumRetry":2,"retryDelayMs":0,"maxRetryDelayMs":0},"errorRetry":{"maxNumRetry":1,"retryDelayMs":1e3,"maxRetryDelayMs":8e3}}},"manifestLoadingTimeOut":1e4,"manifestLoadingMaxRetry":1,"manifestLoadingRetryDelay":1e3,"manifestLoadingMaxRetryTimeout":64e3,"levelLoadingTimeOut":1e4,"levelLoadingMaxRetry":4,"levelLoadingRetryDelay":1e3,"levelLoadingMaxRetryTimeout":64e3,"fragLoadingTimeOut":2e4,"fragLoadingMaxRetry":6,"fragLoadingRetryDelay":1e3,"fragLoadingMaxRetryTimeout":64e3},function timelineConfig(){return{"cueHandler":na,"enableWebVTT":!0,"enableIMSC1":!0,"enableCEA708Captions":!0,"captionsTextTrack1Label":"English","captionsTextTrack1LanguageCode":"en","captionsTextTrack2Label":"Spanish","captionsTextTrack2LanguageCode":"es","captionsTextTrack3Label":"Unknown CC","captionsTextTrack3LanguageCode":"","captionsTextTrack4Label":"Unknown CC","captionsTextTrack4LanguageCode":"","renderTextTracksNatively":!0}}()),{},{"subtitleStreamController":ir,"subtitleTrackController":sr,"timelineController":Wr,"audioStreamController":rr,"audioTrackController":ar,"emeController":qr,"cmcdController":Qr,"contentSteeringController":$r});function deepCpy(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(deepCpy):Object.keys(t).reduce((function(r,a){return r[a]=deepCpy(t[a]),r}),{}):t}function enableStreamingMode(t){var r=t.loader;r!==ra&&r!==ea?(w.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):function fetchSupported(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1}()&&(t.loader=ra,t.progressive=!0,t.enableSoftwareAES=!0,w.log("[config]: Progressive streaming enabled, using FetchLoader"))}var oa=function(){function Hls(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(0,m.Z)(this,Hls),this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new jt,this._autoLevelCapping=void 0,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,function enableLogs(t,r){if(self.console&&!0===t||"object"==typeof t){exportLoggerFunctions(t,"debug","log","info","warn","error");try{_.log('Debug logs enabled for "'.concat(r,'" in hls.js version ',"1.4.1"))}catch(t){_=P}}else _=P}(t.debug||!1,"Hls instance");var r=this.config=function mergeConfig(t,r){if((r.liveSyncDurationCount||r.liveMaxLatencyDurationCount)&&(r.liveSyncDuration||r.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==r.liveMaxLatencyDurationCount&&(void 0===r.liveSyncDurationCount||r.liveMaxLatencyDurationCount<=r.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==r.liveMaxLatencyDuration&&(void 0===r.liveSyncDuration||r.liveMaxLatencyDuration<=r.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');var a=deepCpy(t),i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((function(t){var o="".concat("level"===t?"playlist":t,"LoadPolicy"),l=void 0===r[o],u=[];i.forEach((function(i){var c="".concat(t,"Loading").concat(i),d=r[c];if(void 0!==d&&l){u.push(c);var h=a[o].default;switch(r[o]={"default":h},i){case"TimeOut":h.maxLoadTimeMs=d,h.maxTimeToFirstByteMs=d;break;case"MaxRetry":h.errorRetry.maxNumRetry=d,h.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":h.errorRetry.retryDelayMs=d,h.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":h.errorRetry.maxRetryDelayMs=d,h.timeoutRetry.maxRetryDelayMs=d}}})),u.length&&w.warn('hls.js config: "'.concat(u.join('", "'),'" setting(s) are deprecated, use "').concat(o,'": ').concat(JSON.stringify(r[o])))})),_objectSpread2(_objectSpread2({},a),r)}(Hls.DefaultConfig,t);this.userConfig=t,this._autoLevelCapping=-1,r.progressive&&enableStreamingMode(r);var a=r.abrController,i=r.bufferController,o=r.capLevelController,l=r.errorController,u=r.fpsController,c=new l(this),d=this.abrController=new a(this),h=this.bufferController=new i(this),g=this.capLevelController=new o(this),v=new u(this),y=new Ie(this),p=new _e(this),T=r.contentSteeringController,E=T?new T(this):null,k=this.levelController=new qe(this,E),S=new Je(this),L=new at(this.config),A=this.streamController=new Qt(this,S,L);g.setStreamController(A),v.setStreamController(A);var R=[y,k,A];E&&R.splice(1,0,E),this.networkControllers=R;var D=[d,h,g,v,p,S];this.audioTrackController=this.createController(r.audioTrackController,R);var b=r.audioStreamController;b&&R.push(new b(this,S,L)),this.subtitleTrackController=this.createController(r.subtitleTrackController,R);var C=r.subtitleStreamController;C&&R.push(new C(this,S,L)),this.createController(r.timelineController,D),L.emeController=this.emeController=this.createController(r.emeController,D),this.cmcdController=this.createController(r.cmcdController,D),this.latencyController=this.createController(we,D),this.coreComponents=D,R.push(c);var M=c.onErrorOut;"function"==typeof M&&this.on(I.ERROR,M,c)}return(0,y.Z)(Hls,[{"key":"createController","value":function createController(t,r){if(t){var a=new t(this);return r&&r.push(a),a}return null}},{"key":"on","value":function on(t,r){var a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.on(t,r,a)}},{"key":"once","value":function once(t,r){var a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.once(t,r,a)}},{"key":"removeAllListeners","value":function removeAllListeners(t){this._emitter.removeAllListeners(t)}},{"key":"off","value":function off(t,r){var a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this,i=arguments.length>3?arguments[3]:void 0;this._emitter.off(t,r,a,i)}},{"key":"listeners","value":function listeners(t){return this._emitter.listeners(t)}},{"key":"emit","value":function emit(t,r,a){return this._emitter.emit(t,r,a)}},{"key":"trigger","value":function trigger(t,r){if(this.config.debug)return this.emit(t,t,r);try{return this.emit(t,t,r)}catch(r){w.error("An internal error happened while handling event "+t+'. Error message: "'+r.message+'". Here is a stacktrace:',r),this.trigger(I.ERROR,{"type":D.OTHER_ERROR,"details":b.INTERNAL_EXCEPTION,"fatal":!1,"event":t,"error":r})}return!1}},{"key":"listenerCount","value":function listenerCount(t){return this._emitter.listenerCount(t)}},{"key":"destroy","value":function destroy(){w.log("destroy"),this.trigger(I.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((function(t){return t.destroy()})),this.networkControllers.length=0,this.coreComponents.forEach((function(t){return t.destroy()})),this.coreComponents.length=0;var t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}},{"key":"attachMedia","value":function attachMedia(t){w.log("attachMedia"),this._media=t,this.trigger(I.MEDIA_ATTACHING,{"media":t})}},{"key":"detachMedia","value":function detachMedia(){w.log("detachMedia"),this.trigger(I.MEDIA_DETACHING,void 0),this._media=null}},{"key":"loadSource","value":function loadSource(t){this.stopLoad();var r=this.media,a=this.url,i=this.url=A.buildAbsoluteURL(self.location.href,t,{"alwaysNormalize":!0});w.log("loadSource:".concat(i)),r&&a&&(a!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(r)),this.trigger(I.MANIFEST_LOADING,{"url":t})}},{"key":"startLoad","value":function startLoad(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1;w.log("startLoad(".concat(t,")")),this.networkControllers.forEach((function(r){r.startLoad(t)}))}},{"key":"stopLoad","value":function stopLoad(){w.log("stopLoad"),this.networkControllers.forEach((function(t){t.stopLoad()}))}},{"key":"swapAudioCodec","value":function swapAudioCodec(){w.log("swapAudioCodec"),this.streamController.swapAudioCodec()}},{"key":"recoverMediaError","value":function recoverMediaError(){w.log("recoverMediaError");var t=this._media;this.detachMedia(),t&&this.attachMedia(t)}},{"key":"removeLevel","value":function removeLevel(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;this.levelController.removeLevel(t,r)}},{"key":"levels","get":function get(){var t=this.levelController.levels;return t||[]}},{"key":"currentLevel","get":function get(){return this.streamController.currentLevel},"set":function set(t){w.log("set currentLevel:".concat(t)),this.loadLevel=t,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}},{"key":"nextLevel","get":function get(){return this.streamController.nextLevel},"set":function set(t){w.log("set nextLevel:".concat(t)),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}},{"key":"loadLevel","get":function get(){return this.levelController.level},"set":function set(t){w.log("set loadLevel:".concat(t)),this.levelController.manualLevel=t}},{"key":"nextLoadLevel","get":function get(){return this.levelController.nextLoadLevel},"set":function set(t){this.levelController.nextLoadLevel=t}},{"key":"firstLevel","get":function get(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},"set":function set(t){w.log("set firstLevel:".concat(t)),this.levelController.firstLevel=t}},{"key":"startLevel","get":function get(){return this.levelController.startLevel},"set":function set(t){w.log("set startLevel:".concat(t)),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}},{"key":"capLevelToPlayerSize","get":function get(){return this.config.capLevelToPlayerSize},"set":function set(t){var r=!!t;r!==this.config.capLevelToPlayerSize&&(r?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=r)}},{"key":"autoLevelCapping","get":function get(){return this._autoLevelCapping},"set":function set(t){this._autoLevelCapping!==t&&(w.log("set autoLevelCapping:".concat(t)),this._autoLevelCapping=t)}},{"key":"bandwidthEstimate","get":function get(){var t=this.abrController.bwEstimator;return t?t.getEstimate():NaN}},{"key":"ttfbEstimate","get":function get(){var t=this.abrController.bwEstimator;return t?t.getEstimateTTFB():NaN}},{"key":"maxHdcpLevel","get":function get(){return this._maxHdcpLevel},"set":function set(t){Me.indexOf(t)>-1&&(this._maxHdcpLevel=t)}},{"key":"autoLevelEnabled","get":function get(){return-1===this.levelController.manualLevel}},{"key":"manualLevel","get":function get(){return this.levelController.manualLevel}},{"key":"minAutoLevel","get":function get(){var t=this.levels,r=this.config.minAutoBitrate;if(!t)return 0;for(var a=t.length,i=0;i<a;i++)if(t[i].maxBitrate>=r)return i;return 0}},{"key":"maxAutoLevel","get":function get(){var t,r=this.levels,a=this.autoLevelCapping,i=this.maxHdcpLevel;if(t=-1===a&&r&&r.length?r.length-1:a,i)for(var o=t;o--;){var l=r[o].attrs["HDCP-LEVEL"];if(l&&l<=i)return o}return t}},{"key":"nextAutoLevel","get":function get(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)},"set":function set(t){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,t)}},{"key":"playingDate","get":function get(){return this.streamController.currentProgramDateTime}},{"key":"mainForwardBufferInfo","get":function get(){return this.streamController.getMainFwdBufferInfo()}},{"key":"audioTracks","get":function get(){var t=this.audioTrackController;return t?t.audioTracks:[]}},{"key":"audioTrack","get":function get(){var t=this.audioTrackController;return t?t.audioTrack:-1},"set":function set(t){var r=this.audioTrackController;r&&(r.audioTrack=t)}},{"key":"subtitleTracks","get":function get(){var t=this.subtitleTrackController;return t?t.subtitleTracks:[]}},{"key":"subtitleTrack","get":function get(){var t=this.subtitleTrackController;return t?t.subtitleTrack:-1},"set":function set(t){var r=this.subtitleTrackController;r&&(r.subtitleTrack=t)}},{"key":"media","get":function get(){return this._media}},{"key":"subtitleDisplay","get":function get(){var t=this.subtitleTrackController;return!!t&&t.subtitleDisplay},"set":function set(t){var r=this.subtitleTrackController;r&&(r.subtitleDisplay=t)}},{"key":"lowLatencyMode","get":function get(){return this.config.lowLatencyMode},"set":function set(t){this.config.lowLatencyMode=t}},{"key":"liveSyncPosition","get":function get(){return this.latencyController.liveSyncPosition}},{"key":"latency","get":function get(){return this.latencyController.latency}},{"key":"maxLatency","get":function get(){return this.latencyController.maxLatency}},{"key":"targetLatency","get":function get(){return this.latencyController.targetLatency}},{"key":"drift","get":function get(){return this.latencyController.drift}},{"key":"forceStartLoad","get":function get(){return this.streamController.forceStartLoad}}],[{"key":"version","get":function get(){return"1.4.1"}},{"key":"isSupported","value":function isSupported(){return function _isSupported(){var t=getMediaSource();if(!t)return!1;var r=getSourceBuffer(),a=t&&"function"==typeof t.isTypeSupported&&t.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),i=!r||r.prototype&&"function"==typeof r.prototype.appendBuffer&&"function"==typeof r.prototype.remove;return!!a&&!!i}()}},{"key":"Events","get":function get(){return I}},{"key":"ErrorTypes","get":function get(){return D}},{"key":"ErrorDetails","get":function get(){return b}},{"key":"DefaultConfig","get":function get(){return Hls.defaultConfig?Hls.defaultConfig:sa},"set":function set(t){Hls.defaultConfig=t}}]),Hls}();oa.defaultConfig=void 0,r.default=oa},"7453":function(t,r,a){a.d(r,{"Z":function(){return _createForOfIteratorHelper}});var i=a(4787);function _createForOfIteratorHelper(t,r){var a="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!a){if(Array.isArray(t)||(a=(0,i.Z)(t))||r&&t&&"number"==typeof t.length){a&&(t=a);var o=0,l=function F(){};return{"s":l,"n":function n(){return o>=t.length?{"done":!0}:{"done":!1,"value":t[o++]}},"e":function e(t){throw t},"f":l}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var u,c=!0,d=!1;return{"s":function s(){a=a.call(t)},"n":function n(){var t=a.next();return c=t.done,t},"e":function e(t){d=!0,u=t},"f":function f(){try{c||null==a.return||a.return()}finally{if(d)throw u}}}}}}]);