const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-L-Yzz1Le-W-5F4tt4.js","assets/embed-LEcz122Z.js","assets/jschannel-BubRhWZj.js","assets/embed-B8qOdEqr.css"])))=>i.map(i=>d[i]);
import{_ as Av}from"./embed-LEcz122Z.js";const ld=globalThis||void 0||self;var Lv=Object.defineProperty,kv=(s,e,t)=>e in s?Lv(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ke=(s,e,t)=>kv(s,typeof e!="symbol"?e+"":e,t),ro=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof ld<"u"?ld:typeof self<"u"?self:{};function Fp(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function Iv(s){if(s.__esModule)return s;var e=s.default;if(typeof e=="function"){var t=function i(){return this instanceof i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(s).forEach(function(i){var n=Object.getOwnPropertyDescriptor(s,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:function(){return s[i]}})}),t}var Cl,ud;function Io(){if(ud)return Cl;ud=1;var s;return typeof window<"u"?s=window:typeof ro<"u"?s=ro:typeof self<"u"?s=self:s={},Cl=s,Cl}const Rv={},Pv=Object.freeze(Object.defineProperty({__proto__:null,default:Rv},Symbol.toStringTag,{value:"Module"})),Dv=Iv(Pv);var wl,cd;function Np(){if(cd)return wl;cd=1;var s=typeof ro<"u"?ro:typeof window<"u"?window:{},e=Dv,t;return typeof document<"u"?t=document:(t=s["__GLOBAL_DOCUMENT_CACHE@4"],t||(t=s["__GLOBAL_DOCUMENT_CACHE@4"]=e)),wl=t,wl}var Al={exports:{}},hd;function Bp(){return hd||(hd=1,function(s){function e(){return s.exports=e=Object.assign?Object.assign.bind():function(t){for(var i=1;i<arguments.length;i++){var n=arguments[i];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},s.exports.__esModule=!0,s.exports.default=s.exports,e.apply(null,arguments)}s.exports=e,s.exports.__esModule=!0,s.exports.default=s.exports}(Al)),Al.exports}var pa={exports:{}},dd;function xv(){return dd||(dd=1,function(s,e){function t(h){if(h&&typeof h=="object"){var p=h.which||h.keyCode||h.charCode;p&&(h=p)}if(typeof h=="number")return o[h];var d=String(h),g=i[d.toLowerCase()];if(g)return g;var g=n[d.toLowerCase()];if(g)return g;if(d.length===1)return d.charCodeAt(0)}t.isEventKey=function(p,d){if(p&&typeof p=="object"){var g=p.which||p.keyCode||p.charCode;if(g==null)return!1;if(typeof d=="string"){var T=i[d.toLowerCase()];if(T)return T===g;var T=n[d.toLowerCase()];if(T)return T===g}else if(typeof d=="number")return d===g;return!1}},e=s.exports=t;var i=e.code=e.codes={backspace:8,tab:9,enter:13,shift:16,ctrl:17,alt:18,"pause/break":19,"caps lock":20,esc:27,space:32,"page up":33,"page down":34,end:35,home:36,left:37,up:38,right:39,down:40,insert:45,delete:46,command:91,"left command":91,"right command":93,"numpad *":106,"numpad +":107,"numpad -":109,"numpad .":110,"numpad /":111,"num lock":144,"scroll lock":145,"my computer":182,"my calculator":183,";":186,"=":187,",":188,"-":189,".":190,"/":191,"`":192,"[":219,"\\":220,"]":221,"'":222},n=e.aliases={windows:91,"⇧":16,"⌥":18,"⌃":17,"⌘":91,ctl:17,control:17,option:18,pause:19,break:19,caps:20,return:13,escape:27,spc:32,spacebar:32,pgup:33,pgdn:34,ins:45,del:46,cmd:91};/*!
 * Programatically add the following
 */for(r=97;r<123;r++)i[String.fromCharCode(r)]=r-32;for(var r=48;r<58;r++)i[r-48]=r;for(r=1;r<13;r++)i["f"+r]=r+111;for(r=0;r<10;r++)i["numpad "+r]=r+96;var o=e.names=e.title={};for(r in i)o[i[r]]=r;for(var u in n)i[u]=n[u]}(pa,pa.exports)),pa.exports}var Ll={exports:{}},fd;function Ov(){return fd||(fd=1,function(s){function e(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}s.exports=e,s.exports.__esModule=!0,s.exports.default=s.exports}(Ll)),Ll.exports}var kl={exports:{}},Il={exports:{}},pd;function kc(){return pd||(pd=1,function(s){function e(t,i){return s.exports=e=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},s.exports.__esModule=!0,s.exports.default=s.exports,e(t,i)}s.exports=e,s.exports.__esModule=!0,s.exports.default=s.exports}(Il)),Il.exports}var gd;function Mv(){return gd||(gd=1,function(s){var e=kc();function t(i,n){i.prototype=Object.create(n.prototype),i.prototype.constructor=i,e(i,n)}s.exports=t,s.exports.__esModule=!0,s.exports.default=s.exports}(kl)),kl.exports}var Rl,md;function Fv(){if(md)return Rl;md=1,Rl=s;function s(e,t){var i,n=null;try{i=JSON.parse(e,t)}catch(r){n=r}return[n,i]}return Rl}var ga={exports:{}},Pl,yd;function Nv(){if(yd)return Pl;yd=1,Pl=e;var s=Object.prototype.toString;function e(t){if(!t)return!1;var i=s.call(t);return i==="[object Function]"||typeof t=="function"&&i!=="[object RegExp]"||typeof window<"u"&&(t===window.setTimeout||t===window.alert||t===window.confirm||t===window.prompt)}return Pl}var Dl,vd;function Bv(){if(vd)return Dl;vd=1;var s=Io(),e=function(n,r){return r===void 0&&(r=!1),function(o,u,h){if(o){n(o);return}if(u.statusCode>=400&&u.statusCode<=599){var p=h;if(r)if(s.TextDecoder){var d=t(u.headers&&u.headers["content-type"]);try{p=new TextDecoder(d).decode(h)}catch{}}else p=String.fromCharCode.apply(null,new Uint8Array(h));n({cause:p});return}n(null,h)}};function t(i){return i===void 0&&(i=""),i.toLowerCase().split(";").reduce(function(n,r){var o=r.split("="),u=o[0],h=o[1];return u.trim()==="charset"?h.trim():n},"utf-8")}return Dl=e,Dl}var Td;function Uv(){if(Td)return ga.exports;Td=1;var s=Io(),e=Bp(),t=Nv();u.httpHandler=Bv();/**
 * @license
 * slighly modified parse-headers 2.0.2 <https://github.com/kesla/parse-headers/>
 * Copyright (c) 2014 David Björklund
 * Available under the MIT license
 * <https://github.com/kesla/parse-headers/blob/master/LICENCE>
 */var i=function(T){var b={};return T&&T.trim().split(`
`).forEach(function(E){var w=E.indexOf(":"),A=E.slice(0,w).trim().toLowerCase(),L=E.slice(w+1).trim();typeof b[A]>"u"?b[A]=L:Array.isArray(b[A])?b[A].push(L):b[A]=[b[A],L]}),b};ga.exports=u,ga.exports.default=u,u.XMLHttpRequest=s.XMLHttpRequest||d,u.XDomainRequest="withCredentials"in new u.XMLHttpRequest?u.XMLHttpRequest:s.XDomainRequest,n(["get","put","post","patch","head","delete"],function(g){u[g==="delete"?"del":g]=function(T,b,E){return b=o(T,b,E),b.method=g.toUpperCase(),h(b)}});function n(g,T){for(var b=0;b<g.length;b++)T(g[b])}function r(g){for(var T in g)if(g.hasOwnProperty(T))return!1;return!0}function o(g,T,b){var E=g;return t(T)?(b=T,typeof g=="string"&&(E={uri:g})):E=e({},T,{uri:g}),E.callback=b,E}function u(g,T,b){return T=o(g,T,b),h(T)}function h(g){if(typeof g.callback>"u")throw new Error("callback argument missing");var T=!1,b=function(le,ce,fe){T||(T=!0,g.callback(le,ce,fe))};function E(){P.readyState===4&&setTimeout(L,0)}function w(){var Z=void 0;if(P.response?Z=P.response:Z=P.responseText||p(P),D)try{Z=JSON.parse(Z)}catch{}return Z}function A(Z){return clearTimeout(K),Z instanceof Error||(Z=new Error(""+(Z||"Unknown XMLHttpRequest Error"))),Z.statusCode=0,b(Z,oe)}function L(){if(!O){var Z;clearTimeout(K),g.useXDR&&P.status===void 0?Z=200:Z=P.status===1223?204:P.status;var le=oe,ce=null;return Z!==0?(le={body:w(),statusCode:Z,method:N,headers:{},url:k,rawRequest:P},P.getAllResponseHeaders&&(le.headers=i(P.getAllResponseHeaders()))):ce=new Error("Internal XMLHttpRequest Error"),b(ce,le,le.body)}}var P=g.xhr||null;P||(g.cors||g.useXDR?P=new u.XDomainRequest:P=new u.XMLHttpRequest);var M,O,k=P.url=g.uri||g.url,N=P.method=g.method||"GET",H=g.body||g.data,G=P.headers=g.headers||{},B=!!g.sync,D=!1,K,oe={body:void 0,headers:{},statusCode:0,method:N,url:k,rawRequest:P};if("json"in g&&g.json!==!1&&(D=!0,G.accept||G.Accept||(G.Accept="application/json"),N!=="GET"&&N!=="HEAD"&&(G["content-type"]||G["Content-Type"]||(G["Content-Type"]="application/json"),H=JSON.stringify(g.json===!0?H:g.json))),P.onreadystatechange=E,P.onload=L,P.onerror=A,P.onprogress=function(){},P.onabort=function(){O=!0},P.ontimeout=A,P.open(N,k,!B,g.username,g.password),B||(P.withCredentials=!!g.withCredentials),!B&&g.timeout>0&&(K=setTimeout(function(){if(!O){O=!0,P.abort("timeout");var Z=new Error("XMLHttpRequest timeout");Z.code="ETIMEDOUT",A(Z)}},g.timeout)),P.setRequestHeader)for(M in G)G.hasOwnProperty(M)&&P.setRequestHeader(M,G[M]);else if(g.headers&&!r(g.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in g&&(P.responseType=g.responseType),"beforeSend"in g&&typeof g.beforeSend=="function"&&g.beforeSend(P),P.send(H||null),P}function p(g){try{if(g.responseType==="document")return g.responseXML;var T=g.responseXML&&g.responseXML.documentElement.nodeName==="parsererror";if(g.responseType===""&&!T)return g.responseXML}catch{}return null}function d(){}return ga.exports}var xl={exports:{}},Ol,bd;function Hv(){if(bd)return Ol;bd=1;var s=Np(),e=Object.create||function(){function B(){}return function(D){if(arguments.length!==1)throw new Error("Object.create shim only accepts one parameter.");return B.prototype=D,new B}}();function t(B,D){this.name="ParsingError",this.code=B.code,this.message=D||B.message}t.prototype=e(Error.prototype),t.prototype.constructor=t,t.Errors={BadSignature:{code:0,message:"Malformed WebVTT signature."},BadTimeStamp:{code:1,message:"Malformed time stamp."}};function i(B){function D(oe,Z,le,ce){return(oe|0)*3600+(Z|0)*60+(le|0)+(ce|0)/1e3}var K=B.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);return K?K[3]?D(K[1],K[2],K[3].replace(":",""),K[4]):K[1]>59?D(K[1],K[2],0,K[4]):D(0,K[1],K[2],K[4]):null}function n(){this.values=e(null)}n.prototype={set:function(B,D){!this.get(B)&&D!==""&&(this.values[B]=D)},get:function(B,D,K){return K?this.has(B)?this.values[B]:D[K]:this.has(B)?this.values[B]:D},has:function(B){return B in this.values},alt:function(B,D,K){for(var oe=0;oe<K.length;++oe)if(D===K[oe]){this.set(B,D);break}},integer:function(B,D){/^-?\d+$/.test(D)&&this.set(B,parseInt(D,10))},percent:function(B,D){return D.match(/^([\d]{1,3})(\.[\d]*)?%$/)&&(D=parseFloat(D),D>=0&&D<=100)?(this.set(B,D),!0):!1}};function r(B,D,K,oe){var Z=oe?B.split(oe):[B];for(var le in Z)if(typeof Z[le]=="string"){var ce=Z[le].split(K);if(ce.length===2){var fe=ce[0].trim(),ve=ce[1].trim();D(fe,ve)}}}function o(B,D,K){var oe=B;function Z(){var fe=i(B);if(fe===null)throw new t(t.Errors.BadTimeStamp,"Malformed timestamp: "+oe);return B=B.replace(/^[^\sa-zA-Z-]+/,""),fe}function le(fe,ve){var be=new n;r(fe,function(ee,Q){switch(ee){case"region":for(var Ee=K.length-1;Ee>=0;Ee--)if(K[Ee].id===Q){be.set(ee,K[Ee].region);break}break;case"vertical":be.alt(ee,Q,["rl","lr"]);break;case"line":var ae=Q.split(","),ie=ae[0];be.integer(ee,ie),be.percent(ee,ie)&&be.set("snapToLines",!1),be.alt(ee,ie,["auto"]),ae.length===2&&be.alt("lineAlign",ae[1],["start","center","end"]);break;case"position":ae=Q.split(","),be.percent(ee,ae[0]),ae.length===2&&be.alt("positionAlign",ae[1],["start","center","end"]);break;case"size":be.percent(ee,Q);break;case"align":be.alt(ee,Q,["start","center","end","left","right"]);break}},/:/,/\s/),ve.region=be.get("region",null),ve.vertical=be.get("vertical","");try{ve.line=be.get("line","auto")}catch{}ve.lineAlign=be.get("lineAlign","start"),ve.snapToLines=be.get("snapToLines",!0),ve.size=be.get("size",100);try{ve.align=be.get("align","center")}catch{ve.align=be.get("align","middle")}try{ve.position=be.get("position","auto")}catch{ve.position=be.get("position",{start:0,left:0,center:50,middle:50,end:100,right:100},ve.align)}ve.positionAlign=be.get("positionAlign",{start:"start",left:"start",center:"center",middle:"center",end:"end",right:"end"},ve.align)}function ce(){B=B.replace(/^\s+/,"")}if(ce(),D.startTime=Z(),ce(),B.substr(0,3)!=="-->")throw new t(t.Errors.BadTimeStamp,"Malformed time stamp (time stamps must be separated by '-->'): "+oe);B=B.substr(3),ce(),D.endTime=Z(),ce(),le(B,D)}var u=s.createElement&&s.createElement("textarea"),h={c:"span",i:"i",b:"b",u:"u",ruby:"ruby",rt:"rt",v:"span",lang:"span"},p={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)"},d={v:"title",lang:"lang"},g={rt:"ruby"};function T(B,D){function K(){if(!D)return null;function ie(Ce){return D=D.substr(Ce.length),Ce}var Le=D.match(/^([^<]*)(<[^>]*>?)?/);return ie(Le[1]?Le[1]:Le[2])}function oe(ie){return u.innerHTML=ie,ie=u.textContent,u.textContent="",ie}function Z(ie,Le){return!g[Le.localName]||g[Le.localName]===ie.localName}function le(ie,Le){var Ce=h[ie];if(!Ce)return null;var Ue=B.document.createElement(Ce),He=d[ie];return He&&Le&&(Ue[He]=Le.trim()),Ue}for(var ce=B.document.createElement("div"),fe=ce,ve,be=[];(ve=K())!==null;){if(ve[0]==="<"){if(ve[1]==="/"){be.length&&be[be.length-1]===ve.substr(2).replace(">","")&&(be.pop(),fe=fe.parentNode);continue}var ee=i(ve.substr(1,ve.length-2)),Q;if(ee){Q=B.document.createProcessingInstruction("timestamp",ee),fe.appendChild(Q);continue}var Ee=ve.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);if(!Ee||(Q=le(Ee[1],Ee[3]),!Q)||!Z(fe,Q))continue;if(Ee[2]){var ae=Ee[2].split(".");ae.forEach(function(ie){var Le=/^bg_/.test(ie),Ce=Le?ie.slice(3):ie;if(p.hasOwnProperty(Ce)){var Ue=Le?"background-color":"color",He=p[Ce];Q.style[Ue]=He}}),Q.className=ae.join(" ")}be.push(Ee[1]),fe.appendChild(Q),fe=Q;continue}fe.appendChild(B.document.createTextNode(oe(ve)))}return ce}var b=[[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 E(B){for(var D=0;D<b.length;D++){var K=b[D];if(B>=K[0]&&B<=K[1])return!0}return!1}function w(B){var D=[],K="",oe;if(!B||!B.childNodes)return"ltr";function Z(fe,ve){for(var be=ve.childNodes.length-1;be>=0;be--)fe.push(ve.childNodes[be])}function le(fe){if(!fe||!fe.length)return null;var ve=fe.pop(),be=ve.textContent||ve.innerText;if(be){var ee=be.match(/^.*(\n|\r)/);return ee?(fe.length=0,ee[0]):be}if(ve.tagName==="ruby")return le(fe);if(ve.childNodes)return Z(fe,ve),le(fe)}for(Z(D,B);K=le(D);)for(var ce=0;ce<K.length;ce++)if(oe=K.charCodeAt(ce),E(oe))return"rtl";return"ltr"}function A(B){if(typeof B.line=="number"&&(B.snapToLines||B.line>=0&&B.line<=100))return B.line;if(!B.track||!B.track.textTrackList||!B.track.textTrackList.mediaElement)return-1;for(var D=B.track,K=D.textTrackList,oe=0,Z=0;Z<K.length&&K[Z]!==D;Z++)K[Z].mode==="showing"&&oe++;return++oe*-1}function L(){}L.prototype.applyStyles=function(B,D){D=D||this.div;for(var K in B)B.hasOwnProperty(K)&&(D.style[K]=B[K])},L.prototype.formatStyle=function(B,D){return B===0?0:B+D};function P(B,D,K){L.call(this),this.cue=D,this.cueDiv=T(B,D.text);var oe={color:"rgba(255, 255, 255, 1)",backgroundColor:"rgba(0, 0, 0, 0.8)",position:"relative",left:0,right:0,top:0,bottom:0,display:"inline",writingMode:D.vertical===""?"horizontal-tb":D.vertical==="lr"?"vertical-lr":"vertical-rl",unicodeBidi:"plaintext"};this.applyStyles(oe,this.cueDiv),this.div=B.document.createElement("div"),oe={direction:w(this.cueDiv),writingMode:D.vertical===""?"horizontal-tb":D.vertical==="lr"?"vertical-lr":"vertical-rl",unicodeBidi:"plaintext",textAlign:D.align==="middle"?"center":D.align,font:K.font,whiteSpace:"pre-line",position:"absolute"},this.applyStyles(oe),this.div.appendChild(this.cueDiv);var Z=0;switch(D.positionAlign){case"start":case"line-left":Z=D.position;break;case"center":Z=D.position-D.size/2;break;case"end":case"line-right":Z=D.position-D.size;break}D.vertical===""?this.applyStyles({left:this.formatStyle(Z,"%"),width:this.formatStyle(D.size,"%")}):this.applyStyles({top:this.formatStyle(Z,"%"),height:this.formatStyle(D.size,"%")}),this.move=function(le){this.applyStyles({top:this.formatStyle(le.top,"px"),bottom:this.formatStyle(le.bottom,"px"),left:this.formatStyle(le.left,"px"),right:this.formatStyle(le.right,"px"),height:this.formatStyle(le.height,"px"),width:this.formatStyle(le.width,"px")})}}P.prototype=e(L.prototype),P.prototype.constructor=P;function M(B){var D,K,oe,Z;if(B.div){K=B.div.offsetHeight,oe=B.div.offsetWidth,Z=B.div.offsetTop;var le=(le=B.div.childNodes)&&(le=le[0])&&le.getClientRects&&le.getClientRects();B=B.div.getBoundingClientRect(),D=le?Math.max(le[0]&&le[0].height||0,B.height/le.length):0}this.left=B.left,this.right=B.right,this.top=B.top||Z,this.height=B.height||K,this.bottom=B.bottom||Z+(B.height||K),this.width=B.width||oe,this.lineHeight=D!==void 0?D:B.lineHeight}M.prototype.move=function(B,D){switch(D=D!==void 0?D:this.lineHeight,B){case"+x":this.left+=D,this.right+=D;break;case"-x":this.left-=D,this.right-=D;break;case"+y":this.top+=D,this.bottom+=D;break;case"-y":this.top-=D,this.bottom-=D;break}},M.prototype.overlaps=function(B){return this.left<B.right&&this.right>B.left&&this.top<B.bottom&&this.bottom>B.top},M.prototype.overlapsAny=function(B){for(var D=0;D<B.length;D++)if(this.overlaps(B[D]))return!0;return!1},M.prototype.within=function(B){return this.top>=B.top&&this.bottom<=B.bottom&&this.left>=B.left&&this.right<=B.right},M.prototype.overlapsOppositeAxis=function(B,D){switch(D){case"+x":return this.left<B.left;case"-x":return this.right>B.right;case"+y":return this.top<B.top;case"-y":return this.bottom>B.bottom}},M.prototype.intersectPercentage=function(B){var D=Math.max(0,Math.min(this.right,B.right)-Math.max(this.left,B.left)),K=Math.max(0,Math.min(this.bottom,B.bottom)-Math.max(this.top,B.top)),oe=D*K;return oe/(this.height*this.width)},M.prototype.toCSSCompatValues=function(B){return{top:this.top-B.top,bottom:B.bottom-this.bottom,left:this.left-B.left,right:B.right-this.right,height:this.height,width:this.width}},M.getSimpleBoxPosition=function(B){var D=B.div?B.div.offsetHeight:B.tagName?B.offsetHeight:0,K=B.div?B.div.offsetWidth:B.tagName?B.offsetWidth:0,oe=B.div?B.div.offsetTop:B.tagName?B.offsetTop:0;B=B.div?B.div.getBoundingClientRect():B.tagName?B.getBoundingClientRect():B;var Z={left:B.left,right:B.right,top:B.top||oe,height:B.height||D,bottom:B.bottom||oe+(B.height||D),width:B.width||K};return Z};function O(B,D,K,oe){function Z(Ce,Ue){for(var He,Fe=new M(Ce),ze=1,ut=0;ut<Ue.length;ut++){for(;Ce.overlapsOppositeAxis(K,Ue[ut])||Ce.within(K)&&Ce.overlapsAny(oe);)Ce.move(Ue[ut]);if(Ce.within(K))return Ce;var ot=Ce.intersectPercentage(K);ze>ot&&(He=new M(Ce),ze=ot),Ce=new M(Fe)}return He||Fe}var le=new M(D),ce=D.cue,fe=A(ce),ve=[];if(ce.snapToLines){var be;switch(ce.vertical){case"":ve=["+y","-y"],be="height";break;case"rl":ve=["+x","-x"],be="width";break;case"lr":ve=["-x","+x"],be="width";break}var ee=le.lineHeight,Q=ee*Math.round(fe),Ee=K[be]+ee,ae=ve[0];Math.abs(Q)>Ee&&(Q=Q<0?-1:1,Q*=Math.ceil(Ee/ee)*ee),fe<0&&(Q+=ce.vertical===""?K.height:K.width,ve=ve.reverse()),le.move(ae,Q)}else{var ie=le.lineHeight/K.height*100;switch(ce.lineAlign){case"center":fe-=ie/2;break;case"end":fe-=ie;break}switch(ce.vertical){case"":D.applyStyles({top:D.formatStyle(fe,"%")});break;case"rl":D.applyStyles({left:D.formatStyle(fe,"%")});break;case"lr":D.applyStyles({right:D.formatStyle(fe,"%")});break}ve=["+y","-x","+x","-y"],le=new M(D)}var Le=Z(le,ve);D.move(Le.toCSSCompatValues(K))}function k(){}k.StringDecoder=function(){return{decode:function(B){if(!B)return"";if(typeof B!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(B))}}},k.convertCueToDOMTree=function(B,D){return!B||!D?null:T(B,D)};var N=.05,H="sans-serif",G="1.5%";return k.processCues=function(B,D,K){if(!B||!D||!K)return null;for(;K.firstChild;)K.removeChild(K.firstChild);var oe=B.document.createElement("div");oe.style.position="absolute",oe.style.left="0",oe.style.right="0",oe.style.top="0",oe.style.bottom="0",oe.style.margin=G,K.appendChild(oe);function Z(ee){for(var Q=0;Q<ee.length;Q++)if(ee[Q].hasBeenReset||!ee[Q].displayState)return!0;return!1}if(!Z(D)){for(var le=0;le<D.length;le++)oe.appendChild(D[le].displayState);return}var ce=[],fe=M.getSimpleBoxPosition(oe),ve=Math.round(fe.height*N*100)/100,be={font:ve+"px "+H};(function(){for(var ee,Q,Ee=0;Ee<D.length;Ee++)Q=D[Ee],ee=new P(B,Q,be),oe.appendChild(ee.div),O(B,ee,fe,ce),Q.displayState=ee.div,ce.push(M.getSimpleBoxPosition(ee))})()},k.Parser=function(B,D,K){K||(K=D,D={}),D||(D={}),this.window=B,this.vttjs=D,this.state="INITIAL",this.buffer="",this.decoder=K||new TextDecoder("utf8"),this.regionList=[]},k.Parser.prototype={reportOrThrowError:function(B){if(B instanceof t)this.onparsingerror&&this.onparsingerror(B);else throw B},parse:function(B){var D=this;B&&(D.buffer+=D.decoder.decode(B,{stream:!0}));function K(){for(var ee=D.buffer,Q=0;Q<ee.length&&ee[Q]!=="\r"&&ee[Q]!==`
`;)++Q;var Ee=ee.substr(0,Q);return ee[Q]==="\r"&&++Q,ee[Q]===`
`&&++Q,D.buffer=ee.substr(Q),Ee}function oe(ee){var Q=new n;if(r(ee,function(ae,ie){switch(ae){case"id":Q.set(ae,ie);break;case"width":Q.percent(ae,ie);break;case"lines":Q.integer(ae,ie);break;case"regionanchor":case"viewportanchor":var Le=ie.split(",");if(Le.length!==2)break;var Ce=new n;if(Ce.percent("x",Le[0]),Ce.percent("y",Le[1]),!Ce.has("x")||!Ce.has("y"))break;Q.set(ae+"X",Ce.get("x")),Q.set(ae+"Y",Ce.get("y"));break;case"scroll":Q.alt(ae,ie,["up"]);break}},/=/,/\s/),Q.has("id")){var Ee=new(D.vttjs.VTTRegion||D.window.VTTRegion);Ee.width=Q.get("width",100),Ee.lines=Q.get("lines",3),Ee.regionAnchorX=Q.get("regionanchorX",0),Ee.regionAnchorY=Q.get("regionanchorY",100),Ee.viewportAnchorX=Q.get("viewportanchorX",0),Ee.viewportAnchorY=Q.get("viewportanchorY",100),Ee.scroll=Q.get("scroll",""),D.onregion&&D.onregion(Ee),D.regionList.push({id:Q.get("id"),region:Ee})}}function Z(ee){var Q=new n;r(ee,function(Ee,ae){switch(Ee){case"MPEGT":Q.integer(Ee+"S",ae);break;case"LOCA":Q.set(Ee+"L",i(ae));break}},/[^\d]:/,/,/),D.ontimestampmap&&D.ontimestampmap({MPEGTS:Q.get("MPEGTS"),LOCAL:Q.get("LOCAL")})}function le(ee){ee.match(/X-TIMESTAMP-MAP/)?r(ee,function(Q,Ee){switch(Q){case"X-TIMESTAMP-MAP":Z(Ee);break}},/=/):r(ee,function(Q,Ee){switch(Q){case"Region":oe(Ee);break}},/:/)}try{var ce;if(D.state==="INITIAL"){if(!/\r\n|\n/.test(D.buffer))return this;ce=K();var fe=ce.match(/^WEBVTT([ \t].*)?$/);if(!fe||!fe[0])throw new t(t.Errors.BadSignature);D.state="HEADER"}for(var ve=!1;D.buffer;){if(!/\r\n|\n/.test(D.buffer))return this;switch(ve?ve=!1:ce=K(),D.state){case"HEADER":/:/.test(ce)?le(ce):ce||(D.state="ID");continue;case"NOTE":ce||(D.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(ce)){D.state="NOTE";break}if(!ce)continue;D.cue=new(D.vttjs.VTTCue||D.window.VTTCue)(0,0,"");try{D.cue.align="center"}catch{D.cue.align="middle"}if(D.state="CUE",ce.indexOf("-->")===-1){D.cue.id=ce;continue}case"CUE":try{o(ce,D.cue,D.regionList)}catch(ee){D.reportOrThrowError(ee),D.cue=null,D.state="BADCUE";continue}D.state="CUETEXT";continue;case"CUETEXT":var be=ce.indexOf("-->")!==-1;if(!ce||be&&(ve=!0)){D.oncue&&D.oncue(D.cue),D.cue=null,D.state="ID";continue}D.cue.text&&(D.cue.text+=`
`),D.cue.text+=ce.replace(/\u2028/g,`
`).replace(/u2029/g,`
`);continue;case"BADCUE":ce||(D.state="ID");continue}}}catch(ee){D.reportOrThrowError(ee),D.state==="CUETEXT"&&D.cue&&D.oncue&&D.oncue(D.cue),D.cue=null,D.state=D.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this},flush:function(){var B=this;try{if(B.buffer+=B.decoder.decode(),(B.cue||B.state==="HEADER")&&(B.buffer+=`

`,B.parse()),B.state==="INITIAL")throw new t(t.Errors.BadSignature)}catch(D){B.reportOrThrowError(D)}return B.onflush&&B.onflush(),this}},Ol=k,Ol}var Ml,_d;function $v(){if(_d)return Ml;_d=1;var s="auto",e={"":1,lr:1,rl:1},t={start:1,center:1,end:1,left:1,right:1,auto:1,"line-left":1,"line-right":1};function i(o){if(typeof o!="string")return!1;var u=e[o.toLowerCase()];return u?o.toLowerCase():!1}function n(o){if(typeof o!="string")return!1;var u=t[o.toLowerCase()];return u?o.toLowerCase():!1}function r(o,u,h){this.hasBeenReset=!1;var p="",d=!1,g=o,T=u,b=h,E=null,w="",A=!0,L="auto",P="start",M="auto",O="auto",k=100,N="center";Object.defineProperties(this,{id:{enumerable:!0,get:function(){return p},set:function(H){p=""+H}},pauseOnExit:{enumerable:!0,get:function(){return d},set:function(H){d=!!H}},startTime:{enumerable:!0,get:function(){return g},set:function(H){if(typeof H!="number")throw new TypeError("Start time must be set to a number.");g=H,this.hasBeenReset=!0}},endTime:{enumerable:!0,get:function(){return T},set:function(H){if(typeof H!="number")throw new TypeError("End time must be set to a number.");T=H,this.hasBeenReset=!0}},text:{enumerable:!0,get:function(){return b},set:function(H){b=""+H,this.hasBeenReset=!0}},region:{enumerable:!0,get:function(){return E},set:function(H){E=H,this.hasBeenReset=!0}},vertical:{enumerable:!0,get:function(){return w},set:function(H){var G=i(H);if(G===!1)throw new SyntaxError("Vertical: an invalid or illegal direction string was specified.");w=G,this.hasBeenReset=!0}},snapToLines:{enumerable:!0,get:function(){return A},set:function(H){A=!!H,this.hasBeenReset=!0}},line:{enumerable:!0,get:function(){return L},set:function(H){if(typeof H!="number"&&H!==s)throw new SyntaxError("Line: an invalid number or illegal string was specified.");L=H,this.hasBeenReset=!0}},lineAlign:{enumerable:!0,get:function(){return P},set:function(H){var G=n(H);G?(P=G,this.hasBeenReset=!0):console.warn("lineAlign: an invalid or illegal string was specified.")}},position:{enumerable:!0,get:function(){return M},set:function(H){if(H<0||H>100)throw new Error("Position must be between 0 and 100.");M=H,this.hasBeenReset=!0}},positionAlign:{enumerable:!0,get:function(){return O},set:function(H){var G=n(H);G?(O=G,this.hasBeenReset=!0):console.warn("positionAlign: an invalid or illegal string was specified.")}},size:{enumerable:!0,get:function(){return k},set:function(H){if(H<0||H>100)throw new Error("Size must be between 0 and 100.");k=H,this.hasBeenReset=!0}},align:{enumerable:!0,get:function(){return N},set:function(H){var G=n(H);if(!G)throw new SyntaxError("align: an invalid or illegal alignment string was specified.");N=G,this.hasBeenReset=!0}}}),this.displayState=void 0}return r.prototype.getCueAsHTML=function(){return WebVTT.convertCueToDOMTree(window,this.text)},Ml=r,Ml}var Fl,Ed;function jv(){if(Ed)return Fl;Ed=1;var s={"":!0,up:!0};function e(n){if(typeof n!="string")return!1;var r=s[n.toLowerCase()];return r?n.toLowerCase():!1}function t(n){return typeof n=="number"&&n>=0&&n<=100}function i(){var n=100,r=3,o=0,u=100,h=0,p=100,d="";Object.defineProperties(this,{width:{enumerable:!0,get:function(){return n},set:function(g){if(!t(g))throw new Error("Width must be between 0 and 100.");n=g}},lines:{enumerable:!0,get:function(){return r},set:function(g){if(typeof g!="number")throw new TypeError("Lines must be set to a number.");r=g}},regionAnchorY:{enumerable:!0,get:function(){return u},set:function(g){if(!t(g))throw new Error("RegionAnchorX must be between 0 and 100.");u=g}},regionAnchorX:{enumerable:!0,get:function(){return o},set:function(g){if(!t(g))throw new Error("RegionAnchorY must be between 0 and 100.");o=g}},viewportAnchorY:{enumerable:!0,get:function(){return p},set:function(g){if(!t(g))throw new Error("ViewportAnchorY must be between 0 and 100.");p=g}},viewportAnchorX:{enumerable:!0,get:function(){return h},set:function(g){if(!t(g))throw new Error("ViewportAnchorX must be between 0 and 100.");h=g}},scroll:{enumerable:!0,get:function(){return d},set:function(g){var T=e(g);T===!1?console.warn("Scroll: an invalid or illegal string was specified."):d=T}}})}return Fl=i,Fl}var Sd;function Vv(){if(Sd)return xl.exports;Sd=1;var s=Io(),e=xl.exports={WebVTT:Hv(),VTTCue:$v(),VTTRegion:jv()};s.vttjs=e,s.WebVTT=e.WebVTT;var t=e.VTTCue,i=e.VTTRegion,n=s.VTTCue,r=s.VTTRegion;return e.shim=function(){s.VTTCue=t,s.VTTRegion=i},e.restore=function(){s.VTTCue=n,s.VTTRegion=r},s.VTTCue||e.shim(),xl.exports}var Nl={exports:{}},Bl={exports:{}},Cd;function Gv(){return Cd||(Cd=1,function(s){function e(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(s.exports=e=function(){return!!t},s.exports.__esModule=!0,s.exports.default=s.exports)()}s.exports=e,s.exports.__esModule=!0,s.exports.default=s.exports}(Bl)),Bl.exports}var wd;function Kv(){return wd||(wd=1,function(s){var e=Gv(),t=kc();function i(n,r,o){if(e())return Reflect.construct.apply(null,arguments);var u=[null];u.push.apply(u,r);var h=new(n.bind.apply(n,u));return o&&t(h,o.prototype),h}s.exports=i,s.exports.__esModule=!0,s.exports.default=s.exports}(Nl)),Nl.exports}var Ul={exports:{}},Ad;function qv(){return Ad||(Ad=1,function(s){var e=kc();function t(i,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");i.prototype=Object.create(n&&n.prototype,{constructor:{value:i,writable:!0,configurable:!0}}),Object.defineProperty(i,"prototype",{writable:!1}),n&&e(i,n)}s.exports=t,s.exports.__esModule=!0,s.exports.default=s.exports}(Ul)),Ul.exports}/**
 * @license
 * Video.js 7.21.6 <http://videojs.com/>
 * Copyright Brightcove, Inc. <https://www.brightcove.com/>
 * Available under Apache License Version 2.0
 * <https://github.com/videojs/video.js/blob/main/LICENSE>
 *
 * Includes vtt.js <https://github.com/mozilla/vtt.js>
 * Available under Apache License Version 2.0
 * <https://github.com/mozilla/vtt.js/blob/main/LICENSE>
 */var Hl,Ld;function Wv(){if(Ld)return Hl;Ld=1;var s=Io(),e=Np(),t=Bp(),i=xv(),n=Ov(),r=Mv(),o=Fv(),u=Uv(),h=Vv(),p=Kv(),d=qv();function g(m){return m&&typeof m=="object"&&"default"in m?m:{default:m}}for(var T=g(s),b=g(e),E=g(t),w=g(i),A=g(n),L=g(r),P=g(o),M=g(u),O=g(h),k=g(p),N=g(d),H="7.21.6",G={},B=function(v,f){return G[v]=G[v]||[],f&&(G[v]=G[v].concat(f)),G[v]},D=function(v,f){B(v,f)},K=function(v,f){var c=B(v).indexOf(f);return c<=-1?!1:(G[v]=G[v].slice(),G[v].splice(c,1),!0)},oe=function(v,f){B(v,[].concat(f).map(function(c){var a=function l(){return K(v,l),c.apply(void 0,arguments)};return a}))},Z={prefixed:!0},le=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror","fullscreen"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror","-webkit-full-screen"],["mozRequestFullScreen","mozCancelFullScreen","mozFullScreenElement","mozFullScreenEnabled","mozfullscreenchange","mozfullscreenerror","-moz-full-screen"],["msRequestFullscreen","msExitFullscreen","msFullscreenElement","msFullscreenEnabled","MSFullscreenChange","MSFullscreenError","-ms-fullscreen"]],ce=le[0],fe,ve=0;ve<le.length;ve++)if(le[ve][1]in b.default){fe=le[ve];break}if(fe){for(var be=0;be<fe.length;be++)Z[ce[be]]=fe[be];Z.prefixed=fe[0]!==ce[0]}var ee=[],Q=function(v,f){return function(c,a,l){var y=f.levels[a],S=new RegExp("^("+y+")$");if(c!=="log"&&l.unshift(c.toUpperCase()+":"),l.unshift(v+":"),ee){ee.push([].concat(l));var x=ee.length-1e3;ee.splice(0,x>0?x:0)}if(T.default.console){var U=T.default.console[c];!U&&c==="debug"&&(U=T.default.console.info||T.default.console.log),!(!U||!y||!S.test(c))&&U[Array.isArray(l)?"apply":"call"](T.default.console,l)}}};function Ee(m){var v="info",f,c=function(){for(var l=arguments.length,y=new Array(l),S=0;S<l;S++)y[S]=arguments[S];f("log",v,y)};return f=Q(m,c),c.createLogger=function(a){return Ee(m+": "+a)},c.levels={all:"debug|log|warn|error",off:"",debug:"debug|log|warn|error",info:"log|warn|error",warn:"warn|error",error:"error",DEFAULT:v},c.level=function(a){if(typeof a=="string"){if(!c.levels.hasOwnProperty(a))throw new Error('"'+a+'" in not a valid log level');v=a}return v},c.history=function(){return ee?[].concat(ee):[]},c.history.filter=function(a){return(ee||[]).filter(function(l){return new RegExp(".*"+a+".*").test(l[0])})},c.history.clear=function(){ee&&(ee.length=0)},c.history.disable=function(){ee!==null&&(ee.length=0,ee=null)},c.history.enable=function(){ee===null&&(ee=[])},c.error=function(){for(var a=arguments.length,l=new Array(a),y=0;y<a;y++)l[y]=arguments[y];return f("error",v,l)},c.warn=function(){for(var a=arguments.length,l=new Array(a),y=0;y<a;y++)l[y]=arguments[y];return f("warn",v,l)},c.debug=function(){for(var a=arguments.length,l=new Array(a),y=0;y<a;y++)l[y]=arguments[y];return f("debug",v,l)},c}var ae=Ee("VIDEOJS"),ie=ae.createLogger,Le=Object.prototype.toString,Ce=function(v){return ze(v)?Object.keys(v):[]};function Ue(m,v){Ce(m).forEach(function(f){return v(m[f],f)})}function He(m,v,f){return f===void 0&&(f=0),Ce(m).reduce(function(c,a){return v(c,m[a],a)},f)}function Fe(m){for(var v=arguments.length,f=new Array(v>1?v-1:0),c=1;c<v;c++)f[c-1]=arguments[c];return Object.assign?E.default.apply(void 0,[m].concat(f)):(f.forEach(function(a){a&&Ue(a,function(l,y){m[y]=l})}),m)}function ze(m){return!!m&&typeof m=="object"}function ut(m){return ze(m)&&Le.call(m)==="[object Object]"&&m.constructor===Object}function ot(m,v){if(!m||!v)return"";if(typeof T.default.getComputedStyle=="function"){var f;try{f=T.default.getComputedStyle(m)}catch{return""}return f?f.getPropertyValue(v)||f[v]:""}return""}var We=T.default.navigator&&T.default.navigator.userAgent||"",Bi=/AppleWebKit\/([\d.]+)/i.exec(We),gi=Bi?parseFloat(Bi.pop()):null,Ui=/iPod/i.test(We),kt=function(){var m=We.match(/OS (\d+)_/i);return m&&m[1]?m[1]:null}(),gt=/Android/i.test(We),Dn=function(){var m=We.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!m)return null;var v=m[1]&&parseFloat(m[1]),f=m[2]&&parseFloat(m[2]);return v&&f?parseFloat(m[1]+"."+m[2]):v||null}(),xn=gt&&Dn<5&&gi<537,an=/Firefox/i.test(We),Hi=/Edg/i.test(We),Kt=!Hi&&(/Chrome/i.test(We)||/CriOS/i.test(We)),on=function(){var m=We.match(/(Chrome|CriOS)\/(\d+)/);return m&&m[2]?parseFloat(m[2]):null}(),qt=function(){var m=/MSIE\s(\d+)\.\d/.exec(We),v=m&&parseFloat(m[1]);return!v&&/Trident\/7.0/i.test(We)&&/rv:11.0/.test(We)&&(v=11),v}(),Ct=/Safari/i.test(We)&&!Kt&&!gt&&!Hi,Wt=/Windows/i.test(We),ri=!!(ne()&&("ontouchstart"in T.default||T.default.navigator.maxTouchPoints||T.default.DocumentTouch&&T.default.document instanceof T.default.DocumentTouch)),It=/iPad/i.test(We)||Ct&&ri&&!/iPhone/i.test(We),Rt=/iPhone/i.test(We)&&!It,R=Rt||It||Ui,_=(Ct||R)&&!Kt,C=Object.freeze({__proto__:null,IS_IPOD:Ui,IOS_VERSION:kt,IS_ANDROID:gt,ANDROID_VERSION:Dn,IS_NATIVE_ANDROID:xn,IS_FIREFOX:an,IS_EDGE:Hi,IS_CHROME:Kt,CHROME_VERSION:on,IE_VERSION:qt,IS_SAFARI:Ct,IS_WINDOWS:Wt,TOUCH_ENABLED:ri,IS_IPAD:It,IS_IPHONE:Rt,IS_IOS:R,IS_ANY_SAFARI:_});function $(m){return typeof m=="string"&&!!m.trim()}function q(m){if(m.indexOf(" ")>=0)throw new Error("class has illegal whitespace characters")}function J(m){return new RegExp("(^|\\s)"+m+"($|\\s)")}function ne(){return b.default===T.default.document}function Oe(m){return ze(m)&&m.nodeType===1}function tt(){try{return T.default.parent!==T.default.self}catch{return!0}}function Xe(m){return function(v,f){if(!$(v))return b.default[m](null);$(f)&&(f=b.default.querySelector(f));var c=Oe(f)?f:b.default;return c[m]&&c[m](v)}}function Ie(m,v,f,c){m===void 0&&(m="div"),v===void 0&&(v={}),f===void 0&&(f={});var a=b.default.createElement(m);return Object.getOwnPropertyNames(v).forEach(function(l){var y=v[l];l.indexOf("aria-")!==-1||l==="role"||l==="type"?(ae.warn(`Setting attributes in the second argument of createEl()
has been deprecated. Use the third argument instead.
`+("createEl(type, properties, attributes). Attempting to set "+l+" to "+y+".")),a.setAttribute(l,y)):l==="textContent"?$e(a,y):(a[l]!==y||l==="tabIndex")&&(a[l]=y)}),Object.getOwnPropertyNames(f).forEach(function(l){a.setAttribute(l,f[l])}),c&&Xs(a,c),a}function $e(m,v){return typeof m.textContent>"u"?m.innerText=v:m.textContent=v,m}function Ws(m,v){v.firstChild?v.insertBefore(m,v.firstChild):v.appendChild(m)}function $i(m,v){return q(v),m.classList?m.classList.contains(v):J(v).test(m.className)}function ai(m,v){return m.classList?m.classList.add(v):$i(m,v)||(m.className=(m.className+" "+v).trim()),m}function On(m,v){return m?(m.classList?m.classList.remove(v):(q(v),m.className=m.className.split(/\s+/).filter(function(f){return f!==v}).join(" ")),m):(ae.warn("removeClass was called with an element that doesn't exist"),null)}function zs(m,v,f){var c=$i(m,v);if(typeof f=="function"&&(f=f(m,v)),typeof f!="boolean"&&(f=!c),f!==c)return f?ai(m,v):On(m,v),m}function Fr(m,v){Object.getOwnPropertyNames(v).forEach(function(f){var c=v[f];c===null||typeof c>"u"||c===!1?m.removeAttribute(f):m.setAttribute(f,c===!0?"":c)})}function zt(m){var v={},f=",autoplay,controls,playsinline,loop,muted,default,defaultMuted,";if(m&&m.attributes&&m.attributes.length>0)for(var c=m.attributes,a=c.length-1;a>=0;a--){var l=c[a].name,y=c[a].value;(typeof m[l]=="boolean"||f.indexOf(","+l+",")!==-1)&&(y=y!==null),v[l]=y}return v}function Nr(m,v){return m.getAttribute(v)}function ln(m,v,f){m.setAttribute(v,f)}function rs(m,v){m.removeAttribute(v)}function Br(){b.default.body.focus(),b.default.onselectstart=function(){return!1}}function Ur(){b.default.onselectstart=function(){return!0}}function un(m){if(m&&m.getBoundingClientRect&&m.parentNode){var v=m.getBoundingClientRect(),f={};return["bottom","height","left","right","top","width"].forEach(function(c){v[c]!==void 0&&(f[c]=v[c])}),f.height||(f.height=parseFloat(ot(m,"height"))),f.width||(f.width=parseFloat(ot(m,"width"))),f}}function mi(m){if(!m||m&&!m.offsetParent)return{left:0,top:0,width:0,height:0};for(var v=m.offsetWidth,f=m.offsetHeight,c=0,a=0;m.offsetParent&&m!==b.default[Z.fullscreenElement];)c+=m.offsetLeft,a+=m.offsetTop,m=m.offsetParent;return{left:c,top:a,width:v,height:f}}function Mn(m,v){var f={x:0,y:0};if(R)for(var c=m;c&&c.nodeName.toLowerCase()!=="html";){var a=ot(c,"transform");if(/^matrix/.test(a)){var l=a.slice(7,-1).split(/,\s/).map(Number);f.x+=l[4],f.y+=l[5]}else if(/^matrix3d/.test(a)){var y=a.slice(9,-1).split(/,\s/).map(Number);f.x+=y[12],f.y+=y[13]}c=c.parentNode}var S={},x=mi(v.target),U=mi(m),V=U.width,z=U.height,j=v.offsetY-(U.top-x.top),he=v.offsetX-(U.left-x.left);return v.changedTouches&&(he=v.changedTouches[0].pageX-U.left,j=v.changedTouches[0].pageY+U.top,R&&(he-=f.x,j-=f.y)),S.y=1-Math.max(0,Math.min(1,j/z)),S.x=Math.max(0,Math.min(1,he/V)),S}function Hr(m){return ze(m)&&m.nodeType===3}function Ys(m){for(;m.firstChild;)m.removeChild(m.firstChild);return m}function $r(m){return typeof m=="function"&&(m=m()),(Array.isArray(m)?m:[m]).map(function(v){if(typeof v=="function"&&(v=v()),Oe(v)||Hr(v))return v;if(typeof v=="string"&&/\S/.test(v))return b.default.createTextNode(v)}).filter(function(v){return v})}function Xs(m,v){return $r(v).forEach(function(f){return m.appendChild(f)}),m}function jr(m,v){return Xs(Ys(m),v)}function cn(m){return m.button===void 0&&m.buttons===void 0||m.button===0&&m.buttons===void 0||m.type==="mouseup"&&m.button===0&&m.buttons===0?!0:!(m.button!==0||m.buttons!==1)}var yi=Xe("querySelector"),Vr=Xe("querySelectorAll"),Gr=Object.freeze({__proto__:null,isReal:ne,isEl:Oe,isInFrame:tt,createEl:Ie,textContent:$e,prependTo:Ws,hasClass:$i,addClass:ai,removeClass:On,toggleClass:zs,setAttributes:Fr,getAttributes:zt,getAttribute:Nr,setAttribute:ln,removeAttribute:rs,blockTextSelection:Br,unblockTextSelection:Ur,getBoundingClientRect:un,findPosition:mi,getPointerPosition:Mn,isTextNode:Hr,emptyEl:Ys,normalizeContent:$r,appendContent:Xs,insertContent:jr,isSingleLeftClick:cn,$:yi,$$:Vr}),Kr=!1,Qs,qr=function(){if(Qs.options.autoSetup!==!1){var v=Array.prototype.slice.call(b.default.getElementsByTagName("video")),f=Array.prototype.slice.call(b.default.getElementsByTagName("audio")),c=Array.prototype.slice.call(b.default.getElementsByTagName("video-js")),a=v.concat(f,c);if(a&&a.length>0)for(var l=0,y=a.length;l<y;l++){var S=a[l];if(S&&S.getAttribute){if(S.player===void 0){var x=S.getAttribute("data-setup");x!==null&&Qs(S)}}else{Js(1);break}}else Kr||Js(1)}};function Js(m,v){ne()&&(v&&(Qs=v),T.default.setTimeout(qr,m))}function Zs(){Kr=!0,T.default.removeEventListener("load",Zs)}ne()&&(b.default.readyState==="complete"?Zs():T.default.addEventListener("load",Zs));var as=function(v){var f=b.default.createElement("style");return f.className=v,f},hn=function(v,f){v.styleSheet?v.styleSheet.cssText=f:v.textContent=f},Wr=3,er=Wr;function Yt(){return er++}var zr;T.default.WeakMap||(zr=function(){function m(){this.vdata="vdata"+Math.floor(T.default.performance&&T.default.performance.now()||Date.now()),this.data={}}var v=m.prototype;return v.set=function(c,a){var l=c[this.vdata]||Yt();return c[this.vdata]||(c[this.vdata]=l),this.data[l]=a,this},v.get=function(c){var a=c[this.vdata];if(a)return this.data[a];ae("We have no data for this element",c)},v.has=function(c){var a=c[this.vdata];return a in this.data},v.delete=function(c){var a=c[this.vdata];a&&(delete this.data[a],delete c[this.vdata])},m}());var wt=T.default.WeakMap?new WeakMap:new zr;function Yr(m,v){if(wt.has(m)){var f=wt.get(m);f.handlers[v].length===0&&(delete f.handlers[v],m.removeEventListener?m.removeEventListener(v,f.dispatcher,!1):m.detachEvent&&m.detachEvent("on"+v,f.dispatcher)),Object.getOwnPropertyNames(f.handlers).length<=0&&(delete f.handlers,delete f.dispatcher,delete f.disabled),Object.getOwnPropertyNames(f).length===0&&wt.delete(m)}}function os(m,v,f,c){f.forEach(function(a){m(v,a,c)})}function ls(m){if(m.fixed_)return m;function v(){return!0}function f(){return!1}if(!m||!m.isPropagationStopped||!m.isImmediatePropagationStopped){var c=m||T.default.event;m={};for(var a in c)a!=="layerX"&&a!=="layerY"&&a!=="keyLocation"&&a!=="webkitMovementX"&&a!=="webkitMovementY"&&a!=="path"&&(a==="returnValue"&&c.preventDefault||(m[a]=c[a]));if(m.target||(m.target=m.srcElement||b.default),m.relatedTarget||(m.relatedTarget=m.fromElement===m.target?m.toElement:m.fromElement),m.preventDefault=function(){c.preventDefault&&c.preventDefault(),m.returnValue=!1,c.returnValue=!1,m.defaultPrevented=!0},m.defaultPrevented=!1,m.stopPropagation=function(){c.stopPropagation&&c.stopPropagation(),m.cancelBubble=!0,c.cancelBubble=!0,m.isPropagationStopped=v},m.isPropagationStopped=f,m.stopImmediatePropagation=function(){c.stopImmediatePropagation&&c.stopImmediatePropagation(),m.isImmediatePropagationStopped=v,m.stopPropagation()},m.isImmediatePropagationStopped=f,m.clientX!==null&&m.clientX!==void 0){var l=b.default.documentElement,y=b.default.body;m.pageX=m.clientX+(l&&l.scrollLeft||y&&y.scrollLeft||0)-(l&&l.clientLeft||y&&y.clientLeft||0),m.pageY=m.clientY+(l&&l.scrollTop||y&&y.scrollTop||0)-(l&&l.clientTop||y&&y.clientTop||0)}m.which=m.charCode||m.keyCode,m.button!==null&&m.button!==void 0&&(m.button=m.button&1?0:m.button&4?1:m.button&2?2:0)}return m.fixed_=!0,m}var Fn,Nn=function(){if(typeof Fn!="boolean"){Fn=!1;try{var v=Object.defineProperty({},"passive",{get:function(){Fn=!0}});T.default.addEventListener("test",null,v),T.default.removeEventListener("test",null,v)}catch{}}return Fn},Bo=["touchstart","touchmove"];function Ot(m,v,f){if(Array.isArray(v))return os(Ot,m,v,f);wt.has(m)||wt.set(m,{});var c=wt.get(m);if(c.handlers||(c.handlers={}),c.handlers[v]||(c.handlers[v]=[]),f.guid||(f.guid=Yt()),c.handlers[v].push(f),c.dispatcher||(c.disabled=!1,c.dispatcher=function(l,y){if(!c.disabled){l=ls(l);var S=c.handlers[l.type];if(S)for(var x=S.slice(0),U=0,V=x.length;U<V&&!l.isImmediatePropagationStopped();U++)try{x[U].call(m,l,y)}catch(z){ae.error(z)}}}),c.handlers[v].length===1)if(m.addEventListener){var a=!1;Nn()&&Bo.indexOf(v)>-1&&(a={passive:!0}),m.addEventListener(v,c.dispatcher,a)}else m.attachEvent&&m.attachEvent("on"+v,c.dispatcher)}function bt(m,v,f){if(wt.has(m)){var c=wt.get(m);if(c.handlers){if(Array.isArray(v))return os(bt,m,v,f);var a=function(U,V){c.handlers[V]=[],Yr(U,V)};if(v===void 0){for(var l in c.handlers)Object.prototype.hasOwnProperty.call(c.handlers||{},l)&&a(m,l);return}var y=c.handlers[v];if(y){if(!f){a(m,v);return}if(f.guid)for(var S=0;S<y.length;S++)y[S].guid===f.guid&&y.splice(S--,1);Yr(m,v)}}}}function dn(m,v,f){var c=wt.has(m)?wt.get(m):{},a=m.parentNode||m.ownerDocument;if(typeof v=="string"?v={type:v,target:m}:v.target||(v.target=m),v=ls(v),c.dispatcher&&c.dispatcher.call(m,v,f),a&&!v.isPropagationStopped()&&v.bubbles===!0)dn.call(null,a,v,f);else if(!a&&!v.defaultPrevented&&v.target&&v.target[v.type]){wt.has(v.target)||wt.set(v.target,{});var l=wt.get(v.target);v.target[v.type]&&(l.disabled=!0,typeof v.target[v.type]=="function"&&v.target[v.type](),l.disabled=!1)}return!v.defaultPrevented}function us(m,v,f){if(Array.isArray(v))return os(us,m,v,f);var c=function a(){bt(m,v,a),f.apply(this,arguments)};c.guid=f.guid=f.guid||Yt(),Ot(m,v,c)}function Xr(m,v,f){var c=function a(){bt(m,v,a),f.apply(this,arguments)};c.guid=f.guid=f.guid||Yt(),Ot(m,v,c)}var Qr=Object.freeze({__proto__:null,fixEvent:ls,on:Ot,off:bt,trigger:dn,one:us,any:Xr}),Nt=30,it=function(v,f,c){f.guid||(f.guid=Yt());var a=f.bind(v);return a.guid=c?c+"_"+f.guid:f.guid,a},oi=function(v,f){var c=T.default.performance.now(),a=function(){var y=T.default.performance.now();y-c>=f&&(v.apply(void 0,arguments),c=y)};return a},_e=function(v,f,c,a){a===void 0&&(a=T.default);var l,y=function(){a.clearTimeout(l),l=null},S=function(){var U=this,V=arguments,z=function(){l=null,z=null,v.apply(U,V)};a.clearTimeout(l),l=a.setTimeout(z,f)};return S.cancel=y,S},F=function(){};F.prototype.allowedEvents_={},F.prototype.on=function(m,v){var f=this.addEventListener;this.addEventListener=function(){},Ot(this,m,v),this.addEventListener=f},F.prototype.addEventListener=F.prototype.on,F.prototype.off=function(m,v){bt(this,m,v)},F.prototype.removeEventListener=F.prototype.off,F.prototype.one=function(m,v){var f=this.addEventListener;this.addEventListener=function(){},us(this,m,v),this.addEventListener=f},F.prototype.any=function(m,v){var f=this.addEventListener;this.addEventListener=function(){},Xr(this,m,v),this.addEventListener=f},F.prototype.trigger=function(m){var v=m.type||m;typeof m=="string"&&(m={type:v}),m=ls(m),this.allowedEvents_[v]&&this["on"+v]&&this["on"+v](m),dn(this,m)},F.prototype.dispatchEvent=F.prototype.trigger;var me;F.prototype.queueTrigger=function(m){var v=this;me||(me=new Map);var f=m.type||m,c=me.get(this);c||(c=new Map,me.set(this,c));var a=c.get(f);c.delete(f),T.default.clearTimeout(a);var l=T.default.setTimeout(function(){c.delete(f),c.size===0&&(c=null,me.delete(v)),v.trigger(m)},0);c.set(f,l)};var De=function(v){return typeof v.name=="function"?v.name():typeof v.name=="string"?v.name:v.name_?v.name_:v.constructor&&v.constructor.name?v.constructor.name:typeof v},Me=function(v){return v instanceof F||!!v.eventBusEl_&&["on","one","off","trigger"].every(function(f){return typeof v[f]=="function"})},st=function(v,f){Me(v)?f():(v.eventedCallbacks||(v.eventedCallbacks=[]),v.eventedCallbacks.push(f))},Qe=function(v){return typeof v=="string"&&/\S/.test(v)||Array.isArray(v)&&!!v.length},li=function(v,f,c){if(!v||!v.nodeName&&!Me(v))throw new Error("Invalid target for "+De(f)+"#"+c+"; must be a DOM node or evented object.")},fn=function(v,f,c){if(!Qe(v))throw new Error("Invalid event type for "+De(f)+"#"+c+"; must be a non-empty string or array.")},Ge=function(v,f,c){if(typeof v!="function")throw new Error("Invalid listener for "+De(f)+"#"+c+"; must be a function.")},Bt=function(v,f,c){var a=f.length<3||f[0]===v||f[0]===v.eventBusEl_,l,y,S;return a?(l=v.eventBusEl_,f.length>=3&&f.shift(),y=f[0],S=f[1]):(l=f[0],y=f[1],S=f[2]),li(l,v,c),fn(y,v,c),Ge(S,v,c),S=it(v,S),{isTargetingSelf:a,target:l,type:y,listener:S}},Pt=function(v,f,c,a){li(v,v,f),v.nodeName?Qr[f](v,c,a):v[f](c,a)},tr={on:function(){for(var v=this,f=arguments.length,c=new Array(f),a=0;a<f;a++)c[a]=arguments[a];var l=Bt(this,c,"on"),y=l.isTargetingSelf,S=l.target,x=l.type,U=l.listener;if(Pt(S,"on",x,U),!y){var V=function(){return v.off(S,x,U)};V.guid=U.guid;var z=function(){return v.off("dispose",V)};z.guid=U.guid,Pt(this,"on","dispose",V),Pt(S,"on","dispose",z)}},one:function(){for(var v=this,f=arguments.length,c=new Array(f),a=0;a<f;a++)c[a]=arguments[a];var l=Bt(this,c,"one"),y=l.isTargetingSelf,S=l.target,x=l.type,U=l.listener;if(y)Pt(S,"one",x,U);else{var V=function z(){v.off(S,x,z);for(var j=arguments.length,he=new Array(j),we=0;we<j;we++)he[we]=arguments[we];U.apply(null,he)};V.guid=U.guid,Pt(S,"one",x,V)}},any:function(){for(var v=this,f=arguments.length,c=new Array(f),a=0;a<f;a++)c[a]=arguments[a];var l=Bt(this,c,"any"),y=l.isTargetingSelf,S=l.target,x=l.type,U=l.listener;if(y)Pt(S,"any",x,U);else{var V=function z(){v.off(S,x,z);for(var j=arguments.length,he=new Array(j),we=0;we<j;we++)he[we]=arguments[we];U.apply(null,he)};V.guid=U.guid,Pt(S,"any",x,V)}},off:function(v,f,c){if(!v||Qe(v))bt(this.eventBusEl_,v,f);else{var a=v,l=f;li(a,this,"off"),fn(l,this,"off"),Ge(c,this,"off"),c=it(this,c),this.off("dispose",c),a.nodeName?(bt(a,l,c),bt(a,"dispose",c)):Me(a)&&(a.off(l,c),a.off("dispose",c))}},trigger:function(v,f){li(this.eventBusEl_,this,"trigger");var c=v&&typeof v!="string"?v.type:v;if(!Qe(c)){var a="Invalid event type for "+De(this)+"#trigger; must be a non-empty string or object with a type key that has a non-empty value.";if(v)(this.log||ae).error(a);else throw new Error(a)}return dn(this.eventBusEl_,v,f)}};function ir(m,v){v===void 0&&(v={});var f=v,c=f.eventBusKey;if(c){if(!m[c].nodeName)throw new Error('The eventBusKey "'+c+'" does not refer to an element.');m.eventBusEl_=m[c]}else m.eventBusEl_=Ie("span",{className:"vjs-event-bus"});return Fe(m,tr),m.eventedCallbacks&&m.eventedCallbacks.forEach(function(a){a()}),m.on("dispose",function(){m.off(),[m,m.el_,m.eventBusEl_].forEach(function(a){a&&wt.has(a)&&wt.delete(a)}),T.default.setTimeout(function(){m.eventBusEl_=null},0)}),m}var my={state:{},setState:function(v){var f=this;typeof v=="function"&&(v=v());var c;return Ue(v,function(a,l){f.state[l]!==a&&(c=c||{},c[l]={from:f.state[l],to:a}),f.state[l]=a}),c&&Me(this)&&this.trigger({changes:c,type:"statechanged"}),c}};function rh(m,v){return Fe(m,my),m.state=Fe({},m.state,v),typeof m.handleStateChanged=="function"&&Me(m)&&m.on("statechanged",m.handleStateChanged),m}var Jr=function(v){return typeof v!="string"?v:v.replace(/./,function(f){return f.toLowerCase()})},dt=function(v){return typeof v!="string"?v:v.replace(/./,function(f){return f.toUpperCase()})},yy=function(v,f){return dt(v)===dt(f)};function lt(){for(var m={},v=arguments.length,f=new Array(v),c=0;c<v;c++)f[c]=arguments[c];return f.forEach(function(a){a&&Ue(a,function(l,y){if(!ut(l)){m[y]=l;return}ut(m[y])||(m[y]={}),m[y]=lt(m[y],l)})}),m}var vy=function(){function m(){this.map_={}}var v=m.prototype;return v.has=function(c){return c in this.map_},v.delete=function(c){var a=this.has(c);return delete this.map_[c],a},v.set=function(c,a){return this.map_[c]=a,this},v.forEach=function(c,a){for(var l in this.map_)c.call(a,this.map_[l],l,this)},m}(),Ty=T.default.Map?T.default.Map:vy,by=function(){function m(){this.set_={}}var v=m.prototype;return v.has=function(c){return c in this.set_},v.delete=function(c){var a=this.has(c);return delete this.set_[c],a},v.add=function(c){return this.set_[c]=1,this},v.forEach=function(c,a){for(var l in this.set_)c.call(a,l,l,this)},m}(),Uo=T.default.Set?T.default.Set:by,pe=function(){function m(f,c,a){var l=this;if(!f&&this.play?this.player_=f=this:this.player_=f,this.isDisposed_=!1,this.parentComponent_=null,this.options_=lt({},this.options_),c=this.options_=lt(this.options_,c),this.id_=c.id||c.el&&c.el.id,!this.id_){var y=f&&f.id&&f.id()||"no_player";this.id_=y+"_component_"+Yt()}this.name_=c.name||null,c.el?this.el_=c.el:c.createEl!==!1&&(this.el_=this.createEl()),c.className&&this.el_&&c.className.split(" ").forEach(function(S){return l.addClass(S)}),c.evented!==!1&&(ir(this,{eventBusKey:this.el_?"el_":null}),this.handleLanguagechange=this.handleLanguagechange.bind(this),this.on(this.player_,"languagechange",this.handleLanguagechange)),rh(this,this.constructor.defaultState),this.children_=[],this.childIndex_={},this.childNameIndex_={},this.setTimeoutIds_=new Uo,this.setIntervalIds_=new Uo,this.rafIds_=new Uo,this.namedRafs_=new Ty,this.clearingTimersOnDispose_=!1,c.initChildren!==!1&&this.initChildren(),this.ready(a),c.reportTouchActivity!==!1&&this.enableTouchActivity()}var v=m.prototype;return v.dispose=function(c){if(c===void 0&&(c={}),!this.isDisposed_){if(this.readyQueue_&&(this.readyQueue_.length=0),this.trigger({type:"dispose",bubbles:!1}),this.isDisposed_=!0,this.children_)for(var a=this.children_.length-1;a>=0;a--)this.children_[a].dispose&&this.children_[a].dispose();this.children_=null,this.childIndex_=null,this.childNameIndex_=null,this.parentComponent_=null,this.el_&&(this.el_.parentNode&&(c.restoreEl?this.el_.parentNode.replaceChild(c.restoreEl,this.el_):this.el_.parentNode.removeChild(this.el_)),this.el_=null),this.player_=null}},v.isDisposed=function(){return!!this.isDisposed_},v.player=function(){return this.player_},v.options=function(c){return c?(this.options_=lt(this.options_,c),this.options_):this.options_},v.el=function(){return this.el_},v.createEl=function(c,a,l){return Ie(c,a,l)},v.localize=function(c,a,l){l===void 0&&(l=c);var y=this.player_.language&&this.player_.language(),S=this.player_.languages&&this.player_.languages(),x=S&&S[y],U=y&&y.split("-")[0],V=S&&S[U],z=l;return x&&x[c]?z=x[c]:V&&V[c]&&(z=V[c]),a&&(z=z.replace(/\{(\d+)\}/g,function(j,he){var we=a[he-1],je=we;return typeof we>"u"&&(je=j),je})),z},v.handleLanguagechange=function(){},v.contentEl=function(){return this.contentEl_||this.el_},v.id=function(){return this.id_},v.name=function(){return this.name_},v.children=function(){return this.children_},v.getChildById=function(c){return this.childIndex_[c]},v.getChild=function(c){if(c)return this.childNameIndex_[c]},v.getDescendant=function(){for(var c=arguments.length,a=new Array(c),l=0;l<c;l++)a[l]=arguments[l];a=a.reduce(function(x,U){return x.concat(U)},[]);for(var y=this,S=0;S<a.length;S++)if(y=y.getChild(a[S]),!y||!y.getChild)return;return y},v.addChild=function(c,a,l){a===void 0&&(a={}),l===void 0&&(l=this.children_.length);var y,S;if(typeof c=="string"){S=dt(c);var x=a.componentClass||S;a.name=S;var U=m.getComponent(x);if(!U)throw new Error("Component "+x+" does not exist");if(typeof U!="function")return null;y=new U(this.player_||this,a)}else y=c;if(y.parentComponent_&&y.parentComponent_.removeChild(y),this.children_.splice(l,0,y),y.parentComponent_=this,typeof y.id=="function"&&(this.childIndex_[y.id()]=y),S=S||y.name&&dt(y.name()),S&&(this.childNameIndex_[S]=y,this.childNameIndex_[Jr(S)]=y),typeof y.el=="function"&&y.el()){var V=null;this.children_[l+1]&&(this.children_[l+1].el_?V=this.children_[l+1].el_:Oe(this.children_[l+1])&&(V=this.children_[l+1])),this.contentEl().insertBefore(y.el(),V)}return y},v.removeChild=function(c){if(typeof c=="string"&&(c=this.getChild(c)),!(!c||!this.children_)){for(var a=!1,l=this.children_.length-1;l>=0;l--)if(this.children_[l]===c){a=!0,this.children_.splice(l,1);break}if(a){c.parentComponent_=null,this.childIndex_[c.id()]=null,this.childNameIndex_[dt(c.name())]=null,this.childNameIndex_[Jr(c.name())]=null;var y=c.el();y&&y.parentNode===this.contentEl()&&this.contentEl().removeChild(c.el())}}},v.initChildren=function(){var c=this,a=this.options_.children;if(a){var l=this.options_,y=function(V){var z=V.name,j=V.opts;if(l[z]!==void 0&&(j=l[z]),j!==!1){j===!0&&(j={}),j.playerOptions=c.options_.playerOptions;var he=c.addChild(z,j);he&&(c[z]=he)}},S,x=m.getComponent("Tech");Array.isArray(a)?S=a:S=Object.keys(a),S.concat(Object.keys(this.options_).filter(function(U){return!S.some(function(V){return typeof V=="string"?U===V:U===V.name})})).map(function(U){var V,z;return typeof U=="string"?(V=U,z=a[V]||c.options_[V]||{}):(V=U.name,z=U),{name:V,opts:z}}).filter(function(U){var V=m.getComponent(U.opts.componentClass||dt(U.name));return V&&!x.isTech(V)}).forEach(y)}},v.buildCSSClass=function(){return""},v.ready=function(c,a){if(a===void 0&&(a=!1),!!c){if(!this.isReady_){this.readyQueue_=this.readyQueue_||[],this.readyQueue_.push(c);return}a?c.call(this):this.setTimeout(c,1)}},v.triggerReady=function(){this.isReady_=!0,this.setTimeout(function(){var c=this.readyQueue_;this.readyQueue_=[],c&&c.length>0&&c.forEach(function(a){a.call(this)},this),this.trigger("ready")},1)},v.$=function(c,a){return yi(c,a||this.contentEl())},v.$$=function(c,a){return Vr(c,a||this.contentEl())},v.hasClass=function(c){return $i(this.el_,c)},v.addClass=function(c){ai(this.el_,c)},v.removeClass=function(c){On(this.el_,c)},v.toggleClass=function(c,a){zs(this.el_,c,a)},v.show=function(){this.removeClass("vjs-hidden")},v.hide=function(){this.addClass("vjs-hidden")},v.lockShowing=function(){this.addClass("vjs-lock-showing")},v.unlockShowing=function(){this.removeClass("vjs-lock-showing")},v.getAttribute=function(c){return Nr(this.el_,c)},v.setAttribute=function(c,a){ln(this.el_,c,a)},v.removeAttribute=function(c){rs(this.el_,c)},v.width=function(c,a){return this.dimension("width",c,a)},v.height=function(c,a){return this.dimension("height",c,a)},v.dimensions=function(c,a){this.width(c,!0),this.height(a)},v.dimension=function(c,a,l){if(a!==void 0){(a===null||a!==a)&&(a=0),(""+a).indexOf("%")!==-1||(""+a).indexOf("px")!==-1?this.el_.style[c]=a:a==="auto"?this.el_.style[c]="":this.el_.style[c]=a+"px",l||this.trigger("componentresize");return}if(!this.el_)return 0;var y=this.el_.style[c],S=y.indexOf("px");return parseInt(S!==-1?y.slice(0,S):this.el_["offset"+dt(c)],10)},v.currentDimension=function(c){var a=0;if(c!=="width"&&c!=="height")throw new Error("currentDimension only accepts width or height value");if(a=ot(this.el_,c),a=parseFloat(a),a===0||isNaN(a)){var l="offset"+dt(c);a=this.el_[l]}return a},v.currentDimensions=function(){return{width:this.currentDimension("width"),height:this.currentDimension("height")}},v.currentWidth=function(){return this.currentDimension("width")},v.currentHeight=function(){return this.currentDimension("height")},v.focus=function(){this.el_.focus()},v.blur=function(){this.el_.blur()},v.handleKeyDown=function(c){this.player_&&(w.default.isEventKey(c,"Tab")||c.stopPropagation(),this.player_.handleKeyDown(c))},v.handleKeyPress=function(c){this.handleKeyDown(c)},v.emitTapEvents=function(){var c=0,a=null,l=10,y=200,S;this.on("touchstart",function(U){U.touches.length===1&&(a={pageX:U.touches[0].pageX,pageY:U.touches[0].pageY},c=T.default.performance.now(),S=!0)}),this.on("touchmove",function(U){if(U.touches.length>1)S=!1;else if(a){var V=U.touches[0].pageX-a.pageX,z=U.touches[0].pageY-a.pageY,j=Math.sqrt(V*V+z*z);j>l&&(S=!1)}});var x=function(){S=!1};this.on("touchleave",x),this.on("touchcancel",x),this.on("touchend",function(U){if(a=null,S===!0){var V=T.default.performance.now()-c;V<y&&(U.preventDefault(),this.trigger("tap"))}})},v.enableTouchActivity=function(){if(!(!this.player()||!this.player().reportUserActivity)){var c=it(this.player(),this.player().reportUserActivity),a;this.on("touchstart",function(){c(),this.clearInterval(a),a=this.setInterval(c,250)});var l=function(S){c(),this.clearInterval(a)};this.on("touchmove",c),this.on("touchend",l),this.on("touchcancel",l)}},v.setTimeout=function(c,a){var l=this,y;return c=it(this,c),this.clearTimersOnDispose_(),y=T.default.setTimeout(function(){l.setTimeoutIds_.has(y)&&l.setTimeoutIds_.delete(y),c()},a),this.setTimeoutIds_.add(y),y},v.clearTimeout=function(c){return this.setTimeoutIds_.has(c)&&(this.setTimeoutIds_.delete(c),T.default.clearTimeout(c)),c},v.setInterval=function(c,a){c=it(this,c),this.clearTimersOnDispose_();var l=T.default.setInterval(c,a);return this.setIntervalIds_.add(l),l},v.clearInterval=function(c){return this.setIntervalIds_.has(c)&&(this.setIntervalIds_.delete(c),T.default.clearInterval(c)),c},v.requestAnimationFrame=function(c){var a=this;if(!this.supportsRaf_)return this.setTimeout(c,1e3/60);this.clearTimersOnDispose_();var l;return c=it(this,c),l=T.default.requestAnimationFrame(function(){a.rafIds_.has(l)&&a.rafIds_.delete(l),c()}),this.rafIds_.add(l),l},v.requestNamedAnimationFrame=function(c,a){var l=this;if(!this.namedRafs_.has(c)){this.clearTimersOnDispose_(),a=it(this,a);var y=this.requestAnimationFrame(function(){a(),l.namedRafs_.has(c)&&l.namedRafs_.delete(c)});return this.namedRafs_.set(c,y),c}},v.cancelNamedAnimationFrame=function(c){this.namedRafs_.has(c)&&(this.cancelAnimationFrame(this.namedRafs_.get(c)),this.namedRafs_.delete(c))},v.cancelAnimationFrame=function(c){return this.supportsRaf_?(this.rafIds_.has(c)&&(this.rafIds_.delete(c),T.default.cancelAnimationFrame(c)),c):this.clearTimeout(c)},v.clearTimersOnDispose_=function(){var c=this;this.clearingTimersOnDispose_||(this.clearingTimersOnDispose_=!0,this.one("dispose",function(){[["namedRafs_","cancelNamedAnimationFrame"],["rafIds_","cancelAnimationFrame"],["setTimeoutIds_","clearTimeout"],["setIntervalIds_","clearInterval"]].forEach(function(a){var l=a[0],y=a[1];c[l].forEach(function(S,x){return c[y](x)})}),c.clearingTimersOnDispose_=!1}))},m.registerComponent=function(c,a){if(typeof c!="string"||!c)throw new Error('Illegal component name, "'+c+'"; must be a non-empty string.');var l=m.getComponent("Tech"),y=l&&l.isTech(a),S=m===a||m.prototype.isPrototypeOf(a.prototype);if(y||!S){var x;throw y?x="techs must be registered using Tech.registerTech()":x="must be a Component subclass",new Error('Illegal component, "'+c+'"; '+x+".")}c=dt(c),m.components_||(m.components_={});var U=m.getComponent("Player");if(c==="Player"&&U&&U.players){var V=U.players,z=Object.keys(V);if(V&&z.length>0&&z.map(function(j){return V[j]}).every(Boolean))throw new Error("Can not register Player component after player has been created.")}return m.components_[c]=a,m.components_[Jr(c)]=a,a},m.getComponent=function(c){if(!(!c||!m.components_))return m.components_[c]},m}();pe.prototype.supportsRaf_=typeof T.default.requestAnimationFrame=="function"&&typeof T.default.cancelAnimationFrame=="function",pe.registerComponent("Component",pe);function _y(m,v,f){if(typeof v!="number"||v<0||v>f)throw new Error("Failed to execute '"+m+"' on 'TimeRanges': The index provided ("+v+") is non-numeric or out of bounds (0-"+f+").")}function ah(m,v,f,c){return _y(m,c,f.length-1),f[c][v]}function Ho(m){var v;return m===void 0||m.length===0?v={length:0,start:function(){throw new Error("This TimeRanges object is empty")},end:function(){throw new Error("This TimeRanges object is empty")}}:v={length:m.length,start:ah.bind(null,"start",0,m),end:ah.bind(null,"end",1,m)},T.default.Symbol&&T.default.Symbol.iterator&&(v[T.default.Symbol.iterator]=function(){return(m||[]).values()}),v}function Bn(m,v){return Array.isArray(m)?Ho(m):m===void 0||v===void 0?Ho():Ho([[m,v]])}function oh(m,v){var f=0,c,a;if(!v)return 0;(!m||!m.length)&&(m=Bn(0,0));for(var l=0;l<m.length;l++)c=m.start(l),a=m.end(l),a>v&&(a=v),f+=a-c;return f/v}function Mt(m){if(m instanceof Mt)return m;typeof m=="number"?this.code=m:typeof m=="string"?this.message=m:ze(m)&&(typeof m.code=="number"&&(this.code=m.code),Fe(this,m)),this.message||(this.message=Mt.defaultMessages[this.code]||"")}Mt.prototype.code=0,Mt.prototype.message="",Mt.prototype.status=null,Mt.errorTypes=["MEDIA_ERR_CUSTOM","MEDIA_ERR_ABORTED","MEDIA_ERR_NETWORK","MEDIA_ERR_DECODE","MEDIA_ERR_SRC_NOT_SUPPORTED","MEDIA_ERR_ENCRYPTED"],Mt.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."};for(var cs=0;cs<Mt.errorTypes.length;cs++)Mt[Mt.errorTypes[cs]]=cs,Mt.prototype[Mt.errorTypes[cs]]=cs;function nr(m){return m!=null&&typeof m.then=="function"}function vi(m){nr(m)&&m.then(null,function(v){})}var $o=function(v){var f=["kind","label","language","id","inBandMetadataTrackDispatchType","mode","src"].reduce(function(c,a,l){return v[a]&&(c[a]=v[a]),c},{cues:v.cues&&Array.prototype.map.call(v.cues,function(c){return{startTime:c.startTime,endTime:c.endTime,text:c.text,id:c.id}})});return f},Ey=function(v){var f=v.$$("track"),c=Array.prototype.map.call(f,function(l){return l.track}),a=Array.prototype.map.call(f,function(l){var y=$o(l.track);return l.src&&(y.src=l.src),y});return a.concat(Array.prototype.filter.call(v.textTracks(),function(l){return c.indexOf(l)===-1}).map($o))},Sy=function(v,f){return v.forEach(function(c){var a=f.addRemoteTextTrack(c).track;!c.src&&c.cues&&c.cues.forEach(function(l){return a.addCue(l)})}),f.textTracks()},lh={textTracksToJson:Ey,jsonToTextTracks:Sy,trackToJson_:$o},jo="vjs-modal-dialog",hs=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.handleKeyDown_=function(y){return l.handleKeyDown(y)},l.close_=function(y){return l.close(y)},l.opened_=l.hasBeenOpened_=l.hasBeenFilled_=!1,l.closeable(!l.options_.uncloseable),l.content(l.options_.content),l.contentEl_=Ie("div",{className:jo+"-content"},{role:"document"}),l.descEl_=Ie("p",{className:jo+"-description vjs-control-text",id:l.el().getAttribute("aria-describedby")}),$e(l.descEl_,l.description()),l.el_.appendChild(l.descEl_),l.el_.appendChild(l.contentEl_),l}var f=v.prototype;return f.createEl=function(){return m.prototype.createEl.call(this,"div",{className:this.buildCSSClass(),tabIndex:-1},{"aria-describedby":this.id()+"_description","aria-hidden":"true","aria-label":this.label(),role:"dialog"})},f.dispose=function(){this.contentEl_=null,this.descEl_=null,this.previouslyActiveEl_=null,m.prototype.dispose.call(this)},f.buildCSSClass=function(){return jo+" vjs-hidden "+m.prototype.buildCSSClass.call(this)},f.label=function(){return this.localize(this.options_.label||"Modal Window")},f.description=function(){var a=this.options_.description||this.localize("This is a modal window.");return this.closeable()&&(a+=" "+this.localize("This modal can be closed by pressing the Escape key or activating the close button.")),a},f.open=function(){if(!this.opened_){var a=this.player();this.trigger("beforemodalopen"),this.opened_=!0,(this.options_.fillAlways||!this.hasBeenOpened_&&!this.hasBeenFilled_)&&this.fill(),this.wasPlaying_=!a.paused(),this.options_.pauseOnOpen&&this.wasPlaying_&&a.pause(),this.on("keydown",this.handleKeyDown_),this.hadControls_=a.controls(),a.controls(!1),this.show(),this.conditionalFocus_(),this.el().setAttribute("aria-hidden","false"),this.trigger("modalopen"),this.hasBeenOpened_=!0}},f.opened=function(a){return typeof a=="boolean"&&this[a?"open":"close"](),this.opened_},f.close=function(){if(this.opened_){var a=this.player();this.trigger("beforemodalclose"),this.opened_=!1,this.wasPlaying_&&this.options_.pauseOnOpen&&a.play(),this.off("keydown",this.handleKeyDown_),this.hadControls_&&a.controls(!0),this.hide(),this.el().setAttribute("aria-hidden","true"),this.trigger("modalclose"),this.conditionalBlur_(),this.options_.temporary&&this.dispose()}},f.closeable=function(a){if(typeof a=="boolean"){var l=this.closeable_=!!a,y=this.getChild("closeButton");if(l&&!y){var S=this.contentEl_;this.contentEl_=this.el_,y=this.addChild("closeButton",{controlText:"Close Modal Dialog"}),this.contentEl_=S,this.on(y,"close",this.close_)}!l&&y&&(this.off(y,"close",this.close_),this.removeChild(y),y.dispose())}return this.closeable_},f.fill=function(){this.fillWith(this.content())},f.fillWith=function(a){var l=this.contentEl(),y=l.parentNode,S=l.nextSibling;this.trigger("beforemodalfill"),this.hasBeenFilled_=!0,y.removeChild(l),this.empty(),jr(l,a),this.trigger("modalfill"),S?y.insertBefore(l,S):y.appendChild(l);var x=this.getChild("closeButton");x&&y.appendChild(x.el_)},f.empty=function(){this.trigger("beforemodalempty"),Ys(this.contentEl()),this.trigger("modalempty")},f.content=function(a){return typeof a<"u"&&(this.content_=a),this.content_},f.conditionalFocus_=function(){var a=b.default.activeElement,l=this.player_.el_;this.previouslyActiveEl_=null,(l.contains(a)||l===a)&&(this.previouslyActiveEl_=a,this.focus())},f.conditionalBlur_=function(){this.previouslyActiveEl_&&(this.previouslyActiveEl_.focus(),this.previouslyActiveEl_=null)},f.handleKeyDown=function(a){if(a.stopPropagation(),w.default.isEventKey(a,"Escape")&&this.closeable()){a.preventDefault(),this.close();return}if(w.default.isEventKey(a,"Tab")){for(var l=this.focusableEls_(),y=this.el_.querySelector(":focus"),S,x=0;x<l.length;x++)if(y===l[x]){S=x;break}b.default.activeElement===this.el_&&(S=0),a.shiftKey&&S===0?(l[l.length-1].focus(),a.preventDefault()):!a.shiftKey&&S===l.length-1&&(l[0].focus(),a.preventDefault())}},f.focusableEls_=function(){var a=this.el_.querySelectorAll("*");return Array.prototype.filter.call(a,function(l){return(l instanceof T.default.HTMLAnchorElement||l instanceof T.default.HTMLAreaElement)&&l.hasAttribute("href")||(l instanceof T.default.HTMLInputElement||l instanceof T.default.HTMLSelectElement||l instanceof T.default.HTMLTextAreaElement||l instanceof T.default.HTMLButtonElement)&&!l.hasAttribute("disabled")||l instanceof T.default.HTMLIFrameElement||l instanceof T.default.HTMLObjectElement||l instanceof T.default.HTMLEmbedElement||l.hasAttribute("tabindex")&&l.getAttribute("tabindex")!==-1||l.hasAttribute("contenteditable")})},v}(pe);hs.prototype.options_={pauseOnOpen:!0,temporary:!0},pe.registerComponent("ModalDialog",hs);var ds=function(m){L.default(v,m);function v(c){var a;c===void 0&&(c=[]),a=m.call(this)||this,a.tracks_=[],Object.defineProperty(A.default(a),"length",{get:function(){return this.tracks_.length}});for(var l=0;l<c.length;l++)a.addTrack(c[l]);return a}var f=v.prototype;return f.addTrack=function(a){var l=this,y=this.tracks_.length;""+y in this||Object.defineProperty(this,y,{get:function(){return this.tracks_[y]}}),this.tracks_.indexOf(a)===-1&&(this.tracks_.push(a),this.trigger({track:a,type:"addtrack",target:this})),a.labelchange_=function(){l.trigger({track:a,type:"labelchange",target:l})},Me(a)&&a.addEventListener("labelchange",a.labelchange_)},f.removeTrack=function(a){for(var l,y=0,S=this.length;y<S;y++)if(this[y]===a){l=this[y],l.off&&l.off(),this.tracks_.splice(y,1);break}l&&this.trigger({track:l,type:"removetrack",target:this})},f.getTrackById=function(a){for(var l=null,y=0,S=this.length;y<S;y++){var x=this[y];if(x.id===a){l=x;break}}return l},v}(F);ds.prototype.allowedEvents_={change:"change",addtrack:"addtrack",removetrack:"removetrack",labelchange:"labelchange"};for(var Cy in ds.prototype.allowedEvents_)ds.prototype["on"+Cy]=null;var Vo=function(v,f){for(var c=0;c<v.length;c++)!Object.keys(v[c]).length||f.id===v[c].id||(v[c].enabled=!1)},wy=function(m){L.default(v,m);function v(c){var a;c===void 0&&(c=[]);for(var l=c.length-1;l>=0;l--)if(c[l].enabled){Vo(c,c[l]);break}return a=m.call(this,c)||this,a.changing_=!1,a}var f=v.prototype;return f.addTrack=function(a){var l=this;a.enabled&&Vo(this,a),m.prototype.addTrack.call(this,a),a.addEventListener&&(a.enabledChange_=function(){l.changing_||(l.changing_=!0,Vo(l,a),l.changing_=!1,l.trigger("change"))},a.addEventListener("enabledchange",a.enabledChange_))},f.removeTrack=function(a){m.prototype.removeTrack.call(this,a),a.removeEventListener&&a.enabledChange_&&(a.removeEventListener("enabledchange",a.enabledChange_),a.enabledChange_=null)},v}(ds),Go=function(v,f){for(var c=0;c<v.length;c++)!Object.keys(v[c]).length||f.id===v[c].id||(v[c].selected=!1)},Ay=function(m){L.default(v,m);function v(c){var a;c===void 0&&(c=[]);for(var l=c.length-1;l>=0;l--)if(c[l].selected){Go(c,c[l]);break}return a=m.call(this,c)||this,a.changing_=!1,Object.defineProperty(A.default(a),"selectedIndex",{get:function(){for(var S=0;S<this.length;S++)if(this[S].selected)return S;return-1},set:function(){}}),a}var f=v.prototype;return f.addTrack=function(a){var l=this;a.selected&&Go(this,a),m.prototype.addTrack.call(this,a),a.addEventListener&&(a.selectedChange_=function(){l.changing_||(l.changing_=!0,Go(l,a),l.changing_=!1,l.trigger("change"))},a.addEventListener("selectedchange",a.selectedChange_))},f.removeTrack=function(a){m.prototype.removeTrack.call(this,a),a.removeEventListener&&a.selectedChange_&&(a.removeEventListener("selectedchange",a.selectedChange_),a.selectedChange_=null)},v}(ds),uh=function(m){L.default(v,m);function v(){return m.apply(this,arguments)||this}var f=v.prototype;return f.addTrack=function(a){var l=this;m.prototype.addTrack.call(this,a),this.queueChange_||(this.queueChange_=function(){return l.queueTrigger("change")}),this.triggerSelectedlanguagechange||(this.triggerSelectedlanguagechange_=function(){return l.trigger("selectedlanguagechange")}),a.addEventListener("modechange",this.queueChange_);var y=["metadata","chapters"];y.indexOf(a.kind)===-1&&a.addEventListener("modechange",this.triggerSelectedlanguagechange_)},f.removeTrack=function(a){m.prototype.removeTrack.call(this,a),a.removeEventListener&&(this.queueChange_&&a.removeEventListener("modechange",this.queueChange_),this.selectedlanguagechange_&&a.removeEventListener("modechange",this.triggerSelectedlanguagechange_))},v}(ds),Ly=function(){function m(f){f===void 0&&(f=[]),this.trackElements_=[],Object.defineProperty(this,"length",{get:function(){return this.trackElements_.length}});for(var c=0,a=f.length;c<a;c++)this.addTrackElement_(f[c])}var v=m.prototype;return v.addTrackElement_=function(c){var a=this.trackElements_.length;""+a in this||Object.defineProperty(this,a,{get:function(){return this.trackElements_[a]}}),this.trackElements_.indexOf(c)===-1&&this.trackElements_.push(c)},v.getTrackElementByTrack_=function(c){for(var a,l=0,y=this.trackElements_.length;l<y;l++)if(c===this.trackElements_[l].track){a=this.trackElements_[l];break}return a},v.removeTrackElement_=function(c){for(var a=0,l=this.trackElements_.length;a<l;a++)if(c===this.trackElements_[a]){this.trackElements_[a].track&&typeof this.trackElements_[a].track.off=="function"&&this.trackElements_[a].track.off(),typeof this.trackElements_[a].off=="function"&&this.trackElements_[a].off(),this.trackElements_.splice(a,1);break}},m}(),ch=function(){function m(f){m.prototype.setCues_.call(this,f),Object.defineProperty(this,"length",{get:function(){return this.length_}})}var v=m.prototype;return v.setCues_=function(c){var a=this.length||0,l=0,y=c.length;this.cues_=c,this.length_=c.length;var S=function(U){""+U in this||Object.defineProperty(this,""+U,{get:function(){return this.cues_[U]}})};if(a<y)for(l=a;l<y;l++)S.call(this,l)},v.getCueById=function(c){for(var a=null,l=0,y=this.length;l<y;l++){var S=this[l];if(S.id===c){a=S;break}}return a},m}(),ky={alternative:"alternative",captions:"captions",main:"main",sign:"sign",subtitles:"subtitles",commentary:"commentary"},Iy={alternative:"alternative",descriptions:"descriptions",main:"main","main-desc":"main-desc",translation:"translation",commentary:"commentary"},Ry={subtitles:"subtitles",captions:"captions",descriptions:"descriptions",chapters:"chapters",metadata:"metadata"},hh={disabled:"disabled",hidden:"hidden",showing:"showing"},Ko=function(m){L.default(v,m);function v(f){var c;f===void 0&&(f={}),c=m.call(this)||this;var a={id:f.id||"vjs_track_"+Yt(),kind:f.kind||"",language:f.language||""},l=f.label||"",y=function(U){Object.defineProperty(A.default(c),U,{get:function(){return a[U]},set:function(){}})};for(var S in a)y(S);return Object.defineProperty(A.default(c),"label",{get:function(){return l},set:function(U){U!==l&&(l=U,this.trigger("labelchange"))}}),c}return v}(F),qo=function(v){var f=["protocol","hostname","port","pathname","search","hash","host"],c=b.default.createElement("a");c.href=v;for(var a={},l=0;l<f.length;l++)a[f[l]]=c[f[l]];return a.protocol==="http:"&&(a.host=a.host.replace(/:80$/,"")),a.protocol==="https:"&&(a.host=a.host.replace(/:443$/,"")),a.protocol||(a.protocol=T.default.location.protocol),a.host||(a.host=T.default.location.host),a},dh=function(v){if(!v.match(/^https?:\/\//)){var f=b.default.createElement("a");f.href=v,v=f.href}return v},Wo=function(v){if(typeof v=="string"){var f=/^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/,c=f.exec(v);if(c)return c.pop().toLowerCase()}return""},Zr=function(v,f){f===void 0&&(f=T.default.location);var c=qo(v),a=c.protocol===":"?f.protocol:c.protocol,l=a+c.host!==f.protocol+f.host;return l},Py=Object.freeze({__proto__:null,parseUrl:qo,getAbsoluteURL:dh,getFileExtension:Wo,isCrossOrigin:Zr}),fh=function(v,f){var c=new T.default.WebVTT.Parser(T.default,T.default.vttjs,T.default.WebVTT.StringDecoder()),a=[];c.oncue=function(l){f.addCue(l)},c.onparsingerror=function(l){a.push(l)},c.onflush=function(){f.trigger({type:"loadeddata",target:f})},c.parse(v),a.length>0&&(T.default.console&&T.default.console.groupCollapsed&&T.default.console.groupCollapsed("Text Track parsing errors for "+f.src),a.forEach(function(l){return ae.error(l)}),T.default.console&&T.default.console.groupEnd&&T.default.console.groupEnd()),c.flush()},ph=function(v,f){var c={uri:v},a=Zr(v);a&&(c.cors=a);var l=f.tech_.crossOrigin()==="use-credentials";l&&(c.withCredentials=l),M.default(c,it(this,function(y,S,x){if(y)return ae.error(y,S);f.loaded_=!0,typeof T.default.WebVTT!="function"?f.tech_&&f.tech_.any(["vttjsloaded","vttjserror"],function(U){if(U.type==="vttjserror"){ae.error("vttjs failed to load, stopping trying to process "+f.src);return}return fh(x,f)}):fh(x,f)}))},sr=function(m){L.default(v,m);function v(c){var a;if(c===void 0&&(c={}),!c.tech)throw new Error("A tech was not provided.");var l=lt(c,{kind:Ry[c.kind]||"subtitles",language:c.language||c.srclang||""}),y=hh[l.mode]||"disabled",S=l.default;(l.kind==="metadata"||l.kind==="chapters")&&(y="hidden"),a=m.call(this,l)||this,a.tech_=l.tech,a.cues_=[],a.activeCues_=[],a.preload_=a.tech_.preloadTextTracks!==!1;var x=new ch(a.cues_),U=new ch(a.activeCues_),V=!1;a.timeupdateHandler=it(A.default(a),function(j){if(j===void 0&&(j={}),!this.tech_.isDisposed()){if(!this.tech_.isReady_){j.type!=="timeupdate"&&(this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler));return}this.activeCues=this.activeCues,V&&(this.trigger("cuechange"),V=!1),j.type!=="timeupdate"&&(this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler))}});var z=function(){a.stopTracking()};return a.tech_.one("dispose",z),y!=="disabled"&&a.startTracking(),Object.defineProperties(A.default(a),{default:{get:function(){return S},set:function(){}},mode:{get:function(){return y},set:function(he){hh[he]&&y!==he&&(y=he,!this.preload_&&y!=="disabled"&&this.cues.length===0&&ph(this.src,this),this.stopTracking(),y!=="disabled"&&this.startTracking(),this.trigger("modechange"))}},cues:{get:function(){return this.loaded_?x:null},set:function(){}},activeCues:{get:function(){if(!this.loaded_)return null;if(this.cues.length===0)return U;for(var he=this.tech_.currentTime(),we=[],je=0,jn=this.cues.length;je<jn;je++){var bi=this.cues[je];(bi.startTime<=he&&bi.endTime>=he||bi.startTime===bi.endTime&&bi.startTime<=he&&bi.startTime+.5>=he)&&we.push(bi)}if(V=!1,we.length!==this.activeCues_.length)V=!0;else for(var Sl=0;Sl<we.length;Sl++)this.activeCues_.indexOf(we[Sl])===-1&&(V=!0);return this.activeCues_=we,U.setCues_(this.activeCues_),U},set:function(){}}}),l.src?(a.src=l.src,a.preload_||(a.loaded_=!0),(a.preload_||l.kind!=="subtitles"&&l.kind!=="captions")&&ph(a.src,A.default(a))):a.loaded_=!0,a}var f=v.prototype;return f.startTracking=function(){this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler),this.tech_.on("timeupdate",this.timeupdateHandler)},f.stopTracking=function(){this.rvf_&&(this.tech_.cancelVideoFrameCallback(this.rvf_),this.rvf_=void 0),this.tech_.off("timeupdate",this.timeupdateHandler)},f.addCue=function(a){var l=a;if(l.constructor&&l.constructor.name!=="VTTCue"){l=new T.default.vttjs.VTTCue(a.startTime,a.endTime,a.text);for(var y in a)y in l||(l[y]=a[y]);l.id=a.id,l.originalCue_=a}for(var S=this.tech_.textTracks(),x=0;x<S.length;x++)S[x]!==this&&S[x].removeCue(l);this.cues_.push(l),this.cues.setCues_(this.cues_)},f.removeCue=function(a){for(var l=this.cues_.length;l--;){var y=this.cues_[l];if(y===a||y.originalCue_&&y.originalCue_===a){this.cues_.splice(l,1),this.cues.setCues_(this.cues_);break}}},v}(Ko);sr.prototype.allowedEvents_={cuechange:"cuechange"};var gh=function(m){L.default(v,m);function v(f){var c;f===void 0&&(f={});var a=lt(f,{kind:Iy[f.kind]||""});c=m.call(this,a)||this;var l=!1;return Object.defineProperty(A.default(c),"enabled",{get:function(){return l},set:function(S){typeof S!="boolean"||S===l||(l=S,this.trigger("enabledchange"))}}),a.enabled&&(c.enabled=a.enabled),c.loaded_=!0,c}return v}(Ko),mh=function(m){L.default(v,m);function v(f){var c;f===void 0&&(f={});var a=lt(f,{kind:ky[f.kind]||""});c=m.call(this,a)||this;var l=!1;return Object.defineProperty(A.default(c),"selected",{get:function(){return l},set:function(S){typeof S!="boolean"||S===l||(l=S,this.trigger("selectedchange"))}}),a.selected&&(c.selected=a.selected),c}return v}(Ko),yh=0,Dy=1,vh=2,xy=3,fs=function(m){L.default(v,m);function v(f){var c;f===void 0&&(f={}),c=m.call(this)||this;var a,l=new sr(f);return c.kind=l.kind,c.src=l.src,c.srclang=l.language,c.label=l.label,c.default=l.default,Object.defineProperties(A.default(c),{readyState:{get:function(){return a}},track:{get:function(){return l}}}),a=yh,l.addEventListener("loadeddata",function(){a=vh,c.trigger({type:"load",target:A.default(c)})}),c}return v}(F);fs.prototype.allowedEvents_={load:"load"},fs.NONE=yh,fs.LOADING=Dy,fs.LOADED=vh,fs.ERROR=xy;var Xt={audio:{ListClass:wy,TrackClass:gh,capitalName:"Audio"},video:{ListClass:Ay,TrackClass:mh,capitalName:"Video"},text:{ListClass:uh,TrackClass:sr,capitalName:"Text"}};Object.keys(Xt).forEach(function(m){Xt[m].getterName=m+"Tracks",Xt[m].privateName=m+"Tracks_"});var ps={remoteText:{ListClass:uh,TrackClass:sr,capitalName:"RemoteText",getterName:"remoteTextTracks",privateName:"remoteTextTracks_"},remoteTextEl:{ListClass:Ly,TrackClass:fs,capitalName:"RemoteTextTrackEls",getterName:"remoteTextTrackEls",privateName:"remoteTextTrackEls_"}},Ft=E.default({},Xt,ps);ps.names=Object.keys(ps),Xt.names=Object.keys(Xt),Ft.names=[].concat(ps.names).concat(Xt.names);function Oy(m,v,f,c,a){a===void 0&&(a={});var l=m.textTracks();a.kind=v,f&&(a.label=f),c&&(a.language=c),a.tech=m;var y=new Ft.text.TrackClass(a);return l.addTrack(y),y}var nt=function(m){L.default(v,m);function v(c,a){var l;return c===void 0&&(c={}),a===void 0&&(a=function(){}),c.reportTouchActivity=!1,l=m.call(this,null,c,a)||this,l.onDurationChange_=function(y){return l.onDurationChange(y)},l.trackProgress_=function(y){return l.trackProgress(y)},l.trackCurrentTime_=function(y){return l.trackCurrentTime(y)},l.stopTrackingCurrentTime_=function(y){return l.stopTrackingCurrentTime(y)},l.disposeSourceHandler_=function(y){return l.disposeSourceHandler(y)},l.queuedHanders_=new Set,l.hasStarted_=!1,l.on("playing",function(){this.hasStarted_=!0}),l.on("loadstart",function(){this.hasStarted_=!1}),Ft.names.forEach(function(y){var S=Ft[y];c&&c[S.getterName]&&(l[S.privateName]=c[S.getterName])}),l.featuresProgressEvents||l.manualProgressOn(),l.featuresTimeupdateEvents||l.manualTimeUpdatesOn(),["Text","Audio","Video"].forEach(function(y){c["native"+y+"Tracks"]===!1&&(l["featuresNative"+y+"Tracks"]=!1)}),c.nativeCaptions===!1||c.nativeTextTracks===!1?l.featuresNativeTextTracks=!1:(c.nativeCaptions===!0||c.nativeTextTracks===!0)&&(l.featuresNativeTextTracks=!0),l.featuresNativeTextTracks||l.emulateTextTracks(),l.preloadTextTracks=c.preloadTextTracks!==!1,l.autoRemoteTextTracks_=new Ft.text.ListClass,l.initTrackListeners(),c.nativeControlsForTouch||l.emitTapEvents(),l.constructor&&(l.name_=l.constructor.name||"Unknown Tech"),l}var f=v.prototype;return f.triggerSourceset=function(a){var l=this;this.isReady_||this.one("ready",function(){return l.setTimeout(function(){return l.triggerSourceset(a)},1)}),this.trigger({src:a,type:"sourceset"})},f.manualProgressOn=function(){this.on("durationchange",this.onDurationChange_),this.manualProgress=!0,this.one("ready",this.trackProgress_)},f.manualProgressOff=function(){this.manualProgress=!1,this.stopTrackingProgress(),this.off("durationchange",this.onDurationChange_)},f.trackProgress=function(a){this.stopTrackingProgress(),this.progressInterval=this.setInterval(it(this,function(){var l=this.bufferedPercent();this.bufferedPercent_!==l&&this.trigger("progress"),this.bufferedPercent_=l,l===1&&this.stopTrackingProgress()}),500)},f.onDurationChange=function(a){this.duration_=this.duration()},f.buffered=function(){return Bn(0,0)},f.bufferedPercent=function(){return oh(this.buffered(),this.duration_)},f.stopTrackingProgress=function(){this.clearInterval(this.progressInterval)},f.manualTimeUpdatesOn=function(){this.manualTimeUpdates=!0,this.on("play",this.trackCurrentTime_),this.on("pause",this.stopTrackingCurrentTime_)},f.manualTimeUpdatesOff=function(){this.manualTimeUpdates=!1,this.stopTrackingCurrentTime(),this.off("play",this.trackCurrentTime_),this.off("pause",this.stopTrackingCurrentTime_)},f.trackCurrentTime=function(){this.currentTimeInterval&&this.stopTrackingCurrentTime(),this.currentTimeInterval=this.setInterval(function(){this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})},250)},f.stopTrackingCurrentTime=function(){this.clearInterval(this.currentTimeInterval),this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})},f.dispose=function(){this.clearTracks(Xt.names),this.manualProgress&&this.manualProgressOff(),this.manualTimeUpdates&&this.manualTimeUpdatesOff(),m.prototype.dispose.call(this)},f.clearTracks=function(a){var l=this;a=[].concat(a),a.forEach(function(y){for(var S=l[y+"Tracks"]()||[],x=S.length;x--;){var U=S[x];y==="text"&&l.removeRemoteTextTrack(U),S.removeTrack(U)}})},f.cleanupAutoTextTracks=function(){for(var a=this.autoRemoteTextTracks_||[],l=a.length;l--;){var y=a[l];this.removeRemoteTextTrack(y)}},f.reset=function(){},f.crossOrigin=function(){},f.setCrossOrigin=function(){},f.error=function(a){return a!==void 0&&(this.error_=new Mt(a),this.trigger("error")),this.error_},f.played=function(){return this.hasStarted_?Bn(0,0):Bn()},f.play=function(){},f.setScrubbing=function(){},f.scrubbing=function(){},f.setCurrentTime=function(){this.manualTimeUpdates&&this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})},f.initTrackListeners=function(){var a=this;Xt.names.forEach(function(l){var y=Xt[l],S=function(){a.trigger(l+"trackchange")},x=a[y.getterName]();x.addEventListener("removetrack",S),x.addEventListener("addtrack",S),a.on("dispose",function(){x.removeEventListener("removetrack",S),x.removeEventListener("addtrack",S)})})},f.addWebVttScript_=function(){var a=this;if(!T.default.WebVTT)if(b.default.body.contains(this.el())){if(!this.options_["vtt.js"]&&ut(O.default)&&Object.keys(O.default).length>0){this.trigger("vttjsloaded");return}var l=b.default.createElement("script");l.src=this.options_["vtt.js"]||"https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js",l.onload=function(){a.trigger("vttjsloaded")},l.onerror=function(){a.trigger("vttjserror")},this.on("dispose",function(){l.onload=null,l.onerror=null}),T.default.WebVTT=!0,this.el().parentNode.appendChild(l)}else this.ready(this.addWebVttScript_)},f.emulateTextTracks=function(){var a=this,l=this.textTracks(),y=this.remoteTextTracks(),S=function(j){return l.addTrack(j.track)},x=function(j){return l.removeTrack(j.track)};y.on("addtrack",S),y.on("removetrack",x),this.addWebVttScript_();var U=function(){return a.trigger("texttrackchange")},V=function(){U();for(var j=0;j<l.length;j++){var he=l[j];he.removeEventListener("cuechange",U),he.mode==="showing"&&he.addEventListener("cuechange",U)}};V(),l.addEventListener("change",V),l.addEventListener("addtrack",V),l.addEventListener("removetrack",V),this.on("dispose",function(){y.off("addtrack",S),y.off("removetrack",x),l.removeEventListener("change",V),l.removeEventListener("addtrack",V),l.removeEventListener("removetrack",V);for(var z=0;z<l.length;z++){var j=l[z];j.removeEventListener("cuechange",U)}})},f.addTextTrack=function(a,l,y){if(!a)throw new Error("TextTrack kind is required but was not provided");return Oy(this,a,l,y)},f.createRemoteTextTrack=function(a){var l=lt(a,{tech:this});return new ps.remoteTextEl.TrackClass(l)},f.addRemoteTextTrack=function(a,l){var y=this;a===void 0&&(a={});var S=this.createRemoteTextTrack(a);return l!==!0&&l!==!1&&(ae.warn('Calling addRemoteTextTrack without explicitly setting the "manualCleanup" parameter to `true` is deprecated and default to `false` in future version of video.js'),l=!0),this.remoteTextTrackEls().addTrackElement_(S),this.remoteTextTracks().addTrack(S.track),l!==!0&&this.ready(function(){return y.autoRemoteTextTracks_.addTrack(S.track)}),S},f.removeRemoteTextTrack=function(a){var l=this.remoteTextTrackEls().getTrackElementByTrack_(a);this.remoteTextTrackEls().removeTrackElement_(l),this.remoteTextTracks().removeTrack(a),this.autoRemoteTextTracks_.removeTrack(a)},f.getVideoPlaybackQuality=function(){return{}},f.requestPictureInPicture=function(){var a=this.options_.Promise||T.default.Promise;if(a)return a.reject()},f.disablePictureInPicture=function(){return!0},f.setDisablePictureInPicture=function(){},f.requestVideoFrameCallback=function(a){var l=this,y=Yt();return!this.isReady_||this.paused()?(this.queuedHanders_.add(y),this.one("playing",function(){l.queuedHanders_.has(y)&&(l.queuedHanders_.delete(y),a())})):this.requestNamedAnimationFrame(y,a),y},f.cancelVideoFrameCallback=function(a){this.queuedHanders_.has(a)?this.queuedHanders_.delete(a):this.cancelNamedAnimationFrame(a)},f.setPoster=function(){},f.playsinline=function(){},f.setPlaysinline=function(){},f.overrideNativeAudioTracks=function(){},f.overrideNativeVideoTracks=function(){},f.canPlayType=function(){return""},v.canPlayType=function(){return""},v.canPlaySource=function(a,l){return v.canPlayType(a.type)},v.isTech=function(a){return a.prototype instanceof v||a instanceof v||a===v},v.registerTech=function(a,l){if(v.techs_||(v.techs_={}),!v.isTech(l))throw new Error("Tech "+a+" must be a Tech");if(!v.canPlayType)throw new Error("Techs must have a static canPlayType method on them");if(!v.canPlaySource)throw new Error("Techs must have a static canPlaySource method on them");return a=dt(a),v.techs_[a]=l,v.techs_[Jr(a)]=l,a!=="Tech"&&v.defaultTechOrder_.push(a),l},v.getTech=function(a){if(a){if(v.techs_&&v.techs_[a])return v.techs_[a];if(a=dt(a),T.default&&T.default.videojs&&T.default.videojs[a])return ae.warn("The "+a+" tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)"),T.default.videojs[a]}},v}(pe);Ft.names.forEach(function(m){var v=Ft[m];nt.prototype[v.getterName]=function(){return this[v.privateName]=this[v.privateName]||new v.ListClass,this[v.privateName]}}),nt.prototype.featuresVolumeControl=!0,nt.prototype.featuresMuteControl=!0,nt.prototype.featuresFullscreenResize=!1,nt.prototype.featuresPlaybackRate=!1,nt.prototype.featuresProgressEvents=!1,nt.prototype.featuresSourceset=!1,nt.prototype.featuresTimeupdateEvents=!1,nt.prototype.featuresNativeTextTracks=!1,nt.prototype.featuresVideoFrameCallback=!1,nt.withSourceHandlers=function(m){m.registerSourceHandler=function(f,c){var a=m.sourceHandlers;a||(a=m.sourceHandlers=[]),c===void 0&&(c=a.length),a.splice(c,0,f)},m.canPlayType=function(f){for(var c=m.sourceHandlers||[],a,l=0;l<c.length;l++)if(a=c[l].canPlayType(f),a)return a;return""},m.selectSourceHandler=function(f,c){for(var a=m.sourceHandlers||[],l,y=0;y<a.length;y++)if(l=a[y].canHandleSource(f,c),l)return a[y];return null},m.canPlaySource=function(f,c){var a=m.selectSourceHandler(f,c);return a?a.canHandleSource(f,c):""};var v=["seekable","seeking","duration"];v.forEach(function(f){var c=this[f];typeof c=="function"&&(this[f]=function(){return this.sourceHandler_&&this.sourceHandler_[f]?this.sourceHandler_[f].apply(this.sourceHandler_,arguments):c.apply(this,arguments)})},m.prototype),m.prototype.setSource=function(f){var c=m.selectSourceHandler(f,this.options_);c||(m.nativeSourceHandler?c=m.nativeSourceHandler:ae.error("No source handler found for the current source.")),this.disposeSourceHandler(),this.off("dispose",this.disposeSourceHandler_),c!==m.nativeSourceHandler&&(this.currentSource_=f),this.sourceHandler_=c.handleSource(f,this,this.options_),this.one("dispose",this.disposeSourceHandler_)},m.prototype.disposeSourceHandler=function(){this.currentSource_&&(this.clearTracks(["audio","video"]),this.currentSource_=null),this.cleanupAutoTextTracks(),this.sourceHandler_&&(this.sourceHandler_.dispose&&this.sourceHandler_.dispose(),this.sourceHandler_=null)}},pe.registerComponent("Tech",nt),nt.registerTech("Tech",nt),nt.defaultTechOrder_=[];var Un={},zo={},ea={};function My(m,v){Un[m]=Un[m]||[],Un[m].push(v)}function Fy(m,v,f){m.setTimeout(function(){return Hn(v,Un[v.type],f,m)},1)}function Ny(m,v){m.forEach(function(f){return f.setTech&&f.setTech(v)})}function By(m,v,f){return m.reduceRight(Yo(f),v[f]())}function Uy(m,v,f,c){return v[f](m.reduce(Yo(f),c))}function Th(m,v,f,c){c===void 0&&(c=null);var a="call"+dt(f),l=m.reduce(Yo(a),c),y=l===ea,S=y?null:v[f](l);return jy(m,f,S,y),S}var Hy={buffered:1,currentTime:1,duration:1,muted:1,played:1,paused:1,seekable:1,volume:1,ended:1},$y={setCurrentTime:1,setMuted:1,setVolume:1},bh={play:1,pause:1};function Yo(m){return function(v,f){return v===ea?ea:f[m]?f[m](v):v}}function jy(m,v,f,c){for(var a=m.length-1;a>=0;a--){var l=m[a];l[v]&&l[v](c,f)}}function Vy(m){zo[m.id()]=null}function Gy(m,v){var f=zo[m.id()],c=null;if(f==null)return c=v(m),zo[m.id()]=[[v,c]],c;for(var a=0;a<f.length;a++){var l=f[a],y=l[0],S=l[1];y===v&&(c=S)}return c===null&&(c=v(m),f.push([v,c])),c}function Hn(m,v,f,c,a,l){m===void 0&&(m={}),v===void 0&&(v=[]),a===void 0&&(a=[]),l===void 0&&(l=!1);var y=v,S=y[0],x=y.slice(1);if(typeof S=="string")Hn(m,Un[S],f,c,a,l);else if(S){var U=Gy(c,S);if(!U.setSource)return a.push(U),Hn(m,x,f,c,a,l);U.setSource(Fe({},m),function(V,z){if(V)return Hn(m,x,f,c,a,l);a.push(U),Hn(z,m.type===z.type?x:Un[z.type],f,c,a,l)})}else x.length?Hn(m,x,f,c,a,l):l?f(m,a):Hn(m,Un["*"],f,c,a,!0)}var Ky={opus:"video/ogg",ogv:"video/ogg",mp4:"video/mp4",mov:"video/mp4",m4v:"video/mp4",mkv:"video/x-matroska",m4a:"audio/mp4",mp3:"audio/mpeg",aac:"audio/aac",caf:"audio/x-caf",flac:"audio/flac",oga:"audio/ogg",wav:"audio/wav",m3u8:"application/x-mpegURL",mpd:"application/dash+xml",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",png:"image/png",svg:"image/svg+xml",webp:"image/webp"},ta=function(v){v===void 0&&(v="");var f=Wo(v),c=Ky[f.toLowerCase()];return c||""},qy=function(v,f){if(!f)return"";if(v.cache_.source.src===f&&v.cache_.source.type)return v.cache_.source.type;var c=v.cache_.sources.filter(function(S){return S.src===f});if(c.length)return c[0].type;for(var a=v.$$("source"),l=0;l<a.length;l++){var y=a[l];if(y.type&&y.src&&y.src===f)return y.type}return ta(f)},Wy=function m(v){if(Array.isArray(v)){var f=[];v.forEach(function(c){c=m(c),Array.isArray(c)?f=f.concat(c):ze(c)&&f.push(c)}),v=f}else typeof v=="string"&&v.trim()?v=[_h({src:v})]:ze(v)&&typeof v.src=="string"&&v.src&&v.src.trim()?v=[_h(v)]:v=[];return v};function _h(m){if(!m.type){var v=ta(m.src);v&&(m.type=v)}return m}var zy=function(m){L.default(v,m);function v(f,c,a){var l,y=lt({createEl:!1},c);if(l=m.call(this,f,y,a)||this,!c.playerOptions.sources||c.playerOptions.sources.length===0)for(var S=0,x=c.playerOptions.techOrder;S<x.length;S++){var U=dt(x[S]),V=nt.getTech(U);if(U||(V=pe.getComponent(U)),V&&V.isSupported()){f.loadTech_(U);break}}else f.src(c.playerOptions.sources);return l}return v}(pe);pe.registerComponent("MediaLoader",zy);var ia=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.options_.controlText&&l.controlText(l.options_.controlText),l.handleMouseOver_=function(y){return l.handleMouseOver(y)},l.handleMouseOut_=function(y){return l.handleMouseOut(y)},l.handleClick_=function(y){return l.handleClick(y)},l.handleKeyDown_=function(y){return l.handleKeyDown(y)},l.emitTapEvents(),l.enable(),l}var f=v.prototype;return f.createEl=function(a,l,y){a===void 0&&(a="div"),l===void 0&&(l={}),y===void 0&&(y={}),l=Fe({className:this.buildCSSClass(),tabIndex:0},l),a==="button"&&ae.error("Creating a ClickableComponent with an HTML element of "+a+" is not supported; use a Button instead."),y=Fe({role:"button"},y),this.tabIndex_=l.tabIndex;var S=Ie(a,l,y);return S.appendChild(Ie("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),this.createControlTextEl(S),S},f.dispose=function(){this.controlTextEl_=null,m.prototype.dispose.call(this)},f.createControlTextEl=function(a){return this.controlTextEl_=Ie("span",{className:"vjs-control-text"},{"aria-live":"polite"}),a&&a.appendChild(this.controlTextEl_),this.controlText(this.controlText_,a),this.controlTextEl_},f.controlText=function(a,l){if(l===void 0&&(l=this.el()),a===void 0)return this.controlText_||"Need Text";var y=this.localize(a);this.controlText_=a,$e(this.controlTextEl_,y),!this.nonIconControl&&!this.player_.options_.noUITitleAttributes&&l.setAttribute("title",y)},f.buildCSSClass=function(){return"vjs-control vjs-button "+m.prototype.buildCSSClass.call(this)},f.enable=function(){this.enabled_||(this.enabled_=!0,this.removeClass("vjs-disabled"),this.el_.setAttribute("aria-disabled","false"),typeof this.tabIndex_<"u"&&this.el_.setAttribute("tabIndex",this.tabIndex_),this.on(["tap","click"],this.handleClick_),this.on("keydown",this.handleKeyDown_))},f.disable=function(){this.enabled_=!1,this.addClass("vjs-disabled"),this.el_.setAttribute("aria-disabled","true"),typeof this.tabIndex_<"u"&&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_)},f.handleLanguagechange=function(){this.controlText(this.controlText_)},f.handleClick=function(a){this.options_.clickHandler&&this.options_.clickHandler.call(this,arguments)},f.handleKeyDown=function(a){w.default.isEventKey(a,"Space")||w.default.isEventKey(a,"Enter")?(a.preventDefault(),a.stopPropagation(),this.trigger("click")):m.prototype.handleKeyDown.call(this,a)},v}(pe);pe.registerComponent("ClickableComponent",ia);var Yy=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.update(),l.update_=function(y){return l.update(y)},c.on("posterchange",l.update_),l}var f=v.prototype;return f.dispose=function(){this.player().off("posterchange",this.update_),m.prototype.dispose.call(this)},f.createEl=function(){var a=Ie("div",{className:"vjs-poster",tabIndex:-1});return a},f.update=function(a){var l=this.player().poster();this.setSrc(l),l?this.show():this.hide()},f.setSrc=function(a){var l="";a&&(l='url("'+a+'")'),this.el_.style.backgroundImage=l},f.handleClick=function(a){if(this.player_.controls()){var l=this.player_.usingPlugin("eme")&&this.player_.eme.sessions&&this.player_.eme.sessions.length>0;this.player_.tech(!0)&&!((qt||Hi)&&l)&&this.player_.tech(!0).focus(),this.player_.paused()?vi(this.player_.play()):this.player_.pause()}},v}(ia);pe.registerComponent("PosterImage",Yy);var Qt="#222",Eh="#ccc",Xy={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 Xo(m,v){var f;if(m.length===4)f=m[1]+m[1]+m[2]+m[2]+m[3]+m[3];else if(m.length===7)f=m.slice(1);else throw new Error("Invalid color code provided, "+m+"; must be formatted as e.g. #f0e or #f604e2.");return"rgba("+parseInt(f.slice(0,2),16)+","+parseInt(f.slice(2,4),16)+","+parseInt(f.slice(4,6),16)+","+v+")"}function Qo(m,v,f){try{m.style[v]=f}catch{return}}var Qy=function(m){L.default(v,m);function v(c,a,l){var y;y=m.call(this,c,a,l)||this;var S=function(U){return y.updateDisplay(U)};return c.on("loadstart",function(x){return y.toggleDisplay(x)}),c.on("texttrackchange",S),c.on("loadedmetadata",function(x){return y.preselectTrack(x)}),c.ready(it(A.default(y),function(){if(c.tech_&&c.tech_.featuresNativeTextTracks){this.hide();return}c.on("fullscreenchange",S),c.on("playerresize",S),T.default.addEventListener("orientationchange",S),c.on("dispose",function(){return T.default.removeEventListener("orientationchange",S)});for(var x=this.options_.playerOptions.tracks||[],U=0;U<x.length;U++)this.player_.addRemoteTextTrack(x[U],!0);this.preselectTrack()})),y}var f=v.prototype;return f.preselectTrack=function(){for(var a={captions:1,subtitles:1},l=this.player_.textTracks(),y=this.player_.cache_.selectedLanguage,S,x,U,V=0;V<l.length;V++){var z=l[V];y&&y.enabled&&y.language&&y.language===z.language&&z.kind in a?z.kind===y.kind?U=z:U||(U=z):y&&!y.enabled?(U=null,S=null,x=null):z.default&&(z.kind==="descriptions"&&!S?S=z:z.kind in a&&!x&&(x=z))}U?U.mode="showing":x?x.mode="showing":S&&(S.mode="showing")},f.toggleDisplay=function(){this.player_.tech_&&this.player_.tech_.featuresNativeTextTracks?this.hide():this.show()},f.createEl=function(){return m.prototype.createEl.call(this,"div",{className:"vjs-text-track-display"},{translate:"yes","aria-live":"off","aria-atomic":"true"})},f.clearDisplay=function(){typeof T.default.WebVTT=="function"&&T.default.WebVTT.processCues(T.default,[],this.el_)},f.updateDisplay=function(){var a=this.player_.textTracks(),l=this.options_.allowMultipleShowingTracks;if(this.clearDisplay(),l){for(var y=[],S=0;S<a.length;++S){var x=a[S];x.mode==="showing"&&y.push(x)}this.updateForTrack(y);return}for(var U=null,V=null,z=a.length;z--;){var j=a[z];j.mode==="showing"&&(j.kind==="descriptions"?U=j:V=j)}V?(this.getAttribute("aria-live")!=="off"&&this.setAttribute("aria-live","off"),this.updateForTrack(V)):U&&(this.getAttribute("aria-live")!=="assertive"&&this.setAttribute("aria-live","assertive"),this.updateForTrack(U))},f.updateDisplayState=function(a){for(var l=this.player_.textTrackSettings.getValues(),y=a.activeCues,S=y.length;S--;){var x=y[S];if(x){var U=x.displayState;if(l.color&&(U.firstChild.style.color=l.color),l.textOpacity&&Qo(U.firstChild,"color",Xo(l.color||"#fff",l.textOpacity)),l.backgroundColor&&(U.firstChild.style.backgroundColor=l.backgroundColor),l.backgroundOpacity&&Qo(U.firstChild,"backgroundColor",Xo(l.backgroundColor||"#000",l.backgroundOpacity)),l.windowColor&&(l.windowOpacity?Qo(U,"backgroundColor",Xo(l.windowColor,l.windowOpacity)):U.style.backgroundColor=l.windowColor),l.edgeStyle&&(l.edgeStyle==="dropshadow"?U.firstChild.style.textShadow="2px 2px 3px "+Qt+", 2px 2px 4px "+Qt+", 2px 2px 5px "+Qt:l.edgeStyle==="raised"?U.firstChild.style.textShadow="1px 1px "+Qt+", 2px 2px "+Qt+", 3px 3px "+Qt:l.edgeStyle==="depressed"?U.firstChild.style.textShadow="1px 1px "+Eh+", 0 1px "+Eh+", -1px -1px "+Qt+", 0 -1px "+Qt:l.edgeStyle==="uniform"&&(U.firstChild.style.textShadow="0 0 4px "+Qt+", 0 0 4px "+Qt+", 0 0 4px "+Qt+", 0 0 4px "+Qt)),l.fontPercent&&l.fontPercent!==1){var V=T.default.parseFloat(U.style.fontSize);U.style.fontSize=V*l.fontPercent+"px",U.style.height="auto",U.style.top="auto"}l.fontFamily&&l.fontFamily!=="default"&&(l.fontFamily==="small-caps"?U.firstChild.style.fontVariant="small-caps":U.firstChild.style.fontFamily=Xy[l.fontFamily])}}},f.updateForTrack=function(a){if(Array.isArray(a)||(a=[a]),!(typeof T.default.WebVTT!="function"||a.every(function(he){return!he.activeCues}))){for(var l=[],y=0;y<a.length;++y)for(var S=a[y],x=0;x<S.activeCues.length;++x)l.push(S.activeCues[x]);T.default.WebVTT.processCues(T.default,l,this.el_);for(var U=0;U<a.length;++U){for(var V=a[U],z=0;z<V.activeCues.length;++z){var j=V.activeCues[z].displayState;ai(j,"vjs-text-track-cue"),ai(j,"vjs-text-track-cue-"+(V.language?V.language:U)),V.language&&ln(j,"lang",V.language)}this.player_.textTrackSettings&&this.updateDisplayState(V)}}},v}(pe);pe.registerComponent("TextTrackDisplay",Qy);var Jy=function(m){L.default(v,m);function v(){return m.apply(this,arguments)||this}var f=v.prototype;return f.createEl=function(){var a=this.player_.isAudio(),l=this.localize(a?"Audio Player":"Video Player"),y=Ie("span",{className:"vjs-control-text",textContent:this.localize("{1} is loading.",[l])}),S=m.prototype.createEl.call(this,"div",{className:"vjs-loading-spinner",dir:"ltr"});return S.appendChild(y),S},v}(pe);pe.registerComponent("LoadingSpinner",Jy);var ui=function(m){L.default(v,m);function v(){return m.apply(this,arguments)||this}var f=v.prototype;return f.createEl=function(a,l,y){l===void 0&&(l={}),y===void 0&&(y={}),a="button",l=Fe({className:this.buildCSSClass()},l),y=Fe({type:"button"},y);var S=Ie(a,l,y);return S.appendChild(Ie("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),this.createControlTextEl(S),S},f.addChild=function(a,l){l===void 0&&(l={});var y=this.constructor.name;return ae.warn("Adding an actionable (user controllable) child to a Button ("+y+") is not supported; use a ClickableComponent instead."),pe.prototype.addChild.call(this,a,l)},f.enable=function(){m.prototype.enable.call(this),this.el_.removeAttribute("disabled")},f.disable=function(){m.prototype.disable.call(this),this.el_.setAttribute("disabled","disabled")},f.handleKeyDown=function(a){if(w.default.isEventKey(a,"Space")||w.default.isEventKey(a,"Enter")){a.stopPropagation();return}m.prototype.handleKeyDown.call(this,a)},v}(ia);pe.registerComponent("Button",ui);var Sh=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.mouseused_=!1,l.on("mousedown",function(y){return l.handleMouseDown(y)}),l}var f=v.prototype;return f.buildCSSClass=function(){return"vjs-big-play-button"},f.handleClick=function(a){var l=this.player_.play();if(this.mouseused_&&a.clientX&&a.clientY){var y=this.player_.usingPlugin("eme")&&this.player_.eme.sessions&&this.player_.eme.sessions.length>0;vi(l),this.player_.tech(!0)&&!((qt||Hi)&&y)&&this.player_.tech(!0).focus();return}var S=this.player_.getChild("controlBar"),x=S&&S.getChild("playToggle");if(!x){this.player_.tech(!0).focus();return}var U=function(){return x.focus()};nr(l)?l.then(U,function(){}):this.setTimeout(U,1)},f.handleKeyDown=function(a){this.mouseused_=!1,m.prototype.handleKeyDown.call(this,a)},f.handleMouseDown=function(a){this.mouseused_=!0},v}(ui);Sh.prototype.controlText_="Play Video",pe.registerComponent("BigPlayButton",Sh);var Zy=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.controlText(a&&a.controlText||l.localize("Close")),l}var f=v.prototype;return f.buildCSSClass=function(){return"vjs-close-button "+m.prototype.buildCSSClass.call(this)},f.handleClick=function(a){this.trigger({type:"close",bubbles:!1})},f.handleKeyDown=function(a){w.default.isEventKey(a,"Esc")?(a.preventDefault(),a.stopPropagation(),this.trigger("click")):m.prototype.handleKeyDown.call(this,a)},v}(ui);pe.registerComponent("CloseButton",Zy);var Ch=function(m){L.default(v,m);function v(c,a){var l;return a===void 0&&(a={}),l=m.call(this,c,a)||this,a.replay=a.replay===void 0||a.replay,l.on(c,"play",function(y){return l.handlePlay(y)}),l.on(c,"pause",function(y){return l.handlePause(y)}),a.replay&&l.on(c,"ended",function(y){return l.handleEnded(y)}),l}var f=v.prototype;return f.buildCSSClass=function(){return"vjs-play-control "+m.prototype.buildCSSClass.call(this)},f.handleClick=function(a){this.player_.paused()?vi(this.player_.play()):this.player_.pause()},f.handleSeeked=function(a){this.removeClass("vjs-ended"),this.player_.paused()?this.handlePause(a):this.handlePlay(a)},f.handlePlay=function(a){this.removeClass("vjs-ended"),this.removeClass("vjs-paused"),this.addClass("vjs-playing"),this.controlText("Pause")},f.handlePause=function(a){this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.controlText("Play")},f.handleEnded=function(a){var l=this;this.removeClass("vjs-playing"),this.addClass("vjs-ended"),this.controlText("Replay"),this.one(this.player_,"seeked",function(y){return l.handleSeeked(y)})},v}(ui);Ch.prototype.controlText_="Play",pe.registerComponent("PlayToggle",Ch);var wh=function(v,f){v=v<0?0:v;var c=Math.floor(v%60),a=Math.floor(v/60%60),l=Math.floor(v/3600),y=Math.floor(f/60%60),S=Math.floor(f/3600);return(isNaN(v)||v===1/0)&&(l=a=c="-"),l=l>0||S>0?l+":":"",a=((l||y>=10)&&a<10?"0"+a:a)+":",c=c<10?"0"+c:c,l+a+c},Jo=wh;function ev(m){Jo=m}function tv(){Jo=wh}function gs(m,v){return v===void 0&&(v=m),Jo(m,v)}var ms=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.on(c,["timeupdate","ended"],function(y){return l.updateContent(y)}),l.updateTextNode_(),l}var f=v.prototype;return f.createEl=function(){var a=this.buildCSSClass(),l=m.prototype.createEl.call(this,"div",{className:a+" vjs-time-control vjs-control"}),y=Ie("span",{className:"vjs-control-text",textContent:this.localize(this.labelText_)+" "},{role:"presentation"});return l.appendChild(y),this.contentEl_=Ie("span",{className:a+"-display"},{"aria-live":"off",role:"presentation"}),l.appendChild(this.contentEl_),l},f.dispose=function(){this.contentEl_=null,this.textNode_=null,m.prototype.dispose.call(this)},f.updateTextNode_=function(a){var l=this;a===void 0&&(a=0),a=gs(a),this.formattedTime_!==a&&(this.formattedTime_=a,this.requestNamedAnimationFrame("TimeDisplay#updateTextNode_",function(){if(l.contentEl_){var y=l.textNode_;y&&l.contentEl_.firstChild!==y&&(y=null,ae.warn("TimeDisplay#updateTextnode_: Prevented replacement of text node element since it was no longer a child of this node. Appending a new node instead.")),l.textNode_=b.default.createTextNode(l.formattedTime_),l.textNode_&&(y?l.contentEl_.replaceChild(l.textNode_,y):l.contentEl_.appendChild(l.textNode_))}}))},f.updateContent=function(a){},v}(pe);ms.prototype.labelText_="Time",ms.prototype.controlText_="Time",pe.registerComponent("TimeDisplay",ms);var Zo=function(m){L.default(v,m);function v(){return m.apply(this,arguments)||this}var f=v.prototype;return f.buildCSSClass=function(){return"vjs-current-time"},f.updateContent=function(a){var l;this.player_.ended()?l=this.player_.duration():l=this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime(),this.updateTextNode_(l)},v}(ms);Zo.prototype.labelText_="Current Time",Zo.prototype.controlText_="Current Time",pe.registerComponent("CurrentTimeDisplay",Zo);var el=function(m){L.default(v,m);function v(c,a){var l;l=m.call(this,c,a)||this;var y=function(x){return l.updateContent(x)};return l.on(c,"durationchange",y),l.on(c,"loadstart",y),l.on(c,"loadedmetadata",y),l}var f=v.prototype;return f.buildCSSClass=function(){return"vjs-duration"},f.updateContent=function(a){var l=this.player_.duration();this.updateTextNode_(l)},v}(ms);el.prototype.labelText_="Duration",el.prototype.controlText_="Duration",pe.registerComponent("DurationDisplay",el);var iv=function(m){L.default(v,m);function v(){return m.apply(this,arguments)||this}var f=v.prototype;return f.createEl=function(){var a=m.prototype.createEl.call(this,"div",{className:"vjs-time-control vjs-time-divider"},{"aria-hidden":!0}),l=m.prototype.createEl.call(this,"div"),y=m.prototype.createEl.call(this,"span",{textContent:"/"});return l.appendChild(y),a.appendChild(l),a},v}(pe);pe.registerComponent("TimeDivider",iv);var tl=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.on(c,"durationchange",function(y){return l.updateContent(y)}),l}var f=v.prototype;return f.buildCSSClass=function(){return"vjs-remaining-time"},f.createEl=function(){var a=m.prototype.createEl.call(this);return this.options_.displayNegative!==!1&&a.insertBefore(Ie("span",{},{"aria-hidden":!0},"-"),this.contentEl_),a},f.updateContent=function(a){if(typeof this.player_.duration()=="number"){var l;this.player_.ended()?l=0:this.player_.remainingTimeDisplay?l=this.player_.remainingTimeDisplay():l=this.player_.remainingTime(),this.updateTextNode_(l)}},v}(ms);tl.prototype.labelText_="Remaining Time",tl.prototype.controlText_="Remaining Time",pe.registerComponent("RemainingTimeDisplay",tl);var nv=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.updateShowing(),l.on(l.player(),"durationchange",function(y){return l.updateShowing(y)}),l}var f=v.prototype;return f.createEl=function(){var a=m.prototype.createEl.call(this,"div",{className:"vjs-live-control vjs-control"});return this.contentEl_=Ie("div",{className:"vjs-live-display"},{"aria-live":"off"}),this.contentEl_.appendChild(Ie("span",{className:"vjs-control-text",textContent:this.localize("Stream Type")+" "})),this.contentEl_.appendChild(b.default.createTextNode(this.localize("LIVE"))),a.appendChild(this.contentEl_),a},f.dispose=function(){this.contentEl_=null,m.prototype.dispose.call(this)},f.updateShowing=function(a){this.player().duration()===1/0?this.show():this.hide()},v}(pe);pe.registerComponent("LiveDisplay",nv);var Ah=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.updateLiveEdgeStatus(),l.player_.liveTracker&&(l.updateLiveEdgeStatusHandler_=function(y){return l.updateLiveEdgeStatus(y)},l.on(l.player_.liveTracker,"liveedgechange",l.updateLiveEdgeStatusHandler_)),l}var f=v.prototype;return f.createEl=function(){var a=m.prototype.createEl.call(this,"button",{className:"vjs-seek-to-live-control vjs-control"});return this.textEl_=Ie("span",{className:"vjs-seek-to-live-text",textContent:this.localize("LIVE")},{"aria-hidden":"true"}),a.appendChild(this.textEl_),a},f.updateLiveEdgeStatus=function(){!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"))},f.handleClick=function(){this.player_.liveTracker.seekToLiveEdge()},f.dispose=function(){this.player_.liveTracker&&this.off(this.player_.liveTracker,"liveedgechange",this.updateLiveEdgeStatusHandler_),this.textEl_=null,m.prototype.dispose.call(this)},v}(ui);Ah.prototype.controlText_="Seek to live, currently playing live",pe.registerComponent("SeekToLive",Ah);var na=function(v,f,c){return v=Number(v),Math.min(c,Math.max(f,isNaN(v)?f:v))},il=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.handleMouseDown_=function(y){return l.handleMouseDown(y)},l.handleMouseUp_=function(y){return l.handleMouseUp(y)},l.handleKeyDown_=function(y){return l.handleKeyDown(y)},l.handleClick_=function(y){return l.handleClick(y)},l.handleMouseMove_=function(y){return l.handleMouseMove(y)},l.update_=function(y){return l.update(y)},l.bar=l.getChild(l.options_.barName),l.vertical(!!l.options_.vertical),l.enable(),l}var f=v.prototype;return f.enabled=function(){return this.enabled_},f.enable=function(){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)},f.disable=function(){if(this.enabled()){var a=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(a,"mousemove",this.handleMouseMove_),this.off(a,"mouseup",this.handleMouseUp_),this.off(a,"touchmove",this.handleMouseMove_),this.off(a,"touchend",this.handleMouseUp_),this.removeAttribute("tabindex"),this.addClass("disabled"),this.playerEvent&&this.off(this.player_,this.playerEvent,this.update),this.enabled_=!1}},f.createEl=function(a,l,y){return l===void 0&&(l={}),y===void 0&&(y={}),l.className=l.className+" vjs-slider",l=Fe({tabIndex:0},l),y=Fe({role:"slider","aria-valuenow":0,"aria-valuemin":0,"aria-valuemax":100,tabIndex:0},y),m.prototype.createEl.call(this,a,l,y)},f.handleMouseDown=function(a){var l=this.bar.el_.ownerDocument;a.type==="mousedown"&&a.preventDefault(),a.type==="touchstart"&&!Kt&&a.preventDefault(),Br(),this.addClass("vjs-sliding"),this.trigger("slideractive"),this.on(l,"mousemove",this.handleMouseMove_),this.on(l,"mouseup",this.handleMouseUp_),this.on(l,"touchmove",this.handleMouseMove_),this.on(l,"touchend",this.handleMouseUp_),this.handleMouseMove(a,!0)},f.handleMouseMove=function(a){},f.handleMouseUp=function(){var a=this.bar.el_.ownerDocument;Ur(),this.removeClass("vjs-sliding"),this.trigger("sliderinactive"),this.off(a,"mousemove",this.handleMouseMove_),this.off(a,"mouseup",this.handleMouseUp_),this.off(a,"touchmove",this.handleMouseMove_),this.off(a,"touchend",this.handleMouseUp_),this.update()},f.update=function(){var a=this;if(!(!this.el_||!this.bar)){var l=this.getProgress();return l===this.progress_||(this.progress_=l,this.requestNamedAnimationFrame("Slider#update",function(){var y=a.vertical()?"height":"width";a.bar.el().style[y]=(l*100).toFixed(2)+"%"})),l}},f.getProgress=function(){return Number(na(this.getPercent(),0,1).toFixed(4))},f.calculateDistance=function(a){var l=Mn(this.el_,a);return this.vertical()?l.y:l.x},f.handleKeyDown=function(a){w.default.isEventKey(a,"Left")||w.default.isEventKey(a,"Down")?(a.preventDefault(),a.stopPropagation(),this.stepBack()):w.default.isEventKey(a,"Right")||w.default.isEventKey(a,"Up")?(a.preventDefault(),a.stopPropagation(),this.stepForward()):m.prototype.handleKeyDown.call(this,a)},f.handleClick=function(a){a.stopPropagation(),a.preventDefault()},f.vertical=function(a){if(a===void 0)return this.vertical_||!1;this.vertical_=!!a,this.vertical_?this.addClass("vjs-slider-vertical"):this.addClass("vjs-slider-horizontal")},v}(pe);pe.registerComponent("Slider",il);var nl=function(v,f){return na(v/f*100,0,100).toFixed(2)+"%"},sv=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.partEls_=[],l.on(c,"progress",function(y){return l.update(y)}),l}var f=v.prototype;return f.createEl=function(){var a=m.prototype.createEl.call(this,"div",{className:"vjs-load-progress"}),l=Ie("span",{className:"vjs-control-text"}),y=Ie("span",{textContent:this.localize("Loaded")}),S=b.default.createTextNode(": ");return this.percentageEl_=Ie("span",{className:"vjs-control-text-loaded-percentage",textContent:"0%"}),a.appendChild(l),l.appendChild(y),l.appendChild(S),l.appendChild(this.percentageEl_),a},f.dispose=function(){this.partEls_=null,this.percentageEl_=null,m.prototype.dispose.call(this)},f.update=function(a){var l=this;this.requestNamedAnimationFrame("LoadProgressBar#update",function(){var y=l.player_.liveTracker,S=l.player_.buffered(),x=y&&y.isLive()?y.seekableEnd():l.player_.duration(),U=l.player_.bufferedEnd(),V=l.partEls_,z=nl(U,x);l.percent_!==z&&(l.el_.style.width=z,$e(l.percentageEl_,z),l.percent_=z);for(var j=0;j<S.length;j++){var he=S.start(j),we=S.end(j),je=V[j];je||(je=l.el_.appendChild(Ie()),V[j]=je),!(je.dataset.start===he&&je.dataset.end===we)&&(je.dataset.start=he,je.dataset.end=we,je.style.left=nl(he,U),je.style.width=nl(we-he,U))}for(var jn=V.length;jn>S.length;jn--)l.el_.removeChild(V[jn-1]);V.length=S.length})},v}(pe);pe.registerComponent("LoadProgressBar",sv);var rv=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.update=oi(it(A.default(l),l.update),Nt),l}var f=v.prototype;return f.createEl=function(){return m.prototype.createEl.call(this,"div",{className:"vjs-time-tooltip"},{"aria-hidden":"true"})},f.update=function(a,l,y){var S=mi(this.el_),x=un(this.player_.el()),U=a.width*l;if(!(!x||!S)){var V=a.left-x.left+U,z=a.width-U+(x.right-a.right),j=S.width/2;V<j?j+=j-V:z<j&&(j=z),j<0?j=0:j>S.width&&(j=S.width),j=Math.round(j),this.el_.style.right="-"+j+"px",this.write(y)}},f.write=function(a){$e(this.el_,a)},f.updateTime=function(a,l,y,S){var x=this;this.requestNamedAnimationFrame("TimeTooltip#updateTime",function(){var U,V=x.player_.duration();if(x.player_.liveTracker&&x.player_.liveTracker.isLive()){var z=x.player_.liveTracker.liveWindow(),j=z-l*z;U=(j<1?"":"-")+gs(j,z)}else U=gs(y,V);x.update(a,l,U),S&&S()})},v}(pe);pe.registerComponent("TimeTooltip",rv);var sl=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.update=oi(it(A.default(l),l.update),Nt),l}var f=v.prototype;return f.createEl=function(){return m.prototype.createEl.call(this,"div",{className:"vjs-play-progress vjs-slider-bar"},{"aria-hidden":"true"})},f.update=function(a,l){var y=this.getChild("timeTooltip");if(y){var S=this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime();y.updateTime(a,l,S)}},v}(pe);sl.prototype.options_={children:[]},!R&&!gt&&sl.prototype.options_.children.push("timeTooltip"),pe.registerComponent("PlayProgressBar",sl);var Lh=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.update=oi(it(A.default(l),l.update),Nt),l}var f=v.prototype;return f.createEl=function(){return m.prototype.createEl.call(this,"div",{className:"vjs-mouse-display"})},f.update=function(a,l){var y=this,S=l*this.player_.duration();this.getChild("timeTooltip").updateTime(a,l,S,function(){y.el_.style.left=a.width*l+"px"})},v}(pe);Lh.prototype.options_={children:["timeTooltip"]},pe.registerComponent("MouseTimeDisplay",Lh);var sa=5,kh=12,rl=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.setEventHandlers_(),l}var f=v.prototype;return f.setEventHandlers_=function(){var a=this;this.update_=it(this,this.update),this.update=oi(this.update_,Nt),this.on(this.player_,["ended","durationchange","timeupdate"],this.update),this.player_.liveTracker&&this.on(this.player_.liveTracker,"liveedgechange",this.update),this.updateInterval=null,this.enableIntervalHandler_=function(l){return a.enableInterval_(l)},this.disableIntervalHandler_=function(l){return a.disableInterval_(l)},this.on(this.player_,["playing"],this.enableIntervalHandler_),this.on(this.player_,["ended","pause","waiting"],this.disableIntervalHandler_),"hidden"in b.default&&"visibilityState"in b.default&&this.on(b.default,"visibilitychange",this.toggleVisibility_)},f.toggleVisibility_=function(a){b.default.visibilityState==="hidden"?(this.cancelNamedAnimationFrame("SeekBar#update"),this.cancelNamedAnimationFrame("Slider#update"),this.disableInterval_(a)):(!this.player_.ended()&&!this.player_.paused()&&this.enableInterval_(),this.update())},f.enableInterval_=function(){this.updateInterval||(this.updateInterval=this.setInterval(this.update,Nt))},f.disableInterval_=function(a){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&a&&a.type!=="ended"||this.updateInterval&&(this.clearInterval(this.updateInterval),this.updateInterval=null)},f.createEl=function(){return m.prototype.createEl.call(this,"div",{className:"vjs-progress-holder"},{"aria-label":this.localize("Progress Bar")})},f.update=function(a){var l=this;if(b.default.visibilityState!=="hidden"){var y=m.prototype.update.call(this);return this.requestNamedAnimationFrame("SeekBar#update",function(){var S=l.player_.ended()?l.player_.duration():l.getCurrentTime_(),x=l.player_.liveTracker,U=l.player_.duration();x&&x.isLive()&&(U=l.player_.liveTracker.liveCurrentTime()),l.percent_!==y&&(l.el_.setAttribute("aria-valuenow",(y*100).toFixed(2)),l.percent_=y),(l.currentTime_!==S||l.duration_!==U)&&(l.el_.setAttribute("aria-valuetext",l.localize("progress bar timing: currentTime={1} duration={2}",[gs(S,U),gs(U,U)],"{1} of {2}")),l.currentTime_=S,l.duration_=U),l.bar&&l.bar.update(un(l.el()),l.getProgress())}),y}},f.userSeek_=function(a){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&this.player_.liveTracker.nextSeekedFromUser(),this.player_.currentTime(a)},f.getCurrentTime_=function(){return this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime()},f.getPercent=function(){var a=this.getCurrentTime_(),l,y=this.player_.liveTracker;return y&&y.isLive()?(l=(a-y.seekableStart())/y.liveWindow(),y.atLiveEdge()&&(l=1)):l=a/this.player_.duration(),l},f.handleMouseDown=function(a){cn(a)&&(a.stopPropagation(),this.videoWasPlaying=!this.player_.paused(),this.player_.pause(),m.prototype.handleMouseDown.call(this,a))},f.handleMouseMove=function(a,l){if(l===void 0&&(l=!1),!!cn(a)){!l&&!this.player_.scrubbing()&&this.player_.scrubbing(!0);var y,S=this.calculateDistance(a),x=this.player_.liveTracker;if(!x||!x.isLive())y=S*this.player_.duration(),y===this.player_.duration()&&(y=y-.1);else{if(S>=.99){x.seekToLiveEdge();return}var U=x.seekableStart(),V=x.liveCurrentTime();if(y=U+S*x.liveWindow(),y>=V&&(y=V),y<=U&&(y=U+.1),y===1/0)return}this.userSeek_(y)}},f.enable=function(){m.prototype.enable.call(this);var a=this.getChild("mouseTimeDisplay");a&&a.show()},f.disable=function(){m.prototype.disable.call(this);var a=this.getChild("mouseTimeDisplay");a&&a.hide()},f.handleMouseUp=function(a){m.prototype.handleMouseUp.call(this,a),a&&a.stopPropagation(),this.player_.scrubbing(!1),this.player_.trigger({type:"timeupdate",target:this,manuallyTriggered:!0}),this.videoWasPlaying?vi(this.player_.play()):this.update_()},f.stepForward=function(){this.userSeek_(this.player_.currentTime()+sa)},f.stepBack=function(){this.userSeek_(this.player_.currentTime()-sa)},f.handleAction=function(a){this.player_.paused()?this.player_.play():this.player_.pause()},f.handleKeyDown=function(a){var l=this.player_.liveTracker;if(w.default.isEventKey(a,"Space")||w.default.isEventKey(a,"Enter"))a.preventDefault(),a.stopPropagation(),this.handleAction(a);else if(w.default.isEventKey(a,"Home"))a.preventDefault(),a.stopPropagation(),this.userSeek_(0);else if(w.default.isEventKey(a,"End"))a.preventDefault(),a.stopPropagation(),l&&l.isLive()?this.userSeek_(l.liveCurrentTime()):this.userSeek_(this.player_.duration());else if(/^[0-9]$/.test(w.default(a))){a.preventDefault(),a.stopPropagation();var y=(w.default.codes[w.default(a)]-w.default.codes[0])*10/100;l&&l.isLive()?this.userSeek_(l.seekableStart()+l.liveWindow()*y):this.userSeek_(this.player_.duration()*y)}else w.default.isEventKey(a,"PgDn")?(a.preventDefault(),a.stopPropagation(),this.userSeek_(this.player_.currentTime()-sa*kh)):w.default.isEventKey(a,"PgUp")?(a.preventDefault(),a.stopPropagation(),this.userSeek_(this.player_.currentTime()+sa*kh)):m.prototype.handleKeyDown.call(this,a)},f.dispose=function(){this.disableInterval_(),this.off(this.player_,["ended","durationchange","timeupdate"],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 b.default&&"visibilityState"in b.default&&this.off(b.default,"visibilitychange",this.toggleVisibility_),m.prototype.dispose.call(this)},v}(il);rl.prototype.options_={children:["loadProgressBar","playProgressBar"],barName:"playProgressBar"},!R&&!gt&&rl.prototype.options_.children.splice(1,0,"mouseTimeDisplay"),pe.registerComponent("SeekBar",rl);var Ih=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.handleMouseMove=oi(it(A.default(l),l.handleMouseMove),Nt),l.throttledHandleMouseSeek=oi(it(A.default(l),l.handleMouseSeek),Nt),l.handleMouseUpHandler_=function(y){return l.handleMouseUp(y)},l.handleMouseDownHandler_=function(y){return l.handleMouseDown(y)},l.enable(),l}var f=v.prototype;return f.createEl=function(){return m.prototype.createEl.call(this,"div",{className:"vjs-progress-control vjs-control"})},f.handleMouseMove=function(a){var l=this.getChild("seekBar");if(l){var y=l.getChild("playProgressBar"),S=l.getChild("mouseTimeDisplay");if(!(!y&&!S)){var x=l.el(),U=mi(x),V=Mn(x,a).x;V=na(V,0,1),S&&S.update(U,V),y&&y.update(U,l.getProgress())}}},f.handleMouseSeek=function(a){var l=this.getChild("seekBar");l&&l.handleMouseMove(a)},f.enabled=function(){return this.enabled_},f.disable=function(){if(this.children().forEach(function(l){return l.disable&&l.disable()}),!!this.enabled()&&(this.off(["mousedown","touchstart"],this.handleMouseDownHandler_),this.off(this.el_,"mousemove",this.handleMouseMove),this.removeListenersAddedOnMousedownAndTouchstart(),this.addClass("disabled"),this.enabled_=!1,this.player_.scrubbing())){var a=this.getChild("seekBar");this.player_.scrubbing(!1),a.videoWasPlaying&&vi(this.player_.play())}},f.enable=function(){this.children().forEach(function(a){return a.enable&&a.enable()}),!this.enabled()&&(this.on(["mousedown","touchstart"],this.handleMouseDownHandler_),this.on(this.el_,"mousemove",this.handleMouseMove),this.removeClass("disabled"),this.enabled_=!0)},f.removeListenersAddedOnMousedownAndTouchstart=function(){var a=this.el_.ownerDocument;this.off(a,"mousemove",this.throttledHandleMouseSeek),this.off(a,"touchmove",this.throttledHandleMouseSeek),this.off(a,"mouseup",this.handleMouseUpHandler_),this.off(a,"touchend",this.handleMouseUpHandler_)},f.handleMouseDown=function(a){var l=this.el_.ownerDocument,y=this.getChild("seekBar");y&&y.handleMouseDown(a),this.on(l,"mousemove",this.throttledHandleMouseSeek),this.on(l,"touchmove",this.throttledHandleMouseSeek),this.on(l,"mouseup",this.handleMouseUpHandler_),this.on(l,"touchend",this.handleMouseUpHandler_)},f.handleMouseUp=function(a){var l=this.getChild("seekBar");l&&l.handleMouseUp(a),this.removeListenersAddedOnMousedownAndTouchstart()},v}(pe);Ih.prototype.options_={children:["seekBar"]},pe.registerComponent("ProgressControl",Ih);var Rh=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.on(c,["enterpictureinpicture","leavepictureinpicture"],function(y){return l.handlePictureInPictureChange(y)}),l.on(c,["disablepictureinpicturechanged","loadedmetadata"],function(y){return l.handlePictureInPictureEnabledChange(y)}),l.on(c,["loadedmetadata","audioonlymodechange","audiopostermodechange"],function(){var y=c.currentType().substring(0,5)==="audio";y||c.audioPosterMode()||c.audioOnlyMode()?(c.isInPictureInPicture()&&c.exitPictureInPicture(),l.hide()):l.show()}),l.disable(),l}var f=v.prototype;return f.buildCSSClass=function(){return"vjs-picture-in-picture-control "+m.prototype.buildCSSClass.call(this)},f.handlePictureInPictureEnabledChange=function(){b.default.pictureInPictureEnabled&&this.player_.disablePictureInPicture()===!1?this.enable():this.disable()},f.handlePictureInPictureChange=function(a){this.player_.isInPictureInPicture()?this.controlText("Exit Picture-in-Picture"):this.controlText("Picture-in-Picture"),this.handlePictureInPictureEnabledChange()},f.handleClick=function(a){this.player_.isInPictureInPicture()?this.player_.exitPictureInPicture():this.player_.requestPictureInPicture()},v}(ui);Rh.prototype.controlText_="Picture-in-Picture",pe.registerComponent("PictureInPictureToggle",Rh);var Ph=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.on(c,"fullscreenchange",function(y){return l.handleFullscreenChange(y)}),b.default[c.fsApi_.fullscreenEnabled]===!1&&l.disable(),l}var f=v.prototype;return f.buildCSSClass=function(){return"vjs-fullscreen-control "+m.prototype.buildCSSClass.call(this)},f.handleFullscreenChange=function(a){this.player_.isFullscreen()?this.controlText("Non-Fullscreen"):this.controlText("Fullscreen")},f.handleClick=function(a){this.player_.isFullscreen()?this.player_.exitFullscreen():this.player_.requestFullscreen()},v}(ui);Ph.prototype.controlText_="Fullscreen",pe.registerComponent("FullscreenToggle",Ph);var av=function(v,f){f.tech_&&!f.tech_.featuresVolumeControl&&v.addClass("vjs-hidden"),v.on(f,"loadstart",function(){f.tech_.featuresVolumeControl?v.removeClass("vjs-hidden"):v.addClass("vjs-hidden")})},ov=function(m){L.default(v,m);function v(){return m.apply(this,arguments)||this}var f=v.prototype;return f.createEl=function(){var a=m.prototype.createEl.call(this,"div",{className:"vjs-volume-level"});return a.appendChild(m.prototype.createEl.call(this,"span",{className:"vjs-control-text"})),a},v}(pe);pe.registerComponent("VolumeLevel",ov);var lv=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.update=oi(it(A.default(l),l.update),Nt),l}var f=v.prototype;return f.createEl=function(){return m.prototype.createEl.call(this,"div",{className:"vjs-volume-tooltip"},{"aria-hidden":"true"})},f.update=function(a,l,y,S){if(!y){var x=un(this.el_),U=un(this.player_.el()),V=a.width*l;if(!U||!x)return;var z=a.left-U.left+V,j=a.width-V+(U.right-a.right),he=x.width/2;z<he?he+=he-z:j<he&&(he=j),he<0?he=0:he>x.width&&(he=x.width),this.el_.style.right="-"+he+"px"}this.write(S+"%")},f.write=function(a){$e(this.el_,a)},f.updateVolume=function(a,l,y,S,x){var U=this;this.requestNamedAnimationFrame("VolumeLevelTooltip#updateVolume",function(){U.update(a,l,y,S.toFixed(0)),x&&x()})},v}(pe);pe.registerComponent("VolumeLevelTooltip",lv);var Dh=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.update=oi(it(A.default(l),l.update),Nt),l}var f=v.prototype;return f.createEl=function(){return m.prototype.createEl.call(this,"div",{className:"vjs-mouse-display"})},f.update=function(a,l,y){var S=this,x=100*l;this.getChild("volumeLevelTooltip").updateVolume(a,l,y,x,function(){y?S.el_.style.bottom=a.height*l+"px":S.el_.style.left=a.width*l+"px"})},v}(pe);Dh.prototype.options_={children:["volumeLevelTooltip"]},pe.registerComponent("MouseVolumeLevelDisplay",Dh);var ra=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.on("slideractive",function(y){return l.updateLastVolume_(y)}),l.on(c,"volumechange",function(y){return l.updateARIAAttributes(y)}),c.ready(function(){return l.updateARIAAttributes()}),l}var f=v.prototype;return f.createEl=function(){return m.prototype.createEl.call(this,"div",{className:"vjs-volume-bar vjs-slider-bar"},{"aria-label":this.localize("Volume Level"),"aria-live":"polite"})},f.handleMouseDown=function(a){cn(a)&&m.prototype.handleMouseDown.call(this,a)},f.handleMouseMove=function(a){var l=this.getChild("mouseVolumeLevelDisplay");if(l){var y=this.el(),S=un(y),x=this.vertical(),U=Mn(y,a);U=x?U.y:U.x,U=na(U,0,1),l.update(S,U,x)}cn(a)&&(this.checkMuted(),this.player_.volume(this.calculateDistance(a)))},f.checkMuted=function(){this.player_.muted()&&this.player_.muted(!1)},f.getPercent=function(){return this.player_.muted()?0:this.player_.volume()},f.stepForward=function(){this.checkMuted(),this.player_.volume(this.player_.volume()+.1)},f.stepBack=function(){this.checkMuted(),this.player_.volume(this.player_.volume()-.1)},f.updateARIAAttributes=function(a){var l=this.player_.muted()?0:this.volumeAsPercentage_();this.el_.setAttribute("aria-valuenow",l),this.el_.setAttribute("aria-valuetext",l+"%")},f.volumeAsPercentage_=function(){return Math.round(this.player_.volume()*100)},f.updateLastVolume_=function(){var a=this,l=this.player_.volume();this.one("sliderinactive",function(){a.player_.volume()===0&&a.player_.lastVolume_(l)})},v}(il);ra.prototype.options_={children:["volumeLevel"],barName:"volumeLevel"},!R&&!gt&&ra.prototype.options_.children.splice(0,0,"mouseVolumeLevelDisplay"),ra.prototype.playerEvent="volumechange",pe.registerComponent("VolumeBar",ra);var xh=function(m){L.default(v,m);function v(c,a){var l;return a===void 0&&(a={}),a.vertical=a.vertical||!1,(typeof a.volumeBar>"u"||ut(a.volumeBar))&&(a.volumeBar=a.volumeBar||{},a.volumeBar.vertical=a.vertical),l=m.call(this,c,a)||this,av(A.default(l),c),l.throttledHandleMouseMove=oi(it(A.default(l),l.handleMouseMove),Nt),l.handleMouseUpHandler_=function(y){return l.handleMouseUp(y)},l.on("mousedown",function(y){return l.handleMouseDown(y)}),l.on("touchstart",function(y){return l.handleMouseDown(y)}),l.on("mousemove",function(y){return l.handleMouseMove(y)}),l.on(l.volumeBar,["focus","slideractive"],function(){l.volumeBar.addClass("vjs-slider-active"),l.addClass("vjs-slider-active"),l.trigger("slideractive")}),l.on(l.volumeBar,["blur","sliderinactive"],function(){l.volumeBar.removeClass("vjs-slider-active"),l.removeClass("vjs-slider-active"),l.trigger("sliderinactive")}),l}var f=v.prototype;return f.createEl=function(){var a="vjs-volume-horizontal";return this.options_.vertical&&(a="vjs-volume-vertical"),m.prototype.createEl.call(this,"div",{className:"vjs-volume-control vjs-control "+a})},f.handleMouseDown=function(a){var l=this.el_.ownerDocument;this.on(l,"mousemove",this.throttledHandleMouseMove),this.on(l,"touchmove",this.throttledHandleMouseMove),this.on(l,"mouseup",this.handleMouseUpHandler_),this.on(l,"touchend",this.handleMouseUpHandler_)},f.handleMouseUp=function(a){var l=this.el_.ownerDocument;this.off(l,"mousemove",this.throttledHandleMouseMove),this.off(l,"touchmove",this.throttledHandleMouseMove),this.off(l,"mouseup",this.handleMouseUpHandler_),this.off(l,"touchend",this.handleMouseUpHandler_)},f.handleMouseMove=function(a){this.volumeBar.handleMouseMove(a)},v}(pe);xh.prototype.options_={children:["volumeBar"]},pe.registerComponent("VolumeControl",xh);var uv=function(v,f){f.tech_&&!f.tech_.featuresMuteControl&&v.addClass("vjs-hidden"),v.on(f,"loadstart",function(){f.tech_.featuresMuteControl?v.removeClass("vjs-hidden"):v.addClass("vjs-hidden")})},Oh=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,uv(A.default(l),c),l.on(c,["loadstart","volumechange"],function(y){return l.update(y)}),l}var f=v.prototype;return f.buildCSSClass=function(){return"vjs-mute-control "+m.prototype.buildCSSClass.call(this)},f.handleClick=function(a){var l=this.player_.volume(),y=this.player_.lastVolume_();if(l===0){var S=y<.1?.1:y;this.player_.volume(S),this.player_.muted(!1)}else this.player_.muted(!this.player_.muted())},f.update=function(a){this.updateIcon_(),this.updateControlText_()},f.updateIcon_=function(){var a=this.player_.volume(),l=3;R&&this.player_.tech_&&this.player_.tech_.el_&&this.player_.muted(this.player_.tech_.el_.muted),a===0||this.player_.muted()?l=0:a<.33?l=1:a<.67&&(l=2);for(var y=0;y<4;y++)On(this.el_,"vjs-vol-"+y);ai(this.el_,"vjs-vol-"+l)},f.updateControlText_=function(){var a=this.player_.muted()||this.player_.volume()===0,l=a?"Unmute":"Mute";this.controlText()!==l&&this.controlText(l)},v}(ui);Oh.prototype.controlText_="Mute",pe.registerComponent("MuteToggle",Oh);var Mh=function(m){L.default(v,m);function v(c,a){var l;return a===void 0&&(a={}),typeof a.inline<"u"?a.inline=a.inline:a.inline=!0,(typeof a.volumeControl>"u"||ut(a.volumeControl))&&(a.volumeControl=a.volumeControl||{},a.volumeControl.vertical=!a.inline),l=m.call(this,c,a)||this,l.handleKeyPressHandler_=function(y){return l.handleKeyPress(y)},l.on(c,["loadstart"],function(y){return l.volumePanelState_(y)}),l.on(l.muteToggle,"keyup",function(y){return l.handleKeyPress(y)}),l.on(l.volumeControl,"keyup",function(y){return l.handleVolumeControlKeyUp(y)}),l.on("keydown",function(y){return l.handleKeyPress(y)}),l.on("mouseover",function(y){return l.handleMouseOver(y)}),l.on("mouseout",function(y){return l.handleMouseOut(y)}),l.on(l.volumeControl,["slideractive"],l.sliderActive_),l.on(l.volumeControl,["sliderinactive"],l.sliderInactive_),l}var f=v.prototype;return f.sliderActive_=function(){this.addClass("vjs-slider-active")},f.sliderInactive_=function(){this.removeClass("vjs-slider-active")},f.volumePanelState_=function(){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")},f.createEl=function(){var a="vjs-volume-panel-horizontal";return this.options_.inline||(a="vjs-volume-panel-vertical"),m.prototype.createEl.call(this,"div",{className:"vjs-volume-panel vjs-control "+a})},f.dispose=function(){this.handleMouseOut(),m.prototype.dispose.call(this)},f.handleVolumeControlKeyUp=function(a){w.default.isEventKey(a,"Esc")&&this.muteToggle.focus()},f.handleMouseOver=function(a){this.addClass("vjs-hover"),Ot(b.default,"keyup",this.handleKeyPressHandler_)},f.handleMouseOut=function(a){this.removeClass("vjs-hover"),bt(b.default,"keyup",this.handleKeyPressHandler_)},f.handleKeyPress=function(a){w.default.isEventKey(a,"Esc")&&this.handleMouseOut()},v}(pe);Mh.prototype.options_={children:["muteToggle","volumeControl"]},pe.registerComponent("VolumePanel",Mh);var Fh=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,a&&(l.menuButton_=a.menuButton),l.focusedChild_=-1,l.on("keydown",function(y){return l.handleKeyDown(y)}),l.boundHandleBlur_=function(y){return l.handleBlur(y)},l.boundHandleTapClick_=function(y){return l.handleTapClick(y)},l}var f=v.prototype;return f.addEventListenerForItem=function(a){a instanceof pe&&(this.on(a,"blur",this.boundHandleBlur_),this.on(a,["tap","click"],this.boundHandleTapClick_))},f.removeEventListenerForItem=function(a){a instanceof pe&&(this.off(a,"blur",this.boundHandleBlur_),this.off(a,["tap","click"],this.boundHandleTapClick_))},f.removeChild=function(a){typeof a=="string"&&(a=this.getChild(a)),this.removeEventListenerForItem(a),m.prototype.removeChild.call(this,a)},f.addItem=function(a){var l=this.addChild(a);l&&this.addEventListenerForItem(l)},f.createEl=function(){var a=this.options_.contentElType||"ul";this.contentEl_=Ie(a,{className:"vjs-menu-content"}),this.contentEl_.setAttribute("role","menu");var l=m.prototype.createEl.call(this,"div",{append:this.contentEl_,className:"vjs-menu"});return l.appendChild(this.contentEl_),Ot(l,"click",function(y){y.preventDefault(),y.stopImmediatePropagation()}),l},f.dispose=function(){this.contentEl_=null,this.boundHandleBlur_=null,this.boundHandleTapClick_=null,m.prototype.dispose.call(this)},f.handleBlur=function(a){var l=a.relatedTarget||b.default.activeElement;if(!this.children().some(function(S){return S.el()===l})){var y=this.menuButton_;y&&y.buttonPressed_&&l!==y.el().firstChild&&y.unpressButton()}},f.handleTapClick=function(a){if(this.menuButton_){this.menuButton_.unpressButton();var l=this.children();if(!Array.isArray(l))return;var y=l.filter(function(S){return S.el()===a.target})[0];if(!y)return;y.name()!=="CaptionSettingsMenuItem"&&this.menuButton_.focus()}},f.handleKeyDown=function(a){w.default.isEventKey(a,"Left")||w.default.isEventKey(a,"Down")?(a.preventDefault(),a.stopPropagation(),this.stepForward()):(w.default.isEventKey(a,"Right")||w.default.isEventKey(a,"Up"))&&(a.preventDefault(),a.stopPropagation(),this.stepBack())},f.stepForward=function(){var a=0;this.focusedChild_!==void 0&&(a=this.focusedChild_+1),this.focus(a)},f.stepBack=function(){var a=0;this.focusedChild_!==void 0&&(a=this.focusedChild_-1),this.focus(a)},f.focus=function(a){a===void 0&&(a=0);var l=this.children().slice(),y=l.length&&l[0].hasClass("vjs-menu-title");y&&l.shift(),l.length>0&&(a<0?a=0:a>=l.length&&(a=l.length-1),this.focusedChild_=a,l[a].el_.focus())},v}(pe);pe.registerComponent("Menu",Fh);var al=function(m){L.default(v,m);function v(c,a){var l;a===void 0&&(a={}),l=m.call(this,c,a)||this,l.menuButton_=new ui(c,a),l.menuButton_.controlText(l.controlText_),l.menuButton_.el_.setAttribute("aria-haspopup","true");var y=ui.prototype.buildCSSClass();l.menuButton_.el_.className=l.buildCSSClass()+" "+y,l.menuButton_.removeClass("vjs-control"),l.addChild(l.menuButton_),l.update(),l.enabled_=!0;var S=function(U){return l.handleClick(U)};return l.handleMenuKeyUp_=function(x){return l.handleMenuKeyUp(x)},l.on(l.menuButton_,"tap",S),l.on(l.menuButton_,"click",S),l.on(l.menuButton_,"keydown",function(x){return l.handleKeyDown(x)}),l.on(l.menuButton_,"mouseenter",function(){l.addClass("vjs-hover"),l.menu.show(),Ot(b.default,"keyup",l.handleMenuKeyUp_)}),l.on("mouseleave",function(x){return l.handleMouseLeave(x)}),l.on("keydown",function(x){return l.handleSubmenuKeyDown(x)}),l}var f=v.prototype;return f.update=function(){var a=this.createMenu();this.menu&&(this.menu.dispose(),this.removeChild(this.menu)),this.menu=a,this.addChild(a),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"))},f.createMenu=function(){var a=new Fh(this.player_,{menuButton:this});if(this.hideThreshold_=0,this.options_.title){var l=Ie("li",{className:"vjs-menu-title",textContent:dt(this.options_.title),tabIndex:-1}),y=new pe(this.player_,{el:l});a.addItem(y)}if(this.items=this.createItems(),this.items)for(var S=0;S<this.items.length;S++)a.addItem(this.items[S]);return a},f.createItems=function(){},f.createEl=function(){return m.prototype.createEl.call(this,"div",{className:this.buildWrapperCSSClass()},{})},f.buildWrapperCSSClass=function(){var a="vjs-menu-button";this.options_.inline===!0?a+="-inline":a+="-popup";var l=ui.prototype.buildCSSClass();return"vjs-menu-button "+a+" "+l+" "+m.prototype.buildCSSClass.call(this)},f.buildCSSClass=function(){var a="vjs-menu-button";return this.options_.inline===!0?a+="-inline":a+="-popup","vjs-menu-button "+a+" "+m.prototype.buildCSSClass.call(this)},f.controlText=function(a,l){return l===void 0&&(l=this.menuButton_.el()),this.menuButton_.controlText(a,l)},f.dispose=function(){this.handleMouseLeave(),m.prototype.dispose.call(this)},f.handleClick=function(a){this.buttonPressed_?this.unpressButton():this.pressButton()},f.handleMouseLeave=function(a){this.removeClass("vjs-hover"),bt(b.default,"keyup",this.handleMenuKeyUp_)},f.focus=function(){this.menuButton_.focus()},f.blur=function(){this.menuButton_.blur()},f.handleKeyDown=function(a){w.default.isEventKey(a,"Esc")||w.default.isEventKey(a,"Tab")?(this.buttonPressed_&&this.unpressButton(),w.default.isEventKey(a,"Tab")||(a.preventDefault(),this.menuButton_.focus())):(w.default.isEventKey(a,"Up")||w.default.isEventKey(a,"Down"))&&(this.buttonPressed_||(a.preventDefault(),this.pressButton()))},f.handleMenuKeyUp=function(a){(w.default.isEventKey(a,"Esc")||w.default.isEventKey(a,"Tab"))&&this.removeClass("vjs-hover")},f.handleSubmenuKeyPress=function(a){this.handleSubmenuKeyDown(a)},f.handleSubmenuKeyDown=function(a){(w.default.isEventKey(a,"Esc")||w.default.isEventKey(a,"Tab"))&&(this.buttonPressed_&&this.unpressButton(),w.default.isEventKey(a,"Tab")||(a.preventDefault(),this.menuButton_.focus()))},f.pressButton=function(){if(this.enabled_){if(this.buttonPressed_=!0,this.menu.show(),this.menu.lockShowing(),this.menuButton_.el_.setAttribute("aria-expanded","true"),R&&tt())return;this.menu.focus()}},f.unpressButton=function(){this.enabled_&&(this.buttonPressed_=!1,this.menu.unlockShowing(),this.menu.hide(),this.menuButton_.el_.setAttribute("aria-expanded","false"))},f.disable=function(){this.unpressButton(),this.enabled_=!1,this.addClass("vjs-disabled"),this.menuButton_.disable()},f.enable=function(){this.enabled_=!0,this.removeClass("vjs-disabled"),this.menuButton_.enable()},v}(pe);pe.registerComponent("MenuButton",al);var ol=function(m){L.default(v,m);function v(f,c){var a,l=c.tracks;if(a=m.call(this,f,c)||this,a.items.length<=1&&a.hide(),!l)return A.default(a);var y=it(A.default(a),a.update);return l.addEventListener("removetrack",y),l.addEventListener("addtrack",y),l.addEventListener("labelchange",y),a.player_.on("ready",y),a.player_.on("dispose",function(){l.removeEventListener("removetrack",y),l.removeEventListener("addtrack",y),l.removeEventListener("labelchange",y)}),a}return v}(al);pe.registerComponent("TrackButton",ol);var cv=["Tab","Esc","Up","Down","Right","Left"],rr=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.selectable=a.selectable,l.isSelected_=a.selected||!1,l.multiSelectable=a.multiSelectable,l.selected(l.isSelected_),l.selectable?l.multiSelectable?l.el_.setAttribute("role","menuitemcheckbox"):l.el_.setAttribute("role","menuitemradio"):l.el_.setAttribute("role","menuitem"),l}var f=v.prototype;return f.createEl=function(a,l,y){this.nonIconControl=!0;var S=m.prototype.createEl.call(this,"li",Fe({className:"vjs-menu-item",tabIndex:-1},l),y);return S.replaceChild(Ie("span",{className:"vjs-menu-item-text",textContent:this.localize(this.options_.label)}),S.querySelector(".vjs-icon-placeholder")),S},f.handleKeyDown=function(a){cv.some(function(l){return w.default.isEventKey(a,l)})||m.prototype.handleKeyDown.call(this,a)},f.handleClick=function(a){this.selected(!0)},f.selected=function(a){this.selectable&&(a?(this.addClass("vjs-selected"),this.el_.setAttribute("aria-checked","true"),this.controlText(", selected"),this.isSelected_=!0):(this.removeClass("vjs-selected"),this.el_.setAttribute("aria-checked","false"),this.controlText(""),this.isSelected_=!1))},v}(ia);pe.registerComponent("MenuItem",rr);var ar=function(m){L.default(v,m);function v(c,a){var l,y=a.track,S=c.textTracks();a.label=y.label||y.language||"Unknown",a.selected=y.mode==="showing",l=m.call(this,c,a)||this,l.track=y,l.kinds=(a.kinds||[a.kind||l.track.kind]).filter(Boolean);var x=function(){for(var j=arguments.length,he=new Array(j),we=0;we<j;we++)he[we]=arguments[we];l.handleTracksChange.apply(A.default(l),he)},U=function(){for(var j=arguments.length,he=new Array(j),we=0;we<j;we++)he[we]=arguments[we];l.handleSelectedLanguageChange.apply(A.default(l),he)};if(c.on(["loadstart","texttrackchange"],x),S.addEventListener("change",x),S.addEventListener("selectedlanguagechange",U),l.on("dispose",function(){c.off(["loadstart","texttrackchange"],x),S.removeEventListener("change",x),S.removeEventListener("selectedlanguagechange",U)}),S.onchange===void 0){var V;l.on(["tap","click"],function(){if(typeof T.default.Event!="object")try{V=new T.default.Event("change")}catch{}V||(V=b.default.createEvent("Event"),V.initEvent("change",!0,!0)),S.dispatchEvent(V)})}return l.handleTracksChange(),l}var f=v.prototype;return f.handleClick=function(a){var l=this.track,y=this.player_.textTracks();if(m.prototype.handleClick.call(this,a),!!y)for(var S=0;S<y.length;S++){var x=y[S];this.kinds.indexOf(x.kind)!==-1&&(x===l?x.mode!=="showing"&&(x.mode="showing"):x.mode!=="disabled"&&(x.mode="disabled"))}},f.handleTracksChange=function(a){var l=this.track.mode==="showing";l!==this.isSelected_&&this.selected(l)},f.handleSelectedLanguageChange=function(a){if(this.track.mode==="showing"){var l=this.player_.cache_.selectedLanguage;if(l&&l.enabled&&l.language===this.track.language&&l.kind!==this.track.kind)return;this.player_.cache_.selectedLanguage={enabled:!0,language:this.track.language,kind:this.track.kind}}},f.dispose=function(){this.track=null,m.prototype.dispose.call(this)},v}(rr);pe.registerComponent("TextTrackMenuItem",ar);var Nh=function(m){L.default(v,m);function v(c,a){return a.track={player:c,kind:a.kind,kinds:a.kinds,default:!1,mode:"disabled"},a.kinds||(a.kinds=[a.kind]),a.label?a.track.label=a.label:a.track.label=a.kinds.join(" and ")+" off",a.selectable=!0,a.multiSelectable=!1,m.call(this,c,a)||this}var f=v.prototype;return f.handleTracksChange=function(a){for(var l=this.player().textTracks(),y=!0,S=0,x=l.length;S<x;S++){var U=l[S];if(this.options_.kinds.indexOf(U.kind)>-1&&U.mode==="showing"){y=!1;break}}y!==this.isSelected_&&this.selected(y)},f.handleSelectedLanguageChange=function(a){for(var l=this.player().textTracks(),y=!0,S=0,x=l.length;S<x;S++){var U=l[S];if(["captions","descriptions","subtitles"].indexOf(U.kind)>-1&&U.mode==="showing"){y=!1;break}}y&&(this.player_.cache_.selectedLanguage={enabled:!1})},v}(ar);pe.registerComponent("OffTextTrackMenuItem",Nh);var ys=function(m){L.default(v,m);function v(c,a){return a===void 0&&(a={}),a.tracks=c.textTracks(),m.call(this,c,a)||this}var f=v.prototype;return f.createItems=function(a,l){a===void 0&&(a=[]),l===void 0&&(l=ar);var y;this.label_&&(y=this.label_+" off"),a.push(new Nh(this.player_,{kinds:this.kinds_,kind:this.kind_,label:y})),this.hideThreshold_+=1;var S=this.player_.textTracks();Array.isArray(this.kinds_)||(this.kinds_=[this.kind_]);for(var x=0;x<S.length;x++){var U=S[x];if(this.kinds_.indexOf(U.kind)>-1){var V=new l(this.player_,{track:U,kinds:this.kinds_,kind:this.kind_,selectable:!0,multiSelectable:!1});V.addClass("vjs-"+U.kind+"-menu-item"),a.push(V)}}return a},v}(ol);pe.registerComponent("TextTrackButton",ys);var Bh=function(m){L.default(v,m);function v(c,a){var l,y=a.track,S=a.cue,x=c.currentTime();return a.selectable=!0,a.multiSelectable=!1,a.label=S.text,a.selected=S.startTime<=x&&x<S.endTime,l=m.call(this,c,a)||this,l.track=y,l.cue=S,l}var f=v.prototype;return f.handleClick=function(a){m.prototype.handleClick.call(this),this.player_.currentTime(this.cue.startTime)},v}(rr);pe.registerComponent("ChaptersTrackMenuItem",Bh);var ll=function(m){L.default(v,m);function v(c,a,l){var y;return y=m.call(this,c,a,l)||this,y.selectCurrentItem_=function(){y.items.forEach(function(S){S.selected(y.track_.activeCues[0]===S.cue)})},y}var f=v.prototype;return f.buildCSSClass=function(){return"vjs-chapters-button "+m.prototype.buildCSSClass.call(this)},f.buildWrapperCSSClass=function(){return"vjs-chapters-button "+m.prototype.buildWrapperCSSClass.call(this)},f.update=function(a){if(!(a&&a.track&&a.track.kind!=="chapters")){var l=this.findChaptersTrack();l!==this.track_?(this.setTrack(l),m.prototype.update.call(this)):(!this.items||l&&l.cues&&l.cues.length!==this.items.length)&&m.prototype.update.call(this)}},f.setTrack=function(a){if(this.track_!==a){if(this.updateHandler_||(this.updateHandler_=this.update.bind(this)),this.track_){var l=this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);l&&l.removeEventListener("load",this.updateHandler_),this.track_.removeEventListener("cuechange",this.selectCurrentItem_),this.track_=null}if(this.track_=a,this.track_){this.track_.mode="hidden";var y=this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);y&&y.addEventListener("load",this.updateHandler_),this.track_.addEventListener("cuechange",this.selectCurrentItem_)}}},f.findChaptersTrack=function(){for(var a=this.player_.textTracks()||[],l=a.length-1;l>=0;l--){var y=a[l];if(y.kind===this.kind_)return y}},f.getMenuCaption=function(){return this.track_&&this.track_.label?this.track_.label:this.localize(dt(this.kind_))},f.createMenu=function(){return this.options_.title=this.getMenuCaption(),m.prototype.createMenu.call(this)},f.createItems=function(){var a=[];if(!this.track_)return a;var l=this.track_.cues;if(!l)return a;for(var y=0,S=l.length;y<S;y++){var x=l[y],U=new Bh(this.player_,{track:this.track_,cue:x});a.push(U)}return a},v}(ys);ll.prototype.kind_="chapters",ll.prototype.controlText_="Chapters",pe.registerComponent("ChaptersButton",ll);var ul=function(m){L.default(v,m);function v(c,a,l){var y;y=m.call(this,c,a,l)||this;var S=c.textTracks(),x=it(A.default(y),y.handleTracksChange);return S.addEventListener("change",x),y.on("dispose",function(){S.removeEventListener("change",x)}),y}var f=v.prototype;return f.handleTracksChange=function(a){for(var l=this.player().textTracks(),y=!1,S=0,x=l.length;S<x;S++){var U=l[S];if(U.kind!==this.kind_&&U.mode==="showing"){y=!0;break}}y?this.disable():this.enable()},f.buildCSSClass=function(){return"vjs-descriptions-button "+m.prototype.buildCSSClass.call(this)},f.buildWrapperCSSClass=function(){return"vjs-descriptions-button "+m.prototype.buildWrapperCSSClass.call(this)},v}(ys);ul.prototype.kind_="descriptions",ul.prototype.controlText_="Descriptions",pe.registerComponent("DescriptionsButton",ul);var cl=function(m){L.default(v,m);function v(c,a,l){return m.call(this,c,a,l)||this}var f=v.prototype;return f.buildCSSClass=function(){return"vjs-subtitles-button "+m.prototype.buildCSSClass.call(this)},f.buildWrapperCSSClass=function(){return"vjs-subtitles-button "+m.prototype.buildWrapperCSSClass.call(this)},v}(ys);cl.prototype.kind_="subtitles",cl.prototype.controlText_="Subtitles",pe.registerComponent("SubtitlesButton",cl);var hl=function(m){L.default(v,m);function v(c,a){var l;return a.track={player:c,kind:a.kind,label:a.kind+" settings",selectable:!1,default:!1,mode:"disabled"},a.selectable=!1,a.name="CaptionSettingsMenuItem",l=m.call(this,c,a)||this,l.addClass("vjs-texttrack-settings"),l.controlText(", opens "+a.kind+" settings dialog"),l}var f=v.prototype;return f.handleClick=function(a){this.player().getChild("textTrackSettings").open()},v}(ar);pe.registerComponent("CaptionSettingsMenuItem",hl);var dl=function(m){L.default(v,m);function v(c,a,l){return m.call(this,c,a,l)||this}var f=v.prototype;return f.buildCSSClass=function(){return"vjs-captions-button "+m.prototype.buildCSSClass.call(this)},f.buildWrapperCSSClass=function(){return"vjs-captions-button "+m.prototype.buildWrapperCSSClass.call(this)},f.createItems=function(){var a=[];return!(this.player().tech_&&this.player().tech_.featuresNativeTextTracks)&&this.player().getChild("textTrackSettings")&&(a.push(new hl(this.player_,{kind:this.kind_})),this.hideThreshold_+=1),m.prototype.createItems.call(this,a)},v}(ys);dl.prototype.kind_="captions",dl.prototype.controlText_="Captions",pe.registerComponent("CaptionsButton",dl);var Uh=function(m){L.default(v,m);function v(){return m.apply(this,arguments)||this}var f=v.prototype;return f.createEl=function(a,l,y){var S=m.prototype.createEl.call(this,a,l,y),x=S.querySelector(".vjs-menu-item-text");return this.options_.track.kind==="captions"&&(x.appendChild(Ie("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),x.appendChild(Ie("span",{className:"vjs-control-text",textContent:" "+this.localize("Captions")}))),S},v}(ar);pe.registerComponent("SubsCapsMenuItem",Uh);var fl=function(m){L.default(v,m);function v(c,a){var l;return a===void 0&&(a={}),l=m.call(this,c,a)||this,l.label_="subtitles",["en","en-us","en-ca","fr-ca"].indexOf(l.player_.language_)>-1&&(l.label_="captions"),l.menuButton_.controlText(dt(l.label_)),l}var f=v.prototype;return f.buildCSSClass=function(){return"vjs-subs-caps-button "+m.prototype.buildCSSClass.call(this)},f.buildWrapperCSSClass=function(){return"vjs-subs-caps-button "+m.prototype.buildWrapperCSSClass.call(this)},f.createItems=function(){var a=[];return!(this.player().tech_&&this.player().tech_.featuresNativeTextTracks)&&this.player().getChild("textTrackSettings")&&(a.push(new hl(this.player_,{kind:this.label_})),this.hideThreshold_+=1),a=m.prototype.createItems.call(this,a,Uh),a},v}(ys);fl.prototype.kinds_=["captions","subtitles"],fl.prototype.controlText_="Subtitles",pe.registerComponent("SubsCapsButton",fl);var Hh=function(m){L.default(v,m);function v(c,a){var l,y=a.track,S=c.audioTracks();a.label=y.label||y.language||"Unknown",a.selected=y.enabled,l=m.call(this,c,a)||this,l.track=y,l.addClass("vjs-"+y.kind+"-menu-item");var x=function(){for(var V=arguments.length,z=new Array(V),j=0;j<V;j++)z[j]=arguments[j];l.handleTracksChange.apply(A.default(l),z)};return S.addEventListener("change",x),l.on("dispose",function(){S.removeEventListener("change",x)}),l}var f=v.prototype;return f.createEl=function(a,l,y){var S=m.prototype.createEl.call(this,a,l,y),x=S.querySelector(".vjs-menu-item-text");return this.options_.track.kind==="main-desc"&&(x.appendChild(Ie("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),x.appendChild(Ie("span",{className:"vjs-control-text",textContent:" "+this.localize("Descriptions")}))),S},f.handleClick=function(a){if(m.prototype.handleClick.call(this,a),this.track.enabled=!0,this.player_.tech_.featuresNativeAudioTracks)for(var l=this.player_.audioTracks(),y=0;y<l.length;y++){var S=l[y];S!==this.track&&(S.enabled=S===this.track)}},f.handleTracksChange=function(a){this.selected(this.track.enabled)},v}(rr);pe.registerComponent("AudioTrackMenuItem",Hh);var $h=function(m){L.default(v,m);function v(c,a){return a===void 0&&(a={}),a.tracks=c.audioTracks(),m.call(this,c,a)||this}var f=v.prototype;return f.buildCSSClass=function(){return"vjs-audio-button "+m.prototype.buildCSSClass.call(this)},f.buildWrapperCSSClass=function(){return"vjs-audio-button "+m.prototype.buildWrapperCSSClass.call(this)},f.createItems=function(a){a===void 0&&(a=[]),this.hideThreshold_=1;for(var l=this.player_.audioTracks(),y=0;y<l.length;y++){var S=l[y];a.push(new Hh(this.player_,{track:S,selectable:!0,multiSelectable:!1}))}return a},v}(ol);$h.prototype.controlText_="Audio Track",pe.registerComponent("AudioTrackButton",$h);var pl=function(m){L.default(v,m);function v(c,a){var l,y=a.rate,S=parseFloat(y,10);return a.label=y,a.selected=S===c.playbackRate(),a.selectable=!0,a.multiSelectable=!1,l=m.call(this,c,a)||this,l.label=y,l.rate=S,l.on(c,"ratechange",function(x){return l.update(x)}),l}var f=v.prototype;return f.handleClick=function(a){m.prototype.handleClick.call(this),this.player().playbackRate(this.rate)},f.update=function(a){this.selected(this.player().playbackRate()===this.rate)},v}(rr);pl.prototype.contentElType="button",pe.registerComponent("PlaybackRateMenuItem",pl);var jh=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.menuButton_.el_.setAttribute("aria-describedby",l.labelElId_),l.updateVisibility(),l.updateLabel(),l.on(c,"loadstart",function(y){return l.updateVisibility(y)}),l.on(c,"ratechange",function(y){return l.updateLabel(y)}),l.on(c,"playbackrateschange",function(y){return l.handlePlaybackRateschange(y)}),l}var f=v.prototype;return f.createEl=function(){var a=m.prototype.createEl.call(this);return this.labelElId_="vjs-playback-rate-value-label-"+this.id_,this.labelEl_=Ie("div",{className:"vjs-playback-rate-value",id:this.labelElId_,textContent:"1x"}),a.appendChild(this.labelEl_),a},f.dispose=function(){this.labelEl_=null,m.prototype.dispose.call(this)},f.buildCSSClass=function(){return"vjs-playback-rate "+m.prototype.buildCSSClass.call(this)},f.buildWrapperCSSClass=function(){return"vjs-playback-rate "+m.prototype.buildWrapperCSSClass.call(this)},f.createItems=function(){for(var a=this.playbackRates(),l=[],y=a.length-1;y>=0;y--)l.push(new pl(this.player(),{rate:a[y]+"x"}));return l},f.updateARIAAttributes=function(){this.el().setAttribute("aria-valuenow",this.player().playbackRate())},f.handleClick=function(a){var l=this.player().playbackRate(),y=this.playbackRates(),S=y.indexOf(l),x=(S+1)%y.length;this.player().playbackRate(y[x])},f.handlePlaybackRateschange=function(a){this.update()},f.playbackRates=function(){var a=this.player();return a.playbackRates&&a.playbackRates()||[]},f.playbackRateSupported=function(){return this.player().tech_&&this.player().tech_.featuresPlaybackRate&&this.playbackRates()&&this.playbackRates().length>0},f.updateVisibility=function(a){this.playbackRateSupported()?this.removeClass("vjs-hidden"):this.addClass("vjs-hidden")},f.updateLabel=function(a){this.playbackRateSupported()&&(this.labelEl_.textContent=this.player().playbackRate()+"x")},v}(al);jh.prototype.controlText_="Playback Rate",pe.registerComponent("PlaybackRateMenuButton",jh);var Vh=function(m){L.default(v,m);function v(){return m.apply(this,arguments)||this}var f=v.prototype;return f.buildCSSClass=function(){return"vjs-spacer "+m.prototype.buildCSSClass.call(this)},f.createEl=function(a,l,y){return a===void 0&&(a="div"),l===void 0&&(l={}),y===void 0&&(y={}),l.className||(l.className=this.buildCSSClass()),m.prototype.createEl.call(this,a,l,y)},v}(pe);pe.registerComponent("Spacer",Vh);var hv=function(m){L.default(v,m);function v(){return m.apply(this,arguments)||this}var f=v.prototype;return f.buildCSSClass=function(){return"vjs-custom-control-spacer "+m.prototype.buildCSSClass.call(this)},f.createEl=function(){return m.prototype.createEl.call(this,"div",{className:this.buildCSSClass(),textContent:" "})},v}(Vh);pe.registerComponent("CustomControlSpacer",hv);var aa=function(m){L.default(v,m);function v(){return m.apply(this,arguments)||this}var f=v.prototype;return f.createEl=function(){return m.prototype.createEl.call(this,"div",{className:"vjs-control-bar",dir:"ltr"})},v}(pe);aa.prototype.options_={children:["playToggle","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","liveDisplay","seekToLive","remainingTimeDisplay","customControlSpacer","playbackRateMenuButton","chaptersButton","descriptionsButton","subsCapsButton","audioTrackButton","fullscreenToggle"]},"exitPictureInPicture"in b.default&&aa.prototype.options_.children.splice(aa.prototype.options_.children.length-1,0,"pictureInPictureToggle"),pe.registerComponent("ControlBar",aa);var Gh=function(m){L.default(v,m);function v(c,a){var l;return l=m.call(this,c,a)||this,l.on(c,"error",function(y){return l.open(y)}),l}var f=v.prototype;return f.buildCSSClass=function(){return"vjs-error-display "+m.prototype.buildCSSClass.call(this)},f.content=function(){var a=this.player().error();return a?this.localize(a.message):""},v}(hs);Gh.prototype.options_=E.default({},hs.prototype.options_,{pauseOnOpen:!1,fillAlways:!0,temporary:!1,uncloseable:!0}),pe.registerComponent("ErrorDisplay",Gh);var gl="vjs-text-track-settings",Kh=["#000","Black"],qh=["#00F","Blue"],Wh=["#0FF","Cyan"],zh=["#0F0","Green"],Yh=["#F0F","Magenta"],Xh=["#F00","Red"],Qh=["#FFF","White"],Jh=["#FF0","Yellow"],ml=["1","Opaque"],yl=["0.5","Semi-Transparent"],Zh=["0","Transparent"],$n={backgroundColor:{selector:".vjs-bg-color > select",id:"captions-background-color-%s",label:"Color",options:[Kh,Qh,Xh,zh,qh,Jh,Yh,Wh]},backgroundOpacity:{selector:".vjs-bg-opacity > select",id:"captions-background-opacity-%s",label:"Transparency",options:[ml,yl,Zh]},color:{selector:".vjs-fg-color > select",id:"captions-foreground-color-%s",label:"Color",options:[Qh,Kh,Xh,zh,qh,Jh,Yh,Wh]},edgeStyle:{selector:".vjs-edge-style > select",id:"%s",label:"Text Edge Style",options:[["none","None"],["raised","Raised"],["depressed","Depressed"],["uniform","Uniform"],["dropshadow","Dropshadow"]]},fontFamily:{selector:".vjs-font-family > select",id:"captions-font-family-%s",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:"captions-font-size-%s",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:function(v){return v==="1.00"?null:Number(v)}},textOpacity:{selector:".vjs-text-opacity > select",id:"captions-foreground-opacity-%s",label:"Transparency",options:[ml,yl]},windowColor:{selector:".vjs-window-color > select",id:"captions-window-color-%s",label:"Color"},windowOpacity:{selector:".vjs-window-opacity > select",id:"captions-window-opacity-%s",label:"Transparency",options:[Zh,yl,ml]}};$n.windowColor.options=$n.backgroundColor.options;function ed(m,v){if(v&&(m=v(m)),m&&m!=="none")return m}function dv(m,v){var f=m.options[m.options.selectedIndex].value;return ed(f,v)}function fv(m,v,f){if(v){for(var c=0;c<m.options.length;c++)if(ed(m.options[c].value,f)===v){m.selectedIndex=c;break}}}var pv=function(m){L.default(v,m);function v(c,a){var l;return a.temporary=!1,l=m.call(this,c,a)||this,l.updateDisplay=l.updateDisplay.bind(A.default(l)),l.fill(),l.hasBeenOpened_=l.hasBeenFilled_=!0,l.endDialog=Ie("p",{className:"vjs-control-text",textContent:l.localize("End of dialog window.")}),l.el().appendChild(l.endDialog),l.setDefaults(),a.persistTextTrackSettings===void 0&&(l.options_.persistTextTrackSettings=l.options_.playerOptions.persistTextTrackSettings),l.on(l.$(".vjs-done-button"),"click",function(){l.saveSettings(),l.close()}),l.on(l.$(".vjs-default-button"),"click",function(){l.setDefaults(),l.updateDisplay()}),Ue($n,function(y){l.on(l.$(y.selector),"change",l.updateDisplay)}),l.options_.persistTextTrackSettings&&l.restoreSettings(),l}var f=v.prototype;return f.dispose=function(){this.endDialog=null,m.prototype.dispose.call(this)},f.createElSelect_=function(a,l,y){var S=this;l===void 0&&(l=""),y===void 0&&(y="label");var x=$n[a],U=x.id.replace("%s",this.id_),V=[l,U].join(" ").trim();return["<"+y+' id="'+U+'" class="'+(y==="label"?"vjs-label":"")+'">',this.localize(x.label),"</"+y+">",'<select aria-labelledby="'+V+'">'].concat(x.options.map(function(z){var j=U+"-"+z[1].replace(/\W+/g,"");return['<option id="'+j+'" value="'+z[0]+'" ','aria-labelledby="'+V+" "+j+'">',S.localize(z[1]),"</option>"].join("")})).concat("</select>").join("")},f.createElFgColor_=function(){var a="captions-text-legend-"+this.id_;return['<fieldset class="vjs-fg-color vjs-track-setting">','<legend id="'+a+'">',this.localize("Text"),"</legend>",this.createElSelect_("color",a),'<span class="vjs-text-opacity vjs-opacity">',this.createElSelect_("textOpacity",a),"</span>","</fieldset>"].join("")},f.createElBgColor_=function(){var a="captions-background-"+this.id_;return['<fieldset class="vjs-bg-color vjs-track-setting">','<legend id="'+a+'">',this.localize("Background"),"</legend>",this.createElSelect_("backgroundColor",a),'<span class="vjs-bg-opacity vjs-opacity">',this.createElSelect_("backgroundOpacity",a),"</span>","</fieldset>"].join("")},f.createElWinColor_=function(){var a="captions-window-"+this.id_;return['<fieldset class="vjs-window-color vjs-track-setting">','<legend id="'+a+'">',this.localize("Window"),"</legend>",this.createElSelect_("windowColor",a),'<span class="vjs-window-opacity vjs-opacity">',this.createElSelect_("windowOpacity",a),"</span>","</fieldset>"].join("")},f.createElColors_=function(){return Ie("div",{className:"vjs-track-settings-colors",innerHTML:[this.createElFgColor_(),this.createElBgColor_(),this.createElWinColor_()].join("")})},f.createElFont_=function(){return Ie("div",{className:"vjs-track-settings-font",innerHTML:['<fieldset class="vjs-font-percent vjs-track-setting">',this.createElSelect_("fontPercent","","legend"),"</fieldset>",'<fieldset class="vjs-edge-style vjs-track-setting">',this.createElSelect_("edgeStyle","","legend"),"</fieldset>",'<fieldset class="vjs-font-family vjs-track-setting">',this.createElSelect_("fontFamily","","legend"),"</fieldset>"].join("")})},f.createElControls_=function(){var a=this.localize("restore all settings to the default values");return Ie("div",{className:"vjs-track-settings-controls",innerHTML:['<button type="button" class="vjs-default-button" title="'+a+'">',this.localize("Reset"),'<span class="vjs-control-text"> '+a+"</span>","</button>",'<button type="button" class="vjs-done-button">'+this.localize("Done")+"</button>"].join("")})},f.content=function(){return[this.createElColors_(),this.createElFont_(),this.createElControls_()]},f.label=function(){return this.localize("Caption Settings Dialog")},f.description=function(){return this.localize("Beginning of dialog window. Escape will cancel and close the window.")},f.buildCSSClass=function(){return m.prototype.buildCSSClass.call(this)+" vjs-text-track-settings"},f.getValues=function(){var a=this;return He($n,function(l,y,S){var x=dv(a.$(y.selector),y.parser);return x!==void 0&&(l[S]=x),l},{})},f.setValues=function(a){var l=this;Ue($n,function(y,S){fv(l.$(y.selector),a[S],y.parser)})},f.setDefaults=function(){var a=this;Ue($n,function(l){var y=l.hasOwnProperty("default")?l.default:0;a.$(l.selector).selectedIndex=y})},f.restoreSettings=function(){var a;try{a=JSON.parse(T.default.localStorage.getItem(gl))}catch(l){ae.warn(l)}a&&this.setValues(a)},f.saveSettings=function(){if(this.options_.persistTextTrackSettings){var a=this.getValues();try{Object.keys(a).length?T.default.localStorage.setItem(gl,JSON.stringify(a)):T.default.localStorage.removeItem(gl)}catch(l){ae.warn(l)}}},f.updateDisplay=function(){var a=this.player_.getChild("textTrackDisplay");a&&a.updateDisplay()},f.conditionalBlur_=function(){this.previouslyActiveEl_=null;var a=this.player_.controlBar,l=a&&a.subsCapsButton,y=a&&a.captionsButton;l?l.focus():y&&y.focus()},v}(hs);pe.registerComponent("TextTrackSettings",pv);var gv=function(m){L.default(v,m);function v(c,a){var l,y=a.ResizeObserver||T.default.ResizeObserver;a.ResizeObserver===null&&(y=!1);var S=lt({createEl:!y,reportTouchActivity:!1},a);return l=m.call(this,c,S)||this,l.ResizeObserver=a.ResizeObserver||T.default.ResizeObserver,l.loadListener_=null,l.resizeObserver_=null,l.debouncedHandler_=_e(function(){l.resizeHandler()},100,!1,A.default(l)),y?(l.resizeObserver_=new l.ResizeObserver(l.debouncedHandler_),l.resizeObserver_.observe(c.el())):(l.loadListener_=function(){if(!(!l.el_||!l.el_.contentWindow)){var x=l.debouncedHandler_,U=l.unloadListener_=function(){bt(this,"resize",x),bt(this,"unload",U),U=null};Ot(l.el_.contentWindow,"unload",U),Ot(l.el_.contentWindow,"resize",x)}},l.one("load",l.loadListener_)),l}var f=v.prototype;return f.createEl=function(){return m.prototype.createEl.call(this,"iframe",{className:"vjs-resize-manager",tabIndex:-1,title:this.localize("No content")},{"aria-hidden":"true"})},f.resizeHandler=function(){!this.player_||!this.player_.trigger||this.player_.trigger("playerresize")},f.dispose=function(){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,m.prototype.dispose.call(this)},v}(pe);pe.registerComponent("ResizeManager",gv);var mv={trackingThreshold:20,liveTolerance:15},yv=function(m){L.default(v,m);function v(c,a){var l,y=lt(mv,a,{createEl:!1});return l=m.call(this,c,y)||this,l.handleVisibilityChange_=function(S){return l.handleVisibilityChange(S)},l.trackLiveHandler_=function(){return l.trackLive_()},l.handlePlay_=function(S){return l.handlePlay(S)},l.handleFirstTimeupdate_=function(S){return l.handleFirstTimeupdate(S)},l.handleSeeked_=function(S){return l.handleSeeked(S)},l.seekToLiveEdge_=function(S){return l.seekToLiveEdge(S)},l.reset_(),l.on(l.player_,"durationchange",function(S){return l.handleDurationchange(S)}),l.on(l.player_,"canplay",function(){return l.toggleTracking()}),qt&&"hidden"in b.default&&"visibilityState"in b.default&&l.on(b.default,"visibilitychange",l.handleVisibilityChange_),l}var f=v.prototype;return f.handleVisibilityChange=function(){this.player_.duration()===1/0&&(b.default.hidden?this.stopTracking():this.startTracking())},f.trackLive_=function(){var a=this.player_.seekable();if(!(!a||!a.length)){var l=Number(T.default.performance.now().toFixed(4)),y=this.lastTime_===-1?0:(l-this.lastTime_)/1e3;this.lastTime_=l,this.pastSeekEnd_=this.pastSeekEnd()+y;var S=this.liveCurrentTime(),x=this.player_.currentTime(),U=this.player_.paused()||this.seekedBehindLive_||Math.abs(S-x)>this.options_.liveTolerance;(!this.timeupdateSeen_||S===1/0)&&(U=!1),U!==this.behindLiveEdge_&&(this.behindLiveEdge_=U,this.trigger("liveedgechange"))}},f.handleDurationchange=function(){this.toggleTracking()},f.toggleTracking=function(){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())},f.startTracking=function(){this.isTracking()||(this.timeupdateSeen_||(this.timeupdateSeen_=this.player_.hasStarted()),this.trackingInterval_=this.setInterval(this.trackLiveHandler_,Nt),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_)))},f.handleFirstTimeupdate=function(){this.timeupdateSeen_=!0,this.on(this.player_,"seeked",this.handleSeeked_)},f.handleSeeked=function(){var a=Math.abs(this.liveCurrentTime()-this.player_.currentTime());this.seekedBehindLive_=this.nextSeekedFromUser_&&a>2,this.nextSeekedFromUser_=!1,this.trackLive_()},f.handlePlay=function(){this.one(this.player_,"timeupdate",this.seekToLiveEdge_)},f.reset_=function(){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_)},f.nextSeekedFromUser=function(){this.nextSeekedFromUser_=!0},f.stopTracking=function(){this.isTracking()&&(this.reset_(),this.trigger("liveedgechange"))},f.seekableEnd=function(){for(var a=this.player_.seekable(),l=[],y=a?a.length:0;y--;)l.push(a.end(y));return l.length?l.sort()[l.length-1]:1/0},f.seekableStart=function(){for(var a=this.player_.seekable(),l=[],y=a?a.length:0;y--;)l.push(a.start(y));return l.length?l.sort()[0]:0},f.liveWindow=function(){var a=this.liveCurrentTime();return a===1/0?0:a-this.seekableStart()},f.isLive=function(){return this.isTracking()},f.atLiveEdge=function(){return!this.behindLiveEdge()},f.liveCurrentTime=function(){return this.pastSeekEnd()+this.seekableEnd()},f.pastSeekEnd=function(){var a=this.seekableEnd();return this.lastSeekEnd_!==-1&&a!==this.lastSeekEnd_&&(this.pastSeekEnd_=0),this.lastSeekEnd_=a,this.pastSeekEnd_},f.behindLiveEdge=function(){return this.behindLiveEdge_},f.isTracking=function(){return typeof this.trackingInterval_=="number"},f.seekToLiveEdge=function(){this.seekedBehindLive_=!1,!this.atLiveEdge()&&(this.nextSeekedFromUser_=!1,this.player_.currentTime(this.liveCurrentTime()))},f.dispose=function(){this.off(b.default,"visibilitychange",this.handleVisibilityChange_),this.stopTracking(),m.prototype.dispose.call(this)},v}(pe);pe.registerComponent("LiveTracker",yv);var vl=function(v){var f=v.el();if(f.hasAttribute("src"))return v.triggerSourceset(f.src),!0;var c=v.$$("source"),a=[],l="";if(!c.length)return!1;for(var y=0;y<c.length;y++){var S=c[y].src;S&&a.indexOf(S)===-1&&a.push(S)}return a.length?(a.length===1&&(l=a[0]),v.triggerSourceset(l),!0):!1},vv=Object.defineProperty({},"innerHTML",{get:function(){return this.cloneNode(!0).innerHTML},set:function(v){var f=b.default.createElement(this.nodeName.toLowerCase());f.innerHTML=v;for(var c=b.default.createDocumentFragment();f.childNodes.length;)c.appendChild(f.childNodes[0]);return this.innerText="",T.default.Element.prototype.appendChild.call(this,c),this.innerHTML}}),td=function(v,f){for(var c={},a=0;a<v.length&&(c=Object.getOwnPropertyDescriptor(v[a],f),!(c&&c.set&&c.get));a++);return c.enumerable=!0,c.configurable=!0,c},Tv=function(v){return td([v.el(),T.default.HTMLMediaElement.prototype,T.default.Element.prototype,vv],"innerHTML")},id=function(v){var f=v.el();if(!f.resetSourceWatch_){var c={},a=Tv(v),l=function(S){return function(){for(var x=arguments.length,U=new Array(x),V=0;V<x;V++)U[V]=arguments[V];var z=S.apply(f,U);return vl(v),z}};["append","appendChild","insertAdjacentHTML"].forEach(function(y){f[y]&&(c[y]=f[y],f[y]=l(c[y]))}),Object.defineProperty(f,"innerHTML",lt(a,{set:l(a.set)})),f.resetSourceWatch_=function(){f.resetSourceWatch_=null,Object.keys(c).forEach(function(y){f[y]=c[y]}),Object.defineProperty(f,"innerHTML",a)},v.one("sourceset",f.resetSourceWatch_)}},bv=Object.defineProperty({},"src",{get:function(){return this.hasAttribute("src")?dh(T.default.Element.prototype.getAttribute.call(this,"src")):""},set:function(v){return T.default.Element.prototype.setAttribute.call(this,"src",v),v}}),_v=function(v){return td([v.el(),T.default.HTMLMediaElement.prototype,bv],"src")},Ev=function(v){if(v.featuresSourceset){var f=v.el();if(!f.resetSourceset_){var c=_v(v),a=f.setAttribute,l=f.load;Object.defineProperty(f,"src",lt(c,{set:function(S){var x=c.set.call(f,S);return v.triggerSourceset(f.src),x}})),f.setAttribute=function(y,S){var x=a.call(f,y,S);return/src/i.test(y)&&v.triggerSourceset(f.src),x},f.load=function(){var y=l.call(f);return vl(v)||(v.triggerSourceset(""),id(v)),y},f.currentSrc?v.triggerSourceset(f.currentSrc):vl(v)||id(v),f.resetSourceset_=function(){f.resetSourceset_=null,f.load=l,f.setAttribute=a,Object.defineProperty(f,"src",c),f.resetSourceWatch_&&f.resetSourceWatch_()}}}},Tl=function(v,f,c,a){a===void 0&&(a=!0);var l=function(x){return Object.defineProperty(v,f,{value:x,enumerable:!0,writable:!0})},y={configurable:!0,enumerable:!0,get:function(){var x=c();return l(x),x}};return a&&(y.set=l),Object.defineProperty(v,f,y)},Se=function(m){L.default(v,m);function v(c,a){var l;l=m.call(this,c,a)||this;var y=c.source,S=!1;if(l.featuresVideoFrameCallback=l.featuresVideoFrameCallback&&l.el_.tagName==="VIDEO",y&&(l.el_.currentSrc!==y.src||c.tag&&c.tag.initNetworkState_===3)?l.setSource(y):l.handleLateInit_(l.el_),c.enableSourceset&&l.setupSourcesetHandling_(),l.isScrubbing_=!1,l.el_.hasChildNodes()){for(var x=l.el_.childNodes,U=x.length,V=[];U--;){var z=x[U],j=z.nodeName.toLowerCase();j==="track"&&(l.featuresNativeTextTracks?(l.remoteTextTrackEls().addTrackElement_(z),l.remoteTextTracks().addTrack(z.track),l.textTracks().addTrack(z.track),!S&&!l.el_.hasAttribute("crossorigin")&&Zr(z.src)&&(S=!0)):V.push(z))}for(var he=0;he<V.length;he++)l.el_.removeChild(V[he])}return l.proxyNativeTracks_(),l.featuresNativeTextTracks&&S&&ae.warn(`Text Tracks are being loaded from another origin but the crossorigin attribute isn't used.
This may prevent text tracks from loading.`),l.restoreMetadataTracksInIOSNativePlayer_(),(ri||Rt||xn)&&c.nativeControlsForTouch===!0&&l.setControls(!0),l.proxyWebkitFullscreen_(),l.triggerReady(),l}var f=v.prototype;return f.dispose=function(){this.el_&&this.el_.resetSourceset_&&this.el_.resetSourceset_(),v.disposeMediaElement(this.el_),this.options_=null,m.prototype.dispose.call(this)},f.setupSourcesetHandling_=function(){Ev(this)},f.restoreMetadataTracksInIOSNativePlayer_=function(){var a=this.textTracks(),l,y=function(){l=[];for(var U=0;U<a.length;U++){var V=a[U];V.kind==="metadata"&&l.push({track:V,storedMode:V.mode})}};y(),a.addEventListener("change",y),this.on("dispose",function(){return a.removeEventListener("change",y)});var S=function x(){for(var U=0;U<l.length;U++){var V=l[U];V.track.mode==="disabled"&&V.track.mode!==V.storedMode&&(V.track.mode=V.storedMode)}a.removeEventListener("change",x)};this.on("webkitbeginfullscreen",function(){a.removeEventListener("change",y),a.removeEventListener("change",S),a.addEventListener("change",S)}),this.on("webkitendfullscreen",function(){a.removeEventListener("change",y),a.addEventListener("change",y),a.removeEventListener("change",S)})},f.overrideNative_=function(a,l){var y=this;if(l===this["featuresNative"+a+"Tracks"]){var S=a.toLowerCase();this[S+"TracksListeners_"]&&Object.keys(this[S+"TracksListeners_"]).forEach(function(x){var U=y.el()[S+"Tracks"];U.removeEventListener(x,y[S+"TracksListeners_"][x])}),this["featuresNative"+a+"Tracks"]=!l,this[S+"TracksListeners_"]=null,this.proxyNativeTracksForType_(S)}},f.overrideNativeAudioTracks=function(a){this.overrideNative_("Audio",a)},f.overrideNativeVideoTracks=function(a){this.overrideNative_("Video",a)},f.proxyNativeTracksForType_=function(a){var l=this,y=Xt[a],S=this.el()[y.getterName],x=this[y.getterName]();if(!(!this["featuresNative"+y.capitalName+"Tracks"]||!S||!S.addEventListener)){var U={change:function(j){var he={type:"change",target:x,currentTarget:x,srcElement:x};x.trigger(he),a==="text"&&l[ps.remoteText.getterName]().trigger(he)},addtrack:function(j){x.addTrack(j.track)},removetrack:function(j){x.removeTrack(j.track)}},V=function(){for(var j=[],he=0;he<x.length;he++){for(var we=!1,je=0;je<S.length;je++)if(S[je]===x[he]){we=!0;break}we||j.push(x[he])}for(;j.length;)x.removeTrack(j.shift())};this[y.getterName+"Listeners_"]=U,Object.keys(U).forEach(function(z){var j=U[z];S.addEventListener(z,j),l.on("dispose",function(he){return S.removeEventListener(z,j)})}),this.on("loadstart",V),this.on("dispose",function(z){return l.off("loadstart",V)})}},f.proxyNativeTracks_=function(){var a=this;Xt.names.forEach(function(l){a.proxyNativeTracksForType_(l)})},f.createEl=function(){var a=this.options_.tag;if(!a||!(this.options_.playerElIngest||this.movingMediaElementInDOM)){if(a){var l=a.cloneNode(!0);a.parentNode&&a.parentNode.insertBefore(l,a),v.disposeMediaElement(a),a=l}else{a=b.default.createElement("video");var y=this.options_.tag&&zt(this.options_.tag),S=lt({},y);(!ri||this.options_.nativeControlsForTouch!==!0)&&delete S.controls,Fr(a,Fe(S,{id:this.options_.techId,class:"vjs-tech"}))}a.playerId=this.options_.playerId}typeof this.options_.preload<"u"&&ln(a,"preload",this.options_.preload),this.options_.disablePictureInPicture!==void 0&&(a.disablePictureInPicture=this.options_.disablePictureInPicture);for(var x=["loop","muted","playsinline","autoplay"],U=0;U<x.length;U++){var V=x[U],z=this.options_[V];typeof z<"u"&&(z?ln(a,V,V):rs(a,V),a[V]=z)}return a},f.handleLateInit_=function(a){if(!(a.networkState===0||a.networkState===3)){if(a.readyState===0){var l=!1,y=function(){l=!0};this.on("loadstart",y);var S=function(){l||this.trigger("loadstart")};this.on("loadedmetadata",S),this.ready(function(){this.off("loadstart",y),this.off("loadedmetadata",S),l||this.trigger("loadstart")});return}var x=["loadstart"];x.push("loadedmetadata"),a.readyState>=2&&x.push("loadeddata"),a.readyState>=3&&x.push("canplay"),a.readyState>=4&&x.push("canplaythrough"),this.ready(function(){x.forEach(function(U){this.trigger(U)},this)})}},f.setScrubbing=function(a){this.isScrubbing_=a},f.scrubbing=function(){return this.isScrubbing_},f.setCurrentTime=function(a){try{this.isScrubbing_&&this.el_.fastSeek&&_?this.el_.fastSeek(a):this.el_.currentTime=a}catch(l){ae(l,"Video is not ready. (Video.js)")}},f.duration=function(){var a=this;if(this.el_.duration===1/0&&gt&&Kt&&this.el_.currentTime===0){var l=function y(){a.el_.currentTime>0&&(a.el_.duration===1/0&&a.trigger("durationchange"),a.off("timeupdate",y))};return this.on("timeupdate",l),NaN}return this.el_.duration||NaN},f.width=function(){return this.el_.offsetWidth},f.height=function(){return this.el_.offsetHeight},f.proxyWebkitFullscreen_=function(){var a=this;if("webkitDisplayingFullscreen"in this.el_){var l=function(){this.trigger("fullscreenchange",{isFullscreen:!1}),this.el_.controls&&!this.options_.nativeControlsForTouch&&this.controls()&&(this.el_.controls=!1)},y=function(){"webkitPresentationMode"in this.el_&&this.el_.webkitPresentationMode!=="picture-in-picture"&&(this.one("webkitendfullscreen",l),this.trigger("fullscreenchange",{isFullscreen:!0,nativeIOSFullscreen:!0}))};this.on("webkitbeginfullscreen",y),this.on("dispose",function(){a.off("webkitbeginfullscreen",y),a.off("webkitendfullscreen",l)})}},f.supportsFullScreen=function(){if(typeof this.el_.webkitEnterFullScreen=="function"){var a=T.default.navigator&&T.default.navigator.userAgent||"";if(/Android/.test(a)||!/Chrome|Mac OS X 10.5/.test(a))return!0}return!1},f.enterFullScreen=function(){var a=this.el_;if(a.paused&&a.networkState<=a.HAVE_METADATA)vi(this.el_.play()),this.setTimeout(function(){a.pause();try{a.webkitEnterFullScreen()}catch(l){this.trigger("fullscreenerror",l)}},0);else try{a.webkitEnterFullScreen()}catch(l){this.trigger("fullscreenerror",l)}},f.exitFullScreen=function(){if(!this.el_.webkitDisplayingFullscreen){this.trigger("fullscreenerror",new Error("The video is not fullscreen"));return}this.el_.webkitExitFullScreen()},f.requestPictureInPicture=function(){return this.el_.requestPictureInPicture()},f.requestVideoFrameCallback=function(a){return this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.requestVideoFrameCallback(a):m.prototype.requestVideoFrameCallback.call(this,a)},f.cancelVideoFrameCallback=function(a){this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.cancelVideoFrameCallback(a):m.prototype.cancelVideoFrameCallback.call(this,a)},f.src=function(a){if(a===void 0)return this.el_.src;this.setSrc(a)},f.reset=function(){v.resetMediaElement(this.el_)},f.currentSrc=function(){return this.currentSource_?this.currentSource_.src:this.el_.currentSrc},f.setControls=function(a){this.el_.controls=!!a},f.addTextTrack=function(a,l,y){return this.featuresNativeTextTracks?this.el_.addTextTrack(a,l,y):m.prototype.addTextTrack.call(this,a,l,y)},f.createRemoteTextTrack=function(a){if(!this.featuresNativeTextTracks)return m.prototype.createRemoteTextTrack.call(this,a);var l=b.default.createElement("track");return a.kind&&(l.kind=a.kind),a.label&&(l.label=a.label),(a.language||a.srclang)&&(l.srclang=a.language||a.srclang),a.default&&(l.default=a.default),a.id&&(l.id=a.id),a.src&&(l.src=a.src),l},f.addRemoteTextTrack=function(a,l){var y=m.prototype.addRemoteTextTrack.call(this,a,l);return this.featuresNativeTextTracks&&this.el().appendChild(y),y},f.removeRemoteTextTrack=function(a){if(m.prototype.removeRemoteTextTrack.call(this,a),this.featuresNativeTextTracks)for(var l=this.$$("track"),y=l.length;y--;)(a===l[y]||a===l[y].track)&&this.el().removeChild(l[y])},f.getVideoPlaybackQuality=function(){if(typeof this.el().getVideoPlaybackQuality=="function")return this.el().getVideoPlaybackQuality();var a={};return typeof this.el().webkitDroppedFrameCount<"u"&&typeof this.el().webkitDecodedFrameCount<"u"&&(a.droppedVideoFrames=this.el().webkitDroppedFrameCount,a.totalVideoFrames=this.el().webkitDecodedFrameCount),T.default.performance&&typeof T.default.performance.now=="function"?a.creationTime=T.default.performance.now():T.default.performance&&T.default.performance.timing&&typeof T.default.performance.timing.navigationStart=="number"&&(a.creationTime=T.default.Date.now()-T.default.performance.timing.navigationStart),a},v}(nt);Tl(Se,"TEST_VID",function(){if(ne()){var m=b.default.createElement("video"),v=b.default.createElement("track");return v.kind="captions",v.srclang="en",v.label="English",m.appendChild(v),m}}),Se.isSupported=function(){try{Se.TEST_VID.volume=.5}catch{return!1}return!!(Se.TEST_VID&&Se.TEST_VID.canPlayType)},Se.canPlayType=function(m){return Se.TEST_VID.canPlayType(m)},Se.canPlaySource=function(m,v){return Se.canPlayType(m.type)},Se.canControlVolume=function(){try{var m=Se.TEST_VID.volume;Se.TEST_VID.volume=m/2+.1;var v=m!==Se.TEST_VID.volume;return v&&R?(T.default.setTimeout(function(){Se&&Se.prototype&&(Se.prototype.featuresVolumeControl=m!==Se.TEST_VID.volume)}),!1):v}catch{return!1}},Se.canMuteVolume=function(){try{var m=Se.TEST_VID.muted;return Se.TEST_VID.muted=!m,Se.TEST_VID.muted?ln(Se.TEST_VID,"muted","muted"):rs(Se.TEST_VID,"muted","muted"),m!==Se.TEST_VID.muted}catch{return!1}},Se.canControlPlaybackRate=function(){if(gt&&Kt&&on<58)return!1;try{var m=Se.TEST_VID.playbackRate;return Se.TEST_VID.playbackRate=m/2+.1,m!==Se.TEST_VID.playbackRate}catch{return!1}},Se.canOverrideAttributes=function(){try{var m=function(){};Object.defineProperty(b.default.createElement("video"),"src",{get:m,set:m}),Object.defineProperty(b.default.createElement("audio"),"src",{get:m,set:m}),Object.defineProperty(b.default.createElement("video"),"innerHTML",{get:m,set:m}),Object.defineProperty(b.default.createElement("audio"),"innerHTML",{get:m,set:m})}catch{return!1}return!0},Se.supportsNativeTextTracks=function(){return _||R&&Kt},Se.supportsNativeVideoTracks=function(){return!!(Se.TEST_VID&&Se.TEST_VID.videoTracks)},Se.supportsNativeAudioTracks=function(){return!!(Se.TEST_VID&&Se.TEST_VID.audioTracks)},Se.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(m){var v=m[0],f=m[1];Tl(Se.prototype,v,function(){return Se[f]()},!0)}),Se.prototype.featuresVolumeControl=Se.canControlVolume(),Se.prototype.movingMediaElementInDOM=!R,Se.prototype.featuresFullscreenResize=!0,Se.prototype.featuresProgressEvents=!0,Se.prototype.featuresTimeupdateEvents=!0,Se.prototype.featuresVideoFrameCallback=!!(Se.TEST_VID&&Se.TEST_VID.requestVideoFrameCallback);var oa;Se.patchCanPlayType=function(){Dn>=4&&!an&&!Kt&&(oa=Se.TEST_VID&&Se.TEST_VID.constructor.prototype.canPlayType,Se.TEST_VID.constructor.prototype.canPlayType=function(m){var v=/^application\/(?:x-|vnd\.apple\.)mpegurl/i;return m&&v.test(m)?"maybe":oa.call(this,m)})},Se.unpatchCanPlayType=function(){var m=Se.TEST_VID.constructor.prototype.canPlayType;return oa&&(Se.TEST_VID.constructor.prototype.canPlayType=oa),m},Se.patchCanPlayType(),Se.disposeMediaElement=function(m){if(m){for(m.parentNode&&m.parentNode.removeChild(m);m.hasChildNodes();)m.removeChild(m.firstChild);m.removeAttribute("src"),typeof m.load=="function"&&function(){try{m.load()}catch{}}()}},Se.resetMediaElement=function(m){if(m){for(var v=m.querySelectorAll("source"),f=v.length;f--;)m.removeChild(v[f]);m.removeAttribute("src"),typeof m.load=="function"&&function(){try{m.load()}catch{}}()}},["muted","defaultMuted","autoplay","controls","loop","playsinline"].forEach(function(m){Se.prototype[m]=function(){return this.el_[m]||this.el_.hasAttribute(m)}}),["muted","defaultMuted","autoplay","loop","playsinline"].forEach(function(m){Se.prototype["set"+dt(m)]=function(v){this.el_[m]=v,v?this.el_.setAttribute(m,m):this.el_.removeAttribute(m)}}),["paused","currentTime","buffered","volume","poster","preload","error","seeking","seekable","ended","playbackRate","defaultPlaybackRate","disablePictureInPicture","played","networkState","readyState","videoWidth","videoHeight","crossOrigin"].forEach(function(m){Se.prototype[m]=function(){return this.el_[m]}}),["volume","src","poster","preload","playbackRate","defaultPlaybackRate","disablePictureInPicture","crossOrigin"].forEach(function(m){Se.prototype["set"+dt(m)]=function(v){this.el_[m]=v}}),["pause","load","play"].forEach(function(m){Se.prototype[m]=function(){return this.el_[m]()}}),nt.withSourceHandlers(Se),Se.nativeSourceHandler={},Se.nativeSourceHandler.canPlayType=function(m){try{return Se.TEST_VID.canPlayType(m)}catch{return""}},Se.nativeSourceHandler.canHandleSource=function(m,v){if(m.type)return Se.nativeSourceHandler.canPlayType(m.type);if(m.src){var f=Wo(m.src);return Se.nativeSourceHandler.canPlayType("video/"+f)}return""},Se.nativeSourceHandler.handleSource=function(m,v,f){v.setSrc(m.src)},Se.nativeSourceHandler.dispose=function(){},Se.registerSourceHandler(Se.nativeSourceHandler),nt.registerTech("Html5",Se);var nd=["progress","abort","suspend","emptied","stalled","loadedmetadata","loadeddata","timeupdate","resize","volumechange","texttrackchange"],bl={canplay:"CanPlay",canplaythrough:"CanPlayThrough",playing:"Playing",seeked:"Seeked"},_l=["tiny","xsmall","small","medium","large","xlarge","huge"],la={};_l.forEach(function(m){var v=m.charAt(0)==="x"?"x-"+m.substring(1):m;la[m]="vjs-layout-"+v});var Sv={tiny:210,xsmall:320,small:425,medium:768,large:1440,xlarge:2560,huge:1/0},mt=function(m){L.default(v,m);function v(c,a,l){var y;if(c.id=c.id||a.id||"vjs_video_"+Yt(),a=Fe(v.getTagSettings(c),a),a.initChildren=!1,a.createEl=!1,a.evented=!1,a.reportTouchActivity=!1,!a.language)if(typeof c.closest=="function"){var S=c.closest("[lang]");S&&S.getAttribute&&(a.language=S.getAttribute("lang"))}else for(var x=c;x&&x.nodeType===1;){if(zt(x).hasOwnProperty("lang")){a.language=x.getAttribute("lang");break}x=x.parentNode}if(y=m.call(this,null,a,l)||this,y.boundDocumentFullscreenChange_=function(j){return y.documentFullscreenChange_(j)},y.boundFullWindowOnEscKey_=function(j){return y.fullWindowOnEscKey(j)},y.boundUpdateStyleEl_=function(j){return y.updateStyleEl_(j)},y.boundApplyInitTime_=function(j){return y.applyInitTime_(j)},y.boundUpdateCurrentBreakpoint_=function(j){return y.updateCurrentBreakpoint_(j)},y.boundHandleTechClick_=function(j){return y.handleTechClick_(j)},y.boundHandleTechDoubleClick_=function(j){return y.handleTechDoubleClick_(j)},y.boundHandleTechTouchStart_=function(j){return y.handleTechTouchStart_(j)},y.boundHandleTechTouchMove_=function(j){return y.handleTechTouchMove_(j)},y.boundHandleTechTouchEnd_=function(j){return y.handleTechTouchEnd_(j)},y.boundHandleTechTap_=function(j){return y.handleTechTap_(j)},y.isFullscreen_=!1,y.log=ie(y.id_),y.fsApi_=Z,y.isPosterFromTech_=!1,y.queuedCallbacks_=[],y.isReady_=!1,y.hasStarted_=!1,y.userActive_=!1,y.debugEnabled_=!1,y.audioOnlyMode_=!1,y.audioPosterMode_=!1,y.audioOnlyCache_={playerHeight:null,hiddenChildren:[]},!y.options_||!y.options_.techOrder||!y.options_.techOrder.length)throw new Error("No techOrder specified. Did you overwrite videojs.options instead of just changing the properties you want to override?");if(y.tag=c,y.tagAttributes=c&&zt(c),y.language(y.options_.language),a.languages){var U={};Object.getOwnPropertyNames(a.languages).forEach(function(j){U[j.toLowerCase()]=a.languages[j]}),y.languages_=U}else y.languages_=v.prototype.options_.languages;y.resetCache_(),y.poster_=a.poster||"",y.controls_=!!a.controls,c.controls=!1,c.removeAttribute("controls"),y.changingSrc_=!1,y.playCallbacks_=[],y.playTerminatedQueue_=[],c.hasAttribute("autoplay")?y.autoplay(!0):y.autoplay(y.options_.autoplay),a.plugins&&Object.keys(a.plugins).forEach(function(j){if(typeof y[j]!="function")throw new Error('plugin "'+j+'" does not exist')}),y.scrubbing_=!1,y.el_=y.createEl(),ir(A.default(y),{eventBusKey:"el_"}),y.fsApi_.requestFullscreen&&(Ot(b.default,y.fsApi_.fullscreenchange,y.boundDocumentFullscreenChange_),y.on(y.fsApi_.fullscreenchange,y.boundDocumentFullscreenChange_)),y.fluid_&&y.on(["playerreset","resize"],y.boundUpdateStyleEl_);var V=lt(y.options_);a.plugins&&Object.keys(a.plugins).forEach(function(j){y[j](a.plugins[j])}),a.debug&&y.debug(!0),y.options_.playerOptions=V,y.middleware_=[],y.playbackRates(a.playbackRates),y.initChildren(),y.isAudio(c.nodeName.toLowerCase()==="audio"),y.controls()?y.addClass("vjs-controls-enabled"):y.addClass("vjs-controls-disabled"),y.el_.setAttribute("role","region"),y.isAudio()?y.el_.setAttribute("aria-label",y.localize("Audio Player")):y.el_.setAttribute("aria-label",y.localize("Video Player")),y.isAudio()&&y.addClass("vjs-audio"),y.flexNotSupported_()&&y.addClass("vjs-no-flex"),ri&&y.addClass("vjs-touch-enabled"),R||y.addClass("vjs-workinghover"),v.players[y.id_]=A.default(y);var z=H.split(".")[0];return y.addClass("vjs-v"+z),y.userActive(!0),y.reportUserActivity(),y.one("play",function(j){return y.listenForUserActivity_(j)}),y.on("stageclick",function(j){return y.handleStageClick_(j)}),y.on("keydown",function(j){return y.handleKeyDown(j)}),y.on("languagechange",function(j){return y.handleLanguagechange(j)}),y.breakpoints(y.options_.breakpoints),y.responsive(y.options_.responsive),y.on("ready",function(){y.audioPosterMode(y.options_.audioPosterMode),y.audioOnlyMode(y.options_.audioOnlyMode)}),y}var f=v.prototype;return f.dispose=function(){var a=this;this.trigger("dispose"),this.off("dispose"),bt(b.default,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),bt(b.default,"keydown",this.boundFullWindowOnEscKey_),this.styleEl_&&this.styleEl_.parentNode&&(this.styleEl_.parentNode.removeChild(this.styleEl_),this.styleEl_=null),v.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_&&(this.playerElIngest_=null),this.tag&&(this.tag=null),Vy(this),Ft.names.forEach(function(l){var y=Ft[l],S=a[y.getterName]();S&&S.off&&S.off()}),m.prototype.dispose.call(this,{restoreEl:this.options_.restoreEl})},f.createEl=function(){var a=this.tag,l,y=this.playerElIngest_=a.parentNode&&a.parentNode.hasAttribute&&a.parentNode.hasAttribute("data-vjs-player"),S=this.tag.tagName.toLowerCase()==="video-js";y?l=this.el_=a.parentNode:S||(l=this.el_=m.prototype.createEl.call(this,"div"));var x=zt(a);if(S){for(l=this.el_=a,a=this.tag=b.default.createElement("video");l.children.length;)a.appendChild(l.firstChild);$i(l,"video-js")||ai(l,"video-js"),l.appendChild(a),y=this.playerElIngest_=l,Object.keys(l).forEach(function(we){try{a[we]=l[we]}catch{}})}if(a.setAttribute("tabindex","-1"),x.tabindex="-1",(qt||Kt&&Wt)&&(a.setAttribute("role","application"),x.role="application"),a.removeAttribute("width"),a.removeAttribute("height"),"width"in x&&delete x.width,"height"in x&&delete x.height,Object.getOwnPropertyNames(x).forEach(function(we){S&&we==="class"||l.setAttribute(we,x[we]),S&&a.setAttribute(we,x[we])}),a.playerId=a.id,a.id+="_html5_api",a.className="vjs-tech",a.player=l.player=this,this.addClass("vjs-paused"),T.default.VIDEOJS_NO_DYNAMIC_STYLE!==!0){this.styleEl_=as("vjs-styles-dimensions");var U=yi(".vjs-styles-defaults"),V=yi("head");V.insertBefore(this.styleEl_,U?U.nextSibling:V.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);for(var z=a.getElementsByTagName("a"),j=0;j<z.length;j++){var he=z.item(j);ai(he,"vjs-hidden"),he.setAttribute("hidden","hidden")}return a.initNetworkState_=a.networkState,a.parentNode&&!y&&a.parentNode.insertBefore(l,a),Ws(a,l),this.children_.unshift(a),this.el_.setAttribute("lang",this.language_),this.el_.setAttribute("translate","no"),this.el_=l,l},f.crossOrigin=function(a){if(!a)return this.techGet_("crossOrigin");if(a!=="anonymous"&&a!=="use-credentials"){ae.warn('crossOrigin must be "anonymous" or "use-credentials", given "'+a+'"');return}this.techCall_("setCrossOrigin",a)},f.width=function(a){return this.dimension("width",a)},f.height=function(a){return this.dimension("height",a)},f.dimension=function(a,l){var y=a+"_";if(l===void 0)return this[y]||0;if(l===""||l==="auto"){this[y]=void 0,this.updateStyleEl_();return}var S=parseFloat(l);if(isNaN(S)){ae.error('Improper value "'+l+'" supplied for for '+a);return}this[y]=S,this.updateStyleEl_()},f.fluid=function(a){var l=this;if(a===void 0)return!!this.fluid_;this.fluid_=!!a,Me(this)&&this.off(["playerreset","resize"],this.boundUpdateStyleEl_),a?(this.addClass("vjs-fluid"),this.fill(!1),st(this,function(){l.on(["playerreset","resize"],l.boundUpdateStyleEl_)})):this.removeClass("vjs-fluid"),this.updateStyleEl_()},f.fill=function(a){if(a===void 0)return!!this.fill_;this.fill_=!!a,a?(this.addClass("vjs-fill"),this.fluid(!1)):this.removeClass("vjs-fill")},f.aspectRatio=function(a){if(a===void 0)return this.aspectRatio_;if(!/^\d+\:\d+$/.test(a))throw new Error("Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.");this.aspectRatio_=a,this.fluid(!0),this.updateStyleEl_()},f.updateStyleEl_=function(){if(T.default.VIDEOJS_NO_DYNAMIC_STYLE===!0){var a=typeof this.width_=="number"?this.width_:this.options_.width,l=typeof this.height_=="number"?this.height_:this.options_.height,y=this.tech_&&this.tech_.el();y&&(a>=0&&(y.width=a),l>=0&&(y.height=l));return}var S,x,U,V;this.aspectRatio_!==void 0&&this.aspectRatio_!=="auto"?U=this.aspectRatio_:this.videoWidth()>0?U=this.videoWidth()+":"+this.videoHeight():U="16:9";var z=U.split(":"),j=z[1]/z[0];this.width_!==void 0?S=this.width_:this.height_!==void 0?S=this.height_/j:S=this.videoWidth()||300,this.height_!==void 0?x=this.height_:x=S*j,/^[^a-zA-Z]/.test(this.id())?V="dimensions-"+this.id():V=this.id()+"-dimensions",this.addClass(V),hn(this.styleEl_,`
      .`+V+` {
        width: `+S+`px;
        height: `+x+`px;
      }

      .`+V+`.vjs-fluid:not(.vjs-audio-only-mode) {
        padding-top: `+j*100+`%;
      }
    `)},f.loadTech_=function(a,l){var y=this;this.tech_&&this.unloadTech_();var S=dt(a),x=a.charAt(0).toLowerCase()+a.slice(1);S!=="Html5"&&this.tag&&(nt.getTech("Html5").disposeMediaElement(this.tag),this.tag.player=null,this.tag=null),this.techName_=S,this.isReady_=!1;var U=this.autoplay();(typeof this.autoplay()=="string"||this.autoplay()===!0&&this.options_.normalizeAutoplay)&&(U=!1);var V={source:l,autoplay:U,nativeControlsForTouch:this.options_.nativeControlsForTouch,playerId:this.id(),techId:this.id()+"_"+x+"_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,Promise:this.options_.Promise};Ft.names.forEach(function(j){var he=Ft[j];V[he.getterName]=y[he.privateName]}),Fe(V,this.options_[S]),Fe(V,this.options_[x]),Fe(V,this.options_[a.toLowerCase()]),this.tag&&(V.tag=this.tag),l&&l.src===this.cache_.src&&this.cache_.currentTime>0&&(V.startTime=this.cache_.currentTime);var z=nt.getTech(a);if(!z)throw new Error("No Tech named '"+S+"' exists! '"+S+"' should be registered using videojs.registerTech()'");this.tech_=new z(V),this.tech_.ready(it(this,this.handleTechReady_),!0),lh.jsonToTextTracks(this.textTracksJson_||[],this.tech_),nd.forEach(function(j){y.on(y.tech_,j,function(he){return y["handleTech"+dt(j)+"_"](he)})}),Object.keys(bl).forEach(function(j){y.on(y.tech_,j,function(he){if(y.tech_.playbackRate()===0&&y.tech_.seeking()){y.queuedCallbacks_.push({callback:y["handleTech"+bl[j]+"_"].bind(y),event:he});return}y["handleTech"+bl[j]+"_"](he)})}),this.on(this.tech_,"loadstart",function(j){return y.handleTechLoadStart_(j)}),this.on(this.tech_,"sourceset",function(j){return y.handleTechSourceset_(j)}),this.on(this.tech_,"waiting",function(j){return y.handleTechWaiting_(j)}),this.on(this.tech_,"ended",function(j){return y.handleTechEnded_(j)}),this.on(this.tech_,"seeking",function(j){return y.handleTechSeeking_(j)}),this.on(this.tech_,"play",function(j){return y.handleTechPlay_(j)}),this.on(this.tech_,"firstplay",function(j){return y.handleTechFirstPlay_(j)}),this.on(this.tech_,"pause",function(j){return y.handleTechPause_(j)}),this.on(this.tech_,"durationchange",function(j){return y.handleTechDurationChange_(j)}),this.on(this.tech_,"fullscreenchange",function(j,he){return y.handleTechFullscreenChange_(j,he)}),this.on(this.tech_,"fullscreenerror",function(j,he){return y.handleTechFullscreenError_(j,he)}),this.on(this.tech_,"enterpictureinpicture",function(j){return y.handleTechEnterPictureInPicture_(j)}),this.on(this.tech_,"leavepictureinpicture",function(j){return y.handleTechLeavePictureInPicture_(j)}),this.on(this.tech_,"error",function(j){return y.handleTechError_(j)}),this.on(this.tech_,"posterchange",function(j){return y.handleTechPosterChange_(j)}),this.on(this.tech_,"textdata",function(j){return y.handleTechTextData_(j)}),this.on(this.tech_,"ratechange",function(j){return y.handleTechRateChange_(j)}),this.on(this.tech_,"loadedmetadata",this.boundUpdateStyleEl_),this.usingNativeControls(this.techGet_("controls")),this.controls()&&!this.usingNativeControls()&&this.addTechControlsListeners_(),this.tech_.el().parentNode!==this.el()&&(S!=="Html5"||!this.tag)&&Ws(this.tech_.el(),this.el()),this.tag&&(this.tag.player=null,this.tag=null)},f.unloadTech_=function(){var a=this;Ft.names.forEach(function(l){var y=Ft[l];a[y.privateName]=a[y.getterName]()}),this.textTracksJson_=lh.textTracksToJson(this.tech_),this.isReady_=!1,this.tech_.dispose(),this.tech_=!1,this.isPosterFromTech_&&(this.poster_="",this.trigger("posterchange")),this.isPosterFromTech_=!1},f.tech=function(a){return a===void 0&&ae.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_},f.addTechControlsListeners_=function(){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_)},f.removeTechControlsListeners_=function(){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_)},f.handleTechReady_=function(){this.triggerReady(),this.cache_.volume&&this.techCall_("setVolume",this.cache_.volume),this.handleTechPosterChange_(),this.handleTechDurationChange_()},f.handleTechLoadStart_=function(){this.removeClass("vjs-ended"),this.removeClass("vjs-seeking"),this.error(null),this.handleTechDurationChange_(),this.paused()?(this.hasStarted(!1),this.trigger("loadstart")):(this.trigger("loadstart"),this.trigger("firstplay")),this.manualAutoplay_(this.autoplay()===!0&&this.options_.normalizeAutoplay?"play":this.autoplay())},f.manualAutoplay_=function(a){var l=this;if(!(!this.tech_||typeof a!="string")){var y=function(){var U=l.muted();l.muted(!0);var V=function(){l.muted(U)};l.playTerminatedQueue_.push(V);var z=l.play();if(nr(z))return z.catch(function(j){throw V(),new Error("Rejection at manualAutoplay. Restoring muted value. "+(j||""))})},S;if(a==="any"&&!this.muted()?(S=this.play(),nr(S)&&(S=S.catch(y))):a==="muted"&&!this.muted()?S=y():S=this.play(),!!nr(S))return S.then(function(){l.trigger({type:"autoplay-success",autoplay:a})}).catch(function(){l.trigger({type:"autoplay-failure",autoplay:a})})}},f.updateSourceCaches_=function(a){a===void 0&&(a="");var l=a,y="";typeof l!="string"&&(l=a.src,y=a.type),this.cache_.source=this.cache_.source||{},this.cache_.sources=this.cache_.sources||[],l&&!y&&(y=qy(this,l)),this.cache_.source=lt({},a,{src:l,type:y});for(var S=this.cache_.sources.filter(function(he){return he.src&&he.src===l}),x=[],U=this.$$("source"),V=[],z=0;z<U.length;z++){var j=zt(U[z]);x.push(j),j.src&&j.src===l&&V.push(j.src)}V.length&&!S.length?this.cache_.sources=x:S.length||(this.cache_.sources=[this.cache_.source]),this.cache_.src=l},f.handleTechSourceset_=function(a){var l=this;if(!this.changingSrc_){var y=function(V){return l.updateSourceCaches_(V)},S=this.currentSource().src,x=a.src;S&&!/^blob:/.test(S)&&/^blob:/.test(x)&&(!this.lastSource_||this.lastSource_.tech!==x&&this.lastSource_.player!==S)&&(y=function(){}),y(x),a.src||this.tech_.any(["sourceset","loadstart"],function(U){if(U.type!=="sourceset"){var V=l.techGet("currentSrc");l.lastSource_.tech=V,l.updateSourceCaches_(V)}})}this.lastSource_={player:this.currentSource().src,tech:a.src},this.trigger({src:a.src,type:"sourceset"})},f.hasStarted=function(a){if(a===void 0)return this.hasStarted_;a!==this.hasStarted_&&(this.hasStarted_=a,this.hasStarted_?(this.addClass("vjs-has-started"),this.trigger("firstplay")):this.removeClass("vjs-has-started"))},f.handleTechPlay_=function(){this.removeClass("vjs-ended"),this.removeClass("vjs-paused"),this.addClass("vjs-playing"),this.hasStarted(!0),this.trigger("play")},f.handleTechRateChange_=function(){this.tech_.playbackRate()>0&&this.cache_.lastPlaybackRate===0&&(this.queuedCallbacks_.forEach(function(a){return a.callback(a.event)}),this.queuedCallbacks_=[]),this.cache_.lastPlaybackRate=this.tech_.playbackRate(),this.trigger("ratechange")},f.handleTechWaiting_=function(){var a=this;this.addClass("vjs-waiting"),this.trigger("waiting");var l=this.currentTime(),y=function S(){l!==a.currentTime()&&(a.removeClass("vjs-waiting"),a.off("timeupdate",S))};this.on("timeupdate",y)},f.handleTechCanPlay_=function(){this.removeClass("vjs-waiting"),this.trigger("canplay")},f.handleTechCanPlayThrough_=function(){this.removeClass("vjs-waiting"),this.trigger("canplaythrough")},f.handleTechPlaying_=function(){this.removeClass("vjs-waiting"),this.trigger("playing")},f.handleTechSeeking_=function(){this.addClass("vjs-seeking"),this.trigger("seeking")},f.handleTechSeeked_=function(){this.removeClass("vjs-seeking"),this.removeClass("vjs-ended"),this.trigger("seeked")},f.handleTechFirstPlay_=function(){this.options_.starttime&&(ae.warn("Passing the `starttime` option to the player will be deprecated in 6.0"),this.currentTime(this.options_.starttime)),this.addClass("vjs-has-started"),this.trigger("firstplay")},f.handleTechPause_=function(){this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.trigger("pause")},f.handleTechEnded_=function(){this.addClass("vjs-ended"),this.removeClass("vjs-waiting"),this.options_.loop?(this.currentTime(0),this.play()):this.paused()||this.pause(),this.trigger("ended")},f.handleTechDurationChange_=function(){this.duration(this.techGet_("duration"))},f.handleTechClick_=function(a){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,a):this.paused()?vi(this.play()):this.pause())},f.handleTechDoubleClick_=function(a){if(this.controls_){var l=Array.prototype.some.call(this.$$(".vjs-control-bar, .vjs-modal-dialog"),function(y){return y.contains(a.target)});l||(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,a):this.isFullscreen()?this.exitFullscreen():this.requestFullscreen())}},f.handleTechTap_=function(){this.userActive(!this.userActive())},f.handleTechTouchStart_=function(){this.userWasActive=this.userActive()},f.handleTechTouchMove_=function(){this.userWasActive&&this.reportUserActivity()},f.handleTechTouchEnd_=function(a){a.cancelable&&a.preventDefault()},f.handleStageClick_=function(){this.reportUserActivity()},f.toggleFullscreenClass_=function(){this.isFullscreen()?this.addClass("vjs-fullscreen"):this.removeClass("vjs-fullscreen")},f.documentFullscreenChange_=function(a){var l=a.target.player;if(!(l&&l!==this)){var y=this.el(),S=b.default[this.fsApi_.fullscreenElement]===y;!S&&y.matches?S=y.matches(":"+this.fsApi_.fullscreen):!S&&y.msMatchesSelector&&(S=y.msMatchesSelector(":"+this.fsApi_.fullscreen)),this.isFullscreen(S)}},f.handleTechFullscreenChange_=function(a,l){var y=this;l&&(l.nativeIOSFullscreen&&(this.addClass("vjs-ios-native-fs"),this.tech_.one("webkitendfullscreen",function(){y.removeClass("vjs-ios-native-fs")})),this.isFullscreen(l.isFullscreen))},f.handleTechFullscreenError_=function(a,l){this.trigger("fullscreenerror",l)},f.togglePictureInPictureClass_=function(){this.isInPictureInPicture()?this.addClass("vjs-picture-in-picture"):this.removeClass("vjs-picture-in-picture")},f.handleTechEnterPictureInPicture_=function(a){this.isInPictureInPicture(!0)},f.handleTechLeavePictureInPicture_=function(a){this.isInPictureInPicture(!1)},f.handleTechError_=function(){var a=this.tech_.error();this.error(a)},f.handleTechTextData_=function(){var a=null;arguments.length>1&&(a=arguments[1]),this.trigger("textdata",a)},f.getCache=function(){return this.cache_},f.resetCache_=function(){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}},f.techCall_=function(a,l){this.ready(function(){if(a in $y)return Uy(this.middleware_,this.tech_,a,l);if(a in bh)return Th(this.middleware_,this.tech_,a,l);try{this.tech_&&this.tech_[a](l)}catch(y){throw ae(y),y}},!0)},f.techGet_=function(a){if(!(!this.tech_||!this.tech_.isReady_)){if(a in Hy)return By(this.middleware_,this.tech_,a);if(a in bh)return Th(this.middleware_,this.tech_,a);try{return this.tech_[a]()}catch(l){throw this.tech_[a]===void 0?(ae("Video.js: "+a+" method not defined for "+this.techName_+" playback technology.",l),l):l.name==="TypeError"?(ae("Video.js: "+a+" unavailable on "+this.techName_+" playback technology element.",l),this.tech_.isReady_=!1,l):(ae(l),l)}}},f.play=function(){var a=this,l=this.options_.Promise||T.default.Promise;return l?new l(function(y){a.play_(y)}):this.play_()},f.play_=function(a){var l=this;a===void 0&&(a=vi),this.playCallbacks_.push(a);var y=!!(!this.changingSrc_&&(this.src()||this.currentSrc())),S=!!(_||R);if(this.waitToPlay_&&(this.off(["ready","loadstart"],this.waitToPlay_),this.waitToPlay_=null),!this.isReady_||!y){this.waitToPlay_=function(V){l.play_()},this.one(["ready","loadstart"],this.waitToPlay_),!y&&S&&this.load();return}var x=this.techGet_("play"),U=S&&this.hasClass("vjs-ended");U&&this.resetProgressBar_(),x===null?this.runPlayTerminatedQueue_():this.runPlayCallbacks_(x)},f.runPlayTerminatedQueue_=function(){var a=this.playTerminatedQueue_.slice(0);this.playTerminatedQueue_=[],a.forEach(function(l){l()})},f.runPlayCallbacks_=function(a){var l=this.playCallbacks_.slice(0);this.playCallbacks_=[],this.playTerminatedQueue_=[],l.forEach(function(y){y(a)})},f.pause=function(){this.techCall_("pause")},f.paused=function(){return this.techGet_("paused")!==!1},f.played=function(){return this.techGet_("played")||Bn(0,0)},f.scrubbing=function(a){if(typeof a>"u")return this.scrubbing_;this.scrubbing_=!!a,this.techCall_("setScrubbing",this.scrubbing_),a?this.addClass("vjs-scrubbing"):this.removeClass("vjs-scrubbing")},f.currentTime=function(a){if(typeof a<"u"){if(a<0&&(a=0),!this.isReady_||this.changingSrc_||!this.tech_||!this.tech_.isReady_){this.cache_.initTime=a,this.off("canplay",this.boundApplyInitTime_),this.one("canplay",this.boundApplyInitTime_);return}this.techCall_("setCurrentTime",a),this.cache_.initTime=0;return}return this.cache_.currentTime=this.techGet_("currentTime")||0,this.cache_.currentTime},f.applyInitTime_=function(){this.currentTime(this.cache_.initTime)},f.duration=function(a){if(a===void 0)return this.cache_.duration!==void 0?this.cache_.duration:NaN;a=parseFloat(a),a<0&&(a=1/0),a!==this.cache_.duration&&(this.cache_.duration=a,a===1/0?this.addClass("vjs-live"):this.removeClass("vjs-live"),isNaN(a)||this.trigger("durationchange"))},f.remainingTime=function(){return this.duration()-this.currentTime()},f.remainingTimeDisplay=function(){return Math.floor(this.duration())-Math.floor(this.currentTime())},f.buffered=function(){var a=this.techGet_("buffered");return(!a||!a.length)&&(a=Bn(0,0)),a},f.bufferedPercent=function(){return oh(this.buffered(),this.duration())},f.bufferedEnd=function(){var a=this.buffered(),l=this.duration(),y=a.end(a.length-1);return y>l&&(y=l),y},f.volume=function(a){var l;if(a!==void 0){l=Math.max(0,Math.min(1,parseFloat(a))),this.cache_.volume=l,this.techCall_("setVolume",l),l>0&&this.lastVolume_(l);return}return l=parseFloat(this.techGet_("volume")),isNaN(l)?1:l},f.muted=function(a){if(a!==void 0){this.techCall_("setMuted",a);return}return this.techGet_("muted")||!1},f.defaultMuted=function(a){return a!==void 0?this.techCall_("setDefaultMuted",a):this.techGet_("defaultMuted")||!1},f.lastVolume_=function(a){if(a!==void 0&&a!==0){this.cache_.lastVolume=a;return}return this.cache_.lastVolume},f.supportsFullScreen=function(){return this.techGet_("supportsFullScreen")||!1},f.isFullscreen=function(a){if(a!==void 0){var l=this.isFullscreen_;this.isFullscreen_=!!a,this.isFullscreen_!==l&&this.fsApi_.prefixed&&this.trigger("fullscreenchange"),this.toggleFullscreenClass_();return}return this.isFullscreen_},f.requestFullscreen=function(a){var l=this.options_.Promise||T.default.Promise;if(l){var y=this;return new l(function(S,x){function U(){y.off("fullscreenerror",z),y.off("fullscreenchange",V)}function V(){U(),S()}function z(he,we){U(),x(we)}y.one("fullscreenchange",V),y.one("fullscreenerror",z);var j=y.requestFullscreenHelper_(a);j&&(j.then(U,U),j.then(S,x))})}return this.requestFullscreenHelper_()},f.requestFullscreenHelper_=function(a){var l=this,y;if(this.fsApi_.prefixed||(y=this.options_.fullscreen&&this.options_.fullscreen.options||{},a!==void 0&&(y=a)),this.fsApi_.requestFullscreen){var S=this.el_[this.fsApi_.requestFullscreen](y);return S&&S.then(function(){return l.isFullscreen(!0)},function(){return l.isFullscreen(!1)}),S}else this.tech_.supportsFullScreen()&&!this.options_.preferFullWindow?this.techCall_("enterFullScreen"):this.enterFullWindow()},f.exitFullscreen=function(){var a=this.options_.Promise||T.default.Promise;if(a){var l=this;return new a(function(y,S){function x(){l.off("fullscreenerror",V),l.off("fullscreenchange",U)}function U(){x(),y()}function V(j,he){x(),S(he)}l.one("fullscreenchange",U),l.one("fullscreenerror",V);var z=l.exitFullscreenHelper_();z&&(z.then(x,x),z.then(y,S))})}return this.exitFullscreenHelper_()},f.exitFullscreenHelper_=function(){var a=this;if(this.fsApi_.requestFullscreen){var l=b.default[this.fsApi_.exitFullscreen]();return l&&vi(l.then(function(){return a.isFullscreen(!1)})),l}else this.tech_.supportsFullScreen()&&!this.options_.preferFullWindow?this.techCall_("exitFullScreen"):this.exitFullWindow()},f.enterFullWindow=function(){this.isFullscreen(!0),this.isFullWindow=!0,this.docOrigOverflow=b.default.documentElement.style.overflow,Ot(b.default,"keydown",this.boundFullWindowOnEscKey_),b.default.documentElement.style.overflow="hidden",ai(b.default.body,"vjs-full-window"),this.trigger("enterFullWindow")},f.fullWindowOnEscKey=function(a){w.default.isEventKey(a,"Esc")&&this.isFullscreen()===!0&&(this.isFullWindow?this.exitFullWindow():this.exitFullscreen())},f.exitFullWindow=function(){this.isFullscreen(!1),this.isFullWindow=!1,bt(b.default,"keydown",this.boundFullWindowOnEscKey_),b.default.documentElement.style.overflow=this.docOrigOverflow,On(b.default.body,"vjs-full-window"),this.trigger("exitFullWindow")},f.disablePictureInPicture=function(a){if(a===void 0)return this.techGet_("disablePictureInPicture");this.techCall_("setDisablePictureInPicture",a),this.options_.disablePictureInPicture=a,this.trigger("disablepictureinpicturechanged")},f.isInPictureInPicture=function(a){if(a!==void 0){this.isInPictureInPicture_=!!a,this.togglePictureInPictureClass_();return}return!!this.isInPictureInPicture_},f.requestPictureInPicture=function(){if("pictureInPictureEnabled"in b.default&&this.disablePictureInPicture()===!1)return this.techGet_("requestPictureInPicture")},f.exitPictureInPicture=function(){if("pictureInPictureEnabled"in b.default)return b.default.exitPictureInPicture()},f.handleKeyDown=function(a){var l=this.options_.userActions;if(!(!l||!l.hotkeys)){var y=function(x){var U=x.tagName.toLowerCase();if(x.isContentEditable)return!0;var V=["button","checkbox","hidden","radio","reset","submit"];if(U==="input")return V.indexOf(x.type)===-1;var z=["textarea"];return z.indexOf(U)!==-1};y(this.el_.ownerDocument.activeElement)||(typeof l.hotkeys=="function"?l.hotkeys.call(this,a):this.handleHotkeys(a))}},f.handleHotkeys=function(a){var l=this.options_.userActions?this.options_.userActions.hotkeys:{},y=l.fullscreenKey,S=y===void 0?function(je){return w.default.isEventKey(je,"f")}:y,x=l.muteKey,U=x===void 0?function(je){return w.default.isEventKey(je,"m")}:x,V=l.playPauseKey,z=V===void 0?function(je){return w.default.isEventKey(je,"k")||w.default.isEventKey(je,"Space")}:V;if(S.call(this,a)){a.preventDefault(),a.stopPropagation();var j=pe.getComponent("FullscreenToggle");b.default[this.fsApi_.fullscreenEnabled]!==!1&&j.prototype.handleClick.call(this,a)}else if(U.call(this,a)){a.preventDefault(),a.stopPropagation();var he=pe.getComponent("MuteToggle");he.prototype.handleClick.call(this,a)}else if(z.call(this,a)){a.preventDefault(),a.stopPropagation();var we=pe.getComponent("PlayToggle");we.prototype.handleClick.call(this,a)}},f.canPlayType=function(a){for(var l,y=0,S=this.options_.techOrder;y<S.length;y++){var x=S[y],U=nt.getTech(x);if(U||(U=pe.getComponent(x)),!U){ae.error('The "'+x+'" tech is undefined. Skipped browser support check for that tech.');continue}if(U.isSupported()&&(l=U.canPlayType(a),l))return l}return""},f.selectSource=function(a){var l=this,y=this.options_.techOrder.map(function(z){return[z,nt.getTech(z)]}).filter(function(z){var j=z[0],he=z[1];return he?he.isSupported():(ae.error('The "'+j+'" tech is undefined. Skipped browser support check for that tech.'),!1)}),S=function(j,he,we){var je;return j.some(function(jn){return he.some(function(bi){if(je=we(jn,bi),je)return!0})}),je},x,U=function(j){return function(he,we){return j(we,he)}},V=function(j,he){var we=j[0],je=j[1];if(je.canPlaySource(he,l.options_[we.toLowerCase()]))return{source:he,tech:we}};return this.options_.sourceOrder?x=S(a,y,U(V)):x=S(y,a,V),x||!1},f.handleSrc_=function(a,l){var y=this;if(typeof a>"u")return this.cache_.src||"";this.resetRetryOnError_&&this.resetRetryOnError_();var S=Wy(a);if(!S.length){this.setTimeout(function(){this.error({code:4,message:this.options_.notSupportedMessage})},0);return}if(this.changingSrc_=!0,l||(this.cache_.sources=S),this.updateSourceCaches_(S[0]),Fy(this,S[0],function(V,z){y.middleware_=z,l||(y.cache_.sources=S),y.updateSourceCaches_(V);var j=y.src_(V);if(j){if(S.length>1)return y.handleSrc_(S.slice(1));y.changingSrc_=!1,y.setTimeout(function(){this.error({code:4,message:this.options_.notSupportedMessage})},0),y.triggerReady();return}Ny(z,y.tech_)}),this.options_.retryOnError&&S.length>1){var x=function(){y.error(null),y.handleSrc_(S.slice(1),!0)},U=function(){y.off("error",x)};this.one("error",x),this.one("playing",U),this.resetRetryOnError_=function(){y.off("error",x),y.off("playing",U)}}},f.src=function(a){return this.handleSrc_(a,!1)},f.src_=function(a){var l=this,y=this.selectSource([a]);return y?yy(y.tech,this.techName_)?(this.ready(function(){this.tech_.constructor.prototype.hasOwnProperty("setSource")?this.techCall_("setSource",a):this.techCall_("src",a.src),this.changingSrc_=!1},!0),!1):(this.changingSrc_=!0,this.loadTech_(y.tech,y.source),this.tech_.ready(function(){l.changingSrc_=!1}),!1):!0},f.load=function(){this.techCall_("load")},f.reset=function(){var a=this,l=this.options_.Promise||T.default.Promise;if(this.paused()||!l)this.doReset_();else{var y=this.play();vi(y.then(function(){return a.doReset_()}))}},f.doReset_=function(){this.tech_&&this.tech_.clearTracks("text"),this.resetCache_(),this.poster(""),this.loadTech_(this.options_.techOrder[0],null),this.techCall_("reset"),this.resetControlBarUI_(),Me(this)&&this.trigger("playerreset")},f.resetControlBarUI_=function(){this.resetProgressBar_(),this.resetPlaybackRate_(),this.resetVolumeBar_()},f.resetProgressBar_=function(){this.currentTime(0);var a=this.controlBar||{},l=a.durationDisplay,y=a.remainingTimeDisplay;l&&l.updateContent(),y&&y.updateContent()},f.resetPlaybackRate_=function(){this.playbackRate(this.defaultPlaybackRate()),this.handleTechRateChange_()},f.resetVolumeBar_=function(){this.volume(1),this.trigger("volumechange")},f.currentSources=function(){var a=this.currentSource(),l=[];return Object.keys(a).length!==0&&l.push(a),this.cache_.sources||l},f.currentSource=function(){return this.cache_.source||{}},f.currentSrc=function(){return this.currentSource()&&this.currentSource().src||""},f.currentType=function(){return this.currentSource()&&this.currentSource().type||""},f.preload=function(a){if(a!==void 0){this.techCall_("setPreload",a),this.options_.preload=a;return}return this.techGet_("preload")},f.autoplay=function(a){if(a===void 0)return this.options_.autoplay||!1;var l;typeof a=="string"&&/(any|play|muted)/.test(a)||a===!0&&this.options_.normalizeAutoplay?(this.options_.autoplay=a,this.manualAutoplay_(typeof a=="string"?a:"play"),l=!1):a?this.options_.autoplay=!0:this.options_.autoplay=!1,l=typeof l>"u"?this.options_.autoplay:l,this.tech_&&this.techCall_("setAutoplay",l)},f.playsinline=function(a){return a!==void 0?(this.techCall_("setPlaysinline",a),this.options_.playsinline=a,this):this.techGet_("playsinline")},f.loop=function(a){if(a!==void 0){this.techCall_("setLoop",a),this.options_.loop=a;return}return this.techGet_("loop")},f.poster=function(a){if(a===void 0)return this.poster_;a||(a=""),a!==this.poster_&&(this.poster_=a,this.techCall_("setPoster",a),this.isPosterFromTech_=!1,this.trigger("posterchange"))},f.handleTechPosterChange_=function(){if((!this.poster_||this.options_.techCanOverridePoster)&&this.tech_&&this.tech_.poster){var a=this.tech_.poster()||"";a!==this.poster_&&(this.poster_=a,this.isPosterFromTech_=!0,this.trigger("posterchange"))}},f.controls=function(a){if(a===void 0)return!!this.controls_;a=!!a,this.controls_!==a&&(this.controls_=a,this.usingNativeControls()&&this.techCall_("setControls",a),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_()))},f.usingNativeControls=function(a){if(a===void 0)return!!this.usingNativeControls_;a=!!a,this.usingNativeControls_!==a&&(this.usingNativeControls_=a,this.usingNativeControls_?(this.addClass("vjs-using-native-controls"),this.trigger("usingnativecontrols")):(this.removeClass("vjs-using-native-controls"),this.trigger("usingcustomcontrols")))},f.error=function(a){var l=this;if(a===void 0)return this.error_||null;if(B("beforeerror").forEach(function(S){var x=S(l,a);if(!(ze(x)&&!Array.isArray(x)||typeof x=="string"||typeof x=="number"||x===null)){l.log.error("please return a value that MediaError expects in beforeerror hooks");return}a=x}),this.options_.suppressNotSupportedError&&a&&a.code===4){var y=function(){this.error(a)};this.options_.suppressNotSupportedError=!1,this.any(["click","touchstart"],y),this.one("loadstart",function(){this.off(["click","touchstart"],y)});return}if(a===null){this.error_=a,this.removeClass("vjs-error"),this.errorDisplay&&this.errorDisplay.close();return}this.error_=new Mt(a),this.addClass("vjs-error"),ae.error("(CODE:"+this.error_.code+" "+Mt.errorTypes[this.error_.code]+")",this.error_.message,this.error_),this.trigger("error"),B("error").forEach(function(S){return S(l,l.error_)})},f.reportUserActivity=function(a){this.userActivity_=!0},f.userActive=function(a){if(a===void 0)return this.userActive_;if(a=!!a,a!==this.userActive_){if(this.userActive_=a,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(l){l.stopPropagation(),l.preventDefault()}),this.userActivity_=!1,this.removeClass("vjs-user-active"),this.addClass("vjs-user-inactive"),this.trigger("userinactive")}},f.listenForUserActivity_=function(){var a,l,y,S=it(this,this.reportUserActivity),x=function(we){(we.screenX!==l||we.screenY!==y)&&(l=we.screenX,y=we.screenY,S())},U=function(){S(),this.clearInterval(a),a=this.setInterval(S,250)},V=function(we){S(),this.clearInterval(a)};this.on("mousedown",U),this.on("mousemove",x),this.on("mouseup",V),this.on("mouseleave",V);var z=this.getChild("controlBar");z&&!R&&!gt&&(z.on("mouseenter",function(he){this.player().options_.inactivityTimeout!==0&&(this.player().cache_.inactivityTimeout=this.player().options_.inactivityTimeout),this.player().options_.inactivityTimeout=0}),z.on("mouseleave",function(he){this.player().options_.inactivityTimeout=this.player().cache_.inactivityTimeout})),this.on("keydown",S),this.on("keyup",S);var j;this.setInterval(function(){if(this.userActivity_){this.userActivity_=!1,this.userActive(!0),this.clearTimeout(j);var he=this.options_.inactivityTimeout;he<=0||(j=this.setTimeout(function(){this.userActivity_||this.userActive(!1)},he))}},250)},f.playbackRate=function(a){if(a!==void 0){this.techCall_("setPlaybackRate",a);return}return this.tech_&&this.tech_.featuresPlaybackRate?this.cache_.lastPlaybackRate||this.techGet_("playbackRate"):1},f.defaultPlaybackRate=function(a){return a!==void 0?this.techCall_("setDefaultPlaybackRate",a):this.tech_&&this.tech_.featuresPlaybackRate?this.techGet_("defaultPlaybackRate"):1},f.isAudio=function(a){if(a!==void 0){this.isAudio_=!!a;return}return!!this.isAudio_},f.enableAudioOnlyUI_=function(){var a=this;this.addClass("vjs-audio-only-mode");var l=this.children(),y=this.getChild("ControlBar"),S=y&&y.currentHeight();l.forEach(function(x){x!==y&&x.el_&&!x.hasClass("vjs-hidden")&&(x.hide(),a.audioOnlyCache_.hiddenChildren.push(x))}),this.audioOnlyCache_.playerHeight=this.currentHeight(),this.height(S),this.trigger("audioonlymodechange")},f.disableAudioOnlyUI_=function(){this.removeClass("vjs-audio-only-mode"),this.audioOnlyCache_.hiddenChildren.forEach(function(a){return a.show()}),this.height(this.audioOnlyCache_.playerHeight),this.trigger("audioonlymodechange")},f.audioOnlyMode=function(a){var l=this;if(typeof a!="boolean"||a===this.audioOnlyMode_)return this.audioOnlyMode_;this.audioOnlyMode_=a;var y=this.options_.Promise||T.default.Promise;if(y){if(a){var S=[];return this.isInPictureInPicture()&&S.push(this.exitPictureInPicture()),this.isFullscreen()&&S.push(this.exitFullscreen()),this.audioPosterMode()&&S.push(this.audioPosterMode(!1)),y.all(S).then(function(){return l.enableAudioOnlyUI_()})}return y.resolve().then(function(){return l.disableAudioOnlyUI_()})}a?(this.isInPictureInPicture()&&this.exitPictureInPicture(),this.isFullscreen()&&this.exitFullscreen(),this.enableAudioOnlyUI_()):this.disableAudioOnlyUI_()},f.enablePosterModeUI_=function(){var a=this.tech_&&this.tech_;a.hide(),this.addClass("vjs-audio-poster-mode"),this.trigger("audiopostermodechange")},f.disablePosterModeUI_=function(){var a=this.tech_&&this.tech_;a.show(),this.removeClass("vjs-audio-poster-mode"),this.trigger("audiopostermodechange")},f.audioPosterMode=function(a){var l=this;if(typeof a!="boolean"||a===this.audioPosterMode_)return this.audioPosterMode_;this.audioPosterMode_=a;var y=this.options_.Promise||T.default.Promise;if(y){if(a){if(this.audioOnlyMode()){var S=this.audioOnlyMode(!1);return S.then(function(){l.enablePosterModeUI_()})}return y.resolve().then(function(){l.enablePosterModeUI_()})}return y.resolve().then(function(){l.disablePosterModeUI_()})}if(a){this.audioOnlyMode()&&this.audioOnlyMode(!1),this.enablePosterModeUI_();return}this.disablePosterModeUI_()},f.addTextTrack=function(a,l,y){if(this.tech_)return this.tech_.addTextTrack(a,l,y)},f.addRemoteTextTrack=function(a,l){if(this.tech_)return this.tech_.addRemoteTextTrack(a,l)},f.removeRemoteTextTrack=function(a){a===void 0&&(a={});var l=a,y=l.track;if(y||(y=a),this.tech_)return this.tech_.removeRemoteTextTrack(y)},f.getVideoPlaybackQuality=function(){return this.techGet_("getVideoPlaybackQuality")},f.videoWidth=function(){return this.tech_&&this.tech_.videoWidth&&this.tech_.videoWidth()||0},f.videoHeight=function(){return this.tech_&&this.tech_.videoHeight&&this.tech_.videoHeight()||0},f.language=function(a){if(a===void 0)return this.language_;this.language_!==String(a).toLowerCase()&&(this.language_=String(a).toLowerCase(),Me(this)&&this.trigger("languagechange"))},f.languages=function(){return lt(v.prototype.options_.languages,this.languages_)},f.toJSON=function(){var a=lt(this.options_),l=a.tracks;a.tracks=[];for(var y=0;y<l.length;y++){var S=l[y];S=lt(S),S.player=void 0,a.tracks[y]=S}return a},f.createModal=function(a,l){var y=this;l=l||{},l.content=a||"";var S=new hs(this,l);return this.addChild(S),S.on("dispose",function(){y.removeChild(S)}),S.open(),S},f.updateCurrentBreakpoint_=function(){if(this.responsive())for(var a=this.currentBreakpoint(),l=this.currentWidth(),y=0;y<_l.length;y++){var S=_l[y],x=this.breakpoints_[S];if(l<=x){if(a===S)return;a&&this.removeClass(la[a]),this.addClass(la[S]),this.breakpoint_=S;break}}},f.removeCurrentBreakpoint_=function(){var a=this.currentBreakpointClass();this.breakpoint_="",a&&this.removeClass(a)},f.breakpoints=function(a){return a===void 0?Fe(this.breakpoints_):(this.breakpoint_="",this.breakpoints_=Fe({},Sv,a),this.updateCurrentBreakpoint_(),Fe(this.breakpoints_))},f.responsive=function(a){if(a===void 0)return this.responsive_;a=!!a;var l=this.responsive_;if(a!==l)return this.responsive_=a,a?(this.on("playerresize",this.boundUpdateCurrentBreakpoint_),this.updateCurrentBreakpoint_()):(this.off("playerresize",this.boundUpdateCurrentBreakpoint_),this.removeCurrentBreakpoint_()),a},f.currentBreakpoint=function(){return this.breakpoint_},f.currentBreakpointClass=function(){return la[this.breakpoint_]||""},f.loadMedia=function(a,l){var y=this;if(!(!a||typeof a!="object")){this.reset(),this.cache_.media=lt(a);var S=this.cache_.media,x=S.artwork,U=S.poster,V=S.src,z=S.textTracks;!x&&U&&(this.cache_.media.artwork=[{src:U,type:ta(U)}]),V&&this.src(V),U&&this.poster(U),Array.isArray(z)&&z.forEach(function(j){return y.addRemoteTextTrack(j,!1)}),this.ready(l)}},f.getMedia=function(){if(!this.cache_.media){var a=this.poster(),l=this.currentSources(),y=Array.prototype.map.call(this.remoteTextTracks(),function(x){return{kind:x.kind,label:x.label,language:x.language,src:x.src}}),S={src:l,textTracks:y};return a&&(S.poster=a,S.artwork=[{src:S.poster,type:ta(S.poster)}]),S}return lt(this.cache_.media)},v.getTagSettings=function(a){var l={sources:[],tracks:[]},y=zt(a),S=y["data-setup"];if($i(a,"vjs-fill")&&(y.fill=!0),$i(a,"vjs-fluid")&&(y.fluid=!0),S!==null){var x=P.default(S||"{}"),U=x[0],V=x[1];U&&ae.error(U),Fe(y,V)}if(Fe(l,y),a.hasChildNodes())for(var z=a.childNodes,j=0,he=z.length;j<he;j++){var we=z[j],je=we.nodeName.toLowerCase();je==="source"?l.sources.push(zt(we)):je==="track"&&l.tracks.push(zt(we))}return l},f.flexNotSupported_=function(){var a=b.default.createElement("i");return!("flexBasis"in a.style||"webkitFlexBasis"in a.style||"mozFlexBasis"in a.style||"msFlexBasis"in a.style||"msFlexOrder"in a.style)},f.debug=function(a){if(a===void 0)return this.debugEnabled_;a?(this.trigger("debugon"),this.previousLogLevel_=this.log.level,this.log.level("debug"),this.debugEnabled_=!0):(this.trigger("debugoff"),this.log.level(this.previousLogLevel_),this.previousLogLevel_=void 0,this.debugEnabled_=!1)},f.playbackRates=function(a){if(a===void 0)return this.cache_.playbackRates;Array.isArray(a)&&a.every(function(l){return typeof l=="number"})&&(this.cache_.playbackRates=a,this.trigger("playbackrateschange"))},v}(pe);Ft.names.forEach(function(m){var v=Ft[m];mt.prototype[v.getterName]=function(){return this.tech_?this.tech_[v.getterName]():(this[v.privateName]=this[v.privateName]||new v.ListClass,this[v.privateName])}}),mt.prototype.crossorigin=mt.prototype.crossOrigin,mt.players={};var or=T.default.navigator;mt.prototype.options_={techOrder:nt.defaultTechOrder_,html5:{},inactivityTimeout:2e3,playbackRates:[],liveui:!1,children:["mediaLoader","posterImage","textTrackDisplay","loadingSpinner","bigPlayButton","liveTracker","controlBar","errorDisplay","textTrackSettings","resizeManager"],language:or&&(or.languages&&or.languages[0]||or.userLanguage||or.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},["ended","seeking","seekable","networkState","readyState"].forEach(function(m){mt.prototype[m]=function(){return this.techGet_(m)}}),nd.forEach(function(m){mt.prototype["handleTech"+dt(m)+"_"]=function(){return this.trigger(m)}}),pe.registerComponent("Player",mt);var ua="plugin",vs="activePlugins_",Ts={},ca=function(v){return Ts.hasOwnProperty(v)},ha=function(v){return ca(v)?Ts[v]:void 0},sd=function(v,f){v[vs]=v[vs]||{},v[vs][f]=!0},da=function(v,f,c){var a=(c?"before":"")+"pluginsetup";v.trigger(a,f),v.trigger(a+":"+f.name,f)},Cv=function(v,f){var c=function(){da(this,{name:v,plugin:f,instance:null},!0);var l=f.apply(this,arguments);return sd(this,v),da(this,{name:v,plugin:f,instance:l}),l};return Object.keys(f).forEach(function(a){c[a]=f[a]}),c},rd=function(v,f){return f.prototype.name=v,function(){da(this,{name:v,plugin:f,instance:null},!0);for(var c=arguments.length,a=new Array(c),l=0;l<c;l++)a[l]=arguments[l];var y=k.default(f,[this].concat(a));return this[v]=function(){return y},da(this,y.getEventHash()),y}},Ti=function(){function m(f){if(this.constructor===m)throw new Error("Plugin must be sub-classed; not directly instantiated.");this.player=f,this.log||(this.log=this.player.log.createLogger(this.name)),ir(this),delete this.trigger,rh(this,this.constructor.defaultState),sd(f,this.name),this.dispose=this.dispose.bind(this),f.on("dispose",this.dispose)}var v=m.prototype;return v.version=function(){return this.constructor.VERSION},v.getEventHash=function(c){return c===void 0&&(c={}),c.name=this.name,c.plugin=this.constructor,c.instance=this,c},v.trigger=function(c,a){return a===void 0&&(a={}),dn(this.eventBusEl_,c,this.getEventHash(a))},v.handleStateChanged=function(c){},v.dispose=function(){var c=this.name,a=this.player;this.trigger("dispose"),this.off(),a.off("dispose",this.dispose),a[vs][c]=!1,this.player=this.state=null,a[c]=rd(c,Ts[c])},m.isBasic=function(c){var a=typeof c=="string"?ha(c):c;return typeof a=="function"&&!m.prototype.isPrototypeOf(a.prototype)},m.registerPlugin=function(c,a){if(typeof c!="string")throw new Error('Illegal plugin name, "'+c+'", must be a string, was '+typeof c+".");if(ca(c))ae.warn('A plugin named "'+c+'" already exists. You may want to avoid re-registering plugins!');else if(mt.prototype.hasOwnProperty(c))throw new Error('Illegal plugin name, "'+c+'", cannot share a name with an existing player method!');if(typeof a!="function")throw new Error('Illegal plugin for "'+c+'", must be a function, was '+typeof a+".");return Ts[c]=a,c!==ua&&(m.isBasic(a)?mt.prototype[c]=Cv(c,a):mt.prototype[c]=rd(c,a)),a},m.deregisterPlugin=function(c){if(c===ua)throw new Error("Cannot de-register base plugin.");ca(c)&&(delete Ts[c],delete mt.prototype[c])},m.getPlugins=function(c){c===void 0&&(c=Object.keys(Ts));var a;return c.forEach(function(l){var y=ha(l);y&&(a=a||{},a[l]=y)}),a},m.getPluginVersion=function(c){var a=ha(c);return a&&a.VERSION||""},m}();Ti.getPlugin=ha,Ti.BASE_PLUGIN_NAME=ua,Ti.registerPlugin(ua,Ti),mt.prototype.usingPlugin=function(m){return!!this[vs]&&this[vs][m]===!0},mt.prototype.hasPlugin=function(m){return!!ca(m)};var ad=!1,wv=function(v,f){f===void 0&&(f={}),ad||(ae.warn("videojs.extend is deprecated as of Video.js 7.22.0 and will be removed in Video.js 8.0.0"),ad=!0);var c=function(){v.apply(this,arguments)},a={};typeof f=="object"?(f.constructor!==Object.prototype.constructor&&(c=f.constructor),a=f):typeof f=="function"&&(c=f),N.default(c,v),v&&(c.super_=v);for(var l in a)a.hasOwnProperty(l)&&(c.prototype[l]=a[l]);return c},od=function(v){return v.indexOf("#")===0?v.slice(1):v};function ke(m,v,f){var c=ke.getPlayer(m);if(c)return v&&ae.warn('Player "'+m+'" is already initialised. Options will not be applied.'),f&&c.ready(f),c;var a=typeof m=="string"?yi("#"+od(m)):m;if(!Oe(a))throw new TypeError("The element or ID supplied is not valid. (videojs)");(!a.ownerDocument.defaultView||!a.ownerDocument.body.contains(a))&&ae.warn("The element supplied is not included in the DOM"),v=v||{},v.restoreEl===!0&&(v.restoreEl=(a.parentNode&&a.parentNode.hasAttribute("data-vjs-player")?a.parentNode:a).cloneNode(!0)),B("beforesetup").forEach(function(y){var S=y(a,lt(v));if(!ze(S)||Array.isArray(S)){ae.error("please return an object in beforesetup hooks");return}v=lt(v,S)});var l=pe.getComponent("Player");return c=new l(a,v,f),B("setup").forEach(function(y){return y(c)}),c}if(ke.hooks_=G,ke.hooks=B,ke.hook=D,ke.hookOnce=oe,ke.removeHook=K,T.default.VIDEOJS_NO_DYNAMIC_STYLE!==!0&&ne()){var fa=yi(".vjs-styles-defaults");if(!fa){fa=as("vjs-styles-defaults");var El=yi("head");El&&El.insertBefore(fa,El.firstChild),hn(fa,`
      .video-js {
        width: 300px;
        height: 150px;
      }

      .vjs-fluid:not(.vjs-audio-only-mode) {
        padding-top: 56.25%
      }
    `)}}return Js(1,ke),ke.VERSION=H,ke.options=mt.prototype.options_,ke.getPlayers=function(){return mt.players},ke.getPlayer=function(m){var v=mt.players,f;if(typeof m=="string"){var c=od(m),a=v[c];if(a)return a;f=yi("#"+c)}else f=m;if(Oe(f)){var l=f,y=l.player,S=l.playerId;if(y||v[S])return y||v[S]}},ke.getAllPlayers=function(){return Object.keys(mt.players).map(function(m){return mt.players[m]}).filter(Boolean)},ke.players=mt.players,ke.getComponent=pe.getComponent,ke.registerComponent=function(m,v){nt.isTech(v)&&ae.warn("The "+m+" tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)"),pe.registerComponent.call(pe,m,v)},ke.getTech=nt.getTech,ke.registerTech=nt.registerTech,ke.use=My,Object.defineProperty(ke,"middleware",{value:{},writeable:!1,enumerable:!0}),Object.defineProperty(ke.middleware,"TERMINATOR",{value:ea,writeable:!1,enumerable:!0}),ke.browser=C,ke.TOUCH_ENABLED=ri,ke.extend=wv,ke.mergeOptions=lt,ke.bind=it,ke.registerPlugin=Ti.registerPlugin,ke.deregisterPlugin=Ti.deregisterPlugin,ke.plugin=function(m,v){return ae.warn("videojs.plugin() is deprecated; use videojs.registerPlugin() instead"),Ti.registerPlugin(m,v)},ke.getPlugins=Ti.getPlugins,ke.getPlugin=Ti.getPlugin,ke.getPluginVersion=Ti.getPluginVersion,ke.addLanguage=function(m,v){var f;return m=(""+m).toLowerCase(),ke.options.languages=lt(ke.options.languages,(f={},f[m]=v,f)),ke.options.languages[m]},ke.log=ae,ke.createLogger=ie,ke.createTimeRange=ke.createTimeRanges=Bn,ke.formatTime=gs,ke.setFormatTime=ev,ke.resetFormatTime=tv,ke.parseUrl=qo,ke.isCrossOrigin=Zr,ke.EventTarget=F,ke.on=Ot,ke.one=us,ke.off=bt,ke.trigger=dn,ke.xhr=M.default,ke.TextTrack=sr,ke.AudioTrack=gh,ke.VideoTrack=mh,["isEl","isTextNode","createEl","hasClass","addClass","removeClass","toggleClass","setAttributes","getAttributes","emptyEl","appendContent","insertContent"].forEach(function(m){ke[m]=function(){return ae.warn("videojs."+m+"() is deprecated; use videojs.dom."+m+"() instead"),Gr[m].apply(null,arguments)}}),ke.computedStyle=ot,ke.dom=Gr,ke.url=Py,ke.defineLazyProperty=Tl,ke.addLanguage("en",{"Non-Fullscreen":"Exit Fullscreen"}),Hl=ke,Hl}var zv=Wv();const X=Fp(zv),Yv=X.getComponent("MenuItem");class Xv extends Yv{constructor(e,t){super(e,t)}handleClick(e){super.handleClick(e),this.options_.listener(e),setTimeout(()=>{this.player().contextMenu().menu.dispose()},1)}createEl(e,t,i){const n=super.createEl(e,t,i),r=X.dom.createEl("span");return r.innerHTML=`<span class="vjs-menu-item-text">${this.localize(this.options_.label)}</span>`,n.replaceChild(r,n.querySelector(".vjs-menu-item-text")),n}}const Qv=X.getComponent("Menu");class Jv extends Qv{constructor(e,t){super(e,{...t,menuButton:void 0}),this.dispose=X.bind(this,this.dispose);for(const i of t.content())this.addItem(new Xv(e,{label:i.label,listener:X.bind(e,i.listener)}))}createEl(){const e=super.createEl();return X.dom.addClass(e,"vjs-contextmenu-ui-menu"),e.style.left=this.options_.position.left+"px",e.style.top=this.options_.position.top+"px",e}}function Zv(s){let e;if(s.getBoundingClientRect&&s.parentNode&&(e=s.getBoundingClientRect()),!e)return{left:0,top:0};const t=document.documentElement,i=document.body,n=t.clientLeft||i.clientLeft||0,r=window.pageXOffset||i.scrollLeft,o=e.left+r-n,u=t.clientTop||i.clientTop||0,h=window.pageYOffset||i.scrollTop,p=e.top+h-u;return{left:Math.round(o),top:Math.round(p)}}function eT(s,e){const t={},i=Zv(s),n=s.offsetWidth,r=s.offsetHeight,o=i.top,u=i.left;let h=e.pageY,p=e.pageX;return e.changedTouches&&(p=e.changedTouches[0].pageX,h=e.changedTouches[0].pageY),t.y=Math.max(0,Math.min(1,(o-h+r)/r)),t.x=Math.max(0,Math.min(1,(p-u)/n)),t}const tT=X.getPlugin("plugin");class iT extends tT{constructor(e,t){super(e,t),this.options_=t,this.menu&&(this.menu.dispose(),this.player.off("contextmenu",this.onContextMenuBind)),this.onContextMenuBind=this.onContextMenu.bind(this),this.player.on("contextmenu",this.onContextMenuBind),this.player.ready(()=>this.player.addClass("vjs-contextmenu-ui"))}onContextMenu(e){if(nT(this.player)){this.menu.dispose();return}if(sT(e.target))return;const t=eT(this.player.el(),e),i=this.player.el().getBoundingClientRect(),n=rT(t,i),r=X.browser.IS_FIREFOX?document.documentElement:document;e.preventDefault();const o=this.menu=new Jv(this.player,{content:this.options_.content,position:n});o.on("dispose",()=>{for(const d of["click","tap"])X.off(r,d,o.dispose);this.player.removeChild(o),this.menu=void 0}),this.player.addChild(o);const u=o.el(),h=u.getBoundingClientRect(),p=document.body.getBoundingClientRect();(h.right>p.width||h.bottom>p.height)&&(u.style.left=Math.floor(Math.min(n.left,this.player.currentWidth()-o.currentWidth()))+"px",u.style.top=Math.floor(Math.min(n.top,this.player.currentHeight()-o.currentHeight()))+"px");for(const d of["click","tap"])X.on(r,d,o.dispose)}}X.registerPlugin("contextMenu",iT);function nT(s){var e;return s.usingPlugin("contextMenu")?!!((e=s.contextMenu().menu)!=null&&e.el()):!1}function sT(s){const e=s.tagName.toLowerCase();return e==="input"||e==="textarea"}function rT(s,e){return{left:Math.round(e.width*s.x),top:Math.round(e.height-e.height*s.y)}}function aT(s){return`
    <div class="vjs-upnext-top">
      <span class="vjs-upnext-headtext">${s.headText}</span>
      <div class="vjs-upnext-title"></div>
    </div>
    <div class="vjs-upnext-autoplay-icon">
      <svg height="100%" version="1.1" viewbox="0 0 98 98" width="100%">
        <circle class="vjs-upnext-svg-autoplay-circle" cx="49" cy="49" fill="#000" fill-opacity="0.8" r="48"></circle>
        <circle class="vjs-upnext-svg-autoplay-ring" cx="-49" cy="49" fill-opacity="0" r="46.5"
                stroke="#FFFFFF" stroke-width="4" transform="rotate(-90)"
        ></circle>
        <polygon class="vjs-upnext-svg-autoplay-triangle" fill="#fff" points="32,27 72,49 32,71"></polygon></svg>
    </div>
    <span class="vjs-upnext-bottom">
      <span class="vjs-upnext-cancel">
        <button class="vjs-upnext-cancel-button" tabindex="0" aria-label="Cancel autoplay">${s.cancelText}</button>
      </span>
      <span class="vjs-upnext-suspended">${s.suspendedText}</span>
    </span>
  `}const oT=X.getComponent("Component");class Up extends oT{constructor(e,t){super(e,t),this.dashOffsetTotal=586,this.dashOffsetStart=293,this.interval=50,this.upNextEvents=new X.EventTarget,this.ticks=0,this.totalTicks=this.options_.timeout/this.interval,this.onEndedHandler=()=>{this.options_.isDisplayed()&&(e.addClass("vjs-upnext--showing"),this.showCard(i=>{e.removeClass("vjs-upnext--showing"),this.container.style.display="none",i||this.options_.next()}))},this.onPlayingHandler=()=>{this.upNextEvents.trigger("playing")},e.on(["auto-stopped","ended"],this.onEndedHandler),e.on("playing",this.onPlayingHandler)}dispose(){this.onEndedHandler&&this.player().off(["auto-stopped","ended"],this.onEndedHandler),this.onPlayingHandler&&this.player().off("playing",this.onPlayingHandler),this.timeout&&clearTimeout(this.timeout),super.dispose()}createEl(){const e=super.createEl("div",{className:"vjs-upnext-content",innerHTML:aT(this.options_)});return this.container=e,e.style.display="none",this.autoplayRing=e.getElementsByClassName("vjs-upnext-svg-autoplay-ring")[0],this.title=e.getElementsByClassName("vjs-upnext-title")[0],this.cancelButton=e.getElementsByClassName("vjs-upnext-cancel-button")[0],this.suspendedMessage=e.getElementsByClassName("vjs-upnext-suspended")[0],this.nextButton=e.getElementsByClassName("vjs-upnext-autoplay-icon")[0],this.cancelButton.onclick=()=>{this.upNextEvents.trigger("cancel")},this.nextButton.onclick=()=>{this.upNextEvents.trigger("next")},e}showCard(e){if(this.autoplayRing.setAttribute("stroke-dasharray",`${this.dashOffsetStart}`),this.autoplayRing.setAttribute("stroke-dashoffset",`${-this.dashOffsetStart}`),this.title.innerText=this.options_.getTitle(),this.totalTicks===0)return e(!1);this.upNextEvents.one("cancel",()=>{clearTimeout(this.timeout),this.timeout=void 0,e(!0)}),this.upNextEvents.one("playing",()=>{clearTimeout(this.timeout),this.timeout=void 0,e(!0)}),this.upNextEvents.one("next",()=>{clearTimeout(this.timeout),this.timeout=void 0,e(!1)});const t=r=>{const o=Math.max(-this.dashOffsetTotal,-this.dashOffsetStart-r*this.dashOffsetTotal/2/100);this.autoplayRing.setAttribute("stroke-dashoffset",""+o)},i=()=>{t(this.ticks++*100/this.totalTicks)},n=()=>{this.options_.isSuspended()?(this.suspendedMessage.innerText=this.options_.suspendedText,t(0),this.ticks=0,this.timeout=setTimeout(n.bind(this),300)):this.ticks>=this.totalTicks?(clearTimeout(this.timeout),this.timeout=void 0,e(!1)):(this.suspendedMessage.innerText="",i(),this.timeout=setTimeout(n.bind(this),this.interval))};this.container.style.display="block",this.timeout=setTimeout(n.bind(this),this.interval)}}X.registerComponent("EndCard",Up);const lT=X.getPlugin("plugin");class uT extends lT{constructor(e,t){super(e);const i={next:t.next,getTitle:t.getTitle,timeout:t.timeout,cancelText:e.localize("Cancel"),headText:e.localize("Up Next"),suspendedText:e.localize("Autoplay is suspended"),isDisplayed:t.isDisplayed,isSuspended:t.isSuspended};this.player.ready(()=>{e.addClass("vjs-upnext")});const n=new Up(e,i);e.addChild(n),this.on("dispose",()=>e.removeChild(n))}}X.registerPlugin("upnext",uT);const yn=new Map;function kd(s){return new Proxy(s,{set:function(e,t,i){return Object.prototype.hasOwnProperty.call(Ku,t)?s[t]=i:s.setItem(t,i),!0},get:function(e,t){if(typeof s[t]=="function")return s[t];if(yn.has(t))return s.getItem(t)}})}class Ku{getItem(e){const t=String(e);return yn.has(e)?String(yn.get(t)):null}setItem(e,t){yn.set(String(e),String(t))}removeItem(e){yn.delete(e)}clear(){yn.clear()}key(e){if(arguments.length===0)throw new TypeError('Failed to execute "key" on "Storage": 1 argument required, but only 0 present.');return Array.from(yn.keys())[e]}get length(){return yn.size}}let is,Or;function Hp(){const s=new Ku,e=new Ku;is=kd(s),Or=kd(e)}try{is=localStorage,Or=sessionStorage}catch{Hp()}(!is||!Or)&&Hp();const ji={ACCESS_TOKEN:"access_token",REFRESH_TOKEN:"refresh_token",TOKEN_TYPE:"token_type"};class Ic{constructor(e){Ke(this,"accessToken"),Ke(this,"refreshToken"),Ke(this,"tokenType"),e&&(this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,e.tokenType==="bearer"?this.tokenType="Bearer":this.tokenType=e.tokenType)}static getUserTokens(e){const t=e.getItem(ji.ACCESS_TOKEN),i=e.getItem(ji.REFRESH_TOKEN),n=e.getItem(ji.TOKEN_TYPE);return!t||!i||!n?null:new Ic({accessToken:t,refreshToken:i,tokenType:n})}static saveToLocalStorage(e,t){e.setItem(ji.ACCESS_TOKEN,t.accessToken),e.setItem(ji.REFRESH_TOKEN,t.refreshToken),e.setItem(ji.TOKEN_TYPE,t.tokenType)}static flushLocalStorage(e){e.removeItem(ji.ACCESS_TOKEN),e.removeItem(ji.REFRESH_TOKEN),e.removeItem(ji.TOKEN_TYPE)}}class cT{constructor(){Ke(this,"hooks",[])}info(e,t){this.runHooks("info",e,t),t?console.log(e,t):console.log(e)}warn(e,t){this.runHooks("warn",e,t),this.clientWarn(e,t)}clientWarn(e,t){t?console.warn(e,t):console.warn(e)}error(e,t){this.runHooks("error",e,t),this.clientError(e,t)}clientError(e,t){t?console.error(e,t):console.error(e)}addHook(e,t){this.hooks.push({level:e,hook:t})}registerServerSending(e){this.addHook("warn",(t,i)=>this.sendClientLog(e,this.buildServerLogPayload("warn",t,i))),this.addHook("error",(t,i)=>this.sendClientLog(e,this.buildServerLogPayload("error",t,i)))}sendClientLog(e,t){if(!t)return;const i=new Headers({Accept:"application/json","Content-Type":"application/json"});try{const n=Ic.getUserTokens(is);n&&i.set("Authorization",`${n.tokenType} ${n.accessToken}`)}catch(n){console.error("Cannot set tokens to client log sender.",{err:n})}fetch(e+"/api/v1/server/logs/client",{headers:i,method:"POST",body:JSON.stringify(t)}).catch(n=>console.error("Cannot send client warn/error to server.",n))}buildServerLogPayload(e,t,i){return t?{message:this.buildMessageServerLogPayload(t),userAgent:navigator.userAgent,url:window.location.href,level:e,stackTrace:this.buildStackServerLogPayload(t,i),meta:this.buildMetaServerLogPayload(i)}:null}buildMessageServerLogPayload(e){return typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}buildStackServerLogPayload(e,t){if(e instanceof Error)return this.buildStack(e);if(t instanceof Error)return this.buildStack(t);if(t?.err instanceof Error)return this.buildStack(t.err)}buildMetaServerLogPayload(e){if(!e||e instanceof Error)return;let t;try{t=JSON.stringify(e,(i,n)=>{if(i!=="err")return n})}catch(i){console.error("Cannot stringify meta.",i)}return t}runHooks(e,t,i){for(const n of this.hooks)n.level===e&&n.hook(t,i)}buildStack(e){return`${e.message}
${e.stack||""}`}}const Ve=window.logger||new cT;window.logger=Ve;const hT={"filter:api.trending-videos.videos.list.params":!0,"filter:api.trending-videos.videos.list.result":!0,"filter:api.most-liked-videos.videos.list.params":!0,"filter:api.most-liked-videos.videos.list.result":!0,"filter:api.local-videos.videos.list.params":!0,"filter:api.local-videos.videos.list.result":!0,"filter:api.recently-added-videos.videos.list.params":!0,"filter:api.recently-added-videos.videos.list.result":!0,"filter:api.browse-videos.videos.list.params":!0,"filter:api.browse-videos.videos.list.result":!0,"filter:api.user-subscriptions-videos.videos.list.params":!0,"filter:api.user-subscriptions-videos.videos.list.result":!0,"filter:api.video-watch.video.get.params":!0,"filter:api.video-watch.video.get.result":!0,"filter:api.video-watch.video-playlist-elements.get.params":!0,"filter:api.video-watch.video-playlist-elements.get.result":!0,"filter:api.video-watch.video-threads.list.params":!0,"filter:api.video-watch.video-threads.list.result":!0,"filter:api.video-watch.video-thread-replies.list.params":!0,"filter:api.video-watch.video-thread-replies.list.result":!0,"filter:api.search.videos.list.params":!0,"filter:api.search.videos.list.result":!0,"filter:api.search.video-channels.list.params":!0,"filter:api.search.video-channels.list.result":!0,"filter:api.search.video-playlists.list.params":!0,"filter:api.search.video-playlists.list.result":!0,"filter:api.signup.registration.create.params":!0,"filter:api.my-library.video-playlist-elements.list.params":!0,"filter:api.my-library.video-playlist-elements.list.result":!0,"filter:internal.video-watch.player.build-options.params":!0,"filter:internal.video-watch.player.build-options.result":!0,"filter:internal.video-watch.player.load-options.params":!0,"filter:internal.video-watch.player.load-options.result":!0,"filter:internal.common.svg-icons.get-content.params":!0,"filter:internal.common.svg-icons.get-content.result":!0,"filter:left-menu.links.create.result":!0,"filter:upload.messages.create.result":!0,"filter:login.instance-about-plugin-panels.create.result":!0,"filter:signup.instance-about-plugin-panels.create.result":!0,"filter:share.video-embed-code.build.params":!0,"filter:share.video-embed-code.build.result":!0,"filter:share.video-playlist-embed-code.build.params":!0,"filter:share.video-playlist-embed-code.build.result":!0,"filter:share.video-embed-url.build.params":!0,"filter:share.video-embed-url.build.result":!0,"filter:share.video-playlist-embed-url.build.params":!0,"filter:share.video-playlist-embed-url.build.result":!0,"filter:share.video-url.build.params":!0,"filter:share.video-url.build.result":!0,"filter:share.video-playlist-url.build.params":!0,"filter:share.video-playlist-url.build.result":!0,"filter:video-watch.video-plugin-metadata.result":!0,"filter:internal.player.videojs.options.result":!0,"filter:internal.player.p2p-media-loader.options.result":!0,"filter:admin-users-list.bulk-actions.create.result":!0,"filter:admin-video-comments-list.actions.create.result":!0,"filter:admin-video-comments-list.bulk-actions.create.result":!0,"filter:user-moderation.actions.create.result":!0,"filter:admin-abuse-list.actions.create.result":!0},dT={"action:application.init":!0,"action:video-watch.init":!0,"action:video-watch.video.loaded":!0,"action:video-watch.player.loaded":!0,"action:video-watch.video-threads.loaded":!0,"action:video-watch.video-thread-replies.loaded":!0,"action:video-channel-create.init":!0,"action:video-channel-update.init":!0,"action:video-channel-update.video-channel.loaded":!0,"action:video-channel-videos.init":!0,"action:video-channel-videos.video-channel.loaded":!0,"action:video-channel-videos.videos.loaded":!0,"action:video-channel-playlists.init":!0,"action:video-channel-playlists.video-channel.loaded":!0,"action:video-channel-playlists.playlists.loaded":!0,"action:video-edit.init":!0,"action:video-edit.form.updated":!0,"action:login.init":!0,"action:search.init":!0,"action:router.navigation-end":!0,"action:signup.register.init":!0,"action:admin-plugin-settings.init":!0,"action:video-upload.init":!0,"action:video-url-import.init":!0,"action:video-torrent-import.init":!0,"action:go-live.init":!0,"action:auth-user.logged-in":!0,"action:auth-user.logged-out":!0,"action:auth-user.information-loaded":!0,"action:modal.video-download.shown":!0,"action:modal.share.shown":!0,"action:embed.player.loaded":!0};Object.assign({},hT,dT);const fT={"filter:api.videos.list.params":!0,"filter:api.videos.list.result":!0,"filter:api.video-playlist.videos.list.params":!0,"filter:api.video-playlist.videos.list.result":!0,"filter:api.accounts.videos.list.params":!0,"filter:api.accounts.videos.list.result":!0,"filter:api.video-channels.videos.list.params":!0,"filter:api.video-channels.videos.list.result":!0,"filter:api.user.me.videos.list.params":!0,"filter:api.user.me.videos.list.result":!0,"filter:api.overviews.videos.list.params":!0,"filter:api.overviews.videos.list.result":!0,"filter:api.user.me.subscription-videos.list.params":!0,"filter:api.user.me.subscription-videos.list.result":!0,"filter:api.search.videos.local.list.params":!0,"filter:api.search.videos.local.list.result":!0,"filter:api.search.videos.index.list.params":!0,"filter:api.search.videos.index.list.result":!0,"filter:api.search.video-channels.local.list.params":!0,"filter:api.search.video-channels.local.list.result":!0,"filter:api.search.video-channels.index.list.params":!0,"filter:api.search.video-channels.index.list.result":!0,"filter:api.search.video-playlists.local.list.params":!0,"filter:api.search.video-playlists.local.list.result":!0,"filter:api.search.video-playlists.index.list.params":!0,"filter:api.search.video-playlists.index.list.result":!0,"filter:api.video.get.result":!0,"filter:api.video-channels.list.params":!0,"filter:api.video-channels.list.result":!0,"filter:api.video-channel.get.result":!0,"filter:api.video.upload.accept.result":!0,"filter:api.live-video.create.accept.result":!0,"filter:api.video.pre-import-url.accept.result":!0,"filter:api.video.pre-import-torrent.accept.result":!0,"filter:api.video.post-import-url.accept.result":!0,"filter:api.video.post-import-torrent.accept.result":!0,"filter:api.video.update-file.accept.result":!0,"filter:api.video.user-import.accept.result":!0,"filter:api.video-thread.create.accept.result":!0,"filter:api.video-comment-reply.create.accept.result":!0,"filter:api.video.upload.video-attribute.result":!0,"filter:api.video.import-url.video-attribute.result":!0,"filter:api.video.import-torrent.video-attribute.result":!0,"filter:api.video.live.video-attribute.result":!0,"filter:api.video.user-import.video-attribute.result":!0,"filter:api.video-threads.list.params":!0,"filter:api.video-threads.list.result":!0,"filter:api.video-thread-comments.list.params":!0,"filter:api.video-thread-comments.list.result":!0,"filter:api.server.stats.get.result":!0,"filter:video.auto-blacklist.result":!0,"filter:api.user.signup.allowed.result":!0,"filter:api.user.request-signup.allowed.result":!0,"filter:api.download.video.allowed.result":!0,"filter:api.download.generated-video.allowed.result":!0,"filter:api.download.torrent.allowed.result":!0,"filter:html.embed.video.allowed.result":!0,"filter:html.embed.video-playlist.allowed.result":!0,"filter:html.client.json-ld.result":!0,"filter:job-queue.process.params":!0,"filter:job-queue.process.result":!0,"filter:transcoding.manual.resolutions-to-transcode.result":!0,"filter:transcoding.auto.resolutions-to-transcode.result":!0,"filter:activity-pub.remote-video-comment.create.accept.result":!0,"filter:activity-pub.activity.context.build.result":!0,"filter:activity-pub.video.json-ld.build.result":!0,"filter:feed.podcast.rss.create-custom-xmlns.result":!0,"filter:feed.podcast.channel.create-custom-tags.result":!0,"filter:feed.podcast.video.create-custom-tags.result":!0,"filter:api.user.me.get.result":!0,"filter:oauth.password-grant.get-user.params":!0,"filter:api.email-verification.ask-send-verify-email.body":!0,"filter:api.users.ask-reset-password.body":!0,"filter:email.subject.result":!0,"filter:email.template-path.result":!0},pT={"action:application.listening":!0,"action:notifier.notification.created":!0,"action:api.video.updated":!0,"action:api.video.deleted":!0,"action:api.video.uploaded":!0,"action:api.video.viewed":!0,"action:api.video.file-updated":!0,"action:api.video-channel.created":!0,"action:api.video-channel.updated":!0,"action:api.video-channel.deleted":!0,"action:api.live-video.created":!0,"action:live.video.state.updated":!0,"action:api.video-thread.created":!0,"action:api.video-comment-reply.created":!0,"action:api.video-comment.deleted":!0,"action:api.video-caption.created":!0,"action:api.video-caption.deleted":!0,"action:api.user.blocked":!0,"action:api.user.unblocked":!0,"action:api.user.registered":!0,"action:api.user.requested-registration":!0,"action:api.user.created":!0,"action:api.user.deleted":!0,"action:api.user.updated":!0,"action:api.user.oauth2-got-token":!0,"action:api.video-playlist-element.created":!0,"action:activity-pub.remote-video.created":!0,"action:activity-pub.remote-video.updated":!0};Object.assign({},fT,pT);const ma={HIGH_LATENCY:2,SMALL_LATENCY:3},xt={H_NOVIDEO:0,H_144P:144,H_240P:240,H_360P:360,H_480P:480,H_720P:720,H_1080P:1080,H_1440P:1440,H_4K:2160};function ja(s){if(!s)return 0;if(typeof s=="number")return Math.floor(s);const e=new RegExp("^((?<hours>\\d+)h)?((?<minutes>\\d+)m)?((?<seconds>\\d+)s?)?$"),t=s.match(e);if(t){const o=parseInt(t.groups.hours||"0",10),u=parseInt(t.groups.minutes||"0",10),h=parseInt(t.groups.seconds||"0",10);return o*3600+u*60+h}const i=s.split(":").reverse(),n={0:1,1:60,2:3600};let r=0;for(let o=0;o<i.length;o++){const u=parseInt(i[o],10);if(isNaN(u))return 0;r+=n[o]*u}return r}function An(s){var e;let t,i="short",n;typeof s=="number"?t=s:(t=s.seconds,i=(e=s.format)!==null&&e!==void 0?e:"short",n=s.symbol);let r="";if(t===0&&i!=="full")return"0s";const o=T=>i==="locale-string"?T.toLocaleString():T,u=n||"h",h=n||"m",p=i==="full"?"":"s",d=Math.floor(t/3600);d>=1&&d<10&&i==="full"?r="0"+d+u:d>=1?r=o(d)+u:i==="full"&&(r="00"+u),t%=3600;const g=Math.floor(t/60);return g>=1&&g<10&&i==="full"?r+="0"+g+h:g>=1?r+=o(g)+h:i==="full"&&(r+="00"+h),t=Math.round(t)%60,t>=1&&t<10&&i==="full"?r+="0"+t+p:t>=1?r+=o(t)+p:i==="full"&&(r+="00"),r}function $l(s,e){const t={};for(const i of e)Object.prototype.hasOwnProperty.call(s,i)&&(t[i]=s[i]);return t}function Id(s,e){const t={},i=new Set(e);for(const[n,r]of Object.entries(s))i.has(n)||(t[n]=r);return t}function $p(s,e){const t=new URL(s);for(const i of Object.keys(e))t.searchParams.append(i,e[i]);return t.toString()}function gT(s){const e=new URL(s);return e.searchParams.forEach((t,i)=>e.searchParams.delete(i)),e.toString()}function mT(s){return"/w/"+s.shortUUID}function qu(s,e){return window.location.origin+mT(s)}function jp(s){const{url:e}=s,t=new URLSearchParams;if(s.startTime!==void 0&&s.startTime!==null){const i=Math.floor(s.startTime);t.set("start",An(i))}if(s.stopTime){const i=Math.floor(s.stopTime);t.set("stop",An(i))}return s.subtitle&&t.set("subtitle",s.subtitle),s.loop===!0&&t.set("loop","1"),s.autoplay===!0&&t.set("autoplay","1"),s.muted===!0&&t.set("muted","1"),s.title===!1&&t.set("title","0"),s.warningTitle===!1&&t.set("warningTitle","0"),s.controls===!1&&t.set("controls","0"),s.controlBar===!1&&t.set("controlBar","0"),s.peertubeLink===!1&&t.set("peertubeLink","0"),s.p2p!==void 0&&t.set("p2p",s.p2p?"1":"0"),s.api!==void 0&&t.set("api",s.api?"1":"0"),s.version!==void 0&&t.set("v",s.version+""),yT(e,t)}function yT(s,e){let t=!1;return e.forEach(()=>{t=!0}),t?s+"?"+e.toString():s}const vT={"en-US":"English",ar:"العربية","ca-ES":"Català","cs-CZ":"Čeština","de-DE":"Deutsch","el-GR":"ελληνικά",eo:"Esperanto","es-ES":"Español","eu-ES":"Euskara","fa-IR":"فارسی","fi-FI":"Suomi","fr-FR":"Français",gd:"Gàidhlig","gl-ES":"Galego",hr:"Hrvatski","hu-HU":"Magyar",is:"Íslenska","it-IT":"Italiano","ja-JP":"日本語",kab:"Taqbaylit","nb-NO":"Norsk bokmål","nl-NL":"Nederlands",nn:"Norsk nynorsk",oc:"Occitan","pl-PL":"Polski","pt-BR":"Português (Brasil)","pt-PT":"Português (Portugal)","ru-RU":"Pусский","sk-SK":"Slovenčina",sq:"Shqip","sv-SE":"Svenska","th-TH":"ไทย",tok:"Toki Pona","tr-TR":"Türkçe","uk-UA":"украї́нська мо́ва","vi-VN":"Tiếng Việt","zh-Hans-CN":"简体中文（中国）","zh-Hant-TW":"繁體中文（台灣）"},Vp={"ar-001":"ar",ca:"ca-ES",cs:"cs-CZ",de:"de-DE",el:"el-GR",en:"en-US",es:"es-ES",eu:"eu-ES",fa:"fa-IR",fi:"fi-FI",fr:"fr-FR",gl:"gl-ES",hu:"hu-HU",it:"it-IT",ja:"ja-JP",nb:"nb-NO",nl:"nl-NL",pl:"pl-PL",pt:"pt-BR",ru:"ru-RU",sk:"sk-SK",sv:"sv-SE",th:"th-TH",tr:"tr-TR",uk:"uk-UA",vi:"vi-VN","zh-CN":"zh-Hans-CN","zh-Hans":"zh-Hans-CN","zh-Hant":"zh-Hant-TW","zh-TW":"zh-Hant-TW",zh:"zh-Hans-CN"},Gp=Object.keys(vT).concat(Object.keys(Vp));function TT(){return"en-US"}function Kp(s){return ao(s)===ao(TT())}Gp.map(s=>"/"+s);function bT(s){return Gp.includes(s)}function ao(s){return s&&(Vp[s]||s)}function _T(s){return s.includes("-")===!1?s:s.split("-")[0]}const ET=new Set([xt.H_NOVIDEO,xt.H_144P,xt.H_240P,xt.H_360P,xt.H_480P,xt.H_720P,xt.H_1080P,xt.H_1440P,xt.H_4K]),Rd={3840:xt.H_4K,1920:xt.H_1080P,1280:xt.H_720P,854:xt.H_480P,640:xt.H_360P,426:xt.H_240P,256:xt.H_144P};function ST(s){const{height:e,width:t}=s;if(s.resolution===0)return"Audio only";let i=s.resolution;if(!ET.has(i)&&typeof e=="number"&&typeof t=="number"){const n=Math.max(e,t);Rd[n]&&(i=Rd[n])}return`${i}p`}function qp(s,e){return e&&e>=50?s+e:s}function Wp(s){return s.charAt(0).toUpperCase()+s.slice(1)}const jl=[{max:1024,type:"B",decimals:0},{max:1048576,type:"KB",decimals:0},{max:1073741824,type:"MB",decimals:0},{max:10995116e5,type:"GB",decimals:1}];function Vt(s){const e=jl.find(i=>s<i.max)||jl[jl.length-1];return[(s/(e.max/1024)).toFixed(e.decimals),e.type]}function CT(s){return{iceServers:s.map(e=>({urls:e}))}}const wT=X.getComponent("Component");class zp extends wT{constructor(e,t){super(e,t),this.metadataStore={},this.intervalMs=300,this.playerNetworkInfo={}}createEl(){this.containerEl=X.dom.createEl("div",{className:"vjs-stats-content"}),this.containerEl.style.display="none",this.infoListEl=X.dom.createEl("div",{className:"vjs-stats-list"});const e=X.dom.createEl("button",{className:"vjs-stats-close",tabindex:"0",title:"Close stats",innerText:"[x]"},{"aria-label":"Close stats"});return e.onclick=()=>this.hide(),this.containerEl.appendChild(e),this.containerEl.appendChild(this.infoListEl),this.populateInfoBlocks(),this.onNetworkInfoHandler=(t,i)=>{this.mode=i.source;const n=i.p2p,r=i.http;this.playerNetworkInfo.downloadSpeed=Vt((n?.downloadSpeed||0)+(r.downloadSpeed||0)).join(" "),this.playerNetworkInfo.uploadSpeed=Vt(n?.uploadSpeed||0).join(" "),this.playerNetworkInfo.totalDownloaded=Vt((n?.downloaded||0)+r.downloaded).join(" "),this.playerNetworkInfo.totalUploaded=Vt(n?.uploaded||0).join(" "),this.playerNetworkInfo.numPeers=n?.peersWithWebSeed,i.source==="p2p-media-loader"&&(this.playerNetworkInfo.averageBandwidth=Vt(i.bandwidthEstimate).join(" ")+"/s",this.playerNetworkInfo.downloadedFromServer=Vt(r.downloaded).join(" "),this.playerNetworkInfo.downloadedFromPeers=Vt(n?.downloaded||0).join(" "))},this.player().on("network-info",this.onNetworkInfoHandler),this.containerEl}dispose(){this.updateInterval&&clearInterval(this.updateInterval),this.player().off("network-info",this.onNetworkInfoHandler),super.dispose()}toggle(){this.updateInterval?this.hide():this.show()}show(){this.containerEl.style.display="block",this.updateInterval=setInterval(async()=>{if(this.mode)try{const e=this.mode==="p2p-media-loader"?this.buildHLSOptions():await this.buildWebVideoOptions();this.populateInfoValues(e)}catch(e){Ve.error("Cannot update stats.",e),clearInterval(this.updateInterval)}},this.intervalMs)}hide(){clearInterval(this.updateInterval),this.containerEl.style.display="none"}buildHLSOptions(){const e=this.player_.p2pMediaLoader(),t=e.getCurrentLevel(),i=t?.videoCodec||t?.audioCodec?`${t?.videoCodec||""} / ${t?.audioCodec||""}`:void 0,n=t?.height?`${t.height}p${t?.attrs["FRAME-RATE"]||""}`:void 0,r=this.timeRangesToString(this.player().buffered());let o,u,h;return this.options_.videoIsLive?(u=An(e.getLiveLatency()),h=An(e.getLiveLatencyFromEdge())):o=this.player().bufferedPercent(),{playerNetworkInfo:this.playerNetworkInfo,resolution:n,codecs:i,buffer:r,latency:u,latencyFromEdge:h,progress:o}}async buildWebVideoOptions(){var e;const t=this.player_.webVideo().getCurrentVideoFile();this.metadataStore[t.fileUrl]||(this.metadataStore[t.fileUrl]=await fetch(t.metadataUrl).then(p=>p.json()));const i=this.metadataStore[t.fileUrl];let n="unknown",r="unknown";if((e=i?.streams)!=null&&e[0]){const p=i.streams[0];n=p.color_space!=="unknown"?p.color_space:"bt709",r=p.codec_name||"avc1"}const o=t?.resolution.label+t?.fps,u=this.timeRangesToString(this.player_.buffered()),h=this.player_.bufferedPercent();return{playerNetworkInfo:this.playerNetworkInfo,progress:h,colorSpace:n,codecs:r,resolution:o,buffer:u}}populateInfoBlocks(){this.playerMode=this.buildInfoRow(this.player().localize("Player mode")),this.p2p=this.buildInfoRow(this.player().localize("P2P")),this.uuid=this.buildInfoRow(this.player().localize("Video UUID")),this.viewport=this.buildInfoRow(this.player().localize("Viewport / Frames")),this.resolution=this.buildInfoRow(this.player().localize("Resolution")),this.volume=this.buildInfoRow(this.player().localize("Volume")),this.codecs=this.buildInfoRow(this.player().localize("Codecs")),this.color=this.buildInfoRow(this.player().localize("Color")),this.connection=this.buildInfoRow(this.player().localize("Connection Speed")),this.network=this.buildInfoRow(this.player().localize("Network Activity")),this.transferred=this.buildInfoRow(this.player().localize("Total Transfered")),this.download=this.buildInfoRow(this.player().localize("Download Breakdown")),this.bufferProgress=this.buildInfoRow(this.player().localize("Buffer Progress")),this.bufferState=this.buildInfoRow(this.player().localize("Buffer State")),this.liveLatency=this.buildInfoRow(this.player().localize("Live Latency")),this.infoListEl.appendChild(this.playerMode.root),this.infoListEl.appendChild(this.p2p.root),this.infoListEl.appendChild(this.uuid.root),this.infoListEl.appendChild(this.viewport.root),this.infoListEl.appendChild(this.resolution.root),this.infoListEl.appendChild(this.volume.root),this.infoListEl.appendChild(this.codecs.root),this.infoListEl.appendChild(this.color.root),this.infoListEl.appendChild(this.connection.root),this.infoListEl.appendChild(this.network.root),this.infoListEl.appendChild(this.transferred.root),this.infoListEl.appendChild(this.download.root),this.infoListEl.appendChild(this.bufferProgress.root),this.infoListEl.appendChild(this.bufferState.root),this.infoListEl.appendChild(this.liveLatency.root)}populateInfoValues(e){const{playerNetworkInfo:t,progress:i,colorSpace:n,codecs:r,resolution:o,buffer:u,latency:h,latencyFromEdge:p}=e,{downloadedFromServer:d,downloadedFromPeers:g}=t,T=this.player(),b=T.getVideoPlaybackQuality(),E=Math.max(document.documentElement.clientWidth||0,window.innerWidth||0),w=Math.max(document.documentElement.clientHeight||0,window.innerHeight||0),A=(window.devicePixelRatio||1).toFixed(2),L=`${E}x${w}*${A}`,{droppedVideoFrames:P,totalVideoFrames:M}=b,O=T.localize("{1} / {2} dropped of {3}",[L,P+"",M+""]),k=T.duration();let N=`${Math.round(T.volume()*100)}`;T.muted()&&(N+=T.localize(" (muted)"));const H=t.downloadSpeed?`${t.downloadSpeed} ⇓ / ${t.uploadSpeed} ⇑`:void 0;let G=t.totalDownloaded?`${t.totalDownloaded} ⇓`:"";t.totalUploaded&&(G+=`/ ${t.totalUploaded} ⇑`);const B=t.downloadedFromServer?T.localize("{1} from servers · {2} from peers",[d,g]):void 0,D=i!==void 0?`${(i*100).toFixed(1)}% (${(i*k).toFixed(1)}s)`:void 0,K=this.options_.p2pEnabled&&this.mode==="p2p-media-loader";this.setInfoValue(this.playerMode,this.mode==="p2p-media-loader"?"P2P Media Loader (v2)":"Web Video"),this.setInfoValue(this.p2p,T.localize(K?"enabled":"disabled")),this.setInfoValue(this.uuid,this.options_.videoUUID),this.setInfoValue(this.viewport,O),this.setInfoValue(this.resolution,o),this.setInfoValue(this.volume,N),this.setInfoValue(this.codecs,r),this.setInfoValue(this.color,n),this.setInfoValue(this.transferred,G),this.setInfoValue(this.connection,t.averageBandwidth),this.setInfoValue(this.network,H),this.setInfoValue(this.download,B),this.setInfoValue(this.bufferProgress,D),this.setInfoValue(this.bufferState,u),h&&p&&this.setInfoValue(this.liveLatency,T.localize("{1} (from edge: {2})",[h,p]))}setInfoValue(e,t){if(!t){e.root.style.display="none";return}e.root.style.display="block",e.value.innerText!==t&&(e.value.innerText=t)}buildInfoRow(e){const t=X.dom.createEl("div");t.style.display="none";const i=X.dom.createEl("div",{innerText:e}),n=X.dom.createEl("span");return t.appendChild(i),t.appendChild(n),{root:t,value:n}}timeRangesToString(e){let t="";for(let i=0;i<e.length;i++){const n=Math.floor(e.start(i)),r=Math.floor(e.end(i));t+=`[${An(n)}, ${An(r)}] `}return t}}X.registerComponent("StatsCard",zp);const AT=X.getPlugin("plugin");class LT extends AT{constructor(e,t){super(e),this.player.ready(()=>{e.addClass("vjs-stats-for-nerds")}),this.statsCard=new zp(e,t),e.addChild(this.statsCard)}dispose(){this.statsCard&&(this.statsCard.dispose(),this.player.removeChild(this.statsCard)),super.dispose()}show(){this.statsCard.show()}}X.registerPlugin("stats",LT);function kT(){return/iPad|iPhone|iPod/.test(navigator.platform)?!0:!!(navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&navigator.platform.includes("MacIntel"))}function IT(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function oo(){return/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)}function RT(){return`
  <div class="vjs-bezels-pause">
    <div class="vjs-bezel" role="status" aria-label="Pause">
      <div class="vjs-bezel-icon">
        <svg height="100%" version="1.1" viewBox="0 0 36 36" width="100%">
          <use class="vjs-svg-shadow" xlink:href="#vjs-id-1"></use>
          <path class="vjs-svg-fill" d="M 12,26 16,26 16,10 12,10 z M 21,26 25,26 25,10 21,10 z" id="vjs-id-1"></path>
        </svg>
      </div>
    </div>
  </div>
  `}function PT(){return`
  <div class="vjs-bezels-play">
    <div class="vjs-bezel" role="status" aria-label="Play">
      <div class="vjs-bezel-icon">
        <svg height="100%" version="1.1" viewBox="0 0 36 36" width="100%">
          <use class="vjs-svg-shadow" xlink:href="#vjs-id-2"></use>
          <path class="vjs-svg-fill" d="M 12,26 18.5,22 18.5,14 12,10 z M 18.5,22 25,18 25,18 18.5,14 z" id="ytp-id-2"></path>
        </svg>
      </div>
    </div>
  </div>
  `}const DT=X.getComponent("Component");class Yp extends DT{constructor(e,t){super(e,t),!oo()&&(this.firstPlayDone=!1,this.paused=!1,this.playerPauseHandler=()=>{e.seeking()||(this.paused=!0,!e.ended()&&(this.container.innerHTML=RT(),this.showBezel()))},this.playerPlayHandler=()=>{if(e.seeking()||!this.firstPlayDone||!this.paused){this.firstPlayDone=!0;return}this.paused=!1,this.firstPlayDone=!0,this.container.innerHTML=PT(),this.showBezel()},this.videoChangeHandler=()=>{this.firstPlayDone=!1},e.on("video-change",()=>this.videoChangeHandler),e.on("pause",this.playerPauseHandler),e.on("play",this.playerPlayHandler))}dispose(){this.playerPauseHandler&&this.player().off("pause",this.playerPauseHandler),this.playerPlayHandler&&this.player().off("play",this.playerPlayHandler),this.videoChangeHandler&&this.player().off("video-change",this.videoChangeHandler),super.dispose()}createEl(){return this.container=super.createEl("div",{className:"vjs-bezels-content"}),this.container.style.display="none",this.container}showBezel(){this.container.style.display="inherit",setTimeout(()=>{this.container.style.display="none"},500)}}X.registerComponent("PauseBezel",Yp);const xT=X.getPlugin("plugin");class OT extends xT{constructor(e,t){super(e),this.player.ready(()=>{e.addClass("vjs-bezels")});const i=new Yp(e,t);e.addChild(i),this.on("dispose",()=>e.removeChild(i))}}X.registerPlugin("bezels",OT);function MT(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Xp={exports:{}},ft=Xp.exports={},Si,Ci;function Wu(){throw new Error("setTimeout has not been defined")}function zu(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?Si=setTimeout:Si=Wu}catch{Si=Wu}try{typeof clearTimeout=="function"?Ci=clearTimeout:Ci=zu}catch{Ci=zu}})();function Qp(s){if(Si===setTimeout)return setTimeout(s,0);if((Si===Wu||!Si)&&setTimeout)return Si=setTimeout,setTimeout(s,0);try{return Si(s,0)}catch{try{return Si.call(null,s,0)}catch{return Si.call(this,s,0)}}}function FT(s){if(Ci===clearTimeout)return clearTimeout(s);if((Ci===zu||!Ci)&&clearTimeout)return Ci=clearTimeout,clearTimeout(s);try{return Ci(s)}catch{try{return Ci.call(null,s)}catch{return Ci.call(this,s)}}}var Xi=[],Ds=!1,Xn,Va=-1;function NT(){!Ds||!Xn||(Ds=!1,Xn.length?Xi=Xn.concat(Xi):Va=-1,Xi.length&&Jp())}function Jp(){if(!Ds){var s=Qp(NT);Ds=!0;for(var e=Xi.length;e;){for(Xn=Xi,Xi=[];++Va<e;)Xn&&Xn[Va].run();Va=-1,e=Xi.length}Xn=null,Ds=!1,FT(s)}}ft.nextTick=function(s){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];Xi.push(new Zp(s,e)),Xi.length===1&&!Ds&&Qp(Jp)};function Zp(s,e){this.fun=s,this.array=e}Zp.prototype.run=function(){this.fun.apply(null,this.array)};ft.title="browser";ft.browser=!0;ft.env={};ft.argv=[];ft.version="";ft.versions={};function sn(){}ft.on=sn;ft.addListener=sn;ft.once=sn;ft.off=sn;ft.removeListener=sn;ft.removeAllListeners=sn;ft.emit=sn;ft.prependListener=sn;ft.prependOnceListener=sn;ft.listeners=function(s){return[]};ft.binding=function(s){throw new Error("process.binding is not supported")};ft.cwd=function(){return"/"};ft.chdir=function(s){throw new Error("process.chdir is not supported")};ft.umask=function(){return 0};var BT=Xp.exports;const Vl=MT(BT);var ya={exports:{}},Gl,Pd;function UT(){if(Pd)return Gl;Pd=1;var s=1e3,e=s*60,t=e*60,i=t*24,n=i*7,r=i*365.25;Gl=function(d,g){g=g||{};var T=typeof d;if(T==="string"&&d.length>0)return o(d);if(T==="number"&&isFinite(d))return g.long?h(d):u(d);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(d))};function o(d){if(d=String(d),!(d.length>100)){var g=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(d);if(g){var T=parseFloat(g[1]),b=(g[2]||"ms").toLowerCase();switch(b){case"years":case"year":case"yrs":case"yr":case"y":return T*r;case"weeks":case"week":case"w":return T*n;case"days":case"day":case"d":return T*i;case"hours":case"hour":case"hrs":case"hr":case"h":return T*t;case"minutes":case"minute":case"mins":case"min":case"m":return T*e;case"seconds":case"second":case"secs":case"sec":case"s":return T*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return T;default:return}}}}function u(d){var g=Math.abs(d);return g>=i?Math.round(d/i)+"d":g>=t?Math.round(d/t)+"h":g>=e?Math.round(d/e)+"m":g>=s?Math.round(d/s)+"s":d+"ms"}function h(d){var g=Math.abs(d);return g>=i?p(d,g,i,"day"):g>=t?p(d,g,t,"hour"):g>=e?p(d,g,e,"minute"):g>=s?p(d,g,s,"second"):d+" ms"}function p(d,g,T,b){var E=g>=T*1.5;return Math.round(d/T)+" "+b+(E?"s":"")}return Gl}var Kl,Dd;function HT(){if(Dd)return Kl;Dd=1;function s(e){i.debug=i,i.default=i,i.coerce=p,i.disable=u,i.enable=r,i.enabled=h,i.humanize=UT(),i.destroy=d,Object.keys(e).forEach(g=>{i[g]=e[g]}),i.names=[],i.skips=[],i.formatters={};function t(g){let T=0;for(let b=0;b<g.length;b++)T=(T<<5)-T+g.charCodeAt(b),T|=0;return i.colors[Math.abs(T)%i.colors.length]}i.selectColor=t;function i(g){let T,b=null,E,w;function A(...L){if(!A.enabled)return;const P=A,M=Number(new Date),O=M-(T||M);P.diff=O,P.prev=T,P.curr=M,T=M,L[0]=i.coerce(L[0]),typeof L[0]!="string"&&L.unshift("%O");let k=0;L[0]=L[0].replace(/%([a-zA-Z%])/g,(H,G)=>{if(H==="%%")return"%";k++;const B=i.formatters[G];if(typeof B=="function"){const D=L[k];H=B.call(P,D),L.splice(k,1),k--}return H}),i.formatArgs.call(P,L),(P.log||i.log).apply(P,L)}return A.namespace=g,A.useColors=i.useColors(),A.color=i.selectColor(g),A.extend=n,A.destroy=i.destroy,Object.defineProperty(A,"enabled",{enumerable:!0,configurable:!1,get:()=>b!==null?b:(E!==i.namespaces&&(E=i.namespaces,w=i.enabled(g)),w),set:L=>{b=L}}),typeof i.init=="function"&&i.init(A),A}function n(g,T){const b=i(this.namespace+(typeof T>"u"?":":T)+g);return b.log=this.log,b}function r(g){i.save(g),i.namespaces=g,i.names=[],i.skips=[];const T=(typeof g=="string"?g:"").trim().replace(" ",",").split(",").filter(Boolean);for(const b of T)b[0]==="-"?i.skips.push(b.slice(1)):i.names.push(b)}function o(g,T){let b=0,E=0,w=-1,A=0;for(;b<g.length;)if(E<T.length&&(T[E]===g[b]||T[E]==="*"))T[E]==="*"?(w=E,A=b,E++):(b++,E++);else if(w!==-1)E=w+1,A++,b=A;else return!1;for(;E<T.length&&T[E]==="*";)E++;return E===T.length}function u(){const g=[...i.names,...i.skips.map(T=>"-"+T)].join(",");return i.enable(""),g}function h(g){for(const T of i.skips)if(o(g,T))return!1;for(const T of i.names)if(o(g,T))return!0;return!1}function p(g){return g instanceof Error?g.stack||g.message:g}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return i.enable(i.load()),i}return Kl=s,Kl}var xd;function $T(){return xd||(xd=1,function(s,e){e.formatArgs=i,e.save=n,e.load=r,e.useColors=t,e.storage=o(),e.destroy=(()=>{let h=!1;return()=>{h||(h=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let h;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(h=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(h[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function i(h){if(h[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+h[0]+(this.useColors?"%c ":" ")+"+"+s.exports.humanize(this.diff),!this.useColors)return;const p="color: "+this.color;h.splice(1,0,p,"color: inherit");let d=0,g=0;h[0].replace(/%[a-zA-Z%]/g,T=>{T!=="%%"&&(d++,T==="%c"&&(g=d))}),h.splice(g,0,p)}e.log=console.debug||console.log||(()=>{});function n(h){try{h?e.storage.setItem("debug",h):e.storage.removeItem("debug")}catch{}}function r(){let h;try{h=e.storage.getItem("debug")}catch{}return!h&&typeof Vl<"u"&&"env"in Vl&&(h=Vl.env.DEBUG),h}function o(){try{return localStorage}catch{}}s.exports=HT()(e);const{formatters:u}=s.exports;u.j=function(h){try{return JSON.stringify(h)}catch(p){return"[UnexpectedJSONParseError]: "+p.message}}}(ya,ya.exports)),ya.exports}var jT=$T();const In=Fp(jT);var VT="2.0.3",Yu=500,Od="user-agent",Bs="",Md="?",lo="function",Ln="undefined",Us="object",Xu="string",Ht="browser",Yi="cpu",ki="device",fi="engine",ni="os",xs="result",ye="name",re="type",ge="vendor",Te="version",$t="architecture",Ar="major",ue="model",Tr="console",Be="mobile",Ze="tablet",yt="smarttv",Ei="wearable",ql="xr",br="embedded",lr="inapp",Rc="brands",zn="formFactors",Pc="fullVersionList",Os="platform",Dc="platformVersion",Ro="bitness",Rn="sec-ch-ua",GT=Rn+"-full-version-list",KT=Rn+"-arch",qT=Rn+"-"+Ro,WT=Rn+"-form-factors",zT=Rn+"-"+Be,YT=Rn+"-"+ue,eg=Rn+"-"+Os,XT=eg+"-version",tg=[Rc,Pc,Be,ue,Os,Dc,$t,zn,Ro],va="Amazon",bs="Apple",Fd="ASUS",Nd="BlackBerry",Vn="Google",Bd="Huawei",Ud="Lenovo",Hd="Honor",Ta="LG",Wl="Microsoft",zl="Motorola",Yl="Nvidia",$d="OnePlus",Xl="OPPO",ur="Samsung",jd="Sharp",cr="Sony",Ql="Xiaomi",Jl="Zebra",Vd="Chrome",Gd="Chromium",pn="Chromecast",QT="Edge",hr="Firefox",dr="Opera",Zl="Facebook",Kd="Sogou",_s="Mobile ",fr=" Browser",Qu="Windows",JT=typeof window!==Ln,jt=JT&&window.navigator?window.navigator:void 0,En=jt&&jt.userAgentData?jt.userAgentData:void 0,ZT=function(s,e){var t={},i=e;if(!uo(e)){i={};for(var n in e)for(var r in e[n])i[r]=e[n][r].concat(i[r]?i[r]:[])}for(var o in s)t[o]=i[o]&&i[o].length%2===0?i[o].concat(s[o]):s[o];return t},Po=function(s){for(var e={},t=0;t<s.length;t++)e[s[t].toUpperCase()]=s[t];return e},Ju=function(s,e){if(typeof s===Us&&s.length>0){for(var t in s)if(Qi(s[t])==Qi(e))return!0;return!1}return qs(s)?Qi(e).indexOf(Qi(s))!==-1:!1},uo=function(s,e){for(var t in s)return/^(browser|cpu|device|engine|os)$/.test(t)||(e?uo(s[t]):!1)},qs=function(s){return typeof s===Xu},eu=function(s){if(s){for(var e=[],t=Hs(/\\?\"/g,s).split(","),i=0;i<t.length;i++)if(t[i].indexOf(";")>-1){var n=Lr(t[i]).split(";v=");e[i]={brand:n[0],version:n[1]}}else e[i]=Lr(t[i]);return e}},Qi=function(s){return qs(s)?s.toLowerCase():s},tu=function(s){return qs(s)?Hs(/[^\d\.]/g,s).split(".")[0]:void 0},Ji=function(s){for(var e in s){var t=s[e];typeof t==Us&&t.length==2?this[t[0]]=t[1]:this[t]=void 0}return this},Hs=function(s,e){return qs(e)?e.replace(s,Bs):e},pr=function(s){return Hs(/\\?\"/g,s)},Lr=function(s,e){if(qs(s))return s=Hs(/^\s\s*/,s),typeof e===Ln?s:s.substring(0,Yu)},iu=function(s,e){if(!(!s||!e))for(var t=0,i,n,r,o,u,h;t<e.length&&!u;){var p=e[t],d=e[t+1];for(i=n=0;i<p.length&&!u&&p[i];)if(u=p[i++].exec(s),u)for(r=0;r<d.length;r++)h=u[++n],o=d[r],typeof o===Us&&o.length>0?o.length===2?typeof o[1]==lo?this[o[0]]=o[1].call(this,h):this[o[0]]=o[1]:o.length===3?typeof o[1]===lo&&!(o[1].exec&&o[1].test)?this[o[0]]=h?o[1].call(this,h,o[2]):void 0:this[o[0]]=h?h.replace(o[1],o[2]):void 0:o.length===4&&(this[o[0]]=h?o[3].call(this,h.replace(o[1],o[2])):void 0):this[o]=h||void 0;t+=2}},Sn=function(s,e){for(var t in e)if(typeof e[t]===Us&&e[t].length>0){for(var i=0;i<e[t].length;i++)if(Ju(e[t][i],s))return t===Md?void 0:t}else if(Ju(e[t],s))return t===Md?void 0:t;return e.hasOwnProperty("*")?e["*"]:s},qd={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2","8.1":"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Wd={embedded:"Automotive",mobile:"Mobile",tablet:["Tablet","EInk"],smarttv:"TV",wearable:"Watch",xr:["VR","XR"],"?":["Desktop","Unknown"],"*":void 0},zd={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[Te,[ye,_s+"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[Te,[ye,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[ye,Te],[/opios[\/ ]+([\w\.]+)/i],[Te,[ye,dr+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[Te,[ye,dr+" GX"]],[/\bopr\/([\w\.]+)/i],[Te,[ye,dr]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[Te,[ye,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[Te,[ye,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon|otter|dooble|(?:lg |qute)browser)\/([-\w\.]+)/i,/(heytap|ovi|115|surf)browser\/([\d\.]+)/i,/(ecosia|weibo)(?:__| \w+@)([\d\.]+)/i],[ye,Te],[/quark(?:pc)?\/([-\w\.]+)/i],[Te,[ye,"Quark"]],[/\bddg\/([\w\.]+)/i],[Te,[ye,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[Te,[ye,"UCBrowser"]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[Te,[ye,"WeChat"]],[/konqueror\/([\w\.]+)/i],[Te,[ye,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[Te,[ye,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[Te,[ye,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[Te,[ye,"Smart "+Ud+fr]],[/(avast|avg)\/([\w\.]+)/i],[[ye,/(.+)/,"$1 Secure"+fr],Te],[/\bfocus\/([\w\.]+)/i],[Te,[ye,hr+" Focus"]],[/\bopt\/([\w\.]+)/i],[Te,[ye,dr+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[Te,[ye,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[Te,[ye,"Dolphin"]],[/coast\/([\w\.]+)/i],[Te,[ye,dr+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[Te,[ye,"MIUI"+fr]],[/fxios\/([\w\.-]+)/i],[Te,[ye,_s+hr]],[/\bqihoobrowser\/?([\w\.]*)/i],[Te,[ye,"360"]],[/\b(qq)\/([\w\.]+)/i],[[ye,/(.+)/,"$1Browser"],Te],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[ye,/(.+)/,"$1"+fr],Te],[/samsungbrowser\/([\w\.]+)/i],[Te,[ye,ur+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[Te,[ye,Kd+" Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[ye,Kd+" Mobile"],Te],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[ye,Te],[/(lbbrowser|rekonq)/i],[ye],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[Te,ye],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[ye,Zl],Te,[re,lr]],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/(daum)apps[\/ ]([\w\.]+)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(instagram|snapchat)[\/ ]([-\w\.]+)/i],[ye,Te,[re,lr]],[/\bgsa\/([\w\.]+) .*safari\//i],[Te,[ye,"GSA"],[re,lr]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[Te,[ye,"TikTok"],[re,lr]],[/\[(linkedin)app\]/i],[ye,[re,lr]],[/(chromium)[\/ ]([-\w\.]+)/i],[ye,Te],[/headlesschrome(?:\/([\w\.]+)| )/i],[Te,[ye,Vd+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[ye,Vd+" WebView"],Te],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[Te,[ye,"Android"+fr]],[/chrome\/([\w\.]+) mobile/i],[Te,[ye,_s+"Chrome"]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[ye,Te],[/version\/([\w\.\,]+) .*mobile(?:\/\w+ | ?)safari/i],[Te,[ye,_s+"Safari"]],[/iphone .*mobile(?:\/\w+ | ?)safari/i],[[ye,_s+"Safari"]],[/version\/([\w\.\,]+) .*(safari)/i],[Te,ye],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[ye,[Te,"1"]],[/(webkit|khtml)\/([\w\.]+)/i],[ye,Te],[/(?:mobile|tablet);.*(firefox)\/([\w\.-]+)/i],[[ye,_s+hr],Te],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[ye,"Netscape"],Te],[/(wolvic|librewolf)\/([\w\.]+)/i],[ye,Te],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[Te,[ye,hr+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(amaya|dillo|doris|icab|ladybird|lynx|mosaic|netsurf|obigo|polaris|w3m|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/\b(links) \(([\w\.]+)/i],[ye,[Te,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[ye,[Te,/[^\d\.]+./,Bs]]],cpu:[[/\b((amd|x|x86[-_]?|wow|win)64)\b/i],[[$t,"amd64"]],[/(ia32(?=;))/i,/\b((i[346]|x)86)(pc)?\b/i],[[$t,"ia32"]],[/\b(aarch64|arm(v?[89]e?l?|_?64))\b/i],[[$t,"arm64"]],[/\b(arm(v[67])?ht?n?[fl]p?)\b/i],[[$t,"armhf"]],[/( (ce|mobile); ppc;|\/[\w\.]+arm\b)/i],[[$t,"arm"]],[/((ppc|powerpc)(64)?)( mac|;|\))/i],[[$t,/ower/,Bs,Qi]],[/ sun4\w[;\)]/i],[[$t,"sparc"]],[/\b(avr32|ia64(?=;)|68k(?=\))|\barm(?=v([1-7]|[5-7]1)l?|;|eabi)|(irix|mips|sparc)(64)?\b|pa-risc)/i],[[$t,Qi]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[ue,[ge,ur],[re,Ze]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[ue,[ge,ur],[re,Be]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[ue,[ge,bs],[re,Be]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[ue,[ge,bs],[re,Ze]],[/(macintosh);/i],[ue,[ge,bs]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[ue,[ge,jd],[re,Be]],[/\b((?:brt|eln|hey2?|gdi|jdn)-a?[lnw]09|(?:ag[rm]3?|jdn2|kob2)-a?[lw]0[09]hn)(?: bui|\)|;)/i],[ue,[ge,Hd],[re,Ze]],[/honor([-\w ]+)[;\)]/i],[ue,[ge,Hd],[re,Be]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?|605hw|bg2-u03|(?:gem|fdr|m2|ple|t1)-[7a]0[1-4][lu]|t1-a2[13][lw]|mediapad[\w\. ]*(?= bui|\)))\b(?!.+d\/s)/i],[ue,[ge,Bd],[re,Ze]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[ue,[ge,Bd],[re,Be]],[/oid[^\)]+; (2[\dbc]{4}(182|283|rp\w{2})[cgl]|m2105k81a?c)(?: bui|\))/i,/\b((?:red)?mi[-_ ]?pad[\w- ]*)(?: bui|\))/i],[[ue,/_/g," "],[ge,Ql],[re,Ze]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i,/ ([\w ]+) miui\/v?\d/i],[[ue,/_/g," "],[ge,Ql],[re,Be]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[ue,[ge,Xl],[re,Be]],[/\b(opd2(\d{3}a?))(?: bui|\))/i],[ue,[ge,Sn,{OnePlus:["304","403","203"],"*":Xl}],[re,Ze]],[/(vivo (5r?|6|8l?|go|one|s|x[il]?[2-4]?)[\w\+ ]*)(?: bui|\))/i],[ue,[ge,"BLU"],[re,Be]],[/; vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[ue,[ge,"Vivo"],[re,Be]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[ue,[ge,"Realme"],[re,Be]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto(?! 360)[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[ue,[ge,zl],[re,Be]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[ue,[ge,zl],[re,Ze]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[ue,[ge,Ta],[re,Ze]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+(?!.*(?:browser|netcast|android tv|watch))(\w+)/i,/\blg-?([\d\w]+) bui/i],[ue,[ge,Ta],[re,Be]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])( bui|;|\)|\/)/i,/lenovo ?(b[68]0[08]0-?[hf]?|tab(?:[\w- ]+?)|tb[\w-]{6,7})( bui|;|\)|\/)/i],[ue,[ge,Ud],[re,Ze]],[/(nokia) (t[12][01])/i],[ge,ue,[re,Ze]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,/nokia[-_ ]?(([-\w\. ]*))/i],[[ue,/_/g," "],[re,Be],[ge,"Nokia"]],[/(pixel (c|tablet))\b/i],[ue,[ge,Vn],[re,Ze]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[ue,[ge,Vn],[re,Be]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[ue,[ge,cr],[re,Be]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[ue,"Xperia Tablet"],[ge,cr],[re,Ze]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[ue,[ge,$d],[re,Be]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[ue,[ge,va],[re,Ze]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[ue,/(.+)/g,"Fire Phone $1"],[ge,va],[re,Be]],[/(playbook);[-\w\),; ]+(rim)/i],[ue,ge,[re,Ze]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[ue,[ge,Nd],[re,Be]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[ue,[ge,Fd],[re,Ze]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[ue,[ge,Fd],[re,Be]],[/(nexus 9)/i],[ue,[ge,"HTC"],[re,Ze]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[ge,[ue,/_/g," "],[re,Be]],[/tcl (xess p17aa)/i,/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])(_\w(\w|\w\w))?(\)| bui)/i],[ue,[ge,"TCL"],[re,Ze]],[/droid [\w\.]+; (418(?:7d|8v)|5087z|5102l|61(?:02[dh]|25[adfh]|27[ai]|56[dh]|59k|65[ah])|a509dl|t(?:43(?:0w|1[adepqu])|50(?:6d|7[adju])|6(?:09dl|10k|12b|71[efho]|76[hjk])|7(?:66[ahju]|67[hw]|7[045][bh]|71[hk]|73o|76[ho]|79w|81[hks]?|82h|90[bhsy]|99b)|810[hs]))(_\w(\w|\w\w))?(\)| bui)/i],[ue,[ge,"TCL"],[re,Be]],[/(itel) ((\w+))/i],[[ge,Qi],ue,[re,Sn,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[ue,[ge,"Acer"],[re,Ze]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[ue,[ge,"Meizu"],[re,Be]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[ue,[ge,"Ulefone"],[re,Be]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[ue,[ge,"Energizer"],[re,Be]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[ue,[ge,"Cat"],[re,Be]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[ue,[ge,"Smartfren"],[re,Be]],[/droid.+; (a(?:015|06[35]|142p?))/i],[ue,[ge,"Nothing"],[re,Be]],[/; (x67 5g|tikeasy \w+|ac[1789]\d\w+)( b|\))/i,/archos ?(5|gamepad2?|([\w ]*[t1789]|hello) ?\d+[\w ]*)( b|\))/i],[ue,[ge,"Archos"],[re,Ze]],[/archos ([\w ]+)( b|\))/i,/; (ac[3-6]\d\w{2,8})( b|\))/i],[ue,[ge,"Archos"],[re,Be]],[/(imo) (tab \w+)/i,/(infinix) (x1101b?)/i],[ge,ue,[re,Ze]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus(?! zenw)|dell|jolla|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (blu|hmd|imo|tcl)[_ ]([\w\+ ]+?)(?: bui|\)|; r)/i,/(hp) ([\w ]+\w)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,/(oppo) ?([\w ]+) bui/i],[ge,ue,[re,Be]],[/(kobo)\s(ereader|touch)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i],[ge,ue,[re,Ze]],[/(surface duo)/i],[ue,[ge,Wl],[re,Ze]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[ue,[ge,"Fairphone"],[re,Be]],[/((?:tegranote|shield t(?!.+d tv))[\w- ]*?)(?: b|\))/i],[ue,[ge,Yl],[re,Ze]],[/(sprint) (\w+)/i],[ge,ue,[re,Be]],[/(kin\.[onetw]{3})/i],[[ue,/\./g," "],[ge,Wl],[re,Be]],[/droid.+; ([c6]+|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[ue,[ge,Jl],[re,Ze]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[ue,[ge,Jl],[re,Be]],[/smart-tv.+(samsung)/i],[ge,[re,yt]],[/hbbtv.+maple;(\d+)/i],[[ue,/^/,"SmartTV"],[ge,ur],[re,yt]],[/tcast.+(lg)e?. ([-\w]+)/i],[ge,ue,[re,yt]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[ge,Ta],[re,yt]],[/(apple) ?tv/i],[ge,[ue,bs+" TV"],[re,yt]],[/crkey.*devicetype\/chromecast/i],[[ue,pn+" Third Generation"],[ge,Vn],[re,yt]],[/crkey.*devicetype\/([^/]*)/i],[[ue,/^/,"Chromecast "],[ge,Vn],[re,yt]],[/fuchsia.*crkey/i],[[ue,pn+" Nest Hub"],[ge,Vn],[re,yt]],[/crkey/i],[[ue,pn],[ge,Vn],[re,yt]],[/(portaltv)/i],[ue,[ge,Zl],[re,yt]],[/droid.+aft(\w+)( bui|\))/i],[ue,[ge,va],[re,yt]],[/(shield \w+ tv)/i],[ue,[ge,Yl],[re,yt]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[ue,[ge,jd],[re,yt]],[/(bravia[\w ]+)( bui|\))/i],[ue,[ge,cr],[re,yt]],[/(mi(tv|box)-?\w+) bui/i],[ue,[ge,Ql],[re,yt]],[/Hbbtv.*(technisat) (.*);/i],[ge,ue,[re,yt]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[ge,Lr],[ue,Lr],[re,yt]],[/droid.+; ([\w- ]+) (?:android tv|smart[- ]?tv)/i],[ue,[re,yt]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[re,yt]],[/(ouya)/i,/(nintendo) (\w+)/i],[ge,ue,[re,Tr]],[/droid.+; (shield)( bui|\))/i],[ue,[ge,Yl],[re,Tr]],[/(playstation \w+)/i],[ue,[ge,cr],[re,Tr]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[ue,[ge,Wl],[re,Tr]],[/\b(sm-[lr]\d\d[0156][fnuw]?s?|gear live)\b/i],[ue,[ge,ur],[re,Ei]],[/((pebble))app/i,/(asus|google|lg|oppo) ((pixel |zen)?watch[\w ]*)( bui|\))/i],[ge,ue,[re,Ei]],[/(ow(?:19|20)?we?[1-3]{1,3})/i],[ue,[ge,Xl],[re,Ei]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[ue,[ge,bs],[re,Ei]],[/(opwwe\d{3})/i],[ue,[ge,$d],[re,Ei]],[/(moto 360)/i],[ue,[ge,zl],[re,Ei]],[/(smartwatch 3)/i],[ue,[ge,cr],[re,Ei]],[/(g watch r)/i],[ue,[ge,Ta],[re,Ei]],[/droid.+; (wt63?0{2,3})\)/i],[ue,[ge,Jl],[re,Ei]],[/droid.+; (glass) \d/i],[ue,[ge,Vn],[re,ql]],[/(pico) (4|neo3(?: link|pro)?)/i],[ge,ue,[re,ql]],[/(quest( \d| pro)?s?).+vr/i],[ue,[ge,Zl],[re,ql]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[ge,[re,br]],[/(aeobc)\b/i],[ue,[ge,va],[re,br]],[/(homepod).+mac os/i],[ue,[ge,bs],[re,br]],[/windows iot/i],[[re,br]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+?(mobile|vr|\d) safari/i],[ue,[re,Sn,{mobile:"Mobile",xr:"VR","*":Ze}]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[re,Ze]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[re,Be]],[/droid .+?; ([\w\. -]+)( bui|\))/i],[ue,[ge,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[Te,[ye,QT+"HTML"]],[/(arkweb)\/([\w\.]+)/i],[ye,Te],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[Te,[ye,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[ye,Te],[/ladybird\//i],[[ye,"LibWeb"]],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[Te,ye]],os:[[/microsoft (windows) (vista|xp)/i],[ye,Te],[/(windows (?:phone(?: os)?|mobile|iot))[\/ ]?([\d\.\w ]*)/i],[ye,[Te,Sn,qd]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[Te,Sn,qd],[ye,Qu]],[/[adehimnop]{4,7}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[Te,/_/g,"."],[ye,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[ye,"macOS"],[Te,/_/g,"."]],[/android ([\d\.]+).*crkey/i],[Te,[ye,pn+" Android"]],[/fuchsia.*crkey\/([\d\.]+)/i],[Te,[ye,pn+" Fuchsia"]],[/crkey\/([\d\.]+).*devicetype\/smartspeaker/i],[Te,[ye,pn+" SmartSpeaker"]],[/linux.*crkey\/([\d\.]+)/i],[Te,[ye,pn+" Linux"]],[/crkey\/([\d\.]+)/i],[Te,[ye,pn]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[Te,ye],[/(ubuntu) ([\w\.]+) like android/i],[[ye,/(.+)/,"$1 Touch"],Te],[/(android|bada|blackberry|kaios|maemo|meego|openharmony|qnx|rim tablet os|sailfish|series40|symbian|tizen|webos)\w*[-\/\.; ]?([\d\.]*)/i],[ye,Te],[/\(bb(10);/i],[Te,[ye,Nd]],[/(?:symbian ?os|symbos|s60(?=;)|series ?60)[-\/ ]?([\w\.]*)/i],[Te,[ye,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[Te,[ye,hr+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[Te,[ye,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[Te,[ye,"watchOS"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[ye,"Chrome OS"],Te],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) (\w+)/i,/(xbox); +xbox ([^\);]+)/i,/(pico) .+os([\w\.]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux)(?: arm\w*| x86\w*| ?)([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[ye,Te],[/(sunos) ?([\w\.\d]*)/i],[[ye,"Solaris"],Te],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[ye,Te]]},ba=function(){var s={init:{},isIgnore:{},isIgnoreRgx:{},toString:{}};return Ji.call(s.init,[[Ht,[ye,Te,Ar,re]],[Yi,[$t]],[ki,[re,ue,ge]],[fi,[ye,Te]],[ni,[ye,Te]]]),Ji.call(s.isIgnore,[[Ht,[Te,Ar]],[fi,[Te]],[ni,[Te]]]),Ji.call(s.isIgnoreRgx,[[Ht,/ ?browser$/i],[ni,/ ?os$/i]]),Ji.call(s.toString,[[Ht,[ye,Te]],[Yi,[$t]],[ki,[ge,ue]],[fi,[ye,Te]],[ni,[ye,Te]]]),s}(),eb=function(s,e){var t=ba.init[e],i=ba.isIgnore[e]||0,n=ba.isIgnoreRgx[e]||0,r=ba.toString[e]||0;function o(){Ji.call(this,t)}return o.prototype.getItem=function(){return s},o.prototype.withClientHints=function(){return En?En.getHighEntropyValues(tg).then(function(u){return s.setCH(new ig(u,!1)).parseCH().get()}):s.parseCH().get()},o.prototype.withFeatureCheck=function(){return s.detectFeature().get()},e!=xs&&(o.prototype.is=function(u){var h=!1;for(var p in this)if(this.hasOwnProperty(p)&&!Ju(i,p)&&Qi(n?Hs(n,this[p]):this[p])==Qi(n?Hs(n,u):u)){if(h=!0,u!=Ln)break}else if(u==Ln&&h){h=!h;break}return h},o.prototype.toString=function(){var u=Bs;for(var h in r)typeof this[r[h]]!==Ln&&(u+=(u?" ":Bs)+this[r[h]]);return u||Ln}),En||(o.prototype.then=function(u){var h=this,p=function(){for(var g in h)h.hasOwnProperty(g)&&(this[g]=h[g])};p.prototype={is:o.prototype.is,toString:o.prototype.toString};var d=new p;return u(d),d}),new o};function ig(s,e){if(s=s||{},Ji.call(this,tg),e)Ji.call(this,[[Rc,eu(s[Rn])],[Pc,eu(s[GT])],[Be,/\?1/.test(s[zT])],[ue,pr(s[YT])],[Os,pr(s[eg])],[Dc,pr(s[XT])],[$t,pr(s[KT])],[zn,eu(s[WT])],[Ro,pr(s[qT])]]);else for(var t in s)this.hasOwnProperty(t)&&typeof s[t]!==Ln&&(this[t]=s[t])}function Yd(s,e,t,i){return this.get=function(n){return n?this.data.hasOwnProperty(n)?this.data[n]:void 0:this.data},this.set=function(n,r){return this.data[n]=r,this},this.setCH=function(n){return this.uaCH=n,this},this.detectFeature=function(){if(jt&&jt.userAgent==this.ua)switch(this.itemType){case Ht:jt.brave&&typeof jt.brave.isBrave==lo&&this.set(ye,"Brave");break;case ki:!this.get(re)&&En&&En[Be]&&this.set(re,Be),this.get(ue)=="Macintosh"&&jt&&typeof jt.standalone!==Ln&&jt.maxTouchPoints&&jt.maxTouchPoints>2&&this.set(ue,"iPad").set(re,Ze);break;case ni:!this.get(ye)&&En&&En[Os]&&this.set(ye,En[Os]);break;case xs:var n=this.data,r=function(o){return n[o].getItem().detectFeature().get()};this.set(Ht,r(Ht)).set(Yi,r(Yi)).set(ki,r(ki)).set(fi,r(fi)).set(ni,r(ni))}return this},this.parseUA=function(){return this.itemType!=xs&&iu.call(this.data,this.ua,this.rgxMap),this.itemType==Ht&&this.set(Ar,tu(this.get(Te))),this},this.parseCH=function(){var n=this.uaCH,r=this.rgxMap;switch(this.itemType){case Ht:case fi:var o=n[Pc]||n[Rc],u;if(o)for(var h in o){var p=o[h].brand||o[h],d=o[h].version;this.itemType==Ht&&!/not.a.brand/i.test(p)&&(!u||/chrom/i.test(u)&&p!=Gd)&&(p=Sn(p,{Chrome:"Google Chrome",Edge:"Microsoft Edge","Chrome WebView":"Android WebView","Chrome Headless":"HeadlessChrome","Huawei Browser":"HuaweiBrowser","MIUI Browser":"Miui Browser","Opera Mobi":"OperaMobile",Yandex:"YaBrowser"}),this.set(ye,p).set(Te,d).set(Ar,tu(d)),u=p),this.itemType==fi&&p==Gd&&this.set(Te,d)}break;case Yi:var g=n[$t];g&&(g&&n[Ro]=="64"&&(g+="64"),iu.call(this.data,g+";",r));break;case ki:if(n[Be]&&this.set(re,Be),n[ue]&&(this.set(ue,n[ue]),!this.get(re)||!this.get(ge))){var T={};iu.call(T,"droid 9; "+n[ue]+")",r),!this.get(re)&&T.type&&this.set(re,T.type),!this.get(ge)&&T.vendor&&this.set(ge,T.vendor)}if(n[zn]){var b;if(typeof n[zn]!="string")for(var E=0;!b&&E<n[zn].length;)b=Sn(n[zn][E++],Wd);else b=Sn(n[zn],Wd);this.set(re,b)}break;case ni:var w=n[Os];if(w){var A=n[Dc];w==Qu&&(A=parseInt(tu(A),10)>=13?"11":"10"),this.set(ye,w).set(Te,A)}this.get(ye)==Qu&&n[ue]=="Xbox"&&this.set(ye,"Xbox").set(Te,void 0);break;case xs:var L=this.data,P=function(M){return L[M].getItem().setCH(n).parseCH().get()};this.set(Ht,P(Ht)).set(Yi,P(Yi)).set(ki,P(ki)).set(fi,P(fi)).set(ni,P(ni))}return this},Ji.call(this,[["itemType",s],["ua",e],["uaCH",i],["rgxMap",t],["data",eb(this,s)]]),this}function nn(s,e,t){if(typeof s===Us?(uo(s,!0)?(typeof e===Us&&(t=e),e=s):(t=s,e=void 0),s=void 0):typeof s===Xu&&!uo(e,!0)&&(t=e,e=void 0),t&&typeof t.append===lo){var i={};t.forEach(function(h,p){i[p]=h}),t=i}if(!(this instanceof nn))return new nn(s,e,t).getResult();var n=typeof s===Xu?s:t&&t[Od]?t[Od]:jt&&jt.userAgent?jt.userAgent:Bs,r=new ig(t,!0),o=e?ZT(zd,e):zd,u=function(h){return h==xs?function(){return new Yd(h,n,o,r).set("ua",n).set(Ht,this.getBrowser()).set(Yi,this.getCPU()).set(ki,this.getDevice()).set(fi,this.getEngine()).set(ni,this.getOS()).get()}:function(){return new Yd(h,n,o[h],r).parseUA().get()}};return Ji.call(this,[["getBrowser",u(Ht)],["getCPU",u(Yi)],["getDevice",u(ki)],["getEngine",u(fi)],["getOS",u(ni)],["getResult",u(xs)],["getUA",function(){return n}],["setUA",function(h){return qs(h)&&(n=h.length>Yu?Lr(h,Yu):h),this}]]).setUA(n),this}nn.VERSION=VT;nn.BROWSER=Po([ye,Te,Ar,re]);nn.CPU=Po([$t]);nn.DEVICE=Po([ue,ge,re,Tr,Be,yt,Ze,Ei,br]);nn.ENGINE=nn.OS=Po([ye,Te]);function tb(s){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=e.length,i=new Uint8Array(s);let n="";for(const r of crypto.getRandomValues(i))n+=e[r%t];return n}function ng(){const s=ns("volume");if(s!=null){const e=parseFloat(s);return isNaN(e)?void 0:e}}function sg(){const s=ns("mute");if(s!=null)return s==="true"}function rg(){const s=ns("theater-enabled");return s!=null?s==="true":!1}function ag(s){return Pn("volume",s.toString())}function og(s){return Pn("mute",s.toString())}function lg(s){return Pn("theater-enabled",s.toString())}function ug(s){return Pn("average-bandwidth",s.toString())}function cg(){const s=ns("average-bandwidth");if(s!=null){const e=parseInt(s,10);return isNaN(e)?void 0:e}}function Zu(s){return Pn("last-subtitle",s)}function hg(){return ns("last-subtitle")}function dg(s){return Pn("preferred-subtitle",s)}function fg(){return ns("preferred-subtitle")}function pg(s,e){return Pn("video-watch-history",JSON.stringify({...xc(),[s]:{duration:e,date:`${new Date().toISOString()}`}}))}function xc(s){let e;try{const t=ns("video-watch-history");if(!t)return{};e=JSON.parse(t)}catch(t){Ve.error("Cannot parse video watch history from local storage/",t)}return e=e||{},s?e[s]:e}function ib(){const s=xc();if(!s)return;const e=Object.keys(s).reduce((t,i)=>{const n=Date.parse(s[i].date);return Math.ceil((new Date().getTime()-n)/(1e3*3600*24))>30?t:{...t,[i]:s[i]}},{});Pn("video-watch-history",JSON.stringify(e))}function gg(){const s="session-id";let e=nb(s);return e||(e=tb(32),sb(s,e),e)}const Do="peertube-videojs-";function ns(s){return is.getItem(Do+s)}function Pn(s,e){is.setItem(Do+s,e)}function nb(s){return Or.getItem(Do+s)}function sb(s,e){Or.setItem(Do+s,e)}const At=In("peertube:player:peertube"),rb=X.getPlugin("plugin");class ab extends rb{constructor(e,t){super(e),this.options=t,this.setUserAgentInfo(),this.menuOpened=!1,this.mouseInControlBar=!1,this.mouseInSettings=!1,this.hasInitialSeek=!1,this.videoViewUrl=t.videoViewUrl,this.authorizationHeader=t.authorizationHeader,this.hasAutoplay=t.hasAutoplay,this.initialInactivityTimeout=this.player.options_.inactivityTimeout,this.currentSubtitle=this.options.subtitle()||hg(),this.initializePlayer(),this.initOnVideoChange(),this.player.removeClass("vjs-can-play"),this.deleteLegacyIndexedDB(),this.player.on("autoplay-failure",()=>{At("Autoplay failed"),this.player.removeClass("vjs-has-autoplay"),this.player.poster(t.poster()),(kT()||IT())&&this.player.hasStarted(!1)}),this.player.on("ratechange",()=>{this.currentPlaybackRate=this.player.playbackRate(),this.player.defaultPlaybackRate(this.currentPlaybackRate)}),this.player.one("canplay",()=>{const i=this.player.options_,n=ng();n!==void 0&&this.player.volume(n);const r=i.muted!==void 0?i.muted:sg();r!==void 0&&this.player.muted(r),this.player.addClass("vjs-can-play")}),this.player.ready(()=>{this.player.on("volumechange",()=>{ag(this.player.volume()),og(this.player.muted())}),this.player.textTracks().addEventListener("change",()=>{const i=this.player.textTracks().tracks_.find(n=>n.kind==="captions"&&n.mode==="showing");if(!i){Zu("off"),this.currentSubtitle=void 0;return}this.currentSubtitle!==i.language&&(this.currentSubtitle=i.language,Zu(i.language),dg(i.language))}),this.player.on("video-change",()=>{this.initOnVideoChange(),this.hideFatalError()}),this.updatePlayerSizeClasses(),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>{this.updatePlayerSizeClasses()}),this.resizeObserver.observe(this.player.el()))}),this.player.on("resolution-change",(i,{resolution:n})=>{if(this.player.paused()){this.player.on("play",()=>this.adaptPosterForAudioOnly(n));return}this.adaptPosterForAudioOnly(n)}),this.initOnRatioChange()}dispose(){this.videoViewInterval&&clearInterval(this.videoViewInterval),this.resizeObserver&&this.resizeObserver.disconnect(),super.dispose()}onMenuOpened(){this.menuOpened=!0,this.alterInactivity()}onMenuClosed(){this.menuOpened=!1,this.alterInactivity()}displayFatalError(){if(this.errorModal)return;At("Display fatal error"),this.player.loadingSpinner.hide();const e=t=>{const i=this.player.localize.bind(this.player),n=document.createElement("div"),r=document.createElement("h1");r.innerText=i("Failed to play video"),n.appendChild(r);const o=document.createElement("div");o.innerText=i("The video failed to play due to technical issues."),n.appendChild(o);const u=document.createElement("p");return u.classList.add("error-details"),u.innerText=t.message,n.appendChild(u),n};this.errorModal=this.player.createModal(e(this.player.error()),{temporary:!0,uncloseable:!0}),this.errorModal.addClass("vjs-custom-error-display"),this.player.addClass("vjs-error-display-enabled"),/googlebot/i.test(navigator.userAgent)?console.error(this.player.error()):Ve.error("Fatal error in player",this.player.error())}hideFatalError(){this.errorModal&&(At("Hiding fatal error"),this.player.removeClass("vjs-error-display-enabled"),this.player.removeChild(this.errorModal),this.errorModal.close(),this.errorModal=void 0,this.player.loadingSpinner&&this.player.loadingSpinner.show())}setUserAgentInfo(){const e=nn(window.navigator.userAgent),t=oo()?"mobile":"desktop";this.userAgentInfo={client:e.browser.name,os:e.os.name,device:e.device.type||t}}initializePlayer(){oo()&&this.player.addClass("vjs-is-mobile"),this.initSmoothProgressBar(),this.player.ready(()=>{this.listenControlBarMouse()}),this.listenFullScreenChange()}initOnVideoChange(){this.hasAutoplay()!==!1?this.player.addClass("vjs-has-autoplay"):this.player.removeClass("vjs-has-autoplay"),this.currentPlaybackRate&&this.currentPlaybackRate!==1&&(At("Setting playback rate to "+this.currentPlaybackRate),this.player.playbackRate(this.currentPlaybackRate)),this.player.ready(()=>{this.initCaptions(),this.updateControlBar()}),this.handleStartStopTime(),this.runUserViewing()}initOnRatioChange(){if(!this.options.autoPlayerRatio)return;const e=getComputedStyle(this.player.el()).getPropertyValue(this.options.autoPlayerRatio.cssRatioVariable),t=()=>{this.options.videoRatio()&&(this.adaptPlayerFromRatio({ratio:this.options.videoRatio(),defaultRatio:e}),this.updatePlayerSizeClasses())};t(),this.player.on("video-change",()=>t()),this.player.on("video-ratio-changed",(i,n)=>{this.options.videoRatio()||(this.adaptPlayerFromRatio({ratio:n.ratio,defaultRatio:e}),this.updatePlayerSizeClasses())})}adaptPlayerFromRatio(e){const{ratio:t,defaultRatio:i}=e,n=this.player.el(),r=getComputedStyle(n).getPropertyValue(this.options.autoPlayerRatio.cssPlayerPortraitModeVariable)==="1",o=isNaN(t)||!r&&t<1?i:t;n.style.setProperty(this.options.autoPlayerRatio.cssRatioVariable,o+"")}runUserViewing(){const e=ja(this.options.startTime());let t=e,i,n=!1;this.disableUserViewing(),this.videoViewOnPlayHandler=()=>{At("Notify user is watching on play: "+e),this.notifyUserIsWatching(e,i)},this.videoViewOnSeekedHandler=()=>{if(this.hasInitialSeek){this.hasInitialSeek=!1;return}const r=Math.floor(this.player.currentTime());if(r===0&&this.player.loop()){At("Disabling viewing notification after first video loop."),this.disableUserViewing();return}const o=r-t;o>0&&o<3||(At("Detected seek event for user watching"),i="seek")},this.videoViewOnEndedHandler=()=>{if(n=!0,this.options.isLive())return;const r=Math.floor(this.player.duration());t=r,At("Notify user is watching on end: "+r),this.notifyUserIsWatching(r,i),i=void 0},this.player.one("play",this.videoViewOnPlayHandler),this.player.on("seeked",this.videoViewOnSeekedHandler),this.player.one("ended",this.videoViewOnEndedHandler),this.videoViewInterval=setInterval(()=>{if(n)return;const r=Math.floor(this.player.currentTime());r!==t&&(At("Notify user is watching: "+r),t=r,this.notifyUserIsWatching(r,i).catch(o=>Ve.error("Cannot notify user is watching.",o)),i=void 0)},this.options.videoViewIntervalMs)}disableUserViewing(){this.videoViewInterval&&(clearInterval(this.videoViewInterval),this.videoViewInterval=void 0),this.videoViewOnPlayHandler&&(this.player.off("play",this.videoViewOnPlayHandler),this.videoViewOnPlayHandler=void 0),this.videoViewOnSeekedHandler&&(this.player.off("seeked",this.videoViewOnSeekedHandler),this.videoViewOnSeekedHandler=void 0),this.videoViewOnEndedHandler&&(this.player.off("ended",this.videoViewOnEndedHandler),this.videoViewOnEndedHandler=void 0)}notifyUserIsWatching(e,t){if(this.authorizationHeader()||pg(this.options.videoUUID(),e),!this.videoViewUrl())return Promise.resolve(!0);const i=gg(),n={currentTime:e,viewEvent:t,sessionId:i,client:this.userAgentInfo.client||void 0,device:this.userAgentInfo.device||void 0,operatingSystem:this.userAgentInfo.os||void 0},r=new Headers({"Content-type":"application/json; charset=UTF-8"});return this.authorizationHeader()&&r.set("Authorization",this.authorizationHeader()),fetch(this.videoViewUrl(),{method:"POST",body:JSON.stringify(n),headers:r})}adaptPosterForAudioOnly(e){if(At("Check if we need to adapt player for audio only",e),e===0){this.player.audioPosterMode(!0),this.player.poster(this.options.poster());return}this.player.audioPosterMode(!1),this.player.poster("")}updatePlayerSizeClasses(){requestAnimationFrame(()=>{if(!this.player)return;At("Updating player size classes");const e=this.player.currentWidth(),t=[350,570,750];for(const i of t)e<=i?this.player.addClass("vjs-size-"+i):this.player.removeClass("vjs-size-"+i)})}listenFullScreenChange(){this.player.on("fullscreenchange",()=>{this.player.isFullscreen()&&this.player.focus()})}listenControlBarMouse(){const e=this.player.controlBar,t=e.settingsButton;e.on("mouseenter",()=>{this.mouseInControlBar=!0,this.alterInactivity()}),e.on("mouseleave",()=>{this.mouseInControlBar=!1,this.alterInactivity()}),t.dialog.on("mouseenter",()=>{this.mouseInSettings=!0,this.alterInactivity()}),t.dialog.on("mouseleave",()=>{this.mouseInSettings=!1,this.alterInactivity()})}alterInactivity(){if(this.menuOpened||this.mouseInSettings||this.mouseInControlBar){this.setInactivityTimeout(0);return}this.setInactivityTimeout(this.initialInactivityTimeout),this.player.reportUserActivity(!0)}setInactivityTimeout(e){this.player.cache_.inactivityTimeout=e,this.player.options_.inactivityTimeout=e}initCaptions(){this.currentSubtitle?At("Init captions with current subtitle "+this.currentSubtitle):At("Init captions without current subtitle"),this.player.tech(!0).clearTracks("text"),this.player.removeClass("vjs-has-captions");for(const e of this.options.videoCaptions())this.player.addRemoteTextTrack({kind:"captions",label:e.automaticallyGenerated?this.player.localize("{1} (auto-generated)",[e.label]):e.label,language:e.language,id:e.language,src:e.src,default:this.currentSubtitle===e.language},!0),this.player.addClass("vjs-has-captions");this.player.trigger("captions-changed")}updateControlBar(){At("Updating control bar"),this.options.isLive()?(this.getPlaybackRateButton().hide(),this.player.controlBar.getChild("progressControl").hide(),this.player.controlBar.getChild("currentTimeDisplay").hide(),this.player.controlBar.getChild("timeDivider").hide(),this.player.controlBar.getChild("durationDisplay").hide(),this.player.controlBar.getChild("peerTubeLiveDisplay").show()):(this.getPlaybackRateButton().show(),this.player.controlBar.getChild("progressControl").show(),this.player.controlBar.getChild("currentTimeDisplay").show(),this.player.controlBar.getChild("timeDivider").show(),this.player.controlBar.getChild("durationDisplay").show(),this.player.controlBar.getChild("peerTubeLiveDisplay").hide()),this.options.videoCaptions().length===0?this.getCaptionsButton().hide():this.getCaptionsButton().show()}handleStartStopTime(){this.player.duration(this.options.videoDuration()),this.stopTimeHandler&&(this.player.off("timeupdate",this.stopTimeHandler),this.stopTimeHandler=void 0),this.player.one("canplaythrough",()=>{const e=this.options.startTime();if(e!=null&&(At("Start the video at "+e),this.hasInitialSeek=!0,this.player.currentTime(ja(e))),this.options.stopTime()){const t=ja(this.options.stopTime());this.stopTimeHandler=()=>{this.player.currentTime()<=t||(At("Stopping the video at "+this.options.stopTime()),this.player.pause(),this.player.trigger("auto-stopped"),this.player.off("timeupdate",this.stopTimeHandler),this.stopTimeHandler=void 0)},this.player.on("timeupdate",this.stopTimeHandler)}})}initSmoothProgressBar(){const e=X.getComponent("SeekBar");e.prototype.getPercent=function(){const n=this.player_.currentTime()/this.player_.duration();return n>=1?1:n},e.prototype.handleMouseMove=function(i){let n=this.calculateDistance(i)*this.player_.duration();n===this.player_.duration()&&(n=n-.1),this.player_.currentTime(n),this.update()}}getCaptionsButton(){return this.player.controlBar.getDescendant(["settingsButton"]).menu.getChild("captionsButton")}getPlaybackRateButton(){return this.player.controlBar.getDescendant(["settingsButton"]).menu.getChild("playbackRateMenuButton")}deleteLegacyIndexedDB(){try{if(typeof window.indexedDB>"u"||!window.indexedDB||typeof window.indexedDB.databases!="function")return;window.indexedDB.databases().then(e=>{for(const t of e)window.indexedDB.deleteDatabase(t.name)})}catch(e){At("Cannot delete legacy indexed DB",e)}}}X.registerPlugin("peertube",ab);const ob=X.getPlugin("plugin");class lb extends ob{constructor(e){super(e),this.resolutions=[],e.on("video-change",()=>{this.resolutions=[],this.trigger("resolutions-removed")})}add(e){for(const t of e)this.resolutions.push(t);this.currentSelection=this.getSelected(),this.sort(),this.trigger("resolutions-added")}remove(e){this.resolutions=this.resolutions.filter(t=>t.id!==e),this.trigger("resolutions-removed")}getResolutions(){return this.resolutions}getSelected(){return this.resolutions.find(e=>e.selected)}getAutoResolutionChosen(){return this.resolutions.find(e=>e.id===this.autoResolutionChosenId)}select(e){var t;const{id:i,autoResolutionChosenId:n,fireCallback:r}=e;if(!(((t=this.currentSelection)==null?void 0:t.id)===i&&this.autoResolutionChosenId===n)){n!==void 0&&(this.autoResolutionChosenId=n);for(const o of this.resolutions)o.selected=o.id===i,o.selected&&(this.currentSelection=o,r&&o.selectCallback());this.trigger("resolutions-changed")}}sort(){this.resolutions.sort((e,t)=>e.id===-1?1:t.id===-1||e.height>t.height?-1:e.height===t.height?0:1)}}X.registerPlugin("peertubeResolutions",lb);const ub=X.getComponent("Button");class cb extends ub{constructor(e,t){super(e,t),e.on("texttrackchange",()=>this.update())}buildCSSClass(){return`vjs-caption-toggle-control vjs-captions-button ${super.buildCSSClass()}`}handleClick(e){var t;super.handleClick(e);const i=this.getShowing()||(t=this.getCaptionToEnable())==null?void 0:t.id;for(const n of this.player_.textTracks().tracks_)i&&n.id===i?n.mode="showing":n.mode="disabled"}update(){var e;if(this.getShowing()){this.controlText("Disable subtitles"),this.addClass("enabled");return}this.controlText(this.player_.localize("Enable {1} subtitle",[(e=this.getCaptionToEnable())==null?void 0:e.label])),this.removeClass("enabled")}getShowing(){return this.listCaptions().find(e=>e.mode==="showing")}getCaptionToEnable(){var e;const t=fg()||((e=this.listCaptions()[0])==null?void 0:e.id),i=this.listCaptions();return i.find(n=>n.id===t)||i[0]}listCaptions(){return this.player_.textTracks().tracks_.filter(e=>e.kind==="captions")}}X.registerComponent("CaptionToggleButton",cb);const hb=X.getPlugin("plugin");class db extends hb{constructor(e,t){super(e,t),this.url=t.url,this.height=t.height,this.width=t.width,this.interval=t.interval,this.sprites={},this.boundedHijackMouseTooltip=this.hijackMouseTooltip.bind(this),this.init(),this.player.ready(()=>{e.addClass("vjs-storyboard")})}init(){var e,t,i,n,r;const o=this.player.controlBar;this.progress=o?.progressControl,this.seekBar=(e=this.progress)==null?void 0:e.seekBar,this.mouseTimeTooltip=(i=(t=this.seekBar)==null?void 0:t.mouseTimeDisplay)==null?void 0:i.timeTooltip,this.spritePlaceholder=X.dom.createEl("div",{className:"vjs-storyboard-sprite-placeholder"}),(r=(n=this.seekBar)==null?void 0:n.el())==null||r.appendChild(this.spritePlaceholder),this.onReadyOrLoadstartHandler=u=>{if(u.type!=="ready"){const h=this.player.currentSources().find(d=>Object.prototype.hasOwnProperty.call(d,"storyboard")),p=h?.storyboard;p&&(this.url=p.url,this.height=p.height,this.width=p.width,this.interval=p.interval)}this.cached=!!this.sprites[this.url],this.load()},this.player.on(["ready","loadstart"],this.onReadyOrLoadstartHandler)}dispose(){var e,t;this.onReadyOrLoadstartHandler&&this.player.off(["ready","loadstart"],this.onReadyOrLoadstartHandler),this.progress&&this.progress.off(["mousemove","touchmove"],this.boundedHijackMouseTooltip),(t=(e=this.seekBar)==null?void 0:e.el())==null||t.removeChild(this.spritePlaceholder),super.dispose()}load(){const e=["mousemove","touchmove"];this.isReady()?(this.cached||(this.sprites[this.url]=X.dom.createEl("img",{src:this.url})),this.progress.on(e,this.boundedHijackMouseTooltip)):(this.progress.off(e,this.boundedHijackMouseTooltip),this.resetMouseTooltip())}hijackMouseTooltip(e){const t=this.sprites[this.url],i=t.naturalWidth,n=t.naturalHeight,r=this.seekBar.el();if(!t.complete||!i||!n){this.resetMouseTooltip();return}this.player.requestNamedAnimationFrame("StoryBoardPlugin#hijackMouseTooltip",()=>{const o=X.dom.getBoundingClientRect(r),u=X.dom.getBoundingClientRect(this.player.el());if(!o||!u)return;const h=X.dom.getPointerPosition(r,e).x;let p=h*this.player.duration();const d=Math.round(n/this.height*(i/this.width))-1;p=Math.min(p/this.interval,d);const g=600,T=this.player.currentWidth(),b=T<g?T/g:1,E=i/this.width,w=this.width*b,A=this.height*b,L=Math.floor(p%E)*-w,P=Math.floor(p/E)*-A,M=`${i*b}px ${n*b}px`,O=this.player.el().querySelector(".vjs-time-tooltip"),k=-A+parseInt(getComputedStyle(O).top.replace("px",""))-20,N=Math.round(w/2);let H=o.width*h-N;const G=u.left-o.left,B=o.width-w+(u.right-o.right);H<G&&(H=G),H>B&&(H=B);const D={"background-image":`url("${this.url}")`,"background-repeat":"no-repeat","background-position":`${L}px ${P}px`,"background-size":M,color:"#fff","text-shadow":"1px 1px #000",position:"relative",top:`${k}px`,border:"1px solid #000",width:`${w+2}px`,height:`${A+2}px`};D.left=`${H}px`;for(const[K,oe]of Object.entries(D))this.spritePlaceholder.style.setProperty(K,oe)})}resetMouseTooltip(){this.spritePlaceholder&&(this.spritePlaceholder.style.cssText="")}isReady(){return this.mouseTimeTooltip&&this.width&&this.height&&this.url}}X.registerPlugin("storyboard",db);const fb=X.getComponent("ClickableComponent");class mg extends fb{constructor(e,t){super(e,t);const i=()=>{if(!this.hasValidDuration())return;const r=this.el();r.style.setProperty("left",this.buildLeftStyle()),r.style.setProperty("display","inline")};this.player().on("durationchange",i);const n=r=>r.stopPropagation();this.on(["mousedown","touchstart"],n),this.one("dispose",()=>{this.player()&&this.player().off("durationchange",i),this.el()&&this.off(["mousedown","touchstart"],n)})}createEl(){return X.dom.createEl("span",{className:"vjs-chapter-marker",style:this.hasValidDuration()?`left: ${this.buildLeftStyle()}`:"display: none;"})}handleClick(e){e.stopPropagation(),this.player()&&this.player().currentTime(this.options_.timecode)}buildLeftStyle(){return`${this.options_.timecode/this.player().duration()*100}%`}hasValidDuration(){const e=this.player().duration();return!(isNaN(e)||!e)}}X.registerComponent("ProgressBarMarkerComponent",mg);const pb=X.getPlugin("plugin");class gb extends pb{constructor(e,t){super(e,t),Ke(this,"activeChapter"),this.markers=[],this.chapters=t.chapters,this.player.ready(()=>{e.addClass("vjs-chapters");for(const i of this.chapters){if(i.timecode===0)continue;const n=new mg(e,{timecode:i.timecode});n.on("mouseenter",()=>this.activeChapter=i),n.on("mouseleave",()=>this.activeChapter=void 0),this.markers.push(n),this.getSeekBar().addChild(n)}})}dispose(){for(const e of this.markers)this.getSeekBar().removeChild(e);super.dispose()}getChapter(e){if(this.activeChapter)return this.player.addClass("has-chapter"),{title:this.activeChapter.title,fixedTimecode:this.activeChapter.timecode};if(this.chapters.length!==0)for(let t=this.chapters.length-1;t>=0;t--){const i=this.chapters[t];if(i.timecode<=e)return this.player.addClass("has-chapter"),{title:i.title}}return this.player.removeClass("has-chapter"),{title:""}}getSeekBar(){return this.player.getDescendant("ControlBar","ProgressControl","SeekBar")}}X.registerPlugin("chapters",gb);const mb=X.getComponent("TimeTooltip");class yb extends mb{write(e){var t;const i=this.player();if(i.usingPlugin("chapters")){if(e===this.currentTimecode)return;this.currentTimecode=e;const{title:n,fixedTimecode:r}=i.chapters().getChapter(ja(this.currentTimecode));if(n){const o=r?X.formatTime(r,(t=this.player())==null?void 0:t.duration()):this.currentTimecode;return super.write(n+`\r
`+o)}}return super.write(e)}}X.registerComponent("TimeTooltip",yb);const vb=X.getComponent("Button");class yg extends vb{constructor(e,t){super(e,t),this.player().on("video-change",()=>{this.updateDisabled(),this.updateShowing()}),this.updateDisabled(),this.updateShowing()}createEl(){const e=this.options_.type,t=X.dom.createEl("button",{className:"vjs-"+e+"-video"}),i=X.dom.createEl("span",{className:"icon icon-"+e});return t.appendChild(i),e==="next"?t.title=this.player_.localize("Next video"):t.title=this.player_.localize("Previous video"),t}handleClick(){this.options_.handler()}updateDisabled(){this.options_.isDisabled()?this.addClass("vjs-disabled"):this.removeClass("vjs-disabled")}updateShowing(){this.options_.isDisplayed()?this.show():this.hide()}}X.registerComponent("NextVideoButton",yg);X.registerComponent("PreviousVideoButton",yg);const Tb=X.getComponent("Button");class bb extends Tb{createEl(){const e=X.dom.createEl("div",{className:"vjs-peertube"}),t=X.dom.createEl("div",{className:"vjs-peertube-hidden"});e.appendChild(t);const i=X.dom.createEl("span",{className:"icon icon-download"});t.appendChild(i);const n=X.dom.createEl("span",{className:"download-speed-text"}),r=X.dom.createEl("span",{className:"download-speed-number"}),o=X.dom.createEl("span");n.appendChild(r),n.appendChild(o),t.appendChild(n);const u=X.dom.createEl("span",{className:"icon icon-upload"});t.appendChild(u);const h=X.dom.createEl("span",{className:"upload-speed-text"}),p=X.dom.createEl("span",{className:"upload-speed-number"}),d=X.dom.createEl("span");h.appendChild(p),h.appendChild(d),t.appendChild(h);const g=X.dom.createEl("span",{className:"peers-text"}),T=X.dom.createEl("span",{className:"peers-number"});t.appendChild(T),t.appendChild(g);const b=X.dom.createEl("div",{className:"vjs-peertube-hidden"}),E=X.dom.createEl("span",{className:"http-fallback"});return b.appendChild(E),e.appendChild(b),this.player_.on("network-info",(w,A)=>{if(!A.p2p)return;t.className="vjs-peertube-displayed",b.className="vjs-peertube-hidden";const L=A.p2p,P=A.http,M=Vt(L.downloadSpeed+P.downloadSpeed),O=Vt(L.uploadSpeed),k=Vt(L.downloaded+P.downloaded),N=Vt(L.uploaded),H=L.peersWithWebSeed;if(t.title=this.player().localize("Total downloaded: ")+k.join(" ")+`
`,A.source==="p2p-media-loader"){const G=Vt(P.downloaded).join(" "),B=Vt(L.downloaded).join(" ");t.title+=" * "+this.player().localize("From servers: ")+G+`
 * `+this.player().localize("From peers: ")+B+`
`}t.title+=this.player().localize("Total uploaded: ")+N.join(" "),r.textContent=M[0],o.textContent=" "+M[1],p.textContent=O[0],d.textContent=" "+O[1],T.textContent=H.toString(),g.textContent=" "+(H>1?this.player().localize("peers"):this.player_.localize("peer")),b.className="vjs-peertube-hidden",t.className="vjs-peertube-displayed"}),this.player_.on("network-info",(w,A)=>{A.p2p||(A.source==="web-video"?E.textContent="HTTP":A.source==="p2p-media-loader"&&(E.textContent="HLS"),b.className="vjs-peertube-displayed",t.className="vjs-peertube-hidden",b.title=this.player().localize("Total downloaded: ")+Vt(A.http.downloaded).join(" "))}),this.player_.on("video-change",()=>{t.className="vjs-peertube-hidden",b.className="vjs-peertube-hidden"}),e}}X.registerComponent("P2PInfoButton",bb);const _b=X.getComponent("Component");class Eb extends _b{constructor(e,t){super(e,t),this.updateShowing(),this.player().on("video-change",()=>this.updateShowing())}dispose(){this.el()||(this.el().removeEventListener("mouseenter",this.mouseEnterHandler),this.el().removeEventListener("click",this.clickHandler),super.dispose())}createEl(){const e=X.dom.createEl("a",{href:this.buildLink(),innerText:this.options_.instanceName,title:this.player().localize("Video page (new window)"),className:"vjs-peertube-link",target:"_blank"});return this.mouseEnterHandler=()=>this.updateHref(),this.clickHandler=()=>this.player().pause(),e.addEventListener("mouseenter",this.mouseEnterHandler),e.addEventListener("click",this.clickHandler),e}updateShowing(){this.options_.isDisplayed()?this.show():this.hide()}updateHref(){this.el().setAttribute("href",this.buildLink())}buildLink(){const e=qu({shortUUID:this.options_.shortUUID()});return jp({url:e,startTime:this.player().currentTime()})}}X.registerComponent("PeerTubeLinkButton",Eb);const Sb=X.getComponent("Button"),vg=class Ga extends Sb{constructor(e,t){super(e,t),this.theaterButtonOptions=t;const i=rg();i===!0&&(this.player().addClass(Ga.THEATER_MODE_CLASS),this.handleTheaterChange()),this.controlText("Theater mode"),this.player().theaterEnabled=i,this.updateShowing(),this.player().on("video-change",()=>this.updateShowing())}buildCSSClass(){return`vjs-theater-control ${super.buildCSSClass()}`}handleTheaterChange(){const e=this.isTheaterEnabled();e?this.controlText("Normal mode"):this.controlText("Theater mode"),lg(e),this.player_.trigger("theater-change",e)}handleClick(){this.player_.toggleClass(Ga.THEATER_MODE_CLASS),this.handleTheaterChange()}isTheaterEnabled(){return this.player_.hasClass(Ga.THEATER_MODE_CLASS)}updateShowing(){this.theaterButtonOptions.isDisplayed()?this.show():this.hide()}};Ke(vg,"THEATER_MODE_CLASS","vjs-theater-enabled");let Cb=vg;X.registerComponent("TheaterButton",Cb);const wb=X.getComponent("ClickableComponent");class Ab extends wb{constructor(e,t){super(e,t),this.interval=this.setInterval(()=>this.updateClass(),1e3),this.updateSync(!0)}dispose(){this.interval&&(this.clearInterval(this.interval),this.interval=void 0),this.contentEl_=null,super.dispose()}createEl(){const e=super.createEl("div",{className:"vjs-pt-live-control vjs-control"});return this.contentEl_=X.dom.createEl("div",{className:"vjs-live-display"},{"aria-live":"off"}),this.contentEl_.appendChild(X.dom.createEl("span",{className:"vjs-control-text",textContent:`${this.localize("Stream Type")} `})),this.contentEl_.appendChild(document.createTextNode(this.localize("LIVE"))),e.appendChild(this.contentEl_),e}handleClick(){const e=this.getHLSJS();e&&(this.player().currentTime(e.liveSyncPosition),this.player().play(),this.updateSync(!0))}updateClass(){const e=this.getHLSJS();if(!e||this.player().currentTime()===0)return;const t=Math.abs(this.player().currentTime()-e.liveSyncPosition)<10;this.updateSync(t)}updateSync(e){e?(this.addClass("synced-with-live-edge"),this.removeAttribute("title"),this.disable()):(this.removeClass("synced-with-live-edge"),this.setAttribute("title",this.localize("Go back to the live")),this.enable())}getHLSJS(){var e;if((e=this.player())!=null&&e.usingPlugin("p2pMediaLoader"))return this.player().p2pMediaLoader().getHLSJS()}}X.registerComponent("PeerTubeLiveDisplay",Ab);const Lb=X.getComponent("Menu"),kb=X.getComponent("Component");class Tg extends Lb{handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),e.stopPropagation(),this.trigger("escaped-key");return}return super.handleKeyDown(e)}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){const t=this.children().slice();if(t.length&&t[0].hasClass("vjs-menu-title")&&t.shift(),t.length>0){e<0?e=0:e>=t.length&&(e=t.length-1);const n=t[e].el();if(n.classList.contains("vjs-hidden"))return this.focusedChild_<e?e===t.length-1?void 0:this.focus(e+1):e===0?void 0:this.focus(e-1);this.focusedChild_=e,n.focus()}}}kb.registerComponent("MenuFocusFixed",Tg);const Ib=X.getComponent("MenuItem");class bg extends Ib{constructor(e,t){super(e,{...t,selectable:!0}),this.autoResolutionChosen="",this.resolutionId=t.resolutionId,this.label=t.label,this.updateSelectionHandler=()=>this.updateSelection(),e.peertubeResolutions().on("resolutions-changed",this.updateSelectionHandler)}dispose(){this.player().peertubeResolutions().off("resolutions-changed",this.updateSelectionHandler),super.dispose()}handleClick(e){super.handleClick(e),this.player().peertubeResolutions().select({id:this.resolutionId,fireCallback:!0})}updateSelection(){var e;const t=this.player().peertubeResolutions().getSelected();this.resolutionId===-1&&(this.autoResolutionChosen=(e=this.player().peertubeResolutions().getAutoResolutionChosen())==null?void 0:e.label),this.selected(this.resolutionId===t.id)}getLabel(){return this.resolutionId===-1?this.label+" <small>"+this.autoResolutionChosen+"</small>":this.label}}X.registerComponent("ResolutionMenuItem",bg);const Rb=X.getComponent("Menu"),Pb=X.getComponent("MenuButton");class Db extends Pb{constructor(e,t){super(e,t),this.controlText("Quality"),e.peertubeResolutions().on("resolutions-added",()=>this.update()),e.peertubeResolutions().on("resolutions-removed",()=>this.update()),e.peertubeResolutions().on("resolutions-changed",()=>{setTimeout(()=>this.trigger("label-updated"))})}createEl(){const e=super.createEl();return this.labelEl_=X.dom.createEl("div",{className:"vjs-resolution-value"}),e.appendChild(this.labelEl_),e}updateARIAAttributes(){this.el().setAttribute("aria-label","Quality")}createMenu(){const e=new Rb(this.player_,{menuButton:this}),t=this.player().peertubeResolutions().getResolutions();for(const i of t){const n=i.label==="0p"?this.player().localize("Audio only"):i.label,r=new bg(this.player_,{id:i.id+"",resolutionId:i.id,label:n,selected:i.selected});e.addItem(r)}return e}update(){super.update(),this.trigger("resolution-menu-changed")}buildCSSClass(){return"vjs-resolution-button "+super.buildCSSClass()}buildWrapperCSSClass(){return"vjs-resolution-control "+super.buildWrapperCSSClass()}}X.registerComponent("ResolutionMenuButton",Db);const _g=X.getComponent("Component");class xb extends _g{constructor(e){super(e),this.hide()}createEl(){const e=this.id(),t="TTsettingsDialogLabel-"+e,i="TTsettingsDialogDescription-"+e;return super.createEl("div",{className:"vjs-settings-dialog vjs-modal-overlay",tabIndex:-1},{role:"dialog","aria-labelledby":t,"aria-describedby":i})}show(){this.player().addClass("vjs-settings-dialog-opened"),super.show()}hide(){this.player().removeClass("vjs-settings-dialog-opened"),super.hide()}}_g.registerComponent("SettingsDialog",xb);const Ob=In("peertube:player:settings"),Xd=X.getComponent("MenuItem"),Mb=X.getComponent("Component");class Oc extends Xd{constructor(e,t){super(e,t),this.settingsButton=t.menuButton,this.dialog=this.settingsButton.dialog,this.mainMenu=this.settingsButton.menu,this.panel=this.dialog.getChild("settingsPanel"),this.panelChild=this.panel.getChild("settingsPanelChild"),this.panelChildEl=this.panelChild.el(),this.size=null,this.menuToLoad="mainmenu";const i=Wp(t.entry),n=X.getComponent(i);if(!n)throw new Error(`Component ${i} does not exist`);const r=Object.assign({},t,{entry:t.menuButton,menuButton:this});this.subMenu=new n(this.player(),r);const o=this.subMenu.buildCSSClass().split(" ")[0];this.settingsSubMenuEl_.className+=" "+o,this.eventHandlers(),e.ready(()=>{setTimeout(()=>{this.player_&&(this.build(),i==="PlaybackRateMenuButton"&&e.on("ratechange",this.submenuClickHandler),i==="CaptionsButton"&&(e.on("captions-changed",()=>{setTimeout(()=>this.rebuildAfterMenuChange())}),e.on("texttrackchange",this.submenuClickHandler)),i==="ResolutionMenuButton"&&this.subMenu.on("resolution-menu-changed",()=>{this.rebuildAfterMenuChange()}),this.reset())},0)})}dispose(){this.settingsSubMenuEl_.removeEventListener("transitionend",this.transitionEndHandler),super.dispose()}eventHandlers(){this.submenuClickHandler=this.onSubmenuClick.bind(this),this.transitionEndHandler=this.onTransitionEnd.bind(this)}onSubmenuClick(e){let t=null;if(e.type==="tap"?t=e.target:t=e.currentTarget||e.target,t?.classList.contains("vjs-back-button")){this.loadMainMenu();return}setTimeout(()=>this.update(e),0),this.subMenu.menu.removeClass("vjs-hidden")}createEl(){const e=X.dom.createEl("li",{className:"vjs-menu-item",tabIndex:0});return this.settingsSubMenuTitleEl_=X.dom.createEl("div",{className:"vjs-settings-sub-menu-title"}),e.appendChild(this.settingsSubMenuTitleEl_),this.settingsSubMenuValueEl_=X.dom.createEl("div",{className:"vjs-settings-sub-menu-value"}),e.appendChild(this.settingsSubMenuValueEl_),this.settingsSubMenuEl_=X.dom.createEl("div",{className:"vjs-settings-sub-menu"}),e}handleClick(e){this.menuToLoad="submenu",X.dom.removeClass(this.el(),"open"),super.handleClick(e),this.mainMenu.el().style.opacity="0",X.dom.hasClass(this.settingsSubMenuEl_,"vjs-hidden")?(X.dom.removeClass(this.settingsSubMenuEl_,"vjs-hidden"),setTimeout(()=>{this.settingsSubMenuEl_.style.opacity="1",this.settingsSubMenuEl_.style.marginRight="0px"},0),this.settingsButton.setDialogSize(this.size),this.subMenu.menu.focus()):X.dom.addClass(this.settingsSubMenuEl_,"vjs-hidden")}createBackButton(){const e=this.subMenu.menu.addChild("MenuItem",{},0);e.setAttribute("aria-label",this.player().localize("Go back")),e.addClass("vjs-back-button"),e.el().innerHTML=this.player().localize(this.subMenu.controlText())}onTransitionEnd(e){e.propertyName==="margin-right"&&this.menuToLoad==="mainmenu"&&(X.dom.addClass(this.settingsSubMenuEl_,"vjs-hidden"),this.settingsSubMenuEl_.style.opacity="0")}reset(){X.dom.addClass(this.settingsSubMenuEl_,"vjs-hidden"),this.settingsSubMenuEl_.style.opacity="0",this.setMargin()}loadMainMenu(){const e=this.mainMenu.el();this.menuToLoad="mainmenu",this.mainMenu.show(),e.style.opacity="0";const t=this.mainMenu;this.settingsButton.setDialogSize([t.width(),t.height()]),setTimeout(()=>{this.setMargin(),e.style.opacity="1",this.mainMenu.focus()},0)}build(){this.subMenu.on("label-updated",()=>{this.update()}),this.settingsSubMenuTitleEl_.innerHTML=this.player().localize(this.subMenu.controlText()),this.settingsSubMenuEl_.appendChild(this.subMenu.menu.el()),this.panelChildEl.appendChild(this.settingsSubMenuEl_),this.update(),this.createBackButton(),this.setSize(),this.bindClickEvents(),this.settingsSubMenuEl_.addEventListener("transitionend",this.transitionEndHandler,!1)}update(e){if(this.subMenu.name()==="PlaybackRateMenuButton")this.settingsSubMenuValueEl_.innerHTML=this.subMenu.labelEl_.textContent;else for(const i of this.subMenu.menu.children_){if(!(i instanceof Xd))continue;const n=i;if(n.isSelected_){if(typeof n.getLabel=="function"){this.settingsSubMenuValueEl_.innerHTML=n.getLabel();break}this.settingsSubMenuValueEl_.innerHTML=this.player().localize(n.options_.label)}}let t=null;e&&e.type==="tap"?t=e.target:e&&(t=e.currentTarget),t&&!t.classList.contains("vjs-back-button")&&this.settingsButton.hideDialog()}bindClickEvents(){for(const e of this.subMenu.menu.children())e instanceof Mb&&e.on(["tap","click"],this.submenuClickHandler)}setSize(){this.dialog.removeClass("vjs-hidden"),X.dom.removeClass(this.settingsSubMenuEl_,"vjs-hidden"),this.size=this.settingsButton.getComponentSize(this.settingsSubMenuEl_),this.setMargin(),this.dialog.addClass("vjs-hidden"),X.dom.addClass(this.settingsSubMenuEl_,"vjs-hidden")}setMargin(){if(!this.size)return;const[e]=this.size;this.settingsSubMenuEl_.style.marginRight=`-${e}px`}hideSubMenu(){this.el()&&X.dom.hasClass(this.el(),"open")&&(X.dom.addClass(this.settingsSubMenuEl_,"vjs-hidden"),X.dom.removeClass(this.el(),"open"))}rebuildAfterMenuChange(){Ob("Rebuilding menu "+this.subMenu.name()+" after change"),this.settingsSubMenuEl_.innerHTML="",this.settingsSubMenuEl_.appendChild(this.subMenu.menu.el()),this.update(),this.createBackButton(),this.setSize(),this.bindClickEvents()}}Oc.prototype.contentElType="button";X.registerComponent("SettingsMenuItem",Oc);const Fb=X.getComponent("Button"),Eg=X.getComponent("Component");class Nb extends Fb{constructor(e,t){super(e,t),this.settingsButtonOptions=t,this.controlText("Settings"),this.dialog=this.player().addChild("settingsDialog"),this.dialogEl=this.dialog.el(),this.menu=null,this.panel=this.dialog.addChild("settingsPanel"),this.panelChild=this.panel.addChild("settingsPanelChild"),this.addClass("vjs-settings"),this.addSettingsItemHandler=this.onAddSettingsItem.bind(this),this.disposeSettingsItemHandler=this.onDisposeSettingsItem.bind(this),this.documentClickHandler=this.onDocumentClick.bind(this),this.userInactiveHandler=this.onUserInactive.bind(this),this.buildMenu(),this.bindEvents(),this.player().one("play",()=>this.hideDialog())}onDocumentClick(e){var t,i,n;const r=e.target;(t=r?.classList)!=null&&t.contains("vjs-settings")||(n=(i=r?.parentElement)==null?void 0:i.classList)!=null&&n.contains("vjs-settings")||this.dialog.hasClass("vjs-hidden")||this.hideDialog()}onDisposeSettingsItem(e,t){if(t===void 0){const i=this.menu.children();for(;i.length>0;)i[0].dispose(),this.menu.removeChild(i[0]);this.addClass("vjs-hidden")}else{const i=this.menu.getChild(t);i&&(i.dispose(),this.menu.removeChild(i))}this.hideDialog(),this.settingsButtonOptions.entries.length===0&&this.addClass("vjs-hidden")}dispose(){document.removeEventListener("click",this.documentClickHandler),this.isInIframe()&&window.removeEventListener("blur",this.documentClickHandler),super.dispose()}onAddSettingsItem(e,t){const[i,n]=t;this.addMenuItem(i,n),this.removeClass("vjs-hidden")}onUserInactive(){this.dialog.hasClass("vjs-hidden")||this.hideDialog()}bindEvents(){document.addEventListener("click",this.documentClickHandler),this.isInIframe()&&window.addEventListener("blur",this.documentClickHandler),this.player().on("addsettingsitem",this.addSettingsItemHandler),this.player().on("disposesettingsitem",this.disposeSettingsItemHandler),this.player().on("userinactive",this.userInactiveHandler)}buildCSSClass(){return`vjs-icon-settings ${super.buildCSSClass()}`}handleClick(){this.dialog.hasClass("vjs-hidden")?this.showDialog():this.hideDialog()}showDialog(){this.player().peertube().onMenuOpened(),this.menu.el().style.opacity="1",this.dialog.show(),this.el().setAttribute("aria-expanded","true"),this.setDialogSize(this.getComponentSize(this.menu)),this.menu.focus()}hideDialog(){this.player_.peertube().onMenuClosed(),this.dialog.hide(),this.el().setAttribute("aria-expanded","false"),this.setDialogSize(this.getComponentSize(this.menu)),this.menu.el().style.opacity="1",this.resetChildren()}getComponentSize(e){let t=null,i=null;if(e instanceof Eg){const n=e.el();t=n.offsetWidth,i=n.offsetHeight}else t=e.offsetWidth,i=e.offsetHeight;return[t,i]}setDialogSize([e,t]){if(typeof t!="number")return;const i=this.settingsButtonOptions.setup.maxHeightOffset,n=this.player().el().offsetHeight-i,r=this.panel.el();t>n?(t=n,e+=15,r.style.maxHeight=`${t}px`):r.style.maxHeight!==""&&(r.style.maxHeight=""),this.dialogEl.style.width=`${e}px`,this.dialogEl.style.height=`${t}px`}buildMenu(){this.menu=new Tg(this.player()),this.menu.on("escaped-key",()=>{this.hideDialog(),this.focus()}),this.menu.addClass("vjs-main-menu");const e=this.settingsButtonOptions.entries;if(e.length===0){this.addClass("vjs-hidden"),this.panelChild.addChild(this.menu);return}for(const t of e)this.addMenuItem(t,this.settingsButtonOptions);this.panelChild.addChild(this.menu)}addMenuItem(e,t){const i=function(){X.dom.hasClass(this.el_,"open")?X.dom.removeClass(this.el_,"open"):X.dom.addClass(this.el_,"open")};t.name=Wp(e);const n=Object.assign({},t,{entry:e,menuButton:this}),r=new Oc(this.player(),n);this.menu.addChild(r),r.on("click",X.bind(this,this.hideChildren)),r.on("click",i)}resetChildren(){for(const e of this.menu.children())e.reset()}hideChildren(){for(const e of this.menu.children())e.hideSubMenu()}isInIframe(){return window.self!==window.top}}Eg.registerComponent("SettingsButton",Nb);const Sg=X.getComponent("Component");class Bb extends Sg{createEl(){return super.createEl("div",{className:"vjs-settings-panel",tabIndex:-1})}}Sg.registerComponent("SettingsPanel",Bb);const Cg=X.getComponent("Component");class Ub extends Cg{createEl(){return super.createEl("div",{className:"vjs-settings-panel-child",tabIndex:-1})}}Cg.registerComponent("SettingsPanelChild",Ub);const Hb=X.getComponent("ClickableComponent");class wg extends Hb{constructor(e,t){super(e,t)}createEl(){this.wrapper=super.createEl("div",{className:"vjs-playlist-button",tabIndex:-1});const e=super.createEl("div",{className:"vjs-playlist-icon",tabIndex:-1});return this.playlistInfoElement=super.createEl("div",{className:"vjs-playlist-info",tabIndex:-1}),this.wrapper.appendChild(e),this.wrapper.appendChild(this.playlistInfoElement),this.update(),this.wrapper}update(){this.playlistInfoElement.innerText=this.options_.getCurrentPosition()+"/"+this.options_.playlist.videosLength,this.wrapper.title=this.player().localize("Playlist: {1}",[this.options_.playlist.displayName])}handleClick(){this.options_.playlistMenu.open()}}X.registerComponent("PlaylistButton",wg);const Ag=X.getComponent("Component");class Lg extends Ag{constructor(e,t){super(e,t),this.emitTapEvents(),this.element=t.element,this.clickHandler=()=>this.switchPlaylistItem(),this.keyDownHandler=i=>this.handleKeyDown(i),this.on(["click","tap"],this.clickHandler),this.on("keydown",this.keyDownHandler)}dispose(){this.off(["click","tap"],this.clickHandler),this.off("keydown",this.keyDownHandler),super.dispose()}createEl(){const e=super.createEl("li",{className:"vjs-playlist-menu-item"});this.options_.element.video||e.classList.add("vjs-disabled");const t=super.createEl("div",{className:"item-position-block"}),i=super.createEl("div",{className:"item-position",innerText:this.options_.element.position});return t.appendChild(i),e.appendChild(t),this.options_.element.video?this.buildAvailableVideo(e,t,this.options_):this.buildUnavailableVideo(e),e}setSelected(e){e?this.addClass("vjs-selected"):this.removeClass("vjs-selected")}getElement(){return this.element}buildAvailableVideo(e,t,i){const n=i.element,r=super.createEl("div",{className:"item-player"});t.appendChild(r);const o=super.createEl("img",{src:window.location.origin+n.video.thumbnailPath}),u=super.createEl("div",{className:"info-block"}),h=super.createEl("div",{innerText:n.video.name,className:"title"}),p=super.createEl("div",{innerText:n.video.channel.displayName,className:"channel"});if(u.appendChild(h),u.appendChild(p),n.startTimestamp||n.stopTimestamp){let d="";n.startTimestamp&&(d+=An(n.startTimestamp)),n.stopTimestamp&&(d+=" - "+An(n.stopTimestamp));const g=super.createEl("div",{innerText:d,className:"timestamps"});u.append(g)}e.append(o),e.append(u)}buildUnavailableVideo(e){const t=super.createEl("div",{className:"item-unavailable",innerText:this.player().localize("Unavailable video")});e.appendChild(t)}handleKeyDown(e){(e.code==="Space"||e.code==="Enter")&&this.switchPlaylistItem()}switchPlaylistItem(){this.options_.onClicked()}}Ag.registerComponent("PlaylistMenuItem",Lg);const kg=X.getComponent("Component");class Ig extends kg{constructor(e,t){super(e,t),this.menuItems=[],this.userInactiveHandler=()=>{this.close()},this.onMouseEnter=()=>{this.player().off("userinactive",this.userInactiveHandler)},this.onMouseLeave=()=>{this.player().one("userinactive",this.userInactiveHandler)},this.onPlayerCick=i=>{let n=i.target;do{if(n.classList.contains("vjs-playlist-menu")||n.classList.contains("vjs-playlist-button"))return;n=n.parentElement}while(n);this.close()},this.el().addEventListener("mouseenter",this.onMouseEnter),this.el().addEventListener("mouseleave",this.onMouseLeave),this.player().on("click",this.onPlayerCick)}dispose(){this.el().removeEventListener("mouseenter",this.onMouseEnter),this.el().removeEventListener("mouseleave",this.onMouseLeave),this.player().off("userinactive",this.userInactiveHandler),this.player().off("click",this.onPlayerCick);for(const e of this.menuItems)e.dispose();super.dispose()}createEl(){this.menuItems=[];const e=super.createEl("div",{className:"vjs-playlist-menu",tabIndex:-1}),t=super.createEl("div",{className:"header"}),i=super.createEl("div"),n=super.createEl("div",{innerText:this.options_.playlist.displayName,className:"title"}),r=this.options_.playlist.videoChannel,o=super.createEl("div",{innerText:r?this.player().localize("By {1}",[r.displayName]):"",className:"channel"});i.appendChild(n),i.appendChild(o);const u=super.createEl("div",{className:"cross"});u.addEventListener("click",()=>this.close()),t.appendChild(i),t.appendChild(u);const h=super.createEl("ol");for(const p of this.options_.elements){const d=new Lg(this.player(),{element:p,onClicked:()=>this.onItemClicked(p)});h.appendChild(d.el()),this.menuItems.push(d)}return e.appendChild(t),e.appendChild(h),this.update(),e}update(){this.updateSelected(this.options_.getCurrentPosition())}open(){this.player().addClass("playlist-menu-displayed")}close(){this.player().removeClass("playlist-menu-displayed")}updateSelected(e){for(const t of this.menuItems)t.setSelected(t.getElement().position===e)}onItemClicked(e){this.options_.onItemClicked(e)}}kg.registerComponent("PlaylistMenu",Ig);const $b=X.getPlugin("plugin");class jb extends $b{constructor(e,t){super(e,t),this.playlistMenu=new Ig(e,t),this.playlistButton=new wg(e,{...t,playlistMenu:this.playlistMenu}),e.addChild(this.playlistMenu,t),e.addChild(this.playlistButton,t)}dispose(){this.player.removeClass("vjs-playlist"),this.playlistMenu.dispose(),this.playlistButton.dispose(),this.player.removeChild(this.playlistMenu),this.player.removeChild(this.playlistButton),super.dispose()}}X.registerPlugin("playlist",jb);const Es=In("peertube:player:mobile"),Vb=X.getPlugin("plugin"),Mc=class Ka extends Vb{constructor(e,t){super(e,t),this.seekAmount=0,X.browser.IS_ANDROID&&screen.orientation&&this.handleFullscreenRotation(),e.controls()&&(this.peerTubeMobileButtons=e.addChild("PeerTubeMobileButtons",{reportTouchActivity:!1}),this.player.options_.userActions||(this.player.options_.userActions={}),this.player.options_.userActions.click=!1,this.player.options_.userActions.doubleClick=!1,this.onPlayHandler=()=>this.initTouchStartEvents(),this.player.one("play",this.onPlayHandler),this.seekBar=this.player.getDescendant(["controlBar","progressControl","seekBar"]),this.sliderActiveHandler=()=>this.player.addClass("vjs-mobile-sliding"),this.sliderInactiveHandler=()=>this.player.removeClass("vjs-mobile-sliding"),this.seekBar.on("slideractive",this.sliderActiveHandler),this.seekBar.on("sliderinactive",this.sliderInactiveHandler))}dispose(){var e;this.onPlayHandler&&this.player.off("play",this.onPlayHandler),this.onFullScreenChangeHandler&&this.player.off("fullscreenchange",this.onFullScreenChangeHandler),this.onTouchStartHandler&&this.player.off("touchstart",this.onFullScreenChangeHandler),this.onMobileButtonTouchStartHandler&&((e=this.peerTubeMobileButtons)==null||e.el().removeEventListener("touchstart",this.onMobileButtonTouchStartHandler)),super.dispose()}handleFullscreenRotation(){this.onFullScreenChangeHandler=()=>{!this.player.isFullscreen()||this.isPortraitVideo()||screen.orientation.lock("landscape").catch(e=>Ve.error("Cannot lock screen to landscape.",e))},this.player.on("fullscreenchange",this.onFullScreenChangeHandler)}isPortraitVideo(){return this.player.videoWidth()<this.player.videoHeight()}initTouchStartEvents(){const e=(t,i=!1)=>{if(Es("Handle touch start"),this.tapTimeout&&(clearTimeout(this.tapTimeout),this.tapTimeout=void 0),this.doubleTapping||this.lastTapEvent&&t.timeStamp-this.lastTapEvent.timeStamp<Ka.DOUBLE_TAP_DELAY_MS){Es("Detected double tap"),this.lastTapEvent=t,this.onDoubleTap(t);return}i||(this.newActiveState=!this.player.userActive(),!this.player.paused()&&this.newActiveState===!0&&this.player.addClass("vjs-force-inactive"),this.tapTimeout=setTimeout(()=>{Es("No double tap detected, set user active state to "+this.newActiveState),this.player.removeClass("vjs-force-inactive"),this.player.userActive(this.newActiveState)},Ka.DOUBLE_TAP_DELAY_MS),this.lastTapEvent=t)};this.onTouchStartHandler=t=>{const i=this.player.userActive();e(t,i)},this.player.on("touchstart",this.onTouchStartHandler),this.onMobileButtonTouchStartHandler=t=>{t.preventDefault(),t.stopPropagation(),e(t)},this.peerTubeMobileButtons.el().addEventListener("touchstart",this.onMobileButtonTouchStartHandler,{passive:!1})}onDoubleTap(e){const t=this.player.currentWidth(),i=this.findPlayerTarget(e.target).getBoundingClientRect(),n=e.targetTouches[0].pageX-i.left;Es("Calculating double tap zone (player width: %d, offset X: %d)",t,n),n>.66*t?(this.seekAmount<0&&(this.seekAmount=0),this.seekAmount+=10,Es("Will forward %d seconds",this.seekAmount)):n<.33*t&&(this.seekAmount>0&&(this.seekAmount=0),this.seekAmount-=10,Es("Will rewind %d seconds",this.seekAmount)),this.peerTubeMobileButtons.displayFastSeek(this.seekAmount),this.scheduleSetCurrentTime()}findPlayerTarget(e){return e.classList.contains("video-js")?e:this.findPlayerTarget(e.parentElement)}scheduleSetCurrentTime(){this.player.pause(),this.player.addClass("vjs-fast-seeking"),this.doubleTapping=!0,this.setCurrentTimeTimeout&&clearTimeout(this.setCurrentTimeTimeout),this.setCurrentTimeTimeout=setTimeout(()=>{let e=this.player.currentTime()+this.seekAmount;this.seekAmount=0,e=Math.max(0,e),e=Math.min(this.player.duration(),e),this.player.currentTime(e),this.seekAmount=0,this.peerTubeMobileButtons.displayFastSeek(0),this.player.userActive(!1),this.doubleTapping=!1,this.player.play(),setTimeout(()=>{this.player.removeClass("vjs-fast-seeking"),this.player.removeClass("vjs-force-inactive")},100)},Ka.SET_CURRENT_TIME_DELAY)}};Ke(Mc,"DOUBLE_TAP_DELAY_MS",250);Ke(Mc,"SET_CURRENT_TIME_DELAY",750);let Gb=Mc;X.registerPlugin("peertubeMobile",Gb);const Kb=X.getComponent("Component");class qb extends Kb{createEl(){const e=super.createEl("div",{className:"vjs-mobile-buttons-overlay"});this.mainButton=super.createEl("div",{className:"main-button"}),this.touchStartHandler=t=>{if(t.stopPropagation(),this.player_.paused()||this.player_.ended()){this.player_.play();return}this.player_.pause()},this.mainButton.addEventListener("touchstart",this.touchStartHandler,{passive:!0}),this.rewind=super.createEl("div",{className:"rewind-button vjs-hidden"}),this.forward=super.createEl("div",{className:"forward-button vjs-hidden"});for(let t=0;t<3;t++)this.rewind.appendChild(super.createEl("span",{className:"icon"})),this.forward.appendChild(super.createEl("span",{className:"icon"}));return this.rewindText=this.rewind.appendChild(super.createEl("div",{className:"text"})),this.forwardText=this.forward.appendChild(super.createEl("div",{className:"text"})),e.appendChild(this.rewind),e.appendChild(this.mainButton),e.appendChild(this.forward),e}dispose(){this.touchStartHandler&&this.mainButton.removeEventListener("touchstart",this.touchStartHandler),super.dispose()}displayFastSeek(e){if(e===0){this.hideRewind(),this.hideForward();return}if(e>0){this.hideRewind(),this.displayForward(e);return}if(e<0){this.hideForward(),this.displayRewind(e);return}}hideRewind(){this.rewind.classList.add("vjs-hidden"),this.rewindText.textContent=""}displayRewind(e){this.rewind.classList.remove("vjs-hidden"),this.rewindText.textContent=this.player().localize("{1} seconds",[e+""])}hideForward(){this.forward.classList.add("vjs-hidden"),this.forwardText.textContent=""}displayForward(e){this.forward.classList.remove("vjs-hidden"),this.forwardText.textContent=this.player().localize("{1} seconds",[e+""])}}X.registerComponent("PeerTubeMobileButtons",qb);const Wb=X.getPlugin("plugin"),Fc=class _r extends Wb{constructor(e,t){super(e,t),this.isLive=t.isLive,this.handlers=this.buildHandlers(),this.handleKeyFunction=i=>this.onKeyDown(i),document.addEventListener("keydown",this.handleKeyFunction)}dispose(){document.removeEventListener("keydown",this.handleKeyFunction),super.dispose()}onKeyDown(e){if(this.isValidKeyTarget(e.target)){for(const t of this.handlers)if(t.accept(e)){t.cb(e);return}}}buildHandlers(){const e=[{accept:t=>t.key===" "||t.key==="MediaPlayPause",cb:t=>{t.preventDefault(),t.stopPropagation(),this.player.paused()?this.player.play():this.player.pause()}},{accept:t=>this.isNaked(t,"ArrowUp"),cb:t=>{t.preventDefault(),this.player.volume(this.player.volume()+_r.VOLUME_STEP)}},{accept:t=>this.isNaked(t,"ArrowDown"),cb:t=>{t.preventDefault(),this.player.volume(this.player.volume()-_r.VOLUME_STEP)}},{accept:t=>this.isNaked(t,"f")||!t.altKey&&t.ctrlKey&&t.key==="Enter",cb:t=>{t.preventDefault(),this.player.isFullscreen()?this.player.exitFullscreen():this.player.requestFullscreen()}},{accept:t=>this.isNaked(t,"m"),cb:t=>{t.preventDefault(),this.player.muted(!this.player.muted())}},{accept:t=>t.key===">",cb:()=>{if(this.isLive)return;const t=Math.min(this.player.playbackRate()+.1,5);this.player.playbackRate(parseFloat(t.toFixed(2)))}},{accept:t=>t.key==="<",cb:()=>{if(this.isLive)return;const t=Math.max(this.player.playbackRate()-.1,.1);this.player.playbackRate(parseFloat(t.toFixed(2)))}},{accept:t=>t.key===",",cb:()=>{if(this.isLive)return;this.player.pause();const t=1/30;this.player.currentTime(this.player.currentTime()-t)}},{accept:t=>t.key===".",cb:()=>{if(this.isLive)return;this.player.pause();const t=1/30;this.player.currentTime(this.player.currentTime()+t)}}];return this.isLive?e:e.concat(this.buildVODHandlers())}buildVODHandlers(){const e=[{accept:t=>this.isNaked(t,"ArrowLeft")||this.isNaked(t,"MediaRewind"),cb:t=>{if(this.isLive)return;t.preventDefault();const i=Math.max(0,this.player.currentTime()-_r.SEEK_STEP);this.player.currentTime(i)}},{accept:t=>this.isNaked(t,"ArrowRight")||this.isNaked(t,"MediaForward"),cb:t=>{if(this.isLive)return;t.preventDefault();const i=Math.min(this.player.duration(),this.player.currentTime()+_r.SEEK_STEP);this.player.currentTime(i)}}];for(let t=0;t<10;t++)e.push({accept:i=>this.isNakedOrShift(i,t+""),cb:i=>{this.isLive||(i.preventDefault(),this.player.currentTime(this.player.duration()*t*.1))}});return e}isValidKeyTarget(e){const t=this.player.el(),i=document.activeElement,n=e.tagName.toLowerCase();return i===t||i===t.querySelector(".vjs-tech")||i===t.querySelector(".vjs-control-bar")||e.id==="content"||n==="body"||n==="video"}isNaked(e,t){return t.length===1&&(t=t.toUpperCase()),!e.ctrlKey&&!e.altKey&&!e.metaKey&&!e.shiftKey&&this.getLatinKey(e.key,e.code)===t}isNakedOrShift(e,t){return!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key===t}getLatinKey(e,t){if(e.length!==1)return e;if(e.charCodeAt(0)>=880){if(t.indexOf("Key")===0&&t.length===4)return t.charAt(3);if(t.indexOf("Digit")===0&&t.length===6)return t.charAt(5)}return e.toUpperCase()}};Ke(Fc,"VOLUME_STEP",.1);Ke(Fc,"SEEK_STEP",5);let zb=Fc;X.registerPlugin("peerTubeHotkeysPlugin",zb);const gr=In("peertube:player:metrics"),Yb=X.getPlugin("plugin");class Xb extends Yb{constructor(e,t){super(e),this.options_=t,this.downloadedBytesP2P=0,this.downloadedBytesHTTP=0,this.uploadedBytesP2P=0,this.resolutionChanges=0,this.errors=0,this.bufferStalled=0,this.p2pPeers=0,this.trackBytes(),this.trackResolutionChange(),this.trackErrors(),this.trackBufferStalled(),this.one("play",()=>{this.player.on("video-change",()=>{this.runMetricsIntervalOnPlay()})}),this.runMetricsIntervalOnPlay()}dispose(){this.metricsInterval&&clearInterval(this.metricsInterval),super.dispose()}runMetricsIntervalOnPlay(){this.downloadedBytesP2P=0,this.downloadedBytesHTTP=0,this.uploadedBytesP2P=0,this.resolutionChanges=0,this.errors=0,this.bufferStalled=0,this.lastPlayerNetworkInfo=void 0,gr("Will track metrics on next play"),this.player.one("play",()=>{gr("Tracking metrics"),this.runMetricsInterval()})}runMetricsInterval(){this.metricsInterval&&clearInterval(this.metricsInterval),this.options_.metricsUrl()&&(this.metricsInterval=setInterval(()=>{let e,t;if(this.player.usingPlugin("p2pMediaLoader")){const r=this.player.p2pMediaLoader().getCurrentLevel();if(!r)return;e=Math.min(r.height||0,r.width||0);const o=r?.attrs["FRAME-RATE"];t=o?parseInt(o,10):void 0}else if(this.player.usingPlugin("webVideo")){const r=this.player.webVideo().getCurrentVideoFile();if(!r)return;e=r.resolution.id,t=r.fps&&r.fps!==-1?r.fps:void 0}else return;const i={resolution:e,fps:t,playerMode:this.options_.mode(),resolutionChanges:this.resolutionChanges,errors:this.errors,bufferStalled:this.bufferStalled,downloadedBytesHTTP:this.downloadedBytesHTTP,downloadedBytesP2P:this.downloadedBytesP2P,uploadedBytesP2P:this.uploadedBytesP2P,p2pPeers:this.p2pPeers,p2pEnabled:this.p2pEnabled,videoId:this.options_.videoUUID()};this.resolutionChanges=0,this.downloadedBytesP2P=0,this.downloadedBytesHTTP=0,this.uploadedBytesP2P=0,this.errors=0,this.bufferStalled=0;const n=new Headers({"Content-type":"application/json; charset=UTF-8"});return fetch(this.options_.metricsUrl(),{method:"POST",body:JSON.stringify(i),headers:n}).catch(r=>Ve.clientWarn("Cannot send metrics to the server.",r))},this.options_.metricsInterval()))}trackBytes(){this.player.on("network-info",(e,t)=>{var i,n,r,o,u,h,p,d;this.downloadedBytesHTTP+=Math.max(Math.round(t.http.downloaded-(((i=this.lastPlayerNetworkInfo)==null?void 0:i.http.downloaded)||0)),0),this.downloadedBytesP2P+=Math.max(Math.round((((n=t.p2p)==null?void 0:n.downloaded)||0)-(((o=(r=this.lastPlayerNetworkInfo)==null?void 0:r.p2p)==null?void 0:o.downloaded)||0)),0),this.uploadedBytesP2P+=Math.max(Math.round((((u=t.p2p)==null?void 0:u.uploaded)||0)-(((p=(h=this.lastPlayerNetworkInfo)==null?void 0:h.p2p)==null?void 0:p.uploaded)||0)),0),this.p2pPeers=(d=t.p2p)==null?void 0:d.peersP2POnly,this.p2pEnabled=!!t.p2p,this.lastPlayerNetworkInfo=t})}trackResolutionChange(){this.player.on("resolution-change",(e,{initResolutionChange:t})=>{t!==!0&&(gr("Adding resolution change"),this.resolutionChanges++)})}trackErrors(){this.player.on("error",()=>{gr("Adding player error"),this.errors++})}trackBufferStalled(){this.player.on("buffer-stalled",()=>{gr("Adding buffer stalled"),this.bufferStalled++})}}X.registerPlugin("metrics",Xb);function Qb(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Rg={exports:{}};(function(s,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,n=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,o=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,u={buildAbsoluteURL:function(h,p,d){if(d=d||{},h=h.trim(),p=p.trim(),!p){if(!d.alwaysNormalize)return h;var g=u.parseURL(h);if(!g)throw new Error("Error trying to parse base URL.");return g.path=u.normalizePath(g.path),u.buildURLFromParts(g)}var T=u.parseURL(p);if(!T)throw new Error("Error trying to parse relative URL.");if(T.scheme)return d.alwaysNormalize?(T.path=u.normalizePath(T.path),u.buildURLFromParts(T)):p;var b=u.parseURL(h);if(!b)throw new Error("Error trying to parse base URL.");if(!b.netLoc&&b.path&&b.path[0]!=="/"){var E=n.exec(b.path);b.netLoc=E[1],b.path=E[2]}b.netLoc&&!b.path&&(b.path="/");var w={scheme:b.scheme,netLoc:T.netLoc,path:null,params:T.params,query:T.query,fragment:T.fragment};if(!T.netLoc&&(w.netLoc=b.netLoc,T.path[0]!=="/"))if(!T.path)w.path=b.path,T.params||(w.params=b.params,T.query||(w.query=b.query));else{var A=b.path,L=A.substring(0,A.lastIndexOf("/")+1)+T.path;w.path=u.normalizePath(L)}return w.path===null&&(w.path=d.alwaysNormalize?u.normalizePath(T.path):T.path),u.buildURLFromParts(w)},parseURL:function(h){var p=i.exec(h);return p?{scheme:p[1]||"",netLoc:p[2]||"",path:p[3]||"",params:p[4]||"",query:p[5]||"",fragment:p[6]||""}:null},normalizePath:function(h){for(h=h.split("").reverse().join("").replace(r,"");h.length!==(h=h.replace(o,"")).length;);return h.split("").reverse().join("")},buildURLFromParts:function(h){return h.scheme+h.netLoc+h.path+h.params+h.query+h.fragment}};s.exports=u})()})(Rg);var Nc=Rg.exports;function Qd(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);e&&(i=i.filter(function(n){return Object.getOwnPropertyDescriptor(s,n).enumerable})),t.push.apply(t,i)}return t}function St(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Qd(Object(t),!0).forEach(function(i){e_(s,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):Qd(Object(t)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(t,i))})}return s}function Jb(s,e){if(typeof s!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var i=t.call(s,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(s)}function Zb(s){var e=Jb(s,"string");return typeof e=="symbol"?e:String(e)}function e_(s,e,t){return e=Zb(e),e in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function vt(){return vt=Object.assign?Object.assign.bind():function(s){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(s[i]=t[i])}return s},vt.apply(this,arguments)}const Ae=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},t_=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=i_},i_=Number.MAX_SAFE_INTEGER||9007199254740991;let I=function(s){return s.MEDIA_ATTACHING="hlsMediaAttaching",s.MEDIA_ATTACHED="hlsMediaAttached",s.MEDIA_DETACHING="hlsMediaDetaching",s.MEDIA_DETACHED="hlsMediaDetached",s.BUFFER_RESET="hlsBufferReset",s.BUFFER_CODECS="hlsBufferCodecs",s.BUFFER_CREATED="hlsBufferCreated",s.BUFFER_APPENDING="hlsBufferAppending",s.BUFFER_APPENDED="hlsBufferAppended",s.BUFFER_EOS="hlsBufferEos",s.BUFFER_FLUSHING="hlsBufferFlushing",s.BUFFER_FLUSHED="hlsBufferFlushed",s.MANIFEST_LOADING="hlsManifestLoading",s.MANIFEST_LOADED="hlsManifestLoaded",s.MANIFEST_PARSED="hlsManifestParsed",s.LEVEL_SWITCHING="hlsLevelSwitching",s.LEVEL_SWITCHED="hlsLevelSwitched",s.LEVEL_LOADING="hlsLevelLoading",s.LEVEL_LOADED="hlsLevelLoaded",s.LEVEL_UPDATED="hlsLevelUpdated",s.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",s.LEVELS_UPDATED="hlsLevelsUpdated",s.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",s.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",s.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",s.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",s.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",s.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",s.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",s.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",s.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",s.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",s.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",s.CUES_PARSED="hlsCuesParsed",s.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",s.INIT_PTS_FOUND="hlsInitPtsFound",s.FRAG_LOADING="hlsFragLoading",s.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",s.FRAG_LOADED="hlsFragLoaded",s.FRAG_DECRYPTED="hlsFragDecrypted",s.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",s.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",s.FRAG_PARSING_METADATA="hlsFragParsingMetadata",s.FRAG_PARSED="hlsFragParsed",s.FRAG_BUFFERED="hlsFragBuffered",s.FRAG_CHANGED="hlsFragChanged",s.FPS_DROP="hlsFpsDrop",s.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",s.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",s.ERROR="hlsError",s.DESTROYING="hlsDestroying",s.KEY_LOADING="hlsKeyLoading",s.KEY_LOADED="hlsKeyLoaded",s.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",s.BACK_BUFFER_REACHED="hlsBackBufferReached",s.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",s}({}),xe=function(s){return s.NETWORK_ERROR="networkError",s.MEDIA_ERROR="mediaError",s.KEY_SYSTEM_ERROR="keySystemError",s.MUX_ERROR="muxError",s.OTHER_ERROR="otherError",s}({}),te=function(s){return s.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",s.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",s.KEY_SYSTEM_NO_SESSION="keySystemNoSession",s.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",s.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",s.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",s.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",s.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",s.MANIFEST_LOAD_ERROR="manifestLoadError",s.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",s.MANIFEST_PARSING_ERROR="manifestParsingError",s.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",s.LEVEL_EMPTY_ERROR="levelEmptyError",s.LEVEL_LOAD_ERROR="levelLoadError",s.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",s.LEVEL_PARSING_ERROR="levelParsingError",s.LEVEL_SWITCH_ERROR="levelSwitchError",s.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",s.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",s.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",s.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",s.FRAG_LOAD_ERROR="fragLoadError",s.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",s.FRAG_DECRYPT_ERROR="fragDecryptError",s.FRAG_PARSING_ERROR="fragParsingError",s.FRAG_GAP="fragGap",s.REMUX_ALLOC_ERROR="remuxAllocError",s.KEY_LOAD_ERROR="keyLoadError",s.KEY_LOAD_TIMEOUT="keyLoadTimeOut",s.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",s.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",s.BUFFER_APPEND_ERROR="bufferAppendError",s.BUFFER_APPENDING_ERROR="bufferAppendingError",s.BUFFER_STALLED_ERROR="bufferStalledError",s.BUFFER_FULL_ERROR="bufferFullError",s.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",s.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",s.INTERNAL_EXCEPTION="internalException",s.INTERNAL_ABORTED="aborted",s.UNKNOWN="unknown",s}({});const qn=function(){},ec={trace:qn,debug:qn,log:qn,warn:qn,info:qn,error:qn};let Cr=ec;function n_(s){const e=self.console[s];return e?e.bind(self.console,`[${s}] >`):qn}function s_(s,...e){e.forEach(function(t){Cr[t]=s[t]?s[t].bind(s):n_(t)})}function r_(s,e){if(typeof console=="object"&&s===!0||typeof s=="object"){s_(s,"debug","log","info","warn","error");try{Cr.log(`Debug logs enabled for "${e}" in hls.js version 1.5.20`)}catch{Cr=ec}}else Cr=ec}const W=Cr,a_=/^(\d+)x(\d+)$/,Jd=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ct{constructor(e){typeof e=="string"&&(e=ct.parseAttrList(e)),vt(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const i=new Uint8Array(t.length/2);for(let n=0;n<t.length/2;n++)i[n]=parseInt(t.slice(n*2,n*2+2),16);return i}else return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}bool(e){return this[e]==="YES"}decimalResolution(e){const t=a_.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const i={},n='"';for(Jd.lastIndex=0;(t=Jd.exec(e))!==null;){let r=t[2];r.indexOf(n)===0&&r.lastIndexOf(n)===r.length-1&&(r=r.slice(1,-1));const o=t[1].trim();i[o]=r}return i}}function o_(s){return s!=="ID"&&s!=="CLASS"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function l_(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"}class Pg{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const i=t.attr;for(const n in i)if(Object.prototype.hasOwnProperty.call(e,n)&&e[n]!==i[n]){W.warn(`DATERANGE tag attribute: "${n}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=n;break}e=vt(new ct({}),i,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const i=new Date(this.attr["END-DATE"]);Ae(i.getTime())&&(this._endDate=i)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return e!==null?new Date(this._startDate.getTime()+e*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(Ae(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 isValid(){return!!this.id&&!this._badValueForSameId&&Ae(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class xo{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var Je={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Dg{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[Je.AUDIO]:null,[Je.VIDEO]:null,[Je.AUDIOVIDEO]:null},this.baseurl=e}setByteRange(e,t){const i=e.split("@",2);let n;i.length===1?n=t?.byteRangeEndOffset||0:n=parseInt(i[1]),this._byteRange=[n,parseInt(i[0])+n]}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Nc.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class nu extends Dg{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new xo,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const i=Object.keys(this.levelkeys);if(i.length===1)return this._decryptdata=this.levelkeys[i[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!Ae(this.programDateTime))return null;const e=Ae(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),i=t.length;if(i>1||i===1&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,n,r,o=!1){const{elementaryStreams:u}=this,h=u[e];if(!h){u[e]={startPTS:t,endPTS:i,startDTS:n,endDTS:r,partial:o};return}h.startPTS=Math.min(h.startPTS,t),h.endPTS=Math.max(h.endPTS,i),h.startDTS=Math.min(h.startDTS,n),h.endDTS=Math.max(h.endDTS,r)}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Je.AUDIO]=null,e[Je.VIDEO]=null,e[Je.AUDIOVIDEO]=null}}class u_ extends Dg{constructor(e,t,i,n,r){super(i),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.stats=new xo,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=n;const o=e.enumeratedString("BYTERANGE");o&&this.setByteRange(o,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}const c_=10;class h_{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.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?Ae(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||c_}get drift(){const 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(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end: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 lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function Bc(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function d_(s){const e=tc(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function f_(s){const e=function(i,n,r){const o=i[n];i[n]=i[r],i[r]=o};e(s,0,3),e(s,1,2),e(s,4,5),e(s,6,7)}function p_(s){const e=s.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),n=i[i.length-1].split(",");if(n.length===2){const r=n[0]==="base64",o=n[1];r?(i.splice(-1,1),t=Bc(o)):t=d_(o)}}return t}function tc(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}const $s=typeof self<"u"?self:void 0;var Ye={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Gt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function su(s){switch(s){case Gt.FAIRPLAY:return Ye.FAIRPLAY;case Gt.PLAYREADY:return Ye.PLAYREADY;case Gt.WIDEVINE:return Ye.WIDEVINE;case Gt.CLEARKEY:return Ye.CLEARKEY}}var _a={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function ru(s){if(s===_a.WIDEVINE)return Ye.WIDEVINE;if(s===_a.PLAYREADY)return Ye.PLAYREADY;if(s===_a.CENC||s===_a.CLEARKEY)return Ye.CLEARKEY}function au(s){switch(s){case Ye.FAIRPLAY:return Gt.FAIRPLAY;case Ye.PLAYREADY:return Gt.PLAYREADY;case Ye.WIDEVINE:return Gt.WIDEVINE;case Ye.CLEARKEY:return Gt.CLEARKEY}}function Ea(s){const{drmSystems:e,widevineLicenseUrl:t}=s,i=e?[Ye.FAIRPLAY,Ye.WIDEVINE,Ye.PLAYREADY,Ye.CLEARKEY].filter(n=>!!e[n]):[];return!i[Ye.WIDEVINE]&&t&&i.push(Ye.WIDEVINE),i}const xg=function(s){return $s!=null&&(s=$s.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function g_(s,e,t,i){let n;switch(s){case Ye.FAIRPLAY:n=["cenc","sinf"];break;case Ye.WIDEVINE:case Ye.PLAYREADY:n=["cenc"];break;case Ye.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return m_(n,e,t,i)}function m_(s,e,t,i){return[{initDataTypes:s,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs="${r}"`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs="${r}"`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function Og(s){const e=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),i=t.substring(t.indexOf("<"),t.length),o=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(o){const u=o.childNodes[0]?o.childNodes[0].nodeValue:o.getAttribute("VALUE");if(u){const h=Bc(u).subarray(0,16);return f_(h),h}}return null}function Zn(s,e,t){return Uint8Array.prototype.slice?s.slice(e,t):new Uint8Array(Array.prototype.slice.call(s,e,t))}const Uc=(s,e)=>e+10<=s.length&&s[e]===73&&s[e+1]===68&&s[e+2]===51&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128,Mg=(s,e)=>e+10<=s.length&&s[e]===51&&s[e+1]===68&&s[e+2]===73&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128,kr=(s,e)=>{const t=e;let i=0;for(;Uc(s,e);){i+=10;const n=Oo(s,e+6);i+=n,Mg(s,e+10)&&(i+=10),e+=i}if(i>0)return s.subarray(t,t+i)},Oo=(s,e)=>{let t=0;return t=(s[e]&127)<<21,t|=(s[e+1]&127)<<14,t|=(s[e+2]&127)<<7,t|=s[e+3]&127,t},y_=(s,e)=>Uc(s,e)&&Oo(s,e+6)+10<=s.length-e,Hc=s=>{const e=Ng(s);for(let t=0;t<e.length;t++){const i=e[t];if(Fg(i))return S_(i)}},Fg=s=>s&&s.key==="PRIV"&&s.info==="com.apple.streaming.transportStreamTimestamp",v_=s=>{const e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=Oo(s,4),i=10;return{type:e,size:t,data:s.subarray(i,i+t)}},Ng=s=>{let e=0;const t=[];for(;Uc(s,e);){const i=Oo(s,e+6);e+=10;const n=e+i;for(;e+8<n;){const r=v_(s.subarray(e)),o=T_(r);o&&t.push(o),e+=r.size+10}Mg(s,e)&&(e+=10)}return t},T_=s=>s.type==="PRIV"?b_(s):s.type[0]==="W"?E_(s):__(s),b_=s=>{if(s.size<2)return;const e=Oi(s.data,!0),t=new Uint8Array(s.data.subarray(e.length+1));return{key:s.type,info:e,data:t.buffer}},__=s=>{if(s.size<2)return;if(s.type==="TXXX"){let t=1;const i=Oi(s.data.subarray(t),!0);t+=i.length+1;const n=Oi(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=Oi(s.data.subarray(1));return{key:s.type,data:e}},E_=s=>{if(s.type==="WXXX"){if(s.size<2)return;let t=1;const i=Oi(s.data.subarray(t),!0);t+=i.length+1;const n=Oi(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=Oi(s.data);return{key:s.type,data:e}},S_=s=>{if(s.data.byteLength===8){const e=new Uint8Array(s.data),t=e[3]&1;let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}},Oi=(s,e=!1)=>{const t=C_();if(t){const p=t.decode(s);if(e){const d=p.indexOf("\0");return d!==-1?p.substring(0,d):p}return p.replace(/\0/g,"")}const i=s.length;let n,r,o,u="",h=0;for(;h<i;){if(n=s[h++],n===0&&e)return u;if(n===0||n===3)continue;switch(n>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:u+=String.fromCharCode(n);break;case 12:case 13:r=s[h++],u+=String.fromCharCode((n&31)<<6|r&63);break;case 14:r=s[h++],o=s[h++],u+=String.fromCharCode((n&15)<<12|(r&63)<<6|(o&63)<<0);break}}return u};let ou;function C_(){if(!navigator.userAgent.includes("PlayStation 4"))return!ou&&typeof self.TextDecoder<"u"&&(ou=new self.TextDecoder("utf-8")),ou}const wi={hexDump:function(s){let e="";for(let t=0;t<s.length;t++){let i=s[t].toString(16);i.length<2&&(i="0"+i),e+=i}return e}},co=Math.pow(2,32)-1,w_=[].push,Bg={video:1,audio:2,id3:3,text:4};function Tt(s){return String.fromCharCode.apply(null,s)}function Ug(s,e){const t=s[e]<<8|s[e+1];return t<0?65536+t:t}function Re(s,e){const t=Hg(s,e);return t<0?4294967296+t:t}function Zd(s,e){let t=Re(s,e);return t*=Math.pow(2,32),t+=Re(s,e+4),t}function Hg(s,e){return s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3]}function lu(s,e,t){s[e]=t>>24,s[e+1]=t>>16&255,s[e+2]=t>>8&255,s[e+3]=t&255}function A_(s){const e=s.byteLength;for(let t=0;t<e;){const i=Re(s,t);if(i>8&&s[t+4]===109&&s[t+5]===111&&s[t+6]===111&&s[t+7]===102)return!0;t=i>1?t+i:e}return!1}function Ne(s,e){const t=[];if(!e.length)return t;const i=s.byteLength;for(let n=0;n<i;){const r=Re(s,n),o=Tt(s.subarray(n+4,n+8)),u=r>1?n+r:i;if(o===e[0])if(e.length===1)t.push(s.subarray(n+8,u));else{const h=Ne(s.subarray(n+8,u),e.slice(1));h.length&&w_.apply(t,h)}n=u}return t}function L_(s){const e=[],t=s[0];let i=8;const n=Re(s,i);i+=4;let r=0,o=0;t===0?(r=Re(s,i),o=Re(s,i+4),i+=8):(r=Zd(s,i),o=Zd(s,i+8),i+=16),i+=2;let u=s.length+o;const h=Ug(s,i);i+=2;for(let p=0;p<h;p++){let d=i;const g=Re(s,d);d+=4;const T=g&2147483647;if((g&2147483648)>>>31===1)return W.warn("SIDX has hierarchical references (not supported)"),null;const E=Re(s,d);d+=4,e.push({referenceSize:T,subsegmentDuration:E,info:{duration:E/n,start:u,end:u+T-1}}),u+=T,d+=4,i=d}return{earliestPresentationTime:r,timescale:n,version:t,referencesCount:h,references:e}}function $g(s){const e=[],t=Ne(s,["moov","trak"]);for(let n=0;n<t.length;n++){const r=t[n],o=Ne(r,["tkhd"])[0];if(o){let u=o[0];const h=Re(o,u===0?12:20),p=Ne(r,["mdia","mdhd"])[0];if(p){u=p[0];const d=Re(p,u===0?12:20),g=Ne(r,["mdia","hdlr"])[0];if(g){const T=Tt(g.subarray(8,12)),b={soun:Je.AUDIO,vide:Je.VIDEO}[T];if(b){const E=Ne(r,["mdia","minf","stbl","stsd"])[0],w=k_(E);e[h]={timescale:d,type:b},e[b]=St({timescale:d,id:h},w)}}}}}return Ne(s,["moov","mvex","trex"]).forEach(n=>{const r=Re(n,4),o=e[r];o&&(o.default={duration:Re(n,12),flags:Re(n,20)})}),e}function k_(s){const e=s.subarray(8),t=e.subarray(86),i=Tt(e.subarray(4,8));let n=i;const r=i==="enca"||i==="encv";if(r){const u=Ne(e,[i])[0].subarray(i==="enca"?28:78);Ne(u,["sinf"]).forEach(p=>{const d=Ne(p,["schm"])[0];if(d){const g=Tt(d.subarray(4,8));if(g==="cbcs"||g==="cenc"){const T=Ne(p,["frma"])[0];T&&(n=Tt(T))}}})}switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const o=Ne(t,["avcC"])[0];n+="."+Sa(o[1])+Sa(o[2])+Sa(o[3]);break}case"mp4a":{const o=Ne(e,[i])[0],u=Ne(o.subarray(28),["esds"])[0];if(u&&u.length>12){let h=4;if(u[h++]!==3)break;h=uu(u,h),h+=2;const p=u[h++];if(p&128&&(h+=2),p&64&&(h+=u[h++]),u[h++]!==4)break;h=uu(u,h);const d=u[h++];if(d===64)n+="."+Sa(d);else break;if(h+=12,u[h++]!==5)break;h=uu(u,h);const g=u[h++];let T=(g&248)>>3;T===31&&(T+=1+((g&7)<<3)+((u[h]&224)>>5)),n+="."+T}break}case"hvc1":case"hev1":{const o=Ne(t,["hvcC"])[0],u=o[1],h=["","A","B","C"][u>>6],p=u&31,d=Re(o,2),g=(u&32)>>5?"H":"L",T=o[12],b=o.subarray(6,12);n+="."+h+p,n+="."+d.toString(16).toUpperCase(),n+="."+g+T;let E="";for(let w=b.length;w--;){const A=b[w];(A||E)&&(E="."+A.toString(16).toUpperCase()+E)}n+=E;break}case"dvh1":case"dvhe":{const o=Ne(t,["dvcC"])[0],u=o[2]>>1&127,h=o[2]<<5&32|o[3]>>3&31;n+="."+_i(u)+"."+_i(h);break}case"vp09":{const o=Ne(t,["vpcC"])[0],u=o[4],h=o[5],p=o[6]>>4&15;n+="."+_i(u)+"."+_i(h)+"."+_i(p);break}case"av01":{const o=Ne(t,["av1C"])[0],u=o[1]>>>5,h=o[1]&31,p=o[2]>>>7?"H":"M",d=(o[2]&64)>>6,g=(o[2]&32)>>5,T=u===2&&d?g?12:10:d?10:8,b=(o[2]&16)>>4,E=(o[2]&8)>>3,w=(o[2]&4)>>2,A=o[2]&3;n+="."+u+"."+_i(h)+p+"."+_i(T)+"."+b+"."+E+w+A+"."+_i(1)+"."+_i(1)+"."+_i(1)+"."+0;break}}return{codec:n,encrypted:r}}function uu(s,e){const t=e+5;for(;s[e++]&128&&e<t;);return e}function Sa(s){return("0"+s.toString(16).toUpperCase()).slice(-2)}function _i(s){return(s<10?"0":"")+s}function I_(s,e){if(!s||!e)return s;const t=e.keyId;return t&&e.isCommonEncryption&&Ne(s,["moov","trak"]).forEach(n=>{const o=Ne(n,["mdia","minf","stbl","stsd"])[0].subarray(8);let u=Ne(o,["enca"]);const h=u.length>0;h||(u=Ne(o,["encv"])),u.forEach(p=>{const d=h?p.subarray(28):p.subarray(78);Ne(d,["sinf"]).forEach(T=>{const b=jg(T);if(b){const E=b.subarray(8,24);E.some(w=>w!==0)||(W.log(`[eme] Patching keyId in 'enc${h?"a":"v"}>sinf>>tenc' box: ${wi.hexDump(E)} -> ${wi.hexDump(t)}`),b.set(t,8))}})})}),s}function jg(s){const e=Ne(s,["schm"])[0];if(e){const t=Tt(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return Ne(s,["schi","tenc"])[0]}return null}function R_(s,e){return Ne(e,["moof","traf"]).reduce((t,i)=>{const n=Ne(i,["tfdt"])[0],r=n[0],o=Ne(i,["tfhd"]).reduce((u,h)=>{const p=Re(h,4),d=s[p];if(d){let g=Re(n,4);if(r===1){if(g===co)return W.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),u;g*=co+1,g+=Re(n,8)}const T=d.timescale||9e4,b=g/T;if(Ae(b)&&(u===null||b<u))return b}return u},null);return o!==null&&Ae(o)&&(t===null||o<t)?o:t},null)}function P_(s,e){let t=0,i=0,n=0;const r=Ne(s,["moof","traf"]);for(let o=0;o<r.length;o++){const u=r[o],h=Ne(u,["tfhd"])[0],p=Re(h,4),d=e[p];if(!d)continue;const g=d.default,T=Re(h,0)|g?.flags;let b=g?.duration;T&8&&(T&2?b=Re(h,12):b=Re(h,8));const E=d.timescale||9e4,w=Ne(u,["trun"]);for(let A=0;A<w.length;A++){if(t=D_(w[A]),!t&&b){const L=Re(w[A],4);t=b*L}d.type===Je.VIDEO?i+=t/E:d.type===Je.AUDIO&&(n+=t/E)}}if(i===0&&n===0){let o=1/0,u=0,h=0;const p=Ne(s,["sidx"]);for(let d=0;d<p.length;d++){const g=L_(p[d]);if(g!=null&&g.references){o=Math.min(o,g.earliestPresentationTime/g.timescale);const T=g.references.reduce((b,E)=>b+E.info.duration||0,0);u=Math.max(u,T+g.earliestPresentationTime/g.timescale),h=u-o}}if(h&&Ae(h))return h}return i||n}function D_(s){const e=Re(s,0);let t=8;e&1&&(t+=4),e&4&&(t+=4);let i=0;const n=Re(s,4);for(let r=0;r<n;r++){if(e&256){const o=Re(s,t);i+=o,t+=4}e&512&&(t+=4),e&1024&&(t+=4),e&2048&&(t+=4)}return i}function x_(s,e,t){Ne(e,["moof","traf"]).forEach(i=>{Ne(i,["tfhd"]).forEach(n=>{const r=Re(n,4),o=s[r];if(!o)return;const u=o.timescale||9e4;Ne(i,["tfdt"]).forEach(h=>{const p=h[0],d=t*u;if(d){let g=Re(h,4);if(p===0)g-=d,g=Math.max(g,0),lu(h,4,g);else{g*=Math.pow(2,32),g+=Re(h,8),g-=d,g=Math.max(g,0);const T=Math.floor(g/(co+1)),b=Math.floor(g%(co+1));lu(h,4,T),lu(h,8,b)}}})})})}function O_(s){const e={valid:null,remainder:null},t=Ne(s,["moof"]);if(t.length<2)return e.remainder=s,e;const i=t[t.length-1];return e.valid=Zn(s,0,i.byteOffset-8),e.remainder=Zn(s,i.byteOffset-8),e}function si(s,e){const t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function ef(s,e){const t=[],i=e.samples,n=e.timescale,r=e.id;let o=!1;return Ne(i,["moof"]).map(h=>{const p=h.byteOffset-8;Ne(h,["traf"]).map(g=>{const T=Ne(g,["tfdt"]).map(b=>{const E=b[0];let w=Re(b,4);return E===1&&(w*=Math.pow(2,32),w+=Re(b,8)),w/n})[0];return T!==void 0&&(s=T),Ne(g,["tfhd"]).map(b=>{const E=Re(b,4),w=Re(b,0)&16777215,A=(w&1)!==0,L=(w&2)!==0,P=(w&8)!==0;let M=0;const O=(w&16)!==0;let k=0;const N=(w&32)!==0;let H=8;E===r&&(A&&(H+=8),L&&(H+=4),P&&(M=Re(b,H),H+=4),O&&(k=Re(b,H),H+=4),N&&(H+=4),e.type==="video"&&(o=M_(e.codec)),Ne(g,["trun"]).map(G=>{const B=G[0],D=Re(G,0)&16777215,K=(D&1)!==0;let oe=0;const Z=(D&4)!==0,le=(D&256)!==0;let ce=0;const fe=(D&512)!==0;let ve=0;const be=(D&1024)!==0,ee=(D&2048)!==0;let Q=0;const Ee=Re(G,4);let ae=8;K&&(oe=Re(G,ae),ae+=4),Z&&(ae+=4);let ie=oe+p;for(let Le=0;Le<Ee;Le++){if(le?(ce=Re(G,ae),ae+=4):ce=M,fe?(ve=Re(G,ae),ae+=4):ve=k,be&&(ae+=4),ee&&(B===0?Q=Re(G,ae):Q=Hg(G,ae),ae+=4),e.type===Je.VIDEO){let Ce=0;for(;Ce<ve;){const Ue=Re(i,ie);if(ie+=4,F_(o,i[ie])){const He=i.subarray(ie,ie+Ue);Vg(He,o?2:1,s+Q/n,t)}ie+=Ue,Ce+=Ue+4}}s+=ce/n}}))})})}),t}function M_(s){if(!s)return!1;const e=s.indexOf("."),t=e<0?s:s.substring(0,e);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function F_(s,e){if(s){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Vg(s,e,t,i){const n=Gg(s);let r=0;r+=e;let o=0,u=0,h=0;for(;r<n.length;){o=0;do{if(r>=n.length)break;h=n[r++],o+=h}while(h===255);u=0;do{if(r>=n.length)break;h=n[r++],u+=h}while(h===255);const p=n.length-r;let d=r;if(u<p)r+=u;else if(u>p){W.error(`Malformed SEI payload. ${u} is too small, only ${p} bytes left to parse.`);break}if(o===4){if(n[d++]===181){const T=Ug(n,d);if(d+=2,T===49){const b=Re(n,d);if(d+=4,b===1195456820){const E=n[d++];if(E===3){const w=n[d++],A=31&w,L=64&w,P=L?2+A*3:0,M=new Uint8Array(P);if(L){M[0]=w;for(let O=1;O<P;O++)M[O]=n[d++]}i.push({type:E,payloadType:o,pts:t,bytes:M})}}}}}else if(o===5&&u>16){const g=[];for(let E=0;E<16;E++){const w=n[d++].toString(16);g.push(w.length==1?"0"+w:w),(E===3||E===5||E===7||E===9)&&g.push("-")}const T=u-16,b=new Uint8Array(T);for(let E=0;E<T;E++)b[E]=n[d++];i.push({payloadType:o,pts:t,uuid:g.join(""),userData:Oi(b),userDataBytes:b})}}}function Gg(s){const e=s.byteLength,t=[];let i=1;for(;i<e-2;)s[i]===0&&s[i+1]===0&&s[i+2]===3?(t.push(i+2),i+=2):i++;if(t.length===0)return s;const n=e-t.length,r=new Uint8Array(n);let o=0;for(i=0;i<n;o++,i++)o===t[0]&&(o++,t.shift()),r[i]=s[o];return r}function N_(s){const e=s[0];let t="",i="",n=0,r=0,o=0,u=0,h=0,p=0;if(e===0){for(;Tt(s.subarray(p,p+1))!=="\0";)t+=Tt(s.subarray(p,p+1)),p+=1;for(t+=Tt(s.subarray(p,p+1)),p+=1;Tt(s.subarray(p,p+1))!=="\0";)i+=Tt(s.subarray(p,p+1)),p+=1;i+=Tt(s.subarray(p,p+1)),p+=1,n=Re(s,12),r=Re(s,16),u=Re(s,20),h=Re(s,24),p=28}else if(e===1){p+=4,n=Re(s,p),p+=4;const g=Re(s,p);p+=4;const T=Re(s,p);for(p+=4,o=2**32*g+T,t_(o)||(o=Number.MAX_SAFE_INTEGER,W.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),u=Re(s,p),p+=4,h=Re(s,p),p+=4;Tt(s.subarray(p,p+1))!=="\0";)t+=Tt(s.subarray(p,p+1)),p+=1;for(t+=Tt(s.subarray(p,p+1)),p+=1;Tt(s.subarray(p,p+1))!=="\0";)i+=Tt(s.subarray(p,p+1)),p+=1;i+=Tt(s.subarray(p,p+1)),p+=1}const d=s.subarray(p,s.byteLength);return{schemeIdUri:t,value:i,timeScale:n,presentationTime:o,presentationTimeDelta:r,eventDuration:u,id:h,payload:d}}function B_(s,...e){const t=e.length;let i=8,n=t;for(;n--;)i+=e[n].byteLength;const r=new Uint8Array(i);for(r[0]=i>>24&255,r[1]=i>>16&255,r[2]=i>>8&255,r[3]=i&255,r.set(s,4),n=0,i=8;n<t;n++)r.set(e[n],i),i+=e[n].byteLength;return r}function U_(s,e,t){if(s.byteLength!==16)throw new RangeError("Invalid system id");let i,n;i=0,n=new Uint8Array;let r;i>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const o=new Uint8Array(4);return t&&t.byteLength>0&&new DataView(o.buffer).setUint32(0,t.byteLength,!1),B_([112,115,115,104],new Uint8Array([i,0,0,0]),s,r,n,o,t||new Uint8Array)}function H_(s){const e=[];if(s instanceof ArrayBuffer){const t=s.byteLength;let i=0;for(;i+32<t;){const n=new DataView(s,i),r=$_(n);e.push(r),i+=r.size}}return e}function $_(s){const e=s.getUint32(0),t=s.byteOffset,i=s.byteLength;if(i<e)return{offset:t,size:i};if(s.getUint32(4)!==1886614376)return{offset:t,size:e};const r=s.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};const o=s.buffer,u=wi.hexDump(new Uint8Array(o,t+12,16)),h=s.getUint32(28);let p=null,d=null;if(r===0){if(e-32<h||h<22)return{offset:t,size:e};d=new Uint8Array(o,t+32,h)}else if(r===1){if(!h||i<t+32+h*16+16)return{offset:t,size:e};p=[];for(let g=0;g<h;g++)p.push(new Uint8Array(o,t+32+g*16,16))}return{version:r,systemId:u,kids:p,data:d,offset:t,size:e}}let Ca={};class Ir{static clearKeyUriToKeyIdMap(){Ca={}}constructor(e,t,i,n=[1],r=null){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=i,this.keyFormatVersions=n,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&e!=="AES-128"}isSupported(){if(this.method){if(this.method==="AES-128"||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Gt.FAIRPLAY:case Gt.WIDEVINE:case Gt.PLAYREADY:case Gt.CLEARKEY:return["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(this.method==="AES-128"&&this.uri&&!this.iv){typeof e!="number"&&(this.method==="AES-128"&&!this.iv&&W.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const i=j_(e);return new Ir(this.method,this.uri,"identity",this.keyFormatVersions,i)}const t=p_(this.uri);if(t)switch(this.keyFormat){case Gt.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case Gt.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=U_(i,null,t),this.keyId=Og(t);break}default:{let i=t.subarray(0,16);if(i.length!==16){const n=new Uint8Array(16);n.set(i,16-i.length),i=n}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i=Ca[this.uri];if(!i){const n=Object.keys(Ca).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,n),Ca[this.uri]=i}this.keyId=i}return this}}function j_(s){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}const Kg=/\{\$([a-zA-Z0-9-_]+)\}/g;function tf(s){return Kg.test(s)}function Ut(s,e,t){if(s.variableList!==null||s.hasVariableRefs)for(let i=t.length;i--;){const n=t[i],r=e[n];r&&(e[n]=ic(s,r))}}function ic(s,e){if(s.variableList!==null||s.hasVariableRefs){const t=s.variableList;return e.replace(Kg,i=>{const n=i.substring(2,i.length-1),r=t?.[n];return r===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),i):r})}return e}function nf(s,e,t){let i=s.variableList;i||(s.variableList=i={});let n,r;if("QUERYPARAM"in e){n=e.QUERYPARAM;try{const o=new self.URL(t).searchParams;if(o.has(n))r=o.get(n);else throw new Error(`"${n}" does not match any query parameter in URI: "${t}"`)}catch(o){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${o.message}`))}}else n=e.NAME,r=e.VALUE;n in i?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):i[n]=r||""}function V_(s,e,t){const i=e.IMPORT;if(t&&i in t){let n=s.variableList;n||(s.variableList=n={}),n[i]=t[i]}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function ts(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function G_(s){return typeof self<"u"&&s===self.ManagedMediaSource}const ho={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,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 K_(s,e){const t=ho[e];return!!t&&!!t[s.slice(0,4)]}function cu(s,e,t=!0){return!s.split(",").some(i=>!qg(i,e,t))}function qg(s,e,t=!0){var i;const n=ts(t);return(i=n?.isTypeSupported(Rr(s,e)))!=null?i:!1}function Rr(s,e){return`${e}/mp4;codecs="${s}"`}function sf(s){if(s){const e=s.substring(0,4);return ho.video[e]}return 2}function fo(s){return s.split(",").reduce((e,t)=>{const i=ho.video[t];return i?(i*2+e)/(e?3:2):(ho.audio[t]+e)/(e?2:1)},0)}const hu={};function q_(s,e=!0){if(hu[s])return hu[s];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[s];for(let i=0;i<t.length;i++)if(qg(t[i],"audio",e))return hu[s]=t[i],t[i];return s}const W_=/flac|opus/i;function po(s,e=!0){return s.replace(W_,t=>q_(t.toLowerCase(),e))}function rf(s,e){return s&&s!=="mp4a"?s:e&&e.split(",")[0]}function z_(s){const e=s.split(",");for(let t=0;t<e.length;t++){const i=e[t].split(".");if(i.length>2){let n=i.shift()+".";n+=parseInt(i.shift()).toString(16),n+=("000"+parseInt(i.shift()).toString(16)).slice(-4),e[t]=n}}return e.join(",")}const af=/#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,of=/#EXT-X-MEDIA:(.*)/g,Y_=/^#EXT(?:INF|-X-TARGETDURATION):/m,lf=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),X_=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Pi{static findGroup(e,t){for(let i=0;i<e.length;i++){const n=e[i];if(n.id===t)return n}}static resolve(e,t){return Nc.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Y_.test(e)}static parseMasterPlaylist(e,t){const i=tf(e),n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},r=[];af.lastIndex=0;let o;for(;(o=af.exec(e))!=null;)if(o[1]){var u;const p=new ct(o[1]);Ut(n,p,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const d=ic(n,o[2]),g={attrs:p,bitrate:p.decimalInteger("BANDWIDTH")||p.decimalInteger("AVERAGE-BANDWIDTH"),name:p.NAME,url:Pi.resolve(d,t)},T=p.decimalResolution("RESOLUTION");T&&(g.width=T.width,g.height=T.height),Q_(p.CODECS,g),(u=g.unknownCodecs)!=null&&u.length||r.push(g),n.levels.push(g)}else if(o[3]){const p=o[3],d=o[4];switch(p){case"SESSION-DATA":{const g=new ct(d);Ut(n,g,["DATA-ID","LANGUAGE","VALUE","URI"]);const T=g["DATA-ID"];T&&(n.sessionData===null&&(n.sessionData={}),n.sessionData[T]=g);break}case"SESSION-KEY":{const g=uf(d,t,n);g.encrypted&&g.isSupported()?(n.sessionKeys===null&&(n.sessionKeys=[]),n.sessionKeys.push(g)):W.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${d}"`);break}case"DEFINE":{{const g=new ct(d);Ut(n,g,["NAME","VALUE","QUERYPARAM"]),nf(n,g,t)}break}case"CONTENT-STEERING":{const g=new ct(d);Ut(n,g,["SERVER-URI","PATHWAY-ID"]),n.contentSteering={uri:Pi.resolve(g["SERVER-URI"],t),pathwayId:g["PATHWAY-ID"]||"."};break}case"START":{n.startTimeOffset=cf(d);break}}}const h=r.length>0&&r.length<n.levels.length;return n.levels=h?r:n.levels,n.levels.length===0&&(n.playlistParsingError=new Error("no levels found in manifest")),n}static parseMasterPlaylistMedia(e,t,i){let n;const r={},o=i.levels,u={AUDIO:o.map(p=>({id:p.attrs.AUDIO,audioCodec:p.audioCodec})),SUBTITLES:o.map(p=>({id:p.attrs.SUBTITLES,textCodec:p.textCodec})),"CLOSED-CAPTIONS":[]};let h=0;for(of.lastIndex=0;(n=of.exec(e))!==null;){const p=new ct(n[1]),d=p.TYPE;if(d){const g=u[d],T=r[d]||[];r[d]=T,Ut(i,p,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const b=p.LANGUAGE,E=p["ASSOC-LANGUAGE"],w=p.CHANNELS,A=p.CHARACTERISTICS,L=p["INSTREAM-ID"],P={attrs:p,bitrate:0,id:h++,groupId:p["GROUP-ID"]||"",name:p.NAME||b||"",type:d,default:p.bool("DEFAULT"),autoselect:p.bool("AUTOSELECT"),forced:p.bool("FORCED"),lang:b,url:p.URI?Pi.resolve(p.URI,t):""};if(E&&(P.assocLang=E),w&&(P.channels=w),A&&(P.characteristics=A),L&&(P.instreamId=L),g!=null&&g.length){const M=Pi.findGroup(g,P.groupId)||g[0];hf(P,M,"audioCodec"),hf(P,M,"textCodec")}T.push(P)}}return r}static parseLevelPlaylist(e,t,i,n,r,o){const u=new h_(t),h=u.fragments;let p=null,d=0,g=0,T=0,b=0,E=null,w=new nu(n,t),A,L,P,M=-1,O=!1,k=null;for(lf.lastIndex=0,u.m3u8=e,u.hasVariableRefs=tf(e);(A=lf.exec(e))!==null;){O&&(O=!1,w=new nu(n,t),w.start=T,w.sn=d,w.cc=b,w.level=i,p&&(w.initSegment=p,w.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null,k&&(w.setByteRange(k),k=null)));const B=A[1];if(B){w.duration=parseFloat(B);const D=(" "+A[2]).slice(1);w.title=D||null,w.tagList.push(D?["INF",B,D]:["INF",B])}else if(A[3]){if(Ae(w.duration)){w.start=T,P&&pf(w,P,u),w.sn=d,w.level=i,w.cc=b,h.push(w);const D=(" "+A[3]).slice(1);w.relurl=ic(u,D),df(w,E),E=w,T+=w.duration,d++,g=0,O=!0}}else if(A[4]){const D=(" "+A[4]).slice(1);E?w.setByteRange(D,E):w.setByteRange(D)}else if(A[5])w.rawProgramDateTime=(" "+A[5]).slice(1),w.tagList.push(["PROGRAM-DATE-TIME",w.rawProgramDateTime]),M===-1&&(M=h.length);else{if(A=A[0].match(X_),!A){W.warn("No matches on slow regex match for level playlist!");continue}for(L=1;L<A.length&&!(typeof A[L]<"u");L++);const D=(" "+A[L]).slice(1),K=(" "+A[L+1]).slice(1),oe=A[L+2]?(" "+A[L+2]).slice(1):"";switch(D){case"PLAYLIST-TYPE":u.type=K.toUpperCase();break;case"MEDIA-SEQUENCE":d=u.startSN=parseInt(K);break;case"SKIP":{const Z=new ct(K);Ut(u,Z,["RECENTLY-REMOVED-DATERANGES"]);const le=Z.decimalInteger("SKIPPED-SEGMENTS");if(Ae(le)){u.skippedSegments=le;for(let fe=le;fe--;)h.unshift(null);d+=le}const ce=Z.enumeratedString("RECENTLY-REMOVED-DATERANGES");ce&&(u.recentlyRemovedDateranges=ce.split("	"));break}case"TARGETDURATION":u.targetduration=Math.max(parseInt(K),1);break;case"VERSION":u.version=parseInt(K);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":u.live=!1;break;case"#":(K||oe)&&w.tagList.push(oe?[K,oe]:[K]);break;case"DISCONTINUITY":b++,w.tagList.push(["DIS"]);break;case"GAP":w.gap=!0,w.tagList.push([D]);break;case"BITRATE":w.tagList.push([D,K]);break;case"DATERANGE":{const Z=new ct(K);Ut(u,Z,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),Ut(u,Z,Z.clientAttrs);const le=new Pg(Z,u.dateRanges[Z.ID]);le.isValid||u.skippedSegments?u.dateRanges[le.id]=le:W.warn(`Ignoring invalid DATERANGE tag: "${K}"`),w.tagList.push(["EXT-X-DATERANGE",K]);break}case"DEFINE":{{const Z=new ct(K);Ut(u,Z,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in Z?V_(u,Z,o):nf(u,Z,t)}break}case"DISCONTINUITY-SEQUENCE":b=parseInt(K);break;case"KEY":{const Z=uf(K,t,u);if(Z.isSupported()){if(Z.method==="NONE"){P=void 0;break}P||(P={}),P[Z.keyFormat]&&(P=vt({},P)),P[Z.keyFormat]=Z}else W.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${K}"`);break}case"START":u.startTimeOffset=cf(K);break;case"MAP":{const Z=new ct(K);if(Ut(u,Z,["BYTERANGE","URI"]),w.duration){const le=new nu(n,t);ff(le,Z,i,P),p=le,w.initSegment=p,p.rawProgramDateTime&&!w.rawProgramDateTime&&(w.rawProgramDateTime=p.rawProgramDateTime)}else{const le=w.byteRangeEndOffset;if(le){const ce=w.byteRangeStartOffset;k=`${le-ce}@${ce}`}else k=null;ff(w,Z,i,P),p=w,O=!0}break}case"SERVER-CONTROL":{const Z=new ct(K);u.canBlockReload=Z.bool("CAN-BLOCK-RELOAD"),u.canSkipUntil=Z.optionalFloat("CAN-SKIP-UNTIL",0),u.canSkipDateRanges=u.canSkipUntil>0&&Z.bool("CAN-SKIP-DATERANGES"),u.partHoldBack=Z.optionalFloat("PART-HOLD-BACK",0),u.holdBack=Z.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const Z=new ct(K);u.partTarget=Z.decimalFloatingPoint("PART-TARGET");break}case"PART":{let Z=u.partList;Z||(Z=u.partList=[]);const le=g>0?Z[Z.length-1]:void 0,ce=g++,fe=new ct(K);Ut(u,fe,["BYTERANGE","URI"]);const ve=new u_(fe,w,t,ce,le);Z.push(ve),w.duration+=ve.duration;break}case"PRELOAD-HINT":{const Z=new ct(K);Ut(u,Z,["URI"]),u.preloadHint=Z;break}case"RENDITION-REPORT":{const Z=new ct(K);Ut(u,Z,["URI"]),u.renditionReports=u.renditionReports||[],u.renditionReports.push(Z);break}default:W.warn(`line parsed but not handled: ${A}`);break}}}E&&!E.relurl?(h.pop(),T-=E.duration,u.partList&&(u.fragmentHint=E)):u.partList&&(df(w,E),w.cc=b,u.fragmentHint=w,P&&pf(w,P,u));const N=h.length,H=h[0],G=h[N-1];if(T+=u.skippedSegments*u.targetduration,T>0&&N&&G){u.averagetargetduration=T/N;const B=G.sn;u.endSN=B!=="initSegment"?B:0,u.live||(G.endList=!0),H&&(u.startCC=H.cc)}else u.endSN=0,u.startCC=0;return u.fragmentHint&&(T+=u.fragmentHint.duration),u.totalduration=T,u.endCC=b,M>0&&J_(h,M),u}}function uf(s,e,t){var i,n;const r=new ct(s);Ut(t,r,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const o=(i=r.METHOD)!=null?i:"",u=r.URI,h=r.hexadecimalInteger("IV"),p=r.KEYFORMATVERSIONS,d=(n=r.KEYFORMAT)!=null?n:"identity";u&&r.IV&&!h&&W.error(`Invalid IV: ${r.IV}`);const g=u?Pi.resolve(u,e):"",T=(p||"1").split("/").map(Number).filter(Number.isFinite);return new Ir(o,g,d,T,h)}function cf(s){const t=new ct(s).decimalFloatingPoint("TIME-OFFSET");return Ae(t)?t:null}function Q_(s,e){let t=(s||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const n=t.filter(r=>K_(r,i));n.length&&(e[`${i}Codec`]=n.join(","),t=t.filter(r=>n.indexOf(r)===-1))}),e.unknownCodecs=t}function hf(s,e,t){const i=e[t];i&&(s[t]=i)}function J_(s,e){let t=s[e];for(let i=e;i--;){const n=s[i];if(!n)return;n.programDateTime=t.programDateTime-n.duration*1e3,t=n}}function df(s,e){s.rawProgramDateTime?s.programDateTime=Date.parse(s.rawProgramDateTime):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime),Ae(s.programDateTime)||(s.programDateTime=null,s.rawProgramDateTime=null)}function ff(s,e,t,i){s.relurl=e.URI,e.BYTERANGE&&s.setByteRange(e.BYTERANGE),s.level=t,s.sn="initSegment",i&&(s.levelkeys=i),s.initSegment=null}function pf(s,e,t){s.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(n=>e[n].isCommonEncryption)&&i.push(s)}var qe={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Pe={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function gf(s){const{type:e}=s;switch(e){case qe.AUDIO_TRACK:return Pe.AUDIO;case qe.SUBTITLE_TRACK:return Pe.SUBTITLE;default:return Pe.MAIN}}function du(s,e){let t=s.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Z_{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(I.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_LOADING,this.onLevelLoading,this),e.off(I.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(I.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,n=t.loader,r=i||n,o=new r(t);return this.loaders[e.type]=o,o}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:qe.MANIFEST,url:i,deliveryDirectives:null})}onLevelLoading(e,t){const{id:i,level:n,pathwayId:r,url:o,deliveryDirectives:u}=t;this.load({id:i,level:n,pathwayId:r,responseType:"text",type:qe.LEVEL,url:o,deliveryDirectives:u})}onAudioTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:o}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:qe.AUDIO_TRACK,url:r,deliveryDirectives:o})}onSubtitleTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:o}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:qe.SUBTITLE_TRACK,url:r,deliveryDirectives:o})}load(e){var t;const i=this.hls.config;let n=this.getInternalLoader(e);if(n){const p=n.context;if(p&&p.url===e.url&&p.level===e.level){W.trace("[playlist-loader]: playlist request ongoing");return}W.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let r;if(e.type===qe.MANIFEST?r=i.manifestLoadPolicy.default:r=vt({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),Ae((t=e.deliveryDirectives)==null?void 0:t.part)){let p;if(e.type===qe.LEVEL&&e.level!==null?p=this.hls.levels[e.level].details:e.type===qe.AUDIO_TRACK&&e.id!==null?p=this.hls.audioTracks[e.id].details:e.type===qe.SUBTITLE_TRACK&&e.id!==null&&(p=this.hls.subtitleTracks[e.id].details),p){const d=p.partTarget,g=p.targetduration;if(d&&g){const T=Math.max(d*3,g*.8)*1e3;r=vt({},r,{maxTimeToFirstByteMs:Math.min(T,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(T,r.maxTimeToFirstByteMs)})}}}const o=r.errorRetry||r.timeoutRetry||{},u={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},h={onSuccess:(p,d,g,T)=>{const b=this.getInternalLoader(g);this.resetInternalLoader(g.type);const E=p.data;if(E.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(p,g,new Error("no EXTM3U delimiter"),T||null,d);return}d.parsing.start=performance.now(),Pi.isMediaPlaylist(E)?this.handleTrackOrLevelPlaylist(p,d,g,T||null,b):this.handleMasterPlaylist(p,d,g,T)},onError:(p,d,g,T)=>{this.handleNetworkError(d,g,!1,p,T)},onTimeout:(p,d,g)=>{this.handleNetworkError(d,g,!0,void 0,p)}};n.load(e,u,h)}handleMasterPlaylist(e,t,i,n){const r=this.hls,o=e.data,u=du(e,i),h=Pi.parseMasterPlaylist(o,u);if(h.playlistParsingError){this.handleManifestParsingError(e,i,h.playlistParsingError,n,t);return}const{contentSteering:p,levels:d,sessionData:g,sessionKeys:T,startTimeOffset:b,variableList:E}=h;this.variableList=E;const{AUDIO:w=[],SUBTITLES:A,"CLOSED-CAPTIONS":L}=Pi.parseMasterPlaylistMedia(o,u,h);w.length&&!w.some(M=>!M.url)&&d[0].audioCodec&&!d[0].attrs.AUDIO&&(W.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),w.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ct({}),bitrate:0,url:""})),r.trigger(I.MANIFEST_LOADED,{levels:d,audioTracks:w,subtitles:A,captions:L,contentSteering:p,url:u,stats:t,networkDetails:n,sessionData:g,sessionKeys:T,startTimeOffset:b,variableList:E})}handleTrackOrLevelPlaylist(e,t,i,n,r){const o=this.hls,{id:u,level:h,type:p}=i,d=du(e,i),g=0,T=Ae(h)?h:Ae(u)?u:0,b=gf(i),E=Pi.parseLevelPlaylist(e.data,d,T,b,g,this.variableList);if(p===qe.MANIFEST){const w={attrs:new ct({}),bitrate:0,details:E,name:"",url:d};o.trigger(I.MANIFEST_LOADED,{levels:[w],audioTracks:[],url:d,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=E,this.handlePlaylistLoaded(E,e,t,i,n,r)}handleManifestParsingError(e,t,i,n,r){this.hls.trigger(I.ERROR,{type:xe.NETWORK_ERROR,details:te.MANIFEST_PARSING_ERROR,fatal:t.type===qe.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:n,stats:r})}handleNetworkError(e,t,i=!1,n,r){let o=`A network ${i?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===qe.LEVEL?o+=`: ${e.level} id: ${e.id}`:(e.type===qe.AUDIO_TRACK||e.type===qe.SUBTITLE_TRACK)&&(o+=` id: ${e.id} group-id: "${e.groupId}"`);const u=new Error(o);W.warn(`[playlist-loader]: ${o}`);let h=te.UNKNOWN,p=!1;const d=this.getInternalLoader(e);switch(e.type){case qe.MANIFEST:h=i?te.MANIFEST_LOAD_TIMEOUT:te.MANIFEST_LOAD_ERROR,p=!0;break;case qe.LEVEL:h=i?te.LEVEL_LOAD_TIMEOUT:te.LEVEL_LOAD_ERROR,p=!1;break;case qe.AUDIO_TRACK:h=i?te.AUDIO_TRACK_LOAD_TIMEOUT:te.AUDIO_TRACK_LOAD_ERROR,p=!1;break;case qe.SUBTITLE_TRACK:h=i?te.SUBTITLE_TRACK_LOAD_TIMEOUT:te.SUBTITLE_LOAD_ERROR,p=!1;break}d&&this.resetInternalLoader(e.type);const g={type:xe.NETWORK_ERROR,details:h,fatal:p,url:e.url,loader:d,context:e,error:u,networkDetails:t,stats:r};if(n){const T=t?.url||e.url;g.response=St({url:T,data:void 0},n)}this.hls.trigger(I.ERROR,g)}handlePlaylistLoaded(e,t,i,n,r,o){const u=this.hls,{type:h,level:p,id:d,groupId:g,deliveryDirectives:T}=n,b=du(t,n),E=gf(n),w=typeof n.level=="number"&&E===Pe.MAIN?p:void 0;if(!e.fragments.length){const L=new Error("No Segments found in Playlist");u.trigger(I.ERROR,{type:xe.NETWORK_ERROR,details:te.LEVEL_EMPTY_ERROR,fatal:!1,url:b,error:L,reason:L.message,response:t,context:n,level:w,parent:E,networkDetails:r,stats:i});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const A=e.playlistParsingError;if(A){u.trigger(I.ERROR,{type:xe.NETWORK_ERROR,details:te.LEVEL_PARSING_ERROR,fatal:!1,url:b,error:A,reason:A.message,response:t,context:n,level:w,parent:E,networkDetails:r,stats:i});return}switch(e.live&&o&&(o.getCacheAge&&(e.ageHeader=o.getCacheAge()||0),(!o.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),h){case qe.MANIFEST:case qe.LEVEL:u.trigger(I.LEVEL_LOADED,{details:e,level:w||0,id:d||0,stats:i,networkDetails:r,deliveryDirectives:T});break;case qe.AUDIO_TRACK:u.trigger(I.AUDIO_TRACK_LOADED,{details:e,id:d||0,groupId:g||"",stats:i,networkDetails:r,deliveryDirectives:T});break;case qe.SUBTITLE_TRACK:u.trigger(I.SUBTITLE_TRACK_LOADED,{details:e,id:d||0,groupId:g||"",stats:i,networkDetails:r,deliveryDirectives:T});break}}}function Wg(s,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=s,e.dispatchEvent(t)}function zg(s,e){const t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues&&!s.cues.getCueById(e.id))try{if(s.addCue(e),!s.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){W.debug(`[texttrack-utils]: ${i}`);try{const n=new self.TextTrackCue(e.startTime,e.endTime,e.text);n.id=e.id,s.addCue(n)}catch(n){W.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${n}`)}}t==="disabled"&&(s.mode=t)}function Rs(s){const e=s.mode;if(e==="disabled"&&(s.mode="hidden"),s.cues)for(let t=s.cues.length;t--;)s.removeCue(s.cues[t]);e==="disabled"&&(s.mode=e)}function nc(s,e,t,i){const n=s.mode;if(n==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const r=tE(s.cues,e,t);for(let o=0;o<r.length;o++)(!i||i(r[o]))&&s.removeCue(r[o])}n==="disabled"&&(s.mode=n)}function eE(s,e){if(e<s[0].startTime)return 0;const t=s.length-1;if(e>s[t].endTime)return-1;let i=0,n=t;for(;i<=n;){const r=Math.floor((n+i)/2);if(e<s[r].startTime)n=r-1;else if(e>s[r].startTime&&i<t)i=r+1;else return r}return s[i].startTime-e<e-s[n].startTime?i:n}function tE(s,e,t){const i=[],n=eE(s,e);if(n>-1)for(let r=n,o=s.length;r<o;r++){const u=s[r];if(u.startTime>=e&&u.endTime<=t)i.push(u);else if(u.startTime>t)return i}return i}function qa(s){const e=[];for(let t=0;t<s.length;t++){const i=s[t];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&e.push(s[t])}return e}var pi={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};const iE=.25;function sc(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function mf(s,e,t,i,n){let r=new s(e,t,"");try{r.value=i,n&&(r.type=n)}catch{r=new s(e,t,JSON.stringify(n?St({type:n},i):i))}return r}const wa=(()=>{const s=sc();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function fu(s,e){return s.getTime()/1e3-e}function nE(s){return Uint8Array.from(s.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class sE{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:e}=this;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(Rs(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const i=e[t];if(i.kind==="metadata"&&i.label==="id3")return Wg(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:i,enableID3MetadataCues:n}}}=this;if(!i&&!n)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=sc();if(o)for(let u=0;u<r.length;u++){const h=r[u].type;if(h===pi.emsg&&!i||!n)continue;const p=Ng(r[u].data);if(p){const d=r[u].pts;let g=d+r[u].duration;g>wa&&(g=wa),g-d<=0&&(g=d+iE);for(let b=0;b<p.length;b++){const E=p[b];if(!Fg(E)){this.updateId3CueEnds(d,h);const w=mf(o,d,g,E,h);w&&this.id3Track.addCue(w)}}}}}updateId3CueEnds(e,t){var i;const n=(i=this.id3Track)==null?void 0:i.cues;if(n)for(let r=n.length;r--;){const o=n[r];o.type===t&&o.startTime<e&&o.endTime===wa&&(o.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:n}){const{id3Track:r,hls:o}=this;if(!o)return;const{config:{enableEmsgMetadataCues:u,enableID3MetadataCues:h}}=o;if(r&&(u||h)){let p;n==="audio"?p=d=>d.type===pi.audioId3&&h:n==="video"?p=d=>d.type===pi.emsg&&u:p=d=>d.type===pi.audioId3&&h||d.type===pi.emsg&&u,nc(r,t,i,p)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:i,id3Track:n}=this,{dateRanges:r}=t,o=Object.keys(r);if(n){const d=Object.keys(i).filter(g=>!o.includes(g));for(let g=d.length;g--;){const T=d[g];Object.keys(i[T].cues).forEach(b=>{n.removeCue(i[T].cues[b])}),delete i[T]}}const u=t.fragments[t.fragments.length-1];if(o.length===0||!Ae(u?.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const h=u.programDateTime/1e3-u.start,p=sc();for(let d=0;d<o.length;d++){const g=o[d],T=r[g],b=fu(T.startDate,h),E=i[g],w=E?.cues||{};let A=E?.durationKnown||!1,L=wa;const P=T.endDate;if(P)L=fu(P,h),A=!0;else if(T.endOnNext&&!A){const O=o.reduce((k,N)=>{if(N!==T.id){const H=r[N];if(H.class===T.class&&H.startDate>T.startDate&&(!k||T.startDate<k.startDate))return H}return k},null);O&&(L=fu(O.startDate,h),A=!0)}const M=Object.keys(T.attr);for(let O=0;O<M.length;O++){const k=M[O];if(!o_(k))continue;const N=w[k];if(N)A&&!E.durationKnown&&(N.endTime=L);else if(p){let H=T.attr[k];l_(k)&&(H=nE(H));const G=mf(p,b,L,{key:k,data:H},pi.dateRange);G&&(G.id=g,this.id3Track.addCue(G),w[k]=G)}}i[g]={cues:w,dateRange:T,durationKnown:A}}}}class rE{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:t}=this;return e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(e===null)return null;const{holdBack:t,partHoldBack:i,targetduration:n}=e,{liveSyncDuration:r,liveSyncDurationCount:o,lowLatencyMode:u}=this.config,h=this.hls.userConfig;let p=u&&i||t;(h.liveSyncDuration||h.liveSyncDurationCount||p===0)&&(p=r!==void 0?r:o*n);const d=n;return p+Math.min(this.stallCount*1,d)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,i=this.levelDetails;if(e===null||t===null||i===null)return null;const n=i.edge,r=e-t-this.edgeStalled,o=n-i.totalduration,u=n-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(o,r),u)}get drift(){const{levelDetails:e}=this;return e===null?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e,levelDetails:t}=this;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(I.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(I.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var i;t.details===te.BUFFER_STALLED_ERROR&&(this.stallCount++,(i=this.levelDetails)!=null&&i.live&&W.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:r}=this.config;if(!n||r===1||!t.live)return;const o=this.targetLatency;if(o===null)return;const u=i-o,h=Math.min(this.maxLatency,o+t.targetduration);if(u<h&&u>.05&&this.forwardBufferLength>1){const d=Math.min(2,Math.max(1,r)),g=Math.round(2/(1+Math.exp(-.75*u-this.edgeStalled))*20)/20;e.playbackRate=Math.min(d,Math.max(1,g))}else e.playbackRate!==1&&e.playbackRate!==0&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}const rc=["NONE","TYPE-0","TYPE-1",null];function aE(s){return rc.indexOf(s)>-1}const go=["SDR","PQ","HLG"];function oE(s){return!!s&&go.indexOf(s)>-1}var Wa={No:"",Yes:"YES",v2:"v2"};function yf(s){const{canSkipUntil:e,canSkipDateRanges:t,age:i}=s,n=i<e/2;return e&&n?t?Wa.v2:Wa.Yes:Wa.No}class vf{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class js{constructor(e){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(t=>!!t).map(t=>t.substring(0,4)).join(","),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 Tf(this._audioGroups,e)}hasSubtitleGroup(e){return Tf(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.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(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function Tf(s,e){return!e||!s?!1:s.indexOf(e)!==-1}function pu(s,e){const t=e.startPTS;if(Ae(t)){let i=0,n;e.sn>s.sn?(i=t-s.start,n=s):(i=s.start-t,n=e),n.duration!==i&&(n.duration=i)}else e.sn>s.sn?s.cc===e.cc&&s.minEndPTS?e.start=s.start+(s.minEndPTS-s.start):e.start=s.start+s.duration:e.start=Math.max(s.start-e.duration,0)}function Yg(s,e,t,i,n,r){i-t<=0&&(W.warn("Fragment should have a positive duration",e),i=t+e.duration,r=n+e.duration);let u=t,h=i;const p=e.startPTS,d=e.endPTS;if(Ae(p)){const A=Math.abs(p-t);Ae(e.deltaPTS)?e.deltaPTS=Math.max(A,e.deltaPTS):e.deltaPTS=A,u=Math.max(t,p),t=Math.min(t,p),n=Math.min(n,e.startDTS),h=Math.min(i,d),i=Math.max(i,d),r=Math.max(r,e.endDTS)}const g=t-e.start;e.start!==0&&(e.start=t),e.duration=i-e.start,e.startPTS=t,e.maxStartPTS=u,e.startDTS=n,e.endPTS=i,e.minEndPTS=h,e.endDTS=r;const T=e.sn;if(!s||T<s.startSN||T>s.endSN)return 0;let b;const E=T-s.startSN,w=s.fragments;for(w[E]=e,b=E;b>0;b--)pu(w[b],w[b-1]);for(b=E;b<w.length-1;b++)pu(w[b],w[b+1]);return s.fragmentHint&&pu(w[w.length-1],s.fragmentHint),s.PTSKnown=s.alignedSliding=!0,g}function lE(s,e){let t=null;const i=s.fragments;for(let u=i.length-1;u>=0;u--){const h=i[u].initSegment;if(h){t=h;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let n;hE(s,e,(u,h,p,d)=>{if(e.skippedSegments&&h.cc!==u.cc){const g=u.cc-h.cc;for(let T=p;T<d.length;T++)d[T].cc+=g}Ae(u.startPTS)&&Ae(u.endPTS)&&(h.start=h.startPTS=u.startPTS,h.startDTS=u.startDTS,h.maxStartPTS=u.maxStartPTS,h.endPTS=u.endPTS,h.endDTS=u.endDTS,h.minEndPTS=u.minEndPTS,h.duration=u.endPTS-u.startPTS,h.duration&&(n=h),e.PTSKnown=e.alignedSliding=!0),h.elementaryStreams=u.elementaryStreams,h.loader=u.loader,h.stats=u.stats,u.initSegment&&(h.initSegment=u.initSegment,t=u.initSegment)});const r=e.fragments;if(t&&(e.fragmentHint?r.concat(e.fragmentHint):r).forEach(h=>{var p;h&&(!h.initSegment||h.initSegment.relurl===((p=t)==null?void 0:p.relurl))&&(h.initSegment=t)}),e.skippedSegments){if(e.deltaUpdateFailed=r.some(u=>!u),e.deltaUpdateFailed){W.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let u=e.skippedSegments;u--;)r.shift();e.startSN=r[0].sn}else e.canSkipDateRanges&&(e.dateRanges=uE(s.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));e.startCC=e.fragments[0].cc,e.endCC=r[r.length-1].cc}cE(s.partList,e.partList,(u,h)=>{h.elementaryStreams=u.elementaryStreams,h.stats=u.stats}),n?Yg(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):Xg(s,e),r.length&&(e.totalduration=e.edge-r[0].start),e.driftStartTime=s.driftStartTime,e.driftStart=s.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const u=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=u),e.driftEndTime=o,e.driftEnd=u}else e.driftEndTime=s.driftEndTime,e.driftEnd=s.driftEnd,e.advancedDateTime=s.advancedDateTime}function uE(s,e,t){const i=vt({},s);return t&&t.forEach(n=>{delete i[n]}),Object.keys(e).forEach(n=>{const r=new Pg(e[n].attr,i[n]);r.isValid?i[n]=r:W.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[n].attr)}"`)}),i}function cE(s,e,t){if(s&&e){let i=0;for(let n=0,r=s.length;n<=r;n++){const o=s[n],u=e[n+i];o&&u&&o.index===u.index&&o.fragment.sn===u.fragment.sn?t(o,u):i--}}}function hE(s,e,t){const i=e.skippedSegments,n=Math.max(s.startSN,e.startSN)-e.startSN,r=(s.fragmentHint?1:0)+(i?e.endSN:Math.min(s.endSN,e.endSN))-e.startSN,o=e.startSN-s.startSN,u=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,h=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let p=n;p<=r;p++){const d=h[o+p];let g=u[p];i&&!g&&p<i&&(g=e.fragments[p]=d),d&&g&&t(d,g,p,u)}}function Xg(s,e){const t=e.startSN+e.skippedSegments-s.startSN,i=s.fragments;t<0||t>=i.length||ac(e,i[t].start)}function ac(s,e){if(e){const t=s.fragments;for(let i=s.skippedSegments;i<t.length;i++)t[i].start+=e;s.fragmentHint&&(s.fragmentHint.start+=e)}}function dE(s,e=1/0){let t=1e3*s.targetduration;if(s.updated){const i=s.fragments;if(i.length&&t*4>e){const r=i[i.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function fE(s,e,t){if(!(s!=null&&s.details))return null;const i=s.details;let n=i.fragments[e-i.startSN];return n||(n=i.fragmentHint,n&&n.sn===e)?n:e<i.startSN&&t&&t.sn===e?t:null}function bf(s,e,t){var i;return s!=null&&s.details?Qg((i=s.details)==null?void 0:i.partList,e,t):null}function Qg(s,e,t){if(s)for(let i=s.length;i--;){const n=s[i];if(n.index===t&&n.fragment.sn===e)return n}return null}function Jg(s){s.forEach((e,t)=>{const{details:i}=e;i!=null&&i.fragments&&i.fragments.forEach(n=>{n.level=t})})}function mo(s){switch(s.details){case te.FRAG_LOAD_TIMEOUT:case te.KEY_LOAD_TIMEOUT:case te.LEVEL_LOAD_TIMEOUT:case te.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function _f(s,e){const t=mo(e);return s.default[`${t?"timeout":"error"}Retry`]}function $c(s,e){const t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function Ef(s){return St(St({},s),{errorRetry:null,timeoutRetry:null})}function yo(s,e,t,i){if(!s)return!1;const n=i?.code,r=e<s.maxNumRetry&&(pE(n)||!!t);return s.shouldRetry?s.shouldRetry(s,e,t,i,r):r}function pE(s){return s===0&&navigator.onLine===!1||!!s&&(s<400||s>499)}const Zg={search:function(s,e){let t=0,i=s.length-1,n=null,r=null;for(;t<=i;){n=(t+i)/2|0,r=s[n];const o=e(r);if(o>0)t=n+1;else if(o<0)i=n-1;else return r}return null}};function gE(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!Ae(e))return null;const i=s[0].programDateTime;if(e<(i||0))return null;const n=s[s.length-1].endProgramDateTime;if(e>=(n||0))return null;t=t||0;for(let r=0;r<s.length;++r){const o=s[r];if(yE(e,t,o))return o}return null}function vo(s,e,t=0,i=0,n=.005){let r=null;if(s){r=e[s.sn-e[0].sn+1]||null;const u=s.endDTS-t;u>0&&u<15e-7&&(t+=15e-7)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!s||s.level===r.level)&&oc(t,i,r)===0||mE(r,s,Math.min(n,i))))return r;const o=Zg.search(e,oc.bind(null,t,i));return o&&(o!==s||!r)?o:r}function mE(s,e,t){if(e&&e.start===0&&e.level<s.level&&(e.endPTS||0)>0){const i=e.tagList.reduce((n,r)=>(r[0]==="INF"&&(n+=parseFloat(r[1])),n),t);return s.start<=i}return!1}function oc(s=0,e=0,t){if(t.start<=s&&t.start+t.duration>s)return 0;const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=s?1:t.start-i>s&&t.start?-1:0}function yE(s,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>s}function vE(s,e){return Zg.search(s,t=>t.cc<e?1:t.cc>e?-1:0)}var Lt={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},hi={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2};class TE{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=W.log.bind(W,"[info]:"),this.warn=W.warn.bind(W,"[warning]:"),this.error=W.error.bind(W,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(I.ERROR,this.onError,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(I.ERROR,this.onError,this),e.off(I.ERROR,this.onErrorOut,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===Pe.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i,n;if(t.fatal)return;const r=this.hls,o=t.context;switch(t.details){case te.FRAG_LOAD_ERROR:case te.FRAG_LOAD_TIMEOUT:case te.KEY_LOAD_ERROR:case te.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case te.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction={action:Lt.DoNothing,flags:hi.None};return}case te.FRAG_GAP:case te.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Lt.SendAlternateToPenaltyBox;return}case te.LEVEL_EMPTY_ERROR:case te.LEVEL_PARSING_ERROR:{var u,h;const p=t.parent===Pe.MAIN?t.level:r.loadLevel;t.details===te.LEVEL_EMPTY_ERROR&&((u=t.context)!=null&&(h=u.levelDetails)!=null&&h.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,p):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,p))}return;case te.LEVEL_LOAD_ERROR:case te.LEVEL_LOAD_TIMEOUT:typeof o?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,o.level));return;case te.AUDIO_TRACK_LOAD_ERROR:case te.AUDIO_TRACK_LOAD_TIMEOUT:case te.SUBTITLE_LOAD_ERROR:case te.SUBTITLE_TRACK_LOAD_TIMEOUT:if(o){const p=r.levels[r.loadLevel];if(p&&(o.type===qe.AUDIO_TRACK&&p.hasAudioGroup(o.groupId)||o.type===qe.SUBTITLE_TRACK&&p.hasSubtitleGroup(o.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=Lt.SendAlternateToPenaltyBox,t.errorAction.flags=hi.MoveAllAlternatesMatchingHost;return}}return;case te.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const p=r.levels[r.loadLevel],d=p?.attrs["HDCP-LEVEL"];d?t.errorAction={action:Lt.SendAlternateToPenaltyBox,flags:hi.MoveAllAlternatesMatchingHDCP,hdcpLevel:d}:this.keySystemError(t)}return;case te.BUFFER_ADD_CODEC_ERROR:case te.REMUX_ALLOC_ERROR:case te.BUFFER_APPEND_ERROR:t.errorAction=this.getLevelSwitchAction(t,(n=t.level)!=null?n:r.loadLevel);return;case te.INTERNAL_EXCEPTION:case te.BUFFER_APPENDING_ERROR:case te.BUFFER_FULL_ERROR:case te.LEVEL_SWITCH_ERROR:case te.BUFFER_STALLED_ERROR:case te.BUFFER_SEEK_OVER_HOLE:case te.BUFFER_NUDGE_ON_STALL:t.errorAction={action:Lt.DoNothing,flags:hi.None};return}t.type===xe.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,n=_f(i.config.playlistLoadPolicy,e),r=this.playlistError++;if(yo(n,r,mo(e),e.response))return{action:Lt.RetryRequest,flags:hi.None,retryConfig:n,retryCount:r};const u=this.getLevelSwitchAction(e,t);return n&&(u.retryConfig=n,u.retryCount=r),u}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),n=t.levels[i],{fragLoadPolicy:r,keyLoadPolicy:o}=t.config,u=_f(e.details.startsWith("key")?o:r,e),h=t.levels.reduce((d,g)=>d+g.fragmentError,0);if(n&&(e.details!==te.FRAG_GAP&&n.fragmentError++,yo(u,h,mo(e),e.response)))return{action:Lt.RetryRequest,flags:hi.None,retryConfig:u,retryCount:h};const p=this.getLevelSwitchAction(e,i);return u&&(p.retryConfig=u,p.retryCount=h),p}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const n=this.hls.levels[t];if(n){var r,o;const p=e.details;n.loadError++,p===te.BUFFER_APPEND_ERROR&&n.fragmentError++;let d=-1;const{levels:g,loadLevel:T,minAutoLevel:b,maxAutoLevel:E}=i;i.autoLevelEnabled||(i.loadLevel=-1);const w=(r=e.frag)==null?void 0:r.type,L=(w===Pe.AUDIO&&p===te.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(p===te.BUFFER_ADD_CODEC_ERROR||p===te.BUFFER_APPEND_ERROR))&&g.some(({audioCodec:N})=>n.audioCodec!==N),M=e.sourceBufferName==="video"&&(p===te.BUFFER_ADD_CODEC_ERROR||p===te.BUFFER_APPEND_ERROR)&&g.some(({codecSet:N,audioCodec:H})=>n.codecSet!==N&&n.audioCodec===H),{type:O,groupId:k}=(o=e.context)!=null?o:{};for(let N=g.length;N--;){const H=(N+T)%g.length;if(H!==T&&H>=b&&H<=E&&g[H].loadError===0){var u,h;const G=g[H];if(p===te.FRAG_GAP&&w===Pe.MAIN&&e.frag){const B=g[H].details;if(B){const D=vo(e.frag,B.fragments,e.frag.start);if(D!=null&&D.gap)continue}}else{if(O===qe.AUDIO_TRACK&&G.hasAudioGroup(k)||O===qe.SUBTITLE_TRACK&&G.hasSubtitleGroup(k))continue;if(w===Pe.AUDIO&&(u=n.audioGroups)!=null&&u.some(B=>G.hasAudioGroup(B))||w===Pe.SUBTITLE&&(h=n.subtitleGroups)!=null&&h.some(B=>G.hasSubtitleGroup(B))||L&&n.audioCodec===G.audioCodec||!L&&n.audioCodec!==G.audioCodec||M&&n.codecSet===G.codecSet)continue}d=H;break}}if(d>-1&&i.loadLevel!==d)return e.levelRetry=!0,this.playlistError=0,{action:Lt.SendAlternateToPenaltyBox,flags:hi.None,nextAutoLevel:d}}return{action:Lt.SendAlternateToPenaltyBox,flags:hi.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case Lt.DoNothing:break;case Lt.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==te.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}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:n,hdcpLevel:r,nextAutoLevel:o}=i;switch(n){case hi.None:this.switchLevel(e,o);break;case hi.MoveAllAlternatesMatchingHDCP:r&&(t.maxHdcpLevel=rc[rc.indexOf(r)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}i.resolved||this.switchLevel(e,o)}switchLevel(e,t){t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}}class jc{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=W.log.bind(W,`${t}:`),this.warn=W.warn.bind(W,`${t}:`),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.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const n=t?.renditionReports;if(n){let r=-1;for(let o=0;o<n.length;o++){const u=n[o];let h;try{h=new self.URL(u.URI,t.url).href}catch(p){W.warn(`Could not construct new URL for Rendition Report: ${p}`),h=u.URI||""}if(h===e){r=o;break}else h===e.substring(0,h.length)&&(r=o)}if(r!==-1){const o=n[r],u=parseInt(o["LAST-MSN"])||t?.lastPartSn;let h=parseInt(o["LAST-PART"])||t?.lastPartIndex;if(this.hls.config.lowLatencyMode){const d=Math.min(t.age-t.partTarget,t.targetduration);h>=0&&d>t.partTarget&&(h+=1)}const p=i&&yf(i);return new vf(u,h>=0?h:void 0,p)}}}loadPlaylist(e){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,i){const{details:n,stats:r}=t,o=self.performance.now(),u=r.loading.first?Math.max(0,o-r.loading.first):0;if(n.advancedDateTime=Date.now()-u,n.live||i!=null&&i.live){if(n.reloaded(i),i&&this.log(`live playlist ${e} ${n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:n.updated?"UPDATED":"MISSED"}`),i&&n.fragments.length>0&&lE(i,n),!this.canLoad||!n.live)return;let h,p,d;if(n.canBlockReload&&n.endSN&&n.advanced){const A=this.hls.config.lowLatencyMode,L=n.lastPartSn,P=n.endSN,M=n.lastPartIndex,O=M!==-1,k=L===P,N=A?0:M;O?(p=k?P+1:L,d=k?N:M+1):p=P+1;const H=n.age,G=H+n.ageHeader;let B=Math.min(G-n.partTarget,n.targetduration*1.5);if(B>0){if(i&&B>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${B} with playlist age: ${n.age}`),B=0;else{const D=Math.floor(B/n.targetduration);if(p+=D,d!==void 0){const K=Math.round(B%n.targetduration/n.partTarget);d+=K}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${H.toFixed(2)}s goal: ${B} skip sn ${D} to part ${d}`)}n.tuneInGoal=B}if(h=this.getDeliveryDirectives(n,t.deliveryDirectives,p,d),A||!k){this.loadPlaylist(h);return}}else(n.canBlockReload||n.canSkipUntil)&&(h=this.getDeliveryDirectives(n,t.deliveryDirectives,p,d));const g=this.hls.mainForwardBufferInfo,T=g?g.end-g.len:0,b=(n.edge-T)*1e3,E=dE(n,b);n.updated&&o>this.requestScheduled+E&&(this.requestScheduled=r.loading.start),p!==void 0&&n.canBlockReload?this.requestScheduled=r.loading.first+E-(n.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+E<o?this.requestScheduled=o:this.requestScheduled-o<=0&&(this.requestScheduled+=E);let w=this.requestScheduled-o;w=Math.max(0,w),this.log(`reload live playlist ${e} in ${Math.round(w)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(h),w)}else this.clearTimer()}getDeliveryDirectives(e,t,i,n){let r=yf(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,n=t.part,r=Wa.No),new vf(i,n,r)}checkRetry(e){const t=e.details,i=mo(e),n=e.errorAction,{action:r,retryCount:o=0,retryConfig:u}=n||{},h=!!n&&!!u&&(r===Lt.RetryRequest||!n.resolved&&r===Lt.SendAlternateToPenaltyBox);if(h){var p;if(this.requestScheduled=-1,o>=u.maxNumRetry)return!1;if(i&&(p=e.context)!=null&&p.deliveryDirectives)this.warn(`Retrying playlist loading ${o+1}/${u.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const d=$c(u,o);this.timer=self.setTimeout(()=>this.loadPlaylist(),d),this.warn(`Retrying playlist loading ${o+1}/${u.maxNumRetry} after "${t}" in ${d}ms`)}e.levelRetry=!0,n.resolved=!0}return h}}class Ss{constructor(e,t=0,i=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_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class bE{constructor(e,t,i,n=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_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ss(e),this.fast_=new Ss(t),this.defaultTTFB_=n,this.ttfb_=new Ss(e)}update(e,t){const{slow_:i,fast_:n,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new Ss(e,i.getEstimate(),i.getTotalWeight())),n.halfLife!==t&&(this.fast_=new Ss(t,n.getEstimate(),n.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new Ss(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const i=8*t,n=e/1e3,r=i/n;this.fast_.sample(n,r),this.slow_.sample(n,r)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,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_}destroy(){}}const em={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Sf={};function _E(s,e,t,i,n,r){const o=s.audioCodec?s.audioGroups:null,u=r?.audioCodec,h=r?.channels,p=h?parseInt(h):u?1/0:2;let d=null;if(o!=null&&o.length)try{o.length===1&&o[0]?d=e.groups[o[0]].channels:d=o.reduce((g,T)=>{if(T){const b=e.groups[T];if(!b)throw new Error(`Audio track group ${T} not found`);Object.keys(b.channels).forEach(E=>{g[E]=(g[E]||0)+b.channels[E]})}return g},{2:0})}catch{return!0}return s.videoCodec!==void 0&&(s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(i,30)||s.videoRange!=="SDR"&&s.videoRange!==t||s.bitrate>Math.max(n,8e6))||!!d&&Ae(p)&&Object.keys(d).some(g=>parseInt(g)>p)}function EE(s,e,t){const i=s.videoCodec,n=s.audioCodec;if(!i||!n||!t)return Promise.resolve(em);const r={width:s.width,height:s.height,bitrate:Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)),framerate:s.frameRate||30},o=s.videoRange;o!=="SDR"&&(r.transferFunction=o.toLowerCase());const u=i.split(",").map(h=>({type:"media-source",video:St(St({},r),{},{contentType:Rr(h,"video")})}));return n&&s.audioGroups&&s.audioGroups.forEach(h=>{var p;h&&((p=e.groups[h])==null||p.tracks.forEach(d=>{if(d.groupId===h){const g=d.channels||"",T=parseFloat(g);Ae(T)&&T>2&&u.push.apply(u,n.split(",").map(b=>({type:"media-source",audio:{contentType:Rr(b,"audio"),channels:""+T}})))}}))}),Promise.all(u.map(h=>{const p=SE(h);return Sf[p]||(Sf[p]=t.decodingInfo(h))})).then(h=>({supported:!h.some(p=>!p.supported),configurations:u,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:u,decodingInfoResults:[],error:h}))}function SE(s){const{audio:e,video:t}=s,i=t||e;if(i){const n=i.contentType.split('"')[1];if(t)return`r${t.height}x${t.width}f${Math.ceil(t.framerate)}${t.transferFunction||"sd"}_${n}_${Math.ceil(t.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${n}`}return""}function CE(){if(typeof matchMedia=="function"){const s=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(s.media!==e.media)return s.matches===!0}return!1}function wE(s,e){let t=!1,i=[];return s&&(t=s!=="SDR",i=[s]),e&&(i=e.allowedVideoRanges||go.slice(0),t=e.preferHDR!==void 0?e.preferHDR:CE(),t?i=i.filter(n=>n!=="SDR"):i=["SDR"]),{preferHDR:t,allowedVideoRanges:i}}function AE(s,e,t,i,n){const r=Object.keys(s),o=i?.channels,u=i?.audioCodec,h=o&&parseInt(o)===2;let p=!0,d=!1,g=1/0,T=1/0,b=1/0,E=0,w=[];const{preferHDR:A,allowedVideoRanges:L}=wE(e,n);for(let k=r.length;k--;){const N=s[r[k]];p=N.channels[2]>0,g=Math.min(g,N.minHeight),T=Math.min(T,N.minFramerate),b=Math.min(b,N.minBitrate);const H=L.filter(G=>N.videoRanges[G]>0);H.length>0&&(d=!0,w=H)}g=Ae(g)?g:0,T=Ae(T)?T:0;const P=Math.max(1080,g),M=Math.max(30,T);return b=Ae(b)?b:t,t=Math.max(b,t),d||(e=void 0,w=[]),{codecSet:r.reduce((k,N)=>{const H=s[N];if(N===k)return k;if(H.minBitrate>t)return Vi(N,`min bitrate of ${H.minBitrate} > current estimate of ${t}`),k;if(!H.hasDefaultAudio)return Vi(N,"no renditions with default or auto-select sound found"),k;if(u&&N.indexOf(u.substring(0,4))%5!==0)return Vi(N,`audio codec preference "${u}" not found`),k;if(o&&!h){if(!H.channels[o])return Vi(N,`no renditions with ${o} channel sound found (channels options: ${Object.keys(H.channels)})`),k}else if((!u||h)&&p&&H.channels[2]===0)return Vi(N,"no renditions with stereo sound found"),k;return H.minHeight>P?(Vi(N,`min resolution of ${H.minHeight} > maximum of ${P}`),k):H.minFramerate>M?(Vi(N,`min framerate of ${H.minFramerate} > maximum of ${M}`),k):w.some(G=>H.videoRanges[G]>0)?H.maxScore<E?(Vi(N,`max score of ${H.maxScore} < selected max of ${E}`),k):k&&(fo(N)>=fo(k)||H.fragmentError>s[k].fragmentError)?k:(E=H.maxScore,N):(Vi(N,`no variants with VIDEO-RANGE of ${JSON.stringify(w)} found`),k)},void 0),videoRanges:w,preferHDR:A,minFramerate:T,minBitrate:b}}function Vi(s,e){W.log(`[abr] start candidates with "${s}" ignored because ${e}`)}function LE(s){return s.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);const n=t.channels||"2";return i.channels[n]=(i.channels[n]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function kE(s,e,t,i){return s.slice(t,i+1).reduce((n,r)=>{if(!r.codecSet)return n;const o=r.audioGroups;let u=n[r.codecSet];u||(n[r.codecSet]=u={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),u.minBitrate=Math.min(u.minBitrate,r.bitrate);const h=Math.min(r.height,r.width);return u.minHeight=Math.min(u.minHeight,h),u.minFramerate=Math.min(u.minFramerate,r.frameRate),u.maxScore=Math.max(u.maxScore,r.score),u.fragmentError+=r.fragmentError,u.videoRanges[r.videoRange]=(u.videoRanges[r.videoRange]||0)+1,o&&o.forEach(p=>{if(!p)return;const d=e.groups[p];d&&(u.hasDefaultAudio=u.hasDefaultAudio||e.hasDefaultAudio?d.hasDefault:d.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(d.channels).forEach(g=>{u.channels[g]=(u.channels[g]||0)+d.channels[g]}))}),n},{})}function Di(s,e,t){if("attrs"in s){const i=e.indexOf(s);if(i!==-1)return i}for(let i=0;i<e.length;i++){const n=e[i];if(es(s,n,t))return i}return-1}function es(s,e,t){const{groupId:i,name:n,lang:r,assocLang:o,default:u}=s,h=s.forced;return(i===void 0||e.groupId===i)&&(n===void 0||e.name===n)&&(r===void 0||e.lang===r)&&(r===void 0||e.assocLang===o)&&(u===void 0||e.default===u)&&(h===void 0||e.forced===h)&&(!("characteristics"in s)||IE(s.characteristics||"",e.characteristics))&&(t===void 0||t(s,e))}function IE(s,e=""){const t=s.split(","),i=e.split(",");return t.length===i.length&&!t.some(n=>i.indexOf(n)===-1)}function Wn(s,e){const{audioCodec:t,channels:i}=s;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function RE(s,e,t,i,n){const r=e[i],u=e.reduce((T,b,E)=>{const w=b.uri;return(T[w]||(T[w]=[])).push(E),T},{})[r.uri];u.length>1&&(i=Math.max.apply(Math,u));const h=r.videoRange,p=r.frameRate,d=r.codecSet.substring(0,4),g=Cf(e,i,T=>{if(T.videoRange!==h||T.frameRate!==p||T.codecSet.substring(0,4)!==d)return!1;const b=T.audioGroups,E=t.filter(w=>!b||b.indexOf(w.groupId)!==-1);return Di(s,E,n)>-1});return g>-1?g:Cf(e,i,T=>{const b=T.audioGroups,E=t.filter(w=>!b||b.indexOf(w.groupId)!==-1);return Di(s,E,n)>-1})}function Cf(s,e,t){for(let i=e;i>-1;i--)if(t(s[i]))return i;for(let i=e+1;i<s.length;i++)if(t(s[i]))return i;return-1}class PE{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:t,partCurrent:i,hls:n}=this,{autoLevelEnabled:r,media:o}=n;if(!t||!o)return;const u=performance.now(),h=i?i.stats:t.stats,p=i?i.duration:t.duration,d=u-h.loading.start,g=n.minAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||t.level<=g){this.clearTimer(),this._nextAutoLevel=-1;return}if(!r||o.paused||!o.playbackRate||!o.readyState)return;const T=n.mainForwardBufferInfo;if(T===null)return;const b=this.bwEstimator.getEstimateTTFB(),E=Math.abs(o.playbackRate);if(d<=Math.max(b,1e3*(p/(E*2))))return;const w=T.len/E,A=h.loading.first?h.loading.first-h.loading.start:-1,L=h.loaded&&A>-1,P=this.getBwEstimate(),M=n.levels,O=M[t.level],k=h.total||Math.max(h.loaded,Math.round(p*O.averageBitrate/8));let N=L?d-A:d;N<1&&L&&(N=Math.min(d,h.loaded*8/P));const H=L?h.loaded*1e3/N:0,G=H?(k-h.loaded)/H:k*8/P+b/1e3;if(G<=w)return;const B=H?H*8:P;let D=Number.POSITIVE_INFINITY,K;for(K=t.level-1;K>g;K--){const Z=M[K].maxBitrate;if(D=this.getTimeToLoadFrag(b/1e3,B,p*Z,!M[K].details),D<w)break}if(D>=G||D>p*10)return;n.nextLoadLevel=n.nextAutoLevel=K,L?this.bwEstimator.sample(d-Math.min(b,A),h.loaded):this.bwEstimator.sampleTTFB(d);const oe=M[K].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>oe&&this.resetEstimator(oe),this.clearTimer(),W.warn(`[abr] Fragment ${t.sn}${i?" part "+i.index:""} of level ${t.level} is loading too slowly;
      Time to underbuffer: ${w.toFixed(3)} s
      Estimated load time for current fragment: ${G.toFixed(3)} s
      Estimated load time for down switch fragment: ${D.toFixed(3)} s
      TTFB estimate: ${A|0} ms
      Current BW estimate: ${Ae(P)?P|0:"Unknown"} bps
      New BW estimate: ${this.getBwEstimate()|0} bps
      Switching to level ${K} @ ${oe|0} bps`),n.trigger(I.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:i,stats:h})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(W.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new bE(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.FRAG_LOADING,this.onFragLoading,this),e.on(I.FRAG_LOADED,this.onFragLoaded,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this),e.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.FRAG_LOADING,this.onFragLoading,this),e.off(I.FRAG_LOADED,this.onFragLoaded,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this),e.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(I.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,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){const i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var n;this.fragCurrent=i,this.partCurrent=(n=t.part)!=null?n: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 te.BUFFER_ADD_CODEC_ERROR:case te.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case te.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:n,partCurrent:r}=this;if(i&&n&&i.sn===n.sn&&i.level===n.level){const o=performance.now(),u=r?r.stats:i.stats,h=o-u.loading.start,p=u.loading.first?u.loading.first-u.loading.start:-1;if(u.loaded&&p>-1){const g=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(h-Math.min(g,p),u.loaded)}else this.bwEstimator.sampleTTFB(h)}break}}}getTimeToLoadFrag(e,t,i,n){const r=e+i/t,o=n?this.lastLevelLoadSec:0;return r+o}onLevelLoaded(e,t){const i=this.hls.config,{loading:n}=t.stats,r=n.end-n.start;Ae(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}onFragLoaded(e,{frag:t,part:i}){const n=i?i.stats:t.stats;if(t.type===Pe.MAIN&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=i?i.duration:t.duration,o=this.hls.levels[t.level],u=(o.loaded?o.loaded.bytes:0)+n.loaded,h=(o.loaded?o.loaded.duration:0)+r;o.loaded={bytes:u,duration:h},o.realBitrate=Math.round(8*u/h)}if(t.bitrateTest){const r={stats:n,frag:t,part:i,id:t.type};this.onFragBuffered(I.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:n}=t,r=n!=null&&n.stats.loaded?n.stats:i.stats;if(r.aborted||this.ignoreFragment(i))return;const o=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=o/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Pe.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,t,e,0,n,1,1);if(r>-1)return r;const o=this.hls.firstLevel,u=Math.min(Math.max(o,t),e);return W.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${u}`),u}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),n=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!n||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=i&&n?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const o=this.hls.levels;if(o.length>Math.max(e,r)&&o[e].loadError<=o[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this,{maxAutoLevel:n,config:r,minAutoLevel:o}=i,u=t?t.duration:e?e.duration:0,h=this.getBwEstimate(),p=this.getStarvationDelay();let d=r.abrBandWidthFactor,g=r.abrBandWidthUpFactor;if(p){const A=this.findBestLevel(h,o,n,p,0,d,g);if(A>=0)return A}let T=u?Math.min(u,r.maxStarvationDelay):r.maxStarvationDelay;if(!p){const A=this.bitrateTestDelay;A&&(T=(u?Math.min(u,r.maxLoadingDelay):r.maxLoadingDelay)-A,W.info(`[abr] bitrate test took ${Math.round(1e3*A)}ms, set first fragment max fetchDuration to ${Math.round(1e3*T)} ms`),d=g=1)}const b=this.findBestLevel(h,o,n,p,T,d,g);if(W.info(`[abr] ${p?"rebuffering expected":"buffer is empty"}, optimal quality level ${b}`),b>-1)return b;const E=i.levels[o],w=i.levels[i.loadLevel];return E?.bitrate<w?.bitrate?o:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,n,r,o,u){var h;const p=n+r,d=this.lastLoadedFragLevel,g=d===-1?this.hls.firstLevel:d,{fragCurrent:T,partCurrent:b}=this,{levels:E,allAudioTracks:w,loadLevel:A,config:L}=this.hls;if(E.length===1)return 0;const P=E[g],M=!!(P!=null&&(h=P.details)!=null&&h.live),O=A===-1||d===-1;let k,N="SDR",H=P?.frameRate||0;const{audioPreference:G,videoPreference:B}=L,D=this.audioTracksByGroup||(this.audioTracksByGroup=LE(w));if(O){if(this.firstSelection!==-1)return this.firstSelection;const ce=this.codecTiers||(this.codecTiers=kE(E,D,t,i)),fe=AE(ce,N,e,G,B),{codecSet:ve,videoRanges:be,minFramerate:ee,minBitrate:Q,preferHDR:Ee}=fe;k=ve,N=Ee?be[be.length-1]:be[0],H=ee,e=Math.max(e,Q),W.log(`[abr] picked start tier ${JSON.stringify(fe)}`)}else k=P?.codecSet,N=P?.videoRange;const K=b?b.duration:T?T.duration:0,oe=this.bwEstimator.getEstimateTTFB()/1e3,Z=[];for(let ce=i;ce>=t;ce--){var le;const fe=E[ce],ve=ce>g;if(!fe)continue;if(L.useMediaCapabilities&&!fe.supportedResult&&!fe.supportedPromise){const Le=navigator.mediaCapabilities;typeof Le?.decodingInfo=="function"&&_E(fe,D,N,H,e,G)?(fe.supportedPromise=EE(fe,D,Le),fe.supportedPromise.then(Ce=>{if(!this.hls)return;fe.supportedResult=Ce;const Ue=this.hls.levels,He=Ue.indexOf(fe);Ce.error?W.warn(`[abr] MediaCapabilities decodingInfo error: "${Ce.error}" for level ${He} ${JSON.stringify(Ce)}`):Ce.supported||(W.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${He} ${JSON.stringify(Ce)}`),He>-1&&Ue.length>1&&(W.log(`[abr] Removing unsupported level ${He}`),this.hls.removeLevel(He)))})):fe.supportedResult=em}if(k&&fe.codecSet!==k||N&&fe.videoRange!==N||ve&&H>fe.frameRate||!ve&&H>0&&H<fe.frameRate||fe.supportedResult&&!((le=fe.supportedResult.decodingInfoResults)!=null&&le[0].smooth)){Z.push(ce);continue}const be=fe.details,ee=(b?be?.partTarget:be?.averagetargetduration)||K;let Q;ve?Q=u*e:Q=o*e;const Ee=K&&n>=K*2&&r===0?E[ce].averageBitrate:E[ce].maxBitrate,ae=this.getTimeToLoadFrag(oe,Q,Ee*ee,be===void 0);if(Q>=Ee&&(ce===d||fe.loadError===0&&fe.fragmentError===0)&&(ae<=oe||!Ae(ae)||M&&!this.bitrateTestDelay||ae<p)){const Le=this.forcedAutoLevel;return ce!==A&&(Le===-1||Le!==A)&&(Z.length&&W.trace(`[abr] Skipped level(s) ${Z.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${E[Z[0]].codecs}" ${E[Z[0]].videoRange}; not compatible with "${P.codecs}" ${N}`),W.info(`[abr] switch candidate:${g}->${ce} adjustedbw(${Math.round(Q)})-bitrate=${Math.round(Q-Ee)} ttfb:${oe.toFixed(1)} avgDuration:${ee.toFixed(1)} maxFetchDuration:${p.toFixed(1)} fetchDuration:${ae.toFixed(1)} firstSelection:${O} codecSet:${k} videoRange:${N} hls.loadLevel:${A}`)),O&&(this.firstSelection=ce),ce}}return-1}set nextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls,n=Math.min(Math.max(e,i),t);this._nextAutoLevel!==n&&(this.nextAutoLevelKey="",this._nextAutoLevel=n)}}class DE{constructor(){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(){}}var Et={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class xE{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(I.BUFFER_APPENDED,this.onBufferAppended,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this),e.on(I.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(I.BUFFER_APPENDED,this.onBufferAppended,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this),e.off(I.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let n=i.length;n--;){const r=i[n];if(!r)break;const o=r.end;if(r.start<=e&&o!==null&&e<=o)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:i}=this,n=Object.keys(i);for(let r=n.length;r--;){const o=i[n[r]];if(o?.body.type===t&&o.buffered){const u=o.body;if(u.start<=e&&e<=u.end)return u}}return null}detectEvictedFragments(e,t,i,n){this.timeRanges&&(this.timeRanges[e]=t);const r=n?.fragment.sn||-1;Object.keys(this.fragments).forEach(o=>{const u=this.fragments[o];if(!u||r>=u.body.sn)return;if(!u.buffered&&!u.loaded){u.body.type===i&&this.removeFragment(u.body);return}const h=u.range[e];h&&h.time.some(p=>{const d=!this.isTimeBuffered(p.startPTS,p.endPTS,t);return d&&this.removeFragment(u.body),d})})}detectPartialFragments(e){const t=this.timeRanges,{frag:i,part:n}=e;if(!t||i.sn==="initSegment")return;const r=Cs(i),o=this.fragments[r];if(!o||o.buffered&&i.gap)return;const u=!i.relurl;Object.keys(t).forEach(h=>{const p=i.elementaryStreams[h];if(!p)return;const d=t[h],g=u||p.partial===!0;o.range[h]=this.getBufferedTimes(i,n,g,d)}),o.loaded=null,Object.keys(o.range).length?(o.buffered=!0,(o.body.endList=i.endList||o.body.endList)&&(this.endListFragments[o.body.type]=o),Aa(o)||this.removeParts(i.sn-1,i.type)):this.removeFragment(o.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=i.filter(n=>n.fragment.sn>=e))}fragBuffered(e,t){const i=Cs(e);let n=this.fragments[i];!n&&t&&(n=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,n.buffered=!0)}getBufferedTimes(e,t,i,n){const r={time:[],partial:i},o=e.start,u=e.end,h=e.minEndPTS||u,p=e.maxStartPTS||o;for(let d=0;d<n.length;d++){const g=n.start(d)-this.bufferPadding,T=n.end(d)+this.bufferPadding;if(p>=g&&h<=T){r.time.push({startPTS:Math.max(o,n.start(d)),endPTS:Math.min(u,n.end(d))});break}else if(o<T&&u>g){const b=Math.max(o,n.start(d)),E=Math.min(u,n.end(d));E>b&&(r.partial=!0,r.time.push({startPTS:b,endPTS:E}))}else if(u<=g)break}return r}getPartialFragment(e){let t=null,i,n,r,o=0;const{bufferPadding:u,fragments:h}=this;return Object.keys(h).forEach(p=>{const d=h[p];d&&Aa(d)&&(n=d.body.start-u,r=d.body.end+u,e>=n&&e<=r&&(i=Math.min(e-n,r-e),o<=i&&(t=d.body,o=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Aa(t))}getState(e){const t=Cs(e),i=this.fragments[t];return i?i.buffered?Aa(i)?Et.PARTIAL:Et.OK:Et.APPENDING:Et.NOT_LOADED}isTimeBuffered(e,t,i){let n,r;for(let o=0;o<i.length;o++){if(n=i.start(o)-this.bufferPadding,r=i.end(o)+this.bufferPadding,e>=n&&t<=r)return!0;if(t<=n)return!1}return!1}onFragLoaded(e,t){const{frag:i,part:n}=t;if(i.sn==="initSegment"||i.bitrateTest)return;const r=n?null:t,o=Cs(i);this.fragments[o]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:n,timeRanges:r}=t;if(i.sn==="initSegment")return;const o=i.type;if(n){let u=this.activePartLists[o];u||(this.activePartLists[o]=u=[]),u.push(n)}this.timeRanges=r,Object.keys(r).forEach(u=>{const h=r[u];this.detectEvictedFragments(u,h,o,n)})}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Cs(e);return!!this.fragments[t]}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,n,r){n&&!this.hasGaps||Object.keys(this.fragments).forEach(o=>{const u=this.fragments[o];if(!u)return;const h=u.body;h.type!==i||n&&!h.gap||h.start<t&&h.end>e&&(u.buffered||r)&&this.removeFragment(h)})}removeFragment(e){const t=Cs(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const n=e.sn;this.activePartLists[e.type]=i.filter(r=>r.fragment.sn!==n)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function Aa(s){var e,t,i;return s.buffered&&(s.body.gap||((e=s.range.video)==null?void 0:e.partial)||((t=s.range.audio)==null?void 0:t.partial)||((i=s.range.audiovideo)==null?void 0:i.partial))}function Cs(s){return`${s.type}_${s.level}_${s.sn}`}const OE={length:0,start:()=>0,end:()=>0};class at{static isBuffered(e,t){try{if(e){const i=at.getBuffered(e);for(let n=0;n<i.length;n++)if(t>=i.start(n)&&t<=i.end(n))return!0}}catch{}return!1}static bufferInfo(e,t,i){try{if(e){const n=at.getBuffered(e),r=[];let o;for(o=0;o<n.length;o++)r.push({start:n.start(o),end:n.end(o)});return this.bufferedInfo(r,t,i)}}catch{}return{len:0,start:t,end:t,nextStart:void 0}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.sort(function(p,d){const g=p.start-d.start;return g||d.end-p.end});let n=[];if(i)for(let p=0;p<e.length;p++){const d=n.length;if(d){const g=n[d-1].end;e[p].start-g<i?e[p].end>g&&(n[d-1].end=e[p].end):n.push(e[p])}else n.push(e[p])}else n=e;let r=0,o,u=t,h=t;for(let p=0;p<n.length;p++){const d=n[p].start,g=n[p].end;if(t+i>=d&&t<g)u=d,h=g,r=h-t;else if(t+i<d){o=d;break}}return{len:r,start:u||0,end:h||0,nextStart:o}}static getBuffered(e){try{return e.buffered}catch(t){return W.log("failed to get media.buffered",t),OE}}}class Vc{constructor(e,t,i,n=0,r=-1,o=!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=La(),this.buffering={audio:La(),video:La(),audiovideo:La()},this.level=e,this.sn=t,this.id=i,this.size=n,this.part=r,this.partial=o}}function La(){return{start:0,executeStart:0,executeEnd:0,end:0}}function za(s,e){for(let i=0,n=s.length;i<n;i++){var t;if(((t=s[i])==null?void 0:t.cc)===e)return s[i]}return null}function ME(s,e,t){return!!(e&&(t.endCC>t.startCC||s&&s.cc<t.startCC))}function FE(s,e){const t=s.fragments,i=e.fragments;if(!i.length||!t.length){W.log("No fragments to align");return}const n=za(t,i[0].cc);if(!n||n&&!n.startPTS){W.log("No frag in previous level to align on");return}return n}function wf(s,e){if(s){const t=s.start+e;s.start=s.startPTS=t,s.endPTS=t+s.duration}}function tm(s,e){const t=e.fragments;for(let i=0,n=t.length;i<n;i++)wf(t[i],s);e.fragmentHint&&wf(e.fragmentHint,s),e.alignedSliding=!0}function NE(s,e,t){e&&(BE(s,t,e),!t.alignedSliding&&e&&To(t,e),!t.alignedSliding&&e&&!t.skippedSegments&&Xg(e,t))}function BE(s,e,t){if(ME(s,t,e)){const i=FE(t,e);i&&Ae(i.start)&&(W.log(`Adjusting PTS using last level due to CC increase within current level ${e.url}`),tm(i.start,e))}}function To(s,e){if(!s.hasProgramDateTime||!e.hasProgramDateTime)return;const t=s.fragments,i=e.fragments;if(!t.length||!i.length)return;let n,r;const o=Math.min(e.endCC,s.endCC);e.startCC<o&&s.startCC<o&&(n=za(i,o),r=za(t,o)),(!n||!r)&&(n=i[Math.floor(i.length/2)],r=za(t,n.cc)||t[Math.floor(t.length/2)]);const u=n.programDateTime,h=r.programDateTime;if(!u||!h)return;const p=(h-u)/1e3-(r.start-n.start);tm(p,s)}const Af=Math.pow(2,17);class UE{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const i=e.url;if(!i)return Promise.reject(new Wi({type:xe.NETWORK_ERROR,details:te.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const n=this.config,r=n.fLoader,o=n.loader;return new Promise((u,h)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(b=>b[0]==="GAP")){h(kf(e));return}else e.gap=!1;const p=this.loader=e.loader=r?new r(n):new o(n),d=Lf(e),g=Ef(n.fragLoadPolicy.default),T={loadPolicy:g,timeout:g.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Af};e.stats=p.stats,p.load(d,T,{onSuccess:(b,E,w,A)=>{this.resetLoader(e,p);let L=b.data;w.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(L.slice(0,16)),L=L.slice(16)),u({frag:e,part:null,payload:L,networkDetails:A})},onError:(b,E,w,A)=>{this.resetLoader(e,p),h(new Wi({type:xe.NETWORK_ERROR,details:te.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:St({url:i,data:void 0},b),error:new Error(`HTTP Error ${b.code} ${b.text}`),networkDetails:w,stats:A}))},onAbort:(b,E,w)=>{this.resetLoader(e,p),h(new Wi({type:xe.NETWORK_ERROR,details:te.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:w,stats:b}))},onTimeout:(b,E,w)=>{this.resetLoader(e,p),h(new Wi({type:xe.NETWORK_ERROR,details:te.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${T.timeout}ms`),networkDetails:w,stats:b}))},onProgress:(b,E,w,A)=>{t&&t({frag:e,part:null,payload:w,networkDetails:A})}})})}loadPart(e,t,i){this.abort();const n=this.config,r=n.fLoader,o=n.loader;return new Promise((u,h)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){h(kf(e,t));return}const p=this.loader=e.loader=r?new r(n):new o(n),d=Lf(e,t),g=Ef(n.fragLoadPolicy.default),T={loadPolicy:g,timeout:g.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Af};t.stats=p.stats,p.load(d,T,{onSuccess:(b,E,w,A)=>{this.resetLoader(e,p),this.updateStatsFromPart(e,t);const L={frag:e,part:t,payload:b.data,networkDetails:A};i(L),u(L)},onError:(b,E,w,A)=>{this.resetLoader(e,p),h(new Wi({type:xe.NETWORK_ERROR,details:te.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:St({url:d.url,data:void 0},b),error:new Error(`HTTP Error ${b.code} ${b.text}`),networkDetails:w,stats:A}))},onAbort:(b,E,w)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,p),h(new Wi({type:xe.NETWORK_ERROR,details:te.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:w,stats:b}))},onTimeout:(b,E,w)=>{this.resetLoader(e,p),h(new Wi({type:xe.NETWORK_ERROR,details:te.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${T.timeout}ms`),networkDetails:w,stats:b}))}})})}updateStatsFromPart(e,t){const i=e.stats,n=t.stats,r=n.total;if(i.loaded+=n.loaded,r){const h=Math.round(e.duration/t.duration),p=Math.min(Math.round(i.loaded/r),h),g=(h-p)*Math.round(i.loaded/p);i.total=i.loaded+g}else i.total=Math.max(i.loaded,i.total);const o=i.loading,u=n.loading;o.start?o.first+=u.first-u.start:(o.start=u.start,o.first=u.first),o.end=u.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Lf(s,e=null){const t=e||s,i={frag:s,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},n=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(Ae(n)&&Ae(r)){var o;let u=n,h=r;if(s.sn==="initSegment"&&((o=s.decryptdata)==null?void 0:o.method)==="AES-128"){const p=r-n;p%16&&(h=r+(16-p%16)),n!==0&&(i.resetIV=!0,u=n-16)}i.rangeStart=u,i.rangeEnd=h}return i}function kf(s,e){const t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:xe.MEDIA_ERROR,details:te.FRAG_GAP,fatal:!1,frag:s,error:t,networkDetails:null};return e&&(i.part=e),(e||s).stats.aborted=!0,new Wi(i)}class Wi extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class HE{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}}class $E{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}function jE(s){const e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?Zn(s,0,e-t):s}class VE{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(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let n=0;n<4;n++)i[n]=t.getUint32(n*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,n=i[0],r=i[1],o=i[2],u=i[3],h=this.invSubMix,p=h[0],d=h[1],g=h[2],T=h[3],b=new Uint32Array(256);let E=0,w=0,A=0;for(A=0;A<256;A++)A<128?b[A]=A<<1:b[A]=A<<1^283;for(A=0;A<256;A++){let L=w^w<<1^w<<2^w<<3^w<<4;L=L>>>8^L&255^99,e[E]=L,t[L]=E;const P=b[E],M=b[P],O=b[M];let k=b[L]*257^L*16843008;n[E]=k<<24|k>>>8,r[E]=k<<16|k>>>16,o[E]=k<<8|k>>>24,u[E]=k,k=O*16843009^M*65537^P*257^E*16843008,p[L]=k<<24|k>>>8,d[L]=k<<16|k>>>16,g[L]=k<<8|k>>>24,T[L]=k,E?(E=P^b[b[b[O^P]]],w^=b[b[w]]):E=w=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,n=0;for(;n<t.length&&i;)i=t[n]===this.key[n],n++;if(i)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const o=this.ksRows=(r+6+1)*4;let u,h;const p=this.keySchedule=new Uint32Array(o),d=this.invKeySchedule=new Uint32Array(o),g=this.sBox,T=this.rcon,b=this.invSubMix,E=b[0],w=b[1],A=b[2],L=b[3];let P,M;for(u=0;u<o;u++){if(u<r){P=p[u]=t[u];continue}M=P,u%r===0?(M=M<<8|M>>>24,M=g[M>>>24]<<24|g[M>>>16&255]<<16|g[M>>>8&255]<<8|g[M&255],M^=T[u/r|0]<<24):r>6&&u%r===4&&(M=g[M>>>24]<<24|g[M>>>16&255]<<16|g[M>>>8&255]<<8|g[M&255]),p[u]=P=(p[u-r]^M)>>>0}for(h=0;h<o;h++)u=o-h,h&3?M=p[u]:M=p[u-4],h<4||u<=4?d[h]=M:d[h]=E[g[M>>>24]]^w[g[M>>>16&255]]^A[g[M>>>8&255]]^L[g[M&255]],d[h]=d[h]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){const n=this.keySize+6,r=this.invKeySchedule,o=this.invSBox,u=this.invSubMix,h=u[0],p=u[1],d=u[2],g=u[3],T=this.uint8ArrayToUint32Array_(i);let b=T[0],E=T[1],w=T[2],A=T[3];const L=new Int32Array(e),P=new Int32Array(L.length);let M,O,k,N,H,G,B,D,K,oe,Z,le,ce,fe;const ve=this.networkToHostOrderSwap;for(;t<L.length;){for(K=ve(L[t]),oe=ve(L[t+1]),Z=ve(L[t+2]),le=ve(L[t+3]),H=K^r[0],G=le^r[1],B=Z^r[2],D=oe^r[3],ce=4,fe=1;fe<n;fe++)M=h[H>>>24]^p[G>>16&255]^d[B>>8&255]^g[D&255]^r[ce],O=h[G>>>24]^p[B>>16&255]^d[D>>8&255]^g[H&255]^r[ce+1],k=h[B>>>24]^p[D>>16&255]^d[H>>8&255]^g[G&255]^r[ce+2],N=h[D>>>24]^p[H>>16&255]^d[G>>8&255]^g[B&255]^r[ce+3],H=M,G=O,B=k,D=N,ce=ce+4;M=o[H>>>24]<<24^o[G>>16&255]<<16^o[B>>8&255]<<8^o[D&255]^r[ce],O=o[G>>>24]<<24^o[B>>16&255]<<16^o[D>>8&255]<<8^o[H&255]^r[ce+1],k=o[B>>>24]<<24^o[D>>16&255]<<16^o[H>>8&255]<<8^o[G&255]^r[ce+2],N=o[D>>>24]<<24^o[H>>16&255]<<16^o[G>>8&255]<<8^o[B&255]^r[ce+3],P[t]=ve(M^b),P[t+1]=ve(N^E),P[t+2]=ve(k^w),P[t+3]=ve(O^A),b=K,E=oe,w=Z,A=le,t=t+4}return P.buffer}}const GE=16;class Gc{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.useSoftware=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const i=self.crypto;i&&(this.subtle=i.subtle||i.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(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?jE(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i){return this.useSoftware?new Promise((n,r)=>{this.softwareDecrypt(new Uint8Array(e),t,i);const o=this.flush();o?n(o.buffer):r(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i)}softwareDecrypt(e,t,i){const{currentIV:n,currentResult:r,remainderData:o}=this;this.logOnce("JS AES decrypt"),o&&(e=si(o,e),this.remainderData=null);const u=this.getValidChunk(e);if(!u.length)return null;n&&(i=n);let h=this.softwareDecrypter;h||(h=this.softwareDecrypter=new VE),h.expandKey(t);const p=r;return this.currentResult=h.decrypt(u.buffer,0,i),this.currentIV=Zn(u,-16).buffer,p||null}webCryptoDecrypt(e,t,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i));this.key=t,this.fastAesKey=new $E(this.subtle,t)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new HE(this.subtle,new Uint8Array(i)).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(W.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,i)))}onWebCryptoError(e,t,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i);const n=this.flush();if(n)return n.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%GE;return i!==e.length&&(t=Zn(e,0,i),this.remainderData=Zn(e,i)),t}logOnce(e){this.logEnabled&&(W.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const KE={toString:function(s){let e="";const t=s.length;for(let i=0;i<t;i++)e+=`[${s.start(i).toFixed(3)}-${s.end(i).toFixed(3)}]`;return e}},de={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class Kc extends DE{constructor(e,t,i,n,r){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=de.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=r,this.logPrefix=n,this.log=W.log.bind(W,`${n}:`),this.warn=W.warn.bind(W,`${n}:`),this.hls=e,this.fragmentLoader=new UE(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Gc(e.config),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const 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=de.STOPPED}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}_streamEnded(e,t){if(t.live||e.nextStart||!e.end||!this.media)return!1;const i=t.partList;if(i!=null&&i.length){const r=i[i.length-1];return at.isBuffered(this.media,r.start+r.duration/2)}const n=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(n)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var e;return(e=this.levelLastLoaded)==null?void 0:e.details}}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),i.addEventListener("seeking",this.onvseeking),i.addEventListener("ended",this.onvended);const n=this.config;this.levels&&n.autoStartLoad&&this.state===de.STOPPED&&this.startLoad(n.startPosition)}onMediaDetaching(){const e=this.media;e!=null&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:e,fragCurrent:t,media:i,mediaBuffer:n,state:r}=this,o=i?i.currentTime:0,u=at.bufferInfo(n||i,o,e.maxBufferHole);if(this.log(`media seeking to ${Ae(o)?o.toFixed(3):o}, state: ${r}`),this.state===de.ENDED)this.resetLoadingState();else if(t){const h=e.maxFragLookUpTolerance,p=t.start-h,d=t.start+t.duration+h;if(!u.len||d<u.start||p>u.end){const g=o>d;(o<p||g)&&(g&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}i&&(this.fragmentTracker.removeFragmentsInRange(o,1/0,this.playlistType,!0),this.lastCurrentTime=o),!this.loadedmetadata&&!u.len&&(this.nextLoadPosition=this.startPosition=o),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.hls.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null}onHandlerDestroyed(){this.state=de.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){const n=r=>{if(this.fragContextChanged(e)){this.warn(`Fragment ${e.sn}${r.part?" p: "+r.part.index:""} of level ${e.level} was dropped during download.`),this.fragmentTracker.removeFragment(e);return}e.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,i,n).then(r=>{if(!r)return;const o=this.state;if(this.fragContextChanged(e)){(o===de.FRAG_LOADING||!this.fragCurrent&&o===de.PARSING)&&(this.fragmentTracker.removeFragment(e),this.state=de.IDLE);return}"payload"in r&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(I.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===de.STOPPED||this.state===de.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===Et.APPENDING){const r=e.type,o=this.getFwdBufferInfo(this.mediaBuffer,r),u=Math.max(e.duration,o?o.len:this.config.maxBufferLength),h=this.backtrackFragment;((h?e.sn-h.sn:0)===1||this.reduceMaxBufferLength(u,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===Et.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const 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)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:i};this.hls.trigger(I.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{if(!i||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:n}=this,{payload:r}=i,o=e.decryptdata;if(r&&r.byteLength>0&&o!=null&&o.key&&o.iv&&o.method==="AES-128"){const u=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),o.key.buffer,o.iv.buffer).catch(h=>{throw n.trigger(I.ERROR,{type:xe.MEDIA_ERROR,details:te.FRAG_DECRYPT_ERROR,fatal:!1,error:h,reason:h.message,frag:e}),h}).then(h=>{const p=self.performance.now();return n.trigger(I.FRAG_DECRYPTED,{frag:e,payload:h,stats:{tstart:u,tdecrypt:p}}),i.payload=h,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===de.STOPPED||this.state===de.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state=de.IDLE,e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){var i,n,r,o;const u=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===Pe.MAIN?"level":"track"} ${e.level} (frag:[${((i=e.startPTS)!=null?i:NaN).toFixed(3)}-${((n=e.endPTS)!=null?n:NaN).toFixed(3)}] > buffer:${u?KE.toString(at.getBuffered(u)):"(detached)"})`),e.sn!=="initSegment"){var h;if(e.type!==Pe.SUBTITLE){const d=e.elementaryStreams;if(!Object.keys(d).some(g=>!!d[g])){this.state=de.IDLE;return}}const p=(h=this.levels)==null?void 0:h[e.level];p!=null&&p.fragmentError&&(this.log(`Resetting level fragment error count of ${p.fragmentError} on frag buffered`),p.fragmentError=0)}this.state=de.IDLE,u&&(!this.loadedmetadata&&e.type==Pe.MAIN&&u.buffered.length&&((r=this.fragCurrent)==null?void 0:r.sn)===((o=this.fragPrevious)==null?void 0:o.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:n,partsLoaded:r}=e,o=!r||r.length===0||r.some(h=>!h),u=new Vc(i.level,i.sn,i.stats.chunkCount+1,0,n?n.index:-1,!o);t.flush(u)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,n){var r;const o=t?.details;if(!this.levels||!o)throw new Error(`frag load aborted, missing level${o?"":" detail"}s`);let u=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)?(this.log(`Loading key for ${e.sn} of [${o.startSN}-${o.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${e.level}`),this.state=de.KEY_LOADING,this.fragCurrent=e,u=this.keyLoader.load(e).then(d=>{if(!this.fragContextChanged(d.frag))return this.hls.trigger(I.KEY_LOADED,d),this.state===de.KEY_LOADING&&(this.state=de.IDLE),d}),this.hls.trigger(I.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(u=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&o.encryptedFragments.length&&this.keyLoader.loadClear(e,o.encryptedFragments),i=Math.max(e.start,i||0),this.config.lowLatencyMode&&e.sn!=="initSegment"){const d=o.partList;if(d&&n){i>e.end&&o.fragmentHint&&(e=o.fragmentHint);const g=this.getNextPart(d,e,i);if(g>-1){const T=d[g];this.log(`Loading part sn: ${e.sn} p: ${T.index} cc: ${e.cc} of playlist [${o.startSN}-${o.endSN}] parts [0-${g}-${d.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=T.start+T.duration,this.state=de.FRAG_LOADING;let b;return u?b=u.then(E=>!E||this.fragContextChanged(E.frag)?null:this.doFragPartsLoad(e,T,t,n)).catch(E=>this.handleFragLoadError(E)):b=this.doFragPartsLoad(e,T,t,n).catch(E=>this.handleFragLoadError(E)),this.hls.trigger(I.FRAG_LOADING,{frag:e,part:T,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):b}else if(!e.url||this.loadedEndOfParts(d,i))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${o?"of ["+o.startSN+"-"+o.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),Ae(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=de.FRAG_LOADING;const h=this.config.progressive;let p;return h&&u?p=u.then(d=>!d||this.fragContextChanged(d?.frag)?null:this.fragmentLoader.load(e,n)).catch(d=>this.handleFragLoadError(d)):p=Promise.all([this.fragmentLoader.load(e,h?n:void 0),u]).then(([d])=>(!h&&d&&n&&n(d),d)).catch(d=>this.handleFragLoadError(d)),this.hls.trigger(I.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):p}doFragPartsLoad(e,t,i,n){return new Promise((r,o)=>{var u;const h=[],p=(u=i.details)==null?void 0:u.partList,d=g=>{this.fragmentLoader.loadPart(e,g,n).then(T=>{h[g.index]=T;const b=T.part;this.hls.trigger(I.FRAG_LOADED,T);const E=bf(i,e.sn,g.index+1)||Qg(p,e.sn,g.index+1);if(E)d(E);else return r({frag:e,part:b,partsLoaded:h})}).catch(o)};d(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===te.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(I.ERROR,t)}else this.hls.trigger(I.ERROR,{type:xe.OTHER_ERROR,details:te.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==de.PARSING){!this.fragCurrent&&this.state!==de.STOPPED&&this.state!==de.ERROR&&(this.state=de.IDLE);return}const{frag:i,part:n,level:r}=t,o=self.performance.now();i.stats.parsing.end=o,n&&(n.stats.parsing.end=o),this.updateLevelTiming(i,n,r,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:n,sn:r,part:o}=e;if(!(t!=null&&t[n]))return this.warn(`Levels object was unset while buffering fragment ${r} of level ${n}. The current chunk will not be buffered.`),null;const u=t[n],h=o>-1?bf(u,r,o):null,p=h?h.fragment:fE(u,r,i);return p?(i&&i!==p&&(p.stats=i.stats),{frag:p,part:h,level:u}):null}bufferFragmentData(e,t,i,n,r){var o;if(!e||this.state!==de.PARSING)return;const{data1:u,data2:h}=e;let p=u;if(u&&h&&(p=si(u,h)),!((o=p)!=null&&o.length))return;const d={type:e.type,frag:t,part:i,chunkMeta:n,parent:t.type,data:p};if(this.hls.trigger(I.BUFFER_APPENDING,d),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!at.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,n=at.bufferInfo(t,i,0),r=e.duration,o=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),u=Math.max(Math.min(e.start-o,n.end-o),i+o);e.start-u>o&&this.flushMainBuffer(u,e.start)}getFwdBufferInfo(e,t){const i=this.getLoadPosition();return Ae(i)?this.getFwdBufferInfoAtPos(e,i,t):null}getFwdBufferInfoAtPos(e,t,i){const{config:{maxBufferHole:n}}=this,r=at.bufferInfo(e,t,n);if(r.len===0&&r.nextStart!==void 0){const o=this.fragmentTracker.getBufferedFrag(t,i);if(o&&r.nextStart<o.end)return at.bufferInfo(e,t,Math.max(r.nextStart,n))}return r}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const i=this.config,n=Math.max(Math.min(e-t,i.maxBufferLength),t),r=Math.max(e-t*3,i.maxMaxBufferLength/2,n);return r>=n?(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=Pe.MAIN){const i=this.fragmentTracker.getAppendedFrag(e,Pe.MAIN);return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,n=i.length;if(!n)return null;const{config:r}=this,o=i[0].start;let u;if(t.live){const h=r.initialLiveManifestSize;if(n<h)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${h})`),null;(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<o)&&(u=this.getInitialLiveFragment(t,i),this.startPosition=this.nextLoadPosition=u?this.hls.liveSyncPosition||u.start:e)}else e<=o&&(u=i[0]);if(!u){const h=r.lowLatencyMode?t.partEnd:t.fragmentEnd;u=this.getFragmentAtPosition(e,h,t)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===Et.OK||i===Et.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,n,r){const o=e.gap,u=this.getNextFragment(this.nextLoadPosition,t);if(u===null)return u;if(e=u,o&&e&&!e.gap&&i.nextStart){const h=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,n);if(h!==null&&i.len+h.len>=r)return this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let n=-1,r=!1,o=!0;for(let u=0,h=e.length;u<h;u++){const p=e[u];if(o=o&&!p.independent,n>-1&&i<p.start)break;const d=p.loaded;d?n=-1:(r||p.independent||o)&&p.fragment===t&&(n=u),r=d}return n}loadedEndOfParts(e,t){const i=e[e.length-1];return i&&t>i.start&&i.loaded}getInitialLiveFragment(e,t){const i=this.fragPrevious;let n=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),n=gE(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){const o=t[r-e.startSN];i.cc===o.cc&&(n=o,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=vE(t,i.cc),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(n=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,i){const{config:n}=this;let{fragPrevious:r}=this,{fragments:o,endSN:u}=i;const{fragmentHint:h}=i,{maxFragLookUpTolerance:p}=n,d=i.partList,g=!!(n.lowLatencyMode&&d!=null&&d.length&&h);g&&h&&!this.bitrateTest&&(o=o.concat(h),u=h.sn);let T;if(e<t){const b=e>t-p?0:p;T=vo(r,o,e,b)}else T=o[o.length-1];if(T){const b=T.sn-i.startSN,E=this.fragmentTracker.getState(T);if((E===Et.OK||E===Et.PARTIAL&&T.gap)&&(r=T),r&&T.sn===r.sn&&(!g||d[0].fragment.sn>T.sn)&&r&&T.level===r.level){const A=o[b+1];T.sn<u&&this.fragmentTracker.getState(A)!==Et.OK?T=A:T=null}}return T}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const n=this.hls.liveSyncPosition,r=i.currentTime,o=e.fragments[0].start,u=e.edge,h=r>=o-t.maxFragLookUpTolerance&&r<=u;if(n!==null&&i.duration>n&&(r<n||!h)){const p=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!h&&i.readyState<4||r<u-p)&&(this.loadedmetadata||(this.nextLoadPosition=n),i.readyState&&(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${u}, reset currentTime to : ${n.toFixed(3)}`),i.currentTime=n))}}alignPlaylists(e,t,i){const n=e.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;const r=e.fragments[0].start,o=!t,u=e.alignedSliding&&Ae(r);if(o||!u&&!r){const{fragPrevious:h}=this;NE(h,i,e);const p=e.fragments[0].start;return this.log(`Live playlist sliding: ${p.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} prev-sn: ${h?h.sn:"na"} fragments: ${n}`),p}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;if(i<t&&(i=-1),i===-1||this.lastCurrentTime===-1){const n=this.startTimeOffset!==null,r=n?this.startTimeOffset:e.startTimeOffset;r!==null&&Ae(r)?(i=t+r,r<0&&(i+=e.totalduration),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Start time offset ${r} found in ${n?"multivariant":"media"} playlist, adjust startPosition to ${i}`),this.startPosition=i):e.live?i=this.hls.liveSyncPosition||t:this.startPosition=i=0,this.lastCurrentTime=i}this.nextLoadPosition=i}getLoadPosition(){const{media:e}=this;let t=0;return this.loadedmetadata&&e?t=e.currentTime:this.nextLoadPosition&&(t=this.nextLoadPosition),t}handleFragLoadAborted(e,t){this.transmuxer&&e.sn!=="initSegment"&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==de.FRAG_LOADING_WAITING_RETRY)&&(this.state=de.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const d=this.getCurrentContext(t.chunkMeta);d&&(t.frag=d.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var n;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}const r=t.details===te.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(i,!0);const o=t.errorAction,{action:u,retryCount:h=0,retryConfig:p}=o||{};if(o&&u===Lt.RetryRequest&&p){this.resetStartWhenNotLoaded(this.levelLastLoaded);const d=$c(p,h);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${h+1}/${p.maxNumRetry} in ${d}ms`),o.resolved=!0,this.retryDate=self.performance.now()+d,this.state=de.FRAG_LOADING_WAITING_RETRY}else if(p&&o)if(this.resetFragmentErrors(e),h<p.maxNumRetry)!r&&u!==Lt.RemoveAlternatePermanently&&(o.resolved=!0);else{W.warn(`${t.details} reached or exceeded max retry (${h})`);return}else o?.action===Lt.SendAlternateToPenaltyBox?this.state=de.WAITING_LEVEL:this.state=de.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===de.PARSING||this.state===de.PARSED){const t=e.frag,i=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,i),r=n&&n.len>.5;r&&this.reduceMaxBufferLength(n.len,t?.duration||10);const o=!r;return o&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),o}return!1}resetFragmentErrors(e){e===Pe.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==de.STOPPED&&(this.state=de.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const n=at.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,i),this.state===de.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=de.IDLE}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=e?e.details:null;t!=null&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,n){var r;const o=i.details;if(!o){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((h,p)=>{const d=e.elementaryStreams[p];if(d){const g=d.endPTS-d.startPTS;if(g<=0)return this.warn(`Could not parse fragment ${e.sn} ${p} duration reliably (${g})`),h||!1;const T=n?0:Yg(o,e,d.startPTS,d.endPTS,d.startDTS,d.endDTS);return this.hls.trigger(I.LEVEL_PTS_UPDATED,{details:o,level:i,drift:T,type:p,frag:e,start:d.startPTS,end:d.endPTS}),!0}return h},!1)&&((r=this.transmuxer)==null?void 0:r.error)===null){const h=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(i.fragmentError===0&&(i.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(h.message),this.hls.trigger(I.ERROR,{type:xe.MEDIA_ERROR,details:te.FRAG_PARSING_ERROR,fatal:!1,error:h,frag:e,reason:`Found no media in msn ${e.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=de.PARSED,this.hls.trigger(I.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}class im{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=qE(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function qE(s,e){const t=new Uint8Array(e);let i=0;for(let n=0;n<s.length;n++){const r=s[n];t.set(r,i),i+=r.length}return t}function WE(){return typeof __HLS_WORKER_BUNDLE__=="function"}function zE(){const s=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(s);return{worker:new self.Worker(e),objectURL:e}}function YE(s){const e=new self.URL(s,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}function Ii(s="",e=9e4){return{type:s,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class qc{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,n){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=si(this.cachedData,e),this.cachedData=null);let i=kr(e,0),n=i?i.length:0,r;const o=this._audioTrack,u=this._id3Track,h=i?Hc(i):void 0,p=e.length;for((this.basePTS===null||this.frameIndex===0&&Ae(h))&&(this.basePTS=XE(h,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&u.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:pi.audioId3,duration:Number.POSITIVE_INFINITY});n<p;){if(this.canParse(e,n)){const d=this.appendFrame(o,e,n);d?(this.frameIndex++,this.lastPTS=d.sample.pts,n+=d.length,r=n):n=p}else y_(e,n)?(i=kr(e,n),u.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:pi.audioId3,duration:Number.POSITIVE_INFINITY}),n+=i.length,r=n):n++;if(n===p&&r!==p){const d=Zn(e,r);this.cachedData?this.cachedData=si(this.cachedData,d):this.cachedData=d}}return{audioTrack:o,videoTrack:Ii(),id3Track:u,textTrack:Ii()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Ii(),id3Track:this._id3Track,textTrack:Ii()}}destroy(){}}const XE=(s,e,t)=>{if(Ae(s))return s*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};function QE(s,e,t,i){let n,r,o,u;const h=navigator.userAgent.toLowerCase(),p=i,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];n=((e[t+2]&192)>>>6)+1;const g=(e[t+2]&60)>>>2;if(g>d.length-1){const T=new Error(`invalid ADTS sampling index:${g}`);s.emit(I.ERROR,I.ERROR,{type:xe.MEDIA_ERROR,details:te.FRAG_PARSING_ERROR,fatal:!0,error:T,reason:T.message});return}return o=(e[t+2]&1)<<2,o|=(e[t+3]&192)>>>6,W.log(`manifest codec:${i}, ADTS type:${n}, samplingIndex:${g}`),/firefox/i.test(h)?g>=6?(n=5,u=new Array(4),r=g-3):(n=2,u=new Array(2),r=g):h.indexOf("android")!==-1?(n=2,u=new Array(2),r=g):(n=5,u=new Array(4),i&&(i.indexOf("mp4a.40.29")!==-1||i.indexOf("mp4a.40.5")!==-1)||!i&&g>=6?r=g-3:((i&&i.indexOf("mp4a.40.2")!==-1&&(g>=6&&o===1||/vivaldi/i.test(h))||!i&&o===1)&&(n=2,u=new Array(2)),r=g)),u[0]=n<<3,u[0]|=(g&14)>>1,u[1]|=(g&1)<<7,u[1]|=o<<3,n===5&&(u[1]|=(r&14)>>1,u[2]=(r&1)<<7,u[2]|=8,u[3]=0),{config:u,samplerate:d[g],channelCount:o,codec:"mp4a.40."+n,manifestCodec:p}}function nm(s,e){return s[e]===255&&(s[e+1]&246)===240}function sm(s,e){return s[e+1]&1?7:9}function Wc(s,e){return(s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function JE(s,e){return e+5<s.length}function bo(s,e){return e+1<s.length&&nm(s,e)}function ZE(s,e){return JE(s,e)&&nm(s,e)&&Wc(s,e)<=s.length-e}function eS(s,e){if(bo(s,e)){const t=sm(s,e);if(e+t>=s.length)return!1;const i=Wc(s,e);if(i<=t)return!1;const n=e+i;return n===s.length||bo(s,n)}return!1}function rm(s,e,t,i,n){if(!s.samplerate){const r=QE(e,t,i,n);if(!r)return;s.config=r.config,s.samplerate=r.samplerate,s.channelCount=r.channelCount,s.codec=r.codec,s.manifestCodec=r.manifestCodec,W.log(`parsed codec:${s.codec}, rate:${r.samplerate}, channels:${r.channelCount}`)}}function am(s){return 1024*9e4/s}function tS(s,e){const t=sm(s,e);if(e+t<=s.length){const i=Wc(s,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function om(s,e,t,i,n){const r=am(s.samplerate),o=i+n*r,u=tS(e,t);let h;if(u){const{frameLength:g,headerLength:T}=u,b=T+g,E=Math.max(0,t+b-e.length);E?(h=new Uint8Array(b-T),h.set(e.subarray(t+T,e.length),0)):h=e.subarray(t+T,t+b);const w={unit:h,pts:o};return E||s.samples.push(w),{sample:w,length:b,missing:E}}const p=e.length-t;return h=new Uint8Array(p),h.set(e.subarray(t,e.length),0),{sample:{unit:h,pts:o},length:p,missing:-1}}let ka=null;const iS=[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],nS=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],sS=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],rS=[0,1,1,4];function lm(s,e,t,i,n){if(t+24>e.length)return;const r=um(e,t);if(r&&t+r.frameLength<=e.length){const o=r.samplesPerFrame*9e4/r.sampleRate,u=i+n*o,h={unit:e.subarray(t,t+r.frameLength),pts:u,dts:u};return s.config=[],s.channelCount=r.channelCount,s.samplerate=r.sampleRate,s.samples.push(h),{sample:h,length:r.frameLength,missing:0}}}function um(s,e){const t=s[e+1]>>3&3,i=s[e+1]>>1&3,n=s[e+2]>>4&15,r=s[e+2]>>2&3;if(t!==1&&n!==0&&n!==15&&r!==3){const o=s[e+2]>>1&1,u=s[e+3]>>6,h=t===3?3-i:i===3?3:4,p=iS[h*14+n-1]*1e3,g=nS[(t===3?0:t===2?1:2)*3+r],T=u===3?1:2,b=sS[t][i],E=rS[i],w=b*8*E,A=Math.floor(b*p/g+o)*E;if(ka===null){const M=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ka=M?parseInt(M[1]):0}return!!ka&&ka<=87&&i===2&&p>=224e3&&u===0&&(s[e+3]=s[e+3]|128),{sampleRate:g,channelCount:T,frameLength:A,samplesPerFrame:w}}}function zc(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function cm(s,e){return e+1<s.length&&zc(s,e)}function aS(s,e){return zc(s,e)&&4<=s.length-e}function hm(s,e){if(e+1<s.length&&zc(s,e)){const i=um(s,e);let n=4;i!=null&&i.frameLength&&(n=i.frameLength);const r=e+n;return r===s.length||cm(s,r)}return!1}class oS extends qc{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=kr(e,0);let i=t?.length||0;if(hm(e,i))return!1;for(let n=e.length;i<n;i++)if(eS(e,i))return W.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return ZE(e,t)}appendFrame(e,t,i){rm(e,this.observer,t,i,e.manifestCodec);const n=om(e,t,i,this.basePTS,this.frameIndex);if(n&&n.missing===0)return n}}const lS=/\/emsg[-/]ID3/i;class uS{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,n){const r=this.videoTrack=Ii("video",1),o=this.audioTrack=Ii("audio",1),u=this.txtTrack=Ii("text",1);if(this.id3Track=Ii("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const h=$g(e);if(h.video){const{id:p,timescale:d,codec:g}=h.video;r.id=p,r.timescale=u.timescale=d,r.codec=g}if(h.audio){const{id:p,timescale:d,codec:g}=h.audio;o.id=p,o.timescale=d,o.codec=g}u.id=Bg.text,r.sampleDuration=0,r.duration=o.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return A_(e)}demux(e,t){this.timeOffset=t;let i=e;const n=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=si(this.remainderData,e));const u=O_(i);this.remainderData=u.remainder,n.samples=u.valid||new Uint8Array}else n.samples=i;const o=this.extractID3Track(n,t);return r.samples=ef(t,n),{videoTrack:n,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(t,this.timeOffset);return i.samples=ef(e,t),{videoTrack:t,audioTrack:Ii(),id3Track:n,textTrack:Ii()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const n=Ne(e.samples,["emsg"]);n&&n.forEach(r=>{const o=N_(r);if(lS.test(o.schemeIdUri)){const u=Ae(o.presentationTime)?o.presentationTime/o.timeScale:t+o.presentationTimeDelta/o.timeScale;let h=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;h<=.001&&(h=Number.POSITIVE_INFINITY);const p=o.payload;i.samples.push({data:p,len:p.byteLength,dts:u,pts:u,type:pi.emsg,duration:h})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}const dm=(s,e)=>{let t=0,i=5;e+=i;const n=new Uint32Array(1),r=new Uint32Array(1),o=new Uint8Array(1);for(;i>0;){o[0]=s[e];const u=Math.min(i,8),h=8-u;r[0]=4278190080>>>24+h<<h,n[0]=(o[0]&r[0])>>h,t=t?t<<u|n[0]:n[0],e+=1,i-=u}return t};class cS extends qc{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){const n=fm(e,t,i,this.basePTS,this.frameIndex);if(n!==-1)return{sample:e.samples[e.samples.length-1],length:n,missing:0}}static probe(e){if(!e)return!1;const t=kr(e,0);if(!t)return!1;const i=t.length;return e[i]===11&&e[i+1]===119&&Hc(t)!==void 0&&dm(e,i)<16}}function fm(s,e,t,i,n){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const u=[48e3,44100,32e3][r],h=e[t+4]&63,d=[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][h*3+r]*2;if(t+d>e.length)return-1;const g=e[t+6]>>5;let T=0;g===2?T+=2:(g&1&&g!==1&&(T+=2),g&4&&(T+=2));const b=(e[t+6]<<8|e[t+7])>>12-T&1,w=[2,1,2,3,3,4,4,5][g]+b,A=e[t+5]>>3,L=e[t+5]&7,P=new Uint8Array([r<<6|A<<1|L>>2,(L&3)<<6|g<<3|b<<2|h>>4,h<<4&224]),M=1536/u*9e4,O=i+n*M,k=e.subarray(t,t+d);return s.config=P,s.channelCount=w,s.samplerate=u,s.samples.push({unit:k,pts:O}),d}class hS{constructor(){this.VideoSample=null}createVideoSample(e,t,i,n){return{key:e,frame:!1,pts:t,dts:i,units:[],debug:n,length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,n;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const r=i.units;n=r[r.length-1]}return n}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,n=i.length;if(n){const r=i[n-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}e.debug.length&&W.log(e.pts+"/"+e.dts+":"+e.debug)}}class If{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(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,n=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");n.set(e.subarray(i,i+r)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}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);const i=this.word>>>32-t;if(e>32&&W.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 new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>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(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const 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)}skipScalingList(e){let t=8,i=8,n;for(let r=0;r<e;r++)i!==0&&(n=this.readEG(),i=(t+n+256)%256),t=i===0?t:i}readSPS(){let e=0,t=0,i=0,n=0,r,o,u;const h=this.readUByte.bind(this),p=this.readBits.bind(this),d=this.readUEG.bind(this),g=this.readBoolean.bind(this),T=this.skipBits.bind(this),b=this.skipEG.bind(this),E=this.skipUEG.bind(this),w=this.skipScalingList.bind(this);h();const A=h();if(p(5),T(3),h(),E(),A===100||A===110||A===122||A===244||A===44||A===83||A===86||A===118||A===128){const N=d();if(N===3&&T(1),E(),E(),T(1),g())for(o=N!==3?8:12,u=0;u<o;u++)g()&&(u<6?w(16):w(64))}E();const L=d();if(L===0)d();else if(L===1)for(T(1),b(),b(),r=d(),u=0;u<r;u++)b();E(),T(1);const P=d(),M=d(),O=p(1);O===0&&T(1),T(1),g()&&(e=d(),t=d(),i=d(),n=d());let k=[1,1];if(g()&&g())switch(h()){case 1:k=[1,1];break;case 2:k=[12,11];break;case 3:k=[10,11];break;case 4:k=[16,11];break;case 5:k=[40,33];break;case 6:k=[24,11];break;case 7:k=[20,11];break;case 8:k=[32,11];break;case 9:k=[80,33];break;case 10:k=[18,11];break;case 11:k=[15,11];break;case 12:k=[64,33];break;case 13:k=[160,99];break;case 14:k=[4,3];break;case 15:k=[3,2];break;case 16:k=[2,1];break;case 255:{k=[h()<<8|h(),h()<<8|h()];break}}return{width:Math.ceil((P+1)*16-e*2-t*2),height:(2-O)*(M+1)*16-(O?2:4)*(i+n),pixelRatio:k}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class dS extends hS{parseAVCPES(e,t,i,n,r){const o=this.parseAVCNALu(e,i.data);let u=this.VideoSample,h,p=!1;i.data=null,u&&o.length&&!e.audFound&&(this.pushAccessUnit(u,e),u=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"")),o.forEach(d=>{var g;switch(d.type){case 1:{let w=!1;h=!0;const A=d.data;if(p&&A.length>4){const L=new If(A).readSliceType();(L===2||L===4||L===7||L===9)&&(w=!0)}if(w){var T;(T=u)!=null&&T.frame&&!u.key&&(this.pushAccessUnit(u,e),u=this.VideoSample=null)}u||(u=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),u.frame=!0,u.key=w;break}case 5:h=!0,(g=u)!=null&&g.frame&&!u.key&&(this.pushAccessUnit(u,e),u=this.VideoSample=null),u||(u=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),u.key=!0,u.frame=!0;break;case 6:{h=!0,Vg(d.data,1,i.pts,t.samples);break}case 7:{var b,E;h=!0,p=!0;const w=d.data,L=new If(w).readSPS();if(!e.sps||e.width!==L.width||e.height!==L.height||((b=e.pixelRatio)==null?void 0:b[0])!==L.pixelRatio[0]||((E=e.pixelRatio)==null?void 0:E[1])!==L.pixelRatio[1]){e.width=L.width,e.height=L.height,e.pixelRatio=L.pixelRatio,e.sps=[w],e.duration=r;const P=w.subarray(1,4);let M="avc1.";for(let O=0;O<3;O++){let k=P[O].toString(16);k.length<2&&(k="0"+k),M+=k}e.codec=M}break}case 8:h=!0,e.pps=[d.data];break;case 9:h=!0,e.audFound=!0,u&&this.pushAccessUnit(u,e),u=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"");break;case 12:h=!0;break;default:h=!1,u&&(u.debug+="unknown NAL "+d.type+" ");break}u&&h&&u.units.push(d)}),n&&u&&(this.pushAccessUnit(u,e),this.VideoSample=null)}parseAVCNALu(e,t){const i=t.byteLength;let n=e.naluState||0;const r=n,o=[];let u=0,h,p,d,g=-1,T=0;for(n===-1&&(g=0,T=t[0]&31,n=0,u=1);u<i;){if(h=t[u++],!n){n=h?0:1;continue}if(n===1){n=h?0:2;continue}if(!h)n=3;else if(h===1){if(p=u-n-1,g>=0){const b={data:t.subarray(g,p),type:T};o.push(b)}else{const b=this.getLastNalUnit(e.samples);b&&(r&&u<=4-r&&b.state&&(b.data=b.data.subarray(0,b.data.byteLength-r)),p>0&&(b.data=si(b.data,t.subarray(0,p)),b.state=0))}u<i?(d=t[u]&31,g=u,T=d,n=0):n=-1}else n=0}if(g>=0&&n>=0){const b={data:t.subarray(g,i),type:T,state:n};o.push(b)}if(o.length===0){const b=this.getLastNalUnit(e.samples);b&&(b.data=si(b.data,t))}return e.naluState=n,o}}class fS{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Gc(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,i){const n=e[t].unit;if(n.length<=16)return;const r=n.subarray(16,n.length-n.length%16),o=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(o).then(u=>{const h=new Uint8Array(u);n.set(h,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)})}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let n=0;for(let r=32;r<e.length-16;r+=160,n+=16)i.set(e.subarray(r,r+16),n);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let n=0;for(let r=32;r<e.length-16;r+=160,n+=16)e.set(i.subarray(n,n+16),r);return e}decryptAvcSample(e,t,i,n,r){const o=Gg(r.data),u=this.getAvcEncryptedData(o);this.decryptBuffer(u.buffer).then(h=>{r.data=this.getAvcDecryptedUnit(o,h),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,n)})}decryptAvcSamples(e,t,i,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){n();return}const r=e[t].units;for(;!(i>=r.length);i++){const o=r[i];if(!(o.data.length<=48||o.type!==1&&o.type!==5)&&(this.decryptAvcSample(e,t,i,n,o),!this.decrypter.isSync()))return}}}}const _t=188;class Tn{constructor(e,t,i){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._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=i,this.videoParser=new dS}static probe(e){const t=Tn.syncOffset(e);return t>0&&W.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),t!==-1}static syncOffset(e){const t=e.length;let i=Math.min(_t*5,t-_t)+1,n=0;for(;n<i;){let r=!1,o=-1,u=0;for(let h=n;h<t;h+=_t)if(e[h]===71&&(t-h===_t||e[h+_t]===71)){if(u++,o===-1&&(o=h,o!==0&&(i=Math.min(o+_t*99,e.length-_t)+1)),r||(r=lc(e,h)===0),r&&u>1&&(o===0&&u>2||h+_t>i))return o}else{if(u)return-1;break}n++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Bg[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Tn.createTrack("video"),this._audioTrack=Tn.createTrack("audio",n),this._id3Track=Tn.createTrack("id3"),this._txtTrack=Tn.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,this._duration=n}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,n=!1){i||(this.sampleAes=null);let r;const o=this._videoTrack,u=this._audioTrack,h=this._id3Track,p=this._txtTrack;let d=o.pid,g=o.pesData,T=u.pid,b=h.pid,E=u.pesData,w=h.pesData,A=null,L=this.pmtParsed,P=this._pmtId,M=e.length;if(this.remainderData&&(e=si(this.remainderData,e),M=e.length,this.remainderData=null),M<_t&&!n)return this.remainderData=e,{audioTrack:u,videoTrack:o,id3Track:h,textTrack:p};const O=Math.max(0,Tn.syncOffset(e));M-=(M-O)%_t,M<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,M,e.buffer.byteLength-M));let k=0;for(let H=O;H<M;H+=_t)if(e[H]===71){const G=!!(e[H+1]&64),B=lc(e,H),D=(e[H+3]&48)>>4;let K;if(D>1){if(K=H+5+e[H+4],K===H+_t)continue}else K=H+4;switch(B){case d:G&&(g&&(r=ws(g))&&this.videoParser.parseAVCPES(o,p,r,!1,this._duration),g={data:[],size:0}),g&&(g.data.push(e.subarray(K,H+_t)),g.size+=H+_t-K);break;case T:if(G){if(E&&(r=ws(E)))switch(u.segmentCodec){case"aac":this.parseAACPES(u,r);break;case"mp3":this.parseMPEGPES(u,r);break;case"ac3":this.parseAC3PES(u,r);break}E={data:[],size:0}}E&&(E.data.push(e.subarray(K,H+_t)),E.size+=H+_t-K);break;case b:G&&(w&&(r=ws(w))&&this.parseID3PES(h,r),w={data:[],size:0}),w&&(w.data.push(e.subarray(K,H+_t)),w.size+=H+_t-K);break;case 0:G&&(K+=e[K]+1),P=this._pmtId=pS(e,K);break;case P:{G&&(K+=e[K]+1);const oe=gS(e,K,this.typeSupported,i,this.observer);d=oe.videoPid,d>0&&(o.pid=d,o.segmentCodec=oe.segmentVideoCodec),T=oe.audioPid,T>0&&(u.pid=T,u.segmentCodec=oe.segmentAudioCodec),b=oe.id3Pid,b>0&&(h.pid=b),A!==null&&!L&&(W.warn(`MPEG-TS PMT found at ${H} after unknown PID '${A}'. Backtracking to sync byte @${O} to parse all TS packets.`),A=null,H=O-188),L=this.pmtParsed=!0;break}case 17:case 8191:break;default:A=B;break}}else k++;k>0&&_o(this.observer,new Error(`Found ${k} TS packet/s that do not start with 0x47`)),o.pesData=g,u.pesData=E,h.pesData=w;const N={audioTrack:u,videoTrack:o,id3Track:h,textTrack:p};return n&&this.extractRemainingSamples(N),N}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={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){const{audioTrack:t,videoTrack:i,id3Track:n,textTrack:r}=e,o=i.pesData,u=t.pesData,h=n.pesData;let p;if(o&&(p=ws(o))?(this.videoParser.parseAVCPES(i,r,p,!0,this._duration),i.pesData=null):i.pesData=o,u&&(p=ws(u))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,p);break;case"mp3":this.parseMPEGPES(t,p);break;case"ac3":this.parseAC3PES(t,p);break}t.pesData=null}else u!=null&&u.size&&W.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=u;h&&(p=ws(h))?(this.parseID3PES(n,p),n.pesData=null):n.pesData=h}demuxSampleAes(e,t,i){const n=this.demux(e,i,!0,!this.config.progressive),r=this.sampleAes=new fS(this.observer,this.config,t);return this.decrypt(n,r)}decrypt(e,t){return new Promise(i=>{const{audioTrack:n,videoTrack:r}=e;n.samples&&n.segmentCodec==="aac"?t.decryptAacSamples(n.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{i(e)}):i(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{i(e)})})}destroy(){this._duration=0}parseAACPES(e,t){let i=0;const n=this.aacOverFlow;let r=t.data;if(n){this.aacOverFlow=null;const g=n.missing,T=n.sample.unit.byteLength;if(g===-1)r=si(n.sample.unit,r);else{const b=T-g;n.sample.unit.set(r.subarray(0,g),b),e.samples.push(n.sample),i=n.missing}}let o,u;for(o=i,u=r.length;o<u-1&&!bo(r,o);o++);if(o!==i){let g;const T=o<u-1;if(T?g=`AAC PES did not start with ADTS header,offset:${o}`:g="No ADTS header found in AAC PES",_o(this.observer,new Error(g),T),!T)return}rm(e,this.observer,r,o,this.audioCodec);let h;if(t.pts!==void 0)h=t.pts;else if(n){const g=am(e.samplerate);h=n.sample.pts+g}else{W.warn("[tsdemuxer]: AAC PES unknown PTS");return}let p=0,d;for(;o<u;)if(d=om(e,r,o,h,p),o+=d.length,d.missing){this.aacOverFlow=d;break}else for(p++;o<u-1&&!bo(r,o);o++);}parseMPEGPES(e,t){const i=t.data,n=i.length;let r=0,o=0;const u=t.pts;if(u===void 0){W.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;o<n;)if(cm(i,o)){const h=lm(e,i,o,u,r);if(h)o+=h.length,r++;else break}else o++}parseAC3PES(e,t){{const i=t.data,n=t.pts;if(n===void 0){W.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=i.length;let o=0,u=0,h;for(;u<r&&(h=fm(e,i,u,n,o++))>0;)u+=h}}parseID3PES(e,t){if(t.pts===void 0){W.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=vt({},t,{type:this._videoTrack?pi.emsg:pi.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function lc(s,e){return((s[e+1]&31)<<8)+s[e+2]}function pS(s,e){return(s[e+10]&31)<<8|s[e+11]}function gS(s,e,t,i,n){const r={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(s[e+1]&15)<<8|s[e+2],u=e+3+o-4,h=(s[e+10]&15)<<8|s[e+11];for(e+=12+h;e<u;){const p=lc(s,e),d=(s[e+3]&15)<<8|s[e+4];switch(s[e]){case 207:if(!i){gu("ADTS AAC");break}case 15:r.audioPid===-1&&(r.audioPid=p);break;case 21:r.id3Pid===-1&&(r.id3Pid=p);break;case 219:if(!i){gu("H.264");break}case 27:r.videoPid===-1&&(r.videoPid=p,r.segmentVideoCodec="avc");break;case 3:case 4:!t.mpeg&&!t.mp3?W.log("MPEG audio found, not supported in this browser"):r.audioPid===-1&&(r.audioPid=p,r.segmentAudioCodec="mp3");break;case 193:if(!i){gu("AC-3");break}case 129:t.ac3?r.audioPid===-1&&(r.audioPid=p,r.segmentAudioCodec="ac3"):W.log("AC-3 audio found, not supported in this browser");break;case 6:if(r.audioPid===-1&&d>0){let g=e+5,T=d;for(;T>2;){switch(s[g]){case 106:t.ac3!==!0?W.log("AC-3 audio found, not supported in this browser for now"):(r.audioPid=p,r.segmentAudioCodec="ac3");break}const E=s[g+1]+2;g+=E,T-=E}}break;case 194:case 135:return _o(n,new Error("Unsupported EC-3 in M2TS found")),r;case 36:return _o(n,new Error("Unsupported HEVC in M2TS found")),r}e+=d+5}return r}function _o(s,e,t){W.warn(`parsing error: ${e.message}`),s.emit(I.ERROR,I.ERROR,{type:xe.MEDIA_ERROR,details:te.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function gu(s){W.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function ws(s){let e=0,t,i,n,r,o;const u=s.data;if(!s||s.size===0)return null;for(;u[0].length<19&&u.length>1;)u[0]=si(u[0],u[1]),u.splice(1,1);if(t=u[0],(t[0]<<16)+(t[1]<<8)+t[2]===1){if(i=(t[4]<<8)+t[5],i&&i>s.size-6)return null;const p=t[7];p&192&&(r=(t[9]&14)*536870912+(t[10]&255)*4194304+(t[11]&254)*16384+(t[12]&255)*128+(t[13]&254)/2,p&64?(o=(t[14]&14)*536870912+(t[15]&255)*4194304+(t[16]&254)*16384+(t[17]&255)*128+(t[18]&254)/2,r-o>60*9e4&&(W.warn(`${Math.round((r-o)/9e4)}s delta between PTS and DTS, align them`),r=o)):o=r),n=t[8];let d=n+9;if(s.size<=d)return null;s.size-=d;const g=new Uint8Array(s.size);for(let T=0,b=u.length;T<b;T++){t=u[T];let E=t.byteLength;if(d)if(d>E){d-=E;continue}else t=t.subarray(d),E-=d,d=0;g.set(t,e),e+=E}return i&&(i-=n+3),{data:g,pts:r,dts:o,len:i}}return null}class mS extends qc{resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=kr(e,0);let i=t?.length||0;if(t&&e[i]===11&&e[i+1]===119&&Hc(t)!==void 0&&dm(e,i)<=16)return!1;for(let n=e.length;i<n;i++)if(hm(e,i))return W.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return aS(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return lm(e,t,i,this.basePTS,this.frameIndex)}}class Rf{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)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(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}}}const gn=Math.pow(2,32)-1;class Y{static init(){Y.types={avc1:[],avcC:[],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 e;for(e in Y.types)Y.types.hasOwnProperty(e)&&(Y.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=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]),i=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]);Y.HDLR_TYPES={video:t,audio:i};const n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);Y.STTS=Y.STSC=Y.STCO=r,Y.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Y.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Y.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Y.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const o=new Uint8Array([105,115,111,109]),u=new Uint8Array([97,118,99,49]),h=new Uint8Array([0,0,0,1]);Y.FTYP=Y.box(Y.types.ftyp,o,h,o,u),Y.DINF=Y.box(Y.types.dinf,Y.box(Y.types.dref,n))}static box(e,...t){let i=8,n=t.length;const r=n;for(;n--;)i+=t[n].byteLength;const o=new Uint8Array(i);for(o[0]=i>>24&255,o[1]=i>>16&255,o[2]=i>>8&255,o[3]=i&255,o.set(e,4),n=0,i=8;n<r;n++)o.set(t[n],i),i+=t[n].byteLength;return o}static hdlr(e){return Y.box(Y.types.hdlr,Y.HDLR_TYPES[e])}static mdat(e){return Y.box(Y.types.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(gn+1)),n=Math.floor(t%(gn+1));return Y.box(Y.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,n>>24,n>>16&255,n>>8&255,n&255,85,196,0,0]))}static mdia(e){return Y.box(Y.types.mdia,Y.mdhd(e.timescale,e.duration),Y.hdlr(e.type),Y.minf(e))}static mfhd(e){return Y.box(Y.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?Y.box(Y.types.minf,Y.box(Y.types.smhd,Y.SMHD),Y.DINF,Y.stbl(e)):Y.box(Y.types.minf,Y.box(Y.types.vmhd,Y.VMHD),Y.DINF,Y.stbl(e))}static moof(e,t,i){return Y.box(Y.types.moof,Y.mfhd(e),Y.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=Y.trak(e[t]);return Y.box.apply(null,[Y.types.moov,Y.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(Y.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=Y.trex(e[t]);return Y.box.apply(null,[Y.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(gn+1)),n=Math.floor(t%(gn+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,n>>24,n>>16&255,n>>8&255,n&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 Y.box(Y.types.mvhd,r)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let n,r;for(n=0;n<t.length;n++)r=t[n].flags,i[n+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return Y.box(Y.types.sdtp,i)}static stbl(e){return Y.box(Y.types.stbl,Y.stsd(e),Y.box(Y.types.stts,Y.STTS),Y.box(Y.types.stsc,Y.STSC),Y.box(Y.types.stsz,Y.STSZ),Y.box(Y.types.stco,Y.STCO))}static avc1(e){let t=[],i=[],n,r,o;for(n=0;n<e.sps.length;n++)r=e.sps[n],o=r.byteLength,t.push(o>>>8&255),t.push(o&255),t=t.concat(Array.prototype.slice.call(r));for(n=0;n<e.pps.length;n++)r=e.pps[n],o=r.byteLength,i.push(o>>>8&255),i.push(o&255),i=i.concat(Array.prototype.slice.call(r));const u=Y.box(Y.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),h=e.width,p=e.height,d=e.pixelRatio[0],g=e.pixelRatio[1];return Y.box(Y.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,h>>8&255,h&255,p>>8&255,p&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]),u,Y.box(Y.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Y.box(Y.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,g>>24,g>>16&255,g>>8&255,g&255])))}static esds(e){const t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static audioStsd(e){const t=e.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return Y.box(Y.types.mp4a,Y.audioStsd(e),Y.box(Y.types.esds,Y.esds(e)))}static mp3(e){return Y.box(Y.types[".mp3"],Y.audioStsd(e))}static ac3(e){return Y.box(Y.types["ac-3"],Y.audioStsd(e),Y.box(Y.types.dac3,e.config))}static stsd(e){return e.type==="audio"?e.segmentCodec==="mp3"&&e.codec==="mp3"?Y.box(Y.types.stsd,Y.STSD,Y.mp3(e)):e.segmentCodec==="ac3"?Y.box(Y.types.stsd,Y.STSD,Y.ac3(e)):Y.box(Y.types.stsd,Y.STSD,Y.mp4a(e)):Y.box(Y.types.stsd,Y.STSD,Y.avc1(e))}static tkhd(e){const t=e.id,i=e.duration*e.timescale,n=e.width,r=e.height,o=Math.floor(i/(gn+1)),u=Math.floor(i%(gn+1));return Y.box(Y.types.tkhd,new Uint8Array([1,0,0,7,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,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,u>>24,u>>16&255,u>>8&255,u&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,n>>8&255,n&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const i=Y.sdtp(e),n=e.id,r=Math.floor(t/(gn+1)),o=Math.floor(t%(gn+1));return Y.box(Y.types.traf,Y.box(Y.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255])),Y.box(Y.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,o>>24,o>>16&255,o>>8&255,o&255])),Y.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,Y.box(Y.types.trak,Y.tkhd(e),Y.mdia(e))}static trex(e){const t=e.id;return Y.box(Y.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],n=i.length,r=12+16*n,o=new Uint8Array(r);let u,h,p,d,g,T;for(t+=8+r,o.set([e.type==="video"?1:0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,n&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),u=0;u<n;u++)h=i[u],p=h.duration,d=h.size,g=h.flags,T=h.cts,o.set([p>>>24&255,p>>>16&255,p>>>8&255,p&255,d>>>24&255,d>>>16&255,d>>>8&255,d&255,g.isLeading<<2|g.dependsOn,g.isDependedOn<<6|g.hasRedundancy<<4|g.paddingValue<<1|g.isNonSync,g.degradPrio&61440,g.degradPrio&15,T>>>24&255,T>>>16&255,T>>>8&255,T&255],12+16*u);return Y.box(Y.types.trun,o)}static initSegment(e){Y.types||Y.init();const t=Y.moov(e);return si(Y.FTYP,t)}}Y.types=void 0;Y.HDLR_TYPES=void 0;Y.STTS=void 0;Y.STSC=void 0;Y.STCO=void 0;Y.STSZ=void 0;Y.VMHD=void 0;Y.SMHD=void 0;Y.STSD=void 0;Y.FTYP=void 0;Y.DINF=void 0;const pm=9e4;function Yc(s,e,t=1,i=!1){const n=s*e*t;return i?Math.round(n):n}function yS(s,e,t=1,i=!1){return Yc(s,e,1/t,i)}function mr(s,e=!1){return Yc(s,1e3,1/pm,e)}function vS(s,e=1){return Yc(s,pm,1/e)}const TS=10*1e3,Pf=1024,bS=1152,_S=1536;let As=null,mu=null;class Ya{constructor(e,t,i,n=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,As===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);As=o?parseInt(o[1]):0}if(mu===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);mu=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){W.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){W.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){W.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,n=e.reduce((r,o)=>{let u=o.pts,h=u-r;return h<-4294967296&&(t=!0,u=ii(u,i),h=u-r),h>0?r:u},i);return t&&W.debug("PTS rollover detected"),n}remux(e,t,i,n,r,o,u,h){let p,d,g,T,b,E,w=r,A=r;const L=e.pid>-1,P=t.pid>-1,M=t.samples.length,O=e.samples.length>0,k=u&&M>0||M>1;if((!L||O)&&(!P||k)||this.ISGenerated||u){if(this.ISGenerated){var H,G,B,D;const le=this.videoTrackConfig;le&&(t.width!==le.width||t.height!==le.height||((H=t.pixelRatio)==null?void 0:H[0])!==((G=le.pixelRatio)==null?void 0:G[0])||((B=t.pixelRatio)==null?void 0:B[1])!==((D=le.pixelRatio)==null?void 0:D[1]))&&this.resetInitSegment()}else g=this.generateIS(e,t,r,o);const K=this.isVideoContiguous;let oe=-1,Z;if(k&&(oe=ES(t.samples),!K&&this.config.forceKeyFrameOnDiscontinuity))if(E=!0,oe>0){W.warn(`[mp4-remuxer]: Dropped ${oe} out of ${M} video samples due to a missing keyframe`);const le=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(oe),t.dropped+=oe,A+=(t.samples[0].pts-le)/t.inputTimeScale,Z=A}else oe===-1&&(W.warn(`[mp4-remuxer]: No keyframe found out of ${M} video samples`),E=!1);if(this.ISGenerated){if(O&&k){const le=this.getVideoStartPts(t.samples),fe=(ii(e.samples[0].pts,le)-le)/t.inputTimeScale;w+=Math.max(0,fe),A+=Math.max(0,-fe)}if(O){if(e.samplerate||(W.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),g=this.generateIS(e,t,r,o)),d=this.remuxAudio(e,w,this.isAudioContiguous,o,P||k||h===Pe.AUDIO?A:void 0),k){const le=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(W.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),g=this.generateIS(e,t,r,o)),p=this.remuxVideo(t,A,K,le)}}else k&&(p=this.remuxVideo(t,A,K,0));p&&(p.firstKeyFrame=oe,p.independent=oe!==-1,p.firstKeyFramePTS=Z)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(b=gm(i,r,this._initPTS,this._initDTS)),n.samples.length&&(T=mm(n,r,this._initPTS))),{audio:d,video:p,initSegment:g,independent:E,text:T,id3:b}}generateIS(e,t,i,n){const r=e.samples,o=t.samples,u=this.typeSupported,h={},p=this._initPTS;let d=!p||n,g="audio/mp4",T,b,E;if(d&&(T=b=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":u.mpeg?(g="audio/mpeg",e.codec=""):u.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}h.audio={id:"audio",container:g,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&u.mpeg?new Uint8Array(0):Y.initSegment([e]),metadata:{channelCount:e.channelCount}},d&&(E=e.inputTimeScale,!p||E!==p.timescale?T=b=r[0].pts-Math.round(E*i):d=!1)}if(t.sps&&t.pps&&o.length){if(t.timescale=t.inputTimeScale,h.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Y.initSegment([t]),metadata:{width:t.width,height:t.height}},d)if(E=t.inputTimeScale,!p||E!==p.timescale){const w=this.getVideoStartPts(o),A=Math.round(E*i);b=Math.min(b,ii(o[0].dts,w)-A),T=Math.min(T,w-A)}else d=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(h).length)return this.ISGenerated=!0,d?(this._initPTS={baseTime:T,timescale:E},this._initDTS={baseTime:b,timescale:E}):T=E=void 0,{tracks:h,initPTS:T,timescale:E}}remuxVideo(e,t,i,n){const r=e.inputTimeScale,o=e.samples,u=[],h=o.length,p=this._initPTS;let d=this.nextAvcDts,g=8,T=this.videoSampleDuration,b,E,w=Number.POSITIVE_INFINITY,A=Number.NEGATIVE_INFINITY,L=!1;if(!i||d===null){const ee=t*r,Q=o[0].pts-ii(o[0].dts,o[0].pts);As&&d!==null&&Math.abs(ee-Q-d)<15e3?i=!0:d=ee-Q}const P=p.baseTime*r/p.timescale;for(let ee=0;ee<h;ee++){const Q=o[ee];Q.pts=ii(Q.pts-P,d),Q.dts=ii(Q.dts-P,d),Q.dts<o[ee>0?ee-1:ee].dts&&(L=!0)}L&&o.sort(function(ee,Q){const Ee=ee.dts-Q.dts,ae=ee.pts-Q.pts;return Ee||ae}),b=o[0].dts,E=o[o.length-1].dts;const M=E-b,O=M?Math.round(M/(h-1)):T||e.inputTimeScale/30;if(i){const ee=b-d,Q=ee>O,Ee=ee<-1;if((Q||Ee)&&(Q?W.warn(`AVC: ${mr(ee,!0)} ms (${ee}dts) hole between fragments detected at ${t.toFixed(3)}`):W.warn(`AVC: ${mr(-ee,!0)} ms (${ee}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!Ee||d>=o[0].pts||As)){b=d;const ae=o[0].pts-ee;if(Q)o[0].dts=b,o[0].pts=ae;else for(let ie=0;ie<o.length&&!(o[ie].dts>ae);ie++)o[ie].dts-=ee,o[ie].pts-=ee;W.log(`Video: Initial PTS/DTS adjusted: ${mr(ae,!0)}/${mr(b,!0)}, delta: ${mr(ee,!0)} ms`)}}b=Math.max(0,b);let k=0,N=0,H=b;for(let ee=0;ee<h;ee++){const Q=o[ee],Ee=Q.units,ae=Ee.length;let ie=0;for(let Le=0;Le<ae;Le++)ie+=Ee[Le].data.length;N+=ie,k+=ae,Q.length=ie,Q.dts<H?(Q.dts=H,H+=O/4|0||1):H=Q.dts,w=Math.min(Q.pts,w),A=Math.max(Q.pts,A)}E=o[h-1].dts;const G=N+4*k+8;let B;try{B=new Uint8Array(G)}catch(ee){this.observer.emit(I.ERROR,I.ERROR,{type:xe.MUX_ERROR,details:te.REMUX_ALLOC_ERROR,fatal:!1,error:ee,bytes:G,reason:`fail allocating video mdat ${G}`});return}const D=new DataView(B.buffer);D.setUint32(0,G),B.set(Y.types.mdat,4);let K=!1,oe=Number.POSITIVE_INFINITY,Z=Number.POSITIVE_INFINITY,le=Number.NEGATIVE_INFINITY,ce=Number.NEGATIVE_INFINITY;for(let ee=0;ee<h;ee++){const Q=o[ee],Ee=Q.units;let ae=0;for(let Ce=0,Ue=Ee.length;Ce<Ue;Ce++){const He=Ee[Ce],Fe=He.data,ze=He.data.byteLength;D.setUint32(g,ze),g+=4,B.set(Fe,g),g+=ze,ae+=4+ze}let ie;if(ee<h-1)T=o[ee+1].dts-Q.dts,ie=o[ee+1].pts-Q.pts;else{const Ce=this.config,Ue=ee>0?Q.dts-o[ee-1].dts:O;if(ie=ee>0?Q.pts-o[ee-1].pts:O,Ce.stretchShortVideoTrack&&this.nextAudioPts!==null){const He=Math.floor(Ce.maxBufferHole*r),Fe=(n?w+n*r:this.nextAudioPts)-Q.pts;Fe>He?(T=Fe-Ue,T<0?T=Ue:K=!0,W.log(`[mp4-remuxer]: It is approximately ${Fe/90} ms to the next segment; using duration ${T/90} ms for the last video frame.`)):T=Ue}else T=Ue}const Le=Math.round(Q.pts-Q.dts);oe=Math.min(oe,T),le=Math.max(le,T),Z=Math.min(Z,ie),ce=Math.max(ce,ie),u.push(new Df(Q.key,T,ae,Le))}if(u.length){if(As){if(As<70){const ee=u[0].flags;ee.dependsOn=2,ee.isNonSync=0}}else if(mu&&ce-Z<le-oe&&O/le<.025&&u[0].cts===0){W.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let ee=b;for(let Q=0,Ee=u.length;Q<Ee;Q++){const ae=ee+u[Q].duration,ie=ee+u[Q].cts;if(Q<Ee-1){const Le=ae+u[Q+1].cts;u[Q].duration=Le-ie}else u[Q].duration=Q?u[Q-1].duration:O;u[Q].cts=0,ee=ae}}}T=K||!T?O:T,this.nextAvcDts=d=E+T,this.videoSampleDuration=T,this.isVideoContiguous=!0;const be={data1:Y.moof(e.sequenceNumber++,b,vt({},e,{samples:u})),data2:B,startPTS:w/r,endPTS:(A+T)/r,startDTS:b/r,endDTS:d/r,type:"video",hasAudio:!1,hasVideo:!0,nb:u.length,dropped:e.dropped};return e.samples=[],e.dropped=0,be}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return bS;case"ac3":return _S;default:return Pf}}remuxAudio(e,t,i,n,r){const o=e.inputTimeScale,u=e.samplerate?e.samplerate:o,h=o/u,p=this.getSamplesPerFrame(e),d=p*h,g=this._initPTS,T=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,b=[],E=r!==void 0;let w=e.samples,A=T?0:8,L=this.nextAudioPts||-1;const P=t*o,M=g.baseTime*o/g.timescale;if(this.isAudioContiguous=i=i||w.length&&L>0&&(n&&Math.abs(P-L)<9e3||Math.abs(ii(w[0].pts-M,P)-L)<20*d),w.forEach(function(fe){fe.pts=ii(fe.pts-M,P)}),!i||L<0){if(w=w.filter(fe=>fe.pts>=0),!w.length)return;r===0?L=0:n&&!E?L=Math.max(0,P):L=w[0].pts}if(e.segmentCodec==="aac"){const fe=this.config.maxAudioFramesDrift;for(let ve=0,be=L;ve<w.length;ve++){const ee=w[ve],Q=ee.pts,Ee=Q-be,ae=Math.abs(1e3*Ee/o);if(Ee<=-fe*d&&E)ve===0&&(W.warn(`Audio frame @ ${(Q/o).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*Ee/o)} ms.`),this.nextAudioPts=L=be=Q);else if(Ee>=fe*d&&ae<TS&&E){let ie=Math.round(Ee/d);be=Q-ie*d,be<0&&(ie--,be+=d),ve===0&&(this.nextAudioPts=L=be),W.warn(`[mp4-remuxer]: Injecting ${ie} audio frame @ ${(be/o).toFixed(3)}s due to ${Math.round(1e3*Ee/o)} ms gap.`);for(let Le=0;Le<ie;Le++){const Ce=Math.max(be,0);let Ue=Rf.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);Ue||(W.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),Ue=ee.unit.subarray()),w.splice(ve,0,{unit:Ue,pts:Ce}),be+=d,ve++}}ee.pts=be,be+=d}}let O=null,k=null,N,H=0,G=w.length;for(;G--;)H+=w[G].unit.byteLength;for(let fe=0,ve=w.length;fe<ve;fe++){const be=w[fe],ee=be.unit;let Q=be.pts;if(k!==null){const ae=b[fe-1];ae.duration=Math.round((Q-k)/h)}else if(i&&e.segmentCodec==="aac"&&(Q=L),O=Q,H>0){H+=A;try{N=new Uint8Array(H)}catch(ae){this.observer.emit(I.ERROR,I.ERROR,{type:xe.MUX_ERROR,details:te.REMUX_ALLOC_ERROR,fatal:!1,error:ae,bytes:H,reason:`fail allocating audio mdat ${H}`});return}T||(new DataView(N.buffer).setUint32(0,H),N.set(Y.types.mdat,4))}else return;N.set(ee,A);const Ee=ee.byteLength;A+=Ee,b.push(new Df(!0,p,Ee,0)),k=Q}const B=b.length;if(!B)return;const D=b[b.length-1];this.nextAudioPts=L=k+h*D.duration;const K=T?new Uint8Array(0):Y.moof(e.sequenceNumber++,O/h,vt({},e,{samples:b}));e.samples=[];const oe=O/o,Z=L/o,ce={data1:K,data2:N,startPTS:oe,endPTS:Z,startDTS:oe,endDTS:Z,type:"audio",hasAudio:!0,hasVideo:!1,nb:B};return this.isAudioContiguous=!0,ce}remuxEmptyAudio(e,t,i,n){const r=e.inputTimeScale,o=e.samplerate?e.samplerate:r,u=r/o,h=this.nextAudioPts,p=this._initDTS,d=p.baseTime*9e4/p.timescale,g=(h!==null?h:n.startDTS*r)+d,T=n.endDTS*r+d,b=u*Pf,E=Math.ceil((T-g)/b),w=Rf.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(W.warn("[mp4-remuxer]: remux empty Audio"),!w){W.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}const A=[];for(let L=0;L<E;L++){const P=g+L*b;A.push({unit:w,pts:P,dts:P})}return e.samples=A,this.remuxAudio(e,t,i,!1)}}function ii(s,e){let t;if(e===null)return s;for(e<s?t=-8589934592:t=8589934592;Math.abs(s-e)>4294967296;)s+=t;return s}function ES(s){for(let e=0;e<s.length;e++)if(s[e].key)return e;return-1}function gm(s,e,t,i){const n=s.samples.length;if(!n)return;const r=s.inputTimeScale;for(let u=0;u<n;u++){const h=s.samples[u];h.pts=ii(h.pts-t.baseTime*r/t.timescale,e*r)/r,h.dts=ii(h.dts-i.baseTime*r/i.timescale,e*r)/r}const o=s.samples;return s.samples=[],{samples:o}}function mm(s,e,t){const i=s.samples.length;if(!i)return;const n=s.inputTimeScale;for(let o=0;o<i;o++){const u=s.samples[o];u.pts=ii(u.pts-t.baseTime*n/t.timescale,e*n)/n}s.samples.sort((o,u)=>o.pts-u.pts);const r=s.samples;return s.samples=[],{samples:r}}class Df{constructor(e,t,i,n){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=i,this.cts=n,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class SS{constructor(){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}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,n){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(I_(e,n)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const n=this.initData=$g(e);n.audio&&(t=xf(n.audio,Je.AUDIO)),n.video&&(i=xf(n.video,Je.VIDEO));const r={};n.audio&&n.video?r.audiovideo={container:"video/mp4",codec:t+","+i,initSegment:e,id:"main"}:n.audio?r.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:n.video?r.video={container:"video/mp4",codec:i,initSegment:e,id:"main"}:W.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=r}remux(e,t,i,n,r,o){var u,h;let{initPTS:p,lastEndTime:d}=this;const g={audio:void 0,video:void 0,text:n,id3:i,initSegment:void 0};Ae(d)||(d=this.lastEndTime=r||0);const T=t.samples;if(!(T!=null&&T.length))return g;const b={initPTS:void 0,timescale:1};let E=this.initData;if((u=E)!=null&&u.length||(this.generateInitSegment(T),E=this.initData),!((h=E)!=null&&h.length))return W.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),g;this.emitInitSegment&&(b.tracks=this.initTracks,this.emitInitSegment=!1);const w=P_(T,E),A=R_(E,T),L=A===null?r:A;(CS(p,L,r,w)||b.timescale!==p.timescale&&o)&&(b.initPTS=L-r,p&&p.timescale===1&&W.warn(`Adjusting initPTS by ${b.initPTS-p.baseTime}`),this.initPTS=p={baseTime:b.initPTS,timescale:1});const P=e?L-p.baseTime/p.timescale:d,M=P+w;x_(E,T,p.baseTime/p.timescale),w>0?this.lastEndTime=M:(W.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const O=!!E.audio,k=!!E.video;let N="";O&&(N+="audio"),k&&(N+="video");const H={data1:T,startPTS:P,startDTS:P,endPTS:M,endDTS:M,type:N,hasAudio:O,hasVideo:k,nb:1,dropped:0};return g.audio=H.type==="audio"?H:void 0,g.video=H.type!=="audio"?H:void 0,g.initSegment=b,g.id3=gm(i,r,p,p),n.samples.length&&(g.text=mm(n,r,p)),g}}function CS(s,e,t,i){if(s===null)return!0;const n=Math.max(i,1),r=e-s.baseTime/s.timescale;return Math.abs(r-t)>n}function xf(s,e){const t=s?.codec;if(t&&t.length>4)return t;if(e===Je.AUDIO){if(t==="ec-3"||t==="ac-3"||t==="alac")return t;if(t==="fLaC"||t==="Opus")return po(t,!1);const i="mp4a.40.5";return W.info(`Parsed audio codec "${t}" or audio object type not handled. Using "${i}"`),i}return W.warn(`Unhandled video codec "${t}"`),t==="hvc1"||t==="hev1"?"hvc1.1.6.L120.90":t==="av01"?"av01.0.04M.08":"avc1.42e01e"}let zi;try{zi=self.performance.now.bind(self.performance)}catch{W.debug("Unable to use Performance API on this environment"),zi=$s?.Date.now}const Xa=[{demux:uS,remux:SS},{demux:Tn,remux:Ya},{demux:oS,remux:Ya},{demux:mS,remux:Ya}];Xa.splice(2,0,{demux:cS,remux:Ya});class Of{constructor(e,t,i,n,r){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.vendor=n,this.id=r}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,n){const r=i.transmuxing;r.executeStart=zi();let o=new Uint8Array(e);const{currentTransmuxState:u,transmuxConfig:h}=this;n&&(this.currentTransmuxState=n);const{contiguous:p,discontinuity:d,trackSwitch:g,accurateTimeOffset:T,timeOffset:b,initSegmentChange:E}=n||u,{audioCodec:w,videoCodec:A,defaultInitPts:L,duration:P,initSegmentData:M}=h,O=wS(o,t);if(O&&O.method==="AES-128"){const G=this.getDecrypter();if(G.isSync()){let B=G.softwareDecrypt(o,O.key.buffer,O.iv.buffer);if(i.part>-1&&(B=G.flush()),!B)return r.executeEnd=zi(),yu(i);o=new Uint8Array(B)}else return this.decryptionPromise=G.webCryptoDecrypt(o,O.key.buffer,O.iv.buffer).then(B=>{const D=this.push(B,null,i);return this.decryptionPromise=null,D}),this.decryptionPromise}const k=this.needsProbing(d,g);if(k){const G=this.configureTransmuxer(o);if(G)return W.warn(`[transmuxer] ${G.message}`),this.observer.emit(I.ERROR,I.ERROR,{type:xe.MEDIA_ERROR,details:te.FRAG_PARSING_ERROR,fatal:!1,error:G,reason:G.message}),r.executeEnd=zi(),yu(i)}(d||g||E||k)&&this.resetInitSegment(M,w,A,P,t),(d||E||k)&&this.resetInitialTimestamp(L),p||this.resetContiguity();const N=this.transmux(o,O,b,T,i),H=this.currentTransmuxState;return H.contiguous=!0,H.discontinuity=!1,H.trackSwitch=!1,r.executeEnd=zi(),N}flush(e){const t=e.transmuxing;t.executeStart=zi();const{decrypter:i,currentTransmuxState:n,decryptionPromise:r}=this;if(r)return r.then(()=>this.flush(e));const o=[],{timeOffset:u}=n;if(i){const g=i.flush();g&&o.push(this.push(g,null,e))}const{demuxer:h,remuxer:p}=this;if(!h||!p)return t.executeEnd=zi(),[yu(e)];const d=h.flush(u);return Qa(d)?d.then(g=>(this.flushRemux(o,g,e),o)):(this.flushRemux(o,d,e),o)}flushRemux(e,t,i){const{audioTrack:n,videoTrack:r,id3Track:o,textTrack:u}=t,{accurateTimeOffset:h,timeOffset:p}=this.currentTransmuxState;W.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);const d=this.remuxer.remux(n,r,o,u,p,h,!0,this.id);e.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=zi()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,n,r){const{demuxer:o,remuxer:u}=this;!o||!u||(o.resetInitSegment(e,t,i,n),u.resetInitSegment(e,t,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,n,r){let o;return t&&t.method==="SAMPLE-AES"?o=this.transmuxSampleAes(e,t,i,n,r):o=this.transmuxUnencrypted(e,i,n,r),o}transmuxUnencrypted(e,t,i,n){const{audioTrack:r,videoTrack:o,id3Track:u,textTrack:h}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,o,u,h,t,i,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,i,n,r){return this.demuxer.demuxSampleAes(e,t,i).then(o=>({remuxResult:this.remuxer.remux(o.audioTrack,o.videoTrack,o.id3Track,o.textTrack,i,n,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:n,vendor:r}=this;let o;for(let T=0,b=Xa.length;T<b;T++){var u;if((u=Xa[T].demux)!=null&&u.probe(e)){o=Xa[T];break}}if(!o)return new Error("Failed to find demuxer by probing fragment data");const h=this.demuxer,p=this.remuxer,d=o.remux,g=o.demux;(!p||!(p instanceof d))&&(this.remuxer=new d(i,t,n,r)),(!h||!(h instanceof g))&&(this.demuxer=new g(i,t,n),this.probe=g.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Gc(this.config)),e}}function wS(s,e){let t=null;return s.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const yu=s=>({remuxResult:{},chunkMeta:s});function Qa(s){return"then"in s&&s.then instanceof Function}class AS{constructor(e,t,i,n,r){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=i,this.duration=n,this.defaultInitPts=r||null}}class LS{constructor(e,t,i,n,r,o){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=i,this.trackSwitch=n,this.timeOffset=r,this.initSegmentChange=o}}var ym={exports:{}};(function(s){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function n(h,p,d){this.fn=h,this.context=p,this.once=d||!1}function r(h,p,d,g,T){if(typeof d!="function")throw new TypeError("The listener must be a function");var b=new n(d,g||h,T),E=t?t+p:p;return h._events[E]?h._events[E].fn?h._events[E]=[h._events[E],b]:h._events[E].push(b):(h._events[E]=b,h._eventsCount++),h}function o(h,p){--h._eventsCount===0?h._events=new i:delete h._events[p]}function u(){this._events=new i,this._eventsCount=0}u.prototype.eventNames=function(){var p=[],d,g;if(this._eventsCount===0)return p;for(g in d=this._events)e.call(d,g)&&p.push(t?g.slice(1):g);return Object.getOwnPropertySymbols?p.concat(Object.getOwnPropertySymbols(d)):p},u.prototype.listeners=function(p){var d=t?t+p:p,g=this._events[d];if(!g)return[];if(g.fn)return[g.fn];for(var T=0,b=g.length,E=new Array(b);T<b;T++)E[T]=g[T].fn;return E},u.prototype.listenerCount=function(p){var d=t?t+p:p,g=this._events[d];return g?g.fn?1:g.length:0},u.prototype.emit=function(p,d,g,T,b,E){var w=t?t+p:p;if(!this._events[w])return!1;var A=this._events[w],L=arguments.length,P,M;if(A.fn){switch(A.once&&this.removeListener(p,A.fn,void 0,!0),L){case 1:return A.fn.call(A.context),!0;case 2:return A.fn.call(A.context,d),!0;case 3:return A.fn.call(A.context,d,g),!0;case 4:return A.fn.call(A.context,d,g,T),!0;case 5:return A.fn.call(A.context,d,g,T,b),!0;case 6:return A.fn.call(A.context,d,g,T,b,E),!0}for(M=1,P=new Array(L-1);M<L;M++)P[M-1]=arguments[M];A.fn.apply(A.context,P)}else{var O=A.length,k;for(M=0;M<O;M++)switch(A[M].once&&this.removeListener(p,A[M].fn,void 0,!0),L){case 1:A[M].fn.call(A[M].context);break;case 2:A[M].fn.call(A[M].context,d);break;case 3:A[M].fn.call(A[M].context,d,g);break;case 4:A[M].fn.call(A[M].context,d,g,T);break;default:if(!P)for(k=1,P=new Array(L-1);k<L;k++)P[k-1]=arguments[k];A[M].fn.apply(A[M].context,P)}}return!0},u.prototype.on=function(p,d,g){return r(this,p,d,g,!1)},u.prototype.once=function(p,d,g){return r(this,p,d,g,!0)},u.prototype.removeListener=function(p,d,g,T){var b=t?t+p:p;if(!this._events[b])return this;if(!d)return o(this,b),this;var E=this._events[b];if(E.fn)E.fn===d&&(!T||E.once)&&(!g||E.context===g)&&o(this,b);else{for(var w=0,A=[],L=E.length;w<L;w++)(E[w].fn!==d||T&&!E[w].once||g&&E[w].context!==g)&&A.push(E[w]);A.length?this._events[b]=A.length===1?A[0]:A:o(this,b)}return this},u.prototype.removeAllListeners=function(p){var d;return p?(d=t?t+p:p,this._events[d]&&o(this,d)):(this._events=new i,this._eventsCount=0),this},u.prototype.off=u.prototype.removeListener,u.prototype.addListener=u.prototype.on,u.prefixed=t,u.EventEmitter=u,s.exports=u})(ym);var kS=ym.exports,Xc=Qb(kS);class vm{constructor(e,t,i,n){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;const o=(p,d)=>{d=d||{},d.frag=this.frag,d.id=this.id,p===I.ERROR&&(this.error=d.error),this.hls.trigger(p,d)};this.observer=new Xc,this.observer.on(I.FRAG_DECRYPTED,o),this.observer.on(I.ERROR,o);const u=ts(r.preferManagedMediaSource)||{isTypeSupported:()=>!1},h={mpeg:u.isTypeSupported("audio/mpeg"),mp3:u.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:u.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&typeof Worker<"u"&&(r.workerPath||WE())){try{r.workerPath?(W.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=YE(r.workerPath)):(W.log(`injecting Web Worker for "${t}"`),this.workerContext=zE()),this.onwmsg=g=>this.onWorkerMessage(g);const{worker:d}=this.workerContext;d.addEventListener("message",this.onwmsg),d.onerror=g=>{const T=new Error(`${g.message}  (${g.filename}:${g.lineno})`);r.enableWorker=!1,W.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(I.ERROR,{type:xe.OTHER_ERROR,details:te.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:T})},d.postMessage({cmd:"init",typeSupported:h,vendor:"",id:t,config:JSON.stringify(r)})}catch(d){W.warn(`Error setting up "${t}" Web Worker, fallback to inline`,d),this.resetWorker(),this.error=null,this.transmuxer=new Of(this.observer,h,r,"",t)}return}this.transmuxer=new Of(this.observer,h,r,"",t)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,i,n,r,o,u,h,p,d){var g,T;p.transmuxing.start=self.performance.now();const{transmuxer:b}=this,E=o?o.start:r.start,w=r.decryptdata,A=this.frag,L=!(A&&r.cc===A.cc),P=!(A&&p.level===A.level),M=A?p.sn-A.sn:-1,O=this.part?p.part-this.part.index:-1,k=M===0&&p.id>1&&p.id===A?.stats.chunkCount,N=!P&&(M===1||M===0&&(O===1||k&&O<=0)),H=self.performance.now();(P||M||r.stats.parsing.start===0)&&(r.stats.parsing.start=H),o&&(O||!N)&&(o.stats.parsing.start=H);const G=!(A&&((g=r.initSegment)==null?void 0:g.url)===((T=A.initSegment)==null?void 0:T.url)),B=new LS(L,N,h,P,E,G);if(!N||L||G){W.log(`[transmuxer-interface, ${r.type}]: Starting new transmux session for sn: ${p.sn} p: ${p.part} level: ${p.level} id: ${p.id}
        discontinuity: ${L}
        trackSwitch: ${P}
        contiguous: ${N}
        accurateTimeOffset: ${h}
        timeOffset: ${E}
        initSegmentChange: ${G}`);const D=new AS(i,n,t,u,d);this.configureTransmuxer(D)}if(this.frag=r,this.part=o,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:w,chunkMeta:p,state:B},e instanceof ArrayBuffer?[e]:[]);else if(b){const D=b.push(e,w,p,B);Qa(D)?(b.async=!0,D.then(K=>{this.handleTransmuxComplete(K)}).catch(K=>{this.transmuxerError(K,p,"transmuxer-interface push error")})):(b.async=!1,this.handleTransmuxComplete(D))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let i=t.flush(e);Qa(i)||t.async?(Qa(i)||(i=Promise.resolve(i)),i.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")})):this.handleFlushResult(i,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(I.ERROR,{type:xe.MEDIA_ERROR,details:te.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}onWorkerMessage(e){const t=e.data;if(!(t!=null&&t.event)){W.warn(`worker message received with no ${t?"event name":"data"}`);return}const i=this.hls;if(this.hls)switch(t.event){case"init":{var n;const r=(n=this.workerContext)==null?void 0:n.objectURL;r&&self.URL.revokeObjectURL(r);break}case"transmuxComplete":{this.handleTransmuxComplete(t.data);break}case"flush":{this.onFlush(t.data);break}case"workerLog":W[t.data.logType]&&W[t.data.logType](t.data.message);break;default:{t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,i.trigger(t.event,t.data);break}}}configureTransmuxer(e){const{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const Mf=100;class IS extends Kc{constructor(e,t,i){super(e,t,i,"[audio-stream-controller]",Pe.AUDIO),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-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.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:e}=this;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(I.ERROR,this.onError,this),e.on(I.BUFFER_RESET,this.onBufferReset,this),e.on(I.BUFFER_CREATED,this.onBufferCreated,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(I.ERROR,this.onError,this),e.off(I.BUFFER_RESET,this.onBufferReset,this),e.off(I.BUFFER_CREATED,this.onBufferCreated,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r}){if(i==="main"){const o=t.cc;this.initPTS[t.cc]={baseTime:n,timescale:r},this.log(`InitPTS for cc: ${o} found from main: ${n}`),this.videoTrackCC=o,this.state===de.WAITING_INIT_PTS&&this.tick()}}startLoad(e){if(!this.levels){this.startPosition=e,this.state=de.STOPPED;return}const t=this.lastCurrentTime;this.stopLoad(),this.setInterval(Mf),t>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=de.IDLE):(this.loadedmetadata=!1,this.state=de.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case de.IDLE:this.doTickIdle();break;case de.WAITING_TRACK:{var e;const{levels:i,trackId:n}=this,r=i==null||(e=i[n])==null?void 0:e.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=de.WAITING_INIT_PTS}break}case de.FRAG_LOADING_WAITING_RETRY:{var t;const i=performance.now(),n=this.retryDate;if(!n||i>=n||(t=this.media)!=null&&t.seeking){const{levels:r,trackId:o}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(r?.[o]||null),this.state=de.IDLE}break}case de.WAITING_INIT_PTS:{const i=this.waitingData;if(i){const{frag:n,part:r,cache:o,complete:u}=i;if(this.initPTS[n.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=de.FRAG_LOADING;const h=o.flush(),p={frag:n,part:r,payload:h,networkDetails:null};this._handleFragmentLoadProgress(p),u&&super._handleFragmentLoadComplete(p)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${n.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const h=this.getLoadPosition(),p=at.bufferInfo(this.mediaBuffer,h,this.config.maxBufferHole);oc(p.end,this.config.maxFragLookUpTolerance,n)<0&&(this.log(`Waiting fragment cc (${n.cc}) @ ${n.start} cancelled because another fragment at ${p.end} is needed`),this.clearWaitingFragment())}}else this.state=de.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=de.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:t,media:i,trackId:n}=this,r=e.config;if(!this.buffering||!i&&(this.startFragRequested||!r.startFragPrefetch)||!(t!=null&&t[n]))return;const o=t[n],u=o.details;if(!u||u.live&&this.levelLastLoaded!==o||this.waitForCdnTuneIn(u)){this.state=de.WAITING_TRACK;return}const h=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&h&&(this.bufferFlushed=!1,this.afterBufferFlushed(h,Je.AUDIO,Pe.AUDIO));const p=this.getFwdBufferInfo(h,Pe.AUDIO);if(p===null)return;if(!this.switchingTrack&&this._streamEnded(p,u)){e.trigger(I.BUFFER_EOS,{type:"audio"}),this.state=de.ENDED;return}const d=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Pe.MAIN),g=p.len,T=this.getMaxBufferLength(d?.len),b=u.fragments,E=b[0].start,w=this.getLoadPosition(),A=this.flushing?w:p.end;if(this.switchingTrack&&i){const O=w;u.PTSKnown&&O<E&&(p.end>E||p.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=E+.05)}if(g>=T&&!this.switchingTrack&&A<b[b.length-1].start)return;let L=this.getNextFragment(A,u),P=!1;if(L&&this.isLoopLoading(L,A)&&(P=!!L.gap,L=this.getNextFragmentLoopLoading(L,u,p,Pe.MAIN,T)),!L){this.bufferFlushed=!0;return}const M=d&&L.start>d.end+u.targetduration;if(M||!(d!=null&&d.len)&&p.len){const O=this.getAppendedFrag(L.start,Pe.MAIN);if(O===null||(P||(P=!!O.gap||!!M&&d.len===0),M&&!P||P&&p.nextStart&&p.nextStart<O.end))return}this.loadFragment(L,o,A)}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.min(Math.max(t,e),this.config.maxMaxBufferLength):t}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new js(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),i?this.setInterval(Mf):this.resetTransmuxer(),i?(this.switchingTrack=t,this.state=de.IDLE,this.flushAudioIfNeeded(t)):(this.switchingTrack=null,this.bufferedTrack=t,this.state=de.STOPPED),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,this.cachedTrackLoadedData!==null&&(this.hls.trigger(I.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var i;if(this.mainDetails==null){this.cachedTrackLoadedData=t;return}const{levels:n}=this,{details:r,id:o}=t;if(!n){this.warn(`Audio tracks were reset while loading level ${o}`);return}this.log(`Audio track ${o} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const u=n[o];let h=0;if(r.live||(i=u.details)!=null&&i.live){this.checkLiveUpdate(r);const d=this.mainDetails;if(r.deltaUpdateFailed||!d)return;if(!u.details&&r.hasProgramDateTime&&d.hasProgramDateTime)To(r,d),h=r.fragments[0].start;else{var p;h=this.alignPlaylists(r,u.details,(p=this.levelLastLoaded)==null?void 0:p.details)}}u.details=r,this.levelLastLoaded=u,!this.startFragRequested&&(this.mainDetails||!r.live)&&this.setStartPosition(this.mainDetails||r,h),this.state===de.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=de.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:n,payload:r}=e,{config:o,trackId:u,levels:h}=this;if(!h){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const p=h[u];if(!p){this.warn("Audio track is undefined on fragment load progress");return}const d=p.details;if(!d){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const g=o.defaultAudioCodec||p.audioCodec||"mp4a.40.2";let T=this.transmuxer;T||(T=this.transmuxer=new vm(this.hls,Pe.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const b=this.initPTS[i.cc],E=(t=i.initSegment)==null?void 0:t.data;if(b!==void 0){const A=n?n.index:-1,L=A!==-1,P=new Vc(i.level,i.sn,i.stats.chunkCount,r.byteLength,A,L);T.push(r,E,g,"",i,n,d.totalduration,!1,P,b)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${d.startSN} ,${d.endSN}],track ${u}`);const{cache:w}=this.waitingData=this.waitingData||{frag:i,part:n,cache:new im,complete:!1};w.push(new Uint8Array(r)),this.waitingVideoCC=this.videoTrackCC,this.state=de.WAITING_INIT_PTS}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:i,part:n}=t;if(i.type!==Pe.AUDIO){if(!this.loadedmetadata&&i.type===Pe.MAIN){const r=this.videoBuffer||this.media;r&&at.getBuffered(r).length&&(this.loadedmetadata=!0)}return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(i.sn!=="initSegment"){this.fragPrevious=i;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(I.AUDIO_TRACK_SWITCHED,St({},r)))}this.fragBufferedComplete(i,n)}onError(e,t){var i;if(t.fatal){this.state=de.ERROR;return}switch(t.details){case te.FRAG_GAP:case te.FRAG_PARSING_ERROR:case te.FRAG_DECRYPT_ERROR:case te.FRAG_LOAD_ERROR:case te.FRAG_LOAD_TIMEOUT:case te.KEY_LOAD_ERROR:case te.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Pe.AUDIO,t);break;case te.AUDIO_TRACK_LOAD_ERROR:case te.AUDIO_TRACK_LOAD_TIMEOUT:case te.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===de.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===qe.AUDIO_TRACK&&(this.state=de.IDLE);break;case te.BUFFER_APPEND_ERROR:case te.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="audio")return;if(t.details===te.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case te.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==Je.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Je.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===de.ENDED&&(this.state=de.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,Pe.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:n}=this,{remuxResult:r,chunkMeta:o}=e,u=this.getCurrentContext(o);if(!u){this.resetWhenMissingContext(o);return}const{frag:h,part:p,level:d}=u,{details:g}=d,{audio:T,text:b,id3:E,initSegment:w}=r;if(this.fragContextChanged(h)||!g){this.fragmentTracker.removeFragment(h);return}if(this.state=de.PARSING,this.switchingTrack&&T&&this.completeAudioSwitch(this.switchingTrack),w!=null&&w.tracks){const A=h.initSegment||h;this._bufferInitSegment(d,w.tracks,A,o),n.trigger(I.FRAG_PARSING_INIT_SEGMENT,{frag:A,id:i,tracks:w.tracks})}if(T){const{startPTS:A,endPTS:L,startDTS:P,endDTS:M}=T;p&&(p.elementaryStreams[Je.AUDIO]={startPTS:A,endPTS:L,startDTS:P,endDTS:M}),h.setElementaryStreamInfo(Je.AUDIO,A,L,P,M),this.bufferFragmentData(T,h,p,o)}if(E!=null&&(t=E.samples)!=null&&t.length){const A=vt({id:i,frag:h,details:g},E);n.trigger(I.FRAG_PARSING_METADATA,A)}if(b){const A=vt({id:i,frag:h,details:g},b);n.trigger(I.FRAG_PARSING_USERDATA,A)}}_bufferInitSegment(e,t,i,n){if(this.state!==de.PARSING)return;t.video&&delete t.video;const r=t.audio;if(!r)return;r.id="audio";const o=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${o}/${r.codec}]`),o&&o.split(",").length===1&&(r.levelCodec=o),this.hls.trigger(I.BUFFER_CODECS,t);const u=r.initSegment;if(u!=null&&u.byteLength){const h={type:"audio",frag:i,part:null,chunkMeta:n,parent:i.type,data:u};this.hls.trigger(I.BUFFER_APPENDING,h)}this.tickImmediate()}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||n===Et.NOT_LOADED||n===Et.PARTIAL){var r;if(e.sn==="initSegment")this._loadInitSegment(e,t);else if((r=t.details)!=null&&r.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=de.WAITING_INIT_PTS;const o=this.mainDetails;o&&o.fragments[0].start!==t.details.fragments[0].start&&To(t.details,o)}else this.startFragRequested=!0,super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:n,characteristics:r,audioCodec:o,channels:u}=this.bufferedTrack;es({name:t,lang:i,assocLang:n,characteristics:r,audioCodec:o,channels:u},e,Wn)||(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(I.AUDIO_TRACK_SWITCHED,St({},e))}}function Tm(s,e){if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(!Pr(s[t].attrs,e[t].attrs))return!1;return!0}function Pr(s,e,t){const i=s["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(n=>s[n]!==e[n])}function uc(s,e){return e.label.toLowerCase()===s.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(s.lang||"").toLowerCase())}class RS extends jc{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(){const{hls:e}=this;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVEL_LOADING,this.onLevelLoading,this),e.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(I.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){const{id:i,groupId:n,details:r}=t,o=this.tracksInGroup[i];if(!o||o.groupId!==n){this.warn(`Audio track with id:${i} and group:${n} not found in active group ${o?.groupId}`);return}const u=o.details;o.details=t.details,this.log(`Audio track ${i} "${o.name}" lang:${o.lang} group:${n} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,u)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,n=this.groupIds;let r=this.currentTrack;if(!i||n?.length!==i?.length||i!=null&&i.some(u=>n?.indexOf(u)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const u=this.tracks.filter(T=>!i||i.indexOf(T.groupId)!==-1);if(u.length)this.selectDefaultTrack&&!u.some(T=>T.default)&&(this.selectDefaultTrack=!1),u.forEach((T,b)=>{T.id=b});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=u;const h=this.hls.config.audioPreference;if(!r&&h){const T=Di(h,u,Wn);if(T>-1)r=u[T];else{const b=Di(h,this.tracks);r=this.tracks[b]}}let p=this.findTrackId(r);p===-1&&r&&(p=this.findTrackId(null));const d={audioTracks:u};this.log(`Updating audio tracks, ${u.length} track(s) found in group(s): ${i?.join(",")}`),this.hls.trigger(I.AUDIO_TRACKS_UPDATED,d);const g=this.trackId;if(p!==-1&&g===-1)this.setAudioTrack(p);else if(u.length&&g===-1){var o;const T=new Error(`No audio track selected for current audio group-ID(s): ${(o=this.groupIds)==null?void 0:o.join(",")} track count: ${u.length}`);this.warn(T.message),this.hls.trigger(I.ERROR,{type:xe.MEDIA_ERROR,details:te.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:T})}}else this.shouldReloadPlaylist(r)&&this.setAudioTrack(this.trackId)}onError(e,t){t.fatal||!t.context||t.context.type===qe.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&(this.requestScheduled=-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){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const n=this.currentTrack;if(n&&es(e,n,Wn))return n;const r=Di(e,this.tracksInGroup,Wn);if(r>-1){const o=this.tracksInGroup[r];return this.setAudioTrack(r),o}else if(n){let o=t.loadLevel;o===-1&&(o=t.firstAutoLevel);const u=RE(e,t.levels,i,o,Wn);if(u===-1)return null;t.nextLoadLevel=u}if(e.channels||e.audioCodec){const o=Di(e,i);if(o>-1)return i[o]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,n=t[e],r=n.details&&!n.details.live;if(e===this.trackId&&n===i&&r||(this.log(`Switching to audio-track ${e} "${n.name}" lang:${n.lang} group:${n.groupId} channels:${n.channels}`),this.trackId=e,this.currentTrack=n,this.hls.trigger(I.AUDIO_TRACK_SWITCHING,St({},n)),r))return;const o=this.switchParams(n.url,i?.details,n.details);this.loadPlaylist(o)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const n=t[i];if(!(this.selectDefaultTrack&&!n.default)&&(!e||es(e,n,Wn)))return i}if(e){const{name:i,lang:n,assocLang:r,characteristics:o,audioCodec:u,channels:h}=e;for(let p=0;p<t.length;p++){const d=t[p];if(es({name:i,lang:n,assocLang:r,characteristics:o,audioCodec:u,channels:h},d,Wn))return p}for(let p=0;p<t.length;p++){const d=t[p];if(Pr(e.attrs,d.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return p}for(let p=0;p<t.length;p++){const d=t[p];if(Pr(e.attrs,d.attrs,["LANGUAGE"]))return p}}return-1}loadPlaylist(e){const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){super.loadPlaylist();const i=t.id,n=t.groupId;let r=t.url;if(e)try{r=e.addDirectives(r)}catch(o){this.warn(`Could not construct new URL with HLS Delivery Directives: ${o}`)}this.log(`loading audio-track playlist ${i} "${t.name}" lang:${t.lang} group:${n}`),this.clearTimer(),this.hls.trigger(I.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:n,deliveryDirectives:e||null})}}}const Ff=500;class PS extends Kc{constructor(e,t,i){super(e,t,i,"[subtitle-stream-controller]",Pe.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.ERROR,this.onError,this),e.on(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(I.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.ERROR,this.onError,this),e.off(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(I.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=de.IDLE,this.setInterval(Ff),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:n}=t;if(this.fragPrevious=i,this.state=de.IDLE,!n)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let o;const u=i.start;for(let p=0;p<r.length;p++)if(u>=r[p].start&&u<=r[p].end){o=r[p];break}const h=i.start+i.duration;o?o.end=h:(o={start:u,end:h},r.push(o)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null)}onBufferFlushing(e,t){const{startOffset:i,endOffset:n}=t;if(i===0&&n!==Number.POSITIVE_INFINITY){const r=n-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(o=>{for(let u=0;u<o.length;){if(o[u].end<=r){o.shift();continue}else if(o[u].start<r)o[u].start=r;else break;u++}}),this.fragmentTracker.removeFragmentsInRange(i,r,Pe.SUBTITLE)}}onFragBuffered(e,t){if(!this.loadedmetadata&&t.frag.type===Pe.MAIN){var i;(i=this.media)!=null&&i.buffered.length&&(this.loadedmetadata=!0)}}onError(e,t){const i=t.frag;i?.type===Pe.SUBTITLE&&(t.details===te.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==de.STOPPED&&(this.state=de.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Tm(this.levels,t)){this.levels=t.map(i=>new js(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const n=new js(i);return this.tracksBuffered[n.id]=[],n}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Pe.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}const n=this.levels[this.currentTrackId];n!=null&&n.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,n&&this.setInterval(Ff)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:n,levels:r}=this,{details:o,id:u}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${u}`);return}const h=r[u];if(u>=r.length||!h)return;this.log(`Subtitle track ${u} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""},duration:${o.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let p=0;if(o.live||(i=h.details)!=null&&i.live){const g=this.mainDetails;if(o.deltaUpdateFailed||!g)return;const T=g.fragments[0];if(!h.details)o.hasProgramDateTime&&g.hasProgramDateTime?(To(o,g),p=o.fragments[0].start):T&&(p=T.start,ac(o,p));else{var d;p=this.alignPlaylists(o,h.details,(d=this.levelLastLoaded)==null?void 0:d.details),p===0&&T&&(p=T.start,ac(o,p))}}h.details=o,this.levelLastLoaded=h,u===n&&(!this.startFragRequested&&(this.mainDetails||!o.live)&&this.setStartPosition(this.mainDetails||o,p),this.tick(),o.live&&!this.fragCurrent&&this.media&&this.state===de.IDLE&&(vo(null,o.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),h.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,n=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&n!=null&&n.key&&n.iv&&n.method==="AES-128"){const o=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer).catch(u=>{throw r.trigger(I.ERROR,{type:xe.MEDIA_ERROR,details:te.FRAG_DECRYPT_ERROR,fatal:!1,error:u,reason:u.message,frag:t}),u}).then(u=>{const h=performance.now();r.trigger(I.FRAG_DECRYPTED,{frag:t,payload:u,stats:{tstart:o,tdecrypt:h}})}).catch(u=>{this.warn(`${u.name}: ${u.message}`),this.state=de.IDLE})}}doTick(){if(!this.media){this.state=de.IDLE;return}if(this.state===de.IDLE){const{currentTrackId:e,levels:t}=this,i=t?.[e];if(!i||!t.length||!i.details)return;const{config:n}=this,r=this.getLoadPosition(),o=at.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,n.maxBufferHole),{end:u,len:h}=o,p=this.getFwdBufferInfo(this.media,Pe.MAIN),d=i.details,g=this.getMaxBufferLength(p?.len)+d.levelTargetDuration;if(h>g)return;const T=d.fragments,b=T.length,E=d.edge;let w=null;const A=this.fragPrevious;if(u<E){const L=n.maxFragLookUpTolerance,P=u>E-L?0:L;w=vo(A,T,Math.max(T[0].start,u),P),!w&&A&&A.start<T[0].start&&(w=T[0])}else w=T[b-1];if(!w)return;if(w=this.mapToInitFragWhenRequired(w),w.sn!=="initSegment"){const L=w.sn-d.startSN,P=T[L-1];P&&P.cc===w.cc&&this.fragmentTracker.getState(P)===Et.NOT_LOADED&&(w=P)}this.fragmentTracker.getState(w)===Et.NOT_LOADED&&this.loadFragment(w,i,u)}}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.max(t,e):t}loadFragment(e,t,i){this.fragCurrent=e,e.sn==="initSegment"?this._loadInitSegment(e,t):(this.startFragRequested=!0,super.loadFragment(e,t,i))}get mediaBufferTimeRanges(){return new DS(this.tracksBuffered[this.currentTrackId]||[])}}class DS{constructor(e){this.buffered=void 0;const t=(i,n,r)=>{if(n=n>>>0,n>r-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${r})`);return e[n][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}}class xS extends jc{constructor(e){super(e,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const i=qa(this.media.textTracks);for(let r=0;r<i.length;r++)if(i[r].mode==="hidden")t=i[r];else if(i[r].mode==="showing"){t=i[r];break}const n=this.findTrackForTextTrack(t);this.subtitleTrack!==n&&this.setSubtitleTrack(n)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVEL_LOADING,this.onLevelLoading,this),e.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(I.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(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),qa(this.media.textTracks).forEach(t=>{Rs(t)}),this.subtitleTrack=-1,this.media=null}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){const{id:i,groupId:n,details:r}=t,o=this.tracksInGroup[i];if(!o||o.groupId!==n){this.warn(`Subtitle track with id:${i} and group:${n} not found in active group ${o?.groupId}`);return}const u=o.details;o.details=t.details,this.log(`Subtitle track ${i} "${o.name}" lang:${o.lang} group:${n} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,u)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,n=this.groupIds;let r=this.currentTrack;if(!i||n?.length!==i?.length||i!=null&&i.some(o=>n?.indexOf(o)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>!i||i.indexOf(d.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,g)=>{d.id=g});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const u=this.hls.config.subtitlePreference;if(!r&&u){this.selectDefaultTrack=!1;const d=Di(u,o);if(d>-1)r=o[d];else{const g=Di(u,this.tracks);r=this.tracks[g]}}let h=this.findTrackId(r);h===-1&&r&&(h=this.findTrackId(null));const p={subtitleTracks:o};this.log(`Updating subtitle tracks, ${o.length} track(s) found in "${i?.join(",")}" group-id`),this.hls.trigger(I.SUBTITLE_TRACKS_UPDATED,p),h!==-1&&this.trackId===-1&&this.setSubtitleTrack(h)}else this.shouldReloadPlaylist(r)&&this.setSubtitleTrack(this.trackId)}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let n=0;n<t.length;n++){const r=t[n];if(!(i&&!r.default||!i&&!e)&&(!e||es(r,e)))return n}if(e){for(let n=0;n<t.length;n++){const r=t[n];if(Pr(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return n}for(let n=0;n<t.length;n++){const r=t[n];if(Pr(e.attrs,r.attrs,["LANGUAGE"]))return n}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const n=t[i];if(uc(n,e))return i}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===qe.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const i=this.currentTrack;if(i&&es(e,i))return i;const n=Di(e,this.tracksInGroup);if(n>-1){const r=this.tracksInGroup[n];return this.setSubtitleTrack(n),r}else{if(i)return null;{const r=Di(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){const i=t.id,n=t.groupId;let r=t.url;if(e)try{r=e.addDirectives(r)}catch(o){this.warn(`Could not construct new URL with HLS Delivery Directives: ${o}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(I.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:n,deliveryDirectives:e||null})}}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=qa(e.textTracks),i=this.currentTrack;let n;if(i&&(n=t.filter(r=>uc(i,r))[0],n||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==n&&(r.mode="disabled")}),n){const r=this.subtitleDisplay?"showing":"hidden";n.mode!==r&&(n.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!Ae(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,n=t[e]||null;if(this.trackId=e,this.currentTrack=n,this.toggleTrackModes(),!n){this.hls.trigger(I.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!n.details&&!n.details.live;if(e===this.trackId&&n===i&&r)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:o,groupId:u="",name:h,type:p,url:d}=n;this.hls.trigger(I.SUBTITLE_TRACK_SWITCH,{id:o,groupId:u,name:h,type:p,url:d});const g=this.switchParams(n.url,i?.details,n.details);this.loadPlaylist(g)}}class OS{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t,i){const n=this.queues[t];n.push(e),n.length===1&&!i&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const i=new Promise(r=>{t=r}),n={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(n,e),i}executeNext(e){const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(n){W.warn(`[buffer-operation-queue]: Exception executing "${e}" SourceBuffer operation: ${n}`),i.onError(n);const r=this.buffers[e];r!=null&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const Nf=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;class MS{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=i=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:i,mediaSource:n}=this;this.log("Media source opened"),i&&(i.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(I.MEDIA_ATTACHED,{media:i,mediaSource:n})),n&&n.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:i,_objectUrl:n}=this;i!==n&&W.error(`Media element src was set while attaching MediaSource (${n} > ${i})`)},this.hls=e;const t="[buffer-controller]";this.appendSource=G_(ts(e.config.preferManagedMediaSource)),this.log=W.log.bind(W,t),this.warn=W.warn.bind(W,t),this.error=W.error.bind(W,t),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){const{hls:e}=this;e.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.BUFFER_RESET,this.onBufferReset,this),e.on(I.BUFFER_APPENDING,this.onBufferAppending,this),e.on(I.BUFFER_CODECS,this.onBufferCodecs,this),e.on(I.BUFFER_EOS,this.onBufferEos,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(I.FRAG_PARSED,this.onFragParsed,this),e.on(I.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.BUFFER_RESET,this.onBufferReset,this),e.off(I.BUFFER_APPENDING,this.onBufferAppending,this),e.off(I.BUFFER_CODECS,this.onBufferCodecs,this),e.off(I.BUFFER_EOS,this.onBufferEos,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(I.FRAG_PARSED,this.onFragParsed,this),e.off(I.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new OS(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const i=this.media=t.media,n=ts(this.appendSource);if(i&&n){var r;const o=this.mediaSource=new n;this.log(`created media source: ${(r=o.constructor)==null?void 0:r.name}`),o.addEventListener("sourceopen",this._onMediaSourceOpen),o.addEventListener("sourceended",this._onMediaSourceEnded),o.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(o.addEventListener("startstreaming",this._onStartStreaming),o.addEventListener("endstreaming",this._onEndStreaming));const u=this._objectUrl=self.URL.createObjectURL(o);if(this.appendSource)try{i.removeAttribute("src");const h=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||h&&o instanceof h,Bf(i),FS(i,u),i.load()}catch{i.src=u}else i.src=u;i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:i}=this;if(t){if(this.log("media source detaching"),t.readyState==="open")try{t.endOfStream()}catch(n){this.warn(`onMediaDetaching: ${n.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.removeEventListener("startstreaming",this._onStartStreaming),t.removeEventListener("endstreaming",this._onEndStreaming)),e&&(e.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),this.mediaSrc===i?(e.removeAttribute("src"),this.appendSource&&Bf(e),e.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(I.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(e=>{this.resetBuffer(e)}),this._initSourceBuffer(),this.hls.resumeBuffering()}resetBuffer(e){const t=this.sourceBuffer[e];try{if(t){var i;this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}}catch(n){this.warn(`onBufferReset ${e}`,n)}}onBufferCodecs(e,t){const i=this.getSourceBufferTypes().length,n=Object.keys(t);if(n.forEach(o=>{if(i){const h=this.tracks[o];if(h&&typeof h.buffer.changeType=="function"){var u;const{id:p,codec:d,levelCodec:g,container:T,metadata:b}=t[o],E=rf(h.codec,h.levelCodec),w=E?.replace(Nf,"$1");let A=rf(d,g);const L=(u=A)==null?void 0:u.replace(Nf,"$1");if(A&&w!==L){o.slice(0,5)==="audio"&&(A=po(A,this.appendSource));const P=`${T};codecs=${A}`;this.appendChangeType(o,P),this.log(`switching codec ${E} to ${A}`),this.tracks[o]={buffer:h.buffer,codec:d,container:T,levelCodec:g,metadata:b,id:p}}}}else this.pendingTracks[o]=t[o]}),i)return;const r=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==r&&(this.log(`${r} bufferCodec event(s) expected ${n.join(",")}`),this.bufferCodecEventsExpected=r),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks()}appendChangeType(e,t){const{operationQueue:i}=this,n={execute:()=>{const r=this.sourceBuffer[e];r&&(this.log(`changing ${e} sourceBuffer type to ${t}`),r.changeType(t)),i.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:r=>{this.warn(`Failed to change ${e} SourceBuffer type`,r)}};i.append(n,e,!!this.pendingTracks[e])}onBufferAppending(e,t){const{hls:i,operationQueue:n,tracks:r}=this,{data:o,type:u,frag:h,part:p,chunkMeta:d}=t,g=d.buffering[u],T=self.performance.now();g.start=T;const b=h.stats.buffering,E=p?p.stats.buffering:null;b.start===0&&(b.start=T),E&&E.start===0&&(E.start=T);const w=r.audio;let A=!1;u==="audio"&&w?.container==="audio/mpeg"&&(A=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const L=h.start,P={execute:()=>{if(g.executeStart=self.performance.now(),A){const M=this.sourceBuffer[u];if(M){const O=L-M.timestampOffset;Math.abs(O)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${L} (delta: ${O}) sn: ${h.sn})`),M.timestampOffset=L)}}this.appendExecutor(o,u)},onStart:()=>{},onComplete:()=>{const M=self.performance.now();g.executeEnd=g.end=M,b.first===0&&(b.first=M),E&&E.first===0&&(E.first=M);const{sourceBuffer:O}=this,k={};for(const N in O)k[N]=at.getBuffered(O[N]);this.appendErrors[u]=0,u==="audio"||u==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(I.BUFFER_APPENDED,{type:u,frag:h,part:p,chunkMeta:d,parent:h.type,timeRanges:k})},onError:M=>{const O={type:xe.MEDIA_ERROR,parent:h.type,details:te.BUFFER_APPEND_ERROR,sourceBufferName:u,frag:h,part:p,chunkMeta:d,error:M,err:M,fatal:!1};if(M.code===DOMException.QUOTA_EXCEEDED_ERR)O.details=te.BUFFER_FULL_ERROR;else{const k=++this.appendErrors[u];O.details=te.BUFFER_APPEND_ERROR,this.warn(`Failed ${k}/${i.config.appendErrorMaxRetry} times to append segment in "${u}" sourceBuffer`),k>=i.config.appendErrorMaxRetry&&(O.fatal=!0)}i.trigger(I.ERROR,O)}};n.append(P,u,!!this.pendingTracks[u])}onBufferFlushing(e,t){const{operationQueue:i}=this,n=r=>({execute:this.removeExecutor.bind(this,r,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(I.BUFFER_FLUSHED,{type:r})},onError:o=>{this.warn(`Failed to remove from ${r} SourceBuffer`,o)}});t.type?i.append(n(t.type),t.type):this.getSourceBufferTypes().forEach(r=>{i.append(n(r),r)})}onFragParsed(e,t){const{frag:i,part:n}=t,r=[],o=n?n.elementaryStreams:i.elementaryStreams;o[Je.AUDIOVIDEO]?r.push("audiovideo"):(o[Je.AUDIO]&&r.push("audio"),o[Je.VIDEO]&&r.push("video"));const u=()=>{const h=self.performance.now();i.stats.buffering.end=h,n&&(n.stats.buffering.end=h);const p=n?n.stats:i.stats;this.hls.trigger(I.FRAG_BUFFERED,{frag:i,part:n,stats:p,id:i.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(u,r)}onFragChanged(e,t){this.trimBuffers()}onBufferEos(e,t){this.getSourceBufferTypes().reduce((n,r)=>{const o=this.sourceBuffer[r];return o&&(!t.type||t.type===r)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${r} sourceBuffer now EOS`))),n&&!!(!o||o.ended)},!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(r=>{const o=this.sourceBuffer[r];o&&(o.ending=!1)});const{mediaSource:n}=this;if(!n||n.readyState!=="open"){n&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${n.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),n.endOfStream()}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||t===null||!this.getSourceBufferTypes().length)return;const r=e.config,o=i.currentTime,u=t.levelTargetDuration,h=t.live&&r.liveBackBufferLength!==null?r.liveBackBufferLength:r.backBufferLength;if(Ae(h)&&h>0){const p=Math.max(h,u),d=Math.floor(o/u)*u-p;this.flushBackBuffer(o,u,d)}if(Ae(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){const p=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),d=Math.max(p,u),g=Math.floor(o/u)*u+d;this.flushFrontBuffer(o,u,g)}}flushBackBuffer(e,t,i){const{details:n,sourceBuffer:r}=this;this.getSourceBufferTypes().forEach(u=>{const h=r[u];if(h){const p=at.getBuffered(h);if(p.length>0&&i>p.start(0)){if(this.hls.trigger(I.BACK_BUFFER_REACHED,{bufferEnd:i}),n!=null&&n.live)this.hls.trigger(I.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(h.ended&&p.end(p.length-1)-e<t*2){this.log(`Cannot flush ${u} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:u})}}})}flushFrontBuffer(e,t,i){const{sourceBuffer:n}=this;this.getSourceBufferTypes().forEach(o=>{const u=n[o];if(u){const h=at.getBuffered(u),p=h.length;if(p<2)return;const d=h.start(p-1),g=h.end(p-1);if(i>d||e>=d&&e<=g)return;if(u.ended&&e-g<2*t){this.log(`Cannot flush ${o} front buffer while SourceBuffer is in ended state`);return}this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:d,endOffset:1/0,type:o})}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")return;const{details:e,hls:t,media:i,mediaSource:n}=this,r=e.fragments[0].start+e.totalduration,o=i.duration,u=Ae(n.duration)?n.duration:0;e.live&&t.config.liveDurationInfinity?(n.duration=1/0,this.updateSeekableRange(e)):(r>u&&r>o||!Ae(o))&&(this.log(`Updating Media Source duration to ${r.toFixed(3)}`),n.duration=r)}updateSeekableRange(e){const t=this.mediaSource,i=e.fragments;if(i.length&&e.live&&t!=null&&t.setLiveSeekableRange){const r=Math.max(0,i[0].start),o=Math.max(r,r+e.totalduration);this.log(`Media Source duration is set to ${t.duration}. Setting seekable range to ${r}-${o}.`),t.setLiveSeekableRange(r,o)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:i}=this,n=Object.keys(i).length;if(n&&(!e||n===2||"audiovideo"in i)){this.createSourceBuffers(i),this.pendingTracks={};const r=this.getSourceBufferTypes();if(r.length)this.hls.trigger(I.BUFFER_CREATED,{tracks:this.tracks}),r.forEach(o=>{t.executeNext(o)});else{const o=new Error("could not create source buffer for media codec(s)");this.hls.trigger(I.ERROR,{type:xe.MEDIA_ERROR,details:te.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:o,reason:o.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(const r in e)if(!t[r]){var n;const o=e[r];if(!o)throw Error(`source buffer exists for track ${r}, however track does not`);let u=((n=o.levelCodec)==null?void 0:n.indexOf(","))===-1?o.levelCodec:o.codec;u&&r.slice(0,5)==="audio"&&(u=po(u,this.appendSource));const h=`${o.container};codecs=${u}`;this.log(`creating sourceBuffer(${h})`);try{const p=t[r]=i.addSourceBuffer(h),d=r;this.addBufferListener(d,"updatestart",this._onSBUpdateStart),this.addBufferListener(d,"updateend",this._onSBUpdateEnd),this.addBufferListener(d,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(d,"bufferedchange",(g,T)=>{const b=T.removedRanges;b!=null&&b.length&&this.hls.trigger(I.BUFFER_FLUSHED,{type:r})}),this.tracks[r]={buffer:p,codec:u,container:o.container,levelCodec:o.levelCodec,metadata:o.metadata,id:o.id}}catch(p){this.error(`error while trying to add sourceBuffer: ${p.message}`),this.hls.trigger(I.ERROR,{type:xe.MEDIA_ERROR,details:te.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:p,sourceBufferName:r,mimeType:h})}}}get mediaSrc(){var e,t;const i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i?.src}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const{operationQueue:i}=this;i.current(e).onComplete(),i.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){var i;const n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${n}`,t),this.hls.trigger(I.ERROR,{type:xe.MEDIA_ERROR,details:te.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const r=this.operationQueue.current(e);r&&r.onError(n)}removeExecutor(e,t,i){const{media:n,mediaSource:r,operationQueue:o,sourceBuffer:u}=this,h=u[e];if(!n||!r||!h){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),o.shiftAndExecuteNext(e);return}const p=Ae(n.duration)?n.duration:1/0,d=Ae(r.duration)?r.duration:1/0,g=Math.max(0,t),T=Math.min(i,p,d);T>g&&(!h.ending||h.ended)?(h.ended=!1,this.log(`Removing [${g},${T}] from the ${e} SourceBuffer`),h.remove(g,T)):o.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.sourceBuffer[t];if(!i){if(!this.pendingTracks[t])throw new Error(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);return}i.ended=!1,i.appendBuffer(e)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length){this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);return}const{operationQueue:i}=this,n=t.map(r=>i.appendBlocker(r));Promise.all(n).then(()=>{e(),t.forEach(r=>{const o=this.sourceBuffer[r];o!=null&&o.updating||i.shiftAndExecuteNext(r)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,i){const n=this.sourceBuffer[e];if(!n)return;const r=i.bind(this,e);this.listeners[e].push({event:t,listener:r}),n.addEventListener(t,r)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach(i=>{t.removeEventListener(i.event,i.listener)})}}function Bf(s){const e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t)})}function FS(s,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t)}const NS={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},bm=s=>String.fromCharCode(NS[s]||s),di=15,Gi=100,BS={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},US={17:2,18:4,21:6,22:8,23:10,19:13,20:15},HS={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},$S={25:2,26:4,29:6,30:8,31:10,27:13,28:15},jS=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class VS{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;W.log(`${this.time} [${e}] ${i}`)}}}const Gn=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class _m{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){const n=t[i];e.hasOwnProperty(n)&&(this[n]=e[n])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class GS{constructor(){this.uchar=" ",this.penState=new _m}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class KS{constructor(e){this.chars=[],this.pos=0,this.currPenState=new _m,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Gi;t++)this.chars.push(new GS);this.logger=e}equals(e){for(let t=0;t<Gi;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Gi;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Gi;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Gi&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Gi)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i<t+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=bm(e);if(this.pos>=Gi){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<Gi;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let i=0;i<Gi;i++){const n=this.chars[i].uchar;n!==" "&&(t=!1),e.push(n)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class vu{constructor(e){this.rows=[],this.currRow=di-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<di;t++)this.rows.push(new KS(e));this.logger=e}reset(){for(let e=0;e<di;e++)this.rows[e].clear();this.currRow=di-1}equals(e){let t=!0;for(let i=0;i<di;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<di;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<di;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+JSON.stringify(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let u=0;u<di;u++)this.rows[u].clear();const r=this.currRow+1-this.nrRollUpRows,o=this.lastOutputScreen;if(o){const u=o.rows[r].cueStartTime,h=this.logger.time;if(u!==null&&h!==null&&u<h)for(let p=0;p<this.nrRollUpRows;p++)this.rows[t-this.nrRollUpRows+p+1].copy(o.rows[r+p])}}this.currRow=t;const i=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,o=Math.max(r-1,0);i.setCursor(e.indent),e.color=i.chars[o].penState.foreground}const n={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(n)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+JSON.stringify(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());const 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=e||!1;const t=[];let i="",n=-1;for(let r=0;r<di;r++){const o=this.rows[r].getTextString();o&&(n=r+1,e?t.push("Row "+n+": '"+o+"'"):t.push(o.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
`)),i}getTextAndFormat(){return this.rows}}class Uf{constructor(e,t,i){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 vu(i),this.nonDisplayedMemory=new vu(i),this.lastOutputScreen=new vu(i),this.currRollUpRow=this.displayedMemory.rows[di-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[di-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 i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+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"){const 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){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,n=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=n[i]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const 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))}}class Hf{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=WS(),this.logger=void 0;const n=this.logger=new VS;this.channels=[null,new Uf(e,t,n),new Uf(e+1,i,n)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let i=0;i<t.length;i+=2){const n=t[i]&127,r=t[i+1]&127;let o=!1,u=null;if(n===0&&r===0)continue;this.logger.log(3,()=>"["+Gn([t[i],t[i+1]])+"] -> ("+Gn([n,r])+")");const h=this.cmdHistory;if(n>=16&&n<=31){if(qS(n,r,h)){Ia(null,null,h),this.logger.log(3,()=>"Repeated command ("+Gn([n,r])+") is dropped");continue}Ia(n,r,this.cmdHistory),o=this.parseCmd(n,r),o||(o=this.parseMidrow(n,r)),o||(o=this.parsePAC(n,r)),o||(o=this.parseBackgroundAttributes(n,r))}else Ia(null,null,h);if(!o&&(u=this.parseChars(n,r),u)){const d=this.currentChannel;d&&d>0?this.channels[d].insertChars(u):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!o&&!u&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Gn([n,r])+" orig: "+Gn([t[i],t[i+1]]))}}parseCmd(e,t){const i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=33&&t<=35;if(!(i||n))return!1;const r=e===20||e===21||e===23?1:2,o=this.channels[r];return e===20||e===21||e===28||e===29?t===32?o.ccRCL():t===33?o.ccBS():t===34?o.ccAOF():t===35?o.ccAON():t===36?o.ccDER():t===37?o.ccRU(2):t===38?o.ccRU(3):t===39?o.ccRU(4):t===40?o.ccFON():t===41?o.ccRDC():t===42?o.ccTR():t===43?o.ccRTD():t===44?o.ccEDM():t===45?o.ccCR():t===46?o.ccENM():t===47&&o.ccEOC():o.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const n=this.channels[i];return n?(n.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Gn([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i;const n=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(n||r))return!1;const o=e<=23?1:2;t>=64&&t<=95?i=o===1?BS[e]:HS[e]:i=o===1?US[e]:$S[e];const u=this.channels[o];return u?(u.setPAC(this.interpretPAC(i,t)),this.currentChannel=o,!0):!1}interpretPAC(e,t){let i;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,n.underline=(i&1)===1,i<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(n.italics=!0,n.color="white"):n.indent=Math.floor((i-16)/2)*4,n}parseChars(e,t){let i,n=null,r=null;if(e>=25?(i=2,r=e-8):(i=1,r=e),r>=17&&r<=19){let o;r===17?o=t+80:r===18?o=t+112:o=t+144,this.logger.log(2,()=>"Special char '"+bm(o)+"' in channel "+i),n=[o]}else e>=32&&e<=127&&(n=t===0?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes =  "+Gn(n).join(",")),n}parseBackgroundAttributes(e,t){const i=(e===16||e===24)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=45&&t<=47;if(!(i||n))return!1;let r;const o={};e===16||e===24?(r=Math.floor((t-32)/2),o.background=jS[r],t%2===1&&(o.background=o.background+"_semi")):t===45?o.background="transparent":(o.foreground="black",t===47&&(o.underline=!0));const u=e<=23?1:2;return this.channels[u].setBkgData(o),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Ia(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const i=this.channels[t];i&&i.cueSplitAtTime(e)}}}function Ia(s,e,t){t.a=s,t.b=e}function qS(s,e,t){return t.a===s&&t.b===e}function WS(){return{a:null,b:null}}class Ra{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,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var Qc=function(){if($s!=null&&$s.VTTCue)return self.VTTCue;const s=["","lr","rl"],e=["start","middle","end","left","right"];function t(u,h){if(typeof h!="string"||!Array.isArray(u))return!1;const p=h.toLowerCase();return~u.indexOf(p)?p:!1}function i(u){return t(s,u)}function n(u){return t(e,u)}function r(u,...h){let p=1;for(;p<arguments.length;p++){const d=arguments[p];for(const g in d)u[g]=d[g]}return u}function o(u,h,p){const d=this,g={enumerable:!0};d.hasBeenReset=!1;let T="",b=!1,E=u,w=h,A=p,L=null,P="",M=!0,O="auto",k="start",N=50,H="middle",G=50,B="middle";Object.defineProperty(d,"id",r({},g,{get:function(){return T},set:function(D){T=""+D}})),Object.defineProperty(d,"pauseOnExit",r({},g,{get:function(){return b},set:function(D){b=!!D}})),Object.defineProperty(d,"startTime",r({},g,{get:function(){return E},set:function(D){if(typeof D!="number")throw new TypeError("Start time must be set to a number.");E=D,this.hasBeenReset=!0}})),Object.defineProperty(d,"endTime",r({},g,{get:function(){return w},set:function(D){if(typeof D!="number")throw new TypeError("End time must be set to a number.");w=D,this.hasBeenReset=!0}})),Object.defineProperty(d,"text",r({},g,{get:function(){return A},set:function(D){A=""+D,this.hasBeenReset=!0}})),Object.defineProperty(d,"region",r({},g,{get:function(){return L},set:function(D){L=D,this.hasBeenReset=!0}})),Object.defineProperty(d,"vertical",r({},g,{get:function(){return P},set:function(D){const K=i(D);if(K===!1)throw new SyntaxError("An invalid or illegal string was specified.");P=K,this.hasBeenReset=!0}})),Object.defineProperty(d,"snapToLines",r({},g,{get:function(){return M},set:function(D){M=!!D,this.hasBeenReset=!0}})),Object.defineProperty(d,"line",r({},g,{get:function(){return O},set:function(D){if(typeof D!="number"&&D!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");O=D,this.hasBeenReset=!0}})),Object.defineProperty(d,"lineAlign",r({},g,{get:function(){return k},set:function(D){const K=n(D);if(!K)throw new SyntaxError("An invalid or illegal string was specified.");k=K,this.hasBeenReset=!0}})),Object.defineProperty(d,"position",r({},g,{get:function(){return N},set:function(D){if(D<0||D>100)throw new Error("Position must be between 0 and 100.");N=D,this.hasBeenReset=!0}})),Object.defineProperty(d,"positionAlign",r({},g,{get:function(){return H},set:function(D){const K=n(D);if(!K)throw new SyntaxError("An invalid or illegal string was specified.");H=K,this.hasBeenReset=!0}})),Object.defineProperty(d,"size",r({},g,{get:function(){return G},set:function(D){if(D<0||D>100)throw new Error("Size must be between 0 and 100.");G=D,this.hasBeenReset=!0}})),Object.defineProperty(d,"align",r({},g,{get:function(){return B},set:function(D){const K=n(D);if(!K)throw new SyntaxError("An invalid or illegal string was specified.");B=K,this.hasBeenReset=!0}})),d.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o}();class zS{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Em(s){function e(i,n,r,o){return(i|0)*3600+(n|0)*60+(r|0)+parseFloat(o||0)}const t=s.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class YS{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let n=0;n<i.length;++n)if(t===i[n]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}}function Sm(s,e,t,i){const n=i?s.split(i):[s];for(const r in n){if(typeof n[r]!="string")continue;const o=n[r].split(t);if(o.length!==2)continue;const u=o[0],h=o[1];e(u,h)}}const cc=new Qc(0,0,""),Pa=cc.align==="middle"?"middle":"center";function XS(s,e,t){const i=s;function n(){const u=Em(s);if(u===null)throw new Error("Malformed timestamp: "+i);return s=s.replace(/^[^\sa-zA-Z-]+/,""),u}function r(u,h){const p=new YS;Sm(u,function(T,b){let E;switch(T){case"region":for(let w=t.length-1;w>=0;w--)if(t[w].id===b){p.set(T,t[w].region);break}break;case"vertical":p.alt(T,b,["rl","lr"]);break;case"line":E=b.split(","),p.integer(T,E[0]),p.percent(T,E[0])&&p.set("snapToLines",!1),p.alt(T,E[0],["auto"]),E.length===2&&p.alt("lineAlign",E[1],["start",Pa,"end"]);break;case"position":E=b.split(","),p.percent(T,E[0]),E.length===2&&p.alt("positionAlign",E[1],["start",Pa,"end","line-left","line-right","auto"]);break;case"size":p.percent(T,b);break;case"align":p.alt(T,b,["start",Pa,"end","left","right"]);break}},/:/,/\s/),h.region=p.get("region",null),h.vertical=p.get("vertical","");let d=p.get("line","auto");d==="auto"&&cc.line===-1&&(d=-1),h.line=d,h.lineAlign=p.get("lineAlign","start"),h.snapToLines=p.get("snapToLines",!0),h.size=p.get("size",100),h.align=p.get("align",Pa);let g=p.get("position","auto");g==="auto"&&cc.position===50&&(g=h.align==="start"||h.align==="left"?0:h.align==="end"||h.align==="right"?100:50),h.position=g}function o(){s=s.replace(/^\s+/,"")}if(o(),e.startTime=n(),o(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);s=s.slice(3),o(),e.endTime=n(),o(),r(s,e)}function Cm(s){return s.replace(/<br(?: \/)?>/gi,`
`)}class QS{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new zS,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let r=t.buffer,o=0;for(r=Cm(r);o<r.length&&r[o]!=="\r"&&r[o]!==`
`;)++o;const u=r.slice(0,o);return r[o]==="\r"&&++o,r[o]===`
`&&++o,t.buffer=r.slice(o),u}function n(r){Sm(r,function(o,u){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=i();const u=r.match(/^(ï»¿)?WEBVTT([ \t].*)?$/);if(!(u!=null&&u[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let o=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(o?o=!1:r=i(),t.state){case"HEADER":/:/.test(r)?n(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new Qc(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{XS(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const u=r.indexOf("-->")!==-1;if(!r||u&&(o=!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+=r}continue;case"BADCUE":r||(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(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`

`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const JS=/\r\n|\n\r|\n|\r/g,Tu=function(e,t,i=0){return e.slice(i,i+t.length)===t},ZS=function(e){let t=parseInt(e.slice(-3));const i=parseInt(e.slice(-6,-4)),n=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!Ae(t)||!Ae(i)||!Ae(n)||!Ae(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*n,t+=60*60*1e3*r,t},bu=function(e){let t=5381,i=e.length;for(;i;)t=t*33^e.charCodeAt(--i);return(t>>>0).toString()};function Jc(s,e,t){return bu(s.toString())+bu(e.toString())+bu(t)}const eC=function(e,t,i){let n=e[t],r=e[n.prevCC];if(!r||!r.new&&n.new){e.ccOffset=e.presentationOffset=n.start,n.new=!1;return}for(;(o=r)!=null&&o.new;){var o;e.ccOffset+=n.start-r.start,n.new=!1,n=r,r=e[n.prevCC]}e.presentationOffset=i};function tC(s,e,t,i,n,r,o){const u=new QS,h=Oi(new Uint8Array(s)).trim().replace(JS,`
`).split(`
`),p=[],d=e?vS(e.baseTime,e.timescale):0;let g="00:00.000",T=0,b=0,E,w=!0;u.oncue=function(A){const L=t[i];let P=t.ccOffset;const M=(T-d)/9e4;if(L!=null&&L.new&&(b!==void 0?P=t.ccOffset=L.start:eC(t,i,M)),M){if(!e){E=new Error("Missing initPTS for VTT MPEGTS");return}P=M-t.presentationOffset}const O=A.endTime-A.startTime,k=ii((A.startTime+P-b)*9e4,n*9e4)/9e4;A.startTime=Math.max(k,0),A.endTime=Math.max(k+O,0);const N=A.text.trim();A.text=decodeURIComponent(encodeURIComponent(N)),A.id||(A.id=Jc(A.startTime,A.endTime,N)),A.endTime>0&&p.push(A)},u.onparsingerror=function(A){E=A},u.onflush=function(){if(E){o(E);return}r(p)},h.forEach(A=>{if(w)if(Tu(A,"X-TIMESTAMP-MAP=")){w=!1,A.slice(16).split(",").forEach(L=>{Tu(L,"LOCAL:")?g=L.slice(6):Tu(L,"MPEGTS:")&&(T=parseInt(L.slice(7)))});try{b=ZS(g)/1e3}catch(L){E=L}return}else A===""&&(w=!1);u.parse(A+`
`)}),u.flush()}const _u="stpp.ttml.im1t",wm=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Am=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,iC={left:"start",center:"center",right:"end",start:"start",end:"end"};function $f(s,e,t,i){const n=Ne(new Uint8Array(s),["mdat"]);if(n.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const r=n.map(u=>Oi(u)),o=yS(e.baseTime,1,e.timescale);try{r.forEach(u=>t(nC(u,o)))}catch(u){i(u)}}function nC(s,e){const n=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!n)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},o=Object.keys(r).reduce((g,T)=>(g[T]=n.getAttribute(`ttp:${T}`)||r[T],g),{}),u=n.getAttribute("xml:space")!=="preserve",h=jf(Eu(n,"styling","style")),p=jf(Eu(n,"layout","region")),d=Eu(n,"body","[begin]");return[].map.call(d,g=>{const T=Lm(g,u);if(!T||!g.hasAttribute("begin"))return null;const b=Cu(g.getAttribute("begin"),o),E=Cu(g.getAttribute("dur"),o);let w=Cu(g.getAttribute("end"),o);if(b===null)throw Vf(g);if(w===null){if(E===null)throw Vf(g);w=b+E}const A=new Qc(b-e,w-e,T);A.id=Jc(A.startTime,A.endTime,A.text);const L=p[g.getAttribute("region")],P=h[g.getAttribute("style")],M=sC(L,P,h),{textAlign:O}=M;if(O){const k=iC[O];k&&(A.lineAlign=k),A.align=O}return vt(A,M),A}).filter(g=>g!==null)}function Eu(s,e,t){const i=s.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function jf(s){return s.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function Lm(s,e){return[].slice.call(s.childNodes).reduce((t,i,n)=>{var r;return i.nodeName==="br"&&n?t+`
`:(r=i.childNodes)!=null&&r.length?Lm(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function sC(s,e,t){const i="http://www.w3.org/ns/ttml#styling";let n=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],o=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return o&&t.hasOwnProperty(o)&&(n=t[o]),r.reduce((u,h)=>{const p=Su(e,i,h)||Su(s,i,h)||Su(n,i,h);return p&&(u[h]=p),u},{})}function Su(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function Vf(s){return new Error(`Could not parse ttml timestamp ${s}`)}function Cu(s,e){if(!s)return null;let t=Em(s);return t===null&&(wm.test(s)?t=rC(s,e):Am.test(s)&&(t=aC(s,e))),t}function rC(s,e){const t=wm.exec(s),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function aC(s,e){const t=Am.exec(s),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}class oC{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=Kf(),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(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(I.FRAG_LOADING,this.onFragLoading,this),e.on(I.FRAG_LOADED,this.onFragLoaded,this),e.on(I.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(I.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(I.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(I.FRAG_LOADING,this.onFragLoading,this),e.off(I.FRAG_LOADED,this.onFragLoaded,this),e.off(I.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(I.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(I.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const e=new Ra(this,"textTrack1"),t=new Ra(this,"textTrack2"),i=new Ra(this,"textTrack3"),n=new Ra(this,"textTrack4");this.cea608Parser1=new Hf(1,e,t),this.cea608Parser2=new Hf(3,i,n)}}addCues(e,t,i,n,r){let o=!1;for(let u=r.length;u--;){const h=r[u],p=lC(h[0],h[1],t,i);if(p>=0&&(h[0]=Math.min(h[0],t),h[1]=Math.max(h[1],i),o=!0,p/(i-t)>.5))return}if(o||r.push([t,i]),this.config.renderTextTracksNatively){const u=this.captionsTracks[e];this.Cues.newCue(u,t,i,n)}else{const u=this.Cues.newCue(null,t,i,n);this.hls.trigger(I.CUES_PARSED,{type:"captions",cues:u,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r}){const{unparsedVttFrags:o}=this;i==="main"&&(this.initPTS[t.cc]={baseTime:n,timescale:r}),o.length&&(this.unparsedVttFrags=[],o.forEach(u=>{this.onFragLoaded(I.FRAG_LOADED,u)}))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let n=0;n<i.textTracks.length;n++){const r=i.textTracks[n];if(Gf(r,{name:e,lang:t}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,media:n}=this,{label:r,languageCode:o}=t[e],u=this.getExistingTrack(r,o);if(u)i[e]=u,Rs(i[e]),Wg(i[e],n);else{const h=this.createTextTrack("captions",r,o);h&&(h[e]=!0,i[e]=h)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i=t.label,n={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=n,this.hls.trigger(I.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[n]})}createTextTrack(e,t,i){const n=this.media;if(n)return n.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:e}=this;Object.keys(e).forEach(t=>{Rs(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Kf(),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(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let i=0;i<t.length;i++)Rs(t[i])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],n=i.some(r=>r.textCodec===_u);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(Tm(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const o=this.media,u=o?qa(o.textTracks):null;if(this.tracks.forEach((h,p)=>{let d;if(u){let g=null;for(let T=0;T<u.length;T++)if(u[T]&&Gf(u[T],h)){g=u[T],u[T]=null;break}g&&(d=g)}if(d)Rs(d);else{const g=km(h);d=this.createTextTrack(g,h.name,h.lang),d&&(d.mode="disabled")}d&&this.textTracks.push(d)}),u!=null&&u.length){const h=u.filter(p=>p!==null).map(p=>p.label);h.length&&W.warn(`Media element contains unused subtitle tracks: ${h.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const o=this.tracks.map(u=>({label:u.name,kind:u.type.toLowerCase(),default:u.default,subtitleTrack:u}));this.hls.trigger(I.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:o})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const n=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!n)return;const r=`textTrack${n[1]}`,o=this.captionsProperties[r];o&&(o.label=i.name,i.lang&&(o.languageCode=i.lang),o.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===Pe.MAIN){var i,n;const{cea608Parser1:r,cea608Parser2:o,lastSn:u}=this,{cc:h,sn:p}=t.frag,d=(i=(n=t.part)==null?void 0:n.index)!=null?i:-1;r&&o&&(p!==u+1||p===u&&d!==this.lastPartIndex+1||h!==this.lastCc)&&(r.reset(),o.reset()),this.lastCc=h,this.lastSn=p,this.lastPartIndex=d}}onFragLoaded(e,t){const{frag:i,payload:n}=t;if(i.type===Pe.SUBTITLE)if(n.byteLength){const r=i.decryptdata,o="stats"in t;if(r==null||!r.encrypted||o){const u=this.tracks[i.level],h=this.vttCCs;h[i.cc]||(h[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),u&&u.textCodec===_u?this._parseIMSC1(i,n):this._parseVTTs(t)}}else this.hls.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;$f(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),i.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{W.log(`Failed to parse IMSC1: ${n}`),i.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:n})})}_parseVTTs(e){var t;const{frag:i,payload:n}=e,{initPTS:r,unparsedVttFrags:o}=this,u=r.length-1;if(!r[i.cc]&&u===-1){o.push(e);return}const h=this.hls,p=(t=i.initSegment)!=null&&t.data?si(i.initSegment.data,new Uint8Array(n)):n;tC(p,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,d=>{this._appendCues(d,i.level),h.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},d=>{const g=d.message==="Missing initPTS for VTT MPEGTS";g?o.push(e):this._fallbackToIMSC1(i,n),W.log(`Failed to parse VTT cue: ${d}`),!(g&&u>i.cc)&&h.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:d})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||$f(t,this.initPTS[e.cc],()=>{i.textCodec=_u,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const n=this.textTracks[t];if(!n||n.mode==="disabled")return;e.forEach(r=>zg(n,r))}else{const n=this.tracks[t];if(!n)return;const r=n.default?"default":"subtitles"+t;i.trigger(I.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===Pe.SUBTITLE&&this.onFragLoaded(I.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){this.initCea608Parsers();const{cea608Parser1:i,cea608Parser2:n}=this;if(!this.enabled||!i||!n)return;const{frag:r,samples:o}=t;if(!(r.type===Pe.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let u=0;u<o.length;u++){const h=o[u].bytes;if(h){const p=this.extractCea608Data(h);i.addData(o[u].pts,p[0]),n.addData(o[u].pts,p[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:n,type:r}){const{media:o}=this;if(!(!o||o.currentTime<i)){if(!r||r==="video"){const{captionsTracks:u}=this;Object.keys(u).forEach(h=>nc(u[h],t,i))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:u}=this;Object.keys(u).forEach(h=>nc(u[h],t,n))}}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let n=2;for(let r=0;r<i;r++){const o=e[n++],u=127&e[n++],h=127&e[n++];if(u===0&&h===0)continue;if((4&o)!==0){const d=3&o;(d===0||d===1)&&(t[d].push(u),t[d].push(h))}}return t}}function km(s){return s.characteristics&&/transcribes-spoken-dialog/gi.test(s.characteristics)&&/describes-music-and-sound/gi.test(s.characteristics)?"captions":"subtitles"}function Gf(s,e){return!!s&&s.kind===km(e)&&uc(e,s)}function lC(s,e,t,i){return Math.min(e,i)-Math.max(s,t)}function Kf(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}class Zc{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=Number.POSITIVE_INFINITY,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(){const{hls:e}=this;e.on(I.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.BUFFER_CODECS,this.onBufferCodecs,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(I.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.BUFFER_CODECS,this.onBufferCodecs,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.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){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&Ae(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&W.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((n,r)=>this.isLevelAllowed(n)&&r<=e);return this.clientRect=null,Zc.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.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 e}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const n=(u,h)=>h?u.width!==h.width||u.height!==h.height:!0;let r=e.length-1;const o=Math.max(t,i);for(let u=0;u<e.length;u+=1){const h=e[u];if((h.width>=o||h.height>=o)&&n(h,e[u+1])){r=u;break}}return r}}class uC{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(I.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const n=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=n,n&&typeof n.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,i){const n=performance.now();if(t){if(this.lastTime){const r=n-this.lastTime,o=i-this.lastDroppedFrames,u=t-this.lastDecodedFrames,h=1e3*o/r,p=this.hls;if(p.trigger(I.FPS_DROP,{currentDropped:o,currentDecoded:u,totalDroppedFrames:i}),h>0&&o>p.config.fpsDroppedMonitoringThreshold*u){let d=p.currentLevel;W.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(p.autoLevelCapping===-1||p.autoLevelCapping>=d)&&(d=d-1,p.trigger(I.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:p.currentLevel}),p.autoLevelCapping=d,this.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}const Da="[eme]";class Ms{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=Ms.CDMCleanupPromise?[Ms.CDMCleanupPromise]:[],this.debug=W.debug.bind(W,Da),this.log=W.log.bind(W,Da),this.warn=W.warn.bind(W,Da),this.error=W.error.bind(W,Da),this.onMediaEncrypted=t=>{const{initDataType:i,initData:n}=t,r=`"${t.type}" event: init data type: "${i}"`;if(this.debug(r),n!==null){if(!this.keyFormatPromise){let o=Object.keys(this.keySystemAccessPromises);o.length||(o=Ea(this.config));const u=o.map(au).filter(h=>!!h);this.keyFormatPromise=this.getKeyFormatPromise(u)}this.keyFormatPromise.then(o=>{const u=su(o);let h,p;if(i==="sinf"){if(u!==Ye.FAIRPLAY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${u}`);return}const E=Tt(new Uint8Array(n));try{const w=Bc(JSON.parse(E).sinf),A=jg(w);if(!A)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");h=A.subarray(8,24),p=Ye.FAIRPLAY}catch(w){this.warn(`${r} Failed to parse sinf: ${w}`);return}}else{if(u!==Ye.WIDEVINE&&u!==Ye.PLAYREADY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${u}`);return}const E=H_(n),w=E.filter(L=>!!L.systemId&&ru(L.systemId)===u);w.length>1&&this.warn(`${r} Using first of ${w.length} pssh found for selected key-system ${u}`);const A=w[0];if(!A){E.length===0||E.some(L=>!L.systemId)?this.warn(`${r} contains incomplete or invalid pssh data`):this.log(`ignoring ${r} for ${E.map(L=>ru(L.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(p=ru(A.systemId),A.version===0&&A.data)if(p===Ye.WIDEVINE){const L=A.data.length-22;h=A.data.subarray(L,L+16)}else p===Ye.PLAYREADY&&(h=Og(A.data))}if(!p||!h){this.log(`Unable to handle ${r} with key-system ${u}`);return}const d=wi.hexDump(h),{keyIdToKeySessionPromise:g,mediaKeySessions:T}=this;let b=g[d];for(let E=0;E<T.length;E++){const w=T[E],A=w.decryptdata;if(!A.keyId)continue;const L=wi.hexDump(A.keyId);if(d===L||A.uri.replace(/-/g,"").indexOf(d)!==-1){if(b=g[L],A.pssh)break;delete g[L],A.pssh=new Uint8Array(n),A.keyId=h,b=g[d]=b.then(()=>this.generateRequestWithPreferredKeySession(w,i,n,"encrypted-event-key-match")),b.catch(P=>this.handleError(P));break}}if(!b){if(p!==u){this.log(`Ignoring "${r}" with ${p} init data for selected key-system ${u}`);return}b=g[d]=this.getKeySystemSelectionPromise([p]).then(({keySystem:E,mediaKeys:w})=>{var A;this.throwIfDestroyed();const L=new Ir("ISO-23001-7",d,(A=au(E))!=null?A:"");return L.pssh=new Uint8Array(n),L.keyId=h,this.attemptSetMediaKeys(E,w).then(()=>{this.throwIfDestroyed();const P=this.createMediaKeySessionContext({decryptdata:L,keySystem:E,mediaKeys:w});return this.generateRequestWithPreferredKeySession(P,i,n,"encrypted-event-no-match")})}),b.catch(E=>this.handleError(E))}})}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const 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(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(I.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(I.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(I.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(I.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,n=t[e];if(n)return n.licenseUrl;if(e===Ye.WIDEVINE&&i)return i}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(o,u,h)=>!!o&&h.indexOf(o)===u,n=t.map(o=>o.audioCodec).filter(i),r=t.map(o=>o.videoCodec).filter(i);return n.length+r.length===0&&r.push("avc1.42e01e"),new Promise((o,u)=>{const h=p=>{const d=p.shift();this.getMediaKeysPromise(d,n,r).then(g=>o({keySystem:d,mediaKeys:g})).catch(g=>{p.length?h(p):g instanceof Jt?u(g):u(new Jt({type:xe.KEY_SYSTEM_ERROR,details:te.KEY_SYSTEM_NO_ACCESS,error:g,fatal:!0},g.message))})};h(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let n=`Configured requestMediaKeySystemAccess is not a function ${i}`;return xg===null&&self.location.protocol==="http:"&&(n=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(n))}return i(e,t)}getMediaKeysPromise(e,t,i){const n=g_(e,t,i,this.config.drmSystemOptions),r=this.keySystemAccessPromises[e];let o=r?.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(n)}`),o=this.requestMediaKeySystemAccess(e,n);const u=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(h=>{this.log(`Failed to obtain access to key-system "${e}": ${h}`)}),o.then(h=>{this.log(`Access for key-system "${h.keySystem}" obtained`);const p=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),u.mediaKeys=h.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),p.then(g=>g?this.setMediaKeysServerCertificate(d,e,g):d))),u.mediaKeys.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),u.mediaKeys})}return o.then(()=>r.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${wi.hexDump(e.keyId||[])}`);const n=i.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),n=this.getKeyIdString(t),r="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(i,r,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return wi.hexDump(e.keyId)}updateKeySession(e,t){var i;const n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyID ${wi.hexDump(((i=e.decryptdata)==null?void 0:i.keyId)||[])}
      } (data length: ${t&&t.byteLength})`),n.update(t)}selectKeySystemFormat(e){const 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.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,i)=>{const n=Ea(this.config),r=e.map(su).filter(o=>!!o&&n.indexOf(o)!==-1);return this.getKeySystemSelectionPromise(r).then(({keySystem:o})=>{const u=au(o);u?t(u):i(new Error(`Unable to find format for key-system "${o}"`))}).catch(i)})}loadKey(e){const t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),n=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);let r=this.keyIdToKeySessionPromise[i];return r||(r=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then(({keySystem:o,mediaKeys:u})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(o,u).then(()=>{this.throwIfDestroyed();const h=this.createMediaKeySessionContext({keySystem:o,mediaKeys:u,decryptdata:t});return this.generateRequestWithPreferredKeySession(h,"cenc",t.pssh,"playlist-key")}))),r.catch(o=>this.handleError(o))),r}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Jt?this.hls.trigger(I.ERROR,e.data):this.hls.trigger(I.ERROR,{type:xe.KEY_SYSTEM_ERROR,details:te.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const n=su(e.keyFormat),r=n?[n]:Ea(this.config);return this.attemptKeySystemAccess(r)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Ea(this.config)),e.length===0)throw new Jt({type:xe.KEY_SYSTEM_ERROR,details:te.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const n=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(n),n.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>i.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,i,n){var r,o;const u=(r=this.config.drmSystems)==null||(o=r[e.keySystem])==null?void 0:o.generateRequest;if(u)try{const E=u.call(this.hls,t,i,e);if(!E)throw new Error("Invalid response from configured generateRequest filter");t=E.initDataType,i=e.decryptdata.pssh=E.initData?new Uint8Array(E.initData):null}catch(E){var h;if(this.warn(E.message),(h=this.hls)!=null&&h.config.debug)throw E}if(i===null)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e);const p=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${n}": ${p} (init data type: ${t} length: ${i?i.byteLength:null})`);const d=new Xc,g=e._onmessage=E=>{const w=e.mediaKeysSession;if(!w){d.emit("error",new Error("invalid state"));return}const{messageType:A,message:L}=E;this.log(`"${A}" message event for session "${w.sessionId}" message size: ${L.byteLength}`),A==="license-request"||A==="license-renewal"?this.renewLicense(e,L).catch(P=>{this.handleError(P),d.emit("error",P)}):A==="license-release"?e.keySystem===Ye.FAIRPLAY&&(this.updateKeySession(e,tc("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${A}"`)},T=e._onkeystatuseschange=E=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const A=e.keyStatus;d.emit("keyStatus",A),A==="expired"&&(this.warn(`${e.keySystem} expired for key ${p}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",g),e.mediaKeysSession.addEventListener("keystatuseschange",T);const b=new Promise((E,w)=>{d.on("error",w),d.on("keyStatus",A=>{A.startsWith("usable")?E():A==="output-restricted"?w(new Jt({type:xe.KEY_SYSTEM_ERROR,details:te.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):A==="internal-error"?w(new Jt({type:xe.KEY_SYSTEM_ERROR,details:te.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${A}"`)):A==="expired"?w(new Error("key expired while generating request")):this.warn(`unhandled key status change "${A}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var E;this.log(`Request generated for key-session "${(E=e.mediaKeysSession)==null?void 0:E.sessionId}" keyId: ${p}`)}).catch(E=>{throw new Jt({type:xe.KEY_SYSTEM_ERROR,details:te.KEY_SYSTEM_NO_SESSION,error:E,fatal:!1},`Error generating key-session request: ${E}`)}).then(()=>b).catch(E=>{throw d.removeAllListeners(),this.removeSession(e),E}).then(()=>(d.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${wi.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${wi.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,i=t.loader,n=new i(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((o,u)=>{const h={responseType:"arraybuffer",url:r},p=t.certLoadPolicy.default,d={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(T,b,E,w)=>{o(T.data)},onError:(T,b,E,w)=>{u(new Jt({type:xe.KEY_SYSTEM_ERROR,details:te.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:E,response:St({url:h.url,data:void 0},T)},`"${e}" certificate request failed (${r}). Status: ${T.code} (${T.text})`))},onTimeout:(T,b,E)=>{u(new Jt({type:xe.KEY_SYSTEM_ERROR,details:te.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:E,response:{url:h.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(T,b,E)=>{u(new Error("aborted"))}};n.load(h,d,g)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((n,r)=>{e.setServerCertificate(i).then(o=>{this.log(`setServerCertificate ${o?"success":"not supported by CDM"} (${i?.byteLength}) on "${t}"`),n(e)}).catch(o=>{r(new Jt({type:xe.KEY_SYSTEM_ERROR,details:te.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:o,fatal:!0},o.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(n=>{throw new Jt({type:xe.KEY_SYSTEM_ERROR,details:te.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:n,fatal:!0},n.message)}))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const n=new DOMParser().parseFromString(i,"application/xml"),r=n.querySelectorAll("HttpHeader");if(r.length>0){let d;for(let g=0,T=r.length;g<T;g++){var o,u;d=r[g];const b=(o=d.querySelector("name"))==null?void 0:o.textContent,E=(u=d.querySelector("value"))==null?void 0:u.textContent;b&&E&&e.setRequestHeader(b,E)}}const h=n.querySelector("Challenge"),p=h?.textContent;if(!p)throw new Error("Cannot find <Challenge> in key message");return tc(atob(p))}setupLicenseXHR(e,t,i,n){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,i,n)}).catch(o=>{if(!i.decryptdata)throw o;return e.open("POST",t,!0),r.call(this.hls,e,t,i,n)}).then(o=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:o||n})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((n,r)=>{const o=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${o}`);const u=new XMLHttpRequest;u.responseType="arraybuffer",u.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(u.readyState===4)if(u.status===200){this._requestLicenseFailureCount=0;let h=u.response;this.log(`License received ${h instanceof ArrayBuffer?h.byteLength:h}`);const p=this.config.licenseResponseCallback;if(p)try{h=p.call(this.hls,u,o,e)}catch(d){this.error(d)}n(h)}else{const h=i.errorRetry,p=h?h.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>p||u.status>=400&&u.status<500)r(new Jt({type:xe.KEY_SYSTEM_ERROR,details:te.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:u,response:{url:o,data:void 0,code:u.status,text:u.statusText}},`License Request XHR failed (${o}). Status: ${u.status} (${u.statusText})`));else{const d=p-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${d} attempts left`),this.requestLicense(e,t).then(n,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=u,this.setupLicenseXHR(u,o,e,t).then(({xhr:h,licenseChallenge:p})=>{e.keySystem==Ye.PLAYREADY&&(p=this.unpackPlayReadyKeyMessage(h,p)),h.send(p)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,i.removeEventListener("encrypted",this.onMediaEncrypted),i.removeEventListener("waitingforkey",this.onWaitingForKey),i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Ir.clearKeyUriToKeyIdMap();const i=t.length;Ms.CDMCleanupPromise=Promise.all(t.map(n=>this.removeSession(n)).concat(e?.setMediaKeys(null).catch(n=>{this.log(`Could not clear media keys: ${n}`)}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(n=>{this.log(`Could not close sessions and clear media keys: ${n}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((n,r)=>(n.indexOf(r.keyFormat)===-1&&n.push(r.keyFormat),n),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const n=this.mediaKeySessions.indexOf(e);return n>-1&&this.mediaKeySessions.splice(n,1),t.remove().catch(r=>{this.log(`Could not remove session: ${r}`)}).then(()=>t.close()).catch(r=>{this.log(`Could not close session: ${r}`)})}}}Ms.CDMCleanupPromise=void 0;class Jt extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}var Dt;(function(s){s.MANIFEST="m",s.AUDIO="a",s.VIDEO="v",s.MUXED="av",s.INIT="i",s.CAPTION="c",s.TIMED_TEXT="tt",s.KEY="k",s.OTHER="o"})(Dt||(Dt={}));var hc;(function(s){s.DASH="d",s.HLS="h",s.SMOOTH="s",s.OTHER="o"})(hc||(hc={}));var Qn;(function(s){s.OBJECT="CMCD-Object",s.REQUEST="CMCD-Request",s.SESSION="CMCD-Session",s.STATUS="CMCD-Status"})(Qn||(Qn={}));const cC={[Qn.OBJECT]:["br","d","ot","tb"],[Qn.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Qn.SESSION]:["cid","pr","sf","sid","st","v"],[Qn.STATUS]:["bs","rtp"]};class Vs{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(i=>i instanceof Vs?i:new Vs(i))),this.value=e,this.params=t}}class Im{constructor(e){this.description=void 0,this.description=e}}const hC="Dict";function dC(s){return Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":typeof s=="object"?JSON.stringify(s):String(s)}function fC(s,e,t,i){return new Error(`failed to ${s} "${dC(e)}" as ${t}`,{cause:i})}const qf="Bare Item",pC="Boolean",gC="Byte Sequence",mC="Decimal",yC="Integer";function vC(s){return s<-999999999999999||999999999999999<s}const TC=/[\x00-\x1f\x7f]+/,bC="Token",_C="Key";function Mi(s,e,t){return fC("serialize",s,e,t)}function EC(s){if(typeof s!="boolean")throw Mi(s,pC);return s?"?1":"?0"}function SC(s){return btoa(String.fromCharCode(...s))}function CC(s){if(ArrayBuffer.isView(s)===!1)throw Mi(s,gC);return`:${SC(s)}:`}function Rm(s){if(vC(s))throw Mi(s,yC);return s.toString()}function wC(s){return`@${Rm(s.getTime()/1e3)}`}function Pm(s,e){if(s<0)return-Pm(-s,e);const t=Math.pow(10,e);if(Math.abs(s*t%1-.5)<Number.EPSILON){const n=Math.floor(s*t);return(n%2===0?n:n+1)/t}else return Math.round(s*t)/t}function AC(s){const e=Pm(s,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Mi(s,mC);const t=e.toString();return t.includes(".")?t:`${t}.0`}const LC="String";function kC(s){if(TC.test(s))throw Mi(s,LC);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function IC(s){return s.description||s.toString().slice(7,-1)}function Wf(s){const e=IC(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Mi(e,bC);return e}function dc(s){switch(typeof s){case"number":if(!Ae(s))throw Mi(s,qf);return Number.isInteger(s)?Rm(s):AC(s);case"string":return kC(s);case"symbol":return Wf(s);case"boolean":return EC(s);case"object":if(s instanceof Date)return wC(s);if(s instanceof Uint8Array)return CC(s);if(s instanceof Im)return Wf(s);default:throw Mi(s,qf)}}function fc(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw Mi(s,_C);return s}function eh(s){return s==null?"":Object.entries(s).map(([e,t])=>t===!0?`;${fc(e)}`:`;${fc(e)}=${dc(t)}`).join("")}function Dm(s){return s instanceof Vs?`${dc(s.value)}${eh(s.params)}`:dc(s)}function RC(s){return`(${s.value.map(Dm).join(" ")})${eh(s.params)}`}function PC(s,e={whitespace:!0}){if(typeof s!="object")throw Mi(s,hC);const t=s instanceof Map?s.entries():Object.entries(s),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([n,r])=>{r instanceof Vs||(r=new Vs(r));let o=fc(n);return r.value===!0?o+=eh(r.params):(o+="=",Array.isArray(r.value)?o+=RC(r):o+=Dm(r)),o}).join(`,${i}`)}function DC(s,e){return PC(s,e)}const xC=s=>s==="ot"||s==="sf"||s==="st",OC=s=>typeof s=="number"?Ae(s):s!=null&&s!==""&&s!==!1;function MC(s,e){const t=new URL(s),i=new URL(e);if(t.origin!==i.origin)return s;const n=t.pathname.split("/").slice(1),r=i.pathname.split("/").slice(1,-1);for(;n[0]===r[0];)n.shift(),r.shift();for(;r.length;)r.shift(),n.unshift("..");return n.join("/")}function FC(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(n=="x"?r:r&3|8).toString(16)})}}}const Ja=s=>Math.round(s),NC=(s,e)=>(e!=null&&e.baseUrl&&(s=MC(s,e.baseUrl)),encodeURIComponent(s)),xa=s=>Ja(s/100)*100,BC={br:Ja,d:Ja,bl:xa,dl:xa,mtp:xa,nor:NC,rtp:xa,tb:Ja};function UC(s,e){const t={};if(s==null||typeof s!="object")return t;const i=Object.keys(s).sort(),n=vt({},BC,e?.formatters),r=e?.filter;return i.forEach(o=>{if(r!=null&&r(o))return;let u=s[o];const h=n[o];h&&(u=h(u,e)),!(o==="v"&&u===1)&&(o=="pr"&&u===1||OC(u)&&(xC(o)&&typeof u=="string"&&(u=new Im(u)),t[o]=u))}),t}function xm(s,e={}){return s?DC(UC(s,e),vt({whitespace:!1},e)):""}function HC(s,e={}){if(!s)return{};const t=Object.entries(s),i=Object.entries(cC).concat(Object.entries(e?.customHeaderMap||{})),n=t.reduce((r,o)=>{var u,h;const[p,d]=o,g=((u=i.find(T=>T[1].includes(p)))==null?void 0:u[0])||Qn.REQUEST;return(h=r[g])!=null||(r[g]={}),r[g][p]=d,r},{});return Object.entries(n).reduce((r,[o,u])=>(r[o]=xm(u,e),r),{})}function $C(s,e,t){return vt(s,HC(e,t))}const jC="CMCD";function VC(s,e={}){if(!s)return"";const t=xm(s,e);return`${jC}=${encodeURIComponent(t)}`}const zf=/CMCD=[^&#]+/;function GC(s,e,t){const i=VC(e,t);if(!i)return s;if(zf.test(s))return s.replace(zf,i);const n=s.includes("?")?"&":"?";return`${s}${n}${i}`}class KC{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||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=n=>{try{this.apply(n,{ot:Dt.MANIFEST,su:!this.initialized})}catch(r){W.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=n=>{try{const r=n.frag,o=this.hls.levels[r.level],u=this.getObjectType(r),h={d:r.duration*1e3,ot:u};(u===Dt.VIDEO||u===Dt.AUDIO||u==Dt.MUXED)&&(h.br=o.bitrate/1e3,h.tb=this.getTopBandwidth(u)/1e3,h.bl=this.getBufferLength(u)),this.apply(n,h)}catch(r){W.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||FC(),this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHED,this.onMediaDetached,this),e.on(I.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHED,this.onMediaDetached,this),e.off(I.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=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),this.media=null)}onBufferCreated(e,t){var i,n;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(n=t.tracks.video)==null?void 0:n.buffer}createData(){var e;return{v:1,sf:hc.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){vt(t,this.createData());const i=t.ot===Dt.INIT||t.ot===Dt.VIDEO||t.ot===Dt.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:n}=this;n&&(t=Object.keys(t).reduce((r,o)=>(n.includes(o)&&(r[o]=t[o]),r),{})),this.useHeaders?(e.headers||(e.headers={}),$C(e.headers,t)):e.url=GC(e.url,t)}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Dt.TIMED_TEXT;if(e.sn==="initSegment")return Dt.INIT;if(t==="audio")return Dt.AUDIO;if(t==="main")return this.hls.audioTracks.length?Dt.VIDEO:Dt.MUXED}getTopBandwidth(e){let t=0,i;const n=this.hls;if(e===Dt.AUDIO)i=n.audioTracks;else{const r=n.maxAutoLevel,o=r>-1?r+1:n.levels.length;i=n.levels.slice(0,o)}for(const r of i)r.bitrate>t&&(t=r.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.hls.media,i=e===Dt.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:at.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,o,u){t(r),this.loader.load(r,o,u)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,o,u){t(r),this.loader.load(r,o,u)}}}}const qC=3e5;class WC{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=W.log.bind(W,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const 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(),this.loader=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){const t=this.levels;t&&(this.levels=t.filter(i=>i!==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){const{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if(i?.action===Lt.SendAlternateToPenaltyBox&&i.flags===hi.MoveAllAlternatesMatchingHost){const n=this.levels;let r=this.pathwayPriority,o=this.pathwayId;if(t.context){const{groupId:u,pathwayId:h,type:p}=t.context;u&&n?o=this.getPathwayForGroupId(u,p,o):h&&(o=h)}o in this.penalizedPathways||(this.penalizedPathways[o]=performance.now()),!r&&n&&(r=n.reduce((u,h)=>(u.indexOf(h.pathwayId)===-1&&u.push(h.pathwayId),u),[])),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==o),i.resolved||W.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${o} levels: ${n&&n.length} priorities: ${JSON.stringify(r)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}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;const i=this.penalizedPathways,n=performance.now();Object.keys(i).forEach(r=>{n-i[r]>qC&&delete i[r]});for(let r=0;r<e.length;r++){const o=e[r];if(o in i)continue;if(o===this.pathwayId)return;const u=this.hls.nextLoadLevel,h=this.hls.levels[u];if(t=this.getLevelsForPathway(o),t.length>0){this.log(`Setting Pathway to "${o}"`),this.pathwayId=o,Jg(t),this.hls.trigger(I.LEVELS_UPDATED,{levels:t});const p=this.hls.levels[u];h&&p&&this.levels&&(p.attrs["STABLE-VARIANT-ID"]!==h.attrs["STABLE-VARIANT-ID"]&&p.bitrate!==h.bitrate&&this.log(`Unstable Pathways change from bitrate ${h.bitrate} to ${p.bitrate}`),this.hls.nextLoadLevel=u);break}}}getPathwayForGroupId(e,t,i){const n=this.getLevelsForPathway(i).concat(this.levels||[]);for(let r=0;r<n.length;r++)if(t===qe.AUDIO_TRACK&&n[r].hasAudioGroup(e)||t===qe.SUBTITLE_TRACK&&n[r].hasSubtitleGroup(e))return n[r].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},n={};e.forEach(r=>{const{ID:o,"BASE-ID":u,"URI-REPLACEMENT":h}=r;if(t.some(d=>d.pathwayId===o))return;const p=this.getLevelsForPathway(u).map(d=>{const g=new ct(d.attrs);g["PATHWAY-ID"]=o;const T=g.AUDIO&&`${g.AUDIO}_clone_${o}`,b=g.SUBTITLES&&`${g.SUBTITLES}_clone_${o}`;T&&(i[g.AUDIO]=T,g.AUDIO=T),b&&(n[g.SUBTITLES]=b,g.SUBTITLES=b);const E=Om(d.uri,g["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",h),w=new js({attrs:g,audioCodec:d.audioCodec,bitrate:d.bitrate,height:d.height,name:d.name,url:E,videoCodec:d.videoCodec,width:d.width});if(d.audioGroups)for(let A=1;A<d.audioGroups.length;A++)w.addGroupId("audio",`${d.audioGroups[A]}_clone_${o}`);if(d.subtitleGroups)for(let A=1;A<d.subtitleGroups.length;A++)w.addGroupId("text",`${d.subtitleGroups[A]}_clone_${o}`);return w});t.push(...p),Yf(this.audioTracks,i,h,o),Yf(this.subtitleTracks,n,h,o)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let n;try{n=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(n.protocol!=="data:"){const d=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+d)}const r={responseType:"json",url:n.href},o=t.steeringManifestLoadPolicy.default,u=o.errorRetry||o.timeoutRetry||{},h={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:u.maxNumRetry||0,retryDelay:u.retryDelayMs||0,maxRetryDelay:u.maxRetryDelayMs||0},p={onSuccess:(d,g,T,b)=>{this.log(`Loaded steering manifest: "${n}"`);const E=d.data;if(E.VERSION!==1){this.log(`Steering VERSION ${E.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=E.TTL;const{"RELOAD-URI":w,"PATHWAY-CLONES":A,"PATHWAY-PRIORITY":L}=E;if(w)try{this.uri=new self.URL(w,n).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${w}`);return}this.scheduleRefresh(this.uri||T.url),A&&this.clonePathways(A);const P={steeringManifest:E,url:n.toString()};this.hls.trigger(I.STEERING_MANIFEST_LOADED,P),L&&this.updatePathwayPriority(L)},onError:(d,g,T,b)=>{if(this.log(`Error loading steering manifest: ${d.code} ${d.text} (${g.url})`),this.stopLoad(),d.code===410){this.enabled=!1,this.log(`Steering manifest ${g.url} no longer available`);return}let E=this.timeToLoad*1e3;if(d.code===429){const w=this.loader;if(typeof w?.getResponseHeader=="function"){const A=w.getResponseHeader("Retry-After");A&&(E=parseFloat(A)*1e3)}this.log(`Steering manifest ${g.url} rate limited`);return}this.scheduleRefresh(this.uri||g.url,E)},onTimeout:(d,g,T)=>{this.log(`Timeout loading steering manifest (${g.url})`),this.scheduleRefresh(this.uri||g.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(r,h,p)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const n=(i=this.hls)==null?void 0:i.media;if(n&&!n.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Yf(s,e,t,i){s&&Object.keys(e).forEach(n=>{const r=s.filter(o=>o.groupId===n).map(o=>{const u=vt({},o);return u.details=void 0,u.attrs=new ct(u.attrs),u.url=u.attrs.URI=Om(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),u.groupId=u.attrs["GROUP-ID"]=e[n],u.attrs["PATHWAY-ID"]=i,u});s.push(...r)})}function Om(s,e,t,i){const{HOST:n,PARAMS:r,[t]:o}=i;let u;e&&(u=o?.[e],u&&(s=u));const h=new self.URL(s);return n&&!u&&(h.host=n),r&&Object.keys(r).sort().forEach(p=>{p&&h.searchParams.set(p,r[p])}),h.href}const zC=/^age:\s*[\d.]+\s*$/im;class Mm{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 xo,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const 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,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return r(i,t.url)}).catch(o=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),r(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(o=>{this.callbacks.onError({code:i.status,text:o.message},t,i,n)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const n=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:o}=i.loadPolicy;if(n)for(const u in n)e.setRequestHeader(u,n[u]);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),i.timeout=r&&Ae(r)?r:o,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const n=t.readyState,r=this.config;if(!i.aborted&&n>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),n===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const o=t.status,u=t.responseType==="text"?t.responseText:null;if(o>=200&&o<300){const g=u??t.response;if(g!=null){i.loading.end=Math.max(self.performance.now(),i.loading.first);const T=t.responseType==="arraybuffer"?g.byteLength:g.length;if(i.loaded=i.total=T,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;const b=this.callbacks.onProgress;if(b&&b(i,e,g,t),!this.callbacks)return;const E={url:t.responseURL,data:g,code:o};this.callbacks.onSuccess(E,i,e,t);return}}const h=r.loadPolicy.errorRetry,p=i.retry,d={url:e.url,data:void 0,code:o};yo(h,p,!1,d)?this.retry(h):(W.error(`${o} while loading ${e.url}`),this.callbacks.onError({code:o,text:t.statusText},e,t,i))}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(yo(e,t,!0))this.retry(e);else{var i;W.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=$c(e,i.retry),i.retry++,W.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${i.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){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&zC.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}function YC(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const XC=/(\d+)-(\d+)\/(\d+)/;class Xf{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||ew,this.controller=new self.AbortController,this.stats=new xo}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,i){const n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();const r=QC(e,this.controller.signal),o=i.onProgress,u=e.responseType==="arraybuffer",h=u?"byteLength":"length",{maxTimeToFirstByteMs:p,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=p&&Ae(p)?p:d,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(n,e,this.response)},t.timeout),self.fetch(this.request).then(g=>{this.response=this.loader=g;const T=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(n,e,this.response)},d-(T-n.loading.start)),!g.ok){const{status:b,statusText:E}=g;throw new tw(E||"fetch, bad network response",b,g)}return n.loading.first=T,n.total=ZC(g.headers)||n.total,o&&Ae(t.highWaterMark)?this.loadProgressively(g,n,e,t.highWaterMark,o):u?g.arrayBuffer():e.responseType==="json"?g.json():g.text()}).then(g=>{const T=this.response;if(!T)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const b=g[h];b&&(n.loaded=n.total=b);const E={url:T.url,data:g,code:T.status};o&&!Ae(t.highWaterMark)&&o(n,e,g,T),i.onSuccess(E,n,e,T)}).catch(g=>{if(self.clearTimeout(this.requestTimeout),n.aborted)return;const T=g&&g.code||0,b=g?g.message:null;i.onError({code:T,text:b},e,g?g.details:null,n)})}getCacheAge(){let e=null;if(this.response){const 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,i,n=0,r){const o=new im,u=e.body.getReader(),h=()=>u.read().then(p=>{if(p.done)return o.dataLength&&r(t,i,o.flush(),e),Promise.resolve(new ArrayBuffer(0));const d=p.value,g=d.length;return t.loaded+=g,g<n||o.dataLength?(o.push(d),o.dataLength>=n&&r(t,i,o.flush(),e)):r(t,i,d,e),h()}).catch(()=>Promise.reject());return h()}}function QC(s,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(vt({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function JC(s){const e=XC.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function ZC(s){const e=s.get("Content-Range");if(e){const i=JC(e);if(Ae(i))return i}const t=s.get("Content-Length");if(t)return parseInt(t)}function ew(s,e){return new self.Request(s.url,e)}class tw extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const iw=/\s/,nw={newCue(s,e,t,i){const n=[];let r,o,u,h,p;const d=self.VTTCue||self.TextTrackCue;for(let T=0;T<i.rows.length;T++)if(r=i.rows[T],u=!0,h=0,p="",!r.isEmpty()){var g;for(let w=0;w<r.chars.length;w++)iw.test(r.chars[w].uchar)&&u?h++:(p+=r.chars[w].uchar,u=!1);r.cueStartTime=e,e===t&&(t+=1e-4),h>=16?h--:h++;const b=Cm(p.trim()),E=Jc(e,t,b);s!=null&&(g=s.cues)!=null&&g.getCueById(E)||(o=new d(e,t,b),o.id=E,o.line=T+1,o.align="left",o.position=10+Math.min(80,Math.floor(h*8/32)*10),n.push(o))}return s&&n.length&&(n.sort((T,b)=>T.line==="auto"||b.line==="auto"?0:T.line>8&&b.line>8?b.line-T.line:T.line-b.line),n.forEach(T=>zg(s,T))),n}},sw={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Fm=St(St({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:Mm,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:PE,bufferController:MS,capLevelController:Zc,errorController:TE,fpsController:uC,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:xg,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:sw},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},rw()),{},{subtitleStreamController:PS,subtitleTrackController:xS,timelineController:oC,audioStreamController:IS,audioTrackController:RS,emeController:Ms,cmcdController:KC,contentSteeringController:WC});function rw(){return{cueHandler:nw,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 aw(s,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const t=pc(s),i=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(r=>{const o=`${r==="level"?"playlist":r}LoadPolicy`,u=e[o]===void 0,h=[];n.forEach(p=>{const d=`${r}Loading${p}`,g=e[d];if(g!==void 0&&u){h.push(d);const T=t[o].default;switch(e[o]={default:T},p){case"TimeOut":T.maxLoadTimeMs=g,T.maxTimeToFirstByteMs=g;break;case"MaxRetry":T.errorRetry.maxNumRetry=g,T.timeoutRetry.maxNumRetry=g;break;case"RetryDelay":T.errorRetry.retryDelayMs=g,T.timeoutRetry.retryDelayMs=g;break;case"MaxRetryTimeout":T.errorRetry.maxRetryDelayMs=g,T.timeoutRetry.maxRetryDelayMs=g;break}}}),h.length&&W.warn(`hls.js config: "${h.join('", "')}" setting(s) are deprecated, use "${o}": ${JSON.stringify(e[o])}`)}),St(St({},t),e)}function pc(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(pc):Object.keys(s).reduce((e,t)=>(e[t]=pc(s[t]),e),{}):s}function ow(s){const e=s.loader;e!==Xf&&e!==Mm?(W.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):YC()&&(s.loader=Xf,s.progressive=!0,s.enableSoftwareAES=!0,W.log("[config]: Progressive streaming enabled, using FetchLoader"))}let wu;class lw extends jc{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(){const{hls:e}=this;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this),e.on(I.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this),e.off(I.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.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){const i=this.hls.config.preferManagedMediaSource,n=[],r={},o={};let u=!1,h=!1,p=!1;t.levels.forEach(d=>{var g,T;const b=d.attrs;let{audioCodec:E,videoCodec:w}=d;((g=E)==null?void 0:g.indexOf("mp4a.40.34"))!==-1&&(wu||(wu=/chrome|firefox/i.test(navigator.userAgent)),wu&&(d.audioCodec=E=void 0)),E&&(d.audioCodec=E=po(E,i)),((T=w)==null?void 0:T.indexOf("avc1"))===0&&(w=d.videoCodec=z_(w));const{width:A,height:L,unknownCodecs:P}=d;if(u||(u=!!(A&&L)),h||(h=!!w),p||(p=!!E),P!=null&&P.length||E&&!cu(E,"audio",i)||w&&!cu(w,"video",i))return;const{CODECS:M,"FRAME-RATE":O,"HDCP-LEVEL":k,"PATHWAY-ID":N,RESOLUTION:H,"VIDEO-RANGE":G}=b,D=`${`${N||"."}-`}${d.bitrate}-${H}-${O}-${M}-${G}-${k}`;if(r[D])if(r[D].uri!==d.url&&!d.attrs["PATHWAY-ID"]){const K=o[D]+=1;d.attrs["PATHWAY-ID"]=new Array(K+1).join(".");const oe=new js(d);r[D]=oe,n.push(oe)}else r[D].addGroupId("audio",b.AUDIO),r[D].addGroupId("text",b.SUBTITLES);else{const K=new js(d);r[D]=K,o[D]=1,n.push(K)}}),this.filterAndSortMediaOptions(n,t,u,h,p)}filterAndSortMediaOptions(e,t,i,n,r){let o=[],u=[],h=e;if((i||n)&&r&&(h=h.filter(({videoCodec:E,videoRange:w,width:A,height:L})=>(!!E||!!(A&&L))&&oE(w))),h.length===0){Promise.resolve().then(()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);const E=new Error("no level with compatible codecs found in manifest");this.hls.trigger(I.ERROR,{type:xe.MEDIA_ERROR,details:te.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:E,reason:E.message})}});return}if(t.audioTracks){const{preferManagedMediaSource:E}=this.hls.config;o=t.audioTracks.filter(w=>!w.audioCodec||cu(w.audioCodec,"audio",E)),Qf(o)}t.subtitles&&(u=t.subtitles,Qf(u));const p=h.slice(0);h.sort((E,w)=>{if(E.attrs["HDCP-LEVEL"]!==w.attrs["HDCP-LEVEL"])return(E.attrs["HDCP-LEVEL"]||"")>(w.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&E.height!==w.height)return E.height-w.height;if(E.frameRate!==w.frameRate)return E.frameRate-w.frameRate;if(E.videoRange!==w.videoRange)return go.indexOf(E.videoRange)-go.indexOf(w.videoRange);if(E.videoCodec!==w.videoCodec){const A=sf(E.videoCodec),L=sf(w.videoCodec);if(A!==L)return L-A}if(E.uri===w.uri&&E.codecSet!==w.codecSet){const A=fo(E.codecSet),L=fo(w.codecSet);if(A!==L)return L-A}return E.averageBitrate!==w.averageBitrate?E.averageBitrate-w.averageBitrate:0});let d=p[0];if(this.steering&&(h=this.steering.filterParsedLevels(h),h.length!==p.length)){for(let E=0;E<p.length;E++)if(p[E].pathwayId===h[0].pathwayId){d=p[E];break}}this._levels=h;for(let E=0;E<h.length;E++)if(h[E]===d){var g;this._firstLevel=E;const w=d.bitrate,A=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${h.length} level(s) found, first bitrate: ${w}`),((g=this.hls.userConfig)==null?void 0:g.abrEwmaDefaultEstimate)===void 0){const L=Math.min(w,this.hls.config.abrEwmaDefaultEstimateMax);L>A&&A===Fm.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=L)}break}const T=r&&!n,b={levels:h,audioTracks:o,subtitleTracks:u,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:n,altAudio:!T&&o.some(E=>!!E.url)};this.hls.trigger(I.MANIFEST_PARSED,b),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const d=new Error("invalid level idx"),g=e<0;if(this.hls.trigger(I.ERROR,{type:xe.OTHER_ERROR,details:te.LEVEL_SWITCH_ERROR,level:e,fatal:g,error:d,reason:d.message}),g)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,n=this.currentLevel,r=n?n.attrs["PATHWAY-ID"]:void 0,o=t[e],u=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,i===e&&o.details&&n&&r===u)return;this.log(`Switching to level ${e} (${o.height?o.height+"p ":""}${o.videoRange?o.videoRange+" ":""}${o.codecSet?o.codecSet+" ":""}@${o.bitrate})${u?" with Pathway "+u:""} from level ${i}${r?" with Pathway "+r:""}`);const h={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(I.LEVEL_SWITCHING,h);const p=o.details;if(!p||p.live){const d=this.switchParams(o.uri,n?.details,p);this.loadPlaylist(d)}}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){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){t.fatal||!t.context||t.context.type===qe.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===Pe.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(r=>!!i[r]))return;const 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 i;const{level:n,details:r}=t,o=this._levels[n];if(!o){var u;this.warn(`Invalid level index ${n}`),(u=t.deliveryDirectives)!=null&&u.skip&&(r.deltaUpdateFailed=!0);return}n===this.currentLevelIndex?(o.fragmentError===0&&(o.loadError=0),this.playlistLoaded(n,t,o.details)):(i=t.deliveryDirectives)!=null&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let n=i.uri;if(e)try{n=e.addDirectives(n)}catch(o){this.warn(`Could not construct new URL with HLS Delivery Directives: ${o}`)}const r=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${e?.msn!==void 0?" at sn "+e.msn+" part "+e.part:""} with${r?" Pathway "+r:""} ${n}`),this.clearTimer(),this.hls.trigger(I.LEVEL_LOADING,{url:n,level:t,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;const i=this._levels.filter((n,r)=>r!==e?!0:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),!1));Jg(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(I.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(I.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function Qf(s){const e={};s.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}class uw{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyUriToKeyInfo){const n=this.keyUriToKeyInfo[i].loader;if(n){var t;if(e&&e!==((t=n.context)==null?void 0:t.frag.type))return;n.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=te.KEY_LOAD_ERROR,i,n,r){return new Wi({type:xe.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:i,networkDetails:n})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:n}=e;for(let r=0;r<t.length;r++){const o=t[r];if(n<=o.cc&&(i==="initSegment"||o.sn==="initSegment"||i<o.sn)){this.emeController.selectKeySystemFormat(o).then(u=>{o.setKeyFormat(u)});break}}}}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 i,n;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const p=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,te.KEY_LOAD_ERROR,p))}const o=r.uri;if(!o)return Promise.reject(this.createKeyLoadError(e,te.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${o}"`)));let u=this.keyUriToKeyInfo[o];if((i=u)!=null&&i.decryptdata.key)return r.key=u.decryptdata.key,Promise.resolve({frag:e,keyInfo:u});if((n=u)!=null&&n.keyLoadPromise){var h;switch((h=u.mediaKeySessionContext)==null?void 0:h.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return u.keyLoadPromise.then(p=>(r.key=p.keyInfo.decryptdata.key,{frag:e,keyInfo:u}))}}switch(u=this.keyUriToKeyInfo[o]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(u,e):this.loadKeyEME(u,e);case"AES-128":return this.loadKeyHTTP(u,e);default:return Promise.reject(this.createKeyLoadError(e,te.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const n=this.emeController.loadKey(i);if(n)return(e.keyLoadPromise=n.then(r=>(e.mediaKeySessionContext=r,i))).catch(r=>{throw e.keyLoadPromise=null,r})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,n=i.loader,r=new n(i);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((o,u)=>{const h={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},p=i.keyLoadPolicy.default,d={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(T,b,E,w)=>{const{frag:A,keyInfo:L,url:P}=E;if(!A.decryptdata||L!==this.keyUriToKeyInfo[P])return u(this.createKeyLoadError(A,te.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),w));L.decryptdata.key=A.decryptdata.key=new Uint8Array(T.data),A.keyLoader=null,L.loader=null,o({frag:A,keyInfo:L})},onError:(T,b,E,w)=>{this.resetLoader(b),u(this.createKeyLoadError(t,te.KEY_LOAD_ERROR,new Error(`HTTP Error ${T.code} loading key ${T.text}`),E,St({url:h.url,data:void 0},T)))},onTimeout:(T,b,E)=>{this.resetLoader(b),u(this.createKeyLoadError(t,te.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),E))},onAbort:(T,b,E)=>{this.resetLoader(b),u(this.createKeyLoadError(t,te.INTERNAL_ABORTED,new Error("key loading aborted"),E))}};r.load(h,d,g)})}resetLoader(e){const{frag:t,keyInfo:i,url:n}=e,r=i.loader;t.keyLoader===r&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[n],r&&r.destroy()}}function Nm(){return self.SourceBuffer||self.WebKitSourceBuffer}function Bm(){if(!ts())return!1;const e=Nm();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function cw(){if(!Bm())return!1;const s=ts();return typeof s?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(Rr(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(Rr(e,"audio"))))}function hw(){var s;const e=Nm();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}const dw=250,Za=2,fw=.1,pw=.05;class gw{constructor(e,t,i,n){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=i,this.hls=n}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:i,media:n,stalled:r}=this;if(n===null)return;const{currentTime:o,seeking:u}=n,h=this.seeking&&!u,p=!this.seeking&&u;if(this.seeking=u,o!==e){if(this.moved=!0,u||(this.nudgeRetry=0),r!==null){if(this.stallReported){const A=self.performance.now()-r;W.warn(`playback not stuck anymore @${o}, after ${Math.round(A)}ms`),this.stallReported=!1}this.stalled=null}return}if(p||h){this.stalled=null;return}if(n.paused&&!u||n.ended||n.playbackRate===0||!at.getBuffered(n).length){this.nudgeRetry=0;return}const d=at.bufferInfo(n,o,0),g=d.nextStart||0;if(u){const A=d.len>Za,L=!g||t&&t.start<=o||g-o>Za&&!this.fragmentTracker.getPartialFragment(o);if(A||L)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var T;if(!(d.len>0)&&!g)return;const L=Math.max(g,d.start||0)-o,P=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,O=(P==null||(T=P.details)==null?void 0:T.live)?P.details.targetduration*2:Za,k=this.fragmentTracker.getPartialFragment(o);if(L>0&&(L<=O||k)){n.paused||this._trySkipBufferHole(k);return}}const b=self.performance.now();if(r===null){this.stalled=b;return}const E=b-r;if(!u&&E>=dw&&(this._reportStall(d),!this.media))return;const w=at.bufferInfo(n,o,i.maxBufferHole);this._tryFixBufferStall(w,E)}_tryFixBufferStall(e,t){const{config:i,fragmentTracker:n,media:r}=this;if(r===null)return;const o=r.currentTime,u=n.getPartialFragment(o);u&&(this._trySkipBufferHole(u)||!this.media)||(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-o<i.maxBufferHole)&&t>i.highBufferWatchdogPeriod*1e3&&(W.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:i,stallReported:n}=this;if(!n&&i){this.stallReported=!0;const r=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);W.warn(r.message),t.trigger(I.ERROR,{type:xe.MEDIA_ERROR,details:te.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:i,media:n}=this;if(n===null)return 0;const r=n.currentTime,o=at.bufferInfo(n,r,0),u=r<o.start?o.start:o.nextStart;if(u){const h=o.len<=t.maxBufferHole,p=o.len>0&&o.len<1&&n.readyState<3,d=u-r;if(d>0&&(h||p)){if(d>t.maxBufferHole){const{fragmentTracker:T}=this;let b=!1;if(r===0){const E=T.getAppendedFrag(0,Pe.MAIN);E&&u<E.end&&(b=!0)}if(!b){const E=e||T.getAppendedFrag(r,Pe.MAIN);if(E){let w=!1,A=E.end;for(;A<u;){const L=T.getPartialFragment(A);if(L)A+=L.duration;else{w=!0;break}}if(w)return 0}}}const g=Math.max(u+pw,r+fw);if(W.warn(`skipping hole, adjusting currentTime from ${r} to ${g}`),this.moved=!0,this.stalled=null,n.currentTime=g,e&&!e.gap){const T=new Error(`fragment loaded with buffer holes, seeking from ${r} to ${g}`);i.trigger(I.ERROR,{type:xe.MEDIA_ERROR,details:te.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:T,reason:T.message,frag:e})}return g}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:i,nudgeRetry:n}=this;if(i===null)return;const r=i.currentTime;if(this.nudgeRetry++,n<e.nudgeMaxRetry){const o=r+(n+1)*e.nudgeOffset,u=new Error(`Nudging 'currentTime' from ${r} to ${o}`);W.warn(u.message),i.currentTime=o,t.trigger(I.ERROR,{type:xe.MEDIA_ERROR,details:te.BUFFER_NUDGE_ON_STALL,error:u,fatal:!1})}else{const o=new Error(`Playhead still not moving while enough data buffered @${r} after ${e.nudgeMaxRetry} nudges`);W.error(o.message),t.trigger(I.ERROR,{type:xe.MEDIA_ERROR,details:te.BUFFER_STALLED_ERROR,error:o,fatal:!0})}}}const mw=100;class yw extends Kc{constructor(e,t,i){super(e,t,i,"[stream-controller]",Pe.MAIN),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(I.ERROR,this.onError,this),e.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(I.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(I.BUFFER_CREATED,this.onBufferCreated,this),e.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(I.ERROR,this.onError,this),e.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(I.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(I.BUFFER_CREATED,this.onBufferCreated,this),e.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(e){if(this.levels){const{lastCurrentTime:t,hls:i}=this;if(this.stopLoad(),this.setInterval(mw),this.level=-1,!this.startFragRequested){let n=i.startLevel;n===-1&&(i.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=i.firstAutoLevel),i.nextLoadLevel=n,this.level=i.loadLevel,this.loadedmetadata=!1}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=de.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=de.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case de.WAITING_LEVEL:{const{levels:t,level:i}=this,n=t?.[i],r=n?.details;if(r&&(!r.live||this.levelLastLoaded===n)){if(this.waitForCdnTuneIn(r))break;this.state=de.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=de.IDLE;break}break}case de.FRAG_LOADING_WAITING_RETRY:{var e;const t=self.performance.now(),i=this.retryDate;if(!i||t>=i||(e=this.media)!=null&&e.seeking){const{levels:n,level:r}=this,o=n?.[r];this.resetStartWhenNotLoaded(o||null),this.state=de.IDLE}}break}this.state===de.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:n}=this;if(t===null||!n&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[r]))return;const o=i[r],u=this.getMainFwdBufferInfo();if(u===null)return;const h=this.getLevelDetails();if(h&&this._streamEnded(u,h)){const w={};this.altAudio&&(w.type="video"),this.hls.trigger(I.BUFFER_EOS,w),this.state=de.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const p=o.details;if(!p||this.state===de.WAITING_LEVEL||p.live&&this.levelLastLoaded!==o){this.level=r,this.state=de.WAITING_LEVEL;return}const d=u.len,g=this.getMaxBufferLength(o.maxBitrate);if(d>=g)return;this.backtrackFragment&&this.backtrackFragment.start>u.end&&(this.backtrackFragment=null);const T=this.backtrackFragment?this.backtrackFragment.start:u.end;let b=this.getNextFragment(T,p);if(this.couldBacktrack&&!this.fragPrevious&&b&&b.sn!=="initSegment"&&this.fragmentTracker.getState(b)!==Et.OK){var E;const A=((E=this.backtrackFragment)!=null?E:b).sn-p.startSN,L=p.fragments[A-1];L&&b.cc===L.cc&&(b=L,this.fragmentTracker.removeFragment(L))}else this.backtrackFragment&&u.len&&(this.backtrackFragment=null);if(b&&this.isLoopLoading(b,T)){if(!b.gap){const A=this.audioOnly&&!this.altAudio?Je.AUDIO:Je.VIDEO,L=(A===Je.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;L&&this.afterBufferFlushed(L,A,Pe.MAIN)}b=this.getNextFragmentLoopLoading(b,p,u,Pe.MAIN,g)}b&&(b.initSegment&&!b.initSegment.data&&!this.bitrateTest&&(b=b.initSegment),this.loadFragment(b,o,T))}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);this.fragCurrent=e,n===Et.NOT_LOADED||n===Et.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,t):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)):(this.startFragRequested=!0,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,Pe.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let i;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const u=this.getMainFwdBufferInfo();if(!u||u.len<r.targetduration*2)return}if(!t.paused&&e){const u=this.hls.nextLoadLevel,h=e[u],p=this.fragLastKbps;p&&this.fragCurrent?i=this.fragCurrent.duration*h.maxBitrate/(1e3*p)+1:i=0}else i=0;const o=this.getBufferedFrag(t.currentTime+i);if(o){const u=this.followingBufferedFrag(o);if(u){this.abortCurrentFrag();const h=u.maxStartPTS?u.maxStartPTS:u.start,p=u.duration,d=Math.max(o.end,h+Math.min(Math.max(p-this.config.maxFragLookUpTolerance,p*(this.couldBacktrack?.5:.125)),p*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(d,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case de.KEY_LOADING:case de.FRAG_LOADING:case de.FRAG_LOADING_WAITING_RETRY:case de.PARSING:case de.PARSED:this.state=de.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new gw(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;Ae(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const i=this.getMainFwdBufferInfo();if(i===null||i.len===0){this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(I.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(e,t){let i=!1,n=!1;t.levels.forEach(r=>{const o=r.audioCodec;o&&(i=i||o.indexOf("mp4a.40.2")!==-1,n=n||o.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=i&&n&&!hw(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==de.IDLE)return;const n=i[t.level];(!n.details||n.details.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(n.details))&&(this.state=de.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:n}=this,r=t.level,o=t.details,u=o.totalduration;if(!n){this.warn(`Levels were reset while loading level ${r}`);return}this.log(`Level ${r} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${u}`);const h=n[r],p=this.fragCurrent;p&&(this.state===de.FRAG_LOADING||this.state===de.FRAG_LOADING_WAITING_RETRY)&&p.level!==t.level&&p.loader&&this.abortCurrentFrag();let d=0;if(o.live||(i=h.details)!=null&&i.live){var g;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;d=this.alignPlaylists(o,h.details,(g=this.levelLastLoaded)==null?void 0:g.details)}if(h.details=o,this.levelLastLoaded=h,this.hls.trigger(I.LEVEL_UPDATED,{details:o,level:r}),this.state===de.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=de.IDLE}this.startFragRequested?o.live&&this.synchronizeToLiveEdge(o):this.setStartPosition(o,d),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:n,payload:r}=e,{levels:o}=this;if(!o){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const u=o[i.level],h=u.details;if(!h){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const p=u.videoCodec,d=h.PTSKnown||!h.live,g=(t=i.initSegment)==null?void 0:t.data,T=this._getAudioCodec(u),b=this.transmuxer=this.transmuxer||new vm(this.hls,Pe.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),E=n?n.index:-1,w=E!==-1,A=new Vc(i.level,i.sn,i.stats.chunkCount,r.byteLength,E,w),L=this.initPTS[i.cc];b.push(r,g,T,p,i,n,h.totalduration,d,A,L)}onAudioTrackSwitching(e,t){const i=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const o=this.fragCurrent;o&&(this.log("Switching to main audio track, cancel main fragment load"),o.abortRequests(),this.fragmentTracker.removeFragment(o)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const r=this.hls;i&&(r.trigger(I.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),r.trigger(I.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=t.id,n=!!this.hls.audioTracks[i].url;if(n){const r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=n,this.tick()}onBufferCreated(e,t){const i=t.tracks;let n,r,o=!1;for(const u in i){const h=i[u];if(h.id==="main"){if(r=u,n=h,u==="video"){const p=i[u];p&&(this.videoBuffer=p.buffer)}}else o=!0}o&&n?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:n}=t;if(i&&i.type!==Pe.MAIN)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===de.PARSED&&(this.state=de.IDLE);return}const r=n?n.stats:i.stats;this.fragLastKbps=Math.round(8*r.total/(r.buffering.end-r.loading.first)),i.sn!=="initSegment"&&(this.fragPrevious=i),this.fragBufferedComplete(i,n)}onError(e,t){var i;if(t.fatal){this.state=de.ERROR;return}switch(t.details){case te.FRAG_GAP:case te.FRAG_PARSING_ERROR:case te.FRAG_DECRYPT_ERROR:case te.FRAG_LOAD_ERROR:case te.FRAG_LOAD_TIMEOUT:case te.KEY_LOAD_ERROR:case te.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Pe.MAIN,t);break;case te.LEVEL_LOAD_ERROR:case te.LEVEL_LOAD_TIMEOUT:case te.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===de.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===qe.LEVEL&&(this.state=de.IDLE);break;case te.BUFFER_APPEND_ERROR:case te.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;if(t.details===te.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case te.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}checkBuffer(){const{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!at.getBuffered(e).length){const i=this.state!==de.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,i)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=de.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Je.AUDIO||this.audioOnly&&!this.altAudio){const i=(t===Je.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,t,Pe.MAIN),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}const n=at.getBuffered(e),o=(n.length?n.start(0):0)-i;o>0&&(o<this.config.maxBufferHole||o<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${o} to match buffer start`),i+=o,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${t}`),e.currentTime=i}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{const{hls:n}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=de.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const r=e.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),n.trigger(I.FRAG_LOADED,i),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const i="main",{hls:n}=this,{remuxResult:r,chunkMeta:o}=e,u=this.getCurrentContext(o);if(!u){this.resetWhenMissingContext(o);return}const{frag:h,part:p,level:d}=u,{video:g,text:T,id3:b,initSegment:E}=r,{details:w}=d,A=this.altAudio?void 0:r.audio;if(this.fragContextChanged(h)){this.fragmentTracker.removeFragment(h);return}if(this.state=de.PARSING,E){if(E!=null&&E.tracks){const M=h.initSegment||h;this._bufferInitSegment(d,E.tracks,M,o),n.trigger(I.FRAG_PARSING_INIT_SEGMENT,{frag:M,id:i,tracks:E.tracks})}const L=E.initPTS,P=E.timescale;Ae(L)&&(this.initPTS[h.cc]={baseTime:L,timescale:P},n.trigger(I.INIT_PTS_FOUND,{frag:h,id:i,initPTS:L,timescale:P}))}if(g&&w&&h.sn!=="initSegment"){const L=w.fragments[h.sn-1-w.startSN],P=h.sn===w.startSN,M=!L||h.cc>L.cc;if(r.independent!==!1){const{startPTS:O,endPTS:k,startDTS:N,endDTS:H}=g;if(p)p.elementaryStreams[g.type]={startPTS:O,endPTS:k,startDTS:N,endDTS:H};else if(g.firstKeyFrame&&g.independent&&o.id===1&&!M&&(this.couldBacktrack=!0),g.dropped&&g.independent){const G=this.getMainFwdBufferInfo(),B=(G?G.end:this.getLoadPosition())+this.config.maxBufferHole,D=g.firstKeyFramePTS?g.firstKeyFramePTS:O;if(!P&&B<D-this.config.maxBufferHole&&!M){this.backtrack(h);return}else M&&(h.gap=!0);h.setElementaryStreamInfo(g.type,h.start,k,h.start,H,!0)}else P&&O>Za&&(h.gap=!0);h.setElementaryStreamInfo(g.type,O,k,N,H),this.backtrackFragment&&(this.backtrackFragment=h),this.bufferFragmentData(g,h,p,o,P||M)}else if(P||M)h.gap=!0;else{this.backtrack(h);return}}if(A){const{startPTS:L,endPTS:P,startDTS:M,endDTS:O}=A;p&&(p.elementaryStreams[Je.AUDIO]={startPTS:L,endPTS:P,startDTS:M,endDTS:O}),h.setElementaryStreamInfo(Je.AUDIO,L,P,M,O),this.bufferFragmentData(A,h,p,o)}if(w&&b!=null&&(t=b.samples)!=null&&t.length){const L={id:i,frag:h,details:w,samples:b.samples};n.trigger(I.FRAG_PARSING_METADATA,L)}if(w&&T){const L={id:i,frag:h,details:w,samples:T.samples};n.trigger(I.FRAG_PARSING_USERDATA,L)}}_bufferInitSegment(e,t,i,n){if(this.state!==de.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:r,video:o,audiovideo:u}=t;if(r){let h=e.audioCodec;const p=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");const d=r.metadata;d&&"channelCount"in d&&(d.channelCount||1)!==1&&p.indexOf("firefox")===-1&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&p.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),e.audioCodec&&e.audioCodec!==h&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${h}"`),r.levelCodec=h,r.id="main",this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${h||""}/${e.audioCodec||""}/${r.codec}]`)}o&&(o.levelCodec=e.videoCodec,o.id="main",this.log(`Init video buffer, container:${o.container}, codecs[level/parsed]=[${e.videoCodec||""}/${o.codec}]`)),u&&this.log(`Init audiovideo buffer, container:${u.container}, codecs[level/parsed]=[${e.codecs}/${u.codec}]`),this.hls.trigger(I.BUFFER_CODECS,t),Object.keys(t).forEach(h=>{const d=t[h].initSegment;d!=null&&d.byteLength&&this.hls.trigger(I.BUFFER_APPENDING,{type:h,data:d,frag:i,part:null,chunkMeta:n,parent:i.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,Pe.MAIN)}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=de.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(at.isBuffered(e,i)?t=this.getAppendedFrag(i):at.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const n=this.fragPlaying,r=t.level;(!n||t.sn!==n.sn||n.level!==r)&&(this.fragPlaying=t,this.hls.trigger(I.FRAG_CHANGED,{frag:t}),(!n||n.level!==r)&&this.hls.trigger(I.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,i=this.currentFrag;if(i&&Ae(t)&&Ae(i.programDateTime)){const n=i.programDateTime+(t-i.start)*1e3;return new Date(n)}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class et{static get version(){return"1.5.20"}static isMSESupported(){return Bm()}static isSupported(){return cw()}static getMediaSource(){return ts()}static get Events(){return I}static get ErrorTypes(){return xe}static get ErrorDetails(){return te}static get DefaultConfig(){return et.defaultConfig?et.defaultConfig:Fm}static set DefaultConfig(e){et.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new Xc,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.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,r_(e.debug||!1,"Hls instance");const t=this.config=aw(et.DefaultConfig,e);this.userConfig=e,t.progressive&&ow(t);const{abrController:i,bufferController:n,capLevelController:r,errorController:o,fpsController:u}=t,h=new o(this),p=this.abrController=new i(this),d=this.bufferController=new n(this),g=this.capLevelController=new r(this),T=new u(this),b=new Z_(this),E=new sE(this),w=t.contentSteeringController,A=w?new w(this):null,L=this.levelController=new lw(this,A),P=new xE(this),M=new uw(this.config),O=this.streamController=new yw(this,P,M);g.setStreamController(O),T.setStreamController(O);const k=[b,L,O];A&&k.splice(1,0,A),this.networkControllers=k;const N=[p,d,g,T,E,P];this.audioTrackController=this.createController(t.audioTrackController,k);const H=t.audioStreamController;H&&k.push(new H(this,P,M)),this.subtitleTrackController=this.createController(t.subtitleTrackController,k);const G=t.subtitleStreamController;G&&k.push(new G(this,P,M)),this.createController(t.timelineController,N),M.emeController=this.emeController=this.createController(t.emeController,N),this.cmcdController=this.createController(t.cmcdController,N),this.latencyController=this.createController(rE,N),this.coreComponents=N,k.push(h);const B=h.onErrorOut;typeof B=="function"&&this.on(I.ERROR,B,h)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,n){this._emitter.off(e,t,i,n)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(W.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;const n=e===I.ERROR;this.trigger(I.ERROR,{type:xe.OTHER_ERROR,details:te.INTERNAL_EXCEPTION,fatal:n,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){W.log("destroy"),this.trigger(I.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){W.log("attachMedia"),this._media=e,this.trigger(I.MEDIA_ATTACHING,{media:e})}detachMedia(){W.log("detachMedia"),this.trigger(I.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,i=this.url,n=this.url=Nc.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,W.log(`loadSource:${n}`),t&&i&&(i!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(I.MANIFEST_LOADING,{url:e})}startLoad(e=-1){W.log(`startLoad(${e})`),this.started=!0,this.resumeBuffering();for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].startLoad(e),!(!this.started||!this.networkControllers));t++);}stopLoad(){W.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}resumeBuffering(){W.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()})}pauseBuffering(){W.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()})}swapAudioCodec(){W.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){W.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){W.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){W.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){W.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){W.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){W.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){const 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(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(W.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){aE(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(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let n=0;n<i;n++)if(e[n].maxBitrate>=t)return n;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let n;if(t===-1&&e!=null&&e.length?n=e.length-1:n=t,i)for(let r=n;r--;){const o=e[r].attrs["HDCP-LEVEL"];if(o&&o<=i)return r}return n}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()}setAudioOption(e){var t;return(t=this.audioTrackController)==null?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return(t=this.subtitleTrackController)==null||t.setSubtitleOption(e),null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const 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}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}et.defaultConfig=void 0;function Um(s,e){return e?`${s}|${e.start}-${e.end}`:s}function Hm(s,e){if(s!==void 0&&e!==void 0&&s<=e)return{start:s,end:e}}const Jf=globalThis||void 0||self;var vw=Object.defineProperty,Tw=(s,e,t)=>e in s?vw(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,se=(s,e,t)=>Tw(s,typeof e!="symbol"?e+"":e,t);class ei extends Error{constructor(e,t){super(t),se(this,"timestamp"),this.type=e,this.timestamp=performance.now()}}class Eo extends Error{constructor(e){super(),this.type=e}}class bw{constructor(e,t,i){se(this,"requestControls"),se(this,"abortController",new AbortController),se(this,"expectedBytesLength"),se(this,"requestByteRange"),se(this,"onChunkDownloaded"),this.request=e,this.httpConfig=t,this.onChunkDownloaded=i.getEventDispatcher("onChunkDownloaded");const{byteRange:n}=this.request.segment;n&&(this.requestByteRange={...n}),e.loadedBytes!==0&&(this.requestByteRange=this.requestByteRange??{start:0},this.requestByteRange.start=this.requestByteRange.start+e.loadedBytes),this.request.totalBytes&&(this.expectedBytesLength=this.request.totalBytes-this.request.loadedBytes),this.requestControls=this.request.start({downloadSource:"http"},{abort:()=>this.abortController.abort("abort"),notReceivingBytesTimeoutMs:this.httpConfig.httpNotReceivingBytesTimeoutMs}),this.fetch()}async fetch(){var e,t,i,n;const{segment:r}=this.request;try{let o=await((t=(e=this.httpConfig).httpRequestSetup)==null?void 0:t.call(e,r.url,r.byteRange,this.abortController.signal,this.requestByteRange));if(!o){const g=new Headers(this.requestByteRange?{Range:`bytes=${this.requestByteRange.start}-${this.requestByteRange.end??""}`}:void 0);o=new Request(r.url,{headers:g,signal:this.abortController.signal})}if(this.abortController.signal.aborted)throw new DOMException("Request aborted before request fetch","AbortError");const u=await window.fetch(o);if(this.handleResponseHeaders(u),!u.body)return;const{requestControls:h}=this;h.firstBytesReceived();const p=u.body.getReader();for await(const g of _w(p))this.requestControls.addLoadedChunk(g),this.onChunkDownloaded(g.byteLength,"http");if(!(await((n=(i=this.httpConfig).validateHTTPSegment)==null?void 0:n.call(i,r.url,r.byteRange,this.request.data))??!0))throw this.request.clearLoadedBytes(),new ei("http-segment-validation-failed");h.completeOnSuccess()}catch(o){this.handleError(o)}}handleResponseHeaders(e){if(!e.ok)throw e.status===406?(this.request.clearLoadedBytes(),new ei("http-bytes-mismatch",e.statusText)):new ei("http-error",e.statusText);const{requestByteRange:t}=this;if(t)if(e.status===200){if(this.request.segment.byteRange)throw new ei("http-unexpected-status-code");this.request.clearLoadedBytes()}else{if(e.status!==206)throw new ei("http-unexpected-status-code",e.statusText);const i=e.headers.get("Content-Length");if(i&&this.expectedBytesLength!==void 0&&this.expectedBytesLength!==+i)throw this.request.clearLoadedBytes(),new ei("http-bytes-mismatch",e.statusText);const n=e.headers.get("Content-Range"),r=n?Sw(n):void 0;if(r){const{from:o,to:u}=r,h=u!==void 0&&o!==void 0?u-o+1:void 0;if(h!==void 0&&this.expectedBytesLength!==h||o!==void 0&&t.start!==o||u!==void 0&&t.end!==void 0&&t.end!==u)throw this.request.clearLoadedBytes(),new ei("http-bytes-mismatch",e.statusText)}}if(e.status===200&&this.request.totalBytes===void 0){const i=e.headers.get("Content-Length");i&&this.request.setTotalBytes(+i)}}handleError(e){if(e instanceof Error){if(e.name!=="abort")return;const t=e instanceof ei?e:new ei("http-error",e.message);this.requestControls.abortOnError(t)}}}async function*_w(s){for(;;){const{done:e,value:t}=await s.read();if(e)break;yield t}}const Ew=/^bytes (?:(?:(\d+)|)-(?:(\d+)|)|\*)\/(?:(\d+)|\*)$/;function Sw(s){const e=Ew.exec(s.trim());if(!e)return;const[,t,i,n]=e;return{from:t?parseInt(t):void 0,to:i?parseInt(i):void 0,total:n?parseInt(n):void 0}}function Cw(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var $m={exports:{}},pt=$m.exports={},Ai,Li;function gc(){throw new Error("setTimeout has not been defined")}function mc(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?Ai=setTimeout:Ai=gc}catch{Ai=gc}try{typeof clearTimeout=="function"?Li=clearTimeout:Li=mc}catch{Li=mc}})();function jm(s){if(Ai===setTimeout)return setTimeout(s,0);if((Ai===gc||!Ai)&&setTimeout)return Ai=setTimeout,setTimeout(s,0);try{return Ai(s,0)}catch{try{return Ai.call(null,s,0)}catch{return Ai.call(this,s,0)}}}function ww(s){if(Li===clearTimeout)return clearTimeout(s);if((Li===mc||!Li)&&clearTimeout)return Li=clearTimeout,clearTimeout(s);try{return Li(s)}catch{try{return Li.call(null,s)}catch{return Li.call(this,s)}}}var Zi=[],Fs=!1,Jn,eo=-1;function Aw(){!Fs||!Jn||(Fs=!1,Jn.length?Zi=Jn.concat(Zi):eo=-1,Zi.length&&Vm())}function Vm(){if(!Fs){var s=jm(Aw);Fs=!0;for(var e=Zi.length;e;){for(Jn=Zi,Zi=[];++eo<e;)Jn&&Jn[eo].run();eo=-1,e=Zi.length}Jn=null,Fs=!1,ww(s)}}pt.nextTick=function(s){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];Zi.push(new Gm(s,e)),Zi.length===1&&!Fs&&jm(Vm)};function Gm(s,e){this.fun=s,this.array=e}Gm.prototype.run=function(){this.fun.apply(null,this.array)};pt.title="browser";pt.browser=!0;pt.env={};pt.argv=[];pt.version="";pt.versions={};function rn(){}pt.on=rn;pt.addListener=rn;pt.once=rn;pt.off=rn;pt.removeListener=rn;pt.removeAllListeners=rn;pt.emit=rn;pt.prependListener=rn;pt.prependOnceListener=rn;pt.listeners=function(s){return[]};pt.binding=function(s){throw new Error("process.binding is not supported")};pt.cwd=function(){return"/"};pt.chdir=function(s){throw new Error("process.chdir is not supported")};pt.umask=function(){return 0};var Lw=$m.exports;const to=Cw(Lw);var kw=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof Jf<"u"?Jf:typeof self<"u"?self:{};function ss(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Oa={exports:{}},Au,Zf;function Iw(){if(Zf)return Au;Zf=1;var s=1e3,e=s*60,t=e*60,i=t*24,n=i*7,r=i*365.25;Au=function(d,g){g=g||{};var T=typeof d;if(T==="string"&&d.length>0)return o(d);if(T==="number"&&isFinite(d))return g.long?h(d):u(d);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(d))};function o(d){if(d=String(d),!(d.length>100)){var g=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(d);if(g){var T=parseFloat(g[1]),b=(g[2]||"ms").toLowerCase();switch(b){case"years":case"year":case"yrs":case"yr":case"y":return T*r;case"weeks":case"week":case"w":return T*n;case"days":case"day":case"d":return T*i;case"hours":case"hour":case"hrs":case"hr":case"h":return T*t;case"minutes":case"minute":case"mins":case"min":case"m":return T*e;case"seconds":case"second":case"secs":case"sec":case"s":return T*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return T;default:return}}}}function u(d){var g=Math.abs(d);return g>=i?Math.round(d/i)+"d":g>=t?Math.round(d/t)+"h":g>=e?Math.round(d/e)+"m":g>=s?Math.round(d/s)+"s":d+"ms"}function h(d){var g=Math.abs(d);return g>=i?p(d,g,i,"day"):g>=t?p(d,g,t,"hour"):g>=e?p(d,g,e,"minute"):g>=s?p(d,g,s,"second"):d+" ms"}function p(d,g,T,b){var E=g>=T*1.5;return Math.round(d/T)+" "+b+(E?"s":"")}return Au}var Lu,ep;function Rw(){if(ep)return Lu;ep=1;function s(e){i.debug=i,i.default=i,i.coerce=p,i.disable=u,i.enable=r,i.enabled=h,i.humanize=Iw(),i.destroy=d,Object.keys(e).forEach(g=>{i[g]=e[g]}),i.names=[],i.skips=[],i.formatters={};function t(g){let T=0;for(let b=0;b<g.length;b++)T=(T<<5)-T+g.charCodeAt(b),T|=0;return i.colors[Math.abs(T)%i.colors.length]}i.selectColor=t;function i(g){let T,b=null,E,w;function A(...L){if(!A.enabled)return;const P=A,M=Number(new Date),O=M-(T||M);P.diff=O,P.prev=T,P.curr=M,T=M,L[0]=i.coerce(L[0]),typeof L[0]!="string"&&L.unshift("%O");let k=0;L[0]=L[0].replace(/%([a-zA-Z%])/g,(H,G)=>{if(H==="%%")return"%";k++;const B=i.formatters[G];if(typeof B=="function"){const D=L[k];H=B.call(P,D),L.splice(k,1),k--}return H}),i.formatArgs.call(P,L),(P.log||i.log).apply(P,L)}return A.namespace=g,A.useColors=i.useColors(),A.color=i.selectColor(g),A.extend=n,A.destroy=i.destroy,Object.defineProperty(A,"enabled",{enumerable:!0,configurable:!1,get:()=>b!==null?b:(E!==i.namespaces&&(E=i.namespaces,w=i.enabled(g)),w),set:L=>{b=L}}),typeof i.init=="function"&&i.init(A),A}function n(g,T){const b=i(this.namespace+(typeof T>"u"?":":T)+g);return b.log=this.log,b}function r(g){i.save(g),i.namespaces=g,i.names=[],i.skips=[];const T=(typeof g=="string"?g:"").trim().replace(" ",",").split(",").filter(Boolean);for(const b of T)b[0]==="-"?i.skips.push(b.slice(1)):i.names.push(b)}function o(g,T){let b=0,E=0,w=-1,A=0;for(;b<g.length;)if(E<T.length&&(T[E]===g[b]||T[E]==="*"))T[E]==="*"?(w=E,A=b,E++):(b++,E++);else if(w!==-1)E=w+1,A++,b=A;else return!1;for(;E<T.length&&T[E]==="*";)E++;return E===T.length}function u(){const g=[...i.names,...i.skips.map(T=>"-"+T)].join(",");return i.enable(""),g}function h(g){for(const T of i.skips)if(o(g,T))return!1;for(const T of i.names)if(o(g,T))return!0;return!1}function p(g){return g instanceof Error?g.stack||g.message:g}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return i.enable(i.load()),i}return Lu=s,Lu}var tp;function Pw(){return tp||(tp=1,function(s,e){e.formatArgs=i,e.save=n,e.load=r,e.useColors=t,e.storage=o(),e.destroy=(()=>{let h=!1;return()=>{h||(h=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let h;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(h=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(h[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function i(h){if(h[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+h[0]+(this.useColors?"%c ":" ")+"+"+s.exports.humanize(this.diff),!this.useColors)return;const p="color: "+this.color;h.splice(1,0,p,"color: inherit");let d=0,g=0;h[0].replace(/%[a-zA-Z%]/g,T=>{T!=="%%"&&(d++,T==="%c"&&(g=d))}),h.splice(g,0,p)}e.log=console.debug||console.log||(()=>{});function n(h){try{h?e.storage.setItem("debug",h):e.storage.removeItem("debug")}catch{}}function r(){let h;try{h=e.storage.getItem("debug")}catch{}return!h&&typeof to<"u"&&"env"in to&&(h=to.env.DEBUG),h}function o(){try{return localStorage}catch{}}s.exports=Rw()(e);const{formatters:u}=s.exports;u.j=function(h){try{return JSON.stringify(h)}catch(p){return"[UnexpectedJSONParseError]: "+p.message}}}(Oa,Oa.exports)),Oa.exports}var Km=Pw();const Ni=ss(Km);var Ma={exports:{}},ip;function qm(){if(ip)return Ma.exports;ip=1;var s=typeof Reflect=="object"?Reflect:null,e=s&&typeof s.apply=="function"?s.apply:function(k,N,H){return Function.prototype.apply.call(k,N,H)},t;s&&typeof s.ownKeys=="function"?t=s.ownKeys:Object.getOwnPropertySymbols?t=function(k){return Object.getOwnPropertyNames(k).concat(Object.getOwnPropertySymbols(k))}:t=function(k){return Object.getOwnPropertyNames(k)};function i(O){console&&console.warn&&console.warn(O)}var n=Number.isNaN||function(k){return k!==k};function r(){r.init.call(this)}Ma.exports=r,Ma.exports.once=L,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var o=10;function u(O){if(typeof O!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof O)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(O){if(typeof O!="number"||O<0||n(O))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+O+".");o=O}}),r.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(k){if(typeof k!="number"||k<0||n(k))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+k+".");return this._maxListeners=k,this};function h(O){return O._maxListeners===void 0?r.defaultMaxListeners:O._maxListeners}r.prototype.getMaxListeners=function(){return h(this)},r.prototype.emit=function(k){for(var N=[],H=1;H<arguments.length;H++)N.push(arguments[H]);var G=k==="error",B=this._events;if(B!==void 0)G=G&&B.error===void 0;else if(!G)return!1;if(G){var D;if(N.length>0&&(D=N[0]),D instanceof Error)throw D;var K=new Error("Unhandled error."+(D?" ("+D.message+")":""));throw K.context=D,K}var oe=B[k];if(oe===void 0)return!1;if(typeof oe=="function")e(oe,this,N);else for(var Z=oe.length,le=E(oe,Z),H=0;H<Z;++H)e(le[H],this,N);return!0};function p(O,k,N,H){var G,B,D;if(u(N),B=O._events,B===void 0?(B=O._events=Object.create(null),O._eventsCount=0):(B.newListener!==void 0&&(O.emit("newListener",k,N.listener?N.listener:N),B=O._events),D=B[k]),D===void 0)D=B[k]=N,++O._eventsCount;else if(typeof D=="function"?D=B[k]=H?[N,D]:[D,N]:H?D.unshift(N):D.push(N),G=h(O),G>0&&D.length>G&&!D.warned){D.warned=!0;var K=new Error("Possible EventEmitter memory leak detected. "+D.length+" "+String(k)+" listeners added. Use emitter.setMaxListeners() to increase limit");K.name="MaxListenersExceededWarning",K.emitter=O,K.type=k,K.count=D.length,i(K)}return O}r.prototype.addListener=function(k,N){return p(this,k,N,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(k,N){return p(this,k,N,!0)};function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function g(O,k,N){var H={fired:!1,wrapFn:void 0,target:O,type:k,listener:N},G=d.bind(H);return G.listener=N,H.wrapFn=G,G}r.prototype.once=function(k,N){return u(N),this.on(k,g(this,k,N)),this},r.prototype.prependOnceListener=function(k,N){return u(N),this.prependListener(k,g(this,k,N)),this},r.prototype.removeListener=function(k,N){var H,G,B,D,K;if(u(N),G=this._events,G===void 0)return this;if(H=G[k],H===void 0)return this;if(H===N||H.listener===N)--this._eventsCount===0?this._events=Object.create(null):(delete G[k],G.removeListener&&this.emit("removeListener",k,H.listener||N));else if(typeof H!="function"){for(B=-1,D=H.length-1;D>=0;D--)if(H[D]===N||H[D].listener===N){K=H[D].listener,B=D;break}if(B<0)return this;B===0?H.shift():w(H,B),H.length===1&&(G[k]=H[0]),G.removeListener!==void 0&&this.emit("removeListener",k,K||N)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(k){var N,H,G;if(H=this._events,H===void 0)return this;if(H.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):H[k]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete H[k]),this;if(arguments.length===0){var B=Object.keys(H),D;for(G=0;G<B.length;++G)D=B[G],D!=="removeListener"&&this.removeAllListeners(D);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(N=H[k],typeof N=="function")this.removeListener(k,N);else if(N!==void 0)for(G=N.length-1;G>=0;G--)this.removeListener(k,N[G]);return this};function T(O,k,N){var H=O._events;if(H===void 0)return[];var G=H[k];return G===void 0?[]:typeof G=="function"?N?[G.listener||G]:[G]:N?A(G):E(G,G.length)}r.prototype.listeners=function(k){return T(this,k,!0)},r.prototype.rawListeners=function(k){return T(this,k,!1)},r.listenerCount=function(O,k){return typeof O.listenerCount=="function"?O.listenerCount(k):b.call(O,k)},r.prototype.listenerCount=b;function b(O){var k=this._events;if(k!==void 0){var N=k[O];if(typeof N=="function")return 1;if(N!==void 0)return N.length}return 0}r.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function E(O,k){for(var N=new Array(k),H=0;H<k;++H)N[H]=O[H];return N}function w(O,k){for(;k+1<O.length;k++)O[k]=O[k+1];O.pop()}function A(O){for(var k=new Array(O.length),N=0;N<k.length;++N)k[N]=O[N].listener||O[N];return k}function L(O,k){return new Promise(function(N,H){function G(D){O.removeListener(k,B),H(D)}function B(){typeof O.removeListener=="function"&&O.removeListener("error",G),N([].slice.call(arguments))}M(O,k,B,{once:!0}),k!=="error"&&P(O,G,{once:!0})})}function P(O,k,N){typeof O.on=="function"&&M(O,"error",k,N)}function M(O,k,N,H){if(typeof O.on=="function")H.once?O.once(k,N):O.on(k,N);else if(typeof O.addEventListener=="function")O.addEventListener(k,function G(B){H.once&&O.removeEventListener(k,G),N(B)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof O)}return Ma.exports}var Dw=qm();const Wm=ss(Dw);var Fa={exports:{}},ku,np;function xw(){if(np)return ku;np=1,ku=s;function s(e,t){if(e&&t)return s(e)(t);if(typeof e!="function")throw new TypeError("need wrapper function");return Object.keys(e).forEach(function(n){i[n]=e[n]}),i;function i(){for(var n=new Array(arguments.length),r=0;r<n.length;r++)n[r]=arguments[r];var o=e.apply(this,n),u=n[n.length-1];return typeof o=="function"&&o!==u&&Object.keys(u).forEach(function(h){o[h]=u[h]}),o}}return ku}var sp;function Ow(){if(sp)return Fa.exports;sp=1;var s=xw();Fa.exports=s(e),Fa.exports.strict=s(t),e.proto=e(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return e(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return t(this)},configurable:!0})});function e(i){var n=function(){return n.called?n.value:(n.called=!0,n.value=i.apply(this,arguments))};return n.called=!1,n}function t(i){var n=function(){if(n.called)throw new Error(n.onceError);return n.called=!0,n.value=i.apply(this,arguments)},r=i.name||"Function wrapped with `once`";return n.onceError=r+" shouldn't be called more than once",n.called=!1,n}return Fa.exports}var Mw=Ow();const Fw=ss(Mw);/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var Iu,rp;function zm(){if(rp)return Iu;rp=1;let s;return Iu=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:kw):e=>(s||(s=Promise.resolve())).then(e).catch(t=>setTimeout(()=>{throw t},0)),Iu}/*! run-parallel. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var Ru,ap;function Nw(){if(ap)return Ru;ap=1,Ru=e;const s=zm();function e(t,i){let n,r,o,u=!0;Array.isArray(t)?(n=[],r=t.length):(o=Object.keys(t),n={},r=o.length);function h(d){function g(){i&&i(d,n),i=null}u?s(g):g()}function p(d,g,T){n[d]=T,(--r===0||g)&&h(g)}r?o?o.forEach(function(d){t[d](function(g,T){p(d,g,T)})}):t.forEach(function(d,g){d(function(T,b){p(g,T,b)})}):h(null),u=!1}return Ru}var Bw=Nw();const Uw=ss(Bw),tn=typeof window<"u"?window:self,yc=tn.RTCPeerConnection||tn.mozRTCPeerConnection||tn.webkitRTCPeerConnection,Hw=tn.RTCSessionDescription||tn.mozRTCSessionDescription||tn.webkitRTCSessionDescription,$w=tn.RTCIceCandidate||tn.mozRTCIceCandidate||tn.webkitRTCIceCandidate;var Pu,op;function jw(){return op||(op=1,Pu=class{constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}clear(){this.top=this.btm=0,this.next=null,this.buffer.fill(void 0)}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}),Pu}var Du,lp;function Vw(){if(lp)return Du;lp=1;const s=jw();return Du=class{constructor(t){this.hwm=t||16,this.head=new s(this.hwm),this.tail=this.head,this.length=0}clear(){this.head=this.tail,this.head.clear(),this.length=0}push(t){if(this.length++,!this.head.push(t)){const i=this.head;this.head=i.next=new s(2*this.head.buffer.length),this.head.push(t)}}shift(){this.length!==0&&this.length--;const t=this.tail.shift();if(t===void 0&&this.tail.next){const i=this.tail.next;return this.tail.next=null,this.tail=i,this.tail.shift()}return t}peek(){const t=this.tail.peek();return t===void 0&&this.tail.next?this.tail.next.peek():t}isEmpty(){return this.length===0}},Du}var xu,up;function cp(){return up||(up=1,xu=class{constructor(e){this.decoder=new TextDecoder(e==="utf16le"?"utf16-le":e)}get remaining(){return-1}decode(e){return this.decoder.decode(e,{stream:!0})}flush(){return this.decoder.decode(new Uint8Array(0))}}),xu}var Ou,hp;function Gw(){if(hp)return Ou;hp=1;const s=cp(),e=cp();Ou=class{constructor(n="utf8"){switch(this.encoding=t(n),this.encoding){case"utf8":this.decoder=new e;break;case"utf16le":case"base64":throw new Error("Unsupported encoding: "+this.encoding);default:this.decoder=new s(this.encoding)}}get remaining(){return this.decoder.remaining}push(n){return typeof n=="string"?n:this.decoder.decode(n)}write(n){return this.push(n)}end(n){let r="";return n&&(r=this.push(n)),r+=this.decoder.flush(),r}};function t(i){switch(i=i.toLowerCase(),i){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return i;default:throw new Error("Unknown encoding: "+i)}}return Ou}var Mu,dp;function Kw(){if(dp)return Mu;dp=1;const{EventEmitter:s}=qm(),e=new Error("Stream was destroyed"),t=new Error("Premature close"),i=Vw(),n=Gw(),r=(1<<29)-1,o=1,u=2,h=4,p=8,d=r^o,g=r^u,T=16,b=32,E=64,w=128,A=256,L=512,P=1024,M=2048,O=4096,k=8192,N=16384,H=32768,G=65536,B=131072,D=A|L,K=T|G,oe=E|T,Z=O|w,le=A|B,ce=r^T,fe=r^E,ve=r^(E|G),be=r^G,ee=r^A,Q=r^(w|k),Ee=r^P,ae=r^D,ie=r^H,Le=r^b,Ce=r^B,Ue=r^le,He=1<<18,Fe=2<<18,ze=4<<18,ut=8<<18,ot=16<<18,We=32<<18,Bi=64<<18,gi=128<<18,Ui=256<<18,kt=512<<18,gt=1024<<18,Dn=r^(He|Ui),xn=r^ze,an=r^(He|kt),Hi=r^ot,Kt=r^ut,on=r^gi,qt=r^Fe,Ct=r^gt,Wt=T|He,ri=r^Wt,It=N|We,Rt=h|p|u,R=Rt|o,_=Rt|It,C=xn&fe,$=gi|H,q=$&ri,J=R|q,ne=R|P|N,Oe=R|N|w,tt=R|P|w,Xe=R|O|w|k,Ie=R|T|P|N|G|B,$e=Rt|P|N,Ws=b|R|H|E,$i=H|o,ai=R|kt|We,On=ut|ot,zs=ut|He,Fr=ut|ot|R|He,zt=R|He|ut|gt,Nr=ze|He,ln=He|Ui,rs=R|kt|zs|We,Br=ot|Rt|kt|We,Ur=Fe|R|gi|ze,un=kt|We|Rt,mi=Symbol.asyncIterator||Symbol("asyncIterator");class Mn{constructor(F,{highWaterMark:me=16384,map:De=null,mapWritable:Me,byteLength:st,byteLengthWritable:Qe}={}){this.stream=F,this.queue=new i,this.highWaterMark=me,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=Qe||st||Qr,this.map=Me||De,this.afterWrite=yi.bind(this),this.afterUpdateNextTick=Kr.bind(this)}get ended(){return(this.stream._duplexState&We)!==0}push(F){return this.stream._duplexState&un?!1:(this.map!==null&&(F=this.map(F)),this.buffered+=this.byteLength(F),this.queue.push(F),this.buffered<this.highWaterMark?(this.stream._duplexState|=ut,!0):(this.stream._duplexState|=On,!1))}shift(){const F=this.queue.shift();return this.buffered-=this.byteLength(F),this.buffered===0&&(this.stream._duplexState&=Kt),F}end(F){typeof F=="function"?this.stream.once("finish",F):F!=null&&this.push(F),this.stream._duplexState=(this.stream._duplexState|kt)&xn}autoBatch(F,me){const De=[],Me=this.stream;for(De.push(F);(Me._duplexState&zt)===zs;)De.push(Me._writableState.shift());if(Me._duplexState&R)return me(null);Me._writev(De,me)}update(){const F=this.stream;F._duplexState|=Fe;do{for(;(F._duplexState&zt)===ut;){const me=this.shift();F._duplexState|=ln,F._write(me,this.afterWrite)}F._duplexState&Nr||this.updateNonPrimary()}while(this.continueUpdate()===!0);F._duplexState&=qt}updateNonPrimary(){const F=this.stream;if((F._duplexState&rs)===kt){F._duplexState=F._duplexState|He,F._final(jr.bind(this));return}if((F._duplexState&Rt)===h){F._duplexState&$||(F._duplexState|=Wt,F._destroy(cn.bind(this)));return}(F._duplexState&J)===o&&(F._duplexState=(F._duplexState|Wt)&d,F._open(qr.bind(this)))}continueUpdate(){return this.stream._duplexState&gi?(this.stream._duplexState&=on,!0):!1}updateCallback(){(this.stream._duplexState&Ur)===ze?this.update():this.updateNextTick()}updateNextTick(){this.stream._duplexState&gi||(this.stream._duplexState|=gi,this.stream._duplexState&Fe||queueMicrotask(this.afterUpdateNextTick))}}class Hr{constructor(F,{highWaterMark:me=16384,map:De=null,mapReadable:Me,byteLength:st,byteLengthReadable:Qe}={}){this.stream=F,this.queue=new i,this.highWaterMark=me===0?1:me,this.buffered=0,this.readAhead=me>0,this.error=null,this.pipeline=null,this.byteLength=Qe||st||Qr,this.map=Me||De,this.pipeTo=null,this.afterRead=Vr.bind(this),this.afterUpdateNextTick=Gr.bind(this)}get ended(){return(this.stream._duplexState&N)!==0}pipe(F,me){if(this.pipeTo!==null)throw new Error("Can only pipe to one destination");if(typeof me!="function"&&(me=null),this.stream._duplexState|=L,this.pipeTo=F,this.pipeline=new $r(this.stream,F,me),me&&this.stream.on("error",Nt),Nn(F))F._writableState.pipeline=this.pipeline,me&&F.on("error",Nt),F.on("finish",this.pipeline.finished.bind(this.pipeline));else{const De=this.pipeline.done.bind(this.pipeline,F),Me=this.pipeline.done.bind(this.pipeline,F,null);F.on("error",De),F.on("close",Me),F.on("finish",this.pipeline.finished.bind(this.pipeline))}F.on("drain",Xs.bind(this)),this.stream.emit("piping",F),F.emit("pipe",this.stream)}push(F){const me=this.stream;return F===null?(this.highWaterMark=0,me._duplexState=(me._duplexState|P)&ve,!1):this.map!==null&&(F=this.map(F),F===null)?(me._duplexState&=be,this.buffered<this.highWaterMark):(this.buffered+=this.byteLength(F),this.queue.push(F),me._duplexState=(me._duplexState|w)&be,this.buffered<this.highWaterMark)}shift(){const F=this.queue.shift();return this.buffered-=this.byteLength(F),this.buffered===0&&(this.stream._duplexState&=Q),F}unshift(F){const me=[this.map!==null?this.map(F):F];for(;this.buffered>0;)me.push(this.shift());for(let De=0;De<me.length-1;De++){const Me=me[De];this.buffered+=this.byteLength(Me),this.queue.push(Me)}this.push(me[me.length-1])}read(){const F=this.stream;if((F._duplexState&Oe)===w){const me=this.shift();return this.pipeTo!==null&&this.pipeTo.write(me)===!1&&(F._duplexState&=ae),F._duplexState&M&&F.emit("data",me),me}return this.readAhead===!1&&(F._duplexState|=B,this.updateNextTick()),null}drain(){const F=this.stream;for(;(F._duplexState&Oe)===w&&F._duplexState&D;){const me=this.shift();this.pipeTo!==null&&this.pipeTo.write(me)===!1&&(F._duplexState&=ae),F._duplexState&M&&F.emit("data",me)}}update(){const F=this.stream;F._duplexState|=b;do{for(this.drain();this.buffered<this.highWaterMark&&(F._duplexState&Ie)===B;)F._duplexState|=K,F._read(this.afterRead),this.drain();(F._duplexState&Xe)===Z&&(F._duplexState|=k,F.emit("readable")),F._duplexState&oe||this.updateNonPrimary()}while(this.continueUpdate()===!0);F._duplexState&=Le}updateNonPrimary(){const F=this.stream;if((F._duplexState&tt)===P&&(F._duplexState=(F._duplexState|N)&Ee,F.emit("end"),(F._duplexState&_)===It&&(F._duplexState|=h),this.pipeTo!==null&&this.pipeTo.end()),(F._duplexState&Rt)===h){F._duplexState&$||(F._duplexState|=Wt,F._destroy(cn.bind(this)));return}(F._duplexState&J)===o&&(F._duplexState=(F._duplexState|Wt)&d,F._open(qr.bind(this)))}continueUpdate(){return this.stream._duplexState&H?(this.stream._duplexState&=ie,!0):!1}updateCallback(){(this.stream._duplexState&Ws)===E?this.update():this.updateNextTick()}updateNextTickIfOpen(){this.stream._duplexState&$i||(this.stream._duplexState|=H,this.stream._duplexState&b||queueMicrotask(this.afterUpdateNextTick))}updateNextTick(){this.stream._duplexState&H||(this.stream._duplexState|=H,this.stream._duplexState&b||queueMicrotask(this.afterUpdateNextTick))}}class Ys{constructor(F){this.data=null,this.afterTransform=Js.bind(F),this.afterFinal=null}}class $r{constructor(F,me,De){this.from=F,this.to=me,this.afterPipe=De,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(F,me){if(me&&(this.error=me),F===this.to&&(this.to=null,this.from!==null)){(!(this.from._duplexState&N)||!this.pipeToFinished)&&this.from.destroy(this.error||new Error("Writable stream closed prematurely"));return}if(F===this.from&&(this.from=null,this.to!==null)){F._duplexState&N||this.to.destroy(this.error||new Error("Readable stream closed before ending"));return}this.afterPipe!==null&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null}}function Xs(){this.stream._duplexState|=L,this.updateCallback()}function jr(_e){const F=this.stream;_e&&F.destroy(_e),F._duplexState&Rt||(F._duplexState|=We,F.emit("finish")),(F._duplexState&_)===It&&(F._duplexState|=h),F._duplexState&=an,F._duplexState&Fe?this.updateNextTick():this.update()}function cn(_e){const F=this.stream;!_e&&this.error!==e&&(_e=this.error),_e&&F.emit("error",_e),F._duplexState|=p,F.emit("close");const me=F._readableState,De=F._writableState;if(me!==null&&me.pipeline!==null&&me.pipeline.done(F,_e),De!==null){for(;De.drains!==null&&De.drains.length>0;)De.drains.shift().resolve(!1);De.pipeline!==null&&De.pipeline.done(F,_e)}}function yi(_e){const F=this.stream;_e&&F.destroy(_e),F._duplexState&=Dn,this.drains!==null&&Qs(this.drains),(F._duplexState&Fr)===ot&&(F._duplexState&=Hi,(F._duplexState&Bi)===Bi&&F.emit("drain")),this.updateCallback()}function Vr(_e){_e&&this.stream.destroy(_e),this.stream._duplexState&=ce,this.readAhead===!1&&!(this.stream._duplexState&A)&&(this.stream._duplexState&=Ce),this.updateCallback()}function Gr(){this.stream._duplexState&b||(this.stream._duplexState&=ie,this.update())}function Kr(){this.stream._duplexState&Fe||(this.stream._duplexState&=on,this.update())}function Qs(_e){for(let F=0;F<_e.length;F++)--_e[F].writes===0&&(_e.shift().resolve(!0),F--)}function qr(_e){const F=this.stream;_e&&F.destroy(_e),F._duplexState&h||(F._duplexState&ne||(F._duplexState|=E),F._duplexState&ai||(F._duplexState|=ze),F.emit("open")),F._duplexState&=ri,F._writableState!==null&&F._writableState.updateCallback(),F._readableState!==null&&F._readableState.updateCallback()}function Js(_e,F){F!=null&&this.push(F),this._writableState.afterWrite(_e)}function Zs(_e){this._readableState!==null&&(_e==="data"&&(this._duplexState|=M|le,this._readableState.updateNextTick()),_e==="readable"&&(this._duplexState|=O,this._readableState.updateNextTick())),this._writableState!==null&&_e==="drain"&&(this._duplexState|=Bi,this._writableState.updateNextTick())}class as extends s{constructor(F){super(),this._duplexState=0,this._readableState=null,this._writableState=null,F&&(F.open&&(this._open=F.open),F.destroy&&(this._destroy=F.destroy),F.predestroy&&(this._predestroy=F.predestroy),F.signal&&F.signal.addEventListener("abort",it.bind(this))),this.on("newListener",Zs)}_open(F){F(null)}_destroy(F){F(null)}_predestroy(){}get readable(){return this._readableState!==null?!0:void 0}get writable(){return this._writableState!==null?!0:void 0}get destroyed(){return(this._duplexState&p)!==0}get destroying(){return(this._duplexState&Rt)!==0}destroy(F){this._duplexState&Rt||(F||(F=e),this._duplexState=(this._duplexState|h)&C,this._readableState!==null&&(this._readableState.highWaterMark=0,this._readableState.error=F),this._writableState!==null&&(this._writableState.highWaterMark=0,this._writableState.error=F),this._duplexState|=u,this._predestroy(),this._duplexState&=g,this._readableState!==null&&this._readableState.updateNextTick(),this._writableState!==null&&this._writableState.updateNextTick())}}class hn extends as{constructor(F){super(F),this._duplexState|=o|We|B,this._readableState=new Hr(this,F),F&&(this._readableState.readAhead===!1&&(this._duplexState&=Ce),F.read&&(this._read=F.read),F.eagerOpen&&this._readableState.updateNextTick(),F.encoding&&this.setEncoding(F.encoding))}setEncoding(F){const me=new n(F),De=this._readableState.map||ls;return this._readableState.map=Me,this;function Me(st){const Qe=me.push(st);return Qe===""&&(st.byteLength!==0||me.remaining>0)?null:De(Qe)}}_read(F){F(null)}pipe(F,me){return this._readableState.updateNextTick(),this._readableState.pipe(F,me),F}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(F){return this._readableState.updateNextTickIfOpen(),this._readableState.push(F)}unshift(F){return this._readableState.updateNextTickIfOpen(),this._readableState.unshift(F)}resume(){return this._duplexState|=le,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=this._readableState.readAhead===!1?Ue:ee,this}static _fromAsyncIterator(F,me){let De;const Me=new hn({...me,read(Qe){F.next().then(st).then(Qe.bind(null,null)).catch(Qe)},predestroy(){De=F.return()},destroy(Qe){if(!De)return Qe(null);De.then(Qe.bind(null,null)).catch(Qe)}});return Me;function st(Qe){Qe.done?Me.push(null):Me.push(Qe.value)}}static from(F,me){if(dn(F))return F;if(F[mi])return this._fromAsyncIterator(F[mi](),me);Array.isArray(F)||(F=F===void 0?[]:[F]);let De=0;return new hn({...me,read(Me){this.push(De===F.length?null:F[De++]),Me(null)}})}static isBackpressured(F){return(F._duplexState&$e)!==0||F._readableState.buffered>=F._readableState.highWaterMark}static isPaused(F){return(F._duplexState&A)===0}[mi](){const F=this;let me=null,De=null,Me=null;return this.on("error",Ge=>{me=Ge}),this.on("readable",st),this.on("close",Qe),{[mi](){return this},next(){return new Promise(function(Ge,Bt){De=Ge,Me=Bt;const Pt=F.read();Pt!==null?li(Pt):F._duplexState&p&&li(null)})},return(){return fn(null)},throw(Ge){return fn(Ge)}};function st(){De!==null&&li(F.read())}function Qe(){De!==null&&li(null)}function li(Ge){Me!==null&&(me?Me(me):Ge===null&&!(F._duplexState&N)?Me(e):De({value:Ge,done:Ge===null}),Me=De=null)}function fn(Ge){return F.destroy(Ge),new Promise((Bt,Pt)=>{if(F._duplexState&p)return Bt({value:void 0,done:!0});F.once("close",function(){Ge?Pt(Ge):Bt({value:void 0,done:!0})})})}}}class Wr extends as{constructor(F){super(F),this._duplexState|=o|N,this._writableState=new Mn(this,F),F&&(F.writev&&(this._writev=F.writev),F.write&&(this._write=F.write),F.final&&(this._final=F.final),F.eagerOpen&&this._writableState.updateNextTick())}cork(){this._duplexState|=gt}uncork(){this._duplexState&=Ct,this._writableState.updateNextTick()}_writev(F,me){me(null)}_write(F,me){this._writableState.autoBatch(F,me)}_final(F){F(null)}static isBackpressured(F){return(F._duplexState&Br)!==0}static drained(F){if(F.destroyed)return Promise.resolve(!1);const me=F._writableState,Me=(oi(F)?Math.min(1,me.queue.length):me.queue.length)+(F._duplexState&Ui?1:0);return Me===0?Promise.resolve(!0):(me.drains===null&&(me.drains=[]),new Promise(st=>{me.drains.push({writes:Me,resolve:st})}))}write(F){return this._writableState.updateNextTick(),this._writableState.push(F)}end(F){return this._writableState.updateNextTick(),this._writableState.end(F),this}}class er extends hn{constructor(F){super(F),this._duplexState=o|this._duplexState&B,this._writableState=new Mn(this,F),F&&(F.writev&&(this._writev=F.writev),F.write&&(this._write=F.write),F.final&&(this._final=F.final))}cork(){this._duplexState|=gt}uncork(){this._duplexState&=Ct,this._writableState.updateNextTick()}_writev(F,me){me(null)}_write(F,me){this._writableState.autoBatch(F,me)}_final(F){F(null)}write(F){return this._writableState.updateNextTick(),this._writableState.push(F)}end(F){return this._writableState.updateNextTick(),this._writableState.end(F),this}}class Yt extends er{constructor(F){super(F),this._transformState=new Ys(this),F&&(F.transform&&(this._transform=F.transform),F.flush&&(this._flush=F.flush))}_write(F,me){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=F:this._transform(F,this._transformState.afterTransform)}_read(F){if(this._transformState.data!==null){const me=this._transformState.data;this._transformState.data=null,F(null),this._transform(me,this._transformState.afterTransform)}else F(null)}destroy(F){super.destroy(F),this._transformState.data!==null&&(this._transformState.data=null,this._transformState.afterTransform())}_transform(F,me){me(null,F)}_flush(F){F(null)}_final(F){this._transformState.afterFinal=F,this._flush(wt.bind(this))}}class zr extends Yt{}function wt(_e,F){const me=this._transformState.afterFinal;if(_e)return me(_e);F!=null&&this.push(F),this.push(null),me(null)}function Yr(..._e){return new Promise((F,me)=>os(..._e,De=>{if(De)return me(De);F()}))}function os(_e,...F){const me=Array.isArray(_e)?[..._e,...F]:[_e,...F],De=me.length&&typeof me[me.length-1]=="function"?me.pop():null;if(me.length<2)throw new Error("Pipeline requires at least 2 streams");let Me=me[0],st=null,Qe=null;for(let Ge=1;Ge<me.length;Ge++)st=me[Ge],Nn(Me)?Me.pipe(st,fn):(li(Me,!0,Ge>1,fn),Me.pipe(st)),Me=st;if(De){let Ge=!1;const Bt=Nn(st)||!!(st._writableState&&st._writableState.autoDestroy);st.on("error",Pt=>{Qe===null&&(Qe=Pt)}),st.on("finish",()=>{Ge=!0,Bt||De(Qe)}),Bt&&st.on("close",()=>De(Qe||(Ge?null:t)))}return st;function li(Ge,Bt,Pt,tr){Ge.on("error",tr),Ge.on("close",ir);function ir(){if(Ge._readableState&&!Ge._readableState.ended||Pt&&Ge._writableState&&!Ge._writableState.ended)return tr(t)}}function fn(Ge){if(!(!Ge||Qe)){Qe=Ge;for(const Bt of me)Bt.destroy(Ge)}}}function ls(_e){return _e}function Fn(_e){return!!_e._readableState||!!_e._writableState}function Nn(_e){return typeof _e._duplexState=="number"&&Fn(_e)}function Bo(_e){return!!_e._readableState&&_e._readableState.ended}function Ot(_e){return!!_e._writableState&&_e._writableState.ended}function bt(_e,F={}){const me=_e._readableState&&_e._readableState.error||_e._writableState&&_e._writableState.error;return!F.all&&me===e?null:me}function dn(_e){return Nn(_e)&&_e.readable}function us(_e){return(_e._duplexState&o)!==o||(_e._duplexState&$)!==0}function Xr(_e){return typeof _e=="object"&&_e!==null&&typeof _e.byteLength=="number"}function Qr(_e){return Xr(_e)?_e.byteLength:1024}function Nt(){}function it(){this.destroy(new Error("Stream aborted."))}function oi(_e){return _e._writev!==Wr.prototype._writev&&_e._writev!==er.prototype._writev}return Mu={pipeline:os,pipelinePromise:Yr,isStream:Fn,isStreamx:Nn,isEnded:Bo,isFinished:Ot,isDisturbed:us,getStreamError:bt,Stream:as,Writable:Wr,Readable:hn,Duplex:er,Transform:Yt,PassThrough:zr},Mu}var Ym=Kw(),Fu,fp;function qw(){if(fp)return Fu;fp=1;function s(t,i){for(const n in i)Object.defineProperty(t,n,{value:i[n],enumerable:!0,configurable:!0});return t}function e(t,i,n){if(!t||typeof t=="string")throw new TypeError("Please pass an Error to err-code");n||(n={}),typeof i=="object"&&(n=i,i=""),i&&(n.code=i);try{return s(t,n)}catch{n.message=t.message,n.stack=t.stack;const o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(t)),s(new o,n)}}return Fu=e,Fu}var Ww=qw();const ht=ss(Ww);/* Common package for dealing with hex/string/uint8 conversions (and sha1 hashing)
*
* @author   Jimmy Wärting <jimmy@warting.se> (https://jimmy.warting.se/opensource)
* @license  MIT
*/const So="0123456789abcdef",Xm=[],Co=[];for(let s=0;s<256;s++)Xm[s]=So[s>>4&15]+So[s&15],s<16&&(s<10?Co[48+s]=s:Co[87+s]=s);const Gs=s=>{const e=s.length;let t="",i=0;for(;i<e;)t+=Xm[s[i++]];return t},vc=s=>{const e=s.length>>1,t=e<<1,i=new Uint8Array(e);let n=0,r=0;for(;r<t;)i[n++]=Co[s.charCodeAt(r++)]<<4|Co[s.charCodeAt(r++)];return i};var pp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",zw=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(var Na=0;Na<pp.length;Na++)zw[pp.charCodeAt(Na)]=Na;const Yw=new TextDecoder,Qm=(s,e)=>Yw.decode(s),Xw=new TextEncoder,th=s=>Xw.encode(s),Ls=s=>{let e="",t,i=0;const n=s.length;for(;i<n;)t=s.charCodeAt(i++),e+=So[t>>4]+So[t&15];return e},gp=65536,wr=s=>{const e=vc(s);if(e.length<=gp)return String.fromCharCode(...e);let t="",i=0;for(;i<e.length;)t+=String.fromCharCode(...e.subarray(i,i+=gp));return t},mp=typeof window<"u"?window:self,Tc=mp.crypto||mp.msCrypto||{};Tc.subtle||Tc.webkitSubtle;const wo=s=>{const e=new Uint8Array(s);return Tc.getRandomValues(e)};/*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */const Qw=Ni("simple-peer"),Nu=64*1024,Jw=5*1e3,Zw=5*1e3;function yp(s){return s.replace(/a=ice-options:trickle\s\n/g,"")}function e0(s){console.warn(s)}let Mr=class bc extends Ym.Duplex{constructor(e){if(e=Object.assign({allowHalfOpen:!1},e),super(e),se(this,"_pc"),this.__objectMode=!!e.objectMode,this._id=Gs(wo(4)).slice(0,7),this._debug("new peer %o",e),this.channelName=e.initiator?e.channelName||Gs(wo(20)):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||bc.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},bc.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(t=>t),this.trickle=e.trickle!==void 0?e.trickle:!0,this.allowHalfTrickle=e.allowHalfTrickle!==void 0?e.allowHalfTrickle:!1,this.iceCompleteTimeout=e.iceCompleteTimeout||Jw,this._destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,!yc)throw ht(typeof window>"u"?new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"):new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new yc(this.config)}catch(t){this.__destroy(ht(t,"ERR_PC_CONSTRUCTOR"));return}this._isReactNativeWebrtc=typeof this._pc._peerConnectionId=="number",this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=t=>{this._onIceCandidate(t)},typeof this._pc.peerIdentity=="object"&&this._pc.peerIdentity.catch(t=>{this.__destroy(ht(t,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=t=>{this._setupData(t)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&this._channel.readyState==="open"}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(e){if(!this._destroying){if(this.destroyed)throw ht(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if(typeof e=="string")try{e=JSON.parse(e)}catch{e={}}this._debug("signal()"),e.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),e.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new Hw(e)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(t=>{this._addIceCandidate(t)}),this._pendingCandidates=[],this._pc.remoteDescription.type==="offer"&&this._createAnswer())}).catch(t=>{this.__destroy(ht(t,"ERR_SET_REMOTE_DESCRIPTION"))}),!e.sdp&&!e.candidate&&!e.renegotiate&&!e.transceiverRequest&&this.__destroy(ht(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(e){const t=new $w(e);this._pc.addIceCandidate(t).catch(i=>{!t.address||t.address.endsWith(".local")?e0("Ignoring unsupported ICE candidate."):this.__destroy(ht(i,"ERR_ADD_ICE_CANDIDATE"))})}send(e){if(!this._destroying){if(this.destroyed)throw ht(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(e)}}_needsNegotiation(){this._debug("_needsNegotiation"),!this._batchedNegotiation&&(this._batchedNegotiation=!0,queueMicrotask(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this._destroying){if(this.destroyed)throw ht(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}_final(e){this._readableState.ended||this.push(null),e(null)}__destroy(e){this.end(),this._destroy(()=>{},e)}_destroy(e,t){this.destroyed||this._destroying||(this._destroying=!0,this._debug("destroying (error: %s)",t&&(t.message||t)),setTimeout(()=>{if(this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch{}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch{}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,t&&this.emit("error",t),e()},0))}_setupData(e){if(!e.channel)return this.__destroy(ht(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=e.channel,this._channel.binaryType="arraybuffer",typeof this._channel.bufferedAmountLowThreshold=="number"&&(this._channel.bufferedAmountLowThreshold=Nu),this.channelName=this._channel.label,this._channel.onmessage=i=>{this._onChannelMessage(i)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=i=>{const n=i.error instanceof Error?i.error:new Error(`Datachannel error: ${i.message} ${i.filename}:${i.lineno}:${i.colno}`);this.__destroy(ht(n,"ERR_DATA_CHANNEL"))};let t=!1;this._closingInterval=setInterval(()=>{this._channel&&this._channel.readyState==="closing"?(t&&this._onChannelClose(),t=!0):t=!1},Zw)}_write(e,t){if(this.destroyed)return t(ht(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(e)}catch(i){return this.__destroy(ht(i,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>Nu?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=t):t(null)}else this._debug("write before connect"),this._chunk=e,this._cb=t}_onFinish(){if(this.destroyed)return;const e=()=>{setTimeout(()=>this.__destroy(),1e3)};this._connected?e():this.once("connect",e)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(e=>{if(this.destroyed)return;!this.trickle&&!this.allowHalfTrickle&&(e.sdp=yp(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const r=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:r.type,sdp:r.sdp})},i=()=>{this._debug("createOffer success"),!this.destroyed&&(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))},n=r=>{this.__destroy(ht(r,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(e).then(i).catch(n)}).catch(e=>{this.__destroy(ht(e,"ERR_CREATE_OFFER"))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(e=>{if(this.destroyed)return;!this.trickle&&!this.allowHalfTrickle&&(e.sdp=yp(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{var r;if(this.destroyed)return;const o=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:o.type,sdp:o.sdp}),this.initiator||(r=this._requestMissingTransceivers)==null||r.call(this)},i=()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))},n=r=>{this.__destroy(ht(r,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(e).then(i).catch(n)}).catch(e=>{this.__destroy(ht(e,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||this._destroying||this._pc.connectionState==="failed"&&this.__destroy(ht(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",e,t),this.emit("iceStateChange",e,t),(e==="connected"||e==="completed")&&(this._pcReady=!0,this._maybeReady()),e==="failed"&&this.__destroy(ht(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),e==="closed"&&this.__destroy(ht(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(e){const t=i=>(Object.prototype.toString.call(i.values)==="[object Array]"&&i.values.forEach(n=>{Object.assign(i,n)}),i);this._pc.getStats.length===0||this._isReactNativeWebrtc?this._pc.getStats().then(i=>{const n=[];i.forEach(r=>{n.push(t(r))}),e(null,n)},i=>e(i)):this._pc.getStats.length>0?this._pc.getStats(i=>{if(this.destroyed)return;const n=[];i.result().forEach(r=>{const o={};r.names().forEach(u=>{o[u]=r.stat(u)}),o.id=r.id,o.type=r.type,o.timestamp=r.timestamp,n.push(t(o))}),e(null,n)},i=>e(i)):e(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this._destroying||this.getStats((t,i)=>{if(this.destroyed||this._destroying)return;t&&(i=[]);const n={},r={},o={};let u=!1;i.forEach(p=>{(p.type==="remotecandidate"||p.type==="remote-candidate")&&(n[p.id]=p),(p.type==="localcandidate"||p.type==="local-candidate")&&(r[p.id]=p),(p.type==="candidatepair"||p.type==="candidate-pair")&&(o[p.id]=p)});const h=p=>{u=!0;let d=r[p.localCandidateId];d&&(d.ip||d.address)?(this.localAddress=d.ip||d.address,this.localPort=Number(d.port)):d&&d.ipAddress?(this.localAddress=d.ipAddress,this.localPort=Number(d.portNumber)):typeof p.googLocalAddress=="string"&&(d=p.googLocalAddress.split(":"),this.localAddress=d[0],this.localPort=Number(d[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let g=n[p.remoteCandidateId];g&&(g.ip||g.address)?(this.remoteAddress=g.ip||g.address,this.remotePort=Number(g.port)):g&&g.ipAddress?(this.remoteAddress=g.ipAddress,this.remotePort=Number(g.portNumber)):typeof p.googRemoteAddress=="string"&&(g=p.googRemoteAddress.split(":"),this.remoteAddress=g[0],this.remotePort=Number(g[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(i.forEach(p=>{p.type==="transport"&&p.selectedCandidatePairId&&h(o[p.selectedCandidatePairId]),(p.type==="googCandidatePair"&&p.googActiveConnection==="true"||(p.type==="candidatepair"||p.type==="candidate-pair")&&p.selected)&&h(p)}),!u&&(!Object.keys(o).length||Object.keys(r).length)){setTimeout(e,100);return}else this._connecting=!1,this._connected=!0;if(this._chunk){try{this.send(this._chunk)}catch(d){return this.__destroy(ht(d,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const p=this._cb;this._cb=null,p(null)}typeof this._channel.bufferedAmountLowThreshold!="number"&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>Nu||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||(this._pc.signalingState==="stable"&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):!e.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer?t=new Uint8Array(t):this.__objectMode===!1&&(t=th(t)),this.push(t)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const e=this._cb;this._cb=null,e(null)}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.__destroy())}_debug(){const e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],Qw.apply(null,e)}};Mr.WEBRTC_SUPPORT=!!yc;Mr.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"};Mr.channelConfig={};var t0=zm();const _c=ss(t0),xi={},i0=Object.freeze(Object.defineProperty({__proto__:null,default:xi},Symbol.toStringTag,{value:"Module"})),n0=50,s0=s=>{const e=new URL(s.replace(/^udp:/,"http:"));return s.match(/^udp:/)&&Object.defineProperties(e,{href:{value:e.href.replace(/^http/,"udp")},protocol:{value:e.protocol.replace(/^http/,"udp")},origin:{value:e.origin.replace(/^http/,"udp")}}),e},Ec={DEFAULT_ANNOUNCE_PEERS:n0,parseUrl:s0,...i0};/*! simple-websocket. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */const r0=Ni("simple-websocket"),Er=typeof xi!="function"?WebSocket:xi,vp=64*1024;class Jm extends Ym.Duplex{constructor(e={}){if(typeof e=="string"&&(e={url:e}),e=Object.assign({allowHalfOpen:!1},e),super(e),this.__objectMode=!!e.objectMode,e.objectMode!=null&&delete e.objectMode,e.url==null&&e.socket==null)throw new Error("Missing required `url` or `socket` option");if(e.url!=null&&e.socket!=null)throw new Error("Must specify either `url` or `socket` option, not both");if(this._id=Gs(wo(4)).slice(0,7),this._debug("new websocket: %o",e),this.connected=!1,this._chunk=null,this._cb=null,this._interval=null,e.socket)this.url=e.socket.url,this._ws=e.socket,this.connected=e.socket.readyState===Er.OPEN;else{this.url=e.url;try{typeof xi=="function"?this._ws=new Er(e.url,{...e,encoding:void 0}):this._ws=new Er(e.url)}catch(t){_c(()=>this.destroy(t));return}}this._ws.binaryType="arraybuffer",e.socket&&this.connected?_c(()=>this._handleOpen()):this._ws.onopen=()=>this._handleOpen(),this._ws.onmessage=t=>this._handleMessage(t),this._ws.onclose=()=>this._handleClose(),this._ws.onerror=t=>this._handleError(t),this._handleFinishBound=()=>this._handleFinish(),this.once("finish",this._handleFinishBound)}send(e){this._ws.send(e)}_final(e){this._readableState.ended||this.push(null),e(null)}_destroy(e){if(!this.destroyed){if(this._writableState.ended||this.end(),this.connected=!1,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._handleFinishBound&&this.removeListener("finish",this._handleFinishBound),this._handleFinishBound=null,this._ws){const t=this._ws,i=()=>{t.onclose=null};if(t.readyState===Er.CLOSED)i();else try{t.onclose=i,t.close()}catch{i()}t.onopen=null,t.onmessage=null,t.onerror=()=>{}}this._ws=null,e()}}_write(e,t){if(this.destroyed)return t(new Error("cannot write after socket is destroyed"));if(this.connected){try{this.send(e)}catch(i){return this.destroy(i)}typeof xi!="function"&&this._ws.bufferedAmount>vp?(this._debug("start backpressure: bufferedAmount %d",this._ws.bufferedAmount),this._cb=t):t(null)}else this._debug("write before connect"),this._chunk=e,this._cb=t}_handleOpen(){if(!(this.connected||this.destroyed)){if(this.connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.destroy(t)}this._chunk=null,this._debug('sent chunk from "write before connect"');const e=this._cb;this._cb=null,e(null)}typeof xi!="function"&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}}_handleMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=new Uint8Array(t)),this.__objectMode===!1&&(t=th(t)),this.push(t)}_handleClose(){this.destroyed||(this._debug("on close"),this.destroy())}_handleError(e){this.destroy(new Error(`Error connecting to ${this.url}`))}_handleFinish(){if(this.destroyed)return;const e=()=>{setTimeout(()=>this.destroy(),1e3)};this.connected?e():this.once("connect",e)}_onInterval(){if(!this._cb||!this._ws||this._ws.bufferedAmount>vp)return;this._debug("ending backpressure: bufferedAmount %d",this._ws.bufferedAmount);const e=this._cb;this._cb=null,e(null)}_debug(){const e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],r0.apply(null,e)}}Jm.WEBSOCKET_SUPPORT=!!Er;class a0 extends Wm{constructor(e,t){super(),this.client=e,this.announceUrl=t,this.interval=null,this.destroyed=!1}setInterval(e){e==null&&(e=this.DEFAULT_ANNOUNCE_INTERVAL),clearInterval(this.interval),e&&(this.interval=setInterval(()=>{this.announce(this.client._defaultAnnounceOpts())},e),this.interval.unref&&this.interval.unref())}}const ci=Ni("bittorrent-tracker:websocket-tracker"),Ki={},o0=10*1e3,l0=60*60*1e3,u0=5*60*1e3,c0=50*1e3;class ih extends a0{constructor(e,t){super(e,t),ci("new websocket tracker %s",t),this.peers={},this.socket=null,this.reconnecting=!1,this.retries=0,this.reconnectTimer=null,this.expectingResponse=!1,this._openSocket()}announce(e){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected){this.socket.once("connect",()=>{this.announce(e)});return}const t=Object.assign({},e,{action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary});if(this._trackerId&&(t.trackerid=this._trackerId),e.event==="stopped"||e.event==="completed")this._send(t);else{const i=Math.min(e.numwant,5);this._generateOffers(i,n=>{t.numwant=i,t.offers=n,this._send(t)})}}scrape(e){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected){this.socket.once("connect",()=>{this.scrape(e)});return}const i={action:"scrape",info_hash:Array.isArray(e.infoHash)&&e.infoHash.length>0?e.infoHash.map(n=>wr(n)):e.infoHash&&wr(e.infoHash)||this.client._infoHashBinary};this._send(i)}destroy(e=Tp){if(this.destroyed)return e(null);this.destroyed=!0,clearInterval(this.interval),clearTimeout(this.reconnectTimer);for(const r in this.peers){const o=this.peers[r];clearTimeout(o.trackerTimeout),o.destroy()}if(this.peers=null,this.socket&&(this.socket.removeListener("connect",this._onSocketConnectBound),this.socket.removeListener("data",this._onSocketDataBound),this.socket.removeListener("close",this._onSocketCloseBound),this.socket.removeListener("error",this._onSocketErrorBound),this.socket=null),this._onSocketConnectBound=null,this._onSocketErrorBound=null,this._onSocketDataBound=null,this._onSocketCloseBound=null,Ki[this.announceUrl]&&(Ki[this.announceUrl].consumers-=1),Ki[this.announceUrl].consumers>0)return e();let t=Ki[this.announceUrl];delete Ki[this.announceUrl],t.on("error",Tp),t.once("close",e);let i;if(!this.expectingResponse)return n();i=setTimeout(n,Ec.DESTROY_TIMEOUT),t.once("data",n);function n(){i&&(clearTimeout(i),i=null),t.removeListener("data",n),t.destroy(),t=null}}_openSocket(){if(this.destroyed=!1,this.peers||(this.peers={}),this._onSocketConnectBound=()=>{this._onSocketConnect()},this._onSocketErrorBound=e=>{this._onSocketError(e)},this._onSocketDataBound=e=>{this._onSocketData(e)},this._onSocketCloseBound=()=>{this._onSocketClose()},this.socket=Ki[this.announceUrl],this.socket)Ki[this.announceUrl].consumers+=1,this.socket.connected&&this._onSocketConnectBound();else{const e=new URL(this.announceUrl);let t;this.client._proxyOpts&&(t=e.protocol==="wss:"?this.client._proxyOpts.httpsAgent:this.client._proxyOpts.httpAgent,!t&&this.client._proxyOpts.socksProxy&&(t=this.client._proxyOpts.socksProxy)),this.socket=Ki[this.announceUrl]=new Jm({url:this.announceUrl,agent:t}),this.socket.consumers=1,this.socket.once("connect",this._onSocketConnectBound)}this.socket.on("data",this._onSocketDataBound),this.socket.once("close",this._onSocketCloseBound),this.socket.once("error",this._onSocketErrorBound)}_onSocketConnect(){this.destroyed||this.reconnecting&&(this.reconnecting=!1,this.retries=0,this.announce(this.client._defaultAnnounceOpts()))}_onSocketData(e){if(!this.destroyed){this.expectingResponse=!1;try{e=JSON.parse(Qm(e))}catch{this.client.emit("warning",new Error("Invalid tracker response"));return}e.action==="announce"?this._onAnnounceResponse(e):e.action==="scrape"?this._onScrapeResponse(e):this._onSocketError(new Error(`invalid action in WS response: ${e.action}`))}}_onAnnounceResponse(e){if(e.info_hash!==this.client._infoHashBinary){ci("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,Ls(e.info_hash),this.client.infoHash);return}if(e.peer_id&&e.peer_id===this.client._peerIdBinary)return;ci("received %s from %s for %s",JSON.stringify(e),this.announceUrl,this.client.infoHash);const t=e["failure reason"];if(t)return this.client.emit("warning",new Error(t));const i=e["warning message"];i&&this.client.emit("warning",new Error(i));const n=e.interval||e["min interval"];n&&this.setInterval(n*1e3);const r=e["tracker id"];if(r&&(this._trackerId=r),e.complete!=null){const u=Object.assign({},e,{announce:this.announceUrl,infoHash:Ls(e.info_hash)});this.client.emit("update",u)}let o;if(e.offer&&e.peer_id&&(ci("creating peer (from remote offer)"),o=this._createPeer(),o.id=Ls(e.peer_id),o.once("signal",u=>{const h={action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary,to_peer_id:e.peer_id,answer:u,offer_id:e.offer_id};this._trackerId&&(h.trackerid=this._trackerId),this._send(h)}),this.client.emit("peer",o),o.signal(e.offer)),e.answer&&e.peer_id){const u=Ls(e.offer_id);o=this.peers[u],o?(o.id=Ls(e.peer_id),this.client.emit("peer",o),o.signal(e.answer),clearTimeout(o.trackerTimeout),o.trackerTimeout=null,delete this.peers[u]):ci(`got unexpected answer: ${JSON.stringify(e.answer)}`)}}_onScrapeResponse(e){e=e.files||{};const t=Object.keys(e);if(t.length===0){this.client.emit("warning",new Error("invalid scrape response"));return}t.forEach(i=>{const n=Object.assign(e[i],{announce:this.announceUrl,infoHash:Ls(i)});this.client.emit("scrape",n)})}_onSocketClose(){this.destroyed||(this.destroy(),this._startReconnectTimer())}_onSocketError(e){this.destroyed||(this.destroy(),this.client.emit("warning",e),this._startReconnectTimer())}_startReconnectTimer(){const e=Math.floor(Math.random()*u0)+Math.min(Math.pow(2,this.retries)*o0,l0);this.reconnecting=!0,clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.retries++,this._openSocket()},e),this.reconnectTimer.unref&&this.reconnectTimer.unref(),ci("reconnecting socket in %s ms",e)}_send(e){if(this.destroyed)return;this.expectingResponse=!0;const t=JSON.stringify(e);ci("send %s",t),this.socket.send(t)}_generateOffers(e,t){const i=this,n=[];ci("generating %s offers",e);for(let u=0;u<e;++u)r();o();function r(){const u=Gs(wo(20));ci("creating peer (from _generateOffers)");const h=i.peers[u]=i._createPeer({initiator:!0});h.once("signal",p=>{n.push({offer:p,offer_id:wr(u)}),o()}),h.trackerTimeout=setTimeout(()=>{ci("tracker timeout: destroying peer"),h.trackerTimeout=null,delete i.peers[u],h.destroy()},c0),h.trackerTimeout.unref&&h.trackerTimeout.unref()}function o(){n.length===e&&(ci("generated %s offers",e),t(n))}}_createPeer(e){const t=this;e=Object.assign({trickle:!1,config:t.client._rtcConfig,wrtc:t.client._wrtc},e);const i=new Mr(e);return i.once("error",n),i.once("connect",r),i;function n(o){t.client.emit("warning",new Error(`Connection error: ${o.message}`)),i.destroy()}function r(){i.removeListener("error",n),i.removeListener("connect",r)}}}ih.prototype.DEFAULT_ANNOUNCE_INTERVAL=30*1e3;ih._socketPool=Ki;function Tp(){}const mn=Ni("bittorrent-tracker:client");class Sc extends Wm{constructor(e={}){if(super(),!e.peerId)throw new Error("Option `peerId` is required");if(!e.infoHash)throw new Error("Option `infoHash` is required");if(!e.announce)throw new Error("Option `announce` is required");if(!to.browser&&!e.port)throw new Error("Option `port` is required");this.peerId=typeof e.peerId=="string"?e.peerId:Gs(e.peerId),this._peerIdBuffer=vc(this.peerId),this._peerIdBinary=wr(this.peerId),this.infoHash=typeof e.infoHash=="string"?e.infoHash.toLowerCase():Gs(e.infoHash),this._infoHashBuffer=vc(this.infoHash),this._infoHashBinary=wr(this.infoHash),mn("new client %s",this.infoHash),this.destroyed=!1,this._port=e.port,this._getAnnounceOpts=e.getAnnounceOpts,this._rtcConfig=e.rtcConfig,this._userAgent=e.userAgent,this._proxyOpts=e.proxyOpts,this._wrtc=typeof e.wrtc=="function"?e.wrtc():e.wrtc;let t=typeof e.announce=="string"?[e.announce]:e.announce==null?[]:e.announce;t=t.map(r=>(ArrayBuffer.isView(r)&&(r=Qm(r)),r[r.length-1]==="/"&&(r=r.substring(0,r.length-1)),r)),t=Array.from(new Set(t));const i=this._wrtc!==!1&&(!!this._wrtc||Mr.WEBRTC_SUPPORT),n=r=>{_c(()=>{this.emit("warning",r)})};this._trackers=t.map(r=>{let o;try{o=Ec.parseUrl(r)}catch{return n(new Error(`Invalid tracker URL: ${r}`)),null}const u=o.port;if(u<0||u>65535)return n(new Error(`Invalid tracker port: ${r}`)),null;const h=o.protocol;return(h==="http:"||h==="https:")&&typeof xi=="function"?new xi(this,r):h==="udp:"&&typeof xi=="function"?new xi(this,r):(h==="ws:"||h==="wss:")&&i?h==="ws:"&&typeof window<"u"&&window.location.protocol==="https:"?(n(new Error(`Unsupported tracker protocol: ${r}`)),null):new ih(this,r):(n(new Error(`Unsupported tracker protocol: ${r}`)),null)}).filter(Boolean)}start(e){e=this._defaultAnnounceOpts(e),e.event="started",mn("send `start` %o",e),this._announce(e),this._trackers.forEach(t=>{t.setInterval()})}stop(e){e=this._defaultAnnounceOpts(e),e.event="stopped",mn("send `stop` %o",e),this._announce(e)}complete(e){e||(e={}),e=this._defaultAnnounceOpts(e),e.event="completed",mn("send `complete` %o",e),this._announce(e)}update(e){e=this._defaultAnnounceOpts(e),e.event&&delete e.event,mn("send `update` %o",e),this._announce(e)}_announce(e){this._trackers.forEach(t=>{t.announce(e)})}scrape(e){mn("send `scrape`"),e||(e={}),this._trackers.forEach(t=>{t.scrape(e)})}setInterval(e){mn("setInterval %d",e),this._trackers.forEach(t=>{t.setInterval(e)})}destroy(e){if(this.destroyed)return;this.destroyed=!0,mn("destroy");const t=this._trackers.map(i=>n=>{i.destroy(n)});Uw(t,e),this._trackers=[],this._getAnnounceOpts=null}_defaultAnnounceOpts(e={}){return e.numwant==null&&(e.numwant=Ec.DEFAULT_ANNOUNCE_PEERS),e.uploaded==null&&(e.uploaded=0),e.downloaded==null&&(e.downloaded=0),this._getAnnounceOpts&&(e=Object.assign({},e,this._getAnnounceOpts())),e}}Sc.scrape=(s,e)=>{if(e=Fw(e),!s.infoHash)throw new Error("Option `infoHash` is required");if(!s.announce)throw new Error("Option `announce` is required");const t=Object.assign({},s,{infoHash:Array.isArray(s.infoHash)?s.infoHash[0]:s.infoHash,peerId:th("01234567890123456789"),port:6881}),i=new Sc(t);i.once("error",e),i.once("warning",e);let n=Array.isArray(s.infoHash)?s.infoHash.length:1;const r={};return i.on("scrape",o=>{if(n-=1,r[o.infoHash]=o,n===0){i.destroy();const u=Object.keys(r);u.length===1?e(null,r[u[0]]):e(null,r)}}),i.scrape({infoHash:s.infoHash}),i};var Bu={exports:{}},bp;function h0(){if(bp)return Bu.exports;bp=1;function s(L,P,M,O,k,N,H){var G=L+(P&M|~P&O)+(k>>>0)+H;return(G<<N|G>>>32-N)+P}function e(L,P,M,O,k,N,H){var G=L+(P&O|M&~O)+(k>>>0)+H;return(G<<N|G>>>32-N)+P}function t(L,P,M,O,k,N,H){var G=L+(P^M^O)+(k>>>0)+H;return(G<<N|G>>>32-N)+P}function i(L,P,M,O,k,N,H){var G=L+(M^(P|~O))+(k>>>0)+H;return(G<<N|G>>>32-N)+P}function n(L){return(256+(L&255)).toString(16).substr(-2)}function r(L){return String.fromCharCode(L&255)}function o(L){return r(L)+r(L>>>8)+r(L>>>16)+r(L>>>24)}var u=function(L){return unescape(encodeURIComponent(L))};function h(L){for(var P=L.length,M=P<<3,O=new Uint32Array(P+72>>>6<<4),k=0,N=L.length;k<N;++k)O[k>>>2]|=L.charCodeAt(k)<<((k&3)<<3);return O[P>>2]|=128<<(M&31),O[O.length-2]=M,O}var p=Bu.exports=function(P){return g(P).toHex()},d=p.fromBytes=function(L){for(var P=h(L),M=1732584193,O=4023233417,k=2562383102,N=271733878,H=7,G=12,B=17,D=22,K=5,oe=9,Z=14,le=20,ce=4,fe=11,ve=16,be=23,ee=6,Q=10,Ee=15,ae=21,ie=0,Le=P.length;ie<Le;ie+=16){var Ce=M,Ue=O,He=k,Fe=N;M=s(M,O,k,N,P[ie+0],H,3614090360),N=s(N,M,O,k,P[ie+1],G,3905402710),k=s(k,N,M,O,P[ie+2],B,606105819),O=s(O,k,N,M,P[ie+3],D,3250441966),M=s(M,O,k,N,P[ie+4],H,4118548399),N=s(N,M,O,k,P[ie+5],G,1200080426),k=s(k,N,M,O,P[ie+6],B,2821735955),O=s(O,k,N,M,P[ie+7],D,4249261313),M=s(M,O,k,N,P[ie+8],H,1770035416),N=s(N,M,O,k,P[ie+9],G,2336552879),k=s(k,N,M,O,P[ie+10],B,4294925233),O=s(O,k,N,M,P[ie+11],D,2304563134),M=s(M,O,k,N,P[ie+12],H,1804603682),N=s(N,M,O,k,P[ie+13],G,4254626195),k=s(k,N,M,O,P[ie+14],B,2792965006),O=s(O,k,N,M,P[ie+15],D,1236535329),M=e(M,O,k,N,P[ie+1],K,4129170786),N=e(N,M,O,k,P[ie+6],oe,3225465664),k=e(k,N,M,O,P[ie+11],Z,643717713),O=e(O,k,N,M,P[ie+0],le,3921069994),M=e(M,O,k,N,P[ie+5],K,3593408605),N=e(N,M,O,k,P[ie+10],oe,38016083),k=e(k,N,M,O,P[ie+15],Z,3634488961),O=e(O,k,N,M,P[ie+4],le,3889429448),M=e(M,O,k,N,P[ie+9],K,568446438),N=e(N,M,O,k,P[ie+14],oe,3275163606),k=e(k,N,M,O,P[ie+3],Z,4107603335),O=e(O,k,N,M,P[ie+8],le,1163531501),M=e(M,O,k,N,P[ie+13],K,2850285829),N=e(N,M,O,k,P[ie+2],oe,4243563512),k=e(k,N,M,O,P[ie+7],Z,1735328473),O=e(O,k,N,M,P[ie+12],le,2368359562),M=t(M,O,k,N,P[ie+5],ce,4294588738),N=t(N,M,O,k,P[ie+8],fe,2272392833),k=t(k,N,M,O,P[ie+11],ve,1839030562),O=t(O,k,N,M,P[ie+14],be,4259657740),M=t(M,O,k,N,P[ie+1],ce,2763975236),N=t(N,M,O,k,P[ie+4],fe,1272893353),k=t(k,N,M,O,P[ie+7],ve,4139469664),O=t(O,k,N,M,P[ie+10],be,3200236656),M=t(M,O,k,N,P[ie+13],ce,681279174),N=t(N,M,O,k,P[ie+0],fe,3936430074),k=t(k,N,M,O,P[ie+3],ve,3572445317),O=t(O,k,N,M,P[ie+6],be,76029189),M=t(M,O,k,N,P[ie+9],ce,3654602809),N=t(N,M,O,k,P[ie+12],fe,3873151461),k=t(k,N,M,O,P[ie+15],ve,530742520),O=t(O,k,N,M,P[ie+2],be,3299628645),M=i(M,O,k,N,P[ie+0],ee,4096336452),N=i(N,M,O,k,P[ie+7],Q,1126891415),k=i(k,N,M,O,P[ie+14],Ee,2878612391),O=i(O,k,N,M,P[ie+5],ae,4237533241),M=i(M,O,k,N,P[ie+12],ee,1700485571),N=i(N,M,O,k,P[ie+3],Q,2399980690),k=i(k,N,M,O,P[ie+10],Ee,4293915773),O=i(O,k,N,M,P[ie+1],ae,2240044497),M=i(M,O,k,N,P[ie+8],ee,1873313359),N=i(N,M,O,k,P[ie+15],Q,4264355552),k=i(k,N,M,O,P[ie+6],Ee,2734768916),O=i(O,k,N,M,P[ie+13],ae,1309151649),M=i(M,O,k,N,P[ie+4],ee,4149444226),N=i(N,M,O,k,P[ie+11],Q,3174756917),k=i(k,N,M,O,P[ie+2],Ee,718787259),O=i(O,k,N,M,P[ie+9],ae,3951481745),M=M+Ce>>>0,O=O+Ue>>>0,k=k+He>>>0,N=N+Fe>>>0}var ze=new String(o(M)+o(O)+o(k)+o(N));return ze.toHex=function(){for(var ut="",ot=0,We=ze.length;ot<We;++ot)ut+=n(ze.charCodeAt(ot));return ut},ze},g=p.fromUtf8=function(L){return d(u(L))},T="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function b(L,P){for(var M="";--P>=0;L>>>=6)M+=T.charAt(L&63);return M}var E=64,w=[0,6,12,1,7,13,2,8,14,3,9,15,4,10,5,11],A=p.salt=function(L){var P="";L||(L=8);do P+=T.charAt(64*Math.random()>>>0);while(--L);return P};return p.crypt=function(L,P){if(L.length>E)throw Error("too long key");P||(P="$1$"+A()),L=u(L);for(var M=u(P.replace(/^\$1\$([^$]+)(?:\$.*)?$/,"$1")),O=d(L+M+L),k=L+"$1$"+M,N=L.length;N>16;N-=16)k+=O;k+=O.slice(0,N);for(var N=L.length;N;N>>=1)k+=N&1?"\0":L.charAt(0);O=d(k);for(var H=0;H<1e3;++H)O=d((H&1?L:O)+(H%3?M:"")+(H%7?L:"")+(H&1?O:L));for(var G="$1$"+M+"$",H=0;H<15;H+=3)G+=b(O.charCodeAt(w[H+0])<<16|O.charCodeAt(w[H+1])<<8|O.charCodeAt(w[H+2]),4);return G+b(O.charCodeAt(w[15]),2)},Bu.exports}var d0=h0();const f0=ss(d0),p0="2.2.1",g0=`-PM${T0(p0)}-`,_p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",m0=20;function y0(s){const e=f0.fromUtf8(s).slice(1);return btoa(e)}function v0(s){const e=[s],t=m0-s.length;for(let i=0;i<t;i++)e.push(_p[Math.floor(Math.random()*_p.length)]);return e.join("")}function T0(s){const e=s.split(".");return`${e[0].padStart(2,"0")}${e[1].padStart(2,"0")}`}function kn(s){return`${s.type}-${s.index}`}function Ep(s){const{externalId:e}=s;return`(${kn(s.stream)} | ${e})`}function b0(){let s,e;return{promise:new Promise((i,n)=>{s=i,e=n}),resolve:s,reject:e}}function Zm(s,e){e===void 0&&(e=s.reduce((n,r)=>n+r.byteLength,0));const t=new Uint8Array(e);let i=0;for(const n of s)t.set(n,i),i+=n.byteLength;return t}function _0(s){return s[Math.floor(Math.random()*s.length)]}function Sp(s){const e=new TextEncoder,t=new Uint8Array(s.length);return e.encodeInto(s,t),t}function E0(s){const e=new Uint8Array(s.length/2);for(let i=0;i<s.length;i+=2)e[i/2]=parseInt(s.slice(i,i+2),16);return new TextDecoder().decode(e)}function*Cp(s){for(let e=s.length-1;e>=0;e--)yield s[e]}function ey(s){return!!s&&typeof s=="object"&&!Array.isArray(s)}function S0(s){return Array.isArray(s)}function C0(s){function e(t){if(ey(t)){const i={};return Object.keys(t).forEach(n=>{if(t[n]!==void 0){const r=e(t[n]);r!==void 0&&(i[n]=r)}}),i}else return t}return e(s)}function Cn(s){if(S0(s))return s.map(e=>Cn(e));if(ey(s)){const e={};for(const t of Object.keys(s))e[t]=Cn(s[t]);return e}else return s}function w0(s){for(let e=s.length-1;e>0;e--){const t=Math.floor(Math.random()*(e+1));[s[e],s[t]]=[s[t],s[e]]}return s}function yr(s,e,t={}){return typeof s!="object"||s===null||typeof e!="object"||e===null||Object.keys(e).forEach(i=>{if(i==="__proto__"||i==="constructor"||i==="prototype")throw new Error(`Attempt to modify restricted property '${String(i)}'`);const n=e[i],r=t[i];i in s&&(n===void 0?s[i]=r===void 0?void 0:r:s[i]=n)}),s}function Uu(s){const{defaultConfig:e,baseConfig:t={},specificStreamConfig:i={}}=s,n=Cn({...e,...t,...i}),r=Object.keys(e),o={};return r.forEach(u=>{u in n&&(o[u]=n[u])}),o}var bn=(s=>(s[s.SegmentsAnnouncement=0]="SegmentsAnnouncement",s[s.SegmentRequest=1]="SegmentRequest",s[s.SegmentData=2]="SegmentData",s[s.SegmentDataSendingCompleted=3]="SegmentDataSendingCompleted",s[s.SegmentAbsent=4]="SegmentAbsent",s[s.CancelSegmentRequest=5]="CancelSegmentRequest",s))(bn||{}),Ns=(s=>(s[s.Min=-1]="Min",s[s.Int=0]="Int",s[s.SimilarIntArray=1]="SimilarIntArray",s[s.String=2]="String",s[s.Max=3]="Max",s))(Ns||{});function A0(s){return s<0?-s:s}function L0(s){const e=s.toString(2),t=s<0?e.length:e.length+1;return Math.ceil(t/8)}function k0(s){const e=s<0,t=L0(s),i=new Uint8Array(t),n=BigInt(t);s=A0(s);for(let r=0;r<t;r++){const o=8n*(n-1n-BigInt(r)),u=s>>o&0xffn;i[r]=Number(u)}return e&&(i[0]=i[0]|128),i}function I0(s){const e=BigInt(s.length),t=(n,r)=>{const o=8n*(e-1n-BigInt(r));return BigInt(n)<<o};let i=t(s[0]&127,0);for(let n=1;n<e;n++)i=t(s[n],n)|i;return(s[0]&128)>>7&&(i=-i),i}function ty(s){const e=k0(s),t=0|e.length;return new Uint8Array([t,...e])}function iy(s){const e=s[0];if(e>>4!==0)throw new Error("Trying to deserialize integer with invalid serialized item code");const i=e&15,n=1,r=n+i;return{number:I0(s.slice(n,r)),byteLength:i+1}}function R0(s){const e=new Map;for(const i of s){const n=i&~0xffn,r=i&0xffn,o=e.get(n)??new Dr;o.length||e.set(n,o),o.push(Number(r))}const t=new Dr;t.push([16,e.size]);for(const[i,n]of e){const{length:r}=n.getBytesChunks(),o=i|BigInt(r)&0xffn;n.unshift(ty(o)),t.push(n.getBuffer())}return t.getBuffer()}function P0(s){const[e,t]=s;if(e>>4!==1)throw new Error("Trying to deserialize similar int array with invalid serialized item code");let n=2;const r=[];for(let o=0;o<t;o++){const{number:u,byteLength:h}=iy(s.slice(n));n+=h;const p=u&0xffn,d=u&~0xffn;for(let g=0;g<p;g++){const T=BigInt(s[n]);r.push(d|T),n++}}return{numbers:r,byteLength:n}}function D0(s){const{length:e}=s,t=new Dr;return t.push([32|e>>8&15,e&255]),t.push(new TextEncoder().encode(s)),t.getBuffer()}function x0(s){const[e,t]=s;if(e>>4!==2)throw new Error("Trying to deserialize bytes (sting) with invalid serialized item code.");const n=(e&15)<<8|t,r=s.slice(2,n+2);return{string:new TextDecoder("utf8").decode(r),byteLength:n+2}}class Dr{constructor(){se(this,"bytes",[]),se(this,"_length",0)}push(e){this.addBytes(e,"end")}unshift(e){this.addBytes(e,"start")}addBytes(e,t){let i;e instanceof Uint8Array?i=e:Array.isArray(e)?i=new Uint8Array(e):i=new Uint8Array([e]),this._length+=i.length,this.bytes[t==="start"?"unshift":"push"](i)}getBytesChunks(){return this.bytes}getBuffer(){return Zm(this.bytes,this._length)}get length(){return this._length}}const Fi=4,Ks=Fo("cstr",Fi),xr=Fo("cend",Fi),Cc=Fo("dstr",Fi),wc=Fo("dend",Fi),O0=[Ks,Cc],M0=[xr,wc],wp=Ks.length+xr.length;function ny(s){const{length:e}=Ks,t=s.slice(-e);return O0.some(i=>Lo(s,i,Fi))&&M0.some(i=>Lo(t,i,Fi))}function F0(s){return Lo(s,Ks,Fi)}function N0(s){return Lo(s.slice(-4),xr,Fi)}class Ao extends Error{constructor(e){super(),this.type=e}}class sy{constructor(e){se(this,"chunks",new Dr),se(this,"status","joining"),this.onComplete=e}addCommandChunk(e){if(this.status==="completed")return;const t=F0(e);if(!this.chunks.length&&!t)throw new Ao("no-first-chunk");if(this.chunks.length&&t)throw new Ao("incomplete-joining");this.chunks.push(this.unframeCommandChunk(e)),N0(e)&&(this.status="completed",this.onComplete(this.chunks.getBuffer()))}unframeCommandChunk(e){return e.slice(Fi,e.length-Fi)}}class Mo{constructor(e,t){se(this,"bytes",new Dr),se(this,"resultBuffers",[]),se(this,"status","creating"),this.maxChunkLength=t,this.bytes.push(e)}addInteger(e,t){this.bytes.push(e.charCodeAt(0));const i=ty(BigInt(t));this.bytes.push(i)}addSimilarIntArr(e,t){this.bytes.push(e.charCodeAt(0));const i=R0(t.map(n=>BigInt(n)));this.bytes.push(i)}addString(e,t){this.bytes.push(e.charCodeAt(0));const i=D0(t);this.bytes.push(i)}complete(){if(!this.bytes.length)throw new Error("Buffer is empty");if(this.status==="completed")return;this.status="completed";const e=this.bytes.getBuffer();if(e.length+wp<=this.maxChunkLength){this.resultBuffers.push(Ba(e,Ks,xr));return}let t=Math.ceil(e.length/this.maxChunkLength);Math.ceil(e.length/t)+wp>this.maxChunkLength&&t++;for(const[i,n]of U0(e,t))i===0?this.resultBuffers.push(Ba(n,Ks,wc)):i===t-1?this.resultBuffers.push(Ba(n,Cc,xr)):this.resultBuffers.push(Ba(n,Cc,wc))}getResultBuffers(){if(this.status==="creating"||!this.resultBuffers.length)throw new Error("Command is not complete.");return this.resultBuffers}}function ry(s){const[e]=s,t={c:e};let i=1;for(;i<s.length;){const n=String.fromCharCode(s[i]);switch(i++,B0(s[i])){case Ns.Int:{const{number:o,byteLength:u}=iy(s.slice(i));t[n]=Number(o),i+=u}break;case Ns.SimilarIntArray:{const{numbers:o,byteLength:u}=P0(s.slice(i));t[n]=o.map(h=>Number(h)),i+=u}break;case Ns.String:{const{string:o,byteLength:u}=x0(s.slice(i));t[n]=o,i+=u}break}}return t}function B0(s){const e=s>>4;if(e<=Ns.Min||e>=Ns.Max)throw new Error("Not existing type");return e}function Fo(s,e){if(s.length!==e)throw new Error("Wrong string length");const t=new Uint8Array(e);for(let i=0;i<s.length;i++)t[i]=s.charCodeAt(i);return t}function*U0(s,e){const t=Math.ceil(s.length/e);for(let i=0;i<e;i++)yield[i,s.slice(i*t,(i+1)*t)]}function Ba(s,e,t){const i=new Uint8Array(s.length+e.length+t.length);return i.set(e),i.set(s,e.length),i.set(t,e.length+s.length),i}function Lo(s,e,t){for(let i=0;i<t;i++)if(s[i]!==e[i])return!1;return!0}function H0(s,e){const{c:t,p:i,l:n}=s,r=new Mo(t,e);return n?.length&&r.addSimilarIntArr("l",n),i?.length&&r.addSimilarIntArr("p",i),r.complete(),r.getResultBuffers()}function $0(s,e){const t=new Mo(s.c,e);return t.addInteger("i",s.i),t.addInteger("r",s.r),t.complete(),t.getResultBuffers()}function j0(s,e){const t=new Mo(s.c,e);return t.addInteger("i",s.i),t.addInteger("s",s.s),t.addInteger("r",s.r),t.complete(),t.getResultBuffers()}function V0(s,e){const t=new Mo(s.c,e);return t.addInteger("i",s.i),t.addInteger("r",s.r),s.b&&t.addInteger("b",s.b),t.complete(),t.getResultBuffers()}function ay(s,e){switch(s.c){case bn.CancelSegmentRequest:case bn.SegmentAbsent:case bn.SegmentDataSendingCompleted:return $0(s,e);case bn.SegmentRequest:return V0(s,e);case bn.SegmentsAnnouncement:return H0(s,e);case bn.SegmentData:return j0(s,e)}}const G0=Object.freeze(Object.defineProperty({__proto__:null,BinaryCommandChunksJoiner:sy,BinaryCommandJoiningError:Ao,PeerCommandType:bn,deserializeCommand:ry,isCommandChunk:ny,serializePeerCommand:ay},Symbol.toStringTag,{value:"Module"}));class K0{constructor(e,t,i,n){se(this,"commandChunks"),se(this,"uploadingContext"),se(this,"onChunkDownloaded"),se(this,"onChunkUploaded"),se(this,"onDataReceived",r=>{ny(r)?this.receivingCommandBytes(r):(this.eventHandlers.onSegmentChunkReceived(r),this.onChunkDownloaded(r.byteLength,"p2p",this.connection.idUtf8))}),this.connection=e,this.peerConfig=t,this.eventHandlers=i,this.onChunkDownloaded=n.getEventDispatcher("onChunkDownloaded"),this.onChunkUploaded=n.getEventDispatcher("onChunkUploaded"),e.on("data",this.onDataReceived)}sendCommand(e){const t=ay(e,this.peerConfig.webRtcMaxMessageSize);for(const i of t)this.connection.write(i)}stopUploadingSegmentData(){var e;(e=this.uploadingContext)==null||e.stopUploading(),this.uploadingContext=void 0}getUploadingRequestId(){var e;return(e=this.uploadingContext)==null?void 0:e.requestId}async splitSegmentDataToChunksAndUploadAsync(e,t){if(this.uploadingContext)throw new Error("Some segment data is already uploading.");const i=q0(e,this.peerConfig.webRtcMaxMessageSize),{promise:n,resolve:r,reject:o}=b0();let u=!1;const h={stopUploading:()=>{u=!1},requestId:t};this.uploadingContext=h;const p=()=>{if(!u){o();return}for(;;){const d=i.next().value;if(!d){r();break}const g=this.connection.write(d);if(this.onChunkUploaded(d.byteLength,this.connection.idUtf8),!g)break}};try{this.connection.on("drain",p),u=!0,p(),await n}finally{this.connection.off("drain",p),this.uploadingContext===h&&(this.uploadingContext=void 0)}}receivingCommandBytes(e){this.commandChunks||(this.commandChunks=new sy(t=>{this.commandChunks=void 0;const i=ry(t);this.eventHandlers.onCommandReceived(i)}));try{this.commandChunks.addCommandChunk(e)}catch(t){if(!(t instanceof Ao))return;this.commandChunks=void 0}}}function*q0(s,e){let t=s.byteLength;for(;t>0;){const i=t>=e?e:t,n=s.byteLength-t,r=s.slice(n,n+i);t-=i,yield r}}const{PeerCommandType:Zt}=G0;class ko{constructor(e,t,i,n,r){se(this,"id"),se(this,"peerProtocol"),se(this,"downloadingContext"),se(this,"loadedSegments",new Set),se(this,"httpLoadingSegments",new Set),se(this,"downloadingErrors",[]),se(this,"logger",Ni("p2pml-core:peer")),se(this,"onPeerClosed"),se(this,"onCommandReceived",async o=>{var u,h,p;switch(o.c){case Zt.SegmentsAnnouncement:this.loadedSegments=new Set(o.l),this.httpLoadingSegments=new Set(o.p),this.eventHandlers.onSegmentsAnnouncement();break;case Zt.SegmentRequest:this.peerProtocol.stopUploadingSegmentData(),this.eventHandlers.onSegmentRequested(this,o.i,o.r,o.b);break;case Zt.SegmentData:{if(!this.downloadingContext||this.downloadingContext.isSegmentDataCommandReceived)break;const{request:d,controls:g,requestId:T}=this.downloadingContext;if(d.segment.externalId!==o.i||T!==o.r)break;this.downloadingContext.isSegmentDataCommandReceived=!0,g.firstBytesReceived(),d.totalBytes===void 0?d.setTotalBytes(o.s):d.totalBytes-d.loadedBytes!==o.s&&(d.clearLoadedBytes(),this.sendCancelSegmentRequestCommand(d.segment,T),this.cancelSegmentDownloading("peer-response-bytes-length-mismatch"),this.destroy())}break;case Zt.SegmentDataSendingCompleted:{const{downloadingContext:d}=this;if(!d?.isSegmentDataCommandReceived)return;const{request:g,controls:T}=d;if(d.request.segment.externalId!==o.i||d.requestId!==o.r){g.clearLoadedBytes(),this.cancelSegmentDownloading("peer-protocol-violation"),this.destroy();return}if(g.loadedBytes!==g.totalBytes){g.clearLoadedBytes(),this.cancelSegmentDownloading("peer-response-bytes-length-mismatch"),this.destroy();return}const w=await((h=(u=this.peerConfig).validateP2PSegment)==null?void 0:h.call(u,g.segment.url,g.segment.byteRange,g.data))??!0;if(this.downloadingContext!==d)return;if(!w){g.clearLoadedBytes(),this.cancelSegmentDownloading("p2p-segment-validation-failed"),this.destroy();return}this.downloadingErrors=[],T.completeOnSuccess(),this.downloadingContext=void 0;break}case Zt.SegmentAbsent:((p=this.downloadingContext)==null?void 0:p.request.segment.externalId)===o.i&&this.downloadingContext.requestId===o.r&&(this.cancelSegmentDownloading("peer-segment-absent"),this.loadedSegments.delete(o.i));break;case Zt.CancelSegmentRequest:{if(this.peerProtocol.getUploadingRequestId()!==o.r)break;this.peerProtocol.stopUploadingSegmentData();break}}}),se(this,"onSegmentChunkReceived",o=>{var u;if(!((u=this.downloadingContext)!=null&&u.isSegmentDataCommandReceived))return;const{request:h,controls:p}=this.downloadingContext;if(h.totalBytes!==void 0&&h.loadedBytes+o.byteLength>h.totalBytes){h.clearLoadedBytes(),this.cancelSegmentDownloading("peer-response-bytes-length-mismatch"),this.destroy();return}p.addLoadedChunk(o)}),se(this,"onPeerConnectionClosed",()=>{this.destroy()}),se(this,"onConnectionError",o=>{this.logger(`peer connection error ${this.id} %O`,o),this.eventTarget.getEventDispatcher("onPeerError")({peerId:this.id,streamType:this.streamType,error:o});const{code:u}=o;u==="ERR_DATA_CHANNEL"?this.destroy():u==="ERR_CONNECTION_FAILURE"&&this.destroy()}),se(this,"destroy",()=>{this.cancelSegmentDownloading("peer-closed"),this.connection.destroy(),this.eventHandlers.onPeerClosed(this),this.onPeerClosed({peerId:this.id,streamType:this.streamType}),this.logger(`peer closed ${this.id}`)}),this.connection=e,this.eventHandlers=t,this.peerConfig=i,this.streamType=n,this.eventTarget=r,this.onPeerClosed=r.getEventDispatcher("onPeerClose"),this.id=ko.getPeerIdFromConnection(e),this.peerProtocol=new K0(e,i,{onSegmentChunkReceived:this.onSegmentChunkReceived,onCommandReceived:this.onCommandReceived},r),r.getEventDispatcher("onPeerConnect")({peerId:this.id,streamType:n}),e.on("error",this.onConnectionError),e.on("close",this.onPeerConnectionClosed),e.on("end",this.onPeerConnectionClosed),e.on("finish",this.onPeerConnectionClosed)}get downloadingSegment(){var e;return(e=this.downloadingContext)==null?void 0:e.request.segment}getSegmentStatus(e){const{externalId:t}=e;if(this.loadedSegments.has(t))return"loaded";if(this.httpLoadingSegments.has(t))return"http-loading"}downloadSegment(e){if(this.downloadingContext)throw new Error("Some segment already is downloading");this.downloadingContext={request:e,requestId:Math.floor(Math.random()*1e3),isSegmentDataCommandReceived:!1,controls:e.start({downloadSource:"p2p",peerId:this.id},{notReceivingBytesTimeoutMs:this.peerConfig.p2pNotReceivingBytesTimeoutMs,abort:i=>{if(!this.downloadingContext)return;const{request:n,requestId:r}=this.downloadingContext;this.sendCancelSegmentRequestCommand(n.segment,r),this.downloadingErrors.push(i),this.downloadingContext=void 0,this.downloadingErrors.filter(u=>u.type==="bytes-receiving-timeout").length>=this.peerConfig.p2pErrorRetries&&this.destroy()}})};const t={c:Zt.SegmentRequest,r:this.downloadingContext.requestId,i:e.segment.externalId};e.loadedBytes&&(t.b=e.loadedBytes),this.peerProtocol.sendCommand(t)}async uploadSegmentData(e,t,i){const{externalId:n}=e;this.logger(`send segment ${e.externalId} to ${this.id}`);const r={c:Zt.SegmentData,i:n,r:t,s:i.byteLength};this.peerProtocol.sendCommand(r);try{await this.peerProtocol.splitSegmentDataToChunksAndUploadAsync(i,t),this.sendSegmentDataSendingCompletedCommand(e,t),this.logger(`segment ${n} has been sent to ${this.id}`)}catch{this.logger(`cancel segment uploading ${n}`)}}cancelSegmentDownloading(e){if(!this.downloadingContext)return;const{request:t,controls:i}=this.downloadingContext,{segment:n}=t;this.logger(`cancel segment request ${n.externalId} (${e})`);const r=new ei(e);i.abortOnError(r),this.downloadingContext=void 0,this.downloadingErrors.push(r)}sendSegmentsAnnouncementCommand(e,t){const i={c:Zt.SegmentsAnnouncement,p:t,l:e};this.peerProtocol.sendCommand(i)}sendSegmentAbsentCommand(e,t){this.peerProtocol.sendCommand({c:Zt.SegmentAbsent,i:e,r:t})}sendCancelSegmentRequestCommand(e,t){this.peerProtocol.sendCommand({c:Zt.CancelSegmentRequest,i:e.externalId,r:t})}sendSegmentDataSendingCompletedCommand(e,t){this.peerProtocol.sendCommand({c:Zt.SegmentDataSendingCompleted,r:t,i:e.externalId})}static getPeerIdFromConnection(e){return E0(e.id)}}function W0(){const s=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),e=/\b(iPad|iPhone|Macintosh).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent);return s||e}const oy=class io{constructor(e,t,i,n,r){se(this,"streamShortId"),se(this,"client"),se(this,"_peers",new Map),se(this,"logger",Ni("p2pml-core:p2p-tracker-client")),se(this,"onReceivePeerConnection",h=>{const p=ko.getPeerIdFromConnection(h);let d=this._peers.get(p);if(d?.peer){h.destroy();return}d||(d={potentialConnections:new Set},h.idUtf8=p,this._peers.set(p,d)),d.potentialConnections.add(h),h.on("connect",()=>{if(!d.peer){for(const g of d.potentialConnections)g!==h&&g.destroy();d.potentialConnections.clear(),d.peer=new ko(h,{onPeerClosed:this.onPeerClosed,onSegmentRequested:this.eventHandlers.onSegmentRequested,onSegmentsAnnouncement:this.eventHandlers.onSegmentsAnnouncement},this.config,this.stream.type,this.eventTarget),this.logger(`connected with peer: ${d.peer.id} ${this.streamShortId}`),this.eventHandlers.onPeerConnected(d.peer)}})}),se(this,"onTrackerClientWarning",h=>{this.logger("tracker warning %s:",this.streamShortId,h),this.eventTarget.getEventDispatcher("onTrackerWarning")({streamType:this.stream.type,warning:h})}),se(this,"onTrackerClientError",h=>{this.logger("tracker error in stream %s:",this.streamShortId,h),this.eventTarget.getEventDispatcher("onTrackerError")({streamType:this.stream.type,error:h})}),se(this,"onPeerClosed",h=>{this.logger(`peer closed: ${h.id}`),this._peers.delete(h.id)}),this.stream=t,this.eventHandlers=i,this.config=n,this.eventTarget=r;const o=y0(e);this.streamShortId=kn(t);let u=io.PEER_ID_BY_INFO_HASH.get(o);u||(u=v0(n.trackerClientVersionPrefix),io.PEER_ID_BY_INFO_HASH.set(o,u)),this.client=new Sc({infoHash:Sp(o),peerId:Sp(u),announce:W0()?n.announceTrackers.slice(0,1):n.announceTrackers,rtcConfig:this.config.rtcConfig}),this.client.on("peer",this.onReceivePeerConnection),this.client.on("warning",this.onTrackerClientWarning),this.client.on("error",this.onTrackerClientError),this.logger(`create new client; 
stream: ${this.streamShortId}; hash: ${o}
peerId: ${u}`)}start(){this.client.start()}destroy(){this.client.destroy();for(const{peer:e,potentialConnections:t}of this._peers.values()){e?.destroy();for(const i of t)i.destroy()}this._peers.clear(),this.logger("destroy client; stream:",this.streamShortId)}*peers(){for(const e of this._peers.values())e.peer&&(yield e.peer)}static clearPeerIdCache(){io.PEER_ID_BY_INFO_HASH.clear()}};se(oy,"PEER_ID_BY_INFO_HASH",new Map);let ly=oy;const z0="v2";function en(s,e){return`${z0}-${s}-${X0(e)}`}function Ap(s,e){for(const t of s.values()){const i=t.segments.get(e);if(i)return i}}function Y0(s,e){for(const t of s.segments.values())if(t.externalId===e)return t}function X0(s){return`${s.type}-${s.index}`}function Q0(s){const{segments:e}=s;let t=0;const{size:i}=e;for(const n of e.values()){const r=n.endTime-n.startTime;t+=r}return t/i}function J0(s,e){const{highDemandTimeWindow:t,httpDownloadTimeWindow:i,p2pDownloadTimeWindow:n}=s,r={highDemandTimeWindow:t,httpDownloadTimeWindow:i,p2pDownloadTimeWindow:n};return e<=5?(r.httpDownloadTimeWindow=0,r.p2pDownloadTimeWindow=0):e<=10&&(r.p2pDownloadTimeWindow=r.httpDownloadTimeWindow),r}function Hu(s,e,t,i,n){const{highDemandTimeWindow:r,httpDownloadTimeWindow:o,p2pDownloadTimeWindow:u}=J0(t,n);return{isHighDemand:$u(s,e,r),isHttpDownloadable:$u(s,e,o),isP2PDownloadable:$u(s,e,u)&&i.isSegmentLoadingOrLoadedBySomeone(s)}}function $u(s,e,t){const{startTime:i,endTime:n}=s,{position:r,rate:o}=e;return!(r+t*o<i||r>n)}class Z0{constructor(e,t,i,n,r,o,u){se(this,"trackerClient"),se(this,"isAnnounceMicrotaskCreated",!1),se(this,"onPeerConnected",d=>{if(this.config.isP2PUploadDisabled)return;const{httpLoading:g,loaded:T}=this.getSegmentsAnnouncement();d.sendSegmentsAnnouncementCommand(T,g)}),se(this,"broadcastAnnouncement",(d=!1)=>{if(d){this.sendSegmentsAnnouncement([],[]);return}if(this.isAnnounceMicrotaskCreated||this.config.isP2PUploadDisabled)return;const{loaded:g,httpLoading:T}=this.getSegmentsAnnouncement();this.sendSegmentsAnnouncement(g,T)}),se(this,"sendSegmentsAnnouncement",(d,g)=>{this.isAnnounceMicrotaskCreated=!0,queueMicrotask(()=>{for(const T of this.trackerClient.peers())T.sendSegmentsAnnouncementCommand(d,g);this.isAnnounceMicrotaskCreated=!1})}),se(this,"onSegmentRequested",async(d,g,T,b)=>{const E=Y0(this.stream,g);if(!E)return;if(this.config.isP2PUploadDisabled){d.sendSegmentAbsentCommand(g,T);return}const w=this.config.swarmId??this.streamManifestUrl,A=en(w,this.stream),L=await this.segmentStorage.getSegmentData(w,A,E.externalId);if(!L){d.sendSegmentAbsentCommand(g,T);return}await d.uploadSegmentData(E,T,b!==void 0?L.slice(b):L)}),this.streamManifestUrl=e,this.stream=t,this.requests=i,this.segmentStorage=n,this.config=r,this.eventTarget=o,this.onSegmentAnnouncement=u;const h=this.config.swarmId??this.streamManifestUrl,p=en(h,this.stream);this.trackerClient=new ly(p,this.stream,{onPeerConnected:this.onPeerConnected,onSegmentRequested:this.onSegmentRequested,onSegmentsAnnouncement:this.onSegmentAnnouncement},this.config,this.eventTarget),this.eventTarget.addEventListener(`onStorageUpdated-${p}`,this.broadcastAnnouncement),this.segmentStorage.setSegmentChangeCallback(d=>{this.eventTarget.dispatchEvent(`onStorageUpdated-${d}`)}),this.trackerClient.start()}downloadSegment(e){const t=[];for(const r of this.trackerClient.peers())!r.downloadingSegment&&r.getSegmentStatus(e)==="loaded"&&t.push(r);if(t.length===0)return;const i=_0(t),n=this.requests.getOrCreateRequest(e);i.downloadSegment(n)}isSegmentLoadingOrLoadedBySomeone(e){for(const t of this.trackerClient.peers())if(t.getSegmentStatus(e))return!0;return!1}isSegmentLoadedBySomeone(e){for(const t of this.trackerClient.peers())if(t.getSegmentStatus(e)==="loaded")return!0;return!1}get connectedPeerCount(){let e=0;const t=this.trackerClient.peers();for(;!t.next().done;)e++;return e}getSegmentsAnnouncement(){const e=this.config.swarmId??this.streamManifestUrl,t=en(e,this.stream),i=this.segmentStorage.getStoredSegmentIds(e,t),n=[];for(const r of this.requests.httpRequests()){const o=this.stream.segments.get(r.segment.runtimeId);o&&n.push(o.externalId)}return{loaded:i,httpLoading:n}}destroy(){const e=this.config.swarmId??this.streamManifestUrl,t=en(e,this.stream);this.eventTarget.removeEventListener(`onStorageUpdated-${t}`,this.broadcastAnnouncement),this.trackerClient.destroy()}}class eA{constructor(e,t,i,n,r,o,u){se(this,"loaders",new Map),se(this,"_currentLoaderItem"),se(this,"logger",Ni("p2pml-core:p2p-loaders-container")),this.streamManifestUrl=e,this.requests=i,this.segmentStorage=n,this.config=r,this.eventTarget=o,this.onSegmentAnnouncement=u,this._currentLoaderItem=this.findOrCreateLoaderForStream(t),this.logger(`set current p2p loader: ${kn(t)}`)}createLoader(e){if(this.loaders.has(e.runtimeId))throw new Error("Loader for this stream already exists");const t=new Z0(this.streamManifestUrl,e,this.requests,this.segmentStorage,this.config,this.eventTarget,()=>{this._currentLoaderItem.loader===t&&this.onSegmentAnnouncement()}),i=kn(e);return this.logger(`created new loader: ${i}`),{loader:t,stream:e,loggerInfo:kn(e)}}findOrCreateLoaderForStream(e){const t=this.loaders.get(e.runtimeId);if(t)return clearTimeout(t.destroyTimeoutId),t.destroyTimeoutId=void 0,t;{const i=this.createLoader(e);return this.loaders.set(e.runtimeId,i),i}}changeCurrentLoader(e){const t=this.config.swarmId??this.streamManifestUrl,i=en(t,this._currentLoaderItem.stream);this.segmentStorage.getStoredSegmentIds(t,i).length?this.setLoaderDestroyTimeout(this._currentLoaderItem):this.destroyAndRemoveLoader(this._currentLoaderItem),this._currentLoaderItem=this.findOrCreateLoaderForStream(e),this.logger(`change current p2p loader: ${kn(e)}`)}setLoaderDestroyTimeout(e){e.destroyTimeoutId=window.setTimeout(()=>this.destroyAndRemoveLoader(e),this.config.p2pInactiveLoaderDestroyTimeoutMs)}destroyAndRemoveLoader(e){e.loader.destroy(),this.loaders.delete(e.stream.runtimeId),this.logger("destroy p2p loader: ",e.loggerInfo)}get currentLoader(){return this._currentLoaderItem.loader}destroy(){for(const{loader:e,destroyTimeoutId:t}of this.loaders.values())e.destroy(),clearTimeout(t);this.loaders.clear()}}function Ua(s){return{runtimeId:s.runtimeId,externalId:s.externalId,url:s.url,byteRange:s.byteRange,startTime:s.startTime,endTime:s.endTime}}let tA=class{constructor(e,t,i,n,r,o){se(this,"currentAttempt"),se(this,"_failedAttempts",new iA),se(this,"finalData"),se(this,"bytes",[]),se(this,"_loadedBytes",0),se(this,"_totalBytes"),se(this,"_status","not-started"),se(this,"progress"),se(this,"notReceivingBytesTimeout"),se(this,"_abortRequestCallback"),se(this,"_logger"),se(this,"_isHandledByProcessQueue",!1),se(this,"onSegmentError"),se(this,"onSegmentAbort"),se(this,"onSegmentStart"),se(this,"onSegmentLoaded"),se(this,"abortOnTimeout",()=>{var p;if(this.throwErrorIfNotLoadingStatus(),!this.currentAttempt)return;this.setStatus("failed");const d=new ei("bytes-receiving-timeout");(p=this._abortRequestCallback)==null||p.call(this,d),this.logger(`${this.downloadSource} ${this.segment.externalId} failed ${d.type}`),this._failedAttempts.add({...this.currentAttempt,error:d}),this.onSegmentError({segment:Ua(this.segment),error:d,downloadSource:this.currentAttempt.downloadSource,peerId:this.currentAttempt.downloadSource==="p2p"?this.currentAttempt.peerId:void 0,streamType:this.segment.stream.type}),this.notReceivingBytesTimeout.clear(),this.manageBandwidthCalculatorsState("stop"),this.requestProcessQueueCallback()}),se(this,"abortOnError",p=>{this.throwErrorIfNotLoadingStatus(),this.currentAttempt&&(this.setStatus("failed"),this.logger(`${this.downloadSource} ${this.segment.externalId} failed ${p.type}`),this._failedAttempts.add({...this.currentAttempt,error:p}),this.onSegmentError({segment:Ua(this.segment),error:p,downloadSource:this.currentAttempt.downloadSource,peerId:this.currentAttempt.downloadSource==="p2p"?this.currentAttempt.peerId:void 0,streamType:this.segment.stream.type}),this.notReceivingBytesTimeout.clear(),this.manageBandwidthCalculatorsState("stop"),this.requestProcessQueueCallback())}),se(this,"completeOnSuccess",()=>{this.throwErrorIfNotLoadingStatus(),this.currentAttempt&&(this.manageBandwidthCalculatorsState("stop"),this.notReceivingBytesTimeout.clear(),this.setStatus("succeed"),this._totalBytes=this._loadedBytes,this.onSegmentLoaded({segmentUrl:this.segment.url,bytesLength:this.data.byteLength,downloadSource:this.currentAttempt.downloadSource,peerId:this.currentAttempt.downloadSource==="p2p"?this.currentAttempt.peerId:void 0,streamType:this.segment.stream.type}),this.logger(`${this.currentAttempt.downloadSource} ${this.segment.externalId} succeed`),this.requestProcessQueueCallback())}),se(this,"addLoadedChunk",p=>{if(this.throwErrorIfNotLoadingStatus(),!this.currentAttempt||!this.progress)return;this.notReceivingBytesTimeout.restart();const{byteLength:d}=p,{all:g,http:T}=this.bandwidthCalculators;g.addBytes(d),this.currentAttempt.downloadSource==="http"&&T.addBytes(d),this.bytes.push(p),this.progress.lastLoadedChunkTimestamp=performance.now(),this.progress.loadedBytes+=d,this._loadedBytes+=d}),se(this,"firstBytesReceived",()=>{this.throwErrorIfNotLoadingStatus(),this.notReceivingBytesTimeout.restart()}),this.segment=e,this.requestProcessQueueCallback=t,this.bandwidthCalculators=i,this.playback=n,this.playbackConfig=r,this.onSegmentError=o.getEventDispatcher("onSegmentError"),this.onSegmentAbort=o.getEventDispatcher("onSegmentAbort"),this.onSegmentStart=o.getEventDispatcher("onSegmentStart"),this.onSegmentLoaded=o.getEventDispatcher("onSegmentLoaded");const{byteRange:u}=this.segment;if(u){const{end:p,start:d}=u;this._totalBytes=p-d+1}this.notReceivingBytesTimeout=new nA(this.abortOnTimeout);const{type:h}=this.segment.stream;this._logger=Ni(`p2pml-core:request-${h}`)}clearLoadedBytes(){this._loadedBytes=0,this.bytes=[],this._totalBytes=void 0,this.finalData=void 0}get status(){return this._status}setStatus(e){this._status=e,this._isHandledByProcessQueue=!1}get downloadSource(){var e;return(e=this.currentAttempt)==null?void 0:e.downloadSource}get loadedBytes(){return this._loadedBytes}get totalBytes(){return this._totalBytes}get data(){return this.finalData||(this.finalData=Zm(this.bytes)),this.finalData}get failedAttempts(){return this._failedAttempts}get isHandledByProcessQueue(){return this._isHandledByProcessQueue}markHandledByProcessQueue(){this._isHandledByProcessQueue=!0}setTotalBytes(e){if(this._totalBytes!==void 0)throw new Error("Request total bytes value is already set");this._totalBytes=e}start(e,t){if(this._status==="succeed")throw new Error(`Request ${this.segment.externalId} has been already succeed.`);if(this._status==="loading")throw new Error(`Request ${this.segment.externalId} has been already started.`);this.setStatus("loading"),this.currentAttempt={...e},this.progress={startFromByte:this._loadedBytes,loadedBytes:0,startTimestamp:performance.now()},this.manageBandwidthCalculatorsState("start");const{notReceivingBytesTimeoutMs:i,abort:n}=t;return this._abortRequestCallback=n,i!==void 0&&this.notReceivingBytesTimeout.start(i),this.logger(`${e.downloadSource} ${this.segment.externalId} started`),this.onSegmentStart({segment:Ua(this.segment),downloadSource:e.downloadSource,peerId:e.downloadSource==="p2p"?e.peerId:void 0}),{firstBytesReceived:this.firstBytesReceived,addLoadedChunk:this.addLoadedChunk,completeOnSuccess:this.completeOnSuccess,abortOnError:this.abortOnError}}abortFromProcessQueue(){var e,t,i,n;this.throwErrorIfNotLoadingStatus(),this.setStatus("aborted"),this.logger(`${(e=this.currentAttempt)==null?void 0:e.downloadSource} ${this.segment.externalId} aborted`),(t=this._abortRequestCallback)==null||t.call(this,new ei("abort")),this.onSegmentAbort({segment:Ua(this.segment),downloadSource:(i=this.currentAttempt)==null?void 0:i.downloadSource,peerId:((n=this.currentAttempt)==null?void 0:n.downloadSource)==="p2p"?this.currentAttempt.peerId:void 0,streamType:this.segment.stream.type}),this._abortRequestCallback=void 0,this.manageBandwidthCalculatorsState("stop"),this.notReceivingBytesTimeout.clear()}throwErrorIfNotLoadingStatus(){if(this._status!=="loading")throw new Error(`Request has been already ${this.status}.`)}logger(e){var t;this._logger.color=((t=this.currentAttempt)==null?void 0:t.downloadSource)==="http"?"green":"red",this._logger(e),this._logger.color=""}manageBandwidthCalculatorsState(e){var t;const{all:i,http:n}=this.bandwidthCalculators,r=e==="start"?"startLoading":"stopLoading";((t=this.currentAttempt)==null?void 0:t.downloadSource)==="http"&&n[r](),i[r]()}};class iA{constructor(){se(this,"attempts",[])}add(e){this.attempts.push(e)}get httpAttemptsCount(){return this.attempts.reduce((e,t)=>t.downloadSource==="http"?e+1:e,0)}get lastAttempt(){return this.attempts[this.attempts.length-1]}clear(){this.attempts=[]}}class nA{constructor(e){se(this,"timeoutId"),se(this,"ms"),this.action=e}start(e){if(this.timeoutId)throw new Error("Timeout is already started.");this.ms=e,this.timeoutId=window.setTimeout(this.action,this.ms)}restart(e){this.timeoutId&&clearTimeout(this.timeoutId),e&&(this.ms=e),this.ms&&(this.timeoutId=window.setTimeout(this.action,this.ms))}clear(){clearTimeout(this.timeoutId),this.timeoutId=void 0}}class sA{constructor(e,t,i,n,r){se(this,"requests",new Map),this.requestProcessQueueCallback=e,this.bandwidthCalculators=t,this.playback=i,this.config=n,this.eventTarget=r}get executingHttpCount(){let e=0;for(const t of this.httpRequests())t.status==="loading"&&e++;return e}get executingP2PCount(){let e=0;for(const t of this.p2pRequests())t.status==="loading"&&e++;return e}get(e){return this.requests.get(e)}getOrCreateRequest(e){let t=this.requests.get(e);return t||(t=new tA(e,this.requestProcessQueueCallback,this.bandwidthCalculators,this.playback,this.config,this.eventTarget),this.requests.set(e,t)),t}remove(e){this.requests.delete(e.segment)}items(){return this.requests.values()}*httpRequests(){for(const e of this.requests.values())e.downloadSource==="http"&&(yield e)}*p2pRequests(){for(const e of this.requests.values())e.downloadSource==="p2p"&&(yield e)}destroy(){for(const e of this.requests.values())e.status==="loading"&&e.abortFromProcessQueue();this.requests.clear()}}class rA{constructor(e,t){se(this,"_status","pending"),se(this,"_shouldBeStartedImmediately",!1),this.segment=e,this.engineCallbacks=t}get status(){return this._status}get shouldBeStartedImmediately(){return this._shouldBeStartedImmediately}resolve(e,t){this._status==="pending"&&(this._status="succeed",this.engineCallbacks.onSuccess({data:e,bandwidth:t}))}reject(){this._status==="pending"&&(this._status="failed",this.engineCallbacks.onError(new Eo("failed")))}abort(){this._status==="pending"&&(this._status="aborted",this.engineCallbacks.onError(new Eo("aborted")))}markAsShouldBeStartedImmediately(){this._shouldBeStartedImmediately=!0}}function*Lp(s,e,t,i,n){const{runtimeId:r,stream:o}=s,u=o.segments.get(r);if(!u)return;const h=o.segments.values();let p;do{const g=h.next();if(g.done)return;p=g.value}while(p!==u);const d=Hu(p,e,t,i,n);if(ju(d)){const g=h.next();if(g.done)return;const T=g.value,b=Hu(T,e,t,i,n);if(ju(b))return;d.isHighDemand=!0,yield{segment:p,statuses:d},yield{segment:T,statuses:b}}else yield{segment:p,statuses:d};for(const g of h){const T=Hu(g,e,t,i,n);if(ju(T))break;yield{segment:g,statuses:T}}}function ju(s){const{isHighDemand:e=!1,isHttpDownloadable:t=!1,isP2PDownloadable:i=!1}=s;return!e&&!t&&!i}const aA=6e4,kp=1e3;class oA{constructor(e,t,i,n,r,o,u){se(this,"requests"),se(this,"engineRequest"),se(this,"p2pLoaders"),se(this,"playback"),se(this,"segmentAvgDuration"),se(this,"logger"),se(this,"storageCleanUpIntervalId"),se(this,"levelChangedTimestamp"),se(this,"lastQueueProcessingTimeStamp"),se(this,"randomHttpDownloadInterval"),se(this,"isProcessQueueMicrotaskCreated",!1),se(this,"requestProcessQueueMicrotask",(p=!0)=>{const d=performance.now();!p&&this.lastQueueProcessingTimeStamp!==void 0&&d-this.lastQueueProcessingTimeStamp<=1e3||this.isProcessQueueMicrotaskCreated||(this.isProcessQueueMicrotaskCreated=!0,queueMicrotask(()=>{try{this.processQueue(),this.lastQueueProcessingTimeStamp=d}finally{this.isProcessQueueMicrotaskCreated=!1}}))}),this.streamManifestUrl=e,this.lastRequestedSegment=t,this.streamDetails=i,this.config=n,this.bandwidthCalculators=r,this.segmentStorage=o,this.eventTarget=u;const h=this.lastRequestedSegment.stream;this.playback={position:this.lastRequestedSegment.startTime,rate:1},this.segmentAvgDuration=Q0(h),this.requests=new sA(this.requestProcessQueueMicrotask,this.bandwidthCalculators,this.playback,this.config,this.eventTarget),this.p2pLoaders=new eA(this.streamManifestUrl,this.lastRequestedSegment.stream,this.requests,this.segmentStorage,this.config,this.eventTarget,this.requestProcessQueueMicrotask),this.logger=Ni(`p2pml-core:hybrid-loader-${h.type}`),this.logger.color="coral",this.setIntervalLoading()}setIntervalLoading(){const e=this.p2pLoaders.currentLoader.connectedPeerCount,t=Math.random()*kp*e+kp;this.randomHttpDownloadInterval=window.setTimeout(()=>{this.loadRandomThroughHttp(),this.setIntervalLoading()},t)}async loadSegment(e,t){var i;this.logger(`requests: ${Ep(e)}`);const{stream:n}=e;n!==this.lastRequestedSegment.stream&&(this.logger(`stream changed to ${kn(n)}`),this.p2pLoaders.changeCurrentLoader(n)),this.lastRequestedSegment=e;const r=this.config.swarmId??this.streamManifestUrl,o=en(r,n);this.segmentStorage.onSegmentRequested(r,o,e.externalId,e.startTime,e.endTime,n.type,this.streamDetails.isLive);const u=new rA(e,t);try{if(this.segmentStorage.hasSegment(r,o,e.externalId)){const p=await this.segmentStorage.getSegmentData(r,o,e.externalId);if(p){const{queueDownloadRatio:d}=this.generateQueue();u.resolve(p,this.getBandwidth(d));return}}(i=this.engineRequest)==null||i.abort(),this.engineRequest=u}catch{u.reject()}finally{this.requestProcessQueueMicrotask()}}processRequests(e,t){var i;const{stream:n}=this.lastRequestedSegment,{httpErrorRetries:r}=this.config,o=performance.now();for(const u of this.requests.items()){const{downloadSource:h,status:p,segment:d,isHandledByProcessQueue:g}=u,T=((i=this.engineRequest)==null?void 0:i.segment)===d?this.engineRequest:void 0;switch(p){case"loading":!e.has(d.runtimeId)&&!T&&(u.abortFromProcessQueue(),this.requests.remove(u));break;case"succeed":{if(!h)break;h==="http"&&this.p2pLoaders.currentLoader.broadcastAnnouncement(),T&&(T.resolve(u.data,this.getBandwidth(t)),this.engineRequest=void 0),this.requests.remove(u);const E=this.config.swarmId??this.streamManifestUrl,w=en(E,n);this.segmentStorage.storeSegment(E,w,d.externalId,u.data,d.startTime,d.endTime,d.stream.type,this.streamDetails.isLive);break}case"failed":h==="http"&&!g&&this.p2pLoaders.currentLoader.broadcastAnnouncement(),!T&&!n.segments.has(u.segment.runtimeId)&&this.requests.remove(u),u.failedAttempts.httpAttemptsCount>=r&&T&&(this.engineRequest=void 0,T.reject());break;case"not-started":this.requests.remove(u);break;case"aborted":this.requests.remove(u);break}u.markHandledByProcessQueue();const{lastAttempt:b}=u.failedAttempts;b&&o-b.error.timestamp>aA&&u.failedAttempts.clear()}}processQueue(){var e;const{queue:t,queueSegmentIds:i,queueDownloadRatio:n}=this.generateQueue();this.processRequests(i,n);const{simultaneousHttpDownloads:r,simultaneousP2PDownloads:o,httpErrorRetries:u}=this.config;if((e=this.engineRequest)!=null&&e.shouldBeStartedImmediately&&this.engineRequest.status==="pending"&&this.requests.executingHttpCount<r){const{segment:h}=this.engineRequest,p=this.requests.get(h);(!p||p.status==="not-started"||p.status==="failed"&&p.failedAttempts.httpAttemptsCount<this.config.httpErrorRetries)&&this.loadThroughHttp(h)}for(const h of t){const{statuses:p,segment:d}=h,g=this.requests.get(d);if(p.isHighDemand){if(g?.downloadSource==="http"&&g.status==="loading"||g?.downloadSource==="http"&&g.status==="failed"&&g.failedAttempts.httpAttemptsCount>=u)continue;const T=g?.status==="loading"&&g.downloadSource==="p2p";if(this.requests.executingHttpCount<r){T&&g.abortFromProcessQueue(),this.loadThroughHttp(d);continue}if(this.abortLastHttpLoadingInQueueAfterItem(t,d)&&this.requests.executingHttpCount<r){T&&g.abortFromProcessQueue(),this.loadThroughHttp(d);continue}if(T)continue;if(this.requests.executingP2PCount<o){this.loadThroughP2P(d);continue}if(this.abortLastP2PLoadingInQueueAfterItem(t,d)&&this.requests.executingP2PCount<o){this.loadThroughP2P(d);continue}}else if(p.isP2PDownloadable){if(g?.status==="loading")continue;this.requests.executingP2PCount<o?this.loadThroughP2P(d):this.p2pLoaders.currentLoader.isSegmentLoadedBySomeone(d)&&this.abortLastP2PLoadingInQueueAfterItem(t,d)&&this.requests.executingP2PCount<o&&this.loadThroughP2P(d)}}}abortSegmentRequest(e){var t;((t=this.engineRequest)==null?void 0:t.segment.runtimeId)===e&&(this.engineRequest.abort(),this.logger("abort: ",Ep(this.engineRequest.segment)),this.engineRequest=void 0,this.requestProcessQueueMicrotask())}loadThroughHttp(e){const t=this.requests.getOrCreateRequest(e);new bw(t,this.config,this.eventTarget),this.p2pLoaders.currentLoader.broadcastAnnouncement()}loadThroughP2P(e){this.p2pLoaders.currentLoader.downloadSegment(e)}loadRandomThroughHttp(){const e=this.getAvailableStorageCapacityPercent();if(e<=10)return;const{simultaneousHttpDownloads:t,httpErrorRetries:i}=this.config,n=this.p2pLoaders.currentLoader;if(this.requests.executingHttpCount>=t||!n.connectedPeerCount)return;const r=[];for(const{segment:g,statuses:T}of Lp(this.lastRequestedSegment,this.playback,this.config,this.p2pLoaders.currentLoader,e)){const b=this.config.swarmId??this.streamManifestUrl,E=en(b,g.stream);if(!T.isHttpDownloadable||T.isP2PDownloadable||this.segmentStorage.hasSegment(b,E,g.externalId))continue;const w=this.requests.get(g);w&&(w.status==="loading"||w.status==="succeed"||w.failedAttempts.httpAttemptsCount>=i)||r.push(g)}if(!r.length||t-this.requests.executingHttpCount===0)return;const u=n.connectedPeerCount+1,h=Math.min(r.length,t*u),p=w0(Array.from({length:h},(g,T)=>T));let d=h/u;for(const g of p){if(this.requests.executingHttpCount>=t)break;if(d>=1||Math.random()<=d){const T=r[g];this.loadThroughHttp(T)}if(d--,d<=0)break}}abortLastHttpLoadingInQueueAfterItem(e,t){for(const{segment:i}of Cp(e)){if(i===t)break;const n=this.requests.get(i);if(n?.downloadSource==="http"&&n.status==="loading")return n.abortFromProcessQueue(),!0}return!1}abortLastP2PLoadingInQueueAfterItem(e,t){for(const{segment:i}of Cp(e)){if(i===t)break;const n=this.requests.get(i);if(n?.downloadSource==="p2p"&&n.status==="loading")return n.abortFromProcessQueue(),!0}return!1}getAvailableStorageCapacityPercent(){const{totalCapacity:e,usedCapacity:t}=this.segmentStorage.getUsage();return 100-t/e*100}generateQueue(){var e;const t=[],i=new Set;let n=0,r=0;const o=this.getAvailableStorageCapacityPercent();for(const u of Lp(this.lastRequestedSegment,this.playback,this.config,this.p2pLoaders.currentLoader,o)){n++;const{segment:h}=u,p=this.config.swarmId??this.streamManifestUrl,d=en(p,h.stream);if(this.segmentStorage.hasSegment(p,d,h.externalId)||((e=this.requests.get(h))==null?void 0:e.status)==="succeed"){r++;continue}t.push(u),i.add(h.runtimeId)}return{queue:t,queueSegmentIds:i,maxPossibleLength:n,alreadyLoadedCount:r,queueDownloadRatio:n!==0?r/n:0}}getBandwidth(e){const{http:t,all:i}=this.bandwidthCalculators,{activeLevelBitrate:n}=this.streamDetails;if(this.streamDetails.activeLevelBitrate===0)return i.getBandwidthLoadingOnly(3);const r=Math.max(i.getBandwidth(30,this.levelChangedTimestamp),i.getBandwidth(60,this.levelChangedTimestamp),i.getBandwidth(90,this.levelChangedTimestamp));if(e>=.8||r>=n*.9)return Math.max(i.getBandwidthLoadingOnly(1),i.getBandwidthLoadingOnly(3),i.getBandwidthLoadingOnly(5));const o=Math.max(t.getBandwidthLoadingOnly(1),t.getBandwidthLoadingOnly(3),t.getBandwidthLoadingOnly(5));return Math.max(r,o)}notifyLevelChanged(){this.levelChangedTimestamp=performance.now()}sendBroadcastAnnouncement(e=!1){this.p2pLoaders.currentLoader.broadcastAnnouncement(e)}updatePlayback(e,t){var i;const n=this.playback.rate!==t,r=this.playback.position!==e;if(!n&&!r)return;const o=Math.abs(e-this.playback.position)/this.segmentAvgDuration>.5;r&&(this.playback.position=e),n&&t!==0&&(this.playback.rate=t),o&&(this.logger("position significantly changed"),(i=this.engineRequest)==null||i.markAsShouldBeStartedImmediately()),this.segmentStorage.onPlaybackUpdated(e,t),this.requestProcessQueueMicrotask(o)}updateStream(e){e===this.lastRequestedSegment.stream&&(this.logger(`update stream: ${kn(e)}`),this.requestProcessQueueMicrotask())}destroy(){var e;clearInterval(this.storageCleanUpIntervalId),clearInterval(this.randomHttpDownloadInterval),this.storageCleanUpIntervalId=void 0,(e=this.engineRequest)==null||e.abort(),this.requests.destroy(),this.p2pLoaders.destroy()}}class Ip{constructor(e=2e4){se(this,"loadingsCount",0),se(this,"bytes",[]),se(this,"loadingOnlyTimestamps",[]),se(this,"timestamps",[]),se(this,"noLoadingsTime",0),se(this,"loadingsStoppedAt",0),this.clearThresholdMs=e}addBytes(e,t=performance.now()){this.bytes.push(e),this.loadingOnlyTimestamps.push(t-this.noLoadingsTime),this.timestamps.push(t)}startLoading(e=performance.now()){this.clearStale(),this.loadingsCount===0&&this.loadingsStoppedAt!==0&&(this.noLoadingsTime+=e-this.loadingsStoppedAt),this.loadingsCount++}stopLoading(e=performance.now()){this.loadingsCount>0&&(this.loadingsCount--,this.loadingsCount===0&&(this.loadingsStoppedAt=e))}getBandwidthLoadingOnly(e,t=Number.NEGATIVE_INFINITY){if(!this.loadingOnlyTimestamps.length)return 0;const i=e*1e3,n=this.loadingOnlyTimestamps[this.loadingOnlyTimestamps.length-1];let r=n;const o=n-i;let u=0;for(let h=this.bytes.length-1;h>=0;h--){const p=this.loadingOnlyTimestamps[h];if(p<o||this.timestamps[h]<t)break;r=p,u+=this.bytes[h]}return u*8e3/(n-r)}getBandwidth(e,t=Number.NEGATIVE_INFINITY,i=performance.now()){if(!this.timestamps.length)return 0;const n=e*1e3,r=i-n;let o=i,u=0;for(let h=this.bytes.length-1;h>=0;h--){const p=this.timestamps[h];if(p<r||p<t)break;o=p,u+=this.bytes[h]}return u*8e3/(i-o)}clearStale(){if(!this.loadingOnlyTimestamps.length)return;const e=this.loadingOnlyTimestamps[this.loadingOnlyTimestamps.length-1]-this.clearThresholdMs;let t=0;for(const i of this.loadingOnlyTimestamps){if(i>e)break;t++}this.bytes.splice(0,t),this.loadingOnlyTimestamps.splice(0,t),this.timestamps.splice(0,t)}}const Ha=(s,e)=>`${s}|${e}`,lA=s=>/Android/i.test(s),uA=s=>/iPad|iPhone/i.test(s),cA=s=>/Android/i.test(s)&&!/Chrome|Firefox/i.test(s),$a=1048576;class hA{constructor(){se(this,"userAgent",navigator.userAgent),se(this,"segmentMemoryStorageLimit",4*1024),se(this,"currentStorageUsage",0),se(this,"cache",new Map),se(this,"logger"),se(this,"coreConfig"),se(this,"mainStreamConfig"),se(this,"secondaryStreamConfig"),se(this,"currentPlayback"),se(this,"lastRequestedSegment"),se(this,"segmentChangeCallback"),this.logger=Ni("p2pml-core:segment-memory-storage"),this.logger.color="RebeccaPurple"}async initialize(e,t,i){this.coreConfig=e,this.mainStreamConfig=t,this.secondaryStreamConfig=i,this.setMemoryStorageLimit(),this.logger("initialized")}onPlaybackUpdated(e,t){this.currentPlayback={position:e,rate:t}}onSegmentRequested(e,t,i,n,r,o,u){this.lastRequestedSegment={streamId:t,segmentId:i,startTime:n,endTime:r,swarmId:e,streamType:o,isLiveStream:u}}async storeSegment(e,t,i,n,r,o,u,h){this.clear(h,n.byteLength);const p=Ha(t,i);if(this.cache.set(p,{data:n,segmentId:i,streamId:t,startTime:r,endTime:o,streamType:u}),this.increaseStorageUsage(n.byteLength),this.logger(`add segment: ${i} to ${t}`),!this.segmentChangeCallback)throw new Error("dispatchStorageUpdatedEvent is not set");this.segmentChangeCallback(t)}async getSegmentData(e,t,i){const n=Ha(t,i),r=this.cache.get(n);if(r!==void 0)return r.data}getUsage(){if(!this.lastRequestedSegment||!this.currentPlayback)return{totalCapacity:this.segmentMemoryStorageLimit,usedCapacity:this.currentStorageUsage};const e=this.currentPlayback.position;let t=0;for(const{endTime:i,data:n}of this.cache.values())e>i||(t+=n.byteLength);return{totalCapacity:this.segmentMemoryStorageLimit,usedCapacity:t/$a}}hasSegment(e,t,i){const n=Ha(t,i);return this.cache.get(n)!==void 0}getStoredSegmentIds(e,t){const i=[];for(const{segmentId:n,streamId:r}of this.cache.values())r===t&&i.push(n);return i}clear(e,t){if(!this.currentPlayback||!this.mainStreamConfig||!this.secondaryStreamConfig||!this.coreConfig||!this.isMemoryLimitReached(t)&&!e)return;const n=new Set,r=Array.from(this.cache.values()).sort((o,u)=>o.startTime-u.startTime);for(const o of r){const{streamId:u,segmentId:h,data:p}=o,d=Ha(u,h);if(this.shouldRemoveSegment(o,e,this.currentPlayback.position)&&(this.cache.delete(d),n.add(u),this.decreaseStorageUsage(p.byteLength),this.logger(`Removed segment ${h} from stream ${u}`),!this.isMemoryLimitReached(t)&&!e))break}this.sendUpdatesToAffectedStreams(n)}isMemoryLimitReached(e){return this.currentStorageUsage+e/$a>this.segmentMemoryStorageLimit}setSegmentChangeCallback(e){this.segmentChangeCallback=e}sendUpdatesToAffectedStreams(e){e.size!==0&&e.forEach(t=>{if(!this.segmentChangeCallback)throw new Error("dispatchStorageUpdatedEvent is not set");this.segmentChangeCallback(t)})}shouldRemoveSegment(e,t,i){const{endTime:n,streamType:r}=e,o=this.getStreamTimeWindow(r,"highDemandTimeWindow");return i<=n?!1:t?i>o+n:!0}increaseStorageUsage(e){this.currentStorageUsage+=e/$a}decreaseStorageUsage(e){this.currentStorageUsage-=e/$a}setMemoryStorageLimit(){var e;if((e=this.coreConfig)!=null&&e.segmentMemoryStorageLimit){this.segmentMemoryStorageLimit=this.coreConfig.segmentMemoryStorageLimit;return}cA(this.userAgent)||uA(this.userAgent)?this.segmentMemoryStorageLimit=1024:lA(this.userAgent)&&(this.segmentMemoryStorageLimit=2*1024)}getStreamTimeWindow(e,t){const i=e==="main"?this.mainStreamConfig:this.secondaryStreamConfig;return i?.[t]??0}destroy(){this.cache.clear()}}class dA{constructor(){se(this,"events",new Map)}dispatchEvent(e,...t){const i=this.events.get(e);if(i)for(const n of i)n(...t)}getEventDispatcher(e){let t=this.events.get(e);t||(t=[],this.events.set(e,t));const i=t;return(...n)=>{for(const r of i)r(...n)}}addEventListener(e,t){const i=this.events.get(e);i?i.push(t):this.events.set(e,[t])}removeEventListener(e,t){const i=this.events.get(e);if(i){const n=i.indexOf(t);n!==-1&&i.splice(n,1)}}}const nh=class no{constructor(e){se(this,"eventTarget",new dA),se(this,"manifestResponseUrl"),se(this,"streams",new Map),se(this,"mainStreamConfig"),se(this,"secondaryStreamConfig"),se(this,"commonCoreConfig"),se(this,"bandwidthCalculators",{all:new Ip,http:new Ip}),se(this,"segmentStorage"),se(this,"mainStreamLoader"),se(this,"secondaryStreamLoader"),se(this,"streamDetails",{isLive:!1,activeLevelBitrate:0});const t=C0(e??{});this.commonCoreConfig=Uu({defaultConfig:no.DEFAULT_COMMON_CORE_CONFIG,baseConfig:t}),this.mainStreamConfig=Uu({defaultConfig:no.DEFAULT_STREAM_CONFIG,baseConfig:t,specificStreamConfig:t.mainStream}),this.secondaryStreamConfig=Uu({defaultConfig:no.DEFAULT_STREAM_CONFIG,baseConfig:t,specificStreamConfig:t.secondaryStream})}getConfig(){return{...Cn(this.commonCoreConfig),mainStream:Cn(this.mainStreamConfig),secondaryStream:Cn(this.secondaryStreamConfig)}}applyDynamicConfig(e){const{mainStream:t,secondaryStream:i}=e,n=Cn(this.mainStreamConfig),r=Cn(this.secondaryStreamConfig);this.overrideAllConfigs(e,t,i),this.processSpecificDynamicConfigParams(n,e,"main"),this.processSpecificDynamicConfigParams(r,e,"secondary")}processSpecificDynamicConfigParams(e,t,i){const n=this.getUpdatedStreamProperty("isP2PDisabled",t,i);n&&e.isP2PDisabled!==n&&this.destroyStreamLoader(i);const r=this.getUpdatedStreamProperty("isP2PUploadDisabled",t,i);if(r!==void 0&&e.isP2PUploadDisabled!==r){const o=i==="main"?this.mainStreamLoader:this.secondaryStreamLoader;o?.sendBroadcastAnnouncement(r)}}getUpdatedStreamProperty(e,t,i){const n=i==="main"?t.mainStream:t.secondaryStream;return n?.[e]??t[e]}addEventListener(e,t){this.eventTarget.addEventListener(e,t)}removeEventListener(e,t){this.eventTarget.removeEventListener(e,t)}setManifestResponseUrl(e){this.manifestResponseUrl=e.split("?")[0]}hasSegment(e){return!!Ap(this.streams,e)}getStream(e){return this.streams.get(e)}addStreamIfNoneExists(e){this.streams.has(e.runtimeId)||this.streams.set(e.runtimeId,{...e,segments:new Map})}updateStream(e,t,i){var n,r;const o=this.streams.get(e);if(o){if(t)for(const u of t)o.segments.has(u.runtimeId)||o.segments.set(u.runtimeId,{...u,stream:o});if(i)for(const u of i)o.segments.delete(u);(n=this.mainStreamLoader)==null||n.updateStream(o),(r=this.secondaryStreamLoader)==null||r.updateStream(o)}}async loadSegment(e,t){if(!this.manifestResponseUrl)throw new Error("Manifest response url is not defined");await this.initializeSegmentStorage();const i=this.identifySegment(e);this.getStreamHybridLoader(i).loadSegment(i,t)}abortSegmentLoading(e){var t,i;(t=this.mainStreamLoader)==null||t.abortSegmentRequest(e),(i=this.secondaryStreamLoader)==null||i.abortSegmentRequest(e)}updatePlayback(e,t){var i,n;(i=this.mainStreamLoader)==null||i.updatePlayback(e,t),(n=this.secondaryStreamLoader)==null||n.updatePlayback(e,t)}setActiveLevelBitrate(e){var t,i;e!==this.streamDetails.activeLevelBitrate&&(this.streamDetails.activeLevelBitrate=e,(t=this.mainStreamLoader)==null||t.notifyLevelChanged(),(i=this.secondaryStreamLoader)==null||i.notifyLevelChanged())}setIsLive(e){this.streamDetails.isLive=e}isSegmentLoadable(e){try{const t=this.identifySegment(e);return!(t.stream.type==="main"&&this.mainStreamConfig.isP2PDisabled||t.stream.type==="secondary"&&this.secondaryStreamConfig.isP2PDisabled)}catch{return!1}}destroy(){var e,t,i;this.streams.clear(),(e=this.mainStreamLoader)==null||e.destroy(),(t=this.secondaryStreamLoader)==null||t.destroy(),(i=this.segmentStorage)==null||i.destroy(),this.mainStreamLoader=void 0,this.secondaryStreamLoader=void 0,this.segmentStorage=void 0,this.manifestResponseUrl=void 0,this.streamDetails={isLive:!1,activeLevelBitrate:0},ly.clearPeerIdCache()}async initializeSegmentStorage(){if(this.segmentStorage)return;const{isLive:e}=this.streamDetails,t=this.commonCoreConfig.customSegmentStorageFactory;if(t&&typeof t!="function")throw new Error("Storage configuration is invalid");const i=t?t(e):new hA;await i.initialize(this.commonCoreConfig,this.mainStreamConfig,this.secondaryStreamConfig),this.segmentStorage=i}identifySegment(e){if(!this.manifestResponseUrl)throw new Error("Manifest response url is undefined");const t=Ap(this.streams,e);if(!t)throw new Error(`Not found segment with id: ${e}`);return t}overrideAllConfigs(e,t,i){yr(this.commonCoreConfig,e),yr(this.mainStreamConfig,e),yr(this.secondaryStreamConfig,e),t&&yr(this.mainStreamConfig,t),i&&yr(this.secondaryStreamConfig,i)}destroyStreamLoader(e){var t,i;e==="main"?((t=this.mainStreamLoader)==null||t.destroy(),this.mainStreamLoader=void 0):((i=this.secondaryStreamLoader)==null||i.destroy(),this.secondaryStreamLoader=void 0)}getStreamHybridLoader(e){return e.stream.type==="main"?(this.mainStreamLoader??(this.mainStreamLoader=this.createNewHybridLoader(e)),this.mainStreamLoader):(this.secondaryStreamLoader??(this.secondaryStreamLoader=this.createNewHybridLoader(e)),this.secondaryStreamLoader)}createNewHybridLoader(e){if(!this.manifestResponseUrl)throw new Error("Manifest response url is not defined");if(!this.segmentStorage)throw new Error("Segment storage is not initialized");const t=e.stream.type==="main"?this.mainStreamConfig:this.secondaryStreamConfig;return new oA(this.manifestResponseUrl,e,this.streamDetails,t,this.bandwidthCalculators,this.segmentStorage,this.eventTarget)}};se(nh,"DEFAULT_COMMON_CORE_CONFIG",{segmentMemoryStorageLimit:void 0,customSegmentStorageFactory:void 0});se(nh,"DEFAULT_STREAM_CONFIG",{isP2PUploadDisabled:!1,isP2PDisabled:!1,simultaneousHttpDownloads:2,simultaneousP2PDownloads:3,highDemandTimeWindow:15,httpDownloadTimeWindow:3e3,p2pDownloadTimeWindow:6e3,webRtcMaxMessageSize:64*1024-1,p2pNotReceivingBytesTimeoutMs:2e3,p2pInactiveLoaderDestroyTimeoutMs:30*1e3,httpNotReceivingBytesTimeoutMs:3e3,httpErrorRetries:3,p2pErrorRetries:3,trackerClientVersionPrefix:g0,announceTrackers:["wss://tracker.novage.com.ua","wss://tracker.webtorrent.dev","wss://tracker.openwebtorrent.com"],rtcConfig:{iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:global.stun.twilio.com:3478"}]},validateP2PSegment:void 0,validateHTTPSegment:void 0,httpRequestSetup:void 0,swarmId:void 0});let fA=nh;const pA=Km.debug;var Kn=function(s,e,t,i,n){if(typeof e=="function"?s!==e||!0:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(s,t),t},rt=function(s,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!i:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(s):i?i.value:e.get(s)},Sr,Ps,so,qi,Yn,_n,wn,uy,Ac;const gA=10;class mA{constructor(e,t){Sr.add(this),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stats",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Ps.set(this,void 0),so.set(this,void 0),qi.set(this,void 0),Yn.set(this,void 0),_n.set(this,void 0),wn.set(this,void 0),Kn(this,Yn,t),Kn(this,so,()=>new e.loader(e)),this.stats={aborted:!1,chunkCount:0,loading:{start:0,first:0,end:0},buffering:{start:0,first:0,end:0},parsing:{start:0,end:0},total:1,loaded:1,bwEstimate:0,retry:0}}load(e,t,i){this.context=e,this.config=t,Kn(this,Ps,i);const{stats:n}=this,{rangeStart:r,rangeEnd:o}=e,u=Hm(r,o!==void 0?o-1:void 0);Kn(this,wn,Um(e.url,u));const h=rt(this,Yn,"f").isSegmentLoadable(rt(this,wn,"f"));if(!rt(this,Yn,"f").hasSegment(rt(this,wn,"f"))||!h){Kn(this,qi,rt(this,so,"f").call(this)),rt(this,qi,"f").stats=this.stats,rt(this,qi,"f").load(e,t,i);return}const p=g=>{Kn(this,_n,g);const T=rt(this,_n,"f").data.byteLength;n.loading=yA(rt(this,_n,"f").bandwidth,T,performance.now()),n.total=T,n.loaded=T,i.onProgress&&i.onProgress(this.stats,e,rt(this,_n,"f").data,void 0),i.onSuccess({data:rt(this,_n,"f").data,url:e.url},this.stats,e,void 0)},d=g=>{g instanceof Eo&&g.type==="aborted"&&this.stats.aborted||rt(this,Sr,"m",uy).call(this,g)};rt(this,Yn,"f").loadSegment(rt(this,wn,"f"),{onSuccess:p,onError:d})}abort(){var e,t;rt(this,qi,"f")?rt(this,qi,"f").abort():(rt(this,Sr,"m",Ac).call(this),(t=(e=rt(this,Ps,"f"))==null?void 0:e.onAbort)==null||t.call(e,this.stats,this.context,{}))}destroy(){rt(this,qi,"f")?rt(this,qi,"f").destroy():(this.stats.aborted||rt(this,Sr,"m",Ac).call(this),Kn(this,Ps,null),this.config=null)}}Ps=new WeakMap,so=new WeakMap,qi=new WeakMap,Yn=new WeakMap,_n=new WeakMap,wn=new WeakMap,Sr=new WeakSet,uy=function(e){var t;const i={code:0,text:""};(e instanceof Eo&&e.type==="failed"||e instanceof Error)&&(i.text=e.message),(t=rt(this,Ps,"f"))==null||t.onError(i,this.context,null,this.stats)},Ac=function(){!rt(this,_n,"f")&&rt(this,wn,"f")&&(this.stats.aborted=!0,rt(this,Yn,"f").abortSegmentLoading(rt(this,wn,"f")))};function yA(s,e,t){const i=e*8e3/s,n=t-i;return{start:n-gA,first:n,end:t}}var vA=function(s,e,t,i,n){if(typeof e=="function"?s!==e||!0:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(s,t),t},vr=function(s,e,t,i){if(typeof e=="function"?s!==e||!0:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(s):i?i.value:e.get(s)},vn;class TA{constructor(e){vn.set(this,void 0),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stats",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),vA(this,vn,new e.loader(e)),this.stats=vr(this,vn,"f").stats,this.context=vr(this,vn,"f").context}load(e,t,i){vr(this,vn,"f").load(e,t,i)}abort(){vr(this,vn,"f").abort()}destroy(){vr(this,vn,"f").destroy()}}vn=new WeakMap;class bA{constructor(e){Object.defineProperty(this,"core",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.core=e}processMainManifest(e){const{levels:t,audioTracks:i}=e;for(const[n,r]of t.entries()){const{url:o}=r;this.core.addStreamIfNoneExists({runtimeId:Array.isArray(o)?o[0]:o,type:"main",index:n})}for(const[n,r]of i.entries()){const{url:o}=r;this.core.addStreamIfNoneExists({runtimeId:Array.isArray(o)?o[0]:o,type:"secondary",index:n})}}updatePlaylist(e){const{details:{url:t,fragments:i,live:n}}=e,r=this.core.getStream(t);if(!r)return;const o=new Set(r.segments.keys()),u=[];i.forEach((h,p)=>{const{url:d,byteRange:g,sn:T,start:b,end:E}=h;if(T==="initSegment")return;const[w,A]=g,L=Hm(w,A!==void 0?A-1:void 0),P=Um(d,L);o.delete(P),!r.segments.has(P)&&u.push({runtimeId:P,url:d,externalId:n?T:p,byteRange:L,startTime:b,endTime:E})}),!(!u.length&&!o.size)&&this.core.updateStream(t,u,o.values())}}var _A=function(s,e,t,i){if(typeof e=="function"?s!==e||!0:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(s):i?i.value:e.get(s)},EA=function(s,e,t,i,n){if(typeof e=="function"?s!==e||!0:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(s,t),t};function SA(s){var e,t;return t=class extends s{get p2pEngine(){return _A(this,e,"f")}constructor(...n){var r;const o=n[0],{p2p:u,...h}=o??{},p=new cy(u);super({...h,...p.getConfigForHlsJs()}),e.set(this,void 0),p.bindHls(this),EA(this,e,p),(r=u?.onHlsJsCreated)==null||r.call(u,this)}},e=new WeakMap,t}const CA=120;class cy{static injectMixin(e){return SA(e)}constructor(e){Object.defineProperty(this,"core",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"segmentManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hlsInstanceGetter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"currentHlsInstance",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:pA("p2pml-hlsjs:engine")}),Object.defineProperty(this,"updateMediaElementEventHandlers",{enumerable:!0,configurable:!0,writable:!0,value:t=>{var i;const n=(i=this.currentHlsInstance)==null?void 0:i.media;if(!n)return;const r=t==="register"?"addEventListener":"removeEventListener";n[r]("timeupdate",this.handlePlaybackUpdate),n[r]("seeking",this.handlePlaybackUpdate),n[r]("ratechange",this.handlePlaybackUpdate)}}),Object.defineProperty(this,"handleManifestLoaded",{enumerable:!0,configurable:!0,writable:!0,value:(t,i)=>{const n=i.networkDetails;n instanceof XMLHttpRequest?this.core.setManifestResponseUrl(n.responseURL):n instanceof Response&&this.core.setManifestResponseUrl(n.url),this.segmentManager.processMainManifest(i)}}),Object.defineProperty(this,"handleLevelSwitching",{enumerable:!0,configurable:!0,writable:!0,value:(t,i)=>{i.bitrate&&this.core.setActiveLevelBitrate(i.bitrate)}}),Object.defineProperty(this,"handleLevelUpdated",{enumerable:!0,configurable:!0,writable:!0,value:(t,i)=>{this.currentHlsInstance&&i.details.live&&i.details.fragments[0].type==="main"&&!this.currentHlsInstance.userConfig.liveSyncDuration&&!this.currentHlsInstance.userConfig.liveSyncDurationCount&&i.details.fragments.length>4&&this.updateLiveSyncDurationCount(i),this.core.setIsLive(i.details.live),this.segmentManager.updatePlaylist(i)}}),Object.defineProperty(this,"handleMediaAttached",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.updateMediaElementEventHandlers("register")}}),Object.defineProperty(this,"handleMediaDetached",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.updateMediaElementEventHandlers("unregister")}}),Object.defineProperty(this,"handlePlaybackUpdate",{enumerable:!0,configurable:!0,writable:!0,value:t=>{const i=t.target;this.core.updatePlayback(i.currentTime,i.playbackRate)}}),Object.defineProperty(this,"destroyCore",{enumerable:!0,configurable:!0,writable:!0,value:()=>this.core.destroy()}),Object.defineProperty(this,"destroy",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.destroyCore(),this.updateHlsEventsHandlers("unregister"),this.updateMediaElementEventHandlers("unregister"),this.currentHlsInstance=void 0}}),this.core=new fA(e?.core),this.segmentManager=new bA(this.core)}addEventListener(e,t){this.core.addEventListener(e,t)}removeEventListener(e,t){this.core.removeEventListener(e,t)}getConfigForHlsJs(){return{fLoader:this.createFragmentLoaderClass(),pLoader:this.createPlaylistLoaderClass()}}getConfig(){return{core:this.core.getConfig()}}applyDynamicConfig(e){e.core&&this.core.applyDynamicConfig(e.core)}bindHls(e){this.hlsInstanceGetter=typeof e=="function"?e:()=>e}initHlsEvents(){var e;const t=(e=this.hlsInstanceGetter)==null?void 0:e.call(this);this.currentHlsInstance!==t&&(this.currentHlsInstance&&this.destroy(),this.currentHlsInstance=t,this.updateHlsEventsHandlers("register"),this.updateMediaElementEventHandlers("register"))}updateHlsEventsHandlers(e){const t=this.currentHlsInstance;if(!t)return;const i=e==="register"?"on":"off";t[i]("hlsManifestLoaded",this.handleManifestLoaded),t[i]("hlsLevelSwitching",this.handleLevelSwitching),t[i]("hlsLevelUpdated",this.handleLevelUpdated),t[i]("hlsAudioTrackLoaded",this.handleLevelUpdated),t[i]("hlsDestroying",this.destroy),t[i]("hlsMediaAttaching",this.destroyCore),t[i]("hlsManifestLoading",this.destroyCore),t[i]("hlsMediaDetached",this.handleMediaDetached),t[i]("hlsMediaAttached",this.handleMediaAttached)}updateLiveSyncDurationCount(e){const t=e.details.targetduration,i=Math.floor(CA/t),n=Math.min(e.details.fragments.length-1,i);this.currentHlsInstance&&this.currentHlsInstance.config.liveSyncDurationCount!==n&&(this.debug(`Setting liveSyncDurationCount to ${n}`),this.currentHlsInstance.config.liveSyncDurationCount=n)}createFragmentLoaderClass(){const{core:e}=this,t=this;return class extends mA{constructor(n){super(n,e)}static getEngine(){return t}}}createPlaylistLoaderClass(){const e=this;return class extends TA{constructor(i){super(i),e.initHlsEvents()}}}}const Rp=cy.injectMixin(et);let Pp=!1;const wA=function(s){if(!et.isSupported()){Ve.info("Hls.js is not supported in this browser.");return}const e=s.getTech("Html5");if(!e){Ve.error('No "Html5" tech found in videojs');return}Pp||(Pp=!0,e.registerSourceHandler({canHandleSource:function(t){const i=/^application\/x-mpegURL|application\/vnd\.apple\.mpegurl$/i,n=/\.m3u8/i;return i.test(t.type)?"probably":n.test(t.src)?"maybe":""},handleSource:function(t,i){return i.hlsProvider&&i.hlsProvider.dispose(),i.hlsProvider=new Dp(s,t,i),i.hlsProvider}},0),s.Html5Hlsjs=Dp)},AA=X.getPlugin("plugin");class LA extends AA{constructor(e,t){super(e,t),t&&(e.srOptions_||(e.srOptions_={}),e.srOptions_.hlsjsConfig||(e.srOptions_.hlsjsConfig=t.hlsjsConfig),t.levelLabelHandler&&!e.srOptions_.levelLabelHandler&&(e.srOptions_.levelLabelHandler=t.levelLabelHandler),wA(X))}dispose(){this.player.srOptions_=void 0;const e=this.player.tech(!0);e.hlsProvider&&(e.hlsProvider.dispose(),e.hlsProvider=void 0),super.dispose()}}X.registerPlugin("hlsjs",LA);class Dp{constructor(e,t,i){Ke(this,"videoElement"),Ke(this,"errorCounts",{}),Ke(this,"player"),Ke(this,"tech"),Ke(this,"source"),Ke(this,"vjs"),Ke(this,"maxNetworkErrorRecovery",5),Ke(this,"hls"),Ke(this,"hlsjsConfig",null),Ke(this,"_duration",null),Ke(this,"metadata",null),Ke(this,"isLive",null),Ke(this,"dvrDuration",null),Ke(this,"edgeMargin",null),Ke(this,"liveEnded",!1),Ke(this,"handlers",{play:null,error:null}),Ke(this,"audioMode",!1),this.vjs=e,this.source=t,this.tech=i,this.tech.name_="Hlsjs",this.videoElement=i.el(),this.player=e(i.options_.playerId),this.handlers.error=n=>{let r;const o=(n.currentTarget||n.target).error;if(o){switch(Ve.info(o),o.code){case o.MEDIA_ERR_ABORTED:r="You aborted the video playback";break;case o.MEDIA_ERR_DECODE:r="The video playback was aborted due to a corruption problem or because the video used features your browser did not support",this._handleMediaError(o);break;case o.MEDIA_ERR_NETWORK:r="A network error caused the video download to fail part-way";break;case o.MEDIA_ERR_SRC_NOT_SUPPORTED:r="The video could not be loaded, either because the server or network failed or because the format is not supported";break;default:r=o.message}Ve.error(`MEDIA_ERROR: ${r}`)}},this.videoElement.addEventListener("error",this.handlers.error),this.initialize()}duration(){return this._duration===1/0?1/0:isNaN(this.videoElement.duration)?this._duration||0:this.videoElement.duration}seekable(){if(this.hls.media){if(!this.isLive)return this.vjs.createTimeRanges(0,this.hls.media.duration);const e=Math.round(this.hls.media.duration-this.dvrDuration),t=Math.round(this.hls.media.duration-this.edgeMargin);return this.vjs.createTimeRanges(e,t)}return this.vjs.createTimeRanges()}dispose(){this.videoElement.removeEventListener("play",this.handlers.play),this.videoElement.removeEventListener("error",this.handlers.error),this.hls.destroy()}_getHumanErrorMsg(e){switch(e.code){default:return e.message}}_handleUnrecovarableError(e){if(this.hls.levels.filter(t=>t.id>-1).length>1){this._removeQuality(this.hls.loadLevel);return}this.hls.destroy(),Ve.info("bubbling error up to VIDEOJS"),this.tech.error=()=>({...e,message:this._getHumanErrorMsg(e)}),this.tech.trigger("error")}_handleMediaError(e){if(this.errorCounts[et.ErrorTypes.MEDIA_ERROR]===1){Ve.info("trying to recover media error"),this.hls.recoverMediaError();return}if(this.errorCounts[et.ErrorTypes.MEDIA_ERROR]===2){Ve.info("2nd try to recover media error (by swapping audio codec"),this.hls.swapAudioCodec(),this.hls.recoverMediaError();return}this.errorCounts[et.ErrorTypes.MEDIA_ERROR]>2&&this._handleUnrecovarableError(e)}_handleNetworkError(e){var t,i;if(navigator.onLine!==!1){if(this.liveEnded){Ve.info("Forcing end of live stream after a network error"),(t=this.player)==null||t.handleTechEnded_(),(i=this.hls)==null||i.stopLoad();return}if(this.errorCounts[et.ErrorTypes.NETWORK_ERROR]<=this.maxNetworkErrorRecovery){Ve.info("trying to recover network error"),setTimeout(()=>this.hls.startLoad(),1e3),this.hls.once(et.Events.FRAG_LOADED,()=>{this.errorCounts[et.ErrorTypes.NETWORK_ERROR]=0});return}this._handleUnrecovarableError(e)}}_onError(e,t){const i={message:`HLS.js error: ${t.type} - fatal: ${t.fatal} - ${t.details}`};this.errorCounts[t.type]?this.errorCounts[t.type]+=1:this.errorCounts[t.type]=1,/googlebot/i.test(navigator.userAgent)||(t.fatal?Ve.error(i.message,{currentTime:this.player.currentTime(),data:t}):Ve.clientWarn(i.message)),t.type===et.ErrorTypes.NETWORK_ERROR?(i.code=2,this._handleNetworkError(i)):t.fatal&&t.type===et.ErrorTypes.MEDIA_ERROR&&t.details!=="manifestIncompatibleCodecsError"?(i.code=3,this._handleMediaError(i)):t.fatal&&this._handleUnrecovarableError(i)}buildLevelLabel(e){return this.player.srOptions_.levelLabelHandler(e,this.player)}_removeQuality(e){this.hls.removeLevel(e),this.player.peertubeResolutions().remove(e),this.hls.currentLevel=-1}_notifyVideoQualities(){if(!this.metadata)return;const e=[];if(this.metadata.levels.forEach((i,n)=>{e.push({id:n,height:i.height,width:i.width,bitrate:i.bitrate,label:this.buildLevelLabel(i),selected:i.id===this.hls.manualLevel,selectCallback:()=>this.manuallySelectVideoLevel(n)})}),e.filter(i=>i.height!==0).length!==0&&this.getSeparateAudioTrack()){const i=this.getSeparateAudioTrack();e.push({id:-2,label:this.player.localize("Audio only"),selected:!1,selectCallback:()=>{this.audioMode||(this.audioMode=!0,this.updateToAudioOrVideo(i))}})}e.push({id:-1,label:this.player.localize("Auto"),selected:!0,selectCallback:()=>this.manuallySelectVideoLevel(-1)}),this.player.peertubeResolutions().add(e)}manuallySelectVideoLevel(e){if(this.audioMode){this.audioMode=!1,this.updateToAudioOrVideo(this.source.src,e);return}this.hls.currentLevel=e}_startLoad(){this.hls.startLoad(-1),this.videoElement.removeEventListener("play",this.handlers.play)}_onMetaData(e,t){this.metadata=t,this._notifyVideoQualities()}initialize(){this.liveEnded=!1,this.buildBaseConfig(),["","auto"].includes(this.videoElement.preload)&&!this.videoElement.autoplay&&this.hlsjsConfig.autoStartLoad===void 0&&(this.hlsjsConfig.autoStartLoad=!1),this.hlsjsConfig.autoStartLoad===!1&&(this.handlers.play=this._startLoad.bind(this),this.videoElement.addEventListener("play",this.handlers.play)),this.hls=new Rp({...Id(this.hlsjsConfig,["p2pMediaLoaderOptions"]),p2p:{core:this.hlsjsConfig.p2pMediaLoaderOptions}}),this.player.trigger("hlsjs-initialized",{hlsjs:this.hls}),this.hls.on(et.Events.ERROR,(e,t)=>this._onError(e,t)),this.hls.on(et.Events.MANIFEST_PARSED,(e,t)=>this._onMetaData(e,t)),this.hls.on(et.Events.LEVEL_LOADED,(e,t)=>{this.hlsjsConfig.liveSyncDuration?this.edgeMargin=this.hlsjsConfig.liveSyncDuration:this.hlsjsConfig.liveSyncDurationCount&&(this.edgeMargin=this.hlsjsConfig.liveSyncDurationCount*t.details.targetduration),this.isLive&&!t.details.live&&(this.liveEnded=!0,this.player.trigger("hlsjs-live-ended")),this.isLive=t.details.live,this.dvrDuration=t.details.totalduration,this._duration=this.isLive?1/0:t.details.totalduration,this.isLive&&(this.maxNetworkErrorRecovery=30)}),this.registerLevelEventSwitch(),this.hls.once(et.Events.FRAG_LOADED,()=>{this.tech.trigger("loadedmetadata")}),this.hls.attachMedia(this.videoElement),this.hls.loadSource(this.source.src)}updateToAudioOrVideo(e,t){this.player.addClass("vjs-updating-resolution");const i=this.player.currentTime();this.dispose(),this.buildBaseConfig(),this.hlsjsConfig.autoStartLoad=!0,this.player.autoplay("play"),this.hls=new Rp({...Id(this.hlsjsConfig,["p2pMediaLoaderOptions"]),p2p:{core:this.hlsjsConfig.p2pMediaLoaderOptions},startPosition:this.duration()===1/0?void 0:i,startLevel:t}),this.player.trigger("hlsjs-initialized",{hlsjs:this.hls}),this.hls.on(et.Events.ERROR,(n,r)=>this._onError(n,r)),this.registerLevelEventSwitch(),this.hls.attachMedia(this.videoElement),this.hls.loadSource(e),this.player.one("canplay",()=>{this.player.removeClass("vjs-updating-resolution")})}registerLevelEventSwitch(){this.hls.on(et.Events.LEVEL_SWITCHING,(e,t)=>{let i=t.level,n=-1;this.audioMode?i=-2:this.hls.autoLevelEnabled&&(i=-1,n=t.level),this.player.peertubeResolutions().select({id:i,autoResolutionChosenId:n,fireCallback:!1})})}buildBaseConfig(){const e=this.tech.options_,t=this.player.srOptions_,i=t?.hlsjsConfig||e.hlsjsConfig;this.hlsjsConfig=i?{...i}:{}}getSeparateAudioTrack(){if(this.metadata.audioTracks.length!==0)return this.metadata.audioTracks[0].url}}const xp=In("peertube:player:p2p-media-loader"),kA=X.getPlugin("plugin");class IA extends kA{constructor(e,t){if(super(e),this.options=t,this.statsP2PBytes={pendingDownload:[],pendingUpload:[],peersWithWebSeed:0,peersP2POnly:0,totalDownload:0,totalUpload:0},this.statsHTTPBytes={pendingDownload:[],totalDownload:0},this.liveEnded=!1,!X.Html5Hlsjs){if(e.canPlayType("application/vnd.apple.mpegurl")){this.fallbackToBuiltInIOS();return}const i="HLS.js does not seem to be supported. Cannot fallback to built-in HLS";Ve.warn(i);const n={code:MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED,message:i,MEDIA_ERR_ABORTED:MediaError.MEDIA_ERR_ABORTED,MEDIA_ERR_DECODE:MediaError.MEDIA_ERR_DECODE,MEDIA_ERR_NETWORK:MediaError.MEDIA_ERR_NETWORK,MEDIA_ERR_SRC_NOT_SUPPORTED:MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED};e.ready(()=>e.error(n));return}{const i=(r,{hlsjs:o})=>{var u,h;(h=(u=this.hlsjs)==null?void 0:u.p2pEngine)==null||h.destroy(),clearInterval(this.networkInfoInterval),this.hlsjs=o,xp("hls.js initialized, initializing p2p-media-loader plugin",{hlsjs:o}),e.ready(()=>this.initializePlugin())};e.on("hlsjs-initialized",i);const n=()=>{xp("hls.js says the live is ended"),this.liveEnded=!0};e.on("hlsjs-live-ended",n),this.on("dispose",()=>{this.player.off("hlsjs-initialized",i),this.player.off("hlsjs-live-ended",n)})}e.src({type:t.type,src:t.src})}dispose(){var e,t,i,n;(t=(e=this.hlsjs)==null?void 0:e.p2pEngine)==null||t.destroy(),(i=this.hlsjs)==null||i.destroy(),(n=this.options.segmentValidator)==null||n.destroy(),clearInterval(this.networkInfoInterval),super.dispose()}getCurrentLevel(){if(this.hlsjs)return this.hlsjs.levels[this.hlsjs.currentLevel]}getLiveLatency(){return Math.round(this.hlsjs.latency)}getLiveLatencyFromEdge(){return Math.round(this.hlsjs.latency-this.hlsjs.targetLatency)}getHLSJS(){return this.hlsjs}initializePlugin(){this.hlsjs.p2pEngine.addEventListener("onSegmentError",i=>{if(navigator.onLine===!1||this.liveEnded||i.downloadSource!=="http")return;const n=i.segment;Ve.clientError(`Segment ${n.runtimeId} error.`,i),this.options.redundancyUrlManager&&this.options.redundancyUrlManager.onSegmentError(n.url)}),this.hlsjs.p2pEngine.addEventListener("onSegmentLoaded",i=>{i.downloadSource==="http"&&this.options.redundancyUrlManager&&this.options.redundancyUrlManager.onSegmentSuccess(i.segmentUrl)});const e=this.options.redundancyUrlManager?this.options.redundancyUrlManager.countBaseUrls():0;this.totalHTTPPeers=1+e,this.statsP2PBytes.peersWithWebSeed=this.totalHTTPPeers,this.runStats();let t=!0;this.hlsjs.on(et.Events.LEVEL_SWITCHED,()=>{const i=this.getCurrentLevel(),n=Math.min(i?.height||0,i?.width||0);this.player.trigger("resolution-change",{resolution:n,initResolutionChange:t}),t=!1}),this.hlsjs.on(et.Events.MANIFEST_PARSED,(i,n)=>{if(Array.isArray(n.levels)&&n.levels.length>=1){const r=n.levels[0];this.player.trigger("video-ratio-changed",{ratio:r.width/r.height})}}),this.hlsjs.on(et.Events.ERROR,(i,n)=>{n.type===et.ErrorTypes.MEDIA_ERROR&&n.details===et.ErrorDetails.BUFFER_STALLED_ERROR&&this.player.trigger("buffer-stalled")})}runStats(){this.connectedPeers=new Set,this.hlsjs.p2pEngine.getConfig().core.mainStream.isP2PDisabled&&this.hlsjs.on(et.Events.FRAG_LOADED,(e,t)=>{const i=t.frag.stats.loaded;this.statsHTTPBytes.pendingDownload.push(i),this.statsHTTPBytes.totalDownload+=i}),this.hlsjs.p2pEngine.addEventListener("onChunkDownloaded",(e,t)=>{const i=t==="p2p"?this.statsP2PBytes:this.statsHTTPBytes;i.pendingDownload.push(e),i.totalDownload+=e}),this.hlsjs.p2pEngine.addEventListener("onChunkUploaded",e=>{this.statsP2PBytes.pendingUpload.push(e),this.statsP2PBytes.totalUpload+=e}),this.hlsjs.p2pEngine.addEventListener("onPeerConnect",e=>{e.streamType==="main"&&(this.connectedPeers.add(e.peerId),this.statsP2PBytes.peersP2POnly=this.connectedPeers.size,this.statsP2PBytes.peersWithWebSeed=this.totalHTTPPeers+this.statsP2PBytes.peersP2POnly)}),this.hlsjs.p2pEngine.addEventListener("onPeerClose",e=>{e.streamType==="main"&&(this.connectedPeers.delete(e.peerId),this.statsP2PBytes.peersP2POnly=this.connectedPeers.size,this.statsP2PBytes.peersWithWebSeed=this.totalHTTPPeers+this.statsP2PBytes.peersP2POnly)}),this.networkInfoInterval=setInterval(()=>{const e=this.arraySum(this.statsP2PBytes.pendingDownload),t=this.arraySum(this.statsP2PBytes.pendingUpload),i=this.arraySum(this.statsHTTPBytes.pendingDownload);return this.statsP2PBytes.pendingDownload=[],this.statsP2PBytes.pendingUpload=[],this.statsHTTPBytes.pendingDownload=[],this.player.trigger("network-info",{source:"p2p-media-loader",bandwidthEstimate:this.hlsjs.bandwidthEstimate/8,http:{downloadSpeed:i,downloaded:this.statsHTTPBytes.totalDownload},p2p:this.options.p2pEnabled?{downloadSpeed:e,uploadSpeed:t,peersWithWebSeed:this.statsP2PBytes.peersWithWebSeed,peersP2POnly:this.statsP2PBytes.peersP2POnly,downloaded:this.statsP2PBytes.totalDownload,uploaded:this.statsP2PBytes.totalUpload}:void 0})},1e3)}arraySum(e){return e.reduce((t,i)=>t+i,0)}fallbackToBuiltInIOS(){Ve.info("HLS.js does not seem to be supported. Fallback to built-in HLS."),this.player.src({type:this.options.type,src:$p(this.options.src,{videoFileToken:this.options.videoFileToken(),reinjectVideoFileToken:"true"})}),this.getResolutionButton().hide()}getResolutionButton(){return this.player.controlBar.getDescendant(["settingsButton"]).menu.getChild("resolutionMenuButton")}}X.registerPlugin("p2pMediaLoader",IA);const Op=In("peertube:player:web-video-plugin"),RA=X.getPlugin("plugin");class PA extends RA{constructor(e,t){super(e,t),this.videoFiles=t.videoFiles,this.videoFileToken=t.videoFileToken;const i=this.pickAverageVideoFile();i&&this.updateVideoFile({videoFile:i,isUserResolutionChange:!1}),this.onLoadedMetadata=()=>{e.trigger("video-ratio-changed",{ratio:this.player.videoWidth()/this.player.videoHeight()})},e.on("loadedmetadata",this.onLoadedMetadata),e.ready(()=>{if(this.videoFiles.length===0){this.player.addClass("disabled");return}this.buildQualities(),this.setupNetworkInfoInterval()})}dispose(){this.networkInfoInterval&&clearInterval(this.networkInfoInterval),this.onLoadedMetadata&&this.player.off("loadedmetadata",this.onLoadedMetadata),this.onErrorHandler&&this.player.off("error",this.onErrorHandler),this.onPlayHandler&&this.player.off("canplay",this.onPlayHandler),super.dispose()}getCurrentResolutionId(){var e;return(e=this.currentVideoFile)==null?void 0:e.resolution.id}updateVideoFile(e){this.currentVideoFile=e.videoFile,Op("Updating web video file to "+this.currentVideoFile.fileUrl);const t=this.player.paused(),i=this.player.playbackRate(),n=this.player.currentTime();this.onErrorHandler||(this.onErrorHandler=()=>this.player.peertube().displayFatalError(),this.player.one("error",this.onErrorHandler));let r=this.currentVideoFile.fileUrl;this.videoFileToken()&&(r=$p(r,{videoFileToken:this.videoFileToken()}));const o=this.player.autoplay();e.isUserResolutionChange&&(this.player.autoplay(!1),this.player.addClass("vjs-updating-resolution")),this.player.src(r),this.onPlayHandler=()=>{var u;this.player.playbackRate(i),this.player.currentTime(n),this.player.trigger("resolution-change",{resolution:(u=this.currentVideoFile)==null?void 0:u.resolution.id,initResolutionChange:!e.isUserResolutionChange}),e.isUserResolutionChange&&(this.player.trigger("web-video-source-change"),this.tryToPlay().then(()=>{t&&this.player.pause(),this.player.autoplay(o)}))},this.player.one("canplay",this.onPlayHandler)}getCurrentVideoFile(){return this.currentVideoFile}tryToPlay(){Op("Try to play manually the video");const e=this.player.play();if(e!==void 0)return e.catch(t=>{t.message.includes("The play() request was interrupted by a call to pause()")||(Ve.warn(t),this.player.pause(),this.player.posterImage.show(),this.player.removeClass("vjs-has-autoplay"),this.player.removeClass("vjs-playing-audio-only-content"))}).finally(()=>{this.player.removeClass("vjs-updating-resolution")})}pickAverageVideoFile(){if(!this.videoFiles||this.videoFiles.length===0)return;if(this.videoFiles.length===1)return this.videoFiles[0];const e=this.videoFiles.filter(t=>t.resolution.id!==0);return e[Math.floor(e.length/2)]}buildQualities(){const e=this.videoFiles.map(t=>{var i;return{id:t.resolution.id,label:this.player.localize(qp(t.resolution.label,t.fps)),height:t.resolution.id,selected:t.id===((i=this.currentVideoFile)==null?void 0:i.id),selectCallback:()=>this.updateVideoFile({videoFile:t,isUserResolutionChange:!0})}});this.player.peertubeResolutions().add(e)}setupNetworkInfoInterval(){this.networkInfoInterval=setInterval(()=>{var e;return this.player.trigger("network-info",{source:"web-video",http:{downloaded:this.player.bufferedPercent()*((e=this.currentVideoFile)==null?void 0:e.size)}})},1e3)}}X.registerPlugin("webVideo",PA);const DA=X.getComponent("Component");class hy extends DA{constructor(e,t){super(e,t)}createEl(){const e=super.createEl("div",{className:"peertube-dock"});if(this.options_.avatarUrl){const i=X.dom.createEl("img",{className:"peertube-dock-avatar",src:this.options_.avatarUrl});e.appendChild(i)}const t=super.createEl("div",{className:"peertube-dock-title-description"});if(this.options_.title){const i=X.dom.createEl("div",{className:"peertube-dock-title",title:this.options_.title,innerText:this.options_.title});t.appendChild(i)}if(this.options_.description){const i=X.dom.createEl("div",{className:"peertube-dock-description",title:this.options_.description,innerText:this.options_.description});t.appendChild(i)}return(this.options_.title||this.options_.description)&&e.appendChild(t),e}}X.registerComponent("PeerTubeDockComponent",hy);const xA=X.getPlugin("plugin");class OA extends xA{constructor(e,t){super(e,t),e.ready(()=>{e.addClass("peertube-dock")}),this.dockComponent=new hy(e,t),e.addChild(this.dockComponent)}dispose(){var e;(e=this.dockComponent)==null||e.dispose(),this.player.removeChild(this.dockComponent),this.player.removeClass("peertube-dock"),super.dispose()}}X.registerPlugin("peertubeDock",OA);function Vu(s,e){e||(e=document.body);const t=document.createElement("textarea");t.value=s,t.setAttribute("readonly",""),t.style.position="absolute",t.style.left="-9999px",e.appendChild(t),t.select(),document.execCommand("copy"),e.removeChild(t)}function MA(s){return new Promise(e=>{setTimeout(()=>e(),s)})}function FA(s){const{embedUrl:e,embedTitle:t,aspectRatio:i,responsive:n=!1}=s,r=document.createElement("iframe");if(r.title=t,r.width=n?"100%":"560",r.height=n?"100%":"315",r.src=e,r.frameBorder="0",r.allowFullscreen=!0,r.sandbox.add("allow-same-origin","allow-scripts","allow-popups","allow-forms"),n){const o=document.createElement("div");return o.style.position="relative",o.style.paddingTop=i?(1/i*100).toFixed(2)+"%":"56.25%",r.style.position="absolute",r.style.inset="0",o.appendChild(r),o.outerHTML}return r.outerHTML}class NA{constructor(e){this.options=e}getChildrenOptions(){return{...this.getPreviousVideo(),playToggle:{},...this.getNextVideo(),...this.getTimeControls(),...this.getProgressControl(),p2PInfoButton:{},muteToggle:{},volumeControl:{},captionToggleButton:{},...this.getSettingsButton(),...this.getPeerTubeLinkButton(),...this.getTheaterButton(),fullscreenToggle:{}}}getSettingsButton(){const e=[];return e.push("playbackRateMenuButton"),e.push("captionsButton"),e.push("resolutionMenuButton"),{settingsButton:{setup:{maxHeightOffset:60},entries:e}}}getTimeControls(){return{peerTubeLiveDisplay:{},currentTimeDisplay:{},timeDivider:{},durationDisplay:{}}}getProgressControl(){return{progressControl:{children:{seekBar:{children:{loadProgressBar:{},mouseTimeDisplay:{},playProgressBar:{}}}}}}}getPreviousVideo(){return{previousVideoButton:{type:"previous",handler:()=>this.options.previousVideo().handler(),isDisabled:()=>!this.options.previousVideo().enabled,isDisplayed:()=>this.options.previousVideo().displayControlBarButton}}}getNextVideo(){return{nextVideoButton:{type:"next",handler:()=>this.options.nextVideo().handler(),isDisabled:()=>!this.options.nextVideo().enabled,isDisplayed:()=>this.options.nextVideo().displayControlBarButton}}}getPeerTubeLinkButton(){return{peerTubeLinkButton:{isDisplayed:this.options.peertubeLink,shortUUID:this.options.videoShortUUID,instanceName:this.options.instanceName}}}getTheaterButton(){return{theaterButton:{isDisplayed:()=>this.options.theaterButton}}}}function Lc(s,e){const t=new URL(s),i=new URL(e);return t.hostname==="localhost"&&i.hostname==="localhost"?!0:t.origin===i.origin}class BA{constructor(e=[]){Ke(this,"map",new Map),this.baseUrls=e}onSegmentError(e){if(!this.map.has(e))return;const t=this.map.get(e);this.map.delete(e);const i=HA(t),n=i.length;this.baseUrls=this.baseUrls.filter(r=>r!==i&&r!==i+"/"),n!==this.baseUrls.length&&Ve.info(`Removed redundancy of segment URL ${t}.`)}onSegmentSuccess(e){this.map.delete(e)}buildUrl(e){const t=this.baseUrls.length+1,i=this.getRandomInt(t);if(i===t-1)return e;const n=this.baseUrls[i],r=n.endsWith("/")?"":"/",o=n+r+UA(e);return this.map.set(e,o),o}countBaseUrls(){return this.baseUrls.length}getRandomInt(e){return Math.floor(Math.random()*Math.floor(e))}}function UA(s){return s.split("/").pop()}function HA(s){const e=s.split("/");return e.pop(),e.join("/")}var dy={},No={};No.byteLength=VA;No.toByteArray=KA;No.fromByteArray=zA;var Ri=[],ti=[],$A=typeof Uint8Array<"u"?Uint8Array:Array,Gu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var ks=0,jA=Gu.length;ks<jA;++ks)Ri[ks]=Gu[ks],ti[Gu.charCodeAt(ks)]=ks;ti[45]=62;ti[95]=63;function fy(s){var e=s.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=s.indexOf("=");t===-1&&(t=e);var i=t===e?0:4-t%4;return[t,i]}function VA(s){var e=fy(s),t=e[0],i=e[1];return(t+i)*3/4-i}function GA(s,e,t){return(e+t)*3/4-t}function KA(s){var e,t=fy(s),i=t[0],n=t[1],r=new $A(GA(s,i,n)),o=0,u=n>0?i-4:i,h;for(h=0;h<u;h+=4)e=ti[s.charCodeAt(h)]<<18|ti[s.charCodeAt(h+1)]<<12|ti[s.charCodeAt(h+2)]<<6|ti[s.charCodeAt(h+3)],r[o++]=e>>16&255,r[o++]=e>>8&255,r[o++]=e&255;return n===2&&(e=ti[s.charCodeAt(h)]<<2|ti[s.charCodeAt(h+1)]>>4,r[o++]=e&255),n===1&&(e=ti[s.charCodeAt(h)]<<10|ti[s.charCodeAt(h+1)]<<4|ti[s.charCodeAt(h+2)]>>2,r[o++]=e>>8&255,r[o++]=e&255),r}function qA(s){return Ri[s>>18&63]+Ri[s>>12&63]+Ri[s>>6&63]+Ri[s&63]}function WA(s,e,t){for(var i,n=[],r=e;r<t;r+=3)i=(s[r]<<16&16711680)+(s[r+1]<<8&65280)+(s[r+2]&255),n.push(qA(i));return n.join("")}function zA(s){for(var e,t=s.length,i=t%3,n=[],r=16383,o=0,u=t-i;o<u;o+=r)n.push(WA(s,o,o+r>u?u:o+r));return i===1?(e=s[t-1],n.push(Ri[e>>2]+Ri[e<<4&63]+"==")):i===2&&(e=(s[t-2]<<8)+s[t-1],n.push(Ri[e>>10]+Ri[e>>4&63]+Ri[e<<2&63]+"=")),n.join("")}var sh={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */sh.read=function(s,e,t,i,n){var r,o,u=n*8-i-1,h=(1<<u)-1,p=h>>1,d=-7,g=t?n-1:0,T=t?-1:1,b=s[e+g];for(g+=T,r=b&(1<<-d)-1,b>>=-d,d+=u;d>0;r=r*256+s[e+g],g+=T,d-=8);for(o=r&(1<<-d)-1,r>>=-d,d+=i;d>0;o=o*256+s[e+g],g+=T,d-=8);if(r===0)r=1-p;else{if(r===h)return o?NaN:(b?-1:1)*(1/0);o=o+Math.pow(2,i),r=r-p}return(b?-1:1)*o*Math.pow(2,r-i)};sh.write=function(s,e,t,i,n,r){var o,u,h,p=r*8-n-1,d=(1<<p)-1,g=d>>1,T=n===23?Math.pow(2,-24)-Math.pow(2,-77):0,b=i?0:r-1,E=i?1:-1,w=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,o=d):(o=Math.floor(Math.log(e)/Math.LN2),e*(h=Math.pow(2,-o))<1&&(o--,h*=2),o+g>=1?e+=T/h:e+=T*Math.pow(2,1-g),e*h>=2&&(o++,h/=2),o+g>=d?(u=0,o=d):o+g>=1?(u=(e*h-1)*Math.pow(2,n),o=o+g):(u=e*Math.pow(2,g-1)*Math.pow(2,n),o=0));n>=8;s[t+b]=u&255,b+=E,u/=256,n-=8);for(o=o<<n|u,p+=n;p>0;s[t+b]=o&255,b+=E,o/=256,p-=8);s[t+b-E]|=w*128};/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */(function(s){const e=No,t=sh,i=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;s.Buffer=d,s.SlowBuffer=k,s.INSPECT_MAX_BYTES=50;const n=2147483647;s.kMaxLength=n;const{Uint8Array:r,ArrayBuffer:o,SharedArrayBuffer:u}=globalThis;d.TYPED_ARRAY_SUPPORT=h(),!d.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function h(){try{const R=new r(1),_={foo:function(){return 42}};return Object.setPrototypeOf(_,r.prototype),Object.setPrototypeOf(R,_),R.foo()===42}catch{return!1}}Object.defineProperty(d.prototype,"parent",{enumerable:!0,get:function(){if(d.isBuffer(this))return this.buffer}}),Object.defineProperty(d.prototype,"offset",{enumerable:!0,get:function(){if(d.isBuffer(this))return this.byteOffset}});function p(R){if(R>n)throw new RangeError('The value "'+R+'" is invalid for option "size"');const _=new r(R);return Object.setPrototypeOf(_,d.prototype),_}function d(R,_,C){if(typeof R=="number"){if(typeof _=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return E(R)}return g(R,_,C)}d.poolSize=8192;function g(R,_,C){if(typeof R=="string")return w(R,_);if(o.isView(R))return L(R);if(R==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof R);if(Ct(R,o)||R&&Ct(R.buffer,o)||typeof u<"u"&&(Ct(R,u)||R&&Ct(R.buffer,u)))return P(R,_,C);if(typeof R=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const $=R.valueOf&&R.valueOf();if($!=null&&$!==R)return d.from($,_,C);const q=M(R);if(q)return q;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof R[Symbol.toPrimitive]=="function")return d.from(R[Symbol.toPrimitive]("string"),_,C);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof R)}d.from=function(R,_,C){return g(R,_,C)},Object.setPrototypeOf(d.prototype,r.prototype),Object.setPrototypeOf(d,r);function T(R){if(typeof R!="number")throw new TypeError('"size" argument must be of type number');if(R<0)throw new RangeError('The value "'+R+'" is invalid for option "size"')}function b(R,_,C){return T(R),R<=0?p(R):_!==void 0?typeof C=="string"?p(R).fill(_,C):p(R).fill(_):p(R)}d.alloc=function(R,_,C){return b(R,_,C)};function E(R){return T(R),p(R<0?0:O(R)|0)}d.allocUnsafe=function(R){return E(R)},d.allocUnsafeSlow=function(R){return E(R)};function w(R,_){if((typeof _!="string"||_==="")&&(_="utf8"),!d.isEncoding(_))throw new TypeError("Unknown encoding: "+_);const C=N(R,_)|0;let $=p(C);const q=$.write(R,_);return q!==C&&($=$.slice(0,q)),$}function A(R){const _=R.length<0?0:O(R.length)|0,C=p(_);for(let $=0;$<_;$+=1)C[$]=R[$]&255;return C}function L(R){if(Ct(R,r)){const _=new r(R);return P(_.buffer,_.byteOffset,_.byteLength)}return A(R)}function P(R,_,C){if(_<0||R.byteLength<_)throw new RangeError('"offset" is outside of buffer bounds');if(R.byteLength<_+(C||0))throw new RangeError('"length" is outside of buffer bounds');let $;return _===void 0&&C===void 0?$=new r(R):C===void 0?$=new r(R,_):$=new r(R,_,C),Object.setPrototypeOf($,d.prototype),$}function M(R){if(d.isBuffer(R)){const _=O(R.length)|0,C=p(_);return C.length===0||R.copy(C,0,0,_),C}if(R.length!==void 0)return typeof R.length!="number"||Wt(R.length)?p(0):A(R);if(R.type==="Buffer"&&Array.isArray(R.data))return A(R.data)}function O(R){if(R>=n)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n.toString(16)+" bytes");return R|0}function k(R){return+R!=R&&(R=0),d.alloc(+R)}d.isBuffer=function(_){return _!=null&&_._isBuffer===!0&&_!==d.prototype},d.compare=function(_,C){if(Ct(_,r)&&(_=d.from(_,_.offset,_.byteLength)),Ct(C,r)&&(C=d.from(C,C.offset,C.byteLength)),!d.isBuffer(_)||!d.isBuffer(C))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(_===C)return 0;let $=_.length,q=C.length;for(let J=0,ne=Math.min($,q);J<ne;++J)if(_[J]!==C[J]){$=_[J],q=C[J];break}return $<q?-1:q<$?1:0},d.isEncoding=function(_){switch(String(_).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},d.concat=function(_,C){if(!Array.isArray(_))throw new TypeError('"list" argument must be an Array of Buffers');if(_.length===0)return d.alloc(0);let $;if(C===void 0)for(C=0,$=0;$<_.length;++$)C+=_[$].length;const q=d.allocUnsafe(C);let J=0;for($=0;$<_.length;++$){let ne=_[$];if(Ct(ne,r))J+ne.length>q.length?(d.isBuffer(ne)||(ne=d.from(ne)),ne.copy(q,J)):r.prototype.set.call(q,ne,J);else if(d.isBuffer(ne))ne.copy(q,J);else throw new TypeError('"list" argument must be an Array of Buffers');J+=ne.length}return q};function N(R,_){if(d.isBuffer(R))return R.length;if(o.isView(R)||Ct(R,o))return R.byteLength;if(typeof R!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof R);const C=R.length,$=arguments.length>2&&arguments[2]===!0;if(!$&&C===0)return 0;let q=!1;for(;;)switch(_){case"ascii":case"latin1":case"binary":return C;case"utf8":case"utf-8":return an(R).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C*2;case"hex":return C>>>1;case"base64":return on(R).length;default:if(q)return $?-1:an(R).length;_=(""+_).toLowerCase(),q=!0}}d.byteLength=N;function H(R,_,C){let $=!1;if((_===void 0||_<0)&&(_=0),_>this.length||((C===void 0||C>this.length)&&(C=this.length),C<=0)||(C>>>=0,_>>>=0,C<=_))return"";for(R||(R="utf8");;)switch(R){case"hex":return ae(this,_,C);case"utf8":case"utf-8":return ve(this,_,C);case"ascii":return Q(this,_,C);case"latin1":case"binary":return Ee(this,_,C);case"base64":return fe(this,_,C);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ie(this,_,C);default:if($)throw new TypeError("Unknown encoding: "+R);R=(R+"").toLowerCase(),$=!0}}d.prototype._isBuffer=!0;function G(R,_,C){const $=R[_];R[_]=R[C],R[C]=$}d.prototype.swap16=function(){const _=this.length;if(_%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let C=0;C<_;C+=2)G(this,C,C+1);return this},d.prototype.swap32=function(){const _=this.length;if(_%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let C=0;C<_;C+=4)G(this,C,C+3),G(this,C+1,C+2);return this},d.prototype.swap64=function(){const _=this.length;if(_%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let C=0;C<_;C+=8)G(this,C,C+7),G(this,C+1,C+6),G(this,C+2,C+5),G(this,C+3,C+4);return this},d.prototype.toString=function(){const _=this.length;return _===0?"":arguments.length===0?ve(this,0,_):H.apply(this,arguments)},d.prototype.toLocaleString=d.prototype.toString,d.prototype.equals=function(_){if(!d.isBuffer(_))throw new TypeError("Argument must be a Buffer");return this===_?!0:d.compare(this,_)===0},d.prototype.inspect=function(){let _="";const C=s.INSPECT_MAX_BYTES;return _=this.toString("hex",0,C).replace(/(.{2})/g,"$1 ").trim(),this.length>C&&(_+=" ... "),"<Buffer "+_+">"},i&&(d.prototype[i]=d.prototype.inspect),d.prototype.compare=function(_,C,$,q,J){if(Ct(_,r)&&(_=d.from(_,_.offset,_.byteLength)),!d.isBuffer(_))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof _);if(C===void 0&&(C=0),$===void 0&&($=_?_.length:0),q===void 0&&(q=0),J===void 0&&(J=this.length),C<0||$>_.length||q<0||J>this.length)throw new RangeError("out of range index");if(q>=J&&C>=$)return 0;if(q>=J)return-1;if(C>=$)return 1;if(C>>>=0,$>>>=0,q>>>=0,J>>>=0,this===_)return 0;let ne=J-q,Oe=$-C;const tt=Math.min(ne,Oe),Xe=this.slice(q,J),Ie=_.slice(C,$);for(let $e=0;$e<tt;++$e)if(Xe[$e]!==Ie[$e]){ne=Xe[$e],Oe=Ie[$e];break}return ne<Oe?-1:Oe<ne?1:0};function B(R,_,C,$,q){if(R.length===0)return-1;if(typeof C=="string"?($=C,C=0):C>2147483647?C=2147483647:C<-2147483648&&(C=-2147483648),C=+C,Wt(C)&&(C=q?0:R.length-1),C<0&&(C=R.length+C),C>=R.length){if(q)return-1;C=R.length-1}else if(C<0)if(q)C=0;else return-1;if(typeof _=="string"&&(_=d.from(_,$)),d.isBuffer(_))return _.length===0?-1:D(R,_,C,$,q);if(typeof _=="number")return _=_&255,typeof r.prototype.indexOf=="function"?q?r.prototype.indexOf.call(R,_,C):r.prototype.lastIndexOf.call(R,_,C):D(R,[_],C,$,q);throw new TypeError("val must be string, number or Buffer")}function D(R,_,C,$,q){let J=1,ne=R.length,Oe=_.length;if($!==void 0&&($=String($).toLowerCase(),$==="ucs2"||$==="ucs-2"||$==="utf16le"||$==="utf-16le")){if(R.length<2||_.length<2)return-1;J=2,ne/=2,Oe/=2,C/=2}function tt(Ie,$e){return J===1?Ie[$e]:Ie.readUInt16BE($e*J)}let Xe;if(q){let Ie=-1;for(Xe=C;Xe<ne;Xe++)if(tt(R,Xe)===tt(_,Ie===-1?0:Xe-Ie)){if(Ie===-1&&(Ie=Xe),Xe-Ie+1===Oe)return Ie*J}else Ie!==-1&&(Xe-=Xe-Ie),Ie=-1}else for(C+Oe>ne&&(C=ne-Oe),Xe=C;Xe>=0;Xe--){let Ie=!0;for(let $e=0;$e<Oe;$e++)if(tt(R,Xe+$e)!==tt(_,$e)){Ie=!1;break}if(Ie)return Xe}return-1}d.prototype.includes=function(_,C,$){return this.indexOf(_,C,$)!==-1},d.prototype.indexOf=function(_,C,$){return B(this,_,C,$,!0)},d.prototype.lastIndexOf=function(_,C,$){return B(this,_,C,$,!1)};function K(R,_,C,$){C=Number(C)||0;const q=R.length-C;$?($=Number($),$>q&&($=q)):$=q;const J=_.length;$>J/2&&($=J/2);let ne;for(ne=0;ne<$;++ne){const Oe=parseInt(_.substr(ne*2,2),16);if(Wt(Oe))return ne;R[C+ne]=Oe}return ne}function oe(R,_,C,$){return qt(an(_,R.length-C),R,C,$)}function Z(R,_,C,$){return qt(Hi(_),R,C,$)}function le(R,_,C,$){return qt(on(_),R,C,$)}function ce(R,_,C,$){return qt(Kt(_,R.length-C),R,C,$)}d.prototype.write=function(_,C,$,q){if(C===void 0)q="utf8",$=this.length,C=0;else if($===void 0&&typeof C=="string")q=C,$=this.length,C=0;else if(isFinite(C))C=C>>>0,isFinite($)?($=$>>>0,q===void 0&&(q="utf8")):(q=$,$=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const J=this.length-C;if(($===void 0||$>J)&&($=J),_.length>0&&($<0||C<0)||C>this.length)throw new RangeError("Attempt to write outside buffer bounds");q||(q="utf8");let ne=!1;for(;;)switch(q){case"hex":return K(this,_,C,$);case"utf8":case"utf-8":return oe(this,_,C,$);case"ascii":case"latin1":case"binary":return Z(this,_,C,$);case"base64":return le(this,_,C,$);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ce(this,_,C,$);default:if(ne)throw new TypeError("Unknown encoding: "+q);q=(""+q).toLowerCase(),ne=!0}},d.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function fe(R,_,C){return _===0&&C===R.length?e.fromByteArray(R):e.fromByteArray(R.slice(_,C))}function ve(R,_,C){C=Math.min(R.length,C);const $=[];let q=_;for(;q<C;){const J=R[q];let ne=null,Oe=J>239?4:J>223?3:J>191?2:1;if(q+Oe<=C){let tt,Xe,Ie,$e;switch(Oe){case 1:J<128&&(ne=J);break;case 2:tt=R[q+1],(tt&192)===128&&($e=(J&31)<<6|tt&63,$e>127&&(ne=$e));break;case 3:tt=R[q+1],Xe=R[q+2],(tt&192)===128&&(Xe&192)===128&&($e=(J&15)<<12|(tt&63)<<6|Xe&63,$e>2047&&($e<55296||$e>57343)&&(ne=$e));break;case 4:tt=R[q+1],Xe=R[q+2],Ie=R[q+3],(tt&192)===128&&(Xe&192)===128&&(Ie&192)===128&&($e=(J&15)<<18|(tt&63)<<12|(Xe&63)<<6|Ie&63,$e>65535&&$e<1114112&&(ne=$e))}}ne===null?(ne=65533,Oe=1):ne>65535&&(ne-=65536,$.push(ne>>>10&1023|55296),ne=56320|ne&1023),$.push(ne),q+=Oe}return ee($)}const be=4096;function ee(R){const _=R.length;if(_<=be)return String.fromCharCode.apply(String,R);let C="",$=0;for(;$<_;)C+=String.fromCharCode.apply(String,R.slice($,$+=be));return C}function Q(R,_,C){let $="";C=Math.min(R.length,C);for(let q=_;q<C;++q)$+=String.fromCharCode(R[q]&127);return $}function Ee(R,_,C){let $="";C=Math.min(R.length,C);for(let q=_;q<C;++q)$+=String.fromCharCode(R[q]);return $}function ae(R,_,C){const $=R.length;(!_||_<0)&&(_=0),(!C||C<0||C>$)&&(C=$);let q="";for(let J=_;J<C;++J)q+=ri[R[J]];return q}function ie(R,_,C){const $=R.slice(_,C);let q="";for(let J=0;J<$.length-1;J+=2)q+=String.fromCharCode($[J]+$[J+1]*256);return q}d.prototype.slice=function(_,C){const $=this.length;_=~~_,C=C===void 0?$:~~C,_<0?(_+=$,_<0&&(_=0)):_>$&&(_=$),C<0?(C+=$,C<0&&(C=0)):C>$&&(C=$),C<_&&(C=_);const q=this.subarray(_,C);return Object.setPrototypeOf(q,d.prototype),q};function Le(R,_,C){if(R%1!==0||R<0)throw new RangeError("offset is not uint");if(R+_>C)throw new RangeError("Trying to access beyond buffer length")}d.prototype.readUintLE=d.prototype.readUIntLE=function(_,C,$){_=_>>>0,C=C>>>0,$||Le(_,C,this.length);let q=this[_],J=1,ne=0;for(;++ne<C&&(J*=256);)q+=this[_+ne]*J;return q},d.prototype.readUintBE=d.prototype.readUIntBE=function(_,C,$){_=_>>>0,C=C>>>0,$||Le(_,C,this.length);let q=this[_+--C],J=1;for(;C>0&&(J*=256);)q+=this[_+--C]*J;return q},d.prototype.readUint8=d.prototype.readUInt8=function(_,C){return _=_>>>0,C||Le(_,1,this.length),this[_]},d.prototype.readUint16LE=d.prototype.readUInt16LE=function(_,C){return _=_>>>0,C||Le(_,2,this.length),this[_]|this[_+1]<<8},d.prototype.readUint16BE=d.prototype.readUInt16BE=function(_,C){return _=_>>>0,C||Le(_,2,this.length),this[_]<<8|this[_+1]},d.prototype.readUint32LE=d.prototype.readUInt32LE=function(_,C){return _=_>>>0,C||Le(_,4,this.length),(this[_]|this[_+1]<<8|this[_+2]<<16)+this[_+3]*16777216},d.prototype.readUint32BE=d.prototype.readUInt32BE=function(_,C){return _=_>>>0,C||Le(_,4,this.length),this[_]*16777216+(this[_+1]<<16|this[_+2]<<8|this[_+3])},d.prototype.readBigUInt64LE=It(function(_){_=_>>>0,kt(_,"offset");const C=this[_],$=this[_+7];(C===void 0||$===void 0)&&gt(_,this.length-8);const q=C+this[++_]*2**8+this[++_]*2**16+this[++_]*2**24,J=this[++_]+this[++_]*2**8+this[++_]*2**16+$*2**24;return BigInt(q)+(BigInt(J)<<BigInt(32))}),d.prototype.readBigUInt64BE=It(function(_){_=_>>>0,kt(_,"offset");const C=this[_],$=this[_+7];(C===void 0||$===void 0)&&gt(_,this.length-8);const q=C*2**24+this[++_]*2**16+this[++_]*2**8+this[++_],J=this[++_]*2**24+this[++_]*2**16+this[++_]*2**8+$;return(BigInt(q)<<BigInt(32))+BigInt(J)}),d.prototype.readIntLE=function(_,C,$){_=_>>>0,C=C>>>0,$||Le(_,C,this.length);let q=this[_],J=1,ne=0;for(;++ne<C&&(J*=256);)q+=this[_+ne]*J;return J*=128,q>=J&&(q-=Math.pow(2,8*C)),q},d.prototype.readIntBE=function(_,C,$){_=_>>>0,C=C>>>0,$||Le(_,C,this.length);let q=C,J=1,ne=this[_+--q];for(;q>0&&(J*=256);)ne+=this[_+--q]*J;return J*=128,ne>=J&&(ne-=Math.pow(2,8*C)),ne},d.prototype.readInt8=function(_,C){return _=_>>>0,C||Le(_,1,this.length),this[_]&128?(255-this[_]+1)*-1:this[_]},d.prototype.readInt16LE=function(_,C){_=_>>>0,C||Le(_,2,this.length);const $=this[_]|this[_+1]<<8;return $&32768?$|4294901760:$},d.prototype.readInt16BE=function(_,C){_=_>>>0,C||Le(_,2,this.length);const $=this[_+1]|this[_]<<8;return $&32768?$|4294901760:$},d.prototype.readInt32LE=function(_,C){return _=_>>>0,C||Le(_,4,this.length),this[_]|this[_+1]<<8|this[_+2]<<16|this[_+3]<<24},d.prototype.readInt32BE=function(_,C){return _=_>>>0,C||Le(_,4,this.length),this[_]<<24|this[_+1]<<16|this[_+2]<<8|this[_+3]},d.prototype.readBigInt64LE=It(function(_){_=_>>>0,kt(_,"offset");const C=this[_],$=this[_+7];(C===void 0||$===void 0)&&gt(_,this.length-8);const q=this[_+4]+this[_+5]*2**8+this[_+6]*2**16+($<<24);return(BigInt(q)<<BigInt(32))+BigInt(C+this[++_]*2**8+this[++_]*2**16+this[++_]*2**24)}),d.prototype.readBigInt64BE=It(function(_){_=_>>>0,kt(_,"offset");const C=this[_],$=this[_+7];(C===void 0||$===void 0)&&gt(_,this.length-8);const q=(C<<24)+this[++_]*2**16+this[++_]*2**8+this[++_];return(BigInt(q)<<BigInt(32))+BigInt(this[++_]*2**24+this[++_]*2**16+this[++_]*2**8+$)}),d.prototype.readFloatLE=function(_,C){return _=_>>>0,C||Le(_,4,this.length),t.read(this,_,!0,23,4)},d.prototype.readFloatBE=function(_,C){return _=_>>>0,C||Le(_,4,this.length),t.read(this,_,!1,23,4)},d.prototype.readDoubleLE=function(_,C){return _=_>>>0,C||Le(_,8,this.length),t.read(this,_,!0,52,8)},d.prototype.readDoubleBE=function(_,C){return _=_>>>0,C||Le(_,8,this.length),t.read(this,_,!1,52,8)};function Ce(R,_,C,$,q,J){if(!d.isBuffer(R))throw new TypeError('"buffer" argument must be a Buffer instance');if(_>q||_<J)throw new RangeError('"value" argument is out of bounds');if(C+$>R.length)throw new RangeError("Index out of range")}d.prototype.writeUintLE=d.prototype.writeUIntLE=function(_,C,$,q){if(_=+_,C=C>>>0,$=$>>>0,!q){const Oe=Math.pow(2,8*$)-1;Ce(this,_,C,$,Oe,0)}let J=1,ne=0;for(this[C]=_&255;++ne<$&&(J*=256);)this[C+ne]=_/J&255;return C+$},d.prototype.writeUintBE=d.prototype.writeUIntBE=function(_,C,$,q){if(_=+_,C=C>>>0,$=$>>>0,!q){const Oe=Math.pow(2,8*$)-1;Ce(this,_,C,$,Oe,0)}let J=$-1,ne=1;for(this[C+J]=_&255;--J>=0&&(ne*=256);)this[C+J]=_/ne&255;return C+$},d.prototype.writeUint8=d.prototype.writeUInt8=function(_,C,$){return _=+_,C=C>>>0,$||Ce(this,_,C,1,255,0),this[C]=_&255,C+1},d.prototype.writeUint16LE=d.prototype.writeUInt16LE=function(_,C,$){return _=+_,C=C>>>0,$||Ce(this,_,C,2,65535,0),this[C]=_&255,this[C+1]=_>>>8,C+2},d.prototype.writeUint16BE=d.prototype.writeUInt16BE=function(_,C,$){return _=+_,C=C>>>0,$||Ce(this,_,C,2,65535,0),this[C]=_>>>8,this[C+1]=_&255,C+2},d.prototype.writeUint32LE=d.prototype.writeUInt32LE=function(_,C,$){return _=+_,C=C>>>0,$||Ce(this,_,C,4,4294967295,0),this[C+3]=_>>>24,this[C+2]=_>>>16,this[C+1]=_>>>8,this[C]=_&255,C+4},d.prototype.writeUint32BE=d.prototype.writeUInt32BE=function(_,C,$){return _=+_,C=C>>>0,$||Ce(this,_,C,4,4294967295,0),this[C]=_>>>24,this[C+1]=_>>>16,this[C+2]=_>>>8,this[C+3]=_&255,C+4};function Ue(R,_,C,$,q){Ui(_,$,q,R,C,7);let J=Number(_&BigInt(4294967295));R[C++]=J,J=J>>8,R[C++]=J,J=J>>8,R[C++]=J,J=J>>8,R[C++]=J;let ne=Number(_>>BigInt(32)&BigInt(4294967295));return R[C++]=ne,ne=ne>>8,R[C++]=ne,ne=ne>>8,R[C++]=ne,ne=ne>>8,R[C++]=ne,C}function He(R,_,C,$,q){Ui(_,$,q,R,C,7);let J=Number(_&BigInt(4294967295));R[C+7]=J,J=J>>8,R[C+6]=J,J=J>>8,R[C+5]=J,J=J>>8,R[C+4]=J;let ne=Number(_>>BigInt(32)&BigInt(4294967295));return R[C+3]=ne,ne=ne>>8,R[C+2]=ne,ne=ne>>8,R[C+1]=ne,ne=ne>>8,R[C]=ne,C+8}d.prototype.writeBigUInt64LE=It(function(_,C=0){return Ue(this,_,C,BigInt(0),BigInt("0xffffffffffffffff"))}),d.prototype.writeBigUInt64BE=It(function(_,C=0){return He(this,_,C,BigInt(0),BigInt("0xffffffffffffffff"))}),d.prototype.writeIntLE=function(_,C,$,q){if(_=+_,C=C>>>0,!q){const tt=Math.pow(2,8*$-1);Ce(this,_,C,$,tt-1,-tt)}let J=0,ne=1,Oe=0;for(this[C]=_&255;++J<$&&(ne*=256);)_<0&&Oe===0&&this[C+J-1]!==0&&(Oe=1),this[C+J]=(_/ne>>0)-Oe&255;return C+$},d.prototype.writeIntBE=function(_,C,$,q){if(_=+_,C=C>>>0,!q){const tt=Math.pow(2,8*$-1);Ce(this,_,C,$,tt-1,-tt)}let J=$-1,ne=1,Oe=0;for(this[C+J]=_&255;--J>=0&&(ne*=256);)_<0&&Oe===0&&this[C+J+1]!==0&&(Oe=1),this[C+J]=(_/ne>>0)-Oe&255;return C+$},d.prototype.writeInt8=function(_,C,$){return _=+_,C=C>>>0,$||Ce(this,_,C,1,127,-128),_<0&&(_=255+_+1),this[C]=_&255,C+1},d.prototype.writeInt16LE=function(_,C,$){return _=+_,C=C>>>0,$||Ce(this,_,C,2,32767,-32768),this[C]=_&255,this[C+1]=_>>>8,C+2},d.prototype.writeInt16BE=function(_,C,$){return _=+_,C=C>>>0,$||Ce(this,_,C,2,32767,-32768),this[C]=_>>>8,this[C+1]=_&255,C+2},d.prototype.writeInt32LE=function(_,C,$){return _=+_,C=C>>>0,$||Ce(this,_,C,4,2147483647,-2147483648),this[C]=_&255,this[C+1]=_>>>8,this[C+2]=_>>>16,this[C+3]=_>>>24,C+4},d.prototype.writeInt32BE=function(_,C,$){return _=+_,C=C>>>0,$||Ce(this,_,C,4,2147483647,-2147483648),_<0&&(_=4294967295+_+1),this[C]=_>>>24,this[C+1]=_>>>16,this[C+2]=_>>>8,this[C+3]=_&255,C+4},d.prototype.writeBigInt64LE=It(function(_,C=0){return Ue(this,_,C,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),d.prototype.writeBigInt64BE=It(function(_,C=0){return He(this,_,C,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Fe(R,_,C,$,q,J){if(C+$>R.length)throw new RangeError("Index out of range");if(C<0)throw new RangeError("Index out of range")}function ze(R,_,C,$,q){return _=+_,C=C>>>0,q||Fe(R,_,C,4),t.write(R,_,C,$,23,4),C+4}d.prototype.writeFloatLE=function(_,C,$){return ze(this,_,C,!0,$)},d.prototype.writeFloatBE=function(_,C,$){return ze(this,_,C,!1,$)};function ut(R,_,C,$,q){return _=+_,C=C>>>0,q||Fe(R,_,C,8),t.write(R,_,C,$,52,8),C+8}d.prototype.writeDoubleLE=function(_,C,$){return ut(this,_,C,!0,$)},d.prototype.writeDoubleBE=function(_,C,$){return ut(this,_,C,!1,$)},d.prototype.copy=function(_,C,$,q){if(!d.isBuffer(_))throw new TypeError("argument should be a Buffer");if($||($=0),!q&&q!==0&&(q=this.length),C>=_.length&&(C=_.length),C||(C=0),q>0&&q<$&&(q=$),q===$||_.length===0||this.length===0)return 0;if(C<0)throw new RangeError("targetStart out of bounds");if($<0||$>=this.length)throw new RangeError("Index out of range");if(q<0)throw new RangeError("sourceEnd out of bounds");q>this.length&&(q=this.length),_.length-C<q-$&&(q=_.length-C+$);const J=q-$;return this===_&&typeof r.prototype.copyWithin=="function"?this.copyWithin(C,$,q):r.prototype.set.call(_,this.subarray($,q),C),J},d.prototype.fill=function(_,C,$,q){if(typeof _=="string"){if(typeof C=="string"?(q=C,C=0,$=this.length):typeof $=="string"&&(q=$,$=this.length),q!==void 0&&typeof q!="string")throw new TypeError("encoding must be a string");if(typeof q=="string"&&!d.isEncoding(q))throw new TypeError("Unknown encoding: "+q);if(_.length===1){const ne=_.charCodeAt(0);(q==="utf8"&&ne<128||q==="latin1")&&(_=ne)}}else typeof _=="number"?_=_&255:typeof _=="boolean"&&(_=Number(_));if(C<0||this.length<C||this.length<$)throw new RangeError("Out of range index");if($<=C)return this;C=C>>>0,$=$===void 0?this.length:$>>>0,_||(_=0);let J;if(typeof _=="number")for(J=C;J<$;++J)this[J]=_;else{const ne=d.isBuffer(_)?_:d.from(_,q),Oe=ne.length;if(Oe===0)throw new TypeError('The value "'+_+'" is invalid for argument "value"');for(J=0;J<$-C;++J)this[J+C]=ne[J%Oe]}return this};const ot={};function We(R,_,C){ot[R]=class extends C{constructor(){super(),Object.defineProperty(this,"message",{value:_.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${R}]`,this.stack,delete this.name}get code(){return R}set code(q){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:q,writable:!0})}toString(){return`${this.name} [${R}]: ${this.message}`}}}We("ERR_BUFFER_OUT_OF_BOUNDS",function(R){return R?`${R} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),We("ERR_INVALID_ARG_TYPE",function(R,_){return`The "${R}" argument must be of type number. Received type ${typeof _}`},TypeError),We("ERR_OUT_OF_RANGE",function(R,_,C){let $=`The value of "${R}" is out of range.`,q=C;return Number.isInteger(C)&&Math.abs(C)>2**32?q=Bi(String(C)):typeof C=="bigint"&&(q=String(C),(C>BigInt(2)**BigInt(32)||C<-(BigInt(2)**BigInt(32)))&&(q=Bi(q)),q+="n"),$+=` It must be ${_}. Received ${q}`,$},RangeError);function Bi(R){let _="",C=R.length;const $=R[0]==="-"?1:0;for(;C>=$+4;C-=3)_=`_${R.slice(C-3,C)}${_}`;return`${R.slice(0,C)}${_}`}function gi(R,_,C){kt(_,"offset"),(R[_]===void 0||R[_+C]===void 0)&&gt(_,R.length-(C+1))}function Ui(R,_,C,$,q,J){if(R>C||R<_){const ne=typeof _=="bigint"?"n":"";let Oe;throw _===0||_===BigInt(0)?Oe=`>= 0${ne} and < 2${ne} ** ${(J+1)*8}${ne}`:Oe=`>= -(2${ne} ** ${(J+1)*8-1}${ne}) and < 2 ** ${(J+1)*8-1}${ne}`,new ot.ERR_OUT_OF_RANGE("value",Oe,R)}gi($,q,J)}function kt(R,_){if(typeof R!="number")throw new ot.ERR_INVALID_ARG_TYPE(_,"number",R)}function gt(R,_,C){throw Math.floor(R)!==R?(kt(R,C),new ot.ERR_OUT_OF_RANGE("offset","an integer",R)):_<0?new ot.ERR_BUFFER_OUT_OF_BOUNDS:new ot.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${_}`,R)}const Dn=/[^+/0-9A-Za-z-_]/g;function xn(R){if(R=R.split("=")[0],R=R.trim().replace(Dn,""),R.length<2)return"";for(;R.length%4!==0;)R=R+"=";return R}function an(R,_){_=_||1/0;let C;const $=R.length;let q=null;const J=[];for(let ne=0;ne<$;++ne){if(C=R.charCodeAt(ne),C>55295&&C<57344){if(!q){if(C>56319){(_-=3)>-1&&J.push(239,191,189);continue}else if(ne+1===$){(_-=3)>-1&&J.push(239,191,189);continue}q=C;continue}if(C<56320){(_-=3)>-1&&J.push(239,191,189),q=C;continue}C=(q-55296<<10|C-56320)+65536}else q&&(_-=3)>-1&&J.push(239,191,189);if(q=null,C<128){if((_-=1)<0)break;J.push(C)}else if(C<2048){if((_-=2)<0)break;J.push(C>>6|192,C&63|128)}else if(C<65536){if((_-=3)<0)break;J.push(C>>12|224,C>>6&63|128,C&63|128)}else if(C<1114112){if((_-=4)<0)break;J.push(C>>18|240,C>>12&63|128,C>>6&63|128,C&63|128)}else throw new Error("Invalid code point")}return J}function Hi(R){const _=[];for(let C=0;C<R.length;++C)_.push(R.charCodeAt(C)&255);return _}function Kt(R,_){let C,$,q;const J=[];for(let ne=0;ne<R.length&&!((_-=2)<0);++ne)C=R.charCodeAt(ne),$=C>>8,q=C%256,J.push(q),J.push($);return J}function on(R){return e.toByteArray(xn(R))}function qt(R,_,C,$){let q;for(q=0;q<$&&!(q+C>=_.length||q>=R.length);++q)_[q+C]=R[q];return q}function Ct(R,_){return R instanceof _||R!=null&&R.constructor!=null&&R.constructor.name!=null&&R.constructor.name===_.name}function Wt(R){return R!==R}const ri=function(){const R="0123456789abcdef",_=new Array(256);for(let C=0;C<16;++C){const $=C*16;for(let q=0;q<16;++q)_[$+q]=R[C]+R[q]}return _}();function It(R){return typeof BigInt>"u"?Rt:R}function Rt(){throw new Error("BigInt not supported")}})(dy);const YA=dy.Buffer,XA=In("peertube:player:segment-validator"),QA=10;class JA{constructor(e){Ke(this,"destroyed",!1),Ke(this,"segmentJSONPromise"),this.options=e}async validate(e,t,i,n=1){if(this.destroyed)return!1;this.loadSha256SegmentsPromiseIfNeeded();const r=gT(e).split("/").pop(),o=(await this.segmentJSONPromise)[r];if(!o&&n>QA)return Ve.clientError(`Unknown segment name ${r} in segment validator`),!1;if(!o)return Ve.info(`Refetching sha segments for ${r}`),await MA(500),this.loadSha256SegmentsPromise(),this.validate(e,t,i,n+1);let u,h="";if(typeof o=="string"?u=o:(h=t.start+"-"+t.end,u=o[h]),u===void 0)return Ve.clientError(`Unknown segment name ${r}/${h} in segment validator`),!1;XA(`Validating ${r}`+(h?` range ${h}`:""));const p=await this.sha256Hex(i);if(p!==u)return Ve.clientError(`Hashes does not correspond for segment ${r}/${h} (expected: ${u} instead of ${p})`),!0}destroy(){this.destroyed=!0}loadSha256SegmentsPromiseIfNeeded(){this.segmentJSONPromise||this.loadSha256SegmentsPromise()}loadSha256SegmentsPromise(){this.segmentJSONPromise=this.fetchSha256Segments()}fetchSha256Segments(){let e={};return Lc(this.options.serverUrl,this.options.segmentsSha256Url)&&(this.options.requiresPassword?e={"x-peertube-video-password":this.options.videoPassword()}:this.options.requiresUserAuth&&(e={Authorization:this.options.authorizationHeader()})),fetch(this.options.segmentsSha256Url,{headers:e}).then(t=>t.json()).catch(t=>(Ve.clientError("Cannot get sha256 segments",t),{}))}async sha256Hex(e){if(!e)return;if(window.crypto.subtle)return window.crypto.subtle.digest("SHA-256",e).then(i=>this.bufferToHex(i));const t=(await Av(()=>import("./index-L-Yzz1Le-W-5F4tt4.js"),__vite__mapDeps([0,1,2,3])).then(i=>i.i)).default;return new t.sha256().update(YA.from(e)).digest("hex")}bufferToHex(e){if(!e)return"";let t="";const i="0123456789abcdef";return new Uint8Array(e).forEach(r=>{t+=i[r>>4]+i[r&15]}),t}}const ZA=In("peertube:player:hls");class eL{constructor(e){this.options=e}async getPluginOptions(){const e=this.options.hls.segmentsSha256Url;e||Ve.info("No segmentsSha256Url found. Disabling P2P & redundancy.");const t=e?new BA(this.options.hls.redundancyBaseUrls):null,i=e?new JA({segmentsSha256Url:e,authorizationHeader:this.options.authorizationHeader,requiresUserAuth:this.options.requiresUserAuth,serverUrl:this.options.serverUrl,requiresPassword:this.options.requiresPassword,videoPassword:this.options.videoPassword}):null,n=await this.options.pluginsManager.runHook("filter:internal.player.p2p-media-loader.options.result",this.getP2PMediaLoaderOptions({redundancyUrlManager:t,segmentValidator:i})),r={requiresUserAuth:this.options.requiresUserAuth,videoFileToken:this.options.videoFileToken,p2pEnabled:e&&this.options.p2pEnabled,redundancyUrlManager:t,type:"application/x-mpegURL",src:this.options.hls.playlistUrl,segmentValidator:i},o={hlsjsConfig:this.getHLSJSOptions(n),levelLabelHandler:(u,h)=>{const p=Math.min(u.height||0,u.width||0),d=this.options.hls.videoFiles.find(T=>T.resolution.id===p),g=ST({resolution:p,height:d?.height??u.height,width:d?.width??u.width});return h.localize(qp(g,d?.fps??u.frameRate))}};return ZA("Creating HLS player options",{hlsjs:o,p2pMediaLoader:r,loaderOptions:n}),{p2pMediaLoader:r,hlsjs:o}}getP2PMediaLoaderOptions(e){var t;const{redundancyUrlManager:i,segmentValidator:n}=e;let r=!1;(((t=navigator?.connection)==null?void 0:t.type)==="cellular"||is.getItem("peertube-videojs-p2p-consume-only")==="true")&&(Ve.info("We are on a cellular connection: disabling seeding."),r=!0);const o=this.options.hls.trackerAnnounce.filter(p=>p.startsWith("ws")),u=this.options.isLive?this.getP2PMediaLoaderLiveOptions():this.getP2PMediaLoaderVODOptions();return{loader:{announceTrackers:o,rtcConfig:CT(this.options.stunServers),httpRequestSetup:(p,d,g,T)=>{const{requiresUserAuth:b,requiresPassword:E}=this.options,w=i?i.buildUrl(p):p,A=new Headers;return T&&A.set("Range",`bytes=${T.start}-${T.end??""}`),Lc(this.options.serverUrl,w)&&(E?A.set("x-peertube-video-password",this.options.videoPassword()):b&&A.set("Authorization",this.options.authorizationHeader())),Promise.resolve(new Request(w,{headers:A,signal:g}))},validateP2PSegment:n?n.validate.bind(n):null,validateHTTPSegment:n?n.validate.bind(n):null,isP2PDisabled:!this.options.p2pEnabled,isP2PUploadDisabled:r,swarmId:this.options.hls.playlistUrl,...u}}}getP2PMediaLoaderLiveOptions(){const e={highDemandTimeWindow:4};switch(this.options.liveOptions.latencyMode){case ma.SMALL_LATENCY:return{...e,isP2PDisabled:!0};case ma.HIGH_LATENCY:return e;default:return e}}getP2PMediaLoaderVODOptions(){return{highDemandTimeWindow:15,segmentMemoryStorageLimit:1024}}getHLSJSOptions(e){const t=this.options.isLive?this.getHLSLiveOptions():this.getHLSVODOptions(),i={capLevelToPlayerSize:!0,autoStartLoad:!1,p2pMediaLoaderOptions:e.loader,xhrSetup:(r,o)=>{const{requiresUserAuth:u,requiresPassword:h}=this.options;Lc(this.options.serverUrl,o)&&(h?r.setRequestHeader("x-peertube-video-password",this.options.videoPassword()):u&&r.setRequestHeader("Authorization",this.options.authorizationHeader()))},...t},n=cg();return n?{...i,abrEwmaDefaultEstimate:n*8,backBufferLength:90,startLevel:-1,testBandwidth:!1,debug:!1,enableWorker:!1}:i}getHLSLiveOptions(){switch(this.options.liveOptions.latencyMode){case ma.SMALL_LATENCY:return{liveSyncDurationCount:2};case ma.HIGH_LATENCY:return{liveSyncDurationCount:10};default:return{liveSyncDurationCount:5}}}getHLSVODOptions(){return{liveSyncDurationCount:5}}}class tL{constructor(e){this.options=e}getPluginOptions(){var e;return{videoFileToken:this.options.videoFileToken,videoFiles:this.options.webVideo.videoFiles.length!==0?this.options.webVideo.videoFiles:((e=this.options.hls)==null?void 0:e.videoFiles)||[]}}}const py=class Is{static getServerTranslations(e,t){const i=Is.getLocalePath(e,t);return i?fetch(i+"/server.json").then(n=>n.json()).catch(n=>{Ve.error("Cannot get server translations",n)}):Promise.resolve(void 0)}static loadLocaleInVideoJS(e,t,i){const n=Is.getLocalePath(e,t);if(!n)return Promise.resolve(void 0);let r;Is.videojsLocaleCache[n]?r=Promise.resolve(Is.videojsLocaleCache[n]):r=fetch(n+"/player.json").then(u=>u.json()).then(u=>(Is.videojsLocaleCache[n]=u,u)).catch(u=>{Ve.error("Cannot get player translations",u)});const o=ao(t);return r.then(u=>i.addLanguage(_T(o),u))}static getLocalePath(e,t){const i=ao(t);if(!(!bT(i)||Kp(i)))return e+"/client/locales/"+i}};Ke(py,"videojsLocaleCache",{});let iL=py;X.getComponent("PlaybackRateMenuButton").prototype.controlText_="Speed";const gy=X.getComponent("CaptionsButton");gy.prototype.controlText_="Subtitles/CC";gy.prototype.label_=" ";const Mp=X.getComponent("PlayProgressBar");Mp.prototype.options_.children.includes("timeTooltip")!==!0&&Mp.prototype.options_.children.push("timeTooltip");class nL{constructor(e){Ke(this,"pluginsManager"),Ke(this,"videojsDecodeErrors",0),Ke(this,"player"),Ke(this,"currentLoadOptions"),this.options=e,this.pluginsManager=e.pluginsManager}unload(){this.player&&(this.disposeDynamicPluginsIfNeeded(),this.player.reset())}async load(e){this.currentLoadOptions=e,this.setPoster(""),this.disposeDynamicPluginsIfNeeded(),await this.buildPlayerIfNeeded(),this.currentLoadOptions.mode==="p2p-media-loader"?await this.loadP2PMediaLoader():this.loadWebVideo(),this.loadDynamicPlugins(),this.options.controlBar===!1?this.player.controlBar.hide():this.player.controlBar.show(),this.player.autoplay(this.getAutoPlayValue(this.currentLoadOptions.autoplay)),this.player.autoplay()||this.setPoster(e.poster),this.player.trigger("video-change")}getPlayer(){return this.player}destroy(){this.player&&this.player.dispose()}setPoster(e){var t;if(!this.player){this.options.playerElement().poster=e;return}(t=this.player)==null||t.poster(e),this.options.playerElement().poster=""}enable(){this.player&&(this.player.el().style.pointerEvents="auto")}disable(){this.player&&(this.player.isFullscreen()&&this.player.exitFullscreen(),this.player.hasStarted(!1),this.player.removeClass("vjs-has-autoplay"),this.player.bigPlayButton.hide(),this.player.el().style.pointerEvents="none")}setCurrentTime(e){if(this.player.paused()){this.currentLoadOptions.startTime=e,this.player.play();return}this.player.currentTime(e),this.player.userActive(!0)}async loadP2PMediaLoader(){const e=new eL({...$l(this.options,["pluginsManager","serverUrl","authorizationHeader","stunServers"]),...$l(this.currentLoadOptions,["videoPassword","requiresUserAuth","videoFileToken","requiresPassword","isLive","p2pEnabled","liveOptions","hls"])}),{hlsjs:t,p2pMediaLoader:i}=await e.getPluginOptions();this.player.hlsjs(t),this.player.p2pMediaLoader(i)}loadWebVideo(){const e=new tL($l(this.currentLoadOptions,["videoFileToken","webVideo","hls"]));this.player.webVideo(e.getPluginOptions())}async buildPlayerIfNeeded(){if(this.player)return;await iL.loadLocaleInVideoJS(this.options.serverUrl,this.options.language,X);const e=await this.pluginsManager.runHook("filter:internal.player.videojs.options.result",this.getVideojsOptions());this.player=X(this.options.playerElement(),e),this.player.ready(()=>{isNaN(+this.options.playbackRate)||this.player.playbackRate(+this.options.playbackRate);let t=!1;const i=()=>{t||(t=!0,this.currentLoadOptions.mode==="p2p-media-loader"?this.tryToRecoverHLSError(this.player.error()):this.maybeFallbackToWebVideo())};this.player.on("video-change",()=>t=!1),this.player.on("error",()=>i()),this.player.on("network-info",(n,r)=>{r.source!=="p2p-media-loader"||isNaN(r.bandwidthEstimate)||ug(r.bandwidthEstimate)}),this.player.contextMenu(this.getContextMenuOptions()),this.displayNotificationWhenOffline()})}disposeDynamicPluginsIfNeeded(){this.player&&(this.player.usingPlugin("peertubeMobile")&&this.player.peertubeMobile().dispose(),this.player.usingPlugin("peerTubeHotkeysPlugin")&&this.player.peerTubeHotkeysPlugin().dispose(),this.player.usingPlugin("playlist")&&this.player.playlist().dispose(),this.player.usingPlugin("bezels")&&this.player.bezels().dispose(),this.player.usingPlugin("upnext")&&this.player.upnext().dispose(),this.player.usingPlugin("stats")&&this.player.stats().dispose(),this.player.usingPlugin("storyboard")&&this.player.storyboard().dispose(),this.player.usingPlugin("chapters")&&this.player.chapters().dispose(),this.player.usingPlugin("peertubeDock")&&this.player.peertubeDock().dispose(),this.player.usingPlugin("p2pMediaLoader")&&this.player.p2pMediaLoader().dispose(),this.player.usingPlugin("hlsjs")&&this.player.hlsjs().dispose(),this.player.usingPlugin("webVideo")&&this.player.webVideo().dispose())}loadDynamicPlugins(){oo()&&this.player.peertubeMobile(),this.player.bezels(),this.player.stats({videoUUID:this.currentLoadOptions.videoUUID,videoIsLive:this.currentLoadOptions.isLive,mode:this.currentLoadOptions.mode,p2pEnabled:this.currentLoadOptions.p2pEnabled}),this.options.enableHotkeys===!0&&this.player.peerTubeHotkeysPlugin({isLive:this.currentLoadOptions.isLive}),this.currentLoadOptions.playlist&&this.player.playlist(this.currentLoadOptions.playlist),this.currentLoadOptions.upnext&&this.player.upnext({timeout:this.currentLoadOptions.upnext.timeout,getTitle:()=>this.currentLoadOptions.nextVideo.getVideoTitle(),next:()=>this.currentLoadOptions.nextVideo.handler(),isDisplayed:()=>this.currentLoadOptions.nextVideo.enabled&&this.currentLoadOptions.upnext.isEnabled(),isSuspended:()=>this.currentLoadOptions.upnext.isSuspended(this.player)}),this.currentLoadOptions.storyboard&&this.player.storyboard(this.currentLoadOptions.storyboard),this.currentLoadOptions.videoChapters&&this.player.chapters({chapters:this.currentLoadOptions.videoChapters}),this.currentLoadOptions.dock&&this.player.peertubeDock(this.currentLoadOptions.dock)}async tryToRecoverHLSError(e){if(e.code===MediaError.MEDIA_ERR_DECODE){if(this.videojsDecodeErrors===0&&this.options.errorNotifier(this.player.localize("The video failed to play, will try to fast forward.")),this.videojsDecodeErrors===20){this.maybeFallbackToWebVideo();return}Ve.info("Fast forwarding HLS to recover from an error.",{err:e,videoShortUUID:this.currentLoadOptions.videoShortUUID,currentTime:this.player.currentTime(),resolution:this.player.videoHeight()}),this.videojsDecodeErrors++,await this.load({...this.currentLoadOptions,mode:"p2p-media-loader",startTime:this.player.currentTime()+2,autoplay:!0})}else this.maybeFallbackToWebVideo()}async maybeFallbackToWebVideo(){if(this.currentLoadOptions.mode==="web-video"){this.player.peertube().displayFatalError();return}Ve.info("Fallback to web-video."),await this.load({...this.currentLoadOptions,mode:"web-video",startTime:this.player.currentTime(),autoplay:!0})}getVideojsOptions(){const e={preloadTextTracks:!1,nativeTextTracks:!1},t={peertube:{hasAutoplay:()=>this.getAutoPlayValue(this.currentLoadOptions.autoplay),videoViewUrl:()=>this.currentLoadOptions.videoViewUrl,videoViewIntervalMs:this.options.videoViewIntervalMs,authorizationHeader:this.options.authorizationHeader,videoDuration:()=>this.currentLoadOptions.duration,startTime:()=>this.currentLoadOptions.startTime,stopTime:()=>this.currentLoadOptions.stopTime,videoCaptions:()=>this.currentLoadOptions.videoCaptions,isLive:()=>this.currentLoadOptions.isLive,videoUUID:()=>this.currentLoadOptions.videoUUID,subtitle:()=>this.currentLoadOptions.subtitle,videoRatio:()=>this.currentLoadOptions.videoRatio,poster:()=>this.currentLoadOptions.poster,autoPlayerRatio:this.options.autoPlayerRatio},metrics:{mode:()=>this.currentLoadOptions.mode,metricsUrl:()=>this.options.metricsUrl,metricsInterval:()=>this.options.metricsInterval,videoUUID:()=>this.currentLoadOptions.videoUUID}},i=new NA({...this.options,videoShortUUID:()=>this.currentLoadOptions.videoShortUUID,p2pEnabled:()=>this.currentLoadOptions.p2pEnabled,nextVideo:()=>this.currentLoadOptions.nextVideo,previousVideo:()=>this.currentLoadOptions.previousVideo});return{html5:e,textTrackSettings:!1,controls:this.options.controls!==void 0?this.options.controls:!0,loop:this.options.loop!==void 0?this.options.loop:!1,muted:this.options.muted!==void 0?this.options.muted:void 0,autoplay:this.getAutoPlayValue(this.currentLoadOptions.autoplay),poster:this.currentLoadOptions.poster,inactivityTimeout:this.options.inactivityTimeout,playbackRates:[.25,.5,.75,1,1.25,1.5,1.75,2],plugins:t,controlBar:{children:i.getChildrenOptions()},language:this.options.language&&!Kp(this.options.language)?this.options.language:void 0}}getAutoPlayValue(e){return e!==!0?!1:this.currentLoadOptions.forceAutoplay?"any":"play"}displayNotificationWhenOffline(){const e=document.createElement("div");e.classList.add("vjs-peertube-offline-notification"),e.innerText=this.player.localize("You seem to be offline and the video may not work");let t=!1;const i=()=>{t&&(this.player.el().removeChild(e),t=!1,Ve.info("The browser is online"))},n=()=>{t||(this.player.el().appendChild(e),t=!0,Ve.info("The browser is offline"))};window.addEventListener("online",i),window.addEventListener("offline",n),this.player.on("dispose",()=>{window.removeEventListener("online",i),window.removeEventListener("offline",n)})}getContextMenuOptions(){return{content:()=>{const t=this,i=this.player,n=t.currentLoadOptions.videoShortUUID,r=i.options_.loop,o=[{icon:"repeat",label:i.localize("Play in loop")+(r?'<span class="vjs-icon-tick-white"></span>':""),listener:function(){i.options_.loop=!r}},{label:i.localize("Copy the video URL"),listener:function(){Vu(qu({shortUUID:n}),i.el())}},{label:i.localize("Copy the video URL at the current time"),listener:function(){const u=qu({shortUUID:n});Vu(jp({url:u,startTime:i.currentTime()}),i.el())}},{icon:"code",label:i.localize("Copy embed code"),listener:()=>{Vu(FA({embedUrl:t.currentLoadOptions.embedUrl,embedTitle:t.currentLoadOptions.embedTitle}),i.el())}}];return o.push({icon:"info",label:i.localize("Stats for nerds"),listener:()=>{i.stats().show()}}),o.map(u=>({...u,label:`<span class="vjs-icon-${u.icon||"link-2"}"></span>`+u.label}))}}}}const mL=Object.freeze(Object.defineProperty({__proto__:null,PeerTubePlayer:nL,cleanupVideoWatch:ib,getAverageBandwidthInStore:cg,getPlayerSessionId:gg,getStoredLastSubtitle:hg,getStoredMute:sg,getStoredPreferredSubtitle:fg,getStoredTheater:rg,getStoredVideoWatchHistory:xc,getStoredVolume:ng,saveAverageBandwidth:ug,saveLastSubtitle:Zu,saveMuteInStore:og,savePreferredSubtitle:dg,saveTheaterInStore:lg,saveVideoWatchHistory:pg,saveVolumeInStore:ag,videojs:X},Symbol.toStringTag,{value:"Module"}));export{Fp as g,mL as p};
