const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BDeSbJJz-CfH3UO9z.js","assets/embed-C3S6myBQ.js","assets/jschannel-Cj5tj0oB.js","assets/embed-C5fS-1lQ.css"])))=>i.map(i=>d[i]);
import{_ as Km}from"./embed-C3S6myBQ.js";const qc=globalThis||void 0||self;var qm=Object.defineProperty,Wm=(s,e,t)=>e in s?qm(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ue=(s,e,t)=>Wm(s,typeof e!="symbol"?e+"":e,t),ha=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof qc<"u"?qc:typeof self<"u"?self:{};function sf(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function zm(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 wo,Wc;function Pa(){if(Wc)return wo;Wc=1;var s;return typeof window<"u"?s=window:typeof ha<"u"?s=ha:typeof self<"u"?s=self:s={},wo=s,wo}const Ym={},Xm=Object.freeze(Object.defineProperty({__proto__:null,default:Ym},Symbol.toStringTag,{value:"Module"})),Qm=zm(Xm);var Lo,zc;function rf(){if(zc)return Lo;zc=1;var s=typeof ha<"u"?ha:typeof window<"u"?window:{},e=Qm,t;return typeof document<"u"?t=document:(t=s["__GLOBAL_DOCUMENT_CACHE@4"],t||(t=s["__GLOBAL_DOCUMENT_CACHE@4"]=e)),Lo=t,Lo}var Ao={exports:{}},Yc;function af(){return Yc||(Yc=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}(Ao)),Ao.exports}var Sr={exports:{}},Xc;function Jm(){return Xc||(Xc=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 f=String(h),m=i[f.toLowerCase()];if(m)return m;var m=n[f.toLowerCase()];if(m)return m;if(f.length===1)return f.charCodeAt(0)}t.isEventKey=function(p,f){if(p&&typeof p=="object"){var m=p.which||p.keyCode||p.charCode;if(m==null)return!1;if(typeof f=="string"){var T=i[f.toLowerCase()];if(T)return T===m;var T=n[f.toLowerCase()];if(T)return T===m}else if(typeof f=="number")return f===m;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]}(Sr,Sr.exports)),Sr.exports}var ko={exports:{}},Qc;function Zm(){return Qc||(Qc=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}(ko)),ko.exports}var Io={exports:{}},Ro={exports:{}},Jc;function pu(){return Jc||(Jc=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}(Ro)),Ro.exports}var Zc;function ey(){return Zc||(Zc=1,function(s){var e=pu();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}(Io)),Io.exports}var Po,eh;function ty(){if(eh)return Po;eh=1,Po=s;function s(e,t){var i,n=null;try{i=JSON.parse(e,t)}catch(r){n=r}return[n,i]}return Po}var Cr={exports:{}},Do,th;function iy(){if(th)return Do;th=1,Do=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 Do}var xo,ih;function ny(){if(ih)return xo;ih=1;var s=Pa(),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 f=t(u.headers&&u.headers["content-type"]);try{p=new TextDecoder(f).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 xo=e,xo}var nh;function sy(){if(nh)return Cr.exports;nh=1;var s=Pa(),e=af(),t=iy();u.httpHandler=ny();/**
 * @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 _={};return T&&T.trim().split(`
`).forEach(function(b){var w=b.indexOf(":"),L=b.slice(0,w).trim().toLowerCase(),A=b.slice(w+1).trim();typeof _[L]>"u"?_[L]=A:Array.isArray(_[L])?_[L].push(A):_[L]=[_[L],A]}),_};Cr.exports=u,Cr.exports.default=u,u.XMLHttpRequest=s.XMLHttpRequest||f,u.XDomainRequest="withCredentials"in new u.XMLHttpRequest?u.XMLHttpRequest:s.XDomainRequest,n(["get","put","post","patch","head","delete"],function(m){u[m==="delete"?"del":m]=function(T,_,b){return _=o(T,_,b),_.method=m.toUpperCase(),h(_)}});function n(m,T){for(var _=0;_<m.length;_++)T(m[_])}function r(m){for(var T in m)if(m.hasOwnProperty(T))return!1;return!0}function o(m,T,_){var b=m;return t(T)?(_=T,typeof m=="string"&&(b={uri:m})):b=e({},T,{uri:m}),b.callback=_,b}function u(m,T,_){return T=o(m,T,_),h(T)}function h(m){if(typeof m.callback>"u")throw new Error("callback argument missing");var T=!1,_=function(oe,le,he){T||(T=!0,m.callback(oe,le,he))};function b(){P.readyState===4&&setTimeout(A,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 L(Z){return clearTimeout(K),Z instanceof Error||(Z=new Error(""+(Z||"Unknown XMLHttpRequest Error"))),Z.statusCode=0,_(Z,ae)}function A(){if(!M){var Z;clearTimeout(K),m.useXDR&&P.status===void 0?Z=200:Z=P.status===1223?204:P.status;var oe=ae,le=null;return Z!==0?(oe={body:w(),statusCode:Z,method:N,headers:{},url:k,rawRequest:P},P.getAllResponseHeaders&&(oe.headers=i(P.getAllResponseHeaders()))):le=new Error("Internal XMLHttpRequest Error"),_(le,oe,oe.body)}}var P=m.xhr||null;P||(m.cors||m.useXDR?P=new u.XDomainRequest:P=new u.XMLHttpRequest);var O,M,k=P.url=m.uri||m.url,N=P.method=m.method||"GET",H=m.body||m.data,G=P.headers=m.headers||{},B=!!m.sync,D=!1,K,ae={body:void 0,headers:{},statusCode:0,method:N,url:k,rawRequest:P};if("json"in m&&m.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(m.json===!0?H:m.json))),P.onreadystatechange=b,P.onload=A,P.onerror=L,P.onprogress=function(){},P.onabort=function(){M=!0},P.ontimeout=L,P.open(N,k,!B,m.username,m.password),B||(P.withCredentials=!!m.withCredentials),!B&&m.timeout>0&&(K=setTimeout(function(){if(!M){M=!0,P.abort("timeout");var Z=new Error("XMLHttpRequest timeout");Z.code="ETIMEDOUT",L(Z)}},m.timeout)),P.setRequestHeader)for(O in G)G.hasOwnProperty(O)&&P.setRequestHeader(O,G[O]);else if(m.headers&&!r(m.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in m&&(P.responseType=m.responseType),"beforeSend"in m&&typeof m.beforeSend=="function"&&m.beforeSend(P),P.send(H||null),P}function p(m){try{if(m.responseType==="document")return m.responseXML;var T=m.responseXML&&m.responseXML.documentElement.nodeName==="parsererror";if(m.responseType===""&&!T)return m.responseXML}catch{}return null}function f(){}return Cr.exports}var Mo={exports:{}},Oo,sh;function ry(){if(sh)return Oo;sh=1;var s=rf(),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(ae,Z,oe,le){return(ae|0)*3600+(Z|0)*60+(oe|0)+(le|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 ae=0;ae<K.length;++ae)if(D===K[ae]){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,ae){var Z=ae?B.split(ae):[B];for(var oe in Z)if(typeof Z[oe]=="string"){var le=Z[oe].split(K);if(le.length===2){var he=le[0].trim(),pe=le[1].trim();D(he,pe)}}}function o(B,D,K){var ae=B;function Z(){var he=i(B);if(he===null)throw new t(t.Errors.BadTimeStamp,"Malformed timestamp: "+ae);return B=B.replace(/^[^\sa-zA-Z-]+/,""),he}function oe(he,pe){var ge=new n;r(he,function(ee,Q){switch(ee){case"region":for(var ye=K.length-1;ye>=0;ye--)if(K[ye].id===Q){ge.set(ee,K[ye].region);break}break;case"vertical":ge.alt(ee,Q,["rl","lr"]);break;case"line":var re=Q.split(","),ie=re[0];ge.integer(ee,ie),ge.percent(ee,ie)&&ge.set("snapToLines",!1),ge.alt(ee,ie,["auto"]),re.length===2&&ge.alt("lineAlign",re[1],["start","center","end"]);break;case"position":re=Q.split(","),ge.percent(ee,re[0]),re.length===2&&ge.alt("positionAlign",re[1],["start","center","end"]);break;case"size":ge.percent(ee,Q);break;case"align":ge.alt(ee,Q,["start","center","end","left","right"]);break}},/:/,/\s/),pe.region=ge.get("region",null),pe.vertical=ge.get("vertical","");try{pe.line=ge.get("line","auto")}catch{}pe.lineAlign=ge.get("lineAlign","start"),pe.snapToLines=ge.get("snapToLines",!0),pe.size=ge.get("size",100);try{pe.align=ge.get("align","center")}catch{pe.align=ge.get("align","middle")}try{pe.position=ge.get("position","auto")}catch{pe.position=ge.get("position",{start:0,left:0,center:50,middle:50,end:100,right:100},pe.align)}pe.positionAlign=ge.get("positionAlign",{start:"start",left:"start",center:"center",middle:"center",end:"end",right:"end"},pe.align)}function le(){B=B.replace(/^\s+/,"")}if(le(),D.startTime=Z(),le(),B.substr(0,3)!=="-->")throw new t(t.Errors.BadTimeStamp,"Malformed time stamp (time stamps must be separated by '-->'): "+ae);B=B.substr(3),le(),D.endTime=Z(),le(),oe(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)"},f={v:"title",lang:"lang"},m={rt:"ruby"};function T(B,D){function K(){if(!D)return null;function ie(Te){return D=D.substr(Te.length),Te}var be=D.match(/^([^<]*)(<[^>]*>?)?/);return ie(be[1]?be[1]:be[2])}function ae(ie){return u.innerHTML=ie,ie=u.textContent,u.textContent="",ie}function Z(ie,be){return!m[be.localName]||m[be.localName]===ie.localName}function oe(ie,be){var Te=h[ie];if(!Te)return null;var xe=B.document.createElement(Te),Me=f[ie];return Me&&be&&(xe[Me]=be.trim()),xe}for(var le=B.document.createElement("div"),he=le,pe,ge=[];(pe=K())!==null;){if(pe[0]==="<"){if(pe[1]==="/"){ge.length&&ge[ge.length-1]===pe.substr(2).replace(">","")&&(ge.pop(),he=he.parentNode);continue}var ee=i(pe.substr(1,pe.length-2)),Q;if(ee){Q=B.document.createProcessingInstruction("timestamp",ee),he.appendChild(Q);continue}var ye=pe.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);if(!ye||(Q=oe(ye[1],ye[3]),!Q)||!Z(he,Q))continue;if(ye[2]){var re=ye[2].split(".");re.forEach(function(ie){var be=/^bg_/.test(ie),Te=be?ie.slice(3):ie;if(p.hasOwnProperty(Te)){var xe=be?"background-color":"color",Me=p[Te];Q.style[xe]=Me}}),Q.className=re.join(" ")}ge.push(ye[1]),he.appendChild(Q),he=Q;continue}he.appendChild(B.document.createTextNode(ae(pe)))}return le}var _=[[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 b(B){for(var D=0;D<_.length;D++){var K=_[D];if(B>=K[0]&&B<=K[1])return!0}return!1}function w(B){var D=[],K="",ae;if(!B||!B.childNodes)return"ltr";function Z(he,pe){for(var ge=pe.childNodes.length-1;ge>=0;ge--)he.push(pe.childNodes[ge])}function oe(he){if(!he||!he.length)return null;var pe=he.pop(),ge=pe.textContent||pe.innerText;if(ge){var ee=ge.match(/^.*(\n|\r)/);return ee?(he.length=0,ee[0]):ge}if(pe.tagName==="ruby")return oe(he);if(pe.childNodes)return Z(he,pe),oe(he)}for(Z(D,B);K=oe(D);)for(var le=0;le<K.length;le++)if(ae=K.charCodeAt(le),b(ae))return"rtl";return"ltr"}function L(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,ae=0,Z=0;Z<K.length&&K[Z]!==D;Z++)K[Z].mode==="showing"&&ae++;return++ae*-1}function A(){}A.prototype.applyStyles=function(B,D){D=D||this.div;for(var K in B)B.hasOwnProperty(K)&&(D.style[K]=B[K])},A.prototype.formatStyle=function(B,D){return B===0?0:B+D};function P(B,D,K){A.call(this),this.cue=D,this.cueDiv=T(B,D.text);var ae={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(ae,this.cueDiv),this.div=B.document.createElement("div"),ae={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(ae),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(oe){this.applyStyles({top:this.formatStyle(oe.top,"px"),bottom:this.formatStyle(oe.bottom,"px"),left:this.formatStyle(oe.left,"px"),right:this.formatStyle(oe.right,"px"),height:this.formatStyle(oe.height,"px"),width:this.formatStyle(oe.width,"px")})}}P.prototype=e(A.prototype),P.prototype.constructor=P;function O(B){var D,K,ae,Z;if(B.div){K=B.div.offsetHeight,ae=B.div.offsetWidth,Z=B.div.offsetTop;var oe=(oe=B.div.childNodes)&&(oe=oe[0])&&oe.getClientRects&&oe.getClientRects();B=B.div.getBoundingClientRect(),D=oe?Math.max(oe[0]&&oe[0].height||0,B.height/oe.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||ae,this.lineHeight=D!==void 0?D:B.lineHeight}O.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}},O.prototype.overlaps=function(B){return this.left<B.right&&this.right>B.left&&this.top<B.bottom&&this.bottom>B.top},O.prototype.overlapsAny=function(B){for(var D=0;D<B.length;D++)if(this.overlaps(B[D]))return!0;return!1},O.prototype.within=function(B){return this.top>=B.top&&this.bottom<=B.bottom&&this.left>=B.left&&this.right<=B.right},O.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}},O.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)),ae=D*K;return ae/(this.height*this.width)},O.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}},O.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,ae=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||ae,height:B.height||D,bottom:B.bottom||ae+(B.height||D),width:B.width||K};return Z};function M(B,D,K,ae){function Z(Te,xe){for(var Me,Pe=new O(Te),je=1,it=0;it<xe.length;it++){for(;Te.overlapsOppositeAxis(K,xe[it])||Te.within(K)&&Te.overlapsAny(ae);)Te.move(xe[it]);if(Te.within(K))return Te;var et=Te.intersectPercentage(K);je>et&&(Me=new O(Te),je=et),Te=new O(Pe)}return Me||Pe}var oe=new O(D),le=D.cue,he=L(le),pe=[];if(le.snapToLines){var ge;switch(le.vertical){case"":pe=["+y","-y"],ge="height";break;case"rl":pe=["+x","-x"],ge="width";break;case"lr":pe=["-x","+x"],ge="width";break}var ee=oe.lineHeight,Q=ee*Math.round(he),ye=K[ge]+ee,re=pe[0];Math.abs(Q)>ye&&(Q=Q<0?-1:1,Q*=Math.ceil(ye/ee)*ee),he<0&&(Q+=le.vertical===""?K.height:K.width,pe=pe.reverse()),oe.move(re,Q)}else{var ie=oe.lineHeight/K.height*100;switch(le.lineAlign){case"center":he-=ie/2;break;case"end":he-=ie;break}switch(le.vertical){case"":D.applyStyles({top:D.formatStyle(he,"%")});break;case"rl":D.applyStyles({left:D.formatStyle(he,"%")});break;case"lr":D.applyStyles({right:D.formatStyle(he,"%")});break}pe=["+y","-x","+x","-y"],oe=new O(D)}var be=Z(oe,pe);D.move(be.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 ae=B.document.createElement("div");ae.style.position="absolute",ae.style.left="0",ae.style.right="0",ae.style.top="0",ae.style.bottom="0",ae.style.margin=G,K.appendChild(ae);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 oe=0;oe<D.length;oe++)ae.appendChild(D[oe].displayState);return}var le=[],he=O.getSimpleBoxPosition(ae),pe=Math.round(he.height*N*100)/100,ge={font:pe+"px "+H};(function(){for(var ee,Q,ye=0;ye<D.length;ye++)Q=D[ye],ee=new P(B,Q,ge),ae.appendChild(ee.div),M(B,ee,he,le),Q.displayState=ee.div,le.push(O.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 ye=ee.substr(0,Q);return ee[Q]==="\r"&&++Q,ee[Q]===`
`&&++Q,D.buffer=ee.substr(Q),ye}function ae(ee){var Q=new n;if(r(ee,function(re,ie){switch(re){case"id":Q.set(re,ie);break;case"width":Q.percent(re,ie);break;case"lines":Q.integer(re,ie);break;case"regionanchor":case"viewportanchor":var be=ie.split(",");if(be.length!==2)break;var Te=new n;if(Te.percent("x",be[0]),Te.percent("y",be[1]),!Te.has("x")||!Te.has("y"))break;Q.set(re+"X",Te.get("x")),Q.set(re+"Y",Te.get("y"));break;case"scroll":Q.alt(re,ie,["up"]);break}},/=/,/\s/),Q.has("id")){var ye=new(D.vttjs.VTTRegion||D.window.VTTRegion);ye.width=Q.get("width",100),ye.lines=Q.get("lines",3),ye.regionAnchorX=Q.get("regionanchorX",0),ye.regionAnchorY=Q.get("regionanchorY",100),ye.viewportAnchorX=Q.get("viewportanchorX",0),ye.viewportAnchorY=Q.get("viewportanchorY",100),ye.scroll=Q.get("scroll",""),D.onregion&&D.onregion(ye),D.regionList.push({id:Q.get("id"),region:ye})}}function Z(ee){var Q=new n;r(ee,function(ye,re){switch(ye){case"MPEGT":Q.integer(ye+"S",re);break;case"LOCA":Q.set(ye+"L",i(re));break}},/[^\d]:/,/,/),D.ontimestampmap&&D.ontimestampmap({MPEGTS:Q.get("MPEGTS"),LOCAL:Q.get("LOCAL")})}function oe(ee){ee.match(/X-TIMESTAMP-MAP/)?r(ee,function(Q,ye){switch(Q){case"X-TIMESTAMP-MAP":Z(ye);break}},/=/):r(ee,function(Q,ye){switch(Q){case"Region":ae(ye);break}},/:/)}try{var le;if(D.state==="INITIAL"){if(!/\r\n|\n/.test(D.buffer))return this;le=K();var he=le.match(/^WEBVTT([ \t].*)?$/);if(!he||!he[0])throw new t(t.Errors.BadSignature);D.state="HEADER"}for(var pe=!1;D.buffer;){if(!/\r\n|\n/.test(D.buffer))return this;switch(pe?pe=!1:le=K(),D.state){case"HEADER":/:/.test(le)?oe(le):le||(D.state="ID");continue;case"NOTE":le||(D.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(le)){D.state="NOTE";break}if(!le)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",le.indexOf("-->")===-1){D.cue.id=le;continue}case"CUE":try{o(le,D.cue,D.regionList)}catch(ee){D.reportOrThrowError(ee),D.cue=null,D.state="BADCUE";continue}D.state="CUETEXT";continue;case"CUETEXT":var ge=le.indexOf("-->")!==-1;if(!le||ge&&(pe=!0)){D.oncue&&D.oncue(D.cue),D.cue=null,D.state="ID";continue}D.cue.text&&(D.cue.text+=`
`),D.cue.text+=le.replace(/\u2028/g,`
`).replace(/u2029/g,`
`);continue;case"BADCUE":le||(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}},Oo=k,Oo}var Fo,rh;function ay(){if(rh)return Fo;rh=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="",f=!1,m=o,T=u,_=h,b=null,w="",L=!0,A="auto",P="start",O="auto",M="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 f},set:function(H){f=!!H}},startTime:{enumerable:!0,get:function(){return m},set:function(H){if(typeof H!="number")throw new TypeError("Start time must be set to a number.");m=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 _},set:function(H){_=""+H,this.hasBeenReset=!0}},region:{enumerable:!0,get:function(){return b},set:function(H){b=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 L},set:function(H){L=!!H,this.hasBeenReset=!0}},line:{enumerable:!0,get:function(){return A},set:function(H){if(typeof H!="number"&&H!==s)throw new SyntaxError("Line: an invalid number or illegal string was specified.");A=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 O},set:function(H){if(H<0||H>100)throw new Error("Position must be between 0 and 100.");O=H,this.hasBeenReset=!0}},positionAlign:{enumerable:!0,get:function(){return M},set:function(H){var G=n(H);G?(M=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)},Fo=r,Fo}var No,ah;function oy(){if(ah)return No;ah=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,f="";Object.defineProperties(this,{width:{enumerable:!0,get:function(){return n},set:function(m){if(!t(m))throw new Error("Width must be between 0 and 100.");n=m}},lines:{enumerable:!0,get:function(){return r},set:function(m){if(typeof m!="number")throw new TypeError("Lines must be set to a number.");r=m}},regionAnchorY:{enumerable:!0,get:function(){return u},set:function(m){if(!t(m))throw new Error("RegionAnchorX must be between 0 and 100.");u=m}},regionAnchorX:{enumerable:!0,get:function(){return o},set:function(m){if(!t(m))throw new Error("RegionAnchorY must be between 0 and 100.");o=m}},viewportAnchorY:{enumerable:!0,get:function(){return p},set:function(m){if(!t(m))throw new Error("ViewportAnchorY must be between 0 and 100.");p=m}},viewportAnchorX:{enumerable:!0,get:function(){return h},set:function(m){if(!t(m))throw new Error("ViewportAnchorX must be between 0 and 100.");h=m}},scroll:{enumerable:!0,get:function(){return f},set:function(m){var T=e(m);T===!1?console.warn("Scroll: an invalid or illegal string was specified."):f=T}}})}return No=i,No}var oh;function ly(){if(oh)return Mo.exports;oh=1;var s=Pa(),e=Mo.exports={WebVTT:ry(),VTTCue:ay(),VTTRegion:oy()};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(),Mo.exports}var Bo={exports:{}},Uo={exports:{}},lh;function uy(){return lh||(lh=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}(Uo)),Uo.exports}var uh;function cy(){return uh||(uh=1,function(s){var e=uy(),t=pu();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}(Bo)),Bo.exports}var Ho={exports:{}},ch;function hy(){return ch||(ch=1,function(s){var e=pu();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}(Ho)),Ho.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 $o,hh;function dy(){if(hh)return $o;hh=1;var s=Pa(),e=rf(),t=af(),i=Jm(),n=Zm(),r=ey(),o=ty(),u=sy(),h=ly(),p=cy(),f=hy();function m(g){return g&&typeof g=="object"&&"default"in g?g:{default:g}}for(var T=m(s),_=m(e),b=m(t),w=m(i),L=m(n),A=m(r),P=m(o),O=m(u),M=m(h),k=m(p),N=m(f),H="7.21.6",G={},B=function(v,d){return G[v]=G[v]||[],d&&(G[v]=G[v].concat(d)),G[v]},D=function(v,d){B(v,d)},K=function(v,d){var c=B(v).indexOf(d);return c<=-1?!1:(G[v]=G[v].slice(),G[v].splice(c,1),!0)},ae=function(v,d){B(v,[].concat(d).map(function(c){var a=function l(){return K(v,l),c.apply(void 0,arguments)};return a}))},Z={prefixed:!0},oe=[["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"]],le=oe[0],he,pe=0;pe<oe.length;pe++)if(oe[pe][1]in _.default){he=oe[pe];break}if(he){for(var ge=0;ge<he.length;ge++)Z[le[ge]]=he[ge];Z.prefixed=he[0]!==le[0]}var ee=[],Q=function(v,d){return function(c,a,l){var y=d.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 ye(g){var v="info",d,c=function(){for(var l=arguments.length,y=new Array(l),S=0;S<l;S++)y[S]=arguments[S];d("log",v,y)};return d=Q(g,c),c.createLogger=function(a){return ye(g+": "+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 d("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 d("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 d("debug",v,l)},c}var re=ye("VIDEOJS"),ie=re.createLogger,be=Object.prototype.toString,Te=function(v){return je(v)?Object.keys(v):[]};function xe(g,v){Te(g).forEach(function(d){return v(g[d],d)})}function Me(g,v,d){return d===void 0&&(d=0),Te(g).reduce(function(c,a){return v(c,g[a],a)},d)}function Pe(g){for(var v=arguments.length,d=new Array(v>1?v-1:0),c=1;c<v;c++)d[c-1]=arguments[c];return Object.assign?b.default.apply(void 0,[g].concat(d)):(d.forEach(function(a){a&&xe(a,function(l,y){g[y]=l})}),g)}function je(g){return!!g&&typeof g=="object"}function it(g){return je(g)&&be.call(g)==="[object Object]"&&g.constructor===Object}function et(g,v){if(!g||!v)return"";if(typeof T.default.getComputedStyle=="function"){var d;try{d=T.default.getComputedStyle(g)}catch{return""}return d?d.getPropertyValue(v)||d[v]:""}return""}var $e=T.default.navigator&&T.default.navigator.userAgent||"",Si=/AppleWebKit\/([\d.]+)/i.exec($e),ii=Si?parseFloat(Si.pop()):null,Ci=/iPod/i.test($e),_t=function(){var g=$e.match(/OS (\d+)_/i);return g&&g[1]?g[1]:null}(),lt=/Android/i.test($e),ln=function(){var g=$e.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!g)return null;var v=g[1]&&parseFloat(g[1]),d=g[2]&&parseFloat(g[2]);return v&&d?parseFloat(g[1]+"."+g[2]):v||null}(),un=lt&&ln<5&&ii<537,Hi=/Firefox/i.test($e),wi=/Edg/i.test($e),Mt=!wi&&(/Chrome/i.test($e)||/CriOS/i.test($e)),$i=function(){var g=$e.match(/(Chrome|CriOS)\/(\d+)/);return g&&g[2]?parseFloat(g[2]):null}(),Ot=function(){var g=/MSIE\s(\d+)\.\d/.exec($e),v=g&&parseFloat(g[1]);return!v&&/Trident\/7.0/i.test($e)&&/rv:11.0/.test($e)&&(v=11),v}(),mt=/Safari/i.test($e)&&!Mt&&!lt&&!wi,Ft=/Windows/i.test($e),qt=!!(ne()&&("ontouchstart"in T.default||T.default.navigator.maxTouchPoints||T.default.DocumentTouch&&T.default.document instanceof T.default.DocumentTouch)),Et=/iPad/i.test($e)||mt&&qt&&!/iPhone/i.test($e),bt=/iPhone/i.test($e)&&!Et,R=bt||Et||Ci,E=(mt||R)&&!Mt,C=Object.freeze({__proto__:null,IS_IPOD:Ci,IOS_VERSION:_t,IS_ANDROID:lt,ANDROID_VERSION:ln,IS_NATIVE_ANDROID:un,IS_FIREFOX:Hi,IS_EDGE:wi,IS_CHROME:Mt,CHROME_VERSION:$i,IE_VERSION:Ot,IS_SAFARI:mt,IS_WINDOWS:Ft,TOUCH_ENABLED:qt,IS_IPAD:Et,IS_IPHONE:bt,IS_IOS:R,IS_ANY_SAFARI:E});function $(g){return typeof g=="string"&&!!g.trim()}function q(g){if(g.indexOf(" ")>=0)throw new Error("class has illegal whitespace characters")}function J(g){return new RegExp("(^|\\s)"+g+"($|\\s)")}function ne(){return _.default===T.default.document}function Ie(g){return je(g)&&g.nodeType===1}function ze(){try{return T.default.parent!==T.default.self}catch{return!0}}function Ge(g){return function(v,d){if(!$(v))return _.default[g](null);$(d)&&(d=_.default.querySelector(d));var c=Ie(d)?d:_.default;return c[g]&&c[g](v)}}function Ce(g,v,d,c){g===void 0&&(g="div"),v===void 0&&(v={}),d===void 0&&(d={});var a=_.default.createElement(g);return Object.getOwnPropertyNames(v).forEach(function(l){var y=v[l];l.indexOf("aria-")!==-1||l==="role"||l==="type"?(re.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"?Oe(a,y):(a[l]!==y||l==="tabIndex")&&(a[l]=y)}),Object.getOwnPropertyNames(d).forEach(function(l){a.setAttribute(l,d[l])}),c&&ms(a,c),a}function Oe(g,v){return typeof g.textContent>"u"?g.innerText=v:g.textContent=v,g}function fs(g,v){v.firstChild?v.insertBefore(g,v.firstChild):v.appendChild(g)}function Li(g,v){return q(v),g.classList?g.classList.contains(v):J(v).test(g.className)}function Wt(g,v){return g.classList?g.classList.add(v):Li(g,v)||(g.className=(g.className+" "+v).trim()),g}function cn(g,v){return g?(g.classList?g.classList.remove(v):(q(v),g.className=g.className.split(/\s+/).filter(function(d){return d!==v}).join(" ")),g):(re.warn("removeClass was called with an element that doesn't exist"),null)}function ps(g,v,d){var c=Li(g,v);if(typeof d=="function"&&(d=d(g,v)),typeof d!="boolean"&&(d=!c),d!==c)return d?Wt(g,v):cn(g,v),g}function Ks(g,v){Object.getOwnPropertyNames(v).forEach(function(d){var c=v[d];c===null||typeof c>"u"||c===!1?g.removeAttribute(d):g.setAttribute(d,c===!0?"":c)})}function Nt(g){var v={},d=",autoplay,controls,playsinline,loop,muted,default,defaultMuted,";if(g&&g.attributes&&g.attributes.length>0)for(var c=g.attributes,a=c.length-1;a>=0;a--){var l=c[a].name,y=c[a].value;(typeof g[l]=="boolean"||d.indexOf(","+l+",")!==-1)&&(y=y!==null),v[l]=y}return v}function qs(g,v){return g.getAttribute(v)}function ji(g,v,d){g.setAttribute(v,d)}function xn(g,v){g.removeAttribute(v)}function Ws(){_.default.body.focus(),_.default.onselectstart=function(){return!1}}function zs(){_.default.onselectstart=function(){return!0}}function Vi(g){if(g&&g.getBoundingClientRect&&g.parentNode){var v=g.getBoundingClientRect(),d={};return["bottom","height","left","right","top","width"].forEach(function(c){v[c]!==void 0&&(d[c]=v[c])}),d.height||(d.height=parseFloat(et(g,"height"))),d.width||(d.width=parseFloat(et(g,"width"))),d}}function ni(g){if(!g||g&&!g.offsetParent)return{left:0,top:0,width:0,height:0};for(var v=g.offsetWidth,d=g.offsetHeight,c=0,a=0;g.offsetParent&&g!==_.default[Z.fullscreenElement];)c+=g.offsetLeft,a+=g.offsetTop,g=g.offsetParent;return{left:c,top:a,width:v,height:d}}function hn(g,v){var d={x:0,y:0};if(R)for(var c=g;c&&c.nodeName.toLowerCase()!=="html";){var a=et(c,"transform");if(/^matrix/.test(a)){var l=a.slice(7,-1).split(/,\s/).map(Number);d.x+=l[4],d.y+=l[5]}else if(/^matrix3d/.test(a)){var y=a.slice(9,-1).split(/,\s/).map(Number);d.x+=y[12],d.y+=y[13]}c=c.parentNode}var S={},x=ni(v.target),U=ni(g),V=U.width,z=U.height,j=v.offsetY-(U.top-x.top),ue=v.offsetX-(U.left-x.left);return v.changedTouches&&(ue=v.changedTouches[0].pageX-U.left,j=v.changedTouches[0].pageY+U.top,R&&(ue-=d.x,j-=d.y)),S.y=1-Math.max(0,Math.min(1,j/z)),S.x=Math.max(0,Math.min(1,ue/V)),S}function Ys(g){return je(g)&&g.nodeType===3}function gs(g){for(;g.firstChild;)g.removeChild(g.firstChild);return g}function Xs(g){return typeof g=="function"&&(g=g()),(Array.isArray(g)?g:[g]).map(function(v){if(typeof v=="function"&&(v=v()),Ie(v)||Ys(v))return v;if(typeof v=="string"&&/\S/.test(v))return _.default.createTextNode(v)}).filter(function(v){return v})}function ms(g,v){return Xs(v).forEach(function(d){return g.appendChild(d)}),g}function Qs(g,v){return ms(gs(g),v)}function Gi(g){return g.button===void 0&&g.buttons===void 0||g.button===0&&g.buttons===void 0||g.type==="mouseup"&&g.button===0&&g.buttons===0?!0:!(g.button!==0||g.buttons!==1)}var si=Ge("querySelector"),Js=Ge("querySelectorAll"),Zs=Object.freeze({__proto__:null,isReal:ne,isEl:Ie,isInFrame:ze,createEl:Ce,textContent:Oe,prependTo:fs,hasClass:Li,addClass:Wt,removeClass:cn,toggleClass:ps,setAttributes:Ks,getAttributes:Nt,getAttribute:qs,setAttribute:ji,removeAttribute:xn,blockTextSelection:Ws,unblockTextSelection:zs,getBoundingClientRect:Vi,findPosition:ni,getPointerPosition:hn,isTextNode:Ys,emptyEl:gs,normalizeContent:Xs,appendContent:ms,insertContent:Qs,isSingleLeftClick:Gi,$:si,$$:Js}),er=!1,ys,tr=function(){if(ys.options.autoSetup!==!1){var v=Array.prototype.slice.call(_.default.getElementsByTagName("video")),d=Array.prototype.slice.call(_.default.getElementsByTagName("audio")),c=Array.prototype.slice.call(_.default.getElementsByTagName("video-js")),a=v.concat(d,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&&ys(S)}}else{vs(1);break}}else er||vs(1)}};function vs(g,v){ne()&&(v&&(ys=v),T.default.setTimeout(tr,g))}function Ts(){er=!0,T.default.removeEventListener("load",Ts)}ne()&&(_.default.readyState==="complete"?Ts():T.default.addEventListener("load",Ts));var Mn=function(v){var d=_.default.createElement("style");return d.className=v,d},Ki=function(v,d){v.styleSheet?v.styleSheet.cssText=d:v.textContent=d},ir=3,_s=ir;function Bt(){return _s++}var nr;T.default.WeakMap||(nr=function(){function g(){this.vdata="vdata"+Math.floor(T.default.performance&&T.default.performance.now()||Date.now()),this.data={}}var v=g.prototype;return v.set=function(c,a){var l=c[this.vdata]||Bt();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];re("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])},g}());var yt=T.default.WeakMap?new WeakMap:new nr;function sr(g,v){if(yt.has(g)){var d=yt.get(g);d.handlers[v].length===0&&(delete d.handlers[v],g.removeEventListener?g.removeEventListener(v,d.dispatcher,!1):g.detachEvent&&g.detachEvent("on"+v,d.dispatcher)),Object.getOwnPropertyNames(d.handlers).length<=0&&(delete d.handlers,delete d.dispatcher,delete d.disabled),Object.getOwnPropertyNames(d).length===0&&yt.delete(g)}}function On(g,v,d,c){d.forEach(function(a){g(v,a,c)})}function Fn(g){if(g.fixed_)return g;function v(){return!0}function d(){return!1}if(!g||!g.isPropagationStopped||!g.isImmediatePropagationStopped){var c=g||T.default.event;g={};for(var a in c)a!=="layerX"&&a!=="layerY"&&a!=="keyLocation"&&a!=="webkitMovementX"&&a!=="webkitMovementY"&&a!=="path"&&(a==="returnValue"&&c.preventDefault||(g[a]=c[a]));if(g.target||(g.target=g.srcElement||_.default),g.relatedTarget||(g.relatedTarget=g.fromElement===g.target?g.toElement:g.fromElement),g.preventDefault=function(){c.preventDefault&&c.preventDefault(),g.returnValue=!1,c.returnValue=!1,g.defaultPrevented=!0},g.defaultPrevented=!1,g.stopPropagation=function(){c.stopPropagation&&c.stopPropagation(),g.cancelBubble=!0,c.cancelBubble=!0,g.isPropagationStopped=v},g.isPropagationStopped=d,g.stopImmediatePropagation=function(){c.stopImmediatePropagation&&c.stopImmediatePropagation(),g.isImmediatePropagationStopped=v,g.stopPropagation()},g.isImmediatePropagationStopped=d,g.clientX!==null&&g.clientX!==void 0){var l=_.default.documentElement,y=_.default.body;g.pageX=g.clientX+(l&&l.scrollLeft||y&&y.scrollLeft||0)-(l&&l.clientLeft||y&&y.clientLeft||0),g.pageY=g.clientY+(l&&l.scrollTop||y&&y.scrollTop||0)-(l&&l.clientTop||y&&y.clientTop||0)}g.which=g.charCode||g.keyCode,g.button!==null&&g.button!==void 0&&(g.button=g.button&1?0:g.button&4?1:g.button&2?2:0)}return g.fixed_=!0,g}var dn,fn=function(){if(typeof dn!="boolean"){dn=!1;try{var v=Object.defineProperty({},"passive",{get:function(){dn=!0}});T.default.addEventListener("test",null,v),T.default.removeEventListener("test",null,v)}catch{}}return dn},Ba=["touchstart","touchmove"];function Lt(g,v,d){if(Array.isArray(v))return On(Lt,g,v,d);yt.has(g)||yt.set(g,{});var c=yt.get(g);if(c.handlers||(c.handlers={}),c.handlers[v]||(c.handlers[v]=[]),d.guid||(d.guid=Bt()),c.handlers[v].push(d),c.dispatcher||(c.disabled=!1,c.dispatcher=function(l,y){if(!c.disabled){l=Fn(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(g,l,y)}catch(z){re.error(z)}}}),c.handlers[v].length===1)if(g.addEventListener){var a=!1;fn()&&Ba.indexOf(v)>-1&&(a={passive:!0}),g.addEventListener(v,c.dispatcher,a)}else g.attachEvent&&g.attachEvent("on"+v,c.dispatcher)}function dt(g,v,d){if(yt.has(g)){var c=yt.get(g);if(c.handlers){if(Array.isArray(v))return On(dt,g,v,d);var a=function(U,V){c.handlers[V]=[],sr(U,V)};if(v===void 0){for(var l in c.handlers)Object.prototype.hasOwnProperty.call(c.handlers||{},l)&&a(g,l);return}var y=c.handlers[v];if(y){if(!d){a(g,v);return}if(d.guid)for(var S=0;S<y.length;S++)y[S].guid===d.guid&&y.splice(S--,1);sr(g,v)}}}}function qi(g,v,d){var c=yt.has(g)?yt.get(g):{},a=g.parentNode||g.ownerDocument;if(typeof v=="string"?v={type:v,target:g}:v.target||(v.target=g),v=Fn(v),c.dispatcher&&c.dispatcher.call(g,v,d),a&&!v.isPropagationStopped()&&v.bubbles===!0)qi.call(null,a,v,d);else if(!a&&!v.defaultPrevented&&v.target&&v.target[v.type]){yt.has(v.target)||yt.set(v.target,{});var l=yt.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 Nn(g,v,d){if(Array.isArray(v))return On(Nn,g,v,d);var c=function a(){dt(g,v,a),d.apply(this,arguments)};c.guid=d.guid=d.guid||Bt(),Lt(g,v,c)}function rr(g,v,d){var c=function a(){dt(g,v,a),d.apply(this,arguments)};c.guid=d.guid=d.guid||Bt(),Lt(g,v,c)}var ar=Object.freeze({__proto__:null,fixEvent:Fn,on:Lt,off:dt,trigger:qi,one:Nn,any:rr}),It=30,Ye=function(v,d,c){d.guid||(d.guid=Bt());var a=d.bind(v);return a.guid=c?c+"_"+d.guid:d.guid,a},zt=function(v,d){var c=T.default.performance.now(),a=function(){var y=T.default.performance.now();y-c>=d&&(v.apply(void 0,arguments),c=y)};return a},me=function(v,d,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,d)};return S.cancel=y,S},F=function(){};F.prototype.allowedEvents_={},F.prototype.on=function(g,v){var d=this.addEventListener;this.addEventListener=function(){},Lt(this,g,v),this.addEventListener=d},F.prototype.addEventListener=F.prototype.on,F.prototype.off=function(g,v){dt(this,g,v)},F.prototype.removeEventListener=F.prototype.off,F.prototype.one=function(g,v){var d=this.addEventListener;this.addEventListener=function(){},Nn(this,g,v),this.addEventListener=d},F.prototype.any=function(g,v){var d=this.addEventListener;this.addEventListener=function(){},rr(this,g,v),this.addEventListener=d},F.prototype.trigger=function(g){var v=g.type||g;typeof g=="string"&&(g={type:v}),g=Fn(g),this.allowedEvents_[v]&&this["on"+v]&&this["on"+v](g),qi(this,g)},F.prototype.dispatchEvent=F.prototype.trigger;var fe;F.prototype.queueTrigger=function(g){var v=this;fe||(fe=new Map);var d=g.type||g,c=fe.get(this);c||(c=new Map,fe.set(this,c));var a=c.get(d);c.delete(d),T.default.clearTimeout(a);var l=T.default.setTimeout(function(){c.delete(d),c.size===0&&(c=null,fe.delete(v)),v.trigger(g)},0);c.set(d,l)};var Ae=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},Re=function(v){return v instanceof F||!!v.eventBusEl_&&["on","one","off","trigger"].every(function(d){return typeof v[d]=="function"})},Qe=function(v,d){Re(v)?d():(v.eventedCallbacks||(v.eventedCallbacks=[]),v.eventedCallbacks.push(d))},Ke=function(v){return typeof v=="string"&&/\S/.test(v)||Array.isArray(v)&&!!v.length},Yt=function(v,d,c){if(!v||!v.nodeName&&!Re(v))throw new Error("Invalid target for "+Ae(d)+"#"+c+"; must be a DOM node or evented object.")},Wi=function(v,d,c){if(!Ke(v))throw new Error("Invalid event type for "+Ae(d)+"#"+c+"; must be a non-empty string or array.")},Be=function(v,d,c){if(typeof v!="function")throw new Error("Invalid listener for "+Ae(d)+"#"+c+"; must be a function.")},Rt=function(v,d,c){var a=d.length<3||d[0]===v||d[0]===v.eventBusEl_,l,y,S;return a?(l=v.eventBusEl_,d.length>=3&&d.shift(),y=d[0],S=d[1]):(l=d[0],y=d[1],S=d[2]),Yt(l,v,c),Wi(y,v,c),Be(S,v,c),S=Ye(v,S),{isTargetingSelf:a,target:l,type:y,listener:S}},St=function(v,d,c,a){Yt(v,v,d),v.nodeName?ar[d](v,c,a):v[d](c,a)},Es={on:function(){for(var v=this,d=arguments.length,c=new Array(d),a=0;a<d;a++)c[a]=arguments[a];var l=Rt(this,c,"on"),y=l.isTargetingSelf,S=l.target,x=l.type,U=l.listener;if(St(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,St(this,"on","dispose",V),St(S,"on","dispose",z)}},one:function(){for(var v=this,d=arguments.length,c=new Array(d),a=0;a<d;a++)c[a]=arguments[a];var l=Rt(this,c,"one"),y=l.isTargetingSelf,S=l.target,x=l.type,U=l.listener;if(y)St(S,"one",x,U);else{var V=function z(){v.off(S,x,z);for(var j=arguments.length,ue=new Array(j),_e=0;_e<j;_e++)ue[_e]=arguments[_e];U.apply(null,ue)};V.guid=U.guid,St(S,"one",x,V)}},any:function(){for(var v=this,d=arguments.length,c=new Array(d),a=0;a<d;a++)c[a]=arguments[a];var l=Rt(this,c,"any"),y=l.isTargetingSelf,S=l.target,x=l.type,U=l.listener;if(y)St(S,"any",x,U);else{var V=function z(){v.off(S,x,z);for(var j=arguments.length,ue=new Array(j),_e=0;_e<j;_e++)ue[_e]=arguments[_e];U.apply(null,ue)};V.guid=U.guid,St(S,"any",x,V)}},off:function(v,d,c){if(!v||Ke(v))dt(this.eventBusEl_,v,d);else{var a=v,l=d;Yt(a,this,"off"),Wi(l,this,"off"),Be(c,this,"off"),c=Ye(this,c),this.off("dispose",c),a.nodeName?(dt(a,l,c),dt(a,"dispose",c)):Re(a)&&(a.off(l,c),a.off("dispose",c))}},trigger:function(v,d){Yt(this.eventBusEl_,this,"trigger");var c=v&&typeof v!="string"?v.type:v;if(!Ke(c)){var a="Invalid event type for "+Ae(this)+"#trigger; must be a non-empty string or object with a type key that has a non-empty value.";if(v)(this.log||re).error(a);else throw new Error(a)}return qi(this.eventBusEl_,v,d)}};function bs(g,v){v===void 0&&(v={});var d=v,c=d.eventBusKey;if(c){if(!g[c].nodeName)throw new Error('The eventBusKey "'+c+'" does not refer to an element.');g.eventBusEl_=g[c]}else g.eventBusEl_=Ce("span",{className:"vjs-event-bus"});return Pe(g,Es),g.eventedCallbacks&&g.eventedCallbacks.forEach(function(a){a()}),g.on("dispose",function(){g.off(),[g,g.el_,g.eventBusEl_].forEach(function(a){a&&yt.has(a)&&yt.delete(a)}),T.default.setTimeout(function(){g.eventBusEl_=null},0)}),g}var Og={state:{},setState:function(v){var d=this;typeof v=="function"&&(v=v());var c;return xe(v,function(a,l){d.state[l]!==a&&(c=c||{},c[l]={from:d.state[l],to:a}),d.state[l]=a}),c&&Re(this)&&this.trigger({changes:c,type:"statechanged"}),c}};function Vu(g,v){return Pe(g,Og),g.state=Pe({},g.state,v),typeof g.handleStateChanged=="function"&&Re(g)&&g.on("statechanged",g.handleStateChanged),g}var or=function(v){return typeof v!="string"?v:v.replace(/./,function(d){return d.toLowerCase()})},rt=function(v){return typeof v!="string"?v:v.replace(/./,function(d){return d.toUpperCase()})},Fg=function(v,d){return rt(v)===rt(d)};function tt(){for(var g={},v=arguments.length,d=new Array(v),c=0;c<v;c++)d[c]=arguments[c];return d.forEach(function(a){a&&xe(a,function(l,y){if(!it(l)){g[y]=l;return}it(g[y])||(g[y]={}),g[y]=tt(g[y],l)})}),g}var Ng=function(){function g(){this.map_={}}var v=g.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)},g}(),Bg=T.default.Map?T.default.Map:Ng,Ug=function(){function g(){this.set_={}}var v=g.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)},g}(),Ua=T.default.Set?T.default.Set:Ug,de=function(){function g(d,c,a){var l=this;if(!d&&this.play?this.player_=d=this:this.player_=d,this.isDisposed_=!1,this.parentComponent_=null,this.options_=tt({},this.options_),c=this.options_=tt(this.options_,c),this.id_=c.id||c.el&&c.el.id,!this.id_){var y=d&&d.id&&d.id()||"no_player";this.id_=y+"_component_"+Bt()}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&&(bs(this,{eventBusKey:this.el_?"el_":null}),this.handleLanguagechange=this.handleLanguagechange.bind(this),this.on(this.player_,"languagechange",this.handleLanguagechange)),Vu(this,this.constructor.defaultState),this.children_=[],this.childIndex_={},this.childNameIndex_={},this.setTimeoutIds_=new Ua,this.setIntervalIds_=new Ua,this.rafIds_=new Ua,this.namedRafs_=new Bg,this.clearingTimersOnDispose_=!1,c.initChildren!==!1&&this.initChildren(),this.ready(a),c.reportTouchActivity!==!1&&this.enableTouchActivity()}var v=g.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_=tt(this.options_,c),this.options_):this.options_},v.el=function(){return this.el_},v.createEl=function(c,a,l){return Ce(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,ue){var _e=a[ue-1],Fe=_e;return typeof _e>"u"&&(Fe=j),Fe})),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=rt(c);var x=a.componentClass||S;a.name=S;var U=g.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&&rt(y.name()),S&&(this.childNameIndex_[S]=y,this.childNameIndex_[or(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_:Ie(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_[rt(c.name())]=null,this.childNameIndex_[or(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 ue=c.addChild(z,j);ue&&(c[z]=ue)}},S,x=g.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=g.getComponent(U.opts.componentClass||rt(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 si(c,a||this.contentEl())},v.$$=function(c,a){return Js(c,a||this.contentEl())},v.hasClass=function(c){return Li(this.el_,c)},v.addClass=function(c){Wt(this.el_,c)},v.removeClass=function(c){cn(this.el_,c)},v.toggleClass=function(c,a){ps(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 qs(this.el_,c)},v.setAttribute=function(c,a){ji(this.el_,c,a)},v.removeAttribute=function(c){xn(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"+rt(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=et(this.el_,c),a=parseFloat(a),a===0||isNaN(a)){var l="offset"+rt(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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}))},g.registerComponent=function(c,a){if(typeof c!="string"||!c)throw new Error('Illegal component name, "'+c+'"; must be a non-empty string.');var l=g.getComponent("Tech"),y=l&&l.isTech(a),S=g===a||g.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=rt(c),g.components_||(g.components_={});var U=g.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 g.components_[c]=a,g.components_[or(c)]=a,a},g.getComponent=function(c){if(!(!c||!g.components_))return g.components_[c]},g}();de.prototype.supportsRaf_=typeof T.default.requestAnimationFrame=="function"&&typeof T.default.cancelAnimationFrame=="function",de.registerComponent("Component",de);function Hg(g,v,d){if(typeof v!="number"||v<0||v>d)throw new Error("Failed to execute '"+g+"' on 'TimeRanges': The index provided ("+v+") is non-numeric or out of bounds (0-"+d+").")}function Gu(g,v,d,c){return Hg(g,c,d.length-1),d[c][v]}function Ha(g){var v;return g===void 0||g.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:g.length,start:Gu.bind(null,"start",0,g),end:Gu.bind(null,"end",1,g)},T.default.Symbol&&T.default.Symbol.iterator&&(v[T.default.Symbol.iterator]=function(){return(g||[]).values()}),v}function pn(g,v){return Array.isArray(g)?Ha(g):g===void 0||v===void 0?Ha():Ha([[g,v]])}function Ku(g,v){var d=0,c,a;if(!v)return 0;(!g||!g.length)&&(g=pn(0,0));for(var l=0;l<g.length;l++)c=g.start(l),a=g.end(l),a>v&&(a=v),d+=a-c;return d/v}function At(g){if(g instanceof At)return g;typeof g=="number"?this.code=g:typeof g=="string"?this.message=g:je(g)&&(typeof g.code=="number"&&(this.code=g.code),Pe(this,g)),this.message||(this.message=At.defaultMessages[this.code]||"")}At.prototype.code=0,At.prototype.message="",At.prototype.status=null,At.errorTypes=["MEDIA_ERR_CUSTOM","MEDIA_ERR_ABORTED","MEDIA_ERR_NETWORK","MEDIA_ERR_DECODE","MEDIA_ERR_SRC_NOT_SUPPORTED","MEDIA_ERR_ENCRYPTED"],At.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 Bn=0;Bn<At.errorTypes.length;Bn++)At[At.errorTypes[Bn]]=Bn,At.prototype[At.errorTypes[Bn]]=Bn;function Ss(g){return g!=null&&typeof g.then=="function"}function ri(g){Ss(g)&&g.then(null,function(v){})}var $a=function(v){var d=["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 d},$g=function(v){var d=v.$$("track"),c=Array.prototype.map.call(d,function(l){return l.track}),a=Array.prototype.map.call(d,function(l){var y=$a(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($a))},jg=function(v,d){return v.forEach(function(c){var a=d.addRemoteTextTrack(c).track;!c.src&&c.cues&&c.cues.forEach(function(l){return a.addCue(l)})}),d.textTracks()},qu={textTracksToJson:$g,jsonToTextTracks:jg,trackToJson_:$a},ja="vjs-modal-dialog",Un=function(g){A.default(v,g);function v(c,a){var l;return l=g.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_=Ce("div",{className:ja+"-content"},{role:"document"}),l.descEl_=Ce("p",{className:ja+"-description vjs-control-text",id:l.el().getAttribute("aria-describedby")}),Oe(l.descEl_,l.description()),l.el_.appendChild(l.descEl_),l.el_.appendChild(l.contentEl_),l}var d=v.prototype;return d.createEl=function(){return g.prototype.createEl.call(this,"div",{className:this.buildCSSClass(),tabIndex:-1},{"aria-describedby":this.id()+"_description","aria-hidden":"true","aria-label":this.label(),role:"dialog"})},d.dispose=function(){this.contentEl_=null,this.descEl_=null,this.previouslyActiveEl_=null,g.prototype.dispose.call(this)},d.buildCSSClass=function(){return ja+" vjs-hidden "+g.prototype.buildCSSClass.call(this)},d.label=function(){return this.localize(this.options_.label||"Modal Window")},d.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},d.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}},d.opened=function(a){return typeof a=="boolean"&&this[a?"open":"close"](),this.opened_},d.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()}},d.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_},d.fill=function(){this.fillWith(this.content())},d.fillWith=function(a){var l=this.contentEl(),y=l.parentNode,S=l.nextSibling;this.trigger("beforemodalfill"),this.hasBeenFilled_=!0,y.removeChild(l),this.empty(),Qs(l,a),this.trigger("modalfill"),S?y.insertBefore(l,S):y.appendChild(l);var x=this.getChild("closeButton");x&&y.appendChild(x.el_)},d.empty=function(){this.trigger("beforemodalempty"),gs(this.contentEl()),this.trigger("modalempty")},d.content=function(a){return typeof a<"u"&&(this.content_=a),this.content_},d.conditionalFocus_=function(){var a=_.default.activeElement,l=this.player_.el_;this.previouslyActiveEl_=null,(l.contains(a)||l===a)&&(this.previouslyActiveEl_=a,this.focus())},d.conditionalBlur_=function(){this.previouslyActiveEl_&&(this.previouslyActiveEl_.focus(),this.previouslyActiveEl_=null)},d.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}_.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())}},d.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}(de);Un.prototype.options_={pauseOnOpen:!0,temporary:!0},de.registerComponent("ModalDialog",Un);var Hn=function(g){A.default(v,g);function v(c){var a;c===void 0&&(c=[]),a=g.call(this)||this,a.tracks_=[],Object.defineProperty(L.default(a),"length",{get:function(){return this.tracks_.length}});for(var l=0;l<c.length;l++)a.addTrack(c[l]);return a}var d=v.prototype;return d.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})},Re(a)&&a.addEventListener("labelchange",a.labelchange_)},d.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})},d.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);Hn.prototype.allowedEvents_={change:"change",addtrack:"addtrack",removetrack:"removetrack",labelchange:"labelchange"};for(var Vg in Hn.prototype.allowedEvents_)Hn.prototype["on"+Vg]=null;var Va=function(v,d){for(var c=0;c<v.length;c++)!Object.keys(v[c]).length||d.id===v[c].id||(v[c].enabled=!1)},Gg=function(g){A.default(v,g);function v(c){var a;c===void 0&&(c=[]);for(var l=c.length-1;l>=0;l--)if(c[l].enabled){Va(c,c[l]);break}return a=g.call(this,c)||this,a.changing_=!1,a}var d=v.prototype;return d.addTrack=function(a){var l=this;a.enabled&&Va(this,a),g.prototype.addTrack.call(this,a),a.addEventListener&&(a.enabledChange_=function(){l.changing_||(l.changing_=!0,Va(l,a),l.changing_=!1,l.trigger("change"))},a.addEventListener("enabledchange",a.enabledChange_))},d.removeTrack=function(a){g.prototype.removeTrack.call(this,a),a.removeEventListener&&a.enabledChange_&&(a.removeEventListener("enabledchange",a.enabledChange_),a.enabledChange_=null)},v}(Hn),Ga=function(v,d){for(var c=0;c<v.length;c++)!Object.keys(v[c]).length||d.id===v[c].id||(v[c].selected=!1)},Kg=function(g){A.default(v,g);function v(c){var a;c===void 0&&(c=[]);for(var l=c.length-1;l>=0;l--)if(c[l].selected){Ga(c,c[l]);break}return a=g.call(this,c)||this,a.changing_=!1,Object.defineProperty(L.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 d=v.prototype;return d.addTrack=function(a){var l=this;a.selected&&Ga(this,a),g.prototype.addTrack.call(this,a),a.addEventListener&&(a.selectedChange_=function(){l.changing_||(l.changing_=!0,Ga(l,a),l.changing_=!1,l.trigger("change"))},a.addEventListener("selectedchange",a.selectedChange_))},d.removeTrack=function(a){g.prototype.removeTrack.call(this,a),a.removeEventListener&&a.selectedChange_&&(a.removeEventListener("selectedchange",a.selectedChange_),a.selectedChange_=null)},v}(Hn),Wu=function(g){A.default(v,g);function v(){return g.apply(this,arguments)||this}var d=v.prototype;return d.addTrack=function(a){var l=this;g.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_)},d.removeTrack=function(a){g.prototype.removeTrack.call(this,a),a.removeEventListener&&(this.queueChange_&&a.removeEventListener("modechange",this.queueChange_),this.selectedlanguagechange_&&a.removeEventListener("modechange",this.triggerSelectedlanguagechange_))},v}(Hn),qg=function(){function g(d){d===void 0&&(d=[]),this.trackElements_=[],Object.defineProperty(this,"length",{get:function(){return this.trackElements_.length}});for(var c=0,a=d.length;c<a;c++)this.addTrackElement_(d[c])}var v=g.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}},g}(),zu=function(){function g(d){g.prototype.setCues_.call(this,d),Object.defineProperty(this,"length",{get:function(){return this.length_}})}var v=g.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},g}(),Wg={alternative:"alternative",captions:"captions",main:"main",sign:"sign",subtitles:"subtitles",commentary:"commentary"},zg={alternative:"alternative",descriptions:"descriptions",main:"main","main-desc":"main-desc",translation:"translation",commentary:"commentary"},Yg={subtitles:"subtitles",captions:"captions",descriptions:"descriptions",chapters:"chapters",metadata:"metadata"},Yu={disabled:"disabled",hidden:"hidden",showing:"showing"},Ka=function(g){A.default(v,g);function v(d){var c;d===void 0&&(d={}),c=g.call(this)||this;var a={id:d.id||"vjs_track_"+Bt(),kind:d.kind||"",language:d.language||""},l=d.label||"",y=function(U){Object.defineProperty(L.default(c),U,{get:function(){return a[U]},set:function(){}})};for(var S in a)y(S);return Object.defineProperty(L.default(c),"label",{get:function(){return l},set:function(U){U!==l&&(l=U,this.trigger("labelchange"))}}),c}return v}(F),qa=function(v){var d=["protocol","hostname","port","pathname","search","hash","host"],c=_.default.createElement("a");c.href=v;for(var a={},l=0;l<d.length;l++)a[d[l]]=c[d[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},Xu=function(v){if(!v.match(/^https?:\/\//)){var d=_.default.createElement("a");d.href=v,v=d.href}return v},Wa=function(v){if(typeof v=="string"){var d=/^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/,c=d.exec(v);if(c)return c.pop().toLowerCase()}return""},lr=function(v,d){d===void 0&&(d=T.default.location);var c=qa(v),a=c.protocol===":"?d.protocol:c.protocol,l=a+c.host!==d.protocol+d.host;return l},Xg=Object.freeze({__proto__:null,parseUrl:qa,getAbsoluteURL:Xu,getFileExtension:Wa,isCrossOrigin:lr}),Qu=function(v,d){var c=new T.default.WebVTT.Parser(T.default,T.default.vttjs,T.default.WebVTT.StringDecoder()),a=[];c.oncue=function(l){d.addCue(l)},c.onparsingerror=function(l){a.push(l)},c.onflush=function(){d.trigger({type:"loadeddata",target:d})},c.parse(v),a.length>0&&(T.default.console&&T.default.console.groupCollapsed&&T.default.console.groupCollapsed("Text Track parsing errors for "+d.src),a.forEach(function(l){return re.error(l)}),T.default.console&&T.default.console.groupEnd&&T.default.console.groupEnd()),c.flush()},Ju=function(v,d){var c={uri:v},a=lr(v);a&&(c.cors=a);var l=d.tech_.crossOrigin()==="use-credentials";l&&(c.withCredentials=l),O.default(c,Ye(this,function(y,S,x){if(y)return re.error(y,S);d.loaded_=!0,typeof T.default.WebVTT!="function"?d.tech_&&d.tech_.any(["vttjsloaded","vttjserror"],function(U){if(U.type==="vttjserror"){re.error("vttjs failed to load, stopping trying to process "+d.src);return}return Qu(x,d)}):Qu(x,d)}))},Cs=function(g){A.default(v,g);function v(c){var a;if(c===void 0&&(c={}),!c.tech)throw new Error("A tech was not provided.");var l=tt(c,{kind:Yg[c.kind]||"subtitles",language:c.language||c.srclang||""}),y=Yu[l.mode]||"disabled",S=l.default;(l.kind==="metadata"||l.kind==="chapters")&&(y="hidden"),a=g.call(this,l)||this,a.tech_=l.tech,a.cues_=[],a.activeCues_=[],a.preload_=a.tech_.preloadTextTracks!==!1;var x=new zu(a.cues_),U=new zu(a.activeCues_),V=!1;a.timeupdateHandler=Ye(L.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(L.default(a),{default:{get:function(){return S},set:function(){}},mode:{get:function(){return y},set:function(ue){Yu[ue]&&y!==ue&&(y=ue,!this.preload_&&y!=="disabled"&&this.cues.length===0&&Ju(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 ue=this.tech_.currentTime(),_e=[],Fe=0,vn=this.cues.length;Fe<vn;Fe++){var oi=this.cues[Fe];(oi.startTime<=ue&&oi.endTime>=ue||oi.startTime===oi.endTime&&oi.startTime<=ue&&oi.startTime+.5>=ue)&&_e.push(oi)}if(V=!1,_e.length!==this.activeCues_.length)V=!0;else for(var Co=0;Co<_e.length;Co++)this.activeCues_.indexOf(_e[Co])===-1&&(V=!0);return this.activeCues_=_e,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")&&Ju(a.src,L.default(a))):a.loaded_=!0,a}var d=v.prototype;return d.startTracking=function(){this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler),this.tech_.on("timeupdate",this.timeupdateHandler)},d.stopTracking=function(){this.rvf_&&(this.tech_.cancelVideoFrameCallback(this.rvf_),this.rvf_=void 0),this.tech_.off("timeupdate",this.timeupdateHandler)},d.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_)},d.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}(Ka);Cs.prototype.allowedEvents_={cuechange:"cuechange"};var Zu=function(g){A.default(v,g);function v(d){var c;d===void 0&&(d={});var a=tt(d,{kind:zg[d.kind]||""});c=g.call(this,a)||this;var l=!1;return Object.defineProperty(L.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}(Ka),ec=function(g){A.default(v,g);function v(d){var c;d===void 0&&(d={});var a=tt(d,{kind:Wg[d.kind]||""});c=g.call(this,a)||this;var l=!1;return Object.defineProperty(L.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}(Ka),tc=0,Qg=1,ic=2,Jg=3,$n=function(g){A.default(v,g);function v(d){var c;d===void 0&&(d={}),c=g.call(this)||this;var a,l=new Cs(d);return c.kind=l.kind,c.src=l.src,c.srclang=l.language,c.label=l.label,c.default=l.default,Object.defineProperties(L.default(c),{readyState:{get:function(){return a}},track:{get:function(){return l}}}),a=tc,l.addEventListener("loadeddata",function(){a=ic,c.trigger({type:"load",target:L.default(c)})}),c}return v}(F);$n.prototype.allowedEvents_={load:"load"},$n.NONE=tc,$n.LOADING=Qg,$n.LOADED=ic,$n.ERROR=Jg;var Ut={audio:{ListClass:Gg,TrackClass:Zu,capitalName:"Audio"},video:{ListClass:Kg,TrackClass:ec,capitalName:"Video"},text:{ListClass:Wu,TrackClass:Cs,capitalName:"Text"}};Object.keys(Ut).forEach(function(g){Ut[g].getterName=g+"Tracks",Ut[g].privateName=g+"Tracks_"});var jn={remoteText:{ListClass:Wu,TrackClass:Cs,capitalName:"RemoteText",getterName:"remoteTextTracks",privateName:"remoteTextTracks_"},remoteTextEl:{ListClass:qg,TrackClass:$n,capitalName:"RemoteTextTrackEls",getterName:"remoteTextTrackEls",privateName:"remoteTextTrackEls_"}},kt=b.default({},Ut,jn);jn.names=Object.keys(jn),Ut.names=Object.keys(Ut),kt.names=[].concat(jn.names).concat(Ut.names);function Zg(g,v,d,c,a){a===void 0&&(a={});var l=g.textTracks();a.kind=v,d&&(a.label=d),c&&(a.language=c),a.tech=g;var y=new kt.text.TrackClass(a);return l.addTrack(y),y}var Xe=function(g){A.default(v,g);function v(c,a){var l;return c===void 0&&(c={}),a===void 0&&(a=function(){}),c.reportTouchActivity=!1,l=g.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}),kt.names.forEach(function(y){var S=kt[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 kt.text.ListClass,l.initTrackListeners(),c.nativeControlsForTouch||l.emitTapEvents(),l.constructor&&(l.name_=l.constructor.name||"Unknown Tech"),l}var d=v.prototype;return d.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"})},d.manualProgressOn=function(){this.on("durationchange",this.onDurationChange_),this.manualProgress=!0,this.one("ready",this.trackProgress_)},d.manualProgressOff=function(){this.manualProgress=!1,this.stopTrackingProgress(),this.off("durationchange",this.onDurationChange_)},d.trackProgress=function(a){this.stopTrackingProgress(),this.progressInterval=this.setInterval(Ye(this,function(){var l=this.bufferedPercent();this.bufferedPercent_!==l&&this.trigger("progress"),this.bufferedPercent_=l,l===1&&this.stopTrackingProgress()}),500)},d.onDurationChange=function(a){this.duration_=this.duration()},d.buffered=function(){return pn(0,0)},d.bufferedPercent=function(){return Ku(this.buffered(),this.duration_)},d.stopTrackingProgress=function(){this.clearInterval(this.progressInterval)},d.manualTimeUpdatesOn=function(){this.manualTimeUpdates=!0,this.on("play",this.trackCurrentTime_),this.on("pause",this.stopTrackingCurrentTime_)},d.manualTimeUpdatesOff=function(){this.manualTimeUpdates=!1,this.stopTrackingCurrentTime(),this.off("play",this.trackCurrentTime_),this.off("pause",this.stopTrackingCurrentTime_)},d.trackCurrentTime=function(){this.currentTimeInterval&&this.stopTrackingCurrentTime(),this.currentTimeInterval=this.setInterval(function(){this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})},250)},d.stopTrackingCurrentTime=function(){this.clearInterval(this.currentTimeInterval),this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})},d.dispose=function(){this.clearTracks(Ut.names),this.manualProgress&&this.manualProgressOff(),this.manualTimeUpdates&&this.manualTimeUpdatesOff(),g.prototype.dispose.call(this)},d.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)}})},d.cleanupAutoTextTracks=function(){for(var a=this.autoRemoteTextTracks_||[],l=a.length;l--;){var y=a[l];this.removeRemoteTextTrack(y)}},d.reset=function(){},d.crossOrigin=function(){},d.setCrossOrigin=function(){},d.error=function(a){return a!==void 0&&(this.error_=new At(a),this.trigger("error")),this.error_},d.played=function(){return this.hasStarted_?pn(0,0):pn()},d.play=function(){},d.setScrubbing=function(){},d.scrubbing=function(){},d.setCurrentTime=function(){this.manualTimeUpdates&&this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})},d.initTrackListeners=function(){var a=this;Ut.names.forEach(function(l){var y=Ut[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)})})},d.addWebVttScript_=function(){var a=this;if(!T.default.WebVTT)if(_.default.body.contains(this.el())){if(!this.options_["vtt.js"]&&it(M.default)&&Object.keys(M.default).length>0){this.trigger("vttjsloaded");return}var l=_.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_)},d.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 ue=l[j];ue.removeEventListener("cuechange",U),ue.mode==="showing"&&ue.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)}})},d.addTextTrack=function(a,l,y){if(!a)throw new Error("TextTrack kind is required but was not provided");return Zg(this,a,l,y)},d.createRemoteTextTrack=function(a){var l=tt(a,{tech:this});return new jn.remoteTextEl.TrackClass(l)},d.addRemoteTextTrack=function(a,l){var y=this;a===void 0&&(a={});var S=this.createRemoteTextTrack(a);return l!==!0&&l!==!1&&(re.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},d.removeRemoteTextTrack=function(a){var l=this.remoteTextTrackEls().getTrackElementByTrack_(a);this.remoteTextTrackEls().removeTrackElement_(l),this.remoteTextTracks().removeTrack(a),this.autoRemoteTextTracks_.removeTrack(a)},d.getVideoPlaybackQuality=function(){return{}},d.requestPictureInPicture=function(){var a=this.options_.Promise||T.default.Promise;if(a)return a.reject()},d.disablePictureInPicture=function(){return!0},d.setDisablePictureInPicture=function(){},d.requestVideoFrameCallback=function(a){var l=this,y=Bt();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},d.cancelVideoFrameCallback=function(a){this.queuedHanders_.has(a)?this.queuedHanders_.delete(a):this.cancelNamedAnimationFrame(a)},d.setPoster=function(){},d.playsinline=function(){},d.setPlaysinline=function(){},d.overrideNativeAudioTracks=function(){},d.overrideNativeVideoTracks=function(){},d.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=rt(a),v.techs_[a]=l,v.techs_[or(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=rt(a),T.default&&T.default.videojs&&T.default.videojs[a])return re.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}(de);kt.names.forEach(function(g){var v=kt[g];Xe.prototype[v.getterName]=function(){return this[v.privateName]=this[v.privateName]||new v.ListClass,this[v.privateName]}}),Xe.prototype.featuresVolumeControl=!0,Xe.prototype.featuresMuteControl=!0,Xe.prototype.featuresFullscreenResize=!1,Xe.prototype.featuresPlaybackRate=!1,Xe.prototype.featuresProgressEvents=!1,Xe.prototype.featuresSourceset=!1,Xe.prototype.featuresTimeupdateEvents=!1,Xe.prototype.featuresNativeTextTracks=!1,Xe.prototype.featuresVideoFrameCallback=!1,Xe.withSourceHandlers=function(g){g.registerSourceHandler=function(d,c){var a=g.sourceHandlers;a||(a=g.sourceHandlers=[]),c===void 0&&(c=a.length),a.splice(c,0,d)},g.canPlayType=function(d){for(var c=g.sourceHandlers||[],a,l=0;l<c.length;l++)if(a=c[l].canPlayType(d),a)return a;return""},g.selectSourceHandler=function(d,c){for(var a=g.sourceHandlers||[],l,y=0;y<a.length;y++)if(l=a[y].canHandleSource(d,c),l)return a[y];return null},g.canPlaySource=function(d,c){var a=g.selectSourceHandler(d,c);return a?a.canHandleSource(d,c):""};var v=["seekable","seeking","duration"];v.forEach(function(d){var c=this[d];typeof c=="function"&&(this[d]=function(){return this.sourceHandler_&&this.sourceHandler_[d]?this.sourceHandler_[d].apply(this.sourceHandler_,arguments):c.apply(this,arguments)})},g.prototype),g.prototype.setSource=function(d){var c=g.selectSourceHandler(d,this.options_);c||(g.nativeSourceHandler?c=g.nativeSourceHandler:re.error("No source handler found for the current source.")),this.disposeSourceHandler(),this.off("dispose",this.disposeSourceHandler_),c!==g.nativeSourceHandler&&(this.currentSource_=d),this.sourceHandler_=c.handleSource(d,this,this.options_),this.one("dispose",this.disposeSourceHandler_)},g.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)}},de.registerComponent("Tech",Xe),Xe.registerTech("Tech",Xe),Xe.defaultTechOrder_=[];var gn={},za={},ur={};function em(g,v){gn[g]=gn[g]||[],gn[g].push(v)}function tm(g,v,d){g.setTimeout(function(){return mn(v,gn[v.type],d,g)},1)}function im(g,v){g.forEach(function(d){return d.setTech&&d.setTech(v)})}function nm(g,v,d){return g.reduceRight(Ya(d),v[d]())}function sm(g,v,d,c){return v[d](g.reduce(Ya(d),c))}function nc(g,v,d,c){c===void 0&&(c=null);var a="call"+rt(d),l=g.reduce(Ya(a),c),y=l===ur,S=y?null:v[d](l);return om(g,d,S,y),S}var rm={buffered:1,currentTime:1,duration:1,muted:1,played:1,paused:1,seekable:1,volume:1,ended:1},am={setCurrentTime:1,setMuted:1,setVolume:1},sc={play:1,pause:1};function Ya(g){return function(v,d){return v===ur?ur:d[g]?d[g](v):v}}function om(g,v,d,c){for(var a=g.length-1;a>=0;a--){var l=g[a];l[v]&&l[v](c,d)}}function lm(g){za[g.id()]=null}function um(g,v){var d=za[g.id()],c=null;if(d==null)return c=v(g),za[g.id()]=[[v,c]],c;for(var a=0;a<d.length;a++){var l=d[a],y=l[0],S=l[1];y===v&&(c=S)}return c===null&&(c=v(g),d.push([v,c])),c}function mn(g,v,d,c,a,l){g===void 0&&(g={}),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")mn(g,gn[S],d,c,a,l);else if(S){var U=um(c,S);if(!U.setSource)return a.push(U),mn(g,x,d,c,a,l);U.setSource(Pe({},g),function(V,z){if(V)return mn(g,x,d,c,a,l);a.push(U),mn(z,g.type===z.type?x:gn[z.type],d,c,a,l)})}else x.length?mn(g,x,d,c,a,l):l?d(g,a):mn(g,gn["*"],d,c,a,!0)}var cm={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"},cr=function(v){v===void 0&&(v="");var d=Wa(v),c=cm[d.toLowerCase()];return c||""},hm=function(v,d){if(!d)return"";if(v.cache_.source.src===d&&v.cache_.source.type)return v.cache_.source.type;var c=v.cache_.sources.filter(function(S){return S.src===d});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===d)return y.type}return cr(d)},dm=function g(v){if(Array.isArray(v)){var d=[];v.forEach(function(c){c=g(c),Array.isArray(c)?d=d.concat(c):je(c)&&d.push(c)}),v=d}else typeof v=="string"&&v.trim()?v=[rc({src:v})]:je(v)&&typeof v.src=="string"&&v.src&&v.src.trim()?v=[rc(v)]:v=[];return v};function rc(g){if(!g.type){var v=cr(g.src);v&&(g.type=v)}return g}var fm=function(g){A.default(v,g);function v(d,c,a){var l,y=tt({createEl:!1},c);if(l=g.call(this,d,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=rt(x[S]),V=Xe.getTech(U);if(U||(V=de.getComponent(U)),V&&V.isSupported()){d.loadTech_(U);break}}else d.src(c.playerOptions.sources);return l}return v}(de);de.registerComponent("MediaLoader",fm);var hr=function(g){A.default(v,g);function v(c,a){var l;return l=g.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 d=v.prototype;return d.createEl=function(a,l,y){a===void 0&&(a="div"),l===void 0&&(l={}),y===void 0&&(y={}),l=Pe({className:this.buildCSSClass(),tabIndex:0},l),a==="button"&&re.error("Creating a ClickableComponent with an HTML element of "+a+" is not supported; use a Button instead."),y=Pe({role:"button"},y),this.tabIndex_=l.tabIndex;var S=Ce(a,l,y);return S.appendChild(Ce("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),this.createControlTextEl(S),S},d.dispose=function(){this.controlTextEl_=null,g.prototype.dispose.call(this)},d.createControlTextEl=function(a){return this.controlTextEl_=Ce("span",{className:"vjs-control-text"},{"aria-live":"polite"}),a&&a.appendChild(this.controlTextEl_),this.controlText(this.controlText_,a),this.controlTextEl_},d.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,Oe(this.controlTextEl_,y),!this.nonIconControl&&!this.player_.options_.noUITitleAttributes&&l.setAttribute("title",y)},d.buildCSSClass=function(){return"vjs-control vjs-button "+g.prototype.buildCSSClass.call(this)},d.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_))},d.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_)},d.handleLanguagechange=function(){this.controlText(this.controlText_)},d.handleClick=function(a){this.options_.clickHandler&&this.options_.clickHandler.call(this,arguments)},d.handleKeyDown=function(a){w.default.isEventKey(a,"Space")||w.default.isEventKey(a,"Enter")?(a.preventDefault(),a.stopPropagation(),this.trigger("click")):g.prototype.handleKeyDown.call(this,a)},v}(de);de.registerComponent("ClickableComponent",hr);var pm=function(g){A.default(v,g);function v(c,a){var l;return l=g.call(this,c,a)||this,l.update(),l.update_=function(y){return l.update(y)},c.on("posterchange",l.update_),l}var d=v.prototype;return d.dispose=function(){this.player().off("posterchange",this.update_),g.prototype.dispose.call(this)},d.createEl=function(){var a=Ce("div",{className:"vjs-poster",tabIndex:-1});return a},d.update=function(a){var l=this.player().poster();this.setSrc(l),l?this.show():this.hide()},d.setSrc=function(a){var l="";a&&(l='url("'+a+'")'),this.el_.style.backgroundImage=l},d.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)&&!((Ot||wi)&&l)&&this.player_.tech(!0).focus(),this.player_.paused()?ri(this.player_.play()):this.player_.pause()}},v}(hr);de.registerComponent("PosterImage",pm);var Ht="#222",ac="#ccc",gm={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 Xa(g,v){var d;if(g.length===4)d=g[1]+g[1]+g[2]+g[2]+g[3]+g[3];else if(g.length===7)d=g.slice(1);else throw new Error("Invalid color code provided, "+g+"; must be formatted as e.g. #f0e or #f604e2.");return"rgba("+parseInt(d.slice(0,2),16)+","+parseInt(d.slice(2,4),16)+","+parseInt(d.slice(4,6),16)+","+v+")"}function Qa(g,v,d){try{g.style[v]=d}catch{return}}var mm=function(g){A.default(v,g);function v(c,a,l){var y;y=g.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(Ye(L.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 d=v.prototype;return d.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")},d.toggleDisplay=function(){this.player_.tech_&&this.player_.tech_.featuresNativeTextTracks?this.hide():this.show()},d.createEl=function(){return g.prototype.createEl.call(this,"div",{className:"vjs-text-track-display"},{translate:"yes","aria-live":"off","aria-atomic":"true"})},d.clearDisplay=function(){typeof T.default.WebVTT=="function"&&T.default.WebVTT.processCues(T.default,[],this.el_)},d.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))},d.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&&Qa(U.firstChild,"color",Xa(l.color||"#fff",l.textOpacity)),l.backgroundColor&&(U.firstChild.style.backgroundColor=l.backgroundColor),l.backgroundOpacity&&Qa(U.firstChild,"backgroundColor",Xa(l.backgroundColor||"#000",l.backgroundOpacity)),l.windowColor&&(l.windowOpacity?Qa(U,"backgroundColor",Xa(l.windowColor,l.windowOpacity)):U.style.backgroundColor=l.windowColor),l.edgeStyle&&(l.edgeStyle==="dropshadow"?U.firstChild.style.textShadow="2px 2px 3px "+Ht+", 2px 2px 4px "+Ht+", 2px 2px 5px "+Ht:l.edgeStyle==="raised"?U.firstChild.style.textShadow="1px 1px "+Ht+", 2px 2px "+Ht+", 3px 3px "+Ht:l.edgeStyle==="depressed"?U.firstChild.style.textShadow="1px 1px "+ac+", 0 1px "+ac+", -1px -1px "+Ht+", 0 -1px "+Ht:l.edgeStyle==="uniform"&&(U.firstChild.style.textShadow="0 0 4px "+Ht+", 0 0 4px "+Ht+", 0 0 4px "+Ht+", 0 0 4px "+Ht)),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=gm[l.fontFamily])}}},d.updateForTrack=function(a){if(Array.isArray(a)||(a=[a]),!(typeof T.default.WebVTT!="function"||a.every(function(ue){return!ue.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;Wt(j,"vjs-text-track-cue"),Wt(j,"vjs-text-track-cue-"+(V.language?V.language:U)),V.language&&ji(j,"lang",V.language)}this.player_.textTrackSettings&&this.updateDisplayState(V)}}},v}(de);de.registerComponent("TextTrackDisplay",mm);var ym=function(g){A.default(v,g);function v(){return g.apply(this,arguments)||this}var d=v.prototype;return d.createEl=function(){var a=this.player_.isAudio(),l=this.localize(a?"Audio Player":"Video Player"),y=Ce("span",{className:"vjs-control-text",textContent:this.localize("{1} is loading.",[l])}),S=g.prototype.createEl.call(this,"div",{className:"vjs-loading-spinner",dir:"ltr"});return S.appendChild(y),S},v}(de);de.registerComponent("LoadingSpinner",ym);var Xt=function(g){A.default(v,g);function v(){return g.apply(this,arguments)||this}var d=v.prototype;return d.createEl=function(a,l,y){l===void 0&&(l={}),y===void 0&&(y={}),a="button",l=Pe({className:this.buildCSSClass()},l),y=Pe({type:"button"},y);var S=Ce(a,l,y);return S.appendChild(Ce("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),this.createControlTextEl(S),S},d.addChild=function(a,l){l===void 0&&(l={});var y=this.constructor.name;return re.warn("Adding an actionable (user controllable) child to a Button ("+y+") is not supported; use a ClickableComponent instead."),de.prototype.addChild.call(this,a,l)},d.enable=function(){g.prototype.enable.call(this),this.el_.removeAttribute("disabled")},d.disable=function(){g.prototype.disable.call(this),this.el_.setAttribute("disabled","disabled")},d.handleKeyDown=function(a){if(w.default.isEventKey(a,"Space")||w.default.isEventKey(a,"Enter")){a.stopPropagation();return}g.prototype.handleKeyDown.call(this,a)},v}(hr);de.registerComponent("Button",Xt);var oc=function(g){A.default(v,g);function v(c,a){var l;return l=g.call(this,c,a)||this,l.mouseused_=!1,l.on("mousedown",function(y){return l.handleMouseDown(y)}),l}var d=v.prototype;return d.buildCSSClass=function(){return"vjs-big-play-button"},d.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;ri(l),this.player_.tech(!0)&&!((Ot||wi)&&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()};Ss(l)?l.then(U,function(){}):this.setTimeout(U,1)},d.handleKeyDown=function(a){this.mouseused_=!1,g.prototype.handleKeyDown.call(this,a)},d.handleMouseDown=function(a){this.mouseused_=!0},v}(Xt);oc.prototype.controlText_="Play Video",de.registerComponent("BigPlayButton",oc);var vm=function(g){A.default(v,g);function v(c,a){var l;return l=g.call(this,c,a)||this,l.controlText(a&&a.controlText||l.localize("Close")),l}var d=v.prototype;return d.buildCSSClass=function(){return"vjs-close-button "+g.prototype.buildCSSClass.call(this)},d.handleClick=function(a){this.trigger({type:"close",bubbles:!1})},d.handleKeyDown=function(a){w.default.isEventKey(a,"Esc")?(a.preventDefault(),a.stopPropagation(),this.trigger("click")):g.prototype.handleKeyDown.call(this,a)},v}(Xt);de.registerComponent("CloseButton",vm);var lc=function(g){A.default(v,g);function v(c,a){var l;return a===void 0&&(a={}),l=g.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 d=v.prototype;return d.buildCSSClass=function(){return"vjs-play-control "+g.prototype.buildCSSClass.call(this)},d.handleClick=function(a){this.player_.paused()?ri(this.player_.play()):this.player_.pause()},d.handleSeeked=function(a){this.removeClass("vjs-ended"),this.player_.paused()?this.handlePause(a):this.handlePlay(a)},d.handlePlay=function(a){this.removeClass("vjs-ended"),this.removeClass("vjs-paused"),this.addClass("vjs-playing"),this.controlText("Pause")},d.handlePause=function(a){this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.controlText("Play")},d.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}(Xt);lc.prototype.controlText_="Play",de.registerComponent("PlayToggle",lc);var uc=function(v,d){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(d/60%60),S=Math.floor(d/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},Ja=uc;function Tm(g){Ja=g}function _m(){Ja=uc}function Vn(g,v){return v===void 0&&(v=g),Ja(g,v)}var Gn=function(g){A.default(v,g);function v(c,a){var l;return l=g.call(this,c,a)||this,l.on(c,["timeupdate","ended"],function(y){return l.updateContent(y)}),l.updateTextNode_(),l}var d=v.prototype;return d.createEl=function(){var a=this.buildCSSClass(),l=g.prototype.createEl.call(this,"div",{className:a+" vjs-time-control vjs-control"}),y=Ce("span",{className:"vjs-control-text",textContent:this.localize(this.labelText_)+" "},{role:"presentation"});return l.appendChild(y),this.contentEl_=Ce("span",{className:a+"-display"},{"aria-live":"off",role:"presentation"}),l.appendChild(this.contentEl_),l},d.dispose=function(){this.contentEl_=null,this.textNode_=null,g.prototype.dispose.call(this)},d.updateTextNode_=function(a){var l=this;a===void 0&&(a=0),a=Vn(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,re.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_=_.default.createTextNode(l.formattedTime_),l.textNode_&&(y?l.contentEl_.replaceChild(l.textNode_,y):l.contentEl_.appendChild(l.textNode_))}}))},d.updateContent=function(a){},v}(de);Gn.prototype.labelText_="Time",Gn.prototype.controlText_="Time",de.registerComponent("TimeDisplay",Gn);var Za=function(g){A.default(v,g);function v(){return g.apply(this,arguments)||this}var d=v.prototype;return d.buildCSSClass=function(){return"vjs-current-time"},d.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}(Gn);Za.prototype.labelText_="Current Time",Za.prototype.controlText_="Current Time",de.registerComponent("CurrentTimeDisplay",Za);var eo=function(g){A.default(v,g);function v(c,a){var l;l=g.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 d=v.prototype;return d.buildCSSClass=function(){return"vjs-duration"},d.updateContent=function(a){var l=this.player_.duration();this.updateTextNode_(l)},v}(Gn);eo.prototype.labelText_="Duration",eo.prototype.controlText_="Duration",de.registerComponent("DurationDisplay",eo);var Em=function(g){A.default(v,g);function v(){return g.apply(this,arguments)||this}var d=v.prototype;return d.createEl=function(){var a=g.prototype.createEl.call(this,"div",{className:"vjs-time-control vjs-time-divider"},{"aria-hidden":!0}),l=g.prototype.createEl.call(this,"div"),y=g.prototype.createEl.call(this,"span",{textContent:"/"});return l.appendChild(y),a.appendChild(l),a},v}(de);de.registerComponent("TimeDivider",Em);var to=function(g){A.default(v,g);function v(c,a){var l;return l=g.call(this,c,a)||this,l.on(c,"durationchange",function(y){return l.updateContent(y)}),l}var d=v.prototype;return d.buildCSSClass=function(){return"vjs-remaining-time"},d.createEl=function(){var a=g.prototype.createEl.call(this);return this.options_.displayNegative!==!1&&a.insertBefore(Ce("span",{},{"aria-hidden":!0},"-"),this.contentEl_),a},d.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}(Gn);to.prototype.labelText_="Remaining Time",to.prototype.controlText_="Remaining Time",de.registerComponent("RemainingTimeDisplay",to);var bm=function(g){A.default(v,g);function v(c,a){var l;return l=g.call(this,c,a)||this,l.updateShowing(),l.on(l.player(),"durationchange",function(y){return l.updateShowing(y)}),l}var d=v.prototype;return d.createEl=function(){var a=g.prototype.createEl.call(this,"div",{className:"vjs-live-control vjs-control"});return this.contentEl_=Ce("div",{className:"vjs-live-display"},{"aria-live":"off"}),this.contentEl_.appendChild(Ce("span",{className:"vjs-control-text",textContent:this.localize("Stream Type")+" "})),this.contentEl_.appendChild(_.default.createTextNode(this.localize("LIVE"))),a.appendChild(this.contentEl_),a},d.dispose=function(){this.contentEl_=null,g.prototype.dispose.call(this)},d.updateShowing=function(a){this.player().duration()===1/0?this.show():this.hide()},v}(de);de.registerComponent("LiveDisplay",bm);var cc=function(g){A.default(v,g);function v(c,a){var l;return l=g.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 d=v.prototype;return d.createEl=function(){var a=g.prototype.createEl.call(this,"button",{className:"vjs-seek-to-live-control vjs-control"});return this.textEl_=Ce("span",{className:"vjs-seek-to-live-text",textContent:this.localize("LIVE")},{"aria-hidden":"true"}),a.appendChild(this.textEl_),a},d.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"))},d.handleClick=function(){this.player_.liveTracker.seekToLiveEdge()},d.dispose=function(){this.player_.liveTracker&&this.off(this.player_.liveTracker,"liveedgechange",this.updateLiveEdgeStatusHandler_),this.textEl_=null,g.prototype.dispose.call(this)},v}(Xt);cc.prototype.controlText_="Seek to live, currently playing live",de.registerComponent("SeekToLive",cc);var dr=function(v,d,c){return v=Number(v),Math.min(c,Math.max(d,isNaN(v)?d:v))},io=function(g){A.default(v,g);function v(c,a){var l;return l=g.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 d=v.prototype;return d.enabled=function(){return this.enabled_},d.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)},d.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}},d.createEl=function(a,l,y){return l===void 0&&(l={}),y===void 0&&(y={}),l.className=l.className+" vjs-slider",l=Pe({tabIndex:0},l),y=Pe({role:"slider","aria-valuenow":0,"aria-valuemin":0,"aria-valuemax":100,tabIndex:0},y),g.prototype.createEl.call(this,a,l,y)},d.handleMouseDown=function(a){var l=this.bar.el_.ownerDocument;a.type==="mousedown"&&a.preventDefault(),a.type==="touchstart"&&!Mt&&a.preventDefault(),Ws(),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)},d.handleMouseMove=function(a){},d.handleMouseUp=function(){var a=this.bar.el_.ownerDocument;zs(),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()},d.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}},d.getProgress=function(){return Number(dr(this.getPercent(),0,1).toFixed(4))},d.calculateDistance=function(a){var l=hn(this.el_,a);return this.vertical()?l.y:l.x},d.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()):g.prototype.handleKeyDown.call(this,a)},d.handleClick=function(a){a.stopPropagation(),a.preventDefault()},d.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}(de);de.registerComponent("Slider",io);var no=function(v,d){return dr(v/d*100,0,100).toFixed(2)+"%"},Sm=function(g){A.default(v,g);function v(c,a){var l;return l=g.call(this,c,a)||this,l.partEls_=[],l.on(c,"progress",function(y){return l.update(y)}),l}var d=v.prototype;return d.createEl=function(){var a=g.prototype.createEl.call(this,"div",{className:"vjs-load-progress"}),l=Ce("span",{className:"vjs-control-text"}),y=Ce("span",{textContent:this.localize("Loaded")}),S=_.default.createTextNode(": ");return this.percentageEl_=Ce("span",{className:"vjs-control-text-loaded-percentage",textContent:"0%"}),a.appendChild(l),l.appendChild(y),l.appendChild(S),l.appendChild(this.percentageEl_),a},d.dispose=function(){this.partEls_=null,this.percentageEl_=null,g.prototype.dispose.call(this)},d.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=no(U,x);l.percent_!==z&&(l.el_.style.width=z,Oe(l.percentageEl_,z),l.percent_=z);for(var j=0;j<S.length;j++){var ue=S.start(j),_e=S.end(j),Fe=V[j];Fe||(Fe=l.el_.appendChild(Ce()),V[j]=Fe),!(Fe.dataset.start===ue&&Fe.dataset.end===_e)&&(Fe.dataset.start=ue,Fe.dataset.end=_e,Fe.style.left=no(ue,U),Fe.style.width=no(_e-ue,U))}for(var vn=V.length;vn>S.length;vn--)l.el_.removeChild(V[vn-1]);V.length=S.length})},v}(de);de.registerComponent("LoadProgressBar",Sm);var Cm=function(g){A.default(v,g);function v(c,a){var l;return l=g.call(this,c,a)||this,l.update=zt(Ye(L.default(l),l.update),It),l}var d=v.prototype;return d.createEl=function(){return g.prototype.createEl.call(this,"div",{className:"vjs-time-tooltip"},{"aria-hidden":"true"})},d.update=function(a,l,y){var S=ni(this.el_),x=Vi(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)}},d.write=function(a){Oe(this.el_,a)},d.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?"":"-")+Vn(j,z)}else U=Vn(y,V);x.update(a,l,U),S&&S()})},v}(de);de.registerComponent("TimeTooltip",Cm);var so=function(g){A.default(v,g);function v(c,a){var l;return l=g.call(this,c,a)||this,l.update=zt(Ye(L.default(l),l.update),It),l}var d=v.prototype;return d.createEl=function(){return g.prototype.createEl.call(this,"div",{className:"vjs-play-progress vjs-slider-bar"},{"aria-hidden":"true"})},d.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}(de);so.prototype.options_={children:[]},!R&&!lt&&so.prototype.options_.children.push("timeTooltip"),de.registerComponent("PlayProgressBar",so);var hc=function(g){A.default(v,g);function v(c,a){var l;return l=g.call(this,c,a)||this,l.update=zt(Ye(L.default(l),l.update),It),l}var d=v.prototype;return d.createEl=function(){return g.prototype.createEl.call(this,"div",{className:"vjs-mouse-display"})},d.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}(de);hc.prototype.options_={children:["timeTooltip"]},de.registerComponent("MouseTimeDisplay",hc);var fr=5,dc=12,ro=function(g){A.default(v,g);function v(c,a){var l;return l=g.call(this,c,a)||this,l.setEventHandlers_(),l}var d=v.prototype;return d.setEventHandlers_=function(){var a=this;this.update_=Ye(this,this.update),this.update=zt(this.update_,It),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 _.default&&"visibilityState"in _.default&&this.on(_.default,"visibilitychange",this.toggleVisibility_)},d.toggleVisibility_=function(a){_.default.visibilityState==="hidden"?(this.cancelNamedAnimationFrame("SeekBar#update"),this.cancelNamedAnimationFrame("Slider#update"),this.disableInterval_(a)):(!this.player_.ended()&&!this.player_.paused()&&this.enableInterval_(),this.update())},d.enableInterval_=function(){this.updateInterval||(this.updateInterval=this.setInterval(this.update,It))},d.disableInterval_=function(a){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&a&&a.type!=="ended"||this.updateInterval&&(this.clearInterval(this.updateInterval),this.updateInterval=null)},d.createEl=function(){return g.prototype.createEl.call(this,"div",{className:"vjs-progress-holder"},{"aria-label":this.localize("Progress Bar")})},d.update=function(a){var l=this;if(_.default.visibilityState!=="hidden"){var y=g.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}",[Vn(S,U),Vn(U,U)],"{1} of {2}")),l.currentTime_=S,l.duration_=U),l.bar&&l.bar.update(Vi(l.el()),l.getProgress())}),y}},d.userSeek_=function(a){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&this.player_.liveTracker.nextSeekedFromUser(),this.player_.currentTime(a)},d.getCurrentTime_=function(){return this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime()},d.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},d.handleMouseDown=function(a){Gi(a)&&(a.stopPropagation(),this.videoWasPlaying=!this.player_.paused(),this.player_.pause(),g.prototype.handleMouseDown.call(this,a))},d.handleMouseMove=function(a,l){if(l===void 0&&(l=!1),!!Gi(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)}},d.enable=function(){g.prototype.enable.call(this);var a=this.getChild("mouseTimeDisplay");a&&a.show()},d.disable=function(){g.prototype.disable.call(this);var a=this.getChild("mouseTimeDisplay");a&&a.hide()},d.handleMouseUp=function(a){g.prototype.handleMouseUp.call(this,a),a&&a.stopPropagation(),this.player_.scrubbing(!1),this.player_.trigger({type:"timeupdate",target:this,manuallyTriggered:!0}),this.videoWasPlaying?ri(this.player_.play()):this.update_()},d.stepForward=function(){this.userSeek_(this.player_.currentTime()+fr)},d.stepBack=function(){this.userSeek_(this.player_.currentTime()-fr)},d.handleAction=function(a){this.player_.paused()?this.player_.play():this.player_.pause()},d.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()-fr*dc)):w.default.isEventKey(a,"PgUp")?(a.preventDefault(),a.stopPropagation(),this.userSeek_(this.player_.currentTime()+fr*dc)):g.prototype.handleKeyDown.call(this,a)},d.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 _.default&&"visibilityState"in _.default&&this.off(_.default,"visibilitychange",this.toggleVisibility_),g.prototype.dispose.call(this)},v}(io);ro.prototype.options_={children:["loadProgressBar","playProgressBar"],barName:"playProgressBar"},!R&&!lt&&ro.prototype.options_.children.splice(1,0,"mouseTimeDisplay"),de.registerComponent("SeekBar",ro);var fc=function(g){A.default(v,g);function v(c,a){var l;return l=g.call(this,c,a)||this,l.handleMouseMove=zt(Ye(L.default(l),l.handleMouseMove),It),l.throttledHandleMouseSeek=zt(Ye(L.default(l),l.handleMouseSeek),It),l.handleMouseUpHandler_=function(y){return l.handleMouseUp(y)},l.handleMouseDownHandler_=function(y){return l.handleMouseDown(y)},l.enable(),l}var d=v.prototype;return d.createEl=function(){return g.prototype.createEl.call(this,"div",{className:"vjs-progress-control vjs-control"})},d.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=ni(x),V=hn(x,a).x;V=dr(V,0,1),S&&S.update(U,V),y&&y.update(U,l.getProgress())}}},d.handleMouseSeek=function(a){var l=this.getChild("seekBar");l&&l.handleMouseMove(a)},d.enabled=function(){return this.enabled_},d.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&&ri(this.player_.play())}},d.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)},d.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_)},d.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_)},d.handleMouseUp=function(a){var l=this.getChild("seekBar");l&&l.handleMouseUp(a),this.removeListenersAddedOnMousedownAndTouchstart()},v}(de);fc.prototype.options_={children:["seekBar"]},de.registerComponent("ProgressControl",fc);var pc=function(g){A.default(v,g);function v(c,a){var l;return l=g.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 d=v.prototype;return d.buildCSSClass=function(){return"vjs-picture-in-picture-control "+g.prototype.buildCSSClass.call(this)},d.handlePictureInPictureEnabledChange=function(){_.default.pictureInPictureEnabled&&this.player_.disablePictureInPicture()===!1?this.enable():this.disable()},d.handlePictureInPictureChange=function(a){this.player_.isInPictureInPicture()?this.controlText("Exit Picture-in-Picture"):this.controlText("Picture-in-Picture"),this.handlePictureInPictureEnabledChange()},d.handleClick=function(a){this.player_.isInPictureInPicture()?this.player_.exitPictureInPicture():this.player_.requestPictureInPicture()},v}(Xt);pc.prototype.controlText_="Picture-in-Picture",de.registerComponent("PictureInPictureToggle",pc);var gc=function(g){A.default(v,g);function v(c,a){var l;return l=g.call(this,c,a)||this,l.on(c,"fullscreenchange",function(y){return l.handleFullscreenChange(y)}),_.default[c.fsApi_.fullscreenEnabled]===!1&&l.disable(),l}var d=v.prototype;return d.buildCSSClass=function(){return"vjs-fullscreen-control "+g.prototype.buildCSSClass.call(this)},d.handleFullscreenChange=function(a){this.player_.isFullscreen()?this.controlText("Non-Fullscreen"):this.controlText("Fullscreen")},d.handleClick=function(a){this.player_.isFullscreen()?this.player_.exitFullscreen():this.player_.requestFullscreen()},v}(Xt);gc.prototype.controlText_="Fullscreen",de.registerComponent("FullscreenToggle",gc);var wm=function(v,d){d.tech_&&!d.tech_.featuresVolumeControl&&v.addClass("vjs-hidden"),v.on(d,"loadstart",function(){d.tech_.featuresVolumeControl?v.removeClass("vjs-hidden"):v.addClass("vjs-hidden")})},Lm=function(g){A.default(v,g);function v(){return g.apply(this,arguments)||this}var d=v.prototype;return d.createEl=function(){var a=g.prototype.createEl.call(this,"div",{className:"vjs-volume-level"});return a.appendChild(g.prototype.createEl.call(this,"span",{className:"vjs-control-text"})),a},v}(de);de.registerComponent("VolumeLevel",Lm);var Am=function(g){A.default(v,g);function v(c,a){var l;return l=g.call(this,c,a)||this,l.update=zt(Ye(L.default(l),l.update),It),l}var d=v.prototype;return d.createEl=function(){return g.prototype.createEl.call(this,"div",{className:"vjs-volume-tooltip"},{"aria-hidden":"true"})},d.update=function(a,l,y,S){if(!y){var x=Vi(this.el_),U=Vi(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),ue=x.width/2;z<ue?ue+=ue-z:j<ue&&(ue=j),ue<0?ue=0:ue>x.width&&(ue=x.width),this.el_.style.right="-"+ue+"px"}this.write(S+"%")},d.write=function(a){Oe(this.el_,a)},d.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}(de);de.registerComponent("VolumeLevelTooltip",Am);var mc=function(g){A.default(v,g);function v(c,a){var l;return l=g.call(this,c,a)||this,l.update=zt(Ye(L.default(l),l.update),It),l}var d=v.prototype;return d.createEl=function(){return g.prototype.createEl.call(this,"div",{className:"vjs-mouse-display"})},d.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}(de);mc.prototype.options_={children:["volumeLevelTooltip"]},de.registerComponent("MouseVolumeLevelDisplay",mc);var pr=function(g){A.default(v,g);function v(c,a){var l;return l=g.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 d=v.prototype;return d.createEl=function(){return g.prototype.createEl.call(this,"div",{className:"vjs-volume-bar vjs-slider-bar"},{"aria-label":this.localize("Volume Level"),"aria-live":"polite"})},d.handleMouseDown=function(a){Gi(a)&&g.prototype.handleMouseDown.call(this,a)},d.handleMouseMove=function(a){var l=this.getChild("mouseVolumeLevelDisplay");if(l){var y=this.el(),S=Vi(y),x=this.vertical(),U=hn(y,a);U=x?U.y:U.x,U=dr(U,0,1),l.update(S,U,x)}Gi(a)&&(this.checkMuted(),this.player_.volume(this.calculateDistance(a)))},d.checkMuted=function(){this.player_.muted()&&this.player_.muted(!1)},d.getPercent=function(){return this.player_.muted()?0:this.player_.volume()},d.stepForward=function(){this.checkMuted(),this.player_.volume(this.player_.volume()+.1)},d.stepBack=function(){this.checkMuted(),this.player_.volume(this.player_.volume()-.1)},d.updateARIAAttributes=function(a){var l=this.player_.muted()?0:this.volumeAsPercentage_();this.el_.setAttribute("aria-valuenow",l),this.el_.setAttribute("aria-valuetext",l+"%")},d.volumeAsPercentage_=function(){return Math.round(this.player_.volume()*100)},d.updateLastVolume_=function(){var a=this,l=this.player_.volume();this.one("sliderinactive",function(){a.player_.volume()===0&&a.player_.lastVolume_(l)})},v}(io);pr.prototype.options_={children:["volumeLevel"],barName:"volumeLevel"},!R&&!lt&&pr.prototype.options_.children.splice(0,0,"mouseVolumeLevelDisplay"),pr.prototype.playerEvent="volumechange",de.registerComponent("VolumeBar",pr);var yc=function(g){A.default(v,g);function v(c,a){var l;return a===void 0&&(a={}),a.vertical=a.vertical||!1,(typeof a.volumeBar>"u"||it(a.volumeBar))&&(a.volumeBar=a.volumeBar||{},a.volumeBar.vertical=a.vertical),l=g.call(this,c,a)||this,wm(L.default(l),c),l.throttledHandleMouseMove=zt(Ye(L.default(l),l.handleMouseMove),It),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 d=v.prototype;return d.createEl=function(){var a="vjs-volume-horizontal";return this.options_.vertical&&(a="vjs-volume-vertical"),g.prototype.createEl.call(this,"div",{className:"vjs-volume-control vjs-control "+a})},d.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_)},d.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_)},d.handleMouseMove=function(a){this.volumeBar.handleMouseMove(a)},v}(de);yc.prototype.options_={children:["volumeBar"]},de.registerComponent("VolumeControl",yc);var km=function(v,d){d.tech_&&!d.tech_.featuresMuteControl&&v.addClass("vjs-hidden"),v.on(d,"loadstart",function(){d.tech_.featuresMuteControl?v.removeClass("vjs-hidden"):v.addClass("vjs-hidden")})},vc=function(g){A.default(v,g);function v(c,a){var l;return l=g.call(this,c,a)||this,km(L.default(l),c),l.on(c,["loadstart","volumechange"],function(y){return l.update(y)}),l}var d=v.prototype;return d.buildCSSClass=function(){return"vjs-mute-control "+g.prototype.buildCSSClass.call(this)},d.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())},d.update=function(a){this.updateIcon_(),this.updateControlText_()},d.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++)cn(this.el_,"vjs-vol-"+y);Wt(this.el_,"vjs-vol-"+l)},d.updateControlText_=function(){var a=this.player_.muted()||this.player_.volume()===0,l=a?"Unmute":"Mute";this.controlText()!==l&&this.controlText(l)},v}(Xt);vc.prototype.controlText_="Mute",de.registerComponent("MuteToggle",vc);var Tc=function(g){A.default(v,g);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"||it(a.volumeControl))&&(a.volumeControl=a.volumeControl||{},a.volumeControl.vertical=!a.inline),l=g.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 d=v.prototype;return d.sliderActive_=function(){this.addClass("vjs-slider-active")},d.sliderInactive_=function(){this.removeClass("vjs-slider-active")},d.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")},d.createEl=function(){var a="vjs-volume-panel-horizontal";return this.options_.inline||(a="vjs-volume-panel-vertical"),g.prototype.createEl.call(this,"div",{className:"vjs-volume-panel vjs-control "+a})},d.dispose=function(){this.handleMouseOut(),g.prototype.dispose.call(this)},d.handleVolumeControlKeyUp=function(a){w.default.isEventKey(a,"Esc")&&this.muteToggle.focus()},d.handleMouseOver=function(a){this.addClass("vjs-hover"),Lt(_.default,"keyup",this.handleKeyPressHandler_)},d.handleMouseOut=function(a){this.removeClass("vjs-hover"),dt(_.default,"keyup",this.handleKeyPressHandler_)},d.handleKeyPress=function(a){w.default.isEventKey(a,"Esc")&&this.handleMouseOut()},v}(de);Tc.prototype.options_={children:["muteToggle","volumeControl"]},de.registerComponent("VolumePanel",Tc);var _c=function(g){A.default(v,g);function v(c,a){var l;return l=g.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 d=v.prototype;return d.addEventListenerForItem=function(a){a instanceof de&&(this.on(a,"blur",this.boundHandleBlur_),this.on(a,["tap","click"],this.boundHandleTapClick_))},d.removeEventListenerForItem=function(a){a instanceof de&&(this.off(a,"blur",this.boundHandleBlur_),this.off(a,["tap","click"],this.boundHandleTapClick_))},d.removeChild=function(a){typeof a=="string"&&(a=this.getChild(a)),this.removeEventListenerForItem(a),g.prototype.removeChild.call(this,a)},d.addItem=function(a){var l=this.addChild(a);l&&this.addEventListenerForItem(l)},d.createEl=function(){var a=this.options_.contentElType||"ul";this.contentEl_=Ce(a,{className:"vjs-menu-content"}),this.contentEl_.setAttribute("role","menu");var l=g.prototype.createEl.call(this,"div",{append:this.contentEl_,className:"vjs-menu"});return l.appendChild(this.contentEl_),Lt(l,"click",function(y){y.preventDefault(),y.stopImmediatePropagation()}),l},d.dispose=function(){this.contentEl_=null,this.boundHandleBlur_=null,this.boundHandleTapClick_=null,g.prototype.dispose.call(this)},d.handleBlur=function(a){var l=a.relatedTarget||_.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()}},d.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()}},d.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())},d.stepForward=function(){var a=0;this.focusedChild_!==void 0&&(a=this.focusedChild_+1),this.focus(a)},d.stepBack=function(){var a=0;this.focusedChild_!==void 0&&(a=this.focusedChild_-1),this.focus(a)},d.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}(de);de.registerComponent("Menu",_c);var ao=function(g){A.default(v,g);function v(c,a){var l;a===void 0&&(a={}),l=g.call(this,c,a)||this,l.menuButton_=new Xt(c,a),l.menuButton_.controlText(l.controlText_),l.menuButton_.el_.setAttribute("aria-haspopup","true");var y=Xt.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(),Lt(_.default,"keyup",l.handleMenuKeyUp_)}),l.on("mouseleave",function(x){return l.handleMouseLeave(x)}),l.on("keydown",function(x){return l.handleSubmenuKeyDown(x)}),l}var d=v.prototype;return d.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"))},d.createMenu=function(){var a=new _c(this.player_,{menuButton:this});if(this.hideThreshold_=0,this.options_.title){var l=Ce("li",{className:"vjs-menu-title",textContent:rt(this.options_.title),tabIndex:-1}),y=new de(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},d.createItems=function(){},d.createEl=function(){return g.prototype.createEl.call(this,"div",{className:this.buildWrapperCSSClass()},{})},d.buildWrapperCSSClass=function(){var a="vjs-menu-button";this.options_.inline===!0?a+="-inline":a+="-popup";var l=Xt.prototype.buildCSSClass();return"vjs-menu-button "+a+" "+l+" "+g.prototype.buildCSSClass.call(this)},d.buildCSSClass=function(){var a="vjs-menu-button";return this.options_.inline===!0?a+="-inline":a+="-popup","vjs-menu-button "+a+" "+g.prototype.buildCSSClass.call(this)},d.controlText=function(a,l){return l===void 0&&(l=this.menuButton_.el()),this.menuButton_.controlText(a,l)},d.dispose=function(){this.handleMouseLeave(),g.prototype.dispose.call(this)},d.handleClick=function(a){this.buttonPressed_?this.unpressButton():this.pressButton()},d.handleMouseLeave=function(a){this.removeClass("vjs-hover"),dt(_.default,"keyup",this.handleMenuKeyUp_)},d.focus=function(){this.menuButton_.focus()},d.blur=function(){this.menuButton_.blur()},d.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()))},d.handleMenuKeyUp=function(a){(w.default.isEventKey(a,"Esc")||w.default.isEventKey(a,"Tab"))&&this.removeClass("vjs-hover")},d.handleSubmenuKeyPress=function(a){this.handleSubmenuKeyDown(a)},d.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()))},d.pressButton=function(){if(this.enabled_){if(this.buttonPressed_=!0,this.menu.show(),this.menu.lockShowing(),this.menuButton_.el_.setAttribute("aria-expanded","true"),R&&ze())return;this.menu.focus()}},d.unpressButton=function(){this.enabled_&&(this.buttonPressed_=!1,this.menu.unlockShowing(),this.menu.hide(),this.menuButton_.el_.setAttribute("aria-expanded","false"))},d.disable=function(){this.unpressButton(),this.enabled_=!1,this.addClass("vjs-disabled"),this.menuButton_.disable()},d.enable=function(){this.enabled_=!0,this.removeClass("vjs-disabled"),this.menuButton_.enable()},v}(de);de.registerComponent("MenuButton",ao);var oo=function(g){A.default(v,g);function v(d,c){var a,l=c.tracks;if(a=g.call(this,d,c)||this,a.items.length<=1&&a.hide(),!l)return L.default(a);var y=Ye(L.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}(ao);de.registerComponent("TrackButton",oo);var Im=["Tab","Esc","Up","Down","Right","Left"],ws=function(g){A.default(v,g);function v(c,a){var l;return l=g.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 d=v.prototype;return d.createEl=function(a,l,y){this.nonIconControl=!0;var S=g.prototype.createEl.call(this,"li",Pe({className:"vjs-menu-item",tabIndex:-1},l),y);return S.replaceChild(Ce("span",{className:"vjs-menu-item-text",textContent:this.localize(this.options_.label)}),S.querySelector(".vjs-icon-placeholder")),S},d.handleKeyDown=function(a){Im.some(function(l){return w.default.isEventKey(a,l)})||g.prototype.handleKeyDown.call(this,a)},d.handleClick=function(a){this.selected(!0)},d.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}(hr);de.registerComponent("MenuItem",ws);var Ls=function(g){A.default(v,g);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=g.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,ue=new Array(j),_e=0;_e<j;_e++)ue[_e]=arguments[_e];l.handleTracksChange.apply(L.default(l),ue)},U=function(){for(var j=arguments.length,ue=new Array(j),_e=0;_e<j;_e++)ue[_e]=arguments[_e];l.handleSelectedLanguageChange.apply(L.default(l),ue)};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=_.default.createEvent("Event"),V.initEvent("change",!0,!0)),S.dispatchEvent(V)})}return l.handleTracksChange(),l}var d=v.prototype;return d.handleClick=function(a){var l=this.track,y=this.player_.textTracks();if(g.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"))}},d.handleTracksChange=function(a){var l=this.track.mode==="showing";l!==this.isSelected_&&this.selected(l)},d.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}}},d.dispose=function(){this.track=null,g.prototype.dispose.call(this)},v}(ws);de.registerComponent("TextTrackMenuItem",Ls);var Ec=function(g){A.default(v,g);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,g.call(this,c,a)||this}var d=v.prototype;return d.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)},d.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}(Ls);de.registerComponent("OffTextTrackMenuItem",Ec);var Kn=function(g){A.default(v,g);function v(c,a){return a===void 0&&(a={}),a.tracks=c.textTracks(),g.call(this,c,a)||this}var d=v.prototype;return d.createItems=function(a,l){a===void 0&&(a=[]),l===void 0&&(l=Ls);var y;this.label_&&(y=this.label_+" off"),a.push(new Ec(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}(oo);de.registerComponent("TextTrackButton",Kn);var bc=function(g){A.default(v,g);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=g.call(this,c,a)||this,l.track=y,l.cue=S,l}var d=v.prototype;return d.handleClick=function(a){g.prototype.handleClick.call(this),this.player_.currentTime(this.cue.startTime)},v}(ws);de.registerComponent("ChaptersTrackMenuItem",bc);var lo=function(g){A.default(v,g);function v(c,a,l){var y;return y=g.call(this,c,a,l)||this,y.selectCurrentItem_=function(){y.items.forEach(function(S){S.selected(y.track_.activeCues[0]===S.cue)})},y}var d=v.prototype;return d.buildCSSClass=function(){return"vjs-chapters-button "+g.prototype.buildCSSClass.call(this)},d.buildWrapperCSSClass=function(){return"vjs-chapters-button "+g.prototype.buildWrapperCSSClass.call(this)},d.update=function(a){if(!(a&&a.track&&a.track.kind!=="chapters")){var l=this.findChaptersTrack();l!==this.track_?(this.setTrack(l),g.prototype.update.call(this)):(!this.items||l&&l.cues&&l.cues.length!==this.items.length)&&g.prototype.update.call(this)}},d.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_)}}},d.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}},d.getMenuCaption=function(){return this.track_&&this.track_.label?this.track_.label:this.localize(rt(this.kind_))},d.createMenu=function(){return this.options_.title=this.getMenuCaption(),g.prototype.createMenu.call(this)},d.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 bc(this.player_,{track:this.track_,cue:x});a.push(U)}return a},v}(Kn);lo.prototype.kind_="chapters",lo.prototype.controlText_="Chapters",de.registerComponent("ChaptersButton",lo);var uo=function(g){A.default(v,g);function v(c,a,l){var y;y=g.call(this,c,a,l)||this;var S=c.textTracks(),x=Ye(L.default(y),y.handleTracksChange);return S.addEventListener("change",x),y.on("dispose",function(){S.removeEventListener("change",x)}),y}var d=v.prototype;return d.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()},d.buildCSSClass=function(){return"vjs-descriptions-button "+g.prototype.buildCSSClass.call(this)},d.buildWrapperCSSClass=function(){return"vjs-descriptions-button "+g.prototype.buildWrapperCSSClass.call(this)},v}(Kn);uo.prototype.kind_="descriptions",uo.prototype.controlText_="Descriptions",de.registerComponent("DescriptionsButton",uo);var co=function(g){A.default(v,g);function v(c,a,l){return g.call(this,c,a,l)||this}var d=v.prototype;return d.buildCSSClass=function(){return"vjs-subtitles-button "+g.prototype.buildCSSClass.call(this)},d.buildWrapperCSSClass=function(){return"vjs-subtitles-button "+g.prototype.buildWrapperCSSClass.call(this)},v}(Kn);co.prototype.kind_="subtitles",co.prototype.controlText_="Subtitles",de.registerComponent("SubtitlesButton",co);var ho=function(g){A.default(v,g);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=g.call(this,c,a)||this,l.addClass("vjs-texttrack-settings"),l.controlText(", opens "+a.kind+" settings dialog"),l}var d=v.prototype;return d.handleClick=function(a){this.player().getChild("textTrackSettings").open()},v}(Ls);de.registerComponent("CaptionSettingsMenuItem",ho);var fo=function(g){A.default(v,g);function v(c,a,l){return g.call(this,c,a,l)||this}var d=v.prototype;return d.buildCSSClass=function(){return"vjs-captions-button "+g.prototype.buildCSSClass.call(this)},d.buildWrapperCSSClass=function(){return"vjs-captions-button "+g.prototype.buildWrapperCSSClass.call(this)},d.createItems=function(){var a=[];return!(this.player().tech_&&this.player().tech_.featuresNativeTextTracks)&&this.player().getChild("textTrackSettings")&&(a.push(new ho(this.player_,{kind:this.kind_})),this.hideThreshold_+=1),g.prototype.createItems.call(this,a)},v}(Kn);fo.prototype.kind_="captions",fo.prototype.controlText_="Captions",de.registerComponent("CaptionsButton",fo);var Sc=function(g){A.default(v,g);function v(){return g.apply(this,arguments)||this}var d=v.prototype;return d.createEl=function(a,l,y){var S=g.prototype.createEl.call(this,a,l,y),x=S.querySelector(".vjs-menu-item-text");return this.options_.track.kind==="captions"&&(x.appendChild(Ce("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),x.appendChild(Ce("span",{className:"vjs-control-text",textContent:" "+this.localize("Captions")}))),S},v}(Ls);de.registerComponent("SubsCapsMenuItem",Sc);var po=function(g){A.default(v,g);function v(c,a){var l;return a===void 0&&(a={}),l=g.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(rt(l.label_)),l}var d=v.prototype;return d.buildCSSClass=function(){return"vjs-subs-caps-button "+g.prototype.buildCSSClass.call(this)},d.buildWrapperCSSClass=function(){return"vjs-subs-caps-button "+g.prototype.buildWrapperCSSClass.call(this)},d.createItems=function(){var a=[];return!(this.player().tech_&&this.player().tech_.featuresNativeTextTracks)&&this.player().getChild("textTrackSettings")&&(a.push(new ho(this.player_,{kind:this.label_})),this.hideThreshold_+=1),a=g.prototype.createItems.call(this,a,Sc),a},v}(Kn);po.prototype.kinds_=["captions","subtitles"],po.prototype.controlText_="Subtitles",de.registerComponent("SubsCapsButton",po);var Cc=function(g){A.default(v,g);function v(c,a){var l,y=a.track,S=c.audioTracks();a.label=y.label||y.language||"Unknown",a.selected=y.enabled,l=g.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(L.default(l),z)};return S.addEventListener("change",x),l.on("dispose",function(){S.removeEventListener("change",x)}),l}var d=v.prototype;return d.createEl=function(a,l,y){var S=g.prototype.createEl.call(this,a,l,y),x=S.querySelector(".vjs-menu-item-text");return this.options_.track.kind==="main-desc"&&(x.appendChild(Ce("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),x.appendChild(Ce("span",{className:"vjs-control-text",textContent:" "+this.localize("Descriptions")}))),S},d.handleClick=function(a){if(g.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)}},d.handleTracksChange=function(a){this.selected(this.track.enabled)},v}(ws);de.registerComponent("AudioTrackMenuItem",Cc);var wc=function(g){A.default(v,g);function v(c,a){return a===void 0&&(a={}),a.tracks=c.audioTracks(),g.call(this,c,a)||this}var d=v.prototype;return d.buildCSSClass=function(){return"vjs-audio-button "+g.prototype.buildCSSClass.call(this)},d.buildWrapperCSSClass=function(){return"vjs-audio-button "+g.prototype.buildWrapperCSSClass.call(this)},d.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 Cc(this.player_,{track:S,selectable:!0,multiSelectable:!1}))}return a},v}(oo);wc.prototype.controlText_="Audio Track",de.registerComponent("AudioTrackButton",wc);var go=function(g){A.default(v,g);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=g.call(this,c,a)||this,l.label=y,l.rate=S,l.on(c,"ratechange",function(x){return l.update(x)}),l}var d=v.prototype;return d.handleClick=function(a){g.prototype.handleClick.call(this),this.player().playbackRate(this.rate)},d.update=function(a){this.selected(this.player().playbackRate()===this.rate)},v}(ws);go.prototype.contentElType="button",de.registerComponent("PlaybackRateMenuItem",go);var Lc=function(g){A.default(v,g);function v(c,a){var l;return l=g.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 d=v.prototype;return d.createEl=function(){var a=g.prototype.createEl.call(this);return this.labelElId_="vjs-playback-rate-value-label-"+this.id_,this.labelEl_=Ce("div",{className:"vjs-playback-rate-value",id:this.labelElId_,textContent:"1x"}),a.appendChild(this.labelEl_),a},d.dispose=function(){this.labelEl_=null,g.prototype.dispose.call(this)},d.buildCSSClass=function(){return"vjs-playback-rate "+g.prototype.buildCSSClass.call(this)},d.buildWrapperCSSClass=function(){return"vjs-playback-rate "+g.prototype.buildWrapperCSSClass.call(this)},d.createItems=function(){for(var a=this.playbackRates(),l=[],y=a.length-1;y>=0;y--)l.push(new go(this.player(),{rate:a[y]+"x"}));return l},d.updateARIAAttributes=function(){this.el().setAttribute("aria-valuenow",this.player().playbackRate())},d.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])},d.handlePlaybackRateschange=function(a){this.update()},d.playbackRates=function(){var a=this.player();return a.playbackRates&&a.playbackRates()||[]},d.playbackRateSupported=function(){return this.player().tech_&&this.player().tech_.featuresPlaybackRate&&this.playbackRates()&&this.playbackRates().length>0},d.updateVisibility=function(a){this.playbackRateSupported()?this.removeClass("vjs-hidden"):this.addClass("vjs-hidden")},d.updateLabel=function(a){this.playbackRateSupported()&&(this.labelEl_.textContent=this.player().playbackRate()+"x")},v}(ao);Lc.prototype.controlText_="Playback Rate",de.registerComponent("PlaybackRateMenuButton",Lc);var Ac=function(g){A.default(v,g);function v(){return g.apply(this,arguments)||this}var d=v.prototype;return d.buildCSSClass=function(){return"vjs-spacer "+g.prototype.buildCSSClass.call(this)},d.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()),g.prototype.createEl.call(this,a,l,y)},v}(de);de.registerComponent("Spacer",Ac);var Rm=function(g){A.default(v,g);function v(){return g.apply(this,arguments)||this}var d=v.prototype;return d.buildCSSClass=function(){return"vjs-custom-control-spacer "+g.prototype.buildCSSClass.call(this)},d.createEl=function(){return g.prototype.createEl.call(this,"div",{className:this.buildCSSClass(),textContent:" "})},v}(Ac);de.registerComponent("CustomControlSpacer",Rm);var gr=function(g){A.default(v,g);function v(){return g.apply(this,arguments)||this}var d=v.prototype;return d.createEl=function(){return g.prototype.createEl.call(this,"div",{className:"vjs-control-bar",dir:"ltr"})},v}(de);gr.prototype.options_={children:["playToggle","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","liveDisplay","seekToLive","remainingTimeDisplay","customControlSpacer","playbackRateMenuButton","chaptersButton","descriptionsButton","subsCapsButton","audioTrackButton","fullscreenToggle"]},"exitPictureInPicture"in _.default&&gr.prototype.options_.children.splice(gr.prototype.options_.children.length-1,0,"pictureInPictureToggle"),de.registerComponent("ControlBar",gr);var kc=function(g){A.default(v,g);function v(c,a){var l;return l=g.call(this,c,a)||this,l.on(c,"error",function(y){return l.open(y)}),l}var d=v.prototype;return d.buildCSSClass=function(){return"vjs-error-display "+g.prototype.buildCSSClass.call(this)},d.content=function(){var a=this.player().error();return a?this.localize(a.message):""},v}(Un);kc.prototype.options_=b.default({},Un.prototype.options_,{pauseOnOpen:!1,fillAlways:!0,temporary:!1,uncloseable:!0}),de.registerComponent("ErrorDisplay",kc);var mo="vjs-text-track-settings",Ic=["#000","Black"],Rc=["#00F","Blue"],Pc=["#0FF","Cyan"],Dc=["#0F0","Green"],xc=["#F0F","Magenta"],Mc=["#F00","Red"],Oc=["#FFF","White"],Fc=["#FF0","Yellow"],yo=["1","Opaque"],vo=["0.5","Semi-Transparent"],Nc=["0","Transparent"],yn={backgroundColor:{selector:".vjs-bg-color > select",id:"captions-background-color-%s",label:"Color",options:[Ic,Oc,Mc,Dc,Rc,Fc,xc,Pc]},backgroundOpacity:{selector:".vjs-bg-opacity > select",id:"captions-background-opacity-%s",label:"Transparency",options:[yo,vo,Nc]},color:{selector:".vjs-fg-color > select",id:"captions-foreground-color-%s",label:"Color",options:[Oc,Ic,Mc,Dc,Rc,Fc,xc,Pc]},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:[yo,vo]},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:[Nc,vo,yo]}};yn.windowColor.options=yn.backgroundColor.options;function Bc(g,v){if(v&&(g=v(g)),g&&g!=="none")return g}function Pm(g,v){var d=g.options[g.options.selectedIndex].value;return Bc(d,v)}function Dm(g,v,d){if(v){for(var c=0;c<g.options.length;c++)if(Bc(g.options[c].value,d)===v){g.selectedIndex=c;break}}}var xm=function(g){A.default(v,g);function v(c,a){var l;return a.temporary=!1,l=g.call(this,c,a)||this,l.updateDisplay=l.updateDisplay.bind(L.default(l)),l.fill(),l.hasBeenOpened_=l.hasBeenFilled_=!0,l.endDialog=Ce("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()}),xe(yn,function(y){l.on(l.$(y.selector),"change",l.updateDisplay)}),l.options_.persistTextTrackSettings&&l.restoreSettings(),l}var d=v.prototype;return d.dispose=function(){this.endDialog=null,g.prototype.dispose.call(this)},d.createElSelect_=function(a,l,y){var S=this;l===void 0&&(l=""),y===void 0&&(y="label");var x=yn[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("")},d.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("")},d.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("")},d.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("")},d.createElColors_=function(){return Ce("div",{className:"vjs-track-settings-colors",innerHTML:[this.createElFgColor_(),this.createElBgColor_(),this.createElWinColor_()].join("")})},d.createElFont_=function(){return Ce("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("")})},d.createElControls_=function(){var a=this.localize("restore all settings to the default values");return Ce("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("")})},d.content=function(){return[this.createElColors_(),this.createElFont_(),this.createElControls_()]},d.label=function(){return this.localize("Caption Settings Dialog")},d.description=function(){return this.localize("Beginning of dialog window. Escape will cancel and close the window.")},d.buildCSSClass=function(){return g.prototype.buildCSSClass.call(this)+" vjs-text-track-settings"},d.getValues=function(){var a=this;return Me(yn,function(l,y,S){var x=Pm(a.$(y.selector),y.parser);return x!==void 0&&(l[S]=x),l},{})},d.setValues=function(a){var l=this;xe(yn,function(y,S){Dm(l.$(y.selector),a[S],y.parser)})},d.setDefaults=function(){var a=this;xe(yn,function(l){var y=l.hasOwnProperty("default")?l.default:0;a.$(l.selector).selectedIndex=y})},d.restoreSettings=function(){var a;try{a=JSON.parse(T.default.localStorage.getItem(mo))}catch(l){re.warn(l)}a&&this.setValues(a)},d.saveSettings=function(){if(this.options_.persistTextTrackSettings){var a=this.getValues();try{Object.keys(a).length?T.default.localStorage.setItem(mo,JSON.stringify(a)):T.default.localStorage.removeItem(mo)}catch(l){re.warn(l)}}},d.updateDisplay=function(){var a=this.player_.getChild("textTrackDisplay");a&&a.updateDisplay()},d.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}(Un);de.registerComponent("TextTrackSettings",xm);var Mm=function(g){A.default(v,g);function v(c,a){var l,y=a.ResizeObserver||T.default.ResizeObserver;a.ResizeObserver===null&&(y=!1);var S=tt({createEl:!y,reportTouchActivity:!1},a);return l=g.call(this,c,S)||this,l.ResizeObserver=a.ResizeObserver||T.default.ResizeObserver,l.loadListener_=null,l.resizeObserver_=null,l.debouncedHandler_=me(function(){l.resizeHandler()},100,!1,L.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(){dt(this,"resize",x),dt(this,"unload",U),U=null};Lt(l.el_.contentWindow,"unload",U),Lt(l.el_.contentWindow,"resize",x)}},l.one("load",l.loadListener_)),l}var d=v.prototype;return d.createEl=function(){return g.prototype.createEl.call(this,"iframe",{className:"vjs-resize-manager",tabIndex:-1,title:this.localize("No content")},{"aria-hidden":"true"})},d.resizeHandler=function(){!this.player_||!this.player_.trigger||this.player_.trigger("playerresize")},d.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,g.prototype.dispose.call(this)},v}(de);de.registerComponent("ResizeManager",Mm);var Om={trackingThreshold:20,liveTolerance:15},Fm=function(g){A.default(v,g);function v(c,a){var l,y=tt(Om,a,{createEl:!1});return l=g.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()}),Ot&&"hidden"in _.default&&"visibilityState"in _.default&&l.on(_.default,"visibilitychange",l.handleVisibilityChange_),l}var d=v.prototype;return d.handleVisibilityChange=function(){this.player_.duration()===1/0&&(_.default.hidden?this.stopTracking():this.startTracking())},d.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"))}},d.handleDurationchange=function(){this.toggleTracking()},d.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())},d.startTracking=function(){this.isTracking()||(this.timeupdateSeen_||(this.timeupdateSeen_=this.player_.hasStarted()),this.trackingInterval_=this.setInterval(this.trackLiveHandler_,It),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_)))},d.handleFirstTimeupdate=function(){this.timeupdateSeen_=!0,this.on(this.player_,"seeked",this.handleSeeked_)},d.handleSeeked=function(){var a=Math.abs(this.liveCurrentTime()-this.player_.currentTime());this.seekedBehindLive_=this.nextSeekedFromUser_&&a>2,this.nextSeekedFromUser_=!1,this.trackLive_()},d.handlePlay=function(){this.one(this.player_,"timeupdate",this.seekToLiveEdge_)},d.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_)},d.nextSeekedFromUser=function(){this.nextSeekedFromUser_=!0},d.stopTracking=function(){this.isTracking()&&(this.reset_(),this.trigger("liveedgechange"))},d.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},d.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},d.liveWindow=function(){var a=this.liveCurrentTime();return a===1/0?0:a-this.seekableStart()},d.isLive=function(){return this.isTracking()},d.atLiveEdge=function(){return!this.behindLiveEdge()},d.liveCurrentTime=function(){return this.pastSeekEnd()+this.seekableEnd()},d.pastSeekEnd=function(){var a=this.seekableEnd();return this.lastSeekEnd_!==-1&&a!==this.lastSeekEnd_&&(this.pastSeekEnd_=0),this.lastSeekEnd_=a,this.pastSeekEnd_},d.behindLiveEdge=function(){return this.behindLiveEdge_},d.isTracking=function(){return typeof this.trackingInterval_=="number"},d.seekToLiveEdge=function(){this.seekedBehindLive_=!1,!this.atLiveEdge()&&(this.nextSeekedFromUser_=!1,this.player_.currentTime(this.liveCurrentTime()))},d.dispose=function(){this.off(_.default,"visibilitychange",this.handleVisibilityChange_),this.stopTracking(),g.prototype.dispose.call(this)},v}(de);de.registerComponent("LiveTracker",Fm);var To=function(v){var d=v.el();if(d.hasAttribute("src"))return v.triggerSourceset(d.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},Nm=Object.defineProperty({},"innerHTML",{get:function(){return this.cloneNode(!0).innerHTML},set:function(v){var d=_.default.createElement(this.nodeName.toLowerCase());d.innerHTML=v;for(var c=_.default.createDocumentFragment();d.childNodes.length;)c.appendChild(d.childNodes[0]);return this.innerText="",T.default.Element.prototype.appendChild.call(this,c),this.innerHTML}}),Uc=function(v,d){for(var c={},a=0;a<v.length&&(c=Object.getOwnPropertyDescriptor(v[a],d),!(c&&c.set&&c.get));a++);return c.enumerable=!0,c.configurable=!0,c},Bm=function(v){return Uc([v.el(),T.default.HTMLMediaElement.prototype,T.default.Element.prototype,Nm],"innerHTML")},Hc=function(v){var d=v.el();if(!d.resetSourceWatch_){var c={},a=Bm(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(d,U);return To(v),z}};["append","appendChild","insertAdjacentHTML"].forEach(function(y){d[y]&&(c[y]=d[y],d[y]=l(c[y]))}),Object.defineProperty(d,"innerHTML",tt(a,{set:l(a.set)})),d.resetSourceWatch_=function(){d.resetSourceWatch_=null,Object.keys(c).forEach(function(y){d[y]=c[y]}),Object.defineProperty(d,"innerHTML",a)},v.one("sourceset",d.resetSourceWatch_)}},Um=Object.defineProperty({},"src",{get:function(){return this.hasAttribute("src")?Xu(T.default.Element.prototype.getAttribute.call(this,"src")):""},set:function(v){return T.default.Element.prototype.setAttribute.call(this,"src",v),v}}),Hm=function(v){return Uc([v.el(),T.default.HTMLMediaElement.prototype,Um],"src")},$m=function(v){if(v.featuresSourceset){var d=v.el();if(!d.resetSourceset_){var c=Hm(v),a=d.setAttribute,l=d.load;Object.defineProperty(d,"src",tt(c,{set:function(S){var x=c.set.call(d,S);return v.triggerSourceset(d.src),x}})),d.setAttribute=function(y,S){var x=a.call(d,y,S);return/src/i.test(y)&&v.triggerSourceset(d.src),x},d.load=function(){var y=l.call(d);return To(v)||(v.triggerSourceset(""),Hc(v)),y},d.currentSrc?v.triggerSourceset(d.currentSrc):To(v)||Hc(v),d.resetSourceset_=function(){d.resetSourceset_=null,d.load=l,d.setAttribute=a,Object.defineProperty(d,"src",c),d.resetSourceWatch_&&d.resetSourceWatch_()}}}},_o=function(v,d,c,a){a===void 0&&(a=!0);var l=function(x){return Object.defineProperty(v,d,{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,d,y)},ve=function(g){A.default(v,g);function v(c,a){var l;l=g.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")&&lr(z.src)&&(S=!0)):V.push(z))}for(var ue=0;ue<V.length;ue++)l.el_.removeChild(V[ue])}return l.proxyNativeTracks_(),l.featuresNativeTextTracks&&S&&re.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_(),(qt||bt||un)&&c.nativeControlsForTouch===!0&&l.setControls(!0),l.proxyWebkitFullscreen_(),l.triggerReady(),l}var d=v.prototype;return d.dispose=function(){this.el_&&this.el_.resetSourceset_&&this.el_.resetSourceset_(),v.disposeMediaElement(this.el_),this.options_=null,g.prototype.dispose.call(this)},d.setupSourcesetHandling_=function(){$m(this)},d.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)})},d.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)}},d.overrideNativeAudioTracks=function(a){this.overrideNative_("Audio",a)},d.overrideNativeVideoTracks=function(a){this.overrideNative_("Video",a)},d.proxyNativeTracksForType_=function(a){var l=this,y=Ut[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 ue={type:"change",target:x,currentTarget:x,srcElement:x};x.trigger(ue),a==="text"&&l[jn.remoteText.getterName]().trigger(ue)},addtrack:function(j){x.addTrack(j.track)},removetrack:function(j){x.removeTrack(j.track)}},V=function(){for(var j=[],ue=0;ue<x.length;ue++){for(var _e=!1,Fe=0;Fe<S.length;Fe++)if(S[Fe]===x[ue]){_e=!0;break}_e||j.push(x[ue])}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(ue){return S.removeEventListener(z,j)})}),this.on("loadstart",V),this.on("dispose",function(z){return l.off("loadstart",V)})}},d.proxyNativeTracks_=function(){var a=this;Ut.names.forEach(function(l){a.proxyNativeTracksForType_(l)})},d.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=_.default.createElement("video");var y=this.options_.tag&&Nt(this.options_.tag),S=tt({},y);(!qt||this.options_.nativeControlsForTouch!==!0)&&delete S.controls,Ks(a,Pe(S,{id:this.options_.techId,class:"vjs-tech"}))}a.playerId=this.options_.playerId}typeof this.options_.preload<"u"&&ji(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?ji(a,V,V):xn(a,V),a[V]=z)}return a},d.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)})}},d.setScrubbing=function(a){this.isScrubbing_=a},d.scrubbing=function(){return this.isScrubbing_},d.setCurrentTime=function(a){try{this.isScrubbing_&&this.el_.fastSeek&&E?this.el_.fastSeek(a):this.el_.currentTime=a}catch(l){re(l,"Video is not ready. (Video.js)")}},d.duration=function(){var a=this;if(this.el_.duration===1/0&&lt&&Mt&&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},d.width=function(){return this.el_.offsetWidth},d.height=function(){return this.el_.offsetHeight},d.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)})}},d.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},d.enterFullScreen=function(){var a=this.el_;if(a.paused&&a.networkState<=a.HAVE_METADATA)ri(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)}},d.exitFullScreen=function(){if(!this.el_.webkitDisplayingFullscreen){this.trigger("fullscreenerror",new Error("The video is not fullscreen"));return}this.el_.webkitExitFullScreen()},d.requestPictureInPicture=function(){return this.el_.requestPictureInPicture()},d.requestVideoFrameCallback=function(a){return this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.requestVideoFrameCallback(a):g.prototype.requestVideoFrameCallback.call(this,a)},d.cancelVideoFrameCallback=function(a){this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.cancelVideoFrameCallback(a):g.prototype.cancelVideoFrameCallback.call(this,a)},d.src=function(a){if(a===void 0)return this.el_.src;this.setSrc(a)},d.reset=function(){v.resetMediaElement(this.el_)},d.currentSrc=function(){return this.currentSource_?this.currentSource_.src:this.el_.currentSrc},d.setControls=function(a){this.el_.controls=!!a},d.addTextTrack=function(a,l,y){return this.featuresNativeTextTracks?this.el_.addTextTrack(a,l,y):g.prototype.addTextTrack.call(this,a,l,y)},d.createRemoteTextTrack=function(a){if(!this.featuresNativeTextTracks)return g.prototype.createRemoteTextTrack.call(this,a);var l=_.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},d.addRemoteTextTrack=function(a,l){var y=g.prototype.addRemoteTextTrack.call(this,a,l);return this.featuresNativeTextTracks&&this.el().appendChild(y),y},d.removeRemoteTextTrack=function(a){if(g.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])},d.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}(Xe);_o(ve,"TEST_VID",function(){if(ne()){var g=_.default.createElement("video"),v=_.default.createElement("track");return v.kind="captions",v.srclang="en",v.label="English",g.appendChild(v),g}}),ve.isSupported=function(){try{ve.TEST_VID.volume=.5}catch{return!1}return!!(ve.TEST_VID&&ve.TEST_VID.canPlayType)},ve.canPlayType=function(g){return ve.TEST_VID.canPlayType(g)},ve.canPlaySource=function(g,v){return ve.canPlayType(g.type)},ve.canControlVolume=function(){try{var g=ve.TEST_VID.volume;ve.TEST_VID.volume=g/2+.1;var v=g!==ve.TEST_VID.volume;return v&&R?(T.default.setTimeout(function(){ve&&ve.prototype&&(ve.prototype.featuresVolumeControl=g!==ve.TEST_VID.volume)}),!1):v}catch{return!1}},ve.canMuteVolume=function(){try{var g=ve.TEST_VID.muted;return ve.TEST_VID.muted=!g,ve.TEST_VID.muted?ji(ve.TEST_VID,"muted","muted"):xn(ve.TEST_VID,"muted","muted"),g!==ve.TEST_VID.muted}catch{return!1}},ve.canControlPlaybackRate=function(){if(lt&&Mt&&$i<58)return!1;try{var g=ve.TEST_VID.playbackRate;return ve.TEST_VID.playbackRate=g/2+.1,g!==ve.TEST_VID.playbackRate}catch{return!1}},ve.canOverrideAttributes=function(){try{var g=function(){};Object.defineProperty(_.default.createElement("video"),"src",{get:g,set:g}),Object.defineProperty(_.default.createElement("audio"),"src",{get:g,set:g}),Object.defineProperty(_.default.createElement("video"),"innerHTML",{get:g,set:g}),Object.defineProperty(_.default.createElement("audio"),"innerHTML",{get:g,set:g})}catch{return!1}return!0},ve.supportsNativeTextTracks=function(){return E||R&&Mt},ve.supportsNativeVideoTracks=function(){return!!(ve.TEST_VID&&ve.TEST_VID.videoTracks)},ve.supportsNativeAudioTracks=function(){return!!(ve.TEST_VID&&ve.TEST_VID.audioTracks)},ve.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(g){var v=g[0],d=g[1];_o(ve.prototype,v,function(){return ve[d]()},!0)}),ve.prototype.featuresVolumeControl=ve.canControlVolume(),ve.prototype.movingMediaElementInDOM=!R,ve.prototype.featuresFullscreenResize=!0,ve.prototype.featuresProgressEvents=!0,ve.prototype.featuresTimeupdateEvents=!0,ve.prototype.featuresVideoFrameCallback=!!(ve.TEST_VID&&ve.TEST_VID.requestVideoFrameCallback);var mr;ve.patchCanPlayType=function(){ln>=4&&!Hi&&!Mt&&(mr=ve.TEST_VID&&ve.TEST_VID.constructor.prototype.canPlayType,ve.TEST_VID.constructor.prototype.canPlayType=function(g){var v=/^application\/(?:x-|vnd\.apple\.)mpegurl/i;return g&&v.test(g)?"maybe":mr.call(this,g)})},ve.unpatchCanPlayType=function(){var g=ve.TEST_VID.constructor.prototype.canPlayType;return mr&&(ve.TEST_VID.constructor.prototype.canPlayType=mr),g},ve.patchCanPlayType(),ve.disposeMediaElement=function(g){if(g){for(g.parentNode&&g.parentNode.removeChild(g);g.hasChildNodes();)g.removeChild(g.firstChild);g.removeAttribute("src"),typeof g.load=="function"&&function(){try{g.load()}catch{}}()}},ve.resetMediaElement=function(g){if(g){for(var v=g.querySelectorAll("source"),d=v.length;d--;)g.removeChild(v[d]);g.removeAttribute("src"),typeof g.load=="function"&&function(){try{g.load()}catch{}}()}},["muted","defaultMuted","autoplay","controls","loop","playsinline"].forEach(function(g){ve.prototype[g]=function(){return this.el_[g]||this.el_.hasAttribute(g)}}),["muted","defaultMuted","autoplay","loop","playsinline"].forEach(function(g){ve.prototype["set"+rt(g)]=function(v){this.el_[g]=v,v?this.el_.setAttribute(g,g):this.el_.removeAttribute(g)}}),["paused","currentTime","buffered","volume","poster","preload","error","seeking","seekable","ended","playbackRate","defaultPlaybackRate","disablePictureInPicture","played","networkState","readyState","videoWidth","videoHeight","crossOrigin"].forEach(function(g){ve.prototype[g]=function(){return this.el_[g]}}),["volume","src","poster","preload","playbackRate","defaultPlaybackRate","disablePictureInPicture","crossOrigin"].forEach(function(g){ve.prototype["set"+rt(g)]=function(v){this.el_[g]=v}}),["pause","load","play"].forEach(function(g){ve.prototype[g]=function(){return this.el_[g]()}}),Xe.withSourceHandlers(ve),ve.nativeSourceHandler={},ve.nativeSourceHandler.canPlayType=function(g){try{return ve.TEST_VID.canPlayType(g)}catch{return""}},ve.nativeSourceHandler.canHandleSource=function(g,v){if(g.type)return ve.nativeSourceHandler.canPlayType(g.type);if(g.src){var d=Wa(g.src);return ve.nativeSourceHandler.canPlayType("video/"+d)}return""},ve.nativeSourceHandler.handleSource=function(g,v,d){v.setSrc(g.src)},ve.nativeSourceHandler.dispose=function(){},ve.registerSourceHandler(ve.nativeSourceHandler),Xe.registerTech("Html5",ve);var $c=["progress","abort","suspend","emptied","stalled","loadedmetadata","loadeddata","timeupdate","resize","volumechange","texttrackchange"],Eo={canplay:"CanPlay",canplaythrough:"CanPlayThrough",playing:"Playing",seeked:"Seeked"},bo=["tiny","xsmall","small","medium","large","xlarge","huge"],yr={};bo.forEach(function(g){var v=g.charAt(0)==="x"?"x-"+g.substring(1):g;yr[g]="vjs-layout-"+v});var jm={tiny:210,xsmall:320,small:425,medium:768,large:1440,xlarge:2560,huge:1/0},ut=function(g){A.default(v,g);function v(c,a,l){var y;if(c.id=c.id||a.id||"vjs_video_"+Bt(),a=Pe(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(Nt(x).hasOwnProperty("lang")){a.language=x.getAttribute("lang");break}x=x.parentNode}if(y=g.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&&Nt(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(),bs(L.default(y),{eventBusKey:"el_"}),y.fsApi_.requestFullscreen&&(Lt(_.default,y.fsApi_.fullscreenchange,y.boundDocumentFullscreenChange_),y.on(y.fsApi_.fullscreenchange,y.boundDocumentFullscreenChange_)),y.fluid_&&y.on(["playerreset","resize"],y.boundUpdateStyleEl_);var V=tt(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"),qt&&y.addClass("vjs-touch-enabled"),R||y.addClass("vjs-workinghover"),v.players[y.id_]=L.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 d=v.prototype;return d.dispose=function(){var a=this;this.trigger("dispose"),this.off("dispose"),dt(_.default,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),dt(_.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),lm(this),kt.names.forEach(function(l){var y=kt[l],S=a[y.getterName]();S&&S.off&&S.off()}),g.prototype.dispose.call(this,{restoreEl:this.options_.restoreEl})},d.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_=g.prototype.createEl.call(this,"div"));var x=Nt(a);if(S){for(l=this.el_=a,a=this.tag=_.default.createElement("video");l.children.length;)a.appendChild(l.firstChild);Li(l,"video-js")||Wt(l,"video-js"),l.appendChild(a),y=this.playerElIngest_=l,Object.keys(l).forEach(function(_e){try{a[_e]=l[_e]}catch{}})}if(a.setAttribute("tabindex","-1"),x.tabindex="-1",(Ot||Mt&&Ft)&&(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(_e){S&&_e==="class"||l.setAttribute(_e,x[_e]),S&&a.setAttribute(_e,x[_e])}),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_=Mn("vjs-styles-dimensions");var U=si(".vjs-styles-defaults"),V=si("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 ue=z.item(j);Wt(ue,"vjs-hidden"),ue.setAttribute("hidden","hidden")}return a.initNetworkState_=a.networkState,a.parentNode&&!y&&a.parentNode.insertBefore(l,a),fs(a,l),this.children_.unshift(a),this.el_.setAttribute("lang",this.language_),this.el_.setAttribute("translate","no"),this.el_=l,l},d.crossOrigin=function(a){if(!a)return this.techGet_("crossOrigin");if(a!=="anonymous"&&a!=="use-credentials"){re.warn('crossOrigin must be "anonymous" or "use-credentials", given "'+a+'"');return}this.techCall_("setCrossOrigin",a)},d.width=function(a){return this.dimension("width",a)},d.height=function(a){return this.dimension("height",a)},d.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)){re.error('Improper value "'+l+'" supplied for for '+a);return}this[y]=S,this.updateStyleEl_()},d.fluid=function(a){var l=this;if(a===void 0)return!!this.fluid_;this.fluid_=!!a,Re(this)&&this.off(["playerreset","resize"],this.boundUpdateStyleEl_),a?(this.addClass("vjs-fluid"),this.fill(!1),Qe(this,function(){l.on(["playerreset","resize"],l.boundUpdateStyleEl_)})):this.removeClass("vjs-fluid"),this.updateStyleEl_()},d.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")},d.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_()},d.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),Ki(this.styleEl_,`
      .`+V+` {
        width: `+S+`px;
        height: `+x+`px;
      }

      .`+V+`.vjs-fluid:not(.vjs-audio-only-mode) {
        padding-top: `+j*100+`%;
      }
    `)},d.loadTech_=function(a,l){var y=this;this.tech_&&this.unloadTech_();var S=rt(a),x=a.charAt(0).toLowerCase()+a.slice(1);S!=="Html5"&&this.tag&&(Xe.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};kt.names.forEach(function(j){var ue=kt[j];V[ue.getterName]=y[ue.privateName]}),Pe(V,this.options_[S]),Pe(V,this.options_[x]),Pe(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=Xe.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(Ye(this,this.handleTechReady_),!0),qu.jsonToTextTracks(this.textTracksJson_||[],this.tech_),$c.forEach(function(j){y.on(y.tech_,j,function(ue){return y["handleTech"+rt(j)+"_"](ue)})}),Object.keys(Eo).forEach(function(j){y.on(y.tech_,j,function(ue){if(y.tech_.playbackRate()===0&&y.tech_.seeking()){y.queuedCallbacks_.push({callback:y["handleTech"+Eo[j]+"_"].bind(y),event:ue});return}y["handleTech"+Eo[j]+"_"](ue)})}),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,ue){return y.handleTechFullscreenChange_(j,ue)}),this.on(this.tech_,"fullscreenerror",function(j,ue){return y.handleTechFullscreenError_(j,ue)}),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)&&fs(this.tech_.el(),this.el()),this.tag&&(this.tag.player=null,this.tag=null)},d.unloadTech_=function(){var a=this;kt.names.forEach(function(l){var y=kt[l];a[y.privateName]=a[y.getterName]()}),this.textTracksJson_=qu.textTracksToJson(this.tech_),this.isReady_=!1,this.tech_.dispose(),this.tech_=!1,this.isPosterFromTech_&&(this.poster_="",this.trigger("posterchange")),this.isPosterFromTech_=!1},d.tech=function(a){return a===void 0&&re.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_},d.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_)},d.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_)},d.handleTechReady_=function(){this.triggerReady(),this.cache_.volume&&this.techCall_("setVolume",this.cache_.volume),this.handleTechPosterChange_(),this.handleTechDurationChange_()},d.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())},d.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(Ss(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(),Ss(S)&&(S=S.catch(y))):a==="muted"&&!this.muted()?S=y():S=this.play(),!!Ss(S))return S.then(function(){l.trigger({type:"autoplay-success",autoplay:a})}).catch(function(){l.trigger({type:"autoplay-failure",autoplay:a})})}},d.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=hm(this,l)),this.cache_.source=tt({},a,{src:l,type:y});for(var S=this.cache_.sources.filter(function(ue){return ue.src&&ue.src===l}),x=[],U=this.$$("source"),V=[],z=0;z<U.length;z++){var j=Nt(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},d.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"})},d.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"))},d.handleTechPlay_=function(){this.removeClass("vjs-ended"),this.removeClass("vjs-paused"),this.addClass("vjs-playing"),this.hasStarted(!0),this.trigger("play")},d.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")},d.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)},d.handleTechCanPlay_=function(){this.removeClass("vjs-waiting"),this.trigger("canplay")},d.handleTechCanPlayThrough_=function(){this.removeClass("vjs-waiting"),this.trigger("canplaythrough")},d.handleTechPlaying_=function(){this.removeClass("vjs-waiting"),this.trigger("playing")},d.handleTechSeeking_=function(){this.addClass("vjs-seeking"),this.trigger("seeking")},d.handleTechSeeked_=function(){this.removeClass("vjs-seeking"),this.removeClass("vjs-ended"),this.trigger("seeked")},d.handleTechFirstPlay_=function(){this.options_.starttime&&(re.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")},d.handleTechPause_=function(){this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.trigger("pause")},d.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")},d.handleTechDurationChange_=function(){this.duration(this.techGet_("duration"))},d.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()?ri(this.play()):this.pause())},d.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())}},d.handleTechTap_=function(){this.userActive(!this.userActive())},d.handleTechTouchStart_=function(){this.userWasActive=this.userActive()},d.handleTechTouchMove_=function(){this.userWasActive&&this.reportUserActivity()},d.handleTechTouchEnd_=function(a){a.cancelable&&a.preventDefault()},d.handleStageClick_=function(){this.reportUserActivity()},d.toggleFullscreenClass_=function(){this.isFullscreen()?this.addClass("vjs-fullscreen"):this.removeClass("vjs-fullscreen")},d.documentFullscreenChange_=function(a){var l=a.target.player;if(!(l&&l!==this)){var y=this.el(),S=_.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)}},d.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))},d.handleTechFullscreenError_=function(a,l){this.trigger("fullscreenerror",l)},d.togglePictureInPictureClass_=function(){this.isInPictureInPicture()?this.addClass("vjs-picture-in-picture"):this.removeClass("vjs-picture-in-picture")},d.handleTechEnterPictureInPicture_=function(a){this.isInPictureInPicture(!0)},d.handleTechLeavePictureInPicture_=function(a){this.isInPictureInPicture(!1)},d.handleTechError_=function(){var a=this.tech_.error();this.error(a)},d.handleTechTextData_=function(){var a=null;arguments.length>1&&(a=arguments[1]),this.trigger("textdata",a)},d.getCache=function(){return this.cache_},d.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}},d.techCall_=function(a,l){this.ready(function(){if(a in am)return sm(this.middleware_,this.tech_,a,l);if(a in sc)return nc(this.middleware_,this.tech_,a,l);try{this.tech_&&this.tech_[a](l)}catch(y){throw re(y),y}},!0)},d.techGet_=function(a){if(!(!this.tech_||!this.tech_.isReady_)){if(a in rm)return nm(this.middleware_,this.tech_,a);if(a in sc)return nc(this.middleware_,this.tech_,a);try{return this.tech_[a]()}catch(l){throw this.tech_[a]===void 0?(re("Video.js: "+a+" method not defined for "+this.techName_+" playback technology.",l),l):l.name==="TypeError"?(re("Video.js: "+a+" unavailable on "+this.techName_+" playback technology element.",l),this.tech_.isReady_=!1,l):(re(l),l)}}},d.play=function(){var a=this,l=this.options_.Promise||T.default.Promise;return l?new l(function(y){a.play_(y)}):this.play_()},d.play_=function(a){var l=this;a===void 0&&(a=ri),this.playCallbacks_.push(a);var y=!!(!this.changingSrc_&&(this.src()||this.currentSrc())),S=!!(E||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)},d.runPlayTerminatedQueue_=function(){var a=this.playTerminatedQueue_.slice(0);this.playTerminatedQueue_=[],a.forEach(function(l){l()})},d.runPlayCallbacks_=function(a){var l=this.playCallbacks_.slice(0);this.playCallbacks_=[],this.playTerminatedQueue_=[],l.forEach(function(y){y(a)})},d.pause=function(){this.techCall_("pause")},d.paused=function(){return this.techGet_("paused")!==!1},d.played=function(){return this.techGet_("played")||pn(0,0)},d.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")},d.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},d.applyInitTime_=function(){this.currentTime(this.cache_.initTime)},d.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"))},d.remainingTime=function(){return this.duration()-this.currentTime()},d.remainingTimeDisplay=function(){return Math.floor(this.duration())-Math.floor(this.currentTime())},d.buffered=function(){var a=this.techGet_("buffered");return(!a||!a.length)&&(a=pn(0,0)),a},d.bufferedPercent=function(){return Ku(this.buffered(),this.duration())},d.bufferedEnd=function(){var a=this.buffered(),l=this.duration(),y=a.end(a.length-1);return y>l&&(y=l),y},d.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},d.muted=function(a){if(a!==void 0){this.techCall_("setMuted",a);return}return this.techGet_("muted")||!1},d.defaultMuted=function(a){return a!==void 0?this.techCall_("setDefaultMuted",a):this.techGet_("defaultMuted")||!1},d.lastVolume_=function(a){if(a!==void 0&&a!==0){this.cache_.lastVolume=a;return}return this.cache_.lastVolume},d.supportsFullScreen=function(){return this.techGet_("supportsFullScreen")||!1},d.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_},d.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(ue,_e){U(),x(_e)}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_()},d.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()},d.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,ue){x(),S(ue)}l.one("fullscreenchange",U),l.one("fullscreenerror",V);var z=l.exitFullscreenHelper_();z&&(z.then(x,x),z.then(y,S))})}return this.exitFullscreenHelper_()},d.exitFullscreenHelper_=function(){var a=this;if(this.fsApi_.requestFullscreen){var l=_.default[this.fsApi_.exitFullscreen]();return l&&ri(l.then(function(){return a.isFullscreen(!1)})),l}else this.tech_.supportsFullScreen()&&!this.options_.preferFullWindow?this.techCall_("exitFullScreen"):this.exitFullWindow()},d.enterFullWindow=function(){this.isFullscreen(!0),this.isFullWindow=!0,this.docOrigOverflow=_.default.documentElement.style.overflow,Lt(_.default,"keydown",this.boundFullWindowOnEscKey_),_.default.documentElement.style.overflow="hidden",Wt(_.default.body,"vjs-full-window"),this.trigger("enterFullWindow")},d.fullWindowOnEscKey=function(a){w.default.isEventKey(a,"Esc")&&this.isFullscreen()===!0&&(this.isFullWindow?this.exitFullWindow():this.exitFullscreen())},d.exitFullWindow=function(){this.isFullscreen(!1),this.isFullWindow=!1,dt(_.default,"keydown",this.boundFullWindowOnEscKey_),_.default.documentElement.style.overflow=this.docOrigOverflow,cn(_.default.body,"vjs-full-window"),this.trigger("exitFullWindow")},d.disablePictureInPicture=function(a){if(a===void 0)return this.techGet_("disablePictureInPicture");this.techCall_("setDisablePictureInPicture",a),this.options_.disablePictureInPicture=a,this.trigger("disablepictureinpicturechanged")},d.isInPictureInPicture=function(a){if(a!==void 0){this.isInPictureInPicture_=!!a,this.togglePictureInPictureClass_();return}return!!this.isInPictureInPicture_},d.requestPictureInPicture=function(){if("pictureInPictureEnabled"in _.default&&this.disablePictureInPicture()===!1)return this.techGet_("requestPictureInPicture")},d.exitPictureInPicture=function(){if("pictureInPictureEnabled"in _.default)return _.default.exitPictureInPicture()},d.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))}},d.handleHotkeys=function(a){var l=this.options_.userActions?this.options_.userActions.hotkeys:{},y=l.fullscreenKey,S=y===void 0?function(Fe){return w.default.isEventKey(Fe,"f")}:y,x=l.muteKey,U=x===void 0?function(Fe){return w.default.isEventKey(Fe,"m")}:x,V=l.playPauseKey,z=V===void 0?function(Fe){return w.default.isEventKey(Fe,"k")||w.default.isEventKey(Fe,"Space")}:V;if(S.call(this,a)){a.preventDefault(),a.stopPropagation();var j=de.getComponent("FullscreenToggle");_.default[this.fsApi_.fullscreenEnabled]!==!1&&j.prototype.handleClick.call(this,a)}else if(U.call(this,a)){a.preventDefault(),a.stopPropagation();var ue=de.getComponent("MuteToggle");ue.prototype.handleClick.call(this,a)}else if(z.call(this,a)){a.preventDefault(),a.stopPropagation();var _e=de.getComponent("PlayToggle");_e.prototype.handleClick.call(this,a)}},d.canPlayType=function(a){for(var l,y=0,S=this.options_.techOrder;y<S.length;y++){var x=S[y],U=Xe.getTech(x);if(U||(U=de.getComponent(x)),!U){re.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""},d.selectSource=function(a){var l=this,y=this.options_.techOrder.map(function(z){return[z,Xe.getTech(z)]}).filter(function(z){var j=z[0],ue=z[1];return ue?ue.isSupported():(re.error('The "'+j+'" tech is undefined. Skipped browser support check for that tech.'),!1)}),S=function(j,ue,_e){var Fe;return j.some(function(vn){return ue.some(function(oi){if(Fe=_e(vn,oi),Fe)return!0})}),Fe},x,U=function(j){return function(ue,_e){return j(_e,ue)}},V=function(j,ue){var _e=j[0],Fe=j[1];if(Fe.canPlaySource(ue,l.options_[_e.toLowerCase()]))return{source:ue,tech:_e}};return this.options_.sourceOrder?x=S(a,y,U(V)):x=S(y,a,V),x||!1},d.handleSrc_=function(a,l){var y=this;if(typeof a>"u")return this.cache_.src||"";this.resetRetryOnError_&&this.resetRetryOnError_();var S=dm(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]),tm(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}im(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)}}},d.src=function(a){return this.handleSrc_(a,!1)},d.src_=function(a){var l=this,y=this.selectSource([a]);return y?Fg(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},d.load=function(){this.techCall_("load")},d.reset=function(){var a=this,l=this.options_.Promise||T.default.Promise;if(this.paused()||!l)this.doReset_();else{var y=this.play();ri(y.then(function(){return a.doReset_()}))}},d.doReset_=function(){this.tech_&&this.tech_.clearTracks("text"),this.resetCache_(),this.poster(""),this.loadTech_(this.options_.techOrder[0],null),this.techCall_("reset"),this.resetControlBarUI_(),Re(this)&&this.trigger("playerreset")},d.resetControlBarUI_=function(){this.resetProgressBar_(),this.resetPlaybackRate_(),this.resetVolumeBar_()},d.resetProgressBar_=function(){this.currentTime(0);var a=this.controlBar||{},l=a.durationDisplay,y=a.remainingTimeDisplay;l&&l.updateContent(),y&&y.updateContent()},d.resetPlaybackRate_=function(){this.playbackRate(this.defaultPlaybackRate()),this.handleTechRateChange_()},d.resetVolumeBar_=function(){this.volume(1),this.trigger("volumechange")},d.currentSources=function(){var a=this.currentSource(),l=[];return Object.keys(a).length!==0&&l.push(a),this.cache_.sources||l},d.currentSource=function(){return this.cache_.source||{}},d.currentSrc=function(){return this.currentSource()&&this.currentSource().src||""},d.currentType=function(){return this.currentSource()&&this.currentSource().type||""},d.preload=function(a){if(a!==void 0){this.techCall_("setPreload",a),this.options_.preload=a;return}return this.techGet_("preload")},d.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)},d.playsinline=function(a){return a!==void 0?(this.techCall_("setPlaysinline",a),this.options_.playsinline=a,this):this.techGet_("playsinline")},d.loop=function(a){if(a!==void 0){this.techCall_("setLoop",a),this.options_.loop=a;return}return this.techGet_("loop")},d.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"))},d.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"))}},d.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_()))},d.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")))},d.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(!(je(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 At(a),this.addClass("vjs-error"),re.error("(CODE:"+this.error_.code+" "+At.errorTypes[this.error_.code]+")",this.error_.message,this.error_),this.trigger("error"),B("error").forEach(function(S){return S(l,l.error_)})},d.reportUserActivity=function(a){this.userActivity_=!0},d.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")}},d.listenForUserActivity_=function(){var a,l,y,S=Ye(this,this.reportUserActivity),x=function(_e){(_e.screenX!==l||_e.screenY!==y)&&(l=_e.screenX,y=_e.screenY,S())},U=function(){S(),this.clearInterval(a),a=this.setInterval(S,250)},V=function(_e){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&&!lt&&(z.on("mouseenter",function(ue){this.player().options_.inactivityTimeout!==0&&(this.player().cache_.inactivityTimeout=this.player().options_.inactivityTimeout),this.player().options_.inactivityTimeout=0}),z.on("mouseleave",function(ue){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 ue=this.options_.inactivityTimeout;ue<=0||(j=this.setTimeout(function(){this.userActivity_||this.userActive(!1)},ue))}},250)},d.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},d.defaultPlaybackRate=function(a){return a!==void 0?this.techCall_("setDefaultPlaybackRate",a):this.tech_&&this.tech_.featuresPlaybackRate?this.techGet_("defaultPlaybackRate"):1},d.isAudio=function(a){if(a!==void 0){this.isAudio_=!!a;return}return!!this.isAudio_},d.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")},d.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")},d.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_()},d.enablePosterModeUI_=function(){var a=this.tech_&&this.tech_;a.hide(),this.addClass("vjs-audio-poster-mode"),this.trigger("audiopostermodechange")},d.disablePosterModeUI_=function(){var a=this.tech_&&this.tech_;a.show(),this.removeClass("vjs-audio-poster-mode"),this.trigger("audiopostermodechange")},d.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_()},d.addTextTrack=function(a,l,y){if(this.tech_)return this.tech_.addTextTrack(a,l,y)},d.addRemoteTextTrack=function(a,l){if(this.tech_)return this.tech_.addRemoteTextTrack(a,l)},d.removeRemoteTextTrack=function(a){a===void 0&&(a={});var l=a,y=l.track;if(y||(y=a),this.tech_)return this.tech_.removeRemoteTextTrack(y)},d.getVideoPlaybackQuality=function(){return this.techGet_("getVideoPlaybackQuality")},d.videoWidth=function(){return this.tech_&&this.tech_.videoWidth&&this.tech_.videoWidth()||0},d.videoHeight=function(){return this.tech_&&this.tech_.videoHeight&&this.tech_.videoHeight()||0},d.language=function(a){if(a===void 0)return this.language_;this.language_!==String(a).toLowerCase()&&(this.language_=String(a).toLowerCase(),Re(this)&&this.trigger("languagechange"))},d.languages=function(){return tt(v.prototype.options_.languages,this.languages_)},d.toJSON=function(){var a=tt(this.options_),l=a.tracks;a.tracks=[];for(var y=0;y<l.length;y++){var S=l[y];S=tt(S),S.player=void 0,a.tracks[y]=S}return a},d.createModal=function(a,l){var y=this;l=l||{},l.content=a||"";var S=new Un(this,l);return this.addChild(S),S.on("dispose",function(){y.removeChild(S)}),S.open(),S},d.updateCurrentBreakpoint_=function(){if(this.responsive())for(var a=this.currentBreakpoint(),l=this.currentWidth(),y=0;y<bo.length;y++){var S=bo[y],x=this.breakpoints_[S];if(l<=x){if(a===S)return;a&&this.removeClass(yr[a]),this.addClass(yr[S]),this.breakpoint_=S;break}}},d.removeCurrentBreakpoint_=function(){var a=this.currentBreakpointClass();this.breakpoint_="",a&&this.removeClass(a)},d.breakpoints=function(a){return a===void 0?Pe(this.breakpoints_):(this.breakpoint_="",this.breakpoints_=Pe({},jm,a),this.updateCurrentBreakpoint_(),Pe(this.breakpoints_))},d.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},d.currentBreakpoint=function(){return this.breakpoint_},d.currentBreakpointClass=function(){return yr[this.breakpoint_]||""},d.loadMedia=function(a,l){var y=this;if(!(!a||typeof a!="object")){this.reset(),this.cache_.media=tt(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:cr(U)}]),V&&this.src(V),U&&this.poster(U),Array.isArray(z)&&z.forEach(function(j){return y.addRemoteTextTrack(j,!1)}),this.ready(l)}},d.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:cr(S.poster)}]),S}return tt(this.cache_.media)},v.getTagSettings=function(a){var l={sources:[],tracks:[]},y=Nt(a),S=y["data-setup"];if(Li(a,"vjs-fill")&&(y.fill=!0),Li(a,"vjs-fluid")&&(y.fluid=!0),S!==null){var x=P.default(S||"{}"),U=x[0],V=x[1];U&&re.error(U),Pe(y,V)}if(Pe(l,y),a.hasChildNodes())for(var z=a.childNodes,j=0,ue=z.length;j<ue;j++){var _e=z[j],Fe=_e.nodeName.toLowerCase();Fe==="source"?l.sources.push(Nt(_e)):Fe==="track"&&l.tracks.push(Nt(_e))}return l},d.flexNotSupported_=function(){var a=_.default.createElement("i");return!("flexBasis"in a.style||"webkitFlexBasis"in a.style||"mozFlexBasis"in a.style||"msFlexBasis"in a.style||"msFlexOrder"in a.style)},d.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)},d.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}(de);kt.names.forEach(function(g){var v=kt[g];ut.prototype[v.getterName]=function(){return this.tech_?this.tech_[v.getterName]():(this[v.privateName]=this[v.privateName]||new v.ListClass,this[v.privateName])}}),ut.prototype.crossorigin=ut.prototype.crossOrigin,ut.players={};var As=T.default.navigator;ut.prototype.options_={techOrder:Xe.defaultTechOrder_,html5:{},inactivityTimeout:2e3,playbackRates:[],liveui:!1,children:["mediaLoader","posterImage","textTrackDisplay","loadingSpinner","bigPlayButton","liveTracker","controlBar","errorDisplay","textTrackSettings","resizeManager"],language:As&&(As.languages&&As.languages[0]||As.userLanguage||As.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(g){ut.prototype[g]=function(){return this.techGet_(g)}}),$c.forEach(function(g){ut.prototype["handleTech"+rt(g)+"_"]=function(){return this.trigger(g)}}),de.registerComponent("Player",ut);var vr="plugin",qn="activePlugins_",Wn={},Tr=function(v){return Wn.hasOwnProperty(v)},_r=function(v){return Tr(v)?Wn[v]:void 0},jc=function(v,d){v[qn]=v[qn]||{},v[qn][d]=!0},Er=function(v,d,c){var a=(c?"before":"")+"pluginsetup";v.trigger(a,d),v.trigger(a+":"+d.name,d)},Vm=function(v,d){var c=function(){Er(this,{name:v,plugin:d,instance:null},!0);var l=d.apply(this,arguments);return jc(this,v),Er(this,{name:v,plugin:d,instance:l}),l};return Object.keys(d).forEach(function(a){c[a]=d[a]}),c},Vc=function(v,d){return d.prototype.name=v,function(){Er(this,{name:v,plugin:d,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(d,[this].concat(a));return this[v]=function(){return y},Er(this,y.getEventHash()),y}},ai=function(){function g(d){if(this.constructor===g)throw new Error("Plugin must be sub-classed; not directly instantiated.");this.player=d,this.log||(this.log=this.player.log.createLogger(this.name)),bs(this),delete this.trigger,Vu(this,this.constructor.defaultState),jc(d,this.name),this.dispose=this.dispose.bind(this),d.on("dispose",this.dispose)}var v=g.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={}),qi(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[qn][c]=!1,this.player=this.state=null,a[c]=Vc(c,Wn[c])},g.isBasic=function(c){var a=typeof c=="string"?_r(c):c;return typeof a=="function"&&!g.prototype.isPrototypeOf(a.prototype)},g.registerPlugin=function(c,a){if(typeof c!="string")throw new Error('Illegal plugin name, "'+c+'", must be a string, was '+typeof c+".");if(Tr(c))re.warn('A plugin named "'+c+'" already exists. You may want to avoid re-registering plugins!');else if(ut.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 Wn[c]=a,c!==vr&&(g.isBasic(a)?ut.prototype[c]=Vm(c,a):ut.prototype[c]=Vc(c,a)),a},g.deregisterPlugin=function(c){if(c===vr)throw new Error("Cannot de-register base plugin.");Tr(c)&&(delete Wn[c],delete ut.prototype[c])},g.getPlugins=function(c){c===void 0&&(c=Object.keys(Wn));var a;return c.forEach(function(l){var y=_r(l);y&&(a=a||{},a[l]=y)}),a},g.getPluginVersion=function(c){var a=_r(c);return a&&a.VERSION||""},g}();ai.getPlugin=_r,ai.BASE_PLUGIN_NAME=vr,ai.registerPlugin(vr,ai),ut.prototype.usingPlugin=function(g){return!!this[qn]&&this[qn][g]===!0},ut.prototype.hasPlugin=function(g){return!!Tr(g)};var Gc=!1,Gm=function(v,d){d===void 0&&(d={}),Gc||(re.warn("videojs.extend is deprecated as of Video.js 7.22.0 and will be removed in Video.js 8.0.0"),Gc=!0);var c=function(){v.apply(this,arguments)},a={};typeof d=="object"?(d.constructor!==Object.prototype.constructor&&(c=d.constructor),a=d):typeof d=="function"&&(c=d),N.default(c,v),v&&(c.super_=v);for(var l in a)a.hasOwnProperty(l)&&(c.prototype[l]=a[l]);return c},Kc=function(v){return v.indexOf("#")===0?v.slice(1):v};function Se(g,v,d){var c=Se.getPlayer(g);if(c)return v&&re.warn('Player "'+g+'" is already initialised. Options will not be applied.'),d&&c.ready(d),c;var a=typeof g=="string"?si("#"+Kc(g)):g;if(!Ie(a))throw new TypeError("The element or ID supplied is not valid. (videojs)");(!a.ownerDocument.defaultView||!a.ownerDocument.body.contains(a))&&re.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,tt(v));if(!je(S)||Array.isArray(S)){re.error("please return an object in beforesetup hooks");return}v=tt(v,S)});var l=de.getComponent("Player");return c=new l(a,v,d),B("setup").forEach(function(y){return y(c)}),c}if(Se.hooks_=G,Se.hooks=B,Se.hook=D,Se.hookOnce=ae,Se.removeHook=K,T.default.VIDEOJS_NO_DYNAMIC_STYLE!==!0&&ne()){var br=si(".vjs-styles-defaults");if(!br){br=Mn("vjs-styles-defaults");var So=si("head");So&&So.insertBefore(br,So.firstChild),Ki(br,`
      .video-js {
        width: 300px;
        height: 150px;
      }

      .vjs-fluid:not(.vjs-audio-only-mode) {
        padding-top: 56.25%
      }
    `)}}return vs(1,Se),Se.VERSION=H,Se.options=ut.prototype.options_,Se.getPlayers=function(){return ut.players},Se.getPlayer=function(g){var v=ut.players,d;if(typeof g=="string"){var c=Kc(g),a=v[c];if(a)return a;d=si("#"+c)}else d=g;if(Ie(d)){var l=d,y=l.player,S=l.playerId;if(y||v[S])return y||v[S]}},Se.getAllPlayers=function(){return Object.keys(ut.players).map(function(g){return ut.players[g]}).filter(Boolean)},Se.players=ut.players,Se.getComponent=de.getComponent,Se.registerComponent=function(g,v){Xe.isTech(v)&&re.warn("The "+g+" tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)"),de.registerComponent.call(de,g,v)},Se.getTech=Xe.getTech,Se.registerTech=Xe.registerTech,Se.use=em,Object.defineProperty(Se,"middleware",{value:{},writeable:!1,enumerable:!0}),Object.defineProperty(Se.middleware,"TERMINATOR",{value:ur,writeable:!1,enumerable:!0}),Se.browser=C,Se.TOUCH_ENABLED=qt,Se.extend=Gm,Se.mergeOptions=tt,Se.bind=Ye,Se.registerPlugin=ai.registerPlugin,Se.deregisterPlugin=ai.deregisterPlugin,Se.plugin=function(g,v){return re.warn("videojs.plugin() is deprecated; use videojs.registerPlugin() instead"),ai.registerPlugin(g,v)},Se.getPlugins=ai.getPlugins,Se.getPlugin=ai.getPlugin,Se.getPluginVersion=ai.getPluginVersion,Se.addLanguage=function(g,v){var d;return g=(""+g).toLowerCase(),Se.options.languages=tt(Se.options.languages,(d={},d[g]=v,d)),Se.options.languages[g]},Se.log=re,Se.createLogger=ie,Se.createTimeRange=Se.createTimeRanges=pn,Se.formatTime=Vn,Se.setFormatTime=Tm,Se.resetFormatTime=_m,Se.parseUrl=qa,Se.isCrossOrigin=lr,Se.EventTarget=F,Se.on=Lt,Se.one=Nn,Se.off=dt,Se.trigger=qi,Se.xhr=O.default,Se.TextTrack=Cs,Se.AudioTrack=Zu,Se.VideoTrack=ec,["isEl","isTextNode","createEl","hasClass","addClass","removeClass","toggleClass","setAttributes","getAttributes","emptyEl","appendContent","insertContent"].forEach(function(g){Se[g]=function(){return re.warn("videojs."+g+"() is deprecated; use videojs.dom."+g+"() instead"),Zs[g].apply(null,arguments)}}),Se.computedStyle=et,Se.dom=Zs,Se.url=Xg,Se.defineLazyProperty=_o,Se.addLanguage("en",{"Non-Fullscreen":"Exit Fullscreen"}),$o=Se,$o}var fy=dy();const X=sf(fy),py=X.getComponent("MenuItem");class gy extends py{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 my=X.getComponent("Menu");class yy extends my{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 gy(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 vy(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 Ty(s,e){const t={},i=vy(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 _y=X.getPlugin("plugin");class Ey extends _y{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(by(this.player)){this.menu.dispose();return}if(Sy(e.target))return;const t=Ty(this.player.el(),e),i=this.player.el().getBoundingClientRect(),n=Cy(t,i),r=X.browser.IS_FIREFOX?document.documentElement:document;e.preventDefault();const o=this.menu=new yy(this.player,{content:this.options_.content,position:n});o.on("dispose",()=>{for(const f of["click","tap"])X.off(r,f,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 f of["click","tap"])X.on(r,f,o.dispose)}}X.registerPlugin("contextMenu",Ey);function by(s){var e;return s.usingPlugin("contextMenu")?!!((e=s.contextMenu().menu)!=null&&e.el()):!1}function Sy(s){const e=s.tagName.toLowerCase();return e==="input"||e==="textarea"}function Cy(s,e){return{left:Math.round(e.width*s.x),top:Math.round(e.height-e.height*s.y)}}function wy(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 Ly=X.getComponent("Component");class of extends Ly{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:wy(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",of);const Ay=X.getPlugin("plugin");class ky extends Ay{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 of(e,i);e.addChild(n),this.on("dispose",()=>e.removeChild(n))}}X.registerPlugin("upnext",ky);const Xi=new Map;function dh(s){return new Proxy(s,{set:function(e,t,i){return Object.prototype.hasOwnProperty.call(Ol,t)?s[t]=i:s.setItem(t,i),!0},get:function(e,t){if(typeof s[t]=="function")return s[t];if(Xi.has(t))return s.getItem(t)}})}class Ol{getItem(e){const t=String(e);return Xi.has(e)?String(Xi.get(t)):null}setItem(e,t){Xi.set(String(e),String(t))}removeItem(e){Xi.delete(e)}clear(){Xi.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(Xi.keys())[e]}get length(){return Xi.size}}let Rn,Vs;function lf(){const s=new Ol,e=new Ol;Rn=dh(s),Vs=dh(e)}try{Rn=localStorage,Vs=sessionStorage}catch{lf()}(!Rn||!Vs)&&lf();const Ai={ACCESS_TOKEN:"access_token",REFRESH_TOKEN:"refresh_token",TOKEN_TYPE:"token_type"};class gu{constructor(e){Ue(this,"accessToken"),Ue(this,"refreshToken"),Ue(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(Ai.ACCESS_TOKEN),i=e.getItem(Ai.REFRESH_TOKEN),n=e.getItem(Ai.TOKEN_TYPE);return!t||!i||!n?null:new gu({accessToken:t,refreshToken:i,tokenType:n})}static saveToLocalStorage(e,t){e.setItem(Ai.ACCESS_TOKEN,t.accessToken),e.setItem(Ai.REFRESH_TOKEN,t.refreshToken),e.setItem(Ai.TOKEN_TYPE,t.tokenType)}static flushLocalStorage(e){e.removeItem(Ai.ACCESS_TOKEN),e.removeItem(Ai.REFRESH_TOKEN),e.removeItem(Ai.TOKEN_TYPE)}}class Iy{constructor(){Ue(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=gu.getUserTokens(Rn);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 Ne=window.logger||new Iy;window.logger=Ne;const Ry={"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},Py={"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({},Ry,Py);const Dy={"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},xy={"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({},Dy,xy);const wr={HIGH_LATENCY:2,SMALL_LATENCY:3},wt={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 zr(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 sn(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",f=Math.floor(t/3600);f>=1&&f<10&&i==="full"?r="0"+f+u:f>=1?r=o(f)+u:i==="full"&&(r="00"+u),t%=3600;const m=Math.floor(t/60);return m>=1&&m<10&&i==="full"?r+="0"+m+h:m>=1?r+=o(m)+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 jo(s,e){const t={};for(const i of e)Object.prototype.hasOwnProperty.call(s,i)&&(t[i]=s[i]);return t}function fh(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 uf(s,e){const t=new URL(s);for(const i of Object.keys(e))t.searchParams.append(i,e[i]);return t.toString()}function My(s){const e=new URL(s);return e.searchParams.forEach((t,i)=>e.searchParams.delete(i)),e.toString()}function Oy(s){return"/w/"+s.shortUUID}function Fl(s,e){return window.location.origin+Oy(s)}function cf(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",sn(i))}if(s.stopTime){const i=Math.floor(s.stopTime);t.set("stop",sn(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"),Fy(e,t)}function Fy(s,e){let t=!1;return e.forEach(()=>{t=!0}),t?s+"?"+e.toString():s}const Ny={"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":"繁體中文（台灣）"},hf={"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"},df=Object.keys(Ny).concat(Object.keys(hf));function By(){return"en-US"}function ff(s){return da(s)===da(By())}df.map(s=>"/"+s);function Uy(s){return df.includes(s)}function da(s){return s&&(hf[s]||s)}function Hy(s){return s.includes("-")===!1?s:s.split("-")[0]}const $y=new Set([wt.H_NOVIDEO,wt.H_144P,wt.H_240P,wt.H_360P,wt.H_480P,wt.H_720P,wt.H_1080P,wt.H_1440P,wt.H_4K]),ph={3840:wt.H_4K,1920:wt.H_1080P,1280:wt.H_720P,854:wt.H_480P,640:wt.H_360P,426:wt.H_240P,256:wt.H_144P};function jy(s){const{height:e,width:t}=s;if(s.resolution===0)return"Audio only";let i=s.resolution;if(!$y.has(i)&&typeof e=="number"&&typeof t=="number"){const n=Math.max(e,t);ph[n]&&(i=ph[n])}return`${i}p`}function pf(s,e){return e&&e>=50?s+e:s}function gf(s){return s.charAt(0).toUpperCase()+s.slice(1)}const Vo=[{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 Dt(s){const e=Vo.find(i=>s<i.max)||Vo[Vo.length-1];return[(s/(e.max/1024)).toFixed(e.decimals),e.type]}function Vy(s){return{iceServers:s.map(e=>({urls:e}))}}function Nl(s,e){return new URL(s).origin===new URL(e).origin}const Gy=X.getComponent("Component");class mf extends Gy{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=Dt((n?.downloadSpeed||0)+(r.downloadSpeed||0)).join(" "),this.playerNetworkInfo.uploadSpeed=Dt(n?.uploadSpeed||0).join(" "),this.playerNetworkInfo.totalDownloaded=Dt((n?.downloaded||0)+r.downloaded).join(" "),this.playerNetworkInfo.totalUploaded=Dt(n?.uploaded||0).join(" "),this.playerNetworkInfo.numPeers=n?.peersWithWebSeed,i.source==="p2p-media-loader"&&(this.playerNetworkInfo.averageBandwidth=Dt(i.bandwidthEstimate).join(" ")+"/s",this.playerNetworkInfo.downloadedFromServer=Dt(r.downloaded).join(" "),this.playerNetworkInfo.downloadedFromPeers=Dt(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){Ne.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=sn(e.getLiveLatency()),h=sn(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:f,downloadedFromPeers:m}=t,T=this.player(),_=T.getVideoPlaybackQuality(),b=Math.max(document.documentElement.clientWidth||0,window.innerWidth||0),w=Math.max(document.documentElement.clientHeight||0,window.innerHeight||0),L=(window.devicePixelRatio||1).toFixed(2),A=`${b}x${w}*${L}`,{droppedVideoFrames:P,totalVideoFrames:O}=_,M=T.localize("{1} / {2} dropped of {3}",[A,P+"",O+""]),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",[f,m]):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,M),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+=`[${sn(n)}, ${sn(r)}] `}return t}}X.registerComponent("StatsCard",mf);const Ky=X.getPlugin("plugin");class qy extends Ky{constructor(e,t){super(e),this.player.ready(()=>{e.addClass("vjs-stats-for-nerds")}),this.statsCard=new mf(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",qy);function Wy(){return/iPad|iPhone|iPod/.test(navigator.platform)?!0:!!(navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&navigator.platform.includes("MacIntel"))}function zy(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function mu(){return/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)}function Yy(){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 Xy(){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 Qy=X.getComponent("Component");class yf extends Qy{constructor(e,t){super(e,t),!mu()&&(this.firstPlayDone=!1,this.paused=!1,this.playerPauseHandler=()=>{e.seeking()||(this.paused=!0,!e.ended()&&(this.container.innerHTML=Yy(),this.showBezel()))},this.playerPlayHandler=()=>{if(e.seeking()||!this.firstPlayDone||!this.paused){this.firstPlayDone=!0;return}this.paused=!1,this.firstPlayDone=!0,this.container.innerHTML=Xy(),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",yf);const Jy=X.getPlugin("plugin");class Zy extends Jy{constructor(e,t){super(e),this.player.ready(()=>{e.addClass("vjs-bezels")});const i=new yf(e,t);e.addChild(i),this.on("dispose",()=>e.removeChild(i))}}X.registerPlugin("bezels",Zy);function ev(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var vf={exports:{}},at=vf.exports={},ui,ci;function Bl(){throw new Error("setTimeout has not been defined")}function Ul(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?ui=setTimeout:ui=Bl}catch{ui=Bl}try{typeof clearTimeout=="function"?ci=clearTimeout:ci=Ul}catch{ci=Ul}})();function Tf(s){if(ui===setTimeout)return setTimeout(s,0);if((ui===Bl||!ui)&&setTimeout)return ui=setTimeout,setTimeout(s,0);try{return ui(s,0)}catch{try{return ui.call(null,s,0)}catch{return ui.call(this,s,0)}}}function tv(s){if(ci===clearTimeout)return clearTimeout(s);if((ci===Ul||!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 Mi=[],ss=!1,Cn,Yr=-1;function iv(){!ss||!Cn||(ss=!1,Cn.length?Mi=Cn.concat(Mi):Yr=-1,Mi.length&&_f())}function _f(){if(!ss){var s=Tf(iv);ss=!0;for(var e=Mi.length;e;){for(Cn=Mi,Mi=[];++Yr<e;)Cn&&Cn[Yr].run();Yr=-1,e=Mi.length}Cn=null,ss=!1,tv(s)}}at.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];Mi.push(new Ef(s,e)),Mi.length===1&&!ss&&Tf(_f)};function Ef(s,e){this.fun=s,this.array=e}Ef.prototype.run=function(){this.fun.apply(null,this.array)};at.title="browser";at.browser=!0;at.env={};at.argv=[];at.version="";at.versions={};function Bi(){}at.on=Bi;at.addListener=Bi;at.once=Bi;at.off=Bi;at.removeListener=Bi;at.removeAllListeners=Bi;at.emit=Bi;at.prependListener=Bi;at.prependOnceListener=Bi;at.listeners=function(s){return[]};at.binding=function(s){throw new Error("process.binding is not supported")};at.cwd=function(){return"/"};at.chdir=function(s){throw new Error("process.chdir is not supported")};at.umask=function(){return 0};var nv=vf.exports;const Go=ev(nv);var Lr={exports:{}},Ko,gh;function sv(){if(gh)return Ko;gh=1;var s=1e3,e=s*60,t=e*60,i=t*24,n=i*7,r=i*365.25;Ko=function(f,m){m=m||{};var T=typeof f;if(T==="string"&&f.length>0)return o(f);if(T==="number"&&isFinite(f))return m.long?h(f):u(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))};function o(f){if(f=String(f),!(f.length>100)){var m=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(f);if(m){var T=parseFloat(m[1]),_=(m[2]||"ms").toLowerCase();switch(_){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(f){var m=Math.abs(f);return m>=i?Math.round(f/i)+"d":m>=t?Math.round(f/t)+"h":m>=e?Math.round(f/e)+"m":m>=s?Math.round(f/s)+"s":f+"ms"}function h(f){var m=Math.abs(f);return m>=i?p(f,m,i,"day"):m>=t?p(f,m,t,"hour"):m>=e?p(f,m,e,"minute"):m>=s?p(f,m,s,"second"):f+" ms"}function p(f,m,T,_){var b=m>=T*1.5;return Math.round(f/T)+" "+_+(b?"s":"")}return Ko}var qo,mh;function rv(){if(mh)return qo;mh=1;function s(e){i.debug=i,i.default=i,i.coerce=p,i.disable=u,i.enable=r,i.enabled=h,i.humanize=sv(),i.destroy=f,Object.keys(e).forEach(m=>{i[m]=e[m]}),i.names=[],i.skips=[],i.formatters={};function t(m){let T=0;for(let _=0;_<m.length;_++)T=(T<<5)-T+m.charCodeAt(_),T|=0;return i.colors[Math.abs(T)%i.colors.length]}i.selectColor=t;function i(m){let T,_=null,b,w;function L(...A){if(!L.enabled)return;const P=L,O=Number(new Date),M=O-(T||O);P.diff=M,P.prev=T,P.curr=O,T=O,A[0]=i.coerce(A[0]),typeof A[0]!="string"&&A.unshift("%O");let k=0;A[0]=A[0].replace(/%([a-zA-Z%])/g,(H,G)=>{if(H==="%%")return"%";k++;const B=i.formatters[G];if(typeof B=="function"){const D=A[k];H=B.call(P,D),A.splice(k,1),k--}return H}),i.formatArgs.call(P,A),(P.log||i.log).apply(P,A)}return L.namespace=m,L.useColors=i.useColors(),L.color=i.selectColor(m),L.extend=n,L.destroy=i.destroy,Object.defineProperty(L,"enabled",{enumerable:!0,configurable:!1,get:()=>_!==null?_:(b!==i.namespaces&&(b=i.namespaces,w=i.enabled(m)),w),set:A=>{_=A}}),typeof i.init=="function"&&i.init(L),L}function n(m,T){const _=i(this.namespace+(typeof T>"u"?":":T)+m);return _.log=this.log,_}function r(m){i.save(m),i.namespaces=m,i.names=[],i.skips=[];const T=(typeof m=="string"?m:"").trim().replace(" ",",").split(",").filter(Boolean);for(const _ of T)_[0]==="-"?i.skips.push(_.slice(1)):i.names.push(_)}function o(m,T){let _=0,b=0,w=-1,L=0;for(;_<m.length;)if(b<T.length&&(T[b]===m[_]||T[b]==="*"))T[b]==="*"?(w=b,L=_,b++):(_++,b++);else if(w!==-1)b=w+1,L++,_=L;else return!1;for(;b<T.length&&T[b]==="*";)b++;return b===T.length}function u(){const m=[...i.names,...i.skips.map(T=>"-"+T)].join(",");return i.enable(""),m}function h(m){for(const T of i.skips)if(o(m,T))return!1;for(const T of i.names)if(o(m,T))return!0;return!1}function p(m){return m instanceof Error?m.stack||m.message:m}function f(){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 qo=s,qo}var yh;function av(){return yh||(yh=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 f=0,m=0;h[0].replace(/%[a-zA-Z%]/g,T=>{T!=="%%"&&(f++,T==="%c"&&(m=f))}),h.splice(m,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 Go<"u"&&"env"in Go&&(h=Go.env.DEBUG),h}function o(){try{return localStorage}catch{}}s.exports=rv()(e);const{formatters:u}=s.exports;u.j=function(h){try{return JSON.stringify(h)}catch(p){return"[UnexpectedJSONParseError]: "+p.message}}}(Lr,Lr.exports)),Lr.exports}var ov=av();const an=sf(ov);function lv(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 bf(){const s=Pn("volume");if(s!=null){const e=parseFloat(s);return isNaN(e)?void 0:e}}function Sf(){const s=Pn("mute");if(s!=null)return s==="true"}function Cf(){const s=Pn("theater-enabled");return s!=null?s==="true":!1}function wf(s){return on("volume",s.toString())}function Lf(s){return on("mute",s.toString())}function Af(s){return on("theater-enabled",s.toString())}function kf(s){return on("average-bandwidth",s.toString())}function If(){const s=Pn("average-bandwidth");if(s!=null){const e=parseInt(s,10);return isNaN(e)?void 0:e}}function Hl(s){return on("last-subtitle",s)}function Rf(){return Pn("last-subtitle")}function Pf(s){return on("preferred-subtitle",s)}function Df(){return Pn("preferred-subtitle")}function xf(s,e){return on("video-watch-history",JSON.stringify({...yu(),[s]:{duration:e,date:`${new Date().toISOString()}`}}))}function yu(s){let e;try{const t=Pn("video-watch-history");if(!t)return{};e=JSON.parse(t)}catch(t){Ne.error("Cannot parse video watch history from local storage/",t)}return e=e||{},s?e[s]:e}function uv(){const s=yu();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]}},{});on("video-watch-history",JSON.stringify(e))}function Mf(){const s="session-id";let e=cv(s);return e||(e=lv(32),hv(s,e),e)}const Da="peertube-videojs-";function Pn(s){return Rn.getItem(Da+s)}function on(s,e){Rn.setItem(Da+s,e)}function cv(s){return Vs.getItem(Da+s)}function hv(s,e){Vs.setItem(Da+s,e)}const vt=an("peertube:player:peertube"),dv=X.getPlugin("plugin");class fv extends dv{constructor(e,t){super(e),this.options=t,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()||Rf(),this.initializePlayer(),this.initOnVideoChange(),this.player.removeClass("vjs-can-play"),this.deleteLegacyIndexedDB(),this.player.on("autoplay-failure",()=>{vt("Autoplay failed"),this.player.removeClass("vjs-has-autoplay"),this.player.poster(t.poster()),(Wy()||zy())&&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=bf();n!==void 0&&this.player.volume(n);const r=i.muted!==void 0?i.muted:Sf();r!==void 0&&this.player.muted(r),this.player.addClass("vjs-can-play")}),this.player.ready(()=>{this.player.on("volumechange",()=>{wf(this.player.volume()),Lf(this.player.muted())}),this.player.textTracks().addEventListener("change",()=>{const i=this.player.textTracks().tracks_.find(n=>n.kind==="captions"&&n.mode==="showing");if(!i){Hl("off"),this.currentSubtitle=void 0;return}this.currentSubtitle!==i.language&&(this.currentSubtitle=i.language,Hl(i.language),Pf(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;vt("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()):Ne.error("Fatal error in player",this.player.error())}hideFatalError(){this.errorModal&&(vt("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())}initializePlayer(){mu()&&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&&(vt("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("--player-ratio",o+"")}runUserViewing(){const e=zr(this.options.startTime());let t=e,i,n=!1;this.disableUserViewing(),this.videoViewOnPlayHandler=()=>{vt("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()){vt("Disabling viewing notification after first video loop."),this.disableUserViewing();return}const o=r-t;o>0&&o<3||(vt("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,vt("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&&(vt("Notify user is watching: "+r),t=r,this.notifyUserIsWatching(r,i).catch(o=>Ne.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()||xf(this.options.videoUUID(),e),!this.videoViewUrl())return Promise.resolve(!0);const i=Mf(),n={currentTime:e,viewEvent:t,sessionId:i},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(vt("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;vt("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?vt("Init captions with current subtitle "+this.currentSubtitle):vt("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(){vt("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&&(vt("Start the video at "+e),this.hasInitialSeek=!0,this.player.currentTime(zr(e))),this.options.stopTime()){const t=zr(this.options.stopTime());this.stopTimeHandler=()=>{this.player.currentTime()<=t||(vt("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){vt("Cannot delete legacy indexed DB",e)}}}X.registerPlugin("peertube",fv);const pv=X.getPlugin("plugin");class gv extends pv{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",gv);const mv=X.getComponent("Button");class yv extends mv{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=Df()||((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",yv);const vv=X.getPlugin("plugin");class Tv extends vv{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(f=>Object.prototype.hasOwnProperty.call(f,"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 f=Math.round(n/this.height*(i/this.width))-1;p=Math.min(p/this.interval,f);const m=600,T=this.player.currentWidth(),_=T<m?T/m:1,b=i/this.width,w=this.width*_,L=this.height*_,A=Math.floor(p%b)*-w,P=Math.floor(p/b)*-L,O=`${i*_}px ${n*_}px`,M=this.player.el().querySelector(".vjs-time-tooltip"),k=-L+parseInt(getComputedStyle(M).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":`${A}px ${P}px`,"background-size":O,color:"#fff","text-shadow":"1px 1px #000",position:"relative",top:`${k}px`,border:"1px solid #000",width:`${w+2}px`,height:`${L+2}px`};D.left=`${H}px`;for(const[K,ae]of Object.entries(D))this.spritePlaceholder.style.setProperty(K,ae)})}resetMouseTooltip(){this.spritePlaceholder&&(this.spritePlaceholder.style.cssText="")}isReady(){return this.mouseTimeTooltip&&this.width&&this.height&&this.url}}X.registerPlugin("storyboard",Tv);const _v=X.getComponent("ClickableComponent");class Of extends _v{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",Of);const Ev=X.getPlugin("plugin");class bv extends Ev{constructor(e,t){super(e,t),Ue(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 Of(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",bv);const Sv=X.getComponent("TimeTooltip");class Cv extends Sv{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(zr(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",Cv);const wv=X.getComponent("Button");class Ff extends wv{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",Ff);X.registerComponent("PreviousVideoButton",Ff);const Lv=X.getComponent("Button");class Av extends Lv{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"}),f=X.dom.createEl("span");h.appendChild(p),h.appendChild(f),t.appendChild(h);const m=X.dom.createEl("span",{className:"peers-text"}),T=X.dom.createEl("span",{className:"peers-number"});t.appendChild(T),t.appendChild(m);const _=X.dom.createEl("div",{className:"vjs-peertube-hidden"}),b=X.dom.createEl("span",{className:"http-fallback"});return _.appendChild(b),e.appendChild(_),this.player_.on("network-info",(w,L)=>{if(!L.p2p)return;t.className="vjs-peertube-displayed",_.className="vjs-peertube-hidden";const A=L.p2p,P=L.http,O=Dt(A.downloadSpeed+P.downloadSpeed),M=Dt(A.uploadSpeed),k=Dt(A.downloaded+P.downloaded),N=Dt(A.uploaded),H=A.peersWithWebSeed;if(t.title=this.player().localize("Total downloaded: ")+k.join(" ")+`
`,L.source==="p2p-media-loader"){const G=Dt(P.downloaded).join(" "),B=Dt(A.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=O[0],o.textContent=" "+O[1],p.textContent=M[0],f.textContent=" "+M[1],T.textContent=H.toString(),m.textContent=" "+(H>1?this.player().localize("peers"):this.player_.localize("peer")),_.className="vjs-peertube-hidden",t.className="vjs-peertube-displayed"}),this.player_.on("network-info",(w,L)=>{L.p2p||(L.source==="web-video"?b.textContent="HTTP":L.source==="p2p-media-loader"&&(b.textContent="HLS"),_.className="vjs-peertube-displayed",t.className="vjs-peertube-hidden",_.title=this.player().localize("Total downloaded: ")+Dt(L.http.downloaded).join(" "))}),this.player_.on("video-change",()=>{t.className="vjs-peertube-hidden",_.className="vjs-peertube-hidden"}),e}}X.registerComponent("P2PInfoButton",Av);const kv=X.getComponent("Component");class Iv extends kv{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=Fl({shortUUID:this.options_.shortUUID()});return cf({url:e,startTime:this.player().currentTime()})}}X.registerComponent("PeerTubeLinkButton",Iv);const Rv=X.getComponent("Button"),Nf=class Xr extends Rv{constructor(e,t){super(e,t),this.theaterButtonOptions=t;const i=Cf();i===!0&&(this.player().addClass(Xr.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"),Af(e),this.player_.trigger("theater-change",e)}handleClick(){this.player_.toggleClass(Xr.THEATER_MODE_CLASS),this.handleTheaterChange()}isTheaterEnabled(){return this.player_.hasClass(Xr.THEATER_MODE_CLASS)}updateShowing(){this.theaterButtonOptions.isDisplayed()?this.show():this.hide()}};Ue(Nf,"THEATER_MODE_CLASS","vjs-theater-enabled");let Pv=Nf;X.registerComponent("TheaterButton",Pv);const Dv=X.getComponent("ClickableComponent");class xv extends Dv{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",xv);const Mv=X.getComponent("Menu"),Ov=X.getComponent("Component");class Bf extends Mv{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()}}}Ov.registerComponent("MenuFocusFixed",Bf);const Fv=X.getComponent("MenuItem");class Uf extends Fv{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",Uf);const Nv=X.getComponent("Menu"),Bv=X.getComponent("MenuButton");class Uv extends Bv{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 Nv(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 Uf(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",Uv);const Hf=X.getComponent("Component");class Hv extends Hf{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()}}Hf.registerComponent("SettingsDialog",Hv);const $v=an("peertube:player:settings"),vh=X.getComponent("MenuItem"),jv=X.getComponent("Component");class vu extends vh{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=gf(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 vh))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 jv&&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(){$v("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()}}vu.prototype.contentElType="button";X.registerComponent("SettingsMenuItem",vu);const Vv=X.getComponent("Button"),$f=X.getComponent("Component");class Gv extends Vv{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 $f){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 Bf(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=gf(e);const n=Object.assign({},t,{entry:e,menuButton:this}),r=new vu(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}}$f.registerComponent("SettingsButton",Gv);const jf=X.getComponent("Component");class Kv extends jf{createEl(){return super.createEl("div",{className:"vjs-settings-panel",tabIndex:-1})}}jf.registerComponent("SettingsPanel",Kv);const Vf=X.getComponent("Component");class qv extends Vf{createEl(){return super.createEl("div",{className:"vjs-settings-panel-child",tabIndex:-1})}}Vf.registerComponent("SettingsPanelChild",qv);const Wv=X.getComponent("ClickableComponent");class Gf extends Wv{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",Gf);const Kf=X.getComponent("Component");class qf extends Kf{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 f="";n.startTimestamp&&(f+=sn(n.startTimestamp)),n.stopTimestamp&&(f+=" - "+sn(n.stopTimestamp));const m=super.createEl("div",{innerText:f,className:"timestamps"});u.append(m)}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()}}Kf.registerComponent("PlaylistMenuItem",qf);const Wf=X.getComponent("Component");class zf extends Wf{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 f=new qf(this.player(),{element:p,onClicked:()=>this.onItemClicked(p)});h.appendChild(f.el()),this.menuItems.push(f)}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)}}Wf.registerComponent("PlaylistMenu",zf);const zv=X.getPlugin("plugin");class Yv extends zv{constructor(e,t){super(e,t),this.playlistMenu=new zf(e,t),this.playlistButton=new Gf(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",Yv);const zn=an("peertube:player:mobile"),Xv=X.getPlugin("plugin"),Tu=class Qr extends Xv{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=>Ne.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(zn("Handle touch start"),this.tapTimeout&&(clearTimeout(this.tapTimeout),this.tapTimeout=void 0),this.doubleTapping||this.lastTapEvent&&t.timeStamp-this.lastTapEvent.timeStamp<Qr.DOUBLE_TAP_DELAY_MS){zn("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(()=>{zn("No double tap detected, set user active state to "+this.newActiveState),this.player.removeClass("vjs-force-inactive"),this.player.userActive(this.newActiveState)},Qr.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;zn("Calculating double tap zone (player width: %d, offset X: %d)",t,n),n>.66*t?(this.seekAmount<0&&(this.seekAmount=0),this.seekAmount+=10,zn("Will forward %d seconds",this.seekAmount)):n<.33*t&&(this.seekAmount>0&&(this.seekAmount=0),this.seekAmount-=10,zn("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)},Qr.SET_CURRENT_TIME_DELAY)}};Ue(Tu,"DOUBLE_TAP_DELAY_MS",250);Ue(Tu,"SET_CURRENT_TIME_DELAY",750);let Qv=Tu;X.registerPlugin("peertubeMobile",Qv);const Jv=X.getComponent("Component");class Zv extends Jv{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",Zv);const eT=X.getPlugin("plugin"),_u=class Ds extends eT{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()+Ds.VOLUME_STEP)}},{accept:t=>this.isNaked(t,"ArrowDown"),cb:t=>{t.preventDefault(),this.player.volume(this.player.volume()-Ds.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()-Ds.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()+Ds.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()}};Ue(_u,"VOLUME_STEP",.1);Ue(_u,"SEEK_STEP",5);let tT=_u;X.registerPlugin("peerTubeHotkeysPlugin",tT);const ks=an("peertube:player:metrics"),iT=X.getPlugin("plugin");class nT extends iT{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,ks("Will track metrics on next play"),this.player.one("play",()=>{ks("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=>Ne.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,f;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=(f=t.p2p)==null?void 0:f.peersP2POnly,this.p2pEnabled=!!t.p2p,this.lastPlayerNetworkInfo=t})}trackResolutionChange(){this.player.on("resolution-change",(e,{initResolutionChange:t})=>{t!==!0&&(ks("Adding resolution change"),this.resolutionChanges++)})}trackErrors(){this.player.on("error",()=>{ks("Adding player error"),this.errors++})}trackBufferStalled(){this.player.on("buffer-stalled",()=>{ks("Adding buffer stalled"),this.bufferStalled++})}}X.registerPlugin("metrics",nT);function sT(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Yf={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,f){if(f=f||{},h=h.trim(),p=p.trim(),!p){if(!f.alwaysNormalize)return h;var m=u.parseURL(h);if(!m)throw new Error("Error trying to parse base URL.");return m.path=u.normalizePath(m.path),u.buildURLFromParts(m)}var T=u.parseURL(p);if(!T)throw new Error("Error trying to parse relative URL.");if(T.scheme)return f.alwaysNormalize?(T.path=u.normalizePath(T.path),u.buildURLFromParts(T)):p;var _=u.parseURL(h);if(!_)throw new Error("Error trying to parse base URL.");if(!_.netLoc&&_.path&&_.path[0]!=="/"){var b=n.exec(_.path);_.netLoc=b[1],_.path=b[2]}_.netLoc&&!_.path&&(_.path="/");var w={scheme:_.scheme,netLoc:T.netLoc,path:null,params:T.params,query:T.query,fragment:T.fragment};if(!T.netLoc&&(w.netLoc=_.netLoc,T.path[0]!=="/"))if(!T.path)w.path=_.path,T.params||(w.params=_.params,T.query||(w.query=_.query));else{var L=_.path,A=L.substring(0,L.lastIndexOf("/")+1)+T.path;w.path=u.normalizePath(A)}return w.path===null&&(w.path=f.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})()})(Yf);var Eu=Yf.exports;function Th(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 gt(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Th(Object(t),!0).forEach(function(i){oT(s,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):Th(Object(t)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(t,i))})}return s}function rT(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 aT(s){var e=rT(s,"string");return typeof e=="symbol"?e:String(e)}function oT(s,e,t){return e=aT(e),e in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function ct(){return ct=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},ct.apply(this,arguments)}const Ee=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},lT=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=uT},uT=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}({}),ke=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 En=function(){},$l={trace:En,debug:En,log:En,warn:En,info:En,error:En};let Os=$l;function cT(s){const e=self.console[s];return e?e.bind(self.console,`[${s}] >`):En}function hT(s,...e){e.forEach(function(t){Os[t]=s[t]?s[t].bind(s):cT(t)})}function dT(s,e){if(typeof console=="object"&&s===!0||typeof s=="object"){hT(s,"debug","log","info","warn","error");try{Os.log(`Debug logs enabled for "${e}" in hls.js version 1.5.20`)}catch{Os=$l}}else Os=$l}const W=Os,fT=/^(\d+)x(\d+)$/,_h=/(.+?)=(".*?"|.*?)(?:,|$)/g;class nt{constructor(e){typeof e=="string"&&(e=nt.parseAttrList(e)),ct(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=fT.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(_h.lastIndex=0;(t=_h.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 pT(s){return s!=="ID"&&s!=="CLASS"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function gT(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"}class Xf{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=ct(new nt({}),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"]);Ee(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(Ee(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&&Ee(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class xa{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 qe={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Qf{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[qe.AUDIO]:null,[qe.VIDEO]:null,[qe.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=Eu.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class Wo extends Qf{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 xa,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||!Ee(this.programDateTime))return null;const e=Ee(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[qe.AUDIO]=null,e[qe.VIDEO]=null,e[qe.AUDIOVIDEO]=null}}class mT extends Qf{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 xa,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 yT=10;class vT{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?Ee(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||yT}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 bu(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function TT(s){const e=jl(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function _T(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 ET(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=bu(o)):t=TT(o)}}return t}function jl(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}const ls=typeof self<"u"?self:void 0;var Ve={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},xt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function zo(s){switch(s){case xt.FAIRPLAY:return Ve.FAIRPLAY;case xt.PLAYREADY:return Ve.PLAYREADY;case xt.WIDEVINE:return Ve.WIDEVINE;case xt.CLEARKEY:return Ve.CLEARKEY}}var Ar={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Yo(s){if(s===Ar.WIDEVINE)return Ve.WIDEVINE;if(s===Ar.PLAYREADY)return Ve.PLAYREADY;if(s===Ar.CENC||s===Ar.CLEARKEY)return Ve.CLEARKEY}function Xo(s){switch(s){case Ve.FAIRPLAY:return xt.FAIRPLAY;case Ve.PLAYREADY:return xt.PLAYREADY;case Ve.WIDEVINE:return xt.WIDEVINE;case Ve.CLEARKEY:return xt.CLEARKEY}}function kr(s){const{drmSystems:e,widevineLicenseUrl:t}=s,i=e?[Ve.FAIRPLAY,Ve.WIDEVINE,Ve.PLAYREADY,Ve.CLEARKEY].filter(n=>!!e[n]):[];return!i[Ve.WIDEVINE]&&t&&i.push(Ve.WIDEVINE),i}const Jf=function(s){return ls!=null&&(s=ls.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function bT(s,e,t,i){let n;switch(s){case Ve.FAIRPLAY:n=["cenc","sinf"];break;case Ve.WIDEVINE:case Ve.PLAYREADY:n=["cenc"];break;case Ve.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return ST(n,e,t,i)}function ST(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 Zf(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=bu(u).subarray(0,16);return _T(h),h}}return null}function An(s,e,t){return Uint8Array.prototype.slice?s.slice(e,t):new Uint8Array(Array.prototype.slice.call(s,e,t))}const Su=(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,ep=(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,Ns=(s,e)=>{const t=e;let i=0;for(;Su(s,e);){i+=10;const n=Ma(s,e+6);i+=n,ep(s,e+10)&&(i+=10),e+=i}if(i>0)return s.subarray(t,t+i)},Ma=(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},CT=(s,e)=>Su(s,e)&&Ma(s,e+6)+10<=s.length-e,Cu=s=>{const e=ip(s);for(let t=0;t<e.length;t++){const i=e[t];if(tp(i))return RT(i)}},tp=s=>s&&s.key==="PRIV"&&s.info==="com.apple.streaming.transportStreamTimestamp",wT=s=>{const e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=Ma(s,4),i=10;return{type:e,size:t,data:s.subarray(i,i+t)}},ip=s=>{let e=0;const t=[];for(;Su(s,e);){const i=Ma(s,e+6);e+=10;const n=e+i;for(;e+8<n;){const r=wT(s.subarray(e)),o=LT(r);o&&t.push(o),e+=r.size+10}ep(s,e)&&(e+=10)}return t},LT=s=>s.type==="PRIV"?AT(s):s.type[0]==="W"?IT(s):kT(s),AT=s=>{if(s.size<2)return;const e=Ti(s.data,!0),t=new Uint8Array(s.data.subarray(e.length+1));return{key:s.type,info:e,data:t.buffer}},kT=s=>{if(s.size<2)return;if(s.type==="TXXX"){let t=1;const i=Ti(s.data.subarray(t),!0);t+=i.length+1;const n=Ti(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=Ti(s.data.subarray(1));return{key:s.type,data:e}},IT=s=>{if(s.type==="WXXX"){if(s.size<2)return;let t=1;const i=Ti(s.data.subarray(t),!0);t+=i.length+1;const n=Ti(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=Ti(s.data);return{key:s.type,data:e}},RT=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)}},Ti=(s,e=!1)=>{const t=PT();if(t){const p=t.decode(s);if(e){const f=p.indexOf("\0");return f!==-1?p.substring(0,f):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 Qo;function PT(){if(!navigator.userAgent.includes("PlayStation 4"))return!Qo&&typeof self.TextDecoder<"u"&&(Qo=new self.TextDecoder("utf-8")),Qo}const hi={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}},fa=Math.pow(2,32)-1,DT=[].push,np={video:1,audio:2,id3:3,text:4};function ht(s){return String.fromCharCode.apply(null,s)}function sp(s,e){const t=s[e]<<8|s[e+1];return t<0?65536+t:t}function we(s,e){const t=rp(s,e);return t<0?4294967296+t:t}function Eh(s,e){let t=we(s,e);return t*=Math.pow(2,32),t+=we(s,e+4),t}function rp(s,e){return s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3]}function Jo(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 xT(s){const e=s.byteLength;for(let t=0;t<e;){const i=we(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 De(s,e){const t=[];if(!e.length)return t;const i=s.byteLength;for(let n=0;n<i;){const r=we(s,n),o=ht(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=De(s.subarray(n+8,u),e.slice(1));h.length&&DT.apply(t,h)}n=u}return t}function MT(s){const e=[],t=s[0];let i=8;const n=we(s,i);i+=4;let r=0,o=0;t===0?(r=we(s,i),o=we(s,i+4),i+=8):(r=Eh(s,i),o=Eh(s,i+8),i+=16),i+=2;let u=s.length+o;const h=sp(s,i);i+=2;for(let p=0;p<h;p++){let f=i;const m=we(s,f);f+=4;const T=m&2147483647;if((m&2147483648)>>>31===1)return W.warn("SIDX has hierarchical references (not supported)"),null;const b=we(s,f);f+=4,e.push({referenceSize:T,subsegmentDuration:b,info:{duration:b/n,start:u,end:u+T-1}}),u+=T,f+=4,i=f}return{earliestPresentationTime:r,timescale:n,version:t,referencesCount:h,references:e}}function ap(s){const e=[],t=De(s,["moov","trak"]);for(let n=0;n<t.length;n++){const r=t[n],o=De(r,["tkhd"])[0];if(o){let u=o[0];const h=we(o,u===0?12:20),p=De(r,["mdia","mdhd"])[0];if(p){u=p[0];const f=we(p,u===0?12:20),m=De(r,["mdia","hdlr"])[0];if(m){const T=ht(m.subarray(8,12)),_={soun:qe.AUDIO,vide:qe.VIDEO}[T];if(_){const b=De(r,["mdia","minf","stbl","stsd"])[0],w=OT(b);e[h]={timescale:f,type:_},e[_]=gt({timescale:f,id:h},w)}}}}}return De(s,["moov","mvex","trex"]).forEach(n=>{const r=we(n,4),o=e[r];o&&(o.default={duration:we(n,12),flags:we(n,20)})}),e}function OT(s){const e=s.subarray(8),t=e.subarray(86),i=ht(e.subarray(4,8));let n=i;const r=i==="enca"||i==="encv";if(r){const u=De(e,[i])[0].subarray(i==="enca"?28:78);De(u,["sinf"]).forEach(p=>{const f=De(p,["schm"])[0];if(f){const m=ht(f.subarray(4,8));if(m==="cbcs"||m==="cenc"){const T=De(p,["frma"])[0];T&&(n=ht(T))}}})}switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const o=De(t,["avcC"])[0];n+="."+Ir(o[1])+Ir(o[2])+Ir(o[3]);break}case"mp4a":{const o=De(e,[i])[0],u=De(o.subarray(28),["esds"])[0];if(u&&u.length>12){let h=4;if(u[h++]!==3)break;h=Zo(u,h),h+=2;const p=u[h++];if(p&128&&(h+=2),p&64&&(h+=u[h++]),u[h++]!==4)break;h=Zo(u,h);const f=u[h++];if(f===64)n+="."+Ir(f);else break;if(h+=12,u[h++]!==5)break;h=Zo(u,h);const m=u[h++];let T=(m&248)>>3;T===31&&(T+=1+((m&7)<<3)+((u[h]&224)>>5)),n+="."+T}break}case"hvc1":case"hev1":{const o=De(t,["hvcC"])[0],u=o[1],h=["","A","B","C"][u>>6],p=u&31,f=we(o,2),m=(u&32)>>5?"H":"L",T=o[12],_=o.subarray(6,12);n+="."+h+p,n+="."+f.toString(16).toUpperCase(),n+="."+m+T;let b="";for(let w=_.length;w--;){const L=_[w];(L||b)&&(b="."+L.toString(16).toUpperCase()+b)}n+=b;break}case"dvh1":case"dvhe":{const o=De(t,["dvcC"])[0],u=o[2]>>1&127,h=o[2]<<5&32|o[3]>>3&31;n+="."+li(u)+"."+li(h);break}case"vp09":{const o=De(t,["vpcC"])[0],u=o[4],h=o[5],p=o[6]>>4&15;n+="."+li(u)+"."+li(h)+"."+li(p);break}case"av01":{const o=De(t,["av1C"])[0],u=o[1]>>>5,h=o[1]&31,p=o[2]>>>7?"H":"M",f=(o[2]&64)>>6,m=(o[2]&32)>>5,T=u===2&&f?m?12:10:f?10:8,_=(o[2]&16)>>4,b=(o[2]&8)>>3,w=(o[2]&4)>>2,L=o[2]&3;n+="."+u+"."+li(h)+p+"."+li(T)+"."+_+"."+b+w+L+"."+li(1)+"."+li(1)+"."+li(1)+"."+0;break}}return{codec:n,encrypted:r}}function Zo(s,e){const t=e+5;for(;s[e++]&128&&e<t;);return e}function Ir(s){return("0"+s.toString(16).toUpperCase()).slice(-2)}function li(s){return(s<10?"0":"")+s}function FT(s,e){if(!s||!e)return s;const t=e.keyId;return t&&e.isCommonEncryption&&De(s,["moov","trak"]).forEach(n=>{const o=De(n,["mdia","minf","stbl","stsd"])[0].subarray(8);let u=De(o,["enca"]);const h=u.length>0;h||(u=De(o,["encv"])),u.forEach(p=>{const f=h?p.subarray(28):p.subarray(78);De(f,["sinf"]).forEach(T=>{const _=op(T);if(_){const b=_.subarray(8,24);b.some(w=>w!==0)||(W.log(`[eme] Patching keyId in 'enc${h?"a":"v"}>sinf>>tenc' box: ${hi.hexDump(b)} -> ${hi.hexDump(t)}`),_.set(t,8))}})})}),s}function op(s){const e=De(s,["schm"])[0];if(e){const t=ht(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return De(s,["schi","tenc"])[0]}return null}function NT(s,e){return De(e,["moof","traf"]).reduce((t,i)=>{const n=De(i,["tfdt"])[0],r=n[0],o=De(i,["tfhd"]).reduce((u,h)=>{const p=we(h,4),f=s[p];if(f){let m=we(n,4);if(r===1){if(m===fa)return W.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),u;m*=fa+1,m+=we(n,8)}const T=f.timescale||9e4,_=m/T;if(Ee(_)&&(u===null||_<u))return _}return u},null);return o!==null&&Ee(o)&&(t===null||o<t)?o:t},null)}function BT(s,e){let t=0,i=0,n=0;const r=De(s,["moof","traf"]);for(let o=0;o<r.length;o++){const u=r[o],h=De(u,["tfhd"])[0],p=we(h,4),f=e[p];if(!f)continue;const m=f.default,T=we(h,0)|m?.flags;let _=m?.duration;T&8&&(T&2?_=we(h,12):_=we(h,8));const b=f.timescale||9e4,w=De(u,["trun"]);for(let L=0;L<w.length;L++){if(t=UT(w[L]),!t&&_){const A=we(w[L],4);t=_*A}f.type===qe.VIDEO?i+=t/b:f.type===qe.AUDIO&&(n+=t/b)}}if(i===0&&n===0){let o=1/0,u=0,h=0;const p=De(s,["sidx"]);for(let f=0;f<p.length;f++){const m=MT(p[f]);if(m!=null&&m.references){o=Math.min(o,m.earliestPresentationTime/m.timescale);const T=m.references.reduce((_,b)=>_+b.info.duration||0,0);u=Math.max(u,T+m.earliestPresentationTime/m.timescale),h=u-o}}if(h&&Ee(h))return h}return i||n}function UT(s){const e=we(s,0);let t=8;e&1&&(t+=4),e&4&&(t+=4);let i=0;const n=we(s,4);for(let r=0;r<n;r++){if(e&256){const o=we(s,t);i+=o,t+=4}e&512&&(t+=4),e&1024&&(t+=4),e&2048&&(t+=4)}return i}function HT(s,e,t){De(e,["moof","traf"]).forEach(i=>{De(i,["tfhd"]).forEach(n=>{const r=we(n,4),o=s[r];if(!o)return;const u=o.timescale||9e4;De(i,["tfdt"]).forEach(h=>{const p=h[0],f=t*u;if(f){let m=we(h,4);if(p===0)m-=f,m=Math.max(m,0),Jo(h,4,m);else{m*=Math.pow(2,32),m+=we(h,8),m-=f,m=Math.max(m,0);const T=Math.floor(m/(fa+1)),_=Math.floor(m%(fa+1));Jo(h,4,T),Jo(h,8,_)}}})})})}function $T(s){const e={valid:null,remainder:null},t=De(s,["moof"]);if(t.length<2)return e.remainder=s,e;const i=t[t.length-1];return e.valid=An(s,0,i.byteOffset-8),e.remainder=An(s,i.byteOffset-8),e}function Kt(s,e){const t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function bh(s,e){const t=[],i=e.samples,n=e.timescale,r=e.id;let o=!1;return De(i,["moof"]).map(h=>{const p=h.byteOffset-8;De(h,["traf"]).map(m=>{const T=De(m,["tfdt"]).map(_=>{const b=_[0];let w=we(_,4);return b===1&&(w*=Math.pow(2,32),w+=we(_,8)),w/n})[0];return T!==void 0&&(s=T),De(m,["tfhd"]).map(_=>{const b=we(_,4),w=we(_,0)&16777215,L=(w&1)!==0,A=(w&2)!==0,P=(w&8)!==0;let O=0;const M=(w&16)!==0;let k=0;const N=(w&32)!==0;let H=8;b===r&&(L&&(H+=8),A&&(H+=4),P&&(O=we(_,H),H+=4),M&&(k=we(_,H),H+=4),N&&(H+=4),e.type==="video"&&(o=jT(e.codec)),De(m,["trun"]).map(G=>{const B=G[0],D=we(G,0)&16777215,K=(D&1)!==0;let ae=0;const Z=(D&4)!==0,oe=(D&256)!==0;let le=0;const he=(D&512)!==0;let pe=0;const ge=(D&1024)!==0,ee=(D&2048)!==0;let Q=0;const ye=we(G,4);let re=8;K&&(ae=we(G,re),re+=4),Z&&(re+=4);let ie=ae+p;for(let be=0;be<ye;be++){if(oe?(le=we(G,re),re+=4):le=O,he?(pe=we(G,re),re+=4):pe=k,ge&&(re+=4),ee&&(B===0?Q=we(G,re):Q=rp(G,re),re+=4),e.type===qe.VIDEO){let Te=0;for(;Te<pe;){const xe=we(i,ie);if(ie+=4,VT(o,i[ie])){const Me=i.subarray(ie,ie+xe);lp(Me,o?2:1,s+Q/n,t)}ie+=xe,Te+=xe+4}}s+=le/n}}))})})}),t}function jT(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 VT(s,e){if(s){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function lp(s,e,t,i){const n=up(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 f=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[f++]===181){const T=sp(n,f);if(f+=2,T===49){const _=we(n,f);if(f+=4,_===1195456820){const b=n[f++];if(b===3){const w=n[f++],L=31&w,A=64&w,P=A?2+L*3:0,O=new Uint8Array(P);if(A){O[0]=w;for(let M=1;M<P;M++)O[M]=n[f++]}i.push({type:b,payloadType:o,pts:t,bytes:O})}}}}}else if(o===5&&u>16){const m=[];for(let b=0;b<16;b++){const w=n[f++].toString(16);m.push(w.length==1?"0"+w:w),(b===3||b===5||b===7||b===9)&&m.push("-")}const T=u-16,_=new Uint8Array(T);for(let b=0;b<T;b++)_[b]=n[f++];i.push({payloadType:o,pts:t,uuid:m.join(""),userData:Ti(_),userDataBytes:_})}}}function up(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 GT(s){const e=s[0];let t="",i="",n=0,r=0,o=0,u=0,h=0,p=0;if(e===0){for(;ht(s.subarray(p,p+1))!=="\0";)t+=ht(s.subarray(p,p+1)),p+=1;for(t+=ht(s.subarray(p,p+1)),p+=1;ht(s.subarray(p,p+1))!=="\0";)i+=ht(s.subarray(p,p+1)),p+=1;i+=ht(s.subarray(p,p+1)),p+=1,n=we(s,12),r=we(s,16),u=we(s,20),h=we(s,24),p=28}else if(e===1){p+=4,n=we(s,p),p+=4;const m=we(s,p);p+=4;const T=we(s,p);for(p+=4,o=2**32*m+T,lT(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=we(s,p),p+=4,h=we(s,p),p+=4;ht(s.subarray(p,p+1))!=="\0";)t+=ht(s.subarray(p,p+1)),p+=1;for(t+=ht(s.subarray(p,p+1)),p+=1;ht(s.subarray(p,p+1))!=="\0";)i+=ht(s.subarray(p,p+1)),p+=1;i+=ht(s.subarray(p,p+1)),p+=1}const f=s.subarray(p,s.byteLength);return{schemeIdUri:t,value:i,timeScale:n,presentationTime:o,presentationTimeDelta:r,eventDuration:u,id:h,payload:f}}function KT(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 qT(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),KT([112,115,115,104],new Uint8Array([i,0,0,0]),s,r,n,o,t||new Uint8Array)}function WT(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=zT(n);e.push(r),i+=r.size}}return e}function zT(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=hi.hexDump(new Uint8Array(o,t+12,16)),h=s.getUint32(28);let p=null,f=null;if(r===0){if(e-32<h||h<22)return{offset:t,size:e};f=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 m=0;m<h;m++)p.push(new Uint8Array(o,t+32+m*16,16))}return{version:r,systemId:u,kids:p,data:f,offset:t,size:e}}let Rr={};class Bs{static clearKeyUriToKeyIdMap(){Rr={}}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 xt.FAIRPLAY:case xt.WIDEVINE:case xt.PLAYREADY:case xt.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=YT(e);return new Bs(this.method,this.uri,"identity",this.keyFormatVersions,i)}const t=ET(this.uri);if(t)switch(this.keyFormat){case xt.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case xt.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=qT(i,null,t),this.keyId=Zf(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=Rr[this.uri];if(!i){const n=Object.keys(Rr).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,n),Rr[this.uri]=i}this.keyId=i}return this}}function YT(s){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}const cp=/\{\$([a-zA-Z0-9-_]+)\}/g;function Sh(s){return cp.test(s)}function Pt(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]=Vl(s,r))}}function Vl(s,e){if(s.variableList!==null||s.hasVariableRefs){const t=s.variableList;return e.replace(cp,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 Ch(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 XT(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 In(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function QT(s){return typeof self<"u"&&s===self.ManagedMediaSource}const pa={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 JT(s,e){const t=pa[e];return!!t&&!!t[s.slice(0,4)]}function el(s,e,t=!0){return!s.split(",").some(i=>!hp(i,e,t))}function hp(s,e,t=!0){var i;const n=In(t);return(i=n?.isTypeSupported(Us(s,e)))!=null?i:!1}function Us(s,e){return`${e}/mp4;codecs="${s}"`}function wh(s){if(s){const e=s.substring(0,4);return pa.video[e]}return 2}function ga(s){return s.split(",").reduce((e,t)=>{const i=pa.video[t];return i?(i*2+e)/(e?3:2):(pa.audio[t]+e)/(e?2:1)},0)}const tl={};function ZT(s,e=!0){if(tl[s])return tl[s];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[s];for(let i=0;i<t.length;i++)if(hp(t[i],"audio",e))return tl[s]=t[i],t[i];return s}const e_=/flac|opus/i;function ma(s,e=!0){return s.replace(e_,t=>ZT(t.toLowerCase(),e))}function Lh(s,e){return s&&s!=="mp4a"?s:e&&e.split(",")[0]}function t_(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 Ah=/#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,kh=/#EXT-X-MEDIA:(.*)/g,i_=/^#EXT(?:INF|-X-TARGETDURATION):/m,Ih=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"),n_=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 mi{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 Eu.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return i_.test(e)}static parseMasterPlaylist(e,t){const i=Sh(e),n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},r=[];Ah.lastIndex=0;let o;for(;(o=Ah.exec(e))!=null;)if(o[1]){var u;const p=new nt(o[1]);Pt(n,p,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const f=Vl(n,o[2]),m={attrs:p,bitrate:p.decimalInteger("BANDWIDTH")||p.decimalInteger("AVERAGE-BANDWIDTH"),name:p.NAME,url:mi.resolve(f,t)},T=p.decimalResolution("RESOLUTION");T&&(m.width=T.width,m.height=T.height),s_(p.CODECS,m),(u=m.unknownCodecs)!=null&&u.length||r.push(m),n.levels.push(m)}else if(o[3]){const p=o[3],f=o[4];switch(p){case"SESSION-DATA":{const m=new nt(f);Pt(n,m,["DATA-ID","LANGUAGE","VALUE","URI"]);const T=m["DATA-ID"];T&&(n.sessionData===null&&(n.sessionData={}),n.sessionData[T]=m);break}case"SESSION-KEY":{const m=Rh(f,t,n);m.encrypted&&m.isSupported()?(n.sessionKeys===null&&(n.sessionKeys=[]),n.sessionKeys.push(m)):W.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${f}"`);break}case"DEFINE":{{const m=new nt(f);Pt(n,m,["NAME","VALUE","QUERYPARAM"]),Ch(n,m,t)}break}case"CONTENT-STEERING":{const m=new nt(f);Pt(n,m,["SERVER-URI","PATHWAY-ID"]),n.contentSteering={uri:mi.resolve(m["SERVER-URI"],t),pathwayId:m["PATHWAY-ID"]||"."};break}case"START":{n.startTimeOffset=Ph(f);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(kh.lastIndex=0;(n=kh.exec(e))!==null;){const p=new nt(n[1]),f=p.TYPE;if(f){const m=u[f],T=r[f]||[];r[f]=T,Pt(i,p,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const _=p.LANGUAGE,b=p["ASSOC-LANGUAGE"],w=p.CHANNELS,L=p.CHARACTERISTICS,A=p["INSTREAM-ID"],P={attrs:p,bitrate:0,id:h++,groupId:p["GROUP-ID"]||"",name:p.NAME||_||"",type:f,default:p.bool("DEFAULT"),autoselect:p.bool("AUTOSELECT"),forced:p.bool("FORCED"),lang:_,url:p.URI?mi.resolve(p.URI,t):""};if(b&&(P.assocLang=b),w&&(P.channels=w),L&&(P.characteristics=L),A&&(P.instreamId=A),m!=null&&m.length){const O=mi.findGroup(m,P.groupId)||m[0];Dh(P,O,"audioCodec"),Dh(P,O,"textCodec")}T.push(P)}}return r}static parseLevelPlaylist(e,t,i,n,r,o){const u=new vT(t),h=u.fragments;let p=null,f=0,m=0,T=0,_=0,b=null,w=new Wo(n,t),L,A,P,O=-1,M=!1,k=null;for(Ih.lastIndex=0,u.m3u8=e,u.hasVariableRefs=Sh(e);(L=Ih.exec(e))!==null;){M&&(M=!1,w=new Wo(n,t),w.start=T,w.sn=f,w.cc=_,w.level=i,p&&(w.initSegment=p,w.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null,k&&(w.setByteRange(k),k=null)));const B=L[1];if(B){w.duration=parseFloat(B);const D=(" "+L[2]).slice(1);w.title=D||null,w.tagList.push(D?["INF",B,D]:["INF",B])}else if(L[3]){if(Ee(w.duration)){w.start=T,P&&Oh(w,P,u),w.sn=f,w.level=i,w.cc=_,h.push(w);const D=(" "+L[3]).slice(1);w.relurl=Vl(u,D),xh(w,b),b=w,T+=w.duration,f++,m=0,M=!0}}else if(L[4]){const D=(" "+L[4]).slice(1);b?w.setByteRange(D,b):w.setByteRange(D)}else if(L[5])w.rawProgramDateTime=(" "+L[5]).slice(1),w.tagList.push(["PROGRAM-DATE-TIME",w.rawProgramDateTime]),O===-1&&(O=h.length);else{if(L=L[0].match(n_),!L){W.warn("No matches on slow regex match for level playlist!");continue}for(A=1;A<L.length&&!(typeof L[A]<"u");A++);const D=(" "+L[A]).slice(1),K=(" "+L[A+1]).slice(1),ae=L[A+2]?(" "+L[A+2]).slice(1):"";switch(D){case"PLAYLIST-TYPE":u.type=K.toUpperCase();break;case"MEDIA-SEQUENCE":f=u.startSN=parseInt(K);break;case"SKIP":{const Z=new nt(K);Pt(u,Z,["RECENTLY-REMOVED-DATERANGES"]);const oe=Z.decimalInteger("SKIPPED-SEGMENTS");if(Ee(oe)){u.skippedSegments=oe;for(let he=oe;he--;)h.unshift(null);f+=oe}const le=Z.enumeratedString("RECENTLY-REMOVED-DATERANGES");le&&(u.recentlyRemovedDateranges=le.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||ae)&&w.tagList.push(ae?[K,ae]:[K]);break;case"DISCONTINUITY":_++,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 nt(K);Pt(u,Z,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),Pt(u,Z,Z.clientAttrs);const oe=new Xf(Z,u.dateRanges[Z.ID]);oe.isValid||u.skippedSegments?u.dateRanges[oe.id]=oe:W.warn(`Ignoring invalid DATERANGE tag: "${K}"`),w.tagList.push(["EXT-X-DATERANGE",K]);break}case"DEFINE":{{const Z=new nt(K);Pt(u,Z,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in Z?XT(u,Z,o):Ch(u,Z,t)}break}case"DISCONTINUITY-SEQUENCE":_=parseInt(K);break;case"KEY":{const Z=Rh(K,t,u);if(Z.isSupported()){if(Z.method==="NONE"){P=void 0;break}P||(P={}),P[Z.keyFormat]&&(P=ct({},P)),P[Z.keyFormat]=Z}else W.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${K}"`);break}case"START":u.startTimeOffset=Ph(K);break;case"MAP":{const Z=new nt(K);if(Pt(u,Z,["BYTERANGE","URI"]),w.duration){const oe=new Wo(n,t);Mh(oe,Z,i,P),p=oe,w.initSegment=p,p.rawProgramDateTime&&!w.rawProgramDateTime&&(w.rawProgramDateTime=p.rawProgramDateTime)}else{const oe=w.byteRangeEndOffset;if(oe){const le=w.byteRangeStartOffset;k=`${oe-le}@${le}`}else k=null;Mh(w,Z,i,P),p=w,M=!0}break}case"SERVER-CONTROL":{const Z=new nt(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 nt(K);u.partTarget=Z.decimalFloatingPoint("PART-TARGET");break}case"PART":{let Z=u.partList;Z||(Z=u.partList=[]);const oe=m>0?Z[Z.length-1]:void 0,le=m++,he=new nt(K);Pt(u,he,["BYTERANGE","URI"]);const pe=new mT(he,w,t,le,oe);Z.push(pe),w.duration+=pe.duration;break}case"PRELOAD-HINT":{const Z=new nt(K);Pt(u,Z,["URI"]),u.preloadHint=Z;break}case"RENDITION-REPORT":{const Z=new nt(K);Pt(u,Z,["URI"]),u.renditionReports=u.renditionReports||[],u.renditionReports.push(Z);break}default:W.warn(`line parsed but not handled: ${L}`);break}}}b&&!b.relurl?(h.pop(),T-=b.duration,u.partList&&(u.fragmentHint=b)):u.partList&&(xh(w,b),w.cc=_,u.fragmentHint=w,P&&Oh(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=_,O>0&&r_(h,O),u}}function Rh(s,e,t){var i,n;const r=new nt(s);Pt(t,r,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const o=(i=r.METHOD)!=null?i:"",u=r.URI,h=r.hexadecimalInteger("IV"),p=r.KEYFORMATVERSIONS,f=(n=r.KEYFORMAT)!=null?n:"identity";u&&r.IV&&!h&&W.error(`Invalid IV: ${r.IV}`);const m=u?mi.resolve(u,e):"",T=(p||"1").split("/").map(Number).filter(Number.isFinite);return new Bs(o,m,f,T,h)}function Ph(s){const t=new nt(s).decimalFloatingPoint("TIME-OFFSET");return Ee(t)?t:null}function s_(s,e){let t=(s||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const n=t.filter(r=>JT(r,i));n.length&&(e[`${i}Codec`]=n.join(","),t=t.filter(r=>n.indexOf(r)===-1))}),e.unknownCodecs=t}function Dh(s,e,t){const i=e[t];i&&(s[t]=i)}function r_(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 xh(s,e){s.rawProgramDateTime?s.programDateTime=Date.parse(s.rawProgramDateTime):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime),Ee(s.programDateTime)||(s.programDateTime=null,s.rawProgramDateTime=null)}function Mh(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 Oh(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 He={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Le={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function Fh(s){const{type:e}=s;switch(e){case He.AUDIO_TRACK:return Le.AUDIO;case He.SUBTITLE_TRACK:return Le.SUBTITLE;default:return Le.MAIN}}function il(s,e){let t=s.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class a_{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:He.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:He.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:He.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:He.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===He.MANIFEST?r=i.manifestLoadPolicy.default:r=ct({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),Ee((t=e.deliveryDirectives)==null?void 0:t.part)){let p;if(e.type===He.LEVEL&&e.level!==null?p=this.hls.levels[e.level].details:e.type===He.AUDIO_TRACK&&e.id!==null?p=this.hls.audioTracks[e.id].details:e.type===He.SUBTITLE_TRACK&&e.id!==null&&(p=this.hls.subtitleTracks[e.id].details),p){const f=p.partTarget,m=p.targetduration;if(f&&m){const T=Math.max(f*3,m*.8)*1e3;r=ct({},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,f,m,T)=>{const _=this.getInternalLoader(m);this.resetInternalLoader(m.type);const b=p.data;if(b.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(p,m,new Error("no EXTM3U delimiter"),T||null,f);return}f.parsing.start=performance.now(),mi.isMediaPlaylist(b)?this.handleTrackOrLevelPlaylist(p,f,m,T||null,_):this.handleMasterPlaylist(p,f,m,T)},onError:(p,f,m,T)=>{this.handleNetworkError(f,m,!1,p,T)},onTimeout:(p,f,m)=>{this.handleNetworkError(f,m,!0,void 0,p)}};n.load(e,u,h)}handleMasterPlaylist(e,t,i,n){const r=this.hls,o=e.data,u=il(e,i),h=mi.parseMasterPlaylist(o,u);if(h.playlistParsingError){this.handleManifestParsingError(e,i,h.playlistParsingError,n,t);return}const{contentSteering:p,levels:f,sessionData:m,sessionKeys:T,startTimeOffset:_,variableList:b}=h;this.variableList=b;const{AUDIO:w=[],SUBTITLES:L,"CLOSED-CAPTIONS":A}=mi.parseMasterPlaylistMedia(o,u,h);w.length&&!w.some(O=>!O.url)&&f[0].audioCodec&&!f[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 nt({}),bitrate:0,url:""})),r.trigger(I.MANIFEST_LOADED,{levels:f,audioTracks:w,subtitles:L,captions:A,contentSteering:p,url:u,stats:t,networkDetails:n,sessionData:m,sessionKeys:T,startTimeOffset:_,variableList:b})}handleTrackOrLevelPlaylist(e,t,i,n,r){const o=this.hls,{id:u,level:h,type:p}=i,f=il(e,i),m=0,T=Ee(h)?h:Ee(u)?u:0,_=Fh(i),b=mi.parseLevelPlaylist(e.data,f,T,_,m,this.variableList);if(p===He.MANIFEST){const w={attrs:new nt({}),bitrate:0,details:b,name:"",url:f};o.trigger(I.MANIFEST_LOADED,{levels:[w],audioTracks:[],url:f,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=b,this.handlePlaylistLoaded(b,e,t,i,n,r)}handleManifestParsingError(e,t,i,n,r){this.hls.trigger(I.ERROR,{type:ke.NETWORK_ERROR,details:te.MANIFEST_PARSING_ERROR,fatal:t.type===He.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===He.LEVEL?o+=`: ${e.level} id: ${e.id}`:(e.type===He.AUDIO_TRACK||e.type===He.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 f=this.getInternalLoader(e);switch(e.type){case He.MANIFEST:h=i?te.MANIFEST_LOAD_TIMEOUT:te.MANIFEST_LOAD_ERROR,p=!0;break;case He.LEVEL:h=i?te.LEVEL_LOAD_TIMEOUT:te.LEVEL_LOAD_ERROR,p=!1;break;case He.AUDIO_TRACK:h=i?te.AUDIO_TRACK_LOAD_TIMEOUT:te.AUDIO_TRACK_LOAD_ERROR,p=!1;break;case He.SUBTITLE_TRACK:h=i?te.SUBTITLE_TRACK_LOAD_TIMEOUT:te.SUBTITLE_LOAD_ERROR,p=!1;break}f&&this.resetInternalLoader(e.type);const m={type:ke.NETWORK_ERROR,details:h,fatal:p,url:e.url,loader:f,context:e,error:u,networkDetails:t,stats:r};if(n){const T=t?.url||e.url;m.response=gt({url:T,data:void 0},n)}this.hls.trigger(I.ERROR,m)}handlePlaylistLoaded(e,t,i,n,r,o){const u=this.hls,{type:h,level:p,id:f,groupId:m,deliveryDirectives:T}=n,_=il(t,n),b=Fh(n),w=typeof n.level=="number"&&b===Le.MAIN?p:void 0;if(!e.fragments.length){const A=new Error("No Segments found in Playlist");u.trigger(I.ERROR,{type:ke.NETWORK_ERROR,details:te.LEVEL_EMPTY_ERROR,fatal:!1,url:_,error:A,reason:A.message,response:t,context:n,level:w,parent:b,networkDetails:r,stats:i});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const L=e.playlistParsingError;if(L){u.trigger(I.ERROR,{type:ke.NETWORK_ERROR,details:te.LEVEL_PARSING_ERROR,fatal:!1,url:_,error:L,reason:L.message,response:t,context:n,level:w,parent:b,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 He.MANIFEST:case He.LEVEL:u.trigger(I.LEVEL_LOADED,{details:e,level:w||0,id:f||0,stats:i,networkDetails:r,deliveryDirectives:T});break;case He.AUDIO_TRACK:u.trigger(I.AUDIO_TRACK_LOADED,{details:e,id:f||0,groupId:m||"",stats:i,networkDetails:r,deliveryDirectives:T});break;case He.SUBTITLE_TRACK:u.trigger(I.SUBTITLE_TRACK_LOADED,{details:e,id:f||0,groupId:m||"",stats:i,networkDetails:r,deliveryDirectives:T});break}}}function dp(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 fp(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 is(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 Gl(s,e,t,i){const n=s.mode;if(n==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const r=l_(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 o_(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 l_(s,e,t){const i=[],n=o_(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 Jr(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 ti={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};const u_=.25;function Kl(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Nh(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?gt({type:n},i):i))}return r}const Pr=(()=>{const s=Kl();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function nl(s,e){return s.getTime()/1e3-e}function c_(s){return Uint8Array.from(s.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class h_{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&&(is(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 dp(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=Kl();if(o)for(let u=0;u<r.length;u++){const h=r[u].type;if(h===ti.emsg&&!i||!n)continue;const p=ip(r[u].data);if(p){const f=r[u].pts;let m=f+r[u].duration;m>Pr&&(m=Pr),m-f<=0&&(m=f+u_);for(let _=0;_<p.length;_++){const b=p[_];if(!tp(b)){this.updateId3CueEnds(f,h);const w=Nh(o,f,m,b,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===Pr&&(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=f=>f.type===ti.audioId3&&h:n==="video"?p=f=>f.type===ti.emsg&&u:p=f=>f.type===ti.audioId3&&h||f.type===ti.emsg&&u,Gl(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 f=Object.keys(i).filter(m=>!o.includes(m));for(let m=f.length;m--;){const T=f[m];Object.keys(i[T].cues).forEach(_=>{n.removeCue(i[T].cues[_])}),delete i[T]}}const u=t.fragments[t.fragments.length-1];if(o.length===0||!Ee(u?.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const h=u.programDateTime/1e3-u.start,p=Kl();for(let f=0;f<o.length;f++){const m=o[f],T=r[m],_=nl(T.startDate,h),b=i[m],w=b?.cues||{};let L=b?.durationKnown||!1,A=Pr;const P=T.endDate;if(P)A=nl(P,h),L=!0;else if(T.endOnNext&&!L){const M=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);M&&(A=nl(M.startDate,h),L=!0)}const O=Object.keys(T.attr);for(let M=0;M<O.length;M++){const k=O[M];if(!pT(k))continue;const N=w[k];if(N)L&&!b.durationKnown&&(N.endTime=A);else if(p){let H=T.attr[k];gT(k)&&(H=c_(H));const G=Nh(p,_,A,{key:k,data:H},ti.dateRange);G&&(G.id=m,this.id3Track.addCue(G),w[k]=G)}}i[m]={cues:w,dateRange:T,durationKnown:L}}}}class d_{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 f=n;return p+Math.min(this.stallCount*1,f)}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 f=Math.min(2,Math.max(1,r)),m=Math.round(2/(1+Math.exp(-.75*u-this.edgeStalled))*20)/20;e.playbackRate=Math.min(f,Math.max(1,m))}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 ql=["NONE","TYPE-0","TYPE-1",null];function f_(s){return ql.indexOf(s)>-1}const ya=["SDR","PQ","HLG"];function p_(s){return!!s&&ya.indexOf(s)>-1}var Zr={No:"",Yes:"YES",v2:"v2"};function Bh(s){const{canSkipUntil:e,canSkipDateRanges:t,age:i}=s,n=i<e/2;return e&&n?t?Zr.v2:Zr.Yes:Zr.No}class Uh{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 us{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 Hh(this._audioGroups,e)}hasSubtitleGroup(e){return Hh(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 Hh(s,e){return!e||!s?!1:s.indexOf(e)!==-1}function sl(s,e){const t=e.startPTS;if(Ee(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 pp(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,f=e.endPTS;if(Ee(p)){const L=Math.abs(p-t);Ee(e.deltaPTS)?e.deltaPTS=Math.max(L,e.deltaPTS):e.deltaPTS=L,u=Math.max(t,p),t=Math.min(t,p),n=Math.min(n,e.startDTS),h=Math.min(i,f),i=Math.max(i,f),r=Math.max(r,e.endDTS)}const m=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 _;const b=T-s.startSN,w=s.fragments;for(w[b]=e,_=b;_>0;_--)sl(w[_],w[_-1]);for(_=b;_<w.length-1;_++)sl(w[_],w[_+1]);return s.fragmentHint&&sl(w[w.length-1],s.fragmentHint),s.PTSKnown=s.alignedSliding=!0,m}function g_(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;v_(s,e,(u,h,p,f)=>{if(e.skippedSegments&&h.cc!==u.cc){const m=u.cc-h.cc;for(let T=p;T<f.length;T++)f[T].cc+=m}Ee(u.startPTS)&&Ee(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=m_(s.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));e.startCC=e.fragments[0].cc,e.endCC=r[r.length-1].cc}y_(s.partList,e.partList,(u,h)=>{h.elementaryStreams=u.elementaryStreams,h.stats=u.stats}),n?pp(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):gp(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 m_(s,e,t){const i=ct({},s);return t&&t.forEach(n=>{delete i[n]}),Object.keys(e).forEach(n=>{const r=new Xf(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 y_(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 v_(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 f=h[o+p];let m=u[p];i&&!m&&p<i&&(m=e.fragments[p]=f),f&&m&&t(f,m,p,u)}}function gp(s,e){const t=e.startSN+e.skippedSegments-s.startSN,i=s.fragments;t<0||t>=i.length||Wl(e,i[t].start)}function Wl(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 T_(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 __(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 $h(s,e,t){var i;return s!=null&&s.details?mp((i=s.details)==null?void 0:i.partList,e,t):null}function mp(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 yp(s){s.forEach((e,t)=>{const{details:i}=e;i!=null&&i.fragments&&i.fragments.forEach(n=>{n.level=t})})}function va(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 jh(s,e){const t=va(e);return s.default[`${t?"timeout":"error"}Retry`]}function wu(s,e){const t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function Vh(s){return gt(gt({},s),{errorRetry:null,timeoutRetry:null})}function Ta(s,e,t,i){if(!s)return!1;const n=i?.code,r=e<s.maxNumRetry&&(E_(n)||!!t);return s.shouldRetry?s.shouldRetry(s,e,t,i,r):r}function E_(s){return s===0&&navigator.onLine===!1||!!s&&(s<400||s>499)}const vp={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 b_(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!Ee(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(C_(e,t,o))return o}return null}function _a(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)&&zl(t,i,r)===0||S_(r,s,Math.min(n,i))))return r;const o=vp.search(e,zl.bind(null,t,i));return o&&(o!==s||!r)?o:r}function S_(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 zl(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 C_(s,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>s}function w_(s,e){return vp.search(s,t=>t.cc<e?1:t.cc>e?-1:0)}var Tt={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Jt={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2};class L_{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===Le.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:Tt.DoNothing,flags:Jt.None};return}case te.FRAG_GAP:case te.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Tt.SendAlternateToPenaltyBox;return}case te.LEVEL_EMPTY_ERROR:case te.LEVEL_PARSING_ERROR:{var u,h;const p=t.parent===Le.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===He.AUDIO_TRACK&&p.hasAudioGroup(o.groupId)||o.type===He.SUBTITLE_TRACK&&p.hasSubtitleGroup(o.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=Tt.SendAlternateToPenaltyBox,t.errorAction.flags=Jt.MoveAllAlternatesMatchingHost;return}}return;case te.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const p=r.levels[r.loadLevel],f=p?.attrs["HDCP-LEVEL"];f?t.errorAction={action:Tt.SendAlternateToPenaltyBox,flags:Jt.MoveAllAlternatesMatchingHDCP,hdcpLevel:f}: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:Tt.DoNothing,flags:Jt.None};return}t.type===ke.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=jh(i.config.playlistLoadPolicy,e),r=this.playlistError++;if(Ta(n,r,va(e),e.response))return{action:Tt.RetryRequest,flags:Jt.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=jh(e.details.startsWith("key")?o:r,e),h=t.levels.reduce((f,m)=>f+m.fragmentError,0);if(n&&(e.details!==te.FRAG_GAP&&n.fragmentError++,Ta(u,h,va(e),e.response)))return{action:Tt.RetryRequest,flags:Jt.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 f=-1;const{levels:m,loadLevel:T,minAutoLevel:_,maxAutoLevel:b}=i;i.autoLevelEnabled||(i.loadLevel=-1);const w=(r=e.frag)==null?void 0:r.type,A=(w===Le.AUDIO&&p===te.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(p===te.BUFFER_ADD_CODEC_ERROR||p===te.BUFFER_APPEND_ERROR))&&m.some(({audioCodec:N})=>n.audioCodec!==N),O=e.sourceBufferName==="video"&&(p===te.BUFFER_ADD_CODEC_ERROR||p===te.BUFFER_APPEND_ERROR)&&m.some(({codecSet:N,audioCodec:H})=>n.codecSet!==N&&n.audioCodec===H),{type:M,groupId:k}=(o=e.context)!=null?o:{};for(let N=m.length;N--;){const H=(N+T)%m.length;if(H!==T&&H>=_&&H<=b&&m[H].loadError===0){var u,h;const G=m[H];if(p===te.FRAG_GAP&&w===Le.MAIN&&e.frag){const B=m[H].details;if(B){const D=_a(e.frag,B.fragments,e.frag.start);if(D!=null&&D.gap)continue}}else{if(M===He.AUDIO_TRACK&&G.hasAudioGroup(k)||M===He.SUBTITLE_TRACK&&G.hasSubtitleGroup(k))continue;if(w===Le.AUDIO&&(u=n.audioGroups)!=null&&u.some(B=>G.hasAudioGroup(B))||w===Le.SUBTITLE&&(h=n.subtitleGroups)!=null&&h.some(B=>G.hasSubtitleGroup(B))||A&&n.audioCodec===G.audioCodec||!A&&n.audioCodec!==G.audioCodec||O&&n.codecSet===G.codecSet)continue}f=H;break}}if(f>-1&&i.loadLevel!==f)return e.levelRetry=!0,this.playlistError=0,{action:Tt.SendAlternateToPenaltyBox,flags:Jt.None,nextAutoLevel:f}}return{action:Tt.SendAlternateToPenaltyBox,flags:Jt.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case Tt.DoNothing:break;case Tt.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 Jt.None:this.switchLevel(e,o);break;case Jt.MoveAllAlternatesMatchingHDCP:r&&(t.maxHdcpLevel=ql[ql.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 Lu{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 f=Math.min(t.age-t.partTarget,t.targetduration);h>=0&&f>t.partTarget&&(h+=1)}const p=i&&Bh(i);return new Uh(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&&g_(i,n),!this.canLoad||!n.live)return;let h,p,f;if(n.canBlockReload&&n.endSN&&n.advanced){const L=this.hls.config.lowLatencyMode,A=n.lastPartSn,P=n.endSN,O=n.lastPartIndex,M=O!==-1,k=A===P,N=L?0:O;M?(p=k?P+1:A,f=k?N:O+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,f!==void 0){const K=Math.round(B%n.targetduration/n.partTarget);f+=K}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${H.toFixed(2)}s goal: ${B} skip sn ${D} to part ${f}`)}n.tuneInGoal=B}if(h=this.getDeliveryDirectives(n,t.deliveryDirectives,p,f),L||!k){this.loadPlaylist(h);return}}else(n.canBlockReload||n.canSkipUntil)&&(h=this.getDeliveryDirectives(n,t.deliveryDirectives,p,f));const m=this.hls.mainForwardBufferInfo,T=m?m.end-m.len:0,_=(n.edge-T)*1e3,b=T_(n,_);n.updated&&o>this.requestScheduled+b&&(this.requestScheduled=r.loading.start),p!==void 0&&n.canBlockReload?this.requestScheduled=r.loading.first+b-(n.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+b<o?this.requestScheduled=o:this.requestScheduled-o<=0&&(this.requestScheduled+=b);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=Bh(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,n=t.part,r=Zr.No),new Uh(i,n,r)}checkRetry(e){const t=e.details,i=va(e),n=e.errorAction,{action:r,retryCount:o=0,retryConfig:u}=n||{},h=!!n&&!!u&&(r===Tt.RetryRequest||!n.resolved&&r===Tt.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 f=wu(u,o);this.timer=self.setTimeout(()=>this.loadPlaylist(),f),this.warn(`Retrying playlist loading ${o+1}/${u.maxNumRetry} after "${t}" in ${f}ms`)}e.levelRetry=!0,n.resolved=!0}return h}}class Yn{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 A_{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 Yn(e),this.fast_=new Yn(t),this.defaultTTFB_=n,this.ttfb_=new Yn(e)}update(e,t){const{slow_:i,fast_:n,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new Yn(e,i.getEstimate(),i.getTotalWeight())),n.halfLife!==t&&(this.fast_=new Yn(t,n.getEstimate(),n.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new Yn(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 Tp={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Gh={};function k_(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 f=null;if(o!=null&&o.length)try{o.length===1&&o[0]?f=e.groups[o[0]].channels:f=o.reduce((m,T)=>{if(T){const _=e.groups[T];if(!_)throw new Error(`Audio track group ${T} not found`);Object.keys(_.channels).forEach(b=>{m[b]=(m[b]||0)+_.channels[b]})}return m},{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))||!!f&&Ee(p)&&Object.keys(f).some(m=>parseInt(m)>p)}function I_(s,e,t){const i=s.videoCodec,n=s.audioCodec;if(!i||!n||!t)return Promise.resolve(Tp);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:gt(gt({},r),{},{contentType:Us(h,"video")})}));return n&&s.audioGroups&&s.audioGroups.forEach(h=>{var p;h&&((p=e.groups[h])==null||p.tracks.forEach(f=>{if(f.groupId===h){const m=f.channels||"",T=parseFloat(m);Ee(T)&&T>2&&u.push.apply(u,n.split(",").map(_=>({type:"media-source",audio:{contentType:Us(_,"audio"),channels:""+T}})))}}))}),Promise.all(u.map(h=>{const p=R_(h);return Gh[p]||(Gh[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 R_(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 P_(){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 D_(s,e){let t=!1,i=[];return s&&(t=s!=="SDR",i=[s]),e&&(i=e.allowedVideoRanges||ya.slice(0),t=e.preferHDR!==void 0?e.preferHDR:P_(),t?i=i.filter(n=>n!=="SDR"):i=["SDR"]),{preferHDR:t,allowedVideoRanges:i}}function x_(s,e,t,i,n){const r=Object.keys(s),o=i?.channels,u=i?.audioCodec,h=o&&parseInt(o)===2;let p=!0,f=!1,m=1/0,T=1/0,_=1/0,b=0,w=[];const{preferHDR:L,allowedVideoRanges:A}=D_(e,n);for(let k=r.length;k--;){const N=s[r[k]];p=N.channels[2]>0,m=Math.min(m,N.minHeight),T=Math.min(T,N.minFramerate),_=Math.min(_,N.minBitrate);const H=A.filter(G=>N.videoRanges[G]>0);H.length>0&&(f=!0,w=H)}m=Ee(m)?m:0,T=Ee(T)?T:0;const P=Math.max(1080,m),O=Math.max(30,T);return _=Ee(_)?_:t,t=Math.max(_,t),f||(e=void 0,w=[]),{codecSet:r.reduce((k,N)=>{const H=s[N];if(N===k)return k;if(H.minBitrate>t)return ki(N,`min bitrate of ${H.minBitrate} > current estimate of ${t}`),k;if(!H.hasDefaultAudio)return ki(N,"no renditions with default or auto-select sound found"),k;if(u&&N.indexOf(u.substring(0,4))%5!==0)return ki(N,`audio codec preference "${u}" not found`),k;if(o&&!h){if(!H.channels[o])return ki(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 ki(N,"no renditions with stereo sound found"),k;return H.minHeight>P?(ki(N,`min resolution of ${H.minHeight} > maximum of ${P}`),k):H.minFramerate>O?(ki(N,`min framerate of ${H.minFramerate} > maximum of ${O}`),k):w.some(G=>H.videoRanges[G]>0)?H.maxScore<b?(ki(N,`max score of ${H.maxScore} < selected max of ${b}`),k):k&&(ga(N)>=ga(k)||H.fragmentError>s[k].fragmentError)?k:(b=H.maxScore,N):(ki(N,`no variants with VIDEO-RANGE of ${JSON.stringify(w)} found`),k)},void 0),videoRanges:w,preferHDR:L,minFramerate:T,minBitrate:_}}function ki(s,e){W.log(`[abr] start candidates with "${s}" ignored because ${e}`)}function M_(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 O_(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 f=e.groups[p];f&&(u.hasDefaultAudio=u.hasDefaultAudio||e.hasDefaultAudio?f.hasDefault:f.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(f.channels).forEach(m=>{u.channels[m]=(u.channels[m]||0)+f.channels[m]}))}),n},{})}function yi(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(kn(s,n,t))return i}return-1}function kn(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)||F_(s.characteristics||"",e.characteristics))&&(t===void 0||t(s,e))}function F_(s,e=""){const t=s.split(","),i=e.split(",");return t.length===i.length&&!t.some(n=>i.indexOf(n)===-1)}function bn(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 N_(s,e,t,i,n){const r=e[i],u=e.reduce((T,_,b)=>{const w=_.uri;return(T[w]||(T[w]=[])).push(b),T},{})[r.uri];u.length>1&&(i=Math.max.apply(Math,u));const h=r.videoRange,p=r.frameRate,f=r.codecSet.substring(0,4),m=Kh(e,i,T=>{if(T.videoRange!==h||T.frameRate!==p||T.codecSet.substring(0,4)!==f)return!1;const _=T.audioGroups,b=t.filter(w=>!_||_.indexOf(w.groupId)!==-1);return yi(s,b,n)>-1});return m>-1?m:Kh(e,i,T=>{const _=T.audioGroups,b=t.filter(w=>!_||_.indexOf(w.groupId)!==-1);return yi(s,b,n)>-1})}function Kh(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 B_{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,f=u-h.loading.start,m=n.minAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||t.level<=m){this.clearTimer(),this._nextAutoLevel=-1;return}if(!r||o.paused||!o.playbackRate||!o.readyState)return;const T=n.mainForwardBufferInfo;if(T===null)return;const _=this.bwEstimator.getEstimateTTFB(),b=Math.abs(o.playbackRate);if(f<=Math.max(_,1e3*(p/(b*2))))return;const w=T.len/b,L=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&L>-1,P=this.getBwEstimate(),O=n.levels,M=O[t.level],k=h.total||Math.max(h.loaded,Math.round(p*M.averageBitrate/8));let N=A?f-L:f;N<1&&A&&(N=Math.min(f,h.loaded*8/P));const H=A?h.loaded*1e3/N:0,G=H?(k-h.loaded)/H:k*8/P+_/1e3;if(G<=w)return;const B=H?H*8:P;let D=Number.POSITIVE_INFINITY,K;for(K=t.level-1;K>m;K--){const Z=O[K].maxBitrate;if(D=this.getTimeToLoadFrag(_/1e3,B,p*Z,!O[K].details),D<w)break}if(D>=G||D>p*10)return;n.nextLoadLevel=n.nextAutoLevel=K,A?this.bwEstimator.sample(f-Math.min(_,L),h.loaded):this.bwEstimator.sampleTTFB(f);const ae=O[K].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>ae&&this.resetEstimator(ae),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: ${L|0} ms
      Current BW estimate: ${Ee(P)?P|0:"Unknown"} bps
      New BW estimate: ${this.getBwEstimate()|0} bps
      Switching to level ${K} @ ${ae|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 A_(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 m=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(h-Math.min(m,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;Ee(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===Le.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!==Le.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 f=r.abrBandWidthFactor,m=r.abrBandWidthUpFactor;if(p){const L=this.findBestLevel(h,o,n,p,0,f,m);if(L>=0)return L}let T=u?Math.min(u,r.maxStarvationDelay):r.maxStarvationDelay;if(!p){const L=this.bitrateTestDelay;L&&(T=(u?Math.min(u,r.maxLoadingDelay):r.maxLoadingDelay)-L,W.info(`[abr] bitrate test took ${Math.round(1e3*L)}ms, set first fragment max fetchDuration to ${Math.round(1e3*T)} ms`),f=m=1)}const _=this.findBestLevel(h,o,n,p,T,f,m);if(W.info(`[abr] ${p?"rebuffering expected":"buffer is empty"}, optimal quality level ${_}`),_>-1)return _;const b=i.levels[o],w=i.levels[i.loadLevel];return b?.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,f=this.lastLoadedFragLevel,m=f===-1?this.hls.firstLevel:f,{fragCurrent:T,partCurrent:_}=this,{levels:b,allAudioTracks:w,loadLevel:L,config:A}=this.hls;if(b.length===1)return 0;const P=b[m],O=!!(P!=null&&(h=P.details)!=null&&h.live),M=L===-1||f===-1;let k,N="SDR",H=P?.frameRate||0;const{audioPreference:G,videoPreference:B}=A,D=this.audioTracksByGroup||(this.audioTracksByGroup=M_(w));if(M){if(this.firstSelection!==-1)return this.firstSelection;const le=this.codecTiers||(this.codecTiers=O_(b,D,t,i)),he=x_(le,N,e,G,B),{codecSet:pe,videoRanges:ge,minFramerate:ee,minBitrate:Q,preferHDR:ye}=he;k=pe,N=ye?ge[ge.length-1]:ge[0],H=ee,e=Math.max(e,Q),W.log(`[abr] picked start tier ${JSON.stringify(he)}`)}else k=P?.codecSet,N=P?.videoRange;const K=_?_.duration:T?T.duration:0,ae=this.bwEstimator.getEstimateTTFB()/1e3,Z=[];for(let le=i;le>=t;le--){var oe;const he=b[le],pe=le>m;if(!he)continue;if(A.useMediaCapabilities&&!he.supportedResult&&!he.supportedPromise){const be=navigator.mediaCapabilities;typeof be?.decodingInfo=="function"&&k_(he,D,N,H,e,G)?(he.supportedPromise=I_(he,D,be),he.supportedPromise.then(Te=>{if(!this.hls)return;he.supportedResult=Te;const xe=this.hls.levels,Me=xe.indexOf(he);Te.error?W.warn(`[abr] MediaCapabilities decodingInfo error: "${Te.error}" for level ${Me} ${JSON.stringify(Te)}`):Te.supported||(W.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${Me} ${JSON.stringify(Te)}`),Me>-1&&xe.length>1&&(W.log(`[abr] Removing unsupported level ${Me}`),this.hls.removeLevel(Me)))})):he.supportedResult=Tp}if(k&&he.codecSet!==k||N&&he.videoRange!==N||pe&&H>he.frameRate||!pe&&H>0&&H<he.frameRate||he.supportedResult&&!((oe=he.supportedResult.decodingInfoResults)!=null&&oe[0].smooth)){Z.push(le);continue}const ge=he.details,ee=(_?ge?.partTarget:ge?.averagetargetduration)||K;let Q;pe?Q=u*e:Q=o*e;const ye=K&&n>=K*2&&r===0?b[le].averageBitrate:b[le].maxBitrate,re=this.getTimeToLoadFrag(ae,Q,ye*ee,ge===void 0);if(Q>=ye&&(le===f||he.loadError===0&&he.fragmentError===0)&&(re<=ae||!Ee(re)||O&&!this.bitrateTestDelay||re<p)){const be=this.forcedAutoLevel;return le!==L&&(be===-1||be!==L)&&(Z.length&&W.trace(`[abr] Skipped level(s) ${Z.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${b[Z[0]].codecs}" ${b[Z[0]].videoRange}; not compatible with "${P.codecs}" ${N}`),W.info(`[abr] switch candidate:${m}->${le} adjustedbw(${Math.round(Q)})-bitrate=${Math.round(Q-ye)} ttfb:${ae.toFixed(1)} avgDuration:${ee.toFixed(1)} maxFetchDuration:${p.toFixed(1)} fetchDuration:${re.toFixed(1)} firstSelection:${M} codecSet:${k} videoRange:${N} hls.loadLevel:${L}`)),M&&(this.firstSelection=le),le}}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 U_{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 pt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class H_{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 f=!this.isTimeBuffered(p.startPTS,p.endPTS,t);return f&&this.removeFragment(u.body),f})})}detectPartialFragments(e){const t=this.timeRanges,{frag:i,part:n}=e;if(!t||i.sn==="initSegment")return;const r=Xn(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 f=t[h],m=u||p.partial===!0;o.range[h]=this.getBufferedTimes(i,n,m,f)}),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),Dr(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=Xn(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 f=0;f<n.length;f++){const m=n.start(f)-this.bufferPadding,T=n.end(f)+this.bufferPadding;if(p>=m&&h<=T){r.time.push({startPTS:Math.max(o,n.start(f)),endPTS:Math.min(u,n.end(f))});break}else if(o<T&&u>m){const _=Math.max(o,n.start(f)),b=Math.min(u,n.end(f));b>_&&(r.partial=!0,r.time.push({startPTS:_,endPTS:b}))}else if(u<=m)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 f=h[p];f&&Dr(f)&&(n=f.body.start-u,r=f.body.end+u,e>=n&&e<=r&&(i=Math.min(e-n,r-e),o<=i&&(t=f.body,o=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Dr(t))}getState(e){const t=Xn(e),i=this.fragments[t];return i?i.buffered?Dr(i)?pt.PARTIAL:pt.OK:pt.APPENDING:pt.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=Xn(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=Xn(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=Xn(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 Dr(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 Xn(s){return`${s.type}_${s.level}_${s.sn}`}const $_={length:0,start:()=>0,end:()=>0};class Ze{static isBuffered(e,t){try{if(e){const i=Ze.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=Ze.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,f){const m=p.start-f.start;return m||f.end-p.end});let n=[];if(i)for(let p=0;p<e.length;p++){const f=n.length;if(f){const m=n[f-1].end;e[p].start-m<i?e[p].end>m&&(n[f-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 f=n[p].start,m=n[p].end;if(t+i>=f&&t<m)u=f,h=m,r=h-t;else if(t+i<f){o=f;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),$_}}}class Au{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=xr(),this.buffering={audio:xr(),video:xr(),audiovideo:xr()},this.level=e,this.sn=t,this.id=i,this.size=n,this.part=r,this.partial=o}}function xr(){return{start:0,executeStart:0,executeEnd:0,end:0}}function ea(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 j_(s,e,t){return!!(e&&(t.endCC>t.startCC||s&&s.cc<t.startCC))}function V_(s,e){const t=s.fragments,i=e.fragments;if(!i.length||!t.length){W.log("No fragments to align");return}const n=ea(t,i[0].cc);if(!n||n&&!n.startPTS){W.log("No frag in previous level to align on");return}return n}function qh(s,e){if(s){const t=s.start+e;s.start=s.startPTS=t,s.endPTS=t+s.duration}}function _p(s,e){const t=e.fragments;for(let i=0,n=t.length;i<n;i++)qh(t[i],s);e.fragmentHint&&qh(e.fragmentHint,s),e.alignedSliding=!0}function G_(s,e,t){e&&(K_(s,t,e),!t.alignedSliding&&e&&Ea(t,e),!t.alignedSliding&&e&&!t.skippedSegments&&gp(e,t))}function K_(s,e,t){if(j_(s,t,e)){const i=V_(t,e);i&&Ee(i.start)&&(W.log(`Adjusting PTS using last level due to CC increase within current level ${e.url}`),_p(i.start,e))}}function Ea(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=ea(i,o),r=ea(t,o)),(!n||!r)&&(n=i[Math.floor(i.length/2)],r=ea(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);_p(p,s)}const Wh=Math.pow(2,17);class q_{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 Di({type:ke.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(_=>_[0]==="GAP")){h(Yh(e));return}else e.gap=!1;const p=this.loader=e.loader=r?new r(n):new o(n),f=zh(e),m=Vh(n.fragLoadPolicy.default),T={loadPolicy:m,timeout:m.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Wh};e.stats=p.stats,p.load(f,T,{onSuccess:(_,b,w,L)=>{this.resetLoader(e,p);let A=_.data;w.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(A.slice(0,16)),A=A.slice(16)),u({frag:e,part:null,payload:A,networkDetails:L})},onError:(_,b,w,L)=>{this.resetLoader(e,p),h(new Di({type:ke.NETWORK_ERROR,details:te.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:gt({url:i,data:void 0},_),error:new Error(`HTTP Error ${_.code} ${_.text}`),networkDetails:w,stats:L}))},onAbort:(_,b,w)=>{this.resetLoader(e,p),h(new Di({type:ke.NETWORK_ERROR,details:te.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:w,stats:_}))},onTimeout:(_,b,w)=>{this.resetLoader(e,p),h(new Di({type:ke.NETWORK_ERROR,details:te.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${T.timeout}ms`),networkDetails:w,stats:_}))},onProgress:(_,b,w,L)=>{t&&t({frag:e,part:null,payload:w,networkDetails:L})}})})}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(Yh(e,t));return}const p=this.loader=e.loader=r?new r(n):new o(n),f=zh(e,t),m=Vh(n.fragLoadPolicy.default),T={loadPolicy:m,timeout:m.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Wh};t.stats=p.stats,p.load(f,T,{onSuccess:(_,b,w,L)=>{this.resetLoader(e,p),this.updateStatsFromPart(e,t);const A={frag:e,part:t,payload:_.data,networkDetails:L};i(A),u(A)},onError:(_,b,w,L)=>{this.resetLoader(e,p),h(new Di({type:ke.NETWORK_ERROR,details:te.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:gt({url:f.url,data:void 0},_),error:new Error(`HTTP Error ${_.code} ${_.text}`),networkDetails:w,stats:L}))},onAbort:(_,b,w)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,p),h(new Di({type:ke.NETWORK_ERROR,details:te.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:w,stats:_}))},onTimeout:(_,b,w)=>{this.resetLoader(e,p),h(new Di({type:ke.NETWORK_ERROR,details:te.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${T.timeout}ms`),networkDetails:w,stats:_}))}})})}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),m=(h-p)*Math.round(i.loaded/p);i.total=i.loaded+m}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 zh(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(Ee(n)&&Ee(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 Yh(s,e){const t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:ke.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 Di(i)}class Di extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class W_{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 z_{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 Y_(s){const e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?An(s,0,e-t):s}class X_{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],f=h[1],m=h[2],T=h[3],_=new Uint32Array(256);let b=0,w=0,L=0;for(L=0;L<256;L++)L<128?_[L]=L<<1:_[L]=L<<1^283;for(L=0;L<256;L++){let A=w^w<<1^w<<2^w<<3^w<<4;A=A>>>8^A&255^99,e[b]=A,t[A]=b;const P=_[b],O=_[P],M=_[O];let k=_[A]*257^A*16843008;n[b]=k<<24|k>>>8,r[b]=k<<16|k>>>16,o[b]=k<<8|k>>>24,u[b]=k,k=M*16843009^O*65537^P*257^b*16843008,p[A]=k<<24|k>>>8,f[A]=k<<16|k>>>16,m[A]=k<<8|k>>>24,T[A]=k,b?(b=P^_[_[_[M^P]]],w^=_[_[w]]):b=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),f=this.invKeySchedule=new Uint32Array(o),m=this.sBox,T=this.rcon,_=this.invSubMix,b=_[0],w=_[1],L=_[2],A=_[3];let P,O;for(u=0;u<o;u++){if(u<r){P=p[u]=t[u];continue}O=P,u%r===0?(O=O<<8|O>>>24,O=m[O>>>24]<<24|m[O>>>16&255]<<16|m[O>>>8&255]<<8|m[O&255],O^=T[u/r|0]<<24):r>6&&u%r===4&&(O=m[O>>>24]<<24|m[O>>>16&255]<<16|m[O>>>8&255]<<8|m[O&255]),p[u]=P=(p[u-r]^O)>>>0}for(h=0;h<o;h++)u=o-h,h&3?O=p[u]:O=p[u-4],h<4||u<=4?f[h]=O:f[h]=b[m[O>>>24]]^w[m[O>>>16&255]]^L[m[O>>>8&255]]^A[m[O&255]],f[h]=f[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],f=u[2],m=u[3],T=this.uint8ArrayToUint32Array_(i);let _=T[0],b=T[1],w=T[2],L=T[3];const A=new Int32Array(e),P=new Int32Array(A.length);let O,M,k,N,H,G,B,D,K,ae,Z,oe,le,he;const pe=this.networkToHostOrderSwap;for(;t<A.length;){for(K=pe(A[t]),ae=pe(A[t+1]),Z=pe(A[t+2]),oe=pe(A[t+3]),H=K^r[0],G=oe^r[1],B=Z^r[2],D=ae^r[3],le=4,he=1;he<n;he++)O=h[H>>>24]^p[G>>16&255]^f[B>>8&255]^m[D&255]^r[le],M=h[G>>>24]^p[B>>16&255]^f[D>>8&255]^m[H&255]^r[le+1],k=h[B>>>24]^p[D>>16&255]^f[H>>8&255]^m[G&255]^r[le+2],N=h[D>>>24]^p[H>>16&255]^f[G>>8&255]^m[B&255]^r[le+3],H=O,G=M,B=k,D=N,le=le+4;O=o[H>>>24]<<24^o[G>>16&255]<<16^o[B>>8&255]<<8^o[D&255]^r[le],M=o[G>>>24]<<24^o[B>>16&255]<<16^o[D>>8&255]<<8^o[H&255]^r[le+1],k=o[B>>>24]<<24^o[D>>16&255]<<16^o[H>>8&255]<<8^o[G&255]^r[le+2],N=o[D>>>24]<<24^o[H>>16&255]<<16^o[G>>8&255]<<8^o[B&255]^r[le+3],P[t]=pe(O^_),P[t+1]=pe(N^b),P[t+2]=pe(k^w),P[t+3]=pe(M^L),_=K,b=ae,w=Z,L=oe,t=t+4}return P.buffer}}const Q_=16;class ku{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?Y_(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=Kt(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 X_),h.expandKey(t);const p=r;return this.currentResult=h.decrypt(u.buffer,0,i),this.currentIV=An(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 z_(this.subtle,t)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new W_(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%Q_;return i!==e.length&&(t=An(e,0,i),this.remainderData=An(e,i)),t}logOnce(e){this.logEnabled&&(W.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const J_={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}},ce={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 Iu extends U_{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=ce.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 q_(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new ku(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=ce.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 Ze.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===ce.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=Ze.bufferInfo(n||i,o,e.maxBufferHole);if(this.log(`media seeking to ${Ee(o)?o.toFixed(3):o}, state: ${r}`),this.state===ce.ENDED)this.resetLoadingState();else if(t){const h=e.maxFragLookUpTolerance,p=t.start-h,f=t.start+t.duration+h;if(!u.len||f<u.start||p>u.end){const m=o>f;(o<p||m)&&(m&&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=ce.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===ce.FRAG_LOADING||!this.fragCurrent&&o===ce.PARSING)&&(this.fragmentTracker.removeFragment(e),this.state=ce.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===ce.STOPPED||this.state===ce.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===pt.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)===pt.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:ke.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===ce.STOPPED||this.state===ce.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=ce.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===Le.MAIN?"level":"track"} ${e.level} (frag:[${((i=e.startPTS)!=null?i:NaN).toFixed(3)}-${((n=e.endPTS)!=null?n:NaN).toFixed(3)}] > buffer:${u?J_.toString(Ze.getBuffered(u)):"(detached)"})`),e.sn!=="initSegment"){var h;if(e.type!==Le.SUBTITLE){const f=e.elementaryStreams;if(!Object.keys(f).some(m=>!!f[m])){this.state=ce.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=ce.IDLE,u&&(!this.loadedmetadata&&e.type==Le.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 Au(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=ce.KEY_LOADING,this.fragCurrent=e,u=this.keyLoader.load(e).then(f=>{if(!this.fragContextChanged(f.frag))return this.hls.trigger(I.KEY_LOADED,f),this.state===ce.KEY_LOADING&&(this.state=ce.IDLE),f}),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 f=o.partList;if(f&&n){i>e.end&&o.fragmentHint&&(e=o.fragmentHint);const m=this.getNextPart(f,e,i);if(m>-1){const T=f[m];this.log(`Loading part sn: ${e.sn} p: ${T.index} cc: ${e.cc} of playlist [${o.startSN}-${o.endSN}] parts [0-${m}-${f.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=T.start+T.duration,this.state=ce.FRAG_LOADING;let _;return u?_=u.then(b=>!b||this.fragContextChanged(b.frag)?null:this.doFragPartsLoad(e,T,t,n)).catch(b=>this.handleFragLoadError(b)):_=this.doFragPartsLoad(e,T,t,n).catch(b=>this.handleFragLoadError(b)),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")):_}else if(!e.url||this.loadedEndOfParts(f,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))}`),Ee(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=ce.FRAG_LOADING;const h=this.config.progressive;let p;return h&&u?p=u.then(f=>!f||this.fragContextChanged(f?.frag)?null:this.fragmentLoader.load(e,n)).catch(f=>this.handleFragLoadError(f)):p=Promise.all([this.fragmentLoader.load(e,h?n:void 0),u]).then(([f])=>(!h&&f&&n&&n(f),f)).catch(f=>this.handleFragLoadError(f)),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,f=m=>{this.fragmentLoader.loadPart(e,m,n).then(T=>{h[m.index]=T;const _=T.part;this.hls.trigger(I.FRAG_LOADED,T);const b=$h(i,e.sn,m.index+1)||mp(p,e.sn,m.index+1);if(b)f(b);else return r({frag:e,part:_,partsLoaded:h})}).catch(o)};f(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:ke.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!==ce.PARSING){!this.fragCurrent&&this.state!==ce.STOPPED&&this.state!==ce.ERROR&&(this.state=ce.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?$h(u,r,o):null,p=h?h.fragment:__(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!==ce.PARSING)return;const{data1:u,data2:h}=e;let p=u;if(u&&h&&(p=Kt(u,h)),!((o=p)!=null&&o.length))return;const f={type:e.type,frag:t,part:i,chunkMeta:n,parent:t.type,data:p};if(this.hls.trigger(I.BUFFER_APPENDING,f),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Ze.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,n=Ze.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 Ee(i)?this.getFwdBufferInfoAtPos(e,i,t):null}getFwdBufferInfoAtPos(e,t,i){const{config:{maxBufferHole:n}}=this,r=Ze.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 Ze.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=Le.MAIN){const i=this.fragmentTracker.getAppendedFrag(e,Le.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===pt.OK||i===pt.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 f=p.loaded;f?n=-1:(r||p.independent||o)&&p.fragment===t&&(n=u),r=f}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=b_(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=w_(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,f=i.partList,m=!!(n.lowLatencyMode&&f!=null&&f.length&&h);m&&h&&!this.bitrateTest&&(o=o.concat(h),u=h.sn);let T;if(e<t){const _=e>t-p?0:p;T=_a(r,o,e,_)}else T=o[o.length-1];if(T){const _=T.sn-i.startSN,b=this.fragmentTracker.getState(T);if((b===pt.OK||b===pt.PARTIAL&&T.gap)&&(r=T),r&&T.sn===r.sn&&(!m||f[0].fragment.sn>T.sn)&&r&&T.level===r.level){const L=o[_+1];T.sn<u&&this.fragmentTracker.getState(L)!==pt.OK?T=L: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&&Ee(r);if(o||!u&&!r){const{fragPrevious:h}=this;G_(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&&Ee(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!==ce.FRAG_LOADING_WAITING_RETRY)&&(this.state=ce.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const f=this.getCurrentContext(t.chunkMeta);f&&(t.frag=f.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===Tt.RetryRequest&&p){this.resetStartWhenNotLoaded(this.levelLastLoaded);const f=wu(p,h);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${h+1}/${p.maxNumRetry} in ${f}ms`),o.resolved=!0,this.retryDate=self.performance.now()+f,this.state=ce.FRAG_LOADING_WAITING_RETRY}else if(p&&o)if(this.resetFragmentErrors(e),h<p.maxNumRetry)!r&&u!==Tt.RemoveAlternatePermanently&&(o.resolved=!0);else{W.warn(`${t.details} reached or exceeded max retry (${h})`);return}else o?.action===Tt.SendAlternateToPenaltyBox?this.state=ce.WAITING_LEVEL:this.state=ce.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===ce.PARSING||this.state===ce.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===Le.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==ce.STOPPED&&(this.state=ce.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const n=Ze.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,i),this.state===ce.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=ce.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 f=e.elementaryStreams[p];if(f){const m=f.endPTS-f.startPTS;if(m<=0)return this.warn(`Could not parse fragment ${e.sn} ${p} duration reliably (${m})`),h||!1;const T=n?0:pp(o,e,f.startPTS,f.endPTS,f.startDTS,f.endDTS);return this.hls.trigger(I.LEVEL_PTS_UPDATED,{details:o,level:i,drift:T,type:p,frag:e,start:f.startPTS,end:f.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:ke.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=ce.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 Ep{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=Z_(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function Z_(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 eE(){return typeof __HLS_WORKER_BUNDLE__=="function"}function tE(){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 iE(s){const e=new self.URL(s,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}function pi(s="",e=9e4){return{type:s,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Ru{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=Kt(this.cachedData,e),this.cachedData=null);let i=Ns(e,0),n=i?i.length:0,r;const o=this._audioTrack,u=this._id3Track,h=i?Cu(i):void 0,p=e.length;for((this.basePTS===null||this.frameIndex===0&&Ee(h))&&(this.basePTS=nE(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:ti.audioId3,duration:Number.POSITIVE_INFINITY});n<p;){if(this.canParse(e,n)){const f=this.appendFrame(o,e,n);f?(this.frameIndex++,this.lastPTS=f.sample.pts,n+=f.length,r=n):n=p}else CT(e,n)?(i=Ns(e,n),u.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:ti.audioId3,duration:Number.POSITIVE_INFINITY}),n+=i.length,r=n):n++;if(n===p&&r!==p){const f=An(e,r);this.cachedData?this.cachedData=Kt(this.cachedData,f):this.cachedData=f}}return{audioTrack:o,videoTrack:pi(),id3Track:u,textTrack:pi()}}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:pi(),id3Track:this._id3Track,textTrack:pi()}}destroy(){}}const nE=(s,e,t)=>{if(Ee(s))return s*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};function sE(s,e,t,i){let n,r,o,u;const h=navigator.userAgent.toLowerCase(),p=i,f=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];n=((e[t+2]&192)>>>6)+1;const m=(e[t+2]&60)>>>2;if(m>f.length-1){const T=new Error(`invalid ADTS sampling index:${m}`);s.emit(I.ERROR,I.ERROR,{type:ke.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:${m}`),/firefox/i.test(h)?m>=6?(n=5,u=new Array(4),r=m-3):(n=2,u=new Array(2),r=m):h.indexOf("android")!==-1?(n=2,u=new Array(2),r=m):(n=5,u=new Array(4),i&&(i.indexOf("mp4a.40.29")!==-1||i.indexOf("mp4a.40.5")!==-1)||!i&&m>=6?r=m-3:((i&&i.indexOf("mp4a.40.2")!==-1&&(m>=6&&o===1||/vivaldi/i.test(h))||!i&&o===1)&&(n=2,u=new Array(2)),r=m)),u[0]=n<<3,u[0]|=(m&14)>>1,u[1]|=(m&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:f[m],channelCount:o,codec:"mp4a.40."+n,manifestCodec:p}}function bp(s,e){return s[e]===255&&(s[e+1]&246)===240}function Sp(s,e){return s[e+1]&1?7:9}function Pu(s,e){return(s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function rE(s,e){return e+5<s.length}function ba(s,e){return e+1<s.length&&bp(s,e)}function aE(s,e){return rE(s,e)&&bp(s,e)&&Pu(s,e)<=s.length-e}function oE(s,e){if(ba(s,e)){const t=Sp(s,e);if(e+t>=s.length)return!1;const i=Pu(s,e);if(i<=t)return!1;const n=e+i;return n===s.length||ba(s,n)}return!1}function Cp(s,e,t,i,n){if(!s.samplerate){const r=sE(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 wp(s){return 1024*9e4/s}function lE(s,e){const t=Sp(s,e);if(e+t<=s.length){const i=Pu(s,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function Lp(s,e,t,i,n){const r=wp(s.samplerate),o=i+n*r,u=lE(e,t);let h;if(u){const{frameLength:m,headerLength:T}=u,_=T+m,b=Math.max(0,t+_-e.length);b?(h=new Uint8Array(_-T),h.set(e.subarray(t+T,e.length),0)):h=e.subarray(t+T,t+_);const w={unit:h,pts:o};return b||s.samples.push(w),{sample:w,length:_,missing:b}}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 Mr=null;const uE=[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],cE=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],hE=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],dE=[0,1,1,4];function Ap(s,e,t,i,n){if(t+24>e.length)return;const r=kp(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 kp(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=uE[h*14+n-1]*1e3,m=cE[(t===3?0:t===2?1:2)*3+r],T=u===3?1:2,_=hE[t][i],b=dE[i],w=_*8*b,L=Math.floor(_*p/m+o)*b;if(Mr===null){const O=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Mr=O?parseInt(O[1]):0}return!!Mr&&Mr<=87&&i===2&&p>=224e3&&u===0&&(s[e+3]=s[e+3]|128),{sampleRate:m,channelCount:T,frameLength:L,samplesPerFrame:w}}}function Du(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function Ip(s,e){return e+1<s.length&&Du(s,e)}function fE(s,e){return Du(s,e)&&4<=s.length-e}function Rp(s,e){if(e+1<s.length&&Du(s,e)){const i=kp(s,e);let n=4;i!=null&&i.frameLength&&(n=i.frameLength);const r=e+n;return r===s.length||Ip(s,r)}return!1}class pE extends Ru{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=Ns(e,0);let i=t?.length||0;if(Rp(e,i))return!1;for(let n=e.length;i<n;i++)if(oE(e,i))return W.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return aE(e,t)}appendFrame(e,t,i){Cp(e,this.observer,t,i,e.manifestCodec);const n=Lp(e,t,i,this.basePTS,this.frameIndex);if(n&&n.missing===0)return n}}const gE=/\/emsg[-/]ID3/i;class mE{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=pi("video",1),o=this.audioTrack=pi("audio",1),u=this.txtTrack=pi("text",1);if(this.id3Track=pi("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const h=ap(e);if(h.video){const{id:p,timescale:f,codec:m}=h.video;r.id=p,r.timescale=u.timescale=f,r.codec=m}if(h.audio){const{id:p,timescale:f,codec:m}=h.audio;o.id=p,o.timescale=f,o.codec=m}u.id=np.text,r.sampleDuration=0,r.duration=o.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return xT(e)}demux(e,t){this.timeOffset=t;let i=e;const n=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Kt(this.remainderData,e));const u=$T(i);this.remainderData=u.remainder,n.samples=u.valid||new Uint8Array}else n.samples=i;const o=this.extractID3Track(n,t);return r.samples=bh(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=bh(e,t),{videoTrack:t,audioTrack:pi(),id3Track:n,textTrack:pi()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const n=De(e.samples,["emsg"]);n&&n.forEach(r=>{const o=GT(r);if(gE.test(o.schemeIdUri)){const u=Ee(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:ti.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 Pp=(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 yE extends Ru{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=Dp(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=Ns(e,0);if(!t)return!1;const i=t.length;return e[i]===11&&e[i+1]===119&&Cu(t)!==void 0&&Pp(e,i)<16}}function Dp(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,f=[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+f>e.length)return-1;const m=e[t+6]>>5;let T=0;m===2?T+=2:(m&1&&m!==1&&(T+=2),m&4&&(T+=2));const _=(e[t+6]<<8|e[t+7])>>12-T&1,w=[2,1,2,3,3,4,4,5][m]+_,L=e[t+5]>>3,A=e[t+5]&7,P=new Uint8Array([r<<6|L<<1|A>>2,(A&3)<<6|m<<3|_<<2|h>>4,h<<4&224]),O=1536/u*9e4,M=i+n*O,k=e.subarray(t,t+f);return s.config=P,s.channelCount=w,s.samplerate=u,s.samples.push({unit:k,pts:M}),f}class vE{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 Xh{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),f=this.readUEG.bind(this),m=this.readBoolean.bind(this),T=this.skipBits.bind(this),_=this.skipEG.bind(this),b=this.skipUEG.bind(this),w=this.skipScalingList.bind(this);h();const L=h();if(p(5),T(3),h(),b(),L===100||L===110||L===122||L===244||L===44||L===83||L===86||L===118||L===128){const N=f();if(N===3&&T(1),b(),b(),T(1),m())for(o=N!==3?8:12,u=0;u<o;u++)m()&&(u<6?w(16):w(64))}b();const A=f();if(A===0)f();else if(A===1)for(T(1),_(),_(),r=f(),u=0;u<r;u++)_();b(),T(1);const P=f(),O=f(),M=p(1);M===0&&T(1),T(1),m()&&(e=f(),t=f(),i=f(),n=f());let k=[1,1];if(m()&&m())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-M)*(O+1)*16-(M?2:4)*(i+n),pixelRatio:k}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class TE extends vE{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(f=>{var m;switch(f.type){case 1:{let w=!1;h=!0;const L=f.data;if(p&&L.length>4){const A=new Xh(L).readSliceType();(A===2||A===4||A===7||A===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,(m=u)!=null&&m.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,lp(f.data,1,i.pts,t.samples);break}case 7:{var _,b;h=!0,p=!0;const w=f.data,A=new Xh(w).readSPS();if(!e.sps||e.width!==A.width||e.height!==A.height||((_=e.pixelRatio)==null?void 0:_[0])!==A.pixelRatio[0]||((b=e.pixelRatio)==null?void 0:b[1])!==A.pixelRatio[1]){e.width=A.width,e.height=A.height,e.pixelRatio=A.pixelRatio,e.sps=[w],e.duration=r;const P=w.subarray(1,4);let O="avc1.";for(let M=0;M<3;M++){let k=P[M].toString(16);k.length<2&&(k="0"+k),O+=k}e.codec=O}break}case 8:h=!0,e.pps=[f.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 "+f.type+" ");break}u&&h&&u.units.push(f)}),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,f,m=-1,T=0;for(n===-1&&(m=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,m>=0){const _={data:t.subarray(m,p),type:T};o.push(_)}else{const _=this.getLastNalUnit(e.samples);_&&(r&&u<=4-r&&_.state&&(_.data=_.data.subarray(0,_.data.byteLength-r)),p>0&&(_.data=Kt(_.data,t.subarray(0,p)),_.state=0))}u<i?(f=t[u]&31,m=u,T=f,n=0):n=-1}else n=0}if(m>=0&&n>=0){const _={data:t.subarray(m,i),type:T,state:n};o.push(_)}if(o.length===0){const _=this.getLastNalUnit(e.samples);_&&(_.data=Kt(_.data,t))}return e.naluState=n,o}}class _E{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new ku(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=up(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 ft=188;class Ji{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 TE}static probe(e){const t=Ji.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(ft*5,t-ft)+1,n=0;for(;n<i;){let r=!1,o=-1,u=0;for(let h=n;h<t;h+=ft)if(e[h]===71&&(t-h===ft||e[h+ft]===71)){if(u++,o===-1&&(o=h,o!==0&&(i=Math.min(o+ft*99,e.length-ft)+1)),r||(r=Yl(e,h)===0),r&&u>1&&(o===0&&u>2||h+ft>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:np[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=Ji.createTrack("video"),this._audioTrack=Ji.createTrack("audio",n),this._id3Track=Ji.createTrack("id3"),this._txtTrack=Ji.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 f=o.pid,m=o.pesData,T=u.pid,_=h.pid,b=u.pesData,w=h.pesData,L=null,A=this.pmtParsed,P=this._pmtId,O=e.length;if(this.remainderData&&(e=Kt(this.remainderData,e),O=e.length,this.remainderData=null),O<ft&&!n)return this.remainderData=e,{audioTrack:u,videoTrack:o,id3Track:h,textTrack:p};const M=Math.max(0,Ji.syncOffset(e));O-=(O-M)%ft,O<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,O,e.buffer.byteLength-O));let k=0;for(let H=M;H<O;H+=ft)if(e[H]===71){const G=!!(e[H+1]&64),B=Yl(e,H),D=(e[H+3]&48)>>4;let K;if(D>1){if(K=H+5+e[H+4],K===H+ft)continue}else K=H+4;switch(B){case f:G&&(m&&(r=Qn(m))&&this.videoParser.parseAVCPES(o,p,r,!1,this._duration),m={data:[],size:0}),m&&(m.data.push(e.subarray(K,H+ft)),m.size+=H+ft-K);break;case T:if(G){if(b&&(r=Qn(b)))switch(u.segmentCodec){case"aac":this.parseAACPES(u,r);break;case"mp3":this.parseMPEGPES(u,r);break;case"ac3":this.parseAC3PES(u,r);break}b={data:[],size:0}}b&&(b.data.push(e.subarray(K,H+ft)),b.size+=H+ft-K);break;case _:G&&(w&&(r=Qn(w))&&this.parseID3PES(h,r),w={data:[],size:0}),w&&(w.data.push(e.subarray(K,H+ft)),w.size+=H+ft-K);break;case 0:G&&(K+=e[K]+1),P=this._pmtId=EE(e,K);break;case P:{G&&(K+=e[K]+1);const ae=bE(e,K,this.typeSupported,i,this.observer);f=ae.videoPid,f>0&&(o.pid=f,o.segmentCodec=ae.segmentVideoCodec),T=ae.audioPid,T>0&&(u.pid=T,u.segmentCodec=ae.segmentAudioCodec),_=ae.id3Pid,_>0&&(h.pid=_),L!==null&&!A&&(W.warn(`MPEG-TS PMT found at ${H} after unknown PID '${L}'. Backtracking to sync byte @${M} to parse all TS packets.`),L=null,H=M-188),A=this.pmtParsed=!0;break}case 17:case 8191:break;default:L=B;break}}else k++;k>0&&Sa(this.observer,new Error(`Found ${k} TS packet/s that do not start with 0x47`)),o.pesData=m,u.pesData=b,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=Qn(o))?(this.videoParser.parseAVCPES(i,r,p,!0,this._duration),i.pesData=null):i.pesData=o,u&&(p=Qn(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=Qn(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 _E(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 m=n.missing,T=n.sample.unit.byteLength;if(m===-1)r=Kt(n.sample.unit,r);else{const _=T-m;n.sample.unit.set(r.subarray(0,m),_),e.samples.push(n.sample),i=n.missing}}let o,u;for(o=i,u=r.length;o<u-1&&!ba(r,o);o++);if(o!==i){let m;const T=o<u-1;if(T?m=`AAC PES did not start with ADTS header,offset:${o}`:m="No ADTS header found in AAC PES",Sa(this.observer,new Error(m),T),!T)return}Cp(e,this.observer,r,o,this.audioCodec);let h;if(t.pts!==void 0)h=t.pts;else if(n){const m=wp(e.samplerate);h=n.sample.pts+m}else{W.warn("[tsdemuxer]: AAC PES unknown PTS");return}let p=0,f;for(;o<u;)if(f=Lp(e,r,o,h,p),o+=f.length,f.missing){this.aacOverFlow=f;break}else for(p++;o<u-1&&!ba(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(Ip(i,o)){const h=Ap(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=Dp(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=ct({},t,{type:this._videoTrack?ti.emsg:ti.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Yl(s,e){return((s[e+1]&31)<<8)+s[e+2]}function EE(s,e){return(s[e+10]&31)<<8|s[e+11]}function bE(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=Yl(s,e),f=(s[e+3]&15)<<8|s[e+4];switch(s[e]){case 207:if(!i){rl("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){rl("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){rl("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&&f>0){let m=e+5,T=f;for(;T>2;){switch(s[m]){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 b=s[m+1]+2;m+=b,T-=b}}break;case 194:case 135:return Sa(n,new Error("Unsupported EC-3 in M2TS found")),r;case 36:return Sa(n,new Error("Unsupported HEVC in M2TS found")),r}e+=f+5}return r}function Sa(s,e,t){W.warn(`parsing error: ${e.message}`),s.emit(I.ERROR,I.ERROR,{type:ke.MEDIA_ERROR,details:te.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function rl(s){W.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function Qn(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]=Kt(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 f=n+9;if(s.size<=f)return null;s.size-=f;const m=new Uint8Array(s.size);for(let T=0,_=u.length;T<_;T++){t=u[T];let b=t.byteLength;if(f)if(f>b){f-=b;continue}else t=t.subarray(f),b-=f,f=0;m.set(t,e),e+=b}return i&&(i-=n+3),{data:m,pts:r,dts:o,len:i}}return null}class SE extends Ru{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=Ns(e,0);let i=t?.length||0;if(t&&e[i]===11&&e[i+1]===119&&Cu(t)!==void 0&&Pp(e,i)<=16)return!1;for(let n=e.length;i<n;i++)if(Rp(e,i))return W.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return fE(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return Ap(e,t,i,this.basePTS,this.frameIndex)}}class Qh{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 zi=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/(zi+1)),n=Math.floor(t%(zi+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/(zi+1)),n=Math.floor(t%(zi+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,f=e.pixelRatio[0],m=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([f>>24,f>>16&255,f>>8&255,f&255,m>>24,m>>16&255,m>>8&255,m&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/(zi+1)),u=Math.floor(i%(zi+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/(zi+1)),o=Math.floor(t%(zi+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,f,m,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,f=h.size,m=h.flags,T=h.cts,o.set([p>>>24&255,p>>>16&255,p>>>8&255,p&255,f>>>24&255,f>>>16&255,f>>>8&255,f&255,m.isLeading<<2|m.dependsOn,m.isDependedOn<<6|m.hasRedundancy<<4|m.paddingValue<<1|m.isNonSync,m.degradPrio&61440,m.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 Kt(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 xp=9e4;function xu(s,e,t=1,i=!1){const n=s*e*t;return i?Math.round(n):n}function CE(s,e,t=1,i=!1){return xu(s,e,1/t,i)}function Is(s,e=!1){return xu(s,1e3,1/xp,e)}function wE(s,e=1){return xu(s,xp,1/e)}const LE=10*1e3,Jh=1024,AE=1152,kE=1536;let Jn=null,al=null;class ta{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,Jn===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Jn=o?parseInt(o[1]):0}if(al===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);al=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=Gt(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,f,m,T,_,b,w=r,L=r;const A=e.pid>-1,P=t.pid>-1,O=t.samples.length,M=e.samples.length>0,k=u&&O>0||O>1;if((!A||M)&&(!P||k)||this.ISGenerated||u){if(this.ISGenerated){var H,G,B,D;const oe=this.videoTrackConfig;oe&&(t.width!==oe.width||t.height!==oe.height||((H=t.pixelRatio)==null?void 0:H[0])!==((G=oe.pixelRatio)==null?void 0:G[0])||((B=t.pixelRatio)==null?void 0:B[1])!==((D=oe.pixelRatio)==null?void 0:D[1]))&&this.resetInitSegment()}else m=this.generateIS(e,t,r,o);const K=this.isVideoContiguous;let ae=-1,Z;if(k&&(ae=IE(t.samples),!K&&this.config.forceKeyFrameOnDiscontinuity))if(b=!0,ae>0){W.warn(`[mp4-remuxer]: Dropped ${ae} out of ${O} video samples due to a missing keyframe`);const oe=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(ae),t.dropped+=ae,L+=(t.samples[0].pts-oe)/t.inputTimeScale,Z=L}else ae===-1&&(W.warn(`[mp4-remuxer]: No keyframe found out of ${O} video samples`),b=!1);if(this.ISGenerated){if(M&&k){const oe=this.getVideoStartPts(t.samples),he=(Gt(e.samples[0].pts,oe)-oe)/t.inputTimeScale;w+=Math.max(0,he),L+=Math.max(0,-he)}if(M){if(e.samplerate||(W.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),m=this.generateIS(e,t,r,o)),f=this.remuxAudio(e,w,this.isAudioContiguous,o,P||k||h===Le.AUDIO?L:void 0),k){const oe=f?f.endPTS-f.startPTS:0;t.inputTimeScale||(W.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),m=this.generateIS(e,t,r,o)),p=this.remuxVideo(t,L,K,oe)}}else k&&(p=this.remuxVideo(t,L,K,0));p&&(p.firstKeyFrame=ae,p.independent=ae!==-1,p.firstKeyFramePTS=Z)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(_=Mp(i,r,this._initPTS,this._initDTS)),n.samples.length&&(T=Op(n,r,this._initPTS))),{audio:f,video:p,initSegment:m,independent:b,text:T,id3:_}}generateIS(e,t,i,n){const r=e.samples,o=t.samples,u=this.typeSupported,h={},p=this._initPTS;let f=!p||n,m="audio/mp4",T,_,b;if(f&&(T=_=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":u.mpeg?(m="audio/mpeg",e.codec=""):u.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}h.audio={id:"audio",container:m,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&u.mpeg?new Uint8Array(0):Y.initSegment([e]),metadata:{channelCount:e.channelCount}},f&&(b=e.inputTimeScale,!p||b!==p.timescale?T=_=r[0].pts-Math.round(b*i):f=!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}},f)if(b=t.inputTimeScale,!p||b!==p.timescale){const w=this.getVideoStartPts(o),L=Math.round(b*i);_=Math.min(_,Gt(o[0].dts,w)-L),T=Math.min(T,w-L)}else f=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(h).length)return this.ISGenerated=!0,f?(this._initPTS={baseTime:T,timescale:b},this._initDTS={baseTime:_,timescale:b}):T=b=void 0,{tracks:h,initPTS:T,timescale:b}}remuxVideo(e,t,i,n){const r=e.inputTimeScale,o=e.samples,u=[],h=o.length,p=this._initPTS;let f=this.nextAvcDts,m=8,T=this.videoSampleDuration,_,b,w=Number.POSITIVE_INFINITY,L=Number.NEGATIVE_INFINITY,A=!1;if(!i||f===null){const ee=t*r,Q=o[0].pts-Gt(o[0].dts,o[0].pts);Jn&&f!==null&&Math.abs(ee-Q-f)<15e3?i=!0:f=ee-Q}const P=p.baseTime*r/p.timescale;for(let ee=0;ee<h;ee++){const Q=o[ee];Q.pts=Gt(Q.pts-P,f),Q.dts=Gt(Q.dts-P,f),Q.dts<o[ee>0?ee-1:ee].dts&&(A=!0)}A&&o.sort(function(ee,Q){const ye=ee.dts-Q.dts,re=ee.pts-Q.pts;return ye||re}),_=o[0].dts,b=o[o.length-1].dts;const O=b-_,M=O?Math.round(O/(h-1)):T||e.inputTimeScale/30;if(i){const ee=_-f,Q=ee>M,ye=ee<-1;if((Q||ye)&&(Q?W.warn(`AVC: ${Is(ee,!0)} ms (${ee}dts) hole between fragments detected at ${t.toFixed(3)}`):W.warn(`AVC: ${Is(-ee,!0)} ms (${ee}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!ye||f>=o[0].pts||Jn)){_=f;const re=o[0].pts-ee;if(Q)o[0].dts=_,o[0].pts=re;else for(let ie=0;ie<o.length&&!(o[ie].dts>re);ie++)o[ie].dts-=ee,o[ie].pts-=ee;W.log(`Video: Initial PTS/DTS adjusted: ${Is(re,!0)}/${Is(_,!0)}, delta: ${Is(ee,!0)} ms`)}}_=Math.max(0,_);let k=0,N=0,H=_;for(let ee=0;ee<h;ee++){const Q=o[ee],ye=Q.units,re=ye.length;let ie=0;for(let be=0;be<re;be++)ie+=ye[be].data.length;N+=ie,k+=re,Q.length=ie,Q.dts<H?(Q.dts=H,H+=M/4|0||1):H=Q.dts,w=Math.min(Q.pts,w),L=Math.max(Q.pts,L)}b=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:ke.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,ae=Number.POSITIVE_INFINITY,Z=Number.POSITIVE_INFINITY,oe=Number.NEGATIVE_INFINITY,le=Number.NEGATIVE_INFINITY;for(let ee=0;ee<h;ee++){const Q=o[ee],ye=Q.units;let re=0;for(let Te=0,xe=ye.length;Te<xe;Te++){const Me=ye[Te],Pe=Me.data,je=Me.data.byteLength;D.setUint32(m,je),m+=4,B.set(Pe,m),m+=je,re+=4+je}let ie;if(ee<h-1)T=o[ee+1].dts-Q.dts,ie=o[ee+1].pts-Q.pts;else{const Te=this.config,xe=ee>0?Q.dts-o[ee-1].dts:M;if(ie=ee>0?Q.pts-o[ee-1].pts:M,Te.stretchShortVideoTrack&&this.nextAudioPts!==null){const Me=Math.floor(Te.maxBufferHole*r),Pe=(n?w+n*r:this.nextAudioPts)-Q.pts;Pe>Me?(T=Pe-xe,T<0?T=xe:K=!0,W.log(`[mp4-remuxer]: It is approximately ${Pe/90} ms to the next segment; using duration ${T/90} ms for the last video frame.`)):T=xe}else T=xe}const be=Math.round(Q.pts-Q.dts);ae=Math.min(ae,T),oe=Math.max(oe,T),Z=Math.min(Z,ie),le=Math.max(le,ie),u.push(new Zh(Q.key,T,re,be))}if(u.length){if(Jn){if(Jn<70){const ee=u[0].flags;ee.dependsOn=2,ee.isNonSync=0}}else if(al&&le-Z<oe-ae&&M/oe<.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=_;for(let Q=0,ye=u.length;Q<ye;Q++){const re=ee+u[Q].duration,ie=ee+u[Q].cts;if(Q<ye-1){const be=re+u[Q+1].cts;u[Q].duration=be-ie}else u[Q].duration=Q?u[Q-1].duration:M;u[Q].cts=0,ee=re}}}T=K||!T?M:T,this.nextAvcDts=f=b+T,this.videoSampleDuration=T,this.isVideoContiguous=!0;const ge={data1:Y.moof(e.sequenceNumber++,_,ct({},e,{samples:u})),data2:B,startPTS:w/r,endPTS:(L+T)/r,startDTS:_/r,endDTS:f/r,type:"video",hasAudio:!1,hasVideo:!0,nb:u.length,dropped:e.dropped};return e.samples=[],e.dropped=0,ge}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return AE;case"ac3":return kE;default:return Jh}}remuxAudio(e,t,i,n,r){const o=e.inputTimeScale,u=e.samplerate?e.samplerate:o,h=o/u,p=this.getSamplesPerFrame(e),f=p*h,m=this._initPTS,T=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,_=[],b=r!==void 0;let w=e.samples,L=T?0:8,A=this.nextAudioPts||-1;const P=t*o,O=m.baseTime*o/m.timescale;if(this.isAudioContiguous=i=i||w.length&&A>0&&(n&&Math.abs(P-A)<9e3||Math.abs(Gt(w[0].pts-O,P)-A)<20*f),w.forEach(function(he){he.pts=Gt(he.pts-O,P)}),!i||A<0){if(w=w.filter(he=>he.pts>=0),!w.length)return;r===0?A=0:n&&!b?A=Math.max(0,P):A=w[0].pts}if(e.segmentCodec==="aac"){const he=this.config.maxAudioFramesDrift;for(let pe=0,ge=A;pe<w.length;pe++){const ee=w[pe],Q=ee.pts,ye=Q-ge,re=Math.abs(1e3*ye/o);if(ye<=-he*f&&b)pe===0&&(W.warn(`Audio frame @ ${(Q/o).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*ye/o)} ms.`),this.nextAudioPts=A=ge=Q);else if(ye>=he*f&&re<LE&&b){let ie=Math.round(ye/f);ge=Q-ie*f,ge<0&&(ie--,ge+=f),pe===0&&(this.nextAudioPts=A=ge),W.warn(`[mp4-remuxer]: Injecting ${ie} audio frame @ ${(ge/o).toFixed(3)}s due to ${Math.round(1e3*ye/o)} ms gap.`);for(let be=0;be<ie;be++){const Te=Math.max(ge,0);let xe=Qh.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);xe||(W.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),xe=ee.unit.subarray()),w.splice(pe,0,{unit:xe,pts:Te}),ge+=f,pe++}}ee.pts=ge,ge+=f}}let M=null,k=null,N,H=0,G=w.length;for(;G--;)H+=w[G].unit.byteLength;for(let he=0,pe=w.length;he<pe;he++){const ge=w[he],ee=ge.unit;let Q=ge.pts;if(k!==null){const re=_[he-1];re.duration=Math.round((Q-k)/h)}else if(i&&e.segmentCodec==="aac"&&(Q=A),M=Q,H>0){H+=L;try{N=new Uint8Array(H)}catch(re){this.observer.emit(I.ERROR,I.ERROR,{type:ke.MUX_ERROR,details:te.REMUX_ALLOC_ERROR,fatal:!1,error:re,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,L);const ye=ee.byteLength;L+=ye,_.push(new Zh(!0,p,ye,0)),k=Q}const B=_.length;if(!B)return;const D=_[_.length-1];this.nextAudioPts=A=k+h*D.duration;const K=T?new Uint8Array(0):Y.moof(e.sequenceNumber++,M/h,ct({},e,{samples:_}));e.samples=[];const ae=M/o,Z=A/o,le={data1:K,data2:N,startPTS:ae,endPTS:Z,startDTS:ae,endDTS:Z,type:"audio",hasAudio:!0,hasVideo:!1,nb:B};return this.isAudioContiguous=!0,le}remuxEmptyAudio(e,t,i,n){const r=e.inputTimeScale,o=e.samplerate?e.samplerate:r,u=r/o,h=this.nextAudioPts,p=this._initDTS,f=p.baseTime*9e4/p.timescale,m=(h!==null?h:n.startDTS*r)+f,T=n.endDTS*r+f,_=u*Jh,b=Math.ceil((T-m)/_),w=Qh.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 L=[];for(let A=0;A<b;A++){const P=m+A*_;L.push({unit:w,pts:P,dts:P})}return e.samples=L,this.remuxAudio(e,t,i,!1)}}function Gt(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 IE(s){for(let e=0;e<s.length;e++)if(s[e].key)return e;return-1}function Mp(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=Gt(h.pts-t.baseTime*r/t.timescale,e*r)/r,h.dts=Gt(h.dts-i.baseTime*r/i.timescale,e*r)/r}const o=s.samples;return s.samples=[],{samples:o}}function Op(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=Gt(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 Zh{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 RE{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(FT(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=ap(e);n.audio&&(t=ed(n.audio,qe.AUDIO)),n.video&&(i=ed(n.video,qe.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:f}=this;const m={audio:void 0,video:void 0,text:n,id3:i,initSegment:void 0};Ee(f)||(f=this.lastEndTime=r||0);const T=t.samples;if(!(T!=null&&T.length))return m;const _={initPTS:void 0,timescale:1};let b=this.initData;if((u=b)!=null&&u.length||(this.generateInitSegment(T),b=this.initData),!((h=b)!=null&&h.length))return W.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),m;this.emitInitSegment&&(_.tracks=this.initTracks,this.emitInitSegment=!1);const w=BT(T,b),L=NT(b,T),A=L===null?r:L;(PE(p,A,r,w)||_.timescale!==p.timescale&&o)&&(_.initPTS=A-r,p&&p.timescale===1&&W.warn(`Adjusting initPTS by ${_.initPTS-p.baseTime}`),this.initPTS=p={baseTime:_.initPTS,timescale:1});const P=e?A-p.baseTime/p.timescale:f,O=P+w;HT(b,T,p.baseTime/p.timescale),w>0?this.lastEndTime=O:(W.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const M=!!b.audio,k=!!b.video;let N="";M&&(N+="audio"),k&&(N+="video");const H={data1:T,startPTS:P,startDTS:P,endPTS:O,endDTS:O,type:N,hasAudio:M,hasVideo:k,nb:1,dropped:0};return m.audio=H.type==="audio"?H:void 0,m.video=H.type!=="audio"?H:void 0,m.initSegment=_,m.id3=Mp(i,r,p,p),n.samples.length&&(m.text=Op(n,r,p)),m}}function PE(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 ed(s,e){const t=s?.codec;if(t&&t.length>4)return t;if(e===qe.AUDIO){if(t==="ec-3"||t==="ac-3"||t==="alac")return t;if(t==="fLaC"||t==="Opus")return ma(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 xi;try{xi=self.performance.now.bind(self.performance)}catch{W.debug("Unable to use Performance API on this environment"),xi=ls?.Date.now}const ia=[{demux:mE,remux:RE},{demux:Ji,remux:ta},{demux:pE,remux:ta},{demux:SE,remux:ta}];ia.splice(2,0,{demux:yE,remux:ta});class td{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=xi();let o=new Uint8Array(e);const{currentTransmuxState:u,transmuxConfig:h}=this;n&&(this.currentTransmuxState=n);const{contiguous:p,discontinuity:f,trackSwitch:m,accurateTimeOffset:T,timeOffset:_,initSegmentChange:b}=n||u,{audioCodec:w,videoCodec:L,defaultInitPts:A,duration:P,initSegmentData:O}=h,M=DE(o,t);if(M&&M.method==="AES-128"){const G=this.getDecrypter();if(G.isSync()){let B=G.softwareDecrypt(o,M.key.buffer,M.iv.buffer);if(i.part>-1&&(B=G.flush()),!B)return r.executeEnd=xi(),ol(i);o=new Uint8Array(B)}else return this.decryptionPromise=G.webCryptoDecrypt(o,M.key.buffer,M.iv.buffer).then(B=>{const D=this.push(B,null,i);return this.decryptionPromise=null,D}),this.decryptionPromise}const k=this.needsProbing(f,m);if(k){const G=this.configureTransmuxer(o);if(G)return W.warn(`[transmuxer] ${G.message}`),this.observer.emit(I.ERROR,I.ERROR,{type:ke.MEDIA_ERROR,details:te.FRAG_PARSING_ERROR,fatal:!1,error:G,reason:G.message}),r.executeEnd=xi(),ol(i)}(f||m||b||k)&&this.resetInitSegment(O,w,L,P,t),(f||b||k)&&this.resetInitialTimestamp(A),p||this.resetContiguity();const N=this.transmux(o,M,_,T,i),H=this.currentTransmuxState;return H.contiguous=!0,H.discontinuity=!1,H.trackSwitch=!1,r.executeEnd=xi(),N}flush(e){const t=e.transmuxing;t.executeStart=xi();const{decrypter:i,currentTransmuxState:n,decryptionPromise:r}=this;if(r)return r.then(()=>this.flush(e));const o=[],{timeOffset:u}=n;if(i){const m=i.flush();m&&o.push(this.push(m,null,e))}const{demuxer:h,remuxer:p}=this;if(!h||!p)return t.executeEnd=xi(),[ol(e)];const f=h.flush(u);return na(f)?f.then(m=>(this.flushRemux(o,m,e),o)):(this.flushRemux(o,f,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 f=this.remuxer.remux(n,r,o,u,p,h,!0,this.id);e.push({remuxResult:f,chunkMeta:i}),i.transmuxing.executeEnd=xi()}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,_=ia.length;T<_;T++){var u;if((u=ia[T].demux)!=null&&u.probe(e)){o=ia[T];break}}if(!o)return new Error("Failed to find demuxer by probing fragment data");const h=this.demuxer,p=this.remuxer,f=o.remux,m=o.demux;(!p||!(p instanceof f))&&(this.remuxer=new f(i,t,n,r)),(!h||!(h instanceof m))&&(this.demuxer=new m(i,t,n),this.probe=m.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new ku(this.config)),e}}function DE(s,e){let t=null;return s.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const ol=s=>({remuxResult:{},chunkMeta:s});function na(s){return"then"in s&&s.then instanceof Function}class xE{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 ME{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 Fp={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,f){this.fn=h,this.context=p,this.once=f||!1}function r(h,p,f,m,T){if(typeof f!="function")throw new TypeError("The listener must be a function");var _=new n(f,m||h,T),b=t?t+p:p;return h._events[b]?h._events[b].fn?h._events[b]=[h._events[b],_]:h._events[b].push(_):(h._events[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=[],f,m;if(this._eventsCount===0)return p;for(m in f=this._events)e.call(f,m)&&p.push(t?m.slice(1):m);return Object.getOwnPropertySymbols?p.concat(Object.getOwnPropertySymbols(f)):p},u.prototype.listeners=function(p){var f=t?t+p:p,m=this._events[f];if(!m)return[];if(m.fn)return[m.fn];for(var T=0,_=m.length,b=new Array(_);T<_;T++)b[T]=m[T].fn;return b},u.prototype.listenerCount=function(p){var f=t?t+p:p,m=this._events[f];return m?m.fn?1:m.length:0},u.prototype.emit=function(p,f,m,T,_,b){var w=t?t+p:p;if(!this._events[w])return!1;var L=this._events[w],A=arguments.length,P,O;if(L.fn){switch(L.once&&this.removeListener(p,L.fn,void 0,!0),A){case 1:return L.fn.call(L.context),!0;case 2:return L.fn.call(L.context,f),!0;case 3:return L.fn.call(L.context,f,m),!0;case 4:return L.fn.call(L.context,f,m,T),!0;case 5:return L.fn.call(L.context,f,m,T,_),!0;case 6:return L.fn.call(L.context,f,m,T,_,b),!0}for(O=1,P=new Array(A-1);O<A;O++)P[O-1]=arguments[O];L.fn.apply(L.context,P)}else{var M=L.length,k;for(O=0;O<M;O++)switch(L[O].once&&this.removeListener(p,L[O].fn,void 0,!0),A){case 1:L[O].fn.call(L[O].context);break;case 2:L[O].fn.call(L[O].context,f);break;case 3:L[O].fn.call(L[O].context,f,m);break;case 4:L[O].fn.call(L[O].context,f,m,T);break;default:if(!P)for(k=1,P=new Array(A-1);k<A;k++)P[k-1]=arguments[k];L[O].fn.apply(L[O].context,P)}}return!0},u.prototype.on=function(p,f,m){return r(this,p,f,m,!1)},u.prototype.once=function(p,f,m){return r(this,p,f,m,!0)},u.prototype.removeListener=function(p,f,m,T){var _=t?t+p:p;if(!this._events[_])return this;if(!f)return o(this,_),this;var b=this._events[_];if(b.fn)b.fn===f&&(!T||b.once)&&(!m||b.context===m)&&o(this,_);else{for(var w=0,L=[],A=b.length;w<A;w++)(b[w].fn!==f||T&&!b[w].once||m&&b[w].context!==m)&&L.push(b[w]);L.length?this._events[_]=L.length===1?L[0]:L:o(this,_)}return this},u.prototype.removeAllListeners=function(p){var f;return p?(f=t?t+p:p,this._events[f]&&o(this,f)):(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})(Fp);var OE=Fp.exports,Mu=sT(OE);class Np{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,f)=>{f=f||{},f.frag=this.frag,f.id=this.id,p===I.ERROR&&(this.error=f.error),this.hls.trigger(p,f)};this.observer=new Mu,this.observer.on(I.FRAG_DECRYPTED,o),this.observer.on(I.ERROR,o);const u=In(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||eE())){try{r.workerPath?(W.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=iE(r.workerPath)):(W.log(`injecting Web Worker for "${t}"`),this.workerContext=tE()),this.onwmsg=m=>this.onWorkerMessage(m);const{worker:f}=this.workerContext;f.addEventListener("message",this.onwmsg),f.onerror=m=>{const T=new Error(`${m.message}  (${m.filename}:${m.lineno})`);r.enableWorker=!1,W.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(I.ERROR,{type:ke.OTHER_ERROR,details:te.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:T})},f.postMessage({cmd:"init",typeSupported:h,vendor:"",id:t,config:JSON.stringify(r)})}catch(f){W.warn(`Error setting up "${t}" Web Worker, fallback to inline`,f),this.resetWorker(),this.error=null,this.transmuxer=new td(this.observer,h,r,"",t)}return}this.transmuxer=new td(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,f){var m,T;p.transmuxing.start=self.performance.now();const{transmuxer:_}=this,b=o?o.start:r.start,w=r.decryptdata,L=this.frag,A=!(L&&r.cc===L.cc),P=!(L&&p.level===L.level),O=L?p.sn-L.sn:-1,M=this.part?p.part-this.part.index:-1,k=O===0&&p.id>1&&p.id===L?.stats.chunkCount,N=!P&&(O===1||O===0&&(M===1||k&&M<=0)),H=self.performance.now();(P||O||r.stats.parsing.start===0)&&(r.stats.parsing.start=H),o&&(M||!N)&&(o.stats.parsing.start=H);const G=!(L&&((m=r.initSegment)==null?void 0:m.url)===((T=L.initSegment)==null?void 0:T.url)),B=new ME(A,N,h,P,b,G);if(!N||A||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: ${A}
        trackSwitch: ${P}
        contiguous: ${N}
        accurateTimeOffset: ${h}
        timeOffset: ${b}
        initSegmentChange: ${G}`);const D=new xE(i,n,t,u,f);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(_){const D=_.push(e,w,p,B);na(D)?(_.async=!0,D.then(K=>{this.handleTransmuxComplete(K)}).catch(K=>{this.transmuxerError(K,p,"transmuxer-interface push error")})):(_.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);na(i)||t.async?(na(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:ke.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 id=100;class FE extends Iu{constructor(e,t,i){super(e,t,i,"[audio-stream-controller]",Le.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===ce.WAITING_INIT_PTS&&this.tick()}}startLoad(e){if(!this.levels){this.startPosition=e,this.state=ce.STOPPED;return}const t=this.lastCurrentTime;this.stopLoad(),this.setInterval(id),t>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=ce.IDLE):(this.loadedmetadata=!1,this.state=ce.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case ce.IDLE:this.doTickIdle();break;case ce.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=ce.WAITING_INIT_PTS}break}case ce.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=ce.IDLE}break}case ce.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=ce.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=Ze.bufferInfo(this.mediaBuffer,h,this.config.maxBufferHole);zl(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=ce.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=ce.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=ce.WAITING_TRACK;return}const h=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&h&&(this.bufferFlushed=!1,this.afterBufferFlushed(h,qe.AUDIO,Le.AUDIO));const p=this.getFwdBufferInfo(h,Le.AUDIO);if(p===null)return;if(!this.switchingTrack&&this._streamEnded(p,u)){e.trigger(I.BUFFER_EOS,{type:"audio"}),this.state=ce.ENDED;return}const f=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Le.MAIN),m=p.len,T=this.getMaxBufferLength(f?.len),_=u.fragments,b=_[0].start,w=this.getLoadPosition(),L=this.flushing?w:p.end;if(this.switchingTrack&&i){const M=w;u.PTSKnown&&M<b&&(p.end>b||p.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=b+.05)}if(m>=T&&!this.switchingTrack&&L<_[_.length-1].start)return;let A=this.getNextFragment(L,u),P=!1;if(A&&this.isLoopLoading(A,L)&&(P=!!A.gap,A=this.getNextFragmentLoopLoading(A,u,p,Le.MAIN,T)),!A){this.bufferFlushed=!0;return}const O=f&&A.start>f.end+u.targetduration;if(O||!(f!=null&&f.len)&&p.len){const M=this.getAppendedFrag(A.start,Le.MAIN);if(M===null||(P||(P=!!M.gap||!!O&&f.len===0),O&&!P||P&&p.nextStart&&p.nextStart<M.end))return}this.loadFragment(A,o,L)}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 us(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(id):this.resetTransmuxer(),i?(this.switchingTrack=t,this.state=ce.IDLE,this.flushAudioIfNeeded(t)):(this.switchingTrack=null,this.bufferedTrack=t,this.state=ce.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 f=this.mainDetails;if(r.deltaUpdateFailed||!f)return;if(!u.details&&r.hasProgramDateTime&&f.hasProgramDateTime)Ea(r,f),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===ce.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=ce.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 f=p.details;if(!f){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const m=o.defaultAudioCodec||p.audioCodec||"mp4a.40.2";let T=this.transmuxer;T||(T=this.transmuxer=new Np(this.hls,Le.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const _=this.initPTS[i.cc],b=(t=i.initSegment)==null?void 0:t.data;if(_!==void 0){const L=n?n.index:-1,A=L!==-1,P=new Au(i.level,i.sn,i.stats.chunkCount,r.byteLength,L,A);T.push(r,b,m,"",i,n,f.totalduration,!1,P,_)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${f.startSN} ,${f.endSN}],track ${u}`);const{cache:w}=this.waitingData=this.waitingData||{frag:i,part:n,cache:new Ep,complete:!1};w.push(new Uint8Array(r)),this.waitingVideoCC=this.videoTrackCC,this.state=ce.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!==Le.AUDIO){if(!this.loadedmetadata&&i.type===Le.MAIN){const r=this.videoBuffer||this.media;r&&Ze.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,gt({},r)))}this.fragBufferedComplete(i,n)}onError(e,t){var i;if(t.fatal){this.state=ce.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(Le.AUDIO,t);break;case te.AUDIO_TRACK_LOAD_ERROR:case te.AUDIO_TRACK_LOAD_TIMEOUT:case te.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===ce.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===He.AUDIO_TRACK&&(this.state=ce.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!==qe.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==qe.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===ce.ENDED&&(this.state=ce.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,Le.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:f}=u,{details:m}=f,{audio:T,text:_,id3:b,initSegment:w}=r;if(this.fragContextChanged(h)||!m){this.fragmentTracker.removeFragment(h);return}if(this.state=ce.PARSING,this.switchingTrack&&T&&this.completeAudioSwitch(this.switchingTrack),w!=null&&w.tracks){const L=h.initSegment||h;this._bufferInitSegment(f,w.tracks,L,o),n.trigger(I.FRAG_PARSING_INIT_SEGMENT,{frag:L,id:i,tracks:w.tracks})}if(T){const{startPTS:L,endPTS:A,startDTS:P,endDTS:O}=T;p&&(p.elementaryStreams[qe.AUDIO]={startPTS:L,endPTS:A,startDTS:P,endDTS:O}),h.setElementaryStreamInfo(qe.AUDIO,L,A,P,O),this.bufferFragmentData(T,h,p,o)}if(b!=null&&(t=b.samples)!=null&&t.length){const L=ct({id:i,frag:h,details:m},b);n.trigger(I.FRAG_PARSING_METADATA,L)}if(_){const L=ct({id:i,frag:h,details:m},_);n.trigger(I.FRAG_PARSING_USERDATA,L)}}_bufferInitSegment(e,t,i,n){if(this.state!==ce.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===pt.NOT_LOADED||n===pt.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=ce.WAITING_INIT_PTS;const o=this.mainDetails;o&&o.fragments[0].start!==t.details.fragments[0].start&&Ea(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;kn({name:t,lang:i,assocLang:n,characteristics:r,audioCodec:o,channels:u},e,bn)||(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,gt({},e))}}function Bp(s,e){if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(!Hs(s[t].attrs,e[t].attrs))return!1;return!0}function Hs(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 Xl(s,e){return e.label.toLowerCase()===s.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(s.lang||"").toLowerCase())}class NE extends Lu{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,_)=>{T.id=_});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=u;const h=this.hls.config.audioPreference;if(!r&&h){const T=yi(h,u,bn);if(T>-1)r=u[T];else{const _=yi(h,this.tracks);r=this.tracks[_]}}let p=this.findTrackId(r);p===-1&&r&&(p=this.findTrackId(null));const f={audioTracks:u};this.log(`Updating audio tracks, ${u.length} track(s) found in group(s): ${i?.join(",")}`),this.hls.trigger(I.AUDIO_TRACKS_UPDATED,f);const m=this.trackId;if(p!==-1&&m===-1)this.setAudioTrack(p);else if(u.length&&m===-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:ke.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===He.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&&kn(e,n,bn))return n;const r=yi(e,this.tracksInGroup,bn);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=N_(e,t.levels,i,o,bn);if(u===-1)return null;t.nextLoadLevel=u}if(e.channels||e.audioCodec){const o=yi(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,gt({},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||kn(e,n,bn)))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 f=t[p];if(kn({name:i,lang:n,assocLang:r,characteristics:o,audioCodec:u,channels:h},f,bn))return p}for(let p=0;p<t.length;p++){const f=t[p];if(Hs(e.attrs,f.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return p}for(let p=0;p<t.length;p++){const f=t[p];if(Hs(e.attrs,f.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 nd=500;class BE extends Iu{constructor(e,t,i){super(e,t,i,"[subtitle-stream-controller]",Le.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=ce.IDLE,this.setInterval(nd),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=ce.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,Le.SUBTITLE)}}onFragBuffered(e,t){if(!this.loadedmetadata&&t.frag.type===Le.MAIN){var i;(i=this.media)!=null&&i.buffered.length&&(this.loadedmetadata=!0)}}onError(e,t){const i=t.frag;i?.type===Le.SUBTITLE&&(t.details===te.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==ce.STOPPED&&(this.state=ce.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Bp(this.levels,t)){this.levels=t.map(i=>new us(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const n=new us(i);return this.tracksBuffered[n.id]=[],n}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Le.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(nd)}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 m=this.mainDetails;if(o.deltaUpdateFailed||!m)return;const T=m.fragments[0];if(!h.details)o.hasProgramDateTime&&m.hasProgramDateTime?(Ea(o,m),p=o.fragments[0].start):T&&(p=T.start,Wl(o,p));else{var f;p=this.alignPlaylists(o,h.details,(f=this.levelLastLoaded)==null?void 0:f.details),p===0&&T&&(p=T.start,Wl(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===ce.IDLE&&(_a(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:ke.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=ce.IDLE})}}doTick(){if(!this.media){this.state=ce.IDLE;return}if(this.state===ce.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=Ze.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,n.maxBufferHole),{end:u,len:h}=o,p=this.getFwdBufferInfo(this.media,Le.MAIN),f=i.details,m=this.getMaxBufferLength(p?.len)+f.levelTargetDuration;if(h>m)return;const T=f.fragments,_=T.length,b=f.edge;let w=null;const L=this.fragPrevious;if(u<b){const A=n.maxFragLookUpTolerance,P=u>b-A?0:A;w=_a(L,T,Math.max(T[0].start,u),P),!w&&L&&L.start<T[0].start&&(w=T[0])}else w=T[_-1];if(!w)return;if(w=this.mapToInitFragWhenRequired(w),w.sn!=="initSegment"){const A=w.sn-f.startSN,P=T[A-1];P&&P.cc===w.cc&&this.fragmentTracker.getState(P)===pt.NOT_LOADED&&(w=P)}this.fragmentTracker.getState(w)===pt.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 UE(this.tracksBuffered[this.currentTrackId]||[])}}class UE{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 HE extends Lu{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=Jr(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),Jr(this.media.textTracks).forEach(t=>{is(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(f=>!i||i.indexOf(f.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(f=>f.default)&&(this.selectDefaultTrack=!1),o.forEach((f,m)=>{f.id=m});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const u=this.hls.config.subtitlePreference;if(!r&&u){this.selectDefaultTrack=!1;const f=yi(u,o);if(f>-1)r=o[f];else{const m=yi(u,this.tracks);r=this.tracks[m]}}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||kn(r,e)))return n}if(e){for(let n=0;n<t.length;n++){const r=t[n];if(Hs(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return n}for(let n=0;n<t.length;n++){const r=t[n];if(Hs(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(Xl(n,e))return i}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===He.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&&kn(e,i))return i;const n=yi(e,this.tracksInGroup);if(n>-1){const r=this.tracksInGroup[n];return this.setSubtitleTrack(n),r}else{if(i)return null;{const r=yi(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=Jr(e.textTracks),i=this.currentTrack;let n;if(i&&(n=t.filter(r=>Xl(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||!Ee(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:f}=n;this.hls.trigger(I.SUBTITLE_TRACK_SWITCH,{id:o,groupId:u,name:h,type:p,url:f});const m=this.switchParams(n.url,i?.details,n.details);this.loadPlaylist(m)}}class $E{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 sd=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;class jE{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=QT(In(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 $E(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=In(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,rd(i),VE(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&&rd(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:f,levelCodec:m,container:T,metadata:_}=t[o],b=Lh(h.codec,h.levelCodec),w=b?.replace(sd,"$1");let L=Lh(f,m);const A=(u=L)==null?void 0:u.replace(sd,"$1");if(L&&w!==A){o.slice(0,5)==="audio"&&(L=ma(L,this.appendSource));const P=`${T};codecs=${L}`;this.appendChangeType(o,P),this.log(`switching codec ${b} to ${L}`),this.tracks[o]={buffer:h.buffer,codec:f,container:T,levelCodec:m,metadata:_,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:f}=t,m=f.buffering[u],T=self.performance.now();m.start=T;const _=h.stats.buffering,b=p?p.stats.buffering:null;_.start===0&&(_.start=T),b&&b.start===0&&(b.start=T);const w=r.audio;let L=!1;u==="audio"&&w?.container==="audio/mpeg"&&(L=!this.lastMpegAudioChunk||f.id===1||this.lastMpegAudioChunk.sn!==f.sn,this.lastMpegAudioChunk=f);const A=h.start,P={execute:()=>{if(m.executeStart=self.performance.now(),L){const O=this.sourceBuffer[u];if(O){const M=A-O.timestampOffset;Math.abs(M)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${A} (delta: ${M}) sn: ${h.sn})`),O.timestampOffset=A)}}this.appendExecutor(o,u)},onStart:()=>{},onComplete:()=>{const O=self.performance.now();m.executeEnd=m.end=O,_.first===0&&(_.first=O),b&&b.first===0&&(b.first=O);const{sourceBuffer:M}=this,k={};for(const N in M)k[N]=Ze.getBuffered(M[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:f,parent:h.type,timeRanges:k})},onError:O=>{const M={type:ke.MEDIA_ERROR,parent:h.type,details:te.BUFFER_APPEND_ERROR,sourceBufferName:u,frag:h,part:p,chunkMeta:f,error:O,err:O,fatal:!1};if(O.code===DOMException.QUOTA_EXCEEDED_ERR)M.details=te.BUFFER_FULL_ERROR;else{const k=++this.appendErrors[u];M.details=te.BUFFER_APPEND_ERROR,this.warn(`Failed ${k}/${i.config.appendErrorMaxRetry} times to append segment in "${u}" sourceBuffer`),k>=i.config.appendErrorMaxRetry&&(M.fatal=!0)}i.trigger(I.ERROR,M)}};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[qe.AUDIOVIDEO]?r.push("audiovideo"):(o[qe.AUDIO]&&r.push("audio"),o[qe.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(Ee(h)&&h>0){const p=Math.max(h,u),f=Math.floor(o/u)*u-p;this.flushBackBuffer(o,u,f)}if(Ee(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){const p=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),f=Math.max(p,u),m=Math.floor(o/u)*u+f;this.flushFrontBuffer(o,u,m)}}flushBackBuffer(e,t,i){const{details:n,sourceBuffer:r}=this;this.getSourceBufferTypes().forEach(u=>{const h=r[u];if(h){const p=Ze.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=Ze.getBuffered(u),p=h.length;if(p<2)return;const f=h.start(p-1),m=h.end(p-1);if(i>f||e>=f&&e<=m)return;if(u.ended&&e-m<2*t){this.log(`Cannot flush ${o} front buffer while SourceBuffer is in ended state`);return}this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:f,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=Ee(n.duration)?n.duration:0;e.live&&t.config.liveDurationInfinity?(n.duration=1/0,this.updateSeekableRange(e)):(r>u&&r>o||!Ee(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:ke.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=ma(u,this.appendSource));const h=`${o.container};codecs=${u}`;this.log(`creating sourceBuffer(${h})`);try{const p=t[r]=i.addSourceBuffer(h),f=r;this.addBufferListener(f,"updatestart",this._onSBUpdateStart),this.addBufferListener(f,"updateend",this._onSBUpdateEnd),this.addBufferListener(f,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(f,"bufferedchange",(m,T)=>{const _=T.removedRanges;_!=null&&_.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:ke.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:ke.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=Ee(n.duration)?n.duration:1/0,f=Ee(r.duration)?r.duration:1/0,m=Math.max(0,t),T=Math.min(i,p,f);T>m&&(!h.ending||h.ended)?(h.ended=!1,this.log(`Removing [${m},${T}] from the ${e} SourceBuffer`),h.remove(m,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 rd(s){const e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t)})}function VE(s,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t)}const GE={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},Up=s=>String.fromCharCode(GE[s]||s),Zt=15,Ii=100,KE={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},qE={17:2,18:4,21:6,22:8,23:10,19:13,20:15},WE={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},zE={25:2,26:4,29:6,30:8,31:10,27:13,28:15},YE=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class XE{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 Tn=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class Hp{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 QE{constructor(){this.uchar=" ",this.penState=new Hp}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 JE{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Hp,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Ii;t++)this.chars.push(new QE);this.logger=e}equals(e){for(let t=0;t<Ii;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Ii;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Ii;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>Ii&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ii)}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=Up(e);if(this.pos>=Ii){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<Ii;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<Ii;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 ll{constructor(e){this.rows=[],this.currRow=Zt-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Zt;t++)this.rows.push(new JE(e));this.logger=e}reset(){for(let e=0;e<Zt;e++)this.rows[e].clear();this.currRow=Zt-1}equals(e){let t=!0;for(let i=0;i<Zt;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<Zt;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Zt;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<Zt;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<Zt;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 ad{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 ll(i),this.nonDisplayedMemory=new ll(i),this.lastOutputScreen=new ll(i),this.currRollUpRow=this.displayedMemory.rows[Zt-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[Zt-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 od{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=eb(),this.logger=void 0;const n=this.logger=new XE;this.channels=[null,new ad(e,t,n),new ad(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,()=>"["+Tn([t[i],t[i+1]])+"] -> ("+Tn([n,r])+")");const h=this.cmdHistory;if(n>=16&&n<=31){if(ZE(n,r,h)){Or(null,null,h),this.logger.log(3,()=>"Repeated command ("+Tn([n,r])+") is dropped");continue}Or(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 Or(null,null,h);if(!o&&(u=this.parseChars(n,r),u)){const f=this.currentChannel;f&&f>0?this.channels[f].insertChars(u):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!o&&!u&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Tn([n,r])+" orig: "+Tn([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 ("+Tn([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?KE[e]:WE[e]:i=o===1?qE[e]:zE[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 '"+Up(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 =  "+Tn(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=YE[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()}Or(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 Or(s,e,t){t.a=s,t.b=e}function ZE(s,e,t){return t.a===s&&t.b===e}function eb(){return{a:null,b:null}}class Fr{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 Ou=function(){if(ls!=null&&ls.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 f=arguments[p];for(const m in f)u[m]=f[m]}return u}function o(u,h,p){const f=this,m={enumerable:!0};f.hasBeenReset=!1;let T="",_=!1,b=u,w=h,L=p,A=null,P="",O=!0,M="auto",k="start",N=50,H="middle",G=50,B="middle";Object.defineProperty(f,"id",r({},m,{get:function(){return T},set:function(D){T=""+D}})),Object.defineProperty(f,"pauseOnExit",r({},m,{get:function(){return _},set:function(D){_=!!D}})),Object.defineProperty(f,"startTime",r({},m,{get:function(){return b},set:function(D){if(typeof D!="number")throw new TypeError("Start time must be set to a number.");b=D,this.hasBeenReset=!0}})),Object.defineProperty(f,"endTime",r({},m,{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(f,"text",r({},m,{get:function(){return L},set:function(D){L=""+D,this.hasBeenReset=!0}})),Object.defineProperty(f,"region",r({},m,{get:function(){return A},set:function(D){A=D,this.hasBeenReset=!0}})),Object.defineProperty(f,"vertical",r({},m,{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(f,"snapToLines",r({},m,{get:function(){return O},set:function(D){O=!!D,this.hasBeenReset=!0}})),Object.defineProperty(f,"line",r({},m,{get:function(){return M},set:function(D){if(typeof D!="number"&&D!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");M=D,this.hasBeenReset=!0}})),Object.defineProperty(f,"lineAlign",r({},m,{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(f,"position",r({},m,{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(f,"positionAlign",r({},m,{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(f,"size",r({},m,{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(f,"align",r({},m,{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}})),f.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o}();class tb{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function $p(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 ib{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 jp(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 Ql=new Ou(0,0,""),Nr=Ql.align==="middle"?"middle":"center";function nb(s,e,t){const i=s;function n(){const u=$p(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 ib;jp(u,function(T,_){let b;switch(T){case"region":for(let w=t.length-1;w>=0;w--)if(t[w].id===_){p.set(T,t[w].region);break}break;case"vertical":p.alt(T,_,["rl","lr"]);break;case"line":b=_.split(","),p.integer(T,b[0]),p.percent(T,b[0])&&p.set("snapToLines",!1),p.alt(T,b[0],["auto"]),b.length===2&&p.alt("lineAlign",b[1],["start",Nr,"end"]);break;case"position":b=_.split(","),p.percent(T,b[0]),b.length===2&&p.alt("positionAlign",b[1],["start",Nr,"end","line-left","line-right","auto"]);break;case"size":p.percent(T,_);break;case"align":p.alt(T,_,["start",Nr,"end","left","right"]);break}},/:/,/\s/),h.region=p.get("region",null),h.vertical=p.get("vertical","");let f=p.get("line","auto");f==="auto"&&Ql.line===-1&&(f=-1),h.line=f,h.lineAlign=p.get("lineAlign","start"),h.snapToLines=p.get("snapToLines",!0),h.size=p.get("size",100),h.align=p.get("align",Nr);let m=p.get("position","auto");m==="auto"&&Ql.position===50&&(m=h.align==="start"||h.align==="left"?0:h.align==="end"||h.align==="right"?100:50),h.position=m}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 Vp(s){return s.replace(/<br(?: \/)?>/gi,`
`)}class sb{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new tb,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=Vp(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){jp(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 Ou(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{nb(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 rb=/\r\n|\n\r|\n|\r/g,ul=function(e,t,i=0){return e.slice(i,i+t.length)===t},ab=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(!Ee(t)||!Ee(i)||!Ee(n)||!Ee(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*n,t+=60*60*1e3*r,t},cl=function(e){let t=5381,i=e.length;for(;i;)t=t*33^e.charCodeAt(--i);return(t>>>0).toString()};function Fu(s,e,t){return cl(s.toString())+cl(e.toString())+cl(t)}const ob=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 lb(s,e,t,i,n,r,o){const u=new sb,h=Ti(new Uint8Array(s)).trim().replace(rb,`
`).split(`
`),p=[],f=e?wE(e.baseTime,e.timescale):0;let m="00:00.000",T=0,_=0,b,w=!0;u.oncue=function(L){const A=t[i];let P=t.ccOffset;const O=(T-f)/9e4;if(A!=null&&A.new&&(_!==void 0?P=t.ccOffset=A.start:ob(t,i,O)),O){if(!e){b=new Error("Missing initPTS for VTT MPEGTS");return}P=O-t.presentationOffset}const M=L.endTime-L.startTime,k=Gt((L.startTime+P-_)*9e4,n*9e4)/9e4;L.startTime=Math.max(k,0),L.endTime=Math.max(k+M,0);const N=L.text.trim();L.text=decodeURIComponent(encodeURIComponent(N)),L.id||(L.id=Fu(L.startTime,L.endTime,N)),L.endTime>0&&p.push(L)},u.onparsingerror=function(L){b=L},u.onflush=function(){if(b){o(b);return}r(p)},h.forEach(L=>{if(w)if(ul(L,"X-TIMESTAMP-MAP=")){w=!1,L.slice(16).split(",").forEach(A=>{ul(A,"LOCAL:")?m=A.slice(6):ul(A,"MPEGTS:")&&(T=parseInt(A.slice(7)))});try{_=ab(m)/1e3}catch(A){b=A}return}else L===""&&(w=!1);u.parse(L+`
`)}),u.flush()}const hl="stpp.ttml.im1t",Gp=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Kp=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,ub={left:"start",center:"center",right:"end",start:"start",end:"end"};function ld(s,e,t,i){const n=De(new Uint8Array(s),["mdat"]);if(n.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const r=n.map(u=>Ti(u)),o=CE(e.baseTime,1,e.timescale);try{r.forEach(u=>t(cb(u,o)))}catch(u){i(u)}}function cb(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((m,T)=>(m[T]=n.getAttribute(`ttp:${T}`)||r[T],m),{}),u=n.getAttribute("xml:space")!=="preserve",h=ud(dl(n,"styling","style")),p=ud(dl(n,"layout","region")),f=dl(n,"body","[begin]");return[].map.call(f,m=>{const T=qp(m,u);if(!T||!m.hasAttribute("begin"))return null;const _=pl(m.getAttribute("begin"),o),b=pl(m.getAttribute("dur"),o);let w=pl(m.getAttribute("end"),o);if(_===null)throw cd(m);if(w===null){if(b===null)throw cd(m);w=_+b}const L=new Ou(_-e,w-e,T);L.id=Fu(L.startTime,L.endTime,L.text);const A=p[m.getAttribute("region")],P=h[m.getAttribute("style")],O=hb(A,P,h),{textAlign:M}=O;if(M){const k=ub[M];k&&(L.lineAlign=k),L.align=M}return ct(L,O),L}).filter(m=>m!==null)}function dl(s,e,t){const i=s.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function ud(s){return s.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function qp(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?qp(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function hb(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=fl(e,i,h)||fl(s,i,h)||fl(n,i,h);return p&&(u[h]=p),u},{})}function fl(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function cd(s){return new Error(`Could not parse ttml timestamp ${s}`)}function pl(s,e){if(!s)return null;let t=$p(s);return t===null&&(Gp.test(s)?t=db(s,e):Kp.test(s)&&(t=fb(s,e))),t}function db(s,e){const t=Gp.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 fb(s,e){const t=Kp.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 pb{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=dd(),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 Fr(this,"textTrack1"),t=new Fr(this,"textTrack2"),i=new Fr(this,"textTrack3"),n=new Fr(this,"textTrack4");this.cea608Parser1=new od(1,e,t),this.cea608Parser2=new od(3,i,n)}}addCues(e,t,i,n,r){let o=!1;for(let u=r.length;u--;){const h=r[u],p=gb(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(hd(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,is(i[e]),dp(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=>{is(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=dd(),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++)is(t[i])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],n=i.some(r=>r.textCodec===hl);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(Bp(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const o=this.media,u=o?Jr(o.textTracks):null;if(this.tracks.forEach((h,p)=>{let f;if(u){let m=null;for(let T=0;T<u.length;T++)if(u[T]&&hd(u[T],h)){m=u[T],u[T]=null;break}m&&(f=m)}if(f)is(f);else{const m=Wp(h);f=this.createTextTrack(m,h.name,h.lang),f&&(f.mode="disabled")}f&&this.textTracks.push(f)}),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===Le.MAIN){var i,n;const{cea608Parser1:r,cea608Parser2:o,lastSn:u}=this,{cc:h,sn:p}=t.frag,f=(i=(n=t.part)==null?void 0:n.index)!=null?i:-1;r&&o&&(p!==u+1||p===u&&f!==this.lastPartIndex+1||h!==this.lastCc)&&(r.reset(),o.reset()),this.lastCc=h,this.lastSn=p,this.lastPartIndex=f}}onFragLoaded(e,t){const{frag:i,payload:n}=t;if(i.type===Le.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===hl?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;ld(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?Kt(i.initSegment.data,new Uint8Array(n)):n;lb(p,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,f=>{this._appendCues(f,i.level),h.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},f=>{const m=f.message==="Missing initPTS for VTT MPEGTS";m?o.push(e):this._fallbackToIMSC1(i,n),W.log(`Failed to parse VTT cue: ${f}`),!(m&&u>i.cc)&&h.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:f})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||ld(t,this.initPTS[e.cc],()=>{i.textCodec=hl,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=>fp(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===Le.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===Le.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=>Gl(u[h],t,i))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:u}=this;Object.keys(u).forEach(h=>Gl(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 f=3&o;(f===0||f===1)&&(t[f].push(u),t[f].push(h))}}return t}}function Wp(s){return s.characteristics&&/transcribes-spoken-dialog/gi.test(s.characteristics)&&/describes-music-and-sound/gi.test(s.characteristics)?"captions":"subtitles"}function hd(s,e){return!!s&&s.kind===Wp(e)&&Xl(e,s)}function gb(s,e,t,i){return Math.min(e,i)-Math.max(s,t)}function dd(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}class Nu{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&&Ee(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,Nu.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 mb{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 f=p.currentLevel;W.warn("drop FPS ratio greater than max allowed value for currentLevel: "+f),f>0&&(p.autoLevelCapping===-1||p.autoLevelCapping>=f)&&(f=f-1,p.trigger(I.FPS_DROP_LEVEL_CAPPING,{level:f,droppedLevel:p.currentLevel}),p.autoLevelCapping=f,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 Br="[eme]";class rs{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=rs.CDMCleanupPromise?[rs.CDMCleanupPromise]:[],this.debug=W.debug.bind(W,Br),this.log=W.log.bind(W,Br),this.warn=W.warn.bind(W,Br),this.error=W.error.bind(W,Br),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=kr(this.config));const u=o.map(Xo).filter(h=>!!h);this.keyFormatPromise=this.getKeyFormatPromise(u)}this.keyFormatPromise.then(o=>{const u=zo(o);let h,p;if(i==="sinf"){if(u!==Ve.FAIRPLAY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${u}`);return}const b=ht(new Uint8Array(n));try{const w=bu(JSON.parse(b).sinf),L=op(w);if(!L)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");h=L.subarray(8,24),p=Ve.FAIRPLAY}catch(w){this.warn(`${r} Failed to parse sinf: ${w}`);return}}else{if(u!==Ve.WIDEVINE&&u!==Ve.PLAYREADY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${u}`);return}const b=WT(n),w=b.filter(A=>!!A.systemId&&Yo(A.systemId)===u);w.length>1&&this.warn(`${r} Using first of ${w.length} pssh found for selected key-system ${u}`);const L=w[0];if(!L){b.length===0||b.some(A=>!A.systemId)?this.warn(`${r} contains incomplete or invalid pssh data`):this.log(`ignoring ${r} for ${b.map(A=>Yo(A.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(p=Yo(L.systemId),L.version===0&&L.data)if(p===Ve.WIDEVINE){const A=L.data.length-22;h=L.data.subarray(A,A+16)}else p===Ve.PLAYREADY&&(h=Zf(L.data))}if(!p||!h){this.log(`Unable to handle ${r} with key-system ${u}`);return}const f=hi.hexDump(h),{keyIdToKeySessionPromise:m,mediaKeySessions:T}=this;let _=m[f];for(let b=0;b<T.length;b++){const w=T[b],L=w.decryptdata;if(!L.keyId)continue;const A=hi.hexDump(L.keyId);if(f===A||L.uri.replace(/-/g,"").indexOf(f)!==-1){if(_=m[A],L.pssh)break;delete m[A],L.pssh=new Uint8Array(n),L.keyId=h,_=m[f]=_.then(()=>this.generateRequestWithPreferredKeySession(w,i,n,"encrypted-event-key-match")),_.catch(P=>this.handleError(P));break}}if(!_){if(p!==u){this.log(`Ignoring "${r}" with ${p} init data for selected key-system ${u}`);return}_=m[f]=this.getKeySystemSelectionPromise([p]).then(({keySystem:b,mediaKeys:w})=>{var L;this.throwIfDestroyed();const A=new Bs("ISO-23001-7",f,(L=Xo(b))!=null?L:"");return A.pssh=new Uint8Array(n),A.keyId=h,this.attemptSetMediaKeys(b,w).then(()=>{this.throwIfDestroyed();const P=this.createMediaKeySessionContext({decryptdata:A,keySystem:b,mediaKeys:w});return this.generateRequestWithPreferredKeySession(P,i,n,"encrypted-event-no-match")})}),_.catch(b=>this.handleError(b))}})}},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===Ve.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 f=p.shift();this.getMediaKeysPromise(f,n,r).then(m=>o({keySystem:f,mediaKeys:m})).catch(m=>{p.length?h(p):m instanceof $t?u(m):u(new $t({type:ke.KEY_SYSTEM_ERROR,details:te.KEY_SYSTEM_NO_ACCESS,error:m,fatal:!0},m.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 Jf===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=bT(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(f=>(this.log(`Media-keys created for "${e}"`),p.then(m=>m?this.setMediaKeysServerCertificate(f,e,m):f))),u.mediaKeys.catch(f=>{this.error(`Failed to create media-keys for "${e}"}: ${f}`)}),u.mediaKeys})}return o.then(()=>r.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${hi.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 hi.hexDump(e.keyId)}updateKeySession(e,t){var i;const n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyID ${hi.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=kr(this.config),r=e.map(zo).filter(o=>!!o&&n.indexOf(o)!==-1);return this.getKeySystemSelectionPromise(r).then(({keySystem:o})=>{const u=Xo(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 $t?this.hls.trigger(I.ERROR,e.data):this.hls.trigger(I.ERROR,{type:ke.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=zo(e.keyFormat),r=n?[n]:kr(this.config);return this.attemptKeySystemAccess(r)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=kr(this.config)),e.length===0)throw new $t({type:ke.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 b=u.call(this.hls,t,i,e);if(!b)throw new Error("Invalid response from configured generateRequest filter");t=b.initDataType,i=e.decryptdata.pssh=b.initData?new Uint8Array(b.initData):null}catch(b){var h;if(this.warn(b.message),(h=this.hls)!=null&&h.config.debug)throw b}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 f=new Mu,m=e._onmessage=b=>{const w=e.mediaKeysSession;if(!w){f.emit("error",new Error("invalid state"));return}const{messageType:L,message:A}=b;this.log(`"${L}" message event for session "${w.sessionId}" message size: ${A.byteLength}`),L==="license-request"||L==="license-renewal"?this.renewLicense(e,A).catch(P=>{this.handleError(P),f.emit("error",P)}):L==="license-release"?e.keySystem===Ve.FAIRPLAY&&(this.updateKeySession(e,jl("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${L}"`)},T=e._onkeystatuseschange=b=>{if(!e.mediaKeysSession){f.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const L=e.keyStatus;f.emit("keyStatus",L),L==="expired"&&(this.warn(`${e.keySystem} expired for key ${p}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",m),e.mediaKeysSession.addEventListener("keystatuseschange",T);const _=new Promise((b,w)=>{f.on("error",w),f.on("keyStatus",L=>{L.startsWith("usable")?b():L==="output-restricted"?w(new $t({type:ke.KEY_SYSTEM_ERROR,details:te.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):L==="internal-error"?w(new $t({type:ke.KEY_SYSTEM_ERROR,details:te.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${L}"`)):L==="expired"?w(new Error("key expired while generating request")):this.warn(`unhandled key status change "${L}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var b;this.log(`Request generated for key-session "${(b=e.mediaKeysSession)==null?void 0:b.sessionId}" keyId: ${p}`)}).catch(b=>{throw new $t({type:ke.KEY_SYSTEM_ERROR,details:te.KEY_SYSTEM_NO_SESSION,error:b,fatal:!1},`Error generating key-session request: ${b}`)}).then(()=>_).catch(b=>{throw f.removeAllListeners(),this.removeSession(e),b}).then(()=>(f.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${hi.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${hi.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,f={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},m={onSuccess:(T,_,b,w)=>{o(T.data)},onError:(T,_,b,w)=>{u(new $t({type:ke.KEY_SYSTEM_ERROR,details:te.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:b,response:gt({url:h.url,data:void 0},T)},`"${e}" certificate request failed (${r}). Status: ${T.code} (${T.text})`))},onTimeout:(T,_,b)=>{u(new $t({type:ke.KEY_SYSTEM_ERROR,details:te.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:b,response:{url:h.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(T,_,b)=>{u(new Error("aborted"))}};n.load(h,f,m)})):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 $t({type:ke.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 $t({type:ke.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 f;for(let m=0,T=r.length;m<T;m++){var o,u;f=r[m];const _=(o=f.querySelector("name"))==null?void 0:o.textContent,b=(u=f.querySelector("value"))==null?void 0:u.textContent;_&&b&&e.setRequestHeader(_,b)}}const h=n.querySelector("Challenge"),p=h?.textContent;if(!p)throw new Error("Cannot find <Challenge> in key message");return jl(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(f){this.error(f)}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 $t({type:ke.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 f=p-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${f} 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==Ve.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={},Bs.clearKeyUriToKeyIdMap();const i=t.length;rs.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}`)})}}}rs.CDMCleanupPromise=void 0;class $t 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 Ct;(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"})(Ct||(Ct={}));var Jl;(function(s){s.DASH="d",s.HLS="h",s.SMOOTH="s",s.OTHER="o"})(Jl||(Jl={}));var wn;(function(s){s.OBJECT="CMCD-Object",s.REQUEST="CMCD-Request",s.SESSION="CMCD-Session",s.STATUS="CMCD-Status"})(wn||(wn={}));const yb={[wn.OBJECT]:["br","d","ot","tb"],[wn.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[wn.SESSION]:["cid","pr","sf","sid","st","v"],[wn.STATUS]:["bs","rtp"]};class cs{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(i=>i instanceof cs?i:new cs(i))),this.value=e,this.params=t}}class zp{constructor(e){this.description=void 0,this.description=e}}const vb="Dict";function Tb(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 _b(s,e,t,i){return new Error(`failed to ${s} "${Tb(e)}" as ${t}`,{cause:i})}const fd="Bare Item",Eb="Boolean",bb="Byte Sequence",Sb="Decimal",Cb="Integer";function wb(s){return s<-999999999999999||999999999999999<s}const Lb=/[\x00-\x1f\x7f]+/,Ab="Token",kb="Key";function _i(s,e,t){return _b("serialize",s,e,t)}function Ib(s){if(typeof s!="boolean")throw _i(s,Eb);return s?"?1":"?0"}function Rb(s){return btoa(String.fromCharCode(...s))}function Pb(s){if(ArrayBuffer.isView(s)===!1)throw _i(s,bb);return`:${Rb(s)}:`}function Yp(s){if(wb(s))throw _i(s,Cb);return s.toString()}function Db(s){return`@${Yp(s.getTime()/1e3)}`}function Xp(s,e){if(s<0)return-Xp(-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 xb(s){const e=Xp(s,3);if(Math.floor(Math.abs(e)).toString().length>12)throw _i(s,Sb);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Mb="String";function Ob(s){if(Lb.test(s))throw _i(s,Mb);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Fb(s){return s.description||s.toString().slice(7,-1)}function pd(s){const e=Fb(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw _i(e,Ab);return e}function Zl(s){switch(typeof s){case"number":if(!Ee(s))throw _i(s,fd);return Number.isInteger(s)?Yp(s):xb(s);case"string":return Ob(s);case"symbol":return pd(s);case"boolean":return Ib(s);case"object":if(s instanceof Date)return Db(s);if(s instanceof Uint8Array)return Pb(s);if(s instanceof zp)return pd(s);default:throw _i(s,fd)}}function eu(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw _i(s,kb);return s}function Bu(s){return s==null?"":Object.entries(s).map(([e,t])=>t===!0?`;${eu(e)}`:`;${eu(e)}=${Zl(t)}`).join("")}function Qp(s){return s instanceof cs?`${Zl(s.value)}${Bu(s.params)}`:Zl(s)}function Nb(s){return`(${s.value.map(Qp).join(" ")})${Bu(s.params)}`}function Bb(s,e={whitespace:!0}){if(typeof s!="object")throw _i(s,vb);const t=s instanceof Map?s.entries():Object.entries(s),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([n,r])=>{r instanceof cs||(r=new cs(r));let o=eu(n);return r.value===!0?o+=Bu(r.params):(o+="=",Array.isArray(r.value)?o+=Nb(r):o+=Qp(r)),o}).join(`,${i}`)}function Ub(s,e){return Bb(s,e)}const Hb=s=>s==="ot"||s==="sf"||s==="st",$b=s=>typeof s=="number"?Ee(s):s!=null&&s!==""&&s!==!1;function jb(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 Vb(){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 sa=s=>Math.round(s),Gb=(s,e)=>(e!=null&&e.baseUrl&&(s=jb(s,e.baseUrl)),encodeURIComponent(s)),Ur=s=>sa(s/100)*100,Kb={br:sa,d:sa,bl:Ur,dl:Ur,mtp:Ur,nor:Gb,rtp:Ur,tb:sa};function qb(s,e){const t={};if(s==null||typeof s!="object")return t;const i=Object.keys(s).sort(),n=ct({},Kb,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||$b(u)&&(Hb(o)&&typeof u=="string"&&(u=new zp(u)),t[o]=u))}),t}function Jp(s,e={}){return s?Ub(qb(s,e),ct({whitespace:!1},e)):""}function Wb(s,e={}){if(!s)return{};const t=Object.entries(s),i=Object.entries(yb).concat(Object.entries(e?.customHeaderMap||{})),n=t.reduce((r,o)=>{var u,h;const[p,f]=o,m=((u=i.find(T=>T[1].includes(p)))==null?void 0:u[0])||wn.REQUEST;return(h=r[m])!=null||(r[m]={}),r[m][p]=f,r},{});return Object.entries(n).reduce((r,[o,u])=>(r[o]=Jp(u,e),r),{})}function zb(s,e,t){return ct(s,Wb(e,t))}const Yb="CMCD";function Xb(s,e={}){if(!s)return"";const t=Jp(s,e);return`${Yb}=${encodeURIComponent(t)}`}const gd=/CMCD=[^&#]+/;function Qb(s,e,t){const i=Xb(e,t);if(!i)return s;if(gd.test(s))return s.replace(gd,i);const n=s.includes("?")?"&":"?";return`${s}${n}${i}`}class Jb{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:Ct.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===Ct.VIDEO||u===Ct.AUDIO||u==Ct.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||Vb(),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:Jl.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ct(t,this.createData());const i=t.ot===Ct.INIT||t.ot===Ct.VIDEO||t.ot===Ct.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={}),zb(e.headers,t)):e.url=Qb(e.url,t)}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Ct.TIMED_TEXT;if(e.sn==="initSegment")return Ct.INIT;if(t==="audio")return Ct.AUDIO;if(t==="main")return this.hls.audioTracks.length?Ct.VIDEO:Ct.MUXED}getTopBandwidth(e){let t=0,i;const n=this.hls;if(e===Ct.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===Ct.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:Ze.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 Zb=3e5;class eS{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===Tt.SendAlternateToPenaltyBox&&i.flags===Jt.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]>Zb&&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,yp(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===He.AUDIO_TRACK&&n[r].hasAudioGroup(e)||t===He.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(f=>f.pathwayId===o))return;const p=this.getLevelsForPathway(u).map(f=>{const m=new nt(f.attrs);m["PATHWAY-ID"]=o;const T=m.AUDIO&&`${m.AUDIO}_clone_${o}`,_=m.SUBTITLES&&`${m.SUBTITLES}_clone_${o}`;T&&(i[m.AUDIO]=T,m.AUDIO=T),_&&(n[m.SUBTITLES]=_,m.SUBTITLES=_);const b=Zp(f.uri,m["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",h),w=new us({attrs:m,audioCodec:f.audioCodec,bitrate:f.bitrate,height:f.height,name:f.name,url:b,videoCodec:f.videoCodec,width:f.width});if(f.audioGroups)for(let L=1;L<f.audioGroups.length;L++)w.addGroupId("audio",`${f.audioGroups[L]}_clone_${o}`);if(f.subtitleGroups)for(let L=1;L<f.subtitleGroups.length;L++)w.addGroupId("text",`${f.subtitleGroups[L]}_clone_${o}`);return w});t.push(...p),md(this.audioTracks,i,h,o),md(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 f=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+f)}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:(f,m,T,_)=>{this.log(`Loaded steering manifest: "${n}"`);const b=f.data;if(b.VERSION!==1){this.log(`Steering VERSION ${b.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=b.TTL;const{"RELOAD-URI":w,"PATHWAY-CLONES":L,"PATHWAY-PRIORITY":A}=b;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),L&&this.clonePathways(L);const P={steeringManifest:b,url:n.toString()};this.hls.trigger(I.STEERING_MANIFEST_LOADED,P),A&&this.updatePathwayPriority(A)},onError:(f,m,T,_)=>{if(this.log(`Error loading steering manifest: ${f.code} ${f.text} (${m.url})`),this.stopLoad(),f.code===410){this.enabled=!1,this.log(`Steering manifest ${m.url} no longer available`);return}let b=this.timeToLoad*1e3;if(f.code===429){const w=this.loader;if(typeof w?.getResponseHeader=="function"){const L=w.getResponseHeader("Retry-After");L&&(b=parseFloat(L)*1e3)}this.log(`Steering manifest ${m.url} rate limited`);return}this.scheduleRefresh(this.uri||m.url,b)},onTimeout:(f,m,T)=>{this.log(`Timeout loading steering manifest (${m.url})`),this.scheduleRefresh(this.uri||m.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 md(s,e,t,i){s&&Object.keys(e).forEach(n=>{const r=s.filter(o=>o.groupId===n).map(o=>{const u=ct({},o);return u.details=void 0,u.attrs=new nt(u.attrs),u.url=u.attrs.URI=Zp(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 Zp(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 tS=/^age:\s*[\d.]+\s*$/im;class eg{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 xa,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&&Ee(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 m=u??t.response;if(m!=null){i.loading.end=Math.max(self.performance.now(),i.loading.first);const T=t.responseType==="arraybuffer"?m.byteLength:m.length;if(i.loaded=i.total=T,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;const _=this.callbacks.onProgress;if(_&&_(i,e,m,t),!this.callbacks)return;const b={url:t.responseURL,data:m,code:o};this.callbacks.onSuccess(b,i,e,t);return}}const h=r.loadPolicy.errorRetry,p=i.retry,f={url:e.url,data:void 0,code:o};Ta(h,p,!1,f)?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(Ta(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=wu(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&&tS.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 iS(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const nS=/(\d+)-(\d+)\/(\d+)/;class yd{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||oS,this.controller=new self.AbortController,this.stats=new xa}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=sS(e,this.controller.signal),o=i.onProgress,u=e.responseType==="arraybuffer",h=u?"byteLength":"length",{maxTimeToFirstByteMs:p,maxLoadTimeMs:f}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=p&&Ee(p)?p:f,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(n,e,this.response)},t.timeout),self.fetch(this.request).then(m=>{this.response=this.loader=m;const T=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=f,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(n,e,this.response)},f-(T-n.loading.start)),!m.ok){const{status:_,statusText:b}=m;throw new lS(b||"fetch, bad network response",_,m)}return n.loading.first=T,n.total=aS(m.headers)||n.total,o&&Ee(t.highWaterMark)?this.loadProgressively(m,n,e,t.highWaterMark,o):u?m.arrayBuffer():e.responseType==="json"?m.json():m.text()}).then(m=>{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 _=m[h];_&&(n.loaded=n.total=_);const b={url:T.url,data:m,code:T.status};o&&!Ee(t.highWaterMark)&&o(n,e,m,T),i.onSuccess(b,n,e,T)}).catch(m=>{if(self.clearTimeout(this.requestTimeout),n.aborted)return;const T=m&&m.code||0,_=m?m.message:null;i.onError({code:T,text:_},e,m?m.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 Ep,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 f=p.value,m=f.length;return t.loaded+=m,m<n||o.dataLength?(o.push(f),o.dataLength>=n&&r(t,i,o.flush(),e)):r(t,i,f,e),h()}).catch(()=>Promise.reject());return h()}}function sS(s,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ct({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function rS(s){const e=nS.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function aS(s){const e=s.get("Content-Range");if(e){const i=rS(e);if(Ee(i))return i}const t=s.get("Content-Length");if(t)return parseInt(t)}function oS(s,e){return new self.Request(s.url,e)}class lS extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const uS=/\s/,cS={newCue(s,e,t,i){const n=[];let r,o,u,h,p;const f=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 m;for(let w=0;w<r.chars.length;w++)uS.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 _=Vp(p.trim()),b=Fu(e,t,_);s!=null&&(m=s.cues)!=null&&m.getCueById(b)||(o=new f(e,t,_),o.id=b,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,_)=>T.line==="auto"||_.line==="auto"?0:T.line>8&&_.line>8?_.line-T.line:T.line-_.line),n.forEach(T=>fp(s,T))),n}},hS={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},tg=gt(gt({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:eg,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:B_,bufferController:jE,capLevelController:Nu,errorController:L_,fpsController:mb,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:Jf,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:hS},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},dS()),{},{subtitleStreamController:BE,subtitleTrackController:HE,timelineController:pb,audioStreamController:FE,audioTrackController:NE,emeController:rs,cmcdController:Jb,contentSteeringController:eS});function dS(){return{cueHandler:cS,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 fS(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=tu(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 f=`${r}Loading${p}`,m=e[f];if(m!==void 0&&u){h.push(f);const T=t[o].default;switch(e[o]={default:T},p){case"TimeOut":T.maxLoadTimeMs=m,T.maxTimeToFirstByteMs=m;break;case"MaxRetry":T.errorRetry.maxNumRetry=m,T.timeoutRetry.maxNumRetry=m;break;case"RetryDelay":T.errorRetry.retryDelayMs=m,T.timeoutRetry.retryDelayMs=m;break;case"MaxRetryTimeout":T.errorRetry.maxRetryDelayMs=m,T.timeoutRetry.maxRetryDelayMs=m;break}}}),h.length&&W.warn(`hls.js config: "${h.join('", "')}" setting(s) are deprecated, use "${o}": ${JSON.stringify(e[o])}`)}),gt(gt({},t),e)}function tu(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(tu):Object.keys(s).reduce((e,t)=>(e[t]=tu(s[t]),e),{}):s}function pS(s){const e=s.loader;e!==yd&&e!==eg?(W.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):iS()&&(s.loader=yd,s.progressive=!0,s.enableSoftwareAES=!0,W.log("[config]: Progressive streaming enabled, using FetchLoader"))}let gl;class gS extends Lu{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(f=>{var m,T;const _=f.attrs;let{audioCodec:b,videoCodec:w}=f;((m=b)==null?void 0:m.indexOf("mp4a.40.34"))!==-1&&(gl||(gl=/chrome|firefox/i.test(navigator.userAgent)),gl&&(f.audioCodec=b=void 0)),b&&(f.audioCodec=b=ma(b,i)),((T=w)==null?void 0:T.indexOf("avc1"))===0&&(w=f.videoCodec=t_(w));const{width:L,height:A,unknownCodecs:P}=f;if(u||(u=!!(L&&A)),h||(h=!!w),p||(p=!!b),P!=null&&P.length||b&&!el(b,"audio",i)||w&&!el(w,"video",i))return;const{CODECS:O,"FRAME-RATE":M,"HDCP-LEVEL":k,"PATHWAY-ID":N,RESOLUTION:H,"VIDEO-RANGE":G}=_,D=`${`${N||"."}-`}${f.bitrate}-${H}-${M}-${O}-${G}-${k}`;if(r[D])if(r[D].uri!==f.url&&!f.attrs["PATHWAY-ID"]){const K=o[D]+=1;f.attrs["PATHWAY-ID"]=new Array(K+1).join(".");const ae=new us(f);r[D]=ae,n.push(ae)}else r[D].addGroupId("audio",_.AUDIO),r[D].addGroupId("text",_.SUBTITLES);else{const K=new us(f);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:b,videoRange:w,width:L,height:A})=>(!!b||!!(L&&A))&&p_(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 b=new Error("no level with compatible codecs found in manifest");this.hls.trigger(I.ERROR,{type:ke.MEDIA_ERROR,details:te.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:b,reason:b.message})}});return}if(t.audioTracks){const{preferManagedMediaSource:b}=this.hls.config;o=t.audioTracks.filter(w=>!w.audioCodec||el(w.audioCodec,"audio",b)),vd(o)}t.subtitles&&(u=t.subtitles,vd(u));const p=h.slice(0);h.sort((b,w)=>{if(b.attrs["HDCP-LEVEL"]!==w.attrs["HDCP-LEVEL"])return(b.attrs["HDCP-LEVEL"]||"")>(w.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&b.height!==w.height)return b.height-w.height;if(b.frameRate!==w.frameRate)return b.frameRate-w.frameRate;if(b.videoRange!==w.videoRange)return ya.indexOf(b.videoRange)-ya.indexOf(w.videoRange);if(b.videoCodec!==w.videoCodec){const L=wh(b.videoCodec),A=wh(w.videoCodec);if(L!==A)return A-L}if(b.uri===w.uri&&b.codecSet!==w.codecSet){const L=ga(b.codecSet),A=ga(w.codecSet);if(L!==A)return A-L}return b.averageBitrate!==w.averageBitrate?b.averageBitrate-w.averageBitrate:0});let f=p[0];if(this.steering&&(h=this.steering.filterParsedLevels(h),h.length!==p.length)){for(let b=0;b<p.length;b++)if(p[b].pathwayId===h[0].pathwayId){f=p[b];break}}this._levels=h;for(let b=0;b<h.length;b++)if(h[b]===f){var m;this._firstLevel=b;const w=f.bitrate,L=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${h.length} level(s) found, first bitrate: ${w}`),((m=this.hls.userConfig)==null?void 0:m.abrEwmaDefaultEstimate)===void 0){const A=Math.min(w,this.hls.config.abrEwmaDefaultEstimateMax);A>L&&L===tg.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=A)}break}const T=r&&!n,_={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(b=>!!b.url)};this.hls.trigger(I.MANIFEST_PARSED,_),(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 f=new Error("invalid level idx"),m=e<0;if(this.hls.trigger(I.ERROR,{type:ke.OTHER_ERROR,details:te.LEVEL_SWITCH_ERROR,level:e,fatal:m,error:f,reason:f.message}),m)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 f=this.switchParams(o.uri,n?.details,p);this.loadPlaylist(f)}}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===He.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===Le.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));yp(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 vd(s){const e={};s.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}class mS{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 Di({type:ke.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,f={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},m={onSuccess:(T,_,b,w)=>{const{frag:L,keyInfo:A,url:P}=b;if(!L.decryptdata||A!==this.keyUriToKeyInfo[P])return u(this.createKeyLoadError(L,te.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),w));A.decryptdata.key=L.decryptdata.key=new Uint8Array(T.data),L.keyLoader=null,A.loader=null,o({frag:L,keyInfo:A})},onError:(T,_,b,w)=>{this.resetLoader(_),u(this.createKeyLoadError(t,te.KEY_LOAD_ERROR,new Error(`HTTP Error ${T.code} loading key ${T.text}`),b,gt({url:h.url,data:void 0},T)))},onTimeout:(T,_,b)=>{this.resetLoader(_),u(this.createKeyLoadError(t,te.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),b))},onAbort:(T,_,b)=>{this.resetLoader(_),u(this.createKeyLoadError(t,te.INTERNAL_ABORTED,new Error("key loading aborted"),b))}};r.load(h,f,m)})}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 ig(){return self.SourceBuffer||self.WebKitSourceBuffer}function ng(){if(!In())return!1;const e=ig();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function yS(){if(!ng())return!1;const s=In();return typeof s?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(Us(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(Us(e,"audio"))))}function vS(){var s;const e=ig();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}const TS=250,ra=2,_S=.1,ES=.05;class bS{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 L=self.performance.now()-r;W.warn(`playback not stuck anymore @${o}, after ${Math.round(L)}ms`),this.stallReported=!1}this.stalled=null}return}if(p||h){this.stalled=null;return}if(n.paused&&!u||n.ended||n.playbackRate===0||!Ze.getBuffered(n).length){this.nudgeRetry=0;return}const f=Ze.bufferInfo(n,o,0),m=f.nextStart||0;if(u){const L=f.len>ra,A=!m||t&&t.start<=o||m-o>ra&&!this.fragmentTracker.getPartialFragment(o);if(L||A)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var T;if(!(f.len>0)&&!m)return;const A=Math.max(m,f.start||0)-o,P=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,M=(P==null||(T=P.details)==null?void 0:T.live)?P.details.targetduration*2:ra,k=this.fragmentTracker.getPartialFragment(o);if(A>0&&(A<=M||k)){n.paused||this._trySkipBufferHole(k);return}}const _=self.performance.now();if(r===null){this.stalled=_;return}const b=_-r;if(!u&&b>=TS&&(this._reportStall(f),!this.media))return;const w=Ze.bufferInfo(n,o,i.maxBufferHole);this._tryFixBufferStall(w,b)}_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:ke.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=Ze.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,f=u-r;if(f>0&&(h||p)){if(f>t.maxBufferHole){const{fragmentTracker:T}=this;let _=!1;if(r===0){const b=T.getAppendedFrag(0,Le.MAIN);b&&u<b.end&&(_=!0)}if(!_){const b=e||T.getAppendedFrag(r,Le.MAIN);if(b){let w=!1,L=b.end;for(;L<u;){const A=T.getPartialFragment(L);if(A)L+=A.duration;else{w=!0;break}}if(w)return 0}}}const m=Math.max(u+ES,r+_S);if(W.warn(`skipping hole, adjusting currentTime from ${r} to ${m}`),this.moved=!0,this.stalled=null,n.currentTime=m,e&&!e.gap){const T=new Error(`fragment loaded with buffer holes, seeking from ${r} to ${m}`);i.trigger(I.ERROR,{type:ke.MEDIA_ERROR,details:te.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:T,reason:T.message,frag:e})}return m}}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:ke.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:ke.MEDIA_ERROR,details:te.BUFFER_STALLED_ERROR,error:o,fatal:!0})}}}const SS=100;class CS extends Iu{constructor(e,t,i){super(e,t,i,"[stream-controller]",Le.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(SS),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=ce.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=ce.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case ce.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=ce.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=ce.IDLE;break}break}case ce.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=ce.IDLE}}break}this.state===ce.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=ce.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===ce.WAITING_LEVEL||p.live&&this.levelLastLoaded!==o){this.level=r,this.state=ce.WAITING_LEVEL;return}const f=u.len,m=this.getMaxBufferLength(o.maxBitrate);if(f>=m)return;this.backtrackFragment&&this.backtrackFragment.start>u.end&&(this.backtrackFragment=null);const T=this.backtrackFragment?this.backtrackFragment.start:u.end;let _=this.getNextFragment(T,p);if(this.couldBacktrack&&!this.fragPrevious&&_&&_.sn!=="initSegment"&&this.fragmentTracker.getState(_)!==pt.OK){var b;const L=((b=this.backtrackFragment)!=null?b:_).sn-p.startSN,A=p.fragments[L-1];A&&_.cc===A.cc&&(_=A,this.fragmentTracker.removeFragment(A))}else this.backtrackFragment&&u.len&&(this.backtrackFragment=null);if(_&&this.isLoopLoading(_,T)){if(!_.gap){const L=this.audioOnly&&!this.altAudio?qe.AUDIO:qe.VIDEO,A=(L===qe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;A&&this.afterBufferFlushed(A,L,Le.MAIN)}_=this.getNextFragmentLoopLoading(_,p,u,Le.MAIN,m)}_&&(_.initSegment&&!_.initSegment.data&&!this.bitrateTest&&(_=_.initSegment),this.loadFragment(_,o,T))}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);this.fragCurrent=e,n===pt.NOT_LOADED||n===pt.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,Le.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,f=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(f,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 ce.KEY_LOADING:case ce.FRAG_LOADING:case ce.FRAG_LOADING_WAITING_RETRY:case ce.PARSING:case ce.PARSED:this.state=ce.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 bS(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;Ee(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&&!vS(),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!==ce.IDLE)return;const n=i[t.level];(!n.details||n.details.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(n.details))&&(this.state=ce.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===ce.FRAG_LOADING||this.state===ce.FRAG_LOADING_WAITING_RETRY)&&p.level!==t.level&&p.loader&&this.abortCurrentFrag();let f=0;if(o.live||(i=h.details)!=null&&i.live){var m;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;f=this.alignPlaylists(o,h.details,(m=this.levelLastLoaded)==null?void 0:m.details)}if(h.details=o,this.levelLastLoaded=h,this.hls.trigger(I.LEVEL_UPDATED,{details:o,level:r}),this.state===ce.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=ce.IDLE}this.startFragRequested?o.live&&this.synchronizeToLiveEdge(o):this.setStartPosition(o,f),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,f=h.PTSKnown||!h.live,m=(t=i.initSegment)==null?void 0:t.data,T=this._getAudioCodec(u),_=this.transmuxer=this.transmuxer||new Np(this.hls,Le.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),b=n?n.index:-1,w=b!==-1,L=new Au(i.level,i.sn,i.stats.chunkCount,r.byteLength,b,w),A=this.initPTS[i.cc];_.push(r,m,T,p,i,n,h.totalduration,f,L,A)}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!==Le.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===ce.PARSED&&(this.state=ce.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=ce.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(Le.MAIN,t);break;case te.LEVEL_LOAD_ERROR:case te.LEVEL_LOAD_TIMEOUT:case te.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===ce.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===He.LEVEL&&(this.state=ce.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||!Ze.getBuffered(e).length){const i=this.state!==ce.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,i)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=ce.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==qe.AUDIO||this.audioOnly&&!this.altAudio){const i=(t===qe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,t,Le.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=Ze.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=ce.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:f}=u,{video:m,text:T,id3:_,initSegment:b}=r,{details:w}=f,L=this.altAudio?void 0:r.audio;if(this.fragContextChanged(h)){this.fragmentTracker.removeFragment(h);return}if(this.state=ce.PARSING,b){if(b!=null&&b.tracks){const O=h.initSegment||h;this._bufferInitSegment(f,b.tracks,O,o),n.trigger(I.FRAG_PARSING_INIT_SEGMENT,{frag:O,id:i,tracks:b.tracks})}const A=b.initPTS,P=b.timescale;Ee(A)&&(this.initPTS[h.cc]={baseTime:A,timescale:P},n.trigger(I.INIT_PTS_FOUND,{frag:h,id:i,initPTS:A,timescale:P}))}if(m&&w&&h.sn!=="initSegment"){const A=w.fragments[h.sn-1-w.startSN],P=h.sn===w.startSN,O=!A||h.cc>A.cc;if(r.independent!==!1){const{startPTS:M,endPTS:k,startDTS:N,endDTS:H}=m;if(p)p.elementaryStreams[m.type]={startPTS:M,endPTS:k,startDTS:N,endDTS:H};else if(m.firstKeyFrame&&m.independent&&o.id===1&&!O&&(this.couldBacktrack=!0),m.dropped&&m.independent){const G=this.getMainFwdBufferInfo(),B=(G?G.end:this.getLoadPosition())+this.config.maxBufferHole,D=m.firstKeyFramePTS?m.firstKeyFramePTS:M;if(!P&&B<D-this.config.maxBufferHole&&!O){this.backtrack(h);return}else O&&(h.gap=!0);h.setElementaryStreamInfo(m.type,h.start,k,h.start,H,!0)}else P&&M>ra&&(h.gap=!0);h.setElementaryStreamInfo(m.type,M,k,N,H),this.backtrackFragment&&(this.backtrackFragment=h),this.bufferFragmentData(m,h,p,o,P||O)}else if(P||O)h.gap=!0;else{this.backtrack(h);return}}if(L){const{startPTS:A,endPTS:P,startDTS:O,endDTS:M}=L;p&&(p.elementaryStreams[qe.AUDIO]={startPTS:A,endPTS:P,startDTS:O,endDTS:M}),h.setElementaryStreamInfo(qe.AUDIO,A,P,O,M),this.bufferFragmentData(L,h,p,o)}if(w&&_!=null&&(t=_.samples)!=null&&t.length){const A={id:i,frag:h,details:w,samples:_.samples};n.trigger(I.FRAG_PARSING_METADATA,A)}if(w&&T){const A={id:i,frag:h,details:w,samples:T.samples};n.trigger(I.FRAG_PARSING_USERDATA,A)}}_bufferInitSegment(e,t,i,n){if(this.state!==ce.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 f=r.metadata;f&&"channelCount"in f&&(f.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 f=t[h].initSegment;f!=null&&f.byteLength&&this.hls.trigger(I.BUFFER_APPENDING,{type:h,data:f,frag:i,part:null,chunkMeta:n,parent:i.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,Le.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=ce.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(Ze.isBuffered(e,i)?t=this.getAppendedFrag(i):Ze.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&&Ee(t)&&Ee(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 We{static get version(){return"1.5.20"}static isMSESupported(){return ng()}static isSupported(){return yS()}static getMediaSource(){return In()}static get Events(){return I}static get ErrorTypes(){return ke}static get ErrorDetails(){return te}static get DefaultConfig(){return We.defaultConfig?We.defaultConfig:tg}static set DefaultConfig(e){We.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 Mu,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,dT(e.debug||!1,"Hls instance");const t=this.config=fS(We.DefaultConfig,e);this.userConfig=e,t.progressive&&pS(t);const{abrController:i,bufferController:n,capLevelController:r,errorController:o,fpsController:u}=t,h=new o(this),p=this.abrController=new i(this),f=this.bufferController=new n(this),m=this.capLevelController=new r(this),T=new u(this),_=new a_(this),b=new h_(this),w=t.contentSteeringController,L=w?new w(this):null,A=this.levelController=new gS(this,L),P=new H_(this),O=new mS(this.config),M=this.streamController=new CS(this,P,O);m.setStreamController(M),T.setStreamController(M);const k=[_,A,M];L&&k.splice(1,0,L),this.networkControllers=k;const N=[p,f,m,T,b,P];this.audioTrackController=this.createController(t.audioTrackController,k);const H=t.audioStreamController;H&&k.push(new H(this,P,O)),this.subtitleTrackController=this.createController(t.subtitleTrackController,k);const G=t.subtitleStreamController;G&&k.push(new G(this,P,O)),this.createController(t.timelineController,N),O.emeController=this.emeController=this.createController(t.emeController,N),this.cmcdController=this.createController(t.cmcdController,N),this.latencyController=this.createController(d_,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:ke.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=Eu.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){f_(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}}We.defaultConfig=void 0;function sg(s,e){return e?`${s}|${e.start}-${e.end}`:s}function rg(s,e){if(s!==void 0&&e!==void 0&&s<=e)return{start:s,end:e}}const Td=globalThis||void 0||self;var wS=Object.defineProperty,LS=(s,e,t)=>e in s?wS(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,se=(s,e,t)=>LS(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 Ca extends Error{constructor(e){super(),this.type=e}}class AS{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;const{segment:i}=this.request;try{let n=await((t=(e=this.httpConfig).httpRequestSetup)==null?void 0:t.call(e,i.url,i.byteRange,this.abortController.signal,this.requestByteRange));if(!n){const h=new Headers(this.requestByteRange?{Range:`bytes=${this.requestByteRange.start}-${this.requestByteRange.end??""}`}:void 0);n=new Request(i.url,{headers:h,signal:this.abortController.signal})}if(this.abortController.signal.aborted)throw new DOMException("Request aborted before request fetch","AbortError");const r=await window.fetch(n);if(this.handleResponseHeaders(r),!r.body)return;const{requestControls:o}=this;o.firstBytesReceived();const u=r.body.getReader();for await(const h of kS(u))this.requestControls.addLoadedChunk(h),this.onChunkDownloaded(h.byteLength,"http");o.completeOnSuccess()}catch(n){this.handleError(n)}}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?RS(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*kS(s){for(;;){const{done:e,value:t}=await s.read();if(e)break;yield t}}const IS=/^bytes (?:(?:(\d+)|)-(?:(\d+)|)|\*)\/(?:(\d+)|\*)$/;function RS(s){const e=IS.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 PS(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var ag={exports:{}},ot=ag.exports={},di,fi;function iu(){throw new Error("setTimeout has not been defined")}function nu(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?di=setTimeout:di=iu}catch{di=iu}try{typeof clearTimeout=="function"?fi=clearTimeout:fi=nu}catch{fi=nu}})();function og(s){if(di===setTimeout)return setTimeout(s,0);if((di===iu||!di)&&setTimeout)return di=setTimeout,setTimeout(s,0);try{return di(s,0)}catch{try{return di.call(null,s,0)}catch{return di.call(this,s,0)}}}function DS(s){if(fi===clearTimeout)return clearTimeout(s);if((fi===nu||!fi)&&clearTimeout)return fi=clearTimeout,clearTimeout(s);try{return fi(s)}catch{try{return fi.call(null,s)}catch{return fi.call(this,s)}}}var Oi=[],as=!1,Ln,aa=-1;function xS(){!as||!Ln||(as=!1,Ln.length?Oi=Ln.concat(Oi):aa=-1,Oi.length&&lg())}function lg(){if(!as){var s=og(xS);as=!0;for(var e=Oi.length;e;){for(Ln=Oi,Oi=[];++aa<e;)Ln&&Ln[aa].run();aa=-1,e=Oi.length}Ln=null,as=!1,DS(s)}}ot.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];Oi.push(new ug(s,e)),Oi.length===1&&!as&&og(lg)};function ug(s,e){this.fun=s,this.array=e}ug.prototype.run=function(){this.fun.apply(null,this.array)};ot.title="browser";ot.browser=!0;ot.env={};ot.argv=[];ot.version="";ot.versions={};function Ui(){}ot.on=Ui;ot.addListener=Ui;ot.once=Ui;ot.off=Ui;ot.removeListener=Ui;ot.removeAllListeners=Ui;ot.emit=Ui;ot.prependListener=Ui;ot.prependOnceListener=Ui;ot.listeners=function(s){return[]};ot.binding=function(s){throw new Error("process.binding is not supported")};ot.cwd=function(){return"/"};ot.chdir=function(s){throw new Error("process.chdir is not supported")};ot.umask=function(){return 0};var MS=ag.exports;const oa=PS(MS);var OS=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof Td<"u"?Td:typeof self<"u"?self:{};function Dn(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Hr={exports:{}},ml,_d;function FS(){if(_d)return ml;_d=1;var s=1e3,e=s*60,t=e*60,i=t*24,n=i*7,r=i*365.25;ml=function(f,m){m=m||{};var T=typeof f;if(T==="string"&&f.length>0)return o(f);if(T==="number"&&isFinite(f))return m.long?h(f):u(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))};function o(f){if(f=String(f),!(f.length>100)){var m=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(f);if(m){var T=parseFloat(m[1]),_=(m[2]||"ms").toLowerCase();switch(_){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(f){var m=Math.abs(f);return m>=i?Math.round(f/i)+"d":m>=t?Math.round(f/t)+"h":m>=e?Math.round(f/e)+"m":m>=s?Math.round(f/s)+"s":f+"ms"}function h(f){var m=Math.abs(f);return m>=i?p(f,m,i,"day"):m>=t?p(f,m,t,"hour"):m>=e?p(f,m,e,"minute"):m>=s?p(f,m,s,"second"):f+" ms"}function p(f,m,T,_){var b=m>=T*1.5;return Math.round(f/T)+" "+_+(b?"s":"")}return ml}var yl,Ed;function NS(){if(Ed)return yl;Ed=1;function s(e){i.debug=i,i.default=i,i.coerce=p,i.disable=u,i.enable=r,i.enabled=h,i.humanize=FS(),i.destroy=f,Object.keys(e).forEach(m=>{i[m]=e[m]}),i.names=[],i.skips=[],i.formatters={};function t(m){let T=0;for(let _=0;_<m.length;_++)T=(T<<5)-T+m.charCodeAt(_),T|=0;return i.colors[Math.abs(T)%i.colors.length]}i.selectColor=t;function i(m){let T,_=null,b,w;function L(...A){if(!L.enabled)return;const P=L,O=Number(new Date),M=O-(T||O);P.diff=M,P.prev=T,P.curr=O,T=O,A[0]=i.coerce(A[0]),typeof A[0]!="string"&&A.unshift("%O");let k=0;A[0]=A[0].replace(/%([a-zA-Z%])/g,(H,G)=>{if(H==="%%")return"%";k++;const B=i.formatters[G];if(typeof B=="function"){const D=A[k];H=B.call(P,D),A.splice(k,1),k--}return H}),i.formatArgs.call(P,A),(P.log||i.log).apply(P,A)}return L.namespace=m,L.useColors=i.useColors(),L.color=i.selectColor(m),L.extend=n,L.destroy=i.destroy,Object.defineProperty(L,"enabled",{enumerable:!0,configurable:!1,get:()=>_!==null?_:(b!==i.namespaces&&(b=i.namespaces,w=i.enabled(m)),w),set:A=>{_=A}}),typeof i.init=="function"&&i.init(L),L}function n(m,T){const _=i(this.namespace+(typeof T>"u"?":":T)+m);return _.log=this.log,_}function r(m){i.save(m),i.namespaces=m,i.names=[],i.skips=[];const T=(typeof m=="string"?m:"").trim().replace(" ",",").split(",").filter(Boolean);for(const _ of T)_[0]==="-"?i.skips.push(_.slice(1)):i.names.push(_)}function o(m,T){let _=0,b=0,w=-1,L=0;for(;_<m.length;)if(b<T.length&&(T[b]===m[_]||T[b]==="*"))T[b]==="*"?(w=b,L=_,b++):(_++,b++);else if(w!==-1)b=w+1,L++,_=L;else return!1;for(;b<T.length&&T[b]==="*";)b++;return b===T.length}function u(){const m=[...i.names,...i.skips.map(T=>"-"+T)].join(",");return i.enable(""),m}function h(m){for(const T of i.skips)if(o(m,T))return!1;for(const T of i.names)if(o(m,T))return!0;return!1}function p(m){return m instanceof Error?m.stack||m.message:m}function f(){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 yl=s,yl}var bd;function BS(){return bd||(bd=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 f=0,m=0;h[0].replace(/%[a-zA-Z%]/g,T=>{T!=="%%"&&(f++,T==="%c"&&(m=f))}),h.splice(m,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 oa<"u"&&"env"in oa&&(h=oa.env.DEBUG),h}function o(){try{return localStorage}catch{}}s.exports=NS()(e);const{formatters:u}=s.exports;u.j=function(h){try{return JSON.stringify(h)}catch(p){return"[UnexpectedJSONParseError]: "+p.message}}}(Hr,Hr.exports)),Hr.exports}var cg=BS();const bi=Dn(cg);var $r={exports:{}},Sd;function hg(){if(Sd)return $r.exports;Sd=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(M){console&&console.warn&&console.warn(M)}var n=Number.isNaN||function(k){return k!==k};function r(){r.init.call(this)}$r.exports=r,$r.exports.once=A,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var o=10;function u(M){if(typeof M!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof M)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(M){if(typeof M!="number"||M<0||n(M))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+M+".");o=M}}),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(M){return M._maxListeners===void 0?r.defaultMaxListeners:M._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 ae=B[k];if(ae===void 0)return!1;if(typeof ae=="function")e(ae,this,N);else for(var Z=ae.length,oe=b(ae,Z),H=0;H<Z;++H)e(oe[H],this,N);return!0};function p(M,k,N,H){var G,B,D;if(u(N),B=M._events,B===void 0?(B=M._events=Object.create(null),M._eventsCount=0):(B.newListener!==void 0&&(M.emit("newListener",k,N.listener?N.listener:N),B=M._events),D=B[k]),D===void 0)D=B[k]=N,++M._eventsCount;else if(typeof D=="function"?D=B[k]=H?[N,D]:[D,N]:H?D.unshift(N):D.push(N),G=h(M),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=M,K.type=k,K.count=D.length,i(K)}return M}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 f(){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 m(M,k,N){var H={fired:!1,wrapFn:void 0,target:M,type:k,listener:N},G=f.bind(H);return G.listener=N,H.wrapFn=G,G}r.prototype.once=function(k,N){return u(N),this.on(k,m(this,k,N)),this},r.prototype.prependOnceListener=function(k,N){return u(N),this.prependListener(k,m(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(M,k,N){var H=M._events;if(H===void 0)return[];var G=H[k];return G===void 0?[]:typeof G=="function"?N?[G.listener||G]:[G]:N?L(G):b(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(M,k){return typeof M.listenerCount=="function"?M.listenerCount(k):_.call(M,k)},r.prototype.listenerCount=_;function _(M){var k=this._events;if(k!==void 0){var N=k[M];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 b(M,k){for(var N=new Array(k),H=0;H<k;++H)N[H]=M[H];return N}function w(M,k){for(;k+1<M.length;k++)M[k]=M[k+1];M.pop()}function L(M){for(var k=new Array(M.length),N=0;N<k.length;++N)k[N]=M[N].listener||M[N];return k}function A(M,k){return new Promise(function(N,H){function G(D){M.removeListener(k,B),H(D)}function B(){typeof M.removeListener=="function"&&M.removeListener("error",G),N([].slice.call(arguments))}O(M,k,B,{once:!0}),k!=="error"&&P(M,G,{once:!0})})}function P(M,k,N){typeof M.on=="function"&&O(M,"error",k,N)}function O(M,k,N,H){if(typeof M.on=="function")H.once?M.once(k,N):M.on(k,N);else if(typeof M.addEventListener=="function")M.addEventListener(k,function G(B){H.once&&M.removeEventListener(k,G),N(B)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof M)}return $r.exports}var US=hg();const dg=Dn(US);var jr={exports:{}},vl,Cd;function HS(){if(Cd)return vl;Cd=1,vl=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 vl}var wd;function $S(){if(wd)return jr.exports;wd=1;var s=HS();jr.exports=s(e),jr.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 jr.exports}var jS=$S();const VS=Dn(jS);/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var Tl,Ld;function fg(){if(Ld)return Tl;Ld=1;let s;return Tl=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:OS):e=>(s||(s=Promise.resolve())).then(e).catch(t=>setTimeout(()=>{throw t},0)),Tl}/*! run-parallel. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var _l,Ad;function GS(){if(Ad)return _l;Ad=1,_l=e;const s=fg();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(f){function m(){i&&i(f,n),i=null}u?s(m):m()}function p(f,m,T){n[f]=T,(--r===0||m)&&h(m)}r?o?o.forEach(function(f){t[f](function(m,T){p(f,m,T)})}):t.forEach(function(f,m){f(function(T,_){p(m,T,_)})}):h(null),u=!1}return _l}var KS=GS();const qS=Dn(KS),Ni=typeof window<"u"?window:self,su=Ni.RTCPeerConnection||Ni.mozRTCPeerConnection||Ni.webkitRTCPeerConnection,WS=Ni.RTCSessionDescription||Ni.mozRTCSessionDescription||Ni.webkitRTCSessionDescription,zS=Ni.RTCIceCandidate||Ni.mozRTCIceCandidate||Ni.webkitRTCIceCandidate;var El,kd;function YS(){return kd||(kd=1,El=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}}),El}var bl,Id;function XS(){if(Id)return bl;Id=1;const s=YS();return bl=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}},bl}var Sl,Rd;function Pd(){return Rd||(Rd=1,Sl=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))}}),Sl}var Cl,Dd;function QS(){if(Dd)return Cl;Dd=1;const s=Pd(),e=Pd();Cl=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 Cl}var wl,xd;function JS(){if(xd)return wl;xd=1;const{EventEmitter:s}=hg(),e=new Error("Stream was destroyed"),t=new Error("Premature close"),i=XS(),n=QS(),r=(1<<29)-1,o=1,u=2,h=4,p=8,f=r^o,m=r^u,T=16,_=32,b=64,w=128,L=256,A=512,P=1024,O=2048,M=4096,k=8192,N=16384,H=32768,G=65536,B=131072,D=L|A,K=T|G,ae=b|T,Z=M|w,oe=L|B,le=r^T,he=r^b,pe=r^(b|G),ge=r^G,ee=r^L,Q=r^(w|k),ye=r^P,re=r^D,ie=r^H,be=r^_,Te=r^B,xe=r^oe,Me=1<<18,Pe=2<<18,je=4<<18,it=8<<18,et=16<<18,$e=32<<18,Si=64<<18,ii=128<<18,Ci=256<<18,_t=512<<18,lt=1024<<18,ln=r^(Me|Ci),un=r^je,Hi=r^(Me|_t),wi=r^et,Mt=r^it,$i=r^ii,Ot=r^Pe,mt=r^lt,Ft=T|Me,qt=r^Ft,Et=N|$e,bt=h|p|u,R=bt|o,E=bt|Et,C=un&he,$=ii|H,q=$&qt,J=R|q,ne=R|P|N,Ie=R|N|w,ze=R|P|w,Ge=R|M|w|k,Ce=R|T|P|N|G|B,Oe=bt|P|N,fs=_|R|H|b,Li=H|o,Wt=R|_t|$e,cn=it|et,ps=it|Me,Ks=it|et|R|Me,Nt=R|Me|it|lt,qs=je|Me,ji=Me|Ci,xn=R|_t|ps|$e,Ws=et|bt|_t|$e,zs=Pe|R|ii|je,Vi=_t|$e|bt,ni=Symbol.asyncIterator||Symbol("asyncIterator");class hn{constructor(F,{highWaterMark:fe=16384,map:Ae=null,mapWritable:Re,byteLength:Qe,byteLengthWritable:Ke}={}){this.stream=F,this.queue=new i,this.highWaterMark=fe,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=Ke||Qe||ar,this.map=Re||Ae,this.afterWrite=si.bind(this),this.afterUpdateNextTick=er.bind(this)}get ended(){return(this.stream._duplexState&$e)!==0}push(F){return this.stream._duplexState&Vi?!1:(this.map!==null&&(F=this.map(F)),this.buffered+=this.byteLength(F),this.queue.push(F),this.buffered<this.highWaterMark?(this.stream._duplexState|=it,!0):(this.stream._duplexState|=cn,!1))}shift(){const F=this.queue.shift();return this.buffered-=this.byteLength(F),this.buffered===0&&(this.stream._duplexState&=Mt),F}end(F){typeof F=="function"?this.stream.once("finish",F):F!=null&&this.push(F),this.stream._duplexState=(this.stream._duplexState|_t)&un}autoBatch(F,fe){const Ae=[],Re=this.stream;for(Ae.push(F);(Re._duplexState&Nt)===ps;)Ae.push(Re._writableState.shift());if(Re._duplexState&R)return fe(null);Re._writev(Ae,fe)}update(){const F=this.stream;F._duplexState|=Pe;do{for(;(F._duplexState&Nt)===it;){const fe=this.shift();F._duplexState|=ji,F._write(fe,this.afterWrite)}F._duplexState&qs||this.updateNonPrimary()}while(this.continueUpdate()===!0);F._duplexState&=Ot}updateNonPrimary(){const F=this.stream;if((F._duplexState&xn)===_t){F._duplexState=F._duplexState|Me,F._final(Qs.bind(this));return}if((F._duplexState&bt)===h){F._duplexState&$||(F._duplexState|=Ft,F._destroy(Gi.bind(this)));return}(F._duplexState&J)===o&&(F._duplexState=(F._duplexState|Ft)&f,F._open(tr.bind(this)))}continueUpdate(){return this.stream._duplexState&ii?(this.stream._duplexState&=$i,!0):!1}updateCallback(){(this.stream._duplexState&zs)===je?this.update():this.updateNextTick()}updateNextTick(){this.stream._duplexState&ii||(this.stream._duplexState|=ii,this.stream._duplexState&Pe||queueMicrotask(this.afterUpdateNextTick))}}class Ys{constructor(F,{highWaterMark:fe=16384,map:Ae=null,mapReadable:Re,byteLength:Qe,byteLengthReadable:Ke}={}){this.stream=F,this.queue=new i,this.highWaterMark=fe===0?1:fe,this.buffered=0,this.readAhead=fe>0,this.error=null,this.pipeline=null,this.byteLength=Ke||Qe||ar,this.map=Re||Ae,this.pipeTo=null,this.afterRead=Js.bind(this),this.afterUpdateNextTick=Zs.bind(this)}get ended(){return(this.stream._duplexState&N)!==0}pipe(F,fe){if(this.pipeTo!==null)throw new Error("Can only pipe to one destination");if(typeof fe!="function"&&(fe=null),this.stream._duplexState|=A,this.pipeTo=F,this.pipeline=new Xs(this.stream,F,fe),fe&&this.stream.on("error",It),fn(F))F._writableState.pipeline=this.pipeline,fe&&F.on("error",It),F.on("finish",this.pipeline.finished.bind(this.pipeline));else{const Ae=this.pipeline.done.bind(this.pipeline,F),Re=this.pipeline.done.bind(this.pipeline,F,null);F.on("error",Ae),F.on("close",Re),F.on("finish",this.pipeline.finished.bind(this.pipeline))}F.on("drain",ms.bind(this)),this.stream.emit("piping",F),F.emit("pipe",this.stream)}push(F){const fe=this.stream;return F===null?(this.highWaterMark=0,fe._duplexState=(fe._duplexState|P)&pe,!1):this.map!==null&&(F=this.map(F),F===null)?(fe._duplexState&=ge,this.buffered<this.highWaterMark):(this.buffered+=this.byteLength(F),this.queue.push(F),fe._duplexState=(fe._duplexState|w)&ge,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 fe=[this.map!==null?this.map(F):F];for(;this.buffered>0;)fe.push(this.shift());for(let Ae=0;Ae<fe.length-1;Ae++){const Re=fe[Ae];this.buffered+=this.byteLength(Re),this.queue.push(Re)}this.push(fe[fe.length-1])}read(){const F=this.stream;if((F._duplexState&Ie)===w){const fe=this.shift();return this.pipeTo!==null&&this.pipeTo.write(fe)===!1&&(F._duplexState&=re),F._duplexState&O&&F.emit("data",fe),fe}return this.readAhead===!1&&(F._duplexState|=B,this.updateNextTick()),null}drain(){const F=this.stream;for(;(F._duplexState&Ie)===w&&F._duplexState&D;){const fe=this.shift();this.pipeTo!==null&&this.pipeTo.write(fe)===!1&&(F._duplexState&=re),F._duplexState&O&&F.emit("data",fe)}}update(){const F=this.stream;F._duplexState|=_;do{for(this.drain();this.buffered<this.highWaterMark&&(F._duplexState&Ce)===B;)F._duplexState|=K,F._read(this.afterRead),this.drain();(F._duplexState&Ge)===Z&&(F._duplexState|=k,F.emit("readable")),F._duplexState&ae||this.updateNonPrimary()}while(this.continueUpdate()===!0);F._duplexState&=be}updateNonPrimary(){const F=this.stream;if((F._duplexState&ze)===P&&(F._duplexState=(F._duplexState|N)&ye,F.emit("end"),(F._duplexState&E)===Et&&(F._duplexState|=h),this.pipeTo!==null&&this.pipeTo.end()),(F._duplexState&bt)===h){F._duplexState&$||(F._duplexState|=Ft,F._destroy(Gi.bind(this)));return}(F._duplexState&J)===o&&(F._duplexState=(F._duplexState|Ft)&f,F._open(tr.bind(this)))}continueUpdate(){return this.stream._duplexState&H?(this.stream._duplexState&=ie,!0):!1}updateCallback(){(this.stream._duplexState&fs)===b?this.update():this.updateNextTick()}updateNextTickIfOpen(){this.stream._duplexState&Li||(this.stream._duplexState|=H,this.stream._duplexState&_||queueMicrotask(this.afterUpdateNextTick))}updateNextTick(){this.stream._duplexState&H||(this.stream._duplexState|=H,this.stream._duplexState&_||queueMicrotask(this.afterUpdateNextTick))}}class gs{constructor(F){this.data=null,this.afterTransform=vs.bind(F),this.afterFinal=null}}class Xs{constructor(F,fe,Ae){this.from=F,this.to=fe,this.afterPipe=Ae,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(F,fe){if(fe&&(this.error=fe),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 ms(){this.stream._duplexState|=A,this.updateCallback()}function Qs(me){const F=this.stream;me&&F.destroy(me),F._duplexState&bt||(F._duplexState|=$e,F.emit("finish")),(F._duplexState&E)===Et&&(F._duplexState|=h),F._duplexState&=Hi,F._duplexState&Pe?this.updateNextTick():this.update()}function Gi(me){const F=this.stream;!me&&this.error!==e&&(me=this.error),me&&F.emit("error",me),F._duplexState|=p,F.emit("close");const fe=F._readableState,Ae=F._writableState;if(fe!==null&&fe.pipeline!==null&&fe.pipeline.done(F,me),Ae!==null){for(;Ae.drains!==null&&Ae.drains.length>0;)Ae.drains.shift().resolve(!1);Ae.pipeline!==null&&Ae.pipeline.done(F,me)}}function si(me){const F=this.stream;me&&F.destroy(me),F._duplexState&=ln,this.drains!==null&&ys(this.drains),(F._duplexState&Ks)===et&&(F._duplexState&=wi,(F._duplexState&Si)===Si&&F.emit("drain")),this.updateCallback()}function Js(me){me&&this.stream.destroy(me),this.stream._duplexState&=le,this.readAhead===!1&&!(this.stream._duplexState&L)&&(this.stream._duplexState&=Te),this.updateCallback()}function Zs(){this.stream._duplexState&_||(this.stream._duplexState&=ie,this.update())}function er(){this.stream._duplexState&Pe||(this.stream._duplexState&=$i,this.update())}function ys(me){for(let F=0;F<me.length;F++)--me[F].writes===0&&(me.shift().resolve(!0),F--)}function tr(me){const F=this.stream;me&&F.destroy(me),F._duplexState&h||(F._duplexState&ne||(F._duplexState|=b),F._duplexState&Wt||(F._duplexState|=je),F.emit("open")),F._duplexState&=qt,F._writableState!==null&&F._writableState.updateCallback(),F._readableState!==null&&F._readableState.updateCallback()}function vs(me,F){F!=null&&this.push(F),this._writableState.afterWrite(me)}function Ts(me){this._readableState!==null&&(me==="data"&&(this._duplexState|=O|oe,this._readableState.updateNextTick()),me==="readable"&&(this._duplexState|=M,this._readableState.updateNextTick())),this._writableState!==null&&me==="drain"&&(this._duplexState|=Si,this._writableState.updateNextTick())}class Mn 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",Ye.bind(this))),this.on("newListener",Ts)}_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&bt)!==0}destroy(F){this._duplexState&bt||(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&=m,this._readableState!==null&&this._readableState.updateNextTick(),this._writableState!==null&&this._writableState.updateNextTick())}}class Ki extends Mn{constructor(F){super(F),this._duplexState|=o|$e|B,this._readableState=new Ys(this,F),F&&(this._readableState.readAhead===!1&&(this._duplexState&=Te),F.read&&(this._read=F.read),F.eagerOpen&&this._readableState.updateNextTick(),F.encoding&&this.setEncoding(F.encoding))}setEncoding(F){const fe=new n(F),Ae=this._readableState.map||Fn;return this._readableState.map=Re,this;function Re(Qe){const Ke=fe.push(Qe);return Ke===""&&(Qe.byteLength!==0||fe.remaining>0)?null:Ae(Ke)}}_read(F){F(null)}pipe(F,fe){return this._readableState.updateNextTick(),this._readableState.pipe(F,fe),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|=oe,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=this._readableState.readAhead===!1?xe:ee,this}static _fromAsyncIterator(F,fe){let Ae;const Re=new Ki({...fe,read(Ke){F.next().then(Qe).then(Ke.bind(null,null)).catch(Ke)},predestroy(){Ae=F.return()},destroy(Ke){if(!Ae)return Ke(null);Ae.then(Ke.bind(null,null)).catch(Ke)}});return Re;function Qe(Ke){Ke.done?Re.push(null):Re.push(Ke.value)}}static from(F,fe){if(qi(F))return F;if(F[ni])return this._fromAsyncIterator(F[ni](),fe);Array.isArray(F)||(F=F===void 0?[]:[F]);let Ae=0;return new Ki({...fe,read(Re){this.push(Ae===F.length?null:F[Ae++]),Re(null)}})}static isBackpressured(F){return(F._duplexState&Oe)!==0||F._readableState.buffered>=F._readableState.highWaterMark}static isPaused(F){return(F._duplexState&L)===0}[ni](){const F=this;let fe=null,Ae=null,Re=null;return this.on("error",Be=>{fe=Be}),this.on("readable",Qe),this.on("close",Ke),{[ni](){return this},next(){return new Promise(function(Be,Rt){Ae=Be,Re=Rt;const St=F.read();St!==null?Yt(St):F._duplexState&p&&Yt(null)})},return(){return Wi(null)},throw(Be){return Wi(Be)}};function Qe(){Ae!==null&&Yt(F.read())}function Ke(){Ae!==null&&Yt(null)}function Yt(Be){Re!==null&&(fe?Re(fe):Be===null&&!(F._duplexState&N)?Re(e):Ae({value:Be,done:Be===null}),Re=Ae=null)}function Wi(Be){return F.destroy(Be),new Promise((Rt,St)=>{if(F._duplexState&p)return Rt({value:void 0,done:!0});F.once("close",function(){Be?St(Be):Rt({value:void 0,done:!0})})})}}}class ir extends Mn{constructor(F){super(F),this._duplexState|=o|N,this._writableState=new hn(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|=lt}uncork(){this._duplexState&=mt,this._writableState.updateNextTick()}_writev(F,fe){fe(null)}_write(F,fe){this._writableState.autoBatch(F,fe)}_final(F){F(null)}static isBackpressured(F){return(F._duplexState&Ws)!==0}static drained(F){if(F.destroyed)return Promise.resolve(!1);const fe=F._writableState,Re=(zt(F)?Math.min(1,fe.queue.length):fe.queue.length)+(F._duplexState&Ci?1:0);return Re===0?Promise.resolve(!0):(fe.drains===null&&(fe.drains=[]),new Promise(Qe=>{fe.drains.push({writes:Re,resolve:Qe})}))}write(F){return this._writableState.updateNextTick(),this._writableState.push(F)}end(F){return this._writableState.updateNextTick(),this._writableState.end(F),this}}class _s extends Ki{constructor(F){super(F),this._duplexState=o|this._duplexState&B,this._writableState=new hn(this,F),F&&(F.writev&&(this._writev=F.writev),F.write&&(this._write=F.write),F.final&&(this._final=F.final))}cork(){this._duplexState|=lt}uncork(){this._duplexState&=mt,this._writableState.updateNextTick()}_writev(F,fe){fe(null)}_write(F,fe){this._writableState.autoBatch(F,fe)}_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 Bt extends _s{constructor(F){super(F),this._transformState=new gs(this),F&&(F.transform&&(this._transform=F.transform),F.flush&&(this._flush=F.flush))}_write(F,fe){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=F:this._transform(F,this._transformState.afterTransform)}_read(F){if(this._transformState.data!==null){const fe=this._transformState.data;this._transformState.data=null,F(null),this._transform(fe,this._transformState.afterTransform)}else F(null)}destroy(F){super.destroy(F),this._transformState.data!==null&&(this._transformState.data=null,this._transformState.afterTransform())}_transform(F,fe){fe(null,F)}_flush(F){F(null)}_final(F){this._transformState.afterFinal=F,this._flush(yt.bind(this))}}class nr extends Bt{}function yt(me,F){const fe=this._transformState.afterFinal;if(me)return fe(me);F!=null&&this.push(F),this.push(null),fe(null)}function sr(...me){return new Promise((F,fe)=>On(...me,Ae=>{if(Ae)return fe(Ae);F()}))}function On(me,...F){const fe=Array.isArray(me)?[...me,...F]:[me,...F],Ae=fe.length&&typeof fe[fe.length-1]=="function"?fe.pop():null;if(fe.length<2)throw new Error("Pipeline requires at least 2 streams");let Re=fe[0],Qe=null,Ke=null;for(let Be=1;Be<fe.length;Be++)Qe=fe[Be],fn(Re)?Re.pipe(Qe,Wi):(Yt(Re,!0,Be>1,Wi),Re.pipe(Qe)),Re=Qe;if(Ae){let Be=!1;const Rt=fn(Qe)||!!(Qe._writableState&&Qe._writableState.autoDestroy);Qe.on("error",St=>{Ke===null&&(Ke=St)}),Qe.on("finish",()=>{Be=!0,Rt||Ae(Ke)}),Rt&&Qe.on("close",()=>Ae(Ke||(Be?null:t)))}return Qe;function Yt(Be,Rt,St,Es){Be.on("error",Es),Be.on("close",bs);function bs(){if(Be._readableState&&!Be._readableState.ended||St&&Be._writableState&&!Be._writableState.ended)return Es(t)}}function Wi(Be){if(!(!Be||Ke)){Ke=Be;for(const Rt of fe)Rt.destroy(Be)}}}function Fn(me){return me}function dn(me){return!!me._readableState||!!me._writableState}function fn(me){return typeof me._duplexState=="number"&&dn(me)}function Ba(me){return!!me._readableState&&me._readableState.ended}function Lt(me){return!!me._writableState&&me._writableState.ended}function dt(me,F={}){const fe=me._readableState&&me._readableState.error||me._writableState&&me._writableState.error;return!F.all&&fe===e?null:fe}function qi(me){return fn(me)&&me.readable}function Nn(me){return(me._duplexState&o)!==o||(me._duplexState&$)!==0}function rr(me){return typeof me=="object"&&me!==null&&typeof me.byteLength=="number"}function ar(me){return rr(me)?me.byteLength:1024}function It(){}function Ye(){this.destroy(new Error("Stream aborted."))}function zt(me){return me._writev!==ir.prototype._writev&&me._writev!==_s.prototype._writev}return wl={pipeline:On,pipelinePromise:sr,isStream:dn,isStreamx:fn,isEnded:Ba,isFinished:Lt,isDisturbed:Nn,getStreamError:dt,Stream:Mn,Writable:ir,Readable:Ki,Duplex:_s,Transform:Bt,PassThrough:nr},wl}var pg=JS(),Ll,Md;function ZS(){if(Md)return Ll;Md=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 Ll=e,Ll}var eC=ZS();const st=Dn(eC);/* 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 wa="0123456789abcdef",gg=[],La=[];for(let s=0;s<256;s++)gg[s]=wa[s>>4&15]+wa[s&15],s<16&&(s<10?La[48+s]=s:La[87+s]=s);const hs=s=>{const e=s.length;let t="",i=0;for(;i<e;)t+=gg[s[i++]];return t},ru=s=>{const e=s.length>>1,t=e<<1,i=new Uint8Array(e);let n=0,r=0;for(;r<t;)i[n++]=La[s.charCodeAt(r++)]<<4|La[s.charCodeAt(r++)];return i};var Od="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",tC=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(var Vr=0;Vr<Od.length;Vr++)tC[Od.charCodeAt(Vr)]=Vr;const iC=new TextDecoder,mg=(s,e)=>iC.decode(s),nC=new TextEncoder,Uu=s=>nC.encode(s),Zn=s=>{let e="",t,i=0;const n=s.length;for(;i<n;)t=s.charCodeAt(i++),e+=wa[t>>4]+wa[t&15];return e},Fd=65536,Fs=s=>{const e=ru(s);if(e.length<=Fd)return String.fromCharCode(...e);let t="",i=0;for(;i<e.length;)t+=String.fromCharCode(...e.subarray(i,i+=Fd));return t},Nd=typeof window<"u"?window:self,au=Nd.crypto||Nd.msCrypto||{};au.subtle||au.webkitSubtle;const Aa=s=>{const e=new Uint8Array(s);return au.getRandomValues(e)};/*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */const sC=bi("simple-peer"),Al=64*1024,rC=5*1e3,aC=5*1e3;function Bd(s){return s.replace(/a=ice-options:trickle\s\n/g,"")}function oC(s){console.warn(s)}let Gs=class ou extends pg.Duplex{constructor(e){if(e=Object.assign({allowHalfOpen:!1},e),super(e),se(this,"_pc"),this.__objectMode=!!e.objectMode,this._id=hs(Aa(4)).slice(0,7),this._debug("new peer %o",e),this.channelName=e.initiator?e.channelName||hs(Aa(20)):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||ou.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},ou.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||rC,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,!su)throw st(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 su(this.config)}catch(t){this.__destroy(st(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(st(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 st(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 WS(e)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(t=>{this._addIceCandidate(t)}),this._pendingCandidates=[],this._pc.remoteDescription.type==="offer"&&this._createAnswer())}).catch(t=>{this.__destroy(st(t,"ERR_SET_REMOTE_DESCRIPTION"))}),!e.sdp&&!e.candidate&&!e.renegotiate&&!e.transceiverRequest&&this.__destroy(st(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(e){const t=new zS(e);this._pc.addIceCandidate(t).catch(i=>{!t.address||t.address.endsWith(".local")?oC("Ignoring unsupported ICE candidate."):this.__destroy(st(i,"ERR_ADD_ICE_CANDIDATE"))})}send(e){if(!this._destroying){if(this.destroyed)throw st(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 st(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(st(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=Al),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(st(n,"ERR_DATA_CHANNEL"))};let t=!1;this._closingInterval=setInterval(()=>{this._channel&&this._channel.readyState==="closing"?(t&&this._onChannelClose(),t=!0):t=!1},aC)}_write(e,t){if(this.destroyed)return t(st(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(e)}catch(i){return this.__destroy(st(i,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>Al?(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=Bd(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(st(r,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(e).then(i).catch(n)}).catch(e=>{this.__destroy(st(e,"ERR_CREATE_OFFER"))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(e=>{if(this.destroyed)return;!this.trickle&&!this.allowHalfTrickle&&(e.sdp=Bd(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(st(r,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(e).then(i).catch(n)}).catch(e=>{this.__destroy(st(e,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||this._destroying||this._pc.connectionState==="failed"&&this.__destroy(st(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(st(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),e==="closed"&&this.__destroy(st(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 f=r[p.localCandidateId];f&&(f.ip||f.address)?(this.localAddress=f.ip||f.address,this.localPort=Number(f.port)):f&&f.ipAddress?(this.localAddress=f.ipAddress,this.localPort=Number(f.portNumber)):typeof p.googLocalAddress=="string"&&(f=p.googLocalAddress.split(":"),this.localAddress=f[0],this.localPort=Number(f[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let m=n[p.remoteCandidateId];m&&(m.ip||m.address)?(this.remoteAddress=m.ip||m.address,this.remotePort=Number(m.port)):m&&m.ipAddress?(this.remoteAddress=m.ipAddress,this.remotePort=Number(m.portNumber)):typeof p.googRemoteAddress=="string"&&(m=p.googRemoteAddress.split(":"),this.remoteAddress=m[0],this.remotePort=Number(m[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(f){return this.__destroy(st(f,"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>Al||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=Uu(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],sC.apply(null,e)}};Gs.WEBRTC_SUPPORT=!!su;Gs.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"};Gs.channelConfig={};var lC=fg();const lu=Dn(lC),vi={},uC=Object.freeze(Object.defineProperty({__proto__:null,default:vi},Symbol.toStringTag,{value:"Module"})),cC=50,hC=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},uu={DEFAULT_ANNOUNCE_PEERS:cC,parseUrl:hC,...uC};/*! simple-websocket. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */const dC=bi("simple-websocket"),xs=typeof vi!="function"?WebSocket:vi,Ud=64*1024;class yg extends pg.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=hs(Aa(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===xs.OPEN;else{this.url=e.url;try{typeof vi=="function"?this._ws=new xs(e.url,{...e,encoding:void 0}):this._ws=new xs(e.url)}catch(t){lu(()=>this.destroy(t));return}}this._ws.binaryType="arraybuffer",e.socket&&this.connected?lu(()=>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===xs.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 vi!="function"&&this._ws.bufferedAmount>Ud?(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 vi!="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=Uu(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>Ud)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],dC.apply(null,e)}}yg.WEBSOCKET_SUPPORT=!!xs;class fC extends dg{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 Qt=bi("bittorrent-tracker:websocket-tracker"),Ri={},pC=10*1e3,gC=60*60*1e3,mC=5*60*1e3,yC=50*1e3;class Hu extends fC{constructor(e,t){super(e,t),Qt("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=>Fs(n)):e.infoHash&&Fs(e.infoHash)||this.client._infoHashBinary};this._send(i)}destroy(e=Hd){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,Ri[this.announceUrl]&&(Ri[this.announceUrl].consumers-=1),Ri[this.announceUrl].consumers>0)return e();let t=Ri[this.announceUrl];delete Ri[this.announceUrl],t.on("error",Hd),t.once("close",e);let i;if(!this.expectingResponse)return n();i=setTimeout(n,uu.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=Ri[this.announceUrl],this.socket)Ri[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=Ri[this.announceUrl]=new yg({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(mg(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){Qt("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,Zn(e.info_hash),this.client.infoHash);return}if(e.peer_id&&e.peer_id===this.client._peerIdBinary)return;Qt("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:Zn(e.info_hash)});this.client.emit("update",u)}let o;if(e.offer&&e.peer_id&&(Qt("creating peer (from remote offer)"),o=this._createPeer(),o.id=Zn(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=Zn(e.offer_id);o=this.peers[u],o?(o.id=Zn(e.peer_id),this.client.emit("peer",o),o.signal(e.answer),clearTimeout(o.trackerTimeout),o.trackerTimeout=null,delete this.peers[u]):Qt(`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:Zn(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()*mC)+Math.min(Math.pow(2,this.retries)*pC,gC);this.reconnecting=!0,clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.retries++,this._openSocket()},e),this.reconnectTimer.unref&&this.reconnectTimer.unref(),Qt("reconnecting socket in %s ms",e)}_send(e){if(this.destroyed)return;this.expectingResponse=!0;const t=JSON.stringify(e);Qt("send %s",t),this.socket.send(t)}_generateOffers(e,t){const i=this,n=[];Qt("generating %s offers",e);for(let u=0;u<e;++u)r();o();function r(){const u=hs(Aa(20));Qt("creating peer (from _generateOffers)");const h=i.peers[u]=i._createPeer({initiator:!0});h.once("signal",p=>{n.push({offer:p,offer_id:Fs(u)}),o()}),h.trackerTimeout=setTimeout(()=>{Qt("tracker timeout: destroying peer"),h.trackerTimeout=null,delete i.peers[u],h.destroy()},yC),h.trackerTimeout.unref&&h.trackerTimeout.unref()}function o(){n.length===e&&(Qt("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 Gs(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)}}}Hu.prototype.DEFAULT_ANNOUNCE_INTERVAL=30*1e3;Hu._socketPool=Ri;function Hd(){}const Yi=bi("bittorrent-tracker:client");class cu extends dg{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(!oa.browser&&!e.port)throw new Error("Option `port` is required");this.peerId=typeof e.peerId=="string"?e.peerId:hs(e.peerId),this._peerIdBuffer=ru(this.peerId),this._peerIdBinary=Fs(this.peerId),this.infoHash=typeof e.infoHash=="string"?e.infoHash.toLowerCase():hs(e.infoHash),this._infoHashBuffer=ru(this.infoHash),this._infoHashBinary=Fs(this.infoHash),Yi("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=mg(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||Gs.WEBRTC_SUPPORT),n=r=>{lu(()=>{this.emit("warning",r)})};this._trackers=t.map(r=>{let o;try{o=uu.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 vi=="function"?new vi(this,r):h==="udp:"&&typeof vi=="function"?new vi(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 Hu(this,r):(n(new Error(`Unsupported tracker protocol: ${r}`)),null)}).filter(Boolean)}start(e){e=this._defaultAnnounceOpts(e),e.event="started",Yi("send `start` %o",e),this._announce(e),this._trackers.forEach(t=>{t.setInterval()})}stop(e){e=this._defaultAnnounceOpts(e),e.event="stopped",Yi("send `stop` %o",e),this._announce(e)}complete(e){e||(e={}),e=this._defaultAnnounceOpts(e),e.event="completed",Yi("send `complete` %o",e),this._announce(e)}update(e){e=this._defaultAnnounceOpts(e),e.event&&delete e.event,Yi("send `update` %o",e),this._announce(e)}_announce(e){this._trackers.forEach(t=>{t.announce(e)})}scrape(e){Yi("send `scrape`"),e||(e={}),this._trackers.forEach(t=>{t.scrape(e)})}setInterval(e){Yi("setInterval %d",e),this._trackers.forEach(t=>{t.setInterval(e)})}destroy(e){if(this.destroyed)return;this.destroyed=!0,Yi("destroy");const t=this._trackers.map(i=>n=>{i.destroy(n)});qS(t,e),this._trackers=[],this._getAnnounceOpts=null}_defaultAnnounceOpts(e={}){return e.numwant==null&&(e.numwant=uu.DEFAULT_ANNOUNCE_PEERS),e.uploaded==null&&(e.uploaded=0),e.downloaded==null&&(e.downloaded=0),this._getAnnounceOpts&&(e=Object.assign({},e,this._getAnnounceOpts())),e}}cu.scrape=(s,e)=>{if(e=VS(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:Uu("01234567890123456789"),port:6881}),i=new cu(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 kl={exports:{}},$d;function vC(){if($d)return kl.exports;$d=1;function s(A,P,O,M,k,N,H){var G=A+(P&O|~P&M)+(k>>>0)+H;return(G<<N|G>>>32-N)+P}function e(A,P,O,M,k,N,H){var G=A+(P&M|O&~M)+(k>>>0)+H;return(G<<N|G>>>32-N)+P}function t(A,P,O,M,k,N,H){var G=A+(P^O^M)+(k>>>0)+H;return(G<<N|G>>>32-N)+P}function i(A,P,O,M,k,N,H){var G=A+(O^(P|~M))+(k>>>0)+H;return(G<<N|G>>>32-N)+P}function n(A){return(256+(A&255)).toString(16).substr(-2)}function r(A){return String.fromCharCode(A&255)}function o(A){return r(A)+r(A>>>8)+r(A>>>16)+r(A>>>24)}var u=function(A){return unescape(encodeURIComponent(A))};function h(A){for(var P=A.length,O=P<<3,M=new Uint32Array(P+72>>>6<<4),k=0,N=A.length;k<N;++k)M[k>>>2]|=A.charCodeAt(k)<<((k&3)<<3);return M[P>>2]|=128<<(O&31),M[M.length-2]=O,M}var p=kl.exports=function(P){return m(P).toHex()},f=p.fromBytes=function(A){for(var P=h(A),O=1732584193,M=4023233417,k=2562383102,N=271733878,H=7,G=12,B=17,D=22,K=5,ae=9,Z=14,oe=20,le=4,he=11,pe=16,ge=23,ee=6,Q=10,ye=15,re=21,ie=0,be=P.length;ie<be;ie+=16){var Te=O,xe=M,Me=k,Pe=N;O=s(O,M,k,N,P[ie+0],H,3614090360),N=s(N,O,M,k,P[ie+1],G,3905402710),k=s(k,N,O,M,P[ie+2],B,606105819),M=s(M,k,N,O,P[ie+3],D,3250441966),O=s(O,M,k,N,P[ie+4],H,4118548399),N=s(N,O,M,k,P[ie+5],G,1200080426),k=s(k,N,O,M,P[ie+6],B,2821735955),M=s(M,k,N,O,P[ie+7],D,4249261313),O=s(O,M,k,N,P[ie+8],H,1770035416),N=s(N,O,M,k,P[ie+9],G,2336552879),k=s(k,N,O,M,P[ie+10],B,4294925233),M=s(M,k,N,O,P[ie+11],D,2304563134),O=s(O,M,k,N,P[ie+12],H,1804603682),N=s(N,O,M,k,P[ie+13],G,4254626195),k=s(k,N,O,M,P[ie+14],B,2792965006),M=s(M,k,N,O,P[ie+15],D,1236535329),O=e(O,M,k,N,P[ie+1],K,4129170786),N=e(N,O,M,k,P[ie+6],ae,3225465664),k=e(k,N,O,M,P[ie+11],Z,643717713),M=e(M,k,N,O,P[ie+0],oe,3921069994),O=e(O,M,k,N,P[ie+5],K,3593408605),N=e(N,O,M,k,P[ie+10],ae,38016083),k=e(k,N,O,M,P[ie+15],Z,3634488961),M=e(M,k,N,O,P[ie+4],oe,3889429448),O=e(O,M,k,N,P[ie+9],K,568446438),N=e(N,O,M,k,P[ie+14],ae,3275163606),k=e(k,N,O,M,P[ie+3],Z,4107603335),M=e(M,k,N,O,P[ie+8],oe,1163531501),O=e(O,M,k,N,P[ie+13],K,2850285829),N=e(N,O,M,k,P[ie+2],ae,4243563512),k=e(k,N,O,M,P[ie+7],Z,1735328473),M=e(M,k,N,O,P[ie+12],oe,2368359562),O=t(O,M,k,N,P[ie+5],le,4294588738),N=t(N,O,M,k,P[ie+8],he,2272392833),k=t(k,N,O,M,P[ie+11],pe,1839030562),M=t(M,k,N,O,P[ie+14],ge,4259657740),O=t(O,M,k,N,P[ie+1],le,2763975236),N=t(N,O,M,k,P[ie+4],he,1272893353),k=t(k,N,O,M,P[ie+7],pe,4139469664),M=t(M,k,N,O,P[ie+10],ge,3200236656),O=t(O,M,k,N,P[ie+13],le,681279174),N=t(N,O,M,k,P[ie+0],he,3936430074),k=t(k,N,O,M,P[ie+3],pe,3572445317),M=t(M,k,N,O,P[ie+6],ge,76029189),O=t(O,M,k,N,P[ie+9],le,3654602809),N=t(N,O,M,k,P[ie+12],he,3873151461),k=t(k,N,O,M,P[ie+15],pe,530742520),M=t(M,k,N,O,P[ie+2],ge,3299628645),O=i(O,M,k,N,P[ie+0],ee,4096336452),N=i(N,O,M,k,P[ie+7],Q,1126891415),k=i(k,N,O,M,P[ie+14],ye,2878612391),M=i(M,k,N,O,P[ie+5],re,4237533241),O=i(O,M,k,N,P[ie+12],ee,1700485571),N=i(N,O,M,k,P[ie+3],Q,2399980690),k=i(k,N,O,M,P[ie+10],ye,4293915773),M=i(M,k,N,O,P[ie+1],re,2240044497),O=i(O,M,k,N,P[ie+8],ee,1873313359),N=i(N,O,M,k,P[ie+15],Q,4264355552),k=i(k,N,O,M,P[ie+6],ye,2734768916),M=i(M,k,N,O,P[ie+13],re,1309151649),O=i(O,M,k,N,P[ie+4],ee,4149444226),N=i(N,O,M,k,P[ie+11],Q,3174756917),k=i(k,N,O,M,P[ie+2],ye,718787259),M=i(M,k,N,O,P[ie+9],re,3951481745),O=O+Te>>>0,M=M+xe>>>0,k=k+Me>>>0,N=N+Pe>>>0}var je=new String(o(O)+o(M)+o(k)+o(N));return je.toHex=function(){for(var it="",et=0,$e=je.length;et<$e;++et)it+=n(je.charCodeAt(et));return it},je},m=p.fromUtf8=function(A){return f(u(A))},T="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function _(A,P){for(var O="";--P>=0;A>>>=6)O+=T.charAt(A&63);return O}var b=64,w=[0,6,12,1,7,13,2,8,14,3,9,15,4,10,5,11],L=p.salt=function(A){var P="";A||(A=8);do P+=T.charAt(64*Math.random()>>>0);while(--A);return P};return p.crypt=function(A,P){if(A.length>b)throw Error("too long key");P||(P="$1$"+L()),A=u(A);for(var O=u(P.replace(/^\$1\$([^$]+)(?:\$.*)?$/,"$1")),M=f(A+O+A),k=A+"$1$"+O,N=A.length;N>16;N-=16)k+=M;k+=M.slice(0,N);for(var N=A.length;N;N>>=1)k+=N&1?"\0":A.charAt(0);M=f(k);for(var H=0;H<1e3;++H)M=f((H&1?A:M)+(H%3?O:"")+(H%7?A:"")+(H&1?M:A));for(var G="$1$"+O+"$",H=0;H<15;H+=3)G+=_(M.charCodeAt(w[H+0])<<16|M.charCodeAt(w[H+1])<<8|M.charCodeAt(w[H+2]),4);return G+_(M.charCodeAt(w[15]),2)},kl.exports}var TC=vC();const _C=Dn(TC),EC="2.1.2",bC=`-PM${LC(EC)}-`,jd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",SC=20;function CC(s){const e=_C.fromUtf8(s).slice(1);return btoa(e)}function wC(s){const e=[s],t=SC-s.length;for(let i=0;i<t;i++)e.push(jd[Math.floor(Math.random()*jd.length)]);return e.join("")}function LC(s){const e=s.split(".");return`${e[0].padStart(2,"0")}${e[1].padStart(2,"0")}`}function rn(s){return`${s.type}-${s.index}`}function Vd(s){const{externalId:e}=s;return`(${rn(s.stream)} | ${e})`}function AC(){let s,e;return{promise:new Promise((i,n)=>{s=i,e=n}),resolve:s,reject:e}}function vg(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 kC(s){return s[Math.floor(Math.random()*s.length)]}function Gd(s){const e=new TextEncoder,t=new Uint8Array(s.length);return e.encodeInto(s,t),t}function IC(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*Kd(s){for(let e=s.length-1;e>=0;e--)yield s[e]}function Tg(s){return!!s&&typeof s=="object"&&!Array.isArray(s)}function RC(s){return Array.isArray(s)}function PC(s){function e(t){if(Tg(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 tn(s){if(RC(s))return s.map(e=>tn(e));if(Tg(s)){const e={};for(const t of Object.keys(s))e[t]=tn(s[t]);return e}else return s}function DC(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 Rs(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 Il(s){const{defaultConfig:e,baseConfig:t={},specificStreamConfig:i={}}=s,n=tn({...e,...t,...i}),r=Object.keys(e),o={};return r.forEach(u=>{u in n&&(o[u]=n[u])}),o}var Zi=(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))(Zi||{}),os=(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))(os||{});function xC(s){return s<0?-s:s}function MC(s){const e=s.toString(2),t=s<0?e.length:e.length+1;return Math.ceil(t/8)}function OC(s){const e=s<0,t=MC(s),i=new Uint8Array(t),n=BigInt(t);s=xC(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 FC(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 _g(s){const e=OC(s),t=0|e.length;return new Uint8Array([t,...e])}function Eg(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:FC(s.slice(n,r)),byteLength:i+1}}function NC(s){const e=new Map;for(const i of s){const n=i&~0xffn,r=i&0xffn,o=e.get(n)??new $s;o.length||e.set(n,o),o.push(Number(r))}const t=new $s;t.push([16,e.size]);for(const[i,n]of e){const{length:r}=n.getBytesChunks(),o=i|BigInt(r)&0xffn;n.unshift(_g(o)),t.push(n.getBuffer())}return t.getBuffer()}function BC(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}=Eg(s.slice(n));n+=h;const p=u&0xffn,f=u&~0xffn;for(let m=0;m<p;m++){const T=BigInt(s[n]);r.push(f|T),n++}}return{numbers:r,byteLength:n}}function UC(s){const{length:e}=s,t=new $s;return t.push([32|e>>8&15,e&255]),t.push(new TextEncoder().encode(s)),t.getBuffer()}function HC(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 $s{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 vg(this.bytes,this._length)}get length(){return this._length}}const Ei=4,ds=Fa("cstr",Ei),js=Fa("cend",Ei),hu=Fa("dstr",Ei),du=Fa("dend",Ei),$C=[ds,hu],jC=[js,du],qd=ds.length+js.length;function bg(s){const{length:e}=ds,t=s.slice(-e);return $C.some(i=>Ia(s,i,Ei))&&jC.some(i=>Ia(t,i,Ei))}function VC(s){return Ia(s,ds,Ei)}function GC(s){return Ia(s.slice(-4),js,Ei)}class ka extends Error{constructor(e){super(),this.type=e}}class Sg{constructor(e){se(this,"chunks",new $s),se(this,"status","joining"),this.onComplete=e}addCommandChunk(e){if(this.status==="completed")return;const t=VC(e);if(!this.chunks.length&&!t)throw new ka("no-first-chunk");if(this.chunks.length&&t)throw new ka("incomplete-joining");this.chunks.push(this.unframeCommandChunk(e)),GC(e)&&(this.status="completed",this.onComplete(this.chunks.getBuffer()))}unframeCommandChunk(e){return e.slice(Ei,e.length-Ei)}}class Oa{constructor(e,t){se(this,"bytes",new $s),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=_g(BigInt(t));this.bytes.push(i)}addSimilarIntArr(e,t){this.bytes.push(e.charCodeAt(0));const i=NC(t.map(n=>BigInt(n)));this.bytes.push(i)}addString(e,t){this.bytes.push(e.charCodeAt(0));const i=UC(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+qd<=this.maxChunkLength){this.resultBuffers.push(Gr(e,ds,js));return}let t=Math.ceil(e.length/this.maxChunkLength);Math.ceil(e.length/t)+qd>this.maxChunkLength&&t++;for(const[i,n]of qC(e,t))i===0?this.resultBuffers.push(Gr(n,ds,du)):i===t-1?this.resultBuffers.push(Gr(n,hu,js)):this.resultBuffers.push(Gr(n,hu,du))}getResultBuffers(){if(this.status==="creating"||!this.resultBuffers.length)throw new Error("Command is not complete.");return this.resultBuffers}}function Cg(s){const[e]=s,t={c:e};let i=1;for(;i<s.length;){const n=String.fromCharCode(s[i]);switch(i++,KC(s[i])){case os.Int:{const{number:o,byteLength:u}=Eg(s.slice(i));t[n]=Number(o),i+=u}break;case os.SimilarIntArray:{const{numbers:o,byteLength:u}=BC(s.slice(i));t[n]=o.map(h=>Number(h)),i+=u}break;case os.String:{const{string:o,byteLength:u}=HC(s.slice(i));t[n]=o,i+=u}break}}return t}function KC(s){const e=s>>4;if(e<=os.Min||e>=os.Max)throw new Error("Not existing type");return e}function Fa(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*qC(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 Gr(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 Ia(s,e,t){for(let i=0;i<t;i++)if(s[i]!==e[i])return!1;return!0}function WC(s,e){const{c:t,p:i,l:n}=s,r=new Oa(t,e);return n?.length&&r.addSimilarIntArr("l",n),i?.length&&r.addSimilarIntArr("p",i),r.complete(),r.getResultBuffers()}function zC(s,e){const t=new Oa(s.c,e);return t.addInteger("i",s.i),t.addInteger("r",s.r),t.complete(),t.getResultBuffers()}function YC(s,e){const t=new Oa(s.c,e);return t.addInteger("i",s.i),t.addInteger("s",s.s),t.addInteger("r",s.r),t.complete(),t.getResultBuffers()}function XC(s,e){const t=new Oa(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 wg(s,e){switch(s.c){case Zi.CancelSegmentRequest:case Zi.SegmentAbsent:case Zi.SegmentDataSendingCompleted:return zC(s,e);case Zi.SegmentRequest:return XC(s,e);case Zi.SegmentsAnnouncement:return WC(s,e);case Zi.SegmentData:return YC(s,e)}}const QC=Object.freeze(Object.defineProperty({__proto__:null,BinaryCommandChunksJoiner:Sg,BinaryCommandJoiningError:ka,PeerCommandType:Zi,deserializeCommand:Cg,isCommandChunk:bg,serializePeerCommand:wg},Symbol.toStringTag,{value:"Module"}));class JC{constructor(e,t,i,n){se(this,"commandChunks"),se(this,"uploadingContext"),se(this,"onChunkDownloaded"),se(this,"onChunkUploaded"),se(this,"onDataReceived",r=>{bg(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=wg(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=ZC(e,this.peerConfig.webRtcMaxMessageSize),{promise:n,resolve:r,reject:o}=AC();let u=!1;const h={stopUploading:()=>{u=!1},requestId:t};this.uploadingContext=h;const p=()=>{if(!u){o();return}for(;;){const f=i.next().value;if(!f){r();break}const m=this.connection.write(f);if(this.onChunkUploaded(f.byteLength,this.connection.idUtf8),!m)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 Sg(t=>{this.commandChunks=void 0;const i=Cg(t);this.eventHandlers.onCommandReceived(i)}));try{this.commandChunks.addCommandChunk(e)}catch(t){if(!(t instanceof ka))return;this.commandChunks=void 0}}}function*ZC(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:jt}=QC;class Ra{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",bi("p2pml-core:peer")),se(this,"onPeerClosed"),se(this,"onCommandReceived",async o=>{var u,h,p;switch(o.c){case jt.SegmentsAnnouncement:this.loadedSegments=new Set(o.l),this.httpLoadingSegments=new Set(o.p),this.eventHandlers.onSegmentsAnnouncement();break;case jt.SegmentRequest:this.peerProtocol.stopUploadingSegmentData(),this.eventHandlers.onSegmentRequested(this,o.i,o.r,o.b);break;case jt.SegmentData:{if(!this.downloadingContext||this.downloadingContext.isSegmentDataCommandReceived)break;const{request:f,controls:m,requestId:T}=this.downloadingContext;if(f.segment.externalId!==o.i||T!==o.r)break;this.downloadingContext.isSegmentDataCommandReceived=!0,m.firstBytesReceived(),f.totalBytes===void 0?f.setTotalBytes(o.s):f.totalBytes-f.loadedBytes!==o.s&&(f.clearLoadedBytes(),this.sendCancelSegmentRequestCommand(f.segment,T),this.cancelSegmentDownloading("peer-response-bytes-length-mismatch"),this.destroy())}break;case jt.SegmentDataSendingCompleted:{const{downloadingContext:f}=this;if(!f?.isSegmentDataCommandReceived)return;const{request:m,controls:T}=f;if(f.request.segment.externalId!==o.i||f.requestId!==o.r){m.clearLoadedBytes(),this.cancelSegmentDownloading("peer-protocol-violation"),this.destroy();return}if(m.loadedBytes!==m.totalBytes){m.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,m.segment.url,m.segment.byteRange,m.data))??!0;if(this.downloadingContext!==f)return;if(!w){m.clearLoadedBytes(),this.cancelSegmentDownloading("p2p-segment-validation-failed"),this.destroy();return}this.downloadingErrors=[],T.completeOnSuccess(),this.downloadingContext=void 0;break}case jt.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 jt.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=Ra.getPeerIdFromConnection(e),this.peerProtocol=new JC(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:jt.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:jt.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:jt.SegmentsAnnouncement,p:t,l:e};this.peerProtocol.sendCommand(i)}sendSegmentAbsentCommand(e,t){this.peerProtocol.sendCommand({c:jt.SegmentAbsent,i:e,r:t})}sendCancelSegmentRequestCommand(e,t){this.peerProtocol.sendCommand({c:jt.CancelSegmentRequest,i:e.externalId,r:t})}sendSegmentDataSendingCompletedCommand(e,t){this.peerProtocol.sendCommand({c:jt.SegmentDataSendingCompleted,r:t,i:e.externalId})}static getPeerIdFromConnection(e){return IC(e.id)}}function ew(){const s=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),e=/\b(iPad|iPhone|Macintosh).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent);return s||e}const Lg=class la{constructor(e,t,i,n,r){se(this,"streamShortId"),se(this,"client"),se(this,"_peers",new Map),se(this,"logger",bi("p2pml-core:p2p-tracker-client")),se(this,"onReceivePeerConnection",h=>{const p=Ra.getPeerIdFromConnection(h);let f=this._peers.get(p);if(f?.peer){h.destroy();return}else f||(f={potentialConnections:new Set},h.idUtf8=p,f.potentialConnections.add(h),this._peers.set(p,f));h.on("connect",()=>{if(!f.peer){for(const m of f.potentialConnections)m!==h&&m.destroy();f.potentialConnections.clear(),f.peer=new Ra(h,{onPeerClosed:this.onPeerClosed,onSegmentRequested:this.eventHandlers.onSegmentRequested,onSegmentsAnnouncement:this.eventHandlers.onSegmentsAnnouncement},this.config,this.stream.type,this.eventTarget),this.logger(`connected with peer: ${f.peer.id} ${this.streamShortId}`),this.eventHandlers.onPeerConnected(f.peer)}})}),se(this,"onTrackerClientWarning",h=>{this.logger(`tracker warning (${this.streamShortId}: ${h})`),this.eventTarget.getEventDispatcher("onTrackerWarning")({streamType:this.stream.type,warning:h})}),se(this,"onTrackerClientError",h=>{this.logger(`tracker error (${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=CC(e);this.streamShortId=rn(t);let u=la.PEER_ID_BY_INFO_HASH.get(o);u||(u=wC(n.trackerClientVersionPrefix),la.PEER_ID_BY_INFO_HASH.set(o,u)),this.client=new cu({infoHash:Gd(o),peerId:Gd(u),announce:ew()?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(){la.PEER_ID_BY_INFO_HASH.clear()}};se(Lg,"PEER_ID_BY_INFO_HASH",new Map);let Ag=Lg;const tw="v2";function Fi(s,e){return`${tw}-${s}-${nw(e)}`}function Wd(s,e){for(const t of s.values()){const i=t.segments.get(e);if(i)return i}}function iw(s,e){for(const t of s.segments.values())if(t.externalId===e)return t}function nw(s){return`${s.type}-${s.index}`}function sw(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 rw(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 Rl(s,e,t,i,n){const{highDemandTimeWindow:r,httpDownloadTimeWindow:o,p2pDownloadTimeWindow:u}=rw(t,n);return{isHighDemand:Pl(s,e,r),isHttpDownloadable:Pl(s,e,o),isP2PDownloadable:Pl(s,e,u)&&i.isSegmentLoadingOrLoadedBySomeone(s)}}function Pl(s,e,t){const{startTime:i,endTime:n}=s,{position:r,rate:o}=e;return!(r+t*o<i||r>n)}class aw{constructor(e,t,i,n,r,o,u){se(this,"trackerClient"),se(this,"isAnnounceMicrotaskCreated",!1),se(this,"onPeerConnected",f=>{if(this.config.isP2PUploadDisabled)return;const{httpLoading:m,loaded:T}=this.getSegmentsAnnouncement();f.sendSegmentsAnnouncementCommand(T,m)}),se(this,"broadcastAnnouncement",(f=!1)=>{if(f){this.sendSegmentsAnnouncement([],[]);return}if(this.isAnnounceMicrotaskCreated||this.config.isP2PUploadDisabled)return;const{loaded:m,httpLoading:T}=this.getSegmentsAnnouncement();this.sendSegmentsAnnouncement(m,T)}),se(this,"sendSegmentsAnnouncement",(f,m)=>{this.isAnnounceMicrotaskCreated=!0,queueMicrotask(()=>{for(const T of this.trackerClient.peers())T.sendSegmentsAnnouncementCommand(f,m);this.isAnnounceMicrotaskCreated=!1})}),se(this,"onSegmentRequested",async(f,m,T,_)=>{const b=iw(this.stream,m);if(!b)return;if(this.config.isP2PUploadDisabled){f.sendSegmentAbsentCommand(m,T);return}const w=this.config.swarmId??this.streamManifestUrl,L=Fi(w,this.stream),A=await this.segmentStorage.getSegmentData(w,L,b.externalId);if(!A){f.sendSegmentAbsentCommand(m,T);return}await f.uploadSegmentData(b,T,_!==void 0?A.slice(_):A)}),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=Fi(h,this.stream);this.trackerClient=new Ag(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(f=>{this.eventTarget.dispatchEvent(`onStorageUpdated-${f}`)}),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=kC(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;for(const t of this.trackerClient.peers())e++;return e}getSegmentsAnnouncement(){const e=this.config.swarmId??this.streamManifestUrl,t=Fi(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=Fi(e,this.stream);this.eventTarget.removeEventListener(`onStorageUpdated-${t}`,this.broadcastAnnouncement),this.trackerClient.destroy()}}class ow{constructor(e,t,i,n,r,o,u){se(this,"loaders",new Map),se(this,"_currentLoaderItem"),se(this,"logger",bi("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: ${rn(t)}`)}createLoader(e){if(this.loaders.has(e.runtimeId))throw new Error("Loader for this stream already exists");const t=new aw(this.streamManifestUrl,e,this.requests,this.segmentStorage,this.config,this.eventTarget,()=>{this._currentLoaderItem.loader===t&&this.onSegmentAnnouncement()}),i=rn(e);return this.logger(`created new loader: ${i}`),{loader:t,stream:e,loggerInfo:rn(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=Fi(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: ${rn(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 Kr(s){return{runtimeId:s.runtimeId,externalId:s.externalId,url:s.url,byteRange:s.byteRange,startTime:s.startTime,endTime:s.endTime}}let lw=class{constructor(e,t,i,n,r,o){se(this,"currentAttempt"),se(this,"_failedAttempts",new uw),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 f=new ei("bytes-receiving-timeout");(p=this._abortRequestCallback)==null||p.call(this,f),this.logger(`${this.downloadSource} ${this.segment.externalId} failed ${f.type}`),this._failedAttempts.add({...this.currentAttempt,error:f}),this.onSegmentError({segment:Kr(this.segment),error:f,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:Kr(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:f}=p,{all:m,http:T}=this.bandwidthCalculators;m.addBytes(f),this.currentAttempt.downloadSource==="http"&&T.addBytes(f),this.bytes.push(p),this.progress.lastLoadedChunkTimestamp=performance.now(),this.progress.loadedBytes+=f,this._loadedBytes+=f}),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:f}=u;this._totalBytes=p-f+1}this.notReceivingBytesTimeout=new cw(this.abortOnTimeout);const{type:h}=this.segment.stream;this._logger=bi(`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=vg(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:Kr(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:Kr(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 uw{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 cw{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 hw{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 lw(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 dw{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 Ca("failed")))}abort(){this._status==="pending"&&(this._status="aborted",this.engineCallbacks.onError(new Ca("aborted")))}markAsShouldBeStartedImmediately(){this._shouldBeStartedImmediately=!0}}function*zd(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 m=h.next();if(m.done)return;p=m.value}while(p!==u);const f=Rl(p,e,t,i,n);if(Dl(f)){const m=h.next();if(m.done)return;const T=m.value,_=Rl(T,e,t,i,n);if(Dl(_))return;f.isHighDemand=!0,yield{segment:p,statuses:f},yield{segment:T,statuses:_}}else yield{segment:p,statuses:f};for(const m of h){const T=Rl(m,e,t,i,n);if(Dl(T))break;yield{segment:m,statuses:T}}}function Dl(s){const{isHighDemand:e=!1,isHttpDownloadable:t=!1,isP2PDownloadable:i=!1}=s;return!e&&!t&&!i}const fw=6e4,Yd=1e3;class pw{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 f=performance.now();!p&&this.lastQueueProcessingTimeStamp!==void 0&&f-this.lastQueueProcessingTimeStamp<=1e3||this.isProcessQueueMicrotaskCreated||(this.isProcessQueueMicrotaskCreated=!0,queueMicrotask(()=>{try{this.processQueue(),this.lastQueueProcessingTimeStamp=f}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=sw(h),this.requests=new hw(this.requestProcessQueueMicrotask,this.bandwidthCalculators,this.playback,this.config,this.eventTarget),this.p2pLoaders=new ow(this.streamManifestUrl,this.lastRequestedSegment.stream,this.requests,this.segmentStorage,this.config,this.eventTarget,this.requestProcessQueueMicrotask),this.logger=bi(`p2pml-core:hybrid-loader-${h.type}`),this.logger.color="coral",this.setIntervalLoading()}setIntervalLoading(){const e=this.p2pLoaders.currentLoader.connectedPeerCount,t=Math.random()*Yd*e+Yd;this.randomHttpDownloadInterval=window.setTimeout(()=>{this.loadRandomThroughHttp(),this.setIntervalLoading()},t)}async loadSegment(e,t){var i;this.logger(`requests: ${Vd(e)}`);const{stream:n}=e;n!==this.lastRequestedSegment.stream&&(this.logger(`stream changed to ${rn(n)}`),this.p2pLoaders.changeCurrentLoader(n)),this.lastRequestedSegment=e;const r=this.config.swarmId??this.streamManifestUrl,o=Fi(r,n);this.segmentStorage.onSegmentRequested(r,o,e.externalId,e.startTime,e.endTime,n.type,this.streamDetails.isLive);const u=new dw(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:f}=this.generateQueue();u.resolve(p,this.getBandwidth(f));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:f,isHandledByProcessQueue:m}=u,T=((i=this.engineRequest)==null?void 0:i.segment)===f?this.engineRequest:void 0;switch(p){case"loading":!e.has(f.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 b=this.config.swarmId??this.streamManifestUrl,w=Fi(b,n);this.segmentStorage.storeSegment(b,w,f.externalId,u.data,f.startTime,f.endTime,f.stream.type,this.streamDetails.isLive);break}case"failed":h==="http"&&!m&&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:_}=u.failedAttempts;_&&o-_.error.timestamp>fw&&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:f}=h,m=this.requests.get(f);if(p.isHighDemand){if(m?.downloadSource==="http"&&m.status==="loading"||m?.downloadSource==="http"&&m.status==="failed"&&m.failedAttempts.httpAttemptsCount>=u)continue;const T=m?.status==="loading"&&m.downloadSource==="p2p";if(this.requests.executingHttpCount<r){T&&m.abortFromProcessQueue(),this.loadThroughHttp(f);continue}if(this.abortLastHttpLoadingInQueueAfterItem(t,f)&&this.requests.executingHttpCount<r){T&&m.abortFromProcessQueue(),this.loadThroughHttp(f);continue}if(T)continue;if(this.requests.executingP2PCount<o){this.loadThroughP2P(f);continue}if(this.abortLastP2PLoadingInQueueAfterItem(t,f)&&this.requests.executingP2PCount<o){this.loadThroughP2P(f);continue}}else if(p.isP2PDownloadable){if(m?.status==="loading")continue;this.requests.executingP2PCount<o?this.loadThroughP2P(f):this.p2pLoaders.currentLoader.isSegmentLoadedBySomeone(f)&&this.abortLastP2PLoadingInQueueAfterItem(t,f)&&this.requests.executingP2PCount<o&&this.loadThroughP2P(f)}}}abortSegmentRequest(e){var t;((t=this.engineRequest)==null?void 0:t.segment.runtimeId)===e&&(this.engineRequest.abort(),this.logger("abort: ",Vd(this.engineRequest.segment)),this.engineRequest=void 0,this.requestProcessQueueMicrotask())}loadThroughHttp(e){const t=this.requests.getOrCreateRequest(e);new AS(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:m,statuses:T}of zd(this.lastRequestedSegment,this.playback,this.config,this.p2pLoaders.currentLoader,e)){const _=this.config.swarmId??this.streamManifestUrl,b=Fi(_,m.stream);if(!T.isHttpDownloadable||T.isP2PDownloadable||this.segmentStorage.hasSegment(_,b,m.externalId))continue;const w=this.requests.get(m);w&&(w.status==="loading"||w.status==="succeed"||w.failedAttempts.httpAttemptsCount>=i)||r.push(m)}if(!r.length||t-this.requests.executingHttpCount===0)return;const u=n.connectedPeerCount+1,h=Math.min(r.length,t*u),p=DC(Array.from({length:h},(m,T)=>T));let f=h/u;for(const m of p){if(this.requests.executingHttpCount>=t)break;if(f>=1||Math.random()<=f){const T=r[m];this.loadThroughHttp(T)}if(f--,f<=0)break}}abortLastHttpLoadingInQueueAfterItem(e,t){for(const{segment:i}of Kd(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 Kd(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 zd(this.lastRequestedSegment,this.playback,this.config,this.p2pLoaders.currentLoader,o)){n++;const{segment:h}=u,p=this.config.swarmId??this.streamManifestUrl,f=Fi(p,h.stream);if(this.segmentStorage.hasSegment(p,f,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: ${rn(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 Xd{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 qr=(s,e)=>`${s}|${e}`,gw=s=>/Android/i.test(s),mw=s=>/iPad|iPhone/i.test(s),yw=s=>/Android/i.test(s)&&!/Chrome|Firefox/i.test(s),Wr=1048576;class vw{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=bi("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=qr(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=qr(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/Wr}}hasSegment(e,t,i){const n=qr(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,f=qr(u,h);if(this.shouldRemoveSegment(o,e,this.currentPlayback.position)&&(this.cache.delete(f),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/Wr>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/Wr}decreaseStorageUsage(e){this.currentStorageUsage-=e/Wr}setMemoryStorageLimit(){var e;if((e=this.coreConfig)!=null&&e.segmentMemoryStorageLimit){this.segmentMemoryStorageLimit=this.coreConfig.segmentMemoryStorageLimit;return}yw(this.userAgent)||mw(this.userAgent)?this.segmentMemoryStorageLimit=1024:gw(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 Tw{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 $u=class ua{constructor(e){se(this,"eventTarget",new Tw),se(this,"manifestResponseUrl"),se(this,"streams",new Map),se(this,"mainStreamConfig"),se(this,"secondaryStreamConfig"),se(this,"commonCoreConfig"),se(this,"bandwidthCalculators",{all:new Xd,http:new Xd}),se(this,"segmentStorage"),se(this,"mainStreamLoader"),se(this,"secondaryStreamLoader"),se(this,"streamDetails",{isLive:!1,activeLevelBitrate:0});const t=PC(e??{});this.commonCoreConfig=Il({defaultConfig:ua.DEFAULT_COMMON_CORE_CONFIG,baseConfig:t}),this.mainStreamConfig=Il({defaultConfig:ua.DEFAULT_STREAM_CONFIG,baseConfig:t,specificStreamConfig:t.mainStream}),this.secondaryStreamConfig=Il({defaultConfig:ua.DEFAULT_STREAM_CONFIG,baseConfig:t,specificStreamConfig:t.secondaryStream})}getConfig(){return{...tn(this.commonCoreConfig),mainStream:tn(this.mainStreamConfig),secondaryStream:tn(this.secondaryStreamConfig)}}applyDynamicConfig(e){const{mainStream:t,secondaryStream:i}=e,n=tn(this.mainStreamConfig),r=tn(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!!Wd(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},Ag.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 vw;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=Wd(this.streams,e);if(!t)throw new Error(`Not found segment with id: ${e}`);return t}overrideAllConfigs(e,t,i){Rs(this.commonCoreConfig,e),Rs(this.mainStreamConfig,e),Rs(this.secondaryStreamConfig,e),t&&Rs(this.mainStreamConfig,t),i&&Rs(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 pw(this.manifestResponseUrl,e,this.streamDetails,t,this.bandwidthCalculators,this.segmentStorage,this.eventTarget)}};se($u,"DEFAULT_COMMON_CORE_CONFIG",{segmentMemoryStorageLimit:void 0,customSegmentStorageFactory:void 0});se($u,"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:bC,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,httpRequestSetup:void 0,swarmId:void 0});let _w=$u;const Ew=cg.debug;var _n=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},Je=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)},Ms,ns,ca,Pi,Sn,en,nn,kg,fu;const bw=10;class Sw{constructor(e,t){Ms.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}),ns.set(this,void 0),ca.set(this,void 0),Pi.set(this,void 0),Sn.set(this,void 0),en.set(this,void 0),nn.set(this,void 0),_n(this,Sn,t),_n(this,ca,()=>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,_n(this,ns,i);const{stats:n}=this,{rangeStart:r,rangeEnd:o}=e,u=rg(r,o!==void 0?o-1:void 0);_n(this,nn,sg(e.url,u));const h=Je(this,Sn,"f").isSegmentLoadable(Je(this,nn,"f"));if(!Je(this,Sn,"f").hasSegment(Je(this,nn,"f"))||!h){_n(this,Pi,Je(this,ca,"f").call(this)),Je(this,Pi,"f").stats=this.stats,Je(this,Pi,"f").load(e,t,i);return}const p=m=>{_n(this,en,m);const T=Je(this,en,"f").data.byteLength;n.loading=Cw(Je(this,en,"f").bandwidth,T,performance.now()),n.total=T,n.loaded=T,i.onProgress&&i.onProgress(this.stats,e,Je(this,en,"f").data,void 0),i.onSuccess({data:Je(this,en,"f").data,url:e.url},this.stats,e,void 0)},f=m=>{m instanceof Ca&&m.type==="aborted"&&this.stats.aborted||Je(this,Ms,"m",kg).call(this,m)};Je(this,Sn,"f").loadSegment(Je(this,nn,"f"),{onSuccess:p,onError:f})}abort(){var e,t;Je(this,Pi,"f")?Je(this,Pi,"f").abort():(Je(this,Ms,"m",fu).call(this),(t=(e=Je(this,ns,"f"))==null?void 0:e.onAbort)==null||t.call(e,this.stats,this.context,{}))}destroy(){Je(this,Pi,"f")?Je(this,Pi,"f").destroy():(this.stats.aborted||Je(this,Ms,"m",fu).call(this),_n(this,ns,null),this.config=null)}}ns=new WeakMap,ca=new WeakMap,Pi=new WeakMap,Sn=new WeakMap,en=new WeakMap,nn=new WeakMap,Ms=new WeakSet,kg=function(e){var t;const i={code:0,text:""};(e instanceof Ca&&e.type==="failed"||e instanceof Error)&&(i.text=e.message),(t=Je(this,ns,"f"))==null||t.onError(i,this.context,null,this.stats)},fu=function(){!Je(this,en,"f")&&Je(this,nn,"f")&&(this.stats.aborted=!0,Je(this,Sn,"f").abortSegmentLoading(Je(this,nn,"f")))};function Cw(s,e,t){const i=e*8e3/s,n=t-i;return{start:n-bw,first:n,end:t}}var ww=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},Ps=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)},Qi;class Lw{constructor(e){Qi.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}),ww(this,Qi,new e.loader(e)),this.stats=Ps(this,Qi,"f").stats,this.context=Ps(this,Qi,"f").context}load(e,t,i){Ps(this,Qi,"f").load(e,t,i)}abort(){Ps(this,Qi,"f").abort()}destroy(){Ps(this,Qi,"f").destroy()}}Qi=new WeakMap;class Aw{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:f,byteRange:m,sn:T,start:_,end:b}=h;if(T==="initSegment")return;const[w,L]=m,A=rg(w,L!==void 0?L-1:void 0),P=sg(f,A);o.delete(P),!r.segments.has(P)&&u.push({runtimeId:P,url:f,externalId:n?T:p,byteRange:A,startTime:_,endTime:b})}),!(!u.length&&!o.size)&&this.core.updateStream(t,u,o.values())}}var kw=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)},Iw=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 Rw(s){var e,t;return t=class extends s{get p2pEngine(){return kw(this,e,"f")}constructor(...n){var r;const o=n[0],{p2p:u,...h}=o??{},p=new Ig(u);super({...h,...p.getConfigForHlsJs()}),e.set(this,void 0),p.bindHls(this),Iw(this,e,p),(r=u?.onHlsJsCreated)==null||r.call(u,this)}},e=new WeakMap,t}const Pw=120;class Ig{static injectMixin(e){return Rw(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:Ew("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 _w(e?.core),this.segmentManager=new Aw(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(Pw/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 Sw{constructor(n){super(n,e)}static getEngine(){return t}}}createPlaylistLoaderClass(){const e=this;return class extends Lw{constructor(i){super(i),e.initHlsEvents()}}}}const Qd=Ig.injectMixin(We);let Jd=!1;const Dw=function(s){if(!We.isSupported()){Ne.info("Hls.js is not supported in this browser.");return}const e=s.getTech("Html5");if(!e){Ne.error('No "Html5" tech found in videojs');return}Jd||(Jd=!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 Zd(s,t,i),i.hlsProvider}},0),s.Html5Hlsjs=Zd)},xw=X.getPlugin("plugin");class Mw extends xw{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),Dw(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",Mw);class Zd{constructor(e,t,i){Ue(this,"videoElement"),Ue(this,"errorCounts",{}),Ue(this,"player"),Ue(this,"tech"),Ue(this,"source"),Ue(this,"vjs"),Ue(this,"maxNetworkErrorRecovery",5),Ue(this,"hls"),Ue(this,"hlsjsConfig",null),Ue(this,"_duration",null),Ue(this,"metadata",null),Ue(this,"isLive",null),Ue(this,"dvrDuration",null),Ue(this,"edgeMargin",null),Ue(this,"liveEnded",!1),Ue(this,"handlers",{play:null,error:null}),Ue(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(Ne.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}Ne.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(),Ne.info("bubbling error up to VIDEOJS"),this.tech.error=()=>({...e,message:this._getHumanErrorMsg(e)}),this.tech.trigger("error")}_handleMediaError(e){if(this.errorCounts[We.ErrorTypes.MEDIA_ERROR]===1){Ne.info("trying to recover media error"),this.hls.recoverMediaError();return}if(this.errorCounts[We.ErrorTypes.MEDIA_ERROR]===2){Ne.info("2nd try to recover media error (by swapping audio codec"),this.hls.swapAudioCodec(),this.hls.recoverMediaError();return}this.errorCounts[We.ErrorTypes.MEDIA_ERROR]>2&&this._handleUnrecovarableError(e)}_handleNetworkError(e){var t,i;if(navigator.onLine!==!1){if(this.liveEnded){Ne.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[We.ErrorTypes.NETWORK_ERROR]<=this.maxNetworkErrorRecovery){Ne.info("trying to recover network error"),setTimeout(()=>this.hls.startLoad(),1e3),this.hls.once(We.Events.FRAG_LOADED,()=>{this.errorCounts[We.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?Ne.error(i.message,{currentTime:this.player.currentTime(),data:t}):Ne.clientWarn(i.message)),t.type===We.ErrorTypes.NETWORK_ERROR?(i.code=2,this._handleNetworkError(i)):t.fatal&&t.type===We.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 Qd({...fh(this.hlsjsConfig,["p2pMediaLoaderOptions"]),p2p:{core:this.hlsjsConfig.p2pMediaLoaderOptions}}),this.player.trigger("hlsjs-initialized",{hlsjs:this.hls}),this.hls.on(We.Events.ERROR,(e,t)=>this._onError(e,t)),this.hls.on(We.Events.MANIFEST_PARSED,(e,t)=>this._onMetaData(e,t)),this.hls.on(We.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(We.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 Qd({...fh(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(We.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(We.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 ef=an("peertube:player:p2p-media-loader"),Ow=X.getPlugin("plugin");class Fw extends Ow{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";Ne.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,ef("hls.js initialized, initializing p2p-media-loader plugin",{hlsjs:o}),e.ready(()=>this.initializePlugin())};e.on("hlsjs-initialized",i);const n=()=>{ef("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;Ne.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(We.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(We.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(We.Events.ERROR,(i,n)=>{n.type===We.ErrorTypes.MEDIA_ERROR&&n.details===We.ErrorDetails.BUFFER_STALLED_ERROR&&this.player.trigger("buffer-stalled")})}runStats(){this.connectedPeers=new Set,this.hlsjs.p2pEngine.getConfig().core.mainStream.isP2PDisabled&&this.hlsjs.on(We.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(){Ne.info("HLS.js does not seem to be supported. Fallback to built-in HLS."),this.player.src({type:this.options.type,src:uf(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",Fw);const tf=an("peertube:player:web-video-plugin"),Nw=X.getPlugin("plugin");class Bw extends Nw{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,tf("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=uf(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(){tf("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()")||(Ne.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(pf(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",Bw);const Uw=X.getComponent("Component");class Rg extends Uw{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",Rg);const Hw=X.getPlugin("plugin");class $w extends Hw{constructor(e,t){super(e,t),e.ready(()=>{e.addClass("peertube-dock")}),this.dockComponent=new Rg(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",$w);function xl(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 jw(s){return new Promise(e=>{setTimeout(()=>e(),s)})}function Vw(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 Gw{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}}}}class Kw{constructor(e=[]){Ue(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=Ww(t),n=i.length;this.baseUrls=this.baseUrls.filter(r=>r!==i&&r!==i+"/"),n!==this.baseUrls.length&&Ne.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+qw(e);return this.map.set(e,o),o}countBaseUrls(){return this.baseUrls.length}getRandomInt(e){return Math.floor(Math.random()*Math.floor(e))}}function qw(s){return s.split("/").pop()}function Ww(s){const e=s.split("/");return e.pop(),e.join("/")}var Pg={},Na={};Na.byteLength=Xw;Na.toByteArray=Jw;Na.fromByteArray=t0;var gi=[],Vt=[],zw=typeof Uint8Array<"u"?Uint8Array:Array,Ml="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var es=0,Yw=Ml.length;es<Yw;++es)gi[es]=Ml[es],Vt[Ml.charCodeAt(es)]=es;Vt[45]=62;Vt[95]=63;function Dg(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 Xw(s){var e=Dg(s),t=e[0],i=e[1];return(t+i)*3/4-i}function Qw(s,e,t){return(e+t)*3/4-t}function Jw(s){var e,t=Dg(s),i=t[0],n=t[1],r=new zw(Qw(s,i,n)),o=0,u=n>0?i-4:i,h;for(h=0;h<u;h+=4)e=Vt[s.charCodeAt(h)]<<18|Vt[s.charCodeAt(h+1)]<<12|Vt[s.charCodeAt(h+2)]<<6|Vt[s.charCodeAt(h+3)],r[o++]=e>>16&255,r[o++]=e>>8&255,r[o++]=e&255;return n===2&&(e=Vt[s.charCodeAt(h)]<<2|Vt[s.charCodeAt(h+1)]>>4,r[o++]=e&255),n===1&&(e=Vt[s.charCodeAt(h)]<<10|Vt[s.charCodeAt(h+1)]<<4|Vt[s.charCodeAt(h+2)]>>2,r[o++]=e>>8&255,r[o++]=e&255),r}function Zw(s){return gi[s>>18&63]+gi[s>>12&63]+gi[s>>6&63]+gi[s&63]}function e0(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(Zw(i));return n.join("")}function t0(s){for(var e,t=s.length,i=t%3,n=[],r=16383,o=0,u=t-i;o<u;o+=r)n.push(e0(s,o,o+r>u?u:o+r));return i===1?(e=s[t-1],n.push(gi[e>>2]+gi[e<<4&63]+"==")):i===2&&(e=(s[t-2]<<8)+s[t-1],n.push(gi[e>>10]+gi[e>>4&63]+gi[e<<2&63]+"=")),n.join("")}var ju={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */ju.read=function(s,e,t,i,n){var r,o,u=n*8-i-1,h=(1<<u)-1,p=h>>1,f=-7,m=t?n-1:0,T=t?-1:1,_=s[e+m];for(m+=T,r=_&(1<<-f)-1,_>>=-f,f+=u;f>0;r=r*256+s[e+m],m+=T,f-=8);for(o=r&(1<<-f)-1,r>>=-f,f+=i;f>0;o=o*256+s[e+m],m+=T,f-=8);if(r===0)r=1-p;else{if(r===h)return o?NaN:(_?-1:1)*(1/0);o=o+Math.pow(2,i),r=r-p}return(_?-1:1)*o*Math.pow(2,r-i)};ju.write=function(s,e,t,i,n,r){var o,u,h,p=r*8-n-1,f=(1<<p)-1,m=f>>1,T=n===23?Math.pow(2,-24)-Math.pow(2,-77):0,_=i?0:r-1,b=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=f):(o=Math.floor(Math.log(e)/Math.LN2),e*(h=Math.pow(2,-o))<1&&(o--,h*=2),o+m>=1?e+=T/h:e+=T*Math.pow(2,1-m),e*h>=2&&(o++,h/=2),o+m>=f?(u=0,o=f):o+m>=1?(u=(e*h-1)*Math.pow(2,n),o=o+m):(u=e*Math.pow(2,m-1)*Math.pow(2,n),o=0));n>=8;s[t+_]=u&255,_+=b,u/=256,n-=8);for(o=o<<n|u,p+=n;p>0;s[t+_]=o&255,_+=b,o/=256,p-=8);s[t+_-b]|=w*128};/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */(function(s){const e=Na,t=ju,i=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;s.Buffer=f,s.SlowBuffer=k,s.INSPECT_MAX_BYTES=50;const n=2147483647;s.kMaxLength=n;const{Uint8Array:r,ArrayBuffer:o,SharedArrayBuffer:u}=globalThis;f.TYPED_ARRAY_SUPPORT=h(),!f.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),E={foo:function(){return 42}};return Object.setPrototypeOf(E,r.prototype),Object.setPrototypeOf(R,E),R.foo()===42}catch{return!1}}Object.defineProperty(f.prototype,"parent",{enumerable:!0,get:function(){if(f.isBuffer(this))return this.buffer}}),Object.defineProperty(f.prototype,"offset",{enumerable:!0,get:function(){if(f.isBuffer(this))return this.byteOffset}});function p(R){if(R>n)throw new RangeError('The value "'+R+'" is invalid for option "size"');const E=new r(R);return Object.setPrototypeOf(E,f.prototype),E}function f(R,E,C){if(typeof R=="number"){if(typeof E=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return b(R)}return m(R,E,C)}f.poolSize=8192;function m(R,E,C){if(typeof R=="string")return w(R,E);if(o.isView(R))return A(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(mt(R,o)||R&&mt(R.buffer,o)||typeof u<"u"&&(mt(R,u)||R&&mt(R.buffer,u)))return P(R,E,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 f.from($,E,C);const q=O(R);if(q)return q;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof R[Symbol.toPrimitive]=="function")return f.from(R[Symbol.toPrimitive]("string"),E,C);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof R)}f.from=function(R,E,C){return m(R,E,C)},Object.setPrototypeOf(f.prototype,r.prototype),Object.setPrototypeOf(f,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 _(R,E,C){return T(R),R<=0?p(R):E!==void 0?typeof C=="string"?p(R).fill(E,C):p(R).fill(E):p(R)}f.alloc=function(R,E,C){return _(R,E,C)};function b(R){return T(R),p(R<0?0:M(R)|0)}f.allocUnsafe=function(R){return b(R)},f.allocUnsafeSlow=function(R){return b(R)};function w(R,E){if((typeof E!="string"||E==="")&&(E="utf8"),!f.isEncoding(E))throw new TypeError("Unknown encoding: "+E);const C=N(R,E)|0;let $=p(C);const q=$.write(R,E);return q!==C&&($=$.slice(0,q)),$}function L(R){const E=R.length<0?0:M(R.length)|0,C=p(E);for(let $=0;$<E;$+=1)C[$]=R[$]&255;return C}function A(R){if(mt(R,r)){const E=new r(R);return P(E.buffer,E.byteOffset,E.byteLength)}return L(R)}function P(R,E,C){if(E<0||R.byteLength<E)throw new RangeError('"offset" is outside of buffer bounds');if(R.byteLength<E+(C||0))throw new RangeError('"length" is outside of buffer bounds');let $;return E===void 0&&C===void 0?$=new r(R):C===void 0?$=new r(R,E):$=new r(R,E,C),Object.setPrototypeOf($,f.prototype),$}function O(R){if(f.isBuffer(R)){const E=M(R.length)|0,C=p(E);return C.length===0||R.copy(C,0,0,E),C}if(R.length!==void 0)return typeof R.length!="number"||Ft(R.length)?p(0):L(R);if(R.type==="Buffer"&&Array.isArray(R.data))return L(R.data)}function M(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),f.alloc(+R)}f.isBuffer=function(E){return E!=null&&E._isBuffer===!0&&E!==f.prototype},f.compare=function(E,C){if(mt(E,r)&&(E=f.from(E,E.offset,E.byteLength)),mt(C,r)&&(C=f.from(C,C.offset,C.byteLength)),!f.isBuffer(E)||!f.isBuffer(C))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(E===C)return 0;let $=E.length,q=C.length;for(let J=0,ne=Math.min($,q);J<ne;++J)if(E[J]!==C[J]){$=E[J],q=C[J];break}return $<q?-1:q<$?1:0},f.isEncoding=function(E){switch(String(E).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}},f.concat=function(E,C){if(!Array.isArray(E))throw new TypeError('"list" argument must be an Array of Buffers');if(E.length===0)return f.alloc(0);let $;if(C===void 0)for(C=0,$=0;$<E.length;++$)C+=E[$].length;const q=f.allocUnsafe(C);let J=0;for($=0;$<E.length;++$){let ne=E[$];if(mt(ne,r))J+ne.length>q.length?(f.isBuffer(ne)||(ne=f.from(ne)),ne.copy(q,J)):r.prototype.set.call(q,ne,J);else if(f.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,E){if(f.isBuffer(R))return R.length;if(o.isView(R)||mt(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(E){case"ascii":case"latin1":case"binary":return C;case"utf8":case"utf-8":return Hi(R).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C*2;case"hex":return C>>>1;case"base64":return $i(R).length;default:if(q)return $?-1:Hi(R).length;E=(""+E).toLowerCase(),q=!0}}f.byteLength=N;function H(R,E,C){let $=!1;if((E===void 0||E<0)&&(E=0),E>this.length||((C===void 0||C>this.length)&&(C=this.length),C<=0)||(C>>>=0,E>>>=0,C<=E))return"";for(R||(R="utf8");;)switch(R){case"hex":return re(this,E,C);case"utf8":case"utf-8":return pe(this,E,C);case"ascii":return Q(this,E,C);case"latin1":case"binary":return ye(this,E,C);case"base64":return he(this,E,C);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ie(this,E,C);default:if($)throw new TypeError("Unknown encoding: "+R);R=(R+"").toLowerCase(),$=!0}}f.prototype._isBuffer=!0;function G(R,E,C){const $=R[E];R[E]=R[C],R[C]=$}f.prototype.swap16=function(){const E=this.length;if(E%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let C=0;C<E;C+=2)G(this,C,C+1);return this},f.prototype.swap32=function(){const E=this.length;if(E%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let C=0;C<E;C+=4)G(this,C,C+3),G(this,C+1,C+2);return this},f.prototype.swap64=function(){const E=this.length;if(E%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let C=0;C<E;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},f.prototype.toString=function(){const E=this.length;return E===0?"":arguments.length===0?pe(this,0,E):H.apply(this,arguments)},f.prototype.toLocaleString=f.prototype.toString,f.prototype.equals=function(E){if(!f.isBuffer(E))throw new TypeError("Argument must be a Buffer");return this===E?!0:f.compare(this,E)===0},f.prototype.inspect=function(){let E="";const C=s.INSPECT_MAX_BYTES;return E=this.toString("hex",0,C).replace(/(.{2})/g,"$1 ").trim(),this.length>C&&(E+=" ... "),"<Buffer "+E+">"},i&&(f.prototype[i]=f.prototype.inspect),f.prototype.compare=function(E,C,$,q,J){if(mt(E,r)&&(E=f.from(E,E.offset,E.byteLength)),!f.isBuffer(E))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof E);if(C===void 0&&(C=0),$===void 0&&($=E?E.length:0),q===void 0&&(q=0),J===void 0&&(J=this.length),C<0||$>E.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===E)return 0;let ne=J-q,Ie=$-C;const ze=Math.min(ne,Ie),Ge=this.slice(q,J),Ce=E.slice(C,$);for(let Oe=0;Oe<ze;++Oe)if(Ge[Oe]!==Ce[Oe]){ne=Ge[Oe],Ie=Ce[Oe];break}return ne<Ie?-1:Ie<ne?1:0};function B(R,E,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,Ft(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 E=="string"&&(E=f.from(E,$)),f.isBuffer(E))return E.length===0?-1:D(R,E,C,$,q);if(typeof E=="number")return E=E&255,typeof r.prototype.indexOf=="function"?q?r.prototype.indexOf.call(R,E,C):r.prototype.lastIndexOf.call(R,E,C):D(R,[E],C,$,q);throw new TypeError("val must be string, number or Buffer")}function D(R,E,C,$,q){let J=1,ne=R.length,Ie=E.length;if($!==void 0&&($=String($).toLowerCase(),$==="ucs2"||$==="ucs-2"||$==="utf16le"||$==="utf-16le")){if(R.length<2||E.length<2)return-1;J=2,ne/=2,Ie/=2,C/=2}function ze(Ce,Oe){return J===1?Ce[Oe]:Ce.readUInt16BE(Oe*J)}let Ge;if(q){let Ce=-1;for(Ge=C;Ge<ne;Ge++)if(ze(R,Ge)===ze(E,Ce===-1?0:Ge-Ce)){if(Ce===-1&&(Ce=Ge),Ge-Ce+1===Ie)return Ce*J}else Ce!==-1&&(Ge-=Ge-Ce),Ce=-1}else for(C+Ie>ne&&(C=ne-Ie),Ge=C;Ge>=0;Ge--){let Ce=!0;for(let Oe=0;Oe<Ie;Oe++)if(ze(R,Ge+Oe)!==ze(E,Oe)){Ce=!1;break}if(Ce)return Ge}return-1}f.prototype.includes=function(E,C,$){return this.indexOf(E,C,$)!==-1},f.prototype.indexOf=function(E,C,$){return B(this,E,C,$,!0)},f.prototype.lastIndexOf=function(E,C,$){return B(this,E,C,$,!1)};function K(R,E,C,$){C=Number(C)||0;const q=R.length-C;$?($=Number($),$>q&&($=q)):$=q;const J=E.length;$>J/2&&($=J/2);let ne;for(ne=0;ne<$;++ne){const Ie=parseInt(E.substr(ne*2,2),16);if(Ft(Ie))return ne;R[C+ne]=Ie}return ne}function ae(R,E,C,$){return Ot(Hi(E,R.length-C),R,C,$)}function Z(R,E,C,$){return Ot(wi(E),R,C,$)}function oe(R,E,C,$){return Ot($i(E),R,C,$)}function le(R,E,C,$){return Ot(Mt(E,R.length-C),R,C,$)}f.prototype.write=function(E,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),E.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,E,C,$);case"utf8":case"utf-8":return ae(this,E,C,$);case"ascii":case"latin1":case"binary":return Z(this,E,C,$);case"base64":return oe(this,E,C,$);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return le(this,E,C,$);default:if(ne)throw new TypeError("Unknown encoding: "+q);q=(""+q).toLowerCase(),ne=!0}},f.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function he(R,E,C){return E===0&&C===R.length?e.fromByteArray(R):e.fromByteArray(R.slice(E,C))}function pe(R,E,C){C=Math.min(R.length,C);const $=[];let q=E;for(;q<C;){const J=R[q];let ne=null,Ie=J>239?4:J>223?3:J>191?2:1;if(q+Ie<=C){let ze,Ge,Ce,Oe;switch(Ie){case 1:J<128&&(ne=J);break;case 2:ze=R[q+1],(ze&192)===128&&(Oe=(J&31)<<6|ze&63,Oe>127&&(ne=Oe));break;case 3:ze=R[q+1],Ge=R[q+2],(ze&192)===128&&(Ge&192)===128&&(Oe=(J&15)<<12|(ze&63)<<6|Ge&63,Oe>2047&&(Oe<55296||Oe>57343)&&(ne=Oe));break;case 4:ze=R[q+1],Ge=R[q+2],Ce=R[q+3],(ze&192)===128&&(Ge&192)===128&&(Ce&192)===128&&(Oe=(J&15)<<18|(ze&63)<<12|(Ge&63)<<6|Ce&63,Oe>65535&&Oe<1114112&&(ne=Oe))}}ne===null?(ne=65533,Ie=1):ne>65535&&(ne-=65536,$.push(ne>>>10&1023|55296),ne=56320|ne&1023),$.push(ne),q+=Ie}return ee($)}const ge=4096;function ee(R){const E=R.length;if(E<=ge)return String.fromCharCode.apply(String,R);let C="",$=0;for(;$<E;)C+=String.fromCharCode.apply(String,R.slice($,$+=ge));return C}function Q(R,E,C){let $="";C=Math.min(R.length,C);for(let q=E;q<C;++q)$+=String.fromCharCode(R[q]&127);return $}function ye(R,E,C){let $="";C=Math.min(R.length,C);for(let q=E;q<C;++q)$+=String.fromCharCode(R[q]);return $}function re(R,E,C){const $=R.length;(!E||E<0)&&(E=0),(!C||C<0||C>$)&&(C=$);let q="";for(let J=E;J<C;++J)q+=qt[R[J]];return q}function ie(R,E,C){const $=R.slice(E,C);let q="";for(let J=0;J<$.length-1;J+=2)q+=String.fromCharCode($[J]+$[J+1]*256);return q}f.prototype.slice=function(E,C){const $=this.length;E=~~E,C=C===void 0?$:~~C,E<0?(E+=$,E<0&&(E=0)):E>$&&(E=$),C<0?(C+=$,C<0&&(C=0)):C>$&&(C=$),C<E&&(C=E);const q=this.subarray(E,C);return Object.setPrototypeOf(q,f.prototype),q};function be(R,E,C){if(R%1!==0||R<0)throw new RangeError("offset is not uint");if(R+E>C)throw new RangeError("Trying to access beyond buffer length")}f.prototype.readUintLE=f.prototype.readUIntLE=function(E,C,$){E=E>>>0,C=C>>>0,$||be(E,C,this.length);let q=this[E],J=1,ne=0;for(;++ne<C&&(J*=256);)q+=this[E+ne]*J;return q},f.prototype.readUintBE=f.prototype.readUIntBE=function(E,C,$){E=E>>>0,C=C>>>0,$||be(E,C,this.length);let q=this[E+--C],J=1;for(;C>0&&(J*=256);)q+=this[E+--C]*J;return q},f.prototype.readUint8=f.prototype.readUInt8=function(E,C){return E=E>>>0,C||be(E,1,this.length),this[E]},f.prototype.readUint16LE=f.prototype.readUInt16LE=function(E,C){return E=E>>>0,C||be(E,2,this.length),this[E]|this[E+1]<<8},f.prototype.readUint16BE=f.prototype.readUInt16BE=function(E,C){return E=E>>>0,C||be(E,2,this.length),this[E]<<8|this[E+1]},f.prototype.readUint32LE=f.prototype.readUInt32LE=function(E,C){return E=E>>>0,C||be(E,4,this.length),(this[E]|this[E+1]<<8|this[E+2]<<16)+this[E+3]*16777216},f.prototype.readUint32BE=f.prototype.readUInt32BE=function(E,C){return E=E>>>0,C||be(E,4,this.length),this[E]*16777216+(this[E+1]<<16|this[E+2]<<8|this[E+3])},f.prototype.readBigUInt64LE=Et(function(E){E=E>>>0,_t(E,"offset");const C=this[E],$=this[E+7];(C===void 0||$===void 0)&&lt(E,this.length-8);const q=C+this[++E]*2**8+this[++E]*2**16+this[++E]*2**24,J=this[++E]+this[++E]*2**8+this[++E]*2**16+$*2**24;return BigInt(q)+(BigInt(J)<<BigInt(32))}),f.prototype.readBigUInt64BE=Et(function(E){E=E>>>0,_t(E,"offset");const C=this[E],$=this[E+7];(C===void 0||$===void 0)&&lt(E,this.length-8);const q=C*2**24+this[++E]*2**16+this[++E]*2**8+this[++E],J=this[++E]*2**24+this[++E]*2**16+this[++E]*2**8+$;return(BigInt(q)<<BigInt(32))+BigInt(J)}),f.prototype.readIntLE=function(E,C,$){E=E>>>0,C=C>>>0,$||be(E,C,this.length);let q=this[E],J=1,ne=0;for(;++ne<C&&(J*=256);)q+=this[E+ne]*J;return J*=128,q>=J&&(q-=Math.pow(2,8*C)),q},f.prototype.readIntBE=function(E,C,$){E=E>>>0,C=C>>>0,$||be(E,C,this.length);let q=C,J=1,ne=this[E+--q];for(;q>0&&(J*=256);)ne+=this[E+--q]*J;return J*=128,ne>=J&&(ne-=Math.pow(2,8*C)),ne},f.prototype.readInt8=function(E,C){return E=E>>>0,C||be(E,1,this.length),this[E]&128?(255-this[E]+1)*-1:this[E]},f.prototype.readInt16LE=function(E,C){E=E>>>0,C||be(E,2,this.length);const $=this[E]|this[E+1]<<8;return $&32768?$|4294901760:$},f.prototype.readInt16BE=function(E,C){E=E>>>0,C||be(E,2,this.length);const $=this[E+1]|this[E]<<8;return $&32768?$|4294901760:$},f.prototype.readInt32LE=function(E,C){return E=E>>>0,C||be(E,4,this.length),this[E]|this[E+1]<<8|this[E+2]<<16|this[E+3]<<24},f.prototype.readInt32BE=function(E,C){return E=E>>>0,C||be(E,4,this.length),this[E]<<24|this[E+1]<<16|this[E+2]<<8|this[E+3]},f.prototype.readBigInt64LE=Et(function(E){E=E>>>0,_t(E,"offset");const C=this[E],$=this[E+7];(C===void 0||$===void 0)&&lt(E,this.length-8);const q=this[E+4]+this[E+5]*2**8+this[E+6]*2**16+($<<24);return(BigInt(q)<<BigInt(32))+BigInt(C+this[++E]*2**8+this[++E]*2**16+this[++E]*2**24)}),f.prototype.readBigInt64BE=Et(function(E){E=E>>>0,_t(E,"offset");const C=this[E],$=this[E+7];(C===void 0||$===void 0)&&lt(E,this.length-8);const q=(C<<24)+this[++E]*2**16+this[++E]*2**8+this[++E];return(BigInt(q)<<BigInt(32))+BigInt(this[++E]*2**24+this[++E]*2**16+this[++E]*2**8+$)}),f.prototype.readFloatLE=function(E,C){return E=E>>>0,C||be(E,4,this.length),t.read(this,E,!0,23,4)},f.prototype.readFloatBE=function(E,C){return E=E>>>0,C||be(E,4,this.length),t.read(this,E,!1,23,4)},f.prototype.readDoubleLE=function(E,C){return E=E>>>0,C||be(E,8,this.length),t.read(this,E,!0,52,8)},f.prototype.readDoubleBE=function(E,C){return E=E>>>0,C||be(E,8,this.length),t.read(this,E,!1,52,8)};function Te(R,E,C,$,q,J){if(!f.isBuffer(R))throw new TypeError('"buffer" argument must be a Buffer instance');if(E>q||E<J)throw new RangeError('"value" argument is out of bounds');if(C+$>R.length)throw new RangeError("Index out of range")}f.prototype.writeUintLE=f.prototype.writeUIntLE=function(E,C,$,q){if(E=+E,C=C>>>0,$=$>>>0,!q){const Ie=Math.pow(2,8*$)-1;Te(this,E,C,$,Ie,0)}let J=1,ne=0;for(this[C]=E&255;++ne<$&&(J*=256);)this[C+ne]=E/J&255;return C+$},f.prototype.writeUintBE=f.prototype.writeUIntBE=function(E,C,$,q){if(E=+E,C=C>>>0,$=$>>>0,!q){const Ie=Math.pow(2,8*$)-1;Te(this,E,C,$,Ie,0)}let J=$-1,ne=1;for(this[C+J]=E&255;--J>=0&&(ne*=256);)this[C+J]=E/ne&255;return C+$},f.prototype.writeUint8=f.prototype.writeUInt8=function(E,C,$){return E=+E,C=C>>>0,$||Te(this,E,C,1,255,0),this[C]=E&255,C+1},f.prototype.writeUint16LE=f.prototype.writeUInt16LE=function(E,C,$){return E=+E,C=C>>>0,$||Te(this,E,C,2,65535,0),this[C]=E&255,this[C+1]=E>>>8,C+2},f.prototype.writeUint16BE=f.prototype.writeUInt16BE=function(E,C,$){return E=+E,C=C>>>0,$||Te(this,E,C,2,65535,0),this[C]=E>>>8,this[C+1]=E&255,C+2},f.prototype.writeUint32LE=f.prototype.writeUInt32LE=function(E,C,$){return E=+E,C=C>>>0,$||Te(this,E,C,4,4294967295,0),this[C+3]=E>>>24,this[C+2]=E>>>16,this[C+1]=E>>>8,this[C]=E&255,C+4},f.prototype.writeUint32BE=f.prototype.writeUInt32BE=function(E,C,$){return E=+E,C=C>>>0,$||Te(this,E,C,4,4294967295,0),this[C]=E>>>24,this[C+1]=E>>>16,this[C+2]=E>>>8,this[C+3]=E&255,C+4};function xe(R,E,C,$,q){Ci(E,$,q,R,C,7);let J=Number(E&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(E>>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 Me(R,E,C,$,q){Ci(E,$,q,R,C,7);let J=Number(E&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(E>>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}f.prototype.writeBigUInt64LE=Et(function(E,C=0){return xe(this,E,C,BigInt(0),BigInt("0xffffffffffffffff"))}),f.prototype.writeBigUInt64BE=Et(function(E,C=0){return Me(this,E,C,BigInt(0),BigInt("0xffffffffffffffff"))}),f.prototype.writeIntLE=function(E,C,$,q){if(E=+E,C=C>>>0,!q){const ze=Math.pow(2,8*$-1);Te(this,E,C,$,ze-1,-ze)}let J=0,ne=1,Ie=0;for(this[C]=E&255;++J<$&&(ne*=256);)E<0&&Ie===0&&this[C+J-1]!==0&&(Ie=1),this[C+J]=(E/ne>>0)-Ie&255;return C+$},f.prototype.writeIntBE=function(E,C,$,q){if(E=+E,C=C>>>0,!q){const ze=Math.pow(2,8*$-1);Te(this,E,C,$,ze-1,-ze)}let J=$-1,ne=1,Ie=0;for(this[C+J]=E&255;--J>=0&&(ne*=256);)E<0&&Ie===0&&this[C+J+1]!==0&&(Ie=1),this[C+J]=(E/ne>>0)-Ie&255;return C+$},f.prototype.writeInt8=function(E,C,$){return E=+E,C=C>>>0,$||Te(this,E,C,1,127,-128),E<0&&(E=255+E+1),this[C]=E&255,C+1},f.prototype.writeInt16LE=function(E,C,$){return E=+E,C=C>>>0,$||Te(this,E,C,2,32767,-32768),this[C]=E&255,this[C+1]=E>>>8,C+2},f.prototype.writeInt16BE=function(E,C,$){return E=+E,C=C>>>0,$||Te(this,E,C,2,32767,-32768),this[C]=E>>>8,this[C+1]=E&255,C+2},f.prototype.writeInt32LE=function(E,C,$){return E=+E,C=C>>>0,$||Te(this,E,C,4,2147483647,-2147483648),this[C]=E&255,this[C+1]=E>>>8,this[C+2]=E>>>16,this[C+3]=E>>>24,C+4},f.prototype.writeInt32BE=function(E,C,$){return E=+E,C=C>>>0,$||Te(this,E,C,4,2147483647,-2147483648),E<0&&(E=4294967295+E+1),this[C]=E>>>24,this[C+1]=E>>>16,this[C+2]=E>>>8,this[C+3]=E&255,C+4},f.prototype.writeBigInt64LE=Et(function(E,C=0){return xe(this,E,C,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),f.prototype.writeBigInt64BE=Et(function(E,C=0){return Me(this,E,C,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Pe(R,E,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 je(R,E,C,$,q){return E=+E,C=C>>>0,q||Pe(R,E,C,4),t.write(R,E,C,$,23,4),C+4}f.prototype.writeFloatLE=function(E,C,$){return je(this,E,C,!0,$)},f.prototype.writeFloatBE=function(E,C,$){return je(this,E,C,!1,$)};function it(R,E,C,$,q){return E=+E,C=C>>>0,q||Pe(R,E,C,8),t.write(R,E,C,$,52,8),C+8}f.prototype.writeDoubleLE=function(E,C,$){return it(this,E,C,!0,$)},f.prototype.writeDoubleBE=function(E,C,$){return it(this,E,C,!1,$)},f.prototype.copy=function(E,C,$,q){if(!f.isBuffer(E))throw new TypeError("argument should be a Buffer");if($||($=0),!q&&q!==0&&(q=this.length),C>=E.length&&(C=E.length),C||(C=0),q>0&&q<$&&(q=$),q===$||E.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),E.length-C<q-$&&(q=E.length-C+$);const J=q-$;return this===E&&typeof r.prototype.copyWithin=="function"?this.copyWithin(C,$,q):r.prototype.set.call(E,this.subarray($,q),C),J},f.prototype.fill=function(E,C,$,q){if(typeof E=="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"&&!f.isEncoding(q))throw new TypeError("Unknown encoding: "+q);if(E.length===1){const ne=E.charCodeAt(0);(q==="utf8"&&ne<128||q==="latin1")&&(E=ne)}}else typeof E=="number"?E=E&255:typeof E=="boolean"&&(E=Number(E));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,E||(E=0);let J;if(typeof E=="number")for(J=C;J<$;++J)this[J]=E;else{const ne=f.isBuffer(E)?E:f.from(E,q),Ie=ne.length;if(Ie===0)throw new TypeError('The value "'+E+'" is invalid for argument "value"');for(J=0;J<$-C;++J)this[J+C]=ne[J%Ie]}return this};const et={};function $e(R,E,C){et[R]=class extends C{constructor(){super(),Object.defineProperty(this,"message",{value:E.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}`}}}$e("ERR_BUFFER_OUT_OF_BOUNDS",function(R){return R?`${R} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),$e("ERR_INVALID_ARG_TYPE",function(R,E){return`The "${R}" argument must be of type number. Received type ${typeof E}`},TypeError),$e("ERR_OUT_OF_RANGE",function(R,E,C){let $=`The value of "${R}" is out of range.`,q=C;return Number.isInteger(C)&&Math.abs(C)>2**32?q=Si(String(C)):typeof C=="bigint"&&(q=String(C),(C>BigInt(2)**BigInt(32)||C<-(BigInt(2)**BigInt(32)))&&(q=Si(q)),q+="n"),$+=` It must be ${E}. Received ${q}`,$},RangeError);function Si(R){let E="",C=R.length;const $=R[0]==="-"?1:0;for(;C>=$+4;C-=3)E=`_${R.slice(C-3,C)}${E}`;return`${R.slice(0,C)}${E}`}function ii(R,E,C){_t(E,"offset"),(R[E]===void 0||R[E+C]===void 0)&&lt(E,R.length-(C+1))}function Ci(R,E,C,$,q,J){if(R>C||R<E){const ne=typeof E=="bigint"?"n":"";let Ie;throw E===0||E===BigInt(0)?Ie=`>= 0${ne} and < 2${ne} ** ${(J+1)*8}${ne}`:Ie=`>= -(2${ne} ** ${(J+1)*8-1}${ne}) and < 2 ** ${(J+1)*8-1}${ne}`,new et.ERR_OUT_OF_RANGE("value",Ie,R)}ii($,q,J)}function _t(R,E){if(typeof R!="number")throw new et.ERR_INVALID_ARG_TYPE(E,"number",R)}function lt(R,E,C){throw Math.floor(R)!==R?(_t(R,C),new et.ERR_OUT_OF_RANGE("offset","an integer",R)):E<0?new et.ERR_BUFFER_OUT_OF_BOUNDS:new et.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${E}`,R)}const ln=/[^+/0-9A-Za-z-_]/g;function un(R){if(R=R.split("=")[0],R=R.trim().replace(ln,""),R.length<2)return"";for(;R.length%4!==0;)R=R+"=";return R}function Hi(R,E){E=E||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){(E-=3)>-1&&J.push(239,191,189);continue}else if(ne+1===$){(E-=3)>-1&&J.push(239,191,189);continue}q=C;continue}if(C<56320){(E-=3)>-1&&J.push(239,191,189),q=C;continue}C=(q-55296<<10|C-56320)+65536}else q&&(E-=3)>-1&&J.push(239,191,189);if(q=null,C<128){if((E-=1)<0)break;J.push(C)}else if(C<2048){if((E-=2)<0)break;J.push(C>>6|192,C&63|128)}else if(C<65536){if((E-=3)<0)break;J.push(C>>12|224,C>>6&63|128,C&63|128)}else if(C<1114112){if((E-=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 wi(R){const E=[];for(let C=0;C<R.length;++C)E.push(R.charCodeAt(C)&255);return E}function Mt(R,E){let C,$,q;const J=[];for(let ne=0;ne<R.length&&!((E-=2)<0);++ne)C=R.charCodeAt(ne),$=C>>8,q=C%256,J.push(q),J.push($);return J}function $i(R){return e.toByteArray(un(R))}function Ot(R,E,C,$){let q;for(q=0;q<$&&!(q+C>=E.length||q>=R.length);++q)E[q+C]=R[q];return q}function mt(R,E){return R instanceof E||R!=null&&R.constructor!=null&&R.constructor.name!=null&&R.constructor.name===E.name}function Ft(R){return R!==R}const qt=function(){const R="0123456789abcdef",E=new Array(256);for(let C=0;C<16;++C){const $=C*16;for(let q=0;q<16;++q)E[$+q]=R[C]+R[q]}return E}();function Et(R){return typeof BigInt>"u"?bt:R}function bt(){throw new Error("BigInt not supported")}})(Pg);const i0=Pg.Buffer,n0=an("peertube:player:segment-validator"),s0=10;class r0{constructor(e){Ue(this,"destroyed",!1),Ue(this,"segmentJSONPromise"),this.options=e}async validate(e,t,i,n=1){if(this.destroyed)return!1;this.loadSha256SegmentsPromiseIfNeeded();const r=My(e).split("/").pop(),o=(await this.segmentJSONPromise)[r];if(!o&&n>s0)return Ne.clientError(`Unknown segment name ${r} in segment validator`),!1;if(!o)return Ne.info(`Refetching sha segments for ${r}`),await jw(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 Ne.clientError(`Unknown segment name ${r}/${h} in segment validator`),!1;n0(`Validating ${r}`+(h?` range ${h}`:""));const p=await this.sha256Hex(i);if(p!==u)return Ne.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 Nl(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=>(Ne.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 Km(()=>import("./index-BDeSbJJz-CfH3UO9z.js"),__vite__mapDeps([0,1,2,3])).then(i=>i.i)).default;return new t.sha256().update(i0.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 a0=an("peertube:player:hls");class o0{constructor(e){this.options=e}async getPluginOptions(){const e=this.options.hls.segmentsSha256Url;e||Ne.info("No segmentsSha256Url found. Disabling P2P & redundancy.");const t=e?new Kw(this.options.hls.redundancyBaseUrls):null,i=e?new r0({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),f=this.options.hls.videoFiles.find(T=>T.resolution.id===p),m=jy({resolution:p,height:f?.height??u.height,width:f?.width??u.width});return h.localize(pf(m,f?.fps??u.frameRate))}};return a0("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"||Rn.getItem("peertube-videojs-p2p-consume-only")==="true")&&(Ne.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:Vy(this.options.stunServers),httpRequestSetup:(p,f,m,T)=>{const{requiresUserAuth:_,requiresPassword:b}=this.options,w=i?i.buildUrl(p):p,L=new Headers;return T&&L.set("Range",`bytes=${T.start}-${T.end??""}`),Nl(this.options.serverUrl,w)&&(b?L.set("x-peertube-video-password",this.options.videoPassword()):_&&L.set("Authorization",this.options.authorizationHeader())),Promise.resolve(new Request(w,{headers:L,signal:m}))},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 wr.SMALL_LATENCY:return{...e,isP2PDisabled:!0};case wr.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;Nl(this.options.serverUrl,o)&&(h?r.setRequestHeader("x-peertube-video-password",this.options.videoPassword()):u&&r.setRequestHeader("Authorization",this.options.authorizationHeader()))},...t},n=If();return n?{...i,abrEwmaDefaultEstimate:n*8,backBufferLength:90,startLevel:-1,testBandwidth:!1,debug:!1,enableWorker:!1}:i}getHLSLiveOptions(){switch(this.options.liveOptions.latencyMode){case wr.SMALL_LATENCY:return{liveSyncDurationCount:2};case wr.HIGH_LATENCY:return{liveSyncDurationCount:10};default:return{liveSyncDurationCount:5}}}getHLSVODOptions(){return{liveSyncDurationCount:5}}}class l0{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 xg=class ts{static getServerTranslations(e,t){const i=ts.getLocalePath(e,t);return i?fetch(i+"/server.json").then(n=>n.json()).catch(n=>{Ne.error("Cannot get server translations",n)}):Promise.resolve(void 0)}static loadLocaleInVideoJS(e,t,i){const n=ts.getLocalePath(e,t);if(!n)return Promise.resolve(void 0);let r;ts.videojsLocaleCache[n]?r=Promise.resolve(ts.videojsLocaleCache[n]):r=fetch(n+"/player.json").then(u=>u.json()).then(u=>(ts.videojsLocaleCache[n]=u,u)).catch(u=>{Ne.error("Cannot get player translations",u)});const o=da(t);return r.then(u=>i.addLanguage(Hy(o),u))}static getLocalePath(e,t){const i=da(t);if(!(!Uy(i)||ff(i)))return e+"/client/locales/"+i}};Ue(xg,"videojsLocaleCache",{});let u0=xg;X.getComponent("PlaybackRateMenuButton").prototype.controlText_="Speed";const Mg=X.getComponent("CaptionsButton");Mg.prototype.controlText_="Subtitles/CC";Mg.prototype.label_=" ";const nf=X.getComponent("PlayProgressBar");nf.prototype.options_.children.includes("timeTooltip")!==!0&&nf.prototype.options_.children.push("timeTooltip");class c0{constructor(e){Ue(this,"pluginsManager"),Ue(this,"videojsDecodeErrors",0),Ue(this,"player"),Ue(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 o0({...jo(this.options,["pluginsManager","serverUrl","authorizationHeader","stunServers"]),...jo(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 l0(jo(this.currentLoadOptions,["videoFileToken","webVideo","hls"]));this.player.webVideo(e.getPluginOptions())}async buildPlayerIfNeeded(){if(this.player)return;await u0.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)||kf(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(){mu()&&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}Ne.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}Ne.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 Gw({...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&&!ff(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,Ne.info("The browser is online"))},n=()=>{t||(this.player.el().appendChild(e),t=!0,Ne.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(){xl(Fl({shortUUID:n}),i.el())}},{label:i.localize("Copy the video URL at the current time"),listener:function(){const u=Fl({shortUUID:n});xl(cf({url:u,startTime:i.currentTime()}),i.el())}},{icon:"code",label:i.localize("Copy embed code"),listener:()=>{xl(Vw({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 S0=Object.freeze(Object.defineProperty({__proto__:null,PeerTubePlayer:c0,cleanupVideoWatch:uv,getAverageBandwidthInStore:If,getPlayerSessionId:Mf,getStoredLastSubtitle:Rf,getStoredMute:Sf,getStoredPreferredSubtitle:Df,getStoredTheater:Cf,getStoredVideoWatchHistory:yu,getStoredVolume:bf,saveAverageBandwidth:kf,saveLastSubtitle:Hl,saveMuteInStore:Lf,savePreferredSubtitle:Pf,saveTheaterInStore:Af,saveVideoWatchHistory:xf,saveVolumeInStore:wf,videojs:X},Symbol.toStringTag,{value:"Module"}));export{sf as g,S0 as p};
