"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;r1?r-1:0),i=1;i")):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;iNumber.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+81&&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>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>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;o1?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>>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>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)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&&l16){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;bg)break}}function discardEPB(t){for(var r=t.byteLength,a=[],i=1;i0?(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>24&255,c[1]=l>>16&255,c[2]=l>>8&255,c[3]=255&l,c.set(t,4),u=0,l=8;u3&&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;a2){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.length0&&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(rt[a].endTime)return-1;var i=0,o=a;for(;i<=o;){var l=Math.floor((o+i)/2);if(rt[l].startTime&&i-1)for(var l=o,u=t.length;l=r&&c.endTime<=a)i.push(c);else if(c.startTime>a)return i}return i}(t.cues,r,a),u=0;uPe&&(v=Pe),v-g<=0&&(v=g+.25);for(var m=0;mr.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.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||yt.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=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.length||addSliding(r,i[a].start)}function addSliding(t,r){if(r){for(var a=t.fragments,i=t.skippedSegments;i499)}(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.length3*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=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;othis.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(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=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;l1&&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=g&&c<=v){o.time.push({"startPTS":Math.max(l,i.start(h)),"endPTS":Math.min(u,i.end(h))});break}if(lg)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=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.startt&&(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||i1&&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.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;iu&&(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=m&&r3&&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;ia.startCC||t&&t.cc>>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>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>>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;iu.end){var g=l>h;(l2&&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:rl&&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=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(ir}},{"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-1&&aa.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.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.ccr?-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),tr-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=l-r.maxFragLookUpTolerance&&o<=u;if(null!==i&&a.duration>i&&(o").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 ").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.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;a0&&u.samples.push({"pts":this.lastPTS,"dts":this.lastPTS,"data":i,"type":De,"duration":Number.POSITIVE_INFINITY});o>>5}function isHeader$1(t,r){return r+1=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+516384?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+1t?(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<>>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.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)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>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=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=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;a0&&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;ia)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]);r1;){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;mp){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;r1?a-1:0),o=1;o>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>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>>8&255),o.push(255&i),o=o.concat(Array.prototype.slice.call(a));for(r=0;r>>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>>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;r0){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;S0?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;N0?$.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-q0&&(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=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;x0))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;T4294967296;)t+=a;return t}function flushTextTrackMetadataCueSamples(t,r,a,i){var o=t.samples.length;if(o){for(var l=t.inputTimeScale,u=0;u0;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||d1}(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;u0?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;u1&&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-l1e3*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=o0&&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&&u1?(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&&r0&&(o1&&!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))=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||C0&&-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&&Ep||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=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=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=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>>=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=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 ").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;agr&&(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=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;r0&&(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=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 ("+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;tt)&&(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;i100)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=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(//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);a2&&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;a0&&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=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-32v||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);l1&&(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;o0){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&&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=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=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}}}}}}]);