import{t as e}from"./function-call-DPS7n1ao.js";import{E as t,F as n,I as r,J as i,K as a,N as o,P as s,Q as c,R as l,S as u,T as d,X as f,Y as p,a as m,at as h,i as g,j as _,n as v,q as y,t as b,tt as x,w as S,z as C}from"./index-BxA7k3xF.js";import{n as w,t as T}from"./iframe-proxy-CG6_BD05.js";import{t as E}from"./_plugin-vue_export-helper-S3RvzygF.js";var D=Object.create,O=Object.defineProperty,k=Object.getOwnPropertyDescriptor,A=Object.getOwnPropertyNames,j=Object.getPrototypeOf,M=Object.prototype.hasOwnProperty,N=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),ee=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=A(t),a=0,o=i.length,s;at[e]).bind(null,s),enumerable:!(r=k(t,s))||r.enumerable});return e},P=(e,t,n)=>(n=e==null?{}:D(j(e)),ee(t||!e||!e.__esModule?O(n,`default`,{value:e,enumerable:!0}):n,e)),te=N(((e,t)=>{t.exports=typeof window<`u`?window:typeof global<`u`?global:typeof self<`u`?self:{}})),ne=N(((e,t)=>{t.exports={}})),re=N(((e,t)=>{var n=typeof global<`u`?global:typeof window<`u`?window:{},r=ne(),i;typeof document<`u`?i=document:(i=n[`__GLOBAL_DOCUMENT_CACHE@4`],i||=n[`__GLOBAL_DOCUMENT_CACHE@4`]=r),t.exports=i})),ie=N(((e,t)=>{function n(){return t.exports=n=Object.assign?Object.assign.bind():function(e){for(var t=1;t{t.exports=r;var n=Object.prototype.toString;function r(e){if(!e)return!1;var t=n.call(e);return t===`[object Function]`||typeof e==`function`&&t!==`[object RegExp]`||typeof window<`u`&&(e===window.setTimeout||e===window.alert||e===window.confirm||e===window.prompt)}})),ae=N(((e,t)=>{function n(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=r(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var i=0;return function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}}}throw TypeError(`Invalid attempt to iterate non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function r(e,t){if(e){if(typeof e==`string`)return i(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`)return Array.from(e);if(n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return i(e,t)}}function i(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=function(){function e(){this.maxAttempts_=1,this.delayFactor_=.1,this.fuzzFactor_=.1,this.initialDelay_=1e3,this.enabled_=!1}var t=e.prototype;return t.getIsEnabled=function(){return this.enabled_},t.enable=function(){this.enabled_=!0},t.disable=function(){this.enabled_=!1},t.reset=function(){this.maxAttempts_=1,this.delayFactor_=.1,this.fuzzFactor_=.1,this.initialDelay_=1e3,this.enabled_=!1},t.getMaxAttempts=function(){return this.maxAttempts_},t.setMaxAttempts=function(e){this.maxAttempts_=e},t.getDelayFactor=function(){return this.delayFactor_},t.setDelayFactor=function(e){this.delayFactor_=e},t.getFuzzFactor=function(){return this.fuzzFactor_},t.setFuzzFactor=function(e){this.fuzzFactor_=e},t.getInitialDelay=function(){return this.initialDelay_},t.setInitialDelay=function(e){this.initialDelay_=e},t.createRetry=function(e){var t=e===void 0?{}:e,n=t.maxAttempts,i=t.delayFactor,a=t.fuzzFactor,o=t.initialDelay;return new r({maxAttempts:n||this.maxAttempts_,delayFactor:i||this.delayFactor_,fuzzFactor:a||this.fuzzFactor_,initialDelay:o||this.initialDelay_})},e}(),r=function(){function e(e){this.maxAttempts_=e.maxAttempts,this.delayFactor_=e.delayFactor,this.fuzzFactor_=e.fuzzFactor,this.currentDelay_=e.initialDelay,this.currentAttempt_=1}var t=e.prototype;return t.moveToNextAttempt=function(){this.currentAttempt_++;var e=this.currentDelay_*this.delayFactor_;this.currentDelay_+=e},t.shouldRetry=function(){return this.currentAttempt_{var n=te(),r=function(e,t){return t===void 0&&(t=!1),function(r,a,o){if(r){e(r);return}if(a.statusCode>=400&&a.statusCode<=599){var s=o;if(t)if(n.TextDecoder){var c=i(a.headers&&a.headers[`content-type`]);try{s=new TextDecoder(c).decode(o)}catch{}}else s=String.fromCharCode.apply(null,new Uint8Array(o));e({cause:s});return}e(null,o)}};function i(e){return e===void 0&&(e=``),e.toLowerCase().split(`;`).reduce(function(e,t){var n=t.split(`=`),r=n[0],i=n[1];return r.trim()===`charset`?i.trim():e},`utf-8`)}t.exports=r})),ce=N(((e,t)=>{var n=te(),r=ie(),i=F(),a=ae(),o=oe();d.httpHandler=se(),d.requestInterceptorsStorage=new a,d.responseInterceptorsStorage=new a,d.retryManager=new o;var s=function(e){var t={};return e&&e.trim().split(` `).forEach(function(e){var n=e.indexOf(`:`),r=e.slice(0,n).trim().toLowerCase(),i=e.slice(n+1).trim();t[r]===void 0?t[r]=i:Array.isArray(t[r])?t[r].push(i):t[r]=[t[r],i]}),t};t.exports=d,t.exports.default=d,d.XMLHttpRequest=n.XMLHttpRequest||m,d.XDomainRequest=`withCredentials`in new d.XMLHttpRequest?d.XMLHttpRequest:n.XDomainRequest,c([`get`,`put`,`post`,`patch`,`head`,`delete`],function(e){d[e===`delete`?`del`:e]=function(t,n,r){return n=u(t,n,r),n.method=e.toUpperCase(),f(n)}});function c(e,t){for(var n=0;n0&&(C=setTimeout(function(){if(!g){g=!0,m.abort(`timeout`);var e=Error(`XMLHttpRequest timeout`);e.code=`ETIMEDOUT`,c(e)}},e.timeout)),m.setRequestHeader)for(h in b)b.hasOwnProperty(h)&&m.setRequestHeader(h,b[h]);else if(e.headers&&!l(e.headers))throw Error(`Headers cannot be set on an XDomainRequest object`);return`responseType`in e&&(m.responseType=e.responseType),`beforeSend`in e&&typeof e.beforeSend==`function`&&e.beforeSend(m),m.send(y||null),m}function p(e){try{if(e.responseType===`document`)return e.responseXML;var t=e.responseXML&&e.responseXML.documentElement.nodeName===`parsererror`;if(e.responseType===``&&!t)return e.responseXML}catch{}return null}function m(){}})),le=N(((e,t)=>{var n=re(),r=Object.create||(function(){function e(){}return function(t){if(arguments.length!==1)throw Error(`Object.create shim only accepts one parameter.`);return e.prototype=t,new e}})();function i(e,t){this.name=`ParsingError`,this.code=e.code,this.message=t||e.message}i.prototype=r(Error.prototype),i.prototype.constructor=i,i.Errors={BadSignature:{code:0,message:`Malformed WebVTT signature.`},BadTimeStamp:{code:1,message:`Malformed time stamp.`}};function a(e){function t(e,t,n,r){return(e|0)*3600+(t|0)*60+(n|0)+(r|0)/1e3}var n=e.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);return n?n[3]?t(n[1],n[2],n[3].replace(`:`,``),n[4]):n[1]>59?t(n[1],n[2],0,n[4]):t(0,n[1],n[2],n[4]):null}function o(){this.values=r(null)}o.prototype={set:function(e,t){!this.get(e)&&t!==``&&(this.values[e]=t)},get:function(e,t,n){return n?this.has(e)?this.values[e]:t[n]:this.has(e)?this.values[e]:t},has:function(e){return e in this.values},alt:function(e,t,n){for(var r=0;r=0&&t<=100)?(this.set(e,t),!0):!1}};function s(e,t,n,r){var i=r?e.split(r):[e];for(var a in i)if(typeof i[a]==`string`){var o=i[a].split(n);o.length===2&&t(o[0].trim(),o[1].trim())}}function c(e,t,n){var r=e;function c(){var t=a(e);if(t===null)throw new i(i.Errors.BadTimeStamp,`Malformed timestamp: `+r);return e=e.replace(/^[^\sa-zA-Z-]+/,``),t}function l(e,t){var r=new o;s(e,function(e,t){switch(e){case`region`:for(var i=n.length-1;i>=0;i--)if(n[i].id===t){r.set(e,n[i].region);break}break;case`vertical`:r.alt(e,t,[`rl`,`lr`]);break;case`line`:var a=t.split(`,`),o=a[0];r.integer(e,o),r.percent(e,o)&&r.set(`snapToLines`,!1),r.alt(e,o,[`auto`]),a.length===2&&r.alt(`lineAlign`,a[1],[`start`,`center`,`end`]);break;case`position`:a=t.split(`,`),r.percent(e,a[0]),a.length===2&&r.alt(`positionAlign`,a[1],[`start`,`center`,`end`]);break;case`size`:r.percent(e,t);break;case`align`:r.alt(e,t,[`start`,`center`,`end`,`left`,`right`]);break}},/:/,/\s/),t.region=r.get(`region`,null),t.vertical=r.get(`vertical`,``);try{t.line=r.get(`line`,`auto`)}catch{}t.lineAlign=r.get(`lineAlign`,`start`),t.snapToLines=r.get(`snapToLines`,!0),t.size=r.get(`size`,100);try{t.align=r.get(`align`,`center`)}catch{t.align=r.get(`align`,`middle`)}try{t.position=r.get(`position`,`auto`)}catch{t.position=r.get(`position`,{start:0,left:0,center:50,middle:50,end:100,right:100},t.align)}t.positionAlign=r.get(`positionAlign`,{start:`start`,left:`start`,center:`center`,middle:`center`,end:`end`,right:`end`},t.align)}function u(){e=e.replace(/^\s+/,``)}if(u(),t.startTime=c(),u(),e.substr(0,3)!==`-->`)throw new i(i.Errors.BadTimeStamp,`Malformed time stamp (time stamps must be separated by '-->'): `+r);e=e.substr(3),u(),t.endTime=c(),u(),l(e,t)}var l=n.createElement&&n.createElement(`textarea`),u={c:`span`,i:`i`,b:`b`,u:`u`,ruby:`ruby`,rt:`rt`,v:`span`,lang:`span`},d={white:`rgba(255,255,255,1)`,lime:`rgba(0,255,0,1)`,cyan:`rgba(0,255,255,1)`,red:`rgba(255,0,0,1)`,yellow:`rgba(255,255,0,1)`,magenta:`rgba(255,0,255,1)`,blue:`rgba(0,0,255,1)`,black:`rgba(0,0,0,1)`},f={v:`title`,lang:`lang`},p={rt:`ruby`};function m(e,t){function n(){if(!t)return null;function e(e){return t=t.substr(e.length),e}var n=t.match(/^([^<]*)(<[^>]*>?)?/);return e(n[1]?n[1]:n[2])}function r(e){return l.innerHTML=e,e=l.textContent,l.textContent=``,e}function i(e,t){return!p[t.localName]||p[t.localName]===e.localName}function o(t,n){var r=u[t];if(!r)return null;var i=e.document.createElement(r),a=f[t];return a&&n&&(i[a]=n.trim()),i}for(var s=e.document.createElement(`div`),c=s,m,h=[];(m=n())!==null;){if(m[0]===`<`){if(m[1]===`/`){h.length&&h[h.length-1]===m.substr(2).replace(`>`,``)&&(h.pop(),c=c.parentNode);continue}var g=a(m.substr(1,m.length-2)),_;if(g){_=e.document.createProcessingInstruction(`timestamp`,g),c.appendChild(_);continue}var v=m.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);if(!v||(_=o(v[1],v[3]),!_)||!i(c,_))continue;if(v[2]){var y=v[2].split(`.`);y.forEach(function(e){var t=/^bg_/.test(e),n=t?e.slice(3):e;if(d.hasOwnProperty(n)){var r=t?`background-color`:`color`,i=d[n];_.style[r]=i}}),_.className=y.join(` `)}h.push(v[1]),c.appendChild(_),c=_;continue}c.appendChild(e.document.createTextNode(r(m)))}return s}var h=[[1470,1470],[1472,1472],[1475,1475],[1478,1478],[1488,1514],[1520,1524],[1544,1544],[1547,1547],[1549,1549],[1563,1563],[1566,1610],[1645,1647],[1649,1749],[1765,1766],[1774,1775],[1786,1805],[1807,1808],[1810,1839],[1869,1957],[1969,1969],[1984,2026],[2036,2037],[2042,2042],[2048,2069],[2074,2074],[2084,2084],[2088,2088],[2096,2110],[2112,2136],[2142,2142],[2208,2208],[2210,2220],[8207,8207],[64285,64285],[64287,64296],[64298,64310],[64312,64316],[64318,64318],[64320,64321],[64323,64324],[64326,64449],[64467,64829],[64848,64911],[64914,64967],[65008,65020],[65136,65140],[65142,65276],[67584,67589],[67592,67592],[67594,67637],[67639,67640],[67644,67644],[67647,67669],[67671,67679],[67840,67867],[67872,67897],[67903,67903],[67968,68023],[68030,68031],[68096,68096],[68112,68115],[68117,68119],[68121,68147],[68160,68167],[68176,68184],[68192,68223],[68352,68405],[68416,68437],[68440,68466],[68472,68479],[68608,68680],[126464,126467],[126469,126495],[126497,126498],[126500,126500],[126503,126503],[126505,126514],[126516,126519],[126521,126521],[126523,126523],[126530,126530],[126535,126535],[126537,126537],[126539,126539],[126541,126543],[126545,126546],[126548,126548],[126551,126551],[126553,126553],[126555,126555],[126557,126557],[126559,126559],[126561,126562],[126564,126564],[126567,126570],[126572,126578],[126580,126583],[126585,126588],[126590,126590],[126592,126601],[126603,126619],[126625,126627],[126629,126633],[126635,126651],[1114109,1114109]];function g(e){for(var t=0;t=n[0]&&e<=n[1])return!0}return!1}function _(e){var t=[],n=``,r;if(!e||!e.childNodes)return`ltr`;function i(e,t){for(var n=t.childNodes.length-1;n>=0;n--)e.push(t.childNodes[n])}function a(e){if(!e||!e.length)return null;var t=e.pop(),n=t.textContent||t.innerText;if(n){var r=n.match(/^.*(\n|\r)/);return r?(e.length=0,r[0]):n}if(t.tagName===`ruby`)return a(e);if(t.childNodes)return i(e,t),a(e)}for(i(t,e);n=a(t);)for(var o=0;o=0&&e.line<=100))return e.line;if(!e.track||!e.track.textTrackList||!e.track.textTrackList.mediaElement)return-1;for(var t=e.track,n=t.textTrackList,r=0,i=0;ie.left&&this.tope.top},x.prototype.overlapsAny=function(e){for(var t=0;t=e.top&&this.bottom<=e.bottom&&this.left>=e.left&&this.right<=e.right},x.prototype.overlapsOppositeAxis=function(e,t){switch(t){case`+x`:return this.lefte.right;case`+y`:return this.tope.bottom}},x.prototype.intersectPercentage=function(e){return Math.max(0,Math.min(this.right,e.right)-Math.max(this.left,e.left))*Math.max(0,Math.min(this.bottom,e.bottom)-Math.max(this.top,e.top))/(this.height*this.width)},x.prototype.toCSSCompatValues=function(e){return{top:this.top-e.top,bottom:e.bottom-this.bottom,left:this.left-e.left,right:e.right-this.right,height:this.height,width:this.width}},x.getSimpleBoxPosition=function(e){var t=e.div?e.div.offsetHeight:e.tagName?e.offsetHeight:0,n=e.div?e.div.offsetWidth:e.tagName?e.offsetWidth:0,r=e.div?e.div.offsetTop:e.tagName?e.offsetTop:0;return e=e.div?e.div.getBoundingClientRect():e.tagName?e.getBoundingClientRect():e,{left:e.left,right:e.right,top:e.top||r,height:e.height||t,bottom:e.bottom||r+(e.height||t),width:e.width||n}};function S(e,t,n,r){function i(e,t){for(var i,a=new x(e),o=1,s=0;sc&&(i=new x(e),o=c),e=new x(a)}return i||a}var a=new x(t),o=t.cue,s=v(o),c=[];if(o.snapToLines){var l;switch(o.vertical){case``:c=[`+y`,`-y`],l=`height`;break;case`rl`:c=[`+x`,`-x`],l=`width`;break;case`lr`:c=[`-x`,`+x`],l=`width`;break}var u=a.lineHeight,d=u*Math.round(s),f=n[l]+u,p=c[0];Math.abs(d)>f&&(d=d<0?-1:1,d*=Math.ceil(f/u)*u),s<0&&(d+=o.vertical===``?n.height:n.width,c=c.reverse()),a.move(p,d)}else{var m=a.lineHeight/n.height*100;switch(o.lineAlign){case`center`:s-=m/2;break;case`end`:s-=m;break}switch(o.vertical){case``:t.applyStyles({top:t.formatStyle(s,`%`)});break;case`rl`:t.applyStyles({left:t.formatStyle(s,`%`)});break;case`lr`:t.applyStyles({right:t.formatStyle(s,`%`)});break}c=[`+y`,`-x`,`+x`,`-y`],a=new x(t)}var h=i(a,c);t.move(h.toCSSCompatValues(n))}function C(){}C.StringDecoder=function(){return{decode:function(e){if(!e)return``;if(typeof e!=`string`)throw Error(`Error - expected string data.`);return decodeURIComponent(encodeURIComponent(e))}}},C.convertCueToDOMTree=function(e,t){return!e||!t?null:m(e,t)};var w=.05,T=`sans-serif`,E=`1.5%`;C.processCues=function(e,t,n){if(!e||!t||!n)return null;for(;n.firstChild;)n.removeChild(n.firstChild);var r=e.document.createElement(`div`);r.style.position=`absolute`,r.style.left=`0`,r.style.right=`0`,r.style.top=`0`,r.style.bottom=`0`,r.style.margin=E,n.appendChild(r);function i(e){for(var t=0;t`)===-1){t.cue.id=d;continue}case`CUE`:try{c(d,t.cue,t.regionList)}catch(e){t.reportOrThrowError(e),t.cue=null,t.state=`BADCUE`;continue}t.state=`CUETEXT`;continue;case`CUETEXT`:var m=d.indexOf(`-->`)!==-1;if(!d||m&&(p=!0)){t.oncue&&t.oncue(t.cue),t.cue=null,t.state=`ID`;continue}t.cue.text&&(t.cue.text+=` `),t.cue.text+=d.replace(/\u2028/g,` `).replace(/u2029/g,` `);continue;case`BADCUE`:d||(t.state=`ID`);continue}}}catch(e){t.reportOrThrowError(e),t.state===`CUETEXT`&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state===`INITIAL`?`BADWEBVTT`:`BADCUE`}return this},flush:function(){var e=this;try{if(e.buffer+=e.decoder.decode(),(e.cue||e.state===`HEADER`)&&(e.buffer+=` `,e.parse()),e.state===`INITIAL`)throw new i(i.Errors.BadSignature)}catch(t){e.reportOrThrowError(t)}return e.onflush&&e.onflush(),this}},t.exports=C})),ue=N(((e,t)=>{var n=`auto`,r={"":1,lr:1,rl:1},i={start:1,center:1,end:1,left:1,right:1,auto:1,"line-left":1,"line-right":1};function a(e){return typeof e==`string`&&r[e.toLowerCase()]?e.toLowerCase():!1}function o(e){return typeof e==`string`&&i[e.toLowerCase()]?e.toLowerCase():!1}function s(e,t,r){this.hasBeenReset=!1;var i=``,s=!1,c=e,l=t,u=r,d=null,f=``,p=!0,m=`auto`,h=`start`,g=`auto`,_=`auto`,v=100,y=`center`;Object.defineProperties(this,{id:{enumerable:!0,get:function(){return i},set:function(e){i=``+e}},pauseOnExit:{enumerable:!0,get:function(){return s},set:function(e){s=!!e}},startTime:{enumerable:!0,get:function(){return c},set:function(e){if(typeof e!=`number`)throw TypeError(`Start time must be set to a number.`);c=e,this.hasBeenReset=!0}},endTime:{enumerable:!0,get:function(){return l},set:function(e){if(typeof e!=`number`)throw TypeError(`End time must be set to a number.`);l=e,this.hasBeenReset=!0}},text:{enumerable:!0,get:function(){return u},set:function(e){u=``+e,this.hasBeenReset=!0}},region:{enumerable:!0,get:function(){return d},set:function(e){d=e,this.hasBeenReset=!0}},vertical:{enumerable:!0,get:function(){return f},set:function(e){var t=a(e);if(t===!1)throw SyntaxError(`Vertical: an invalid or illegal direction string was specified.`);f=t,this.hasBeenReset=!0}},snapToLines:{enumerable:!0,get:function(){return p},set:function(e){p=!!e,this.hasBeenReset=!0}},line:{enumerable:!0,get:function(){return m},set:function(e){if(typeof e!=`number`&&e!==n)throw SyntaxError(`Line: an invalid number or illegal string was specified.`);m=e,this.hasBeenReset=!0}},lineAlign:{enumerable:!0,get:function(){return h},set:function(e){var t=o(e);t?(h=t,this.hasBeenReset=!0):console.warn(`lineAlign: an invalid or illegal string was specified.`)}},position:{enumerable:!0,get:function(){return g},set:function(e){if(e<0||e>100)throw Error(`Position must be between 0 and 100.`);g=e,this.hasBeenReset=!0}},positionAlign:{enumerable:!0,get:function(){return _},set:function(e){var t=o(e);t?(_=t,this.hasBeenReset=!0):console.warn(`positionAlign: an invalid or illegal string was specified.`)}},size:{enumerable:!0,get:function(){return v},set:function(e){if(e<0||e>100)throw Error(`Size must be between 0 and 100.`);v=e,this.hasBeenReset=!0}},align:{enumerable:!0,get:function(){return y},set:function(e){var t=o(e);if(!t)throw SyntaxError(`align: an invalid or illegal alignment string was specified.`);y=t,this.hasBeenReset=!0}}}),this.displayState=void 0}s.prototype.getCueAsHTML=function(){return WebVTT.convertCueToDOMTree(window,this.text)},t.exports=s})),de=N(((e,t)=>{var n={"":!0,up:!0};function r(e){return typeof e==`string`&&n[e.toLowerCase()]?e.toLowerCase():!1}function i(e){return typeof e==`number`&&e>=0&&e<=100}function a(){var e=100,t=3,n=0,a=100,o=0,s=100,c=``;Object.defineProperties(this,{width:{enumerable:!0,get:function(){return e},set:function(t){if(!i(t))throw Error(`Width must be between 0 and 100.`);e=t}},lines:{enumerable:!0,get:function(){return t},set:function(e){if(typeof e!=`number`)throw TypeError(`Lines must be set to a number.`);t=e}},regionAnchorY:{enumerable:!0,get:function(){return a},set:function(e){if(!i(e))throw Error(`RegionAnchorX must be between 0 and 100.`);a=e}},regionAnchorX:{enumerable:!0,get:function(){return n},set:function(e){if(!i(e))throw Error(`RegionAnchorY must be between 0 and 100.`);n=e}},viewportAnchorY:{enumerable:!0,get:function(){return s},set:function(e){if(!i(e))throw Error(`ViewportAnchorY must be between 0 and 100.`);s=e}},viewportAnchorX:{enumerable:!0,get:function(){return o},set:function(e){if(!i(e))throw Error(`ViewportAnchorX must be between 0 and 100.`);o=e}},scroll:{enumerable:!0,get:function(){return c},set:function(e){var t=r(e);t===!1?console.warn(`Scroll: an invalid or illegal string was specified.`):c=t}}})}t.exports=a})),fe=N(((e,t)=>{var n=te(),r=t.exports={WebVTT:le(),VTTCue:ue(),VTTRegion:de()};n.vttjs=r,n.WebVTT=r.WebVTT;var i=r.VTTCue,a=r.VTTRegion,o=n.VTTCue,s=n.VTTRegion;r.shim=function(){n.VTTCue=i,n.VTTRegion=a},r.restore=function(){n.VTTCue=o,n.VTTRegion=s},n.VTTCue||r.shim()})),I=P(te()),L=P(re()),R=P(ce()),pe=P(fe());function me(){return me=Object.assign?Object.assign.bind():function(e){for(var t=1;t-1},t.trigger=function(e){var t=this.listeners[e];if(t)if(arguments.length===2)for(var n=t.length,r=0;r-1;t=this.buffer.indexOf(` `))this.trigger(`data`,this.buffer.substring(0,t)),this.buffer=this.buffer.substring(t+1)}},xe=` `,Se=function(e){let t=/([0-9.]*)?@?([0-9.]*)?/.exec(e||``),n={};return t[1]&&(n.length=parseInt(t[1],10)),t[2]&&(n.offset=parseInt(t[2],10)),n},Ce=function(){return RegExp(`(?:^|,)((?:[^=]*)=(?:"[^"]*"|[^,]*))`)},we=function(e){let t={};if(!e)return t;let n=e.split(Ce()),r=n.length,i;for(;r--;)n[r]!==``&&(i=/([^=]*)=(.*)/.exec(n[r]).slice(1),i[0]=i[0].replace(/^\s+|\s+$/g,``),i[1]=i[1].replace(/^\s+|\s+$/g,``),i[1]=i[1].replace(/^['"](.*)['"]$/g,`$1`),t[i[0]]=i[1]);return t},Te=e=>{let t=e.split(`x`),n={};return t[0]&&(n.width=parseInt(t[0],10)),t[1]&&(n.height=parseInt(t[1],10)),n},Ee=class extends _e{constructor(){super(),this.customParsers=[],this.tagMappers=[]}push(e){let t,n;if(e=e.trim(),e.length!==0){if(e[0]!==`#`){this.trigger(`data`,{type:`uri`,uri:e});return}this.tagMappers.reduce((t,n)=>{let r=n(e);return r===e?t:t.concat([r])},[e]).forEach(e=>{for(let t=0;te),this.customParsers.push(i=>{if(e.exec(i))return this.trigger(`data`,{type:`custom`,data:n(i),customType:t,segment:r}),!0})}addTagMapper({expression:e,map:t}){this.tagMappers.push(n=>e.test(n)?t(n):n)}},De=e=>e.toLowerCase().replace(/-(\w)/g,e=>e[1].toUpperCase()),Oe=function(e){let t={};return Object.keys(e).forEach(function(n){t[De(n)]=e[n]}),t},ke=function(e){let{serverControl:t,targetDuration:n,partTargetDuration:r}=e;if(!t)return;let i=`#EXT-X-SERVER-CONTROL`,a=`holdBack`,o=`partHoldBack`,s=n&&n*3,c=r&&r*2;n&&!t.hasOwnProperty(a)&&(t[a]=s,this.trigger(`info`,{message:`${i} defaulting HOLD-BACK to targetDuration * 3 (${s}).`})),s&&t[a]{r.uri||!r.parts&&!r.preloadHints||(!r.map&&i&&(r.map=i),!r.key&&a&&(r.key=a),!r.timeline&&typeof l==`number`&&(r.timeline=l),this.manifest.preloadSegment=r)}),this.parseStream.on(`data`,function(e){let p,m;if(t.manifest.definitions){for(let n in t.manifest.definitions)if(e.uri&&=e.uri.replace(`{$${n}}`,t.manifest.definitions[n]),e.attributes)for(let r in e.attributes)typeof e.attributes[r]==`string`&&(e.attributes[r]=e.attributes[r].replace(`{$${n}}`,t.manifest.definitions[n]))}({tag(){({version(){e.version&&(this.manifest.version=e.version)},"allow-cache"(){this.manifest.allowCache=e.allowed,`allowed`in e||(this.trigger(`info`,{message:`defaulting allowCache to YES`}),this.manifest.allowCache=!0)},byterange(){let t={};`length`in e&&(r.byterange=t,t.length=e.length,`offset`in e||(e.offset=u)),`offset`in e&&(r.byterange=t,t.offset=e.offset),u=t.offset+t.length},endlist(){this.manifest.endList=!0},inf(){`mediaSequence`in this.manifest||(this.manifest.mediaSequence=0,this.trigger(`info`,{message:`defaulting media sequence to zero`})),`discontinuitySequence`in this.manifest||(this.manifest.discontinuitySequence=0,this.trigger(`info`,{message:`defaulting discontinuity sequence to zero`})),e.title&&(r.title=e.title),e.duration>0&&(r.duration=e.duration),e.duration===0&&(r.duration=.01,this.trigger(`info`,{message:`updating zero segment duration to a small value`})),this.manifest.segments=n},key(){if(!e.attributes){this.trigger(`warn`,{message:`ignoring key declaration without attribute list`});return}if(e.attributes.METHOD===`NONE`){a=null;return}if(!e.attributes.URI){this.trigger(`warn`,{message:`ignoring key declaration without URI`});return}if(e.attributes.KEYFORMAT===`com.apple.streamingkeydelivery`){this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection[`com.apple.fps.1_0`]={attributes:e.attributes};return}if(e.attributes.KEYFORMAT===`com.microsoft.playready`){this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection[`com.microsoft.playready`]={uri:e.attributes.URI};return}if(e.attributes.KEYFORMAT===`urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed`){if([`SAMPLE-AES`,`SAMPLE-AES-CTR`,`SAMPLE-AES-CENC`].indexOf(e.attributes.METHOD)===-1){this.trigger(`warn`,{message:`invalid key method provided for Widevine`});return}if(e.attributes.METHOD===`SAMPLE-AES-CENC`&&this.trigger(`warn`,{message:`SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead`}),e.attributes.URI.substring(0,23)!==`data:text/plain;base64,`){this.trigger(`warn`,{message:`invalid key URI provided for Widevine`});return}if(!(e.attributes.KEYID&&e.attributes.KEYID.substring(0,2)===`0x`)){this.trigger(`warn`,{message:`invalid key ID provided for Widevine`});return}this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection[`com.widevine.alpha`]={attributes:{schemeIdUri:e.attributes.KEYFORMAT,keyId:e.attributes.KEYID.substring(2)},pssh:ye(e.attributes.URI.split(`,`)[1])};return}e.attributes.METHOD||this.trigger(`warn`,{message:`defaulting key method to AES-128`}),a={method:e.attributes.METHOD||`AES-128`,uri:e.attributes.URI},e.attributes.IV!==void 0&&(a.iv=e.attributes.IV)},"media-sequence"(){if(!isFinite(e.number)){this.trigger(`warn`,{message:`ignoring invalid media sequence: `+e.number});return}this.manifest.mediaSequence=e.number},"discontinuity-sequence"(){if(!isFinite(e.number)){this.trigger(`warn`,{message:`ignoring invalid discontinuity sequence: `+e.number});return}this.manifest.discontinuitySequence=e.number,l=e.number},"playlist-type"(){if(!/VOD|EVENT/.test(e.playlistType)){this.trigger(`warn`,{message:`ignoring unknown playlist type: `+e.playlist});return}this.manifest.playlistType=e.playlistType},map(){i={},e.uri&&(i.uri=e.uri),e.byterange&&(i.byterange=e.byterange),a&&(i.key=a)},"stream-inf"(){if(this.manifest.playlists=n,this.manifest.mediaGroups=this.manifest.mediaGroups||c,!e.attributes){this.trigger(`warn`,{message:`ignoring empty stream-inf attributes`});return}r.attributes||={},me(r.attributes,e.attributes)},media(){if(this.manifest.mediaGroups=this.manifest.mediaGroups||c,!(e.attributes&&e.attributes.TYPE&&e.attributes[`GROUP-ID`]&&e.attributes.NAME)){this.trigger(`warn`,{message:`ignoring incomplete or missing media group`});return}let t=this.manifest.mediaGroups[e.attributes.TYPE];t[e.attributes[`GROUP-ID`]]=t[e.attributes[`GROUP-ID`]]||{},p=t[e.attributes[`GROUP-ID`]],m={default:/yes/i.test(e.attributes.DEFAULT)},m.default?m.autoselect=!0:m.autoselect=/yes/i.test(e.attributes.AUTOSELECT),e.attributes.LANGUAGE&&(m.language=e.attributes.LANGUAGE),e.attributes.URI&&(m.uri=e.attributes.URI),e.attributes[`INSTREAM-ID`]&&(m.instreamId=e.attributes[`INSTREAM-ID`]),e.attributes.CHARACTERISTICS&&(m.characteristics=e.attributes.CHARACTERISTICS),e.attributes.FORCED&&(m.forced=/yes/i.test(e.attributes.FORCED)),p[e.attributes.NAME]=m},discontinuity(){l+=1,r.discontinuity=!0,this.manifest.discontinuityStarts.push(n.length)},"program-date-time"(){this.manifest.dateTimeString===void 0&&(this.manifest.dateTimeString=e.dateTimeString,this.manifest.dateTimeObject=e.dateTimeObject),r.dateTimeString=e.dateTimeString,r.dateTimeObject=e.dateTimeObject;let{lastProgramDateTime:t}=this;this.lastProgramDateTime=new Date(e.dateTimeString).getTime(),t===null&&this.manifest.segments.reduceRight((e,t)=>(t.programDateTime=e-t.duration*1e3,t.programDateTime),this.lastProgramDateTime)},targetduration(){if(!isFinite(e.duration)||e.duration<0){this.trigger(`warn`,{message:`ignoring invalid target duration: `+e.duration});return}this.manifest.targetDuration=e.duration,ke.call(this,this.manifest)},start(){if(!e.attributes||isNaN(e.attributes[`TIME-OFFSET`])){this.trigger(`warn`,{message:`ignoring start declaration without appropriate attribute list`});return}this.manifest.start={timeOffset:e.attributes[`TIME-OFFSET`],precise:e.attributes.PRECISE}},"cue-out"(){r.cueOut=e.data},"cue-out-cont"(){r.cueOutCont=e.data},"cue-in"(){r.cueIn=e.data},skip(){this.manifest.skip=Oe(e.attributes),this.warnOnMissingAttributes_(`#EXT-X-SKIP`,e.attributes,[`SKIPPED-SEGMENTS`])},part(){o=!0;let t=this.manifest.segments.length,n=Oe(e.attributes);r.parts=r.parts||[],r.parts.push(n),n.byterange&&(n.byterange.hasOwnProperty(`offset`)||(n.byterange.offset=d),d=n.byterange.offset+n.byterange.length);let i=r.parts.length-1;this.warnOnMissingAttributes_(`#EXT-X-PART #${i} for segment #${t}`,e.attributes,[`URI`,`DURATION`]),this.manifest.renditionReports&&this.manifest.renditionReports.forEach((e,t)=>{e.hasOwnProperty(`lastPart`)||this.trigger(`warn`,{message:`#EXT-X-RENDITION-REPORT #${t} lacks required attribute(s): LAST-PART`})})},"server-control"(){let t=this.manifest.serverControl=Oe(e.attributes);t.hasOwnProperty(`canBlockReload`)||(t.canBlockReload=!1,this.trigger(`info`,{message:`#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false`})),ke.call(this,this.manifest),t.canSkipDateranges&&!t.hasOwnProperty(`canSkipUntil`)&&this.trigger(`warn`,{message:`#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set`})},"preload-hint"(){let t=this.manifest.segments.length,n=Oe(e.attributes),i=n.type&&n.type===`PART`;r.preloadHints=r.preloadHints||[],r.preloadHints.push(n),n.byterange&&(n.byterange.hasOwnProperty(`offset`)||(n.byterange.offset=i?d:0,i&&(d=n.byterange.offset+n.byterange.length)));let a=r.preloadHints.length-1;if(this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${a} for segment #${t}`,e.attributes,[`TYPE`,`URI`]),n.type)for(let e=0;ee.id===n.id);this.manifest.dateRanges[e]=me(this.manifest.dateRanges[e],n),f[n.id]=me(f[n.id],n),this.manifest.dateRanges.pop()}},"independent-segments"(){this.manifest.independentSegments=!0},"i-frames-only"(){this.manifest.iFramesOnly=!0,this.requiredCompatibilityversion(this.manifest.version,4)},"content-steering"(){this.manifest.contentSteering=Oe(e.attributes),this.warnOnMissingAttributes_(`#EXT-X-CONTENT-STEERING`,e.attributes,[`SERVER-URI`])},define(){this.manifest.definitions=this.manifest.definitions||{};let t=(e,t)=>{if(e in this.manifest.definitions){this.trigger(`error`,{message:`EXT-X-DEFINE: Duplicate name ${e}`});return}this.manifest.definitions[e]=t};if(`QUERYPARAM`in e.attributes){if(`NAME`in e.attributes||`IMPORT`in e.attributes){this.trigger(`error`,{message:`EXT-X-DEFINE: Invalid attributes`});return}let n=this.params.get(e.attributes.QUERYPARAM);if(!n){this.trigger(`error`,{message:`EXT-X-DEFINE: No query param ${e.attributes.QUERYPARAM}`});return}t(e.attributes.QUERYPARAM,decodeURIComponent(n));return}if(`NAME`in e.attributes){if(`IMPORT`in e.attributes){this.trigger(`error`,{message:`EXT-X-DEFINE: Invalid attributes`});return}if(!(`VALUE`in e.attributes)||typeof e.attributes.VALUE!=`string`){this.trigger(`error`,{message:`EXT-X-DEFINE: No value for ${e.attributes.NAME}`});return}t(e.attributes.NAME,e.attributes.VALUE);return}if(`IMPORT`in e.attributes){if(!this.mainDefinitions[e.attributes.IMPORT]){this.trigger(`error`,{message:`EXT-X-DEFINE: No value ${e.attributes.IMPORT} to import, or IMPORT used on main playlist`});return}t(e.attributes.IMPORT,this.mainDefinitions[e.attributes.IMPORT]);return}this.trigger(`error`,{message:`EXT-X-DEFINE: No attribute`})},"i-frame-playlist"(){this.manifest.iFramePlaylists.push({attributes:e.attributes,uri:e.uri,timeline:l}),this.warnOnMissingAttributes_(`#EXT-X-I-FRAME-STREAM-INF`,e.attributes,[`BANDWIDTH`,`URI`])}}[e.tagType]||s).call(t)},uri(){r.uri=e.uri,n.push(r),this.manifest.targetDuration&&!(`duration`in r)&&(this.trigger(`warn`,{message:`defaulting segment duration to the target duration`}),r.duration=this.manifest.targetDuration),a&&(r.key=a),r.timeline=l,i&&(r.map=i),d=0,this.lastProgramDateTime!==null&&(r.programDateTime=this.lastProgramDateTime,this.lastProgramDateTime+=r.duration*1e3),r={}},comment(){},custom(){e.segment?(r.custom=r.custom||{},r.custom[e.customType]=e.data):(this.manifest.custom=this.manifest.custom||{},this.manifest.custom[e.customType]=e.data)}})[e.type].call(t)})}requiredCompatibilityversion(e,t){(el&&(c-=l,c-=l,c-=Ye(2))}return Number(c)},Qe=function(e,t){var n=(t===void 0?{}:t).le,r=n===void 0?!1:n;(typeof e!=`bigint`&&typeof e!=`number`||typeof e==`number`&&e!==e)&&(e=0),e=Ye(e);for(var i=Ke(e),a=new Uint8Array(new ArrayBuffer(i)),o=0;o=t.length&&c.call(t,function(t,n){return t===(s[n]?s[n]&e[a+n]:e[a+n])})},rt=function(e,t,n){t.forEach(function(t){for(var r in e.mediaGroups[t])for(var i in e.mediaGroups[t][r]){var a=e.mediaGroups[t][r][i];n(a,t,r,i)}})},it=N((e=>{function t(e,t,n){if(n===void 0&&(n=Array.prototype),e&&typeof n.find==`function`)return n.find.call(e,t);for(var r=0;r{var t=it(),n=t.find,r=t.NAMESPACE;function i(e){return e!==``}function a(e){return e?e.split(/[\t\n\f\r ]+/).filter(i):[]}function o(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function s(e){if(!e)return[];var t=a(e);return Object.keys(t.reduce(o,{}))}function c(e){return function(t){return e&&e.indexOf(t)!==-1}}function l(e,t){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])}function u(e,t){var n=e.prototype;if(!(n instanceof t)){function r(){}r.prototype=t.prototype,r=new r,l(n,r),e.prototype=n=r}n.constructor!=e&&(typeof e!=`function`&&console.error(`unknown Class:`+e),n.constructor=e)}var d={},f=d.ELEMENT_NODE=1,p=d.ATTRIBUTE_NODE=2,m=d.TEXT_NODE=3,h=d.CDATA_SECTION_NODE=4,g=d.ENTITY_REFERENCE_NODE=5,_=d.ENTITY_NODE=6,v=d.PROCESSING_INSTRUCTION_NODE=7,y=d.COMMENT_NODE=8,b=d.DOCUMENT_NODE=9,x=d.DOCUMENT_TYPE_NODE=10,S=d.DOCUMENT_FRAGMENT_NODE=11,C=d.NOTATION_NODE=12,w={},T={};w.INDEX_SIZE_ERR=(T[1]=`Index size error`,1),w.DOMSTRING_SIZE_ERR=(T[2]=`DOMString size error`,2);var E=w.HIERARCHY_REQUEST_ERR=(T[3]=`Hierarchy request error`,3);w.WRONG_DOCUMENT_ERR=(T[4]=`Wrong document`,4);var D=w.INVALID_CHARACTER_ERR=(T[5]=`Invalid character`,5);w.NO_DATA_ALLOWED_ERR=(T[6]=`No data allowed`,6),w.NO_MODIFICATION_ALLOWED_ERR=(T[7]=`No modification allowed`,7);var O=w.NOT_FOUND_ERR=(T[8]=`Not found`,8);w.NOT_SUPPORTED_ERR=(T[9]=`Not supported`,9);var k=w.INUSE_ATTRIBUTE_ERR=(T[10]=`Attribute in use`,10),A=w.INVALID_STATE_ERR=(T[11]=`Invalid state`,11);w.SYNTAX_ERR=(T[12]=`Syntax error`,12),w.INVALID_MODIFICATION_ERR=(T[13]=`Invalid modification`,13),w.NAMESPACE_ERR=(T[14]=`Invalid namespace`,14),w.INVALID_ACCESS_ERR=(T[15]=`Invalid access`,15);function j(e,t){if(t instanceof Error)var n=t;else n=this,Error.call(this,T[e]),this.message=T[e],Error.captureStackTrace&&Error.captureStackTrace(this,j);return n.code=e,t&&(this.message=this.message+`: `+t),n}j.prototype=Error.prototype,l(w,j);function M(){}M.prototype={length:0,item:function(e){return e>=0&&e=0){for(var i=t.length-1;r0},lookupPrefix:function(e){for(var t=this;t;){var n=t._nsMap;if(n){for(var r in n)if(Object.prototype.hasOwnProperty.call(n,r)&&n[r]===e)return r}t=t.nodeType==p?t.ownerDocument:t.parentNode}return null},lookupNamespaceURI:function(e){for(var t=this;t;){var n=t._nsMap;if(n&&Object.prototype.hasOwnProperty.call(n,e))return n[e];t=t.nodeType==p?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){return this.lookupPrefix(e)==null}};function ae(e){return e==`<`&&`<`||e==`>`&&`>`||e==`&`&&`&`||e==`"`&&`"`||`&#`+e.charCodeAt()+`;`}l(d,F),l(d,F.prototype);function oe(e,t){return se(e,null,{enter:function(e){return t(e)?se.STOP:!0}})===se.STOP}function se(e,t,n){for(var r=[{node:e,context:t,phase:se.ENTER}];r.length>0;){var i=r.pop();if(i.phase===se.ENTER){var a=n.enter(i.node,i.context);if(a===se.STOP)return se.STOP;if(r.push({node:i.node,context:a,phase:se.EXIT}),a==null)continue;for(var o=i.node.lastChild;o;)r.push({node:o,context:a,phase:se.ENTER}),o=o.previousSibling}else n.exit&&n.exit(i.node,i.context)}}se.STOP=Symbol(`walkDOM.STOP`),se.ENTER=0,se.EXIT=1;function ce(){this.ownerDocument=this}function le(e,t,n){e&&e._inc++,n.namespaceURI===r.XMLNS&&(t._nsMap[n.prefix?n.localName:``]=n.value)}function ue(e,t,n,i){e&&e._inc++,n.namespaceURI===r.XMLNS&&delete t._nsMap[n.prefix?n.localName:``]}function de(e,t,n){if(e&&e._inc){e._inc++;var r=t.childNodes;if(n)r[r.length++]=n;else{for(var i=t.firstChild,a=0;i;)r[a++]=i,i=i.nextSibling;r.length=a,delete r[r.length]}}}function fe(e,t){var n=t.previousSibling,r=t.nextSibling;return n?n.nextSibling=r:e.firstChild=r,r?r.previousSibling=n:e.lastChild=n,t.parentNode=null,t.previousSibling=null,t.nextSibling=null,de(e.ownerDocument,e),t}function I(e){return e&&(e.nodeType===F.DOCUMENT_NODE||e.nodeType===F.DOCUMENT_FRAGMENT_NODE||e.nodeType===F.ELEMENT_NODE)}function L(e){return e&&(pe(e)||me(e)||R(e)||e.nodeType===F.DOCUMENT_FRAGMENT_NODE||e.nodeType===F.COMMENT_NODE||e.nodeType===F.PROCESSING_INSTRUCTION_NODE)}function R(e){return e&&e.nodeType===F.DOCUMENT_TYPE_NODE}function pe(e){return e&&e.nodeType===F.ELEMENT_NODE}function me(e){return e&&e.nodeType===F.TEXT_NODE}function he(e,t){var r=e.childNodes||[];if(n(r,pe)||R(t))return!1;var i=n(r,R);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function ge(e,t){var r=e.childNodes||[];function i(e){return pe(e)&&e!==t}if(n(r,i))return!1;var a=n(r,R);return!(t&&a&&r.indexOf(a)>r.indexOf(t))}function _e(e,t,n){if(!I(e))throw new j(E,`Unexpected parent node type `+e.nodeType);if(n&&n.parentNode!==e)throw new j(O,`child not in parent`);if(!L(t)||R(t)&&e.nodeType!==F.DOCUMENT_NODE)throw new j(E,`Unexpected node type `+t.nodeType+` for parent node type `+e.nodeType)}function ve(e,t,r){var i=e.childNodes||[],a=t.childNodes||[];if(t.nodeType===F.DOCUMENT_FRAGMENT_NODE){var o=a.filter(pe);if(o.length>1||n(a,me))throw new j(E,`More than one element or text in fragment`);if(o.length===1&&!he(e,r))throw new j(E,`Element in fragment can not be inserted before doctype`)}if(pe(t)&&!he(e,r))throw new j(E,`Only one element can be added and only after doctype`);if(R(t)){if(n(i,R))throw new j(E,`Only one doctype is allowed`);var s=n(i,pe);if(r&&i.indexOf(s)1||n(a,me))throw new j(E,`More than one element or text in fragment`);if(o.length===1&&!ge(e,r))throw new j(E,`Element in fragment can not be inserted before doctype`)}if(pe(t)&&!ge(e,r))throw new j(E,`Only one element can be added and only after doctype`);if(R(t)){function e(e){return R(e)&&e!==r}if(n(i,e))throw new j(E,`Only one doctype is allowed`);var s=n(i,pe);if(r&&i.indexOf(s)0&&oe(n.documentElement,function(i){if(i!==n&&i.nodeType===f){var a=i.getAttribute(`class`);if(a){var o=e===a;if(!o){var l=s(a);o=t.every(c(l))}o&&r.push(i)}}}),r})},createElement:function(e){var t=new Ce;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new M;var n=t.attributes=new P;return n._ownerElement=t,t},createDocumentFragment:function(){var e=new Ne;return e.ownerDocument=this,e.childNodes=new M,e},createTextNode:function(e){var t=new Ee;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new De;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf(`]]>`)!==-1)throw new j(D,`data contains "]]>"`);var t=new Oe;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var n=new Pe;return n.ownerDocument=this,n.tagName=n.nodeName=n.target=e,n.nodeValue=n.data=t,n},createAttribute:function(e){var t=new we;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){var t=new Me;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var n=new Ce,r=t.split(`:`),i=n.attributes=new P;return n.childNodes=new M,n.ownerDocument=this,n.nodeName=t,n.tagName=t,n.namespaceURI=e,r.length==2?(n.prefix=r[0],n.localName=r[1]):n.localName=t,i._ownerElement=n,n},createAttributeNS:function(e,t){var n=new we,r=t.split(`:`);return n.ownerDocument=this,n.nodeName=t,n.name=t,n.namespaceURI=e,n.specified=!0,r.length==2?(n.prefix=r[0],n.localName=r[1]):n.localName=t,n}},u(ce,F);function Ce(){this._nsMap={}}Ce.prototype={nodeType:f,hasAttribute:function(e){return this.getAttributeNode(e)!=null},getAttribute:function(e){var t=this.getAttributeNode(e);return t&&t.value||``},getAttributeNode:function(e){return this.attributes.getNamedItem(e)},setAttribute:function(e,t){var n=this.ownerDocument.createAttribute(e);n.value=n.nodeValue=``+t,this.setAttributeNode(n)},removeAttribute:function(e){var t=this.getAttributeNode(e);t&&this.removeAttributeNode(t)},appendChild:function(e){return e.nodeType===S?this.insertBefore(e,null):Se(this,e)},setAttributeNode:function(e){return this.attributes.setNamedItem(e)},setAttributeNodeNS:function(e){return this.attributes.setNamedItemNS(e)},removeAttributeNode:function(e){return this.attributes.removeNamedItem(e.nodeName)},removeAttributeNS:function(e,t){var n=this.getAttributeNodeNS(e,t);n&&this.removeAttributeNode(n)},hasAttributeNS:function(e,t){return this.getAttributeNodeNS(e,t)!=null},getAttributeNS:function(e,t){var n=this.getAttributeNodeNS(e,t);return n&&n.value||``},setAttributeNS:function(e,t,n){var r=this.ownerDocument.createAttributeNS(e,t);r.value=r.nodeValue=``+n,this.setAttributeNode(r)},getAttributeNodeNS:function(e,t){return this.attributes.getNamedItemNS(e,t)},getElementsByTagName:function(e){return new N(this,function(t){var n=[];return oe(t,function(r){r!==t&&r.nodeType==f&&(e===`*`||r.tagName==e)&&n.push(r)}),n})},getElementsByTagNameNS:function(e,t){return new N(this,function(n){var r=[];return oe(n,function(i){i!==n&&i.nodeType===f&&(e===`*`||i.namespaceURI===e)&&(t===`*`||i.localName==t)&&r.push(i)}),r})}},ce.prototype.getElementsByTagName=Ce.prototype.getElementsByTagName,ce.prototype.getElementsByTagNameNS=Ce.prototype.getElementsByTagNameNS,u(Ce,F);function we(){}we.prototype.nodeType=p,u(we,F);function Te(){}Te.prototype={data:``,substringData:function(e,t){return this.data.substring(e,e+t)},appendData:function(e){e=this.data+e,this.nodeValue=this.data=e,this.length=e.length},insertData:function(e,t){this.replaceData(e,0,t)},appendChild:function(e){throw Error(T[E])},deleteData:function(e,t){this.replaceData(e,t,``)},replaceData:function(e,t,n){var r=this.data.substring(0,e),i=this.data.substring(e+t);n=r+n+i,this.nodeValue=this.data=n,this.length=n.length}},u(Te,F);function Ee(){}Ee.prototype={nodeName:`#text`,nodeType:m,splitText:function(e){var t=this.data,n=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var r=this.ownerDocument.createTextNode(n);return this.parentNode&&this.parentNode.insertBefore(r,this.nextSibling),r}},u(Ee,Te);function De(){}De.prototype={nodeName:`#comment`,nodeType:y},u(De,Te);function Oe(){}Oe.prototype={nodeName:`#cdata-section`,nodeType:h},u(Oe,Te);function ke(){}ke.prototype.nodeType=x,u(ke,F);function Ae(){}Ae.prototype.nodeType=C,u(Ae,F);function je(){}je.prototype.nodeType=_,u(je,F);function Me(){}Me.prototype.nodeType=g,u(Me,F);function Ne(){}Ne.prototype.nodeName=`#document-fragment`,Ne.prototype.nodeType=S,u(Ne,F);function Pe(){}Pe.prototype.nodeType=v,u(Pe,F);function Fe(){}Fe.prototype.serializeToString=function(e,t,n,r){return Ie.call(e,t,n,r)},F.prototype.toString=Ie;function Ie(e,t,n){var r=!!n&&!!n.requireWellFormed,i=[],a=this.nodeType==9&&this.documentElement||this,o=a.prefix,s=a.namespaceURI;if(s&&o==null){var o=a.lookupPrefix(s);if(o==null)var c=[{namespace:s,prefix:null}]}return ze(this,i,e,t,c,r),i.join(``)}function Le(e,t,n){var i=e.prefix||``,a=e.namespaceURI;if(!a||i===`xml`&&a===r.XML||a===r.XMLNS)return!1;for(var o=n.length;o--;){var s=n[o];if(s.prefix===i)return s.namespace!==a}return!0}function Re(e,t,n){e.push(` `,t,`="`,n.replace(/[<>&"\t\n\r]/g,ae),`"`)}function ze(e,t,n,i,a,o){a||=[],se(e,{ns:a,isHTML:n},{enter:function(e,n){var a=n.ns,s=n.isHTML;if(i)if(e=i(e),e){if(typeof e==`string`)return t.push(e),null}else return null;switch(e.nodeType){case f:var c=e.attributes,l=c.length,u=e.tagName;s=r.isHTML(e.namespaceURI)||s;var d=u;if(!s&&!e.prefix&&e.namespaceURI){for(var _,C=0;C=0;w--){var T=a[w];if(T.prefix===``&&T.namespace===e.namespaceURI){_=T.namespace;break}}if(_!==e.namespaceURI)for(var w=a.length-1;w>=0;w--){var T=a[w];if(T.namespace===e.namespaceURI){T.prefix&&(d=T.prefix+`:`+u);break}}}t.push(`<`,d);for(var E=a.slice(),D=0;D`),s&&/^script$/i.test(u)){for(;P;)P.data?t.push(P.data):ze(P,t,s,i,E.slice(),o),P=P.nextSibling;return t.push(``),null}return{ns:E,isHTML:s,tag:d}}else return t.push(`/>`),null;case b:case S:return{ns:a.slice(),isHTML:s,tag:null};case p:return Re(t,e.name,e.value),null;case m:return t.push(e.data.replace(/[<&>]/g,ae)),null;case h:if(o&&e.data.indexOf(`]]>`)!==-1)throw new j(A,`The CDATASection data contains "]]>"`);return t.push(`/g,`]]]]>`),`]]>`),null;case y:if(o&&e.data.indexOf(`-->`)!==-1)throw new j(A,`The comment node data contains "-->"`);return t.push(``),null;case x:if(o){if(e.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(e.publicId))throw new j(A,`DocumentType publicId is not a valid PubidLiteral`);if(e.systemId&&!/^("[^"]*"|'[^']*')$/.test(e.systemId))throw new j(A,`DocumentType systemId is not a valid SystemLiteral`);if(e.internalSubset&&e.internalSubset.indexOf(`]>`)!==-1)throw new j(A,`DocumentType internalSubset contains "]>"`)}var te=e.publicId,ne=e.systemId;if(t.push(``);else if(ne&&ne!=`.`)t.push(` SYSTEM `,ne,`>`);else{var re=e.internalSubset;re&&t.push(` [`,re,`]`),t.push(`>`)}return null;case v:if(o&&e.data.indexOf(`?>`)!==-1)throw new j(A,`The ProcessingInstruction data contains "?>"`);return t.push(``),null;case g:return t.push(`&`,e.nodeName,`;`),null;default:return t.push(`??`,e.nodeName),null}},exit:function(e,n){n&&n.tag&&t.push(``)}})}function Be(e,t,n){var r;return se(t,null,{enter:function(t,i){var a=t.cloneNode(!1);return a.ownerDocument=e,a.parentNode=null,i===null?r=a:i.appendChild(a),t.nodeType===p||n?a:null}}),r}function Ve(e,t,n){var r;return se(t,null,{enter:function(t,i){var a=new t.constructor;for(var o in t)if(Object.prototype.hasOwnProperty.call(t,o)){var s=t[o];typeof s!=`object`&&s!=a[o]&&(a[o]=s)}t.childNodes&&(a.childNodes=new M),a.ownerDocument=e;var c=n;switch(a.nodeType){case f:var l=t.attributes,u=a.attributes=new P,d=l.length;u._ownerElement=a;for(var m=0;m{var t=it().freeze;e.XML_ENTITIES=t({amp:`&`,apos:`'`,gt:`>`,lt:`<`,quot:`"`}),e.HTML_ENTITIES=t({Aacute:`Á`,aacute:`á`,Abreve:`Ă`,abreve:`ă`,ac:`∾`,acd:`∿`,acE:`∾̳`,Acirc:`Â`,acirc:`â`,acute:`´`,Acy:`А`,acy:`а`,AElig:`Æ`,aelig:`æ`,af:`⁡`,Afr:`𝔄`,afr:`𝔞`,Agrave:`À`,agrave:`à`,alefsym:`ℵ`,aleph:`ℵ`,Alpha:`Α`,alpha:`α`,Amacr:`Ā`,amacr:`ā`,amalg:`⨿`,AMP:`&`,amp:`&`,And:`⩓`,and:`∧`,andand:`⩕`,andd:`⩜`,andslope:`⩘`,andv:`⩚`,ang:`∠`,ange:`⦤`,angle:`∠`,angmsd:`∡`,angmsdaa:`⦨`,angmsdab:`⦩`,angmsdac:`⦪`,angmsdad:`⦫`,angmsdae:`⦬`,angmsdaf:`⦭`,angmsdag:`⦮`,angmsdah:`⦯`,angrt:`∟`,angrtvb:`⊾`,angrtvbd:`⦝`,angsph:`∢`,angst:`Å`,angzarr:`⍼`,Aogon:`Ą`,aogon:`ą`,Aopf:`𝔸`,aopf:`𝕒`,ap:`≈`,apacir:`⩯`,apE:`⩰`,ape:`≊`,apid:`≋`,apos:`'`,ApplyFunction:`⁡`,approx:`≈`,approxeq:`≊`,Aring:`Å`,aring:`å`,Ascr:`𝒜`,ascr:`𝒶`,Assign:`≔`,ast:`*`,asymp:`≈`,asympeq:`≍`,Atilde:`Ã`,atilde:`ã`,Auml:`Ä`,auml:`ä`,awconint:`∳`,awint:`⨑`,backcong:`≌`,backepsilon:`϶`,backprime:`‵`,backsim:`∽`,backsimeq:`⋍`,Backslash:`∖`,Barv:`⫧`,barvee:`⊽`,Barwed:`⌆`,barwed:`⌅`,barwedge:`⌅`,bbrk:`⎵`,bbrktbrk:`⎶`,bcong:`≌`,Bcy:`Б`,bcy:`б`,bdquo:`„`,becaus:`∵`,Because:`∵`,because:`∵`,bemptyv:`⦰`,bepsi:`϶`,bernou:`ℬ`,Bernoullis:`ℬ`,Beta:`Β`,beta:`β`,beth:`ℶ`,between:`≬`,Bfr:`𝔅`,bfr:`𝔟`,bigcap:`⋂`,bigcirc:`◯`,bigcup:`⋃`,bigodot:`⨀`,bigoplus:`⨁`,bigotimes:`⨂`,bigsqcup:`⨆`,bigstar:`★`,bigtriangledown:`▽`,bigtriangleup:`△`,biguplus:`⨄`,bigvee:`⋁`,bigwedge:`⋀`,bkarow:`⤍`,blacklozenge:`⧫`,blacksquare:`▪`,blacktriangle:`▴`,blacktriangledown:`▾`,blacktriangleleft:`◂`,blacktriangleright:`▸`,blank:`␣`,blk12:`▒`,blk14:`░`,blk34:`▓`,block:`█`,bne:`=⃥`,bnequiv:`≡⃥`,bNot:`⫭`,bnot:`⌐`,Bopf:`𝔹`,bopf:`𝕓`,bot:`⊥`,bottom:`⊥`,bowtie:`⋈`,boxbox:`⧉`,boxDL:`╗`,boxDl:`╖`,boxdL:`╕`,boxdl:`┐`,boxDR:`╔`,boxDr:`╓`,boxdR:`╒`,boxdr:`┌`,boxH:`═`,boxh:`─`,boxHD:`╦`,boxHd:`╤`,boxhD:`╥`,boxhd:`┬`,boxHU:`╩`,boxHu:`╧`,boxhU:`╨`,boxhu:`┴`,boxminus:`⊟`,boxplus:`⊞`,boxtimes:`⊠`,boxUL:`╝`,boxUl:`╜`,boxuL:`╛`,boxul:`┘`,boxUR:`╚`,boxUr:`╙`,boxuR:`╘`,boxur:`└`,boxV:`║`,boxv:`│`,boxVH:`╬`,boxVh:`╫`,boxvH:`╪`,boxvh:`┼`,boxVL:`╣`,boxVl:`╢`,boxvL:`╡`,boxvl:`┤`,boxVR:`╠`,boxVr:`╟`,boxvR:`╞`,boxvr:`├`,bprime:`‵`,Breve:`˘`,breve:`˘`,brvbar:`¦`,Bscr:`ℬ`,bscr:`𝒷`,bsemi:`⁏`,bsim:`∽`,bsime:`⋍`,bsol:`\\`,bsolb:`⧅`,bsolhsub:`⟈`,bull:`•`,bullet:`•`,bump:`≎`,bumpE:`⪮`,bumpe:`≏`,Bumpeq:`≎`,bumpeq:`≏`,Cacute:`Ć`,cacute:`ć`,Cap:`⋒`,cap:`∩`,capand:`⩄`,capbrcup:`⩉`,capcap:`⩋`,capcup:`⩇`,capdot:`⩀`,CapitalDifferentialD:`ⅅ`,caps:`∩︀`,caret:`⁁`,caron:`ˇ`,Cayleys:`ℭ`,ccaps:`⩍`,Ccaron:`Č`,ccaron:`č`,Ccedil:`Ç`,ccedil:`ç`,Ccirc:`Ĉ`,ccirc:`ĉ`,Cconint:`∰`,ccups:`⩌`,ccupssm:`⩐`,Cdot:`Ċ`,cdot:`ċ`,cedil:`¸`,Cedilla:`¸`,cemptyv:`⦲`,cent:`¢`,CenterDot:`·`,centerdot:`·`,Cfr:`ℭ`,cfr:`𝔠`,CHcy:`Ч`,chcy:`ч`,check:`✓`,checkmark:`✓`,Chi:`Χ`,chi:`χ`,cir:`○`,circ:`ˆ`,circeq:`≗`,circlearrowleft:`↺`,circlearrowright:`↻`,circledast:`⊛`,circledcirc:`⊚`,circleddash:`⊝`,CircleDot:`⊙`,circledR:`®`,circledS:`Ⓢ`,CircleMinus:`⊖`,CirclePlus:`⊕`,CircleTimes:`⊗`,cirE:`⧃`,cire:`≗`,cirfnint:`⨐`,cirmid:`⫯`,cirscir:`⧂`,ClockwiseContourIntegral:`∲`,CloseCurlyDoubleQuote:`”`,CloseCurlyQuote:`’`,clubs:`♣`,clubsuit:`♣`,Colon:`∷`,colon:`:`,Colone:`⩴`,colone:`≔`,coloneq:`≔`,comma:`,`,commat:`@`,comp:`∁`,compfn:`∘`,complement:`∁`,complexes:`ℂ`,cong:`≅`,congdot:`⩭`,Congruent:`≡`,Conint:`∯`,conint:`∮`,ContourIntegral:`∮`,Copf:`ℂ`,copf:`𝕔`,coprod:`∐`,Coproduct:`∐`,COPY:`©`,copy:`©`,copysr:`℗`,CounterClockwiseContourIntegral:`∳`,crarr:`↵`,Cross:`⨯`,cross:`✗`,Cscr:`𝒞`,cscr:`𝒸`,csub:`⫏`,csube:`⫑`,csup:`⫐`,csupe:`⫒`,ctdot:`⋯`,cudarrl:`⤸`,cudarrr:`⤵`,cuepr:`⋞`,cuesc:`⋟`,cularr:`↶`,cularrp:`⤽`,Cup:`⋓`,cup:`∪`,cupbrcap:`⩈`,CupCap:`≍`,cupcap:`⩆`,cupcup:`⩊`,cupdot:`⊍`,cupor:`⩅`,cups:`∪︀`,curarr:`↷`,curarrm:`⤼`,curlyeqprec:`⋞`,curlyeqsucc:`⋟`,curlyvee:`⋎`,curlywedge:`⋏`,curren:`¤`,curvearrowleft:`↶`,curvearrowright:`↷`,cuvee:`⋎`,cuwed:`⋏`,cwconint:`∲`,cwint:`∱`,cylcty:`⌭`,Dagger:`‡`,dagger:`†`,daleth:`ℸ`,Darr:`↡`,dArr:`⇓`,darr:`↓`,dash:`‐`,Dashv:`⫤`,dashv:`⊣`,dbkarow:`⤏`,dblac:`˝`,Dcaron:`Ď`,dcaron:`ď`,Dcy:`Д`,dcy:`д`,DD:`ⅅ`,dd:`ⅆ`,ddagger:`‡`,ddarr:`⇊`,DDotrahd:`⤑`,ddotseq:`⩷`,deg:`°`,Del:`∇`,Delta:`Δ`,delta:`δ`,demptyv:`⦱`,dfisht:`⥿`,Dfr:`𝔇`,dfr:`𝔡`,dHar:`⥥`,dharl:`⇃`,dharr:`⇂`,DiacriticalAcute:`´`,DiacriticalDot:`˙`,DiacriticalDoubleAcute:`˝`,DiacriticalGrave:"`",DiacriticalTilde:`˜`,diam:`⋄`,Diamond:`⋄`,diamond:`⋄`,diamondsuit:`♦`,diams:`♦`,die:`¨`,DifferentialD:`ⅆ`,digamma:`ϝ`,disin:`⋲`,div:`÷`,divide:`÷`,divideontimes:`⋇`,divonx:`⋇`,DJcy:`Ђ`,djcy:`ђ`,dlcorn:`⌞`,dlcrop:`⌍`,dollar:`$`,Dopf:`𝔻`,dopf:`𝕕`,Dot:`¨`,dot:`˙`,DotDot:`⃜`,doteq:`≐`,doteqdot:`≑`,DotEqual:`≐`,dotminus:`∸`,dotplus:`∔`,dotsquare:`⊡`,doublebarwedge:`⌆`,DoubleContourIntegral:`∯`,DoubleDot:`¨`,DoubleDownArrow:`⇓`,DoubleLeftArrow:`⇐`,DoubleLeftRightArrow:`⇔`,DoubleLeftTee:`⫤`,DoubleLongLeftArrow:`⟸`,DoubleLongLeftRightArrow:`⟺`,DoubleLongRightArrow:`⟹`,DoubleRightArrow:`⇒`,DoubleRightTee:`⊨`,DoubleUpArrow:`⇑`,DoubleUpDownArrow:`⇕`,DoubleVerticalBar:`∥`,DownArrow:`↓`,Downarrow:`⇓`,downarrow:`↓`,DownArrowBar:`⤓`,DownArrowUpArrow:`⇵`,DownBreve:`̑`,downdownarrows:`⇊`,downharpoonleft:`⇃`,downharpoonright:`⇂`,DownLeftRightVector:`⥐`,DownLeftTeeVector:`⥞`,DownLeftVector:`↽`,DownLeftVectorBar:`⥖`,DownRightTeeVector:`⥟`,DownRightVector:`⇁`,DownRightVectorBar:`⥗`,DownTee:`⊤`,DownTeeArrow:`↧`,drbkarow:`⤐`,drcorn:`⌟`,drcrop:`⌌`,Dscr:`𝒟`,dscr:`𝒹`,DScy:`Ѕ`,dscy:`ѕ`,dsol:`⧶`,Dstrok:`Đ`,dstrok:`đ`,dtdot:`⋱`,dtri:`▿`,dtrif:`▾`,duarr:`⇵`,duhar:`⥯`,dwangle:`⦦`,DZcy:`Џ`,dzcy:`џ`,dzigrarr:`⟿`,Eacute:`É`,eacute:`é`,easter:`⩮`,Ecaron:`Ě`,ecaron:`ě`,ecir:`≖`,Ecirc:`Ê`,ecirc:`ê`,ecolon:`≕`,Ecy:`Э`,ecy:`э`,eDDot:`⩷`,Edot:`Ė`,eDot:`≑`,edot:`ė`,ee:`ⅇ`,efDot:`≒`,Efr:`𝔈`,efr:`𝔢`,eg:`⪚`,Egrave:`È`,egrave:`è`,egs:`⪖`,egsdot:`⪘`,el:`⪙`,Element:`∈`,elinters:`⏧`,ell:`ℓ`,els:`⪕`,elsdot:`⪗`,Emacr:`Ē`,emacr:`ē`,empty:`∅`,emptyset:`∅`,EmptySmallSquare:`◻`,emptyv:`∅`,EmptyVerySmallSquare:`▫`,emsp:` `,emsp13:` `,emsp14:` `,ENG:`Ŋ`,eng:`ŋ`,ensp:` `,Eogon:`Ę`,eogon:`ę`,Eopf:`𝔼`,eopf:`𝕖`,epar:`⋕`,eparsl:`⧣`,eplus:`⩱`,epsi:`ε`,Epsilon:`Ε`,epsilon:`ε`,epsiv:`ϵ`,eqcirc:`≖`,eqcolon:`≕`,eqsim:`≂`,eqslantgtr:`⪖`,eqslantless:`⪕`,Equal:`⩵`,equals:`=`,EqualTilde:`≂`,equest:`≟`,Equilibrium:`⇌`,equiv:`≡`,equivDD:`⩸`,eqvparsl:`⧥`,erarr:`⥱`,erDot:`≓`,Escr:`ℰ`,escr:`ℯ`,esdot:`≐`,Esim:`⩳`,esim:`≂`,Eta:`Η`,eta:`η`,ETH:`Ð`,eth:`ð`,Euml:`Ë`,euml:`ë`,euro:`€`,excl:`!`,exist:`∃`,Exists:`∃`,expectation:`ℰ`,ExponentialE:`ⅇ`,exponentiale:`ⅇ`,fallingdotseq:`≒`,Fcy:`Ф`,fcy:`ф`,female:`♀`,ffilig:`ffi`,fflig:`ff`,ffllig:`ffl`,Ffr:`𝔉`,ffr:`𝔣`,filig:`fi`,FilledSmallSquare:`◼`,FilledVerySmallSquare:`▪`,fjlig:`fj`,flat:`♭`,fllig:`fl`,fltns:`▱`,fnof:`ƒ`,Fopf:`𝔽`,fopf:`𝕗`,ForAll:`∀`,forall:`∀`,fork:`⋔`,forkv:`⫙`,Fouriertrf:`ℱ`,fpartint:`⨍`,frac12:`½`,frac13:`⅓`,frac14:`¼`,frac15:`⅕`,frac16:`⅙`,frac18:`⅛`,frac23:`⅔`,frac25:`⅖`,frac34:`¾`,frac35:`⅗`,frac38:`⅜`,frac45:`⅘`,frac56:`⅚`,frac58:`⅝`,frac78:`⅞`,frasl:`⁄`,frown:`⌢`,Fscr:`ℱ`,fscr:`𝒻`,gacute:`ǵ`,Gamma:`Γ`,gamma:`γ`,Gammad:`Ϝ`,gammad:`ϝ`,gap:`⪆`,Gbreve:`Ğ`,gbreve:`ğ`,Gcedil:`Ģ`,Gcirc:`Ĝ`,gcirc:`ĝ`,Gcy:`Г`,gcy:`г`,Gdot:`Ġ`,gdot:`ġ`,gE:`≧`,ge:`≥`,gEl:`⪌`,gel:`⋛`,geq:`≥`,geqq:`≧`,geqslant:`⩾`,ges:`⩾`,gescc:`⪩`,gesdot:`⪀`,gesdoto:`⪂`,gesdotol:`⪄`,gesl:`⋛︀`,gesles:`⪔`,Gfr:`𝔊`,gfr:`𝔤`,Gg:`⋙`,gg:`≫`,ggg:`⋙`,gimel:`ℷ`,GJcy:`Ѓ`,gjcy:`ѓ`,gl:`≷`,gla:`⪥`,glE:`⪒`,glj:`⪤`,gnap:`⪊`,gnapprox:`⪊`,gnE:`≩`,gne:`⪈`,gneq:`⪈`,gneqq:`≩`,gnsim:`⋧`,Gopf:`𝔾`,gopf:`𝕘`,grave:"`",GreaterEqual:`≥`,GreaterEqualLess:`⋛`,GreaterFullEqual:`≧`,GreaterGreater:`⪢`,GreaterLess:`≷`,GreaterSlantEqual:`⩾`,GreaterTilde:`≳`,Gscr:`𝒢`,gscr:`ℊ`,gsim:`≳`,gsime:`⪎`,gsiml:`⪐`,Gt:`≫`,GT:`>`,gt:`>`,gtcc:`⪧`,gtcir:`⩺`,gtdot:`⋗`,gtlPar:`⦕`,gtquest:`⩼`,gtrapprox:`⪆`,gtrarr:`⥸`,gtrdot:`⋗`,gtreqless:`⋛`,gtreqqless:`⪌`,gtrless:`≷`,gtrsim:`≳`,gvertneqq:`≩︀`,gvnE:`≩︀`,Hacek:`ˇ`,hairsp:` `,half:`½`,hamilt:`ℋ`,HARDcy:`Ъ`,hardcy:`ъ`,hArr:`⇔`,harr:`↔`,harrcir:`⥈`,harrw:`↭`,Hat:`^`,hbar:`ℏ`,Hcirc:`Ĥ`,hcirc:`ĥ`,hearts:`♥`,heartsuit:`♥`,hellip:`…`,hercon:`⊹`,Hfr:`ℌ`,hfr:`𝔥`,HilbertSpace:`ℋ`,hksearow:`⤥`,hkswarow:`⤦`,hoarr:`⇿`,homtht:`∻`,hookleftarrow:`↩`,hookrightarrow:`↪`,Hopf:`ℍ`,hopf:`𝕙`,horbar:`―`,HorizontalLine:`─`,Hscr:`ℋ`,hscr:`𝒽`,hslash:`ℏ`,Hstrok:`Ħ`,hstrok:`ħ`,HumpDownHump:`≎`,HumpEqual:`≏`,hybull:`⁃`,hyphen:`‐`,Iacute:`Í`,iacute:`í`,ic:`⁣`,Icirc:`Î`,icirc:`î`,Icy:`И`,icy:`и`,Idot:`İ`,IEcy:`Е`,iecy:`е`,iexcl:`¡`,iff:`⇔`,Ifr:`ℑ`,ifr:`𝔦`,Igrave:`Ì`,igrave:`ì`,ii:`ⅈ`,iiiint:`⨌`,iiint:`∭`,iinfin:`⧜`,iiota:`℩`,IJlig:`IJ`,ijlig:`ij`,Im:`ℑ`,Imacr:`Ī`,imacr:`ī`,image:`ℑ`,ImaginaryI:`ⅈ`,imagline:`ℐ`,imagpart:`ℑ`,imath:`ı`,imof:`⊷`,imped:`Ƶ`,Implies:`⇒`,in:`∈`,incare:`℅`,infin:`∞`,infintie:`⧝`,inodot:`ı`,Int:`∬`,int:`∫`,intcal:`⊺`,integers:`ℤ`,Integral:`∫`,intercal:`⊺`,Intersection:`⋂`,intlarhk:`⨗`,intprod:`⨼`,InvisibleComma:`⁣`,InvisibleTimes:`⁢`,IOcy:`Ё`,iocy:`ё`,Iogon:`Į`,iogon:`į`,Iopf:`𝕀`,iopf:`𝕚`,Iota:`Ι`,iota:`ι`,iprod:`⨼`,iquest:`¿`,Iscr:`ℐ`,iscr:`𝒾`,isin:`∈`,isindot:`⋵`,isinE:`⋹`,isins:`⋴`,isinsv:`⋳`,isinv:`∈`,it:`⁢`,Itilde:`Ĩ`,itilde:`ĩ`,Iukcy:`І`,iukcy:`і`,Iuml:`Ï`,iuml:`ï`,Jcirc:`Ĵ`,jcirc:`ĵ`,Jcy:`Й`,jcy:`й`,Jfr:`𝔍`,jfr:`𝔧`,jmath:`ȷ`,Jopf:`𝕁`,jopf:`𝕛`,Jscr:`𝒥`,jscr:`𝒿`,Jsercy:`Ј`,jsercy:`ј`,Jukcy:`Є`,jukcy:`є`,Kappa:`Κ`,kappa:`κ`,kappav:`ϰ`,Kcedil:`Ķ`,kcedil:`ķ`,Kcy:`К`,kcy:`к`,Kfr:`𝔎`,kfr:`𝔨`,kgreen:`ĸ`,KHcy:`Х`,khcy:`х`,KJcy:`Ќ`,kjcy:`ќ`,Kopf:`𝕂`,kopf:`𝕜`,Kscr:`𝒦`,kscr:`𝓀`,lAarr:`⇚`,Lacute:`Ĺ`,lacute:`ĺ`,laemptyv:`⦴`,lagran:`ℒ`,Lambda:`Λ`,lambda:`λ`,Lang:`⟪`,lang:`⟨`,langd:`⦑`,langle:`⟨`,lap:`⪅`,Laplacetrf:`ℒ`,laquo:`«`,Larr:`↞`,lArr:`⇐`,larr:`←`,larrb:`⇤`,larrbfs:`⤟`,larrfs:`⤝`,larrhk:`↩`,larrlp:`↫`,larrpl:`⤹`,larrsim:`⥳`,larrtl:`↢`,lat:`⪫`,lAtail:`⤛`,latail:`⤙`,late:`⪭`,lates:`⪭︀`,lBarr:`⤎`,lbarr:`⤌`,lbbrk:`❲`,lbrace:`{`,lbrack:`[`,lbrke:`⦋`,lbrksld:`⦏`,lbrkslu:`⦍`,Lcaron:`Ľ`,lcaron:`ľ`,Lcedil:`Ļ`,lcedil:`ļ`,lceil:`⌈`,lcub:`{`,Lcy:`Л`,lcy:`л`,ldca:`⤶`,ldquo:`“`,ldquor:`„`,ldrdhar:`⥧`,ldrushar:`⥋`,ldsh:`↲`,lE:`≦`,le:`≤`,LeftAngleBracket:`⟨`,LeftArrow:`←`,Leftarrow:`⇐`,leftarrow:`←`,LeftArrowBar:`⇤`,LeftArrowRightArrow:`⇆`,leftarrowtail:`↢`,LeftCeiling:`⌈`,LeftDoubleBracket:`⟦`,LeftDownTeeVector:`⥡`,LeftDownVector:`⇃`,LeftDownVectorBar:`⥙`,LeftFloor:`⌊`,leftharpoondown:`↽`,leftharpoonup:`↼`,leftleftarrows:`⇇`,LeftRightArrow:`↔`,Leftrightarrow:`⇔`,leftrightarrow:`↔`,leftrightarrows:`⇆`,leftrightharpoons:`⇋`,leftrightsquigarrow:`↭`,LeftRightVector:`⥎`,LeftTee:`⊣`,LeftTeeArrow:`↤`,LeftTeeVector:`⥚`,leftthreetimes:`⋋`,LeftTriangle:`⊲`,LeftTriangleBar:`⧏`,LeftTriangleEqual:`⊴`,LeftUpDownVector:`⥑`,LeftUpTeeVector:`⥠`,LeftUpVector:`↿`,LeftUpVectorBar:`⥘`,LeftVector:`↼`,LeftVectorBar:`⥒`,lEg:`⪋`,leg:`⋚`,leq:`≤`,leqq:`≦`,leqslant:`⩽`,les:`⩽`,lescc:`⪨`,lesdot:`⩿`,lesdoto:`⪁`,lesdotor:`⪃`,lesg:`⋚︀`,lesges:`⪓`,lessapprox:`⪅`,lessdot:`⋖`,lesseqgtr:`⋚`,lesseqqgtr:`⪋`,LessEqualGreater:`⋚`,LessFullEqual:`≦`,LessGreater:`≶`,lessgtr:`≶`,LessLess:`⪡`,lesssim:`≲`,LessSlantEqual:`⩽`,LessTilde:`≲`,lfisht:`⥼`,lfloor:`⌊`,Lfr:`𝔏`,lfr:`𝔩`,lg:`≶`,lgE:`⪑`,lHar:`⥢`,lhard:`↽`,lharu:`↼`,lharul:`⥪`,lhblk:`▄`,LJcy:`Љ`,ljcy:`љ`,Ll:`⋘`,ll:`≪`,llarr:`⇇`,llcorner:`⌞`,Lleftarrow:`⇚`,llhard:`⥫`,lltri:`◺`,Lmidot:`Ŀ`,lmidot:`ŀ`,lmoust:`⎰`,lmoustache:`⎰`,lnap:`⪉`,lnapprox:`⪉`,lnE:`≨`,lne:`⪇`,lneq:`⪇`,lneqq:`≨`,lnsim:`⋦`,loang:`⟬`,loarr:`⇽`,lobrk:`⟦`,LongLeftArrow:`⟵`,Longleftarrow:`⟸`,longleftarrow:`⟵`,LongLeftRightArrow:`⟷`,Longleftrightarrow:`⟺`,longleftrightarrow:`⟷`,longmapsto:`⟼`,LongRightArrow:`⟶`,Longrightarrow:`⟹`,longrightarrow:`⟶`,looparrowleft:`↫`,looparrowright:`↬`,lopar:`⦅`,Lopf:`𝕃`,lopf:`𝕝`,loplus:`⨭`,lotimes:`⨴`,lowast:`∗`,lowbar:`_`,LowerLeftArrow:`↙`,LowerRightArrow:`↘`,loz:`◊`,lozenge:`◊`,lozf:`⧫`,lpar:`(`,lparlt:`⦓`,lrarr:`⇆`,lrcorner:`⌟`,lrhar:`⇋`,lrhard:`⥭`,lrm:`‎`,lrtri:`⊿`,lsaquo:`‹`,Lscr:`ℒ`,lscr:`𝓁`,Lsh:`↰`,lsh:`↰`,lsim:`≲`,lsime:`⪍`,lsimg:`⪏`,lsqb:`[`,lsquo:`‘`,lsquor:`‚`,Lstrok:`Ł`,lstrok:`ł`,Lt:`≪`,LT:`<`,lt:`<`,ltcc:`⪦`,ltcir:`⩹`,ltdot:`⋖`,lthree:`⋋`,ltimes:`⋉`,ltlarr:`⥶`,ltquest:`⩻`,ltri:`◃`,ltrie:`⊴`,ltrif:`◂`,ltrPar:`⦖`,lurdshar:`⥊`,luruhar:`⥦`,lvertneqq:`≨︀`,lvnE:`≨︀`,macr:`¯`,male:`♂`,malt:`✠`,maltese:`✠`,Map:`⤅`,map:`↦`,mapsto:`↦`,mapstodown:`↧`,mapstoleft:`↤`,mapstoup:`↥`,marker:`▮`,mcomma:`⨩`,Mcy:`М`,mcy:`м`,mdash:`—`,mDDot:`∺`,measuredangle:`∡`,MediumSpace:` `,Mellintrf:`ℳ`,Mfr:`𝔐`,mfr:`𝔪`,mho:`℧`,micro:`µ`,mid:`∣`,midast:`*`,midcir:`⫰`,middot:`·`,minus:`−`,minusb:`⊟`,minusd:`∸`,minusdu:`⨪`,MinusPlus:`∓`,mlcp:`⫛`,mldr:`…`,mnplus:`∓`,models:`⊧`,Mopf:`𝕄`,mopf:`𝕞`,mp:`∓`,Mscr:`ℳ`,mscr:`𝓂`,mstpos:`∾`,Mu:`Μ`,mu:`μ`,multimap:`⊸`,mumap:`⊸`,nabla:`∇`,Nacute:`Ń`,nacute:`ń`,nang:`∠⃒`,nap:`≉`,napE:`⩰̸`,napid:`≋̸`,napos:`ʼn`,napprox:`≉`,natur:`♮`,natural:`♮`,naturals:`ℕ`,nbsp:`\xA0`,nbump:`≎̸`,nbumpe:`≏̸`,ncap:`⩃`,Ncaron:`Ň`,ncaron:`ň`,Ncedil:`Ņ`,ncedil:`ņ`,ncong:`≇`,ncongdot:`⩭̸`,ncup:`⩂`,Ncy:`Н`,ncy:`н`,ndash:`–`,ne:`≠`,nearhk:`⤤`,neArr:`⇗`,nearr:`↗`,nearrow:`↗`,nedot:`≐̸`,NegativeMediumSpace:`​`,NegativeThickSpace:`​`,NegativeThinSpace:`​`,NegativeVeryThinSpace:`​`,nequiv:`≢`,nesear:`⤨`,nesim:`≂̸`,NestedGreaterGreater:`≫`,NestedLessLess:`≪`,NewLine:` `,nexist:`∄`,nexists:`∄`,Nfr:`𝔑`,nfr:`𝔫`,ngE:`≧̸`,nge:`≱`,ngeq:`≱`,ngeqq:`≧̸`,ngeqslant:`⩾̸`,nges:`⩾̸`,nGg:`⋙̸`,ngsim:`≵`,nGt:`≫⃒`,ngt:`≯`,ngtr:`≯`,nGtv:`≫̸`,nhArr:`⇎`,nharr:`↮`,nhpar:`⫲`,ni:`∋`,nis:`⋼`,nisd:`⋺`,niv:`∋`,NJcy:`Њ`,njcy:`њ`,nlArr:`⇍`,nlarr:`↚`,nldr:`‥`,nlE:`≦̸`,nle:`≰`,nLeftarrow:`⇍`,nleftarrow:`↚`,nLeftrightarrow:`⇎`,nleftrightarrow:`↮`,nleq:`≰`,nleqq:`≦̸`,nleqslant:`⩽̸`,nles:`⩽̸`,nless:`≮`,nLl:`⋘̸`,nlsim:`≴`,nLt:`≪⃒`,nlt:`≮`,nltri:`⋪`,nltrie:`⋬`,nLtv:`≪̸`,nmid:`∤`,NoBreak:`⁠`,NonBreakingSpace:`\xA0`,Nopf:`ℕ`,nopf:`𝕟`,Not:`⫬`,not:`¬`,NotCongruent:`≢`,NotCupCap:`≭`,NotDoubleVerticalBar:`∦`,NotElement:`∉`,NotEqual:`≠`,NotEqualTilde:`≂̸`,NotExists:`∄`,NotGreater:`≯`,NotGreaterEqual:`≱`,NotGreaterFullEqual:`≧̸`,NotGreaterGreater:`≫̸`,NotGreaterLess:`≹`,NotGreaterSlantEqual:`⩾̸`,NotGreaterTilde:`≵`,NotHumpDownHump:`≎̸`,NotHumpEqual:`≏̸`,notin:`∉`,notindot:`⋵̸`,notinE:`⋹̸`,notinva:`∉`,notinvb:`⋷`,notinvc:`⋶`,NotLeftTriangle:`⋪`,NotLeftTriangleBar:`⧏̸`,NotLeftTriangleEqual:`⋬`,NotLess:`≮`,NotLessEqual:`≰`,NotLessGreater:`≸`,NotLessLess:`≪̸`,NotLessSlantEqual:`⩽̸`,NotLessTilde:`≴`,NotNestedGreaterGreater:`⪢̸`,NotNestedLessLess:`⪡̸`,notni:`∌`,notniva:`∌`,notnivb:`⋾`,notnivc:`⋽`,NotPrecedes:`⊀`,NotPrecedesEqual:`⪯̸`,NotPrecedesSlantEqual:`⋠`,NotReverseElement:`∌`,NotRightTriangle:`⋫`,NotRightTriangleBar:`⧐̸`,NotRightTriangleEqual:`⋭`,NotSquareSubset:`⊏̸`,NotSquareSubsetEqual:`⋢`,NotSquareSuperset:`⊐̸`,NotSquareSupersetEqual:`⋣`,NotSubset:`⊂⃒`,NotSubsetEqual:`⊈`,NotSucceeds:`⊁`,NotSucceedsEqual:`⪰̸`,NotSucceedsSlantEqual:`⋡`,NotSucceedsTilde:`≿̸`,NotSuperset:`⊃⃒`,NotSupersetEqual:`⊉`,NotTilde:`≁`,NotTildeEqual:`≄`,NotTildeFullEqual:`≇`,NotTildeTilde:`≉`,NotVerticalBar:`∤`,npar:`∦`,nparallel:`∦`,nparsl:`⫽⃥`,npart:`∂̸`,npolint:`⨔`,npr:`⊀`,nprcue:`⋠`,npre:`⪯̸`,nprec:`⊀`,npreceq:`⪯̸`,nrArr:`⇏`,nrarr:`↛`,nrarrc:`⤳̸`,nrarrw:`↝̸`,nRightarrow:`⇏`,nrightarrow:`↛`,nrtri:`⋫`,nrtrie:`⋭`,nsc:`⊁`,nsccue:`⋡`,nsce:`⪰̸`,Nscr:`𝒩`,nscr:`𝓃`,nshortmid:`∤`,nshortparallel:`∦`,nsim:`≁`,nsime:`≄`,nsimeq:`≄`,nsmid:`∤`,nspar:`∦`,nsqsube:`⋢`,nsqsupe:`⋣`,nsub:`⊄`,nsubE:`⫅̸`,nsube:`⊈`,nsubset:`⊂⃒`,nsubseteq:`⊈`,nsubseteqq:`⫅̸`,nsucc:`⊁`,nsucceq:`⪰̸`,nsup:`⊅`,nsupE:`⫆̸`,nsupe:`⊉`,nsupset:`⊃⃒`,nsupseteq:`⊉`,nsupseteqq:`⫆̸`,ntgl:`≹`,Ntilde:`Ñ`,ntilde:`ñ`,ntlg:`≸`,ntriangleleft:`⋪`,ntrianglelefteq:`⋬`,ntriangleright:`⋫`,ntrianglerighteq:`⋭`,Nu:`Ν`,nu:`ν`,num:`#`,numero:`№`,numsp:` `,nvap:`≍⃒`,nVDash:`⊯`,nVdash:`⊮`,nvDash:`⊭`,nvdash:`⊬`,nvge:`≥⃒`,nvgt:`>⃒`,nvHarr:`⤄`,nvinfin:`⧞`,nvlArr:`⤂`,nvle:`≤⃒`,nvlt:`<⃒`,nvltrie:`⊴⃒`,nvrArr:`⤃`,nvrtrie:`⊵⃒`,nvsim:`∼⃒`,nwarhk:`⤣`,nwArr:`⇖`,nwarr:`↖`,nwarrow:`↖`,nwnear:`⤧`,Oacute:`Ó`,oacute:`ó`,oast:`⊛`,ocir:`⊚`,Ocirc:`Ô`,ocirc:`ô`,Ocy:`О`,ocy:`о`,odash:`⊝`,Odblac:`Ő`,odblac:`ő`,odiv:`⨸`,odot:`⊙`,odsold:`⦼`,OElig:`Œ`,oelig:`œ`,ofcir:`⦿`,Ofr:`𝔒`,ofr:`𝔬`,ogon:`˛`,Ograve:`Ò`,ograve:`ò`,ogt:`⧁`,ohbar:`⦵`,ohm:`Ω`,oint:`∮`,olarr:`↺`,olcir:`⦾`,olcross:`⦻`,oline:`‾`,olt:`⧀`,Omacr:`Ō`,omacr:`ō`,Omega:`Ω`,omega:`ω`,Omicron:`Ο`,omicron:`ο`,omid:`⦶`,ominus:`⊖`,Oopf:`𝕆`,oopf:`𝕠`,opar:`⦷`,OpenCurlyDoubleQuote:`“`,OpenCurlyQuote:`‘`,operp:`⦹`,oplus:`⊕`,Or:`⩔`,or:`∨`,orarr:`↻`,ord:`⩝`,order:`ℴ`,orderof:`ℴ`,ordf:`ª`,ordm:`º`,origof:`⊶`,oror:`⩖`,orslope:`⩗`,orv:`⩛`,oS:`Ⓢ`,Oscr:`𝒪`,oscr:`ℴ`,Oslash:`Ø`,oslash:`ø`,osol:`⊘`,Otilde:`Õ`,otilde:`õ`,Otimes:`⨷`,otimes:`⊗`,otimesas:`⨶`,Ouml:`Ö`,ouml:`ö`,ovbar:`⌽`,OverBar:`‾`,OverBrace:`⏞`,OverBracket:`⎴`,OverParenthesis:`⏜`,par:`∥`,para:`¶`,parallel:`∥`,parsim:`⫳`,parsl:`⫽`,part:`∂`,PartialD:`∂`,Pcy:`П`,pcy:`п`,percnt:`%`,period:`.`,permil:`‰`,perp:`⊥`,pertenk:`‱`,Pfr:`𝔓`,pfr:`𝔭`,Phi:`Φ`,phi:`φ`,phiv:`ϕ`,phmmat:`ℳ`,phone:`☎`,Pi:`Π`,pi:`π`,pitchfork:`⋔`,piv:`ϖ`,planck:`ℏ`,planckh:`ℎ`,plankv:`ℏ`,plus:`+`,plusacir:`⨣`,plusb:`⊞`,pluscir:`⨢`,plusdo:`∔`,plusdu:`⨥`,pluse:`⩲`,PlusMinus:`±`,plusmn:`±`,plussim:`⨦`,plustwo:`⨧`,pm:`±`,Poincareplane:`ℌ`,pointint:`⨕`,Popf:`ℙ`,popf:`𝕡`,pound:`£`,Pr:`⪻`,pr:`≺`,prap:`⪷`,prcue:`≼`,prE:`⪳`,pre:`⪯`,prec:`≺`,precapprox:`⪷`,preccurlyeq:`≼`,Precedes:`≺`,PrecedesEqual:`⪯`,PrecedesSlantEqual:`≼`,PrecedesTilde:`≾`,preceq:`⪯`,precnapprox:`⪹`,precneqq:`⪵`,precnsim:`⋨`,precsim:`≾`,Prime:`″`,prime:`′`,primes:`ℙ`,prnap:`⪹`,prnE:`⪵`,prnsim:`⋨`,prod:`∏`,Product:`∏`,profalar:`⌮`,profline:`⌒`,profsurf:`⌓`,prop:`∝`,Proportion:`∷`,Proportional:`∝`,propto:`∝`,prsim:`≾`,prurel:`⊰`,Pscr:`𝒫`,pscr:`𝓅`,Psi:`Ψ`,psi:`ψ`,puncsp:` `,Qfr:`𝔔`,qfr:`𝔮`,qint:`⨌`,Qopf:`ℚ`,qopf:`𝕢`,qprime:`⁗`,Qscr:`𝒬`,qscr:`𝓆`,quaternions:`ℍ`,quatint:`⨖`,quest:`?`,questeq:`≟`,QUOT:`"`,quot:`"`,rAarr:`⇛`,race:`∽̱`,Racute:`Ŕ`,racute:`ŕ`,radic:`√`,raemptyv:`⦳`,Rang:`⟫`,rang:`⟩`,rangd:`⦒`,range:`⦥`,rangle:`⟩`,raquo:`»`,Rarr:`↠`,rArr:`⇒`,rarr:`→`,rarrap:`⥵`,rarrb:`⇥`,rarrbfs:`⤠`,rarrc:`⤳`,rarrfs:`⤞`,rarrhk:`↪`,rarrlp:`↬`,rarrpl:`⥅`,rarrsim:`⥴`,Rarrtl:`⤖`,rarrtl:`↣`,rarrw:`↝`,rAtail:`⤜`,ratail:`⤚`,ratio:`∶`,rationals:`ℚ`,RBarr:`⤐`,rBarr:`⤏`,rbarr:`⤍`,rbbrk:`❳`,rbrace:`}`,rbrack:`]`,rbrke:`⦌`,rbrksld:`⦎`,rbrkslu:`⦐`,Rcaron:`Ř`,rcaron:`ř`,Rcedil:`Ŗ`,rcedil:`ŗ`,rceil:`⌉`,rcub:`}`,Rcy:`Р`,rcy:`р`,rdca:`⤷`,rdldhar:`⥩`,rdquo:`”`,rdquor:`”`,rdsh:`↳`,Re:`ℜ`,real:`ℜ`,realine:`ℛ`,realpart:`ℜ`,reals:`ℝ`,rect:`▭`,REG:`®`,reg:`®`,ReverseElement:`∋`,ReverseEquilibrium:`⇋`,ReverseUpEquilibrium:`⥯`,rfisht:`⥽`,rfloor:`⌋`,Rfr:`ℜ`,rfr:`𝔯`,rHar:`⥤`,rhard:`⇁`,rharu:`⇀`,rharul:`⥬`,Rho:`Ρ`,rho:`ρ`,rhov:`ϱ`,RightAngleBracket:`⟩`,RightArrow:`→`,Rightarrow:`⇒`,rightarrow:`→`,RightArrowBar:`⇥`,RightArrowLeftArrow:`⇄`,rightarrowtail:`↣`,RightCeiling:`⌉`,RightDoubleBracket:`⟧`,RightDownTeeVector:`⥝`,RightDownVector:`⇂`,RightDownVectorBar:`⥕`,RightFloor:`⌋`,rightharpoondown:`⇁`,rightharpoonup:`⇀`,rightleftarrows:`⇄`,rightleftharpoons:`⇌`,rightrightarrows:`⇉`,rightsquigarrow:`↝`,RightTee:`⊢`,RightTeeArrow:`↦`,RightTeeVector:`⥛`,rightthreetimes:`⋌`,RightTriangle:`⊳`,RightTriangleBar:`⧐`,RightTriangleEqual:`⊵`,RightUpDownVector:`⥏`,RightUpTeeVector:`⥜`,RightUpVector:`↾`,RightUpVectorBar:`⥔`,RightVector:`⇀`,RightVectorBar:`⥓`,ring:`˚`,risingdotseq:`≓`,rlarr:`⇄`,rlhar:`⇌`,rlm:`‏`,rmoust:`⎱`,rmoustache:`⎱`,rnmid:`⫮`,roang:`⟭`,roarr:`⇾`,robrk:`⟧`,ropar:`⦆`,Ropf:`ℝ`,ropf:`𝕣`,roplus:`⨮`,rotimes:`⨵`,RoundImplies:`⥰`,rpar:`)`,rpargt:`⦔`,rppolint:`⨒`,rrarr:`⇉`,Rrightarrow:`⇛`,rsaquo:`›`,Rscr:`ℛ`,rscr:`𝓇`,Rsh:`↱`,rsh:`↱`,rsqb:`]`,rsquo:`’`,rsquor:`’`,rthree:`⋌`,rtimes:`⋊`,rtri:`▹`,rtrie:`⊵`,rtrif:`▸`,rtriltri:`⧎`,RuleDelayed:`⧴`,ruluhar:`⥨`,rx:`℞`,Sacute:`Ś`,sacute:`ś`,sbquo:`‚`,Sc:`⪼`,sc:`≻`,scap:`⪸`,Scaron:`Š`,scaron:`š`,sccue:`≽`,scE:`⪴`,sce:`⪰`,Scedil:`Ş`,scedil:`ş`,Scirc:`Ŝ`,scirc:`ŝ`,scnap:`⪺`,scnE:`⪶`,scnsim:`⋩`,scpolint:`⨓`,scsim:`≿`,Scy:`С`,scy:`с`,sdot:`⋅`,sdotb:`⊡`,sdote:`⩦`,searhk:`⤥`,seArr:`⇘`,searr:`↘`,searrow:`↘`,sect:`§`,semi:`;`,seswar:`⤩`,setminus:`∖`,setmn:`∖`,sext:`✶`,Sfr:`𝔖`,sfr:`𝔰`,sfrown:`⌢`,sharp:`♯`,SHCHcy:`Щ`,shchcy:`щ`,SHcy:`Ш`,shcy:`ш`,ShortDownArrow:`↓`,ShortLeftArrow:`←`,shortmid:`∣`,shortparallel:`∥`,ShortRightArrow:`→`,ShortUpArrow:`↑`,shy:`­`,Sigma:`Σ`,sigma:`σ`,sigmaf:`ς`,sigmav:`ς`,sim:`∼`,simdot:`⩪`,sime:`≃`,simeq:`≃`,simg:`⪞`,simgE:`⪠`,siml:`⪝`,simlE:`⪟`,simne:`≆`,simplus:`⨤`,simrarr:`⥲`,slarr:`←`,SmallCircle:`∘`,smallsetminus:`∖`,smashp:`⨳`,smeparsl:`⧤`,smid:`∣`,smile:`⌣`,smt:`⪪`,smte:`⪬`,smtes:`⪬︀`,SOFTcy:`Ь`,softcy:`ь`,sol:`/`,solb:`⧄`,solbar:`⌿`,Sopf:`𝕊`,sopf:`𝕤`,spades:`♠`,spadesuit:`♠`,spar:`∥`,sqcap:`⊓`,sqcaps:`⊓︀`,sqcup:`⊔`,sqcups:`⊔︀`,Sqrt:`√`,sqsub:`⊏`,sqsube:`⊑`,sqsubset:`⊏`,sqsubseteq:`⊑`,sqsup:`⊐`,sqsupe:`⊒`,sqsupset:`⊐`,sqsupseteq:`⊒`,squ:`□`,Square:`□`,square:`□`,SquareIntersection:`⊓`,SquareSubset:`⊏`,SquareSubsetEqual:`⊑`,SquareSuperset:`⊐`,SquareSupersetEqual:`⊒`,SquareUnion:`⊔`,squarf:`▪`,squf:`▪`,srarr:`→`,Sscr:`𝒮`,sscr:`𝓈`,ssetmn:`∖`,ssmile:`⌣`,sstarf:`⋆`,Star:`⋆`,star:`☆`,starf:`★`,straightepsilon:`ϵ`,straightphi:`ϕ`,strns:`¯`,Sub:`⋐`,sub:`⊂`,subdot:`⪽`,subE:`⫅`,sube:`⊆`,subedot:`⫃`,submult:`⫁`,subnE:`⫋`,subne:`⊊`,subplus:`⪿`,subrarr:`⥹`,Subset:`⋐`,subset:`⊂`,subseteq:`⊆`,subseteqq:`⫅`,SubsetEqual:`⊆`,subsetneq:`⊊`,subsetneqq:`⫋`,subsim:`⫇`,subsub:`⫕`,subsup:`⫓`,succ:`≻`,succapprox:`⪸`,succcurlyeq:`≽`,Succeeds:`≻`,SucceedsEqual:`⪰`,SucceedsSlantEqual:`≽`,SucceedsTilde:`≿`,succeq:`⪰`,succnapprox:`⪺`,succneqq:`⪶`,succnsim:`⋩`,succsim:`≿`,SuchThat:`∋`,Sum:`∑`,sum:`∑`,sung:`♪`,Sup:`⋑`,sup:`⊃`,sup1:`¹`,sup2:`²`,sup3:`³`,supdot:`⪾`,supdsub:`⫘`,supE:`⫆`,supe:`⊇`,supedot:`⫄`,Superset:`⊃`,SupersetEqual:`⊇`,suphsol:`⟉`,suphsub:`⫗`,suplarr:`⥻`,supmult:`⫂`,supnE:`⫌`,supne:`⊋`,supplus:`⫀`,Supset:`⋑`,supset:`⊃`,supseteq:`⊇`,supseteqq:`⫆`,supsetneq:`⊋`,supsetneqq:`⫌`,supsim:`⫈`,supsub:`⫔`,supsup:`⫖`,swarhk:`⤦`,swArr:`⇙`,swarr:`↙`,swarrow:`↙`,swnwar:`⤪`,szlig:`ß`,Tab:` `,target:`⌖`,Tau:`Τ`,tau:`τ`,tbrk:`⎴`,Tcaron:`Ť`,tcaron:`ť`,Tcedil:`Ţ`,tcedil:`ţ`,Tcy:`Т`,tcy:`т`,tdot:`⃛`,telrec:`⌕`,Tfr:`𝔗`,tfr:`𝔱`,there4:`∴`,Therefore:`∴`,therefore:`∴`,Theta:`Θ`,theta:`θ`,thetasym:`ϑ`,thetav:`ϑ`,thickapprox:`≈`,thicksim:`∼`,ThickSpace:`  `,thinsp:` `,ThinSpace:` `,thkap:`≈`,thksim:`∼`,THORN:`Þ`,thorn:`þ`,Tilde:`∼`,tilde:`˜`,TildeEqual:`≃`,TildeFullEqual:`≅`,TildeTilde:`≈`,times:`×`,timesb:`⊠`,timesbar:`⨱`,timesd:`⨰`,tint:`∭`,toea:`⤨`,top:`⊤`,topbot:`⌶`,topcir:`⫱`,Topf:`𝕋`,topf:`𝕥`,topfork:`⫚`,tosa:`⤩`,tprime:`‴`,TRADE:`™`,trade:`™`,triangle:`▵`,triangledown:`▿`,triangleleft:`◃`,trianglelefteq:`⊴`,triangleq:`≜`,triangleright:`▹`,trianglerighteq:`⊵`,tridot:`◬`,trie:`≜`,triminus:`⨺`,TripleDot:`⃛`,triplus:`⨹`,trisb:`⧍`,tritime:`⨻`,trpezium:`⏢`,Tscr:`𝒯`,tscr:`𝓉`,TScy:`Ц`,tscy:`ц`,TSHcy:`Ћ`,tshcy:`ћ`,Tstrok:`Ŧ`,tstrok:`ŧ`,twixt:`≬`,twoheadleftarrow:`↞`,twoheadrightarrow:`↠`,Uacute:`Ú`,uacute:`ú`,Uarr:`↟`,uArr:`⇑`,uarr:`↑`,Uarrocir:`⥉`,Ubrcy:`Ў`,ubrcy:`ў`,Ubreve:`Ŭ`,ubreve:`ŭ`,Ucirc:`Û`,ucirc:`û`,Ucy:`У`,ucy:`у`,udarr:`⇅`,Udblac:`Ű`,udblac:`ű`,udhar:`⥮`,ufisht:`⥾`,Ufr:`𝔘`,ufr:`𝔲`,Ugrave:`Ù`,ugrave:`ù`,uHar:`⥣`,uharl:`↿`,uharr:`↾`,uhblk:`▀`,ulcorn:`⌜`,ulcorner:`⌜`,ulcrop:`⌏`,ultri:`◸`,Umacr:`Ū`,umacr:`ū`,uml:`¨`,UnderBar:`_`,UnderBrace:`⏟`,UnderBracket:`⎵`,UnderParenthesis:`⏝`,Union:`⋃`,UnionPlus:`⊎`,Uogon:`Ų`,uogon:`ų`,Uopf:`𝕌`,uopf:`𝕦`,UpArrow:`↑`,Uparrow:`⇑`,uparrow:`↑`,UpArrowBar:`⤒`,UpArrowDownArrow:`⇅`,UpDownArrow:`↕`,Updownarrow:`⇕`,updownarrow:`↕`,UpEquilibrium:`⥮`,upharpoonleft:`↿`,upharpoonright:`↾`,uplus:`⊎`,UpperLeftArrow:`↖`,UpperRightArrow:`↗`,Upsi:`ϒ`,upsi:`υ`,upsih:`ϒ`,Upsilon:`Υ`,upsilon:`υ`,UpTee:`⊥`,UpTeeArrow:`↥`,upuparrows:`⇈`,urcorn:`⌝`,urcorner:`⌝`,urcrop:`⌎`,Uring:`Ů`,uring:`ů`,urtri:`◹`,Uscr:`𝒰`,uscr:`𝓊`,utdot:`⋰`,Utilde:`Ũ`,utilde:`ũ`,utri:`▵`,utrif:`▴`,uuarr:`⇈`,Uuml:`Ü`,uuml:`ü`,uwangle:`⦧`,vangrt:`⦜`,varepsilon:`ϵ`,varkappa:`ϰ`,varnothing:`∅`,varphi:`ϕ`,varpi:`ϖ`,varpropto:`∝`,vArr:`⇕`,varr:`↕`,varrho:`ϱ`,varsigma:`ς`,varsubsetneq:`⊊︀`,varsubsetneqq:`⫋︀`,varsupsetneq:`⊋︀`,varsupsetneqq:`⫌︀`,vartheta:`ϑ`,vartriangleleft:`⊲`,vartriangleright:`⊳`,Vbar:`⫫`,vBar:`⫨`,vBarv:`⫩`,Vcy:`В`,vcy:`в`,VDash:`⊫`,Vdash:`⊩`,vDash:`⊨`,vdash:`⊢`,Vdashl:`⫦`,Vee:`⋁`,vee:`∨`,veebar:`⊻`,veeeq:`≚`,vellip:`⋮`,Verbar:`‖`,verbar:`|`,Vert:`‖`,vert:`|`,VerticalBar:`∣`,VerticalLine:`|`,VerticalSeparator:`❘`,VerticalTilde:`≀`,VeryThinSpace:` `,Vfr:`𝔙`,vfr:`𝔳`,vltri:`⊲`,vnsub:`⊂⃒`,vnsup:`⊃⃒`,Vopf:`𝕍`,vopf:`𝕧`,vprop:`∝`,vrtri:`⊳`,Vscr:`𝒱`,vscr:`𝓋`,vsubnE:`⫋︀`,vsubne:`⊊︀`,vsupnE:`⫌︀`,vsupne:`⊋︀`,Vvdash:`⊪`,vzigzag:`⦚`,Wcirc:`Ŵ`,wcirc:`ŵ`,wedbar:`⩟`,Wedge:`⋀`,wedge:`∧`,wedgeq:`≙`,weierp:`℘`,Wfr:`𝔚`,wfr:`𝔴`,Wopf:`𝕎`,wopf:`𝕨`,wp:`℘`,wr:`≀`,wreath:`≀`,Wscr:`𝒲`,wscr:`𝓌`,xcap:`⋂`,xcirc:`◯`,xcup:`⋃`,xdtri:`▽`,Xfr:`𝔛`,xfr:`𝔵`,xhArr:`⟺`,xharr:`⟷`,Xi:`Ξ`,xi:`ξ`,xlArr:`⟸`,xlarr:`⟵`,xmap:`⟼`,xnis:`⋻`,xodot:`⨀`,Xopf:`𝕏`,xopf:`𝕩`,xoplus:`⨁`,xotime:`⨂`,xrArr:`⟹`,xrarr:`⟶`,Xscr:`𝒳`,xscr:`𝓍`,xsqcup:`⨆`,xuplus:`⨄`,xutri:`△`,xvee:`⋁`,xwedge:`⋀`,Yacute:`Ý`,yacute:`ý`,YAcy:`Я`,yacy:`я`,Ycirc:`Ŷ`,ycirc:`ŷ`,Ycy:`Ы`,ycy:`ы`,yen:`¥`,Yfr:`𝔜`,yfr:`𝔶`,YIcy:`Ї`,yicy:`ї`,Yopf:`𝕐`,yopf:`𝕪`,Yscr:`𝒴`,yscr:`𝓎`,YUcy:`Ю`,yucy:`ю`,Yuml:`Ÿ`,yuml:`ÿ`,Zacute:`Ź`,zacute:`ź`,Zcaron:`Ž`,zcaron:`ž`,Zcy:`З`,zcy:`з`,Zdot:`Ż`,zdot:`ż`,zeetrf:`ℨ`,ZeroWidthSpace:`​`,Zeta:`Ζ`,zeta:`ζ`,Zfr:`ℨ`,zfr:`𝔷`,ZHcy:`Ж`,zhcy:`ж`,zigrarr:`⇝`,Zopf:`ℤ`,zopf:`𝕫`,Zscr:`𝒵`,zscr:`𝓏`,zwj:`‍`,zwnj:`‌`}),e.entityMap=e.HTML_ENTITIES})),st=N((e=>{var t=it().NAMESPACE,n=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,r=RegExp(`[\\-\\.0-9`+n.source.slice(1,-1)+`\\u00B7\\u0300-\\u036F\\u203F-\\u2040]`),i=RegExp(`^`+n.source+r.source+`*(?::`+n.source+r.source+`*)?$`),a=0,o=1,s=2,c=3,l=4,u=5,d=6,f=7;function p(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,p)}p.prototype=Error(),p.prototype.name=p.name;function m(){}m.prototype={parse:function(e,t,n){var r=this.domBuilder;r.startDocument(),x(t,t={}),h(e,t,n,r,this.errorHandler),r.endDocument()}};function h(e,n,r,i,a){function o(e){if(e>65535){e-=65536;var t=55296+(e>>10),n=56320+(e&1023);return String.fromCharCode(t,n)}else return String.fromCharCode(e)}function s(e){var t=e.slice(1,-1);return Object.hasOwnProperty.call(r,t)?r[t]:t.charAt(0)===`#`?o(parseInt(t.substr(1).replace(`x`,`0x`))):(a.error(`entity not found:`+e),e)}function c(t){if(t>T){var n=e.substring(T,t).replace(/&#?\w+;/g,s);m&&l(T),i.characters(n,0,t-T),T=t}}function l(t,n){for(;t>=d&&(n=f.exec(e));)u=n.index,d=u+n[0].length,m.lineNumber++;m.columnNumber=t-u+1}for(var u=0,d=0,f=/.*(?:\r\n?|\n)|.*$/g,m=i.locator,h=[{currentNSMap:n}],x={},T=0;;){try{var E=e.indexOf(`<`,T);if(E<0){if(!e.substr(T).match(/^\s*$/)){var D=i.doc,O=D.createTextNode(e.substr(T));D.appendChild(O),i.currentElement=O}return}switch(E>T&&c(E),e.charAt(E+1)){case`/`:var k=e.indexOf(`>`,E+3),A=e.substring(E+2,k).replace(/[ \t\n\r]+$/g,``),j=h.pop();k<0?(A=e.substring(E+2).replace(/[\s<].*/,``),a.error(`end tag name: `+A+` is not complete:`+j.tagName),k=E+1+A.length):A.match(/\sT?T=k:c(Math.max(E,T)+1)}}function g(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function _(e,n,r,i,p,m){function h(e,t,n){r.attributeNames.hasOwnProperty(e)&&m.fatalError(`Attribute `+e+` redefined`),r.addValue(e,t.replace(/[\t\n\r]/g,` `).replace(/&#?\w+;/g,p),n)}for(var g,_,v=++n,y=a;;){var b=e.charAt(v);switch(b){case`=`:if(y===o)g=e.slice(n,v),y=c;else if(y===s)y=c;else throw Error(`attribute equal must after attrName`);break;case`'`:case`"`:if(y===c||y===o)if(y===o&&(m.warning(`attribute value must after "="`),g=e.slice(n,v)),n=v+1,v=e.indexOf(b,n),v>0)_=e.slice(n,v),h(g,_,n-1),y=u;else throw Error(`attribute value no end '`+b+`' match`);else if(y==l)_=e.slice(n,v),h(g,_,n),m.warning(`attribute "`+g+`" missed start quot(`+b+`)!!`),n=v+1,y=u;else throw Error(`attribute value must after "="`);break;case`/`:switch(y){case a:r.setTagName(e.slice(n,v));case u:case d:case f:y=f,r.closed=!0;case l:case o:break;case s:r.closed=!0;break;default:throw Error(`attribute invalid close char('/')`)}break;case``:return m.error(`unexpected end of input`),y==a&&r.setTagName(e.slice(n,v)),v;case`>`:switch(y){case a:r.setTagName(e.slice(n,v));case u:case d:case f:break;case l:case o:_=e.slice(n,v),_.slice(-1)===`/`&&(r.closed=!0,_=_.slice(0,-1));case s:y===s&&(_=g),y==l?(m.warning(`attribute "`+_+`" missed quot(")!`),h(g,_,n)):((!t.isHTML(i[``])||!_.match(/^(?:disabled|checked|selected)$/i))&&m.warning(`attribute "`+_+`" missed value!! "`+_+`" instead!!`),h(_,_,n));break;case c:throw Error(`attribute value missed!!`)}return v;case`€`:b=` `;default:if(b<=` `)switch(y){case a:r.setTagName(e.slice(n,v)),y=d;break;case o:g=e.slice(n,v),y=s;break;case l:var _=e.slice(n,v);m.warning(`attribute "`+_+`" missed quot(")!!`),h(g,_,n);case u:y=d;break}else switch(y){case s:r.tagName,(!t.isHTML(i[``])||!g.match(/^(?:disabled|checked|selected)$/i))&&m.warning(`attribute "`+g+`" missed value!! "`+g+`" instead2!!`),h(g,g,n),n=v,y=o;break;case u:m.warning(`attribute space is required"`+g+`"!!`);case d:y=o,n=v;break;case c:y=l,n=v;break;case f:throw Error(`elements closed character '/' and '>' must be connected to`)}}v++}}function v(e,n,r){for(var i=e.tagName,a=null,o=e.length;o--;){var s=e[o],c=s.qName,l=s.value,u=c.indexOf(`:`);if(u>0)var d=s.prefix=c.slice(0,u),f=c.slice(u+1),p=d===`xmlns`&&f;else f=c,d=null,p=c===`xmlns`&&``;s.localName=f,p!==!1&&(a??(a={},x(r,r={})),r[p]=a[p]=l,s.uri=t.XMLNS,n.startPrefixMapping(p,l))}for(var o=e.length;o--;){s=e[o];var d=s.prefix;d&&(d===`xml`&&(s.uri=t.XML),d!==`xmlns`&&(s.uri=r[d||``]))}var u=i.indexOf(`:`);u>0?(d=e.prefix=i.slice(0,u),f=e.localName=i.slice(u+1)):(d=null,f=e.localName=i);var m=e.uri=r[d||``];if(n.startElement(m,f,i,e),e.closed){if(n.endElement(m,f,i),a)for(d in a)Object.prototype.hasOwnProperty.call(a,d)&&n.endPrefixMapping(d)}else return e.currentNSMap=r,e.localNSMap=a,!0}function y(e,t,n,r,i){if(/^(?:script|textarea)$/i.test(n)){var a=e.indexOf(``,t),o=e.substring(t+1,a);if(/[&<]/.test(o))return/^script$/i.test(n)?(i.characters(o,0,o.length),a):(o=o.replace(/&#?\w+;/g,r),i.characters(o,0,o.length),a)}return t+1}function b(e,t,n,r){var i=r[n];return i??(i=e.lastIndexOf(``),i`,t+4);return i>t?(n.comment(e,t+4,i-t-4),i+3):(r.error(`Unclosed comment`),-1)}else return-1;default:if(e.substr(t+3,6)==`CDATA[`){var i=e.indexOf(`]]>`,t+9);return n.startCDATA(),n.characters(e,t+9,i-t-9),n.endCDATA(),i+3}var a=T(e,t),o=a.length;if(o>1&&/!doctype/i.test(a[0][0])){var s=a[1][0],c=!1,l=!1;o>3&&(/^public$/i.test(a[2][0])?(c=a[3][0],l=o>4&&a[4][0]):/^system$/i.test(a[2][0])&&(l=a[3][0]));var u=a[o-1];return n.startDTD(s,c,l),n.endDTD(),u.index+u[0].length}}return-1}function C(e,t,n){var r=e.indexOf(`?>`,t);if(r){var i=e.substring(t,r).match(/^<\?(\S*)\s*([\s\S]*?)$/);return i?(i[0].length,n.processingInstruction(i[1],i[2]),r+2):-1}return-1}function w(){this.attributeNames={}}w.prototype={setTagName:function(e){if(!i.test(e))throw Error(`invalid tagName:`+e);this.tagName=e},addValue:function(e,t,n){if(!i.test(e))throw Error(`invalid attribute:`+e);this.attributeNames[e]=this.length,this[this.length++]={qName:e,value:t,offset:n}},length:0,getLocalName:function(e){return this[e].localName},getLocator:function(e){return this[e].locator},getQName:function(e){return this[e].qName},getURI:function(e){return this[e].uri},getValue:function(e){return this[e].value}};function T(e,t){var n,r=[],i=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(i.lastIndex=t,i.exec(e);n=i.exec(e);)if(r.push(n),n[1])return r}e.XMLReader=m,e.ParseError=p})),ct=N((e=>{var t=it(),n=at(),r=ot(),i=st(),a=n.DOMImplementation,o=t.NAMESPACE,s=i.ParseError,c=i.XMLReader;function l(e){return e.replace(/\r[\n\u0085]/g,` `).replace(/[\r\u0085\u2028]/g,` `)}function u(e){this.options=e||{locator:{}}}u.prototype.parseFromString=function(e,t){var n=this.options,i=new c,a=n.domBuilder||new f,s=n.errorHandler,u=n.locator,p=n.xmlns||{},m=/\/x?html?$/.test(t),h=m?r.HTML_ENTITIES:r.XML_ENTITIES;u&&a.setDocumentLocator(u),i.errorHandler=d(s,a,u),i.domBuilder=n.domBuilder||a,m&&(p[``]=o.HTML),p.xml=p.xml||o.XML;var g=n.normalizeLineEndings||l;return e&&typeof e==`string`?i.parse(g(e),p,h):i.errorHandler.error(`invalid doc source`),a.doc};function d(e,t,n){if(!e){if(t instanceof f)return t;e=t}var r={},i=e instanceof Function;n||={};function a(t){var a=e[t];!a&&i&&(a=e.length==2?function(n){e(t,n)}:e),r[t]=a&&function(e){a(`[xmldom `+t+`] `+e+m(n))}||function(){}}return a(`warning`),a(`error`),a(`fatalError`),r}function f(){this.cdata=!1}function p(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}f.prototype={startDocument:function(){this.doc=new a().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,n,r){var i=this.doc,a=i.createElementNS(e,n||t),o=r.length;g(this,a),this.currentElement=a,this.locator&&p(this.locator,a);for(var s=0;s=t+n||t?new java.lang.String(e,t,n)+``:e}`endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl`.replace(/\w+/g,function(e){f.prototype[e]=function(){return null}});function g(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}e.__DOMHandler=f,e.normalizeLineEndings=l,e.DOMParser=u})),lt=N((e=>{var t=at();e.DOMImplementation=t.DOMImplementation,e.XMLSerializer=t.XMLSerializer,e.DOMParser=ct().DOMParser}))(),ut=e=>!!e&&typeof e==`object`,dt=(...e)=>e.reduce((e,t)=>(typeof t==`object`&&Object.keys(t).forEach(n=>{Array.isArray(e[n])&&Array.isArray(t[n])?e[n]=e[n].concat(t[n]):ut(e[n])&&ut(t[n])?e[n]=dt(e[n],t[n]):e[n]=t[n]}),e),{}),ft=e=>Object.keys(e).map(t=>e[t]),pt=(e,t)=>{let n=[];for(let r=e;re.reduce((e,t)=>e.concat(t),[]),ht=e=>{if(!e.length)return[];let t=[];for(let n=0;ne.reduce((e,n,r)=>(n[t]&&e.push(r),e),[]),_t=(e,t)=>ft(e.reduce((e,n)=>(n.forEach(n=>{e[t(n)]=n}),e),{})),vt={INVALID_NUMBER_OF_PERIOD:`INVALID_NUMBER_OF_PERIOD`,INVALID_NUMBER_OF_CONTENT_STEERING:`INVALID_NUMBER_OF_CONTENT_STEERING`,DASH_EMPTY_MANIFEST:`DASH_EMPTY_MANIFEST`,DASH_INVALID_XML:`DASH_INVALID_XML`,NO_BASE_URL:`NO_BASE_URL`,MISSING_SEGMENT_INFORMATION:`MISSING_SEGMENT_INFORMATION`,SEGMENT_TIME_UNSPECIFIED:`SEGMENT_TIME_UNSPECIFIED`,UNSUPPORTED_UTC_TIMING_SCHEME:`UNSUPPORTED_UTC_TIMING_SCHEME`},yt=({baseUrl:e=``,source:t=``,range:n=``,indexRange:r=``})=>{let i={uri:t,resolvedUri:ge(e||``,t)};if(n||r){let e=(n||r).split(`-`),t=I.default.BigInt?I.default.BigInt(e[0]):parseInt(e[0],10),a=I.default.BigInt?I.default.BigInt(e[1]):parseInt(e[1],10);t<2**53-1&&typeof t==`bigint`&&(t=Number(t)),a<2**53-1&&typeof a==`bigint`&&(a=Number(a));let o;o=typeof a==`bigint`||typeof t==`bigint`?I.default.BigInt(a)-I.default.BigInt(t)+I.default.BigInt(1):a-t+1,typeof o==`bigint`&&o<2**53-1&&(o=Number(o)),i.byterange={length:o,offset:t}}return i},bt=e=>{let t;return t=typeof e.offset==`bigint`||typeof e.length==`bigint`?I.default.BigInt(e.offset)+I.default.BigInt(e.length)-I.default.BigInt(1):e.offset+e.length-1,`${e.offset}-${t}`},xt=e=>(e&&typeof e!=`number`&&(e=parseInt(e,10)),isNaN(e)?null:e),St={static(e){let{duration:t,timescale:n=1,sourceDuration:r,periodDuration:i}=e,a=xt(e.endNumber),o=t/n;return typeof a==`number`?{start:0,end:a}:typeof i==`number`?{start:0,end:i/o}:{start:0,end:r/o}},dynamic(e){let{NOW:t,clientOffset:n,availabilityStartTime:r,timescale:i=1,duration:a,periodStart:o=0,minimumUpdatePeriod:s=0,timeShiftBufferDepth:c=1/0}=e,l=xt(e.endNumber),u=(t+n)/1e3,d=r+o,f=u+s-d,p=Math.ceil(f*i/a),m=Math.floor((u-d-c)*i/a),h=Math.floor((u-d)*i/a);return{start:Math.max(0,m),end:typeof l==`number`?l:Math.min(p,h)}}},Ct=e=>t=>{let{duration:n,timescale:r=1,periodStart:i,startNumber:a=1}=e;return{number:a+t,duration:n/r,timeline:i,time:t*n}},wt=e=>{let{type:t,duration:n,timescale:r=1,periodDuration:i,sourceDuration:a}=e,{start:o,end:s}=St[t](e),c=pt(o,s).map(Ct(e));if(t===`static`){let e=c.length-1,t=typeof i==`number`?i:a;c[e].duration=t-n/r*e}return c},Tt=e=>{let{baseUrl:t,initialization:n={},sourceDuration:r,indexRange:i=``,periodStart:a,presentationTime:o,number:s=0,duration:c}=e;if(!t)throw Error(vt.NO_BASE_URL);let l=yt({baseUrl:t,source:n.sourceURL,range:n.range}),u=yt({baseUrl:t,source:t,indexRange:i});if(u.map=l,c){let t=wt(e);t.length&&(u.duration=t[0].duration,u.timeline=t[0].timeline)}else r&&(u.duration=r,u.timeline=a);return u.presentationTime=o||a,u.number=s,[u]},Et=(e,t,n)=>{let r=e.sidx.map?e.sidx.map:null,i=e.sidx.duration,a=e.timeline||0,o=e.sidx.byterange,s=o.offset+o.length,c=t.timescale,l=t.references.filter(e=>e.referenceType!==1),u=[],d=e.endList?`static`:`dynamic`,f=e.sidx.timeline,p=f,m=e.mediaSequence||0,h;h=typeof t.firstOffset==`bigint`?I.default.BigInt(s)+t.firstOffset:s+t.firstOffset;for(let e=0;e_t(e,({timeline:e})=>e).sort((e,t)=>e.timeline>t.timeline?1:-1),At=(e,t)=>{for(let n=0;n{let t=[];return rt(e,Dt,(e,n,r,i)=>{t=t.concat(e.playlists||[])}),t},Mt=({playlist:e,mediaSequence:t})=>{e.mediaSequence=t,e.segments.forEach((t,n)=>{t.number=e.mediaSequence+n})},Nt=({oldPlaylists:e,newPlaylists:t,timelineStarts:n})=>{t.forEach(t=>{t.discontinuitySequence=n.findIndex(function({timeline:e}){return e===t.timeline});let r=At(e,t.attributes.NAME);if(!r||t.sidx)return;let i=t.segments[0],a=r.segments.findIndex(function(e){return Math.abs(e.presentationTime-i.presentationTime)r.timeline||r.segments.length&&t.timeline>r.segments[r.segments.length-1].timeline)&&t.discontinuitySequence--;return}r.segments[a].discontinuity&&!i.discontinuity&&(i.discontinuity=!0,t.discontinuityStarts.unshift(0),t.discontinuitySequence--),Mt({playlist:t,mediaSequence:r.segments[a].number})})},Pt=({oldManifest:e,newManifest:t})=>{let n=e.playlists.concat(jt(e)),r=t.playlists.concat(jt(t));return t.timelineStarts=kt([e.timelineStarts,t.timelineStarts]),Nt({oldPlaylists:n,newPlaylists:r,timelineStarts:t.timelineStarts}),t},Ft=e=>e&&e.uri+`-`+bt(e.byterange),It=e=>{let t=e.reduce(function(e,t){return e[t.attributes.baseUrl]||(e[t.attributes.baseUrl]=[]),e[t.attributes.baseUrl].push(t),e},{}),n=[];return Object.values(t).forEach(e=>{let t=ft(e.reduce((e,t)=>{let n=t.attributes.id+(t.attributes.lang||``);return e[n]?(t.segments&&(t.segments[0]&&(t.segments[0].discontinuity=!0),e[n].segments.push(...t.segments)),t.attributes.contentProtection&&(e[n].attributes.contentProtection=t.attributes.contentProtection)):(e[n]=t,e[n].attributes.timelineStarts=[]),e[n].attributes.timelineStarts.push({start:t.attributes.periodStart,timeline:t.attributes.periodStart}),e},{}));n=n.concat(t)}),n.map(e=>(e.discontinuityStarts=gt(e.segments||[],`discontinuity`),e))},Lt=(e,t)=>{let n=Ft(e.sidx),r=n&&t[n]&&t[n].sidx;return r&&Et(e,r,e.sidx.resolvedUri),e},Rt=(e,t={})=>{if(!Object.keys(t).length)return e;for(let n in e)e[n]=Lt(e[n],t);return e},zt=({attributes:e,segments:t,sidx:n,mediaSequence:r,discontinuitySequence:i,discontinuityStarts:a},o)=>{let s={attributes:{NAME:e.id,BANDWIDTH:e.bandwidth,CODECS:e.codecs,"PROGRAM-ID":1},uri:``,endList:e.type===`static`,timeline:e.periodStart,resolvedUri:e.baseUrl||``,targetDuration:e.duration,discontinuitySequence:i,discontinuityStarts:a,timelineStarts:e.timelineStarts,mediaSequence:r,segments:t};return e.contentProtection&&(s.contentProtection=e.contentProtection),e.serviceLocation&&(s.attributes.serviceLocation=e.serviceLocation),n&&(s.sidx=n),o&&(s.attributes.AUDIO=`audio`,s.attributes.SUBTITLES=`subs`),s},Bt=({attributes:e,segments:t,mediaSequence:n,discontinuityStarts:r,discontinuitySequence:i})=>{t===void 0&&(t=[{uri:e.baseUrl,timeline:e.periodStart,resolvedUri:e.baseUrl||``,duration:e.sourceDuration,number:0}],e.duration=e.sourceDuration);let a={NAME:e.id,BANDWIDTH:e.bandwidth,"PROGRAM-ID":1};e.codecs&&(a.CODECS=e.codecs);let o={attributes:a,uri:``,endList:e.type===`static`,timeline:e.periodStart,resolvedUri:e.baseUrl||``,targetDuration:e.duration,timelineStarts:e.timelineStarts,discontinuityStarts:r,discontinuitySequence:i,mediaSequence:n,segments:t};return e.serviceLocation&&(o.attributes.serviceLocation=e.serviceLocation),o},Vt=(e,t={},n=!1)=>{let r,i=e.reduce((e,i)=>{let a=i.attributes.role&&i.attributes.role.value||``,o=i.attributes.lang||``,s=i.attributes.label||`main`;if(o&&!i.attributes.label){let e=a?` (${a})`:``;s=`${i.attributes.lang}${e}`}e[s]||(e[s]={language:o,autoselect:!0,default:a===`main`,playlists:[],uri:``});let c=Lt(zt(i,n),t);return e[s].playlists.push(c),r===void 0&&a===`main`&&(r=i,r.default=!0),e},{});if(!r){let e=Object.keys(i)[0];i[e].default=!0}return i},Ht=(e,t={})=>e.reduce((e,n)=>{let r=n.attributes.label||n.attributes.lang||`text`,i=n.attributes.lang||`und`;return e[r]||(e[r]={language:i,default:!1,autoselect:!1,playlists:[],uri:``}),e[r].playlists.push(Lt(Bt(n),t)),e},{}),Ut=e=>e.reduce((e,t)=>(t&&t.forEach(t=>{let{channel:n,language:r}=t;e[r]={autoselect:!1,default:!1,instreamId:n,language:r},t.hasOwnProperty(`aspectRatio`)&&(e[r].aspectRatio=t.aspectRatio),t.hasOwnProperty(`easyReader`)&&(e[r].easyReader=t.easyReader),t.hasOwnProperty(`3D`)&&(e[r][`3D`]=t[`3D`])}),e),{}),Wt=({attributes:e,segments:t,sidx:n,discontinuityStarts:r})=>{let i={attributes:{NAME:e.id,AUDIO:`audio`,SUBTITLES:`subs`,RESOLUTION:{width:e.width,height:e.height},CODECS:e.codecs,BANDWIDTH:e.bandwidth,"PROGRAM-ID":1},uri:``,endList:e.type===`static`,timeline:e.periodStart,resolvedUri:e.baseUrl||``,targetDuration:e.duration,discontinuityStarts:r,timelineStarts:e.timelineStarts,segments:t};return e.frameRate&&(i.attributes[`FRAME-RATE`]=e.frameRate),e.contentProtection&&(i.contentProtection=e.contentProtection),e.serviceLocation&&(i.attributes.serviceLocation=e.serviceLocation),n&&(i.sidx=n),i},Gt=({attributes:e})=>e.mimeType===`video/mp4`||e.mimeType===`video/webm`||e.contentType===`video`,Kt=({attributes:e})=>e.mimeType===`audio/mp4`||e.mimeType===`audio/webm`||e.contentType===`audio`,qt=({attributes:e})=>e.mimeType===`text/vtt`||e.contentType===`text`,Jt=(e,t)=>{e.forEach(e=>{e.mediaSequence=0,e.discontinuitySequence=t.findIndex(function({timeline:t}){return t===e.timeline}),e.segments&&e.segments.forEach((e,t)=>{e.number=t})})},Yt=e=>e?Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(r.playlists)},[]):[],Xt=({dashPlaylists:e,locations:t,contentSteering:n,sidxMapping:r={},previousManifest:i,eventStream:a})=>{if(!e.length)return{};let{sourceDuration:o,type:s,suggestedPresentationDelay:c,minimumUpdatePeriod:l}=e[0].attributes,u=It(e.filter(Gt)).map(Wt),d=It(e.filter(Kt)),f=It(e.filter(qt)),p=e.map(e=>e.attributes.captionServices).filter(Boolean),m={allowCache:!0,discontinuityStarts:[],segments:[],endList:!0,mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:``,duration:o,playlists:Rt(u,r)};l>=0&&(m.minimumUpdatePeriod=l*1e3),t&&(m.locations=t),n&&(m.contentSteering=n),s===`dynamic`&&(m.suggestedPresentationDelay=c),a&&a.length>0&&(m.eventStream=a);let h=m.playlists.length===0,g=d.length?Vt(d,r,h):null,_=f.length?Ht(f,r):null,v=u.concat(Yt(g),Yt(_));return m.timelineStarts=kt(v.map(({timelineStarts:e})=>e)),Jt(v,m.timelineStarts),g&&(m.mediaGroups.AUDIO.audio=g),_&&(m.mediaGroups.SUBTITLES.subs=_),p.length&&(m.mediaGroups[`CLOSED-CAPTIONS`].cc=Ut(p)),i?Pt({oldManifest:i,newManifest:m}):m},Zt=(e,t,n)=>{let{NOW:r,clientOffset:i,availabilityStartTime:a,timescale:o=1,periodStart:s=0,minimumUpdatePeriod:c=0}=e,l=(r+i)/1e3,u=a+s,d=l+c-u;return Math.ceil((d*o-t)/n)},Qt=(e,t)=>{let{type:n,minimumUpdatePeriod:r=0,media:i=``,sourceDuration:a,timescale:o=1,startNumber:s=1,periodStart:c}=e,l=[],u=-1;for(let d=0;du&&(u=h);let g;if(m<0){let s=d+1;g=s===t.length?n===`dynamic`&&r>0&&i.indexOf(`$Number$`)>0?Zt(e,u,p):(a*o-u)/p:(t[s].t-u)/p}else g=m+1;let _=s+l.length+g,v=s+l.length;for(;v<_;)l.push({number:v,duration:p/o,time:u,timeline:c}),u+=p,v++}return l},$t=/\$([A-z]*)(?:(%0)([0-9]+)d)?\$/g,en=e=>(t,n,r,i)=>{if(t===`$$`)return`$`;if(e[n]===void 0)return t;let a=``+e[n];return n===`RepresentationID`||(i=r?parseInt(i,10):1,a.length>=i)?a:`${Array(i-a.length+1).join(`0`)}${a}`},tn=(e,t)=>e.replace($t,en(t)),nn=(e,t)=>!e.duration&&!t?[{number:e.startNumber||1,duration:e.sourceDuration,time:0,timeline:e.periodStart}]:e.duration?wt(e):Qt(e,t),rn=(e,t)=>{let n={RepresentationID:e.id,Bandwidth:e.bandwidth||0},{initialization:r={sourceURL:``,range:``}}=e,i=yt({baseUrl:e.baseUrl,source:tn(r.sourceURL,n),range:r.range});return nn(e,t).map(t=>{n.Number=t.number,n.Time=t.time;let r=tn(e.media||``,n),a=e.timescale||1,o=e.presentationTimeOffset||0,s=e.periodStart+(t.time-o)/a;return{uri:r,timeline:t.timeline,duration:t.duration,resolvedUri:ge(e.baseUrl||``,r),map:i,number:t.number,presentationTime:s}})},an=(e,t)=>{let{baseUrl:n,initialization:r={}}=e,i=yt({baseUrl:n,source:r.sourceURL,range:r.range}),a=yt({baseUrl:n,source:t.media,range:t.mediaRange});return a.map=i,a},on=(e,t)=>{let{duration:n,segmentUrls:r=[],periodStart:i}=e;if(!n&&!t||n&&t)throw Error(vt.SEGMENT_TIME_UNSPECIFIED);let a=r.map(t=>an(e,t)),o;return n&&(o=wt(e)),t&&(o=Qt(e,t)),o.map((t,n)=>{if(a[n]){let r=a[n],o=e.timescale||1,s=e.presentationTimeOffset||0;return r.timeline=t.timeline,r.duration=t.duration,r.number=t.number,r.presentationTime=i+(t.time-s)/o,r}}).filter(e=>e)},sn=({attributes:e,segmentInfo:t})=>{let n,r;t.template?(r=rn,n=dt(e,t.template)):t.base?(r=Tt,n=dt(e,t.base)):t.list&&(r=on,n=dt(e,t.list));let i={attributes:e};if(!r)return i;let a=r(n,t.segmentTimeline);if(n.duration){let{duration:e,timescale:t=1}=n;n.duration=e/t}else a.length?n.duration=a.reduce((e,t)=>Math.max(e,Math.ceil(t.duration)),0):n.duration=0;return i.attributes=n,i.segments=a,t.base&&n.indexRange&&(i.sidx=a[0],i.segments=[]),i},cn=e=>e.map(sn),ln=(e,t)=>ht(e.childNodes).filter(({tagName:e})=>e===t),un=e=>e.textContent.trim(),dn=e=>parseFloat(e.split(`/`).reduce((e,t)=>e/t)),fn=e=>{let t=/P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/.exec(e);if(!t)return 0;let[n,r,i,a,o,s]=t.slice(1);return parseFloat(n||0)*31536e3+parseFloat(r||0)*2592e3+parseFloat(i||0)*86400+parseFloat(a||0)*3600+parseFloat(o||0)*60+parseFloat(s||0)},pn=e=>(/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(e)&&(e+=`Z`),Date.parse(e)),mn={mediaPresentationDuration(e){return fn(e)},availabilityStartTime(e){return pn(e)/1e3},minimumUpdatePeriod(e){return fn(e)},suggestedPresentationDelay(e){return fn(e)},type(e){return e},timeShiftBufferDepth(e){return fn(e)},start(e){return fn(e)},width(e){return parseInt(e,10)},height(e){return parseInt(e,10)},bandwidth(e){return parseInt(e,10)},frameRate(e){return dn(e)},startNumber(e){return parseInt(e,10)},timescale(e){return parseInt(e,10)},presentationTimeOffset(e){return parseInt(e,10)},duration(e){let t=parseInt(e,10);return isNaN(t)?fn(e):t},d(e){return parseInt(e,10)},t(e){return parseInt(e,10)},r(e){return parseInt(e,10)},presentationTime(e){return parseInt(e,10)},DEFAULT(e){return e}},hn=e=>e&&e.attributes?ht(e.attributes).reduce((e,t)=>{let n=mn[t.name]||mn.DEFAULT;return e[t.name]=n(t.value),e},{}):{},gn={"urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b":`org.w3.clearkey`,"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed":`com.widevine.alpha`,"urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95":`com.microsoft.playready`,"urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb":`com.adobe.primetime`,"urn:mpeg:dash:mp4protection:2011":`mp4protection`},_n=(e,t)=>t.length?mt(e.map(function(e){return t.map(function(t){let n=un(t),r=ge(e.baseUrl,n),i=dt(hn(t),{baseUrl:r});return r!==n&&!i.serviceLocation&&e.serviceLocation&&(i.serviceLocation=e.serviceLocation),i})})):e,vn=e=>{let t=ln(e,`SegmentTemplate`)[0],n=ln(e,`SegmentList`)[0],r=n&&ln(n,`SegmentURL`).map(e=>dt({tag:`SegmentURL`},hn(e))),i=ln(e,`SegmentBase`)[0],a=n||t,o=a&&ln(a,`SegmentTimeline`)[0],s=n||i||t,c=s&&ln(s,`Initialization`)[0],l=t&&hn(t);l&&c?l.initialization=c&&hn(c):l&&l.initialization&&(l.initialization={sourceURL:l.initialization});let u={template:l,segmentTimeline:o&&ln(o,`S`).map(e=>hn(e)),list:n&&dt(hn(n),{segmentUrls:r,initialization:hn(c)}),base:i&&dt(hn(i),{initialization:hn(c)})};return Object.keys(u).forEach(e=>{u[e]||delete u[e]}),u},yn=(e,t,n)=>r=>{let i=_n(t,ln(r,`BaseURL`)),a=dt(e,hn(r)),o=vn(r);return i.map(e=>({segmentInfo:dt(n,o),attributes:dt(a,e)}))},bn=e=>e.reduce((e,t)=>{let n=hn(t);n.schemeIdUri&&=n.schemeIdUri.toLowerCase();let r=gn[n.schemeIdUri];if(r){e[r]={attributes:n};let i=ln(t,`cenc:pssh`)[0];if(i){let t=un(i);e[r].pssh=t&&ye(t)}}return e},{}),xn=e=>{if(e.schemeIdUri===`urn:scte:dash:cc:cea-608:2015`)return(typeof e.value==`string`?e.value.split(`;`):[]).map(e=>{let t,n;return n=e,/^CC\d=/.test(e)?[t,n]=e.split(`=`):/^CC\d$/.test(e)&&(t=e),{channel:t,language:n}});if(e.schemeIdUri===`urn:scte:dash:cc:cea-708:2015`)return(typeof e.value==`string`?e.value.split(`;`):[]).map(e=>{let t={channel:void 0,language:void 0,aspectRatio:1,easyReader:0,"3D":0};if(/=/.test(e)){let[n,r=``]=e.split(`=`);t.channel=n,t.language=e,r.split(`,`).forEach(e=>{let[n,r]=e.split(`:`);n===`lang`?t.language=r:n===`er`?t.easyReader=Number(r):n===`war`?t.aspectRatio=Number(r):n===`3D`&&(t[`3D`]=Number(r))})}else t.language=e;return t.channel&&=`SERVICE`+t.channel,t})},Sn=e=>mt(ln(e.node,`EventStream`).map(t=>{let n=hn(t),r=n.schemeIdUri;return ln(t,`Event`).map(t=>{let i=hn(t),a=i.presentationTime||0,o=n.timescale||1,s=i.duration||0,c=a/o+e.attributes.start;return{schemeIdUri:r,value:n.value,id:i.id,start:c,end:c+s/o,messageData:un(t)||i.messageData,contentEncoding:n.contentEncoding,presentationTimeOffset:n.presentationTimeOffset||0}})})),Cn=(e,t,n)=>r=>{let i=hn(r),a=_n(t,ln(r,`BaseURL`)),o=ln(r,`Role`)[0],s=dt(e,i,{role:hn(o)}),c=ln(r,`Accessibility`)[0],l=xn(hn(c));l&&(s=dt(s,{captionServices:l}));let u=ln(r,`Label`)[0];if(u&&u.childNodes.length){let e=u.childNodes[0].nodeValue.trim();s=dt(s,{label:e})}let d=bn(ln(r,`ContentProtection`));Object.keys(d).length&&(s=dt(s,{contentProtection:d}));let f=vn(r),p=ln(r,`Representation`),m=dt(n,f);return mt(p.map(yn(s,a,m)))},wn=(e,t)=>(n,r)=>{let i=_n(t,ln(n.node,`BaseURL`)),a=dt(e,{periodStart:n.attributes.start});typeof n.attributes.duration==`number`&&(a.periodDuration=n.attributes.duration);let o=ln(n.node,`AdaptationSet`),s=vn(n.node);return mt(o.map(Cn(a,i,s)))},Tn=(e,t)=>{if(e.length>1&&t({type:`warn`,message:`The MPD manifest should contain no more than one ContentSteering tag`}),!e.length)return null;let n=dt({serverURL:un(e[0])},hn(e[0]));return n.queryBeforeStart=n.queryBeforeStart===`true`,n},En=({attributes:e,priorPeriodAttributes:t,mpdType:n})=>typeof e.start==`number`?e.start:t&&typeof t.start==`number`&&typeof t.duration==`number`?t.start+t.duration:!t&&n===`static`?0:null,Dn=(e,t={})=>{let{manifestUri:n=``,NOW:r=Date.now(),clientOffset:i=0,eventHandler:a=function(){}}=t,o=ln(e,`Period`);if(!o.length)throw Error(vt.INVALID_NUMBER_OF_PERIOD);let s=ln(e,`Location`),c=hn(e),l=_n([{baseUrl:n}],ln(e,`BaseURL`)),u=ln(e,`ContentSteering`);c.type=c.type||`static`,c.sourceDuration=c.mediaPresentationDuration||0,c.NOW=r,c.clientOffset=i,s.length&&(c.locations=s.map(un));let d=[];return o.forEach((e,t)=>{let n=hn(e),r=d[t-1];n.start=En({attributes:n,priorPeriodAttributes:r?r.attributes:null,mpdType:c.type}),d.push({node:e,attributes:n})}),{locations:c.locations,contentSteeringInfo:Tn(u,a),representationInfo:mt(d.map(wn(c,l))),eventStream:mt(d.map(Sn))}},On=e=>{if(e===``)throw Error(vt.DASH_EMPTY_MANIFEST);let t=new lt.DOMParser,n,r;try{n=t.parseFromString(e,`application/xml`),r=n&&n.documentElement.tagName===`MPD`?n.documentElement:null}catch{}if(!r||r&&r.getElementsByTagName(`parsererror`).length>0)throw Error(vt.DASH_INVALID_XML);return r},kn=e=>{let t=ln(e,`UTCTiming`)[0];if(!t)return null;let n=hn(t);switch(n.schemeIdUri){case`urn:mpeg:dash:utc:http-head:2014`:case`urn:mpeg:dash:utc:http-head:2012`:n.method=`HEAD`;break;case`urn:mpeg:dash:utc:http-xsdate:2014`:case`urn:mpeg:dash:utc:http-iso:2014`:case`urn:mpeg:dash:utc:http-xsdate:2012`:case`urn:mpeg:dash:utc:http-iso:2012`:n.method=`GET`;break;case`urn:mpeg:dash:utc:direct:2014`:case`urn:mpeg:dash:utc:direct:2012`:n.method=`DIRECT`,n.value=Date.parse(n.value);break;default:throw Error(vt.UNSUPPORTED_UTC_TIMING_SCHEME)}return n},An=(e,t={})=>{let n=Dn(On(e),t);return Xt({dashPlaylists:cn(n.representationInfo),locations:n.locations,contentSteering:n.contentSteeringInfo,sidxMapping:t.sidxMapping,previousManifest:t.previousManifest,eventStream:n.eventStream})},jn=e=>kn(On(e)),Mn=N(((e,t)=>{var n=2**32;t.exports={getUint64:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),r;return t.getBigUint64?(r=t.getBigUint64(0),r<2**53-1?Number(r):r):t.getUint32(0)*n+t.getUint32(4)},MAX_UINT32:n}})),Nn=P(N(((e,t)=>{var n=Mn().getUint64;t.exports=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),r={version:e[0],flags:new Uint8Array(e.subarray(1,4)),references:[],referenceId:t.getUint32(4),timescale:t.getUint32(8)},i=12;r.version===0?(r.earliestPresentationTime=t.getUint32(i),r.firstOffset=t.getUint32(i+4),i+=8):(r.earliestPresentationTime=n(e.subarray(i)),r.firstOffset=n(e.subarray(i+8)),i+=16),i+=2;var a=t.getUint16(i);for(i+=2;a>0;i+=12,a--)r.references.push({referenceType:(e[i]&128)>>>7,referencedSize:t.getUint32(i)&2147483647,subsegmentDuration:t.getUint32(i+4),startsWithSap:!!(e[i+8]&128),sapType:(e[i+8]&112)>>>4,sapDeltaTime:t.getUint32(i+8)&268435455});return r}}))()),Pn=z([73,68,51]),Fn=function(e,t){t===void 0&&(t=0),e=z(e);var n=e[t+5],r=e[t+6]<<21|e[t+7]<<14|e[t+8]<<7|e[t+9];return(n&16)>>4?r+20:r+10},In=function e(t,n){return n===void 0&&(n=0),t=z(t),t.length-n<10||!nt(t,Pn,{offset:n})?n:(n+=Fn(t,n),e(t,n))};new Uint8Array([79,112,117,115,72,101,97,100]);var Ln=function(e){return typeof e==`string`?et(e):e},Rn=function(e){return Array.isArray(e)?e.map(function(e){return Ln(e)}):[Ln(e)]},zn,Bn=function(e){e=z(e);for(var t=[],n=0;e.length>n;){var r=e[n],i=0,a=0;a++;var o=e[a];for(a++;o&128;)i=(o&127)<<7,o=e[a],a++;i+=o&127;for(var s=0;s>>0,s=t.subarray(a+4,a+8);if(o===0)break;var c=a+o;if(c>t.length){if(r)break;c=t.length}var l=t.subarray(a+8,c);nt(s,n[0])&&(n.length===1?i.push(l):i.push.apply(i,e(l,n.slice(1),r))),a=c}return i},Hn={EBML:z([26,69,223,163]),DocType:z([66,130]),Segment:z([24,83,128,103]),SegmentInfo:z([21,73,169,102]),Tracks:z([22,84,174,107]),Track:z([174]),TrackNumber:z([215]),DefaultDuration:z([35,227,131]),TrackEntry:z([174]),TrackType:z([131]),FlagDefault:z([136]),CodecID:z([134]),CodecPrivate:z([99,162]),VideoTrack:z([224]),AudioTrack:z([225]),Cluster:z([31,67,182,117]),Timestamp:z([231]),TimestampScale:z([42,215,177]),BlockGroup:z([160]),BlockDuration:z([155]),Block:z([161]),SimpleBlock:z([163])},Un=[128,64,32,16,8,4,2,1],Wn=function(e){for(var t=1,n=0;n=n.length)return n.length;var i=Gn(n,r,!1);if(nt(t.bytes,i.bytes))return r;var a=Gn(n,r+i.length);return e(t,n,r+a.length+a.value+i.length)},Yn=function e(t,n){n=qn(n),t=z(t);var r=[];if(!n.length)return r;for(var i=0;it.length?t.length:s+o.value,l=t.subarray(s,c);nt(n[0],a.bytes)&&(n.length===1?r.push(l):r=r.concat(e(l,n.slice(1))));var u=a.length+o.length+l.length;i+=u}return r},Xn=z([0,0,0,1]),Zn=z([0,0,1]),Qn=z([0,0,3]),$n=function(e){for(var t=[],n=1;n>1&63),n.indexOf(c)!==-1&&(a=i+s),i+=s+(t===`h264`?1:2)}return e.subarray(0,0)},tr=function(e,t,n){return er(e,`h264`,t,n)},nr=function(e,t,n){return er(e,`h265`,t,n)},rr={webm:z([119,101,98,109]),matroska:z([109,97,116,114,111,115,107,97]),flac:z([102,76,97,67]),ogg:z([79,103,103,83]),ac3:z([11,119]),riff:z([82,73,70,70]),avi:z([65,86,73]),wav:z([87,65,86,69]),"3gp":z([102,116,121,112,51,103]),mp4:z([102,116,121,112]),fmp4:z([115,116,121,112]),mov:z([102,116,121,112,113,116]),moov:z([109,111,111,118]),moof:z([109,111,111,102])},ir={aac:function(e){return nt(e,[255,16],{offset:In(e),mask:[255,22]})},mp3:function(e){return nt(e,[255,2],{offset:In(e),mask:[255,6]})},webm:function(e){var t=Yn(e,[Hn.EBML,Hn.DocType])[0];return nt(t,rr.webm)},mkv:function(e){var t=Yn(e,[Hn.EBML,Hn.DocType])[0];return nt(t,rr.matroska)},mp4:function(e){if(ir[`3gp`](e)||ir.mov(e))return!1;if(nt(e,rr.mp4,{offset:4})||nt(e,rr.fmp4,{offset:4})||nt(e,rr.moof,{offset:4})||nt(e,rr.moov,{offset:4}))return!0},mov:function(e){return nt(e,rr.mov,{offset:4})},"3gp":function(e){return nt(e,rr[`3gp`],{offset:4})},ac3:function(e){var t=In(e);return nt(e,rr.ac3,{offset:t})},ts:function(e){if(e.length<189&&e.length>=1)return e[0]===71;for(var t=0;t+1880},lr=N(((e,t)=>{var n=9e4,r=function(e){return e*n},i=function(e,t){return e*t},a=function(e){return e/n},o=function(e,t){return e/t};t.exports={ONE_SECOND_IN_TS:n,secondsToVideoTs:r,secondsToAudioTs:i,videoTsToSeconds:a,audioTsToSeconds:o,audioTsToVideoTs:function(e,t){return r(o(e,t))},videoTsToAudioTs:function(e,t){return i(a(e),t)},metadataTsToSeconds:function(e,t,n){return a(n?e:e-t)}}}))(),ur=`8.23.7`,dr={},fr=function(e,t){return dr[e]=dr[e]||[],t&&(dr[e]=dr[e].concat(t)),dr[e]},pr=function(e,t){fr(e,t)},mr=function(e,t){let n=fr(e).indexOf(t);return n<=-1?!1:(dr[e]=dr[e].slice(),dr[e].splice(n,1),!0)},hr=function(e,t){fr(e,[].concat(t).map(t=>{let n=(...r)=>(mr(e,n),t(...r));return n}))},gr={prefixed:!0},_r=[[`requestFullscreen`,`exitFullscreen`,`fullscreenElement`,`fullscreenEnabled`,`fullscreenchange`,`fullscreenerror`,`fullscreen`],[`webkitRequestFullscreen`,`webkitExitFullscreen`,`webkitFullscreenElement`,`webkitFullscreenEnabled`,`webkitfullscreenchange`,`webkitfullscreenerror`,`-webkit-full-screen`]],vr=_r[0],yr;for(let e=0;e<_r.length;e++)if(_r[e][1]in L.default){yr=_r[e];break}if(yr){for(let e=0;e(r,i,a)=>{let o=t.levels[i],s=RegExp(`^(${o})$`),c=e;if(r!==`log`&&a.unshift(r.toUpperCase()+`:`),n&&(c=`%c${e}`,a.unshift(n)),a.unshift(c+`:`),br){br.push([].concat(a));let e=br.length-1e3;br.splice(0,e>0?e:0)}if(!I.default.console)return;let l=I.default.console[r];!l&&r===`debug`&&(l=I.default.console.info||I.default.console.log),!(!l||!o||!s.test(r))&&l[Array.isArray(a)?`apply`:`call`](I.default.console,a)};function Sr(e,t=`:`,n=``){let r=`info`,i;function a(...e){i(`log`,r,e)}return i=xr(e,a,n),a.createLogger=(r,i,a)=>{let o=i===void 0?t:i,s=a===void 0?n:a;return Sr(`${e} ${o} ${r}`,o,s)},a.createNewLogger=(e,t,n)=>Sr(e,t,n),a.levels={all:`debug|log|warn|error`,off:``,debug:`debug|log|warn|error`,info:`log|warn|error`,warn:`warn|error`,error:`error`,DEFAULT:r},a.level=e=>{if(typeof e==`string`){if(!a.levels.hasOwnProperty(e))throw Error(`"${e}" in not a valid log level`);r=e}return r},a.history=()=>br?[].concat(br):[],a.history.filter=e=>(br||[]).filter(t=>RegExp(`.*${e}.*`).test(t[0])),a.history.clear=()=>{br&&(br.length=0)},a.history.disable=()=>{br!==null&&(br.length=0,br=null)},a.history.enable=()=>{br===null&&(br=[])},a.error=(...e)=>i(`error`,r,e),a.warn=(...e)=>i(`warn`,r,e),a.debug=(...e)=>i(`debug`,r,e),a}var B=Sr(`VIDEOJS`),Cr=B.createLogger,wr=Object.prototype.toString,Tr=function(e){return Or(e)?Object.keys(e):[]};function Er(e,t){Tr(e).forEach(n=>t(e[n],n))}function Dr(e,t,n=0){return Tr(e).reduce((n,r)=>t(n,e[r],r),n)}function Or(e){return!!e&&typeof e==`object`}function kr(e){return Or(e)&&wr.call(e)===`[object Object]`&&e.constructor===Object}function Ar(...e){let t={};return e.forEach(e=>{e&&Er(e,(e,n)=>{if(!kr(e)){t[n]=e;return}kr(t[n])||(t[n]={}),t[n]=Ar(t[n],e)})}),t}function jr(e={}){let t=[];for(let n in e)if(e.hasOwnProperty(n)){let r=e[n];t.push(r)}return t}function Mr(e,t,n,r=!0){let i=n=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0}),a={configurable:!0,enumerable:!0,get(){let e=n();return i(e),e}};return r&&(a.set=i),Object.defineProperty(e,t,a)}var Nr=Object.freeze({__proto__:null,each:Er,reduce:Dr,isObject:Or,isPlain:kr,merge:Ar,values:jr,defineLazyProperty:Mr}),Pr=!1,Fr=null,Ir=!1,Lr,Rr=!1,zr=!1,Br=!1,Vr=!1,Hr=null,Ur=null,Wr=!!(I.default.cast&&I.default.cast.framework&&I.default.cast.framework.CastReceiverContext),Gr=null,Kr=!1,qr=!1,Jr=!1,Yr=!1,Xr=!1,Zr=!1,Qr=!1,$r=!!(oi()&&(`ontouchstart`in I.default||I.default.navigator.maxTouchPoints||I.default.DocumentTouch&&I.default.document instanceof I.default.DocumentTouch)),ei=I.default.navigator&&I.default.navigator.userAgentData;if(ei&&ei.platform&&ei.brands&&(Ir=ei.platform===`Android`,zr=!!ei.brands.find(e=>e.brand===`Microsoft Edge`),Br=!!ei.brands.find(e=>e.brand===`Chromium`),Vr=!zr&&Br,Hr=Ur=(ei.brands.find(e=>e.brand===`Chromium`)||{}).version||null,qr=ei.platform===`Windows`),!Br){let e=I.default.navigator&&I.default.navigator.userAgent||``;Pr=/iPod/i.test(e),Fr=function(){let t=e.match(/OS (\d+)_/i);return t&&t[1]?t[1]:null}(),Ir=/Android/i.test(e),Lr=function(){let t=e.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!t)return null;let n=t[1]&&parseFloat(t[1]),r=t[2]&&parseFloat(t[2]);return n&&r?parseFloat(t[1]+`.`+t[2]):n||null}(),Rr=/Firefox/i.test(e),zr=/Edg/i.test(e),Br=/Chrome/i.test(e)||/CriOS/i.test(e),Vr=!zr&&Br,Hr=Ur=function(){let t=e.match(/(Chrome|CriOS)\/(\d+)/);return t&&t[2]?parseFloat(t[2]):null}(),Gr=function(){let t=/MSIE\s(\d+)\.\d/.exec(e),n=t&&parseFloat(t[1]);return!n&&/Trident\/7.0/i.test(e)&&/rv:11.0/.test(e)&&(n=11),n}(),Xr=/Tizen/i.test(e),Zr=/Web0S/i.test(e),Qr=Xr||Zr,Kr=/Safari/i.test(e)&&!Vr&&!Ir&&!zr&&!Qr,qr=/Windows/i.test(e),Jr=/iPad/i.test(e)||Kr&&$r&&!/iPhone/i.test(e),Yr=/iPhone/i.test(e)&&!Jr}var ti=Yr||Jr||Pr,ni=(Kr||ti)&&!Vr,ri=Object.freeze({__proto__:null,get IS_IPOD(){return Pr},get IOS_VERSION(){return Fr},get IS_ANDROID(){return Ir},get ANDROID_VERSION(){return Lr},get IS_FIREFOX(){return Rr},get IS_EDGE(){return zr},get IS_CHROMIUM(){return Br},get IS_CHROME(){return Vr},get CHROMIUM_VERSION(){return Hr},get CHROME_VERSION(){return Ur},IS_CHROMECAST_RECEIVER:Wr,get IE_VERSION(){return Gr},get IS_SAFARI(){return Kr},get IS_WINDOWS(){return qr},get IS_IPAD(){return Jr},get IS_IPHONE(){return Yr},get IS_TIZEN(){return Xr},get IS_WEBOS(){return Zr},get IS_SMART_TV(){return Qr},TOUCH_ENABLED:$r,IS_IOS:ti,IS_ANY_SAFARI:ni});function ii(e){return typeof e==`string`&&!!e.trim()}function ai(e){if(e.indexOf(` `)>=0)throw Error(`class has illegal whitespace characters`)}function oi(){return L.default===I.default.document}function si(e){return Or(e)&&e.nodeType===1}function ci(){try{return I.default.parent!==I.default.self}catch{return!0}}function li(e){return function(t,n){if(!ii(t))return L.default[e](null);ii(n)&&(n=L.default.querySelector(n));let r=si(n)?n:L.default;return r[e]&&r[e](t)}}function V(e=`div`,t={},n={},r){let i=L.default.createElement(e);return Object.getOwnPropertyNames(t).forEach(function(e){let n=t[e];e===`textContent`?ui(i,n):(i[e]!==n||e===`tabIndex`)&&(i[e]=n)}),Object.getOwnPropertyNames(n).forEach(function(e){i.setAttribute(e,n[e])}),r&&ki(i,r),i}function ui(e,t){return e.textContent===void 0?e.innerText=t:e.textContent=t,e}function di(e,t){t.firstChild?t.insertBefore(e,t.firstChild):t.appendChild(e)}function fi(e,t){return ai(t),e.classList.contains(t)}function pi(e,...t){return e.classList.add(...t.reduce((e,t)=>e.concat(t.split(/\s+/)),[])),e}function mi(e,...t){return e?(e.classList.remove(...t.reduce((e,t)=>e.concat(t.split(/\s+/)),[])),e):(B.warn(`removeClass was called with an element that doesn't exist`),null)}function hi(e,t,n){return typeof n==`function`&&(n=n(e,t)),typeof n!=`boolean`&&(n=void 0),t.split(/\s+/).forEach(t=>e.classList.toggle(t,n)),e}function gi(e,t){Object.getOwnPropertyNames(t).forEach(function(n){let r=t[n];r==null||r===!1?e.removeAttribute(n):e.setAttribute(n,r===!0?``:r)})}function _i(e){let t={},n=[`autoplay`,`controls`,`playsinline`,`loop`,`muted`,`default`,`defaultMuted`];if(e&&e.attributes&&e.attributes.length>0){let r=e.attributes;for(let e=r.length-1;e>=0;e--){let i=r[e].name,a=r[e].value;n.includes(i)&&(a=a!==null),t[i]=a}}return t}function vi(e,t){return e.getAttribute(t)}function yi(e,t,n){e.setAttribute(t,n)}function bi(e,t){e.removeAttribute(t)}function xi(){L.default.body.focus(),L.default.onselectstart=function(){return!1}}function Si(){L.default.onselectstart=function(){return!0}}function Ci(e){if(e&&e.getBoundingClientRect&&e.parentNode){let t=e.getBoundingClientRect(),n={};return[`bottom`,`height`,`left`,`right`,`top`,`width`].forEach(e=>{t[e]!==void 0&&(n[e]=t[e])}),n.height||=parseFloat(Pi(e,`height`)),n.width||=parseFloat(Pi(e,`width`)),n}}function wi(e){if(!e||e&&!e.offsetParent)return{left:0,top:0,width:0,height:0};let t=e.offsetWidth,n=e.offsetHeight,r=0,i=0;for(;e.offsetParent&&e!==L.default[gr.fullscreenElement];)r+=e.offsetLeft,i+=e.offsetTop,e=e.offsetParent;return{left:r,top:i,width:t,height:n}}function Ti(e,t){let n={x:0,y:0};if(ti){let t=e;for(;t&&t.nodeName.toLowerCase()!==`html`;){let e=Pi(t,`transform`);if(/^matrix/.test(e)){let t=e.slice(7,-1).split(/,\s/).map(Number);n.x+=t[4],n.y+=t[5]}else if(/^matrix3d/.test(e)){let t=e.slice(9,-1).split(/,\s/).map(Number);n.x+=t[12],n.y+=t[13]}if(t.assignedSlot&&t.assignedSlot.parentElement&&I.default.WebKitCSSMatrix){let e=I.default.getComputedStyle(t.assignedSlot.parentElement).transform,r=new I.default.WebKitCSSMatrix(e);n.x+=r.m41,n.y+=r.m42}t=t.parentNode||t.host}}let r={},i=wi(t.target),a=wi(e),o=a.width,s=a.height,c=t.offsetY-(a.top-i.top),l=t.offsetX-(a.left-i.left);return t.changedTouches&&(l=t.changedTouches[0].pageX-a.left,c=t.changedTouches[0].pageY+a.top,ti&&(l-=n.x,c-=n.y)),r.y=1-Math.max(0,Math.min(1,c/s)),r.x=Math.max(0,Math.min(1,l/o)),r}function Ei(e){return Or(e)&&e.nodeType===3}function Di(e){for(;e.firstChild;)e.removeChild(e.firstChild);return e}function Oi(e){return typeof e==`function`&&(e=e()),(Array.isArray(e)?e:[e]).map(e=>{if(typeof e==`function`&&(e=e()),si(e)||Ei(e))return e;if(typeof e==`string`&&/\S/.test(e))return L.default.createTextNode(e)}).filter(e=>e)}function ki(e,t){return Oi(t).forEach(t=>e.appendChild(t)),e}function Ai(e,t){return ki(Di(e),t)}function ji(e){return e.button===void 0&&e.buttons===void 0||e.button===0&&e.buttons===void 0||e.type===`mouseup`&&e.button===0&&e.buttons===0||e.type===`mousedown`&&e.button===0&&e.buttons===0?!0:!(e.button!==0||e.buttons!==1)}var Mi=li(`querySelector`),Ni=li(`querySelectorAll`);function Pi(e,t){if(!e||!t)return``;if(typeof I.default.getComputedStyle==`function`){let n;try{n=I.default.getComputedStyle(e)}catch{return``}return n?n.getPropertyValue(t)||n[t]:``}return``}function Fi(e){[...L.default.styleSheets].forEach(t=>{try{let n=[...t.cssRules].map(e=>e.cssText).join(``),r=L.default.createElement(`style`);r.textContent=n,e.document.head.appendChild(r)}catch{let n=L.default.createElement(`link`);n.rel=`stylesheet`,n.type=t.type,n.media=t.media.mediaText,n.href=t.href,e.document.head.appendChild(n)}})}var Ii=Object.freeze({__proto__:null,isReal:oi,isEl:si,isInFrame:ci,createEl:V,textContent:ui,prependTo:di,hasClass:fi,addClass:pi,removeClass:mi,toggleClass:hi,setAttributes:gi,getAttributes:_i,getAttribute:vi,setAttribute:yi,removeAttribute:bi,blockTextSelection:xi,unblockTextSelection:Si,getBoundingClientRect:Ci,findPosition:wi,getPointerPosition:Ti,isTextNode:Ei,emptyEl:Di,normalizeContent:Oi,appendContent:ki,insertContent:Ai,isSingleLeftClick:ji,$:Mi,$$:Ni,computedStyle:Pi,copyStyleSheetsToWindow:Fi}),Li=!1,Ri,zi=function(){if(Ri.options.autoSetup===!1)return;let e=Array.prototype.slice.call(L.default.getElementsByTagName(`video`)),t=Array.prototype.slice.call(L.default.getElementsByTagName(`audio`)),n=Array.prototype.slice.call(L.default.getElementsByTagName(`video-js`)),r=e.concat(t,n);if(r&&r.length>0)for(let e=0,t=r.length;e-1&&(n={passive:!0}),e.addEventListener(t,r.dispatcher,n)}else e.attachEvent&&e.attachEvent(`on`+t,r.dispatcher)}function ea(e,t,n){if(!Wi.has(e))return;let r=Wi.get(e);if(!r.handlers)return;if(Array.isArray(t))return Ji(ea,e,t,n);let i=function(e,t){r.handlers[t]=[],qi(e,t)};if(t===void 0){for(let t in r.handlers)Object.prototype.hasOwnProperty.call(r.handlers||{},t)&&i(e,t);return}let a=r.handlers[t];if(a){if(!n){i(e,t);return}if(n.guid)for(let e=0;e=t&&(e(...r),n=i)}},ca=function(e,t,n,r=I.default){let i,a=()=>{r.clearTimeout(i),i=null},o=function(){let a=this,o=arguments,s=function(){i=null,s=null,n||e.apply(a,o)};!i&&n&&e.apply(a,o),r.clearTimeout(i),i=r.setTimeout(s,t)};return o.cancel=a,o},la=Object.freeze({__proto__:null,UPDATE_REFRESH_INTERVAL:aa,bind_:oa,throttle:sa,debounce:ca}),ua,da=class{on(e,t){let n=this.addEventListener;this.addEventListener=()=>{},$i(this,e,t),this.addEventListener=n}off(e,t){ea(this,e,t)}one(e,t){let n=this.addEventListener;this.addEventListener=()=>{},na(this,e,t),this.addEventListener=n}any(e,t){let n=this.addEventListener;this.addEventListener=()=>{},ra(this,e,t),this.addEventListener=n}trigger(e){let t=e.type||e;typeof e==`string`&&(e={type:t}),e=Yi(e),this.allowedEvents_[t]&&this[`on`+t]&&this[`on`+t](e),ta(this,e)}queueTrigger(e){ua||=new Map;let t=e.type||e,n=ua.get(this);n||(n=new Map,ua.set(this,n));let r=n.get(t);n.delete(t),I.default.clearTimeout(r);let i=I.default.setTimeout(()=>{n.delete(t),n.size===0&&(n=null,ua.delete(this)),this.trigger(e)},0);n.set(t,i)}};da.prototype.allowedEvents_={},da.prototype.addEventListener=da.prototype.on,da.prototype.removeEventListener=da.prototype.off,da.prototype.dispatchEvent=da.prototype.trigger;var fa=e=>typeof e.name==`function`?e.name():typeof e.name==`string`?e.name:e.name_?e.name_:e.constructor&&e.constructor.name?e.constructor.name:typeof e,pa=e=>e instanceof da||!!e.eventBusEl_&&[`on`,`one`,`off`,`trigger`].every(t=>typeof e[t]==`function`),ma=(e,t)=>{pa(e)?t():(e.eventedCallbacks||=[],e.eventedCallbacks.push(t))},ha=e=>typeof e==`string`&&/\S/.test(e)||Array.isArray(e)&&!!e.length,ga=(e,t,n)=>{if(!e||!e.nodeName&&!pa(e))throw Error(`Invalid target for ${fa(t)}#${n}; must be a DOM node or evented object.`)},_a=(e,t,n)=>{if(!ha(e))throw Error(`Invalid event type for ${fa(t)}#${n}; must be a non-empty string or array.`)},va=(e,t,n)=>{if(typeof e!=`function`)throw Error(`Invalid listener for ${fa(t)}#${n}; must be a function.`)},ya=(e,t,n)=>{let r=t.length<3||t[0]===e||t[0]===e.eventBusEl_,i,a,o;return r?(i=e.eventBusEl_,t.length>=3&&t.shift(),[a,o]=t):(i=t[0],a=t[1],o=t[2]),ga(i,e,n),_a(a,e,n),va(o,e,n),o=oa(e,o),{isTargetingSelf:r,target:i,type:a,listener:o}},ba=(e,t,n,r)=>{ga(e,e,t),e.nodeName?ia[t](e,n,r):e[t](n,r)},xa={on(...e){let{isTargetingSelf:t,target:n,type:r,listener:i}=ya(this,e,`on`);if(ba(n,`on`,r,i),!t){let e=()=>this.off(n,r,i);e.guid=i.guid;let t=()=>this.off(`dispose`,e);t.guid=i.guid,ba(this,`on`,`dispose`,e),ba(n,`on`,`dispose`,t)}},one(...e){let{isTargetingSelf:t,target:n,type:r,listener:i}=ya(this,e,`one`);if(t)ba(n,`one`,r,i);else{let e=(...t)=>{this.off(n,r,e),i.apply(null,t)};e.guid=i.guid,ba(n,`one`,r,e)}},any(...e){let{isTargetingSelf:t,target:n,type:r,listener:i}=ya(this,e,`any`);if(t)ba(n,`any`,r,i);else{let e=(...t)=>{this.off(n,r,e),i.apply(null,t)};e.guid=i.guid,ba(n,`any`,r,e)}},off(e,t,n){if(!e||ha(e))ea(this.eventBusEl_,e,t);else{let r=e,i=t;ga(r,this,`off`),_a(i,this,`off`),va(n,this,`off`),n=oa(this,n),this.off(`dispose`,n),r.nodeName?(ea(r,i,n),ea(r,`dispose`,n)):pa(r)&&(r.off(i,n),r.off(`dispose`,n))}},trigger(e,t){if(ga(this.eventBusEl_,this,`trigger`),!ha(e&&typeof e!=`string`?e.type:e))throw Error(`Invalid event type for ${fa(this)}#trigger; must be a non-empty string or object with a type key that has a non-empty value.`);return ta(this.eventBusEl_,e,t)}};function Sa(e,t={}){let{eventBusKey:n}=t;if(n){if(!e[n].nodeName)throw Error(`The eventBusKey "${n}" does not refer to an element.`);e.eventBusEl_=e[n]}else e.eventBusEl_=V(`span`,{className:`vjs-event-bus`});return Object.assign(e,xa),e.eventedCallbacks&&e.eventedCallbacks.forEach(e=>{e()}),e.on(`dispose`,()=>{e.off(),[e,e.el_,e.eventBusEl_].forEach(function(e){e&&Wi.has(e)&&Wi.delete(e)}),I.default.setTimeout(()=>{e.eventBusEl_=null},0)}),e}var Ca={state:{},setState(e){typeof e==`function`&&(e=e());let t;return Er(e,(e,n)=>{this.state[n]!==e&&(t||={},t[n]={from:this.state[n],to:e}),this.state[n]=e}),t&&pa(this)&&this.trigger({changes:t,type:`statechanged`}),t}};function wa(e,t){return Object.assign(e,Ca),e.state=Object.assign({},e.state,t),typeof e.handleStateChanged==`function`&&pa(e)&&e.on(`statechanged`,e.handleStateChanged),e}var Ta=function(e){return typeof e==`string`?e.replace(/./,e=>e.toLowerCase()):e},Ea=function(e){return typeof e==`string`?e.replace(/./,e=>e.toUpperCase()):e},Da=function(e,t){return Ea(e)===Ea(t)},Oa=Object.freeze({__proto__:null,toLowerCase:Ta,toTitleCase:Ea,titleCaseEquals:Da}),H=class e{constructor(e,t,n){if(!e&&this.play?this.player_=e=this:this.player_=e,this.isDisposed_=!1,this.parentComponent_=null,this.options_=Ar({},this.options_),t=this.options_=Ar(this.options_,t),this.id_=t.id||t.el&&t.el.id,!this.id_){let t=e&&e.id&&e.id()||`no_player`;this.id_=`${t}_component_${Ki()}`}this.name_=t.name||null,t.el?this.el_=t.el:t.createEl!==!1&&(this.el_=this.createEl()),t.className&&this.el_&&t.className.split(` `).forEach(e=>this.addClass(e)),[`on`,`off`,`one`,`any`,`trigger`].forEach(e=>{this[e]=void 0}),t.evented!==!1&&(Sa(this,{eventBusKey:this.el_?`el_`:null}),this.handleLanguagechange=this.handleLanguagechange.bind(this),this.on(this.player_,`languagechange`,this.handleLanguagechange)),wa(this,this.constructor.defaultState),this.children_=[],this.childIndex_={},this.childNameIndex_={},this.setTimeoutIds_=new Set,this.setIntervalIds_=new Set,this.rafIds_=new Set,this.namedRafs_=new Map,this.clearingTimersOnDispose_=!1,t.initChildren!==!1&&this.initChildren(),this.ready(n),t.reportTouchActivity!==!1&&this.enableTouchActivity()}dispose(e={}){if(!this.isDisposed_){if(this.readyQueue_&&(this.readyQueue_.length=0),this.trigger({type:`dispose`,bubbles:!1}),this.isDisposed_=!0,this.children_)for(let e=this.children_.length-1;e>=0;e--)this.children_[e].dispose&&this.children_[e].dispose();this.children_=null,this.childIndex_=null,this.childNameIndex_=null,this.parentComponent_=null,this.el_&&=(this.el_.parentNode&&(e.restoreEl?this.el_.parentNode.replaceChild(e.restoreEl,this.el_):this.el_.parentNode.removeChild(this.el_)),null),this.player_=null}}isDisposed(){return!!this.isDisposed_}player(){return this.player_}options(e){return e&&(this.options_=Ar(this.options_,e)),this.options_}el(){return this.el_}createEl(e,t,n){return V(e,t,n)}localize(e,t,n=e){let r=this.player_.language&&this.player_.language(),i=this.player_.languages&&this.player_.languages(),a=i&&i[r],o=r&&r.split(`-`)[0],s=i&&i[o],c=n;return a&&a[e]?c=a[e]:s&&s[e]&&(c=s[e]),t&&(c=c.replace(/\{(\d+)\}/g,function(e,n){let r=t[n-1],i=r;return r===void 0&&(i=e),i})),c}handleLanguagechange(){}contentEl(){return this.contentEl_||this.el_}id(){return this.id_}name(){return this.name_}children(){return this.children_}getChildById(e){return this.childIndex_[e]}getChild(e){if(e)return this.childNameIndex_[e]}getDescendant(...e){e=e.reduce((e,t)=>e.concat(t),[]);let t=this;for(let n=0;n=0;n--)if(this.children_[n]===e){t=!0,this.children_.splice(n,1);break}if(!t)return;e.parentComponent_=null,this.childIndex_[e.id()]=null,this.childNameIndex_[Ea(e.name())]=null,this.childNameIndex_[Ta(e.name())]=null;let n=e.el();n&&n.parentNode===this.contentEl()&&this.contentEl().removeChild(e.el())}initChildren(){let t=this.options_.children;if(t){let n=this.options_,r=e=>{let t=e.name,r=e.opts;if(n[t]!==void 0&&(r=n[t]),r===!1)return;r===!0&&(r={}),r.playerOptions=this.options_.playerOptions;let i=this.addChild(t,r);i&&(this[t]=i)},i,a=e.getComponent(`Tech`);i=Array.isArray(t)?t:Object.keys(t),i.concat(Object.keys(this.options_).filter(function(e){return!i.some(function(t){return typeof t==`string`?e===t:e===t.name})})).map(e=>{let n,r;return typeof e==`string`?(n=e,r=t[n]||this.options_[n]||{}):(n=e.name,r=e),{name:n,opts:r}}).filter(t=>{let n=e.getComponent(t.opts.componentClass||Ea(t.name));return n&&!a.isTech(n)}).forEach(r)}}buildCSSClass(){return``}ready(e,t=!1){if(e){if(!this.isReady_){this.readyQueue_=this.readyQueue_||[],this.readyQueue_.push(e);return}t?e.call(this):this.setTimeout(e,1)}}triggerReady(){this.isReady_=!0,this.setTimeout(function(){let e=this.readyQueue_;this.readyQueue_=[],e&&e.length>0&&e.forEach(function(e){e.call(this)},this),this.trigger(`ready`)},1)}$(e,t){return Mi(e,t||this.contentEl())}$$(e,t){return Ni(e,t||this.contentEl())}hasClass(e){return fi(this.el_,e)}addClass(...e){pi(this.el_,...e)}removeClass(...e){mi(this.el_,...e)}toggleClass(e,t){hi(this.el_,e,t)}show(){this.removeClass(`vjs-hidden`)}hide(){this.addClass(`vjs-hidden`)}lockShowing(){this.addClass(`vjs-lock-showing`)}unlockShowing(){this.removeClass(`vjs-lock-showing`)}getAttribute(e){return vi(this.el_,e)}setAttribute(e,t){yi(this.el_,e,t)}removeAttribute(e){bi(this.el_,e)}width(e,t){return this.dimension(`width`,e,t)}height(e,t){return this.dimension(`height`,e,t)}dimensions(e,t){this.width(e,!0),this.height(t)}dimension(e,t,n){if(t!==void 0){(t===null||t!==t)&&(t=0),(``+t).indexOf(`%`)!==-1||(``+t).indexOf(`px`)!==-1?this.el_.style[e]=t:t===`auto`?this.el_.style[e]=``:this.el_.style[e]=t+`px`,n||this.trigger(`componentresize`);return}if(!this.el_)return 0;let r=this.el_.style[e],i=r.indexOf(`px`);return parseInt(i===-1?this.el_[`offset`+Ea(e)]:r.slice(0,i),10)}currentDimension(e){let t=0;if(e!==`width`&&e!==`height`)throw Error(`currentDimension only accepts width or height value`);if(t=Pi(this.el_,e),t=parseFloat(t),t===0||isNaN(t)){let n=`offset${Ea(e)}`;t=this.el_[n]}return t}currentDimensions(){return{width:this.currentDimension(`width`),height:this.currentDimension(`height`)}}currentWidth(){return this.currentDimension(`width`)}currentHeight(){return this.currentDimension(`height`)}getPositions(){let e=this.el_.getBoundingClientRect();return{boundingClientRect:{x:e.x,y:e.y,width:e.width,height:e.height,top:e.top,right:e.right,bottom:e.bottom,left:e.left},center:{x:e.left+e.width/2,y:e.top+e.height/2,width:0,height:0,top:e.top+e.height/2,right:e.left+e.width/2,bottom:e.top+e.height/2,left:e.left+e.width/2}}}focus(){this.el_.focus()}blur(){this.el_.blur()}handleKeyDown(e){this.player_&&(e.key!==`Tab`&&!(this.player_.options_.playerOptions.spatialNavigation&&this.player_.options_.playerOptions.spatialNavigation.enabled)&&e.stopPropagation(),this.player_.handleKeyDown(e))}handleKeyPress(e){this.handleKeyDown(e)}emitTapEvents(){let e=0,t=null,n;this.on(`touchstart`,function(r){r.touches.length===1&&(t={pageX:r.touches[0].pageX,pageY:r.touches[0].pageY},e=I.default.performance.now(),n=!0)}),this.on(`touchmove`,function(e){if(e.touches.length>1)n=!1;else if(t){let r=e.touches[0].pageX-t.pageX,i=e.touches[0].pageY-t.pageY;Math.sqrt(r*r+i*i)>10&&(n=!1)}});let r=function(){n=!1};this.on(`touchleave`,r),this.on(`touchcancel`,r),this.on(`touchend`,function(r){t=null,n===!0&&I.default.performance.now()-e<200&&(r.preventDefault(),this.trigger(`tap`))})}enableTouchActivity(){if(!this.player()||!this.player().reportUserActivity)return;let e=oa(this.player(),this.player().reportUserActivity),t;this.on(`touchstart`,function(){e(),this.clearInterval(t),t=this.setInterval(e,250)});let n=function(n){e(),this.clearInterval(t)};this.on(`touchmove`,e),this.on(`touchend`,n),this.on(`touchcancel`,n)}setTimeout(e,t){var n;return e=oa(this,e),this.clearTimersOnDispose_(),n=I.default.setTimeout(()=>{this.setTimeoutIds_.has(n)&&this.setTimeoutIds_.delete(n),e()},t),this.setTimeoutIds_.add(n),n}clearTimeout(e){return this.setTimeoutIds_.has(e)&&(this.setTimeoutIds_.delete(e),I.default.clearTimeout(e)),e}setInterval(e,t){e=oa(this,e),this.clearTimersOnDispose_();let n=I.default.setInterval(e,t);return this.setIntervalIds_.add(n),n}clearInterval(e){return this.setIntervalIds_.has(e)&&(this.setIntervalIds_.delete(e),I.default.clearInterval(e)),e}requestAnimationFrame(e){this.clearTimersOnDispose_();var t;return e=oa(this,e),t=I.default.requestAnimationFrame(()=>{this.rafIds_.has(t)&&this.rafIds_.delete(t),e()}),this.rafIds_.add(t),t}requestNamedAnimationFrame(e,t){this.namedRafs_.has(e)&&this.cancelNamedAnimationFrame(e),this.clearTimersOnDispose_(),t=oa(this,t);let n=this.requestAnimationFrame(()=>{t(),this.namedRafs_.has(e)&&this.namedRafs_.delete(e)});return this.namedRafs_.set(e,n),e}cancelNamedAnimationFrame(e){this.namedRafs_.has(e)&&(this.cancelAnimationFrame(this.namedRafs_.get(e)),this.namedRafs_.delete(e))}cancelAnimationFrame(e){return this.rafIds_.has(e)&&(this.rafIds_.delete(e),I.default.cancelAnimationFrame(e)),e}clearTimersOnDispose_(){this.clearingTimersOnDispose_||(this.clearingTimersOnDispose_=!0,this.one(`dispose`,()=>{[[`namedRafs_`,`cancelNamedAnimationFrame`],[`rafIds_`,`cancelAnimationFrame`],[`setTimeoutIds_`,`clearTimeout`],[`setIntervalIds_`,`clearInterval`]].forEach(([e,t])=>{this[e].forEach((e,n)=>this[t](n))}),this.clearingTimersOnDispose_=!1}))}getIsDisabled(){return!!this.el_.disabled}getIsExpresslyInert(){return this.el_.inert&&!this.el_.ownerDocument.documentElement.inert}getIsFocusable(e){return(e||this.el_).tabIndex>=0&&!(this.getIsDisabled()||this.getIsExpresslyInert())}getIsAvailableToBeFocused(e){function t(e){let t=I.default.getComputedStyle(e,null),n=t.getPropertyValue(`visibility`);return t.getPropertyValue(`display`)!==`none`&&![`hidden`,`collapse`].includes(n)}function n(e){return!(!t(e.parentElement)||!t(e)||e.style.opacity===`0`||I.default.getComputedStyle(e).height===`0px`||I.default.getComputedStyle(e).width===`0px`)}function r(e){if(e.offsetWidth+e.offsetHeight+e.getBoundingClientRect().height+e.getBoundingClientRect().width===0)return!1;let t={x:e.getBoundingClientRect().left+e.offsetWidth/2,y:e.getBoundingClientRect().top+e.offsetHeight/2};if(t.x<0||t.x>(L.default.documentElement.clientWidth||I.default.innerWidth)||t.y<0||t.y>(L.default.documentElement.clientHeight||I.default.innerHeight))return!1;let n=L.default.elementFromPoint(t.x,t.y);for(;n;){if(n===e)return!0;if(n.parentNode)n=n.parentNode;else return!1}}return e||=this.el(),!!(r(e)&&n(e)&&(!e.parentElement||e.tabIndex>=0))}static registerComponent(t,n){if(typeof t!=`string`||!t)throw Error(`Illegal component name, "${t}"; must be a non-empty string.`);let r=e.getComponent(`Tech`),i=r&&r.isTech(n),a=e===n||e.prototype.isPrototypeOf(n.prototype);if(i||!a){let e;throw e=i?`techs must be registered using Tech.registerTech()`:`must be a Component subclass`,Error(`Illegal component, "${t}"; ${e}.`)}t=Ea(t),e.components_||={};let o=e.getComponent(`Player`);if(t===`Player`&&o&&o.players){let e=o.players,t=Object.keys(e);if(e&&t.length>0){for(let n=0;nn)throw Error(`Failed to execute '${e}' on 'TimeRanges': The index provided (${t}) is non-numeric or out of bounds (0-${n}).`)}function Aa(e,t,n,r){return ka(e,r,n.length-1),n[r][t]}function ja(e){let t;return t=e===void 0||e.length===0?{length:0,start(){throw Error(`This TimeRanges object is empty`)},end(){throw Error(`This TimeRanges object is empty`)}}:{length:e.length,start:Aa.bind(null,`start`,0,e),end:Aa.bind(null,`end`,1,e)},I.default.Symbol&&I.default.Symbol.iterator&&(t[I.default.Symbol.iterator]=()=>(e||[]).values()),t}function Ma(e,t){return Array.isArray(e)?ja(e):e===void 0||t===void 0?ja():ja([[e,t]])}var Na=function(e,t){e=e<0?0:e;let n=Math.floor(e%60),r=Math.floor(e/60%60),i=Math.floor(e/3600),a=Math.floor(t/60%60),o=Math.floor(t/3600);return(isNaN(e)||e===1/0)&&(i=r=n=`-`),i=i>0||o>0?i+`:`:``,r=((i||a>=10)&&r<10?`0`+r:r)+`:`,n=n<10?`0`+n:n,i+r+n},Pa=Na;function Fa(e){Pa=e}function Ia(){Pa=Na}function La(e,t=e){return Pa(e,t)}var Ra=Object.freeze({__proto__:null,createTimeRanges:Ma,createTimeRange:Ma,setFormatTime:Fa,resetFormatTime:Ia,formatTime:La});function za(e,t){let n=0,r,i;if(!t)return 0;(!e||!e.length)&&(e=Ma(0,0));for(let a=0;at&&(i=t),n+=i-r;return n/t}function Ba(e){if(e instanceof Ba)return e;typeof e==`number`?this.code=e:typeof e==`string`?this.message=e:Or(e)&&(typeof e.code==`number`&&(this.code=e.code),Object.assign(this,e)),this.message||=Ba.defaultMessages[this.code]||``}Ba.prototype.code=0,Ba.prototype.message=``,Ba.prototype.status=null,Ba.prototype.metadata=null,Ba.errorTypes=[`MEDIA_ERR_CUSTOM`,`MEDIA_ERR_ABORTED`,`MEDIA_ERR_NETWORK`,`MEDIA_ERR_DECODE`,`MEDIA_ERR_SRC_NOT_SUPPORTED`,`MEDIA_ERR_ENCRYPTED`],Ba.defaultMessages={1:`You aborted the media playback`,2:`A network error caused the media download to fail part-way.`,3:`The media playback was aborted due to a corruption problem or because the media used features your browser did not support.`,4:`The media could not be loaded, either because the server or network failed or because the format is not supported.`,5:`The media is encrypted and we do not have the keys to decrypt it.`},Ba.MEDIA_ERR_CUSTOM=0,Ba.prototype.MEDIA_ERR_CUSTOM=0,Ba.MEDIA_ERR_ABORTED=1,Ba.prototype.MEDIA_ERR_ABORTED=1,Ba.MEDIA_ERR_NETWORK=2,Ba.prototype.MEDIA_ERR_NETWORK=2,Ba.MEDIA_ERR_DECODE=3,Ba.prototype.MEDIA_ERR_DECODE=3,Ba.MEDIA_ERR_SRC_NOT_SUPPORTED=4,Ba.prototype.MEDIA_ERR_SRC_NOT_SUPPORTED=4,Ba.MEDIA_ERR_ENCRYPTED=5,Ba.prototype.MEDIA_ERR_ENCRYPTED=5;function Va(e){return e!=null&&typeof e.then==`function`}function Ha(e){Va(e)&&e.then(null,e=>{})}var Ua=function(e){return[`kind`,`label`,`language`,`id`,`inBandMetadataTrackDispatchType`,`mode`,`src`].reduce((t,n,r)=>(e[n]&&(t[n]=e[n]),t),{cues:e.cues&&Array.prototype.map.call(e.cues,function(e){return{startTime:e.startTime,endTime:e.endTime,text:e.text,id:e.id}})})},Wa={textTracksToJson:function(e){let t=e.$$(`track`),n=Array.prototype.map.call(t,e=>e.track);return Array.prototype.map.call(t,function(e){let t=Ua(e.track);return e.src&&(t.src=e.src),t}).concat(Array.prototype.filter.call(e.textTracks(),function(e){return n.indexOf(e)===-1}).map(Ua))},jsonToTextTracks:function(e,t){return e.forEach(function(e){let n=t.addRemoteTextTrack(e).track;!e.src&&e.cues&&e.cues.forEach(e=>n.addCue(e))}),t.textTracks()},trackToJson:Ua},Ga=`vjs-modal-dialog`,Ka=class extends H{constructor(e,t){super(e,t),this.handleKeyDown_=e=>this.handleKeyDown(e),this.close_=e=>this.close(e),this.opened_=this.hasBeenOpened_=this.hasBeenFilled_=!1,this.closeable(!this.options_.uncloseable),this.content(this.options_.content),this.contentEl_=V(`div`,{className:`${Ga}-content`},{role:`document`}),this.descEl_=V(`p`,{className:`${Ga}-description vjs-control-text`,id:this.el().getAttribute(`aria-describedby`)}),ui(this.descEl_,this.description()),this.el_.appendChild(this.descEl_),this.el_.appendChild(this.contentEl_)}createEl(){return super.createEl(`div`,{className:this.buildCSSClass(),tabIndex:-1},{"aria-describedby":`${this.id()}_description`,"aria-hidden":`true`,"aria-label":this.label(),role:`dialog`,"aria-live":`polite`})}dispose(){this.contentEl_=null,this.descEl_=null,this.previouslyActiveEl_=null,super.dispose()}buildCSSClass(){return`${Ga} vjs-hidden ${super.buildCSSClass()}`}label(){return this.localize(this.options_.label||`Modal Window`)}description(){let e=this.options_.description||this.localize(`This is a modal window.`);return this.closeable()&&(e+=` `+this.localize(`This modal can be closed by pressing the Escape key or activating the close button.`)),e}open(){if(this.opened_){this.options_.fillAlways&&this.fill();return}let e=this.player();this.trigger(`beforemodalopen`),this.opened_=!0,(this.options_.fillAlways||!this.hasBeenOpened_&&!this.hasBeenFilled_)&&this.fill(),this.wasPlaying_=!e.paused(),this.options_.pauseOnOpen&&this.wasPlaying_&&e.pause(),this.on(`keydown`,this.handleKeyDown_),this.hadControls_=e.controls(),e.controls(!1),this.show(),this.conditionalFocus_(),this.el().setAttribute(`aria-hidden`,`false`),this.trigger(`modalopen`),this.hasBeenOpened_=!0}opened(e){return typeof e==`boolean`&&this[e?`open`:`close`](),this.opened_}close(){if(!this.opened_)return;let e=this.player();this.trigger(`beforemodalclose`),this.opened_=!1,this.wasPlaying_&&this.options_.pauseOnOpen&&e.play(),this.off(`keydown`,this.handleKeyDown_),this.hadControls_&&e.controls(!0),this.hide(),this.el().setAttribute(`aria-hidden`,`true`),this.trigger({type:`modalclose`,bubbles:!0}),this.conditionalBlur_(),this.options_.temporary&&this.dispose()}closeable(e){if(typeof e==`boolean`){let t=this.closeable_=!!e,n=this.getChild(`closeButton`);if(t&&!n){let e=this.contentEl_;this.contentEl_=this.el_,n=this.addChild(`closeButton`,{controlText:`Close Modal Dialog`}),this.contentEl_=e,this.on(n,`close`,this.close_)}!t&&n&&(this.off(n,`close`,this.close_),this.removeChild(n),n.dispose())}return this.closeable_}fill(){this.fillWith(this.content())}fillWith(e){let t=this.contentEl(),n=t.parentNode,r=t.nextSibling;this.trigger(`beforemodalfill`),this.hasBeenFilled_=!0,n.removeChild(t),this.empty(),Ai(t,e),this.trigger(`modalfill`),r?n.insertBefore(t,r):n.appendChild(t);let i=this.getChild(`closeButton`);i&&n.appendChild(i.el_),this.trigger(`aftermodalfill`)}empty(){this.trigger(`beforemodalempty`),Di(this.contentEl()),this.trigger(`modalempty`)}content(e){return e!==void 0&&(this.content_=e),this.content_}conditionalFocus_(){let e=L.default.activeElement,t=this.player_.el_;this.previouslyActiveEl_=null,(t.contains(e)||t===e)&&(this.previouslyActiveEl_=e,this.focus())}conditionalBlur_(){this.previouslyActiveEl_&&=(this.previouslyActiveEl_.focus(),null)}handleKeyDown(e){if(this.trigger({type:`modalKeydown`,originalEvent:e,target:this,bubbles:!0}),e.stopPropagation(),e.key===`Escape`&&this.closeable()){e.preventDefault(),this.close();return}if(e.key!==`Tab`)return;let t=this.focusableEls_(),n=this.el_.querySelector(`:focus`),r;for(let e=0;e(e instanceof I.default.HTMLAnchorElement||e instanceof I.default.HTMLAreaElement)&&e.hasAttribute(`href`)||(e instanceof I.default.HTMLInputElement||e instanceof I.default.HTMLSelectElement||e instanceof I.default.HTMLTextAreaElement||e instanceof I.default.HTMLButtonElement)&&!e.hasAttribute(`disabled`)||e instanceof I.default.HTMLIFrameElement||e instanceof I.default.HTMLObjectElement||e instanceof I.default.HTMLEmbedElement||e.hasAttribute(`tabindex`)&&e.getAttribute(`tabindex`)!==-1||e.hasAttribute(`contenteditable`))}};Ka.prototype.options_={pauseOnOpen:!0,temporary:!0},H.registerComponent(`ModalDialog`,Ka);var qa=class extends da{constructor(e=[]){super(),this.tracks_=[];for(let t=0;t{this.trigger({track:e,type:`labelchange`,target:this})},pa(e)&&e.addEventListener(`labelchange`,e.labelchange_)}removeTrack(e){let t;for(let n=0,r=this.length;n=0;t--)if(e[t].enabled){Ja(e,e[t]);break}super(e),this.changing_=!1}addTrack(e){e.enabled&&Ja(this,e),super.addTrack(e),e.addEventListener&&(e.enabledChange_=()=>{this.changing_||(this.changing_=!0,Ja(this,e),this.changing_=!1,this.trigger(`change`))},e.addEventListener(`enabledchange`,e.enabledChange_))}removeTrack(e){super.removeTrack(e),e.removeEventListener&&e.enabledChange_&&(e.removeEventListener(`enabledchange`,e.enabledChange_),e.enabledChange_=null)}},Xa=function(e,t){for(let n=0;n=0;t--)if(e[t].selected){Xa(e,e[t]);break}super(e),this.changing_=!1,Object.defineProperty(this,`selectedIndex`,{get(){for(let e=0;e{this.changing_||(this.changing_=!0,Xa(this,e),this.changing_=!1,this.trigger(`change`))},e.addEventListener(`selectedchange`,e.selectedChange_))}removeTrack(e){super.removeTrack(e),e.removeEventListener&&e.selectedChange_&&(e.removeEventListener(`selectedchange`,e.selectedChange_),e.selectedChange_=null)}},Qa=class extends qa{addTrack(e){super.addTrack(e),this.queueChange_||=()=>this.queueTrigger(`change`),this.triggerSelectedlanguagechange||(this.triggerSelectedlanguagechange_=()=>this.trigger(`selectedlanguagechange`)),e.addEventListener(`modechange`,this.queueChange_),[`metadata`,`chapters`].indexOf(e.kind)===-1&&e.addEventListener(`modechange`,this.triggerSelectedlanguagechange_)}removeTrack(e){super.removeTrack(e),e.removeEventListener&&(this.queueChange_&&e.removeEventListener(`modechange`,this.queueChange_),this.selectedlanguagechange_&&e.removeEventListener(`modechange`,this.triggerSelectedlanguagechange_))}toJSON(){return this.tracks_.map(e=>e.toJSON())}},$a=class{constructor(e=[]){this.trackElements_=[],Object.defineProperty(this,`length`,{get(){return this.trackElements_.length}});for(let t=0,n=e.length;t0&&(I.default.console&&I.default.console.groupCollapsed&&I.default.console.groupCollapsed(`Text Track parsing errors for ${t.src}`),r.forEach(e=>B.error(e)),I.default.console&&I.default.console.groupEnd&&I.default.console.groupEnd()),n.flush()},po=function(e,t){let n={uri:e},r=lo(e);r&&(n.cors=r);let i=t.tech_.crossOrigin()===`use-credentials`;i&&(n.withCredentials=i),(0,R.default)(n,oa(this,function(e,n,r){if(e)return B.error(e,n);t.loaded_=!0,typeof I.default.WebVTT==`function`?fo(r,t):t.tech_&&t.tech_.any([`vttjsloaded`,`vttjserror`],e=>{if(e.type===`vttjserror`){B.error(`vttjs failed to load, stopping trying to process ${t.src}`);return}return fo(r,t)})}))},mo=class extends ao{constructor(e={}){if(!e.tech)throw Error(`A tech was not provided.`);let t=Ar(e,{kind:ro[e.kind]||`subtitles`,language:e.language||e.srclang||``}),n=io[t.mode]||`disabled`,r=t.default;(t.kind===`metadata`||t.kind===`chapters`)&&(n=`hidden`),super(t),this.tech_=t.tech,this.cues_=[],this.activeCues_=[],this.preload_=this.tech_.preloadTextTracks!==!1;let i=new eo(this.cues_),a=new eo(this.activeCues_),o=!1;this.timeupdateHandler=oa(this,function(e={}){if(!this.tech_.isDisposed()){if(!this.tech_.isReady_){e.type!==`timeupdate`&&(this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler));return}this.activeCues=this.activeCues,o&&=(this.trigger(`cuechange`),!1),e.type!==`timeupdate`&&(this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler))}}),this.tech_.one(`dispose`,()=>{this.stopTracking()}),n!==`disabled`&&this.startTracking(),Object.defineProperties(this,{default:{get(){return r},set(){}},mode:{get(){return n},set(e){io[e]&&n!==e&&(n=e,!this.preload_&&n!==`disabled`&&this.cues.length===0&&po(this.src,this),this.stopTracking(),n!==`disabled`&&this.startTracking(),this.trigger(`modechange`))}},cues:{get(){return this.loaded_?i:null},set(){}},activeCues:{get(){if(!this.loaded_)return null;if(this.cues.length===0)return a;let e=this.tech_.currentTime(),t=[];for(let n=0,r=this.cues.length;n=e&&t.push(r)}if(o=!1,t.length!==this.activeCues_.length)o=!0;else for(let e=0;e{n=e.LOADED,this.trigger({type:`load`,target:this})})}};_o.prototype.allowedEvents_={load:`load`},_o.NONE=0,_o.LOADING=1,_o.LOADED=2,_o.ERROR=3;var vo={audio:{ListClass:Ya,TrackClass:ho,capitalName:`Audio`},video:{ListClass:Za,TrackClass:go,capitalName:`Video`},text:{ListClass:Qa,TrackClass:mo,capitalName:`Text`}};Object.keys(vo).forEach(function(e){vo[e].getterName=`${e}Tracks`,vo[e].privateName=`${e}Tracks_`});var yo={remoteText:{ListClass:Qa,TrackClass:mo,capitalName:`RemoteText`,getterName:`remoteTextTracks`,privateName:`remoteTextTracks_`},remoteTextEl:{ListClass:$a,TrackClass:_o,capitalName:`RemoteTextTrackEls`,getterName:`remoteTextTrackEls`,privateName:`remoteTextTrackEls_`}},bo=Object.assign({},vo,yo);yo.names=Object.keys(yo),vo.names=Object.keys(vo),bo.names=[].concat(yo.names,vo.names);function xo(e,t,n,r,i={}){let a=e.textTracks();i.kind=t,n&&(i.label=n),r&&(i.language=r),i.tech=e;let o=new bo.text.TrackClass(i);return a.addTrack(o),o}var So=class e extends H{constructor(e={},t=function(){}){e.reportTouchActivity=!1,super(null,e,t),this.onDurationChange_=e=>this.onDurationChange(e),this.trackProgress_=e=>this.trackProgress(e),this.trackCurrentTime_=e=>this.trackCurrentTime(e),this.stopTrackingCurrentTime_=e=>this.stopTrackingCurrentTime(e),this.disposeSourceHandler_=e=>this.disposeSourceHandler(e),this.queuedHanders_=new Set,this.hasStarted_=!1,this.on(`playing`,function(){this.hasStarted_=!0}),this.on(`loadstart`,function(){this.hasStarted_=!1}),bo.names.forEach(t=>{let n=bo[t];e&&e[n.getterName]&&(this[n.privateName]=e[n.getterName])}),this.featuresProgressEvents||this.manualProgressOn(),this.featuresTimeupdateEvents||this.manualTimeUpdatesOn(),[`Text`,`Audio`,`Video`].forEach(t=>{e[`native${t}Tracks`]===!1&&(this[`featuresNative${t}Tracks`]=!1)}),e.nativeCaptions===!1||e.nativeTextTracks===!1?this.featuresNativeTextTracks=!1:(e.nativeCaptions===!0||e.nativeTextTracks===!0)&&(this.featuresNativeTextTracks=!0),this.featuresNativeTextTracks||this.emulateTextTracks(),this.preloadTextTracks=e.preloadTextTracks!==!1,this.autoRemoteTextTracks_=new bo.text.ListClass,this.initTrackListeners(),e.nativeControlsForTouch||this.emitTapEvents(),this.constructor&&(this.name_=this.constructor.name||`Unknown Tech`)}triggerSourceset(e){this.isReady_||this.one(`ready`,()=>this.setTimeout(()=>this.triggerSourceset(e),1)),this.trigger({src:e,type:`sourceset`})}manualProgressOn(){this.on(`durationchange`,this.onDurationChange_),this.manualProgress=!0,this.one(`ready`,this.trackProgress_)}manualProgressOff(){this.manualProgress=!1,this.stopTrackingProgress(),this.off(`durationchange`,this.onDurationChange_)}trackProgress(e){this.stopTrackingProgress(),this.progressInterval=this.setInterval(oa(this,function(){let e=this.bufferedPercent();this.bufferedPercent_!==e&&this.trigger(`progress`),this.bufferedPercent_=e,e===1&&this.stopTrackingProgress()}),500)}onDurationChange(e){this.duration_=this.duration()}buffered(){return Ma(0,0)}bufferedPercent(){return za(this.buffered(),this.duration_)}stopTrackingProgress(){this.clearInterval(this.progressInterval)}manualTimeUpdatesOn(){this.manualTimeUpdates=!0,this.on(`play`,this.trackCurrentTime_),this.on(`pause`,this.stopTrackingCurrentTime_)}manualTimeUpdatesOff(){this.manualTimeUpdates=!1,this.stopTrackingCurrentTime(),this.off(`play`,this.trackCurrentTime_),this.off(`pause`,this.stopTrackingCurrentTime_)}trackCurrentTime(){this.currentTimeInterval&&this.stopTrackingCurrentTime(),this.currentTimeInterval=this.setInterval(function(){this.trigger({type:`timeupdate`,target:this,manuallyTriggered:!0})},250)}stopTrackingCurrentTime(){this.clearInterval(this.currentTimeInterval),this.trigger({type:`timeupdate`,target:this,manuallyTriggered:!0})}dispose(){this.clearTracks(vo.names),this.manualProgress&&this.manualProgressOff(),this.manualTimeUpdates&&this.manualTimeUpdatesOff(),super.dispose()}clearTracks(e){e=[].concat(e),e.forEach(e=>{let t=this[`${e}Tracks`]()||[],n=t.length;for(;n--;){let r=t[n];e===`text`&&this.removeRemoteTextTrack(r),t.removeTrack(r)}})}cleanupAutoTextTracks(){let e=this.autoRemoteTextTracks_||[],t=e.length;for(;t--;){let n=e[t];this.removeRemoteTextTrack(n)}}reset(){}crossOrigin(){}setCrossOrigin(){}error(e){return e!==void 0&&(this.error_=new Ba(e),this.trigger(`error`)),this.error_}played(){return this.hasStarted_?Ma(0,0):Ma()}play(){}setScrubbing(e){}scrubbing(){}setCurrentTime(e){this.manualTimeUpdates&&this.trigger({type:`timeupdate`,target:this,manuallyTriggered:!0})}initTrackListeners(){vo.names.forEach(e=>{let t=vo[e],n=()=>{this.trigger(`${e}trackchange`)},r=this[t.getterName]();r.addEventListener(`removetrack`,n),r.addEventListener(`addtrack`,n),this.on(`dispose`,()=>{r.removeEventListener(`removetrack`,n),r.removeEventListener(`addtrack`,n)})})}addWebVttScript_(){if(!I.default.WebVTT)if(L.default.body.contains(this.el())){if(!this.options_[`vtt.js`]&&kr(pe.default)&&Object.keys(pe.default).length>0){this.trigger(`vttjsloaded`);return}let e=L.default.createElement(`script`);e.src=this.options_[`vtt.js`]||`https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js`,e.onload=()=>{this.trigger(`vttjsloaded`)},e.onerror=()=>{this.trigger(`vttjserror`)},this.on(`dispose`,()=>{e.onload=null,e.onerror=null}),I.default.WebVTT=!0,this.el().parentNode.appendChild(e)}else this.ready(this.addWebVttScript_)}emulateTextTracks(){let e=this.textTracks(),t=this.remoteTextTracks(),n=t=>e.addTrack(t.track),r=t=>e.removeTrack(t.track);t.on(`addtrack`,n),t.on(`removetrack`,r),this.addWebVttScript_();let i=()=>this.trigger(`texttrackchange`),a=()=>{i();for(let t=0;tthis.autoRemoteTextTracks_.addTrack(n.track)),n}removeRemoteTextTrack(e){let t=this.remoteTextTrackEls().getTrackElementByTrack_(e);this.remoteTextTrackEls().removeTrackElement_(t),this.remoteTextTracks().removeTrack(e),this.autoRemoteTextTracks_.removeTrack(e)}getVideoPlaybackQuality(){return{}}requestPictureInPicture(){return Promise.reject()}disablePictureInPicture(){return!0}setDisablePictureInPicture(){}requestVideoFrameCallback(e){let t=Ki();return!this.isReady_||this.paused()?(this.queuedHanders_.add(t),this.one(`playing`,()=>{this.queuedHanders_.has(t)&&(this.queuedHanders_.delete(t),e())})):this.requestNamedAnimationFrame(t,e),t}cancelVideoFrameCallback(e){this.queuedHanders_.has(e)?this.queuedHanders_.delete(e):this.cancelNamedAnimationFrame(e)}setPoster(){}playsinline(){}setPlaysinline(){}overrideNativeAudioTracks(e){}overrideNativeVideoTracks(e){}canPlayType(e){return``}static canPlayType(e){return``}static canPlaySource(t,n){return e.canPlayType(t.type)}static isTech(t){return t.prototype instanceof e||t instanceof e||t===e}static registerTech(t,n){if(e.techs_||={},!e.isTech(n))throw Error(`Tech ${t} must be a Tech`);if(!e.canPlayType)throw Error(`Techs must have a static canPlayType method on them`);if(!e.canPlaySource)throw Error(`Techs must have a static canPlaySource method on them`);return t=Ea(t),e.techs_[t]=n,e.techs_[Ta(t)]=n,t!==`Tech`&&e.defaultTechOrder_.push(t),n}static getTech(t){if(t){if(e.techs_&&e.techs_[t])return e.techs_[t];if(t=Ea(t),I.default&&I.default.videojs&&I.default.videojs[t])return B.warn(`The ${t} tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)`),I.default.videojs[t]}}};bo.names.forEach(function(e){let t=bo[e];So.prototype[t.getterName]=function(){return this[t.privateName]=this[t.privateName]||new t.ListClass,this[t.privateName]}}),So.prototype.featuresVolumeControl=!0,So.prototype.featuresMuteControl=!0,So.prototype.featuresFullscreenResize=!1,So.prototype.featuresPlaybackRate=!1,So.prototype.featuresProgressEvents=!1,So.prototype.featuresSourceset=!1,So.prototype.featuresTimeupdateEvents=!1,So.prototype.featuresNativeTextTracks=!1,So.prototype.featuresVideoFrameCallback=!1,So.withSourceHandlers=function(e){e.registerSourceHandler=function(t,n){let r=e.sourceHandlers;r||=e.sourceHandlers=[],n===void 0&&(n=r.length),r.splice(n,0,t)},e.canPlayType=function(t){let n=e.sourceHandlers||[],r;for(let e=0;ezo(t,Co[t.type],n,e),1)}function Oo(e,t){e.forEach(e=>e.setTech&&e.setTech(t))}function ko(e,t,n){return e.reduceRight(Fo(n),t[n]())}function Ao(e,t,n,r){return t[n](e.reduce(Fo(n),r))}function jo(e,t,n,r=null){let i=`call`+Ea(n),a=e.reduce(Fo(i),r),o=a===To,s=o?null:t[n](a);return Io(e,n,s,o),s}var Mo={buffered:1,currentTime:1,duration:1,muted:1,played:1,paused:1,seekable:1,volume:1,ended:1},No={setCurrentTime:1,setMuted:1,setVolume:1},Po={play:1,pause:1};function Fo(e){return(t,n)=>t===To?To:n[e]?n[e](t):t}function Io(e,t,n,r){for(let i=e.length-1;i>=0;i--){let a=e[i];a[t]&&a[t](r,n)}}function Lo(e){wo.hasOwnProperty(e.id())&&delete wo[e.id()]}function Ro(e,t){let n=wo[e.id()],r=null;if(n==null)return r=t(e),wo[e.id()]=[[t,r]],r;for(let e=0;e{if(!t)return``;if(e.cache_.source.src===t&&e.cache_.source.type)return e.cache_.source.type;let n=e.cache_.sources.filter(e=>e.src===t);if(n.length)return n[0].type;let r=e.$$(`source`);for(let e=0;e `,Ko=Xr?10009:Zr?461:8,qo={codes:{play:415,pause:19,ff:417,rw:412,back:Ko},names:{415:`play`,19:`pause`,417:`ff`,412:`rw`,[Ko]:`back`},isEventKey(e,t){return t=t.toLowerCase(),!!(this.names[e.keyCode]&&this.names[e.keyCode]===t)},getEventName(e){if(this.names[e.keyCode])return this.names[e.keyCode];if(this.codes[e.code]){let t=this.codes[e.code];return this.names[t]}return null}},Jo=5,Yo=class extends da{constructor(e){super(),this.player_=e,this.focusableComponents=[],this.isListening_=!1,this.isPaused_=!1,this.onKeyDown_=this.onKeyDown_.bind(this),this.lastFocusedComponent_=null}start(){this.isListening_||(this.player_.on(`keydown`,this.onKeyDown_),this.player_.on(`modalKeydown`,this.onKeyDown_),this.player_.on(`loadedmetadata`,()=>{this.focus(this.updateFocusableComponents()[0])}),this.player_.on(`modalclose`,()=>{this.refocusComponent()}),this.player_.on(`focusin`,this.handlePlayerFocus_.bind(this)),this.player_.on(`focusout`,this.handlePlayerBlur_.bind(this)),this.isListening_=!0,this.player_.errorDisplay&&this.player_.errorDisplay.on(`aftermodalfill`,()=>{this.updateFocusableComponents(),this.focusableComponents.length&&(this.focusableComponents.length>1?this.focusableComponents[1].focus():this.focusableComponents[0].focus())}))}stop(){this.player_.off(`keydown`,this.onKeyDown_),this.isListening_=!1}onKeyDown_(e){let t=e.originalEvent?e.originalEvent:e;if([`ArrowLeft`,`ArrowRight`,`ArrowUp`,`ArrowDown`].includes(t.key)){if(this.isPaused_)return;t.preventDefault();let e=t.key.substring(5).toLowerCase();this.move(e)}else if(qo.isEventKey(t,`play`)||qo.isEventKey(t,`pause`)||qo.isEventKey(t,`ff`)||qo.isEventKey(t,`rw`)){t.preventDefault();let e=qo.getEventName(t);this.performMediaAction_(e)}else qo.isEventKey(t,`Back`)&&e.target&&typeof e.target.closeable==`function`&&e.target.closeable()&&(t.preventDefault(),e.target.close())}performMediaAction_(e){if(this.player_)switch(e){case`play`:this.player_.paused()&&this.player_.play();break;case`pause`:this.player_.paused()||this.player_.pause();break;case`ff`:this.userSeek_(this.player_.currentTime()+Jo);break;case`rw`:this.userSeek_(this.player_.currentTime()-Jo);break}}userSeek_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&this.player_.liveTracker.nextSeekedFromUser(),this.player_.currentTime(e)}pause(){this.isPaused_=!0}resume(){this.isPaused_=!1}handlePlayerBlur_(e){let t=e.relatedTarget,n=null,r=this.getCurrentComponent(e.target);t&&(n=!!t.closest(`.video-js`),t.classList.contains(`vjs-text-track-settings`)&&!this.isPaused_&&this.searchForTrackSelect_()),(!e.currentTarget.contains(e.relatedTarget)&&!n||!t)&&(r&&r.name()===`CloseButton`?this.refocusComponent():(this.pause(),r&&r.el()&&(this.lastFocusedComponent_=r)))}handlePlayerFocus_(){this.getCurrentComponent()&&this.getCurrentComponent().getIsFocusable()&&this.resume()}updateFocusableComponents(){let e=this.player_,t=[];function n(e){for(let r of e)r.hasOwnProperty(`el_`)&&r.getIsFocusable()&&r.getIsAvailableToBeFocused(r.el())&&t.push(r),r.hasOwnProperty(`children_`)&&r.children_.length>0&&n(r.children_)}return e.children_.forEach(e=>{if(e.hasOwnProperty(`el_`))if(e.getIsFocusable&&e.getIsAvailableToBeFocused&&e.getIsFocusable()&&e.getIsAvailableToBeFocused(e.el())){t.push(e);return}else e.hasOwnProperty(`children_`)&&e.children_.length>0?n(e.children_):e.hasOwnProperty(`items`)&&e.items.length>0?n(e.items):this.findSuitableDOMChild(e)&&t.push(e);if(e.name_===`ErrorDisplay`&&e.opened_){let n=e.el_.querySelector(`.vjs-errors-ok-button-container`);n&&n.querySelectorAll(`button`).forEach((e,n)=>{t.push({name:()=>`ModalButton`+(n+1),el:()=>e,getPositions:()=>{let t=e.getBoundingClientRect();return{boundingClientRect:{x:t.x,y:t.y,width:t.width,height:t.height,top:t.top,right:t.right,bottom:t.bottom,left:t.left},center:{x:t.left+t.width/2,y:t.top+t.height/2,width:0,height:0,top:t.top+t.height/2,right:t.left+t.width/2,bottom:t.top+t.height/2,left:t.left+t.width/2}}},getIsAvailableToBeFocused:()=>!0,getIsFocusable:e=>!0,focus:()=>e.focus()})})}}),this.focusableComponents=t,this.focusableComponents}findSuitableDOMChild(e){function t(n){if(e.getIsFocusable(n)&&e.getIsAvailableToBeFocused(n))return n;for(let e=0;e0&&(this.focusableComponents=[],this.trigger({type:`focusableComponentsChanged`,focusableComponents:this.focusableComponents}))}move(e){let t=this.getCurrentComponent();if(!t)return;let n=t.getPositions(),r=this.focusableComponents.filter(r=>r!==t&&this.isInDirection_(n.boundingClientRect,r.getPositions().boundingClientRect,e)),i=this.findBestCandidate_(n.center,r,e);i?this.focus(i):this.trigger({type:`endOfFocusableComponents`,direction:e,focusedComponent:t})}findBestCandidate_(e,t,n){let r=1/0,i=null;for(let a of t){let t=a.getPositions().center,o=this.calculateDistance_(e,t,n);o=e.right;case`left`:return t.right<=e.left;case`down`:return t.top>=e.bottom;case`up`:return t.bottom<=e.top;default:return!1}}refocusComponent(){if(this.lastFocusedComponent_){this.player_.userActive()||this.player_.userActive(!0),this.updateFocusableComponents();for(let e=0;ethis.handleMouseOver(e),this.handleMouseOut_=e=>this.handleMouseOut(e),this.handleClick_=e=>this.handleClick(e),this.handleKeyDown_=e=>this.handleKeyDown(e),this.emitTapEvents(),this.enable()}createEl(e=`div`,t={},n={}){t=Object.assign({className:this.buildCSSClass(),tabIndex:0},t),e===`button`&&B.error(`Creating a ClickableComponent with an HTML element of ${e} is not supported; use a Button instead.`),n=Object.assign({role:`button`},n),this.tabIndex_=t.tabIndex;let r=V(e,t,n);return this.player_.options_.experimentalSvgIcons||r.appendChild(V(`span`,{className:`vjs-icon-placeholder`},{"aria-hidden":!0})),this.createControlTextEl(r),r}dispose(){this.controlTextEl_=null,super.dispose()}createControlTextEl(e){return this.controlTextEl_=V(`span`,{className:`vjs-control-text`},{"aria-live":`polite`}),e&&e.appendChild(this.controlTextEl_),this.controlText(this.controlText_,e),this.controlTextEl_}controlText(e,t=this.el()){if(e===void 0)return this.controlText_||`Need Text`;let n=this.localize(e);this.controlText_=e,ui(this.controlTextEl_,n),!this.nonIconControl&&!this.player_.options_.noUITitleAttributes&&t.setAttribute(`title`,n)}buildCSSClass(){return`vjs-control vjs-button ${super.buildCSSClass()}`}enable(){this.enabled_||(this.enabled_=!0,this.removeClass(`vjs-disabled`),this.el_.setAttribute(`aria-disabled`,`false`),this.tabIndex_!==void 0&&this.el_.setAttribute(`tabIndex`,this.tabIndex_),this.on([`tap`,`click`],this.handleClick_),this.on(`keydown`,this.handleKeyDown_))}disable(){this.enabled_=!1,this.addClass(`vjs-disabled`),this.el_.setAttribute(`aria-disabled`,`true`),this.tabIndex_!==void 0&&this.el_.removeAttribute(`tabIndex`),this.off(`mouseover`,this.handleMouseOver_),this.off(`mouseout`,this.handleMouseOut_),this.off([`tap`,`click`],this.handleClick_),this.off(`keydown`,this.handleKeyDown_)}handleLanguagechange(){this.controlText(this.controlText_)}handleClick(e){this.options_.clickHandler&&this.options_.clickHandler.call(this,arguments)}handleKeyDown(e){e.key===` `||e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),this.trigger(`click`)):super.handleKeyDown(e)}};H.registerComponent(`ClickableComponent`,Zo);var Qo=class extends Zo{constructor(e,t){super(e,t),this.update(),this.update_=e=>this.update(e),e.on(`posterchange`,this.update_)}dispose(){this.player().off(`posterchange`,this.update_),super.dispose()}createEl(){return V(`div`,{className:`vjs-poster`})}crossOrigin(e){if(e===void 0)return this.$(`img`)?this.$(`img`).crossOrigin:this.player_.tech_&&this.player_.tech_.isReady_?this.player_.crossOrigin():this.player_.options_.crossOrigin||this.player_.options_.crossorigin||null;if(e!==null&&e!==`anonymous`&&e!==`use-credentials`){this.player_.log.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${e}"`);return}this.$(`img`)&&(this.$(`img`).crossOrigin=e)}update(e){let t=this.player().poster();this.setSrc(t),t?this.show():this.hide()}setSrc(e){if(!e){this.el_.textContent=``;return}this.$(`img`)||this.el_.appendChild(V(`picture`,{className:`vjs-poster`,tabIndex:-1},{},V(`img`,{loading:`lazy`,crossOrigin:this.crossOrigin()},{alt:``}))),this.$(`img`).src=e}handleClick(e){this.player_.controls()&&(this.player_.tech(!0)&&this.player_.tech(!0).focus(),this.player_.paused()?Ha(this.player_.play()):this.player_.pause())}};Qo.prototype.crossorigin=Qo.prototype.crossOrigin,H.registerComponent(`PosterImage`,Qo);var $o=`#222`,es=`#ccc`,ts={monospace:`monospace`,sansSerif:`sans-serif`,serif:`serif`,monospaceSansSerif:`"Andale Mono", "Lucida Console", monospace`,monospaceSerif:`"Courier New", monospace`,proportionalSansSerif:`sans-serif`,proportionalSerif:`serif`,casual:`"Comic Sans MS", Impact, fantasy`,script:`"Monotype Corsiva", cursive`,smallcaps:`"Andale Mono", "Lucida Console", monospace, sans-serif`};function ns(e,t){let n;if(e.length===4)n=e[1]+e[1]+e[2]+e[2]+e[3]+e[3];else if(e.length===7)n=e.slice(1);else throw Error(`Invalid color code provided, `+e+`; must be formatted as e.g. #f0e or #f604e2.`);return`rgba(`+parseInt(n.slice(0,2),16)+`,`+parseInt(n.slice(2,4),16)+`,`+parseInt(n.slice(4,6),16)+`,`+t+`)`}function rs(e,t,n){try{e.style[t]=n}catch{return}}function is(e){return e?`${e}px`:``}var as=class extends H{constructor(e,t,n){super(e,t,n);let r=e=>this.updateDisplay(e),i=e=>{this.updateDisplayOverlay(),this.updateDisplay(e)};e.on(`loadstart`,e=>this.toggleDisplay(e)),e.on(`useractive`,r),e.on(`userinactive`,r),e.on(`texttrackchange`,r),e.on(`loadedmetadata`,e=>{this.updateDisplayOverlay(),this.preselectTrack(e)}),e.ready(oa(this,function(){if(e.tech_&&e.tech_.featuresNativeTextTracks){this.hide();return}e.on(`fullscreenchange`,i),e.on(`playerresize`,i);let t=I.default.screen.orientation||I.default,n=I.default.screen.orientation?`change`:`orientationchange`;t.addEventListener(n,i),e.on(`dispose`,()=>t.removeEventListener(n,i));let r=this.options_.playerOptions.tracks||[];for(let e=0;e0&&t.forEach(e=>{if(e.style.inset){let t=e.style.inset.split(` `);t.length===3&&Object.assign(e.style,{top:t[0],right:t[1],bottom:t[2],left:`unset`})}})}}updateDisplayOverlay(){if(!this.player_.videoHeight()||!(I.default.CSS!==void 0&&I.default.CSS.supports(`inset-inline: 10px`)))return;let e=this.player_.currentWidth(),t=this.player_.currentHeight(),n=e/t,r=this.player_.videoWidth()/this.player_.videoHeight(),i=0,a=0;Math.abs(n-r)>.1&&(n>r?i=Math.round((e-t*r)/2):a=Math.round((t-e/r)/2)),rs(this.el_,`insetInline`,is(i)),rs(this.el_,`insetBlock`,is(a))}updateDisplayState(e){let t=this.player_.textTrackSettings.getValues(),n=e.activeCues,r=n.length;for(;r--;){let e=n[r];if(!e)continue;let i=e.displayState;if(t.color&&(i.firstChild.style.color=t.color),t.textOpacity&&rs(i.firstChild,`color`,ns(t.color||`#fff`,t.textOpacity)),t.backgroundColor&&(i.firstChild.style.backgroundColor=t.backgroundColor),t.backgroundOpacity&&rs(i.firstChild,`backgroundColor`,ns(t.backgroundColor||`#000`,t.backgroundOpacity)),t.windowColor&&(t.windowOpacity?rs(i,`backgroundColor`,ns(t.windowColor,t.windowOpacity)):i.style.backgroundColor=t.windowColor),t.edgeStyle&&(t.edgeStyle===`dropshadow`?i.firstChild.style.textShadow=`2px 2px 3px ${$o}, 2px 2px 4px ${$o}, 2px 2px 5px ${$o}`:t.edgeStyle===`raised`?i.firstChild.style.textShadow=`1px 1px ${$o}, 2px 2px ${$o}, 3px 3px ${$o}`:t.edgeStyle===`depressed`?i.firstChild.style.textShadow=`1px 1px ${es}, 0 1px ${es}, -1px -1px ${$o}, 0 -1px ${$o}`:t.edgeStyle===`uniform`&&(i.firstChild.style.textShadow=`0 0 4px ${$o}, 0 0 4px ${$o}, 0 0 4px ${$o}, 0 0 4px ${$o}`)),t.fontPercent&&t.fontPercent!==1){let e=I.default.parseFloat(i.style.fontSize);i.style.fontSize=e*t.fontPercent+`px`,i.style.height=`auto`,i.style.top=`auto`}t.fontFamily&&t.fontFamily!==`default`&&(t.fontFamily===`small-caps`?i.firstChild.style.fontVariant=`small-caps`:i.firstChild.style.fontFamily=ts[t.fontFamily])}}updateForTrack(e){if(Array.isArray(e)||(e=[e]),typeof I.default.WebVTT!=`function`||e.every(e=>!e.activeCues))return;let t=[];for(let n=0;nthis.handleMouseDown(e))}buildCSSClass(){return`vjs-big-play-button`}handleClick(e){let t=this.player_.play();if(e.type===`tap`||this.mouseused_&&`clientX`in e&&`clientY`in e){Ha(t),this.player_.tech(!0)&&this.player_.tech(!0).focus();return}let n=this.player_.getChild(`controlBar`),r=n&&n.getChild(`playToggle`);if(!r){this.player_.tech(!0).focus();return}let i=()=>r.focus();Va(t)?t.then(i,()=>{}):this.setTimeout(i,1)}handleKeyDown(e){this.mouseused_=!1,super.handleKeyDown(e)}handleMouseDown(e){this.mouseused_=!0}};cs.prototype.controlText_=`Play Video`,H.registerComponent(`BigPlayButton`,cs);var ls=class extends ss{constructor(e,t){super(e,t),this.setIcon(`cancel`),this.controlText(t&&t.controlText||this.localize(`Close`))}buildCSSClass(){return`vjs-close-button ${super.buildCSSClass()}`}handleClick(e){this.trigger({type:`close`,bubbles:!1})}handleKeyDown(e){e.key===`Escape`?(e.preventDefault(),e.stopPropagation(),this.trigger(`click`)):super.handleKeyDown(e)}};H.registerComponent(`CloseButton`,ls);var us=class extends ss{constructor(e,t={}){super(e,t),t.replay=t.replay===void 0||t.replay,this.setIcon(`play`),this.on(e,`play`,e=>this.handlePlay(e)),this.on(e,`pause`,e=>this.handlePause(e)),t.replay&&this.on(e,`ended`,e=>this.handleEnded(e))}buildCSSClass(){return`vjs-play-control ${super.buildCSSClass()}`}handleClick(e){this.player_.paused()?Ha(this.player_.play()):this.player_.pause()}handleSeeked(e){this.removeClass(`vjs-ended`),this.player_.paused()?this.handlePause(e):this.handlePlay(e)}handlePlay(e){this.removeClass(`vjs-ended`,`vjs-paused`),this.addClass(`vjs-playing`),this.setIcon(`pause`),this.controlText(`Pause`)}handlePause(e){this.removeClass(`vjs-playing`),this.addClass(`vjs-paused`),this.setIcon(`play`),this.controlText(`Play`)}handleEnded(e){this.removeClass(`vjs-playing`),this.addClass(`vjs-ended`),this.setIcon(`replay`),this.controlText(`Replay`),this.one(this.player_,`seeked`,e=>this.handleSeeked(e))}};us.prototype.controlText_=`Play`,H.registerComponent(`PlayToggle`,us);var ds=class extends H{constructor(e,t){super(e,t),this.on(e,[`timeupdate`,`ended`,`seeking`],e=>this.update(e)),this.updateTextNode_()}createEl(){let e=this.buildCSSClass(),t=super.createEl(`div`,{className:`${e} vjs-time-control vjs-control`}),n=V(`span`,{className:`vjs-control-text`,textContent:`${this.localize(this.labelText_)}\u00a0`},{role:`presentation`});return t.appendChild(n),this.contentEl_=V(`span`,{className:`${e}-display`},{role:`presentation`}),t.appendChild(this.contentEl_),t}dispose(){this.contentEl_=null,this.textNode_=null,super.dispose()}update(e){!this.player_.options_.enableSmoothSeeking&&e.type===`seeking`||this.updateContent(e)}updateTextNode_(e=0){e=La(e),this.formattedTime_!==e&&(this.formattedTime_=e,this.requestNamedAnimationFrame(`TimeDisplay#updateTextNode_`,()=>{if(!this.contentEl_)return;let e=this.textNode_;e&&this.contentEl_.firstChild!==e&&(e=null,B.warn(`TimeDisplay#updateTextnode_: Prevented replacement of text node element since it was no longer a child of this node. Appending a new node instead.`)),this.textNode_=L.default.createTextNode(this.formattedTime_),this.textNode_&&(e?this.contentEl_.replaceChild(this.textNode_,e):this.contentEl_.appendChild(this.textNode_))}))}updateContent(e){}};ds.prototype.labelText_=`Time`,ds.prototype.controlText_=`Time`,H.registerComponent(`TimeDisplay`,ds);var fs=class extends ds{buildCSSClass(){return`vjs-current-time`}updateContent(e){let t;t=this.player_.ended()?this.player_.duration():e&&e.target&&typeof e.target.pendingSeekTime==`function`&&e.target.pendingSeekTime()!==null?e.target.pendingSeekTime():this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime(),this.updateTextNode_(t)}};fs.prototype.labelText_=`Current Time`,fs.prototype.controlText_=`Current Time`,H.registerComponent(`CurrentTimeDisplay`,fs);var ps=class extends ds{constructor(e,t){super(e,t);let n=e=>this.updateContent(e);this.on(e,`durationchange`,n),this.on(e,`loadstart`,n),this.on(e,`loadedmetadata`,n)}buildCSSClass(){return`vjs-duration`}updateContent(e){let t=this.player_.duration();this.updateTextNode_(t)}};ps.prototype.labelText_=`Duration`,ps.prototype.controlText_=`Duration`,H.registerComponent(`DurationDisplay`,ps);var ms=class extends H{createEl(){let e=super.createEl(`div`,{className:`vjs-time-control vjs-time-divider`},{"aria-hidden":!0}),t=super.createEl(`div`),n=super.createEl(`span`,{textContent:`/`});return t.appendChild(n),e.appendChild(t),e}};H.registerComponent(`TimeDivider`,ms);var hs=class extends ds{constructor(e,t){super(e,t),this.on(e,`durationchange`,e=>this.updateContent(e))}buildCSSClass(){return`vjs-remaining-time`}createEl(){let e=super.createEl();return this.options_.displayNegative!==!1&&e.insertBefore(V(`span`,{},{"aria-hidden":!0},`-`),this.contentEl_),e}updateContent(e){if(typeof this.player_.duration()!=`number`)return;let t;t=this.player_.ended()?0:this.player_.remainingTimeDisplay?this.player_.remainingTimeDisplay():this.player_.remainingTime(),this.updateTextNode_(t)}};hs.prototype.labelText_=`Remaining Time`,hs.prototype.controlText_=`Remaining Time`,H.registerComponent(`RemainingTimeDisplay`,hs);var gs=class extends H{constructor(e,t){super(e,t),this.updateShowing(),this.on(this.player(),`durationchange`,e=>this.updateShowing(e))}createEl(){let e=super.createEl(`div`,{className:`vjs-live-control vjs-control`});return this.contentEl_=V(`div`,{className:`vjs-live-display`},{"aria-live":`off`}),this.contentEl_.appendChild(V(`span`,{className:`vjs-control-text`,textContent:`${this.localize(`Stream Type`)}\u00a0`})),this.contentEl_.appendChild(L.default.createTextNode(this.localize(`LIVE`))),e.appendChild(this.contentEl_),e}dispose(){this.contentEl_=null,super.dispose()}updateShowing(e){this.player().duration()===1/0?this.show():this.hide()}};H.registerComponent(`LiveDisplay`,gs);var _s=class extends ss{constructor(e,t){super(e,t),this.updateLiveEdgeStatus(),this.player_.liveTracker&&(this.updateLiveEdgeStatusHandler_=e=>this.updateLiveEdgeStatus(e),this.on(this.player_.liveTracker,`liveedgechange`,this.updateLiveEdgeStatusHandler_))}createEl(){let e=super.createEl(`button`,{className:`vjs-seek-to-live-control vjs-control`});return this.setIcon(`circle`,e),this.textEl_=V(`span`,{className:`vjs-seek-to-live-text`,textContent:this.localize(`LIVE`)},{"aria-hidden":`true`}),e.appendChild(this.textEl_),e}updateLiveEdgeStatus(){!this.player_.liveTracker||this.player_.liveTracker.atLiveEdge()?(this.setAttribute(`aria-disabled`,!0),this.addClass(`vjs-at-live-edge`),this.controlText(`Seek to live, currently playing live`)):(this.setAttribute(`aria-disabled`,!1),this.removeClass(`vjs-at-live-edge`),this.controlText(`Seek to live, currently behind live`))}handleClick(){this.player_.liveTracker.seekToLiveEdge()}dispose(){this.player_.liveTracker&&this.off(this.player_.liveTracker,`liveedgechange`,this.updateLiveEdgeStatusHandler_),this.textEl_=null,super.dispose()}};_s.prototype.controlText_=`Seek to live, currently playing live`,H.registerComponent(`SeekToLive`,_s);function vs(e,t,n){return e=Number(e),Math.min(n,Math.max(t,isNaN(e)?t:e))}var ys=Object.freeze({__proto__:null,clamp:vs}),bs=class extends H{constructor(e,t){super(e,t),this.handleMouseDown_=e=>this.handleMouseDown(e),this.handleMouseUp_=e=>this.handleMouseUp(e),this.handleKeyDown_=e=>this.handleKeyDown(e),this.handleClick_=e=>this.handleClick(e),this.handleMouseMove_=e=>this.handleMouseMove(e),this.update_=e=>this.update(e),this.bar=this.getChild(this.options_.barName),this.vertical(!!this.options_.vertical),this.enable()}enabled(){return this.enabled_}enable(){this.enabled()||(this.on(`mousedown`,this.handleMouseDown_),this.on(`touchstart`,this.handleMouseDown_),this.on(`keydown`,this.handleKeyDown_),this.on(`click`,this.handleClick_),this.on(this.player_,`controlsvisible`,this.update),this.playerEvent&&this.on(this.player_,this.playerEvent,this.update),this.removeClass(`disabled`),this.setAttribute(`tabindex`,0),this.enabled_=!0)}disable(){if(!this.enabled())return;let e=this.bar.el_.ownerDocument;this.off(`mousedown`,this.handleMouseDown_),this.off(`touchstart`,this.handleMouseDown_),this.off(`keydown`,this.handleKeyDown_),this.off(`click`,this.handleClick_),this.off(this.player_,`controlsvisible`,this.update_),this.off(e,`mousemove`,this.handleMouseMove_),this.off(e,`mouseup`,this.handleMouseUp_),this.off(e,`touchmove`,this.handleMouseMove_),this.off(e,`touchend`,this.handleMouseUp_),this.removeAttribute(`tabindex`),this.addClass(`disabled`),this.playerEvent&&this.off(this.player_,this.playerEvent,this.update),this.enabled_=!1}createEl(e,t={},n={}){return t.className+=` vjs-slider`,t=Object.assign({tabIndex:0},t),n=Object.assign({role:`slider`,"aria-valuenow":0,"aria-valuemin":0,"aria-valuemax":100},n),super.createEl(e,t,n)}handleMouseDown(e){let t=this.bar.el_.ownerDocument;e.type===`mousedown`&&e.preventDefault(),e.type===`touchstart`&&!Vr&&e.preventDefault(),xi(),this.addClass(`vjs-sliding`),this.trigger(`slideractive`),this.on(t,`mousemove`,this.handleMouseMove_),this.on(t,`mouseup`,this.handleMouseUp_),this.on(t,`touchmove`,this.handleMouseMove_),this.on(t,`touchend`,this.handleMouseUp_),this.handleMouseMove(e,!0)}handleMouseMove(e){}handleMouseUp(e){let t=this.bar.el_.ownerDocument;Si(),this.removeClass(`vjs-sliding`),this.trigger(`sliderinactive`),this.off(t,`mousemove`,this.handleMouseMove_),this.off(t,`mouseup`,this.handleMouseUp_),this.off(t,`touchmove`,this.handleMouseMove_),this.off(t,`touchend`,this.handleMouseUp_),this.update()}update(){if(!this.el_||!this.bar)return;let e=this.getProgress();return e===this.progress_?e:(this.progress_=e,this.requestNamedAnimationFrame(`Slider#update`,()=>{let t=this.vertical()?`height`:`width`;this.bar.el().style[t]=(e*100).toFixed(2)+`%`}),e)}getProgress(){return Number(vs(this.getPercent(),0,1).toFixed(4))}calculateDistance(e){let t=Ti(this.el_,e);return this.vertical()?t.y:t.x}handleKeyDown(e){let t=this.options_.playerOptions.spatialNavigation,n=t&&t.enabled,r=t&&t.horizontalSeek;n?r&&e.key===`ArrowLeft`||!r&&e.key===`ArrowDown`?(e.preventDefault(),e.stopPropagation(),this.stepBack()):r&&e.key===`ArrowRight`||!r&&e.key===`ArrowUp`?(e.preventDefault(),e.stopPropagation(),this.stepForward()):(this.pendingSeekTime()&&(this.pendingSeekTime(null),this.userSeek_(this.player_.currentTime())),super.handleKeyDown(e)):e.key===`ArrowLeft`||e.key===`ArrowDown`?(e.preventDefault(),e.stopPropagation(),this.stepBack()):e.key===`ArrowUp`||e.key===`ArrowRight`?(e.preventDefault(),e.stopPropagation(),this.stepForward()):super.handleKeyDown(e)}handleClick(e){e.stopPropagation(),e.preventDefault()}vertical(e){if(e===void 0)return this.vertical_||!1;this.vertical_=!!e,this.vertical_?this.addClass(`vjs-slider-vertical`):this.addClass(`vjs-slider-horizontal`)}};H.registerComponent(`Slider`,bs);var xs=(e,t)=>vs(e/t*100,0,100).toFixed(2)+`%`,Ss=class extends H{constructor(e,t){super(e,t),this.partEls_=[],this.on(e,`progress`,e=>this.update(e))}createEl(){let e=super.createEl(`div`,{className:`vjs-load-progress`}),t=V(`span`,{className:`vjs-control-text`}),n=V(`span`,{textContent:this.localize(`Loaded`)}),r=L.default.createTextNode(`: `);return this.percentageEl_=V(`span`,{className:`vjs-control-text-loaded-percentage`,textContent:`0%`}),e.appendChild(t),t.appendChild(n),t.appendChild(r),t.appendChild(this.percentageEl_),e}dispose(){this.partEls_=null,this.percentageEl_=null,super.dispose()}update(e){this.requestNamedAnimationFrame(`LoadProgressBar#update`,()=>{let e=this.player_.liveTracker,t=this.player_.buffered(),n=e&&e.isLive()?e.seekableEnd():this.player_.duration(),r=this.player_.bufferedEnd(),i=this.partEls_,a=xs(r,n);this.percent_!==a&&(this.el_.style.width=a,ui(this.percentageEl_,a),this.percent_=a);for(let e=0;et.length;e--)this.el_.removeChild(i[e-1]);i.length=t.length})}};H.registerComponent(`LoadProgressBar`,Ss);var Cs=class extends H{constructor(e,t){super(e,t),this.update=sa(oa(this,this.update),aa)}createEl(){return super.createEl(`div`,{className:`vjs-time-tooltip`},{"aria-hidden":`true`})}update(e,t,n){let r=wi(this.el_),i=Ci(this.player_.el()),a=e.width*t;if(!i||!r)return;let o=e.left-i.left+a,s=e.width-a+(i.right-e.right);s||(s=e.width-a,o=a);let c=r.width/2;or.width&&(c=r.width),c=Math.round(c),this.el_.style.right=`-${c}px`,this.write(n)}write(e){ui(this.el_,e)}updateTime(e,t,n,r){this.requestNamedAnimationFrame(`TimeTooltip#updateTime`,()=>{let i,a=this.player_.duration();if(this.player_.liveTracker&&this.player_.liveTracker.isLive()){let e=this.player_.liveTracker.liveWindow(),n=e-t*e;i=(n<1?``:`-`)+La(n,e)}else i=La(n,a);this.update(e,t,i),r&&r()})}};H.registerComponent(`TimeTooltip`,Cs);var ws=class extends H{constructor(e,t){super(e,t),this.setIcon(`circle`),this.update=sa(oa(this,this.update),aa)}createEl(){return super.createEl(`div`,{className:`vjs-play-progress vjs-slider-bar`},{"aria-hidden":`true`})}update(e,t,n){let r=this.getChild(`timeTooltip`);if(!r)return;let i=n&&n.target&&typeof n.target.pendingSeekTime==`function`?n.target.pendingSeekTime():this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime();r.updateTime(e,t,i)}};ws.prototype.options_={children:[]},!ti&&!Ir&&ws.prototype.options_.children.push(`timeTooltip`),H.registerComponent(`PlayProgressBar`,ws);var Ts=class extends H{constructor(e,t){super(e,t),this.update=sa(oa(this,this.update),aa)}createEl(){return super.createEl(`div`,{className:`vjs-mouse-display`})}update(e,t){let n=t*this.player_.duration();this.getChild(`timeTooltip`).updateTime(e,t,n,()=>{this.el_.style.left=`${e.width*t}px`})}};Ts.prototype.options_={children:[`timeTooltip`]},H.registerComponent(`MouseTimeDisplay`,Ts);var Es=class e extends bs{constructor(t,n){n=Ar(e.prototype.options_,n),n.children=[...n.children];let r=t.options_.disableSeekWhileScrubbingOnMobile&&(ti||Ir)||t.options_.disableSeekWhileScrubbingOnSTV;(!ti&&!Ir||r)&&n.children.splice(1,0,`mouseTimeDisplay`),super(t,n),this.shouldDisableSeekWhileScrubbing_=r,this.pendingSeekTime_=null,this.setEventHandlers_()}setEventHandlers_(){this.update_=oa(this,this.update),this.update=sa(this.update_,aa),this.on(this.player_,[`durationchange`,`timeupdate`],this.update),this.on(this.player_,[`ended`],this.update_),this.player_.liveTracker&&this.on(this.player_.liveTracker,`liveedgechange`,this.update),this.updateInterval=null,this.enableIntervalHandler_=e=>this.enableInterval_(e),this.disableIntervalHandler_=e=>this.disableInterval_(e),this.on(this.player_,[`playing`],this.enableIntervalHandler_),this.on(this.player_,[`ended`,`pause`,`waiting`],this.disableIntervalHandler_),`hidden`in L.default&&`visibilityState`in L.default&&this.on(L.default,`visibilitychange`,this.toggleVisibility_)}toggleVisibility_(e){L.default.visibilityState===`hidden`?(this.cancelNamedAnimationFrame(`SeekBar#update`),this.cancelNamedAnimationFrame(`Slider#update`),this.disableInterval_(e)):(!this.player_.ended()&&!this.player_.paused()&&this.enableInterval_(),this.update())}enableInterval_(){this.updateInterval||=this.setInterval(this.update,aa)}disableInterval_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&e&&e.type!==`ended`||(this.updateInterval&&=(this.clearInterval(this.updateInterval),null))}createEl(){return super.createEl(`div`,{className:`vjs-progress-holder`},{"aria-label":this.localize(`Progress Bar`)})}update(e){if(L.default.visibilityState===`hidden`)return;let t=super.update();return this.requestNamedAnimationFrame(`SeekBar#update`,()=>{let n=this.player_.ended()?this.player_.duration():this.getCurrentTime_(),r=this.player_.liveTracker,i=this.player_.duration();r&&r.isLive()&&(i=this.player_.liveTracker.liveCurrentTime()),this.percent_!==t&&(this.el_.setAttribute(`aria-valuenow`,(t*100).toFixed(2)),this.percent_=t),(this.currentTime_!==n||this.duration_!==i)&&(this.el_.setAttribute(`aria-valuetext`,this.localize(`progress bar timing: currentTime={1} duration={2}`,[La(n,i),La(i,i)],`{1} of {2}`)),this.currentTime_=n,this.duration_=i),this.bar&&this.bar.update(Ci(this.el()),this.getProgress(),e)}),t}userSeek_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&this.player_.liveTracker.nextSeekedFromUser(),this.player_.currentTime(e)}getCurrentTime_(){return this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime()}pendingSeekTime(e){if(e!==void 0)if(e!==null){let t=this.player_.duration();this.pendingSeekTime_=Math.max(0,Math.min(e,t))}else this.pendingSeekTime_=null;return this.pendingSeekTime_}getPercent(){if(this.pendingSeekTime()!==null)return this.pendingSeekTime()/this.player_.duration();let e=this.getCurrentTime_(),t,n=this.player_.liveTracker;return n&&n.isLive()?(t=(e-n.seekableStart())/n.liveWindow(),n.atLiveEdge()&&(t=1)):t=e/this.player_.duration(),t}handleMouseDown(e){ji(e)&&(e.stopPropagation(),this.videoWasPlaying=!this.player_.paused(),this.shouldDisableSeekWhileScrubbing_||this.player_.pause(),super.handleMouseDown(e))}handleMouseMove(e,t=!1){if(!ji(e)||isNaN(this.player_.duration()))return;!t&&!this.player_.scrubbing()&&this.player_.scrubbing(!0);let n,r=this.calculateDistance(e),i=this.player_.liveTracker;if(!i||!i.isLive())n=r*this.player_.duration(),n===this.player_.duration()&&(n-=.1);else{if(r>=.99){i.seekToLiveEdge();return}let e=i.seekableStart(),t=i.liveCurrentTime();if(n=e+r*i.liveWindow(),n>=t&&(n=t),n<=e&&(n=e+.1),n===1/0)return}this.shouldDisableSeekWhileScrubbing_?this.pendingSeekTime(n):this.userSeek_(n),this.player_.options_.enableSmoothSeeking&&this.update()}enable(){super.enable();let e=this.getChild(`mouseTimeDisplay`);e&&e.show()}disable(){super.disable();let e=this.getChild(`mouseTimeDisplay`);e&&e.hide()}handleMouseUp(e){super.handleMouseUp(e),e&&e.stopPropagation(),this.player_.scrubbing(!1),this.pendingSeekTime()!==null&&(this.userSeek_(this.pendingSeekTime()),this.pendingSeekTime(null)),this.player_.trigger({type:`timeupdate`,target:this,manuallyTriggered:!0}),this.videoWasPlaying?Ha(this.player_.play()):this.update_()}handlePendingSeek_(e){this.player_.paused()||this.player_.pause();let t=this.pendingSeekTime()===null?this.player_.currentTime():this.pendingSeekTime();this.pendingSeekTime(t+e),this.player_.trigger({type:`timeupdate`,target:this,manuallyTriggered:!0})}stepForward(){this.shouldDisableSeekWhileScrubbing_?this.handlePendingSeek_(this.options().stepSeconds):this.userSeek_(this.player_.currentTime()+this.options().stepSeconds)}stepBack(){this.shouldDisableSeekWhileScrubbing_?this.handlePendingSeek_(-this.options().stepSeconds):this.userSeek_(this.player_.currentTime()-this.options().stepSeconds)}handleAction(e){this.pendingSeekTime()!==null&&(this.userSeek_(this.pendingSeekTime()),this.pendingSeekTime(null)),this.player_.paused()?this.player_.play():this.player_.pause()}handleKeyDown(e){let t=this.player_.liveTracker;if(e.key===` `||e.key===`Enter`)e.preventDefault(),e.stopPropagation(),this.handleAction(e);else if(e.key===`Home`)e.preventDefault(),e.stopPropagation(),this.userSeek_(0);else if(e.key===`End`)e.preventDefault(),e.stopPropagation(),t&&t.isLive()?this.userSeek_(t.liveCurrentTime()):this.userSeek_(this.player_.duration());else if(/^[0-9]$/.test(e.key)){e.preventDefault(),e.stopPropagation();let n=parseInt(e.key,10)*.1;t&&t.isLive()?this.userSeek_(t.seekableStart()+t.liveWindow()*n):this.userSeek_(this.player_.duration()*n)}else e.key===`PageDown`?(e.preventDefault(),e.stopPropagation(),this.userSeek_(this.player_.currentTime()-this.options().stepSeconds*this.options().pageMultiplier)):e.key===`PageUp`?(e.preventDefault(),e.stopPropagation(),this.userSeek_(this.player_.currentTime()+this.options().stepSeconds*this.options().pageMultiplier)):super.handleKeyDown(e)}dispose(){this.disableInterval_(),this.off(this.player_,[`durationchange`,`timeupdate`],this.update),this.off(this.player_,[`ended`],this.update_),this.player_.liveTracker&&this.off(this.player_.liveTracker,`liveedgechange`,this.update),this.off(this.player_,[`playing`],this.enableIntervalHandler_),this.off(this.player_,[`ended`,`pause`,`waiting`],this.disableIntervalHandler_),`hidden`in L.default&&`visibilityState`in L.default&&this.off(L.default,`visibilitychange`,this.toggleVisibility_),super.dispose()}};Es.prototype.options_={children:[`loadProgressBar`,`playProgressBar`],barName:`playProgressBar`,stepSeconds:5,pageMultiplier:12},H.registerComponent(`SeekBar`,Es);var Ds=class extends H{constructor(e,t){super(e,t),this.handleMouseMove=sa(oa(this,this.handleMouseMove),aa),this.throttledHandleMouseSeek=sa(oa(this,this.handleMouseSeek),aa),this.handleMouseUpHandler_=e=>this.handleMouseUp(e),this.handleMouseDownHandler_=e=>this.handleMouseDown(e),this.enable()}createEl(){return super.createEl(`div`,{className:`vjs-progress-control vjs-control`})}handleMouseMove(e){let t=this.getChild(`seekBar`);if(!t)return;let n=t.getChild(`playProgressBar`),r=t.getChild(`mouseTimeDisplay`);if(!n&&!r)return;let i=t.el(),a=wi(i),o=Ti(i,e).x;o=vs(o,0,1),r&&r.update(a,o),n&&n.update(a,t.getProgress())}handleMouseSeek(e){let t=this.getChild(`seekBar`);t&&t.handleMouseMove(e)}enabled(){return this.enabled_}disable(){if(this.children().forEach(e=>e.disable&&e.disable()),this.enabled()&&(this.off([`mousedown`,`touchstart`],this.handleMouseDownHandler_),this.off(this.el_,[`mousemove`,`touchmove`],this.handleMouseMove),this.removeListenersAddedOnMousedownAndTouchstart(),this.addClass(`disabled`),this.enabled_=!1,this.player_.scrubbing())){let e=this.getChild(`seekBar`);this.player_.scrubbing(!1),e.videoWasPlaying&&Ha(this.player_.play())}}enable(){this.children().forEach(e=>e.enable&&e.enable()),!this.enabled()&&(this.on([`mousedown`,`touchstart`],this.handleMouseDownHandler_),this.on(this.el_,[`mousemove`,`touchmove`],this.handleMouseMove),this.removeClass(`disabled`),this.enabled_=!0)}removeListenersAddedOnMousedownAndTouchstart(){let e=this.el_.ownerDocument;this.off(e,`mousemove`,this.throttledHandleMouseSeek),this.off(e,`touchmove`,this.throttledHandleMouseSeek),this.off(e,`mouseup`,this.handleMouseUpHandler_),this.off(e,`touchend`,this.handleMouseUpHandler_)}handleMouseDown(e){let t=this.el_.ownerDocument,n=this.getChild(`seekBar`);n&&n.handleMouseDown(e),this.on(t,`mousemove`,this.throttledHandleMouseSeek),this.on(t,`touchmove`,this.throttledHandleMouseSeek),this.on(t,`mouseup`,this.handleMouseUpHandler_),this.on(t,`touchend`,this.handleMouseUpHandler_)}handleMouseUp(e){let t=this.getChild(`seekBar`);t&&t.handleMouseUp(e),this.removeListenersAddedOnMousedownAndTouchstart()}};Ds.prototype.options_={children:[`seekBar`]},H.registerComponent(`ProgressControl`,Ds);var Os=class extends ss{constructor(e,t){super(e,t),this.setIcon(`picture-in-picture-enter`),this.on(e,[`enterpictureinpicture`,`leavepictureinpicture`],e=>this.handlePictureInPictureChange(e)),this.on(e,[`disablepictureinpicturechanged`,`loadedmetadata`],e=>this.handlePictureInPictureEnabledChange(e)),this.on(e,[`loadedmetadata`,`audioonlymodechange`,`audiopostermodechange`],()=>this.handlePictureInPictureAudioModeChange()),this.disable()}buildCSSClass(){return`vjs-picture-in-picture-control vjs-hidden ${super.buildCSSClass()}`}handlePictureInPictureAudioModeChange(){if(!(this.player_.currentType().substring(0,5)===`audio`||this.player_.audioPosterMode()||this.player_.audioOnlyMode())){this.show();return}this.player_.isInPictureInPicture()&&this.player_.exitPictureInPicture(),this.hide()}handlePictureInPictureEnabledChange(){L.default.pictureInPictureEnabled&&this.player_.disablePictureInPicture()===!1||this.player_.options_.enableDocumentPictureInPicture&&`documentPictureInPicture`in I.default?this.enable():this.disable()}handlePictureInPictureChange(e){this.player_.isInPictureInPicture()?(this.setIcon(`picture-in-picture-exit`),this.controlText(`Exit Picture-in-Picture`)):(this.setIcon(`picture-in-picture-enter`),this.controlText(`Picture-in-Picture`)),this.handlePictureInPictureEnabledChange()}handleClick(e){this.player_.isInPictureInPicture()?this.player_.exitPictureInPicture():this.player_.requestPictureInPicture()}show(){typeof L.default.exitPictureInPicture==`function`&&super.show()}};Os.prototype.controlText_=`Picture-in-Picture`,H.registerComponent(`PictureInPictureToggle`,Os);var ks=class extends ss{constructor(e,t){super(e,t),this.setIcon(`fullscreen-enter`),this.on(e,`fullscreenchange`,e=>this.handleFullscreenChange(e)),L.default[e.fsApi_.fullscreenEnabled]===!1&&this.disable()}buildCSSClass(){return`vjs-fullscreen-control ${super.buildCSSClass()}`}handleFullscreenChange(e){this.player_.isFullscreen()?(this.controlText(`Exit Fullscreen`),this.setIcon(`fullscreen-exit`)):(this.controlText(`Fullscreen`),this.setIcon(`fullscreen-enter`))}handleClick(e){this.player_.isFullscreen()?this.player_.exitFullscreen():this.player_.requestFullscreen()}};ks.prototype.controlText_=`Fullscreen`,H.registerComponent(`FullscreenToggle`,ks);var As=function(e,t){t.tech_&&!t.tech_.featuresVolumeControl&&e.addClass(`vjs-hidden`),e.on(t,`loadstart`,function(){t.tech_.featuresVolumeControl?e.removeClass(`vjs-hidden`):e.addClass(`vjs-hidden`)})},js=class extends H{createEl(){let e=super.createEl(`div`,{className:`vjs-volume-level`});return this.setIcon(`circle`,e),e.appendChild(super.createEl(`span`,{className:`vjs-control-text`})),e}};H.registerComponent(`VolumeLevel`,js);var Ms=class extends H{constructor(e,t){super(e,t),this.update=sa(oa(this,this.update),aa)}createEl(){return super.createEl(`div`,{className:`vjs-volume-tooltip`},{"aria-hidden":`true`})}update(e,t,n,r){if(!n){let n=Ci(this.el_),r=Ci(this.player_.el()),i=e.width*t;if(!r||!n)return;let a=e.left-r.left+i,o=e.width-i+(r.right-e.right),s=n.width/2;an.width&&(s=n.width),this.el_.style.right=`-${s}px`}this.write(`${r}%`)}write(e){ui(this.el_,e)}updateVolume(e,t,n,r,i){this.requestNamedAnimationFrame(`VolumeLevelTooltip#updateVolume`,()=>{this.update(e,t,n,r.toFixed(0)),i&&i()})}};H.registerComponent(`VolumeLevelTooltip`,Ms);var Ns=class extends H{constructor(e,t){super(e,t),this.update=sa(oa(this,this.update),aa)}createEl(){return super.createEl(`div`,{className:`vjs-mouse-display`})}update(e,t,n){let r=100*t;this.getChild(`volumeLevelTooltip`).updateVolume(e,t,n,r,()=>{n?this.el_.style.bottom=`${e.height*t}px`:this.el_.style.left=`${e.width*t}px`})}};Ns.prototype.options_={children:[`volumeLevelTooltip`]},H.registerComponent(`MouseVolumeLevelDisplay`,Ns);var Ps=class extends bs{constructor(e,t){super(e,t),this.on(`slideractive`,e=>this.updateLastVolume_(e)),this.on(e,`volumechange`,e=>this.updateARIAAttributes(e)),e.ready(()=>this.updateARIAAttributes())}createEl(){return super.createEl(`div`,{className:`vjs-volume-bar vjs-slider-bar`},{"aria-label":this.localize(`Volume Level`),"aria-live":`polite`})}handleMouseDown(e){ji(e)&&super.handleMouseDown(e)}handleMouseMove(e){let t=this.getChild(`mouseVolumeLevelDisplay`);if(t){let n=this.el(),r=Ci(n),i=this.vertical(),a=Ti(n,e);a=i?a.y:a.x,a=vs(a,0,1),t.update(r,a,i)}ji(e)&&(this.checkMuted(),this.player_.volume(this.calculateDistance(e)))}checkMuted(){this.player_.muted()&&this.player_.muted(!1)}getPercent(){return this.player_.muted()?0:this.player_.volume()}stepForward(){this.checkMuted(),this.player_.volume(this.player_.volume()+.1)}stepBack(){this.checkMuted(),this.player_.volume(this.player_.volume()-.1)}updateARIAAttributes(e){let t=this.player_.muted()?0:this.volumeAsPercentage_();this.el_.setAttribute(`aria-valuenow`,t),this.el_.setAttribute(`aria-valuetext`,t+`%`)}volumeAsPercentage_(){return Math.round(this.player_.volume()*100)}updateLastVolume_(){let e=this.player_.volume();this.one(`sliderinactive`,()=>{this.player_.volume()===0&&this.player_.lastVolume_(e)})}};Ps.prototype.options_={children:[`volumeLevel`],barName:`volumeLevel`},!ti&&!Ir&&Ps.prototype.options_.children.splice(0,0,`mouseVolumeLevelDisplay`),Ps.prototype.playerEvent=`volumechange`,H.registerComponent(`VolumeBar`,Ps);var Fs=class extends H{constructor(e,t={}){t.vertical=t.vertical||!1,(t.volumeBar===void 0||kr(t.volumeBar))&&(t.volumeBar=t.volumeBar||{},t.volumeBar.vertical=t.vertical),super(e,t),As(this,e),this.throttledHandleMouseMove=sa(oa(this,this.handleMouseMove),aa),this.handleMouseUpHandler_=e=>this.handleMouseUp(e),this.on(`mousedown`,e=>this.handleMouseDown(e)),this.on(`touchstart`,e=>this.handleMouseDown(e)),this.on(`mousemove`,e=>this.handleMouseMove(e)),this.on(this.volumeBar,[`focus`,`slideractive`],()=>{this.volumeBar.addClass(`vjs-slider-active`),this.addClass(`vjs-slider-active`),this.trigger(`slideractive`)}),this.on(this.volumeBar,[`blur`,`sliderinactive`],()=>{this.volumeBar.removeClass(`vjs-slider-active`),this.removeClass(`vjs-slider-active`),this.trigger(`sliderinactive`)})}createEl(){let e=`vjs-volume-horizontal`;return this.options_.vertical&&(e=`vjs-volume-vertical`),super.createEl(`div`,{className:`vjs-volume-control vjs-control ${e}`})}handleMouseDown(e){let t=this.el_.ownerDocument;this.on(t,`mousemove`,this.throttledHandleMouseMove),this.on(t,`touchmove`,this.throttledHandleMouseMove),this.on(t,`mouseup`,this.handleMouseUpHandler_),this.on(t,`touchend`,this.handleMouseUpHandler_)}handleMouseUp(e){let t=this.el_.ownerDocument;this.off(t,`mousemove`,this.throttledHandleMouseMove),this.off(t,`touchmove`,this.throttledHandleMouseMove),this.off(t,`mouseup`,this.handleMouseUpHandler_),this.off(t,`touchend`,this.handleMouseUpHandler_)}handleMouseMove(e){this.volumeBar.handleMouseMove(e)}};Fs.prototype.options_={children:[`volumeBar`]},H.registerComponent(`VolumeControl`,Fs);var Is=function(e,t){t.tech_&&!t.tech_.featuresMuteControl&&e.addClass(`vjs-hidden`),e.on(t,`loadstart`,function(){t.tech_.featuresMuteControl?e.removeClass(`vjs-hidden`):e.addClass(`vjs-hidden`)})},Ls=class extends ss{constructor(e,t){super(e,t),Is(this,e),this.on(e,[`loadstart`,`volumechange`],e=>this.update(e))}buildCSSClass(){return`vjs-mute-control ${super.buildCSSClass()}`}handleClick(e){let t=this.player_.volume(),n=this.player_.lastVolume_();if(t===0){let e=n<.1?.1:n;this.player_.volume(e),this.player_.muted(!1)}else this.player_.muted(!this.player_.muted())}update(e){this.updateIcon_(),this.updateControlText_()}updateIcon_(){let e=this.player_.volume(),t=3;this.setIcon(`volume-high`),ti&&this.player_.tech_&&this.player_.tech_.el_&&this.player_.muted(this.player_.tech_.el_.muted),e===0||this.player_.muted()?(this.setIcon(`volume-mute`),t=0):e<.33?(this.setIcon(`volume-low`),t=1):e<.67&&(this.setIcon(`volume-medium`),t=2),mi(this.el_,[0,1,2,3].reduce((e,t)=>e+`${t?` `:``}vjs-vol-${t}`,``)),pi(this.el_,`vjs-vol-${t}`)}updateControlText_(){let e=this.player_.muted()||this.player_.volume()===0?`Unmute`:`Mute`;this.controlText()!==e&&this.controlText(e)}};Ls.prototype.controlText_=`Mute`,H.registerComponent(`MuteToggle`,Ls);var Rs=class extends H{constructor(e,t={}){t.inline===void 0?t.inline=!0:t.inline=t.inline,(t.volumeControl===void 0||kr(t.volumeControl))&&(t.volumeControl=t.volumeControl||{},t.volumeControl.vertical=!t.inline),super(e,t),this.handleKeyPressHandler_=e=>this.handleKeyPress(e),this.on(e,[`loadstart`],e=>this.volumePanelState_(e)),this.on(this.muteToggle,`keyup`,e=>this.handleKeyPress(e)),this.on(this.volumeControl,`keyup`,e=>this.handleVolumeControlKeyUp(e)),this.on(`keydown`,e=>this.handleKeyPress(e)),this.on(`mouseover`,e=>this.handleMouseOver(e)),this.on(`mouseout`,e=>this.handleMouseOut(e)),this.on(this.volumeControl,[`slideractive`],this.sliderActive_),this.on(this.volumeControl,[`sliderinactive`],this.sliderInactive_)}sliderActive_(){this.addClass(`vjs-slider-active`)}sliderInactive_(){this.removeClass(`vjs-slider-active`)}volumePanelState_(){this.volumeControl.hasClass(`vjs-hidden`)&&this.muteToggle.hasClass(`vjs-hidden`)&&this.addClass(`vjs-hidden`),this.volumeControl.hasClass(`vjs-hidden`)&&!this.muteToggle.hasClass(`vjs-hidden`)&&this.addClass(`vjs-mute-toggle-only`)}createEl(){let e=`vjs-volume-panel-horizontal`;return this.options_.inline||(e=`vjs-volume-panel-vertical`),super.createEl(`div`,{className:`vjs-volume-panel vjs-control ${e}`})}dispose(){this.handleMouseOut(),super.dispose()}handleVolumeControlKeyUp(e){e.key===`Escape`&&this.muteToggle.focus()}handleMouseOver(e){this.addClass(`vjs-hover`),$i(L.default,`keyup`,this.handleKeyPressHandler_)}handleMouseOut(e){this.removeClass(`vjs-hover`),ea(L.default,`keyup`,this.handleKeyPressHandler_)}handleKeyPress(e){e.key===`Escape`&&this.handleMouseOut()}};Rs.prototype.options_={children:[`muteToggle`,`volumeControl`]},H.registerComponent(`VolumePanel`,Rs);var zs=class extends ss{constructor(e,t){super(e,t),this.validOptions=[5,10,30],this.skipTime=this.getSkipForwardTime(),this.skipTime&&this.validOptions.includes(this.skipTime)?(this.setIcon(`forward-${this.skipTime}`),this.controlText(this.localize(`Skip forward {1} seconds`,[this.skipTime.toLocaleString(e.language())])),this.show()):this.hide()}getSkipForwardTime(){let e=this.options_.playerOptions;return e.controlBar&&e.controlBar.skipButtons&&e.controlBar.skipButtons.forward}buildCSSClass(){return`vjs-skip-forward-${this.getSkipForwardTime()} ${super.buildCSSClass()}`}handleClick(e){if(isNaN(this.player_.duration()))return;let t=this.player_.currentTime(),n=this.player_.liveTracker,r=n&&n.isLive()?n.seekableEnd():this.player_.duration(),i;i=t+this.skipTime<=r?t+this.skipTime:r,this.player_.currentTime(i)}handleLanguagechange(){this.controlText(this.localize(`Skip forward {1} seconds`,[this.skipTime]))}};zs.prototype.controlText_=`Skip Forward`,H.registerComponent(`SkipForward`,zs);var Bs=class extends ss{constructor(e,t){super(e,t),this.validOptions=[5,10,30],this.skipTime=this.getSkipBackwardTime(),this.skipTime&&this.validOptions.includes(this.skipTime)?(this.setIcon(`replay-${this.skipTime}`),this.controlText(this.localize(`Skip backward {1} seconds`,[this.skipTime.toLocaleString(e.language())])),this.show()):this.hide()}getSkipBackwardTime(){let e=this.options_.playerOptions;return e.controlBar&&e.controlBar.skipButtons&&e.controlBar.skipButtons.backward}buildCSSClass(){return`vjs-skip-backward-${this.getSkipBackwardTime()} ${super.buildCSSClass()}`}handleClick(e){let t=this.player_.currentTime(),n=this.player_.liveTracker,r=n&&n.isLive()&&n.seekableStart(),i;i=r&&t-this.skipTime<=r?r:t>=this.skipTime?t-this.skipTime:0,this.player_.currentTime(i)}handleLanguagechange(){this.controlText(this.localize(`Skip backward {1} seconds`,[this.skipTime]))}};Bs.prototype.controlText_=`Skip Backward`,H.registerComponent(`SkipBackward`,Bs);var Vs=class extends H{constructor(e,t){super(e,t),t&&(this.menuButton_=t.menuButton),this.focusedChild_=-1,this.on(`keydown`,e=>this.handleKeyDown(e)),this.boundHandleBlur_=e=>this.handleBlur(e),this.boundHandleTapClick_=e=>this.handleTapClick(e)}addEventListenerForItem(e){e instanceof H&&(this.on(e,`blur`,this.boundHandleBlur_),this.on(e,[`tap`,`click`],this.boundHandleTapClick_))}removeEventListenerForItem(e){e instanceof H&&(this.off(e,`blur`,this.boundHandleBlur_),this.off(e,[`tap`,`click`],this.boundHandleTapClick_))}removeChild(e){typeof e==`string`&&(e=this.getChild(e)),this.removeEventListenerForItem(e),super.removeChild(e)}addItem(e){let t=this.addChild(e);t&&this.addEventListenerForItem(t)}createEl(){let e=this.options_.contentElType||`ul`;this.contentEl_=V(e,{className:`vjs-menu-content`}),this.contentEl_.setAttribute(`role`,`menu`);let t=super.createEl(`div`,{append:this.contentEl_,className:`vjs-menu`});return t.appendChild(this.contentEl_),$i(t,`click`,function(e){e.preventDefault(),e.stopImmediatePropagation()}),t}dispose(){this.contentEl_=null,this.boundHandleBlur_=null,this.boundHandleTapClick_=null,super.dispose()}handleBlur(e){let t=e.relatedTarget||L.default.activeElement;if(!this.children().some(e=>e.el()===t)){let e=this.menuButton_;e&&e.buttonPressed_&&t!==e.el().firstChild&&e.unpressButton()}}handleTapClick(e){if(this.menuButton_){this.menuButton_.unpressButton();let t=this.children();if(!Array.isArray(t))return;let n=t.filter(t=>t.el()===e.target)[0];if(!n)return;n.name()!==`CaptionSettingsMenuItem`&&this.menuButton_.focus()}}handleKeyDown(e){e.key===`ArrowLeft`||e.key===`ArrowDown`?(e.preventDefault(),e.stopPropagation(),this.stepForward()):(e.key===`ArrowRight`||e.key===`ArrowUp`)&&(e.preventDefault(),e.stopPropagation(),this.stepBack())}stepForward(){let e=0;this.focusedChild_!==void 0&&(e=this.focusedChild_+1),this.focus(e)}stepBack(){let e=0;this.focusedChild_!==void 0&&(e=this.focusedChild_-1),this.focus(e)}focus(e=0){let t=this.children().slice();t.length&&t[0].hasClass(`vjs-menu-title`)&&t.shift(),t.length>0&&(e<0?e=0:e>=t.length&&(e=t.length-1),this.focusedChild_=e,t[e].el_.focus())}};H.registerComponent(`Menu`,Vs);var Hs=class extends H{constructor(e,t={}){super(e,t),this.menuButton_=new ss(e,t),this.menuButton_.controlText(this.controlText_),this.menuButton_.el_.setAttribute(`aria-haspopup`,`true`);let n=ss.prototype.buildCSSClass();this.menuButton_.el_.className=this.buildCSSClass()+` `+n,this.menuButton_.removeClass(`vjs-control`),this.addChild(this.menuButton_),this.update(),this.enabled_=!0;let r=e=>this.handleClick(e);this.handleMenuKeyUp_=e=>this.handleMenuKeyUp(e),this.on(this.menuButton_,`tap`,r),this.on(this.menuButton_,`click`,r),this.on(this.menuButton_,`keydown`,e=>this.handleKeyDown(e)),this.on(this.menuButton_,`mouseenter`,()=>{this.addClass(`vjs-hover`),this.menu.show(),$i(L.default,`keyup`,this.handleMenuKeyUp_)}),this.on(`mouseleave`,e=>this.handleMouseLeave(e)),this.on(`keydown`,e=>this.handleSubmenuKeyDown(e))}update(){let e=this.createMenu();this.menu&&(this.menu.dispose(),this.removeChild(this.menu)),this.menu=e,this.addChild(e),this.buttonPressed_=!1,this.menuButton_.el_.setAttribute(`aria-expanded`,`false`),this.items&&this.items.length<=this.hideThreshold_?(this.hide(),this.menu.contentEl_.removeAttribute(`role`)):(this.show(),this.menu.contentEl_.setAttribute(`role`,`menu`))}createMenu(){let e=new Vs(this.player_,{menuButton:this});if(this.hideThreshold_=0,this.options_.title){let t=V(`li`,{className:`vjs-menu-title`,textContent:Ea(this.options_.title),tabIndex:-1}),n=new H(this.player_,{el:t});e.addItem(n)}if(this.items=this.createItems(),this.items)for(let t=0;t{this.handleTracksChange.apply(this,e)},a=(...e)=>{this.handleSelectedLanguageChange.apply(this,e)};if(e.on([`loadstart`,`texttrackchange`],i),r.addEventListener(`change`,i),r.addEventListener(`selectedlanguagechange`,a),this.on(`dispose`,function(){e.off([`loadstart`,`texttrackchange`],i),r.removeEventListener(`change`,i),r.removeEventListener(`selectedlanguagechange`,a)}),r.onchange===void 0){let e;this.on([`tap`,`click`],function(){if(typeof I.default.Event!=`object`)try{e=new I.default.Event(`change`)}catch{}e||(e=L.default.createEvent(`Event`),e.initEvent(`change`,!0,!0)),r.dispatchEvent(e)})}this.handleTracksChange()}handleClick(e){let t=this.track,n=this.player_.textTracks();if(super.handleClick(e),n)for(let e=0;e-1&&r.mode===`showing`){n=!1;break}}n!==this.isSelected_&&this.selected(n)}handleSelectedLanguageChange(e){let t=this.player().textTracks(),n=!0;for(let e=0,r=t.length;e-1&&r.mode===`showing`){n=!1;break}}n&&(this.player_.cache_.selectedLanguage={enabled:!1})}handleLanguagechange(){this.$(`.vjs-menu-item-text`).textContent=this.player_.localize(this.options_.label),super.handleLanguagechange()}};H.registerComponent(`OffTextTrackMenuItem`,Ks);var qs=class extends Us{constructor(e,t={}){t.tracks=e.textTracks(),super(e,t)}createItems(e=[],t=Gs){let n;this.label_&&(n=`${this.label_} off`),e.push(new Ks(this.player_,{kinds:this.kinds_,kind:this.kind_,label:n})),this.hideThreshold_+=1;let r=this.player_.textTracks();Array.isArray(this.kinds_)||(this.kinds_=[this.kind_]);for(let n=0;n-1){let n=new t(this.player_,{track:i,kinds:this.kinds_,kind:this.kind_,selectable:!0,multiSelectable:!1});n.addClass(`vjs-${i.kind}-menu-item`),e.push(n)}}return e}};H.registerComponent(`TextTrackButton`,qs);var Js=class extends Ws{constructor(e,t){let n=t.track,r=t.cue,i=e.currentTime();t.selectable=!0,t.multiSelectable=!1,t.label=r.text,t.selected=r.startTime<=i&&i{this.items.forEach(e=>{e.selected(this.track_.activeCues[0]===e.cue)})}}buildCSSClass(){return`vjs-chapters-button ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-chapters-button ${super.buildWrapperCSSClass()}`}update(e){if(e&&e.track&&e.track.kind!==`chapters`)return;let t=this.findChaptersTrack();t===this.track_?(!this.items||t&&t.cues&&t.cues.length!==this.items.length)&&super.update():(this.setTrack(t),super.update())}setTrack(e){if(this.track_!==e){if(this.updateHandler_||=this.update.bind(this),this.track_){let e=this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);e&&e.removeEventListener(`load`,this.updateHandler_),this.track_.removeEventListener(`cuechange`,this.selectCurrentItem_),this.track_=null}if(this.track_=e,this.track_){this.track_.mode=`hidden`;let e=this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);e&&e.addEventListener(`load`,this.updateHandler_),this.track_.addEventListener(`cuechange`,this.selectCurrentItem_)}}}findChaptersTrack(){let e=this.player_.textTracks()||[];for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.kind===this.kind_)return n}}getMenuCaption(){return this.track_&&this.track_.label?this.track_.label:this.localize(Ea(this.kind_))}createMenu(){return this.options_.title=this.getMenuCaption(),super.createMenu()}createItems(){let e=[];if(!this.track_)return e;let t=this.track_.cues;if(!t)return e;for(let n=0,r=t.length;n-1&&(this.label_=`captions`,this.setIcon(`captions`)),this.menuButton_.controlText(Ea(this.label_))}buildCSSClass(){return`vjs-subs-caps-button ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-subs-caps-button ${super.buildWrapperCSSClass()}`}createItems(){let e=[];return!(this.player().tech_&&this.player().tech_.featuresNativeTextTracks)&&this.player().getChild(`textTrackSettings`)&&(e.push(new Qs(this.player_,{kind:this.label_})),this.hideThreshold_+=1),e=super.createItems(e,ec),e}};tc.prototype.kinds_=[`captions`,`subtitles`],tc.prototype.controlText_=`Subtitles`,H.registerComponent(`SubsCapsButton`,tc);var nc=class extends Ws{constructor(e,t){let n=t.track,r=e.audioTracks();t.label=n.label||n.language||`Unknown`,t.selected=n.enabled,super(e,t),this.track=n,this.addClass(`vjs-${n.kind}-menu-item`);let i=(...e)=>{this.handleTracksChange.apply(this,e)};r.addEventListener(`change`,i),this.on(`dispose`,()=>{r.removeEventListener(`change`,i)})}createEl(e,t,n){let r=super.createEl(e,t,n),i=r.querySelector(`.vjs-menu-item-text`);return[`main-desc`,`descriptions`].indexOf(this.options_.track.kind)>=0&&(i.appendChild(V(`span`,{className:`vjs-icon-placeholder`},{"aria-hidden":!0})),i.appendChild(V(`span`,{className:`vjs-control-text`,textContent:` `+this.localize(`Descriptions`)}))),r}handleClick(e){if(super.handleClick(e),this.track.enabled=!0,this.player_.tech_.featuresNativeAudioTracks){let e=this.player_.audioTracks();for(let t=0;tthis.update(e))}handleClick(e){super.handleClick(),this.player().playbackRate(this.rate)}update(e){this.selected(this.player().playbackRate()===this.rate)}};ic.prototype.contentElType=`button`,H.registerComponent(`PlaybackRateMenuItem`,ic);var ac=class extends Hs{constructor(e,t){super(e,t),this.menuButton_.el_.setAttribute(`aria-describedby`,this.labelElId_),this.updateVisibility(),this.updateLabel(),this.on(e,`loadstart`,e=>this.updateVisibility(e)),this.on(e,`ratechange`,e=>this.updateLabel(e)),this.on(e,`playbackrateschange`,e=>this.handlePlaybackRateschange(e))}createEl(){let e=super.createEl();return this.labelElId_=`vjs-playback-rate-value-label-`+this.id_,this.labelEl_=V(`div`,{className:`vjs-playback-rate-value`,id:this.labelElId_,textContent:`1x`}),e.appendChild(this.labelEl_),e}dispose(){this.labelEl_=null,super.dispose()}buildCSSClass(){return`vjs-playback-rate ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-playback-rate ${super.buildWrapperCSSClass()}`}createItems(){let e=this.playbackRates(),t=[];for(let n=e.length-1;n>=0;n--)t.push(new ic(this.player(),{rate:e[n]+`x`}));return t}handlePlaybackRateschange(e){this.update()}playbackRates(){let e=this.player();return e.playbackRates&&e.playbackRates()||[]}playbackRateSupported(){return this.player().tech_&&this.player().tech_.featuresPlaybackRate&&this.playbackRates()&&this.playbackRates().length>0}updateVisibility(e){this.playbackRateSupported()?this.removeClass(`vjs-hidden`):this.addClass(`vjs-hidden`)}updateLabel(e){this.playbackRateSupported()&&(this.labelEl_.textContent=this.player().playbackRate()+`x`)}};ac.prototype.controlText_=`Playback Rate`,H.registerComponent(`PlaybackRateMenuButton`,ac);var oc=class extends H{buildCSSClass(){return`vjs-spacer ${super.buildCSSClass()}`}createEl(e=`div`,t={},n={}){return t.className||=this.buildCSSClass(),super.createEl(e,t,n)}};H.registerComponent(`Spacer`,oc);var sc=class extends oc{buildCSSClass(){return`vjs-custom-control-spacer ${super.buildCSSClass()}`}createEl(){return super.createEl(`div`,{className:this.buildCSSClass(),textContent:`\xA0`})}};H.registerComponent(`CustomControlSpacer`,sc);var cc=class extends H{createEl(){return super.createEl(`div`,{className:`vjs-control-bar`,dir:`ltr`})}};cc.prototype.options_={children:[`playToggle`,`skipBackward`,`skipForward`,`volumePanel`,`currentTimeDisplay`,`timeDivider`,`durationDisplay`,`progressControl`,`liveDisplay`,`seekToLive`,`remainingTimeDisplay`,`customControlSpacer`,`playbackRateMenuButton`,`chaptersButton`,`descriptionsButton`,`subsCapsButton`,`audioTrackButton`,`pictureInPictureToggle`,`fullscreenToggle`]},H.registerComponent(`ControlBar`,cc);var lc=class extends Ka{constructor(e,t){super(e,t),this.on(e,`error`,e=>{this.open(e)})}buildCSSClass(){return`vjs-error-display ${super.buildCSSClass()}`}content(){let e=this.player().error();return e?this.localize(e.message):``}};lc.prototype.options_=Object.assign({},Ka.prototype.options_,{pauseOnOpen:!1,fillAlways:!0,temporary:!1,uncloseable:!0}),H.registerComponent(`ErrorDisplay`,lc);var uc=class extends H{constructor(e,t={}){super(e,t),this.el_.setAttribute(`aria-labelledby`,this.selectLabelledbyIds)}createEl(){return this.selectLabelledbyIds=[this.options_.legendId,this.options_.labelId].join(` `).trim(),V(`select`,{id:this.options_.id},{},this.options_.SelectOptions.map(e=>{let t=(this.options_.labelId?this.options_.labelId:`vjs-track-option-${Ki()}`)+`-`+e[1].replace(/\W+/g,``),n=V(`option`,{id:t,value:this.localize(e[0]),textContent:this.localize(e[1])});return n.setAttribute(`aria-labelledby`,`${this.selectLabelledbyIds} ${t}`),n}))}};H.registerComponent(`TextTrackSelect`,uc);var dc=class extends H{constructor(e,t={}){super(e,t);let n=V(`legend`,{textContent:this.localize(this.options_.legendText),id:this.options_.legendId});this.el().appendChild(n);let r=this.options_.selects;for(let t of r){let n=this.options_.selectConfigs[t],r=n.className,i=n.id.replace(`%s`,this.options_.id_),a=null,o=`vjs_select_${Ki()}`;if(this.options_.type===`colors`){a=V(`span`,{className:r});let e=V(`label`,{id:i,className:`vjs-label`,textContent:this.localize(n.label)});e.setAttribute(`for`,o),a.appendChild(e)}let s=new uc(e,{SelectOptions:n.options,legendId:this.options_.legendId,id:o,labelId:i});this.addChild(s),this.options_.type===`colors`&&(a.appendChild(s.el()),this.el().appendChild(a))}}createEl(){return V(`fieldset`,{className:this.options_.className})}};H.registerComponent(`TextTrackFieldset`,dc);var fc=class extends H{constructor(e,t={}){super(e,t);let n=this.options_.textTrackComponentid,r=new dc(e,{id_:n,legendId:`captions-text-legend-${n}`,legendText:this.localize(`Text`),className:`vjs-fg vjs-track-setting`,selects:this.options_.fieldSets[0],selectConfigs:this.options_.selectConfigs,type:`colors`});this.addChild(r);let i=new dc(e,{id_:n,legendId:`captions-background-${n}`,legendText:this.localize(`Text Background`),className:`vjs-bg vjs-track-setting`,selects:this.options_.fieldSets[1],selectConfigs:this.options_.selectConfigs,type:`colors`});this.addChild(i);let a=new dc(e,{id_:n,legendId:`captions-window-${n}`,legendText:this.localize(`Caption Area Background`),className:`vjs-window vjs-track-setting`,selects:this.options_.fieldSets[2],selectConfigs:this.options_.selectConfigs,type:`colors`});this.addChild(a)}createEl(){return V(`div`,{className:`vjs-track-settings-colors`})}};H.registerComponent(`TextTrackSettingsColors`,fc);var pc=class extends H{constructor(e,t={}){super(e,t);let n=this.options_.textTrackComponentid,r=new dc(e,{id_:n,legendId:`captions-font-size-${n}`,legendText:`Font Size`,className:`vjs-font-percent vjs-track-setting`,selects:this.options_.fieldSets[0],selectConfigs:this.options_.selectConfigs,type:`font`});this.addChild(r);let i=new dc(e,{id_:n,legendId:`captions-edge-style-${n}`,legendText:this.localize(`Text Edge Style`),className:`vjs-edge-style vjs-track-setting`,selects:this.options_.fieldSets[1],selectConfigs:this.options_.selectConfigs,type:`font`});this.addChild(i);let a=new dc(e,{id_:n,legendId:`captions-font-family-${n}`,legendText:this.localize(`Font Family`),className:`vjs-font-family vjs-track-setting`,selects:this.options_.fieldSets[2],selectConfigs:this.options_.selectConfigs,type:`font`});this.addChild(a)}createEl(){return V(`div`,{className:`vjs-track-settings-font`})}};H.registerComponent(`TextTrackSettingsFont`,pc);var mc=class extends H{constructor(e,t={}){super(e,t);let n=new ss(e,{controlText:this.localize(`restore all settings to the default values`),className:`vjs-default-button`});n.el().classList.remove(`vjs-control`,`vjs-button`),n.el().textContent=this.localize(`Reset`),this.addChild(n);let r=this.localize(`Done`),i=new ss(e,{controlText:r,className:`vjs-done-button`});i.el().classList.remove(`vjs-control`,`vjs-button`),i.el().textContent=r,this.addChild(i)}createEl(){return V(`div`,{className:`vjs-track-settings-controls`})}};H.registerComponent(`TrackSettingsControls`,mc);var hc=`vjs-text-track-settings`,gc=[`#000`,`Black`],_c=[`#00F`,`Blue`],vc=[`#0FF`,`Cyan`],yc=[`#0F0`,`Green`],bc=[`#F0F`,`Magenta`],xc=[`#F00`,`Red`],Sc=[`#FFF`,`White`],Cc=[`#FF0`,`Yellow`],wc=[`1`,`Opaque`],Tc=[`0.5`,`Semi-Transparent`],Ec=[`0`,`Transparent`],Dc={backgroundColor:{selector:`.vjs-bg-color > select`,id:`captions-background-color-%s`,label:`Color`,options:[gc,Sc,xc,yc,_c,Cc,bc,vc],className:`vjs-bg-color`},backgroundOpacity:{selector:`.vjs-bg-opacity > select`,id:`captions-background-opacity-%s`,label:`Opacity`,options:[wc,Tc,Ec],className:`vjs-bg-opacity vjs-opacity`},color:{selector:`.vjs-text-color > select`,id:`captions-foreground-color-%s`,label:`Color`,options:[Sc,gc,xc,yc,_c,Cc,bc,vc],className:`vjs-text-color`},edgeStyle:{selector:`.vjs-edge-style > select`,id:``,label:`Text Edge Style`,options:[[`none`,`None`],[`raised`,`Raised`],[`depressed`,`Depressed`],[`uniform`,`Uniform`],[`dropshadow`,`Drop shadow`]]},fontFamily:{selector:`.vjs-font-family > select`,id:``,label:`Font Family`,options:[[`proportionalSansSerif`,`Proportional Sans-Serif`],[`monospaceSansSerif`,`Monospace Sans-Serif`],[`proportionalSerif`,`Proportional Serif`],[`monospaceSerif`,`Monospace Serif`],[`casual`,`Casual`],[`script`,`Script`],[`small-caps`,`Small Caps`]]},fontPercent:{selector:`.vjs-font-percent > select`,id:``,label:`Font Size`,options:[[`0.50`,`50%`],[`0.75`,`75%`],[`1.00`,`100%`],[`1.25`,`125%`],[`1.50`,`150%`],[`1.75`,`175%`],[`2.00`,`200%`],[`3.00`,`300%`],[`4.00`,`400%`]],default:2,parser:e=>e===`1.00`?null:Number(e)},textOpacity:{selector:`.vjs-text-opacity > select`,id:`captions-foreground-opacity-%s`,label:`Opacity`,options:[wc,Tc],className:`vjs-text-opacity vjs-opacity`},windowColor:{selector:`.vjs-window-color > select`,id:`captions-window-color-%s`,label:`Color`,className:`vjs-window-color`},windowOpacity:{selector:`.vjs-window-opacity > select`,id:`captions-window-opacity-%s`,label:`Opacity`,options:[Ec,Tc,wc],className:`vjs-window-opacity vjs-opacity`}};Dc.windowColor.options=Dc.backgroundColor.options;function Oc(e,t){if(t&&(e=t(e)),e&&e!==`none`)return e}function kc(e,t){let n=e.options[e.options.selectedIndex].value;return Oc(n,t)}function Ac(e,t,n){if(t){for(let r=0;r{this.saveSettings(),this.close()}),this.on(this.$(`.vjs-default-button`),[`click`,`tap`],()=>{this.setDefaults(),this.updateDisplay()}),Er(Dc,e=>{this.on(this.$(e.selector),`change`,this.updateDisplay)})}dispose(){this.endDialog=null,super.dispose()}label(){return this.localize(`Caption Settings Dialog`)}description(){return this.localize(`Beginning of dialog window. Escape will cancel and close the window.`)}buildCSSClass(){return super.buildCSSClass()+` vjs-text-track-settings`}getValues(){return Dr(Dc,(e,t,n)=>{let r=kc(this.$(t.selector),t.parser);return r!==void 0&&(e[n]=r),e},{})}setValues(e){Er(Dc,(t,n)=>{Ac(this.$(t.selector),e[n],t.parser)})}setDefaults(){Er(Dc,e=>{let t=e.hasOwnProperty(`default`)?e.default:0;this.$(e.selector).selectedIndex=t})}restoreSettings(){let e;try{e=JSON.parse(I.default.localStorage.getItem(hc))}catch(e){B.warn(e)}e&&this.setValues(e)}saveSettings(){if(!this.options_.persistTextTrackSettings)return;let e=this.getValues();try{Object.keys(e).length?I.default.localStorage.setItem(hc,JSON.stringify(e)):I.default.localStorage.removeItem(hc)}catch(e){B.warn(e)}}updateDisplay(){let e=this.player_.getChild(`textTrackDisplay`);e&&e.updateDisplay()}handleLanguagechange(){this.fill(),this.renderModalComponents(this.player_),this.bindFunctionsToSelectsAndButtons()}};H.registerComponent(`TextTrackSettings`,jc);var Mc=class extends H{constructor(e,t){let n=t.ResizeObserver||I.default.ResizeObserver;t.ResizeObserver===null&&(n=!1);let r=Ar({createEl:!n,reportTouchActivity:!1},t);super(e,r),this.ResizeObserver=t.ResizeObserver||I.default.ResizeObserver,this.loadListener_=null,this.resizeObserver_=null,this.debouncedHandler_=ca(()=>{this.resizeHandler()},100,!1,this),n?(this.resizeObserver_=new this.ResizeObserver(this.debouncedHandler_),this.resizeObserver_.observe(e.el())):(this.loadListener_=()=>{if(!this.el_||!this.el_.contentWindow)return;let e=this.debouncedHandler_,t=this.unloadListener_=function(){ea(this,`resize`,e),ea(this,`unload`,t),t=null};$i(this.el_.contentWindow,`unload`,t),$i(this.el_.contentWindow,`resize`,e)},this.one(`load`,this.loadListener_))}createEl(){return super.createEl(`iframe`,{className:`vjs-resize-manager`,tabIndex:-1,title:this.localize(`No content`)},{"aria-hidden":`true`})}resizeHandler(){!this.player_||!this.player_.trigger||this.player_.trigger(`playerresize`)}dispose(){this.debouncedHandler_&&this.debouncedHandler_.cancel(),this.resizeObserver_&&(this.player_.el()&&this.resizeObserver_.unobserve(this.player_.el()),this.resizeObserver_.disconnect()),this.loadListener_&&this.off(`load`,this.loadListener_),this.el_&&this.el_.contentWindow&&this.unloadListener_&&this.unloadListener_.call(this.el_.contentWindow),this.ResizeObserver=null,this.resizeObserver=null,this.debouncedHandler_=null,this.loadListener_=null,super.dispose()}};H.registerComponent(`ResizeManager`,Mc);var Nc={trackingThreshold:20,liveTolerance:15},Pc=class extends H{constructor(e,t){let n=Ar(Nc,t,{createEl:!1});super(e,n),this.trackLiveHandler_=()=>this.trackLive_(),this.handlePlay_=e=>this.handlePlay(e),this.handleFirstTimeupdate_=e=>this.handleFirstTimeupdate(e),this.handleSeeked_=e=>this.handleSeeked(e),this.seekToLiveEdge_=e=>this.seekToLiveEdge(e),this.reset_(),this.on(this.player_,`durationchange`,e=>this.handleDurationchange(e)),this.on(this.player_,`canplay`,()=>this.toggleTracking())}trackLive_(){let e=this.player_.seekable();if(!e||!e.length)return;let t=Number(I.default.performance.now().toFixed(4)),n=this.lastTime_===-1?0:(t-this.lastTime_)/1e3;this.lastTime_=t,this.pastSeekEnd_=this.pastSeekEnd()+n;let r=this.liveCurrentTime(),i=this.player_.currentTime(),a=this.player_.paused()||this.seekedBehindLive_||Math.abs(r-i)>this.options_.liveTolerance;(!this.timeupdateSeen_||r===1/0)&&(a=!1),a!==this.behindLiveEdge_&&(this.behindLiveEdge_=a,this.trigger(`liveedgechange`))}handleDurationchange(){this.toggleTracking()}toggleTracking(){this.player_.duration()===1/0&&this.liveWindow()>=this.options_.trackingThreshold?(this.player_.options_.liveui&&this.player_.addClass(`vjs-liveui`),this.startTracking()):(this.player_.removeClass(`vjs-liveui`),this.stopTracking())}startTracking(){this.isTracking()||(this.timeupdateSeen_||=this.player_.hasStarted(),this.trackingInterval_=this.setInterval(this.trackLiveHandler_,aa),this.trackLive_(),this.on(this.player_,[`play`,`pause`],this.trackLiveHandler_),this.timeupdateSeen_?this.on(this.player_,`seeked`,this.handleSeeked_):(this.one(this.player_,`play`,this.handlePlay_),this.one(this.player_,`timeupdate`,this.handleFirstTimeupdate_)))}handleFirstTimeupdate(){this.timeupdateSeen_=!0,this.on(this.player_,`seeked`,this.handleSeeked_)}handleSeeked(){let e=Math.abs(this.liveCurrentTime()-this.player_.currentTime());this.seekedBehindLive_=this.nextSeekedFromUser_&&e>2,this.nextSeekedFromUser_=!1,this.trackLive_()}handlePlay(){this.one(this.player_,`timeupdate`,this.seekToLiveEdge_)}reset_(){this.lastTime_=-1,this.pastSeekEnd_=0,this.lastSeekEnd_=-1,this.behindLiveEdge_=!0,this.timeupdateSeen_=!1,this.seekedBehindLive_=!1,this.nextSeekedFromUser_=!1,this.clearInterval(this.trackingInterval_),this.trackingInterval_=null,this.off(this.player_,[`play`,`pause`],this.trackLiveHandler_),this.off(this.player_,`seeked`,this.handleSeeked_),this.off(this.player_,`play`,this.handlePlay_),this.off(this.player_,`timeupdate`,this.handleFirstTimeupdate_),this.off(this.player_,`timeupdate`,this.seekToLiveEdge_)}nextSeekedFromUser(){this.nextSeekedFromUser_=!0}stopTracking(){this.isTracking()&&(this.reset_(),this.trigger(`liveedgechange`))}seekableEnd(){let e=this.player_.seekable(),t=[],n=e?e.length:0;for(;n--;)t.push(e.end(n));return t.length?t.sort()[t.length-1]:1/0}seekableStart(){let e=this.player_.seekable(),t=[],n=e?e.length:0;for(;n--;)t.push(e.start(n));return t.length?t.sort()[0]:0}liveWindow(){let e=this.liveCurrentTime();return e===1/0?0:e-this.seekableStart()}isLive(){return this.isTracking()}atLiveEdge(){return!this.behindLiveEdge()}liveCurrentTime(){return this.pastSeekEnd()+this.seekableEnd()}pastSeekEnd(){let e=this.seekableEnd();return this.lastSeekEnd_!==-1&&e!==this.lastSeekEnd_&&(this.pastSeekEnd_=0),this.lastSeekEnd_=e,this.pastSeekEnd_}behindLiveEdge(){return this.behindLiveEdge_}isTracking(){return typeof this.trackingInterval_==`number`}seekToLiveEdge(){this.seekedBehindLive_=!1,!this.atLiveEdge()&&(this.nextSeekedFromUser_=!1,this.player_.currentTime(this.liveCurrentTime()))}dispose(){this.stopTracking(),super.dispose()}};H.registerComponent(`LiveTracker`,Pc);var Fc=class extends H{constructor(e,t){super(e,t),this.on(`statechanged`,e=>this.updateDom_()),this.updateDom_()}createEl(){return this.els={title:V(`div`,{className:`vjs-title-bar-title`,id:`vjs-title-bar-title-${Ki()}`}),description:V(`div`,{className:`vjs-title-bar-description`,id:`vjs-title-bar-description-${Ki()}`})},V(`div`,{className:`vjs-title-bar`},{},jr(this.els))}updateDom_(){let e=this.player_.tech_,t=e&&e.el_,n={title:`aria-labelledby`,description:`aria-describedby`};[`title`,`description`].forEach(e=>{let r=this.state[e],i=this.els[e],a=n[e];Di(i),r&&ui(i,r),t&&(t.removeAttribute(a),r&&t.setAttribute(a,i.id))}),this.state.title||this.state.description?this.show():this.hide()}update(e){this.setState(e)}dispose(){let e=this.player_.tech_,t=e&&e.el_;t&&(t.removeAttribute(`aria-labelledby`),t.removeAttribute(`aria-describedby`)),super.dispose(),this.els=null}};H.registerComponent(`TitleBar`,Fc);var Ic={initialDisplay:4e3,position:[],takeFocus:!1},Lc=class extends ss{constructor(e,t){t=Ar(Ic,t),super(e,t),this.controlText(t.controlText),this.hide(),this.on(this.player_,[`useractive`,`userinactive`],e=>{this.removeClass(`force-display`)})}buildCSSClass(){return`vjs-transient-button focus-visible ${this.options_.position.map(e=>`vjs-${e}`).join(` `)}`}createEl(){let e=V(`button`,{},{type:`button`,class:this.buildCSSClass()},V(`span`));return this.controlTextEl_=e.querySelector(`span`),e}show(){super.show(),this.addClass(`force-display`),this.options_.takeFocus&&this.el().focus({preventScroll:!0}),this.forceDisplayTimeout=this.player_.setTimeout(()=>{this.removeClass(`force-display`)},this.options_.initialDisplay)}hide(){this.removeClass(`force-display`),super.hide()}dispose(){this.player_.clearTimeout(this.forceDisplayTimeout),super.dispose()}};H.registerComponent(`TransientButton`,Lc);var Rc=e=>{let t=e.el();if(t.hasAttribute(`src`))return e.triggerSourceset(t.src),!0;let n=e.$$(`source`),r=[],i=``;if(!n.length)return!1;for(let e=0;e{let n={};for(let r=0;rBc([e.el(),I.default.HTMLMediaElement.prototype,I.default.Element.prototype,zc],`innerHTML`),Hc=function(e){let t=e.el();if(t.resetSourceWatch_)return;let n={},r=Vc(e),i=n=>(...r)=>{let i=n.apply(t,r);return Rc(e),i};[`append`,`appendChild`,`insertAdjacentHTML`].forEach(e=>{t[e]&&(n[e]=t[e],t[e]=i(n[e]))}),Object.defineProperty(t,`innerHTML`,Ar(r,{set:i(r.set)})),t.resetSourceWatch_=()=>{t.resetSourceWatch_=null,Object.keys(n).forEach(e=>{t[e]=n[e]}),Object.defineProperty(t,`innerHTML`,r)},e.one(`sourceset`,t.resetSourceWatch_)},Uc=Object.defineProperty({},`src`,{get(){return this.hasAttribute(`src`)?so(I.default.Element.prototype.getAttribute.call(this,`src`)):``},set(e){return I.default.Element.prototype.setAttribute.call(this,`src`,e),e}}),Wc=e=>Bc([e.el(),I.default.HTMLMediaElement.prototype,Uc],`src`),Gc=function(e){if(!e.featuresSourceset)return;let t=e.el();if(t.resetSourceset_)return;let n=Wc(e),r=t.setAttribute,i=t.load;Object.defineProperty(t,`src`,Ar(n,{set:r=>{let i=n.set.call(t,r);return e.triggerSourceset(t.src),i}})),t.setAttribute=(n,i)=>{let a=r.call(t,n,i);return/src/i.test(n)&&e.triggerSourceset(t.src),a},t.load=()=>{let n=i.call(t);return Rc(e)||(e.triggerSourceset(``),Hc(e)),n},t.currentSrc?e.triggerSourceset(t.currentSrc):Rc(e)||Hc(e),t.resetSourceset_=()=>{t.resetSourceset_=null,t.load=i,t.setAttribute=r,Object.defineProperty(t,`src`,n),t.resetSourceWatch_&&t.resetSourceWatch_()}},U=class e extends So{constructor(e,t){super(e,t);let n=e.source,r=!1;if(this.featuresVideoFrameCallback=this.featuresVideoFrameCallback&&this.el_.tagName===`VIDEO`,n&&(this.el_.currentSrc!==n.src||e.tag&&e.tag.initNetworkState_===3)?this.setSource(n):this.handleLateInit_(this.el_),e.enableSourceset&&this.setupSourcesetHandling_(),this.isScrubbing_=!1,this.el_.hasChildNodes()){let e=this.el_.childNodes,t=e.length,n=[];for(;t--;){let i=e[t];i.nodeName.toLowerCase()===`track`&&(this.featuresNativeTextTracks?(this.remoteTextTrackEls().addTrackElement_(i),this.remoteTextTracks().addTrack(i.track),this.textTracks().addTrack(i.track),!r&&!this.el_.hasAttribute(`crossorigin`)&&lo(i.src)&&(r=!0)):n.push(i))}for(let e=0;e{t=[];for(let n=0;ne.removeEventListener(`change`,n));let r=()=>{for(let e=0;e{e.removeEventListener(`change`,n),e.removeEventListener(`change`,r),e.addEventListener(`change`,r)}),this.on(`webkitendfullscreen`,()=>{e.removeEventListener(`change`,n),e.addEventListener(`change`,n),e.removeEventListener(`change`,r)})}overrideNative_(e,t){if(t!==this[`featuresNative${e}Tracks`])return;let n=e.toLowerCase();this[`${n}TracksListeners_`]&&Object.keys(this[`${n}TracksListeners_`]).forEach(e=>{this.el()[`${n}Tracks`].removeEventListener(e,this[`${n}TracksListeners_`][e])}),this[`featuresNative${e}Tracks`]=!t,this[`${n}TracksListeners_`]=null,this.proxyNativeTracksForType_(n)}overrideNativeAudioTracks(e){this.overrideNative_(`Audio`,e)}overrideNativeVideoTracks(e){this.overrideNative_(`Video`,e)}proxyNativeTracksForType_(e){let t=vo[e],n=this.el()[t.getterName],r=this[t.getterName]();if(!this[`featuresNative${t.capitalName}Tracks`]||!n||!n.addEventListener)return;let i={change:t=>{let n={type:`change`,target:r,currentTarget:r,srcElement:r};r.trigger(n),e===`text`&&this[yo.remoteText.getterName]().trigger(n)},addtrack(e){r.addTrack(e.track)},removetrack(e){r.removeTrack(e.track)}},a=function(){let e=[];for(let t=0;t{let t=i[e];n.addEventListener(e,t),this.on(`dispose`,r=>n.removeEventListener(e,t))}),this.on(`loadstart`,a),this.on(`dispose`,e=>this.off(`loadstart`,a))}proxyNativeTracks_(){vo.names.forEach(e=>{this.proxyNativeTracksForType_(e)})}createEl(){let t=this.options_.tag;if(!t||!(this.options_.playerElIngest||this.movingMediaElementInDOM)){if(t){let n=t.cloneNode(!0);t.parentNode&&t.parentNode.insertBefore(n,t),e.disposeMediaElement(t),t=n}else{t=L.default.createElement(`video`);let e=Ar({},this.options_.tag&&_i(this.options_.tag));(!$r||this.options_.nativeControlsForTouch!==!0)&&delete e.controls,gi(t,Object.assign(e,{id:this.options_.techId,class:`vjs-tech`}))}t.playerId=this.options_.playerId}this.options_.preload!==void 0&&yi(t,`preload`,this.options_.preload),this.options_.disablePictureInPicture!==void 0&&(t.disablePictureInPicture=this.options_.disablePictureInPicture);let n=[`loop`,`muted`,`playsinline`,`autoplay`];for(let e=0;e=2&&t.push(`loadeddata`),e.readyState>=3&&t.push(`canplay`),e.readyState>=4&&t.push(`canplaythrough`),this.ready(function(){t.forEach(function(e){this.trigger(e)},this)})}setScrubbing(e){this.isScrubbing_=e}scrubbing(){return this.isScrubbing_}setCurrentTime(e){try{this.isScrubbing_&&this.el_.fastSeek&&ni?this.el_.fastSeek(e):this.el_.currentTime=e}catch(e){B(e,`Video is not ready. (Video.js)`)}}duration(){if(this.el_.duration===1/0&&Ir&&Vr&&this.el_.currentTime===0){let e=()=>{this.el_.currentTime>0&&(this.el_.duration===1/0&&this.trigger(`durationchange`),this.off(`timeupdate`,e))};return this.on(`timeupdate`,e),NaN}return this.el_.duration||NaN}width(){return this.el_.offsetWidth}height(){return this.el_.offsetHeight}proxyWebkitFullscreen_(){if(!(`webkitDisplayingFullscreen`in this.el_))return;let e=function(){this.trigger(`fullscreenchange`,{isFullscreen:!1}),this.el_.controls&&!this.options_.nativeControlsForTouch&&this.controls()&&(this.el_.controls=!1)},t=function(){`webkitPresentationMode`in this.el_&&this.el_.webkitPresentationMode!==`picture-in-picture`&&(this.one(`webkitendfullscreen`,e),this.trigger(`fullscreenchange`,{isFullscreen:!0,nativeIOSFullscreen:!0}))};this.on(`webkitbeginfullscreen`,t),this.on(`dispose`,()=>{this.off(`webkitbeginfullscreen`,t),this.off(`webkitendfullscreen`,e)})}supportsFullScreen(){return typeof this.el_.webkitEnterFullScreen==`function`}enterFullScreen(){let e=this.el_;if(e.paused&&e.networkState<=e.HAVE_METADATA)Ha(this.el_.play()),this.setTimeout(function(){e.pause();try{e.webkitEnterFullScreen()}catch(e){this.trigger(`fullscreenerror`,e)}},0);else try{e.webkitEnterFullScreen()}catch(e){this.trigger(`fullscreenerror`,e)}}exitFullScreen(){if(!this.el_.webkitDisplayingFullscreen){this.trigger(`fullscreenerror`,Error(`The video is not fullscreen`));return}this.el_.webkitExitFullScreen()}requestPictureInPicture(){return this.el_.requestPictureInPicture()}requestVideoFrameCallback(e){return this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.requestVideoFrameCallback(e):super.requestVideoFrameCallback(e)}cancelVideoFrameCallback(e){this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.cancelVideoFrameCallback(e):super.cancelVideoFrameCallback(e)}src(e){if(e===void 0)return this.el_.src;this.setSrc(e)}addSourceElement(e,t){if(!e)return B.error(`Invalid source URL.`),!1;let n={src:e};t&&(n.type=t);let r=V(`source`,{},n);return this.el_.appendChild(r),!0}removeSourceElement(e){if(!e)return B.error(`Source URL is required to remove the source element.`),!1;let t=this.el_.querySelectorAll(`source`);for(let n of t)if(n.src===e)return this.el_.removeChild(n),!0;return B.warn(`No matching source element found with src: ${e}`),!1}reset(){e.resetMediaElement(this.el_)}currentSrc(){return this.currentSource_?this.currentSource_.src:this.el_.currentSrc}setControls(e){this.el_.controls=!!e}addTextTrack(e,t,n){return this.featuresNativeTextTracks?this.el_.addTextTrack(e,t,n):super.addTextTrack(e,t,n)}createRemoteTextTrack(e){if(!this.featuresNativeTextTracks)return super.createRemoteTextTrack(e);let t=L.default.createElement(`track`);return e.kind&&(t.kind=e.kind),e.label&&(t.label=e.label),(e.language||e.srclang)&&(t.srclang=e.language||e.srclang),e.default&&(t.default=e.default),e.id&&(t.id=e.id),e.src&&(t.src=e.src),t}addRemoteTextTrack(e,t){let n=super.addRemoteTextTrack(e,t);return this.featuresNativeTextTracks&&this.el().appendChild(n),n}removeRemoteTextTrack(e){if(super.removeRemoteTextTrack(e),this.featuresNativeTextTracks){let t=this.$$(`track`),n=t.length;for(;n--;)(e===t[n]||e===t[n].track)&&this.el().removeChild(t[n])}}getVideoPlaybackQuality(){if(typeof this.el().getVideoPlaybackQuality==`function`)return this.el().getVideoPlaybackQuality();let e={};return this.el().webkitDroppedFrameCount!==void 0&&this.el().webkitDecodedFrameCount!==void 0&&(e.droppedVideoFrames=this.el().webkitDroppedFrameCount,e.totalVideoFrames=this.el().webkitDecodedFrameCount),I.default.performance&&(e.creationTime=I.default.performance.now()),e}};Mr(U,`TEST_VID`,function(){if(!oi())return;let e=L.default.createElement(`video`),t=L.default.createElement(`track`);return t.kind=`captions`,t.srclang=`en`,t.label=`English`,e.appendChild(t),e}),U.isSupported=function(){try{U.TEST_VID.volume=.5}catch{return!1}return!!(U.TEST_VID&&U.TEST_VID.canPlayType)},U.canPlayType=function(e){return U.TEST_VID.canPlayType(e)},U.canPlaySource=function(e,t){return U.canPlayType(e.type)},U.canControlVolume=function(){try{let e=U.TEST_VID.volume;U.TEST_VID.volume=e/2+.1;let t=e!==U.TEST_VID.volume;return t&&ti?(I.default.setTimeout(()=>{U&&U.prototype&&(U.prototype.featuresVolumeControl=e!==U.TEST_VID.volume)}),!1):t}catch{return!1}},U.canMuteVolume=function(){try{let e=U.TEST_VID.muted;return U.TEST_VID.muted=!e,U.TEST_VID.muted?yi(U.TEST_VID,`muted`,`muted`):bi(U.TEST_VID,`muted`,`muted`),e!==U.TEST_VID.muted}catch{return!1}},U.canControlPlaybackRate=function(){if(Ir&&Vr&&Ur<58)return!1;try{let e=U.TEST_VID.playbackRate;return U.TEST_VID.playbackRate=e/2+.1,e!==U.TEST_VID.playbackRate}catch{return!1}},U.canOverrideAttributes=function(){try{let e=()=>{};Object.defineProperty(L.default.createElement(`video`),`src`,{get:e,set:e}),Object.defineProperty(L.default.createElement(`audio`),`src`,{get:e,set:e}),Object.defineProperty(L.default.createElement(`video`),`innerHTML`,{get:e,set:e}),Object.defineProperty(L.default.createElement(`audio`),`innerHTML`,{get:e,set:e})}catch{return!1}return!0},U.supportsNativeTextTracks=function(){return ni||ti&&Vr},U.supportsNativeVideoTracks=function(){return!!(U.TEST_VID&&U.TEST_VID.videoTracks)},U.supportsNativeAudioTracks=function(){return!!(U.TEST_VID&&U.TEST_VID.audioTracks)},U.Events=[`loadstart`,`suspend`,`abort`,`error`,`emptied`,`stalled`,`loadedmetadata`,`loadeddata`,`canplay`,`canplaythrough`,`playing`,`waiting`,`seeking`,`seeked`,`ended`,`durationchange`,`timeupdate`,`progress`,`play`,`pause`,`ratechange`,`resize`,`volumechange`],[[`featuresMuteControl`,`canMuteVolume`],[`featuresPlaybackRate`,`canControlPlaybackRate`],[`featuresSourceset`,`canOverrideAttributes`],[`featuresNativeTextTracks`,`supportsNativeTextTracks`],[`featuresNativeVideoTracks`,`supportsNativeVideoTracks`],[`featuresNativeAudioTracks`,`supportsNativeAudioTracks`]].forEach(function([e,t]){Mr(U.prototype,e,()=>U[t](),!0)}),U.prototype.featuresVolumeControl=U.canControlVolume(),U.prototype.movingMediaElementInDOM=!ti,U.prototype.featuresFullscreenResize=!0,U.prototype.featuresProgressEvents=!0,U.prototype.featuresTimeupdateEvents=!0,U.prototype.featuresVideoFrameCallback=!!(U.TEST_VID&&U.TEST_VID.requestVideoFrameCallback),U.disposeMediaElement=function(e){if(e){for(e.parentNode&&e.parentNode.removeChild(e);e.hasChildNodes();)e.removeChild(e.firstChild);e.removeAttribute(`src`),typeof e.load==`function`&&(function(){try{e.load()}catch{}})()}},U.resetMediaElement=function(e){if(!e)return;let t=e.querySelectorAll(`source`),n=t.length;for(;n--;)e.removeChild(t[n]);e.removeAttribute(`src`),typeof e.load==`function`&&(function(){try{e.load()}catch{}})()},[`muted`,`defaultMuted`,`autoplay`,`controls`,`loop`,`playsinline`].forEach(function(e){U.prototype[e]=function(){return this.el_[e]||this.el_.hasAttribute(e)}}),[`muted`,`defaultMuted`,`autoplay`,`loop`,`playsinline`].forEach(function(e){U.prototype[`set`+Ea(e)]=function(t){this.el_[e]=t,t?this.el_.setAttribute(e,e):this.el_.removeAttribute(e)}}),[`paused`,`currentTime`,`buffered`,`volume`,`poster`,`preload`,`error`,`seeking`,`seekable`,`ended`,`playbackRate`,`defaultPlaybackRate`,`disablePictureInPicture`,`played`,`networkState`,`readyState`,`videoWidth`,`videoHeight`,`crossOrigin`].forEach(function(e){U.prototype[e]=function(){return this.el_[e]}}),[`volume`,`src`,`poster`,`preload`,`playbackRate`,`defaultPlaybackRate`,`disablePictureInPicture`,`crossOrigin`].forEach(function(e){U.prototype[`set`+Ea(e)]=function(t){this.el_[e]=t}}),[`pause`,`load`,`play`].forEach(function(e){U.prototype[e]=function(){return this.el_[e]()}}),So.withSourceHandlers(U),U.nativeSourceHandler={},U.nativeSourceHandler.canPlayType=function(e){try{return U.TEST_VID.canPlayType(e)}catch{return``}},U.nativeSourceHandler.canHandleSource=function(e,t){if(e.type)return U.nativeSourceHandler.canPlayType(e.type);if(e.src){let t=co(e.src);return U.nativeSourceHandler.canPlayType(`video/${t}`)}return``},U.nativeSourceHandler.handleSource=function(e,t,n){t.setSrc(e.src)},U.nativeSourceHandler.dispose=function(){},U.registerSourceHandler(U.nativeSourceHandler),So.registerTech(`Html5`,U);var Kc=[`progress`,`abort`,`suspend`,`emptied`,`stalled`,`loadedmetadata`,`loadeddata`,`timeupdate`,`resize`,`volumechange`,`texttrackchange`],qc={canplay:`CanPlay`,canplaythrough:`CanPlayThrough`,playing:`Playing`,seeked:`Seeked`},Jc=[`tiny`,`xsmall`,`small`,`medium`,`large`,`xlarge`,`huge`],Yc={};Jc.forEach(e=>{Yc[e]=`vjs-layout-${e.charAt(0)===`x`?`x-${e.substring(1)}`:e}`});var Xc={tiny:210,xsmall:320,small:425,medium:768,large:1440,xlarge:2560,huge:1/0},Zc=class e extends H{constructor(t,n,r){if(t.id=t.id||n.id||`vjs_video_${Ki()}`,n=Object.assign(e.getTagSettings(t),n),n.initChildren=!1,n.createEl=!1,n.evented=!1,n.reportTouchActivity=!1,!n.language){let e=t.closest(`[lang]`);e&&(n.language=e.getAttribute(`lang`))}if(super(null,n,r),this.boundDocumentFullscreenChange_=e=>this.documentFullscreenChange_(e),this.boundFullWindowOnEscKey_=e=>this.fullWindowOnEscKey(e),this.boundUpdateStyleEl_=e=>this.updateStyleEl_(e),this.boundApplyInitTime_=e=>this.applyInitTime_(e),this.boundUpdateCurrentBreakpoint_=e=>this.updateCurrentBreakpoint_(e),this.boundHandleTechClick_=e=>this.handleTechClick_(e),this.boundHandleTechDoubleClick_=e=>this.handleTechDoubleClick_(e),this.boundHandleTechTouchStart_=e=>this.handleTechTouchStart_(e),this.boundHandleTechTouchMove_=e=>this.handleTechTouchMove_(e),this.boundHandleTechTouchEnd_=e=>this.handleTechTouchEnd_(e),this.boundHandleTechTap_=e=>this.handleTechTap_(e),this.boundUpdatePlayerHeightOnAudioOnlyMode_=e=>this.updatePlayerHeightOnAudioOnlyMode_(e),this.isFullscreen_=!1,this.log=Cr(this.id_),this.fsApi_=gr,this.isPosterFromTech_=!1,this.queuedCallbacks_=[],this.isReady_=!1,this.hasStarted_=!1,this.userActive_=!1,this.debugEnabled_=!1,this.audioOnlyMode_=!1,this.audioPosterMode_=!1,this.audioOnlyCache_={controlBarHeight:null,playerHeight:null,hiddenChildren:[]},!this.options_||!this.options_.techOrder||!this.options_.techOrder.length)throw Error(`No techOrder specified. Did you overwrite videojs.options instead of just changing the properties you want to override?`);if(this.tag=t,this.tagAttributes=t&&_i(t),this.language(this.options_.language),n.languages){let e={};Object.getOwnPropertyNames(n.languages).forEach(function(t){e[t.toLowerCase()]=n.languages[t]}),this.languages_=e}else this.languages_=e.prototype.options_.languages;this.resetCache_(),this.poster_=n.poster||``,this.controls_=!!n.controls,t.controls=!1,t.removeAttribute(`controls`),this.changingSrc_=!1,this.playCallbacks_=[],this.playTerminatedQueue_=[],t.hasAttribute(`autoplay`)?this.autoplay(!0):this.autoplay(this.options_.autoplay),n.plugins&&Object.keys(n.plugins).forEach(e=>{if(typeof this[e]!=`function`)throw Error(`plugin "${e}" does not exist`)}),this.scrubbing_=!1,this.el_=this.createEl(),Sa(this,{eventBusKey:`el_`}),this.fsApi_.requestFullscreen&&($i(L.default,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),this.on(this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_)),this.fluid_&&this.on([`playerreset`,`resize`],this.boundUpdateStyleEl_);let i=Ar(this.options_);if(n.plugins&&Object.keys(n.plugins).forEach(e=>{this[e](n.plugins[e])}),n.debug&&this.debug(!0),this.options_.playerOptions=i,this.middleware_=[],this.playbackRates(n.playbackRates),n.experimentalSvgIcons){let e=new I.default.DOMParser().parseFromString(Go,`image/svg+xml`);if(e.querySelector(`parsererror`))B.warn(`Failed to load SVG Icons. Falling back to Font Icons.`),this.options_.experimentalSvgIcons=null;else{let t=e.documentElement;t.style.display=`none`,this.el_.appendChild(t),this.addClass(`vjs-svg-icons-enabled`)}}this.initChildren(),this.isAudio(t.nodeName.toLowerCase()===`audio`),this.controls()?this.addClass(`vjs-controls-enabled`):this.addClass(`vjs-controls-disabled`),this.el_.setAttribute(`role`,`region`),this.isAudio()?this.el_.setAttribute(`aria-label`,this.localize(`Audio Player`)):this.el_.setAttribute(`aria-label`,this.localize(`Video Player`)),this.isAudio()&&this.addClass(`vjs-audio`),n.spatialNavigation&&n.spatialNavigation.enabled&&(this.spatialNavigation=new Yo(this),this.addClass(`vjs-spatial-navigation-enabled`)),$r&&this.addClass(`vjs-touch-enabled`),ti||this.addClass(`vjs-workinghover`),e.players[this.id_]=this;let a=ur.split(`.`)[0];this.addClass(`vjs-v${a}`),this.userActive(!0),this.reportUserActivity(),this.one(`play`,e=>this.listenForUserActivity_(e)),this.on(`keydown`,e=>this.handleKeyDown(e)),this.on(`languagechange`,e=>this.handleLanguagechange(e)),this.breakpoints(this.options_.breakpoints),this.responsive(this.options_.responsive),this.on(`ready`,()=>{this.audioPosterMode(this.options_.audioPosterMode),this.audioOnlyMode(this.options_.audioOnlyMode)})}dispose(){this.trigger(`dispose`),this.off(`dispose`),ea(L.default,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),ea(L.default,`keydown`,this.boundFullWindowOnEscKey_),this.styleEl_&&this.styleEl_.parentNode&&(this.styleEl_.parentNode.removeChild(this.styleEl_),this.styleEl_=null),e.players[this.id_]=null,this.tag&&this.tag.player&&(this.tag.player=null),this.el_&&this.el_.player&&(this.el_.player=null),this.tech_&&(this.tech_.dispose(),this.isPosterFromTech_=!1,this.poster_=``),this.playerElIngest_&&=null,this.tag&&=null,Lo(this),bo.names.forEach(e=>{let t=bo[e],n=this[t.getterName]();n&&n.off&&n.off()}),super.dispose({restoreEl:this.options_.restoreEl})}createEl(){let e=this.tag,t,n=this.playerElIngest_=e.parentNode&&e.parentNode.hasAttribute&&e.parentNode.hasAttribute(`data-vjs-player`),r=this.tag.tagName.toLowerCase()===`video-js`;n?t=this.el_=e.parentNode:r||(t=this.el_=super.createEl(`div`));let i=_i(e);if(r){for(t=this.el_=e,e=this.tag=L.default.createElement(`video`);t.children.length;)e.appendChild(t.firstChild);fi(t,`video-js`)||pi(t,`video-js`),t.appendChild(e),n=this.playerElIngest_=t,Object.keys(t).forEach(n=>{try{e[n]=t[n]}catch{}})}e.setAttribute(`tabindex`,`-1`),i.tabindex=`-1`,Vr&&qr&&(e.setAttribute(`role`,`application`),i.role=`application`),e.removeAttribute(`width`),e.removeAttribute(`height`),`width`in i&&delete i.width,`height`in i&&delete i.height,Object.getOwnPropertyNames(i).forEach(function(n){r&&n===`class`||t.setAttribute(n,i[n]),r&&e.setAttribute(n,i[n])}),e.playerId=e.id,e.id+=`_html5_api`,e.className=`vjs-tech`,e.player=t.player=this,this.addClass(`vjs-paused`);let a=[`IS_SMART_TV`,`IS_TIZEN`,`IS_WEBOS`,`IS_ANDROID`,`IS_IPAD`,`IS_IPHONE`,`IS_CHROMECAST_RECEIVER`].filter(e=>ri[e]).map(e=>`vjs-device-`+e.substring(3).toLowerCase().replace(/\_/g,`-`));if(this.addClass(...a),I.default.VIDEOJS_NO_DYNAMIC_STYLE!==!0){this.styleEl_=Hi(`vjs-styles-dimensions`);let e=Mi(`.vjs-styles-defaults`),t=Mi(`head`);t.insertBefore(this.styleEl_,e?e.nextSibling:t.firstChild)}this.fill_=!1,this.fluid_=!1,this.width(this.options_.width),this.height(this.options_.height),this.fill(this.options_.fill),this.fluid(this.options_.fluid),this.aspectRatio(this.options_.aspectRatio),this.crossOrigin(this.options_.crossOrigin||this.options_.crossorigin);let o=e.getElementsByTagName(`a`);for(let e=0;e{this.on([`playerreset`,`resize`],this.boundUpdateStyleEl_)})):this.removeClass(`vjs-fluid`),this.updateStyleEl_()}fill(e){if(e===void 0)return!!this.fill_;this.fill_=!!e,e?(this.addClass(`vjs-fill`),this.fluid(!1)):this.removeClass(`vjs-fill`)}aspectRatio(e){if(e===void 0)return this.aspectRatio_;if(!/^\d+\:\d+$/.test(e))throw Error(`Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.`);this.aspectRatio_=e,this.fluid(!0),this.updateStyleEl_()}updateStyleEl_(){if(I.default.VIDEOJS_NO_DYNAMIC_STYLE===!0){let e=typeof this.width_==`number`?this.width_:this.options_.width,t=typeof this.height_==`number`?this.height_:this.options_.height,n=this.tech_&&this.tech_.el();n&&(e>=0&&(n.width=e),t>=0&&(n.height=t));return}let e,t,n,r;n=this.aspectRatio_!==void 0&&this.aspectRatio_!==`auto`?this.aspectRatio_:this.videoWidth()>0?this.videoWidth()+`:`+this.videoHeight():`16:9`;let i=n.split(`:`),a=i[1]/i[0];e=this.width_===void 0?this.height_===void 0?this.videoWidth()||300:this.height_/a:this.width_,t=this.height_===void 0?e*a:this.height_,r=/^[^a-zA-Z]/.test(this.id())?`dimensions-`+this.id():this.id()+`-dimensions`,this.addClass(r),Ui(this.styleEl_,` .${r} { width: ${e}px; height: ${t}px; } .${r}.vjs-fluid:not(.vjs-audio-only-mode) { padding-top: ${a*100}%; } `)}loadTech_(e,t){this.tech_&&this.unloadTech_();let n=Ea(e),r=e.charAt(0).toLowerCase()+e.slice(1);n!==`Html5`&&this.tag&&(So.getTech(`Html5`).disposeMediaElement(this.tag),this.tag.player=null,this.tag=null),this.techName_=n,this.isReady_=!1;let i=this.autoplay();(typeof this.autoplay()==`string`||this.autoplay()===!0&&this.options_.normalizeAutoplay)&&(i=!1);let a={source:t,autoplay:i,nativeControlsForTouch:this.options_.nativeControlsForTouch,playerId:this.id(),techId:`${this.id()}_${r}_api`,playsinline:this.options_.playsinline,preload:this.options_.preload,loop:this.options_.loop,disablePictureInPicture:this.options_.disablePictureInPicture,muted:this.options_.muted,poster:this.poster(),language:this.language(),playerElIngest:this.playerElIngest_||!1,"vtt.js":this.options_[`vtt.js`],canOverridePoster:!!this.options_.techCanOverridePoster,enableSourceset:this.options_.enableSourceset};bo.names.forEach(e=>{let t=bo[e];a[t.getterName]=this[t.privateName]}),Object.assign(a,this.options_[n]),Object.assign(a,this.options_[r]),Object.assign(a,this.options_[e.toLowerCase()]),this.tag&&(a.tag=this.tag),t&&t.src===this.cache_.src&&this.cache_.currentTime>0&&(a.startTime=this.cache_.currentTime);let o=So.getTech(e);if(!o)throw Error(`No Tech named '${n}' exists! '${n}' should be registered using videojs.registerTech()'`);this.tech_=new o(a),this.tech_.ready(oa(this,this.handleTechReady_),!0),Wa.jsonToTextTracks(this.textTracksJson_||[],this.tech_),Kc.forEach(e=>{this.on(this.tech_,e,t=>this[`handleTech${Ea(e)}_`](t))}),Object.keys(qc).forEach(e=>{this.on(this.tech_,e,t=>{if(this.tech_.playbackRate()===0&&this.tech_.seeking()){this.queuedCallbacks_.push({callback:this[`handleTech${qc[e]}_`].bind(this),event:t});return}this[`handleTech${qc[e]}_`](t)})}),this.on(this.tech_,`loadstart`,e=>this.handleTechLoadStart_(e)),this.on(this.tech_,`sourceset`,e=>this.handleTechSourceset_(e)),this.on(this.tech_,`waiting`,e=>this.handleTechWaiting_(e)),this.on(this.tech_,`ended`,e=>this.handleTechEnded_(e)),this.on(this.tech_,`seeking`,e=>this.handleTechSeeking_(e)),this.on(this.tech_,`play`,e=>this.handleTechPlay_(e)),this.on(this.tech_,`pause`,e=>this.handleTechPause_(e)),this.on(this.tech_,`durationchange`,e=>this.handleTechDurationChange_(e)),this.on(this.tech_,`fullscreenchange`,(e,t)=>this.handleTechFullscreenChange_(e,t)),this.on(this.tech_,`fullscreenerror`,(e,t)=>this.handleTechFullscreenError_(e,t)),this.on(this.tech_,`enterpictureinpicture`,e=>this.handleTechEnterPictureInPicture_(e)),this.on(this.tech_,`leavepictureinpicture`,e=>this.handleTechLeavePictureInPicture_(e)),this.on(this.tech_,`error`,e=>this.handleTechError_(e)),this.on(this.tech_,`posterchange`,e=>this.handleTechPosterChange_(e)),this.on(this.tech_,`textdata`,e=>this.handleTechTextData_(e)),this.on(this.tech_,`ratechange`,e=>this.handleTechRateChange_(e)),this.on(this.tech_,`loadedmetadata`,this.boundUpdateStyleEl_),this.usingNativeControls(this.techGet_(`controls`)),this.controls()&&!this.usingNativeControls()&&this.addTechControlsListeners_(),this.tech_.el().parentNode!==this.el()&&(n!==`Html5`||!this.tag)&&di(this.tech_.el(),this.el()),this.tag&&=(this.tag.player=null,null)}unloadTech_(){bo.names.forEach(e=>{let t=bo[e];this[t.privateName]=this[t.getterName]()}),this.textTracksJson_=Wa.textTracksToJson(this.tech_),this.isReady_=!1,this.tech_.dispose(),this.tech_=!1,this.isPosterFromTech_&&(this.poster_=``,this.trigger(`posterchange`)),this.isPosterFromTech_=!1}tech(e){return e===void 0&&B.warn(`Using the tech directly can be dangerous. I hope you know what you're doing. See https://github.com/videojs/video.js/issues/2617 for more info. `),this.tech_}version(){return{"video.js":ur}}addTechControlsListeners_(){this.removeTechControlsListeners_(),this.on(this.tech_,`click`,this.boundHandleTechClick_),this.on(this.tech_,`dblclick`,this.boundHandleTechDoubleClick_),this.on(this.tech_,`touchstart`,this.boundHandleTechTouchStart_),this.on(this.tech_,`touchmove`,this.boundHandleTechTouchMove_),this.on(this.tech_,`touchend`,this.boundHandleTechTouchEnd_),this.on(this.tech_,`tap`,this.boundHandleTechTap_)}removeTechControlsListeners_(){this.off(this.tech_,`tap`,this.boundHandleTechTap_),this.off(this.tech_,`touchstart`,this.boundHandleTechTouchStart_),this.off(this.tech_,`touchmove`,this.boundHandleTechTouchMove_),this.off(this.tech_,`touchend`,this.boundHandleTechTouchEnd_),this.off(this.tech_,`click`,this.boundHandleTechClick_),this.off(this.tech_,`dblclick`,this.boundHandleTechDoubleClick_)}handleTechReady_(){this.triggerReady(),this.cache_.volume&&this.techCall_(`setVolume`,this.cache_.volume),this.handleTechPosterChange_(),this.handleTechDurationChange_()}handleTechLoadStart_(){this.removeClass(`vjs-ended`,`vjs-seeking`),this.error(null),this.handleTechDurationChange_(),this.paused()&&this.hasStarted(!1),this.trigger(`loadstart`),this.manualAutoplay_(this.autoplay()===!0&&this.options_.normalizeAutoplay?`play`:this.autoplay())}manualAutoplay_(e){if(!this.tech_||typeof e!=`string`)return;let t=()=>{let e=this.muted();this.muted(!0);let t=()=>{this.muted(e)};this.playTerminatedQueue_.push(t);let n=this.play();if(Va(n))return n.catch(e=>{throw t(),Error(`Rejection at manualAutoplay. Restoring muted value. ${e||``}`)})},n;if(e===`any`&&!this.muted()?(n=this.play(),Va(n)&&(n=n.catch(t))):n=e===`muted`&&!this.muted()?t():this.play(),Va(n))return n.then(()=>{this.trigger({type:`autoplay-success`,autoplay:e})}).catch(()=>{this.trigger({type:`autoplay-failure`,autoplay:e})})}updateSourceCaches_(e=``){let t=e,n=``;typeof t!=`string`&&(t=e.src,n=e.type),this.cache_.source=this.cache_.source||{},this.cache_.sources=this.cache_.sources||[],t&&!n&&(n=Ho(this,t)),this.cache_.source=Ar({},e,{src:t,type:n});let r=this.cache_.sources.filter(e=>e.src&&e.src===t),i=[],a=this.$$(`source`),o=[];for(let e=0;ethis.updateSourceCaches_(e),n=this.currentSource().src,r=e.src;n&&!/^blob:/.test(n)&&/^blob:/.test(r)&&(!this.lastSource_||this.lastSource_.tech!==r&&this.lastSource_.player!==n)&&(t=()=>{}),t(r),e.src||this.tech_.any([`sourceset`,`loadstart`],e=>{if(e.type===`sourceset`)return;let t=this.techGet_(`currentSrc`);this.lastSource_.tech=t,this.updateSourceCaches_(t)})}this.lastSource_={player:this.currentSource().src,tech:e.src},this.trigger({src:e.src,type:`sourceset`})}hasStarted(e){if(e===void 0)return this.hasStarted_;e!==this.hasStarted_&&(this.hasStarted_=e,this.hasStarted_?this.addClass(`vjs-has-started`):this.removeClass(`vjs-has-started`))}handleTechPlay_(){this.removeClass(`vjs-ended`,`vjs-paused`),this.addClass(`vjs-playing`),this.hasStarted(!0),this.trigger(`play`)}handleTechRateChange_(){this.tech_.playbackRate()>0&&this.cache_.lastPlaybackRate===0&&(this.queuedCallbacks_.forEach(e=>e.callback(e.event)),this.queuedCallbacks_=[]),this.cache_.lastPlaybackRate=this.tech_.playbackRate(),this.trigger(`ratechange`)}handleTechWaiting_(){this.addClass(`vjs-waiting`),this.trigger(`waiting`);let e=this.currentTime(),t=()=>{e!==this.currentTime()&&(this.removeClass(`vjs-waiting`),this.off(`timeupdate`,t))};this.on(`timeupdate`,t)}handleTechCanPlay_(){this.removeClass(`vjs-waiting`),this.trigger(`canplay`)}handleTechCanPlayThrough_(){this.removeClass(`vjs-waiting`),this.trigger(`canplaythrough`)}handleTechPlaying_(){this.removeClass(`vjs-waiting`),this.trigger(`playing`)}handleTechSeeking_(){this.addClass(`vjs-seeking`),this.trigger(`seeking`)}handleTechSeeked_(){this.removeClass(`vjs-seeking`,`vjs-ended`),this.trigger(`seeked`)}handleTechPause_(){this.removeClass(`vjs-playing`),this.addClass(`vjs-paused`),this.trigger(`pause`)}handleTechEnded_(){this.addClass(`vjs-ended`),this.removeClass(`vjs-waiting`),this.options_.loop?(this.currentTime(0),this.play()):this.paused()||this.pause(),this.trigger(`ended`)}handleTechDurationChange_(){this.duration(this.techGet_(`duration`))}handleTechClick_(e){this.controls_&&(this.options_===void 0||this.options_.userActions===void 0||this.options_.userActions.click===void 0||this.options_.userActions.click!==!1)&&(this.options_!==void 0&&this.options_.userActions!==void 0&&typeof this.options_.userActions.click==`function`?this.options_.userActions.click.call(this,e):this.paused()?Ha(this.play()):this.pause())}handleTechDoubleClick_(e){this.controls_&&(Array.prototype.some.call(this.$$(`.vjs-control-bar, .vjs-modal-dialog`),t=>t.contains(e.target))||(this.options_===void 0||this.options_.userActions===void 0||this.options_.userActions.doubleClick===void 0||this.options_.userActions.doubleClick!==!1)&&(this.options_!==void 0&&this.options_.userActions!==void 0&&typeof this.options_.userActions.doubleClick==`function`?this.options_.userActions.doubleClick.call(this,e):this.isInPictureInPicture()&&!L.default.pictureInPictureElement?this.exitPictureInPicture():this.isFullscreen()?this.exitFullscreen():this.requestFullscreen()))}handleTechTap_(){this.userActive(!this.userActive())}handleTechTouchStart_(){this.userWasActive=this.userActive()}handleTechTouchMove_(){this.userWasActive&&this.reportUserActivity()}handleTechTouchEnd_(e){e.cancelable&&e.preventDefault()}toggleFullscreenClass_(){this.isFullscreen()?this.addClass(`vjs-fullscreen`):this.removeClass(`vjs-fullscreen`)}documentFullscreenChange_(e){let t=e.target.player;if(t&&t!==this)return;let n=this.el(),r=L.default[this.fsApi_.fullscreenElement]===n;!r&&n.matches&&(r=n.matches(`:`+this.fsApi_.fullscreen)),this.isFullscreen(r)}handleTechFullscreenChange_(e,t){t&&(t.nativeIOSFullscreen&&(this.addClass(`vjs-ios-native-fs`),this.tech_.one(`webkitendfullscreen`,()=>{this.removeClass(`vjs-ios-native-fs`)})),this.isFullscreen(t.isFullscreen))}handleTechFullscreenError_(e,t){this.trigger(`fullscreenerror`,t)}togglePictureInPictureClass_(){this.isInPictureInPicture()?this.addClass(`vjs-picture-in-picture`):this.removeClass(`vjs-picture-in-picture`)}handleTechEnterPictureInPicture_(e){this.isInPictureInPicture(!0)}handleTechLeavePictureInPicture_(e){this.isInPictureInPicture(!1)}handleTechError_(){let e=this.tech_.error();e&&this.error(e)}handleTechTextData_(){let e=null;arguments.length>1&&(e=arguments[1]),this.trigger(`textdata`,e)}getCache(){return this.cache_}resetCache_(){this.cache_={currentTime:0,initTime:0,inactivityTimeout:this.options_.inactivityTimeout,duration:NaN,lastVolume:1,lastPlaybackRate:this.defaultPlaybackRate(),media:null,src:``,source:{},sources:[],playbackRates:[],volume:1}}techCall_(e,t){this.ready(function(){if(e in No)return Ao(this.middleware_,this.tech_,e,t);if(e in Po)return jo(this.middleware_,this.tech_,e,t);try{this.tech_&&this.tech_[e](t)}catch(e){throw B(e),e}},!0)}techGet_(e){if(!(!this.tech_||!this.tech_.isReady_)){if(e in Mo)return ko(this.middleware_,this.tech_,e);if(e in Po)return jo(this.middleware_,this.tech_,e);try{return this.tech_[e]()}catch(t){throw this.tech_[e]===void 0?(B(`Video.js: ${e} method not defined for ${this.techName_} playback technology.`,t),t):t.name===`TypeError`?(B(`Video.js: ${e} unavailable on ${this.techName_} playback technology element.`,t),this.tech_.isReady_=!1,t):(B(t),t)}}}play(){return new Promise(e=>{this.play_(e)})}play_(e=Ha){this.playCallbacks_.push(e);let t=!!(!this.changingSrc_&&(this.src()||this.currentSrc())),n=!!(ni||ti);if(this.waitToPlay_&&=(this.off([`ready`,`loadstart`],this.waitToPlay_),null),!this.isReady_||!t){this.waitToPlay_=e=>{this.play_()},this.one([`ready`,`loadstart`],this.waitToPlay_),!t&&n&&this.load();return}let r=this.techGet_(`play`);n&&this.hasClass(`vjs-ended`)&&this.resetProgressBar_(),r===null?this.runPlayTerminatedQueue_():this.runPlayCallbacks_(r)}runPlayTerminatedQueue_(){let e=this.playTerminatedQueue_.slice(0);this.playTerminatedQueue_=[],e.forEach(function(e){e()})}runPlayCallbacks_(e){let t=this.playCallbacks_.slice(0);this.playCallbacks_=[],this.playTerminatedQueue_=[],t.forEach(function(t){t(e)})}pause(){this.techCall_(`pause`)}paused(){return this.techGet_(`paused`)!==!1}played(){return this.techGet_(`played`)||Ma(0,0)}scrubbing(e){if(e===void 0)return this.scrubbing_;this.scrubbing_=!!e,this.techCall_(`setScrubbing`,this.scrubbing_),e?this.addClass(`vjs-scrubbing`):this.removeClass(`vjs-scrubbing`)}currentTime(e){if(e===void 0)return this.cache_.currentTime=this.techGet_(`currentTime`)||0,this.cache_.currentTime;if(e<0&&(e=0),!this.isReady_||this.changingSrc_||!this.tech_||!this.tech_.isReady_){this.cache_.initTime=e,this.off(`canplay`,this.boundApplyInitTime_),this.one(`canplay`,this.boundApplyInitTime_);return}this.techCall_(`setCurrentTime`,e),this.cache_.initTime=0,isFinite(e)&&(this.cache_.currentTime=Number(e))}applyInitTime_(){this.currentTime(this.cache_.initTime)}duration(e){if(e===void 0)return this.cache_.duration===void 0?NaN:this.cache_.duration;e=parseFloat(e),e<0&&(e=1/0),e!==this.cache_.duration&&(this.cache_.duration=e,e===1/0?this.addClass(`vjs-live`):this.removeClass(`vjs-live`),isNaN(e)||this.trigger(`durationchange`))}remainingTime(){return this.duration()-this.currentTime()}remainingTimeDisplay(){return Math.floor(this.duration())-Math.floor(this.currentTime())}buffered(){let e=this.techGet_(`buffered`);return(!e||!e.length)&&(e=Ma(0,0)),e}seekable(){let e=this.techGet_(`seekable`);return(!e||!e.length)&&(e=Ma(0,0)),e}seeking(){return this.techGet_(`seeking`)}ended(){return this.techGet_(`ended`)}networkState(){return this.techGet_(`networkState`)}readyState(){return this.techGet_(`readyState`)}bufferedPercent(){return za(this.buffered(),this.duration())}bufferedEnd(){let e=this.buffered(),t=this.duration(),n=e.end(e.length-1);return n>t&&(n=t),n}volume(e){let t;if(e!==void 0){t=Math.max(0,Math.min(1,e)),this.cache_.volume=t,this.techCall_(`setVolume`,t),t>0&&this.lastVolume_(t);return}return t=parseFloat(this.techGet_(`volume`)),isNaN(t)?1:t}muted(e){if(e!==void 0){this.techCall_(`setMuted`,e);return}return this.techGet_(`muted`)||!1}defaultMuted(e){return e!==void 0&&this.techCall_(`setDefaultMuted`,e),this.techGet_(`defaultMuted`)||!1}lastVolume_(e){if(e!==void 0&&e!==0){this.cache_.lastVolume=e;return}return this.cache_.lastVolume}supportsFullScreen(){return this.techGet_(`supportsFullScreen`)||!1}isFullscreen(e){if(e!==void 0){let t=this.isFullscreen_;this.isFullscreen_=!!e,this.isFullscreen_!==t&&this.fsApi_.prefixed&&this.trigger(`fullscreenchange`),this.toggleFullscreenClass_();return}return this.isFullscreen_}requestFullscreen(e){this.isInPictureInPicture()&&this.exitPictureInPicture();let t=this;return new Promise((n,r)=>{function i(){t.off(`fullscreenerror`,o),t.off(`fullscreenchange`,a)}function a(){i(),n()}function o(e,t){i(),r(t)}t.one(`fullscreenchange`,a),t.one(`fullscreenerror`,o);let s=t.requestFullscreenHelper_(e);s&&(s.then(i,i),s.then(n,r))})}requestFullscreenHelper_(e){let t;if(this.fsApi_.prefixed||(t=this.options_.fullscreen&&this.options_.fullscreen.options||{},e!==void 0&&(t=e)),this.fsApi_.requestFullscreen){let e=this.el_[this.fsApi_.requestFullscreen](t);return e&&e.then(()=>this.isFullscreen(!0),()=>this.isFullscreen(!1)),e}else this.tech_.supportsFullScreen()&&!this.options_.preferFullWindow?this.techCall_(`enterFullScreen`):this.enterFullWindow()}exitFullscreen(){let e=this;return new Promise((t,n)=>{function r(){e.off(`fullscreenerror`,a),e.off(`fullscreenchange`,i)}function i(){r(),t()}function a(e,t){r(),n(t)}e.one(`fullscreenchange`,i),e.one(`fullscreenerror`,a);let o=e.exitFullscreenHelper_();o&&(o.then(r,r),o.then(t,n))})}exitFullscreenHelper_(){if(this.fsApi_.requestFullscreen){let e=L.default[this.fsApi_.exitFullscreen]();return e&&Ha(e.then(()=>this.isFullscreen(!1))),e}else this.tech_.supportsFullScreen()&&!this.options_.preferFullWindow?this.techCall_(`exitFullScreen`):this.exitFullWindow()}enterFullWindow(){this.isFullscreen(!0),this.isFullWindow=!0,this.docOrigOverflow=L.default.documentElement.style.overflow,$i(L.default,`keydown`,this.boundFullWindowOnEscKey_),L.default.documentElement.style.overflow=`hidden`,pi(L.default.body,`vjs-full-window`),this.trigger(`enterFullWindow`)}fullWindowOnEscKey(e){e.key===`Escape`&&this.isFullscreen()===!0&&(this.isFullWindow?this.exitFullWindow():this.exitFullscreen())}exitFullWindow(){this.isFullscreen(!1),this.isFullWindow=!1,ea(L.default,`keydown`,this.boundFullWindowOnEscKey_),L.default.documentElement.style.overflow=this.docOrigOverflow,mi(L.default.body,`vjs-full-window`),this.trigger(`exitFullWindow`)}disablePictureInPicture(e){if(e===void 0)return this.techGet_(`disablePictureInPicture`);this.techCall_(`setDisablePictureInPicture`,e),this.options_.disablePictureInPicture=e,this.trigger(`disablepictureinpicturechanged`)}isInPictureInPicture(e){if(e!==void 0){this.isInPictureInPicture_=!!e,this.togglePictureInPictureClass_();return}return!!this.isInPictureInPicture_}requestPictureInPicture(){if(this.options_.enableDocumentPictureInPicture&&I.default.documentPictureInPicture){let e=L.default.createElement(this.el().tagName);return e.classList=this.el().classList,e.classList.add(`vjs-pip-container`),this.posterImage&&e.appendChild(this.posterImage.el().cloneNode(!0)),this.titleBar&&e.appendChild(this.titleBar.el().cloneNode(!0)),e.appendChild(V(`p`,{className:`vjs-pip-text`},{},this.localize(`Playing in picture-in-picture`))),I.default.documentPictureInPicture.requestWindow({width:this.videoWidth(),height:this.videoHeight()}).then(t=>(Fi(t),this.el_.parentNode.insertBefore(e,this.el_),t.document.body.appendChild(this.el_),t.document.body.classList.add(`vjs-pip-window`),this.player_.isInPictureInPicture(!0),this.player_.trigger({type:`enterpictureinpicture`,pipWindow:t}),t.addEventListener(`pagehide`,t=>{let n=t.target.querySelector(`.video-js`);e.parentNode.replaceChild(n,e),this.player_.isInPictureInPicture(!1),this.player_.trigger(`leavepictureinpicture`)}),t))}return`pictureInPictureEnabled`in L.default&&this.disablePictureInPicture()===!1?this.techGet_(`requestPictureInPicture`):Promise.reject(`No PiP mode is available`)}exitPictureInPicture(){if(I.default.documentPictureInPicture&&I.default.documentPictureInPicture.window)return I.default.documentPictureInPicture.window.close(),Promise.resolve();if(`pictureInPictureEnabled`in L.default)return L.default.exitPictureInPicture()}handleKeyDown(e){let{userActions:t}=this.options_;!t||!t.hotkeys||(e=>{let t=e.tagName.toLowerCase();return e.isContentEditable?!0:t===`input`?[`button`,`checkbox`,`hidden`,`radio`,`reset`,`submit`].indexOf(e.type)===-1:[`textarea`].indexOf(t)!==-1})(this.el_.ownerDocument.activeElement)||(typeof t.hotkeys==`function`?t.hotkeys.call(this,e):this.handleHotkeys(e))}handleHotkeys(e){let{fullscreenKey:t=t=>e.key.toLowerCase()===`f`,muteKey:n=t=>e.key.toLowerCase()===`m`,playPauseKey:r=t=>e.key.toLowerCase()===`k`||e.key.toLowerCase()===` `}=this.options_.userActions?this.options_.userActions.hotkeys:{};if(t.call(this,e)){e.preventDefault(),e.stopPropagation();let t=H.getComponent(`FullscreenToggle`);L.default[this.fsApi_.fullscreenEnabled]!==!1&&t.prototype.handleClick.call(this,e)}else n.call(this,e)?(e.preventDefault(),e.stopPropagation(),H.getComponent(`MuteToggle`).prototype.handleClick.call(this,e)):r.call(this,e)&&(e.preventDefault(),e.stopPropagation(),H.getComponent(`PlayToggle`).prototype.handleClick.call(this,e))}canPlayType(e){let t;for(let n=0,r=this.options_.techOrder;n[e,So.getTech(e)]).filter(([e,t])=>t?t.isSupported():(B.error(`The "${e}" tech is undefined. Skipped browser support check for that tech.`),!1)),n=function(e,t,n){let r;return e.some(e=>t.some(t=>{if(r=n(e,t),r)return!0})),r},r,i=e=>(t,n)=>e(n,t),a=([e,t],n)=>{if(t.canPlaySource(n,this.options_[e.toLowerCase()]))return{source:n,tech:e}};return r=this.options_.sourceOrder?n(e,t,i(a)):n(t,e,a),r||!1}handleSrc_(e,t){if(e===void 0)return this.cache_.src||``;this.resetRetryOnError_&&this.resetRetryOnError_();let n=Uo(e);if(!n.length){this.setTimeout(function(){this.error({code:4,message:this.options_.notSupportedMessage})},0);return}if(this.changingSrc_=!0,t||(this.cache_.sources=n),this.updateSourceCaches_(n[0]),Do(this,n[0],(e,r)=>{if(this.middleware_=r,t||(this.cache_.sources=n),this.updateSourceCaches_(e),this.src_(e)){if(n.length>1)return this.handleSrc_(n.slice(1));this.changingSrc_=!1,this.setTimeout(function(){this.error({code:4,message:this.options_.notSupportedMessage})},0),this.triggerReady();return}Oo(r,this.tech_)}),n.length>1){let e=()=>{this.error(null),this.handleSrc_(n.slice(1),!0)},t=()=>{this.off(`error`,e)};this.one(`error`,e),this.one(`playing`,t),this.resetRetryOnError_=()=>{this.off(`error`,e),this.off(`playing`,t)}}}src(e){return this.handleSrc_(e,!1)}src_(e){let t=this.selectSource([e]);return t?Da(t.tech,this.techName_)?(this.ready(function(){this.tech_.constructor.prototype.hasOwnProperty(`setSource`)?this.techCall_(`setSource`,e):this.techCall_(`src`,e.src),this.changingSrc_=!1},!0),!1):(this.changingSrc_=!0,this.loadTech_(t.tech,t.source),this.tech_.ready(()=>{this.changingSrc_=!1}),!1):!0}addSourceElement(e,t){return this.tech_?this.tech_.addSourceElement(e,t):!1}removeSourceElement(e){return this.tech_?this.tech_.removeSourceElement(e):!1}load(){if(this.tech_&&this.tech_.vhs){this.src(this.currentSource());return}this.techCall_(`load`)}reset(){this.paused()?this.doReset_():Ha(this.play().then(()=>this.doReset_()))}doReset_(){this.tech_&&this.tech_.clearTracks(`text`),this.removeClass(`vjs-playing`),this.addClass(`vjs-paused`),this.resetCache_(),this.poster(``),this.loadTech_(this.options_.techOrder[0],null),this.techCall_(`reset`),this.resetControlBarUI_(),this.error(null),this.titleBar&&this.titleBar.update({title:void 0,description:void 0}),pa(this)&&this.trigger(`playerreset`)}resetControlBarUI_(){this.resetProgressBar_(),this.resetPlaybackRate_(),this.resetVolumeBar_()}resetProgressBar_(){this.currentTime(0);let{currentTimeDisplay:e,durationDisplay:t,progressControl:n,remainingTimeDisplay:r}=this.controlBar||{},{seekBar:i}=n||{};e&&e.updateContent(),t&&t.updateContent(),r&&r.updateContent(),i&&(i.update(),i.loadProgressBar&&i.loadProgressBar.update())}resetPlaybackRate_(){this.playbackRate(this.defaultPlaybackRate()),this.handleTechRateChange_()}resetVolumeBar_(){this.volume(1),this.trigger(`volumechange`)}currentSources(){let e=this.currentSource(),t=[];return Object.keys(e).length!==0&&t.push(e),this.cache_.sources||t}currentSource(){return this.cache_.source||{}}currentSrc(){return this.currentSource()&&this.currentSource().src||``}currentType(){return this.currentSource()&&this.currentSource().type||``}preload(e){if(e!==void 0){this.techCall_(`setPreload`,e),this.options_.preload=e;return}return this.techGet_(`preload`)}autoplay(e){if(e===void 0)return this.options_.autoplay||!1;let t;typeof e==`string`&&/(any|play|muted)/.test(e)||e===!0&&this.options_.normalizeAutoplay?(this.options_.autoplay=e,this.manualAutoplay_(typeof e==`string`?e:`play`),t=!1):e?this.options_.autoplay=!0:this.options_.autoplay=!1,t=t===void 0?this.options_.autoplay:t,this.tech_&&this.techCall_(`setAutoplay`,t)}playsinline(e){return e!==void 0&&(this.techCall_(`setPlaysinline`,e),this.options_.playsinline=e),this.techGet_(`playsinline`)}loop(e){if(e!==void 0){this.techCall_(`setLoop`,e),this.options_.loop=e;return}return this.techGet_(`loop`)}poster(e){if(e===void 0)return this.poster_;e||=``,e!==this.poster_&&(this.poster_=e,this.techCall_(`setPoster`,e),this.isPosterFromTech_=!1,this.trigger(`posterchange`))}handleTechPosterChange_(){if((!this.poster_||this.options_.techCanOverridePoster)&&this.tech_&&this.tech_.poster){let e=this.tech_.poster()||``;e!==this.poster_&&(this.poster_=e,this.isPosterFromTech_=!0,this.trigger(`posterchange`))}}controls(e){if(e===void 0)return!!this.controls_;e=!!e,this.controls_!==e&&(this.controls_=e,this.usingNativeControls()&&this.techCall_(`setControls`,e),this.controls_?(this.removeClass(`vjs-controls-disabled`),this.addClass(`vjs-controls-enabled`),this.trigger(`controlsenabled`),this.usingNativeControls()||this.addTechControlsListeners_()):(this.removeClass(`vjs-controls-enabled`),this.addClass(`vjs-controls-disabled`),this.trigger(`controlsdisabled`),this.usingNativeControls()||this.removeTechControlsListeners_()))}usingNativeControls(e){if(e===void 0)return!!this.usingNativeControls_;e=!!e,this.usingNativeControls_!==e&&(this.usingNativeControls_=e,this.usingNativeControls_?(this.addClass(`vjs-using-native-controls`),this.trigger(`usingnativecontrols`)):(this.removeClass(`vjs-using-native-controls`),this.trigger(`usingcustomcontrols`)))}error(e){if(e===void 0)return this.error_||null;if(fr(`beforeerror`).forEach(t=>{let n=t(this,e);if(!(Or(n)&&!Array.isArray(n)||typeof n==`string`||typeof n==`number`||n===null)){this.log.error(`please return a value that MediaError expects in beforeerror hooks`);return}e=n}),this.options_.suppressNotSupportedError&&e&&e.code===4){let t=function(){this.error(e)};this.options_.suppressNotSupportedError=!1,this.any([`click`,`touchstart`],t),this.one(`loadstart`,function(){this.off([`click`,`touchstart`],t)});return}if(e===null){this.error_=null,this.removeClass(`vjs-error`),this.errorDisplay&&this.errorDisplay.close();return}this.error_=new Ba(e),this.addClass(`vjs-error`),B.error(`(CODE:${this.error_.code} ${Ba.errorTypes[this.error_.code]})`,this.error_.message,this.error_),this.trigger(`error`),fr(`error`).forEach(e=>e(this,this.error_))}reportUserActivity(e){this.userActivity_=!0}userActive(e){if(e===void 0)return this.userActive_;if(e=!!e,e!==this.userActive_){if(this.userActive_=e,this.userActive_){this.userActivity_=!0,this.removeClass(`vjs-user-inactive`),this.addClass(`vjs-user-active`),this.trigger(`useractive`);return}this.tech_&&this.tech_.one(`mousemove`,function(e){e.stopPropagation(),e.preventDefault()}),this.userActivity_=!1,this.removeClass(`vjs-user-active`),this.addClass(`vjs-user-inactive`),this.trigger(`userinactive`)}}listenForUserActivity_(){let e,t,n,r=oa(this,this.reportUserActivity),i=function(e){(e.screenX!==t||e.screenY!==n)&&(t=e.screenX,n=e.screenY,r())},a=function(){r(),this.clearInterval(e),e=this.setInterval(r,250)},o=function(t){r(),this.clearInterval(e)};this.on(`mousedown`,a),this.on(`mousemove`,i),this.on(`mouseup`,o),this.on(`mouseleave`,o);let s=this.getChild(`controlBar`);s&&!ti&&!Ir&&(s.on(`mouseenter`,function(e){this.player().options_.inactivityTimeout!==0&&(this.player().cache_.inactivityTimeout=this.player().options_.inactivityTimeout),this.player().options_.inactivityTimeout=0}),s.on(`mouseleave`,function(e){this.player().options_.inactivityTimeout=this.player().cache_.inactivityTimeout})),this.on(`keydown`,r),this.on(`keyup`,r);let c;this.setInterval(function(){if(!this.userActivity_)return;this.userActivity_=!1,this.userActive(!0),this.clearTimeout(c);let e=this.options_.inactivityTimeout;e<=0||(c=this.setTimeout(function(){this.userActivity_||this.userActive(!1)},e))},250)}playbackRate(e){if(e!==void 0){this.techCall_(`setPlaybackRate`,e);return}return this.tech_&&this.tech_.featuresPlaybackRate?this.cache_.lastPlaybackRate||this.techGet_(`playbackRate`):1}defaultPlaybackRate(e){return e===void 0?this.tech_&&this.tech_.featuresPlaybackRate?this.techGet_(`defaultPlaybackRate`):1:this.techCall_(`setDefaultPlaybackRate`,e)}isAudio(e){if(e!==void 0){this.isAudio_=!!e;return}return!!this.isAudio_}updatePlayerHeightOnAudioOnlyMode_(){let e=this.getChild(`ControlBar`);!e||this.audioOnlyCache_.controlBarHeight===e.currentHeight()||(this.audioOnlyCache_.controlBarHeight=e.currentHeight(),this.height(this.audioOnlyCache_.controlBarHeight))}enableAudioOnlyUI_(){this.addClass(`vjs-audio-only-mode`);let e=this.children(),t=this.getChild(`ControlBar`),n=t&&t.currentHeight();e.forEach(e=>{e!==t&&e.el_&&!e.hasClass(`vjs-hidden`)&&(e.hide(),this.audioOnlyCache_.hiddenChildren.push(e))}),this.audioOnlyCache_.playerHeight=this.currentHeight(),this.audioOnlyCache_.controlBarHeight=n,this.on(`playerresize`,this.boundUpdatePlayerHeightOnAudioOnlyMode_),this.height(n),this.trigger(`audioonlymodechange`)}disableAudioOnlyUI_(){this.removeClass(`vjs-audio-only-mode`),this.off(`playerresize`,this.boundUpdatePlayerHeightOnAudioOnlyMode_),this.audioOnlyCache_.hiddenChildren.forEach(e=>e.show()),this.height(this.audioOnlyCache_.playerHeight),this.trigger(`audioonlymodechange`)}audioOnlyMode(e){if(typeof e!=`boolean`||e===this.audioOnlyMode_)return this.audioOnlyMode_;if(this.audioOnlyMode_=e,e){let e=[];return this.isInPictureInPicture()&&e.push(this.exitPictureInPicture()),this.isFullscreen()&&e.push(this.exitFullscreen()),this.audioPosterMode()&&e.push(this.audioPosterMode(!1)),Promise.all(e).then(()=>this.enableAudioOnlyUI_())}return Promise.resolve().then(()=>this.disableAudioOnlyUI_())}enablePosterModeUI_(){(this.tech_&&this.tech_).hide(),this.addClass(`vjs-audio-poster-mode`),this.trigger(`audiopostermodechange`)}disablePosterModeUI_(){(this.tech_&&this.tech_).show(),this.removeClass(`vjs-audio-poster-mode`),this.trigger(`audiopostermodechange`)}audioPosterMode(e){return typeof e!=`boolean`||e===this.audioPosterMode_?this.audioPosterMode_:(this.audioPosterMode_=e,e?this.audioOnlyMode()?this.audioOnlyMode(!1).then(()=>{this.enablePosterModeUI_()}):Promise.resolve().then(()=>{this.enablePosterModeUI_()}):Promise.resolve().then(()=>{this.disablePosterModeUI_()}))}addTextTrack(e,t,n){if(this.tech_)return this.tech_.addTextTrack(e,t,n)}addRemoteTextTrack(e,t){if(this.tech_)return this.tech_.addRemoteTextTrack(e,t)}removeRemoteTextTrack(e={}){let{track:t}=e;if(t||=e,this.tech_)return this.tech_.removeRemoteTextTrack(t)}getVideoPlaybackQuality(){return this.techGet_(`getVideoPlaybackQuality`)}videoWidth(){return this.tech_&&this.tech_.videoWidth&&this.tech_.videoWidth()||0}videoHeight(){return this.tech_&&this.tech_.videoHeight&&this.tech_.videoHeight()||0}language(e){if(e===void 0)return this.language_;this.language_!==String(e).toLowerCase()&&(this.language_=String(e).toLowerCase(),pa(this)&&this.trigger(`languagechange`))}languages(){return Ar(e.prototype.options_.languages,this.languages_)}toJSON(){let e=Ar(this.options_),t=e.tracks;e.tracks=[];for(let n=0;n{this.removeChild(n)}),n.open(),n}updateCurrentBreakpoint_(){if(!this.responsive())return;let e=this.currentBreakpoint(),t=this.currentWidth();for(let n=0;nthis.addRemoteTextTrack(e,!1)),this.titleBar&&this.titleBar.update({title:l,description:a||r||``}),this.ready(t)}getMedia(){if(!this.cache_.media){let e=this.poster(),t={src:this.currentSources(),textTracks:Array.prototype.map.call(this.remoteTextTracks(),e=>({kind:e.kind,label:e.label,language:e.language,src:e.src}))};return e&&(t.poster=e,t.artwork=[{src:t.poster,type:Vo(t.poster)}]),t}return Ar(this.cache_.media)}static getTagSettings(e){let t={sources:[],tracks:[]},n=_i(e),r=n[`data-setup`];if(fi(e,`vjs-fill`)&&(n.fill=!0),fi(e,`vjs-fluid`)&&(n.fluid=!0),r!==null)try{Object.assign(n,JSON.parse(r||`{}`))}catch(e){B.error(`data-setup`,e)}if(Object.assign(t,n),e.hasChildNodes()){let n=e.childNodes;for(let e=0,r=n.length;etypeof e==`number`)&&(this.cache_.playbackRates=e,this.trigger(`playbackrateschange`))}};Zc.prototype.videoTracks=()=>{},Zc.prototype.audioTracks=()=>{},Zc.prototype.textTracks=()=>{},Zc.prototype.remoteTextTracks=()=>{},Zc.prototype.remoteTextTrackEls=()=>{},bo.names.forEach(function(e){let t=bo[e];Zc.prototype[t.getterName]=function(){return this.tech_?this.tech_[t.getterName]():(this[t.privateName]=this[t.privateName]||new t.ListClass,this[t.privateName])}}),Zc.prototype.crossorigin=Zc.prototype.crossOrigin,Zc.players={};var Qc=I.default.navigator;Zc.prototype.options_={techOrder:So.defaultTechOrder_,html5:{},enableSourceset:!0,inactivityTimeout:2e3,playbackRates:[],liveui:!1,children:[`mediaLoader`,`posterImage`,`titleBar`,`textTrackDisplay`,`loadingSpinner`,`bigPlayButton`,`liveTracker`,`controlBar`,`errorDisplay`,`textTrackSettings`,`resizeManager`],language:Qc&&(Qc.languages&&Qc.languages[0]||Qc.userLanguage||Qc.language)||`en`,languages:{},notSupportedMessage:`No compatible source was found for this media.`,normalizeAutoplay:!1,fullscreen:{options:{navigationUI:`hide`}},breakpoints:{},responsive:!1,audioOnlyMode:!1,audioPosterMode:!1,spatialNavigation:{enabled:!1,horizontalSeek:!1},enableSmoothSeeking:!1,disableSeekWhileScrubbingOnMobile:!1,disableSeekWhileScrubbingOnSTV:!1},Kc.forEach(function(e){Zc.prototype[`handleTech${Ea(e)}_`]=function(){return this.trigger(e)}}),H.registerComponent(`Player`,Zc);var $c=`plugin`,el=`activePlugins_`,tl={},nl=e=>tl.hasOwnProperty(e),rl=e=>nl(e)?tl[e]:void 0,il=(e,t)=>{e[el]=e[el]||{},e[el][t]=!0},al=(e,t,n)=>{let r=(n?`before`:``)+`pluginsetup`;e.trigger(r,t),e.trigger(r+`:`+t.name,t)},ol=function(e,t){let n=function(){al(this,{name:e,plugin:t,instance:null},!0);let n=t.apply(this,arguments);return il(this,e),al(this,{name:e,plugin:t,instance:n}),n};return Object.keys(t).forEach(function(e){n[e]=t[e]}),n},sl=(e,t)=>(t.prototype.name=e,function(...n){al(this,{name:e,plugin:t,instance:null},!0);let r=new t(this,...n);return this[e]=()=>r,al(this,r.getEventHash()),r}),cl=class e{constructor(t){if(this.constructor===e)throw Error(`Plugin must be sub-classed; not directly instantiated.`);this.player=t,this.log||=this.player.log.createLogger(this.name),Sa(this),delete this.trigger,wa(this,this.constructor.defaultState),il(t,this.name),this.dispose=this.dispose.bind(this),t.on(`dispose`,this.dispose)}version(){return this.constructor.VERSION}getEventHash(e={}){return e.name=this.name,e.plugin=this.constructor,e.instance=this,e}trigger(e,t={}){return ta(this.eventBusEl_,e,this.getEventHash(t))}handleStateChanged(e){}dispose(){let{name:e,player:t}=this;this.trigger(`dispose`),this.off(),t.off(`dispose`,this.dispose),t[el][e]=!1,this.player=this.state=null,t[e]=sl(e,tl[e])}static isBasic(t){let n=typeof t==`string`?rl(t):t;return typeof n==`function`&&!e.prototype.isPrototypeOf(n.prototype)}static registerPlugin(t,n){if(typeof t!=`string`)throw Error(`Illegal plugin name, "${t}", must be a string, was ${typeof t}.`);if(nl(t))B.warn(`A plugin named "${t}" already exists. You may want to avoid re-registering plugins!`);else if(Zc.prototype.hasOwnProperty(t))throw Error(`Illegal plugin name, "${t}", cannot share a name with an existing player method!`);if(typeof n!=`function`)throw Error(`Illegal plugin for "${t}", must be a function, was ${typeof n}.`);return tl[t]=n,t!==$c&&(e.isBasic(n)?Zc.prototype[t]=ol(t,n):Zc.prototype[t]=sl(t,n)),n}static deregisterPlugin(e){if(e===$c)throw Error(`Cannot de-register base plugin.`);nl(e)&&(delete tl[e],delete Zc.prototype[e])}static getPlugins(e=Object.keys(tl)){let t;return e.forEach(e=>{let n=rl(e);n&&(t||={},t[e]=n)}),t}static getPluginVersion(e){let t=rl(e);return t&&t.VERSION||``}};cl.getPlugin=rl,cl.BASE_PLUGIN_NAME=$c,cl.registerPlugin($c,cl),Zc.prototype.usingPlugin=function(e){return!!this[el]&&this[el][e]===!0},Zc.prototype.hasPlugin=function(e){return!!nl(e)};function ll(e,t){let n=!1;return function(...r){return n||B.warn(e),n=!0,t.apply(this,r)}}function ul(e,t,n,r){return ll(`${t} is deprecated and will be removed in ${e}.0; please use ${n} instead.`,r)}var dl={NetworkBadStatus:`networkbadstatus`,NetworkRequestFailed:`networkrequestfailed`,NetworkRequestAborted:`networkrequestaborted`,NetworkRequestTimeout:`networkrequesttimeout`,NetworkBodyParserFailed:`networkbodyparserfailed`,StreamingHlsPlaylistParserError:`streaminghlsplaylistparsererror`,StreamingDashManifestParserError:`streamingdashmanifestparsererror`,StreamingContentSteeringParserError:`streamingcontentsteeringparsererror`,StreamingVttParserError:`streamingvttparsererror`,StreamingFailedToSelectNextSegment:`streamingfailedtoselectnextsegment`,StreamingFailedToDecryptSegment:`streamingfailedtodecryptsegment`,StreamingFailedToTransmuxSegment:`streamingfailedtotransmuxsegment`,StreamingFailedToAppendSegment:`streamingfailedtoappendsegment`,StreamingCodecsChangeError:`streamingcodecschangeerror`},fl=e=>e.indexOf(`#`)===0?e.slice(1):e;function W(e,t,n){let r=W.getPlayer(e);if(r)return t&&B.warn(`Player "${e}" is already initialised. Options will not be applied.`),n&&r.ready(n),r;let i=typeof e==`string`?Mi(`#`+fl(e)):e;if(!si(i))throw TypeError(`The element or ID supplied is not valid. (videojs)`);let a=`getRootNode`in i&&i.getRootNode()instanceof I.default.ShadowRoot?i.getRootNode():i.ownerDocument.body;return(!i.ownerDocument.defaultView||!a.contains(i))&&B.warn(`The element supplied is not included in the DOM`),t||={},t.restoreEl===!0&&(t.restoreEl=(i.parentNode&&i.parentNode.hasAttribute&&i.parentNode.hasAttribute(`data-vjs-player`)?i.parentNode:i).cloneNode(!0)),fr(`beforesetup`).forEach(e=>{let n=e(i,Ar(t));if(!Or(n)||Array.isArray(n)){B.error(`please return an object in beforesetup hooks`);return}t=Ar(t,n)}),r=new(H.getComponent(`Player`))(i,t,n),fr(`setup`).forEach(e=>e(r)),r}if(W.hooks_=dr,W.hooks=fr,W.hook=pr,W.hookOnce=hr,W.removeHook=mr,I.default.VIDEOJS_NO_DYNAMIC_STYLE!==!0&&oi()){let e=Mi(`.vjs-styles-defaults`);if(!e){e=Hi(`vjs-styles-defaults`);let t=Mi(`head`);t&&t.insertBefore(e,t.firstChild),Ui(e,` .video-js { width: 300px; height: 150px; } .vjs-fluid:not(.vjs-audio-only-mode) { padding-top: 56.25% } `)}}Bi(1,W),W.VERSION=ur,W.options=Zc.prototype.options_,W.getPlayers=()=>Zc.players,W.getPlayer=e=>{let t=Zc.players,n;if(typeof e==`string`){let r=fl(e),i=t[r];if(i)return i;n=Mi(`#`+r)}else n=e;if(si(n)){let{player:e,playerId:r}=n;if(e||t[r])return e||t[r]}},W.getAllPlayers=()=>Object.keys(Zc.players).map(e=>Zc.players[e]).filter(Boolean),W.players=Zc.players,W.getComponent=H.getComponent,W.registerComponent=(e,t)=>(So.isTech(t)&&B.warn(`The ${e} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`),H.registerComponent.call(H,e,t)),W.getTech=So.getTech,W.registerTech=So.registerTech,W.use=Eo,Object.defineProperty(W,`middleware`,{value:{},writeable:!1,enumerable:!0}),Object.defineProperty(W.middleware,`TERMINATOR`,{value:To,writeable:!1,enumerable:!0}),W.browser=ri,W.obj=Nr,W.mergeOptions=ul(9,`videojs.mergeOptions`,`videojs.obj.merge`,Ar),W.defineLazyProperty=ul(9,`videojs.defineLazyProperty`,`videojs.obj.defineLazyProperty`,Mr),W.bind=ul(9,`videojs.bind`,`native Function.prototype.bind`,oa),W.registerPlugin=cl.registerPlugin,W.deregisterPlugin=cl.deregisterPlugin,W.plugin=(e,t)=>(B.warn(`videojs.plugin() is deprecated; use videojs.registerPlugin() instead`),cl.registerPlugin(e,t)),W.getPlugins=cl.getPlugins,W.getPlugin=cl.getPlugin,W.getPluginVersion=cl.getPluginVersion,W.addLanguage=function(e,t){return e=(``+e).toLowerCase(),W.options.languages=Ar(W.options.languages,{[e]:t}),W.options.languages[e]},W.log=B,W.createLogger=Cr,W.time=Ra,W.createTimeRange=ul(9,`videojs.createTimeRange`,`videojs.time.createTimeRanges`,Ma),W.createTimeRanges=ul(9,`videojs.createTimeRanges`,`videojs.time.createTimeRanges`,Ma),W.formatTime=ul(9,`videojs.formatTime`,`videojs.time.formatTime`,La),W.setFormatTime=ul(9,`videojs.setFormatTime`,`videojs.time.setFormatTime`,Fa),W.resetFormatTime=ul(9,`videojs.resetFormatTime`,`videojs.time.resetFormatTime`,Ia),W.parseUrl=ul(9,`videojs.parseUrl`,`videojs.url.parseUrl`,oo),W.isCrossOrigin=ul(9,`videojs.isCrossOrigin`,`videojs.url.isCrossOrigin`,lo),W.EventTarget=da,W.any=ra,W.on=$i,W.one=na,W.off=ea,W.trigger=ta,W.xhr=R.default,W.TrackList=qa,W.TextTrack=mo,W.TextTrackList=Qa,W.AudioTrack=ho,W.AudioTrackList=Ya,W.VideoTrack=go,W.VideoTrackList=Za,[`isEl`,`isTextNode`,`createEl`,`hasClass`,`addClass`,`removeClass`,`toggleClass`,`setAttributes`,`getAttributes`,`emptyEl`,`appendContent`,`insertContent`].forEach(e=>{W[e]=function(){return B.warn(`videojs.${e}() is deprecated; use videojs.dom.${e}() instead`),Ii[e].apply(null,arguments)}}),W.computedStyle=ul(9,`videojs.computedStyle`,`videojs.dom.computedStyle`,Pi),W.dom=Ii,W.fn=la,W.num=ys,W.str=Oa,W.url=uo,W.Error=dl;var pl=class{constructor(e){let t=this;return t.id=e.id,t.label=t.id,t.width=e.width,t.height=e.height,t.bitrate=e.bandwidth,t.frameRate=e.frameRate,t.enabled_=e.enabled,Object.defineProperty(t,`enabled`,{get(){return t.enabled_()},set(e){t.enabled_(e)}}),t}},ml=class extends W.EventTarget{constructor(){super();let e=this;return e.levels_=[],e.selectedIndex_=-1,Object.defineProperty(e,`selectedIndex`,{get(){return e.selectedIndex_}}),Object.defineProperty(e,`length`,{get(){return e.levels_.length}}),e[Symbol.iterator]=()=>e.levels_.values(),e}addQualityLevel(e){let t=this.getQualityLevelById(e.id);if(t)return t;let n=this.levels_.length;return t=new pl(e),``+n in this||Object.defineProperty(this,n,{get(){return this.levels_[n]}}),this.levels_.push(t),this.trigger({qualityLevel:t,type:`addqualitylevel`}),t}removeQualityLevel(e){let t=null;for(let n=0,r=this.length;nn&&this.selectedIndex_--;break}return t&&this.trigger({qualityLevel:e,type:`removequalitylevel`}),t}getQualityLevelById(e){for(let t=0,n=this.length;tr,e.qualityLevels.VERSION=hl,r},_l=function(e){return gl(this,W.obj.merge({},e))};W.registerPlugin(`qualityLevels`,_l),_l.VERSION=hl;var vl=ge,yl=(e,t)=>t&&t.responseURL&&e!==t.responseURL?t.responseURL:e,bl=e=>W.log.debug?W.log.debug.bind(W,`VHS:`,`${e} >`):function(){};function xl(...e){let t=W.obj||W;return(t.merge||t.mergeOptions).apply(t,e)}function Sl(...e){let t=W.time||W;return(t.createTimeRanges||t.createTimeRanges).apply(t,e)}function Cl(e){if(e.length===0)return`Buffered Ranges are empty`;let t=`Buffered Ranges: `;for(let n=0;n ${i}. Duration (${i-r})\n`}return t}var wl=1/30,Tl=wl*3,El=function(e,t){let n=[],r;if(e&&e.length)for(r=0;r=t})},Ol=function(e,t){return El(e,function(e){return e-wl>=t})},kl=function(e){if(e.length<2)return Sl();let t=[];for(let n=1;n{let t=[];if(!e||!e.length)return``;for(let n=0;n `+e.end(n));return t.join(`, `)},Ml=function(e,t,n=1){return((e.length?e.end(e.length-1):0)-t)/n},Nl=e=>{let t=[];for(let n=0;na)){if(t>i&&t<=a){n+=a-t;continue}n+=a-i}}return n},Ll=(e,t)=>{if(!t.preload)return t.duration;let n=0;return(t.parts||[]).forEach(function(e){n+=e.duration}),(t.preloadHints||[]).forEach(function(t){t.type===`PART`&&(n+=e.partTargetDuration)}),n},Rl=e=>(e.segments||[]).reduce((e,t,n)=>(t.parts?t.parts.forEach(function(r,i){e.push({duration:r.duration,segmentIndex:n,partIndex:i,part:r,segment:t})}):e.push({duration:t.duration,segmentIndex:n,partIndex:null,segment:t,part:null}),e),[]),zl=e=>{let t=e.segments&&e.segments.length&&e.segments[e.segments.length-1];return t&&t.parts||[]},Bl=({preloadSegment:e})=>{if(!e)return;let{parts:t,preloadHints:n}=e,r=(n||[]).reduce((e,t)=>e+ +(t.type===`PART`),0);return r+=t&&t.length?t.length:0,r},Vl=(e,t)=>{if(t.endList)return 0;if(e&&e.suggestedPresentationDelay)return e.suggestedPresentationDelay;let n=zl(t).length>0;return n&&t.serverControl&&t.serverControl.partHoldBack?t.serverControl.partHoldBack:n&&t.partTargetDuration?t.partTargetDuration*3:t.serverControl&&t.serverControl.holdBack?t.serverControl.holdBack:t.targetDuration?t.targetDuration*3:0},Hl=function(e,t){let n=0,r=t-e.mediaSequence,i=e.segments[r];if(i){if(i.start!==void 0)return{result:i.start,precise:!0};if(i.end!==void 0)return{result:i.end-i.duration,precise:!0}}for(;r--;){if(i=e.segments[r],i.end!==void 0)return{result:n+i.end,precise:!0};if(n+=Ll(e,i),i.start!==void 0)return{result:n+i.start,precise:!0}}return{result:n,precise:!1}},Ul=function(e,t){let n=0,r,i=t-e.mediaSequence;for(;ir&&([n,r]=[r,n]),n<0){for(let t=n;t0)for(let t=c-1;t>=0;t--){let n=s[t];if(o+=n.duration,a){if(o<0)continue}else if(o+wl<=0)continue;return{partIndex:n.partIndex,segmentIndex:n.segmentIndex,startTime:i-Kl({defaultDuration:e.targetDuration,durationList:s,startIndex:c,endIndex:t})}}return{partIndex:s[0]&&s[0].partIndex||null,segmentIndex:s[0]&&s[0].segmentIndex||0,startTime:t}}if(c<0){for(let n=c;n<0;n++)if(o-=e.targetDuration,o<0)return{partIndex:s[0]&&s[0].partIndex||null,segmentIndex:s[0]&&s[0].segmentIndex||0,startTime:t};c=0}for(let t=c;twl,l=o===0,u=r&&o+wl>=0;if(!((l||u)&&t!==s.length-1)){if(a){if(o>0)continue}else if(o-wl>=0)continue;return{partIndex:n.partIndex,segmentIndex:n.segmentIndex,startTime:i+Kl({defaultDuration:e.targetDuration,durationList:s,startIndex:c,endIndex:t})}}}return{segmentIndex:s[s.length-1].segmentIndex,partIndex:s[s.length-1].partIndex,startTime:t}},Xl=function(e){return e.excludeUntil&&e.excludeUntil>Date.now()},Zl=function(e){return e.excludeUntil&&e.excludeUntil===1/0},Ql=function(e){let t=Xl(e);return!e.disabled&&!t},$l=function(e){return e.disabled},eu=function(e){for(let t=0;t{if(e.playlists.length===1)return!0;let n=t.attributes.BANDWIDTH||Number.MAX_VALUE;return e.playlists.filter(e=>Ql(e)?(e.attributes.BANDWIDTH||0)!e&&!t||!e&&t||e&&!t?!1:!!(e===t||e.id&&t.id&&e.id===t.id||e.resolvedUri&&t.resolvedUri&&e.resolvedUri===t.resolvedUri||e.uri&&t.uri&&e.uri===t.uri),au=function(e,t){let n=e&&e.mediaGroups&&e.mediaGroups.AUDIO||{},r=!1;for(let e in n){for(let i in n[e])if(r=t(n[e][i]),r)break;if(r)break}return!!r},ou=e=>{if(!e||!e.playlists||!e.playlists.length)return au(e,e=>e.playlists&&e.playlists.length||e.uri);for(let t=0;tLe(e)))&&!au(e,e=>iu(n,e)))return!1}return!0},su={liveEdgeDelay:Vl,duration:Gl,seekable:Jl,getMediaInfoForTime:Yl,isEnabled:Ql,isDisabled:$l,isExcluded:Xl,isIncompatible:Zl,playlistEnd:ql,isAes:eu,hasAttribute:tu,estimateSegmentRequestTime:nu,isLowestEnabledRendition:ru,isAudioOnly:ou,playlistMatch:iu,segmentDurationWithParts:Ll},{log:cu}=W,lu=(e,t)=>`${e}-${t}`,uu=(e,t,n)=>`placeholder-uri-${e}-${t}-${n}`,du=({onwarn:e,oninfo:t,manifestString:n,customTagParsers:r=[],customTagMappers:i=[],llhls:a})=>{let o=new Ae;e&&o.on(`warn`,e),t&&o.on(`info`,t),r.forEach(e=>o.addParser(e)),i.forEach(e=>o.addTagMapper(e)),o.push(n),o.end();let s=o.manifest;if(a||([`preloadSegment`,`skip`,`serverControl`,`renditionReports`,`partInf`,`partTargetDuration`].forEach(function(e){s.hasOwnProperty(e)&&delete s[e]}),s.segments&&s.segments.forEach(function(e){[`parts`,`preloadHints`].forEach(function(t){e.hasOwnProperty(t)&&delete e[t]})})),!s.targetDuration){let t=10;s.segments&&s.segments.length&&(t=s.segments.reduce((e,t)=>Math.max(e,t.duration),0)),e&&e({message:`manifest has no targetDuration defaulting to ${t}`}),s.targetDuration=t}let c=zl(s);if(c.length&&!s.partTargetDuration){let t=c.reduce((e,t)=>Math.max(e,t.duration),0);e&&(e({message:`manifest has no partTargetDuration defaulting to ${t}`}),cu.error(`LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.`)),s.partTargetDuration=t}return s},fu=(e,t)=>{e.mediaGroups&&[`AUDIO`,`SUBTITLES`].forEach(n=>{if(e.mediaGroups[n])for(let r in e.mediaGroups[n])for(let i in e.mediaGroups[n][r]){let a=e.mediaGroups[n][r][i];t(a,n,r,i)}})},pu=({playlist:e,uri:t,id:n})=>{e.id=n,e.playlistErrors_=0,t&&(e.uri=t),e.attributes=e.attributes||{}},mu=e=>{let t=e.playlists.length;for(;t--;){let n=e.playlists[t];pu({playlist:n,id:lu(t,n.uri)}),n.resolvedUri=vl(e.uri,n.uri),e.playlists[n.id]=n,e.playlists[n.uri]=n,n.attributes.BANDWIDTH||cu.warn(`Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.`)}},hu=e=>{fu(e,t=>{t.uri&&(t.resolvedUri=vl(e.uri,t.uri))})},gu=(e,t)=>{let n=lu(0,t),r={mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:I.default.location.href,resolvedUri:I.default.location.href,playlists:[{uri:t,id:n,resolvedUri:t,attributes:{}}]};return r.playlists[n]=r.playlists[0],r.playlists[t]=r.playlists[0],r},_u=(e,t,n=uu)=>{e.uri=t;for(let t=0;t{if(!t.playlists||!t.playlists.length){if(r&&i===`AUDIO`&&!t.uri)for(let t=0;t(e.set(t.id,t),e),new Map)}processDateRange(e){this.pendingDateRanges_.delete(e.id),this.processedDateRanges_.set(e.id,e)}getDateRangesToProcess(){if(this.offset_===null)return[];let e={},t=[];this.pendingDateRanges_.forEach((n,r)=>{this.processedDateRanges_.has(r)||(n.startTime=n.startDate.getTime()/1e3-this.offset_,n.processDateRange=()=>this.processDateRange(n),t.push(n),n.class&&(e[n.class]?n.classListIndex=e[n.class].push(n)-1:(e[n.class]=[n],n.classListIndex=0)))});for(let n of t){let t=e[n.class]||[];n.endDate?n.endTime=n.endDate.getTime()/1e3-this.offset_:n.endOnNext&&t[n.classListIndex+1]?n.endTime=t[n.classListIndex+1].startTime:n.duration?n.endTime=n.startTime+n.duration:n.plannedDuration?n.endTime=n.startTime+n.plannedDuration:n.endTime=n.startTime}return t}trimProcessedDateRanges_(e){new Map(this.processedDateRanges_).forEach((t,n)=>{t.startDate.getTime(){let i=t.status<200||t.status>299,a=t.status>=400&&t.status<=499,o={uri:t.uri,requestType:e},s=i&&!a||r;return n&&a?(o.error=me({},n),o.errorType=W.Error.NetworkRequestFailed):t.aborted?o.errorType=W.Error.NetworkRequestAborted:t.timedout?o.errorType=W.Error.NetworkRequestTimeout:s&&(o.errorType=r?W.Error.NetworkBodyParserFailed:W.Error.NetworkBadStatus,o.status=t.status,o.headers=t.headers),o},xu=bl(`CodecUtils`),Su=function(e){let t=e.attributes||{};if(t.CODECS)return Fe(t.CODECS)},Cu=(e,t)=>{let n=t.attributes||{};return e&&e.mediaGroups&&e.mediaGroups.AUDIO&&n.AUDIO&&e.mediaGroups.AUDIO[n.AUDIO]},wu=(e,t)=>{if(!Cu(e,t))return!0;let n=t.attributes||{},r=e.mediaGroups.AUDIO[n.AUDIO];for(let e in r)if(!r[e].uri&&!r[e].playlists)return!0;return!1},Tu=function(e){let t={};return e.forEach(({mediaType:e,type:n,details:r})=>{t[e]=t[e]||[],t[e].push(Pe(`${n}${r}`))}),Object.keys(t).forEach(function(e){if(t[e].length>1){xu(`multiple ${e} codecs found as attributes: ${t[e].join(`, `)}. Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.`),t[e]=null;return}t[e]=t[e][0]}),t},Eu=function(e){let t=0;return e.audio&&t++,e.video&&t++,t},Du=function(e,t){let n=t.attributes||{},r=Tu(Su(t)||[]);if(Cu(e,t)&&!r.audio&&!wu(e,t)){let t=Tu(Ie(e,n.AUDIO)||[]);t.audio&&(r.audio=t.audio)}return r},{EventTarget:Ou}=W,ku=(e,t)=>{if(t.endList||!t.serverControl)return e;let n={};if(t.serverControl.canBlockReload){let{preloadSegment:e}=t,r=t.mediaSequence+t.segments.length;if(e){let i=e.parts||[],a=Bl(t)-1;a>-1&&a!==i.length-1&&(n._HLS_part=a),(a>-1||i.length)&&r--}n._HLS_msn=r}if(t.serverControl&&t.serverControl.canSkipUntil&&(n._HLS_skip=t.serverControl.canSkipDateranges?`v2`:`YES`),Object.keys(n).length){let t=new I.default.URL(e);[`_HLS_skip`,`_HLS_msn`,`_HLS_part`].forEach(function(e){n.hasOwnProperty(e)&&t.searchParams.set(e,n[e])}),e=t.toString()}return e},Au=(e,t)=>{if(!e)return t;let n=xl(e,t);if(e.preloadHints&&!t.preloadHints&&delete n.preloadHints,e.parts&&!t.parts)delete n.parts;else if(e.parts&&t.parts)for(let r=0;r{let r=e.slice(),i=t.slice();n||=0;let a=[],o;for(let e=0;e{!e.resolvedUri&&e.uri&&(e.resolvedUri=vl(t,e.uri)),e.key&&!e.key.resolvedUri&&(e.key.resolvedUri=vl(t,e.key.uri)),e.map&&!e.map.resolvedUri&&(e.map.resolvedUri=vl(t,e.map.uri)),e.map&&e.map.key&&!e.map.key.resolvedUri&&(e.map.key.resolvedUri=vl(t,e.map.key.uri)),e.parts&&e.parts.length&&e.parts.forEach(e=>{e.resolvedUri||=vl(t,e.uri)}),e.preloadHints&&e.preloadHints.length&&e.preloadHints.forEach(e=>{e.resolvedUri||=vl(t,e.uri)})},Nu=function(e){let t=e.segments||[],n=e.preloadSegment;if(n&&n.parts&&n.parts.length){if(n.preloadHints){for(let e=0;ee===t||e.segments&&t.segments&&e.segments.length===t.segments.length&&e.endList===t.endList&&e.mediaSequence===t.mediaSequence&&e.preloadSegment===t.preloadSegment,Fu=(e,t,n=Pu)=>{let r=xl(e,{}),i=r.playlists[t.id];if(!i||n(i,t))return null;t.segments=Nu(t);let a=xl(i,t);if(a.preloadSegment&&!t.preloadSegment&&delete a.preloadSegment,i.segments){if(t.skip){t.segments=t.segments||[];for(let e=0;e{Mu(e,a.resolvedUri)});for(let e=0;e{if(e.playlists)for(let n=0;n{let n=e.segments||[],r=n[n.length-1],i=r&&r.parts&&r.parts[r.parts.length-1],a=i&&i.duration||r&&r.duration;return t&&a?a*1e3:(e.partTargetDuration||e.targetDuration||10)*500},Lu=(e,t,n)=>{if(!e)return;let r=[];return e.forEach(e=>{if(!e.attributes)return;let{BANDWIDTH:t,RESOLUTION:n,CODECS:i}=e.attributes;r.push({id:e.id,bandwidth:t,resolution:n,codecs:i})}),{type:t,isLive:n,renditions:r}},Ru=class extends Ou{constructor(e,t,n={}){if(super(),!e)throw Error(`A non-empty playlist URL or object is required`);this.logger_=bl(`PlaylistLoader`);let{withCredentials:r=!1}=n;this.src=e,this.vhs_=t,this.withCredentials=r,this.addDateRangesToTextTrack_=n.addDateRangesToTextTrack;let i=t.options_;this.customTagParsers=i&&i.customTagParsers||[],this.customTagMappers=i&&i.customTagMappers||[],this.llhls=i&&i.llhls,this.dateRangesStorage_=new vu,this.state=`HAVE_NOTHING`,this.handleMediaupdatetimeout_=this.handleMediaupdatetimeout_.bind(this),this.on(`mediaupdatetimeout`,this.handleMediaupdatetimeout_),this.on(`loadedplaylist`,this.handleLoadedPlaylist_.bind(this))}handleLoadedPlaylist_(){let e=this.media();if(!e)return;this.dateRangesStorage_.setOffset(e.segments),this.dateRangesStorage_.setPendingDateRanges(e.dateRanges);let t=this.dateRangesStorage_.getDateRangesToProcess();!t.length||!this.addDateRangesToTextTrack_||this.addDateRangesToTextTrack_(t)}handleMediaupdatetimeout_(){if(this.state!==`HAVE_METADATA`)return;let e=this.media(),t=vl(this.main.uri,e.uri);this.llhls&&(t=ku(t,e)),this.state=`HAVE_CURRENT_METADATA`,this.request=this.vhs_.xhr({uri:t,withCredentials:this.withCredentials,requestType:`hls-playlist`},(e,t)=>{if(this.request){if(e)return this.playlistRequestError(this.request,this.media(),`HAVE_METADATA`);this.haveMetadata({playlistString:this.request.responseText,url:this.media().uri,id:this.media().id})}})}playlistRequestError(e,t,n){let{uri:r,id:i}=t;this.request=null,n&&(this.state=n),this.error={playlist:this.main.playlists[i],status:e.status,message:`HLS playlist request error at URL: ${r}.`,responseText:e.responseText,code:e.status>=500?4:2,metadata:bu({requestType:e.requestType,request:e,error:e.error})},this.trigger(`error`)}parseManifest_({url:e,manifestString:t}){try{let n=du({onwarn:({message:t})=>this.logger_(`m3u8-parser warn for ${e}: ${t}`),oninfo:({message:t})=>this.logger_(`m3u8-parser info for ${e}: ${t}`),manifestString:t,customTagParsers:this.customTagParsers,customTagMappers:this.customTagMappers,llhls:this.llhls});return!n.playlists||!n.playlists.length||this.excludeAudioOnlyVariants(n.playlists),n}catch(e){this.error=e,this.error.metadata={errorType:W.Error.StreamingHlsPlaylistParserError,error:e}}}excludeAudioOnlyVariants(e){let t=e=>{let{width:t,height:n}=(e.attributes||{}).RESOLUTION||{};return t&&n?!0:!!Tu(Su(e)||[]).video};e.some(t)&&e.forEach(e=>{t(e)||(e.excludeUntil=1/0)})}haveMetadata({playlistString:e,playlistObject:t,url:n,id:r}){this.request=null,this.state=`HAVE_METADATA`;let i={playlistInfo:{type:`media`,uri:n}};this.trigger({type:`playlistparsestart`,metadata:i});let a=t||this.parseManifest_({url:n,manifestString:e});a.lastRequest=Date.now(),pu({playlist:a,uri:n,id:r});let o=Fu(this.main,a);this.targetDuration=a.partTargetDuration||a.targetDuration,this.pendingMedia_=null,o?(this.main=o,this.media_=this.main.playlists[r]):this.trigger(`playlistunchanged`),this.updateMediaUpdateTimeout_(Iu(this.media(),!!o)),i.parsedPlaylist=Lu(this.main.playlists,i.playlistInfo.type,!this.media_.endList),this.trigger({type:`playlistparsecomplete`,metadata:i}),this.trigger(`loadedplaylist`)}dispose(){this.trigger(`dispose`),this.stopRequest(),I.default.clearTimeout(this.mediaUpdateTimeout),I.default.clearTimeout(this.finalRenditionTimeout),this.dateRangesStorage_=new vu,this.off()}stopRequest(){if(this.request){let e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}}media(e,t){if(!e)return this.media_;if(this.state===`HAVE_NOTHING`)throw Error(`Cannot switch media playlist from `+this.state);if(typeof e==`string`){if(!this.main.playlists[e])throw Error(`Unknown playlist URI: `+e);e=this.main.playlists[e]}if(I.default.clearTimeout(this.finalRenditionTimeout),t){let t=(e.partTargetDuration||e.targetDuration)/2*1e3||5*1e3;this.finalRenditionTimeout=I.default.setTimeout(this.media.bind(this,e,!1),t);return}let n=this.state,r=!this.media_||e.id!==this.media_.id,i=this.main.playlists[e.id];if(i&&i.endList||e.endList&&e.segments.length){this.request&&=(this.request.onreadystatechange=null,this.request.abort(),null),this.state=`HAVE_METADATA`,this.media_=e,r&&(this.trigger(`mediachanging`),n===`HAVE_MAIN_MANIFEST`?this.trigger(`loadedmetadata`):this.trigger(`mediachange`));return}if(this.updateMediaUpdateTimeout_(Iu(e,!0)),!r)return;if(this.state=`SWITCHING_MEDIA`,this.request){if(e.resolvedUri===this.request.url)return;this.request.onreadystatechange=null,this.request.abort(),this.request=null}this.media_&&this.trigger(`mediachanging`),this.pendingMedia_=e;let a={playlistInfo:{type:`media`,uri:e.uri}};this.trigger({type:`playlistrequeststart`,metadata:a}),this.request=this.vhs_.xhr({uri:e.resolvedUri,withCredentials:this.withCredentials,requestType:`hls-playlist`},(t,r)=>{if(this.request){if(e.lastRequest=Date.now(),e.resolvedUri=yl(e.resolvedUri,r),t)return this.playlistRequestError(this.request,e,n);this.trigger({type:`playlistrequestcomplete`,metadata:a}),this.haveMetadata({playlistString:r.responseText,url:e.uri,id:e.id}),n===`HAVE_MAIN_MANIFEST`?this.trigger(`loadedmetadata`):this.trigger(`mediachange`)}})}pause(){this.mediaUpdateTimeout&&=(I.default.clearTimeout(this.mediaUpdateTimeout),null),this.stopRequest(),this.state===`HAVE_NOTHING`&&(this.started=!1),this.state===`SWITCHING_MEDIA`?this.media_?this.state=`HAVE_METADATA`:this.state=`HAVE_MAIN_MANIFEST`:this.state===`HAVE_CURRENT_METADATA`&&(this.state=`HAVE_METADATA`)}load(e){this.mediaUpdateTimeout&&=(I.default.clearTimeout(this.mediaUpdateTimeout),null);let t=this.media();if(e){let e=t?(t.partTargetDuration||t.targetDuration)/2*1e3:5*1e3;this.mediaUpdateTimeout=I.default.setTimeout(()=>{this.mediaUpdateTimeout=null,this.load()},e);return}if(!this.started){this.start();return}t&&!t.endList?this.trigger(`mediaupdatetimeout`):this.trigger(`loadedplaylist`)}updateMediaUpdateTimeout_(e){this.mediaUpdateTimeout&&=(I.default.clearTimeout(this.mediaUpdateTimeout),null),!(!this.media()||this.media().endList)&&(this.mediaUpdateTimeout=I.default.setTimeout(()=>{this.mediaUpdateTimeout=null,this.trigger(`mediaupdatetimeout`),this.updateMediaUpdateTimeout_(e)},e))}start(){if(this.started=!0,typeof this.src==`object`){this.src.uri||(this.src.uri=I.default.location.href),this.src.resolvedUri=this.src.uri,setTimeout(()=>{this.setupInitialPlaylist(this.src)},0);return}let e={playlistInfo:{type:`multivariant`,uri:this.src}};this.trigger({type:`playlistrequeststart`,metadata:e}),this.request=this.vhs_.xhr({uri:this.src,withCredentials:this.withCredentials,requestType:`hls-playlist`},(t,n)=>{if(!this.request)return;if(this.request=null,t)return this.error={status:n.status,message:`HLS playlist request error at URL: ${this.src}.`,responseText:n.responseText,code:2,metadata:bu({requestType:n.requestType,request:n,error:t})},this.state===`HAVE_NOTHING`&&(this.started=!1),this.trigger(`error`);this.trigger({type:`playlistrequestcomplete`,metadata:e}),this.src=yl(this.src,n),this.trigger({type:`playlistparsestart`,metadata:e});let r=this.parseManifest_({manifestString:n.responseText,url:this.src});e.parsedPlaylist=Lu(r.playlists,e.playlistInfo.type,!1),this.trigger({type:`playlistparsecomplete`,metadata:e}),this.setupInitialPlaylist(r)})}srcUri(){return typeof this.src==`string`?this.src:this.src.uri}setupInitialPlaylist(e){if(this.state=`HAVE_MAIN_MANIFEST`,e.playlists){this.main=e,_u(this.main,this.srcUri()),e.playlists.forEach(e=>{e.segments=Nu(e),e.segments.forEach(t=>{Mu(t,e.resolvedUri)})}),this.trigger(`loadedplaylist`),this.request||this.media(this.main.playlists[0]);return}let t=this.srcUri()||I.default.location.href;this.main=gu(e,t),this.haveMetadata({playlistObject:e,url:t,id:this.main.playlists[0].id}),this.trigger(`loadedmetadata`)}updateOrDeleteClone(e,t){let n=this.main,r=e.ID,i=n.playlists.length;for(;i--;){let a=n.playlists[i];if(a.attributes[`PATHWAY-ID`]===r){let o=a.resolvedUri,s=a.id;if(t){let t=this.createCloneURI_(a.resolvedUri,e),o=lu(r,t),s=this.createCloneAttributes_(r,a.attributes),c=this.createClonePlaylist_(a,o,e,s);n.playlists[i]=c,n.playlists[o]=c,n.playlists[t]=c}else n.playlists.splice(i,1);delete n.playlists[s],delete n.playlists[o]}}this.updateOrDeleteCloneMedia(e,t)}updateOrDeleteCloneMedia(e,t){let n=this.main,r=e.ID;[`AUDIO`,`SUBTITLES`,`CLOSED-CAPTIONS`].forEach(e=>{if(!(!n.mediaGroups[e]||!n.mediaGroups[e][r])){for(let t in n.mediaGroups[e])if(t===r){for(let r in n.mediaGroups[e][t])n.mediaGroups[e][t][r].playlists.forEach((e,t)=>{let r=n.playlists[e.id],i=r.id,a=r.resolvedUri;delete n.playlists[i],delete n.playlists[a]});delete n.mediaGroups[e][t]}}}),t&&this.createClonedMediaGroups_(e)}addClonePathway(e,t={}){let n=this.main,r=n.playlists.length,i=this.createCloneURI_(t.resolvedUri,e),a=lu(e.ID,i),o=this.createCloneAttributes_(e.ID,t.attributes),s=this.createClonePlaylist_(t,a,e,o);n.playlists[r]=s,n.playlists[a]=s,n.playlists[i]=s,this.createClonedMediaGroups_(e)}createClonedMediaGroups_(e){let t=e.ID,n=e[`BASE-ID`],r=this.main;[`AUDIO`,`SUBTITLES`,`CLOSED-CAPTIONS`].forEach(i=>{if(!(!r.mediaGroups[i]||r.mediaGroups[i][t]))for(let a in r.mediaGroups[i]){if(a===n)r.mediaGroups[i][t]={};else continue;for(let n in r.mediaGroups[i][a]){let o=r.mediaGroups[i][a][n];r.mediaGroups[i][t][n]=me({},o);let s=r.mediaGroups[i][t][n],c=this.createCloneURI_(o.resolvedUri,e);s.resolvedUri=c,s.uri=c,s.playlists=[],o.playlists.forEach((a,o)=>{let c=r.playlists[a.id],l=lu(t,uu(i,t,n));if(c&&!r.playlists[l]){let t=this.createClonePlaylist_(c,l,e),n=t.resolvedUri;r.playlists[l]=t,r.playlists[n]=t}s.playlists[o]=this.createClonePlaylist_(a,l,e)})}}})}createClonePlaylist_(e,t,n,r){let i=this.createCloneURI_(e.resolvedUri,n),a={resolvedUri:i,uri:i,id:t};return e.segments&&(a.segments=[]),r&&(a.attributes=r),xl(e,a)}createCloneURI_(e,t){let n=new URL(e);n.hostname=t[`URI-REPLACEMENT`].HOST;let r=t[`URI-REPLACEMENT`].PARAMS;for(let e of Object.keys(r))n.searchParams.set(e,r[e]);return n.href}createCloneAttributes_(e,t){let n={"PATHWAY-ID":e};return[`AUDIO`,`SUBTITLES`,`CLOSED-CAPTIONS`].forEach(r=>{t[r]&&(n[r]=e)}),n}getKeyIdSet(e){let t=new Set;if(!e||!e.contentProtection)return t;for(let n in e.contentProtection)if(e.contentProtection[n]&&e.contentProtection[n].attributes&&e.contentProtection[n].attributes.keyId){let r=e.contentProtection[n].attributes.keyId;t.add(r.toLowerCase())}return t}},zu=function(e,t,n,r){let i=e.responseType===`arraybuffer`?e.response:e.responseText;!t&&i&&(e.responseTime=Date.now(),e.roundTripTime=e.responseTime-e.requestTime,e.bytesReceived=i.byteLength||i.length,e.bandwidth||=Math.floor(e.bytesReceived/e.roundTripTime*8*1e3)),n.headers&&(e.responseHeaders=n.headers),t&&t.code===`ETIMEDOUT`&&(e.timedout=!0),!t&&!e.aborted&&n.statusCode!==200&&n.statusCode!==206&&n.statusCode!==0&&(t=Error(`XHR Failed with a response of: `+(e&&(i||e.responseText)))),r(t,e)},Bu=(e,t)=>{if(!e||!e.size)return;let n=t;return e.forEach(e=>{n=e(n)}),n},Vu=(e,t,n,r)=>{!e||!e.size||e.forEach(e=>{e(t,n,r)})},Hu=function(){let e=function e(t,n){t=xl({timeout:45e3},t);let r=e.beforeRequest||W.Vhs.xhr.beforeRequest,i=e._requestCallbackSet||W.Vhs.xhr._requestCallbackSet||new Set,a=e._responseCallbackSet||W.Vhs.xhr._responseCallbackSet;r&&typeof r==`function`&&(W.log.warn(`beforeRequest is deprecated, use onRequest instead.`),i.add(r));let o=W.Vhs.xhr.original===!0?W.xhr:W.Vhs.xhr,s=Bu(i,t);i.delete(r);let c=o(s||t,function(e,t){return Vu(a,c,e,t),zu(c,e,t,n)}),l=c.abort;return c.abort=function(){return c.aborted=!0,l.apply(c,arguments)},c.uri=t.uri,c.requestType=t.requestType,c.requestTime=Date.now(),c};return e.original=!0,e},Uu=function(e){let t,n=e.offset;return t=typeof e.offset==`bigint`||typeof e.length==`bigint`?I.default.BigInt(e.offset)+I.default.BigInt(e.length)-I.default.BigInt(1):e.offset+e.length-1,`bytes=`+n+`-`+t},Wu=function(e){let t={};return e.byterange&&(t.Range=Uu(e.byterange)),t},Gu=function(e,t){return e.start(t)+`-`+e.end(t)},Ku=function(e,t){let n=e.toString(16);return`00`.substring(0,2-n.length)+n+(t%2?` `:``)},qu=function(e){return e>=32&&e<126?String.fromCharCode(e):`.`},Ju=function(e){let t={};return Object.keys(e).forEach(n=>{let r=e[n];qe(r)?t[n]={bytes:r.buffer,byteOffset:r.byteOffset,byteLength:r.byteLength}:t[n]=r}),t},Yu=function(e){let t=e.byterange||{length:1/0,offset:0};return[t.length,t.offset,e.resolvedUri].join(`,`)},Xu=function(e){return e.resolvedUri},Zu=e=>{let t=Array.prototype.slice.call(e),n=``,r,i;for(let e=0;eZu(e),textRanges:e=>{let t=``,n;for(n=0;n{if(!t.dateTimeObject)return null;let n=t.videoTimingInfo.transmuxerPrependedSeconds,r=e-(t.videoTimingInfo.transmuxedPresentationStart+n);return new Date(t.dateTimeObject.getTime()+r*1e3)},td=e=>e.transmuxedPresentationEnd-e.transmuxedPresentationStart-e.transmuxerPrependedSeconds,nd=(e,t)=>{let n;try{n=new Date(e)}catch{return null}if(!t||!t.segments||t.segments.length===0)return null;let r=t.segments[0];if(ns?null:(n>new Date(a)&&(r=i),{segment:r,estimatedStart:r.videoTimingInfo?r.videoTimingInfo.transmuxedPresentationStart:su.duration(t,t.mediaSequence+t.segments.indexOf(r)),type:r.videoTimingInfo?`accurate`:`estimate`})},rd=(e,t)=>{if(!t||!t.segments||t.segments.length===0)return null;let n=0,r;for(let i=0;in){if(e>n+i.duration*$u)return null;r=i}return{segment:r,estimatedStart:r.videoTimingInfo?r.videoTimingInfo.transmuxedPresentationStart:n-r.duration,type:r.videoTimingInfo?`accurate`:`estimate`}},id=(e,t)=>{let n,r;try{n=new Date(e),r=new Date(t)}catch{}let i=n.getTime();return(r.getTime()-i)/1e3},ad=e=>{if(!e.segments||e.segments.length===0)return!1;for(let t=0;t{if(!n)throw Error(`getProgramTime: callback must be provided`);if(!e||t===void 0)return n({message:`getProgramTime: playlist and time must be provided`});let r=rd(t,e);if(!r)return n({message:`valid programTime was not found`});if(r.type===`estimate`)return n({message:`Accurate programTime could not be determined. Please seek to e.seekTime and try again`,seekTime:r.estimatedStart});let i={mediaSeconds:t},a=ed(t,r.segment);return a&&(i.programDateTime=a.toISOString()),n(null,i)},sd=({programTime:e,playlist:t,retryCount:n=2,seekTo:r,pauseAfterSeek:i=!0,tech:a,callback:o})=>{if(!o)throw Error(`seekToProgramTime: callback must be provided`);if(e===void 0||!t||!r)return o({message:`seekToProgramTime: programTime, seekTo and playlist must be provided`});if(!t.endList&&!a.hasStarted_)return o({message:`player must be playing a live stream to start buffering`});if(!ad(t))return o({message:`programDateTime tags must be provided in the manifest `+t.resolvedUri});let s=nd(e,t);if(!s)return o({message:`${e} was not found in the stream`});let c=s.segment,l=id(c.dateTimeObject,e);if(s.type===`estimate`){if(n===0)return o({message:`${e} is not buffered yet. Try again`});r(s.estimatedStart+l),a.one(`seeked`,()=>{sd({programTime:e,playlist:t,retryCount:n-1,seekTo:r,pauseAfterSeek:i,tech:a,callback:o})});return}let u=c.start+l;a.one(`seeked`,()=>o(null,a.currentTime())),i&&a.pause(),r(u)},cd=(e,t)=>{if(e.readyState===4)return t()},ld=(e,t,n,r)=>{let i=[],a,o=!1,s=function(e,t,r,i){return t.abort(),o=!0,n(e,t,r,i)},c=function(e,t){if(o)return;if(e)return e.metadata=bu({requestType:r,request:t,error:e}),s(e,t,``,i);let n=t.responseText.substring(i&&i.byteLength||0,t.responseText.length);if(i=tt(i,et(n,!0)),a||=In(i),i.length<10||a&&i.lengths(e,t,``,i));let c=sr(i);return c===`ts`&&i.length<188||!c&&i.length<376?cd(t,()=>s(e,t,``,i)):s(null,t,c,i)},l=t({uri:e,beforeSend(e){e.overrideMimeType(`text/plain; charset=x-user-defined`),e.addEventListener(`progress`,function({total:t,loaded:n}){return zu(e,null,{statusCode:e.status},c)})}},function(e,t){return zu(l,e,t,c)});return l},{EventTarget:ud}=W,dd=function(e,t){if(!Pu(e,t)||e.sidx&&t.sidx&&(e.sidx.offset!==t.sidx.offset||e.sidx.length!==t.sidx.length)||!e.sidx&&t.sidx||e.sidx&&!t.sidx||e.segments&&!t.segments||!e.segments&&t.segments)return!1;if(!e.segments&&!t.segments)return!0;for(let n=0;n`placeholder-uri-${e}-${t}-${r.attributes.NAME||n}`,pd=({mainXml:e,srcUrl:t,clientOffset:n,sidxMapping:r,previousManifest:i})=>{let a=An(e,{manifestUri:t,clientOffset:n,sidxMapping:r,previousManifest:i});return _u(a,t,fd),a},md=(e,t)=>{fu(e,(n,r,i,a)=>{(!t.mediaGroups[r][i]||!(a in t.mediaGroups[r][i]))&&delete e.mediaGroups[r][i][a]})},hd=(e,t,n)=>{let r=!0,i=xl(e,{duration:t.duration,minimumUpdatePeriod:t.minimumUpdatePeriod,timelineStarts:t.timelineStarts});for(let e=0;e{if(e.playlists&&e.playlists.length){let o=e.playlists[0].id,s=Fu(i,e.playlists[0],dd);s&&(i=s,a in i.mediaGroups[t][n]||(i.mediaGroups[t][n][a]=e),i.mediaGroups[t][n][a].playlists[0]=i.playlists[o],r=!1)}}),md(i,t),t.minimumUpdatePeriod!==e.minimumUpdatePeriod&&(r=!1),r?null:i},gd=(e,t)=>(!e.map&&!t.map||!!(e.map&&t.map&&e.map.byterange.offset===t.map.byterange.offset&&e.map.byterange.length===t.map.byterange.length))&&e.uri===t.uri&&e.byterange.offset===t.byterange.offset&&e.byterange.length===t.byterange.length,_d=(e,t)=>{let n={};for(let r in e){let i=e[r].sidx;if(i){let e=Ft(i);if(!t[e])break;let r=t[e].sidxInfo;gd(r,i)&&(n[e]=t[e])}}return n},vd=(e,t)=>{let n=_d(e.playlists,t);return fu(e,(e,r,i,a)=>{if(e.playlists&&e.playlists.length){let r=e.playlists;n=xl(n,_d(r,t))}}),n},yd=class extends ud{constructor(e,t,n={},r){super(),this.isPaused_=!0,this.mainPlaylistLoader_=r||this,r||(this.isMain_=!0);let{withCredentials:i=!1}=n;if(this.vhs_=t,this.withCredentials=i,this.addMetadataToTextTrack=n.addMetadataToTextTrack,!e)throw Error(`A non-empty playlist URL or object is required`);this.on(`minimumUpdatePeriod`,()=>{this.refreshXml_()}),this.on(`mediaupdatetimeout`,()=>{this.refreshMedia_(this.media().id)}),this.state=`HAVE_NOTHING`,this.loadedPlaylists_={},this.logger_=bl(`DashPlaylistLoader`),this.isMain_?(this.mainPlaylistLoader_.srcUrl=e,this.mainPlaylistLoader_.sidxMapping_={}):this.childPlaylist_=e}get isPaused(){return this.isPaused_}requestErrored_(e,t,n){if(!this.request)return!0;if(this.request=null,e)return this.error=typeof e==`object`&&!(e instanceof Error)?e:{status:t.status,message:`DASH request error at URL: `+t.uri,response:t.response,code:2,metadata:e.metadata},n&&(this.state=n),this.trigger(`error`),!0}addSidxSegments_(e,t,n){let r=e.sidx&&Ft(e.sidx);if(!e.sidx||!r||this.mainPlaylistLoader_.sidxMapping_[r]){I.default.clearTimeout(this.mediaRequest_),this.mediaRequest_=I.default.setTimeout(()=>n(!1),0);return}let i=yl(e.sidx.resolvedUri),a=(i,a)=>{if(this.requestErrored_(i,a,t))return;let o=this.mainPlaylistLoader_.sidxMapping_,{requestType:s}=a,c;try{c=(0,Nn.default)(z(a.response).subarray(8))}catch(e){e.metadata=bu({requestType:s,request:a,parseFailure:!0}),this.requestErrored_(e,a,t);return}return o[r]={sidxInfo:e.sidx,sidx:c},Et(e,c,e.sidx.resolvedUri),n(!0)};this.request=ld(i,this.vhs_.xhr,(t,n,r,o)=>{if(t)return a(t,n);if(!r||r!==`mp4`){let t=r||`unknown`;return a({status:n.status,message:`Unsupported ${t} container type for sidx segment at URL: ${i}`,response:``,playlist:e,internal:!0,playlistExclusionDuration:1/0,code:2},n)}let{offset:s,length:c}=e.sidx.byterange;if(o.length>=c+s)return a(t,{response:o.subarray(s,s+c),status:n.status,uri:n.uri});this.request=this.vhs_.xhr({uri:i,responseType:`arraybuffer`,requestType:`dash-sidx`,headers:Wu({byterange:e.sidx.byterange})},a)},`dash-sidx`)}dispose(){this.isPaused_=!0,this.trigger(`dispose`),this.stopRequest(),this.loadedPlaylists_={},I.default.clearTimeout(this.minimumUpdatePeriodTimeout_),I.default.clearTimeout(this.mediaRequest_),I.default.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.mediaRequest_=null,this.minimumUpdatePeriodTimeout_=null,this.mainPlaylistLoader_.createMupOnMedia_&&(this.off(`loadedmetadata`,this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.off()}hasPendingRequest(){return this.request||this.mediaRequest_}stopRequest(){if(this.request){let e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}}media(e){if(!e)return this.media_;if(this.state===`HAVE_NOTHING`)throw Error(`Cannot switch media playlist from `+this.state);let t=this.state;if(typeof e==`string`){if(!this.mainPlaylistLoader_.main.playlists[e])throw Error(`Unknown playlist URI: `+e);e=this.mainPlaylistLoader_.main.playlists[e]}let n=!this.media_||e.id!==this.media_.id;if(n&&this.loadedPlaylists_[e.id]&&this.loadedPlaylists_[e.id].endList){this.state=`HAVE_METADATA`,this.media_=e,n&&(this.trigger(`mediachanging`),this.trigger(`mediachange`));return}n&&(this.media_&&this.trigger(`mediachanging`),this.addSidxSegments_(e,t,n=>{this.haveMetadata({startingState:t,playlist:e})}))}haveMetadata({startingState:e,playlist:t}){this.state=`HAVE_METADATA`,this.loadedPlaylists_[t.id]=t,I.default.clearTimeout(this.mediaRequest_),this.mediaRequest_=null,this.refreshMedia_(t.id),e===`HAVE_MAIN_MANIFEST`?this.trigger(`loadedmetadata`):this.trigger(`mediachange`)}pause(){this.isPaused_=!0,this.mainPlaylistLoader_.createMupOnMedia_&&(this.off(`loadedmetadata`,this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.stopRequest(),I.default.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.isMain_&&(I.default.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_),this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_=null),this.state===`HAVE_NOTHING`&&(this.started=!1)}load(e){this.isPaused_=!1,I.default.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null;let t=this.media();if(e){let e=t?t.targetDuration/2*1e3:5*1e3;this.mediaUpdateTimeout=I.default.setTimeout(()=>this.load(),e);return}if(!this.started){this.start();return}t&&!t.endList?(this.isMain_&&!this.minimumUpdatePeriodTimeout_&&(this.trigger(`minimumUpdatePeriod`),this.updateMinimumUpdatePeriodTimeout_()),this.trigger(`mediaupdatetimeout`)):this.trigger(`loadedplaylist`)}start(){if(this.started=!0,!this.isMain_){I.default.clearTimeout(this.mediaRequest_),this.mediaRequest_=I.default.setTimeout(()=>this.haveMain_(),0);return}this.requestMain_((e,t)=>{this.haveMain_(),!this.hasPendingRequest()&&!this.media_&&this.media(this.mainPlaylistLoader_.main.playlists[0])})}requestMain_(e){let t={manifestInfo:{uri:this.mainPlaylistLoader_.srcUrl}};this.trigger({type:`manifestrequeststart`,metadata:t}),this.request=this.vhs_.xhr({uri:this.mainPlaylistLoader_.srcUrl,withCredentials:this.withCredentials,requestType:`dash-manifest`},(n,r)=>{if(n){let{requestType:e}=r;n.metadata=bu({requestType:e,request:r,error:n})}if(this.requestErrored_(n,r)){this.state===`HAVE_NOTHING`&&(this.started=!1);return}this.trigger({type:`manifestrequestcomplete`,metadata:t});let i=r.responseText!==this.mainPlaylistLoader_.mainXml_;if(this.mainPlaylistLoader_.mainXml_=r.responseText,r.responseHeaders&&r.responseHeaders.date?this.mainLoaded_=Date.parse(r.responseHeaders.date):this.mainLoaded_=Date.now(),this.mainPlaylistLoader_.srcUrl=yl(this.mainPlaylistLoader_.srcUrl,r),i){this.handleMain_(),this.syncClientServerClock_(()=>e(r,i));return}return e(r,i)})}syncClientServerClock_(e){let t=jn(this.mainPlaylistLoader_.mainXml_);if(t===null)return this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e();if(t.method===`DIRECT`)return this.mainPlaylistLoader_.clientOffset_=t.value-Date.now(),e();this.request=this.vhs_.xhr({uri:vl(this.mainPlaylistLoader_.srcUrl,t.value),method:t.method,withCredentials:this.withCredentials,requestType:`dash-clock-sync`},(n,r)=>{if(!this.request)return;if(n){let{requestType:t}=r;return this.error.metadata=bu({requestType:t,request:r,error:n}),this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e()}let i;i=t.method===`HEAD`?!r.responseHeaders||!r.responseHeaders.date?this.mainLoaded_:Date.parse(r.responseHeaders.date):Date.parse(r.responseText),this.mainPlaylistLoader_.clientOffset_=i-Date.now(),e()})}haveMain_(){this.state=`HAVE_MAIN_MANIFEST`,this.isMain_?this.trigger(`loadedplaylist`):this.media_||this.media(this.childPlaylist_)}handleMain_(){I.default.clearTimeout(this.mediaRequest_),this.mediaRequest_=null;let e=this.mainPlaylistLoader_.main,t={manifestInfo:{uri:this.mainPlaylistLoader_.srcUrl}};this.trigger({type:`manifestparsestart`,metadata:t});let n;try{n=pd({mainXml:this.mainPlaylistLoader_.mainXml_,srcUrl:this.mainPlaylistLoader_.srcUrl,clientOffset:this.mainPlaylistLoader_.clientOffset_,sidxMapping:this.mainPlaylistLoader_.sidxMapping_,previousManifest:e})}catch(e){this.error=e,this.error.metadata={errorType:W.Error.StreamingDashManifestParserError,error:e},this.trigger(`error`)}e&&(n=hd(e,n,this.mainPlaylistLoader_.sidxMapping_)),this.mainPlaylistLoader_.main=n||e;let r=this.mainPlaylistLoader_.main.locations&&this.mainPlaylistLoader_.main.locations[0];if(r&&r!==this.mainPlaylistLoader_.srcUrl&&(this.mainPlaylistLoader_.srcUrl=r),(!e||n&&n.minimumUpdatePeriod!==e.minimumUpdatePeriod)&&this.updateMinimumUpdatePeriodTimeout_(),this.addEventStreamToMetadataTrack_(n),n){let{duration:e,endList:r}=n,i=[];n.playlists.forEach(e=>{i.push({id:e.id,bandwidth:e.attributes.BANDWIDTH,resolution:e.attributes.RESOLUTION,codecs:e.attributes.CODECS})}),t.parsedManifest={duration:e,isLive:!r,renditions:i},this.trigger({type:`manifestparsecomplete`,metadata:t})}return!!n}updateMinimumUpdatePeriodTimeout_(){let e=this.mainPlaylistLoader_;e.createMupOnMedia_&&=(e.off(`loadedmetadata`,e.createMupOnMedia_),null),e.minimumUpdatePeriodTimeout_&&=(I.default.clearTimeout(e.minimumUpdatePeriodTimeout_),null);let t=e.main&&e.main.minimumUpdatePeriod;if(t===0&&(e.media()?t=e.media().targetDuration*1e3:(e.createMupOnMedia_=e.updateMinimumUpdatePeriodTimeout_,e.one(`loadedmetadata`,e.createMupOnMedia_))),typeof t!=`number`||t<=0){t<0&&this.logger_(`found invalid minimumUpdatePeriod of ${t}, not setting a timeout`);return}this.createMUPTimeout_(t)}createMUPTimeout_(e){let t=this.mainPlaylistLoader_;t.minimumUpdatePeriodTimeout_=I.default.setTimeout(()=>{t.minimumUpdatePeriodTimeout_=null,t.trigger(`minimumUpdatePeriod`),t.createMUPTimeout_(e)},e)}refreshXml_(){this.requestMain_((e,t)=>{t&&(this.media_&&=this.mainPlaylistLoader_.main.playlists[this.media_.id],this.mainPlaylistLoader_.sidxMapping_=vd(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.sidxMapping_),this.addSidxSegments_(this.media(),this.state,e=>{this.refreshMedia_(this.media().id)}))})}refreshMedia_(e){if(!e)throw Error(`refreshMedia_ must take a media id`);this.media_&&this.isMain_&&this.handleMain_();let t=this.mainPlaylistLoader_.main.playlists,n=!this.media_||this.media_!==t[e];if(n?this.media_=t[e]:this.trigger(`playlistunchanged`),!this.mediaUpdateTimeout){let e=()=>{this.media().endList||(this.mediaUpdateTimeout=I.default.setTimeout(()=>{this.trigger(`mediaupdatetimeout`),e()},Iu(this.media(),!!n)))};e()}this.trigger(`loadedplaylist`)}addEventStreamToMetadataTrack_(e){if(e&&this.mainPlaylistLoader_.main.eventStream){let e=this.mainPlaylistLoader_.main.eventStream.map(e=>({cueTime:e.start,frames:[{data:e.messageData}]}));this.addMetadataToTextTrack(`EventStream`,e,this.mainPlaylistLoader_.main.duration)}}getKeyIdSet(e){if(e.contentProtection){let t=new Set;for(let n in e.contentProtection){let r=e.contentProtection[n].attributes[`cenc:default_KID`];r&&t.add(r.replace(/-/g,``).toLowerCase())}return t}}},bd={GOAL_BUFFER_LENGTH:30,MAX_GOAL_BUFFER_LENGTH:60,BACK_BUFFER_LENGTH:30,GOAL_BUFFER_LENGTH_RATE:1,INITIAL_BANDWIDTH:4194304,BANDWIDTH_VARIANCE:1.2,BUFFER_LOW_WATER_LINE:0,MAX_BUFFER_LOW_WATER_LINE:30,EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:16,BUFFER_LOW_WATER_LINE_RATE:1,BUFFER_HIGH_WATER_LINE:30},xd=e=>{let t=new Uint8Array(new ArrayBuffer(e.length));for(let n=0;n-1):!1},this.trigger=function(t){var n=e[t],r,i,a;if(n)if(arguments.length===2)for(i=n.length,r=0;r`u`)){for(e in O)O.hasOwnProperty(e)&&(O[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);k=new Uint8Array([105,115,111,109]),j=new Uint8Array([97,118,99,49]),A=new Uint8Array([0,0,0,1]),M=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),N=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]),ee={video:M,audio:N},ne=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),te=new Uint8Array([0,0,0,0,0,0,0,0]),re=new Uint8Array([0,0,0,0,0,0,0,0]),ie=re,F=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),ae=re,P=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])}})(),o=function(e){var t=[],n=0,r,i,a;for(r=1;r>>1,e.samplingfrequencyindex<<7|e.channelcount<<3,6,1,2]))},l=function(){return o(O.ftyp,k,A,k,j)},x=function(e){return o(O.hdlr,ee[e])},u=function(e){return o(O.mdat,e)},b=function(e){var t=new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,0,1,95,144,e.duration>>>24&255,e.duration>>>16&255,e.duration>>>8&255,e.duration&255,85,196,0,0]);return e.samplerate&&(t[12]=e.samplerate>>>24&255,t[13]=e.samplerate>>>16&255,t[14]=e.samplerate>>>8&255,t[15]=e.samplerate&255),o(O.mdhd,t)},y=function(e){return o(O.mdia,b(e),x(e.type),f(e))},d=function(e){return o(O.mfhd,new Uint8Array([0,0,0,0,(e&4278190080)>>24,(e&16711680)>>16,(e&65280)>>8,e&255]))},f=function(e){return o(O.minf,e.type===`video`?o(O.vmhd,P):o(O.smhd,te),s(),C(e))},p=function(e,t){for(var n=[],r=t.length;r--;)n[r]=T(t[r]);return o.apply(null,[O.moof,d(e)].concat(n))},m=function(e){for(var t=e.length,n=[];t--;)n[t]=_(e[t]);return o.apply(null,[O.moov,g(4294967295)].concat(n,h(e)))},h=function(e){for(var t=e.length,n=[];t--;)n[t]=E(e[t]);return o.apply(null,[O.mvex].concat(n))},g=function(e){var t=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,0,1,95,144,(e&4278190080)>>24,(e&16711680)>>16,(e&65280)>>8,e&255,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 o(O.mvhd,t)},S=function(e){var t=e.samples||[],n=new Uint8Array(4+t.length),r,i;for(i=0;i>>8),r.push(t[a].byteLength&255),r=r.concat(Array.prototype.slice.call(t[a]));for(a=0;a>>8),i.push(n[a].byteLength&255),i=i.concat(Array.prototype.slice.call(n[a]));if(s=[O.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,(e.width&65280)>>8,e.width&255,(e.height&65280)>>8,e.height&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,19,118,105,100,101,111,106,115,45,99,111,110,116,114,105,98,45,104,108,115,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o(O.avcC,new Uint8Array([1,e.profileIdc,e.profileCompatibility,e.levelIdc,255,t.length].concat(r,[n.length],i))),o(O.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192]))],e.sarRatio){var c=e.sarRatio[0],l=e.sarRatio[1];s.push(o(O.pasp,new Uint8Array([(c&4278190080)>>24,(c&16711680)>>16,(c&65280)>>8,c&255,(l&4278190080)>>24,(l&16711680)>>16,(l&65280)>>8,l&255])))}return o.apply(null,s)},t=function(e){return o(O.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,(e.channelcount&65280)>>8,e.channelcount&255,(e.samplesize&65280)>>8,e.samplesize&255,0,0,0,0,(e.samplerate&65280)>>8,e.samplerate&255,0,0]),c(e))}})(),v=function(e){var t=new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,(e.id&4278190080)>>24,(e.id&16711680)>>16,(e.id&65280)>>8,e.id&255,0,0,0,0,(e.duration&4278190080)>>24,(e.duration&16711680)>>16,(e.duration&65280)>>8,e.duration&255,0,0,0,0,0,0,0,0,0,0,0,0,1,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,(e.width&65280)>>8,e.width&255,0,0,(e.height&65280)>>8,e.height&255,0,0]);return o(O.tkhd,t)},T=function(e){var t=o(O.tfhd,new Uint8Array([0,0,0,58,(e.id&4278190080)>>24,(e.id&16711680)>>16,(e.id&65280)>>8,e.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0])),n,r,i,s,c=Math.floor(e.baseMediaDecodeTime/a),l=Math.floor(e.baseMediaDecodeTime%a);return n=o(O.tfdt,new Uint8Array([1,0,0,0,c>>>24&255,c>>>16&255,c>>>8&255,c&255,l>>>24&255,l>>>16&255,l>>>8&255,l&255])),s=92,e.type===`audio`?(r=D(e,s),o(O.traf,t,n,r)):(i=S(e),r=D(e,i.length+s),o(O.traf,t,n,r,i))},_=function(e){return e.duration=e.duration||4294967295,o(O.trak,v(e),y(e))},E=function(e){var t=new Uint8Array([0,0,0,0,(e.id&4278190080)>>24,(e.id&16711680)>>16,(e.id&65280)>>8,e.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return e.type!==`video`&&(t[t.length-1]=0),o(O.trex,t)},(function(){var e,t,n=function(e,t){var n=0,r=0,i=0,a=0;return e.length&&(e[0].duration!==void 0&&(n=1),e[0].size!==void 0&&(r=2),e[0].flags!==void 0&&(i=4),e[0].compositionTimeOffset!==void 0&&(a=8)),[0,0,n|r|i|a,1,(e.length&4278190080)>>>24,(e.length&16711680)>>>16,(e.length&65280)>>>8,e.length&255,(t&4278190080)>>>24,(t&16711680)>>>16,(t&65280)>>>8,t&255]};t=function(e,t){var r,i,a,s=e.samples||[],c,l;for(t+=20+16*s.length,a=n(s,t),i=new Uint8Array(a.length+s.length*16),i.set(a),r=a.length,l=0;l>>24,i[r++]=(c.duration&16711680)>>>16,i[r++]=(c.duration&65280)>>>8,i[r++]=c.duration&255,i[r++]=(c.size&4278190080)>>>24,i[r++]=(c.size&16711680)>>>16,i[r++]=(c.size&65280)>>>8,i[r++]=c.size&255,i[r++]=c.flags.isLeading<<2|c.flags.dependsOn,i[r++]=c.flags.isDependedOn<<6|c.flags.hasRedundancy<<4|c.flags.paddingValue<<1|c.flags.isNonSyncSample,i[r++]=c.flags.degradationPriority&61440,i[r++]=c.flags.degradationPriority&15,i[r++]=(c.compositionTimeOffset&4278190080)>>>24,i[r++]=(c.compositionTimeOffset&16711680)>>>16,i[r++]=(c.compositionTimeOffset&65280)>>>8,i[r++]=c.compositionTimeOffset&255;return o(O.trun,i)},e=function(e,t){var r,i,a,s=e.samples||[],c,l;for(t+=20+8*s.length,a=n(s,t),r=new Uint8Array(a.length+s.length*8),r.set(a),i=a.length,l=0;l>>24,r[i++]=(c.duration&16711680)>>>16,r[i++]=(c.duration&65280)>>>8,r[i++]=c.duration&255,r[i++]=(c.size&4278190080)>>>24,r[i++]=(c.size&16711680)>>>16,r[i++]=(c.size&65280)>>>8,r[i++]=c.size&255;return o(O.trun,r)},D=function(n,r){return n.type===`audio`?e(n,r):t(n,r)}})();var oe={ftyp:l,mdat:u,moof:p,moov:m,initSegment:function(e){var t=l(),n=m(e),r=new Uint8Array(t.byteLength+n.byteLength);return r.set(t),r.set(n,t.byteLength),r}},se=function(e){var t,n,r=[],i=[];for(i.byteLength=0,i.nalCount=0,i.duration=0,r.byteLength=0,t=0;t1&&(t=e.shift(),e.byteLength-=t.byteLength,e.nalCount-=t.nalCount,e[0][0].dts=t.dts,e[0][0].pts=t.pts,e[0][0].duration+=t.duration),e},ue=function(){return{size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0,isNonSyncSample:1}}},de=function(e,t){var n=ue();return n.dataOffset=t,n.compositionTimeOffset=e.pts-e.dts,n.duration=e.duration,n.size=4*e.length,n.size+=e.byteLength,e.keyFrame&&(n.flags.dependsOn=2,n.flags.isNonSyncSample=0),n},fe={groupNalsIntoFrames:se,groupFramesIntoGops:ce,extendFirstKeyFrame:le,generateSampleTable:function(e,t){var n,r,i,a,o,s=t||0,c=[];for(n=0;nCe.ONE_SECOND_IN_TS/2))){for(l=Se()[e.samplerate],l||=t[0].data,u=0;u=n?e:(t.minSegmentDts=1/0,e.filter(function(e){return e.dts>=n?(t.minSegmentDts=Math.min(t.minSegmentDts,e.dts),t.minSegmentPts=t.minSegmentDts,!0):!1}))},generateSampleTable:function(e){var t,n,r=[];for(t=0;t=this.virtualRowCount&&typeof this.beforeRowOverflow==`function`&&this.beforeRowOverflow(e),this.rows.length>0&&(this.rows.push(``),this.rowIdx++);this.rows.length>this.virtualRowCount;)this.rows.shift(),this.rowIdx--},Le.prototype.isEmpty=function(){return this.rows.length===0?!0:this.rows.length===1?this.rows[0]===``:!1},Le.prototype.addText=function(e){this.rows[this.rowIdx]+=e},Le.prototype.backspace=function(){if(!this.isEmpty()){var e=this.rows[this.rowIdx];this.rows[this.rowIdx]=e.substr(0,e.length-1)}};var Re=function(e,t,n){this.serviceNum=e,this.text=``,this.currentWindow=new Le(-1),this.windows=[],this.stream=n,typeof t==`string`&&this.createTextDecoder(t)};Re.prototype.init=function(e,t){this.startPts=e;for(var n=0;n<8;n++)this.windows[n]=new Le(n),typeof t==`function`&&(this.windows[n].beforeRowOverflow=t)},Re.prototype.setCurrentWindow=function(e){this.currentWindow=this.windows[e]},Re.prototype.createTextDecoder=function(e){if(typeof TextDecoder>`u`)this.stream.trigger(`log`,{level:`warn`,message:"The `encoding` option is unsupported without TextDecoder support"});else try{this.textDecoder_=new TextDecoder(e)}catch(t){this.stream.trigger(`log`,{level:`warn`,message:`TextDecoder could not be created with `+e+` encoding. `+t})}};var ze=function(e){e||={},ze.prototype.init.call(this);var t=this,n=e.captionServices||{},r={},i;Object.keys(n).forEach(e=>{i=n[e],/^SERVICE/.test(e)&&(r[e]=i.encoding)}),this.serviceEncodings=r,this.current708Packet=null,this.services={},this.push=function(e){e.type===3?(t.new708Packet(),t.add708Bytes(e)):(t.current708Packet===null&&t.new708Packet(),t.add708Bytes(e))}};ze.prototype=new je,ze.prototype.new708Packet=function(){this.current708Packet!==null&&this.push708Packet(),this.current708Packet={data:[],ptsVals:[]}},ze.prototype.add708Bytes=function(e){var t=e.ccData,n=t>>>8,r=t&255;this.current708Packet.ptsVals.push(e.pts),this.current708Packet.data.push(n),this.current708Packet.data.push(r)},ze.prototype.push708Packet=function(){var e=this.current708Packet,t=e.data,n=null,r=null,i=0,a=t[i++];for(e.seq=a>>6,e.sizeCode=a&63;i>5,r=a&31,n===7&&r>0&&(a=t[i++],n=a),this.pushServiceBlock(n,i,r),r>0&&(i+=r-1)},ze.prototype.pushServiceBlock=function(e,t,n){var r,i=t,a=this.current708Packet.data,o=this.services[e];for(o||=this.initService(e,i);i(`0`+(e&255).toString(16)).slice(-2)).join(``)}if(i?(d=[s,c],e++):d=[s],t.textDecoder_&&!r)u=t.textDecoder_.decode(new Uint8Array(d));else if(i){let e=f(d);u=String.fromCharCode(parseInt(e,16))}else u=Fe(o|s);return l.pendingNewLine&&!l.isEmpty()&&l.newLine(this.getPts(e)),l.pendingNewLine=!1,l.addText(u),e},ze.prototype.multiByteCharacter=function(e,t){var n=this.current708Packet.data,r=n[e+1],i=n[e+2];return Ie(r)&&Ie(i)&&(e=this.handleText(++e,t,{isMultiByte:!0})),e},ze.prototype.setCurrentWindow=function(e,t){var n=this.current708Packet.data[e]&7;return t.setCurrentWindow(n),e},ze.prototype.defineWindow=function(e,t){var n=this.current708Packet.data,r=n[e],i=r&7;t.setCurrentWindow(i);var a=t.currentWindow;return r=n[++e],a.visible=(r&32)>>5,a.rowLock=(r&16)>>4,a.columnLock=(r&8)>>3,a.priority=r&7,r=n[++e],a.relativePositioning=(r&128)>>7,a.anchorVertical=r&127,r=n[++e],a.anchorHorizontal=r,r=n[++e],a.anchorPoint=(r&240)>>4,a.rowCount=r&15,r=n[++e],a.columnCount=r&63,r=n[++e],a.windowStyle=(r&56)>>3,a.penStyle=r&7,a.virtualRowCount=a.rowCount+1,e},ze.prototype.setWindowAttributes=function(e,t){var n=this.current708Packet.data,r=n[e],i=t.currentWindow.winAttr;return r=n[++e],i.fillOpacity=(r&192)>>6,i.fillRed=(r&48)>>4,i.fillGreen=(r&12)>>2,i.fillBlue=r&3,r=n[++e],i.borderType=(r&192)>>6,i.borderRed=(r&48)>>4,i.borderGreen=(r&12)>>2,i.borderBlue=r&3,r=n[++e],i.borderType+=(r&128)>>5,i.wordWrap=(r&64)>>6,i.printDirection=(r&48)>>4,i.scrollDirection=(r&12)>>2,i.justify=r&3,r=n[++e],i.effectSpeed=(r&240)>>4,i.effectDirection=(r&12)>>2,i.displayEffect=r&3,e},ze.prototype.flushDisplayed=function(e,t){for(var n=[],r=0;r<8;r++)t.windows[r].visible&&!t.windows[r].isEmpty()&&n.push(t.windows[r].getText());t.endPts=e,t.text=n.join(` `),this.pushCaption(t),t.startPts=e},ze.prototype.pushCaption=function(e){e.text!==``&&(this.trigger(`data`,{startPts:e.startPts,endPts:e.endPts,text:e.text,stream:`cc708_`+e.serviceNum}),e.text=``,e.startPts=e.endPts)},ze.prototype.displayWindows=function(e,t){var n=this.current708Packet.data[++e],r=this.getPts(e);this.flushDisplayed(r,t);for(var i=0;i<8;i++)n&1<>4,i.offset=(r&12)>>2,i.penSize=r&3,r=n[++e],i.italics=(r&128)>>7,i.underline=(r&64)>>6,i.edgeType=(r&56)>>3,i.fontStyle=r&7,e},ze.prototype.setPenColor=function(e,t){var n=this.current708Packet.data,r=n[e],i=t.currentWindow.penColor;return r=n[++e],i.fgOpacity=(r&192)>>6,i.fgRed=(r&48)>>4,i.fgGreen=(r&12)>>2,i.fgBlue=r&3,r=n[++e],i.bgOpacity=(r&192)>>6,i.bgRed=(r&48)>>4,i.bgGreen=(r&12)>>2,i.bgBlue=r&3,r=n[++e],i.edgeRed=(r&48)>>4,i.edgeGreen=(r&12)>>2,i.edgeBlue=r&3,e},ze.prototype.setPenLocation=function(e,t){var n=this.current708Packet.data,r=n[e],i=t.currentWindow.penLoc;return t.currentWindow.pendingNewLine=!0,r=n[++e],i.row=r&15,r=n[++e],i.column=r&63,e},ze.prototype.reset=function(e,t){var n=this.getPts(e);return this.flushDisplayed(n,t),this.initService(t.serviceNum,e)};var Be={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,304:174,305:176,306:189,307:191,308:8482,309:162,310:163,311:9834,312:224,313:160,314:232,315:226,316:234,317:238,318:244,319:251,544:193,545:201,546:211,547:218,548:220,549:252,550:8216,551:161,552:42,553:39,554:8212,555:169,556:8480,557:8226,558:8220,559:8221,560:192,561:194,562:199,563:200,564:202,565:203,566:235,567:206,568:207,569:239,570:212,571:217,572:249,573:219,574:171,575:187,800:195,801:227,802:205,803:204,804:236,805:210,806:242,807:213,808:245,809:123,810:125,811:92,812:94,813:95,814:124,815:126,816:196,817:228,818:214,819:246,820:223,821:165,822:164,823:9474,824:197,825:229,826:216,827:248,828:9484,829:9488,830:9492,831:9496},Ve=function(e){return e===null?``:(e=Be[e]||e,String.fromCharCode(e))},He=14,Ue=[4352,4384,4608,4640,5376,5408,5632,5664,5888,5920,4096,4864,4896,5120,5152],We=function(){for(var e=[],t=He+1;t--;)e.push({text:``,indent:0,offset:0});return e},Ge=function(e,t){Ge.prototype.init.call(this),this.field_=e||0,this.dataChannel_=t||0,this.name_=`CC`+((this.field_<<1|this.dataChannel_)+1),this.setConstants(),this.reset(),this.push=function(e){var t=e.ccData&32639,n,r,i,a;if(t===this.lastControlCode_){this.lastControlCode_=null;return}if((t&61440)==4096?this.lastControlCode_=t:t!==this.PADDING_&&(this.lastControlCode_=null),r=t>>>8,i=t&255,t!==this.PADDING_)if(t===this.RESUME_CAPTION_LOADING_)this.mode_=`popOn`;else if(t===this.END_OF_CAPTION_)this.mode_=`popOn`,this.clearFormatting(e.pts),this.flushDisplayed(e.pts),n=this.displayed_,this.displayed_=this.nonDisplayed_,this.nonDisplayed_=n,this.startPts_=e.pts;else if(t===this.ROLL_UP_2_ROWS_)this.rollUpRows_=2,this.setRollUp(e.pts);else if(t===this.ROLL_UP_3_ROWS_)this.rollUpRows_=3,this.setRollUp(e.pts);else if(t===this.ROLL_UP_4_ROWS_)this.rollUpRows_=4,this.setRollUp(e.pts);else if(t===this.CARRIAGE_RETURN_)this.clearFormatting(e.pts),this.flushDisplayed(e.pts),this.shiftRowsUp_(),this.startPts_=e.pts;else if(t===this.BACKSPACE_)this.mode_===`popOn`?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1);else if(t===this.ERASE_DISPLAYED_MEMORY_)this.flushDisplayed(e.pts),this.displayed_=We();else if(t===this.ERASE_NON_DISPLAYED_MEMORY_)this.nonDisplayed_=We();else if(t===this.RESUME_DIRECT_CAPTIONING_)this.mode_!==`paintOn`&&(this.flushDisplayed(e.pts),this.displayed_=We()),this.mode_=`paintOn`,this.startPts_=e.pts;else if(this.isSpecialCharacter(r,i))r=(r&3)<<8,a=Ve(r|i),this[this.mode_](e.pts,a),this.column_++;else if(this.isExtCharacter(r,i))this.mode_===`popOn`?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1),r=(r&3)<<8,a=Ve(r|i),this[this.mode_](e.pts,a),this.column_++;else if(this.isMidRowCode(r,i))this.clearFormatting(e.pts),this[this.mode_](e.pts,` `),this.column_++,(i&14)==14&&this.addFormatting(e.pts,[`i`]),(i&1)==1&&this.addFormatting(e.pts,[`u`]);else if(this.isOffsetControlCode(r,i)){let e=i&3;this.nonDisplayed_[this.row_].offset=e,this.column_+=e}else if(this.isPAC(r,i)){var o=Ue.indexOf(t&7968);if(this.mode_===`rollUp`&&(o-this.rollUpRows_+1<0&&(o=this.rollUpRows_-1),this.setRollUp(e.pts,o)),o!==this.row_&&o>=0&&o<=14&&(this.clearFormatting(e.pts),this.row_=o),i&1&&this.formatting_.indexOf(`u`)===-1&&this.addFormatting(e.pts,[`u`]),(t&16)==16){let e=(t&14)>>1;this.column_=e*4,this.nonDisplayed_[this.row_].indent+=e}this.isColorPAC(i)&&(i&14)==14&&this.addFormatting(e.pts,[`i`])}else this.isNormalChar(r)&&(i===0&&(i=null),a=Ve(r),a+=Ve(i),this[this.mode_](e.pts,a),this.column_+=a.length)}};Ge.prototype=new je,Ge.prototype.flushDisplayed=function(e){let t=e=>{this.trigger(`log`,{level:`warn`,message:`Skipping a malformed 608 caption at index `+e+`.`})},n=[];this.displayed_.forEach((e,r)=>{if(e&&e.text&&e.text.length){try{e.text=e.text.trim()}catch{t(r)}e.text.length&&n.push({text:e.text,line:r+1,position:10+Math.min(70,e.indent*10)+e.offset*2.5})}else e??t(r)}),n.length&&this.trigger(`data`,{startPts:this.startPts_,endPts:e,content:n,stream:this.name_})},Ge.prototype.reset=function(){this.mode_=`popOn`,this.topRow_=0,this.startPts_=0,this.displayed_=We(),this.nonDisplayed_=We(),this.lastControlCode_=null,this.column_=0,this.row_=He,this.rollUpRows_=2,this.formatting_=[]},Ge.prototype.setConstants=function(){this.dataChannel_===0?(this.BASE_=16,this.EXT_=17,this.CONTROL_=(20|this.field_)<<8,this.OFFSET_=23):this.dataChannel_===1&&(this.BASE_=24,this.EXT_=25,this.CONTROL_=(28|this.field_)<<8,this.OFFSET_=31),this.PADDING_=0,this.RESUME_CAPTION_LOADING_=this.CONTROL_|32,this.END_OF_CAPTION_=this.CONTROL_|47,this.ROLL_UP_2_ROWS_=this.CONTROL_|37,this.ROLL_UP_3_ROWS_=this.CONTROL_|38,this.ROLL_UP_4_ROWS_=this.CONTROL_|39,this.CARRIAGE_RETURN_=this.CONTROL_|45,this.RESUME_DIRECT_CAPTIONING_=this.CONTROL_|41,this.BACKSPACE_=this.CONTROL_|33,this.ERASE_DISPLAYED_MEMORY_=this.CONTROL_|44,this.ERASE_NON_DISPLAYED_MEMORY_=this.CONTROL_|46},Ge.prototype.isSpecialCharacter=function(e,t){return e===this.EXT_&&t>=48&&t<=63},Ge.prototype.isExtCharacter=function(e,t){return(e===this.EXT_+1||e===this.EXT_+2)&&t>=32&&t<=63},Ge.prototype.isMidRowCode=function(e,t){return e===this.EXT_&&t>=32&&t<=47},Ge.prototype.isOffsetControlCode=function(e,t){return e===this.OFFSET_&&t>=33&&t<=35},Ge.prototype.isPAC=function(e,t){return e>=this.BASE_&&e=64&&t<=127},Ge.prototype.isColorPAC=function(e){return e>=64&&e<=79||e>=96&&e<=127},Ge.prototype.isNormalChar=function(e){return e>=32&&e<=127},Ge.prototype.setRollUp=function(e,t){if(this.mode_!==`rollUp`&&(this.row_=He,this.mode_=`rollUp`,this.flushDisplayed(e),this.nonDisplayed_=We(),this.displayed_=We()),t!==void 0&&t!==this.row_)for(var n=0;n`},``);this[this.mode_](e,n)},Ge.prototype.clearFormatting=function(e){if(this.formatting_.length){var t=this.formatting_.reverse().reduce(function(e,t){return e+``},``);this.formatting_=[],this[this.mode_](e,t)}},Ge.prototype.popOn=function(e,t){var n=this.nonDisplayed_[this.row_].text;n+=t,this.nonDisplayed_[this.row_].text=n},Ge.prototype.rollUp=function(e,t){var n=this.displayed_[this.row_].text;n+=t,this.displayed_[this.row_].text=n},Ge.prototype.shiftRowsUp_=function(){var e;for(e=0;et&&(n=-1);Math.abs(t-e)>Ye;)e+=n*z;return e},Qe=function(e){var t,n;Qe.prototype.init.call(this),this.type_=e||Xe,this.push=function(e){if(e.type===`metadata`){this.trigger(`data`,e);return}this.type_!==Xe&&e.type!==this.type_||(n===void 0&&(n=e.dts),e.dts=Ze(e.dts,n),e.pts=Ze(e.pts,n),t=e.dts,this.trigger(`data`,e))},this.flush=function(){n=t,this.trigger(`done`)},this.endTimeline=function(){this.flush(),this.trigger(`endedtimeline`)},this.discontinuity=function(){n=void 0,t=void 0},this.reset=function(){this.discontinuity(),this.trigger(`reset`)}};Qe.prototype=new Je;var $e={TimestampRolloverStream:Qe,handleRollover:Ze},et={typedArrayIndexOf:(e,t,n)=>{if(!e)return-1;for(var r=n;r`?e.url=it(e.data,t,e.data.length):e.pictureData=e.data.subarray(t,e.data.length))))},"T*":function(e){e.data[0]===tt.Utf8&&(e.value=rt(e.data,1,e.data.length).replace(/\0*$/,``),e.values=e.value.split(`\0`))},TXXX:function(e){var t;e.data[0]===tt.Utf8&&(t=et(e.data,0,1),t!==-1&&(e.description=rt(e.data,1,t),e.value=rt(e.data,t+1,e.data.length).replace(/\0*$/,``),e.data=e.value))},"W*":function(e){e.url=it(e.data,0,e.data.length).replace(/\0.*$/,``)},WXXX:function(e){var t;e.data[0]===tt.Utf8&&(t=et(e.data,0,1),t!==-1&&(e.description=rt(e.data,1,t),e.url=it(e.data,t+1,e.data.length).replace(/\0.*$/,``)))},PRIV:function(e){var t;for(t=0;t>>2;d*=4,d+=u[7]&3,s.timeStamp=d,t.pts===void 0&&t.dts===void 0&&(t.pts=s.timeStamp,t.dts=s.timeStamp),this.trigger(`timestamp`,s)}t.frames.push(s),a+=10,a+=o}while(a>>4>1&&(r+=t[r]+1),n.pid===0)n.type=`pat`,e(t.subarray(r),n),this.trigger(`data`,n);else if(n.pid===this.pmtPid)for(n.type=`pmt`,e(t.subarray(r),n),this.trigger(`data`,n);this.packetsWaitingForPmt.length;)this.processPes_.apply(this,this.packetsWaitingForPmt.shift());else this.programMapTable===void 0?this.packetsWaitingForPmt.push([t,r,n]):this.processPes_(t,r,n)},this.processPes_=function(e,t,n){n.pid===this.programMapTable.video?n.streamType=ht.H264_STREAM_TYPE:n.pid===this.programMapTable.audio?n.streamType=ht.ADTS_STREAM_TYPE:n.streamType=this.programMapTable[`timed-metadata`][n.pid],n.type=`pes`,n.data=e.subarray(t),this.trigger(`data`,n)}},vt.prototype=new pt,vt.STREAM_TYPES={h264:27,adts:15},yt=function(){var e=this,t=!1,n={data:[],size:0},r={data:[],size:0},i={data:[],size:0},a,o=function(e,t){var n;let r=e[0]<<16|e[1]<<8|e[2];t.data=new Uint8Array,r===1&&(t.packetLength=6+(e[4]<<8|e[5]),t.dataAlignmentIndicator=(e[6]&4)!=0,n=e[7],n&192&&(t.pts=(e[9]&14)<<27|(e[10]&255)<<20|(e[11]&254)<<12|(e[12]&255)<<5|(e[13]&254)>>>3,t.pts*=4,t.pts+=(e[13]&6)>>>1,t.dts=t.pts,n&64&&(t.dts=(e[14]&14)<<27|(e[15]&255)<<20|(e[16]&254)<<12|(e[17]&255)<<5|(e[18]&254)>>>3,t.dts*=4,t.dts+=(e[18]&6)>>>1)),t.data=e.subarray(9+e[8]))},s=function(t,n,r){var i=new Uint8Array(t.size),a={type:n},s=0,c=0,l=!1,u;if(!(!t.data.length||t.size<9)){for(a.trackId=t.data[0].pid,s=0;s>5,c=((t[i+6]&3)+1)*1024,l=c*Et/Ot[(t[i+2]&60)>>>2],t.byteLength-i>>6&3)+1,channelcount:(t[i+2]&1)<<2|(t[i+3]&192)>>>6,samplerate:Ot[(t[i+2]&60)>>>2],samplingfrequencyindex:(t[i+2]&60)>>>2,samplesize:16,data:t.subarray(i+7+o,i+a)}),n++,i+=a}typeof u==`number`&&(this.skipWarn_(u,i),u=null),t=t.subarray(i)}},this.flush=function(){n=0,this.trigger(`done`)},this.reset=function(){t=void 0,this.trigger(`reset`)},this.endTimeline=function(){t=void 0,this.trigger(`endedtimeline`)}},Dt.prototype=new Tt;var kt=Dt,At=function(e){var t=e.byteLength,n=0,r=0;this.length=function(){return 8*t},this.bitsAvailable=function(){return 8*t+r},this.loadWord=function(){var i=e.byteLength-t,a=new Uint8Array(4),o=Math.min(4,t);if(o===0)throw Error(`no bytes available`);a.set(e.subarray(i,i+o)),n=new DataView(a.buffer).getUint32(0),r=o*8,t-=o},this.skipBits=function(e){var i;r>e?(n<<=e,r-=e):(e-=r,i=Math.floor(e/8),e-=i*8,t-=i,this.loadWord(),n<<=e,r-=e)},this.readBits=function(e){var i=Math.min(r,e),a=n>>>32-i;return r-=i,r>0?n<<=i:t>0&&this.loadWord(),i=e-i,i>0?a<>>e)return n<<=e,r-=e,e;return this.loadWord(),e+this.skipLeadingZeros()},this.skipUnsignedExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.skipExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.readUnsignedExpGolomb=function(){var e=this.skipLeadingZeros();return this.readBits(e+1)-1},this.readExpGolomb=function(){var e=this.readUnsignedExpGolomb();return 1&e?1+e>>>1:-1*(e>>>1)},this.readBoolean=function(){return this.readBits(1)===1},this.readUnsignedByte=function(){return this.readBits(8)},this.loadWord()},jt=n,Mt=At,Nt,Pt=function(){var e=0,t,n;Pt.prototype.init.call(this),this.push=function(r){var i;n?(i=new Uint8Array(n.byteLength+r.data.byteLength),i.set(n),i.set(r.data,n.byteLength),n=i):n=r.data;for(var a=n.byteLength;e3&&this.trigger(`data`,n.subarray(e+3)),n=null,e=0,this.trigger(`done`)},this.endTimeline=function(){this.flush(),this.trigger(`endedtimeline`)}},Ft;Pt.prototype=new jt,Ft={100:!0,110:!0,122:!0,244:!0,44:!0,83:!0,86:!0,118:!0,128:!0,138:!0,139:!0,134:!0},Nt=function(){var e=new Pt,t,n,r,i,a,o,s;Nt.prototype.init.call(this),t=this,this.push=function(t){t.type===`video`&&(n=t.trackId,r=t.pts,i=t.dts,e.push(t))},e.on(`data`,function(e){var s={trackId:n,pts:r,dts:i,data:e,nalUnitTypeCode:e[0]&31};switch(s.nalUnitTypeCode){case 5:s.nalUnitType=`slice_layer_without_partitioning_rbsp_idr`;break;case 6:s.nalUnitType=`sei_rbsp`,s.escapedRBSP=a(e.subarray(1));break;case 7:s.nalUnitType=`seq_parameter_set_rbsp`,s.escapedRBSP=a(e.subarray(1)),s.config=o(s.escapedRBSP);break;case 8:s.nalUnitType=`pic_parameter_set_rbsp`;break;case 9:s.nalUnitType=`access_unit_delimiter_rbsp`;break}t.trigger(`data`,s)}),e.on(`done`,function(){t.trigger(`done`)}),e.on(`partialdone`,function(){t.trigger(`partialdone`)}),e.on(`reset`,function(){t.trigger(`reset`)}),e.on(`endedtimeline`,function(){t.trigger(`endedtimeline`)}),this.flush=function(){e.flush()},this.partialFlush=function(){e.partialFlush()},this.reset=function(){e.reset()},this.endTimeline=function(){e.endTimeline()},s=function(e,t){var n=8,r=8,i,a;for(i=0;i>4;return n=n>=0?n:0,r?n+20:n+10},zt=function(e,t){return e.length-t<10||e[t]!==73||e[t+1]!==68||e[t+2]!==51?t:(t+=Rt(e,t),zt(e,t))},Bt=function(e){var t=zt(e,0);return e.length>=t+2&&(e[t]&255)==255&&(e[t+1]&240)==240&&(e[t+1]&22)==16},Vt=function(e){return e[0]<<21|e[1]<<14|e[2]<<7|e[3]},Ht=function(e,t,n){var r,i=``;for(r=t;r>5,r=e[t+4]<<3;return e[t+3]&6144|r|n},parseType:function(e,t){return e[t]===73&&e[t+1]===68&&e[t+2]===51?`timed-metadata`:e[t]&!0&&(e[t+1]&240)==240?`audio`:null},parseSampleRate:function(e){for(var t=0;t+5>>2]}return null},parseAacTimestamp:function(e){var t=10,n,r,i;e[5]&64&&(t+=4,t+=Vt(e.subarray(10,14)));do{if(n=Vt(e.subarray(t+4,t+8)),n<1)return null;if(i=String.fromCharCode(e[t],e[t+1],e[t+2],e[t+3]),i===`PRIV`){r=e.subarray(t+10,t+n+10);for(var a=0;a>>2;return s*=4,s+=o[7]&3,s}break}}t+=10,t+=n}while(t=3;){if(e[i]===73&&e[i+1]===68&&e[i+2]===51){if(e.length-i<10||(r=Kt.parseId3TagSize(e,i),i+r>e.length))break;o={type:`timed-metadata`,data:e.subarray(i,i+r)},this.trigger(`data`,o),i+=r;continue}else if((e[i]&255)==255&&(e[i+1]&240)==240){if(e.length-i<7||(r=Kt.parseAdtsSize(e,i),i+r>e.length))break;s={type:`audio`,data:e.subarray(i,i+r),pts:t,dts:t},this.trigger(`data`,s),i+=r;continue}i++}a=e.length-i,e=a>0?e.subarray(i):new Uint8Array},this.reset=function(){e=new Uint8Array,this.trigger(`reset`)},this.endTimeline=function(){e=new Uint8Array,this.trigger(`endedtimeline`)}};qt.prototype=new Gt;var Jt=qt,Yt=[`audioobjecttype`,`channelcount`,`samplerate`,`samplingfrequencyindex`,`samplesize`],Xt=[`width`,`height`,`profileIdc`,`levelIdc`,`profileCompatibility`,`sarRatio`],Zt=n,Qt=oe,$t=fe,en=Te,tn=De,nn=wt,rn=xe,an=kt,on=It.H264Stream,sn=Jt,cn=Wt.isLikelyAacData,ln=xe.ONE_SECOND_IN_TS,un=Yt,dn=Xt,fn,pn,mn,hn,gn=function(e,t){t.stream=e,this.trigger(`log`,t)},_n=function(e,t){for(var n=Object.keys(t),r=0;r=-r&&a<=n&&(!o||i>a)&&(o=c,i=a)));return o?o.gop:null},this.alignGopsAtStart_=function(e){var t,n,r,a,o=e.byteLength,s=e.nalCount,c=e.duration,l;for(t=n=0;tr.pts){t++;continue}n++,o-=a.byteLength,s-=a.nalCount,c-=a.duration}return n===0?e:n===e.length?null:(l=e.slice(n),l.byteLength=o,l.duration=c,l.nalCount=s,l.pts=l[0].pts,l.dts=l[0].dts,l)},this.alignGopsAtEnd_=function(e){for(var t=i.length-1,n=e.length-1,r,a,o=null,s=!1;t>=0&&n>=0;){if(r=i[t],a=e[n],r.pts===a.pts){s=!0;break}if(r.pts>a.pts){t--;continue}t===i.length-1&&(o=n),n--}if(!s&&o===null)return null;var c=s?n:o;if(c===0)return e;var l=e.slice(c),u=l.reduce(function(e,t){return e.byteLength+=t.byteLength,e.duration+=t.duration,e.nalCount+=t.nalCount,e},{byteLength:0,duration:0,nalCount:0});return l.byteLength=u.byteLength,l.duration=u.duration,l.nalCount=u.nalCount,l.pts=l[0].pts,l.dts=l[0].dts,l},this.alignGopsWith=function(e){i=e}},fn.prototype=new Zt,hn=function(e,t){this.numberOfTracks=0,this.metadataStream=t,e||={},e.remux===void 0?this.remuxTracks=!0:this.remuxTracks=!!e.remux,typeof e.keepOriginalTimestamps==`boolean`?this.keepOriginalTimestamps=e.keepOriginalTimestamps:this.keepOriginalTimestamps=!1,this.pendingTracks=[],this.videoTrack=null,this.pendingBoxes=[],this.pendingCaptions=[],this.pendingMetadata=[],this.pendingBytes=0,this.emittedTracks=0,hn.prototype.init.call(this),this.push=function(e){if(e.content||e.text)return this.pendingCaptions.push(e);if(e.frames)return this.pendingMetadata.push(e);this.pendingTracks.push(e.track),this.pendingBytes+=e.boxes.byteLength,e.track.type===`video`&&(this.videoTrack=e.track,this.pendingBoxes.push(e.boxes)),e.track.type===`audio`&&(this.audioTrack=e.track,this.pendingBoxes.unshift(e.boxes))}},hn.prototype=new Zt,hn.prototype.flush=function(e){var t=0,n={captions:[],captionStreams:{},metadata:[],info:{}},r,i,a,o=0,s;if(this.pendingTracks.length=this.numberOfTracks&&(this.trigger(`done`),this.emittedTracks=0);return}}if(this.videoTrack?(o=this.videoTrack.timelineStartInfo.pts,dn.forEach(function(e){n.info[e]=this.videoTrack[e]},this)):this.audioTrack&&(o=this.audioTrack.timelineStartInfo.pts,un.forEach(function(e){n.info[e]=this.audioTrack[e]},this)),this.videoTrack||this.audioTrack){for(this.pendingTracks.length===1?n.type=this.pendingTracks[0].type:n.type=`combined`,this.emittedTracks+=this.pendingTracks.length,a=Qt.initSegment(this.pendingTracks),n.initSegment=new Uint8Array(a.byteLength),n.initSegment.set(a),n.data=new Uint8Array(this.pendingBytes),s=0;s=this.numberOfTracks&&(this.trigger(`done`),this.emittedTracks=0)},hn.prototype.setRemux=function(e){this.remuxTracks=e},mn=function(e){var t=this,n=!0,r,i;mn.prototype.init.call(this),e||={},this.baseMediaDecodeTime=e.baseMediaDecodeTime||0,this.transmuxPipeline_={},this.setupAacPipeline=function(){var n={};this.transmuxPipeline_=n,n.type=`aac`,n.metadataStream=new nn.MetadataStream,n.aacStream=new sn,n.audioTimestampRolloverStream=new nn.TimestampRolloverStream(`audio`),n.timedMetadataTimestampRolloverStream=new nn.TimestampRolloverStream(`timed-metadata`),n.adtsStream=new an,n.coalesceStream=new hn(e,n.metadataStream),n.headOfPipeline=n.aacStream,n.aacStream.pipe(n.audioTimestampRolloverStream).pipe(n.adtsStream),n.aacStream.pipe(n.timedMetadataTimestampRolloverStream).pipe(n.metadataStream).pipe(n.coalesceStream),n.metadataStream.on(`timestamp`,function(e){n.aacStream.setTimestamp(e.timeStamp)}),n.aacStream.on(`data`,function(a){a.type!==`timed-metadata`&&a.type!==`audio`||n.audioSegmentStream||(i||={timelineStartInfo:{baseMediaDecodeTime:t.baseMediaDecodeTime},codec:`adts`,type:`audio`},n.coalesceStream.numberOfTracks++,n.audioSegmentStream=new pn(i,e),n.audioSegmentStream.on(`log`,t.getLogTrigger_(`audioSegmentStream`)),n.audioSegmentStream.on(`timingInfo`,t.trigger.bind(t,`audioTimingInfo`)),n.adtsStream.pipe(n.audioSegmentStream).pipe(n.coalesceStream),t.trigger(`trackinfo`,{hasAudio:!!i,hasVideo:!!r}))}),n.coalesceStream.on(`data`,this.trigger.bind(this,`data`)),n.coalesceStream.on(`done`,this.trigger.bind(this,`done`)),_n(this,n)},this.setupTsPipeline=function(){var n={};this.transmuxPipeline_=n,n.type=`ts`,n.metadataStream=new nn.MetadataStream,n.packetStream=new nn.TransportPacketStream,n.parseStream=new nn.TransportParseStream,n.elementaryStream=new nn.ElementaryStream,n.timestampRolloverStream=new nn.TimestampRolloverStream,n.adtsStream=new an,n.h264Stream=new on,n.captionStream=new nn.CaptionStream(e),n.coalesceStream=new hn(e,n.metadataStream),n.headOfPipeline=n.packetStream,n.packetStream.pipe(n.parseStream).pipe(n.elementaryStream).pipe(n.timestampRolloverStream),n.timestampRolloverStream.pipe(n.h264Stream),n.timestampRolloverStream.pipe(n.adtsStream),n.timestampRolloverStream.pipe(n.metadataStream).pipe(n.coalesceStream),n.h264Stream.pipe(n.captionStream).pipe(n.coalesceStream),n.elementaryStream.on(`data`,function(a){var o;if(a.type===`metadata`){for(o=a.tracks.length;o--;)!r&&a.tracks[o].type===`video`?(r=a.tracks[o],r.timelineStartInfo.baseMediaDecodeTime=t.baseMediaDecodeTime):!i&&a.tracks[o].type===`audio`&&(i=a.tracks[o],i.timelineStartInfo.baseMediaDecodeTime=t.baseMediaDecodeTime);r&&!n.videoSegmentStream&&(n.coalesceStream.numberOfTracks++,n.videoSegmentStream=new fn(r,e),n.videoSegmentStream.on(`log`,t.getLogTrigger_(`videoSegmentStream`)),n.videoSegmentStream.on(`timelineStartInfo`,function(r){i&&!e.keepOriginalTimestamps&&(i.timelineStartInfo=r,n.audioSegmentStream.setEarliestDts(r.dts-t.baseMediaDecodeTime))}),n.videoSegmentStream.on(`processedGopsInfo`,t.trigger.bind(t,`gopInfo`)),n.videoSegmentStream.on(`segmentTimingInfo`,t.trigger.bind(t,`videoSegmentTimingInfo`)),n.videoSegmentStream.on(`baseMediaDecodeTime`,function(e){i&&n.audioSegmentStream.setVideoBaseMediaDecodeTime(e)}),n.videoSegmentStream.on(`timingInfo`,t.trigger.bind(t,`videoTimingInfo`)),n.h264Stream.pipe(n.videoSegmentStream).pipe(n.coalesceStream)),i&&!n.audioSegmentStream&&(n.coalesceStream.numberOfTracks++,n.audioSegmentStream=new pn(i,e),n.audioSegmentStream.on(`log`,t.getLogTrigger_(`audioSegmentStream`)),n.audioSegmentStream.on(`timingInfo`,t.trigger.bind(t,`audioTimingInfo`)),n.audioSegmentStream.on(`segmentTimingInfo`,t.trigger.bind(t,`audioSegmentTimingInfo`)),n.adtsStream.pipe(n.audioSegmentStream).pipe(n.coalesceStream)),t.trigger(`trackinfo`,{hasAudio:!!i,hasVideo:!!r})}}),n.coalesceStream.on(`data`,this.trigger.bind(this,`data`)),n.coalesceStream.on(`id3Frame`,function(e){e.dispatchType=n.metadataStream.dispatchType,t.trigger(`id3Frame`,e)}),n.coalesceStream.on(`caption`,this.trigger.bind(this,`caption`)),n.coalesceStream.on(`done`,this.trigger.bind(this,`done`)),_n(this,n)},this.setBaseMediaDecodeTime=function(t){var n=this.transmuxPipeline_;e.keepOriginalTimestamps||(this.baseMediaDecodeTime=t),i&&(i.timelineStartInfo.dts=void 0,i.timelineStartInfo.pts=void 0,tn.clearDtsInfo(i),n.audioTimestampRolloverStream&&n.audioTimestampRolloverStream.discontinuity()),r&&(n.videoSegmentStream&&(n.videoSegmentStream.gopCache_=[]),r.timelineStartInfo.dts=void 0,r.timelineStartInfo.pts=void 0,tn.clearDtsInfo(r),n.captionStream.reset()),n.timestampRolloverStream&&n.timestampRolloverStream.discontinuity()},this.setAudioAppendStart=function(e){i&&this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(e)},this.setRemux=function(t){var n=this.transmuxPipeline_;e.remux=t,n&&n.coalesceStream&&n.coalesceStream.setRemux(t)},this.alignGopsWith=function(e){r&&this.transmuxPipeline_.videoSegmentStream&&this.transmuxPipeline_.videoSegmentStream.alignGopsWith(e)},this.getLogTrigger_=function(e){var t=this;return function(n){n.stream=e,t.trigger(`log`,n)}},this.push=function(e){if(n){var t=cn(e);t&&this.transmuxPipeline_.type!==`aac`?this.setupAacPipeline():!t&&this.transmuxPipeline_.type!==`ts`&&this.setupTsPipeline(),n=!1}this.transmuxPipeline_.headOfPipeline.push(e)},this.flush=function(){n=!0,this.transmuxPipeline_.headOfPipeline.flush()},this.endTimeline=function(){this.transmuxPipeline_.headOfPipeline.endTimeline()},this.reset=function(){this.transmuxPipeline_.headOfPipeline&&this.transmuxPipeline_.headOfPipeline.reset()},this.resetCaptions=function(){this.transmuxPipeline_.captionStream&&this.transmuxPipeline_.captionStream.reset()}},mn.prototype=new Zt;var bn={Transmuxer:mn,VideoSegmentStream:fn,AudioSegmentStream:pn,AUDIO_PROPERTIES:un,VIDEO_PROPERTIES:dn,generateSegmentTimingInfo:yn},xn={toUnsigned:function(e){return e>>>0},toHexString:function(e){return(`00`+e.toString(16)).slice(-2)}},Sn=function(e){var t=``;return t+=String.fromCharCode(e[0]),t+=String.fromCharCode(e[1]),t+=String.fromCharCode(e[2]),t+=String.fromCharCode(e[3]),t},Cn=xn.toUnsigned,wn=Sn,Tn=function(e,t){var n=[],r,i,a,o,s;if(!t.length)return null;for(r=0;r1?r+i:e.byteLength,a===t[0]&&(t.length===1?n.push(e.subarray(r+8,o)):(s=Tn(e.subarray(r+8,o),t.slice(1)),s.length&&(n=n.concat(s)))),r=o;return n},En=Tn,Dn=xn.toUnsigned,On=i.getUint64,kn=function(e){var t={version:e[0],flags:new Uint8Array(e.subarray(1,4))};return t.version===1?t.baseMediaDecodeTime=On(e.subarray(4)):t.baseMediaDecodeTime=Dn(e[4]<<24|e[5]<<16|e[6]<<8|e[7]),t},An=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),n={version:e[0],flags:new Uint8Array(e.subarray(1,4)),trackId:t.getUint32(4)},r=n.flags[2]&1,i=n.flags[2]&2,a=n.flags[2]&8,o=n.flags[2]&16,s=n.flags[2]&32,c=n.flags[0]&65536,l=n.flags[0]&131072,u=8;return r&&(u+=4,n.baseDataOffset=t.getUint32(12),u+=4),i&&(n.sampleDescriptionIndex=t.getUint32(u),u+=4),a&&(n.defaultSampleDuration=t.getUint32(u),u+=4),o&&(n.defaultSampleSize=t.getUint32(u),u+=4),s&&(n.defaultSampleFlags=t.getUint32(u)),c&&(n.durationIsEmpty=!0),!r&&l&&(n.baseDataOffsetIsMoof=!0),n},jn=i.getUint64,Mn=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),n={version:e[0],flags:new Uint8Array(e.subarray(1,4)),references:[],referenceId:t.getUint32(4),timescale:t.getUint32(8)},r=12;n.version===0?(n.earliestPresentationTime=t.getUint32(r),n.firstOffset=t.getUint32(r+4),r+=8):(n.earliestPresentationTime=jn(e.subarray(r)),n.firstOffset=jn(e.subarray(r+8)),r+=16),r+=2;var i=t.getUint16(r);for(r+=2;i>0;r+=12,i--)n.references.push({referenceType:(e[r]&128)>>>7,referencedSize:t.getUint32(r)&2147483647,subsegmentDuration:t.getUint32(r+4),startsWithSap:!!(e[r+8]&128),sapType:(e[r+8]&112)>>>4,sapDeltaTime:t.getUint32(r+8)&268435455});return n},Nn=function(e){return{isLeading:(e[0]&12)>>>2,dependsOn:e[0]&3,isDependedOn:(e[1]&192)>>>6,hasRedundancy:(e[1]&48)>>>4,paddingValue:(e[1]&14)>>>1,isNonSyncSample:e[1]&1,degradationPriority:e[2]<<8|e[3]}},Pn=function(e){var t={version:e[0],flags:new Uint8Array(e.subarray(1,4)),samples:[]},n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=t.flags[2]&1,i=t.flags[2]&4,a=t.flags[1]&1,o=t.flags[1]&2,s=t.flags[1]&4,c=t.flags[1]&8,l=n.getUint32(4),u=8,d;for(r&&(t.dataOffset=n.getInt32(u),u+=4),i&&l&&(d={flags:Nn(e.subarray(u,u+4))},u+=4,a&&(d.duration=n.getUint32(u),u+=4),o&&(d.size=n.getUint32(u),u+=4),c&&(t.version===1?d.compositionTimeOffset=n.getInt32(u):d.compositionTimeOffset=n.getUint32(u),u+=4),t.samples.push(d),l--);l--;)d={},a&&(d.duration=n.getUint32(u),u+=4),o&&(d.size=n.getUint32(u),u+=4),s&&(d.flags=Nn(e.subarray(u,u+4)),u+=4),c&&(t.version===1?d.compositionTimeOffset=n.getInt32(u):d.compositionTimeOffset=n.getUint32(u),u+=4),t.samples.push(d);return t},Fn=i.getUint64,In,Ln,Rn=function(e){return new Date(e*1e3-20828448e5)},zn=Sn,Bn=En,Vn=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=[],r,i;for(r=0;r+4MALFORMED DATA`);continue}switch(e[r]&31){case 1:n.push(`slice_layer_without_partitioning_rbsp`);break;case 5:n.push(`slice_layer_without_partitioning_rbsp_idr`);break;case 6:n.push(`sei_rbsp`);break;case 7:n.push(`seq_parameter_set_rbsp`);break;case 8:n.push(`pic_parameter_set_rbsp`);break;case 9:n.push(`access_unit_delimiter_rbsp`);break;default:n.push(`UNKNOWN NAL - `+e[r]&31);break}}return n},Hn={avc1:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{dataReferenceIndex:t.getUint16(6),width:t.getUint16(24),height:t.getUint16(26),horizresolution:t.getUint16(28)+t.getUint16(30)/16,vertresolution:t.getUint16(32)+t.getUint16(34)/16,frameCount:t.getUint16(40),depth:t.getUint16(74),config:In(e.subarray(78,e.byteLength))}},avcC:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),n={configurationVersion:e[0],avcProfileIndication:e[1],profileCompatibility:e[2],avcLevelIndication:e[3],lengthSizeMinusOne:e[4]&3,sps:[],pps:[]},r=e[5]&31,i,a,o=6,s;for(s=0;s>>2&63,bufferSize:e[13]<<16|e[14]<<8|e[15],maxBitrate:e[16]<<24|e[17]<<16|e[18]<<8|e[19],avgBitrate:e[20]<<24|e[21]<<16|e[22]<<8|e[23],decoderConfigDescriptor:{tag:e[24],length:e[25],audioObjectType:e[26]>>>3&31,samplingFrequencyIndex:(e[26]&7)<<1|e[27]>>>7&1,channelConfiguration:e[27]>>>3&15}}}},ftyp:function(e){for(var t=new DataView(e.buffer,e.byteOffset,e.byteLength),n={majorBrand:zn(e.subarray(0,4)),minorVersion:t.getUint32(4),compatibleBrands:[]},r=8;r>10)+96),i.language+=String.fromCharCode(((r&992)>>5)+96),i.language+=String.fromCharCode((r&31)+96),i},mdia:function(e){return{boxes:In(e)}},mfhd:function(e){return{version:e[0],flags:new Uint8Array(e.subarray(1,4)),sequenceNumber:e[4]<<24|e[5]<<16|e[6]<<8|e[7]}},minf:function(e){return{boxes:In(e)}},mp4a:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),n={dataReferenceIndex:t.getUint16(6),channelcount:t.getUint16(16),samplesize:t.getUint16(18),samplerate:t.getUint16(24)+t.getUint16(26)/65536};return e.byteLength>28&&(n.streamDescriptor=In(e.subarray(28))[0]),n},moof:function(e){return{boxes:In(e)}},moov:function(e){return{boxes:In(e)}},mvex:function(e){return{boxes:In(e)}},mvhd:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=4,r={version:t.getUint8(0),flags:new Uint8Array(e.subarray(1,4))};return r.version===1?(n+=4,r.creationTime=Rn(t.getUint32(n)),n+=8,r.modificationTime=Rn(t.getUint32(n)),n+=4,r.timescale=t.getUint32(n),n+=8,r.duration=t.getUint32(n)):(r.creationTime=Rn(t.getUint32(n)),n+=4,r.modificationTime=Rn(t.getUint32(n)),n+=4,r.timescale=t.getUint32(n),n+=4,r.duration=t.getUint32(n)),n+=4,r.rate=t.getUint16(n)+t.getUint16(n+2)/16,n+=4,r.volume=t.getUint8(n)+t.getUint8(n+1)/8,n+=2,n+=2,n+=8,r.matrix=new Uint32Array(e.subarray(n,n+36)),n+=36,n+=24,r.nextTrackId=t.getUint32(n),r},pdin:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{version:t.getUint8(0),flags:new Uint8Array(e.subarray(1,4)),rate:t.getUint32(4),initialDelay:t.getUint32(8)}},sdtp:function(e){var t={version:e[0],flags:new Uint8Array(e.subarray(1,4)),samples:[]},n;for(n=4;n>4,isDependedOn:(e[n]&12)>>2,hasRedundancy:e[n]&3});return t},sidx:Mn,smhd:function(e){return{version:e[0],flags:new Uint8Array(e.subarray(1,4)),balance:e[4]+e[5]/256}},stbl:function(e){return{boxes:In(e)}},ctts:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),n={version:t.getUint8(0),flags:new Uint8Array(e.subarray(1,4)),compositionOffsets:[]},r=t.getUint32(4),i;for(i=8;r;i+=8,r--)n.compositionOffsets.push({sampleCount:t.getUint32(i),sampleOffset:t[n.version===0?`getUint32`:`getInt32`](i+4)});return n},stss:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),n={version:t.getUint8(0),flags:new Uint8Array(e.subarray(1,4)),syncSamples:[]},r=t.getUint32(4),i;for(i=8;r;i+=4,r--)n.syncSamples.push(t.getUint32(i));return n},stco:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),n={version:e[0],flags:new Uint8Array(e.subarray(1,4)),chunkOffsets:[]},r=t.getUint32(4),i;for(i=8;r;i+=4,r--)n.chunkOffsets.push(t.getUint32(i));return n},stsc:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(4),r={version:e[0],flags:new Uint8Array(e.subarray(1,4)),sampleToChunks:[]},i;for(i=8;n;i+=12,n--)r.sampleToChunks.push({firstChunk:t.getUint32(i),samplesPerChunk:t.getUint32(i+4),sampleDescriptionIndex:t.getUint32(i+8)});return r},stsd:function(e){return{version:e[0],flags:new Uint8Array(e.subarray(1,4)),sampleDescriptions:In(e.subarray(8))}},stsz:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),n={version:e[0],flags:new Uint8Array(e.subarray(1,4)),sampleSize:t.getUint32(4),entries:[]},r;for(r=12;r>6,sampleHasRedundancy:(e[21]&48)>>4,samplePaddingValue:(e[21]&14)>>1,sampleIsDifferenceSample:!!(e[21]&1),sampleDegradationPriority:t.getUint16(22)}},trun:Pn,"url ":function(e){return{version:e[0],flags:new Uint8Array(e.subarray(1,4))}},vmhd:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{version:e[0],flags:new Uint8Array(e.subarray(1,4)),graphicsmode:t.getUint16(4),opcolor:new Uint16Array([t.getUint16(6),t.getUint16(8),t.getUint16(10)])}}};In=function(e){for(var t=0,n=[],r,i,a,o,s,c=new ArrayBuffer(e.length),l=new Uint8Array(c),u=0;u1?t+i:e.byteLength,s=(Hn[a]||function(e){return{data:e}})(e.subarray(t+8,o)),s.size=i,s.type=a,n.push(s),t=o;return n},Ln=function(e,t){var n;return t||=0,n=Array(t*2+1).join(` `),e.map(function(e,r){return n+e.type+` `+Object.keys(e).filter(function(e){return e!==`type`&&e!==`boxes`}).map(function(t){var r=n+` `+t+`: `,i=e[t];if(i instanceof Uint8Array||i instanceof Uint32Array){var a=Array.prototype.slice.call(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)).map(function(e){return` `+(`00`+e.toString(16)).slice(-2)}).join(``).match(/.{1,24}/g);return a?a.length===1?r+`<`+a.join(``).slice(1)+`>`:r+`< `+a.map(function(e){return n+` `+e}).join(` `)+` `+n+` >`:r+`<>`}return r+JSON.stringify(i,null,2).split(` `).map(function(e,t){return t===0?e:n+` `+e}).join(` `)}).join(` `)+(e.boxes?` `+Ln(e.boxes,t+1):``)}).join(` `)};var Un={inspect:In,textify:Ln,parseType:zn,findBox:Bn,parseTraf:Hn.traf,parseTfdt:Hn.tfdt,parseHdlr:Hn.hdlr,parseTfhd:Hn.tfhd,parseTrun:Hn.trun,parseSidx:Hn.sidx},Wn={uint8ToCString:function(e){for(var t=0,n=String.fromCharCode(e[t]),r=``;n!==`\0`;)r+=n,t++,n=String.fromCharCode(e[t]);return r+=n,r}}.uint8ToCString,Gn=i.getUint64,Kn=function(e){var t=4,n=e[0],r,i,a,o,s,c,l,u;if(n===0){r=Wn(e.subarray(t)),t+=r.length,i=Wn(e.subarray(t)),t+=i.length;var d=new DataView(e.buffer);a=d.getUint32(t),t+=4,s=d.getUint32(t),t+=4,c=d.getUint32(t),t+=4,l=d.getUint32(t),t+=4}else if(n===1){var d=new DataView(e.buffer);a=d.getUint32(t),t+=4,o=Gn(e.subarray(t)),t+=8,c=d.getUint32(t),t+=4,l=d.getUint32(t),t+=4,r=Wn(e.subarray(t)),t+=r.length,i=Wn(e.subarray(t)),t+=i.length}u=new Uint8Array(e.subarray(t,e.byteLength));var f={scheme_id_uri:r,value:i,timescale:a||1,presentation_time:o,presentation_time_delta:s,event_duration:c,id:l,message_data:u};return Jn(n,f)?f:void 0},qn=function(e,t,n,r){return e||e===0?e/t:r+n/t},Jn=function(e,t){var n=t.scheme_id_uri!==`\0`,r=e===0&&Yn(t.presentation_time_delta)&&n,i=e===1&&Yn(t.presentation_time)&&n;return!(e>1)&&r||i},Yn=function(e){return e!==void 0||e!==null},Xn={parseEmsgBox:Kn,scaleTime:qn},Zn=typeof window<`u`?window:e===void 0?typeof self<`u`?self:{}:e,Qn=xn.toUnsigned,$n=xn.toHexString,er=En,tr=Sn,nr=Xn,rr=An,ir=Pn,ar=kn,or=i.getUint64,sr,cr,lr,ur,dr,fr,pr,mr=Zn,hr=st.parseId3Frames;sr=function(e){return er(e,[`moov`,`trak`]).reduce(function(e,t){var n=er(t,[`tkhd`])[0],r,i,a,o;return!n||(r=n[0],i=r===0?12:20,a=Qn(n[i]<<24|n[i+1]<<16|n[i+2]<<8|n[i+3]),o=er(t,[`mdia`,`mdhd`])[0],!o)?null:(r=o[0],i=r===0?12:20,e[a]=Qn(o[i]<<24|o[i+1]<<16|o[i+2]<<8|o[i+3]),e)},{})},cr=function(e,t){var n=er(t,[`moof`,`traf`]).reduce(function(t,n){var r=er(n,[`tfhd`])[0],i=e[Qn(r[4]<<24|r[5]<<16|r[6]<<8|r[7])]||9e4,a=er(n,[`tfdt`])[0],o=new DataView(a.buffer,a.byteOffset,a.byteLength),s=a[0]===1?or(a.subarray(4,12)):o.getUint32(4);let c;return typeof s==`bigint`?c=s/mr.BigInt(i):typeof s==`number`&&!isNaN(s)&&(c=s/i),c<2**53-1&&(c=Number(c)),c11?(t.codec+=`.`,t.codec+=$n(d[9]),t.codec+=$n(d[10]),t.codec+=$n(d[11])):t.codec=`avc1.4d400d`):/^mp4[a,v]$/i.test(t.codec)?(d=u.subarray(28),f=tr(d.subarray(4,8)),f===`esds`&&d.length>20&&d[19]!==0?(t.codec+=`.`+$n(d[19]),t.codec+=`.`+$n(d[20]>>>2&63).replace(/^0/,``)):t.codec=`mp4a.40.2`):t.codec=t.codec.toLowerCase())}var p=er(e,[`mdia`,`mdhd`])[0];p&&(t.timescale=fr(p)),n.push(t)}),n},pr=function(e,t=0){return er(e,[`emsg`]).map(e=>{var n=nr.parseEmsgBox(new Uint8Array(e)),r=hr(n.message_data);return{cueTime:nr.scaleTime(n.presentation_time,n.timescale,n.presentation_time_delta,t),duration:nr.scaleTime(n.event_duration,n.timescale),frames:r}})};var gr={findBox:er,parseType:tr,timescale:sr,startTime:cr,compositionStartTime:lr,videoTrackIds:ur,tracks:dr,getTimescaleFromMediaHeader:fr,getEmsgID3:pr};let{parseTrun:_r}=Un,{findBox:vr}=gr;var yr=Zn,br={getMdatTrafPairs:function(e){var t=vr(e,[`moof`,`traf`]),n=vr(e,[`mdat`]),r=[];return n.forEach(function(e,n){var i=t[n];r.push({mdat:e,traf:i})}),r},parseSamples:function(e,t,n){var r=t,i=n.defaultSampleDuration||0,a=n.defaultSampleSize||0,o=n.trackId,s=[];return e.forEach(function(e){var t=_r(e).samples;t.forEach(function(e){e.duration===void 0&&(e.duration=i),e.size===void 0&&(e.size=a),e.trackId=o,e.dts=r,e.compositionTimeOffset===void 0&&(e.compositionTimeOffset=0),typeof r==`bigint`?(e.pts=r+yr.BigInt(e.compositionTimeOffset),r+=yr.BigInt(e.duration)):(e.pts=r+e.compositionTimeOffset,r+=e.duration)}),s=s.concat(t)}),s}},xr=Ae.discardEmulationPreventionBytes,Sr=Ke.CaptionStream,B=En,Cr=kn,wr=An,{getMdatTrafPairs:Tr,parseSamples:Er}=br,Dr=function(e,t){for(var n=e,r=0;r0?Cr(s[0]).baseMediaDecodeTime:0,l=B(i,[`trun`]),u,d;t===o&&l.length>0&&(u=Er(l,c,a),d=Or(r,u,o),n[o]||(n[o]={seiNals:[],logs:[]}),n[o].seiNals=n[o].seiNals.concat(d.seiNals),n[o].logs=n[o].logs.concat(d.logs))}),n},Ar=function(e,t,n){var r;if(t===null)return null;r=kr(e,t);var i=r[t]||{};return{seiNals:i.seiNals,logs:i.logs,timescale:n}},jr=function(){var e=!1,t,n,r,i,a,o;this.isInitialized=function(){return e},this.init=function(n){t=new Sr,e=!0,o=n?n.isPartial:!1,t.on(`data`,function(e){e.startTime=e.startPts/i,e.endTime=e.endPts/i,a.captions.push(e),a.captionStreams[e.stream]=!0}),t.on(`log`,function(e){a.logs.push(e)})},this.isNewInit=function(e,t){return e&&e.length===0||t&&typeof t==`object`&&Object.keys(t).length===0?!1:r!==e[0]||i!==t[r]},this.parse=function(e,t,o){var s;if(!this.isInitialized()||!t||!o)return null;if(this.isNewInit(t,o))r=t[0],i=o[r];else if(r===null||!i)return n.push(e),null;for(;n.length>0;){var c=n.shift();this.parse(c,t,o)}return s=Ar(e,r,i),s&&s.logs&&(a.logs=a.logs.concat(s.logs)),s===null||!s.seiNals?a.logs.length?{logs:a.logs,captions:[],captionStreams:[]}:null:(this.pushNals(s.seiNals),this.flushStream(),a)},this.pushNals=function(e){if(!this.isInitialized()||!e||e.length===0)return null;e.forEach(function(e){t.push(e)})},this.flushStream=function(){if(!this.isInitialized())return null;o?t.partialFlush():t.flush()},this.clearParsedCaptions=function(){a.captions=[],a.captionStreams={},a.logs=[]},this.resetCaptionStream=function(){if(!this.isInitialized())return null;t.reset()},this.clearAllCaptions=function(){this.clearParsedCaptions(),this.resetCaptionStream()},this.reset=function(){n=[],r=null,i=null,a?this.clearParsedCaptions():a={captions:[],captionStreams:{},logs:[]},this.resetCaptionStream()},this.reset()};let{parseTfdt:Mr}=Un,Nr=En,{getTimescaleFromMediaHeader:Pr}=gr,{parseSamples:Fr,getMdatTrafPairs:Ir}=br;var Lr=function(){let e=9e4;this.init=function(t){let n=Nr(t,[`moov`,`trak`,`mdia`,`mdhd`])[0];n&&(e=Pr(n))},this.parseSegment=function(t){let n=[],r=Ir(t),i=0;return r.forEach(function(t){let r=t.mdat,a=t.traf,o=Nr(a,[`tfdt`])[0],s=Nr(a,[`tfhd`])[0],c=Nr(a,[`trun`]);if(o&&(i=Mr(o).baseMediaDecodeTime),c.length&&s){let t=Fr(c,i,s),a=0;t.forEach(function(t){let i=new TextDecoder(`utf-8`),o=r.slice(a,a+t.size);if(Nr(o,[`vtte`])[0]){a+=t.size;return}Nr(o,[`vttc`]).forEach(function(r){let a=Nr(r,[`payl`])[0],o=Nr(r,[`sttg`])[0],s=t.pts/e,c=(t.pts+t.duration)/e,l,u;if(a)try{l=i.decode(a)}catch(e){console.error(e)}if(o)try{u=i.decode(o)}catch(e){console.error(e)}t.duration&&l&&n.push({cueText:l,start:s,end:c,settings:u})}),a+=t.size})}}),n}},Rr=qe,zr=function(e){var t=e[1]&31;return t<<=8,t|=e[2],t},Br=function(e){return!!(e[1]&64)},Vr=function(e){var t=0;return(e[3]&48)>>>4>1&&(t+=e[4]+1),t},Hr=function(e,t){var n=zr(e);return n===0?`pat`:n===t?`pmt`:t?`pes`:null},Ur=function(e){var t=Br(e),n=4+Vr(e);return t&&(n+=e[n]+1),(e[n+10]&31)<<8|e[n+11]},Wr=function(e){var t={},n=Br(e),r=4+Vr(e);if(n&&(r+=e[r]+1),e[r+5]&1){for(var i=3+((e[r+1]&15)<<8|e[r+2])-4,a=12+((e[r+10]&15)<<8|e[r+11]);a=e.byteLength)return null;var n=null,r=e[t+7];return r&192&&(n={},n.pts=(e[t+9]&14)<<27|(e[t+10]&255)<<20|(e[t+11]&254)<<12|(e[t+12]&255)<<5|(e[t+13]&254)>>>3,n.pts*=4,n.pts+=(e[t+13]&6)>>>1,n.dts=n.pts,r&64&&(n.dts=(e[t+14]&14)<<27|(e[t+15]&255)<<20|(e[t+16]&254)<<12|(e[t+17]&255)<<5|(e[t+18]&254)>>>3,n.dts*=4,n.dts+=(e[t+18]&6)>>>1)),n},qr=function(e){switch(e){case 5:return`slice_layer_without_partitioning_rbsp_idr`;case 6:return`sei_rbsp`;case 7:return`seq_parameter_set_rbsp`;case 8:return`pic_parameter_set_rbsp`;case 9:return`access_unit_delimiter_rbsp`;default:return null}},Jr={parseType:Hr,parsePat:Ur,parsePmt:Wr,parsePayloadUnitStartIndicator:Br,parsePesType:Gr,parsePesTime:Kr,videoPacketContainsKeyFrame:function(e){for(var t=4+Vr(e),n=e.subarray(t),r=0,i=0,a=!1,o;i3&&(o=qr(n[i+3]&31),o===`slice_layer_without_partitioning_rbsp_idr`&&(a=!0)),a}},Yr=qe,Xr=$e.handleRollover,Zr={};Zr.ts=Jr,Zr.aac=Wt;var Qr=xe.ONE_SECOND_IN_TS,$r=188,ei=71,ti=function(e,t){for(var n=0,r=$r,i,a;r=0;){if(e[r]===ei&&(e[i]===ei||i===e.byteLength)){switch(a=e.subarray(r,i),o=Zr.ts.parseType(a,t.pid),o){case`pes`:s=Zr.ts.parsePesType(a,t.table),c=Zr.ts.parsePayloadUnitStartIndicator(a),s===`audio`&&c&&(l=Zr.ts.parsePesTime(a),l&&(l.type=`audio`,n.audio.push(l),u=!0));break}if(u)break;r-=$r,i-=$r;continue}r--,i--}},ri=function(e,t,n){for(var r=0,i=$r,a,o,s,c,l,u,d,f,p=!1,m={data:[],size:0};i=0;){if(e[r]===ei&&e[i]===ei){switch(a=e.subarray(r,i),o=Zr.ts.parseType(a,t.pid),o){case`pes`:s=Zr.ts.parsePesType(a,t.table),c=Zr.ts.parsePayloadUnitStartIndicator(a),s===`video`&&c&&(l=Zr.ts.parsePesTime(a),l&&(l.type=`video`,n.video.push(l),p=!0));break}if(p)break;r-=$r,i-=$r;continue}r--,i--}},ii=function(e,t){if(e.audio&&e.audio.length){var n=t;(n===void 0||isNaN(n))&&(n=e.audio[0].dts),e.audio.forEach(function(e){e.dts=Xr(e.dts,n),e.pts=Xr(e.pts,n),e.dtsTime=e.dts/Qr,e.ptsTime=e.pts/Qr})}if(e.video&&e.video.length){var r=t;if((r===void 0||isNaN(r))&&(r=e.video[0].dts),e.video.forEach(function(e){e.dts=Xr(e.dts,r),e.pts=Xr(e.pts,r),e.dtsTime=e.dts/Qr,e.ptsTime=e.pts/Qr}),e.firstKeyFrame){var i=e.firstKeyFrame;i.dts=Xr(i.dts,r),i.pts=Xr(i.pts,r),i.dtsTime=i.dts/Qr,i.ptsTime=i.pts/Qr}}},ai=function(e){for(var t=!1,n=0,r=null,i=null,a=0,o=0,s;e.length-o>=3;){switch(Zr.aac.parseType(e,o)){case`timed-metadata`:if(e.length-o<10){t=!0;break}if(a=Zr.aac.parseId3TagSize(e,o),a>e.length){t=!0;break}i===null&&(s=e.subarray(o,o+a),i=Zr.aac.parseAacTimestamp(s)),o+=a;break;case`audio`:if(e.length-o<7){t=!0;break}if(a=Zr.aac.parseAdtsSize(e,o),a>e.length){t=!0;break}r===null&&(s=e.subarray(o,o+a),r=Zr.aac.parseSampleRate(s)),n++,o+=a;break;default:o++;break}if(t)return null}if(r===null||i===null)return null;var c=Qr/r;return{audio:[{type:`audio`,dts:i,pts:i},{type:`audio`,dts:i+n*1024*c,pts:i+n*1024*c}]}},oi=function(e){var t={pid:null,table:null},n={};for(var r in ti(e,t),t.table)if(t.table.hasOwnProperty(r))switch(t.table[r]){case Yr.H264_STREAM_TYPE:n.video=[],ri(e,t,n),n.video.length===0&&delete n.video;break;case Yr.ADTS_STREAM_TYPE:n.audio=[],ni(e,t,n),n.audio.length===0&&delete n.audio;break}return n},si={inspect:function(e,t){var n=Zr.aac.isLikelyAacData(e)?ai(e):oi(e);return!n||!n.audio&&!n.video?null:(ii(n,t),n)},parseAudioPes_:ni};let ci=function(e,t){t.on(`data`,function(t){let n=t.initSegment;t.initSegment={data:n.buffer,byteOffset:n.byteOffset,byteLength:n.byteLength};let r=t.data;t.data=r.buffer,e.postMessage({action:`data`,segment:t,byteOffset:r.byteOffset,byteLength:r.byteLength},[t.data])}),t.on(`done`,function(t){e.postMessage({action:`done`})}),t.on(`gopInfo`,function(t){e.postMessage({action:`gopInfo`,gopInfo:t})}),t.on(`videoSegmentTimingInfo`,function(t){let n={start:{decode:xe.videoTsToSeconds(t.start.dts),presentation:xe.videoTsToSeconds(t.start.pts)},end:{decode:xe.videoTsToSeconds(t.end.dts),presentation:xe.videoTsToSeconds(t.end.pts)},baseMediaDecodeTime:xe.videoTsToSeconds(t.baseMediaDecodeTime)};t.prependedContentDuration&&(n.prependedContentDuration=xe.videoTsToSeconds(t.prependedContentDuration)),e.postMessage({action:`videoSegmentTimingInfo`,videoSegmentTimingInfo:n})}),t.on(`audioSegmentTimingInfo`,function(t){let n={start:{decode:xe.videoTsToSeconds(t.start.dts),presentation:xe.videoTsToSeconds(t.start.pts)},end:{decode:xe.videoTsToSeconds(t.end.dts),presentation:xe.videoTsToSeconds(t.end.pts)},baseMediaDecodeTime:xe.videoTsToSeconds(t.baseMediaDecodeTime)};t.prependedContentDuration&&(n.prependedContentDuration=xe.videoTsToSeconds(t.prependedContentDuration)),e.postMessage({action:`audioSegmentTimingInfo`,audioSegmentTimingInfo:n})}),t.on(`id3Frame`,function(t){e.postMessage({action:`id3Frame`,id3Frame:t})}),t.on(`caption`,function(t){e.postMessage({action:`caption`,caption:t})}),t.on(`trackinfo`,function(t){e.postMessage({action:`trackinfo`,trackInfo:t})}),t.on(`audioTimingInfo`,function(t){e.postMessage({action:`audioTimingInfo`,audioTimingInfo:{start:xe.videoTsToSeconds(t.start),end:xe.videoTsToSeconds(t.end)}})}),t.on(`videoTimingInfo`,function(t){e.postMessage({action:`videoTimingInfo`,videoTimingInfo:{start:xe.videoTsToSeconds(t.start),end:xe.videoTsToSeconds(t.end)}})}),t.on(`log`,function(t){e.postMessage({action:`log`,log:t})})};class li{constructor(e,t){this.options=t||{},this.self=e,this.init()}init(){this.transmuxer&&this.transmuxer.dispose(),this.transmuxer=new bn.Transmuxer(this.options),ci(this.self,this.transmuxer)}pushMp4Captions(e){this.captionParser||(this.captionParser=new jr,this.captionParser.init());let t=new Uint8Array(e.data,e.byteOffset,e.byteLength),n=this.captionParser.parse(t,e.trackIds,e.timescales);this.self.postMessage({action:`mp4Captions`,captions:n&&n.captions||[],logs:n&&n.logs||[],data:t.buffer},[t.buffer])}initMp4WebVttParser(e){this.webVttParser||=new Lr;let t=new Uint8Array(e.data,e.byteOffset,e.byteLength);this.webVttParser.init(t)}getMp4WebVttText(e){this.webVttParser||=new Lr;let t=new Uint8Array(e.data,e.byteOffset,e.byteLength),n=this.webVttParser.parseSegment(t);this.self.postMessage({action:`getMp4WebVttText`,mp4VttCues:n||[],data:t.buffer},[t.buffer])}probeMp4StartTime({timescales:e,data:t}){let n=gr.startTime(e,t);this.self.postMessage({action:`probeMp4StartTime`,startTime:n,data:t},[t.buffer])}probeMp4Tracks({data:e}){let t=gr.tracks(e);this.self.postMessage({action:`probeMp4Tracks`,tracks:t,data:e},[e.buffer])}probeEmsgID3({data:e,offset:t}){let n=gr.getEmsgID3(e,t);this.self.postMessage({action:`probeEmsgID3`,id3Frames:n,emsgData:e},[e.buffer])}probeTs({data:e,baseStartTime:t}){let n=typeof t==`number`&&!isNaN(t)?t*xe.ONE_SECOND_IN_TS:void 0,r=si.inspect(e,n),i=null;r&&(i={hasVideo:r.video&&r.video.length===2||!1,hasAudio:r.audio&&r.audio.length===2||!1},i.hasVideo&&(i.videoStart=r.video[0].ptsTime),i.hasAudio&&(i.audioStart=r.audio[0].ptsTime)),this.self.postMessage({action:`probeTs`,result:i,data:e},[e.buffer])}clearAllMp4Captions(){this.captionParser&&this.captionParser.clearAllCaptions()}clearParsedMp4Captions(){this.captionParser&&this.captionParser.clearParsedCaptions()}push(e){let t=new Uint8Array(e.data,e.byteOffset,e.byteLength);this.transmuxer.push(t)}reset(){this.transmuxer.reset()}setTimestampOffset(e){let t=e.timestampOffset||0;this.transmuxer.setBaseMediaDecodeTime(Math.round(xe.secondsToVideoTs(t)))}setAudioAppendStart(e){this.transmuxer.setAudioAppendStart(Math.ceil(xe.secondsToVideoTs(e.appendStart)))}setRemux(e){this.transmuxer.setRemux(e.remux)}flush(e){this.transmuxer.flush(),self.postMessage({action:`done`,type:`transmuxed`})}endTimeline(){this.transmuxer.endTimeline(),self.postMessage({action:`endedtimeline`,type:`transmuxed`})}alignGopsWith(e){this.transmuxer.alignGopsWith(e.gopsToAlignWith.slice())}}self.onmessage=function(e){if(e.data.action===`init`&&e.data.options){this.messageHandlers=new li(self,e.data.options);return}this.messageHandlers||=new li(self),e.data&&e.data.action&&e.data.action!==`init`&&this.messageHandlers[e.data.action]&&this.messageHandlers[e.data.action](e.data)}}))),Od=(e,t,n)=>{let{type:r,initSegment:i,captions:a,captionStreams:o,metadata:s,videoFrameDtsTime:c,videoFramePtsTime:l}=e.data.segment;t.buffer.push({captions:a,captionStreams:o,metadata:s});let u=e.data.segment.boxes||{data:e.data.segment.data},d={type:r,data:new Uint8Array(u.data,u.data.byteOffset,u.data.byteLength),initSegment:new Uint8Array(i.data,i.byteOffset,i.byteLength)};c!==void 0&&(d.videoFrameDtsTime=c),l!==void 0&&(d.videoFramePtsTime=l),n(d)},kd=({transmuxedData:e,callback:t})=>{e.buffer=[],t(e)},Ad=(e,t)=>{t.gopInfo=e.data.gopInfo},jd=e=>{let{transmuxer:t,bytes:n,audioAppendStart:r,gopsToAlignWith:i,remux:a,onData:o,onTrackInfo:s,onAudioTimingInfo:c,onVideoTimingInfo:l,onVideoSegmentTimingInfo:u,onAudioSegmentTimingInfo:d,onId3:f,onCaptions:p,onDone:m,onEndedTimeline:h,onTransmuxerLog:g,isEndOfTimeline:_,segment:v,triggerSegmentEventFn:y}=e,b={buffer:[]},x=_;if(t.onmessage=n=>{t.currentTransmux===e&&(n.data.action===`data`&&Od(n,b,o),n.data.action===`trackinfo`&&s(n.data.trackInfo),n.data.action===`gopInfo`&&Ad(n,b),n.data.action===`audioTimingInfo`&&c(n.data.audioTimingInfo),n.data.action===`videoTimingInfo`&&l(n.data.videoTimingInfo),n.data.action===`videoSegmentTimingInfo`&&u(n.data.videoSegmentTimingInfo),n.data.action===`audioSegmentTimingInfo`&&d(n.data.audioSegmentTimingInfo),n.data.action===`id3Frame`&&f([n.data.id3Frame],n.data.id3Frame.dispatchType),n.data.action===`caption`&&p(n.data.caption),n.data.action===`endedtimeline`&&(x=!1,h()),n.data.action===`log`&&g(n.data.log),n.data.type===`transmuxed`&&(x||(t.onmessage=null,kd({transmuxedData:b,callback:m}),Md(t))))},t.onerror=()=>{m(null,{message:`Received an error message from the transmuxer worker`,metadata:{errorType:W.Error.StreamingFailedToTransmuxSegment,segmentInfo:Zf({segment:v})}})},r&&t.postMessage({action:`setAudioAppendStart`,appendStart:r}),Array.isArray(i)&&t.postMessage({action:`alignGopsWith`,gopsToAlignWith:i}),a!==void 0&&t.postMessage({action:`setRemux`,remux:a}),n.byteLength){let e=n instanceof ArrayBuffer?n:n.buffer,r=n instanceof ArrayBuffer?0:n.byteOffset;y({type:`segmenttransmuxingstart`,segment:v}),t.postMessage({action:`push`,data:e,byteOffset:r,byteLength:n.byteLength},[e])}_&&t.postMessage({action:`endTimeline`}),t.postMessage({action:`flush`})},Md=e=>{e.currentTransmux=null,e.transmuxQueue.length&&(e.currentTransmux=e.transmuxQueue.shift(),typeof e.currentTransmux==`function`?e.currentTransmux():jd(e.currentTransmux))},Nd=(e,t)=>{e.postMessage({action:t}),Md(e)},Pd=(e,t)=>{if(!t.currentTransmux){t.currentTransmux=e,Nd(t,e);return}t.transmuxQueue.push(Nd.bind(null,t,e))},Fd=e=>{Pd(`reset`,e)},Id=e=>{Pd(`endTimeline`,e)},Ld=e=>{if(!e.transmuxer.currentTransmux){e.transmuxer.currentTransmux=e,jd(e);return}e.transmuxer.transmuxQueue.push(e)},Rd={reset:Fd,endTimeline:Id,transmux:Ld,createTransmuxer:e=>{let t=new Dd;t.currentTransmux=null,t.transmuxQueue=[];let n=t.terminate;return t.terminate=()=>(t.currentTransmux=null,t.transmuxQueue.length=0,n.call(t)),t.postMessage({action:`init`,options:e}),t}},zd=function(e){let t=e.transmuxer,n=e.endAction||e.action,r=e.callback,i=me({},e,{endAction:null,transmuxer:null,callback:null}),a=i=>{i.data.action===n&&(t.removeEventListener(`message`,a),i.data.data&&(i.data.data=new Uint8Array(i.data.data,e.byteOffset||0,e.byteLength||i.data.data.byteLength),e.data&&=i.data.data),r(i.data))};if(t.addEventListener(`message`,a),e.data){let n=e.data instanceof ArrayBuffer;i.byteOffset=n?0:e.data.byteOffset,i.byteLength=e.data.byteLength;let r=[n?e.data:e.data.buffer];t.postMessage(i,r)}else t.postMessage(i)},Bd={FAILURE:2,TIMEOUT:-101,ABORTED:-102},Vd=`wvtt`,Hd=e=>{e.forEach(e=>{e.abort()})},Ud=e=>({bandwidth:e.bandwidth,bytesReceived:e.bytesReceived||0,roundTripTime:e.roundTripTime||0}),Wd=e=>{let t=e.target,n={bandwidth:1/0,bytesReceived:0,roundTripTime:Date.now()-t.requestTime||0};return n.bytesReceived=e.loaded,n.bandwidth=Math.floor(n.bytesReceived/n.roundTripTime*8*1e3),n},Gd=(e,t)=>{let{requestType:n}=t,r=bu({requestType:n,request:t,error:e});return t.timedout?{status:t.status,message:`HLS request timed-out at URL: `+t.uri,code:Bd.TIMEOUT,xhr:t,metadata:r}:t.aborted?{status:t.status,message:`HLS request aborted at URL: `+t.uri,code:Bd.ABORTED,xhr:t,metadata:r}:e?{status:t.status,message:`HLS request errored at URL: `+t.uri,code:Bd.FAILURE,xhr:t,metadata:r}:t.responseType===`arraybuffer`&&t.response.byteLength===0?{status:t.status,message:`Empty HLS response at URL: `+t.uri,code:Bd.FAILURE,xhr:t,metadata:r}:null},Kd=(e,t,n,r)=>(i,a)=>{let o=a.response,s=Gd(i,a);if(s)return n(s,e);if(o.byteLength!==16)return n({status:a.status,message:`Invalid HLS key at URL: `+a.uri,code:Bd.FAILURE,xhr:a},e);let c=new DataView(o),l=new Uint32Array([c.getUint32(0),c.getUint32(4),c.getUint32(8),c.getUint32(12)]);for(let e=0;e{t===Vd&&e.transmuxer.postMessage({action:`initMp4WebVttParser`,data:e.map.bytes})},Jd=(e,t,n)=>{t===Vd&&zd({action:`getMp4WebVttText`,data:e.bytes,transmuxer:e.transmuxer,callback:({data:t,mp4VttCues:r})=>{e.bytes=t,n(null,e,{mp4VttCues:r})}})},Yd=(e,t)=>{let n=sr(e.map.bytes);if(n!==`mp4`){let r=e.map.resolvedUri||e.map.uri,i=n||`unknown`;return t({internal:!0,message:`Found unsupported ${i} container for initialization segment at URL: ${r}`,code:Bd.FAILURE,metadata:{mediaType:i}})}zd({action:`probeMp4Tracks`,data:e.map.bytes,transmuxer:e.transmuxer,callback:({tracks:n,data:r})=>(e.map.bytes=r,n.forEach(function(t){e.map.tracks=e.map.tracks||{},!e.map.tracks[t.type]&&(e.map.tracks[t.type]=t,typeof t.id==`number`&&t.timescale&&(e.map.timescales=e.map.timescales||{},e.map.timescales[t.id]=t.timescale),t.type===`text`&&qd(e,t.codec))}),t(null))})},Xd=({segment:e,finishProcessingFn:t,triggerSegmentEventFn:n})=>(r,i)=>{let a=Gd(r,i);if(a)return t(a,e);let o=new Uint8Array(i.response);if(n({type:`segmentloaded`,segment:e}),e.map.key)return e.map.encryptedBytes=o,t(null,e);e.map.bytes=o,Yd(e,function(n){if(n)return n.xhr=i,n.status=i.status,t(n,e);t(null,e)})},Zd=({segment:e,finishProcessingFn:t,responseType:n,triggerSegmentEventFn:r})=>(i,a)=>{let o=Gd(i,a);if(o)return t(o,e);r({type:`segmentloaded`,segment:e});let s=n===`arraybuffer`||!a.responseText?a.response:xd(a.responseText.substring(e.lastReachedChar||0));return e.stats=Ud(a),e.key?e.encryptedBytes=new Uint8Array(s):e.bytes=new Uint8Array(s),t(null,e)},Qd=({segment:e,bytes:t,trackInfoFn:n,timingInfoFn:r,videoSegmentTimingInfoFn:i,audioSegmentTimingInfoFn:a,id3Fn:o,captionsFn:s,isEndOfTimeline:c,endedTimelineFn:l,dataFn:u,doneFn:d,onTransmuxerLog:f,triggerSegmentEventFn:p})=>{let m=e.map&&e.map.tracks||{},h=!!(m.audio&&m.video),g=r.bind(null,e,`audio`,`start`),_=r.bind(null,e,`audio`,`end`),v=r.bind(null,e,`video`,`start`),y=r.bind(null,e,`video`,`end`),b=()=>Ld({bytes:t,transmuxer:e.transmuxer,audioAppendStart:e.audioAppendStart,gopsToAlignWith:e.gopsToAlignWith,remux:h,onData:t=>{t.type=t.type===`combined`?`video`:t.type,u(e,t)},onTrackInfo:t=>{n&&(h&&(t.isMuxed=!0),n(e,t))},onAudioTimingInfo:e=>{g&&e.start!==void 0&&(g(e.start),g=null),_&&e.end!==void 0&&_(e.end)},onVideoTimingInfo:e=>{v&&e.start!==void 0&&(v(e.start),v=null),y&&e.end!==void 0&&y(e.end)},onVideoSegmentTimingInfo:t=>{p({type:`segmenttransmuxingtiminginfoavailable`,segment:e,timingInfo:{pts:{start:t.start.presentation,end:t.end.presentation},dts:{start:t.start.decode,end:t.end.decode}}}),i(t)},onAudioSegmentTimingInfo:t=>{p({type:`segmenttransmuxingtiminginfoavailable`,segment:e,timingInfo:{pts:{start:t.start.pts,end:t.end.pts},dts:{start:t.start.dts,end:t.end.dts}}}),a(t)},onId3:(t,n)=>{o(e,t,n)},onCaptions:t=>{s(e,[t])},isEndOfTimeline:c,onEndedTimeline:()=>{l()},onTransmuxerLog:f,onDone:(t,n)=>{d&&(t.type=t.type===`combined`?`video`:t.type,p({type:`segmenttransmuxingcomplete`,segment:e}),d(n,e,t))},segment:e,triggerSegmentEventFn:p});zd({action:`probeTs`,transmuxer:e.transmuxer,data:t,baseStartTime:e.baseStartTime,callback:r=>{e.bytes=t=r.data;let i=r.result;i&&(n(e,{hasAudio:i.hasAudio,hasVideo:i.hasVideo,isMuxed:h}),n=null),b()}})},$d=({segment:e,bytes:t,trackInfoFn:n,timingInfoFn:r,videoSegmentTimingInfoFn:i,audioSegmentTimingInfoFn:a,id3Fn:o,captionsFn:s,isEndOfTimeline:c,endedTimelineFn:l,dataFn:u,doneFn:d,onTransmuxerLog:f,triggerSegmentEventFn:p})=>{let m=new Uint8Array(t);if(cr(m)){e.isFmp4=!0;let{tracks:i}=e.map;if(i.text&&(!i.audio||!i.video)){u(e,{data:m,type:`text`}),Jd(e,i.text.codec,d);return}let a={isFmp4:!0,hasVideo:!!i.video,hasAudio:!!i.audio};i.audio&&i.audio.codec&&i.audio.codec!==`enca`&&(a.audioCodec=i.audio.codec),i.video&&i.video.codec&&i.video.codec!==`encv`&&(a.videoCodec=i.video.codec),i.video&&i.audio&&(a.isMuxed=!0),n(e,a);let c=(t,n)=>{u(e,{data:m,type:a.hasAudio&&!a.isMuxed?`audio`:`video`}),n&&n.length&&o(e,n),t&&t.length&&s(e,t),d(null,e,{})};zd({action:`probeMp4StartTime`,timescales:e.map.timescales,data:m,transmuxer:e.transmuxer,callback:({data:n,startTime:o})=>{t=n.buffer,e.bytes=m=n,a.hasAudio&&!a.isMuxed&&r(e,`audio`,`start`,o),a.hasVideo&&r(e,`video`,`start`,o),zd({action:`probeEmsgID3`,data:m,transmuxer:e.transmuxer,offset:o,callback:({emsgData:n,id3Frames:r})=>{if(t=n.buffer,e.bytes=m=n,!i.video||!n.byteLength||!e.transmuxer){c(void 0,r);return}zd({action:`pushMp4Captions`,endAction:`mp4Captions`,transmuxer:e.transmuxer,data:m,timescales:e.map.timescales,trackIds:[i.video.id],callback:n=>{t=n.data.buffer,e.bytes=m=n.data,n.logs.forEach(function(e){f(xl(e,{stream:`mp4CaptionParser`}))}),c(n.captions,r)}})}})}});return}if(!e.transmuxer){d(null,e,{});return}if(e.container===void 0&&(e.container=sr(m)),e.container!==`ts`&&e.container!==`aac`){n(e,{hasAudio:!1,hasVideo:!1}),d(null,e,{});return}Qd({segment:e,bytes:t,trackInfoFn:n,timingInfoFn:r,videoSegmentTimingInfoFn:i,audioSegmentTimingInfoFn:a,id3Fn:o,captionsFn:s,isEndOfTimeline:c,endedTimelineFn:l,dataFn:u,doneFn:d,onTransmuxerLog:f,triggerSegmentEventFn:p})},ef=function({id:e,key:t,encryptedBytes:n,decryptionWorker:r,segment:i,doneFn:a},o){let s=t=>{if(t.data.source===e){r.removeEventListener(`message`,s);let e=t.data.decrypted;o(new Uint8Array(e.bytes,e.byteOffset,e.byteLength))}};r.onerror=()=>{let e=`An error occurred in the decryption worker`,t=Zf({segment:i});a({message:e,metadata:{error:Error(e),errorType:W.Error.StreamingFailedToDecryptSegment,segmentInfo:t,keyInfo:{uri:i.key.resolvedUri||i.map.key.resolvedUri}}},i)},r.addEventListener(`message`,s);let c;c=t.bytes.slice?t.bytes.slice():new Uint32Array(Array.prototype.slice.call(t.bytes)),r.postMessage(Ju({source:e,encrypted:n,key:c,iv:t.iv}),[n.buffer,c.buffer])},tf=({decryptionWorker:e,segment:t,trackInfoFn:n,timingInfoFn:r,videoSegmentTimingInfoFn:i,audioSegmentTimingInfoFn:a,id3Fn:o,captionsFn:s,isEndOfTimeline:c,endedTimelineFn:l,dataFn:u,doneFn:d,onTransmuxerLog:f,triggerSegmentEventFn:p})=>{p({type:`segmentdecryptionstart`}),ef({id:t.requestId,key:t.key,encryptedBytes:t.encryptedBytes,decryptionWorker:e,segment:t,doneFn:d},e=>{t.bytes=e,p({type:`segmentdecryptioncomplete`,segment:t}),$d({segment:t,bytes:t.bytes,trackInfoFn:n,timingInfoFn:r,videoSegmentTimingInfoFn:i,audioSegmentTimingInfoFn:a,id3Fn:o,captionsFn:s,isEndOfTimeline:c,endedTimelineFn:l,dataFn:u,doneFn:d,onTransmuxerLog:f,triggerSegmentEventFn:p})})},nf=({activeXhrs:e,decryptionWorker:t,trackInfoFn:n,timingInfoFn:r,videoSegmentTimingInfoFn:i,audioSegmentTimingInfoFn:a,id3Fn:o,captionsFn:s,isEndOfTimeline:c,endedTimelineFn:l,dataFn:u,doneFn:d,onTransmuxerLog:f,triggerSegmentEventFn:p})=>{let m=0,h=!1;return(g,_)=>{if(!h){if(g)return h=!0,Hd(e),d(g,_);if(m+=1,m===e.length){let m=function(){if(_.encryptedBytes)return tf({decryptionWorker:t,segment:_,trackInfoFn:n,timingInfoFn:r,videoSegmentTimingInfoFn:i,audioSegmentTimingInfoFn:a,id3Fn:o,captionsFn:s,isEndOfTimeline:c,endedTimelineFn:l,dataFn:u,doneFn:d,onTransmuxerLog:f,triggerSegmentEventFn:p});$d({segment:_,bytes:_.bytes,trackInfoFn:n,timingInfoFn:r,videoSegmentTimingInfoFn:i,audioSegmentTimingInfoFn:a,id3Fn:o,captionsFn:s,isEndOfTimeline:c,endedTimelineFn:l,dataFn:u,doneFn:d,onTransmuxerLog:f,triggerSegmentEventFn:p})};if(_.endOfAllRequests=Date.now(),_.map&&_.map.encryptedBytes&&!_.map.bytes)return p({type:`segmentdecryptionstart`,segment:_}),ef({decryptionWorker:t,id:_.requestId+`-init`,encryptedBytes:_.map.encryptedBytes,key:_.map.key,segment:_,doneFn:d},t=>{_.map.bytes=t,p({type:`segmentdecryptioncomplete`,segment:_}),Yd(_,t=>{if(t)return Hd(e),d(t,_);m()})});m()}}}},rf=({loadendState:e,abortFn:t})=>n=>{n.target.aborted&&t&&!e.calledAbortFn&&(t(),e.calledAbortFn=!0)},af=({segment:e,progressFn:t,trackInfoFn:n,timingInfoFn:r,videoSegmentTimingInfoFn:i,audioSegmentTimingInfoFn:a,id3Fn:o,captionsFn:s,isEndOfTimeline:c,endedTimelineFn:l,dataFn:u})=>n=>{if(!n.target.aborted)return e.stats=xl(e.stats,Wd(n)),!e.stats.firstBytesReceivedAt&&e.stats.bytesReceived&&(e.stats.firstBytesReceivedAt=Date.now()),t(n,e)},of=({xhr:e,xhrOptions:t,decryptionWorker:n,segment:r,abortFn:i,progressFn:a,trackInfoFn:o,timingInfoFn:s,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:l,id3Fn:u,captionsFn:d,isEndOfTimeline:f,endedTimelineFn:p,dataFn:m,doneFn:h,onTransmuxerLog:g,triggerSegmentEventFn:_})=>{let v=[],y=nf({activeXhrs:v,decryptionWorker:n,trackInfoFn:o,timingInfoFn:s,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:l,id3Fn:u,captionsFn:d,isEndOfTimeline:f,endedTimelineFn:p,dataFn:m,doneFn:h,onTransmuxerLog:g,triggerSegmentEventFn:_});if(r.key&&!r.key.bytes){let n=[r.key];r.map&&!r.map.bytes&&r.map.key&&r.map.key.resolvedUri===r.key.resolvedUri&&n.push(r.map.key);let i=xl(t,{uri:r.key.resolvedUri,responseType:`arraybuffer`,requestType:`segment-key`}),a=Kd(r,n,y,_);_({type:`segmentkeyloadstart`,segment:r,keyInfo:{uri:r.key.resolvedUri}});let o=e(i,a);v.push(o)}if(r.map&&!r.map.bytes){if(r.map.key&&(!r.key||r.key.resolvedUri!==r.map.key.resolvedUri)){let n=xl(t,{uri:r.map.key.resolvedUri,responseType:`arraybuffer`,requestType:`segment-key`}),i=Kd(r,[r.map.key],y,_);_({type:`segmentkeyloadstart`,segment:r,keyInfo:{uri:r.map.key.resolvedUri}});let a=e(n,i);v.push(a)}let n=xl(t,{uri:r.map.resolvedUri,responseType:`arraybuffer`,headers:Wu(r.map),requestType:`segment-media-initialization`}),i=Xd({segment:r,finishProcessingFn:y,triggerSegmentEventFn:_});_({type:`segmentloadstart`,segment:r});let a=e(n,i);v.push(a)}let b=xl(t,{uri:r.part&&r.part.resolvedUri||r.resolvedUri,responseType:`arraybuffer`,headers:Wu(r),requestType:`segment`}),x=Zd({segment:r,finishProcessingFn:y,responseType:b.responseType,triggerSegmentEventFn:_});_({type:`segmentloadstart`,segment:r});let S=e(b,x);S.addEventListener(`progress`,af({segment:r,progressFn:a,trackInfoFn:o,timingInfoFn:s,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:l,id3Fn:u,captionsFn:d,isEndOfTimeline:f,endedTimelineFn:p,dataFn:m})),v.push(S);let C={};return v.forEach(e=>{e.addEventListener(`loadend`,rf({loadendState:C,abortFn:i}))}),()=>Hd(v)},sf=bl(`PlaylistSelector`),cf=function(e){if(!e||!e.playlist)return;let t=e.playlist;return JSON.stringify({id:t.id,bandwidth:e.bandwidth,width:e.width,height:e.height,codecs:t.attributes&&t.attributes.CODECS||``})},lf=function(e,t){if(!e)return``;let n=I.default.getComputedStyle(e);return n?n[t]:``},uf=function(e,t){let n=e.slice();e.sort(function(e,r){let i=t(e,r);return i===0?n.indexOf(e)-n.indexOf(r):i})},df=function(e,t){let n,r;return e.attributes.BANDWIDTH&&(n=e.attributes.BANDWIDTH),n||=I.default.Number.MAX_VALUE,t.attributes.BANDWIDTH&&(r=t.attributes.BANDWIDTH),r||=I.default.Number.MAX_VALUE,n-r},ff=function(e,t){let n,r;return e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width&&(n=e.attributes.RESOLUTION.width),n||=I.default.Number.MAX_VALUE,t.attributes.RESOLUTION&&t.attributes.RESOLUTION.width&&(r=t.attributes.RESOLUTION.width),r||=I.default.Number.MAX_VALUE,n===r&&e.attributes.BANDWIDTH&&t.attributes.BANDWIDTH?e.attributes.BANDWIDTH-t.attributes.BANDWIDTH:n-r},pf=function(e){let{main:t,bandwidth:n,playerWidth:r,playerHeight:i,playerObjectFit:a,limitRenditionByPlayerDimensions:o,playlistController:s}=e;if(!t)return;let c={bandwidth:n,width:r,height:i,limitRenditionByPlayerDimensions:o},l=t.playlists;su.isAudioOnly(t)&&(l=s.getAudioTrackPlaylists_(),c.audioOnly=!0);let u=l.map(e=>{let t,n=e.attributes&&e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width,r=e.attributes&&e.attributes.RESOLUTION&&e.attributes.RESOLUTION.height;return t=e.attributes&&e.attributes.BANDWIDTH,t||=I.default.Number.MAX_VALUE,{bandwidth:t,width:n,height:r,playlist:e}});uf(u,(e,t)=>e.bandwidth-t.bandwidth),u=u.filter(e=>!su.isIncompatible(e.playlist));let d=u.filter(e=>su.isEnabled(e.playlist));d.length||(d=u.filter(e=>!su.isDisabled(e.playlist)));let f=d.filter(e=>e.bandwidth*bd.BANDWIDTH_VARIANCEe.bandwidth===p.bandwidth)[0];if(o===!1){let e=m||d[0]||u[0];if(e&&e.playlist){let t=`sortedPlaylistReps`;return m&&(t=`bandwidthBestRep`),d[0]&&(t=`enabledPlaylistReps`),sf(`choosing ${cf(e)} using ${t} with options`,c),e.playlist}return sf(`could not choose a playlist with options`,c),null}let h=f.filter(e=>e.width&&e.height);uf(h,(e,t)=>e.width-t.width);let g=h.filter(e=>e.width===r&&e.height===i);p=g[g.length-1];let _=g.filter(e=>e.bandwidth===p.bandwidth)[0],v,y,b;_||(v=h.filter(e=>a===`cover`?e.width>r&&e.height>i:e.width>r||e.height>i),y=v.filter(e=>e.width===v[0].width&&e.height===v[0].height),p=y[y.length-1],b=y.filter(e=>e.bandwidth===p.bandwidth)[0]);let x;if(s.leastPixelDiffSelector){let e=h.map(e=>(e.pixelDiff=Math.abs(e.width-r)+Math.abs(e.height-i),e));uf(e,(e,t)=>e.pixelDiff===t.pixelDiff?t.bandwidth-e.bandwidth:e.pixelDiff-t.pixelDiff),x=e[0]}let S=x||b||_||m||d[0]||u[0];if(S&&S.playlist){let e=`sortedPlaylistReps`;return x?e=`leastPixelDiffRep`:b?e=`resolutionPlusOneRep`:_?e=`resolutionBestRep`:m?e=`bandwidthBestRep`:d[0]&&(e=`enabledPlaylistReps`),sf(`choosing ${cf(S)} using ${e} with options`,c),S.playlist}return sf(`could not choose a playlist with options`,c),null},mf=function(){let e=this.useDevicePixelRatio&&I.default.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(e=this.customPixelRatio),pf({main:this.playlists.main,bandwidth:this.systemBandwidth,playerWidth:parseInt(lf(this.tech_.el(),`width`),10)*e,playerHeight:parseInt(lf(this.tech_.el(),`height`),10)*e,playerObjectFit:this.usePlayerObjectFit?lf(this.tech_.el(),`objectFit`):``,limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})},hf=function(e){let t=-1,n=-1;if(e<0||e>1)throw Error(`Moving average bandwidth decay must be between 0 and 1.`);return function(){let r=this.useDevicePixelRatio&&I.default.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(r=this.customPixelRatio),t<0&&(t=this.systemBandwidth,n=this.systemBandwidth),this.systemBandwidth>0&&this.systemBandwidth!==n&&(t=e*this.systemBandwidth+(1-e)*t,n=this.systemBandwidth),pf({main:this.playlists.main,bandwidth:t,playerWidth:parseInt(lf(this.tech_.el(),`width`),10)*r,playerHeight:parseInt(lf(this.tech_.el(),`height`),10)*r,playerObjectFit:this.usePlayerObjectFit?lf(this.tech_.el(),`objectFit`):``,limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})}},gf=function(e){let{main:t,currentTime:n,bandwidth:r,duration:i,segmentDuration:a,timeUntilRebuffer:o,currentTimeline:s,syncController:c}=e,l=t.playlists.filter(e=>!su.isIncompatible(e)),u=l.filter(su.isEnabled);u.length||(u=l.filter(e=>!su.isDisabled(e)));let d=u.filter(su.hasAttribute.bind(null,`BANDWIDTH`)).map(e=>{let t=c.getSyncPoint(e,i,s,n)?1:2;return{playlist:e,rebufferingImpact:su.estimateSegmentRequestTime(a,r,e)*t-o}}),f=d.filter(e=>e.rebufferingImpact<=0);return uf(f,(e,t)=>df(t.playlist,e.playlist)),f.length?f[0]:(uf(d,(e,t)=>e.rebufferingImpact-t.rebufferingImpact),d[0]||null)},_f=function(){let e=this.playlists.main.playlists.filter(su.isEnabled);return uf(e,(e,t)=>df(e,t)),e.filter(e=>!!Du(this.playlists.main,e).video)[0]||null},vf=e=>{let t=0,n;return e.bytes&&(n=new Uint8Array(e.bytes),e.segments.forEach(e=>{n.set(e,t),t+=e.byteLength})),n};function yf(e){try{return new URL(e).pathname.split(`/`).slice(-2).join(`/`)}catch{return``}}var bf=function(e,t,n){if(!e[n]){t.trigger({type:`usage`,name:`vhs-608`});let r=n;/^cc708_/.test(n)&&(r=`SERVICE`+n.split(`_`)[1]);let i=t.textTracks().getTrackById(r);if(i)e[n]=i;else{let i=t.options_.vhs&&t.options_.vhs.captionServices||{},a=n,o=n,s=!1,c=i[r];c&&(a=c.label,o=c.language,s=c.default),e[n]=t.addRemoteTextTrack({kind:`captions`,id:r,default:s,label:a,language:o},!1).track}}},xf=function({inbandTextTracks:e,captionArray:t,timestampOffset:n}){if(!t)return;let r=I.default.WebKitDataCue||I.default.VTTCue;t.forEach(t=>{let i=t.stream;t.content?t.content.forEach(a=>{let o=new r(t.startTime+n,t.endTime+n,a.text);o.line=a.line,o.align=`left`,o.position=a.position,o.positionAlign=`line-left`,e[i].addCue(o)}):e[i].addCue(new r(t.startTime+n,t.endTime+n,t.text))})},Sf=function(e){Object.defineProperties(e.frame,{id:{get(){return W.log.warn(`cue.frame.id is deprecated. Use cue.value.key instead.`),e.value.key}},value:{get(){return W.log.warn(`cue.frame.value is deprecated. Use cue.value.data instead.`),e.value.data}},privateData:{get(){return W.log.warn(`cue.frame.privateData is deprecated. Use cue.value.data instead.`),e.value.data}}})},Cf=({inbandTextTracks:e,metadataArray:t,timestampOffset:n,videoDuration:r})=>{if(!t)return;let i=I.default.WebKitDataCue||I.default.VTTCue,a=e.metadataTrack_;if(!a||(t.forEach(e=>{let t=e.cueTime+n;typeof t!=`number`||I.default.isNaN(t)||t<0||!(t<1/0)||!e.frames||!e.frames.length||e.frames.forEach(e=>{let n=new i(t,t,e.value||e.url||e.data||``);n.frame=e,n.value=e,Sf(n),a.addCue(n)})}),!a.cues||!a.cues.length))return;let o=a.cues,s=[];for(let e=0;e{let n=e[t.startTime]||[];return n.push(t),e[t.startTime]=n,e},{}),l=Object.keys(c).sort((e,t)=>Number(e)-Number(t));l.forEach((e,t)=>{let n=c[e],i=isFinite(r)?r:e,a=Number(l[t+1])||i;n.forEach(e=>{e.endTime=a})})},wf={id:`ID`,class:`CLASS`,startDate:`START-DATE`,duration:`DURATION`,endDate:`END-DATE`,endOnNext:`END-ON-NEXT`,plannedDuration:`PLANNED-DURATION`,scte35Out:`SCTE35-OUT`,scte35In:`SCTE35-IN`},Tf=new Set([`id`,`class`,`startDate`,`duration`,`endDate`,`endOnNext`,`startTime`,`endTime`,`processDateRange`]),Ef=({inbandTextTracks:e,dateRanges:t})=>{let n=e.metadataTrack_;if(!n)return;let r=I.default.WebKitDataCue||I.default.VTTCue;t.forEach(e=>{for(let t of Object.keys(e)){if(Tf.has(t))continue;let i=new r(e.startTime,e.endTime,``);i.id=e.id,i.type=`com.apple.quicktime.HLS`,i.value={key:wf[t],data:e[t]},(t===`scte35Out`||t===`scte35In`)&&(i.value.data=new Uint8Array(i.value.data.match(/[\da-f]{2}/gi)).buffer),n.addCue(i)}e.processDateRange()})},Df=(e,t,n)=>{e.metadataTrack_||(e.metadataTrack_=n.addRemoteTextTrack({kind:`metadata`,label:`Timed Metadata`},!1).track,W.browser.IS_ANY_SAFARI||(e.metadataTrack_.inBandMetadataTrackDispatchType=t))},Of=function(e,t,n){let r,i;if(n&&n.cues)for(r=n.cues.length;r--;)i=n.cues[r],i.startTime>=e&&i.endTime<=t&&n.removeCue(i)},kf=function(e){let t=e.cues;if(!t)return;let n={};for(let r=t.length-1;r>=0;r--){let i=t[r],a=`${i.startTime}-${i.endTime}-${i.text}`;n[a]?e.removeCue(i):n[a]=i}},Af=(e,t,n)=>{if(t==null||!e.length)return[];let r=Math.ceil((t-n+3)*lr.ONE_SECOND_IN_TS),i;for(i=0;ir);i++);return e.slice(i)},jf=(e,t,n)=>{if(!t.length)return e;if(n)return t.slice();let r=t[0].pts,i=0;for(;i=r);i++);return e.slice(0,i).concat(t)},Mf=(e,t,n,r)=>{let i=Math.ceil((t-r)*lr.ONE_SECOND_IN_TS),a=Math.ceil((n-r)*lr.ONE_SECOND_IN_TS),o=e.slice(),s=e.length;for(;s--&&!(e[s].pts<=a););if(s===-1)return o;let c=s+1;for(;c--&&!(e[c].pts<=i););return c=Math.max(c,0),o.splice(c,s-c+1),o},Nf=function(e,t){if(!e&&!t||!e&&t||e&&!t)return!1;if(e===t)return!0;let n=Object.keys(e).sort(),r=Object.keys(t).sort();if(n.length!==r.length)return!1;for(let i=0;in))return a}return r.length===0?0:r[r.length-1]},Ff=1,If=500,Lf=e=>typeof e==`number`&&isFinite(e),Rf=1/60,zf=(e,t,n)=>e!==`main`||!t||!n?null:!n.hasAudio&&!n.hasVideo?`Neither audio nor video found in segment.`:t.hasVideo&&!n.hasVideo?`Only audio found in segment when we expected video. We can't switch to audio only from a stream that had video. To get rid of this message, please add codec information to the manifest.`:!t.hasVideo&&n.hasVideo?`Video found in segment when we expected only audio. We can't switch to a stream with video from an audio only stream. To get rid of this message, please add codec information to the manifest.`:null,Bf=(e,t,n)=>{let r=t-bd.BACK_BUFFER_LENGTH;e.length&&(r=Math.max(r,e.start(0)));let i=t-n;return Math.min(i,r)},Vf=e=>{let{startOfSegment:t,duration:n,segment:r,part:i,playlist:{mediaSequence:a,id:o,segments:s=[]},mediaIndex:c,partIndex:l,timeline:u}=e,d=s.length-1,f=`mediaIndex/partIndex increment`;e.getMediaInfoForTime?f=`getMediaInfoForTime (${e.getMediaInfoForTime})`:e.isSyncRequest&&(f=`getSyncSegmentCandidate (isSyncRequest)`),e.independent&&(f+=` with independent ${e.independent}`);let p=typeof l==`number`,m=e.segment.uri?`segment`:`pre-segment`,h=p?Bl({preloadSegment:r})-1:0;return`${m} [${a+c}/${a+d}]`+(p?` part [${l}/${h}]`:``)+` segment start/end [${r.start} => ${r.end}]`+(p?` part start/end [${i.start} => ${i.end}]`:``)+` startOfSegment [${t}] duration [${n}] timeline [${u}] selected by [${f}] playlist [${o}]`},Hf=e=>`${e}TimingInfo`,Uf=({segmentTimeline:e,currentTimeline:t,startOfSegment:n,buffered:r,overrideCheck:i})=>!i&&e===t?null:e{if(t===n)return!1;if(r===`audio`){let t=e.lastTimelineChange({type:`main`});return!t||t.to!==n}if(r===`main`&&i){let t=e.pendingTimelineChange({type:`audio`});return!(t&&t.to===n)}return!1},Gf=e=>{if(!e)return!1;let t=e.pendingTimelineChange({type:`audio`}),n=e.pendingTimelineChange({type:`main`}),r=t&&n,i=r&&t.to!==n.to;return!!(r&&t.from!==-1&&n.from!==-1&&i)},Kf=e=>{let t=e.timelineChangeController_.pendingTimelineChange({type:`audio`}),n=e.timelineChangeController_.pendingTimelineChange({type:`main`});return t&&n&&t.to{let t=e.pendingSegment_;if(t&&Wf({timelineChangeController:e.timelineChangeController_,currentTimeline:e.currentTimeline_,segmentTimeline:t.timeline,loaderType:e.loaderType_,audioDisabled:e.audioDisabled_})&&Gf(e.timelineChangeController_)){if(Kf(e)){e.timelineChangeController_.trigger(`audioTimelineBehind`);return}e.timelineChangeController_.trigger(`fixBadTimelineChange`)}},Jf=e=>{let t=0;return[`video`,`audio`].forEach(function(n){let r=e[`${n}TimingInfo`];if(!r)return;let{start:i,end:a}=r,o;typeof i==`bigint`||typeof a==`bigint`?o=I.default.BigInt(a)-I.default.BigInt(i):typeof i==`number`&&typeof a==`number`&&(o=a-i),o!==void 0&&o>t&&(t=o)}),typeof t==`bigint`&&t<2**53-1&&(t=Number(t)),t},Yf=({segmentDuration:e,maxDuration:t})=>e?Math.round(e)>t+wl:!1,Xf=(e,t)=>{if(t!==`hls`)return null;let n=Jf({audioTimingInfo:e.audioTimingInfo,videoTimingInfo:e.videoTimingInfo});if(!n)return null;let r=e.playlist.targetDuration,i=Yf({segmentDuration:n,maxDuration:r*2}),a=Yf({segmentDuration:n,maxDuration:r}),o=`Segment with index ${e.mediaIndex} from playlist ${e.playlist.id} has a duration of ${n} when the reported duration is ${e.duration} and the target duration is ${r}. For HLS content, a duration in excess of the target duration may result in playback issues. See the HLS specification section on EXT-X-TARGETDURATION for more details: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1`;return i||a?{severity:i?`warn`:`info`,message:o}:null},Zf=({type:e,segment:t})=>{if(!t)return;let n=!!(t.key||t.map&&t.map.ke),r=!!(t.map&&!t.map.bytes),i=t.startOfSegment===void 0?t.start:t.startOfSegment;return{type:e||t.type,uri:t.resolvedUri||t.uri,start:i,duration:t.duration,isEncrypted:n,isMediaInitialization:r}},Qf=class extends W.EventTarget{constructor(e,t={}){if(super(),!e)throw TypeError(`Initialization settings are required`);if(typeof e.currentTime!=`function`)throw TypeError(`No currentTime getter specified`);if(!e.mediaSource)throw TypeError(`No MediaSource specified`);this.bandwidth=e.bandwidth,this.throughput={rate:0,count:0},this.roundTrip=NaN,this.resetStats_(),this.mediaIndex=null,this.partIndex=null,this.hasPlayed_=e.hasPlayed,this.currentTime_=e.currentTime,this.seekable_=e.seekable,this.seeking_=e.seeking,this.duration_=e.duration,this.mediaSource_=e.mediaSource,this.vhs_=e.vhs,this.loaderType_=e.loaderType,this.currentMediaInfo_=void 0,this.startingMediaInfo_=void 0,this.segmentMetadataTrack_=e.segmentMetadataTrack,this.goalBufferLength_=e.goalBufferLength,this.sourceType_=e.sourceType,this.sourceUpdater_=e.sourceUpdater,this.inbandTextTracks_=e.inbandTextTracks,this.state_=`INIT`,this.timelineChangeController_=e.timelineChangeController,this.shouldSaveSegmentTimingInfo_=!0,this.parse708captions_=e.parse708captions,this.useDtsForTimestampOffset_=e.useDtsForTimestampOffset,this.captionServices_=e.captionServices,this.exactManifestTimings=e.exactManifestTimings,this.addMetadataToTextTrack=e.addMetadataToTextTrack,this.checkBufferTimeout_=null,this.error_=void 0,this.currentTimeline_=-1,this.shouldForceTimestampOffsetAfterResync_=!1,this.pendingSegment_=null,this.xhrOptions_=null,this.pendingSegments_=[],this.audioDisabled_=!1,this.isPendingTimestampOffset_=!1,this.gopBuffer_=[],this.timeMapping_=0,this.safeAppend_=!1,this.appendInitSegment_={audio:!0,video:!0},this.playlistOfLastInitSegment_={audio:null,video:null},this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_={id3:[],caption:[]},this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=null,this.activeInitSegmentId_=null,this.initSegments_={},this.cacheEncryptionKeys_=e.cacheEncryptionKeys,this.keyCache_={},this.decrypter_=e.decrypter,this.syncController_=e.syncController,this.syncPoint_={segmentIndex:0,time:0},this.transmuxer_=this.createTransmuxer_(),this.triggerSyncInfoUpdate_=()=>this.trigger(`syncinfoupdate`),this.syncController_.on(`syncinfoupdate`,this.triggerSyncInfoUpdate_),this.mediaSource_.addEventListener(`sourceopen`,()=>{this.isEndOfStream_()||(this.ended_=!1)}),this.fetchAtBuffer_=!1,this.logger_=bl(`SegmentLoader[${this.loaderType_}]`),Object.defineProperty(this,`state`,{get(){return this.state_},set(e){e!==this.state_&&(this.logger_(`${this.state_} -> ${e}`),this.state_=e,this.trigger(`statechange`))}}),this.sourceUpdater_.on(`ready`,()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():qf(this)}),this.sourceUpdater_.on(`codecschange`,e=>{this.trigger(me({type:`codecschange`},e))}),this.loaderType_===`main`&&this.timelineChangeController_.on(`pendingtimelinechange`,()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():qf(this)}),this.loaderType_===`audio`&&this.timelineChangeController_.on(`timelinechange`,e=>{this.trigger(me({type:`timelinechange`},e)),this.hasEnoughInfoToLoad_()?this.processLoadQueue_():qf(this),this.hasEnoughInfoToAppend_()?this.processCallQueue_():qf(this)})}get mediaSequenceSync_(){return this.syncController_.getMediaSequenceSync(this.loaderType_)}createTransmuxer_(){return Rd.createTransmuxer({remux:!1,alignGopsAtEnd:this.safeAppend_,keepOriginalTimestamps:!0,parse708captions:this.parse708captions_,captionServices:this.captionServices_})}resetStats_(){this.mediaBytesTransferred=0,this.mediaRequests=0,this.mediaRequestsAborted=0,this.mediaRequestsTimedout=0,this.mediaRequestsErrored=0,this.mediaTransferDuration=0,this.mediaSecondsLoaded=0,this.mediaAppends=0}dispose(){this.trigger(`dispose`),this.state=`DISPOSED`,this.pause(),this.abort_(),this.transmuxer_&&this.transmuxer_.terminate(),this.resetStats_(),this.checkBufferTimeout_&&I.default.clearTimeout(this.checkBufferTimeout_),this.syncController_&&this.triggerSyncInfoUpdate_&&this.syncController_.off(`syncinfoupdate`,this.triggerSyncInfoUpdate_),this.off()}setAudio(e){this.audioDisabled_=!e,e?this.appendInitSegment_.audio=!0:this.sourceUpdater_.removeAudio(0,this.duration_())}abort(){if(this.state!==`WAITING`){this.pendingSegment_&&=null,this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);return}this.abort_(),this.state=`READY`,this.paused()||this.monitorBuffer_()}abort_(){this.pendingSegment_&&this.pendingSegment_.abortRequests&&this.pendingSegment_.abortRequests(),this.pendingSegment_=null,this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_),this.waitingOnRemove_=!1,I.default.clearTimeout(this.quotaExceededErrorRetryTimeout_),this.quotaExceededErrorRetryTimeout_=null}checkForAbort_(e){return this.state===`APPENDING`&&!this.pendingSegment_?(this.state=`READY`,!0):!this.pendingSegment_||this.pendingSegment_.requestId!==e}error(e){return e!==void 0&&(this.logger_(`error occurred:`,e),this.error_=e),this.pendingSegment_=null,this.error_}endOfStream(){this.ended_=!0,this.transmuxer_&&Rd.reset(this.transmuxer_),this.gopBuffer_.length=0,this.pause(),this.trigger(`ended`)}buffered_(){let e=this.getMediaInfo_();if(!this.sourceUpdater_||!e)return Sl();if(this.loaderType_===`main`){let{hasAudio:t,hasVideo:n,isMuxed:r}=e;if(n&&t&&!this.audioDisabled_&&!r)return this.sourceUpdater_.buffered();if(n)return this.sourceUpdater_.videoBuffered()}return this.sourceUpdater_.audioBuffered()}initSegmentForMap(e,t=!1){if(!e)return null;let n=Yu(e),r=this.initSegments_[n];return t&&!r&&e.bytes&&(this.initSegments_[n]=r={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:e.bytes,tracks:e.tracks,timescales:e.timescales}),r||e}segmentKey(e,t=!1){if(!e)return null;let n=Xu(e),r=this.keyCache_[n];this.cacheEncryptionKeys_&&t&&!r&&e.bytes&&(this.keyCache_[n]=r={resolvedUri:e.resolvedUri,bytes:e.bytes});let i={resolvedUri:(r||e).resolvedUri};return r&&(i.bytes=r.bytes),i}couldBeginLoading_(){return this.playlist_&&!this.paused()}load(){if(this.monitorBuffer_(),this.playlist_){if(this.state===`INIT`&&this.couldBeginLoading_())return this.init_();!this.couldBeginLoading_()||this.state!==`READY`&&this.state!==`INIT`||(this.state=`READY`)}}init_(){return this.state=`READY`,this.resetEverything(),this.monitorBuffer_()}playlist(e,t={}){if(!e||this.playlist_&&this.playlist_.endList&&e.endList&&this.playlist_.uri===e.uri)return;let n=this.playlist_,r=this.pendingSegment_;this.playlist_=e,this.xhrOptions_=t,this.state===`INIT`&&(e.syncInfo={mediaSequence:e.mediaSequence,time:0},this.loaderType_===`main`&&this.syncController_.setDateTimeMappingForStart(e));let i=null;if(n&&(n.id?i=n.id:n.uri&&(i=n.uri)),this.logger_(`playlist update [${i} => ${e.id||e.uri}]`),this.mediaSequenceSync_&&(this.mediaSequenceSync_.update(e,this.currentTime_()),this.logger_(`Playlist update: currentTime: ${this.currentTime_()} bufferedEnd: ${Fl(this.buffered_())} `,this.mediaSequenceSync_.diagnostics)),this.trigger(`syncinfoupdate`),this.state===`INIT`&&this.couldBeginLoading_())return this.init_();if(!n||n.uri!==e.uri){this.mediaIndex!==null&&(!e.endList&&typeof e.partTargetDuration==`number`?this.resetLoader():this.resyncLoader()),this.currentMediaInfo_=void 0,this.trigger(`playlistupdate`);return}let a=e.mediaSequence-n.mediaSequence;if(this.logger_(`live window shift [${a}]`),this.mediaIndex!==null)if(this.mediaIndex-=a,this.mediaIndex<0)this.mediaIndex=null,this.partIndex=null;else{let e=this.playlist_.segments[this.mediaIndex];if(this.partIndex&&(!e.parts||!e.parts.length||!e.parts[this.partIndex])){let e=this.mediaIndex;this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`),this.resetLoader(),this.mediaIndex=e}}r&&(r.mediaIndex-=a,r.mediaIndex<0?(r.mediaIndex=null,r.partIndex=null):(r.mediaIndex>=0&&(r.segment=e.segments[r.mediaIndex]),r.partIndex>=0&&r.segment.parts&&(r.part=r.segment.parts[r.partIndex]))),this.syncController_.saveExpiredSegmentInfo(n,e)}pause(){this.checkBufferTimeout_&&=(I.default.clearTimeout(this.checkBufferTimeout_),null)}paused(){return this.checkBufferTimeout_===null}resetEverything(e){this.ended_=!1,this.activeInitSegmentId_=null,this.appendInitSegment_={audio:!0,video:!0},this.resetLoader(),this.remove(0,1/0,e),this.transmuxer_&&(this.transmuxer_.postMessage({action:`clearAllMp4Captions`}),this.transmuxer_.postMessage({action:`reset`}))}resetLoader(){this.fetchAtBuffer_=!1,this.mediaSequenceSync_&&this.mediaSequenceSync_.resetAppendedStatus(),this.resyncLoader()}resyncLoader(){this.transmuxer_&&Rd.reset(this.transmuxer_),this.mediaIndex=null,this.partIndex=null,this.syncPoint_=null,this.isPendingTimestampOffset_=!1;let e=this.currentMediaInfo_&&this.currentMediaInfo_.isFmp4;this.sourceType_===`hls`&&!e&&(this.shouldForceTimestampOffsetAfterResync_=!0),this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.abort(),this.transmuxer_&&this.transmuxer_.postMessage({action:`clearParsedMp4Captions`})}remove(e,t,n=()=>{},r=!1){if(t===1/0&&(t=this.duration_()),t<=e){this.logger_("skipping remove because end ${end} is <= start ${start}");return}if(!this.sourceUpdater_||!this.getMediaInfo_()){this.logger_(`skipping remove because no source updater or starting media info`);return}let i=1,a=()=>{i--,i===0&&n()};(r||!this.audioDisabled_)&&(i++,this.sourceUpdater_.removeAudio(e,t,a)),(r||this.loaderType_===`main`)&&(this.gopBuffer_=Mf(this.gopBuffer_,e,t,this.timeMapping_),i++,this.sourceUpdater_.removeVideo(e,t,a));for(let n in this.inbandTextTracks_)Of(e,t,this.inbandTextTracks_[n]);Of(e,t,this.segmentMetadataTrack_),a()}monitorBuffer_(){this.checkBufferTimeout_&&I.default.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=I.default.setTimeout(this.monitorBufferTick_.bind(this),1)}monitorBufferTick_(){this.state===`READY`&&this.fillBuffer_(),this.checkBufferTimeout_&&I.default.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=I.default.setTimeout(this.monitorBufferTick_.bind(this),If)}fillBuffer_(){if(this.sourceUpdater_.updating())return;let e=this.chooseNextRequest_();if(!e)return;let t={segmentInfo:Zf({type:this.loaderType_,segment:e})};this.trigger({type:`segmentselected`,metadata:t}),typeof e.timestampOffset==`number`&&(this.isPendingTimestampOffset_=!1,this.timelineChangeController_.pendingTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline})),this.loadSegment_(e)}isEndOfStream_(e=this.mediaIndex,t=this.playlist_,n=this.partIndex){if(!t||!this.mediaSource_)return!1;let r=typeof e==`number`&&t.segments[e],i=e+1===t.segments.length,a=!r||!r.parts||n+1===r.parts.length;return t.endList&&this.mediaSource_.readyState===`open`&&i&&a}chooseNextRequest_(){let e=this.buffered_(),t=Fl(e)||0,n=Il(e,this.currentTime_()),r=!this.hasPlayed_()&&n>=1,i=n>=this.goalBufferLength_(),a=this.playlist_.segments;if(!a.length||r||i)return null;this.syncPoint_=this.syncPoint_||this.syncController_.getSyncPoint(this.playlist_,this.duration_(),this.currentTimeline_,this.currentTime_(),this.loaderType_);let o={partIndex:null,mediaIndex:null,startOfSegment:null,playlist:this.playlist_,isSyncRequest:!this.syncPoint_};if(o.isSyncRequest)o.mediaIndex=Pf(this.currentTimeline_,a,t),this.logger_(`choose next request. Can not find sync point. Fallback to media Index: ${o.mediaIndex}`);else if(this.mediaIndex!==null){let e=a[this.mediaIndex],n=typeof this.partIndex==`number`?this.partIndex:-1;o.startOfSegment=e.end?e.end:t,e.parts&&e.parts[n+1]?(o.mediaIndex=this.mediaIndex,o.partIndex=n+1):o.mediaIndex=this.mediaIndex+1}else{let e,n,r,i=this.fetchAtBuffer_?t:this.currentTime_();if(this.mediaSequenceSync_&&this.logger_(`chooseNextRequest_ request after Quality Switch: For TargetTime: ${i}. CurrentTime: ${this.currentTime_()} BufferedEnd: ${t} Fetch At Buffer: ${this.fetchAtBuffer_} `,this.mediaSequenceSync_.diagnostics),this.mediaSequenceSync_&&this.mediaSequenceSync_.isReliable){let t=this.getSyncInfoFromMediaSequenceSync_(i);if(!t){let e=`No sync info found while using media sequence sync`;return this.error({message:e,metadata:{errorType:W.Error.StreamingFailedToSelectNextSegment,error:Error(e)}}),this.logger_(`chooseNextRequest_ - no sync info found using media sequence sync`),null}this.logger_(`chooseNextRequest_ mediaSequence syncInfo (${t.start} --> ${t.end})`),e=t.segmentIndex,n=t.partIndex,r=t.start}else{this.logger_(`chooseNextRequest_ - fallback to a regular segment selection algorithm, based on a syncPoint.`);let t=su.getMediaInfoForTime({exactManifestTimings:this.exactManifestTimings,playlist:this.playlist_,currentTime:i,startingPartIndex:this.syncPoint_.partIndex,startingSegmentIndex:this.syncPoint_.segmentIndex,startTime:this.syncPoint_.time});e=t.segmentIndex,n=t.partIndex,r=t.startTime}o.getMediaInfoForTime=this.fetchAtBuffer_?`bufferedEnd ${i}`:`currentTime ${i}`,o.mediaIndex=e,o.startOfSegment=r,o.partIndex=n,this.logger_(`choose next request. Playlist switched and we have a sync point. Media Index: ${o.mediaIndex} `)}let s=a[o.mediaIndex],c=s&&typeof o.partIndex==`number`&&s.parts&&s.parts[o.partIndex];if(!s||typeof o.partIndex==`number`&&!c)return null;typeof o.partIndex!=`number`&&s.parts&&(o.partIndex=0,c=s.parts[0]);let l=this.vhs_.playlists&&this.vhs_.playlists.main&&this.vhs_.playlists.main.independentSegments||this.playlist_.independentSegments;if(!n&&c&&!l&&!c.independent)if(o.partIndex===0){let e=a[o.mediaIndex-1],t=e.parts&&e.parts.length&&e.parts[e.parts.length-1];t&&t.independent&&(--o.mediaIndex,o.partIndex=e.parts.length-1,o.independent=`previous segment`)}else s.parts[o.partIndex-1].independent&&(--o.partIndex,o.independent=`previous part`);let u=this.mediaSource_&&this.mediaSource_.readyState===`ended`;return o.mediaIndex>=a.length-1&&u&&!this.seeking_()?null:(this.shouldForceTimestampOffsetAfterResync_&&(this.shouldForceTimestampOffsetAfterResync_=!1,o.forceTimestampOffset=!0,this.logger_(`choose next request. Force timestamp offset after loader resync`)),this.generateSegmentInfo_(o))}getSyncInfoFromMediaSequenceSync_(e){if(!this.mediaSequenceSync_)return null;let t=Math.max(e,this.mediaSequenceSync_.start);e!==t&&this.logger_(`getSyncInfoFromMediaSequenceSync_. Pulled target time from ${e} to ${t}`);let n=this.mediaSequenceSync_.getSyncInfoForTime(t);if(!n)return null;if(!n.isAppended)return n;let r=this.mediaSequenceSync_.getSyncInfoForTime(n.end);return r?(r.isAppended&&this.logger_(`getSyncInfoFromMediaSequenceSync_: We encounter unexpected scenario where next media sequence sync info is also appended!`),r):null}generateSegmentInfo_(e){let{independent:t,playlist:n,mediaIndex:r,startOfSegment:i,isSyncRequest:a,partIndex:o,forceTimestampOffset:s,getMediaInfoForTime:c}=e,l=n.segments[r],u=typeof o==`number`&&l.parts[o],d={requestId:`segment-loader-`+Math.random(),uri:u&&u.resolvedUri||l.resolvedUri,mediaIndex:r,partIndex:u?o:null,isSyncRequest:a,startOfSegment:i,playlist:n,bytes:null,encryptedBytes:null,timestampOffset:null,timeline:l.timeline,duration:u&&u.duration||l.duration,segment:l,part:u,byteLength:0,transmuxer:this.transmuxer_,getMediaInfoForTime:c,independent:t},f=s===void 0?this.isPendingTimestampOffset_:s;d.timestampOffset=this.timestampOffsetForSegment_({segmentTimeline:l.timeline,currentTimeline:this.currentTimeline_,startOfSegment:i,buffered:this.buffered_(),overrideCheck:f});let p=Fl(this.sourceUpdater_.audioBuffered());return typeof p==`number`&&(d.audioAppendStart=p-this.sourceUpdater_.audioTimestampOffset()),this.sourceUpdater_.videoBuffered().length&&(d.gopsToAlignWith=Af(this.gopBuffer_,this.currentTime_()-this.sourceUpdater_.videoTimestampOffset(),this.timeMapping_)),d}timestampOffsetForSegment_(e){return Uf(e)}earlyAbortWhenNeeded_(e){if(this.vhs_.tech_.paused()||!this.xhrOptions_.timeout||!this.playlist_.attributes.BANDWIDTH||Date.now()-(e.firstBytesReceivedAt||Date.now())<1e3)return;let t=this.currentTime_(),n=e.bandwidth,r=this.pendingSegment_.duration,i=su.estimateSegmentRequestTime(r,n,this.playlist_,e.bytesReceived),a=Ml(this.buffered_(),t,this.vhs_.tech_.playbackRate())-1;if(i<=a)return;let o=gf({main:this.vhs_.playlists.main,currentTime:t,bandwidth:n,duration:this.duration_(),segmentDuration:r,timeUntilRebuffer:a,currentTimeline:this.currentTimeline_,syncController:this.syncController_});if(!o)return;let s=i-a-o.rebufferingImpact,c=.5;a<=wl&&(c=1),!(!o.playlist||o.playlist.uri===this.playlist_.uri||s{r[e.stream]=r[e.stream]||{startTime:1/0,captions:[],endTime:0};let t=r[e.stream];t.startTime=Math.min(t.startTime,e.startTime+n),t.endTime=Math.max(t.endTime,e.endTime+n),t.captions.push(e)}),Object.keys(r).forEach(e=>{let{startTime:t,endTime:i,captions:a}=r[e],o=this.inbandTextTracks_;this.logger_(`adding cues from ${t} -> ${i} for ${e}`),bf(o,this.vhs_.tech_,e),Of(t,i,o[e]),xf({captionArray:a,inbandTextTracks:o,timestampOffset:n})}),this.transmuxer_&&this.transmuxer_.postMessage({action:`clearParsedMp4Captions`})}handleId3_(e,t,n){if(this.earlyAbortWhenNeeded_(e.stats),!this.checkForAbort_(e.requestId)){if(!this.pendingSegment_.hasAppendedData_){this.metadataQueue_.id3.push(this.handleId3_.bind(this,e,t,n));return}this.addMetadataToTextTrack(n,t,this.duration_())}}processMetadataQueue_(){this.metadataQueue_.id3.forEach(e=>e()),this.metadataQueue_.caption.forEach(e=>e()),this.metadataQueue_.id3=[],this.metadataQueue_.caption=[]}processCallQueue_(){let e=this.callQueue_;this.callQueue_=[],e.forEach(e=>e())}processLoadQueue_(){let e=this.loadQueue_;this.loadQueue_=[],e.forEach(e=>e())}hasEnoughInfoToLoad_(){if(this.loaderType_!==`audio`)return!0;let e=this.pendingSegment_;return e?this.getCurrentMediaInfo_()?!Wf({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:e.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}):!0:!1}getCurrentMediaInfo_(e=this.pendingSegment_){return e&&e.trackInfo||this.currentMediaInfo_}getMediaInfo_(e=this.pendingSegment_){return this.getCurrentMediaInfo_(e)||this.startingMediaInfo_}getPendingSegmentPlaylist(){return this.pendingSegment_?this.pendingSegment_.playlist:null}hasEnoughInfoToAppend_(){if(!this.sourceUpdater_.ready()||this.waitingOnRemove_||this.quotaExceededErrorRetryTimeout_)return!1;let e=this.pendingSegment_,t=this.getCurrentMediaInfo_();if(!e||!t)return!1;let{hasAudio:n,hasVideo:r,isMuxed:i}=t;return!(r&&!e.videoTimingInfo||n&&!this.audioDisabled_&&!i&&!e.audioTimingInfo||Wf({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:e.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}))}handleData_(e,t){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(this.callQueue_.length||!this.hasEnoughInfoToAppend_()){qf(this),this.callQueue_.push(this.handleData_.bind(this,e,t));return}let n=this.pendingSegment_;if(this.setTimeMapping_(n.timeline),this.updateMediaSecondsLoaded_(n.part||n.segment),this.mediaSource_.readyState!==`closed`){if(e.map&&(e.map=this.initSegmentForMap(e.map,!0),n.segment.map=e.map),e.key&&this.segmentKey(e.key,!0),n.isFmp4=e.isFmp4,n.timingInfo=n.timingInfo||{},n.isFmp4)this.trigger(`fmp4`),n.timingInfo.start=n[Hf(t.type)].start;else{let e=this.getCurrentMediaInfo_(),t=this.loaderType_===`main`&&e&&e.hasVideo,r;t&&(r=n.videoTimingInfo.start),n.timingInfo.start=this.trueSegmentStart_({currentStart:n.timingInfo.start,playlist:n.playlist,mediaIndex:n.mediaIndex,currentVideoTimestampOffset:this.sourceUpdater_.videoTimestampOffset(),useVideoTimingInfo:t,firstVideoFrameTimeForData:r,videoTimingInfo:n.videoTimingInfo,audioTimingInfo:n.audioTimingInfo})}if(this.updateAppendInitSegmentStatus(n,t.type),this.updateSourceBufferTimestampOffset_(n),n.isSyncRequest){this.updateTimingInfoEnd_(n),this.syncController_.saveSegmentTimingInfo({segmentInfo:n,shouldSaveTimelineMapping:this.loaderType_===`main`});let e=this.chooseNextRequest_();if(e.mediaIndex!==n.mediaIndex||e.partIndex!==n.partIndex){this.logger_(`sync segment was incorrect, not appending`);return}this.logger_(`sync segment was correct, appending`)}n.hasAppendedData_=!0,this.processMetadataQueue_(),this.appendData_(n,t)}}updateAppendInitSegmentStatus(e,t){this.loaderType_===`main`&&typeof e.timestampOffset==`number`&&!e.changedTimestampOffset&&(this.appendInitSegment_={audio:!0,video:!0}),this.playlistOfLastInitSegment_[t]!==e.playlist&&(this.appendInitSegment_[t]=!0)}getInitSegmentAndUpdateState_({type:e,initSegment:t,map:n,playlist:r}){if(n){let e=Yu(n);if(this.activeInitSegmentId_===e)return null;t=this.initSegmentForMap(n,!0).bytes,this.activeInitSegmentId_=e}return t&&this.appendInitSegment_[e]?(this.playlistOfLastInitSegment_[e]=r,this.appendInitSegment_[e]=!1,this.activeInitSegmentId_=null,t):null}handleQuotaExceededError_({segmentInfo:e,type:t,bytes:n},r){let i=this.sourceUpdater_.audioBuffered(),a=this.sourceUpdater_.videoBuffered();i.length>1&&this.logger_(`On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: `+Nl(i).join(`, `)),a.length>1&&this.logger_(`On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: `+Nl(a).join(`, `));let o=i.length?i.start(0):0,s=i.length?i.end(i.length-1):0,c=a.length?a.start(0):0,l=a.length?a.end(a.length-1):0;if(s-o<=Ff&&l-c<=Ff){this.logger_(`On QUOTA_EXCEEDED_ERR, single segment too large to append to buffer, triggering an error. Appended byte length: ${n.byteLength}, audio buffer: ${Nl(i).join(`, `)}, video buffer: ${Nl(a).join(`, `)}, `),this.error({message:`Quota exceeded error with append of a single segment of content`,excludeUntil:1/0}),this.trigger(`error`);return}this.waitingOnRemove_=!0,this.callQueue_.push(this.appendToSourceBuffer_.bind(this,{segmentInfo:e,type:t,bytes:n}));let u=this.currentTime_()-Ff;this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${u}`),this.remove(0,u,()=>{this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${Ff}s`),this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=I.default.setTimeout(()=>{this.logger_(`On QUOTA_EXCEEDED_ERR, re-processing call queue`),this.quotaExceededErrorRetryTimeout_=null,this.processCallQueue_()},Ff*1e3)},!0)}handleAppendError_({segmentInfo:e,type:t,bytes:n},r){if(r){if(r.code===yu){this.handleQuotaExceededError_({segmentInfo:e,type:t,bytes:n});return}this.logger_(`Received non QUOTA_EXCEEDED_ERR on append`,r),this.error({message:`${t} append of ${n.length}b failed for segment #${e.mediaIndex} in playlist ${e.playlist.id}`,metadata:{errorType:W.Error.StreamingFailedToAppendSegment}}),this.trigger(`appenderror`)}}appendToSourceBuffer_({segmentInfo:e,type:t,initSegment:n,data:r,bytes:i}){if(!i){let e=[r],t=r.byteLength;n&&(e.unshift(n),t+=n.byteLength),i=vf({bytes:t,segments:e})}let a={segmentInfo:Zf({type:this.loaderType_,segment:e})};this.trigger({type:`segmentappendstart`,metadata:a}),this.sourceUpdater_.appendBuffer({segmentInfo:e,type:t,bytes:i},this.handleAppendError_.bind(this,{segmentInfo:e,type:t,bytes:i}))}handleSegmentTimingInfo_(e,t,n){if(!this.pendingSegment_||t!==this.pendingSegment_.requestId)return;let r=this.pendingSegment_.segment,i=`${e}TimingInfo`;r[i]||(r[i]={}),r[i].transmuxerPrependedSeconds=n.prependedContentDuration||0,r[i].transmuxedPresentationStart=n.start.presentation,r[i].transmuxedDecodeStart=n.start.decode,r[i].transmuxedPresentationEnd=n.end.presentation,r[i].transmuxedDecodeEnd=n.end.decode,r[i].baseMediaDecodeTime=n.baseMediaDecodeTime}appendData_(e,t){let{type:n,data:r}=t;if(!r||!r.byteLength||n===`audio`&&this.audioDisabled_)return;let i=this.getInitSegmentAndUpdateState_({type:n,initSegment:t.initSegment,playlist:e.playlist,map:e.isFmp4?e.segment.map:null});this.appendToSourceBuffer_({segmentInfo:e,type:n,initSegment:i,data:r})}loadSegment_(e){if(this.state=`WAITING`,this.pendingSegment_=e,this.trimBackBuffer_(e),typeof e.timestampOffset==`number`&&this.transmuxer_&&this.transmuxer_.postMessage({action:`clearAllMp4Captions`}),!this.hasEnoughInfoToLoad_()){qf(this),this.loadQueue_.push(()=>{let t=me({},e,{forceTimestampOffset:!0});me(e,this.generateSegmentInfo_(t)),this.isPendingTimestampOffset_=!1,this.updateTransmuxerAndRequestSegment_(e)});return}this.updateTransmuxerAndRequestSegment_(e)}updateTransmuxerAndRequestSegment_(e){this.shouldUpdateTransmuxerTimestampOffset_(e.timestampOffset)&&(this.gopBuffer_.length=0,e.gopsToAlignWith=[],this.timeMapping_=0,this.transmuxer_.postMessage({action:`reset`}),this.transmuxer_.postMessage({action:`setTimestampOffset`,timestampOffset:e.timestampOffset}));let t=this.createSimplifiedSegmentObj_(e),n=this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex),r=this.mediaIndex!==null,i=e.timeline!==this.currentTimeline_&&e.timeline>0,a=n||r&&i;this.logger_(`Requesting ${yf(e.uri)} ${Vf(e)}`),t.map&&!t.map.bytes&&(this.logger_(`going to request init segment.`),this.appendInitSegment_={video:!0,audio:!0}),e.abortRequests=of({xhr:this.vhs_.xhr,xhrOptions:this.xhrOptions_,decryptionWorker:this.decrypter_,segment:t,abortFn:this.handleAbort_.bind(this,e),progressFn:this.handleProgress_.bind(this),trackInfoFn:this.handleTrackInfo_.bind(this),timingInfoFn:this.handleTimingInfo_.bind(this),videoSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,`video`,e.requestId),audioSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,`audio`,e.requestId),captionsFn:this.handleCaptions_.bind(this),isEndOfTimeline:a,endedTimelineFn:()=>{this.logger_(`received endedtimeline callback`)},id3Fn:this.handleId3_.bind(this),dataFn:this.handleData_.bind(this),doneFn:this.segmentRequestFinished_.bind(this),onTransmuxerLog:({message:t,level:n,stream:r})=>{this.logger_(`${Vf(e)} logged from transmuxer stream ${r} as a ${n}: ${t}`)},triggerSegmentEventFn:({type:e,segment:t,keyInfo:n,trackInfo:r,timingInfo:i})=>{let a={segmentInfo:Zf({segment:t})};n&&(a.keyInfo=n),r&&(a.trackInfo=r),i&&(a.timingInfo=i),this.trigger({type:e,metadata:a})}})}trimBackBuffer_(e){let t=Bf(this.seekable_(),this.currentTime_(),this.playlist_.targetDuration||10);t>0&&this.remove(0,t)}createSimplifiedSegmentObj_(e){let t=e.segment,n=e.part,r=e.segment.key||e.segment.map&&e.segment.map.key,i=e.segment.map&&!e.segment.map.bytes,a={resolvedUri:n?n.resolvedUri:t.resolvedUri,byterange:n?n.byterange:t.byterange,requestId:e.requestId,transmuxer:e.transmuxer,audioAppendStart:e.audioAppendStart,gopsToAlignWith:e.gopsToAlignWith,part:e.part,type:this.loaderType_,start:e.startOfSegment,duration:e.duration,isEncrypted:r,isMediaInitialization:i},o=e.playlist.segments[e.mediaIndex-1];if(o&&o.timeline===t.timeline&&(o.videoTimingInfo?a.baseStartTime=o.videoTimingInfo.transmuxedDecodeEnd:o.audioTimingInfo&&(a.baseStartTime=o.audioTimingInfo.transmuxedDecodeEnd)),t.key){let n=t.key.iv||new Uint32Array([0,0,0,e.mediaIndex+e.playlist.mediaSequence]);a.key=this.segmentKey(t.key),a.key.iv=n}return t.map&&(a.map=this.initSegmentForMap(t.map)),a}saveTransferStats_(e){this.mediaRequests+=1,e&&(this.mediaBytesTransferred+=e.bytesReceived,this.mediaTransferDuration+=e.roundTripTime)}saveBandwidthRelatedStats_(e,t){if(this.pendingSegment_.byteLength=t.bytesReceived,ee.playlist.targetDuration*3,a=r&&r.end&&this.currentTime_()-r.end>e.playlist.partTargetDuration*3;if(i||a){this.logger_(`bad ${i?`segment`:`part`} ${Vf(e)}`),this.resetEverything();return}this.mediaIndex!==null&&this.trigger(`bandwidthupdate`),this.trigger(`progress`),this.mediaIndex=e.mediaIndex,this.partIndex=e.partIndex,this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex)&&this.endOfStream(),this.trigger(`appended`),e.hasAppendedData_&&this.mediaAppends++,this.paused()||this.monitorBuffer_()}recordThroughput_(e){if(e.duratione.toUpperCase()):e},tp=[`video`,`audio`],np=(e,t)=>{let n=t[`${e}Buffer`];return n&&n.updating||t.queuePending[e]},rp=(e,t)=>{for(let n=0;n{if(t.queue.length===0)return;let n=0,r=t.queue[n];if(r.type===`mediaSource`){!t.updating()&&t.mediaSource.readyState!==`closed`&&(t.queue.shift(),r.action(t),r.doneFn&&r.doneFn(),ip(`audio`,t),ip(`video`,t));return}if(e!==`mediaSource`&&!(!t.ready()||t.mediaSource.readyState===`closed`||np(e,t))){if(r.type!==e){if(n=rp(e,t.queue),n===null)return;r=t.queue[n]}if(t.queue.splice(n,1),t.queuePending[e]=r,r.action(e,t),!r.doneFn){t.queuePending[e]=null,ip(e,t);return}}},ap=(e,t)=>{let n=t[`${e}Buffer`],r=ep(e);n&&(n.removeEventListener(`updateend`,t[`on${r}UpdateEnd_`]),n.removeEventListener(`error`,t[`on${r}Error_`]),t.codecs[e]=null,t[`${e}Buffer`]=null)},op=(e,t)=>e&&t&&Array.prototype.indexOf.call(e.sourceBuffers,t)!==-1,sp={appendBuffer:(e,t,n)=>(r,i)=>{let a=i[`${r}Buffer`];if(op(i.mediaSource,a)){i.logger_(`Appending segment ${t.mediaIndex}'s ${e.length} bytes to ${r}Buffer`);try{a.appendBuffer(e)}catch(e){i.logger_(`Error with code ${e.code} `+(e.code===yu?`(QUOTA_EXCEEDED_ERR) `:``)+`when appending segment ${t.mediaIndex} to ${r}Buffer`),i.queuePending[r]=null,n(e)}}},remove:(e,t)=>(n,r)=>{let i=r[`${n}Buffer`];if(op(r.mediaSource,i)){r.logger_(`Removing ${e} to ${t} from ${n}Buffer`);try{i.remove(e,t)}catch{r.logger_(`Remove ${e} to ${t} from ${n}Buffer failed`)}}},timestampOffset:e=>(t,n)=>{let r=n[`${t}Buffer`];op(n.mediaSource,r)&&(n.logger_(`Setting ${t}timestampOffset to ${e}`),r.timestampOffset=e)},callback:e=>(t,n)=>{e()},endOfStream:e=>t=>{if(t.mediaSource.readyState===`open`){t.logger_(`Calling mediaSource endOfStream(${e||``})`);try{t.mediaSource.endOfStream(e)}catch(e){W.log.warn(`Failed to call media source endOfStream`,e)}}},duration:e=>t=>{t.logger_(`Setting mediaSource duration to ${e}`);try{t.mediaSource.duration=e}catch(e){W.log.warn(`Failed to set media source duration`,e)}},abort:()=>(e,t)=>{if(t.mediaSource.readyState!==`open`)return;let n=t[`${e}Buffer`];if(op(t.mediaSource,n)){t.logger_(`calling abort on ${e}Buffer`);try{n.abort()}catch(t){W.log.warn(`Failed to abort on ${e}Buffer`,t)}}},addSourceBuffer:(e,t)=>n=>{let r=ep(e),i=ze(t);n.logger_(`Adding ${e}Buffer with codec ${t} to mediaSource`);let a=n.mediaSource.addSourceBuffer(i);a.addEventListener(`updateend`,n[`on${r}UpdateEnd_`]),a.addEventListener(`error`,n[`on${r}Error_`]),n.codecs[e]=t,n[`${e}Buffer`]=a},removeSourceBuffer:e=>t=>{let n=t[`${e}Buffer`];if(ap(e,t),op(t.mediaSource,n)){t.logger_(`Removing ${e}Buffer with codec ${t.codecs[e]} from mediaSource`);try{t.mediaSource.removeSourceBuffer(n)}catch(t){W.log.warn(`Failed to removeSourceBuffer ${e}Buffer`,t)}}},changeType:e=>(t,n)=>{let r=n[`${t}Buffer`],i=ze(e);if(!op(n.mediaSource,r))return;let a=e.substring(0,e.indexOf(`.`)),o=n.codecs[t];if(o.substring(0,o.indexOf(`.`))===a)return;let s={codecsChangeInfo:{from:o,to:e}};n.trigger({type:`codecschange`,metadata:s}),n.logger_(`changing ${t}Buffer codec from ${o} to ${e}`);try{r.changeType(i),n.codecs[t]=e}catch(e){s.errorType=W.Error.StreamingCodecsChangeError,s.error=e,e.metadata=s,n.error_=e,n.trigger(`error`),W.log.warn(`Failed to changeType on ${t}Buffer`,e)}}},cp=({type:e,sourceUpdater:t,action:n,doneFn:r,name:i})=>{t.queue.push({type:e,action:n,doneFn:r,name:i}),ip(e,t)},lp=(e,t)=>n=>{let r=Cl(t[`${e}Buffered`]());if(t.logger_(`received "updateend" event for ${e} Source Buffer: `,r),t.queuePending[e]){let n=t.queuePending[e].doneFn;t.queuePending[e]=null,n&&n(t[`${e}Error_`])}ip(e,t)},up=class extends W.EventTarget{constructor(e){super(),this.mediaSource=e,this.sourceopenListener_=()=>ip(`mediaSource`,this),this.mediaSource.addEventListener(`sourceopen`,this.sourceopenListener_),this.logger_=bl(`SourceUpdater`),this.audioTimestampOffset_=0,this.videoTimestampOffset_=0,this.queue=[],this.queuePending={audio:null,video:null},this.delayedAudioAppendQueue_=[],this.videoAppendQueued_=!1,this.codecs={},this.onVideoUpdateEnd_=lp(`video`,this),this.onAudioUpdateEnd_=lp(`audio`,this),this.onVideoError_=e=>{this.videoError_=e},this.onAudioError_=e=>{this.audioError_=e},this.createdSourceBuffers_=!1,this.initializedEme_=!1,this.triggeredReady_=!1}initializedEme(){this.initializedEme_=!0,this.triggerReady()}hasCreatedSourceBuffers(){return this.createdSourceBuffers_}hasInitializedAnyEme(){return this.initializedEme_}ready(){return this.hasCreatedSourceBuffers()&&this.hasInitializedAnyEme()}createSourceBuffers(e){this.hasCreatedSourceBuffers()||(this.addOrChangeSourceBuffers(e),this.createdSourceBuffers_=!0,this.trigger(`createdsourcebuffers`),this.triggerReady())}triggerReady(){this.ready()&&!this.triggeredReady_&&(this.triggeredReady_=!0,this.trigger(`ready`))}addSourceBuffer(e,t){cp({type:`mediaSource`,sourceUpdater:this,action:sp.addSourceBuffer(e,t),name:`addSourceBuffer`})}abort(e){cp({type:e,sourceUpdater:this,action:sp.abort(e),name:`abort`})}removeSourceBuffer(e){if(!this.canRemoveSourceBuffer()){W.log.error(`removeSourceBuffer is not supported!`);return}cp({type:`mediaSource`,sourceUpdater:this,action:sp.removeSourceBuffer(e),name:`removeSourceBuffer`})}canRemoveSourceBuffer(){return!W.browser.IS_FIREFOX&&I.default.MediaSource&&I.default.MediaSource.prototype&&typeof I.default.MediaSource.prototype.removeSourceBuffer==`function`}static canChangeType(){return I.default.SourceBuffer&&I.default.SourceBuffer.prototype&&typeof I.default.SourceBuffer.prototype.changeType==`function`}canChangeType(){return this.constructor.canChangeType()}changeType(e,t){if(!this.canChangeType()){W.log.error(`changeType is not supported!`);return}cp({type:e,sourceUpdater:this,action:sp.changeType(t),name:`changeType`})}addOrChangeSourceBuffers(e){if(!e||typeof e!=`object`||Object.keys(e).length===0)throw Error(`Cannot addOrChangeSourceBuffers to undefined codecs`);Object.keys(e).forEach(t=>{let n=e[t];if(!this.hasCreatedSourceBuffers())return this.addSourceBuffer(t,n);this.canChangeType()&&this.changeType(t,n)})}appendBuffer(e,t){let{segmentInfo:n,type:r,bytes:i}=e;if(this.processedAppend_=!0,r===`audio`&&this.videoBuffer&&!this.videoAppendQueued_){this.delayedAudioAppendQueue_.push([e,t]),this.logger_(`delayed audio append of ${i.length} until video append`);return}let a=t;if(cp({type:r,sourceUpdater:this,action:sp.appendBuffer(i,n||{mediaIndex:-1},a),doneFn:t,name:`appendBuffer`}),r===`video`){if(this.videoAppendQueued_=!0,!this.delayedAudioAppendQueue_.length)return;let e=this.delayedAudioAppendQueue_.slice();this.logger_(`queuing delayed audio ${e.length} appendBuffers`),this.delayedAudioAppendQueue_.length=0,e.forEach(e=>{this.appendBuffer.apply(this,e)})}}audioBuffered(){return op(this.mediaSource,this.audioBuffer)&&this.audioBuffer.buffered?this.audioBuffer.buffered:Sl()}videoBuffered(){return op(this.mediaSource,this.videoBuffer)&&this.videoBuffer.buffered?this.videoBuffer.buffered:Sl()}buffered(){let e=op(this.mediaSource,this.videoBuffer)?this.videoBuffer:null,t=op(this.mediaSource,this.audioBuffer)?this.audioBuffer:null;return t&&!e?this.audioBuffered():e&&!t?this.videoBuffered():Al(this.audioBuffered(),this.videoBuffered())}setDuration(e,t=$f){cp({type:`mediaSource`,sourceUpdater:this,action:sp.duration(e),name:`duration`,doneFn:t})}endOfStream(e=null,t=$f){typeof e!=`string`&&(e=void 0),cp({type:`mediaSource`,sourceUpdater:this,action:sp.endOfStream(e),name:`endOfStream`,doneFn:t})}removeAudio(e,t,n=$f){if(!this.audioBuffered().length||this.audioBuffered().end(0)===0){n();return}cp({type:`audio`,sourceUpdater:this,action:sp.remove(e,t),doneFn:n,name:`remove`})}removeVideo(e,t,n=$f){if(!this.videoBuffered().length||this.videoBuffered().end(0)===0){n();return}cp({type:`video`,sourceUpdater:this,action:sp.remove(e,t),doneFn:n,name:`remove`})}updating(){return!!(np(`audio`,this)||np(`video`,this))}audioTimestampOffset(e){return e!==void 0&&this.audioBuffer&&this.audioTimestampOffset_!==e&&(cp({type:`audio`,sourceUpdater:this,action:sp.timestampOffset(e),name:`timestampOffset`}),this.audioTimestampOffset_=e),this.audioTimestampOffset_}videoTimestampOffset(e){return e!==void 0&&this.videoBuffer&&this.videoTimestampOffset_!==e&&(cp({type:`video`,sourceUpdater:this,action:sp.timestampOffset(e),name:`timestampOffset`}),this.videoTimestampOffset_=e),this.videoTimestampOffset_}audioQueueCallback(e){this.audioBuffer&&cp({type:`audio`,sourceUpdater:this,action:sp.callback(e),name:`callback`})}videoQueueCallback(e){this.videoBuffer&&cp({type:`video`,sourceUpdater:this,action:sp.callback(e),name:`callback`})}dispose(){this.trigger(`dispose`),tp.forEach(e=>{this.abort(e),this.canRemoveSourceBuffer()?this.removeSourceBuffer(e):this[`${e}QueueCallback`](()=>ap(e,this))}),this.videoAppendQueued_=!1,this.delayedAudioAppendQueue_.length=0,this.sourceopenListener_&&this.mediaSource.removeEventListener(`sourceopen`,this.sourceopenListener_),this.off()}},dp=e=>decodeURIComponent(escape(String.fromCharCode.apply(null,e))),fp=e=>{let t=new Uint8Array(e);return Array.from(t).map(e=>e.toString(16).padStart(2,`0`)).join(``)},pp=new Uint8Array(` `.split(``).map(e=>e.charCodeAt(0))),mp=class extends Error{constructor(){super(`Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.`)}},hp=class extends Qf{constructor(e,t={}){super(e,t),this.mediaSource_=null,this.subtitlesTrack_=null,this.featuresNativeTextTracks_=e.featuresNativeTextTracks,this.loadVttJs=e.loadVttJs,this.shouldSaveSegmentTimingInfo_=!1}buffered_(){if(!this.subtitlesTrack_||!this.subtitlesTrack_.cues||!this.subtitlesTrack_.cues.length)return Sl();let e=this.subtitlesTrack_.cues,t=e[0].startTime,n=e[e.length-1].startTime;return Sl([[t,n]])}initSegmentForMap(e,t=!1){if(!e)return null;let n=Yu(e),r=this.initSegments_[n];if(t&&!r&&e.bytes){let t=pp.byteLength+e.bytes.byteLength,i=new Uint8Array(t);i.set(e.bytes),i.set(pp,e.bytes.byteLength),this.initSegments_[n]=r={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:i}}return r||e}couldBeginLoading_(){return this.playlist_&&this.subtitlesTrack_&&!this.paused()}init_(){return this.state=`READY`,this.resetEverything(),this.monitorBuffer_()}track(e){return e===void 0?this.subtitlesTrack_:(this.subtitlesTrack_=e,this.state===`INIT`&&this.couldBeginLoading_()&&this.init_(),this.subtitlesTrack_)}remove(e,t){Of(e,t,this.subtitlesTrack_)}fillBuffer_(){let e=this.chooseNextRequest_();if(e){if(this.syncController_.timestampOffsetForTimeline(e.timeline)===null){this.syncController_.one(`timestampoffset`,()=>{this.state=`READY`,this.paused()||this.monitorBuffer_()}),this.state=`WAITING_ON_TIMELINE`;return}this.loadSegment_(e)}}timestampOffsetForSegment_(){return null}chooseNextRequest_(){return this.skipEmptySegments_(super.chooseNextRequest_())}skipEmptySegments_(e){for(;e&&e.segment.empty;){if(e.mediaIndex+1>=e.playlist.segments.length){e=null;break}e=this.generateSegmentInfo_({playlist:e.playlist,mediaIndex:e.mediaIndex+1,startOfSegment:e.startOfSegment+e.duration,isSyncRequest:e.isSyncRequest})}return e}stopForError(e){this.error(e),this.state=`READY`,this.pause(),this.trigger(`error`)}segmentRequestFinished_(e,t,n){if(!this.subtitlesTrack_){this.state=`READY`;return}if(this.saveTransferStats_(t.stats),!this.pendingSegment_){this.state=`READY`,this.mediaRequestsAborted+=1;return}if(e){e.code===Bd.TIMEOUT&&this.handleTimeout_(),e.code===Bd.ABORTED?this.mediaRequestsAborted+=1:this.mediaRequestsErrored+=1,this.stopForError(e);return}let r=this.pendingSegment_,i=n.mp4VttCues&&n.mp4VttCues.length;i&&(r.mp4VttCues=n.mp4VttCues),this.saveBandwidthRelatedStats_(r.duration,t.stats),t.key&&this.segmentKey(t.key,!0),this.state=`APPENDING`,this.trigger(`appending`);let a=r.segment;if(a.map&&(a.map.bytes=t.map.bytes),r.bytes=t.bytes,typeof I.default.WebVTT!=`function`&&typeof this.loadVttJs==`function`){this.state=`WAITING_ON_VTTJS`,this.loadVttJs().then(()=>this.segmentRequestFinished_(e,t,n),()=>this.stopForError({message:`Error loading vtt.js`}));return}a.requested=!0;try{this.parseVTTCues_(r)}catch(e){this.stopForError({message:e.message,metadata:{errorType:W.Error.StreamingVttParserError,error:e}});return}if(i||this.updateTimeMapping_(r,this.syncController_.timelines[r.timeline],this.playlist_),r.cues.length?r.timingInfo={start:r.cues[0].startTime,end:r.cues[r.cues.length-1].endTime}:r.timingInfo={start:r.startOfSegment,end:r.startOfSegment+r.duration},r.isSyncRequest){this.trigger(`syncinfoupdate`),this.pendingSegment_=null,this.state=`READY`;return}r.byteLength=r.bytes.byteLength,this.mediaSecondsLoaded+=a.duration,r.cues.forEach(e=>{this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_?new I.default.VTTCue(e.startTime,e.endTime,e.text):e)}),kf(this.subtitlesTrack_),this.handleAppendsDone_()}handleData_(e,t){let n=e&&e.type===`vtt`,r=t&&t.type===`text`;n&&r&&super.handleData_(e,t)}updateTimingInfoEnd_(){}parseMp4VttCues_(e){let t=this.sourceUpdater_.videoTimestampOffset()===null?this.sourceUpdater_.audioTimestampOffset():this.sourceUpdater_.videoTimestampOffset();e.mp4VttCues.forEach(n=>{let r=n.start+t,i=n.end+t,a=new I.default.VTTCue(r,i,n.cueText);n.settings&&n.settings.split(` `).forEach(e=>{let t=e.split(`:`),n=t[0],r=t[1];a[n]=isNaN(r)?r:Number(r)}),e.cues.push(a)})}parseVTTCues_(e){let t,n=!1;if(typeof I.default.WebVTT!=`function`)throw new mp;if(e.cues=[],e.timestampmap={MPEGTS:0,LOCAL:0},e.mp4VttCues){this.parseMp4VttCues_(e);return}typeof I.default.TextDecoder==`function`?t=new I.default.TextDecoder(`utf8`):(t=I.default.WebVTT.StringDecoder(),n=!0);let r=new I.default.WebVTT.Parser(I.default,I.default.vttjs,t);if(r.oncue=e.cues.push.bind(e.cues),r.ontimestampmap=t=>{e.timestampmap=t},r.onparsingerror=e=>{W.log.warn(`Error encountered when parsing cues: `+e.message)},e.segment.map){let t=e.segment.map.bytes;n&&(t=dp(t)),r.parse(t)}let i=e.bytes;n&&(i=dp(i)),r.parse(i),r.flush()}updateTimeMapping_(e,t,n){let r=e.segment;if(!t)return;if(!e.cues.length){r.empty=!0;return}let{MPEGTS:i,LOCAL:a}=e.timestampmap,o=i/lr.ONE_SECOND_IN_TS-a+t.mapping;if(e.cues.forEach(e=>{let n=e.endTime-e.startTime,r=this.handleRollover_(e.startTime+o,t.time);e.startTime=Math.max(r,0),e.endTime=Math.max(r+n,0)}),!n.syncInfo){let t=e.cues[0].startTime,i=e.cues[e.cues.length-1].startTime;n.syncInfo={mediaSequence:n.mediaSequence+e.mediaIndex,time:Math.min(t,i-r.duration)}}}handleRollover_(e,t){if(t===null)return e;let n=e*lr.ONE_SECOND_IN_TS,r=t*lr.ONE_SECOND_IN_TS,i;for(i=r4294967296;)n+=i;return n/lr.ONE_SECOND_IN_TS}},gp=function(e,t){let n=e.cues;for(let e=0;e=r.adStartTime&&t<=r.adEndTime)return r}return null},_p=function(e,t,n=0){if(!e.segments)return;let r=n,i;for(let n=0;n=this.start&&e0}resetAppendStatus(){this.segmentSyncInfo_.resetAppendedStatus(),this.partsSyncInfo_.forEach(e=>e.resetAppendedStatus())}},bp=class{constructor(){this.storage_=new Map,this.diagnostics_=``,this.isReliable_=!1,this.start_=-1/0,this.end_=1/0}get start(){return this.start_}get end(){return this.end_}get diagnostics(){return this.diagnostics_}get isReliable(){return this.isReliable_}resetAppendedStatus(){this.storage_.forEach(e=>e.resetAppendStatus())}update(e,t){let{mediaSequence:n,segments:r}=e;if(this.isReliable_=this.isReliablePlaylist_(n,r),this.isReliable_)return this.updateStorage_(r,n,this.calculateBaseTime_(n,r,t))}getSyncInfoForTime(e){for(let{segmentSyncInfo:t,partsSyncInfo:n}of this.storage_.values())if(n.length){for(let t of n)if(t.isInRange(e))return t}else if(t.isInRange(e))return t;return null}getSyncInfoForMediaSequence(e){return this.storage_.get(e)}updateStorage_(e,t,n){let r=new Map,i=` `,a=n,o=t;this.start_=a,e.forEach((e,t)=>{let n=this.storage_.get(o),s=a,c=s+e.duration,l=!!(n&&n.segmentSyncInfo&&n.segmentSyncInfo.isAppended),u=new vp({start:s,end:c,appended:l,segmentIndex:t});e.syncInfo=u;let d=a,f=(e.parts||[]).map((e,r)=>{let a=d,s=d+e.duration,c=!!(n&&n.partsSyncInfo&&n.partsSyncInfo[r]&&n.partsSyncInfo[r].isAppended),l=new vp({start:a,end:s,appended:c,segmentIndex:t,partIndex:r});return d=s,i+=`Media Sequence: ${o}.${r} | Range: ${a} --> ${s} | Appended: ${c}\n`,e.syncInfo=l,l});r.set(o,new yp(u,f)),i+=`${yf(e.resolvedUri)} | Media Sequence: ${o} | Range: ${s} --> ${c} | Appended: ${l}\n`,o++,a=c}),this.end_=a,this.storage_=r,this.diagnostics_=i}calculateBaseTime_(e,t,n){if(!this.storage_.size)return 0;if(this.storage_.has(e))return this.storage_.get(e).segmentSyncInfo.start;let r=Math.min(...this.storage_.keys());if(en===1/0?null:{time:0,segmentIndex:0,partIndex:null}},{name:`MediaSequence`,run:(e,t,n,r,i,a)=>{let o=e.getMediaSequenceSync(a);if(!o||!o.isReliable)return null;let s=o.getSyncInfoForTime(i);return s?{time:s.start,partIndex:s.partIndex,segmentIndex:s.segmentIndex}:null}},{name:`ProgramDateTime`,run:(e,t,n,r,i)=>{if(!Object.keys(e.timelineToDatetimeMappings).length)return null;let a=null,o=null,s=Rl(t);i||=0;for(let n=0;n{let a=null,o=null;i||=0;let s=Rl(t);for(let e=0;e=e)&&(o=e,a={time:l,segmentIndex:n.segmentIndex,partIndex:n.partIndex})}}return a}},{name:`Discontinuity`,run:(e,t,n,r,i)=>{let a=null;if(i||=0,t.discontinuityStarts&&t.discontinuityStarts.length){let n=null;for(let r=0;r=e)&&(n=e,a={time:c.time,segmentIndex:o,partIndex:null})}}}return a}},{name:`Playlist`,run:(e,t,n,r,i)=>t.syncInfo?{time:t.syncInfo.time,segmentIndex:t.syncInfo.mediaSequence-t.mediaSequence,partIndex:null}:null}],wp=class extends W.EventTarget{constructor(e={}){super(),this.timelines=[],this.discontinuities=[],this.timelineToDatetimeMappings={};let t=new bp,n=new xp(t),r=new xp(t);this.mediaSequenceStorage_={main:t,audio:n,vtt:r},this.logger_=bl(`SyncController`)}getMediaSequenceSync(e){return this.mediaSequenceStorage_[e]||null}getSyncPoint(e,t,n,r,i){if(t!==1/0)return Cp.find(({name:e})=>e===`VOD`).run(this,e,t);let a=this.runStrategies_(e,t,n,r,i);if(!a.length)return null;for(let t of a){let{syncPoint:n,strategy:i}=t,{segmentIndex:a,time:o}=n;if(a<0)continue;let s=e.segments[a],c=o,l=c+s.duration;if(this.logger_(`Strategy: ${i}. Current time: ${r}. selected segment: ${a}. Time: [${c} -> ${l}]}`),r>=c&&r0&&(r.time*=-1),Math.abs(r.time+Kl({defaultDuration:e.targetDuration,durationList:e.segments,startIndex:r.segmentIndex,endIndex:0}))}runStrategies_(e,t,n,r,i){let a=[];for(let o=0;oSp){W.log.warn(`Not saving expired segment info. Media sequence gap ${n} is too large.`);return}for(let r=n-1;r>=0;r--){let n=e.segments[r];if(n&&n.start!==void 0){t.syncInfo={mediaSequence:e.mediaSequence+r,time:n.start},this.logger_(`playlist refresh sync: [time:${t.syncInfo.time}, mediaSequence: ${t.syncInfo.mediaSequence}]`),this.trigger(`syncinfoupdate`);break}}}setDateTimeMappingForStart(e){if(this.timelineToDatetimeMappings={},e.segments&&e.segments.length&&e.segments[0].dateTimeObject){let t=e.segments[0],n=t.dateTimeObject.getTime()/1e3;this.timelineToDatetimeMappings[t.timeline]=-n}}saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:t}){let n=this.calculateSegmentTimeMapping_(e,e.timingInfo,t),r=e.segment;n&&(this.saveDiscontinuitySyncInfo_(e),e.playlist.syncInfo||(e.playlist.syncInfo={mediaSequence:e.playlist.mediaSequence+e.mediaIndex,time:r.start}));let i=r.dateTimeObject;r.discontinuity&&t&&i&&(this.timelineToDatetimeMappings[r.timeline]=-(i.getTime()/1e3))}timestampOffsetForTimeline(e){return this.timelines[e]===void 0?null:this.timelines[e].time}mappingForTimeline(e){return this.timelines[e]===void 0?null:this.timelines[e].mapping}calculateSegmentTimeMapping_(e,t,n){let r=e.segment,i=e.part,a=this.timelines[e.timeline],o,s;if(typeof e.timestampOffset==`number`)a={time:e.startOfSegment,mapping:e.startOfSegment-t.start},n&&(this.timelines[e.timeline]=a,this.trigger(`timestampoffset`),this.logger_(`time mapping for timeline ${e.timeline}: [time: ${a.time}] [mapping: ${a.mapping}]`)),o=e.startOfSegment,s=t.end+a.mapping;else if(a)o=t.start+a.mapping,s=t.end+a.mapping;else return!1;return i&&(i.start=o,i.end=s),(!r.start||os){let r;r=o<0?n.start-Kl({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex,endIndex:i}):n.end+Kl({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex+1,endIndex:i}),this.discontinuities[a]={time:r,accuracy:s}}}}dispose(){this.trigger(`dispose`),this.off()}},Tp=class extends W.EventTarget{constructor(){super(),this.pendingTimelineChanges_={},this.lastTimelineChanges_={}}clearPendingTimelineChange(e){this.pendingTimelineChanges_[e]=null,this.trigger(`pendingtimelinechange`)}pendingTimelineChange({type:e,from:t,to:n}){return typeof t==`number`&&typeof n==`number`&&(this.pendingTimelineChanges_[e]={type:e,from:t,to:n},this.trigger(`pendingtimelinechange`)),this.pendingTimelineChanges_[e]}lastTimelineChange({type:e,from:t,to:n}){if(typeof t==`number`&&typeof n==`number`){this.lastTimelineChanges_[e]={type:e,from:t,to:n},delete this.pendingTimelineChanges_[e];let r={timelineChangeInfo:{from:t,to:n}};this.trigger({type:`timelinechange`,metadata:r})}return this.lastTimelineChanges_[e]}dispose(){this.trigger(`dispose`),this.pendingTimelineChanges_={},this.lastTimelineChanges_={},this.off()}},Ep=wd(Td(Ed(function(){var e=function(){function e(){this.listeners={}}var t=e.prototype;return t.on=function(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)},t.off=function(e,t){if(!this.listeners[e])return!1;var n=this.listeners[e].indexOf(t);return this.listeners[e]=this.listeners[e].slice(0),this.listeners[e].splice(n,1),n>-1},t.trigger=function(e){var t=this.listeners[e];if(t)if(arguments.length===2)for(var n=t.length,r=0;r>7)*283)^a]=a;for(o=s=0;!r[o];o^=u||1,s=l[s]||1)for(p=s^s<<1^s<<2^s<<3^s<<4,p=p>>8^p&255^99,r[o]=p,i[p]=o,f=c[d=c[u=c[o]]],h=f*16843009^d*65537^u*257^o*16843008,m=c[p]*257^p*16843008,a=0;a<4;a++)t[a][o]=m=m<<24^m>>>8,n[a][p]=h=h<<24^h>>>8;for(a=0;a<5;a++)t[a]=t[a].slice(0),n[a]=n[a].slice(0);return e},r=null;class i{constructor(e){r||=n(),this._tables=[[r[0][0].slice(),r[0][1].slice(),r[0][2].slice(),r[0][3].slice(),r[0][4].slice()],[r[1][0].slice(),r[1][1].slice(),r[1][2].slice(),r[1][3].slice(),r[1][4].slice()]];let t,i,a,o=this._tables[0][4],s=this._tables[1],c=e.length,l=1;if(c!==4&&c!==6&&c!==8)throw Error(`Invalid aes key size`);let u=e.slice(0),d=[];for(this._key=[u,d],t=c;t<4*c+28;t++)a=u[t-1],(t%c===0||c===8&&t%c===4)&&(a=o[a>>>24]<<24^o[a>>16&255]<<16^o[a>>8&255]<<8^o[a&255],t%c===0&&(a=a<<8^a>>>24^l<<24,l=l<<1^(l>>7)*283)),u[t]=u[t-c]^a;for(i=0;t;i++,t--)a=u[i&3?t:t-4],t<=4||i<4?d[i]=a:d[i]=s[0][o[a>>>24]]^s[1][o[a>>16&255]]^s[2][o[a>>8&255]]^s[3][o[a&255]]}decrypt(e,t,n,r,i,a){let o=this._key[1],s=e^o[0],c=r^o[1],l=n^o[2],u=t^o[3],d,f,p,m=o.length/4-2,h,g=4,_=this._tables[1],v=_[0],y=_[1],b=_[2],x=_[3],S=_[4];for(h=0;h>>24]^y[c>>16&255]^b[l>>8&255]^x[u&255]^o[g],f=v[c>>>24]^y[l>>16&255]^b[u>>8&255]^x[s&255]^o[g+1],p=v[l>>>24]^y[u>>16&255]^b[s>>8&255]^x[c&255]^o[g+2],u=v[u>>>24]^y[s>>16&255]^b[c>>8&255]^x[l&255]^o[g+3],g+=4,s=d,c=f,l=p;for(h=0;h<4;h++)i[(3&-h)+a]=S[s>>>24]<<24^S[c>>16&255]<<16^S[l>>8&255]<<8^S[u&255]^o[g++],d=s,s=c,c=l,l=u,u=d}}class a extends e{constructor(){super(e),this.jobs=[],this.delay=1,this.timeout_=null}processJob_(){this.jobs.shift()(),this.jobs.length?this.timeout_=setTimeout(this.processJob_.bind(this),this.delay):this.timeout_=null}push(e){this.jobs.push(e),this.timeout_||=setTimeout(this.processJob_.bind(this),this.delay)}}let o=function(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24},s=function(e,t,n){let r=new Int32Array(e.buffer,e.byteOffset,e.byteLength>>2),a=new i(Array.prototype.slice.call(t)),s=new Uint8Array(e.byteLength),c=new Int32Array(s.buffer),l,u,d,f,p,m,h,g,_;for(l=n[0],u=n[1],d=n[2],f=n[3],_=0;_{let r=e[n];d(r)?t[n]={bytes:r.buffer,byteOffset:r.byteOffset,byteLength:r.byteLength}:t[n]=r}),t};self.onmessage=function(e){let t=e.data;new c(new Uint8Array(t.encrypted.bytes,t.encrypted.byteOffset,t.encrypted.byteLength),new Uint32Array(t.key.bytes,t.key.byteOffset,t.key.byteLength/4),new Uint32Array(t.iv.bytes,t.iv.byteOffset,t.iv.byteLength/4),function(e,n){self.postMessage(p({source:t.source,decrypted:n}),[n.buffer])})}}))),Dp=e=>{let t=e.default?`main`:`alternative`;return e.characteristics&&e.characteristics.indexOf(`public.accessibility.describes-video`)>=0&&(t=`main-desc`),t},Op=(e,t)=>{e.abort(),e.pause(),t&&t.activePlaylistLoader&&(t.activePlaylistLoader.pause(),t.activePlaylistLoader=null)},kp=(e,t)=>{t.activePlaylistLoader=e,e.load()},Ap=(e,t)=>()=>{let{segmentLoaders:{[e]:n,main:r},mediaTypes:{[e]:i}}=t,a=i.activeTrack(),o=i.getActiveGroup(),s=i.activePlaylistLoader,c=i.lastGroup_;if(!(o&&c&&o.id===c.id)&&(i.lastGroup_=o,i.lastTrack_=a,Op(n,i),!(!o||o.isMainPlaylist))){if(!o.playlistLoader){s&&r.resetEverything();return}n.resyncLoader(),kp(o.playlistLoader,i)}},jp=(e,t)=>()=>{let{segmentLoaders:{[e]:n},mediaTypes:{[e]:r}}=t;r.lastGroup_=null,n.abort(),n.pause()},Mp=(e,t)=>()=>{let{mainPlaylistLoader:n,segmentLoaders:{[e]:r,main:i},mediaTypes:{[e]:a}}=t,o=a.activeTrack(),s=a.getActiveGroup(),c=a.activePlaylistLoader,l=a.lastTrack_;if(!(l&&o&&l.id===o.id)&&(a.lastGroup_=s,a.lastTrack_=o,Op(r,a),s)){if(s.isMainPlaylist){if(!o||!l||o.id===l.id)return;let e=t.vhs.playlistController_,r=e.selectPlaylist();if(e.media()===r)return;a.logger_(`track change. Switching main audio from ${l.id} to ${o.id}`),n.pause(),i.resetEverything(),e.fastQualityChange_(r);return}if(e===`AUDIO`){if(!s.playlistLoader){i.setAudio(!0),i.resetEverything();return}r.setAudio(!0),i.setAudio(!1)}if(c===s.playlistLoader){kp(s.playlistLoader,a);return}r.track&&r.track(o),r.resetEverything(),kp(s.playlistLoader,a)}},Np={AUDIO:(e,t)=>()=>{let{mediaTypes:{[e]:n},excludePlaylist:r}=t,i=n.activeTrack(),a=n.activeGroup(),o=(a.filter(e=>e.default)[0]||a[0]).id,s=n.tracks[o];if(i===s){r({error:{message:`Problem encountered loading the default audio track.`}});return}W.log.warn(`Problem encountered loading the alternate audio track.Switching back to default.`);for(let e in n.tracks)n.tracks[e].enabled=n.tracks[e]===s;n.onTrackChanged()},SUBTITLES:(e,t)=>()=>{let{mediaTypes:{[e]:n}}=t;W.log.warn(`Problem encountered loading the subtitle track.Disabling subtitle track.`);let r=n.activeTrack();r&&(r.mode=`disabled`),n.onTrackChanged()}},Pp={AUDIO:(e,t,n)=>{if(!t)return;let{tech:r,requestOptions:i,segmentLoaders:{[e]:a}}=n;t.on(`loadedmetadata`,()=>{let e=t.media();a.playlist(e,i),(!r.paused()||e.endList&&r.preload()!==`none`)&&a.load()}),t.on(`loadedplaylist`,()=>{a.playlist(t.media(),i),r.paused()||a.load()}),t.on(`error`,Np[e](e,n))},SUBTITLES:(e,t,n)=>{let{tech:r,requestOptions:i,segmentLoaders:{[e]:a},mediaTypes:{[e]:o}}=n;t.on(`loadedmetadata`,()=>{let e=t.media();a.playlist(e,i),a.track(o.activeTrack()),(!r.paused()||e.endList&&r.preload()!==`none`)&&a.load()}),t.on(`loadedplaylist`,()=>{a.playlist(t.media(),i),r.paused()||a.load()}),t.on(`error`,Np[e](e,n))}},Fp={AUDIO:(e,t)=>{let{vhs:n,sourceType:r,segmentLoaders:{[e]:i},requestOptions:a,main:{mediaGroups:o},mediaTypes:{[e]:{groups:s,tracks:c,logger_:l}},mainPlaylistLoader:u}=t,d=ou(u.main);(!o[e]||Object.keys(o[e]).length===0)&&(o[e]={main:{default:{default:!0}}},d&&(o[e].main.default.playlists=u.main.playlists));for(let i in o[e]){s[i]||(s[i]=[]);for(let f in o[e][i]){let p=o[e][i][f],m;d?(l(`AUDIO group '${i}' label '${f}' is a main playlist`),p.isMainPlaylist=!0,m=null):m=r===`vhs-json`&&p.playlists?new Ru(p.playlists[0],n,a):p.resolvedUri?new Ru(p.resolvedUri,n,a):p.playlists&&r===`dash`?new yd(p.playlists[0],n,a,u):null,p=xl({id:f,playlistLoader:m},p),Pp[e](e,p.playlistLoader,t),s[i].push(p),c[f]===void 0&&(c[f]=new W.AudioTrack({id:f,kind:Dp(p),enabled:!1,language:p.language,default:p.default,label:f}))}}i.on(`error`,Np[e](e,t))},SUBTITLES:(e,t)=>{let{tech:n,vhs:r,sourceType:i,segmentLoaders:{[e]:a},requestOptions:o,main:{mediaGroups:s},mediaTypes:{[e]:{groups:c,tracks:l}},mainPlaylistLoader:u}=t;for(let a in s[e]){c[a]||(c[a]=[]);for(let d in s[e][a]){if(!r.options_.useForcedSubtitles&&s[e][a][d].forced)continue;let f=s[e][a][d],p;if(i===`hls`)p=new Ru(f.resolvedUri,r,o);else if(i===`dash`){if(!f.playlists.filter(e=>e.excludeUntil!==1/0).length)return;p=new yd(f.playlists[0],r,o,u)}else i===`vhs-json`&&(p=new Ru(f.playlists?f.playlists[0]:f.resolvedUri,r,o));f=xl({id:d,playlistLoader:p},f),Pp[e](e,f.playlistLoader,t),c[a].push(f),l[d]===void 0&&(l[d]=n.addRemoteTextTrack({id:d,kind:`subtitles`,default:f.default&&f.autoselect,language:f.language,label:d},!1).track)}}a.on(`error`,Np[e](e,t))},"CLOSED-CAPTIONS":(e,t)=>{let{tech:n,main:{mediaGroups:r},mediaTypes:{[e]:{groups:i,tracks:a}}}=t;for(let t in r[e]){i[t]||(i[t]=[]);for(let o in r[e][t]){let s=r[e][t][o];if(!/^(?:CC|SERVICE)/.test(s.instreamId))continue;let c=n.options_.vhs&&n.options_.vhs.captionServices||{},l={label:o,language:s.language,instreamId:s.instreamId,default:s.default&&s.autoselect};c[l.instreamId]&&(l=xl(l,c[l.instreamId])),l.default===void 0&&delete l.default,i[t].push(xl({id:o},s)),a[o]===void 0&&(a[o]=n.addRemoteTextTrack({id:l.instreamId,kind:`captions`,default:l.default,language:l.language,label:l.label},!1).track)}}}},Ip=(e,t)=>{for(let n=0;nn=>{let{mainPlaylistLoader:r,mediaTypes:{[e]:{groups:i}}}=t,a=r.media();if(!a)return null;let o=null;a.attributes[e]&&(o=i[a.attributes[e]]);let s=Object.keys(i);if(!o)if(e===`AUDIO`&&s.length>1&&ou(t.main))for(let e=0;ee.id===n.id)[0]||null},Rp={AUDIO:(e,t)=>()=>{let{mediaTypes:{[e]:{tracks:n}}}=t;for(let e in n)if(n[e].enabled)return n[e];return null},SUBTITLES:(e,t)=>()=>{let{mediaTypes:{[e]:{tracks:n}}}=t;for(let e in n)if(n[e].mode===`showing`||n[e].mode===`hidden`)return n[e];return null}},zp=(e,{mediaTypes:t})=>()=>{let n=t[e].activeTrack();return n?t[e].activeGroup(n):null},Bp=e=>{[`AUDIO`,`SUBTITLES`,`CLOSED-CAPTIONS`].forEach(t=>{Fp[t](t,e)});let{mediaTypes:t,mainPlaylistLoader:n,tech:r,vhs:i,segmentLoaders:{AUDIO:a,main:o}}=e;[`AUDIO`,`SUBTITLES`].forEach(n=>{t[n].activeGroup=Lp(n,e),t[n].activeTrack=Rp[n](n,e),t[n].onGroupChanged=Ap(n,e),t[n].onGroupChanging=jp(n,e),t[n].onTrackChanged=Mp(n,e),t[n].getActiveGroup=zp(n,e)});let s=t.AUDIO.activeGroup();if(s){let e=(s.filter(e=>e.default)[0]||s[0]).id;t.AUDIO.tracks[e].enabled=!0,t.AUDIO.onGroupChanged(),t.AUDIO.onTrackChanged(),t.AUDIO.getActiveGroup().playlistLoader?(o.setAudio(!1),a.setAudio(!0)):o.setAudio(!0)}n.on(`mediachange`,()=>{[`AUDIO`,`SUBTITLES`].forEach(e=>t[e].onGroupChanged())}),n.on(`mediachanging`,()=>{[`AUDIO`,`SUBTITLES`].forEach(e=>t[e].onGroupChanging())});let c=()=>{t.AUDIO.onTrackChanged(),r.trigger({type:`usage`,name:`vhs-audio-change`})};r.audioTracks().addEventListener(`change`,c),r.remoteTextTracks().addEventListener(`change`,t.SUBTITLES.onTrackChanged),i.on(`dispose`,()=>{r.audioTracks().removeEventListener(`change`,c),r.remoteTextTracks().removeEventListener(`change`,t.SUBTITLES.onTrackChanged)}),r.clearTracks(`audio`);for(let e in t.AUDIO.tracks)r.audioTracks().addTrack(t.AUDIO.tracks[e])},Vp=()=>{let e={};return[`AUDIO`,`SUBTITLES`,`CLOSED-CAPTIONS`].forEach(t=>{e[t]={groups:{},tracks:{},activePlaylistLoader:null,activeGroup:$f,activeTrack:$f,getActiveGroup:$f,onGroupChanged:$f,onTrackChanged:$f,lastTrack_:null,logger_:bl(`MediaGroups[${t}]`)}}),e},Hp=class{constructor(){this.priority_=[],this.pathwayClones_=new Map}set version(e){e===1&&(this.version_=e)}set ttl(e){this.ttl_=e||300}set reloadUri(e){e&&(this.reloadUri_=vl(this.reloadUri_,e))}set priority(e){e&&e.length&&(this.priority_=e)}set pathwayClones(e){e&&e.length&&(this.pathwayClones_=new Map(e.map(e=>[e.ID,e])))}get version(){return this.version_}get ttl(){return this.ttl_}get reloadUri(){return this.reloadUri_}get priority(){return this.priority_}get pathwayClones(){return this.pathwayClones_}},Up=class extends W.EventTarget{constructor(e,t){super(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=!1,this.availablePathways_=new Set,this.steeringManifest=new Hp,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.currentPathwayClones=new Map,this.nextPathwayClones=new Map,this.excludedSteeringManifestURLs=new Set,this.logger_=bl(`Content Steering`),this.xhr_=e,this.getBandwidth_=t}assignTagProperties(e,t){this.manifestType_=t.serverUri?`HLS`:`DASH`;let n=t.serverUri||t.serverURL;if(!n){this.logger_(`steering manifest URL is ${n}, cannot request steering manifest.`),this.trigger(`error`);return}if(n.startsWith(`data:`)){this.decodeDataUriManifest_(n.substring(n.indexOf(`,`)+1));return}this.steeringManifest.reloadUri=vl(e,n),this.defaultPathway=t.pathwayId||t.defaultServiceLocation,this.queryBeforeStart=t.queryBeforeStart,this.proxyServerUrl_=t.proxyServerURL,this.defaultPathway&&!this.queryBeforeStart&&this.trigger(`content-steering`)}requestSteeringManifest(e){let t=this.steeringManifest.reloadUri;if(!t)return;let n=e?t:this.getRequestURI(t);if(!n){this.logger_(`No valid content steering manifest URIs. Stopping content steering.`),this.trigger(`error`),this.dispose();return}let r={contentSteeringInfo:{uri:n}};this.trigger({type:`contentsteeringloadstart`,metadata:r}),this.request_=this.xhr_({uri:n,requestType:`content-steering-manifest`},(e,t)=>{if(e){if(t.status===410){this.logger_(`manifest request 410 ${e}.`),this.logger_(`There will be no more content steering requests to ${n} this session.`),this.excludedSteeringManifestURLs.add(n);return}if(t.status===429){let n=t.responseHeaders[`retry-after`];this.logger_(`manifest request 429 ${e}.`),this.logger_(`content steering will retry in ${n} seconds.`),this.startTTLTimeout_(parseInt(n,10));return}this.logger_(`manifest failed to load ${e}.`),this.startTTLTimeout_();return}this.trigger({type:`contentsteeringloadcomplete`,metadata:r});let i;try{i=JSON.parse(this.request_.responseText)}catch(e){let t={errorType:W.Error.StreamingContentSteeringParserError,error:e};this.trigger({type:`error`,metadata:t})}this.assignSteeringProperties_(i);let a={contentSteeringInfo:r.contentSteeringInfo,contentSteeringManifest:{version:this.steeringManifest.version,reloadUri:this.steeringManifest.reloadUri,priority:this.steeringManifest.priority}};this.trigger({type:`contentsteeringparsed`,metadata:a}),this.startTTLTimeout_()})}setProxyServerUrl_(e){let t=new I.default.URL(e),n=new I.default.URL(this.proxyServerUrl_);return n.searchParams.set(`url`,encodeURI(t.toString())),this.setSteeringParams_(n.toString())}decodeDataUriManifest_(e){let t=JSON.parse(I.default.atob(e));this.assignSteeringProperties_(t)}setSteeringParams_(e){let t=new I.default.URL(e),n=this.getPathway(),r=this.getBandwidth_();if(n){let e=`_${this.manifestType_}_pathway`;t.searchParams.set(e,n)}if(r){let e=`_${this.manifestType_}_throughput`;t.searchParams.set(e,r)}return t.toString()}assignSteeringProperties_(e){if(this.steeringManifest.version=e.VERSION,!this.steeringManifest.version){this.logger_(`manifest version is ${e.VERSION}, which is not supported.`),this.trigger(`error`);return}this.steeringManifest.ttl=e.TTL,this.steeringManifest.reloadUri=e[`RELOAD-URI`],this.steeringManifest.priority=e[`PATHWAY-PRIORITY`]||e[`SERVICE-LOCATION-PRIORITY`],this.steeringManifest.pathwayClones=e[`PATHWAY-CLONES`],this.nextPathwayClones=this.steeringManifest.pathwayClones,this.availablePathways_.size||(this.logger_(`There are no available pathways for content steering. Ending content steering.`),this.trigger(`error`),this.dispose());let t=(e=>{for(let t of e)if(this.availablePathways_.has(t))return t;return[...this.availablePathways_][0]})(this.steeringManifest.priority);this.currentPathway!==t&&(this.currentPathway=t,this.trigger(`content-steering`))}getPathway(){return this.currentPathway||this.defaultPathway}getRequestURI(e){if(!e)return null;let t=e=>this.excludedSteeringManifestURLs.has(e);if(this.proxyServerUrl_){let n=this.setProxyServerUrl_(e);if(!t(n))return n}let n=this.setSteeringParams_(e);return t(n)?null:n}startTTLTimeout_(e=this.steeringManifest.ttl){let t=e*1e3;this.ttlTimeout_=I.default.setTimeout(()=>{this.requestSteeringManifest()},t)}clearTTLTimeout_(){I.default.clearTimeout(this.ttlTimeout_),this.ttlTimeout_=null}abort(){this.request_&&this.request_.abort(),this.request_=null}dispose(){this.off(`content-steering`),this.off(`error`),this.abort(),this.clearTTLTimeout_(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=null,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.excludedSteeringManifestURLs=new Set,this.availablePathways_=new Set,this.steeringManifest=new Hp}addAvailablePathway(e){e&&this.availablePathways_.add(e)}clearAvailablePathways(){this.availablePathways_.clear()}excludePathway(e){return this.availablePathways_.delete(e)}didDASHTagChange(e,t){return!t&&this.steeringManifest.reloadUri||t&&(vl(e,t.serverURL)!==this.steeringManifest.reloadUri||t.defaultServiceLocation!==this.defaultPathway||t.queryBeforeStart!==this.queryBeforeStart||t.proxyServerURL!==this.proxyServerUrl_)}getAvailablePathways(){return this.availablePathways_}},Wp=(e,t)=>{let n=null;return(...r)=>{clearTimeout(n),n=setTimeout(()=>{e.apply(null,r)},t)}},Gp=10,Kp,qp=[`mediaRequests`,`mediaRequestsAborted`,`mediaRequestsTimedout`,`mediaRequestsErrored`,`mediaTransferDuration`,`mediaBytesTransferred`,`mediaAppends`],Jp=function(e){return this.audioSegmentLoader_[e]+this.mainSegmentLoader_[e]},Yp=function({currentPlaylist:e,buffered:t,currentTime:n,nextPlaylist:r,bufferLowWaterLine:i,bufferHighWaterLine:a,duration:o,bufferBasedABR:s,log:c}){if(!r)return W.log.warn(`We received no playlist to switch to. Please check your stream.`),!1;let l=`allowing switch ${e&&e.id||`null`} -> ${r.id}`;if(!e)return c(`${l} as current playlist is not set`),!0;if(r.id===e.id)return!1;let u=!!Dl(t,n).length;if(!e.endList)return!u&&typeof e.partTargetDuration==`number`?(c(`not ${l} as current playlist is live llhls, but currentTime isn't in buffered.`),!1):(c(`${l} as current playlist is live`),!0);let d=Il(t,n),f=s?bd.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:bd.MAX_BUFFER_LOW_WATER_LINE;if(om)&&d>=i){let e=`${l} as forwardBuffer >= bufferLowWaterLine (${d} >= ${i})`;return s&&(e+=` and next bandwidth > current bandwidth (${p} > ${m})`),c(e),!0}return c(`not ${l} as no switching criteria met`),!1},Xp=class extends W.EventTarget{constructor(e){super(),this.fastQualityChange_=Wp(this.fastQualityChange_.bind(this),100);let{src:t,withCredentials:n,tech:r,bandwidth:i,externVhs:a,useCueTags:o,playlistExclusionDuration:s,enableLowInitialPlaylist:c,sourceType:l,cacheEncryptionKeys:u,bufferBasedABR:d,leastPixelDiffSelector:f,captionServices:p,experimentalUseMMS:m}=e;if(!t)throw Error(`A non-empty playlist URL or JSON manifest string is required`);let{maxPlaylistRetries:h}=e;h??=1/0,Kp=a,this.bufferBasedABR=!!d,this.leastPixelDiffSelector=!!f,this.withCredentials=n,this.tech_=r,this.vhs_=r.vhs,this.player_=e.player_,this.sourceType_=l,this.useCueTags_=o,this.playlistExclusionDuration=s,this.maxPlaylistRetries=h,this.enableLowInitialPlaylist=c,this.usingManagedMediaSource_=!1,this.useCueTags_&&(this.cueTagsTrack_=this.tech_.addTextTrack(`metadata`,`ad-cues`),this.cueTagsTrack_.inBandMetadataTrackDispatchType=``),this.requestOptions_={withCredentials:n,maxPlaylistRetries:h,timeout:null},this.on(`error`,this.pauseLoading),this.mediaTypes_=Vp(),m&&I.default.ManagedMediaSource?(this.tech_.el_.disableRemotePlayback=!0,this.mediaSource=new I.default.ManagedMediaSource,this.usingManagedMediaSource_=!0,W.log(`Using ManagedMediaSource`)):I.default.MediaSource&&(this.mediaSource=new I.default.MediaSource),this.handleDurationChange_=this.handleDurationChange_.bind(this),this.handleSourceOpen_=this.handleSourceOpen_.bind(this),this.handleSourceEnded_=this.handleSourceEnded_.bind(this),this.load=this.load.bind(this),this.pause=this.pause.bind(this),this.mediaSource.addEventListener(`durationchange`,this.handleDurationChange_),this.mediaSource.addEventListener(`sourceopen`,this.handleSourceOpen_),this.mediaSource.addEventListener(`sourceended`,this.handleSourceEnded_),this.mediaSource.addEventListener(`startstreaming`,this.load),this.mediaSource.addEventListener(`endstreaming`,this.pause),this.seekable_=Sl(),this.hasPlayed_=!1,this.syncController_=new wp(e),this.segmentMetadataTrack_=r.addRemoteTextTrack({kind:`metadata`,label:`segment-metadata`},!1).track,this.segmentMetadataTrack_.mode=`hidden`,this.decrypter_=new Ep,this.sourceUpdater_=new up(this.mediaSource),this.inbandTextTracks_={},this.timelineChangeController_=new Tp,this.keyStatusMap_=new Map;let g={vhs:this.vhs_,parse708captions:e.parse708captions,useDtsForTimestampOffset:e.useDtsForTimestampOffset,captionServices:p,mediaSource:this.mediaSource,currentTime:this.tech_.currentTime.bind(this.tech_),seekable:()=>this.seekable(),seeking:()=>this.tech_.seeking(),duration:()=>this.duration(),hasPlayed:()=>this.hasPlayed_,goalBufferLength:()=>this.goalBufferLength(),bandwidth:i,syncController:this.syncController_,decrypter:this.decrypter_,sourceType:this.sourceType_,inbandTextTracks:this.inbandTextTracks_,cacheEncryptionKeys:u,sourceUpdater:this.sourceUpdater_,timelineChangeController:this.timelineChangeController_,exactManifestTimings:e.exactManifestTimings,addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)};this.mainPlaylistLoader_=this.sourceType_===`dash`?new yd(t,this.vhs_,xl(this.requestOptions_,{addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)})):new Ru(t,this.vhs_,xl(this.requestOptions_,{addDateRangesToTextTrack:this.addDateRangesToTextTrack_.bind(this)})),this.setupMainPlaylistLoaderListeners_(),this.mainSegmentLoader_=new Qf(xl(g,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:`main`}),e),this.audioSegmentLoader_=new Qf(xl(g,{loaderType:`audio`}),e),this.subtitleSegmentLoader_=new hp(xl(g,{loaderType:`vtt`,featuresNativeTextTracks:this.tech_.featuresNativeTextTracks,loadVttJs:()=>new Promise((e,t)=>{function n(){r.off(`vttjserror`,i),e()}function i(){r.off(`vttjsloaded`,n),t()}r.one(`vttjsloaded`,n),r.one(`vttjserror`,i),r.addWebVttScript_()})}),e);let _=()=>this.mainSegmentLoader_.bandwidth;this.contentSteeringController_=new Up(this.vhs_.xhr,_),this.setupSegmentLoaderListeners_(),this.bufferBasedABR&&(this.mainPlaylistLoader_.one(`loadedplaylist`,()=>this.startABRTimer_()),this.tech_.on(`pause`,()=>this.stopABRTimer_()),this.tech_.on(`play`,()=>this.startABRTimer_())),qp.forEach(e=>{this[e+`_`]=Jp.bind(this,e)}),this.logger_=bl(`pc`),this.triggeredFmp4Usage=!1,this.tech_.preload()===`none`?(this.loadOnPlay_=()=>{this.loadOnPlay_=null,this.mainPlaylistLoader_.load()},this.tech_.one(`play`,this.loadOnPlay_)):this.mainPlaylistLoader_.load(),this.timeToLoadedData__=-1,this.mainAppendsToLoadedData__=-1,this.audioAppendsToLoadedData__=-1;let v=this.tech_.preload()===`none`?`play`:`loadstart`;this.tech_.one(v,()=>{let e=Date.now();this.tech_.one(`loadeddata`,()=>{this.timeToLoadedData__=Date.now()-e,this.mainAppendsToLoadedData__=this.mainSegmentLoader_.mediaAppends,this.audioAppendsToLoadedData__=this.audioSegmentLoader_.mediaAppends})})}mainAppendsToLoadedData_(){return this.mainAppendsToLoadedData__}audioAppendsToLoadedData_(){return this.audioAppendsToLoadedData__}appendsToLoadedData_(){let e=this.mainAppendsToLoadedData_(),t=this.audioAppendsToLoadedData_();return e===-1||t===-1?-1:e+t}timeToLoadedData_(){return this.timeToLoadedData__}checkABR_(e=`abr`){let t=this.selectPlaylist();t&&this.shouldSwitchToMedia_(t)&&this.switchMedia_(t,e)}switchMedia_(e,t,n){let r=this.media(),i=r&&(r.id||r.uri),a=e&&(e.id||e.uri);if(i&&i!==a){this.logger_(`switch media ${i} -> ${a} from ${t}`);let n={renditionInfo:{id:a,bandwidth:e.attributes.BANDWIDTH,resolution:e.attributes.RESOLUTION,codecs:e.attributes.CODECS},cause:t};this.trigger({type:`renditionselected`,metadata:n}),this.tech_.trigger({type:`usage`,name:`vhs-rendition-change-${t}`})}this.mainPlaylistLoader_.media(e,n)}switchMediaForDASHContentSteering_(){[`AUDIO`,`SUBTITLES`,`CLOSED-CAPTIONS`].forEach(e=>{let t=this.mediaTypes_[e],n=t?t.activeGroup():null,r=this.contentSteeringController_.getPathway();if(n&&r){let t=(n.length?n[0].playlists:n.playlists).filter(e=>e.attributes.serviceLocation===r);t.length&&this.mediaTypes_[e].activePlaylistLoader.media(t[0])}})}startABRTimer_(){this.stopABRTimer_(),this.abrTimer_=I.default.setInterval(()=>this.checkABR_(),250)}stopABRTimer_(){this.tech_.scrubbing&&this.tech_.scrubbing()||(I.default.clearInterval(this.abrTimer_),this.abrTimer_=null)}getAudioTrackPlaylists_(){let e=this.main(),t=e&&e.playlists||[];if(!e||!e.mediaGroups||!e.mediaGroups.AUDIO)return t;let n=e.mediaGroups.AUDIO,r=Object.keys(n),i;if(Object.keys(this.mediaTypes_.AUDIO.groups).length)i=this.mediaTypes_.AUDIO.activeTrack();else{let e=n.main||r.length&&n[r[0]];for(let t in e)if(e[t].default){i={label:t};break}}if(!i)return t;let a=[];for(let t in n)if(n[t][i.label]){let r=n[t][i.label];if(r.playlists&&r.playlists.length)a.push.apply(a,r.playlists);else if(r.uri)a.push(r);else if(e.playlists.length)for(let n=0;n{let e=this.mainPlaylistLoader_.media(),t=e.targetDuration*1.5*1e3;ru(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=t,e.endList&&this.tech_.preload()!==`none`&&(this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.mainSegmentLoader_.load()),Bp({sourceType:this.sourceType_,segmentLoaders:{AUDIO:this.audioSegmentLoader_,SUBTITLES:this.subtitleSegmentLoader_,main:this.mainSegmentLoader_},tech:this.tech_,requestOptions:this.requestOptions_,mainPlaylistLoader:this.mainPlaylistLoader_,vhs:this.vhs_,main:this.main(),mediaTypes:this.mediaTypes_,excludePlaylist:this.excludePlaylist.bind(this)}),this.triggerPresenceUsage_(this.main(),e),this.setupFirstPlay(),!this.mediaTypes_.AUDIO.activePlaylistLoader||this.mediaTypes_.AUDIO.activePlaylistLoader.media()?this.trigger(`selectedinitialmedia`):this.mediaTypes_.AUDIO.activePlaylistLoader.one(`loadedmetadata`,()=>{this.trigger(`selectedinitialmedia`)})}),this.mainPlaylistLoader_.on(`loadedplaylist`,()=>{this.loadOnPlay_&&this.tech_.off(`play`,this.loadOnPlay_);let e=this.mainPlaylistLoader_.media();if(!e){this.attachContentSteeringListeners_(),this.initContentSteeringController_(),this.excludeUnsupportedVariants_();let t;if(this.enableLowInitialPlaylist&&(t=this.selectInitialPlaylist()),t||=this.selectPlaylist(),!t||!this.shouldSwitchToMedia_(t)||(this.initialMedia_=t,this.switchMedia_(this.initialMedia_,`initial`),!(this.sourceType_===`vhs-json`&&this.initialMedia_.segments)))return;e=this.initialMedia_}this.handleUpdatedMediaPlaylist(e)}),this.mainPlaylistLoader_.on(`error`,()=>{let e=this.mainPlaylistLoader_.error;this.excludePlaylist({playlistToExclude:e.playlist,error:e})}),this.mainPlaylistLoader_.on(`mediachanging`,()=>{this.mainSegmentLoader_.abort(),this.mainSegmentLoader_.pause()}),this.mainPlaylistLoader_.on(`mediachange`,()=>{let e=this.mainPlaylistLoader_.media(),t=e.targetDuration*1.5*1e3;ru(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=t,this.sourceType_===`dash`&&this.mainPlaylistLoader_.isPaused&&this.mainPlaylistLoader_.load(),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_?this.runFastQualitySwitch_():this.mainSegmentLoader_.load(),this.tech_.trigger({type:`mediachange`,bubbles:!0})}),this.mainPlaylistLoader_.on(`playlistunchanged`,()=>{let e=this.mainPlaylistLoader_.media();e.lastExcludeReason_!==`playlist-unchanged`&&this.stuckAtPlaylistEnd_(e)&&(this.excludePlaylist({error:{message:`Playlist no longer updating.`,reason:`playlist-unchanged`}}),this.tech_.trigger(`playliststuck`))}),this.mainPlaylistLoader_.on(`renditiondisabled`,()=>{this.tech_.trigger({type:`usage`,name:`vhs-rendition-disabled`})}),this.mainPlaylistLoader_.on(`renditionenabled`,()=>{this.tech_.trigger({type:`usage`,name:`vhs-rendition-enabled`})}),[`manifestrequeststart`,`manifestrequestcomplete`,`manifestparsestart`,`manifestparsecomplete`,`playlistrequeststart`,`playlistrequestcomplete`,`playlistparsestart`,`playlistparsecomplete`,`renditiondisabled`,`renditionenabled`].forEach(e=>{this.mainPlaylistLoader_.on(e,e=>{this.player_.trigger(me({},e))})})}handleUpdatedMediaPlaylist(e){this.useCueTags_&&this.updateAdCues_(e),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_&&this.runFastQualitySwitch_(),this.updateDuration(!e.endList),this.tech_.paused()||(this.mainSegmentLoader_.load(),this.audioSegmentLoader_&&this.audioSegmentLoader_.load())}triggerPresenceUsage_(e,t){let n=e.mediaGroups||{},r=!0,i=Object.keys(n.AUDIO);for(let e in n.AUDIO)for(let t in n.AUDIO[e])n.AUDIO[e][t].uri||(r=!1);r&&this.tech_.trigger({type:`usage`,name:`vhs-demuxed`}),Object.keys(n.SUBTITLES).length&&this.tech_.trigger({type:`usage`,name:`vhs-webvtt`}),Kp.Playlist.isAes(t)&&this.tech_.trigger({type:`usage`,name:`vhs-aes`}),i.length&&Object.keys(n.AUDIO[i[0]]).length>1&&this.tech_.trigger({type:`usage`,name:`vhs-alternate-audio`}),this.useCueTags_&&this.tech_.trigger({type:`usage`,name:`vhs-playlist-cue-tags`})}shouldSwitchToMedia_(e){let t=this.mainPlaylistLoader_.media()||this.mainPlaylistLoader_.pendingMedia_,n=this.tech_.currentTime(),r=this.bufferLowWaterLine(),i=this.bufferHighWaterLine();return Yp({buffered:this.tech_.buffered(),currentTime:n,currentPlaylist:t,nextPlaylist:e,bufferLowWaterLine:r,bufferHighWaterLine:i,duration:this.duration(),bufferBasedABR:this.bufferBasedABR,log:this.logger_})}setupSegmentLoaderListeners_(){this.mainSegmentLoader_.on(`bandwidthupdate`,()=>{this.checkABR_(`bandwidthupdate`),this.tech_.trigger(`bandwidthupdate`)}),this.mainSegmentLoader_.on(`timeout`,()=>{this.bufferBasedABR&&this.mainSegmentLoader_.load()}),this.bufferBasedABR||this.mainSegmentLoader_.on(`progress`,()=>{this.trigger(`progress`)}),this.mainSegmentLoader_.on(`error`,()=>{let e=this.mainSegmentLoader_.error();this.excludePlaylist({playlistToExclude:e.playlist,error:e})}),this.mainSegmentLoader_.on(`appenderror`,()=>{this.error=this.mainSegmentLoader_.error_,this.trigger(`error`)}),this.mainSegmentLoader_.on(`syncinfoupdate`,()=>{this.onSyncInfoUpdate_()}),this.mainSegmentLoader_.on(`timestampoffset`,()=>{this.tech_.trigger({type:`usage`,name:`vhs-timestamp-offset`})}),this.audioSegmentLoader_.on(`syncinfoupdate`,()=>{this.onSyncInfoUpdate_()}),this.audioSegmentLoader_.on(`appenderror`,()=>{this.error=this.audioSegmentLoader_.error_,this.trigger(`error`)}),this.mainSegmentLoader_.on(`ended`,()=>{this.logger_(`main segment loader ended`),this.onEndOfStream()}),this.timelineChangeController_.on(`audioTimelineBehind`,()=>{let e=this.audioSegmentLoader_.pendingSegment_;if(!e||!e.segment||!e.segment.syncInfo)return;let t=e.segment.syncInfo.end+.01;this.tech_.setCurrentTime(t)}),this.timelineChangeController_.on(`fixBadTimelineChange`,()=>{this.logger_(`Fix bad timeline change. Restarting al segment loaders...`),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}),this.mainSegmentLoader_.on(`earlyabort`,e=>{this.bufferBasedABR||(this.delegateLoaders_(`all`,[`abort`]),this.excludePlaylist({error:{message:`Aborted early because there isn't enough bandwidth to complete the request without rebuffering.`},playlistExclusionDuration:Gp}))});let e=()=>{if(!this.sourceUpdater_.hasCreatedSourceBuffers())return this.tryToCreateSourceBuffers_();let e=this.getCodecsOrExclude_();e&&this.sourceUpdater_.addOrChangeSourceBuffers(e)};this.mainSegmentLoader_.on(`trackinfo`,e),this.audioSegmentLoader_.on(`trackinfo`,e),this.mainSegmentLoader_.on(`fmp4`,()=>{this.triggeredFmp4Usage||=(this.tech_.trigger({type:`usage`,name:`vhs-fmp4`}),!0)}),this.audioSegmentLoader_.on(`fmp4`,()=>{this.triggeredFmp4Usage||=(this.tech_.trigger({type:`usage`,name:`vhs-fmp4`}),!0)}),this.audioSegmentLoader_.on(`ended`,()=>{this.logger_(`audioSegmentLoader ended`),this.onEndOfStream()}),[`segmentselected`,`segmentloadstart`,`segmentloaded`,`segmentkeyloadstart`,`segmentkeyloadcomplete`,`segmentdecryptionstart`,`segmentdecryptioncomplete`,`segmenttransmuxingstart`,`segmenttransmuxingcomplete`,`segmenttransmuxingtrackinfoavailable`,`segmenttransmuxingtiminginfoavailable`,`segmentappendstart`,`appendsdone`,`bandwidthupdated`,`timelinechange`,`codecschange`].forEach(e=>{this.mainSegmentLoader_.on(e,e=>{this.player_.trigger(me({},e))}),this.audioSegmentLoader_.on(e,e=>{this.player_.trigger(me({},e))}),this.subtitleSegmentLoader_.on(e,e=>{this.player_.trigger(me({},e))})})}mediaSecondsLoaded_(){return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded+this.mainSegmentLoader_.mediaSecondsLoaded)}load(){this.mainSegmentLoader_.load(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.load(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.load()}pause(){this.mainSegmentLoader_.pause(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.pause(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.pause()}fastQualityChange_(e=this.selectPlaylist()){if(e&&e===this.mainPlaylistLoader_.media()){this.logger_(`skipping fastQualityChange because new media is same as old`);return}this.switchMedia_(e,`fast-quality`),this.waitingForFastQualityPlaylistReceived_=!0}runFastQualitySwitch_(){this.waitingForFastQualityPlaylistReceived_=!1,this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}play(){if(this.setupFirstPlay())return;this.tech_.ended()&&this.tech_.setCurrentTime(0),this.hasPlayed_&&this.load();let e=this.tech_.seekable();if(this.tech_.duration()===1/0&&this.tech_.currentTime(){})}this.trigger(`sourceopen`)}handleSourceEnded_(){if(!this.inbandTextTracks_.metadataTrack_)return;let e=this.inbandTextTracks_.metadataTrack_.cues;if(!e||!e.length)return;let t=this.duration();e[e.length-1].endTime=isNaN(t)||Math.abs(t)===1/0?Number.MAX_VALUE:t}handleDurationChange_(){this.tech_.trigger(`durationchange`)}onEndOfStream(){let e=this.mainSegmentLoader_.ended_;if(this.mediaTypes_.AUDIO.activePlaylistLoader){let t=this.mainSegmentLoader_.getCurrentMediaInfo_();!t||t.hasVideo?e&&=this.audioSegmentLoader_.ended_:e=this.audioSegmentLoader_.ended_}e&&(this.stopABRTimer_(),this.sourceUpdater_.endOfStream())}stuckAtPlaylistEnd_(e){if(!this.seekable().length)return!1;let t=this.syncController_.getExpiredTime(e,this.duration());if(t===null)return!1;let n=Kp.Playlist.playlistEnd(e,t),r=this.tech_.currentTime(),i=this.tech_.buffered();if(!i.length)return n-r<=Tl;let a=i.end(i.length-1);return a-r<=Tl&&n-a<=Tl}excludePlaylist({playlistToExclude:e=this.mainPlaylistLoader_.media(),error:t={},playlistExclusionDuration:n}){if(e||=this.mainPlaylistLoader_.media(),n=n||t.playlistExclusionDuration||this.playlistExclusionDuration,!e){this.error=t,this.mediaSource.readyState===`open`?this.sourceUpdater_.endOfStream(`network`):this.trigger(`error`);return}e.playlistErrors_++;let r=this.mainPlaylistLoader_.main.playlists,i=r.filter(Ql),a=i.length===1&&i[0]===e;if(r.length===1&&n!==1/0)return W.log.warn(`Problem encountered with playlist ${e.id}. Trying again since it is the only playlist.`),this.tech_.trigger(`retryplaylist`),this.mainPlaylistLoader_.load(a);if(a){if(this.main().contentSteering){let t=this.pathwayAttribute_(e),n=this.contentSteeringController_.steeringManifest.ttl*1e3;this.contentSteeringController_.excludePathway(t),this.excludeThenChangePathway_(),setTimeout(()=>{this.contentSteeringController_.addAvailablePathway(t)},n);return}let t=!1;r.forEach(n=>{if(n===e)return;let r=n.excludeUntil;r!==void 0&&r!==1/0&&(t=!0,delete n.excludeUntil)}),t&&(W.log.warn(`Removing other playlists from the exclusion list because the last rendition is about to be excluded.`),this.tech_.trigger(`retryplaylist`))}let o;o=e.playlistErrors_>this.maxPlaylistRetries?1/0:Date.now()+n*1e3,e.excludeUntil=o,t.reason&&(e.lastExcludeReason_=t.reason),this.tech_.trigger(`excludeplaylist`),this.tech_.trigger({type:`usage`,name:`vhs-rendition-excluded`});let s=this.selectPlaylist();if(!s){this.error=`Playback cannot continue. No available working or supported playlists.`,this.trigger(`error`);return}let c=t.internal?this.logger_:W.log.warn,l=t.message?` `+t.message:``;c(`${t.internal?`Internal problem`:`Problem`} encountered with playlist ${e.id}.${l} Switching to playlist ${s.id}.`),s.attributes.AUDIO!==e.attributes.AUDIO&&this.delegateLoaders_(`audio`,[`abort`,`pause`]),s.attributes.SUBTITLES!==e.attributes.SUBTITLES&&this.delegateLoaders_(`subtitle`,[`abort`,`pause`]),this.delegateLoaders_(`main`,[`abort`,`pause`]);let u=s.targetDuration/2*1e3||5*1e3,d=typeof s.lastRequest==`number`&&Date.now()-s.lastRequest<=u;return this.switchMedia_(s,`exclude`,a||d)}pauseLoading(){this.delegateLoaders_(`all`,[`abort`,`pause`]),this.stopABRTimer_()}delegateLoaders_(e,t){let n=[],r=e===`all`;(r||e===`main`)&&n.push(this.mainPlaylistLoader_);let i=[];(r||e===`audio`)&&i.push(`AUDIO`),(r||e===`subtitle`)&&(i.push(`CLOSED-CAPTIONS`),i.push(`SUBTITLES`)),i.forEach(e=>{let t=this.mediaTypes_[e]&&this.mediaTypes_[e].activePlaylistLoader;t&&n.push(t)}),[`main`,`audio`,`subtitle`].forEach(t=>{let r=this[`${t}SegmentLoader_`];r&&(e===t||e===`all`)&&n.push(r)}),n.forEach(e=>t.forEach(t=>{typeof e[t]==`function`&&e[t]()}))}setCurrentTime(e){let t=Dl(this.tech_.buffered(),e);if(!(this.mainPlaylistLoader_&&this.mainPlaylistLoader_.media())||!this.mainPlaylistLoader_.media().segments)return 0;if(t&&t.length)return e;this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}duration(){if(!this.mainPlaylistLoader_)return 0;let e=this.mainPlaylistLoader_.media();return e?e.endList?this.mediaSource?this.mediaSource.duration:Kp.Playlist.duration(e):1/0:0}seekable(){return this.seekable_}getSeekableRange_(e,t){let n=e.media();if(!n)return null;let r=this.syncController_.getMediaSequenceSync(t);if(r&&r.isReliable){let e=r.start,t=r.end;if(!isFinite(e)||!isFinite(t))return null;let i=Kp.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,n);return Sl([[e,Math.max(e,t-i)]])}let i=this.syncController_.getExpiredTime(n,this.duration());if(i===null)return null;let a=Kp.Playlist.seekable(n,i,Kp.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,n));return a.length?a:null}computeFinalSeekable_(e,t){if(!t)return e;let n=e.start(0),r=e.end(0),i=t.start(0),a=t.end(0);return i>r||n>a?e:Sl([[Math.max(n,i),Math.min(r,a)]])}onSyncInfoUpdate_(){if(!this.mainPlaylistLoader_)return;let e=this.getSeekableRange_(this.mainPlaylistLoader_,`main`);if(!e)return;let t;if(this.mediaTypes_.AUDIO.activePlaylistLoader&&(t=this.getSeekableRange_(this.mediaTypes_.AUDIO.activePlaylistLoader,`audio`),!t))return;let n=this.seekable_;if(this.seekable_=this.computeFinalSeekable_(e,t),!this.seekable_||n&&n.length&&this.seekable_.length&&n.start(0)===this.seekable_.start(0)&&n.end(0)===this.seekable_.end(0))return;this.logger_(`seekable updated [${jl(this.seekable_)}]`);let r={seekableRanges:this.seekable_};this.trigger({type:`seekablerangeschanged`,metadata:r}),this.tech_.trigger(`seekablechanged`)}updateDuration(e){if(this.updateDuration_&&=(this.mediaSource.removeEventListener(`sourceopen`,this.updateDuration_),null),this.mediaSource.readyState!==`open`){this.updateDuration_=this.updateDuration.bind(this,e),this.mediaSource.addEventListener(`sourceopen`,this.updateDuration_);return}if(e){let e=this.seekable();if(!e.length)return;(isNaN(this.mediaSource.duration)||this.mediaSource.duration0&&(n=Math.max(n,t.end(t.length-1))),this.mediaSource.duration!==n&&this.sourceUpdater_.setDuration(n)}dispose(){this.trigger(`dispose`),this.decrypter_.terminate(),this.mainPlaylistLoader_.dispose(),this.mainSegmentLoader_.dispose(),this.contentSteeringController_.dispose(),this.keyStatusMap_.clear(),this.loadOnPlay_&&this.tech_.off(`play`,this.loadOnPlay_),[`AUDIO`,`SUBTITLES`].forEach(e=>{let t=this.mediaTypes_[e].groups;for(let e in t)t[e].forEach(e=>{e.playlistLoader&&e.playlistLoader.dispose()})}),this.audioSegmentLoader_.dispose(),this.subtitleSegmentLoader_.dispose(),this.sourceUpdater_.dispose(),this.timelineChangeController_.dispose(),this.stopABRTimer_(),this.updateDuration_&&this.mediaSource.removeEventListener(`sourceopen`,this.updateDuration_),this.mediaSource.removeEventListener(`durationchange`,this.handleDurationChange_),this.mediaSource.removeEventListener(`sourceopen`,this.handleSourceOpen_),this.mediaSource.removeEventListener(`sourceended`,this.handleSourceEnded_),this.off()}main(){return this.mainPlaylistLoader_.main}media(){return this.mainPlaylistLoader_.media()||this.initialMedia_}areMediaTypesKnown_(){let e=!!this.mediaTypes_.AUDIO.activePlaylistLoader,t=!!this.mainSegmentLoader_.getCurrentMediaInfo_(),n=e?!!this.audioSegmentLoader_.getCurrentMediaInfo_():!0;return!(!t||!n)}getCodecsOrExclude_(){let e={main:this.mainSegmentLoader_.getCurrentMediaInfo_()||{},audio:this.audioSegmentLoader_.getCurrentMediaInfo_()||{}},t=this.mainSegmentLoader_.getPendingSegmentPlaylist()||this.media();e.video=e.main;let n=Du(this.main(),t),r={},i=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(e.main.hasVideo&&(r.video=n.video||e.main.videoCodec||`avc1.4d400d`),e.main.isMuxed&&(r.video+=`,${n.audio||e.main.audioCodec||`mp4a.40.2`}`),(e.main.hasAudio&&!e.main.isMuxed||e.audio.hasAudio||i)&&(r.audio=n.audio||e.main.audioCodec||e.audio.audioCodec||`mp4a.40.2`,e.audio.isFmp4=e.main.hasAudio&&!e.main.isMuxed?e.main.isFmp4:e.audio.isFmp4),!r.audio&&!r.video){this.excludePlaylist({playlistToExclude:t,error:{message:`Could not determine codecs for playlist.`},playlistExclusionDuration:1/0});return}let a=(e,t)=>e?Be(t,this.usingManagedMediaSource_):Ve(t),o={},s;if([`video`,`audio`].forEach(function(t){if(r.hasOwnProperty(t)&&!a(e[t].isFmp4,r[t])){let n=e[t].isFmp4?`browser`:`muxer`;o[n]=o[n]||[],o[n].push(r[t]),t===`audio`&&(s=n)}}),i&&s&&t.attributes.AUDIO){let e=t.attributes.AUDIO;this.main().playlists.forEach(n=>{(n.attributes&&n.attributes.AUDIO)===e&&n!==t&&(n.excludeUntil=1/0)}),this.logger_(`excluding audio group ${e} as ${s} does not support codec(s): "${r.audio}"`)}if(Object.keys(o).length){let e=Object.keys(o).reduce((e,t)=>(e&&(e+=`, `),e+=`${t} does not support codec(s): "${o[t].join(`,`)}"`,e),``)+`.`;this.excludePlaylist({playlistToExclude:t,error:{internal:!0,message:e},playlistExclusionDuration:1/0});return}if(this.sourceUpdater_.hasCreatedSourceBuffers()&&!this.sourceUpdater_.canChangeType()){let e=[];if([`video`,`audio`].forEach(t=>{let n=(Fe(this.sourceUpdater_.codecs[t]||``)[0]||{}).type,i=(Fe(r[t]||``)[0]||{}).type;n&&i&&n.toLowerCase()!==i.toLowerCase()&&e.push(`"${this.sourceUpdater_.codecs[t]}" -> "${r[t]}"`)}),e.length){this.excludePlaylist({playlistToExclude:t,error:{message:`Codec switching not supported: ${e.join(`, `)}.`,internal:!0},playlistExclusionDuration:1/0});return}}return r}tryToCreateSourceBuffers_(){if(this.mediaSource.readyState!==`open`||this.sourceUpdater_.hasCreatedSourceBuffers()||!this.areMediaTypesKnown_())return;let e=this.getCodecsOrExclude_();if(!e)return;this.sourceUpdater_.createSourceBuffers(e);let t=[e.video,e.audio].filter(Boolean).join(`,`);this.excludeIncompatibleVariants_(t)}excludeUnsupportedVariants_(){let e=this.main().playlists,t=[];Object.keys(e).forEach(n=>{let r=e[n];if(t.indexOf(r.id)!==-1)return;t.push(r.id);let i=Du(this.main,r),a=[];i.audio&&!Ve(i.audio)&&!Be(i.audio,this.usingManagedMediaSource_)&&a.push(`audio codec ${i.audio}`),i.video&&!Ve(i.video)&&!Be(i.video,this.usingManagedMediaSource_)&&a.push(`video codec ${i.video}`),i.text&&i.text===`stpp.ttml.im1t`&&a.push(`text codec ${i.text}`),a.length&&(r.excludeUntil=1/0,this.logger_(`excluding ${r.id} for unsupported: ${a.join(`, `)}`))})}excludeIncompatibleVariants_(e){let t=[],n=this.main().playlists,r=Tu(Fe(e)),i=Eu(r),a=r.video&&Fe(r.video)[0]||null,o=r.audio&&Fe(r.audio)[0]||null;Object.keys(n).forEach(e=>{let r=n[e];if(t.indexOf(r.id)!==-1||r.excludeUntil===1/0)return;t.push(r.id);let s=[],c=Du(this.mainPlaylistLoader_.main,r),l=Eu(c);if(!(!c.audio&&!c.video)){if(l!==i&&s.push(`codec count "${l}" !== "${i}"`),!this.sourceUpdater_.canChangeType()){let e=c.video&&Fe(c.video)[0]||null,t=c.audio&&Fe(c.audio)[0]||null;e&&a&&e.type.toLowerCase()!==a.type.toLowerCase()&&s.push(`video codec "${e.type}" !== "${a.type}"`),t&&o&&t.type.toLowerCase()!==o.type.toLowerCase()&&s.push(`audio codec "${t.type}" !== "${o.type}"`)}s.length&&(r.excludeUntil=1/0,this.logger_(`excluding ${r.id}: ${s.join(` && `)}`))}})}updateAdCues_(e){let t=0,n=this.seekable();n.length&&(t=n.start(0)),_p(e,this.cueTagsTrack_,t)}goalBufferLength(){let e=this.tech_.currentTime(),t=bd.GOAL_BUFFER_LENGTH,n=bd.GOAL_BUFFER_LENGTH_RATE,r=Math.max(t,bd.MAX_GOAL_BUFFER_LENGTH);return Math.min(t+e*n,r)}bufferLowWaterLine(){let e=this.tech_.currentTime(),t=bd.BUFFER_LOW_WATER_LINE,n=bd.BUFFER_LOW_WATER_LINE_RATE,r=Math.max(t,bd.MAX_BUFFER_LOW_WATER_LINE),i=Math.max(t,bd.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(t+e*n,this.bufferBasedABR?i:r)}bufferHighWaterLine(){return bd.BUFFER_HIGH_WATER_LINE}addDateRangesToTextTrack_(e){Df(this.inbandTextTracks_,`com.apple.streaming`,this.tech_),Ef({inbandTextTracks:this.inbandTextTracks_,dateRanges:e})}addMetadataToTextTrack(e,t,n){let r=this.sourceUpdater_.videoBuffer?this.sourceUpdater_.videoTimestampOffset():this.sourceUpdater_.audioTimestampOffset();Df(this.inbandTextTracks_,e,this.tech_),Cf({inbandTextTracks:this.inbandTextTracks_,metadataArray:t,timestampOffset:r,videoDuration:n})}pathwayAttribute_(e){return e.attributes[`PATHWAY-ID`]||e.attributes.serviceLocation}initContentSteeringController_(){let e=this.main();if(e.contentSteering){for(let t of e.playlists)this.contentSteeringController_.addAvailablePathway(this.pathwayAttribute_(t));if(this.contentSteeringController_.assignTagProperties(e.uri,e.contentSteering),this.contentSteeringController_.queryBeforeStart){this.contentSteeringController_.requestSteeringManifest(!0);return}this.tech_.one(`canplay`,()=>{this.contentSteeringController_.requestSteeringManifest()})}}resetContentSteeringController_(){this.contentSteeringController_.clearAvailablePathways(),this.contentSteeringController_.dispose(),this.initContentSteeringController_()}attachContentSteeringListeners_(){this.contentSteeringController_.on(`content-steering`,this.excludeThenChangePathway_.bind(this)),[`contentsteeringloadstart`,`contentsteeringloadcomplete`,`contentsteeringparsed`].forEach(e=>{this.contentSteeringController_.on(e,e=>{this.trigger(me({},e))})}),this.sourceType_===`dash`&&this.mainPlaylistLoader_.on(`loadedplaylist`,()=>{let e=this.main();(this.contentSteeringController_.didDASHTagChange(e.uri,e.contentSteering)||(()=>{let t=this.contentSteeringController_.getAvailablePathways(),n=[];for(let r of e.playlists){let e=r.attributes.serviceLocation;if(e&&(n.push(e),!t.has(e)))return!0}return!!(!n.length&&t.size)})())&&this.resetContentSteeringController_()})}excludeThenChangePathway_(){let e=this.contentSteeringController_.getPathway();if(!e)return;this.handlePathwayClones_();let t=this.main().playlists,n=new Set,r=!1;Object.keys(t).forEach(i=>{let a=t[i],o=this.pathwayAttribute_(a),s=o&&e!==o;a.excludeUntil===1/0&&a.lastExcludeReason_===`content-steering`&&!s&&(delete a.excludeUntil,delete a.lastExcludeReason_,r=!0);let c=!a.excludeUntil&&a.excludeUntil!==1/0;!n.has(a.id)&&s&&c&&(n.add(a.id),a.excludeUntil=1/0,a.lastExcludeReason_=`content-steering`,this.logger_(`excluding ${a.id} for ${a.lastExcludeReason_}`))}),this.contentSteeringController_.manifestType_===`DASH`&&Object.keys(this.mediaTypes_).forEach(t=>{let n=this.mediaTypes_[t];if(n.activePlaylistLoader){let t=n.activePlaylistLoader.media_;t&&t.attributes.serviceLocation!==e&&(r=!0)}}),r&&this.changeSegmentPathway_()}handlePathwayClones_(){let e=this.main().playlists,t=this.contentSteeringController_.currentPathwayClones,n=this.contentSteeringController_.nextPathwayClones;if(t&&t.size||n&&n.size){for(let[e,r]of t.entries())n.get(e)||(this.mainPlaylistLoader_.updateOrDeleteClone(r),this.contentSteeringController_.excludePathway(e));for(let[r,i]of n.entries()){let n=t.get(r);if(!n){e.filter(e=>e.attributes[`PATHWAY-ID`]===i[`BASE-ID`]).forEach(e=>{this.mainPlaylistLoader_.addClonePathway(i,e)}),this.contentSteeringController_.addAvailablePathway(r);continue}this.equalPathwayClones_(n,i)||(this.mainPlaylistLoader_.updateOrDeleteClone(i,!0),this.contentSteeringController_.addAvailablePathway(r))}this.contentSteeringController_.currentPathwayClones=new Map(JSON.parse(JSON.stringify([...n])))}}equalPathwayClones_(e,t){if(e[`BASE-ID`]!==t[`BASE-ID`]||e.ID!==t.ID||e[`URI-REPLACEMENT`].HOST!==t[`URI-REPLACEMENT`].HOST)return!1;let n=e[`URI-REPLACEMENT`].PARAMS,r=t[`URI-REPLACEMENT`].PARAMS;for(let e in n)if(n[e]!==r[e])return!1;for(let e in r)if(n[e]!==r[e])return!1;return!0}changeSegmentPathway_(){let e=this.selectPlaylist();this.pauseLoading(),this.contentSteeringController_.manifestType_===`DASH`&&this.switchMediaForDASHContentSteering_(),this.switchMedia_(e,`content-steering`)}excludeNonUsablePlaylistsByKeyId_(){if(!this.mainPlaylistLoader_||!this.mainPlaylistLoader_.main)return;let e=0,t=`non-usable`;this.mainPlaylistLoader_.main.playlists.forEach(n=>{let r=this.mainPlaylistLoader_.getKeyIdSet(n);!r||!r.size||r.forEach(r=>{let i=`usable`,a=this.keyStatusMap_.has(r)&&this.keyStatusMap_.get(r)===i,o=n.lastExcludeReason_===t&&n.excludeUntil===1/0;a?a&&o&&(delete n.excludeUntil,delete n.lastExcludeReason_,this.logger_(`enabling playlist ${n.id} because key ID ${r} is ${i}`)):(n.excludeUntil!==1/0&&n.lastExcludeReason_!==t&&(n.excludeUntil=1/0,n.lastExcludeReason_=t,this.logger_(`excluding playlist ${n.id} because the key ID ${r} doesn't exist in the keyStatusMap or is not ${i}`)),e++)})}),e>=this.mainPlaylistLoader_.main.playlists.length&&this.mainPlaylistLoader_.main.playlists.forEach(e=>{let n=e&&e.attributes&&e.attributes.RESOLUTION&&e.attributes.RESOLUTION.height<720,r=e.excludeUntil===1/0&&e.lastExcludeReason_===t;n&&r&&(delete e.excludeUntil,W.log.warn(`enabling non-HD playlist ${e.id} because all playlists were excluded due to ${t} key IDs`))})}addKeyStatus_(e,t){let n=(typeof e==`string`?e:fp(e)).slice(0,32).toLowerCase();this.logger_(`KeyStatus '${t}' with key ID ${n} added to the keyStatusMap`),this.keyStatusMap_.set(n,t)}updatePlaylistByKeyStatus(e,t){this.addKeyStatus_(e,t),this.waitingForFastQualityPlaylistReceived_||this.excludeNonUsableThenChangePlaylist_(),this.mainPlaylistLoader_.off(`loadedplaylist`,this.excludeNonUsableThenChangePlaylist_.bind(this)),this.mainPlaylistLoader_.on(`loadedplaylist`,this.excludeNonUsableThenChangePlaylist_.bind(this))}excludeNonUsableThenChangePlaylist_(){this.excludeNonUsablePlaylistsByKeyId_(),this.fastQualityChange_()}},Zp=(e,t,n)=>r=>{let i=e.main.playlists[t],a=Zl(i),o=Ql(i);if(r===void 0)return o;r?delete i.disabled:i.disabled=!0;let s={renditionInfo:{id:t,bandwidth:i.attributes.BANDWIDTH,resolution:i.attributes.RESOLUTION,codecs:i.attributes.CODECS},cause:`fast-quality`};return r!==o&&!a&&(r?(n(i),e.trigger({type:`renditionenabled`,metadata:s})):e.trigger({type:`renditiondisabled`,metadata:s})),r},Qp=class{constructor(e,t,n){let{playlistController_:r}=e,i=r.fastQualityChange_.bind(r);if(t.attributes){let e=t.attributes.RESOLUTION;this.width=e&&e.width,this.height=e&&e.height,this.bandwidth=t.attributes.BANDWIDTH,this.frameRate=t.attributes[`FRAME-RATE`]}this.codecs=Du(r.main(),t),this.playlist=t,this.id=n,this.enabled=Zp(e.playlists,t.id,i)}},$p=function(e){e.representations=()=>{let t=e.playlistController_.main(),n=ou(t)?e.playlistController_.getAudioTrackPlaylists_():t.playlists;return n?n.filter(e=>!Zl(e)).map((t,n)=>new Qp(e,t,t.id)):[]}},em=[`seeking`,`seeked`,`pause`,`playing`,`error`],tm=class extends W.EventTarget{constructor(e){super(),this.playlistController_=e.playlistController,this.tech_=e.tech,this.seekable=e.seekable,this.allowSeeksWithinUnsafeLiveWindow=e.allowSeeksWithinUnsafeLiveWindow,this.liveRangeSafeTimeDelta=e.liveRangeSafeTimeDelta,this.media=e.media,this.playedRanges_=[],this.consecutiveUpdates=0,this.lastRecordedTime=null,this.checkCurrentTimeTimeout_=null,this.logger_=bl(`PlaybackWatcher`),this.logger_(`initialize`);let t=()=>this.monitorCurrentTime_(),n=()=>this.monitorCurrentTime_(),r=()=>this.techWaiting_(),i=()=>this.resetTimeUpdate_(),a=this.playlistController_,o=[`main`,`subtitle`,`audio`],s={};o.forEach(e=>{s[e]={reset:()=>this.resetSegmentDownloads_(e),updateend:()=>this.checkSegmentDownloads_(e)},a[`${e}SegmentLoader_`].on(`appendsdone`,s[e].updateend),a[`${e}SegmentLoader_`].on(`playlistupdate`,s[e].reset),this.tech_.on([`seeked`,`seeking`],s[e].reset)});let c=e=>{[`main`,`audio`].forEach(t=>{a[`${t}SegmentLoader_`][e](`appended`,this.seekingAppendCheck_)})};this.seekingAppendCheck_=()=>{this.fixesBadSeeks_()&&(this.consecutiveUpdates=0,this.lastRecordedTime=this.tech_.currentTime(),c(`off`))},this.clearSeekingAppendCheck_=()=>c(`off`),this.watchForBadSeeking_=()=>{this.clearSeekingAppendCheck_(),c(`on`)},this.tech_.on(`seeked`,this.clearSeekingAppendCheck_),this.tech_.on(`seeking`,this.watchForBadSeeking_),this.tech_.on(`waiting`,r),this.tech_.on(em,i),this.tech_.on(`canplay`,n),this.tech_.one(`play`,t),this.dispose=()=>{this.clearSeekingAppendCheck_(),this.logger_(`dispose`),this.tech_.off(`waiting`,r),this.tech_.off(em,i),this.tech_.off(`canplay`,n),this.tech_.off(`play`,t),this.tech_.off(`seeking`,this.watchForBadSeeking_),this.tech_.off(`seeked`,this.clearSeekingAppendCheck_),o.forEach(e=>{a[`${e}SegmentLoader_`].off(`appendsdone`,s[e].updateend),a[`${e}SegmentLoader_`].off(`playlistupdate`,s[e].reset),this.tech_.off([`seeked`,`seeking`],s[e].reset)}),this.checkCurrentTimeTimeout_&&I.default.clearTimeout(this.checkCurrentTimeTimeout_),this.resetTimeUpdate_()}}monitorCurrentTime_(){this.checkCurrentTime_(),this.checkCurrentTimeTimeout_&&I.default.clearTimeout(this.checkCurrentTimeTimeout_),this.checkCurrentTimeTimeout_=I.default.setTimeout(this.monitorCurrentTime_.bind(this),250)}resetSegmentDownloads_(e){let t=this.playlistController_[`${e}SegmentLoader_`];this[`${e}StalledDownloads_`]>0&&this.logger_(`resetting possible stalled download count for ${e} loader`),this[`${e}StalledDownloads_`]=0,this[`${e}Buffered_`]=t.buffered_()}checkSegmentDownloads_(e){let t=this.playlistController_,n=t[`${e}SegmentLoader_`],r=n.buffered_(),i=Pl(this[`${e}Buffered_`],r);if(this[`${e}Buffered_`]=r,i){let n={bufferedRanges:r};t.trigger({type:`bufferedrangeschanged`,metadata:n}),this.resetSegmentDownloads_(e);return}this[`${e}StalledDownloads_`]++,this.logger_(`found #${this[`${e}StalledDownloads_`]} ${e} appends that did not increase buffer (possible stalled download)`,{playlistId:n.playlist_&&n.playlist_.id,buffered:Nl(r)}),!(this[`${e}StalledDownloads_`]<10)&&(this.logger_(`${e} loader stalled download exclusion`),this.resetSegmentDownloads_(e),this.tech_.trigger({type:`usage`,name:`vhs-${e}-download-exclusion`}),e!==`subtitle`&&t.excludePlaylist({error:{message:`Excessive ${e} segment downloading detected.`},playlistExclusionDuration:1/0}))}checkCurrentTime_(){if(this.tech_.paused()||this.tech_.seeking())return;let e=this.tech_.currentTime(),t=this.tech_.buffered();if(this.lastRecordedTime===e&&(!t.length||e+Tl>=t.end(t.length-1)))return this.techWaiting_();if(this.consecutiveUpdates>=5&&e===this.lastRecordedTime)this.consecutiveUpdates++,this.waiting_();else if(e===this.lastRecordedTime)this.consecutiveUpdates++;else{this.playedRanges_.push(Sl([this.lastRecordedTime,e]));let t={playedRanges:this.playedRanges_};this.playlistController_.trigger({type:`playedrangeschanged`,metadata:t}),this.consecutiveUpdates=0,this.lastRecordedTime=e}}resetTimeUpdate_(){this.consecutiveUpdates=0}fixesBadSeeks_(){if(!this.tech_.seeking())return!1;let e=this.seekable(),t=this.tech_.currentTime(),n=this.afterSeekableWindow_(e,t,this.media(),this.allowSeeksWithinUnsafeLiveWindow),r;if(n&&(r=e.end(e.length-1)),this.beforeSeekableWindow_(e,t)){let t=e.start(0);r=t+(t===e.end(0)?0:Tl)}if(r!==void 0)return this.logger_(`Trying to seek outside of seekable at time ${t} with seekable range ${jl(e)}. Seeking to ${r}.`),this.tech_.setCurrentTime(r),!0;let i=this.playlistController_.sourceUpdater_,a=this.tech_.buffered(),o=i.audioBuffer?i.audioBuffered():null,s=i.videoBuffer?i.videoBuffered():null,c=this.media(),l=c.partTargetDuration?c.partTargetDuration:(c.targetDuration-wl)*2,u=[o,s];for(let e=0;e ${t.end(0)}]. Attempting to resume playback by seeking to the current time.`),this.tech_.trigger({type:`usage`,name:`vhs-unknown-waiting`});return}}techWaiting_(){let e=this.seekable(),t=this.tech_.currentTime();if(this.tech_.seeking())return!0;if(this.beforeSeekableWindow_(e,t)){let n=e.end(e.length-1);return this.logger_(`Fell out of live window at time ${t}. Seeking to live point (seekable end) ${n}`),this.resetTimeUpdate_(),this.tech_.setCurrentTime(n),this.tech_.trigger({type:`usage`,name:`vhs-live-resync`}),!0}let n=this.tech_.vhs.playlistController_.sourceUpdater_,r=this.tech_.buffered();if(this.videoUnderflow_({audioBuffered:n.audioBuffered(),videoBuffered:n.videoBuffered(),currentTime:t}))return this.resetTimeUpdate_(),this.tech_.setCurrentTime(t),this.tech_.trigger({type:`usage`,name:`vhs-video-underflow`}),!0;let i=Ol(r,t);return i.length>0?(this.logger_(`Stopped at ${t} and seeking to ${i.start(0)}`),this.resetTimeUpdate_(),this.skipTheGap_(t),!0):!1}afterSeekableWindow_(e,t,n,r=!1){if(!e.length)return!1;let i=e.end(e.length-1)+Tl,a=!n.endList,o=typeof n.partTargetDuration==`number`;return a&&(o||r)&&(i=e.end(e.length-1)+n.targetDuration*3),t>i}beforeSeekableWindow_(e,t){return!!(e.length&&e.start(0)>0&&t2)return{start:r,end:i}}return null}},nm={errorInterval:30,getSource(e){return e(this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource())}},rm=function(e,t){let n=0,r=0,i=xl(nm,t);e.ready(()=>{e.trigger({type:`usage`,name:`vhs-error-reload-initialized`})});let a=function(){r&&e.currentTime(r)},o=function(t){t!=null&&(r=e.duration()!==1/0&&e.currentTime()||0,e.one(`loadedmetadata`,a),e.src(t),e.trigger({type:`usage`,name:`vhs-error-reload`}),e.play())},s=function(){if(Date.now()-n{Object.defineProperty(um,e,{get(){return W.log.warn(`using Vhs.${e} is UNSAFE be sure you know what you are doing`),bd[e]},set(t){if(W.log.warn(`using Vhs.${e} is UNSAFE be sure you know what you are doing`),typeof t!=`number`||t<0){W.log.warn(`value of Vhs.${e} must be greater than or equal to 0`);return}bd[e]=t}})});var dm=`videojs-vhs`,fm=function(e,t){let n=t.media(),r=-1;for(let t=0;t{e.addQualityLevel(t)}),fm(e,t.playlists)};um.canPlaySource=function(){return W.log.warn(`VHS is no longer a tech. Please remove it from your player's techOrder.`)};var mm=(e,t,n)=>{if(!e)return e;let r={};t&&t.attributes&&t.attributes.CODECS&&(r=Tu(Fe(t.attributes.CODECS))),n&&n.attributes&&n.attributes.CODECS&&(r.audio=n.attributes.CODECS);let i=ze(r.video),a=ze(r.audio),o={};for(let n in e)o[n]={},a&&(o[n].audioContentType=a),i&&(o[n].videoContentType=i),t.contentProtection&&t.contentProtection[n]&&t.contentProtection[n].pssh&&(o[n].pssh=t.contentProtection[n].pssh),typeof e[n]==`string`&&(o[n].url=e[n]);return xl(e,o)},hm=(e,t)=>e.reduce((e,n)=>{if(!n.contentProtection)return e;let r=t.reduce((e,t)=>{let r=n.contentProtection[t];return r&&r.pssh&&(e[t]={pssh:r.pssh}),e},{});return Object.keys(r).length&&e.push(r),e},[]),gm=({player:e,sourceKeySystems:t,audioMedia:n,mainPlaylists:r})=>{if(!e.eme.initializeMediaKeys)return Promise.resolve();let i=hm(n?r.concat([n]):r,Object.keys(t)),a=[],o=[];return i.forEach(t=>{o.push(new Promise((t,n)=>{e.tech_.one(`keysessioncreated`,t)})),a.push(new Promise((n,r)=>{e.eme.initializeMediaKeys({keySystems:t},e=>{if(e){r(e);return}n()})}))}),Promise.race([Promise.all(a),Promise.race(o)])},_m=({player:e,sourceKeySystems:t,media:n,audioMedia:r})=>{let i=mm(t,n,r);return i?(e.currentSource().keySystems=i,i&&!e.eme?(W.log.warn(`DRM encrypted source cannot be decrypted without a DRM plugin`),!1):!0):!1},vm=()=>{if(!I.default.localStorage)return null;let e=I.default.localStorage.getItem(dm);if(!e)return null;try{return JSON.parse(e)}catch{return null}},ym=e=>{if(!I.default.localStorage)return!1;let t=vm();t=t?xl(t,e):e;try{I.default.localStorage.setItem(dm,JSON.stringify(t))}catch{return!1}return t},bm=e=>e.toLowerCase().indexOf(`data:application/vnd.videojs.vhs+json,`)===0?JSON.parse(e.substring(e.indexOf(`,`)+1)):e,xm=(e,t)=>{e._requestCallbackSet||=new Set,e._requestCallbackSet.add(t)},Sm=(e,t)=>{e._responseCallbackSet||=new Set,e._responseCallbackSet.add(t)},Cm=(e,t)=>{e._requestCallbackSet&&(e._requestCallbackSet.delete(t),e._requestCallbackSet.size||delete e._requestCallbackSet)},wm=(e,t)=>{e._responseCallbackSet&&(e._responseCallbackSet.delete(t),e._responseCallbackSet.size||delete e._responseCallbackSet)};um.supportsNativeHls=function(){if(!L.default||!L.default.createElement)return!1;let e=L.default.createElement(`video`);return W.getTech(`Html5`).isSupported()?[`application/vnd.apple.mpegurl`,`audio/mpegurl`,`audio/x-mpegurl`,`application/x-mpegurl`,`video/x-mpegurl`,`video/mpegurl`,`application/mpegurl`].some(function(t){return/maybe|probably/i.test(e.canPlayType(t))}):!1}(),um.supportsNativeDash=function(){return!L.default||!L.default.createElement||!W.getTech(`Html5`).isSupported()?!1:/maybe|probably/i.test(L.default.createElement(`video`).canPlayType(`application/dash+xml`))}(),um.supportsTypeNatively=e=>e===`hls`?um.supportsNativeHls:e===`dash`?um.supportsNativeDash:!1,um.isSupported=function(){return W.log.warn(`VHS is no longer a tech. Please remove it from your player's techOrder.`)},um.xhr.onRequest=function(e){xm(um.xhr,e)},um.xhr.onResponse=function(e){Sm(um.xhr,e)},um.xhr.offRequest=function(e){Cm(um.xhr,e)},um.xhr.offResponse=function(e){wm(um.xhr,e)};var Tm=W.getComponent(`Component`),Em=class extends Tm{constructor(e,t,n){if(super(t,n.vhs),typeof n.initialBandwidth==`number`&&(this.options_.bandwidth=n.initialBandwidth),this.logger_=bl(`VhsHandler`),t.options_&&t.options_.playerId){let e=W.getPlayer(t.options_.playerId);this.player_=e}if(this.tech_=t,this.source_=e,this.stats={},this.ignoreNextSeekingEvent_=!1,this.setOptions_(),this.options_.overrideNative&&t.overrideNativeAudioTracks&&t.overrideNativeVideoTracks)t.overrideNativeAudioTracks(!0),t.overrideNativeVideoTracks(!0);else if(this.options_.overrideNative&&(t.featuresNativeVideoTracks||t.featuresNativeAudioTracks))throw Error(`Overriding native VHS requires emulated tracks. See https://git.io/vMpjB`);this.on(L.default,[`fullscreenchange`,`webkitfullscreenchange`,`mozfullscreenchange`,`MSFullscreenChange`],e=>{let t=L.default.fullscreenElement||L.default.webkitFullscreenElement||L.default.mozFullScreenElement||L.default.msFullscreenElement;t&&t.contains(this.tech_.el())?this.playlistController_.fastQualityChange_():this.playlistController_.checkABR_()}),this.on(this.tech_,`seeking`,function(){if(this.ignoreNextSeekingEvent_){this.ignoreNextSeekingEvent_=!1;return}this.setCurrentTime(this.tech_.currentTime())}),this.on(this.tech_,`error`,function(){this.tech_.error()&&this.playlistController_&&this.playlistController_.pauseLoading()}),this.on(this.tech_,`play`,this.play)}setOptions_(e={}){if(this.options_=xl(this.options_,e),this.options_.withCredentials=this.options_.withCredentials||!1,this.options_.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions!==!1,this.options_.useDevicePixelRatio=this.options_.useDevicePixelRatio||!1,this.options_.usePlayerObjectFit=this.options_.usePlayerObjectFit||!1,this.options_.useBandwidthFromLocalStorage=this.source_.useBandwidthFromLocalStorage===void 0?this.options_.useBandwidthFromLocalStorage||!1:this.source_.useBandwidthFromLocalStorage,this.options_.useForcedSubtitles=this.options_.useForcedSubtitles||!1,this.options_.useNetworkInformationApi=this.options_.useNetworkInformationApi===void 0?!0:this.options_.useNetworkInformationApi,this.options_.useDtsForTimestampOffset=this.options_.useDtsForTimestampOffset||!1,this.options_.customTagParsers=this.options_.customTagParsers||[],this.options_.customTagMappers=this.options_.customTagMappers||[],this.options_.cacheEncryptionKeys=this.options_.cacheEncryptionKeys||!1,this.options_.llhls=this.options_.llhls!==!1,this.options_.bufferBasedABR=this.options_.bufferBasedABR||!1,typeof this.options_.playlistExclusionDuration!=`number`&&(this.options_.playlistExclusionDuration=60),typeof this.options_.bandwidth!=`number`&&this.options_.useBandwidthFromLocalStorage){let e=vm();e&&e.bandwidth&&(this.options_.bandwidth=e.bandwidth,this.tech_.trigger({type:`usage`,name:`vhs-bandwidth-from-local-storage`})),e&&e.throughput&&(this.options_.throughput=e.throughput,this.tech_.trigger({type:`usage`,name:`vhs-throughput-from-local-storage`}))}typeof this.options_.bandwidth!=`number`&&(this.options_.bandwidth=bd.INITIAL_BANDWIDTH),this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===bd.INITIAL_BANDWIDTH,[`withCredentials`,`useDevicePixelRatio`,`usePlayerObjectFit`,`customPixelRatio`,`limitRenditionByPlayerDimensions`,`bandwidth`,`customTagParsers`,`customTagMappers`,`cacheEncryptionKeys`,`playlistSelector`,`initialPlaylistSelector`,`bufferBasedABR`,`liveRangeSafeTimeDelta`,`llhls`,`useForcedSubtitles`,`useNetworkInformationApi`,`useDtsForTimestampOffset`,`exactManifestTimings`,`leastPixelDiffSelector`].forEach(e=>{this.source_[e]!==void 0&&(this.options_[e]=this.source_[e])}),this.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions,this.useDevicePixelRatio=this.options_.useDevicePixelRatio,this.usePlayerObjectFit=this.options_.usePlayerObjectFit;let t=this.options_.customPixelRatio;typeof t==`number`&&t>=0&&(this.customPixelRatio=t)}setOptions(e={}){this.setOptions_(e)}src(e,t){if(!e)return;this.setOptions_(),this.options_.src=bm(this.source_.src),this.options_.tech=this.tech_,this.options_.externVhs=um,this.options_.sourceType=We(t),this.options_.seekTo=e=>{this.tech_.setCurrentTime(e)},this.options_.player_=this.player_,this.playlistController_=new Xp(this.options_);let n=xl({liveRangeSafeTimeDelta:Tl},this.options_,{seekable:()=>this.seekable(),media:()=>this.playlistController_.media(),playlistController:this.playlistController_});this.playbackWatcher_=new tm(n),this.attachStreamingEventListeners_(),this.playlistController_.on(`error`,()=>{let e=W.players[this.tech_.options_.playerId],t=this.playlistController_.error;typeof t==`object`&&!t.code?t.code=3:typeof t==`string`&&(t={message:t,code:3}),e.error(t)});let r=this.options_.bufferBasedABR?um.movingAverageBandwidthSelector(.55):um.STANDARD_PLAYLIST_SELECTOR;this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):r.bind(this),this.playlistController_.selectInitialPlaylist=um.INITIAL_PLAYLIST_SELECTOR.bind(this),this.playlists=this.playlistController_.mainPlaylistLoader_,this.mediaSource=this.playlistController_.mediaSource,Object.defineProperties(this,{selectPlaylist:{get(){return this.playlistController_.selectPlaylist},set(e){this.playlistController_.selectPlaylist=e.bind(this)}},throughput:{get(){return this.playlistController_.mainSegmentLoader_.throughput.rate},set(e){this.playlistController_.mainSegmentLoader_.throughput.rate=e,this.playlistController_.mainSegmentLoader_.throughput.count=1}},bandwidth:{get(){let e=this.playlistController_.mainSegmentLoader_.bandwidth,t=I.default.navigator.connection||I.default.navigator.mozConnection||I.default.navigator.webkitConnection,n=1e7;if(this.options_.useNetworkInformationApi&&t){let r=t.downlink*1e3*1e3;e=r>=n&&e>=n?Math.max(e,r):r}return e},set(e){this.playlistController_.mainSegmentLoader_.bandwidth=e,this.playlistController_.mainSegmentLoader_.throughput={rate:0,count:0}}},systemBandwidth:{get(){let e=1/(this.bandwidth||1),t;return t=this.throughput>0?1/this.throughput:0,Math.floor(1/(e+t))},set(){W.log.error(`The "systemBandwidth" property is read-only`)}}}),this.options_.bandwidth&&(this.bandwidth=this.options_.bandwidth),this.options_.throughput&&(this.throughput=this.options_.throughput),Object.defineProperties(this.stats,{bandwidth:{get:()=>this.bandwidth||0,enumerable:!0},mediaRequests:{get:()=>this.playlistController_.mediaRequests_()||0,enumerable:!0},mediaRequestsAborted:{get:()=>this.playlistController_.mediaRequestsAborted_()||0,enumerable:!0},mediaRequestsTimedout:{get:()=>this.playlistController_.mediaRequestsTimedout_()||0,enumerable:!0},mediaRequestsErrored:{get:()=>this.playlistController_.mediaRequestsErrored_()||0,enumerable:!0},mediaTransferDuration:{get:()=>this.playlistController_.mediaTransferDuration_()||0,enumerable:!0},mediaBytesTransferred:{get:()=>this.playlistController_.mediaBytesTransferred_()||0,enumerable:!0},mediaSecondsLoaded:{get:()=>this.playlistController_.mediaSecondsLoaded_()||0,enumerable:!0},mediaAppends:{get:()=>this.playlistController_.mediaAppends_()||0,enumerable:!0},mainAppendsToLoadedData:{get:()=>this.playlistController_.mainAppendsToLoadedData_()||0,enumerable:!0},audioAppendsToLoadedData:{get:()=>this.playlistController_.audioAppendsToLoadedData_()||0,enumerable:!0},appendsToLoadedData:{get:()=>this.playlistController_.appendsToLoadedData_()||0,enumerable:!0},timeToLoadedData:{get:()=>this.playlistController_.timeToLoadedData_()||0,enumerable:!0},buffered:{get:()=>Nl(this.tech_.buffered()),enumerable:!0},currentTime:{get:()=>this.tech_.currentTime(),enumerable:!0},currentSource:{get:()=>this.tech_.currentSource_,enumerable:!0},currentTech:{get:()=>this.tech_.name_,enumerable:!0},duration:{get:()=>this.tech_.duration(),enumerable:!0},main:{get:()=>this.playlists.main,enumerable:!0},playerDimensions:{get:()=>this.tech_.currentDimensions(),enumerable:!0},seekable:{get:()=>Nl(this.tech_.seekable()),enumerable:!0},timestamp:{get:()=>Date.now(),enumerable:!0},videoPlaybackQuality:{get:()=>this.tech_.getVideoPlaybackQuality(),enumerable:!0}}),this.tech_.one(`canplay`,this.playlistController_.setupFirstPlay.bind(this.playlistController_)),this.tech_.on(`bandwidthupdate`,()=>{this.options_.useBandwidthFromLocalStorage&&ym({bandwidth:this.bandwidth,throughput:Math.round(this.throughput)})}),this.playlistController_.on(`selectedinitialmedia`,()=>{$p(this)}),this.playlistController_.sourceUpdater_.on(`createdsourcebuffers`,()=>{this.setupEme_()}),this.on(this.playlistController_,`progress`,function(){this.tech_.trigger(`progress`)}),this.on(this.playlistController_,`firstplay`,function(){this.ignoreNextSeekingEvent_=!0}),this.setupQualityLevels_(),this.tech_.el()&&(this.mediaSourceUrl_=I.default.URL.createObjectURL(this.playlistController_.mediaSource),(W.browser.IS_ANY_SAFARI||W.browser.IS_IOS)&&this.options_.overrideNative&&this.options_.sourceType===`hls`&&typeof this.tech_.addSourceElement==`function`?(this.tech_.addSourceElement(this.mediaSourceUrl_),this.tech_.addSourceElement(this.source_.src)):this.tech_.src(this.mediaSourceUrl_))}createKeySessions_(){let e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;this.logger_(`waiting for EME key session creation`),gm({player:this.player_,sourceKeySystems:this.source_.keySystems,audioMedia:e&&e.media(),mainPlaylists:this.playlists.main.playlists}).then(()=>{this.logger_(`created EME key session`),this.playlistController_.sourceUpdater_.initializedEme()}).catch(e=>{this.logger_(`error while creating EME key session`,e),this.player_.error({message:`Failed to initialize media keys for EME`,code:3})})}handleWaitingForKey_(){this.logger_(`waitingforkey fired, attempting to create any new key sessions`),this.createKeySessions_()}setupEme_(){let e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader,t=_m({player:this.player_,sourceKeySystems:this.source_.keySystems,media:this.playlists.media(),audioMedia:e&&e.media()});if(this.player_.tech_.on(`keystatuschange`,e=>{this.playlistController_.updatePlaylistByKeyStatus(e.keyId,e.status)}),this.handleWaitingForKey_=this.handleWaitingForKey_.bind(this),this.player_.tech_.on(`waitingforkey`,this.handleWaitingForKey_),!t){this.playlistController_.sourceUpdater_.initializedEme();return}this.createKeySessions_()}setupQualityLevels_(){let e=W.players[this.tech_.options_.playerId];!e||!e.qualityLevels||this.qualityLevels_||(this.qualityLevels_=e.qualityLevels(),this.playlistController_.on(`selectedinitialmedia`,()=>{pm(this.qualityLevels_,this)}),this.playlists.on(`mediachange`,()=>{fm(this.qualityLevels_,this.playlists)}))}static version(){return{"@videojs/http-streaming":am,"mux.js":om,"mpd-parser":sm,"m3u8-parser":cm,"aes-decrypter":lm}}version(){return this.constructor.version()}canChangeType(){return up.canChangeType()}play(){this.playlistController_.play()}setCurrentTime(e){this.playlistController_.setCurrentTime(e)}duration(){return this.playlistController_.duration()}seekable(){return this.playlistController_.seekable()}dispose(){this.playbackWatcher_&&this.playbackWatcher_.dispose(),this.playlistController_&&this.playlistController_.dispose(),this.qualityLevels_&&this.qualityLevels_.dispose(),this.tech_&&this.tech_.vhs&&delete this.tech_.vhs,this.mediaSourceUrl_&&I.default.URL.revokeObjectURL&&(I.default.URL.revokeObjectURL(this.mediaSourceUrl_),this.mediaSourceUrl_=null),this.tech_&&this.tech_.off(`waitingforkey`,this.handleWaitingForKey_),super.dispose()}convertToProgramTime(e,t){return od({playlist:this.playlistController_.media(),time:e,callback:t})}seekToProgramTime(e,t,n=!0,r=2){return sd({programTime:e,playlist:this.playlistController_.media(),retryCount:r,pauseAfterSeek:n,seekTo:this.options_.seekTo,tech:this.options_.tech,callback:t})}setupXhrHooks_(){this.xhr.onRequest=e=>{xm(this.xhr,e)},this.xhr.onResponse=e=>{Sm(this.xhr,e)},this.xhr.offRequest=e=>{Cm(this.xhr,e)},this.xhr.offResponse=e=>{wm(this.xhr,e)},this.player_.trigger(`xhr-hooks-ready`)}attachStreamingEventListeners_(){[`seekablerangeschanged`,`bufferedrangeschanged`,`contentsteeringloadstart`,`contentsteeringloadcomplete`,`contentsteeringparsed`].forEach(e=>{this.playlistController_.on(e,e=>{this.player_.trigger(me({},e))})}),[`gapjumped`,`playedrangeschanged`].forEach(e=>{this.playbackWatcher_.on(e,e=>{this.player_.trigger(me({},e))})})}},Dm={name:`videojs-http-streaming`,VERSION:am,canHandleSource(e,t={}){let n=xl(W.options,t);return!n.vhs.experimentalUseMMS&&!Be(`avc1.4d400d,mp4a.40.2`,!1)?!1:Dm.canPlayType(e.type,n)},handleSource(e,t,n={}){return t.vhs=new Em(e,t,xl(W.options,n)),t.vhs.xhr=Hu(),t.vhs.setupXhrHooks_(),t.vhs.src(e.src,e.type),t.vhs},canPlayType(e,t){let n=We(e);if(!n)return``;let r=Dm.getOverrideNative(t);return!um.supportsTypeNatively(n)||r?`maybe`:``},getOverrideNative(e={}){let{vhs:t={}}=e,n=!(W.browser.IS_ANY_SAFARI||W.browser.IS_IOS),{overrideNative:r=n}=t;return r}};Be(`avc1.4d400d,mp4a.40.2`,!0)&&W.getTech(`Html5`).registerSourceHandler(Dm,0),W.VhsHandler=Em,W.VhsSourceHandler=Dm,W.Vhs=um,W.use||W.registerComponent(`Vhs`,um),W.options.vhs=W.options.vhs||{},(!W.getPlugin||!W.getPlugin(`reloadSourceOnError`))&&W.registerPlugin(`reloadSourceOnError`,im);var G=Number.isFinite||function(e){return typeof e==`number`&&isFinite(e)},Om=Number.isSafeInteger||function(e){return typeof e==`number`&&Math.abs(e)<=km},km=2**53-1||9007199254740991,K=function(e){return e.NETWORK_ERROR=`networkError`,e.MEDIA_ERROR=`mediaError`,e.KEY_SYSTEM_ERROR=`keySystemError`,e.MUX_ERROR=`muxError`,e.OTHER_ERROR=`otherError`,e}({}),q=function(e){return e.KEY_SYSTEM_NO_KEYS=`keySystemNoKeys`,e.KEY_SYSTEM_NO_ACCESS=`keySystemNoAccess`,e.KEY_SYSTEM_NO_SESSION=`keySystemNoSession`,e.KEY_SYSTEM_NO_CONFIGURED_LICENSE=`keySystemNoConfiguredLicense`,e.KEY_SYSTEM_LICENSE_REQUEST_FAILED=`keySystemLicenseRequestFailed`,e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED=`keySystemServerCertificateRequestFailed`,e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED=`keySystemServerCertificateUpdateFailed`,e.KEY_SYSTEM_SESSION_UPDATE_FAILED=`keySystemSessionUpdateFailed`,e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED=`keySystemStatusOutputRestricted`,e.KEY_SYSTEM_STATUS_INTERNAL_ERROR=`keySystemStatusInternalError`,e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR=`keySystemDestroyMediaKeysError`,e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR=`keySystemDestroyCloseSessionError`,e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR=`keySystemDestroyRemoveSessionError`,e.MANIFEST_LOAD_ERROR=`manifestLoadError`,e.MANIFEST_LOAD_TIMEOUT=`manifestLoadTimeOut`,e.MANIFEST_PARSING_ERROR=`manifestParsingError`,e.MANIFEST_INCOMPATIBLE_CODECS_ERROR=`manifestIncompatibleCodecsError`,e.LEVEL_EMPTY_ERROR=`levelEmptyError`,e.LEVEL_LOAD_ERROR=`levelLoadError`,e.LEVEL_LOAD_TIMEOUT=`levelLoadTimeOut`,e.LEVEL_PARSING_ERROR=`levelParsingError`,e.LEVEL_SWITCH_ERROR=`levelSwitchError`,e.AUDIO_TRACK_LOAD_ERROR=`audioTrackLoadError`,e.AUDIO_TRACK_LOAD_TIMEOUT=`audioTrackLoadTimeOut`,e.SUBTITLE_LOAD_ERROR=`subtitleTrackLoadError`,e.SUBTITLE_TRACK_LOAD_TIMEOUT=`subtitleTrackLoadTimeOut`,e.FRAG_LOAD_ERROR=`fragLoadError`,e.FRAG_LOAD_TIMEOUT=`fragLoadTimeOut`,e.FRAG_DECRYPT_ERROR=`fragDecryptError`,e.FRAG_PARSING_ERROR=`fragParsingError`,e.FRAG_GAP=`fragGap`,e.REMUX_ALLOC_ERROR=`remuxAllocError`,e.KEY_LOAD_ERROR=`keyLoadError`,e.KEY_LOAD_TIMEOUT=`keyLoadTimeOut`,e.BUFFER_ADD_CODEC_ERROR=`bufferAddCodecError`,e.BUFFER_INCOMPATIBLE_CODECS_ERROR=`bufferIncompatibleCodecsError`,e.BUFFER_APPEND_ERROR=`bufferAppendError`,e.BUFFER_APPENDING_ERROR=`bufferAppendingError`,e.BUFFER_STALLED_ERROR=`bufferStalledError`,e.BUFFER_FULL_ERROR=`bufferFullError`,e.BUFFER_SEEK_OVER_HOLE=`bufferSeekOverHole`,e.BUFFER_NUDGE_ON_STALL=`bufferNudgeOnStall`,e.ASSET_LIST_LOAD_ERROR=`assetListLoadError`,e.ASSET_LIST_LOAD_TIMEOUT=`assetListLoadTimeout`,e.ASSET_LIST_PARSING_ERROR=`assetListParsingError`,e.INTERSTITIAL_ASSET_ITEM_ERROR=`interstitialAssetItemError`,e.INTERNAL_EXCEPTION=`internalException`,e.INTERNAL_ABORTED=`aborted`,e.ATTACH_MEDIA_ERROR=`attachMediaError`,e.UNKNOWN=`unknown`,e}({}),J=function(e){return e.MEDIA_ATTACHING=`hlsMediaAttaching`,e.MEDIA_ATTACHED=`hlsMediaAttached`,e.MEDIA_DETACHING=`hlsMediaDetaching`,e.MEDIA_DETACHED=`hlsMediaDetached`,e.MEDIA_ENDED=`hlsMediaEnded`,e.STALL_RESOLVED=`hlsStallResolved`,e.BUFFER_RESET=`hlsBufferReset`,e.BUFFER_CODECS=`hlsBufferCodecs`,e.BUFFER_CREATED=`hlsBufferCreated`,e.BUFFER_APPENDING=`hlsBufferAppending`,e.BUFFER_APPENDED=`hlsBufferAppended`,e.BUFFER_EOS=`hlsBufferEos`,e.BUFFERED_TO_END=`hlsBufferedToEnd`,e.BUFFER_FLUSHING=`hlsBufferFlushing`,e.BUFFER_FLUSHED=`hlsBufferFlushed`,e.MANIFEST_LOADING=`hlsManifestLoading`,e.MANIFEST_LOADED=`hlsManifestLoaded`,e.MANIFEST_PARSED=`hlsManifestParsed`,e.LEVEL_SWITCHING=`hlsLevelSwitching`,e.LEVEL_SWITCHED=`hlsLevelSwitched`,e.LEVEL_LOADING=`hlsLevelLoading`,e.LEVEL_LOADED=`hlsLevelLoaded`,e.LEVEL_UPDATED=`hlsLevelUpdated`,e.LEVEL_PTS_UPDATED=`hlsLevelPtsUpdated`,e.LEVELS_UPDATED=`hlsLevelsUpdated`,e.AUDIO_TRACKS_UPDATED=`hlsAudioTracksUpdated`,e.AUDIO_TRACK_SWITCHING=`hlsAudioTrackSwitching`,e.AUDIO_TRACK_SWITCHED=`hlsAudioTrackSwitched`,e.AUDIO_TRACK_LOADING=`hlsAudioTrackLoading`,e.AUDIO_TRACK_LOADED=`hlsAudioTrackLoaded`,e.AUDIO_TRACK_UPDATED=`hlsAudioTrackUpdated`,e.SUBTITLE_TRACKS_UPDATED=`hlsSubtitleTracksUpdated`,e.SUBTITLE_TRACKS_CLEARED=`hlsSubtitleTracksCleared`,e.SUBTITLE_TRACK_SWITCH=`hlsSubtitleTrackSwitch`,e.SUBTITLE_TRACK_LOADING=`hlsSubtitleTrackLoading`,e.SUBTITLE_TRACK_LOADED=`hlsSubtitleTrackLoaded`,e.SUBTITLE_TRACK_UPDATED=`hlsSubtitleTrackUpdated`,e.SUBTITLE_FRAG_PROCESSED=`hlsSubtitleFragProcessed`,e.CUES_PARSED=`hlsCuesParsed`,e.NON_NATIVE_TEXT_TRACKS_FOUND=`hlsNonNativeTextTracksFound`,e.INIT_PTS_FOUND=`hlsInitPtsFound`,e.FRAG_LOADING=`hlsFragLoading`,e.FRAG_LOAD_EMERGENCY_ABORTED=`hlsFragLoadEmergencyAborted`,e.FRAG_LOADED=`hlsFragLoaded`,e.FRAG_DECRYPTED=`hlsFragDecrypted`,e.FRAG_PARSING_INIT_SEGMENT=`hlsFragParsingInitSegment`,e.FRAG_PARSING_USERDATA=`hlsFragParsingUserdata`,e.FRAG_PARSING_METADATA=`hlsFragParsingMetadata`,e.FRAG_PARSED=`hlsFragParsed`,e.FRAG_BUFFERED=`hlsFragBuffered`,e.FRAG_CHANGED=`hlsFragChanged`,e.FPS_DROP=`hlsFpsDrop`,e.FPS_DROP_LEVEL_CAPPING=`hlsFpsDropLevelCapping`,e.MAX_AUTO_LEVEL_UPDATED=`hlsMaxAutoLevelUpdated`,e.ERROR=`hlsError`,e.DESTROYING=`hlsDestroying`,e.KEY_LOADING=`hlsKeyLoading`,e.KEY_LOADED=`hlsKeyLoaded`,e.LIVE_BACK_BUFFER_REACHED=`hlsLiveBackBufferReached`,e.BACK_BUFFER_REACHED=`hlsBackBufferReached`,e.STEERING_MANIFEST_LOADED=`hlsSteeringManifestLoaded`,e.ASSET_LIST_LOADING=`hlsAssetListLoading`,e.ASSET_LIST_LOADED=`hlsAssetListLoaded`,e.INTERSTITIALS_UPDATED=`hlsInterstitialsUpdated`,e.INTERSTITIALS_BUFFERED_TO_BOUNDARY=`hlsInterstitialsBufferedToBoundary`,e.INTERSTITIAL_ASSET_PLAYER_CREATED=`hlsInterstitialAssetPlayerCreated`,e.INTERSTITIAL_STARTED=`hlsInterstitialStarted`,e.INTERSTITIAL_ASSET_STARTED=`hlsInterstitialAssetStarted`,e.INTERSTITIAL_ASSET_ENDED=`hlsInterstitialAssetEnded`,e.INTERSTITIAL_ASSET_ERROR=`hlsInterstitialAssetError`,e.INTERSTITIAL_ENDED=`hlsInterstitialEnded`,e.INTERSTITIALS_PRIMARY_RESUMED=`hlsInterstitialsPrimaryResumed`,e.PLAYOUT_LIMIT_REACHED=`hlsPlayoutLimitReached`,e.EVENT_CUE_ENTER=`hlsEventCueEnter`,e}({}),Am={MANIFEST:`manifest`,LEVEL:`level`,AUDIO_TRACK:`audioTrack`,SUBTITLE_TRACK:`subtitleTrack`},Y={MAIN:`main`,AUDIO:`audio`,SUBTITLE:`subtitle`},jm=class{constructor(e,t=0,n=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=n}sample(e,t){let n=this.alpha_**+e;this.estimate_=t*(1-n)+n*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-this.alpha_**+this.totalWeight_;if(e)return this.estimate_/e}return this.estimate_}},Mm=class{constructor(e,t,n,r=100){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_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new jm(e),this.fast_=new jm(t),this.defaultTTFB_=r,this.ttfb_=new jm(e)}update(e,t){let{slow_:n,fast_:r,ttfb_:i}=this;n.halfLife!==e&&(this.slow_=new jm(e,n.getEstimate(),n.getTotalWeight())),r.halfLife!==t&&(this.fast_=new jm(t,r.getEstimate(),r.getTotalWeight())),i.halfLife!==e&&(this.ttfb_=new jm(e,i.getEstimate(),i.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);let n=8*t,r=e/1e3,i=n/r;this.fast_.sample(r,i),this.slow_.sample(r,i)}sampleTTFB(e){let t=e/1e3,n=Math.sqrt(2)*Math.exp(-(t**2)/2);this.ttfb_.sample(n,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}};function Nm(e,t,n){return(t=Rm(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Pm(){return Pm=Object.assign?Object.assign.bind():function(e){for(var t=1;t`):Bm}function Wm(e,t,n){return t[e]?t[e].bind(t):Um(e,n)}var Gm=Hm();function Km(e,t,n){let r=Hm();if(typeof console==`object`&&e===!0||typeof e==`object`){let i=[`debug`,`log`,`info`,`warn`,`error`];i.forEach(t=>{r[t]=Wm(t,e,n)});try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch{return Hm()}i.forEach(t=>{Gm[t]=Wm(t,e)})}else Pm(Gm,r);return r}var qm=Gm;function Jm(e=!0){if(!(typeof self>`u`))return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Ym(e){return typeof self<`u`&&e===self.ManagedMediaSource}function Xm(e,t){let n=Object.keys(e),r=Object.keys(t),i=n.length,a=r.length;return!i||!a||i===a&&!n.some(e=>r.indexOf(e)===-1)}function Zm(e,t=!1){if(typeof TextDecoder<`u`){let n=new TextDecoder(`utf-8`).decode(e);if(t){let e=n.indexOf(`\0`);return e===-1?n:n.substring(0,e)}return n.replace(/\0/g,``)}let n=e.length,r,i,a,o=``,s=0;for(;s>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(r);break;case 12:case 13:i=e[s++],o+=String.fromCharCode((r&31)<<6|i&63);break;case 14:i=e[s++],a=e[s++],o+=String.fromCharCode((r&15)<<12|(i&63)<<6|(a&63)<<0);break}}return o}function Qm(e){let t=``;for(let n=0;n1||n===1&&(t=this.levelkeys[e[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!G(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return ch(this)?(this._ref||={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime},this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){let t=this.levelkeys;if(t){var n;let r=t[e];r&&!((n=this._decryptdata)!=null&&n.keyId)&&(this._decryptdata=r.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,n,r,i,a=!1){let{elementaryStreams:o}=this,s=o[e];if(!s){o[e]={startPTS:t,endPTS:n,startDTS:r,endDTS:i,partial:a};return}s.startPTS=Math.min(s.startPTS,t),s.endPTS=Math.max(s.endPTS,n),s.startDTS=Math.min(s.startDTS,r),s.endDTS=Math.max(s.endDTS,i)}},uh=class extends sh{constructor(e,t,n,r,i){super(n),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint(`DURATION`),this.gap=e.bool(`GAP`),this.independent=e.bool(`INDEPENDENT`),this.relurl=e.enumeratedString(`URI`),this.fragment=t,this.index=r;let a=e.enumeratedString(`BYTERANGE`);a&&this.setByteRange(a,i),i&&(this.fragOffset=i.fragOffset+i.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}};function dh(e,t){let n=Object.getPrototypeOf(e);if(n)return Object.getOwnPropertyDescriptor(n,t)||dh(n,t)}function fh(e,t){let n=dh(e,t);n&&(n.enumerable=!0,Object.defineProperty(e,t,n))}var ph=2**32-1,mh=[].push,hh={video:1,audio:2,id3:3,text:4};function gh(e){return String.fromCharCode.apply(null,e)}function _h(e,t){let n=e[t]<<8|e[t+1];return n<0?65536+n:n}function X(e,t){let n=yh(e,t);return n<0?4294967296+n:n}function vh(e,t){let n=X(e,t);return n*=2**32,n+=X(e,t+4),n}function yh(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function bh(e){let t=e.byteLength;for(let n=0;n8&&e[n+4]===109&&e[n+5]===111&&e[n+6]===111&&e[n+7]===102)return!0;n=r>1?n+r:t}return!1}function Z(e,t){let n=[];if(!t.length)return n;let r=e.byteLength;for(let i=0;i1?i+a:r;if(o===t[0])if(t.length===1)n.push(e.subarray(i+8,s));else{let r=Z(e.subarray(i+8,s),t.slice(1));r.length&&mh.apply(n,r)}i=s}return n}function xh(e){let t=[],n=e[0],r=8,i=X(e,r);r+=4;let a=0,o=0;n===0?(a=X(e,r),o=X(e,r+4),r+=8):(a=vh(e,r),o=vh(e,r+8),r+=16),r+=2;let s=e.length+o,c=_h(e,r);r+=2;for(let n=0;n>>31==1)return qm.warn(`SIDX has hierarchical references (not supported)`),null;let c=X(e,n);n+=4,t.push({referenceSize:o,subsegmentDuration:c,info:{duration:c/i,start:s,end:s+o-1}}),s+=o,n+=4,r=n}return{earliestPresentationTime:a,timescale:i,version:n,referencesCount:c,references:t}}function Sh(e){let t=[],n=Z(e,[`moov`,`trak`]);for(let e=0;e{let n=t[X(e,4)];n&&(n.default={duration:X(e,12),flags:X(e,20)})}),t}function Ch(e){let t=e.subarray(8),n=t.subarray(86),r=gh(t.subarray(4,8)),i=r,a,o=r===`enca`||r===`encv`;o&&Z(Z(t,[r])[0].subarray(r===`enca`?28:78),[`sinf`]).forEach(e=>{let t=Z(e,[`schm`])[0];if(t){let n=gh(t.subarray(4,8));if(n===`cbcs`||n===`cenc`){let t=Z(e,[`frma`])[0];t&&(i=gh(t))}}});let s=i;switch(i){case`avc1`:case`avc2`:case`avc3`:case`avc4`:{let e=Z(n,[`avcC`])[0];e&&e.length>3&&(i+=`.`+Dh(e[1])+Dh(e[2])+Dh(e[3]),a=wh(s===`avc1`?`dva1`:`dvav`,n));break}case`mp4a`:{let e=Z(t,[r])[0],n=Z(e.subarray(28),[`esds`])[0];if(n&&n.length>7){let e=4;if(n[e++]!==3)break;e=Eh(n,e),e+=2;let t=n[e++];if(t&128&&(e+=2),t&64&&(e+=n[e++]),n[e++]!==4)break;e=Eh(n,e);let r=n[e++];if(r===64)i+=`.`+Dh(r);else break;if(e+=12,n[e++]!==5)break;e=Eh(n,e);let a=n[e++],o=(a&248)>>3;o===31&&(o+=1+((a&7)<<3)+((n[e]&224)>>5)),i+=`.`+o}break}case`hvc1`:case`hev1`:{let e=Z(n,[`hvcC`])[0];if(e&&e.length>12){let t=e[1],n=[``,`A`,`B`,`C`][t>>6],r=t&31,a=X(e,2),o=(t&32)>>5?`H`:`L`,s=e[12],c=e.subarray(6,12);i+=`.`+n+r,i+=`.`+Th(a).toString(16).toUpperCase(),i+=`.`+o+s;let l=``;for(let e=c.length;e--;){let t=c[e];(t||l)&&(l=`.`+t.toString(16).toUpperCase()+l)}i+=l}a=wh(s==`hev1`?`dvhe`:`dvh1`,n);break}case`dvh1`:case`dvhe`:case`dvav`:case`dva1`:case`dav1`:i=wh(i,n)||i;break;case`vp09`:{let e=Z(n,[`vpcC`])[0];if(e&&e.length>6){let t=e[4],n=e[5],r=e[6]>>4&15;i+=`.`+Oh(t)+`.`+Oh(n)+`.`+Oh(r)}break}case`av01`:{let e=Z(n,[`av1C`])[0];if(e&&e.length>2){let t=e[1]>>>5,r=e[1]&31,o=e[2]>>>7?`H`:`M`,s=(e[2]&64)>>6,c=(e[2]&32)>>5,l=t===2&&s?c?12:10:s?10:8,u=(e[2]&16)>>4,d=(e[2]&8)>>3,f=(e[2]&4)>>2,p=e[2]&3;i+=`.`+t+`.`+Oh(r)+o+`.`+Oh(l)+`.`+u+`.`+d+f+p+`.`+Oh(1)+`.`+Oh(1)+`.`+Oh(1)+`.0`,a=wh(`dav1`,n)}break}}return{codec:i,encrypted:o,supplemental:a}}function wh(e,t){let n=Z(t,[`dvvC`]),r=n.length?n[0]:Z(t,[`dvcC`])[0];if(r){let t=r[2]>>1&127,n=r[2]<<5&32|r[3]>>3&31;return e+`.`+Oh(t)+`.`+Oh(n)}}function Th(e){let t=0;for(let n=0;n<32;n++)t|=(e>>n&1)<<31-n;return t>>>0}function Eh(e,t){let n=t+5;for(;e[t++]&128&&t{let r=e.subarray(8,24);r.some(e=>e!==0)||(qm.log(`[eme] Patching keyId in 'enc${t?`a`:`v`}>sinf>>tenc' box: ${Qm(r)} -> ${Qm(n)}`),e.set(n,8))})}function Ah(e){let t=[];return jh(e,e=>t.push(e.subarray(8,24))),t}function jh(e,t){Z(e,[`moov`,`trak`]).forEach(e=>{let n=Z(e,[`mdia`,`minf`,`stbl`,`stsd`])[0];if(!n)return;let r=n.subarray(8),i=Z(r,[`enca`]),a=i.length>0;a||(i=Z(r,[`encv`])),i.forEach(e=>{Z(a?e.subarray(28):e.subarray(78),[`sinf`]).forEach(e=>{let n=Mh(e);n&&t(n,a)})})})}function Mh(e){let t=Z(e,[`schm`])[0];if(t){let n=gh(t.subarray(4,8));if(n===`cbcs`||n===`cenc`){let t=Z(e,[`schi`,`tenc`])[0];if(t)return t}}}function Nh(e,t,n){let r={},i=Z(e,[`moof`,`traf`]);for(let e=0;er[e].duration)){let t=1/0,n=0,i=Z(e,[`sidx`]);for(let e=0;ee+t.info.duration||0,0);n=Math.max(n,e+r.earliestPresentationTime/r.timescale)}}n&&G(n)&&Object.keys(r).forEach(e=>{r[e].duration||(r[e].duration=n*r[e].timescale-r[e].start)})}return r}function Ph(e){let t={valid:null,remainder:null},n=Z(e,[`moof`]);if(n.length<2)return t.remainder=e,t;let r=n[n.length-1];return t.valid=e.slice(0,r.byteOffset-8),t.remainder=e.slice(r.byteOffset-8),t}function Fh(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function Ih(e,t){let n=[],r=t.samples,i=t.timescale,a=t.id,o=!1;return Z(r,[`moof`]).map(s=>{let c=s.byteOffset-8;Z(s,[`traf`]).map(s=>{let l=Z(s,[`tfdt`]).map(e=>{let t=e[0],n=X(e,4);return t===1&&(n*=2**32,n+=X(e,8)),n/i})[0];return l!==void 0&&(e=l),Z(s,[`tfhd`]).map(l=>{let u=X(l,4),d=X(l,0)&16777215,f=(d&1)!=0,p=(d&2)!=0,m=(d&8)!=0,h=0,g=(d&16)!=0,_=0,v=(d&32)!=0,y=8;u===a&&(f&&(y+=8),p&&(y+=4),m&&(h=X(l,y),y+=4),g&&(_=X(l,y),y+=4),v&&(y+=4),t.type===`video`&&(o=Lh(t.codec)),Z(s,[`trun`]).map(a=>{let s=a[0],l=X(a,0)&16777215,u=(l&1)!=0,d=0,f=(l&4)!=0,p=(l&256)!=0,m=0,g=(l&512)!=0,v=0,y=(l&1024)!=0,b=(l&2048)!=0,x=0,S=X(a,4),C=8;u&&(d=X(a,C),C+=4),f&&(C+=4);let w=d+c;for(let c=0;c>1&63;return e===39||e===40}else return(t&31)==6}function zh(e,t,n,r){let i=Bh(e),a=0;a+=t;let o=0,s=0,c=0;for(;a=i.length)break;c=i[a++],o+=c}while(c===255);s=0;do{if(a>=i.length)break;c=i[a++],s+=c}while(c===255);let e=i.length-a,t=a;if(se){qm.error(`Malformed SEI payload. ${s} is too small, only ${e} bytes left to parse.`);break}if(o===4){if(i[t++]===181){let e=_h(i,t);if(t+=2,e===49){let e=X(i,t);if(t+=4,e===1195456820){let e=i[t++];if(e===3){let a=i[t++],s=31&a,c=64&a,l=c?2+s*3:0,u=new Uint8Array(l);if(c){u[0]=a;for(let e=1;e16){let e=[];for(let n=0;n<16;n++){let r=i[t++].toString(16);e.push(r.length==1?`0`+r:r),(n===3||n===5||n===7||n===9)&&e.push(`-`)}let a=s-16,c=new Uint8Array(a);for(let e=0;e>24&255,a[1]=r>>16&255,a[2]=r>>8&255,a[3]=r&255,a.set(e,4),i=0,r=8;i0?(a=new Uint8Array(4),t.length>0&&new DataView(a.buffer).setUint32(0,t.length,!1)):a=new Uint8Array;let o=new Uint8Array(4);return n.byteLength>0&&new DataView(o.buffer).setUint32(0,n.byteLength,!1),Hh([112,115,115,104],new Uint8Array([r,0,0,0]),e,a,i,o,n)}function Wh(e){let t=[];if(e instanceof ArrayBuffer){let n=e.byteLength,r=0;for(;r+32>>24;if(i!==0&&i!==1)return{offset:n,size:t};let a=e.buffer,o=Qm(new Uint8Array(a,n+12,16)),s=null,c=null,l=0;if(i===0)l=28;else{let i=e.getUint32(28);if(!i||r<32+i*16)return{offset:n,size:t};s=[];for(let e=0;e/\(Windows.+Firefox\//i.test(navigator.userAgent),qh={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Jh(e,t){let n=qh[t];return!!n&&!!n[e.slice(0,4)]}function Yh(e,t,n=!0){return!e.split(`,`).some(e=>!Xh(e,t,n))}function Xh(e,t,n=!0){return Jm(n)?.isTypeSupported(Zh(e,t))??!1}function Zh(e,t){return`${t}/mp4;codecs=${e}`}function Qh(e){if(e){let t=e.substring(0,4);return qh.video[t]}return 2}function $h(e){let t=Kh();return e.split(`,`).reduce((e,n)=>{let r=t&&Lh(n)?9:qh.video[n];return r?(r*2+e)/(e?3:2):(qh.audio[n]+e)/(e?2:1)},0)}var eg={};function tg(e,t=!0){if(eg[e])return eg[e];let n={flac:[`flac`,`fLaC`,`FLAC`],opus:[`opus`,`Opus`],"mp4a.40.34":[`mp3`]}[e];for(let i=0;itg(e.toLowerCase(),t))}function ig(e,t){let n=[];if(e){let t=e.split(`,`);for(let e=0;e4||[`ac-3`,`ec-3`,`alac`,`fLaC`,`Opus`].indexOf(e)!==-1)&&(og(e,`audio`)||og(e,`video`)))return e;if(t){let n=t.split(`,`);if(n.length>1){if(e){for(let t=n.length;t--;)if(n[t].substring(0,4)===e.substring(0,4))return n[t]}return n[0]}}return t||e}function og(e,t){return Jh(e,t)&&Xh(e,t)}function sg(e){let t=e.split(`,`);for(let e=0;e2&&n[0]===`avc1`&&(t[e]=`avc1.${parseInt(n[1]).toString(16)}${(`000`+parseInt(n[2]).toString(16)).slice(-4)}`)}return t.join(`,`)}function cg(e){if(e.startsWith(`av01.`)){let t=e.split(`.`),n=[`0`,`111`,`01`,`01`,`01`,`0`];for(let e=t.length;e>4&&e<10;e++)t[e]=n[e-4];return t.join(`.`)}return e}function lg(e){let t=Jm(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported(`audio/mpeg`),mp3:t.isTypeSupported(`audio/mp4; codecs="mp3"`),ac3:t.isTypeSupported(`audio/mp4; codecs="ac-3"`)}}function ug(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,`$1`)}var dg={supported:!0,powerEfficient:!0,smooth:!0},fg={supported:!1,smooth:!1,powerEfficient:!1},pg={supported:!0,configurations:[],decodingInfoResults:[dg]};function mg(e,t){return{supported:!1,configurations:t,decodingInfoResults:[fg],error:e}}function hg(e,t,n,r,i,a){let o=e.videoCodec,s=e.audioCodec?e.audioGroups:null,c=a?.audioCodec,l=a?.channels,u=l?parseInt(l):c?1/0:2,d=null;if(s!=null&&s.length)try{d=s.length===1&&s[0]?t.groups[s[0]].channels:s.reduce((e,n)=>{if(n){let r=t.groups[n];if(!r)throw Error(`Audio track group ${n} not found`);Object.keys(r.channels).forEach(t=>{e[t]=(e[t]||0)+r.channels[t]})}return e},{2:0})}catch{return!0}return o!==void 0&&(o.split(`,`).some(e=>Lh(e))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(r,30)||e.videoRange!==`SDR`&&e.videoRange!==n||e.bitrate>Math.max(i,8e6))||!!d&&G(u)&&Object.keys(d).some(e=>parseInt(e)>u)}function gg(e,t,n,r={}){let i=e.videoCodec;if(!i&&!e.audioCodec||!n)return Promise.resolve(pg);let a=[],o=_g(e),s=o.length,c=vg(e,t,s>0),l=c.length;for(let e=s||1*l||1;e--;){let t={type:`media-source`};if(s&&(t.video=o[e%s]),l){t.audio=c[e%l];let n=t.audio.bitrate;t.video&&n&&(t.video.bitrate-=n)}a.push(t)}if(i){let e=navigator.userAgent;if(i.split(`,`).some(e=>Lh(e))&&Kh())return Promise.resolve(mg(Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),a))}return Promise.all(a.map(e=>{let t=xg(e);return r[t]||(r[t]=n.decodingInfo(e))})).then(e=>({supported:!e.some(e=>!e.supported),configurations:a,decodingInfoResults:e})).catch(e=>({supported:!1,configurations:a,decodingInfoResults:[],error:e}))}function _g(e){let t=e.videoCodec?.split(`,`),n=bg(e),r=e.width||640,i=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return t?t.map(e=>{let t={contentType:Zh(cg(e),`video`),width:r,height:i,bitrate:n,framerate:a};return o!==`sdr`&&(t.transferFunction=o),t}):[]}function vg(e,t,n){let r=e.audioCodec?.split(`,`),i=bg(e);return r&&e.audioGroups?e.audioGroups.reduce((e,a)=>{let o=a?t.groups[a]?.tracks:null;return o?o.reduce((e,t)=>{if(t.groupId===a){let a=parseFloat(t.channels||``);r.forEach(t=>{let r={contentType:Zh(t,`audio`),bitrate:n?yg(t,i):i};a&&(r.channels=``+a),e.push(r)})}return e},e):e},[]):[]}function yg(e,t){if(t<=1)return 1;let n=128e3;return e===`ec-3`?n=768e3:e===`ac-3`&&(n=64e4),Math.min(t/2,n)}function bg(e){return Math.ceil(Math.max(e.bitrate*.9,e.averageBitrate)/1e3)*1e3||1}function xg(e){let t=``,{audio:n,video:r}=e;if(r){let e=ug(r.contentType);t+=`${e}_r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||`sd`}_${Math.ceil(r.bitrate/1e5)}`}if(n){let e=ug(n.contentType);t+=`${r?`_`:``}${e}_c${n.channels}`}return t}var Sg=[`NONE`,`TYPE-0`,`TYPE-1`,null];function Cg(e){return Sg.indexOf(e)>-1}var wg=[`SDR`,`PQ`,`HLG`];function Tg(e){return!!e&&wg.indexOf(e)>-1}var Eg={No:``,Yes:`YES`,v2:`v2`};function Dg(e){let{canSkipUntil:t,canSkipDateRanges:n,age:r}=e,i=r!!e).map(e=>e.substring(0,4)).join(`,`),`supplemental`in e){this.supplemental=e.supplemental;let t=e.supplemental?.videoCodec;t&&t!==e.videoCodec&&(this.codecSet+=`,${t.substring(0,4)}`)}this.addGroupId(`audio`,e.attrs.AUDIO),this.addGroupId(`text`,e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||``}get pathwayId(){return this.attrs[`PATHWAY-ID`]||`.`}get videoRange(){return this.attrs[`VIDEO-RANGE`]||`SDR`}get score(){return this.attrs.optionalFloat(`SCORE`,0)}get uri(){return this.url[0]||``}hasAudioGroup(e){return Ag(this._audioGroups,e)}hasSubtitleGroup(e){return Ag(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e===`audio`){let e=this._audioGroups;e||=this._audioGroups=[],e.indexOf(t)===-1&&e.push(t)}else if(e===`text`){let e=this._subtitleGroups;e||=this._subtitleGroups=[],e.indexOf(t)===-1&&e.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){return this.audioGroups?.[0]}get textGroupId(){return this.subtitleGroups?.[0]}addFallback(){}};function Ag(e,t){return!t||!e?!1:e.indexOf(t)!==-1}function jg(){if(typeof matchMedia==`function`){let e=matchMedia(`(dynamic-range: high)`),t=matchMedia(`bad query`);if(e.media!==t.media)return e.matches===!0}return!1}function Mg(e,t){let n=!1,r=[];if(e&&(n=e!==`SDR`,r=[e]),t){r=t.allowedVideoRanges||wg.slice(0);let e=r.join(``)!==`SDR`&&!t.videoCodec;n=t.preferHDR===void 0?e&&jg():t.preferHDR,n||(r=[`SDR`])}return{preferHDR:n,allowedVideoRanges:r}}var Ng=e=>{let t=new WeakSet;return(n,r)=>{if(e&&(r=e(n,r)),typeof r==`object`&&r){if(t.has(r))return;t.add(r)}return r}},Pg=(e,t)=>JSON.stringify(e,Ng(t));function Fg(e,t,n,r,i){let a=Object.keys(e),o=r?.channels,s=r?.audioCodec,c=i?.videoCodec,l=o&&parseInt(o)===2,u=!1,d=!1,f=1/0,p=1/0,m=1/0,h=1/0,g=0,_=[],{preferHDR:v,allowedVideoRanges:y}=Mg(t,i);for(let t=a.length;t--;){let n=e[a[t]];u||=n.channels[2]>0,f=Math.min(f,n.minHeight),p=Math.min(p,n.minFramerate),m=Math.min(m,n.minBitrate),y.filter(e=>n.videoRanges[e]>0).length>0&&(d=!0)}f=G(f)?f:0,p=G(p)?p:0;let b=Math.max(1080,f),x=Math.max(30,p);m=G(m)?m:n,n=Math.max(m,n),d||(t=void 0);let S=a.length>1;return{codecSet:a.reduce((t,r)=>{let i=e[r];if(r===t)return t;if(_=d?y.filter(e=>i.videoRanges[e]>0):[],S){if(i.minBitrate>n)return Ig(r,`min bitrate of ${i.minBitrate} > current estimate of ${n}`),t;if(!i.hasDefaultAudio)return Ig(r,`no renditions with default or auto-select sound found`),t;if(s&&r.indexOf(s.substring(0,4))%5!=0)return Ig(r,`audio codec preference "${s}" not found`),t;if(o&&!l){if(!i.channels[o])return Ig(r,`no renditions with ${o} channel sound found (channels options: ${Object.keys(i.channels)})`),t}else if((!s||l)&&u&&i.channels[2]===0)return Ig(r,`no renditions with stereo sound found`),t;if(i.minHeight>b)return Ig(r,`min resolution of ${i.minHeight} > maximum of ${b}`),t;if(i.minFramerate>x)return Ig(r,`min framerate of ${i.minFramerate} > maximum of ${x}`),t;if(!_.some(e=>i.videoRanges[e]>0))return Ig(r,`no variants with VIDEO-RANGE of ${Pg(_)} found`),t;if(c&&r.indexOf(c.substring(0,4))%5!=0)return Ig(r,`video codec preference "${c}" not found`),t;if(i.maxScore=$h(t)||i.fragmentError>e[t].fragmentError)?t:(h=i.minIndex,g=i.maxScore,r)},void 0),videoRanges:_,preferHDR:v,minFramerate:p,minBitrate:m,minIndex:h}}function Ig(e,t){qm.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function Lg(e){return e.reduce((e,t)=>{let n=e.groups[t.groupId];n||=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1},n.tracks.push(t);let r=t.channels||`2`;return n.channels[r]=(n.channels[r]||0)+1,n.hasDefault=n.hasDefault||t.default,n.hasAutoSelect=n.hasAutoSelect||t.autoselect,n.hasDefault&&(e.hasDefaultAudio=!0),n.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Rg(e,t,n,r){return e.slice(n,r+1).reduce((e,n,r)=>{if(!n.codecSet)return e;let i=n.audioGroups,a=e[n.codecSet];a||(e[n.codecSet]=a={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),a.minBitrate=Math.min(a.minBitrate,n.bitrate);let o=Math.min(n.height,n.width);return a.minHeight=Math.min(a.minHeight,o),a.minFramerate=Math.min(a.minFramerate,n.frameRate),a.minIndex=Math.min(a.minIndex,r),a.maxScore=Math.max(a.maxScore,n.score),a.fragmentError+=n.fragmentError,a.videoRanges[n.videoRange]=(a.videoRanges[n.videoRange]||0)+1,i&&i.forEach(e=>{if(!e)return;let n=t.groups[e];n&&(a.hasDefaultAudio=a.hasDefaultAudio||t.hasDefaultAudio?n.hasDefault:n.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(n.channels).forEach(e=>{a.channels[e]=(a.channels[e]||0)+n.channels[e]}))}),e},{})}function zg(e){if(!e)return e;let{lang:t,assocLang:n,characteristics:r,channels:i,audioCodec:a}=e;return{lang:t,assocLang:n,characteristics:r,channels:i,audioCodec:a}}function Bg(e,t,n){if(`attrs`in e){let n=t.indexOf(e);if(n!==-1)return n}for(let r=0;rr.indexOf(e)===-1)}function Wg(e,t){let{audioCodec:n,channels:r}=e;return(n===void 0||(t.audioCodec||``).substring(0,4)===n.substring(0,4))&&(r===void 0||r===(t.channels||`2`))}function Gg(e,t,n,r,i){let a=t[r],o=t.reduce((e,t,n)=>{let r=t.uri;return(e[r]||(e[r]=[])).push(n),e},{})[a.uri];o.length>1&&(r=Math.max.apply(Math,o));let s=a.videoRange,c=a.frameRate,l=a.codecSet.substring(0,4),u=Kg(t,r,t=>{if(t.videoRange!==s||t.frameRate!==c||t.codecSet.substring(0,4)!==l)return!1;let r=t.audioGroups;return Bg(e,n.filter(e=>!r||r.indexOf(e.groupId)!==-1),i)>-1});return u>-1?u:Kg(t,r,t=>{let r=t.audioGroups;return Bg(e,n.filter(e=>!r||r.indexOf(e.groupId)!==-1),i)>-1})}function Kg(e,t,n){for(let r=t;r>-1;r--)if(n(e[r]))return r;for(let r=t+1;r{let{fragCurrent:t,partCurrent:n,hls:r}=this,{autoLevelEnabled:i,media:a}=r;if(!t||!a)return;let o=performance.now(),s=n?n.stats:t.stats,c=n?n.duration:t.duration,l=o-s.loading.start,u=r.minAutoLevel,d=t.level,f=this._nextAutoLevel;if(s.aborted||s.loaded&&s.loaded===s.total||d<=u){this.clearTimer(),this._nextAutoLevel=-1;return}if(!i)return;let p=f>-1&&f!==d,m=!!e||p;if(!m&&(a.paused||!a.playbackRate||!a.readyState))return;let h=r.mainForwardBufferInfo;if(!m&&h===null)return;let g=this.bwEstimator.getEstimateTTFB(),_=Math.abs(a.playbackRate);if(l<=Math.max(g,1e3*(c/(_*2))))return;let v=h?h.len/_:0,y=s.loading.first?s.loading.first-s.loading.start:-1,b=s.loaded&&y>-1,x=this.getBwEstimate(),S=r.levels,C=S[d],w=Math.max(s.loaded,Math.round(c*(t.bitrate||C.averageBitrate)/8)),T=b?l-y:l;T<1&&b&&(T=Math.min(l,s.loaded*8/x));let E=b?s.loaded*1e3/T:0,D=g/1e3,O=E?(w-s.loaded)/E:w*8/x+D;if(O<=v)return;let k=E?E*8:x,A=(e?.details||this.hls.latestLevelDetails)?.live===!0,j=this.hls.config.abrBandWidthUpFactor,M=1/0,N;for(N=d-1;N>u;N--){let e=S[N].maxBitrate,t=!S[N].details||A;if(M=this.getTimeToLoadFrag(D,k,c*e,t),M=O||M>c*10)return;b?this.bwEstimator.sample(l-Math.min(g,y),s.loaded):this.bwEstimator.sampleTTFB(l);let ee=S[N].maxBitrate;this.getBwEstimate()*j>ee&&this.resetEstimator(ee);let P=this.findBestLevel(ee,u,N,0,v,1,1);P>-1&&(N=P),this.warn(`Fragment ${t.sn}${n?` part `+n.index:``} of level ${d} is loading too slowly; Fragment duration: ${t.duration.toFixed(3)} Time to underbuffer: ${v.toFixed(3)} s Estimated load time for current fragment: ${O.toFixed(3)} s Estimated load time for down switch fragment: ${M.toFixed(3)} s TTFB estimate: ${y|0} ms Current BW estimate: ${G(x)?x|0:`Unknown`} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${N} @ ${ee|0} bps`),r.nextLoadLevel=r.nextAutoLevel=N,this.clearTimer();let te=()=>{if(this.clearTimer(),this.fragCurrent===t&&this.hls.loadLevel===N&&N>0){let e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${N>0?`and switching down`:``} Fragment duration: ${t.duration.toFixed(3)} s Time to underbuffer: ${e.toFixed(3)} s`),t.abortRequests(),this.fragCurrent=this.partCurrent=null,N>u){let t=this.findBestLevel(this.hls.levels[u].bitrate,u,N,0,e,1,1);t===-1&&(t=u),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}};p||O>M*2?te():this.timer=self.setInterval(te,M*1e3),r.trigger(J.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:n,stats:s})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){let e=this.hls.config;return new Mm(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let{hls:e}=this;e.on(J.MANIFEST_LOADING,this.onManifestLoading,this),e.on(J.FRAG_LOADING,this.onFragLoading,this),e.on(J.FRAG_LOADED,this.onFragLoaded,this),e.on(J.FRAG_BUFFERED,this.onFragBuffered,this),e.on(J.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(J.LEVEL_LOADED,this.onLevelLoaded,this),e.on(J.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(J.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(J.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e&&(e.off(J.MANIFEST_LOADING,this.onManifestLoading,this),e.off(J.FRAG_LOADING,this.onFragLoading,this),e.off(J.FRAG_LOADED,this.onFragLoaded,this),e.off(J.FRAG_BUFFERED,this.onFragBuffered,this),e.off(J.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(J.LEVEL_LOADED,this.onLevelLoaded,this),e.off(J.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(J.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(J.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=``}onFragLoading(e,t){let n=t.frag;this.ignoreFragment(n)||(n.bitrateTest||(this.fragCurrent=n,this.partCurrent=t.part??null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case q.BUFFER_ADD_CODEC_ERROR:case q.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case q.FRAG_LOAD_TIMEOUT:{let e=t.frag,{fragCurrent:n,partCurrent:r}=this;if(e&&n&&e.sn===n.sn&&e.level===n.level){let t=performance.now(),n=r?r.stats:e.stats,i=t-n.loading.start,a=n.loading.first?n.loading.first-n.loading.start:-1;if(n.loaded&&a>-1){let e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(i-Math.min(e,a),n.loaded)}else this.bwEstimator.sampleTTFB(i)}break}}}getTimeToLoadFrag(e,t,n,r){return e+n/t+(r?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){let n=this.hls.config,{loading:r}=t.stats,i=r.end-r.first;G(i)&&(this.lastLevelLoadSec=i/1e3),t.details.live?this.bwEstimator.update(n.abrEwmaSlowLive,n.abrEwmaFastLive):this.bwEstimator.update(n.abrEwmaSlowVoD,n.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:n}){let r=n?n.stats:t.stats;if(t.type===Y.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){let e=n?n.duration:t.duration,i=this.hls.levels[t.level],a=(i.loaded?i.loaded.bytes:0)+r.loaded,o=(i.loaded?i.loaded.duration:0)+e;i.loaded={bytes:a,duration:o},i.realBitrate=Math.round(8*a/o)}if(t.bitrateTest){let e={stats:r,frag:t,part:n,id:t.type};this.onFragBuffered(J.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){let{frag:n,part:r}=t,i=r!=null&&r.stats.loaded?r.stats:n.stats;if(i.aborted||this.ignoreFragment(n))return;let a=i.parsing.end-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,i.loaded),i.bwEstimate=this.getBwEstimate(),n.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Y.MAIN||e.sn===`initSegment`}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){let{maxAutoLevel:e,minAutoLevel:t}=this.hls,n=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,i=this.findBestLevel(n,t,e,0,r,1,1);if(i>-1)return i;let a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){let e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),n=this.lastLoadedFragLevel>-1;if(e!==-1&&(!t||!n||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let r=t&&n?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){let t=this.hls.levels;if(t.length>Math.max(e,r)&&t[e].loadError<=t[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:n}=this;if(n.levels.length<=1)return n.loadLevel;let{maxAutoLevel:r,config:i,minAutoLevel:a}=n,o=t?t.duration:e?e.duration:0,s=this.getBwEstimate(),c=this.getStarvationDelay(),l=i.abrBandWidthFactor,u=i.abrBandWidthUpFactor;if(c){let e=this.findBestLevel(s,a,r,c,0,l,u);if(e>=0)return this.rebufferNotice=-1,e}let d=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay;if(!c){let e=this.bitrateTestDelay;e&&(d=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),l=u=1)}let f=this.findBestLevel(s,a,r,c,d,l,u);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${c?`rebuffering expected`:`buffer is empty`}, optimal quality level ${f}`)),f>-1)return f;let p=n.levels[a],m=n.loadLevelObj;return m&&p?.bitrate=t;s--){var A;let t=p[s],d=s>u;if(!t)continue;if(g.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){let n=navigator.mediaCapabilities;typeof n?.decodingInfo==`function`&&hg(t,T,x,S,e,C)?(t.supportedPromise=gg(t,T,n,this.supportedCache),t.supportedPromise.then(e=>{if(!this.hls)return;t.supportedResult=e;let n=this.hls.levels,r=n.indexOf(t);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${r} ${Pg(e)}`):e.supported?e.decodingInfoResults.some(e=>e.smooth===!1||e.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${r} not smooth or powerEfficient: ${Pg(e)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${r} ${Pg(e)}`),r>-1&&n.length>1&&(this.log(`Removing unsupported level ${r}`),this.hls.removeLevel(r),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(e=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${e}`)})):t.supportedResult=pg}if((b&&t.codecSet!==b||x&&t.videoRange!==x||d&&S>t.frameRate||!d&&S>0&&Se.smooth===!1))&&(!y||s!==E)){k.push(s);continue}let m=t.details,_=(f?m?.partTarget:m?.averagetargetduration)||D,w;w=d?o*e:a*e;let j=D&&r>=D*2&&i===0?t.averageBitrate:t.maxBitrate,M=this.getTimeToLoadFrag(O,w,j*_,m===void 0);if(w>=j&&(s===l||t.loadError===0&&t.fragmentError===0)&&(M<=O||!G(M)||v&&!this.bitrateTestDelay||M${s} adjustedbw(${Math.round(w)})-bitrate=${Math.round(w-j)} ttfb:${O.toFixed(1)} avgDuration:${_.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${M.toFixed(1)} firstSelection:${y} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${h}`)),y&&(this.firstSelection=s),s}}return-1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey=``,this._nextAutoLevel=t)}deriveNextAutoLevel(e){let{maxAutoLevel:t,minAutoLevel:n}=this.hls;return Math.min(Math.max(e,n),t)}},Yg={search:function(e,t){let n=0,r=e.length-1,i=null,a=null;for(;n<=r;){i=(n+r)/2|0,a=e[i];let o=t(a);if(o>0)n=i+1;else if(o<0)r=i-1;else return a}return null}};function Xg(e,t,n){if(t===null||!Array.isArray(e)||!e.length||!G(t)||t<(e[0].programDateTime||0)||t>=(e[e.length-1].endProgramDateTime||0))return null;for(let r=0;r0&&r<15e-7&&(n+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else n===0&&t[0].start===0&&(a=t[0]);if(a&&((!e||e.level===a.level)&&$g(n,r,a)===0||Qg(a,e,Math.min(i,r))))return a;let o=Yg.search(t,$g.bind(null,n,r));return o&&(o!==e||!a)?o:a}function Qg(e,t,n){if(t&&t.start===0&&t.level0){let r=t.tagList.reduce((e,t)=>(t[0]===`INF`&&(e+=parseFloat(t[1])),e),n);return e.start<=r}return!1}function $g(e=0,t=0,n){if(n.start<=e&&n.start+n.duration>e)return 0;let r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0));return n.start+n.duration-r<=e?1:n.start-r>e&&n.start?-1:0}function e_(e,t,n){let r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0))*1e3;return(n.endProgramDateTime||0)-r>e}function t_(e,t,n){if(e&&e.startCC<=t&&e.endCC>=t){let r=e.fragments,{fragmentHint:i}=e;i&&(r=r.concat(i));let a;return Yg.search(r,e=>e.cct?-1:(a=e,e.end<=n?1:e.start>n?-1:0)),a||null}return null}function n_(e){switch(e.details){case q.FRAG_LOAD_TIMEOUT:case q.KEY_LOAD_TIMEOUT:case q.LEVEL_LOAD_TIMEOUT:case q.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function r_(e){return e.details.startsWith(`key`)}function i_(e){return r_(e)&&!!e.frag&&!e.frag.decryptdata}function a_(e,t){let n=n_(t);return e.default[`${n?`timeout`:`error`}Retry`]}function o_(e,t){let n=e.backoff===`linear`?1:2**t;return Math.min(n*e.retryDelayMs,e.maxRetryDelayMs)}function s_(e){return Im(Im({},e),{errorRetry:null,timeoutRetry:null})}function c_(e,t,n,r){if(!e)return!1;let i=r?.code,a=t499)}function u_(e){return e===0&&navigator.onLine===!1}var d_={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},f_={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8},p_=class extends zm{constructor(e){super(`error-controller`,e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(J.ERROR,this.onError,this),e.on(J.MANIFEST_LOADING,this.onManifestLoading,this),e.on(J.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(J.ERROR,this.onError,this),e.off(J.ERROR,this.onErrorOut,this),e.off(J.MANIFEST_LOADING,this.onManifestLoading,this),e.off(J.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===Y.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,n=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||n===-1?t.loadLevel:n}variantHasKey(e,t){if(e){var n;if((n=e.details)!=null&&n.hasKey(t))return!0;let r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter(e=>r.indexOf(e.groupId)>=0).some(e=>e.details?.hasKey(t))}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var n;if(t.fatal)return;let r=this.hls,i=t.context;switch(t.details){case q.FRAG_LOAD_ERROR:case q.FRAG_LOAD_TIMEOUT:case q.KEY_LOAD_ERROR:case q.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case q.FRAG_PARSING_ERROR:if((n=t.frag)!=null&&n.gap){t.errorAction=m_();return}case q.FRAG_GAP:case q.FRAG_DECRYPT_ERROR:t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=d_.SendAlternateToPenaltyBox;return;case q.LEVEL_EMPTY_ERROR:case q.LEVEL_PARSING_ERROR:{var a;let e=t.parent===Y.MAIN?t.level:r.loadLevel;t.details===q.LEVEL_EMPTY_ERROR&&(a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case q.LEVEL_LOAD_ERROR:case q.LEVEL_LOAD_TIMEOUT:typeof i?.level==`number`&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level));return;case q.AUDIO_TRACK_LOAD_ERROR:case q.AUDIO_TRACK_LOAD_TIMEOUT:case q.SUBTITLE_LOAD_ERROR:case q.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){let e=r.loadLevelObj;if(e&&(i.type===Am.AUDIO_TRACK&&e.hasAudioGroup(i.groupId)||i.type===Am.SUBTITLE_TRACK&&e.hasSubtitleGroup(i.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=d_.SendAlternateToPenaltyBox,t.errorAction.flags=f_.MoveAllAlternatesMatchingHost;return}}return;case q.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:d_.SendAlternateToPenaltyBox,flags:f_.MoveAllAlternatesMatchingHDCP};return;case q.KEY_SYSTEM_SESSION_UPDATE_FAILED:case q.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case q.KEY_SYSTEM_NO_SESSION:t.errorAction={action:d_.SendAlternateToPenaltyBox,flags:f_.MoveAllAlternatesMatchingKey};return;case q.BUFFER_ADD_CODEC_ERROR:case q.REMUX_ALLOC_ERROR:case q.BUFFER_APPEND_ERROR:t.errorAction||=this.getLevelSwitchAction(t,t.level??r.loadLevel);return;case q.INTERNAL_EXCEPTION:case q.BUFFER_APPENDING_ERROR:case q.BUFFER_FULL_ERROR:case q.LEVEL_SWITCH_ERROR:case q.BUFFER_STALLED_ERROR:case q.BUFFER_SEEK_OVER_HOLE:case q.BUFFER_NUDGE_ON_STALL:t.errorAction=m_();return}t.type===K.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=m_())}getPlaylistRetryOrSwitchAction(e,t){let n=this.hls,r=a_(n.config.playlistLoadPolicy,e),i=this.playlistError++;if(c_(r,i,n_(e),e.response))return{action:d_.RetryRequest,flags:f_.None,retryConfig:r,retryCount:i};let a=this.getLevelSwitchAction(e,t);return r&&(a.retryConfig=r,a.retryCount=i),a}getFragRetryOrSwitchAction(e){let t=this.hls,n=this.getVariantLevelIndex(e.frag),r=t.levels[n],{fragLoadPolicy:i,keyLoadPolicy:a}=t.config,o=a_(r_(e)?a:i,e),s=t.levels.reduce((e,t)=>e+t.fragmentError,0);if(r&&(e.details!==q.FRAG_GAP&&r.fragmentError++,!i_(e)&&c_(o,s,n_(e),e.response)))return{action:d_.RetryRequest,flags:f_.None,retryConfig:o,retryCount:s};let c=this.getLevelSwitchAction(e,n);return o&&(c.retryConfig=o,c.retryCount=s),c}getLevelSwitchAction(e,t){let n=this.hls;t??=n.loadLevel;let r=this.hls.levels[t];if(r){let t=e.details;r.loadError++,t===q.BUFFER_APPEND_ERROR&&r.fragmentError++;let o=-1,{levels:s,loadLevel:c,minAutoLevel:l,maxAutoLevel:u}=n;!n.autoLevelEnabled&&!n.config.preserveManualLevelOnError&&(n.loadLevel=-1);let d=e.frag?.type,f=(d===Y.AUDIO&&t===q.FRAG_PARSING_ERROR||e.sourceBufferName===`audio`&&(t===q.BUFFER_ADD_CODEC_ERROR||t===q.BUFFER_APPEND_ERROR))&&s.some(({audioCodec:e})=>r.audioCodec!==e),p=e.sourceBufferName===`video`&&(t===q.BUFFER_ADD_CODEC_ERROR||t===q.BUFFER_APPEND_ERROR)&&s.some(({codecSet:e,audioCodec:t})=>r.codecSet!==e&&r.audioCodec===t),{type:m,groupId:h}=e.context??{};for(let n=s.length;n--;){let g=(n+c)%s.length;if(g!==c&&g>=l&&g<=u&&s[g].loadError===0){var i,a;let n=s[g];if(t===q.FRAG_GAP&&d===Y.MAIN&&e.frag){let t=s[g].details;if(t){let n=Zg(e.frag,t.fragments,e.frag.start);if(n!=null&&n.gap)continue}}else if(m===Am.AUDIO_TRACK&&n.hasAudioGroup(h)||m===Am.SUBTITLE_TRACK&&n.hasSubtitleGroup(h))continue;else if(d===Y.AUDIO&&(i=r.audioGroups)!=null&&i.some(e=>n.hasAudioGroup(e))||d===Y.SUBTITLE&&(a=r.subtitleGroups)!=null&&a.some(e=>n.hasSubtitleGroup(e))||f&&r.audioCodec===n.audioCodec||p&&r.codecSet===n.codecSet||!f&&r.codecSet!==n.codecSet)continue;o=g;break}}if(o>-1&&n.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:d_.SendAlternateToPenaltyBox,flags:f_.None,nextAutoLevel:o}}return{action:d_.SendAlternateToPenaltyBox,flags:f_.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){switch(t.errorAction?.action){case d_.DoNothing:break;case d_.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==q.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break;case d_.RetryRequest:break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,n=e.errorAction;if(!n)return;let{flags:r}=n,i=n.nextAutoLevel;switch(r){case f_.None:this.switchLevel(e,i);break;case f_.MoveAllAlternatesMatchingHDCP:{let r=this.getVariantLevelIndex(e.frag),i=t.levels[r]?.attrs[`HDCP-LEVEL`];if(n.hdcpLevel=i,i===`NONE`)this.warn(`HDCP policy resticted output with HDCP-LEVEL=NONE`);else if(i){t.maxHdcpLevel=Sg[Sg.indexOf(i)-1],n.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case f_.MoveAllAlternatesMatchingKey:{let t=e.decryptdata;if(t){let r=this.hls.levels,i=r.length;for(let n=i;n--;)this.variantHasKey(r[n],t)&&(this.log(`Banned key found in level ${n} (${r[n].bitrate}bps) or audio group "${r[n].audioGroups?.join(`,`)}" (${e.frag?.type} fragment) ${Qm(t.keyId||[])}`),r[n].fragmentError++,r[n].loadError++,this.log(`Removing level ${n} with key error (${e.error})`),this.hls.removeLevel(n));let a=e.frag;if(this.hls.levels.length{let o=this.fragments[r];if(!o||a>=o.body.sn)return;if(!o.buffered&&(!o.loaded||i)){o.body.type===n&&this.removeFragment(o.body);return}let s=o.range[e];if(s){if(s.time.length===0){this.removeFragment(o.body);return}s.time.some(e=>{let n=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return n&&this.removeFragment(o.body),n})}})}detectPartialFragments(e){let t=this.timeRanges;if(!t||e.frag.sn===`initSegment`)return;let n=e.frag,r=v_(n),i=this.fragments[r];if(!i||i.buffered&&n.gap)return;let a=!n.relurl;Object.keys(t).forEach(r=>{let o=n.elementaryStreams[r];if(!o)return;let s=t[r],c=a||o.partial===!0;i.range[r]=this.getBufferedTimes(n,e.part,c,s)}),i.loaded=null,Object.keys(i.range).length?(this.bufferedEnd(i,n),__(i)||this.removeParts(n.sn-1,n.type)):this.removeFragment(i.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){let n=this.activePartLists[t];n&&(this.activePartLists[t]=y_(n,t=>t.fragment.sn>=e))}fragBuffered(e,t){let n=v_(e),r=this.fragments[n];!r&&t&&(r=this.fragments[n]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,this.bufferedEnd(r,e))}getBufferedTimes(e,t,n,r){let i={time:[],partial:n},a=e.start,o=e.end,s=e.minEndPTS||o,c=e.maxStartPTS||a;for(let e=0;e=t&&s<=n){i.time.push({startPTS:Math.max(a,r.start(e)),endPTS:Math.min(o,r.end(e))});break}else if(at){let t=Math.max(a,r.start(e)),n=Math.min(o,r.end(e));n>t&&(i.partial=!0,i.time.push({startPTS:t,endPTS:n}))}else if(o<=t)break}return i}getPartialFragment(e){let t=null,n,r,i,a=0,{bufferPadding:o,fragments:s}=this;return Object.keys(s).forEach(c=>{let l=s[c];l&&__(l)&&(r=l.body.start-o,i=l.body.end+o,e>=r&&e<=i&&(n=Math.min(e-r,i-e),a<=n&&(t=l.body,a=n)))}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||__(t))}getState(e){let t=v_(e),n=this.fragments[t];return n?n.buffered?__(n)?h_.PARTIAL:h_.OK:h_.APPENDING:h_.NOT_LOADED}isTimeBuffered(e,t,n){let r,i;for(let a=0;a=r&&t<=i)return!0;if(t<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn===`initSegment`||t.frag.bitrateTest)return;let n=t.frag,r=t.part?null:t,i=v_(n);this.fragments[i]={body:n,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:n,part:r,timeRanges:i,type:a}=t;if(n.sn===`initSegment`)return;let o=n.type;if(r){let e=this.activePartLists[o];e||(this.activePartLists[o]=e=[]),e.push(r)}this.timeRanges=i;let s=i[a];this.detectEvictedFragments(a,s,o,r)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=v_(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,n=Object.keys(t);if(!e)return n.length>0;for(let r=n.length;r--;)if(t[n[r]]?.body.type===e)return!0;return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,n,r,i){r&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o)return;let s=o.body;s.type!==n||r&&!s.gap||s.starte&&(o.buffered||i)&&this.removeFragment(s)})}removeFragment(e){let t=v_(e);e.clearElementaryStreamInfo();let n=this.activePartLists[e.type];if(n){let t=e.sn;this.activePartLists[e.type]=y_(n,e=>e.fragment.sn!==t)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;let t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(e=>e.clearElementaryStreamInfo())}};function __(e){var t,n,r;return e.buffered&&!!(e.body.gap||(t=e.range.video)!=null&&t.partial||(n=e.range.audio)!=null&&n.partial||(r=e.range.audiovideo)!=null&&r.partial)}function v_(e){return`${e.type}_${e.level}_${e.sn}`}function y_(e,t){return e.filter(e=>{let n=t(e);return n||e.clearElementaryStreamInfo(),n})}var b_={cbc:0,ctr:1},x_=class{constructor(e,t,n){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=n}decrypt(e,t){switch(this.aesMode){case b_.cbc:return this.subtle.decrypt({name:`AES-CBC`,iv:this.aesIV},t,e);case b_.ctr:return this.subtle.decrypt({name:`AES-CTR`,counter:this.aesIV,length:64},t,e);default:throw Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}};function S_(e){let t=e.byteLength,n=t&&new DataView(e.buffer).getUint8(t-1);return n?e.slice(0,t-n):e}var C_=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array,this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){let t=new DataView(e),n=new Uint32Array(4);for(let e=0;e<4;e++)n[e]=t.getUint32(e*4);return n}initTable(){let e=this.sBox,t=this.invSBox,n=this.subMix,r=n[0],i=n[1],a=n[2],o=n[3],s=this.invSubMix,c=s[0],l=s[1],u=s[2],d=s[3],f=new Uint32Array(256),p=0,m=0,h=0;for(h=0;h<256;h++)h<128?f[h]=h<<1:f[h]=h<<1^283;for(h=0;h<256;h++){let n=m^m<<1^m<<2^m<<3^m<<4;n=n>>>8^n&255^99,e[p]=n,t[n]=p;let s=f[p],h=f[s],g=f[h],_=f[n]*257^n*16843008;r[p]=_<<24|_>>>8,i[p]=_<<16|_>>>16,a[p]=_<<8|_>>>24,o[p]=_,_=g*16843009^h*65537^s*257^p*16843008,c[n]=_<<24|_>>>8,l[n]=_<<16|_>>>16,u[n]=_<<8|_>>>24,d[n]=_,p?(p=s^f[f[f[g^s]]],m^=f[f[m]]):p=m=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),n=!0,r=0;for(;r>>24,v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[v&255],v^=d[o/i|0]<<24):i>6&&o%i===4&&(v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[v&255]),c[o]=_=(c[o-i]^v)>>>0}for(s=0;s>>24]]^m[u[v>>>16&255]]^h[u[v>>>8&255]]^g[u[v&255]],l[s]=l[s]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,n){let r=this.keySize+6,i=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,s=o[0],c=o[1],l=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(n),f=d[0],p=d[1],m=d[2],h=d[3],g=new Int32Array(e),_=new Int32Array(g.length),v,y,b,x,S,C,w,T,E,D,O,k,A,j,M=this.networkToHostOrderSwap;for(;t>>24]^c[C>>16&255]^l[w>>8&255]^u[T&255]^i[A],y=s[C>>>24]^c[w>>16&255]^l[T>>8&255]^u[S&255]^i[A+1],b=s[w>>>24]^c[T>>16&255]^l[S>>8&255]^u[C&255]^i[A+2],x=s[T>>>24]^c[S>>16&255]^l[C>>8&255]^u[w&255]^i[A+3],S=v,C=y,w=b,T=x,A+=4;v=a[S>>>24]<<24^a[C>>16&255]<<16^a[w>>8&255]<<8^a[T&255]^i[A],y=a[C>>>24]<<24^a[w>>16&255]<<16^a[T>>8&255]<<8^a[S&255]^i[A+1],b=a[w>>>24]<<24^a[T>>16&255]<<16^a[S>>8&255]<<8^a[C&255]^i[A+2],x=a[T>>>24]<<24^a[S>>16&255]<<16^a[C>>8&255]<<8^a[w&255]^i[A+3],_[t]=M(v^f),_[t+1]=M(x^p),_[t+2]=M(b^m),_[t+3]=M(y^h),f=E,p=D,m=O,h=k,t+=4}return _.buffer}},w_=class{constructor(e,t,n){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=n}expandKey(){let e=T_(this.aesMode);return this.subtle.importKey(`raw`,this.key,{name:e},!1,[`encrypt`,`decrypt`])}};function T_(e){switch(e){case b_.cbc:return`AES-CBC`;case b_.ctr:return`AES-CTR`;default:throw Error(`[FastAESKey] invalid aes mode ${e}`)}}var E_=16,D_=class{constructor(e,{removePKCS7Padding:t=!0}={}){if(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.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{let e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){let{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;let n=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?S_(n):n}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&=null}decrypt(e,t,n,r){return this.useSoftware?new Promise((i,a)=>{let o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,n,r);let s=this.flush();s?i(s.buffer):a(Error(`[softwareDecrypt] Failed to decrypt data`))}):this.webCryptoDecrypt(new Uint8Array(e),t,n,r)}softwareDecrypt(e,t,n,r){let{currentIV:i,currentResult:a,remainderData:o}=this;if(r!==b_.cbc||t.byteLength!==16)return qm.warn(`SoftwareDecrypt: can only handle AES-128-CBC`),null;this.logOnce(`JS AES decrypt`),o&&(e=Fh(o,e),this.remainderData=null);let s=this.getValidChunk(e);if(!s.length)return null;i&&(n=i);let c=this.softwareDecrypter;c||=this.softwareDecrypter=new C_,c.expandKey(t);let l=a;return this.currentResult=c.decrypt(s.buffer,0,n),this.currentIV=s.slice(-16).buffer,l||null}webCryptoDecrypt(e,t,n,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,n,r));this.key=t,this.fastAesKey=new w_(this.subtle,t,r)}return this.fastAesKey.expandKey().then(t=>this.subtle?(this.logOnce(`WebCrypto AES decrypt`),new x_(this.subtle,new Uint8Array(n),r).decrypt(e.buffer,t)):Promise.reject(Error(`web crypto not initialized`))).catch(i=>(qm.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(e,t,n,r)))}onWebCryptoError(e,t,n,r){let i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,n,r);let i=this.flush();if(i)return i.buffer}throw Error(`WebCrypto`+(i?` and softwareDecrypt`:``)+`: failed to decrypt data`)}getValidChunk(e){let t=e,n=e.length-e.length%E_;return n!==e.length&&(t=e.slice(0,n),this.remainderData=e.slice(n)),t}logOnce(e){this.logEnabled&&=(qm.log(`[decrypter]: ${e}`),!1)}},O_=2**17,k_=class{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&=(this.loader.destroy(),null)}abort(){this.loader&&this.loader.abort()}load(e,t){let n=e.url;if(!n)return Promise.reject(new N_({type:K.NETWORK_ERROR,details:q.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:Error(`Fragment does not have a ${n?`part list`:`url`}`),networkDetails:null}));this.abort();let r=this.config,i=r.fLoader,a=r.loader;return new Promise((o,s)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(e=>e[0]===`GAP`)){s(j_(e));return}else e.gap=!1;let c=this.loader=i?new i(r):new a(r),l=A_(e);e.loader=c;let u=s_(r.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn===`initSegment`?1/0:O_};e.stats=c.stats;let f={onSuccess:(t,n,r,i)=>{this.resetLoader(e,c);let a=t.data;r.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(a.slice(0,16)),a=a.slice(16)),o({frag:e,part:null,payload:a,networkDetails:i})},onError:(t,r,i,a)=>{this.resetLoader(e,c),s(new N_({type:K.NETWORK_ERROR,details:q.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Im({url:n,data:void 0},t),error:Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:i,stats:a}))},onAbort:(t,n,r)=>{this.resetLoader(e,c),s(new N_({type:K.NETWORK_ERROR,details:q.INTERNAL_ABORTED,fatal:!1,frag:e,error:Error(`Aborted`),networkDetails:r,stats:t}))},onTimeout:(t,n,r)=>{this.resetLoader(e,c),s(new N_({type:K.NETWORK_ERROR,details:q.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:Error(`Timeout after ${d.timeout}ms`),networkDetails:r,stats:t}))}};t&&(f.onProgress=(n,r,i,a)=>t({frag:e,part:null,payload:i,networkDetails:a})),c.load(l,d,f)})}loadPart(e,t,n){this.abort();let r=this.config,i=r.fLoader,a=r.loader;return new Promise((o,s)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){s(j_(e,t));return}let c=this.loader=i?new i(r):new a(r),l=A_(e,t);e.loader=c;let u=s_(r.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:O_};t.stats=c.stats,c.load(l,d,{onSuccess:(r,i,a,s)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);let l={frag:e,part:t,payload:r.data,networkDetails:s};n(l),o(l)},onError:(n,r,i,a)=>{this.resetLoader(e,c),s(new N_({type:K.NETWORK_ERROR,details:q.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Im({url:l.url,data:void 0},n),error:Error(`HTTP Error ${n.code} ${n.text}`),networkDetails:i,stats:a}))},onAbort:(n,r,i)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),s(new N_({type:K.NETWORK_ERROR,details:q.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:Error(`Aborted`),networkDetails:i,stats:n}))},onTimeout:(n,r,i)=>{this.resetLoader(e,c),s(new N_({type:K.NETWORK_ERROR,details:q.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:Error(`Timeout after ${d.timeout}ms`),networkDetails:i,stats:n}))}})})}updateStatsFromPart(e,t){let n=e.stats,r=t.stats,i=r.total;if(n.loaded+=r.loaded,i){let r=Math.round(e.duration/t.duration),a=Math.min(Math.round(n.loaded/i),r),o=(r-a)*Math.round(n.loaded/a);n.total=n.loaded+o}else n.total=Math.max(n.loaded,n.total);let a=n.loading,o=r.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}};function A_(e,t=null){let n=t||e,r={frag:e,part:t,responseType:`arraybuffer`,url:n.url,headers:{},rangeStart:0,rangeEnd:0},i=n.byteRangeStartOffset,a=n.byteRangeEndOffset;if(G(i)&&G(a)){let t=i,n=a;if(e.sn===`initSegment`&&M_(e.decryptdata?.method)){let e=a-i;e%16&&(n=a+(16-e%16)),i!==0&&(r.resetIV=!0,t=i-16)}r.rangeStart=t,r.rangeEnd=n}return r}function j_(e,t){let n=Error(`GAP ${e.gap?`tag`:`attribute`} found`),r={type:K.MEDIA_ERROR,details:q.FRAG_GAP,fatal:!1,frag:e,error:n,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new N_(r)}function M_(e){return e===`AES-128`||e===`AES-256`}var N_=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},P_=class extends zm{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},F_=class{constructor(e,t,n,r=0,i=-1,a=!1){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=I_(),this.buffering={audio:I_(),video:I_(),audiovideo:I_()},this.level=e,this.sn=t,this.id=n,this.size=r,this.part=i,this.partial=a}};function I_(){return{start:0,executeStart:0,executeEnd:0,end:0}}var L_={length:0,start:()=>0,end:()=>0},Q=class e{static isBuffered(t,n){if(t){let r=e.getBuffered(t);for(let e=r.length;e--;)if(n>=r.start(e)&&n<=r.end(e))return!0}return!1}static bufferedRanges(t){if(t){let n=e.getBuffered(t);return e.timeRangesToArray(n)}return[]}static timeRangesToArray(e){let t=[];for(let n=0;n1&&e.sort((e,t)=>e.start-t.start||t.end-e.end);let r=-1,i=[];if(n)for(let a=0;a=e[a].start&&t<=e[a].end&&(r=a);let o=i.length;if(o){let t=i[o-1].end;e[a].start-tt&&(i[o-1].end=e[a].end):i.push(e[a])}else i.push(e[a])}else i=e;let a=0,o,s=t,c=t;for(let e=0;e=l&&t<=u&&(r=e),t+n>=l&&t{let r=t.substring(2,t.length-1),i=n?.[r];return i===void 0?(e.playlistParsingError||=Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`),t):i})}return t}function V_(e,t,n){let r=e.variableList;r||(e.variableList=r={});let i,a;if(`QUERYPARAM`in t){i=t.QUERYPARAM;try{let e=new self.URL(n).searchParams;if(e.has(i))a=e.get(i);else throw Error(`"${i}" does not match any query parameter in URI: "${n}"`)}catch(t){e.playlistParsingError||=Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`)}}else i=t.NAME,a=t.VALUE;i in r?e.playlistParsingError||=Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`):r[i]=a||``}function H_(e,t,n){let r=t.IMPORT;if(n&&r in n){let t=e.variableList;t||(e.variableList=t={}),t[r]=n[r]}else e.playlistParsingError||=Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`)}var U_=/^(\d+)x(\d+)$/,W_=/(.+?)=(".*?"|.*?)(?:,|$)/g,G_=class e{constructor(t,n){typeof t==`string`&&(t=e.parseAttrList(t,n)),Pm(this,t)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)===`X-`)}decimalInteger(e){let t=parseInt(this[e],10);return t>2**53-1?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||`0x`).slice(2);t=(t.length&1?`0`:``)+t;let n=new Uint8Array(t.length/2);for(let e=0;e2**53-1?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let n=this[e];return n?parseFloat(n):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let n=this[e];return(n?n.split(/[ ,]+/):[]).reduce((e,t)=>(e[t.toLowerCase()]=!0,e),t)}bool(e){return this[e]===`YES`}decimalResolution(e){let t=U_.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let n,r={};for(W_.lastIndex=0;(n=W_.exec(e))!==null;){let i=n[1].trim(),a=n[2],o=a.indexOf(`"`)===0&&a.lastIndexOf(`"`)===a.length-1,s=!1;if(o)a=a.slice(1,-1);else switch(i){case`IV`:case`SCTE35-CMD`:case`SCTE35-IN`:case`SCTE35-OUT`:s=!0}if(t&&(o||s))a=B_(t,a);else if(!s&&!o)switch(i){case`CLOSED-CAPTIONS`:if(a===`NONE`)break;case`ALLOWED-CPC`:case`CLASS`:case`ASSOC-LANGUAGE`:case`AUDIO`:case`BYTERANGE`:case`CHANNELS`:case`CHARACTERISTICS`:case`CODECS`:case`DATA-ID`:case`END-DATE`:case`GROUP-ID`:case`ID`:case`IMPORT`:case`INSTREAM-ID`:case`KEYFORMAT`:case`KEYFORMATVERSIONS`:case`LANGUAGE`:case`NAME`:case`PATHWAY-ID`:case`QUERYPARAM`:case`RECENTLY-REMOVED-DATERANGES`:case`SERVER-URI`:case`STABLE-RENDITION-ID`:case`STABLE-VARIANT-ID`:case`START-DATE`:case`SUBTITLES`:case`SUPPLEMENTAL-CODECS`:case`URI`:case`VALUE`:case`VIDEO`:case`X-ASSET-LIST`:case`X-ASSET-URI`:qm.warn(`${e}: attribute ${i} is missing quotes`)}r[i]=a}return r}},K_=`com.apple.hls.interstitial`;function q_(e){return e!==`ID`&&e!==`CLASS`&&e!==`CUE`&&e!==`START-DATE`&&e!==`DURATION`&&e!==`END-DATE`&&e!==`END-ON-NEXT`}function J_(e){return e===`SCTE35-OUT`||e===`SCTE35-IN`||e===`SCTE35-CMD`}var Y_=class{constructor(e,t,n=0){if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=t?.tagOrder??n,t){let n=t.attr;for(let t in n)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==n[t]){qm.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=Pm(new G_({}),n,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e[`START-DATE`]),`END-DATE`in this.attr){let e=t?.endDate||new Date(this.attr[`END-DATE`]);G(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?`CUE`:`X-CUE`,{pre:!1,post:!1,once:!1}):e}get startTime(){let{tagAnchor:e}=this;return e===null||e.programDateTime===null?(qm.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){let e=this._endDate||this._dateAtEnd;if(e)return e;let t=this.duration;return t===null?null:this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3)}get duration(){if(`DURATION`in this.attr){let e=this.attr.decimalFloatingPoint(`DURATION`);if(G(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return`PLANNED-DURATION`in this.attr?this.attr.decimalFloatingPoint(`PLANNED-DURATION`):null}get endOnNext(){return this.attr.bool(`END-ON-NEXT`)}get isInterstitial(){return this.class===K_}get isValid(){return!!this.id&&!this._badValueForSameId&&G(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||`X-ASSET-URI`in this.attr||`X-ASSET-LIST`in this.attr)}},X_=10,Z_=class{constructor(e){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.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!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.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}let t=this.lastPartSn-e.lastPartSn,n=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!n||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&n>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let n=t.decryptdata;return n||=(t.setKeyFormat(e.keyFormat),t.decryptdata),!!n&&e.matches(n)})}get hasProgramDateTime(){return this.fragments.length?G(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||X_}get drift(){let e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(t!==-1){for(let n=e.length;n--;)if(e[n].index>t)return e[n].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}};function Q_(e,t){return e.length===t.length?!e.some((e,n)=>e!==t[n]):!1}function $_(e,t){return!e&&!t?!0:!e||!t?!1:Q_(e,t)}function ev(e){return e===`AES-128`||e===`AES-256`||e===`AES-256-CTR`}function tv(e){switch(e){case`AES-128`:case`AES-256`:return b_.cbc;case`AES-256-CTR`:return b_.ctr;default:throw Error(`invalid full segment method ${e}`)}}function nv(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function rv(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}function iv(e){let t=rv(e).subarray(0,16),n=new Uint8Array(16);return n.set(t,16-t.length),n}function av(e){let t=function(e,t,n){let r=e[t];e[t]=e[n],e[n]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function ov(e){let t=e.split(`:`),n=null;if(t[0]===`data`&&t.length===2){let e=t[1].split(`;`),r=e[e.length-1].split(`,`);if(r.length===2){let t=r[0]===`base64`,i=r[1];t?(e.splice(-1,1),n=nv(i)):n=iv(i)}}return n}var sv=typeof self<`u`?self:void 0,cv={CLEARKEY:`org.w3.clearkey`,FAIRPLAY:`com.apple.fps`,PLAYREADY:`com.microsoft.playready`,WIDEVINE:`com.widevine.alpha`},lv={CLEARKEY:`org.w3.clearkey`,FAIRPLAY:`com.apple.streamingkeydelivery`,PLAYREADY:`com.microsoft.playready`,WIDEVINE:`urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed`};function uv(e){switch(e){case lv.FAIRPLAY:return cv.FAIRPLAY;case lv.PLAYREADY:return cv.PLAYREADY;case lv.WIDEVINE:return cv.WIDEVINE;case lv.CLEARKEY:return cv.CLEARKEY}}function dv(e){switch(e){case cv.FAIRPLAY:return lv.FAIRPLAY;case cv.PLAYREADY:return lv.PLAYREADY;case cv.WIDEVINE:return lv.WIDEVINE;case cv.CLEARKEY:return lv.CLEARKEY}}function fv(e){let{drmSystems:t,widevineLicenseUrl:n}=e,r=t?[cv.FAIRPLAY,cv.WIDEVINE,cv.PLAYREADY,cv.CLEARKEY].filter(e=>!!t[e]):[];return!r[cv.WIDEVINE]&&n&&r.push(cv.WIDEVINE),r}var pv=function(e){return sv!=null&&(e=sv.navigator)!=null&&e.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function mv(e,t,n,r){let i;switch(e){case cv.FAIRPLAY:i=[`cenc`,`sinf`];break;case cv.WIDEVINE:case cv.PLAYREADY:i=[`cenc`];break;case cv.CLEARKEY:i=[`cenc`,`keyids`];break;default:throw Error(`Unknown key-system: ${e}`)}return hv(i,t,n,r)}function hv(e,t,n,r){return[{initDataTypes:e,persistentState:r.persistentState||`optional`,distinctiveIdentifier:r.distinctiveIdentifier||`optional`,sessionTypes:r.sessionTypes||[r.sessionType||`temporary`],audioCapabilities:t.map(e=>({contentType:`audio/mp4; codecs=${e}`,robustness:r.audioRobustness||``,encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:n.map(e=>({contentType:`video/mp4; codecs=${e}`,robustness:r.videoRobustness||``,encryptionScheme:r.videoEncryptionScheme||null}))}]}function gv(e){var t;return!!e&&(e.sessionType===`persistent-license`||!!((t=e.sessionTypes)!=null&&t.some(e=>e===`persistent-license`)))}function _v(e){let t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),n=String.fromCharCode.apply(null,Array.from(t)),r=n.substring(n.indexOf(`<`),n.length),i=new DOMParser().parseFromString(r,`text/xml`).getElementsByTagName(`KID`)[0];if(i){let e=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute(`VALUE`);if(e){let t=nv(e).subarray(0,16);return av(t),t}}return null}var vv={},yv=class e{static clearKeyUriToKeyIdMap(){vv={}}static setKeyIdForUri(e,t){vv[e]=t}static addKeyIdForUri(e){let t=Object.keys(vv).length%(2**53-1),n=new Uint8Array(16);return new DataView(n.buffer,12,4).setUint32(0,t),vv[e]=n,n}constructor(e,t,n,r=[1],i=null,a){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=e,this.uri=t,this.keyFormat=n,this.keyFormatVersions=r,this.iv=i,this.encrypted=e?e!==`NONE`:!1,this.isCommonEncryption=this.encrypted&&!ev(e),a!=null&&a.startsWith(`0x`)&&(this.keyId=new Uint8Array($m(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Q_(e.keyFormatVersions,this.keyFormatVersions)&&$_(e.iv,this.iv)&&$_(e.keyId,this.keyId)}isSupported(){if(this.method){if(ev(this.method)||this.method===`NONE`)return!0;if(this.keyFormat===`identity`)return this.method===`SAMPLE-AES`;switch(this.keyFormat){case lv.FAIRPLAY:case lv.WIDEVINE:case lv.PLAYREADY:case lv.CLEARKEY:return[`SAMPLE-AES`,`SAMPLE-AES-CENC`,`SAMPLE-AES-CTR`].indexOf(this.method)!==-1}}return!1}getDecryptData(t,n){if(!this.encrypted||!this.uri)return null;if(ev(this.method)){let n=this.iv;return n||=(typeof t!=`number`&&(qm.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),Sv(t)),new e(this.method,this.uri,`identity`,this.keyFormatVersions,n)}if(this.keyId){let t=vv[this.uri];if(t&&!Q_(this.keyId,t)&&e.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let r=ov(this.uri);if(r)switch(this.keyFormat){case lv.WIDEVINE:if(this.pssh=r,!this.keyId){let e=Wh(r.buffer);if(e.length){var i;let t=e[0];this.keyId=(i=t.kids)!=null&&i.length?t.kids[0]:null}}this.keyId||=xv(n);break;case lv.PLAYREADY:{let e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Uh(e,null,r),this.keyId=_v(r);break}default:{let e=r.subarray(0,16);if(e.length!==16){let t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||this.keyId.byteLength!==16){let t;t=bv(n),t||(t=xv(n),t||=vv[this.uri]),t&&(this.keyId=t,e.setKeyIdForUri(this.uri,t))}return this}};function bv(e){let t=e?.[lv.WIDEVINE];return t?t.keyId:null}function xv(e){let t=e?.[lv.PLAYREADY];if(t){let e=ov(t.uri);if(e)return _v(e)}return null}function Sv(e){let t=new Uint8Array(16);for(let n=12;n<16;n++)t[n]=e>>8*(15-n)&255;return t}var Cv=/#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,wv=/#EXT-X-MEDIA:(.*)/g,Tv=/^#EXT(?:INF|-X-TARGETDURATION):/m,Ev=new RegExp([`#EXTINF:\\s*(\\d*(?:\\.\\d+)?)(?:,(.*)\\s+)?`,`(?!#) *(\\S[^\\r\\n]*)`,`#.*`].join(`|`),`g`),Dv=new RegExp([`#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)`,`#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\\d+)`,`#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)`,`(#)([^:]*):(.*)`,`(#)(.*)(?:.*)\\r?\\n?`].join(`|`)),Ov=class e{static findGroup(e,t){for(let n=0;n0&&i.length({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:o.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]},c=0;for(wv.lastIndex=0;(i=wv.exec(t))!==null;){let t=new G_(i[1],r),o=t.TYPE;if(o){let r=s[o],i=a[o]||[];a[o]=i;let l=t.LANGUAGE,u=t[`ASSOC-LANGUAGE`],d=t.CHANNELS,f=t.CHARACTERISTICS,p=t[`INSTREAM-ID`],m={attrs:t,bitrate:0,id:c++,groupId:t[`GROUP-ID`]||``,name:t.NAME||l||``,type:o,default:t.bool(`DEFAULT`),autoselect:t.bool(`AUTOSELECT`),forced:t.bool(`FORCED`),lang:l,url:t.URI?e.resolve(t.URI,n):``};if(u&&(m.assocLang=u),d&&(m.channels=d),f&&(m.characteristics=f),p&&(m.instreamId=p),r!=null&&r.length){let t=e.findGroup(r,m.groupId)||r[0];Pv(m,t,`audioCodec`),Pv(m,t,`textCodec`)}i.push(m)}}return a}static parseLevelPlaylist(e,t,n,r,i,a){let o={url:t},s=new Z_(t),c=s.fragments,l=[],u=null,d=0,f=0,p=0,m=0,h=0,g=null,_=new lh(r,o),v,y,b,x=-1,S=!1,C=null,w;if(Ev.lastIndex=0,s.m3u8=e,s.hasVariableRefs=z_(e),Ev.exec(e)?.[0]!==`#EXTM3U`)return s.playlistParsingError=Error(`Missing format identifier #EXTM3U`),s;for(;(v=Ev.exec(e))!==null;){S&&(S=!1,_=new lh(r,o),_.playlistOffset=p,_.setStart(p),_.sn=d,_.cc=m,h&&(_.bitrate=h),_.level=n,u&&(_.initSegment=u,u.rawProgramDateTime&&(_.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null),C&&=(_.setByteRange(C),null)));let e=v[1];if(e){_.duration=parseFloat(e);let t=(` `+v[2]).slice(1);_.title=t||null,_.tagList.push(t?[`INF`,e,t]:[`INF`,e])}else if(v[3]){if(G(_.duration)){_.playlistOffset=p,_.setStart(p),b&&Rv(_,b,s),_.sn=d,_.level=n,_.cc=m,c.push(_);let e=(` `+v[3]).slice(1);_.relurl=B_(s,e),Iv(_,g,l),g=_,p+=_.duration,d++,f=0,S=!0}}else{if(v=v[0].match(Dv),!v){qm.warn(`No matches on slow regex match for level playlist!`);continue}for(y=1;y0&&Bv(s,e,v):zv(s,e,v),d=s.startSN=parseInt(i);break;case`SKIP`:{s.skippedSegments&&zv(s,e,v);let t=new G_(i,s),n=t.decimalInteger(`SKIPPED-SEGMENTS`);if(G(n)){s.skippedSegments+=n;for(let e=n;e--;)c.push(null);d+=n}let r=t.enumeratedString(`RECENTLY-REMOVED-DATERANGES`);r&&(s.recentlyRemovedDateranges=(s.recentlyRemovedDateranges||[]).concat(r.split(` `)));break}case`TARGETDURATION`:s.targetduration!==0&&zv(s,e,v),s.targetduration=Math.max(parseInt(i),1);break;case`VERSION`:s.version!==null&&zv(s,e,v),s.version=parseInt(i);break;case`INDEPENDENT-SEGMENTS`:break;case`ENDLIST`:s.live||zv(s,e,v),s.live=!1;break;case`#`:(i||l)&&_.tagList.push(l?[i,l]:[i]);break;case`DISCONTINUITY`:m++,_.tagList.push([`DIS`]);break;case`GAP`:_.gap=!0,_.tagList.push([e]);break;case`BITRATE`:_.tagList.push([e,i]),h=parseInt(i)*1e3,G(h)?_.bitrate=h:h=0;break;case`DATERANGE`:{let e=new G_(i,s),t=new Y_(e,s.dateRanges[e.ID],s.dateRangeTagCount);s.dateRangeTagCount++,t.isValid||s.skippedSegments?s.dateRanges[t.id]=t:qm.warn(`Ignoring invalid DATERANGE tag: "${i}"`),_.tagList.push([`EXT-X-DATERANGE`,i]);break}case`DEFINE`:{let e=new G_(i,s);`IMPORT`in e?H_(s,e,a):V_(s,e,t)}break;case`DISCONTINUITY-SEQUENCE`:s.startCC===0?c.length>0&&Bv(s,e,v):zv(s,e,v),s.startCC=m=parseInt(i);break;case`KEY`:{let e=jv(i,t,s);if(e.isSupported()){if(e.method===`NONE`){b=void 0;break}b||={};let t=b[e.keyFormat];t!=null&&t.matches(e)||(t&&(b=Pm({},b)),b[e.keyFormat]=e)}else qm.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${i}"`);break}case`START`:s.startTimeOffset=Mv(i);break;case`MAP`:{let e=new G_(i,s);if(_.duration){let t=new lh(r,o);Lv(t,e,n,b),u=t,_.initSegment=u,u.rawProgramDateTime&&!_.rawProgramDateTime&&(_.rawProgramDateTime=u.rawProgramDateTime)}else{let t=_.byteRangeEndOffset;if(t){let e=_.byteRangeStartOffset;C=`${t-e}@${e}`}else C=null;Lv(_,e,n,b),u=_,S=!0}u.cc=m;break}case`SERVER-CONTROL`:w&&zv(s,e,v),w=new G_(i),s.canBlockReload=w.bool(`CAN-BLOCK-RELOAD`),s.canSkipUntil=w.optionalFloat(`CAN-SKIP-UNTIL`,0),s.canSkipDateRanges=s.canSkipUntil>0&&w.bool(`CAN-SKIP-DATERANGES`),s.partHoldBack=w.optionalFloat(`PART-HOLD-BACK`,0),s.holdBack=w.optionalFloat(`HOLD-BACK`,0);break;case`PART-INF`:s.partTarget&&zv(s,e,v),s.partTarget=new G_(i).decimalFloatingPoint(`PART-TARGET`);break;case`PART`:{let e=s.partList;e||=s.partList=[];let t=f>0?e[e.length-1]:void 0,n=f++,r=new uh(new G_(i,s),_,o,n,t);e.push(r),_.duration+=r.duration;break}case`PRELOAD-HINT`:s.preloadHint=new G_(i,s);break;case`RENDITION-REPORT`:{let e=new G_(i,s);s.renditionReports=s.renditionReports||[],s.renditionReports.push(e);break}default:qm.warn(`line parsed but not handled: ${v}`);break}}}g&&!g.relurl?(c.pop(),p-=g.duration,s.partList&&(s.fragmentHint=g)):s.partList&&(Iv(_,g,l),_.cc=m,s.fragmentHint=_,b&&Rv(_,b,s)),s.targetduration||(s.playlistParsingError=Error(`Missing Target Duration`));let T=c.length,E=c[0],D=c[T-1];if(p+=s.skippedSegments*s.targetduration,p>0&&T&&D){s.averagetargetduration=p/T;let e=D.sn;s.endSN=e===`initSegment`?0:e,s.live||(D.endList=!0),x>0&&(Fv(c,x),E&&l.unshift(E))}return s.fragmentHint&&(p+=s.fragmentHint.duration),s.totalduration=p,l.length&&s.dateRangeTagCount&&E&&kv(l,s),s.endCC=m,s}};function kv(e,t){let n=e.length;if(!n)if(t.hasProgramDateTime){let r=t.fragments[t.fragments.length-1];e.push(r),n++}else return;let r=e[n-1],i=t.live?1/0:t.totalduration,a=Object.keys(t.dateRanges);for(let o=a.length;o--;){let s=t.dateRanges[a[o]],c=s.startDate.getTime();s.tagAnchor=r.ref;for(let r=n;r--&&!(e[r]?.sn=o||r===0)&&t<=o+((n[r+1]?.start||i)-a.start)*1e3){let i=n[r].sn-e.startSN;if(i<0)return-1;let a=e.fragments;if(a.length>n.length){let o=(n[r+1]||a[a.length-1]).sn-e.startSN;for(let e=o;e>i;e--){let n=a[e].programDateTime;if(t>=n&&te);[`video`,`audio`,`text`].forEach(e=>{let r=n.filter(t=>Jh(t,e));r.length&&(t[`${e}Codec`]=r.map(e=>e.split(`/`)[0]).join(`,`),n=n.filter(e=>r.indexOf(e)===-1))}),t.unknownCodecs=n}function Pv(e,t,n){let r=t[n];r&&(e[n]=r)}function Fv(e,t){let n=e[t];for(let r=t;r--;){let t=e[r];if(!t)return;t.programDateTime=n.programDateTime-t.duration*1e3,n=t}}function Iv(e,t,n){e.rawProgramDateTime?n.push(e):t!=null&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Lv(e,t,n,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=n,e.sn=`initSegment`,r&&(e.levelkeys=r),e.initSegment=null}function Rv(e,t,n){e.levelkeys=t;let{encryptedFragments:r}=n;(!r.length||r[r.length-1].levelkeys!==t)&&Object.keys(t).some(e=>t[e].isCommonEncryption)&&r.push(e)}function zv(e,t,n){e.playlistParsingError=Error(`#EXT-X-${t} must not appear more than once (${n[0]})`)}function Bv(e,t,n){e.playlistParsingError=Error(`#EXT-X-${t} must appear before the first Media Segment (${n[0]})`)}function Vv(e,t){let n=t.startPTS;if(G(n)){let r=0,i;t.sn>e.sn?(r=n-e.start,i=e):(r=e.start-n,i=t),i.duration!==r&&i.setDuration(r)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function Hv(e,t,n,r,i,a,o){r-n<=0&&(o.warn(`Fragment should have a positive duration`,t),r=n+t.duration,a=i+t.duration);let s=n,c=r,l=t.startPTS,u=t.endPTS;if(G(l)){let d=Math.abs(l-n);e&&d>e.totalduration?o.warn(`media timestamps and playlist times differ by ${d}s for level ${t.level} ${e.url}`):G(t.deltaPTS)?t.deltaPTS=Math.max(d,t.deltaPTS):t.deltaPTS=d,s=Math.max(n,l),n=Math.min(n,l),i=t.startDTS===void 0?i:Math.min(i,t.startDTS),c=Math.min(r,u),r=Math.max(r,u),a=t.endDTS===void 0?a:Math.max(a,t.endDTS)}let d=n-t.start;t.start!==0&&t.setStart(n),t.setDuration(r-t.start),t.startPTS=n,t.maxStartPTS=s,t.startDTS=i,t.endPTS=r,t.minEndPTS=c,t.endDTS=a;let f=t.sn;if(!e||fe.endSN)return 0;let p,m=f-e.startSN,h=e.fragments;for(h[m]=t,p=m;p>0;p--)Vv(h[p],h[p-1]);for(p=m;p=0;e--){let t=i[e].initSegment;if(t){r=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let a;Kv(e,t,(e,n,i,o)=>{if((!t.startCC||t.skippedSegments)&&n.cc!==e.cc){let r=e.cc-n.cc;for(let e=i;e{e&&(!e.initSegment||e.initSegment.relurl===r?.relurl)&&(e.initSegment=r)}),t.skippedSegments){if(t.deltaUpdateFailed=o.some(e=>!e),t.deltaUpdateFailed){n.warn(`[level-helper] Previous playlist missing segments skipped in delta playlist`);for(let e=t.skippedSegments;e--;)o.shift();t.startSN=o[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=Wv(e.dateRanges,t,n));let r=e.fragments.filter(e=>e.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),a?Hv(t,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS,n):Jv(e,t),o.length&&(t.totalduration=t.edge-o[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;let c=t.advancedDateTime;if(t.advanced&&c){let e=t.edge;t.driftStart||=(t.driftStartTime=c,e),t.driftEndTime=c,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=e.requestScheduled)}function Wv(e,t,n){let{dateRanges:r,recentlyRemovedDateranges:i}=t,a=Pm({},e);i&&i.forEach(e=>{delete a[e]});let o=Object.keys(a).length;return o?(Object.keys(r).forEach(e=>{let t=a[e],i=new Y_(r[e].attr,t);i.isValid?(a[e]=i,t||(i.tagOrder+=o)):n.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Pg(r[e].attr)}"`)}),a):r}function Gv(e,t,n){if(e&&t){let r=0;for(let i=0,a=e.length;i<=a;i++){let a=e[i],o=t[i+r];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?n(a,o):r--}}}function Kv(e,t,n){let r=t.skippedSegments,i=Math.max(e.startSN,t.startSN)-t.startSN,a=+!!e.fragmentHint+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,o=t.startSN-e.startSN,s=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,c=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let l=i;l<=a;l++){let i=c[o+l],a=s[l];if(r&&!a&&i&&(a=t.fragments[l]=i),i&&a){n(i,a,l,s);let r=i.relurl,o=a.relurl;if(r&&ty(r,o)){t.playlistParsingError=qv(`media sequence mismatch ${a.sn}:`,e,t,i,a);return}else if(i.cc!==a.cc){t.playlistParsingError=qv(`discontinuity sequence mismatch (${i.cc}!=${a.cc})`,e,t,i,a);return}}}}function qv(e,t,n,r,i){return Error(`${e} ${i.url} Playlist starting @${t.startSN} ${t.m3u8} Playlist starting @${n.startSN} ${n.m3u8}`)}function Jv(e,t,n=!0){let r=t.startSN+t.skippedSegments-e.startSN,i=e.fragments,a=r>=0,o=0;if(a&&rt){let e=r[r.length-1].duration*1e3;e{var n;(n=e.details)==null||n.fragments.forEach(e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function ty(e,t){return e!==t&&t?ny(e)!==ny(t):!1}function ny(e){return e.replace(/\?[^?]*$/,``)}function ry(e,t){for(let n=0,r=e.length;ne.startCC)}function ay(e,t){let n=e.start+t;e.startPTS=n,e.setStart(n),e.endPTS=n+e.duration}function oy(e,t){let n=t.fragments;for(let t=0,r=n.length;t{let{config:e,fragCurrent:t,media:n,mediaBuffer:r,state:i}=this,a=n?n.currentTime:0,o=Q.bufferInfo(r||n,a,e.maxBufferHole),s=!o.len;if(this.log(`Media seeking to ${G(a)?a.toFixed(3):a}, state: ${i}, ${s?`out of`:`in`} buffer`),this.state===$.ENDED)this.resetLoadingState();else if(t){let n=e.maxFragLookUpTolerance,r=t.start-n,i=t.start+t.duration+n;if(s||io.end){let e=a>i;(athis.lastCurrentTime&&(this.lastCurrentTime=a),!this.loadingParts)){let e=Math.max(o.end,a),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${a.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}this.hls.hasEnoughToStart||(this.log(`Setting ${s?`startPosition`:`nextLoadPosition`} to ${a} for seek without enough to start`),this.nextLoadPosition=a,s&&(this.startPosition=a)),s&&this.state===$.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log(`setting startPosition to 0 because media ended`),this.startPosition=this.lastCurrentTime=0},this.playlistType=i,this.hls=e,this.fragmentLoader=new k_(e.config),this.keyLoader=n,this.fragmentTracker=t,this.config=e.config,this.decrypter=new D_(e.config)}registerListeners(){let{hls:e}=this;e.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(J.MANIFEST_LOADING,this.onManifestLoading,this),e.on(J.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(J.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(J.MANIFEST_LOADING,this.onManifestLoading,this),e.off(J.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(J.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===$.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=$.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;let n=e.end||0,r=this.config.timelineOffset||0;if(n<=r)return!1;let i=e.buffered;this.config.maxBufferHole&&i&&i.length>1&&(e=Q.bufferedInfo(i,e.start,0));let a=e.nextStart;if(a&&a>r&&a{let t=e.frag;if(this.fragContextChanged(t)){this.warn(`${t.type} sn: ${t.sn}${e.part?` part: `+e.part.index:``} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(t);return}t.stats.chunkCount++,this._handleFragmentLoadProgress(e)}).then(e=>{if(!e)return;let t=this.state,n=e.frag;if(this.fragContextChanged(n)){(t===$.FRAG_LOADING||!this.fragCurrent&&t===$.PARSING)&&(this.fragmentTracker.removeFragment(n),this.state=$.IDLE);return}`payload`in e&&(this.log(`Loaded ${n.type} sn: ${n.sn} of ${this.playlistLabel()} ${n.level}`),this.hls.trigger(J.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e)}).catch(t=>{this.state===$.STOPPED||this.state===$.ERROR||(this.warn(`Frag error: ${t?.message||t}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){let{fragmentTracker:t}=this;if(t.getState(e)===h_.APPENDING){let n=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,n),i=Math.max(e.duration,r?r.len:this.config.maxBufferLength),a=this.backtrackFragment;((a?e.sn-a.sn:0)===1||this.reduceMaxBufferLength(i,e.duration))&&t.removeFragment(e)}else this.mediaBuffer?.buffered.length===0?t.removeAllFragments():t.hasParts(e.type)&&(t.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),t.getState(e)===h_.PARTIAL&&t.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){let t=e.details;return t?.live&&t.type!==`EVENT`&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,n=null){if(!(e-t))return;let r={startOffset:e,endOffset:t,type:n};this.hls.trigger(J.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(e=>{let t=e?.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw Error(`init load aborted`);return e}).then(e=>{let{hls:t}=this,{frag:n,payload:r}=e,i=n.decryptdata;if(r&&r.byteLength>0&&i!=null&&i.key&&i.iv&&ev(i.method)){let a=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),i.key.buffer,i.iv.buffer,tv(i.method)).catch(e=>{throw t.trigger(J.ERROR,{type:K.MEDIA_ERROR,details:q.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:n}),e}).then(r=>{let i=self.performance.now();return t.trigger(J.FRAG_DECRYPTED,{frag:n,payload:r,stats:{tstart:a,tdecrypt:i}}),e.payload=r,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)}).catch(t=>{this.state===$.STOPPED||this.state===$.ERROR||(this.warn(t),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){let{levels:t}=this;if(!t)throw Error(`init load aborted, missing levels`);let n=e.frag.stats;this.state!==$.STOPPED&&(this.state=$.IDLE),e.frag.data=new Uint8Array(e.payload),n.parsing.start=n.buffering.start=self.performance.now(),n.parsing.end=n.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var n,r;let i=e.tracks;if(i&&!t.encrypted&&((n=i.audio)!=null&&n.encrypted||(r=i.video)!=null&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let e=this.media,n=Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${e?`attached mediaKeys: `+e.mediaKeys:`detached`})`);return this.warn(n.message),!e||e.mediaKeys?!1:(this.hls.trigger(J.ERROR,{type:K.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_NO_KEYS,fatal:!1,error:n,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){let n=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?` part: `+t.index:``} of ${this.fragInfo(e,!1,t)} > buffer:${n?fy.toString(Q.getBuffered(n)):`(detached)`})`),ch(e)){if(e.type!==Y.SUBTITLE){let t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e])){this.state=$.IDLE;return}}let t=this.levels?.[e.level];t!=null&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=$.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let{frag:n,part:r,partsLoaded:i}=e,a=!i||i.length===0||i.some(e=>!e),o=new F_(n.level,n.sn,n.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,n=null,r){var i;this.fragCurrent=e;let a=t.details;if(!this.levels||!a)throw Error(`frag load aborted, missing level${a?``:` detail`}s`);let o=null;if(e.encrypted&&!((i=e.decryptdata)!=null&&i.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=$.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(J.KEY_LOADED,e),this.state===$.KEY_LOADING&&(this.state=$.IDLE),e}),this.hls.trigger(J.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log(`context changed in KEY_LOADING`),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log(`[eme] blocking frag load until media-keys acquired`));let s=this.fragPrevious;if(ch(e)&&(!s||e.sn!==s.sn)){let n=this.shouldLoadParts(t.details,e.end);n!==this.loadingParts&&(this.log(`LL-Part loading ${n?`ON`:`OFF`} loading sn ${s?.sn}->${e.sn}`),this.loadingParts=n)}if(n=Math.max(e.start,n||0),this.loadingParts&&ch(e)){let i=a.partList;if(i&&r){n>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);let s=this.getNextPart(i,e,n);if(s>-1){let c=i[s];e=this.fragCurrent=c.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${c.index} (${s}/${i.length-1}) of ${this.fragInfo(e,!1,c)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(n.toFixed(3))}`),this.nextLoadPosition=c.start+c.duration,this.state=$.FRAG_LOADING;let l;return l=o?o.then(n=>!n||this.fragContextChanged(n.frag)?null:this.doFragPartsLoad(e,c,t,r)).catch(e=>this.handleFragLoadError(e)):this.doFragPartsLoad(e,c,t,r).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(J.FRAG_LOADING,{frag:e,part:c,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(Error(`frag load aborted, context changed in FRAG_LOADING parts`)):l}else if(!e.url||this.loadedEndOfParts(i,n))return Promise.resolve(null)}}if(ch(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${n.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${a.partList?.filter(e=>e.loaded).map(e=>`[${e.start}-${e.end}]`)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${`[`+a.startSN+`-`+a.endSN+`]`}, target: ${parseFloat(n.toFixed(3))}`),G(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=$.FRAG_LOADING;let c=this.config.progressive&&e.type!==Y.SUBTITLE,l;return l=c&&o?o.then(t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,r)).catch(e=>this.handleFragLoadError(e)):Promise.all([this.fragmentLoader.load(e,c?r:void 0),o]).then(([e])=>(!c&&r&&r(e),e)).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(J.FRAG_LOADING,{frag:e,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(Error(`frag load aborted, context changed in FRAG_LOADING`)):l}doFragPartsLoad(e,t,n,r){return new Promise((i,a)=>{let o=[],s=n.details?.partList,c=t=>{this.fragmentLoader.loadPart(e,t,r).then(r=>{o[t.index]=r;let a=r.part;this.hls.trigger(J.FRAG_LOADED,r);let l=Qv(n.details,e.sn,t.index+1)||$v(s,e.sn,t.index+1);if(l)c(l);else return i({frag:e,part:a,partsLoaded:o})}).catch(a)};c(t)})}handleFragLoadError(e){if(`data`in e){let t=e.data;t.frag&&t.details===q.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===K.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(J.ERROR,t)}else this.hls.trigger(J.ERROR,{type:K.OTHER_ERROR,details:q.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==$.PARSING){!this.fragCurrent&&this.state!==$.STOPPED&&this.state!==$.ERROR&&(this.state=$.IDLE);return}let{frag:n,part:r,level:i}=t,a=self.performance.now();n.stats.parsing.end=a,r&&(r.stats.parsing.end=a);let o=this.getLevelDetails(),s=o&&n.sn>o.endSN||this.shouldLoadParts(o,n.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?`ON`:`OFF`} after parsing segment ending @${n.end.toFixed(2)}`),this.loadingParts=s),this.updateLevelTiming(n,r,i,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){let n=e.partList[0];if(n.fragment.type===Y.SUBTITLE)return!1;if(t>=n.end+(e.fragmentHint?.duration||0)&&(this.hls.hasEnoughToStart?this.media?.currentTime||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:n}=this,{level:r,sn:i,part:a}=e;if(!(t!=null&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;let o=t[r],s=o.details,c=a>-1?Qv(s,i,a):null,l=c?c.fragment:Zv(s,i,n);return l?(n&&n!==l&&(l.stats=n.stats),{frag:l,part:c,level:o}):null}bufferFragmentData(e,t,n,r,i){if(this.state!==$.PARSING)return;let{data1:a,data2:o}=e,s=a;if(o&&(s=Fh(a,o)),!s.length)return;let c=this.initPTS[t.cc],l=c?-c.baseTime/c.timescale:void 0,u={type:e.type,frag:t,part:n,chunkMeta:r,offset:l,parent:t.type,data:s};if(this.hls.trigger(J.BUFFER_APPENDING,u),e.dropped&&e.independent&&!n){if(i)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!Q.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let n=t.currentTime,r=Q.bufferInfo(t,n,0),i=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,i*.25),o=Math.max(Math.min(e.start-a,r.end-a),n+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var n;let r=this.getLoadPosition();if(!G(r))return null;let i=this.lastCurrentTime>r||(n=this.media)!=null&&n.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,i)}getFwdBufferInfoAtPos(e,t,n,r){let i=Q.bufferInfo(e,t,r);if(i.len===0&&i.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,n);if(a&&(i.nextStart<=a.end||a.gap)){let n=Math.max(Math.min(i.nextStart,a.end)-t,r);return Q.bufferInfo(e,t,n)}}return i}getMaxBufferLength(e){let{config:t}=this,n;return n=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(n,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,n){let r=e.nextStart;if(r&&n.start>r){let r=e.buffered;if(r){let i=e.len,a=e.bufferedIndex;for(let e=r.length-1;e>a;e--)r[e].start=t}}return!1}reduceMaxBufferLength(e,t){let n=this.config,r=Math.max(Math.min(e-t,n.maxBufferLength),t),i=Math.max(e-t*3,n.maxMaxBufferLength/2,r);return i>=r?(n.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0):!1}getAppendedFrag(e,t=Y.MAIN){let n=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return n&&`fragment`in n?n.fragment:n}getNextFragment(e,t){let n=t.fragments,r=n.length;if(!r)return null;let{config:i}=this,a=t.fragmentStart,o=i.lowLatencyMode&&!!t.partList,s=null;if(t.live){let n=i.initialLiveManifestSize;if(r=a?(l=r,u=r===n?`config`:`next load start`):i===null?(l=e,u=`buffer pos`):(l=i,u=`live edge`),l=i){let e=a.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(my(this.config)){var e;if(!((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null)&&e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(my(this.config)&&e.type!==Y.SUBTITLE){let n=this.hls.interstitialsManager,r=n?.bufferingItem;if(r){let n=r.event;if(n){if(n.appendInPlace||Math.abs(e.start-r.start)>1||r.start===0)return null}else if(e.end<=r.start&&t?.live===!1||e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}let i=n?.playerQueue;if(i)for(let t=i.length;t--;){let n=i[t].interstitial;if(n.appendInPlace&&e.start>=n.startTime&&e.end<=n.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,n){let r=-1,i=!1,a=!0;for(let o=0,s=e.length;o-1&&nn.start)return!0}return!1}getInitialLiveFragment(e){let t=e.fragments,n=this.fragPrevious,r=null;if(n){if(e.hasProgramDateTime&&(r=Xg(t,n.endProgramDateTime,this.config.maxFragLookUpTolerance),r&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${n.programDateTime}`)),!r){let i=n.sn+1;if(i>=e.startSN&&i<=e.endSN){let a=t[i-e.startSN];n.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=t_(e,n.cc,n.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{let t=this.hls.liveSyncPosition;t!==null&&(r=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,n){let{config:r}=this,{fragPrevious:i}=this,{fragments:a,endSN:o}=n,{fragmentHint:s}=n,{maxFragLookUpTolerance:c}=r,l=n.partList,u=!!(this.loadingParts&&l!=null&&l.length&&s);u&&!this.bitrateTest&&l[l.length-1].fragment.sn===s.sn&&(a=a.concat(s),o=s.sn);let d;if(et-c||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:c;d=Zg(i,a,e,n)}else d=a[a.length-1];if(d){let e=d.sn-n.startSN,t=this.fragmentTracker.getState(d);if((t===h_.OK||t===h_.PARTIAL&&d.gap)&&(i=d),i&&d.sn===i.sn&&(!u||l[0].fragment.sn>d.sn||!n.live)&&d.level===i.level){let t=a[e+1];d=d.sn${e.startSN} fragments: ${r}`),i}return i}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let n=this.startPosition;n=0&&(n=this.nextLoadPosition),n}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&ch(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?` part `+t.index:``} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==$.FRAG_LOADING_WAITING_RETRY)&&(this.state=$.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){let e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}let n=t.frag;if(!n||n.type!==e||!this.levels)return;if(this.fragContextChanged(n)){this.warn(`Frag load error must match current frag to retry ${n.url} > ${this.fragCurrent?.url}`);return}let r=t.details===q.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(n,!0);let i=t.errorAction;if(!i){this.state=$.ERROR;return}let{action:a,flags:o,retryCount:s=0,retryConfig:c}=i,l=!!c,u=l&&a===d_.RetryRequest,d=l&&!i.resolved&&o===f_.MoveAllAlternatesMatchingHost,f=this.hls.latestLevelDetails?.live;if(!u&&d&&ch(n)&&!n.endList&&f&&!i_(t))this.resetFragmentErrors(e),this.treatAsGap(n),i.resolved=!0;else if((u||d)&&s=t||n&&!u_(0))&&(n&&this.log(`Connection restored (online)`),this.resetStartWhenNotLoaded(),this.state=$.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===$.PARSING||this.state===$.PARSED){let t=e.frag,n=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,n),i=r&&r.len>.5;i&&this.reduceMaxBufferLength(r.len,t?.duration||10);let a=!i;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${n} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===Y.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==$.STOPPED&&(this.state=$.IDLE)}afterBufferFlushed(e,t,n){if(!e)return;let r=Q.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,n),this.state===$.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log(`Reset loading state`),this.fragCurrent=null,this.fragPrevious=null,this.state!==$.STOPPED&&(this.state=$.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log(`resetting startPosition for live start`),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?``:e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,n,r){let i=n.details;if(!i){this.warn(`level.details undefined`);return}if(!Object.keys(e.elementaryStreams).reduce((t,a)=>{let o=e.elementaryStreams[a];if(o){let s=o.endPTS-o.startPTS;if(s<=0)return this.warn(`Could not parse fragment ${e.sn} ${a} duration reliably (${s})`),t||!1;let c=r?0:Hv(i,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS,this);return this.hls.trigger(J.LEVEL_PTS_UPDATED,{details:i,level:n,drift:c,type:a,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t},!1)){let t=this.transmuxer?.error===null;if((n.fragmentError===0||t&&(n.fragmentError<2||e.endList))&&this.treatAsGap(e,n),t){let t=Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger(J.ERROR,{type:K.MEDIA_ERROR,details:q.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=$.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?` part: `+t.index:``} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(J.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===Y.MAIN?`level`:`track`}fragInfo(e,t=!0,n){return`${this.playlistLabel()} ${e.level} (${n?`part`:`frag`}:[${((t&&!n?e.startPTS:(n||e).start)??NaN).toFixed(3)}-${((t&&!n?e.endPTS:(n||e).end)??NaN).toFixed(3)}]${n&&e.type===`main`?`INDEPENDENT=`+(n.independent?`YES`:`NO`):``}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event===`demuxerWorker`&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&=(this.transmuxer.destroy(),null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}};function my(e){return!!e.interstitialsController&&e.enableInterstitialPlayback!==!1}var hy=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,n;if(e.length)n=e.length===1?e[0]:gy(e,t);else return new Uint8Array;return this.reset(),n}reset(){this.chunks.length=0,this.dataLength=0}};function gy(e,t){let n=new Uint8Array(t),r=0;for(let t=0;t0)return e.subarray(n,n+r)}function jy(e,t,n,r){let i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],a=t[n+2],o=a>>2&15;if(o>12){let t=Error(`invalid ADTS sampling index:${o}`);e.emit(J.ERROR,J.ERROR,{type:K.MEDIA_ERROR,details:q.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message});return}let s=(a>>6&3)+1,c=t[n+3]>>6&3|(a&1)<<2,l=`mp4a.40.`+s,u=i[o],d=o;(s===5||s===29)&&(d-=3);let f=[s<<3|(d&14)>>1,(d&1)<<7|c<<3];return qm.log(`manifest codec:${r}, parsed codec:${l}, channels:${c}, rate:${u} (ADTS object type:${s} sampling index:${o})`),{config:f,samplerate:u,channelCount:c,codec:l,parsedCodec:l,manifestCodec:r}}function My(e,t){return e[t]===255&&(e[t+1]&246)==240}function Ny(e,t){return e[t+1]&1?7:9}function Py(e,t){return(e[t+3]&3)<<11|e[t+4]<<3|(e[t+5]&224)>>>5}function Fy(e,t){return t+5=e.length)return!1;let r=Py(e,t);if(r<=n)return!1;let i=t+r;return i===e.length||Iy(e,i)}return!1}function zy(e,t,n,r,i){if(!e.samplerate){let a=jy(t,n,r,i);if(!a)return;Pm(e,a)}}function By(e){return 1024*9e4/e}function Vy(e,t){let n=Ny(e,t);if(t+n<=e.length){let r=Py(e,t)-n;if(r>0)return{headerLength:n,frameLength:r}}}function Hy(e,t,n,r,i){let a=r+i*By(e.samplerate),o=Vy(t,n),s;if(o){let{frameLength:r,headerLength:i}=o,c=i+r,l=Math.max(0,n+c-t.length);l?(s=new Uint8Array(c-i),s.set(t.subarray(n+i,t.length),0)):s=t.subarray(n+i,n+c);let u={unit:s,pts:a};return l||e.samples.push(u),{sample:u,length:c,missing:l}}let c=t.length-n;return s=new Uint8Array(c),s.set(t.subarray(n,t.length),0),{sample:{unit:s,pts:a},length:c,missing:-1}}function Uy(e,t){return Oy(e,t)&&ky(e,t+6)+10<=e.length-t}function Wy(e){return e instanceof ArrayBuffer?e:e.byteOffset==0&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}function Gy(e,t=0,n=1/0){return Ky(e,t,n,Uint8Array)}function Ky(e,t,n,r){let i=qy(e),a=1;`BYTES_PER_ELEMENT`in r&&(a=r.BYTES_PER_ELEMENT);let o=Jy(e)?e.byteOffset:0,s=(o+e.byteLength)/a,c=(o+t)/a,l=Math.floor(Math.max(0,Math.min(c,s)));return new r(i,l,Math.floor(Math.min(l+Math.max(n,0),s))-l)}function qy(e){return e instanceof ArrayBuffer?e:e.buffer}function Jy(e){return e&&e.buffer instanceof ArrayBuffer&&e.byteLength!==void 0&&e.byteOffset!==void 0}function Yy(e){let t={key:e.type,description:``,data:``,mimeType:null,pictureType:null};if(e.size<2)return;if(e.data[0]!==3){console.log(`Ignore frame with unrecognized character encoding`);return}let n=e.data.subarray(1).indexOf(0);if(n===-1)return;let r=Zm(Gy(e.data,1,n)),i=e.data[2+n],a=e.data.subarray(3+n).indexOf(0);if(a===-1)return;let o=Zm(Gy(e.data,3+n,a)),s;return s=r===`-->`?Zm(Gy(e.data,4+n+a)):Wy(e.data.subarray(4+n+a)),t.mimeType=r,t.pictureType=i,t.description=o,t.data=s,t}function Xy(e){if(e.size<2)return;let t=Zm(e.data,!0),n=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:n.buffer}}function Zy(e){if(e.size<2)return;if(e.type===`TXXX`){let t=1,n=Zm(e.data.subarray(t),!0);t+=n.length+1;let r=Zm(e.data.subarray(t));return{key:e.type,info:n,data:r}}let t=Zm(e.data.subarray(1));return{key:e.type,info:``,data:t}}function Qy(e){if(e.type===`WXXX`){if(e.size<2)return;let t=1,n=Zm(e.data.subarray(t),!0);t+=n.length+1;let r=Zm(e.data.subarray(t));return{key:e.type,info:n,data:r}}let t=Zm(e.data);return{key:e.type,info:``,data:t}}function $y(e){return e.type===`PRIV`?Xy(e):e.type[0]===`W`?Qy(e):e.type===`APIC`?Yy(e):Zy(e)}function eb(e){let t=String.fromCharCode(e[0],e[1],e[2],e[3]),n=ky(e,4);return{type:t,size:n,data:e.subarray(10,10+n)}}var tb=10,nb=10;function rb(e){let t=0,n=[];for(;Oy(e,t);){let r=ky(e,t+6);e[t+5]>>6&1&&(t+=tb),t+=tb;let i=t+r;for(;t+nb0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:sb.audioId3,duration:1/0});r{if(G(e))return e*90;let r=n?n.baseTime*9e4/n.timescale:0;return t*9e4+r},db=null,fb=[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],pb=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],mb=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],hb=[0,1,1,4];function gb(e,t,n,r,i){if(n+24>t.length)return;let a=_b(t,n);if(a&&n+a.frameLength<=t.length){let o=r+i*(a.samplesPerFrame*9e4/a.sampleRate),s={unit:t.subarray(n,n+a.frameLength),pts:o,dts:o};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(s),{sample:s,length:a.frameLength,missing:0}}}function _b(e,t){let n=e[t+1]>>3&3,r=e[t+1]>>1&3,i=e[t+2]>>4&15,a=e[t+2]>>2&3;if(n!==1&&i!==0&&i!==15&&a!==3){let o=e[t+2]>>1&1,s=e[t+3]>>6,c=fb[(n===3?3-r:r===3?3:4)*14+i-1]*1e3,l=pb[(n===3?0:n===2?1:2)*3+a],u=s===3?1:2,d=mb[n][r],f=hb[r],p=d*8*f,m=Math.floor(d*c/l+o)*f;if(db===null){let e=(navigator.userAgent||``).match(/Chrome\/(\d+)/i);db=e?parseInt(e[1]):0}return db&&db<=87&&r===2&&c>=224e3&&s===0&&(e[t+3]=e[t+3]|128),{sampleRate:l,channelCount:u,frameLength:m,samplesPerFrame:p}}}function vb(e,t){return e[t]===255&&(e[t+1]&224)==224&&(e[t+1]&6)!=0}function yb(e,t){return t+1{let n=0,r=5;t+=r;let i=new Uint32Array(1),a=new Uint32Array(1),o=new Uint8Array(1);for(;r>0;){o[0]=e[t];let s=Math.min(r,8),c=8-s;a[0]=4278190080>>>24+c<>c,n=n?n<t.length||t[n]!==11||t[n+1]!==119)return-1;let a=t[n+4]>>6;if(a>=3)return-1;let o=[48e3,44100,32e3][a],s=t[n+4]&63,c=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][s*3+a]*2;if(n+c>t.length)return-1;let l=t[n+6]>>5,u=0;l===2?u+=2:(l&1&&l!==1&&(u+=2),l&4&&(u+=2));let d=(t[n+6]<<8|t[n+7])>>12-u&1,f=[2,1,2,3,3,4,4,5][l]+d,p=t[n+5]>>3,m=t[n+5]&7,h=new Uint8Array([a<<6|p<<1|m>>2,(m&3)<<6|l<<3|d<<2|s>>4,s<<4&224]),g=r+i*(1536/o*9e4),_=t.subarray(n,n+c);return e.config=h,e.channelCount=f,e.samplerate=o,e.samples.push({unit:_,pts:g}),c}var Eb=class extends lb{resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:`audio/mpeg`,type:`audio`,id:2,pid:-1,sequenceNumber:0,segmentCodec:`mp3`,samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=Ay(e,0),n=t?.length||0;if(t&&e[n]===11&&e[n+1]===119&&ob(t)!==void 0&&Cb(e,n)<=16)return!1;for(let t=e.length;n{let r=Vh(e);if(Db.test(r.schemeIdUri)){let e=kb(r,t),i=r.eventDuration===4294967295?1/0:r.eventDuration/r.timeScale;i<=.001&&(i=1/0);let a=r.payload;n.samples.push({data:a,len:a.byteLength,dts:e,pts:e,type:sb.emsg,duration:i})}else if(this.config.enableEmsgKLVMetadata&&r.schemeIdUri.startsWith(`urn:misb:KLV:bin:1910.1`)){let e=kb(r,t);n.samples.push({data:r.payload,len:r.payload.byteLength,dts:e,pts:e,type:sb.misbklv,duration:1/0})}})}return n}demuxSampleAes(e,t,n){return Promise.reject(Error(`The MP4 demuxer does not support SAMPLE-AES decryption`))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}};function kb(e,t){return G(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var Ab=class{constructor(e,t,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new D_(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,b_.cbc)}decryptAacSample(e,t,n){let r=e[t].unit;if(r.length<=16)return;let i=r.subarray(16,r.length-r.length%16),a=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(a).then(i=>{let a=new Uint8Array(i);r.set(a,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,n)}).catch(n)}decryptAacSamples(e,t,n){for(;;t++){if(t>=e.length){n();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,n),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,n=new Int8Array(t),r=0;for(let t=32;t{i.data=this.getAvcDecryptedUnit(a,o),this.decrypter.isSync()||this.decryptAvcSamples(e,t,n+1,r)}).catch(r)}decryptAvcSamples(e,t,n,r){if(e instanceof Uint8Array)throw Error(`Cannot decrypt samples of type Uint8Array`);for(;;t++,n=0){if(t>=e.length){r();return}let i=e[t].units;for(;!(n>=i.length);n++){let a=i[n];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,n,r,a),!this.decrypter.isSync()))return}}}},jb=class{constructor(){this.VideoSample=null}createVideoSample(e,t,n){return{key:e,frame:!1,pts:t,dts:n,units:[],length:0}}getLastNalUnit(e){var t;let n=this.VideoSample,r;if((!n||n.units.length===0)&&(n=e[e.length-1]),(t=n)!=null&&t.units){let e=n.units;r=e[e.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let n=t.samples,r=n.length;if(r){let t=n[r-1];e.pts=t.pts,e.dts=t.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,n){let r=t.byteLength,i=e.naluState||0,a=i,o=[],s=0,c,l,u,d=-1,f=0;for(i===-1&&(d=0,f=this.getNALuType(t,0),i=0,s=1);s=0){let e={data:t.subarray(d,l),type:f};o.push(e)}else{let n=this.getLastNalUnit(e.samples);n&&(a&&s<=4-a&&n.state&&(n.data=n.data.subarray(0,n.data.byteLength-a)),l>0&&(n.data=Fh(n.data,t.subarray(0,l)),n.state=0))}s=0&&i>=0){let e={data:t.subarray(d,r),type:f,state:i};o.push(e)}if(o.length===0){let n=this.getLastNalUnit(e.samples);n&&(n.data=Fh(n.data,t))}return e.naluState=i,o}},Mb=class{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){let e=this.data,t=this.bytesAvailable,n=e.byteLength-t,r=new Uint8Array(4),i=Math.min(4,t);if(i===0)throw Error(`no bytes available`);r.set(e.subarray(n,n+i)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=i*8,this.bytesAvailable-=i}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e),n=this.word>>>32-t;if(e>32&&qm.error(`Cannot read more than 32 bits at a time`),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw Error(`no bits available`);return t=e-t,t>0&&this.bitsAvailable?n<>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}},Nb=class extends jb{parsePES(e,t,n,r){let i=this.parseNALu(e,n.data,r),a=this.VideoSample,o,s=!1;n.data=null,a&&i.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),i.forEach(r=>{var i,c;switch(r.type){case 1:{let t=!1;o=!0;let i=r.data;if(s&&i.length>4){let e=this.readSliceType(i);(e===2||e===4||e===7||e===9)&&(t=!0)}if(t){var l;(l=a)!=null&&l.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts),a.frame=!0,a.key=t;break}case 5:o=!0,(i=a)!=null&&i.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts),a.key=!0,a.frame=!0;break;case 6:o=!0,zh(r.data,1,n.pts,t.samples);break;case 7:{o=!0,s=!0;let t=r.data,n=this.readSPS(t);if(!e.sps||e.width!==n.width||e.height!==n.height||e.pixelRatio?.[0]!==n.pixelRatio[0]||e.pixelRatio?.[1]!==n.pixelRatio[1]){e.width=n.width,e.height=n.height,e.pixelRatio=n.pixelRatio,e.sps=[t];let r=t.subarray(1,4),i=`avc1.`;for(let e=0;e<3;e++){let t=r[e].toString(16);t.length<2&&(t=`0`+t),i+=t}e.codec=i}break}case 8:o=!0,e.pps=[r.data];break;case 9:o=!0,e.audFound=!0,(c=a)!=null&&c.frame&&(this.pushAccessUnit(a,e),a=null),a||=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts);break;case 12:o=!0;break;default:o=!1;break}a&&o&&a.units.push(r)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){let t=new Mb(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let n=8,r=8,i;for(let a=0;a{var i,c;switch(r.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,s){var l;(l=a)!=null&&l.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(i=a)!=null&&i.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts),a.key=!0,a.frame=!0;break;case 39:o=!0,zh(r.data,2,n.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!=`object`&&(e.params={}),e.params=Pm(e.params,this.readVPS(r.data)),this.initVPS=r.data),e.vps=[r.data];break;case 33:if(o=!0,s=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],r.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let t=this.readSPS(r.data);e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],typeof e.params!=`object`&&(e.params={});for(let n in t.params)e.params[n]=t.params[n]}this.pushParameterSet(e.sps,r.data,e.vps),a||=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts),a.key=!0;break;case 34:if(o=!0,typeof e.params==`object`){if(!e.pps){e.pps=[];let t=this.readPPS(r.data);for(let n in t)e.params[n]=t[n]}this.pushParameterSet(e.pps,r.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(c=a)!=null&&c.frame&&(this.pushAccessUnit(a,e),a=null),a||=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts);break;default:o=!1;break}a&&o&&a.units.push(r)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,n){(n&&n[0]===this.initVPS||!n&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),n=0;for(let r=0;r=2&&e[r]===3&&e[r-1]===0&&e[r-2]===0||(t[n]=e[r],n++);return new Uint8Array(t.buffer,0,n)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&=null}readVPS(e){let t=new Mb(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let n=t.readBits(3),r=t.readBoolean();return{numTemporalLayers:n+1,temporalIdNested:r}}readSPS(e){let t=new Mb(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let n=t.readBits(3);t.readBoolean();let r=t.readBits(2),i=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),s=t.readUByte(),c=t.readUByte(),l=t.readUByte(),u=t.readUByte(),d=t.readUByte(),f=t.readUByte(),p=t.readUByte(),m=t.readUByte(),h=t.readUByte(),g=t.readUByte(),_=[],v=[];for(let e=0;e0)for(let e=n;e<8;e++)t.readBits(2);for(let e=0;e1&&t.readEG();for(let e=0;e0&&e<16?(ee=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],P=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):e===255&&(ee=t.readBits(16),P=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),ie=t.readBoolean(),ie&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ne=t.readBits(32),re=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let e=t.readBoolean(),r=t.readBoolean(),i=!1;(e||r)&&(i=t.readBoolean(),i&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),i&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let a=0;a<=n;a++){te=t.readBoolean();let n=te||t.readBoolean(),a=!1;n?t.readEG():a=t.readBoolean();let o=a?1:t.readUEG()+1;if(e)for(let e=0;e>e&1)<<31-e)>>>0;let le=ce.toString(16);return a===1&&le===`2`&&(le=`6`),{codecString:`hvc1.${oe}${a}.${le}.${i?`H`:`L`}${g}.B0`,params:{general_tier_flag:i,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[o,s,c,l],general_constraint_indicator_flags:[u,d,f,p,m,h],general_level_idc:g,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:O,min_spatial_segmentation_idc:N,chroma_format_idc:y,frame_rate:{fixed:te,fps:re/ne}},width:F,height:ae,pixelRatio:[ee,P]}}readPPS(e){let t=new Mb(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);let n=t.readBoolean(),r=t.readBoolean(),i=1;return r&&n?i=0:r?i=3:n&&(i=2),{parallelismType:i}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}},Fb=188,Ib=class e{constructor(e,t,n,r){this.logger=void 0,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._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=n,this.logger=r,this.videoParser=null}static probe(t,n){let r=e.syncOffset(t);return r>0&&n.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),r!==-1}static syncOffset(e){let t=e.length,n=Math.min(Fb*5,t-Fb)+1,r=0;for(;r1&&(a===0&&o>2||s+Fb>n))return a}else if(o)return-1;else break;r++}return-1}static createTrack(e,t){return{container:e===`video`||e===`audio`?`video/mp2t`:void 0,type:e,id:hh[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e===`audio`?t:void 0}}resetInitSegment(t,n,r,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack(`video`),this._videoTrack.duration=i,this._audioTrack=e.createTrack(`audio`,i),this._id3Track=e.createTrack(`id3`),this._txtTrack=e.createTrack(`text`),this._audioTrack.segmentCodec=`aac`,this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=n,this.videoCodec=r}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:n}=this;e&&(e.pesData=null),t&&(t.pesData=null),n&&(n.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,n,r=!1,i=!1){r||(this.sampleAes=null);let a,o=this._videoTrack,s=this._audioTrack,c=this._id3Track,l=this._txtTrack,u=o.pid,d=o.pesData,f=s.pid,p=c.pid,m=s.pesData,h=c.pesData,g=null,_=this.pmtParsed,v=this._pmtId,y=t.length;if(this.remainderData&&=(t=Fh(this.remainderData,t),y=t.length,null),y>4,x;if(y>1){if(x=e+5+t[e+4],x===e+Fb)continue}else x=e+4;switch(i){case u:n&&(d&&(a=Hb(d,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,l,a,!1)),d={data:[],size:0}),d&&(d.data.push(t.subarray(x,e+Fb)),d.size+=e+Fb-x);break;case f:if(n){if(m&&(a=Hb(m,this.logger)))switch(s.segmentCodec){case`aac`:this.parseAACPES(s,a);break;case`mp3`:this.parseMPEGPES(s,a);break;case`ac3`:this.parseAC3PES(s,a);break}m={data:[],size:0}}m&&(m.data.push(t.subarray(x,e+Fb)),m.size+=e+Fb-x);break;case p:n&&(h&&(a=Hb(h,this.logger))&&this.parseID3PES(c,a),h={data:[],size:0}),h&&(h.data.push(t.subarray(x,e+Fb)),h.size+=e+Fb-x);break;case 0:n&&(x+=t[x]+1),v=this._pmtId=Rb(t,x);break;case v:{n&&(x+=t[x]+1);let i=zb(t,x,this.typeSupported,r,this.observer,this.logger);u=i.videoPid,u>0&&(o.pid=u,o.segmentCodec=i.segmentVideoCodec),f=i.audioPid,f>0&&(s.pid=f,s.segmentCodec=i.segmentAudioCodec),p=i.id3Pid,p>0&&(c.pid=p),g!==null&&!_&&(this.logger.warn(`MPEG-TS PMT found at ${e} after unknown PID '${g}'. Backtracking to sync byte @${b} to parse all TS packets.`),g=null,e=b-188),_=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=i;break}}else x++;x>0&&Bb(this.observer,Error(`Found ${x} TS packet/s that do not start with 0x47`),void 0,this.logger),o.pesData=d,s.pesData=m,c.pesData=h;let S={audioTrack:s,videoTrack:o,id3Track:c,textTrack:l};return i&&this.extractRemainingSamples(S),S}flush(){let{remainderData:e}=this;this.remainderData=null;let t;return t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){let{audioTrack:t,videoTrack:n,id3Track:r,textTrack:i}=e,a=n.pesData,o=t.pesData,s=r.pesData,c;if(a&&(c=Hb(a,this.logger))?(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(n,i,c,!0),n.pesData=null)):n.pesData=a,o&&(c=Hb(o,this.logger))){switch(t.segmentCodec){case`aac`:this.parseAACPES(t,c);break;case`mp3`:this.parseMPEGPES(t,c);break;case`ac3`:this.parseAC3PES(t,c);break}t.pesData=null}else o!=null&&o.size&&this.logger.log(`last AAC PES packet truncated,might overlap between fragments`),t.pesData=o;s&&(c=Hb(s,this.logger))?(this.parseID3PES(r,c),r.pesData=null):r.pesData=s}demuxSampleAes(e,t,n){let r=this.demux(e,n,!0,!this.config.progressive),i=this.sampleAes=new Ab(this.observer,this.config,t);return this.decrypt(r,i)}readyVideoParser(e){this.videoParser===null&&(e===`avc`?this.videoParser=new Nb:e===`hevc`&&(this.videoParser=new Pb))}decrypt(e,t){return new Promise(n=>{let{audioTrack:r,videoTrack:i}=e;r.samples&&r.segmentCodec===`aac`?t.decryptAacSamples(r.samples,0,()=>{i.samples?t.decryptAvcSamples(i.samples,0,0,()=>{n(e)}):n(e)}):i.samples&&t.decryptAvcSamples(i.samples,0,0,()=>{n(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let n=0,r=this.aacOverFlow,i=t.data;if(r){this.aacOverFlow=null;let t=r.missing,a=r.sample.unit.byteLength;if(t===-1)i=Fh(r.sample.unit,i);else{let o=a-t;r.sample.unit.set(i.subarray(0,t),o),e.samples.push(r.sample),n=r.missing}}let a,o;for(a=n,o=i.length;a0;)o+=s}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn(`[tsdemuxer]: ID3 PES unknown PTS`);return}let n=Pm({},t,{type:this._videoTrack?sb.emsg:sb.audioId3,duration:1/0});e.samples.push(n)}};function Lb(e,t){return((e[t+1]&31)<<8)+e[t+2]}function Rb(e,t){return(e[t+10]&31)<<8|e[t+11]}function zb(e,t,n,r,i,a){let o={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:`avc`,segmentAudioCodec:`aac`},s=(e[t+1]&15)<<8|e[t+2],c=t+3+s-4,l=(e[t+10]&15)<<8|e[t+11];for(t+=12+l;t0){let r=t+5,i=c;for(;i>2;){switch(e[r]){case 106:n.ac3===!0?(o.audioPid=s,o.segmentAudioCodec=`ac3`):a.log(`AC-3 audio found, not supported in this browser for now`);break}let t=e[r+1]+2;r+=t,i-=t}}break;case 194:case 135:return Bb(i,Error(`Unsupported EC-3 in M2TS found`),void 0,a),o;case 36:o.videoPid===-1&&(o.videoPid=s,o.segmentVideoCodec=`hevc`,a.log(`HEVC in M2TS found`));break}t+=c+5}return o}function Bb(e,t,n,r){r.warn(`parsing error: ${t.message}`),e.emit(J.ERROR,J.ERROR,{type:K.MEDIA_ERROR,details:q.FRAG_PARSING_ERROR,fatal:!1,levelRetry:n,error:t,reason:t.message})}function Vb(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function Hb(e,t){let n=0,r,i,a,o,s,c=e.data;if(!e||e.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=Fh(c[0],c[1]),c.splice(1,1);if(r=c[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(i=(r[4]<<8)+r[5],i&&i>e.size-6)return null;let l=r[7];l&192&&(o=(r[9]&14)*536870912+(r[10]&255)*4194304+(r[11]&254)*16384+(r[12]&255)*128+(r[13]&254)/2,l&64?(s=(r[14]&14)*536870912+(r[15]&255)*4194304+(r[16]&254)*16384+(r[17]&255)*128+(r[18]&254)/2,o-s>60*9e4&&(t.warn(`${Math.round((o-s)/9e4)}s delta between PTS and DTS, align them`),o=s)):s=o),a=r[8];let u=a+9;if(e.size<=u)return null;e.size-=u;let d=new Uint8Array(e.size);for(let e=0,t=c.length;et){u-=t;continue}else r=r.subarray(u),t-=u,u=0;d.set(r,n),n+=t}return i&&(i-=a+3),{data:d,pts:o,dts:s,len:i}}return null}var Ub=class{static getSilentFrame(e,t){switch(e){case`mp4a.40.2`:if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2||t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}},Wb=2**32-1,Gb=class e{static init(){e.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let t;for(t in e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);e.HDLR_TYPES={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])};let n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]);e.STTS=e.STSC=e.STCO=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),e.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),e.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);let r=new Uint8Array([105,115,111,109]),i=new Uint8Array([97,118,99,49]),a=new Uint8Array([0,0,0,1]);e.FTYP=e.box(e.types.ftyp,r,a,r,i),e.DINF=e.box(e.types.dinf,e.box(e.types.dref,n))}static box(e,...t){let n=8,r=t.length,i=r;for(;r--;)n+=t[r].byteLength;let a=new Uint8Array(n);for(a[0]=n>>24&255,a[1]=n>>16&255,a[2]=n>>8&255,a[3]=n&255,a.set(e,4),r=0,n=8;r>24&255,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(t){return e.box(e.types.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))}static mfhd(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type===`audio`?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))}static moof(t,n,r){return e.box(e.types.moof,e.mfhd(t),e.traf(r,n))}static moov(t){let n=t.length,r=[];for(;n--;)r[n]=e.trak(t[n]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r,e.mvex(t)))}static mvex(t){let n=t.length,r=[];for(;n--;)r[n]=e.trex(t[n]);return e.box.apply(null,[e.types.mvex,...r])}static mvhd(t,n){n*=t;let r=Math.floor(n/(Wb+1)),i=Math.floor(n%(Wb+1)),a=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,t&255,r>>24,r>>16&255,r>>8&255,r&255,i>>24,i>>16&255,i>>8&255,i&255,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 e.box(e.types.mvhd,a)}static sdtp(t){let n=t.samples||[],r=new Uint8Array(4+n.length),i,a;for(i=0;i>>8&255),n.push(o&255),n=n.concat(Array.prototype.slice.call(a));for(i=0;i>>8&255),r.push(o&255),r=r.concat(Array.prototype.slice.call(a));let s=e.box(e.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n,[t.pps.length],r))),c=t.width,l=t.height,u=t.pixelRatio[0],d=t.pixelRatio[1];return e.box(e.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,c&255,l>>8&255,l&255,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]),s,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,d>>24,d>>16&255,d>>8&255,d&255])))}static esds(e){let t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){let t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(t){return e.box(e.types.mp4a,e.audioStsd(t),e.box(e.types.esds,e.esds(t)))}static mp3(t){return e.box(e.types[`.mp3`],e.audioStsd(t))}static ac3(t){return e.box(e.types[`ac-3`],e.audioStsd(t),e.box(e.types.dac3,t.config))}static stsd(t){let{segmentCodec:n}=t;if(t.type===`audio`){if(n===`aac`)return e.box(e.types.stsd,e.STSD,e.mp4a(t));if(n===`ac3`&&t.config)return e.box(e.types.stsd,e.STSD,e.ac3(t));if(n===`mp3`&&t.codec===`mp3`)return e.box(e.types.stsd,e.STSD,e.mp3(t))}else if(t.pps&&t.sps){if(n===`avc`)return e.box(e.types.stsd,e.STSD,e.avc1(t));if(n===`hevc`&&t.vps)return e.box(e.types.stsd,e.STSD,e.hvc1(t))}else throw Error(`video track missing pps or sps`);throw Error(`unsupported ${t.type} segment codec (${n}/${t.codec})`)}static tkhd(t){let n=t.id,r=(t.duration||0)*(t.timescale||0),i=t.width||0,a=t.height||0,o=Math.floor(r/(Wb+1)),s=Math.floor(r%(Wb+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,n>>24&255,n>>16&255,n>>8&255,n&255,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,s>>24,s>>16&255,s>>8&255,s&255,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,i&255,0,0,a>>8&255,a&255,0,0]))}static traf(t,n){let r=e.sdtp(t),i=t.id,a=Math.floor(n/(Wb+1)),o=Math.floor(n%(Wb+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255])),e.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))}static trex(t){let n=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,n){let r=t.samples||[],i=r.length,a=12+16*i,o=new Uint8Array(a),s,c,l,u,d,f;for(n+=8+a,o.set([+(t.type===`video`),0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255],0),s=0;s>>24&255,l>>>16&255,l>>>8&255,l&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,f>>>24&255,f>>>16&255,f>>>8&255,f&255],12+16*s);return e.box(e.types.trun,o)}static initSegment(t){e.types||e.init();let n=e.moov(t);return Fh(e.FTYP,n)}static hvc1(t){let n=t.params,r=[t.vps,t.sps,t.pps],i=new Uint8Array([1,n.general_profile_space<<6|(n.general_tier_flag?32:0)|n.general_profile_idc,n.general_profile_compatibility_flags[0],n.general_profile_compatibility_flags[1],n.general_profile_compatibility_flags[2],n.general_profile_compatibility_flags[3],n.general_constraint_indicator_flags[0],n.general_constraint_indicator_flags[1],n.general_constraint_indicator_flags[2],n.general_constraint_indicator_flags[3],n.general_constraint_indicator_flags[4],n.general_constraint_indicator_flags[5],n.general_level_idc,240|n.min_spatial_segmentation_idc>>8,255&n.min_spatial_segmentation_idc,252|n.parallelismType,252|n.chroma_format_idc,248|n.bit_depth_luma_minus8,248|n.bit_depth_chroma_minus8,0,parseInt(n.frame_rate.fps),3|n.temporal_id_nested<<2|n.num_temporal_layers<<3|(n.frame_rate.fixed?64:0),r.length]),a=i.length;for(let e=0;e>8,r[e][t].length&255]),a),a+=2,o.set(r[e][t],a),a+=r[e][t].length}let c=e.box(e.types.hvcC,o),l=t.width,u=t.height,d=t.pixelRatio[0],f=t.pixelRatio[1];return e.box(e.types.hvc1,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,l>>8&255,l&255,u>>8&255,u&255,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]),c,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,f>>24,f>>16&255,f>>8&255,f&255])))}};Gb.types=void 0,Gb.HDLR_TYPES=void 0,Gb.STTS=void 0,Gb.STSC=void 0,Gb.STCO=void 0,Gb.STSZ=void 0,Gb.VMHD=void 0,Gb.SMHD=void 0,Gb.STSD=void 0,Gb.FTYP=void 0,Gb.DINF=void 0;var Kb=9e4;function qb(e,t,n=1,r=!1){let i=e*t*n;return r?Math.round(i):i}function Jb(e,t,n=1,r=!1){return qb(e,t,1/n,r)}function Yb(e,t=!1){return qb(e,1e3,1/Kb,t)}function Xb(e,t=1){return qb(e,Kb,1/t)}function Zb(e){let{baseTime:t,timescale:n,trackId:r}=e;return`${t/n} (${t}/${n}) trackId: ${r}`}var Qb=10*1e3,$b=1024,ex=1152,tx=1536,nx=null,rx=null;function ix(e,t,n,r){return{duration:t,size:n,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:+!e}}}var ax=class extends zm{constructor(e,t,n,r){if(super(`mp4-remuxer`,r),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=n,this.ISGenerated=!1,nx===null){let e=(navigator.userAgent||``).match(/Chrome\/(\d+)/i);nx=e?parseInt(e[1]):0}if(rx===null){let e=navigator.userAgent.match(/Safari\/(\d+)/i);rx=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){let t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&Zb(t)} > ${e&&Zb(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log(`reset next timestamp`),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log(`ISGenerated flag reset`),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1,n=e[0].pts,r=e.reduce((e,r)=>{let i=r.pts,a=i-e;return a<-4294967296&&(t=!0,i=ox(i,n),a=i-e),a>0?e:i},n);return t&&this.debug(`PTS rollover detected`),r}remux(e,t,n,r,i,a,o,s){let c,l,u,d,f,p,m=i,h=i,g=e.pid>-1,_=t.pid>-1,v=t.samples.length,y=e.samples.length>0,b=o&&v>0||v>1;if((!g||y)&&(!_||b)||this.ISGenerated||o){if(this.ISGenerated){let e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||t.pixelRatio?.[0]!==e.pixelRatio?.[0]||t.pixelRatio?.[1]!==e.pixelRatio?.[1])||!e&&b||this.nextAudioTs===null&&y)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,i,a));let n=this.isVideoContiguous,r=-1,o;if(b&&(r=sx(t.samples),!n&&this.config.forceKeyFrameOnDiscontinuity))if(p=!0,r>0){this.warn(`Dropped ${r} out of ${v} video samples due to a missing keyframe`);let e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(r),t.dropped+=r,h+=(t.samples[0].pts-e)/t.inputTimeScale,o=h}else r===-1&&(this.warn(`No keyframe found out of ${v} video samples`),p=!1);if(this.ISGenerated){if(y&&b){let n=this.getVideoStartPts(t.samples),r=(ox(e.samples[0].pts,n)-n)/t.inputTimeScale;m+=Math.max(0,r),h+=Math.max(0,-r)}if(y){if(e.samplerate||(this.warn(`regenerate InitSegment as audio detected`),u=this.generateIS(e,t,i,a)),l=this.remuxAudio(e,m,this.isAudioContiguous,a,_||b||s===Y.AUDIO?h:void 0),b){let r=l?l.endPTS-l.startPTS:0;t.inputTimeScale||(this.warn(`regenerate InitSegment as video detected`),u=this.generateIS(e,t,i,a)),c=this.remuxVideo(t,h,n,r)}}else b&&(c=this.remuxVideo(t,h,n,0));c&&(c.firstKeyFrame=r,c.independent=r!==-1,c.firstKeyFramePTS=o)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(f=cx(n,i,this._initPTS,this._initDTS)),r.samples.length&&(d=lx(r,i,this._initPTS))),{audio:l,video:c,initSegment:u,independent:p,text:d,id3:f}}computeInitPts(e,t,n,r){let i=Math.round(n*t),a=ox(e,i);if(a0?e-1:e].dts&&(_=!0)}_&&a.sort(function(e,t){let n=e.dts-t.dts,r=e.pts-t.pts;return n||r}),p=a[0].dts,m=a[a.length-1].dts;let y=m-p,b=y?Math.round(y/(s-1)):f||e.inputTimeScale/30;if(n){let n=p-v,r=n>b,i=n<-1;if((r||i)&&(r?this.warn(`${(e.segmentCodec||``).toUpperCase()}: ${Yb(n,!0)} ms (${n}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||``).toUpperCase()}: ${Yb(-n,!0)} ms (${n}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!i||v>=a[0].pts||nx)){p=v;let e=a[0].pts-n;if(r)a[0].dts=p,a[0].pts=e;else{let t=!0;for(let r=0;re&&t);r++){let e=a[r].pts;if(a[r].dts-=n,a[r].pts-=n,r0?t.dts-a[e-1].dts:b;if(u=e>0?t.pts-a[e-1].pts:b,n.stretchShortVideoTrack&&this.nextAudioTs!==null){let e=Math.floor(n.maxBufferHole*i),a=(r?h+r*i:this.nextAudioTs+l)-t.pts;a>e?(f=a-o,f<0?f=o:D=!0,this.log(`It is approximately ${a/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=o}else f=o}let p=Math.round(t.pts-t.dts);O=Math.min(O,f),A=Math.max(A,f),k=Math.min(k,u),j=Math.max(j,u),o.push(ix(t.key,f,c,p))}if(o.length){if(nx){if(nx<70){let e=o[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(rx&&j-k0&&(r&&Math.abs(_-(h+g))<9e3||Math.abs(ox(p[0].pts,_)-(h+g))<20*c),p.forEach(function(e){e.pts=ox(e.pts,_)}),!n||h<0){let e=p.length;if(p=p.filter(e=>e.pts>=0),e!==p.length&&this.warn(`Removed ${p.length-e} of ${e} samples (initPTS ${g} / ${a})`),!p.length)return;h=i===0?0:r&&!f?Math.max(0,_-g):p[0].pts-g}if(e.segmentCodec===`aac`){let t=this.config.maxAudioFramesDrift;for(let n=0,r=h+g;n=t*c&&l0){x+=m;try{b=new Uint8Array(x)}catch(e){this.observer.emit(J.ERROR,J.ERROR,{type:K.MUX_ERROR,details:q.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:x,reason:`fail allocating audio mdat ${x}`});return}u||(new DataView(b.buffer).setUint32(0,x),b.set(Gb.types.mdat,4))}else return;b.set(i,m);let c=i.byteLength;m+=c,d.push(ix(!0,s,c,0)),y=a}let C=d.length;if(!C)return;let w=d[d.length-1];h=y-g,this.nextAudioTs=h+o*w.duration;let T=u?new Uint8Array:Gb.moof(e.sequenceNumber++,v/o,Pm({},e,{samples:d}));e.samples=[];let E=(v-g)/a,D=this.nextAudioTs/a,O={data1:T,data2:b,startPTS:E,endPTS:D,startDTS:E,endDTS:D,type:`audio`,hasAudio:!0,hasVideo:!1,nb:C};return this.isAudioContiguous=!0,O}};function ox(e,t){let n;if(t===null)return e;for(n=t4294967296;)e+=n;return e}function sx(e){for(let t=0;te.pts-t.pts);let a=e.samples;return e.samples=[],{samples:a}}var ux=class extends zm{constructor(e,t,n,r){super(`passthrough-remuxer`,r),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,n,r){this.audioCodec=t,this.videoCodec=n,this.generateInitSegment(e,r),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:n,videoCodec:r}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:i,video:a}=this.initData=Sh(e);if(t)kh(e,t);else{let e=i||a;e!=null&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}i&&(n=px(i,oh.AUDIO,this)),a&&(r=px(a,oh.VIDEO,this));let o={};i&&a?o.audiovideo={container:`video/mp4`,codec:n+`,`+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:`main`}:i?o.audio={container:`audio/mp4`,codec:n,encrypted:i.encrypted,initSegment:e,id:`audio`}:a?o.video={container:`video/mp4`,codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:`main`}:this.warn(`initSegment does not contain moov or trak boxes.`),this.initTracks=o}remux(e,t,n,r,i,a){var o,s;let{initPTS:c,lastEndTime:l}=this,u={audio:void 0,video:void 0,text:r,id3:n,initSegment:void 0};G(l)||(l=this.lastEndTime=i||0);let d=t.samples;if(!d.length)return u;let f={initPTS:void 0,timescale:void 0,trackId:void 0},p=this.initData;if((o=p)!=null&&o.length||(this.generateInitSegment(d),p=this.initData),!((s=p)!=null&&s.length))return this.warn(`Failed to generate initSegment.`),u;this.emitInitSegment&&=(f.tracks=this.initTracks,!1);let m=Nh(d,p,this),h=p.audio?m[p.audio.id]:null,g=p.video?m[p.video.id]:null,_=dx(g,1/0),v=dx(h,1/0),y=dx(g,0,!0),b=dx(h,0,!0),x=i,S=0,C=h&&(!g||!c&&v<_||c&&c.trackId===p.audio.id),w=C?h:g;if(w){let e=w.timescale,t=w.start-i*e,n=C?p.audio.id:p.video.id;x=w.start/e,S=C?b-v:y-_,(a||!c)&&(fx(c,x,i,S)||e!==c.timescale)&&(c&&this.warn(`Timestamps at playlist time: ${a?``:`~`}${i} ${t/e} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${x-i} (${t}/${e}) trackId: ${n}`),c=null,f.initPTS=t,f.timescale=e,f.trackId=n)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${i}`);c?(f.initPTS=c.baseTime,f.timescale=c.timescale,f.trackId=c.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn(`Could not set initPTS`),f.initPTS=x,f.timescale=1,f.trackId=-1),this.initPTS=c={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});let T=x-c.baseTime/c.timescale,E=T+S;S>0?this.lastEndTime=E:(this.warn(`Duration parsed from mp4 should be greater than zero`),this.resetNextTimestamp());let D=!!p.audio,O=!!p.video,k=``;D&&(k+=`audio`),O&&(k+=`video`);let A=(p.audio?p.audio.encrypted:!1)||(p.video?p.video.encrypted:!1),j={data1:d,startPTS:T,startDTS:T,endPTS:E,endDTS:E,type:k,hasAudio:D,hasVideo:O,nb:1,dropped:0,encrypted:A};u.audio=D&&!O?j:void 0,u.video=O?j:void 0;let M=g?.sampleCount;if(M){let e=g.keyFrameIndex,t=e!==-1;j.nb=M,j.dropped=e===0||this.isVideoContiguous?0:t?e:M,j.independent=t,j.firstKeyFrame=e,t&&g.keyFrameStart&&(j.firstKeyFramePTS=(g.keyFrameStart-c.baseTime)/c.timescale),this.isVideoContiguous||(u.independent=t),this.isVideoContiguous||=t,j.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${M} dropped: ${j.dropped} start: ${j.firstKeyFramePTS||`NA`}`)}return u.initSegment=f,u.id3=cx(n,i,c,c),r.samples.length&&(u.text=lx(r,i,c)),u}};function dx(e,t,n=!1){return e?.start===void 0?t:(e.start+(n?e.duration:0))/e.timescale}function fx(e,t,n,r){if(e===null)return!0;let i=Math.max(r,1),a=t-e.baseTime/e.timescale;return Math.abs(a-n)>i}function px(e,t,n){let r=e.codec;return r&&r.length>4?r:t===oh.AUDIO?r===`ec-3`||r===`ac-3`||r===`alac`?r:r===`fLaC`||r===`Opus`?rg(r,!1):(n.warn(`Unhandled audio codec "${r}" in mp4 MAP`),r||`mp4a`):(n.warn(`Unhandled video codec "${r}" in mp4 MAP`),r||`avc1`)}var mx;try{mx=self.performance.now.bind(self.performance)}catch{mx=Date.now}var hx=[{demux:Ob,remux:ux},{demux:Ib,remux:ax},{demux:Sb,remux:ax},{demux:Eb,remux:ax}];hx.splice(2,0,{demux:wb,remux:ax});var gx=class{constructor(e,t,n,r,i,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=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=e,this.typeSupported=t,this.config=n,this.id=i,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,n,r){let i=n.transmuxing;i.executeStart=mx();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:s}=this;r&&(this.currentTransmuxState=r);let{contiguous:c,discontinuity:l,trackSwitch:u,accurateTimeOffset:d,timeOffset:f,initSegmentChange:p}=r||o,{audioCodec:m,videoCodec:h,defaultInitPts:g,duration:_,initSegmentData:v}=s,y=_x(a,t);if(y&&ev(y.method)){let e=this.getDecrypter(),t=tv(y.method);if(e.isSync()){let r=e.softwareDecrypt(a,y.key.buffer,y.iv.buffer,t);if(n.part>-1){let t=e.flush();r=t&&t.buffer}if(!r)return i.executeEnd=mx(),vx(n);a=new Uint8Array(r)}else return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(a,y.key.buffer,y.iv.buffer,t).then(e=>{let t=this.push(e,null,n);return this.decryptionPromise=null,t}),this.decryptionPromise}let b=this.needsProbing(l,u);if(b){let e=this.configureTransmuxer(a);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(J.ERROR,J.ERROR,{type:K.MEDIA_ERROR,details:q.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),i.executeEnd=mx(),vx(n)}(l||u||p||b)&&this.resetInitSegment(v,m,h,_,t),(l||p||b)&&this.resetInitialTimestamp(g),c||this.resetContiguity();let x=this.transmux(a,y,f,d,n);this.asyncResult=yx(x);let S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,i.executeEnd=mx(),x}flush(e){let t=e.transmuxing;t.executeStart=mx();let{decrypter:n,currentTransmuxState:r,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then(()=>this.flush(e));let a=[],{timeOffset:o}=r;if(n){let t=n.flush();t&&a.push(this.push(t.buffer,null,e))}let{demuxer:s,remuxer:c}=this;if(!s||!c){t.executeEnd=mx();let n=[vx(e)];return this.asyncResult?Promise.resolve(n):n}let l=s.flush(o);return yx(l)?(this.asyncResult=!0,l.then(t=>(this.flushRemux(a,t,e),a))):(this.flushRemux(a,l,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,n){let{audioTrack:r,videoTrack:i,id3Track:a,textTrack:o}=t,{accurateTimeOffset:s,timeOffset:c}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${n.sn}${n.part>-1?` part: `+n.part:``} of ${this.id===Y.MAIN?`level`:`track`} ${n.level}`);let l=this.remuxer.remux(r,i,a,o,c,s,!0,this.id);e.push({remuxResult:l,chunkMeta:n}),n.transmuxing.executeEnd=mx()}resetInitialTimestamp(e){let{demuxer:t,remuxer:n}=this;!t||!n||(t.resetTimeStamp(e),n.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,n,r,i){let{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,n,r),o.resetInitSegment(e,t,n,i))}destroy(){this.demuxer&&=(this.demuxer.destroy(),void 0),this.remuxer&&=(this.remuxer.destroy(),void 0)}transmux(e,t,n,r,i){let a;return a=t&&t.method===`SAMPLE-AES`?this.transmuxSampleAes(e,t,n,r,i):this.transmuxUnencrypted(e,n,r,i),a}transmuxUnencrypted(e,t,n,r){let{audioTrack:i,videoTrack:a,id3Track:o,textTrack:s}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,a,o,s,t,n,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,n,r,i){return this.demuxer.demuxSampleAes(e,t,n).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,n,r,!1,this.id),chunkMeta:i}))}configureTransmuxer(e){let{config:t,observer:n,typeSupported:r}=this,i;for(let t=0,n=hx.length;t0&&t?.key!=null&&t.iv!==null&&t.method!=null&&(n=t),n}var vx=e=>({remuxResult:{},chunkMeta:e});function yx(e){return`then`in e&&e.then instanceof Function}var bx=class{constructor(e,t,n,r,i){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=n,this.duration=r,this.defaultInitPts=i||null}},xx=class{constructor(e,t,n,r,i,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=n,this.trackSwitch=r,this.timeOffset=i,this.initSegmentChange=a}},Sx=0,Cx=class{constructor(e,t,n,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Sx++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=e=>{let t=e.data,n=this.hls;if(!(!n||!(t!=null&&t.event)||t.instanceNo!==this.instanceNo))switch(t.event){case`init`:{let e=this.workerContext?.objectURL;e&&self.URL.revokeObjectURL(e);break}case`transmuxComplete`:this.handleTransmuxComplete(t.data);break;case`flush`:this.onFlush(t.data);break;case`workerLog`:n.logger[t.data.logType]&&n.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,n.trigger(t.event,t.data);break}},this.onWorkerError=e=>{if(!this.hls)return;let t=Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(J.ERROR,{type:K.OTHER_ERROR,details:q.INTERNAL_EXCEPTION,fatal:!1,event:`demuxerWorker`,error:t})};let i=e.config;this.hls=e,this.id=t,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=n,this.onFlush=r;let a=(e,t)=>{t||={},t.frag=this.frag||void 0,e===J.ERROR&&(t=t,t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new by,this.observer.on(J.FRAG_DECRYPTED,a),this.observer.on(J.ERROR,a);let o=lg(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<`u`){let n=this.hls.logger;if(i.workerPath||Cy()){try{i.workerPath?(n.log(`loading Web Worker ${i.workerPath} for "${t}"`),this.workerContext=Ty(i.workerPath)):(n.log(`injecting Web Worker for "${t}"`),this.workerContext=wy());let{worker:e}=this.workerContext;e.addEventListener(`message`,this.onWorkerMessage),e.addEventListener(`error`,this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:`init`,typeSupported:o,id:t,config:Pg(i)})}catch(r){n.warn(`Error setting up "${t}" Web Worker, fallback to inline`,r),this.terminateWorker(),this.error=null,this.transmuxer=new gx(this.observer,o,i,``,t,e.logger)}return}}this.transmuxer=new gx(this.observer,o,i,``,t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=Sx++;let t=this.hls.config,n=lg(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:`reset`,resetNo:e,typeSupported:n,id:this.id,config:Pg(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener(`message`,this.onWorkerMessage),e.removeEventListener(`error`,this.onWorkerError),Ey(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,n,r,i,a,o,s,c,l){c.transmuxing.start=self.performance.now();let{instanceNo:u,transmuxer:d}=this,f=a?a.start:i.start,p=i.decryptdata,m=this.frag,h=!(m&&i.cc===m.cc),g=!(m&&c.level===m.level),_=m?c.sn-m.sn:-1,v=this.part?c.part-this.part.index:-1,y=_===0&&c.id>1&&c.id===m?.stats.chunkCount,b=!g&&(_===1||_===0&&(v===1||y&&v<=0)),x=self.performance.now();(g||_||i.stats.parsing.start===0)&&(i.stats.parsing.start=x),a&&(v||!b)&&(a.stats.parsing.start=x);let S=!(m&&i.initSegment?.url===m.initSegment?.url),C=new xx(h,b,s,g,f,S);if(!b||h||S){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${c.sn}${c.part>-1?` part: `+c.part:``} ${this.id===Y.MAIN?`level`:`track`}: ${c.level} id: ${c.id} discontinuity: ${h} trackSwitch: ${g} contiguous: ${b} accurateTimeOffset: ${s} timeOffset: ${f} initSegmentChange: ${S}`);let e=new bx(n,r,t,o,l);this.configureTransmuxer(e)}if(this.frag=i,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:`demux`,data:e,decryptdata:p,chunkMeta:c,state:C},e instanceof ArrayBuffer?[e]:[]);else if(d){let t=d.push(e,p,c,C);yx(t)?t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,c,`transmuxer-interface push error`)}):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:n}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:`flush`,chunkMeta:e});else if(n){let t=n.flush(e);yx(t)?t.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,`transmuxer-interface flush error`)}):this.handleFlushResult(t,e)}}transmuxerError(e,t,n){this.hls&&(this.error=e,this.hls.trigger(J.ERROR,{type:K.MEDIA_ERROR,details:q.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:n}))}handleFlushResult(e,t){e.forEach(e=>{this.handleTransmuxComplete(e)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:n}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:`configure`,config:e}):n&&n.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},wx=100,Tx=class extends py{constructor(e,t,n){super(e,t,n,`audio-stream-controller`,Y.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(J.LEVEL_LOADED,this.onLevelLoaded,this),e.on(J.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(J.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(J.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(J.BUFFER_RESET,this.onBufferReset,this),e.on(J.BUFFER_CREATED,this.onBufferCreated,this),e.on(J.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(J.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(J.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(J.FRAG_LOADING,this.onFragLoading,this),e.on(J.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(J.LEVEL_LOADED,this.onLevelLoaded,this),e.off(J.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(J.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(J.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(J.BUFFER_RESET,this.onBufferReset,this),e.off(J.BUFFER_CREATED,this.onBufferCreated,this),e.off(J.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(J.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(J.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(J.FRAG_LOADING,this.onFragLoading,this),e.off(J.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:n,initPTS:r,timescale:i,trackId:a}){if(n===Y.MAIN){let e=t.cc,n=this.fragCurrent;if(this.initPTS[e]={baseTime:r,timescale:i,trackId:a},this.log(`InitPTS for cc: ${e} found from main: ${r/i} (${r}/${i}) trackId: ${a}`),this.mainAnchor=t,this.state===$.WAITING_INIT_PTS){let n=this.waitingData;(!n&&!this.loadingParts||n&&n.frag.cc!==e)&&this.syncWithAnchor(t,n?.frag)}else !this.hls.hasEnoughToStart&&n&&n.cc!==e?(n.abortRequests(),this.syncWithAnchor(t,n)):this.state===$.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){let n=this.mainFragLoading?.frag||null;if(t&&n?.cc===t.cc)return;let r=(n||e).cc,i=t_(this.getLevelDetails(),r,this.getLoadPosition());i&&(this.log(`Syncing with main frag at ${i.start} cc ${i.cc}`),this.startFragRequested=!1,this.nextLoadPosition=i.start,this.resetLoadingState(),this.state===$.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=$.STOPPED;return}let n=this.lastCurrentTime;this.stopLoad(),this.setInterval(wx),n>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),e=n,this.state=$.IDLE):this.state=$.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case $.IDLE:this.doTickIdle();break;case $.WAITING_TRACK:{let{levels:e,trackId:t}=this,n=e?.[t],r=n?.details;if(r&&!this.waitForLive(n)){if(this.waitForCdnTuneIn(r))break;this.state=$.WAITING_INIT_PTS}break}case $.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case $.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:n,cache:r,complete:i}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=$.FRAG_LOADING;let e={frag:t,part:n,payload:r.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),i&&super._handleFragmentLoadComplete(e)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=$.IDLE}}this.onTickEnd()}resetLoadingState(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){let{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){let{hls:e,levels:t,media:n,trackId:r}=this,i=e.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!i.startFragPrefetch)||!(t!=null&&t[r]))return;let a=t[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o)){this.state=$.WAITING_TRACK,this.startFragRequested=!1;return}let s=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&s&&(this.bufferFlushed=!1,this.afterBufferFlushed(s,oh.AUDIO,Y.AUDIO));let c=this.getFwdBufferInfo(s,Y.AUDIO);if(c===null)return;if(!this.switchingTrack&&this._streamEnded(c,o)){e.trigger(J.BUFFER_EOS,{type:`audio`}),this.state=$.ENDED;return}let l=c.len,u=e.maxBufferLength,d=o.fragments,f=d[0].start,p=this.getLoadPosition(),m=this.flushing?p:c.end;if(this.switchingTrack&&n){let e=p;o.PTSKnown&&ef||c.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track`),n.currentTime=f+.05)}if(l>=u&&!this.switchingTrack&&mg.end){let e=this.fragmentTracker.getFragAtPos(m,Y.MAIN);e&&e.end>g.end&&(g=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(h.start>g.end)return}this.loadFragment(h,a,m)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(e=>new kg(e))}onAudioTrackSwitching(e,t){let n=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),n?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==$.STOPPED&&(this.setInterval(wx),this.state=$.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;let n=this.cachedTrackLoadedData;n&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(J.AUDIO_TRACK_LOADED,n))}onAudioTrackLoaded(e,t){var n;let{levels:r}=this,{details:i,id:a,groupId:o,track:s}=t;if(!r){this.warn(`Audio tracks reset while loading track ${a} "${s.name}" of "${o}"`);return}let c=this.mainDetails;if(!c||i.endCC>c.endCC||c.expired){this.cachedTrackLoadedData=t,this.state!==$.STOPPED&&(this.state=$.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${s.name}" of "${o}" loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:``},duration:${i.totalduration}`);let l=r[a],u=0;if(i.live||(n=l.details)!=null&&n.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;l.details&&(u=this.alignPlaylists(i,l.details,this.levelLastLoaded?.details)),i.alignedSliding||(cy(i,c),i.alignedSliding||ly(i,c),u=i.fragmentStart)}l.details=i,this.levelLastLoaded=l,this.startFragRequested||this.setStartPosition(c,u),this.hls.trigger(J.AUDIO_TRACK_UPDATED,{details:i,id:a,groupId:t.groupId}),this.state===$.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=$.IDLE),this.tick()}_handleFragmentLoadProgress(e){let t=e.frag,{part:n,payload:r}=e,{config:i,trackId:a,levels:o}=this;if(!o){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${t.sn} of level ${t.level} will not be buffered`);return}let s=o[a];if(!s){this.warn(`Audio track is undefined on fragment load progress`);return}let c=s.details;if(!c){this.warn(`Audio track details undefined on fragment load progress`),this.removeUnbufferedFrags(t.start);return}let l=i.defaultAudioCodec||s.audioCodec||`mp4a.40.2`,u=this.transmuxer;u||=this.transmuxer=new Cx(this.hls,Y.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this));let d=this.initPTS[t.cc],f=t.initSegment?.data;if(d!==void 0){let e=n?n.index:-1,i=e!==-1,a=new F_(t.level,t.sn,t.stats.chunkCount,r.byteLength,e,i);u.push(r,f,l,``,t,n,c.totalduration,!1,a,d)}else{this.log(`Unknown video PTS for cc ${t.cc}, waiting for video PTS before demuxing audio frag ${t.sn} of [${c.startSN} ,${c.endSN}],track ${a}`);let{cache:e}=this.waitingData=this.waitingData||{frag:t,part:n,cache:new hy,complete:!1};e.push(new Uint8Array(r)),this.state!==$.STOPPED&&(this.state=$.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;let n=t.tracks.audio;n&&(this.mediaBuffer=n.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===Y.MAIN&&ch(t.frag)&&(this.mainFragLoading=t,this.state===$.IDLE&&this.tick())}onFragBuffered(e,t){let{frag:n,part:r}=t;if(n.type!==Y.AUDIO){!this.audioOnly&&n.type===Y.MAIN&&!n.elementaryStreams.video&&!n.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${r?` p: `+r.index:``} of level ${n.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:`false`}`);return}if(ch(n)){this.fragPrevious=n;let e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(J.AUDIO_TRACK_SWITCHED,Im({},e)))}this.fragBufferedComplete(n,r),this.media&&this.tick()}onError(e,t){if(t.fatal){this.state=$.ERROR;return}switch(t.details){case q.FRAG_GAP:case q.FRAG_PARSING_ERROR:case q.FRAG_DECRYPT_ERROR:case q.FRAG_LOAD_ERROR:case q.FRAG_LOAD_TIMEOUT:case q.KEY_LOAD_ERROR:case q.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Y.AUDIO,t);break;case q.AUDIO_TRACK_LOAD_ERROR:case q.AUDIO_TRACK_LOAD_TIMEOUT:case q.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===$.WAITING_TRACK&&t.context?.type===Am.AUDIO_TRACK&&(this.state=$.IDLE);break;case q.BUFFER_ADD_CODEC_ERROR:case q.BUFFER_APPEND_ERROR:if(t.parent!==`audio`)return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case q.BUFFER_FULL_ERROR:if(t.parent!==`audio`)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,1/0,`audio`));break;case q.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==oh.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==oh.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===$.ENDED&&(this.state=$.IDLE);let e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,Y.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;let n=`audio`,{hls:r}=this,{remuxResult:i,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:s,part:c,level:l}=o,{details:u}=l,{audio:d,text:f,id3:p,initSegment:m}=i;if(this.fragContextChanged(s)||!u){this.fragmentTracker.removeFragment(s);return}if(this.state=$.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),m!=null&&m.tracks){let e=s.initSegment||s;if(this.unhandledEncryptionError(m,s))return;this._bufferInitSegment(l,m.tracks,e,a),r.trigger(J.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:n,tracks:m.tracks})}if(d){let{startPTS:e,endPTS:t,startDTS:n,endDTS:r}=d;c&&(c.elementaryStreams[oh.AUDIO]={startPTS:e,endPTS:t,startDTS:n,endDTS:r}),s.setElementaryStreamInfo(oh.AUDIO,e,t,n,r),this.bufferFragmentData(d,s,c,a)}if(p!=null&&(t=p.samples)!=null&&t.length){let e=Pm({id:n,frag:s,details:u},p);r.trigger(J.FRAG_PARSING_METADATA,e)}if(f){let e=Pm({id:n,frag:s,details:u},f);r.trigger(J.FRAG_PARSING_USERDATA,e)}}_bufferInitSegment(e,t,n,r){if(this.state!==$.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let i=t.audio;i.id=Y.AUDIO;let a=e.audioCodec;this.log(`Init audio buffer, container:${i.container}, codecs[level/parsed]=[${a}/${i.codec}]`),a&&a.split(`,`).length===1&&(i.levelCodec=a),this.hls.trigger(J.BUFFER_CODECS,t);let o=i.initSegment;if(o!=null&&o.byteLength){let e={type:`audio`,frag:n,part:null,chunkMeta:r,parent:n.type,data:o};this.hls.trigger(J.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===h_.NOT_LOADED||r===h_.PARTIAL){var i;if(!ch(e))this._loadInitSegment(e,t);else if((i=t.details)!=null&&i.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=$.WAITING_INIT_PTS;let n=this.mainDetails;n&&n.fragmentStart!==t.details.fragmentStart&&ly(t.details,n)}else super.loadFragment(e,t,n)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){let{name:t,lang:n,assocLang:r,characteristics:i,audioCodec:a,channels:o}=this.bufferedTrack;Vg({name:t,lang:n,assocLang:r,characteristics:i,audioCodec:a,channels:o},e,Wg)||(qg(e.url,this.hls)?(this.log(`Switching audio track : flushing all audio`),super.flushMainBuffer(0,1/0,`audio`),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){let{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(J.AUDIO_TRACK_SWITCHED,Im({},e))}},Ex=class extends zm{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,n){let r=t?.renditionReports;if(r){let i=-1;for(let n=0;n=0&&e>t.partTarget&&(o+=1)}let s=n&&Dg(n);return new Og(a,o>=0?o:void 0,s)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,n){let{details:r,stats:i}=t,a=self.performance.now(),o=i.loading.first?Math.max(0,a-i.loading.first):0;r.advancedDateTime=Date.now()-o;let s=this.hls.config.timelineOffset;if(s!==r.appliedTimelineOffset){let e=Math.max(s||0,0);r.appliedTimelineOffset=e,r.fragments.forEach(t=>{t.setStart(t.playlistOffset+e)})}if(r.live||n!=null&&n.live){let s=`levelInfo`in t?t.levelInfo:t.track;if(r.reloaded(n),n&&r.fragments.length>0){Uv(n,r,this);let e=r.playlistParsingError;if(e){this.warn(e);let n=this.hls;if(!n.config.ignorePlaylistParsingErrors){let{networkDetails:a}=t;n.trigger(J.ERROR,{type:K.NETWORK_ERROR,details:q.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:e,reason:e.message,level:t.level||void 0,parent:r.fragments[0]?.type,networkDetails:a,stats:i});return}r.playlistParsingError=null}}r.requestScheduled===-1&&(r.requestScheduled=i.loading.start);let c=this.hls.mainForwardBufferInfo,l=c?c.end-c.len:0,u=Xv(r,(r.edge-l)*1e3);if(r.requestScheduled+u0){if(h>r.targetduration*3)this.log(`Playlist last advanced ${m.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,p=void 0;else if(n!=null&&n.tuneInGoal&&h-r.partTarget>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${g} with playlist age: ${r.age}`),g=0;else{let e=Math.floor(g/r.targetduration);if(f+=e,p!==void 0){let e=Math.round(g%r.targetduration/r.partTarget);p+=e}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${m.toFixed(2)}s goal: ${g} skip sn ${e} to part ${p}`)}r.tuneInGoal=g}if(d=this.getDeliveryDirectives(r,t.deliveryDirectives,f,p),e||!u){r.requestScheduled=a,this.loadingPlaylist(s,d);return}}else (r.canBlockReload||r.canSkipUntil)&&(d=this.getDeliveryDirectives(r,t.deliveryDirectives,f,p));d&&f!==void 0&&r.canBlockReload&&(r.requestScheduled=i.loading.first+Math.max(u-o*2,u/2)),this.scheduleLoading(s,d,r)}else this.clearTimer()}scheduleLoading(e,t,n){let r=n||e.details;if(!r){this.loadingPlaylist(e,t);return}let i=self.performance.now(),a=r.requestScheduled;if(i>=a){this.loadingPlaylist(e,t);return}let o=a-i;this.log(`reload live playlist ${e.name||e.bitrate+`bps`} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,n,r){let i=Dg(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(n=t.msn,r=t.part,i=Eg.No),new Og(n,r,i)}checkRetry(e){let t=e.details,n=n_(e),r=e.errorAction,{action:i,retryCount:a=0,retryConfig:o}=r||{},s=!!r&&!!o&&(i===d_.RetryRequest||!r.resolved&&i===d_.SendAlternateToPenaltyBox);if(s){var c;if(a>=o.maxNumRetry)return!1;if(n&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{let e=o_(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),e),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,r.resolved=!0}return s}};function Dx(e,t){if(e.length!==t.length)return!1;for(let n=0;ne[n]!==t[n])}function kx(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||``).toLowerCase())}var Ax=class extends Ex{constructor(e){super(e,`audio-track-controller`),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){let{hls:e}=this;e.on(J.MANIFEST_LOADING,this.onManifestLoading,this),e.on(J.MANIFEST_PARSED,this.onManifestParsed,this),e.on(J.LEVEL_LOADING,this.onLevelLoading,this),e.on(J.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(J.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(J.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(J.MANIFEST_LOADING,this.onManifestLoading,this),e.off(J.MANIFEST_PARSED,this.onManifestParsed,this),e.off(J.LEVEL_LOADING,this.onLevelLoading,this),e.off(J.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(J.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(J.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){let{id:n,groupId:r,details:i}=t,a=this.tracksInGroup[n];if(!a||a.groupId!==r){this.warn(`Audio track with id:${n} and group:${r} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Audio track ${n} "${a.name}" lang:${a.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let n=t.audioGroups||null,r=this.groupIds,i=this.currentTrack;if(!n||r?.length!==n?.length||n!=null&&n.some(e=>r?.indexOf(e)===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;let e=this.tracks.filter(e=>!n||n.indexOf(e.groupId)!==-1);if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=e;let t=this.hls.config.audioPreference;if(!i&&t){let n=Bg(t,e,Wg);if(n>-1)i=e[n];else{let e=Bg(t,this.tracks);i=this.tracks[e]}}let r=this.findTrackId(i);r===-1&&i&&(r=this.findTrackId(null));let a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${n?.join(`,`)}`),this.hls.trigger(J.AUDIO_TRACKS_UPDATED,a);let o=this.trackId;if(r!==-1&&o===-1)this.setAudioTrack(r);else if(e.length&&o===-1){let t=Error(`No audio track selected for current audio group-ID(s): ${this.groupIds?.join(`,`)} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(J.ERROR,{type:K.MEDIA_ERROR,details:q.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){t.fatal||!t.context||t.context.type===Am.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let n=this.allAudioTracks;if(this.selectDefaultTrack=!1,n.length){let r=this.currentTrack;if(r&&Vg(e,r,Wg))return r;let i=Bg(e,this.tracksInGroup,Wg);if(i>-1){let e=this.tracksInGroup[i];return this.setAudioTrack(i),e}else if(r){let r=t.loadLevel;r===-1&&(r=t.firstAutoLevel);let i=Gg(e,t.levels,n,r,Wg);if(i===-1)return null;t.nextLoadLevel=i}if(e.channels||e.audioCodec){let t=Bg(e,n);if(t>-1)return n[t]}}}return null}setAudioTrack(e){let t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;let n=this.currentTrack,r=t[e],i=r.details&&!r.details.live;if(e===this.trackId&&r===n&&i||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(J.AUDIO_TRACK_SWITCHING,Im({},r)),i))return;let a=this.switchParams(r.url,n?.details,r.details);this.loadPlaylist(a)}findTrackId(e){let t=this.tracksInGroup;for(let n=0;n{let n={label:`async-blocker`,execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(n,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){let n={label:`async-blocker-prepend`,execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(n)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{let t=e[0]?.label;(t===`async-blocker`||t===`async-blocker-prepend`)&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){this.queues!==null&&this.queues.audio[0]===e&&this.shiftAndExecuteNext(`audio`)}executeNext(e){if(this.queues===null||this.tracks===null)return;let t=this.queues[e];if(t.length){let n=t[0];try{n.execute()}catch(t){if(n.onError(t),this.queues===null||this.tracks===null)return;let r=this.tracks[e]?.buffer;r!=null&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){return this.queues?.[e][0]||null}toString(){let{queues:e,tracks:t}=this;return e===null||t===null?``:` ${this.list(`video`)} ${this.list(`audio`)} ${this.list(`audiovideo`)}}`}list(e){var t,n;return(t=this.queues)!=null&&t[e]||(n=this.tracks)!=null&&n[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:``}listSbInfo(e){let t=this.tracks?.[e],n=t?.buffer;return n?`SourceBuffer${n.updating?` updating`:``}${t.ended?` ended`:``}${t.ending?` ending`:``}`:`none`}listOps(e){return this.queues?.[e].map(e=>e.label).join(`, `)||``}},Mx=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Nx=`HlsJsTrackRemovedError`,Px=class extends Error{constructor(e){super(e),this.name=Nx}},Fx=class extends zm{constructor(e,t){super(`buffer-controller`,e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=e=>{this.hls&&this.mediaSource?.readyState===`open`&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{let{media:t,mediaSource:n}=this;e&&this.log(`Media source opened`),!(!t||!n)&&(n.removeEventListener(`sourceopen`,this._onMediaSourceOpen),t.removeEventListener(`emptied`,this._onMediaEmptied),this.updateDuration(),this.hls.trigger(J.MEDIA_ATTACHED,{media:t,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log(`Media source closed`)},this._onMediaSourceEnded=()=>{this.log(`Media source ended`)},this._onMediaEmptied=()=>{let{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=Ym(Jm(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&=(this.operationQueue.destroy(),null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){let{hls:e}=this;e.on(J.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(J.MANIFEST_LOADING,this.onManifestLoading,this),e.on(J.MANIFEST_PARSED,this.onManifestParsed,this),e.on(J.BUFFER_RESET,this.onBufferReset,this),e.on(J.BUFFER_APPENDING,this.onBufferAppending,this),e.on(J.BUFFER_CODECS,this.onBufferCodecs,this),e.on(J.BUFFER_EOS,this.onBufferEos,this),e.on(J.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(J.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(J.FRAG_PARSED,this.onFragParsed,this),e.on(J.FRAG_CHANGED,this.onFragChanged,this),e.on(J.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(J.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(J.MANIFEST_LOADING,this.onManifestLoading,this),e.off(J.MANIFEST_PARSED,this.onManifestParsed,this),e.off(J.BUFFER_RESET,this.onBufferReset,this),e.off(J.BUFFER_APPENDING,this.onBufferAppending,this),e.off(J.BUFFER_CODECS,this.onBufferCodecs,this),e.off(J.BUFFER_EOS,this.onBufferEos,this),e.off(J.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(J.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(J.FRAG_PARSED,this.onFragParsed,this),e.off(J.FRAG_CHANGED,this.onFragChanged,this),e.off(J.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let n={};if(this.operationQueue){let e=this.isUpdating();e||this.operationQueue.removeBlockers();let t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?` operations in queue`:``}${e?` updating SourceBuffer(s)`:``} ${this.operationQueue}`),this.operationQueue.destroy()}let r=this.transferData;return!this.sourceBufferCount&&r&&r.mediaSource===t?Pm(n,r.tracks):this.sourceBuffers.forEach(e=>{let[t]=e;t&&(n[t]=Pm({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null}),{media:e,mediaSource:t,tracks:n}}initTracks(){let e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var n;let r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),(n=this.transferData)!=null&&n.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}onMediaAttaching(e,t){let n=this.media=t.media;this.transferData=this.overrides=void 0;let r=Jm(this.appendSource);if(r){let e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let i=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(i),e)this._objectUrl=n.src,this.attachTransferred();else{let e=this._objectUrl=self.URL.createObjectURL(i);if(this.appendSource)try{n.removeAttribute(`src`);let t=self.ManagedMediaSource;n.disableRemotePlayback=n.disableRemotePlayback||t&&i instanceof t,Ix(n),Lx(n,e),n.load()}catch{n.src=e}else n.src=e}n.addEventListener(`emptied`,this._onMediaEmptied)}}assignMediaSource(e){this.log(`${this.transferData?.mediaSource===e?`transferred`:`created`} media source: ${e.constructor?.name}`),e.addEventListener(`sourceopen`,this._onMediaSourceOpen),e.addEventListener(`sourceended`,this._onMediaSourceEnded),e.addEventListener(`sourceclose`,this._onMediaSourceClose),this.appendSource&&(e.addEventListener(`startstreaming`,this._onStartStreaming),e.addEventListener(`endstreaming`,this._onEndStreaming))}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let n=this.tracks,r=t.tracks,i=r?Object.keys(r):null,a=i?i.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(r&&i&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log(`attachTransferred: waiting for SourceBuffer track info`);return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) required tracks: ${Pg(n,(e,t)=>e===`initSegment`?void 0:t)}; transfer tracks: ${Pg(r,(e,t)=>e===`initSegment`?void 0:t)}}`),!Xm(r,n)){t.mediaSource=null,t.tracks=void 0;let i=e.currentTime,a=this.details,o=Math.max(i,a?.fragments[0].start||0);if(o-i>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${i} -> ${o}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(n)}") start time: ${o} currentTime: ${i}`),this.onMediaDetaching(J.MEDIA_DETACHING,{}),this.onMediaAttaching(J.MEDIA_ATTACHING,t),e.currentTime=o;return}this.transferData=void 0,i.forEach(e=>{let t=e,n=r[t];if(n){let e=n.buffer;if(e){let r=this.fragmentTracker,i=n.id;if(r.hasFragments(i)||r.hasParts(i)){let n=Q.getBuffered(e);r.detectEvictedFragments(t,n,i,null,!0)}let a=Rx(t),o=[t,e];this.sourceBuffers[a]=o,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,n)}}}),o(),this.bufferCreated()}else this.log(`attachTransferred: MediaSource w/o SourceBuffers`),o()}get mediaSourceOpenOrEnded(){let e=this.mediaSource?.readyState;return e===`open`||e===`ended`}onMediaDetaching(e,t){let n=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:r,mediaSource:i,_objectUrl:a}=this;if(i){if(this.log(`media source ${n?`transferring`:`detaching`}`),n)this.sourceBuffers.forEach(([e])=>{e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let e=i.readyState===`open`;try{let t=i.sourceBuffers;for(let n=t.length;n--;)e&&t[n].abort(),i.removeSourceBuffer(t[n]);e&&i.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}i.removeEventListener(`sourceopen`,this._onMediaSourceOpen),i.removeEventListener(`sourceended`,this._onMediaSourceEnded),i.removeEventListener(`sourceclose`,this._onMediaSourceClose),this.appendSource&&(i.removeEventListener(`startstreaming`,this._onStartStreaming),i.removeEventListener(`endstreaming`,this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(r.removeEventListener(`emptied`,this._onMediaEmptied),n||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(r.removeAttribute(`src`),this.appendSource&&Ix(r),r.load()):this.warn(`media|source.src was changed by a third party - skip cleanup`)),this.media=null),this.hls.trigger(J.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){let t=this.tracks[e]?.buffer;if(this.removeBuffer(e),t)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Rx(e)]=[null,null];let t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new jx(this.tracks)}onBufferCodecs(e,t){let n=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);let i=`audiovideo`in t&&(n.audio||n.video)||n.audiovideo&&(`audio`in t||`video`in t),a=!i&&this.sourceBufferCount&&this.media&&r.some(e=>!n[e]);if(i||a){this.warn(`Unsupported transition between "${Object.keys(n)}" and "${r}" SourceBuffers`);return}r.forEach(e=>{var r;let{id:i,codec:a,levelCodec:o,container:s,metadata:c,supplemental:l}=t[e],u=n[e],d=(r=this.transferData)==null||(r=r.tracks)==null?void 0:r[e],f=d!=null&&d.buffer?d:u,p=f?.pendingCodec||f?.codec,m=f?.levelCodec;u||=n[e]={buffer:void 0,listeners:[],codec:a,supplemental:l,container:s,levelCodec:o,metadata:c,id:i};let h=ag(p,m),g=h?.replace(Mx,`$1`),_=ag(a,o),v=_?.replace(Mx,`$1`);_&&h&&g!==v&&(e.slice(0,5)===`audio`&&(_=rg(_,this.appendSource)),this.log(`switching codec ${p} to ${_}`),_!==(u.pendingCodec||u.codec)&&(u.pendingCodec=_),u.container=s,this.appendChangeType(e,s,_))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&t.audio?.id===`main`&&(this.log(`Main audio-only`),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{let n=this.tracks[t];return e[t]={id:n.id,container:n.container,codec:n.codec,levelCodec:n.levelCodec},e},{})}appendChangeType(e,t,n){let r=`${t};codecs=${n}`,i={label:`change-type=${r}`,execute:()=>{let i=this.tracks[e];if(i){let a=i.buffer;a!=null&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),a.changeType(r),i.codec=n,i.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(i,e,this.isPending(this.tracks[e]))}blockAudio(e){let t=e.start,n=t+e.duration*.05;if(this.fragmentTracker.getAppendedFrag(t,Y.MAIN)?.gap===!0)return;let r={label:`block-audio`,execute:()=>{let e=this.tracks.video;(this.lastVideoAppendEnd>n||e!=null&&e.buffer&&Q.isBuffered(e.buffer,n)||this.fragmentTracker.getAppendedFrag(n,Y.MAIN)?.gap===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext(`audio`))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Error executing block-audio operation`,e)}};this.blockedAudioAppend={op:r,frag:e},this.append(r,`audio`,!0)}unblockAudio(){let{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){let{tracks:n}=this,{data:r,type:i,parent:a,frag:o,part:s,chunkMeta:c,offset:l}=t,u=c.buffering[i],{sn:d,cc:f}=o,p=self.performance.now();u.start=p;let m=o.stats.buffering,h=s?s.stats.buffering:null;m.start===0&&(m.start=p),h&&h.start===0&&(h.start=p);let g=n.audio,_=!1;i===`audio`&&g?.container===`audio/mpeg`&&(_=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);let v=n.video,y=v?.buffer;if(y&&d!==`initSegment`){let e=s||o,t=this.blockedAudioAppend;if(i===`audio`&&a!==`main`&&!this.blockedAudioAppend&&!(v.ending||v.ended)){let t=e.start+e.duration*.05,n=y.buffered,r=this.currentOp(`video`);(!n.length&&!r||!r&&!Q.isBuffered(y,t)&&this.lastVideoAppendEnde||n{u.executeStart=self.performance.now();let e=this.tracks[i]?.buffer;e&&(_?this.updateTimestampOffset(e,b,.1,i,d,f):l!==void 0&&G(l)&&this.updateTimestampOffset(e,l,1e-6,i,d,f)),this.appendExecutor(r,i)},onStart:()=>{},onComplete:()=>{let e=self.performance.now();u.executeEnd=u.end=e,m.first===0&&(m.first=e),h&&h.first===0&&(h.first=e);let t={};this.sourceBuffers.forEach(([e,n])=>{e&&(t[e]=Q.getBuffered(n))}),this.appendErrors[i]=0,i===`audio`||i===`video`?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(J.BUFFER_APPENDED,{type:i,frag:o,part:s,chunkMeta:c,parent:o.type,timeRanges:t})},onError:e=>{let t={type:K.MEDIA_ERROR,parent:o.type,details:q.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:s,chunkMeta:c,error:e,err:e,fatal:!1},n=this.media?.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||e.name==`QuotaExceededError`||`quota`in e)t.details=q.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!n)t.errorAction=m_(!0);else if(e.name===Nx&&this.sourceBufferCount===0)t.errorAction=m_(!0);else{let e=++this.appendErrors[i];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${n||`no media error`})`),(e>=this.hls.config.appendErrorMaxRetry||n)&&(t.fatal=!0)}this.hls.trigger(J.ERROR,t)}};this.log(`queuing "${i}" append sn: ${d}${s?` p: `+s.index:``} of ${o.type===Y.MAIN?`level`:`track`} ${o.level} cc: ${f}`),this.append(x,i,this.isPending(this.tracks[i]))}getFlushOp(e,t,n){return this.log(`queuing "${e}" remove ${t}-${n}`),{label:`remove`,execute:()=>{this.removeExecutor(e,t,n)},onStart:()=>{},onComplete:()=>{this.hls.trigger(J.BUFFER_FLUSHED,{type:e})},onError:r=>{this.warn(`Failed to remove ${t}-${n} from "${e}" SourceBuffer`,r)}}}onBufferFlushing(e,t){let{type:n,startOffset:r,endOffset:i}=t;n?this.append(this.getFlushOp(n,r,i),n):this.sourceBuffers.forEach(([e])=>{e&&this.append(this.getFlushOp(e,r,i),e)})}onFragParsed(e,t){let{frag:n,part:r}=t,i=[],a=r?r.elementaryStreams:n.elementaryStreams;a[oh.AUDIOVIDEO]?i.push(`audiovideo`):(a[oh.AUDIO]&&i.push(`audio`),a[oh.VIDEO]&&i.push(`video`)),i.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${n.type} level: ${n.level} sn: ${n.sn}`),this.blockBuffers(()=>{let e=self.performance.now();n.stats.buffering.end=e,r&&(r.stats.buffering.end=e);let t=r?r.stats:n.stats;this.hls.trigger(J.FRAG_BUFFERED,{frag:n,part:r,stats:t,id:n.type})},i).catch(e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){this.sourceBuffers.forEach(([e])=>{if(e){let n=this.tracks[e];(!t.type||t.type===e)&&(n.ending=!0,n.ended||(n.ended=!0,this.log(`${e} buffer reached EOS`)))}});let n=this.overrides?.endOfStream!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t;return e&&!((t=this.tracks[e])!=null&&t.ended)})?n?(this.log(`Queueing EOS`),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:e}=this;if(!e||e.readyState!==`open`){e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`);return}this.log(`Calling mediaSource.endOfStream()`),e.endOfStream(),this.hls.trigger(J.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(J.BUFFERED_TO_END,void 0)):t.type===`video`&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){let t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===q.BUFFER_APPEND_ERROR&&t.frag){let e=t.errorAction?.nextAutoLevel;G(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){let{hls:e,details:t,media:n}=this;if(!n||t===null||!this.sourceBufferCount)return;let r=e.config,i=n.currentTime,a=t.levelTargetDuration,o=t.live&&r.liveBackBufferLength!==null?r.liveBackBufferLength:r.backBufferLength;if(G(o)&&o>=0){let e=Math.max(o,a),t=Math.floor(i/a)*a-e;this.flushBackBuffer(i,a,t)}let s=r.frontBufferFlushThreshold;if(G(s)&&s>0){let e=Math.max(r.maxBufferLength,s),t=Math.max(e,a),n=Math.floor(i/a)*a+t;this.flushFrontBuffer(i,a,n)}}flushBackBuffer(e,t,n){this.sourceBuffers.forEach(([e,t])=>{if(t){let i=Q.getBuffered(t);if(i.length>0&&n>i.start(0)){var r;this.hls.trigger(J.BACK_BUFFER_REACHED,{bufferEnd:n});let t=this.tracks[e];if((r=this.details)!=null&&r.live)this.hls.trigger(J.LIVE_BACK_BUFFER_REACHED,{bufferEnd:n});else if(t!=null&&t.ended){this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(J.BUFFER_FLUSHING,{startOffset:0,endOffset:n,type:e})}}})}flushFrontBuffer(e,t,n){this.sourceBuffers.forEach(([t,r])=>{if(r){let i=Q.getBuffered(r),a=i.length;if(a<2)return;let o=i.start(a-1),s=i.end(a-1);if(n>o||e>=o&&e<=s)return;this.hls.trigger(J.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:t})}})}getDurationAndRange(){let{details:e,mediaSource:t}=this;if(!e||!this.media||t?.readyState!==`open`)return null;let n=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&t.setLiveSeekableRange){let t=Math.max(0,e.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,n)}}return{duration:1/0}}let r=this.overrides?.duration;if(r)return G(r)?{duration:r}:null;let i=this.media.duration;return n>(G(t.duration)?t.duration:0)&&n>i||!G(i)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:n}){let r=this.mediaSource;!this.media||!r||r.readyState!==`open`||(r.duration!==e&&(G(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),t!==void 0&&n!==void 0&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${n}.`),r.setLiveSeekableRange(t,n)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:n}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Pg(n)}`),this.tracksReady){let e=this.transferData?.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,n])=>{if(t){let r=this.tracks[t];e[t]={buffer:n,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}}),this.hls.trigger(J.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{let e=Error(`could not create source buffer for media codec(s)`);this.hls.trigger(J.ERROR,{type:K.MEDIA_ERROR,details:q.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:n}=this;if(!n)throw Error(`createSourceBuffers called when mediaSource was null`);for(let i in e){let a=i,o=e[a];if(this.isPending(o)){let e=this.getTrackCodec(o,a),i=`${o.container};codecs=${e}`;o.codec=e,this.log(`creating sourceBuffer(${i})${this.currentOp(a)?` Queued`:``} ${Pg(o)}`);try{let e=n.addSourceBuffer(i),r=Rx(a);t[r]=[a,e],o.buffer=e}catch(e){var r;this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(a),(r=this.operationQueue)==null||r.removeBlockers(),delete this.tracks[a],this.hls.trigger(J.ERROR,{type:K.MEDIA_ERROR,details:q.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:a,mimeType:i,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){let n=e.supplemental,r=e.codec;n&&(t===`video`||t===`audiovideo`)&&Yh(n,`video`)&&(r=ig(r,n));let i=ag(r,e.levelCodec);return i?t.slice(0,5)===`audio`?rg(i,this.appendSource):i:``}trackSourceBuffer(e,t){let n=t.buffer;if(!n)return;let r=this.getTrackCodec(t,e);this.tracks[e]={buffer:n,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,`updatestart`,this.onSBUpdateStart),this.addBufferListener(e,`updateend`,this.onSBUpdateEnd),this.addBufferListener(e,`error`,this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,`bufferedchange`,(e,t)=>{let n=t.removedRanges;n!=null&&n.length&&this.hls.trigger(J.BUFFER_FLUSHED,{type:e})})}get mediaSrc(){var e,t;return(((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,`source`))||this.media)?.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){if(this.mediaSource?.readyState===`closed`){this.resetBuffer(e);return}let t=this.currentOp(e);t&&(t.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){let n=Error(`${e} SourceBuffer error. MediaSource readyState: ${this.mediaSource?.readyState}`);this.error(`${n}`,t),this.hls.trigger(J.ERROR,{type:K.MEDIA_ERROR,details:q.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});let r=this.currentOp(e);r&&r.onError(n)}updateTimestampOffset(e,t,n,r,i,a){let o=t-e.timestampOffset;Math.abs(o)>=n&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${i} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,n){let{media:r,mediaSource:i}=this,a=this.tracks[e],o=a?.buffer;if(!r||!i||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}let s=G(r.duration)?r.duration:1/0,c=G(i.duration)?i.duration:1/0,l=Math.max(0,t),u=Math.min(n,s,c);u>l&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${l},${u}] from the ${e} SourceBuffer`),o.remove(l,u)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){let n=this.tracks[t],r=n?.buffer;if(!r)throw new Px(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);n.ending=!1,n.ended=!1,r.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log(`Blocking operation requested, but no SourceBuffers exist`),Promise.resolve().then(e);let{operationQueue:n}=this,r=t.map(e=>this.appendBlocker(e));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then(t=>{n===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(e=>{let t=this.tracks[e]?.buffer;!t||t.updating||this.shiftAndExecuteNext(e)})}append(e,t,n){this.operationQueue&&this.operationQueue.append(e,t,n)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+ +!!this.isPending(this.tracks[t]),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+ +!!t,0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,n){let r=this.tracks[e];if(!r)return;let i=r.buffer;if(!i)return;let a=n.bind(this,e);r.listeners.push({event:t,listener:a}),i.addEventListener(t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let n=t.buffer;n&&(t.listeners.forEach(e=>{n.removeEventListener(e.event,e.listener)}),t.listeners.length=0)}};function Ix(e){let t=e.querySelectorAll(`source`);[].slice.call(t).forEach(t=>{e.removeChild(t)})}function Lx(e,t){let n=self.document.createElement(`source`);n.type=`video/mp4`,n.src=t,e.appendChild(n)}function Rx(e){return+(e===`audio`)}var zx=class e{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=1/0,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){let{hls:e}=this;e.on(J.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(J.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(J.MANIFEST_PARSED,this.onManifestParsed,this),e.on(J.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(J.BUFFER_CODECS,this.onBufferCodecs,this),e.on(J.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;e.off(J.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(J.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(J.MANIFEST_PARSED,this.onManifestParsed,this),e.off(J.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(J.BUFFER_CODECS,this.onBufferCodecs,this),e.off(J.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){let n=this.hls.levels[t.droppedLevel];this.isLevelAllowed(n)&&this.restrictedLevels.push({bitrate:n.bitrate,height:n.height,width:n.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){let n=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,n.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&G(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}let e=this.hls.levels;if(e.length){let t=this.hls,n=this.getMaxLevel(e.length-1);n!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${n}: ${e[n].height}p@${e[n].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=n,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(t){let n=this.hls.levels;if(!n.length)return-1;let r=n.filter((e,n)=>this.isLevelAllowed(e)&&n<=t);return this.clientRect=null,e.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=1/0,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=1/0,this.timer&&=(self.clearInterval(this.timer),void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let n=e.getBoundingClientRect();t.width=n.width,t.height=n.height,!t.width&&!t.height&&(t.width=n.right-n.left||e.width||0,t.height=n.bottom-n.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,n){if(!(e!=null&&e.length))return-1;let r=(e,t)=>t?e.width!==t.width||e.height!==t.height:!0,i=e.length-1,a=Math.max(t,n);for(let t=0;t=a||n.height>=a)&&r(n,e[t+1])){i=t;break}}return i}},Bx={MANIFEST:`m`,AUDIO:`a`,VIDEO:`v`,MUXED:`av`,INIT:`i`,CAPTION:`c`,TIMED_TEXT:`tt`,KEY:`k`,OTHER:`o`},Vx={HLS:`h`},Hx=class e{constructor(t,n){Array.isArray(t)&&(t=t.map(t=>t instanceof e?t:new e(t))),this.value=t,this.params=n}},Ux=`Dict`;function Wx(e){return Array.isArray(e)?JSON.stringify(e):e instanceof Map?`Map{}`:e instanceof Set?`Set{}`:typeof e==`object`?JSON.stringify(e):String(e)}function Gx(e,t,n,r){return Error(`failed to ${e} "${Wx(t)}" as ${n}`,{cause:r})}function Kx(e,t,n){return Gx(`serialize`,e,t,n)}var qx=class{constructor(e){this.description=e}},Jx=`Bare Item`,Yx=`Boolean`;function Xx(e){if(typeof e!=`boolean`)throw Kx(e,Yx);return e?`?1`:`?0`}function Zx(e){return btoa(String.fromCharCode(...e))}var Qx=`Byte Sequence`;function $x(e){if(ArrayBuffer.isView(e)===!1)throw Kx(e,Qx);return`:${Zx(e)}:`}var eS=`Integer`;function tS(e){return e<-999999999999999||99999999999999912)throw Kx(e,aS);let n=t.toString();return n.includes(`.`)?n:`${n}.0`}var sS=`String`,cS=/[\x00-\x1f\x7f]+/;function lS(e){if(cS.test(e))throw Kx(e,sS);return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function uS(e){return e.description||e.toString().slice(7,-1)}var dS=`Token`;function fS(e){let t=uS(e);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw Kx(t,dS);return t}function pS(e){switch(typeof e){case`number`:if(!G(e))throw Kx(e,Jx);return Number.isInteger(e)?nS(e):oS(e);case`string`:return lS(e);case`symbol`:return fS(e);case`boolean`:return Xx(e);case`object`:if(e instanceof Date)return rS(e);if(e instanceof Uint8Array)return $x(e);if(e instanceof qx)return fS(e);default:throw Kx(e,Jx)}}var mS=`Key`;function hS(e){if(/^[a-z*][a-z0-9\-_.*]*$/.test(e)===!1)throw Kx(e,mS);return e}function gS(e){return e==null?``:Object.entries(e).map(([e,t])=>t===!0?`;${hS(e)}`:`;${hS(e)}=${pS(t)}`).join(``)}function _S(e){return e instanceof Hx?`${pS(e.value)}${gS(e.params)}`:pS(e)}function vS(e){return`(${e.value.map(_S).join(` `)})${gS(e.params)}`}function yS(e,t={whitespace:!0}){if(typeof e!=`object`||!e)throw Kx(e,Ux);let n=e instanceof Map?e.entries():Object.entries(e),r=t?.whitespace?` `:``;return Array.from(n).map(([e,t])=>{t instanceof Hx||(t=new Hx(t));let n=hS(e);return t.value===!0?n+=gS(t.params):(n+=`=`,Array.isArray(t.value)?n+=vS(t):n+=_S(t)),n}).join(`,${r}`)}function bS(e,t){return yS(e,t)}var xS=`CMCD-Object`,SS=`CMCD-Request`,CS=`CMCD-Session`,wS=`CMCD-Status`,TS={br:xS,ab:xS,d:xS,ot:xS,tb:xS,tpb:xS,lb:xS,tab:xS,lab:xS,url:xS,pb:SS,bl:SS,tbl:SS,dl:SS,ltc:SS,mtp:SS,nor:SS,nrr:SS,rc:SS,sn:SS,sta:SS,su:SS,ttfb:SS,ttfbb:SS,ttlb:SS,cmsdd:SS,cmsds:SS,smrt:SS,df:SS,cs:SS,ts:SS,cid:CS,pr:CS,sf:CS,sid:CS,st:CS,v:CS,msd:CS,bs:wS,bsd:wS,cdn:wS,rtp:wS,bg:wS,pt:wS,ec:wS,e:wS},ES={REQUEST:SS};function DS(e){return Object.keys(e).reduce((t,n)=>{var r;return(r=e[n])==null||r.forEach(e=>t[e]=n),t},{})}function OS(e,t){let n={};if(!e)return n;let r=Object.keys(e),i=t?DS(t):{};return r.reduce((t,n)=>{let r=TS[n]||i[n]||ES.REQUEST,a=t[r]??(t[r]={});return a[n]=e[n],t},n)}function kS(e){return[`ot`,`sf`,`st`,`e`,`sta`].includes(e)}function AS(e){return typeof e==`number`?G(e):e!=null&&e!==``&&e!==!1}var jS=`event`;function MS(e,t){let n=new URL(e),r=new URL(t);if(n.origin!==r.origin)return e;let i=n.pathname.split(`/`).slice(1),a=r.pathname.split(`/`).slice(1,-1);for(;i[0]===a[0];)i.shift(),a.shift();for(;a.length;)a.shift(),i.unshift(`..`);return i.join(`/`)+n.search+n.hash}var NS=e=>Math.round(e),PS=(e,t)=>Array.isArray(e)?e.map(e=>PS(e,t)):e instanceof Hx&&typeof e.value==`string`?new Hx(PS(e.value,t),e.params):(t.baseUrl&&(e=MS(e,t.baseUrl)),t.version===1?encodeURIComponent(e):e),FS=e=>NS(e/100)*100,IS={br:NS,d:NS,bl:FS,dl:FS,mtp:FS,nor:(e,t)=>{let n=e;return t.version>=2&&(e instanceof Hx&&typeof e.value==`string`?n=new Hx([e]):typeof e==`string`&&(n=[e])),PS(n,t)},rtp:FS,tb:NS},LS=`request`,RS=`response`,zS=`ab.bg.bl.br.bs.bsd.cdn.cid.cs.df.ec.lab.lb.ltc.msd.mtp.pb.pr.pt.sf.sid.sn.st.sta.tab.tb.tbl.tpb.ts.v`.split(`.`),BS=[`e`],VS=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function HS(e){return VS.test(e)}function US(e){return zS.includes(e)||BS.includes(e)||HS(e)}var WS=[`d`,`dl`,`nor`,`ot`,`rtp`,`su`];function GS(e){return zS.includes(e)||WS.includes(e)||HS(e)}var KS=[`cmsdd`,`cmsds`,`rc`,`smrt`,`ttfb`,`ttfbb`,`ttlb`,`url`];function qS(e){return zS.includes(e)||WS.includes(e)||KS.includes(e)||HS(e)}var JS=[`bl`,`br`,`bs`,`cid`,`d`,`dl`,`mtp`,`nor`,`nrr`,`ot`,`pr`,`rtp`,`sf`,`sid`,`st`,`su`,`tb`,`v`];function YS(e){return JS.includes(e)||HS(e)}var XS={[RS]:qS,[jS]:US,[LS]:GS};function ZS(e,t={}){let n={};if(typeof e!=`object`||!e)return n;let r=t.version||e.v||1,i=t.reportingMode||LS,a=r===1?YS:XS[i],o=Object.keys(e).filter(a),s=t.filter;typeof s==`function`&&(o=o.filter(s));let c=i===RS||i===jS;c&&!o.includes(`ts`)&&o.push(`ts`),r>1&&!o.includes(`v`)&&o.push(`v`);let l=Pm({},IS,t.formatters),u={version:r,reportingMode:i,baseUrl:t.baseUrl};return o.sort().forEach(t=>{let i=e[t],a=l[t];if(typeof a==`function`&&(i=a(i,u)),t===`v`){if(r===1)return;i=r}t==`pr`&&i===1||(c&&t===`ts`&&!G(i)&&(i=Date.now()),AS(i)&&(kS(t)&&typeof i==`string`&&(i=new qx(i)),n[t]=i))}),n}function QS(e,t={}){let n={};if(!e)return n;let r=OS(ZS(e,t),t?.customHeaderMap);return Object.entries(r).reduce((e,[t,n])=>{let r=bS(n,{whitespace:!1});return r&&(e[t]=r),e},n)}function $S(e,t,n){return Pm(e,QS(t,n))}var eC=`CMCD`;function tC(e,t={}){return e?bS(ZS(e,t),{whitespace:!1}):``}function nC(e,t={}){if(!e)return``;let n=tC(e,t);return encodeURIComponent(n)}function rC(e,t={}){return e?`${eC}=${nC(e,t)}`:``}var iC=/CMCD=[^&#]+/;function aC(e,t,n){let r=rC(t,n);return r?iC.test(e)?e.replace(iC,r):`${e}${e.includes(`?`)?`&`:`?`}${r}`:e}var oC=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||=!0,this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:Bx.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn(`Could not generate manifest CMCD data.`,e)}},this.applyFragmentData=e=>{try{let{frag:t,part:n}=e,r=this.hls.levels[t.level],i=this.getObjectType(t),a={d:(n||t).duration*1e3,ot:i};(i===Bx.VIDEO||i===Bx.AUDIO||i==Bx.MUXED)&&(a.br=r.bitrate/1e3,a.tb=this.getTopBandwidth(i)/1e3,a.bl=this.getBufferLength(i));let o=n?this.getNextPart(n):this.getNextFrag(t);o!=null&&o.url&&o.url!==t.url&&(a.nor=o.url),this.apply(e,a)}catch(e){this.hls.logger.warn(`Could not generate segment CMCD data.`,e)}},this.hls=e;let t=this.config=e.config,{cmcd:n}=t;n!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||e.sessionId,this.cid=n.contentId,this.useHeaders=n.useHeaders===!0,this.includeKeys=n.includeKeys,this.registerListeners())}registerListeners(){let e=this.hls;e.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(J.MEDIA_DETACHED,this.onMediaDetached,this),e.on(J.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(J.MEDIA_DETACHED,this.onMediaDetached,this),e.off(J.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener(`waiting`,this.onWaiting),this.media.addEventListener(`playing`,this.onPlaying)}onMediaDetached(){this.media&&=(this.media.removeEventListener(`waiting`,this.onWaiting),this.media.removeEventListener(`playing`,this.onPlaying),null)}onBufferCreated(e,t){this.audioBuffer=t.tracks.audio?.buffer,this.videoBuffer=t.tracks.video?.buffer}createData(){return{v:1,sf:Vx.HLS,sid:this.sid,cid:this.cid,pr:this.media?.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Pm(t,this.createData());let n=t.ot===Bx.INIT||t.ot===Bx.VIDEO||t.ot===Bx.MUXED;this.starved&&n&&(t.bs=!0,t.su=!0,this.starved=!1),t.su??=this.buffering;let{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((e,n)=>(r.includes(n)&&(e[n]=t[n]),e),{}));let i={baseUrl:e.url};this.useHeaders?(e.headers||={},$S(e.headers,t,i)):e.url=aC(e.url,t,i)}getNextFrag(e){let t=this.hls.levels[e.level]?.details;if(t){let n=e.sn-t.startSN;return t.fragments[n+1]}}getNextPart(e){var t;let{index:n,fragment:r}=e,i=(t=this.hls.levels[r.level])==null||(t=t.details)==null?void 0:t.partList;if(i){let{sn:e}=r;for(let t=i.length-1;t>=0;t--){let r=i[t];if(r.index===n&&r.fragment.sn===e)return i[t+1]}}}getObjectType(e){let{type:t}=e;if(t===`subtitle`)return Bx.TIMED_TEXT;if(e.sn===`initSegment`)return Bx.INIT;if(t===`audio`)return Bx.AUDIO;if(t===`main`)return this.hls.audioTracks.length?Bx.VIDEO:Bx.MUXED}getTopBandwidth(e){let t=0,n,r=this.hls;if(e===Bx.AUDIO)n=r.audioTracks;else{let e=r.maxAutoLevel,t=e>-1?e+1:r.levels.length;n=r.levels.slice(0,t)}return n.forEach(e=>{e.bitrate>t&&(t=e.bitrate)}),t>0?t:NaN}getBufferLength(e){let t=this.media,n=e===Bx.AUDIO?this.audioBuffer:this.videoBuffer;return!n||!t?NaN:Q.bufferInfo(n,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,n=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new n(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,n,r){t(e),this.loader.load(e,n,r)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,n=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new n(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,n,r){t(e),this.loader.load(e,n,r)}}}},sC=3e5,cC=class extends zm{constructor(e){super(`content-steering`,e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=`.`,this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(J.MANIFEST_LOADING,this.onManifestLoading,this),e.on(J.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(J.MANIFEST_PARSED,this.onManifestParsed,this),e.on(J.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(J.MANIFEST_LOADING,this.onManifestLoading,this),e.off(J.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(J.MANIFEST_PARSED,this.onManifestParsed,this),e.off(J.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&=(this.loader.destroy(),null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(t=>t!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=`.`,this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){let{contentSteering:n}=t;n!==null&&(this.pathwayId=n.pathwayId,this.uri=n.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:n}=t;if(n?.action===d_.SendAlternateToPenaltyBox&&n.flags===f_.MoveAllAlternatesMatchingHost){let e=this.levels,r=this._pathwayPriority,i=this.pathwayId;if(t.context){let{groupId:n,pathwayId:r,type:a}=t.context;n&&e?i=this.getPathwayForGroupId(n,a,i):r&&(i=r)}i in this.penalizedPathways||(this.penalizedPathways[i]=performance.now()),!r&&e&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),n.resolved=this.pathwayId!==i),t.details===q.BUFFER_APPEND_ERROR&&!t.fatal?n.resolved=!0:n.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${i} levels: ${e&&e.length} priorities: ${Pg(r)} penalized: ${Pg(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let n=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${n}"`),t=this.getLevelsForPathway(n),this.pathwayId=n}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t,n=this.penalizedPathways,r=performance.now();Object.keys(n).forEach(e=>{r-n[e]>sC&&delete n[e]});for(let r=0;r0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,ey(t),this.hls.trigger(J.LEVELS_UPDATED,{levels:t});let e=this.hls.levels[a];o&&e&&this.levels&&(e.attrs[`STABLE-VARIANT-ID`]!==o.attrs[`STABLE-VARIANT-ID`]&&e.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,n){let r=this.getLevelsForPathway(n).concat(this.levels||[]);for(let n=0;n{let{ID:i,"BASE-ID":a,"URI-REPLACEMENT":o}=e;if(t.some(e=>e.pathwayId===i))return;let s=this.getLevelsForPathway(a).map(e=>{let t=new G_(e.attrs);t[`PATHWAY-ID`]=i;let a=t.AUDIO&&`${t.AUDIO}_clone_${i}`,s=t.SUBTITLES&&`${t.SUBTITLES}_clone_${i}`;a&&(n[t.AUDIO]=a,t.AUDIO=a),s&&(r[t.SUBTITLES]=s,t.SUBTITLES=s);let c=uC(e.uri,t[`STABLE-VARIANT-ID`],`PER-VARIANT-URIS`,o),l=new kg({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:c,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t{this.log(`Loaded steering manifest: "${r}"`);let a=e.data;if(a?.VERSION!==1){this.log(`Steering VERSION ${a.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=a.TTL;let{"RELOAD-URI":o,"PATHWAY-CLONES":s,"PATHWAY-PRIORITY":c}=a;if(o)try{this.uri=new self.URL(o,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${o}`);return}this.scheduleRefresh(this.uri||n.url),s&&this.clonePathways(s);let l={steeringManifest:a,url:r.toString()};this.hls.trigger(J.STEERING_MANIFEST_LOADED,l),c&&this.updatePathwayPriority(c)},onError:(e,t,n,r)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),e.code===410){this.enabled=!1,this.log(`Steering manifest ${t.url} no longer available`);return}let i=this.timeToLoad*1e3;if(e.code===429){let e=this.loader;if(typeof e?.getResponseHeader==`function`){let t=e.getResponseHeader(`Retry-After`);t&&(i=parseFloat(t)*1e3)}this.log(`Steering manifest ${t.url} rate limited`);return}this.scheduleRefresh(this.uri||t.url,i)},onTimeout:(e,t,n)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}})}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{let t=this.hls?.media;if(t&&!t.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function lC(e,t,n,r){e&&Object.keys(t).forEach(i=>{let a=e.filter(e=>e.groupId===i).map(e=>{let a=Pm({},e);return a.details=void 0,a.attrs=new G_(a.attrs),a.url=a.attrs.URI=uC(e.url,e.attrs[`STABLE-RENDITION-ID`],`PER-RENDITION-URIS`,n),a.groupId=a.attrs[`GROUP-ID`]=t[i],a.attrs[`PATHWAY-ID`]=r,a});e.push(...a)})}function uC(e,t,n,r){let{HOST:i,PARAMS:a,[n]:o}=r,s;t&&(s=o?.[t],s&&(e=s));let c=new self.URL(e);return i&&!s&&(c.host=i),a&&Object.keys(a).sort().forEach(e=>{e&&c.searchParams.set(e,a[e])}),c.href}var dC=class e extends zm{constructor(t){super(`eme`,t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=e.CDMCleanupPromise?[e.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=e=>{let{initDataType:t,initData:n}=e,r=`"${e.type}" event: init data type: "${t}"`;if(this.debug(r),n!==null){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=fv(this.config));let t=e.map(dv).filter(e=>!!e);this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then(i=>{let a=uv(i);if(t!==`sinf`||a!==cv.FAIRPLAY){this.log(`Ignoring "${e.type}" event with init data type: "${t}" for selected key-system ${a}`);return}let o;try{let e=gh(new Uint8Array(n)),t=Mh(nv(JSON.parse(e).sinf));if(!t)throw Error(`'schm' box missing or not cbcs/cenc with schi > tenc`);o=new Uint8Array(t.subarray(8,24))}catch(e){this.warn(`${r} Failed to parse sinf: ${e}`);return}let s=Qm(o),{keyIdToKeySessionPromise:c,mediaKeySessions:l}=this,u=c[s];for(let e=0;ethis.generateRequestWithPreferredKeySession(r,t,n,`encrypted-event-key-match`)),u.catch(e=>this.handleError(e));break}}u||this.handleError(Error(`Key ID ${s} not encountered in playlist. Key-system sessions ${l.length}.`))}).catch(e=>this.handleError(e))}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(J.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(J.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(J.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(J.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(J.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(J.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(J.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(J.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:n}=this.config,r=t?.[e];if(r)return r.licenseUrl;if(e===cv.WIDEVINE&&n)return n}getLicenseServerUrlOrThrow(e){let t=this.getLicenseServerUrl(e);if(t===void 0)throw Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){let{drmSystems:t}=this.config,n=t?.[e];if(n)return n.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){let t=this.hls.levels,n=(e,t,n)=>!!e&&n.indexOf(e)===t,r=t.map(e=>e.audioCodec).filter(n),i=t.map(e=>e.videoCodec).filter(n);return r.length+i.length===0&&i.push(`avc1.42e01e`),new Promise((t,n)=>{let a=e=>{let o=e.shift();this.getMediaKeysPromise(o,r,i).then(e=>t({keySystem:o,mediaKeys:e})).catch(t=>{e.length?a(e):t instanceof mC?n(t):n(new mC({type:K.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};a(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!=`function`){let e=`Configured requestMediaKeySystemAccess is not a function ${n}`;return pv===null&&self.location.protocol===`http:`&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(Error(e))}return n(e,t)}getMediaKeysPromise(e,t,n){let r=mv(e,t,n,this.config.drmSystemOptions||{}),i=this.keySystemAccessPromises[e],a=i?.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${Pg(r)}`),a=this.requestMediaKeySystemAccess(e,r);let t=i=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)}),a.then(n=>{this.log(`Access for key-system "${n.keySystem}" obtained`);let r=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let i=t.mediaKeys=n.createMediaKeys().then(n=>(this.log(`Media-keys created for "${e}"`),t.hasMediaKeys=!0,r.then(t=>t?this.setMediaKeysServerCertificate(n,e,t):n)));return i.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),i})}return a.then(()=>i.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:n}){this.log(`Creating key-system session "${t}" keyId: ${Qm(e.keyId||[])} keyUri: ${e.uri}`);let r={decryptdata:e,keySystem:t,mediaKeys:n,mediaKeysSession:n.createSession(),keyStatus:`status-pending`};return this.mediaKeySessions.push(r),r}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let n=this.createMediaKeySessionContext(e),r=fC(t);this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(n,`cenc`,t.pssh.buffer,`expired`)}else this.warn(`Could not renew expired session. Missing pssh initData.`);this.removeSession(e)}updateKeySession(e,t){let n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyId ${Qm(e.decryptdata.keyId||[])} } (data length: ${t.byteLength})`),n.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>dv(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e,mediaKeys:t})=>this.attemptSetMediaKeys(e,t))}selectKeySystem(e){return new Promise((t,n)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:e})=>{let r=dv(e);r?t(r):n(Error(`Unable to find format for key-system "${e}"`))}).catch(n)})}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||=(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(`, `)}`),this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){let t=fv(this.config),n=e.map(uv).filter(e=>!!e&&t.indexOf(e)!==-1);return this.selectKeySystem(n)}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let n=0;n(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${i}`),this.attemptSetMediaKeys(n,r).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:n,mediaKeys:r,decryptdata:t}))))).then(e=>{let n=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(e,`cenc`,n,`playlist-key`)});return r.catch(t=>this.handleError(t,e.frag)),this.keyIdToKeySessionPromise[n]=r,r}return a.catch(n=>{if(n instanceof mC){let r=Im({},n.data);this.getKeyStatus(t)===`internal-error`&&(r.decryptdata=t);let i=new mC(r,n.message);this.handleError(i,e.frag)}}),a}throwIfDestroyed(e=`Invalid state`){if(!this.hls)throw Error(`invalid state`)}handleError(e,t){if(this.hls)if(e instanceof mC){t&&(e.data.frag=t);let n=e.data.decryptdata;this.error(`${e.message}${n?` (${Qm(n.keyId||[])})`:``}`),this.hls.trigger(J.ERROR,e.data)}else this.error(e.message),this.hls.trigger(J.ERROR,{type:K.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){let t=fC(e),n=this.keyIdToKeySessionPromise[t];if(!n){let t=uv(e.keyFormat),n=t?[t]:fv(this.config);return this.attemptKeySystemAccess(n)}return n}getKeySystemSelectionPromise(e){if(e.length||(e=fv(this.config)),e.length===0)throw new mC({type:K.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Pg({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();let n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(n).then(()=>this.media?this.media.setMediaKeys(t):new Promise((e,n)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return n(Error(`Attempted to set mediaKeys without media element attached`));this.mediaKeys=t,this.media.setMediaKeys(t).then(e).catch(n)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),n.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(e=>n.indexOf(e)===-1)})}generateRequestWithPreferredKeySession(e,t,n,r){var i;let a=(i=this.config.drmSystems)==null||(i=i[e.keySystem])==null?void 0:i.generateRequest;if(a)try{let r=a.call(this.hls,t,n,e);if(!r)throw Error(`Invalid response from configured generateRequest filter`);t=r.initDataType,n=r.initData?r.initData:null,e.decryptdata.pssh=n?new Uint8Array(n):null}catch(e){if(this.warn(e.message),this.hls&&this.hls.config.debug)throw e}if(n===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);let o=fC(e.decryptdata),s=e.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${o} URI: ${s} (init data type: ${t} length: ${n.byteLength})`);let c=new by,l=e._onmessage=t=>{let n=e.mediaKeysSession;if(!n){c.emit(`error`,Error(`invalid state`));return}let{messageType:r,message:i}=t;this.log(`"${r}" message event for session "${n.sessionId}" message size: ${i.byteLength}`),r===`license-request`||r===`license-renewal`?this.renewLicense(e,i).catch(e=>{c.eventNames().length?c.emit(`error`,e):this.handleError(e)}):r===`license-release`?e.keySystem===cv.FAIRPLAY&&this.updateKeySession(e,rv(`acknowledged`)).then(()=>this.removeSession(e)).catch(e=>this.handleError(e)):this.warn(`unhandled media key message type "${r}"`)},u=(e,t)=>{t.keyStatus=e;let n;e.startsWith(`usable`)?c.emit(`resolved`):e===`internal-error`||e===`output-restricted`||e===`output-downscaled`?n=hC(e,t.decryptdata):e===`expired`?n=Error(`key expired (keyId: ${o})`):e===`released`?n=Error(`key released`):e===`status-pending`||this.warn(`unhandled key status change "${e}" (keyId: ${o})`),n&&(c.eventNames().length?c.emit(`error`,n):this.handleError(n))},d=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession){c.emit(`error`,Error(`invalid state`));return}let n=this.getKeyStatuses(e);if(!Object.keys(n).some(e=>n[e]!==`status-pending`))return;if(n[o]===`expired`){this.log(`Expired key ${Pg(n)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let r=n[o];if(r)u(r,e);else{var i;let t=1e3;e.keyStatusTimeouts||={},(i=e.keyStatusTimeouts)[o]||(i[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;let n=this.getKeyStatus(e.decryptdata);if(n&&n!==`status-pending`)return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${n} from other session.`),u(n,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after ${t}ms`),r=`internal-error`,u(r,e)},t)),this.log(`No status for keyId ${o} (${Pg(n)}).`)}};uy(e.mediaKeysSession,`message`,l),uy(e.mediaKeysSession,`keystatuseschange`,d);let f=new Promise((e,t)=>{c.on(`error`,t),c.on(`resolved`,e)});return e.mediaKeysSession.generateRequest(t,n).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${s}`)}).catch(t=>{throw new mC({type:K.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${t}`)}).then(()=>f).catch(t=>(c.removeAllListeners(),this.removeSession(e).then(()=>{throw t}))).then(()=>(c.removeAllListeners(),e))}getKeyStatuses(e){let t={};return e.mediaKeysSession.keyStatuses.forEach((n,r)=>{if(typeof r==`string`&&typeof n==`object`){let e=r;r=n,n=e}let i=`buffer`in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(e.keySystem===cv.PLAYREADY&&i.length===16){let e=Qm(i);t[e]=n,av(i)}let a=Qm(i);n===`internal-error`&&(this.bannedKeyIds[a]=n),this.log(`key status change "${n}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=n}),t}fetchServerCertificate(e){let t=this.config,n=t.loader,r=new n(t),i=this.getServerCertificateUrl(e);return i?(this.log(`Fetching server certificate for "${e}"`),new Promise((n,a)=>{let o={responseType:`arraybuffer`,url:i},s=t.certLoadPolicy.default,c={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};r.load(o,c,{onSuccess:(e,t,r,i)=>{n(e.data)},onError:(t,n,r,s)=>{a(new mC({type:K.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:Im({url:o.url,data:void 0},t)},`"${e}" certificate request failed (${i}). Status: ${t.code} (${t.text})`))},onTimeout:(t,n,r)=>{a(new mC({type:K.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:o.url,data:void 0}},`"${e}" certificate request timed out (${i})`))},onAbort:(e,t,n)=>{a(Error(`aborted`))}})})):Promise.resolve()}setMediaKeysServerCertificate(e,t,n){return new Promise((r,i)=>{e.setServerCertificate(n).then(i=>{this.log(`setServerCertificate ${i?`success`:`not supported by CDM`} (${n.byteLength}) on "${t}"`),r(e)}).catch(e=>{i(new mC({type:K.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(t=>this.updateKeySession(e,new Uint8Array(t)).catch(t=>{throw new mC({type:K.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:t,fatal:!1},t.message)}))}unpackPlayReadyKeyMessage(e,t){let n=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!n.includes(`PlayReadyKeyMessage`))return e.setRequestHeader(`Content-Type`,`text/xml; charset=utf-8`),t;let r=new DOMParser().parseFromString(n,`application/xml`),i=r.querySelectorAll(`HttpHeader`);if(i.length>0){let t;for(let n=0,r=i.length;n in key message`);return rv(atob(a))}setupLicenseXHR(e,t,n,r){let i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!n.decryptdata)throw Error(`Key removed`);return i.call(this.hls,e,t,n,r)}).catch(a=>{if(!n.decryptdata)throw a;return e.open(`POST`,t,!0),i.call(this.hls,e,t,n,r)}).then(n=>(e.readyState||e.open(`POST`,t,!0),{xhr:e,licenseChallenge:n||r})):(e.open(`POST`,t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){let n=this.config.keyLoadPolicy.default;return new Promise((r,i)=>{let a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);let o=new XMLHttpRequest;o.responseType=`arraybuffer`,o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return i(Error(`invalid state`));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let t=o.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);let n=this.config.licenseResponseCallback;if(n)try{t=n.call(this.hls,o,a,e)}catch(e){this.error(e)}r(t)}else{let s=n.errorRetry,c=s?s.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)i(new mC({type:K.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{let n=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${n} attempts left`),this.requestLicense(e,t).then(r,i)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:t,licenseChallenge:n})=>{e.keySystem==cv.PLAYREADY&&(n=this.unpackPlayReadyKeyMessage(t,n)),t.send(n)}).catch(i)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let n=t.media;this.media=n,uy(n,`encrypted`,this.onMediaEncrypted),uy(n,`waitingforkey`,this.onWaitingForKey);let r=this.mediaResolved;r?r():this.mediaKeys=n.mediaKeys}onMediaDetached(){let e=this.media;e&&(dy(e,`encrypted`,this.onMediaEncrypted),dy(e,`waitingforkey`,this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};let n=this.mediaResolved;if(n&&n(),!this.mediaKeys&&!this.mediaKeySessions.length)return;let r=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,yv.clearKeyUriToKeyIdMap();let a=i.length;e.CDMCleanupPromise=Promise.all(i.map(e=>this.removeSession(e)).concat((r==null||(t=r.setMediaKeys(null))==null?void 0:t.catch(e=>{this.log(`Could not clear media keys: ${e}`),this.hls&&this.hls.trigger(J.ERROR,{type:K.OTHER_ERROR,details:q.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:Error(`Could not clear media keys: ${e}`)})}))||Promise.resolve())).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}`),this.hls&&this.hls.trigger(J.ERROR,{type:K.OTHER_ERROR,details:q.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error(`Could not close sessions and clear media keys: ${e}`)})}).then(()=>{a&&this.log(`finished closing key sessions and clearing media keys`)})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let e=t.reduce((e,t)=>(e.indexOf(t.keyFormat)===-1&&e.push(t.keyFormat),e),[]);this.log(`Selecting key-system from session-keys ${e.join(`, `)}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){let{mediaKeysSession:t,licenseXhr:n,decryptdata:r}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Qm(r?.keyId||[])}`),e._onmessage&&=(t.removeEventListener(`message`,e._onmessage),void 0),e._onkeystatuseschange&&=(t.removeEventListener(`keystatuseschange`,e._onkeystatuseschange),void 0),n&&n.readyState!==XMLHttpRequest.DONE&&n.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let i=this.mediaKeySessions.indexOf(e);i>-1&&this.mediaKeySessions.splice(i,1);let{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(e=>self.clearTimeout(a[e]));let{drmSystemOptions:o}=this.config;return(gv(o)?new Promise((e,n)=>{self.setTimeout(()=>n(Error(`MediaKeySession.remove() timeout`)),8e3),t.remove().then(e).catch(n)}):Promise.resolve()).catch(e=>{this.log(`Could not remove session: ${e}`),this.hls&&this.hls.trigger(J.ERROR,{type:K.OTHER_ERROR,details:q.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:Error(`Could not remove session: ${e}`)})}).then(()=>t.close()).catch(e=>{this.log(`Could not close session: ${e}`),this.hls&&this.hls.trigger(J.ERROR,{type:K.OTHER_ERROR,details:q.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error(`Could not close session: ${e}`)})})}return Promise.resolve()}};dC.CDMCleanupPromise=void 0;function fC(e){if(!e)throw Error(`Could not read keyId of undefined decryptdata`);if(e.keyId===null)throw Error(`keyId is null`);return Qm(e.keyId)}function pC(e,t){if(e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId))return t.mediaKeysSession.keyStatuses.get(e.keyId);if(e.matches(t.decryptdata))return t.keyStatus}var mC=class extends Error{constructor(e,t){super(t),this.data=void 0,e.error||=Error(t),this.data=e,e.err=e.error}};function hC(e,t){let n=e===`output-restricted`,r=n?q.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:q.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new mC({type:K.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},n?`HDCP level output restricted`:`key status changed to "${e}"`)}var gC=class{constructor(e){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=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(J.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(J.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(J.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(J.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let n=this.hls.config;if(n.capLevelOnFPSDrop){let e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&typeof e.getVideoPlaybackQuality==`function`&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),n.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,n){let r=performance.now();if(t){if(this.lastTime){let e=r-this.lastTime,i=n-this.lastDroppedFrames,a=t-this.lastDecodedFrames,o=1e3*i/e,s=this.hls;if(s.trigger(J.FPS_DROP,{currentDropped:i,currentDecoded:a,totalDroppedFrames:n}),o>0&&i>s.config.fpsDroppedMonitoringThreshold*a){let e=s.currentLevel;s.logger.warn(`drop FPS ratio greater than max allowed value for currentLevel: `+e),e>0&&(s.autoLevelCapping===-1||s.autoLevelCapping>=e)&&(--e,s.trigger(J.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:s.currentLevel}),s.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=n,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}};function _C(e,t){let n;try{n=new Event(`addtrack`)}catch{n=document.createEvent(`Event`),n.initEvent(`addtrack`,!1,!1)}n.track=e,t.dispatchEvent(n)}function vC(e,t){let n=e.mode;if(n===`disabled`&&(e.mode=`hidden`),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw Error(`addCue is failed for: ${t}`)}catch(n){qm.debug(`[texttrack-utils]: ${n}`);try{let n=new self.TextTrackCue(t.startTime,t.endTime,t.text);n.id=t.id,e.addCue(n)}catch(e){qm.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}n===`disabled`&&(e.mode=n)}function yC(e,t){let n=e.mode;if(n===`disabled`&&(e.mode=`hidden`),e.cues)for(let n=e.cues.length;n--;)t&&e.cues[n].removeEventListener(`enter`,t),e.removeCue(e.cues[n]);n===`disabled`&&(e.mode=n)}function bC(e,t,n,r){let i=e.mode;if(i===`disabled`&&(e.mode=`hidden`),e.cues&&e.cues.length>0){let i=SC(e.cues,t,n);for(let t=0;te[n].endTime)return-1;let r=0,i=n,a;for(;r<=i;)if(a=Math.floor((i+r)/2),te[a].startTime&&r-1)for(let a=i,o=e.length;a=t&&i.endTime<=n)r.push(i);else if(i.startTime>n)return r}return r}function CC(e){let t=[];for(let n=0;nthis.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null,t=CC(this.media.textTracks);for(let n=0;n-1&&this.toggleTrackModes()}registerListeners(){let{hls:e}=this;e.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(J.MANIFEST_LOADING,this.onManifestLoading,this),e.on(J.MANIFEST_PARSED,this.onManifestParsed,this),e.on(J.LEVEL_LOADING,this.onLevelLoading,this),e.on(J.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(J.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(J.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(J.MANIFEST_LOADING,this.onManifestLoading,this),e.off(J.MANIFEST_PARSED,this.onManifestParsed,this),e.off(J.LEVEL_LOADING,this.onLevelLoading,this),e.off(J.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(J.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(J.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.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))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let n=this.media;if(!n)return;let r=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||n.textTracks.removeEventListener(`change`,this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,!r&&CC(n.textTracks).forEach(e=>{yC(e)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){let{id:n,groupId:r,details:i}=t,a=this.tracksInGroup[n];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${n} and group:${r} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Subtitle track ${n} "${a.name}" lang:${a.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let n=t.subtitleGroups||null,r=this.groupIds,i=this.currentTrack;if(!n||r?.length!==n?.length||n!=null&&n.some(e=>r?.indexOf(e)===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;let e=this.tracks.filter(e=>!n||n.indexOf(e.groupId)!==-1);if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=e;let t=this.hls.config.subtitlePreference;if(!i&&t){this.selectDefaultTrack=!1;let n=Bg(t,e);if(n>-1)i=e[n];else{let e=Bg(t,this.tracks);i=this.tracks[e]}}let r=this.findTrackId(i);r===-1&&i&&(r=this.findTrackId(null));let a={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${n?.join(`,`)}" group-id`),this.hls.trigger(J.SUBTITLE_TRACKS_UPDATED,a),r!==-1&&this.trackId===-1&&this.setSubtitleTrack(r)}}findTrackId(e){let t=this.tracksInGroup,n=this.selectDefaultTrack;for(let r=0;r-1){let e=this.tracksInGroup[r];return this.setSubtitleTrack(r),e}else if(n)return null;else{let n=Bg(e,t);if(n>-1)return t[n]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let n=e.id,r=e.groupId,i=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading subtitle ${n} "${e.name}" lang:${e.lang} group:${r}${t?.msn===void 0?``:` at sn `+t.msn+` part `+t.part}${o&&a.live?` age `+o.toFixed(1)+(a.type&&` `+a.type||``):``} ${i}`),this.hls.trigger(J.SUBTITLE_TRACK_LOADING,{url:i,id:n,groupId:r,deliveryDirectives:t||null,track:e})}toggleTrackModes(){let{media:e}=this;if(!e)return;let t=CC(e.textTracks),n=this.currentTrack,r;if(n&&(r=t.filter(e=>kx(n,e))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${n.name}" and language "${n.lang}"`)),[].slice.call(t).forEach(e=>{e.mode!==`disabled`&&e!==r&&(e.mode=`disabled`)}),r){let e=this.subtitleDisplay?`showing`:`hidden`;r.mode!==e&&(r.mode=e)}}setSubtitleTrack(e){let t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!G(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;let n=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r){this.hls.trigger(J.SUBTITLE_TRACK_SWITCH,{id:e});return}let i=!!r.details&&!r.details.live;if(e===this.trackId&&r===n&&i)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:``));let{id:a,groupId:o=``,name:s,type:c,url:l}=r;this.hls.trigger(J.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:s,type:c,url:l});let u=this.switchParams(r.url,n?.details,r.details);this.loadPlaylist(u)}};function TC(){try{return crypto.randomUUID()}catch{try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf(`/`)+1)}catch{let e=new Date().getTime();return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,t=>{let n=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(t==`x`?n:n&3|8).toString(16)})}}}function EC(e){let t=5381,n=e.length;for(;n;)t=t*33^e.charCodeAt(--n);return(t>>>0).toString()}var DC=.025,OC=function(e){return e[e.Point=0]=`Point`,e[e.Range=1]=`Range`,e}({});function kC(e,t,n){return`${e.identifier}-${n+1}-${EC(t)}`}var AC=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat(`X-RESUME-OFFSET`,this.resumeOffset),this.playoutLimit=e.attr.optionalFloat(`X-PLAYOUT-LIMIT`,this.playoutLimit),this.restrictions=e.attr.enumeratedStringList(`X-RESTRICT`,this.restrictions),this.snapOptions=e.attr.enumeratedStringList(`X-SNAP`,this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){if(e>0&&e>=this.assetList.length)return!0;let t=this.playoutLimit;return e<=0||isNaN(t)?!1:t===0?!0:(this.assetList[e]?.startOffset||0)>t}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return jC(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;let e=this.dateRange.tagAnchor;if(e){let t=this.dateRange.startTime;return t-jC(t,e)<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=G(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){let e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let t=this.resumeAnchor;if(t)return jC(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)0||this.assetListResponse!==null}toString(){return PC(this)}};function jC(e,t){return e-t.start`:e.cue.post?``:``}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`}function FC(e){let t=e.timelineStart,n=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+n).toFixed(2)}]`}var IC=class{constructor(e,t,n,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(J.PLAYOUT_LIMIT_REACHED,{})};let i=this.hls=new e(t);this.interstitial=n,this.assetItem=r;let a=()=>{this.hasDetails=!0};i.once(J.LEVEL_LOADED,a),i.once(J.AUDIO_TRACK_LOADED,a),i.once(J.SUBTITLE_TRACK_LOADED,a),i.on(J.MEDIA_ATTACHING,(e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t,this.interstitial.playoutLimit&&(t.addEventListener(`timeupdate`,this.checkPlayout),this.appendInPlace&&i.on(J.BUFFER_APPENDED,()=>{let e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,i.trigger(J.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=MC(t,e.config.primarySessionId||``).href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;let n=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,i=Q.bufferInfo(e,r,0);return this.getAssetTime(i.end)>=n-.02}reachedPlayout(e){let t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){return this.hls?.media||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=Q.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){let e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){let e=this.assetItem.duration;if(!e)return 0;let t=this.interstitial.playoutLimit;if(t){let n=t-this.startOffset;if(n>0&&n1/9e4&&this.hls){if(this.hasDetails)throw Error(`Cannot set timelineOffset after playlists are loaded`);this.hls.config.timelineOffset=e}}}getAssetTime(e){let t=this.timelineOffset,n=this.duration;return Math.min(Math.max(0,e-t),n)}removeMediaListeners(){let e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener(`timeupdate`,this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){return this.bufferSnapShot(),this.hls?.transferMedia()||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,n){var r;(r=this.hls)==null||r.on(e,t)}once(e,t,n){var r;(r=this.hls)==null||r.once(e,t)}off(e,t,n){var r;(r=this.hls)==null||r.off(e,t)}toString(){return`HlsAssetPlayer: ${FC(this.assetItem)} ${this.hls?.sessionId} ${this.appendInPlace?`append-in-place`:``}`}},LC=.033,RC=class extends zm{constructor(e,t){super(`interstitials-sched`,t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((n,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,n+1):n,0):0}get duration(){let e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let n=-1;e.nextEvent?n=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(n=this.findEventIndex(e.previousEvent.identifier)+1);let r=this.items;if(r)for(r[n]||(t===void 0&&(t=e.start),n=this.findItemIndexAtTime(t));n>=0&&(i=r[n])!=null&&i.event;){var i;n--}return n}findItemIndexAtTime(e,t){let n=this.items;if(n)for(let r=0;ri.start&&e1)for(let e=0;en&&(t!o.includes(e.identifier)):[];a.length&&a.sort((e,t)=>{let n=e.cue.pre,r=e.cue.post,i=t.cue.pre,a=t.cue.post;if(n&&!i)return-1;if(i&&!n||r&&!a)return 1;if(a&&!r)return-1;if(!n&&!i&&!r&&!a){let n=e.startTime,r=t.startTime;if(n!==r)return n-r}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=a,s.forEach(e=>{this.removeEvent(e)}),this.updateSchedule(e,s)}updateSchedule(e,t=[],n=!1){let r=this.events||[];if(r.length||t.length||this.length<2){let i=this.items,a=this.parseSchedule(r,e);(n||t.length||i?.length!==a.length||a.some((e,t)=>Math.abs(e.playout.start-i[t].playout.start)>.005||Math.abs(e.playout.end-i[t].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,i))}}parseDateRanges(e,t,n){let r=[],i=Object.keys(e);for(let a=0;a!e.error&&!(e.cue.once&&e.hasPlayed)),e.length){this.resolveOffsets(e,t);let r=0,o=0;if(e.forEach((t,s)=>{let c=t.cue.pre,l=t.cue.post,u=e[s-1]||null,d=t.appendInPlace,f=l?i:t.startOffset,p=t.duration,m=t.timelineOccupancy===OC.Range?p:0,h=t.resumptionOffset,g=u?.startTime===f,_=f+t.cumulativeDuration,v=d?_+p:f+h;if(c||!l&&f<=0){let e=o;o+=m,t.timelineStart=_;let r=a;a+=p,n.push({event:t,start:_,end:v,playout:{start:r,end:a},integrated:{start:e,end:o}})}else if(f<=i){if(!g){let i=f-r;if(i>LC){let c=r,l=o;o+=i;let u=a;a+=i;let d={previousEvent:e[s-1]||null,nextEvent:t,start:c,end:c+i,playout:{start:u,end:a},integrated:{start:l,end:o}};n.push(d)}else i>0&&u&&(u.cumulativeDuration+=i,n[n.length-1].end=f)}l&&(v=_),t.timelineStart=_;let i=o;o+=m;let c=a;a+=p,n.push({event:t,start:_,end:v,playout:{start:c,end:a},integrated:{start:i,end:o}})}else return;let y=t.resumeTime;r=l||y>i?i:y}),r{let c=o.cue.pre,l=o.cue.post,u=c?0:l?r:o.startTime;this.updateAssetDurations(o),a===u?o.cumulativeDuration=i:(i=0,a=u),!l&&o.snapOptions.in&&(o.resumeAnchor=Zg(null,n.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&s+1DC?(this.log(`"${e.identifier}" resumption ${n} not aligned with estimated timeline end ${r}`),!1):!Object.keys(t).some(r=>{let i=t[r].details,a=i.edge;if(n>=a)return this.log(`"${e.identifier}" resumption ${n} past ${r} playlist end ${a}`),!1;let o=Zg(null,i.fragments,n);if(!o)return this.log(`"${e.identifier}" resumption ${n} does not align with any fragments in ${r} playlist (${i.fragStart}-${i.fragmentEnd})`),!0;let s=r===`audio`?.175:0;return Math.abs(o.start-n){let a=t.data,o=a?.ASSETS;if(!Array.isArray(o)){let t=this.assignAssetListError(e,q.ASSET_LIST_PARSING_ERROR,Error(`Invalid interstitial asset list`),r.url,n,i);this.hls.trigger(J.ERROR,t);return}e.assetListResponse=a,this.hls.trigger(J.ASSET_LIST_LOADED,{event:e,assetListResponse:a,networkDetails:i})},onError:(t,n,r,i)=>{let a=this.assignAssetListError(e,q.ASSET_LIST_LOAD_ERROR,Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${n.url})`),n.url,i,r);this.hls.trigger(J.ERROR,a)},onTimeout:(t,n,r)=>{let i=this.assignAssetListError(e,q.ASSET_LIST_LOAD_TIMEOUT,Error(`Timeout loading X-ASSET-LIST (${n.url})`),n.url,t,r);this.hls.trigger(J.ERROR,i)}}),this.hls.trigger(J.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,n,r,i,a){return e.error=n,{type:K.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:n,networkDetails:a,stats:i}}};function VC(e){var t;e==null||(t=e.play())==null||t.catch(()=>{})}function HC(e,t){return`[${e}] Advancing timeline position to ${t}`}var UC=class extends zm{constructor(e,t){super(`interstitials`,e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{let e=this.currentTime;if(e===void 0||this.playbackDisabled||!this.schedule)return;let t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;let n=t<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=e,this.bufferedPos=e;let r=this.playingItem;if(!r){this.checkBuffer();return}if(n&&this.schedule.resetErrorsInRange(e,e-t)&&this.updateSchedule(!0),this.checkBuffer(),n&&e=r.end){var i;let t=this.findItemIndex(r),a=this.schedule.findItemIndexAtTime(e);if(a===-1&&(a=t+(n?-1:1),this.log(`seeked ${n?`back `:``}to position not covered by schedule ${e} (resolving from ${t} to ${a})`)),!this.isInterstitial(r)&&(i=this.media)!=null&&i.paused&&(this.shouldPlay=!1),!n&&a>t){let e=this.schedule.findJumpRestrictedIndex(t+1,a);if(e>t){this.setSchedulePosition(e);return}}this.setSchedulePosition(a);return}let a=this.playingAsset;if(!a){if(this.playingLastItem&&this.isInterstitial(r)){let t=r.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}let o=a.timelineStart,s=a.duration||0;if(n&&e=o+s){var c;(c=r.event)!=null&&c.appendInPlace&&(this.clearAssetPlayers(r.event,r),this.flushFrontBuffer(e)),this.setScheduleToAssetAtTime(e,a)}},this.onTimeupdate=()=>{let e=this.currentTime;if(e===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),e>this.timelinePos)this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();else return;let t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;let e=this.findItemIndex(t);this.setSchedulePosition(e+1)}let n=this.playingAsset;n&&e>=n.timelineStart+(n.duration||0)&&this.setScheduleToAssetAtTime(e,n)},this.onScheduleUpdate=(e,t)=>{let n=this.schedule;if(!n)return;let r=this.playingItem,i=n.events||[],a=n.items||[],o=n.durations,s=e.map(e=>e.identifier),c=!!(i.length||s.length);(c||t)&&this.log(`INTERSTITIALS_UPDATED (${i.length}): ${i} Schedule: ${a.map(e=>zC(e))} pos: ${this.timelinePos}`),s.length&&this.log(`Removed events ${s}`);let l=null,u=null;r&&(l=this.updateItem(r,this.timelinePos),this.itemsMatch(r,l)?this.playingItem=l:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);let d=this.bufferingItem;if(d&&(u=this.updateItem(d,this.bufferedPos),this.itemsMatch(d,u)?this.bufferingItem=u:d.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(d.event,null))),e.forEach(e=>{e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,null)})}),this.playerQueue.forEach(e=>{if(e.interstitial.appendInPlace){let t=e.assetItem.timelineStart,n=e.timelineOffset-t;if(n)try{e.timelineOffset=t}catch(r){Math.abs(n)>DC&&this.warn(`${r} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}}),c||t){if(this.hls.trigger(J.INTERSTITIALS_UPDATED,{events:i.slice(0),schedule:a.slice(0),durations:o,removedIds:s}),this.isInterstitial(r)&&s.includes(r.event.identifier)){this.warn(`Interstitial "${r.event.identifier}" removed while playing`),this.primaryFallback(r.event);return}r&&this.trimInPlace(l,r),d&&u!==l&&this.trimInPlace(u,d),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new BC(e),this.schedule=new RC(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(J.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(J.MANIFEST_LOADING,this.onManifestLoading,this),e.on(J.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(J.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(J.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(J.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(J.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(J.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(J.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(J.BUFFER_APPENDED,this.onBufferAppended,this),e.on(J.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(J.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(J.MEDIA_ENDED,this.onMediaEnded,this),e.on(J.ERROR,this.onError,this),e.on(J.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(J.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(J.MANIFEST_LOADING,this.onManifestLoading,this),e.off(J.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(J.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(J.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(J.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(J.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(J.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(J.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(J.BUFFER_CODECS,this.onBufferCodecs,this),e.off(J.BUFFER_APPENDED,this.onBufferAppended,this),e.off(J.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(J.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(J.MEDIA_ENDED,this.onMediaEnded,this),e.off(J.ERROR,this.onError,this),e.off(J.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){let e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){dy(e,`play`,this.onPlay),dy(e,`pause`,this.onPause),dy(e,`seeking`,this.onSeeking),dy(e,`timeupdate`,this.onTimeupdate)}onMediaAttaching(e,t){let n=this.media=t.media;uy(n,`seeking`,this.onSeeking),uy(n,`timeupdate`,this.onTimeupdate),uy(n,`play`,this.onPlay),uy(n,`pause`,this.onPause)}onMediaAttached(e,t){let n=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,n===null)this.checkStart();else if(!r){this.clearScheduleState();let e=this.findItemIndex(n);this.setSchedulePosition(e)}}clearScheduleState(){this.log(`clear schedule state`),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){let n=!!t.transferMedia,r=this.media;if(this.media=null,!n&&(r&&this.removeMediaListeners(r),this.detachedData)){let e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=()=>e.bufferingItem||e.waitingItem,n=t=>t&&e.getAssetPlayer(t.identifier),r=(t,r,i,o,s)=>{if(t){let c=t[r].start,l=t.event;if(l){if(r===`playout`||l.timelineOccupancy!==OC.Point){let e=n(i);e?.interstitial===l&&(c+=e.assetItem.startOffset+e[s])}}else{let n=o===`bufferedPos`?a():e[o];c+=n-t.start}return c}return 0},i=(t,n)=>{var r;if(t!==0&&n!==`primary`&&(r=e.schedule)!=null&&r.length){let r=e.schedule.findItemIndexAtTime(t),i=e.schedule.items?.[r];if(i)return t+(i[n].start-i.start)}return t},a=()=>{let t=e.bufferedPos;return t===Number.MAX_VALUE?o(`primary`):Math.max(t,0)},o=t=>{var n;return(n=e.primaryDetails)!=null&&n.live?e.primaryDetails.edge:e.schedule?.durations[t]||0},s=(t,i)=>{var a;let o=e.effectivePlayingItem;if(o!=null&&(a=o.event)!=null&&a.restrictions.skip||!e.schedule)return;e.log(`seek to ${t} "${i}"`);let s=e.effectivePlayingItem,c=e.schedule.findItemIndexAtTime(t,i),l=e.schedule.items?.[c],u=e.getBufferingPlayer(),d=u?.interstitial?.appendInPlace,f=s&&e.itemsMatch(s,l);if(s&&(d||f)){let a=n(e.playingAsset),o=a?.media||e.primaryMedia;if(o){let n=i===`primary`?o.currentTime:r(s,i,e.playingAsset,`timelinePos`,`currentTime`),c=t-n,l=(d?n:o.currentTime)+c;if(l>=0&&(!a||d||l<=a.duration)){o.currentTime=l;return}}}if(l){let n=t;if(i!==`primary`){let e=t-l[i].start;n=l.start+e}let r=!e.isInterstitial(l);if((!e.isInterstitial(s)||s.event.appendInPlace)&&(r||l.event.appendInPlace)){let t=e.media||(d?u?.media:null);t&&(t.currentTime=n)}else if(s){let a=e.findItemIndex(s);if(c>a){let t=e.schedule.findJumpRestrictedIndex(a+1,c);if(t>a){e.setSchedulePosition(t);return}}let o=0;if(r)e.timelinePos=n,e.checkBuffer();else{let e=l.event.assetList,n=t-(l[i]||l).start;for(let t=e.length;t--;){let r=e[t];if(r.duration&&n>=r.startOffset&&n{let n=e.effectivePlayingItem;if(e.isInterstitial(n))return n;let r=t();return e.isInterstitial(r)?r:null},l={get bufferedEnd(){let n=t(),i=e.bufferingItem;return i&&i===n&&(r(i,`playout`,e.bufferingAsset,`bufferedPos`,`bufferedEnd`)-i.playout.start||e.bufferingAsset?.startOffset)||0},get currentTime(){let t=c(),n=e.effectivePlayingItem;return n&&n===t?r(n,`playout`,e.effectivePlayingAsset,`timelinePos`,`currentTime`)-n.playout.start:0},set currentTime(t){let n=c(),r=e.effectivePlayingItem;r&&r===n&&s(t+r.playout.start,`playout`)},get duration(){let e=c();return e?e.playout.end-e.playout.start:0},get assetPlayers(){let t=c()?.event.assetList;return t?t.map(t=>e.getAssetPlayer(t.identifier)):[]},get playingIndex(){let t=c()?.event;return t&&e.effectivePlayingAsset?t.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return c()}};return this.manager={get events(){var t;return((t=e.schedule)==null||(t=t.events)==null?void 0:t.slice(0))||[]},get schedule(){var t;return((t=e.schedule)==null||(t=t.items)==null?void 0:t.slice(0))||[]},get interstitialPlayer(){return c()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){let n=t();return e.findItemIndex(n)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return a()},get currentTime(){let t=e.timelinePos;return t>0?t:0},set currentTime(e){s(e,`primary`)},get duration(){return o(`primary`)},get seekableStart(){return e.primaryDetails?.fragmentStart||0}},integrated:{get bufferedEnd(){return r(t(),`integrated`,e.bufferingAsset,`bufferedPos`,`bufferedEnd`)},get currentTime(){return r(e.effectivePlayingItem,`integrated`,e.effectivePlayingAsset,`timelinePos`,`currentTime`)},set currentTime(e){s(e,`integrated`)},get duration(){return o(`integrated`)},get seekableStart(){return i(e.primaryDetails?.fragmentStart||0,`integrated`)}},skip:()=>{let t=e.effectivePlayingItem,n=t?.event;if(n&&!n.restrictions.skip){let r=e.findItemIndex(t);n.appendInPlace?s(t.playout.start+t.event.duration+.001,`playout`):e.advanceAfterAssetEnded(n,r,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){let e=this.playingItem,t=this.schedule?.items;return!this.playbackStarted||!e||!t?!1:this.findItemIndex(e)===t.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e;if(this.mediaSelection===null)return;let t=this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&!t.event.appendInPlace)return;let n=this.media;!n&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(n=this.primaryMedia);let r=n?.currentTime;if(!(r===void 0||!G(r)))return r}get primaryMedia(){return this.media||this.detachedData?.media||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){let n=this.getAssetPlayer(e);n&&this.transferMediaFromPlayer(n,t)}transferMediaFromPlayer(e,t){let n=e.interstitial.appendInPlace,r=e.media;if(n&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}let n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${Pg(n)}`),this.detachedData=n}else t&&r&&(this.shouldPlay||=!r.paused)}transferMediaTo(e,t){if(e.media===t)return;let n=null,r=this.hls,i=e!==r,a=i&&e.interstitial.appendInPlace,o=this.detachedData?.mediaSource,s;if(r.media)a&&(n=r.transferMedia(),this.detachedData=n),s=`Primary`;else if(o){let e=this.getBufferingPlayer();e?(n=e.transferMedia(),s=`${e}`):s=`detached MediaSource`}else s=`detached media`;if(!n){if(o)n=this.detachedData,this.log(`using detachedData: MediaSource ${Pg(n)}`);else if(!this.detachedData||r.media===t){let e=this.playerQueue;e.length>1&&e.forEach(e=>{if(i&&e.interstitial.appendInPlace!==a){let t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let c=n&&`mediaSource`in n&&n.mediaSource?.readyState!==`closed`,l=c&&n?n:t;this.log(`${c?`transfering MediaSource`:`attaching media`} to ${i?e:`Primary`} from ${s} (media.currentTime: ${t.currentTime})`);let u=this.schedule;if(l===n&&u){let t=i&&e.assetId===u.assetIdAtEnd;l.overrides={duration:u.duration,endOfStream:!i||t,cueRemoval:!i}}e.attachMedia(l)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=e?.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);let n=this.timelinePos,r=this.effectivePlayingItem;if(n===-1){let n=this.hls.startPosition;if(this.timelinePos=n,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(HC(`checkStart (preroll)`,n));let r=e.findEventIndex(t[0].identifier);this.setSchedulePosition(r)}else if(n>=0||!this.primaryLive){this.log(HC(`checkStart`,n));let t=this.timelinePos=n>0?n:0,r=e.findItemIndexAtTime(t);this.setSchedulePosition(r)}else this.hls.liveSyncPosition===0?this.setSchedulePosition(0):this.log(`[checkStart] waiting for live start`)}else if(r&&!this.playingItem){this.log(HC(`checkStart (playing item)`,r.start));let t=e.findItemIndex(r);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){let n=e.event,r=NC(n,n.findAssetIndex(t));if(!n.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){let t=this.schedule.items?.[this.findItemIndex(e)+1];t&&this.bufferedToItem(t)}}advanceAfterAssetEnded(e,t,n){let r=NC(e,n);if(!e.isAssetPastPlayoutLimit(r)){if(e.appendInPlace){let t=e.assetList[r];t&&this.advanceInPlace(t.timelineStart)}this.setSchedulePosition(t,r)}else if(this.schedule){let n=this.schedule.items;if(n){let r=t+1;if(r>=n.length){this.setSchedulePosition(-1);return}let i=e.resumeTime;this.timelinePos=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&zC(r)}) pos: ${this.timelinePos}`);let i=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(i)){let s=i.event,c=this.playingAsset,l=c?.identifier,u=l?this.getAssetPlayer(l):null;if(u&&l&&(!this.eventItemsMatch(i,r)||t!==void 0&&l!==s.assetList[t].identifier)){var o;let t=s.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${s.assetList.length} ${FC(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(J.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:t,event:s,schedule:n.slice(0),scheduleIndex:e,player:u}),i!==this.playingItem){this.itemsMatch(i,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(s,this.findItemIndex(this.playingItem),t);return}this.retreiveMediaSource(l,r),u.media&&!((o=this.detachedData)!=null&&o.mediaSource)&&u.detachMedia()}if(!this.eventItemsMatch(i,r)&&(this.endedItem=i,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${s} ${zC(i)}`),s.hasPlayed=!0,this.hls.trigger(J.INTERSTITIAL_ENDED,{event:s,schedule:n.slice(0),scheduleIndex:e}),s.cue.once)){this.updateSchedule();let e=this.schedule?.items;if(r&&e){let n=this.findItemIndex(r);this.advanceSchedule(n,e,t,i,a)}return}}this.advanceSchedule(e,n,t,i,a)}advanceSchedule(e,t,n,r,i){let a=this.schedule;if(!a)return;let o=t[e]||null,s=this.primaryMedia,c=this.playerQueue;if(c.length&&c.forEach(t=>{let n=t.interstitial,r=a.findEventIndex(n.identifier);(re+1)&&this.clearInterstitial(n,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);let i=o.event;if(n===void 0){n=a.findAssetIndex(i,this.timelinePos);let t=NC(i,n-1);if(i.isAssetPastPlayoutLimit(t)||i.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(i,e,n);return}n=t}let c=this.waitingItem;this.assetsBuffered(o,s)||this.setBufferingItem(o);let l=this.preloadAssets(i,n);if(this.eventItemsMatch(o,c||r)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${zC(o)} ${i.appendInPlace?`append in place`:``}`),this.hls.trigger(J.INTERSTITIAL_STARTED,{event:i,schedule:t.slice(0),scheduleIndex:e})),!i.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${i}`);return}if(i.assetListLoader&&=(i.assetListLoader.destroy(),void 0),!s){this.log(`Waiting for attachMedia to start Interstitial ${i}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let u=i.assetList[n];if(!u){this.advanceAfterAssetEnded(i,e,n||0);return}if(l||=this.getAssetPlayer(u.identifier),l===null||l.destroyed){let e=i.assetList.length;this.warn(`asset ${n+1}/${e} player destroyed ${i}`),l=this.createAssetPlayer(i,u,n),l.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&i.appendInPlace&&this.isAssetBuffered(u))return;this.startAssetPlayer(l,n,t,e,s),this.shouldPlay&&VC(l.media)}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&VC(this.hls.media)):i&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){return this.mediaSelection?.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,n){var r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${zC(e)}`),!((r=this.detachedData)!=null&&r.mediaSource)){let n=this.timelinePos;(n=e.end)&&(n=this.getPrimaryResumption(e,t),this.log(HC(`resumePrimary`,n)),this.timelinePos=n),this.attachPrimary(n,e)}if(!n)return;let i=this.schedule?.items;i&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${zC(e)}`),this.hls.trigger(J.INTERSTITIALS_PRIMARY_RESUMED,{schedule:i.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){let n=e.start;if(this.primaryLive){let e=this.primaryDetails;if(t===0)return this.hls.startPosition;if(e&&(ne.edge))return this.hls.liveSyncPosition||-1}return n}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:Q.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,n){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let r=this.primaryMedia;if(!r)return;let i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,r),n&&this.startLoadingPrimaryAt(e,n)),n||(this.log(HC(`attachPrimary`,e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,n))}startLoadingPrimaryAt(e,t){let n=this.hls;!n.loadingEnabled||!n.media||Math.abs((n.mainForwardBufferInfo?.start||n.media.currentTime)-e)>.5?n.startLoad(e,t):n.bufferingEnabled||n.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(J.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(J.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let n=this.hls.levels[t.level];if(!n.details)return;let r=Im(Im({},this.mediaSelection||this.altSelection),{},{main:n});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){let n=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=Im(Im({},this.altSelection),{},{audio:n});return}let i=Im(Im({},r),{},{audio:n});this.mediaSelection=i}onSubtitleTrackUpdated(e,t){let n=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=Im(Im({},this.altSelection),{},{subtitles:n});return}let i=Im(Im({},r),{},{subtitles:n});this.mediaSelection=i}onAudioTrackSwitching(e,t){let n=zg(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(n)))}onSubtitleTrackSwitch(e,t){let n=zg(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setSubtitleOption(t)||t.id!==-1&&e.setSubtitleOption(n)))}onBufferCodecs(e,t){let n=t.tracks;n&&(this.requiredTracks=n)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let n=this.playingItem;if(n&&!this.itemsMatch(n,this.bufferingItem)&&!this.isInterstitial(n)){let e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos.25){e.event.assetList.forEach((t,n)=>{e.event.isAssetPastPlayoutLimit(n)&&this.clearAssetPlayer(t.identifier,null)});let n=e.end+.25,r=Q.bufferInfo(this.primaryMedia,n,0);(r.end>n||(r.nextStart||0)>n)&&(this.log(`trim buffered interstitial ${zC(e)} (was ${zC(t)})`),this.attachPrimary(n,null,!0),this.flushFrontBuffer(n))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){return!!t&&(e===t||e.event.identifier===t.event?.identifier)}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;let n=this.mediaSelection;n&&((t=this.schedule)==null||t.updateSchedule(n,[],e))}checkBuffer(e){let t=this.schedule?.items;if(!t)return;let n=Q.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||=n.len<1,this.updateBufferedPos(n.end,t,e)}updateBufferedPos(e,t,n){let r=this.schedule,i=this.bufferingItem;if(this.bufferedPos>e||!r)return;if(t.length===1&&this.itemsMatch(t[0],i)){this.bufferedPos=e;return}let a=this.playingItem,o=this.findItemIndex(a),s=r.findItemIndexAtTime(e);if(this.bufferedPos=i.end||(c=a.event)!=null&&c.appendInPlace&&e+.01>=a.start)&&(s=r),this.isInterstitial(i)){let e=i.event;if(r-o>1&&e.appendInPlace===!1||e.assetList.length===0&&e.assetListLoader)return}if(this.bufferedPos=e,s>n&&s>o)this.bufferedToItem(a);else{let t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&a.start{let n=this.getAssetPlayer(e.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,n=this.schedule;if(!this.itemsMatch(e,t)&&n){let{items:r,events:i}=n;if(!r||!i)return t;let a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let s=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${zC(e)}`+(t?` (${s.toFixed(2)} remaining)`:``)),!this.playbackDisabled)if(a){let t=n.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((e,n)=>{let r=this.getAssetPlayer(e.identifier);r&&(n===t&&r.loadSource(),r.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(e=>e.pauseBuffering());this.hls.trigger(J.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let n=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(n!==null){this.bufferingAsset=null;let t=this.detachedData;t&&t.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e)}}}preloadPrimary(e){let t=this.findItemIndex(e),n=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(n)}bufferedToEvent(e,t){let n=e.event,r=n.assetList.length===0&&!n.assetListLoader,i=n.cue.once;if(r||!i){let e=this.preloadAssets(n,t);if(e!=null&&e.interstitial.appendInPlace){let t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){let n=e.assetUrl,r=e.assetList.length,i=r===0&&!e.assetListLoader,a=e.cue.once;if(i){let i=e.timelineStart;if(e.appendInPlace){var o;let t=this.playingItem;!this.isInterstitial(t)&&(t==null||(o=t.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(i+.25)}let a,s=0;if(!this.playingItem&&this.primaryLive&&(s=this.hls.startPosition,s===-1&&(s=this.hls.liveSyncPosition||0)),s&&!(e.cue.pre||e.cue.post)){let e=s-i;e>0&&(a=Math.round(e*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${n?1:r} ${e}${a?` live-start: ${s} start-offset: ${a}`:``}`),n)return this.createAsset(e,0,0,i,e.duration,n);let c=this.assetListLoader.loadAssetList(e,a);c&&(e.assetListLoader=c)}else if(!a&&r){for(let n=t;n{this.hls.trigger(J.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})}))}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let n=0;n1){let n=t.duration;n&&e{if(r.live){let t=Error(`Interstitials MUST be VOD assets ${e}`),r={fatal:!0,type:K.OTHER_ERROR,details:q.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},i=this.schedule?.findEventIndex(e.identifier)||-1;this.handleAssetItemError(r,e,i,n,t.message);return}let i=r.edge-r.fragmentStart,a=t.duration;(m||a===null||i>a)&&(m=!1,this.log(`Interstitial asset "${u}" duration change ${a} > ${i}`),t.duration=i,this.updateSchedule())};p.on(J.LEVEL_UPDATED,(e,{details:t})=>h(t)),p.on(J.LEVEL_PTS_UPDATED,(e,{details:t})=>h(t)),p.on(J.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let g=(e,t)=>{let n=this.getAssetPlayer(u);if(n&&t.tracks){n.off(J.BUFFER_CODECS,g),n.tracks=t.tracks;let e=this.primaryMedia;this.bufferingAsset===n.assetItem&&e&&!n.media&&this.bufferAssetPlayer(n,e)}};p.on(J.BUFFER_CODECS,g),p.on(J.BUFFERED_TO_END,()=>{let n=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${n}`),!n||!this.schedule)return;let r=this.schedule.findEventIndex(e.identifier),i=this.schedule.items?.[r];this.isInterstitial(i)&&this.advanceAssetBuffering(i,t)});let _=t=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=!0;let n=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,n,t)};return p.once(J.MEDIA_ENDED,_(n)),p.once(J.PLAYOUT_LIMIT_REACHED,_(1/0)),p.on(J.ERROR,(t,r)=>{if(!this.schedule)return;let i=this.getAssetPlayer(u);if(r.details===q.BUFFER_STALLED_ERROR){if(i!=null&&i.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(r,e,this.schedule.findEventIndex(e.identifier),n,`Asset player error ${r.error} ${e}`)}),p.on(J.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;let t=Error(`Asset player destroyed unexpectedly ${u}`),r={fatal:!0,type:K.OTHER_ERROR,details:q.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(r,e,this.schedule.findEventIndex(e.identifier),n,t.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${FC(t)}`),this.hls.trigger(J.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:n,event:e,player:p}),p}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let n=this.playerQueue[t];this.transferMediaFromPlayer(n,null),n.resetDetails()}}clearAssetPlayer(e,t){let n=this.getAssetPlayerQueueIndex(e);if(n!==-1){let e=this.playerQueue[n];this.log(`clear ${e} toSegment: ${t&&zC(t)}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(n,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,n,r,i){let{interstitial:a,assetItem:o,assetId:s}=e,c=a.assetList.length,l=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!l||l.identifier!==s)&&(l&&(this.clearAssetPlayer(l.identifier,n[r]),delete l.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${c} ${FC(o)}`),this.hls.trigger(J.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:n.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,i)}bufferAssetPlayer(e,t){if(!this.schedule)return;let{interstitial:n,assetItem:r}=e,i=this.schedule.findEventIndex(n.identifier),a=this.schedule.items?.[i];if(!a)return;e.loadSource(),this.setBufferingItem(a),this.bufferingAsset=r;let o=this.getBufferingPlayer();if(o===e)return;let s=n.appendInPlace;if(s&&o?.interstitial.appendInPlace===!1)return;let c=o?.tracks||this.detachedData?.tracks||this.requiredTracks;if(s&&r!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(c&&!Xm(c,e.tracks)){let t=Error(`Asset ${FC(r)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),a={fatal:!0,type:K.OTHER_ERROR,details:q.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},o=n.findAssetIndex(r);this.handleAssetItemError(a,n,i,o,t.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,n=this.primaryMedia;if(!t||!n)return;let r=n.currentTime,i=t.findAssetIndex(e,r),a=e.assetList[i];if(a){let o=this.getAssetPlayer(a.identifier);if(o){let s=o.currentTime||r-a.timelineStart,c=o.duration-s;if(this.warn(`Stalled at ${s} of ${s+c} in ${o} ${e} (media.currentTime: ${r})`),s&&(c/n.playbackRate<.5||o.bufferedInPlaceToEnd(n))&&o.hls){let n=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,n,i)}}}}advanceInPlace(e){let t=this.primaryMedia;t&&t.currentTime!e.error))t.error=p;else for(let e=r;e{let n=parseFloat(e.DURATION);this.createAsset(r,t,c,o+c,n,e.URI),c+=n}),r.duration=c,this.log(`Loaded asset-list with duration: ${c} (was: ${s}) ${r}`);let l=this.waitingItem?.event.identifier===i;this.updateSchedule();let u=this.bufferingItem?.event;if(l){let e=this.schedule.findEventIndex(i),t=this.schedule.items?.[e];if(t){if(!this.playingItem&&this.timelinePos>t.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==e){r.error=Error(`Interstitial ${a.length?`no longer within playback range`:`asset-list is empty`} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(t)}this.setSchedulePosition(e)}else if(u?.identifier===i){let e=r.assetList[0];if(e){let t=this.getAssetPlayer(e.identifier);if(u.appendInPlace){let e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case q.ASSET_LIST_PARSING_ERROR:case q.ASSET_LIST_LOAD_ERROR:case q.ASSET_LIST_LOAD_TIMEOUT:{let e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case q.BUFFER_STALLED_ERROR:{let e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace){this.handleInPlaceStall(e.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},WC=500,GC=class extends py{constructor(e,t,n){super(e,t,n,`subtitle-stream-controller`,Y.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(J.LEVEL_LOADED,this.onLevelLoaded,this),e.on(J.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(J.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(J.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(J.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(J.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(J.LEVEL_LOADED,this.onLevelLoaded,this),e.off(J.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(J.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(J.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(J.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(J.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=$.IDLE,this.setInterval(WC),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){let{frag:n,success:r}=t;if(this.fragContextChanged(n)||(ch(n)&&(this.fragPrevious=n),this.state=$.IDLE),!r)return;let i=this.tracksBuffered[this.currentTrackId];if(!i)return;let a,o=n.start;for(let e=0;e=i[e].start&&o<=i[e].end){a=i[e];break}let s=n.start+n.duration;a?a.end=s:(a={start:o,end:s},i.push(a)),this.fragmentTracker.fragBuffered(n),this.fragBufferedComplete(n,null),this.media&&this.tick()}onBufferFlushing(e,t){let{startOffset:n,endOffset:r}=t;if(n===0&&r!==1/0){let e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{for(let n=0;nnew kg(e));return}this.tracksBuffered=[],this.levels=t.map(e=>{let t=new kg(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,1/0,Y.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var n;if(this.currentTrackId=t.id,!((n=this.levels)!=null&&n.length)||this.currentTrackId===-1){this.clearInterval();return}let r=this.levels[this.currentTrackId];r!=null&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==$.STOPPED&&this.setInterval(WC)}onSubtitleTrackLoaded(e,t){var n;let{currentTrackId:r,levels:i}=this,{details:a,id:o}=t;if(!i){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let s=i[o];if(o>=i.length||!s)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:``},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(a.live||(n=s.details)!=null&&n.live){if(a.deltaUpdateFailed)return;let e=this.mainDetails;if(!e){this.startFragRequested=!1;return}let t=e.fragments[0];s.details?(c=this.alignPlaylists(a,s.details,this.levelLastLoaded?.details),c===0&&t&&(c=t.start,Yv(a,c))):a.hasProgramDateTime&&e.hasProgramDateTime?(ly(a,e),c=a.fragmentStart):t&&(c=t.start,Yv(a,c)),e&&!this.startFragRequested&&this.setStartPosition(e,c)}s.details=a,this.levelLastLoaded=s,o===r&&(this.hls.trigger(J.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===$.IDLE&&(Zg(null,a.fragments,this.media.currentTime,0)||(this.warn(`Subtitle playlist not aligned with playback`),s.details=void 0)))}_handleFragmentLoadComplete(e){let{frag:t,payload:n}=e,r=t.decryptdata,i=this.hls;if(!this.fragContextChanged(t)&&n&&n.byteLength>0&&r!=null&&r.key&&r.iv&&ev(r.method)){let e=performance.now();this.decrypter.decrypt(new Uint8Array(n),r.key.buffer,r.iv.buffer,tv(r.method)).catch(e=>{throw i.trigger(J.ERROR,{type:K.MEDIA_ERROR,details:q.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(n=>{let r=performance.now();i.trigger(J.FRAG_DECRYPTED,{frag:t,payload:n,stats:{tstart:e,tdecrypt:r}})}).catch(e=>{this.warn(`${e.name}: ${e.message}`),this.state=$.IDLE})}}doTick(){if(!this.media){this.state=$.IDLE;return}if(this.state===$.IDLE){let{currentTrackId:e,levels:t}=this,n=t?.[e];if(!n||!t.length||!n.details||this.waitForLive(n))return;let{config:r}=this,i=this.getLoadPosition(),{end:a,len:o}=Q.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,r.maxBufferHole),s=n.details;if(o>this.hls.maxBufferLength+s.levelTargetDuration)return;let c=s.fragments,l=c.length,u=s.edge,d=null,f=this.fragPrevious;if(au-e?0:e;d=Zg(f,c,Math.max(c[0].start,a),t),!d&&f&&f.start{if(n>>>=0,n>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${r})`);return e[n][t]};this.buffered={get length(){return e.length},end(n){return t(`end`,n,e.length)},start(n){return t(`start`,n,e.length)}}}},qC={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},JC=e=>String.fromCharCode(qC[e]||e),YC=15,XC=100,ZC={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},QC={17:2,18:4,21:6,22:8,23:10,19:13,20:15},$C={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},ew={25:2,26:4,29:6,30:8,31:10,27:13,28:15},tw=[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`,`black`,`transparent`],nw=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let n=typeof t==`function`?t():t;qm.log(`${this.time} [${e}] ${n}`)}}},rw=function(e){let t=[];for(let n=0;nXC&&(this.logger.log(3,`Too large cursor position `+this.pos),this.pos=XC)}moveCursor(e){let t=this.pos+e;if(e>1)for(let e=this.pos+1;e=144&&this.backSpace();let t=JC(e);if(this.pos>=XC){this.logger.log(0,()=>`Cannot insert `+e.toString(16)+` (`+t+`) at position `+this.pos+`. Skipping it!`);return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t`pacData = `+Pg(e));let t=e.row-1;if(this.nrRollUpRows&&t`bkgData = `+Pg(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,`roll_up but nrRollUpRows not set yet`);return}this.logger.log(1,()=>this.getDisplayText());let e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,`Rolling up`)}getDisplayText(e){e||=!1;let t=[],n=``,r=-1;for(let n=0;n0&&(n=e?`[`+t.join(` | `)+`]`:t.join(` `)),n}getTextAndFormat(){return this.rows}},cw=class{constructor(e,t,n){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=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new sw(n),this.nonDisplayedMemory=new sw(n),this.lastOutputScreen=new sw(n),this.currRollUpRow=this.displayedMemory.rows[YC-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[YC-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>`MODE=`+e),this.mode===`MODE_POP-ON`?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!==`MODE_ROLL-UP`&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;tt+`: `+this.writeScreen.getDisplayText(!0)),(this.mode===`MODE_PAINT-ON`||this.mode===`MODE_ROLL-UP`)&&(this.logger.log(1,()=>`DISPLAYED: `+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,`RCL - Resume Caption Loading`),this.setMode(`MODE_POP-ON`)}ccBS(){this.logger.log(2,`BS - BackSpace`),this.mode!==`MODE_TEXT`&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,`DER- Delete to End of Row`),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,`RU(`+e+`) - Roll Up`),this.writeScreen=this.displayedMemory,this.setMode(`MODE_ROLL-UP`),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,`FON - Flash On`),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,`RDC - Resume Direct Captioning`),this.setMode(`MODE_PAINT-ON`)}ccTR(){this.logger.log(2,`TR`),this.setMode(`MODE_TEXT`)}ccRTD(){this.logger.log(2,`RTD`),this.setMode(`MODE_TEXT`)}ccEDM(){this.logger.log(2,`EDM - Erase Displayed Memory`),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,`CR - Carriage Return`),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,`ENM - Erase Non-displayed Memory`),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,`EOC - End Of Caption`),this.mode===`MODE_POP-ON`){let e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>`DISP: `+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,`TO(`+e+`) - Tab Offset`),this.writeScreen.moveCursor(e)}ccMIDROW(e){let t={flash:!1};t.underline=e%2==1,t.italics=e>=46,t.italics?t.foreground=`white`:t.foreground=[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`][Math.floor(e/2)-16],this.logger.log(2,`MIDROW: `+Pg(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}},lw=class{constructor(e,t,n){this.channels=void 0,this.currentChannel=0,this.cmdHistory=fw(),this.logger=void 0;let r=this.logger=new nw;this.channels=[null,new cw(e,t,r),new cw(e+1,n,r)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let e=0;e`[`+rw([t[e],t[e+1]])+`] -> (`+rw([n,r])+`)`);let o=this.cmdHistory;if(n>=16&&n<=31){if(dw(n,r,o)){uw(null,null,o),this.logger.log(3,()=>`Repeated command (`+rw([n,r])+`) is dropped`);continue}uw(n,r,this.cmdHistory),i=this.parseCmd(n,r),i||=this.parseMidrow(n,r),i||=this.parsePAC(n,r),i||=this.parseBackgroundAttributes(n,r)}else uw(null,null,o);if(!i&&(a=this.parseChars(n,r),a)){let e=this.currentChannel;e&&e>0?this.channels[e].insertChars(a):this.logger.log(2,`No channel found yet. TEXT-MODE?`)}!i&&!a&&this.logger.log(2,()=>`Couldn't parse cleaned data `+rw([n,r])+` orig: `+rw([t[e],t[e+1]]))}}parseCmd(e,t){if(!((e===20||e===28||e===21||e===29)&&t>=32&&t<=47||(e===23||e===31)&&t>=33&&t<=35))return!1;let n=e===20||e===21||e===23?1:2,r=this.channels[n];return e===20||e===21||e===28||e===29?t===32?r.ccRCL():t===33?r.ccBS():t===34?r.ccAOF():t===35?r.ccAON():t===36?r.ccDER():t===37?r.ccRU(2):t===38?r.ccRU(3):t===39?r.ccRU(4):t===40?r.ccFON():t===41?r.ccRDC():t===42?r.ccTR():t===43?r.ccRTD():t===44?r.ccEDM():t===45?r.ccCR():t===46?r.ccENM():t===47&&r.ccEOC():r.ccTO(t-32),this.currentChannel=n,!0}parseMidrow(e,t){let n=0;if((e===17||e===25)&&t>=32&&t<=47){if(n=e===17?1:2,n!==this.currentChannel)return this.logger.log(0,`Mismatch channel in midrow parsing`),!1;let r=this.channels[n];return r?(r.ccMIDROW(t),this.logger.log(3,()=>`MIDROW (`+rw([e,t])+`)`),!0):!1}return!1}parsePAC(e,t){let n;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(e===16||e===24)&&t>=64&&t<=95))return!1;let r=e<=23?1:2;n=t>=64&&t<=95?r===1?ZC[e]:$C[e]:r===1?QC[e]:ew[e];let i=this.channels[r];return i?(i.setPAC(this.interpretPAC(n,t)),this.currentChannel=r,!0):!1}interpretPAC(e,t){let n,r={color:null,italics:!1,indent:null,underline:!1,row:e};return n=t>95?t-96:t-64,r.underline=(n&1)==1,n<=13?r.color=[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`,`white`][Math.floor(n/2)]:n<=15?(r.italics=!0,r.color=`white`):r.indent=Math.floor((n-16)/2)*4,r}parseChars(e,t){let n,r=null,i=null;if(e>=25?(n=2,i=e-8):(n=1,i=e),i>=17&&i<=19){let e;e=i===17?t+80:i===18?t+112:t+144,this.logger.log(2,()=>`Special char '`+JC(e)+`' in channel `+n),r=[e]}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>`Char codes = `+rw(r).join(`,`)),r}parseBackgroundAttributes(e,t){if(!((e===16||e===24)&&t>=32&&t<=47||(e===23||e===31)&&t>=45&&t<=47))return!1;let n,r={};e===16||e===24?(n=Math.floor((t-32)/2),r.background=tw[n],t%2==1&&(r.background+=`_semi`)):t===45?r.background=`transparent`:(r.foreground=`black`,t===47&&(r.underline=!0));let i=e<=23?1:2;return this.channels[i].setBkgData(r),!0}reset(){for(let e=0;e100)throw Error(`Position must be between 0 and 100.`);v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,`positionAlign`,a({},s,{get:function(){return y},set:function(e){let t=i(e);if(!t)throw SyntaxError(`An invalid or illegal string was specified.`);y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,`size`,a({},s,{get:function(){return b},set:function(e){if(e<0||e>100)throw Error(`Size must be between 0 and 100.`);b=e,this.hasBeenReset=!0}})),Object.defineProperty(o,`align`,a({},s,{get:function(){return x},set:function(e){let t=i(e);if(!t)throw SyntaxError(`An invalid or illegal string was specified.`);x=t,this.hasBeenReset=!0}})),o.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o})(),mw=class{decode(e,t){if(!e)return``;if(typeof e!=`string`)throw Error(`Error - expected string data.`);return decodeURIComponent(encodeURIComponent(e))}};function hw(e){function t(e,t,n,r){return(e|0)*3600+(t|0)*60+(n|0)+parseFloat(r||0)}let n=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return n?parseFloat(n[2])>59?t(n[2],n[3],0,n[4]):t(n[1],n[2],n[3],n[4]):null}var gw=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==``&&(this.values[e]=t)}get(e,t,n){return n?this.has(e)?this.values[e]:t[n]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,n){for(let r=0;r=0&&n<=100)return this.set(e,n),!0}return!1}};function _w(e,t,n,r){let i=r?e.split(r):[e];for(let e in i){if(typeof i[e]!=`string`)continue;let r=i[e].split(n);if(r.length!==2)continue;let a=r[0],o=r[1];t(a,o)}}var vw=new pw(0,0,``),yw=vw.align===`middle`?`middle`:`center`;function bw(e,t,n){let r=e;function i(){let t=hw(e);if(t===null)throw Error(`Malformed timestamp: `+r);return e=e.replace(/^[^\sa-zA-Z-]+/,``),t}function a(e,t){let r=new gw;_w(e,function(e,t){let i;switch(e){case`region`:for(let i=n.length-1;i>=0;i--)if(n[i].id===t){r.set(e,n[i].region);break}break;case`vertical`:r.alt(e,t,[`rl`,`lr`]);break;case`line`:i=t.split(`,`),r.integer(e,i[0]),r.percent(e,i[0])&&r.set(`snapToLines`,!1),r.alt(e,i[0],[`auto`]),i.length===2&&r.alt(`lineAlign`,i[1],[`start`,yw,`end`]);break;case`position`:i=t.split(`,`),r.percent(e,i[0]),i.length===2&&r.alt(`positionAlign`,i[1],[`start`,yw,`end`,`line-left`,`line-right`,`auto`]);break;case`size`:r.percent(e,t);break;case`align`:r.alt(e,t,[`start`,yw,`end`,`left`,`right`]);break}},/:/,/\s/),t.region=r.get(`region`,null),t.vertical=r.get(`vertical`,``);let i=r.get(`line`,`auto`);i===`auto`&&vw.line===-1&&(i=-1),t.line=i,t.lineAlign=r.get(`lineAlign`,`start`),t.snapToLines=r.get(`snapToLines`,!0),t.size=r.get(`size`,100),t.align=r.get(`align`,yw);let a=r.get(`position`,`auto`);a===`auto`&&vw.position===50&&(a=t.align===`start`||t.align===`left`?0:t.align===`end`||t.align===`right`?100:50),t.position=a}function o(){e=e.replace(/^\s+/,``)}if(o(),t.startTime=i(),o(),e.slice(0,3)!==`-->`)throw Error(`Malformed time stamp (time stamps must be separated by '-->'): `+r);e=e.slice(3),o(),t.endTime=i(),o(),a(e,t)}function xw(e){return e.replace(//gi,` `)}var Sw=class{constructor(){this.state=`INITIAL`,this.buffer=``,this.decoder=new mw,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){let t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function n(){let e=t.buffer,n=0;for(e=xw(e);n`)===-1){t.cue.id=e;continue}case`CUE`:if(!t.cue){t.state=`BADCUE`;continue}try{bw(e,t.cue,t.regionList)}catch{t.cue=null,t.state=`BADCUE`;continue}t.state=`CUETEXT`;continue;case`CUETEXT`:{let n=e.indexOf(`-->`)!==-1;if(!e||n&&(i=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state=`ID`;continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=` `),t.cue.text+=e}continue;case`BADCUE`:e||(t.state=`ID`)}}}catch{t.state===`CUETEXT`&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state===`INITIAL`?`BADWEBVTT`:`BADCUE`}return this}flush(){let e=this;try{if((e.cue||e.state===`HEADER`)&&(e.buffer+=` `,e.parse()),e.state===`INITIAL`||e.state===`BADWEBVTT`)throw Error(`Malformed WebVTT signature.`)}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}},Cw=/\r\n|\n\r|\n|\r/g,ww=function(e,t,n=0){return e.slice(n,n+t.length)===t},Tw=function(e){let t=parseInt(e.slice(-3)),n=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),i=e.length>9?parseInt(e.substring(0,e.indexOf(`:`))):0;if(!G(t)||!G(n)||!G(r)||!G(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*n,t+=60*1e3*r,t+=3600*1e3*i,t};function Ew(e,t,n){return EC(e.toString())+EC(t.toString())+EC(n)}var Dw=function(e,t,n){let r=e[t],i=e[r.prevCC];if(!i||!i.new&&r.new){e.ccOffset=e.presentationOffset=r.start,r.new=!1;return}for(;(a=i)!=null&&a.new;){var a;e.ccOffset+=r.start-i.start,r.new=!1,r=i,i=e[r.prevCC]}e.presentationOffset=n};function Ow(e,t,n,r,i,a,o){let s=new Sw,c=Zm(new Uint8Array(e)).trim().replace(Cw,` `).split(` `),l=[],u=t?Xb(t.baseTime,t.timescale):0,d=`00:00.000`,f=0,p=0,m,h=!0;s.oncue=function(e){let a=n[r],o=n.ccOffset,s=(f-u)/9e4;if(a!=null&&a.new&&(p===void 0?Dw(n,r,s):o=n.ccOffset=a.start),s){if(!t){m=Error(`Missing initPTS for VTT MPEGTS`);return}o=s-n.presentationOffset}let c=e.endTime-e.startTime,d=ox((e.startTime+o-p)*9e4,i*9e4)/9e4;e.startTime=Math.max(d,0),e.endTime=Math.max(d+c,0);let h=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(h)),e.id||=Ew(e.startTime,e.endTime,h),e.endTime>0&&l.push(e)},s.onparsingerror=function(e){m=e},s.onflush=function(){if(m){o(m);return}a(l)},c.forEach(e=>{if(h)if(ww(e,`X-TIMESTAMP-MAP=`)){h=!1,e.slice(16).split(`,`).forEach(e=>{ww(e,`LOCAL:`)?d=e.slice(6):ww(e,`MPEGTS:`)&&(f=parseInt(e.slice(7)))});try{p=Tw(d)/1e3}catch(e){m=e}return}else e===``&&(h=!1);s.parse(e+` `)}),s.flush()}var kw=`stpp.ttml.im1t`,Aw=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,jw=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Mw={left:`start`,center:`center`,right:`end`,start:`start`,end:`end`};function Nw(e,t,n,r){let i=Z(new Uint8Array(e),[`mdat`]);if(i.length===0){r(Error(`Could not parse IMSC1 mdat`));return}let a=i.map(e=>Zm(e)),o=Jb(t.baseTime,1,t.timescale);try{a.forEach(e=>n(Pw(e,o)))}catch(e){r(e)}}function Pw(e,t){let n=new DOMParser().parseFromString(e,`text/xml`).getElementsByTagName(`tt`)[0];if(!n)throw Error(`Invalid ttml`);let r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},i=Object.keys(r).reduce((e,t)=>(e[t]=n.getAttribute(`ttp:${t}`)||r[t],e),{}),a=n.getAttribute(`xml:space`)!==`preserve`,o=Iw(Fw(n,`styling`,`style`)),s=Iw(Fw(n,`layout`,`region`)),c=Fw(n,`body`,`[begin]`);return[].map.call(c,e=>{let n=Lw(e,a);if(!n||!e.hasAttribute(`begin`))return null;let r=Vw(e.getAttribute(`begin`),i),c=Vw(e.getAttribute(`dur`),i),l=Vw(e.getAttribute(`end`),i);if(r===null)throw Bw(e);if(l===null){if(c===null)throw Bw(e);l=r+c}let u=new pw(r-t,l-t,n);u.id=Ew(u.startTime,u.endTime,u.text);let d=s[e.getAttribute(`region`)],f=o[e.getAttribute(`style`)],p=Rw(d,f,o),{textAlign:m}=p;if(m){let e=Mw[m];e&&(u.lineAlign=e),u.align=m}return Pm(u,p),u}).filter(e=>e!==null)}function Fw(e,t,n){let r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function Iw(e){return e.reduce((e,t)=>{let n=t.getAttribute(`xml:id`);return n&&(e[n]=t),e},{})}function Lw(e,t){return[].slice.call(e.childNodes).reduce((e,n,r)=>{var i;return n.nodeName===`br`&&r?e+` `:(i=n.childNodes)!=null&&i.length?Lw(n,t):t?e+n.textContent.trim().replace(/\s+/g,` `):e+n.textContent},``)}function Rw(e,t,n){let r=`http://www.w3.org/ns/ttml#styling`,i=null,a=[`displayAlign`,`textAlign`,`color`,`backgroundColor`,`fontSize`,`fontFamily`],o=e!=null&&e.hasAttribute(`style`)?e.getAttribute(`style`):null;return o&&n.hasOwnProperty(o)&&(i=n[o]),a.reduce((n,a)=>{let o=zw(t,r,a)||zw(e,r,a)||zw(i,r,a);return o&&(n[a]=o),n},{})}function zw(e,t,n){return e&&e.hasAttributeNS(t,n)?e.getAttributeNS(t,n):null}function Bw(e){return Error(`Could not parse ttml timestamp ${e}`)}function Vw(e,t){if(!e)return null;let n=hw(e);return n===null&&(Aw.test(e)?n=Hw(e,t):jw.test(e)&&(n=Uw(e,t))),n}function Hw(e,t){let n=Aw.exec(e),r=(n[4]|0)+(n[5]|0)/t.subFrameRate;return(n[1]|0)*3600+(n[2]|0)*60+(n[3]|0)+r/t.frameRate}function Uw(e,t){let n=jw.exec(e),r=Number(n[1]);switch(n[2]){case`h`:return r*3600;case`m`:return r*60;case`ms`:return r*1e3;case`f`:return r/t.frameRate;case`t`:return r/t.tickRate}return r}var Ww=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,n){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Gw=class{constructor(e){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.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Yw(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.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}},e.on(J.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(J.MANIFEST_LOADING,this.onManifestLoading,this),e.on(J.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(J.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(J.FRAG_LOADING,this.onFragLoading,this),e.on(J.FRAG_LOADED,this.onFragLoaded,this),e.on(J.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(J.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(J.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(J.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(J.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(J.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(J.MANIFEST_LOADING,this.onManifestLoading,this),e.off(J.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(J.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(J.FRAG_LOADING,this.onFragLoading,this),e.off(J.FRAG_LOADED,this.onFragLoaded,this),e.off(J.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(J.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(J.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(J.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(J.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new Ww(this,`textTrack1`),t=new Ww(this,`textTrack2`),n=new Ww(this,`textTrack3`),r=new Ww(this,`textTrack4`);this.cea608Parser1=new lw(1,e,t),this.cea608Parser2=new lw(3,n,r)}addCues(e,t,n,r,i){let a=!1;for(let e=i.length;e--;){let r=i[e],o=Jw(r[0],r[1],t,n);if(o>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],n),a=!0,o/(n-t)>.5))return}if(a||i.push([t,n]),this.config.renderTextTracksNatively){let i=this.captionsTracks[e];this.Cues.newCue(i,t,n,r)}else{let i=this.Cues.newCue(null,t,n,r);this.hls.trigger(J.CUES_PARSED,{type:`captions`,cues:i,track:e})}}onInitPtsFound(e,{frag:t,id:n,initPTS:r,timescale:i,trackId:a}){let{unparsedVttFrags:o}=this;n===Y.MAIN&&(this.initPTS[t.cc]={baseTime:r,timescale:i,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(J.FRAG_LOADED,e):this.hls.trigger(J.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:Error(`Subtitle discontinuity domain does not match main`)})}))}getExistingTrack(e,t){let{media:n}=this;if(n)for(let r=0;r{yC(r[e]),delete r[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Yw(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){let{media:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let e=0;ee.textCodec===kw);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(Dx(this.tracks,n)){this.tracks=n;return}if(this.textTracks=[],this.tracks=n,this.config.renderTextTracksNatively){let e=this.media,t=e?CC(e.textTracks):null;if(this.tracks.forEach((e,n)=>{let r;if(t){let n=null;for(let r=0;re!==null).map(e=>e.label);e.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${e.join(`, `)}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){let e=this.tracks.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(J.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{let t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;let n=`textTrack${t[1]}`,r=this.captionsProperties[n];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)})}closedCaptionsForLevel(e){return this.hls.levels[e.level]?.attrs[`CLOSED-CAPTIONS`]}onFragLoading(e,t){if(this.enabled&&t.frag.type===Y.MAIN){let{cea608Parser1:e,cea608Parser2:n,lastSn:r}=this,{cc:i,sn:a}=t.frag,o=t.part?.index??-1;e&&n&&(a!==r+1||a===r&&o!==this.lastPartIndex+1||i!==this.lastCc)&&(e.reset(),n.reset()),this.lastCc=i,this.lastSn=a,this.lastPartIndex=o}}onFragLoaded(e,t){let{frag:n,payload:r}=t;if(n.type===Y.SUBTITLE)if(r.byteLength){let e=n.decryptdata,i=`stats`in t;if(e==null||!e.encrypted||i){let e=this.tracks[n.level],i=this.vttCCs;i[n.cc]||(i[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),e&&e.textCodec===kw?this._parseIMSC1(n,r):this._parseVTTs(t)}}else this.hls.trigger(J.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:Error(`Empty subtitle payload`)})}_parseIMSC1(e,t){let n=this.hls;Nw(t,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),n.trigger(J.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},t=>{n.logger.log(`Failed to parse IMSC1: ${t}`),n.trigger(J.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}_parseVTTs(e){var t;let{frag:n,payload:r}=e,{initPTS:i,unparsedVttFrags:a}=this,o=i.length-1;if(!i[n.cc]&&o===-1){a.push(e);return}let s=this.hls;Ow((t=n.initSegment)!=null&&t.data?Fh(n.initSegment.data,new Uint8Array(r)).buffer:r,this.initPTS[n.cc],this.vttCCs,n.cc,n.start,e=>{this._appendCues(e,n.level),s.trigger(J.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n})},t=>{let i=t.message===`Missing initPTS for VTT MPEGTS`;i?a.push(e):this._fallbackToIMSC1(n,r),s.logger.log(`Failed to parse VTT cue: ${t}`),!(i&&o>n.cc)&&s.trigger(J.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:t})})}_fallbackToIMSC1(e,t){let n=this.tracks[e.level];n.textCodec||Nw(t,this.initPTS[e.cc],()=>{n.textCodec=kw,this._parseIMSC1(e,t)},()=>{n.textCodec=`wvtt`})}_appendCues(e,t){let n=this.hls;if(this.config.renderTextTracksNatively){let n=this.textTracks[t];if(!n||n.mode===`disabled`)return;e.forEach(e=>vC(n,e))}else{let r=this.tracks[t];if(!r)return;let i=r.default?`default`:`subtitles`+t;n.trigger(J.CUES_PARSED,{type:`subtitles`,cues:e,track:i})}}onFragDecrypted(e,t){let{frag:n}=t;n.type===Y.SUBTITLE&&this.onFragLoaded(J.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:n,samples:r}=t;if(!(n.type===Y.MAIN&&this.closedCaptionsForLevel(n)===`NONE`))for(let e=0;ebC(e[r],t,n))}if(this.config.renderTextTracksNatively&&t===0&&r!==void 0){let{textTracks:e}=this;Object.keys(e).forEach(n=>bC(e[n],t,r))}}}extractCea608Data(e){let t=[[],[]],n=e[0]&31,r=2;for(let i=0;i=16?c--:c++;let r=xw(l.trim()),p=Ew(t,n,r);e!=null&&(d=e.cues)!=null&&d.getCueById(p)||(o=new u(t,n,r),o.id=p,o.line=f+1,o.align=`left`,o.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(o))}return e&&i.length&&(i.sort((e,t)=>e.line===`auto`||t.line===`auto`?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),i.forEach(t=>vC(e,t))),i}};function Qw(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var $w=/(\d+)-(\d+)\/(\d+)/,eT=class{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||iT,this.controller=new self.AbortController,this.stats=new ah}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,n){let r=this.stats;if(r.loading.start)throw Error(`Loader can only be used once.`);r.loading.start=self.performance.now();let i=tT(e,this.controller.signal),a=e.responseType===`arraybuffer`,o=a?`byteLength`:`length`,{maxTimeToFirstByteMs:s,maxLoadTimeMs:c}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=n,this.request=this.fetchSetup(e,i),self.clearTimeout(this.requestTimeout),t.timeout=s&&G(s)?s:c,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},t.timeout),(yx(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(n=>{this.response=this.loader=n;let i=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},c-(i-r.loading.start)),!n.ok){let{status:e,statusText:t}=n;throw new aT(t||`fetch, bad network response`,e,n)}r.loading.first=i,r.total=rT(n.headers)||r.total;let o=this.callbacks?.onProgress;return o&&G(t.highWaterMark)?this.loadProgressively(n,r,e,t.highWaterMark,o):a?n.arrayBuffer():e.responseType===`json`?n.json():n.text()}).then(n=>{var i;let a=this.response;if(!a)throw Error(`loader destroyed`);self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);let s=n[o];s&&(r.loaded=r.total=s);let c={url:a.url,data:n,code:a.status},l=this.callbacks?.onProgress;l&&!G(t.highWaterMark)&&l(r,e,n,a),(i=this.callbacks)==null||i.onSuccess(c,r,e,a)}).catch(t=>{var n;if(self.clearTimeout(this.requestTimeout),r.aborted)return;let i=t&&t.code||0,a=t?t.message:null;(n=this.callbacks)==null||n.onError({code:i,text:a},e,t?t.details:null,r)})}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get(`age`);e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,n,r=0,i){let a=new hy,o=e.body.getReader(),s=()=>o.read().then(o=>{if(o.done)return a.dataLength&&i(t,n,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let c=o.value,l=c.length;return t.loaded+=l,l=r&&i(t,n,a.flush().buffer,e)):i(t,n,c.buffer,e),s()}).catch(()=>Promise.reject());return s()}};function tT(e,t){let n={method:`GET`,mode:`cors`,credentials:`same-origin`,signal:t,headers:new self.Headers(Pm({},e.headers))};return e.rangeEnd&&n.headers.set(`Range`,`bytes=`+e.rangeStart+`-`+String(e.rangeEnd-1)),n}function nT(e){let t=$w.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function rT(e){let t=e.get(`Content-Range`);if(t){let e=nT(t);if(G(e))return e}let n=e.get(`Content-Length`);if(n)return parseInt(n)}function iT(e,t){return new self.Request(e.url,t)}var aT=class extends Error{constructor(e,t,n){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=n}},oT=/^age:\s*[\d.]+\s*$/im,sT=class{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new ah,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,n){if(this.stats.loading.start)throw Error(`Loader can only be used once.`);this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=n,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let n=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!(this.loader!==n||this.stats.aborted))return i(n,t.url)}).catch(e=>{if(!(this.loader!==n||this.stats.aborted))return n.open(`GET`,t.url,!0),i(n,t.url)}).then(()=>{this.loader!==n||this.stats.aborted||this.openAndSendXhr(n,t,e)}).catch(e=>{var i;(i=this.callbacks)==null||i.onError({code:n.status,text:e.message},t,n,r)}):this.openAndSendXhr(n,t,e)}openAndSendXhr(e,t,n){e.readyState||e.open(`GET`,t.url,!0);let r=t.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:a}=n.loadPolicy;if(r)for(let t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader(`Range`,`bytes=`+t.rangeStart+`-`+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),n.timeout=i&&G(i)?i:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:n}=this;if(!e||!t)return;let r=t.readyState,i=this.config;if(!n.aborted&&r>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let r=t.status,s=t.responseType===`text`?t.responseText:null;if(r>=200&&r<300){let i=s??t.response;if(i!=null){var a;n.loading.end=Math.max(self.performance.now(),n.loading.first),n.loaded=n.total=t.responseType===`arraybuffer`?i.byteLength:i.length,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first);let o=this.callbacks?.onProgress;o&&o(n,e,i,t);let s={url:t.responseURL,data:i,code:r};(a=this.callbacks)==null||a.onSuccess(s,n,e,t);return}}let c=i.loadPolicy.errorRetry,l=n.retry;if(c_(c,l,!1,{url:e.url,data:void 0,code:r}))this.retry(c);else{var o;qm.error(`${r} while loading ${e.url}`),(o=this.callbacks)==null||o.onError({code:r,text:t.statusText},e,t,n)}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(c_(e,t,!0))this.retry(e);else{qm.warn(`timeout while loading ${this.context?.url}`);let e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:n}=this;this.retryDelay=o_(e,n.retry),n.retry++,qm.warn(`${status?`HTTP Status `+status:`Timeout`} while loading ${t?.url}, retrying ${n.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&oT.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader(`age`);e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&RegExp(`^${e}:\\s*[\\d.]+\\s*$`,`im`).test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}},cT=Im(Im({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:1/0,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:`edge`,liveSyncDurationCount:3,liveSyncOnStallIncrease:1,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,ignorePlaylistParsingErrors:!1,loader:sT,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Jg,bufferController:Fx,capLevelController:zx,errorController:p_,fpsController:gC,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:pv,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,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}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,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},lT()),{},{subtitleStreamController:GC,subtitleTrackController:wC,timelineController:Gw,audioStreamController:Tx,audioTrackController:Ax,emeController:dC,cmcdController:oC,contentSteeringController:cC,interstitialsController:UC});function lT(){return{cueHandler:Zw,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:`English`,captionsTextTrack1LanguageCode:`en`,captionsTextTrack2Label:`Spanish`,captionsTextTrack2LanguageCode:`es`,captionsTextTrack3Label:`Unknown CC`,captionsTextTrack3LanguageCode:``,captionsTextTrack4Label:`Unknown CC`,captionsTextTrack4LanguageCode:``,renderTextTracksNatively:!0}}function uT(e,t,n){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw Error(`Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration`);if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw Error(`Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"`);if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw Error(`Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"`);let r=dT(e),i=[`manifest`,`level`,`frag`],a=[`TimeOut`,`MaxRetry`,`RetryDelay`,`MaxRetryTimeout`];return i.forEach(e=>{let i=`${e===`level`?`playlist`:e}LoadPolicy`,o=t[i]===void 0,s=[];a.forEach(n=>{let a=`${e}Loading${n}`,c=t[a];if(c!==void 0&&o){s.push(a);let e=r[i].default;switch(t[i]={default:e},n){case`TimeOut`:e.maxLoadTimeMs=c,e.maxTimeToFirstByteMs=c;break;case`MaxRetry`:e.errorRetry.maxNumRetry=c,e.timeoutRetry.maxNumRetry=c;break;case`RetryDelay`:e.errorRetry.retryDelayMs=c,e.timeoutRetry.retryDelayMs=c;break;case`MaxRetryTimeout`:e.errorRetry.maxRetryDelayMs=c,e.timeoutRetry.maxRetryDelayMs=c;break}}}),s.length&&n.warn(`hls.js config: "${s.join(`", "`)}" setting(s) are deprecated, use "${i}": ${Pg(t[i])}`)}),Im(Im({},r),t)}function dT(e){return e&&typeof e==`object`?Array.isArray(e)?e.map(dT):Object.keys(e).reduce((t,n)=>(t[n]=dT(e[n]),t),{}):e}function fT(e,t){let n=e.loader;n!==eT&&n!==sT?(t.log(`[config]: Custom loader detected, cannot enable progressive streaming`),e.progressive=!1):Qw()&&(e.loader=eT,e.progressive=!0,e.enableSoftwareAES=!0,t.log(`[config]: Progressive streaming enabled, using FetchLoader`))}var pT=2,mT=.1,hT=.05,gT=100,_T=class extends P_{constructor(e,t){super(`gap-controller`,e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var e;(e=this.media)!=null&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{this.hls&&(this.ended=this.media?.currentTime||1,this.hls.trigger(J.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(J.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(J.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(gT),this.mediaSource=t.mediaSource;let n=this.media=t.media;uy(n,`playing`,this.onMediaPlaying),uy(n,`waiting`,this.onMediaWaiting),uy(n,`ended`,this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:n}=this;n&&(dy(n,`playing`,this.onMediaPlaying),dy(n,`waiting`,this.onMediaWaiting),dy(n,`ended`,this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;let t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){let n=this.hls?.config;if(!n)return;let r=this.media;if(!r)return;let{seeking:i}=r,a=this.seeking&&!i,o=!this.seeking&&i,s=r.paused&&!i||r.ended||r.playbackRate===0;if(this.seeking=i,e!==t){t&&(this.ended=0),this.moved=!0,i||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!s&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(o||a){a&&this.stallResolved(e);return}if(s){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&r.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(J.MEDIA_ENDED,{stalled:!1}));return}if(!Q.getBuffered(r).length){this.nudgeRetry=0;return}let c=Q.bufferInfo(r,e,0),l=c.nextStart||0,u=this.fragmentTracker;if(i&&u&&this.hls){let t=vT(this.hls.inFlightFragments,e),n=c.len>pT,r=!l||t||l-e>pT&&!u.getPartialFragment(e);if(n||r)return;this.moved=!1}let d=this.hls?.latestLevelDetails;if(!this.moved&&this.stalled!==null&&u){if(!(c.len>0)&&!l)return;let t=Math.max(l,c.start||0)-e,n=d!=null&&d.live?d.targetduration*2:pT,i=bT(e,u);if(t>0&&(t<=n||i)){r.paused||this._trySkipBufferHole(i);return}}let f=n.detectStallWithCurrentTimeMs,p=self.performance.now(),m=this.waiting,h=this.stalled;if(h===null)if(m>0&&p-m=f||m)&&this.hls){if(this.mediaSource?.readyState===`ended`&&!(d!=null&&d.live)&&Math.abs(e-(d?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(J.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return}let _=Q.bufferInfo(r,e,n.maxBufferHole);this._tryFixBufferStall(_,g,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let n=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(n)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(J.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var n;let r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(n=this.buffered.audio)!=null&&n.length&&r&&r.length>1&&e>r.end(0)){let n=Q.bufferedInfo(Q.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let n=Q.timeRangesToArray(r),i=Q.bufferedInfo(n,t,0).bufferedIndex;if(i>-1&&ii)&&a-r<1&&e-r<2){let n=Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${r} -> ${a} buffered index: ${t}`);this.warn(n.message),this.media.currentTime+=1e-6;let i=bT(e,this.fragmentTracker);i&&`fragment`in i?i=i.fragment:i||=void 0;let o=Q.bufferInfo(this.media,e,0);this.hls.trigger(J.ERROR,{type:K.MEDIA_ERROR,details:q.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:n,reason:n.message,frag:i,buffer:o.len,bufferInfo:o})}}}}}_tryFixBufferStall(e,t,n){let{fragmentTracker:r,media:i}=this,a=this.hls?.config;if(!i||!r||!a)return;let o=this.hls?.latestLevelDetails,s=bT(n,r);if((s||o!=null&&o.live&&n1&&e.len>a.maxBufferHole||e.nextStart&&(e.nextStart-na.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn(`Trying to nudge playhead over buffer-hole`),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let n=this.fragmentTracker,r=e.nextStart;if(n&&r){let e=n.getFragAtPos(t,Y.MAIN),i=n.getFragAtPos(r,Y.MAIN);if(e&&i)return i.sn-e.sn<2}return!1}_reportStall(e){let{hls:t,media:n,stallReported:r,stalled:i}=this;if(!r&&i!==null&&n&&t){this.stallReported=!0;let r=Error(`Playback stalling at @${n.currentTime} due to low buffer (${Pg(e)})`);this.warn(r.message),t.trigger(J.ERROR,{type:K.MEDIA_ERROR,details:q.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len,bufferInfo:e,stalled:{start:i}})}}_trySkipBufferHole(e){let{fragmentTracker:t,media:n}=this,r=this.hls?.config;if(!n||!t||!r)return 0;let i=n.currentTime,a=Q.bufferInfo(n,i,0),o=i0&&a.len<1&&n.readyState<3,u=o-i;if(u>0&&(c||l)){if(u>r.maxBufferHole){let n=!1;if(i===0){let e=t.getAppendedFrag(0,Y.MAIN);e&&o`u`))return self.VTTCue||self.TextTrackCue}function CT(e,t,n,r,i){let a=new e(t,n,``);try{a.value=r,i&&(a.type=i)}catch{a=new e(t,n,Pg(i?Im({type:i},r):r))}return a}var wT=(()=>{let e=ST();try{e&&new e(0,1/0,``)}catch{return Number.MAX_VALUE}return 1/0})(),TT=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(J.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){let{hls:e}=this;e&&(e.on(J.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(J.MANIFEST_LOADING,this.onManifestLoading,this),e.on(J.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(J.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(J.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(J.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(J.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(J.MANIFEST_LOADING,this.onManifestLoading,this),e.off(J.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(J.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(J.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(J.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){this.media=t.media,t.overrides?.cueRemoval===!1&&(this.removeCues=!1)}onMediaAttached(){let e=this.hls?.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&=(this.removeCues&&yC(this.id3Track,this.onEventCueEnter),null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){let t=this.getID3Track(e.textTracks);return t.mode=`hidden`,t}getID3Track(e){if(this.media){for(let t=0;twT&&(c=wT),c-s<=0&&(c=s+xT);for(let e=0;ee.type===sb.audioId3&&s:r===`video`?e=>e.type===sb.emsg&&o:e=>e.type===sb.audioId3&&s||e.type===sb.emsg&&o,bC(i,t,n,e)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;let{assetPlayerId:n,timelineOffset:r,enableDateRangeMetadataCues:i,interstitialsController:a}=this.hls.config;if(!i)return;let o=ST();if(n&&r&&!a){let{fragmentStart:t,fragmentEnd:r}=e,i=this.assetCue;i?(i.startTime=t,i.endTime=r):o&&(i=this.assetCue=CT(o,t,r,{assetPlayerId:this.hls.config.assetPlayerId},`hlsjs.interstitial.asset`),i&&(i.id=n,this.id3Track||=this.createTrack(this.media),this.id3Track.addCue(i),i.addEventListener(`enter`,this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;let{id3Track:s}=this,{dateRanges:c}=e,l=Object.keys(c),u=this.dateRangeCuesAppended;if(s&&t){var d;if((d=s.cues)!=null&&d.length){let e=Object.keys(u).filter(e=>!l.includes(e));for(let t=e.length;t--;){let n=e[t],r=u[n]?.cues;delete u[n],r&&Object.keys(r).forEach(e=>{let t=r[e];if(t){t.removeEventListener(`enter`,this.onEventCueEnter);try{s.removeCue(t)}catch{}}})}}else u=this.dateRangeCuesAppended={}}let f=e.fragments[e.fragments.length-1];if(!(l.length===0||!G(f?.programDateTime))){this.id3Track||=this.createTrack(this.media);for(let e=0;e{if(t!==n.id){let r=c[t];if(r.class===n.class&&r.startDate>n.startDate&&(!e||n.startDate.01&&(l.startTime=r,l.endTime=f);else if(o){let e=n.attr[c];J_(c)&&(e=$m(e));let i=CT(o,r,f,{key:c,data:e},sb.dateRange);i&&(i.id=t,this.id3Track.addCue(i),s[c]=i,a&&(c===`X-ASSET-LIST`||c===`X-ASSET-URL`)&&i.addEventListener(`enter`,this.onEventCueEnter))}}u[t]={cues:s,dateRange:n,durationKnown:d}}}}},ET=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{let{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;let n=this.computeLatency();if(n===null)return;this._latency=n;let{lowLatencyMode:r,maxLiveSyncPlaybackRate:i}=this.config;if(!r||i===1||!t.live)return;let a=this.targetLatency;if(a===null)return;let o=n-a;if(o.05&&this.forwardBufferLength>1){let t=Math.min(2,Math.max(1,i)),n=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20,r=Math.min(t,Math.max(1,n));this.changeMediaPlaybackRate(e,r)}else e.playbackRate!==1&&e.playbackRate!==0&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){return this.hls?.latestLevelDetails||null}get latency(){return this._latency||0}get maxLatency(){let{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;let t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||this.hls===null)return null;let{holdBack:t,partHoldBack:n,targetduration:r}=e,{liveSyncDuration:i,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,s=this.hls.userConfig,c=o&&n||t;(this._targetLatencyUpdated||s.liveSyncDuration||s.liveSyncDurationCount||c===0)&&(c=i===void 0?a*r:i);let l=r;return c+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,l)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;let n=this.levelDetails;if(n===null)return null;let r=n.edge,i=e-t-this.edgeStalled,a=r-n.totalduration,o=r-(this.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(a,i),o)}get drift(){let e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(e===null)return 0;let t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let n=e.buffered.length;return(n?e.buffered.end(n-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(J.MANIFEST_LOADING,this.onManifestLoading,this),e.on(J.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(J.ERROR,this.onError,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(J.MANIFEST_LOADING,this.onManifestLoading,this),e.off(J.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(J.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener(`timeupdate`,this.onTimeupdate)}onMediaDetaching(){this.media&&=(this.media.removeEventListener(`timeupdate`,this.onTimeupdate),null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener(`timeupdate`,this.onTimeupdate)}onError(e,t){var n;t.details===q.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(n=this.levelDetails)!=null&&n.live&&this.hls.logger.warn(`[latency-controller]: Stall detected, adjusting target latency`))}changeMediaPlaybackRate(e,t){var n;e.playbackRate!==t&&((n=this.hls)==null||n.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${this.targetLatency?.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){let e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},DT=class extends Ex{constructor(e,t){super(e,`level-controller`),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(J.MANIFEST_LOADING,this.onManifestLoading,this),e.on(J.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(J.LEVEL_LOADED,this.onLevelLoaded,this),e.on(J.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(J.FRAG_BUFFERED,this.onFragBuffered,this),e.on(J.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(J.MANIFEST_LOADING,this.onManifestLoading,this),e.off(J.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(J.LEVEL_LOADED,this.onLevelLoaded,this),e.off(J.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(J.FRAG_BUFFERED,this.onFragBuffered,this),e.off(J.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let n=this.hls.config.preferManagedMediaSource,r=[],i={},a={},o=!1,s=!1,c=!1;t.levels.forEach(e=>{let t=e.attrs,{audioCodec:l,videoCodec:u}=e;l&&(e.audioCodec=l=rg(l,n)||void 0),u&&=e.videoCodec=sg(u);let{width:d,height:f,unknownCodecs:p}=e,m=p?.length||0;if(o||=!!(d&&f),s||=!!u,c||=!!l,m||l&&!this.isAudioSupported(l)||u&&!this.isVideoSupported(u)){this.log(`Some or all CODECS not supported "${t.CODECS}"`);return}let{CODECS:h,"FRAME-RATE":g,"HDCP-LEVEL":_,"PATHWAY-ID":v,RESOLUTION:y,"VIDEO-RANGE":b}=t,x=`${`${v||`.`}-`}${e.bitrate}-${y}-${g}-${h}-${b}-${_}`;if(!i[x]){let t=this.createLevel(e);i[x]=t,a[x]=1,r.push(t)}else if(i[x].uri!==e.url&&!e.attrs[`PATHWAY-ID`]){let t=a[x]+=1;e.attrs[`PATHWAY-ID`]=Array(t+1).join(`.`);let n=this.createLevel(e);i[x]=n,r.push(n)}else i[x].addGroupId(`audio`,t.AUDIO),i[x].addGroupId(`text`,t.SUBTITLES)}),this.filterAndSortMediaOptions(r,t,o,s,c)}createLevel(e){let t=new kg(e),n=e.supplemental;if(n!=null&&n.videoCodec&&!this.isVideoSupported(n.videoCodec)){let e=Error(`SUPPLEMENTAL-CODECS not supported "${n.videoCodec}"`);this.log(e.message),t.supportedResult=mg(e,[])}return t}isAudioSupported(e){return Yh(e,`audio`,this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Yh(e,`video`,this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,n,r,i){let a=[],o=[],s=e,c=t.stats?.parsing||{};if((n||r)&&i&&(s=s.filter(({videoCodec:e,videoRange:t,width:n,height:r})=>(!!e||!!(n&&r))&&Tg(t))),s.length===0){Promise.resolve().then(()=>{if(this.hls){let e=`no level with compatible codecs found in manifest`,n=e;t.levels.length&&(n=`one or more CODECS in variant not supported: ${Pg(t.levels.map(e=>e.attrs.CODECS).filter((e,t,n)=>n.indexOf(e)===t))}`,this.warn(n),e+=` (${n})`);let r=Error(e);this.hls.trigger(J.ERROR,{type:K.MEDIA_ERROR,details:q.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:r,reason:n})}}),c.end=performance.now();return}t.audioTracks&&(a=t.audioTracks.filter(e=>!e.audioCodec||this.isAudioSupported(e.audioCodec)),OT(a)),t.subtitles&&(o=t.subtitles,OT(o));let l=s.slice(0);s.sort((e,t)=>{if(e.attrs[`HDCP-LEVEL`]!==t.attrs[`HDCP-LEVEL`])return(e.attrs[`HDCP-LEVEL`]||``)>(t.attrs[`HDCP-LEVEL`]||``)?1:-1;if(n&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return wg.indexOf(e.videoRange)-wg.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){let n=Qh(e.videoCodec),r=Qh(t.videoCodec);if(n!==r)return r-n}if(e.uri===t.uri&&e.codecSet!==t.codecSet){let n=$h(e.codecSet),r=$h(t.codecSet);if(n!==r)return r-n}return e.averageBitrate===t.averageBitrate?0:e.averageBitrate-t.averageBitrate});let u=l[0];if(this.steering&&(s=this.steering.filterParsedLevels(s),s.length!==l.length)){for(let e=0;en&&n===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}let d=i&&!r,f=this.hls.config,p=!!(f.audioStreamController&&f.audioTrackController),m={levels:s,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:i,video:r,altAudio:p&&!d&&a.some(e=>!!e.url)};c.end=performance.now(),this.hls.trigger(J.MANIFEST_PARSED,m)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let n=Error(`invalid level idx`),r=e<0;if(this.hls.trigger(J.ERROR,{type:K.OTHER_ERROR,details:q.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:n,reason:n.message}),r)return;e=Math.min(e,t.length-1)}let n=this.currentLevelIndex,r=this.currentLevel,i=r?r.attrs[`PATHWAY-ID`]:void 0,a=t[e],o=a.attrs[`PATHWAY-ID`];if(this.currentLevelIndex=e,this.currentLevel=a,n===e&&r&&i===o)return;this.log(`Switching to level ${e} (${a.height?a.height+`p `:``}${a.videoRange?a.videoRange+` `:``}${a.codecSet?a.codecSet+` `:``}@${a.bitrate})${o?` with Pathway `+o:``} from level ${n}${i?` with Pathway `+i:``}`);let s={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(J.LEVEL_SWITCHING,s);let c=a.details;if(!c||c.live){let e=this.switchParams(a.uri,r?.details,c);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;return e===void 0?this.hls.firstAutoLevel:e}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),n=e.filter(e=>t.indexOf(e)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=n}}onError(e,t){t.fatal||!t.context||t.context.type===Am.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===Y.MAIN){let e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;let n=this._levels[t.level];n!=null&&n.loadError&&(this.log(`Resetting level error count of ${n.loadError} on frag buffered`),n.loadError=0)}}onLevelLoaded(e,t){var n;let{level:r,details:i}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(i.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let e=a.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(r,t,e)}else (n=t.deliveryDirectives)!=null&&n.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let n=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,i=e.attrs[`PATHWAY-ID`],a=e.details,o=a?.age;this.log(`Loading level index ${r}${t?.msn===void 0?``:` at sn `+t.msn+` part `+t.part}${i?` Pathway `+i:``}${o&&a.live?` age `+o.toFixed(1)+(a.type&&` `+a.type||``):``} ${n}`),this.hls.trigger(J.LEVEL_LOADING,{url:n,level:r,levelInfo:e,pathwayId:e.attrs[`PATHWAY-ID`],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex===-1?this.hls.nextAutoLevel:this.manualLevelIndex}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;let n=this._levels.filter((t,n)=>n===e?(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1):!0);ey(n),this._levels=n,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let r=n.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&=Math.min(this._startLevel,r),this.hls.trigger(J.LEVELS_UPDATED,{levels:n})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:n}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(J.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}};function OT(e){let t={};e.forEach(e=>{let n=e.groupId||``;e.id=t[n]=t[n]||0,t[n]++})}function kT(){return self.SourceBuffer||self.WebKitSourceBuffer}function AT(){if(!Jm())return!1;let e=kT();return!e||e.prototype&&typeof e.prototype.appendBuffer==`function`&&typeof e.prototype.remove==`function`}function jT(){if(!AT())return!1;let e=Jm();return typeof e?.isTypeSupported==`function`&&([`avc1.42E01E,mp4a.40.2`,`av01.0.01M.08`,`vp09.00.50.08`].some(t=>e.isTypeSupported(Zh(t,`video`)))||[`mp4a.40.2`,`fLaC`].some(t=>e.isTypeSupported(Zh(t,`audio`))))}function MT(){var e;let t=kT();return typeof(t==null||(e=t.prototype)==null?void 0:e.changeType)==`function`}var NT=100,PT=class extends py{constructor(e,t,n){super(e,t,n,`stream-controller`,Y.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let e=this.media,t=e?e.currentTime:null;if(t===null||!G(t)||(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t)))return;let n=this.getFwdBufferInfoAtPos(e,t,Y.MAIN,0);if(n===null||n.len===0){this.warn(`Main forward buffer length at ${t} on "seeked" event ${n?n.len:`empty`})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(J.MANIFEST_PARSED,this.onManifestParsed,this),e.on(J.LEVEL_LOADING,this.onLevelLoading,this),e.on(J.LEVEL_LOADED,this.onLevelLoaded,this),e.on(J.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(J.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(J.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(J.BUFFER_CREATED,this.onBufferCreated,this),e.on(J.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(J.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(J.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(J.MANIFEST_PARSED,this.onManifestParsed,this),e.off(J.LEVEL_LOADED,this.onLevelLoaded,this),e.off(J.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(J.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(J.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(J.BUFFER_CREATED,this.onBufferCreated,this),e.off(J.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(J.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(J.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:n,hls:r}=this;if(this.stopLoad(),this.setInterval(NT),this.level=-1,!this.startFragRequested){let e=r.startLevel;e===-1&&(r.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=r.firstAutoLevel),r.nextLoadLevel=e,this.level=r.loadLevel,this._hasEnoughToStart=!!t}n>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),e=n),this.state=$.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=$.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case $.WAITING_LEVEL:{let{levels:e,level:t}=this,n=e?.[t],r=n?.details;if(r&&(!r.live||this.levelLastLoaded===n&&!this.waitForLive(n))){if(this.waitForCdnTuneIn(r))break;this.state=$.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=$.IDLE;break}break}case $.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===$.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:n,media:r}=this;if(t===null||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let i=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(n!=null&&n[i]))return;let a=n[i],o=this.getMainFwdBufferInfo();if(o===null)return;let s=this.getLevelDetails();if(s&&this._streamEnded(o,s)){let e={};this.altAudio===2&&(e.type=`video`),this.hls.trigger(J.BUFFER_EOS,e),this.state=$.ENDED;return}if(!this.buffering)return;e.loadLevel!==i&&e.manualLevel===-1&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;let c=a.details;if(!c||this.state===$.WAITING_LEVEL||this.waitForLive(a)){this.level=i,this.state=$.WAITING_LEVEL,this.startFragRequested=!1;return}let l=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(l>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);let d=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(d,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&ch(f)&&this.fragmentTracker.getState(f)!==h_.OK){let e=(this.backtrackFragment??f).sn-c.startSN,t=c.fragments[e-1];t&&f.cc===t.cc&&(f=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,d)){if(!f.gap){let e=this.audioOnly&&!this.altAudio?oh.AUDIO:oh.VIDEO,t=(e===oh.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,Y.MAIN)}f=this.getNextFragmentLoopLoading(f,c,o,Y.MAIN,u)}f&&(this.exceedsMaxBuffer(o,u,f)||(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,d)))}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);r===h_.NOT_LOADED||r===h_.PARTIAL?ch(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,n):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,Y.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,1/0),this.altAudio!==0&&(this.getLevelDetails()?.fragmentStart||0)>this.lastCurrentTime&&super.flushMainBuffer(0,1/0,`audio`)}nextLevelSwitch(){let{levels:e,media:t}=this;if(t!=null&&t.readyState){let n,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);let i=this.getLevelDetails();if(i!=null&&i.live){let e=this.getMainFwdBufferInfo();if(!e||e.len=a-t.maxFragLookUpTolerance&&i<=o;if(r!==null&&n.duration>r&&(i{this.hls&&this.hls.trigger(J.AUDIO_TRACK_SWITCHED,t)}),n.trigger(J.BUFFER_FLUSHING,{startOffset:0,endOffset:1/0,type:null});return}n.trigger(J.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let n=qg(t.url,this.hls);if(n){let e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log(`Switching on alternate audio, use video.buffered to schedule main fragment loading`),this.mediaBuffer=e)}this.altAudio=n?2:0,this.tick()}onBufferCreated(e,t){let n=t.tracks,r,i,a=!1;for(let e in n){let t=n[e];if(t.id===`main`){if(i=e,r=t,e===`video`){let t=n[e];t&&(this.videoBuffer=t.buffer)}}else a=!0}a&&r?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:n,part:r}=t,i=n.type===Y.MAIN;if(i){if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${r?` p: `+r.index:``} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),this.state===$.PARSED&&(this.state=$.IDLE);return}let e=r?r.stats:n.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),ch(n)&&(this.fragPrevious=n),this.fragBufferedComplete(n,r)}let a=this.media;a&&(!this._hasEnoughToStart&&Q.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){if(t.fatal){this.state=$.ERROR;return}switch(t.details){case q.FRAG_GAP:case q.FRAG_PARSING_ERROR:case q.FRAG_DECRYPT_ERROR:case q.FRAG_LOAD_ERROR:case q.FRAG_LOAD_TIMEOUT:case q.KEY_LOAD_ERROR:case q.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Y.MAIN,t);break;case q.LEVEL_LOAD_ERROR:case q.LEVEL_LOAD_TIMEOUT:case q.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===$.WAITING_LEVEL&&t.context?.type===Am.LEVEL&&(this.state=$.IDLE);break;case q.BUFFER_ADD_CODEC_ERROR:case q.BUFFER_APPEND_ERROR:if(t.parent!==`main`)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case q.BUFFER_FULL_ERROR:if(t.parent!==`main`)return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,1/0));break;case q.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=$.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==oh.AUDIO||!this.altAudio){let e=(t===oh.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,Y.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,n=this.startPosition;if(n>=0&&t0&&(s{let{hls:n}=this,r=e?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=$.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let i=r.stats;i.parsing.start=i.parsing.end=i.buffering.start=i.buffering.end=self.performance.now(),n.trigger(J.FRAG_LOADED,e),r.bitrateTest=!1}).catch(t=>{this.state===$.STOPPED||this.state===$.ERROR||(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:n}=this,{remuxResult:r,chunkMeta:i}=e,a=this.getCurrentContext(i);if(!a){this.resetWhenMissingContext(i);return}let{frag:o,part:s,level:c}=a,{video:l,text:u,id3:d,initSegment:f}=r,{details:p}=c,m=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=$.PARSING,f){let e=f.tracks;if(e){let r=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(c,e,r,i),n.trigger(J.FRAG_PARSING_INIT_SEGMENT,{frag:r,id:t,tracks:e})}let r=f.initPTS,a=f.timescale,s=this.initPTS[o.cc];if(G(r)&&(!s||s.baseTime!==r||s.timescale!==a)){let e=f.trackId;this.initPTS[o.cc]={baseTime:r,timescale:a,trackId:e},n.trigger(J.INIT_PTS_FOUND,{frag:o,id:t,initPTS:r,timescale:a,trackId:e})}}if(l&&p){m&&l.type===`audiovideo`&&this.logMuxedErr(o);let e=p.fragments[o.sn-1-p.startSN],t=o.sn===p.startSN,n=!e||o.cc>e.cc;if(r.independent!==!1){let{startPTS:e,endPTS:r,startDTS:a,endDTS:c}=l;if(s)s.elementaryStreams[l.type]={startPTS:e,endPTS:r,startDTS:a,endDTS:c};else if(l.firstKeyFrame&&l.independent&&i.id===1&&!n&&(this.couldBacktrack=!0),l.dropped&&l.independent){let i=this.getMainFwdBufferInfo(),a=(i?i.end:this.getLoadPosition())+this.config.maxBufferHole,s=l.firstKeyFramePTS?l.firstKeyFramePTS:e;if(!t&&apT&&(o.gap=!0);o.setElementaryStreamInfo(l.type,e,r,a,c),this.backtrackFragment&&=o,this.bufferFragmentData(l,o,s,i,t||n)}else if(t||n)o.gap=!0;else{this.backtrack(o);return}}if(m){let{startPTS:e,endPTS:t,startDTS:n,endDTS:r}=m;s&&(s.elementaryStreams[oh.AUDIO]={startPTS:e,endPTS:t,startDTS:n,endDTS:r}),o.setElementaryStreamInfo(oh.AUDIO,e,t,n,r),this.bufferFragmentData(m,o,s,i)}if(p&&d!=null&&d.samples.length){let e={id:t,frag:o,details:p,samples:d.samples};n.trigger(J.FRAG_PARSING_METADATA,e)}if(p&&u){let e={id:t,frag:o,details:p,samples:u.samples};n.trigger(J.FRAG_PARSING_USERDATA,e)}}logMuxedErr(e){this.warn(`${ch(e)?`Media`:`Init`} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,n,r){if(this.state!==$.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(n));let{audio:i,video:a,audiovideo:o}=t;if(i){let n=e.audioCodec,r=ag(i.codec,n);r===`mp4a`&&(r=`mp4a.40.5`);let a=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){r&&=r.indexOf(`mp4a.40.5`)===-1?`mp4a.40.5`:`mp4a.40.2`;let e=i.metadata;e&&`channelCount`in e&&(e.channelCount||1)!==1&&a.indexOf(`firefox`)===-1&&(r=`mp4a.40.5`)}r&&r.indexOf(`mp4a.40.5`)!==-1&&a.indexOf(`android`)!==-1&&i.container!==`audio/mpeg`&&(r=`mp4a.40.2`,this.log(`Android: force audio codec to ${r}`)),n&&n!==r&&this.log(`Swapping manifest audio codec "${n}" for "${r}"`),i.levelCodec=r,i.id=Y.MAIN,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${r||``}/${n||``}/${i.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=Y.MAIN;let n=a.codec;if(n?.length===4)switch(n){case`hvc1`:case`hev1`:a.codec=`hvc1.1.6.L120.90`;break;case`av01`:a.codec=`av01.0.04M.08`;break;case`avc1`:a.codec=`avc1.42e01e`;break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||``}/${n}]${a.codec===n?``:` parsed-corrected=`+a.codec}${a.supplemental?` supplemental=`+a.supplemental:``}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);let s=Object.keys(t);if(s.length){if(this.hls.trigger(J.BUFFER_CODECS,t),!this.hls)return;s.forEach(e=>{let i=t[e].initSegment;i!=null&&i.byteLength&&this.hls.trigger(J.BUFFER_APPENDING,{type:e,data:i,frag:n,part:null,chunkMeta:r,parent:n.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,Y.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,n=e?.[t];return n?this.getMaxBufferLength(n.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=$.IDLE}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let n=e.currentTime;if(Q.isBuffered(e,n)?t=this.getAppendedFrag(n):Q.isBuffered(e,n+.1)&&(t=this.getAppendedFrag(n+.1)),t){this.backtrackFragment=null;let e=this.fragPlaying,n=t.level;(!e||t.sn!==e.sn||e.level!==n)&&(this.fragPlaying=t,this.hls.trigger(J.FRAG_CHANGED,{frag:t}),(!e||e.level!==n)&&this.hls.trigger(J.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){if(this.fragPlaying)return this.fragPlaying;let e=this.media?.currentTime||this.lastCurrentTime;return G(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){let e=this.media?.currentTime||this.lastCurrentTime;if(G(e)){let t=this.getLevelDetails(),n=this.currentFrag||(t?Zg(null,t.fragments,e):null);if(n){let t=n.programDateTime;if(t!==null){let r=t+(e-n.start)*1e3;return new Date(r)}}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},FT=class extends zm{constructor(e,t){super(`key-loader`,t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let t in this.keyIdToKeyInfo){let n=this.keyIdToKeyInfo[t].loader;if(n){if(e&&e!==n.context?.frag.type)return;n.abort()}}}detach(){for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=q.KEY_LOAD_ERROR,n,r,i){return new N_({type:K.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:i,error:n,networkDetails:r})}loadClear(e,t,n){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,i=t.length;r{if(!this.emeController)return;a.setKeyFormat(e);let t=uv(e);if(t)return this.emeController.getKeySystemAccess([t])})}if(this.config.requireKeySystemAccessOnStart){let e=fv(this.config);if(e.length)return this.emeController.getKeySystemAccess(e)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var n,r;t&&e.setKeyFormat(t);let i=e.decryptdata;if(!i){let n=Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,q.KEY_LOAD_ERROR,n))}let a=i.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,q.KEY_LOAD_ERROR,Error(`Invalid key URI: "${a}"`)));let o=IT(i),s=this.keyIdToKeyInfo[o];if((n=s)!=null&&n.decryptdata.key)return i.key=s.decryptdata.key,Promise.resolve({frag:e,keyInfo:s});if(this.emeController&&(r=s)!=null&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(s.decryptdata)){case`usable`:case`usable-in-future`:return s.keyLoadPromise.then(t=>{let{keyInfo:n}=t;return i.key=n.decryptdata.key,{frag:e,keyInfo:n}})}switch(this.log(`${this.keyIdToKeyInfo[o]?`Rel`:`L`}oading${i.keyId?` keyId: `+Qm(i.keyId):``} URI: ${i.uri} from ${e.type} ${e.level}`),s=this.keyIdToKeyInfo[o]={decryptdata:i,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},i.method){case`SAMPLE-AES`:case`SAMPLE-AES-CENC`:case`SAMPLE-AES-CTR`:return i.keyFormat===`identity`?this.loadKeyHTTP(s,e):this.loadKeyEME(s,e);case`AES-128`:case`AES-256`:case`AES-256-CTR`:return this.loadKeyHTTP(s,e);default:return Promise.reject(this.createKeyLoadError(e,q.KEY_LOAD_ERROR,Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(e,t){let n={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r;if(!e.decryptdata.keyId&&(r=t.initSegment)!=null&&r.data){let n=Ah(t.initSegment.data);if(n.length){let t=n[0];t.some(e=>e!==0)?(this.log(`Using keyId found in init segment ${Qm(t)}`),yv.setKeyIdForUri(e.decryptdata.uri,t)):(t=yv.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Qm(t)}`)),e.decryptdata.keyId=t}}return!e.decryptdata.keyId&&!ch(t)?Promise.resolve(n):(e.keyLoadPromise=this.emeController.loadKey(n).then(t=>(e.mediaKeySessionContext=t,n))).catch(n=>{throw e.keyLoadPromise=null,`data`in n&&(n.data.frag=t),n})}return Promise.resolve(n)}loadKeyHTTP(e,t){let n=this.config,r=n.loader,i=new r(n);return t.keyLoader=e.loader=i,e.keyLoadPromise=new Promise((r,a)=>{let o={keyInfo:e,frag:t,responseType:`arraybuffer`,url:e.decryptdata.uri},s=n.keyLoadPolicy.default,c={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};i.load(o,c,{onSuccess:(e,t,n,i)=>{let{frag:o,keyInfo:s}=n,c=IT(s.decryptdata);if(!o.decryptdata||s!==this.keyIdToKeyInfo[c])return a(this.createKeyLoadError(o,q.KEY_LOAD_ERROR,Error(`after key load, decryptdata unset or changed`),i));s.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=null,s.loader=null,r({frag:o,keyInfo:s})},onError:(e,n,r,i)=>{this.resetLoader(n),a(this.createKeyLoadError(t,q.KEY_LOAD_ERROR,Error(`HTTP Error ${e.code} loading key ${e.text}`),r,Im({url:o.url,data:void 0},e)))},onTimeout:(e,n,r)=>{this.resetLoader(n),a(this.createKeyLoadError(t,q.KEY_LOAD_TIMEOUT,Error(`key loading timed out`),r))},onAbort:(e,n,r)=>{this.resetLoader(n),a(this.createKeyLoadError(t,q.INTERNAL_ABORTED,Error(`key loading aborted`),r))}})})}resetLoader(e){let{frag:t,keyInfo:n,url:r}=e,i=n.loader;t.keyLoader===i&&(t.keyLoader=null,n.loader=null);let a=IT(n.decryptdata)||r;delete this.keyIdToKeyInfo[a],i&&i.destroy()}};function IT(e){if(e.keyFormat!==lv.FAIRPLAY){let t=e.keyId;if(t)return Qm(t)}return e.uri}function LT(e){let{type:t}=e;switch(t){case Am.AUDIO_TRACK:return Y.AUDIO;case Am.SUBTITLE_TRACK:return Y.SUBTITLE;default:return Y.MAIN}}function RT(e,t){let n=e.url;return(n===void 0||n.indexOf(`data:`)===0)&&(n=t.url),n}var zT=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(J.MANIFEST_LOADING,this.onManifestLoading,this),e.on(J.LEVEL_LOADING,this.onLevelLoading,this),e.on(J.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(J.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(J.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(J.MANIFEST_LOADING,this.onManifestLoading,this),e.off(J.LEVEL_LOADING,this.onLevelLoading,this),e.off(J.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(J.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(J.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,n=t.pLoader,r=t.loader,i=new(n||r)(t);return this.loaders[e.type]=i,i}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:n}=t;this.variableList=null,this.load({id:null,level:0,responseType:`text`,type:Am.MANIFEST,url:n,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:n,level:r,pathwayId:i,url:a,deliveryDirectives:o,levelInfo:s}=t;this.load({id:n,level:r,pathwayId:i,responseType:`text`,type:Am.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:s})}onAudioTrackLoading(e,t){let{id:n,groupId:r,url:i,deliveryDirectives:a,track:o}=t;this.load({id:n,groupId:r,level:null,responseType:`text`,type:Am.AUDIO_TRACK,url:i,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:n,groupId:r,url:i,deliveryDirectives:a,track:o}=t;this.load({id:n,groupId:r,level:null,responseType:`text`,type:Am.SUBTITLE_TRACK,url:i,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let n=this.loaders[Am.LEVEL];if(n){let e=n.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(n.abort(),delete this.loaders[Am.LEVEL])}}load(e){let t=this.hls.config,n=this.getInternalLoader(e);if(n){let t=this.hls.logger,r=n.context;if(r&&r.levelOrTrack===e.levelOrTrack&&(r.url===e.url||r.deliveryDirectives&&!e.deliveryDirectives)){r.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${r.url}`);return}t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let r;if(r=e.type===Am.MANIFEST?t.manifestLoadPolicy.default:Pm({},t.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),G(e.deliveryDirectives?.part)){let t;if(e.type===Am.LEVEL&&e.level!==null?t=this.hls.levels[e.level].details:e.type===Am.AUDIO_TRACK&&e.id!==null?t=this.hls.audioTracks[e.id].details:e.type===Am.SUBTITLE_TRACK&&e.id!==null&&(t=this.hls.subtitleTracks[e.id].details),t){let e=t.partTarget,n=t.targetduration;if(e&&n){let t=Math.max(e*3,n*.8)*1e3;r=Pm({},r,{maxTimeToFirstByteMs:Math.min(t,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,r.maxTimeToFirstByteMs)})}}}let i=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:i.maxNumRetry||0,retryDelay:i.retryDelayMs||0,maxRetryDelay:i.maxRetryDelayMs||0};n.load(e,a,{onSuccess:(e,t,n,r)=>{let i=this.getInternalLoader(n);this.resetInternalLoader(n.type);let a=e.data;t.parsing.start=performance.now(),Ov.isMediaPlaylist(a)||n.type!==Am.MANIFEST?this.handleTrackOrLevelPlaylist(e,t,n,r||null,i):this.handleMasterPlaylist(e,t,n,r)},onError:(e,t,n,r)=>{this.handleNetworkError(t,n,!1,e,r)},onTimeout:(e,t,n)=>{this.handleNetworkError(t,n,!0,void 0,e)}})}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:n}=this.hls;(e||n)&&(this.hls.logger.log(`${e?`auto`:`force`} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,n,r){let i=this.hls,a=e.data,o=RT(e,n),s=Ov.parseMasterPlaylist(a,o);if(s.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,n,s.playlistParsingError,r,t);return}let{contentSteering:c,levels:l,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:p}=s;this.variableList=p,l.forEach(e=>{let{unknownCodecs:t}=e;if(t){let{preferManagedMediaSource:n}=this.hls.config,{audioCodec:r,videoCodec:i}=e;for(let a=t.length;a--;){let o=t[a];Yh(o,`audio`,n)?(e.audioCodec=r=r?`${r},${o}`:o,qh.audio[r.substring(0,4)]=2,t.splice(a,1)):Yh(o,`video`,n)&&(e.videoCodec=i=i?`${i},${o}`:o,qh.video[i.substring(0,4)]=2,t.splice(a,1))}}});let{AUDIO:m=[],SUBTITLES:h,"CLOSED-CAPTIONS":g}=Ov.parseMasterPlaylistMedia(a,o,s);m.length&&!m.some(e=>!e.url)&&l[0].audioCodec&&!l[0].attrs.AUDIO&&(this.hls.logger.log(`[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one`),m.unshift({type:`main`,name:`main`,groupId:`main`,default:!1,autoselect:!1,forced:!1,id:-1,attrs:new G_({}),bitrate:0,url:``})),i.trigger(J.MANIFEST_LOADED,{levels:l,audioTracks:m,subtitles:h,captions:g,contentSteering:c,url:o,stats:t,networkDetails:r,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:p})}handleTrackOrLevelPlaylist(e,t,n,r,i){let a=this.hls,{id:o,level:s,type:c}=n,l=RT(e,n),u=G(s)?s:G(o)?o:0,d=LT(n),f=Ov.parseLevelPlaylist(e.data,l,u,d,0,this.variableList);if(c===Am.MANIFEST){let e={attrs:new G_({}),bitrate:0,details:f,name:``,url:l};f.requestScheduled=t.loading.start+Xv(f,0),a.trigger(J.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:l,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),n.levelDetails=f,this.handlePlaylistLoaded(f,e,t,n,r,i)}handleManifestParsingError(e,t,n,r,i){this.hls.trigger(J.ERROR,{type:K.NETWORK_ERROR,details:q.MANIFEST_PARSING_ERROR,fatal:t.type===Am.MANIFEST,url:e.url,err:n,error:n,reason:n.message,response:e,context:t,networkDetails:r,stats:i})}handleNetworkError(e,t,n=!1,r,i){let a=`A network ${n?`timeout`:`error`+(r?` (status `+r.code+`)`:``)} occurred while loading ${e.type}`;e.type===Am.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===Am.AUDIO_TRACK||e.type===Am.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let s=q.UNKNOWN,c=!1,l=this.getInternalLoader(e);switch(e.type){case Am.MANIFEST:s=n?q.MANIFEST_LOAD_TIMEOUT:q.MANIFEST_LOAD_ERROR,c=!0;break;case Am.LEVEL:s=n?q.LEVEL_LOAD_TIMEOUT:q.LEVEL_LOAD_ERROR,c=!1;break;case Am.AUDIO_TRACK:s=n?q.AUDIO_TRACK_LOAD_TIMEOUT:q.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case Am.SUBTITLE_TRACK:s=n?q.SUBTITLE_TRACK_LOAD_TIMEOUT:q.SUBTITLE_LOAD_ERROR,c=!1;break}l&&this.resetInternalLoader(e.type);let u={type:K.NETWORK_ERROR,details:s,fatal:c,url:e.url,loader:l,context:e,error:o,networkDetails:t,stats:i};r&&(u.response=Im({url:t?.url||e.url,data:void 0},r)),this.hls.trigger(J.ERROR,u)}handlePlaylistLoaded(e,t,n,r,i,a){let o=this.hls,{type:s,level:c,levelOrTrack:l,id:u,groupId:d,deliveryDirectives:f}=r,p=RT(t,r),m=LT(r),h=typeof r.level==`number`&&m===Y.MAIN?c:void 0,g=e.playlistParsingError;if(g){if(this.hls.logger.warn(`${g} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(J.ERROR,{type:K.NETWORK_ERROR,details:q.LEVEL_PARSING_ERROR,fatal:!1,url:p,error:g,reason:g.message,response:t,context:r,level:h,parent:m,networkDetails:i,stats:n});return}e.playlistParsingError=null}if(!e.fragments.length){let a=e.playlistParsingError=Error(`No Segments found in Playlist`);o.trigger(J.ERROR,{type:K.NETWORK_ERROR,details:q.LEVEL_EMPTY_ERROR,fatal:!1,url:p,error:a,reason:a.message,response:t,context:r,level:h,parent:m,networkDetails:i,stats:n});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),s){case Am.MANIFEST:case Am.LEVEL:if(h){if(!l)h=0;else if(l!==o.levels[h]){let e=o.levels.indexOf(l);e>-1&&(h=e)}}o.trigger(J.LEVEL_LOADED,{details:e,levelInfo:l||o.levels[0],level:h||0,id:u||0,stats:n,networkDetails:i,deliveryDirectives:f,withoutMultiVariant:s===Am.MANIFEST});break;case Am.AUDIO_TRACK:o.trigger(J.AUDIO_TRACK_LOADED,{details:e,track:l,id:u||0,groupId:d||``,stats:n,networkDetails:i,deliveryDirectives:f});break;case Am.SUBTITLE_TRACK:o.trigger(J.SUBTITLE_TRACK_LOADED,{details:e,track:l,id:u||0,groupId:d||``,stats:n,networkDetails:i,deliveryDirectives:f});break}}},BT=class e{static get version(){return xy}static isMSESupported(){return AT()}static isSupported(){return jT()}static getMediaSource(){return Jm()}static get Events(){return J}static get MetadataSchema(){return sb}static get ErrorTypes(){return K}static get ErrorDetails(){return q}static get DefaultConfig(){return e.defaultConfig?e.defaultConfig:cT}static set DefaultConfig(t){e.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new by,this._autoLevelCapping=-1,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.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;let n=this.logger=Km(t.debug||!1,`Hls instance`,t.assetPlayerId),r=this.config=uT(e.DefaultConfig,t,n);this.userConfig=t,r.progressive&&fT(r,n);let{abrController:i,bufferController:a,capLevelController:o,errorController:s,fpsController:c}=r,l=new s(this),u=this.abrController=new i(this),d=new g_(this),f=r.interstitialsController,p=f?this.interstitialsController=new f(this,e):null,m=this.bufferController=new a(this,d),h=this.capLevelController=new o(this),g=new c(this),_=new zT(this),v=r.contentSteeringController,y=v?new v(this):null,b=this.levelController=new DT(this,y),x=new TT(this),S=new FT(this.config,this.logger),C=this.streamController=new PT(this,d,S),w=this.gapController=new _T(this,d);h.setStreamController(C),g.setStreamController(C);let T=[_,b,C];p&&T.splice(1,0,p),y&&T.splice(1,0,y),this.networkControllers=T;let E=[u,m,w,h,g,x,d];this.audioTrackController=this.createController(r.audioTrackController,T);let D=r.audioStreamController;D&&T.push(this.audioStreamController=new D(this,d,S)),this.subtitleTrackController=this.createController(r.subtitleTrackController,T);let O=r.subtitleStreamController;O&&T.push(this.subtititleStreamController=new O(this,d,S)),this.createController(r.timelineController,E),S.emeController=this.emeController=this.createController(r.emeController,E),this.cmcdController=this.createController(r.cmcdController,E),this.latencyController=this.createController(ET,E),this.coreComponents=E,T.push(l);let k=l.onErrorOut;typeof k==`function`&&this.on(J.ERROR,k,l),this.on(J.MANIFEST_LOADED,_.onManifestLoaded,_)}createController(e,t){if(e){let n=new e(this);return t&&t.push(n),n}return null}on(e,t,n=this){this._emitter.on(e,t,n)}once(e,t,n=this){this._emitter.once(e,t,n)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,n=this,r){this._emitter.off(e,t,n,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,n){return this._emitter.emit(e,t,n)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error(`An internal error happened while handling event `+e+`. Error message: "`+t.message+`". Here is a stacktrace:`,t),!this.triggeringException){this.triggeringException=!0;let n=e===J.ERROR;this.trigger(J.ERROR,{type:K.OTHER_ERROR,details:q.INTERNAL_EXCEPTION,fatal:n,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log(`destroy`),this.trigger(J.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||`media`in e&&!e.media){let t=Error(`attachMedia failed: invalid argument (${e})`);this.trigger(J.ERROR,{type:K.OTHER_ERROR,details:q.ATTACH_MEDIA_ERROR,fatal:!0,error:t});return}this.logger.log(`attachMedia`),this._media&&(this.logger.warn(`media must be detached before attaching`),this.detachMedia());let t=`media`in e,n=t?e.media:e,r=t?e:{media:n};this._media=n,this.trigger(J.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log(`detachMedia`),this.trigger(J.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;let e=this.bufferController.transferMedia();return this.trigger(J.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();let t=this.media,n=this._url,r=this._url=ih.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),t&&n&&(n!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(J.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?`, `:``)})`),this.started=!0,this.resumeBuffering();for(let n=0;n{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log(`pause buffering`),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){let e={[Y.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[Y.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[Y.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log(`swapAudioCodec`),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log(`recoverMediaError`);let e=this._media,t=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||=this._sessionId=TC(),e}get levels(){return this.levelController.levels||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Cg(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let n=e.length;for(let r=0;r=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:n}=this,r;if(r=t===-1&&e!=null&&e.length?e.length-1:t,n)for(let t=r;t--;){let r=e[t].attrs[`HDCP-LEVEL`];if(r&&r<=n)return t}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){return this.audioTrackController?.setAudioOption(e)||null}setSubtitleOption(e){return this.subtitleTrackController?.setSubtitleOption(e)||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?.interstitialsManager||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return gg(e,Lg(t),navigator.mediaCapabilities)}};BT.defaultConfig=void 0;var VT=iE;(function(e,t){let n=iE,r=e();for(;;)try{if(parseInt(n(306))/1+-parseInt(n(442))/2+parseInt(n(297))/3+-parseInt(n(417))/4+parseInt(n(279))/5+parseInt(n(413))/6+parseInt(n(629))/7*(parseInt(n(522))/8)===t)break;r.push(r.shift())}catch{r.push(r.shift())}})(vE,761792);var HT=function(){let e=!0;return function(t,n){let r=e?function(){let e=iE;if(n){let r=n[e(509)](t,arguments);return n=null,r}}:function(){};return e=!1,r}}();(function(){let e=iE,t={ATDHa:function(e,t){return e(t)},viLkC:function(e,t){return e+t},Vkmfb:`chain`,WEWXn:`yEsRQ`,VjxxS:function(e,t){return e(t)},dXLZE:function(e,t,n){return e(t,n)}};t[e(585)](HT,this,function(){let n=e,r=RegExp(`function *\\( *\\)`),i=RegExp(`\\+\\+ *(?:[a-zA-Z_$][0-9a-zA-Z_$]*)`,`i`),a=t[n(556)](bE,n(676));!r.test(t[n(678)](a,t[n(482)]))||!i[n(694)](a+n(258))?t[n(654)]===t[n(654)]?t.VjxxS(a,`0`):(_0x3a14a3(_0x3cd690.ts||`购买成功`),_0xe3e5bb()):bE()})()})();var UT={};UT[VT(365)]=VT(480);var WT=UT,GT={};GT[VT(365)]=VT(441);var KT=GT,qT={};qT[VT(612)]=0,qT[VT(365)]=VT(400);var JT=qT,YT={};YT.class=VT(683);var XT=YT,ZT={};ZT[VT(365)]=VT(316);var QT=ZT,$T={};$T[VT(612)]=0,$T[VT(365)]=VT(256);var eE=$T,tE={};tE[VT(612)]=0,tE[VT(365)]=`region-tag`;var nE=tE,rE={};function iE(e,t){e-=240;let n=vE(),r=n[e];iE.VyyebQ===void 0&&(iE.KQBqxV=function(e){let t=``,n=``;for(let n=0,r,i,a=0;i=e.charAt(a++);~i&&(r=n%4?r*64+i:i,n++%4)&&(t+=String.fromCharCode(255&r>>(-2*n&6))))i=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=`.indexOf(i);for(let e=0,r=t.length;e`,xKluE:function(e,t){return e(t)},vurwG:function(e,t){return e(t)},KgnHZ:D(688),JnYen:function(e,t){return e!==t},qiKxs:D(453),TpwfB:D(610),ryLuW:D(292),eGpkB:D(395),WYpUo:function(e,t){return e*t},HhiDR:function(e,t){return e*t},fICrE:function(e,t){return e*t},cjCMp:function(e,t){return e-t},CzCDr:function(e,t){return e/t},mDxTH:D(466),LthKw:function(e,t){return e(t)},xObch:`rKddb`,YHBJa:function(e,t,n){return e(t,n)},DRgFx:function(e){return e()},yPOjM:function(e,t){return e+t},aRXmG:`fVBYe`,Eubfs:function(e,t){return e===t},shIks:function(e,t){return e===t},mQfDq:`yWneP`,ntrxZ:`❌ 缩略图数据为空`,wYvjj:D(523),vuPdU:D(275),mtbyr:D(619),UvKsb:D(403),gVeYV:function(e,t){return e!==t},THbEF:`rgmws`,JREtw:D(298),HRRzY:D(561),Gdjdz:D(549),bMZim:function(e,t){return e===t},XQCvs:`INPUT`,kdeOh:function(e,t){return e===t},MxtAf:D(665),mhGzi:D(407),zIwsr:function(e,t){return e(t)},sQYKW:D(476),cEfMV:D(505),TLMua:function(e,t){return e>t},LtqHl:function(e,t){return e+t},qSonf:D(622),RlgJW:function(e,t){return e>t},VPpWw:D(555),NRFmO:`(致命)`,iwggO:function(e,t){return e>t},ToJAT:`iKvRR`,UGpIE:D(633),rkLzh:D(253),VMDzZ:function(e,t){return e===t},tDlru:D(632),mgmCC:function(e,t,n){return e(t,n)},NtGHD:`progress`,pWEYq:D(307),auGCv:D(488),tjelI:function(e,t){return e||t},LpWeJ:function(e,t){return e===t},LOvsh:`yVcqO`,OhSaW:`video/mp4`,XeowU:D(421),jWBIw:`视频信息错误`,ZAjYo:function(e,t,n){return e(t,n)},EhHqJ:function(e,t){return e(t)},wErKD:D(428),whFFP:`video-tag`,qAxmN:function(e,t,n,r){return e(t,n,r)},IUdzk:function(e,t){return e(t)},LyDTn:function(e,t,n,r,i){return e(t,n,r,i)},ZqoYY:function(e,t){return e(t)},eRLDi:D(332),vygHr:function(e,t){return e(t)},SBFyX:function(e){return e()},ZTWET:function(e,t,n){return e(t,n)},vgOeJ:function(e,t,n,r,i){return e(t,n,r,i)},yPtxv:D(318),VHMjx:D(367),STGhe:function(e,t){return e===t},EQEng:function(e){return e()},ortcA:`warning`,JKEGr:`small`,oMvIH:function(e,t,n,r,i){return e(t,n,r,i)},SSgII:function(e,t){return e+t},zSouQ:function(e,t){return e(t)},sgGqO:function(e,t,n,r,i){return e(t,n,r,i)},sLgJj:function(e,t,n,r){return e(t,n,r)},aKnVr:function(e,t,n,r,i){return e(t,n,r,i)},NXdIz:function(e,t){return e(t)},Fkxpm:function(e,t,n,r){return e(t,n,r)},YzUqF:function(e,t){return e(t)},JfyUY:function(e){return e()},REMOH:D(432),WrFHa:function(e,t,n){return e(t,n)},PpbOJ:D(591),NnWxr:function(e,t){return e(t)},OsRBv:D(464),VoNep:function(e,t){return e(t)},IifDu:`show`,hPsyH:function(e,t){return e(t)},IrdIO:function(e,t){return e(t)}},k=O[D(684)](v),A=O[D(521)](b),j=O[D(377)](x,null),M=null,N=null,ee=``,P=null,te=-1,ne=0,re=()=>{ee&&=(URL[D(415)](ee),``)},ie=x({}),F={};F[D(345)]=0,F[D(604)]=0,F[D(484)]=0;let ae=x(F),oe=x([]),se=x(!1),ce=x(!1),le=x(``),ue=()=>{let e=D,t=A[e(319)].id;t&&(ie.value={id:O.xjbNb(Number,t)}),!ie.value.id&&console[e(421)](O.PvJjk)},de=()=>{let e=D;if(k[e(272)].history[e(663)]?.[e(645)])if(O[e(280)](`iSIIq`,O[e(658)])){let t={..._0x2a12e1[e(414)]};t[e(278)]=_0x528966.info.title||``,t[e(637)]=_0x9c2d14[e(554)][e(637)]||[],t.tag_names=_0x23665e[e(554)][e(467)]||[],t[e(577)]=_0x31e9d9[e(554)][e(477)]||``,t[e(615)]=_0x93996c[e(554)].width||``,t[e(479)]=_0x5ce35f[e(554)].height||``,t.play_count=_0x54b137.info.play_count||`0`,t.fav_count=_0x420280[e(554)][e(520)]||`0`,t.region=_0x4b5582[e(554)][e(673)]||0,t[e(696)]=_0x1a1c7f.info.region_name||``,_0x270fc8[e(414)]=t}else k[e(645)]();else k[e(565)](`/`)},fe=async()=>{let e=D;if(O[e(280)](`ecSXW`,e(397)))try{let t={};t[e(608)]=ie.value.id,t[e(528)]=0;let n=await g[e(540)](t);ae[e(414)]=n,oe.value=n[e(576)]||[]}catch(t){if(O[e(393)]===O[e(393)])console[e(421)](e(553),t);else{_0x4c728b[e(660)]=_0x47e04d[e(572)],_0x49da9a[e(623)]=_0x2e39b0[e(572)],_0x21cb95.loading.first=_0x20f7b5[e(391)][e(580)]=_0x3dbbce[e(532)]();let t={};t[e(350)]=_0x7d8a1f,t[e(576)]=_0x4465ac,_0x3903d0[e(642)](t,_0x529ca3,_0x49e903,null)}}else _0x34b910(()=>{let t=e;_0x26cc6b[t(493)][t(375)]=`none`},500)},I=async()=>{let t=D;if(!le[t(414)][t(385)]()){e(t(240));return}try{let n={};n[t(608)]=ie[t(414)].id,n[t(528)]=0,n[t(433)]=le[t(414)];let r=await g[t(331)](n);r[t(457)]&&e(r.tis);let i={};i[t(433)]=le[t(414)],i.shij=`刚刚`,oe[t(414)][t(617)](i),le[t(414)]=``,ce[t(414)]=!1}catch{O[t(341)](e,O[t(303)])}},L=async()=>{let t=D,n={};n[t(513)]=function(e,t){return e&t};let r=n;if(O[t(285)]===t(475)){_0x5c437f=new _0x235622(_0x79b029[t(612)][t(422)]);for(let e=0;e<_0x1dcd5d.key[t(422)];e++)_0x5f2037[e]=r[t(513)](_0x2ec220[t(612)].charCodeAt(e),255)}else{let n=ie[t(414)].id;try{let r={};r[t(608)]=n,r.caoz=+!!se[t(414)];let i=await g[t(270)](r);if(O[t(376)](i.tis,`ok`)){if(se[t(414)]=!se[t(414)],se.value)if(O[t(376)](t(685),t(618))){let e=_0x4d6d1b[t(545)][0];O[t(671)](_0x185e9d,e[t(507)],_0x5349bc[t(374)]())}else u(n);else d(n);O[t(341)](e,se[t(414)]?t(371):t(675))}}catch{if(O[t(364)]===O.PoCuJ)return _0x18e897[t(421)](t(610),_0x1e869e),_0x5df831;O[t(341)](e,O[t(621)])}}},R=async()=>{let t=D;try{let n={};n[t(519)]=`提示`,n[t(492)]=t(295)+ae[t(414)][t(484)]+t(347),await m(n);let r={};r[t(388)]=2,r[t(273)]=``,r[t(608)]=ie[t(414)].id;let i=await g.dindgm(r);i.zt===0?(e(i.ts||t(508)),fe()):O[t(515)](i.zt,2)&&e(O.vrITE)}catch{}},pe=()=>{e(D(264))},me=[],he=null,ge=[],_e=new Map,ve=async e=>{let t=D;try{let n=(await w(e))[t(378)](` `),r=[],i=0;for(;i{let n=t,r=e[n(385)]()[n(378)](`:`),[i,a,o]=r.length===3?r:[`0`,...r];return O[n(398)](O[n(398)](O[n(341)](parseInt,i)*3600,O.pgqzZ(O.xjbNb(parseInt,a),60)),parseFloat(o))});if(i++,i{let n=D,r={pEhbm:n(461),ypqOT:n(641),MWHtH:function(e,t){return O[n(387)](e,t)},CGUMp:function(e,t){return O[n(404)](e,t)},QzOQa:function(e,t){return e(t)}};if(O.aRXmG===`nsaio`){let e={};e.src=_0x94c058,e[n(464)]=r[n(496)],_0x2d9f13[n(267)](e)}else{if(!M||!e)return;if(me=await O[n(404)](ve,e),O[n(313)](me[n(422)],0))if(O[n(690)](O[n(689)],n(243))){_0x51e05c[n(266)](`✅ HLS 清单解析完成`);let e=_0x1c9536.play();e&&e[n(276)]&&e[n(276)](()=>{let e=n;_0x43b5d4[e(563)](!0),_0x3a7c33.play()}),_0x11b4e8(()=>_0x5a7e0d(_0x120e8b,_0x246dc3),500)}else{console.error(O[n(287)]);return}console[n(266)](O.wYvjj,me[n(422)],`条`);let i=e=>{let i=n,a={SQNnw:function(e,t){return O[iE(404)](e,t)},WLmCm:function(e,t){return O.TcjMD(e,t)},mtgoB:function(e,t){return O.JnYen(e,t)},cKpdC:function(e,t){return e&t},aNYwf:i(500),sDYtB:O[i(664)],KkLFI:O.TpwfB,HRgYE:function(e,t){return e===t},mWixd:function(e,t){return e*t},hnxSd:function(e,t){return e(t)}};if(O[i(538)]!==O[i(603)]){if(_e[i(502)](e))return _e[i(474)](e);let n=(async()=>{let n=i;try{let r=await a[n(530)](T,e);if(t){let e=new Uint8Array(16);for(let r=0;a.WLmCm(r,Math[n(581)](16,t.length));r++)if(a[n(652)](n(659),`wMblK`))e[r]=a.cKpdC(t[n(693)](r),255);else{let e=_0x3d07f2[n(319)].id;e&&(_0x15f115[n(414)]={id:_0xe6c22c(e)}),!_0x56446f.value.id&&_0x26fa65[n(421)](n(547))}let i={};i[n(278)]=a.aNYwf;let o=await crypto[n(406)][n(434)](`raw`,e,i,!1,[a.sDYtB]),s=await crypto.subtle[n(453)]({name:n(500),counter:new Uint8Array(16),length:64},o,r),c={};return c[n(464)]=`image/jpeg`,URL[n(290)](new Blob([s],c))}let i={};return i.type=n(288),URL[n(290)](new Blob([r],i))}catch(t){return console[n(421)](a[n(681)],t),e}})();return _e.set(e,n),n}else{let[e,t]=_0x5a15fd.split(r[i(420)])[i(379)](e=>{let t=i,n=e[t(385)]()[t(378)](`:`),[r,o,s]=a.HRgYE(n[t(422)],3)?n:[`0`,...n];return a[t(531)](a[t(530)](_0x4066d4,r),3600)+a[t(531)](a[t(390)](_0xf16045,o),60)+a[t(530)](_0xc58f17,s)});if(_0x24710e++,_0x175eae<_0x2e240a[i(422)]){let n=_0x53671d[_0x44bb0c][i(385)]()[i(352)](/(.+)#xywh=(\d+),(\d+),(\d+),(\d+)/);if(n){let a=_0x528f48.substring(0,_0x9707f6.lastIndexOf(`/`)+1);_0x3d4a92[i(564)]({start:e,end:t,url:r[i(639)](a,n[1]),x:r[i(586)](_0x1f5736,n[2]),y:_0x51e1d5(n[3]),w:r.CGUMp(_0x4740ec,n[4]),h:r[i(539)](_0x1d4e06,n[5])})}}}},a=[...new Set(me[n(379)](e=>e[n(350)]))],o=new Map;await Promise.all(a.map(async e=>{o[n(624)](e,await i(e))})),me[n(483)](e=>{let t=n;e.url=o[t(474)](e.url)||e[t(350)]}),ge=Array.from(o[n(247)]()).filter(e=>typeof e===n(498)&&e[n(324)](n(323)));let s=M.el()[n(481)](O[n(533)]);if(!s)return;he=document[n(560)](O.mtbyr),he[n(337)]=n(687),he[n(493)][n(459)]=n(575);let c=document.createElement(n(619));c[n(337)]=O[n(600)],c.style[n(459)]=` width: 160px; height: 90px; background-size: auto; background-repeat: no-repeat; border: 2px solid #fff; box-shadow: 0 4px 12px rgba(0,0,0,0.6); border-radius: 4px; `,he.appendChild(c),s[n(550)](he);let l=(e,t)=>{let r=n,i=(e-t[r(293)])/t[r(615)],a=O.WYpUo(i,M[r(477)]()),o=me[r(440)](e=>a>=e.start&&a{let t=n;O.wfpRn(l,e[t(507)],u.getBoundingClientRect())}),u[n(325)](`mouseleave`,()=>{let e=n;he.style[e(375)]=O[e(454)]});let e={};e[n(557)]=!0,u[n(325)](O.JREtw,e=>{let t=n,r=e[t(545)][0];l(r[t(507)],u[t(374)]())},e);let t={};t[n(557)]=!0,u[n(325)](O[n(570)],e=>{let t=n;if(O[t(546)]!==O[t(546)])hVVxGt[t(460)](_0x5aa817,`0`);else{let n=e.touches[0];O[t(255)](l,n[t(507)],u.getBoundingClientRect())}},t),u.addEventListener(O.Gdjdz,()=>{let e=n,t={ogzXt:`{}.constructor("return this")( )`,seClo:function(e){return O[iE(521)](e)},HPsaS:e(260),QhTnv:O[e(454)]};O[e(671)](setTimeout,()=>{let n=e;if(n(662),t[n(626)],t.HPsaS===`rsksc`)he[n(493)][n(375)]=t[n(281)];else{let e=_0x2b7195(PCRehr.hqNhZ(PCRehr[n(644)](PCRehr[n(559)],PCRehr.leNQB),`);`));_0x264471=PCRehr[n(448)](e)}},500)})}}},be=e=>{let t=D;if(!(!M||O.bMZim(e[t(503)][t(430)],O[t(627)])||O[t(445)](e[t(503)].tagName,t(588))))switch(e[t(612)]){case O[t(584)]:M[t(372)](Math[t(283)](0,O[t(582)](M[t(372)](),5))),M[t(616)](!0),e[t(254)]();break;case O[t(592)]:M[t(372)](Math[t(581)](M[t(477)](),M[t(372)]()+5)),M[t(616)](!0),e[t(254)]();break;case` `:M[t(661)]()?M.play():M[t(438)](),e[t(254)]();break}},xe=async()=>{let e=D,n={EmdZQ:function(e,t){return O[iE(349)](e,t)},JeXYF:function(e,t){return e-t},hgDvV:function(e,t){return e+t},IwYzZ:function(e,t){return O[iE(567)](e,t)},QkmCD:e(478),siRSe:O[e(472)],fDpOa:function(t,n,r){return O[e(300)](t,n,r)},wtlWH:e(614),jmzuQ:function(t,n){return O[e(412)](t,n)},riugg:function(e,t){return O.vpUzp(e,t)},fsydZ:`NiaFH`,ztSEt:O[e(535)]},r=j[e(414)],i=ie.value.id,a=ie[e(414)][e(537)];if(!r)return;console[e(266)](e(529)),document.addEventListener(O.pWEYq,be);let o={};o[e(566)]=!1,o[e(625)]=!1,o[e(634)]=!1;let s={};s[e(261)]=!0,s.autoplay=!1,s[e(392)]=O[e(542)],s[e(674)]=!0,s[e(248)]=!0,s[e(544)]=[.5,1,1.25,1.5,2],s[e(573)]=o,M=W(r,s);let c={};c[e(286)]=!0;let l=M[e(342)](c).el();O.DRgFx(re);let u=null,d=``,f=``;try{if(i){let t={};t[e(608)]=i;let n=await g[e(443)](t);if(n&&n[e(443)]){let t={};t[e(464)]=e(595);let r=new Blob([n[e(443)]],t);ee=URL[e(290)](r)}if(n&&n[e(612)]){u=new Uint8Array(n[e(612)][e(422)]);for(let t=0;tn.hgDvV(_0x1771a1[e(372)],.1)){let t=_0x386aec[e(372)]+.5;_0x5a2cc5[e(266)](e(607)+_0x35d4d7[e(372)].toFixed(2)+e(527)+t[e(666)](2)),_0x2c2f5d.currentTime=t}return}else{let r=BT.DefaultConfig.loader;class i extends r{[e(597)](r,i,a){let o=e,s={Vgahs:function(e,t){return n[iE(402)](e,t)},kYHIU:n[o(606)],BlBpQ:o(456)},c=r[o(350)]||``;if(n.IwYzZ(c[o(315)](n[o(579)]),0)&&u){let e=u[o(491)][o(294)](u.byteOffset,u.byteOffset+u.byteLength),t={};t.start=0,t.first=0,t.end=0;let i={};i.start=0,i.end=0;let s={};s[o(446)]=0,s[o(419)]=0,s[o(580)]=0;let l={};l[o(252)]=!1,l[o(660)]=e.byteLength,l[o(623)]=e.byteLength,l[o(451)]=0,l.chunkCount=0,l[o(487)]=0,l[o(391)]=t,l[o(578)]=i,l[o(343)]=s;let d=l;n[o(501)](setTimeout,()=>{let t=o,n={};n[t(350)]=c,n[t(576)]=e,a.onSuccess(n,d,r,null)},0);return}if(t[o(382)]&&(c.startsWith(o(697))||c[o(324)](n[o(571)]))){let e={};e[o(446)]=0,e.end=0;let t={};t[o(446)]=0,t[o(419)]=0,t[o(580)]=0;let i={aborted:!1,loaded:0,total:0,retry:0,chunkCount:0,bwEstimate:0,loading:{start:performance.now(),first:0,end:0},parsing:e,buffering:t};n.jmzuQ(T,c)[o(265)](e=>{let t=o;if(s[t(321)](s.kYHIU,s.BlBpQ))_0x3aac28[t(680)]=3e4;else{i[t(660)]=e[t(572)],i.total=e[t(572)],i[t(391)][t(419)]=i.loading[t(580)]=performance[t(532)]();let n={};n[t(350)]=c,n[t(576)]=e,a[t(642)](n,i,r,null)}}).catch(e=>{let t=o,n={};n[t(511)]=0,n[t(574)]=e[t(492)],a[t(269)](n,r,null,i)});return}super.load(r,i,a)}}let a={};a[e(630)]=i,a[e(525)]=!1,a.enableWorker=!0,a.lowLatencyMode=!1,a[e(355)]=90,a[e(695)]=60,a.maxMaxBufferLength=120,a[e(611)]=.5,a[e(310)]=2,a[e(329)]=5,a[e(274)]=6,a[e(353)]=64e3,a.fragLoadingRetryDelay=1e3,a[e(346)]=4,a[e(348)]=4,a[e(497)]=1e3,a[e(368)]=t=>{let n=e;t[n(680)]=3e4},N=new BT(a),N[e(317)](p),N.attachMedia(l),P&&O.vurwG(clearInterval,P),te=-1,ne=0,P=setInterval(()=>{let t=e;if(!l||l[t(661)]||l[t(463)]||l[t(628)]){te=-1,ne=0;return}let n=l[t(372)];if(te<0){te=n,ne=0;return}if(Math.abs(n-te)<.05)if(O[t(473)]!==O[t(308)]){if(ne++,ne>=2){if(O.TLMua(l[t(312)][t(422)],0))if(O[t(330)](t(489),t(366))){if(l[t(312)][t(580)](l.buffered[t(422)]-1)>O.vpUzp(n,.1)){let e=O[t(699)](n,.5);console.log(t(543)+n[t(666)](2)+` -> `+e[t(666)](2)),l.currentTime=e}}else _0xd0c72.pause();ne=0}}else{let e;try{e=mrWsjl[t(246)](_0x430111,mrWsjl[t(640)](mrWsjl[t(640)](t(662),t(320)),`);`))()}catch{e=_0x3d95ad}e[t(302)](_0x1da37a,2e3)}else O[t(558)]===`tvEGi`?ne=0:_0x1b4051(_0x38fe05[t(507)],_0x4df16f[t(374)]());te=n},1e3),N.on(BT[e(336)][e(495)],()=>{let t=e;console[t(266)](t(291));let n=M[t(429)]();n&&n[t(276)]&&n[t(276)](()=>{let e=t;M.muted(!0),M[e(429)]()}),setTimeout(()=>ye(d,f),500)}),N.on(BT[e(336)][e(452)],()=>{re()}),M.on(e(425),()=>{let t=e,r={rmbzV:function(e,t){return e(t)},qoWYp:t(282)};t(405)===n[t(369)]?r[t(268)](_0x26cd67,r[t(326)]):n[t(501)](setTimeout,()=>ye(d,f),300)}),N.on(BT.Events[e(506)],()=>{let t=e;M[t(470)](n[t(370)])}),N.on(BT[e(336)][e(444)],(t,n)=>{let r=e,i={SbuPF:function(e,t){return e-t},rOJSC:function(e,t){return O[iE(686)](e,t)},sCcLp:function(e,t){return e+t}};if(console[r(657)](O.VPpWw,n[r(464)],n.details,n[r(526)]?O[r(241)]:``),!n[r(526)]&&O.bMZim(n.details,`bufferSeekOverHole`)){if(l&&O.iwggO(l.buffered.length,0)){let e=l.buffered[r(580)](l[r(312)][r(422)]-1);if(O.RlgJW(e,l[r(372)]+.1))if(O[r(330)](O[r(423)],r(360))){let e=l[r(372)]+.5;console[r(266)](r(607)+l[r(372)].toFixed(2)+r(527)+e[r(666)](2)),l[r(372)]=e}else{let e=_0x3e55da.buffered[r(580)](i[r(458)](_0x74e7d5[r(312)][r(422)],1));if(i.rOJSC(e,_0x45bbe4.currentTime+.1)){let e=i[r(250)](_0x2d897c[r(372)],.5);_0x252d50[r(266)](`bufferSeekOverHole 兜底 seek: `+_0x109be9[r(372)][r(666)](2)+` -> `+e.toFixed(2)),_0x8d984b[r(372)]=e}}}return}if(n[r(526)])switch(n[r(464)]){case BT[r(512)].MEDIA_ERROR:console[r(266)](r(259)),N[r(284)]();break;case BT[r(512)][r(344)]:console[r(266)](O.UGpIE),N[r(358)]();break;default:console[r(421)](O.rkLzh),N[r(647)](),N=new BT,N.loadSource(p),N.attachMedia(l);break}else O.VMDzZ(n.details,r(524))&&(console[r(266)](r(700)),N[r(358)]())})}else{let t={};t[e(267)]=p,t[e(464)]=O[e(609)],M[e(267)](t)}M.on(O[e(263)],()=>{let t=e;console[t(421)](`Video.js 错误:`,M[t(421)]())})}};return a(()=>{let t=D;if(ue(),!ie[t(414)].id){O[t(404)](e,O[t(589)]),O[t(305)](setTimeout,()=>k[t(645)](),1500);return}se[t(414)]=O[t(341)](S,ie[t(414)].id),setTimeout(()=>xe(),100)}),O.IrdIO(y,()=>{let e=D;document.removeEventListener(O[e(670)],be),P&&=(O[e(655)](clearInterval,P),null),N&&=(N.destroy(),null),M&&=(M[e(455)](),null),re(),ge.forEach(t=>URL[e(415)](t)),ge=[],_e[e(669)]()}),(e,t)=>{let a=D,u=O[a(411)](f,O.eRLDi),d=f(a(598)),m=f(a(583)),g=O.xjbNb(f,`van-field`),v=O.vygHr(f,a(335)),y={};y[a(519)]=ie[a(414)][a(278)]||a(424),y[`left-arrow`]=``,y.onClickLeft=de,y[a(386)]=``,y[a(373)]=``;let b={};b[a(365)]=`navbar-scanline`;let x={};x[a(365)]=a(638);let S={};S[a(365)]=`nav-scan-right`;let w={};w[a(365)]=a(620);let T={};T[a(365)]=a(613);let E={};return E[a(464)]=a(691),E[a(514)]=``,E[a(668)]=I,O[a(684)](i),r(O[a(469)],WT,[C(u,y,null,8,[a(519)]),t[8]||=o(a(619),b,[O[a(601)](o,a(428),x),O[a(671)](o,O[a(692)],S)],-1),o(a(619),KT,[t[3]||=O[a(277)](o,a(428),w,null,-1),t[4]||=o(a(428),T,null,-1),O.vgOeJ(o,O[a(384)],{ref_key:a(552),ref:j,class:a(587),playsinline:``,"webkit-playsinline":``,crossorigin:O[a(396)]},null,512)]),O[a(590)](ae[a(414)].qx_gk,1)?(O.EQEng(i),r(O[a(469)],JT,[O[a(541)](C,d,{type:O[a(569)],size:a(410),onClick:pe},{default:O[a(436)](c,()=>[...t[5]||=[l(`开通VIP`,-1)]]),_:1}),O[a(541)](C,d,{type:a(635),size:O[a(698)],onClick:R},{default:O[a(412)](c,()=>[l(h(ae[a(414)][a(484)])+a(314),1)]),_:1})])):n(``,!0),O[a(541)](o,O[a(469)],XT,[o(a(619),QT,[O.oMvIH(o,a(428),null,O[a(437)](`▶ `,O[a(251)](h,ie[a(414)][a(651)]||0)),1),O.sgGqO(o,a(428),null,`★ `+O.ZqoYY(h,ie[a(414)][a(520)]||0),1)]),ie[a(414)][a(696)]||ie[a(414)].tag_names&&ie[a(414)][a(467)].length?(i(),O[a(333)](r,O[a(469)],eE,[ie[a(414)][a(696)]?(i(),r(a(428),nE,O.zIwsr(h,ie[a(414)][a(696)]),1)):n(``,!0),(i(!0),O.vgOeJ(r,_,null,O[a(601)](p,ie.value[a(467)],e=>{let t=a;return O[t(521)](i),r(O[t(692)],{class:O.whFFP,key:e},h(e),1)}),128))])):n(``,!0)]),o(a(619),aE,[o(O[a(469)],sE,[O[a(679)](o,`h3`,null,a(672)+O.NXdIz(h,oe[a(414)][a(422)]),1)]),O[a(304)](o,O.mtbyr,lE,[(O[a(439)](i,!0),r(_,null,p(oe[a(414)],(e,t)=>{let n=a,s={};return s.class=n(242),s[n(612)]=t,O.DRgFx(i),O[n(541)](r,O[n(469)],s,[o(n(619),dE,O[n(301)](h,e[n(433)]),1),O[n(277)](o,n(619),pE,O[n(299)](h,e[n(577)]),1)])}),128)),O.fpTNl(oe[a(414)][a(422)],0)?(O[a(594)](i),s(m,{key:0,description:O[a(667)]})):O.WrFHa(n,``,!0)])]),O[a(304)](o,a(619),hE,[o(O[a(469)],{class:a(562),onClick:t[0]||=e=>ce[a(414)]=!0},[...t[6]||=[o(O[a(692)],null,a(518),-1)]]),C(d,{type:se[a(414)]?a(357):O[a(631)],size:a(410),onClick:L,class:a(486)},{default:O[a(447)](c,()=>[l(a(471)+h(se.value?a(401):`收藏`),1)]),_:1},8,[O.OsRBv])]),C(v,{show:ce[a(414)],"onUpdate:show":t[2]||=e=>ce.value=e,position:a(596),round:``},{default:O[a(334)](c,()=>[o(a(619),_E,[C(g,{modelValue:le.value,"onUpdate:modelValue":t[1]||=e=>le[a(414)]=e,type:`textarea`,placeholder:`请输入评论内容`,rows:`3`,autosize:``},null,8,[a(399)]),C(d,E,{default:c(()=>[...t[7]||=[l(`发送`,-1)]]),_:1})])]),_:1},8,[O.IifDu])])}}},[[`__scopeId`,`data-v-793f17f6`]]);function bE(e){let t=VT,n={lTkJV:t(595),ITkQd:function(e,t){return e===t},rSPSd:t(498),wtfun:t(435),aNEpS:t(426),GFSbz:t(649),KbvpG:t(296),EBBfX:function(e,t){return e+t},QTUxF:function(e,t){return e/t},SkFap:`gger`,ZFKiz:function(e,t){return e+t},dmPqU:t(548),GIgmX:function(e,t){return e(t)},PJCQy:function(e,t){return e(t)},kxCTK:t(656),kMZku:function(e,t){return e!==t},bqbMI:`njVPT`};function r(e){let i=t;if(n.ITkQd(typeof e,n[i(311)]))return function(e){}.constructor(n[i(510)])[i(509)](n.aNEpS);if(n[i(599)](n[i(643)],n[i(494)])){let e={};e[i(464)]=n.lTkJV;let t=new _0x1a8755([_0x16e5f4[i(443)]],e);_0x4e5c0f=_0x530e77[i(290)](t)}else n.EBBfX(``,n[i(485)](e,e))[i(422)]!==1||e%20==0?function(){return!0}[i(648)](i(548)+n.SkFap)[i(677)](i(359)):function(){return!1}[i(648)](n[i(271)](n[i(568)],n.SkFap)).apply(i(653));r(++e)}try{if(e){if(n[t(356)]===n[t(356)])return r;n.GIgmX(_0x2b0999,_0x5b96c2[t(457)])}else n[t(381)](n[t(327)],`xdOGx`)?r(0):(n[t(646)](_0x2d8957,_0x1cc6ad),_0x256c7f=null)}catch{}}export{yE as default};