function SI(s,e){for(var t=0;ti[n]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))i(n);new MutationObserver(n=>{for(const r of n)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function t(n){const r={};return n.integrity&&(r.integrity=n.integrity),n.referrerPolicy&&(r.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?r.credentials="include":n.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(n){if(n.ep)return;n.ep=!0;const r=t(n);fetch(n.href,r)}})();var Km=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Mc(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function EI(s){if(Object.prototype.hasOwnProperty.call(s,"__esModule"))return s;var e=s.default;if(typeof e=="function"){var t=function i(){var n=!1;try{n=this instanceof i}catch{}return n?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 ny={exports:{}},$d={};var J_;function wI(){if(J_)return $d;J_=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function t(i,n,r){var o=null;if(r!==void 0&&(o=""+r),n.key!==void 0&&(o=""+n.key),"key"in n){r={};for(var u in n)u!=="key"&&(r[u]=n[u])}else r=n;return n=r.ref,{$$typeof:s,type:i,key:o,ref:n!==void 0?n:null,props:r}}return $d.Fragment=e,$d.jsx=t,$d.jsxs=t,$d}var eS;function AI(){return eS||(eS=1,ny.exports=wI()),ny.exports}var y=AI(),ry={exports:{}},ii={};var tS;function CI(){if(tS)return ii;tS=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),t=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),n=Symbol.for("react.profiler"),r=Symbol.for("react.consumer"),o=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),p=Symbol.for("react.activity"),g=Symbol.iterator;function v(j){return j===null||typeof j!="object"?null:(j=g&&j[g]||j["@@iterator"],typeof j=="function"?j:null)}var b={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,S={};function D(j,ee,he){this.props=j,this.context=ee,this.refs=S,this.updater=he||b}D.prototype.isReactComponent={},D.prototype.setState=function(j,ee){if(typeof j!="object"&&typeof j!="function"&&j!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,j,ee,"setState")},D.prototype.forceUpdate=function(j){this.updater.enqueueForceUpdate(this,j,"forceUpdate")};function R(){}R.prototype=D.prototype;function L(j,ee,he){this.props=j,this.context=ee,this.refs=S,this.updater=he||b}var P=L.prototype=new R;P.constructor=L,_(P,D.prototype),P.isPureReactComponent=!0;var U=Array.isArray;function V(){}var M={H:null,A:null,T:null,S:null},G=Object.prototype.hasOwnProperty;function N(j,ee,he){var Te=he.ref;return{$$typeof:s,type:j,key:ee,ref:Te!==void 0?Te:null,props:he}}function O(j,ee){return N(j.type,ee,j.props)}function K(j){return typeof j=="object"&&j!==null&&j.$$typeof===s}function Q(j){var ee={"=":"=0",":":"=2"};return"$"+j.replace(/[=:]/g,function(he){return ee[he]})}var W=/\/+/g;function re(j,ee){return typeof j=="object"&&j!==null&&j.key!=null?Q(""+j.key):ee.toString(36)}function J(j){switch(j.status){case"fulfilled":return j.value;case"rejected":throw j.reason;default:switch(typeof j.status=="string"?j.then(V,V):(j.status="pending",j.then(function(ee){j.status==="pending"&&(j.status="fulfilled",j.value=ee)},function(ee){j.status==="pending"&&(j.status="rejected",j.reason=ee)})),j.status){case"fulfilled":return j.value;case"rejected":throw j.reason}}throw j}function Y(j,ee,he,Te,xe){var Ae=typeof j;(Ae==="undefined"||Ae==="boolean")&&(j=null);var Ke=!1;if(j===null)Ke=!0;else switch(Ae){case"bigint":case"string":case"number":Ke=!0;break;case"object":switch(j.$$typeof){case s:case e:Ke=!0;break;case f:return Ke=j._init,Y(Ke(j._payload),ee,he,Te,xe)}}if(Ke)return xe=xe(j),Ke=Te===""?"."+re(j,0):Te,U(xe)?(he="",Ke!=null&&(he=Ke.replace(W,"$&/")+"/"),Y(xe,ee,he,"",function(yt){return yt})):xe!=null&&(K(xe)&&(xe=O(xe,he+(xe.key==null||j&&j.key===xe.key?"":(""+xe.key).replace(W,"$&/")+"/")+Ke)),ee.push(xe)),1;Ke=0;var lt=Te===""?".":Te+":";if(U(j))for(var nt=0;nt>>1,ce=Y[ie];if(0>>1;ien(he,Z))Ten(xe,he)?(Y[ie]=xe,Y[Te]=Z,ie=Te):(Y[ie]=he,Y[ee]=Z,ie=ee);else if(Ten(xe,Z))Y[ie]=xe,Y[Te]=Z,ie=Te;else break e}}return z}function n(Y,z){var Z=Y.sortIndex-z.sortIndex;return Z!==0?Z:Y.id-z.id}if(s.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var r=performance;s.unstable_now=function(){return r.now()}}else{var o=Date,u=o.now();s.unstable_now=function(){return o.now()-u}}var c=[],d=[],f=1,p=null,g=3,v=!1,b=!1,_=!1,S=!1,D=typeof setTimeout=="function"?setTimeout:null,R=typeof clearTimeout=="function"?clearTimeout:null,L=typeof setImmediate<"u"?setImmediate:null;function P(Y){for(var z=t(d);z!==null;){if(z.callback===null)i(d);else if(z.startTime<=Y)i(d),z.sortIndex=z.expirationTime,e(c,z);else break;z=t(d)}}function U(Y){if(_=!1,P(Y),!b)if(t(c)!==null)b=!0,V||(V=!0,Q());else{var z=t(d);z!==null&&J(U,z.startTime-Y)}}var V=!1,M=-1,G=5,N=-1;function O(){return S?!0:!(s.unstable_now()-NY&&O());){var ie=p.callback;if(typeof ie=="function"){p.callback=null,g=p.priorityLevel;var ce=ie(p.expirationTime<=Y);if(Y=s.unstable_now(),typeof ce=="function"){p.callback=ce,P(Y),z=!0;break t}p===t(c)&&i(c),P(Y)}else i(c);p=t(c)}if(p!==null)z=!0;else{var j=t(d);j!==null&&J(U,j.startTime-Y),z=!1}}break e}finally{p=null,g=Z,v=!1}z=void 0}}finally{z?Q():V=!1}}}var Q;if(typeof L=="function")Q=function(){L(K)};else if(typeof MessageChannel<"u"){var W=new MessageChannel,re=W.port2;W.port1.onmessage=K,Q=function(){re.postMessage(null)}}else Q=function(){D(K,0)};function J(Y,z){M=D(function(){Y(s.unstable_now())},z)}s.unstable_IdlePriority=5,s.unstable_ImmediatePriority=1,s.unstable_LowPriority=4,s.unstable_NormalPriority=3,s.unstable_Profiling=null,s.unstable_UserBlockingPriority=2,s.unstable_cancelCallback=function(Y){Y.callback=null},s.unstable_forceFrameRate=function(Y){0>Y||125ie?(Y.sortIndex=Z,e(d,Y),t(c)===null&&Y===t(d)&&(_?(R(M),M=-1):_=!0,J(U,Z-ie))):(Y.sortIndex=ce,e(c,Y),b||v||(b=!0,V||(V=!0,Q()))),Y},s.unstable_shouldYield=O,s.unstable_wrapCallback=function(Y){var z=g;return function(){var Z=g;g=z;try{return Y.apply(this,arguments)}finally{g=Z}}}})(ly)),ly}var rS;function DI(){return rS||(rS=1,oy.exports=kI()),oy.exports}var uy={exports:{}},dn={};var aS;function LI(){if(aS)return dn;aS=1;var s=Ip();function e(c){var d="https://react.dev/errors/"+c;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(e){console.error(e)}}return s(),uy.exports=LI(),uy.exports}var lS;function RI(){if(lS)return Hd;lS=1;var s=DI(),e=Ip(),t=Jw();function i(a){var l="https://react.dev/errors/"+a;if(1ce||(a.current=ie[ce],ie[ce]=null,ce--)}function he(a,l){ce++,ie[ce]=a.current,a.current=l}var Te=j(null),xe=j(null),Ae=j(null),Ke=j(null);function lt(a,l){switch(he(Ae,l),he(xe,a),he(Te,null),l.nodeType){case 9:case 11:a=(a=l.documentElement)&&(a=a.namespaceURI)?__(a):0;break;default:if(a=l.tagName,l=l.namespaceURI)l=__(l),a=S_(l,a);else switch(a){case"svg":a=1;break;case"math":a=2;break;default:a=0}}ee(Te),he(Te,a)}function nt(){ee(Te),ee(xe),ee(Ae)}function yt(a){a.memoizedState!==null&&he(Ke,a);var l=Te.current,h=S_(l,a.type);l!==h&&(he(xe,a),he(Te,h))}function it(a){xe.current===a&&(ee(Te),ee(xe)),Ke.current===a&&(ee(Ke),Bd._currentValue=Z)}var Ot,pt;function xt(a){if(Ot===void 0)try{throw Error()}catch(h){var l=h.stack.trim().match(/\n( *(at )?)/);Ot=l&&l[1]||"",pt=-1)":-1T||me[m]!==Ie[T]){var ze=` `+me[m].replace(" at new "," at ");return a.displayName&&ze.includes("")&&(ze=ze.replace("",a.displayName)),ze}while(1<=m&&0<=T);break}}}finally{Pt=!1,Error.prepareStackTrace=h}return(h=a?a.displayName||a.name:"")?xt(h):""}function Nt(a,l){switch(a.tag){case 26:case 27:case 5:return xt(a.type);case 16:return xt("Lazy");case 13:return a.child!==l&&l!==null?xt("Suspense Fallback"):xt("Suspense");case 19:return xt("SuspenseList");case 0:case 15:return Ze(a.type,!1);case 11:return Ze(a.type.render,!1);case 1:return Ze(a.type,!0);case 31:return xt("Activity");default:return""}}function wt(a){try{var l="",h=null;do l+=Nt(a,h),h=a,a=a.return;while(a);return l}catch(m){return` Error generating stack: `+m.message+` `+m.stack}}var jt=Object.prototype.hasOwnProperty,gt=s.unstable_scheduleCallback,Dt=s.unstable_cancelCallback,ge=s.unstable_shouldYield,st=s.unstable_requestPaint,Ve=s.unstable_now,et=s.unstable_getCurrentPriorityLevel,vt=s.unstable_ImmediatePriority,ot=s.unstable_UserBlockingPriority,ht=s.unstable_NormalPriority,rt=s.unstable_LowPriority,Gt=s.unstable_IdlePriority,Bt=s.log,Lt=s.unstable_setDisableYieldValue,si=null,We=null;function Ct(a){if(typeof Bt=="function"&&Lt(a),We&&typeof We.setStrictMode=="function")try{We.setStrictMode(si,a)}catch{}}var Mt=Math.clz32?Math.clz32:Tt,pi=Math.log,Ei=Math.LN2;function Tt(a){return a>>>=0,a===0?32:31-(pi(a)/Ei|0)|0}var ft=256,ui=262144,Pe=4194304;function H(a){var l=a&42;if(l!==0)return l;switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return a&261888;case 262144:case 524288:case 1048576:case 2097152:return a&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return a&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return a}}function q(a,l,h){var m=a.pendingLanes;if(m===0)return 0;var T=0,E=a.suspendedLanes,F=a.pingedLanes;a=a.warmLanes;var X=m&134217727;return X!==0?(m=X&~E,m!==0?T=H(m):(F&=X,F!==0?T=H(F):h||(h=X&~a,h!==0&&(T=H(h))))):(X=m&~E,X!==0?T=H(X):F!==0?T=H(F):h||(h=m&~a,h!==0&&(T=H(h)))),T===0?0:l!==0&&l!==T&&(l&E)===0&&(E=T&-T,h=l&-l,E>=h||E===32&&(h&4194048)!==0)?l:T}function ne(a,l){return(a.pendingLanes&~(a.suspendedLanes&~a.pingedLanes)&l)===0}function Se(a,l){switch(a){case 1:case 2:case 4:case 8:case 64:return l+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return l+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Je(){var a=Pe;return Pe<<=1,(Pe&62914560)===0&&(Pe=4194304),a}function _t(a){for(var l=[],h=0;31>h;h++)l.push(a);return l}function ei(a,l){a.pendingLanes|=l,l!==268435456&&(a.suspendedLanes=0,a.pingedLanes=0,a.warmLanes=0)}function Ai(a,l,h,m,T,E){var F=a.pendingLanes;a.pendingLanes=h,a.suspendedLanes=0,a.pingedLanes=0,a.warmLanes=0,a.expiredLanes&=h,a.entangledLanes&=h,a.errorRecoveryDisabledLanes&=h,a.shellSuspendCounter=0;var X=a.entanglements,me=a.expirationTimes,Ie=a.hiddenUpdates;for(h=F&~h;0"u")return null;try{return a.activeElement||a.body}catch{return a.body}}var Ge=/[\n"\\]/g;function mt(a){return a.replace(Ge,function(l){return"\\"+l.charCodeAt(0).toString(16)+" "})}function Vt(a,l,h,m,T,E,F,X){a.name="",F!=null&&typeof F!="function"&&typeof F!="symbol"&&typeof F!="boolean"?a.type=F:a.removeAttribute("type"),l!=null?F==="number"?(l===0&&a.value===""||a.value!=l)&&(a.value=""+Me(l)):a.value!==""+Me(l)&&(a.value=""+Me(l)):F!=="submit"&&F!=="reset"||a.removeAttribute("value"),l!=null?qt(a,F,Me(l)):h!=null?qt(a,F,Me(h)):m!=null&&a.removeAttribute("value"),T==null&&E!=null&&(a.defaultChecked=!!E),T!=null&&(a.checked=T&&typeof T!="function"&&typeof T!="symbol"),X!=null&&typeof X!="function"&&typeof X!="symbol"&&typeof X!="boolean"?a.name=""+Me(X):a.removeAttribute("name")}function Wt(a,l,h,m,T,E,F,X){if(E!=null&&typeof E!="function"&&typeof E!="symbol"&&typeof E!="boolean"&&(a.type=E),l!=null||h!=null){if(!(E!=="submit"&&E!=="reset"||l!=null)){ct(a);return}h=h!=null?""+Me(h):"",l=l!=null?""+Me(l):h,X||l===a.value||(a.value=l),a.defaultValue=l}m=m??T,m=typeof m!="function"&&typeof m!="symbol"&&!!m,a.checked=X?a.checked:!!m,a.defaultChecked=!!m,F!=null&&typeof F!="function"&&typeof F!="symbol"&&typeof F!="boolean"&&(a.name=F),ct(a)}function qt(a,l,h){l==="number"&&pe(a.ownerDocument)===a||a.defaultValue===""+h||(a.defaultValue=""+h)}function Ft(a,l,h,m){if(a=a.options,l){l={};for(var T=0;T"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),uu=!1;if(qs)try{var hl={};Object.defineProperty(hl,"passive",{get:function(){uu=!0}}),window.addEventListener("test",hl,hl),window.removeEventListener("test",hl,hl)}catch{uu=!1}var Vr=null,cu=null,fl=null;function Uh(){if(fl)return fl;var a,l=cu,h=l.length,m,T="value"in Vr?Vr.value:Vr.textContent,E=T.length;for(a=0;a=xl),Xh=" ",Kc=!1;function vu(a,l){switch(a){case"keyup":return _g.indexOf(l.keyCode)!==-1;case"keydown":return l.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Qh(a){return a=a.detail,typeof a=="object"&&"data"in a?a.data:null}var fo=!1;function Sg(a,l){switch(a){case"compositionend":return Qh(l);case"keypress":return l.which!==32?null:(Kc=!0,Xh);case"textInput":return a=l.data,a===Xh&&Kc?null:a;default:return null}}function Yc(a,l){if(fo)return a==="compositionend"||!ho&&vu(a,l)?(a=Uh(),fl=cu=Vr=null,fo=!1,a):null;switch(a){case"paste":return null;case"keypress":if(!(l.ctrlKey||l.altKey||l.metaKey)||l.ctrlKey&&l.altKey){if(l.char&&1=l)return{node:h,offset:l-a};a=m}e:{for(;h;){if(h.nextSibling){h=h.nextSibling;break e}h=h.parentNode}h=void 0}h=po(h)}}function Da(a,l){return a&&l?a===l?!0:a&&a.nodeType===3?!1:l&&l.nodeType===3?Da(a,l.parentNode):"contains"in a?a.contains(l):a.compareDocumentPosition?!!(a.compareDocumentPosition(l)&16):!1:!1}function xu(a){a=a!=null&&a.ownerDocument!=null&&a.ownerDocument.defaultView!=null?a.ownerDocument.defaultView:window;for(var l=pe(a.document);l instanceof a.HTMLIFrameElement;){try{var h=typeof l.contentWindow.location.href=="string"}catch{h=!1}if(h)a=l.contentWindow;else break;l=pe(a.document)}return l}function ed(a){var l=a&&a.nodeName&&a.nodeName.toLowerCase();return l&&(l==="input"&&(a.type==="text"||a.type==="search"||a.type==="tel"||a.type==="url"||a.type==="password")||l==="textarea"||a.contentEditable==="true")}var Dg=qs&&"documentMode"in document&&11>=document.documentMode,go=null,td=null,yo=null,bu=!1;function id(a,l,h){var m=h.window===h?h.document:h.nodeType===9?h:h.ownerDocument;bu||go==null||go!==pe(m)||(m=go,"selectionStart"in m&&ed(m)?m={start:m.selectionStart,end:m.selectionEnd}:(m=(m.ownerDocument&&m.ownerDocument.defaultView||window).getSelection(),m={anchorNode:m.anchorNode,anchorOffset:m.anchorOffset,focusNode:m.focusNode,focusOffset:m.focusOffset}),yo&&zr(yo,m)||(yo=m,m=zf(td,"onSelect"),0>=F,T-=F,Qn=1<<32-Mt(l)+T|h<oi?(Si=Rt,Rt=null):Si=Rt.sibling;var Di=Oe(Ee,Rt,Re[oi],Ye);if(Di===null){Rt===null&&(Rt=Si);break}a&&Rt&&Di.alternate===null&&l(Ee,Rt),ve=E(Di,ve,oi),ki===null?Ut=Di:ki.sibling=Di,ki=Di,Rt=Si}if(oi===Re.length)return h(Ee,Rt),xi&&hi(Ee,oi),Ut;if(Rt===null){for(;oioi?(Si=Rt,Rt=null):Si=Rt.sibling;var Ho=Oe(Ee,Rt,Di.value,Ye);if(Ho===null){Rt===null&&(Rt=Si);break}a&&Rt&&Ho.alternate===null&&l(Ee,Rt),ve=E(Ho,ve,oi),ki===null?Ut=Ho:ki.sibling=Ho,ki=Ho,Rt=Si}if(Di.done)return h(Ee,Rt),xi&&hi(Ee,oi),Ut;if(Rt===null){for(;!Di.done;oi++,Di=Re.next())Di=Xe(Ee,Di.value,Ye),Di!==null&&(ve=E(Di,ve,oi),ki===null?Ut=Di:ki.sibling=Di,ki=Di);return xi&&hi(Ee,oi),Ut}for(Rt=m(Rt);!Di.done;oi++,Di=Re.next())Di=Ue(Rt,Ee,oi,Di.value,Ye),Di!==null&&(a&&Di.alternate!==null&&Rt.delete(Di.key===null?oi:Di.key),ve=E(Di,ve,oi),ki===null?Ut=Di:ki.sibling=Di,ki=Di);return a&&Rt.forEach(function(_I){return l(Ee,_I)}),xi&&hi(Ee,oi),Ut}function Vi(Ee,ve,Re,Ye){if(typeof Re=="object"&&Re!==null&&Re.type===_&&Re.key===null&&(Re=Re.props.children),typeof Re=="object"&&Re!==null){switch(Re.$$typeof){case v:e:{for(var Ut=Re.key;ve!==null;){if(ve.key===Ut){if(Ut=Re.type,Ut===_){if(ve.tag===7){h(Ee,ve.sibling),Ye=T(ve,Re.props.children),Ye.return=Ee,Ee=Ye;break e}}else if(ve.elementType===Ut||typeof Ut=="object"&&Ut!==null&&Ut.$$typeof===G&&Ll(Ut)===ve.type){h(Ee,ve.sibling),Ye=T(ve,Re.props),md(Ye,Re),Ye.return=Ee,Ee=Ye;break e}h(Ee,ve);break}else l(Ee,ve);ve=ve.sibling}Re.type===_?(Ye=Kr(Re.props.children,Ee.mode,Ye,Re.key),Ye.return=Ee,Ee=Ye):(Ye=ud(Re.type,Re.key,Re.props,null,Ee.mode,Ye),md(Ye,Re),Ye.return=Ee,Ee=Ye)}return F(Ee);case b:e:{for(Ut=Re.key;ve!==null;){if(ve.key===Ut)if(ve.tag===4&&ve.stateNode.containerInfo===Re.containerInfo&&ve.stateNode.implementation===Re.implementation){h(Ee,ve.sibling),Ye=T(ve,Re.children||[]),Ye.return=Ee,Ee=Ye;break e}else{h(Ee,ve);break}else l(Ee,ve);ve=ve.sibling}Ye=_o(Re,Ee.mode,Ye),Ye.return=Ee,Ee=Ye}return F(Ee);case G:return Re=Ll(Re),Vi(Ee,ve,Re,Ye)}if(J(Re))return kt(Ee,ve,Re,Ye);if(Q(Re)){if(Ut=Q(Re),typeof Ut!="function")throw Error(i(150));return Re=Ut.call(Re),zt(Ee,ve,Re,Ye)}if(typeof Re.then=="function")return Vi(Ee,ve,pf(Re),Ye);if(Re.$$typeof===L)return Vi(Ee,ve,Jt(Ee,Re),Ye);gf(Ee,Re)}return typeof Re=="string"&&Re!==""||typeof Re=="number"||typeof Re=="bigint"?(Re=""+Re,ve!==null&&ve.tag===6?(h(Ee,ve.sibling),Ye=T(ve,Re),Ye.return=Ee,Ee=Ye):(h(Ee,ve),Ye=wl(Re,Ee.mode,Ye),Ye.return=Ee,Ee=Ye),F(Ee)):h(Ee,ve)}return function(Ee,ve,Re,Ye){try{fd=0;var Ut=Vi(Ee,ve,Re,Ye);return Au=null,Ut}catch(Rt){if(Rt===wu||Rt===ff)throw Rt;var ki=gs(29,Rt,null,Ee.mode);return ki.lanes=Ye,ki.return=Ee,ki}}}var Il=fT(!0),mT=fT(!1),wo=!1;function Og(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Mg(a,l){a=a.updateQueue,l.updateQueue===a&&(l.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,callbacks:null})}function Ao(a){return{lane:a,tag:0,payload:null,callback:null,next:null}}function Co(a,l,h){var m=a.updateQueue;if(m===null)return null;if(m=m.shared,(Ri&2)!==0){var T=m.pending;return T===null?l.next=l:(l.next=T.next,T.next=l),m.pending=l,l=Su(a),lf(a,null,h),l}return _u(a,m,l,h),Su(a)}function pd(a,l,h){if(l=l.updateQueue,l!==null&&(l=l.shared,(h&4194048)!==0)){var m=l.lanes;m&=a.pendingLanes,h|=m,l.lanes=h,Ii(a,h)}}function Pg(a,l){var h=a.updateQueue,m=a.alternate;if(m!==null&&(m=m.updateQueue,h===m)){var T=null,E=null;if(h=h.firstBaseUpdate,h!==null){do{var F={lane:h.lane,tag:h.tag,payload:h.payload,callback:null,next:null};E===null?T=E=F:E=E.next=F,h=h.next}while(h!==null);E===null?T=E=l:E=E.next=l}else T=E=l;h={baseState:m.baseState,firstBaseUpdate:T,lastBaseUpdate:E,shared:m.shared,callbacks:m.callbacks},a.updateQueue=h;return}a=h.lastBaseUpdate,a===null?h.firstBaseUpdate=l:a.next=l,h.lastBaseUpdate=l}var Bg=!1;function gd(){if(Bg){var a=Ks;if(a!==null)throw a}}function yd(a,l,h,m){Bg=!1;var T=a.updateQueue;wo=!1;var E=T.firstBaseUpdate,F=T.lastBaseUpdate,X=T.shared.pending;if(X!==null){T.shared.pending=null;var me=X,Ie=me.next;me.next=null,F===null?E=Ie:F.next=Ie,F=me;var ze=a.alternate;ze!==null&&(ze=ze.updateQueue,X=ze.lastBaseUpdate,X!==F&&(X===null?ze.firstBaseUpdate=Ie:X.next=Ie,ze.lastBaseUpdate=me))}if(E!==null){var Xe=T.baseState;F=0,ze=Ie=me=null,X=E;do{var Oe=X.lane&-536870913,Ue=Oe!==X.lane;if(Ue?(_i&Oe)===Oe:(m&Oe)===Oe){Oe!==0&&Oe===fr&&(Bg=!0),ze!==null&&(ze=ze.next={lane:0,tag:X.tag,payload:X.payload,callback:null,next:null});e:{var kt=a,zt=X;Oe=l;var Vi=h;switch(zt.tag){case 1:if(kt=zt.payload,typeof kt=="function"){Xe=kt.call(Vi,Xe,Oe);break e}Xe=kt;break e;case 3:kt.flags=kt.flags&-65537|128;case 0:if(kt=zt.payload,Oe=typeof kt=="function"?kt.call(Vi,Xe,Oe):kt,Oe==null)break e;Xe=p({},Xe,Oe);break e;case 2:wo=!0}}Oe=X.callback,Oe!==null&&(a.flags|=64,Ue&&(a.flags|=8192),Ue=T.callbacks,Ue===null?T.callbacks=[Oe]:Ue.push(Oe))}else Ue={lane:Oe,tag:X.tag,payload:X.payload,callback:X.callback,next:null},ze===null?(Ie=ze=Ue,me=Xe):ze=ze.next=Ue,F|=Oe;if(X=X.next,X===null){if(X=T.shared.pending,X===null)break;Ue=X,X=Ue.next,Ue.next=null,T.lastBaseUpdate=Ue,T.shared.pending=null}}while(!0);ze===null&&(me=Xe),T.baseState=me,T.firstBaseUpdate=Ie,T.lastBaseUpdate=ze,E===null&&(T.shared.lanes=0),Io|=F,a.lanes=F,a.memoizedState=Xe}}function pT(a,l){if(typeof a!="function")throw Error(i(191,a));a.call(l)}function gT(a,l){var h=a.callbacks;if(h!==null)for(a.callbacks=null,a=0;aE?E:8;var F=Y.T,X={};Y.T=X,i0(a,!1,l,h);try{var me=T(),Ie=Y.S;if(Ie!==null&&Ie(X,me),me!==null&&typeof me=="object"&&typeof me.then=="function"){var ze=dR(me,m);bd(a,l,ze,ir(a))}else bd(a,l,m,ir(a))}catch(Xe){bd(a,l,{then:function(){},status:"rejected",reason:Xe},ir())}finally{z.p=E,F!==null&&X.types!==null&&(F.types=X.types),Y.T=F}}function yR(){}function e0(a,l,h,m){if(a.tag!==5)throw Error(i(476));var T=YT(a).queue;KT(a,T,l,Z,h===null?yR:function(){return WT(a),h(m)})}function YT(a){var l=a.memoizedState;if(l!==null)return l;l={memoizedState:Z,baseState:Z,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Oa,lastRenderedState:Z},next:null};var h={};return l.next={memoizedState:h,baseState:h,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Oa,lastRenderedState:h},next:null},a.memoizedState=l,a=a.alternate,a!==null&&(a.memoizedState=l),l}function WT(a){var l=YT(a);l.next===null&&(l=a.alternate.memoizedState),bd(a,l.next.queue,{},ir())}function t0(){return St(Bd)}function XT(){return ws().memoizedState}function QT(){return ws().memoizedState}function vR(a){for(var l=a.return;l!==null;){switch(l.tag){case 24:case 3:var h=ir();a=Ao(h);var m=Co(l,a,h);m!==null&&(Pn(m,l,h),pd(m,l,h)),l={cache:Ia()},a.payload=l;return}l=l.return}}function xR(a,l,h){var m=ir();h={lane:m,revertLane:0,gesture:null,action:h,hasEagerState:!1,eagerState:null,next:null},Af(a)?JT(l,h):(h=od(a,l,h,m),h!==null&&(Pn(h,a,m),e1(h,l,m)))}function ZT(a,l,h){var m=ir();bd(a,l,h,m)}function bd(a,l,h,m){var T={lane:m,revertLane:0,gesture:null,action:h,hasEagerState:!1,eagerState:null,next:null};if(Af(a))JT(l,T);else{var E=a.alternate;if(a.lanes===0&&(E===null||E.lanes===0)&&(E=l.lastRenderedReducer,E!==null))try{var F=l.lastRenderedState,X=E(F,h);if(T.hasEagerState=!0,T.eagerState=X,un(X,F))return _u(a,l,T,0),Yi===null&&Tu(),!1}catch{}if(h=od(a,l,T,m),h!==null)return Pn(h,a,m),e1(h,l,m),!0}return!1}function i0(a,l,h,m){if(m={lane:2,revertLane:O0(),gesture:null,action:m,hasEagerState:!1,eagerState:null,next:null},Af(a)){if(l)throw Error(i(479))}else l=od(a,h,m,2),l!==null&&Pn(l,a,2)}function Af(a){var l=a.alternate;return a===ai||l!==null&&l===ai}function JT(a,l){ku=xf=!0;var h=a.pending;h===null?l.next=l:(l.next=h.next,h.next=l),a.pending=l}function e1(a,l,h){if((h&4194048)!==0){var m=l.lanes;m&=a.pendingLanes,h|=m,l.lanes=h,Ii(a,h)}}var Td={readContext:St,use:_f,useCallback:ys,useContext:ys,useEffect:ys,useImperativeHandle:ys,useLayoutEffect:ys,useInsertionEffect:ys,useMemo:ys,useReducer:ys,useRef:ys,useState:ys,useDebugValue:ys,useDeferredValue:ys,useTransition:ys,useSyncExternalStore:ys,useId:ys,useHostTransitionStatus:ys,useFormState:ys,useActionState:ys,useOptimistic:ys,useMemoCache:ys,useCacheRefresh:ys};Td.useEffectEvent=ys;var t1={readContext:St,use:_f,useCallback:function(a,l){return gn().memoizedState=[a,l===void 0?null:l],a},useContext:St,useEffect:FT,useImperativeHandle:function(a,l,h){h=h!=null?h.concat([a]):null,Ef(4194308,4,HT.bind(null,l,a),h)},useLayoutEffect:function(a,l){return Ef(4194308,4,a,l)},useInsertionEffect:function(a,l){Ef(4,2,a,l)},useMemo:function(a,l){var h=gn();l=l===void 0?null:l;var m=a();if(Nl){Ct(!0);try{a()}finally{Ct(!1)}}return h.memoizedState=[m,l],m},useReducer:function(a,l,h){var m=gn();if(h!==void 0){var T=h(l);if(Nl){Ct(!0);try{h(l)}finally{Ct(!1)}}}else T=l;return m.memoizedState=m.baseState=T,a={pending:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:T},m.queue=a,a=a.dispatch=xR.bind(null,ai,a),[m.memoizedState,a]},useRef:function(a){var l=gn();return a={current:a},l.memoizedState=a},useState:function(a){a=Wg(a);var l=a.queue,h=ZT.bind(null,ai,l);return l.dispatch=h,[a.memoizedState,h]},useDebugValue:Zg,useDeferredValue:function(a,l){var h=gn();return Jg(h,a,l)},useTransition:function(){var a=Wg(!1);return a=KT.bind(null,ai,a.queue,!0,!1),gn().memoizedState=a,[!1,a]},useSyncExternalStore:function(a,l,h){var m=ai,T=gn();if(xi){if(h===void 0)throw Error(i(407));h=h()}else{if(h=l(),Yi===null)throw Error(i(349));(_i&127)!==0||_T(m,l,h)}T.memoizedState=h;var E={value:h,getSnapshot:l};return T.queue=E,FT(ET.bind(null,m,E,a),[a]),m.flags|=2048,Lu(9,{destroy:void 0},ST.bind(null,m,E,h,l),null),h},useId:function(){var a=gn(),l=Yi.identifierPrefix;if(xi){var h=en,m=Qn;h=(m&~(1<<32-Mt(m)-1)).toString(32)+h,l="_"+l+"R_"+h,h=bf++,0<\/script>",E=E.removeChild(E.firstChild);break;case"select":E=typeof m.is=="string"?F.createElement("select",{is:m.is}):F.createElement("select"),m.multiple?E.multiple=!0:m.size&&(E.size=m.size);break;default:E=typeof m.is=="string"?F.createElement(T,{is:m.is}):F.createElement(T)}}E[ri]=l,E[Yt]=m;e:for(F=l.child;F!==null;){if(F.tag===5||F.tag===6)E.appendChild(F.stateNode);else if(F.tag!==4&&F.tag!==27&&F.child!==null){F.child.return=F,F=F.child;continue}if(F===l)break e;for(;F.sibling===null;){if(F.return===null||F.return===l)break e;F=F.return}F.sibling.return=F.return,F=F.sibling}l.stateNode=E;e:switch(sn(E,T,m),T){case"button":case"input":case"select":case"textarea":m=!!m.autoFocus;break e;case"img":m=!0;break e;default:m=!1}m&&Pa(l)}}return ns(l),g0(l,l.type,a===null?null:a.memoizedProps,l.pendingProps,h),null;case 6:if(a&&l.stateNode!=null)a.memoizedProps!==m&&Pa(l);else{if(typeof m!="string"&&l.stateNode===null)throw Error(i(166));if(a=Ae.current,x(l)){if(a=l.stateNode,h=l.memoizedProps,m=null,T=ks,T!==null)switch(T.tag){case 27:case 5:m=T.memoizedProps}a[ri]=l,a=!!(a.nodeValue===h||m!==null&&m.suppressHydrationWarning===!0||b_(a.nodeValue,h)),a||Qr(l,!0)}else a=qf(a).createTextNode(m),a[ri]=l,l.stateNode=a}return ns(l),null;case 31:if(h=l.memoizedState,a===null||a.memoizedState!==null){if(m=x(l),h!==null){if(a===null){if(!m)throw Error(i(318));if(a=l.memoizedState,a=a!==null?a.dehydrated:null,!a)throw Error(i(557));a[ri]=l}else w(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;ns(l),a=!1}else h=k(),a!==null&&a.memoizedState!==null&&(a.memoizedState.hydrationErrors=h),a=!0;if(!a)return l.flags&256?(Jn(l),l):(Jn(l),null);if((l.flags&128)!==0)throw Error(i(558))}return ns(l),null;case 13:if(m=l.memoizedState,a===null||a.memoizedState!==null&&a.memoizedState.dehydrated!==null){if(T=x(l),m!==null&&m.dehydrated!==null){if(a===null){if(!T)throw Error(i(318));if(T=l.memoizedState,T=T!==null?T.dehydrated:null,!T)throw Error(i(317));T[ri]=l}else w(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;ns(l),T=!1}else T=k(),a!==null&&a.memoizedState!==null&&(a.memoizedState.hydrationErrors=T),T=!0;if(!T)return l.flags&256?(Jn(l),l):(Jn(l),null)}return Jn(l),(l.flags&128)!==0?(l.lanes=h,l):(h=m!==null,a=a!==null&&a.memoizedState!==null,h&&(m=l.child,T=null,m.alternate!==null&&m.alternate.memoizedState!==null&&m.alternate.memoizedState.cachePool!==null&&(T=m.alternate.memoizedState.cachePool.pool),E=null,m.memoizedState!==null&&m.memoizedState.cachePool!==null&&(E=m.memoizedState.cachePool.pool),E!==T&&(m.flags|=2048)),h!==a&&h&&(l.child.flags|=8192),Rf(l,l.updateQueue),ns(l),null);case 4:return nt(),a===null&&F0(l.stateNode.containerInfo),ns(l),null;case 10:return ue(l.type),ns(l),null;case 19:if(ee(Es),m=l.memoizedState,m===null)return ns(l),null;if(T=(l.flags&128)!==0,E=m.rendering,E===null)if(T)Sd(m,!1);else{if(vs!==0||a!==null&&(a.flags&128)!==0)for(a=l.child;a!==null;){if(E=vf(a),E!==null){for(l.flags|=128,Sd(m,!1),a=E.updateQueue,l.updateQueue=a,Rf(l,a),l.subtreeFlags=0,a=h,h=l.child;h!==null;)uf(h,a),h=h.sibling;return he(Es,Es.current&1|2),xi&&hi(l,m.treeForkCount),l.child}a=a.sibling}m.tail!==null&&Ve()>Pf&&(l.flags|=128,T=!0,Sd(m,!1),l.lanes=4194304)}else{if(!T)if(a=vf(E),a!==null){if(l.flags|=128,T=!0,a=a.updateQueue,l.updateQueue=a,Rf(l,a),Sd(m,!0),m.tail===null&&m.tailMode==="hidden"&&!E.alternate&&!xi)return ns(l),null}else 2*Ve()-m.renderingStartTime>Pf&&h!==536870912&&(l.flags|=128,T=!0,Sd(m,!1),l.lanes=4194304);m.isBackwards?(E.sibling=l.child,l.child=E):(a=m.last,a!==null?a.sibling=E:l.child=E,m.last=E)}return m.tail!==null?(a=m.tail,m.rendering=a,m.tail=a.sibling,m.renderingStartTime=Ve(),a.sibling=null,h=Es.current,he(Es,T?h&1|2:h&1),xi&&hi(l,m.treeForkCount),a):(ns(l),null);case 22:case 23:return Jn(l),Ug(),m=l.memoizedState!==null,a!==null?a.memoizedState!==null!==m&&(l.flags|=8192):m&&(l.flags|=8192),m?(h&536870912)!==0&&(l.flags&128)===0&&(ns(l),l.subtreeFlags&6&&(l.flags|=8192)):ns(l),h=l.updateQueue,h!==null&&Rf(l,h.retryQueue),h=null,a!==null&&a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(h=a.memoizedState.cachePool.pool),m=null,l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(m=l.memoizedState.cachePool.pool),m!==h&&(l.flags|=2048),a!==null&&ee(Dl),null;case 24:return h=null,a!==null&&(h=a.memoizedState.cache),l.memoizedState.cache!==h&&(l.flags|=2048),ue(es),ns(l),null;case 25:return null;case 30:return null}throw Error(i(156,l.tag))}function ER(a,l){switch(Ln(l),l.tag){case 1:return a=l.flags,a&65536?(l.flags=a&-65537|128,l):null;case 3:return ue(es),nt(),a=l.flags,(a&65536)!==0&&(a&128)===0?(l.flags=a&-65537|128,l):null;case 26:case 27:case 5:return it(l),null;case 31:if(l.memoizedState!==null){if(Jn(l),l.alternate===null)throw Error(i(340));w()}return a=l.flags,a&65536?(l.flags=a&-65537|128,l):null;case 13:if(Jn(l),a=l.memoizedState,a!==null&&a.dehydrated!==null){if(l.alternate===null)throw Error(i(340));w()}return a=l.flags,a&65536?(l.flags=a&-65537|128,l):null;case 19:return ee(Es),null;case 4:return nt(),null;case 10:return ue(l.type),null;case 22:case 23:return Jn(l),Ug(),a!==null&&ee(Dl),a=l.flags,a&65536?(l.flags=a&-65537|128,l):null;case 24:return ue(es),null;case 25:return null;default:return null}}function w1(a,l){switch(Ln(l),l.tag){case 3:ue(es),nt();break;case 26:case 27:case 5:it(l);break;case 4:nt();break;case 31:l.memoizedState!==null&&Jn(l);break;case 13:Jn(l);break;case 19:ee(Es);break;case 10:ue(l.type);break;case 22:case 23:Jn(l),Ug(),a!==null&&ee(Dl);break;case 24:ue(es)}}function Ed(a,l){try{var h=l.updateQueue,m=h!==null?h.lastEffect:null;if(m!==null){var T=m.next;h=T;do{if((h.tag&a)===a){m=void 0;var E=h.create,F=h.inst;m=E(),F.destroy=m}h=h.next}while(h!==T)}}catch(X){Bi(l,l.return,X)}}function Lo(a,l,h){try{var m=l.updateQueue,T=m!==null?m.lastEffect:null;if(T!==null){var E=T.next;m=E;do{if((m.tag&a)===a){var F=m.inst,X=F.destroy;if(X!==void 0){F.destroy=void 0,T=l;var me=h,Ie=X;try{Ie()}catch(ze){Bi(T,me,ze)}}}m=m.next}while(m!==E)}}catch(ze){Bi(l,l.return,ze)}}function A1(a){var l=a.updateQueue;if(l!==null){var h=a.stateNode;try{gT(l,h)}catch(m){Bi(a,a.return,m)}}}function C1(a,l,h){h.props=Ol(a.type,a.memoizedProps),h.state=a.memoizedState;try{h.componentWillUnmount()}catch(m){Bi(a,l,m)}}function wd(a,l){try{var h=a.ref;if(h!==null){switch(a.tag){case 26:case 27:case 5:var m=a.stateNode;break;case 30:m=a.stateNode;break;default:m=a.stateNode}typeof h=="function"?a.refCleanup=h(m):h.current=m}}catch(T){Bi(a,l,T)}}function ea(a,l){var h=a.ref,m=a.refCleanup;if(h!==null)if(typeof m=="function")try{m()}catch(T){Bi(a,l,T)}finally{a.refCleanup=null,a=a.alternate,a!=null&&(a.refCleanup=null)}else if(typeof h=="function")try{h(null)}catch(T){Bi(a,l,T)}else h.current=null}function k1(a){var l=a.type,h=a.memoizedProps,m=a.stateNode;try{e:switch(l){case"button":case"input":case"select":case"textarea":h.autoFocus&&m.focus();break e;case"img":h.src?m.src=h.src:h.srcSet&&(m.srcset=h.srcSet)}}catch(T){Bi(a,a.return,T)}}function y0(a,l,h){try{var m=a.stateNode;qR(m,a.type,h,l),m[Yt]=l}catch(T){Bi(a,a.return,T)}}function D1(a){return a.tag===5||a.tag===3||a.tag===26||a.tag===27&&Bo(a.type)||a.tag===4}function v0(a){e:for(;;){for(;a.sibling===null;){if(a.return===null||D1(a.return))return null;a=a.return}for(a.sibling.return=a.return,a=a.sibling;a.tag!==5&&a.tag!==6&&a.tag!==18;){if(a.tag===27&&Bo(a.type)||a.flags&2||a.child===null||a.tag===4)continue e;a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}function x0(a,l,h){var m=a.tag;if(m===5||m===6)a=a.stateNode,l?(h.nodeType===9?h.body:h.nodeName==="HTML"?h.ownerDocument.body:h).insertBefore(a,l):(l=h.nodeType===9?h.body:h.nodeName==="HTML"?h.ownerDocument.body:h,l.appendChild(a),h=h._reactRootContainer,h!=null||l.onclick!==null||(l.onclick=Yn));else if(m!==4&&(m===27&&Bo(a.type)&&(h=a.stateNode,l=null),a=a.child,a!==null))for(x0(a,l,h),a=a.sibling;a!==null;)x0(a,l,h),a=a.sibling}function If(a,l,h){var m=a.tag;if(m===5||m===6)a=a.stateNode,l?h.insertBefore(a,l):h.appendChild(a);else if(m!==4&&(m===27&&Bo(a.type)&&(h=a.stateNode),a=a.child,a!==null))for(If(a,l,h),a=a.sibling;a!==null;)If(a,l,h),a=a.sibling}function L1(a){var l=a.stateNode,h=a.memoizedProps;try{for(var m=a.type,T=l.attributes;T.length;)l.removeAttributeNode(T[0]);sn(l,m,h),l[ri]=a,l[Yt]=h}catch(E){Bi(a,a.return,E)}}var Ba=!1,Rs=!1,b0=!1,R1=typeof WeakSet=="function"?WeakSet:Set,Ys=null;function wR(a,l){if(a=a.containerInfo,$0=Jf,a=xu(a),ed(a)){if("selectionStart"in a)var h={start:a.selectionStart,end:a.selectionEnd};else e:{h=(h=a.ownerDocument)&&h.defaultView||window;var m=h.getSelection&&h.getSelection();if(m&&m.rangeCount!==0){h=m.anchorNode;var T=m.anchorOffset,E=m.focusNode;m=m.focusOffset;try{h.nodeType,E.nodeType}catch{h=null;break e}var F=0,X=-1,me=-1,Ie=0,ze=0,Xe=a,Oe=null;t:for(;;){for(var Ue;Xe!==h||T!==0&&Xe.nodeType!==3||(X=F+T),Xe!==E||m!==0&&Xe.nodeType!==3||(me=F+m),Xe.nodeType===3&&(F+=Xe.nodeValue.length),(Ue=Xe.firstChild)!==null;)Oe=Xe,Xe=Ue;for(;;){if(Xe===a)break t;if(Oe===h&&++Ie===T&&(X=F),Oe===E&&++ze===m&&(me=F),(Ue=Xe.nextSibling)!==null)break;Xe=Oe,Oe=Xe.parentNode}Xe=Ue}h=X===-1||me===-1?null:{start:X,end:me}}else h=null}h=h||{start:0,end:0}}else h=null;for(H0={focusedElem:a,selectionRange:h},Jf=!1,Ys=l;Ys!==null;)if(l=Ys,a=l.child,(l.subtreeFlags&1028)!==0&&a!==null)a.return=l,Ys=a;else for(;Ys!==null;){switch(l=Ys,E=l.alternate,a=l.flags,l.tag){case 0:if((a&4)!==0&&(a=l.updateQueue,a=a!==null?a.events:null,a!==null))for(h=0;h title"))),sn(E,m,h),E[ri]=a,Li(E),m=E;break e;case"link":var F=B_("link","href",T).get(m+(h.href||""));if(F){for(var X=0;XVi&&(F=Vi,Vi=zt,zt=F);var Ee=rs(X,zt),ve=rs(X,Vi);if(Ee&&ve&&(Ue.rangeCount!==1||Ue.anchorNode!==Ee.node||Ue.anchorOffset!==Ee.offset||Ue.focusNode!==ve.node||Ue.focusOffset!==ve.offset)){var Re=Xe.createRange();Re.setStart(Ee.node,Ee.offset),Ue.removeAllRanges(),zt>Vi?(Ue.addRange(Re),Ue.extend(ve.node,ve.offset)):(Re.setEnd(ve.node,ve.offset),Ue.addRange(Re))}}}}for(Xe=[],Ue=X;Ue=Ue.parentNode;)Ue.nodeType===1&&Xe.push({element:Ue,left:Ue.scrollLeft,top:Ue.scrollTop});for(typeof X.focus=="function"&&X.focus(),X=0;Xh?32:h,Y.T=null,h=C0,C0=null;var E=Oo,F=Ha;if(Ps=0,Mu=Oo=null,Ha=0,(Ri&6)!==0)throw Error(i(331));var X=Ri;if(Ri|=4,H1(E.current),U1(E,E.current,F,h),Ri=X,Rd(0,!1),We&&typeof We.onPostCommitFiberRoot=="function")try{We.onPostCommitFiberRoot(si,E)}catch{}return!0}finally{z.p=T,Y.T=m,a_(a,l)}}function l_(a,l,h){l=kn(h,l),l=a0(a.stateNode,l,2),a=Co(a,l,2),a!==null&&(ei(a,2),ta(a))}function Bi(a,l,h){if(a.tag===3)l_(a,a,h);else for(;l!==null;){if(l.tag===3){l_(l,a,h);break}else if(l.tag===1){var m=l.stateNode;if(typeof l.type.getDerivedStateFromError=="function"||typeof m.componentDidCatch=="function"&&(No===null||!No.has(m))){a=kn(h,a),h=u1(2),m=Co(l,h,2),m!==null&&(c1(h,m,l,a),ei(m,2),ta(m));break}}l=l.return}}function R0(a,l,h){var m=a.pingCache;if(m===null){m=a.pingCache=new kR;var T=new Set;m.set(l,T)}else T=m.get(l),T===void 0&&(T=new Set,m.set(l,T));T.has(h)||(S0=!0,T.add(h),a=NR.bind(null,a,l,h),l.then(a,a))}function NR(a,l,h){var m=a.pingCache;m!==null&&m.delete(l),a.pingedLanes|=a.suspendedLanes&h,a.warmLanes&=~h,Yi===a&&(_i&h)===h&&(vs===4||vs===3&&(_i&62914560)===_i&&300>Ve()-Mf?(Ri&2)===0&&Pu(a,0):E0|=h,Ou===_i&&(Ou=0)),ta(a)}function u_(a,l){l===0&&(l=Je()),a=Ra(a,l),a!==null&&(ei(a,l),ta(a))}function OR(a){var l=a.memoizedState,h=0;l!==null&&(h=l.retryLane),u_(a,h)}function MR(a,l){var h=0;switch(a.tag){case 31:case 13:var m=a.stateNode,T=a.memoizedState;T!==null&&(h=T.retryLane);break;case 19:m=a.stateNode;break;case 22:m=a.stateNode._retryCache;break;default:throw Error(i(314))}m!==null&&m.delete(l),u_(a,h)}function PR(a,l){return gt(a,l)}var Hf=null,Fu=null,I0=!1,Vf=!1,N0=!1,Po=0;function ta(a){a!==Fu&&a.next===null&&(Fu===null?Hf=Fu=a:Fu=Fu.next=a),Vf=!0,I0||(I0=!0,FR())}function Rd(a,l){if(!N0&&Vf){N0=!0;do for(var h=!1,m=Hf;m!==null;){if(a!==0){var T=m.pendingLanes;if(T===0)var E=0;else{var F=m.suspendedLanes,X=m.pingedLanes;E=(1<<31-Mt(42|a)+1)-1,E&=T&~(F&~X),E=E&201326741?E&201326741|1:E?E|2:0}E!==0&&(h=!0,f_(m,E))}else E=_i,E=q(m,m===Yi?E:0,m.cancelPendingCommit!==null||m.timeoutHandle!==-1),(E&3)===0||ne(m,E)||(h=!0,f_(m,E));m=m.next}while(h);N0=!1}}function BR(){c_()}function c_(){Vf=I0=!1;var a=0;Po!==0&&YR()&&(a=Po);for(var l=Ve(),h=null,m=Hf;m!==null;){var T=m.next,E=d_(m,l);E===0?(m.next=null,h===null?Hf=T:h.next=T,T===null&&(Fu=h)):(h=m,(a!==0||(E&3)!==0)&&(Vf=!0)),m=T}Ps!==0&&Ps!==5||Rd(a),Po!==0&&(Po=0)}function d_(a,l){for(var h=a.suspendedLanes,m=a.pingedLanes,T=a.expirationTimes,E=a.pendingLanes&-62914561;0X)break;var ze=me.transferSize,Xe=me.initiatorType;ze&&T_(Xe)&&(me=me.responseEnd,F+=ze*(me"u"?null:document;function N_(a,l,h){var m=Uu;if(m&&typeof l=="string"&&l){var T=mt(l);T='link[rel="'+a+'"][href="'+T+'"]',typeof h=="string"&&(T+='[crossorigin="'+h+'"]'),I_.has(T)||(I_.add(T),a={rel:a,crossOrigin:h,href:l},m.querySelector(T)===null&&(l=m.createElement("link"),sn(l,"link",a),Li(l),m.head.appendChild(l)))}}function sI(a){Va.D(a),N_("dns-prefetch",a,null)}function nI(a,l){Va.C(a,l),N_("preconnect",a,l)}function rI(a,l,h){Va.L(a,l,h);var m=Uu;if(m&&a&&l){var T='link[rel="preload"][as="'+mt(l)+'"]';l==="image"&&h&&h.imageSrcSet?(T+='[imagesrcset="'+mt(h.imageSrcSet)+'"]',typeof h.imageSizes=="string"&&(T+='[imagesizes="'+mt(h.imageSizes)+'"]')):T+='[href="'+mt(a)+'"]';var E=T;switch(l){case"style":E=ju(a);break;case"script":E=$u(a)}gr.has(E)||(a=p({rel:"preload",href:l==="image"&&h&&h.imageSrcSet?void 0:a,as:l},h),gr.set(E,a),m.querySelector(T)!==null||l==="style"&&m.querySelector(Md(E))||l==="script"&&m.querySelector(Pd(E))||(l=m.createElement("link"),sn(l,"link",a),Li(l),m.head.appendChild(l)))}}function aI(a,l){Va.m(a,l);var h=Uu;if(h&&a){var m=l&&typeof l.as=="string"?l.as:"script",T='link[rel="modulepreload"][as="'+mt(m)+'"][href="'+mt(a)+'"]',E=T;switch(m){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":E=$u(a)}if(!gr.has(E)&&(a=p({rel:"modulepreload",href:a},l),gr.set(E,a),h.querySelector(T)===null)){switch(m){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(h.querySelector(Pd(E)))return}m=h.createElement("link"),sn(m,"link",a),Li(m),h.head.appendChild(m)}}}function oI(a,l,h){Va.S(a,l,h);var m=Uu;if(m&&a){var T=Os(m).hoistableStyles,E=ju(a);l=l||"default";var F=T.get(E);if(!F){var X={loading:0,preload:null};if(F=m.querySelector(Md(E)))X.loading=5;else{a=p({rel:"stylesheet",href:a,"data-precedence":l},h),(h=gr.get(E))&&W0(a,h);var me=F=m.createElement("link");Li(me),sn(me,"link",a),me._p=new Promise(function(Ie,ze){me.onload=Ie,me.onerror=ze}),me.addEventListener("load",function(){X.loading|=1}),me.addEventListener("error",function(){X.loading|=2}),X.loading|=4,Yf(F,l,m)}F={type:"stylesheet",instance:F,count:1,state:X},T.set(E,F)}}}function lI(a,l){Va.X(a,l);var h=Uu;if(h&&a){var m=Os(h).hoistableScripts,T=$u(a),E=m.get(T);E||(E=h.querySelector(Pd(T)),E||(a=p({src:a,async:!0},l),(l=gr.get(T))&&X0(a,l),E=h.createElement("script"),Li(E),sn(E,"link",a),h.head.appendChild(E)),E={type:"script",instance:E,count:1,state:null},m.set(T,E))}}function uI(a,l){Va.M(a,l);var h=Uu;if(h&&a){var m=Os(h).hoistableScripts,T=$u(a),E=m.get(T);E||(E=h.querySelector(Pd(T)),E||(a=p({src:a,async:!0,type:"module"},l),(l=gr.get(T))&&X0(a,l),E=h.createElement("script"),Li(E),sn(E,"link",a),h.head.appendChild(E)),E={type:"script",instance:E,count:1,state:null},m.set(T,E))}}function O_(a,l,h,m){var T=(T=Ae.current)?Kf(T):null;if(!T)throw Error(i(446));switch(a){case"meta":case"title":return null;case"style":return typeof h.precedence=="string"&&typeof h.href=="string"?(l=ju(h.href),h=Os(T).hoistableStyles,m=h.get(l),m||(m={type:"style",instance:null,count:0,state:null},h.set(l,m)),m):{type:"void",instance:null,count:0,state:null};case"link":if(h.rel==="stylesheet"&&typeof h.href=="string"&&typeof h.precedence=="string"){a=ju(h.href);var E=Os(T).hoistableStyles,F=E.get(a);if(F||(T=T.ownerDocument||T,F={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},E.set(a,F),(E=T.querySelector(Md(a)))&&!E._p&&(F.instance=E,F.state.loading=5),gr.has(a)||(h={rel:"preload",as:"style",href:h.href,crossOrigin:h.crossOrigin,integrity:h.integrity,media:h.media,hrefLang:h.hrefLang,referrerPolicy:h.referrerPolicy},gr.set(a,h),E||cI(T,a,h,F.state))),l&&m===null)throw Error(i(528,""));return F}if(l&&m!==null)throw Error(i(529,""));return null;case"script":return l=h.async,h=h.src,typeof h=="string"&&l&&typeof l!="function"&&typeof l!="symbol"?(l=$u(h),h=Os(T).hoistableScripts,m=h.get(l),m||(m={type:"script",instance:null,count:0,state:null},h.set(l,m)),m):{type:"void",instance:null,count:0,state:null};default:throw Error(i(444,a))}}function ju(a){return'href="'+mt(a)+'"'}function Md(a){return'link[rel="stylesheet"]['+a+"]"}function M_(a){return p({},a,{"data-precedence":a.precedence,precedence:null})}function cI(a,l,h,m){a.querySelector('link[rel="preload"][as="style"]['+l+"]")?m.loading=1:(l=a.createElement("link"),m.preload=l,l.addEventListener("load",function(){return m.loading|=1}),l.addEventListener("error",function(){return m.loading|=2}),sn(l,"link",h),Li(l),a.head.appendChild(l))}function $u(a){return'[src="'+mt(a)+'"]'}function Pd(a){return"script[async]"+a}function P_(a,l,h){if(l.count++,l.instance===null)switch(l.type){case"style":var m=a.querySelector('style[data-href~="'+mt(h.href)+'"]');if(m)return l.instance=m,Li(m),m;var T=p({},h,{"data-href":h.href,"data-precedence":h.precedence,href:null,precedence:null});return m=(a.ownerDocument||a).createElement("style"),Li(m),sn(m,"style",T),Yf(m,h.precedence,a),l.instance=m;case"stylesheet":T=ju(h.href);var E=a.querySelector(Md(T));if(E)return l.state.loading|=4,l.instance=E,Li(E),E;m=M_(h),(T=gr.get(T))&&W0(m,T),E=(a.ownerDocument||a).createElement("link"),Li(E);var F=E;return F._p=new Promise(function(X,me){F.onload=X,F.onerror=me}),sn(E,"link",m),l.state.loading|=4,Yf(E,h.precedence,a),l.instance=E;case"script":return E=$u(h.src),(T=a.querySelector(Pd(E)))?(l.instance=T,Li(T),T):(m=h,(T=gr.get(E))&&(m=p({},h),X0(m,T)),a=a.ownerDocument||a,T=a.createElement("script"),Li(T),sn(T,"link",m),a.head.appendChild(T),l.instance=T);case"void":return null;default:throw Error(i(443,l.type))}else l.type==="stylesheet"&&(l.state.loading&4)===0&&(m=l.instance,l.state.loading|=4,Yf(m,h.precedence,a));return l.instance}function Yf(a,l,h){for(var m=h.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),T=m.length?m[m.length-1]:null,E=T,F=0;F title"):null)}function dI(a,l,h){if(h===1||l.itemProp!=null)return!1;switch(a){case"meta":case"title":return!0;case"style":if(typeof l.precedence!="string"||typeof l.href!="string"||l.href==="")break;return!0;case"link":if(typeof l.rel!="string"||typeof l.href!="string"||l.href===""||l.onLoad||l.onError)break;return l.rel==="stylesheet"?(a=l.disabled,typeof l.precedence=="string"&&a==null):!0;case"script":if(l.async&&typeof l.async!="function"&&typeof l.async!="symbol"&&!l.onLoad&&!l.onError&&l.src&&typeof l.src=="string")return!0}return!1}function U_(a){return!(a.type==="stylesheet"&&(a.state.loading&3)===0)}function hI(a,l,h,m){if(h.type==="stylesheet"&&(typeof m.media!="string"||matchMedia(m.media).matches!==!1)&&(h.state.loading&4)===0){if(h.instance===null){var T=ju(m.href),E=l.querySelector(Md(T));if(E){l=E._p,l!==null&&typeof l=="object"&&typeof l.then=="function"&&(a.count++,a=Xf.bind(a),l.then(a,a)),h.state.loading|=4,h.instance=E,Li(E);return}E=l.ownerDocument||l,m=M_(m),(T=gr.get(T))&&W0(m,T),E=E.createElement("link"),Li(E);var F=E;F._p=new Promise(function(X,me){F.onload=X,F.onerror=me}),sn(E,"link",m),h.instance=E}a.stylesheets===null&&(a.stylesheets=new Map),a.stylesheets.set(h,l),(l=h.state.preload)&&(h.state.loading&3)===0&&(a.count++,h=Xf.bind(a),l.addEventListener("load",h),l.addEventListener("error",h))}}var Q0=0;function fI(a,l){return a.stylesheets&&a.count===0&&Zf(a,a.stylesheets),0Q0?50:800)+l);return a.unsuspend=h,function(){a.unsuspend=null,clearTimeout(m),clearTimeout(T)}}:null}function Xf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Zf(this,this.stylesheets);else if(this.unsuspend){var a=this.unsuspend;this.unsuspend=null,a()}}}var Qf=null;function Zf(a,l){a.stylesheets=null,a.unsuspend!==null&&(a.count++,Qf=new Map,l.forEach(mI,a),Qf=null,Xf.call(a))}function mI(a,l){if(!(l.state.loading&4)){var h=Qf.get(a);if(h)var m=h.get(null);else{h=new Map,Qf.set(a,h);for(var T=a.querySelectorAll("link[data-precedence],style[data-precedence]"),E=0;E"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(e){console.error(e)}}return s(),ay.exports=RI(),ay.exports}var NI=II();function OI(...s){return s.filter(Boolean).join(" ")}const MI="inline-flex items-center justify-center font-semibold focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-50 disabled:cursor-not-allowed",PI={sm:"rounded-sm",md:"rounded-md",full:"rounded-full"},BI={xs:"px-2 py-1 text-xs",sm:"px-2.5 py-1.5 text-sm",md:"px-3 py-2 text-sm",lg:"px-3.5 py-2.5 text-sm"},FI={indigo:{primary:"!bg-indigo-600 !text-white shadow-sm hover:!bg-indigo-700 focus-visible:outline-indigo-600 dark:!bg-indigo-500 dark:hover:!bg-indigo-400 dark:focus-visible:outline-indigo-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-indigo-50 text-indigo-600 shadow-xs hover:bg-indigo-100 dark:bg-indigo-500/20 dark:text-indigo-400 dark:shadow-none dark:hover:bg-indigo-500/30"},blue:{primary:"!bg-blue-600 !text-white shadow-sm hover:!bg-blue-700 focus-visible:outline-blue-600 dark:!bg-blue-500 dark:hover:!bg-blue-400 dark:focus-visible:outline-blue-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-blue-50 text-blue-600 shadow-xs hover:bg-blue-100 dark:bg-blue-500/20 dark:text-blue-400 dark:shadow-none dark:hover:bg-blue-500/30"},emerald:{primary:"!bg-emerald-600 !text-white shadow-sm hover:!bg-emerald-700 focus-visible:outline-emerald-600 dark:!bg-emerald-500 dark:hover:!bg-emerald-400 dark:focus-visible:outline-emerald-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-emerald-50 text-emerald-700 shadow-xs hover:bg-emerald-100 dark:bg-emerald-500/20 dark:text-emerald-400 dark:shadow-none dark:hover:bg-emerald-500/30"},red:{primary:"!bg-red-600 !text-white shadow-sm hover:!bg-red-700 focus-visible:outline-red-600 dark:!bg-red-500 dark:hover:!bg-red-400 dark:focus-visible:outline-red-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-red-50 text-red-700 shadow-xs hover:bg-red-100 dark:bg-red-500/20 dark:text-red-400 dark:shadow-none dark:hover:bg-red-500/30"},amber:{primary:"!bg-amber-500 !text-white shadow-sm hover:!bg-amber-600 focus-visible:outline-amber-500 dark:!bg-amber-500 dark:hover:!bg-amber-400 dark:focus-visible:outline-amber-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-amber-50 text-amber-800 shadow-xs hover:bg-amber-100 dark:bg-amber-500/20 dark:text-amber-300 dark:shadow-none dark:hover:bg-amber-500/30"}};function UI(){return y.jsxs("svg",{viewBox:"0 0 24 24",className:"size-4 animate-spin","aria-hidden":"true",children:[y.jsx("circle",{cx:"12",cy:"12",r:"10",fill:"none",stroke:"currentColor",strokeWidth:"4",opacity:"0.25"}),y.jsx("path",{d:"M22 12a10 10 0 0 1-10 10",fill:"none",stroke:"currentColor",strokeWidth:"4",opacity:"0.9"})]})}function li({children:s,variant:e="primary",color:t="indigo",size:i="md",rounded:n="md",leadingIcon:r,trailingIcon:o,isLoading:u=!1,disabled:c,className:d,type:f="button",...p}){const g=r||o||u?"gap-x-1.5":"";return y.jsxs("button",{type:f,disabled:c||u,className:OI(MI,PI[n],BI[i],FI[t][e],g,d),...p,children:[u?y.jsx("span",{className:"-ml-0.5",children:y.jsx(UI,{})}):r&&y.jsx("span",{className:"-ml-0.5",children:r}),y.jsx("span",{children:s}),o&&!u&&y.jsx("span",{className:"-mr-0.5",children:o})]})}function eA(s){var e,t,i="";if(typeof s=="string"||typeof s=="number")i+=s;else if(typeof s=="object")if(Array.isArray(s)){var n=s.length;for(e=0;ee in s?jI(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,cy=(s,e,t)=>($I(s,typeof e!="symbol"?e+"":e,t),t);let HI=class{constructor(){cy(this,"current",this.detect()),cy(this,"handoffState","pending"),cy(this,"currentId",0)}set(e){this.current!==e&&(this.handoffState="pending",this.currentId=0,this.current=e)}reset(){this.set(this.detect())}nextId(){return++this.currentId}get isServer(){return this.current==="server"}get isClient(){return this.current==="client"}detect(){return typeof window>"u"||typeof document>"u"?"server":"client"}handoff(){this.handoffState==="pending"&&(this.handoffState="complete")}get isHandoffComplete(){return this.handoffState==="complete"}},ya=new HI;function Lh(s){var e;return ya.isServer?null:s==null?document:(e=s?.ownerDocument)!=null?e:document}function Iv(s){var e,t;return ya.isServer?null:s==null?document:(t=(e=s?.getRootNode)==null?void 0:e.call(s))!=null?t:document}function tA(s){var e,t;return(t=(e=Iv(s))==null?void 0:e.activeElement)!=null?t:null}function VI(s){return tA(s)===s}function Np(s){typeof queueMicrotask=="function"?queueMicrotask(s):Promise.resolve().then(s).catch(e=>setTimeout(()=>{throw e}))}function no(){let s=[],e={addEventListener(t,i,n,r){return t.addEventListener(i,n,r),e.add(()=>t.removeEventListener(i,n,r))},requestAnimationFrame(...t){let i=requestAnimationFrame(...t);return e.add(()=>cancelAnimationFrame(i))},nextFrame(...t){return e.requestAnimationFrame(()=>e.requestAnimationFrame(...t))},setTimeout(...t){let i=setTimeout(...t);return e.add(()=>clearTimeout(i))},microTask(...t){let i={current:!0};return Np(()=>{i.current&&t[0]()}),e.add(()=>{i.current=!1})},style(t,i,n){let r=t.style.getPropertyValue(i);return Object.assign(t.style,{[i]:n}),this.add(()=>{Object.assign(t.style,{[i]:r})})},group(t){let i=no();return t(i),this.add(()=>i.dispose())},add(t){return s.includes(t)||s.push(t),()=>{let i=s.indexOf(t);if(i>=0)for(let n of s.splice(i,1))n()}},dispose(){for(let t of s.splice(0))t()}};return e}function Op(){let[s]=A.useState(no);return A.useEffect(()=>()=>s.dispose(),[s]),s}let Gn=(s,e)=>{ya.isServer?A.useEffect(s,e):A.useLayoutEffect(s,e)};function ou(s){let e=A.useRef(s);return Gn(()=>{e.current=s},[s]),e}let Xi=function(s){let e=ou(s);return $t.useCallback((...t)=>e.current(...t),[e])};function Rh(s){return A.useMemo(()=>s,Object.values(s))}let GI=A.createContext(void 0);function zI(){return A.useContext(GI)}function Nv(...s){return Array.from(new Set(s.flatMap(e=>typeof e=="string"?e.split(" "):[]))).filter(Boolean).join(" ")}function io(s,e,...t){if(s in e){let n=e[s];return typeof n=="function"?n(...t):n}let i=new Error(`Tried to handle "${s}" but there is no handler defined. Only defined handlers are: ${Object.keys(e).map(n=>`"${n}"`).join(", ")}.`);throw Error.captureStackTrace&&Error.captureStackTrace(i,io),i}var Ym=(s=>(s[s.None=0]="None",s[s.RenderStrategy=1]="RenderStrategy",s[s.Static=2]="Static",s))(Ym||{}),sl=(s=>(s[s.Unmount=0]="Unmount",s[s.Hidden=1]="Hidden",s))(sl||{});function Sr(){let s=KI();return A.useCallback(e=>qI({mergeRefs:s,...e}),[s])}function qI({ourProps:s,theirProps:e,slot:t,defaultTag:i,features:n,visible:r=!0,name:o,mergeRefs:u}){u=u??YI;let c=iA(e,s);if(r)return am(c,t,i,o,u);let d=n??0;if(d&2){let{static:f=!1,...p}=c;if(f)return am(p,t,i,o,u)}if(d&1){let{unmount:f=!0,...p}=c;return io(f?0:1,{0(){return null},1(){return am({...p,hidden:!0,style:{display:"none"}},t,i,o,u)}})}return am(c,t,i,o,u)}function am(s,e={},t,i,n){let{as:r=t,children:o,refName:u="ref",...c}=dy(s,["unmount","static"]),d=s.ref!==void 0?{[u]:s.ref}:{},f=typeof o=="function"?o(e):o;"className"in c&&c.className&&typeof c.className=="function"&&(c.className=c.className(e)),c["aria-labelledby"]&&c["aria-labelledby"]===c.id&&(c["aria-labelledby"]=void 0);let p={};if(e){let g=!1,v=[];for(let[b,_]of Object.entries(e))typeof _=="boolean"&&(g=!0),_===!0&&v.push(b.replace(/([A-Z])/g,S=>`-${S.toLowerCase()}`));if(g){p["data-headlessui-state"]=v.join(" ");for(let b of v)p[`data-${b}`]=""}}if(nh(r)&&(Object.keys($l(c)).length>0||Object.keys($l(p)).length>0))if(!A.isValidElement(f)||Array.isArray(f)&&f.length>1||XI(f)){if(Object.keys($l(c)).length>0)throw new Error(['Passing props on "Fragment"!',"",`The current component <${i} /> is rendering a "Fragment".`,"However we need to passthrough the following props:",Object.keys($l(c)).concat(Object.keys($l(p))).map(g=>` - ${g}`).join(` `),"","You can apply a few solutions:",['Add an `as="..."` prop, to ensure that we render an actual element instead of a "Fragment".',"Render a single element as the child so that we can forward the props onto that element."].map(g=>` - ${g}`).join(` `)].join(` `))}else{let g=f.props,v=g?.className,b=typeof v=="function"?(...D)=>Nv(v(...D),c.className):Nv(v,c.className),_=b?{className:b}:{},S=iA(f.props,$l(dy(c,["ref"])));for(let D in p)D in S&&delete p[D];return A.cloneElement(f,Object.assign({},S,p,d,{ref:n(WI(f),d.ref)},_))}return A.createElement(r,Object.assign({},dy(c,["ref"]),!nh(r)&&d,!nh(r)&&p),f)}function KI(){let s=A.useRef([]),e=A.useCallback(t=>{for(let i of s.current)i!=null&&(typeof i=="function"?i(t):i.current=t)},[]);return(...t)=>{if(!t.every(i=>i==null))return s.current=t,e}}function YI(...s){return s.every(e=>e==null)?void 0:e=>{for(let t of s)t!=null&&(typeof t=="function"?t(e):t.current=e)}}function iA(...s){if(s.length===0)return{};if(s.length===1)return s[0];let e={},t={};for(let i of s)for(let n in i)n.startsWith("on")&&typeof i[n]=="function"?(t[n]!=null||(t[n]=[]),t[n].push(i[n])):e[n]=i[n];if(e.disabled||e["aria-disabled"])for(let i in t)/^(on(?:Click|Pointer|Mouse|Key)(?:Down|Up|Press)?)$/.test(i)&&(t[i]=[n=>{var r;return(r=n?.preventDefault)==null?void 0:r.call(n)}]);for(let i in t)Object.assign(e,{[i](n,...r){let o=t[i];for(let u of o){if((n instanceof Event||n?.nativeEvent instanceof Event)&&n.defaultPrevented)return;u(n,...r)}}});return e}function qn(s){var e;return Object.assign(A.forwardRef(s),{displayName:(e=s.displayName)!=null?e:s.name})}function $l(s){let e=Object.assign({},s);for(let t in e)e[t]===void 0&&delete e[t];return e}function dy(s,e=[]){let t=Object.assign({},s);for(let i of e)i in t&&delete t[i];return t}function WI(s){return $t.version.split(".")[0]>="19"?s.props.ref:s.ref}function nh(s){return s===A.Fragment||s===Symbol.for("react.fragment")}function XI(s){return nh(s.type)}let QI="span";var Wm=(s=>(s[s.None=1]="None",s[s.Focusable=2]="Focusable",s[s.Hidden=4]="Hidden",s))(Wm||{});function ZI(s,e){var t;let{features:i=1,...n}=s,r={ref:e,"aria-hidden":(i&2)===2?!0:(t=n["aria-hidden"])!=null?t:void 0,hidden:(i&4)===4?!0:void 0,style:{position:"fixed",top:1,left:1,width:1,height:0,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0",...(i&4)===4&&(i&2)!==2&&{display:"none"}}};return Sr()({ourProps:r,theirProps:n,slot:{},defaultTag:QI,name:"Hidden"})}let Ov=qn(ZI);function JI(s){return typeof s!="object"||s===null?!1:"nodeType"in s}function rl(s){return JI(s)&&"tagName"in s}function su(s){return rl(s)&&"accessKey"in s}function nl(s){return rl(s)&&"tabIndex"in s}function eN(s){return rl(s)&&"style"in s}function tN(s){return su(s)&&s.nodeName==="IFRAME"}function iN(s){return su(s)&&s.nodeName==="INPUT"}let sA=Symbol();function sN(s,e=!0){return Object.assign(s,{[sA]:e})}function wa(...s){let e=A.useRef(s);A.useEffect(()=>{e.current=s},[s]);let t=Xi(i=>{for(let n of e.current)n!=null&&(typeof n=="function"?n(i):n.current=i)});return s.every(i=>i==null||i?.[sA])?void 0:t}let Fx=A.createContext(null);Fx.displayName="DescriptionContext";function nA(){let s=A.useContext(Fx);if(s===null){let e=new Error("You used a component, but it is not inside a relevant parent.");throw Error.captureStackTrace&&Error.captureStackTrace(e,nA),e}return s}function nN(){let[s,e]=A.useState([]);return[s.length>0?s.join(" "):void 0,A.useMemo(()=>function(t){let i=Xi(r=>(e(o=>[...o,r]),()=>e(o=>{let u=o.slice(),c=u.indexOf(r);return c!==-1&&u.splice(c,1),u}))),n=A.useMemo(()=>({register:i,slot:t.slot,name:t.name,props:t.props,value:t.value}),[i,t.slot,t.name,t.props,t.value]);return $t.createElement(Fx.Provider,{value:n},t.children)},[e])]}let rN="p";function aN(s,e){let t=A.useId(),i=zI(),{id:n=`headlessui-description-${t}`,...r}=s,o=nA(),u=wa(e);Gn(()=>o.register(n),[n,o.register]);let c=Rh({...o.slot,disabled:i||!1}),d={ref:u,...o.props,id:n};return Sr()({ourProps:d,theirProps:r,slot:c,defaultTag:rN,name:o.name||"Description"})}let oN=qn(aN),lN=Object.assign(oN,{});var rA=(s=>(s.Space=" ",s.Enter="Enter",s.Escape="Escape",s.Backspace="Backspace",s.Delete="Delete",s.ArrowLeft="ArrowLeft",s.ArrowUp="ArrowUp",s.ArrowRight="ArrowRight",s.ArrowDown="ArrowDown",s.Home="Home",s.End="End",s.PageUp="PageUp",s.PageDown="PageDown",s.Tab="Tab",s))(rA||{});let uN=A.createContext(()=>{});function cN({value:s,children:e}){return $t.createElement(uN.Provider,{value:s},e)}let aA=class extends Map{constructor(e){super(),this.factory=e}get(e){let t=super.get(e);return t===void 0&&(t=this.factory(e),this.set(e,t)),t}};var dN=Object.defineProperty,hN=(s,e,t)=>e in s?dN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,fN=(s,e,t)=>(hN(s,e+"",t),t),oA=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},yr=(s,e,t)=>(oA(s,e,"read from private field"),t?t.call(s):e.get(s)),hy=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t)},cS=(s,e,t,i)=>(oA(s,e,"write to private field"),e.set(s,t),t),ra,Qd,Zd;let mN=class{constructor(e){hy(this,ra,{}),hy(this,Qd,new aA(()=>new Set)),hy(this,Zd,new Set),fN(this,"disposables",no()),cS(this,ra,e),ya.isServer&&this.disposables.microTask(()=>{this.dispose()})}dispose(){this.disposables.dispose()}get state(){return yr(this,ra)}subscribe(e,t){if(ya.isServer)return()=>{};let i={selector:e,callback:t,current:e(yr(this,ra))};return yr(this,Zd).add(i),this.disposables.add(()=>{yr(this,Zd).delete(i)})}on(e,t){return ya.isServer?()=>{}:(yr(this,Qd).get(e).add(t),this.disposables.add(()=>{yr(this,Qd).get(e).delete(t)}))}send(e){let t=this.reduce(yr(this,ra),e);if(t!==yr(this,ra)){cS(this,ra,t);for(let i of yr(this,Zd)){let n=i.selector(yr(this,ra));lA(i.current,n)||(i.current=n,i.callback(n))}for(let i of yr(this,Qd).get(e.type))i(yr(this,ra),e)}}};ra=new WeakMap,Qd=new WeakMap,Zd=new WeakMap;function lA(s,e){return Object.is(s,e)?!0:typeof s!="object"||s===null||typeof e!="object"||e===null?!1:Array.isArray(s)&&Array.isArray(e)?s.length!==e.length?!1:fy(s[Symbol.iterator](),e[Symbol.iterator]()):s instanceof Map&&e instanceof Map||s instanceof Set&&e instanceof Set?s.size!==e.size?!1:fy(s.entries(),e.entries()):dS(s)&&dS(e)?fy(Object.entries(s)[Symbol.iterator](),Object.entries(e)[Symbol.iterator]()):!1}function fy(s,e){do{let t=s.next(),i=e.next();if(t.done&&i.done)return!0;if(t.done||i.done||!Object.is(t.value,i.value))return!1}while(!0)}function dS(s){if(Object.prototype.toString.call(s)!=="[object Object]")return!1;let e=Object.getPrototypeOf(s);return e===null||Object.getPrototypeOf(e)===null}var pN=Object.defineProperty,gN=(s,e,t)=>e in s?pN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,hS=(s,e,t)=>(gN(s,typeof e!="symbol"?e+"":e,t),t),yN=(s=>(s[s.Push=0]="Push",s[s.Pop=1]="Pop",s))(yN||{});let vN={0(s,e){let t=e.id,i=s.stack,n=s.stack.indexOf(t);if(n!==-1){let r=s.stack.slice();return r.splice(n,1),r.push(t),i=r,{...s,stack:i}}return{...s,stack:[...s.stack,t]}},1(s,e){let t=e.id,i=s.stack.indexOf(t);if(i===-1)return s;let n=s.stack.slice();return n.splice(i,1),{...s,stack:n}}},xN=class uA extends mN{constructor(){super(...arguments),hS(this,"actions",{push:e=>this.send({type:0,id:e}),pop:e=>this.send({type:1,id:e})}),hS(this,"selectors",{isTop:(e,t)=>e.stack[e.stack.length-1]===t,inStack:(e,t)=>e.stack.includes(t)})}static new(){return new uA({stack:[]})}reduce(e,t){return io(t.type,vN,e,t)}};const cA=new aA(()=>xN.new());var my={exports:{}},py={};var fS;function bN(){if(fS)return py;fS=1;var s=Ip();function e(c,d){return c===d&&(c!==0||1/c===1/d)||c!==c&&d!==d}var t=typeof Object.is=="function"?Object.is:e,i=s.useSyncExternalStore,n=s.useRef,r=s.useEffect,o=s.useMemo,u=s.useDebugValue;return py.useSyncExternalStoreWithSelector=function(c,d,f,p,g){var v=n(null);if(v.current===null){var b={hasValue:!1,value:null};v.current=b}else b=v.current;v=o(function(){function S(U){if(!D){if(D=!0,R=U,U=p(U),g!==void 0&&b.hasValue){var V=b.value;if(g(V,U))return L=V}return L=U}if(V=L,t(R,U))return V;var M=p(U);return g!==void 0&&g(V,M)?(R=U,V):(R=U,L=M)}var D=!1,R,L,P=f===void 0?null:f;return[function(){return S(d())},P===null?void 0:function(){return S(P())}]},[d,f,p,g]);var _=i(c,v[0],v[1]);return r(function(){b.hasValue=!0,b.value=_},[_]),u(_),_},py}var mS;function TN(){return mS||(mS=1,my.exports=bN()),my.exports}var _N=TN();function dA(s,e,t=lA){return _N.useSyncExternalStoreWithSelector(Xi(i=>s.subscribe(SN,i)),Xi(()=>s.state),Xi(()=>s.state),Xi(e),t)}function SN(s){return s}function Ih(s,e){let t=A.useId(),i=cA.get(e),[n,r]=dA(i,A.useCallback(o=>[i.selectors.isTop(o,t),i.selectors.inStack(o,t)],[i,t]));return Gn(()=>{if(s)return i.actions.push(t),()=>i.actions.pop(t)},[i,s,t]),s?r?n:!0:!1}let Mv=new Map,rh=new Map;function pS(s){var e;let t=(e=rh.get(s))!=null?e:0;return rh.set(s,t+1),t!==0?()=>gS(s):(Mv.set(s,{"aria-hidden":s.getAttribute("aria-hidden"),inert:s.inert}),s.setAttribute("aria-hidden","true"),s.inert=!0,()=>gS(s))}function gS(s){var e;let t=(e=rh.get(s))!=null?e:1;if(t===1?rh.delete(s):rh.set(s,t-1),t!==1)return;let i=Mv.get(s);i&&(i["aria-hidden"]===null?s.removeAttribute("aria-hidden"):s.setAttribute("aria-hidden",i["aria-hidden"]),s.inert=i.inert,Mv.delete(s))}function EN(s,{allowed:e,disallowed:t}={}){let i=Ih(s,"inert-others");Gn(()=>{var n,r;if(!i)return;let o=no();for(let c of(n=t?.())!=null?n:[])c&&o.add(pS(c));let u=(r=e?.())!=null?r:[];for(let c of u){if(!c)continue;let d=Lh(c);if(!d)continue;let f=c.parentElement;for(;f&&f!==d.body;){for(let p of f.children)u.some(g=>p.contains(g))||o.add(pS(p));f=f.parentElement}}return o.dispose},[i,e,t])}function wN(s,e,t){let i=ou(n=>{let r=n.getBoundingClientRect();r.x===0&&r.y===0&&r.width===0&&r.height===0&&t()});A.useEffect(()=>{if(!s)return;let n=e===null?null:su(e)?e:e.current;if(!n)return;let r=no();if(typeof ResizeObserver<"u"){let o=new ResizeObserver(()=>i.current(n));o.observe(n),r.add(()=>o.disconnect())}if(typeof IntersectionObserver<"u"){let o=new IntersectionObserver(()=>i.current(n));o.observe(n),r.add(()=>o.disconnect())}return()=>r.dispose()},[e,i,s])}let Xm=["[contentEditable=true]","[tabindex]","a[href]","area[href]","button:not([disabled])","iframe","input:not([disabled])","select:not([disabled])","details>summary","textarea:not([disabled])"].map(s=>`${s}:not([tabindex='-1'])`).join(","),AN=["[data-autofocus]"].map(s=>`${s}:not([tabindex='-1'])`).join(",");var Qa=(s=>(s[s.First=1]="First",s[s.Previous=2]="Previous",s[s.Next=4]="Next",s[s.Last=8]="Last",s[s.WrapAround=16]="WrapAround",s[s.NoScroll=32]="NoScroll",s[s.AutoFocus=64]="AutoFocus",s))(Qa||{}),Pv=(s=>(s[s.Error=0]="Error",s[s.Overflow=1]="Overflow",s[s.Success=2]="Success",s[s.Underflow=3]="Underflow",s))(Pv||{}),CN=(s=>(s[s.Previous=-1]="Previous",s[s.Next=1]="Next",s))(CN||{});function kN(s=document.body){return s==null?[]:Array.from(s.querySelectorAll(Xm)).sort((e,t)=>Math.sign((e.tabIndex||Number.MAX_SAFE_INTEGER)-(t.tabIndex||Number.MAX_SAFE_INTEGER)))}function DN(s=document.body){return s==null?[]:Array.from(s.querySelectorAll(AN)).sort((e,t)=>Math.sign((e.tabIndex||Number.MAX_SAFE_INTEGER)-(t.tabIndex||Number.MAX_SAFE_INTEGER)))}var hA=(s=>(s[s.Strict=0]="Strict",s[s.Loose=1]="Loose",s))(hA||{});function LN(s,e=0){var t;return s===((t=Lh(s))==null?void 0:t.body)?!1:io(e,{0(){return s.matches(Xm)},1(){let i=s;for(;i!==null;){if(i.matches(Xm))return!0;i=i.parentElement}return!1}})}var RN=(s=>(s[s.Keyboard=0]="Keyboard",s[s.Mouse=1]="Mouse",s))(RN||{});typeof window<"u"&&typeof document<"u"&&(document.addEventListener("keydown",s=>{s.metaKey||s.altKey||s.ctrlKey||(document.documentElement.dataset.headlessuiFocusVisible="")},!0),document.addEventListener("click",s=>{s.detail===1?delete document.documentElement.dataset.headlessuiFocusVisible:s.detail===0&&(document.documentElement.dataset.headlessuiFocusVisible="")},!0));function eo(s){s?.focus({preventScroll:!0})}let IN=["textarea","input"].join(",");function NN(s){var e,t;return(t=(e=s?.matches)==null?void 0:e.call(s,IN))!=null?t:!1}function ON(s,e=t=>t){return s.slice().sort((t,i)=>{let n=e(t),r=e(i);if(n===null||r===null)return 0;let o=n.compareDocumentPosition(r);return o&Node.DOCUMENT_POSITION_FOLLOWING?-1:o&Node.DOCUMENT_POSITION_PRECEDING?1:0})}function ah(s,e,{sorted:t=!0,relativeTo:i=null,skipElements:n=[]}={}){let r=Array.isArray(s)?s.length>0?Iv(s[0]):document:Iv(s),o=Array.isArray(s)?t?ON(s):s:e&64?DN(s):kN(s);n.length>0&&o.length>1&&(o=o.filter(v=>!n.some(b=>b!=null&&"current"in b?b?.current===v:b===v))),i=i??r?.activeElement;let u=(()=>{if(e&5)return 1;if(e&10)return-1;throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last")})(),c=(()=>{if(e&1)return 0;if(e&2)return Math.max(0,o.indexOf(i))-1;if(e&4)return Math.max(0,o.indexOf(i))+1;if(e&8)return o.length-1;throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last")})(),d=e&32?{preventScroll:!0}:{},f=0,p=o.length,g;do{if(f>=p||f+p<=0)return 0;let v=c+f;if(e&16)v=(v+p)%p;else{if(v<0)return 3;if(v>=p)return 1}g=o[v],g?.focus(d),f+=u}while(g!==tA(g));return e&6&&NN(g)&&g.select(),2}function fA(){return/iPhone/gi.test(window.navigator.platform)||/Mac/gi.test(window.navigator.platform)&&window.navigator.maxTouchPoints>0}function MN(){return/Android/gi.test(window.navigator.userAgent)}function yS(){return fA()||MN()}function om(s,e,t,i){let n=ou(t);A.useEffect(()=>{if(!s)return;function r(o){n.current(o)}return document.addEventListener(e,r,i),()=>document.removeEventListener(e,r,i)},[s,e,i])}function mA(s,e,t,i){let n=ou(t);A.useEffect(()=>{if(!s)return;function r(o){n.current(o)}return window.addEventListener(e,r,i),()=>window.removeEventListener(e,r,i)},[s,e,i])}const vS=30;function PN(s,e,t){let i=ou(t),n=A.useCallback(function(u,c){if(u.defaultPrevented)return;let d=c(u);if(d===null||!d.getRootNode().contains(d)||!d.isConnected)return;let f=(function p(g){return typeof g=="function"?p(g()):Array.isArray(g)||g instanceof Set?g:[g]})(e);for(let p of f)if(p!==null&&(p.contains(d)||u.composed&&u.composedPath().includes(p)))return;return!LN(d,hA.Loose)&&d.tabIndex!==-1&&u.preventDefault(),i.current(u,d)},[i,e]),r=A.useRef(null);om(s,"pointerdown",u=>{var c,d;yS()||(r.current=((d=(c=u.composedPath)==null?void 0:c.call(u))==null?void 0:d[0])||u.target)},!0),om(s,"pointerup",u=>{if(yS()||!r.current)return;let c=r.current;return r.current=null,n(u,()=>c)},!0);let o=A.useRef({x:0,y:0});om(s,"touchstart",u=>{o.current.x=u.touches[0].clientX,o.current.y=u.touches[0].clientY},!0),om(s,"touchend",u=>{let c={x:u.changedTouches[0].clientX,y:u.changedTouches[0].clientY};if(!(Math.abs(c.x-o.current.x)>=vS||Math.abs(c.y-o.current.y)>=vS))return n(u,()=>nl(u.target)?u.target:null)},!0),mA(s,"blur",u=>n(u,()=>tN(window.document.activeElement)?window.document.activeElement:null),!0)}function Ux(...s){return A.useMemo(()=>Lh(...s),[...s])}function pA(s,e,t,i){let n=ou(t);A.useEffect(()=>{s=s??window;function r(o){n.current(o)}return s.addEventListener(e,r,i),()=>s.removeEventListener(e,r,i)},[s,e,i])}function BN(s){return A.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getSnapshot)}function FN(s,e){let t=s(),i=new Set;return{getSnapshot(){return t},subscribe(n){return i.add(n),()=>i.delete(n)},dispatch(n,...r){let o=e[n].call(t,...r);o&&(t=o,i.forEach(u=>u()))}}}function UN(){let s;return{before({doc:e}){var t;let i=e.documentElement,n=(t=e.defaultView)!=null?t:window;s=Math.max(0,n.innerWidth-i.clientWidth)},after({doc:e,d:t}){let i=e.documentElement,n=Math.max(0,i.clientWidth-i.offsetWidth),r=Math.max(0,s-n);t.style(i,"paddingRight",`${r}px`)}}}function jN(){return fA()?{before({doc:s,d:e,meta:t}){function i(n){for(let r of t().containers)for(let o of r())if(o.contains(n))return!0;return!1}e.microTask(()=>{var n;if(window.getComputedStyle(s.documentElement).scrollBehavior!=="auto"){let u=no();u.style(s.documentElement,"scrollBehavior","auto"),e.add(()=>e.microTask(()=>u.dispose()))}let r=(n=window.scrollY)!=null?n:window.pageYOffset,o=null;e.addEventListener(s,"click",u=>{if(nl(u.target))try{let c=u.target.closest("a");if(!c)return;let{hash:d}=new URL(c.href),f=s.querySelector(d);nl(f)&&!i(f)&&(o=f)}catch{}},!0),e.group(u=>{e.addEventListener(s,"touchstart",c=>{if(u.dispose(),nl(c.target)&&eN(c.target))if(i(c.target)){let d=c.target;for(;d.parentElement&&i(d.parentElement);)d=d.parentElement;u.style(d,"overscrollBehavior","contain")}else u.style(c.target,"touchAction","none")})}),e.addEventListener(s,"touchmove",u=>{if(nl(u.target)){if(iN(u.target))return;if(i(u.target)){let c=u.target;for(;c.parentElement&&c.dataset.headlessuiPortal!==""&&!(c.scrollHeight>c.clientHeight||c.scrollWidth>c.clientWidth);)c=c.parentElement;c.dataset.headlessuiPortal===""&&u.preventDefault()}else u.preventDefault()}},{passive:!1}),e.add(()=>{var u;let c=(u=window.scrollY)!=null?u:window.pageYOffset;r!==c&&window.scrollTo(0,r),o&&o.isConnected&&(o.scrollIntoView({block:"nearest"}),o=null)})})}}:{}}function $N(){return{before({doc:s,d:e}){e.style(s.documentElement,"overflow","hidden")}}}function xS(s){let e={};for(let t of s)Object.assign(e,t(e));return e}let Yl=FN(()=>new Map,{PUSH(s,e){var t;let i=(t=this.get(s))!=null?t:{doc:s,count:0,d:no(),meta:new Set,computedMeta:{}};return i.count++,i.meta.add(e),i.computedMeta=xS(i.meta),this.set(s,i),this},POP(s,e){let t=this.get(s);return t&&(t.count--,t.meta.delete(e),t.computedMeta=xS(t.meta)),this},SCROLL_PREVENT(s){let e={doc:s.doc,d:s.d,meta(){return s.computedMeta}},t=[jN(),UN(),$N()];t.forEach(({before:i})=>i?.(e)),t.forEach(({after:i})=>i?.(e))},SCROLL_ALLOW({d:s}){s.dispose()},TEARDOWN({doc:s}){this.delete(s)}});Yl.subscribe(()=>{let s=Yl.getSnapshot(),e=new Map;for(let[t]of s)e.set(t,t.documentElement.style.overflow);for(let t of s.values()){let i=e.get(t.doc)==="hidden",n=t.count!==0;(n&&!i||!n&&i)&&Yl.dispatch(t.count>0?"SCROLL_PREVENT":"SCROLL_ALLOW",t),t.count===0&&Yl.dispatch("TEARDOWN",t)}});function HN(s,e,t=()=>({containers:[]})){let i=BN(Yl),n=e?i.get(e):void 0,r=n?n.count>0:!1;return Gn(()=>{if(!(!e||!s))return Yl.dispatch("PUSH",e,t),()=>Yl.dispatch("POP",e,t)},[s,e]),r}function VN(s,e,t=()=>[document.body]){let i=Ih(s,"scroll-lock");HN(i,e,n=>{var r;return{containers:[...(r=n.containers)!=null?r:[],t]}})}function GN(s=0){let[e,t]=A.useState(s),i=A.useCallback(c=>t(c),[]),n=A.useCallback(c=>t(d=>d|c),[]),r=A.useCallback(c=>(e&c)===c,[e]),o=A.useCallback(c=>t(d=>d&~c),[]),u=A.useCallback(c=>t(d=>d^c),[]);return{flags:e,setFlag:i,addFlag:n,hasFlag:r,removeFlag:o,toggleFlag:u}}var zN={},bS,TS;typeof process<"u"&&typeof globalThis<"u"&&typeof Element<"u"&&((bS=process==null?void 0:zN)==null?void 0:bS.NODE_ENV)==="test"&&typeof((TS=Element?.prototype)==null?void 0:TS.getAnimations)>"u"&&(Element.prototype.getAnimations=function(){return console.warn(["Headless UI has polyfilled `Element.prototype.getAnimations` for your tests.","Please install a proper polyfill e.g. `jsdom-testing-mocks`, to silence these warnings.","","Example usage:","```js","import { mockAnimationsApi } from 'jsdom-testing-mocks'","mockAnimationsApi()","```"].join(` `)),[]});var qN=(s=>(s[s.None=0]="None",s[s.Closed=1]="Closed",s[s.Enter=2]="Enter",s[s.Leave=4]="Leave",s))(qN||{});function KN(s){let e={};for(let t in s)s[t]===!0&&(e[`data-${t}`]="");return e}function YN(s,e,t,i){let[n,r]=A.useState(t),{hasFlag:o,addFlag:u,removeFlag:c}=GN(s&&n?3:0),d=A.useRef(!1),f=A.useRef(!1),p=Op();return Gn(()=>{var g;if(s){if(t&&r(!0),!e){t&&u(3);return}return(g=i?.start)==null||g.call(i,t),WN(e,{inFlight:d,prepare(){f.current?f.current=!1:f.current=d.current,d.current=!0,!f.current&&(t?(u(3),c(4)):(u(4),c(2)))},run(){f.current?t?(c(3),u(4)):(c(4),u(3)):t?c(1):u(1)},done(){var v;f.current&&ZN(e)||(d.current=!1,c(7),t||r(!1),(v=i?.end)==null||v.call(i,t))}})}},[s,t,e,p]),s?[n,{closed:o(1),enter:o(2),leave:o(4),transition:o(2)||o(4)}]:[t,{closed:void 0,enter:void 0,leave:void 0,transition:void 0}]}function WN(s,{prepare:e,run:t,done:i,inFlight:n}){let r=no();return QN(s,{prepare:e,inFlight:n}),r.nextFrame(()=>{t(),r.requestAnimationFrame(()=>{r.add(XN(s,i))})}),r.dispose}function XN(s,e){var t,i;let n=no();if(!s)return n.dispose;let r=!1;n.add(()=>{r=!0});let o=(i=(t=s.getAnimations)==null?void 0:t.call(s).filter(u=>u instanceof CSSTransition))!=null?i:[];return o.length===0?(e(),n.dispose):(Promise.allSettled(o.map(u=>u.finished)).then(()=>{r||e()}),n.dispose)}function QN(s,{inFlight:e,prepare:t}){if(e!=null&&e.current){t();return}let i=s.style.transition;s.style.transition="none",t(),s.offsetHeight,s.style.transition=i}function ZN(s){var e,t;return((t=(e=s.getAnimations)==null?void 0:e.call(s))!=null?t:[]).some(i=>i instanceof CSSTransition&&i.playState!=="finished")}function jx(s,e){let t=A.useRef([]),i=Xi(s);A.useEffect(()=>{let n=[...t.current];for(let[r,o]of e.entries())if(t.current[r]!==o){let u=i(e,n);return t.current=e,u}},[i,...e])}let Mp=A.createContext(null);Mp.displayName="OpenClosedContext";var Pr=(s=>(s[s.Open=1]="Open",s[s.Closed=2]="Closed",s[s.Closing=4]="Closing",s[s.Opening=8]="Opening",s))(Pr||{});function Pp(){return A.useContext(Mp)}function JN({value:s,children:e}){return $t.createElement(Mp.Provider,{value:s},e)}function e5({children:s}){return $t.createElement(Mp.Provider,{value:null},s)}function t5(s){function e(){document.readyState!=="loading"&&(s(),document.removeEventListener("DOMContentLoaded",e))}typeof window<"u"&&typeof document<"u"&&(document.addEventListener("DOMContentLoaded",e),e())}let il=[];t5(()=>{function s(e){if(!nl(e.target)||e.target===document.body||il[0]===e.target)return;let t=e.target;t=t.closest(Xm),il.unshift(t??e.target),il=il.filter(i=>i!=null&&i.isConnected),il.splice(10)}window.addEventListener("click",s,{capture:!0}),window.addEventListener("mousedown",s,{capture:!0}),window.addEventListener("focus",s,{capture:!0}),document.body.addEventListener("click",s,{capture:!0}),document.body.addEventListener("mousedown",s,{capture:!0}),document.body.addEventListener("focus",s,{capture:!0})});function gA(s){let e=Xi(s),t=A.useRef(!1);A.useEffect(()=>(t.current=!1,()=>{t.current=!0,Np(()=>{t.current&&e()})}),[e])}let yA=A.createContext(!1);function i5(){return A.useContext(yA)}function _S(s){return $t.createElement(yA.Provider,{value:s.force},s.children)}function s5(s){let e=i5(),t=A.useContext(xA),[i,n]=A.useState(()=>{var r;if(!e&&t!==null)return(r=t.current)!=null?r:null;if(ya.isServer)return null;let o=s?.getElementById("headlessui-portal-root");if(o)return o;if(s===null)return null;let u=s.createElement("div");return u.setAttribute("id","headlessui-portal-root"),s.body.appendChild(u)});return A.useEffect(()=>{i!==null&&(s!=null&&s.body.contains(i)||s==null||s.body.appendChild(i))},[i,s]),A.useEffect(()=>{e||t!==null&&n(t.current)},[t,n,e]),i}let vA=A.Fragment,n5=qn(function(s,e){let{ownerDocument:t=null,...i}=s,n=A.useRef(null),r=wa(sN(g=>{n.current=g}),e),o=Ux(n.current),u=t??o,c=s5(u),d=A.useContext(Bv),f=Op(),p=Sr();return gA(()=>{var g;c&&c.childNodes.length<=0&&((g=c.parentElement)==null||g.removeChild(c))}),c?xc.createPortal($t.createElement("div",{"data-headlessui-portal":"",ref:g=>{f.dispose(),d&&g&&f.add(d.register(g))}},p({ourProps:{ref:r},theirProps:i,slot:{},defaultTag:vA,name:"Portal"})),c):null});function r5(s,e){let t=wa(e),{enabled:i=!0,ownerDocument:n,...r}=s,o=Sr();return i?$t.createElement(n5,{...r,ownerDocument:n,ref:t}):o({ourProps:{ref:t},theirProps:r,slot:{},defaultTag:vA,name:"Portal"})}let a5=A.Fragment,xA=A.createContext(null);function o5(s,e){let{target:t,...i}=s,n={ref:wa(e)},r=Sr();return $t.createElement(xA.Provider,{value:t},r({ourProps:n,theirProps:i,defaultTag:a5,name:"Popover.Group"}))}let Bv=A.createContext(null);function l5(){let s=A.useContext(Bv),e=A.useRef([]),t=Xi(r=>(e.current.push(r),s&&s.register(r),()=>i(r))),i=Xi(r=>{let o=e.current.indexOf(r);o!==-1&&e.current.splice(o,1),s&&s.unregister(r)}),n=A.useMemo(()=>({register:t,unregister:i,portals:e}),[t,i,e]);return[e,A.useMemo(()=>function({children:r}){return $t.createElement(Bv.Provider,{value:n},r)},[n])]}let u5=qn(r5),bA=qn(o5),c5=Object.assign(u5,{Group:bA});function d5(s,e=typeof document<"u"?document.defaultView:null,t){let i=Ih(s,"escape");pA(e,"keydown",n=>{i&&(n.defaultPrevented||n.key===rA.Escape&&t(n))})}function h5(){var s;let[e]=A.useState(()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)"):null),[t,i]=A.useState((s=e?.matches)!=null?s:!1);return Gn(()=>{if(!e)return;function n(r){i(r.matches)}return e.addEventListener("change",n),()=>e.removeEventListener("change",n)},[e]),t}function f5({defaultContainers:s=[],portals:e,mainTreeNode:t}={}){let i=Xi(()=>{var n,r;let o=Lh(t),u=[];for(let c of s)c!==null&&(rl(c)?u.push(c):"current"in c&&rl(c.current)&&u.push(c.current));if(e!=null&&e.current)for(let c of e.current)u.push(c);for(let c of(n=o?.querySelectorAll("html > *, body > *"))!=null?n:[])c!==document.body&&c!==document.head&&rl(c)&&c.id!=="headlessui-portal-root"&&(t&&(c.contains(t)||c.contains((r=t?.getRootNode())==null?void 0:r.host))||u.some(d=>c.contains(d))||u.push(c));return u});return{resolveContainers:i,contains:Xi(n=>i().some(r=>r.contains(n)))}}let TA=A.createContext(null);function SS({children:s,node:e}){let[t,i]=A.useState(null),n=_A(e??t);return $t.createElement(TA.Provider,{value:n},s,n===null&&$t.createElement(Ov,{features:Wm.Hidden,ref:r=>{var o,u;if(r){for(let c of(u=(o=Lh(r))==null?void 0:o.querySelectorAll("html > *, body > *"))!=null?u:[])if(c!==document.body&&c!==document.head&&rl(c)&&c!=null&&c.contains(r)){i(c);break}}}}))}function _A(s=null){var e;return(e=A.useContext(TA))!=null?e:s}function m5(){let s=typeof document>"u";return"useSyncExternalStore"in sS?(e=>e.useSyncExternalStore)(sS)(()=>()=>{},()=>!1,()=>!s):!1}function Bp(){let s=m5(),[e,t]=A.useState(ya.isHandoffComplete);return e&&ya.isHandoffComplete===!1&&t(!1),A.useEffect(()=>{e!==!0&&t(!0)},[e]),A.useEffect(()=>ya.handoff(),[]),s?!1:e}function $x(){let s=A.useRef(!1);return Gn(()=>(s.current=!0,()=>{s.current=!1}),[]),s}var Jd=(s=>(s[s.Forwards=0]="Forwards",s[s.Backwards=1]="Backwards",s))(Jd||{});function p5(){let s=A.useRef(0);return mA(!0,"keydown",e=>{e.key==="Tab"&&(s.current=e.shiftKey?1:0)},!0),s}function SA(s){if(!s)return new Set;if(typeof s=="function")return new Set(s());let e=new Set;for(let t of s.current)rl(t.current)&&e.add(t.current);return e}let g5="div";var ql=(s=>(s[s.None=0]="None",s[s.InitialFocus=1]="InitialFocus",s[s.TabLock=2]="TabLock",s[s.FocusLock=4]="FocusLock",s[s.RestoreFocus=8]="RestoreFocus",s[s.AutoFocus=16]="AutoFocus",s))(ql||{});function y5(s,e){let t=A.useRef(null),i=wa(t,e),{initialFocus:n,initialFocusFallback:r,containers:o,features:u=15,...c}=s;Bp()||(u=0);let d=Ux(t.current);T5(u,{ownerDocument:d});let f=_5(u,{ownerDocument:d,container:t,initialFocus:n,initialFocusFallback:r});S5(u,{ownerDocument:d,container:t,containers:o,previousActiveElement:f});let p=p5(),g=Xi(R=>{if(!su(t.current))return;let L=t.current;(P=>P())(()=>{io(p.current,{[Jd.Forwards]:()=>{ah(L,Qa.First,{skipElements:[R.relatedTarget,r]})},[Jd.Backwards]:()=>{ah(L,Qa.Last,{skipElements:[R.relatedTarget,r]})}})})}),v=Ih(!!(u&2),"focus-trap#tab-lock"),b=Op(),_=A.useRef(!1),S={ref:i,onKeyDown(R){R.key=="Tab"&&(_.current=!0,b.requestAnimationFrame(()=>{_.current=!1}))},onBlur(R){if(!(u&4))return;let L=SA(o);su(t.current)&&L.add(t.current);let P=R.relatedTarget;nl(P)&&P.dataset.headlessuiFocusGuard!=="true"&&(EA(L,P)||(_.current?ah(t.current,io(p.current,{[Jd.Forwards]:()=>Qa.Next,[Jd.Backwards]:()=>Qa.Previous})|Qa.WrapAround,{relativeTo:R.target}):nl(R.target)&&eo(R.target)))}},D=Sr();return $t.createElement($t.Fragment,null,v&&$t.createElement(Ov,{as:"button",type:"button","data-headlessui-focus-guard":!0,onFocus:g,features:Wm.Focusable}),D({ourProps:S,theirProps:c,defaultTag:g5,name:"FocusTrap"}),v&&$t.createElement(Ov,{as:"button",type:"button","data-headlessui-focus-guard":!0,onFocus:g,features:Wm.Focusable}))}let v5=qn(y5),x5=Object.assign(v5,{features:ql});function b5(s=!0){let e=A.useRef(il.slice());return jx(([t],[i])=>{i===!0&&t===!1&&Np(()=>{e.current.splice(0)}),i===!1&&t===!0&&(e.current=il.slice())},[s,il,e]),Xi(()=>{var t;return(t=e.current.find(i=>i!=null&&i.isConnected))!=null?t:null})}function T5(s,{ownerDocument:e}){let t=!!(s&8),i=b5(t);jx(()=>{t||VI(e?.body)&&eo(i())},[t]),gA(()=>{t&&eo(i())})}function _5(s,{ownerDocument:e,container:t,initialFocus:i,initialFocusFallback:n}){let r=A.useRef(null),o=Ih(!!(s&1),"focus-trap#initial-focus"),u=$x();return jx(()=>{if(s===0)return;if(!o){n!=null&&n.current&&eo(n.current);return}let c=t.current;c&&Np(()=>{if(!u.current)return;let d=e?.activeElement;if(i!=null&&i.current){if(i?.current===d){r.current=d;return}}else if(c.contains(d)){r.current=d;return}if(i!=null&&i.current)eo(i.current);else{if(s&16){if(ah(c,Qa.First|Qa.AutoFocus)!==Pv.Error)return}else if(ah(c,Qa.First)!==Pv.Error)return;if(n!=null&&n.current&&(eo(n.current),e?.activeElement===n.current))return;console.warn("There are no focusable elements inside the ")}r.current=e?.activeElement})},[n,o,s]),r}function S5(s,{ownerDocument:e,container:t,containers:i,previousActiveElement:n}){let r=$x(),o=!!(s&4);pA(e?.defaultView,"focus",u=>{if(!o||!r.current)return;let c=SA(i);su(t.current)&&c.add(t.current);let d=n.current;if(!d)return;let f=u.target;su(f)?EA(c,f)?(n.current=f,eo(f)):(u.preventDefault(),u.stopPropagation(),eo(d)):eo(n.current)},!0)}function EA(s,e){for(let t of s)if(t.contains(e))return!0;return!1}function wA(s){var e;return!!(s.enter||s.enterFrom||s.enterTo||s.leave||s.leaveFrom||s.leaveTo)||!nh((e=s.as)!=null?e:CA)||$t.Children.count(s.children)===1}let Fp=A.createContext(null);Fp.displayName="TransitionContext";var E5=(s=>(s.Visible="visible",s.Hidden="hidden",s))(E5||{});function w5(){let s=A.useContext(Fp);if(s===null)throw new Error("A is used but it is missing a parent or .");return s}function A5(){let s=A.useContext(Up);if(s===null)throw new Error("A is used but it is missing a parent or .");return s}let Up=A.createContext(null);Up.displayName="NestingContext";function jp(s){return"children"in s?jp(s.children):s.current.filter(({el:e})=>e.current!==null).filter(({state:e})=>e==="visible").length>0}function AA(s,e){let t=ou(s),i=A.useRef([]),n=$x(),r=Op(),o=Xi((v,b=sl.Hidden)=>{let _=i.current.findIndex(({el:S})=>S===v);_!==-1&&(io(b,{[sl.Unmount](){i.current.splice(_,1)},[sl.Hidden](){i.current[_].state="hidden"}}),r.microTask(()=>{var S;!jp(i)&&n.current&&((S=t.current)==null||S.call(t))}))}),u=Xi(v=>{let b=i.current.find(({el:_})=>_===v);return b?b.state!=="visible"&&(b.state="visible"):i.current.push({el:v,state:"visible"}),()=>o(v,sl.Unmount)}),c=A.useRef([]),d=A.useRef(Promise.resolve()),f=A.useRef({enter:[],leave:[]}),p=Xi((v,b,_)=>{c.current.splice(0),e&&(e.chains.current[b]=e.chains.current[b].filter(([S])=>S!==v)),e?.chains.current[b].push([v,new Promise(S=>{c.current.push(S)})]),e?.chains.current[b].push([v,new Promise(S=>{Promise.all(f.current[b].map(([D,R])=>R)).then(()=>S())})]),b==="enter"?d.current=d.current.then(()=>e?.wait.current).then(()=>_(b)):_(b)}),g=Xi((v,b,_)=>{Promise.all(f.current[b].splice(0).map(([S,D])=>D)).then(()=>{var S;(S=c.current.shift())==null||S()}).then(()=>_(b))});return A.useMemo(()=>({children:i,register:u,unregister:o,onStart:p,onStop:g,wait:d,chains:f}),[u,o,i,p,g,f,d])}let CA=A.Fragment,kA=Ym.RenderStrategy;function C5(s,e){var t,i;let{transition:n=!0,beforeEnter:r,afterEnter:o,beforeLeave:u,afterLeave:c,enter:d,enterFrom:f,enterTo:p,entered:g,leave:v,leaveFrom:b,leaveTo:_,...S}=s,[D,R]=A.useState(null),L=A.useRef(null),P=wA(s),U=wa(...P?[L,e,R]:e===null?[]:[e]),V=(t=S.unmount)==null||t?sl.Unmount:sl.Hidden,{show:M,appear:G,initial:N}=w5(),[O,K]=A.useState(M?"visible":"hidden"),Q=A5(),{register:W,unregister:re}=Q;Gn(()=>W(L),[W,L]),Gn(()=>{if(V===sl.Hidden&&L.current){if(M&&O!=="visible"){K("visible");return}return io(O,{hidden:()=>re(L),visible:()=>W(L)})}},[O,L,W,re,M,V]);let J=Bp();Gn(()=>{if(P&&J&&O==="visible"&&L.current===null)throw new Error("Did you forget to passthrough the `ref` to the actual DOM node?")},[L,O,J,P]);let Y=N&&!G,z=G&&M&&N,Z=A.useRef(!1),ie=AA(()=>{Z.current||(K("hidden"),re(L))},Q),ce=Xi(Ke=>{Z.current=!0;let lt=Ke?"enter":"leave";ie.onStart(L,lt,nt=>{nt==="enter"?r?.():nt==="leave"&&u?.()})}),j=Xi(Ke=>{let lt=Ke?"enter":"leave";Z.current=!1,ie.onStop(L,lt,nt=>{nt==="enter"?o?.():nt==="leave"&&c?.()}),lt==="leave"&&!jp(ie)&&(K("hidden"),re(L))});A.useEffect(()=>{P&&n||(ce(M),j(M))},[M,P,n]);let ee=!(!n||!P||!J||Y),[,he]=YN(ee,D,M,{start:ce,end:j}),Te=$l({ref:U,className:((i=Nv(S.className,z&&d,z&&f,he.enter&&d,he.enter&&he.closed&&f,he.enter&&!he.closed&&p,he.leave&&v,he.leave&&!he.closed&&b,he.leave&&he.closed&&_,!he.transition&&M&&g))==null?void 0:i.trim())||void 0,...KN(he)}),xe=0;O==="visible"&&(xe|=Pr.Open),O==="hidden"&&(xe|=Pr.Closed),M&&O==="hidden"&&(xe|=Pr.Opening),!M&&O==="visible"&&(xe|=Pr.Closing);let Ae=Sr();return $t.createElement(Up.Provider,{value:ie},$t.createElement(JN,{value:xe},Ae({ourProps:Te,theirProps:S,defaultTag:CA,features:kA,visible:O==="visible",name:"Transition.Child"})))}function k5(s,e){let{show:t,appear:i=!1,unmount:n=!0,...r}=s,o=A.useRef(null),u=wA(s),c=wa(...u?[o,e]:e===null?[]:[e]);Bp();let d=Pp();if(t===void 0&&d!==null&&(t=(d&Pr.Open)===Pr.Open),t===void 0)throw new Error("A is used but it is missing a `show={true | false}` prop.");let[f,p]=A.useState(t?"visible":"hidden"),g=AA(()=>{t||p("hidden")}),[v,b]=A.useState(!0),_=A.useRef([t]);Gn(()=>{v!==!1&&_.current[_.current.length-1]!==t&&(_.current.push(t),b(!1))},[_,t]);let S=A.useMemo(()=>({show:t,appear:i,initial:v}),[t,i,v]);Gn(()=>{t?p("visible"):!jp(g)&&o.current!==null&&p("hidden")},[t,g]);let D={unmount:n},R=Xi(()=>{var U;v&&b(!1),(U=s.beforeEnter)==null||U.call(s)}),L=Xi(()=>{var U;v&&b(!1),(U=s.beforeLeave)==null||U.call(s)}),P=Sr();return $t.createElement(Up.Provider,{value:g},$t.createElement(Fp.Provider,{value:S},P({ourProps:{...D,as:A.Fragment,children:$t.createElement(DA,{ref:c,...D,...r,beforeEnter:R,beforeLeave:L})},theirProps:{},defaultTag:A.Fragment,features:kA,visible:f==="visible",name:"Transition"})))}function D5(s,e){let t=A.useContext(Fp)!==null,i=Pp()!==null;return $t.createElement($t.Fragment,null,!t&&i?$t.createElement(Fv,{ref:e,...s}):$t.createElement(DA,{ref:e,...s}))}let Fv=qn(k5),DA=qn(C5),Hx=qn(D5),oh=Object.assign(Fv,{Child:Hx,Root:Fv});var L5=(s=>(s[s.Open=0]="Open",s[s.Closed=1]="Closed",s))(L5||{}),R5=(s=>(s[s.SetTitleId=0]="SetTitleId",s))(R5||{});let I5={0(s,e){return s.titleId===e.id?s:{...s,titleId:e.id}}},Vx=A.createContext(null);Vx.displayName="DialogContext";function $p(s){let e=A.useContext(Vx);if(e===null){let t=new Error(`<${s} /> is missing a parent component.`);throw Error.captureStackTrace&&Error.captureStackTrace(t,$p),t}return e}function N5(s,e){return io(e.type,I5,s,e)}let ES=qn(function(s,e){let t=A.useId(),{id:i=`headlessui-dialog-${t}`,open:n,onClose:r,initialFocus:o,role:u="dialog",autoFocus:c=!0,__demoMode:d=!1,unmount:f=!1,...p}=s,g=A.useRef(!1);u=(function(){return u==="dialog"||u==="alertdialog"?u:(g.current||(g.current=!0,console.warn(`Invalid role [${u}] passed to . Only \`dialog\` and and \`alertdialog\` are supported. Using \`dialog\` instead.`)),"dialog")})();let v=Pp();n===void 0&&v!==null&&(n=(v&Pr.Open)===Pr.Open);let b=A.useRef(null),_=wa(b,e),S=Ux(b.current),D=n?0:1,[R,L]=A.useReducer(N5,{titleId:null,descriptionId:null,panelRef:A.createRef()}),P=Xi(()=>r(!1)),U=Xi(he=>L({type:0,id:he})),V=Bp()?D===0:!1,[M,G]=l5(),N={get current(){var he;return(he=R.panelRef.current)!=null?he:b.current}},O=_A(),{resolveContainers:K}=f5({mainTreeNode:O,portals:M,defaultContainers:[N]}),Q=v!==null?(v&Pr.Closing)===Pr.Closing:!1;EN(d||Q?!1:V,{allowed:Xi(()=>{var he,Te;return[(Te=(he=b.current)==null?void 0:he.closest("[data-headlessui-portal]"))!=null?Te:null]}),disallowed:Xi(()=>{var he;return[(he=O?.closest("body > *:not(#headlessui-portal-root)"))!=null?he:null]})});let W=cA.get(null);Gn(()=>{if(V)return W.actions.push(i),()=>W.actions.pop(i)},[W,i,V]);let re=dA(W,A.useCallback(he=>W.selectors.isTop(he,i),[W,i]));PN(re,K,he=>{he.preventDefault(),P()}),d5(re,S?.defaultView,he=>{he.preventDefault(),he.stopPropagation(),document.activeElement&&"blur"in document.activeElement&&typeof document.activeElement.blur=="function"&&document.activeElement.blur(),P()}),VN(d||Q?!1:V,S,K),wN(V,b,P);let[J,Y]=nN(),z=A.useMemo(()=>[{dialogState:D,close:P,setTitleId:U,unmount:f},R],[D,P,U,f,R]),Z=Rh({open:D===0}),ie={ref:_,id:i,role:u,tabIndex:-1,"aria-modal":d?void 0:D===0?!0:void 0,"aria-labelledby":R.titleId,"aria-describedby":J,unmount:f},ce=!h5(),j=ql.None;V&&!d&&(j|=ql.RestoreFocus,j|=ql.TabLock,c&&(j|=ql.AutoFocus),ce&&(j|=ql.InitialFocus));let ee=Sr();return $t.createElement(e5,null,$t.createElement(_S,{force:!0},$t.createElement(c5,null,$t.createElement(Vx.Provider,{value:z},$t.createElement(bA,{target:b},$t.createElement(_S,{force:!1},$t.createElement(Y,{slot:Z},$t.createElement(G,null,$t.createElement(x5,{initialFocus:o,initialFocusFallback:b,containers:K,features:j},$t.createElement(cN,{value:P},ee({ourProps:ie,theirProps:p,slot:Z,defaultTag:O5,features:M5,visible:D===0,name:"Dialog"})))))))))))}),O5="div",M5=Ym.RenderStrategy|Ym.Static;function P5(s,e){let{transition:t=!1,open:i,...n}=s,r=Pp(),o=s.hasOwnProperty("open")||r!==null,u=s.hasOwnProperty("onClose");if(!o&&!u)throw new Error("You have to provide an `open` and an `onClose` prop to the `Dialog` component.");if(!o)throw new Error("You provided an `onClose` prop to the `Dialog`, but forgot an `open` prop.");if(!u)throw new Error("You provided an `open` prop to the `Dialog`, but forgot an `onClose` prop.");if(!r&&typeof s.open!="boolean")throw new Error(`You provided an \`open\` prop to the \`Dialog\`, but the value is not a boolean. Received: ${s.open}`);if(typeof s.onClose!="function")throw new Error(`You provided an \`onClose\` prop to the \`Dialog\`, but the value is not a function. Received: ${s.onClose}`);return(i!==void 0||t)&&!n.static?$t.createElement(SS,null,$t.createElement(oh,{show:i,transition:t,unmount:n.unmount},$t.createElement(ES,{ref:e,...n}))):$t.createElement(SS,null,$t.createElement(ES,{ref:e,open:i,...n}))}let B5="div";function F5(s,e){let t=A.useId(),{id:i=`headlessui-dialog-panel-${t}`,transition:n=!1,...r}=s,[{dialogState:o,unmount:u},c]=$p("Dialog.Panel"),d=wa(e,c.panelRef),f=Rh({open:o===0}),p=Xi(S=>{S.stopPropagation()}),g={ref:d,id:i,onClick:p},v=n?Hx:A.Fragment,b=n?{unmount:u}:{},_=Sr();return $t.createElement(v,{...b},_({ourProps:g,theirProps:r,slot:f,defaultTag:B5,name:"Dialog.Panel"}))}let U5="div";function j5(s,e){let{transition:t=!1,...i}=s,[{dialogState:n,unmount:r}]=$p("Dialog.Backdrop"),o=Rh({open:n===0}),u={ref:e,"aria-hidden":!0},c=t?Hx:A.Fragment,d=t?{unmount:r}:{},f=Sr();return $t.createElement(c,{...d},f({ourProps:u,theirProps:i,slot:o,defaultTag:U5,name:"Dialog.Backdrop"}))}let $5="h2";function H5(s,e){let t=A.useId(),{id:i=`headlessui-dialog-title-${t}`,...n}=s,[{dialogState:r,setTitleId:o}]=$p("Dialog.Title"),u=wa(e);A.useEffect(()=>(o(i),()=>o(null)),[i,o]);let c=Rh({open:r===0}),d={ref:u,id:i};return Sr()({ourProps:d,theirProps:n,slot:c,defaultTag:$5,name:"Dialog.Title"})}let V5=qn(P5),G5=qn(F5);qn(j5);let z5=qn(H5),rc=Object.assign(V5,{Panel:G5,Title:z5,Description:lN});function q5({open:s,onClose:e,onApply:t,initialCookies:i}){const[n,r]=A.useState(""),[o,u]=A.useState(""),[c,d]=A.useState([]),f=A.useRef(!1);A.useEffect(()=>{s&&!f.current&&(r(""),u(""),d(i??[])),f.current=s},[s,i]);function p(){const b=n.trim(),_=o.trim();!b||!_||(d(S=>[...S.filter(R=>R.name!==b),{name:b,value:_}]),r(""),u(""))}function g(b){d(_=>_.filter(S=>S.name!==b))}function v(){t(c),e()}return y.jsxs(rc,{open:s,onClose:e,className:"relative z-50",children:[y.jsx("div",{className:"fixed inset-0 bg-black/40","aria-hidden":"true"}),y.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",children:y.jsxs(rc.Panel,{className:"w-full max-w-lg rounded-lg bg-white dark:bg-gray-800 p-6 shadow-xl dark:outline dark:-outline-offset-1 dark:outline-white/10",children:[y.jsx(rc.Title,{className:"text-base font-semibold text-gray-900 dark:text-white",children:"Zusätzliche Cookies"}),y.jsxs("div",{className:"mt-4 grid grid-cols-1 sm:grid-cols-3 gap-2",children:[y.jsx("input",{value:n,onChange:b=>r(b.target.value),placeholder:"Name (z. B. cf_clearance)",className:"col-span-1 truncate rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white"}),y.jsx("input",{value:o,onChange:b=>u(b.target.value),placeholder:"Wert",className:"col-span-1 truncate sm:col-span-2 rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white"})]}),y.jsx("div",{className:"mt-2",children:y.jsx(li,{size:"sm",variant:"secondary",onClick:p,disabled:!n.trim()||!o.trim(),children:"Hinzufügen"})}),y.jsx("div",{className:"mt-4",children:c.length===0?y.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Noch keine Cookies hinzugefügt."}):y.jsxs("table",{className:"min-w-full text-sm border divide-y dark:divide-white/10",children:[y.jsx("thead",{className:"bg-gray-50 dark:bg-gray-700/50",children:y.jsxs("tr",{children:[y.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Name"}),y.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Wert"}),y.jsx("th",{className:"px-3 py-2"})]})}),y.jsx("tbody",{className:"divide-y dark:divide-white/10",children:c.map(b=>y.jsxs("tr",{children:[y.jsx("td",{className:"px-3 py-2 font-mono",children:b.name}),y.jsx("td",{className:"px-3 py-2 truncate max-w-[240px]",children:b.value}),y.jsx("td",{className:"px-3 py-2 text-right",children:y.jsx("button",{onClick:()=>g(b.name),className:"text-xs text-red-600 hover:underline dark:text-red-400",children:"Entfernen"})})]},b.name))})]})}),y.jsxs("div",{className:"mt-6 flex justify-end gap-2",children:[y.jsx(li,{variant:"secondary",onClick:e,children:"Abbrechen"}),y.jsx(li,{variant:"primary",onClick:v,children:"Übernehmen"})]})]})})]})}function K5({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{fillRule:"evenodd",d:"M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06Z",clipRule:"evenodd"}))}const Y5=A.forwardRef(K5);function wS({tabs:s,value:e,onChange:t,className:i,ariaLabel:n="Ansicht auswählen",variant:r="underline",hideCountUntilMd:o=!1}){if(!s?.length)return null;const u=s.find(g=>g.id===e)??s[0],c=wi("col-start-1 row-start-1 w-full appearance-none rounded-md bg-white py-2 pr-8 pl-3 text-base text-gray-900 outline-1 -outline-offset-1 outline-gray-300 focus:outline-2 focus:-outline-offset-2 focus:outline-indigo-600 dark:text-gray-100 dark:outline-white/10 dark:*:bg-gray-800 dark:focus:outline-indigo-500",r==="pillsBrand"?"dark:bg-gray-800/50":"dark:bg-white/5"),d=g=>wi(g?"bg-indigo-100 text-indigo-600 dark:bg-indigo-500/20 dark:text-indigo-400":"bg-gray-100 text-gray-900 dark:bg-white/10 dark:text-gray-300",o?"ml-3 hidden rounded-full px-2.5 py-0.5 text-xs font-medium md:inline-block":"ml-3 rounded-full px-2.5 py-0.5 text-xs font-medium"),f=(g,v)=>v.count===void 0?null:y.jsx("span",{className:d(g),children:v.count}),p=()=>{switch(r){case"underline":case"underlineIcons":return y.jsx("div",{className:"border-b border-gray-200 dark:border-white/10",children:y.jsx("nav",{"aria-label":n,className:"-mb-px flex space-x-8",children:s.map(g=>{const v=g.id===u.id,b=!!g.disabled;return y.jsxs("button",{type:"button",onClick:()=>!b&&t(g.id),disabled:b,"aria-current":v?"page":void 0,className:wi(v?"border-indigo-500 text-indigo-600 dark:border-indigo-400 dark:text-indigo-400":"border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 dark:text-gray-400 dark:hover:border-white/20 dark:hover:text-gray-200",r==="underlineIcons"?"group inline-flex items-center border-b-2 px-1 py-4 text-sm font-medium":"flex items-center border-b-2 px-1 py-4 text-sm font-medium whitespace-nowrap",b&&"cursor-not-allowed opacity-50 hover:border-transparent hover:text-gray-500 dark:hover:text-gray-400"),children:[r==="underlineIcons"&&g.icon?y.jsx(g.icon,{"aria-hidden":"true",className:wi(v?"text-indigo-500 dark:text-indigo-400":"text-gray-400 group-hover:text-gray-500 dark:text-gray-500 dark:group-hover:text-gray-400","mr-2 -ml-0.5 size-5")}):null,y.jsx("span",{children:g.label}),f(v,g)]},g.id)})})});case"pills":case"pillsGray":case"pillsBrand":{const g=r==="pills"?"bg-gray-100 text-gray-700 dark:bg-white/10 dark:text-gray-200":r==="pillsGray"?"bg-gray-200 text-gray-800 dark:bg-white/10 dark:text-white":"bg-indigo-100 text-indigo-700 dark:bg-indigo-500/20 dark:text-indigo-300",v=r==="pills"?"text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200":r==="pillsGray"?"text-gray-600 hover:text-gray-800 dark:text-gray-400 dark:hover:text-white":"text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200";return y.jsx("nav",{"aria-label":n,className:"flex space-x-4",children:s.map(b=>{const _=b.id===u.id,S=!!b.disabled;return y.jsxs("button",{type:"button",onClick:()=>!S&&t(b.id),disabled:S,"aria-current":_?"page":void 0,className:wi(_?g:v,"inline-flex items-center rounded-md px-3 py-2 text-sm font-medium",S&&"cursor-not-allowed opacity-50 hover:text-inherit"),children:[y.jsx("span",{children:b.label}),b.count!==void 0?y.jsx("span",{className:wi(_?"ml-2 bg-white/70 text-gray-900 dark:bg-white/10 dark:text-white":"ml-2 bg-gray-100 text-gray-900 dark:bg-white/10 dark:text-gray-300","rounded-full px-2 py-0.5 text-xs font-medium"),children:b.count}):null]},b.id)})})}case"fullWidthUnderline":return y.jsx("div",{className:"border-b border-gray-200 dark:border-white/10",children:y.jsx("nav",{"aria-label":n,className:"-mb-px flex",children:s.map(g=>{const v=g.id===u.id,b=!!g.disabled;return y.jsx("button",{type:"button",onClick:()=>!b&&t(g.id),disabled:b,"aria-current":v?"page":void 0,className:wi(v?"border-indigo-500 text-indigo-600 dark:border-indigo-400 dark:text-indigo-400":"border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 dark:text-gray-400 dark:hover:border-white/20 dark:hover:text-gray-300","flex-1 border-b-2 px-1 py-4 text-center text-sm font-medium",b&&"cursor-not-allowed opacity-50 hover:border-transparent hover:text-gray-500 dark:hover:text-gray-400"),children:g.label},g.id)})})});case"barUnderline":return y.jsx("nav",{"aria-label":n,className:"isolate flex divide-x divide-gray-200 rounded-lg bg-white shadow-sm dark:divide-white/10 dark:bg-gray-800/50 dark:shadow-none dark:outline dark:-outline-offset-1 dark:outline-white/10",children:s.map((g,v)=>{const b=g.id===u.id,_=!!g.disabled;return y.jsxs("button",{type:"button",onClick:()=>!_&&t(g.id),disabled:_,"aria-current":b?"page":void 0,className:wi(b?"text-gray-900 dark:text-white":"text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-white",v===0?"rounded-l-lg":"",v===s.length-1?"rounded-r-lg":"","group relative min-w-0 flex-1 overflow-hidden px-4 py-4 text-center text-sm font-medium hover:bg-gray-50 focus:z-10 dark:hover:bg-white/5",_&&"cursor-not-allowed opacity-50 hover:bg-transparent hover:text-gray-500 dark:hover:text-gray-400"),children:[y.jsxs("span",{className:"inline-flex items-center justify-center",children:[g.label,g.count!==void 0?y.jsx("span",{className:"ml-2 rounded-full bg-white/70 px-2 py-0.5 text-xs font-medium text-gray-900 dark:bg-white/10 dark:text-white",children:g.count}):null]}),y.jsx("span",{"aria-hidden":"true",className:wi(b?"bg-indigo-500 dark:bg-indigo-400":"bg-transparent","absolute inset-x-0 bottom-0 h-0.5")})]},g.id)})});case"simple":return y.jsx("nav",{className:"flex border-b border-gray-200 py-4 dark:border-white/10","aria-label":n,children:y.jsx("ul",{role:"list",className:"flex min-w-full flex-none gap-x-8 px-2 text-sm/6 font-semibold text-gray-500 dark:text-gray-400",children:s.map(g=>{const v=g.id===u.id,b=!!g.disabled;return y.jsx("li",{children:y.jsx("button",{type:"button",onClick:()=>!b&&t(g.id),disabled:b,"aria-current":v?"page":void 0,className:wi(v?"text-indigo-600 dark:text-indigo-400":"hover:text-gray-700 dark:hover:text-white",b&&"cursor-not-allowed opacity-50 hover:text-inherit"),children:g.label})},g.id)})})});default:return null}};return y.jsxs("div",{className:i,children:[y.jsxs("div",{className:"grid grid-cols-1 sm:hidden",children:[y.jsx("select",{value:u.id,onChange:g=>t(g.target.value),"aria-label":n,className:c,children:s.map(g=>y.jsx("option",{value:g.id,children:g.label},g.id))}),y.jsx(Y5,{"aria-hidden":"true",className:"pointer-events-none col-start-1 row-start-1 mr-2 size-5 self-center justify-self-end fill-gray-500 dark:fill-gray-400"})]}),y.jsx("div",{className:"hidden sm:block",children:p()})]})}function xa({header:s,footer:e,grayBody:t=!1,grayFooter:i=!1,edgeToEdgeMobile:n=!1,well:r=!1,noBodyPadding:o=!1,className:u,bodyClassName:c,children:d}){const f=r;return y.jsxs("div",{className:wi("overflow-hidden",n?"sm:rounded-lg":"rounded-lg",f?"bg-gray-50 dark:bg-gray-800 shadow-none":"bg-white shadow-sm dark:bg-gray-800 dark:shadow-none dark:outline dark:-outline-offset-1 dark:outline-white/10",u),children:[s&&y.jsx("div",{className:"shrink-0 px-4 py-5 sm:px-6 border-b border-gray-200 dark:border-white/10",children:s}),y.jsx("div",{className:wi("min-h-0",o?"p-0":"px-4 py-5 sm:p-6",t&&"bg-gray-50 dark:bg-gray-800",c),children:d}),e&&y.jsx("div",{className:wi("shrink-0 px-4 py-4 sm:px-6",i&&"bg-gray-50 dark:bg-gray-800/50","border-t border-gray-200 dark:border-white/10"),children:e})]})}function Uv({checked:s,onChange:e,id:t,name:i,disabled:n,required:r,ariaLabel:o,ariaLabelledby:u,ariaDescribedby:c,size:d="default",variant:f="simple",className:p}){const g=b=>{n||e(b.target.checked)},v=wi("absolute inset-0 size-full appearance-none focus:outline-hidden",n&&"cursor-not-allowed");return d==="short"?y.jsxs("div",{className:wi("group relative inline-flex h-5 w-10 shrink-0 items-center justify-center rounded-full outline-offset-2 outline-indigo-600 has-focus-visible:outline-2 dark:outline-indigo-500",n&&"opacity-60",p),children:[y.jsx("span",{className:wi("absolute mx-auto h-4 w-9 rounded-full bg-gray-200 inset-ring inset-ring-gray-900/5 transition-colors duration-200 ease-in-out dark:bg-gray-800/50 dark:inset-ring-white/10",s&&"bg-indigo-600 dark:bg-indigo-500")}),y.jsx("span",{className:wi("absolute left-0 size-5 rounded-full border border-gray-300 bg-white shadow-xs transition-transform duration-200 ease-in-out dark:shadow-none",s&&"translate-x-5")}),y.jsx("input",{id:t,name:i,type:"checkbox",checked:s,onChange:g,disabled:n,required:r,"aria-label":o,"aria-labelledby":u,"aria-describedby":c,className:v})]}):y.jsxs("div",{className:wi("group relative inline-flex w-11 shrink-0 rounded-full bg-gray-200 p-0.5 inset-ring inset-ring-gray-900/5 outline-offset-2 outline-indigo-600 transition-colors duration-200 ease-in-out has-focus-visible:outline-2 dark:bg-white/5 dark:inset-ring-white/10 dark:outline-indigo-500",s&&"bg-indigo-600 dark:bg-indigo-500",n&&"opacity-60",p),children:[f==="icon"?y.jsxs("span",{className:wi("relative size-5 rounded-full bg-white shadow-xs ring-1 ring-gray-900/5 transition-transform duration-200 ease-in-out",s&&"translate-x-5"),children:[y.jsx("span",{"aria-hidden":"true",className:wi("absolute inset-0 flex size-full items-center justify-center transition-opacity ease-in",s?"opacity-0 duration-100":"opacity-100 duration-200"),children:y.jsx("svg",{fill:"none",viewBox:"0 0 12 12",className:"size-3 text-gray-400 dark:text-gray-600",children:y.jsx("path",{d:"M4 8l2-2m0 0l2-2M6 6L4 4m2 2l2 2",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"})})}),y.jsx("span",{"aria-hidden":"true",className:wi("absolute inset-0 flex size-full items-center justify-center transition-opacity ease-out",s?"opacity-100 duration-200":"opacity-0 duration-100"),children:y.jsx("svg",{fill:"currentColor",viewBox:"0 0 12 12",className:"size-3 text-indigo-600 dark:text-indigo-500",children:y.jsx("path",{d:"M3.707 5.293a1 1 0 00-1.414 1.414l1.414-1.414zM5 8l-.707.707a1 1 0 001.414 0L5 8zm4.707-3.293a1 1 0 00-1.414-1.414l1.414 1.414zm-7.414 2l2 2 1.414-1.414-2-2-1.414 1.414zm3.414 2l4-4-1.414-1.414-4 4 1.414 1.414z"})})})]}):y.jsx("span",{className:wi("size-5 rounded-full bg-white shadow-xs ring-1 ring-gray-900/5 transition-transform duration-200 ease-in-out",s&&"translate-x-5")}),y.jsx("input",{id:t,name:i,type:"checkbox",checked:s,onChange:g,disabled:n,required:r,"aria-label":o,"aria-labelledby":u,"aria-describedby":c,className:v})]})}function Xo({label:s,description:e,labelPosition:t="left",id:i,className:n,...r}){const o=A.useId(),u=i??`sw-${o}`,c=`${u}-label`,d=`${u}-desc`;return t==="right"?y.jsxs("div",{className:wi("flex items-center justify-between gap-3",n),children:[y.jsx(Uv,{...r,id:u,ariaLabelledby:c,ariaDescribedby:e?d:void 0}),y.jsxs("div",{className:"text-sm",children:[y.jsx("label",{id:c,htmlFor:u,className:"font-medium text-gray-900 dark:text-white",children:s})," ",e?y.jsx("span",{id:d,className:"text-gray-500 dark:text-gray-400",children:e}):null]})]}):y.jsxs("div",{className:wi("flex items-center justify-between",n),children:[y.jsxs("span",{className:"flex grow flex-col",children:[y.jsx("label",{id:c,htmlFor:u,className:"text-sm/6 font-medium text-gray-900 dark:text-white",children:s}),e?y.jsx("span",{id:d,className:"text-sm text-gray-500 dark:text-gray-400",children:e}):null]}),y.jsx(Uv,{...r,id:u,ariaLabelledby:c,ariaDescribedby:e?d:void 0})]})}function bc({label:s,value:e=0,indeterminate:t=!1,showPercent:i=!1,rightLabel:n,steps:r,currentStep:o,size:u="md",className:c}){const d=Math.max(0,Math.min(100,Number(e)||0)),f=u==="sm"?"h-1.5":"h-2",p=Array.isArray(r)&&r.length>0,g=p?r.length:0,v=S=>S===0?"text-left":S===g-1?"text-right":"text-center",b=S=>typeof o!="number"||!Number.isFinite(o)?!1:S<=o,_=i&&!t;return y.jsxs("div",{className:c,children:[s||_?y.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s?y.jsx("p",{className:"flex-1 min-w-0 truncate text-xs font-medium text-gray-900 dark:text-white",children:s}):y.jsx("span",{className:"flex-1"}),_?y.jsxs("span",{className:"shrink-0 text-xs font-medium text-gray-700 dark:text-gray-300",children:[Math.round(d),"%"]}):null]}):null,y.jsxs("div",{"aria-hidden":"true",className:s||_?"mt-2":"",children:[y.jsx("div",{className:"overflow-hidden rounded-full bg-gray-200 dark:bg-white/10",children:t?y.jsx("div",{className:`${f} w-full rounded-full bg-indigo-600/70 dark:bg-indigo-500/70 animate-pulse`}):y.jsx("div",{className:`${f} rounded-full bg-indigo-600 dark:bg-indigo-500 transition-[width] duration-200`,style:{width:`${d}%`}})}),n?y.jsx("div",{className:"mt-2 text-xs text-gray-600 dark:text-gray-400",children:n}):null,p?y.jsx("div",{className:"mt-3 hidden text-sm font-medium text-gray-600 sm:grid dark:text-gray-400",style:{gridTemplateColumns:`repeat(${g}, minmax(0, 1fr))`},children:r.map((S,D)=>y.jsx("div",{className:[v(D),b(D)?"text-indigo-600 dark:text-indigo-400":""].join(" "),children:S},`${D}-${S}`))}):null]})]})}async function AS(s,e){const t=await fetch(s,{cache:"no-store",...e,headers:{"Content-Type":"application/json",...e?.headers||{}}});let i=null;try{i=await t.json()}catch{}if(!t.ok){const n=i&&(i.error||i.message)||t.statusText;throw new Error(n)}return i}function W5({onFinished:s}){const[e,t]=A.useState(null),[i,n]=A.useState(null),[r,o]=A.useState(!1),[u,c]=A.useState(!1),d=A.useCallback(async()=>{try{const P=await AS("/api/tasks/generate-assets");t(P)}catch(P){n(P?.message??String(P))}},[]),f=A.useRef(!1);A.useEffect(()=>{const P=f.current,U=!!e?.running;f.current=U,P&&!U&&s?.()},[e?.running,s]),A.useEffect(()=>{d()},[d]),A.useEffect(()=>{if(!e?.running)return;const P=window.setInterval(d,1200);return()=>window.clearInterval(P)},[e?.running,d]);async function p(){n(null),o(!0);try{const P=await AS("/api/tasks/generate-assets",{method:"POST"});t(P)}catch(P){n(P?.message??String(P))}finally{o(!1)}}async function g(){n(null),c(!0);try{await fetch("/api/tasks/generate-assets",{method:"DELETE",cache:"no-store"})}catch{}finally{await d(),c(!1)}}const v=!!e?.running,b=e?.total??0,_=e?.done??0,S=b>0?Math.min(100,Math.round(_/b*100)):0,D=P=>{const U=String(P??"").trim();if(!U)return null;const V=new Date(U);return Number.isFinite(V.getTime())?V.toLocaleString(void 0,{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):null},R=D(e?.startedAt),L=D(e?.finishedAt);return y.jsxs("div",{className:`\r rounded-2xl border border-gray-200 bg-white/80 p-4 shadow-sm\r backdrop-blur supports-[backdrop-filter]:bg-white/60\r dark:border-white/10 dark:bg-gray-950/50 dark:supports-[backdrop-filter]:bg-gray-950/35\r `,children:[y.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[y.jsxs("div",{className:"min-w-0",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Assets-Generator"}),v?y.jsx("span",{className:"inline-flex items-center rounded-full bg-indigo-500/10 px-2 py-0.5 text-[11px] font-semibold text-indigo-700 ring-1 ring-inset ring-indigo-200 dark:text-indigo-200 dark:ring-indigo-400/30",children:"läuft"}):y.jsx("span",{className:"inline-flex items-center rounded-full bg-gray-100 px-2 py-0.5 text-[11px] font-semibold text-gray-700 ring-1 ring-inset ring-gray-200 dark:bg-white/5 dark:text-gray-200 dark:ring-white/10",children:"bereit"})]}),y.jsxs("div",{className:"mt-1 text-xs text-gray-600 dark:text-white/70",children:["Erzeugt pro fertiger Datei unter ",y.jsx("span",{className:"font-mono",children:"/generated//"})," ",y.jsx("span",{className:"font-mono",children:"thumbs.jpg"}),", ",y.jsx("span",{className:"font-mono",children:"preview.mp4"})," ","und ",y.jsx("span",{className:"font-mono",children:"meta.json"})," für schnelle Listen & zuverlässige Duration."]})]}),y.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[v?y.jsx(li,{variant:"secondary",color:"red",onClick:g,disabled:u,className:"w-full sm:w-auto",children:u?"Stoppe…":"Stop"}):null,y.jsx(li,{variant:"primary",onClick:p,disabled:r||v,className:"w-full sm:w-auto",children:r?"Starte…":v?"Läuft…":"Generieren"})]})]}),i?y.jsx("div",{className:"mt-3 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-700 dark:border-red-500/30 dark:bg-red-500/10 dark:text-red-200",children:i}):null,e?.error?y.jsx("div",{className:"mt-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800 dark:border-amber-500/30 dark:bg-amber-500/10 dark:text-amber-200",children:e.error}):null,e?y.jsxs("div",{className:"mt-4 space-y-3",children:[y.jsx(bc,{value:S,showPercent:!0,rightLabel:b?`${_}/${b} Dateien`:"—"}),y.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[y.jsxs("div",{className:"rounded-xl border border-gray-200 bg-white px-3 py-2 dark:border-white/10 dark:bg-white/5",children:[y.jsx("div",{className:"text-[11px] font-medium text-gray-600 dark:text-white/70",children:"Thumbs"}),y.jsx("div",{className:"mt-0.5 text-sm font-semibold tabular-nums text-gray-900 dark:text-white",children:e.generatedThumbs??0})]}),y.jsxs("div",{className:"rounded-xl border border-gray-200 bg-white px-3 py-2 dark:border-white/10 dark:bg-white/5",children:[y.jsx("div",{className:"text-[11px] font-medium text-gray-600 dark:text-white/70",children:"Previews"}),y.jsx("div",{className:"mt-0.5 text-sm font-semibold tabular-nums text-gray-900 dark:text-white",children:e.generatedPreviews??0})]}),y.jsxs("div",{className:"rounded-xl border border-gray-200 bg-white px-3 py-2 dark:border-white/10 dark:bg-white/5",children:[y.jsx("div",{className:"text-[11px] font-medium text-gray-600 dark:text-white/70",children:"Übersprungen"}),y.jsx("div",{className:"mt-0.5 text-sm font-semibold tabular-nums text-gray-900 dark:text-white",children:e.skipped??0})]})]}),y.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-x-4 gap-y-1 text-xs text-gray-600 dark:text-white/70",children:[y.jsx("span",{children:R?y.jsxs(y.Fragment,{children:["Start: ",y.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:R})]}):"Start: —"}),y.jsx("span",{children:L?y.jsxs(y.Fragment,{children:["Ende: ",y.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:L})]}):"Ende: —"})]})]}):y.jsx("div",{className:"mt-4 text-xs text-gray-600 dark:text-white/70",children:"Status wird geladen…"})]})}const Bs={recordDir:"records",doneDir:"records/done",ffmpegPath:"",autoAddToDownloadList:!0,autoStartAddedDownloads:!0,useChaturbateApi:!1,useMyFreeCamsWatcher:!1,autoDeleteSmallDownloads:!1,autoDeleteSmallDownloadsBelowMB:50,blurPreviews:!1,teaserPlayback:"hover",teaserAudio:!1,lowDiskPauseBelowGB:5};function X5({onAssetsGenerated:s}){const[e,t]=A.useState(Bs),[i,n]=A.useState(!1),[r,o]=A.useState(!1),[u,c]=A.useState(null),[d,f]=A.useState(null),[p,g]=A.useState(null);A.useEffect(()=>{let S=!0;return fetch("/api/settings",{cache:"no-store"}).then(async D=>{if(!D.ok)throw new Error(await D.text());return D.json()}).then(D=>{S&&t({recordDir:(D.recordDir||Bs.recordDir).toString(),doneDir:(D.doneDir||Bs.doneDir).toString(),ffmpegPath:String(D.ffmpegPath??Bs.ffmpegPath??""),autoAddToDownloadList:D.autoAddToDownloadList??Bs.autoAddToDownloadList,autoStartAddedDownloads:D.autoStartAddedDownloads??Bs.autoStartAddedDownloads,useChaturbateApi:D.useChaturbateApi??Bs.useChaturbateApi,useMyFreeCamsWatcher:D.useMyFreeCamsWatcher??Bs.useMyFreeCamsWatcher,autoDeleteSmallDownloads:D.autoDeleteSmallDownloads??Bs.autoDeleteSmallDownloads,autoDeleteSmallDownloadsBelowMB:D.autoDeleteSmallDownloadsBelowMB??Bs.autoDeleteSmallDownloadsBelowMB,blurPreviews:D.blurPreviews??Bs.blurPreviews,teaserPlayback:D.teaserPlayback??Bs.teaserPlayback,teaserAudio:D.teaserAudio??Bs.teaserAudio,lowDiskPauseBelowGB:D.lowDiskPauseBelowGB??Bs.lowDiskPauseBelowGB})}).catch(()=>{}),()=>{S=!1}},[]);async function v(S){g(null),f(null),c(S);try{window.focus();const D=await fetch(`/api/settings/browse?target=${S}`,{cache:"no-store"});if(D.status===204)return;if(!D.ok){const P=await D.text().catch(()=>"");throw new Error(P||`HTTP ${D.status}`)}const L=((await D.json()).path??"").trim();if(!L)return;t(P=>S==="record"?{...P,recordDir:L}:S==="done"?{...P,doneDir:L}:{...P,ffmpegPath:L})}catch(D){g(D?.message??String(D))}finally{c(null)}}async function b(){g(null),f(null);const S=e.recordDir.trim(),D=e.doneDir.trim(),R=(e.ffmpegPath??"").trim();if(!S||!D){g("Bitte Aufnahme-Ordner und Ziel-Ordner angeben.");return}const L=!!e.autoAddToDownloadList,P=L?!!e.autoStartAddedDownloads:!1,U=!!e.useChaturbateApi,V=!!e.useMyFreeCamsWatcher,M=!!e.autoDeleteSmallDownloads,G=Math.max(0,Math.min(1e5,Math.floor(Number(e.autoDeleteSmallDownloadsBelowMB??Bs.autoDeleteSmallDownloadsBelowMB)))),N=!!e.blurPreviews,O=e.teaserPlayback==="still"||e.teaserPlayback==="all"||e.teaserPlayback==="hover"?e.teaserPlayback:Bs.teaserPlayback,K=!!e.teaserAudio,Q=Math.max(1,Math.floor(Number(e.lowDiskPauseBelowGB??Bs.lowDiskPauseBelowGB)));n(!0);try{const W=await fetch("/api/settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recordDir:S,doneDir:D,ffmpegPath:R,autoAddToDownloadList:L,autoStartAddedDownloads:P,useChaturbateApi:U,useMyFreeCamsWatcher:V,autoDeleteSmallDownloads:M,autoDeleteSmallDownloadsBelowMB:G,blurPreviews:N,teaserPlayback:O,teaserAudio:K,lowDiskPauseBelowGB:Q})});if(!W.ok){const re=await W.text().catch(()=>"");throw new Error(re||`HTTP ${W.status}`)}f("✅ Gespeichert."),window.dispatchEvent(new CustomEvent("recorder-settings-updated"))}catch(W){g(W?.message??String(W))}finally{n(!1)}}async function _(){g(null),f(null);const S=Number(e.autoDeleteSmallDownloadsBelowMB??Bs.autoDeleteSmallDownloadsBelowMB??0),D=(e.doneDir||Bs.doneDir).trim();if(!D){g("doneDir ist leer.");return}if(!S||S<=0){g("Mindestgröße ist 0 – es würde nichts gelöscht.");return}if(window.confirm(`Aufräumen: Alle Dateien in "${D}" löschen, die kleiner als ${S} MB sind? (Ordner "keep" wird übersprungen)`)){o(!0);try{const L=await fetch("/api/settings/cleanup-small-downloads",{method:"POST",headers:{"Content-Type":"application/json"},cache:"no-store"});if(!L.ok){const U=await L.text().catch(()=>"");throw new Error(U||`HTTP ${L.status}`)}const P=await L.json();f(`🧹 Aufräumen fertig: ${P.deletedFiles} Datei(en) gelöscht (${P.deletedBytesHuman}). Geprüft: ${P.scannedFiles}. Übersprungen: ${P.skippedFiles}.`)}catch(L){g(L?.message??String(L))}finally{o(!1)}}}return y.jsx(xa,{header:y.jsxs("div",{className:"flex items-center justify-between gap-4",children:[y.jsxs("div",{children:[y.jsx("div",{className:"text-base font-semibold text-gray-900 dark:text-white",children:"Einstellungen"}),y.jsx("div",{className:"mt-0.5 text-xs text-gray-600 dark:text-gray-300",children:"Recorder-Konfiguration, Automatisierung und Tasks."})]}),y.jsx(li,{variant:"primary",onClick:b,disabled:i,children:"Speichern"})]}),grayBody:!0,children:y.jsxs("div",{className:"space-y-4",children:[p&&y.jsx("div",{className:"rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-500/30 dark:bg-red-500/10 dark:text-red-200",children:p}),d&&y.jsx("div",{className:"rounded-lg border border-green-200 bg-green-50 px-3 py-2 text-sm text-green-700 dark:border-green-500/30 dark:bg-green-500/10 dark:text-green-200",children:d}),y.jsxs("div",{className:"rounded-2xl border border-gray-200 bg-white p-4 shadow-sm dark:border-white/10 dark:bg-gray-950/40",children:[y.jsxs("div",{className:"flex items-start justify-between gap-4",children:[y.jsxs("div",{className:"min-w-0",children:[y.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Tasks"}),y.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Generiere fehlende Vorschauen/Metadaten für schnelle Listenansichten."})]}),y.jsx("div",{className:"shrink-0",children:y.jsx("span",{className:"inline-flex items-center rounded-full bg-gray-100 px-2 py-1 text-[11px] font-medium text-gray-700 dark:bg-white/10 dark:text-gray-200",children:"Utilities"})})]}),y.jsx("div",{className:"mt-3",children:y.jsx(W5,{onFinished:s})})]}),y.jsxs("div",{className:"rounded-2xl border border-gray-200 bg-white p-4 shadow-sm dark:border-white/10 dark:bg-gray-950/40",children:[y.jsxs("div",{className:"mb-3",children:[y.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Pfad-Einstellungen"}),y.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Aufnahme- und Zielverzeichnisse sowie optionaler ffmpeg-Pfad."})]}),y.jsxs("div",{className:"space-y-3",children:[y.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[y.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"Aufnahme-Ordner"}),y.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[y.jsx("input",{value:e.recordDir,onChange:S=>t(D=>({...D,recordDir:S.target.value})),placeholder:"records (oder absolut: C:\\records / /mnt/data/records)",className:`min-w-0 flex-1 rounded-lg px-3 py-2 text-sm bg-white text-gray-900 ring-1 ring-gray-200 focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:bg-white/10 dark:text-white dark:ring-white/10`}),y.jsx(li,{variant:"secondary",onClick:()=>v("record"),disabled:i||u!==null,children:"Durchsuchen..."})]})]}),y.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[y.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"Fertige Downloads nach"}),y.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[y.jsx("input",{value:e.doneDir,onChange:S=>t(D=>({...D,doneDir:S.target.value})),placeholder:"records/done",className:`min-w-0 flex-1 rounded-lg px-3 py-2 text-sm bg-white text-gray-900 ring-1 ring-gray-200 focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:bg-white/10 dark:text-white dark:ring-white/10`}),y.jsx(li,{variant:"secondary",onClick:()=>v("done"),disabled:i||u!==null,children:"Durchsuchen..."})]})]}),y.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[y.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"ffmpeg.exe"}),y.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[y.jsx("input",{value:e.ffmpegPath??"",onChange:S=>t(D=>({...D,ffmpegPath:S.target.value})),placeholder:"Leer = automatisch (FFMPEG_PATH / ffmpeg im PATH)",className:`min-w-0 flex-1 rounded-lg px-3 py-2 text-sm bg-white text-gray-900 ring-1 ring-gray-200 focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:bg-white/10 dark:text-white dark:ring-white/10`}),y.jsx(li,{variant:"secondary",onClick:()=>v("ffmpeg"),disabled:i||u!==null,children:"Durchsuchen..."})]})]})]})]}),y.jsxs("div",{className:"rounded-2xl border border-gray-200 bg-white p-4 shadow-sm dark:border-white/10 dark:bg-gray-950/40",children:[y.jsxs("div",{className:"mb-3",children:[y.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Automatisierung & Anzeige"}),y.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Verhalten beim Hinzufügen/Starten sowie Anzeigeoptionen."})]}),y.jsxs("div",{className:"space-y-3",children:[y.jsx(Xo,{checked:!!e.autoAddToDownloadList,onChange:S=>t(D=>({...D,autoAddToDownloadList:S,autoStartAddedDownloads:S?D.autoStartAddedDownloads:!1})),label:"Automatisch zur Downloadliste hinzufügen",description:"Neue Links/Modelle werden automatisch in die Downloadliste übernommen."}),y.jsx(Xo,{checked:!!e.autoStartAddedDownloads,onChange:S=>t(D=>({...D,autoStartAddedDownloads:S})),disabled:!e.autoAddToDownloadList,label:"Hinzugefügte Downloads automatisch starten",description:"Wenn ein Download hinzugefügt wurde, startet er direkt (sofern möglich)."}),y.jsx(Xo,{checked:!!e.useChaturbateApi,onChange:S=>t(D=>({...D,useChaturbateApi:S})),label:"Chaturbate API",description:"Wenn aktiv, pollt das Backend alle paar Sekunden die Online-Rooms API und cached die aktuell online Models."}),y.jsx(Xo,{checked:!!e.useMyFreeCamsWatcher,onChange:S=>t(D=>({...D,useMyFreeCamsWatcher:S})),label:"MyFreeCams Auto-Check (watched)",description:"Geht watched MyFreeCams-Models einzeln durch und startet einen Download. Wenn keine Output-Datei entsteht, ist der Stream nicht öffentlich (offline/away/private) und der Job wird wieder entfernt."}),y.jsxs("div",{className:"rounded-xl border border-gray-200 bg-gray-50 p-3 dark:border-white/10 dark:bg-white/5",children:[y.jsx(Xo,{checked:!!e.autoDeleteSmallDownloads,onChange:S=>t(D=>({...D,autoDeleteSmallDownloads:S,autoDeleteSmallDownloadsBelowMB:D.autoDeleteSmallDownloadsBelowMB??50})),label:"Kleine Downloads automatisch löschen",description:"Löscht fertige Downloads automatisch, wenn die Datei kleiner als die eingestellte Mindestgröße ist."}),y.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center "+(e.autoDeleteSmallDownloads?"":"opacity-50 pointer-events-none"),children:[y.jsxs("div",{className:"sm:col-span-4",children:[y.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-gray-200",children:"Mindestgröße"}),y.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Alles darunter wird gelöscht."})]}),y.jsx("div",{className:"sm:col-span-8",children:y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("input",{type:"number",min:0,step:1,value:e.autoDeleteSmallDownloadsBelowMB??50,onChange:S=>t(D=>({...D,autoDeleteSmallDownloadsBelowMB:Number(S.target.value||0)})),className:`h-9 w-full rounded-md border border-gray-200 bg-white px-3 text-sm text-gray-900 shadow-sm dark:border-white/10 dark:bg-gray-900 dark:text-gray-100`}),y.jsx("span",{className:"shrink-0 text-xs text-gray-600 dark:text-gray-300",children:"MB"}),y.jsx(li,{variant:"secondary",onClick:_,disabled:i||r||!e.autoDeleteSmallDownloads,className:"h-9 shrink-0 px-3",title:"Löscht Dateien im doneDir kleiner als die Mindestgröße (keep wird übersprungen)",children:r?"…":"Aufräumen"})]})})]})]}),y.jsx(Xo,{checked:!!e.blurPreviews,onChange:S=>t(D=>({...D,blurPreviews:S})),label:"Vorschaubilder blurren",description:"Weichzeichnet Vorschaubilder/Teaser (praktisch auf mobilen Geräten oder im öffentlichen Umfeld)."}),y.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[y.jsxs("div",{className:"sm:col-span-4",children:[y.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-gray-200",children:"Teaser abspielen"}),y.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Standbild spart Leistung. „Bei Hover (Standard)“: Desktop spielt bei Hover ab, Mobile im Viewport. „Alle“ kann viel CPU ziehen."})]}),y.jsxs("div",{className:"sm:col-span-8",children:[y.jsx("label",{className:"sr-only",htmlFor:"teaserPlayback",children:"Teaser abspielen"}),y.jsxs("select",{id:"teaserPlayback",value:e.teaserPlayback??"hover",onChange:S=>t(D=>({...D,teaserPlayback:S.target.value})),className:`h-9 w-full rounded-md border border-gray-200 bg-white px-3 text-sm text-gray-900 shadow-sm dark:border-white/10 dark:bg-gray-900 dark:text-gray-100 dark:[color-scheme:dark]`,children:[y.jsx("option",{value:"still",children:"Standbild"}),y.jsx("option",{value:"hover",children:"Bei Hover (Standard)"}),y.jsx("option",{value:"all",children:"Alle"})]})]})]}),y.jsx(Xo,{checked:!!e.teaserAudio,onChange:S=>t(D=>({...D,teaserAudio:S})),label:"Teaser mit Ton",description:"Wenn aktiv, werden Vorschau/Teaser nicht stumm geschaltet."}),y.jsxs("div",{className:"rounded-xl border border-gray-200 bg-gray-50 p-3 dark:border-white/10 dark:bg-white/5",children:[y.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Speicherplatz-Notbremse"}),y.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Wenn freier Platz darunter fällt: Autostart pausieren + laufende Downloads stoppen. Resume erfolgt automatisch bei +3 GB."}),y.jsxs("div",{className:"mt-3 grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[y.jsxs("div",{className:"sm:col-span-4",children:[y.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-gray-200",children:"Pause unter"}),y.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Freier Speicher in GB"})]}),y.jsxs("div",{className:"sm:col-span-8 flex items-center gap-3",children:[y.jsx("input",{type:"range",min:1,max:500,step:1,value:e.lowDiskPauseBelowGB??5,onChange:S=>t(D=>({...D,lowDiskPauseBelowGB:Number(S.target.value)})),className:"w-full"}),y.jsxs("span",{className:"w-16 text-right text-sm tabular-nums text-gray-900 dark:text-gray-100",children:[e.lowDiskPauseBelowGB??5," GB"]})]})]})]})]})]})]})})}function Q5({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{fillRule:"evenodd",d:"M5.22 8.22a.75.75 0 0 1 1.06 0L10 11.94l3.72-3.72a.75.75 0 1 1 1.06 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L5.22 9.28a.75.75 0 0 1 0-1.06Z",clipRule:"evenodd"}))}const Z5=A.forwardRef(Q5);function J5({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{fillRule:"evenodd",d:"M11.78 5.22a.75.75 0 0 1 0 1.06L8.06 10l3.72 3.72a.75.75 0 1 1-1.06 1.06l-4.25-4.25a.75.75 0 0 1 0-1.06l4.25-4.25a.75.75 0 0 1 1.06 0Z",clipRule:"evenodd"}))}const eO=A.forwardRef(J5);function tO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{fillRule:"evenodd",d:"M8.22 5.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.75.75 0 0 1-1.06-1.06L11.94 10 8.22 6.28a.75.75 0 0 1 0-1.06Z",clipRule:"evenodd"}))}const iO=A.forwardRef(tO);function sO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{d:"M6.28 5.22a.75.75 0 0 0-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 1 0 1.06 1.06L10 11.06l3.72 3.72a.75.75 0 1 0 1.06-1.06L11.06 10l3.72-3.72a.75.75 0 0 0-1.06-1.06L10 8.94 6.28 5.22Z"}))}const nO=A.forwardRef(sO);function Bn(...s){return s.filter(Boolean).join(" ")}function CS(s){return s==="center"?"text-center":s==="right"?"text-right":"text-left"}function rO(s){return s==="center"?"justify-center":s==="right"?"justify-end":"justify-start"}function kS(s,e){const t=s===0,i=s===e-1;return t||i?"pl-2 pr-2":"px-2"}function DS(s){return s==null?{isNull:!0,kind:"string",value:""}:s instanceof Date?{isNull:!1,kind:"number",value:s.getTime()}:typeof s=="number"?{isNull:!1,kind:"number",value:s}:typeof s=="boolean"?{isNull:!1,kind:"number",value:s?1:0}:typeof s=="bigint"?{isNull:!1,kind:"number",value:Number(s)}:{isNull:!1,kind:"string",value:String(s).toLocaleLowerCase()}}function Gx({columns:s,rows:e,getRowKey:t,title:i,description:n,actions:r,fullWidth:o=!1,card:u=!0,striped:c=!1,stickyHeader:d=!1,compact:f=!1,isLoading:p=!1,emptyLabel:g="Keine Daten vorhanden.",className:v,rowClassName:b,onRowClick:_,onRowContextMenu:S,sort:D,onSortChange:R,defaultSort:L=null}){const P=f?"py-2":"py-4",U=f?"py-3":"py-3.5",V=D!==void 0,[M,G]=A.useState(L),N=V?D:M,O=A.useCallback(Q=>{V||G(Q),R?.(Q)},[V,R]),K=A.useMemo(()=>{if(!N)return e;const Q=s.find(J=>J.key===N.key);if(!Q)return e;const W=N.direction==="asc"?1:-1,re=e.map((J,Y)=>({r:J,i:Y}));return re.sort((J,Y)=>{let z=0;if(Q.sortFn)z=Q.sortFn(J.r,Y.r);else{const Z=Q.sortValue?Q.sortValue(J.r):J.r?.[Q.key],ie=Q.sortValue?Q.sortValue(Y.r):Y.r?.[Q.key],ce=DS(Z),j=DS(ie);ce.isNull&&!j.isNull?z=1:!ce.isNull&&j.isNull?z=-1:ce.kind==="number"&&j.kind==="number"?z=ce.valuej.value?1:0:z=String(ce.value).localeCompare(String(j.value),void 0,{numeric:!0})}return z===0?J.i-Y.i:z*W}),re.map(J=>J.r)},[e,s,N]);return y.jsxs("div",{className:Bn(o?"":"px-4 sm:px-6 lg:px-8",v),children:[(i||n||r)&&y.jsxs("div",{className:"sm:flex sm:items-center",children:[y.jsxs("div",{className:"sm:flex-auto",children:[i&&y.jsx("h1",{className:"text-base font-semibold text-gray-900 dark:text-white",children:i}),n&&y.jsx("p",{className:"mt-2 text-sm text-gray-700 dark:text-gray-300",children:n})]}),r&&y.jsx("div",{className:"mt-4 sm:mt-0 sm:ml-16 sm:flex-none",children:r})]}),y.jsx("div",{className:Bn(i||n||r?"mt-8":""),children:y.jsx("div",{className:"flow-root",children:y.jsx("div",{className:"overflow-x-auto",children:y.jsx("div",{className:Bn("inline-block min-w-full align-middle",o?"":"sm:px-6 lg:px-8"),children:y.jsx("div",{className:Bn(u&&"overflow-hidden shadow-sm outline-1 outline-black/5 sm:rounded-lg dark:shadow-none dark:-outline-offset-1 dark:outline-white/10"),children:y.jsxs("table",{className:"relative min-w-full divide-y divide-gray-200 dark:divide-white/10",children:[y.jsx("thead",{className:Bn(u&&"bg-gray-50/90 dark:bg-gray-800/70",d&&"sticky top-0 z-10 backdrop-blur-sm shadow-sm"),children:y.jsx("tr",{children:s.map((Q,W)=>{const re=kS(W,s.length),J=!!N&&N.key===Q.key,Y=J?N.direction:void 0,z=Q.sortable&&!Q.srOnlyHeader?J?Y==="asc"?"ascending":"descending":"none":void 0,Z=()=>{if(!(!Q.sortable||Q.srOnlyHeader))return O(J?Y==="asc"?{key:Q.key,direction:"desc"}:null:{key:Q.key,direction:"asc"})};return y.jsx("th",{scope:"col","aria-sort":z,className:Bn(U,re,"text-xs font-semibold tracking-wide text-gray-700 dark:text-gray-200 whitespace-nowrap",CS(Q.align),Q.widthClassName,Q.headerClassName),children:Q.srOnlyHeader?y.jsx("span",{className:"sr-only",children:Q.header}):Q.sortable?y.jsxs("button",{type:"button",onClick:Z,className:Bn("group inline-flex w-full items-center gap-2 select-none rounded-md px-1.5 py-1 -my-1 hover:bg-gray-100/70 dark:hover:bg-white/5",rO(Q.align)),children:[y.jsx("span",{children:Q.header}),y.jsx("span",{className:Bn("flex-none rounded-sm text-gray-400 dark:text-gray-500",J?"bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-white":"invisible group-hover:visible group-focus-visible:visible"),children:y.jsx(Z5,{"aria-hidden":"true",className:Bn("size-5 transition-transform",J&&Y==="asc"&&"rotate-180")})})]}):Q.header},Q.key)})})}),y.jsx("tbody",{className:Bn("divide-y divide-gray-200 dark:divide-white/10",u?"bg-white dark:bg-gray-800/50":"bg-white dark:bg-gray-900"),children:p?y.jsx("tr",{children:y.jsx("td",{colSpan:s.length,className:Bn(P,"px-2 text-sm text-gray-500 dark:text-gray-400"),children:"Lädt…"})}):K.length===0?y.jsx("tr",{children:y.jsx("td",{colSpan:s.length,className:Bn(P,"px-2 text-sm text-gray-500 dark:text-gray-400"),children:g})}):K.map((Q,W)=>{const re=t?t(Q,W):String(W);return y.jsx("tr",{className:Bn(c&&"even:bg-gray-50 dark:even:bg-gray-800/50",_&&"cursor-pointer",_&&"hover:bg-gray-50 dark:hover:bg-white/5 transition-colors",b?.(Q,W)),onClick:()=>_?.(Q),onContextMenu:S?J=>{J.preventDefault(),S(Q,J)}:void 0,children:s.map((J,Y)=>{const z=kS(Y,s.length),Z=J.cell?.(Q,W)??J.accessor?.(Q)??Q?.[J.key];return y.jsx("td",{className:Bn(P,z,"text-sm whitespace-nowrap",CS(J.align),J.className,J.key===s[0]?.key?"font-medium text-gray-900 dark:text-white":"text-gray-500 dark:text-gray-400"),children:Z},J.key)})},re)})})]})})})})})})]})}function LA({children:s,content:e}){const t=A.useRef(null),i=A.useRef(null),[n,r]=A.useState(!1),[o,u]=A.useState(null),c=A.useRef(null),d=()=>{c.current!==null&&(window.clearTimeout(c.current),c.current=null)},f=()=>{d(),c.current=window.setTimeout(()=>{r(!1),c.current=null},150)},p=()=>{d(),r(!0)},g=()=>{f()},v=()=>{d(),r(!1)},b=()=>{const S=t.current,D=i.current;if(!S||!D)return;const R=8,L=8,P=S.getBoundingClientRect(),U=D.getBoundingClientRect();let V=P.bottom+R;if(V+U.height>window.innerHeight-L){const N=P.top-U.height-R;N>=L?V=N:V=Math.max(L,window.innerHeight-U.height-L)}let G=P.left;G+U.width>window.innerWidth-L&&(G=window.innerWidth-U.width-L),G=Math.max(L,G),u({left:G,top:V})};A.useLayoutEffect(()=>{if(!n)return;const S=requestAnimationFrame(()=>b());return()=>cancelAnimationFrame(S)},[n]),A.useEffect(()=>{if(!n)return;const S=()=>requestAnimationFrame(()=>b());return window.addEventListener("resize",S),window.addEventListener("scroll",S,!0),()=>{window.removeEventListener("resize",S),window.removeEventListener("scroll",S,!0)}},[n]),A.useEffect(()=>()=>d(),[]);const _=()=>typeof e=="function"?e(n,{close:v}):e;return y.jsxs(y.Fragment,{children:[y.jsx("div",{ref:t,className:"inline-flex",onMouseEnter:p,onMouseLeave:g,children:s}),n&&xc.createPortal(y.jsx("div",{ref:i,className:"fixed z-50",style:{left:o?.left??-9999,top:o?.top??-9999,visibility:o?"visible":"hidden"},onMouseEnter:p,onMouseLeave:g,children:y.jsx(xa,{className:"shadow-lg ring-1 ring-black/10 dark:ring-white/10 max-w-[calc(100vw-16px)]",noBodyPadding:!0,children:_()})}),document.body)]})}const Qm=!0,aO=!1;function Zm(s,e){if(!s)return;const t=e?.muted??Qm;s.muted=t,s.defaultMuted=t,s.playsInline=!0,s.setAttribute("playsinline",""),s.setAttribute("webkit-playsinline","")}function zx({job:s,getFileName:e,durationSeconds:t,onDuration:i,animated:n=!1,animatedMode:r="frames",animatedTrigger:o="always",autoTickMs:u=15e3,thumbStepSec:c,thumbSpread:d,thumbSamples:f,clipSeconds:p=1,variant:g="thumb",className:v,showPopover:b=!0,blur:_=!1,inlineVideo:S=!1,inlineNonce:D=0,inlineControls:R=!1,inlineLoop:L=!0,assetNonce:P=0,muted:U=Qm,popoverMuted:V=Qm,noGenerateTeaser:M}){const G=e(s.output||""),N=_?"blur-md":"",O={muted:U,playsInline:!0,preload:"metadata"},[K,Q]=A.useState(!0),[W,re]=A.useState(!0),[J,Y]=A.useState(!1),[z,Z]=A.useState(!1),[ie,ce]=A.useState(!0),j=A.useRef(null),[ee,he]=A.useState(!1),[Te,xe]=A.useState(!1),[Ae,Ke]=A.useState(0),[lt,nt]=A.useState(!1),yt=S===!0||S==="always"?"always":S==="hover"?"hover":"never",it=We=>We.startsWith("HOT ")?We.slice(4):We,Ot=A.useMemo(()=>{const We=e(s.output||"");if(!We)return"";const Ct=We.replace(/\.[^.]+$/,"");return it(Ct).trim()},[s.output,e]),pt=A.useMemo(()=>G?`/api/record/video?file=${encodeURIComponent(G)}`:"",[G]),xt=typeof t=="number"&&Number.isFinite(t)&&t>0,Pt=g==="fill"?"w-full h-full":"w-20 h-16",Ze=A.useRef(null),Nt=A.useRef(null),wt=A.useRef(null),jt=We=>{if(We){try{We.pause()}catch{}try{We.removeAttribute("src"),We.src="",We.load()}catch{}}};A.useEffect(()=>{Z(!1),ce(!0)},[Ot,P,M]),A.useEffect(()=>{const We=Ct=>{const Mt=String(Ct?.detail?.file??"");!Mt||Mt!==G||(jt(Ze.current),jt(Nt.current),jt(wt.current))};return window.addEventListener("player:release",We),window.addEventListener("player:close",We),()=>{window.removeEventListener("player:release",We),window.removeEventListener("player:close",We)}},[G]),A.useEffect(()=>{const We=j.current;if(!We)return;const Ct=new IntersectionObserver(Mt=>{const pi=!!Mt[0]?.isIntersecting;he(pi),pi&&xe(!0)},{threshold:.01,rootMargin:"350px 0px"});return Ct.observe(We),()=>Ct.disconnect()},[]),A.useEffect(()=>{if(!n||r!=="frames"||!ee||document.hidden)return;const We=window.setInterval(()=>Ke(Ct=>Ct+1),u);return()=>window.clearInterval(We)},[n,r,ee,u]);const gt=A.useMemo(()=>{if(!n||r!=="frames"||!xt)return null;const We=t,Ct=Math.max(.25,c??3);if(d){const Ei=Math.max(4,Math.min(f??16,Math.floor(We))),Tt=Ae%Ei,ft=Math.max(.1,We-Ct),ui=Math.min(.25,ft*.02),Pe=Tt/Ei*ft+ui;return Math.min(We-.05,Math.max(.05,Pe))}const Mt=Math.max(We-.1,Ct),pi=Ae*Ct%Mt;return Math.min(We-.05,Math.max(.05,pi))},[n,r,xt,t,Ae,c,d,f]),Dt=P??0,ge=A.useMemo(()=>Ot?gt==null?`/api/record/preview?id=${encodeURIComponent(Ot)}&v=${Dt}`:`/api/record/preview?id=${encodeURIComponent(Ot)}&t=${gt}&v=${Dt}-${Ae}`:"",[Ot,gt,Ae,Dt]),st=A.useMemo(()=>{if(!Ot)return"";const We=M?"&noGenerate=1":"";return`/api/generated/teaser?id=${encodeURIComponent(Ot)}${We}&v=${Dt}`},[Ot,Dt,M]),Ve=We=>{if(Y(!0),!i)return;const Ct=We.currentTarget.duration;Number.isFinite(Ct)&&Ct>0&&i(s,Ct)};if(A.useEffect(()=>{Q(!0),re(!0)},[Ot,P]),!pt)return y.jsx("div",{className:[Pt,"rounded bg-gray-100 dark:bg-white/5"].join(" ")});const et=yt!=="never"&&ee&&W&&(yt==="always"||yt==="hover"&<),vt=n&&ee&&!document.hidden&&W&&!et&&(o==="always"||lt)&&(r==="teaser"&&ie&&!!st||r==="clips"&&xt),ot=yt==="hover"||n&&(r==="clips"||r==="teaser")&&o==="hover",ht=Te||ot&<,rt=A.useMemo(()=>{if(!n)return[];if(r!=="clips")return[];if(!xt)return[];const We=t,Ct=Math.max(.25,p),Mt=Math.max(8,Math.min(f??18,Math.floor(We))),pi=Math.max(.1,We-Ct),Ei=Math.min(.25,pi*.02),Tt=[];for(let ft=0;ftrt.map(We=>We.toFixed(2)).join(","),[rt]),Bt=A.useRef(0),Lt=A.useRef(0);A.useEffect(()=>{const We=Nt.current;if(!We)return;if(!(vt&&r==="teaser")){try{We.pause()}catch{}return}Zm(We,{muted:U});const Mt=We.play?.();Mt&&typeof Mt.catch=="function"&&Mt.catch(()=>{})},[vt,r,st,U]),A.useEffect(()=>{et&&Zm(Ze.current,{muted:U})},[et,U]),A.useEffect(()=>{const We=wt.current;if(!We)return;if(!(vt&&r==="clips")){vt||We.pause();return}if(!rt.length)return;Bt.current=Bt.current%rt.length,Lt.current=rt[Bt.current];const Ct=()=>{try{We.currentTime=Lt.current}catch{}const Ei=We.play();Ei&&typeof Ei.catch=="function"&&Ei.catch(()=>{})},Mt=()=>Ct(),pi=()=>{if(rt.length&&We.currentTime-Lt.current>=p){Bt.current=(Bt.current+1)%rt.length,Lt.current=rt[Bt.current];try{We.currentTime=Lt.current+.01}catch{}}};return We.addEventListener("loadedmetadata",Mt),We.addEventListener("timeupdate",pi),We.readyState>=1&&Ct(),()=>{We.removeEventListener("loadedmetadata",Mt),We.removeEventListener("timeupdate",pi),We.pause()}},[vt,r,Gt,p,rt]);const si=y.jsxs("div",{ref:j,className:["rounded bg-gray-100 dark:bg-white/5 overflow-hidden relative",Pt,v??""].join(" "),onMouseEnter:ot?()=>nt(!0):void 0,onMouseLeave:ot?()=>nt(!1):void 0,onFocus:ot?()=>nt(!0):void 0,onBlur:ot?()=>nt(!1):void 0,children:[ht&&ge&&K?y.jsx("img",{src:ge,loading:"lazy",decoding:"async",alt:G,className:["absolute inset-0 w-full h-full object-cover",N].filter(Boolean).join(" "),onError:()=>Q(!1)}):y.jsx("div",{className:"absolute inset-0 bg-black/10 dark:bg-white/10"}),et?A.createElement("video",{...O,ref:Ze,key:`inline-${Ot}-${D}`,src:pt,className:["absolute inset-0 w-full h-full object-cover",N,R?"pointer-events-auto":"pointer-events-none"].filter(Boolean).join(" "),autoPlay:!0,muted:U,controls:R,loop:L,poster:ht&&ge||void 0,onLoadedMetadata:Ve,onError:()=>re(!1)}):null,!et&&vt&&r==="teaser"?y.jsx("video",{ref:Nt,src:st,className:["absolute inset-0 w-full h-full object-cover pointer-events-none",N,z?"opacity-100":"opacity-0","transition-opacity duration-150"].filter(Boolean).join(" "),muted:U,playsInline:!0,autoPlay:!0,loop:!0,preload:"metadata",poster:ht&&ge||void 0,onLoadedData:()=>Z(!0),onPlaying:()=>Z(!0),onError:()=>{ce(!1),Z(!1)}},`teaser-mp4-${Ot}`):null,!et&&vt&&r==="clips"?y.jsx("video",{ref:wt,src:pt,className:["absolute inset-0 w-full h-full object-cover pointer-events-none",N].filter(Boolean).join(" "),muted:U,playsInline:!0,preload:"metadata",poster:ht&&ge||void 0,onError:()=>re(!1)},`clips-${Ot}-${Gt}`):null,ee&&i&&!xt&&!J&&!et&&y.jsx("video",{src:pt,preload:"metadata",muted:U,playsInline:!0,className:"hidden",onLoadedMetadata:Ve})]});return b?y.jsx(LA,{content:We=>We&&y.jsx("div",{className:"w-[420px]",children:y.jsx("div",{className:"aspect-video",children:y.jsx("video",{src:pt,className:["w-full h-full bg-black",N].filter(Boolean).join(" "),muted:V,playsInline:!0,preload:"metadata",controls:!0,autoPlay:!0,loop:!0,onClick:Ct=>Ct.stopPropagation(),onMouseDown:Ct=>Ct.stopPropagation()})})}),children:si}):si}function gy(...s){return s.filter(Boolean).join(" ")}const oO={sm:{btn:"px-2.5 py-1.5 text-sm",icon:"size-5"},md:{btn:"px-3 py-2 text-sm",icon:"size-5"}};function lO({items:s,value:e,onChange:t,size:i="md",className:n,ariaLabel:r="Optionen"}){const o=oO[i];return y.jsx("span",{className:gy("isolate inline-flex rounded-md shadow-xs dark:shadow-none",n),role:"group","aria-label":r,children:s.map((u,c)=>{const d=u.id===e,f=c===0,p=c===s.length-1,g=!u.label&&!!u.icon;return y.jsxs("button",{type:"button",disabled:u.disabled,onClick:()=>t(u.id),"aria-pressed":d,className:gy("relative inline-flex items-center justify-center font-semibold focus:z-10 transition-colors",!f&&"-ml-px",f&&"rounded-l-md",p&&"rounded-r-md",d?"bg-indigo-100 text-indigo-800 inset-ring-1 inset-ring-indigo-300 hover:bg-indigo-200 dark:bg-indigo-500/40 dark:text-indigo-100 dark:inset-ring-indigo-400/50 dark:hover:bg-indigo-500/50":"bg-white text-gray-900 inset-ring-1 inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:inset-ring-gray-700 dark:hover:bg-white/20","disabled:opacity-50 disabled:cursor-not-allowed",g?"px-2 py-2":o.btn),title:typeof u.label=="string"?u.label:u.srLabel,children:[g&&u.srLabel?y.jsx("span",{className:"sr-only",children:u.srLabel}):null,u.icon?y.jsx("span",{className:gy("shrink-0",g?"":"-ml-0.5",d?"text-indigo-600 dark:text-indigo-200":"text-gray-400 dark:text-gray-500"),children:u.icon}):null,u.label?y.jsx("span",{className:u.icon?"ml-1.5":"",children:u.label}):null]},u.id)})})}function uO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.5 6h9.75M10.5 6a1.5 1.5 0 1 1-3 0m3 0a1.5 1.5 0 1 0-3 0M3.75 6H7.5m3 12h9.75m-9.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-3.75 0H7.5m9-6h3.75m-3.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-9.75 0h9.75"}))}const cO=A.forwardRef(uO);function dO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M13.5 6H5.25A2.25 2.25 0 0 0 3 8.25v10.5A2.25 2.25 0 0 0 5.25 21h10.5A2.25 2.25 0 0 0 18 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25"}))}const yy=A.forwardRef(dO);function hO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 9V4.5M9 9H4.5M9 9 3.75 3.75M9 15v4.5M9 15H4.5M9 15l-5.25 5.25M15 9h4.5M15 9V4.5M15 9l5.25-5.25M15 15h4.5M15 15v4.5m0-4.5 5.25 5.25"}))}const fO=A.forwardRef(hO);function mO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 3.75v4.5m0-4.5h4.5m-4.5 0L9 9M3.75 20.25v-4.5m0 4.5h4.5m-4.5 0L9 15M20.25 3.75h-4.5m4.5 0v4.5m0-4.5L15 9m5.25 11.25h-4.5m4.5 0v-4.5m0 4.5L15 15"}))}const pO=A.forwardRef(mO);function gO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M16.5 3.75V16.5L12 14.25 7.5 16.5V3.75m9 0H18A2.25 2.25 0 0 1 20.25 6v12A2.25 2.25 0 0 1 18 20.25H6A2.25 2.25 0 0 1 3.75 18V6A2.25 2.25 0 0 1 6 3.75h1.5m9 0h-9"}))}const jv=A.forwardRef(gO);function yO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 0 1 2.25-2.25h13.5A2.25 2.25 0 0 1 21 7.5v11.25m-18 0A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75m-18 0v-7.5A2.25 2.25 0 0 1 5.25 9h13.5A2.25 2.25 0 0 1 21 11.25v7.5m-9-6h.008v.008H12v-.008ZM12 15h.008v.008H12V15Zm0 2.25h.008v.008H12v-.008ZM9.75 15h.008v.008H9.75V15Zm0 2.25h.008v.008H9.75v-.008ZM7.5 15h.008v.008H7.5V15Zm0 2.25h.008v.008H7.5v-.008Zm6.75-4.5h.008v.008h-.008v-.008Zm0 2.25h.008v.008h-.008V15Zm0 2.25h.008v.008h-.008v-.008Zm2.25-4.5h.008v.008H16.5v-.008Zm0 2.25h.008v.008H16.5V15Z"}))}const LS=A.forwardRef(yO);function vO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"}))}const xO=A.forwardRef(vO);function bO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6.75a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5ZM12 12.75a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5ZM12 18.75a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5Z"}))}const TO=A.forwardRef(bO);function _O({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z"}))}const SO=A.forwardRef(_O);function EO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z"}),A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"}))}const $v=A.forwardRef(EO);function wO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.362 5.214A8.252 8.252 0 0 1 12 21 8.25 8.25 0 0 1 6.038 7.047 8.287 8.287 0 0 0 9 9.601a8.983 8.983 0 0 1 3.361-6.867 8.21 8.21 0 0 0 3 2.48Z"}),A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 18a3.75 3.75 0 0 0 .495-7.468 5.99 5.99 0 0 0-1.925 3.547 5.975 5.975 0 0 1-2.133-1.001A3.75 3.75 0 0 0 12 18Z"}))}const RS=A.forwardRef(wO);function AO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12Z"}))}const Jm=A.forwardRef(AO);function CO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 9h3.75M15 12h3.75M15 15h3.75M4.5 19.5h15a2.25 2.25 0 0 0 2.25-2.25V6.75A2.25 2.25 0 0 0 19.5 4.5h-15a2.25 2.25 0 0 0-2.25 2.25v10.5A2.25 2.25 0 0 0 4.5 19.5Zm6-10.125a1.875 1.875 0 1 1-3.75 0 1.875 1.875 0 0 1 3.75 0Zm1.294 6.336a6.721 6.721 0 0 1-3.17.789 6.721 6.721 0 0 1-3.168-.789 3.376 3.376 0 0 1 6.338 0Z"}))}const kO=A.forwardRef(CO);function DO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m11.25 11.25.041-.02a.75.75 0 0 1 1.063.852l-.708 2.836a.75.75 0 0 0 1.063.853l.041-.021M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9-3.75h.008v.008H12V8.25Z"}))}const LO=A.forwardRef(DO);function RO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m10.5 21 5.25-11.25L21 21m-9-3h7.5M3 5.621a48.474 48.474 0 0 1 6-.371m0 0c1.12 0 2.233.038 3.334.114M9 5.25V3m3.334 2.364C11.176 10.658 7.69 15.08 3 17.502m9.334-12.138c.896.061 1.785.147 2.666.257m-4.589 8.495a18.023 18.023 0 0 1-3.827-5.802"}))}const IO=A.forwardRef(RO);function NO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M13.19 8.688a4.5 4.5 0 0 1 1.242 7.244l-4.5 4.5a4.5 4.5 0 0 1-6.364-6.364l1.757-1.757m13.35-.622 1.757-1.757a4.5 4.5 0 0 0-6.364-6.364l-4.5 4.5a4.5 4.5 0 0 0 1.242 7.244"}))}const OO=A.forwardRef(NO);function MO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z"}))}const IS=A.forwardRef(MO);function PO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 10.5a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"}),A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19.5 10.5c0 7.142-7.5 11.25-7.5 11.25S4.5 17.642 4.5 10.5a7.5 7.5 0 1 1 15 0Z"}))}const BO=A.forwardRef(PO);function FO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 0 0 1.5-1.5V6a1.5 1.5 0 0 0-1.5-1.5H3.75A1.5 1.5 0 0 0 2.25 6v12a1.5 1.5 0 0 0 1.5 1.5Zm10.5-11.25h.008v.008h-.008V8.25Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z"}))}const UO=A.forwardRef(FO);function jO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 6.878V6a2.25 2.25 0 0 1 2.25-2.25h7.5A2.25 2.25 0 0 1 18 6v.878m-12 0c.235-.083.487-.128.75-.128h10.5c.263 0 .515.045.75.128m-12 0A2.25 2.25 0 0 0 4.5 9v.878m13.5-3A2.25 2.25 0 0 1 19.5 9v.878m0 0a2.246 2.246 0 0 0-.75-.128H5.25c-.263 0-.515.045-.75.128m15 0A2.25 2.25 0 0 1 21 12v6a2.25 2.25 0 0 1-2.25 2.25H5.25A2.25 2.25 0 0 1 3 18v-6c0-.98.626-1.813 1.5-2.122"}))}const $O=A.forwardRef(jO);function HO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9.813 15.904 9 18.75l-.813-2.846a4.5 4.5 0 0 0-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 0 0 3.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 0 0 3.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 0 0-3.09 3.09ZM18.259 8.715 18 9.75l-.259-1.035a3.375 3.375 0 0 0-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 0 0 2.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 0 0 2.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 0 0-2.456 2.456ZM16.894 20.567 16.5 21.75l-.394-1.183a2.25 2.25 0 0 0-1.423-1.423L13.5 18.75l1.183-.394a2.25 2.25 0 0 0 1.423-1.423l.394-1.183.394 1.183a2.25 2.25 0 0 0 1.423 1.423l1.183.394-1.183.394a2.25 2.25 0 0 0-1.423 1.423Z"}))}const NS=A.forwardRef(HO);function VO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6A2.25 2.25 0 0 1 6 3.75h2.25A2.25 2.25 0 0 1 10.5 6v2.25a2.25 2.25 0 0 1-2.25 2.25H6a2.25 2.25 0 0 1-2.25-2.25V6ZM3.75 15.75A2.25 2.25 0 0 1 6 13.5h2.25a2.25 2.25 0 0 1 2.25 2.25V18a2.25 2.25 0 0 1-2.25 2.25H6A2.25 2.25 0 0 1 3.75 18v-2.25ZM13.5 6a2.25 2.25 0 0 1 2.25-2.25H18A2.25 2.25 0 0 1 20.25 6v2.25A2.25 2.25 0 0 1 18 10.5h-2.25a2.25 2.25 0 0 1-2.25-2.25V6ZM13.5 15.75a2.25 2.25 0 0 1 2.25-2.25H18a2.25 2.25 0 0 1 2.25 2.25V18A2.25 2.25 0 0 1 18 20.25h-2.25A2.25 2.25 0 0 1 13.5 18v-2.25Z"}))}const GO=A.forwardRef(VO);function zO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M11.48 3.499a.562.562 0 0 1 1.04 0l2.125 5.111a.563.563 0 0 0 .475.345l5.518.442c.499.04.701.663.321.988l-4.204 3.602a.563.563 0 0 0-.182.557l1.285 5.385a.562.562 0 0 1-.84.61l-4.725-2.885a.562.562 0 0 0-.586 0L6.982 20.54a.562.562 0 0 1-.84-.61l1.285-5.386a.562.562 0 0 0-.182-.557l-4.204-3.602a.562.562 0 0 1 .321-.988l5.518-.442a.563.563 0 0 0 .475-.345L11.48 3.5Z"}))}const Hv=A.forwardRef(zO);function qO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.375 19.5h17.25m-17.25 0a1.125 1.125 0 0 1-1.125-1.125M3.375 19.5h7.5c.621 0 1.125-.504 1.125-1.125m-9.75 0V5.625m0 12.75v-1.5c0-.621.504-1.125 1.125-1.125m18.375 2.625V5.625m0 12.75c0 .621-.504 1.125-1.125 1.125m1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125m0 3.75h-7.5A1.125 1.125 0 0 1 12 18.375m9.75-12.75c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125m19.5 0v1.5c0 .621-.504 1.125-1.125 1.125M2.25 5.625v1.5c0 .621.504 1.125 1.125 1.125m0 0h17.25m-17.25 0h7.5c.621 0 1.125.504 1.125 1.125M3.375 8.25c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125m17.25-3.75h-7.5c-.621 0-1.125.504-1.125 1.125m8.625-1.125c.621 0 1.125.504 1.125 1.125v1.5c0 .621-.504 1.125-1.125 1.125m-17.25 0h7.5m-7.5 0c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125M12 10.875v-1.5m0 1.5c0 .621-.504 1.125-1.125 1.125M12 10.875c0 .621.504 1.125 1.125 1.125m-2.25 0c.621 0 1.125.504 1.125 1.125M13.125 12h7.5m-7.5 0c-.621 0-1.125.504-1.125 1.125M20.625 12c.621 0 1.125.504 1.125 1.125v1.5c0 .621-.504 1.125-1.125 1.125m-17.25 0h7.5M12 14.625v-1.5m0 1.5c0 .621-.504 1.125-1.125 1.125M12 14.625c0 .621.504 1.125 1.125 1.125m-2.25 0c.621 0 1.125.504 1.125 1.125m0 1.5v-1.5m0 0c0-.621.504-1.125 1.125-1.125m0 0h7.5"}))}const KO=A.forwardRef(qO);function YO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"}))}const Vv=A.forwardRef(YO);function WO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 19.128a9.38 9.38 0 0 0 2.625.372 9.337 9.337 0 0 0 4.121-.952 4.125 4.125 0 0 0-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 0 1 8.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0 1 11.964-3.07M12 6.375a3.375 3.375 0 1 1-6.75 0 3.375 3.375 0 0 1 6.75 0Zm8.25 2.25a2.625 2.625 0 1 1-5.25 0 2.625 2.625 0 0 1 5.25 0Z"}))}const XO=A.forwardRef(WO);function QO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m9.75 9.75 4.5 4.5m0-4.5-4.5 4.5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"}))}const ZO=A.forwardRef(QO);function JO({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18 18 6M6 6l12 12"}))}const qx=A.forwardRef(JO);function lm(...s){return s.filter(Boolean).join(" ")}const eM=A.forwardRef(function({children:e,enabled:t=!0,disabled:i=!1,onTap:n,onSwipeLeft:r,onSwipeRight:o,className:u,leftAction:c={label:y.jsxs("span",{className:"inline-flex flex-col items-center gap-1 font-semibold leading-tight",children:[y.jsx(jv,{className:"h-6 w-6","aria-hidden":"true"}),y.jsx("span",{children:"Behalten"})]}),className:"bg-emerald-500/20 text-emerald-800 dark:bg-emerald-500/15 dark:text-emerald-300"},rightAction:d={label:y.jsxs("span",{className:"inline-flex flex-col items-center gap-1 font-semibold leading-tight",children:[y.jsx(Vv,{className:"h-6 w-6","aria-hidden":"true"}),y.jsx("span",{children:"Löschen"})]}),className:"bg-red-500/20 text-red-800 dark:bg-red-500/15 dark:text-red-300"},thresholdPx:f=180,thresholdRatio:p=.1,ignoreFromBottomPx:g=72,ignoreSelector:v="[data-swipe-ignore]",snapMs:b=180,commitMs:_=180,tapIgnoreSelector:S="button,a,input,textarea,select,video[controls],video[controls] *,[data-tap-ignore]"},D){const R=A.useRef(null),L=A.useRef(0),P=A.useRef(null),U=A.useRef(0),V=A.useRef({id:null,x:0,y:0,dragging:!1,captured:!1,tapIgnored:!1}),[M,G]=A.useState(0),[N,O]=A.useState(null),[K,Q]=A.useState(0),W=A.useCallback(()=>{P.current!=null&&(cancelAnimationFrame(P.current),P.current=null),L.current=0,R.current&&(R.current.style.touchAction="pan-y"),Q(b),G(0),O(null),window.setTimeout(()=>Q(0),b)},[b]),re=A.useCallback(async(J,Y)=>{P.current!=null&&(cancelAnimationFrame(P.current),P.current=null),R.current&&(R.current.style.touchAction="pan-y");const Z=R.current?.offsetWidth||360;Q(_),O(J==="right"?"right":"left");const ie=J==="right"?Z+40:-(Z+40);L.current=ie,G(ie);let ce=!0;if(Y)try{ce=J==="right"?await o():await r()}catch{ce=!1}return ce===!1?(Q(b),O(null),G(0),window.setTimeout(()=>Q(0),b),!1):!0},[_,r,o,b]);return A.useImperativeHandle(D,()=>({swipeLeft:J=>re("left",J?.runAction??!0),swipeRight:J=>re("right",J?.runAction??!0),reset:()=>W()}),[re,W]),y.jsxs("div",{className:lm("relative overflow-hidden rounded-lg",u),children:[y.jsxs("div",{className:"absolute inset-0 pointer-events-none overflow-hidden rounded-lg",children:[y.jsx("div",{className:lm("absolute inset-0 transition-opacity duration-200 ease-out",M===0?"opacity-0":"opacity-100",M>0?c.className:d.className)}),y.jsx("div",{className:lm("absolute inset-0 flex items-center transition-all duration-200 ease-out"),style:{transform:`translateX(${Math.max(-24,Math.min(24,M/8))}px)`,opacity:M===0?0:1,justifyContent:M>0?"flex-start":"flex-end",paddingLeft:M>0?16:0,paddingRight:M>0?0:16},children:M>0?c.label:d.label})]}),y.jsx("div",{ref:R,className:"relative",style:{transform:M!==0?`translate3d(${M}px,0,0)`:void 0,transition:K?`transform ${K}ms ease`:void 0,touchAction:"pan-y",willChange:M!==0?"transform":void 0},onPointerDown:J=>{if(!t||i)return;const Y=J.target,z=!!(S&&Y?.closest?.(S));if(v&&Y?.closest?.(v))return;const Z=J.currentTarget,ce=Array.from(Z.querySelectorAll("video")).find(xe=>xe.controls);if(ce){const xe=ce.getBoundingClientRect();if(J.clientX>=xe.left&&J.clientX<=xe.right&&J.clientY>=xe.top&&J.clientY<=xe.bottom){if(xe.bottom-J.clientY<=72)return;const nt=64,yt=J.clientX-xe.left,it=xe.right-J.clientX;if(!(yt<=nt||it<=nt))return}}const ee=J.currentTarget.getBoundingClientRect().bottom-J.clientY;if(g&&ee<=g)return;V.current={id:J.pointerId,x:J.clientX,y:J.clientY,dragging:!1,captured:!1,tapIgnored:z};const Te=R.current?.offsetWidth||360;U.current=Math.min(f,Te*p),L.current=0},onPointerMove:J=>{if(!t||i||V.current.id!==J.pointerId)return;const Y=J.clientX-V.current.x,z=J.clientY-V.current.y;if(!V.current.dragging){if(Math.abs(z)>Math.abs(Y)&&Math.abs(z)>8){V.current.id=null;return}if(Math.abs(Y)<12)return;V.current.dragging=!0,J.currentTarget.style.touchAction="none",Q(0);try{J.currentTarget.setPointerCapture(J.pointerId),V.current.captured=!0}catch{V.current.captured=!1}}L.current=Y,P.current==null&&(P.current=requestAnimationFrame(()=>{P.current=null,G(L.current)}));const Z=U.current,ie=Y>Z?"right":Y<-Z?"left":null;O(ce=>ce===ie?ce:ie)},onPointerUp:J=>{if(!t||i||V.current.id!==J.pointerId)return;const Y=U.current||Math.min(f,(R.current?.offsetWidth||360)*p),z=V.current.dragging,Z=V.current.captured,ie=V.current.tapIgnored;if(V.current.id=null,V.current.dragging=!1,V.current.captured=!1,Z)try{J.currentTarget.releasePointerCapture(J.pointerId)}catch{}if(J.currentTarget.style.touchAction="pan-y",!z){if(ie){Q(0),G(0),O(null);return}W(),n?.();return}const ce=L.current;P.current!=null&&(cancelAnimationFrame(P.current),P.current=null),ce>Y?re("right",!0):ce<-Y?re("left",!0):W(),L.current=0},onPointerCancel:J=>{if(!(!t||i)){if(V.current.captured&&V.current.id!=null)try{J.currentTarget.releasePointerCapture(V.current.id)}catch{}V.current={id:null,x:0,y:0,dragging:!1,captured:!1,tapIgnored:!1},P.current!=null&&(cancelAnimationFrame(P.current),P.current=null),L.current=0;try{J.currentTarget.style.touchAction="pan-y"}catch{}W()}},children:y.jsxs("div",{className:"relative",children:[y.jsx("div",{className:"relative z-10",children:e}),y.jsx("div",{className:lm("absolute inset-0 z-20 pointer-events-none transition-opacity duration-150 rounded-lg",N==="right"&&"bg-emerald-500/20 opacity-100",N==="left"&&"bg-red-500/20 opacity-100",N===null&&"opacity-0")})]})})]})});function tM({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{d:"M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z"}),A.createElement("path",{fillRule:"evenodd",d:"M1.323 11.447C2.811 6.976 7.028 3.75 12.001 3.75c4.97 0 9.185 3.223 10.675 7.69.12.362.12.752 0 1.113-1.487 4.471-5.705 7.697-10.677 7.697-4.97 0-9.186-3.223-10.675-7.69a1.762 1.762 0 0 1 0-1.113ZM17.25 12a5.25 5.25 0 1 1-10.5 0 5.25 5.25 0 0 1 10.5 0Z",clipRule:"evenodd"}))}const Tc=A.forwardRef(tM);function iM({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{fillRule:"evenodd",d:"M12.963 2.286a.75.75 0 0 0-1.071-.136 9.742 9.742 0 0 0-3.539 6.176 7.547 7.547 0 0 1-1.705-1.715.75.75 0 0 0-1.152-.082A9 9 0 1 0 15.68 4.534a7.46 7.46 0 0 1-2.717-2.248ZM15.75 14.25a3.75 3.75 0 1 1-7.313-1.172c.628.465 1.35.81 2.133 1a5.99 5.99 0 0 1 1.925-3.546 3.75 3.75 0 0 1 3.255 3.718Z",clipRule:"evenodd"}))}const OS=A.forwardRef(iM);function sM({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{d:"M7.493 18.5c-.425 0-.82-.236-.975-.632A7.48 7.48 0 0 1 6 15.125c0-1.75.599-3.358 1.602-4.634.151-.192.373-.309.6-.397.473-.183.89-.514 1.212-.924a9.042 9.042 0 0 1 2.861-2.4c.723-.384 1.35-.956 1.653-1.715a4.498 4.498 0 0 0 .322-1.672V2.75A.75.75 0 0 1 15 2a2.25 2.25 0 0 1 2.25 2.25c0 1.152-.26 2.243-.723 3.218-.266.558.107 1.282.725 1.282h3.126c1.026 0 1.945.694 2.054 1.715.045.422.068.85.068 1.285a11.95 11.95 0 0 1-2.649 7.521c-.388.482-.987.729-1.605.729H14.23c-.483 0-.964-.078-1.423-.23l-3.114-1.04a4.501 4.501 0 0 0-1.423-.23h-.777ZM2.331 10.727a11.969 11.969 0 0 0-.831 4.398 12 12 0 0 0 .52 3.507C2.28 19.482 3.105 20 3.994 20H4.9c.445 0 .72-.498.523-.898a8.963 8.963 0 0 1-.924-3.977c0-1.708.476-3.305 1.302-4.666.245-.403-.028-.959-.5-.959H4.25c-.832 0-1.612.453-1.918 1.227Z"}))}const nM=A.forwardRef(sM);function rM({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{d:"m11.645 20.91-.007-.003-.022-.012a15.247 15.247 0 0 1-.383-.218 25.18 25.18 0 0 1-4.244-3.17C4.688 15.36 2.25 12.174 2.25 8.25 2.25 5.322 4.714 3 7.688 3A5.5 5.5 0 0 1 12 5.052 5.5 5.5 0 0 1 16.313 3c2.973 0 5.437 2.322 5.437 5.25 0 3.925-2.438 7.111-4.739 9.256a25.175 25.175 0 0 1-4.244 3.17 15.247 15.247 0 0 1-.383.219l-.022.012-.007.004-.003.001a.752.752 0 0 1-.704 0l-.003-.001Z"}))}const _c=A.forwardRef(rM);function aM({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{fillRule:"evenodd",d:"M6.75 5.25a.75.75 0 0 1 .75-.75H9a.75.75 0 0 1 .75.75v13.5a.75.75 0 0 1-.75.75H7.5a.75.75 0 0 1-.75-.75V5.25Zm7.5 0A.75.75 0 0 1 15 4.5h1.5a.75.75 0 0 1 .75.75v13.5a.75.75 0 0 1-.75.75H15a.75.75 0 0 1-.75-.75V5.25Z",clipRule:"evenodd"}))}const oM=A.forwardRef(aM);function lM({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{fillRule:"evenodd",d:"M4.5 5.653c0-1.427 1.529-2.33 2.779-1.643l11.54 6.347c1.295.712 1.295 2.573 0 3.286L7.28 19.99c-1.25.687-2.779-.217-2.779-1.643V5.653Z",clipRule:"evenodd"}))}const uM=A.forwardRef(lM);function cM({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{fillRule:"evenodd",d:"M5.636 4.575a.75.75 0 0 1 0 1.061 9 9 0 0 0 0 12.728.75.75 0 1 1-1.06 1.06c-4.101-4.1-4.101-10.748 0-14.849a.75.75 0 0 1 1.06 0Zm12.728 0a.75.75 0 0 1 1.06 0c4.101 4.1 4.101 10.75 0 14.85a.75.75 0 1 1-1.06-1.061 9 9 0 0 0 0-12.728.75.75 0 0 1 0-1.06ZM7.757 6.697a.75.75 0 0 1 0 1.06 6 6 0 0 0 0 8.486.75.75 0 0 1-1.06 1.06 7.5 7.5 0 0 1 0-10.606.75.75 0 0 1 1.06 0Zm8.486 0a.75.75 0 0 1 1.06 0 7.5 7.5 0 0 1 0 10.606.75.75 0 0 1-1.06-1.06 6 6 0 0 0 0-8.486.75.75 0 0 1 0-1.06ZM9.879 8.818a.75.75 0 0 1 0 1.06 3 3 0 0 0 0 4.243.75.75 0 1 1-1.061 1.061 4.5 4.5 0 0 1 0-6.364.75.75 0 0 1 1.06 0Zm4.242 0a.75.75 0 0 1 1.061 0 4.5 4.5 0 0 1 0 6.364.75.75 0 0 1-1.06-1.06 3 3 0 0 0 0-4.243.75.75 0 0 1 0-1.061ZM10.875 12a1.125 1.125 0 1 1 2.25 0 1.125 1.125 0 0 1-2.25 0Z",clipRule:"evenodd"}))}const dM=A.forwardRef(cM);function hM({title:s,titleId:e,...t},i){return A.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?A.createElement("title",{id:e},s):null,A.createElement("path",{fillRule:"evenodd",d:"M10.788 3.21c.448-1.077 1.976-1.077 2.424 0l2.082 5.006 5.404.434c1.164.093 1.636 1.545.749 2.305l-4.117 3.527 1.257 5.273c.271 1.136-.964 2.033-1.96 1.425L12 18.354 7.373 21.18c-.996.608-2.231-.29-1.96-1.425l1.257-5.273-4.117-3.527c-.887-.76-.415-2.212.749-2.305l5.404-.434 2.082-5.005Z",clipRule:"evenodd"}))}const yh=A.forwardRef(hM);function Br({tag:s,children:e,title:t,active:i,onClick:n,maxWidthClassName:r="max-w-[11rem]",className:o,stopPropagation:u=!0}){const c=s??(typeof e=="string"||typeof e=="number"?String(e):""),d=wi("inline-flex items-center truncate rounded-md px-2 py-0.5 text-xs",r,"bg-sky-50 text-sky-700 dark:bg-sky-500/10 dark:text-sky-200"),g=wi(d,i?"bg-sky-100 text-sky-800 dark:bg-sky-400/20 dark:text-sky-100":"",n?"cursor-pointer hover:bg-sky-100 dark:hover:bg-sky-400/20 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:focus-visible:outline-indigo-500":"",o),v=_=>_.stopPropagation(),b=u?{onPointerDown:v,onMouseDown:v}:{};return n?y.jsx("button",{type:"button",className:g,title:t??c,"aria-pressed":!!i,...b,onClick:_=>{u&&(_.preventDefault(),_.stopPropagation()),c&&n(c)},children:e??s}):y.jsx("span",{className:g,title:t??c,...b,onClick:u?v:void 0,children:e??s})}function Ci(...s){return s.filter(Boolean).join(" ")}const fM=s=>(s||"").replaceAll("\\","/").trim().split("/").pop()||"",mM=s=>s.startsWith("HOT ")?s.slice(4):s,pM=/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}/;function gM(s){const t=mM(fM(s||"")).replace(/\.[^.]+$/,""),i=t.match(pM);if(i?.[1]?.trim())return i[1].trim();const n=t.lastIndexOf("_");return n>0?t.slice(0,n):t||null}function va({job:s,variant:e="overlay",collapseToMenu:t=!1,inlineCount:i,busy:n=!1,compact:r=!1,isHot:o=!1,isFavorite:u=!1,isLiked:c=!1,isWatching:d=!1,showFavorite:f,showLike:p,showHot:g,showKeep:v,showDelete:b,showWatch:_,showDetails:S,onToggleFavorite:D,onToggleLike:R,onToggleHot:L,onKeep:P,onDelete:U,onToggleWatch:V,order:M,className:G}){const N=e==="overlay"?r?"p-1.5":"p-2":"p-1.5",O=r?"size-4":"size-5",K="h-full w-full",Q=e==="table"?`inline-flex items-center justify-center rounded-md ${N} hover:bg-gray-100/70 dark:hover:bg-white/5 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/60 disabled:opacity-50 disabled:cursor-not-allowed transition-transform active:scale-95`:`inline-flex items-center justify-center rounded-md bg-white/75 ${N} text-gray-900 backdrop-blur ring-1 ring-black/10 hover:bg-white/90 dark:bg-black/40 dark:text-white dark:ring-white/10 dark:hover:bg-black/60 focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500/60 dark:focus-visible:ring-white/40 disabled:opacity-50 disabled:cursor-not-allowed transition-transform active:scale-95`,W=e==="table"?{favOn:"text-amber-600 dark:text-amber-300",likeOn:"text-rose-600 dark:text-rose-300",hotOn:"text-amber-600 dark:text-amber-300",off:"text-gray-500 dark:text-gray-300",keep:"text-emerald-600 dark:text-emerald-300",del:"text-red-600 dark:text-red-300",watchOn:"text-sky-600 dark:text-sky-300"}:{favOn:"text-amber-600 dark:text-amber-300",likeOn:"text-rose-600 dark:text-rose-300",hotOn:"text-amber-600 dark:text-amber-300",off:"text-gray-800/90 dark:text-white/90",keep:"text-emerald-600 dark:text-emerald-200",del:"text-red-600 dark:text-red-300",watchOn:"text-sky-600 dark:text-sky-200"},re=f??!!D,J=p??!!R,Y=g??!!L,z=v??!!P,Z=b??!!U,ie=_??!!V,ce=S??!0,j=gM(s.output||""),ee=j?`Mehr zu ${j} anzeigen`:"Mehr anzeigen",[he,Te]=A.useState(0),[xe,Ae]=A.useState(4),Ke=Tt=>ft=>{ft.preventDefault(),ft.stopPropagation(),!(n||!Tt)&&Promise.resolve(Tt(s)).catch(()=>{})},lt=ce&&j?y.jsxs("button",{type:"button",className:Ci(Q),title:ee,"aria-label":ee,disabled:n,onClick:Tt=>{Tt.preventDefault(),Tt.stopPropagation(),!n&&window.dispatchEvent(new CustomEvent("open-model-details",{detail:{modelKey:j}}))},children:[y.jsx("span",{className:Ci("inline-flex items-center justify-center",O),children:y.jsx(IS,{className:Ci(K,W.off)})}),y.jsx("span",{className:"sr-only",children:ee})]}):null,nt=re?y.jsx("button",{type:"button",className:Q,title:u?"Favorit entfernen":"Als Favorit markieren","aria-label":u?"Favorit entfernen":"Als Favorit markieren","aria-pressed":u,disabled:n||!D,onClick:Ke(D),children:y.jsxs("span",{className:Ci("relative inline-block",O),children:[y.jsx(Hv,{className:Ci("absolute inset-0 transition-all duration-200 ease-out motion-reduce:transition-none",u?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0",K,W.off)}),y.jsx(yh,{className:Ci("absolute inset-0 transition-all duration-200 ease-out motion-reduce:transition-none",u?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12",K,W.favOn)})]})}):null,yt=J?y.jsx("button",{type:"button",className:Q,title:c?"Gefällt mir entfernen":"Als Gefällt mir markieren","aria-label":c?"Gefällt mir entfernen":"Als Gefällt mir markieren","aria-pressed":c,disabled:n||!R,onClick:Ke(R),children:y.jsxs("span",{className:Ci("relative inline-block",O),children:[y.jsx(Jm,{className:Ci("absolute inset-0 transition-all duration-200 ease-out motion-reduce:transition-none",c?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0",K,W.off)}),y.jsx(_c,{className:Ci("absolute inset-0 transition-all duration-200 ease-out motion-reduce:transition-none",c?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12",K,W.likeOn)})]})}):null,it=Y?y.jsx("button",{type:"button",className:Q,title:o?"HOT entfernen":"Als HOT markieren","aria-label":o?"HOT entfernen":"Als HOT markieren","aria-pressed":o,disabled:n||!L,onClick:Ke(L),children:y.jsxs("span",{className:Ci("relative inline-block",O),children:[y.jsx(RS,{className:Ci("absolute inset-0 transition-all duration-200 ease-out",o?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0",K,W.off)}),y.jsx(OS,{className:Ci("absolute inset-0 transition-all duration-200 ease-out",o?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12",K,W.hotOn)})]})}):null,Ot=ie?y.jsx("button",{type:"button",className:Q,title:d?"Watched entfernen":"Als Watched markieren","aria-label":d?"Watched entfernen":"Als Watched markieren","aria-pressed":d,disabled:n||!V,onClick:Ke(V),children:y.jsxs("span",{className:Ci("relative inline-block",O),children:[y.jsx($v,{className:Ci("absolute inset-0 transition-all duration-200 ease-out",d?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0",K,W.off)}),y.jsx(Tc,{className:Ci("absolute inset-0 transition-all duration-200 ease-out",d?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12",K,W.watchOn)})]})}):null,pt=z?y.jsx("button",{type:"button",className:Q,title:"Behalten (nach keep verschieben)","aria-label":"Behalten",disabled:n||!P,onClick:Ke(P),children:y.jsx("span",{className:Ci("inline-flex items-center justify-center",O),children:y.jsx(jv,{className:Ci(K,W.keep)})})}):null,xt=Z?y.jsx("button",{type:"button",className:Q,title:"Löschen","aria-label":"Löschen",disabled:n||!U,onClick:Ke(U),children:y.jsx("span",{className:Ci("inline-flex items-center justify-center",O),children:y.jsx(Vv,{className:Ci(K,W.del)})})}):null,Pt=M??["watch","favorite","like","hot","keep","delete","details"],Ze={details:lt,favorite:nt,like:yt,watch:Ot,hot:it,keep:pt,delete:xt},Nt=t&&e==="overlay",wt=Pt.filter(Tt=>!!Ze[Tt]),jt=Nt&&typeof i!="number",ge=(r?16:20)+(e==="overlay"?r?6:8:6)*2,st=r?2:3,Ve=A.useMemo(()=>{if(!jt)return i??st;const Tt=he||0;if(Tt<=0)return Math.min(wt.length,st);for(let ft=wt.length;ft>=0;ft--)if(ft*ge+ge+(ft>0?ft*xe:0)<=Tt)return ft;return 0},[jt,i,st,he,wt.length,ge,xe]),et=Nt?wt.slice(0,Ve):wt,vt=Nt?wt.slice(Ve):[],[ot,ht]=A.useState(!1),rt=A.useRef(null);A.useLayoutEffect(()=>{const Tt=rt.current;if(!Tt||typeof window>"u")return;const ft=()=>{const Pe=rt.current;if(!Pe)return;const H=Math.floor(Pe.getBoundingClientRect().width||0);H>0&&Te(H);const q=window.getComputedStyle(Pe),ne=q.columnGap||q.gap||"0",Se=parseFloat(ne);Number.isFinite(Se)&&Se>=0&&Ae(Se)};ft();const ui=new ResizeObserver(()=>ft());return ui.observe(Tt),window.addEventListener("resize",ft),()=>{window.removeEventListener("resize",ft),ui.disconnect()}},[]);const Gt=A.useRef(null),Bt=A.useRef(null),Lt=208,si=4,We=8,[Ct,Mt]=A.useState(null);A.useEffect(()=>{if(!ot)return;const Tt=ui=>{ui.key==="Escape"&&ht(!1)},ft=ui=>{const Pe=rt.current,H=Bt.current,q=ui.target;Pe&&Pe.contains(q)||H&&H.contains(q)||ht(!1)};return window.addEventListener("keydown",Tt),window.addEventListener("mousedown",ft),()=>{window.removeEventListener("keydown",Tt),window.removeEventListener("mousedown",ft)}},[ot]),A.useLayoutEffect(()=>{if(!ot){Mt(null);return}const Tt=()=>{const ft=Gt.current;if(!ft)return;const ui=ft.getBoundingClientRect(),Pe=window.innerWidth,H=window.innerHeight;let q=ui.right-Lt;q=Math.max(We,Math.min(q,Pe-Lt-We));let ne=ui.bottom+si;ne=Math.max(We,Math.min(ne,H-We));const Se=Math.max(120,H-ne-We);Mt({top:ne,left:q,maxH:Se})};return Tt(),window.addEventListener("resize",Tt),window.addEventListener("scroll",Tt,!0),()=>{window.removeEventListener("resize",Tt),window.removeEventListener("scroll",Tt,!0)}},[ot]);const pi=()=>{j&&window.dispatchEvent(new CustomEvent("open-model-details",{detail:{modelKey:j}}))},Ei=Tt=>Tt==="details"?y.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-gray-100/70 dark:hover:bg-white/5 disabled:opacity-50",disabled:n,onClick:ft=>{ft.preventDefault(),ft.stopPropagation(),ht(!1),pi()},children:[y.jsx(IS,{className:Ci("size-4",W.off)}),y.jsx("span",{className:"truncate",children:"Details"})]},"details"):Tt==="favorite"?y.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-gray-100/70 dark:hover:bg-white/5 disabled:opacity-50",disabled:n||!D,onClick:async ft=>{ft.preventDefault(),ft.stopPropagation(),ht(!1),await D?.(s)},children:[u?y.jsx(yh,{className:Ci("size-4",W.favOn)}):y.jsx(Hv,{className:Ci("size-4",W.off)}),y.jsx("span",{className:"truncate",children:u?"Favorit entfernen":"Als Favorit markieren"})]},"favorite"):Tt==="like"?y.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-gray-100/70 dark:hover:bg-white/5 disabled:opacity-50",disabled:n||!R,onClick:async ft=>{ft.preventDefault(),ft.stopPropagation(),ht(!1),await R?.(s)},children:[c?y.jsx(_c,{className:Ci("size-4",W.favOn)}):y.jsx(Jm,{className:Ci("size-4",W.off)}),y.jsx("span",{className:"truncate",children:c?"Gefällt mir entfernen":"Gefällt mir"})]},"like"):Tt==="watch"?y.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-gray-100/70 dark:hover:bg-white/5 disabled:opacity-50",disabled:n||!V,onClick:async ft=>{ft.preventDefault(),ft.stopPropagation(),ht(!1),await V?.(s)},children:[d?y.jsx(Tc,{className:Ci("size-4",W.favOn)}):y.jsx($v,{className:Ci("size-4",W.off)}),y.jsx("span",{className:"truncate",children:d?"Watched entfernen":"Watched"})]},"watch"):Tt==="hot"?y.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-gray-100/70 dark:hover:bg-white/5 disabled:opacity-50",disabled:n||!L,onClick:async ft=>{ft.preventDefault(),ft.stopPropagation(),ht(!1),await L?.(s)},children:[o?y.jsx(OS,{className:Ci("size-4",W.favOn)}):y.jsx(RS,{className:Ci("size-4",W.off)}),y.jsx("span",{className:"truncate",children:o?"HOT entfernen":"Als HOT markieren"})]},"hot"):Tt==="keep"?y.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-gray-100/70 dark:hover:bg-white/5 disabled:opacity-50",disabled:n||!P,onClick:async ft=>{ft.preventDefault(),ft.stopPropagation(),ht(!1),await P?.(s)},children:[y.jsx(jv,{className:Ci("size-4",W.keep)}),y.jsx("span",{className:"truncate",children:"Behalten"})]},"keep"):Tt==="delete"?y.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-gray-100/70 dark:hover:bg-white/5 disabled:opacity-50",disabled:n||!U,onClick:async ft=>{ft.preventDefault(),ft.stopPropagation(),ht(!1),await U?.(s)},children:[y.jsx(Vv,{className:Ci("size-4",W.del)}),y.jsx("span",{className:"truncate",children:"Löschen"})]},"delete"):null;return y.jsxs("div",{ref:rt,className:Ci("relative flex items-center flex-nowrap",G??"gap-2"),children:[et.map(Tt=>{const ft=Ze[Tt];return ft?y.jsx(A.Fragment,{children:ft},Tt):null}),Nt&&vt.length>0?y.jsxs("div",{className:"relative",children:[y.jsx("button",{ref:Gt,type:"button",className:Q,"aria-label":"Mehr",title:"Mehr","aria-haspopup":"menu","aria-expanded":ot,disabled:n,onClick:Tt=>{Tt.preventDefault(),Tt.stopPropagation(),!n&&ht(ft=>!ft)},children:y.jsx("span",{className:Ci("inline-flex items-center justify-center",O),children:y.jsx(TO,{className:Ci(K,W.off)})})}),ot&&Ct&&typeof document<"u"?xc.createPortal(y.jsx("div",{ref:Bt,role:"menu",className:"rounded-md bg-white/95 dark:bg-gray-900/95 shadow-lg ring-1 ring-black/10 dark:ring-white/10 p-1 z-[9999] overflow-auto",style:{position:"fixed",top:Ct.top,left:Ct.left,width:Lt,maxHeight:Ct.maxH},onClick:Tt=>Tt.stopPropagation(),children:vt.map(Ei)}),document.body):null]}):null]})}function Kx({children:s,force:e=!1,rootMargin:t="300px",placeholder:i=null,className:n}){const r=A.useRef(null),[o,u]=A.useState(e);return A.useEffect(()=>{e&&!o&&u(!0)},[e,o]),A.useEffect(()=>{if(o||e)return;const c=r.current;if(!c)return;const d=new IntersectionObserver(f=>{f.some(p=>p.isIntersecting)&&(u(!0),d.disconnect())},{rootMargin:t});return d.observe(c),()=>d.disconnect()},[o,e,t]),y.jsx("div",{ref:r,className:n,children:o?s:i})}const RA=/^HOT[ \u00A0]+/i,IA=s=>String(s||"").replaceAll(" "," "),ec=s=>RA.test(IA(s)),ca=s=>IA(s).replace(RA,"");function yM(...s){return s.filter(Boolean).join(" ")}const vM=s=>{const e=String(s??"").trim();if(!e)return[];const t=e.split(/[\n,;|]+/g).map(r=>r.trim()).filter(Boolean),i=new Set,n=[];for(const r of t){const o=r.toLowerCase();i.has(o)||(i.add(o),n.push(r))}return n};function xM({rows:s,isSmall:e,teaserPlayback:t,teaserAudio:i,hoverTeaserKey:n,blurPreviews:r,teaserKey:o,inlinePlay:u,setInlinePlay:c,deletingKeys:d,keepingKeys:f,removingKeys:p,swipeRefs:g,assetNonce:v,keyFor:b,baseName:_,modelNameFromOutput:S,runtimeOf:D,sizeBytesOf:R,formatBytes:L,lower:P,onHoverPreviewKeyChange:U,onOpenPlayer:V,openPlayer:M,startInline:G,tryAutoplayInline:N,registerTeaserHost:O,deleteVideo:K,keepVideo:Q,releasePlayingFile:W,modelsByKey:re,activeTagSet:J,onToggleTagFilter:Y,onToggleHot:z,onToggleFavorite:Z,onToggleLike:ie,onToggleWatch:ce}){const[j,ee]=A.useState(null),he=A.useRef(null);A.useEffect(()=>{if(!j)return;const xe=Ke=>{Ke.key==="Escape"&&ee(null)},Ae=Ke=>{const lt=he.current;lt&&(lt.contains(Ke.target)||ee(null))};return document.addEventListener("keydown",xe),document.addEventListener("pointerdown",Ae),()=>{document.removeEventListener("keydown",xe),document.removeEventListener("pointerdown",Ae)}},[j]),A.useEffect(()=>{if(!j)return;s.some(Ae=>b(Ae)===j)||ee(null)},[s,b,j]);const Te=e?"180px":"500px";return y.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:s.map(xe=>{const Ae=b(xe),Ke=u?.key===Ae,nt=!(!!i&&(Ke||n===Ae)),yt=Ke?u?.nonce??0:0,it=d.has(Ae)||f.has(Ae)||p.has(Ae),Ot=S(xe.output),pt=_(xe.output||""),xt=ec(pt),Pt=re[P(Ot)],Ze=!!Pt?.favorite,Nt=Pt?.liked===!0,wt=!!Pt?.watching,jt=vM(Pt?.tags),gt=jt.slice(0,6),Dt=jt.length-gt.length,ge=jt.join(", "),st=xe.status==="failed"?"bg-red-500/35":xe.status==="finished"?"bg-emerald-500/35":xe.status==="stopped"?"bg-amber-500/35":"bg-black/40",Ve=D(xe),et=L(R(xe)),vt=`inline-prev-${encodeURIComponent(Ae)}`,ot=e?"":"transition-all duration-300 ease-in-out hover:-translate-y-0.5 hover:shadow-md dark:hover:shadow-none",ht=y.jsx("div",{role:"button",tabIndex:0,className:["group",ot,"rounded-xl","focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:focus-visible:outline-indigo-500",it&&"pointer-events-none",d.has(Ae)&&"ring-1 ring-red-300 bg-red-50/60 dark:bg-red-500/10 dark:ring-red-500/30 animate-pulse",f.has(Ae)&&"ring-1 ring-emerald-300 bg-emerald-50/60 dark:bg-emerald-500/10 dark:ring-emerald-500/30 animate-pulse",p.has(Ae)&&"opacity-0 translate-y-2 scale-[0.98]"].filter(Boolean).join(" "),onClick:e?void 0:()=>M(xe),onKeyDown:rt=>{(rt.key==="Enter"||rt.key===" ")&&V(xe)},children:y.jsxs(xa,{noBodyPadding:!0,className:"overflow-hidden",children:[y.jsxs("div",{id:vt,ref:O(Ae),className:"relative aspect-video bg-black/5 dark:bg-white/5",onMouseEnter:e?void 0:()=>U?.(Ae),onMouseLeave:e?void 0:()=>U?.(null),onClick:rt=>{rt.preventDefault(),rt.stopPropagation(),!e&&G(Ae)},children:[y.jsx(Kx,{force:Ke,rootMargin:Te,placeholder:y.jsx("div",{className:"w-full h-full bg-black/5 dark:bg-white/5 animate-pulse"}),className:"absolute inset-0",children:y.jsx(zx,{job:xe,getFileName:rt=>ca(_(rt)),className:"w-full h-full",showPopover:!1,blur:e||Ke?!1:r,animated:t==="all"?!0:t==="hover"?o===Ae:!1,animatedMode:"teaser",animatedTrigger:"always",inlineVideo:Ke?"always":!1,inlineNonce:yt,inlineControls:Ke,inlineLoop:!1,muted:nt,popoverMuted:nt,assetNonce:v??0})}),y.jsx("div",{className:["pointer-events-none absolute inset-x-0 bottom-0 h-20 bg-gradient-to-t from-black/70 to-transparent","transition-opacity duration-150",Ke?"opacity-0":"opacity-100"].join(" ")}),y.jsx("div",{className:["pointer-events-none absolute inset-x-0 bottom-0 p-2 text-white","transition-opacity duration-150",Ke?"opacity-0":"opacity-100"].join(" "),children:y.jsxs("div",{className:"flex items-center justify-between gap-2 text-[11px] opacity-90",children:[y.jsx("span",{className:yM("rounded px-1.5 py-0.5 font-semibold",st),children:xe.status}),y.jsxs("div",{className:"flex items-center gap-1.5",children:[y.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:Ve}),y.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:et})]})]})}),!e&&u?.key===Ae&&y.jsx("button",{type:"button",className:"absolute left-2 top-2 z-10 rounded-md bg-black/40 px-2 py-1 text-xs font-semibold text-white backdrop-blur hover:bg-black/60",onClick:rt=>{rt.preventDefault(),rt.stopPropagation(),c(Gt=>({key:Ae,nonce:Gt?.key===Ae?Gt.nonce+1:1}))},title:"Von vorne starten","aria-label":"Von vorne starten",children:"↻"}),y.jsx("div",{className:"absolute right-2 top-2 flex items-center gap-2",onClick:rt=>rt.stopPropagation(),onMouseDown:rt=>rt.stopPropagation(),children:y.jsx(va,{job:xe,variant:"overlay",busy:it,isHot:xt,isFavorite:Ze,isLiked:Nt,isWatching:wt,onToggleWatch:ce,onToggleFavorite:Z,onToggleLike:ie,onToggleHot:z?async rt=>{const Gt=_(rt.output||"");Gt&&(await W(Gt,{close:!0}),await new Promise(Bt=>setTimeout(Bt,150))),await z(rt)}:void 0,showKeep:!e,showDelete:!e,onKeep:Q,onDelete:K,order:["watch","favorite","like","hot","details","keep","delete"],className:"flex items-center gap-2"})})]}),y.jsxs("div",{className:["px-4 py-3 rounded-b-lg border-t border-gray-200/60 dark:border-white/10",e?"bg-white/90 dark:bg-gray-950/80":"bg-white/60 backdrop-blur dark:bg-white/5"].join(" "),children:[y.jsxs("div",{className:"flex items-center justify-between gap-2",children:[y.jsx("div",{className:"min-w-0 truncate text-sm font-semibold text-gray-900 dark:text-white",children:Ot}),y.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[wt?y.jsx(Tc,{className:"size-4 text-sky-600 dark:text-sky-300"}):null,Nt?y.jsx(_c,{className:"size-4 text-rose-600 dark:text-rose-300"}):null,Ze?y.jsx(yh,{className:"size-4 text-amber-600 dark:text-amber-300"}):null]})]}),y.jsxs("div",{className:"mt-0.5 flex items-center gap-2 min-w-0 text-xs text-gray-500 dark:text-gray-400",children:[y.jsx("span",{className:"truncate",children:ca(pt)||"—"}),xt?y.jsx("span",{className:"shrink-0 rounded bg-amber-500/15 px-1.5 py-0.5 text-[11px] font-semibold text-amber-800 dark:text-amber-300",children:"HOT"}):null]}),y.jsxs("div",{className:"mt-2 h-6 relative flex items-center gap-1.5",onClick:rt=>rt.stopPropagation(),onMouseDown:rt=>rt.stopPropagation(),children:[y.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:y.jsx("div",{className:"flex flex-nowrap items-center gap-1.5",children:gt.length>0?gt.map(rt=>y.jsx(Br,{tag:rt,active:J.has(P(rt)),onClick:Y},rt)):y.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"—"})})}),Dt>0?y.jsxs("button",{type:"button",className:"shrink-0 inline-flex items-center rounded-md bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-700 ring-1 ring-inset ring-gray-200 hover:bg-gray-200/70 dark:bg-white/5 dark:text-gray-200 dark:ring-white/10 dark:hover:bg-white/10",title:ge,"aria-haspopup":"dialog","aria-expanded":j===Ae,onPointerDown:rt=>rt.stopPropagation(),onClick:rt=>{rt.preventDefault(),rt.stopPropagation(),ee(Gt=>Gt===Ae?null:Ae)},children:["+",Dt]}):null,j===Ae?y.jsxs("div",{ref:he,className:["absolute right-0 bottom-8 z-30 w-72 max-w-[calc(100vw-2rem)] overflow-hidden rounded-lg border border-gray-200/70 bg-white/95 shadow-lg ring-1 ring-black/5",e?"":"backdrop-blur","dark:border-white/10 dark:bg-gray-950/90 dark:ring-white/10"].join(" "),onClick:rt=>rt.stopPropagation(),onMouseDown:rt=>rt.stopPropagation(),children:[y.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-gray-200/60 px-3 py-2 dark:border-white/10",children:[y.jsx("div",{className:"text-xs font-semibold text-gray-900 dark:text-white",children:"Tags"}),y.jsx("button",{type:"button",className:"rounded px-2 py-1 text-xs font-medium text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-white/10",onClick:()=>ee(null),"aria-label":"Schließen",title:"Schließen",children:"✕"})]}),y.jsx("div",{className:"max-h-48 overflow-auto p-2",children:y.jsx("div",{className:"flex flex-wrap gap-1.5",children:jt.map(rt=>y.jsx(Br,{tag:rt,active:J.has(P(rt)),onClick:Y},rt))})})]}):null]})]})]})});return e?y.jsx(eM,{ref:rt=>{rt?g.current.set(Ae,rt):g.current.delete(Ae)},enabled:!0,disabled:it,ignoreFromBottomPx:110,onTap:()=>{const rt=`inline-prev-${encodeURIComponent(Ae)}`;G(Ae),requestAnimationFrame(()=>{N(rt)||requestAnimationFrame(()=>N(rt))})},onSwipeLeft:()=>K(xe),onSwipeRight:()=>Q(xe),children:ht},Ae):y.jsx(A.Fragment,{children:ht},Ae)})})}function bM({rows:s,columns:e,getRowKey:t,sort:i,onSortChange:n,onRowClick:r,rowClassName:o}){return y.jsx(Gx,{rows:s,columns:e,getRowKey:t,striped:!0,fullWidth:!0,stickyHeader:!0,compact:!1,card:!0,sort:i,onSortChange:n,onRowClick:r,rowClassName:o})}function TM({rows:s,blurPreviews:e,durations:t,teaserPlayback:i,teaserAudio:n,hoverTeaserKey:r,teaserKey:o,handleDuration:u,keyFor:c,baseName:d,modelNameFromOutput:f,runtimeOf:p,sizeBytesOf:g,formatBytes:v,deletingKeys:b,keepingKeys:_,removingKeys:S,deletedKeys:D,registerTeaserHost:R,onHoverPreviewKeyChange:L,onOpenPlayer:P,deleteVideo:U,keepVideo:V,onToggleHot:M,lower:G,modelsByKey:N,activeTagSet:O,onToggleTagFilter:K,onToggleFavorite:Q,onToggleLike:W,onToggleWatch:re}){const[J,Y]=A.useState(null),z=A.useRef(null),Z=i==="hover"||i==="all",ie=A.useCallback(j=>ee=>{if(!Z){R(j)(null);return}R(j)(ee)},[R,Z]);A.useEffect(()=>{if(!J)return;const j=he=>{he.key==="Escape"&&Y(null)},ee=he=>{const Te=z.current;Te&&(Te.contains(he.target)||Y(null))};return document.addEventListener("keydown",j),document.addEventListener("pointerdown",ee),()=>{document.removeEventListener("keydown",j),document.removeEventListener("pointerdown",ee)}},[J]),A.useEffect(()=>{if(!J)return;s.some(ee=>c(ee)===J)||Y(null)},[s,c,J]);const ce=j=>{const ee=String(j??"").trim();if(!ee)return[];const he=ee.split(/[\n,;|]+/g).map(Ae=>Ae.trim()).filter(Boolean),Te=new Set,xe=[];for(const Ae of he){const Ke=Ae.toLowerCase();Te.has(Ke)||(Te.add(Ke),xe.push(Ae))}return xe};return y.jsx(y.Fragment,{children:y.jsx("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4",children:s.map(j=>{const ee=c(j),Te=!(!!n&&r===ee),xe=f(j.output),Ae=G(xe),Ke=N[Ae],lt=!!Ke?.favorite,nt=Ke?.liked===!0,yt=!!Ke?.watching,it=ce(Ke?.tags),Ot=it.slice(0,6),pt=it.length-Ot.length,xt=it.join(", "),Pt=d(j.output||""),Ze=ec(Pt),Nt=ca(Pt),wt=p(j),jt=v(g(j)),gt=b.has(ee)||_.has(ee)||S.has(ee),Dt=D.has(ee);return y.jsxs("div",{role:"button",tabIndex:0,className:["group relative rounded-lg overflow-hidden outline-1 outline-black/5 dark:-outline-offset-1 dark:outline-white/10","bg-white dark:bg-gray-900/40","transition-all duration-200","hover:-translate-y-0.5 hover:shadow-md dark:hover:shadow-none","focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:focus-visible:outline-indigo-500",gt&&"pointer-events-none opacity-70",b.has(ee)&&"ring-1 ring-red-300 bg-red-50/60 dark:bg-red-500/10 dark:ring-red-500/30",S.has(ee)&&"opacity-0 translate-y-2 scale-[0.98]",Dt&&"hidden"].filter(Boolean).join(" "),onClick:()=>P(j),onKeyDown:ge=>{(ge.key==="Enter"||ge.key===" ")&&P(j)},children:[y.jsxs("div",{className:"group relative aspect-video rounded-t-lg bg-black/5 dark:bg-white/5",ref:ie(ee),onMouseEnter:()=>L?.(ee),onMouseLeave:()=>L?.(null),children:[y.jsxs("div",{className:"absolute inset-0 overflow-hidden rounded-t-lg",children:[y.jsx(Kx,{force:o===ee||r===ee,rootMargin:"500px",placeholder:y.jsx("div",{className:"absolute inset-0 bg-black/5 dark:bg-white/5 animate-pulse"}),className:"absolute inset-0",children:y.jsx(zx,{job:j,getFileName:ge=>ca(d(ge)),durationSeconds:t[ee]??j?.durationSeconds,onDuration:u,variant:"fill",showPopover:!1,blur:e,animated:i==="all"?!0:i==="hover"?o===ee:!1,animatedMode:"teaser",animatedTrigger:"always",clipSeconds:1,thumbSamples:18,muted:Te,popoverMuted:Te})}),y.jsx("div",{className:` pointer-events-none absolute inset-x-0 bottom-0 h-16 bg-gradient-to-t from-black/65 to-transparent transition-opacity duration-150 group-hover:opacity-0 group-focus-within:opacity-0 `}),y.jsx("div",{className:` pointer-events-none absolute inset-x-0 bottom-0 p-2 text-white `,children:y.jsxs("div",{className:"flex items-end justify-between gap-2",children:[y.jsx("div",{className:"min-w-0",children:y.jsx("div",{children:y.jsx("span",{className:["inline-block rounded px-1.5 py-0.5 text-[11px] font-semibold",j.status==="finished"?"bg-emerald-600/70":j.status==="stopped"?"bg-amber-600/70":j.status==="failed"?"bg-red-600/70":"bg-black/50"].join(" "),children:j.status})})}),y.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[y.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 text-xs font-medium",children:wt}),y.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 text-xs font-medium",children:jt})]})]})})]}),y.jsx("div",{className:"absolute inset-x-2 top-2 z-10 flex justify-end",onClick:ge=>ge.stopPropagation(),children:y.jsx(va,{job:j,variant:"overlay",busy:gt,collapseToMenu:!0,isHot:Ze,isFavorite:lt,isLiked:nt,isWatching:yt,onToggleWatch:re,onToggleFavorite:Q,onToggleLike:W,onToggleHot:M,onKeep:V,onDelete:U,order:["watch","favorite","like","hot","keep","delete","details"],className:"w-full justify-end gap-1"})})]}),y.jsxs("div",{className:"px-4 py-3 rounded-b-lg border-t border-gray-200/60 bg-white/60 backdrop-blur dark:border-white/10 dark:bg-white/5",children:[y.jsxs("div",{className:"flex items-center justify-between gap-2",children:[y.jsx("div",{className:"min-w-0 truncate text-sm font-semibold text-gray-900 dark:text-white",children:xe}),y.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[yt?y.jsx(Tc,{className:"size-4 text-sky-600 dark:text-sky-300"}):null,nt?y.jsx(_c,{className:"size-4 text-rose-600 dark:text-rose-300"}):null,lt?y.jsx(yh,{className:"size-4 text-amber-600 dark:text-amber-300"}):null]})]}),y.jsxs("div",{className:"mt-0.5 flex items-center gap-2 min-w-0 text-xs text-gray-500 dark:text-gray-400",children:[y.jsx("span",{className:"truncate",children:ca(Nt)||"—"}),Ze?y.jsx("span",{className:"shrink-0 rounded bg-amber-500/15 px-1.5 py-0.5 text-[11px] font-semibold text-amber-800 dark:text-amber-300",children:"HOT"}):null]}),y.jsxs("div",{className:"mt-2 h-6 relative flex items-center gap-1.5",onClick:ge=>ge.stopPropagation(),onMouseDown:ge=>ge.stopPropagation(),children:[y.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:y.jsx("div",{className:"flex flex-nowrap items-center gap-1.5",children:Ot.length>0?Ot.map(ge=>y.jsx(Br,{tag:ge,active:O.has(G(ge)),onClick:K},ge)):y.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"—"})})}),pt>0?y.jsxs("button",{type:"button",className:"shrink-0 inline-flex items-center rounded-md bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-700 ring-1 ring-inset ring-gray-200 hover:bg-gray-200/70 dark:bg-white/5 dark:text-gray-200 dark:ring-white/10 dark:hover:bg-white/10",title:xt,"aria-haspopup":"dialog","aria-expanded":J===ee,onPointerDown:ge=>ge.stopPropagation(),onClick:ge=>{ge.preventDefault(),ge.stopPropagation(),Y(st=>st===ee?null:ee)},children:["+",pt]}):null,J===ee?y.jsxs("div",{ref:z,className:"absolute right-0 bottom-8 z-30 w-72 max-w-[calc(100vw-2rem)] overflow-hidden rounded-lg border border-gray-200/70 bg-white/95 shadow-lg ring-1 ring-black/5 backdrop-blur dark:border-white/10 dark:bg-gray-950/90 dark:ring-white/10",onClick:ge=>ge.stopPropagation(),onMouseDown:ge=>ge.stopPropagation(),children:[y.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-gray-200/60 px-3 py-2 dark:border-white/10",children:[y.jsx("div",{className:"text-xs font-semibold text-gray-900 dark:text-white",children:"Tags"}),y.jsx("button",{type:"button",className:"rounded px-2 py-1 text-xs font-medium text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-white/10",onClick:()=>Y(null),"aria-label":"Schließen",title:"Schließen",children:"✕"})]}),y.jsx("div",{className:"max-h-48 overflow-auto p-2",children:y.jsx("div",{className:"flex flex-wrap gap-1.5",children:it.map(ge=>y.jsx(Br,{tag:ge,active:O.has(G(ge)),onClick:K},ge))})})]}):null]})]})]},ee)})})})}function MS(s,e,t){return Math.max(e,Math.min(t,s))}function vy(s,e){const t=[];for(let i=s;i<=e;i++)t.push(i);return t}function _M(s,e,t,i){if(s<=1)return[1];const n=1,r=s,o=vy(n,Math.min(t,r)),u=vy(Math.max(r-t+1,t+1),r),c=Math.max(Math.min(e-i,r-t-i*2-1),t+1),d=Math.min(Math.max(e+i,t+i*2+2),r-t),f=[];f.push(...o),c>t+1?f.push("ellipsis"):t+1t&&f.push(r-t),f.push(...u);const p=new Set;return f.filter(g=>{const v=String(g);return p.has(v)?!1:(p.add(v),!0)})}function SM({active:s,disabled:e,rounded:t,onClick:i,children:n,title:r}){const o=t==="l"?"rounded-l-md":t==="r"?"rounded-r-md":"";return y.jsx("button",{type:"button",disabled:e,onClick:e?void 0:i,title:r,className:wi("relative inline-flex items-center px-4 py-2 text-sm font-semibold focus:z-20 focus:outline-offset-0",o,e?"opacity-50 cursor-not-allowed":"cursor-pointer",s?"z-10 bg-indigo-600 text-white focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:bg-indigo-500 dark:focus-visible:outline-indigo-500":"text-gray-900 inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:text-gray-200 dark:inset-ring-gray-700 dark:hover:bg-white/5"),"aria-current":s?"page":void 0,children:n})}function NA({page:s,pageSize:e,totalItems:t,onPageChange:i,siblingCount:n=1,boundaryCount:r=1,showSummary:o=!0,className:u,ariaLabel:c="Pagination",prevLabel:d="Previous",nextLabel:f="Next"}){const p=Math.max(1,Math.ceil((t||0)/Math.max(1,e||1))),g=MS(s||1,1,p);if(p<=1)return null;const v=t===0?0:(g-1)*e+1,b=Math.min(g*e,t),_=_M(p,g,r,n),S=D=>i(MS(D,1,p));return y.jsxs("div",{className:wi("flex items-center justify-between border-t border-gray-200 bg-white px-4 py-3 sm:px-6 dark:border-white/10 dark:bg-transparent",u),children:[y.jsxs("div",{className:"flex flex-1 justify-between sm:hidden",children:[y.jsx("button",{type:"button",onClick:()=>S(g-1),disabled:g<=1,className:"relative inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed dark:border-white/10 dark:bg-white/5 dark:text-gray-200 dark:hover:bg-white/10",children:d}),y.jsx("button",{type:"button",onClick:()=>S(g+1),disabled:g>=p,className:"relative ml-3 inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed dark:border-white/10 dark:bg-white/5 dark:text-gray-200 dark:hover:bg-white/10",children:f})]}),y.jsxs("div",{className:"hidden sm:flex sm:flex-1 sm:items-center sm:justify-between",children:[y.jsx("div",{children:o?y.jsxs("p",{className:"text-sm text-gray-700 dark:text-gray-300",children:["Showing ",y.jsx("span",{className:"font-medium",children:v})," to"," ",y.jsx("span",{className:"font-medium",children:b})," of"," ",y.jsx("span",{className:"font-medium",children:t})," results"]}):null}),y.jsx("div",{children:y.jsxs("nav",{"aria-label":c,className:"isolate inline-flex -space-x-px rounded-md shadow-xs dark:shadow-none",children:[y.jsxs("button",{type:"button",onClick:()=>S(g-1),disabled:g<=1,className:"relative inline-flex items-center rounded-l-md px-2 py-2 text-gray-400 inset-ring inset-ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0 disabled:opacity-50 disabled:cursor-not-allowed dark:inset-ring-gray-700 dark:hover:bg-white/5",children:[y.jsx("span",{className:"sr-only",children:d}),y.jsx(eO,{"aria-hidden":"true",className:"size-5"})]}),_.map((D,R)=>D==="ellipsis"?y.jsx("span",{className:"relative inline-flex items-center px-4 py-2 text-sm font-semibold text-gray-700 inset-ring inset-ring-gray-300 dark:text-gray-400 dark:inset-ring-gray-700",children:"…"},`e-${R}`):y.jsx(SM,{active:D===g,onClick:()=>S(D),rounded:"none",children:D},D)),y.jsxs("button",{type:"button",onClick:()=>S(g+1),disabled:g>=p,className:"relative inline-flex items-center rounded-r-md px-2 py-2 text-gray-400 inset-ring inset-ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0 disabled:opacity-50 disabled:cursor-not-allowed dark:inset-ring-gray-700 dark:hover:bg-white/5",children:[y.jsx("span",{className:"sr-only",children:f}),y.jsx(iO,{"aria-hidden":"true",className:"size-5"})]})]})})]})]})}const OA=A.createContext(null);function EM(s){switch(s){case"success":return{Icon:xO,cls:"text-emerald-500"};case"error":return{Icon:ZO,cls:"text-rose-500"};case"warning":return{Icon:SO,cls:"text-amber-500"};default:return{Icon:LO,cls:"text-sky-500"}}}function wM(s){switch(s){case"success":return"border-emerald-200/70 dark:border-emerald-400/20";case"error":return"border-rose-200/70 dark:border-rose-400/20";case"warning":return"border-amber-200/70 dark:border-amber-400/20";default:return"border-sky-200/70 dark:border-sky-400/20"}}function AM(s){switch(s){case"success":return"Erfolg";case"error":return"Fehler";case"warning":return"Hinweis";default:return"Info"}}function CM(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function kM({children:s,maxToasts:e=3,defaultDurationMs:t=3500,position:i="bottom-right"}){const[n,r]=A.useState([]),o=A.useCallback(v=>{r(b=>b.filter(_=>_.id!==v))},[]),u=A.useCallback(()=>r([]),[]),c=A.useCallback(v=>{const b=CM(),_=v.durationMs??t;return r(S=>[{...v,id:b,durationMs:_},...S].slice(0,Math.max(1,e))),_&&_>0&&window.setTimeout(()=>o(b),_),b},[t,e,o]),d=A.useMemo(()=>({push:c,remove:o,clear:u}),[c,o,u]),f=i==="top-right"||i==="top-left"?"items-start sm:items-start sm:justify-start":"items-end sm:items-end sm:justify-end",p=i.endsWith("left")?"sm:items-start":"sm:items-end",g=i.startsWith("top")?"top-0 bottom-auto":"bottom-0 top-auto";return y.jsxs(OA.Provider,{value:d,children:[s,y.jsx("div",{"aria-live":"assertive",className:["pointer-events-none fixed z-[80] inset-x-0",g].join(" "),children:y.jsx("div",{className:["flex w-full px-4 py-6 sm:p-6",f].join(" "),children:y.jsx("div",{className:["flex w-full flex-col space-y-3",p].join(" "),children:n.map(v=>{const{Icon:b,cls:_}=EM(v.type),S=(v.title||"").trim()||AM(v.type),D=(v.message||"").trim();return y.jsx(oh,{appear:!0,show:!0,children:y.jsx("div",{className:["pointer-events-auto w-full max-w-sm overflow-hidden rounded-xl","border bg-white/90 shadow-lg backdrop-blur","outline-1 outline-black/5","dark:bg-gray-950/70 dark:-outline-offset-1 dark:outline-white/10",wM(v.type),"transition data-closed:opacity-0 data-enter:transform data-enter:duration-200 data-enter:ease-out","data-closed:data-enter:translate-y-2 sm:data-closed:data-enter:translate-y-0",i.endsWith("right")?"sm:data-closed:data-enter:translate-x-2":"sm:data-closed:data-enter:-translate-x-2"].join(" "),children:y.jsx("div",{className:"p-4",children:y.jsxs("div",{className:"flex items-start gap-3",children:[y.jsx("div",{className:"shrink-0",children:y.jsx(b,{className:["size-6",_].join(" "),"aria-hidden":"true"})}),y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsx("p",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:S}),D?y.jsx("p",{className:"mt-1 text-sm text-gray-600 dark:text-gray-300 break-words",children:D}):null]}),y.jsxs("button",{type:"button",onClick:()=>o(v.id),className:"shrink-0 rounded-md text-gray-400 hover:text-gray-600 focus:outline-2 focus:outline-offset-2 focus:outline-indigo-600 dark:hover:text-white dark:focus:outline-indigo-500",children:[y.jsx("span",{className:"sr-only",children:"Close"}),y.jsx(nO,{"aria-hidden":"true",className:"size-5"})]})]})})})},v.id)})})})})]})}function DM(){const s=A.useContext(OA);if(!s)throw new Error("useToast must be used within ");return s}function MA(){const{push:s,remove:e,clear:t}=DM(),i=n=>(r,o,u)=>s({type:n,title:r,message:o,...u});return{push:s,remove:e,clear:t,success:i("success"),error:i("error"),info:i("info"),warning:i("warning")}}const Yx=s=>(s||"").replaceAll("\\","/"),Tn=s=>{const t=Yx(s).split("/");return t[t.length-1]||""},Fn=s=>Tn(s.output||"")||s.id,LM=s=>{const e=Yx(String(s??""));return e.includes("/.trash/")||e.endsWith("/.trash")};function PS(s){if(!Number.isFinite(s)||s<=0)return"—";const e=Math.floor(s/1e3),t=Math.floor(e/3600),i=Math.floor(e%3600/60),n=e%60;return t>0?`${t}h ${i}m`:i>0?`${i}m ${n}s`:`${n}s`}function xy(s){if(typeof s!="number"||!Number.isFinite(s)||s<=0)return"—";const e=["B","KB","MB","GB","TB"];let t=s,i=0;for(;t>=1024&&i=100?0:t>=10?1:2;return`${t.toFixed(n)} ${e[i]}`}function BS(s){const[e,t]=A.useState(!1);return A.useEffect(()=>{const i=window.matchMedia(s),n=()=>t(i.matches);return n(),i.addEventListener?i.addEventListener("change",n):i.addListener(n),()=>{i.removeEventListener?i.removeEventListener("change",n):i.removeListener(n)}},[s]),e}const RM=s=>{const e=(s??"").match(/\bHTTP\s+(\d{3})\b/i);return e?`HTTP ${e[1]}`:null},Vo=s=>{const e=Tn(s||""),t=ca(e);if(!t)return"—";const i=t.replace(/\.[^.]+$/,""),n=i.match(/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}$/);if(n?.[1])return n[1];const r=i.lastIndexOf("_");return r>0?i.slice(0,r):i},yn=s=>(s||"").trim().toLowerCase(),FS=s=>{const e=String(s??"").trim();if(!e)return[];const t=e.split(/[\n,;|]+/g).map(r=>r.trim()).filter(Boolean),i=new Set,n=[];for(const r of t){const o=r.toLowerCase();i.has(o)||(i.add(o),n.push(r))}return n.sort((r,o)=>r.localeCompare(o,void 0,{sensitivity:"base"})),n},um=s=>{const e=s,t=e.sizeBytes??e.fileSizeBytes??e.bytes??e.size??null;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:null};function IM({jobs:s,doneJobs:e,blurPreviews:t,teaserPlayback:i,teaserAudio:n,onOpenPlayer:r,onDeleteJob:o,onToggleHot:u,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f,doneTotal:p,page:g,pageSize:v,onPageChange:b,assetNonce:_,sortMode:S,onSortModeChange:D,modelsByKey:R}){const L=i??"hover",P=BS("(hover: hover) and (pointer: fine)"),U=MA(),V=A.useRef(new Map),[M,G]=A.useState(null),[N,O]=A.useState(null),K=A.useRef(null),Q=A.useRef(new WeakMap),[W,re]=A.useState(()=>new Set),[J,Y]=A.useState(()=>new Set),[z,Z]=A.useState(null),[ie,ce]=A.useState(!1),[j,ee]=A.useState({}),[he,Te]=A.useState(null),[xe,Ae]=A.useState(null),[Ke,lt]=A.useState(0),nt=A.useRef(null),yt=A.useCallback(()=>{nt.current&&window.clearTimeout(nt.current),nt.current=window.setTimeout(()=>lt(le=>le+1),80)},[]),[it,Ot]=A.useState(null),pt="finishedDownloads_view",xt="finishedDownloads_includeKeep_v2",Pt="finishedDownloads_mobileOptionsOpen_v1",[Ze,Nt]=A.useState("table"),[wt,jt]=A.useState(!1),[gt,Dt]=A.useState(!1),ge=A.useRef(new Map),st=A.useCallback(async()=>{if(!z||ie)return;ce(!0);const le=ae=>{re(ye=>{const be=new Set(ye);return be.delete(ae),be}),Y(ye=>{const be=new Set(ye);return be.delete(ae),be}),is(ye=>{const be=new Set(ye);return be.delete(ae),be}),Zi(ye=>{const be=new Set(ye);return be.delete(ae),be})};try{if(z.kind==="delete"){const ae=await fetch(`/api/record/restore?token=${encodeURIComponent(z.undoToken)}`,{method:"POST"});if(!ae.ok){const Me=await ae.text().catch(()=>"");throw new Error(Me||`HTTP ${ae.status}`)}const ye=await ae.json().catch(()=>null),be=String(ye?.restoredFile||z.originalFile);le(z.originalFile),le(be),window.dispatchEvent(new CustomEvent("finished-downloads:count-hint",{detail:{delta:1}})),yt(),Z(null);return}if(z.kind==="keep"){const ae=await fetch(`/api/record/unkeep?file=${encodeURIComponent(z.keptFile)}`,{method:"POST"});if(!ae.ok){const Me=await ae.text().catch(()=>"");throw new Error(Me||`HTTP ${ae.status}`)}const ye=await ae.json().catch(()=>null),be=String(ye?.newFile||z.originalFile);le(z.originalFile),le(be),window.dispatchEvent(new CustomEvent("finished-downloads:count-hint",{detail:{delta:1}})),yt(),Z(null);return}if(z.kind==="hot"){const ae=await fetch(`/api/record/toggle-hot?file=${encodeURIComponent(z.currentFile)}`,{method:"POST"});if(!ae.ok){const Fe=await ae.text().catch(()=>"");throw new Error(Fe||`HTTP ${ae.status}`)}const ye=await ae.json().catch(()=>null),be=String(ye?.oldFile||z.currentFile),Me=String(ye?.newFile||"");Me&&Yt(be,Me),yt(),Z(null);return}}catch(ae){U.error("Undo fehlgeschlagen",String(ae?.message||ae))}finally{ce(!1)}},[z,ie,U,yt]),[Ve,et]=A.useState([]),vt=A.useMemo(()=>new Set(Ve.map(yn)),[Ve]),ot=A.useMemo(()=>{const le={},ae={};for(const[ye,be]of Object.entries(R??{})){const Me=yn(ye),Fe=FS(be?.tags);le[Me]=Fe,ae[Me]=new Set(Fe.map(yn))}return{tagsByModelKey:le,tagSetByModelKey:ae}},[R]),[ht,rt]=A.useState(""),Gt=A.useDeferredValue(ht),Bt=A.useMemo(()=>yn(Gt).split(/\s+/g).map(le=>le.trim()).filter(Boolean),[Gt]),Lt=A.useCallback(()=>rt(""),[]),si=A.useCallback(le=>{const ae=yn(le);et(ye=>ye.some(Me=>yn(Me)===ae)?ye.filter(Me=>yn(Me)!==ae):[...ye,le])},[]),We=Bt.length>0||vt.size>0,Ct=A.useCallback(async le=>{const ae=await fetch(`/api/record/done?all=1&sort=${encodeURIComponent(S)}&withCount=1${wt?"&includeKeep=1":""}`,{cache:"no-store",signal:le});if(!ae.ok)return;const ye=await ae.json().catch(()=>null),be=Array.isArray(ye?.items)?ye.items:[],Me=Number(ye?.count??ye?.totalCount??be.length);Te(be),Ae(Number.isFinite(Me)?Me:be.length)},[S,wt]),Mt=A.useCallback(()=>et([]),[]);A.useEffect(()=>{try{const le=localStorage.getItem("finishedDownloads_pendingTags");if(!le)return;const ae=JSON.parse(le),ye=Array.isArray(ae)?ae.map(be=>String(be||"").trim()).filter(Boolean):[];if(ye.length===0)return;xc.flushSync(()=>et(ye)),g!==1&&b(1)}catch{}finally{try{localStorage.removeItem("finishedDownloads_pendingTags")}catch{}}},[]),A.useEffect(()=>{if(!We)return;const le=new AbortController,ae=window.setTimeout(()=>{Ct(le.signal).catch(()=>{})},250);return()=>{window.clearTimeout(ae),le.abort()}},[We,Ct]),A.useEffect(()=>{if(Ke===0)return;if(We){const ae=new AbortController;return(async()=>{try{await Ct(ae.signal)}catch{}})(),()=>ae.abort()}const le=new AbortController;return(async()=>{try{const ae=await fetch(`/api/record/done?page=${g}&pageSize=${v}&sort=${encodeURIComponent(S)}&withCount=1${wt?"&includeKeep=1":""}`,{cache:"no-store",signal:le.signal});if(ae.ok){const ye=await ae.json().catch(()=>null),be=Array.isArray(ye?.items)?ye.items:[],Me=Number(ye?.count??ye?.totalCount??be.length);if(Te(be),Number.isFinite(Me)&&Me>=0){Ae(Me);const Fe=Math.max(1,Math.ceil(Me/v));if(g>Fe){b(Fe),Te(null);return}}}}catch{}})(),()=>le.abort()},[Ke,g,v,b,S,We,Ct,wt]),A.useEffect(()=>{We||(Te(null),Ae(null))},[g,v,S,wt,We]),A.useEffect(()=>{if(!wt){We||(Te(null),Ae(null));return}if(We)return;const le=new AbortController;return(async()=>{try{const ae=await fetch(`/api/record/done?page=${g}&pageSize=${v}&sort=${encodeURIComponent(S)}&withCount=1&includeKeep=1`,{cache:"no-store",signal:le.signal});if(!ae.ok)return;const ye=await ae.json().catch(()=>null),be=Array.isArray(ye?.items)?ye.items:[],Me=Number(ye?.count??ye?.totalCount??be.length);Te(be),Ae(Number.isFinite(Me)?Me:be.length)}catch{}})(),()=>le.abort()},[wt,We,g,v,S]),A.useEffect(()=>{try{const le=localStorage.getItem(pt);Nt(le==="table"||le==="cards"||le==="gallery"?le:window.matchMedia("(max-width: 639px)").matches?"cards":"table")}catch{Nt("table")}},[]),A.useEffect(()=>{try{localStorage.setItem(pt,Ze)}catch{}},[Ze]),A.useEffect(()=>{try{const le=localStorage.getItem(xt);jt(le==="1"||le==="true"||le==="yes")}catch{jt(!1)}},[]),A.useEffect(()=>{try{localStorage.setItem(xt,wt?"1":"0")}catch{}},[wt]),A.useEffect(()=>{try{const le=localStorage.getItem(Pt);Dt(le==="1"||le==="true"||le==="yes")}catch{Dt(!1)}},[]),A.useEffect(()=>{try{localStorage.setItem(Pt,gt?"1":"0")}catch{}},[gt]);const[pi,Ei]=A.useState({}),Tt=A.useRef({}),ft=A.useRef(null);A.useEffect(()=>{Tt.current=pi},[pi]);const ui=A.useCallback(()=>{ft.current==null&&(ft.current=window.setTimeout(()=>{ft.current=null,Ei({...Tt.current})},200))},[]);A.useEffect(()=>()=>{ft.current!=null&&(window.clearTimeout(ft.current),ft.current=null)},[]);const[Pe,H]=A.useState(null),q=!n,ne=A.useCallback(le=>{const ye=document.getElementById(le)?.querySelector("video");if(!ye)return!1;Zm(ye,{muted:q});const be=ye.play?.();return be&&typeof be.catch=="function"&&be.catch(()=>{}),!0},[q]),Se=A.useCallback(le=>{H(ae=>ae?.key===le?{key:le,nonce:ae.nonce+1}:{key:le,nonce:1})},[]),Je=A.useCallback(le=>{H(null),r(le)},[r]),_t=A.useCallback((le,ae)=>{Y(ye=>{const be=new Set(ye);return ae?be.add(le):be.delete(le),be})},[]),ei=A.useCallback(le=>{re(ae=>{const ye=new Set(ae);return ye.add(le),ye})},[]),[Ai,is]=A.useState(()=>new Set),Ii=A.useCallback((le,ae)=>{is(ye=>{const be=new Set(ye);return ae?be.add(le):be.delete(le),be})},[]),[ji,Zi]=A.useState(()=>new Set),gi=A.useCallback((le,ae)=>{Zi(ye=>{const be=new Set(ye);return ae?be.add(le):be.delete(le),be})},[]),ss=A.useCallback(le=>{gi(le,!0),window.setTimeout(()=>{ei(le),gi(le,!1),yt()},320)},[ei,gi,yt]),ci=A.useCallback(async(le,ae)=>{window.dispatchEvent(new CustomEvent("player:release",{detail:{file:le}})),ae?.close&&window.dispatchEvent(new CustomEvent("player:close",{detail:{file:le}})),await new Promise(ye=>window.setTimeout(ye,250))},[]),Ni=A.useCallback(async le=>{const ae=Tn(le.output||""),ye=Fn(le);if(!ae)return U.error("Löschen nicht möglich","Kein Dateiname gefunden – kann nicht löschen."),!1;if(J.has(ye))return!1;_t(ye,!0);try{if(await ci(ae,{close:!0}),o){const ct=(await o(le))?.undoToken;return typeof ct=="string"&&ct?Z({kind:"delete",undoToken:ct,originalFile:ae}):(Z(null),U.error("Undo nicht möglich","Delete-Handler liefert kein undoToken zurück.")),!0}const be=await fetch(`/api/record/delete?file=${encodeURIComponent(ae)}`,{method:"POST"});if(!be.ok){const Qe=await be.text().catch(()=>"");throw new Error(Qe||`HTTP ${be.status}`)}const Me=await be.json().catch(()=>null),Fe=typeof Me?.undoToken=="string"?Me.undoToken:"";return Z(Fe?{kind:"delete",undoToken:Fe,originalFile:ae}:null),ss(ye),window.dispatchEvent(new CustomEvent("finished-downloads:count-hint",{detail:{delta:-1}})),!0}catch(be){return U.error("Löschen fehlgeschlagen",String(be?.message||be)),!1}finally{_t(ye,!1)}},[J,_t,ci,o,ss,U,Z]),ri=A.useCallback(async le=>{const ae=Tn(le.output||""),ye=Fn(le);if(!ae)return U.error("Keep nicht möglich","Kein Dateiname gefunden – kann nicht behalten."),!1;if(Ai.has(ye)||J.has(ye))return!1;Ii(ye,!0);try{await ci(ae,{close:!0});const be=await fetch(`/api/record/keep?file=${encodeURIComponent(ae)}`,{method:"POST"});if(!be.ok){const Qe=await be.text().catch(()=>"");throw new Error(Qe||`HTTP ${be.status}`)}const Me=await be.json().catch(()=>null),Fe=typeof Me?.newFile=="string"&&Me.newFile?Me.newFile:ae;return Z({kind:"keep",keptFile:Fe,originalFile:ae}),ss(ye),window.dispatchEvent(new CustomEvent("finished-downloads:count-hint",{detail:{delta:-1}})),!0}catch(be){return U.error("Keep fehlgeschlagen",String(be?.message||be)),!1}finally{Ii(ye,!1)}},[Ai,J,Ii,ci,ss,U,Z]),Yt=A.useCallback((le,ae)=>{if(!le||!ae||le===ae)return;ee(Me=>{const Fe={...Me};for(const[Qe,ct]of Object.entries(Fe))(Qe===le||Qe===ae||ct===le||ct===ae)&&delete Fe[Qe];return Fe[le]=ae,Fe});const ye=Tt.current||{},be=ye[le];if(typeof be=="number"){const Me={...ye};delete Me[le],Me[ae]=be,Tt.current=Me,Ei(Me)}else if(le in ye){const Me={...ye};delete Me[le],Tt.current=Me,Ei(Me)}},[]),Xt=A.useCallback(async le=>{const ae=Tn(le.output||"");if(!ae){U.error("HOT nicht möglich","Kein Dateiname gefunden – kann nicht HOT togglen.");return}const ye=Fe=>ec(Fe)?ca(Fe):`HOT ${Fe}`,be=(Fe,Qe)=>{Yt(Fe,Qe)},Me=(Fe,Qe,ct)=>{Qe&&(Qe===ct&&Fe===ae||Yt(Fe,Qe))};try{await ci(ae,{close:!0});const Fe=ae,Qe=ye(Fe);if(be(Fe,Qe),Z({kind:"hot",currentFile:Qe}),u){await u(le),yt();return}const ct=await fetch(`/api/record/toggle-hot?file=${encodeURIComponent(ae)}`,{method:"POST"});if(!ct.ok){const mt=await ct.text().catch(()=>"");throw new Error(mt||`HTTP ${ct.status}`)}const oe=await ct.json().catch(()=>null),pe=typeof oe?.oldFile=="string"&&oe.oldFile?oe.oldFile:ae,Ge=typeof oe?.newFile=="string"&&oe.newFile?oe.newFile:"";Me(pe,Ge,Qe),Ge&&Z({kind:"hot",currentFile:Ge}),yt()}catch(Fe){U.error("HOT umbenennen fehlgeschlagen",String(Fe?.message||Fe))}},[ci,u,U,yt,Yt,Z]),Hs=A.useCallback(le=>{const ae=le?.durationSeconds;if(typeof ae=="number"&&Number.isFinite(ae)&&ae>0)return ae;const ye=Date.parse(String(le?.startedAt||"")),be=Date.parse(String(le?.endedAt||""));if(Number.isFinite(ye)&&Number.isFinite(be)&&be>ye){const Me=(be-ye)/1e3;if(Me>=1&&Me<=1440*60)return Me}return Number.POSITIVE_INFINITY},[]),qi=A.useCallback(le=>{const ae=Yx(le.output||""),ye=Tn(ae),be=j[ye];if(!be)return le;const Me=ae.lastIndexOf("/"),Fe=Me>=0?ae.slice(0,Me+1):"";return{...le,output:Fe+be}},[j,Tn]),Vs=he??e,Kn=xe??p,Ts=A.useMemo(()=>{const le=new Map;for(const ye of Vs){const be=qi(ye);le.set(Fn(be),be)}for(const ye of s){const be=qi(ye),Me=Fn(be);le.has(Me)&&le.set(Me,{...le.get(Me),...be})}return Array.from(le.values()).filter(ye=>W.has(Fn(ye))||LM(ye.output)?!1:ye.status==="finished"||ye.status==="failed"||ye.status==="stopped")},[s,Vs,W,qi]),Zt=Ts;A.useEffect(()=>{const le=ae=>{const ye=ae.detail;if(!ye?.file)return;const be=ye.file;ye.phase==="start"?(_t(be,!0),Ze==="cards"?window.setTimeout(()=>{ei(be)},320):ss(be)):ye.phase==="error"?(_t(be,!1),Ze==="cards"&&ge.current.get(be)?.reset()):ye.phase==="success"&&(_t(be,!1),yt())};return window.addEventListener("finished-downloads:delete",le),()=>window.removeEventListener("finished-downloads:delete",le)},[ss,_t,ei,Ze,yt]),A.useEffect(()=>{const le=ae=>{const ye=ae.detail,be=String(ye?.oldFile??"").trim(),Me=String(ye?.newFile??"").trim();!be||!Me||be===Me||Yt(be,Me)};return window.addEventListener("finished-downloads:rename",le),()=>window.removeEventListener("finished-downloads:rename",le)},[Yt]);const vi=A.useMemo(()=>{const le=Zt.filter(ye=>!W.has(Fn(ye))),ae=Bt.length?le.filter(ye=>{const be=Tn(ye.output||""),Me=Vo(ye.output),Fe=yn(Me),Qe=ot.tagsByModelKey[Fe]??[],ct=yn([be,ca(be),Me,ye.id,ye.status,Qe.join(" ")].join(" "));for(const oe of Bt)if(!ct.includes(oe))return!1;return!0}):le;return vt.size===0?ae:ae.filter(ye=>{const be=yn(Vo(ye.output)),Me=ot.tagSetByModelKey[be];if(!Me||Me.size===0)return!1;for(const Fe of vt)if(!Me.has(Fe))return!1;return!0})},[Zt,W,vt,ot,Bt]),di=We?vi.length:Kn,Ns=A.useMemo(()=>{if(!We)return vi;const le=(g-1)*v,ae=le+v;return vi.slice(Math.max(0,le),Math.max(0,ae))},[We,vi,g,v]);A.useEffect(()=>{if(!We)return;const le=Math.max(1,Math.ceil(vi.length/v));g>le&&b(le)},[We,vi.length,g,v,b]),A.useEffect(()=>{if(!(L==="hover"&&!P&&(Ze==="cards"||Ze==="gallery"||Ze==="table"))){G(null),K.current?.disconnect(),K.current=null;return}if(Ze==="cards"&&Pe?.key){G(Pe.key);return}K.current?.disconnect();const ae=new IntersectionObserver(ye=>{let be=null,Me=0;for(const Fe of ye){if(!Fe.isIntersecting)continue;const Qe=Q.current.get(Fe.target);Qe&&Fe.intersectionRatio>Me&&(Me=Fe.intersectionRatio,be=Qe)}be&&G(Fe=>Fe===be?Fe:be)},{threshold:[0,.15,.3,.5,.7,.9],rootMargin:"0px"});K.current=ae;for(const[ye,be]of V.current)Q.current.set(be,ye),ae.observe(be);return()=>{ae.disconnect(),K.current===ae&&(K.current=null)}},[Ze,L,P,Pe?.key]);const Os=le=>{const ae=Fn(le),ye=pi[ae]??le?.durationSeconds;if(typeof ye=="number"&&Number.isFinite(ye)&&ye>0)return PS(ye*1e3);const be=Date.parse(String(le.startedAt||"")),Me=Date.parse(String(le.endedAt||""));return Number.isFinite(be)&&Number.isFinite(Me)&&Me>be?PS(Me-be):"—"},Li=A.useCallback(le=>ae=>{const ye=V.current.get(le);ye&&K.current&&K.current.unobserve(ye),ae?(V.current.set(le,ae),Q.current.set(ae,le),K.current?.observe(ae)):V.current.delete(le)},[]),Gs=A.useCallback((le,ae)=>{if(!Number.isFinite(ae)||ae<=0)return;const ye=Fn(le),be=Tt.current[ye];typeof be=="number"&&Math.abs(be-ae)<.5||(Tt.current={...Tt.current,[ye]:ae},ui())},[ui]),we=[{key:"preview",header:"Vorschau",widthClassName:"w-[140px]",cell:le=>{const ae=Fn(le),be=!(!!n&&N===ae);return y.jsx("div",{ref:Li(ae),className:"py-1",onClick:Me=>Me.stopPropagation(),onMouseDown:Me=>Me.stopPropagation(),onMouseEnter:()=>{P&&O(ae)},onMouseLeave:()=>{P&&O(null)},children:y.jsx(Kx,{force:M===ae||N===ae,rootMargin:"400px",placeholder:y.jsx("div",{className:"w-28 h-16 rounded-md ring-1 ring-black/5 dark:ring-white/10 bg-black/5 dark:bg-white/5 animate-pulse"}),children:y.jsx(zx,{job:le,getFileName:Tn,durationSeconds:pi[ae],muted:be,popoverMuted:be,onDuration:Gs,className:"w-28 h-16 rounded-md ring-1 ring-black/5 dark:ring-white/10",showPopover:!1,blur:t,animated:i==="all"?!0:i==="hover"?M===ae:!1,animatedMode:"teaser",animatedTrigger:"always",assetNonce:_})})})}},{key:"Model",header:"Model",sortable:!0,sortValue:le=>{const ae=Tn(le.output||""),ye=ec(ae),be=Vo(le.output),Me=ca(ae);return`${be} ${ye?"HOT":""} ${Me}`.trim()},cell:le=>{const ae=Tn(le.output||""),ye=ec(ae),be=ca(ae),Me=Vo(le.output),Fe=yn(Vo(le.output)),Qe=FS(R[Fe]?.tags),ct=Qe.slice(0,6),oe=Qe.length-ct.length,pe=Qe.join(", ");return y.jsxs("div",{className:"min-w-0",children:[y.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:Me}),y.jsxs("div",{className:"mt-0.5 min-w-0 text-xs text-gray-500 dark:text-gray-400",children:[y.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[y.jsx("span",{className:"truncate",title:be,children:be||"—"}),ye?y.jsx("span",{className:"shrink-0 rounded-md bg-amber-500/15 px-1.5 py-0.5 text-[11px] font-semibold text-amber-800 dark:text-amber-300",children:"HOT"}):null]}),ct.length>0?y.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1 min-w-0",children:[ct.map(Ge=>y.jsx(Br,{tag:Ge,active:vt.has(yn(Ge)),onClick:si},Ge)),oe>0?y.jsxs("span",{className:"inline-flex items-center rounded-md bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-700 ring-1 ring-inset ring-gray-200 dark:bg-white/5 dark:text-gray-200 dark:ring-white/10",title:pe,children:["+",oe]}):null]}):null]})]})}},{key:"status",header:"Status",sortable:!0,sortValue:le=>le.status==="finished"?0:le.status==="stopped"?1:le.status==="failed"?2:9,cell:le=>{const ae="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-semibold ring-1 ring-inset";if(le.status==="failed"){const ye=RM(le.error),be=ye?`failed (${ye})`:"failed";return y.jsx("span",{className:`${ae} bg-red-50 text-red-700 ring-red-200 dark:bg-red-500/10 dark:text-red-300 dark:ring-red-500/30`,title:le.error||"",children:be})}return le.status==="finished"?y.jsx("span",{className:`${ae} bg-emerald-50 text-emerald-800 ring-emerald-200 dark:bg-emerald-500/10 dark:text-emerald-300 dark:ring-emerald-500/30`,children:"finished"}):le.status==="stopped"?y.jsx("span",{className:`${ae} bg-amber-50 text-amber-800 ring-amber-200 dark:bg-amber-500/10 dark:text-amber-300 dark:ring-amber-500/30`,children:"stopped"}):y.jsx("span",{className:`${ae} bg-gray-50 text-gray-700 ring-gray-200 dark:bg-white/5 dark:text-gray-300 dark:ring-white/10`,children:le.status})}},{key:"completedAt",header:"Fertiggestellt am",sortable:!0,widthClassName:"w-[150px]",sortValue:le=>{const ae=Date.parse(String(le.endedAt||""));return Number.isFinite(ae)?ae:Number.NEGATIVE_INFINITY},cell:le=>{const ae=Date.parse(String(le.endedAt||""));if(!Number.isFinite(ae))return y.jsx("span",{className:"text-xs text-gray-400",children:"—"});const ye=new Date(ae),be=ye.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"}),Me=ye.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"});return y.jsxs("time",{dateTime:ye.toISOString(),title:`${be} ${Me}`,className:"tabular-nums whitespace-nowrap text-sm text-gray-900 dark:text-white",children:[y.jsx("span",{className:"font-medium",children:be}),y.jsx("span",{className:"mx-1 text-gray-400 dark:text-gray-600",children:"·"}),y.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:Me})]})}},{key:"runtime",header:"Dauer",align:"right",sortable:!0,sortValue:le=>Hs(le),cell:le=>y.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:Os(le)})},{key:"size",header:"Größe",align:"right",sortable:!0,sortValue:le=>{const ae=um(le);return typeof ae=="number"?ae:Number.NEGATIVE_INFINITY},cell:le=>y.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:xy(um(le))})},{key:"actions",header:"Aktionen",align:"right",srOnlyHeader:!0,cell:le=>{const ae=Fn(le),ye=J.has(ae)||Ai.has(ae)||ji.has(ae),be=Tn(le.output||""),Me=ec(be),Fe=yn(Vo(le.output)),Qe=R[Fe],ct=!!Qe?.favorite,oe=Qe?.liked===!0,pe=!!Qe?.watching;return y.jsx(va,{job:le,variant:"table",busy:ye,isHot:Me,isFavorite:ct,isLiked:oe,isWatching:pe,onToggleWatch:f,onToggleFavorite:c,onToggleLike:d,onToggleHot:Xt,onKeep:ri,onDelete:Ni,order:["watch","favorite","like","hot","details","keep","delete"],className:"flex items-center justify-end gap-1"})}}],Ne=le=>{if(!le)return"completed_desc";const ae=le,ye=String(ae.key??ae.columnKey??ae.id??""),be=String(ae.dir??ae.direction??ae.order??"").toLowerCase(),Me=be==="asc"||be==="1"||be==="true";return ye==="completedAt"?Me?"completed_asc":"completed_desc":ye==="runtime"?Me?"duration_asc":"duration_desc":ye==="size"?Me?"size_asc":"size_desc":ye==="video"?Me?"file_asc":"file_desc":Me?"completed_asc":"completed_desc"},ke=le=>{Ot(le);const ae=Ne(le);D(ae),g!==1&&b(1)},tt=BS("(max-width: 639px)");A.useEffect(()=>{tt||(ge.current=new Map)},[tt]);const je=Ts.length===0&&Kn===0,ut=!je&&vi.length===0;return y.jsxs(y.Fragment,{children:[y.jsx("div",{className:"sticky top-[56px] z-20",children:y.jsxs("div",{className:` rounded-xl border border-gray-200/70 bg-white/80 shadow-sm backdrop-blur supports-[backdrop-filter]:bg-white/60 dark:border-white/10 dark:bg-gray-950/60 dark:supports-[backdrop-filter]:bg-gray-950/40 `,children:[y.jsxs("div",{className:"flex items-center gap-3 p-3",children:[y.jsxs("div",{className:"hidden sm:flex items-center gap-2 min-w-0",children:[y.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:"Abgeschlossene Downloads"}),y.jsx("span",{className:"shrink-0 rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-900 dark:bg-white/10 dark:text-gray-200",children:di})]}),y.jsxs("div",{className:"sm:hidden flex items-center gap-2 min-w-0 flex-1",children:[y.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:"Abgeschlossene Downloads"}),y.jsx("span",{className:"shrink-0 rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-900 dark:bg-white/10 dark:text-gray-200",children:di})]}),y.jsxs("div",{className:"flex items-center gap-2 ml-auto shrink-0",children:[y.jsxs("div",{className:"hidden sm:flex items-center gap-2 min-w-0 flex-1",children:[y.jsx("input",{value:ht,onChange:le=>rt(le.target.value),placeholder:"Suchen…",className:` h-9 w-full max-w-[420px] rounded-md border border-gray-200 bg-white px-3 text-sm text-gray-900 shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:border-white/10 dark:bg-gray-900 dark:text-gray-100 dark:[color-scheme:dark] `}),(ht||"").trim()!==""?y.jsx(li,{size:"sm",variant:"soft",onClick:Lt,children:"Leeren"}):null]}),y.jsx("div",{className:"hidden sm:block",children:y.jsx(Xo,{label:"Behaltene Downloads anzeigen",checked:wt,onChange:le=>{g!==1&&b(1),jt(le),yt()}})}),Ze!=="table"&&y.jsxs("div",{className:"hidden sm:block",children:[y.jsx("label",{className:"sr-only",htmlFor:"finished-sort",children:"Sortierung"}),y.jsxs("select",{id:"finished-sort",value:S,onChange:le=>{const ae=le.target.value;D(ae),g!==1&&b(1)},className:` h-9 rounded-md border border-gray-200 bg-white px-2 text-sm text-gray-900 shadow-sm dark:border-white/10 dark:bg-gray-900 dark:text-gray-100 dark:[color-scheme:dark] `,children:[y.jsx("option",{value:"completed_desc",children:"Fertiggestellt am ↓"}),y.jsx("option",{value:"completed_asc",children:"Fertiggestellt am ↑"}),y.jsx("option",{value:"model_asc",children:"Modelname A→Z"}),y.jsx("option",{value:"model_desc",children:"Modelname Z→A"}),y.jsx("option",{value:"file_asc",children:"Dateiname A→Z"}),y.jsx("option",{value:"file_desc",children:"Dateiname Z→A"}),y.jsx("option",{value:"duration_desc",children:"Dauer ↓"}),y.jsx("option",{value:"duration_asc",children:"Dauer ↑"}),y.jsx("option",{value:"size_desc",children:"Größe ↓"}),y.jsx("option",{value:"size_asc",children:"Größe ↑"})]})]}),y.jsx(li,{size:tt?"sm":"md",variant:"soft",disabled:!z||ie,onClick:st,title:z?`Letzte Aktion rückgängig machen (${z.kind})`:"Keine Aktion zum Rückgängig machen",children:"Undo"}),y.jsx(lO,{value:Ze,onChange:le=>Nt(le),size:tt?"sm":"md",ariaLabel:"Ansicht",items:[{id:"table",icon:y.jsx(KO,{className:tt?"size-4":"size-5"}),label:tt?void 0:"Tabelle",srLabel:"Tabelle"},{id:"cards",icon:y.jsx($O,{className:tt?"size-4":"size-5"}),label:tt?void 0:"Cards",srLabel:"Cards"},{id:"gallery",icon:y.jsx(GO,{className:tt?"size-4":"size-5"}),label:tt?void 0:"Galerie",srLabel:"Galerie"}]}),y.jsxs("button",{type:"button",className:`sm:hidden relative inline-flex items-center justify-center rounded-md border border-gray-200 bg-white p-2 shadow-sm hover:bg-gray-50 dark:border-white/10 dark:bg-gray-900 dark:text-gray-100 dark:hover:bg-white/10`,onClick:()=>Dt(le=>!le),"aria-expanded":gt,"aria-controls":"finished-mobile-options","aria-label":"Filter & Optionen",children:[y.jsx(cO,{className:"size-5"}),We||wt?y.jsx("span",{className:"absolute -top-1 -right-1 h-2.5 w-2.5 rounded-full bg-indigo-500 ring-2 ring-white dark:ring-gray-950"}):null]})]})]}),Ve.length>0?y.jsxs("div",{className:"hidden sm:flex items-center gap-2 border-t border-gray-200/60 dark:border-white/10 px-3 py-2",children:[y.jsx("span",{className:"text-xs font-medium text-gray-600 dark:text-gray-300",children:"Tag-Filter"}),y.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[Ve.map(le=>y.jsx(Br,{tag:le,active:!0,onClick:si},le)),y.jsx(li,{className:` ml-1 inline-flex items-center rounded-md px-2 py-1 text-xs font-medium text-gray-700 hover:bg-gray-100 dark:text-gray-200 dark:hover:bg-white/10 `,size:"sm",variant:"soft",onClick:Mt,children:"Zurücksetzen"})]})]}):null,y.jsxs("div",{id:"finished-mobile-options",className:["sm:hidden overflow-hidden transition-[max-height,opacity] duration-200 ease-in-out",gt?"max-h-[720px] opacity-100":"max-h-0 opacity-0"].join(" "),children:[y.jsx("div",{className:"border-t border-gray-200/60 dark:border-white/10 p-3",children:y.jsxs("div",{className:"space-y-2",children:[y.jsx("div",{className:"rounded-lg border border-gray-200/70 bg-white/70 p-2 shadow-sm dark:border-white/10 dark:bg-gray-900/60",children:y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("input",{value:ht,onChange:le=>rt(le.target.value),placeholder:"Suchen…",className:` h-10 w-full rounded-md border border-gray-200 bg-white px-3 text-sm text-gray-900 focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:border-white/10 dark:bg-gray-950/60 dark:text-gray-100 dark:[color-scheme:dark] `}),(ht||"").trim()!==""?y.jsx(li,{size:"sm",variant:"soft",onClick:Lt,children:"Clear"}):null]})}),y.jsx("div",{className:"rounded-lg border border-gray-200/70 bg-white/70 px-3 py-2 shadow-sm dark:border-white/10 dark:bg-gray-900/60",children:y.jsxs("div",{className:"flex items-center justify-between gap-3",children:[y.jsxs("div",{className:"min-w-0",children:[y.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-gray-100",children:"Keep anzeigen"}),y.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Behaltene Downloads in der Liste"})]}),y.jsx(Uv,{checked:wt,onChange:le=>{g!==1&&b(1),jt(le),yt()},ariaLabel:"Behaltene Downloads anzeigen",size:"default"})]})}),Ze!=="table"?y.jsxs("div",{className:"rounded-lg border border-gray-200/70 bg-white/70 px-3 py-2 shadow-sm dark:border-white/10 dark:bg-gray-900/60",children:[y.jsx("div",{className:"text-xs font-medium text-gray-600 dark:text-gray-300 mb-1",children:"Sortierung"}),y.jsxs("select",{id:"finished-sort-mobile",value:S,onChange:le=>{const ae=le.target.value;D(ae),g!==1&&b(1)},className:` w-full h-10 rounded-md border border-gray-200 bg-white px-2 text-sm text-gray-900 shadow-sm dark:border-white/10 dark:bg-gray-950/60 dark:text-gray-100 dark:[color-scheme:dark] `,children:[y.jsx("option",{value:"completed_desc",children:"Fertiggestellt am ↓"}),y.jsx("option",{value:"completed_asc",children:"Fertiggestellt am ↑"}),y.jsx("option",{value:"model_asc",children:"Modelname A→Z"}),y.jsx("option",{value:"model_desc",children:"Modelname Z→A"}),y.jsx("option",{value:"file_asc",children:"Dateiname A→Z"}),y.jsx("option",{value:"file_desc",children:"Dateiname Z→A"}),y.jsx("option",{value:"duration_desc",children:"Dauer ↓"}),y.jsx("option",{value:"duration_asc",children:"Dauer ↑"}),y.jsx("option",{value:"size_desc",children:"Größe ↓"}),y.jsx("option",{value:"size_asc",children:"Größe ↑"})]})]}):null]})}),Ve.length>0?y.jsx("div",{className:"border-t border-gray-200/60 dark:border-white/10 px-3 py-2",children:y.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.jsx("span",{className:"text-xs font-medium text-gray-600 dark:text-gray-300",children:"Tag-Filter"}),y.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[Ve.map(le=>y.jsx(Br,{tag:le,active:!0,onClick:si},le)),y.jsx(li,{className:` ml-1 inline-flex items-center rounded-md px-2 py-1 text-xs font-medium text-gray-700 hover:bg-gray-100 dark:text-gray-200 dark:hover:bg-white/10 `,size:"sm",variant:"soft",onClick:Mt,children:"Zurücksetzen"})]})]})}):null]})]})}),je?y.jsx(xa,{grayBody:!0,children:y.jsxs("div",{className:"flex items-center gap-3",children:[y.jsx("div",{className:"grid h-10 w-10 place-items-center rounded-xl bg-white/70 ring-1 ring-gray-200 dark:bg-white/5 dark:ring-white/10",children:y.jsx("span",{className:"text-lg",children:"📁"})}),y.jsxs("div",{className:"min-w-0",children:[y.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Keine abgeschlossenen Downloads"}),y.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Im Zielordner ist aktuell nichts vorhanden."})]})]})}):ut?y.jsxs(xa,{grayBody:!0,children:[y.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine Treffer für die aktuellen Filter."}),Ve.length>0||(ht||"").trim()!==""?y.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Ve.length>0?y.jsx("button",{type:"button",className:"text-sm font-medium text-gray-700 hover:underline dark:text-gray-200",onClick:Mt,children:"Tag-Filter zurücksetzen"}):null,(ht||"").trim()!==""?y.jsx("button",{type:"button",className:"text-sm font-medium text-gray-700 hover:underline dark:text-gray-200",onClick:Lt,children:"Suche zurücksetzen"}):null]}):null]}):y.jsxs(y.Fragment,{children:[Ze==="cards"&&y.jsx(xM,{rows:Ns,isSmall:tt,blurPreviews:t,durations:pi,teaserKey:M,teaserPlayback:L,teaserAudio:n,hoverTeaserKey:N,inlinePlay:Pe,setInlinePlay:H,deletingKeys:J,keepingKeys:Ai,removingKeys:ji,swipeRefs:ge,keyFor:Fn,baseName:Tn,modelNameFromOutput:Vo,runtimeOf:Os,sizeBytesOf:um,formatBytes:xy,lower:yn,onOpenPlayer:r,openPlayer:Je,startInline:Se,tryAutoplayInline:ne,registerTeaserHost:Li,handleDuration:Gs,deleteVideo:Ni,keepVideo:ri,releasePlayingFile:ci,modelsByKey:R,onToggleHot:Xt,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f,activeTagSet:vt,onToggleTagFilter:si,onHoverPreviewKeyChange:O,assetNonce:_??0}),Ze==="table"&&y.jsx(bM,{rows:Ns,columns:we,getRowKey:le=>Fn(le),sort:it,onSortChange:ke,onRowClick:r,rowClassName:le=>{const ae=Fn(le);return["transition-all duration-300",(J.has(ae)||ji.has(ae))&&"bg-red-50/60 dark:bg-red-500/10 pointer-events-none",J.has(ae)&&"animate-pulse",(Ai.has(ae)||ji.has(ae))&&"pointer-events-none",Ai.has(ae)&&"bg-emerald-50/60 dark:bg-emerald-500/10 animate-pulse",ji.has(ae)&&"opacity-0"].filter(Boolean).join(" ")}}),Ze==="gallery"&&y.jsx(TM,{rows:Ns,blurPreviews:t,durations:pi,handleDuration:Gs,teaserKey:M,teaserPlayback:L,teaserAudio:n,hoverTeaserKey:N,keyFor:Fn,baseName:Tn,modelNameFromOutput:Vo,runtimeOf:Os,sizeBytesOf:um,formatBytes:xy,deletingKeys:J,keepingKeys:Ai,removingKeys:ji,deletedKeys:W,registerTeaserHost:Li,onOpenPlayer:r,deleteVideo:Ni,keepVideo:ri,onToggleHot:Xt,lower:yn,modelsByKey:R,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f,activeTagSet:vt,onToggleTagFilter:si,onHoverPreviewKeyChange:O}),y.jsx(NA,{page:g,pageSize:v,totalItems:di,onPageChange:le=>{xc.flushSync(()=>{H(null),G(null),O(null)});for(const ae of Ns){const ye=Tn(ae.output||"");ye&&(window.dispatchEvent(new CustomEvent("player:release",{detail:{file:ye}})),window.dispatchEvent(new CustomEvent("player:close",{detail:{file:ye}})))}window.scrollTo({top:0,behavior:"auto"}),b(le)},showSummary:!1,prevLabel:"Zurück",nextLabel:"Weiter",className:"mt-4"})]})]})}var by,US;function Hp(){if(US)return by;US=1;var s;return typeof window<"u"?s=window:typeof Km<"u"?s=Km:typeof self<"u"?s=self:s={},by=s,by}var NM=Hp();const de=Mc(NM),OM={},MM=Object.freeze(Object.defineProperty({__proto__:null,default:OM},Symbol.toStringTag,{value:"Module"})),PM=EI(MM);var Ty,jS;function PA(){if(jS)return Ty;jS=1;var s=typeof Km<"u"?Km:typeof window<"u"?window:{},e=PM,t;return typeof document<"u"?t=document:(t=s["__GLOBAL_DOCUMENT_CACHE@4"],t||(t=s["__GLOBAL_DOCUMENT_CACHE@4"]=e)),Ty=t,Ty}var BM=PA();const at=Mc(BM);var cm={exports:{}},_y={exports:{}},$S;function FM(){return $S||($S=1,(function(s){function e(){return s.exports=e=Object.assign?Object.assign.bind():function(t){for(var i=1;i=n.length?{done:!0}:{done:!1,value:n[u++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function e(n,r){if(n){if(typeof n=="string")return t(n,r);var o=Object.prototype.toString.call(n).slice(8,-1);if(o==="Object"&&n.constructor&&(o=n.constructor.name),o==="Map"||o==="Set")return Array.from(n);if(o==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o))return t(n,r)}}function t(n,r){(r==null||r>n.length)&&(r=n.length);for(var o=0,u=new Array(r);o=400&&u.statusCode<=599){var d=c;if(r)if(s.TextDecoder){var f=t(u.headers&&u.headers["content-type"]);try{d=new TextDecoder(f).decode(c)}catch{}}else d=String.fromCharCode.apply(null,new Uint8Array(c));n({cause:d});return}n(null,c)}};function t(i){return i===void 0&&(i=""),i.toLowerCase().split(";").reduce(function(n,r){var o=r.split("="),u=o[0],c=o[1];return u.trim()==="charset"?c.trim():n},"utf-8")}return Ay=e,Ay}var qS;function VM(){if(qS)return cm.exports;qS=1;var s=Hp(),e=FM(),t=UM(),i=jM(),n=$M();d.httpHandler=HM(),d.requestInterceptorsStorage=new i,d.responseInterceptorsStorage=new i,d.retryManager=new n;var r=function(b){var _={};return b&&b.trim().split(` `).forEach(function(S){var D=S.indexOf(":"),R=S.slice(0,D).trim().toLowerCase(),L=S.slice(D+1).trim();typeof _[R]>"u"?_[R]=L:Array.isArray(_[R])?_[R].push(L):_[R]=[_[R],L]}),_};cm.exports=d,cm.exports.default=d,d.XMLHttpRequest=s.XMLHttpRequest||g,d.XDomainRequest="withCredentials"in new d.XMLHttpRequest?d.XMLHttpRequest:s.XDomainRequest,o(["get","put","post","patch","head","delete"],function(v){d[v==="delete"?"del":v]=function(b,_,S){return _=c(b,_,S),_.method=v.toUpperCase(),f(_)}});function o(v,b){for(var _=0;_"u")throw new Error("callback argument missing");if(v.requestType&&d.requestInterceptorsStorage.getIsEnabled()){var b={uri:v.uri||v.url,headers:v.headers||{},body:v.body,metadata:v.metadata||{},retry:v.retry,timeout:v.timeout},_=d.requestInterceptorsStorage.execute(v.requestType,b);v.uri=_.uri,v.headers=_.headers,v.body=_.body,v.metadata=_.metadata,v.retry=_.retry,v.timeout=_.timeout}var S=!1,D=function(Z,ie,ce){S||(S=!0,v.callback(Z,ie,ce))};function R(){V.readyState===4&&!d.responseInterceptorsStorage.getIsEnabled()&&setTimeout(U,0)}function L(){var z=void 0;if(V.response?z=V.response:z=V.responseText||p(V),re)try{z=JSON.parse(z)}catch{}return z}function P(z){if(clearTimeout(J),clearTimeout(v.retryTimeout),z instanceof Error||(z=new Error(""+(z||"Unknown XMLHttpRequest Error"))),z.statusCode=0,!G&&d.retryManager.getIsEnabled()&&v.retry&&v.retry.shouldRetry()){v.retryTimeout=setTimeout(function(){v.retry.moveToNextAttempt(),v.xhr=V,f(v)},v.retry.getCurrentFuzzedDelay());return}if(v.requestType&&d.responseInterceptorsStorage.getIsEnabled()){var Z={headers:Y.headers||{},body:Y.body,responseUrl:V.responseURL,responseType:V.responseType},ie=d.responseInterceptorsStorage.execute(v.requestType,Z);Y.body=ie.body,Y.headers=ie.headers}return D(z,Y)}function U(){if(!G){var z;clearTimeout(J),clearTimeout(v.retryTimeout),v.useXDR&&V.status===void 0?z=200:z=V.status===1223?204:V.status;var Z=Y,ie=null;if(z!==0?(Z={body:L(),statusCode:z,method:O,headers:{},url:N,rawRequest:V},V.getAllResponseHeaders&&(Z.headers=r(V.getAllResponseHeaders()))):ie=new Error("Internal XMLHttpRequest Error"),v.requestType&&d.responseInterceptorsStorage.getIsEnabled()){var ce={headers:Z.headers||{},body:Z.body,responseUrl:V.responseURL,responseType:V.responseType},j=d.responseInterceptorsStorage.execute(v.requestType,ce);Z.body=j.body,Z.headers=j.headers}return D(ie,Z,Z.body)}}var V=v.xhr||null;V||(v.cors||v.useXDR?V=new d.XDomainRequest:V=new d.XMLHttpRequest);var M,G,N=V.url=v.uri||v.url,O=V.method=v.method||"GET",K=v.body||v.data,Q=V.headers=v.headers||{},W=!!v.sync,re=!1,J,Y={body:void 0,headers:{},statusCode:0,method:O,url:N,rawRequest:V};if("json"in v&&v.json!==!1&&(re=!0,Q.accept||Q.Accept||(Q.Accept="application/json"),O!=="GET"&&O!=="HEAD"&&(Q["content-type"]||Q["Content-Type"]||(Q["Content-Type"]="application/json"),K=JSON.stringify(v.json===!0?K:v.json))),V.onreadystatechange=R,V.onload=U,V.onerror=P,V.onprogress=function(){},V.onabort=function(){G=!0,clearTimeout(v.retryTimeout)},V.ontimeout=P,V.open(O,N,!W,v.username,v.password),W||(V.withCredentials=!!v.withCredentials),!W&&v.timeout>0&&(J=setTimeout(function(){if(!G){G=!0,V.abort("timeout");var z=new Error("XMLHttpRequest timeout");z.code="ETIMEDOUT",P(z)}},v.timeout)),V.setRequestHeader)for(M in Q)Q.hasOwnProperty(M)&&V.setRequestHeader(M,Q[M]);else if(v.headers&&!u(v.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in v&&(V.responseType=v.responseType),"beforeSend"in v&&typeof v.beforeSend=="function"&&v.beforeSend(V),V.send(K||null),V}function p(v){try{if(v.responseType==="document")return v.responseXML;var b=v.responseXML&&v.responseXML.documentElement.nodeName==="parsererror";if(v.responseType===""&&!b)return v.responseXML}catch{}return null}function g(){}return cm.exports}var GM=VM();const BA=Mc(GM);var Cy={exports:{}},ky,KS;function zM(){if(KS)return ky;KS=1;var s=PA(),e=Object.create||(function(){function N(){}return function(O){if(arguments.length!==1)throw new Error("Object.create shim only accepts one parameter.");return N.prototype=O,new N}})();function t(N,O){this.name="ParsingError",this.code=N.code,this.message=O||N.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(N){function O(Q,W,re,J){return(Q|0)*3600+(W|0)*60+(re|0)+(J|0)/1e3}var K=N.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);return K?K[3]?O(K[1],K[2],K[3].replace(":",""),K[4]):K[1]>59?O(K[1],K[2],0,K[4]):O(0,K[1],K[2],K[4]):null}function n(){this.values=e(null)}n.prototype={set:function(N,O){!this.get(N)&&O!==""&&(this.values[N]=O)},get:function(N,O,K){return K?this.has(N)?this.values[N]:O[K]:this.has(N)?this.values[N]:O},has:function(N){return N in this.values},alt:function(N,O,K){for(var Q=0;Q=0&&O<=100)?(this.set(N,O),!0):!1}};function r(N,O,K,Q){var W=Q?N.split(Q):[N];for(var re in W)if(typeof W[re]=="string"){var J=W[re].split(K);if(J.length===2){var Y=J[0].trim(),z=J[1].trim();O(Y,z)}}}function o(N,O,K){var Q=N;function W(){var Y=i(N);if(Y===null)throw new t(t.Errors.BadTimeStamp,"Malformed timestamp: "+Q);return N=N.replace(/^[^\sa-zA-Z-]+/,""),Y}function re(Y,z){var Z=new n;r(Y,function(ie,ce){switch(ie){case"region":for(var j=K.length-1;j>=0;j--)if(K[j].id===ce){Z.set(ie,K[j].region);break}break;case"vertical":Z.alt(ie,ce,["rl","lr"]);break;case"line":var ee=ce.split(","),he=ee[0];Z.integer(ie,he),Z.percent(ie,he)&&Z.set("snapToLines",!1),Z.alt(ie,he,["auto"]),ee.length===2&&Z.alt("lineAlign",ee[1],["start","center","end"]);break;case"position":ee=ce.split(","),Z.percent(ie,ee[0]),ee.length===2&&Z.alt("positionAlign",ee[1],["start","center","end"]);break;case"size":Z.percent(ie,ce);break;case"align":Z.alt(ie,ce,["start","center","end","left","right"]);break}},/:/,/\s/),z.region=Z.get("region",null),z.vertical=Z.get("vertical","");try{z.line=Z.get("line","auto")}catch{}z.lineAlign=Z.get("lineAlign","start"),z.snapToLines=Z.get("snapToLines",!0),z.size=Z.get("size",100);try{z.align=Z.get("align","center")}catch{z.align=Z.get("align","middle")}try{z.position=Z.get("position","auto")}catch{z.position=Z.get("position",{start:0,left:0,center:50,middle:50,end:100,right:100},z.align)}z.positionAlign=Z.get("positionAlign",{start:"start",left:"start",center:"center",middle:"center",end:"end",right:"end"},z.align)}function J(){N=N.replace(/^\s+/,"")}if(J(),O.startTime=W(),J(),N.substr(0,3)!=="-->")throw new t(t.Errors.BadTimeStamp,"Malformed time stamp (time stamps must be separated by '-->'): "+Q);N=N.substr(3),J(),O.endTime=W(),J(),re(N,O)}var u=s.createElement&&s.createElement("textarea"),c={c:"span",i:"i",b:"b",u:"u",ruby:"ruby",rt:"rt",v:"span",lang:"span"},d={white:"rgba(255,255,255,1)",lime:"rgba(0,255,0,1)",cyan:"rgba(0,255,255,1)",red:"rgba(255,0,0,1)",yellow:"rgba(255,255,0,1)",magenta:"rgba(255,0,255,1)",blue:"rgba(0,0,255,1)",black:"rgba(0,0,0,1)"},f={v:"title",lang:"lang"},p={rt:"ruby"};function g(N,O){function K(){if(!O)return null;function he(xe){return O=O.substr(xe.length),xe}var Te=O.match(/^([^<]*)(<[^>]*>?)?/);return he(Te[1]?Te[1]:Te[2])}function Q(he){return u.innerHTML=he,he=u.textContent,u.textContent="",he}function W(he,Te){return!p[Te.localName]||p[Te.localName]===he.localName}function re(he,Te){var xe=c[he];if(!xe)return null;var Ae=N.document.createElement(xe),Ke=f[he];return Ke&&Te&&(Ae[Ke]=Te.trim()),Ae}for(var J=N.document.createElement("div"),Y=J,z,Z=[];(z=K())!==null;){if(z[0]==="<"){if(z[1]==="/"){Z.length&&Z[Z.length-1]===z.substr(2).replace(">","")&&(Z.pop(),Y=Y.parentNode);continue}var ie=i(z.substr(1,z.length-2)),ce;if(ie){ce=N.document.createProcessingInstruction("timestamp",ie),Y.appendChild(ce);continue}var j=z.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);if(!j||(ce=re(j[1],j[3]),!ce)||!W(Y,ce))continue;if(j[2]){var ee=j[2].split(".");ee.forEach(function(he){var Te=/^bg_/.test(he),xe=Te?he.slice(3):he;if(d.hasOwnProperty(xe)){var Ae=Te?"background-color":"color",Ke=d[xe];ce.style[Ae]=Ke}}),ce.className=ee.join(" ")}Z.push(j[1]),Y.appendChild(ce),Y=ce;continue}Y.appendChild(N.document.createTextNode(Q(z)))}return J}var v=[[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(N){for(var O=0;O=K[0]&&N<=K[1])return!0}return!1}function _(N){var O=[],K="",Q;if(!N||!N.childNodes)return"ltr";function W(Y,z){for(var Z=z.childNodes.length-1;Z>=0;Z--)Y.push(z.childNodes[Z])}function re(Y){if(!Y||!Y.length)return null;var z=Y.pop(),Z=z.textContent||z.innerText;if(Z){var ie=Z.match(/^.*(\n|\r)/);return ie?(Y.length=0,ie[0]):Z}if(z.tagName==="ruby")return re(Y);if(z.childNodes)return W(Y,z),re(Y)}for(W(O,N);K=re(O);)for(var J=0;J=0&&N.line<=100))return N.line;if(!N.track||!N.track.textTrackList||!N.track.textTrackList.mediaElement)return-1;for(var O=N.track,K=O.textTrackList,Q=0,W=0;WN.left&&this.topN.top},L.prototype.overlapsAny=function(N){for(var O=0;O=N.top&&this.bottom<=N.bottom&&this.left>=N.left&&this.right<=N.right},L.prototype.overlapsOppositeAxis=function(N,O){switch(O){case"+x":return this.leftN.right;case"+y":return this.topN.bottom}},L.prototype.intersectPercentage=function(N){var O=Math.max(0,Math.min(this.right,N.right)-Math.max(this.left,N.left)),K=Math.max(0,Math.min(this.bottom,N.bottom)-Math.max(this.top,N.top)),Q=O*K;return Q/(this.height*this.width)},L.prototype.toCSSCompatValues=function(N){return{top:this.top-N.top,bottom:N.bottom-this.bottom,left:this.left-N.left,right:N.right-this.right,height:this.height,width:this.width}},L.getSimpleBoxPosition=function(N){var O=N.div?N.div.offsetHeight:N.tagName?N.offsetHeight:0,K=N.div?N.div.offsetWidth:N.tagName?N.offsetWidth:0,Q=N.div?N.div.offsetTop:N.tagName?N.offsetTop:0;N=N.div?N.div.getBoundingClientRect():N.tagName?N.getBoundingClientRect():N;var W={left:N.left,right:N.right,top:N.top||Q,height:N.height||O,bottom:N.bottom||Q+(N.height||O),width:N.width||K};return W};function P(N,O,K,Q){function W(xe,Ae){for(var Ke,lt=new L(xe),nt=1,yt=0;ytit&&(Ke=new L(xe),nt=it),xe=new L(lt)}return Ke||lt}var re=new L(O),J=O.cue,Y=S(J),z=[];if(J.snapToLines){var Z;switch(J.vertical){case"":z=["+y","-y"],Z="height";break;case"rl":z=["+x","-x"],Z="width";break;case"lr":z=["-x","+x"],Z="width";break}var ie=re.lineHeight,ce=ie*Math.round(Y),j=K[Z]+ie,ee=z[0];Math.abs(ce)>j&&(ce=ce<0?-1:1,ce*=Math.ceil(j/ie)*ie),Y<0&&(ce+=J.vertical===""?K.height:K.width,z=z.reverse()),re.move(ee,ce)}else{var he=re.lineHeight/K.height*100;switch(J.lineAlign){case"center":Y-=he/2;break;case"end":Y-=he;break}switch(J.vertical){case"":O.applyStyles({top:O.formatStyle(Y,"%")});break;case"rl":O.applyStyles({left:O.formatStyle(Y,"%")});break;case"lr":O.applyStyles({right:O.formatStyle(Y,"%")});break}z=["+y","-x","+x","-y"],re=new L(O)}var Te=W(re,z);O.move(Te.toCSSCompatValues(K))}function U(){}U.StringDecoder=function(){return{decode:function(N){if(!N)return"";if(typeof N!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(N))}}},U.convertCueToDOMTree=function(N,O){return!N||!O?null:g(N,O)};var V=.05,M="sans-serif",G="1.5%";return U.processCues=function(N,O,K){if(!N||!O||!K)return null;for(;K.firstChild;)K.removeChild(K.firstChild);var Q=N.document.createElement("div");Q.style.position="absolute",Q.style.left="0",Q.style.right="0",Q.style.top="0",Q.style.bottom="0",Q.style.margin=G,K.appendChild(Q);function W(ie){for(var ce=0;ce")===-1){O.cue.id=J;continue}case"CUE":try{o(J,O.cue,O.regionList)}catch(ie){O.reportOrThrowError(ie),O.cue=null,O.state="BADCUE";continue}O.state="CUETEXT";continue;case"CUETEXT":var Z=J.indexOf("-->")!==-1;if(!J||Z&&(z=!0)){O.oncue&&O.oncue(O.cue),O.cue=null,O.state="ID";continue}O.cue.text&&(O.cue.text+=` `),O.cue.text+=J.replace(/\u2028/g,` `).replace(/u2029/g,` `);continue;case"BADCUE":J||(O.state="ID");continue}}}catch(ie){O.reportOrThrowError(ie),O.state==="CUETEXT"&&O.cue&&O.oncue&&O.oncue(O.cue),O.cue=null,O.state=O.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this},flush:function(){var N=this;try{if(N.buffer+=N.decoder.decode(),(N.cue||N.state==="HEADER")&&(N.buffer+=` `,N.parse()),N.state==="INITIAL")throw new t(t.Errors.BadSignature)}catch(O){N.reportOrThrowError(O)}return N.onflush&&N.onflush(),this}},ky=U,ky}var Dy,YS;function qM(){if(YS)return Dy;YS=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,c){this.hasBeenReset=!1;var d="",f=!1,p=o,g=u,v=c,b=null,_="",S=!0,D="auto",R="start",L="auto",P="auto",U=100,V="center";Object.defineProperties(this,{id:{enumerable:!0,get:function(){return d},set:function(M){d=""+M}},pauseOnExit:{enumerable:!0,get:function(){return f},set:function(M){f=!!M}},startTime:{enumerable:!0,get:function(){return p},set:function(M){if(typeof M!="number")throw new TypeError("Start time must be set to a number.");p=M,this.hasBeenReset=!0}},endTime:{enumerable:!0,get:function(){return g},set:function(M){if(typeof M!="number")throw new TypeError("End time must be set to a number.");g=M,this.hasBeenReset=!0}},text:{enumerable:!0,get:function(){return v},set:function(M){v=""+M,this.hasBeenReset=!0}},region:{enumerable:!0,get:function(){return b},set:function(M){b=M,this.hasBeenReset=!0}},vertical:{enumerable:!0,get:function(){return _},set:function(M){var G=i(M);if(G===!1)throw new SyntaxError("Vertical: an invalid or illegal direction string was specified.");_=G,this.hasBeenReset=!0}},snapToLines:{enumerable:!0,get:function(){return S},set:function(M){S=!!M,this.hasBeenReset=!0}},line:{enumerable:!0,get:function(){return D},set:function(M){if(typeof M!="number"&&M!==s)throw new SyntaxError("Line: an invalid number or illegal string was specified.");D=M,this.hasBeenReset=!0}},lineAlign:{enumerable:!0,get:function(){return R},set:function(M){var G=n(M);G?(R=G,this.hasBeenReset=!0):console.warn("lineAlign: an invalid or illegal string was specified.")}},position:{enumerable:!0,get:function(){return L},set:function(M){if(M<0||M>100)throw new Error("Position must be between 0 and 100.");L=M,this.hasBeenReset=!0}},positionAlign:{enumerable:!0,get:function(){return P},set:function(M){var G=n(M);G?(P=G,this.hasBeenReset=!0):console.warn("positionAlign: an invalid or illegal string was specified.")}},size:{enumerable:!0,get:function(){return U},set:function(M){if(M<0||M>100)throw new Error("Size must be between 0 and 100.");U=M,this.hasBeenReset=!0}},align:{enumerable:!0,get:function(){return V},set:function(M){var G=n(M);if(!G)throw new SyntaxError("align: an invalid or illegal alignment string was specified.");V=G,this.hasBeenReset=!0}}}),this.displayState=void 0}return r.prototype.getCueAsHTML=function(){return WebVTT.convertCueToDOMTree(window,this.text)},Dy=r,Dy}var Ly,WS;function KM(){if(WS)return Ly;WS=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,c=0,d=100,f="";Object.defineProperties(this,{width:{enumerable:!0,get:function(){return n},set:function(p){if(!t(p))throw new Error("Width must be between 0 and 100.");n=p}},lines:{enumerable:!0,get:function(){return r},set:function(p){if(typeof p!="number")throw new TypeError("Lines must be set to a number.");r=p}},regionAnchorY:{enumerable:!0,get:function(){return u},set:function(p){if(!t(p))throw new Error("RegionAnchorX must be between 0 and 100.");u=p}},regionAnchorX:{enumerable:!0,get:function(){return o},set:function(p){if(!t(p))throw new Error("RegionAnchorY must be between 0 and 100.");o=p}},viewportAnchorY:{enumerable:!0,get:function(){return d},set:function(p){if(!t(p))throw new Error("ViewportAnchorY must be between 0 and 100.");d=p}},viewportAnchorX:{enumerable:!0,get:function(){return c},set:function(p){if(!t(p))throw new Error("ViewportAnchorX must be between 0 and 100.");c=p}},scroll:{enumerable:!0,get:function(){return f},set:function(p){var g=e(p);g===!1?console.warn("Scroll: an invalid or illegal string was specified."):f=g}}})}return Ly=i,Ly}var XS;function YM(){if(XS)return Cy.exports;XS=1;var s=Hp(),e=Cy.exports={WebVTT:zM(),VTTCue:qM(),VTTRegion:KM()};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(),Cy.exports}var WM=YM();const QS=Mc(WM);function Cs(){return Cs=Object.assign?Object.assign.bind():function(s){for(var e=1;e-1},e.trigger=function(i){var n=this.listeners[i];if(n)if(arguments.length===2)for(var r=n.length,o=0;o-1;t=this.buffer.indexOf(` `))this.trigger("data",this.buffer.substring(0,t)),this.buffer=this.buffer.substring(t+1)}}const ZM=" ",Ry=function(s){const e=/([0-9.]*)?@?([0-9.]*)?/.exec(s||""),t={};return e[1]&&(t.length=parseInt(e[1],10)),e[2]&&(t.offset=parseInt(e[2],10)),t},JM=function(){const t="(?:"+"[^=]*"+")=(?:"+'"[^"]*"|[^,]*'+")";return new RegExp("(?:^|,)("+t+")")},vn=function(s){const e={};if(!s)return e;const t=s.split(JM());let i=t.length,n;for(;i--;)t[i]!==""&&(n=/([^=]*)=(.*)/.exec(t[i]).slice(1),n[0]=n[0].replace(/^\s+|\s+$/g,""),n[1]=n[1].replace(/^\s+|\s+$/g,""),n[1]=n[1].replace(/^['"](.*)['"]$/g,"$1"),e[n[0]]=n[1]);return e},JS=s=>{const e=s.split("x"),t={};return e[0]&&(t.width=parseInt(e[0],10)),e[1]&&(t.height=parseInt(e[1],10)),t};class eP extends Wx{constructor(){super(),this.customParsers=[],this.tagMappers=[]}push(e){let t,i;if(e=e.trim(),e.length===0)return;if(e[0]!=="#"){this.trigger("data",{type:"uri",uri:e});return}this.tagMappers.reduce((r,o)=>{const u=o(e);return u===e?r:r.concat([u])},[e]).forEach(r=>{for(let o=0;or),this.customParsers.push(r=>{if(e.exec(r))return this.trigger("data",{type:"custom",data:i(r),customType:t,segment:n}),!0})}addTagMapper({expression:e,map:t}){const i=n=>e.test(n)?t(n):n;this.tagMappers.push(i)}}const tP=s=>s.toLowerCase().replace(/-(\w)/g,e=>e[1].toUpperCase()),Go=function(s){const e={};return Object.keys(s).forEach(function(t){e[tP(t)]=s[t]}),e},Iy=function(s){const{serverControl:e,targetDuration:t,partTargetDuration:i}=s;if(!e)return;const n="#EXT-X-SERVER-CONTROL",r="holdBack",o="partHoldBack",u=t&&t*3,c=i&&i*2;t&&!e.hasOwnProperty(r)&&(e[r]=u,this.trigger("info",{message:`${n} defaulting HOLD-BACK to targetDuration * 3 (${u}).`})),u&&e[r]{n.uri||!n.parts&&!n.preloadHints||(!n.map&&r&&(n.map=r),!n.key&&o&&(n.key=o),!n.timeline&&typeof p=="number"&&(n.timeline=p),this.manifest.preloadSegment=n)}),this.parseStream.on("data",function(_){let S,D;if(t.manifest.definitions){for(const R in t.manifest.definitions)if(_.uri&&(_.uri=_.uri.replace(`{$${R}}`,t.manifest.definitions[R])),_.attributes)for(const L in _.attributes)typeof _.attributes[L]=="string"&&(_.attributes[L]=_.attributes[L].replace(`{$${R}}`,t.manifest.definitions[R]))}({tag(){({version(){_.version&&(this.manifest.version=_.version)},"allow-cache"(){this.manifest.allowCache=_.allowed,"allowed"in _||(this.trigger("info",{message:"defaulting allowCache to YES"}),this.manifest.allowCache=!0)},byterange(){const R={};"length"in _&&(n.byterange=R,R.length=_.length,"offset"in _||(_.offset=g)),"offset"in _&&(n.byterange=R,R.offset=_.offset),g=R.offset+R.length},endlist(){this.manifest.endList=!0},inf(){"mediaSequence"in this.manifest||(this.manifest.mediaSequence=0,this.trigger("info",{message:"defaulting media sequence to zero"})),"discontinuitySequence"in this.manifest||(this.manifest.discontinuitySequence=0,this.trigger("info",{message:"defaulting discontinuity sequence to zero"})),_.title&&(n.title=_.title),_.duration>0&&(n.duration=_.duration),_.duration===0&&(n.duration=.01,this.trigger("info",{message:"updating zero segment duration to a small value"})),this.manifest.segments=i},key(){if(!_.attributes){this.trigger("warn",{message:"ignoring key declaration without attribute list"});return}if(_.attributes.METHOD==="NONE"){o=null;return}if(!_.attributes.URI){this.trigger("warn",{message:"ignoring key declaration without URI"});return}if(_.attributes.KEYFORMAT==="com.apple.streamingkeydelivery"){this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.apple.fps.1_0"]={attributes:_.attributes};return}if(_.attributes.KEYFORMAT==="com.microsoft.playready"){this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.microsoft.playready"]={uri:_.attributes.URI};return}if(_.attributes.KEYFORMAT===f){if(["SAMPLE-AES","SAMPLE-AES-CTR","SAMPLE-AES-CENC"].indexOf(_.attributes.METHOD)===-1){this.trigger("warn",{message:"invalid key method provided for Widevine"});return}if(_.attributes.METHOD==="SAMPLE-AES-CENC"&&this.trigger("warn",{message:"SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead"}),_.attributes.URI.substring(0,23)!=="data:text/plain;base64,"){this.trigger("warn",{message:"invalid key URI provided for Widevine"});return}if(!(_.attributes.KEYID&&_.attributes.KEYID.substring(0,2)==="0x")){this.trigger("warn",{message:"invalid key ID provided for Widevine"});return}this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.widevine.alpha"]={attributes:{schemeIdUri:_.attributes.KEYFORMAT,keyId:_.attributes.KEYID.substring(2)},pssh:FA(_.attributes.URI.split(",")[1])};return}_.attributes.METHOD||this.trigger("warn",{message:"defaulting key method to AES-128"}),o={method:_.attributes.METHOD||"AES-128",uri:_.attributes.URI},typeof _.attributes.IV<"u"&&(o.iv=_.attributes.IV)},"media-sequence"(){if(!isFinite(_.number)){this.trigger("warn",{message:"ignoring invalid media sequence: "+_.number});return}this.manifest.mediaSequence=_.number},"discontinuity-sequence"(){if(!isFinite(_.number)){this.trigger("warn",{message:"ignoring invalid discontinuity sequence: "+_.number});return}this.manifest.discontinuitySequence=_.number,p=_.number},"playlist-type"(){if(!/VOD|EVENT/.test(_.playlistType)){this.trigger("warn",{message:"ignoring unknown playlist type: "+_.playlist});return}this.manifest.playlistType=_.playlistType},map(){r={},_.uri&&(r.uri=_.uri),_.byterange&&(r.byterange=_.byterange),o&&(r.key=o)},"stream-inf"(){if(this.manifest.playlists=i,this.manifest.mediaGroups=this.manifest.mediaGroups||d,!_.attributes){this.trigger("warn",{message:"ignoring empty stream-inf attributes"});return}n.attributes||(n.attributes={}),Cs(n.attributes,_.attributes)},media(){if(this.manifest.mediaGroups=this.manifest.mediaGroups||d,!(_.attributes&&_.attributes.TYPE&&_.attributes["GROUP-ID"]&&_.attributes.NAME)){this.trigger("warn",{message:"ignoring incomplete or missing media group"});return}const R=this.manifest.mediaGroups[_.attributes.TYPE];R[_.attributes["GROUP-ID"]]=R[_.attributes["GROUP-ID"]]||{},S=R[_.attributes["GROUP-ID"]],D={default:/yes/i.test(_.attributes.DEFAULT)},D.default?D.autoselect=!0:D.autoselect=/yes/i.test(_.attributes.AUTOSELECT),_.attributes.LANGUAGE&&(D.language=_.attributes.LANGUAGE),_.attributes.URI&&(D.uri=_.attributes.URI),_.attributes["INSTREAM-ID"]&&(D.instreamId=_.attributes["INSTREAM-ID"]),_.attributes.CHARACTERISTICS&&(D.characteristics=_.attributes.CHARACTERISTICS),_.attributes.FORCED&&(D.forced=/yes/i.test(_.attributes.FORCED)),S[_.attributes.NAME]=D},discontinuity(){p+=1,n.discontinuity=!0,this.manifest.discontinuityStarts.push(i.length)},"program-date-time"(){typeof this.manifest.dateTimeString>"u"&&(this.manifest.dateTimeString=_.dateTimeString,this.manifest.dateTimeObject=_.dateTimeObject),n.dateTimeString=_.dateTimeString,n.dateTimeObject=_.dateTimeObject;const{lastProgramDateTime:R}=this;this.lastProgramDateTime=new Date(_.dateTimeString).getTime(),R===null&&this.manifest.segments.reduceRight((L,P)=>(P.programDateTime=L-P.duration*1e3,P.programDateTime),this.lastProgramDateTime)},targetduration(){if(!isFinite(_.duration)||_.duration<0){this.trigger("warn",{message:"ignoring invalid target duration: "+_.duration});return}this.manifest.targetDuration=_.duration,Iy.call(this,this.manifest)},start(){if(!_.attributes||isNaN(_.attributes["TIME-OFFSET"])){this.trigger("warn",{message:"ignoring start declaration without appropriate attribute list"});return}this.manifest.start={timeOffset:_.attributes["TIME-OFFSET"],precise:_.attributes.PRECISE}},"cue-out"(){n.cueOut=_.data},"cue-out-cont"(){n.cueOutCont=_.data},"cue-in"(){n.cueIn=_.data},skip(){this.manifest.skip=Go(_.attributes),this.warnOnMissingAttributes_("#EXT-X-SKIP",_.attributes,["SKIPPED-SEGMENTS"])},part(){u=!0;const R=this.manifest.segments.length,L=Go(_.attributes);n.parts=n.parts||[],n.parts.push(L),L.byterange&&(L.byterange.hasOwnProperty("offset")||(L.byterange.offset=v),v=L.byterange.offset+L.byterange.length);const P=n.parts.length-1;this.warnOnMissingAttributes_(`#EXT-X-PART #${P} for segment #${R}`,_.attributes,["URI","DURATION"]),this.manifest.renditionReports&&this.manifest.renditionReports.forEach((U,V)=>{U.hasOwnProperty("lastPart")||this.trigger("warn",{message:`#EXT-X-RENDITION-REPORT #${V} lacks required attribute(s): LAST-PART`})})},"server-control"(){const R=this.manifest.serverControl=Go(_.attributes);R.hasOwnProperty("canBlockReload")||(R.canBlockReload=!1,this.trigger("info",{message:"#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false"})),Iy.call(this,this.manifest),R.canSkipDateranges&&!R.hasOwnProperty("canSkipUntil")&&this.trigger("warn",{message:"#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set"})},"preload-hint"(){const R=this.manifest.segments.length,L=Go(_.attributes),P=L.type&&L.type==="PART";n.preloadHints=n.preloadHints||[],n.preloadHints.push(L),L.byterange&&(L.byterange.hasOwnProperty("offset")||(L.byterange.offset=P?v:0,P&&(v=L.byterange.offset+L.byterange.length)));const U=n.preloadHints.length-1;if(this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${U} for segment #${R}`,_.attributes,["TYPE","URI"]),!!L.type)for(let V=0;VV.id===L.id);this.manifest.dateRanges[U]=Cs(this.manifest.dateRanges[U],L),b[L.id]=Cs(b[L.id],L),this.manifest.dateRanges.pop()}},"independent-segments"(){this.manifest.independentSegments=!0},"i-frames-only"(){this.manifest.iFramesOnly=!0,this.requiredCompatibilityversion(this.manifest.version,4)},"content-steering"(){this.manifest.contentSteering=Go(_.attributes),this.warnOnMissingAttributes_("#EXT-X-CONTENT-STEERING",_.attributes,["SERVER-URI"])},define(){this.manifest.definitions=this.manifest.definitions||{};const R=(L,P)=>{if(L in this.manifest.definitions){this.trigger("error",{message:`EXT-X-DEFINE: Duplicate name ${L}`});return}this.manifest.definitions[L]=P};if("QUERYPARAM"in _.attributes){if("NAME"in _.attributes||"IMPORT"in _.attributes){this.trigger("error",{message:"EXT-X-DEFINE: Invalid attributes"});return}const L=this.params.get(_.attributes.QUERYPARAM);if(!L){this.trigger("error",{message:`EXT-X-DEFINE: No query param ${_.attributes.QUERYPARAM}`});return}R(_.attributes.QUERYPARAM,decodeURIComponent(L));return}if("NAME"in _.attributes){if("IMPORT"in _.attributes){this.trigger("error",{message:"EXT-X-DEFINE: Invalid attributes"});return}if(!("VALUE"in _.attributes)||typeof _.attributes.VALUE!="string"){this.trigger("error",{message:`EXT-X-DEFINE: No value for ${_.attributes.NAME}`});return}R(_.attributes.NAME,_.attributes.VALUE);return}if("IMPORT"in _.attributes){if(!this.mainDefinitions[_.attributes.IMPORT]){this.trigger("error",{message:`EXT-X-DEFINE: No value ${_.attributes.IMPORT} to import, or IMPORT used on main playlist`});return}R(_.attributes.IMPORT,this.mainDefinitions[_.attributes.IMPORT]);return}this.trigger("error",{message:"EXT-X-DEFINE: No attribute"})},"i-frame-playlist"(){this.manifest.iFramePlaylists.push({attributes:_.attributes,uri:_.uri,timeline:p}),this.warnOnMissingAttributes_("#EXT-X-I-FRAME-STREAM-INF",_.attributes,["BANDWIDTH","URI"])}}[_.tagType]||c).call(t)},uri(){n.uri=_.uri,i.push(n),this.manifest.targetDuration&&!("duration"in n)&&(this.trigger("warn",{message:"defaulting segment duration to the target duration"}),n.duration=this.manifest.targetDuration),o&&(n.key=o),n.timeline=p,r&&(n.map=r),v=0,this.lastProgramDateTime!==null&&(n.programDateTime=this.lastProgramDateTime,this.lastProgramDateTime+=n.duration*1e3),n={}},comment(){},custom(){_.segment?(n.custom=n.custom||{},n.custom[_.customType]=_.data):(this.manifest.custom=this.manifest.custom||{},this.manifest.custom[_.customType]=_.data)}})[_.type].call(t)})}requiredCompatibilityversion(e,t){(ep&&(f-=p,f-=p,f-=rn(2))}return Number(f)},fP=function(e,t){var i={},n=i.le,r=n===void 0?!1:n;(typeof e!="bigint"&&typeof e!="number"||typeof e=="number"&&e!==e)&&(e=0),e=rn(e);for(var o=cP(e),u=new Uint8Array(new ArrayBuffer(o)),c=0;c=t.length&&d.call(t,function(f,p){var g=c[p]?c[p]&e[o+p]:e[o+p];return f===g})},pP=function(e,t,i){t.forEach(function(n){for(var r in e.mediaGroups[n])for(var o in e.mediaGroups[n][r]){var u=e.mediaGroups[n][r][o];i(u,n,r,o)}})},Vd={},Ga={},Bl={},iE;function Gp(){if(iE)return Bl;iE=1;function s(r,o,u){if(u===void 0&&(u=Array.prototype),r&&typeof u.find=="function")return u.find.call(r,o);for(var c=0;c=0&&H=0){for(var Je=q.length-1;Se0},lookupPrefix:function(H){for(var q=this;q;){var ne=q._nsMap;if(ne){for(var Se in ne)if(Object.prototype.hasOwnProperty.call(ne,Se)&&ne[Se]===H)return Se}q=q.nodeType==g?q.ownerDocument:q.parentNode}return null},lookupNamespaceURI:function(H){for(var q=this;q;){var ne=q._nsMap;if(ne&&Object.prototype.hasOwnProperty.call(ne,H))return ne[H];q=q.nodeType==g?q.ownerDocument:q.parentNode}return null},isDefaultNamespace:function(H){var q=this.lookupPrefix(H);return q==null}};function ee(H){return H=="<"&&"<"||H==">"&&">"||H=="&"&&"&"||H=='"'&&"""||"&#"+H.charCodeAt()+";"}c(f,j),c(f,j.prototype);function he(H,q){if(q(H))return!0;if(H=H.firstChild)do if(he(H,q))return!0;while(H=H.nextSibling)}function Te(){this.ownerDocument=this}function xe(H,q,ne){H&&H._inc++;var Se=ne.namespaceURI;Se===t.XMLNS&&(q._nsMap[ne.prefix?ne.localName:""]=ne.value)}function Ae(H,q,ne,Se){H&&H._inc++;var Je=ne.namespaceURI;Je===t.XMLNS&&delete q._nsMap[ne.prefix?ne.localName:""]}function Ke(H,q,ne){if(H&&H._inc){H._inc++;var Se=q.childNodes;if(ne)Se[Se.length++]=ne;else{for(var Je=q.firstChild,_t=0;Je;)Se[_t++]=Je,Je=Je.nextSibling;Se.length=_t,delete Se[Se.length]}}}function lt(H,q){var ne=q.previousSibling,Se=q.nextSibling;return ne?ne.nextSibling=Se:H.firstChild=Se,Se?Se.previousSibling=ne:H.lastChild=ne,q.parentNode=null,q.previousSibling=null,q.nextSibling=null,Ke(H.ownerDocument,H),q}function nt(H){return H&&(H.nodeType===j.DOCUMENT_NODE||H.nodeType===j.DOCUMENT_FRAGMENT_NODE||H.nodeType===j.ELEMENT_NODE)}function yt(H){return H&&(Ot(H)||pt(H)||it(H)||H.nodeType===j.DOCUMENT_FRAGMENT_NODE||H.nodeType===j.COMMENT_NODE||H.nodeType===j.PROCESSING_INSTRUCTION_NODE)}function it(H){return H&&H.nodeType===j.DOCUMENT_TYPE_NODE}function Ot(H){return H&&H.nodeType===j.ELEMENT_NODE}function pt(H){return H&&H.nodeType===j.TEXT_NODE}function xt(H,q){var ne=H.childNodes||[];if(e(ne,Ot)||it(q))return!1;var Se=e(ne,it);return!(q&&Se&&ne.indexOf(Se)>ne.indexOf(q))}function Pt(H,q){var ne=H.childNodes||[];function Se(_t){return Ot(_t)&&_t!==q}if(e(ne,Se))return!1;var Je=e(ne,it);return!(q&&Je&&ne.indexOf(Je)>ne.indexOf(q))}function Ze(H,q,ne){if(!nt(H))throw new Q(N,"Unexpected parent node type "+H.nodeType);if(ne&&ne.parentNode!==H)throw new Q(O,"child not in parent");if(!yt(q)||it(q)&&H.nodeType!==j.DOCUMENT_NODE)throw new Q(N,"Unexpected node type "+q.nodeType+" for parent node type "+H.nodeType)}function Nt(H,q,ne){var Se=H.childNodes||[],Je=q.childNodes||[];if(q.nodeType===j.DOCUMENT_FRAGMENT_NODE){var _t=Je.filter(Ot);if(_t.length>1||e(Je,pt))throw new Q(N,"More than one element or text in fragment");if(_t.length===1&&!xt(H,ne))throw new Q(N,"Element in fragment can not be inserted before doctype")}if(Ot(q)&&!xt(H,ne))throw new Q(N,"Only one element can be added and only after doctype");if(it(q)){if(e(Se,it))throw new Q(N,"Only one doctype is allowed");var ei=e(Se,Ot);if(ne&&Se.indexOf(ei)1||e(Je,pt))throw new Q(N,"More than one element or text in fragment");if(_t.length===1&&!Pt(H,ne))throw new Q(N,"Element in fragment can not be inserted before doctype")}if(Ot(q)&&!Pt(H,ne))throw new Q(N,"Only one element can be added and only after doctype");if(it(q)){let is=function(Ii){return it(Ii)&&Ii!==ne};var Ai=is;if(e(Se,is))throw new Q(N,"Only one doctype is allowed");var ei=e(Se,Ot);if(ne&&Se.indexOf(ei)0&&he(ne.documentElement,function(Je){if(Je!==ne&&Je.nodeType===p){var _t=Je.getAttribute("class");if(_t){var ei=H===_t;if(!ei){var Ai=o(_t);ei=q.every(u(Ai))}ei&&Se.push(Je)}}}),Se})},createElement:function(H){var q=new ge;q.ownerDocument=this,q.nodeName=H,q.tagName=H,q.localName=H,q.childNodes=new W;var ne=q.attributes=new Y;return ne._ownerElement=q,q},createDocumentFragment:function(){var H=new Lt;return H.ownerDocument=this,H.childNodes=new W,H},createTextNode:function(H){var q=new et;return q.ownerDocument=this,q.appendData(H),q},createComment:function(H){var q=new vt;return q.ownerDocument=this,q.appendData(H),q},createCDATASection:function(H){var q=new ot;return q.ownerDocument=this,q.appendData(H),q},createProcessingInstruction:function(H,q){var ne=new si;return ne.ownerDocument=this,ne.tagName=ne.nodeName=ne.target=H,ne.nodeValue=ne.data=q,ne},createAttribute:function(H){var q=new st;return q.ownerDocument=this,q.name=H,q.nodeName=H,q.localName=H,q.specified=!0,q},createEntityReference:function(H){var q=new Bt;return q.ownerDocument=this,q.nodeName=H,q},createElementNS:function(H,q){var ne=new ge,Se=q.split(":"),Je=ne.attributes=new Y;return ne.childNodes=new W,ne.ownerDocument=this,ne.nodeName=q,ne.tagName=q,ne.namespaceURI=H,Se.length==2?(ne.prefix=Se[0],ne.localName=Se[1]):ne.localName=q,Je._ownerElement=ne,ne},createAttributeNS:function(H,q){var ne=new st,Se=q.split(":");return ne.ownerDocument=this,ne.nodeName=q,ne.name=q,ne.namespaceURI=H,ne.specified=!0,Se.length==2?(ne.prefix=Se[0],ne.localName=Se[1]):ne.localName=q,ne}},d(Te,j);function ge(){this._nsMap={}}ge.prototype={nodeType:p,hasAttribute:function(H){return this.getAttributeNode(H)!=null},getAttribute:function(H){var q=this.getAttributeNode(H);return q&&q.value||""},getAttributeNode:function(H){return this.attributes.getNamedItem(H)},setAttribute:function(H,q){var ne=this.ownerDocument.createAttribute(H);ne.value=ne.nodeValue=""+q,this.setAttributeNode(ne)},removeAttribute:function(H){var q=this.getAttributeNode(H);q&&this.removeAttributeNode(q)},appendChild:function(H){return H.nodeType===U?this.insertBefore(H,null):Dt(this,H)},setAttributeNode:function(H){return this.attributes.setNamedItem(H)},setAttributeNodeNS:function(H){return this.attributes.setNamedItemNS(H)},removeAttributeNode:function(H){return this.attributes.removeNamedItem(H.nodeName)},removeAttributeNS:function(H,q){var ne=this.getAttributeNodeNS(H,q);ne&&this.removeAttributeNode(ne)},hasAttributeNS:function(H,q){return this.getAttributeNodeNS(H,q)!=null},getAttributeNS:function(H,q){var ne=this.getAttributeNodeNS(H,q);return ne&&ne.value||""},setAttributeNS:function(H,q,ne){var Se=this.ownerDocument.createAttributeNS(H,q);Se.value=Se.nodeValue=""+ne,this.setAttributeNode(Se)},getAttributeNodeNS:function(H,q){return this.attributes.getNamedItemNS(H,q)},getElementsByTagName:function(H){return new re(this,function(q){var ne=[];return he(q,function(Se){Se!==q&&Se.nodeType==p&&(H==="*"||Se.tagName==H)&&ne.push(Se)}),ne})},getElementsByTagNameNS:function(H,q){return new re(this,function(ne){var Se=[];return he(ne,function(Je){Je!==ne&&Je.nodeType===p&&(H==="*"||Je.namespaceURI===H)&&(q==="*"||Je.localName==q)&&Se.push(Je)}),Se})}},Te.prototype.getElementsByTagName=ge.prototype.getElementsByTagName,Te.prototype.getElementsByTagNameNS=ge.prototype.getElementsByTagNameNS,d(ge,j);function st(){}st.prototype.nodeType=g,d(st,j);function Ve(){}Ve.prototype={data:"",substringData:function(H,q){return this.data.substring(H,H+q)},appendData:function(H){H=this.data+H,this.nodeValue=this.data=H,this.length=H.length},insertData:function(H,q){this.replaceData(H,0,q)},appendChild:function(H){throw new Error(G[N])},deleteData:function(H,q){this.replaceData(H,q,"")},replaceData:function(H,q,ne){var Se=this.data.substring(0,H),Je=this.data.substring(H+q);ne=Se+ne+Je,this.nodeValue=this.data=ne,this.length=ne.length}},d(Ve,j);function et(){}et.prototype={nodeName:"#text",nodeType:v,splitText:function(H){var q=this.data,ne=q.substring(H);q=q.substring(0,H),this.data=this.nodeValue=q,this.length=q.length;var Se=this.ownerDocument.createTextNode(ne);return this.parentNode&&this.parentNode.insertBefore(Se,this.nextSibling),Se}},d(et,Ve);function vt(){}vt.prototype={nodeName:"#comment",nodeType:R},d(vt,Ve);function ot(){}ot.prototype={nodeName:"#cdata-section",nodeType:b},d(ot,Ve);function ht(){}ht.prototype.nodeType=P,d(ht,j);function rt(){}rt.prototype.nodeType=V,d(rt,j);function Gt(){}Gt.prototype.nodeType=S,d(Gt,j);function Bt(){}Bt.prototype.nodeType=_,d(Bt,j);function Lt(){}Lt.prototype.nodeName="#document-fragment",Lt.prototype.nodeType=U,d(Lt,j);function si(){}si.prototype.nodeType=D,d(si,j);function We(){}We.prototype.serializeToString=function(H,q,ne){return Ct.call(H,q,ne)},j.prototype.toString=Ct;function Ct(H,q){var ne=[],Se=this.nodeType==9&&this.documentElement||this,Je=Se.prefix,_t=Se.namespaceURI;if(_t&&Je==null){var Je=Se.lookupPrefix(_t);if(Je==null)var ei=[{namespace:_t,prefix:null}]}return Ei(this,ne,H,q,ei),ne.join("")}function Mt(H,q,ne){var Se=H.prefix||"",Je=H.namespaceURI;if(!Je||Se==="xml"&&Je===t.XML||Je===t.XMLNS)return!1;for(var _t=ne.length;_t--;){var ei=ne[_t];if(ei.prefix===Se)return ei.namespace!==Je}return!0}function pi(H,q,ne){H.push(" ",q,'="',ne.replace(/[<>&"\t\n\r]/g,ee),'"')}function Ei(H,q,ne,Se,Je){if(Je||(Je=[]),Se)if(H=Se(H),H){if(typeof H=="string"){q.push(H);return}}else return;switch(H.nodeType){case p:var _t=H.attributes,ei=_t.length,Yt=H.firstChild,Ai=H.tagName;ne=t.isHTML(H.namespaceURI)||ne;var is=Ai;if(!ne&&!H.prefix&&H.namespaceURI){for(var Ii,ji=0;ji<_t.length;ji++)if(_t.item(ji).name==="xmlns"){Ii=_t.item(ji).value;break}if(!Ii)for(var Zi=Je.length-1;Zi>=0;Zi--){var gi=Je[Zi];if(gi.prefix===""&&gi.namespace===H.namespaceURI){Ii=gi.namespace;break}}if(Ii!==H.namespaceURI)for(var Zi=Je.length-1;Zi>=0;Zi--){var gi=Je[Zi];if(gi.namespace===H.namespaceURI){gi.prefix&&(is=gi.prefix+":"+Ai);break}}}q.push("<",is);for(var ss=0;ss"),ne&&/^script$/i.test(Ai))for(;Yt;)Yt.data?q.push(Yt.data):Ei(Yt,q,ne,Se,Je.slice()),Yt=Yt.nextSibling;else for(;Yt;)Ei(Yt,q,ne,Se,Je.slice()),Yt=Yt.nextSibling;q.push("")}else q.push("/>");return;case L:case U:for(var Yt=H.firstChild;Yt;)Ei(Yt,q,ne,Se,Je.slice()),Yt=Yt.nextSibling;return;case g:return pi(q,H.name,H.value);case v:return q.push(H.data.replace(/[<&>]/g,ee));case b:return q.push("");case R:return q.push("");case P:var Xt=H.publicId,Hs=H.systemId;if(q.push("");else if(Hs&&Hs!=".")q.push(" SYSTEM ",Hs,">");else{var qi=H.internalSubset;qi&&q.push(" [",qi,"]"),q.push(">")}return;case D:return q.push("");case _:return q.push("&",H.nodeName,";");default:q.push("??",H.nodeName)}}function Tt(H,q,ne){var Se;switch(q.nodeType){case p:Se=q.cloneNode(!1),Se.ownerDocument=H;case U:break;case g:ne=!0;break}if(Se||(Se=q.cloneNode(!1)),Se.ownerDocument=H,Se.parentNode=null,ne)for(var Je=q.firstChild;Je;)Se.appendChild(Tt(H,Je,ne)),Je=Je.nextSibling;return Se}function ft(H,q,ne){var Se=new q.constructor;for(var Je in q)if(Object.prototype.hasOwnProperty.call(q,Je)){var _t=q[Je];typeof _t!="object"&&_t!=Se[Je]&&(Se[Je]=_t)}switch(q.childNodes&&(Se.childNodes=new W),Se.ownerDocument=H,Se.nodeType){case p:var ei=q.attributes,Ai=Se.attributes=new Y,is=ei.length;Ai._ownerElement=Se;for(var Ii=0;Ii",lt:"<",quot:'"'}),s.HTML_ENTITIES=e({Aacute:"Á",aacute:"á",Abreve:"Ă",abreve:"ă",ac:"∾",acd:"∿",acE:"∾̳",Acirc:"Â",acirc:"â",acute:"´",Acy:"А",acy:"а",AElig:"Æ",aelig:"æ",af:"⁡",Afr:"𝔄",afr:"𝔞",Agrave:"À",agrave:"à",alefsym:"ℵ",aleph:"ℵ",Alpha:"Α",alpha:"α",Amacr:"Ā",amacr:"ā",amalg:"⨿",AMP:"&",amp:"&",And:"⩓",and:"∧",andand:"⩕",andd:"⩜",andslope:"⩘",andv:"⩚",ang:"∠",ange:"⦤",angle:"∠",angmsd:"∡",angmsdaa:"⦨",angmsdab:"⦩",angmsdac:"⦪",angmsdad:"⦫",angmsdae:"⦬",angmsdaf:"⦭",angmsdag:"⦮",angmsdah:"⦯",angrt:"∟",angrtvb:"⊾",angrtvbd:"⦝",angsph:"∢",angst:"Å",angzarr:"⍼",Aogon:"Ą",aogon:"ą",Aopf:"𝔸",aopf:"𝕒",ap:"≈",apacir:"⩯",apE:"⩰",ape:"≊",apid:"≋",apos:"'",ApplyFunction:"⁡",approx:"≈",approxeq:"≊",Aring:"Å",aring:"å",Ascr:"𝒜",ascr:"𝒶",Assign:"≔",ast:"*",asymp:"≈",asympeq:"≍",Atilde:"Ã",atilde:"ã",Auml:"Ä",auml:"ä",awconint:"∳",awint:"⨑",backcong:"≌",backepsilon:"϶",backprime:"‵",backsim:"∽",backsimeq:"⋍",Backslash:"∖",Barv:"⫧",barvee:"⊽",Barwed:"⌆",barwed:"⌅",barwedge:"⌅",bbrk:"⎵",bbrktbrk:"⎶",bcong:"≌",Bcy:"Б",bcy:"б",bdquo:"„",becaus:"∵",Because:"∵",because:"∵",bemptyv:"⦰",bepsi:"϶",bernou:"ℬ",Bernoullis:"ℬ",Beta:"Β",beta:"β",beth:"ℶ",between:"≬",Bfr:"𝔅",bfr:"𝔟",bigcap:"⋂",bigcirc:"◯",bigcup:"⋃",bigodot:"⨀",bigoplus:"⨁",bigotimes:"⨂",bigsqcup:"⨆",bigstar:"★",bigtriangledown:"▽",bigtriangleup:"△",biguplus:"⨄",bigvee:"⋁",bigwedge:"⋀",bkarow:"⤍",blacklozenge:"⧫",blacksquare:"▪",blacktriangle:"▴",blacktriangledown:"▾",blacktriangleleft:"◂",blacktriangleright:"▸",blank:"␣",blk12:"▒",blk14:"░",blk34:"▓",block:"█",bne:"=⃥",bnequiv:"≡⃥",bNot:"⫭",bnot:"⌐",Bopf:"𝔹",bopf:"𝕓",bot:"⊥",bottom:"⊥",bowtie:"⋈",boxbox:"⧉",boxDL:"╗",boxDl:"╖",boxdL:"╕",boxdl:"┐",boxDR:"╔",boxDr:"╓",boxdR:"╒",boxdr:"┌",boxH:"═",boxh:"─",boxHD:"╦",boxHd:"╤",boxhD:"╥",boxhd:"┬",boxHU:"╩",boxHu:"╧",boxhU:"╨",boxhu:"┴",boxminus:"⊟",boxplus:"⊞",boxtimes:"⊠",boxUL:"╝",boxUl:"╜",boxuL:"╛",boxul:"┘",boxUR:"╚",boxUr:"╙",boxuR:"╘",boxur:"└",boxV:"║",boxv:"│",boxVH:"╬",boxVh:"╫",boxvH:"╪",boxvh:"┼",boxVL:"╣",boxVl:"╢",boxvL:"╡",boxvl:"┤",boxVR:"╠",boxVr:"╟",boxvR:"╞",boxvr:"├",bprime:"‵",Breve:"˘",breve:"˘",brvbar:"¦",Bscr:"ℬ",bscr:"𝒷",bsemi:"⁏",bsim:"∽",bsime:"⋍",bsol:"\\",bsolb:"⧅",bsolhsub:"⟈",bull:"•",bullet:"•",bump:"≎",bumpE:"⪮",bumpe:"≏",Bumpeq:"≎",bumpeq:"≏",Cacute:"Ć",cacute:"ć",Cap:"⋒",cap:"∩",capand:"⩄",capbrcup:"⩉",capcap:"⩋",capcup:"⩇",capdot:"⩀",CapitalDifferentialD:"ⅅ",caps:"∩︀",caret:"⁁",caron:"ˇ",Cayleys:"ℭ",ccaps:"⩍",Ccaron:"Č",ccaron:"č",Ccedil:"Ç",ccedil:"ç",Ccirc:"Ĉ",ccirc:"ĉ",Cconint:"∰",ccups:"⩌",ccupssm:"⩐",Cdot:"Ċ",cdot:"ċ",cedil:"¸",Cedilla:"¸",cemptyv:"⦲",cent:"¢",CenterDot:"·",centerdot:"·",Cfr:"ℭ",cfr:"𝔠",CHcy:"Ч",chcy:"ч",check:"✓",checkmark:"✓",Chi:"Χ",chi:"χ",cir:"○",circ:"ˆ",circeq:"≗",circlearrowleft:"↺",circlearrowright:"↻",circledast:"⊛",circledcirc:"⊚",circleddash:"⊝",CircleDot:"⊙",circledR:"®",circledS:"Ⓢ",CircleMinus:"⊖",CirclePlus:"⊕",CircleTimes:"⊗",cirE:"⧃",cire:"≗",cirfnint:"⨐",cirmid:"⫯",cirscir:"⧂",ClockwiseContourIntegral:"∲",CloseCurlyDoubleQuote:"”",CloseCurlyQuote:"’",clubs:"♣",clubsuit:"♣",Colon:"∷",colon:":",Colone:"⩴",colone:"≔",coloneq:"≔",comma:",",commat:"@",comp:"∁",compfn:"∘",complement:"∁",complexes:"ℂ",cong:"≅",congdot:"⩭",Congruent:"≡",Conint:"∯",conint:"∮",ContourIntegral:"∮",Copf:"ℂ",copf:"𝕔",coprod:"∐",Coproduct:"∐",COPY:"©",copy:"©",copysr:"℗",CounterClockwiseContourIntegral:"∳",crarr:"↵",Cross:"⨯",cross:"✗",Cscr:"𝒞",cscr:"𝒸",csub:"⫏",csube:"⫑",csup:"⫐",csupe:"⫒",ctdot:"⋯",cudarrl:"⤸",cudarrr:"⤵",cuepr:"⋞",cuesc:"⋟",cularr:"↶",cularrp:"⤽",Cup:"⋓",cup:"∪",cupbrcap:"⩈",CupCap:"≍",cupcap:"⩆",cupcup:"⩊",cupdot:"⊍",cupor:"⩅",cups:"∪︀",curarr:"↷",curarrm:"⤼",curlyeqprec:"⋞",curlyeqsucc:"⋟",curlyvee:"⋎",curlywedge:"⋏",curren:"¤",curvearrowleft:"↶",curvearrowright:"↷",cuvee:"⋎",cuwed:"⋏",cwconint:"∲",cwint:"∱",cylcty:"⌭",Dagger:"‡",dagger:"†",daleth:"ℸ",Darr:"↡",dArr:"⇓",darr:"↓",dash:"‐",Dashv:"⫤",dashv:"⊣",dbkarow:"⤏",dblac:"˝",Dcaron:"Ď",dcaron:"ď",Dcy:"Д",dcy:"д",DD:"ⅅ",dd:"ⅆ",ddagger:"‡",ddarr:"⇊",DDotrahd:"⤑",ddotseq:"⩷",deg:"°",Del:"∇",Delta:"Δ",delta:"δ",demptyv:"⦱",dfisht:"⥿",Dfr:"𝔇",dfr:"𝔡",dHar:"⥥",dharl:"⇃",dharr:"⇂",DiacriticalAcute:"´",DiacriticalDot:"˙",DiacriticalDoubleAcute:"˝",DiacriticalGrave:"`",DiacriticalTilde:"˜",diam:"⋄",Diamond:"⋄",diamond:"⋄",diamondsuit:"♦",diams:"♦",die:"¨",DifferentialD:"ⅆ",digamma:"ϝ",disin:"⋲",div:"÷",divide:"÷",divideontimes:"⋇",divonx:"⋇",DJcy:"Ђ",djcy:"ђ",dlcorn:"⌞",dlcrop:"⌍",dollar:"$",Dopf:"𝔻",dopf:"𝕕",Dot:"¨",dot:"˙",DotDot:"⃜",doteq:"≐",doteqdot:"≑",DotEqual:"≐",dotminus:"∸",dotplus:"∔",dotsquare:"⊡",doublebarwedge:"⌆",DoubleContourIntegral:"∯",DoubleDot:"¨",DoubleDownArrow:"⇓",DoubleLeftArrow:"⇐",DoubleLeftRightArrow:"⇔",DoubleLeftTee:"⫤",DoubleLongLeftArrow:"⟸",DoubleLongLeftRightArrow:"⟺",DoubleLongRightArrow:"⟹",DoubleRightArrow:"⇒",DoubleRightTee:"⊨",DoubleUpArrow:"⇑",DoubleUpDownArrow:"⇕",DoubleVerticalBar:"∥",DownArrow:"↓",Downarrow:"⇓",downarrow:"↓",DownArrowBar:"⤓",DownArrowUpArrow:"⇵",DownBreve:"̑",downdownarrows:"⇊",downharpoonleft:"⇃",downharpoonright:"⇂",DownLeftRightVector:"⥐",DownLeftTeeVector:"⥞",DownLeftVector:"↽",DownLeftVectorBar:"⥖",DownRightTeeVector:"⥟",DownRightVector:"⇁",DownRightVectorBar:"⥗",DownTee:"⊤",DownTeeArrow:"↧",drbkarow:"⤐",drcorn:"⌟",drcrop:"⌌",Dscr:"𝒟",dscr:"𝒹",DScy:"Ѕ",dscy:"ѕ",dsol:"⧶",Dstrok:"Đ",dstrok:"đ",dtdot:"⋱",dtri:"▿",dtrif:"▾",duarr:"⇵",duhar:"⥯",dwangle:"⦦",DZcy:"Џ",dzcy:"џ",dzigrarr:"⟿",Eacute:"É",eacute:"é",easter:"⩮",Ecaron:"Ě",ecaron:"ě",ecir:"≖",Ecirc:"Ê",ecirc:"ê",ecolon:"≕",Ecy:"Э",ecy:"э",eDDot:"⩷",Edot:"Ė",eDot:"≑",edot:"ė",ee:"ⅇ",efDot:"≒",Efr:"𝔈",efr:"𝔢",eg:"⪚",Egrave:"È",egrave:"è",egs:"⪖",egsdot:"⪘",el:"⪙",Element:"∈",elinters:"⏧",ell:"ℓ",els:"⪕",elsdot:"⪗",Emacr:"Ē",emacr:"ē",empty:"∅",emptyset:"∅",EmptySmallSquare:"◻",emptyv:"∅",EmptyVerySmallSquare:"▫",emsp:" ",emsp13:" ",emsp14:" ",ENG:"Ŋ",eng:"ŋ",ensp:" ",Eogon:"Ę",eogon:"ę",Eopf:"𝔼",eopf:"𝕖",epar:"⋕",eparsl:"⧣",eplus:"⩱",epsi:"ε",Epsilon:"Ε",epsilon:"ε",epsiv:"ϵ",eqcirc:"≖",eqcolon:"≕",eqsim:"≂",eqslantgtr:"⪖",eqslantless:"⪕",Equal:"⩵",equals:"=",EqualTilde:"≂",equest:"≟",Equilibrium:"⇌",equiv:"≡",equivDD:"⩸",eqvparsl:"⧥",erarr:"⥱",erDot:"≓",Escr:"ℰ",escr:"ℯ",esdot:"≐",Esim:"⩳",esim:"≂",Eta:"Η",eta:"η",ETH:"Ð",eth:"ð",Euml:"Ë",euml:"ë",euro:"€",excl:"!",exist:"∃",Exists:"∃",expectation:"ℰ",ExponentialE:"ⅇ",exponentiale:"ⅇ",fallingdotseq:"≒",Fcy:"Ф",fcy:"ф",female:"♀",ffilig:"ffi",fflig:"ff",ffllig:"ffl",Ffr:"𝔉",ffr:"𝔣",filig:"fi",FilledSmallSquare:"◼",FilledVerySmallSquare:"▪",fjlig:"fj",flat:"♭",fllig:"fl",fltns:"▱",fnof:"ƒ",Fopf:"𝔽",fopf:"𝕗",ForAll:"∀",forall:"∀",fork:"⋔",forkv:"⫙",Fouriertrf:"ℱ",fpartint:"⨍",frac12:"½",frac13:"⅓",frac14:"¼",frac15:"⅕",frac16:"⅙",frac18:"⅛",frac23:"⅔",frac25:"⅖",frac34:"¾",frac35:"⅗",frac38:"⅜",frac45:"⅘",frac56:"⅚",frac58:"⅝",frac78:"⅞",frasl:"⁄",frown:"⌢",Fscr:"ℱ",fscr:"𝒻",gacute:"ǵ",Gamma:"Γ",gamma:"γ",Gammad:"Ϝ",gammad:"ϝ",gap:"⪆",Gbreve:"Ğ",gbreve:"ğ",Gcedil:"Ģ",Gcirc:"Ĝ",gcirc:"ĝ",Gcy:"Г",gcy:"г",Gdot:"Ġ",gdot:"ġ",gE:"≧",ge:"≥",gEl:"⪌",gel:"⋛",geq:"≥",geqq:"≧",geqslant:"⩾",ges:"⩾",gescc:"⪩",gesdot:"⪀",gesdoto:"⪂",gesdotol:"⪄",gesl:"⋛︀",gesles:"⪔",Gfr:"𝔊",gfr:"𝔤",Gg:"⋙",gg:"≫",ggg:"⋙",gimel:"ℷ",GJcy:"Ѓ",gjcy:"ѓ",gl:"≷",gla:"⪥",glE:"⪒",glj:"⪤",gnap:"⪊",gnapprox:"⪊",gnE:"≩",gne:"⪈",gneq:"⪈",gneqq:"≩",gnsim:"⋧",Gopf:"𝔾",gopf:"𝕘",grave:"`",GreaterEqual:"≥",GreaterEqualLess:"⋛",GreaterFullEqual:"≧",GreaterGreater:"⪢",GreaterLess:"≷",GreaterSlantEqual:"⩾",GreaterTilde:"≳",Gscr:"𝒢",gscr:"ℊ",gsim:"≳",gsime:"⪎",gsiml:"⪐",Gt:"≫",GT:">",gt:">",gtcc:"⪧",gtcir:"⩺",gtdot:"⋗",gtlPar:"⦕",gtquest:"⩼",gtrapprox:"⪆",gtrarr:"⥸",gtrdot:"⋗",gtreqless:"⋛",gtreqqless:"⪌",gtrless:"≷",gtrsim:"≳",gvertneqq:"≩︀",gvnE:"≩︀",Hacek:"ˇ",hairsp:" ",half:"½",hamilt:"ℋ",HARDcy:"Ъ",hardcy:"ъ",hArr:"⇔",harr:"↔",harrcir:"⥈",harrw:"↭",Hat:"^",hbar:"ℏ",Hcirc:"Ĥ",hcirc:"ĥ",hearts:"♥",heartsuit:"♥",hellip:"…",hercon:"⊹",Hfr:"ℌ",hfr:"𝔥",HilbertSpace:"ℋ",hksearow:"⤥",hkswarow:"⤦",hoarr:"⇿",homtht:"∻",hookleftarrow:"↩",hookrightarrow:"↪",Hopf:"ℍ",hopf:"𝕙",horbar:"―",HorizontalLine:"─",Hscr:"ℋ",hscr:"𝒽",hslash:"ℏ",Hstrok:"Ħ",hstrok:"ħ",HumpDownHump:"≎",HumpEqual:"≏",hybull:"⁃",hyphen:"‐",Iacute:"Í",iacute:"í",ic:"⁣",Icirc:"Î",icirc:"î",Icy:"И",icy:"и",Idot:"İ",IEcy:"Е",iecy:"е",iexcl:"¡",iff:"⇔",Ifr:"ℑ",ifr:"𝔦",Igrave:"Ì",igrave:"ì",ii:"ⅈ",iiiint:"⨌",iiint:"∭",iinfin:"⧜",iiota:"℩",IJlig:"IJ",ijlig:"ij",Im:"ℑ",Imacr:"Ī",imacr:"ī",image:"ℑ",ImaginaryI:"ⅈ",imagline:"ℐ",imagpart:"ℑ",imath:"ı",imof:"⊷",imped:"Ƶ",Implies:"⇒",in:"∈",incare:"℅",infin:"∞",infintie:"⧝",inodot:"ı",Int:"∬",int:"∫",intcal:"⊺",integers:"ℤ",Integral:"∫",intercal:"⊺",Intersection:"⋂",intlarhk:"⨗",intprod:"⨼",InvisibleComma:"⁣",InvisibleTimes:"⁢",IOcy:"Ё",iocy:"ё",Iogon:"Į",iogon:"į",Iopf:"𝕀",iopf:"𝕚",Iota:"Ι",iota:"ι",iprod:"⨼",iquest:"¿",Iscr:"ℐ",iscr:"𝒾",isin:"∈",isindot:"⋵",isinE:"⋹",isins:"⋴",isinsv:"⋳",isinv:"∈",it:"⁢",Itilde:"Ĩ",itilde:"ĩ",Iukcy:"І",iukcy:"і",Iuml:"Ï",iuml:"ï",Jcirc:"Ĵ",jcirc:"ĵ",Jcy:"Й",jcy:"й",Jfr:"𝔍",jfr:"𝔧",jmath:"ȷ",Jopf:"𝕁",jopf:"𝕛",Jscr:"𝒥",jscr:"𝒿",Jsercy:"Ј",jsercy:"ј",Jukcy:"Є",jukcy:"є",Kappa:"Κ",kappa:"κ",kappav:"ϰ",Kcedil:"Ķ",kcedil:"ķ",Kcy:"К",kcy:"к",Kfr:"𝔎",kfr:"𝔨",kgreen:"ĸ",KHcy:"Х",khcy:"х",KJcy:"Ќ",kjcy:"ќ",Kopf:"𝕂",kopf:"𝕜",Kscr:"𝒦",kscr:"𝓀",lAarr:"⇚",Lacute:"Ĺ",lacute:"ĺ",laemptyv:"⦴",lagran:"ℒ",Lambda:"Λ",lambda:"λ",Lang:"⟪",lang:"⟨",langd:"⦑",langle:"⟨",lap:"⪅",Laplacetrf:"ℒ",laquo:"«",Larr:"↞",lArr:"⇐",larr:"←",larrb:"⇤",larrbfs:"⤟",larrfs:"⤝",larrhk:"↩",larrlp:"↫",larrpl:"⤹",larrsim:"⥳",larrtl:"↢",lat:"⪫",lAtail:"⤛",latail:"⤙",late:"⪭",lates:"⪭︀",lBarr:"⤎",lbarr:"⤌",lbbrk:"❲",lbrace:"{",lbrack:"[",lbrke:"⦋",lbrksld:"⦏",lbrkslu:"⦍",Lcaron:"Ľ",lcaron:"ľ",Lcedil:"Ļ",lcedil:"ļ",lceil:"⌈",lcub:"{",Lcy:"Л",lcy:"л",ldca:"⤶",ldquo:"“",ldquor:"„",ldrdhar:"⥧",ldrushar:"⥋",ldsh:"↲",lE:"≦",le:"≤",LeftAngleBracket:"⟨",LeftArrow:"←",Leftarrow:"⇐",leftarrow:"←",LeftArrowBar:"⇤",LeftArrowRightArrow:"⇆",leftarrowtail:"↢",LeftCeiling:"⌈",LeftDoubleBracket:"⟦",LeftDownTeeVector:"⥡",LeftDownVector:"⇃",LeftDownVectorBar:"⥙",LeftFloor:"⌊",leftharpoondown:"↽",leftharpoonup:"↼",leftleftarrows:"⇇",LeftRightArrow:"↔",Leftrightarrow:"⇔",leftrightarrow:"↔",leftrightarrows:"⇆",leftrightharpoons:"⇋",leftrightsquigarrow:"↭",LeftRightVector:"⥎",LeftTee:"⊣",LeftTeeArrow:"↤",LeftTeeVector:"⥚",leftthreetimes:"⋋",LeftTriangle:"⊲",LeftTriangleBar:"⧏",LeftTriangleEqual:"⊴",LeftUpDownVector:"⥑",LeftUpTeeVector:"⥠",LeftUpVector:"↿",LeftUpVectorBar:"⥘",LeftVector:"↼",LeftVectorBar:"⥒",lEg:"⪋",leg:"⋚",leq:"≤",leqq:"≦",leqslant:"⩽",les:"⩽",lescc:"⪨",lesdot:"⩿",lesdoto:"⪁",lesdotor:"⪃",lesg:"⋚︀",lesges:"⪓",lessapprox:"⪅",lessdot:"⋖",lesseqgtr:"⋚",lesseqqgtr:"⪋",LessEqualGreater:"⋚",LessFullEqual:"≦",LessGreater:"≶",lessgtr:"≶",LessLess:"⪡",lesssim:"≲",LessSlantEqual:"⩽",LessTilde:"≲",lfisht:"⥼",lfloor:"⌊",Lfr:"𝔏",lfr:"𝔩",lg:"≶",lgE:"⪑",lHar:"⥢",lhard:"↽",lharu:"↼",lharul:"⥪",lhblk:"▄",LJcy:"Љ",ljcy:"љ",Ll:"⋘",ll:"≪",llarr:"⇇",llcorner:"⌞",Lleftarrow:"⇚",llhard:"⥫",lltri:"◺",Lmidot:"Ŀ",lmidot:"ŀ",lmoust:"⎰",lmoustache:"⎰",lnap:"⪉",lnapprox:"⪉",lnE:"≨",lne:"⪇",lneq:"⪇",lneqq:"≨",lnsim:"⋦",loang:"⟬",loarr:"⇽",lobrk:"⟦",LongLeftArrow:"⟵",Longleftarrow:"⟸",longleftarrow:"⟵",LongLeftRightArrow:"⟷",Longleftrightarrow:"⟺",longleftrightarrow:"⟷",longmapsto:"⟼",LongRightArrow:"⟶",Longrightarrow:"⟹",longrightarrow:"⟶",looparrowleft:"↫",looparrowright:"↬",lopar:"⦅",Lopf:"𝕃",lopf:"𝕝",loplus:"⨭",lotimes:"⨴",lowast:"∗",lowbar:"_",LowerLeftArrow:"↙",LowerRightArrow:"↘",loz:"◊",lozenge:"◊",lozf:"⧫",lpar:"(",lparlt:"⦓",lrarr:"⇆",lrcorner:"⌟",lrhar:"⇋",lrhard:"⥭",lrm:"‎",lrtri:"⊿",lsaquo:"‹",Lscr:"ℒ",lscr:"𝓁",Lsh:"↰",lsh:"↰",lsim:"≲",lsime:"⪍",lsimg:"⪏",lsqb:"[",lsquo:"‘",lsquor:"‚",Lstrok:"Ł",lstrok:"ł",Lt:"≪",LT:"<",lt:"<",ltcc:"⪦",ltcir:"⩹",ltdot:"⋖",lthree:"⋋",ltimes:"⋉",ltlarr:"⥶",ltquest:"⩻",ltri:"◃",ltrie:"⊴",ltrif:"◂",ltrPar:"⦖",lurdshar:"⥊",luruhar:"⥦",lvertneqq:"≨︀",lvnE:"≨︀",macr:"¯",male:"♂",malt:"✠",maltese:"✠",Map:"⤅",map:"↦",mapsto:"↦",mapstodown:"↧",mapstoleft:"↤",mapstoup:"↥",marker:"▮",mcomma:"⨩",Mcy:"М",mcy:"м",mdash:"—",mDDot:"∺",measuredangle:"∡",MediumSpace:" ",Mellintrf:"ℳ",Mfr:"𝔐",mfr:"𝔪",mho:"℧",micro:"µ",mid:"∣",midast:"*",midcir:"⫰",middot:"·",minus:"−",minusb:"⊟",minusd:"∸",minusdu:"⨪",MinusPlus:"∓",mlcp:"⫛",mldr:"…",mnplus:"∓",models:"⊧",Mopf:"𝕄",mopf:"𝕞",mp:"∓",Mscr:"ℳ",mscr:"𝓂",mstpos:"∾",Mu:"Μ",mu:"μ",multimap:"⊸",mumap:"⊸",nabla:"∇",Nacute:"Ń",nacute:"ń",nang:"∠⃒",nap:"≉",napE:"⩰̸",napid:"≋̸",napos:"ʼn",napprox:"≉",natur:"♮",natural:"♮",naturals:"ℕ",nbsp:" ",nbump:"≎̸",nbumpe:"≏̸",ncap:"⩃",Ncaron:"Ň",ncaron:"ň",Ncedil:"Ņ",ncedil:"ņ",ncong:"≇",ncongdot:"⩭̸",ncup:"⩂",Ncy:"Н",ncy:"н",ndash:"–",ne:"≠",nearhk:"⤤",neArr:"⇗",nearr:"↗",nearrow:"↗",nedot:"≐̸",NegativeMediumSpace:"​",NegativeThickSpace:"​",NegativeThinSpace:"​",NegativeVeryThinSpace:"​",nequiv:"≢",nesear:"⤨",nesim:"≂̸",NestedGreaterGreater:"≫",NestedLessLess:"≪",NewLine:` `,nexist:"∄",nexists:"∄",Nfr:"𝔑",nfr:"𝔫",ngE:"≧̸",nge:"≱",ngeq:"≱",ngeqq:"≧̸",ngeqslant:"⩾̸",nges:"⩾̸",nGg:"⋙̸",ngsim:"≵",nGt:"≫⃒",ngt:"≯",ngtr:"≯",nGtv:"≫̸",nhArr:"⇎",nharr:"↮",nhpar:"⫲",ni:"∋",nis:"⋼",nisd:"⋺",niv:"∋",NJcy:"Њ",njcy:"њ",nlArr:"⇍",nlarr:"↚",nldr:"‥",nlE:"≦̸",nle:"≰",nLeftarrow:"⇍",nleftarrow:"↚",nLeftrightarrow:"⇎",nleftrightarrow:"↮",nleq:"≰",nleqq:"≦̸",nleqslant:"⩽̸",nles:"⩽̸",nless:"≮",nLl:"⋘̸",nlsim:"≴",nLt:"≪⃒",nlt:"≮",nltri:"⋪",nltrie:"⋬",nLtv:"≪̸",nmid:"∤",NoBreak:"⁠",NonBreakingSpace:" ",Nopf:"ℕ",nopf:"𝕟",Not:"⫬",not:"¬",NotCongruent:"≢",NotCupCap:"≭",NotDoubleVerticalBar:"∦",NotElement:"∉",NotEqual:"≠",NotEqualTilde:"≂̸",NotExists:"∄",NotGreater:"≯",NotGreaterEqual:"≱",NotGreaterFullEqual:"≧̸",NotGreaterGreater:"≫̸",NotGreaterLess:"≹",NotGreaterSlantEqual:"⩾̸",NotGreaterTilde:"≵",NotHumpDownHump:"≎̸",NotHumpEqual:"≏̸",notin:"∉",notindot:"⋵̸",notinE:"⋹̸",notinva:"∉",notinvb:"⋷",notinvc:"⋶",NotLeftTriangle:"⋪",NotLeftTriangleBar:"⧏̸",NotLeftTriangleEqual:"⋬",NotLess:"≮",NotLessEqual:"≰",NotLessGreater:"≸",NotLessLess:"≪̸",NotLessSlantEqual:"⩽̸",NotLessTilde:"≴",NotNestedGreaterGreater:"⪢̸",NotNestedLessLess:"⪡̸",notni:"∌",notniva:"∌",notnivb:"⋾",notnivc:"⋽",NotPrecedes:"⊀",NotPrecedesEqual:"⪯̸",NotPrecedesSlantEqual:"⋠",NotReverseElement:"∌",NotRightTriangle:"⋫",NotRightTriangleBar:"⧐̸",NotRightTriangleEqual:"⋭",NotSquareSubset:"⊏̸",NotSquareSubsetEqual:"⋢",NotSquareSuperset:"⊐̸",NotSquareSupersetEqual:"⋣",NotSubset:"⊂⃒",NotSubsetEqual:"⊈",NotSucceeds:"⊁",NotSucceedsEqual:"⪰̸",NotSucceedsSlantEqual:"⋡",NotSucceedsTilde:"≿̸",NotSuperset:"⊃⃒",NotSupersetEqual:"⊉",NotTilde:"≁",NotTildeEqual:"≄",NotTildeFullEqual:"≇",NotTildeTilde:"≉",NotVerticalBar:"∤",npar:"∦",nparallel:"∦",nparsl:"⫽⃥",npart:"∂̸",npolint:"⨔",npr:"⊀",nprcue:"⋠",npre:"⪯̸",nprec:"⊀",npreceq:"⪯̸",nrArr:"⇏",nrarr:"↛",nrarrc:"⤳̸",nrarrw:"↝̸",nRightarrow:"⇏",nrightarrow:"↛",nrtri:"⋫",nrtrie:"⋭",nsc:"⊁",nsccue:"⋡",nsce:"⪰̸",Nscr:"𝒩",nscr:"𝓃",nshortmid:"∤",nshortparallel:"∦",nsim:"≁",nsime:"≄",nsimeq:"≄",nsmid:"∤",nspar:"∦",nsqsube:"⋢",nsqsupe:"⋣",nsub:"⊄",nsubE:"⫅̸",nsube:"⊈",nsubset:"⊂⃒",nsubseteq:"⊈",nsubseteqq:"⫅̸",nsucc:"⊁",nsucceq:"⪰̸",nsup:"⊅",nsupE:"⫆̸",nsupe:"⊉",nsupset:"⊃⃒",nsupseteq:"⊉",nsupseteqq:"⫆̸",ntgl:"≹",Ntilde:"Ñ",ntilde:"ñ",ntlg:"≸",ntriangleleft:"⋪",ntrianglelefteq:"⋬",ntriangleright:"⋫",ntrianglerighteq:"⋭",Nu:"Ν",nu:"ν",num:"#",numero:"№",numsp:" ",nvap:"≍⃒",nVDash:"⊯",nVdash:"⊮",nvDash:"⊭",nvdash:"⊬",nvge:"≥⃒",nvgt:">⃒",nvHarr:"⤄",nvinfin:"⧞",nvlArr:"⤂",nvle:"≤⃒",nvlt:"<⃒",nvltrie:"⊴⃒",nvrArr:"⤃",nvrtrie:"⊵⃒",nvsim:"∼⃒",nwarhk:"⤣",nwArr:"⇖",nwarr:"↖",nwarrow:"↖",nwnear:"⤧",Oacute:"Ó",oacute:"ó",oast:"⊛",ocir:"⊚",Ocirc:"Ô",ocirc:"ô",Ocy:"О",ocy:"о",odash:"⊝",Odblac:"Ő",odblac:"ő",odiv:"⨸",odot:"⊙",odsold:"⦼",OElig:"Œ",oelig:"œ",ofcir:"⦿",Ofr:"𝔒",ofr:"𝔬",ogon:"˛",Ograve:"Ò",ograve:"ò",ogt:"⧁",ohbar:"⦵",ohm:"Ω",oint:"∮",olarr:"↺",olcir:"⦾",olcross:"⦻",oline:"‾",olt:"⧀",Omacr:"Ō",omacr:"ō",Omega:"Ω",omega:"ω",Omicron:"Ο",omicron:"ο",omid:"⦶",ominus:"⊖",Oopf:"𝕆",oopf:"𝕠",opar:"⦷",OpenCurlyDoubleQuote:"“",OpenCurlyQuote:"‘",operp:"⦹",oplus:"⊕",Or:"⩔",or:"∨",orarr:"↻",ord:"⩝",order:"ℴ",orderof:"ℴ",ordf:"ª",ordm:"º",origof:"⊶",oror:"⩖",orslope:"⩗",orv:"⩛",oS:"Ⓢ",Oscr:"𝒪",oscr:"ℴ",Oslash:"Ø",oslash:"ø",osol:"⊘",Otilde:"Õ",otilde:"õ",Otimes:"⨷",otimes:"⊗",otimesas:"⨶",Ouml:"Ö",ouml:"ö",ovbar:"⌽",OverBar:"‾",OverBrace:"⏞",OverBracket:"⎴",OverParenthesis:"⏜",par:"∥",para:"¶",parallel:"∥",parsim:"⫳",parsl:"⫽",part:"∂",PartialD:"∂",Pcy:"П",pcy:"п",percnt:"%",period:".",permil:"‰",perp:"⊥",pertenk:"‱",Pfr:"𝔓",pfr:"𝔭",Phi:"Φ",phi:"φ",phiv:"ϕ",phmmat:"ℳ",phone:"☎",Pi:"Π",pi:"π",pitchfork:"⋔",piv:"ϖ",planck:"ℏ",planckh:"ℎ",plankv:"ℏ",plus:"+",plusacir:"⨣",plusb:"⊞",pluscir:"⨢",plusdo:"∔",plusdu:"⨥",pluse:"⩲",PlusMinus:"±",plusmn:"±",plussim:"⨦",plustwo:"⨧",pm:"±",Poincareplane:"ℌ",pointint:"⨕",Popf:"ℙ",popf:"𝕡",pound:"£",Pr:"⪻",pr:"≺",prap:"⪷",prcue:"≼",prE:"⪳",pre:"⪯",prec:"≺",precapprox:"⪷",preccurlyeq:"≼",Precedes:"≺",PrecedesEqual:"⪯",PrecedesSlantEqual:"≼",PrecedesTilde:"≾",preceq:"⪯",precnapprox:"⪹",precneqq:"⪵",precnsim:"⋨",precsim:"≾",Prime:"″",prime:"′",primes:"ℙ",prnap:"⪹",prnE:"⪵",prnsim:"⋨",prod:"∏",Product:"∏",profalar:"⌮",profline:"⌒",profsurf:"⌓",prop:"∝",Proportion:"∷",Proportional:"∝",propto:"∝",prsim:"≾",prurel:"⊰",Pscr:"𝒫",pscr:"𝓅",Psi:"Ψ",psi:"ψ",puncsp:" ",Qfr:"𝔔",qfr:"𝔮",qint:"⨌",Qopf:"ℚ",qopf:"𝕢",qprime:"⁗",Qscr:"𝒬",qscr:"𝓆",quaternions:"ℍ",quatint:"⨖",quest:"?",questeq:"≟",QUOT:'"',quot:'"',rAarr:"⇛",race:"∽̱",Racute:"Ŕ",racute:"ŕ",radic:"√",raemptyv:"⦳",Rang:"⟫",rang:"⟩",rangd:"⦒",range:"⦥",rangle:"⟩",raquo:"»",Rarr:"↠",rArr:"⇒",rarr:"→",rarrap:"⥵",rarrb:"⇥",rarrbfs:"⤠",rarrc:"⤳",rarrfs:"⤞",rarrhk:"↪",rarrlp:"↬",rarrpl:"⥅",rarrsim:"⥴",Rarrtl:"⤖",rarrtl:"↣",rarrw:"↝",rAtail:"⤜",ratail:"⤚",ratio:"∶",rationals:"ℚ",RBarr:"⤐",rBarr:"⤏",rbarr:"⤍",rbbrk:"❳",rbrace:"}",rbrack:"]",rbrke:"⦌",rbrksld:"⦎",rbrkslu:"⦐",Rcaron:"Ř",rcaron:"ř",Rcedil:"Ŗ",rcedil:"ŗ",rceil:"⌉",rcub:"}",Rcy:"Р",rcy:"р",rdca:"⤷",rdldhar:"⥩",rdquo:"”",rdquor:"”",rdsh:"↳",Re:"ℜ",real:"ℜ",realine:"ℛ",realpart:"ℜ",reals:"ℝ",rect:"▭",REG:"®",reg:"®",ReverseElement:"∋",ReverseEquilibrium:"⇋",ReverseUpEquilibrium:"⥯",rfisht:"⥽",rfloor:"⌋",Rfr:"ℜ",rfr:"𝔯",rHar:"⥤",rhard:"⇁",rharu:"⇀",rharul:"⥬",Rho:"Ρ",rho:"ρ",rhov:"ϱ",RightAngleBracket:"⟩",RightArrow:"→",Rightarrow:"⇒",rightarrow:"→",RightArrowBar:"⇥",RightArrowLeftArrow:"⇄",rightarrowtail:"↣",RightCeiling:"⌉",RightDoubleBracket:"⟧",RightDownTeeVector:"⥝",RightDownVector:"⇂",RightDownVectorBar:"⥕",RightFloor:"⌋",rightharpoondown:"⇁",rightharpoonup:"⇀",rightleftarrows:"⇄",rightleftharpoons:"⇌",rightrightarrows:"⇉",rightsquigarrow:"↝",RightTee:"⊢",RightTeeArrow:"↦",RightTeeVector:"⥛",rightthreetimes:"⋌",RightTriangle:"⊳",RightTriangleBar:"⧐",RightTriangleEqual:"⊵",RightUpDownVector:"⥏",RightUpTeeVector:"⥜",RightUpVector:"↾",RightUpVectorBar:"⥔",RightVector:"⇀",RightVectorBar:"⥓",ring:"˚",risingdotseq:"≓",rlarr:"⇄",rlhar:"⇌",rlm:"‏",rmoust:"⎱",rmoustache:"⎱",rnmid:"⫮",roang:"⟭",roarr:"⇾",robrk:"⟧",ropar:"⦆",Ropf:"ℝ",ropf:"𝕣",roplus:"⨮",rotimes:"⨵",RoundImplies:"⥰",rpar:")",rpargt:"⦔",rppolint:"⨒",rrarr:"⇉",Rrightarrow:"⇛",rsaquo:"›",Rscr:"ℛ",rscr:"𝓇",Rsh:"↱",rsh:"↱",rsqb:"]",rsquo:"’",rsquor:"’",rthree:"⋌",rtimes:"⋊",rtri:"▹",rtrie:"⊵",rtrif:"▸",rtriltri:"⧎",RuleDelayed:"⧴",ruluhar:"⥨",rx:"℞",Sacute:"Ś",sacute:"ś",sbquo:"‚",Sc:"⪼",sc:"≻",scap:"⪸",Scaron:"Š",scaron:"š",sccue:"≽",scE:"⪴",sce:"⪰",Scedil:"Ş",scedil:"ş",Scirc:"Ŝ",scirc:"ŝ",scnap:"⪺",scnE:"⪶",scnsim:"⋩",scpolint:"⨓",scsim:"≿",Scy:"С",scy:"с",sdot:"⋅",sdotb:"⊡",sdote:"⩦",searhk:"⤥",seArr:"⇘",searr:"↘",searrow:"↘",sect:"§",semi:";",seswar:"⤩",setminus:"∖",setmn:"∖",sext:"✶",Sfr:"𝔖",sfr:"𝔰",sfrown:"⌢",sharp:"♯",SHCHcy:"Щ",shchcy:"щ",SHcy:"Ш",shcy:"ш",ShortDownArrow:"↓",ShortLeftArrow:"←",shortmid:"∣",shortparallel:"∥",ShortRightArrow:"→",ShortUpArrow:"↑",shy:"­",Sigma:"Σ",sigma:"σ",sigmaf:"ς",sigmav:"ς",sim:"∼",simdot:"⩪",sime:"≃",simeq:"≃",simg:"⪞",simgE:"⪠",siml:"⪝",simlE:"⪟",simne:"≆",simplus:"⨤",simrarr:"⥲",slarr:"←",SmallCircle:"∘",smallsetminus:"∖",smashp:"⨳",smeparsl:"⧤",smid:"∣",smile:"⌣",smt:"⪪",smte:"⪬",smtes:"⪬︀",SOFTcy:"Ь",softcy:"ь",sol:"/",solb:"⧄",solbar:"⌿",Sopf:"𝕊",sopf:"𝕤",spades:"♠",spadesuit:"♠",spar:"∥",sqcap:"⊓",sqcaps:"⊓︀",sqcup:"⊔",sqcups:"⊔︀",Sqrt:"√",sqsub:"⊏",sqsube:"⊑",sqsubset:"⊏",sqsubseteq:"⊑",sqsup:"⊐",sqsupe:"⊒",sqsupset:"⊐",sqsupseteq:"⊒",squ:"□",Square:"□",square:"□",SquareIntersection:"⊓",SquareSubset:"⊏",SquareSubsetEqual:"⊑",SquareSuperset:"⊐",SquareSupersetEqual:"⊒",SquareUnion:"⊔",squarf:"▪",squf:"▪",srarr:"→",Sscr:"𝒮",sscr:"𝓈",ssetmn:"∖",ssmile:"⌣",sstarf:"⋆",Star:"⋆",star:"☆",starf:"★",straightepsilon:"ϵ",straightphi:"ϕ",strns:"¯",Sub:"⋐",sub:"⊂",subdot:"⪽",subE:"⫅",sube:"⊆",subedot:"⫃",submult:"⫁",subnE:"⫋",subne:"⊊",subplus:"⪿",subrarr:"⥹",Subset:"⋐",subset:"⊂",subseteq:"⊆",subseteqq:"⫅",SubsetEqual:"⊆",subsetneq:"⊊",subsetneqq:"⫋",subsim:"⫇",subsub:"⫕",subsup:"⫓",succ:"≻",succapprox:"⪸",succcurlyeq:"≽",Succeeds:"≻",SucceedsEqual:"⪰",SucceedsSlantEqual:"≽",SucceedsTilde:"≿",succeq:"⪰",succnapprox:"⪺",succneqq:"⪶",succnsim:"⋩",succsim:"≿",SuchThat:"∋",Sum:"∑",sum:"∑",sung:"♪",Sup:"⋑",sup:"⊃",sup1:"¹",sup2:"²",sup3:"³",supdot:"⪾",supdsub:"⫘",supE:"⫆",supe:"⊇",supedot:"⫄",Superset:"⊃",SupersetEqual:"⊇",suphsol:"⟉",suphsub:"⫗",suplarr:"⥻",supmult:"⫂",supnE:"⫌",supne:"⊋",supplus:"⫀",Supset:"⋑",supset:"⊃",supseteq:"⊇",supseteqq:"⫆",supsetneq:"⊋",supsetneqq:"⫌",supsim:"⫈",supsub:"⫔",supsup:"⫖",swarhk:"⤦",swArr:"⇙",swarr:"↙",swarrow:"↙",swnwar:"⤪",szlig:"ß",Tab:" ",target:"⌖",Tau:"Τ",tau:"τ",tbrk:"⎴",Tcaron:"Ť",tcaron:"ť",Tcedil:"Ţ",tcedil:"ţ",Tcy:"Т",tcy:"т",tdot:"⃛",telrec:"⌕",Tfr:"𝔗",tfr:"𝔱",there4:"∴",Therefore:"∴",therefore:"∴",Theta:"Θ",theta:"θ",thetasym:"ϑ",thetav:"ϑ",thickapprox:"≈",thicksim:"∼",ThickSpace:"  ",thinsp:" ",ThinSpace:" ",thkap:"≈",thksim:"∼",THORN:"Þ",thorn:"þ",Tilde:"∼",tilde:"˜",TildeEqual:"≃",TildeFullEqual:"≅",TildeTilde:"≈",times:"×",timesb:"⊠",timesbar:"⨱",timesd:"⨰",tint:"∭",toea:"⤨",top:"⊤",topbot:"⌶",topcir:"⫱",Topf:"𝕋",topf:"𝕥",topfork:"⫚",tosa:"⤩",tprime:"‴",TRADE:"™",trade:"™",triangle:"▵",triangledown:"▿",triangleleft:"◃",trianglelefteq:"⊴",triangleq:"≜",triangleright:"▹",trianglerighteq:"⊵",tridot:"◬",trie:"≜",triminus:"⨺",TripleDot:"⃛",triplus:"⨹",trisb:"⧍",tritime:"⨻",trpezium:"⏢",Tscr:"𝒯",tscr:"𝓉",TScy:"Ц",tscy:"ц",TSHcy:"Ћ",tshcy:"ћ",Tstrok:"Ŧ",tstrok:"ŧ",twixt:"≬",twoheadleftarrow:"↞",twoheadrightarrow:"↠",Uacute:"Ú",uacute:"ú",Uarr:"↟",uArr:"⇑",uarr:"↑",Uarrocir:"⥉",Ubrcy:"Ў",ubrcy:"ў",Ubreve:"Ŭ",ubreve:"ŭ",Ucirc:"Û",ucirc:"û",Ucy:"У",ucy:"у",udarr:"⇅",Udblac:"Ű",udblac:"ű",udhar:"⥮",ufisht:"⥾",Ufr:"𝔘",ufr:"𝔲",Ugrave:"Ù",ugrave:"ù",uHar:"⥣",uharl:"↿",uharr:"↾",uhblk:"▀",ulcorn:"⌜",ulcorner:"⌜",ulcrop:"⌏",ultri:"◸",Umacr:"Ū",umacr:"ū",uml:"¨",UnderBar:"_",UnderBrace:"⏟",UnderBracket:"⎵",UnderParenthesis:"⏝",Union:"⋃",UnionPlus:"⊎",Uogon:"Ų",uogon:"ų",Uopf:"𝕌",uopf:"𝕦",UpArrow:"↑",Uparrow:"⇑",uparrow:"↑",UpArrowBar:"⤒",UpArrowDownArrow:"⇅",UpDownArrow:"↕",Updownarrow:"⇕",updownarrow:"↕",UpEquilibrium:"⥮",upharpoonleft:"↿",upharpoonright:"↾",uplus:"⊎",UpperLeftArrow:"↖",UpperRightArrow:"↗",Upsi:"ϒ",upsi:"υ",upsih:"ϒ",Upsilon:"Υ",upsilon:"υ",UpTee:"⊥",UpTeeArrow:"↥",upuparrows:"⇈",urcorn:"⌝",urcorner:"⌝",urcrop:"⌎",Uring:"Ů",uring:"ů",urtri:"◹",Uscr:"𝒰",uscr:"𝓊",utdot:"⋰",Utilde:"Ũ",utilde:"ũ",utri:"▵",utrif:"▴",uuarr:"⇈",Uuml:"Ü",uuml:"ü",uwangle:"⦧",vangrt:"⦜",varepsilon:"ϵ",varkappa:"ϰ",varnothing:"∅",varphi:"ϕ",varpi:"ϖ",varpropto:"∝",vArr:"⇕",varr:"↕",varrho:"ϱ",varsigma:"ς",varsubsetneq:"⊊︀",varsubsetneqq:"⫋︀",varsupsetneq:"⊋︀",varsupsetneqq:"⫌︀",vartheta:"ϑ",vartriangleleft:"⊲",vartriangleright:"⊳",Vbar:"⫫",vBar:"⫨",vBarv:"⫩",Vcy:"В",vcy:"в",VDash:"⊫",Vdash:"⊩",vDash:"⊨",vdash:"⊢",Vdashl:"⫦",Vee:"⋁",vee:"∨",veebar:"⊻",veeeq:"≚",vellip:"⋮",Verbar:"‖",verbar:"|",Vert:"‖",vert:"|",VerticalBar:"∣",VerticalLine:"|",VerticalSeparator:"❘",VerticalTilde:"≀",VeryThinSpace:" ",Vfr:"𝔙",vfr:"𝔳",vltri:"⊲",vnsub:"⊂⃒",vnsup:"⊃⃒",Vopf:"𝕍",vopf:"𝕧",vprop:"∝",vrtri:"⊳",Vscr:"𝒱",vscr:"𝓋",vsubnE:"⫋︀",vsubne:"⊊︀",vsupnE:"⫌︀",vsupne:"⊋︀",Vvdash:"⊪",vzigzag:"⦚",Wcirc:"Ŵ",wcirc:"ŵ",wedbar:"⩟",Wedge:"⋀",wedge:"∧",wedgeq:"≙",weierp:"℘",Wfr:"𝔚",wfr:"𝔴",Wopf:"𝕎",wopf:"𝕨",wp:"℘",wr:"≀",wreath:"≀",Wscr:"𝒲",wscr:"𝓌",xcap:"⋂",xcirc:"◯",xcup:"⋃",xdtri:"▽",Xfr:"𝔛",xfr:"𝔵",xhArr:"⟺",xharr:"⟷",Xi:"Ξ",xi:"ξ",xlArr:"⟸",xlarr:"⟵",xmap:"⟼",xnis:"⋻",xodot:"⨀",Xopf:"𝕏",xopf:"𝕩",xoplus:"⨁",xotime:"⨂",xrArr:"⟹",xrarr:"⟶",Xscr:"𝒳",xscr:"𝓍",xsqcup:"⨆",xuplus:"⨄",xutri:"△",xvee:"⋁",xwedge:"⋀",Yacute:"Ý",yacute:"ý",YAcy:"Я",yacy:"я",Ycirc:"Ŷ",ycirc:"ŷ",Ycy:"Ы",ycy:"ы",yen:"¥",Yfr:"𝔜",yfr:"𝔶",YIcy:"Ї",yicy:"ї",Yopf:"𝕐",yopf:"𝕪",Yscr:"𝒴",yscr:"𝓎",YUcy:"Ю",yucy:"ю",Yuml:"Ÿ",yuml:"ÿ",Zacute:"Ź",zacute:"ź",Zcaron:"Ž",zcaron:"ž",Zcy:"З",zcy:"з",Zdot:"Ż",zdot:"ż",zeetrf:"ℨ",ZeroWidthSpace:"​",Zeta:"Ζ",zeta:"ζ",Zfr:"ℨ",zfr:"𝔷",ZHcy:"Ж",zhcy:"ж",zigrarr:"⇝",Zopf:"ℤ",zopf:"𝕫",Zscr:"𝒵",zscr:"𝓏",zwj:"‍",zwnj:"‌"}),s.entityMap=s.HTML_ENTITIES})(Oy)),Oy}var dm={},rE;function yP(){if(rE)return dm;rE=1;var s=Gp().NAMESPACE,e=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,t=new RegExp("[\\-\\.0-9"+e.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),i=new RegExp("^"+e.source+t.source+"*(?::"+e.source+t.source+"*)?$"),n=0,r=1,o=2,u=3,c=4,d=5,f=6,p=7;function g(N,O){this.message=N,this.locator=O,Error.captureStackTrace&&Error.captureStackTrace(this,g)}g.prototype=new Error,g.prototype.name=g.name;function v(){}v.prototype={parse:function(N,O,K){var Q=this.domBuilder;Q.startDocument(),P(O,O={}),b(N,O,K,Q,this.errorHandler),Q.endDocument()}};function b(N,O,K,Q,W){function re(Dt){if(Dt>65535){Dt-=65536;var ge=55296+(Dt>>10),st=56320+(Dt&1023);return String.fromCharCode(ge,st)}else return String.fromCharCode(Dt)}function J(Dt){var ge=Dt.slice(1,-1);return Object.hasOwnProperty.call(K,ge)?K[ge]:ge.charAt(0)==="#"?re(parseInt(ge.substr(1).replace("x","0x"))):(W.error("entity not found:"+Dt),Dt)}function Y(Dt){if(Dt>Te){var ge=N.substring(Te,Dt).replace(/&#?\w+;/g,J);j&&z(Te),Q.characters(ge,0,Dt-Te),Te=Dt}}function z(Dt,ge){for(;Dt>=ie&&(ge=ce.exec(N));)Z=ge.index,ie=Z+ge[0].length,j.lineNumber++;j.columnNumber=Dt-Z+1}for(var Z=0,ie=0,ce=/.*(?:\r\n?|\n)|.*$/g,j=Q.locator,ee=[{currentNSMap:O}],he={},Te=0;;){try{var xe=N.indexOf("<",Te);if(xe<0){if(!N.substr(Te).match(/^\s*$/)){var Ae=Q.doc,Ke=Ae.createTextNode(N.substr(Te));Ae.appendChild(Ke),Q.currentElement=Ke}return}switch(xe>Te&&Y(xe),N.charAt(xe+1)){case"/":var Ze=N.indexOf(">",xe+3),lt=N.substring(xe+2,Ze).replace(/[ \t\n\r]+$/g,""),nt=ee.pop();Ze<0?(lt=N.substring(xe+2).replace(/[\s<].*/,""),W.error("end tag name: "+lt+" is not complete:"+nt.tagName),Ze=xe+1+lt.length):lt.match(/\sTe?Te=Ze:Y(Math.max(xe,Te)+1)}}function _(N,O){return O.lineNumber=N.lineNumber,O.columnNumber=N.columnNumber,O}function S(N,O,K,Q,W,re){function J(j,ee,he){K.attributeNames.hasOwnProperty(j)&&re.fatalError("Attribute "+j+" redefined"),K.addValue(j,ee.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,W),he)}for(var Y,z,Z=++O,ie=n;;){var ce=N.charAt(Z);switch(ce){case"=":if(ie===r)Y=N.slice(O,Z),ie=u;else if(ie===o)ie=u;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(ie===u||ie===r)if(ie===r&&(re.warning('attribute value must after "="'),Y=N.slice(O,Z)),O=Z+1,Z=N.indexOf(ce,O),Z>0)z=N.slice(O,Z),J(Y,z,O-1),ie=d;else throw new Error("attribute value no end '"+ce+"' match");else if(ie==c)z=N.slice(O,Z),J(Y,z,O),re.warning('attribute "'+Y+'" missed start quot('+ce+")!!"),O=Z+1,ie=d;else throw new Error('attribute value must after "="');break;case"/":switch(ie){case n:K.setTagName(N.slice(O,Z));case d:case f:case p:ie=p,K.closed=!0;case c:case r:break;case o:K.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return re.error("unexpected end of input"),ie==n&&K.setTagName(N.slice(O,Z)),Z;case">":switch(ie){case n:K.setTagName(N.slice(O,Z));case d:case f:case p:break;case c:case r:z=N.slice(O,Z),z.slice(-1)==="/"&&(K.closed=!0,z=z.slice(0,-1));case o:ie===o&&(z=Y),ie==c?(re.warning('attribute "'+z+'" missed quot(")!'),J(Y,z,O)):((!s.isHTML(Q[""])||!z.match(/^(?:disabled|checked|selected)$/i))&&re.warning('attribute "'+z+'" missed value!! "'+z+'" instead!!'),J(z,z,O));break;case u:throw new Error("attribute value missed!!")}return Z;case"€":ce=" ";default:if(ce<=" ")switch(ie){case n:K.setTagName(N.slice(O,Z)),ie=f;break;case r:Y=N.slice(O,Z),ie=o;break;case c:var z=N.slice(O,Z);re.warning('attribute "'+z+'" missed quot(")!!'),J(Y,z,O);case d:ie=f;break}else switch(ie){case o:K.tagName,(!s.isHTML(Q[""])||!Y.match(/^(?:disabled|checked|selected)$/i))&&re.warning('attribute "'+Y+'" missed value!! "'+Y+'" instead2!!'),J(Y,Y,O),O=Z,ie=r;break;case d:re.warning('attribute space is required"'+Y+'"!!');case f:ie=r,O=Z;break;case u:ie=c,O=Z;break;case p:throw new Error("elements closed character '/' and '>' must be connected to")}}Z++}}function D(N,O,K){for(var Q=N.tagName,W=null,ce=N.length;ce--;){var re=N[ce],J=re.qName,Y=re.value,j=J.indexOf(":");if(j>0)var z=re.prefix=J.slice(0,j),Z=J.slice(j+1),ie=z==="xmlns"&&Z;else Z=J,z=null,ie=J==="xmlns"&&"";re.localName=Z,ie!==!1&&(W==null&&(W={},P(K,K={})),K[ie]=W[ie]=Y,re.uri=s.XMLNS,O.startPrefixMapping(ie,Y))}for(var ce=N.length;ce--;){re=N[ce];var z=re.prefix;z&&(z==="xml"&&(re.uri=s.XML),z!=="xmlns"&&(re.uri=K[z||""]))}var j=Q.indexOf(":");j>0?(z=N.prefix=Q.slice(0,j),Z=N.localName=Q.slice(j+1)):(z=null,Z=N.localName=Q);var ee=N.uri=K[z||""];if(O.startElement(ee,Z,Q,N),N.closed){if(O.endElement(ee,Z,Q),W)for(z in W)Object.prototype.hasOwnProperty.call(W,z)&&O.endPrefixMapping(z)}else return N.currentNSMap=K,N.localNSMap=W,!0}function R(N,O,K,Q,W){if(/^(?:script|textarea)$/i.test(K)){var re=N.indexOf("",O),J=N.substring(O+1,re);if(/[&<]/.test(J))return/^script$/i.test(K)?(W.characters(J,0,J.length),re):(J=J.replace(/&#?\w+;/g,Q),W.characters(J,0,J.length),re)}return O+1}function L(N,O,K,Q){var W=Q[K];return W==null&&(W=N.lastIndexOf(""),W",O+4);return re>O?(K.comment(N,O+4,re-O-4),re+3):(Q.error("Unclosed comment"),-1)}else return-1;default:if(N.substr(O+3,6)=="CDATA["){var re=N.indexOf("]]>",O+9);return K.startCDATA(),K.characters(N,O+9,re-O-9),K.endCDATA(),re+3}var J=G(N,O),Y=J.length;if(Y>1&&/!doctype/i.test(J[0][0])){var z=J[1][0],Z=!1,ie=!1;Y>3&&(/^public$/i.test(J[2][0])?(Z=J[3][0],ie=Y>4&&J[4][0]):/^system$/i.test(J[2][0])&&(ie=J[3][0]));var ce=J[Y-1];return K.startDTD(z,Z,ie),K.endDTD(),ce.index+ce[0].length}}return-1}function V(N,O,K){var Q=N.indexOf("?>",O);if(Q){var W=N.substring(O,Q).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);return W?(W[0].length,K.processingInstruction(W[1],W[2]),Q+2):-1}return-1}function M(){this.attributeNames={}}M.prototype={setTagName:function(N){if(!i.test(N))throw new Error("invalid tagName:"+N);this.tagName=N},addValue:function(N,O,K){if(!i.test(N))throw new Error("invalid attribute:"+N);this.attributeNames[N]=this.length,this[this.length++]={qName:N,value:O,offset:K}},length:0,getLocalName:function(N){return this[N].localName},getLocator:function(N){return this[N].locator},getQName:function(N){return this[N].qName},getURI:function(N){return this[N].uri},getValue:function(N){return this[N].value}};function G(N,O){var K,Q=[],W=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(W.lastIndex=O,W.exec(N);K=W.exec(N);)if(Q.push(K),K[1])return Q}return dm.XMLReader=v,dm.ParseError=g,dm}var aE;function vP(){if(aE)return Gd;aE=1;var s=Gp(),e=GA(),t=gP(),i=yP(),n=e.DOMImplementation,r=s.NAMESPACE,o=i.ParseError,u=i.XMLReader;function c(S){return S.replace(/\r[\n\u0085]/g,` `).replace(/[\r\u0085\u2028]/g,` `)}function d(S){this.options=S||{locator:{}}}d.prototype.parseFromString=function(S,D){var R=this.options,L=new u,P=R.domBuilder||new p,U=R.errorHandler,V=R.locator,M=R.xmlns||{},G=/\/x?html?$/.test(D),N=G?t.HTML_ENTITIES:t.XML_ENTITIES;V&&P.setDocumentLocator(V),L.errorHandler=f(U,P,V),L.domBuilder=R.domBuilder||P,G&&(M[""]=r.HTML),M.xml=M.xml||r.XML;var O=R.normalizeLineEndings||c;return S&&typeof S=="string"?L.parse(O(S),M,N):L.errorHandler.error("invalid doc source"),P.doc};function f(S,D,R){if(!S){if(D instanceof p)return D;S=D}var L={},P=S instanceof Function;R=R||{};function U(V){var M=S[V];!M&&P&&(M=S.length==2?function(G){S(V,G)}:S),L[V]=M&&function(G){M("[xmldom "+V+"] "+G+v(R))}||function(){}}return U("warning"),U("error"),U("fatalError"),L}function p(){this.cdata=!1}function g(S,D){D.lineNumber=S.lineNumber,D.columnNumber=S.columnNumber}p.prototype={startDocument:function(){this.doc=new n().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(S,D,R,L){var P=this.doc,U=P.createElementNS(S,R||D),V=L.length;_(this,U),this.currentElement=U,this.locator&&g(this.locator,U);for(var M=0;M=D+R||D?new java.lang.String(S,D,R)+"":S}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(S){p.prototype[S]=function(){return null}});function _(S,D){S.currentElement?S.currentElement.appendChild(D):S.doc.appendChild(D)}return Gd.__DOMHandler=p,Gd.normalizeLineEndings=c,Gd.DOMParser=d,Gd}var oE;function xP(){if(oE)return Vd;oE=1;var s=GA();return Vd.DOMImplementation=s.DOMImplementation,Vd.XMLSerializer=s.XMLSerializer,Vd.DOMParser=vP().DOMParser,Vd}var bP=xP();const lE=s=>!!s&&typeof s=="object",Qs=(...s)=>s.reduce((e,t)=>(typeof t!="object"||Object.keys(t).forEach(i=>{Array.isArray(e[i])&&Array.isArray(t[i])?e[i]=e[i].concat(t[i]):lE(e[i])&&lE(t[i])?e[i]=Qs(e[i],t[i]):e[i]=t[i]}),e),{}),zA=s=>Object.keys(s).map(e=>s[e]),TP=(s,e)=>{const t=[];for(let i=s;is.reduce((e,t)=>e.concat(t),[]),qA=s=>{if(!s.length)return[];const e=[];for(let t=0;ts.reduce((t,i,n)=>(i[e]&&t.push(n),t),[]),SP=(s,e)=>zA(s.reduce((t,i)=>(i.forEach(n=>{t[e(n)]=n}),t),{}));var wc={INVALID_NUMBER_OF_PERIOD:"INVALID_NUMBER_OF_PERIOD",DASH_EMPTY_MANIFEST:"DASH_EMPTY_MANIFEST",DASH_INVALID_XML:"DASH_INVALID_XML",NO_BASE_URL:"NO_BASE_URL",SEGMENT_TIME_UNSPECIFIED:"SEGMENT_TIME_UNSPECIFIED",UNSUPPORTED_UTC_TIMING_SCHEME:"UNSUPPORTED_UTC_TIMING_SCHEME"};const vh=({baseUrl:s="",source:e="",range:t="",indexRange:i=""})=>{const n={uri:e,resolvedUri:Vp(s||"",e)};if(t||i){const o=(t||i).split("-");let u=de.BigInt?de.BigInt(o[0]):parseInt(o[0],10),c=de.BigInt?de.BigInt(o[1]):parseInt(o[1],10);u{let e;return typeof s.offset=="bigint"||typeof s.length=="bigint"?e=de.BigInt(s.offset)+de.BigInt(s.length)-de.BigInt(1):e=s.offset+s.length-1,`${s.offset}-${e}`},uE=s=>(s&&typeof s!="number"&&(s=parseInt(s,10)),isNaN(s)?null:s),wP={static(s){const{duration:e,timescale:t=1,sourceDuration:i,periodDuration:n}=s,r=uE(s.endNumber),o=e/t;return typeof r=="number"?{start:0,end:r}:typeof n=="number"?{start:0,end:n/o}:{start:0,end:i/o}},dynamic(s){const{NOW:e,clientOffset:t,availabilityStartTime:i,timescale:n=1,duration:r,periodStart:o=0,minimumUpdatePeriod:u=0,timeShiftBufferDepth:c=1/0}=s,d=uE(s.endNumber),f=(e+t)/1e3,p=i+o,v=f+u-p,b=Math.ceil(v*n/r),_=Math.floor((f-p-c)*n/r),S=Math.floor((f-p)*n/r);return{start:Math.max(0,_),end:typeof d=="number"?d:Math.min(b,S)}}},AP=s=>e=>{const{duration:t,timescale:i=1,periodStart:n,startNumber:r=1}=s;return{number:r+e,duration:t/i,timeline:n,time:e*t}},Xx=s=>{const{type:e,duration:t,timescale:i=1,periodDuration:n,sourceDuration:r}=s,{start:o,end:u}=wP[e](s),c=TP(o,u).map(AP(s));if(e==="static"){const d=c.length-1,f=typeof n=="number"?n:r;c[d].duration=f-t/i*d}return c},KA=s=>{const{baseUrl:e,initialization:t={},sourceDuration:i,indexRange:n="",periodStart:r,presentationTime:o,number:u=0,duration:c}=s;if(!e)throw new Error(wc.NO_BASE_URL);const d=vh({baseUrl:e,source:t.sourceURL,range:t.range}),f=vh({baseUrl:e,source:e,indexRange:n});if(f.map=d,c){const p=Xx(s);p.length&&(f.duration=p[0].duration,f.timeline=p[0].timeline)}else i&&(f.duration=i,f.timeline=r);return f.presentationTime=o||r,f.number=u,[f]},Qx=(s,e,t)=>{const i=s.sidx.map?s.sidx.map:null,n=s.sidx.duration,r=s.timeline||0,o=s.sidx.byterange,u=o.offset+o.length,c=e.timescale,d=e.references.filter(S=>S.referenceType!==1),f=[],p=s.endList?"static":"dynamic",g=s.sidx.timeline;let v=g,b=s.mediaSequence||0,_;typeof e.firstOffset=="bigint"?_=de.BigInt(u)+e.firstOffset:_=u+e.firstOffset;for(let S=0;SSP(s,({timeline:e})=>e).sort((e,t)=>e.timeline>t.timeline?1:-1),DP=(s,e)=>{for(let t=0;t{let e=[];return pP(s,CP,(t,i,n,r)=>{e=e.concat(t.playlists||[])}),e},dE=({playlist:s,mediaSequence:e})=>{s.mediaSequence=e,s.segments.forEach((t,i)=>{t.number=s.mediaSequence+i})},LP=({oldPlaylists:s,newPlaylists:e,timelineStarts:t})=>{e.forEach(i=>{i.discontinuitySequence=t.findIndex(function({timeline:c}){return c===i.timeline});const n=DP(s,i.attributes.NAME);if(!n||i.sidx)return;const r=i.segments[0],o=n.segments.findIndex(function(c){return Math.abs(c.presentationTime-r.presentationTime)n.timeline||n.segments.length&&i.timeline>n.segments[n.segments.length-1].timeline)&&i.discontinuitySequence--;return}n.segments[o].discontinuity&&!r.discontinuity&&(r.discontinuity=!0,i.discontinuityStarts.unshift(0),i.discontinuitySequence--),dE({playlist:i,mediaSequence:n.segments[o].number})})},RP=({oldManifest:s,newManifest:e})=>{const t=s.playlists.concat(cE(s)),i=e.playlists.concat(cE(e));return e.timelineStarts=YA([s.timelineStarts,e.timelineStarts]),LP({oldPlaylists:t,newPlaylists:i,timelineStarts:e.timelineStarts}),e},zp=s=>s&&s.uri+"-"+EP(s.byterange),My=s=>{const e=s.reduce(function(i,n){return i[n.attributes.baseUrl]||(i[n.attributes.baseUrl]=[]),i[n.attributes.baseUrl].push(n),i},{});let t=[];return Object.values(e).forEach(i=>{const n=zA(i.reduce((r,o)=>{const u=o.attributes.id+(o.attributes.lang||"");return r[u]?(o.segments&&(o.segments[0]&&(o.segments[0].discontinuity=!0),r[u].segments.push(...o.segments)),o.attributes.contentProtection&&(r[u].attributes.contentProtection=o.attributes.contentProtection)):(r[u]=o,r[u].attributes.timelineStarts=[]),r[u].attributes.timelineStarts.push({start:o.attributes.periodStart,timeline:o.attributes.periodStart}),r},{}));t=t.concat(n)}),t.map(i=>(i.discontinuityStarts=_P(i.segments||[],"discontinuity"),i))},Zx=(s,e)=>{const t=zp(s.sidx),i=t&&e[t]&&e[t].sidx;return i&&Qx(s,i,s.sidx.resolvedUri),s},IP=(s,e={})=>{if(!Object.keys(e).length)return s;for(const t in s)s[t]=Zx(s[t],e);return s},NP=({attributes:s,segments:e,sidx:t,mediaSequence:i,discontinuitySequence:n,discontinuityStarts:r},o)=>{const u={attributes:{NAME:s.id,BANDWIDTH:s.bandwidth,CODECS:s.codecs,"PROGRAM-ID":1},uri:"",endList:s.type==="static",timeline:s.periodStart,resolvedUri:s.baseUrl||"",targetDuration:s.duration,discontinuitySequence:n,discontinuityStarts:r,timelineStarts:s.timelineStarts,mediaSequence:i,segments:e};return s.contentProtection&&(u.contentProtection=s.contentProtection),s.serviceLocation&&(u.attributes.serviceLocation=s.serviceLocation),t&&(u.sidx=t),o&&(u.attributes.AUDIO="audio",u.attributes.SUBTITLES="subs"),u},OP=({attributes:s,segments:e,mediaSequence:t,discontinuityStarts:i,discontinuitySequence:n})=>{typeof e>"u"&&(e=[{uri:s.baseUrl,timeline:s.periodStart,resolvedUri:s.baseUrl||"",duration:s.sourceDuration,number:0}],s.duration=s.sourceDuration);const r={NAME:s.id,BANDWIDTH:s.bandwidth,"PROGRAM-ID":1};s.codecs&&(r.CODECS=s.codecs);const o={attributes:r,uri:"",endList:s.type==="static",timeline:s.periodStart,resolvedUri:s.baseUrl||"",targetDuration:s.duration,timelineStarts:s.timelineStarts,discontinuityStarts:i,discontinuitySequence:n,mediaSequence:t,segments:e};return s.serviceLocation&&(o.attributes.serviceLocation=s.serviceLocation),o},MP=(s,e={},t=!1)=>{let i;const n=s.reduce((r,o)=>{const u=o.attributes.role&&o.attributes.role.value||"",c=o.attributes.lang||"";let d=o.attributes.label||"main";if(c&&!o.attributes.label){const p=u?` (${u})`:"";d=`${o.attributes.lang}${p}`}r[d]||(r[d]={language:c,autoselect:!0,default:u==="main",playlists:[],uri:""});const f=Zx(NP(o,t),e);return r[d].playlists.push(f),typeof i>"u"&&u==="main"&&(i=o,i.default=!0),r},{});if(!i){const r=Object.keys(n)[0];n[r].default=!0}return n},PP=(s,e={})=>s.reduce((t,i)=>{const n=i.attributes.label||i.attributes.lang||"text",r=i.attributes.lang||"und";return t[n]||(t[n]={language:r,default:!1,autoselect:!1,playlists:[],uri:""}),t[n].playlists.push(Zx(OP(i),e)),t},{}),BP=s=>s.reduce((e,t)=>(t&&t.forEach(i=>{const{channel:n,language:r}=i;e[r]={autoselect:!1,default:!1,instreamId:n,language:r},i.hasOwnProperty("aspectRatio")&&(e[r].aspectRatio=i.aspectRatio),i.hasOwnProperty("easyReader")&&(e[r].easyReader=i.easyReader),i.hasOwnProperty("3D")&&(e[r]["3D"]=i["3D"])}),e),{}),FP=({attributes:s,segments:e,sidx:t,discontinuityStarts:i})=>{const n={attributes:{NAME:s.id,AUDIO:"audio",SUBTITLES:"subs",RESOLUTION:{width:s.width,height:s.height},CODECS:s.codecs,BANDWIDTH:s.bandwidth,"PROGRAM-ID":1},uri:"",endList:s.type==="static",timeline:s.periodStart,resolvedUri:s.baseUrl||"",targetDuration:s.duration,discontinuityStarts:i,timelineStarts:s.timelineStarts,segments:e};return s.frameRate&&(n.attributes["FRAME-RATE"]=s.frameRate),s.contentProtection&&(n.contentProtection=s.contentProtection),s.serviceLocation&&(n.attributes.serviceLocation=s.serviceLocation),t&&(n.sidx=t),n},UP=({attributes:s})=>s.mimeType==="video/mp4"||s.mimeType==="video/webm"||s.contentType==="video",jP=({attributes:s})=>s.mimeType==="audio/mp4"||s.mimeType==="audio/webm"||s.contentType==="audio",$P=({attributes:s})=>s.mimeType==="text/vtt"||s.contentType==="text",HP=(s,e)=>{s.forEach(t=>{t.mediaSequence=0,t.discontinuitySequence=e.findIndex(function({timeline:i}){return i===t.timeline}),t.segments&&t.segments.forEach((i,n)=>{i.number=n})})},hE=s=>s?Object.keys(s).reduce((e,t)=>{const i=s[t];return e.concat(i.playlists)},[]):[],VP=({dashPlaylists:s,locations:e,contentSteering:t,sidxMapping:i={},previousManifest:n,eventStream:r})=>{if(!s.length)return{};const{sourceDuration:o,type:u,suggestedPresentationDelay:c,minimumUpdatePeriod:d}=s[0].attributes,f=My(s.filter(UP)).map(FP),p=My(s.filter(jP)),g=My(s.filter($P)),v=s.map(P=>P.attributes.captionServices).filter(Boolean),b={allowCache:!0,discontinuityStarts:[],segments:[],endList:!0,mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:"",duration:o,playlists:IP(f,i)};d>=0&&(b.minimumUpdatePeriod=d*1e3),e&&(b.locations=e),t&&(b.contentSteering=t),u==="dynamic"&&(b.suggestedPresentationDelay=c),r&&r.length>0&&(b.eventStream=r);const _=b.playlists.length===0,S=p.length?MP(p,i,_):null,D=g.length?PP(g,i):null,R=f.concat(hE(S),hE(D)),L=R.map(({timelineStarts:P})=>P);return b.timelineStarts=YA(L),HP(R,b.timelineStarts),S&&(b.mediaGroups.AUDIO.audio=S),D&&(b.mediaGroups.SUBTITLES.subs=D),v.length&&(b.mediaGroups["CLOSED-CAPTIONS"].cc=BP(v)),n?RP({oldManifest:n,newManifest:b}):b},GP=(s,e,t)=>{const{NOW:i,clientOffset:n,availabilityStartTime:r,timescale:o=1,periodStart:u=0,minimumUpdatePeriod:c=0}=s,d=(i+n)/1e3,f=r+u,g=d+c-f;return Math.ceil((g*o-e)/t)},WA=(s,e)=>{const{type:t,minimumUpdatePeriod:i=0,media:n="",sourceDuration:r,timescale:o=1,startNumber:u=1,periodStart:c}=s,d=[];let f=-1;for(let p=0;pf&&(f=_);let S;if(b<0){const L=p+1;L===e.length?t==="dynamic"&&i>0&&n.indexOf("$Number$")>0?S=GP(s,f,v):S=(r*o-f)/v:S=(e[L].t-f)/v}else S=b+1;const D=u+d.length+S;let R=u+d.length;for(;R(e,t,i,n)=>{if(e==="$$")return"$";if(typeof s[t]>"u")return e;const r=""+s[t];return t==="RepresentationID"||(i?n=parseInt(n,10):n=1,r.length>=n)?r:`${new Array(n-r.length+1).join("0")}${r}`},fE=(s,e)=>s.replace(zP,qP(e)),KP=(s,e)=>!s.duration&&!e?[{number:s.startNumber||1,duration:s.sourceDuration,time:0,timeline:s.periodStart}]:s.duration?Xx(s):WA(s,e),YP=(s,e)=>{const t={RepresentationID:s.id,Bandwidth:s.bandwidth||0},{initialization:i={sourceURL:"",range:""}}=s,n=vh({baseUrl:s.baseUrl,source:fE(i.sourceURL,t),range:i.range});return KP(s,e).map(o=>{t.Number=o.number,t.Time=o.time;const u=fE(s.media||"",t),c=s.timescale||1,d=s.presentationTimeOffset||0,f=s.periodStart+(o.time-d)/c;return{uri:u,timeline:o.timeline,duration:o.duration,resolvedUri:Vp(s.baseUrl||"",u),map:n,number:o.number,presentationTime:f}})},WP=(s,e)=>{const{baseUrl:t,initialization:i={}}=s,n=vh({baseUrl:t,source:i.sourceURL,range:i.range}),r=vh({baseUrl:t,source:e.media,range:e.mediaRange});return r.map=n,r},XP=(s,e)=>{const{duration:t,segmentUrls:i=[],periodStart:n}=s;if(!t&&!e||t&&e)throw new Error(wc.SEGMENT_TIME_UNSPECIFIED);const r=i.map(c=>WP(s,c));let o;return t&&(o=Xx(s)),e&&(o=WA(s,e)),o.map((c,d)=>{if(r[d]){const f=r[d],p=s.timescale||1,g=s.presentationTimeOffset||0;return f.timeline=c.timeline,f.duration=c.duration,f.number=c.number,f.presentationTime=n+(c.time-g)/p,f}}).filter(c=>c)},QP=({attributes:s,segmentInfo:e})=>{let t,i;e.template?(i=YP,t=Qs(s,e.template)):e.base?(i=KA,t=Qs(s,e.base)):e.list&&(i=XP,t=Qs(s,e.list));const n={attributes:s};if(!i)return n;const r=i(t,e.segmentTimeline);if(t.duration){const{duration:o,timescale:u=1}=t;t.duration=o/u}else r.length?t.duration=r.reduce((o,u)=>Math.max(o,Math.ceil(u.duration)),0):t.duration=0;return n.attributes=t,n.segments=r,e.base&&t.indexRange&&(n.sidx=r[0],n.segments=[]),n},ZP=s=>s.map(QP),ls=(s,e)=>qA(s.childNodes).filter(({tagName:t})=>t===e),Nh=s=>s.textContent.trim(),JP=s=>parseFloat(s.split("/").reduce((e,t)=>e/t)),Vu=s=>{const u=/P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/.exec(s);if(!u)return 0;const[c,d,f,p,g,v]=u.slice(1);return parseFloat(c||0)*31536e3+parseFloat(d||0)*2592e3+parseFloat(f||0)*86400+parseFloat(p||0)*3600+parseFloat(g||0)*60+parseFloat(v||0)},e3=s=>(/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(s)&&(s+="Z"),Date.parse(s)),mE={mediaPresentationDuration(s){return Vu(s)},availabilityStartTime(s){return e3(s)/1e3},minimumUpdatePeriod(s){return Vu(s)},suggestedPresentationDelay(s){return Vu(s)},type(s){return s},timeShiftBufferDepth(s){return Vu(s)},start(s){return Vu(s)},width(s){return parseInt(s,10)},height(s){return parseInt(s,10)},bandwidth(s){return parseInt(s,10)},frameRate(s){return JP(s)},startNumber(s){return parseInt(s,10)},timescale(s){return parseInt(s,10)},presentationTimeOffset(s){return parseInt(s,10)},duration(s){const e=parseInt(s,10);return isNaN(e)?Vu(s):e},d(s){return parseInt(s,10)},t(s){return parseInt(s,10)},r(s){return parseInt(s,10)},presentationTime(s){return parseInt(s,10)},DEFAULT(s){return s}},Is=s=>s&&s.attributes?qA(s.attributes).reduce((e,t)=>{const i=mE[t.name]||mE.DEFAULT;return e[t.name]=i(t.value),e},{}):{},t3={"urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b":"org.w3.clearkey","urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed":"com.widevine.alpha","urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95":"com.microsoft.playready","urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb":"com.adobe.primetime","urn:mpeg:dash:mp4protection:2011":"mp4protection"},qp=(s,e)=>e.length?Ec(s.map(function(t){return e.map(function(i){const n=Nh(i),r=Vp(t.baseUrl,n),o=Qs(Is(i),{baseUrl:r});return r!==n&&!o.serviceLocation&&t.serviceLocation&&(o.serviceLocation=t.serviceLocation),o})})):s,Jx=s=>{const e=ls(s,"SegmentTemplate")[0],t=ls(s,"SegmentList")[0],i=t&&ls(t,"SegmentURL").map(p=>Qs({tag:"SegmentURL"},Is(p))),n=ls(s,"SegmentBase")[0],r=t||e,o=r&&ls(r,"SegmentTimeline")[0],u=t||n||e,c=u&&ls(u,"Initialization")[0],d=e&&Is(e);d&&c?d.initialization=c&&Is(c):d&&d.initialization&&(d.initialization={sourceURL:d.initialization});const f={template:d,segmentTimeline:o&&ls(o,"S").map(p=>Is(p)),list:t&&Qs(Is(t),{segmentUrls:i,initialization:Is(c)}),base:n&&Qs(Is(n),{initialization:Is(c)})};return Object.keys(f).forEach(p=>{f[p]||delete f[p]}),f},i3=(s,e,t)=>i=>{const n=ls(i,"BaseURL"),r=qp(e,n),o=Qs(s,Is(i)),u=Jx(i);return r.map(c=>({segmentInfo:Qs(t,u),attributes:Qs(o,c)}))},s3=s=>s.reduce((e,t)=>{const i=Is(t);i.schemeIdUri&&(i.schemeIdUri=i.schemeIdUri.toLowerCase());const n=t3[i.schemeIdUri];if(n){e[n]={attributes:i};const r=ls(t,"cenc:pssh")[0];if(r){const o=Nh(r);e[n].pssh=o&&FA(o)}}return e},{}),n3=s=>{if(s.schemeIdUri==="urn:scte:dash:cc:cea-608:2015")return(typeof s.value!="string"?[]:s.value.split(";")).map(t=>{let i,n;return n=t,/^CC\d=/.test(t)?[i,n]=t.split("="):/^CC\d$/.test(t)&&(i=t),{channel:i,language:n}});if(s.schemeIdUri==="urn:scte:dash:cc:cea-708:2015")return(typeof s.value!="string"?[]:s.value.split(";")).map(t=>{const i={channel:void 0,language:void 0,aspectRatio:1,easyReader:0,"3D":0};if(/=/.test(t)){const[n,r=""]=t.split("=");i.channel=n,i.language=t,r.split(",").forEach(o=>{const[u,c]=o.split(":");u==="lang"?i.language=c:u==="er"?i.easyReader=Number(c):u==="war"?i.aspectRatio=Number(c):u==="3D"&&(i["3D"]=Number(c))})}else i.language=t;return i.channel&&(i.channel="SERVICE"+i.channel),i})},r3=s=>Ec(ls(s.node,"EventStream").map(e=>{const t=Is(e),i=t.schemeIdUri;return ls(e,"Event").map(n=>{const r=Is(n),o=r.presentationTime||0,u=t.timescale||1,c=r.duration||0,d=o/u+s.attributes.start;return{schemeIdUri:i,value:t.value,id:r.id,start:d,end:d+c/u,messageData:Nh(n)||r.messageData,contentEncoding:t.contentEncoding,presentationTimeOffset:t.presentationTimeOffset||0}})})),a3=(s,e,t)=>i=>{const n=Is(i),r=qp(e,ls(i,"BaseURL")),o=ls(i,"Role")[0],u={role:Is(o)};let c=Qs(s,n,u);const d=ls(i,"Accessibility")[0],f=n3(Is(d));f&&(c=Qs(c,{captionServices:f}));const p=ls(i,"Label")[0];if(p&&p.childNodes.length){const S=p.childNodes[0].nodeValue.trim();c=Qs(c,{label:S})}const g=s3(ls(i,"ContentProtection"));Object.keys(g).length&&(c=Qs(c,{contentProtection:g}));const v=Jx(i),b=ls(i,"Representation"),_=Qs(t,v);return Ec(b.map(i3(c,r,_)))},o3=(s,e)=>(t,i)=>{const n=qp(e,ls(t.node,"BaseURL")),r=Qs(s,{periodStart:t.attributes.start});typeof t.attributes.duration=="number"&&(r.periodDuration=t.attributes.duration);const o=ls(t.node,"AdaptationSet"),u=Jx(t.node);return Ec(o.map(a3(r,n,u)))},l3=(s,e)=>{if(s.length>1&&e({type:"warn",message:"The MPD manifest should contain no more than one ContentSteering tag"}),!s.length)return null;const t=Qs({serverURL:Nh(s[0])},Is(s[0]));return t.queryBeforeStart=t.queryBeforeStart==="true",t},u3=({attributes:s,priorPeriodAttributes:e,mpdType:t})=>typeof s.start=="number"?s.start:e&&typeof e.start=="number"&&typeof e.duration=="number"?e.start+e.duration:!e&&t==="static"?0:null,c3=(s,e={})=>{const{manifestUri:t="",NOW:i=Date.now(),clientOffset:n=0,eventHandler:r=function(){}}=e,o=ls(s,"Period");if(!o.length)throw new Error(wc.INVALID_NUMBER_OF_PERIOD);const u=ls(s,"Location"),c=Is(s),d=qp([{baseUrl:t}],ls(s,"BaseURL")),f=ls(s,"ContentSteering");c.type=c.type||"static",c.sourceDuration=c.mediaPresentationDuration||0,c.NOW=i,c.clientOffset=n,u.length&&(c.locations=u.map(Nh));const p=[];return o.forEach((g,v)=>{const b=Is(g),_=p[v-1];b.start=u3({attributes:b,priorPeriodAttributes:_?_.attributes:null,mpdType:c.type}),p.push({node:g,attributes:b})}),{locations:c.locations,contentSteeringInfo:l3(f,r),representationInfo:Ec(p.map(o3(c,d))),eventStream:Ec(p.map(r3))}},XA=s=>{if(s==="")throw new Error(wc.DASH_EMPTY_MANIFEST);const e=new bP.DOMParser;let t,i;try{t=e.parseFromString(s,"application/xml"),i=t&&t.documentElement.tagName==="MPD"?t.documentElement:null}catch{}if(!i||i&&i.getElementsByTagName("parsererror").length>0)throw new Error(wc.DASH_INVALID_XML);return i},d3=s=>{const e=ls(s,"UTCTiming")[0];if(!e)return null;const t=Is(e);switch(t.schemeIdUri){case"urn:mpeg:dash:utc:http-head:2014":case"urn:mpeg:dash:utc:http-head:2012":t.method="HEAD";break;case"urn:mpeg:dash:utc:http-xsdate:2014":case"urn:mpeg:dash:utc:http-iso:2014":case"urn:mpeg:dash:utc:http-xsdate:2012":case"urn:mpeg:dash:utc:http-iso:2012":t.method="GET";break;case"urn:mpeg:dash:utc:direct:2014":case"urn:mpeg:dash:utc:direct:2012":t.method="DIRECT",t.value=Date.parse(t.value);break;default:throw new Error(wc.UNSUPPORTED_UTC_TIMING_SCHEME)}return t},h3=(s,e={})=>{const t=c3(XA(s),e),i=ZP(t.representationInfo);return VP({dashPlaylists:i,locations:t.locations,contentSteering:t.contentSteeringInfo,sidxMapping:e.sidxMapping,previousManifest:e.previousManifest,eventStream:t.eventStream})},f3=s=>d3(XA(s));var Py,pE;function m3(){if(pE)return Py;pE=1;var s=Math.pow(2,32),e=function(t){var i=new DataView(t.buffer,t.byteOffset,t.byteLength),n;return i.getBigUint64?(n=i.getBigUint64(0),n0;r+=12,o--)n.references.push({referenceType:(t[r]&128)>>>7,referencedSize:i.getUint32(r)&2147483647,subsegmentDuration:i.getUint32(r+4),startsWithSap:!!(t[r+8]&128),sapType:(t[r+8]&112)>>>4,sapDeltaTime:i.getUint32(r+8)&268435455});return n};return By=e,By}var g3=p3();const y3=Mc(g3);var v3=Ht([73,68,51]),x3=function(e,t){t===void 0&&(t=0),e=Ht(e);var i=e[t+5],n=e[t+6]<<21|e[t+7]<<14|e[t+8]<<7|e[t+9],r=(i&16)>>4;return r?n+20:n+10},eh=function s(e,t){return t===void 0&&(t=0),e=Ht(e),e.length-t<10||!os(e,v3,{offset:t})?t:(t+=x3(e,t),s(e,t))},yE=function(e){return typeof e=="string"?VA(e):e},b3=function(e){return Array.isArray(e)?e.map(function(t){return yE(t)}):[yE(e)]},T3=function s(e,t,i){i===void 0&&(i=!1),t=b3(t),e=Ht(e);var n=[];if(!t.length)return n;for(var r=0;r>>0,u=e.subarray(r+4,r+8);if(o===0)break;var c=r+o;if(c>e.length){if(i)break;c=e.length}var d=e.subarray(r+8,c);os(u,t[0])&&(t.length===1?n.push(d):n.push.apply(n,s(d,t.slice(1),i))),r=c}return n},hm={EBML:Ht([26,69,223,163]),DocType:Ht([66,130]),Segment:Ht([24,83,128,103]),SegmentInfo:Ht([21,73,169,102]),Tracks:Ht([22,84,174,107]),Track:Ht([174]),TrackNumber:Ht([215]),DefaultDuration:Ht([35,227,131]),TrackEntry:Ht([174]),TrackType:Ht([131]),FlagDefault:Ht([136]),CodecID:Ht([134]),CodecPrivate:Ht([99,162]),VideoTrack:Ht([224]),AudioTrack:Ht([225]),Cluster:Ht([31,67,182,117]),Timestamp:Ht([231]),TimestampScale:Ht([42,215,177]),BlockGroup:Ht([160]),BlockDuration:Ht([155]),Block:Ht([161]),SimpleBlock:Ht([163])},zv=[128,64,32,16,8,4,2,1],_3=function(e){for(var t=1,i=0;i=t.length)return t.length;var n=ep(t,i,!1);if(os(e.bytes,n.bytes))return i;var r=ep(t,i+n.length);return s(e,t,i+r.length+r.value+n.length)},xE=function s(e,t){t=S3(t),e=Ht(e);var i=[];if(!t.length)return i;for(var n=0;ne.length?e.length:u+o.value,d=e.subarray(u,c);os(t[0],r.bytes)&&(t.length===1?i.push(d):i=i.concat(s(d,t.slice(1))));var f=r.length+o.length+d.length;n+=f}return i},w3=Ht([0,0,0,1]),A3=Ht([0,0,1]),C3=Ht([0,0,3]),k3=function(e){for(var t=[],i=1;i>1&63),i.indexOf(d)!==-1&&(o=r+c),r+=c+(t==="h264"?1:2)}return e.subarray(0,0)},D3=function(e,t,i){return QA(e,"h264",t,i)},L3=function(e,t,i){return QA(e,"h265",t,i)},xn={webm:Ht([119,101,98,109]),matroska:Ht([109,97,116,114,111,115,107,97]),flac:Ht([102,76,97,67]),ogg:Ht([79,103,103,83]),ac3:Ht([11,119]),riff:Ht([82,73,70,70]),avi:Ht([65,86,73]),wav:Ht([87,65,86,69]),"3gp":Ht([102,116,121,112,51,103]),mp4:Ht([102,116,121,112]),fmp4:Ht([115,116,121,112]),mov:Ht([102,116,121,112,113,116]),moov:Ht([109,111,111,118]),moof:Ht([109,111,111,102])},Ac={aac:function(e){var t=eh(e);return os(e,[255,16],{offset:t,mask:[255,22]})},mp3:function(e){var t=eh(e);return os(e,[255,2],{offset:t,mask:[255,6]})},webm:function(e){var t=xE(e,[hm.EBML,hm.DocType])[0];return os(t,xn.webm)},mkv:function(e){var t=xE(e,[hm.EBML,hm.DocType])[0];return os(t,xn.matroska)},mp4:function(e){if(Ac["3gp"](e)||Ac.mov(e))return!1;if(os(e,xn.mp4,{offset:4})||os(e,xn.fmp4,{offset:4})||os(e,xn.moof,{offset:4})||os(e,xn.moov,{offset:4}))return!0},mov:function(e){return os(e,xn.mov,{offset:4})},"3gp":function(e){return os(e,xn["3gp"],{offset:4})},ac3:function(e){var t=eh(e);return os(e,xn.ac3,{offset:t})},ts:function(e){if(e.length<189&&e.length>=1)return e[0]===71;for(var t=0;t+1880},Fy,bE;function N3(){if(bE)return Fy;bE=1;var s=9e4,e,t,i,n,r,o,u;return e=function(c){return c*s},t=function(c,d){return c*d},i=function(c){return c/s},n=function(c,d){return c/d},r=function(c,d){return e(n(c,d))},o=function(c,d){return t(i(c),d)},u=function(c,d,f){return i(f?c:c-d)},Fy={ONE_SECOND_IN_TS:s,secondsToVideoTs:e,secondsToAudioTs:t,videoTsToSeconds:i,audioTsToSeconds:n,audioTsToVideoTs:r,videoTsToAudioTs:o,metadataTsToSeconds:u},Fy}var Wl=N3();var Kv="8.23.4";const Za={},ol=function(s,e){return Za[s]=Za[s]||[],e&&(Za[s]=Za[s].concat(e)),Za[s]},O3=function(s,e){ol(s,e)},ZA=function(s,e){const t=ol(s).indexOf(e);return t<=-1?!1:(Za[s]=Za[s].slice(),Za[s].splice(t,1),!0)},M3=function(s,e){ol(s,[].concat(e).map(t=>{const i=(...n)=>(ZA(s,i),t(...n));return i}))},tp={prefixed:!0},Mm=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror","fullscreen"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror","-webkit-full-screen"]],TE=Mm[0];let th;for(let s=0;s(i,n,r)=>{const o=e.levels[n],u=new RegExp(`^(${o})$`);let c=s;if(i!=="log"&&r.unshift(i.toUpperCase()+":"),t&&(c=`%c${s}`,r.unshift(t)),r.unshift(c+":"),jn){jn.push([].concat(r));const f=jn.length-1e3;jn.splice(0,f>0?f:0)}if(!de.console)return;let d=de.console[i];!d&&i==="debug"&&(d=de.console.info||de.console.log),!(!d||!o||!u.test(i))&&d[Array.isArray(r)?"apply":"call"](de.console,r)};function Yv(s,e=":",t=""){let i="info",n;function r(...o){n("log",i,o)}return n=P3(s,r,t),r.createLogger=(o,u,c)=>{const d=u!==void 0?u:e,f=c!==void 0?c:t,p=`${s} ${d} ${o}`;return Yv(p,d,f)},r.createNewLogger=(o,u,c)=>Yv(o,u,c),r.levels={all:"debug|log|warn|error",off:"",debug:"debug|log|warn|error",info:"log|warn|error",warn:"warn|error",error:"error",DEFAULT:i},r.level=o=>{if(typeof o=="string"){if(!r.levels.hasOwnProperty(o))throw new Error(`"${o}" in not a valid log level`);i=o}return i},r.history=()=>jn?[].concat(jn):[],r.history.filter=o=>(jn||[]).filter(u=>new RegExp(`.*${o}.*`).test(u[0])),r.history.clear=()=>{jn&&(jn.length=0)},r.history.disable=()=>{jn!==null&&(jn.length=0,jn=null)},r.history.enable=()=>{jn===null&&(jn=[])},r.error=(...o)=>n("error",i,o),r.warn=(...o)=>n("warn",i,o),r.debug=(...o)=>n("debug",i,o),r}const fi=Yv("VIDEOJS"),JA=fi.createLogger,B3=Object.prototype.toString,eC=function(s){return ba(s)?Object.keys(s):[]};function ac(s,e){eC(s).forEach(t=>e(s[t],t))}function tC(s,e,t=0){return eC(s).reduce((i,n)=>e(i,s[n],n),t)}function ba(s){return!!s&&typeof s=="object"}function Cc(s){return ba(s)&&B3.call(s)==="[object Object]"&&s.constructor===Object}function Gi(...s){const e={};return s.forEach(t=>{t&&ac(t,(i,n)=>{if(!Cc(i)){e[n]=i;return}Cc(e[n])||(e[n]={}),e[n]=Gi(e[n],i)})}),e}function iC(s={}){const e=[];for(const t in s)if(s.hasOwnProperty(t)){const i=s[t];e.push(i)}return e}function Kp(s,e,t,i=!0){const n=o=>Object.defineProperty(s,e,{value:o,enumerable:!0,writable:!0}),r={configurable:!0,enumerable:!0,get(){const o=t();return n(o),o}};return i&&(r.set=n),Object.defineProperty(s,e,r)}var F3=Object.freeze({__proto__:null,each:ac,reduce:tC,isObject:ba,isPlain:Cc,merge:Gi,values:iC,defineLazyProperty:Kp});let tb=!1,sC=null,Ur=!1,nC,rC=!1,oc=!1,lc=!1,Ta=!1,ib=null,Yp=null;const U3=!!(de.cast&&de.cast.framework&&de.cast.framework.CastReceiverContext);let aC=null,ip=!1,Wp=!1,sp=!1,Xp=!1,np=!1,rp=!1,ap=!1;const xh=!!(Pc()&&("ontouchstart"in de||de.navigator.maxTouchPoints||de.DocumentTouch&&de.document instanceof de.DocumentTouch)),zo=de.navigator&&de.navigator.userAgentData;zo&&zo.platform&&zo.brands&&(Ur=zo.platform==="Android",oc=!!zo.brands.find(s=>s.brand==="Microsoft Edge"),lc=!!zo.brands.find(s=>s.brand==="Chromium"),Ta=!oc&&lc,ib=Yp=(zo.brands.find(s=>s.brand==="Chromium")||{}).version||null,Wp=zo.platform==="Windows");if(!lc){const s=de.navigator&&de.navigator.userAgent||"";tb=/iPod/i.test(s),sC=(function(){const e=s.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null})(),Ur=/Android/i.test(s),nC=(function(){const e=s.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!e)return null;const t=e[1]&&parseFloat(e[1]),i=e[2]&&parseFloat(e[2]);return t&&i?parseFloat(e[1]+"."+e[2]):t||null})(),rC=/Firefox/i.test(s),oc=/Edg/i.test(s),lc=/Chrome/i.test(s)||/CriOS/i.test(s),Ta=!oc&&lc,ib=Yp=(function(){const e=s.match(/(Chrome|CriOS)\/(\d+)/);return e&&e[2]?parseFloat(e[2]):null})(),aC=(function(){const e=/MSIE\s(\d+)\.\d/.exec(s);let t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(s)&&/rv:11.0/.test(s)&&(t=11),t})(),np=/Tizen/i.test(s),rp=/Web0S/i.test(s),ap=np||rp,ip=/Safari/i.test(s)&&!Ta&&!Ur&&!oc&&!ap,Wp=/Windows/i.test(s),sp=/iPad/i.test(s)||ip&&xh&&!/iPhone/i.test(s),Xp=/iPhone/i.test(s)&&!sp}const hn=Xp||sp||tb,Qp=(ip||hn)&&!Ta;var oC=Object.freeze({__proto__:null,get IS_IPOD(){return tb},get IOS_VERSION(){return sC},get IS_ANDROID(){return Ur},get ANDROID_VERSION(){return nC},get IS_FIREFOX(){return rC},get IS_EDGE(){return oc},get IS_CHROMIUM(){return lc},get IS_CHROME(){return Ta},get CHROMIUM_VERSION(){return ib},get CHROME_VERSION(){return Yp},IS_CHROMECAST_RECEIVER:U3,get IE_VERSION(){return aC},get IS_SAFARI(){return ip},get IS_WINDOWS(){return Wp},get IS_IPAD(){return sp},get IS_IPHONE(){return Xp},get IS_TIZEN(){return np},get IS_WEBOS(){return rp},get IS_SMART_TV(){return ap},TOUCH_ENABLED:xh,IS_IOS:hn,IS_ANY_SAFARI:Qp});function _E(s){return typeof s=="string"&&!!s.trim()}function j3(s){if(s.indexOf(" ")>=0)throw new Error("class has illegal whitespace characters")}function Pc(){return at===de.document}function Bc(s){return ba(s)&&s.nodeType===1}function lC(){try{return de.parent!==de.self}catch{return!0}}function uC(s){return function(e,t){if(!_E(e))return at[s](null);_E(t)&&(t=at.querySelector(t));const i=Bc(t)?t:at;return i[s]&&i[s](e)}}function Kt(s="div",e={},t={},i){const n=at.createElement(s);return Object.getOwnPropertyNames(e).forEach(function(r){const o=e[r];r==="textContent"?dl(n,o):(n[r]!==o||r==="tabIndex")&&(n[r]=o)}),Object.getOwnPropertyNames(t).forEach(function(r){n.setAttribute(r,t[r])}),i&&sb(n,i),n}function dl(s,e){return typeof s.textContent>"u"?s.innerText=e:s.textContent=e,s}function Wv(s,e){e.firstChild?e.insertBefore(s,e.firstChild):e.appendChild(s)}function uh(s,e){return j3(e),s.classList.contains(e)}function Zl(s,...e){return s.classList.add(...e.reduce((t,i)=>t.concat(i.split(/\s+/)),[])),s}function Zp(s,...e){return s?(s.classList.remove(...e.reduce((t,i)=>t.concat(i.split(/\s+/)),[])),s):(fi.warn("removeClass was called with an element that doesn't exist"),null)}function cC(s,e,t){return typeof t=="function"&&(t=t(s,e)),typeof t!="boolean"&&(t=void 0),e.split(/\s+/).forEach(i=>s.classList.toggle(i,t)),s}function dC(s,e){Object.getOwnPropertyNames(e).forEach(function(t){const i=e[t];i===null||typeof i>"u"||i===!1?s.removeAttribute(t):s.setAttribute(t,i===!0?"":i)})}function Qo(s){const e={},t=["autoplay","controls","playsinline","loop","muted","default","defaultMuted"];if(s&&s.attributes&&s.attributes.length>0){const i=s.attributes;for(let n=i.length-1;n>=0;n--){const r=i[n].name;let o=i[n].value;t.includes(r)&&(o=o!==null),e[r]=o}}return e}function hC(s,e){return s.getAttribute(e)}function kc(s,e,t){s.setAttribute(e,t)}function Jp(s,e){s.removeAttribute(e)}function fC(){at.body.focus(),at.onselectstart=function(){return!1}}function mC(){at.onselectstart=function(){return!0}}function Dc(s){if(s&&s.getBoundingClientRect&&s.parentNode){const e=s.getBoundingClientRect(),t={};return["bottom","height","left","right","top","width"].forEach(i=>{e[i]!==void 0&&(t[i]=e[i])}),t.height||(t.height=parseFloat(Lc(s,"height"))),t.width||(t.width=parseFloat(Lc(s,"width"))),t}}function bh(s){if(!s||s&&!s.offsetParent)return{left:0,top:0,width:0,height:0};const e=s.offsetWidth,t=s.offsetHeight;let i=0,n=0;for(;s.offsetParent&&s!==at[tp.fullscreenElement];)i+=s.offsetLeft,n+=s.offsetTop,s=s.offsetParent;return{left:i,top:n,width:e,height:t}}function eg(s,e){const t={x:0,y:0};if(hn){let f=s;for(;f&&f.nodeName.toLowerCase()!=="html";){const p=Lc(f,"transform");if(/^matrix/.test(p)){const g=p.slice(7,-1).split(/,\s/).map(Number);t.x+=g[4],t.y+=g[5]}else if(/^matrix3d/.test(p)){const g=p.slice(9,-1).split(/,\s/).map(Number);t.x+=g[12],t.y+=g[13]}if(f.assignedSlot&&f.assignedSlot.parentElement&&de.WebKitCSSMatrix){const g=de.getComputedStyle(f.assignedSlot.parentElement).transform,v=new de.WebKitCSSMatrix(g);t.x+=v.m41,t.y+=v.m42}f=f.parentNode||f.host}}const i={},n=bh(e.target),r=bh(s),o=r.width,u=r.height;let c=e.offsetY-(r.top-n.top),d=e.offsetX-(r.left-n.left);return e.changedTouches&&(d=e.changedTouches[0].pageX-r.left,c=e.changedTouches[0].pageY+r.top,hn&&(d-=t.x,c-=t.y)),i.y=1-Math.max(0,Math.min(1,c/u)),i.x=Math.max(0,Math.min(1,d/o)),i}function pC(s){return ba(s)&&s.nodeType===3}function tg(s){for(;s.firstChild;)s.removeChild(s.firstChild);return s}function gC(s){return typeof s=="function"&&(s=s()),(Array.isArray(s)?s:[s]).map(e=>{if(typeof e=="function"&&(e=e()),Bc(e)||pC(e))return e;if(typeof e=="string"&&/\S/.test(e))return at.createTextNode(e)}).filter(e=>e)}function sb(s,e){return gC(e).forEach(t=>s.appendChild(t)),s}function yC(s,e){return sb(tg(s),e)}function Th(s){return s.button===void 0&&s.buttons===void 0||s.button===0&&s.buttons===void 0||s.type==="mouseup"&&s.button===0&&s.buttons===0||s.type==="mousedown"&&s.button===0&&s.buttons===0?!0:!(s.button!==0||s.buttons!==1)}const ll=uC("querySelector"),vC=uC("querySelectorAll");function Lc(s,e){if(!s||!e)return"";if(typeof de.getComputedStyle=="function"){let t;try{t=de.getComputedStyle(s)}catch{return""}return t?t.getPropertyValue(e)||t[e]:""}return""}function xC(s){[...at.styleSheets].forEach(e=>{try{const t=[...e.cssRules].map(n=>n.cssText).join(""),i=at.createElement("style");i.textContent=t,s.document.head.appendChild(i)}catch{const i=at.createElement("link");i.rel="stylesheet",i.type=e.type,i.media=e.media.mediaText,i.href=e.href,s.document.head.appendChild(i)}})}var bC=Object.freeze({__proto__:null,isReal:Pc,isEl:Bc,isInFrame:lC,createEl:Kt,textContent:dl,prependTo:Wv,hasClass:uh,addClass:Zl,removeClass:Zp,toggleClass:cC,setAttributes:dC,getAttributes:Qo,getAttribute:hC,setAttribute:kc,removeAttribute:Jp,blockTextSelection:fC,unblockTextSelection:mC,getBoundingClientRect:Dc,findPosition:bh,getPointerPosition:eg,isTextNode:pC,emptyEl:tg,normalizeContent:gC,appendContent:sb,insertContent:yC,isSingleLeftClick:Th,$:ll,$$:vC,computedStyle:Lc,copyStyleSheetsToWindow:xC});let TC=!1,Xv;const $3=function(){if(Xv.options.autoSetup===!1)return;const s=Array.prototype.slice.call(at.getElementsByTagName("video")),e=Array.prototype.slice.call(at.getElementsByTagName("audio")),t=Array.prototype.slice.call(at.getElementsByTagName("video-js")),i=s.concat(e,t);if(i&&i.length>0)for(let n=0,r=i.length;n-1&&(n={passive:!0}),s.addEventListener(e,i.dispatcher,n)}else s.attachEvent&&s.attachEvent("on"+e,i.dispatcher)}function fn(s,e,t){if(!Sn.has(s))return;const i=Sn.get(s);if(!i.handlers)return;if(Array.isArray(e))return nb(fn,s,e,t);const n=function(o,u){i.handlers[u]=[],SE(o,u)};if(e===void 0){for(const o in i.handlers)Object.prototype.hasOwnProperty.call(i.handlers||{},o)&&n(s,o);return}const r=i.handlers[e];if(r){if(!t){n(s,e);return}if(t.guid)for(let o=0;o=e&&(s(...n),t=r)}},EC=function(s,e,t,i=de){let n;const r=()=>{i.clearTimeout(n),n=null},o=function(){const u=this,c=arguments;let d=function(){n=null,d=null,t||s.apply(u,c)};!n&&t&&s.apply(u,c),i.clearTimeout(n),n=i.setTimeout(d,e)};return o.cancel=r,o};var K3=Object.freeze({__proto__:null,UPDATE_REFRESH_INTERVAL:Tr,bind_:ts,throttle:_a,debounce:EC});let zd;class hr{on(e,t){const i=this.addEventListener;this.addEventListener=()=>{},dr(this,e,t),this.addEventListener=i}off(e,t){fn(this,e,t)}one(e,t){const i=this.addEventListener;this.addEventListener=()=>{},sg(this,e,t),this.addEventListener=i}any(e,t){const i=this.addEventListener;this.addEventListener=()=>{},rb(this,e,t),this.addEventListener=i}trigger(e){const t=e.type||e;typeof e=="string"&&(e={type:t}),e=ig(e),this.allowedEvents_[t]&&this["on"+t]&&this["on"+t](e),Fc(this,e)}queueTrigger(e){zd||(zd=new Map);const t=e.type||e;let i=zd.get(this);i||(i=new Map,zd.set(this,i));const n=i.get(t);i.delete(t),de.clearTimeout(n);const r=de.setTimeout(()=>{i.delete(t),i.size===0&&(i=null,zd.delete(this)),this.trigger(e)},0);i.set(t,r)}}hr.prototype.allowedEvents_={};hr.prototype.addEventListener=hr.prototype.on;hr.prototype.removeEventListener=hr.prototype.off;hr.prototype.dispatchEvent=hr.prototype.trigger;const ng=s=>typeof s.name=="function"?s.name():typeof s.name=="string"?s.name:s.name_?s.name_:s.constructor&&s.constructor.name?s.constructor.name:typeof s,to=s=>s instanceof hr||!!s.eventBusEl_&&["on","one","off","trigger"].every(e=>typeof s[e]=="function"),Y3=(s,e)=>{to(s)?e():(s.eventedCallbacks||(s.eventedCallbacks=[]),s.eventedCallbacks.push(e))},Jv=s=>typeof s=="string"&&/\S/.test(s)||Array.isArray(s)&&!!s.length,op=(s,e,t)=>{if(!s||!s.nodeName&&!to(s))throw new Error(`Invalid target for ${ng(e)}#${t}; must be a DOM node or evented object.`)},wC=(s,e,t)=>{if(!Jv(s))throw new Error(`Invalid event type for ${ng(e)}#${t}; must be a non-empty string or array.`)},AC=(s,e,t)=>{if(typeof s!="function")throw new Error(`Invalid listener for ${ng(e)}#${t}; must be a function.`)},Uy=(s,e,t)=>{const i=e.length<3||e[0]===s||e[0]===s.eventBusEl_;let n,r,o;return i?(n=s.eventBusEl_,e.length>=3&&e.shift(),[r,o]=e):(n=e[0],r=e[1],o=e[2]),op(n,s,t),wC(r,s,t),AC(o,s,t),o=ts(s,o),{isTargetingSelf:i,target:n,type:r,listener:o}},Fl=(s,e,t,i)=>{op(s,s,e),s.nodeName?q3[e](s,t,i):s[e](t,i)},W3={on(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=Uy(this,s,"on");if(Fl(t,"on",i,n),!e){const r=()=>this.off(t,i,n);r.guid=n.guid;const o=()=>this.off("dispose",r);o.guid=n.guid,Fl(this,"on","dispose",r),Fl(t,"on","dispose",o)}},one(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=Uy(this,s,"one");if(e)Fl(t,"one",i,n);else{const r=(...o)=>{this.off(t,i,r),n.apply(null,o)};r.guid=n.guid,Fl(t,"one",i,r)}},any(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=Uy(this,s,"any");if(e)Fl(t,"any",i,n);else{const r=(...o)=>{this.off(t,i,r),n.apply(null,o)};r.guid=n.guid,Fl(t,"any",i,r)}},off(s,e,t){if(!s||Jv(s))fn(this.eventBusEl_,s,e);else{const i=s,n=e;op(i,this,"off"),wC(n,this,"off"),AC(t,this,"off"),t=ts(this,t),this.off("dispose",t),i.nodeName?(fn(i,n,t),fn(i,"dispose",t)):to(i)&&(i.off(n,t),i.off("dispose",t))}},trigger(s,e){op(this.eventBusEl_,this,"trigger");const t=s&&typeof s!="string"?s.type:s;if(!Jv(t))throw new Error(`Invalid event type for ${ng(this)}#trigger; must be a non-empty string or object with a type key that has a non-empty value.`);return Fc(this.eventBusEl_,s,e)}};function ab(s,e={}){const{eventBusKey:t}=e;if(t){if(!s[t].nodeName)throw new Error(`The eventBusKey "${t}" does not refer to an element.`);s.eventBusEl_=s[t]}else s.eventBusEl_=Kt("span",{className:"vjs-event-bus"});return Object.assign(s,W3),s.eventedCallbacks&&s.eventedCallbacks.forEach(i=>{i()}),s.on("dispose",()=>{s.off(),[s,s.el_,s.eventBusEl_].forEach(function(i){i&&Sn.has(i)&&Sn.delete(i)}),de.setTimeout(()=>{s.eventBusEl_=null},0)}),s}const X3={state:{},setState(s){typeof s=="function"&&(s=s());let e;return ac(s,(t,i)=>{this.state[i]!==t&&(e=e||{},e[i]={from:this.state[i],to:t}),this.state[i]=t}),e&&to(this)&&this.trigger({changes:e,type:"statechanged"}),e}};function CC(s,e){return Object.assign(s,X3),s.state=Object.assign({},s.state,e),typeof s.handleStateChanged=="function"&&to(s)&&s.on("statechanged",s.handleStateChanged),s}const ch=function(s){return typeof s!="string"?s:s.replace(/./,e=>e.toLowerCase())},bs=function(s){return typeof s!="string"?s:s.replace(/./,e=>e.toUpperCase())},kC=function(s,e){return bs(s)===bs(e)};var Q3=Object.freeze({__proto__:null,toLowerCase:ch,toTitleCase:bs,titleCaseEquals:kC});class $e{constructor(e,t,i){if(!e&&this.play?this.player_=e=this:this.player_=e,this.isDisposed_=!1,this.parentComponent_=null,this.options_=Gi({},this.options_),t=this.options_=Gi(this.options_,t),this.id_=t.id||t.el&&t.el.id,!this.id_){const n=e&&e.id&&e.id()||"no_player";this.id_=`${n}_component_${br()}`}this.name_=t.name||null,t.el?this.el_=t.el:t.createEl!==!1&&(this.el_=this.createEl()),t.className&&this.el_&&t.className.split(" ").forEach(n=>this.addClass(n)),["on","off","one","any","trigger"].forEach(n=>{this[n]=void 0}),t.evented!==!1&&(ab(this,{eventBusKey:this.el_?"el_":null}),this.handleLanguagechange=this.handleLanguagechange.bind(this),this.on(this.player_,"languagechange",this.handleLanguagechange)),CC(this,this.constructor.defaultState),this.children_=[],this.childIndex_={},this.childNameIndex_={},this.setTimeoutIds_=new Set,this.setIntervalIds_=new Set,this.rafIds_=new Set,this.namedRafs_=new Map,this.clearingTimersOnDispose_=!1,t.initChildren!==!1&&this.initChildren(),this.ready(i),t.reportTouchActivity!==!1&&this.enableTouchActivity()}dispose(e={}){if(!this.isDisposed_){if(this.readyQueue_&&(this.readyQueue_.length=0),this.trigger({type:"dispose",bubbles:!1}),this.isDisposed_=!0,this.children_)for(let t=this.children_.length-1;t>=0;t--)this.children_[t].dispose&&this.children_[t].dispose();this.children_=null,this.childIndex_=null,this.childNameIndex_=null,this.parentComponent_=null,this.el_&&(this.el_.parentNode&&(e.restoreEl?this.el_.parentNode.replaceChild(e.restoreEl,this.el_):this.el_.parentNode.removeChild(this.el_)),this.el_=null),this.player_=null}}isDisposed(){return!!this.isDisposed_}player(){return this.player_}options(e){return e?(this.options_=Gi(this.options_,e),this.options_):this.options_}el(){return this.el_}createEl(e,t,i){return Kt(e,t,i)}localize(e,t,i=e){const n=this.player_.language&&this.player_.language(),r=this.player_.languages&&this.player_.languages(),o=r&&r[n],u=n&&n.split("-")[0],c=r&&r[u];let d=i;return o&&o[e]?d=o[e]:c&&c[e]&&(d=c[e]),t&&(d=d.replace(/\{(\d+)\}/g,function(f,p){const g=t[p-1];let v=g;return typeof g>"u"&&(v=f),v})),d}handleLanguagechange(){}contentEl(){return this.contentEl_||this.el_}id(){return this.id_}name(){return this.name_}children(){return this.children_}getChildById(e){return this.childIndex_[e]}getChild(e){if(e)return this.childNameIndex_[e]}getDescendant(...e){e=e.reduce((i,n)=>i.concat(n),[]);let t=this;for(let i=0;i=0;n--)if(this.children_[n]===e){t=!0,this.children_.splice(n,1);break}if(!t)return;e.parentComponent_=null,this.childIndex_[e.id()]=null,this.childNameIndex_[bs(e.name())]=null,this.childNameIndex_[ch(e.name())]=null;const i=e.el();i&&i.parentNode===this.contentEl()&&this.contentEl().removeChild(e.el())}initChildren(){const e=this.options_.children;if(e){const t=this.options_,i=o=>{const u=o.name;let c=o.opts;if(t[u]!==void 0&&(c=t[u]),c===!1)return;c===!0&&(c={}),c.playerOptions=this.options_.playerOptions;const d=this.addChild(u,c);d&&(this[u]=d)};let n;const r=$e.getComponent("Tech");Array.isArray(e)?n=e:n=Object.keys(e),n.concat(Object.keys(this.options_).filter(function(o){return!n.some(function(u){return typeof u=="string"?o===u:o===u.name})})).map(o=>{let u,c;return typeof o=="string"?(u=o,c=e[u]||this.options_[u]||{}):(u=o.name,c=o),{name:u,opts:c}}).filter(o=>{const u=$e.getComponent(o.opts.componentClass||bs(o.name));return u&&!r.isTech(u)}).forEach(i)}}buildCSSClass(){return""}ready(e,t=!1){if(e){if(!this.isReady_){this.readyQueue_=this.readyQueue_||[],this.readyQueue_.push(e);return}t?e.call(this):this.setTimeout(e,1)}}triggerReady(){this.isReady_=!0,this.setTimeout(function(){const e=this.readyQueue_;this.readyQueue_=[],e&&e.length>0&&e.forEach(function(t){t.call(this)},this),this.trigger("ready")},1)}$(e,t){return ll(e,t||this.contentEl())}$$(e,t){return vC(e,t||this.contentEl())}hasClass(e){return uh(this.el_,e)}addClass(...e){Zl(this.el_,...e)}removeClass(...e){Zp(this.el_,...e)}toggleClass(e,t){cC(this.el_,e,t)}show(){this.removeClass("vjs-hidden")}hide(){this.addClass("vjs-hidden")}lockShowing(){this.addClass("vjs-lock-showing")}unlockShowing(){this.removeClass("vjs-lock-showing")}getAttribute(e){return hC(this.el_,e)}setAttribute(e,t){kc(this.el_,e,t)}removeAttribute(e){Jp(this.el_,e)}width(e,t){return this.dimension("width",e,t)}height(e,t){return this.dimension("height",e,t)}dimensions(e,t){this.width(e,!0),this.height(t)}dimension(e,t,i){if(t!==void 0){(t===null||t!==t)&&(t=0),(""+t).indexOf("%")!==-1||(""+t).indexOf("px")!==-1?this.el_.style[e]=t:t==="auto"?this.el_.style[e]="":this.el_.style[e]=t+"px",i||this.trigger("componentresize");return}if(!this.el_)return 0;const n=this.el_.style[e],r=n.indexOf("px");return parseInt(r!==-1?n.slice(0,r):this.el_["offset"+bs(e)],10)}currentDimension(e){let t=0;if(e!=="width"&&e!=="height")throw new Error("currentDimension only accepts width or height value");if(t=Lc(this.el_,e),t=parseFloat(t),t===0||isNaN(t)){const i=`offset${bs(e)}`;t=this.el_[i]}return t}currentDimensions(){return{width:this.currentDimension("width"),height:this.currentDimension("height")}}currentWidth(){return this.currentDimension("width")}currentHeight(){return this.currentDimension("height")}getPositions(){const e=this.el_.getBoundingClientRect(),t={x:e.x,y:e.y,width:e.width,height:e.height,top:e.top,right:e.right,bottom:e.bottom,left:e.left},i={x:e.left+e.width/2,y:e.top+e.height/2,width:0,height:0,top:e.top+e.height/2,right:e.left+e.width/2,bottom:e.top+e.height/2,left:e.left+e.width/2};return{boundingClientRect:t,center:i}}focus(){this.el_.focus()}blur(){this.el_.blur()}handleKeyDown(e){this.player_&&(e.key!=="Tab"&&!(this.player_.options_.playerOptions.spatialNavigation&&this.player_.options_.playerOptions.spatialNavigation.enabled)&&e.stopPropagation(),this.player_.handleKeyDown(e))}handleKeyPress(e){this.handleKeyDown(e)}emitTapEvents(){let e=0,t=null;const i=10,n=200;let r;this.on("touchstart",function(u){u.touches.length===1&&(t={pageX:u.touches[0].pageX,pageY:u.touches[0].pageY},e=de.performance.now(),r=!0)}),this.on("touchmove",function(u){if(u.touches.length>1)r=!1;else if(t){const c=u.touches[0].pageX-t.pageX,d=u.touches[0].pageY-t.pageY;Math.sqrt(c*c+d*d)>i&&(r=!1)}});const o=function(){r=!1};this.on("touchleave",o),this.on("touchcancel",o),this.on("touchend",function(u){t=null,r===!0&&de.performance.now()-e{this.setTimeoutIds_.has(i)&&this.setTimeoutIds_.delete(i),e()},t),this.setTimeoutIds_.add(i),i}clearTimeout(e){return this.setTimeoutIds_.has(e)&&(this.setTimeoutIds_.delete(e),de.clearTimeout(e)),e}setInterval(e,t){e=ts(this,e),this.clearTimersOnDispose_();const i=de.setInterval(e,t);return this.setIntervalIds_.add(i),i}clearInterval(e){return this.setIntervalIds_.has(e)&&(this.setIntervalIds_.delete(e),de.clearInterval(e)),e}requestAnimationFrame(e){this.clearTimersOnDispose_();var t;return e=ts(this,e),t=de.requestAnimationFrame(()=>{this.rafIds_.has(t)&&this.rafIds_.delete(t),e()}),this.rafIds_.add(t),t}requestNamedAnimationFrame(e,t){this.namedRafs_.has(e)&&this.cancelNamedAnimationFrame(e),this.clearTimersOnDispose_(),t=ts(this,t);const i=this.requestAnimationFrame(()=>{t(),this.namedRafs_.has(e)&&this.namedRafs_.delete(e)});return this.namedRafs_.set(e,i),e}cancelNamedAnimationFrame(e){this.namedRafs_.has(e)&&(this.cancelAnimationFrame(this.namedRafs_.get(e)),this.namedRafs_.delete(e))}cancelAnimationFrame(e){return this.rafIds_.has(e)&&(this.rafIds_.delete(e),de.cancelAnimationFrame(e)),e}clearTimersOnDispose_(){this.clearingTimersOnDispose_||(this.clearingTimersOnDispose_=!0,this.one("dispose",()=>{[["namedRafs_","cancelNamedAnimationFrame"],["rafIds_","cancelAnimationFrame"],["setTimeoutIds_","clearTimeout"],["setIntervalIds_","clearInterval"]].forEach(([e,t])=>{this[e].forEach((i,n)=>this[t](n))}),this.clearingTimersOnDispose_=!1}))}getIsDisabled(){return!!this.el_.disabled}getIsExpresslyInert(){return this.el_.inert&&!this.el_.ownerDocument.documentElement.inert}getIsFocusable(e){return(e||this.el_).tabIndex>=0&&!(this.getIsDisabled()||this.getIsExpresslyInert())}getIsAvailableToBeFocused(e){function t(r){const o=de.getComputedStyle(r,null),u=o.getPropertyValue("visibility");return o.getPropertyValue("display")!=="none"&&!["hidden","collapse"].includes(u)}function i(r){return!(!t(r.parentElement)||!t(r)||r.style.opacity==="0"||de.getComputedStyle(r).height==="0px"||de.getComputedStyle(r).width==="0px")}function n(r){if(r.offsetWidth+r.offsetHeight+r.getBoundingClientRect().height+r.getBoundingClientRect().width===0)return!1;const o={x:r.getBoundingClientRect().left+r.offsetWidth/2,y:r.getBoundingClientRect().top+r.offsetHeight/2};if(o.x<0||o.x>(at.documentElement.clientWidth||de.innerWidth)||o.y<0||o.y>(at.documentElement.clientHeight||de.innerHeight))return!1;let u=at.elementFromPoint(o.x,o.y);for(;u;){if(u===r)return!0;if(u.parentNode)u=u.parentNode;else return!1}}return e||(e=this.el()),!!(n(e)&&i(e)&&(!e.parentElement||e.tabIndex>=0))}static registerComponent(e,t){if(typeof e!="string"||!e)throw new Error(`Illegal component name, "${e}"; must be a non-empty string.`);const i=$e.getComponent("Tech"),n=i&&i.isTech(t),r=$e===t||$e.prototype.isPrototypeOf(t.prototype);if(n||!r){let u;throw n?u="techs must be registered using Tech.registerTech()":u="must be a Component subclass",new Error(`Illegal component, "${e}"; ${u}.`)}e=bs(e),$e.components_||($e.components_={});const o=$e.getComponent("Player");if(e==="Player"&&o&&o.players){const u=o.players,c=Object.keys(u);if(u&&c.length>0){for(let d=0;dt)throw new Error(`Failed to execute '${s}' on 'TimeRanges': The index provided (${e}) is non-numeric or out of bounds (0-${t}).`)}function EE(s,e,t,i){return Z3(s,i,t.length-1),t[i][e]}function jy(s){let e;return s===void 0||s.length===0?e={length:0,start(){throw new Error("This TimeRanges object is empty")},end(){throw new Error("This TimeRanges object is empty")}}:e={length:s.length,start:EE.bind(null,"start",0,s),end:EE.bind(null,"end",1,s)},de.Symbol&&de.Symbol.iterator&&(e[de.Symbol.iterator]=()=>(s||[]).values()),e}function Fr(s,e){return Array.isArray(s)?jy(s):s===void 0||e===void 0?jy():jy([[s,e]])}const DC=function(s,e){s=s<0?0:s;let t=Math.floor(s%60),i=Math.floor(s/60%60),n=Math.floor(s/3600);const r=Math.floor(e/60%60),o=Math.floor(e/3600);return(isNaN(s)||s===1/0)&&(n=i=t="-"),n=n>0||o>0?n+":":"",i=((n||r>=10)&&i<10?"0"+i:i)+":",t=t<10?"0"+t:t,n+i+t};let ob=DC;function LC(s){ob=s}function RC(){ob=DC}function nu(s,e=s){return ob(s,e)}var J3=Object.freeze({__proto__:null,createTimeRanges:Fr,createTimeRange:Fr,setFormatTime:LC,resetFormatTime:RC,formatTime:nu});function IC(s,e){let t=0,i,n;if(!e)return 0;(!s||!s.length)&&(s=Fr(0,0));for(let r=0;re&&(n=e),t+=n-i;return t/e}function ms(s){if(s instanceof ms)return s;typeof s=="number"?this.code=s:typeof s=="string"?this.message=s:ba(s)&&(typeof s.code=="number"&&(this.code=s.code),Object.assign(this,s)),this.message||(this.message=ms.defaultMessages[this.code]||"")}ms.prototype.code=0;ms.prototype.message="";ms.prototype.status=null;ms.prototype.metadata=null;ms.errorTypes=["MEDIA_ERR_CUSTOM","MEDIA_ERR_ABORTED","MEDIA_ERR_NETWORK","MEDIA_ERR_DECODE","MEDIA_ERR_SRC_NOT_SUPPORTED","MEDIA_ERR_ENCRYPTED"];ms.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."};ms.MEDIA_ERR_CUSTOM=0;ms.prototype.MEDIA_ERR_CUSTOM=0;ms.MEDIA_ERR_ABORTED=1;ms.prototype.MEDIA_ERR_ABORTED=1;ms.MEDIA_ERR_NETWORK=2;ms.prototype.MEDIA_ERR_NETWORK=2;ms.MEDIA_ERR_DECODE=3;ms.prototype.MEDIA_ERR_DECODE=3;ms.MEDIA_ERR_SRC_NOT_SUPPORTED=4;ms.prototype.MEDIA_ERR_SRC_NOT_SUPPORTED=4;ms.MEDIA_ERR_ENCRYPTED=5;ms.prototype.MEDIA_ERR_ENCRYPTED=5;function dh(s){return s!=null&&typeof s.then=="function"}function da(s){dh(s)&&s.then(null,e=>{})}const ex=function(s){return["kind","label","language","id","inBandMetadataTrackDispatchType","mode","src"].reduce((t,i,n)=>(s[i]&&(t[i]=s[i]),t),{cues:s.cues&&Array.prototype.map.call(s.cues,function(t){return{startTime:t.startTime,endTime:t.endTime,text:t.text,id:t.id}})})},e4=function(s){const e=s.$$("track"),t=Array.prototype.map.call(e,n=>n.track);return Array.prototype.map.call(e,function(n){const r=ex(n.track);return n.src&&(r.src=n.src),r}).concat(Array.prototype.filter.call(s.textTracks(),function(n){return t.indexOf(n)===-1}).map(ex))},t4=function(s,e){return s.forEach(function(t){const i=e.addRemoteTextTrack(t).track;!t.src&&t.cues&&t.cues.forEach(n=>i.addCue(n))}),e.textTracks()};var tx={textTracksToJson:e4,jsonToTextTracks:t4,trackToJson:ex};const $y="vjs-modal-dialog";class Uc extends $e{constructor(e,t){super(e,t),this.handleKeyDown_=i=>this.handleKeyDown(i),this.close_=i=>this.close(i),this.opened_=this.hasBeenOpened_=this.hasBeenFilled_=!1,this.closeable(!this.options_.uncloseable),this.content(this.options_.content),this.contentEl_=Kt("div",{className:`${$y}-content`},{role:"document"}),this.descEl_=Kt("p",{className:`${$y}-description vjs-control-text`,id:this.el().getAttribute("aria-describedby")}),dl(this.descEl_,this.description()),this.el_.appendChild(this.descEl_),this.el_.appendChild(this.contentEl_)}createEl(){return super.createEl("div",{className:this.buildCSSClass(),tabIndex:-1},{"aria-describedby":`${this.id()}_description`,"aria-hidden":"true","aria-label":this.label(),role:"dialog","aria-live":"polite"})}dispose(){this.contentEl_=null,this.descEl_=null,this.previouslyActiveEl_=null,super.dispose()}buildCSSClass(){return`${$y} vjs-hidden ${super.buildCSSClass()}`}label(){return this.localize(this.options_.label||"Modal Window")}description(){let e=this.options_.description||this.localize("This is a modal window.");return this.closeable()&&(e+=" "+this.localize("This modal can be closed by pressing the Escape key or activating the close button.")),e}open(){if(this.opened_){this.options_.fillAlways&&this.fill();return}const e=this.player();this.trigger("beforemodalopen"),this.opened_=!0,(this.options_.fillAlways||!this.hasBeenOpened_&&!this.hasBeenFilled_)&&this.fill(),this.wasPlaying_=!e.paused(),this.options_.pauseOnOpen&&this.wasPlaying_&&e.pause(),this.on("keydown",this.handleKeyDown_),this.hadControls_=e.controls(),e.controls(!1),this.show(),this.conditionalFocus_(),this.el().setAttribute("aria-hidden","false"),this.trigger("modalopen"),this.hasBeenOpened_=!0}opened(e){return typeof e=="boolean"&&this[e?"open":"close"](),this.opened_}close(){if(!this.opened_)return;const e=this.player();this.trigger("beforemodalclose"),this.opened_=!1,this.wasPlaying_&&this.options_.pauseOnOpen&&e.play(),this.off("keydown",this.handleKeyDown_),this.hadControls_&&e.controls(!0),this.hide(),this.el().setAttribute("aria-hidden","true"),this.trigger({type:"modalclose",bubbles:!0}),this.conditionalBlur_(),this.options_.temporary&&this.dispose()}closeable(e){if(typeof e=="boolean"){const t=this.closeable_=!!e;let i=this.getChild("closeButton");if(t&&!i){const n=this.contentEl_;this.contentEl_=this.el_,i=this.addChild("closeButton",{controlText:"Close Modal Dialog"}),this.contentEl_=n,this.on(i,"close",this.close_)}!t&&i&&(this.off(i,"close",this.close_),this.removeChild(i),i.dispose())}return this.closeable_}fill(){this.fillWith(this.content())}fillWith(e){const t=this.contentEl(),i=t.parentNode,n=t.nextSibling;this.trigger("beforemodalfill"),this.hasBeenFilled_=!0,i.removeChild(t),this.empty(),yC(t,e),this.trigger("modalfill"),n?i.insertBefore(t,n):i.appendChild(t);const r=this.getChild("closeButton");r&&i.appendChild(r.el_),this.trigger("aftermodalfill")}empty(){this.trigger("beforemodalempty"),tg(this.contentEl()),this.trigger("modalempty")}content(e){return typeof e<"u"&&(this.content_=e),this.content_}conditionalFocus_(){const e=at.activeElement,t=this.player_.el_;this.previouslyActiveEl_=null,(t.contains(e)||t===e)&&(this.previouslyActiveEl_=e,this.focus())}conditionalBlur_(){this.previouslyActiveEl_&&(this.previouslyActiveEl_.focus(),this.previouslyActiveEl_=null)}handleKeyDown(e){if(this.trigger({type:"modalKeydown",originalEvent:e,target:this,bubbles:!0}),e.stopPropagation(),e.key==="Escape"&&this.closeable()){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;const t=this.focusableEls_(),i=this.el_.querySelector(":focus");let n;for(let r=0;r(t instanceof de.HTMLAnchorElement||t instanceof de.HTMLAreaElement)&&t.hasAttribute("href")||(t instanceof de.HTMLInputElement||t instanceof de.HTMLSelectElement||t instanceof de.HTMLTextAreaElement||t instanceof de.HTMLButtonElement)&&!t.hasAttribute("disabled")||t instanceof de.HTMLIFrameElement||t instanceof de.HTMLObjectElement||t instanceof de.HTMLEmbedElement||t.hasAttribute("tabindex")&&t.getAttribute("tabindex")!==-1||t.hasAttribute("contenteditable"))}}Uc.prototype.options_={pauseOnOpen:!0,temporary:!0};$e.registerComponent("ModalDialog",Uc);class ru extends hr{constructor(e=[]){super(),this.tracks_=[],Object.defineProperty(this,"length",{get(){return this.tracks_.length}});for(let t=0;t{this.trigger({track:e,type:"labelchange",target:this})},to(e)&&e.addEventListener("labelchange",e.labelchange_)}removeTrack(e){let t;for(let i=0,n=this.length;i=0;t--)if(e[t].enabled){Hy(e,e[t]);break}super(e),this.changing_=!1}addTrack(e){e.enabled&&Hy(this,e),super.addTrack(e),e.addEventListener&&(e.enabledChange_=()=>{this.changing_||(this.changing_=!0,Hy(this,e),this.changing_=!1,this.trigger("change"))},e.addEventListener("enabledchange",e.enabledChange_))}removeTrack(e){super.removeTrack(e),e.removeEventListener&&e.enabledChange_&&(e.removeEventListener("enabledchange",e.enabledChange_),e.enabledChange_=null)}}const Vy=function(s,e){for(let t=0;t=0;t--)if(e[t].selected){Vy(e,e[t]);break}super(e),this.changing_=!1,Object.defineProperty(this,"selectedIndex",{get(){for(let t=0;t{this.changing_||(this.changing_=!0,Vy(this,e),this.changing_=!1,this.trigger("change"))},e.addEventListener("selectedchange",e.selectedChange_))}removeTrack(e){super.removeTrack(e),e.removeEventListener&&e.selectedChange_&&(e.removeEventListener("selectedchange",e.selectedChange_),e.selectedChange_=null)}}class lb extends ru{addTrack(e){super.addTrack(e),this.queueChange_||(this.queueChange_=()=>this.queueTrigger("change")),this.triggerSelectedlanguagechange||(this.triggerSelectedlanguagechange_=()=>this.trigger("selectedlanguagechange")),e.addEventListener("modechange",this.queueChange_),["metadata","chapters"].indexOf(e.kind)===-1&&e.addEventListener("modechange",this.triggerSelectedlanguagechange_)}removeTrack(e){super.removeTrack(e),e.removeEventListener&&(this.queueChange_&&e.removeEventListener("modechange",this.queueChange_),this.selectedlanguagechange_&&e.removeEventListener("modechange",this.triggerSelectedlanguagechange_))}toJSON(){return this.tracks_.map(e=>e.toJSON())}}class i4{constructor(e=[]){this.trackElements_=[],Object.defineProperty(this,"length",{get(){return this.trackElements_.length}});for(let t=0,i=e.length;t0&&(de.console&&de.console.groupCollapsed&&de.console.groupCollapsed(`Text Track parsing errors for ${e.src}`),i.forEach(n=>fi.error(n)),de.console&&de.console.groupEnd&&de.console.groupEnd()),t.flush()},CE=function(s,e){const t={uri:s},i=rg(s);i&&(t.cors=i);const n=e.tech_.crossOrigin()==="use-credentials";n&&(t.withCredentials=n),BA(t,ts(this,function(r,o,u){if(r)return fi.error(r,o);e.loaded_=!0,typeof de.WebVTT!="function"?e.tech_&&e.tech_.any(["vttjsloaded","vttjserror"],c=>{if(c.type==="vttjserror"){fi.error(`vttjs failed to load, stopping trying to process ${e.src}`);return}return AE(u,e)}):AE(u,e)}))};class Oh extends ub{constructor(e={}){if(!e.tech)throw new Error("A tech was not provided.");const t=Gi(e,{kind:r4[e.kind]||"subtitles",language:e.language||e.srclang||""});let i=wE[t.mode]||"disabled";const n=t.default;(t.kind==="metadata"||t.kind==="chapters")&&(i="hidden"),super(t),this.tech_=t.tech,this.cues_=[],this.activeCues_=[],this.preload_=this.tech_.preloadTextTracks!==!1;const r=new lp(this.cues_),o=new lp(this.activeCues_);let u=!1;this.timeupdateHandler=ts(this,function(d={}){if(!this.tech_.isDisposed()){if(!this.tech_.isReady_){d.type!=="timeupdate"&&(this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler));return}this.activeCues=this.activeCues,u&&(this.trigger("cuechange"),u=!1),d.type!=="timeupdate"&&(this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler))}});const c=()=>{this.stopTracking()};this.tech_.one("dispose",c),i!=="disabled"&&this.startTracking(),Object.defineProperties(this,{default:{get(){return n},set(){}},mode:{get(){return i},set(d){wE[d]&&i!==d&&(i=d,!this.preload_&&i!=="disabled"&&this.cues.length===0&&CE(this.src,this),this.stopTracking(),i!=="disabled"&&this.startTracking(),this.trigger("modechange"))}},cues:{get(){return this.loaded_?r:null},set(){}},activeCues:{get(){if(!this.loaded_)return null;if(this.cues.length===0)return o;const d=this.tech_.currentTime(),f=[];for(let p=0,g=this.cues.length;p=d&&f.push(v)}if(u=!1,f.length!==this.activeCues_.length)u=!0;else for(let p=0;p{t=so.LOADED,this.trigger({type:"load",target:this})})}}so.prototype.allowedEvents_={load:"load"};so.NONE=0;so.LOADING=1;so.LOADED=2;so.ERROR=3;const xr={audio:{ListClass:NC,TrackClass:PC,capitalName:"Audio"},video:{ListClass:OC,TrackClass:BC,capitalName:"Video"},text:{ListClass:lb,TrackClass:Oh,capitalName:"Text"}};Object.keys(xr).forEach(function(s){xr[s].getterName=`${s}Tracks`,xr[s].privateName=`${s}Tracks_`});const Rc={remoteText:{ListClass:lb,TrackClass:Oh,capitalName:"RemoteText",getterName:"remoteTextTracks",privateName:"remoteTextTracks_"},remoteTextEl:{ListClass:i4,TrackClass:so,capitalName:"RemoteTextTrackEls",getterName:"remoteTextTrackEls",privateName:"remoteTextTrackEls_"}},_n=Object.assign({},xr,Rc);Rc.names=Object.keys(Rc);xr.names=Object.keys(xr);_n.names=[].concat(Rc.names).concat(xr.names);function o4(s,e,t,i,n={}){const r=s.textTracks();n.kind=e,t&&(n.label=t),i&&(n.language=i),n.tech=s;const o=new _n.text.TrackClass(n);return r.addTrack(o),o}class ni extends $e{constructor(e={},t=function(){}){e.reportTouchActivity=!1,super(null,e,t),this.onDurationChange_=i=>this.onDurationChange(i),this.trackProgress_=i=>this.trackProgress(i),this.trackCurrentTime_=i=>this.trackCurrentTime(i),this.stopTrackingCurrentTime_=i=>this.stopTrackingCurrentTime(i),this.disposeSourceHandler_=i=>this.disposeSourceHandler(i),this.queuedHanders_=new Set,this.hasStarted_=!1,this.on("playing",function(){this.hasStarted_=!0}),this.on("loadstart",function(){this.hasStarted_=!1}),_n.names.forEach(i=>{const n=_n[i];e&&e[n.getterName]&&(this[n.privateName]=e[n.getterName])}),this.featuresProgressEvents||this.manualProgressOn(),this.featuresTimeupdateEvents||this.manualTimeUpdatesOn(),["Text","Audio","Video"].forEach(i=>{e[`native${i}Tracks`]===!1&&(this[`featuresNative${i}Tracks`]=!1)}),e.nativeCaptions===!1||e.nativeTextTracks===!1?this.featuresNativeTextTracks=!1:(e.nativeCaptions===!0||e.nativeTextTracks===!0)&&(this.featuresNativeTextTracks=!0),this.featuresNativeTextTracks||this.emulateTextTracks(),this.preloadTextTracks=e.preloadTextTracks!==!1,this.autoRemoteTextTracks_=new _n.text.ListClass,this.initTrackListeners(),e.nativeControlsForTouch||this.emitTapEvents(),this.constructor&&(this.name_=this.constructor.name||"Unknown Tech")}triggerSourceset(e){this.isReady_||this.one("ready",()=>this.setTimeout(()=>this.triggerSourceset(e),1)),this.trigger({src:e,type:"sourceset"})}manualProgressOn(){this.on("durationchange",this.onDurationChange_),this.manualProgress=!0,this.one("ready",this.trackProgress_)}manualProgressOff(){this.manualProgress=!1,this.stopTrackingProgress(),this.off("durationchange",this.onDurationChange_)}trackProgress(e){this.stopTrackingProgress(),this.progressInterval=this.setInterval(ts(this,function(){const t=this.bufferedPercent();this.bufferedPercent_!==t&&this.trigger("progress"),this.bufferedPercent_=t,t===1&&this.stopTrackingProgress()}),500)}onDurationChange(e){this.duration_=this.duration()}buffered(){return Fr(0,0)}bufferedPercent(){return IC(this.buffered(),this.duration_)}stopTrackingProgress(){this.clearInterval(this.progressInterval)}manualTimeUpdatesOn(){this.manualTimeUpdates=!0,this.on("play",this.trackCurrentTime_),this.on("pause",this.stopTrackingCurrentTime_)}manualTimeUpdatesOff(){this.manualTimeUpdates=!1,this.stopTrackingCurrentTime(),this.off("play",this.trackCurrentTime_),this.off("pause",this.stopTrackingCurrentTime_)}trackCurrentTime(){this.currentTimeInterval&&this.stopTrackingCurrentTime(),this.currentTimeInterval=this.setInterval(function(){this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})},250)}stopTrackingCurrentTime(){this.clearInterval(this.currentTimeInterval),this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}dispose(){this.clearTracks(xr.names),this.manualProgress&&this.manualProgressOff(),this.manualTimeUpdates&&this.manualTimeUpdatesOff(),super.dispose()}clearTracks(e){e=[].concat(e),e.forEach(t=>{const i=this[`${t}Tracks`]()||[];let n=i.length;for(;n--;){const r=i[n];t==="text"&&this.removeRemoteTextTrack(r),i.removeTrack(r)}})}cleanupAutoTextTracks(){const e=this.autoRemoteTextTracks_||[];let t=e.length;for(;t--;){const i=e[t];this.removeRemoteTextTrack(i)}}reset(){}crossOrigin(){}setCrossOrigin(){}error(e){return e!==void 0&&(this.error_=new ms(e),this.trigger("error")),this.error_}played(){return this.hasStarted_?Fr(0,0):Fr()}play(){}setScrubbing(e){}scrubbing(){}setCurrentTime(e){this.manualTimeUpdates&&this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}initTrackListeners(){xr.names.forEach(e=>{const t=xr[e],i=()=>{this.trigger(`${e}trackchange`)},n=this[t.getterName]();n.addEventListener("removetrack",i),n.addEventListener("addtrack",i),this.on("dispose",()=>{n.removeEventListener("removetrack",i),n.removeEventListener("addtrack",i)})})}addWebVttScript_(){if(!de.WebVTT)if(at.body.contains(this.el())){if(!this.options_["vtt.js"]&&Cc(QS)&&Object.keys(QS).length>0){this.trigger("vttjsloaded");return}const e=at.createElement("script");e.src=this.options_["vtt.js"]||"https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js",e.onload=()=>{this.trigger("vttjsloaded")},e.onerror=()=>{this.trigger("vttjserror")},this.on("dispose",()=>{e.onload=null,e.onerror=null}),de.WebVTT=!0,this.el().parentNode.appendChild(e)}else this.ready(this.addWebVttScript_)}emulateTextTracks(){const e=this.textTracks(),t=this.remoteTextTracks(),i=u=>e.addTrack(u.track),n=u=>e.removeTrack(u.track);t.on("addtrack",i),t.on("removetrack",n),this.addWebVttScript_();const r=()=>this.trigger("texttrackchange"),o=()=>{r();for(let u=0;uthis.autoRemoteTextTracks_.addTrack(i.track)),i}removeRemoteTextTrack(e){const t=this.remoteTextTrackEls().getTrackElementByTrack_(e);this.remoteTextTrackEls().removeTrackElement_(t),this.remoteTextTracks().removeTrack(e),this.autoRemoteTextTracks_.removeTrack(e)}getVideoPlaybackQuality(){return{}}requestPictureInPicture(){return Promise.reject()}disablePictureInPicture(){return!0}setDisablePictureInPicture(){}requestVideoFrameCallback(e){const t=br();return!this.isReady_||this.paused()?(this.queuedHanders_.add(t),this.one("playing",()=>{this.queuedHanders_.has(t)&&(this.queuedHanders_.delete(t),e())})):this.requestNamedAnimationFrame(t,e),t}cancelVideoFrameCallback(e){this.queuedHanders_.has(e)?this.queuedHanders_.delete(e):this.cancelNamedAnimationFrame(e)}setPoster(){}playsinline(){}setPlaysinline(){}overrideNativeAudioTracks(e){}overrideNativeVideoTracks(e){}canPlayType(e){return""}static canPlayType(e){return""}static canPlaySource(e,t){return ni.canPlayType(e.type)}static isTech(e){return e.prototype instanceof ni||e instanceof ni||e===ni}static registerTech(e,t){if(ni.techs_||(ni.techs_={}),!ni.isTech(t))throw new Error(`Tech ${e} must be a Tech`);if(!ni.canPlayType)throw new Error("Techs must have a static canPlayType method on them");if(!ni.canPlaySource)throw new Error("Techs must have a static canPlaySource method on them");return e=bs(e),ni.techs_[e]=t,ni.techs_[ch(e)]=t,e!=="Tech"&&ni.defaultTechOrder_.push(e),t}static getTech(e){if(e){if(ni.techs_&&ni.techs_[e])return ni.techs_[e];if(e=bs(e),de&&de.videojs&&de.videojs[e])return fi.warn(`The ${e} tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)`),de.videojs[e]}}}_n.names.forEach(function(s){const e=_n[s];ni.prototype[e.getterName]=function(){return this[e.privateName]=this[e.privateName]||new e.ListClass,this[e.privateName]}});ni.prototype.featuresVolumeControl=!0;ni.prototype.featuresMuteControl=!0;ni.prototype.featuresFullscreenResize=!1;ni.prototype.featuresPlaybackRate=!1;ni.prototype.featuresProgressEvents=!1;ni.prototype.featuresSourceset=!1;ni.prototype.featuresTimeupdateEvents=!1;ni.prototype.featuresNativeTextTracks=!1;ni.prototype.featuresVideoFrameCallback=!1;ni.withSourceHandlers=function(s){s.registerSourceHandler=function(t,i){let n=s.sourceHandlers;n||(n=s.sourceHandlers=[]),i===void 0&&(i=n.length),n.splice(i,0,t)},s.canPlayType=function(t){const i=s.sourceHandlers||[];let n;for(let r=0;rHl(e,Jl[e.type],t,s),1)}function c4(s,e){s.forEach(t=>t.setTech&&t.setTech(e))}function d4(s,e,t){return s.reduceRight(hb(t),e[t]())}function h4(s,e,t,i){return e[t](s.reduce(hb(t),i))}function kE(s,e,t,i=null){const n="call"+bs(t),r=s.reduce(hb(n),i),o=r===cp,u=o?null:e[t](r);return p4(s,t,u,o),u}const f4={buffered:1,currentTime:1,duration:1,muted:1,played:1,paused:1,seekable:1,volume:1,ended:1},m4={setCurrentTime:1,setMuted:1,setVolume:1},DE={play:1,pause:1};function hb(s){return(e,t)=>e===cp?cp:t[s]?t[s](e):e}function p4(s,e,t,i){for(let n=s.length-1;n>=0;n--){const r=s[n];r[e]&&r[e](i,t)}}function g4(s){up.hasOwnProperty(s.id())&&delete up[s.id()]}function y4(s,e){const t=up[s.id()];let i=null;if(t==null)return i=e(s),up[s.id()]=[[e,i]],i;for(let n=0;n{if(!e)return"";if(s.cache_.source.src===e&&s.cache_.source.type)return s.cache_.source.type;const t=s.cache_.sources.filter(n=>n.src===e);if(t.length)return t[0].type;const i=s.$$("source");for(let n=0;n `;const RE=np?10009:rp?461:8,Gu={codes:{play:415,pause:19,ff:417,rw:412,back:RE},names:{415:"play",19:"pause",417:"ff",412:"rw",[RE]:"back"},isEventKey(s,e){return e=e.toLowerCase(),!!(this.names[s.keyCode]&&this.names[s.keyCode]===e)},getEventName(s){if(this.names[s.keyCode])return this.names[s.keyCode];if(this.codes[s.code]){const e=this.codes[s.code];return this.names[e]}return null}},IE=5;class T4 extends hr{constructor(e){super(),this.player_=e,this.focusableComponents=[],this.isListening_=!1,this.isPaused_=!1,this.onKeyDown_=this.onKeyDown_.bind(this),this.lastFocusedComponent_=null}start(){this.isListening_||(this.player_.on("keydown",this.onKeyDown_),this.player_.on("modalKeydown",this.onKeyDown_),this.player_.on("loadedmetadata",()=>{this.focus(this.updateFocusableComponents()[0])}),this.player_.on("modalclose",()=>{this.refocusComponent()}),this.player_.on("focusin",this.handlePlayerFocus_.bind(this)),this.player_.on("focusout",this.handlePlayerBlur_.bind(this)),this.isListening_=!0,this.player_.errorDisplay&&this.player_.errorDisplay.on("aftermodalfill",()=>{this.updateFocusableComponents(),this.focusableComponents.length&&(this.focusableComponents.length>1?this.focusableComponents[1].focus():this.focusableComponents[0].focus())}))}stop(){this.player_.off("keydown",this.onKeyDown_),this.isListening_=!1}onKeyDown_(e){const t=e.originalEvent?e.originalEvent:e;if(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(t.key)){if(this.isPaused_)return;t.preventDefault();const i=t.key.substring(5).toLowerCase();this.move(i)}else if(Gu.isEventKey(t,"play")||Gu.isEventKey(t,"pause")||Gu.isEventKey(t,"ff")||Gu.isEventKey(t,"rw")){t.preventDefault();const i=Gu.getEventName(t);this.performMediaAction_(i)}else Gu.isEventKey(t,"Back")&&e.target&&typeof e.target.closeable=="function"&&e.target.closeable()&&(t.preventDefault(),e.target.close())}performMediaAction_(e){if(this.player_)switch(e){case"play":this.player_.paused()&&this.player_.play();break;case"pause":this.player_.paused()||this.player_.pause();break;case"ff":this.userSeek_(this.player_.currentTime()+IE);break;case"rw":this.userSeek_(this.player_.currentTime()-IE);break}}userSeek_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&this.player_.liveTracker.nextSeekedFromUser(),this.player_.currentTime(e)}pause(){this.isPaused_=!0}resume(){this.isPaused_=!1}handlePlayerBlur_(e){const t=e.relatedTarget;let i=null;const n=this.getCurrentComponent(e.target);t&&(i=!!t.closest(".video-js"),t.classList.contains("vjs-text-track-settings")&&!this.isPaused_&&this.searchForTrackSelect_()),(!e.currentTarget.contains(e.relatedTarget)&&!i||!t)&&(n&&n.name()==="CloseButton"?this.refocusComponent():(this.pause(),n&&n.el()&&(this.lastFocusedComponent_=n)))}handlePlayerFocus_(){this.getCurrentComponent()&&this.getCurrentComponent().getIsFocusable()&&this.resume()}updateFocusableComponents(){const e=this.player_,t=[];function i(n){for(const r of n)r.hasOwnProperty("el_")&&r.getIsFocusable()&&r.getIsAvailableToBeFocused(r.el())&&t.push(r),r.hasOwnProperty("children_")&&r.children_.length>0&&i(r.children_)}return e.children_.forEach(n=>{if(n.hasOwnProperty("el_"))if(n.getIsFocusable&&n.getIsAvailableToBeFocused&&n.getIsFocusable()&&n.getIsAvailableToBeFocused(n.el())){t.push(n);return}else n.hasOwnProperty("children_")&&n.children_.length>0?i(n.children_):n.hasOwnProperty("items")&&n.items.length>0?i(n.items):this.findSuitableDOMChild(n)&&t.push(n);if(n.name_==="ErrorDisplay"&&n.opened_){const r=n.el_.querySelector(".vjs-errors-ok-button-container");r&&r.querySelectorAll("button").forEach((u,c)=>{t.push({name:()=>"ModalButton"+(c+1),el:()=>u,getPositions:()=>{const d=u.getBoundingClientRect(),f={x:d.x,y:d.y,width:d.width,height:d.height,top:d.top,right:d.right,bottom:d.bottom,left:d.left},p={x:d.left+d.width/2,y:d.top+d.height/2,width:0,height:0,top:d.top+d.height/2,right:d.left+d.width/2,bottom:d.top+d.height/2,left:d.left+d.width/2};return{boundingClientRect:f,center:p}},getIsAvailableToBeFocused:()=>!0,getIsFocusable:d=>!0,focus:()=>u.focus()})})}}),this.focusableComponents=t,this.focusableComponents}findSuitableDOMChild(e){function t(i){if(e.getIsFocusable(i)&&e.getIsAvailableToBeFocused(i))return i;for(let n=0;n0&&(this.focusableComponents=[],this.trigger({type:"focusableComponentsChanged",focusableComponents:this.focusableComponents}))}move(e){const t=this.getCurrentComponent();if(!t)return;const i=t.getPositions(),n=this.focusableComponents.filter(o=>o!==t&&this.isInDirection_(i.boundingClientRect,o.getPositions().boundingClientRect,e)),r=this.findBestCandidate_(i.center,n,e);r?this.focus(r):this.trigger({type:"endOfFocusableComponents",direction:e,focusedComponent:t})}findBestCandidate_(e,t,i){let n=1/0,r=null;for(const o of t){const u=o.getPositions().center,c=this.calculateDistance_(e,u,i);c=e.right;case"left":return t.right<=e.left;case"down":return t.top>=e.bottom;case"up":return t.bottom<=e.top;default:return!1}}refocusComponent(){if(this.lastFocusedComponent_){this.player_.userActive()||this.player_.userActive(!0),this.updateFocusableComponents();for(let e=0;ethis.handleMouseOver(i),this.handleMouseOut_=i=>this.handleMouseOut(i),this.handleClick_=i=>this.handleClick(i),this.handleKeyDown_=i=>this.handleKeyDown(i),this.emitTapEvents(),this.enable()}createEl(e="div",t={},i={}){t=Object.assign({className:this.buildCSSClass(),tabIndex:0},t),e==="button"&&fi.error(`Creating a ClickableComponent with an HTML element of ${e} is not supported; use a Button instead.`),i=Object.assign({role:"button"},i),this.tabIndex_=t.tabIndex;const n=Kt(e,t,i);return this.player_.options_.experimentalSvgIcons||n.appendChild(Kt("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),this.createControlTextEl(n),n}dispose(){this.controlTextEl_=null,super.dispose()}createControlTextEl(e){return this.controlTextEl_=Kt("span",{className:"vjs-control-text"},{"aria-live":"polite"}),e&&e.appendChild(this.controlTextEl_),this.controlText(this.controlText_,e),this.controlTextEl_}controlText(e,t=this.el()){if(e===void 0)return this.controlText_||"Need Text";const i=this.localize(e);this.controlText_=e,dl(this.controlTextEl_,i),!this.nonIconControl&&!this.player_.options_.noUITitleAttributes&&t.setAttribute("title",i)}buildCSSClass(){return`vjs-control vjs-button ${super.buildCSSClass()}`}enable(){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_))}disable(){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_)}handleLanguagechange(){this.controlText(this.controlText_)}handleClick(e){this.options_.clickHandler&&this.options_.clickHandler.call(this,arguments)}handleKeyDown(e){e.key===" "||e.key==="Enter"?(e.preventDefault(),e.stopPropagation(),this.trigger("click")):super.handleKeyDown(e)}}$e.registerComponent("ClickableComponent",ag);class ix extends ag{constructor(e,t){super(e,t),this.update(),this.update_=i=>this.update(i),e.on("posterchange",this.update_)}dispose(){this.player().off("posterchange",this.update_),super.dispose()}createEl(){return Kt("div",{className:"vjs-poster"})}crossOrigin(e){if(typeof e>"u")return this.$("img")?this.$("img").crossOrigin:this.player_.tech_&&this.player_.tech_.isReady_?this.player_.crossOrigin():this.player_.options_.crossOrigin||this.player_.options_.crossorigin||null;if(e!==null&&e!=="anonymous"&&e!=="use-credentials"){this.player_.log.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${e}"`);return}this.$("img")&&(this.$("img").crossOrigin=e)}update(e){const t=this.player().poster();this.setSrc(t),t?this.show():this.hide()}setSrc(e){if(!e){this.el_.textContent="";return}this.$("img")||this.el_.appendChild(Kt("picture",{className:"vjs-poster",tabIndex:-1},{},Kt("img",{loading:"lazy",crossOrigin:this.crossOrigin()},{alt:""}))),this.$("img").src=e}handleClick(e){this.player_.controls()&&(this.player_.tech(!0)&&this.player_.tech(!0).focus(),this.player_.paused()?da(this.player_.play()):this.player_.pause())}}ix.prototype.crossorigin=ix.prototype.crossOrigin;$e.registerComponent("PosterImage",ix);const vr="#222",NE="#ccc",S4={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 Gy(s,e){let t;if(s.length===4)t=s[1]+s[1]+s[2]+s[2]+s[3]+s[3];else if(s.length===7)t=s.slice(1);else throw new Error("Invalid color code provided, "+s+"; must be formatted as e.g. #f0e or #f604e2.");return"rgba("+parseInt(t.slice(0,2),16)+","+parseInt(t.slice(2,4),16)+","+parseInt(t.slice(4,6),16)+","+e+")"}function ia(s,e,t){try{s.style[e]=t}catch{return}}function OE(s){return s?`${s}px`:""}class E4 extends $e{constructor(e,t,i){super(e,t,i);const n=o=>this.updateDisplay(o),r=o=>{this.updateDisplayOverlay(),this.updateDisplay(o)};e.on("loadstart",o=>this.toggleDisplay(o)),e.on("useractive",n),e.on("userinactive",n),e.on("texttrackchange",n),e.on("loadedmetadata",o=>{this.updateDisplayOverlay(),this.preselectTrack(o)}),e.ready(ts(this,function(){if(e.tech_&&e.tech_.featuresNativeTextTracks){this.hide();return}e.on("fullscreenchange",r),e.on("playerresize",r);const o=de.screen.orientation||de,u=de.screen.orientation?"change":"orientationchange";o.addEventListener(u,r),e.on("dispose",()=>o.removeEventListener(u,r));const c=this.options_.playerOptions.tracks||[];for(let d=0;d0&&u.forEach(f=>{if(f.style.inset){const p=f.style.inset.split(" ");p.length===3&&Object.assign(f.style,{top:p[0],right:p[1],bottom:p[2],left:"unset"})}})}}updateDisplayOverlay(){if(!this.player_.videoHeight()||!de.CSS.supports("inset-inline: 10px"))return;const e=this.player_.currentWidth(),t=this.player_.currentHeight(),i=e/t,n=this.player_.videoWidth()/this.player_.videoHeight();let r=0,o=0;Math.abs(i-n)>.1&&(i>n?r=Math.round((e-t*n)/2):o=Math.round((t-e/n)/2)),ia(this.el_,"insetInline",OE(r)),ia(this.el_,"insetBlock",OE(o))}updateDisplayState(e){const t=this.player_.textTrackSettings.getValues(),i=e.activeCues;let n=i.length;for(;n--;){const r=i[n];if(!r)continue;const o=r.displayState;if(t.color&&(o.firstChild.style.color=t.color),t.textOpacity&&ia(o.firstChild,"color",Gy(t.color||"#fff",t.textOpacity)),t.backgroundColor&&(o.firstChild.style.backgroundColor=t.backgroundColor),t.backgroundOpacity&&ia(o.firstChild,"backgroundColor",Gy(t.backgroundColor||"#000",t.backgroundOpacity)),t.windowColor&&(t.windowOpacity?ia(o,"backgroundColor",Gy(t.windowColor,t.windowOpacity)):o.style.backgroundColor=t.windowColor),t.edgeStyle&&(t.edgeStyle==="dropshadow"?o.firstChild.style.textShadow=`2px 2px 3px ${vr}, 2px 2px 4px ${vr}, 2px 2px 5px ${vr}`:t.edgeStyle==="raised"?o.firstChild.style.textShadow=`1px 1px ${vr}, 2px 2px ${vr}, 3px 3px ${vr}`:t.edgeStyle==="depressed"?o.firstChild.style.textShadow=`1px 1px ${NE}, 0 1px ${NE}, -1px -1px ${vr}, 0 -1px ${vr}`:t.edgeStyle==="uniform"&&(o.firstChild.style.textShadow=`0 0 4px ${vr}, 0 0 4px ${vr}, 0 0 4px ${vr}, 0 0 4px ${vr}`)),t.fontPercent&&t.fontPercent!==1){const u=de.parseFloat(o.style.fontSize);o.style.fontSize=u*t.fontPercent+"px",o.style.height="auto",o.style.top="auto"}t.fontFamily&&t.fontFamily!=="default"&&(t.fontFamily==="small-caps"?o.firstChild.style.fontVariant="small-caps":o.firstChild.style.fontFamily=S4[t.fontFamily])}}updateForTrack(e){if(Array.isArray(e)||(e=[e]),typeof de.WebVTT!="function"||e.every(i=>!i.activeCues))return;const t=[];for(let i=0;ithis.handleMouseDown(i))}buildCSSClass(){return"vjs-big-play-button"}handleClick(e){const t=this.player_.play();if(e.type==="tap"||this.mouseused_&&"clientX"in e&&"clientY"in e){da(t),this.player_.tech(!0)&&this.player_.tech(!0).focus();return}const i=this.player_.getChild("controlBar"),n=i&&i.getChild("playToggle");if(!n){this.player_.tech(!0).focus();return}const r=()=>n.focus();dh(t)?t.then(r,()=>{}):this.setTimeout(r,1)}handleKeyDown(e){this.mouseused_=!1,super.handleKeyDown(e)}handleMouseDown(e){this.mouseused_=!0}}UC.prototype.controlText_="Play Video";$e.registerComponent("BigPlayButton",UC);class A4 extends mn{constructor(e,t){super(e,t),this.setIcon("cancel"),this.controlText(t&&t.controlText||this.localize("Close"))}buildCSSClass(){return`vjs-close-button ${super.buildCSSClass()}`}handleClick(e){this.trigger({type:"close",bubbles:!1})}handleKeyDown(e){e.key==="Escape"?(e.preventDefault(),e.stopPropagation(),this.trigger("click")):super.handleKeyDown(e)}}$e.registerComponent("CloseButton",A4);class jC extends mn{constructor(e,t={}){super(e,t),t.replay=t.replay===void 0||t.replay,this.setIcon("play"),this.on(e,"play",i=>this.handlePlay(i)),this.on(e,"pause",i=>this.handlePause(i)),t.replay&&this.on(e,"ended",i=>this.handleEnded(i))}buildCSSClass(){return`vjs-play-control ${super.buildCSSClass()}`}handleClick(e){this.player_.paused()?da(this.player_.play()):this.player_.pause()}handleSeeked(e){this.removeClass("vjs-ended"),this.player_.paused()?this.handlePause(e):this.handlePlay(e)}handlePlay(e){this.removeClass("vjs-ended","vjs-paused"),this.addClass("vjs-playing"),this.setIcon("pause"),this.controlText("Pause")}handlePause(e){this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.setIcon("play"),this.controlText("Play")}handleEnded(e){this.removeClass("vjs-playing"),this.addClass("vjs-ended"),this.setIcon("replay"),this.controlText("Replay"),this.one(this.player_,"seeked",t=>this.handleSeeked(t))}}jC.prototype.controlText_="Play";$e.registerComponent("PlayToggle",jC);class jc extends $e{constructor(e,t){super(e,t),this.on(e,["timeupdate","ended","seeking"],i=>this.update(i)),this.updateTextNode_()}createEl(){const e=this.buildCSSClass(),t=super.createEl("div",{className:`${e} vjs-time-control vjs-control`}),i=Kt("span",{className:"vjs-control-text",textContent:`${this.localize(this.labelText_)} `},{role:"presentation"});return t.appendChild(i),this.contentEl_=Kt("span",{className:`${e}-display`},{role:"presentation"}),t.appendChild(this.contentEl_),t}dispose(){this.contentEl_=null,this.textNode_=null,super.dispose()}update(e){!this.player_.options_.enableSmoothSeeking&&e.type==="seeking"||this.updateContent(e)}updateTextNode_(e=0){e=nu(e),this.formattedTime_!==e&&(this.formattedTime_=e,this.requestNamedAnimationFrame("TimeDisplay#updateTextNode_",()=>{if(!this.contentEl_)return;let t=this.textNode_;t&&this.contentEl_.firstChild!==t&&(t=null,fi.warn("TimeDisplay#updateTextnode_: Prevented replacement of text node element since it was no longer a child of this node. Appending a new node instead.")),this.textNode_=at.createTextNode(this.formattedTime_),this.textNode_&&(t?this.contentEl_.replaceChild(this.textNode_,t):this.contentEl_.appendChild(this.textNode_))}))}updateContent(e){}}jc.prototype.labelText_="Time";jc.prototype.controlText_="Time";$e.registerComponent("TimeDisplay",jc);class fb extends jc{buildCSSClass(){return"vjs-current-time"}updateContent(e){let t;this.player_.ended()?t=this.player_.duration():e&&e.target&&typeof e.target.pendingSeekTime=="function"?t=e.target.pendingSeekTime():t=this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime(),this.updateTextNode_(t)}}fb.prototype.labelText_="Current Time";fb.prototype.controlText_="Current Time";$e.registerComponent("CurrentTimeDisplay",fb);class mb extends jc{constructor(e,t){super(e,t);const i=n=>this.updateContent(n);this.on(e,"durationchange",i),this.on(e,"loadstart",i),this.on(e,"loadedmetadata",i)}buildCSSClass(){return"vjs-duration"}updateContent(e){const t=this.player_.duration();this.updateTextNode_(t)}}mb.prototype.labelText_="Duration";mb.prototype.controlText_="Duration";$e.registerComponent("DurationDisplay",mb);class C4 extends $e{createEl(){const e=super.createEl("div",{className:"vjs-time-control vjs-time-divider"},{"aria-hidden":!0}),t=super.createEl("div"),i=super.createEl("span",{textContent:"/"});return t.appendChild(i),e.appendChild(t),e}}$e.registerComponent("TimeDivider",C4);class pb extends jc{constructor(e,t){super(e,t),this.on(e,"durationchange",i=>this.updateContent(i))}buildCSSClass(){return"vjs-remaining-time"}createEl(){const e=super.createEl();return this.options_.displayNegative!==!1&&e.insertBefore(Kt("span",{},{"aria-hidden":!0},"-"),this.contentEl_),e}updateContent(e){if(typeof this.player_.duration()!="number")return;let t;this.player_.ended()?t=0:this.player_.remainingTimeDisplay?t=this.player_.remainingTimeDisplay():t=this.player_.remainingTime(),this.updateTextNode_(t)}}pb.prototype.labelText_="Remaining Time";pb.prototype.controlText_="Remaining Time";$e.registerComponent("RemainingTimeDisplay",pb);class k4 extends $e{constructor(e,t){super(e,t),this.updateShowing(),this.on(this.player(),"durationchange",i=>this.updateShowing(i))}createEl(){const e=super.createEl("div",{className:"vjs-live-control vjs-control"});return this.contentEl_=Kt("div",{className:"vjs-live-display"},{"aria-live":"off"}),this.contentEl_.appendChild(Kt("span",{className:"vjs-control-text",textContent:`${this.localize("Stream Type")} `})),this.contentEl_.appendChild(at.createTextNode(this.localize("LIVE"))),e.appendChild(this.contentEl_),e}dispose(){this.contentEl_=null,super.dispose()}updateShowing(e){this.player().duration()===1/0?this.show():this.hide()}}$e.registerComponent("LiveDisplay",k4);class $C extends mn{constructor(e,t){super(e,t),this.updateLiveEdgeStatus(),this.player_.liveTracker&&(this.updateLiveEdgeStatusHandler_=i=>this.updateLiveEdgeStatus(i),this.on(this.player_.liveTracker,"liveedgechange",this.updateLiveEdgeStatusHandler_))}createEl(){const e=super.createEl("button",{className:"vjs-seek-to-live-control vjs-control"});return this.setIcon("circle",e),this.textEl_=Kt("span",{className:"vjs-seek-to-live-text",textContent:this.localize("LIVE")},{"aria-hidden":"true"}),e.appendChild(this.textEl_),e}updateLiveEdgeStatus(){!this.player_.liveTracker||this.player_.liveTracker.atLiveEdge()?(this.setAttribute("aria-disabled",!0),this.addClass("vjs-at-live-edge"),this.controlText("Seek to live, currently playing live")):(this.setAttribute("aria-disabled",!1),this.removeClass("vjs-at-live-edge"),this.controlText("Seek to live, currently behind live"))}handleClick(){this.player_.liveTracker.seekToLiveEdge()}dispose(){this.player_.liveTracker&&this.off(this.player_.liveTracker,"liveedgechange",this.updateLiveEdgeStatusHandler_),this.textEl_=null,super.dispose()}}$C.prototype.controlText_="Seek to live, currently playing live";$e.registerComponent("SeekToLive",$C);function Mh(s,e,t){return s=Number(s),Math.min(t,Math.max(e,isNaN(s)?e:s))}var D4=Object.freeze({__proto__:null,clamp:Mh});class gb extends $e{constructor(e,t){super(e,t),this.handleMouseDown_=i=>this.handleMouseDown(i),this.handleMouseUp_=i=>this.handleMouseUp(i),this.handleKeyDown_=i=>this.handleKeyDown(i),this.handleClick_=i=>this.handleClick(i),this.handleMouseMove_=i=>this.handleMouseMove(i),this.update_=i=>this.update(i),this.bar=this.getChild(this.options_.barName),this.vertical(!!this.options_.vertical),this.enable()}enabled(){return this.enabled_}enable(){this.enabled()||(this.on("mousedown",this.handleMouseDown_),this.on("touchstart",this.handleMouseDown_),this.on("keydown",this.handleKeyDown_),this.on("click",this.handleClick_),this.on(this.player_,"controlsvisible",this.update),this.playerEvent&&this.on(this.player_,this.playerEvent,this.update),this.removeClass("disabled"),this.setAttribute("tabindex",0),this.enabled_=!0)}disable(){if(!this.enabled())return;const e=this.bar.el_.ownerDocument;this.off("mousedown",this.handleMouseDown_),this.off("touchstart",this.handleMouseDown_),this.off("keydown",this.handleKeyDown_),this.off("click",this.handleClick_),this.off(this.player_,"controlsvisible",this.update_),this.off(e,"mousemove",this.handleMouseMove_),this.off(e,"mouseup",this.handleMouseUp_),this.off(e,"touchmove",this.handleMouseMove_),this.off(e,"touchend",this.handleMouseUp_),this.removeAttribute("tabindex"),this.addClass("disabled"),this.playerEvent&&this.off(this.player_,this.playerEvent,this.update),this.enabled_=!1}createEl(e,t={},i={}){return t.className=t.className+" vjs-slider",t=Object.assign({tabIndex:0},t),i=Object.assign({role:"slider","aria-valuenow":0,"aria-valuemin":0,"aria-valuemax":100},i),super.createEl(e,t,i)}handleMouseDown(e){const t=this.bar.el_.ownerDocument;e.type==="mousedown"&&e.preventDefault(),e.type==="touchstart"&&!Ta&&e.preventDefault(),fC(),this.addClass("vjs-sliding"),this.trigger("slideractive"),this.on(t,"mousemove",this.handleMouseMove_),this.on(t,"mouseup",this.handleMouseUp_),this.on(t,"touchmove",this.handleMouseMove_),this.on(t,"touchend",this.handleMouseUp_),this.handleMouseMove(e,!0)}handleMouseMove(e){}handleMouseUp(e){const t=this.bar.el_.ownerDocument;mC(),this.removeClass("vjs-sliding"),this.trigger("sliderinactive"),this.off(t,"mousemove",this.handleMouseMove_),this.off(t,"mouseup",this.handleMouseUp_),this.off(t,"touchmove",this.handleMouseMove_),this.off(t,"touchend",this.handleMouseUp_),this.update()}update(){if(!this.el_||!this.bar)return;const e=this.getProgress();return e===this.progress_||(this.progress_=e,this.requestNamedAnimationFrame("Slider#update",()=>{const t=this.vertical()?"height":"width";this.bar.el().style[t]=(e*100).toFixed(2)+"%"})),e}getProgress(){return Number(Mh(this.getPercent(),0,1).toFixed(4))}calculateDistance(e){const t=eg(this.el_,e);return this.vertical()?t.y:t.x}handleKeyDown(e){const t=this.options_.playerOptions.spatialNavigation,i=t&&t.enabled,n=t&&t.horizontalSeek;i?n&&e.key==="ArrowLeft"||!n&&e.key==="ArrowDown"?(e.preventDefault(),e.stopPropagation(),this.stepBack()):n&&e.key==="ArrowRight"||!n&&e.key==="ArrowUp"?(e.preventDefault(),e.stopPropagation(),this.stepForward()):(this.pendingSeekTime()&&(this.pendingSeekTime(null),this.userSeek_(this.player_.currentTime())),super.handleKeyDown(e)):e.key==="ArrowLeft"||e.key==="ArrowDown"?(e.preventDefault(),e.stopPropagation(),this.stepBack()):e.key==="ArrowUp"||e.key==="ArrowRight"?(e.preventDefault(),e.stopPropagation(),this.stepForward()):super.handleKeyDown(e)}handleClick(e){e.stopPropagation(),e.preventDefault()}vertical(e){if(e===void 0)return this.vertical_||!1;this.vertical_=!!e,this.vertical_?this.addClass("vjs-slider-vertical"):this.addClass("vjs-slider-horizontal")}}$e.registerComponent("Slider",gb);const zy=(s,e)=>Mh(s/e*100,0,100).toFixed(2)+"%";class L4 extends $e{constructor(e,t){super(e,t),this.partEls_=[],this.on(e,"progress",i=>this.update(i))}createEl(){const e=super.createEl("div",{className:"vjs-load-progress"}),t=Kt("span",{className:"vjs-control-text"}),i=Kt("span",{textContent:this.localize("Loaded")}),n=at.createTextNode(": ");return this.percentageEl_=Kt("span",{className:"vjs-control-text-loaded-percentage",textContent:"0%"}),e.appendChild(t),t.appendChild(i),t.appendChild(n),t.appendChild(this.percentageEl_),e}dispose(){this.partEls_=null,this.percentageEl_=null,super.dispose()}update(e){this.requestNamedAnimationFrame("LoadProgressBar#update",()=>{const t=this.player_.liveTracker,i=this.player_.buffered(),n=t&&t.isLive()?t.seekableEnd():this.player_.duration(),r=this.player_.bufferedEnd(),o=this.partEls_,u=zy(r,n);this.percent_!==u&&(this.el_.style.width=u,dl(this.percentageEl_,u),this.percent_=u);for(let c=0;ci.length;c--)this.el_.removeChild(o[c-1]);o.length=i.length})}}$e.registerComponent("LoadProgressBar",L4);class R4 extends $e{constructor(e,t){super(e,t),this.update=_a(ts(this,this.update),Tr)}createEl(){return super.createEl("div",{className:"vjs-time-tooltip"},{"aria-hidden":"true"})}update(e,t,i){const n=bh(this.el_),r=Dc(this.player_.el()),o=e.width*t;if(!r||!n)return;let u=e.left-r.left+o,c=e.width-o+(r.right-e.right);c||(c=e.width-o,u=o);let d=n.width/2;un.width&&(d=n.width),d=Math.round(d),this.el_.style.right=`-${d}px`,this.write(i)}write(e){dl(this.el_,e)}updateTime(e,t,i,n){this.requestNamedAnimationFrame("TimeTooltip#updateTime",()=>{let r;const o=this.player_.duration();if(this.player_.liveTracker&&this.player_.liveTracker.isLive()){const u=this.player_.liveTracker.liveWindow(),c=u-t*u;r=(c<1?"":"-")+nu(c,u)}else r=nu(i,o);this.update(e,t,r),n&&n()})}}$e.registerComponent("TimeTooltip",R4);class yb extends $e{constructor(e,t){super(e,t),this.setIcon("circle"),this.update=_a(ts(this,this.update),Tr)}createEl(){return super.createEl("div",{className:"vjs-play-progress vjs-slider-bar"},{"aria-hidden":"true"})}update(e,t,i){const n=this.getChild("timeTooltip");if(!n)return;const r=i&&i.target&&typeof i.target.pendingSeekTime=="function"?i.target.pendingSeekTime():this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime();n.updateTime(e,t,r)}}yb.prototype.options_={children:[]};!hn&&!Ur&&yb.prototype.options_.children.push("timeTooltip");$e.registerComponent("PlayProgressBar",yb);class HC extends $e{constructor(e,t){super(e,t),this.update=_a(ts(this,this.update),Tr)}createEl(){return super.createEl("div",{className:"vjs-mouse-display"})}update(e,t){const i=t*this.player_.duration();this.getChild("timeTooltip").updateTime(e,t,i,()=>{this.el_.style.left=`${e.width*t}px`})}}HC.prototype.options_={children:["timeTooltip"]};$e.registerComponent("MouseTimeDisplay",HC);class og extends gb{constructor(e,t){t=Gi(og.prototype.options_,t),t.children=[...t.children];const i=e.options_.disableSeekWhileScrubbingOnMobile&&(hn||Ur)||e.options_.disableSeekWhileScrubbingOnSTV;(!hn&&!Ur||i)&&t.children.splice(1,0,"mouseTimeDisplay"),super(e,t),this.shouldDisableSeekWhileScrubbing_=i,this.pendingSeekTime_=null,this.setEventHandlers_()}setEventHandlers_(){this.update_=ts(this,this.update),this.update=_a(this.update_,Tr),this.on(this.player_,["durationchange","timeupdate"],this.update),this.on(this.player_,["ended"],this.update_),this.player_.liveTracker&&this.on(this.player_.liveTracker,"liveedgechange",this.update),this.updateInterval=null,this.enableIntervalHandler_=e=>this.enableInterval_(e),this.disableIntervalHandler_=e=>this.disableInterval_(e),this.on(this.player_,["playing"],this.enableIntervalHandler_),this.on(this.player_,["ended","pause","waiting"],this.disableIntervalHandler_),"hidden"in at&&"visibilityState"in at&&this.on(at,"visibilitychange",this.toggleVisibility_)}toggleVisibility_(e){at.visibilityState==="hidden"?(this.cancelNamedAnimationFrame("SeekBar#update"),this.cancelNamedAnimationFrame("Slider#update"),this.disableInterval_(e)):(!this.player_.ended()&&!this.player_.paused()&&this.enableInterval_(),this.update())}enableInterval_(){this.updateInterval||(this.updateInterval=this.setInterval(this.update,Tr))}disableInterval_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&e&&e.type!=="ended"||this.updateInterval&&(this.clearInterval(this.updateInterval),this.updateInterval=null)}createEl(){return super.createEl("div",{className:"vjs-progress-holder"},{"aria-label":this.localize("Progress Bar")})}update(e){if(at.visibilityState==="hidden")return;const t=super.update();return this.requestNamedAnimationFrame("SeekBar#update",()=>{const i=this.player_.ended()?this.player_.duration():this.getCurrentTime_(),n=this.player_.liveTracker;let r=this.player_.duration();n&&n.isLive()&&(r=this.player_.liveTracker.liveCurrentTime()),this.percent_!==t&&(this.el_.setAttribute("aria-valuenow",(t*100).toFixed(2)),this.percent_=t),(this.currentTime_!==i||this.duration_!==r)&&(this.el_.setAttribute("aria-valuetext",this.localize("progress bar timing: currentTime={1} duration={2}",[nu(i,r),nu(r,r)],"{1} of {2}")),this.currentTime_=i,this.duration_=r),this.bar&&this.bar.update(Dc(this.el()),this.getProgress(),e)}),t}userSeek_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&this.player_.liveTracker.nextSeekedFromUser(),this.player_.currentTime(e)}getCurrentTime_(){return this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime()}pendingSeekTime(e){if(e!==void 0)if(e!==null){const t=this.player_.duration();this.pendingSeekTime_=Math.max(0,Math.min(e,t))}else this.pendingSeekTime_=null;return this.pendingSeekTime_}getPercent(){if(this.pendingSeekTime()!==null)return this.pendingSeekTime()/this.player_.duration();const e=this.getCurrentTime_();let t;const i=this.player_.liveTracker;return i&&i.isLive()?(t=(e-i.seekableStart())/i.liveWindow(),i.atLiveEdge()&&(t=1)):t=e/this.player_.duration(),t}handleMouseDown(e){Th(e)&&(e.stopPropagation(),this.videoWasPlaying=!this.player_.paused(),this.shouldDisableSeekWhileScrubbing_||this.player_.pause(),super.handleMouseDown(e))}handleMouseMove(e,t=!1){if(!Th(e)||isNaN(this.player_.duration()))return;!t&&!this.player_.scrubbing()&&this.player_.scrubbing(!0);let i;const n=this.calculateDistance(e),r=this.player_.liveTracker;if(!r||!r.isLive())i=n*this.player_.duration(),i===this.player_.duration()&&(i=i-.1);else{if(n>=.99){r.seekToLiveEdge();return}const o=r.seekableStart(),u=r.liveCurrentTime();if(i=o+n*r.liveWindow(),i>=u&&(i=u),i<=o&&(i=o+.1),i===1/0)return}this.shouldDisableSeekWhileScrubbing_?this.pendingSeekTime(i):this.userSeek_(i),this.player_.options_.enableSmoothSeeking&&this.update()}enable(){super.enable();const e=this.getChild("mouseTimeDisplay");e&&e.show()}disable(){super.disable();const e=this.getChild("mouseTimeDisplay");e&&e.hide()}handleMouseUp(e){super.handleMouseUp(e),e&&e.stopPropagation(),this.player_.scrubbing(!1),this.pendingSeekTime()!==null&&(this.userSeek_(this.pendingSeekTime()),this.pendingSeekTime(null)),this.player_.trigger({type:"timeupdate",target:this,manuallyTriggered:!0}),this.videoWasPlaying?da(this.player_.play()):this.update_()}handlePendingSeek_(e){this.player_.paused()||this.player_.pause();const t=this.pendingSeekTime()!==null?this.pendingSeekTime():this.player_.currentTime();this.pendingSeekTime(t+e),this.player_.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}stepForward(){this.shouldDisableSeekWhileScrubbing_?this.handlePendingSeek_(this.options().stepSeconds):this.userSeek_(this.player_.currentTime()+this.options().stepSeconds)}stepBack(){this.shouldDisableSeekWhileScrubbing_?this.handlePendingSeek_(-this.options().stepSeconds):this.userSeek_(this.player_.currentTime()-this.options().stepSeconds)}handleAction(e){this.pendingSeekTime()!==null&&(this.userSeek_(this.pendingSeekTime()),this.pendingSeekTime(null)),this.player_.paused()?this.player_.play():this.player_.pause()}handleKeyDown(e){const t=this.player_.liveTracker;if(e.key===" "||e.key==="Enter")e.preventDefault(),e.stopPropagation(),this.handleAction(e);else if(e.key==="Home")e.preventDefault(),e.stopPropagation(),this.userSeek_(0);else if(e.key==="End")e.preventDefault(),e.stopPropagation(),t&&t.isLive()?this.userSeek_(t.liveCurrentTime()):this.userSeek_(this.player_.duration());else if(/^[0-9]$/.test(e.key)){e.preventDefault(),e.stopPropagation();const i=parseInt(e.key,10)*.1;t&&t.isLive()?this.userSeek_(t.seekableStart()+t.liveWindow()*i):this.userSeek_(this.player_.duration()*i)}else e.key==="PageDown"?(e.preventDefault(),e.stopPropagation(),this.userSeek_(this.player_.currentTime()-this.options().stepSeconds*this.options().pageMultiplier)):e.key==="PageUp"?(e.preventDefault(),e.stopPropagation(),this.userSeek_(this.player_.currentTime()+this.options().stepSeconds*this.options().pageMultiplier)):super.handleKeyDown(e)}dispose(){this.disableInterval_(),this.off(this.player_,["durationchange","timeupdate"],this.update),this.off(this.player_,["ended"],this.update_),this.player_.liveTracker&&this.off(this.player_.liveTracker,"liveedgechange",this.update),this.off(this.player_,["playing"],this.enableIntervalHandler_),this.off(this.player_,["ended","pause","waiting"],this.disableIntervalHandler_),"hidden"in at&&"visibilityState"in at&&this.off(at,"visibilitychange",this.toggleVisibility_),super.dispose()}}og.prototype.options_={children:["loadProgressBar","playProgressBar"],barName:"playProgressBar",stepSeconds:5,pageMultiplier:12};$e.registerComponent("SeekBar",og);class VC extends $e{constructor(e,t){super(e,t),this.handleMouseMove=_a(ts(this,this.handleMouseMove),Tr),this.throttledHandleMouseSeek=_a(ts(this,this.handleMouseSeek),Tr),this.handleMouseUpHandler_=i=>this.handleMouseUp(i),this.handleMouseDownHandler_=i=>this.handleMouseDown(i),this.enable()}createEl(){return super.createEl("div",{className:"vjs-progress-control vjs-control"})}handleMouseMove(e){const t=this.getChild("seekBar");if(!t)return;const i=t.getChild("playProgressBar"),n=t.getChild("mouseTimeDisplay");if(!i&&!n)return;const r=t.el(),o=bh(r);let u=eg(r,e).x;u=Mh(u,0,1),n&&n.update(o,u),i&&i.update(o,t.getProgress())}handleMouseSeek(e){const t=this.getChild("seekBar");t&&t.handleMouseMove(e)}enabled(){return this.enabled_}disable(){if(this.children().forEach(e=>e.disable&&e.disable()),!!this.enabled()&&(this.off(["mousedown","touchstart"],this.handleMouseDownHandler_),this.off(this.el_,["mousemove","touchmove"],this.handleMouseMove),this.removeListenersAddedOnMousedownAndTouchstart(),this.addClass("disabled"),this.enabled_=!1,this.player_.scrubbing())){const e=this.getChild("seekBar");this.player_.scrubbing(!1),e.videoWasPlaying&&da(this.player_.play())}}enable(){this.children().forEach(e=>e.enable&&e.enable()),!this.enabled()&&(this.on(["mousedown","touchstart"],this.handleMouseDownHandler_),this.on(this.el_,["mousemove","touchmove"],this.handleMouseMove),this.removeClass("disabled"),this.enabled_=!0)}removeListenersAddedOnMousedownAndTouchstart(){const e=this.el_.ownerDocument;this.off(e,"mousemove",this.throttledHandleMouseSeek),this.off(e,"touchmove",this.throttledHandleMouseSeek),this.off(e,"mouseup",this.handleMouseUpHandler_),this.off(e,"touchend",this.handleMouseUpHandler_)}handleMouseDown(e){const t=this.el_.ownerDocument,i=this.getChild("seekBar");i&&i.handleMouseDown(e),this.on(t,"mousemove",this.throttledHandleMouseSeek),this.on(t,"touchmove",this.throttledHandleMouseSeek),this.on(t,"mouseup",this.handleMouseUpHandler_),this.on(t,"touchend",this.handleMouseUpHandler_)}handleMouseUp(e){const t=this.getChild("seekBar");t&&t.handleMouseUp(e),this.removeListenersAddedOnMousedownAndTouchstart()}}VC.prototype.options_={children:["seekBar"]};$e.registerComponent("ProgressControl",VC);class GC extends mn{constructor(e,t){super(e,t),this.setIcon("picture-in-picture-enter"),this.on(e,["enterpictureinpicture","leavepictureinpicture"],i=>this.handlePictureInPictureChange(i)),this.on(e,["disablepictureinpicturechanged","loadedmetadata"],i=>this.handlePictureInPictureEnabledChange(i)),this.on(e,["loadedmetadata","audioonlymodechange","audiopostermodechange"],()=>this.handlePictureInPictureAudioModeChange()),this.disable()}buildCSSClass(){return`vjs-picture-in-picture-control vjs-hidden ${super.buildCSSClass()}`}handlePictureInPictureAudioModeChange(){if(!(this.player_.currentType().substring(0,5)==="audio"||this.player_.audioPosterMode()||this.player_.audioOnlyMode())){this.show();return}this.player_.isInPictureInPicture()&&this.player_.exitPictureInPicture(),this.hide()}handlePictureInPictureEnabledChange(){at.pictureInPictureEnabled&&this.player_.disablePictureInPicture()===!1||this.player_.options_.enableDocumentPictureInPicture&&"documentPictureInPicture"in de?this.enable():this.disable()}handlePictureInPictureChange(e){this.player_.isInPictureInPicture()?(this.setIcon("picture-in-picture-exit"),this.controlText("Exit Picture-in-Picture")):(this.setIcon("picture-in-picture-enter"),this.controlText("Picture-in-Picture")),this.handlePictureInPictureEnabledChange()}handleClick(e){this.player_.isInPictureInPicture()?this.player_.exitPictureInPicture():this.player_.requestPictureInPicture()}show(){typeof at.exitPictureInPicture=="function"&&super.show()}}GC.prototype.controlText_="Picture-in-Picture";$e.registerComponent("PictureInPictureToggle",GC);class zC extends mn{constructor(e,t){super(e,t),this.setIcon("fullscreen-enter"),this.on(e,"fullscreenchange",i=>this.handleFullscreenChange(i)),at[e.fsApi_.fullscreenEnabled]===!1&&this.disable()}buildCSSClass(){return`vjs-fullscreen-control ${super.buildCSSClass()}`}handleFullscreenChange(e){this.player_.isFullscreen()?(this.controlText("Exit Fullscreen"),this.setIcon("fullscreen-exit")):(this.controlText("Fullscreen"),this.setIcon("fullscreen-enter"))}handleClick(e){this.player_.isFullscreen()?this.player_.exitFullscreen():this.player_.requestFullscreen()}}zC.prototype.controlText_="Fullscreen";$e.registerComponent("FullscreenToggle",zC);const I4=function(s,e){e.tech_&&!e.tech_.featuresVolumeControl&&s.addClass("vjs-hidden"),s.on(e,"loadstart",function(){e.tech_.featuresVolumeControl?s.removeClass("vjs-hidden"):s.addClass("vjs-hidden")})};class N4 extends $e{createEl(){const e=super.createEl("div",{className:"vjs-volume-level"});return this.setIcon("circle",e),e.appendChild(super.createEl("span",{className:"vjs-control-text"})),e}}$e.registerComponent("VolumeLevel",N4);class O4 extends $e{constructor(e,t){super(e,t),this.update=_a(ts(this,this.update),Tr)}createEl(){return super.createEl("div",{className:"vjs-volume-tooltip"},{"aria-hidden":"true"})}update(e,t,i,n){if(!i){const r=Dc(this.el_),o=Dc(this.player_.el()),u=e.width*t;if(!o||!r)return;const c=e.left-o.left+u,d=e.width-u+(o.right-e.right);let f=r.width/2;cr.width&&(f=r.width),this.el_.style.right=`-${f}px`}this.write(`${n}%`)}write(e){dl(this.el_,e)}updateVolume(e,t,i,n,r){this.requestNamedAnimationFrame("VolumeLevelTooltip#updateVolume",()=>{this.update(e,t,i,n.toFixed(0)),r&&r()})}}$e.registerComponent("VolumeLevelTooltip",O4);class qC extends $e{constructor(e,t){super(e,t),this.update=_a(ts(this,this.update),Tr)}createEl(){return super.createEl("div",{className:"vjs-mouse-display"})}update(e,t,i){const n=100*t;this.getChild("volumeLevelTooltip").updateVolume(e,t,i,n,()=>{i?this.el_.style.bottom=`${e.height*t}px`:this.el_.style.left=`${e.width*t}px`})}}qC.prototype.options_={children:["volumeLevelTooltip"]};$e.registerComponent("MouseVolumeLevelDisplay",qC);class lg extends gb{constructor(e,t){super(e,t),this.on("slideractive",i=>this.updateLastVolume_(i)),this.on(e,"volumechange",i=>this.updateARIAAttributes(i)),e.ready(()=>this.updateARIAAttributes())}createEl(){return super.createEl("div",{className:"vjs-volume-bar vjs-slider-bar"},{"aria-label":this.localize("Volume Level"),"aria-live":"polite"})}handleMouseDown(e){Th(e)&&super.handleMouseDown(e)}handleMouseMove(e){const t=this.getChild("mouseVolumeLevelDisplay");if(t){const i=this.el(),n=Dc(i),r=this.vertical();let o=eg(i,e);o=r?o.y:o.x,o=Mh(o,0,1),t.update(n,o,r)}Th(e)&&(this.checkMuted(),this.player_.volume(this.calculateDistance(e)))}checkMuted(){this.player_.muted()&&this.player_.muted(!1)}getPercent(){return this.player_.muted()?0:this.player_.volume()}stepForward(){this.checkMuted(),this.player_.volume(this.player_.volume()+.1)}stepBack(){this.checkMuted(),this.player_.volume(this.player_.volume()-.1)}updateARIAAttributes(e){const t=this.player_.muted()?0:this.volumeAsPercentage_();this.el_.setAttribute("aria-valuenow",t),this.el_.setAttribute("aria-valuetext",t+"%")}volumeAsPercentage_(){return Math.round(this.player_.volume()*100)}updateLastVolume_(){const e=this.player_.volume();this.one("sliderinactive",()=>{this.player_.volume()===0&&this.player_.lastVolume_(e)})}}lg.prototype.options_={children:["volumeLevel"],barName:"volumeLevel"};!hn&&!Ur&&lg.prototype.options_.children.splice(0,0,"mouseVolumeLevelDisplay");lg.prototype.playerEvent="volumechange";$e.registerComponent("VolumeBar",lg);class KC extends $e{constructor(e,t={}){t.vertical=t.vertical||!1,(typeof t.volumeBar>"u"||Cc(t.volumeBar))&&(t.volumeBar=t.volumeBar||{},t.volumeBar.vertical=t.vertical),super(e,t),I4(this,e),this.throttledHandleMouseMove=_a(ts(this,this.handleMouseMove),Tr),this.handleMouseUpHandler_=i=>this.handleMouseUp(i),this.on("mousedown",i=>this.handleMouseDown(i)),this.on("touchstart",i=>this.handleMouseDown(i)),this.on("mousemove",i=>this.handleMouseMove(i)),this.on(this.volumeBar,["focus","slideractive"],()=>{this.volumeBar.addClass("vjs-slider-active"),this.addClass("vjs-slider-active"),this.trigger("slideractive")}),this.on(this.volumeBar,["blur","sliderinactive"],()=>{this.volumeBar.removeClass("vjs-slider-active"),this.removeClass("vjs-slider-active"),this.trigger("sliderinactive")})}createEl(){let e="vjs-volume-horizontal";return this.options_.vertical&&(e="vjs-volume-vertical"),super.createEl("div",{className:`vjs-volume-control vjs-control ${e}`})}handleMouseDown(e){const t=this.el_.ownerDocument;this.on(t,"mousemove",this.throttledHandleMouseMove),this.on(t,"touchmove",this.throttledHandleMouseMove),this.on(t,"mouseup",this.handleMouseUpHandler_),this.on(t,"touchend",this.handleMouseUpHandler_)}handleMouseUp(e){const t=this.el_.ownerDocument;this.off(t,"mousemove",this.throttledHandleMouseMove),this.off(t,"touchmove",this.throttledHandleMouseMove),this.off(t,"mouseup",this.handleMouseUpHandler_),this.off(t,"touchend",this.handleMouseUpHandler_)}handleMouseMove(e){this.volumeBar.handleMouseMove(e)}}KC.prototype.options_={children:["volumeBar"]};$e.registerComponent("VolumeControl",KC);const M4=function(s,e){e.tech_&&!e.tech_.featuresMuteControl&&s.addClass("vjs-hidden"),s.on(e,"loadstart",function(){e.tech_.featuresMuteControl?s.removeClass("vjs-hidden"):s.addClass("vjs-hidden")})};class YC extends mn{constructor(e,t){super(e,t),M4(this,e),this.on(e,["loadstart","volumechange"],i=>this.update(i))}buildCSSClass(){return`vjs-mute-control ${super.buildCSSClass()}`}handleClick(e){const t=this.player_.volume(),i=this.player_.lastVolume_();if(t===0){const n=i<.1?.1:i;this.player_.volume(n),this.player_.muted(!1)}else this.player_.muted(!this.player_.muted())}update(e){this.updateIcon_(),this.updateControlText_()}updateIcon_(){const e=this.player_.volume();let t=3;this.setIcon("volume-high"),hn&&this.player_.tech_&&this.player_.tech_.el_&&this.player_.muted(this.player_.tech_.el_.muted),e===0||this.player_.muted()?(this.setIcon("volume-mute"),t=0):e<.33?(this.setIcon("volume-low"),t=1):e<.67&&(this.setIcon("volume-medium"),t=2),Zp(this.el_,[0,1,2,3].reduce((i,n)=>i+`${n?" ":""}vjs-vol-${n}`,"")),Zl(this.el_,`vjs-vol-${t}`)}updateControlText_(){const t=this.player_.muted()||this.player_.volume()===0?"Unmute":"Mute";this.controlText()!==t&&this.controlText(t)}}YC.prototype.controlText_="Mute";$e.registerComponent("MuteToggle",YC);class WC extends $e{constructor(e,t={}){typeof t.inline<"u"?t.inline=t.inline:t.inline=!0,(typeof t.volumeControl>"u"||Cc(t.volumeControl))&&(t.volumeControl=t.volumeControl||{},t.volumeControl.vertical=!t.inline),super(e,t),this.handleKeyPressHandler_=i=>this.handleKeyPress(i),this.on(e,["loadstart"],i=>this.volumePanelState_(i)),this.on(this.muteToggle,"keyup",i=>this.handleKeyPress(i)),this.on(this.volumeControl,"keyup",i=>this.handleVolumeControlKeyUp(i)),this.on("keydown",i=>this.handleKeyPress(i)),this.on("mouseover",i=>this.handleMouseOver(i)),this.on("mouseout",i=>this.handleMouseOut(i)),this.on(this.volumeControl,["slideractive"],this.sliderActive_),this.on(this.volumeControl,["sliderinactive"],this.sliderInactive_)}sliderActive_(){this.addClass("vjs-slider-active")}sliderInactive_(){this.removeClass("vjs-slider-active")}volumePanelState_(){this.volumeControl.hasClass("vjs-hidden")&&this.muteToggle.hasClass("vjs-hidden")&&this.addClass("vjs-hidden"),this.volumeControl.hasClass("vjs-hidden")&&!this.muteToggle.hasClass("vjs-hidden")&&this.addClass("vjs-mute-toggle-only")}createEl(){let e="vjs-volume-panel-horizontal";return this.options_.inline||(e="vjs-volume-panel-vertical"),super.createEl("div",{className:`vjs-volume-panel vjs-control ${e}`})}dispose(){this.handleMouseOut(),super.dispose()}handleVolumeControlKeyUp(e){e.key==="Escape"&&this.muteToggle.focus()}handleMouseOver(e){this.addClass("vjs-hover"),dr(at,"keyup",this.handleKeyPressHandler_)}handleMouseOut(e){this.removeClass("vjs-hover"),fn(at,"keyup",this.handleKeyPressHandler_)}handleKeyPress(e){e.key==="Escape"&&this.handleMouseOut()}}WC.prototype.options_={children:["muteToggle","volumeControl"]};$e.registerComponent("VolumePanel",WC);class XC extends mn{constructor(e,t){super(e,t),this.validOptions=[5,10,30],this.skipTime=this.getSkipForwardTime(),this.skipTime&&this.validOptions.includes(this.skipTime)?(this.setIcon(`forward-${this.skipTime}`),this.controlText(this.localize("Skip forward {1} seconds",[this.skipTime.toLocaleString(e.language())])),this.show()):this.hide()}getSkipForwardTime(){const e=this.options_.playerOptions;return e.controlBar&&e.controlBar.skipButtons&&e.controlBar.skipButtons.forward}buildCSSClass(){return`vjs-skip-forward-${this.getSkipForwardTime()} ${super.buildCSSClass()}`}handleClick(e){if(isNaN(this.player_.duration()))return;const t=this.player_.currentTime(),i=this.player_.liveTracker,n=i&&i.isLive()?i.seekableEnd():this.player_.duration();let r;t+this.skipTime<=n?r=t+this.skipTime:r=n,this.player_.currentTime(r)}handleLanguagechange(){this.controlText(this.localize("Skip forward {1} seconds",[this.skipTime]))}}XC.prototype.controlText_="Skip Forward";$e.registerComponent("SkipForward",XC);class QC extends mn{constructor(e,t){super(e,t),this.validOptions=[5,10,30],this.skipTime=this.getSkipBackwardTime(),this.skipTime&&this.validOptions.includes(this.skipTime)?(this.setIcon(`replay-${this.skipTime}`),this.controlText(this.localize("Skip backward {1} seconds",[this.skipTime.toLocaleString(e.language())])),this.show()):this.hide()}getSkipBackwardTime(){const e=this.options_.playerOptions;return e.controlBar&&e.controlBar.skipButtons&&e.controlBar.skipButtons.backward}buildCSSClass(){return`vjs-skip-backward-${this.getSkipBackwardTime()} ${super.buildCSSClass()}`}handleClick(e){const t=this.player_.currentTime(),i=this.player_.liveTracker,n=i&&i.isLive()&&i.seekableStart();let r;n&&t-this.skipTime<=n?r=n:t>=this.skipTime?r=t-this.skipTime:r=0,this.player_.currentTime(r)}handleLanguagechange(){this.controlText(this.localize("Skip backward {1} seconds",[this.skipTime]))}}QC.prototype.controlText_="Skip Backward";$e.registerComponent("SkipBackward",QC);class ZC extends $e{constructor(e,t){super(e,t),t&&(this.menuButton_=t.menuButton),this.focusedChild_=-1,this.on("keydown",i=>this.handleKeyDown(i)),this.boundHandleBlur_=i=>this.handleBlur(i),this.boundHandleTapClick_=i=>this.handleTapClick(i)}addEventListenerForItem(e){e instanceof $e&&(this.on(e,"blur",this.boundHandleBlur_),this.on(e,["tap","click"],this.boundHandleTapClick_))}removeEventListenerForItem(e){e instanceof $e&&(this.off(e,"blur",this.boundHandleBlur_),this.off(e,["tap","click"],this.boundHandleTapClick_))}removeChild(e){typeof e=="string"&&(e=this.getChild(e)),this.removeEventListenerForItem(e),super.removeChild(e)}addItem(e){const t=this.addChild(e);t&&this.addEventListenerForItem(t)}createEl(){const e=this.options_.contentElType||"ul";this.contentEl_=Kt(e,{className:"vjs-menu-content"}),this.contentEl_.setAttribute("role","menu");const t=super.createEl("div",{append:this.contentEl_,className:"vjs-menu"});return t.appendChild(this.contentEl_),dr(t,"click",function(i){i.preventDefault(),i.stopImmediatePropagation()}),t}dispose(){this.contentEl_=null,this.boundHandleBlur_=null,this.boundHandleTapClick_=null,super.dispose()}handleBlur(e){const t=e.relatedTarget||at.activeElement;if(!this.children().some(i=>i.el()===t)){const i=this.menuButton_;i&&i.buttonPressed_&&t!==i.el().firstChild&&i.unpressButton()}}handleTapClick(e){if(this.menuButton_){this.menuButton_.unpressButton();const t=this.children();if(!Array.isArray(t))return;const i=t.filter(n=>n.el()===e.target)[0];if(!i)return;i.name()!=="CaptionSettingsMenuItem"&&this.menuButton_.focus()}}handleKeyDown(e){e.key==="ArrowLeft"||e.key==="ArrowDown"?(e.preventDefault(),e.stopPropagation(),this.stepForward()):(e.key==="ArrowRight"||e.key==="ArrowUp")&&(e.preventDefault(),e.stopPropagation(),this.stepBack())}stepForward(){let e=0;this.focusedChild_!==void 0&&(e=this.focusedChild_+1),this.focus(e)}stepBack(){let e=0;this.focusedChild_!==void 0&&(e=this.focusedChild_-1),this.focus(e)}focus(e=0){const t=this.children().slice();t.length&&t[0].hasClass("vjs-menu-title")&&t.shift(),t.length>0&&(e<0?e=0:e>=t.length&&(e=t.length-1),this.focusedChild_=e,t[e].el_.focus())}}$e.registerComponent("Menu",ZC);class vb extends $e{constructor(e,t={}){super(e,t),this.menuButton_=new mn(e,t),this.menuButton_.controlText(this.controlText_),this.menuButton_.el_.setAttribute("aria-haspopup","true");const i=mn.prototype.buildCSSClass();this.menuButton_.el_.className=this.buildCSSClass()+" "+i,this.menuButton_.removeClass("vjs-control"),this.addChild(this.menuButton_),this.update(),this.enabled_=!0;const n=r=>this.handleClick(r);this.handleMenuKeyUp_=r=>this.handleMenuKeyUp(r),this.on(this.menuButton_,"tap",n),this.on(this.menuButton_,"click",n),this.on(this.menuButton_,"keydown",r=>this.handleKeyDown(r)),this.on(this.menuButton_,"mouseenter",()=>{this.addClass("vjs-hover"),this.menu.show(),dr(at,"keyup",this.handleMenuKeyUp_)}),this.on("mouseleave",r=>this.handleMouseLeave(r)),this.on("keydown",r=>this.handleSubmenuKeyDown(r))}update(){const e=this.createMenu();this.menu&&(this.menu.dispose(),this.removeChild(this.menu)),this.menu=e,this.addChild(e),this.buttonPressed_=!1,this.menuButton_.el_.setAttribute("aria-expanded","false"),this.items&&this.items.length<=this.hideThreshold_?(this.hide(),this.menu.contentEl_.removeAttribute("role")):(this.show(),this.menu.contentEl_.setAttribute("role","menu"))}createMenu(){const e=new ZC(this.player_,{menuButton:this});if(this.hideThreshold_=0,this.options_.title){const t=Kt("li",{className:"vjs-menu-title",textContent:bs(this.options_.title),tabIndex:-1}),i=new $e(this.player_,{el:t});e.addItem(i)}if(this.items=this.createItems(),this.items)for(let t=0;t{this.handleTracksChange.apply(this,u)},o=(...u)=>{this.handleSelectedLanguageChange.apply(this,u)};if(e.on(["loadstart","texttrackchange"],r),n.addEventListener("change",r),n.addEventListener("selectedlanguagechange",o),this.on("dispose",function(){e.off(["loadstart","texttrackchange"],r),n.removeEventListener("change",r),n.removeEventListener("selectedlanguagechange",o)}),n.onchange===void 0){let u;this.on(["tap","click"],function(){if(typeof de.Event!="object")try{u=new de.Event("change")}catch{}u||(u=at.createEvent("Event"),u.initEvent("change",!0,!0)),n.dispatchEvent(u)})}this.handleTracksChange()}handleClick(e){const t=this.track,i=this.player_.textTracks();if(super.handleClick(e),!!i)for(let n=0;n-1&&o.mode==="showing"){i=!1;break}}i!==this.isSelected_&&this.selected(i)}handleSelectedLanguageChange(e){const t=this.player().textTracks();let i=!0;for(let n=0,r=t.length;n-1&&o.mode==="showing"){i=!1;break}}i&&(this.player_.cache_.selectedLanguage={enabled:!1})}handleLanguagechange(){this.$(".vjs-menu-item-text").textContent=this.player_.localize(this.options_.label),super.handleLanguagechange()}}$e.registerComponent("OffTextTrackMenuItem",JC);class $c extends xb{constructor(e,t={}){t.tracks=e.textTracks(),super(e,t)}createItems(e=[],t=Bh){let i;this.label_&&(i=`${this.label_} off`),e.push(new JC(this.player_,{kinds:this.kinds_,kind:this.kind_,label:i})),this.hideThreshold_+=1;const n=this.player_.textTracks();Array.isArray(this.kinds_)||(this.kinds_=[this.kind_]);for(let r=0;r-1){const u=new t(this.player_,{track:o,kinds:this.kinds_,kind:this.kind_,selectable:!0,multiSelectable:!1});u.addClass(`vjs-${o.kind}-menu-item`),e.push(u)}}return e}}$e.registerComponent("TextTrackButton",$c);class ek extends Ph{constructor(e,t){const i=t.track,n=t.cue,r=e.currentTime();t.selectable=!0,t.multiSelectable=!1,t.label=n.text,t.selected=n.startTime<=r&&r{this.items.forEach(n=>{n.selected(this.track_.activeCues[0]===n.cue)})}}buildCSSClass(){return`vjs-chapters-button ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-chapters-button ${super.buildWrapperCSSClass()}`}update(e){if(e&&e.track&&e.track.kind!=="chapters")return;const t=this.findChaptersTrack();t!==this.track_?(this.setTrack(t),super.update()):(!this.items||t&&t.cues&&t.cues.length!==this.items.length)&&super.update()}setTrack(e){if(this.track_!==e){if(this.updateHandler_||(this.updateHandler_=this.update.bind(this)),this.track_){const t=this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);t&&t.removeEventListener("load",this.updateHandler_),this.track_.removeEventListener("cuechange",this.selectCurrentItem_),this.track_=null}if(this.track_=e,this.track_){this.track_.mode="hidden";const t=this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);t&&t.addEventListener("load",this.updateHandler_),this.track_.addEventListener("cuechange",this.selectCurrentItem_)}}}findChaptersTrack(){const e=this.player_.textTracks()||[];for(let t=e.length-1;t>=0;t--){const i=e[t];if(i.kind===this.kind_)return i}}getMenuCaption(){return this.track_&&this.track_.label?this.track_.label:this.localize(bs(this.kind_))}createMenu(){return this.options_.title=this.getMenuCaption(),super.createMenu()}createItems(){const e=[];if(!this.track_)return e;const t=this.track_.cues;if(!t)return e;for(let i=0,n=t.length;i-1&&(this.label_="captions",this.setIcon("captions")),this.menuButton_.controlText(bs(this.label_))}buildCSSClass(){return`vjs-subs-caps-button ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-subs-caps-button ${super.buildWrapperCSSClass()}`}createItems(){let e=[];return!(this.player().tech_&&this.player().tech_.featuresNativeTextTracks)&&this.player().getChild("textTrackSettings")&&(e.push(new Sb(this.player_,{kind:this.label_})),this.hideThreshold_+=1),e=super.createItems(e,tk),e}}wb.prototype.kinds_=["captions","subtitles"];wb.prototype.controlText_="Subtitles";$e.registerComponent("SubsCapsButton",wb);class ik extends Ph{constructor(e,t){const i=t.track,n=e.audioTracks();t.label=i.label||i.language||"Unknown",t.selected=i.enabled,super(e,t),this.track=i,this.addClass(`vjs-${i.kind}-menu-item`);const r=(...o)=>{this.handleTracksChange.apply(this,o)};n.addEventListener("change",r),this.on("dispose",()=>{n.removeEventListener("change",r)})}createEl(e,t,i){const n=super.createEl(e,t,i),r=n.querySelector(".vjs-menu-item-text");return["main-desc","descriptions"].indexOf(this.options_.track.kind)>=0&&(r.appendChild(Kt("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),r.appendChild(Kt("span",{className:"vjs-control-text",textContent:" "+this.localize("Descriptions")}))),n}handleClick(e){if(super.handleClick(e),this.track.enabled=!0,this.player_.tech_.featuresNativeAudioTracks){const t=this.player_.audioTracks();for(let i=0;ithis.update(r))}handleClick(e){super.handleClick(),this.player().playbackRate(this.rate)}update(e){this.selected(this.player().playbackRate()===this.rate)}}Ab.prototype.contentElType="button";$e.registerComponent("PlaybackRateMenuItem",Ab);class nk extends vb{constructor(e,t){super(e,t),this.menuButton_.el_.setAttribute("aria-describedby",this.labelElId_),this.updateVisibility(),this.updateLabel(),this.on(e,"loadstart",i=>this.updateVisibility(i)),this.on(e,"ratechange",i=>this.updateLabel(i)),this.on(e,"playbackrateschange",i=>this.handlePlaybackRateschange(i))}createEl(){const e=super.createEl();return this.labelElId_="vjs-playback-rate-value-label-"+this.id_,this.labelEl_=Kt("div",{className:"vjs-playback-rate-value",id:this.labelElId_,textContent:"1x"}),e.appendChild(this.labelEl_),e}dispose(){this.labelEl_=null,super.dispose()}buildCSSClass(){return`vjs-playback-rate ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-playback-rate ${super.buildWrapperCSSClass()}`}createItems(){const e=this.playbackRates(),t=[];for(let i=e.length-1;i>=0;i--)t.push(new Ab(this.player(),{rate:e[i]+"x"}));return t}handlePlaybackRateschange(e){this.update()}playbackRates(){const e=this.player();return e.playbackRates&&e.playbackRates()||[]}playbackRateSupported(){return this.player().tech_&&this.player().tech_.featuresPlaybackRate&&this.playbackRates()&&this.playbackRates().length>0}updateVisibility(e){this.playbackRateSupported()?this.removeClass("vjs-hidden"):this.addClass("vjs-hidden")}updateLabel(e){this.playbackRateSupported()&&(this.labelEl_.textContent=this.player().playbackRate()+"x")}}nk.prototype.controlText_="Playback Rate";$e.registerComponent("PlaybackRateMenuButton",nk);class rk extends $e{buildCSSClass(){return`vjs-spacer ${super.buildCSSClass()}`}createEl(e="div",t={},i={}){return t.className||(t.className=this.buildCSSClass()),super.createEl(e,t,i)}}$e.registerComponent("Spacer",rk);class P4 extends rk{buildCSSClass(){return`vjs-custom-control-spacer ${super.buildCSSClass()}`}createEl(){return super.createEl("div",{className:this.buildCSSClass(),textContent:" "})}}$e.registerComponent("CustomControlSpacer",P4);class ak extends $e{createEl(){return super.createEl("div",{className:"vjs-control-bar",dir:"ltr"})}}ak.prototype.options_={children:["playToggle","skipBackward","skipForward","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","liveDisplay","seekToLive","remainingTimeDisplay","customControlSpacer","playbackRateMenuButton","chaptersButton","descriptionsButton","subsCapsButton","audioTrackButton","pictureInPictureToggle","fullscreenToggle"]};$e.registerComponent("ControlBar",ak);class ok extends Uc{constructor(e,t){super(e,t),this.on(e,"error",i=>{this.open(i)})}buildCSSClass(){return`vjs-error-display ${super.buildCSSClass()}`}content(){const e=this.player().error();return e?this.localize(e.message):""}}ok.prototype.options_=Object.assign({},Uc.prototype.options_,{pauseOnOpen:!1,fillAlways:!0,temporary:!1,uncloseable:!0});$e.registerComponent("ErrorDisplay",ok);class lk extends $e{constructor(e,t={}){super(e,t),this.el_.setAttribute("aria-labelledby",this.selectLabelledbyIds)}createEl(){return this.selectLabelledbyIds=[this.options_.legendId,this.options_.labelId].join(" ").trim(),Kt("select",{id:this.options_.id},{},this.options_.SelectOptions.map(t=>{const i=(this.options_.labelId?this.options_.labelId:`vjs-track-option-${br()}`)+"-"+t[1].replace(/\W+/g,""),n=Kt("option",{id:i,value:this.localize(t[0]),textContent:this.localize(t[1])});return n.setAttribute("aria-labelledby",`${this.selectLabelledbyIds} ${i}`),n}))}}$e.registerComponent("TextTrackSelect",lk);class eu extends $e{constructor(e,t={}){super(e,t);const i=Kt("legend",{textContent:this.localize(this.options_.legendText),id:this.options_.legendId});this.el().appendChild(i);const n=this.options_.selects;for(const r of n){const o=this.options_.selectConfigs[r],u=o.className,c=o.id.replace("%s",this.options_.id_);let d=null;const f=`vjs_select_${br()}`;if(this.options_.type==="colors"){d=Kt("span",{className:u});const g=Kt("label",{id:c,className:"vjs-label",textContent:this.localize(o.label)});g.setAttribute("for",f),d.appendChild(g)}const p=new lk(e,{SelectOptions:o.options,legendId:this.options_.legendId,id:f,labelId:c});this.addChild(p),this.options_.type==="colors"&&(d.appendChild(p.el()),this.el().appendChild(d))}}createEl(){return Kt("fieldset",{className:this.options_.className})}}$e.registerComponent("TextTrackFieldset",eu);class uk extends $e{constructor(e,t={}){super(e,t);const i=this.options_.textTrackComponentid,n=new eu(e,{id_:i,legendId:`captions-text-legend-${i}`,legendText:this.localize("Text"),className:"vjs-fg vjs-track-setting",selects:this.options_.fieldSets[0],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(n);const r=new eu(e,{id_:i,legendId:`captions-background-${i}`,legendText:this.localize("Text Background"),className:"vjs-bg vjs-track-setting",selects:this.options_.fieldSets[1],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(r);const o=new eu(e,{id_:i,legendId:`captions-window-${i}`,legendText:this.localize("Caption Area Background"),className:"vjs-window vjs-track-setting",selects:this.options_.fieldSets[2],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(o)}createEl(){return Kt("div",{className:"vjs-track-settings-colors"})}}$e.registerComponent("TextTrackSettingsColors",uk);class ck extends $e{constructor(e,t={}){super(e,t);const i=this.options_.textTrackComponentid,n=new eu(e,{id_:i,legendId:`captions-font-size-${i}`,legendText:"Font Size",className:"vjs-font-percent vjs-track-setting",selects:this.options_.fieldSets[0],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(n);const r=new eu(e,{id_:i,legendId:`captions-edge-style-${i}`,legendText:this.localize("Text Edge Style"),className:"vjs-edge-style vjs-track-setting",selects:this.options_.fieldSets[1],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(r);const o=new eu(e,{id_:i,legendId:`captions-font-family-${i}`,legendText:this.localize("Font Family"),className:"vjs-font-family vjs-track-setting",selects:this.options_.fieldSets[2],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(o)}createEl(){return Kt("div",{className:"vjs-track-settings-font"})}}$e.registerComponent("TextTrackSettingsFont",ck);class dk extends $e{constructor(e,t={}){super(e,t);const i=new mn(e,{controlText:this.localize("restore all settings to the default values"),className:"vjs-default-button"});i.el().classList.remove("vjs-control","vjs-button"),i.el().textContent=this.localize("Reset"),this.addChild(i);const n=this.localize("Done"),r=new mn(e,{controlText:n,className:"vjs-done-button"});r.el().classList.remove("vjs-control","vjs-button"),r.el().textContent=n,this.addChild(r)}createEl(){return Kt("div",{className:"vjs-track-settings-controls"})}}$e.registerComponent("TrackSettingsControls",dk);const qy="vjs-text-track-settings",ME=["#000","Black"],PE=["#00F","Blue"],BE=["#0FF","Cyan"],FE=["#0F0","Green"],UE=["#F0F","Magenta"],jE=["#F00","Red"],$E=["#FFF","White"],HE=["#FF0","Yellow"],Ky=["1","Opaque"],Yy=["0.5","Semi-Transparent"],VE=["0","Transparent"],Zo={backgroundColor:{selector:".vjs-bg-color > select",id:"captions-background-color-%s",label:"Color",options:[ME,$E,jE,FE,PE,HE,UE,BE],className:"vjs-bg-color"},backgroundOpacity:{selector:".vjs-bg-opacity > select",id:"captions-background-opacity-%s",label:"Opacity",options:[Ky,Yy,VE],className:"vjs-bg-opacity vjs-opacity"},color:{selector:".vjs-text-color > select",id:"captions-foreground-color-%s",label:"Color",options:[$E,ME,jE,FE,PE,HE,UE,BE],className:"vjs-text-color"},edgeStyle:{selector:".vjs-edge-style > select",id:"",label:"Text Edge Style",options:[["none","None"],["raised","Raised"],["depressed","Depressed"],["uniform","Uniform"],["dropshadow","Drop shadow"]]},fontFamily:{selector:".vjs-font-family > select",id:"",label:"Font Family",options:[["proportionalSansSerif","Proportional Sans-Serif"],["monospaceSansSerif","Monospace Sans-Serif"],["proportionalSerif","Proportional Serif"],["monospaceSerif","Monospace Serif"],["casual","Casual"],["script","Script"],["small-caps","Small Caps"]]},fontPercent:{selector:".vjs-font-percent > select",id:"",label:"Font Size",options:[["0.50","50%"],["0.75","75%"],["1.00","100%"],["1.25","125%"],["1.50","150%"],["1.75","175%"],["2.00","200%"],["3.00","300%"],["4.00","400%"]],default:2,parser:s=>s==="1.00"?null:Number(s)},textOpacity:{selector:".vjs-text-opacity > select",id:"captions-foreground-opacity-%s",label:"Opacity",options:[Ky,Yy],className:"vjs-text-opacity vjs-opacity"},windowColor:{selector:".vjs-window-color > select",id:"captions-window-color-%s",label:"Color",className:"vjs-window-color"},windowOpacity:{selector:".vjs-window-opacity > select",id:"captions-window-opacity-%s",label:"Opacity",options:[VE,Yy,Ky],className:"vjs-window-opacity vjs-opacity"}};Zo.windowColor.options=Zo.backgroundColor.options;function hk(s,e){if(e&&(s=e(s)),s&&s!=="none")return s}function B4(s,e){const t=s.options[s.options.selectedIndex].value;return hk(t,e)}function F4(s,e,t){if(e){for(let i=0;i{this.saveSettings(),this.close()}),this.on(this.$(".vjs-default-button"),["click","tap"],()=>{this.setDefaults(),this.updateDisplay()}),ac(Zo,e=>{this.on(this.$(e.selector),"change",this.updateDisplay)})}dispose(){this.endDialog=null,super.dispose()}label(){return this.localize("Caption Settings Dialog")}description(){return this.localize("Beginning of dialog window. Escape will cancel and close the window.")}buildCSSClass(){return super.buildCSSClass()+" vjs-text-track-settings"}getValues(){return tC(Zo,(e,t,i)=>{const n=B4(this.$(t.selector),t.parser);return n!==void 0&&(e[i]=n),e},{})}setValues(e){ac(Zo,(t,i)=>{F4(this.$(t.selector),e[i],t.parser)})}setDefaults(){ac(Zo,e=>{const t=e.hasOwnProperty("default")?e.default:0;this.$(e.selector).selectedIndex=t})}restoreSettings(){let e;try{e=JSON.parse(de.localStorage.getItem(qy))}catch(t){fi.warn(t)}e&&this.setValues(e)}saveSettings(){if(!this.options_.persistTextTrackSettings)return;const e=this.getValues();try{Object.keys(e).length?de.localStorage.setItem(qy,JSON.stringify(e)):de.localStorage.removeItem(qy)}catch(t){fi.warn(t)}}updateDisplay(){const e=this.player_.getChild("textTrackDisplay");e&&e.updateDisplay()}handleLanguagechange(){this.fill(),this.renderModalComponents(this.player_),this.bindFunctionsToSelectsAndButtons()}}$e.registerComponent("TextTrackSettings",U4);class j4 extends $e{constructor(e,t){let i=t.ResizeObserver||de.ResizeObserver;t.ResizeObserver===null&&(i=!1);const n=Gi({createEl:!i,reportTouchActivity:!1},t);super(e,n),this.ResizeObserver=t.ResizeObserver||de.ResizeObserver,this.loadListener_=null,this.resizeObserver_=null,this.debouncedHandler_=EC(()=>{this.resizeHandler()},100,!1,this),i?(this.resizeObserver_=new this.ResizeObserver(this.debouncedHandler_),this.resizeObserver_.observe(e.el())):(this.loadListener_=()=>{if(!this.el_||!this.el_.contentWindow)return;const r=this.debouncedHandler_;let o=this.unloadListener_=function(){fn(this,"resize",r),fn(this,"unload",o),o=null};dr(this.el_.contentWindow,"unload",o),dr(this.el_.contentWindow,"resize",r)},this.one("load",this.loadListener_))}createEl(){return super.createEl("iframe",{className:"vjs-resize-manager",tabIndex:-1,title:this.localize("No content")},{"aria-hidden":"true"})}resizeHandler(){!this.player_||!this.player_.trigger||this.player_.trigger("playerresize")}dispose(){this.debouncedHandler_&&this.debouncedHandler_.cancel(),this.resizeObserver_&&(this.player_.el()&&this.resizeObserver_.unobserve(this.player_.el()),this.resizeObserver_.disconnect()),this.loadListener_&&this.off("load",this.loadListener_),this.el_&&this.el_.contentWindow&&this.unloadListener_&&this.unloadListener_.call(this.el_.contentWindow),this.ResizeObserver=null,this.resizeObserver=null,this.debouncedHandler_=null,this.loadListener_=null,super.dispose()}}$e.registerComponent("ResizeManager",j4);const $4={trackingThreshold:20,liveTolerance:15};class H4 extends $e{constructor(e,t){const i=Gi($4,t,{createEl:!1});super(e,i),this.trackLiveHandler_=()=>this.trackLive_(),this.handlePlay_=n=>this.handlePlay(n),this.handleFirstTimeupdate_=n=>this.handleFirstTimeupdate(n),this.handleSeeked_=n=>this.handleSeeked(n),this.seekToLiveEdge_=n=>this.seekToLiveEdge(n),this.reset_(),this.on(this.player_,"durationchange",n=>this.handleDurationchange(n)),this.on(this.player_,"canplay",()=>this.toggleTracking())}trackLive_(){const e=this.player_.seekable();if(!e||!e.length)return;const t=Number(de.performance.now().toFixed(4)),i=this.lastTime_===-1?0:(t-this.lastTime_)/1e3;this.lastTime_=t,this.pastSeekEnd_=this.pastSeekEnd()+i;const n=this.liveCurrentTime(),r=this.player_.currentTime();let o=this.player_.paused()||this.seekedBehindLive_||Math.abs(n-r)>this.options_.liveTolerance;(!this.timeupdateSeen_||n===1/0)&&(o=!1),o!==this.behindLiveEdge_&&(this.behindLiveEdge_=o,this.trigger("liveedgechange"))}handleDurationchange(){this.toggleTracking()}toggleTracking(){this.player_.duration()===1/0&&this.liveWindow()>=this.options_.trackingThreshold?(this.player_.options_.liveui&&this.player_.addClass("vjs-liveui"),this.startTracking()):(this.player_.removeClass("vjs-liveui"),this.stopTracking())}startTracking(){this.isTracking()||(this.timeupdateSeen_||(this.timeupdateSeen_=this.player_.hasStarted()),this.trackingInterval_=this.setInterval(this.trackLiveHandler_,Tr),this.trackLive_(),this.on(this.player_,["play","pause"],this.trackLiveHandler_),this.timeupdateSeen_?this.on(this.player_,"seeked",this.handleSeeked_):(this.one(this.player_,"play",this.handlePlay_),this.one(this.player_,"timeupdate",this.handleFirstTimeupdate_)))}handleFirstTimeupdate(){this.timeupdateSeen_=!0,this.on(this.player_,"seeked",this.handleSeeked_)}handleSeeked(){const e=Math.abs(this.liveCurrentTime()-this.player_.currentTime());this.seekedBehindLive_=this.nextSeekedFromUser_&&e>2,this.nextSeekedFromUser_=!1,this.trackLive_()}handlePlay(){this.one(this.player_,"timeupdate",this.seekToLiveEdge_)}reset_(){this.lastTime_=-1,this.pastSeekEnd_=0,this.lastSeekEnd_=-1,this.behindLiveEdge_=!0,this.timeupdateSeen_=!1,this.seekedBehindLive_=!1,this.nextSeekedFromUser_=!1,this.clearInterval(this.trackingInterval_),this.trackingInterval_=null,this.off(this.player_,["play","pause"],this.trackLiveHandler_),this.off(this.player_,"seeked",this.handleSeeked_),this.off(this.player_,"play",this.handlePlay_),this.off(this.player_,"timeupdate",this.handleFirstTimeupdate_),this.off(this.player_,"timeupdate",this.seekToLiveEdge_)}nextSeekedFromUser(){this.nextSeekedFromUser_=!0}stopTracking(){this.isTracking()&&(this.reset_(),this.trigger("liveedgechange"))}seekableEnd(){const e=this.player_.seekable(),t=[];let i=e?e.length:0;for(;i--;)t.push(e.end(i));return t.length?t.sort()[t.length-1]:1/0}seekableStart(){const e=this.player_.seekable(),t=[];let i=e?e.length:0;for(;i--;)t.push(e.start(i));return t.length?t.sort()[0]:0}liveWindow(){const e=this.liveCurrentTime();return e===1/0?0:e-this.seekableStart()}isLive(){return this.isTracking()}atLiveEdge(){return!this.behindLiveEdge()}liveCurrentTime(){return this.pastSeekEnd()+this.seekableEnd()}pastSeekEnd(){const e=this.seekableEnd();return this.lastSeekEnd_!==-1&&e!==this.lastSeekEnd_&&(this.pastSeekEnd_=0),this.lastSeekEnd_=e,this.pastSeekEnd_}behindLiveEdge(){return this.behindLiveEdge_}isTracking(){return typeof this.trackingInterval_=="number"}seekToLiveEdge(){this.seekedBehindLive_=!1,!this.atLiveEdge()&&(this.nextSeekedFromUser_=!1,this.player_.currentTime(this.liveCurrentTime()))}dispose(){this.stopTracking(),super.dispose()}}$e.registerComponent("LiveTracker",H4);class V4 extends $e{constructor(e,t){super(e,t),this.on("statechanged",i=>this.updateDom_()),this.updateDom_()}createEl(){return this.els={title:Kt("div",{className:"vjs-title-bar-title",id:`vjs-title-bar-title-${br()}`}),description:Kt("div",{className:"vjs-title-bar-description",id:`vjs-title-bar-description-${br()}`})},Kt("div",{className:"vjs-title-bar"},{},iC(this.els))}updateDom_(){const e=this.player_.tech_,t=e&&e.el_,i={title:"aria-labelledby",description:"aria-describedby"};["title","description"].forEach(n=>{const r=this.state[n],o=this.els[n],u=i[n];tg(o),r&&dl(o,r),t&&(t.removeAttribute(u),r&&t.setAttribute(u,o.id))}),this.state.title||this.state.description?this.show():this.hide()}update(e){this.setState(e)}dispose(){const e=this.player_.tech_,t=e&&e.el_;t&&(t.removeAttribute("aria-labelledby"),t.removeAttribute("aria-describedby")),super.dispose(),this.els=null}}$e.registerComponent("TitleBar",V4);const G4={initialDisplay:4e3,position:[],takeFocus:!1};class z4 extends mn{constructor(e,t){t=Gi(G4,t),super(e,t),this.controlText(t.controlText),this.hide(),this.on(this.player_,["useractive","userinactive"],i=>{this.removeClass("force-display")})}buildCSSClass(){return`vjs-transient-button focus-visible ${this.options_.position.map(e=>`vjs-${e}`).join(" ")}`}createEl(){const e=Kt("button",{},{type:"button",class:this.buildCSSClass()},Kt("span"));return this.controlTextEl_=e.querySelector("span"),e}show(){super.show(),this.addClass("force-display"),this.options_.takeFocus&&this.el().focus({preventScroll:!0}),this.forceDisplayTimeout=this.player_.setTimeout(()=>{this.removeClass("force-display")},this.options_.initialDisplay)}hide(){this.removeClass("force-display"),super.hide()}dispose(){this.player_.clearTimeout(this.forceDisplayTimeout),super.dispose()}}$e.registerComponent("TransientButton",z4);const sx=s=>{const e=s.el();if(e.hasAttribute("src"))return s.triggerSourceset(e.src),!0;const t=s.$$("source"),i=[];let n="";if(!t.length)return!1;for(let r=0;r{let t={};for(let i=0;ifk([s.el(),de.HTMLMediaElement.prototype,de.Element.prototype,q4],"innerHTML"),GE=function(s){const e=s.el();if(e.resetSourceWatch_)return;const t={},i=K4(s),n=r=>(...o)=>{const u=r.apply(e,o);return sx(s),u};["append","appendChild","insertAdjacentHTML"].forEach(r=>{e[r]&&(t[r]=e[r],e[r]=n(t[r]))}),Object.defineProperty(e,"innerHTML",Gi(i,{set:n(i.set)})),e.resetSourceWatch_=()=>{e.resetSourceWatch_=null,Object.keys(t).forEach(r=>{e[r]=t[r]}),Object.defineProperty(e,"innerHTML",i)},s.one("sourceset",e.resetSourceWatch_)},Y4=Object.defineProperty({},"src",{get(){return this.hasAttribute("src")?MC(de.Element.prototype.getAttribute.call(this,"src")):""},set(s){return de.Element.prototype.setAttribute.call(this,"src",s),s}}),W4=s=>fk([s.el(),de.HTMLMediaElement.prototype,Y4],"src"),X4=function(s){if(!s.featuresSourceset)return;const e=s.el();if(e.resetSourceset_)return;const t=W4(s),i=e.setAttribute,n=e.load;Object.defineProperty(e,"src",Gi(t,{set:r=>{const o=t.set.call(e,r);return s.triggerSourceset(e.src),o}})),e.setAttribute=(r,o)=>{const u=i.call(e,r,o);return/src/i.test(r)&&s.triggerSourceset(e.src),u},e.load=()=>{const r=n.call(e);return sx(s)||(s.triggerSourceset(""),GE(s)),r},e.currentSrc?s.triggerSourceset(e.currentSrc):sx(s)||GE(s),e.resetSourceset_=()=>{e.resetSourceset_=null,e.load=n,e.setAttribute=i,Object.defineProperty(e,"src",t),e.resetSourceWatch_&&e.resetSourceWatch_()}};class Et extends ni{constructor(e,t){super(e,t);const i=e.source;let n=!1;if(this.featuresVideoFrameCallback=this.featuresVideoFrameCallback&&this.el_.tagName==="VIDEO",i&&(this.el_.currentSrc!==i.src||e.tag&&e.tag.initNetworkState_===3)?this.setSource(i):this.handleLateInit_(this.el_),e.enableSourceset&&this.setupSourcesetHandling_(),this.isScrubbing_=!1,this.el_.hasChildNodes()){const r=this.el_.childNodes;let o=r.length;const u=[];for(;o--;){const c=r[o];c.nodeName.toLowerCase()==="track"&&(this.featuresNativeTextTracks?(this.remoteTextTrackEls().addTrackElement_(c),this.remoteTextTracks().addTrack(c.track),this.textTracks().addTrack(c.track),!n&&!this.el_.hasAttribute("crossorigin")&&rg(c.src)&&(n=!0)):u.push(c))}for(let c=0;c{t=[];for(let r=0;re.removeEventListener("change",i));const n=()=>{for(let r=0;r{e.removeEventListener("change",i),e.removeEventListener("change",n),e.addEventListener("change",n)}),this.on("webkitendfullscreen",()=>{e.removeEventListener("change",i),e.addEventListener("change",i),e.removeEventListener("change",n)})}overrideNative_(e,t){if(t!==this[`featuresNative${e}Tracks`])return;const i=e.toLowerCase();this[`${i}TracksListeners_`]&&Object.keys(this[`${i}TracksListeners_`]).forEach(n=>{this.el()[`${i}Tracks`].removeEventListener(n,this[`${i}TracksListeners_`][n])}),this[`featuresNative${e}Tracks`]=!t,this[`${i}TracksListeners_`]=null,this.proxyNativeTracksForType_(i)}overrideNativeAudioTracks(e){this.overrideNative_("Audio",e)}overrideNativeVideoTracks(e){this.overrideNative_("Video",e)}proxyNativeTracksForType_(e){const t=xr[e],i=this.el()[t.getterName],n=this[t.getterName]();if(!this[`featuresNative${t.capitalName}Tracks`]||!i||!i.addEventListener)return;const r={change:u=>{const c={type:"change",target:n,currentTarget:n,srcElement:n};n.trigger(c),e==="text"&&this[Rc.remoteText.getterName]().trigger(c)},addtrack(u){n.addTrack(u.track)},removetrack(u){n.removeTrack(u.track)}},o=function(){const u=[];for(let c=0;c{const c=r[u];i.addEventListener(u,c),this.on("dispose",d=>i.removeEventListener(u,c))}),this.on("loadstart",o),this.on("dispose",u=>this.off("loadstart",o))}proxyNativeTracks_(){xr.names.forEach(e=>{this.proxyNativeTracksForType_(e)})}createEl(){let e=this.options_.tag;if(!e||!(this.options_.playerElIngest||this.movingMediaElementInDOM)){if(e){const i=e.cloneNode(!0);e.parentNode&&e.parentNode.insertBefore(i,e),Et.disposeMediaElement(e),e=i}else{e=at.createElement("video");const i=this.options_.tag&&Qo(this.options_.tag),n=Gi({},i);(!xh||this.options_.nativeControlsForTouch!==!0)&&delete n.controls,dC(e,Object.assign(n,{id:this.options_.techId,class:"vjs-tech"}))}e.playerId=this.options_.playerId}typeof this.options_.preload<"u"&&kc(e,"preload",this.options_.preload),this.options_.disablePictureInPicture!==void 0&&(e.disablePictureInPicture=this.options_.disablePictureInPicture);const t=["loop","muted","playsinline","autoplay"];for(let i=0;i=2&&t.push("loadeddata"),e.readyState>=3&&t.push("canplay"),e.readyState>=4&&t.push("canplaythrough"),this.ready(function(){t.forEach(function(i){this.trigger(i)},this)})}setScrubbing(e){this.isScrubbing_=e}scrubbing(){return this.isScrubbing_}setCurrentTime(e){try{this.isScrubbing_&&this.el_.fastSeek&&Qp?this.el_.fastSeek(e):this.el_.currentTime=e}catch(t){fi(t,"Video is not ready. (Video.js)")}}duration(){if(this.el_.duration===1/0&&Ur&&Ta&&this.el_.currentTime===0){const e=()=>{this.el_.currentTime>0&&(this.el_.duration===1/0&&this.trigger("durationchange"),this.off("timeupdate",e))};return this.on("timeupdate",e),NaN}return this.el_.duration||NaN}width(){return this.el_.offsetWidth}height(){return this.el_.offsetHeight}proxyWebkitFullscreen_(){if(!("webkitDisplayingFullscreen"in this.el_))return;const e=function(){this.trigger("fullscreenchange",{isFullscreen:!1}),this.el_.controls&&!this.options_.nativeControlsForTouch&&this.controls()&&(this.el_.controls=!1)},t=function(){"webkitPresentationMode"in this.el_&&this.el_.webkitPresentationMode!=="picture-in-picture"&&(this.one("webkitendfullscreen",e),this.trigger("fullscreenchange",{isFullscreen:!0,nativeIOSFullscreen:!0}))};this.on("webkitbeginfullscreen",t),this.on("dispose",()=>{this.off("webkitbeginfullscreen",t),this.off("webkitendfullscreen",e)})}supportsFullScreen(){return typeof this.el_.webkitEnterFullScreen=="function"}enterFullScreen(){const e=this.el_;if(e.paused&&e.networkState<=e.HAVE_METADATA)da(this.el_.play()),this.setTimeout(function(){e.pause();try{e.webkitEnterFullScreen()}catch(t){this.trigger("fullscreenerror",t)}},0);else try{e.webkitEnterFullScreen()}catch(t){this.trigger("fullscreenerror",t)}}exitFullScreen(){if(!this.el_.webkitDisplayingFullscreen){this.trigger("fullscreenerror",new Error("The video is not fullscreen"));return}this.el_.webkitExitFullScreen()}requestPictureInPicture(){return this.el_.requestPictureInPicture()}requestVideoFrameCallback(e){return this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.requestVideoFrameCallback(e):super.requestVideoFrameCallback(e)}cancelVideoFrameCallback(e){this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.cancelVideoFrameCallback(e):super.cancelVideoFrameCallback(e)}src(e){if(e===void 0)return this.el_.src;this.setSrc(e)}addSourceElement(e,t){if(!e)return fi.error("Invalid source URL."),!1;const i={src:e};t&&(i.type=t);const n=Kt("source",{},i);return this.el_.appendChild(n),!0}removeSourceElement(e){if(!e)return fi.error("Source URL is required to remove the source element."),!1;const t=this.el_.querySelectorAll("source");for(const i of t)if(i.src===e)return this.el_.removeChild(i),!0;return fi.warn(`No matching source element found with src: ${e}`),!1}reset(){Et.resetMediaElement(this.el_)}currentSrc(){return this.currentSource_?this.currentSource_.src:this.el_.currentSrc}setControls(e){this.el_.controls=!!e}addTextTrack(e,t,i){return this.featuresNativeTextTracks?this.el_.addTextTrack(e,t,i):super.addTextTrack(e,t,i)}createRemoteTextTrack(e){if(!this.featuresNativeTextTracks)return super.createRemoteTextTrack(e);const t=at.createElement("track");return e.kind&&(t.kind=e.kind),e.label&&(t.label=e.label),(e.language||e.srclang)&&(t.srclang=e.language||e.srclang),e.default&&(t.default=e.default),e.id&&(t.id=e.id),e.src&&(t.src=e.src),t}addRemoteTextTrack(e,t){const i=super.addRemoteTextTrack(e,t);return this.featuresNativeTextTracks&&this.el().appendChild(i),i}removeRemoteTextTrack(e){if(super.removeRemoteTextTrack(e),this.featuresNativeTextTracks){const t=this.$$("track");let i=t.length;for(;i--;)(e===t[i]||e===t[i].track)&&this.el().removeChild(t[i])}}getVideoPlaybackQuality(){if(typeof this.el().getVideoPlaybackQuality=="function")return this.el().getVideoPlaybackQuality();const e={};return typeof this.el().webkitDroppedFrameCount<"u"&&typeof this.el().webkitDecodedFrameCount<"u"&&(e.droppedVideoFrames=this.el().webkitDroppedFrameCount,e.totalVideoFrames=this.el().webkitDecodedFrameCount),de.performance&&(e.creationTime=de.performance.now()),e}}Kp(Et,"TEST_VID",function(){if(!Pc())return;const s=at.createElement("video"),e=at.createElement("track");return e.kind="captions",e.srclang="en",e.label="English",s.appendChild(e),s});Et.isSupported=function(){try{Et.TEST_VID.volume=.5}catch{return!1}return!!(Et.TEST_VID&&Et.TEST_VID.canPlayType)};Et.canPlayType=function(s){return Et.TEST_VID.canPlayType(s)};Et.canPlaySource=function(s,e){return Et.canPlayType(s.type)};Et.canControlVolume=function(){try{const s=Et.TEST_VID.volume;Et.TEST_VID.volume=s/2+.1;const e=s!==Et.TEST_VID.volume;return e&&hn?(de.setTimeout(()=>{Et&&Et.prototype&&(Et.prototype.featuresVolumeControl=s!==Et.TEST_VID.volume)}),!1):e}catch{return!1}};Et.canMuteVolume=function(){try{const s=Et.TEST_VID.muted;return Et.TEST_VID.muted=!s,Et.TEST_VID.muted?kc(Et.TEST_VID,"muted","muted"):Jp(Et.TEST_VID,"muted","muted"),s!==Et.TEST_VID.muted}catch{return!1}};Et.canControlPlaybackRate=function(){if(Ur&&Ta&&Yp<58)return!1;try{const s=Et.TEST_VID.playbackRate;return Et.TEST_VID.playbackRate=s/2+.1,s!==Et.TEST_VID.playbackRate}catch{return!1}};Et.canOverrideAttributes=function(){try{const s=()=>{};Object.defineProperty(at.createElement("video"),"src",{get:s,set:s}),Object.defineProperty(at.createElement("audio"),"src",{get:s,set:s}),Object.defineProperty(at.createElement("video"),"innerHTML",{get:s,set:s}),Object.defineProperty(at.createElement("audio"),"innerHTML",{get:s,set:s})}catch{return!1}return!0};Et.supportsNativeTextTracks=function(){return Qp||hn&&Ta};Et.supportsNativeVideoTracks=function(){return!!(Et.TEST_VID&&Et.TEST_VID.videoTracks)};Et.supportsNativeAudioTracks=function(){return!!(Et.TEST_VID&&Et.TEST_VID.audioTracks)};Et.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([s,e]){Kp(Et.prototype,s,()=>Et[e](),!0)});Et.prototype.featuresVolumeControl=Et.canControlVolume();Et.prototype.movingMediaElementInDOM=!hn;Et.prototype.featuresFullscreenResize=!0;Et.prototype.featuresProgressEvents=!0;Et.prototype.featuresTimeupdateEvents=!0;Et.prototype.featuresVideoFrameCallback=!!(Et.TEST_VID&&Et.TEST_VID.requestVideoFrameCallback);Et.disposeMediaElement=function(s){if(s){for(s.parentNode&&s.parentNode.removeChild(s);s.hasChildNodes();)s.removeChild(s.firstChild);s.removeAttribute("src"),typeof s.load=="function"&&(function(){try{s.load()}catch{}})()}};Et.resetMediaElement=function(s){if(!s)return;const e=s.querySelectorAll("source");let t=e.length;for(;t--;)s.removeChild(e[t]);s.removeAttribute("src"),typeof s.load=="function"&&(function(){try{s.load()}catch{}})()};["muted","defaultMuted","autoplay","controls","loop","playsinline"].forEach(function(s){Et.prototype[s]=function(){return this.el_[s]||this.el_.hasAttribute(s)}});["muted","defaultMuted","autoplay","loop","playsinline"].forEach(function(s){Et.prototype["set"+bs(s)]=function(e){this.el_[s]=e,e?this.el_.setAttribute(s,s):this.el_.removeAttribute(s)}});["paused","currentTime","buffered","volume","poster","preload","error","seeking","seekable","ended","playbackRate","defaultPlaybackRate","disablePictureInPicture","played","networkState","readyState","videoWidth","videoHeight","crossOrigin"].forEach(function(s){Et.prototype[s]=function(){return this.el_[s]}});["volume","src","poster","preload","playbackRate","defaultPlaybackRate","disablePictureInPicture","crossOrigin"].forEach(function(s){Et.prototype["set"+bs(s)]=function(e){this.el_[s]=e}});["pause","load","play"].forEach(function(s){Et.prototype[s]=function(){return this.el_[s]()}});ni.withSourceHandlers(Et);Et.nativeSourceHandler={};Et.nativeSourceHandler.canPlayType=function(s){try{return Et.TEST_VID.canPlayType(s)}catch{return""}};Et.nativeSourceHandler.canHandleSource=function(s,e){if(s.type)return Et.nativeSourceHandler.canPlayType(s.type);if(s.src){const t=db(s.src);return Et.nativeSourceHandler.canPlayType(`video/${t}`)}return""};Et.nativeSourceHandler.handleSource=function(s,e,t){e.setSrc(s.src)};Et.nativeSourceHandler.dispose=function(){};Et.registerSourceHandler(Et.nativeSourceHandler);ni.registerTech("Html5",Et);const mk=["progress","abort","suspend","emptied","stalled","loadedmetadata","loadeddata","timeupdate","resize","volumechange","texttrackchange"],Wy={canplay:"CanPlay",canplaythrough:"CanPlayThrough",playing:"Playing",seeked:"Seeked"},nx=["tiny","xsmall","small","medium","large","xlarge","huge"],Pm={};nx.forEach(s=>{const e=s.charAt(0)==="x"?`x-${s.substring(1)}`:s;Pm[s]=`vjs-layout-${e}`});const Q4={tiny:210,xsmall:320,small:425,medium:768,large:1440,xlarge:2560,huge:1/0};let us=class Zu extends $e{constructor(e,t,i){if(e.id=e.id||t.id||`vjs_video_${br()}`,t=Object.assign(Zu.getTagSettings(e),t),t.initChildren=!1,t.createEl=!1,t.evented=!1,t.reportTouchActivity=!1,!t.language){const o=e.closest("[lang]");o&&(t.language=o.getAttribute("lang"))}if(super(null,t,i),this.boundDocumentFullscreenChange_=o=>this.documentFullscreenChange_(o),this.boundFullWindowOnEscKey_=o=>this.fullWindowOnEscKey(o),this.boundUpdateStyleEl_=o=>this.updateStyleEl_(o),this.boundApplyInitTime_=o=>this.applyInitTime_(o),this.boundUpdateCurrentBreakpoint_=o=>this.updateCurrentBreakpoint_(o),this.boundHandleTechClick_=o=>this.handleTechClick_(o),this.boundHandleTechDoubleClick_=o=>this.handleTechDoubleClick_(o),this.boundHandleTechTouchStart_=o=>this.handleTechTouchStart_(o),this.boundHandleTechTouchMove_=o=>this.handleTechTouchMove_(o),this.boundHandleTechTouchEnd_=o=>this.handleTechTouchEnd_(o),this.boundHandleTechTap_=o=>this.handleTechTap_(o),this.boundUpdatePlayerHeightOnAudioOnlyMode_=o=>this.updatePlayerHeightOnAudioOnlyMode_(o),this.isFullscreen_=!1,this.log=JA(this.id_),this.fsApi_=tp,this.isPosterFromTech_=!1,this.queuedCallbacks_=[],this.isReady_=!1,this.hasStarted_=!1,this.userActive_=!1,this.debugEnabled_=!1,this.audioOnlyMode_=!1,this.audioPosterMode_=!1,this.audioOnlyCache_={controlBarHeight:null,playerHeight:null,hiddenChildren:[]},!this.options_||!this.options_.techOrder||!this.options_.techOrder.length)throw new Error("No techOrder specified. Did you overwrite videojs.options instead of just changing the properties you want to override?");if(this.tag=e,this.tagAttributes=e&&Qo(e),this.language(this.options_.language),t.languages){const o={};Object.getOwnPropertyNames(t.languages).forEach(function(u){o[u.toLowerCase()]=t.languages[u]}),this.languages_=o}else this.languages_=Zu.prototype.options_.languages;this.resetCache_(),this.poster_=t.poster||"",this.controls_=!!t.controls,e.controls=!1,e.removeAttribute("controls"),this.changingSrc_=!1,this.playCallbacks_=[],this.playTerminatedQueue_=[],e.hasAttribute("autoplay")?this.autoplay(!0):this.autoplay(this.options_.autoplay),t.plugins&&Object.keys(t.plugins).forEach(o=>{if(typeof this[o]!="function")throw new Error(`plugin "${o}" does not exist`)}),this.scrubbing_=!1,this.el_=this.createEl(),ab(this,{eventBusKey:"el_"}),this.fsApi_.requestFullscreen&&(dr(at,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),this.on(this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_)),this.fluid_&&this.on(["playerreset","resize"],this.boundUpdateStyleEl_);const n=Gi(this.options_);if(t.plugins&&Object.keys(t.plugins).forEach(o=>{this[o](t.plugins[o])}),t.debug&&this.debug(!0),this.options_.playerOptions=n,this.middleware_=[],this.playbackRates(t.playbackRates),t.experimentalSvgIcons){const u=new de.DOMParser().parseFromString(b4,"image/svg+xml");if(u.querySelector("parsererror"))fi.warn("Failed to load SVG Icons. Falling back to Font Icons."),this.options_.experimentalSvgIcons=null;else{const d=u.documentElement;d.style.display="none",this.el_.appendChild(d),this.addClass("vjs-svg-icons-enabled")}}this.initChildren(),this.isAudio(e.nodeName.toLowerCase()==="audio"),this.controls()?this.addClass("vjs-controls-enabled"):this.addClass("vjs-controls-disabled"),this.el_.setAttribute("role","region"),this.isAudio()?this.el_.setAttribute("aria-label",this.localize("Audio Player")):this.el_.setAttribute("aria-label",this.localize("Video Player")),this.isAudio()&&this.addClass("vjs-audio"),t.spatialNavigation&&t.spatialNavigation.enabled&&(this.spatialNavigation=new T4(this),this.addClass("vjs-spatial-navigation-enabled")),xh&&this.addClass("vjs-touch-enabled"),hn||this.addClass("vjs-workinghover"),Zu.players[this.id_]=this;const r=Kv.split(".")[0];this.addClass(`vjs-v${r}`),this.userActive(!0),this.reportUserActivity(),this.one("play",o=>this.listenForUserActivity_(o)),this.on("keydown",o=>this.handleKeyDown(o)),this.on("languagechange",o=>this.handleLanguagechange(o)),this.breakpoints(this.options_.breakpoints),this.responsive(this.options_.responsive),this.on("ready",()=>{this.audioPosterMode(this.options_.audioPosterMode),this.audioOnlyMode(this.options_.audioOnlyMode)})}dispose(){this.trigger("dispose"),this.off("dispose"),fn(at,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),fn(at,"keydown",this.boundFullWindowOnEscKey_),this.styleEl_&&this.styleEl_.parentNode&&(this.styleEl_.parentNode.removeChild(this.styleEl_),this.styleEl_=null),Zu.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),g4(this),_n.names.forEach(e=>{const t=_n[e],i=this[t.getterName]();i&&i.off&&i.off()}),super.dispose({restoreEl:this.options_.restoreEl})}createEl(){let e=this.tag,t,i=this.playerElIngest_=e.parentNode&&e.parentNode.hasAttribute&&e.parentNode.hasAttribute("data-vjs-player");const n=this.tag.tagName.toLowerCase()==="video-js";i?t=this.el_=e.parentNode:n||(t=this.el_=super.createEl("div"));const r=Qo(e);if(n){for(t=this.el_=e,e=this.tag=at.createElement("video");t.children.length;)e.appendChild(t.firstChild);uh(t,"video-js")||Zl(t,"video-js"),t.appendChild(e),i=this.playerElIngest_=t,Object.keys(t).forEach(c=>{try{e[c]=t[c]}catch{}})}e.setAttribute("tabindex","-1"),r.tabindex="-1",Ta&&Wp&&(e.setAttribute("role","application"),r.role="application"),e.removeAttribute("width"),e.removeAttribute("height"),"width"in r&&delete r.width,"height"in r&&delete r.height,Object.getOwnPropertyNames(r).forEach(function(c){n&&c==="class"||t.setAttribute(c,r[c]),n&&e.setAttribute(c,r[c])}),e.playerId=e.id,e.id+="_html5_api",e.className="vjs-tech",e.player=t.player=this,this.addClass("vjs-paused");const o=["IS_SMART_TV","IS_TIZEN","IS_WEBOS","IS_ANDROID","IS_IPAD","IS_IPHONE","IS_CHROMECAST_RECEIVER"].filter(c=>oC[c]).map(c=>"vjs-device-"+c.substring(3).toLowerCase().replace(/\_/g,"-"));if(this.addClass(...o),de.VIDEOJS_NO_DYNAMIC_STYLE!==!0){this.styleEl_=_C("vjs-styles-dimensions");const c=ll(".vjs-styles-defaults"),d=ll("head");d.insertBefore(this.styleEl_,c?c.nextSibling:d.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);const u=e.getElementsByTagName("a");for(let c=0;c"u")return this.techGet_("crossOrigin");if(e!==null&&e!=="anonymous"&&e!=="use-credentials"){fi.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${e}"`);return}this.techCall_("setCrossOrigin",e),this.posterImage&&this.posterImage.crossOrigin(e)}width(e){return this.dimension("width",e)}height(e){return this.dimension("height",e)}dimension(e,t){const i=e+"_";if(t===void 0)return this[i]||0;if(t===""||t==="auto"){this[i]=void 0,this.updateStyleEl_();return}const n=parseFloat(t);if(isNaN(n)){fi.error(`Improper value "${t}" supplied for for ${e}`);return}this[i]=n,this.updateStyleEl_()}fluid(e){if(e===void 0)return!!this.fluid_;this.fluid_=!!e,to(this)&&this.off(["playerreset","resize"],this.boundUpdateStyleEl_),e?(this.addClass("vjs-fluid"),this.fill(!1),Y3(this,()=>{this.on(["playerreset","resize"],this.boundUpdateStyleEl_)})):this.removeClass("vjs-fluid"),this.updateStyleEl_()}fill(e){if(e===void 0)return!!this.fill_;this.fill_=!!e,e?(this.addClass("vjs-fill"),this.fluid(!1)):this.removeClass("vjs-fill")}aspectRatio(e){if(e===void 0)return this.aspectRatio_;if(!/^\d+\:\d+$/.test(e))throw new Error("Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.");this.aspectRatio_=e,this.fluid(!0),this.updateStyleEl_()}updateStyleEl_(){if(de.VIDEOJS_NO_DYNAMIC_STYLE===!0){const u=typeof this.width_=="number"?this.width_:this.options_.width,c=typeof this.height_=="number"?this.height_:this.options_.height,d=this.tech_&&this.tech_.el();d&&(u>=0&&(d.width=u),c>=0&&(d.height=c));return}let e,t,i,n;this.aspectRatio_!==void 0&&this.aspectRatio_!=="auto"?i=this.aspectRatio_:this.videoWidth()>0?i=this.videoWidth()+":"+this.videoHeight():i="16:9";const r=i.split(":"),o=r[1]/r[0];this.width_!==void 0?e=this.width_:this.height_!==void 0?e=this.height_/o:e=this.videoWidth()||300,this.height_!==void 0?t=this.height_:t=e*o,/^[^a-zA-Z]/.test(this.id())?n="dimensions-"+this.id():n=this.id()+"-dimensions",this.addClass(n),SC(this.styleEl_,` .${n} { width: ${e}px; height: ${t}px; } .${n}.vjs-fluid:not(.vjs-audio-only-mode) { padding-top: ${o*100}%; } `)}loadTech_(e,t){this.tech_&&this.unloadTech_();const i=bs(e),n=e.charAt(0).toLowerCase()+e.slice(1);i!=="Html5"&&this.tag&&(ni.getTech("Html5").disposeMediaElement(this.tag),this.tag.player=null,this.tag=null),this.techName_=i,this.isReady_=!1;let r=this.autoplay();(typeof this.autoplay()=="string"||this.autoplay()===!0&&this.options_.normalizeAutoplay)&&(r=!1);const o={source:t,autoplay:r,nativeControlsForTouch:this.options_.nativeControlsForTouch,playerId:this.id(),techId:`${this.id()}_${n}_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};_n.names.forEach(c=>{const d=_n[c];o[d.getterName]=this[d.privateName]}),Object.assign(o,this.options_[i]),Object.assign(o,this.options_[n]),Object.assign(o,this.options_[e.toLowerCase()]),this.tag&&(o.tag=this.tag),t&&t.src===this.cache_.src&&this.cache_.currentTime>0&&(o.startTime=this.cache_.currentTime);const u=ni.getTech(e);if(!u)throw new Error(`No Tech named '${i}' exists! '${i}' should be registered using videojs.registerTech()'`);this.tech_=new u(o),this.tech_.ready(ts(this,this.handleTechReady_),!0),tx.jsonToTextTracks(this.textTracksJson_||[],this.tech_),mk.forEach(c=>{this.on(this.tech_,c,d=>this[`handleTech${bs(c)}_`](d))}),Object.keys(Wy).forEach(c=>{this.on(this.tech_,c,d=>{if(this.tech_.playbackRate()===0&&this.tech_.seeking()){this.queuedCallbacks_.push({callback:this[`handleTech${Wy[c]}_`].bind(this),event:d});return}this[`handleTech${Wy[c]}_`](d)})}),this.on(this.tech_,"loadstart",c=>this.handleTechLoadStart_(c)),this.on(this.tech_,"sourceset",c=>this.handleTechSourceset_(c)),this.on(this.tech_,"waiting",c=>this.handleTechWaiting_(c)),this.on(this.tech_,"ended",c=>this.handleTechEnded_(c)),this.on(this.tech_,"seeking",c=>this.handleTechSeeking_(c)),this.on(this.tech_,"play",c=>this.handleTechPlay_(c)),this.on(this.tech_,"pause",c=>this.handleTechPause_(c)),this.on(this.tech_,"durationchange",c=>this.handleTechDurationChange_(c)),this.on(this.tech_,"fullscreenchange",(c,d)=>this.handleTechFullscreenChange_(c,d)),this.on(this.tech_,"fullscreenerror",(c,d)=>this.handleTechFullscreenError_(c,d)),this.on(this.tech_,"enterpictureinpicture",c=>this.handleTechEnterPictureInPicture_(c)),this.on(this.tech_,"leavepictureinpicture",c=>this.handleTechLeavePictureInPicture_(c)),this.on(this.tech_,"error",c=>this.handleTechError_(c)),this.on(this.tech_,"posterchange",c=>this.handleTechPosterChange_(c)),this.on(this.tech_,"textdata",c=>this.handleTechTextData_(c)),this.on(this.tech_,"ratechange",c=>this.handleTechRateChange_(c)),this.on(this.tech_,"loadedmetadata",this.boundUpdateStyleEl_),this.usingNativeControls(this.techGet_("controls")),this.controls()&&!this.usingNativeControls()&&this.addTechControlsListeners_(),this.tech_.el().parentNode!==this.el()&&(i!=="Html5"||!this.tag)&&Wv(this.tech_.el(),this.el()),this.tag&&(this.tag.player=null,this.tag=null)}unloadTech_(){_n.names.forEach(e=>{const t=_n[e];this[t.privateName]=this[t.getterName]()}),this.textTracksJson_=tx.textTracksToJson(this.tech_),this.isReady_=!1,this.tech_.dispose(),this.tech_=!1,this.isPosterFromTech_&&(this.poster_="",this.trigger("posterchange")),this.isPosterFromTech_=!1}tech(e){return e===void 0&&fi.warn(`Using the tech directly can be dangerous. I hope you know what you're doing. See https://github.com/videojs/video.js/issues/2617 for more info. `),this.tech_}version(){return{"video.js":Kv}}addTechControlsListeners_(){this.removeTechControlsListeners_(),this.on(this.tech_,"click",this.boundHandleTechClick_),this.on(this.tech_,"dblclick",this.boundHandleTechDoubleClick_),this.on(this.tech_,"touchstart",this.boundHandleTechTouchStart_),this.on(this.tech_,"touchmove",this.boundHandleTechTouchMove_),this.on(this.tech_,"touchend",this.boundHandleTechTouchEnd_),this.on(this.tech_,"tap",this.boundHandleTechTap_)}removeTechControlsListeners_(){this.off(this.tech_,"tap",this.boundHandleTechTap_),this.off(this.tech_,"touchstart",this.boundHandleTechTouchStart_),this.off(this.tech_,"touchmove",this.boundHandleTechTouchMove_),this.off(this.tech_,"touchend",this.boundHandleTechTouchEnd_),this.off(this.tech_,"click",this.boundHandleTechClick_),this.off(this.tech_,"dblclick",this.boundHandleTechDoubleClick_)}handleTechReady_(){this.triggerReady(),this.cache_.volume&&this.techCall_("setVolume",this.cache_.volume),this.handleTechPosterChange_(),this.handleTechDurationChange_()}handleTechLoadStart_(){this.removeClass("vjs-ended","vjs-seeking"),this.error(null),this.handleTechDurationChange_(),this.paused()?(this.hasStarted(!1),this.trigger("loadstart")):this.trigger("loadstart"),this.manualAutoplay_(this.autoplay()===!0&&this.options_.normalizeAutoplay?"play":this.autoplay())}manualAutoplay_(e){if(!this.tech_||typeof e!="string")return;const t=()=>{const n=this.muted();this.muted(!0);const r=()=>{this.muted(n)};this.playTerminatedQueue_.push(r);const o=this.play();if(dh(o))return o.catch(u=>{throw r(),new Error(`Rejection at manualAutoplay. Restoring muted value. ${u||""}`)})};let i;if(e==="any"&&!this.muted()?(i=this.play(),dh(i)&&(i=i.catch(t))):e==="muted"&&!this.muted()?i=t():i=this.play(),!!dh(i))return i.then(()=>{this.trigger({type:"autoplay-success",autoplay:e})}).catch(()=>{this.trigger({type:"autoplay-failure",autoplay:e})})}updateSourceCaches_(e=""){let t=e,i="";typeof t!="string"&&(t=e.src,i=e.type),this.cache_.source=this.cache_.source||{},this.cache_.sources=this.cache_.sources||[],t&&!i&&(i=x4(this,t)),this.cache_.source=Gi({},e,{src:t,type:i});const n=this.cache_.sources.filter(c=>c.src&&c.src===t),r=[],o=this.$$("source"),u=[];for(let c=0;cthis.updateSourceCaches_(r);const i=this.currentSource().src,n=e.src;i&&!/^blob:/.test(i)&&/^blob:/.test(n)&&(!this.lastSource_||this.lastSource_.tech!==n&&this.lastSource_.player!==i)&&(t=()=>{}),t(n),e.src||this.tech_.any(["sourceset","loadstart"],r=>{if(r.type==="sourceset")return;const o=this.techGet_("currentSrc");this.lastSource_.tech=o,this.updateSourceCaches_(o)})}this.lastSource_={player:this.currentSource().src,tech:e.src},this.trigger({src:e.src,type:"sourceset"})}hasStarted(e){if(e===void 0)return this.hasStarted_;e!==this.hasStarted_&&(this.hasStarted_=e,this.hasStarted_?this.addClass("vjs-has-started"):this.removeClass("vjs-has-started"))}handleTechPlay_(){this.removeClass("vjs-ended","vjs-paused"),this.addClass("vjs-playing"),this.hasStarted(!0),this.trigger("play")}handleTechRateChange_(){this.tech_.playbackRate()>0&&this.cache_.lastPlaybackRate===0&&(this.queuedCallbacks_.forEach(e=>e.callback(e.event)),this.queuedCallbacks_=[]),this.cache_.lastPlaybackRate=this.tech_.playbackRate(),this.trigger("ratechange")}handleTechWaiting_(){this.addClass("vjs-waiting"),this.trigger("waiting");const e=this.currentTime(),t=()=>{e!==this.currentTime()&&(this.removeClass("vjs-waiting"),this.off("timeupdate",t))};this.on("timeupdate",t)}handleTechCanPlay_(){this.removeClass("vjs-waiting"),this.trigger("canplay")}handleTechCanPlayThrough_(){this.removeClass("vjs-waiting"),this.trigger("canplaythrough")}handleTechPlaying_(){this.removeClass("vjs-waiting"),this.trigger("playing")}handleTechSeeking_(){this.addClass("vjs-seeking"),this.trigger("seeking")}handleTechSeeked_(){this.removeClass("vjs-seeking","vjs-ended"),this.trigger("seeked")}handleTechPause_(){this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.trigger("pause")}handleTechEnded_(){this.addClass("vjs-ended"),this.removeClass("vjs-waiting"),this.options_.loop?(this.currentTime(0),this.play()):this.paused()||this.pause(),this.trigger("ended")}handleTechDurationChange_(){this.duration(this.techGet_("duration"))}handleTechClick_(e){this.controls_&&(this.options_===void 0||this.options_.userActions===void 0||this.options_.userActions.click===void 0||this.options_.userActions.click!==!1)&&(this.options_!==void 0&&this.options_.userActions!==void 0&&typeof this.options_.userActions.click=="function"?this.options_.userActions.click.call(this,e):this.paused()?da(this.play()):this.pause())}handleTechDoubleClick_(e){if(!this.controls_)return;Array.prototype.some.call(this.$$(".vjs-control-bar, .vjs-modal-dialog"),i=>i.contains(e.target))||(this.options_===void 0||this.options_.userActions===void 0||this.options_.userActions.doubleClick===void 0||this.options_.userActions.doubleClick!==!1)&&(this.options_!==void 0&&this.options_.userActions!==void 0&&typeof this.options_.userActions.doubleClick=="function"?this.options_.userActions.doubleClick.call(this,e):this.isInPictureInPicture()&&!at.pictureInPictureElement?this.exitPictureInPicture():this.isFullscreen()?this.exitFullscreen():this.requestFullscreen())}handleTechTap_(){this.userActive(!this.userActive())}handleTechTouchStart_(){this.userWasActive=this.userActive()}handleTechTouchMove_(){this.userWasActive&&this.reportUserActivity()}handleTechTouchEnd_(e){e.cancelable&&e.preventDefault()}toggleFullscreenClass_(){this.isFullscreen()?this.addClass("vjs-fullscreen"):this.removeClass("vjs-fullscreen")}documentFullscreenChange_(e){const t=e.target.player;if(t&&t!==this)return;const i=this.el();let n=at[this.fsApi_.fullscreenElement]===i;!n&&i.matches&&(n=i.matches(":"+this.fsApi_.fullscreen)),this.isFullscreen(n)}handleTechFullscreenChange_(e,t){t&&(t.nativeIOSFullscreen&&(this.addClass("vjs-ios-native-fs"),this.tech_.one("webkitendfullscreen",()=>{this.removeClass("vjs-ios-native-fs")})),this.isFullscreen(t.isFullscreen))}handleTechFullscreenError_(e,t){this.trigger("fullscreenerror",t)}togglePictureInPictureClass_(){this.isInPictureInPicture()?this.addClass("vjs-picture-in-picture"):this.removeClass("vjs-picture-in-picture")}handleTechEnterPictureInPicture_(e){this.isInPictureInPicture(!0)}handleTechLeavePictureInPicture_(e){this.isInPictureInPicture(!1)}handleTechError_(){const e=this.tech_.error();e&&this.error(e)}handleTechTextData_(){let e=null;arguments.length>1&&(e=arguments[1]),this.trigger("textdata",e)}getCache(){return this.cache_}resetCache_(){this.cache_={currentTime:0,initTime:0,inactivityTimeout:this.options_.inactivityTimeout,duration:NaN,lastVolume:1,lastPlaybackRate:this.defaultPlaybackRate(),media:null,src:"",source:{},sources:[],playbackRates:[],volume:1}}techCall_(e,t){this.ready(function(){if(e in m4)return h4(this.middleware_,this.tech_,e,t);if(e in DE)return kE(this.middleware_,this.tech_,e,t);try{this.tech_&&this.tech_[e](t)}catch(i){throw fi(i),i}},!0)}techGet_(e){if(!(!this.tech_||!this.tech_.isReady_)){if(e in f4)return d4(this.middleware_,this.tech_,e);if(e in DE)return kE(this.middleware_,this.tech_,e);try{return this.tech_[e]()}catch(t){throw this.tech_[e]===void 0?(fi(`Video.js: ${e} method not defined for ${this.techName_} playback technology.`,t),t):t.name==="TypeError"?(fi(`Video.js: ${e} unavailable on ${this.techName_} playback technology element.`,t),this.tech_.isReady_=!1,t):(fi(t),t)}}}play(){return new Promise(e=>{this.play_(e)})}play_(e=da){this.playCallbacks_.push(e);const t=!!(!this.changingSrc_&&(this.src()||this.currentSrc())),i=!!(Qp||hn);if(this.waitToPlay_&&(this.off(["ready","loadstart"],this.waitToPlay_),this.waitToPlay_=null),!this.isReady_||!t){this.waitToPlay_=o=>{this.play_()},this.one(["ready","loadstart"],this.waitToPlay_),!t&&i&&this.load();return}const n=this.techGet_("play");i&&this.hasClass("vjs-ended")&&this.resetProgressBar_(),n===null?this.runPlayTerminatedQueue_():this.runPlayCallbacks_(n)}runPlayTerminatedQueue_(){const e=this.playTerminatedQueue_.slice(0);this.playTerminatedQueue_=[],e.forEach(function(t){t()})}runPlayCallbacks_(e){const t=this.playCallbacks_.slice(0);this.playCallbacks_=[],this.playTerminatedQueue_=[],t.forEach(function(i){i(e)})}pause(){this.techCall_("pause")}paused(){return this.techGet_("paused")!==!1}played(){return this.techGet_("played")||Fr(0,0)}scrubbing(e){if(typeof e>"u")return this.scrubbing_;this.scrubbing_=!!e,this.techCall_("setScrubbing",this.scrubbing_),e?this.addClass("vjs-scrubbing"):this.removeClass("vjs-scrubbing")}currentTime(e){if(e===void 0)return this.cache_.currentTime=this.techGet_("currentTime")||0,this.cache_.currentTime;if(e<0&&(e=0),!this.isReady_||this.changingSrc_||!this.tech_||!this.tech_.isReady_){this.cache_.initTime=e,this.off("canplay",this.boundApplyInitTime_),this.one("canplay",this.boundApplyInitTime_);return}this.techCall_("setCurrentTime",e),this.cache_.initTime=0,isFinite(e)&&(this.cache_.currentTime=Number(e))}applyInitTime_(){this.currentTime(this.cache_.initTime)}duration(e){if(e===void 0)return this.cache_.duration!==void 0?this.cache_.duration:NaN;e=parseFloat(e),e<0&&(e=1/0),e!==this.cache_.duration&&(this.cache_.duration=e,e===1/0?this.addClass("vjs-live"):this.removeClass("vjs-live"),isNaN(e)||this.trigger("durationchange"))}remainingTime(){return this.duration()-this.currentTime()}remainingTimeDisplay(){return Math.floor(this.duration())-Math.floor(this.currentTime())}buffered(){let e=this.techGet_("buffered");return(!e||!e.length)&&(e=Fr(0,0)),e}seekable(){let e=this.techGet_("seekable");return(!e||!e.length)&&(e=Fr(0,0)),e}seeking(){return this.techGet_("seeking")}ended(){return this.techGet_("ended")}networkState(){return this.techGet_("networkState")}readyState(){return this.techGet_("readyState")}bufferedPercent(){return IC(this.buffered(),this.duration())}bufferedEnd(){const e=this.buffered(),t=this.duration();let i=e.end(e.length-1);return i>t&&(i=t),i}volume(e){let t;if(e!==void 0){t=Math.max(0,Math.min(1,e)),this.cache_.volume=t,this.techCall_("setVolume",t),t>0&&this.lastVolume_(t);return}return t=parseFloat(this.techGet_("volume")),isNaN(t)?1:t}muted(e){if(e!==void 0){this.techCall_("setMuted",e);return}return this.techGet_("muted")||!1}defaultMuted(e){return e!==void 0&&this.techCall_("setDefaultMuted",e),this.techGet_("defaultMuted")||!1}lastVolume_(e){if(e!==void 0&&e!==0){this.cache_.lastVolume=e;return}return this.cache_.lastVolume}supportsFullScreen(){return this.techGet_("supportsFullScreen")||!1}isFullscreen(e){if(e!==void 0){const t=this.isFullscreen_;this.isFullscreen_=!!e,this.isFullscreen_!==t&&this.fsApi_.prefixed&&this.trigger("fullscreenchange"),this.toggleFullscreenClass_();return}return this.isFullscreen_}requestFullscreen(e){this.isInPictureInPicture()&&this.exitPictureInPicture();const t=this;return new Promise((i,n)=>{function r(){t.off("fullscreenerror",u),t.off("fullscreenchange",o)}function o(){r(),i()}function u(d,f){r(),n(f)}t.one("fullscreenchange",o),t.one("fullscreenerror",u);const c=t.requestFullscreenHelper_(e);c&&(c.then(r,r),c.then(i,n))})}requestFullscreenHelper_(e){let t;if(this.fsApi_.prefixed||(t=this.options_.fullscreen&&this.options_.fullscreen.options||{},e!==void 0&&(t=e)),this.fsApi_.requestFullscreen){const i=this.el_[this.fsApi_.requestFullscreen](t);return i&&i.then(()=>this.isFullscreen(!0),()=>this.isFullscreen(!1)),i}else this.tech_.supportsFullScreen()&&!this.options_.preferFullWindow?this.techCall_("enterFullScreen"):this.enterFullWindow()}exitFullscreen(){const e=this;return new Promise((t,i)=>{function n(){e.off("fullscreenerror",o),e.off("fullscreenchange",r)}function r(){n(),t()}function o(c,d){n(),i(d)}e.one("fullscreenchange",r),e.one("fullscreenerror",o);const u=e.exitFullscreenHelper_();u&&(u.then(n,n),u.then(t,i))})}exitFullscreenHelper_(){if(this.fsApi_.requestFullscreen){const e=at[this.fsApi_.exitFullscreen]();return e&&da(e.then(()=>this.isFullscreen(!1))),e}else this.tech_.supportsFullScreen()&&!this.options_.preferFullWindow?this.techCall_("exitFullScreen"):this.exitFullWindow()}enterFullWindow(){this.isFullscreen(!0),this.isFullWindow=!0,this.docOrigOverflow=at.documentElement.style.overflow,dr(at,"keydown",this.boundFullWindowOnEscKey_),at.documentElement.style.overflow="hidden",Zl(at.body,"vjs-full-window"),this.trigger("enterFullWindow")}fullWindowOnEscKey(e){e.key==="Escape"&&this.isFullscreen()===!0&&(this.isFullWindow?this.exitFullWindow():this.exitFullscreen())}exitFullWindow(){this.isFullscreen(!1),this.isFullWindow=!1,fn(at,"keydown",this.boundFullWindowOnEscKey_),at.documentElement.style.overflow=this.docOrigOverflow,Zp(at.body,"vjs-full-window"),this.trigger("exitFullWindow")}disablePictureInPicture(e){if(e===void 0)return this.techGet_("disablePictureInPicture");this.techCall_("setDisablePictureInPicture",e),this.options_.disablePictureInPicture=e,this.trigger("disablepictureinpicturechanged")}isInPictureInPicture(e){if(e!==void 0){this.isInPictureInPicture_=!!e,this.togglePictureInPictureClass_();return}return!!this.isInPictureInPicture_}requestPictureInPicture(){if(this.options_.enableDocumentPictureInPicture&&de.documentPictureInPicture){const e=at.createElement(this.el().tagName);return e.classList=this.el().classList,e.classList.add("vjs-pip-container"),this.posterImage&&e.appendChild(this.posterImage.el().cloneNode(!0)),this.titleBar&&e.appendChild(this.titleBar.el().cloneNode(!0)),e.appendChild(Kt("p",{className:"vjs-pip-text"},{},this.localize("Playing in picture-in-picture"))),de.documentPictureInPicture.requestWindow({width:this.videoWidth(),height:this.videoHeight()}).then(t=>(xC(t),this.el_.parentNode.insertBefore(e,this.el_),t.document.body.appendChild(this.el_),t.document.body.classList.add("vjs-pip-window"),this.player_.isInPictureInPicture(!0),this.player_.trigger({type:"enterpictureinpicture",pipWindow:t}),t.addEventListener("pagehide",i=>{const n=i.target.querySelector(".video-js");e.parentNode.replaceChild(n,e),this.player_.isInPictureInPicture(!1),this.player_.trigger("leavepictureinpicture")}),t))}return"pictureInPictureEnabled"in at&&this.disablePictureInPicture()===!1?this.techGet_("requestPictureInPicture"):Promise.reject("No PiP mode is available")}exitPictureInPicture(){if(de.documentPictureInPicture&&de.documentPictureInPicture.window)return de.documentPictureInPicture.window.close(),Promise.resolve();if("pictureInPictureEnabled"in at)return at.exitPictureInPicture()}handleKeyDown(e){const{userActions:t}=this.options_;!t||!t.hotkeys||(n=>{const r=n.tagName.toLowerCase();if(n.isContentEditable)return!0;const o=["button","checkbox","hidden","radio","reset","submit"];return r==="input"?o.indexOf(n.type)===-1:["textarea"].indexOf(r)!==-1})(this.el_.ownerDocument.activeElement)||(typeof t.hotkeys=="function"?t.hotkeys.call(this,e):this.handleHotkeys(e))}handleHotkeys(e){const t=this.options_.userActions?this.options_.userActions.hotkeys:{},{fullscreenKey:i=o=>e.key.toLowerCase()==="f",muteKey:n=o=>e.key.toLowerCase()==="m",playPauseKey:r=o=>e.key.toLowerCase()==="k"||e.key.toLowerCase()===" "}=t;if(i.call(this,e)){e.preventDefault(),e.stopPropagation();const o=$e.getComponent("FullscreenToggle");at[this.fsApi_.fullscreenEnabled]!==!1&&o.prototype.handleClick.call(this,e)}else n.call(this,e)?(e.preventDefault(),e.stopPropagation(),$e.getComponent("MuteToggle").prototype.handleClick.call(this,e)):r.call(this,e)&&(e.preventDefault(),e.stopPropagation(),$e.getComponent("PlayToggle").prototype.handleClick.call(this,e))}canPlayType(e){let t;for(let i=0,n=this.options_.techOrder;i[u,ni.getTech(u)]).filter(([u,c])=>c?c.isSupported():(fi.error(`The "${u}" tech is undefined. Skipped browser support check for that tech.`),!1)),i=function(u,c,d){let f;return u.some(p=>c.some(g=>{if(f=d(p,g),f)return!0})),f};let n;const r=u=>(c,d)=>u(d,c),o=([u,c],d)=>{if(c.canPlaySource(d,this.options_[u.toLowerCase()]))return{source:d,tech:u}};return this.options_.sourceOrder?n=i(e,t,r(o)):n=i(t,e,o),n||!1}handleSrc_(e,t){if(typeof e>"u")return this.cache_.src||"";this.resetRetryOnError_&&this.resetRetryOnError_();const i=FC(e);if(!i.length){this.setTimeout(function(){this.error({code:4,message:this.options_.notSupportedMessage})},0);return}if(this.changingSrc_=!0,t||(this.cache_.sources=i),this.updateSourceCaches_(i[0]),u4(this,i[0],(n,r)=>{if(this.middleware_=r,t||(this.cache_.sources=i),this.updateSourceCaches_(n),this.src_(n)){if(i.length>1)return this.handleSrc_(i.slice(1));this.changingSrc_=!1,this.setTimeout(function(){this.error({code:4,message:this.options_.notSupportedMessage})},0),this.triggerReady();return}c4(r,this.tech_)}),i.length>1){const n=()=>{this.error(null),this.handleSrc_(i.slice(1),!0)},r=()=>{this.off("error",n)};this.one("error",n),this.one("playing",r),this.resetRetryOnError_=()=>{this.off("error",n),this.off("playing",r)}}}src(e){return this.handleSrc_(e,!1)}src_(e){const t=this.selectSource([e]);return t?kC(t.tech,this.techName_)?(this.ready(function(){this.tech_.constructor.prototype.hasOwnProperty("setSource")?this.techCall_("setSource",e):this.techCall_("src",e.src),this.changingSrc_=!1},!0),!1):(this.changingSrc_=!0,this.loadTech_(t.tech,t.source),this.tech_.ready(()=>{this.changingSrc_=!1}),!1):!0}addSourceElement(e,t){return this.tech_?this.tech_.addSourceElement(e,t):!1}removeSourceElement(e){return this.tech_?this.tech_.removeSourceElement(e):!1}load(){if(this.tech_&&this.tech_.vhs){this.src(this.currentSource());return}this.techCall_("load")}reset(){if(this.paused())this.doReset_();else{const e=this.play();da(e.then(()=>this.doReset_()))}}doReset_(){this.tech_&&this.tech_.clearTracks("text"),this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.resetCache_(),this.poster(""),this.loadTech_(this.options_.techOrder[0],null),this.techCall_("reset"),this.resetControlBarUI_(),this.error(null),this.titleBar&&this.titleBar.update({title:void 0,description:void 0}),to(this)&&this.trigger("playerreset")}resetControlBarUI_(){this.resetProgressBar_(),this.resetPlaybackRate_(),this.resetVolumeBar_()}resetProgressBar_(){this.currentTime(0);const{currentTimeDisplay:e,durationDisplay:t,progressControl:i,remainingTimeDisplay:n}=this.controlBar||{},{seekBar:r}=i||{};e&&e.updateContent(),t&&t.updateContent(),n&&n.updateContent(),r&&(r.update(),r.loadProgressBar&&r.loadProgressBar.update())}resetPlaybackRate_(){this.playbackRate(this.defaultPlaybackRate()),this.handleTechRateChange_()}resetVolumeBar_(){this.volume(1),this.trigger("volumechange")}currentSources(){const e=this.currentSource(),t=[];return Object.keys(e).length!==0&&t.push(e),this.cache_.sources||t}currentSource(){return this.cache_.source||{}}currentSrc(){return this.currentSource()&&this.currentSource().src||""}currentType(){return this.currentSource()&&this.currentSource().type||""}preload(e){if(e!==void 0){this.techCall_("setPreload",e),this.options_.preload=e;return}return this.techGet_("preload")}autoplay(e){if(e===void 0)return this.options_.autoplay||!1;let t;typeof e=="string"&&/(any|play|muted)/.test(e)||e===!0&&this.options_.normalizeAutoplay?(this.options_.autoplay=e,this.manualAutoplay_(typeof e=="string"?e:"play"),t=!1):e?this.options_.autoplay=!0:this.options_.autoplay=!1,t=typeof t>"u"?this.options_.autoplay:t,this.tech_&&this.techCall_("setAutoplay",t)}playsinline(e){return e!==void 0&&(this.techCall_("setPlaysinline",e),this.options_.playsinline=e),this.techGet_("playsinline")}loop(e){if(e!==void 0){this.techCall_("setLoop",e),this.options_.loop=e;return}return this.techGet_("loop")}poster(e){if(e===void 0)return this.poster_;e||(e=""),e!==this.poster_&&(this.poster_=e,this.techCall_("setPoster",e),this.isPosterFromTech_=!1,this.trigger("posterchange"))}handleTechPosterChange_(){if((!this.poster_||this.options_.techCanOverridePoster)&&this.tech_&&this.tech_.poster){const e=this.tech_.poster()||"";e!==this.poster_&&(this.poster_=e,this.isPosterFromTech_=!0,this.trigger("posterchange"))}}controls(e){if(e===void 0)return!!this.controls_;e=!!e,this.controls_!==e&&(this.controls_=e,this.usingNativeControls()&&this.techCall_("setControls",e),this.controls_?(this.removeClass("vjs-controls-disabled"),this.addClass("vjs-controls-enabled"),this.trigger("controlsenabled"),this.usingNativeControls()||this.addTechControlsListeners_()):(this.removeClass("vjs-controls-enabled"),this.addClass("vjs-controls-disabled"),this.trigger("controlsdisabled"),this.usingNativeControls()||this.removeTechControlsListeners_()))}usingNativeControls(e){if(e===void 0)return!!this.usingNativeControls_;e=!!e,this.usingNativeControls_!==e&&(this.usingNativeControls_=e,this.usingNativeControls_?(this.addClass("vjs-using-native-controls"),this.trigger("usingnativecontrols")):(this.removeClass("vjs-using-native-controls"),this.trigger("usingcustomcontrols")))}error(e){if(e===void 0)return this.error_||null;if(ol("beforeerror").forEach(t=>{const i=t(this,e);if(!(ba(i)&&!Array.isArray(i)||typeof i=="string"||typeof i=="number"||i===null)){this.log.error("please return a value that MediaError expects in beforeerror hooks");return}e=i}),this.options_.suppressNotSupportedError&&e&&e.code===4){const t=function(){this.error(e)};this.options_.suppressNotSupportedError=!1,this.any(["click","touchstart"],t),this.one("loadstart",function(){this.off(["click","touchstart"],t)});return}if(e===null){this.error_=null,this.removeClass("vjs-error"),this.errorDisplay&&this.errorDisplay.close();return}this.error_=new ms(e),this.addClass("vjs-error"),fi.error(`(CODE:${this.error_.code} ${ms.errorTypes[this.error_.code]})`,this.error_.message,this.error_),this.trigger("error"),ol("error").forEach(t=>t(this,this.error_))}reportUserActivity(e){this.userActivity_=!0}userActive(e){if(e===void 0)return this.userActive_;if(e=!!e,e!==this.userActive_){if(this.userActive_=e,this.userActive_){this.userActivity_=!0,this.removeClass("vjs-user-inactive"),this.addClass("vjs-user-active"),this.trigger("useractive");return}this.tech_&&this.tech_.one("mousemove",function(t){t.stopPropagation(),t.preventDefault()}),this.userActivity_=!1,this.removeClass("vjs-user-active"),this.addClass("vjs-user-inactive"),this.trigger("userinactive")}}listenForUserActivity_(){let e,t,i;const n=ts(this,this.reportUserActivity),r=function(p){(p.screenX!==t||p.screenY!==i)&&(t=p.screenX,i=p.screenY,n())},o=function(){n(),this.clearInterval(e),e=this.setInterval(n,250)},u=function(p){n(),this.clearInterval(e)};this.on("mousedown",o),this.on("mousemove",r),this.on("mouseup",u),this.on("mouseleave",u);const c=this.getChild("controlBar");c&&!hn&&!Ur&&(c.on("mouseenter",function(p){this.player().options_.inactivityTimeout!==0&&(this.player().cache_.inactivityTimeout=this.player().options_.inactivityTimeout),this.player().options_.inactivityTimeout=0}),c.on("mouseleave",function(p){this.player().options_.inactivityTimeout=this.player().cache_.inactivityTimeout})),this.on("keydown",n),this.on("keyup",n);let d;const f=function(){if(!this.userActivity_)return;this.userActivity_=!1,this.userActive(!0),this.clearTimeout(d);const p=this.options_.inactivityTimeout;p<=0||(d=this.setTimeout(function(){this.userActivity_||this.userActive(!1)},p))};this.setInterval(f,250)}playbackRate(e){if(e!==void 0){this.techCall_("setPlaybackRate",e);return}return this.tech_&&this.tech_.featuresPlaybackRate?this.cache_.lastPlaybackRate||this.techGet_("playbackRate"):1}defaultPlaybackRate(e){return e!==void 0?this.techCall_("setDefaultPlaybackRate",e):this.tech_&&this.tech_.featuresPlaybackRate?this.techGet_("defaultPlaybackRate"):1}isAudio(e){if(e!==void 0){this.isAudio_=!!e;return}return!!this.isAudio_}updatePlayerHeightOnAudioOnlyMode_(){const e=this.getChild("ControlBar");!e||this.audioOnlyCache_.controlBarHeight===e.currentHeight()||(this.audioOnlyCache_.controlBarHeight=e.currentHeight(),this.height(this.audioOnlyCache_.controlBarHeight))}enableAudioOnlyUI_(){this.addClass("vjs-audio-only-mode");const e=this.children(),t=this.getChild("ControlBar"),i=t&&t.currentHeight();e.forEach(n=>{n!==t&&n.el_&&!n.hasClass("vjs-hidden")&&(n.hide(),this.audioOnlyCache_.hiddenChildren.push(n))}),this.audioOnlyCache_.playerHeight=this.currentHeight(),this.audioOnlyCache_.controlBarHeight=i,this.on("playerresize",this.boundUpdatePlayerHeightOnAudioOnlyMode_),this.height(i),this.trigger("audioonlymodechange")}disableAudioOnlyUI_(){this.removeClass("vjs-audio-only-mode"),this.off("playerresize",this.boundUpdatePlayerHeightOnAudioOnlyMode_),this.audioOnlyCache_.hiddenChildren.forEach(e=>e.show()),this.height(this.audioOnlyCache_.playerHeight),this.trigger("audioonlymodechange")}audioOnlyMode(e){if(typeof e!="boolean"||e===this.audioOnlyMode_)return this.audioOnlyMode_;if(this.audioOnlyMode_=e,e){const t=[];return this.isInPictureInPicture()&&t.push(this.exitPictureInPicture()),this.isFullscreen()&&t.push(this.exitFullscreen()),this.audioPosterMode()&&t.push(this.audioPosterMode(!1)),Promise.all(t).then(()=>this.enableAudioOnlyUI_())}return Promise.resolve().then(()=>this.disableAudioOnlyUI_())}enablePosterModeUI_(){(this.tech_&&this.tech_).hide(),this.addClass("vjs-audio-poster-mode"),this.trigger("audiopostermodechange")}disablePosterModeUI_(){(this.tech_&&this.tech_).show(),this.removeClass("vjs-audio-poster-mode"),this.trigger("audiopostermodechange")}audioPosterMode(e){return typeof e!="boolean"||e===this.audioPosterMode_?this.audioPosterMode_:(this.audioPosterMode_=e,e?this.audioOnlyMode()?this.audioOnlyMode(!1).then(()=>{this.enablePosterModeUI_()}):Promise.resolve().then(()=>{this.enablePosterModeUI_()}):Promise.resolve().then(()=>{this.disablePosterModeUI_()}))}addTextTrack(e,t,i){if(this.tech_)return this.tech_.addTextTrack(e,t,i)}addRemoteTextTrack(e,t){if(this.tech_)return this.tech_.addRemoteTextTrack(e,t)}removeRemoteTextTrack(e={}){let{track:t}=e;if(t||(t=e),this.tech_)return this.tech_.removeRemoteTextTrack(t)}getVideoPlaybackQuality(){return this.techGet_("getVideoPlaybackQuality")}videoWidth(){return this.tech_&&this.tech_.videoWidth&&this.tech_.videoWidth()||0}videoHeight(){return this.tech_&&this.tech_.videoHeight&&this.tech_.videoHeight()||0}language(e){if(e===void 0)return this.language_;this.language_!==String(e).toLowerCase()&&(this.language_=String(e).toLowerCase(),to(this)&&this.trigger("languagechange"))}languages(){return Gi(Zu.prototype.options_.languages,this.languages_)}toJSON(){const e=Gi(this.options_),t=e.tracks;e.tracks=[];for(let i=0;i{this.removeChild(i)}),i.open(),i}updateCurrentBreakpoint_(){if(!this.responsive())return;const e=this.currentBreakpoint(),t=this.currentWidth();for(let i=0;ithis.addRemoteTextTrack(p,!1)),this.titleBar&&this.titleBar.update({title:f,description:o||n||""}),this.ready(t)}getMedia(){if(!this.cache_.media){const e=this.poster(),t=this.currentSources(),i=Array.prototype.map.call(this.remoteTextTracks(),r=>({kind:r.kind,label:r.label,language:r.language,src:r.src})),n={src:t,textTracks:i};return e&&(n.poster=e,n.artwork=[{src:n.poster,type:dp(n.poster)}]),n}return Gi(this.cache_.media)}static getTagSettings(e){const t={sources:[],tracks:[]},i=Qo(e),n=i["data-setup"];if(uh(e,"vjs-fill")&&(i.fill=!0),uh(e,"vjs-fluid")&&(i.fluid=!0),n!==null)try{Object.assign(i,JSON.parse(n||"{}"))}catch(r){fi.error("data-setup",r)}if(Object.assign(t,i),e.hasChildNodes()){const r=e.childNodes;for(let o=0,u=r.length;otypeof t=="number")&&(this.cache_.playbackRates=e,this.trigger("playbackrateschange"))}};us.prototype.videoTracks=()=>{};us.prototype.audioTracks=()=>{};us.prototype.textTracks=()=>{};us.prototype.remoteTextTracks=()=>{};us.prototype.remoteTextTrackEls=()=>{};_n.names.forEach(function(s){const e=_n[s];us.prototype[e.getterName]=function(){return this.tech_?this.tech_[e.getterName]():(this[e.privateName]=this[e.privateName]||new e.ListClass,this[e.privateName])}});us.prototype.crossorigin=us.prototype.crossOrigin;us.players={};const qd=de.navigator;us.prototype.options_={techOrder:ni.defaultTechOrder_,html5:{},enableSourceset:!0,inactivityTimeout:2e3,playbackRates:[],liveui:!1,children:["mediaLoader","posterImage","titleBar","textTrackDisplay","loadingSpinner","bigPlayButton","liveTracker","controlBar","errorDisplay","textTrackSettings","resizeManager"],language:qd&&(qd.languages&&qd.languages[0]||qd.userLanguage||qd.language)||"en",languages:{},notSupportedMessage:"No compatible source was found for this media.",normalizeAutoplay:!1,fullscreen:{options:{navigationUI:"hide"}},breakpoints:{},responsive:!1,audioOnlyMode:!1,audioPosterMode:!1,spatialNavigation:{enabled:!1,horizontalSeek:!1},enableSmoothSeeking:!1,disableSeekWhileScrubbingOnMobile:!1,disableSeekWhileScrubbingOnSTV:!1};mk.forEach(function(s){us.prototype[`handleTech${bs(s)}_`]=function(){return this.trigger(s)}});$e.registerComponent("Player",us);const hp="plugin",uc="activePlugins_",tc={},fp=s=>tc.hasOwnProperty(s),Bm=s=>fp(s)?tc[s]:void 0,pk=(s,e)=>{s[uc]=s[uc]||{},s[uc][e]=!0},mp=(s,e,t)=>{const i=(t?"before":"")+"pluginsetup";s.trigger(i,e),s.trigger(i+":"+e.name,e)},Z4=function(s,e){const t=function(){mp(this,{name:s,plugin:e,instance:null},!0);const i=e.apply(this,arguments);return pk(this,s),mp(this,{name:s,plugin:e,instance:i}),i};return Object.keys(e).forEach(function(i){t[i]=e[i]}),t},zE=(s,e)=>(e.prototype.name=s,function(...t){mp(this,{name:s,plugin:e,instance:null},!0);const i=new e(this,...t);return this[s]=()=>i,mp(this,i.getEventHash()),i});class zn{constructor(e){if(this.constructor===zn)throw new Error("Plugin must be sub-classed; not directly instantiated.");this.player=e,this.log||(this.log=this.player.log.createLogger(this.name)),ab(this),delete this.trigger,CC(this,this.constructor.defaultState),pk(e,this.name),this.dispose=this.dispose.bind(this),e.on("dispose",this.dispose)}version(){return this.constructor.VERSION}getEventHash(e={}){return e.name=this.name,e.plugin=this.constructor,e.instance=this,e}trigger(e,t={}){return Fc(this.eventBusEl_,e,this.getEventHash(t))}handleStateChanged(e){}dispose(){const{name:e,player:t}=this;this.trigger("dispose"),this.off(),t.off("dispose",this.dispose),t[uc][e]=!1,this.player=this.state=null,t[e]=zE(e,tc[e])}static isBasic(e){const t=typeof e=="string"?Bm(e):e;return typeof t=="function"&&!zn.prototype.isPrototypeOf(t.prototype)}static registerPlugin(e,t){if(typeof e!="string")throw new Error(`Illegal plugin name, "${e}", must be a string, was ${typeof e}.`);if(fp(e))fi.warn(`A plugin named "${e}" already exists. You may want to avoid re-registering plugins!`);else if(us.prototype.hasOwnProperty(e))throw new Error(`Illegal plugin name, "${e}", cannot share a name with an existing player method!`);if(typeof t!="function")throw new Error(`Illegal plugin for "${e}", must be a function, was ${typeof t}.`);return tc[e]=t,e!==hp&&(zn.isBasic(t)?us.prototype[e]=Z4(e,t):us.prototype[e]=zE(e,t)),t}static deregisterPlugin(e){if(e===hp)throw new Error("Cannot de-register base plugin.");fp(e)&&(delete tc[e],delete us.prototype[e])}static getPlugins(e=Object.keys(tc)){let t;return e.forEach(i=>{const n=Bm(i);n&&(t=t||{},t[i]=n)}),t}static getPluginVersion(e){const t=Bm(e);return t&&t.VERSION||""}}zn.getPlugin=Bm;zn.BASE_PLUGIN_NAME=hp;zn.registerPlugin(hp,zn);us.prototype.usingPlugin=function(s){return!!this[uc]&&this[uc][s]===!0};us.prototype.hasPlugin=function(s){return!!fp(s)};function J4(s,e){let t=!1;return function(...i){return t||fi.warn(s),t=!0,e.apply(this,i)}}function jr(s,e,t,i){return J4(`${e} is deprecated and will be removed in ${s}.0; please use ${t} instead.`,i)}var eB={NetworkBadStatus:"networkbadstatus",NetworkRequestFailed:"networkrequestfailed",NetworkRequestAborted:"networkrequestaborted",NetworkRequestTimeout:"networkrequesttimeout",NetworkBodyParserFailed:"networkbodyparserfailed",StreamingHlsPlaylistParserError:"streaminghlsplaylistparsererror",StreamingDashManifestParserError:"streamingdashmanifestparsererror",StreamingContentSteeringParserError:"streamingcontentsteeringparsererror",StreamingVttParserError:"streamingvttparsererror",StreamingFailedToSelectNextSegment:"streamingfailedtoselectnextsegment",StreamingFailedToDecryptSegment:"streamingfailedtodecryptsegment",StreamingFailedToTransmuxSegment:"streamingfailedtotransmuxsegment",StreamingFailedToAppendSegment:"streamingfailedtoappendsegment",StreamingCodecsChangeError:"streamingcodecschangeerror"};const gk=s=>s.indexOf("#")===0?s.slice(1):s;function Le(s,e,t){let i=Le.getPlayer(s);if(i)return e&&fi.warn(`Player "${s}" is already initialised. Options will not be applied.`),t&&i.ready(t),i;const n=typeof s=="string"?ll("#"+gk(s)):s;if(!Bc(n))throw new TypeError("The element or ID supplied is not valid. (videojs)");const o=("getRootNode"in n?n.getRootNode()instanceof de.ShadowRoot:!1)?n.getRootNode():n.ownerDocument.body;(!n.ownerDocument.defaultView||!o.contains(n))&&fi.warn("The element supplied is not included in the DOM"),e=e||{},e.restoreEl===!0&&(e.restoreEl=(n.parentNode&&n.parentNode.hasAttribute&&n.parentNode.hasAttribute("data-vjs-player")?n.parentNode:n).cloneNode(!0)),ol("beforesetup").forEach(c=>{const d=c(n,Gi(e));if(!ba(d)||Array.isArray(d)){fi.error("please return an object in beforesetup hooks");return}e=Gi(e,d)});const u=$e.getComponent("Player");return i=new u(n,e,t),ol("setup").forEach(c=>c(i)),i}Le.hooks_=Za;Le.hooks=ol;Le.hook=O3;Le.hookOnce=M3;Le.removeHook=ZA;if(de.VIDEOJS_NO_DYNAMIC_STYLE!==!0&&Pc()){let s=ll(".vjs-styles-defaults");if(!s){s=_C("vjs-styles-defaults");const e=ll("head");e&&e.insertBefore(s,e.firstChild),SC(s,` .video-js { width: 300px; height: 150px; } .vjs-fluid:not(.vjs-audio-only-mode) { padding-top: 56.25% } `)}}Qv(1,Le);Le.VERSION=Kv;Le.options=us.prototype.options_;Le.getPlayers=()=>us.players;Le.getPlayer=s=>{const e=us.players;let t;if(typeof s=="string"){const i=gk(s),n=e[i];if(n)return n;t=ll("#"+i)}else t=s;if(Bc(t)){const{player:i,playerId:n}=t;if(i||e[n])return i||e[n]}};Le.getAllPlayers=()=>Object.keys(us.players).map(s=>us.players[s]).filter(Boolean);Le.players=us.players;Le.getComponent=$e.getComponent;Le.registerComponent=(s,e)=>(ni.isTech(e)&&fi.warn(`The ${s} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`),$e.registerComponent.call($e,s,e));Le.getTech=ni.getTech;Le.registerTech=ni.registerTech;Le.use=l4;Object.defineProperty(Le,"middleware",{value:{},writeable:!1,enumerable:!0});Object.defineProperty(Le.middleware,"TERMINATOR",{value:cp,writeable:!1,enumerable:!0});Le.browser=oC;Le.obj=F3;Le.mergeOptions=jr(9,"videojs.mergeOptions","videojs.obj.merge",Gi);Le.defineLazyProperty=jr(9,"videojs.defineLazyProperty","videojs.obj.defineLazyProperty",Kp);Le.bind=jr(9,"videojs.bind","native Function.prototype.bind",ts);Le.registerPlugin=zn.registerPlugin;Le.deregisterPlugin=zn.deregisterPlugin;Le.plugin=(s,e)=>(fi.warn("videojs.plugin() is deprecated; use videojs.registerPlugin() instead"),zn.registerPlugin(s,e));Le.getPlugins=zn.getPlugins;Le.getPlugin=zn.getPlugin;Le.getPluginVersion=zn.getPluginVersion;Le.addLanguage=function(s,e){return s=(""+s).toLowerCase(),Le.options.languages=Gi(Le.options.languages,{[s]:e}),Le.options.languages[s]};Le.log=fi;Le.createLogger=JA;Le.time=J3;Le.createTimeRange=jr(9,"videojs.createTimeRange","videojs.time.createTimeRanges",Fr);Le.createTimeRanges=jr(9,"videojs.createTimeRanges","videojs.time.createTimeRanges",Fr);Le.formatTime=jr(9,"videojs.formatTime","videojs.time.formatTime",nu);Le.setFormatTime=jr(9,"videojs.setFormatTime","videojs.time.setFormatTime",LC);Le.resetFormatTime=jr(9,"videojs.resetFormatTime","videojs.time.resetFormatTime",RC);Le.parseUrl=jr(9,"videojs.parseUrl","videojs.url.parseUrl",cb);Le.isCrossOrigin=jr(9,"videojs.isCrossOrigin","videojs.url.isCrossOrigin",rg);Le.EventTarget=hr;Le.any=rb;Le.on=dr;Le.one=sg;Le.off=fn;Le.trigger=Fc;Le.xhr=BA;Le.TrackList=ru;Le.TextTrack=Oh;Le.TextTrackList=lb;Le.AudioTrack=PC;Le.AudioTrackList=NC;Le.VideoTrack=BC;Le.VideoTrackList=OC;["isEl","isTextNode","createEl","hasClass","addClass","removeClass","toggleClass","setAttributes","getAttributes","emptyEl","appendContent","insertContent"].forEach(s=>{Le[s]=function(){return fi.warn(`videojs.${s}() is deprecated; use videojs.dom.${s}() instead`),bC[s].apply(null,arguments)}});Le.computedStyle=jr(9,"videojs.computedStyle","videojs.dom.computedStyle",Lc);Le.dom=bC;Le.fn=K3;Le.num=D4;Le.str=Q3;Le.url=a4;Le.Error=eB;class tB{constructor(e){let t=this;return t.id=e.id,t.label=t.id,t.width=e.width,t.height=e.height,t.bitrate=e.bandwidth,t.frameRate=e.frameRate,t.enabled_=e.enabled,Object.defineProperty(t,"enabled",{get(){return t.enabled_()},set(i){t.enabled_(i)}}),t}}class pp extends Le.EventTarget{constructor(){super();let e=this;return e.levels_=[],e.selectedIndex_=-1,Object.defineProperty(e,"selectedIndex",{get(){return e.selectedIndex_}}),Object.defineProperty(e,"length",{get(){return e.levels_.length}}),e[Symbol.iterator]=()=>e.levels_.values(),e}addQualityLevel(e){let t=this.getQualityLevelById(e.id);if(t)return t;const i=this.levels_.length;return t=new tB(e),""+i in this||Object.defineProperty(this,i,{get(){return this.levels_[i]}}),this.levels_.push(t),this.trigger({qualityLevel:t,type:"addqualitylevel"}),t}removeQualityLevel(e){let t=null;for(let i=0,n=this.length;ii&&this.selectedIndex_--;break}return t&&this.trigger({qualityLevel:e,type:"removequalitylevel"}),t}getQualityLevelById(e){for(let t=0,i=this.length;ti,s.qualityLevels.VERSION=yk,i},vk=function(s){return iB(this,Le.obj.merge({},s))};Le.registerPlugin("qualityLevels",vk);vk.VERSION=yk;const $n=Vp,gp=(s,e)=>e&&e.responseURL&&s!==e.responseURL?e.responseURL:s,Er=s=>Le.log.debug?Le.log.debug.bind(Le,"VHS:",`${s} >`):function(){};function Oi(...s){const e=Le.obj||Le;return(e.merge||e.mergeOptions).apply(e,s)}function Zs(...s){const e=Le.time||Le;return(e.createTimeRanges||e.createTimeRanges).apply(e,s)}function sB(s){if(s.length===0)return"Buffered Ranges are empty";let e=`Buffered Ranges: `;for(let t=0;t ${n}. Duration (${n-i}) `}return e}const ha=1/30,fa=ha*3,xk=function(s,e){const t=[];let i;if(s&&s.length)for(i=0;i=e})},mm=function(s,e){return xk(s,function(t){return t-ha>=e})},nB=function(s){if(s.length<2)return Zs();const e=[];for(let t=1;t{const e=[];if(!s||!s.length)return"";for(let t=0;t "+s.end(t));return e.join(", ")},aB=function(s,e,t=1){return((s.length?s.end(s.length-1):0)-e)/t},Xl=s=>{const e=[];for(let t=0;tr)){if(e>n&&e<=r){t+=r-e;continue}t+=r-n}}return t},kb=(s,e)=>{if(!e.preload)return e.duration;let t=0;return(e.parts||[]).forEach(function(i){t+=i.duration}),(e.preloadHints||[]).forEach(function(i){i.type==="PART"&&(t+=s.partTargetDuration)}),t},rx=s=>(s.segments||[]).reduce((e,t,i)=>(t.parts?t.parts.forEach(function(n,r){e.push({duration:n.duration,segmentIndex:i,partIndex:r,part:n,segment:t})}):e.push({duration:t.duration,segmentIndex:i,partIndex:null,segment:t,part:null}),e),[]),Tk=s=>{const e=s.segments&&s.segments.length&&s.segments[s.segments.length-1];return e&&e.parts||[]},_k=({preloadSegment:s})=>{if(!s)return;const{parts:e,preloadHints:t}=s;let i=(t||[]).reduce((n,r)=>n+(r.type==="PART"?1:0),0);return i+=e&&e.length?e.length:0,i},Sk=(s,e)=>{if(e.endList)return 0;if(s&&s.suggestedPresentationDelay)return s.suggestedPresentationDelay;const t=Tk(e).length>0;return t&&e.serverControl&&e.serverControl.partHoldBack?e.serverControl.partHoldBack:t&&e.partTargetDuration?e.partTargetDuration*3:e.serverControl&&e.serverControl.holdBack?e.serverControl.holdBack:e.targetDuration?e.targetDuration*3:0},lB=function(s,e){let t=0,i=e-s.mediaSequence,n=s.segments[i];if(n){if(typeof n.start<"u")return{result:n.start,precise:!0};if(typeof n.end<"u")return{result:n.end-n.duration,precise:!0}}for(;i--;){if(n=s.segments[i],typeof n.end<"u")return{result:t+n.end,precise:!0};if(t+=kb(s,n),typeof n.start<"u")return{result:t+n.start,precise:!0}}return{result:t,precise:!1}},uB=function(s,e){let t=0,i,n=e-s.mediaSequence;for(;n"u"&&(e=s.mediaSequence+s.segments.length),e"u"){if(s.totalDuration)return s.totalDuration;if(!s.endList)return de.Infinity}return Ek(s,e,t)},hh=function({defaultDuration:s,durationList:e,startIndex:t,endIndex:i}){let n=0;if(t>i&&([t,i]=[i,t]),t<0){for(let r=t;r0)for(let d=c-1;d>=0;d--){const f=u[d];if(o+=f.duration,r){if(o<0)continue}else if(o+ha<=0)continue;return{partIndex:f.partIndex,segmentIndex:f.segmentIndex,startTime:n-hh({defaultDuration:s.targetDuration,durationList:u,startIndex:c,endIndex:d})}}return{partIndex:u[0]&&u[0].partIndex||null,segmentIndex:u[0]&&u[0].segmentIndex||0,startTime:e}}if(c<0){for(let d=c;d<0;d++)if(o-=s.targetDuration,o<0)return{partIndex:u[0]&&u[0].partIndex||null,segmentIndex:u[0]&&u[0].segmentIndex||0,startTime:e};c=0}for(let d=c;dha,g=o===0,v=p&&o+ha>=0;if(!((g||v)&&d!==u.length-1)){if(r){if(o>0)continue}else if(o-ha>=0)continue;return{partIndex:f.partIndex,segmentIndex:f.segmentIndex,startTime:n+hh({defaultDuration:s.targetDuration,durationList:u,startIndex:c,endIndex:d})}}}return{segmentIndex:u[u.length-1].segmentIndex,partIndex:u[u.length-1].partIndex,startTime:e}},Ck=function(s){return s.excludeUntil&&s.excludeUntil>Date.now()},Db=function(s){return s.excludeUntil&&s.excludeUntil===1/0},ug=function(s){const e=Ck(s);return!s.disabled&&!e},hB=function(s){return s.disabled},fB=function(s){for(let e=0;e{if(s.playlists.length===1)return!0;const t=e.attributes.BANDWIDTH||Number.MAX_VALUE;return s.playlists.filter(i=>ug(i)?(i.attributes.BANDWIDTH||0)!s&&!e||!s&&e||s&&!e?!1:!!(s===e||s.id&&e.id&&s.id===e.id||s.resolvedUri&&e.resolvedUri&&s.resolvedUri===e.resolvedUri||s.uri&&e.uri&&s.uri===e.uri),qE=function(s,e){const t=s&&s.mediaGroups&&s.mediaGroups.AUDIO||{};let i=!1;for(const n in t){for(const r in t[n])if(i=e(t[n][r]),i)break;if(i)break}return!!i},Fh=s=>{if(!s||!s.playlists||!s.playlists.length)return qE(s,t=>t.playlists&&t.playlists.length||t.uri);for(let e=0;ejA(r))||qE(s,r=>Lb(t,r))))return!1}return!0};var Hn={liveEdgeDelay:Sk,duration:wk,seekable:cB,getMediaInfoForTime:dB,isEnabled:ug,isDisabled:hB,isExcluded:Ck,isIncompatible:Db,playlistEnd:Ak,isAes:fB,hasAttribute:kk,estimateSegmentRequestTime:mB,isLowestEnabledRendition:ax,isAudioOnly:Fh,playlistMatch:Lb,segmentDurationWithParts:kb};const{log:Dk}=Le,cc=(s,e)=>`${s}-${e}`,Lk=(s,e,t)=>`placeholder-uri-${s}-${e}-${t}`,pB=({onwarn:s,oninfo:e,manifestString:t,customTagParsers:i=[],customTagMappers:n=[],llhls:r})=>{const o=new iP;s&&o.on("warn",s),e&&o.on("info",e),i.forEach(d=>o.addParser(d)),n.forEach(d=>o.addTagMapper(d)),o.push(t),o.end();const u=o.manifest;if(r||(["preloadSegment","skip","serverControl","renditionReports","partInf","partTargetDuration"].forEach(function(d){u.hasOwnProperty(d)&&delete u[d]}),u.segments&&u.segments.forEach(function(d){["parts","preloadHints"].forEach(function(f){d.hasOwnProperty(f)&&delete d[f]})})),!u.targetDuration){let d=10;u.segments&&u.segments.length&&(d=u.segments.reduce((f,p)=>Math.max(f,p.duration),0)),s&&s({message:`manifest has no targetDuration defaulting to ${d}`}),u.targetDuration=d}const c=Tk(u);if(c.length&&!u.partTargetDuration){const d=c.reduce((f,p)=>Math.max(f,p.duration),0);s&&(s({message:`manifest has no partTargetDuration defaulting to ${d}`}),Dk.error("LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.")),u.partTargetDuration=d}return u},Hc=(s,e)=>{s.mediaGroups&&["AUDIO","SUBTITLES"].forEach(t=>{if(s.mediaGroups[t])for(const i in s.mediaGroups[t])for(const n in s.mediaGroups[t][i]){const r=s.mediaGroups[t][i][n];e(r,t,i,n)}})},Rk=({playlist:s,uri:e,id:t})=>{s.id=t,s.playlistErrors_=0,e&&(s.uri=e),s.attributes=s.attributes||{}},gB=s=>{let e=s.playlists.length;for(;e--;){const t=s.playlists[e];Rk({playlist:t,id:cc(e,t.uri)}),t.resolvedUri=$n(s.uri,t.uri),s.playlists[t.id]=t,s.playlists[t.uri]=t,t.attributes.BANDWIDTH||Dk.warn("Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.")}},yB=s=>{Hc(s,e=>{e.uri&&(e.resolvedUri=$n(s.uri,e.uri))})},vB=(s,e)=>{const t=cc(0,e),i={mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:de.location.href,resolvedUri:de.location.href,playlists:[{uri:e,id:t,resolvedUri:e,attributes:{}}]};return i.playlists[t]=i.playlists[0],i.playlists[e]=i.playlists[0],i},Ik=(s,e,t=Lk)=>{s.uri=e;for(let n=0;n{if(!n.playlists||!n.playlists.length){if(i&&r==="AUDIO"&&!n.uri)for(let c=0;c(n.set(r.id,r),n),new Map)}processDateRange(e){this.pendingDateRanges_.delete(e.id),this.processedDateRanges_.set(e.id,e)}getDateRangesToProcess(){if(this.offset_===null)return[];const e={},t=[];this.pendingDateRanges_.forEach((i,n)=>{if(!this.processedDateRanges_.has(n)&&(i.startTime=i.startDate.getTime()/1e3-this.offset_,i.processDateRange=()=>this.processDateRange(i),t.push(i),!!i.class))if(e[i.class]){const r=e[i.class].push(i);i.classListIndex=r-1}else e[i.class]=[i],i.classListIndex=0});for(const i of t){const n=e[i.class]||[];i.endDate?i.endTime=i.endDate.getTime()/1e3-this.offset_:i.endOnNext&&n[i.classListIndex+1]?i.endTime=n[i.classListIndex+1].startTime:i.duration?i.endTime=i.startTime+i.duration:i.plannedDuration?i.endTime=i.startTime+i.plannedDuration:i.endTime=i.startTime}return t}trimProcessedDateRanges_(e){new Map(this.processedDateRanges_).forEach((i,n)=>{i.startDate.getTime(){const n=e.status<200||e.status>299,r=e.status>=400&&e.status<=499,o={uri:e.uri,requestType:s},u=n&&!r||i;if(t&&r)o.error=Cs({},t),o.errorType=Le.Error.NetworkRequestFailed;else if(e.aborted)o.errorType=Le.Error.NetworkRequestAborted;else if(e.timedout)o.errorType=Le.Error.NetworkRequestTimeout;else if(u){const c=i?Le.Error.NetworkBodyParserFailed:Le.Error.NetworkBadStatus;o.errorType=c,o.status=e.status,o.headers=e.headers}return o},xB=Er("CodecUtils"),Ok=function(s){const e=s.attributes||{};if(e.CODECS)return oa(e.CODECS)},Mk=(s,e)=>{const t=e.attributes||{};return s&&s.mediaGroups&&s.mediaGroups.AUDIO&&t.AUDIO&&s.mediaGroups.AUDIO[t.AUDIO]},bB=(s,e)=>{if(!Mk(s,e))return!0;const t=e.attributes||{},i=s.mediaGroups.AUDIO[t.AUDIO];for(const n in i)if(!i[n].uri&&!i[n].playlists)return!0;return!1},_h=function(s){const e={};return s.forEach(({mediaType:t,type:i,details:n})=>{e[t]=e[t]||[],e[t].push(UA(`${i}${n}`))}),Object.keys(e).forEach(function(t){if(e[t].length>1){xB(`multiple ${t} codecs found as attributes: ${e[t].join(", ")}. Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.`),e[t]=null;return}e[t]=e[t][0]}),e},YE=function(s){let e=0;return s.audio&&e++,s.video&&e++,e},fh=function(s,e){const t=e.attributes||{},i=_h(Ok(e)||[]);if(Mk(s,e)&&!i.audio&&!bB(s,e)){const n=_h(nP(s,t.AUDIO)||[]);n.audio&&(i.audio=n.audio)}return i},{EventTarget:TB}=Le,_B=(s,e)=>{if(e.endList||!e.serverControl)return s;const t={};if(e.serverControl.canBlockReload){const{preloadSegment:i}=e;let n=e.mediaSequence+e.segments.length;if(i){const r=i.parts||[],o=_k(e)-1;o>-1&&o!==r.length-1&&(t._HLS_part=o),(o>-1||r.length)&&n--}t._HLS_msn=n}if(e.serverControl&&e.serverControl.canSkipUntil&&(t._HLS_skip=e.serverControl.canSkipDateranges?"v2":"YES"),Object.keys(t).length){const i=new de.URL(s);["_HLS_skip","_HLS_msn","_HLS_part"].forEach(function(n){t.hasOwnProperty(n)&&i.searchParams.set(n,t[n])}),s=i.toString()}return s},SB=(s,e)=>{if(!s)return e;const t=Oi(s,e);if(s.preloadHints&&!e.preloadHints&&delete t.preloadHints,s.parts&&!e.parts)delete t.parts;else if(s.parts&&e.parts)for(let i=0;i{const i=s.slice(),n=e.slice();t=t||0;const r=[];let o;for(let u=0;u{!s.resolvedUri&&s.uri&&(s.resolvedUri=$n(e,s.uri)),s.key&&!s.key.resolvedUri&&(s.key.resolvedUri=$n(e,s.key.uri)),s.map&&!s.map.resolvedUri&&(s.map.resolvedUri=$n(e,s.map.uri)),s.map&&s.map.key&&!s.map.key.resolvedUri&&(s.map.key.resolvedUri=$n(e,s.map.key.uri)),s.parts&&s.parts.length&&s.parts.forEach(t=>{t.resolvedUri||(t.resolvedUri=$n(e,t.uri))}),s.preloadHints&&s.preloadHints.length&&s.preloadHints.forEach(t=>{t.resolvedUri||(t.resolvedUri=$n(e,t.uri))})},Bk=function(s){const e=s.segments||[],t=s.preloadSegment;if(t&&t.parts&&t.parts.length){if(t.preloadHints){for(let i=0;is===e||s.segments&&e.segments&&s.segments.length===e.segments.length&&s.endList===e.endList&&s.mediaSequence===e.mediaSequence&&s.preloadSegment===e.preloadSegment,ox=(s,e,t=Fk)=>{const i=Oi(s,{}),n=i.playlists[e.id];if(!n||t(n,e))return null;e.segments=Bk(e);const r=Oi(n,e);if(r.preloadSegment&&!e.preloadSegment&&delete r.preloadSegment,n.segments){if(e.skip){e.segments=e.segments||[];for(let o=0;o{Pk(o,r.resolvedUri)});for(let o=0;o{if(o.playlists)for(let f=0;f{const t=s.segments||[],i=t[t.length-1],n=i&&i.parts&&i.parts[i.parts.length-1],r=n&&n.duration||i&&i.duration;return e&&r?r*1e3:(s.partTargetDuration||s.targetDuration||10)*500},WE=(s,e,t)=>{if(!s)return;const i=[];return s.forEach(n=>{if(!n.attributes)return;const{BANDWIDTH:r,RESOLUTION:o,CODECS:u}=n.attributes;i.push({id:n.id,bandwidth:r,resolution:o,codecs:u})}),{type:e,isLive:t,renditions:i}};let sc=class extends TB{constructor(e,t,i={}){if(super(),!e)throw new Error("A non-empty playlist URL or object is required");this.logger_=Er("PlaylistLoader");const{withCredentials:n=!1}=i;this.src=e,this.vhs_=t,this.withCredentials=n,this.addDateRangesToTextTrack_=i.addDateRangesToTextTrack;const r=t.options_;this.customTagParsers=r&&r.customTagParsers||[],this.customTagMappers=r&&r.customTagMappers||[],this.llhls=r&&r.llhls,this.dateRangesStorage_=new KE,this.state="HAVE_NOTHING",this.handleMediaupdatetimeout_=this.handleMediaupdatetimeout_.bind(this),this.on("mediaupdatetimeout",this.handleMediaupdatetimeout_),this.on("loadedplaylist",this.handleLoadedPlaylist_.bind(this))}handleLoadedPlaylist_(){const e=this.media();if(!e)return;this.dateRangesStorage_.setOffset(e.segments),this.dateRangesStorage_.setPendingDateRanges(e.dateRanges);const t=this.dateRangesStorage_.getDateRangesToProcess();!t.length||!this.addDateRangesToTextTrack_||this.addDateRangesToTextTrack_(t)}handleMediaupdatetimeout_(){if(this.state!=="HAVE_METADATA")return;const e=this.media();let t=$n(this.main.uri,e.uri);this.llhls&&(t=_B(t,e)),this.state="HAVE_CURRENT_METADATA",this.request=this.vhs_.xhr({uri:t,withCredentials:this.withCredentials,requestType:"hls-playlist"},(i,n)=>{if(this.request){if(i)return this.playlistRequestError(this.request,this.media(),"HAVE_METADATA");this.haveMetadata({playlistString:this.request.responseText,url:this.media().uri,id:this.media().id})}})}playlistRequestError(e,t,i){const{uri:n,id:r}=t;this.request=null,i&&(this.state=i),this.error={playlist:this.main.playlists[r],status:e.status,message:`HLS playlist request error at URL: ${n}.`,responseText:e.responseText,code:e.status>=500?4:2,metadata:tu({requestType:e.requestType,request:e,error:e.error})},this.trigger("error")}parseManifest_({url:e,manifestString:t}){try{const i=pB({onwarn:({message:n})=>this.logger_(`m3u8-parser warn for ${e}: ${n}`),oninfo:({message:n})=>this.logger_(`m3u8-parser info for ${e}: ${n}`),manifestString:t,customTagParsers:this.customTagParsers,customTagMappers:this.customTagMappers,llhls:this.llhls});return!i.playlists||!i.playlists.length||this.excludeAudioOnlyVariants(i.playlists),i}catch(i){this.error=i,this.error.metadata={errorType:Le.Error.StreamingHlsPlaylistParserError,error:i}}}excludeAudioOnlyVariants(e){const t=i=>{const n=i.attributes||{},{width:r,height:o}=n.RESOLUTION||{};if(r&&o)return!0;const u=Ok(i)||[];return!!_h(u).video};e.some(t)&&e.forEach(i=>{t(i)||(i.excludeUntil=1/0)})}haveMetadata({playlistString:e,playlistObject:t,url:i,id:n}){this.request=null,this.state="HAVE_METADATA";const r={playlistInfo:{type:"media",uri:i}};this.trigger({type:"playlistparsestart",metadata:r});const o=t||this.parseManifest_({url:i,manifestString:e});o.lastRequest=Date.now(),Rk({playlist:o,uri:i,id:n});const u=ox(this.main,o);this.targetDuration=o.partTargetDuration||o.targetDuration,this.pendingMedia_=null,u?(this.main=u,this.media_=this.main.playlists[n]):this.trigger("playlistunchanged"),this.updateMediaUpdateTimeout_(lx(this.media(),!!u)),r.parsedPlaylist=WE(this.main.playlists,r.playlistInfo.type,!this.media_.endList),this.trigger({type:"playlistparsecomplete",metadata:r}),this.trigger("loadedplaylist")}dispose(){this.trigger("dispose"),this.stopRequest(),de.clearTimeout(this.mediaUpdateTimeout),de.clearTimeout(this.finalRenditionTimeout),this.dateRangesStorage_=new KE,this.off()}stopRequest(){if(this.request){const e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}}media(e,t){if(!e)return this.media_;if(this.state==="HAVE_NOTHING")throw new Error("Cannot switch media playlist from "+this.state);if(typeof e=="string"){if(!this.main.playlists[e])throw new Error("Unknown playlist URI: "+e);e=this.main.playlists[e]}if(de.clearTimeout(this.finalRenditionTimeout),t){const u=(e.partTargetDuration||e.targetDuration)/2*1e3||5e3;this.finalRenditionTimeout=de.setTimeout(this.media.bind(this,e,!1),u);return}const i=this.state,n=!this.media_||e.id!==this.media_.id,r=this.main.playlists[e.id];if(r&&r.endList||e.endList&&e.segments.length){this.request&&(this.request.onreadystatechange=null,this.request.abort(),this.request=null),this.state="HAVE_METADATA",this.media_=e,n&&(this.trigger("mediachanging"),i==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange"));return}if(this.updateMediaUpdateTimeout_(lx(e,!0)),!n)return;if(this.state="SWITCHING_MEDIA",this.request){if(e.resolvedUri===this.request.url)return;this.request.onreadystatechange=null,this.request.abort(),this.request=null}this.media_&&this.trigger("mediachanging"),this.pendingMedia_=e;const o={playlistInfo:{type:"media",uri:e.uri}};this.trigger({type:"playlistrequeststart",metadata:o}),this.request=this.vhs_.xhr({uri:e.resolvedUri,withCredentials:this.withCredentials,requestType:"hls-playlist"},(u,c)=>{if(this.request){if(e.lastRequest=Date.now(),e.resolvedUri=gp(e.resolvedUri,c),u)return this.playlistRequestError(this.request,e,i);this.trigger({type:"playlistrequestcomplete",metadata:o}),this.haveMetadata({playlistString:c.responseText,url:e.uri,id:e.id}),i==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange")}})}pause(){this.mediaUpdateTimeout&&(de.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),this.stopRequest(),this.state==="HAVE_NOTHING"&&(this.started=!1),this.state==="SWITCHING_MEDIA"?this.media_?this.state="HAVE_METADATA":this.state="HAVE_MAIN_MANIFEST":this.state==="HAVE_CURRENT_METADATA"&&(this.state="HAVE_METADATA")}load(e){this.mediaUpdateTimeout&&(de.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null);const t=this.media();if(e){const i=t?(t.partTargetDuration||t.targetDuration)/2*1e3:5e3;this.mediaUpdateTimeout=de.setTimeout(()=>{this.mediaUpdateTimeout=null,this.load()},i);return}if(!this.started){this.start();return}t&&!t.endList?this.trigger("mediaupdatetimeout"):this.trigger("loadedplaylist")}updateMediaUpdateTimeout_(e){this.mediaUpdateTimeout&&(de.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),!(!this.media()||this.media().endList)&&(this.mediaUpdateTimeout=de.setTimeout(()=>{this.mediaUpdateTimeout=null,this.trigger("mediaupdatetimeout"),this.updateMediaUpdateTimeout_(e)},e))}start(){if(this.started=!0,typeof this.src=="object"){this.src.uri||(this.src.uri=de.location.href),this.src.resolvedUri=this.src.uri,setTimeout(()=>{this.setupInitialPlaylist(this.src)},0);return}const e={playlistInfo:{type:"multivariant",uri:this.src}};this.trigger({type:"playlistrequeststart",metadata:e}),this.request=this.vhs_.xhr({uri:this.src,withCredentials:this.withCredentials,requestType:"hls-playlist"},(t,i)=>{if(!this.request)return;if(this.request=null,t)return this.error={status:i.status,message:`HLS playlist request error at URL: ${this.src}.`,responseText:i.responseText,code:2,metadata:tu({requestType:i.requestType,request:i,error:t})},this.state==="HAVE_NOTHING"&&(this.started=!1),this.trigger("error");this.trigger({type:"playlistrequestcomplete",metadata:e}),this.src=gp(this.src,i),this.trigger({type:"playlistparsestart",metadata:e});const n=this.parseManifest_({manifestString:i.responseText,url:this.src});e.parsedPlaylist=WE(n.playlists,e.playlistInfo.type,!1),this.trigger({type:"playlistparsecomplete",metadata:e}),this.setupInitialPlaylist(n)})}srcUri(){return typeof this.src=="string"?this.src:this.src.uri}setupInitialPlaylist(e){if(this.state="HAVE_MAIN_MANIFEST",e.playlists){this.main=e,Ik(this.main,this.srcUri()),e.playlists.forEach(i=>{i.segments=Bk(i),i.segments.forEach(n=>{Pk(n,i.resolvedUri)})}),this.trigger("loadedplaylist"),this.request||this.media(this.main.playlists[0]);return}const t=this.srcUri()||de.location.href;this.main=vB(e,t),this.haveMetadata({playlistObject:e,url:t,id:this.main.playlists[0].id}),this.trigger("loadedmetadata")}updateOrDeleteClone(e,t){const i=this.main,n=e.ID;let r=i.playlists.length;for(;r--;){const o=i.playlists[r];if(o.attributes["PATHWAY-ID"]===n){const u=o.resolvedUri,c=o.id;if(t){const d=this.createCloneURI_(o.resolvedUri,e),f=cc(n,d),p=this.createCloneAttributes_(n,o.attributes),g=this.createClonePlaylist_(o,f,e,p);i.playlists[r]=g,i.playlists[f]=g,i.playlists[d]=g}else i.playlists.splice(r,1);delete i.playlists[c],delete i.playlists[u]}}this.updateOrDeleteCloneMedia(e,t)}updateOrDeleteCloneMedia(e,t){const i=this.main,n=e.ID;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(r=>{if(!(!i.mediaGroups[r]||!i.mediaGroups[r][n])){for(const o in i.mediaGroups[r])if(o===n){for(const u in i.mediaGroups[r][o])i.mediaGroups[r][o][u].playlists.forEach((d,f)=>{const p=i.playlists[d.id],g=p.id,v=p.resolvedUri;delete i.playlists[g],delete i.playlists[v]});delete i.mediaGroups[r][o]}}}),t&&this.createClonedMediaGroups_(e)}addClonePathway(e,t={}){const i=this.main,n=i.playlists.length,r=this.createCloneURI_(t.resolvedUri,e),o=cc(e.ID,r),u=this.createCloneAttributes_(e.ID,t.attributes),c=this.createClonePlaylist_(t,o,e,u);i.playlists[n]=c,i.playlists[o]=c,i.playlists[r]=c,this.createClonedMediaGroups_(e)}createClonedMediaGroups_(e){const t=e.ID,i=e["BASE-ID"],n=this.main;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(r=>{if(!(!n.mediaGroups[r]||n.mediaGroups[r][t]))for(const o in n.mediaGroups[r]){if(o===i)n.mediaGroups[r][t]={};else continue;for(const u in n.mediaGroups[r][o]){const c=n.mediaGroups[r][o][u];n.mediaGroups[r][t][u]=Cs({},c);const d=n.mediaGroups[r][t][u],f=this.createCloneURI_(c.resolvedUri,e);d.resolvedUri=f,d.uri=f,d.playlists=[],c.playlists.forEach((p,g)=>{const v=n.playlists[p.id],b=Lk(r,t,u),_=cc(t,b);if(v&&!n.playlists[_]){const S=this.createClonePlaylist_(v,_,e),D=S.resolvedUri;n.playlists[_]=S,n.playlists[D]=S}d.playlists[g]=this.createClonePlaylist_(p,_,e)})}}})}createClonePlaylist_(e,t,i,n){const r=this.createCloneURI_(e.resolvedUri,i),o={resolvedUri:r,uri:r,id:t};return e.segments&&(o.segments=[]),n&&(o.attributes=n),Oi(e,o)}createCloneURI_(e,t){const i=new URL(e);i.hostname=t["URI-REPLACEMENT"].HOST;const n=t["URI-REPLACEMENT"].PARAMS;for(const r of Object.keys(n))i.searchParams.set(r,n[r]);return i.href}createCloneAttributes_(e,t){const i={"PATHWAY-ID":e};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(n=>{t[n]&&(i[n]=e)}),i}getKeyIdSet(e){const t=new Set;if(!e||!e.contentProtection)return t;for(const i in e.contentProtection)if(e.contentProtection[i]&&e.contentProtection[i].attributes&&e.contentProtection[i].attributes.keyId){const n=e.contentProtection[i].attributes.keyId;t.add(n.toLowerCase())}return t}};const ux=function(s,e,t,i){const n=s.responseType==="arraybuffer"?s.response:s.responseText;!e&&n&&(s.responseTime=Date.now(),s.roundTripTime=s.responseTime-s.requestTime,s.bytesReceived=n.byteLength||n.length,s.bandwidth||(s.bandwidth=Math.floor(s.bytesReceived/s.roundTripTime*8*1e3))),t.headers&&(s.responseHeaders=t.headers),e&&e.code==="ETIMEDOUT"&&(s.timedout=!0),!e&&!s.aborted&&t.statusCode!==200&&t.statusCode!==206&&t.statusCode!==0&&(e=new Error("XHR Failed with a response of: "+(s&&(n||s.responseText)))),i(e,s)},wB=(s,e)=>{if(!s||!s.size)return;let t=e;return s.forEach(i=>{t=i(t)}),t},AB=(s,e,t,i)=>{!s||!s.size||s.forEach(n=>{n(e,t,i)})},Uk=function(){const s=function e(t,i){t=Oi({timeout:45e3},t);const n=e.beforeRequest||Le.Vhs.xhr.beforeRequest,r=e._requestCallbackSet||Le.Vhs.xhr._requestCallbackSet||new Set,o=e._responseCallbackSet||Le.Vhs.xhr._responseCallbackSet;n&&typeof n=="function"&&(Le.log.warn("beforeRequest is deprecated, use onRequest instead."),r.add(n));const u=Le.Vhs.xhr.original===!0?Le.xhr:Le.Vhs.xhr,c=wB(r,t);r.delete(n);const d=u(c||t,function(p,g){return AB(o,d,p,g),ux(d,p,g,i)}),f=d.abort;return d.abort=function(){return d.aborted=!0,f.apply(d,arguments)},d.uri=t.uri,d.requestType=t.requestType,d.requestTime=Date.now(),d};return s.original=!0,s},CB=function(s){let e;const t=s.offset;return typeof s.offset=="bigint"||typeof s.length=="bigint"?e=de.BigInt(s.offset)+de.BigInt(s.length)-de.BigInt(1):e=s.offset+s.length-1,"bytes="+t+"-"+e},cx=function(s){const e={};return s.byterange&&(e.Range=CB(s.byterange)),e},kB=function(s,e){return s.start(e)+"-"+s.end(e)},DB=function(s,e){const t=s.toString(16);return"00".substring(0,2-t.length)+t+(e%2?" ":"")},LB=function(s){return s>=32&&s<126?String.fromCharCode(s):"."},jk=function(s){const e={};return Object.keys(s).forEach(t=>{const i=s[t];HA(i)?e[t]={bytes:i.buffer,byteOffset:i.byteOffset,byteLength:i.byteLength}:e[t]=i}),e},yp=function(s){const e=s.byterange||{length:1/0,offset:0};return[e.length,e.offset,s.resolvedUri].join(",")},$k=function(s){return s.resolvedUri},Hk=s=>{const e=Array.prototype.slice.call(s),t=16;let i="",n,r;for(let o=0;oHk(s),IB=s=>{let e="",t;for(t=0;t{if(!e.dateTimeObject)return null;const t=e.videoTimingInfo.transmuxerPrependedSeconds,n=e.videoTimingInfo.transmuxedPresentationStart+t,r=s-n;return new Date(e.dateTimeObject.getTime()+r*1e3)},MB=s=>s.transmuxedPresentationEnd-s.transmuxedPresentationStart-s.transmuxerPrependedSeconds,PB=(s,e)=>{let t;try{t=new Date(s)}catch{return null}if(!e||!e.segments||e.segments.length===0)return null;let i=e.segments[0];if(tu?null:(t>new Date(r)&&(i=n),{segment:i,estimatedStart:i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationStart:Hn.duration(e,e.mediaSequence+e.segments.indexOf(i)),type:i.videoTimingInfo?"accurate":"estimate"})},BB=(s,e)=>{if(!e||!e.segments||e.segments.length===0)return null;let t=0,i;for(let r=0;rt){if(s>t+n.duration*Vk)return null;i=n}return{segment:i,estimatedStart:i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationStart:t-i.duration,type:i.videoTimingInfo?"accurate":"estimate"}},FB=(s,e)=>{let t,i;try{t=new Date(s),i=new Date(e)}catch{}const n=t.getTime();return(i.getTime()-n)/1e3},UB=s=>{if(!s.segments||s.segments.length===0)return!1;for(let e=0;e{if(!t)throw new Error("getProgramTime: callback must be provided");if(!s||e===void 0)return t({message:"getProgramTime: playlist and time must be provided"});const i=BB(e,s);if(!i)return t({message:"valid programTime was not found"});if(i.type==="estimate")return t({message:"Accurate programTime could not be determined. Please seek to e.seekTime and try again",seekTime:i.estimatedStart});const n={mediaSeconds:e},r=OB(e,i.segment);return r&&(n.programDateTime=r.toISOString()),t(null,n)},Gk=({programTime:s,playlist:e,retryCount:t=2,seekTo:i,pauseAfterSeek:n=!0,tech:r,callback:o})=>{if(!o)throw new Error("seekToProgramTime: callback must be provided");if(typeof s>"u"||!e||!i)return o({message:"seekToProgramTime: programTime, seekTo and playlist must be provided"});if(!e.endList&&!r.hasStarted_)return o({message:"player must be playing a live stream to start buffering"});if(!UB(e))return o({message:"programDateTime tags must be provided in the manifest "+e.resolvedUri});const u=PB(s,e);if(!u)return o({message:`${s} was not found in the stream`});const c=u.segment,d=FB(c.dateTimeObject,s);if(u.type==="estimate"){if(t===0)return o({message:`${s} is not buffered yet. Try again`});i(u.estimatedStart+d),r.one("seeked",()=>{Gk({programTime:s,playlist:e,retryCount:t-1,seekTo:i,pauseAfterSeek:n,tech:r,callback:o})});return}const f=c.start+d,p=()=>o(null,r.currentTime());r.one("seeked",p),n&&r.pause(),i(f)},Qy=(s,e)=>{if(s.readyState===4)return e()},$B=(s,e,t,i)=>{let n=[],r,o=!1;const u=function(p,g,v,b){return g.abort(),o=!0,t(p,g,v,b)},c=function(p,g){if(o)return;if(p)return p.metadata=tu({requestType:i,request:g,error:p}),u(p,g,"",n);const v=g.responseText.substring(n&&n.byteLength||0,g.responseText.length);if(n=mP(n,VA(v,!0)),r=r||eh(n),n.length<10||r&&n.lengthu(p,g,"",n));const b=eb(n);return b==="ts"&&n.length<188?Qy(g,()=>u(p,g,"",n)):!b&&n.length<376?Qy(g,()=>u(p,g,"",n)):u(null,g,b,n)},f=e({uri:s,beforeSend(p){p.overrideMimeType("text/plain; charset=x-user-defined"),p.addEventListener("progress",function({total:g,loaded:v}){return ux(p,null,{statusCode:p.status},c)})}},function(p,g){return ux(f,p,g,c)});return f},{EventTarget:HB}=Le,XE=function(s,e){if(!Fk(s,e)||s.sidx&&e.sidx&&(s.sidx.offset!==e.sidx.offset||s.sidx.length!==e.sidx.length))return!1;if(!s.sidx&&e.sidx||s.sidx&&!e.sidx||s.segments&&!e.segments||!s.segments&&e.segments)return!1;if(!s.segments&&!e.segments)return!0;for(let t=0;t{const n=i.attributes.NAME||t;return`placeholder-uri-${s}-${e}-${n}`},GB=({mainXml:s,srcUrl:e,clientOffset:t,sidxMapping:i,previousManifest:n})=>{const r=h3(s,{manifestUri:e,clientOffset:t,sidxMapping:i,previousManifest:n});return Ik(r,e,VB),r},zB=(s,e)=>{Hc(s,(t,i,n,r)=>{(!e.mediaGroups[i][n]||!(r in e.mediaGroups[i][n]))&&delete s.mediaGroups[i][n][r]})},qB=(s,e,t)=>{let i=!0,n=Oi(s,{duration:e.duration,minimumUpdatePeriod:e.minimumUpdatePeriod,timelineStarts:e.timelineStarts});for(let r=0;r{if(r.playlists&&r.playlists.length){const d=r.playlists[0].id,f=ox(n,r.playlists[0],XE);f&&(n=f,c in n.mediaGroups[o][u]||(n.mediaGroups[o][u][c]=r),n.mediaGroups[o][u][c].playlists[0]=n.playlists[d],i=!1)}}),zB(n,e),e.minimumUpdatePeriod!==s.minimumUpdatePeriod&&(i=!1),i?null:n},KB=(s,e)=>(!s.map&&!e.map||!!(s.map&&e.map&&s.map.byterange.offset===e.map.byterange.offset&&s.map.byterange.length===e.map.byterange.length))&&s.uri===e.uri&&s.byterange.offset===e.byterange.offset&&s.byterange.length===e.byterange.length,QE=(s,e)=>{const t={};for(const i in s){const r=s[i].sidx;if(r){const o=zp(r);if(!e[o])break;const u=e[o].sidxInfo;KB(u,r)&&(t[o]=e[o])}}return t},YB=(s,e)=>{let i=QE(s.playlists,e);return Hc(s,(n,r,o,u)=>{if(n.playlists&&n.playlists.length){const c=n.playlists;i=Oi(i,QE(c,e))}}),i};class dx extends HB{constructor(e,t,i={},n){super(),this.isPaused_=!0,this.mainPlaylistLoader_=n||this,n||(this.isMain_=!0);const{withCredentials:r=!1}=i;if(this.vhs_=t,this.withCredentials=r,this.addMetadataToTextTrack=i.addMetadataToTextTrack,!e)throw new Error("A non-empty playlist URL or object is required");this.on("minimumUpdatePeriod",()=>{this.refreshXml_()}),this.on("mediaupdatetimeout",()=>{this.refreshMedia_(this.media().id)}),this.state="HAVE_NOTHING",this.loadedPlaylists_={},this.logger_=Er("DashPlaylistLoader"),this.isMain_?(this.mainPlaylistLoader_.srcUrl=e,this.mainPlaylistLoader_.sidxMapping_={}):this.childPlaylist_=e}get isPaused(){return this.isPaused_}requestErrored_(e,t,i){if(!this.request)return!0;if(this.request=null,e)return this.error=typeof e=="object"&&!(e instanceof Error)?e:{status:t.status,message:"DASH request error at URL: "+t.uri,response:t.response,code:2,metadata:e.metadata},i&&(this.state=i),this.trigger("error"),!0}addSidxSegments_(e,t,i){const n=e.sidx&&zp(e.sidx);if(!e.sidx||!n||this.mainPlaylistLoader_.sidxMapping_[n]){de.clearTimeout(this.mediaRequest_),this.mediaRequest_=de.setTimeout(()=>i(!1),0);return}const r=gp(e.sidx.resolvedUri),o=(c,d)=>{if(this.requestErrored_(c,d,t))return;const f=this.mainPlaylistLoader_.sidxMapping_,{requestType:p}=d;let g;try{g=y3(Ht(d.response).subarray(8))}catch(v){v.metadata=tu({requestType:p,request:d,parseFailure:!0}),this.requestErrored_(v,d,t);return}return f[n]={sidxInfo:e.sidx,sidx:g},Qx(e,g,e.sidx.resolvedUri),i(!0)},u="dash-sidx";this.request=$B(r,this.vhs_.xhr,(c,d,f,p)=>{if(c)return o(c,d);if(!f||f!=="mp4"){const b=f||"unknown";return o({status:d.status,message:`Unsupported ${b} container type for sidx segment at URL: ${r}`,response:"",playlist:e,internal:!0,playlistExclusionDuration:1/0,code:2},d)}const{offset:g,length:v}=e.sidx.byterange;if(p.length>=v+g)return o(c,{response:p.subarray(g,g+v),status:d.status,uri:d.uri});this.request=this.vhs_.xhr({uri:r,responseType:"arraybuffer",requestType:"dash-sidx",headers:cx({byterange:e.sidx.byterange})},o)},u)}dispose(){this.isPaused_=!0,this.trigger("dispose"),this.stopRequest(),this.loadedPlaylists_={},de.clearTimeout(this.minimumUpdatePeriodTimeout_),de.clearTimeout(this.mediaRequest_),de.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.mediaRequest_=null,this.minimumUpdatePeriodTimeout_=null,this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.off()}hasPendingRequest(){return this.request||this.mediaRequest_}stopRequest(){if(this.request){const e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}}media(e){if(!e)return this.media_;if(this.state==="HAVE_NOTHING")throw new Error("Cannot switch media playlist from "+this.state);const t=this.state;if(typeof e=="string"){if(!this.mainPlaylistLoader_.main.playlists[e])throw new Error("Unknown playlist URI: "+e);e=this.mainPlaylistLoader_.main.playlists[e]}const i=!this.media_||e.id!==this.media_.id;if(i&&this.loadedPlaylists_[e.id]&&this.loadedPlaylists_[e.id].endList){this.state="HAVE_METADATA",this.media_=e,i&&(this.trigger("mediachanging"),this.trigger("mediachange"));return}i&&(this.media_&&this.trigger("mediachanging"),this.addSidxSegments_(e,t,n=>{this.haveMetadata({startingState:t,playlist:e})}))}haveMetadata({startingState:e,playlist:t}){this.state="HAVE_METADATA",this.loadedPlaylists_[t.id]=t,de.clearTimeout(this.mediaRequest_),this.mediaRequest_=null,this.refreshMedia_(t.id),e==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange")}pause(){this.isPaused_=!0,this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.stopRequest(),de.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.isMain_&&(de.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_),this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_=null),this.state==="HAVE_NOTHING"&&(this.started=!1)}load(e){this.isPaused_=!1,de.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null;const t=this.media();if(e){const i=t?t.targetDuration/2*1e3:5e3;this.mediaUpdateTimeout=de.setTimeout(()=>this.load(),i);return}if(!this.started){this.start();return}t&&!t.endList?(this.isMain_&&!this.minimumUpdatePeriodTimeout_&&(this.trigger("minimumUpdatePeriod"),this.updateMinimumUpdatePeriodTimeout_()),this.trigger("mediaupdatetimeout")):this.trigger("loadedplaylist")}start(){if(this.started=!0,!this.isMain_){de.clearTimeout(this.mediaRequest_),this.mediaRequest_=de.setTimeout(()=>this.haveMain_(),0);return}this.requestMain_((e,t)=>{this.haveMain_(),!this.hasPendingRequest()&&!this.media_&&this.media(this.mainPlaylistLoader_.main.playlists[0])})}requestMain_(e){const t={manifestInfo:{uri:this.mainPlaylistLoader_.srcUrl}};this.trigger({type:"manifestrequeststart",metadata:t}),this.request=this.vhs_.xhr({uri:this.mainPlaylistLoader_.srcUrl,withCredentials:this.withCredentials,requestType:"dash-manifest"},(i,n)=>{if(i){const{requestType:o}=n;i.metadata=tu({requestType:o,request:n,error:i})}if(this.requestErrored_(i,n)){this.state==="HAVE_NOTHING"&&(this.started=!1);return}this.trigger({type:"manifestrequestcomplete",metadata:t});const r=n.responseText!==this.mainPlaylistLoader_.mainXml_;if(this.mainPlaylistLoader_.mainXml_=n.responseText,n.responseHeaders&&n.responseHeaders.date?this.mainLoaded_=Date.parse(n.responseHeaders.date):this.mainLoaded_=Date.now(),this.mainPlaylistLoader_.srcUrl=gp(this.mainPlaylistLoader_.srcUrl,n),r){this.handleMain_(),this.syncClientServerClock_(()=>e(n,r));return}return e(n,r)})}syncClientServerClock_(e){const t=f3(this.mainPlaylistLoader_.mainXml_);if(t===null)return this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e();if(t.method==="DIRECT")return this.mainPlaylistLoader_.clientOffset_=t.value-Date.now(),e();this.request=this.vhs_.xhr({uri:$n(this.mainPlaylistLoader_.srcUrl,t.value),method:t.method,withCredentials:this.withCredentials,requestType:"dash-clock-sync"},(i,n)=>{if(!this.request)return;if(i){const{requestType:o}=n;return this.error.metadata=tu({requestType:o,request:n,error:i}),this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e()}let r;t.method==="HEAD"?!n.responseHeaders||!n.responseHeaders.date?r=this.mainLoaded_:r=Date.parse(n.responseHeaders.date):r=Date.parse(n.responseText),this.mainPlaylistLoader_.clientOffset_=r-Date.now(),e()})}haveMain_(){this.state="HAVE_MAIN_MANIFEST",this.isMain_?this.trigger("loadedplaylist"):this.media_||this.media(this.childPlaylist_)}handleMain_(){de.clearTimeout(this.mediaRequest_),this.mediaRequest_=null;const e=this.mainPlaylistLoader_.main,t={manifestInfo:{uri:this.mainPlaylistLoader_.srcUrl}};this.trigger({type:"manifestparsestart",metadata:t});let i;try{i=GB({mainXml:this.mainPlaylistLoader_.mainXml_,srcUrl:this.mainPlaylistLoader_.srcUrl,clientOffset:this.mainPlaylistLoader_.clientOffset_,sidxMapping:this.mainPlaylistLoader_.sidxMapping_,previousManifest:e})}catch(r){this.error=r,this.error.metadata={errorType:Le.Error.StreamingDashManifestParserError,error:r},this.trigger("error")}e&&(i=qB(e,i,this.mainPlaylistLoader_.sidxMapping_)),this.mainPlaylistLoader_.main=i||e;const n=this.mainPlaylistLoader_.main.locations&&this.mainPlaylistLoader_.main.locations[0];if(n&&n!==this.mainPlaylistLoader_.srcUrl&&(this.mainPlaylistLoader_.srcUrl=n),(!e||i&&i.minimumUpdatePeriod!==e.minimumUpdatePeriod)&&this.updateMinimumUpdatePeriodTimeout_(),this.addEventStreamToMetadataTrack_(i),i){const{duration:r,endList:o}=i,u=[];i.playlists.forEach(d=>{u.push({id:d.id,bandwidth:d.attributes.BANDWIDTH,resolution:d.attributes.RESOLUTION,codecs:d.attributes.CODECS})});const c={duration:r,isLive:!o,renditions:u};t.parsedManifest=c,this.trigger({type:"manifestparsecomplete",metadata:t})}return!!i}updateMinimumUpdatePeriodTimeout_(){const e=this.mainPlaylistLoader_;e.createMupOnMedia_&&(e.off("loadedmetadata",e.createMupOnMedia_),e.createMupOnMedia_=null),e.minimumUpdatePeriodTimeout_&&(de.clearTimeout(e.minimumUpdatePeriodTimeout_),e.minimumUpdatePeriodTimeout_=null);let t=e.main&&e.main.minimumUpdatePeriod;if(t===0&&(e.media()?t=e.media().targetDuration*1e3:(e.createMupOnMedia_=e.updateMinimumUpdatePeriodTimeout_,e.one("loadedmetadata",e.createMupOnMedia_))),typeof t!="number"||t<=0){t<0&&this.logger_(`found invalid minimumUpdatePeriod of ${t}, not setting a timeout`);return}this.createMUPTimeout_(t)}createMUPTimeout_(e){const t=this.mainPlaylistLoader_;t.minimumUpdatePeriodTimeout_=de.setTimeout(()=>{t.minimumUpdatePeriodTimeout_=null,t.trigger("minimumUpdatePeriod"),t.createMUPTimeout_(e)},e)}refreshXml_(){this.requestMain_((e,t)=>{t&&(this.media_&&(this.media_=this.mainPlaylistLoader_.main.playlists[this.media_.id]),this.mainPlaylistLoader_.sidxMapping_=YB(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.sidxMapping_),this.addSidxSegments_(this.media(),this.state,i=>{this.refreshMedia_(this.media().id)}))})}refreshMedia_(e){if(!e)throw new Error("refreshMedia_ must take a media id");this.media_&&this.isMain_&&this.handleMain_();const t=this.mainPlaylistLoader_.main.playlists,i=!this.media_||this.media_!==t[e];if(i?this.media_=t[e]:this.trigger("playlistunchanged"),!this.mediaUpdateTimeout){const n=()=>{this.media().endList||(this.mediaUpdateTimeout=de.setTimeout(()=>{this.trigger("mediaupdatetimeout"),n()},lx(this.media(),!!i)))};n()}this.trigger("loadedplaylist")}addEventStreamToMetadataTrack_(e){if(e&&this.mainPlaylistLoader_.main.eventStream){const t=this.mainPlaylistLoader_.main.eventStream.map(i=>({cueTime:i.start,frames:[{data:i.messageData}]}));this.addMetadataToTextTrack("EventStream",t,this.mainPlaylistLoader_.main.duration)}}getKeyIdSet(e){if(e.contentProtection){const t=new Set;for(const i in e.contentProtection){const n=e.contentProtection[i].attributes["cenc:default_KID"];n&&t.add(n.replace(/-/g,"").toLowerCase())}return t}}}var Xs={GOAL_BUFFER_LENGTH:30,MAX_GOAL_BUFFER_LENGTH:60,BACK_BUFFER_LENGTH:30,GOAL_BUFFER_LENGTH_RATE:1,INITIAL_BANDWIDTH:4194304,BANDWIDTH_VARIANCE:1.2,BUFFER_LOW_WATER_LINE:0,MAX_BUFFER_LOW_WATER_LINE:30,EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:16,BUFFER_LOW_WATER_LINE_RATE:1,BUFFER_HIGH_WATER_LINE:30};const WB=s=>{const e=new Uint8Array(new ArrayBuffer(s.length));for(let t=0;t-1):!1},this.trigger=function(w){var k,C,I,B;if(k=x[w],!!k)if(arguments.length===2)for(I=k.length,C=0;C"u")){for(x in W)W.hasOwnProperty(x)&&(W[x]=[x.charCodeAt(0),x.charCodeAt(1),x.charCodeAt(2),x.charCodeAt(3)]);re=new Uint8Array([105,115,111,109]),Y=new Uint8Array([97,118,99,49]),J=new Uint8Array([0,0,0,1]),z=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]),Z=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]),ie={video:z,audio:Z},ee=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),j=new Uint8Array([0,0,0,0,0,0,0,0]),he=new Uint8Array([0,0,0,0,0,0,0,0]),Te=he,xe=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Ae=he,ce=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])}})(),u=function(x){var w=[],k=0,C,I,B;for(C=1;C>>1,x.samplingfrequencyindex<<7|x.channelcount<<3,6,1,2]))},f=function(){return u(W.ftyp,re,J,re,Y)},V=function(x){return u(W.hdlr,ie[x])},p=function(x){return u(W.mdat,x)},U=function(x){var w=new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,0,1,95,144,x.duration>>>24&255,x.duration>>>16&255,x.duration>>>8&255,x.duration&255,85,196,0,0]);return x.samplerate&&(w[12]=x.samplerate>>>24&255,w[13]=x.samplerate>>>16&255,w[14]=x.samplerate>>>8&255,w[15]=x.samplerate&255),u(W.mdhd,w)},P=function(x){return u(W.mdia,U(x),V(x.type),v(x))},g=function(x){return u(W.mfhd,new Uint8Array([0,0,0,0,(x&4278190080)>>24,(x&16711680)>>16,(x&65280)>>8,x&255]))},v=function(x){return u(W.minf,x.type==="video"?u(W.vmhd,ce):u(W.smhd,j),c(),G(x))},b=function(x,w){for(var k=[],C=w.length;C--;)k[C]=O(w[C]);return u.apply(null,[W.moof,g(x)].concat(k))},_=function(x){for(var w=x.length,k=[];w--;)k[w]=R(x[w]);return u.apply(null,[W.moov,D(4294967295)].concat(k).concat(S(x)))},S=function(x){for(var w=x.length,k=[];w--;)k[w]=K(x[w]);return u.apply(null,[W.mvex].concat(k))},D=function(x){var w=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,0,1,95,144,(x&4278190080)>>24,(x&16711680)>>16,(x&65280)>>8,x&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 u(W.mvhd,w)},M=function(x){var w=x.samples||[],k=new Uint8Array(4+w.length),C,I;for(I=0;I>>8),B.push(C[se].byteLength&255),B=B.concat(Array.prototype.slice.call(C[se]));for(se=0;se>>8),te.push(I[se].byteLength&255),te=te.concat(Array.prototype.slice.call(I[se]));if(ue=[W.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,(k.width&65280)>>8,k.width&255,(k.height&65280)>>8,k.height&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,19,118,105,100,101,111,106,115,45,99,111,110,116,114,105,98,45,104,108,115,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),u(W.avcC,new Uint8Array([1,k.profileIdc,k.profileCompatibility,k.levelIdc,255].concat([C.length],B,[I.length],te))),u(W.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192]))],k.sarRatio){var fe=k.sarRatio[0],_e=k.sarRatio[1];ue.push(u(W.pasp,new Uint8Array([(fe&4278190080)>>24,(fe&16711680)>>16,(fe&65280)>>8,fe&255,(_e&4278190080)>>24,(_e&16711680)>>16,(_e&65280)>>8,_e&255])))}return u.apply(null,ue)},w=function(k){return u(W.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,(k.channelcount&65280)>>8,k.channelcount&255,(k.samplesize&65280)>>8,k.samplesize&255,0,0,0,0,(k.samplerate&65280)>>8,k.samplerate&255,0,0]),d(k))}})(),L=function(x){var w=new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,(x.id&4278190080)>>24,(x.id&16711680)>>16,(x.id&65280)>>8,x.id&255,0,0,0,0,(x.duration&4278190080)>>24,(x.duration&16711680)>>16,(x.duration&65280)>>8,x.duration&255,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,(x.width&65280)>>8,x.width&255,0,0,(x.height&65280)>>8,x.height&255,0,0]);return u(W.tkhd,w)},O=function(x){var w,k,C,I,B,te,se;return w=u(W.tfhd,new Uint8Array([0,0,0,58,(x.id&4278190080)>>24,(x.id&16711680)>>16,(x.id&65280)>>8,x.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0])),te=Math.floor(x.baseMediaDecodeTime/o),se=Math.floor(x.baseMediaDecodeTime%o),k=u(W.tfdt,new Uint8Array([1,0,0,0,te>>>24&255,te>>>16&255,te>>>8&255,te&255,se>>>24&255,se>>>16&255,se>>>8&255,se&255])),B=92,x.type==="audio"?(C=Q(x,B),u(W.traf,w,k,C)):(I=M(x),C=Q(x,I.length+B),u(W.traf,w,k,C,I))},R=function(x){return x.duration=x.duration||4294967295,u(W.trak,L(x),P(x))},K=function(x){var w=new Uint8Array([0,0,0,0,(x.id&4278190080)>>24,(x.id&16711680)>>16,(x.id&65280)>>8,x.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return x.type!=="video"&&(w[w.length-1]=0),u(W.trex,w)},(function(){var x,w,k;k=function(C,I){var B=0,te=0,se=0,ue=0;return C.length&&(C[0].duration!==void 0&&(B=1),C[0].size!==void 0&&(te=2),C[0].flags!==void 0&&(se=4),C[0].compositionTimeOffset!==void 0&&(ue=8)),[0,0,B|te|se|ue,1,(C.length&4278190080)>>>24,(C.length&16711680)>>>16,(C.length&65280)>>>8,C.length&255,(I&4278190080)>>>24,(I&16711680)>>>16,(I&65280)>>>8,I&255]},w=function(C,I){var B,te,se,ue,fe,_e;for(ue=C.samples||[],I+=20+16*ue.length,se=k(ue,I),te=new Uint8Array(se.length+ue.length*16),te.set(se),B=se.length,_e=0;_e>>24,te[B++]=(fe.duration&16711680)>>>16,te[B++]=(fe.duration&65280)>>>8,te[B++]=fe.duration&255,te[B++]=(fe.size&4278190080)>>>24,te[B++]=(fe.size&16711680)>>>16,te[B++]=(fe.size&65280)>>>8,te[B++]=fe.size&255,te[B++]=fe.flags.isLeading<<2|fe.flags.dependsOn,te[B++]=fe.flags.isDependedOn<<6|fe.flags.hasRedundancy<<4|fe.flags.paddingValue<<1|fe.flags.isNonSyncSample,te[B++]=fe.flags.degradationPriority&61440,te[B++]=fe.flags.degradationPriority&15,te[B++]=(fe.compositionTimeOffset&4278190080)>>>24,te[B++]=(fe.compositionTimeOffset&16711680)>>>16,te[B++]=(fe.compositionTimeOffset&65280)>>>8,te[B++]=fe.compositionTimeOffset&255;return u(W.trun,te)},x=function(C,I){var B,te,se,ue,fe,_e;for(ue=C.samples||[],I+=20+8*ue.length,se=k(ue,I),B=new Uint8Array(se.length+ue.length*8),B.set(se),te=se.length,_e=0;_e>>24,B[te++]=(fe.duration&16711680)>>>16,B[te++]=(fe.duration&65280)>>>8,B[te++]=fe.duration&255,B[te++]=(fe.size&4278190080)>>>24,B[te++]=(fe.size&16711680)>>>16,B[te++]=(fe.size&65280)>>>8,B[te++]=fe.size&255;return u(W.trun,B)},Q=function(C,I){return C.type==="audio"?x(C,I):w(C,I)}})();var Ke={ftyp:f,mdat:p,moof:b,moov:_,initSegment:function(x){var w=f(),k=_(x),C;return C=new Uint8Array(w.byteLength+k.byteLength),C.set(w),C.set(k,w.byteLength),C}},lt=function(x){var w,k,C=[],I=[];for(I.byteLength=0,I.nalCount=0,I.duration=0,C.byteLength=0,w=0;w1&&(w=x.shift(),x.byteLength-=w.byteLength,x.nalCount-=w.nalCount,x[0][0].dts=w.dts,x[0][0].pts=w.pts,x[0][0].duration+=w.duration),x},it=function(){return{size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0,isNonSyncSample:1}}},Ot=function(x,w){var k=it();return k.dataOffset=w,k.compositionTimeOffset=x.pts-x.dts,k.duration=x.duration,k.size=4*x.length,k.size+=x.byteLength,x.keyFrame&&(k.flags.dependsOn=2,k.flags.isNonSyncSample=0),k},pt=function(x,w){var k,C,I,B,te,se=w||0,ue=[];for(k=0;kWe.ONE_SECOND_IN_TS/2))){for(fe=si()[x.samplerate],fe||(fe=w[0].data),_e=0;_e=k?x:(w.minSegmentDts=1/0,x.filter(function(C){return C.dts>=k?(w.minSegmentDts=Math.min(w.minSegmentDts,C.dts),w.minSegmentPts=w.minSegmentDts,!0):!1}))},Ei=function(x){var w,k,C=[];for(w=0;w=this.virtualRowCount&&typeof this.beforeRowOverflow=="function"&&this.beforeRowOverflow(x),this.rows.length>0&&(this.rows.push(""),this.rowIdx++);this.rows.length>this.virtualRowCount;)this.rows.shift(),this.rowIdx--},ri.prototype.isEmpty=function(){return this.rows.length===0?!0:this.rows.length===1?this.rows[0]==="":!1},ri.prototype.addText=function(x){this.rows[this.rowIdx]+=x},ri.prototype.backspace=function(){if(!this.isEmpty()){var x=this.rows[this.rowIdx];this.rows[this.rowIdx]=x.substr(0,x.length-1)}};var Yt=function(x,w,k){this.serviceNum=x,this.text="",this.currentWindow=new ri(-1),this.windows=[],this.stream=k,typeof w=="string"&&this.createTextDecoder(w)};Yt.prototype.init=function(x,w){this.startPts=x;for(var k=0;k<8;k++)this.windows[k]=new ri(k),typeof w=="function"&&(this.windows[k].beforeRowOverflow=w)},Yt.prototype.setCurrentWindow=function(x){this.currentWindow=this.windows[x]},Yt.prototype.createTextDecoder=function(x){if(typeof TextDecoder>"u")this.stream.trigger("log",{level:"warn",message:"The `encoding` option is unsupported without TextDecoder support"});else try{this.textDecoder_=new TextDecoder(x)}catch(w){this.stream.trigger("log",{level:"warn",message:"TextDecoder could not be created with "+x+" encoding. "+w})}};var Xt=function(x){x=x||{},Xt.prototype.init.call(this);var w=this,k=x.captionServices||{},C={},I;Object.keys(k).forEach(B=>{I=k[B],/^SERVICE/.test(B)&&(C[B]=I.encoding)}),this.serviceEncodings=C,this.current708Packet=null,this.services={},this.push=function(B){B.type===3?(w.new708Packet(),w.add708Bytes(B)):(w.current708Packet===null&&w.new708Packet(),w.add708Bytes(B))}};Xt.prototype=new ji,Xt.prototype.new708Packet=function(){this.current708Packet!==null&&this.push708Packet(),this.current708Packet={data:[],ptsVals:[]}},Xt.prototype.add708Bytes=function(x){var w=x.ccData,k=w>>>8,C=w&255;this.current708Packet.ptsVals.push(x.pts),this.current708Packet.data.push(k),this.current708Packet.data.push(C)},Xt.prototype.push708Packet=function(){var x=this.current708Packet,w=x.data,k=null,C=null,I=0,B=w[I++];for(x.seq=B>>6,x.sizeCode=B&63;I>5,C=B&31,k===7&&C>0&&(B=w[I++],k=B),this.pushServiceBlock(k,I,C),C>0&&(I+=C-1)},Xt.prototype.pushServiceBlock=function(x,w,k){var C,I=w,B=this.current708Packet.data,te=this.services[x];for(te||(te=this.initService(x,I));I("0"+(St&255).toString(16)).slice(-2)).join("")}if(I?(Be=[se,ue],x++):Be=[se],w.textDecoder_&&!C)_e=w.textDecoder_.decode(new Uint8Array(Be));else if(I){const He=dt(Be);_e=String.fromCharCode(parseInt(He,16))}else _e=ci(te|se);return fe.pendingNewLine&&!fe.isEmpty()&&fe.newLine(this.getPts(x)),fe.pendingNewLine=!1,fe.addText(_e),x},Xt.prototype.multiByteCharacter=function(x,w){var k=this.current708Packet.data,C=k[x+1],I=k[x+2];return Ni(C)&&Ni(I)&&(x=this.handleText(++x,w,{isMultiByte:!0})),x},Xt.prototype.setCurrentWindow=function(x,w){var k=this.current708Packet.data,C=k[x],I=C&7;return w.setCurrentWindow(I),x},Xt.prototype.defineWindow=function(x,w){var k=this.current708Packet.data,C=k[x],I=C&7;w.setCurrentWindow(I);var B=w.currentWindow;return C=k[++x],B.visible=(C&32)>>5,B.rowLock=(C&16)>>4,B.columnLock=(C&8)>>3,B.priority=C&7,C=k[++x],B.relativePositioning=(C&128)>>7,B.anchorVertical=C&127,C=k[++x],B.anchorHorizontal=C,C=k[++x],B.anchorPoint=(C&240)>>4,B.rowCount=C&15,C=k[++x],B.columnCount=C&63,C=k[++x],B.windowStyle=(C&56)>>3,B.penStyle=C&7,B.virtualRowCount=B.rowCount+1,x},Xt.prototype.setWindowAttributes=function(x,w){var k=this.current708Packet.data,C=k[x],I=w.currentWindow.winAttr;return C=k[++x],I.fillOpacity=(C&192)>>6,I.fillRed=(C&48)>>4,I.fillGreen=(C&12)>>2,I.fillBlue=C&3,C=k[++x],I.borderType=(C&192)>>6,I.borderRed=(C&48)>>4,I.borderGreen=(C&12)>>2,I.borderBlue=C&3,C=k[++x],I.borderType+=(C&128)>>5,I.wordWrap=(C&64)>>6,I.printDirection=(C&48)>>4,I.scrollDirection=(C&12)>>2,I.justify=C&3,C=k[++x],I.effectSpeed=(C&240)>>4,I.effectDirection=(C&12)>>2,I.displayEffect=C&3,x},Xt.prototype.flushDisplayed=function(x,w){for(var k=[],C=0;C<8;C++)w.windows[C].visible&&!w.windows[C].isEmpty()&&k.push(w.windows[C].getText());w.endPts=x,w.text=k.join(` `),this.pushCaption(w),w.startPts=x},Xt.prototype.pushCaption=function(x){x.text!==""&&(this.trigger("data",{startPts:x.startPts,endPts:x.endPts,text:x.text,stream:"cc708_"+x.serviceNum}),x.text="",x.startPts=x.endPts)},Xt.prototype.displayWindows=function(x,w){var k=this.current708Packet.data,C=k[++x],I=this.getPts(x);this.flushDisplayed(I,w);for(var B=0;B<8;B++)C&1<>4,I.offset=(C&12)>>2,I.penSize=C&3,C=k[++x],I.italics=(C&128)>>7,I.underline=(C&64)>>6,I.edgeType=(C&56)>>3,I.fontStyle=C&7,x},Xt.prototype.setPenColor=function(x,w){var k=this.current708Packet.data,C=k[x],I=w.currentWindow.penColor;return C=k[++x],I.fgOpacity=(C&192)>>6,I.fgRed=(C&48)>>4,I.fgGreen=(C&12)>>2,I.fgBlue=C&3,C=k[++x],I.bgOpacity=(C&192)>>6,I.bgRed=(C&48)>>4,I.bgGreen=(C&12)>>2,I.bgBlue=C&3,C=k[++x],I.edgeRed=(C&48)>>4,I.edgeGreen=(C&12)>>2,I.edgeBlue=C&3,x},Xt.prototype.setPenLocation=function(x,w){var k=this.current708Packet.data,C=k[x],I=w.currentWindow.penLoc;return w.currentWindow.pendingNewLine=!0,C=k[++x],I.row=C&15,C=k[++x],I.column=C&63,x},Xt.prototype.reset=function(x,w){var k=this.getPts(x);return this.flushDisplayed(k,w),this.initService(w.serviceNum,x)};var Hs={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,304:174,305:176,306:189,307:191,308:8482,309:162,310:163,311:9834,312:224,313:160,314:232,315:226,316:234,317:238,318:244,319:251,544:193,545:201,546:211,547:218,548:220,549:252,550:8216,551:161,552:42,553:39,554:8212,555:169,556:8480,557:8226,558:8220,559:8221,560:192,561:194,562:199,563:200,564:202,565:203,566:235,567:206,568:207,569:239,570:212,571:217,572:249,573:219,574:171,575:187,800:195,801:227,802:205,803:204,804:236,805:210,806:242,807:213,808:245,809:123,810:125,811:92,812:94,813:95,814:124,815:126,816:196,817:228,818:214,819:246,820:223,821:165,822:164,823:9474,824:197,825:229,826:216,827:248,828:9484,829:9488,830:9492,831:9496},qi=function(x){return x===null?"":(x=Hs[x]||x,String.fromCharCode(x))},Vs=14,Kn=[4352,4384,4608,4640,5376,5408,5632,5664,5888,5920,4096,4864,4896,5120,5152],Ts=function(){for(var x=[],w=Vs+1;w--;)x.push({text:"",indent:0,offset:0});return x},Zt=function(x,w){Zt.prototype.init.call(this),this.field_=x||0,this.dataChannel_=w||0,this.name_="CC"+((this.field_<<1|this.dataChannel_)+1),this.setConstants(),this.reset(),this.push=function(k){var C,I,B,te,se;if(C=k.ccData&32639,C===this.lastControlCode_){this.lastControlCode_=null;return}if((C&61440)===4096?this.lastControlCode_=C:C!==this.PADDING_&&(this.lastControlCode_=null),B=C>>>8,te=C&255,C!==this.PADDING_)if(C===this.RESUME_CAPTION_LOADING_)this.mode_="popOn";else if(C===this.END_OF_CAPTION_)this.mode_="popOn",this.clearFormatting(k.pts),this.flushDisplayed(k.pts),I=this.displayed_,this.displayed_=this.nonDisplayed_,this.nonDisplayed_=I,this.startPts_=k.pts;else if(C===this.ROLL_UP_2_ROWS_)this.rollUpRows_=2,this.setRollUp(k.pts);else if(C===this.ROLL_UP_3_ROWS_)this.rollUpRows_=3,this.setRollUp(k.pts);else if(C===this.ROLL_UP_4_ROWS_)this.rollUpRows_=4,this.setRollUp(k.pts);else if(C===this.CARRIAGE_RETURN_)this.clearFormatting(k.pts),this.flushDisplayed(k.pts),this.shiftRowsUp_(),this.startPts_=k.pts;else if(C===this.BACKSPACE_)this.mode_==="popOn"?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1);else if(C===this.ERASE_DISPLAYED_MEMORY_)this.flushDisplayed(k.pts),this.displayed_=Ts();else if(C===this.ERASE_NON_DISPLAYED_MEMORY_)this.nonDisplayed_=Ts();else if(C===this.RESUME_DIRECT_CAPTIONING_)this.mode_!=="paintOn"&&(this.flushDisplayed(k.pts),this.displayed_=Ts()),this.mode_="paintOn",this.startPts_=k.pts;else if(this.isSpecialCharacter(B,te))B=(B&3)<<8,se=qi(B|te),this[this.mode_](k.pts,se),this.column_++;else if(this.isExtCharacter(B,te))this.mode_==="popOn"?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1),B=(B&3)<<8,se=qi(B|te),this[this.mode_](k.pts,se),this.column_++;else if(this.isMidRowCode(B,te))this.clearFormatting(k.pts),this[this.mode_](k.pts," "),this.column_++,(te&14)===14&&this.addFormatting(k.pts,["i"]),(te&1)===1&&this.addFormatting(k.pts,["u"]);else if(this.isOffsetControlCode(B,te)){const fe=te&3;this.nonDisplayed_[this.row_].offset=fe,this.column_+=fe}else if(this.isPAC(B,te)){var ue=Kn.indexOf(C&7968);if(this.mode_==="rollUp"&&(ue-this.rollUpRows_+1<0&&(ue=this.rollUpRows_-1),this.setRollUp(k.pts,ue)),ue!==this.row_&&ue>=0&&ue<=14&&(this.clearFormatting(k.pts),this.row_=ue),te&1&&this.formatting_.indexOf("u")===-1&&this.addFormatting(k.pts,["u"]),(C&16)===16){const fe=(C&14)>>1;this.column_=fe*4,this.nonDisplayed_[this.row_].indent+=fe}this.isColorPAC(te)&&(te&14)===14&&this.addFormatting(k.pts,["i"])}else this.isNormalChar(B)&&(te===0&&(te=null),se=qi(B),se+=qi(te),this[this.mode_](k.pts,se),this.column_+=se.length)}};Zt.prototype=new ji,Zt.prototype.flushDisplayed=function(x){const w=C=>{this.trigger("log",{level:"warn",message:"Skipping a malformed 608 caption at index "+C+"."})},k=[];this.displayed_.forEach((C,I)=>{if(C&&C.text&&C.text.length){try{C.text=C.text.trim()}catch{w(I)}C.text.length&&k.push({text:C.text,line:I+1,position:10+Math.min(70,C.indent*10)+C.offset*2.5})}else C==null&&w(I)}),k.length&&this.trigger("data",{startPts:this.startPts_,endPts:x,content:k,stream:this.name_})},Zt.prototype.reset=function(){this.mode_="popOn",this.topRow_=0,this.startPts_=0,this.displayed_=Ts(),this.nonDisplayed_=Ts(),this.lastControlCode_=null,this.column_=0,this.row_=Vs,this.rollUpRows_=2,this.formatting_=[]},Zt.prototype.setConstants=function(){this.dataChannel_===0?(this.BASE_=16,this.EXT_=17,this.CONTROL_=(20|this.field_)<<8,this.OFFSET_=23):this.dataChannel_===1&&(this.BASE_=24,this.EXT_=25,this.CONTROL_=(28|this.field_)<<8,this.OFFSET_=31),this.PADDING_=0,this.RESUME_CAPTION_LOADING_=this.CONTROL_|32,this.END_OF_CAPTION_=this.CONTROL_|47,this.ROLL_UP_2_ROWS_=this.CONTROL_|37,this.ROLL_UP_3_ROWS_=this.CONTROL_|38,this.ROLL_UP_4_ROWS_=this.CONTROL_|39,this.CARRIAGE_RETURN_=this.CONTROL_|45,this.RESUME_DIRECT_CAPTIONING_=this.CONTROL_|41,this.BACKSPACE_=this.CONTROL_|33,this.ERASE_DISPLAYED_MEMORY_=this.CONTROL_|44,this.ERASE_NON_DISPLAYED_MEMORY_=this.CONTROL_|46},Zt.prototype.isSpecialCharacter=function(x,w){return x===this.EXT_&&w>=48&&w<=63},Zt.prototype.isExtCharacter=function(x,w){return(x===this.EXT_+1||x===this.EXT_+2)&&w>=32&&w<=63},Zt.prototype.isMidRowCode=function(x,w){return x===this.EXT_&&w>=32&&w<=47},Zt.prototype.isOffsetControlCode=function(x,w){return x===this.OFFSET_&&w>=33&&w<=35},Zt.prototype.isPAC=function(x,w){return x>=this.BASE_&&x=64&&w<=127},Zt.prototype.isColorPAC=function(x){return x>=64&&x<=79||x>=96&&x<=127},Zt.prototype.isNormalChar=function(x){return x>=32&&x<=127},Zt.prototype.setRollUp=function(x,w){if(this.mode_!=="rollUp"&&(this.row_=Vs,this.mode_="rollUp",this.flushDisplayed(x),this.nonDisplayed_=Ts(),this.displayed_=Ts()),w!==void 0&&w!==this.row_)for(var k=0;k"},"");this[this.mode_](x,k)},Zt.prototype.clearFormatting=function(x){if(this.formatting_.length){var w=this.formatting_.reverse().reduce(function(k,C){return k+""},"");this.formatting_=[],this[this.mode_](x,w)}},Zt.prototype.popOn=function(x,w){var k=this.nonDisplayed_[this.row_].text;k+=w,this.nonDisplayed_[this.row_].text=k},Zt.prototype.rollUp=function(x,w){var k=this.displayed_[this.row_].text;k+=w,this.displayed_[this.row_].text=k},Zt.prototype.shiftRowsUp_=function(){var x;for(x=0;xw&&(k=-1);Math.abs(w-x)>Li;)x+=k*Os;return x},Ne=function(x){var w,k;Ne.prototype.init.call(this),this.type_=x||Gs,this.push=function(C){if(C.type==="metadata"){this.trigger("data",C);return}this.type_!==Gs&&C.type!==this.type_||(k===void 0&&(k=C.dts),C.dts=we(C.dts,k),C.pts=we(C.pts,k),w=C.dts,this.trigger("data",C))},this.flush=function(){k=w,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.discontinuity=function(){k=void 0,w=void 0},this.reset=function(){this.discontinuity(),this.trigger("reset")}};Ne.prototype=new Ns;var ke={TimestampRolloverStream:Ne,handleRollover:we},tt=(x,w,k)=>{if(!x)return-1;for(var C=k;C";x.data[0]===le.Utf8&&(k=ut(x.data,0,w),!(k<0)&&(x.mimeType=be(x.data,w,k),w=k+1,x.pictureType=x.data[w],w++,C=ut(x.data,0,w),!(C<0)&&(x.description=ye(x.data,w,C),w=C+1,x.mimeType===I?x.url=be(x.data,w,x.data.length):x.pictureData=x.data.subarray(w,x.data.length))))},"T*":function(x){x.data[0]===le.Utf8&&(x.value=ye(x.data,1,x.data.length).replace(/\0*$/,""),x.values=x.value.split("\0"))},TXXX:function(x){var w;x.data[0]===le.Utf8&&(w=ut(x.data,0,1),w!==-1&&(x.description=ye(x.data,1,w),x.value=ye(x.data,w+1,x.data.length).replace(/\0*$/,""),x.data=x.value))},"W*":function(x){x.url=be(x.data,0,x.data.length).replace(/\0.*$/,"")},WXXX:function(x){var w;x.data[0]===le.Utf8&&(w=ut(x.data,0,1),w!==-1&&(x.description=ye(x.data,1,w),x.url=be(x.data,w+1,x.data.length).replace(/\0.*$/,"")))},PRIV:function(x){var w;for(w=0;w>>2;St*=4,St+=He[7]&3,_e.timeStamp=St,se.pts===void 0&&se.dts===void 0&&(se.pts=_e.timeStamp,se.dts=_e.timeStamp),this.trigger("timestamp",_e)}se.frames.push(_e),ue+=10,ue+=fe}while(ue>>4>1&&(te+=I[te]+1),B.pid===0)B.type="pat",x(I.subarray(te),B),this.trigger("data",B);else if(B.pid===this.pmtPid)for(B.type="pmt",x(I.subarray(te),B),this.trigger("data",B);this.packetsWaitingForPmt.length;)this.processPes_.apply(this,this.packetsWaitingForPmt.shift());else this.programMapTable===void 0?this.packetsWaitingForPmt.push([I,te,B]):this.processPes_(I,te,B)},this.processPes_=function(I,B,te){te.pid===this.programMapTable.video?te.streamType=Ft.H264_STREAM_TYPE:te.pid===this.programMapTable.audio?te.streamType=Ft.ADTS_STREAM_TYPE:te.streamType=this.programMapTable["timed-metadata"][te.pid],te.type="pes",te.data=I.subarray(B),this.trigger("data",te)}},cs.prototype=new Wt,cs.STREAM_TYPES={h264:27,adts:15},wn=function(){var x=this,w=!1,k={data:[],size:0},C={data:[],size:0},I={data:[],size:0},B,te=function(ue,fe){var _e;const Be=ue[0]<<16|ue[1]<<8|ue[2];fe.data=new Uint8Array,Be===1&&(fe.packetLength=6+(ue[4]<<8|ue[5]),fe.dataAlignmentIndicator=(ue[6]&4)!==0,_e=ue[7],_e&192&&(fe.pts=(ue[9]&14)<<27|(ue[10]&255)<<20|(ue[11]&254)<<12|(ue[12]&255)<<5|(ue[13]&254)>>>3,fe.pts*=4,fe.pts+=(ue[13]&6)>>>1,fe.dts=fe.pts,_e&64&&(fe.dts=(ue[14]&14)<<27|(ue[15]&255)<<20|(ue[16]&254)<<12|(ue[17]&255)<<5|(ue[18]&254)>>>3,fe.dts*=4,fe.dts+=(ue[18]&6)>>>1)),fe.data=ue.subarray(9+ue[8]))},se=function(ue,fe,_e){var Be=new Uint8Array(ue.size),dt={type:fe},He=0,St=0,Jt=!1,Ss;if(!(!ue.data.length||ue.size<9)){for(dt.trackId=ue.data[0].pid,He=0;He>5,ue=((w[I+6]&3)+1)*1024,fe=ue*Yn/Aa[(w[I+2]&60)>>>2],w.byteLength-I>>6&3)+1,channelcount:(w[I+2]&1)<<2|(w[I+3]&192)>>>6,samplerate:Aa[(w[I+2]&60)>>>2],samplingfrequencyindex:(w[I+2]&60)>>>2,samplesize:16,data:w.subarray(I+7+te,I+B)}),k++,I+=B}typeof _e=="number"&&(this.skipWarn_(_e,I),_e=null),w=w.subarray(I)}},this.flush=function(){k=0,this.trigger("done")},this.reset=function(){w=void 0,this.trigger("reset")},this.endTimeline=function(){w=void 0,this.trigger("endedtimeline")}},$r.prototype=new lo;var Ar=$r,Hr;Hr=function(x){var w=x.byteLength,k=0,C=0;this.length=function(){return 8*w},this.bitsAvailable=function(){return 8*w+C},this.loadWord=function(){var I=x.byteLength-w,B=new Uint8Array(4),te=Math.min(4,w);if(te===0)throw new Error("no bytes available");B.set(x.subarray(I,I+te)),k=new DataView(B.buffer).getUint32(0),C=te*8,w-=te},this.skipBits=function(I){var B;C>I?(k<<=I,C-=I):(I-=C,B=Math.floor(I/8),I-=B*8,w-=B,this.loadWord(),k<<=I,C-=I)},this.readBits=function(I){var B=Math.min(C,I),te=k>>>32-B;return C-=B,C>0?k<<=B:w>0&&this.loadWord(),B=I-B,B>0?te<>>I)!==0)return k<<=I,C-=I,I;return this.loadWord(),I+this.skipLeadingZeros()},this.skipUnsignedExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.skipExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.readUnsignedExpGolomb=function(){var I=this.skipLeadingZeros();return this.readBits(I+1)-1},this.readExpGolomb=function(){var I=this.readUnsignedExpGolomb();return 1&I?1+I>>>1:-1*(I>>>1)},this.readBoolean=function(){return this.readBits(1)===1},this.readUnsignedByte=function(){return this.readBits(8)},this.loadWord()};var lu=Hr,Ji=t,ps=lu,zs,qs,uu;qs=function(){var x=0,w,k;qs.prototype.init.call(this),this.push=function(C){var I;k?(I=new Uint8Array(k.byteLength+C.data.byteLength),I.set(k),I.set(C.data,k.byteLength),k=I):k=C.data;for(var B=k.byteLength;x3&&this.trigger("data",k.subarray(x+3)),k=null,x=0,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")}},qs.prototype=new Ji,uu={100:!0,110:!0,122:!0,244:!0,44:!0,83:!0,86:!0,118:!0,128:!0,138:!0,139:!0,134:!0},zs=function(){var x=new qs,w,k,C,I,B,te,se;zs.prototype.init.call(this),w=this,this.push=function(ue){ue.type==="video"&&(k=ue.trackId,C=ue.pts,I=ue.dts,x.push(ue))},x.on("data",function(ue){var fe={trackId:k,pts:C,dts:I,data:ue,nalUnitTypeCode:ue[0]&31};switch(fe.nalUnitTypeCode){case 5:fe.nalUnitType="slice_layer_without_partitioning_rbsp_idr";break;case 6:fe.nalUnitType="sei_rbsp",fe.escapedRBSP=B(ue.subarray(1));break;case 7:fe.nalUnitType="seq_parameter_set_rbsp",fe.escapedRBSP=B(ue.subarray(1)),fe.config=te(fe.escapedRBSP);break;case 8:fe.nalUnitType="pic_parameter_set_rbsp";break;case 9:fe.nalUnitType="access_unit_delimiter_rbsp";break}w.trigger("data",fe)}),x.on("done",function(){w.trigger("done")}),x.on("partialdone",function(){w.trigger("partialdone")}),x.on("reset",function(){w.trigger("reset")}),x.on("endedtimeline",function(){w.trigger("endedtimeline")}),this.flush=function(){x.flush()},this.partialFlush=function(){x.partialFlush()},this.reset=function(){x.reset()},this.endTimeline=function(){x.endTimeline()},se=function(ue,fe){var _e=8,Be=8,dt,He;for(dt=0;dt>4;return k=k>=0?k:0,I?k+20:k+10},fl=function(x,w){return x.length-w<10||x[w]!==73||x[w+1]!==68||x[w+2]!==51?w:(w+=cu(x,w),fl(x,w))},Uh=function(x){var w=fl(x,0);return x.length>=w+2&&(x[w]&255)===255&&(x[w+1]&240)===240&&(x[w+1]&22)===16},ml=function(x){return x[0]<<21|x[1]<<14|x[2]<<7|x[3]},du=function(x,w,k){var C,I="";for(C=w;C>5,C=x[w+4]<<3,I=x[w+3]&6144;return I|C|k},Ca=function(x,w){return x[w]===73&&x[w+1]===68&&x[w+2]===51?"timed-metadata":x[w]&!0&&(x[w+1]&240)===240?"audio":null},hu=function(x){for(var w=0;w+5>>2]}return null},pl=function(x){var w,k,C,I;w=10,x[5]&64&&(w+=4,w+=ml(x.subarray(10,14)));do{if(k=ml(x.subarray(w+4,w+8)),k<1)return null;if(I=String.fromCharCode(x[w],x[w+1],x[w+2],x[w+3]),I==="PRIV"){C=x.subarray(w+10,w+k+10);for(var B=0;B>>2;return ue*=4,ue+=se[7]&3,ue}break}}w+=10,w+=k}while(w=3;){if(x[I]===73&&x[I+1]===68&&x[I+2]===51){if(x.length-I<10||(C=fu.parseId3TagSize(x,I),I+C>x.length))break;te={type:"timed-metadata",data:x.subarray(I,I+C)},this.trigger("data",te),I+=C;continue}else if((x[I]&255)===255&&(x[I+1]&240)===240){if(x.length-I<7||(C=fu.parseAdtsSize(x,I),I+C>x.length))break;se={type:"audio",data:x.subarray(I,I+C),pts:w,dts:w},this.trigger("data",se),I+=C;continue}I++}B=x.length-I,B>0?x=x.subarray(I):x=new Uint8Array},this.reset=function(){x=new Uint8Array,this.trigger("reset")},this.endTimeline=function(){x=new Uint8Array,this.trigger("endedtimeline")}},Gr.prototype=new zc;var mu=Gr,$h=["audioobjecttype","channelcount","samplerate","samplingfrequencyindex","samplesize"],fg=$h,mg=["width","height","profileIdc","levelIdc","profileCompatibility","sarRatio"],pg=mg,uo=t,gl=Ke,yl=Nt,pu=ft,Wn=ne,Cr=Vc,vl=Lt,Hh=Ar,gg=hl.H264Stream,yg=mu,vg=Gc.isLikelyAacData,qc=Lt.ONE_SECOND_IN_TS,Vh=fg,Gh=pg,gu,co,yu,ka,xg=function(x,w){w.stream=x,this.trigger("log",w)},zh=function(x,w){for(var k=Object.keys(w),C=0;C=-1e4&&_e<=ue&&(!Be||fe>_e)&&(Be=He,fe=_e)));return Be?Be.gop:null},this.alignGopsAtStart_=function(se){var ue,fe,_e,Be,dt,He,St,Jt;for(dt=se.byteLength,He=se.nalCount,St=se.duration,ue=fe=0;ue_e.pts){ue++;continue}fe++,dt-=Be.byteLength,He-=Be.nalCount,St-=Be.duration}return fe===0?se:fe===se.length?null:(Jt=se.slice(fe),Jt.byteLength=dt,Jt.duration=St,Jt.nalCount=He,Jt.pts=Jt[0].pts,Jt.dts=Jt[0].dts,Jt)},this.alignGopsAtEnd_=function(se){var ue,fe,_e,Be,dt,He;for(ue=I.length-1,fe=se.length-1,dt=null,He=!1;ue>=0&&fe>=0;){if(_e=I[ue],Be=se[fe],_e.pts===Be.pts){He=!0;break}if(_e.pts>Be.pts){ue--;continue}ue===I.length-1&&(dt=fe),fe--}if(!He&&dt===null)return null;var St;if(He?St=fe:St=dt,St===0)return se;var Jt=se.slice(St),Ss=Jt.reduce(function(pn,Zr){return pn.byteLength+=Zr.byteLength,pn.duration+=Zr.duration,pn.nalCount+=Zr.nalCount,pn},{byteLength:0,duration:0,nalCount:0});return Jt.byteLength=Ss.byteLength,Jt.duration=Ss.duration,Jt.nalCount=Ss.nalCount,Jt.pts=Jt[0].pts,Jt.dts=Jt[0].dts,Jt},this.alignGopsWith=function(se){I=se}},gu.prototype=new uo,ka=function(x,w){this.numberOfTracks=0,this.metadataStream=w,x=x||{},typeof x.remux<"u"?this.remuxTracks=!!x.remux:this.remuxTracks=!0,typeof x.keepOriginalTimestamps=="boolean"?this.keepOriginalTimestamps=x.keepOriginalTimestamps:this.keepOriginalTimestamps=!1,this.pendingTracks=[],this.videoTrack=null,this.pendingBoxes=[],this.pendingCaptions=[],this.pendingMetadata=[],this.pendingBytes=0,this.emittedTracks=0,ka.prototype.init.call(this),this.push=function(k){if(k.content||k.text)return this.pendingCaptions.push(k);if(k.frames)return this.pendingMetadata.push(k);this.pendingTracks.push(k.track),this.pendingBytes+=k.boxes.byteLength,k.track.type==="video"&&(this.videoTrack=k.track,this.pendingBoxes.push(k.boxes)),k.track.type==="audio"&&(this.audioTrack=k.track,this.pendingBoxes.unshift(k.boxes))}},ka.prototype=new uo,ka.prototype.flush=function(x){var w=0,k={captions:[],captionStreams:{},metadata:[],info:{}},C,I,B,te=0,se;if(this.pendingTracks.length=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0);return}}if(this.videoTrack?(te=this.videoTrack.timelineStartInfo.pts,Gh.forEach(function(ue){k.info[ue]=this.videoTrack[ue]},this)):this.audioTrack&&(te=this.audioTrack.timelineStartInfo.pts,Vh.forEach(function(ue){k.info[ue]=this.audioTrack[ue]},this)),this.videoTrack||this.audioTrack){for(this.pendingTracks.length===1?k.type=this.pendingTracks[0].type:k.type="combined",this.emittedTracks+=this.pendingTracks.length,B=gl.initSegment(this.pendingTracks),k.initSegment=new Uint8Array(B.byteLength),k.initSegment.set(B),k.data=new Uint8Array(this.pendingBytes),se=0;se=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0)},ka.prototype.setRemux=function(x){this.remuxTracks=x},yu=function(x){var w=this,k=!0,C,I;yu.prototype.init.call(this),x=x||{},this.baseMediaDecodeTime=x.baseMediaDecodeTime||0,this.transmuxPipeline_={},this.setupAacPipeline=function(){var B={};this.transmuxPipeline_=B,B.type="aac",B.metadataStream=new Cr.MetadataStream,B.aacStream=new yg,B.audioTimestampRolloverStream=new Cr.TimestampRolloverStream("audio"),B.timedMetadataTimestampRolloverStream=new Cr.TimestampRolloverStream("timed-metadata"),B.adtsStream=new Hh,B.coalesceStream=new ka(x,B.metadataStream),B.headOfPipeline=B.aacStream,B.aacStream.pipe(B.audioTimestampRolloverStream).pipe(B.adtsStream),B.aacStream.pipe(B.timedMetadataTimestampRolloverStream).pipe(B.metadataStream).pipe(B.coalesceStream),B.metadataStream.on("timestamp",function(te){B.aacStream.setTimestamp(te.timeStamp)}),B.aacStream.on("data",function(te){te.type!=="timed-metadata"&&te.type!=="audio"||B.audioSegmentStream||(I=I||{timelineStartInfo:{baseMediaDecodeTime:w.baseMediaDecodeTime},codec:"adts",type:"audio"},B.coalesceStream.numberOfTracks++,B.audioSegmentStream=new co(I,x),B.audioSegmentStream.on("log",w.getLogTrigger_("audioSegmentStream")),B.audioSegmentStream.on("timingInfo",w.trigger.bind(w,"audioTimingInfo")),B.adtsStream.pipe(B.audioSegmentStream).pipe(B.coalesceStream),w.trigger("trackinfo",{hasAudio:!!I,hasVideo:!!C}))}),B.coalesceStream.on("data",this.trigger.bind(this,"data")),B.coalesceStream.on("done",this.trigger.bind(this,"done")),zh(this,B)},this.setupTsPipeline=function(){var B={};this.transmuxPipeline_=B,B.type="ts",B.metadataStream=new Cr.MetadataStream,B.packetStream=new Cr.TransportPacketStream,B.parseStream=new Cr.TransportParseStream,B.elementaryStream=new Cr.ElementaryStream,B.timestampRolloverStream=new Cr.TimestampRolloverStream,B.adtsStream=new Hh,B.h264Stream=new gg,B.captionStream=new Cr.CaptionStream(x),B.coalesceStream=new ka(x,B.metadataStream),B.headOfPipeline=B.packetStream,B.packetStream.pipe(B.parseStream).pipe(B.elementaryStream).pipe(B.timestampRolloverStream),B.timestampRolloverStream.pipe(B.h264Stream),B.timestampRolloverStream.pipe(B.adtsStream),B.timestampRolloverStream.pipe(B.metadataStream).pipe(B.coalesceStream),B.h264Stream.pipe(B.captionStream).pipe(B.coalesceStream),B.elementaryStream.on("data",function(te){var se;if(te.type==="metadata"){for(se=te.tracks.length;se--;)!C&&te.tracks[se].type==="video"?(C=te.tracks[se],C.timelineStartInfo.baseMediaDecodeTime=w.baseMediaDecodeTime):!I&&te.tracks[se].type==="audio"&&(I=te.tracks[se],I.timelineStartInfo.baseMediaDecodeTime=w.baseMediaDecodeTime);C&&!B.videoSegmentStream&&(B.coalesceStream.numberOfTracks++,B.videoSegmentStream=new gu(C,x),B.videoSegmentStream.on("log",w.getLogTrigger_("videoSegmentStream")),B.videoSegmentStream.on("timelineStartInfo",function(ue){I&&!x.keepOriginalTimestamps&&(I.timelineStartInfo=ue,B.audioSegmentStream.setEarliestDts(ue.dts-w.baseMediaDecodeTime))}),B.videoSegmentStream.on("processedGopsInfo",w.trigger.bind(w,"gopInfo")),B.videoSegmentStream.on("segmentTimingInfo",w.trigger.bind(w,"videoSegmentTimingInfo")),B.videoSegmentStream.on("baseMediaDecodeTime",function(ue){I&&B.audioSegmentStream.setVideoBaseMediaDecodeTime(ue)}),B.videoSegmentStream.on("timingInfo",w.trigger.bind(w,"videoTimingInfo")),B.h264Stream.pipe(B.videoSegmentStream).pipe(B.coalesceStream)),I&&!B.audioSegmentStream&&(B.coalesceStream.numberOfTracks++,B.audioSegmentStream=new co(I,x),B.audioSegmentStream.on("log",w.getLogTrigger_("audioSegmentStream")),B.audioSegmentStream.on("timingInfo",w.trigger.bind(w,"audioTimingInfo")),B.audioSegmentStream.on("segmentTimingInfo",w.trigger.bind(w,"audioSegmentTimingInfo")),B.adtsStream.pipe(B.audioSegmentStream).pipe(B.coalesceStream)),w.trigger("trackinfo",{hasAudio:!!I,hasVideo:!!C})}}),B.coalesceStream.on("data",this.trigger.bind(this,"data")),B.coalesceStream.on("id3Frame",function(te){te.dispatchType=B.metadataStream.dispatchType,w.trigger("id3Frame",te)}),B.coalesceStream.on("caption",this.trigger.bind(this,"caption")),B.coalesceStream.on("done",this.trigger.bind(this,"done")),zh(this,B)},this.setBaseMediaDecodeTime=function(B){var te=this.transmuxPipeline_;x.keepOriginalTimestamps||(this.baseMediaDecodeTime=B),I&&(I.timelineStartInfo.dts=void 0,I.timelineStartInfo.pts=void 0,Wn.clearDtsInfo(I),te.audioTimestampRolloverStream&&te.audioTimestampRolloverStream.discontinuity()),C&&(te.videoSegmentStream&&(te.videoSegmentStream.gopCache_=[]),C.timelineStartInfo.dts=void 0,C.timelineStartInfo.pts=void 0,Wn.clearDtsInfo(C),te.captionStream.reset()),te.timestampRolloverStream&&te.timestampRolloverStream.discontinuity()},this.setAudioAppendStart=function(B){I&&this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(B)},this.setRemux=function(B){var te=this.transmuxPipeline_;x.remux=B,te&&te.coalesceStream&&te.coalesceStream.setRemux(B)},this.alignGopsWith=function(B){C&&this.transmuxPipeline_.videoSegmentStream&&this.transmuxPipeline_.videoSegmentStream.alignGopsWith(B)},this.getLogTrigger_=function(B){var te=this;return function(se){se.stream=B,te.trigger("log",se)}},this.push=function(B){if(k){var te=vg(B);te&&this.transmuxPipeline_.type!=="aac"?this.setupAacPipeline():!te&&this.transmuxPipeline_.type!=="ts"&&this.setupTsPipeline(),k=!1}this.transmuxPipeline_.headOfPipeline.push(B)},this.flush=function(){k=!0,this.transmuxPipeline_.headOfPipeline.flush()},this.endTimeline=function(){this.transmuxPipeline_.headOfPipeline.endTimeline()},this.reset=function(){this.transmuxPipeline_.headOfPipeline&&this.transmuxPipeline_.headOfPipeline.reset()},this.resetCaptions=function(){this.transmuxPipeline_.captionStream&&this.transmuxPipeline_.captionStream.reset()}},yu.prototype=new uo;var bg={Transmuxer:yu},Tg=function(x){return x>>>0},_g=function(x){return("00"+x.toString(16)).slice(-2)},ho={toUnsigned:Tg,toHexString:_g},xl=function(x){var w="";return w+=String.fromCharCode(x[0]),w+=String.fromCharCode(x[1]),w+=String.fromCharCode(x[2]),w+=String.fromCharCode(x[3]),w},Yh=xl,Wh=ho.toUnsigned,Xh=Yh,Kc=function(x,w){var k=[],C,I,B,te,se;if(!w.length)return null;for(C=0;C1?C+I:x.byteLength,B===w[0]&&(w.length===1?k.push(x.subarray(C+8,te)):(se=Kc(x.subarray(C+8,te),w.slice(1)),se.length&&(k=k.concat(se)))),C=te;return k},vu=Kc,Qh=ho.toUnsigned,fo=r.getUint64,Sg=function(x){var w={version:x[0],flags:new Uint8Array(x.subarray(1,4))};return w.version===1?w.baseMediaDecodeTime=fo(x.subarray(4)):w.baseMediaDecodeTime=Qh(x[4]<<24|x[5]<<16|x[6]<<8|x[7]),w},Yc=Sg,Eg=function(x){var w=new DataView(x.buffer,x.byteOffset,x.byteLength),k={version:x[0],flags:new Uint8Array(x.subarray(1,4)),trackId:w.getUint32(4)},C=k.flags[2]&1,I=k.flags[2]&2,B=k.flags[2]&8,te=k.flags[2]&16,se=k.flags[2]&32,ue=k.flags[0]&65536,fe=k.flags[0]&131072,_e;return _e=8,C&&(_e+=4,k.baseDataOffset=w.getUint32(12),_e+=4),I&&(k.sampleDescriptionIndex=w.getUint32(_e),_e+=4),B&&(k.defaultSampleDuration=w.getUint32(_e),_e+=4),te&&(k.defaultSampleSize=w.getUint32(_e),_e+=4),se&&(k.defaultSampleFlags=w.getUint32(_e)),ue&&(k.durationIsEmpty=!0),!C&&fe&&(k.baseDataOffsetIsMoof=!0),k},Wc=Eg,Zh=function(x){return{isLeading:(x[0]&12)>>>2,dependsOn:x[0]&3,isDependedOn:(x[1]&192)>>>6,hasRedundancy:(x[1]&48)>>>4,paddingValue:(x[1]&14)>>>1,isNonSyncSample:x[1]&1,degradationPriority:x[2]<<8|x[3]}},bl=Zh,mo=bl,wg=function(x){var w={version:x[0],flags:new Uint8Array(x.subarray(1,4)),samples:[]},k=new DataView(x.buffer,x.byteOffset,x.byteLength),C=w.flags[2]&1,I=w.flags[2]&4,B=w.flags[1]&1,te=w.flags[1]&2,se=w.flags[1]&4,ue=w.flags[1]&8,fe=k.getUint32(4),_e=8,Be;for(C&&(w.dataOffset=k.getInt32(_e),_e+=4),I&&fe&&(Be={flags:mo(x.subarray(_e,_e+4))},_e+=4,B&&(Be.duration=k.getUint32(_e),_e+=4),te&&(Be.size=k.getUint32(_e),_e+=4),ue&&(w.version===1?Be.compositionTimeOffset=k.getInt32(_e):Be.compositionTimeOffset=k.getUint32(_e),_e+=4),w.samples.push(Be),fe--);fe--;)Be={},B&&(Be.duration=k.getUint32(_e),_e+=4),te&&(Be.size=k.getUint32(_e),_e+=4),se&&(Be.flags=mo(x.subarray(_e,_e+4)),_e+=4),ue&&(w.version===1?Be.compositionTimeOffset=k.getInt32(_e):Be.compositionTimeOffset=k.getUint32(_e),_e+=4),w.samples.push(Be);return w},Tl=wg,Xc={tfdt:Yc,trun:Tl},Qc={parseTfdt:Xc.tfdt,parseTrun:Xc.trun},Zc=function(x){for(var w=0,k=String.fromCharCode(x[w]),C="";k!=="\0";)C+=k,w++,k=String.fromCharCode(x[w]);return C+=k,C},Jc={uint8ToCString:Zc},_l=Jc.uint8ToCString,Jh=r.getUint64,ef=function(x){var w=4,k=x[0],C,I,B,te,se,ue,fe,_e;if(k===0){C=_l(x.subarray(w)),w+=C.length,I=_l(x.subarray(w)),w+=I.length;var Be=new DataView(x.buffer);B=Be.getUint32(w),w+=4,se=Be.getUint32(w),w+=4,ue=Be.getUint32(w),w+=4,fe=Be.getUint32(w),w+=4}else if(k===1){var Be=new DataView(x.buffer);B=Be.getUint32(w),w+=4,te=Jh(x.subarray(w)),w+=8,ue=Be.getUint32(w),w+=4,fe=Be.getUint32(w),w+=4,C=_l(x.subarray(w)),w+=C.length,I=_l(x.subarray(w)),w+=I.length}_e=new Uint8Array(x.subarray(w,x.byteLength));var dt={scheme_id_uri:C,value:I,timescale:B||1,presentation_time:te,presentation_time_delta:se,event_duration:ue,id:fe,message_data:_e};return Cg(k,dt)?dt:void 0},Ag=function(x,w,k,C){return x||x===0?x/w:C+k/w},Cg=function(x,w){var k=w.scheme_id_uri!=="\0",C=x===0&&tf(w.presentation_time_delta)&&k,I=x===1&&tf(w.presentation_time)&&k;return!(x>1)&&C||I},tf=function(x){return x!==void 0||x!==null},kg={parseEmsgBox:ef,scaleTime:Ag},Sl;typeof window<"u"?Sl=window:typeof s<"u"?Sl=s:typeof self<"u"?Sl=self:Sl={};var un=Sl,zr=ho.toUnsigned,po=ho.toHexString,rs=vu,Da=Yh,xu=kg,ed=Wc,Dg=Tl,go=Yc,td=r.getUint64,yo,bu,id,qr,La,El,sd,kr=un,sf=ct.parseId3Frames;yo=function(x){var w={},k=rs(x,["moov","trak"]);return k.reduce(function(C,I){var B,te,se,ue,fe;return B=rs(I,["tkhd"])[0],!B||(te=B[0],se=te===0?12:20,ue=zr(B[se]<<24|B[se+1]<<16|B[se+2]<<8|B[se+3]),fe=rs(I,["mdia","mdhd"])[0],!fe)?null:(te=fe[0],se=te===0?12:20,C[ue]=zr(fe[se]<<24|fe[se+1]<<16|fe[se+2]<<8|fe[se+3]),C)},w)},bu=function(x,w){var k;k=rs(w,["moof","traf"]);var C=k.reduce(function(I,B){var te=rs(B,["tfhd"])[0],se=zr(te[4]<<24|te[5]<<16|te[6]<<8|te[7]),ue=x[se]||9e4,fe=rs(B,["tfdt"])[0],_e=new DataView(fe.buffer,fe.byteOffset,fe.byteLength),Be;fe[0]===1?Be=td(fe.subarray(4,12)):Be=_e.getUint32(4);let dt;return typeof Be=="bigint"?dt=Be/kr.BigInt(ue):typeof Be=="number"&&!isNaN(Be)&&(dt=Be/ue),dt11?(I.codec+=".",I.codec+=po(He[9]),I.codec+=po(He[10]),I.codec+=po(He[11])):I.codec="avc1.4d400d"):/^mp4[a,v]$/i.test(I.codec)?(He=dt.subarray(28),St=Da(He.subarray(4,8)),St==="esds"&&He.length>20&&He[19]!==0?(I.codec+="."+po(He[19]),I.codec+="."+po(He[20]>>>2&63).replace(/^0/,"")):I.codec="mp4a.40.2"):I.codec=I.codec.toLowerCase())}var Jt=rs(C,["mdia","mdhd"])[0];Jt&&(I.timescale=El(Jt)),k.push(I)}),k},sd=function(x,w=0){var k=rs(x,["emsg"]);return k.map(C=>{var I=xu.parseEmsgBox(new Uint8Array(C)),B=sf(I.message_data);return{cueTime:xu.scaleTime(I.presentation_time,I.timescale,I.presentation_time_delta,w),duration:xu.scaleTime(I.event_duration,I.timescale),frames:B}})};var vo={findBox:rs,parseType:Da,timescale:yo,startTime:bu,compositionStartTime:id,videoTrackIds:qr,tracks:La,getTimescaleFromMediaHeader:El,getEmsgID3:sd};const{parseTrun:nf}=Qc,{findBox:rf}=vo;var af=un,Lg=function(x){var w=rf(x,["moof","traf"]),k=rf(x,["mdat"]),C=[];return k.forEach(function(I,B){var te=w[B];C.push({mdat:I,traf:te})}),C},of=function(x,w,k){var C=w,I=k.defaultSampleDuration||0,B=k.defaultSampleSize||0,te=k.trackId,se=[];return x.forEach(function(ue){var fe=nf(ue),_e=fe.samples;_e.forEach(function(Be){Be.duration===void 0&&(Be.duration=I),Be.size===void 0&&(Be.size=B),Be.trackId=te,Be.dts=C,Be.compositionTimeOffset===void 0&&(Be.compositionTimeOffset=0),typeof C=="bigint"?(Be.pts=C+af.BigInt(Be.compositionTimeOffset),C+=af.BigInt(Be.duration)):(Be.pts=C+Be.compositionTimeOffset,C+=Be.duration)}),se=se.concat(_e)}),se},nd={getMdatTrafPairs:Lg,parseSamples:of},rd=Ii.discardEmulationPreventionBytes,Xn=vi.CaptionStream,xo=vu,Cn=Yc,bo=Wc,{getMdatTrafPairs:ad,parseSamples:Tu}=nd,_u=function(x,w){for(var k=x,C=0;C0?Cn(_e[0]).baseMediaDecodeTime:0,dt=xo(te,["trun"]),He,St;w===fe&&dt.length>0&&(He=Tu(dt,Be,ue),St=od(B,He,fe),k[fe]||(k[fe]={seiNals:[],logs:[]}),k[fe].seiNals=k[fe].seiNals.concat(St.seiNals),k[fe].logs=k[fe].logs.concat(St.logs))}),k},lf=function(x,w,k){var C;if(w===null)return null;C=Ra(x,w);var I=C[w]||{};return{seiNals:I.seiNals,logs:I.logs,timescale:k}},Su=function(){var x=!1,w,k,C,I,B,te;this.isInitialized=function(){return x},this.init=function(se){w=new Xn,x=!0,te=se?se.isPartial:!1,w.on("data",function(ue){ue.startTime=ue.startPts/I,ue.endTime=ue.endPts/I,B.captions.push(ue),B.captionStreams[ue.stream]=!0}),w.on("log",function(ue){B.logs.push(ue)})},this.isNewInit=function(se,ue){return se&&se.length===0||ue&&typeof ue=="object"&&Object.keys(ue).length===0?!1:C!==se[0]||I!==ue[C]},this.parse=function(se,ue,fe){var _e;if(this.isInitialized()){if(!ue||!fe)return null;if(this.isNewInit(ue,fe))C=ue[0],I=fe[C];else if(C===null||!I)return k.push(se),null}else return null;for(;k.length>0;){var Be=k.shift();this.parse(Be,ue,fe)}return _e=lf(se,C,I),_e&&_e.logs&&(B.logs=B.logs.concat(_e.logs)),_e===null||!_e.seiNals?B.logs.length?{logs:B.logs,captions:[],captionStreams:[]}:null:(this.pushNals(_e.seiNals),this.flushStream(),B)},this.pushNals=function(se){if(!this.isInitialized()||!se||se.length===0)return null;se.forEach(function(ue){w.push(ue)})},this.flushStream=function(){if(!this.isInitialized())return null;te?w.partialFlush():w.flush()},this.clearParsedCaptions=function(){B.captions=[],B.captionStreams={},B.logs=[]},this.resetCaptionStream=function(){if(!this.isInitialized())return null;w.reset()},this.clearAllCaptions=function(){this.clearParsedCaptions(),this.resetCaptionStream()},this.reset=function(){k=[],C=null,I=null,B?this.clearParsedCaptions():B={captions:[],captionStreams:{},logs:[]},this.resetCaptionStream()},this.reset()},To=Su;const{parseTfdt:Rg}=Qc,gs=vu,{getTimescaleFromMediaHeader:ld}=vo,{parseSamples:Dr,getMdatTrafPairs:uf}=nd;var Kr=function(){let x=9e4;this.init=function(w){const k=gs(w,["moov","trak","mdia","mdhd"])[0];k&&(x=ld(k))},this.parseSegment=function(w){const k=[],C=uf(w);let I=0;return C.forEach(function(B){const te=B.mdat,se=B.traf,ue=gs(se,["tfdt"])[0],fe=gs(se,["tfhd"])[0],_e=gs(se,["trun"]);if(ue&&(I=Rg(ue).baseMediaDecodeTime),_e.length&&fe){const Be=Dr(_e,I,fe);let dt=0;Be.forEach(function(He){const St="utf-8",Jt=new TextDecoder(St),Ss=te.slice(dt,dt+He.size);if(gs(Ss,["vtte"])[0]){dt+=He.size;return}gs(Ss,["vttc"]).forEach(function(kl){const es=gs(kl,["payl"])[0],Ia=gs(kl,["sttg"])[0],Lr=He.pts/x,Jr=(He.pts+He.duration)/x;let Mi,fr;if(es)try{Mi=Jt.decode(es)}catch(Ks){console.error(Ks)}if(Ia)try{fr=Jt.decode(Ia)}catch(Ks){console.error(Ks)}He.duration&&Mi&&k.push({cueText:Mi,start:Lr,end:Jr,settings:fr})}),dt+=He.size})}}),k}},wl=di,cd=function(x){var w=x[1]&31;return w<<=8,w|=x[2],w},_o=function(x){return!!(x[1]&64)},Al=function(x){var w=0;return(x[3]&48)>>>4>1&&(w+=x[4]+1),w},kn=function(x,w){var k=cd(x);return k===0?"pat":k===w?"pmt":w?"pes":null},So=function(x){var w=_o(x),k=4+Al(x);return w&&(k+=x[k]+1),(x[k+10]&31)<<8|x[k+11]},Eo=function(x){var w={},k=_o(x),C=4+Al(x);if(k&&(C+=x[C]+1),!!(x[C+5]&1)){var I,B,te;I=(x[C+1]&15)<<8|x[C+2],B=3+I-4,te=(x[C+10]&15)<<8|x[C+11];for(var se=12+te;se=x.byteLength)return null;var C=null,I;return I=x[k+7],I&192&&(C={},C.pts=(x[k+9]&14)<<27|(x[k+10]&255)<<20|(x[k+11]&254)<<12|(x[k+12]&255)<<5|(x[k+13]&254)>>>3,C.pts*=4,C.pts+=(x[k+13]&6)>>>1,C.dts=C.pts,I&64&&(C.dts=(x[k+14]&14)<<27|(x[k+15]&255)<<20|(x[k+16]&254)<<12|(x[k+17]&255)<<5|(x[k+18]&254)>>>3,C.dts*=4,C.dts+=(x[k+18]&6)>>>1)),C},cn=function(x){switch(x){case 5:return"slice_layer_without_partitioning_rbsp_idr";case 6:return"sei_rbsp";case 7:return"seq_parameter_set_rbsp";case 8:return"pic_parameter_set_rbsp";case 9:return"access_unit_delimiter_rbsp";default:return null}},Dn=function(x){for(var w=4+Al(x),k=x.subarray(w),C=0,I=0,B=!1,te;I3&&(te=cn(k[I+3]&31),te==="slice_layer_without_partitioning_rbsp_idr"&&(B=!0)),B},Yr={parseType:kn,parsePat:So,parsePmt:Eo,parsePayloadUnitStartIndicator:_o,parsePesType:Eu,parsePesTime:Cl,videoPacketContainsKeyFrame:Dn},Qn=di,en=ke.handleRollover,hi={};hi.ts=Yr,hi.aac=Gc;var Wr=Lt.ONE_SECOND_IN_TS,Ms=188,Ln=71,cf=function(x,w){for(var k=0,C=Ms,I,B;C=0;){if(x[C]===Ln&&(x[I]===Ln||I===x.byteLength)){if(B=x.subarray(C,I),te=hi.ts.parseType(B,w.pid),te==="pes"&&(se=hi.ts.parsePesType(B,w.table),ue=hi.ts.parsePayloadUnitStartIndicator(B),se==="audio"&&ue&&(fe=hi.ts.parsePesTime(B),fe&&(fe.type="audio",k.audio.push(fe),_e=!0))),_e)break;C-=Ms,I-=Ms;continue}C--,I--}},Ki=function(x,w,k){for(var C=0,I=Ms,B,te,se,ue,fe,_e,Be,dt,He=!1,St={data:[],size:0};I=0;){if(x[C]===Ln&&x[I]===Ln){if(B=x.subarray(C,I),te=hi.ts.parseType(B,w.pid),te==="pes"&&(se=hi.ts.parsePesType(B,w.table),ue=hi.ts.parsePayloadUnitStartIndicator(B),se==="video"&&ue&&(fe=hi.ts.parsePesTime(B),fe&&(fe.type="video",k.video.push(fe),He=!0))),He)break;C-=Ms,I-=Ms;continue}C--,I--}},xi=function(x,w){if(x.audio&&x.audio.length){var k=w;(typeof k>"u"||isNaN(k))&&(k=x.audio[0].dts),x.audio.forEach(function(B){B.dts=en(B.dts,k),B.pts=en(B.pts,k),B.dtsTime=B.dts/Wr,B.ptsTime=B.pts/Wr})}if(x.video&&x.video.length){var C=w;if((typeof C>"u"||isNaN(C))&&(C=x.video[0].dts),x.video.forEach(function(B){B.dts=en(B.dts,C),B.pts=en(B.pts,C),B.dtsTime=B.dts/Wr,B.ptsTime=B.pts/Wr}),x.firstKeyFrame){var I=x.firstKeyFrame;I.dts=en(I.dts,C),I.pts=en(I.pts,C),I.dtsTime=I.dts/Wr,I.ptsTime=I.pts/Wr}}},Xr=function(x){for(var w=!1,k=0,C=null,I=null,B=0,te=0,se;x.length-te>=3;){var ue=hi.aac.parseType(x,te);switch(ue){case"timed-metadata":if(x.length-te<10){w=!0;break}if(B=hi.aac.parseId3TagSize(x,te),B>x.length){w=!0;break}I===null&&(se=x.subarray(te,te+B),I=hi.aac.parseAacTimestamp(se)),te+=B;break;case"audio":if(x.length-te<7){w=!0;break}if(B=hi.aac.parseAdtsSize(x,te),B>x.length){w=!0;break}C===null&&(se=x.subarray(te,te+B),C=hi.aac.parseSampleRate(se)),k++,te+=B;break;default:te++;break}if(w)return null}if(C===null||I===null)return null;var fe=Wr/C,_e={audio:[{type:"audio",dts:I,pts:I},{type:"audio",dts:I+k*1024*fe,pts:I+k*1024*fe}]};return _e},Rn=function(x){var w={pid:null,table:null},k={};cf(x,w);for(var C in w.table)if(w.table.hasOwnProperty(C)){var I=w.table[C];switch(I){case Qn.H264_STREAM_TYPE:k.video=[],Ki(x,w,k),k.video.length===0&&delete k.video;break;case Qn.ADTS_STREAM_TYPE:k.audio=[],ks(x,w,k),k.audio.length===0&&delete k.audio;break}}return k},dd=function(x,w){var k=hi.aac.isLikelyAacData(x),C;return k?C=Xr(x):C=Rn(x),!C||!C.audio&&!C.video?null:(xi(C,w),C)},Qr={inspect:dd,parseAudioPes_:ks};const df=function(x,w){w.on("data",function(k){const C=k.initSegment;k.initSegment={data:C.buffer,byteOffset:C.byteOffset,byteLength:C.byteLength};const I=k.data;k.data=I.buffer,x.postMessage({action:"data",segment:k,byteOffset:I.byteOffset,byteLength:I.byteLength},[k.data])}),w.on("done",function(k){x.postMessage({action:"done"})}),w.on("gopInfo",function(k){x.postMessage({action:"gopInfo",gopInfo:k})}),w.on("videoSegmentTimingInfo",function(k){const C={start:{decode:Lt.videoTsToSeconds(k.start.dts),presentation:Lt.videoTsToSeconds(k.start.pts)},end:{decode:Lt.videoTsToSeconds(k.end.dts),presentation:Lt.videoTsToSeconds(k.end.pts)},baseMediaDecodeTime:Lt.videoTsToSeconds(k.baseMediaDecodeTime)};k.prependedContentDuration&&(C.prependedContentDuration=Lt.videoTsToSeconds(k.prependedContentDuration)),x.postMessage({action:"videoSegmentTimingInfo",videoSegmentTimingInfo:C})}),w.on("audioSegmentTimingInfo",function(k){const C={start:{decode:Lt.videoTsToSeconds(k.start.dts),presentation:Lt.videoTsToSeconds(k.start.pts)},end:{decode:Lt.videoTsToSeconds(k.end.dts),presentation:Lt.videoTsToSeconds(k.end.pts)},baseMediaDecodeTime:Lt.videoTsToSeconds(k.baseMediaDecodeTime)};k.prependedContentDuration&&(C.prependedContentDuration=Lt.videoTsToSeconds(k.prependedContentDuration)),x.postMessage({action:"audioSegmentTimingInfo",audioSegmentTimingInfo:C})}),w.on("id3Frame",function(k){x.postMessage({action:"id3Frame",id3Frame:k})}),w.on("caption",function(k){x.postMessage({action:"caption",caption:k})}),w.on("trackinfo",function(k){x.postMessage({action:"trackinfo",trackInfo:k})}),w.on("audioTimingInfo",function(k){x.postMessage({action:"audioTimingInfo",audioTimingInfo:{start:Lt.videoTsToSeconds(k.start),end:Lt.videoTsToSeconds(k.end)}})}),w.on("videoTimingInfo",function(k){x.postMessage({action:"videoTimingInfo",videoTimingInfo:{start:Lt.videoTsToSeconds(k.start),end:Lt.videoTsToSeconds(k.end)}})}),w.on("log",function(k){x.postMessage({action:"log",log:k})})};class hd{constructor(w,k){this.options=k||{},this.self=w,this.init()}init(){this.transmuxer&&this.transmuxer.dispose(),this.transmuxer=new bg.Transmuxer(this.options),df(this.self,this.transmuxer)}pushMp4Captions(w){this.captionParser||(this.captionParser=new To,this.captionParser.init());const k=new Uint8Array(w.data,w.byteOffset,w.byteLength),C=this.captionParser.parse(k,w.trackIds,w.timescales);this.self.postMessage({action:"mp4Captions",captions:C&&C.captions||[],logs:C&&C.logs||[],data:k.buffer},[k.buffer])}initMp4WebVttParser(w){this.webVttParser||(this.webVttParser=new Kr);const k=new Uint8Array(w.data,w.byteOffset,w.byteLength);this.webVttParser.init(k)}getMp4WebVttText(w){this.webVttParser||(this.webVttParser=new Kr);const k=new Uint8Array(w.data,w.byteOffset,w.byteLength),C=this.webVttParser.parseSegment(k);this.self.postMessage({action:"getMp4WebVttText",mp4VttCues:C||[],data:k.buffer},[k.buffer])}probeMp4StartTime({timescales:w,data:k}){const C=vo.startTime(w,k);this.self.postMessage({action:"probeMp4StartTime",startTime:C,data:k},[k.buffer])}probeMp4Tracks({data:w}){const k=vo.tracks(w);this.self.postMessage({action:"probeMp4Tracks",tracks:k,data:w},[w.buffer])}probeEmsgID3({data:w,offset:k}){const C=vo.getEmsgID3(w,k);this.self.postMessage({action:"probeEmsgID3",id3Frames:C,emsgData:w},[w.buffer])}probeTs({data:w,baseStartTime:k}){const C=typeof k=="number"&&!isNaN(k)?k*Lt.ONE_SECOND_IN_TS:void 0,I=Qr.inspect(w,C);let B=null;I&&(B={hasVideo:I.video&&I.video.length===2||!1,hasAudio:I.audio&&I.audio.length===2||!1},B.hasVideo&&(B.videoStart=I.video[0].ptsTime),B.hasAudio&&(B.audioStart=I.audio[0].ptsTime)),this.self.postMessage({action:"probeTs",result:B,data:w},[w.buffer])}clearAllMp4Captions(){this.captionParser&&this.captionParser.clearAllCaptions()}clearParsedMp4Captions(){this.captionParser&&this.captionParser.clearParsedCaptions()}push(w){const k=new Uint8Array(w.data,w.byteOffset,w.byteLength);this.transmuxer.push(k)}reset(){this.transmuxer.reset()}setTimestampOffset(w){const k=w.timestampOffset||0;this.transmuxer.setBaseMediaDecodeTime(Math.round(Lt.secondsToVideoTs(k)))}setAudioAppendStart(w){this.transmuxer.setAudioAppendStart(Math.ceil(Lt.secondsToVideoTs(w.appendStart)))}setRemux(w){this.transmuxer.setRemux(w.remux)}flush(w){this.transmuxer.flush(),self.postMessage({action:"done",type:"transmuxed"})}endTimeline(){this.transmuxer.endTimeline(),self.postMessage({action:"endedtimeline",type:"transmuxed"})}alignGopsWith(w){this.transmuxer.alignGopsWith(w.gopsToAlignWith.slice())}}self.onmessage=function(x){if(x.data.action==="init"&&x.data.options){this.messageHandlers=new hd(self,x.data.options);return}this.messageHandlers||(this.messageHandlers=new hd(self)),x.data&&x.data.action&&x.data.action!=="init"&&this.messageHandlers[x.data.action]&&this.messageHandlers[x.data.action](x.data)}}));var ZB=qk(QB);const JB=(s,e,t)=>{const{type:i,initSegment:n,captions:r,captionStreams:o,metadata:u,videoFrameDtsTime:c,videoFramePtsTime:d}=s.data.segment;e.buffer.push({captions:r,captionStreams:o,metadata:u});const f=s.data.segment.boxes||{data:s.data.segment.data},p={type:i,data:new Uint8Array(f.data,f.data.byteOffset,f.data.byteLength),initSegment:new Uint8Array(n.data,n.byteOffset,n.byteLength)};typeof c<"u"&&(p.videoFrameDtsTime=c),typeof d<"u"&&(p.videoFramePtsTime=d),t(p)},eF=({transmuxedData:s,callback:e})=>{s.buffer=[],e(s)},tF=(s,e)=>{e.gopInfo=s.data.gopInfo},Wk=s=>{const{transmuxer:e,bytes:t,audioAppendStart:i,gopsToAlignWith:n,remux:r,onData:o,onTrackInfo:u,onAudioTimingInfo:c,onVideoTimingInfo:d,onVideoSegmentTimingInfo:f,onAudioSegmentTimingInfo:p,onId3:g,onCaptions:v,onDone:b,onEndedTimeline:_,onTransmuxerLog:S,isEndOfTimeline:D,segment:R,triggerSegmentEventFn:L}=s,P={buffer:[]};let U=D;const V=G=>{e.currentTransmux===s&&(G.data.action==="data"&&JB(G,P,o),G.data.action==="trackinfo"&&u(G.data.trackInfo),G.data.action==="gopInfo"&&tF(G,P),G.data.action==="audioTimingInfo"&&c(G.data.audioTimingInfo),G.data.action==="videoTimingInfo"&&d(G.data.videoTimingInfo),G.data.action==="videoSegmentTimingInfo"&&f(G.data.videoSegmentTimingInfo),G.data.action==="audioSegmentTimingInfo"&&p(G.data.audioSegmentTimingInfo),G.data.action==="id3Frame"&&g([G.data.id3Frame],G.data.id3Frame.dispatchType),G.data.action==="caption"&&v(G.data.caption),G.data.action==="endedtimeline"&&(U=!1,_()),G.data.action==="log"&&S(G.data.log),G.data.type==="transmuxed"&&(U||(e.onmessage=null,eF({transmuxedData:P,callback:b}),Xk(e))))},M=()=>{const G={message:"Received an error message from the transmuxer worker",metadata:{errorType:Le.Error.StreamingFailedToTransmuxSegment,segmentInfo:Kl({segment:R})}};b(null,G)};if(e.onmessage=V,e.onerror=M,i&&e.postMessage({action:"setAudioAppendStart",appendStart:i}),Array.isArray(n)&&e.postMessage({action:"alignGopsWith",gopsToAlignWith:n}),typeof r<"u"&&e.postMessage({action:"setRemux",remux:r}),t.byteLength){const G=t instanceof ArrayBuffer?t:t.buffer,N=t instanceof ArrayBuffer?0:t.byteOffset;L({type:"segmenttransmuxingstart",segment:R}),e.postMessage({action:"push",data:G,byteOffset:N,byteLength:t.byteLength},[G])}D&&e.postMessage({action:"endTimeline"}),e.postMessage({action:"flush"})},Xk=s=>{s.currentTransmux=null,s.transmuxQueue.length&&(s.currentTransmux=s.transmuxQueue.shift(),typeof s.currentTransmux=="function"?s.currentTransmux():Wk(s.currentTransmux))},ZE=(s,e)=>{s.postMessage({action:e}),Xk(s)},Qk=(s,e)=>{if(!e.currentTransmux){e.currentTransmux=s,ZE(e,s);return}e.transmuxQueue.push(ZE.bind(null,e,s))},iF=s=>{Qk("reset",s)},sF=s=>{Qk("endTimeline",s)},Zk=s=>{if(!s.transmuxer.currentTransmux){s.transmuxer.currentTransmux=s,Wk(s);return}s.transmuxer.transmuxQueue.push(s)},nF=s=>{const e=new ZB;e.currentTransmux=null,e.transmuxQueue=[];const t=e.terminate;return e.terminate=()=>(e.currentTransmux=null,e.transmuxQueue.length=0,t.call(e)),e.postMessage({action:"init",options:s}),e};var Zy={reset:iF,endTimeline:sF,transmux:Zk,createTransmuxer:nF};const dc=function(s){const e=s.transmuxer,t=s.endAction||s.action,i=s.callback,n=Cs({},s,{endAction:null,transmuxer:null,callback:null}),r=o=>{o.data.action===t&&(e.removeEventListener("message",r),o.data.data&&(o.data.data=new Uint8Array(o.data.data,s.byteOffset||0,s.byteLength||o.data.data.byteLength),s.data&&(s.data=o.data.data)),i(o.data))};if(e.addEventListener("message",r),s.data){const o=s.data instanceof ArrayBuffer;n.byteOffset=o?0:s.data.byteOffset,n.byteLength=s.data.byteLength;const u=[o?s.data:s.data.buffer];e.postMessage(n,u)}else e.postMessage(n)},ma={FAILURE:2,TIMEOUT:-101,ABORTED:-102},Jk="wvtt",hx=s=>{s.forEach(e=>{e.abort()})},rF=s=>({bandwidth:s.bandwidth,bytesReceived:s.bytesReceived||0,roundTripTime:s.roundTripTime||0}),aF=s=>{const e=s.target,i={bandwidth:1/0,bytesReceived:0,roundTripTime:Date.now()-e.requestTime||0};return i.bytesReceived=s.loaded,i.bandwidth=Math.floor(i.bytesReceived/i.roundTripTime*8*1e3),i},Rb=(s,e)=>{const{requestType:t}=e,i=tu({requestType:t,request:e,error:s});return e.timedout?{status:e.status,message:"HLS request timed-out at URL: "+e.uri,code:ma.TIMEOUT,xhr:e,metadata:i}:e.aborted?{status:e.status,message:"HLS request aborted at URL: "+e.uri,code:ma.ABORTED,xhr:e,metadata:i}:s?{status:e.status,message:"HLS request errored at URL: "+e.uri,code:ma.FAILURE,xhr:e,metadata:i}:e.responseType==="arraybuffer"&&e.response.byteLength===0?{status:e.status,message:"Empty HLS response at URL: "+e.uri,code:ma.FAILURE,xhr:e,metadata:i}:null},JE=(s,e,t,i)=>(n,r)=>{const o=r.response,u=Rb(n,r);if(u)return t(u,s);if(o.byteLength!==16)return t({status:r.status,message:"Invalid HLS key at URL: "+r.uri,code:ma.FAILURE,xhr:r},s);const c=new DataView(o),d=new Uint32Array([c.getUint32(0),c.getUint32(4),c.getUint32(8),c.getUint32(12)]);for(let p=0;p{e===Jk&&s.transmuxer.postMessage({action:"initMp4WebVttParser",data:s.map.bytes})},lF=(s,e,t)=>{e===Jk&&dc({action:"getMp4WebVttText",data:s.bytes,transmuxer:s.transmuxer,callback:({data:i,mp4VttCues:n})=>{s.bytes=i,t(null,s,{mp4VttCues:n})}})},eD=(s,e)=>{const t=eb(s.map.bytes);if(t!=="mp4"){const i=s.map.resolvedUri||s.map.uri,n=t||"unknown";return e({internal:!0,message:`Found unsupported ${n} container for initialization segment at URL: ${i}`,code:ma.FAILURE,metadata:{mediaType:n}})}dc({action:"probeMp4Tracks",data:s.map.bytes,transmuxer:s.transmuxer,callback:({tracks:i,data:n})=>(s.map.bytes=n,i.forEach(function(r){s.map.tracks=s.map.tracks||{},!s.map.tracks[r.type]&&(s.map.tracks[r.type]=r,typeof r.id=="number"&&r.timescale&&(s.map.timescales=s.map.timescales||{},s.map.timescales[r.id]=r.timescale),r.type==="text"&&oF(s,r.codec))}),e(null))})},uF=({segment:s,finishProcessingFn:e,triggerSegmentEventFn:t})=>(i,n)=>{const r=Rb(i,n);if(r)return e(r,s);const o=new Uint8Array(n.response);if(t({type:"segmentloaded",segment:s}),s.map.key)return s.map.encryptedBytes=o,e(null,s);s.map.bytes=o,eD(s,function(u){if(u)return u.xhr=n,u.status=n.status,e(u,s);e(null,s)})},cF=({segment:s,finishProcessingFn:e,responseType:t,triggerSegmentEventFn:i})=>(n,r)=>{const o=Rb(n,r);if(o)return e(o,s);i({type:"segmentloaded",segment:s});const u=t==="arraybuffer"||!r.responseText?r.response:WB(r.responseText.substring(s.lastReachedChar||0));return s.stats=rF(r),s.key?s.encryptedBytes=new Uint8Array(u):s.bytes=new Uint8Array(u),e(null,s)},dF=({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:g,triggerSegmentEventFn:v})=>{const b=s.map&&s.map.tracks||{},_=!!(b.audio&&b.video);let S=i.bind(null,s,"audio","start");const D=i.bind(null,s,"audio","end");let R=i.bind(null,s,"video","start");const L=i.bind(null,s,"video","end"),P=()=>Zk({bytes:e,transmuxer:s.transmuxer,audioAppendStart:s.audioAppendStart,gopsToAlignWith:s.gopsToAlignWith,remux:_,onData:U=>{U.type=U.type==="combined"?"video":U.type,f(s,U)},onTrackInfo:U=>{t&&(_&&(U.isMuxed=!0),t(s,U))},onAudioTimingInfo:U=>{S&&typeof U.start<"u"&&(S(U.start),S=null),D&&typeof U.end<"u"&&D(U.end)},onVideoTimingInfo:U=>{R&&typeof U.start<"u"&&(R(U.start),R=null),L&&typeof U.end<"u"&&L(U.end)},onVideoSegmentTimingInfo:U=>{const V={pts:{start:U.start.presentation,end:U.end.presentation},dts:{start:U.start.decode,end:U.end.decode}};v({type:"segmenttransmuxingtiminginfoavailable",segment:s,timingInfo:V}),n(U)},onAudioSegmentTimingInfo:U=>{const V={pts:{start:U.start.pts,end:U.end.pts},dts:{start:U.start.dts,end:U.end.dts}};v({type:"segmenttransmuxingtiminginfoavailable",segment:s,timingInfo:V}),r(U)},onId3:(U,V)=>{o(s,U,V)},onCaptions:U=>{u(s,[U])},isEndOfTimeline:c,onEndedTimeline:()=>{d()},onTransmuxerLog:g,onDone:(U,V)=>{p&&(U.type=U.type==="combined"?"video":U.type,v({type:"segmenttransmuxingcomplete",segment:s}),p(V,s,U))},segment:s,triggerSegmentEventFn:v});dc({action:"probeTs",transmuxer:s.transmuxer,data:e,baseStartTime:s.baseStartTime,callback:U=>{s.bytes=e=U.data;const V=U.result;V&&(t(s,{hasAudio:V.hasAudio,hasVideo:V.hasVideo,isMuxed:_}),t=null),P()}})},tD=({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:g,triggerSegmentEventFn:v})=>{let b=new Uint8Array(e);if(I3(b)){s.isFmp4=!0;const{tracks:_}=s.map;if(_.text&&(!_.audio||!_.video)){f(s,{data:b,type:"text"}),lF(s,_.text.codec,p);return}const D={isFmp4:!0,hasVideo:!!_.video,hasAudio:!!_.audio};_.audio&&_.audio.codec&&_.audio.codec!=="enca"&&(D.audioCodec=_.audio.codec),_.video&&_.video.codec&&_.video.codec!=="encv"&&(D.videoCodec=_.video.codec),_.video&&_.audio&&(D.isMuxed=!0),t(s,D);const R=(L,P)=>{f(s,{data:b,type:D.hasAudio&&!D.isMuxed?"audio":"video"}),P&&P.length&&o(s,P),L&&L.length&&u(s,L),p(null,s,{})};dc({action:"probeMp4StartTime",timescales:s.map.timescales,data:b,transmuxer:s.transmuxer,callback:({data:L,startTime:P})=>{e=L.buffer,s.bytes=b=L,D.hasAudio&&!D.isMuxed&&i(s,"audio","start",P),D.hasVideo&&i(s,"video","start",P),dc({action:"probeEmsgID3",data:b,transmuxer:s.transmuxer,offset:P,callback:({emsgData:U,id3Frames:V})=>{if(e=U.buffer,s.bytes=b=U,!_.video||!U.byteLength||!s.transmuxer){R(void 0,V);return}dc({action:"pushMp4Captions",endAction:"mp4Captions",transmuxer:s.transmuxer,data:b,timescales:s.map.timescales,trackIds:[_.video.id],callback:M=>{e=M.data.buffer,s.bytes=b=M.data,M.logs.forEach(function(G){g(Oi(G,{stream:"mp4CaptionParser"}))}),R(M.captions,V)}})}})}});return}if(!s.transmuxer){p(null,s,{});return}if(typeof s.container>"u"&&(s.container=eb(b)),s.container!=="ts"&&s.container!=="aac"){t(s,{hasAudio:!1,hasVideo:!1}),p(null,s,{});return}dF({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:g,triggerSegmentEventFn:v})},iD=function({id:s,key:e,encryptedBytes:t,decryptionWorker:i,segment:n,doneFn:r},o){const u=d=>{if(d.data.source===s){i.removeEventListener("message",u);const f=d.data.decrypted;o(new Uint8Array(f.bytes,f.byteOffset,f.byteLength))}};i.onerror=()=>{const d="An error occurred in the decryption worker",f=Kl({segment:n}),p={message:d,metadata:{error:new Error(d),errorType:Le.Error.StreamingFailedToDecryptSegment,segmentInfo:f,keyInfo:{uri:n.key.resolvedUri||n.map.key.resolvedUri}}};r(p,n)},i.addEventListener("message",u);let c;e.bytes.slice?c=e.bytes.slice():c=new Uint32Array(Array.prototype.slice.call(e.bytes)),i.postMessage(jk({source:s,encrypted:t,key:c,iv:e.iv}),[t.buffer,c.buffer])},hF=({decryptionWorker:s,segment:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:g,triggerSegmentEventFn:v})=>{v({type:"segmentdecryptionstart"}),iD({id:e.requestId,key:e.key,encryptedBytes:e.encryptedBytes,decryptionWorker:s,segment:e,doneFn:p},b=>{e.bytes=b,v({type:"segmentdecryptioncomplete",segment:e}),tD({segment:e,bytes:e.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:g,triggerSegmentEventFn:v})})},fF=({activeXhrs:s,decryptionWorker:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:g,triggerSegmentEventFn:v})=>{let b=0,_=!1;return(S,D)=>{if(!_){if(S)return _=!0,hx(s),p(S,D);if(b+=1,b===s.length){const R=function(){if(D.encryptedBytes)return hF({decryptionWorker:e,segment:D,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:g,triggerSegmentEventFn:v});tD({segment:D,bytes:D.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:g,triggerSegmentEventFn:v})};if(D.endOfAllRequests=Date.now(),D.map&&D.map.encryptedBytes&&!D.map.bytes)return v({type:"segmentdecryptionstart",segment:D}),iD({decryptionWorker:e,id:D.requestId+"-init",encryptedBytes:D.map.encryptedBytes,key:D.map.key,segment:D,doneFn:p},L=>{D.map.bytes=L,v({type:"segmentdecryptioncomplete",segment:D}),eD(D,P=>{if(P)return hx(s),p(P,D);R()})});R()}}}},mF=({loadendState:s,abortFn:e})=>t=>{t.target.aborted&&e&&!s.calledAbortFn&&(e(),s.calledAbortFn=!0)},pF=({segment:s,progressFn:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f})=>p=>{if(!p.target.aborted)return s.stats=Oi(s.stats,aF(p)),!s.stats.firstBytesReceivedAt&&s.stats.bytesReceived&&(s.stats.firstBytesReceivedAt=Date.now()),e(p,s)},gF=({xhr:s,xhrOptions:e,decryptionWorker:t,segment:i,abortFn:n,progressFn:r,trackInfoFn:o,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:p,isEndOfTimeline:g,endedTimelineFn:v,dataFn:b,doneFn:_,onTransmuxerLog:S,triggerSegmentEventFn:D})=>{const R=[],L=fF({activeXhrs:R,decryptionWorker:t,trackInfoFn:o,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:p,isEndOfTimeline:g,endedTimelineFn:v,dataFn:b,doneFn:_,onTransmuxerLog:S,triggerSegmentEventFn:D});if(i.key&&!i.key.bytes){const G=[i.key];i.map&&!i.map.bytes&&i.map.key&&i.map.key.resolvedUri===i.key.resolvedUri&&G.push(i.map.key);const N=Oi(e,{uri:i.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),O=JE(i,G,L,D),K={uri:i.key.resolvedUri};D({type:"segmentkeyloadstart",segment:i,keyInfo:K});const Q=s(N,O);R.push(Q)}if(i.map&&!i.map.bytes){if(i.map.key&&(!i.key||i.key.resolvedUri!==i.map.key.resolvedUri)){const Q=Oi(e,{uri:i.map.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),W=JE(i,[i.map.key],L,D),re={uri:i.map.key.resolvedUri};D({type:"segmentkeyloadstart",segment:i,keyInfo:re});const J=s(Q,W);R.push(J)}const N=Oi(e,{uri:i.map.resolvedUri,responseType:"arraybuffer",headers:cx(i.map),requestType:"segment-media-initialization"}),O=uF({segment:i,finishProcessingFn:L,triggerSegmentEventFn:D});D({type:"segmentloadstart",segment:i});const K=s(N,O);R.push(K)}const P=Oi(e,{uri:i.part&&i.part.resolvedUri||i.resolvedUri,responseType:"arraybuffer",headers:cx(i),requestType:"segment"}),U=cF({segment:i,finishProcessingFn:L,responseType:P.responseType,triggerSegmentEventFn:D});D({type:"segmentloadstart",segment:i});const V=s(P,U);V.addEventListener("progress",pF({segment:i,progressFn:r,trackInfoFn:o,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:p,isEndOfTimeline:g,endedTimelineFn:v,dataFn:b})),R.push(V);const M={};return R.forEach(G=>{G.addEventListener("loadend",mF({loadendState:M,abortFn:n}))}),()=>hx(R)},pm=Er("PlaylistSelector"),e2=function(s){if(!s||!s.playlist)return;const e=s.playlist;return JSON.stringify({id:e.id,bandwidth:s.bandwidth,width:s.width,height:s.height,codecs:e.attributes&&e.attributes.CODECS||""})},hc=function(s,e){if(!s)return"";const t=de.getComputedStyle(s);return t?t[e]:""},fc=function(s,e){const t=s.slice();s.sort(function(i,n){const r=e(i,n);return r===0?t.indexOf(i)-t.indexOf(n):r})},Ib=function(s,e){let t,i;return s.attributes.BANDWIDTH&&(t=s.attributes.BANDWIDTH),t=t||de.Number.MAX_VALUE,e.attributes.BANDWIDTH&&(i=e.attributes.BANDWIDTH),i=i||de.Number.MAX_VALUE,t-i},yF=function(s,e){let t,i;return s.attributes.RESOLUTION&&s.attributes.RESOLUTION.width&&(t=s.attributes.RESOLUTION.width),t=t||de.Number.MAX_VALUE,e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width&&(i=e.attributes.RESOLUTION.width),i=i||de.Number.MAX_VALUE,t===i&&s.attributes.BANDWIDTH&&e.attributes.BANDWIDTH?s.attributes.BANDWIDTH-e.attributes.BANDWIDTH:t-i};let sD=function(s){const{main:e,bandwidth:t,playerWidth:i,playerHeight:n,playerObjectFit:r,limitRenditionByPlayerDimensions:o,playlistController:u}=s;if(!e)return;const c={bandwidth:t,width:i,height:n,limitRenditionByPlayerDimensions:o};let d=e.playlists;Hn.isAudioOnly(e)&&(d=u.getAudioTrackPlaylists_(),c.audioOnly=!0);let f=d.map(M=>{let G;const N=M.attributes&&M.attributes.RESOLUTION&&M.attributes.RESOLUTION.width,O=M.attributes&&M.attributes.RESOLUTION&&M.attributes.RESOLUTION.height;return G=M.attributes&&M.attributes.BANDWIDTH,G=G||de.Number.MAX_VALUE,{bandwidth:G,width:N,height:O,playlist:M}});fc(f,(M,G)=>M.bandwidth-G.bandwidth),f=f.filter(M=>!Hn.isIncompatible(M.playlist));let p=f.filter(M=>Hn.isEnabled(M.playlist));p.length||(p=f.filter(M=>!Hn.isDisabled(M.playlist)));const g=p.filter(M=>M.bandwidth*Xs.BANDWIDTH_VARIANCEM.bandwidth===v.bandwidth)[0];if(o===!1){const M=b||p[0]||f[0];if(M&&M.playlist){let G="sortedPlaylistReps";return b&&(G="bandwidthBestRep"),p[0]&&(G="enabledPlaylistReps"),pm(`choosing ${e2(M)} using ${G} with options`,c),M.playlist}return pm("could not choose a playlist with options",c),null}const _=g.filter(M=>M.width&&M.height);fc(_,(M,G)=>M.width-G.width);const S=_.filter(M=>M.width===i&&M.height===n);v=S[S.length-1];const D=S.filter(M=>M.bandwidth===v.bandwidth)[0];let R,L,P;D||(R=_.filter(M=>r==="cover"?M.width>i&&M.height>n:M.width>i||M.height>n),L=R.filter(M=>M.width===R[0].width&&M.height===R[0].height),v=L[L.length-1],P=L.filter(M=>M.bandwidth===v.bandwidth)[0]);let U;if(u.leastPixelDiffSelector){const M=_.map(G=>(G.pixelDiff=Math.abs(G.width-i)+Math.abs(G.height-n),G));fc(M,(G,N)=>G.pixelDiff===N.pixelDiff?N.bandwidth-G.bandwidth:G.pixelDiff-N.pixelDiff),U=M[0]}const V=U||P||D||b||p[0]||f[0];if(V&&V.playlist){let M="sortedPlaylistReps";return U?M="leastPixelDiffRep":P?M="resolutionPlusOneRep":D?M="resolutionBestRep":b?M="bandwidthBestRep":p[0]&&(M="enabledPlaylistReps"),pm(`choosing ${e2(V)} using ${M} with options`,c),V.playlist}return pm("could not choose a playlist with options",c),null};const t2=function(){let s=this.useDevicePixelRatio&&de.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(s=this.customPixelRatio),sD({main:this.playlists.main,bandwidth:this.systemBandwidth,playerWidth:parseInt(hc(this.tech_.el(),"width"),10)*s,playerHeight:parseInt(hc(this.tech_.el(),"height"),10)*s,playerObjectFit:this.usePlayerObjectFit?hc(this.tech_.el(),"objectFit"):"",limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})},vF=function(s){let e=-1,t=-1;if(s<0||s>1)throw new Error("Moving average bandwidth decay must be between 0 and 1.");return function(){let i=this.useDevicePixelRatio&&de.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(i=this.customPixelRatio),e<0&&(e=this.systemBandwidth,t=this.systemBandwidth),this.systemBandwidth>0&&this.systemBandwidth!==t&&(e=s*this.systemBandwidth+(1-s)*e,t=this.systemBandwidth),sD({main:this.playlists.main,bandwidth:e,playerWidth:parseInt(hc(this.tech_.el(),"width"),10)*i,playerHeight:parseInt(hc(this.tech_.el(),"height"),10)*i,playerObjectFit:this.usePlayerObjectFit?hc(this.tech_.el(),"objectFit"):"",limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})}},xF=function(s){const{main:e,currentTime:t,bandwidth:i,duration:n,segmentDuration:r,timeUntilRebuffer:o,currentTimeline:u,syncController:c}=s,d=e.playlists.filter(b=>!Hn.isIncompatible(b));let f=d.filter(Hn.isEnabled);f.length||(f=d.filter(b=>!Hn.isDisabled(b)));const g=f.filter(Hn.hasAttribute.bind(null,"BANDWIDTH")).map(b=>{const S=c.getSyncPoint(b,n,u,t)?1:2,R=Hn.estimateSegmentRequestTime(r,i,b)*S-o;return{playlist:b,rebufferingImpact:R}}),v=g.filter(b=>b.rebufferingImpact<=0);return fc(v,(b,_)=>Ib(_.playlist,b.playlist)),v.length?v[0]:(fc(g,(b,_)=>b.rebufferingImpact-_.rebufferingImpact),g[0]||null)},bF=function(){const s=this.playlists.main.playlists.filter(Hn.isEnabled);return fc(s,(t,i)=>Ib(t,i)),s.filter(t=>!!fh(this.playlists.main,t).video)[0]||null},TF=s=>{let e=0,t;return s.bytes&&(t=new Uint8Array(s.bytes),s.segments.forEach(i=>{t.set(i,e),e+=i.byteLength})),t};function nD(s){try{return new URL(s).pathname.split("/").slice(-2).join("/")}catch{return""}}const _F=function(s,e,t){if(!s[t]){e.trigger({type:"usage",name:"vhs-608"});let i=t;/^cc708_/.test(t)&&(i="SERVICE"+t.split("_")[1]);const n=e.textTracks().getTrackById(i);if(n)s[t]=n;else{const r=e.options_.vhs&&e.options_.vhs.captionServices||{};let o=t,u=t,c=!1;const d=r[i];d&&(o=d.label,u=d.language,c=d.default),s[t]=e.addRemoteTextTrack({kind:"captions",id:i,default:c,label:o,language:u},!1).track}}},SF=function({inbandTextTracks:s,captionArray:e,timestampOffset:t}){if(!e)return;const i=de.WebKitDataCue||de.VTTCue;e.forEach(n=>{const r=n.stream;n.content?n.content.forEach(o=>{const u=new i(n.startTime+t,n.endTime+t,o.text);u.line=o.line,u.align="left",u.position=o.position,u.positionAlign="line-left",s[r].addCue(u)}):s[r].addCue(new i(n.startTime+t,n.endTime+t,n.text))})},EF=function(s){Object.defineProperties(s.frame,{id:{get(){return Le.log.warn("cue.frame.id is deprecated. Use cue.value.key instead."),s.value.key}},value:{get(){return Le.log.warn("cue.frame.value is deprecated. Use cue.value.data instead."),s.value.data}},privateData:{get(){return Le.log.warn("cue.frame.privateData is deprecated. Use cue.value.data instead."),s.value.data}}})},wF=({inbandTextTracks:s,metadataArray:e,timestampOffset:t,videoDuration:i})=>{if(!e)return;const n=de.WebKitDataCue||de.VTTCue,r=s.metadataTrack_;if(!r||(e.forEach(f=>{const p=f.cueTime+t;typeof p!="number"||de.isNaN(p)||p<0||!(p<1/0)||!f.frames||!f.frames.length||f.frames.forEach(g=>{const v=new n(p,p,g.value||g.url||g.data||"");v.frame=g,v.value=g,EF(v),r.addCue(v)})}),!r.cues||!r.cues.length))return;const o=r.cues,u=[];for(let f=0;f{const g=f[p.startTime]||[];return g.push(p),f[p.startTime]=g,f},{}),d=Object.keys(c).sort((f,p)=>Number(f)-Number(p));d.forEach((f,p)=>{const g=c[f],v=isFinite(i)?i:f,b=Number(d[p+1])||v;g.forEach(_=>{_.endTime=b})})},AF={id:"ID",class:"CLASS",startDate:"START-DATE",duration:"DURATION",endDate:"END-DATE",endOnNext:"END-ON-NEXT",plannedDuration:"PLANNED-DURATION",scte35Out:"SCTE35-OUT",scte35In:"SCTE35-IN"},CF=new Set(["id","class","startDate","duration","endDate","endOnNext","startTime","endTime","processDateRange"]),kF=({inbandTextTracks:s,dateRanges:e})=>{const t=s.metadataTrack_;if(!t)return;const i=de.WebKitDataCue||de.VTTCue;e.forEach(n=>{for(const r of Object.keys(n)){if(CF.has(r))continue;const o=new i(n.startTime,n.endTime,"");o.id=n.id,o.type="com.apple.quicktime.HLS",o.value={key:AF[r],data:n[r]},(r==="scte35Out"||r==="scte35In")&&(o.value.data=new Uint8Array(o.value.data.match(/[\da-f]{2}/gi)).buffer),t.addCue(o)}n.processDateRange()})},i2=(s,e,t)=>{s.metadataTrack_||(s.metadataTrack_=t.addRemoteTextTrack({kind:"metadata",label:"Timed Metadata"},!1).track,Le.browser.IS_ANY_SAFARI||(s.metadataTrack_.inBandMetadataTrackDispatchType=e))},ih=function(s,e,t){let i,n;if(t&&t.cues)for(i=t.cues.length;i--;)n=t.cues[i],n.startTime>=s&&n.endTime<=e&&t.removeCue(n)},DF=function(s){const e=s.cues;if(!e)return;const t={};for(let i=e.length-1;i>=0;i--){const n=e[i],r=`${n.startTime}-${n.endTime}-${n.text}`;t[r]?s.removeCue(n):t[r]=n}},LF=(s,e,t)=>{if(typeof e>"u"||e===null||!s.length)return[];const i=Math.ceil((e-t+3)*Wl.ONE_SECOND_IN_TS);let n;for(n=0;ni);n++);return s.slice(n)},RF=(s,e,t)=>{if(!e.length)return s;if(t)return e.slice();const i=e[0].pts;let n=0;for(n;n=i);n++);return s.slice(0,n).concat(e)},IF=(s,e,t,i)=>{const n=Math.ceil((e-i)*Wl.ONE_SECOND_IN_TS),r=Math.ceil((t-i)*Wl.ONE_SECOND_IN_TS),o=s.slice();let u=s.length;for(;u--&&!(s[u].pts<=r););if(u===-1)return o;let c=u+1;for(;c--&&!(s[c].pts<=n););return c=Math.max(c,0),o.splice(c,u-c+1),o},NF=function(s,e){if(!s&&!e||!s&&e||s&&!e)return!1;if(s===e)return!0;const t=Object.keys(s).sort(),i=Object.keys(e).sort();if(t.length!==i.length)return!1;for(let n=0;nt))return r}return i.length===0?0:i[i.length-1]},Kd=1,MF=500,s2=s=>typeof s=="number"&&isFinite(s),gm=1/60,PF=(s,e,t)=>s!=="main"||!e||!t?null:!t.hasAudio&&!t.hasVideo?"Neither audio nor video found in segment.":e.hasVideo&&!t.hasVideo?"Only audio found in segment when we expected video. We can't switch to audio only from a stream that had video. To get rid of this message, please add codec information to the manifest.":!e.hasVideo&&t.hasVideo?"Video found in segment when we expected only audio. We can't switch to a stream with video from an audio only stream. To get rid of this message, please add codec information to the manifest.":null,BF=(s,e,t)=>{let i=e-Xs.BACK_BUFFER_LENGTH;s.length&&(i=Math.max(i,s.start(0)));const n=e-t;return Math.min(n,i)},zu=s=>{const{startOfSegment:e,duration:t,segment:i,part:n,playlist:{mediaSequence:r,id:o,segments:u=[]},mediaIndex:c,partIndex:d,timeline:f}=s,p=u.length-1;let g="mediaIndex/partIndex increment";s.getMediaInfoForTime?g=`getMediaInfoForTime (${s.getMediaInfoForTime})`:s.isSyncRequest&&(g="getSyncSegmentCandidate (isSyncRequest)"),s.independent&&(g+=` with independent ${s.independent}`);const v=typeof d=="number",b=s.segment.uri?"segment":"pre-segment",_=v?_k({preloadSegment:i})-1:0;return`${b} [${r+c}/${r+p}]`+(v?` part [${d}/${_}]`:"")+` segment start/end [${i.start} => ${i.end}]`+(v?` part start/end [${n.start} => ${n.end}]`:"")+` startOfSegment [${e}] duration [${t}] timeline [${f}] selected by [${g}] playlist [${o}]`},n2=s=>`${s}TimingInfo`,FF=({segmentTimeline:s,currentTimeline:e,startOfSegment:t,buffered:i,overrideCheck:n})=>!n&&s===e?null:s{if(e===t)return!1;if(i==="audio"){const r=s.lastTimelineChange({type:"main"});return!r||r.to!==t}if(i==="main"&&n){const r=s.pendingTimelineChange({type:"audio"});return!(r&&r.to===t)}return!1},UF=s=>{if(!s)return!1;const e=s.pendingTimelineChange({type:"audio"}),t=s.pendingTimelineChange({type:"main"}),i=e&&t,n=i&&e.to!==t.to;return!!(i&&e.from!==-1&&t.from!==-1&&n)},jF=s=>{const e=s.timelineChangeController_.pendingTimelineChange({type:"audio"}),t=s.timelineChangeController_.pendingTimelineChange({type:"main"});return e&&t&&e.to{const e=s.pendingSegment_;if(!e)return;if(fx({timelineChangeController:s.timelineChangeController_,currentTimeline:s.currentTimeline_,segmentTimeline:e.timeline,loaderType:s.loaderType_,audioDisabled:s.audioDisabled_})&&UF(s.timelineChangeController_)){if(jF(s)){s.timelineChangeController_.trigger("audioTimelineBehind");return}s.timelineChangeController_.trigger("fixBadTimelineChange")}},$F=s=>{let e=0;return["video","audio"].forEach(function(t){const i=s[`${t}TimingInfo`];if(!i)return;const{start:n,end:r}=i;let o;typeof n=="bigint"||typeof r=="bigint"?o=de.BigInt(r)-de.BigInt(n):typeof n=="number"&&typeof r=="number"&&(o=r-n),typeof o<"u"&&o>e&&(e=o)}),typeof e=="bigint"&&es?Math.round(s)>e+ha:!1,HF=(s,e)=>{if(e!=="hls")return null;const t=$F({audioTimingInfo:s.audioTimingInfo,videoTimingInfo:s.videoTimingInfo});if(!t)return null;const i=s.playlist.targetDuration,n=r2({segmentDuration:t,maxDuration:i*2}),r=r2({segmentDuration:t,maxDuration:i}),o=`Segment with index ${s.mediaIndex} from playlist ${s.playlist.id} has a duration of ${t} when the reported duration is ${s.duration} and the target duration is ${i}. For HLS content, a duration in excess of the target duration may result in playback issues. See the HLS specification section on EXT-X-TARGETDURATION for more details: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1`;return n||r?{severity:n?"warn":"info",message:o}:null},Kl=({type:s,segment:e})=>{if(!e)return;const t=!!(e.key||e.map&&e.map.ke),i=!!(e.map&&!e.map.bytes),n=e.startOfSegment===void 0?e.start:e.startOfSegment;return{type:s||e.type,uri:e.resolvedUri||e.uri,start:n,duration:e.duration,isEncrypted:t,isMediaInitialization:i}};class mx extends Le.EventTarget{constructor(e,t={}){if(super(),!e)throw new TypeError("Initialization settings are required");if(typeof e.currentTime!="function")throw new TypeError("No currentTime getter specified");if(!e.mediaSource)throw new TypeError("No MediaSource specified");this.bandwidth=e.bandwidth,this.throughput={rate:0,count:0},this.roundTrip=NaN,this.resetStats_(),this.mediaIndex=null,this.partIndex=null,this.hasPlayed_=e.hasPlayed,this.currentTime_=e.currentTime,this.seekable_=e.seekable,this.seeking_=e.seeking,this.duration_=e.duration,this.mediaSource_=e.mediaSource,this.vhs_=e.vhs,this.loaderType_=e.loaderType,this.currentMediaInfo_=void 0,this.startingMediaInfo_=void 0,this.segmentMetadataTrack_=e.segmentMetadataTrack,this.goalBufferLength_=e.goalBufferLength,this.sourceType_=e.sourceType,this.sourceUpdater_=e.sourceUpdater,this.inbandTextTracks_=e.inbandTextTracks,this.state_="INIT",this.timelineChangeController_=e.timelineChangeController,this.shouldSaveSegmentTimingInfo_=!0,this.parse708captions_=e.parse708captions,this.useDtsForTimestampOffset_=e.useDtsForTimestampOffset,this.captionServices_=e.captionServices,this.exactManifestTimings=e.exactManifestTimings,this.addMetadataToTextTrack=e.addMetadataToTextTrack,this.checkBufferTimeout_=null,this.error_=void 0,this.currentTimeline_=-1,this.shouldForceTimestampOffsetAfterResync_=!1,this.pendingSegment_=null,this.xhrOptions_=null,this.pendingSegments_=[],this.audioDisabled_=!1,this.isPendingTimestampOffset_=!1,this.gopBuffer_=[],this.timeMapping_=0,this.safeAppend_=!1,this.appendInitSegment_={audio:!0,video:!0},this.playlistOfLastInitSegment_={audio:null,video:null},this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_={id3:[],caption:[]},this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=null,this.activeInitSegmentId_=null,this.initSegments_={},this.cacheEncryptionKeys_=e.cacheEncryptionKeys,this.keyCache_={},this.decrypter_=e.decrypter,this.syncController_=e.syncController,this.syncPoint_={segmentIndex:0,time:0},this.transmuxer_=this.createTransmuxer_(),this.triggerSyncInfoUpdate_=()=>this.trigger("syncinfoupdate"),this.syncController_.on("syncinfoupdate",this.triggerSyncInfoUpdate_),this.mediaSource_.addEventListener("sourceopen",()=>{this.isEndOfStream_()||(this.ended_=!1)}),this.fetchAtBuffer_=!1,this.logger_=Er(`SegmentLoader[${this.loaderType_}]`),Object.defineProperty(this,"state",{get(){return this.state_},set(i){i!==this.state_&&(this.logger_(`${this.state_} -> ${i}`),this.state_=i,this.trigger("statechange"))}}),this.sourceUpdater_.on("ready",()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():qo(this)}),this.sourceUpdater_.on("codecschange",i=>{this.trigger(Cs({type:"codecschange"},i))}),this.loaderType_==="main"&&this.timelineChangeController_.on("pendingtimelinechange",()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():qo(this)}),this.loaderType_==="audio"&&this.timelineChangeController_.on("timelinechange",i=>{this.trigger(Cs({type:"timelinechange"},i)),this.hasEnoughInfoToLoad_()?this.processLoadQueue_():qo(this),this.hasEnoughInfoToAppend_()?this.processCallQueue_():qo(this)})}get mediaSequenceSync_(){return this.syncController_.getMediaSequenceSync(this.loaderType_)}createTransmuxer_(){return Zy.createTransmuxer({remux:!1,alignGopsAtEnd:this.safeAppend_,keepOriginalTimestamps:!0,parse708captions:this.parse708captions_,captionServices:this.captionServices_})}resetStats_(){this.mediaBytesTransferred=0,this.mediaRequests=0,this.mediaRequestsAborted=0,this.mediaRequestsTimedout=0,this.mediaRequestsErrored=0,this.mediaTransferDuration=0,this.mediaSecondsLoaded=0,this.mediaAppends=0}dispose(){this.trigger("dispose"),this.state="DISPOSED",this.pause(),this.abort_(),this.transmuxer_&&this.transmuxer_.terminate(),this.resetStats_(),this.checkBufferTimeout_&&de.clearTimeout(this.checkBufferTimeout_),this.syncController_&&this.triggerSyncInfoUpdate_&&this.syncController_.off("syncinfoupdate",this.triggerSyncInfoUpdate_),this.off()}setAudio(e){this.audioDisabled_=!e,e?this.appendInitSegment_.audio=!0:this.sourceUpdater_.removeAudio(0,this.duration_())}abort(){if(this.state!=="WAITING"){this.pendingSegment_&&(this.pendingSegment_=null),this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);return}this.abort_(),this.state="READY",this.paused()||this.monitorBuffer_()}abort_(){this.pendingSegment_&&this.pendingSegment_.abortRequests&&this.pendingSegment_.abortRequests(),this.pendingSegment_=null,this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_),this.waitingOnRemove_=!1,de.clearTimeout(this.quotaExceededErrorRetryTimeout_),this.quotaExceededErrorRetryTimeout_=null}checkForAbort_(e){return this.state==="APPENDING"&&!this.pendingSegment_?(this.state="READY",!0):!this.pendingSegment_||this.pendingSegment_.requestId!==e}error(e){return typeof e<"u"&&(this.logger_("error occurred:",e),this.error_=e),this.pendingSegment_=null,this.error_}endOfStream(){this.ended_=!0,this.transmuxer_&&Zy.reset(this.transmuxer_),this.gopBuffer_.length=0,this.pause(),this.trigger("ended")}buffered_(){const e=this.getMediaInfo_();if(!this.sourceUpdater_||!e)return Zs();if(this.loaderType_==="main"){const{hasAudio:t,hasVideo:i,isMuxed:n}=e;if(i&&t&&!this.audioDisabled_&&!n)return this.sourceUpdater_.buffered();if(i)return this.sourceUpdater_.videoBuffered()}return this.sourceUpdater_.audioBuffered()}initSegmentForMap(e,t=!1){if(!e)return null;const i=yp(e);let n=this.initSegments_[i];return t&&!n&&e.bytes&&(this.initSegments_[i]=n={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:e.bytes,tracks:e.tracks,timescales:e.timescales}),n||e}segmentKey(e,t=!1){if(!e)return null;const i=$k(e);let n=this.keyCache_[i];this.cacheEncryptionKeys_&&t&&!n&&e.bytes&&(this.keyCache_[i]=n={resolvedUri:e.resolvedUri,bytes:e.bytes});const r={resolvedUri:(n||e).resolvedUri};return n&&(r.bytes=n.bytes),r}couldBeginLoading_(){return this.playlist_&&!this.paused()}load(){if(this.monitorBuffer_(),!!this.playlist_){if(this.state==="INIT"&&this.couldBeginLoading_())return this.init_();!this.couldBeginLoading_()||this.state!=="READY"&&this.state!=="INIT"||(this.state="READY")}}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}playlist(e,t={}){if(!e||this.playlist_&&this.playlist_.endList&&e.endList&&this.playlist_.uri===e.uri)return;const i=this.playlist_,n=this.pendingSegment_;this.playlist_=e,this.xhrOptions_=t,this.state==="INIT"&&(e.syncInfo={mediaSequence:e.mediaSequence,time:0},this.loaderType_==="main"&&this.syncController_.setDateTimeMappingForStart(e));let r=null;if(i&&(i.id?r=i.id:i.uri&&(r=i.uri)),this.logger_(`playlist update [${r} => ${e.id||e.uri}]`),this.mediaSequenceSync_&&(this.mediaSequenceSync_.update(e,this.currentTime_()),this.logger_(`Playlist update: currentTime: ${this.currentTime_()} bufferedEnd: ${Xy(this.buffered_())} `,this.mediaSequenceSync_.diagnostics)),this.trigger("syncinfoupdate"),this.state==="INIT"&&this.couldBeginLoading_())return this.init_();if(!i||i.uri!==e.uri){this.mediaIndex!==null&&(!e.endList&&typeof e.partTargetDuration=="number"?this.resetLoader():this.resyncLoader()),this.currentMediaInfo_=void 0,this.trigger("playlistupdate");return}const o=e.mediaSequence-i.mediaSequence;if(this.logger_(`live window shift [${o}]`),this.mediaIndex!==null)if(this.mediaIndex-=o,this.mediaIndex<0)this.mediaIndex=null,this.partIndex=null;else{const u=this.playlist_.segments[this.mediaIndex];if(this.partIndex&&(!u.parts||!u.parts.length||!u.parts[this.partIndex])){const c=this.mediaIndex;this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`),this.resetLoader(),this.mediaIndex=c}}n&&(n.mediaIndex-=o,n.mediaIndex<0?(n.mediaIndex=null,n.partIndex=null):(n.mediaIndex>=0&&(n.segment=e.segments[n.mediaIndex]),n.partIndex>=0&&n.segment.parts&&(n.part=n.segment.parts[n.partIndex]))),this.syncController_.saveExpiredSegmentInfo(i,e)}pause(){this.checkBufferTimeout_&&(de.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=null)}paused(){return this.checkBufferTimeout_===null}resetEverything(e){this.ended_=!1,this.activeInitSegmentId_=null,this.appendInitSegment_={audio:!0,video:!0},this.resetLoader(),this.remove(0,1/0,e),this.transmuxer_&&(this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),this.transmuxer_.postMessage({action:"reset"}))}resetLoader(){this.fetchAtBuffer_=!1,this.mediaSequenceSync_&&this.mediaSequenceSync_.resetAppendedStatus(),this.resyncLoader()}resyncLoader(){this.transmuxer_&&Zy.reset(this.transmuxer_),this.mediaIndex=null,this.partIndex=null,this.syncPoint_=null,this.isPendingTimestampOffset_=!1;const e=this.currentMediaInfo_&&this.currentMediaInfo_.isFmp4;this.sourceType_==="hls"&&!e&&(this.shouldForceTimestampOffsetAfterResync_=!0),this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.abort(),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}remove(e,t,i=()=>{},n=!1){if(t===1/0&&(t=this.duration_()),t<=e){this.logger_("skipping remove because end ${end} is <= start ${start}");return}if(!this.sourceUpdater_||!this.getMediaInfo_()){this.logger_("skipping remove because no source updater or starting media info");return}let r=1;const o=()=>{r--,r===0&&i()};(n||!this.audioDisabled_)&&(r++,this.sourceUpdater_.removeAudio(e,t,o)),(n||this.loaderType_==="main")&&(this.gopBuffer_=IF(this.gopBuffer_,e,t,this.timeMapping_),r++,this.sourceUpdater_.removeVideo(e,t,o));for(const u in this.inbandTextTracks_)ih(e,t,this.inbandTextTracks_[u]);ih(e,t,this.segmentMetadataTrack_),o()}monitorBuffer_(){this.checkBufferTimeout_&&de.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=de.setTimeout(this.monitorBufferTick_.bind(this),1)}monitorBufferTick_(){this.state==="READY"&&this.fillBuffer_(),this.checkBufferTimeout_&&de.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=de.setTimeout(this.monitorBufferTick_.bind(this),MF)}fillBuffer_(){if(this.sourceUpdater_.updating())return;const e=this.chooseNextRequest_();if(!e)return;const t={segmentInfo:Kl({type:this.loaderType_,segment:e})};this.trigger({type:"segmentselected",metadata:t}),typeof e.timestampOffset=="number"&&(this.isPendingTimestampOffset_=!1,this.timelineChangeController_.pendingTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline})),this.loadSegment_(e)}isEndOfStream_(e=this.mediaIndex,t=this.playlist_,i=this.partIndex){if(!t||!this.mediaSource_)return!1;const n=typeof e=="number"&&t.segments[e],r=e+1===t.segments.length,o=!n||!n.parts||i+1===n.parts.length;return t.endList&&this.mediaSource_.readyState==="open"&&r&&o}chooseNextRequest_(){const e=this.buffered_(),t=Xy(e)||0,i=Cb(e,this.currentTime_()),n=!this.hasPlayed_()&&i>=1,r=i>=this.goalBufferLength_(),o=this.playlist_.segments;if(!o.length||n||r)return null;this.syncPoint_=this.syncPoint_||this.syncController_.getSyncPoint(this.playlist_,this.duration_(),this.currentTimeline_,this.currentTime_(),this.loaderType_);const u={partIndex:null,mediaIndex:null,startOfSegment:null,playlist:this.playlist_,isSyncRequest:!this.syncPoint_};if(u.isSyncRequest)u.mediaIndex=OF(this.currentTimeline_,o,t),this.logger_(`choose next request. Can not find sync point. Fallback to media Index: ${u.mediaIndex}`);else if(this.mediaIndex!==null){const g=o[this.mediaIndex],v=typeof this.partIndex=="number"?this.partIndex:-1;u.startOfSegment=g.end?g.end:t,g.parts&&g.parts[v+1]?(u.mediaIndex=this.mediaIndex,u.partIndex=v+1):u.mediaIndex=this.mediaIndex+1}else{let g,v,b;const _=this.fetchAtBuffer_?t:this.currentTime_();if(this.mediaSequenceSync_&&this.logger_(`chooseNextRequest_ request after Quality Switch: For TargetTime: ${_}. CurrentTime: ${this.currentTime_()} BufferedEnd: ${t} Fetch At Buffer: ${this.fetchAtBuffer_} `,this.mediaSequenceSync_.diagnostics),this.mediaSequenceSync_&&this.mediaSequenceSync_.isReliable){const S=this.getSyncInfoFromMediaSequenceSync_(_);if(!S){const D="No sync info found while using media sequence sync";return this.error({message:D,metadata:{errorType:Le.Error.StreamingFailedToSelectNextSegment,error:new Error(D)}}),this.logger_("chooseNextRequest_ - no sync info found using media sequence sync"),null}this.logger_(`chooseNextRequest_ mediaSequence syncInfo (${S.start} --> ${S.end})`),g=S.segmentIndex,v=S.partIndex,b=S.start}else{this.logger_("chooseNextRequest_ - fallback to a regular segment selection algorithm, based on a syncPoint.");const S=Hn.getMediaInfoForTime({exactManifestTimings:this.exactManifestTimings,playlist:this.playlist_,currentTime:_,startingPartIndex:this.syncPoint_.partIndex,startingSegmentIndex:this.syncPoint_.segmentIndex,startTime:this.syncPoint_.time});g=S.segmentIndex,v=S.partIndex,b=S.startTime}u.getMediaInfoForTime=this.fetchAtBuffer_?`bufferedEnd ${_}`:`currentTime ${_}`,u.mediaIndex=g,u.startOfSegment=b,u.partIndex=v,this.logger_(`choose next request. Playlist switched and we have a sync point. Media Index: ${u.mediaIndex} `)}const c=o[u.mediaIndex];let d=c&&typeof u.partIndex=="number"&&c.parts&&c.parts[u.partIndex];if(!c||typeof u.partIndex=="number"&&!d)return null;typeof u.partIndex!="number"&&c.parts&&(u.partIndex=0,d=c.parts[0]);const f=this.vhs_.playlists&&this.vhs_.playlists.main&&this.vhs_.playlists.main.independentSegments||this.playlist_.independentSegments;if(!i&&d&&!f&&!d.independent)if(u.partIndex===0){const g=o[u.mediaIndex-1],v=g.parts&&g.parts.length&&g.parts[g.parts.length-1];v&&v.independent&&(u.mediaIndex-=1,u.partIndex=g.parts.length-1,u.independent="previous segment")}else c.parts[u.partIndex-1].independent&&(u.partIndex-=1,u.independent="previous part");const p=this.mediaSource_&&this.mediaSource_.readyState==="ended";return u.mediaIndex>=o.length-1&&p&&!this.seeking_()?null:(this.shouldForceTimestampOffsetAfterResync_&&(this.shouldForceTimestampOffsetAfterResync_=!1,u.forceTimestampOffset=!0,this.logger_("choose next request. Force timestamp offset after loader resync")),this.generateSegmentInfo_(u))}getSyncInfoFromMediaSequenceSync_(e){if(!this.mediaSequenceSync_)return null;const t=Math.max(e,this.mediaSequenceSync_.start);e!==t&&this.logger_(`getSyncInfoFromMediaSequenceSync_. Pulled target time from ${e} to ${t}`);const i=this.mediaSequenceSync_.getSyncInfoForTime(t);if(!i)return null;if(!i.isAppended)return i;const n=this.mediaSequenceSync_.getSyncInfoForTime(i.end);return n?(n.isAppended&&this.logger_("getSyncInfoFromMediaSequenceSync_: We encounter unexpected scenario where next media sequence sync info is also appended!"),n):null}generateSegmentInfo_(e){const{independent:t,playlist:i,mediaIndex:n,startOfSegment:r,isSyncRequest:o,partIndex:u,forceTimestampOffset:c,getMediaInfoForTime:d}=e,f=i.segments[n],p=typeof u=="number"&&f.parts[u],g={requestId:"segment-loader-"+Math.random(),uri:p&&p.resolvedUri||f.resolvedUri,mediaIndex:n,partIndex:p?u:null,isSyncRequest:o,startOfSegment:r,playlist:i,bytes:null,encryptedBytes:null,timestampOffset:null,timeline:f.timeline,duration:p&&p.duration||f.duration,segment:f,part:p,byteLength:0,transmuxer:this.transmuxer_,getMediaInfoForTime:d,independent:t},v=typeof c<"u"?c:this.isPendingTimestampOffset_;g.timestampOffset=this.timestampOffsetForSegment_({segmentTimeline:f.timeline,currentTimeline:this.currentTimeline_,startOfSegment:r,buffered:this.buffered_(),overrideCheck:v});const b=Xy(this.sourceUpdater_.audioBuffered());return typeof b=="number"&&(g.audioAppendStart=b-this.sourceUpdater_.audioTimestampOffset()),this.sourceUpdater_.videoBuffered().length&&(g.gopsToAlignWith=LF(this.gopBuffer_,this.currentTime_()-this.sourceUpdater_.videoTimestampOffset(),this.timeMapping_)),g}timestampOffsetForSegment_(e){return FF(e)}earlyAbortWhenNeeded_(e){if(this.vhs_.tech_.paused()||!this.xhrOptions_.timeout||!this.playlist_.attributes.BANDWIDTH||Date.now()-(e.firstBytesReceivedAt||Date.now())<1e3)return;const t=this.currentTime_(),i=e.bandwidth,n=this.pendingSegment_.duration,r=Hn.estimateSegmentRequestTime(n,i,this.playlist_,e.bytesReceived),o=aB(this.buffered_(),t,this.vhs_.tech_.playbackRate())-1;if(r<=o)return;const u=xF({main:this.vhs_.playlists.main,currentTime:t,bandwidth:i,duration:this.duration_(),segmentDuration:n,timeUntilRebuffer:o,currentTimeline:this.currentTimeline_,syncController:this.syncController_});if(!u)return;const d=r-o-u.rebufferingImpact;let f=.5;o<=ha&&(f=1),!(!u.playlist||u.playlist.uri===this.playlist_.uri||d{r[o.stream]=r[o.stream]||{startTime:1/0,captions:[],endTime:0};const u=r[o.stream];u.startTime=Math.min(u.startTime,o.startTime+n),u.endTime=Math.max(u.endTime,o.endTime+n),u.captions.push(o)}),Object.keys(r).forEach(o=>{const{startTime:u,endTime:c,captions:d}=r[o],f=this.inbandTextTracks_;this.logger_(`adding cues from ${u} -> ${c} for ${o}`),_F(f,this.vhs_.tech_,o),ih(u,c,f[o]),SF({captionArray:d,inbandTextTracks:f,timestampOffset:n})}),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}handleId3_(e,t,i){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(!this.pendingSegment_.hasAppendedData_){this.metadataQueue_.id3.push(this.handleId3_.bind(this,e,t,i));return}this.addMetadataToTextTrack(i,t,this.duration_())}processMetadataQueue_(){this.metadataQueue_.id3.forEach(e=>e()),this.metadataQueue_.caption.forEach(e=>e()),this.metadataQueue_.id3=[],this.metadataQueue_.caption=[]}processCallQueue_(){const e=this.callQueue_;this.callQueue_=[],e.forEach(t=>t())}processLoadQueue_(){const e=this.loadQueue_;this.loadQueue_=[],e.forEach(t=>t())}hasEnoughInfoToLoad_(){if(this.loaderType_!=="audio")return!0;const e=this.pendingSegment_;return e?this.getCurrentMediaInfo_()?!fx({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:e.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}):!0:!1}getCurrentMediaInfo_(e=this.pendingSegment_){return e&&e.trackInfo||this.currentMediaInfo_}getMediaInfo_(e=this.pendingSegment_){return this.getCurrentMediaInfo_(e)||this.startingMediaInfo_}getPendingSegmentPlaylist(){return this.pendingSegment_?this.pendingSegment_.playlist:null}hasEnoughInfoToAppend_(){if(!this.sourceUpdater_.ready()||this.waitingOnRemove_||this.quotaExceededErrorRetryTimeout_)return!1;const e=this.pendingSegment_,t=this.getCurrentMediaInfo_();if(!e||!t)return!1;const{hasAudio:i,hasVideo:n,isMuxed:r}=t;return!(n&&!e.videoTimingInfo||i&&!this.audioDisabled_&&!r&&!e.audioTimingInfo||fx({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:e.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}))}handleData_(e,t){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(this.callQueue_.length||!this.hasEnoughInfoToAppend_()){qo(this),this.callQueue_.push(this.handleData_.bind(this,e,t));return}const i=this.pendingSegment_;if(this.setTimeMapping_(i.timeline),this.updateMediaSecondsLoaded_(i.part||i.segment),this.mediaSource_.readyState!=="closed"){if(e.map&&(e.map=this.initSegmentForMap(e.map,!0),i.segment.map=e.map),e.key&&this.segmentKey(e.key,!0),i.isFmp4=e.isFmp4,i.timingInfo=i.timingInfo||{},i.isFmp4)this.trigger("fmp4"),i.timingInfo.start=i[n2(t.type)].start;else{const n=this.getCurrentMediaInfo_(),r=this.loaderType_==="main"&&n&&n.hasVideo;let o;r&&(o=i.videoTimingInfo.start),i.timingInfo.start=this.trueSegmentStart_({currentStart:i.timingInfo.start,playlist:i.playlist,mediaIndex:i.mediaIndex,currentVideoTimestampOffset:this.sourceUpdater_.videoTimestampOffset(),useVideoTimingInfo:r,firstVideoFrameTimeForData:o,videoTimingInfo:i.videoTimingInfo,audioTimingInfo:i.audioTimingInfo})}if(this.updateAppendInitSegmentStatus(i,t.type),this.updateSourceBufferTimestampOffset_(i),i.isSyncRequest){this.updateTimingInfoEnd_(i),this.syncController_.saveSegmentTimingInfo({segmentInfo:i,shouldSaveTimelineMapping:this.loaderType_==="main"});const n=this.chooseNextRequest_();if(n.mediaIndex!==i.mediaIndex||n.partIndex!==i.partIndex){this.logger_("sync segment was incorrect, not appending");return}this.logger_("sync segment was correct, appending")}i.hasAppendedData_=!0,this.processMetadataQueue_(),this.appendData_(i,t)}}updateAppendInitSegmentStatus(e,t){this.loaderType_==="main"&&typeof e.timestampOffset=="number"&&!e.changedTimestampOffset&&(this.appendInitSegment_={audio:!0,video:!0}),this.playlistOfLastInitSegment_[t]!==e.playlist&&(this.appendInitSegment_[t]=!0)}getInitSegmentAndUpdateState_({type:e,initSegment:t,map:i,playlist:n}){if(i){const r=yp(i);if(this.activeInitSegmentId_===r)return null;t=this.initSegmentForMap(i,!0).bytes,this.activeInitSegmentId_=r}return t&&this.appendInitSegment_[e]?(this.playlistOfLastInitSegment_[e]=n,this.appendInitSegment_[e]=!1,this.activeInitSegmentId_=null,t):null}handleQuotaExceededError_({segmentInfo:e,type:t,bytes:i},n){const r=this.sourceUpdater_.audioBuffered(),o=this.sourceUpdater_.videoBuffered();r.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: "+Xl(r).join(", ")),o.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: "+Xl(o).join(", "));const u=r.length?r.start(0):0,c=r.length?r.end(r.length-1):0,d=o.length?o.start(0):0,f=o.length?o.end(o.length-1):0;if(c-u<=Kd&&f-d<=Kd){this.logger_(`On QUOTA_EXCEEDED_ERR, single segment too large to append to buffer, triggering an error. Appended byte length: ${i.byteLength}, audio buffer: ${Xl(r).join(", ")}, video buffer: ${Xl(o).join(", ")}, `),this.error({message:"Quota exceeded error with append of a single segment of content",excludeUntil:1/0}),this.trigger("error");return}this.waitingOnRemove_=!0,this.callQueue_.push(this.appendToSourceBuffer_.bind(this,{segmentInfo:e,type:t,bytes:i}));const g=this.currentTime_()-Kd;this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${g}`),this.remove(0,g,()=>{this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${Kd}s`),this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=de.setTimeout(()=>{this.logger_("On QUOTA_EXCEEDED_ERR, re-processing call queue"),this.quotaExceededErrorRetryTimeout_=null,this.processCallQueue_()},Kd*1e3)},!0)}handleAppendError_({segmentInfo:e,type:t,bytes:i},n){if(n){if(n.code===Nk){this.handleQuotaExceededError_({segmentInfo:e,type:t,bytes:i});return}this.logger_("Received non QUOTA_EXCEEDED_ERR on append",n),this.error({message:`${t} append of ${i.length}b failed for segment #${e.mediaIndex} in playlist ${e.playlist.id}`,metadata:{errorType:Le.Error.StreamingFailedToAppendSegment}}),this.trigger("appenderror")}}appendToSourceBuffer_({segmentInfo:e,type:t,initSegment:i,data:n,bytes:r}){if(!r){const u=[n];let c=n.byteLength;i&&(u.unshift(i),c+=i.byteLength),r=TF({bytes:c,segments:u})}const o={segmentInfo:Kl({type:this.loaderType_,segment:e})};this.trigger({type:"segmentappendstart",metadata:o}),this.sourceUpdater_.appendBuffer({segmentInfo:e,type:t,bytes:r},this.handleAppendError_.bind(this,{segmentInfo:e,type:t,bytes:r}))}handleSegmentTimingInfo_(e,t,i){if(!this.pendingSegment_||t!==this.pendingSegment_.requestId)return;const n=this.pendingSegment_.segment,r=`${e}TimingInfo`;n[r]||(n[r]={}),n[r].transmuxerPrependedSeconds=i.prependedContentDuration||0,n[r].transmuxedPresentationStart=i.start.presentation,n[r].transmuxedDecodeStart=i.start.decode,n[r].transmuxedPresentationEnd=i.end.presentation,n[r].transmuxedDecodeEnd=i.end.decode,n[r].baseMediaDecodeTime=i.baseMediaDecodeTime}appendData_(e,t){const{type:i,data:n}=t;if(!n||!n.byteLength||i==="audio"&&this.audioDisabled_)return;const r=this.getInitSegmentAndUpdateState_({type:i,initSegment:t.initSegment,playlist:e.playlist,map:e.isFmp4?e.segment.map:null});this.appendToSourceBuffer_({segmentInfo:e,type:i,initSegment:r,data:n})}loadSegment_(e){if(this.state="WAITING",this.pendingSegment_=e,this.trimBackBuffer_(e),typeof e.timestampOffset=="number"&&this.transmuxer_&&this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),!this.hasEnoughInfoToLoad_()){qo(this),this.loadQueue_.push(()=>{const t=Cs({},e,{forceTimestampOffset:!0});Cs(e,this.generateSegmentInfo_(t)),this.isPendingTimestampOffset_=!1,this.updateTransmuxerAndRequestSegment_(e)});return}this.updateTransmuxerAndRequestSegment_(e)}updateTransmuxerAndRequestSegment_(e){this.shouldUpdateTransmuxerTimestampOffset_(e.timestampOffset)&&(this.gopBuffer_.length=0,e.gopsToAlignWith=[],this.timeMapping_=0,this.transmuxer_.postMessage({action:"reset"}),this.transmuxer_.postMessage({action:"setTimestampOffset",timestampOffset:e.timestampOffset}));const t=this.createSimplifiedSegmentObj_(e),i=this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex),n=this.mediaIndex!==null,r=e.timeline!==this.currentTimeline_&&e.timeline>0,o=i||n&&r;this.logger_(`Requesting ${nD(e.uri)} ${zu(e)}`),t.map&&!t.map.bytes&&(this.logger_("going to request init segment."),this.appendInitSegment_={video:!0,audio:!0}),e.abortRequests=gF({xhr:this.vhs_.xhr,xhrOptions:this.xhrOptions_,decryptionWorker:this.decrypter_,segment:t,abortFn:this.handleAbort_.bind(this,e),progressFn:this.handleProgress_.bind(this),trackInfoFn:this.handleTrackInfo_.bind(this),timingInfoFn:this.handleTimingInfo_.bind(this),videoSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"video",e.requestId),audioSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"audio",e.requestId),captionsFn:this.handleCaptions_.bind(this),isEndOfTimeline:o,endedTimelineFn:()=>{this.logger_("received endedtimeline callback")},id3Fn:this.handleId3_.bind(this),dataFn:this.handleData_.bind(this),doneFn:this.segmentRequestFinished_.bind(this),onTransmuxerLog:({message:u,level:c,stream:d})=>{this.logger_(`${zu(e)} logged from transmuxer stream ${d} as a ${c}: ${u}`)},triggerSegmentEventFn:({type:u,segment:c,keyInfo:d,trackInfo:f,timingInfo:p})=>{const v={segmentInfo:Kl({segment:c})};d&&(v.keyInfo=d),f&&(v.trackInfo=f),p&&(v.timingInfo=p),this.trigger({type:u,metadata:v})}})}trimBackBuffer_(e){const t=BF(this.seekable_(),this.currentTime_(),this.playlist_.targetDuration||10);t>0&&this.remove(0,t)}createSimplifiedSegmentObj_(e){const t=e.segment,i=e.part,n=e.segment.key||e.segment.map&&e.segment.map.key,r=e.segment.map&&!e.segment.map.bytes,o={resolvedUri:i?i.resolvedUri:t.resolvedUri,byterange:i?i.byterange:t.byterange,requestId:e.requestId,transmuxer:e.transmuxer,audioAppendStart:e.audioAppendStart,gopsToAlignWith:e.gopsToAlignWith,part:e.part,type:this.loaderType_,start:e.startOfSegment,duration:e.duration,isEncrypted:n,isMediaInitialization:r},u=e.playlist.segments[e.mediaIndex-1];if(u&&u.timeline===t.timeline&&(u.videoTimingInfo?o.baseStartTime=u.videoTimingInfo.transmuxedDecodeEnd:u.audioTimingInfo&&(o.baseStartTime=u.audioTimingInfo.transmuxedDecodeEnd)),t.key){const c=t.key.iv||new Uint32Array([0,0,0,e.mediaIndex+e.playlist.mediaSequence]);o.key=this.segmentKey(t.key),o.key.iv=c}return t.map&&(o.map=this.initSegmentForMap(t.map)),o}saveTransferStats_(e){this.mediaRequests+=1,e&&(this.mediaBytesTransferred+=e.bytesReceived,this.mediaTransferDuration+=e.roundTripTime)}saveBandwidthRelatedStats_(e,t){if(this.pendingSegment_.byteLength=t.bytesReceived,e"u"||d.end!==n+r?n:u.start}waitForAppendsToComplete_(e){const t=this.getCurrentMediaInfo_(e);if(!t){this.error({message:"No starting media returned, likely due to an unsupported media format.",playlistExclusionDuration:1/0}),this.trigger("error");return}const{hasAudio:i,hasVideo:n,isMuxed:r}=t,o=this.loaderType_==="main"&&n,u=!this.audioDisabled_&&i&&!r;if(e.waitingOnAppends=0,!e.hasAppendedData_){!e.timingInfo&&typeof e.timestampOffset=="number"&&(this.isPendingTimestampOffset_=!0),e.timingInfo={start:0},e.waitingOnAppends++,this.isPendingTimestampOffset_||(this.updateSourceBufferTimestampOffset_(e),this.processMetadataQueue_()),this.checkAppendsDone_(e);return}o&&e.waitingOnAppends++,u&&e.waitingOnAppends++,o&&this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this,e)),u&&this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this,e))}checkAppendsDone_(e){this.checkForAbort_(e.requestId)||(e.waitingOnAppends--,e.waitingOnAppends===0&&this.handleAppendsDone_())}checkForIllegalMediaSwitch(e){const t=PF(this.loaderType_,this.getCurrentMediaInfo_(),e);return t?(this.error({message:t,playlistExclusionDuration:1/0}),this.trigger("error"),!0):!1}updateSourceBufferTimestampOffset_(e){if(e.timestampOffset===null||typeof e.timingInfo.start!="number"||e.changedTimestampOffset||this.loaderType_!=="main")return;let t=!1;e.timestampOffset-=this.getSegmentStartTimeForTimestampOffsetCalculation_({videoTimingInfo:e.segment.videoTimingInfo,audioTimingInfo:e.segment.audioTimingInfo,timingInfo:e.timingInfo}),e.changedTimestampOffset=!0,e.timestampOffset!==this.sourceUpdater_.videoTimestampOffset()&&(this.sourceUpdater_.videoTimestampOffset(e.timestampOffset),t=!0),e.timestampOffset!==this.sourceUpdater_.audioTimestampOffset()&&(this.sourceUpdater_.audioTimestampOffset(e.timestampOffset),t=!0),t&&this.trigger("timestampoffset")}getSegmentStartTimeForTimestampOffsetCalculation_({videoTimingInfo:e,audioTimingInfo:t,timingInfo:i}){return this.useDtsForTimestampOffset_?e&&typeof e.transmuxedDecodeStart=="number"?e.transmuxedDecodeStart:t&&typeof t.transmuxedDecodeStart=="number"?t.transmuxedDecodeStart:i.start:i.start}updateTimingInfoEnd_(e){e.timingInfo=e.timingInfo||{};const t=this.getMediaInfo_(),n=this.loaderType_==="main"&&t&&t.hasVideo&&e.videoTimingInfo?e.videoTimingInfo:e.audioTimingInfo;n&&(e.timingInfo.end=typeof n.end=="number"?n.end:n.start+e.duration)}handleAppendsDone_(){if(this.pendingSegment_){const c={segmentInfo:Kl({type:this.loaderType_,segment:this.pendingSegment_})};this.trigger({type:"appendsdone",metadata:c})}if(!this.pendingSegment_){this.state="READY",this.paused()||this.monitorBuffer_();return}const e=this.pendingSegment_;e.part&&e.part.syncInfo?e.part.syncInfo.markAppended():e.segment.syncInfo&&e.segment.syncInfo.markAppended(),this.updateTimingInfoEnd_(e),this.shouldSaveSegmentTimingInfo_&&this.syncController_.saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:this.loaderType_==="main"});const t=HF(e,this.sourceType_);if(t&&(t.severity==="warn"?Le.log.warn(t.message):this.logger_(t.message)),this.recordThroughput_(e),this.pendingSegment_=null,this.state="READY",e.isSyncRequest&&(this.trigger("syncinfoupdate"),!e.hasAppendedData_)){this.logger_(`Throwing away un-appended sync request ${zu(e)}`);return}this.logger_(`Appended ${zu(e)}`),this.addSegmentMetadataCue_(e),this.fetchAtBuffer_=!0,this.currentTimeline_!==e.timeline&&(this.timelineChangeController_.lastTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline}),this.loaderType_==="main"&&!this.audioDisabled_&&this.timelineChangeController_.lastTimelineChange({type:"audio",from:this.currentTimeline_,to:e.timeline})),this.currentTimeline_=e.timeline,this.trigger("syncinfoupdate");const i=e.segment,n=e.part,r=i.end&&this.currentTime_()-i.end>e.playlist.targetDuration*3,o=n&&n.end&&this.currentTime_()-n.end>e.playlist.partTargetDuration*3;if(r||o){this.logger_(`bad ${r?"segment":"part"} ${zu(e)}`),this.resetEverything();return}this.mediaIndex!==null&&this.trigger("bandwidthupdate"),this.trigger("progress"),this.mediaIndex=e.mediaIndex,this.partIndex=e.partIndex,this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex)&&this.endOfStream(),this.trigger("appended"),e.hasAppendedData_&&this.mediaAppends++,this.paused()||this.monitorBuffer_()}recordThroughput_(e){if(e.duratione.toUpperCase())},VF=["video","audio"],px=(s,e)=>{const t=e[`${s}Buffer`];return t&&t.updating||e.queuePending[s]},GF=(s,e)=>{for(let t=0;t{if(e.queue.length===0)return;let t=0,i=e.queue[t];if(i.type==="mediaSource"){!e.updating()&&e.mediaSource.readyState!=="closed"&&(e.queue.shift(),i.action(e),i.doneFn&&i.doneFn(),mc("audio",e),mc("video",e));return}if(s!=="mediaSource"&&!(!e.ready()||e.mediaSource.readyState==="closed"||px(s,e))){if(i.type!==s){if(t=GF(s,e.queue),t===null)return;i=e.queue[t]}if(e.queue.splice(t,1),e.queuePending[s]=i,i.action(s,e),!i.doneFn){e.queuePending[s]=null,mc(s,e);return}}},aD=(s,e)=>{const t=e[`${s}Buffer`],i=rD(s);t&&(t.removeEventListener("updateend",e[`on${i}UpdateEnd_`]),t.removeEventListener("error",e[`on${i}Error_`]),e.codecs[s]=null,e[`${s}Buffer`]=null)},la=(s,e)=>s&&e&&Array.prototype.indexOf.call(s.sourceBuffers,e)!==-1,sr={appendBuffer:(s,e,t)=>(i,n)=>{const r=n[`${i}Buffer`];if(la(n.mediaSource,r)){n.logger_(`Appending segment ${e.mediaIndex}'s ${s.length} bytes to ${i}Buffer`);try{r.appendBuffer(s)}catch(o){n.logger_(`Error with code ${o.code} `+(o.code===Nk?"(QUOTA_EXCEEDED_ERR) ":"")+`when appending segment ${e.mediaIndex} to ${i}Buffer`),n.queuePending[i]=null,t(o)}}},remove:(s,e)=>(t,i)=>{const n=i[`${t}Buffer`];if(la(i.mediaSource,n)){i.logger_(`Removing ${s} to ${e} from ${t}Buffer`);try{n.remove(s,e)}catch{i.logger_(`Remove ${s} to ${e} from ${t}Buffer failed`)}}},timestampOffset:s=>(e,t)=>{const i=t[`${e}Buffer`];la(t.mediaSource,i)&&(t.logger_(`Setting ${e}timestampOffset to ${s}`),i.timestampOffset=s)},callback:s=>(e,t)=>{s()},endOfStream:s=>e=>{if(e.mediaSource.readyState==="open"){e.logger_(`Calling mediaSource endOfStream(${s||""})`);try{e.mediaSource.endOfStream(s)}catch(t){Le.log.warn("Failed to call media source endOfStream",t)}}},duration:s=>e=>{e.logger_(`Setting mediaSource duration to ${s}`);try{e.mediaSource.duration=s}catch(t){Le.log.warn("Failed to set media source duration",t)}},abort:()=>(s,e)=>{if(e.mediaSource.readyState!=="open")return;const t=e[`${s}Buffer`];if(la(e.mediaSource,t)){e.logger_(`calling abort on ${s}Buffer`);try{t.abort()}catch(i){Le.log.warn(`Failed to abort on ${s}Buffer`,i)}}},addSourceBuffer:(s,e)=>t=>{const i=rD(s),n=Sc(e);t.logger_(`Adding ${s}Buffer with codec ${e} to mediaSource`);const r=t.mediaSource.addSourceBuffer(n);r.addEventListener("updateend",t[`on${i}UpdateEnd_`]),r.addEventListener("error",t[`on${i}Error_`]),t.codecs[s]=e,t[`${s}Buffer`]=r},removeSourceBuffer:s=>e=>{const t=e[`${s}Buffer`];if(aD(s,e),!!la(e.mediaSource,t)){e.logger_(`Removing ${s}Buffer with codec ${e.codecs[s]} from mediaSource`);try{e.mediaSource.removeSourceBuffer(t)}catch(i){Le.log.warn(`Failed to removeSourceBuffer ${s}Buffer`,i)}}},changeType:s=>(e,t)=>{const i=t[`${e}Buffer`],n=Sc(s);if(!la(t.mediaSource,i))return;const r=s.substring(0,s.indexOf(".")),o=t.codecs[e];if(o.substring(0,o.indexOf("."))===r)return;const c={codecsChangeInfo:{from:o,to:s}};t.trigger({type:"codecschange",metadata:c}),t.logger_(`changing ${e}Buffer codec from ${o} to ${s}`);try{i.changeType(n),t.codecs[e]=s}catch(d){c.errorType=Le.Error.StreamingCodecsChangeError,c.error=d,d.metadata=c,t.error_=d,t.trigger("error"),Le.log.warn(`Failed to changeType on ${e}Buffer`,d)}}},nr=({type:s,sourceUpdater:e,action:t,doneFn:i,name:n})=>{e.queue.push({type:s,action:t,doneFn:i,name:n}),mc(s,e)},a2=(s,e)=>t=>{const i=e[`${s}Buffered`](),n=sB(i);if(e.logger_(`received "updateend" event for ${s} Source Buffer: `,n),e.queuePending[s]){const r=e.queuePending[s].doneFn;e.queuePending[s]=null,r&&r(e[`${s}Error_`])}mc(s,e)};class oD extends Le.EventTarget{constructor(e){super(),this.mediaSource=e,this.sourceopenListener_=()=>mc("mediaSource",this),this.mediaSource.addEventListener("sourceopen",this.sourceopenListener_),this.logger_=Er("SourceUpdater"),this.audioTimestampOffset_=0,this.videoTimestampOffset_=0,this.queue=[],this.queuePending={audio:null,video:null},this.delayedAudioAppendQueue_=[],this.videoAppendQueued_=!1,this.codecs={},this.onVideoUpdateEnd_=a2("video",this),this.onAudioUpdateEnd_=a2("audio",this),this.onVideoError_=t=>{this.videoError_=t},this.onAudioError_=t=>{this.audioError_=t},this.createdSourceBuffers_=!1,this.initializedEme_=!1,this.triggeredReady_=!1}initializedEme(){this.initializedEme_=!0,this.triggerReady()}hasCreatedSourceBuffers(){return this.createdSourceBuffers_}hasInitializedAnyEme(){return this.initializedEme_}ready(){return this.hasCreatedSourceBuffers()&&this.hasInitializedAnyEme()}createSourceBuffers(e){this.hasCreatedSourceBuffers()||(this.addOrChangeSourceBuffers(e),this.createdSourceBuffers_=!0,this.trigger("createdsourcebuffers"),this.triggerReady())}triggerReady(){this.ready()&&!this.triggeredReady_&&(this.triggeredReady_=!0,this.trigger("ready"))}addSourceBuffer(e,t){nr({type:"mediaSource",sourceUpdater:this,action:sr.addSourceBuffer(e,t),name:"addSourceBuffer"})}abort(e){nr({type:e,sourceUpdater:this,action:sr.abort(e),name:"abort"})}removeSourceBuffer(e){if(!this.canRemoveSourceBuffer()){Le.log.error("removeSourceBuffer is not supported!");return}nr({type:"mediaSource",sourceUpdater:this,action:sr.removeSourceBuffer(e),name:"removeSourceBuffer"})}canRemoveSourceBuffer(){return!Le.browser.IS_FIREFOX&&de.MediaSource&&de.MediaSource.prototype&&typeof de.MediaSource.prototype.removeSourceBuffer=="function"}static canChangeType(){return de.SourceBuffer&&de.SourceBuffer.prototype&&typeof de.SourceBuffer.prototype.changeType=="function"}canChangeType(){return this.constructor.canChangeType()}changeType(e,t){if(!this.canChangeType()){Le.log.error("changeType is not supported!");return}nr({type:e,sourceUpdater:this,action:sr.changeType(t),name:"changeType"})}addOrChangeSourceBuffers(e){if(!e||typeof e!="object"||Object.keys(e).length===0)throw new Error("Cannot addOrChangeSourceBuffers to undefined codecs");Object.keys(e).forEach(t=>{const i=e[t];if(!this.hasCreatedSourceBuffers())return this.addSourceBuffer(t,i);this.canChangeType()&&this.changeType(t,i)})}appendBuffer(e,t){const{segmentInfo:i,type:n,bytes:r}=e;if(this.processedAppend_=!0,n==="audio"&&this.videoBuffer&&!this.videoAppendQueued_){this.delayedAudioAppendQueue_.push([e,t]),this.logger_(`delayed audio append of ${r.length} until video append`);return}const o=t;if(nr({type:n,sourceUpdater:this,action:sr.appendBuffer(r,i||{mediaIndex:-1},o),doneFn:t,name:"appendBuffer"}),n==="video"){if(this.videoAppendQueued_=!0,!this.delayedAudioAppendQueue_.length)return;const u=this.delayedAudioAppendQueue_.slice();this.logger_(`queuing delayed audio ${u.length} appendBuffers`),this.delayedAudioAppendQueue_.length=0,u.forEach(c=>{this.appendBuffer.apply(this,c)})}}audioBuffered(){return la(this.mediaSource,this.audioBuffer)&&this.audioBuffer.buffered?this.audioBuffer.buffered:Zs()}videoBuffered(){return la(this.mediaSource,this.videoBuffer)&&this.videoBuffer.buffered?this.videoBuffer.buffered:Zs()}buffered(){const e=la(this.mediaSource,this.videoBuffer)?this.videoBuffer:null,t=la(this.mediaSource,this.audioBuffer)?this.audioBuffer:null;return t&&!e?this.audioBuffered():e&&!t?this.videoBuffered():rB(this.audioBuffered(),this.videoBuffered())}setDuration(e,t=Ja){nr({type:"mediaSource",sourceUpdater:this,action:sr.duration(e),name:"duration",doneFn:t})}endOfStream(e=null,t=Ja){typeof e!="string"&&(e=void 0),nr({type:"mediaSource",sourceUpdater:this,action:sr.endOfStream(e),name:"endOfStream",doneFn:t})}removeAudio(e,t,i=Ja){if(!this.audioBuffered().length||this.audioBuffered().end(0)===0){i();return}nr({type:"audio",sourceUpdater:this,action:sr.remove(e,t),doneFn:i,name:"remove"})}removeVideo(e,t,i=Ja){if(!this.videoBuffered().length||this.videoBuffered().end(0)===0){i();return}nr({type:"video",sourceUpdater:this,action:sr.remove(e,t),doneFn:i,name:"remove"})}updating(){return!!(px("audio",this)||px("video",this))}audioTimestampOffset(e){return typeof e<"u"&&this.audioBuffer&&this.audioTimestampOffset_!==e&&(nr({type:"audio",sourceUpdater:this,action:sr.timestampOffset(e),name:"timestampOffset"}),this.audioTimestampOffset_=e),this.audioTimestampOffset_}videoTimestampOffset(e){return typeof e<"u"&&this.videoBuffer&&this.videoTimestampOffset_!==e&&(nr({type:"video",sourceUpdater:this,action:sr.timestampOffset(e),name:"timestampOffset"}),this.videoTimestampOffset_=e),this.videoTimestampOffset_}audioQueueCallback(e){this.audioBuffer&&nr({type:"audio",sourceUpdater:this,action:sr.callback(e),name:"callback"})}videoQueueCallback(e){this.videoBuffer&&nr({type:"video",sourceUpdater:this,action:sr.callback(e),name:"callback"})}dispose(){this.trigger("dispose"),VF.forEach(e=>{this.abort(e),this.canRemoveSourceBuffer()?this.removeSourceBuffer(e):this[`${e}QueueCallback`](()=>aD(e,this))}),this.videoAppendQueued_=!1,this.delayedAudioAppendQueue_.length=0,this.sourceopenListener_&&this.mediaSource.removeEventListener("sourceopen",this.sourceopenListener_),this.off()}}const o2=s=>decodeURIComponent(escape(String.fromCharCode.apply(null,s))),zF=s=>{const e=new Uint8Array(s);return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")},l2=new Uint8Array(` `.split("").map(s=>s.charCodeAt(0)));class qF extends Error{constructor(){super("Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.")}}class KF extends mx{constructor(e,t={}){super(e,t),this.mediaSource_=null,this.subtitlesTrack_=null,this.featuresNativeTextTracks_=e.featuresNativeTextTracks,this.loadVttJs=e.loadVttJs,this.shouldSaveSegmentTimingInfo_=!1}buffered_(){if(!this.subtitlesTrack_||!this.subtitlesTrack_.cues||!this.subtitlesTrack_.cues.length)return Zs();const e=this.subtitlesTrack_.cues,t=e[0].startTime,i=e[e.length-1].startTime;return Zs([[t,i]])}initSegmentForMap(e,t=!1){if(!e)return null;const i=yp(e);let n=this.initSegments_[i];if(t&&!n&&e.bytes){const r=l2.byteLength+e.bytes.byteLength,o=new Uint8Array(r);o.set(e.bytes),o.set(l2,e.bytes.byteLength),this.initSegments_[i]=n={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:o}}return n||e}couldBeginLoading_(){return this.playlist_&&this.subtitlesTrack_&&!this.paused()}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}track(e){return typeof e>"u"?this.subtitlesTrack_:(this.subtitlesTrack_=e,this.state==="INIT"&&this.couldBeginLoading_()&&this.init_(),this.subtitlesTrack_)}remove(e,t){ih(e,t,this.subtitlesTrack_)}fillBuffer_(){const e=this.chooseNextRequest_();if(e){if(this.syncController_.timestampOffsetForTimeline(e.timeline)===null){const t=()=>{this.state="READY",this.paused()||this.monitorBuffer_()};this.syncController_.one("timestampoffset",t),this.state="WAITING_ON_TIMELINE";return}this.loadSegment_(e)}}timestampOffsetForSegment_(){return null}chooseNextRequest_(){return this.skipEmptySegments_(super.chooseNextRequest_())}skipEmptySegments_(e){for(;e&&e.segment.empty;){if(e.mediaIndex+1>=e.playlist.segments.length){e=null;break}e=this.generateSegmentInfo_({playlist:e.playlist,mediaIndex:e.mediaIndex+1,startOfSegment:e.startOfSegment+e.duration,isSyncRequest:e.isSyncRequest})}return e}stopForError(e){this.error(e),this.state="READY",this.pause(),this.trigger("error")}segmentRequestFinished_(e,t,i){if(!this.subtitlesTrack_){this.state="READY";return}if(this.saveTransferStats_(t.stats),!this.pendingSegment_){this.state="READY",this.mediaRequestsAborted+=1;return}if(e){e.code===ma.TIMEOUT&&this.handleTimeout_(),e.code===ma.ABORTED?this.mediaRequestsAborted+=1:this.mediaRequestsErrored+=1,this.stopForError(e);return}const n=this.pendingSegment_,r=i.mp4VttCues&&i.mp4VttCues.length;r&&(n.mp4VttCues=i.mp4VttCues),this.saveBandwidthRelatedStats_(n.duration,t.stats),t.key&&this.segmentKey(t.key,!0),this.state="APPENDING",this.trigger("appending");const o=n.segment;if(o.map&&(o.map.bytes=t.map.bytes),n.bytes=t.bytes,typeof de.WebVTT!="function"&&typeof this.loadVttJs=="function"){this.state="WAITING_ON_VTTJS",this.loadVttJs().then(()=>this.segmentRequestFinished_(e,t,i),()=>this.stopForError({message:"Error loading vtt.js"}));return}o.requested=!0;try{this.parseVTTCues_(n)}catch(u){this.stopForError({message:u.message,metadata:{errorType:Le.Error.StreamingVttParserError,error:u}});return}if(r||this.updateTimeMapping_(n,this.syncController_.timelines[n.timeline],this.playlist_),n.cues.length?n.timingInfo={start:n.cues[0].startTime,end:n.cues[n.cues.length-1].endTime}:n.timingInfo={start:n.startOfSegment,end:n.startOfSegment+n.duration},n.isSyncRequest){this.trigger("syncinfoupdate"),this.pendingSegment_=null,this.state="READY";return}n.byteLength=n.bytes.byteLength,this.mediaSecondsLoaded+=o.duration,n.cues.forEach(u=>{this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_?new de.VTTCue(u.startTime,u.endTime,u.text):u)}),DF(this.subtitlesTrack_),this.handleAppendsDone_()}handleData_(e,t){const i=e&&e.type==="vtt",n=t&&t.type==="text";i&&n&&super.handleData_(e,t)}updateTimingInfoEnd_(){}parseMp4VttCues_(e){const t=this.sourceUpdater_.videoTimestampOffset()===null?this.sourceUpdater_.audioTimestampOffset():this.sourceUpdater_.videoTimestampOffset();e.mp4VttCues.forEach(i=>{const n=i.start+t,r=i.end+t,o=new de.VTTCue(n,r,i.cueText);i.settings&&i.settings.split(" ").forEach(u=>{const c=u.split(":"),d=c[0],f=c[1];o[d]=isNaN(f)?f:Number(f)}),e.cues.push(o)})}parseVTTCues_(e){let t,i=!1;if(typeof de.WebVTT!="function")throw new qF;if(e.cues=[],e.timestampmap={MPEGTS:0,LOCAL:0},e.mp4VttCues){this.parseMp4VttCues_(e);return}typeof de.TextDecoder=="function"?t=new de.TextDecoder("utf8"):(t=de.WebVTT.StringDecoder(),i=!0);const n=new de.WebVTT.Parser(de,de.vttjs,t);if(n.oncue=e.cues.push.bind(e.cues),n.ontimestampmap=o=>{e.timestampmap=o},n.onparsingerror=o=>{Le.log.warn("Error encountered when parsing cues: "+o.message)},e.segment.map){let o=e.segment.map.bytes;i&&(o=o2(o)),n.parse(o)}let r=e.bytes;i&&(r=o2(r)),n.parse(r),n.flush()}updateTimeMapping_(e,t,i){const n=e.segment;if(!t)return;if(!e.cues.length){n.empty=!0;return}const{MPEGTS:r,LOCAL:o}=e.timestampmap,c=r/Wl.ONE_SECOND_IN_TS-o+t.mapping;if(e.cues.forEach(d=>{const f=d.endTime-d.startTime,p=this.handleRollover_(d.startTime+c,t.time);d.startTime=Math.max(p,0),d.endTime=Math.max(p+f,0)}),!i.syncInfo){const d=e.cues[0].startTime,f=e.cues[e.cues.length-1].startTime;i.syncInfo={mediaSequence:i.mediaSequence+e.mediaIndex,time:Math.min(d,f-n.duration)}}}handleRollover_(e,t){if(t===null)return e;let i=e*Wl.ONE_SECOND_IN_TS;const n=t*Wl.ONE_SECOND_IN_TS;let r;for(n4294967296;)i+=r;return i/Wl.ONE_SECOND_IN_TS}}const YF=function(s,e){const t=s.cues;for(let i=0;i=n.adStartTime&&e<=n.adEndTime)return n}return null},WF=function(s,e,t=0){if(!s.segments)return;let i=t,n;for(let r=0;r=this.start&&e0}resetAppendStatus(){this.segmentSyncInfo_.resetAppendedStatus(),this.partsSyncInfo_.forEach(e=>e.resetAppendedStatus())}}class lD{constructor(){this.storage_=new Map,this.diagnostics_="",this.isReliable_=!1,this.start_=-1/0,this.end_=1/0}get start(){return this.start_}get end(){return this.end_}get diagnostics(){return this.diagnostics_}get isReliable(){return this.isReliable_}resetAppendedStatus(){this.storage_.forEach(e=>e.resetAppendStatus())}update(e,t){const{mediaSequence:i,segments:n}=e;if(this.isReliable_=this.isReliablePlaylist_(i,n),!!this.isReliable_)return this.updateStorage_(n,i,this.calculateBaseTime_(i,n,t))}getSyncInfoForTime(e){for(const{segmentSyncInfo:t,partsSyncInfo:i}of this.storage_.values())if(i.length){for(const n of i)if(n.isInRange(e))return n}else if(t.isInRange(e))return t;return null}getSyncInfoForMediaSequence(e){return this.storage_.get(e)}updateStorage_(e,t,i){const n=new Map;let r=` `,o=i,u=t;this.start_=o,e.forEach((c,d)=>{const f=this.storage_.get(u),p=o,g=p+c.duration,v=!!(f&&f.segmentSyncInfo&&f.segmentSyncInfo.isAppended),b=new u2({start:p,end:g,appended:v,segmentIndex:d});c.syncInfo=b;let _=o;const S=(c.parts||[]).map((D,R)=>{const L=_,P=_+D.duration,U=!!(f&&f.partsSyncInfo&&f.partsSyncInfo[R]&&f.partsSyncInfo[R].isAppended),V=new u2({start:L,end:P,appended:U,segmentIndex:d,partIndex:R});return _=P,r+=`Media Sequence: ${u}.${R} | Range: ${L} --> ${P} | Appended: ${U} `,D.syncInfo=V,V});n.set(u,new XF(b,S)),r+=`${nD(c.resolvedUri)} | Media Sequence: ${u} | Range: ${p} --> ${g} | Appended: ${v} `,u++,o=g}),this.end_=o,this.storage_=n,this.diagnostics_=r}calculateBaseTime_(e,t,i){if(!this.storage_.size)return 0;if(this.storage_.has(e))return this.storage_.get(e).segmentSyncInfo.start;const n=Math.min(...this.storage_.keys());if(et!==1/0?{time:0,segmentIndex:0,partIndex:null}:null},{name:"MediaSequence",run:(s,e,t,i,n,r)=>{const o=s.getMediaSequenceSync(r);if(!o||!o.isReliable)return null;const u=o.getSyncInfoForTime(n);return u?{time:u.start,partIndex:u.partIndex,segmentIndex:u.segmentIndex}:null}},{name:"ProgramDateTime",run:(s,e,t,i,n)=>{if(!Object.keys(s.timelineToDatetimeMappings).length)return null;let r=null,o=null;const u=rx(e);n=n||0;for(let c=0;c{let r=null,o=null;n=n||0;const u=rx(e);for(let c=0;c=v)&&(o=v,r={time:g,segmentIndex:f.segmentIndex,partIndex:f.partIndex})}}return r}},{name:"Discontinuity",run:(s,e,t,i,n)=>{let r=null;if(n=n||0,e.discontinuityStarts&&e.discontinuityStarts.length){let o=null;for(let u=0;u=p)&&(o=p,r={time:f.time,segmentIndex:c,partIndex:null})}}}return r}},{name:"Playlist",run:(s,e,t,i,n)=>e.syncInfo?{time:e.syncInfo.time,segmentIndex:e.syncInfo.mediaSequence-e.mediaSequence,partIndex:null}:null}];class ZF extends Le.EventTarget{constructor(e={}){super(),this.timelines=[],this.discontinuities=[],this.timelineToDatetimeMappings={};const t=new lD,i=new c2(t),n=new c2(t);this.mediaSequenceStorage_={main:t,audio:i,vtt:n},this.logger_=Er("SyncController")}getMediaSequenceSync(e){return this.mediaSequenceStorage_[e]||null}getSyncPoint(e,t,i,n,r){if(t!==1/0)return Jy.find(({name:c})=>c==="VOD").run(this,e,t);const o=this.runStrategies_(e,t,i,n,r);if(!o.length)return null;for(const u of o){const{syncPoint:c,strategy:d}=u,{segmentIndex:f,time:p}=c;if(f<0)continue;const g=e.segments[f],v=p,b=v+g.duration;if(this.logger_(`Strategy: ${d}. Current time: ${n}. selected segment: ${f}. Time: [${v} -> ${b}]}`),n>=v&&n0&&(n.time*=-1),Math.abs(n.time+hh({defaultDuration:e.targetDuration,durationList:e.segments,startIndex:n.segmentIndex,endIndex:0}))}runStrategies_(e,t,i,n,r){const o=[];for(let u=0;uQF){Le.log.warn(`Not saving expired segment info. Media sequence gap ${i} is too large.`);return}for(let n=i-1;n>=0;n--){const r=e.segments[n];if(r&&typeof r.start<"u"){t.syncInfo={mediaSequence:e.mediaSequence+n,time:r.start},this.logger_(`playlist refresh sync: [time:${t.syncInfo.time}, mediaSequence: ${t.syncInfo.mediaSequence}]`),this.trigger("syncinfoupdate");break}}}setDateTimeMappingForStart(e){if(this.timelineToDatetimeMappings={},e.segments&&e.segments.length&&e.segments[0].dateTimeObject){const t=e.segments[0],i=t.dateTimeObject.getTime()/1e3;this.timelineToDatetimeMappings[t.timeline]=-i}}saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:t}){const i=this.calculateSegmentTimeMapping_(e,e.timingInfo,t),n=e.segment;i&&(this.saveDiscontinuitySyncInfo_(e),e.playlist.syncInfo||(e.playlist.syncInfo={mediaSequence:e.playlist.mediaSequence+e.mediaIndex,time:n.start}));const r=n.dateTimeObject;n.discontinuity&&t&&r&&(this.timelineToDatetimeMappings[n.timeline]=-(r.getTime()/1e3))}timestampOffsetForTimeline(e){return typeof this.timelines[e]>"u"?null:this.timelines[e].time}mappingForTimeline(e){return typeof this.timelines[e]>"u"?null:this.timelines[e].mapping}calculateSegmentTimeMapping_(e,t,i){const n=e.segment,r=e.part;let o=this.timelines[e.timeline],u,c;if(typeof e.timestampOffset=="number")o={time:e.startOfSegment,mapping:e.startOfSegment-t.start},i&&(this.timelines[e.timeline]=o,this.trigger("timestampoffset"),this.logger_(`time mapping for timeline ${e.timeline}: [time: ${o.time}] [mapping: ${o.mapping}]`)),u=e.startOfSegment,c=t.end+o.mapping;else if(o)u=t.start+o.mapping,c=t.end+o.mapping;else return!1;return r&&(r.start=u,r.end=c),(!n.start||uc){let d;u<0?d=i.start-hh({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex,endIndex:r}):d=i.end+hh({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex+1,endIndex:r}),this.discontinuities[o]={time:d,accuracy:c}}}}dispose(){this.trigger("dispose"),this.off()}}class JF extends Le.EventTarget{constructor(){super(),this.pendingTimelineChanges_={},this.lastTimelineChanges_={}}clearPendingTimelineChange(e){this.pendingTimelineChanges_[e]=null,this.trigger("pendingtimelinechange")}pendingTimelineChange({type:e,from:t,to:i}){return typeof t=="number"&&typeof i=="number"&&(this.pendingTimelineChanges_[e]={type:e,from:t,to:i},this.trigger("pendingtimelinechange")),this.pendingTimelineChanges_[e]}lastTimelineChange({type:e,from:t,to:i}){if(typeof t=="number"&&typeof i=="number"){this.lastTimelineChanges_[e]={type:e,from:t,to:i},delete this.pendingTimelineChanges_[e];const n={timelineChangeInfo:{from:t,to:i}};this.trigger({type:"timelinechange",metadata:n})}return this.lastTimelineChanges_[e]}dispose(){this.trigger("dispose"),this.pendingTimelineChanges_={},this.lastTimelineChanges_={},this.off()}}const e8=Kk(Yk(function(){var s=(function(){function _(){this.listeners={}}var S=_.prototype;return S.on=function(R,L){this.listeners[R]||(this.listeners[R]=[]),this.listeners[R].push(L)},S.off=function(R,L){if(!this.listeners[R])return!1;var P=this.listeners[R].indexOf(L);return this.listeners[R]=this.listeners[R].slice(0),this.listeners[R].splice(P,1),P>-1},S.trigger=function(R){var L=this.listeners[R];if(L)if(arguments.length===2)for(var P=L.length,U=0;U>7)*283)^P]=P;for(U=V=0;!R[U];U^=N||1,V=G[V]||1)for(Q=V^V<<1^V<<2^V<<3^V<<4,Q=Q>>8^Q&255^99,R[U]=Q,L[Q]=U,K=M[O=M[N=M[U]]],re=K*16843009^O*65537^N*257^U*16843008,W=M[Q]*257^Q*16843008,P=0;P<4;P++)S[P][U]=W=W<<24^W>>>8,D[P][Q]=re=re<<24^re>>>8;for(P=0;P<5;P++)S[P]=S[P].slice(0),D[P]=D[P].slice(0);return _};let i=null;class n{constructor(S){i||(i=t()),this._tables=[[i[0][0].slice(),i[0][1].slice(),i[0][2].slice(),i[0][3].slice(),i[0][4].slice()],[i[1][0].slice(),i[1][1].slice(),i[1][2].slice(),i[1][3].slice(),i[1][4].slice()]];let D,R,L;const P=this._tables[0][4],U=this._tables[1],V=S.length;let M=1;if(V!==4&&V!==6&&V!==8)throw new Error("Invalid aes key size");const G=S.slice(0),N=[];for(this._key=[G,N],D=V;D<4*V+28;D++)L=G[D-1],(D%V===0||V===8&&D%V===4)&&(L=P[L>>>24]<<24^P[L>>16&255]<<16^P[L>>8&255]<<8^P[L&255],D%V===0&&(L=L<<8^L>>>24^M<<24,M=M<<1^(M>>7)*283)),G[D]=G[D-V]^L;for(R=0;D;R++,D--)L=G[R&3?D:D-4],D<=4||R<4?N[R]=L:N[R]=U[0][P[L>>>24]]^U[1][P[L>>16&255]]^U[2][P[L>>8&255]]^U[3][P[L&255]]}decrypt(S,D,R,L,P,U){const V=this._key[1];let M=S^V[0],G=L^V[1],N=R^V[2],O=D^V[3],K,Q,W;const re=V.length/4-2;let J,Y=4;const z=this._tables[1],Z=z[0],ie=z[1],ce=z[2],j=z[3],ee=z[4];for(J=0;J>>24]^ie[G>>16&255]^ce[N>>8&255]^j[O&255]^V[Y],Q=Z[G>>>24]^ie[N>>16&255]^ce[O>>8&255]^j[M&255]^V[Y+1],W=Z[N>>>24]^ie[O>>16&255]^ce[M>>8&255]^j[G&255]^V[Y+2],O=Z[O>>>24]^ie[M>>16&255]^ce[G>>8&255]^j[N&255]^V[Y+3],Y+=4,M=K,G=Q,N=W;for(J=0;J<4;J++)P[(3&-J)+U]=ee[M>>>24]<<24^ee[G>>16&255]<<16^ee[N>>8&255]<<8^ee[O&255]^V[Y++],K=M,M=G,G=N,N=O,O=K}}class r extends s{constructor(){super(s),this.jobs=[],this.delay=1,this.timeout_=null}processJob_(){this.jobs.shift()(),this.jobs.length?this.timeout_=setTimeout(this.processJob_.bind(this),this.delay):this.timeout_=null}push(S){this.jobs.push(S),this.timeout_||(this.timeout_=setTimeout(this.processJob_.bind(this),this.delay))}}const o=function(_){return _<<24|(_&65280)<<8|(_&16711680)>>8|_>>>24},u=function(_,S,D){const R=new Int32Array(_.buffer,_.byteOffset,_.byteLength>>2),L=new n(Array.prototype.slice.call(S)),P=new Uint8Array(_.byteLength),U=new Int32Array(P.buffer);let V,M,G,N,O,K,Q,W,re;for(V=D[0],M=D[1],G=D[2],N=D[3],re=0;re{const R=_[D];g(R)?S[D]={bytes:R.buffer,byteOffset:R.byteOffset,byteLength:R.byteLength}:S[D]=R}),S};self.onmessage=function(_){const S=_.data,D=new Uint8Array(S.encrypted.bytes,S.encrypted.byteOffset,S.encrypted.byteLength),R=new Uint32Array(S.key.bytes,S.key.byteOffset,S.key.byteLength/4),L=new Uint32Array(S.iv.bytes,S.iv.byteOffset,S.iv.byteLength/4);new c(D,R,L,function(P,U){self.postMessage(b({source:S.source,decrypted:U}),[U.buffer])})}}));var t8=qk(e8);const i8=s=>{let e=s.default?"main":"alternative";return s.characteristics&&s.characteristics.indexOf("public.accessibility.describes-video")>=0&&(e="main-desc"),e},uD=(s,e)=>{s.abort(),s.pause(),e&&e.activePlaylistLoader&&(e.activePlaylistLoader.pause(),e.activePlaylistLoader=null)},gx=(s,e)=>{e.activePlaylistLoader=s,s.load()},s8=(s,e)=>()=>{const{segmentLoaders:{[s]:t,main:i},mediaTypes:{[s]:n}}=e,r=n.activeTrack(),o=n.getActiveGroup(),u=n.activePlaylistLoader,c=n.lastGroup_;if(!(o&&c&&o.id===c.id)&&(n.lastGroup_=o,n.lastTrack_=r,uD(t,n),!(!o||o.isMainPlaylist))){if(!o.playlistLoader){u&&i.resetEverything();return}t.resyncLoader(),gx(o.playlistLoader,n)}},n8=(s,e)=>()=>{const{segmentLoaders:{[s]:t},mediaTypes:{[s]:i}}=e;i.lastGroup_=null,t.abort(),t.pause()},r8=(s,e)=>()=>{const{mainPlaylistLoader:t,segmentLoaders:{[s]:i,main:n},mediaTypes:{[s]:r}}=e,o=r.activeTrack(),u=r.getActiveGroup(),c=r.activePlaylistLoader,d=r.lastTrack_;if(!(d&&o&&d.id===o.id)&&(r.lastGroup_=u,r.lastTrack_=o,uD(i,r),!!u)){if(u.isMainPlaylist){if(!o||!d||o.id===d.id)return;const f=e.vhs.playlistController_,p=f.selectPlaylist();if(f.media()===p)return;r.logger_(`track change. Switching main audio from ${d.id} to ${o.id}`),t.pause(),n.resetEverything(),f.fastQualityChange_(p);return}if(s==="AUDIO"){if(!u.playlistLoader){n.setAudio(!0),n.resetEverything();return}i.setAudio(!0),n.setAudio(!1)}if(c===u.playlistLoader){gx(u.playlistLoader,r);return}i.track&&i.track(o),i.resetEverything(),gx(u.playlistLoader,r)}},vp={AUDIO:(s,e)=>()=>{const{mediaTypes:{[s]:t},excludePlaylist:i}=e,n=t.activeTrack(),r=t.activeGroup(),o=(r.filter(c=>c.default)[0]||r[0]).id,u=t.tracks[o];if(n===u){i({error:{message:"Problem encountered loading the default audio track."}});return}Le.log.warn("Problem encountered loading the alternate audio track.Switching back to default.");for(const c in t.tracks)t.tracks[c].enabled=t.tracks[c]===u;t.onTrackChanged()},SUBTITLES:(s,e)=>()=>{const{mediaTypes:{[s]:t}}=e;Le.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track.");const i=t.activeTrack();i&&(i.mode="disabled"),t.onTrackChanged()}},d2={AUDIO:(s,e,t)=>{if(!e)return;const{tech:i,requestOptions:n,segmentLoaders:{[s]:r}}=t;e.on("loadedmetadata",()=>{const o=e.media();r.playlist(o,n),(!i.paused()||o.endList&&i.preload()!=="none")&&r.load()}),e.on("loadedplaylist",()=>{r.playlist(e.media(),n),i.paused()||r.load()}),e.on("error",vp[s](s,t))},SUBTITLES:(s,e,t)=>{const{tech:i,requestOptions:n,segmentLoaders:{[s]:r},mediaTypes:{[s]:o}}=t;e.on("loadedmetadata",()=>{const u=e.media();r.playlist(u,n),r.track(o.activeTrack()),(!i.paused()||u.endList&&i.preload()!=="none")&&r.load()}),e.on("loadedplaylist",()=>{r.playlist(e.media(),n),i.paused()||r.load()}),e.on("error",vp[s](s,t))}},a8={AUDIO:(s,e)=>{const{vhs:t,sourceType:i,segmentLoaders:{[s]:n},requestOptions:r,main:{mediaGroups:o},mediaTypes:{[s]:{groups:u,tracks:c,logger_:d}},mainPlaylistLoader:f}=e,p=Fh(f.main);(!o[s]||Object.keys(o[s]).length===0)&&(o[s]={main:{default:{default:!0}}},p&&(o[s].main.default.playlists=f.main.playlists));for(const g in o[s]){u[g]||(u[g]=[]);for(const v in o[s][g]){let b=o[s][g][v],_;if(p?(d(`AUDIO group '${g}' label '${v}' is a main playlist`),b.isMainPlaylist=!0,_=null):i==="vhs-json"&&b.playlists?_=new sc(b.playlists[0],t,r):b.resolvedUri?_=new sc(b.resolvedUri,t,r):b.playlists&&i==="dash"?_=new dx(b.playlists[0],t,r,f):_=null,b=Oi({id:v,playlistLoader:_},b),d2[s](s,b.playlistLoader,e),u[g].push(b),typeof c[v]>"u"){const S=new Le.AudioTrack({id:v,kind:i8(b),enabled:!1,language:b.language,default:b.default,label:v});c[v]=S}}}n.on("error",vp[s](s,e))},SUBTITLES:(s,e)=>{const{tech:t,vhs:i,sourceType:n,segmentLoaders:{[s]:r},requestOptions:o,main:{mediaGroups:u},mediaTypes:{[s]:{groups:c,tracks:d}},mainPlaylistLoader:f}=e;for(const p in u[s]){c[p]||(c[p]=[]);for(const g in u[s][p]){if(!i.options_.useForcedSubtitles&&u[s][p][g].forced)continue;let v=u[s][p][g],b;if(n==="hls")b=new sc(v.resolvedUri,i,o);else if(n==="dash"){if(!v.playlists.filter(S=>S.excludeUntil!==1/0).length)return;b=new dx(v.playlists[0],i,o,f)}else n==="vhs-json"&&(b=new sc(v.playlists?v.playlists[0]:v.resolvedUri,i,o));if(v=Oi({id:g,playlistLoader:b},v),d2[s](s,v.playlistLoader,e),c[p].push(v),typeof d[g]>"u"){const _=t.addRemoteTextTrack({id:g,kind:"subtitles",default:v.default&&v.autoselect,language:v.language,label:g},!1).track;d[g]=_}}}r.on("error",vp[s](s,e))},"CLOSED-CAPTIONS":(s,e)=>{const{tech:t,main:{mediaGroups:i},mediaTypes:{[s]:{groups:n,tracks:r}}}=e;for(const o in i[s]){n[o]||(n[o]=[]);for(const u in i[s][o]){const c=i[s][o][u];if(!/^(?:CC|SERVICE)/.test(c.instreamId))continue;const d=t.options_.vhs&&t.options_.vhs.captionServices||{};let f={label:u,language:c.language,instreamId:c.instreamId,default:c.default&&c.autoselect};if(d[f.instreamId]&&(f=Oi(f,d[f.instreamId])),f.default===void 0&&delete f.default,n[o].push(Oi({id:u},c)),typeof r[u]>"u"){const p=t.addRemoteTextTrack({id:f.instreamId,kind:"captions",default:f.default,language:f.language,label:f.label},!1).track;r[u]=p}}}}},cD=(s,e)=>{for(let t=0;tt=>{const{mainPlaylistLoader:i,mediaTypes:{[s]:{groups:n}}}=e,r=i.media();if(!r)return null;let o=null;r.attributes[s]&&(o=n[r.attributes[s]]);const u=Object.keys(n);if(!o)if(s==="AUDIO"&&u.length>1&&Fh(e.main))for(let c=0;c"u"?o:t===null||!o?null:o.filter(c=>c.id===t.id)[0]||null},l8={AUDIO:(s,e)=>()=>{const{mediaTypes:{[s]:{tracks:t}}}=e;for(const i in t)if(t[i].enabled)return t[i];return null},SUBTITLES:(s,e)=>()=>{const{mediaTypes:{[s]:{tracks:t}}}=e;for(const i in t)if(t[i].mode==="showing"||t[i].mode==="hidden")return t[i];return null}},u8=(s,{mediaTypes:e})=>()=>{const t=e[s].activeTrack();return t?e[s].activeGroup(t):null},c8=s=>{["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(d=>{a8[d](d,s)});const{mediaTypes:e,mainPlaylistLoader:t,tech:i,vhs:n,segmentLoaders:{["AUDIO"]:r,main:o}}=s;["AUDIO","SUBTITLES"].forEach(d=>{e[d].activeGroup=o8(d,s),e[d].activeTrack=l8[d](d,s),e[d].onGroupChanged=s8(d,s),e[d].onGroupChanging=n8(d,s),e[d].onTrackChanged=r8(d,s),e[d].getActiveGroup=u8(d,s)});const u=e.AUDIO.activeGroup();if(u){const d=(u.filter(p=>p.default)[0]||u[0]).id;e.AUDIO.tracks[d].enabled=!0,e.AUDIO.onGroupChanged(),e.AUDIO.onTrackChanged(),e.AUDIO.getActiveGroup().playlistLoader?(o.setAudio(!1),r.setAudio(!0)):o.setAudio(!0)}t.on("mediachange",()=>{["AUDIO","SUBTITLES"].forEach(d=>e[d].onGroupChanged())}),t.on("mediachanging",()=>{["AUDIO","SUBTITLES"].forEach(d=>e[d].onGroupChanging())});const c=()=>{e.AUDIO.onTrackChanged(),i.trigger({type:"usage",name:"vhs-audio-change"})};i.audioTracks().addEventListener("change",c),i.remoteTextTracks().addEventListener("change",e.SUBTITLES.onTrackChanged),n.on("dispose",()=>{i.audioTracks().removeEventListener("change",c),i.remoteTextTracks().removeEventListener("change",e.SUBTITLES.onTrackChanged)}),i.clearTracks("audio");for(const d in e.AUDIO.tracks)i.audioTracks().addTrack(e.AUDIO.tracks[d])},d8=()=>{const s={};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{s[e]={groups:{},tracks:{},activePlaylistLoader:null,activeGroup:Ja,activeTrack:Ja,getActiveGroup:Ja,onGroupChanged:Ja,onTrackChanged:Ja,lastTrack_:null,logger_:Er(`MediaGroups[${e}]`)}}),s};class h2{constructor(){this.priority_=[],this.pathwayClones_=new Map}set version(e){e===1&&(this.version_=e)}set ttl(e){this.ttl_=e||300}set reloadUri(e){e&&(this.reloadUri_=$n(this.reloadUri_,e))}set priority(e){e&&e.length&&(this.priority_=e)}set pathwayClones(e){e&&e.length&&(this.pathwayClones_=new Map(e.map(t=>[t.ID,t])))}get version(){return this.version_}get ttl(){return this.ttl_}get reloadUri(){return this.reloadUri_}get priority(){return this.priority_}get pathwayClones(){return this.pathwayClones_}}let h8=class extends Le.EventTarget{constructor(e,t){super(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=!1,this.availablePathways_=new Set,this.steeringManifest=new h2,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.currentPathwayClones=new Map,this.nextPathwayClones=new Map,this.excludedSteeringManifestURLs=new Set,this.logger_=Er("Content Steering"),this.xhr_=e,this.getBandwidth_=t}assignTagProperties(e,t){this.manifestType_=t.serverUri?"HLS":"DASH";const i=t.serverUri||t.serverURL;if(!i){this.logger_(`steering manifest URL is ${i}, cannot request steering manifest.`),this.trigger("error");return}if(i.startsWith("data:")){this.decodeDataUriManifest_(i.substring(i.indexOf(",")+1));return}this.steeringManifest.reloadUri=$n(e,i),this.defaultPathway=t.pathwayId||t.defaultServiceLocation,this.queryBeforeStart=t.queryBeforeStart,this.proxyServerUrl_=t.proxyServerURL,this.defaultPathway&&!this.queryBeforeStart&&this.trigger("content-steering")}requestSteeringManifest(e){const t=this.steeringManifest.reloadUri;if(!t)return;const i=e?t:this.getRequestURI(t);if(!i){this.logger_("No valid content steering manifest URIs. Stopping content steering."),this.trigger("error"),this.dispose();return}const n={contentSteeringInfo:{uri:i}};this.trigger({type:"contentsteeringloadstart",metadata:n}),this.request_=this.xhr_({uri:i,requestType:"content-steering-manifest"},(r,o)=>{if(r){if(o.status===410){this.logger_(`manifest request 410 ${r}.`),this.logger_(`There will be no more content steering requests to ${i} this session.`),this.excludedSteeringManifestURLs.add(i);return}if(o.status===429){const d=o.responseHeaders["retry-after"];this.logger_(`manifest request 429 ${r}.`),this.logger_(`content steering will retry in ${d} seconds.`),this.startTTLTimeout_(parseInt(d,10));return}this.logger_(`manifest failed to load ${r}.`),this.startTTLTimeout_();return}this.trigger({type:"contentsteeringloadcomplete",metadata:n});let u;try{u=JSON.parse(this.request_.responseText)}catch(d){const f={errorType:Le.Error.StreamingContentSteeringParserError,error:d};this.trigger({type:"error",metadata:f})}this.assignSteeringProperties_(u);const c={contentSteeringInfo:n.contentSteeringInfo,contentSteeringManifest:{version:this.steeringManifest.version,reloadUri:this.steeringManifest.reloadUri,priority:this.steeringManifest.priority}};this.trigger({type:"contentsteeringparsed",metadata:c}),this.startTTLTimeout_()})}setProxyServerUrl_(e){const t=new de.URL(e),i=new de.URL(this.proxyServerUrl_);return i.searchParams.set("url",encodeURI(t.toString())),this.setSteeringParams_(i.toString())}decodeDataUriManifest_(e){const t=JSON.parse(de.atob(e));this.assignSteeringProperties_(t)}setSteeringParams_(e){const t=new de.URL(e),i=this.getPathway(),n=this.getBandwidth_();if(i){const r=`_${this.manifestType_}_pathway`;t.searchParams.set(r,i)}if(n){const r=`_${this.manifestType_}_throughput`;t.searchParams.set(r,n)}return t.toString()}assignSteeringProperties_(e){if(this.steeringManifest.version=e.VERSION,!this.steeringManifest.version){this.logger_(`manifest version is ${e.VERSION}, which is not supported.`),this.trigger("error");return}this.steeringManifest.ttl=e.TTL,this.steeringManifest.reloadUri=e["RELOAD-URI"],this.steeringManifest.priority=e["PATHWAY-PRIORITY"]||e["SERVICE-LOCATION-PRIORITY"],this.steeringManifest.pathwayClones=e["PATHWAY-CLONES"],this.nextPathwayClones=this.steeringManifest.pathwayClones,this.availablePathways_.size||(this.logger_("There are no available pathways for content steering. Ending content steering."),this.trigger("error"),this.dispose());const i=(n=>{for(const r of n)if(this.availablePathways_.has(r))return r;return[...this.availablePathways_][0]})(this.steeringManifest.priority);this.currentPathway!==i&&(this.currentPathway=i,this.trigger("content-steering"))}getPathway(){return this.currentPathway||this.defaultPathway}getRequestURI(e){if(!e)return null;const t=n=>this.excludedSteeringManifestURLs.has(n);if(this.proxyServerUrl_){const n=this.setProxyServerUrl_(e);if(!t(n))return n}const i=this.setSteeringParams_(e);return t(i)?null:i}startTTLTimeout_(e=this.steeringManifest.ttl){const t=e*1e3;this.ttlTimeout_=de.setTimeout(()=>{this.requestSteeringManifest()},t)}clearTTLTimeout_(){de.clearTimeout(this.ttlTimeout_),this.ttlTimeout_=null}abort(){this.request_&&this.request_.abort(),this.request_=null}dispose(){this.off("content-steering"),this.off("error"),this.abort(),this.clearTTLTimeout_(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=null,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.excludedSteeringManifestURLs=new Set,this.availablePathways_=new Set,this.steeringManifest=new h2}addAvailablePathway(e){e&&this.availablePathways_.add(e)}clearAvailablePathways(){this.availablePathways_.clear()}excludePathway(e){return this.availablePathways_.delete(e)}didDASHTagChange(e,t){return!t&&this.steeringManifest.reloadUri||t&&($n(e,t.serverURL)!==this.steeringManifest.reloadUri||t.defaultServiceLocation!==this.defaultPathway||t.queryBeforeStart!==this.queryBeforeStart||t.proxyServerURL!==this.proxyServerUrl_)}getAvailablePathways(){return this.availablePathways_}};const f8=(s,e)=>{let t=null;return(...i)=>{clearTimeout(t),t=setTimeout(()=>{s.apply(null,i)},e)}},m8=10;let Ko;const p8=["mediaRequests","mediaRequestsAborted","mediaRequestsTimedout","mediaRequestsErrored","mediaTransferDuration","mediaBytesTransferred","mediaAppends"],g8=function(s){return this.audioSegmentLoader_[s]+this.mainSegmentLoader_[s]},y8=function({currentPlaylist:s,buffered:e,currentTime:t,nextPlaylist:i,bufferLowWaterLine:n,bufferHighWaterLine:r,duration:o,bufferBasedABR:u,log:c}){if(!i)return Le.log.warn("We received no playlist to switch to. Please check your stream."),!1;const d=`allowing switch ${s&&s.id||"null"} -> ${i.id}`;if(!s)return c(`${d} as current playlist is not set`),!0;if(i.id===s.id)return!1;const f=!!ic(e,t).length;if(!s.endList)return!f&&typeof s.partTargetDuration=="number"?(c(`not ${d} as current playlist is live llhls, but currentTime isn't in buffered.`),!1):(c(`${d} as current playlist is live`),!0);const p=Cb(e,t),g=u?Xs.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:Xs.MAX_BUFFER_LOW_WATER_LINE;if(ob)&&p>=n){let _=`${d} as forwardBuffer >= bufferLowWaterLine (${p} >= ${n})`;return u&&(_+=` and next bandwidth > current bandwidth (${v} > ${b})`),c(_),!0}return c(`not ${d} as no switching criteria met`),!1};class v8 extends Le.EventTarget{constructor(e){super(),this.fastQualityChange_=f8(this.fastQualityChange_.bind(this),100);const{src:t,withCredentials:i,tech:n,bandwidth:r,externVhs:o,useCueTags:u,playlistExclusionDuration:c,enableLowInitialPlaylist:d,sourceType:f,cacheEncryptionKeys:p,bufferBasedABR:g,leastPixelDiffSelector:v,captionServices:b,experimentalUseMMS:_}=e;if(!t)throw new Error("A non-empty playlist URL or JSON manifest string is required");let{maxPlaylistRetries:S}=e;(S===null||typeof S>"u")&&(S=1/0),Ko=o,this.bufferBasedABR=!!g,this.leastPixelDiffSelector=!!v,this.withCredentials=i,this.tech_=n,this.vhs_=n.vhs,this.player_=e.player_,this.sourceType_=f,this.useCueTags_=u,this.playlistExclusionDuration=c,this.maxPlaylistRetries=S,this.enableLowInitialPlaylist=d,this.usingManagedMediaSource_=!1,this.useCueTags_&&(this.cueTagsTrack_=this.tech_.addTextTrack("metadata","ad-cues"),this.cueTagsTrack_.inBandMetadataTrackDispatchType=""),this.requestOptions_={withCredentials:i,maxPlaylistRetries:S,timeout:null},this.on("error",this.pauseLoading),this.mediaTypes_=d8(),_&&de.ManagedMediaSource?(this.tech_.el_.disableRemotePlayback=!0,this.mediaSource=new de.ManagedMediaSource,this.usingManagedMediaSource_=!0,Le.log("Using ManagedMediaSource")):de.MediaSource&&(this.mediaSource=new de.MediaSource),this.handleDurationChange_=this.handleDurationChange_.bind(this),this.handleSourceOpen_=this.handleSourceOpen_.bind(this),this.handleSourceEnded_=this.handleSourceEnded_.bind(this),this.load=this.load.bind(this),this.pause=this.pause.bind(this),this.mediaSource.addEventListener("durationchange",this.handleDurationChange_),this.mediaSource.addEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.addEventListener("sourceended",this.handleSourceEnded_),this.mediaSource.addEventListener("startstreaming",this.load),this.mediaSource.addEventListener("endstreaming",this.pause),this.seekable_=Zs(),this.hasPlayed_=!1,this.syncController_=new ZF(e),this.segmentMetadataTrack_=n.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},!1).track,this.segmentMetadataTrack_.mode="hidden",this.decrypter_=new t8,this.sourceUpdater_=new oD(this.mediaSource),this.inbandTextTracks_={},this.timelineChangeController_=new JF,this.keyStatusMap_=new Map;const D={vhs:this.vhs_,parse708captions:e.parse708captions,useDtsForTimestampOffset:e.useDtsForTimestampOffset,captionServices:b,mediaSource:this.mediaSource,currentTime:this.tech_.currentTime.bind(this.tech_),seekable:()=>this.seekable(),seeking:()=>this.tech_.seeking(),duration:()=>this.duration(),hasPlayed:()=>this.hasPlayed_,goalBufferLength:()=>this.goalBufferLength(),bandwidth:r,syncController:this.syncController_,decrypter:this.decrypter_,sourceType:this.sourceType_,inbandTextTracks:this.inbandTextTracks_,cacheEncryptionKeys:p,sourceUpdater:this.sourceUpdater_,timelineChangeController:this.timelineChangeController_,exactManifestTimings:e.exactManifestTimings,addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)};this.mainPlaylistLoader_=this.sourceType_==="dash"?new dx(t,this.vhs_,Oi(this.requestOptions_,{addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)})):new sc(t,this.vhs_,Oi(this.requestOptions_,{addDateRangesToTextTrack:this.addDateRangesToTextTrack_.bind(this)})),this.setupMainPlaylistLoaderListeners_(),this.mainSegmentLoader_=new mx(Oi(D,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:"main"}),e),this.audioSegmentLoader_=new mx(Oi(D,{loaderType:"audio"}),e),this.subtitleSegmentLoader_=new KF(Oi(D,{loaderType:"vtt",featuresNativeTextTracks:this.tech_.featuresNativeTextTracks,loadVttJs:()=>new Promise((P,U)=>{function V(){n.off("vttjserror",M),P()}function M(){n.off("vttjsloaded",V),U()}n.one("vttjsloaded",V),n.one("vttjserror",M),n.addWebVttScript_()})}),e);const R=()=>this.mainSegmentLoader_.bandwidth;this.contentSteeringController_=new h8(this.vhs_.xhr,R),this.setupSegmentLoaderListeners_(),this.bufferBasedABR&&(this.mainPlaylistLoader_.one("loadedplaylist",()=>this.startABRTimer_()),this.tech_.on("pause",()=>this.stopABRTimer_()),this.tech_.on("play",()=>this.startABRTimer_())),p8.forEach(P=>{this[P+"_"]=g8.bind(this,P)}),this.logger_=Er("pc"),this.triggeredFmp4Usage=!1,this.tech_.preload()==="none"?(this.loadOnPlay_=()=>{this.loadOnPlay_=null,this.mainPlaylistLoader_.load()},this.tech_.one("play",this.loadOnPlay_)):this.mainPlaylistLoader_.load(),this.timeToLoadedData__=-1,this.mainAppendsToLoadedData__=-1,this.audioAppendsToLoadedData__=-1;const L=this.tech_.preload()==="none"?"play":"loadstart";this.tech_.one(L,()=>{const P=Date.now();this.tech_.one("loadeddata",()=>{this.timeToLoadedData__=Date.now()-P,this.mainAppendsToLoadedData__=this.mainSegmentLoader_.mediaAppends,this.audioAppendsToLoadedData__=this.audioSegmentLoader_.mediaAppends})})}mainAppendsToLoadedData_(){return this.mainAppendsToLoadedData__}audioAppendsToLoadedData_(){return this.audioAppendsToLoadedData__}appendsToLoadedData_(){const e=this.mainAppendsToLoadedData_(),t=this.audioAppendsToLoadedData_();return e===-1||t===-1?-1:e+t}timeToLoadedData_(){return this.timeToLoadedData__}checkABR_(e="abr"){const t=this.selectPlaylist();t&&this.shouldSwitchToMedia_(t)&&this.switchMedia_(t,e)}switchMedia_(e,t,i){const n=this.media(),r=n&&(n.id||n.uri),o=e&&(e.id||e.uri);if(r&&r!==o){this.logger_(`switch media ${r} -> ${o} from ${t}`);const u={renditionInfo:{id:o,bandwidth:e.attributes.BANDWIDTH,resolution:e.attributes.RESOLUTION,codecs:e.attributes.CODECS},cause:t};this.trigger({type:"renditionselected",metadata:u}),this.tech_.trigger({type:"usage",name:`vhs-rendition-change-${t}`})}this.mainPlaylistLoader_.media(e,i)}switchMediaForDASHContentSteering_(){["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{const t=this.mediaTypes_[e],i=t?t.activeGroup():null,n=this.contentSteeringController_.getPathway();if(i&&n){const o=(i.length?i[0].playlists:i.playlists).filter(u=>u.attributes.serviceLocation===n);o.length&&this.mediaTypes_[e].activePlaylistLoader.media(o[0])}})}startABRTimer_(){this.stopABRTimer_(),this.abrTimer_=de.setInterval(()=>this.checkABR_(),250)}stopABRTimer_(){this.tech_.scrubbing&&this.tech_.scrubbing()||(de.clearInterval(this.abrTimer_),this.abrTimer_=null)}getAudioTrackPlaylists_(){const e=this.main(),t=e&&e.playlists||[];if(!e||!e.mediaGroups||!e.mediaGroups.AUDIO)return t;const i=e.mediaGroups.AUDIO,n=Object.keys(i);let r;if(Object.keys(this.mediaTypes_.AUDIO.groups).length)r=this.mediaTypes_.AUDIO.activeTrack();else{const u=i.main||n.length&&i[n[0]];for(const c in u)if(u[c].default){r={label:c};break}}if(!r)return t;const o=[];for(const u in i)if(i[u][r.label]){const c=i[u][r.label];if(c.playlists&&c.playlists.length)o.push.apply(o,c.playlists);else if(c.uri)o.push(c);else if(e.playlists.length)for(let d=0;d{const t=this.mainPlaylistLoader_.media(),i=t.targetDuration*1.5*1e3;ax(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=i,t.endList&&this.tech_.preload()!=="none"&&(this.mainSegmentLoader_.playlist(t,this.requestOptions_),this.mainSegmentLoader_.load()),c8({sourceType:this.sourceType_,segmentLoaders:{AUDIO:this.audioSegmentLoader_,SUBTITLES:this.subtitleSegmentLoader_,main:this.mainSegmentLoader_},tech:this.tech_,requestOptions:this.requestOptions_,mainPlaylistLoader:this.mainPlaylistLoader_,vhs:this.vhs_,main:this.main(),mediaTypes:this.mediaTypes_,excludePlaylist:this.excludePlaylist.bind(this)}),this.triggerPresenceUsage_(this.main(),t),this.setupFirstPlay(),!this.mediaTypes_.AUDIO.activePlaylistLoader||this.mediaTypes_.AUDIO.activePlaylistLoader.media()?this.trigger("selectedinitialmedia"):this.mediaTypes_.AUDIO.activePlaylistLoader.one("loadedmetadata",()=>{this.trigger("selectedinitialmedia")})}),this.mainPlaylistLoader_.on("loadedplaylist",()=>{this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_);let t=this.mainPlaylistLoader_.media();if(!t){this.attachContentSteeringListeners_(),this.initContentSteeringController_(),this.excludeUnsupportedVariants_();let i;if(this.enableLowInitialPlaylist&&(i=this.selectInitialPlaylist()),i||(i=this.selectPlaylist()),!i||!this.shouldSwitchToMedia_(i)||(this.initialMedia_=i,this.switchMedia_(this.initialMedia_,"initial"),!(this.sourceType_==="vhs-json"&&this.initialMedia_.segments)))return;t=this.initialMedia_}this.handleUpdatedMediaPlaylist(t)}),this.mainPlaylistLoader_.on("error",()=>{const t=this.mainPlaylistLoader_.error;this.excludePlaylist({playlistToExclude:t.playlist,error:t})}),this.mainPlaylistLoader_.on("mediachanging",()=>{this.mainSegmentLoader_.abort(),this.mainSegmentLoader_.pause()}),this.mainPlaylistLoader_.on("mediachange",()=>{const t=this.mainPlaylistLoader_.media(),i=t.targetDuration*1.5*1e3;ax(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=i,this.sourceType_==="dash"&&this.mainPlaylistLoader_.isPaused&&this.mainPlaylistLoader_.load(),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(t,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_?this.runFastQualitySwitch_():this.mainSegmentLoader_.load(),this.tech_.trigger({type:"mediachange",bubbles:!0})}),this.mainPlaylistLoader_.on("playlistunchanged",()=>{const t=this.mainPlaylistLoader_.media();if(t.lastExcludeReason_==="playlist-unchanged")return;this.stuckAtPlaylistEnd_(t)&&(this.excludePlaylist({error:{message:"Playlist no longer updating.",reason:"playlist-unchanged"}}),this.tech_.trigger("playliststuck"))}),this.mainPlaylistLoader_.on("renditiondisabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-disabled"})}),this.mainPlaylistLoader_.on("renditionenabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-enabled"})}),["manifestrequeststart","manifestrequestcomplete","manifestparsestart","manifestparsecomplete","playlistrequeststart","playlistrequestcomplete","playlistparsestart","playlistparsecomplete","renditiondisabled","renditionenabled"].forEach(t=>{this.mainPlaylistLoader_.on(t,i=>{this.player_.trigger(Cs({},i))})})}handleUpdatedMediaPlaylist(e){this.useCueTags_&&this.updateAdCues_(e),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_&&this.runFastQualitySwitch_(),this.updateDuration(!e.endList),this.tech_.paused()||(this.mainSegmentLoader_.load(),this.audioSegmentLoader_&&this.audioSegmentLoader_.load())}triggerPresenceUsage_(e,t){const i=e.mediaGroups||{};let n=!0;const r=Object.keys(i.AUDIO);for(const o in i.AUDIO)for(const u in i.AUDIO[o])i.AUDIO[o][u].uri||(n=!1);n&&this.tech_.trigger({type:"usage",name:"vhs-demuxed"}),Object.keys(i.SUBTITLES).length&&this.tech_.trigger({type:"usage",name:"vhs-webvtt"}),Ko.Playlist.isAes(t)&&this.tech_.trigger({type:"usage",name:"vhs-aes"}),r.length&&Object.keys(i.AUDIO[r[0]]).length>1&&this.tech_.trigger({type:"usage",name:"vhs-alternate-audio"}),this.useCueTags_&&this.tech_.trigger({type:"usage",name:"vhs-playlist-cue-tags"})}shouldSwitchToMedia_(e){const t=this.mainPlaylistLoader_.media()||this.mainPlaylistLoader_.pendingMedia_,i=this.tech_.currentTime(),n=this.bufferLowWaterLine(),r=this.bufferHighWaterLine(),o=this.tech_.buffered();return y8({buffered:o,currentTime:i,currentPlaylist:t,nextPlaylist:e,bufferLowWaterLine:n,bufferHighWaterLine:r,duration:this.duration(),bufferBasedABR:this.bufferBasedABR,log:this.logger_})}setupSegmentLoaderListeners_(){this.mainSegmentLoader_.on("bandwidthupdate",()=>{this.checkABR_("bandwidthupdate"),this.tech_.trigger("bandwidthupdate")}),this.mainSegmentLoader_.on("timeout",()=>{this.bufferBasedABR&&this.mainSegmentLoader_.load()}),this.bufferBasedABR||this.mainSegmentLoader_.on("progress",()=>{this.trigger("progress")}),this.mainSegmentLoader_.on("error",()=>{const i=this.mainSegmentLoader_.error();this.excludePlaylist({playlistToExclude:i.playlist,error:i})}),this.mainSegmentLoader_.on("appenderror",()=>{this.error=this.mainSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.mainSegmentLoader_.on("timestampoffset",()=>{this.tech_.trigger({type:"usage",name:"vhs-timestamp-offset"})}),this.audioSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.audioSegmentLoader_.on("appenderror",()=>{this.error=this.audioSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("ended",()=>{this.logger_("main segment loader ended"),this.onEndOfStream()}),this.timelineChangeController_.on("audioTimelineBehind",()=>{const i=this.audioSegmentLoader_.pendingSegment_;if(!i||!i.segment||!i.segment.syncInfo)return;const n=i.segment.syncInfo.end+.01;this.tech_.setCurrentTime(n)}),this.timelineChangeController_.on("fixBadTimelineChange",()=>{this.logger_("Fix bad timeline change. Restarting al segment loaders..."),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}),this.mainSegmentLoader_.on("earlyabort",i=>{this.bufferBasedABR||(this.delegateLoaders_("all",["abort"]),this.excludePlaylist({error:{message:"Aborted early because there isn't enough bandwidth to complete the request without rebuffering."},playlistExclusionDuration:m8}))});const e=()=>{if(!this.sourceUpdater_.hasCreatedSourceBuffers())return this.tryToCreateSourceBuffers_();const i=this.getCodecsOrExclude_();i&&this.sourceUpdater_.addOrChangeSourceBuffers(i)};this.mainSegmentLoader_.on("trackinfo",e),this.audioSegmentLoader_.on("trackinfo",e),this.mainSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)}),this.audioSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)}),this.audioSegmentLoader_.on("ended",()=>{this.logger_("audioSegmentLoader ended"),this.onEndOfStream()}),["segmentselected","segmentloadstart","segmentloaded","segmentkeyloadstart","segmentkeyloadcomplete","segmentdecryptionstart","segmentdecryptioncomplete","segmenttransmuxingstart","segmenttransmuxingcomplete","segmenttransmuxingtrackinfoavailable","segmenttransmuxingtiminginfoavailable","segmentappendstart","appendsdone","bandwidthupdated","timelinechange","codecschange"].forEach(i=>{this.mainSegmentLoader_.on(i,n=>{this.player_.trigger(Cs({},n))}),this.audioSegmentLoader_.on(i,n=>{this.player_.trigger(Cs({},n))}),this.subtitleSegmentLoader_.on(i,n=>{this.player_.trigger(Cs({},n))})})}mediaSecondsLoaded_(){return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded+this.mainSegmentLoader_.mediaSecondsLoaded)}load(){this.mainSegmentLoader_.load(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.load(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.load()}pause(){this.mainSegmentLoader_.pause(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.pause(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.pause()}fastQualityChange_(e=this.selectPlaylist()){if(e&&e===this.mainPlaylistLoader_.media()){this.logger_("skipping fastQualityChange because new media is same as old");return}this.switchMedia_(e,"fast-quality"),this.waitingForFastQualityPlaylistReceived_=!0}runFastQualitySwitch_(){this.waitingForFastQualityPlaylistReceived_=!1,this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}play(){if(this.setupFirstPlay())return;this.tech_.ended()&&this.tech_.setCurrentTime(0),this.hasPlayed_&&this.load();const e=this.tech_.seekable();if(this.tech_.duration()===1/0&&this.tech_.currentTime(){})}this.trigger("sourceopen")}handleSourceEnded_(){if(!this.inbandTextTracks_.metadataTrack_)return;const e=this.inbandTextTracks_.metadataTrack_.cues;if(!e||!e.length)return;const t=this.duration();e[e.length-1].endTime=isNaN(t)||Math.abs(t)===1/0?Number.MAX_VALUE:t}handleDurationChange_(){this.tech_.trigger("durationchange")}onEndOfStream(){let e=this.mainSegmentLoader_.ended_;if(this.mediaTypes_.AUDIO.activePlaylistLoader){const t=this.mainSegmentLoader_.getCurrentMediaInfo_();!t||t.hasVideo?e=e&&this.audioSegmentLoader_.ended_:e=this.audioSegmentLoader_.ended_}e&&(this.stopABRTimer_(),this.sourceUpdater_.endOfStream())}stuckAtPlaylistEnd_(e){if(!this.seekable().length)return!1;const i=this.syncController_.getExpiredTime(e,this.duration());if(i===null)return!1;const n=Ko.Playlist.playlistEnd(e,i),r=this.tech_.currentTime(),o=this.tech_.buffered();if(!o.length)return n-r<=fa;const u=o.end(o.length-1);return u-r<=fa&&n-u<=fa}excludePlaylist({playlistToExclude:e=this.mainPlaylistLoader_.media(),error:t={},playlistExclusionDuration:i}){if(e=e||this.mainPlaylistLoader_.media(),i=i||t.playlistExclusionDuration||this.playlistExclusionDuration,!e){this.error=t,this.mediaSource.readyState!=="open"?this.trigger("error"):this.sourceUpdater_.endOfStream("network");return}e.playlistErrors_++;const n=this.mainPlaylistLoader_.main.playlists,r=n.filter(ug),o=r.length===1&&r[0]===e;if(n.length===1&&i!==1/0)return Le.log.warn(`Problem encountered with playlist ${e.id}. Trying again since it is the only playlist.`),this.tech_.trigger("retryplaylist"),this.mainPlaylistLoader_.load(o);if(o){if(this.main().contentSteering){const b=this.pathwayAttribute_(e),_=this.contentSteeringController_.steeringManifest.ttl*1e3;this.contentSteeringController_.excludePathway(b),this.excludeThenChangePathway_(),setTimeout(()=>{this.contentSteeringController_.addAvailablePathway(b)},_);return}let v=!1;n.forEach(b=>{if(b===e)return;const _=b.excludeUntil;typeof _<"u"&&_!==1/0&&(v=!0,delete b.excludeUntil)}),v&&(Le.log.warn("Removing other playlists from the exclusion list because the last rendition is about to be excluded."),this.tech_.trigger("retryplaylist"))}let u;e.playlistErrors_>this.maxPlaylistRetries?u=1/0:u=Date.now()+i*1e3,e.excludeUntil=u,t.reason&&(e.lastExcludeReason_=t.reason),this.tech_.trigger("excludeplaylist"),this.tech_.trigger({type:"usage",name:"vhs-rendition-excluded"});const c=this.selectPlaylist();if(!c){this.error="Playback cannot continue. No available working or supported playlists.",this.trigger("error");return}const d=t.internal?this.logger_:Le.log.warn,f=t.message?" "+t.message:"";d(`${t.internal?"Internal problem":"Problem"} encountered with playlist ${e.id}.${f} Switching to playlist ${c.id}.`),c.attributes.AUDIO!==e.attributes.AUDIO&&this.delegateLoaders_("audio",["abort","pause"]),c.attributes.SUBTITLES!==e.attributes.SUBTITLES&&this.delegateLoaders_("subtitle",["abort","pause"]),this.delegateLoaders_("main",["abort","pause"]);const p=c.targetDuration/2*1e3||5*1e3,g=typeof c.lastRequest=="number"&&Date.now()-c.lastRequest<=p;return this.switchMedia_(c,"exclude",o||g)}pauseLoading(){this.delegateLoaders_("all",["abort","pause"]),this.stopABRTimer_()}delegateLoaders_(e,t){const i=[],n=e==="all";(n||e==="main")&&i.push(this.mainPlaylistLoader_);const r=[];(n||e==="audio")&&r.push("AUDIO"),(n||e==="subtitle")&&(r.push("CLOSED-CAPTIONS"),r.push("SUBTITLES")),r.forEach(o=>{const u=this.mediaTypes_[o]&&this.mediaTypes_[o].activePlaylistLoader;u&&i.push(u)}),["main","audio","subtitle"].forEach(o=>{const u=this[`${o}SegmentLoader_`];u&&(e===o||e==="all")&&i.push(u)}),i.forEach(o=>t.forEach(u=>{typeof o[u]=="function"&&o[u]()}))}setCurrentTime(e){const t=ic(this.tech_.buffered(),e);if(!(this.mainPlaylistLoader_&&this.mainPlaylistLoader_.media())||!this.mainPlaylistLoader_.media().segments)return 0;if(t&&t.length)return e;this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}duration(){if(!this.mainPlaylistLoader_)return 0;const e=this.mainPlaylistLoader_.media();return e?e.endList?this.mediaSource?this.mediaSource.duration:Ko.Playlist.duration(e):1/0:0}seekable(){return this.seekable_}getSeekableRange_(e,t){const i=e.media();if(!i)return null;const n=this.syncController_.getMediaSequenceSync(t);if(n&&n.isReliable){const u=n.start,c=n.end;if(!isFinite(u)||!isFinite(c))return null;const d=Ko.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i),f=Math.max(u,c-d);return Zs([[u,f]])}const r=this.syncController_.getExpiredTime(i,this.duration());if(r===null)return null;const o=Ko.Playlist.seekable(i,r,Ko.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i));return o.length?o:null}computeFinalSeekable_(e,t){if(!t)return e;const i=e.start(0),n=e.end(0),r=t.start(0),o=t.end(0);return r>n||i>o?e:Zs([[Math.max(i,r),Math.min(n,o)]])}onSyncInfoUpdate_(){if(!this.mainPlaylistLoader_)return;const e=this.getSeekableRange_(this.mainPlaylistLoader_,"main");if(!e)return;let t;if(this.mediaTypes_.AUDIO.activePlaylistLoader&&(t=this.getSeekableRange_(this.mediaTypes_.AUDIO.activePlaylistLoader,"audio"),!t))return;const i=this.seekable_;if(this.seekable_=this.computeFinalSeekable_(e,t),!this.seekable_||i&&i.length&&this.seekable_.length&&i.start(0)===this.seekable_.start(0)&&i.end(0)===this.seekable_.end(0))return;this.logger_(`seekable updated [${bk(this.seekable_)}]`);const n={seekableRanges:this.seekable_};this.trigger({type:"seekablerangeschanged",metadata:n}),this.tech_.trigger("seekablechanged")}updateDuration(e){if(this.updateDuration_&&(this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.updateDuration_=null),this.mediaSource.readyState!=="open"){this.updateDuration_=this.updateDuration.bind(this,e),this.mediaSource.addEventListener("sourceopen",this.updateDuration_);return}if(e){const n=this.seekable();if(!n.length)return;(isNaN(this.mediaSource.duration)||this.mediaSource.duration0&&(i=Math.max(i,t.end(t.length-1))),this.mediaSource.duration!==i&&this.sourceUpdater_.setDuration(i)}dispose(){this.trigger("dispose"),this.decrypter_.terminate(),this.mainPlaylistLoader_.dispose(),this.mainSegmentLoader_.dispose(),this.contentSteeringController_.dispose(),this.keyStatusMap_.clear(),this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_),["AUDIO","SUBTITLES"].forEach(e=>{const t=this.mediaTypes_[e].groups;for(const i in t)t[i].forEach(n=>{n.playlistLoader&&n.playlistLoader.dispose()})}),this.audioSegmentLoader_.dispose(),this.subtitleSegmentLoader_.dispose(),this.sourceUpdater_.dispose(),this.timelineChangeController_.dispose(),this.stopABRTimer_(),this.updateDuration_&&this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.mediaSource.removeEventListener("durationchange",this.handleDurationChange_),this.mediaSource.removeEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.removeEventListener("sourceended",this.handleSourceEnded_),this.off()}main(){return this.mainPlaylistLoader_.main}media(){return this.mainPlaylistLoader_.media()||this.initialMedia_}areMediaTypesKnown_(){const e=!!this.mediaTypes_.AUDIO.activePlaylistLoader,t=!!this.mainSegmentLoader_.getCurrentMediaInfo_(),i=e?!!this.audioSegmentLoader_.getCurrentMediaInfo_():!0;return!(!t||!i)}getCodecsOrExclude_(){const e={main:this.mainSegmentLoader_.getCurrentMediaInfo_()||{},audio:this.audioSegmentLoader_.getCurrentMediaInfo_()||{}},t=this.mainSegmentLoader_.getPendingSegmentPlaylist()||this.media();e.video=e.main;const i=fh(this.main(),t),n={},r=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(e.main.hasVideo&&(n.video=i.video||e.main.videoCodec||aP),e.main.isMuxed&&(n.video+=`,${i.audio||e.main.audioCodec||tE}`),(e.main.hasAudio&&!e.main.isMuxed||e.audio.hasAudio||r)&&(n.audio=i.audio||e.main.audioCodec||e.audio.audioCodec||tE,e.audio.isFmp4=e.main.hasAudio&&!e.main.isMuxed?e.main.isFmp4:e.audio.isFmp4),!n.audio&&!n.video){this.excludePlaylist({playlistToExclude:t,error:{message:"Could not determine codecs for playlist."},playlistExclusionDuration:1/0});return}const o=(d,f)=>d?lh(f,this.usingManagedMediaSource_):Ny(f),u={};let c;if(["video","audio"].forEach(function(d){if(n.hasOwnProperty(d)&&!o(e[d].isFmp4,n[d])){const f=e[d].isFmp4?"browser":"muxer";u[f]=u[f]||[],u[f].push(n[d]),d==="audio"&&(c=f)}}),r&&c&&t.attributes.AUDIO){const d=t.attributes.AUDIO;this.main().playlists.forEach(f=>{(f.attributes&&f.attributes.AUDIO)===d&&f!==t&&(f.excludeUntil=1/0)}),this.logger_(`excluding audio group ${d} as ${c} does not support codec(s): "${n.audio}"`)}if(Object.keys(u).length){const d=Object.keys(u).reduce((f,p)=>(f&&(f+=", "),f+=`${p} does not support codec(s): "${u[p].join(",")}"`,f),"")+".";this.excludePlaylist({playlistToExclude:t,error:{internal:!0,message:d},playlistExclusionDuration:1/0});return}if(this.sourceUpdater_.hasCreatedSourceBuffers()&&!this.sourceUpdater_.canChangeType()){const d=[];if(["video","audio"].forEach(f=>{const p=(oa(this.sourceUpdater_.codecs[f]||"")[0]||{}).type,g=(oa(n[f]||"")[0]||{}).type;p&&g&&p.toLowerCase()!==g.toLowerCase()&&d.push(`"${this.sourceUpdater_.codecs[f]}" -> "${n[f]}"`)}),d.length){this.excludePlaylist({playlistToExclude:t,error:{message:`Codec switching not supported: ${d.join(", ")}.`,internal:!0},playlistExclusionDuration:1/0});return}}return n}tryToCreateSourceBuffers_(){if(this.mediaSource.readyState!=="open"||this.sourceUpdater_.hasCreatedSourceBuffers()||!this.areMediaTypesKnown_())return;const e=this.getCodecsOrExclude_();if(!e)return;this.sourceUpdater_.createSourceBuffers(e);const t=[e.video,e.audio].filter(Boolean).join(",");this.excludeIncompatibleVariants_(t)}excludeUnsupportedVariants_(){const e=this.main().playlists,t=[];Object.keys(e).forEach(i=>{const n=e[i];if(t.indexOf(n.id)!==-1)return;t.push(n.id);const r=fh(this.main,n),o=[];r.audio&&!Ny(r.audio)&&!lh(r.audio,this.usingManagedMediaSource_)&&o.push(`audio codec ${r.audio}`),r.video&&!Ny(r.video)&&!lh(r.video,this.usingManagedMediaSource_)&&o.push(`video codec ${r.video}`),r.text&&r.text==="stpp.ttml.im1t"&&o.push(`text codec ${r.text}`),o.length&&(n.excludeUntil=1/0,this.logger_(`excluding ${n.id} for unsupported: ${o.join(", ")}`))})}excludeIncompatibleVariants_(e){const t=[],i=this.main().playlists,n=_h(oa(e)),r=YE(n),o=n.video&&oa(n.video)[0]||null,u=n.audio&&oa(n.audio)[0]||null;Object.keys(i).forEach(c=>{const d=i[c];if(t.indexOf(d.id)!==-1||d.excludeUntil===1/0)return;t.push(d.id);const f=[],p=fh(this.mainPlaylistLoader_.main,d),g=YE(p);if(!(!p.audio&&!p.video)){if(g!==r&&f.push(`codec count "${g}" !== "${r}"`),!this.sourceUpdater_.canChangeType()){const v=p.video&&oa(p.video)[0]||null,b=p.audio&&oa(p.audio)[0]||null;v&&o&&v.type.toLowerCase()!==o.type.toLowerCase()&&f.push(`video codec "${v.type}" !== "${o.type}"`),b&&u&&b.type.toLowerCase()!==u.type.toLowerCase()&&f.push(`audio codec "${b.type}" !== "${u.type}"`)}f.length&&(d.excludeUntil=1/0,this.logger_(`excluding ${d.id}: ${f.join(" && ")}`))}})}updateAdCues_(e){let t=0;const i=this.seekable();i.length&&(t=i.start(0)),WF(e,this.cueTagsTrack_,t)}goalBufferLength(){const e=this.tech_.currentTime(),t=Xs.GOAL_BUFFER_LENGTH,i=Xs.GOAL_BUFFER_LENGTH_RATE,n=Math.max(t,Xs.MAX_GOAL_BUFFER_LENGTH);return Math.min(t+e*i,n)}bufferLowWaterLine(){const e=this.tech_.currentTime(),t=Xs.BUFFER_LOW_WATER_LINE,i=Xs.BUFFER_LOW_WATER_LINE_RATE,n=Math.max(t,Xs.MAX_BUFFER_LOW_WATER_LINE),r=Math.max(t,Xs.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(t+e*i,this.bufferBasedABR?r:n)}bufferHighWaterLine(){return Xs.BUFFER_HIGH_WATER_LINE}addDateRangesToTextTrack_(e){i2(this.inbandTextTracks_,"com.apple.streaming",this.tech_),kF({inbandTextTracks:this.inbandTextTracks_,dateRanges:e})}addMetadataToTextTrack(e,t,i){const n=this.sourceUpdater_.videoBuffer?this.sourceUpdater_.videoTimestampOffset():this.sourceUpdater_.audioTimestampOffset();i2(this.inbandTextTracks_,e,this.tech_),wF({inbandTextTracks:this.inbandTextTracks_,metadataArray:t,timestampOffset:n,videoDuration:i})}pathwayAttribute_(e){return e.attributes["PATHWAY-ID"]||e.attributes.serviceLocation}initContentSteeringController_(){const e=this.main();if(e.contentSteering){for(const t of e.playlists)this.contentSteeringController_.addAvailablePathway(this.pathwayAttribute_(t));if(this.contentSteeringController_.assignTagProperties(e.uri,e.contentSteering),this.contentSteeringController_.queryBeforeStart){this.contentSteeringController_.requestSteeringManifest(!0);return}this.tech_.one("canplay",()=>{this.contentSteeringController_.requestSteeringManifest()})}}resetContentSteeringController_(){this.contentSteeringController_.clearAvailablePathways(),this.contentSteeringController_.dispose(),this.initContentSteeringController_()}attachContentSteeringListeners_(){this.contentSteeringController_.on("content-steering",this.excludeThenChangePathway_.bind(this)),["contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"].forEach(t=>{this.contentSteeringController_.on(t,i=>{this.trigger(Cs({},i))})}),this.sourceType_==="dash"&&this.mainPlaylistLoader_.on("loadedplaylist",()=>{const t=this.main();(this.contentSteeringController_.didDASHTagChange(t.uri,t.contentSteering)||(()=>{const r=this.contentSteeringController_.getAvailablePathways(),o=[];for(const u of t.playlists){const c=u.attributes.serviceLocation;if(c&&(o.push(c),!r.has(c)))return!0}return!!(!o.length&&r.size)})())&&this.resetContentSteeringController_()})}excludeThenChangePathway_(){const e=this.contentSteeringController_.getPathway();if(!e)return;this.handlePathwayClones_();const i=this.main().playlists,n=new Set;let r=!1;Object.keys(i).forEach(o=>{const u=i[o],c=this.pathwayAttribute_(u),d=c&&e!==c;u.excludeUntil===1/0&&u.lastExcludeReason_==="content-steering"&&!d&&(delete u.excludeUntil,delete u.lastExcludeReason_,r=!0);const p=!u.excludeUntil&&u.excludeUntil!==1/0;!n.has(u.id)&&d&&p&&(n.add(u.id),u.excludeUntil=1/0,u.lastExcludeReason_="content-steering",this.logger_(`excluding ${u.id} for ${u.lastExcludeReason_}`))}),this.contentSteeringController_.manifestType_==="DASH"&&Object.keys(this.mediaTypes_).forEach(o=>{const u=this.mediaTypes_[o];if(u.activePlaylistLoader){const c=u.activePlaylistLoader.media_;c&&c.attributes.serviceLocation!==e&&(r=!0)}}),r&&this.changeSegmentPathway_()}handlePathwayClones_(){const t=this.main().playlists,i=this.contentSteeringController_.currentPathwayClones,n=this.contentSteeringController_.nextPathwayClones;if(i&&i.size||n&&n.size){for(const[o,u]of i.entries())n.get(o)||(this.mainPlaylistLoader_.updateOrDeleteClone(u),this.contentSteeringController_.excludePathway(o));for(const[o,u]of n.entries()){const c=i.get(o);if(!c){t.filter(f=>f.attributes["PATHWAY-ID"]===u["BASE-ID"]).forEach(f=>{this.mainPlaylistLoader_.addClonePathway(u,f)}),this.contentSteeringController_.addAvailablePathway(o);continue}this.equalPathwayClones_(c,u)||(this.mainPlaylistLoader_.updateOrDeleteClone(u,!0),this.contentSteeringController_.addAvailablePathway(o))}this.contentSteeringController_.currentPathwayClones=new Map(JSON.parse(JSON.stringify([...n])))}}equalPathwayClones_(e,t){if(e["BASE-ID"]!==t["BASE-ID"]||e.ID!==t.ID||e["URI-REPLACEMENT"].HOST!==t["URI-REPLACEMENT"].HOST)return!1;const i=e["URI-REPLACEMENT"].PARAMS,n=t["URI-REPLACEMENT"].PARAMS;for(const r in i)if(i[r]!==n[r])return!1;for(const r in n)if(i[r]!==n[r])return!1;return!0}changeSegmentPathway_(){const e=this.selectPlaylist();this.pauseLoading(),this.contentSteeringController_.manifestType_==="DASH"&&this.switchMediaForDASHContentSteering_(),this.switchMedia_(e,"content-steering")}excludeNonUsablePlaylistsByKeyId_(){if(!this.mainPlaylistLoader_||!this.mainPlaylistLoader_.main)return;let e=0;const t="non-usable";this.mainPlaylistLoader_.main.playlists.forEach(i=>{const n=this.mainPlaylistLoader_.getKeyIdSet(i);!n||!n.size||n.forEach(r=>{const o="usable",u=this.keyStatusMap_.has(r)&&this.keyStatusMap_.get(r)===o,c=i.lastExcludeReason_===t&&i.excludeUntil===1/0;u?u&&c&&(delete i.excludeUntil,delete i.lastExcludeReason_,this.logger_(`enabling playlist ${i.id} because key ID ${r} is ${o}`)):(i.excludeUntil!==1/0&&i.lastExcludeReason_!==t&&(i.excludeUntil=1/0,i.lastExcludeReason_=t,this.logger_(`excluding playlist ${i.id} because the key ID ${r} doesn't exist in the keyStatusMap or is not ${o}`)),e++)})}),e>=this.mainPlaylistLoader_.main.playlists.length&&this.mainPlaylistLoader_.main.playlists.forEach(i=>{const n=i&&i.attributes&&i.attributes.RESOLUTION&&i.attributes.RESOLUTION.height<720,r=i.excludeUntil===1/0&&i.lastExcludeReason_===t;n&&r&&(delete i.excludeUntil,Le.log.warn(`enabling non-HD playlist ${i.id} because all playlists were excluded due to ${t} key IDs`))})}addKeyStatus_(e,t){const r=(typeof e=="string"?e:zF(e)).slice(0,32).toLowerCase();this.logger_(`KeyStatus '${t}' with key ID ${r} added to the keyStatusMap`),this.keyStatusMap_.set(r,t)}updatePlaylistByKeyStatus(e,t){this.addKeyStatus_(e,t),this.waitingForFastQualityPlaylistReceived_||this.excludeNonUsableThenChangePlaylist_(),this.mainPlaylistLoader_.off("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this)),this.mainPlaylistLoader_.on("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this))}excludeNonUsableThenChangePlaylist_(){this.excludeNonUsablePlaylistsByKeyId_(),this.fastQualityChange_()}}const x8=(s,e,t)=>i=>{const n=s.main.playlists[e],r=Db(n),o=ug(n);if(typeof i>"u")return o;i?delete n.disabled:n.disabled=!0;const u={renditionInfo:{id:e,bandwidth:n.attributes.BANDWIDTH,resolution:n.attributes.RESOLUTION,codecs:n.attributes.CODECS},cause:"fast-quality"};return i!==o&&!r&&(i?(t(n),s.trigger({type:"renditionenabled",metadata:u})):s.trigger({type:"renditiondisabled",metadata:u})),i};class b8{constructor(e,t,i){const{playlistController_:n}=e,r=n.fastQualityChange_.bind(n);if(t.attributes){const o=t.attributes.RESOLUTION;this.width=o&&o.width,this.height=o&&o.height,this.bandwidth=t.attributes.BANDWIDTH,this.frameRate=t.attributes["FRAME-RATE"]}this.codecs=fh(n.main(),t),this.playlist=t,this.id=i,this.enabled=x8(e.playlists,t.id,r)}}const T8=function(s){s.representations=()=>{const e=s.playlistController_.main(),t=Fh(e)?s.playlistController_.getAudioTrackPlaylists_():e.playlists;return t?t.filter(i=>!Db(i)).map((i,n)=>new b8(s,i,i.id)):[]}},f2=["seeking","seeked","pause","playing","error"];class _8 extends Le.EventTarget{constructor(e){super(),this.playlistController_=e.playlistController,this.tech_=e.tech,this.seekable=e.seekable,this.allowSeeksWithinUnsafeLiveWindow=e.allowSeeksWithinUnsafeLiveWindow,this.liveRangeSafeTimeDelta=e.liveRangeSafeTimeDelta,this.media=e.media,this.playedRanges_=[],this.consecutiveUpdates=0,this.lastRecordedTime=null,this.checkCurrentTimeTimeout_=null,this.logger_=Er("PlaybackWatcher"),this.logger_("initialize");const t=()=>this.monitorCurrentTime_(),i=()=>this.monitorCurrentTime_(),n=()=>this.techWaiting_(),r=()=>this.resetTimeUpdate_(),o=this.playlistController_,u=["main","subtitle","audio"],c={};u.forEach(f=>{c[f]={reset:()=>this.resetSegmentDownloads_(f),updateend:()=>this.checkSegmentDownloads_(f)},o[`${f}SegmentLoader_`].on("appendsdone",c[f].updateend),o[`${f}SegmentLoader_`].on("playlistupdate",c[f].reset),this.tech_.on(["seeked","seeking"],c[f].reset)});const d=f=>{["main","audio"].forEach(p=>{o[`${p}SegmentLoader_`][f]("appended",this.seekingAppendCheck_)})};this.seekingAppendCheck_=()=>{this.fixesBadSeeks_()&&(this.consecutiveUpdates=0,this.lastRecordedTime=this.tech_.currentTime(),d("off"))},this.clearSeekingAppendCheck_=()=>d("off"),this.watchForBadSeeking_=()=>{this.clearSeekingAppendCheck_(),d("on")},this.tech_.on("seeked",this.clearSeekingAppendCheck_),this.tech_.on("seeking",this.watchForBadSeeking_),this.tech_.on("waiting",n),this.tech_.on(f2,r),this.tech_.on("canplay",i),this.tech_.one("play",t),this.dispose=()=>{this.clearSeekingAppendCheck_(),this.logger_("dispose"),this.tech_.off("waiting",n),this.tech_.off(f2,r),this.tech_.off("canplay",i),this.tech_.off("play",t),this.tech_.off("seeking",this.watchForBadSeeking_),this.tech_.off("seeked",this.clearSeekingAppendCheck_),u.forEach(f=>{o[`${f}SegmentLoader_`].off("appendsdone",c[f].updateend),o[`${f}SegmentLoader_`].off("playlistupdate",c[f].reset),this.tech_.off(["seeked","seeking"],c[f].reset)}),this.checkCurrentTimeTimeout_&&de.clearTimeout(this.checkCurrentTimeTimeout_),this.resetTimeUpdate_()}}monitorCurrentTime_(){this.checkCurrentTime_(),this.checkCurrentTimeTimeout_&&de.clearTimeout(this.checkCurrentTimeTimeout_),this.checkCurrentTimeTimeout_=de.setTimeout(this.monitorCurrentTime_.bind(this),250)}resetSegmentDownloads_(e){const t=this.playlistController_[`${e}SegmentLoader_`];this[`${e}StalledDownloads_`]>0&&this.logger_(`resetting possible stalled download count for ${e} loader`),this[`${e}StalledDownloads_`]=0,this[`${e}Buffered_`]=t.buffered_()}checkSegmentDownloads_(e){const t=this.playlistController_,i=t[`${e}SegmentLoader_`],n=i.buffered_(),r=oB(this[`${e}Buffered_`],n);if(this[`${e}Buffered_`]=n,r){const o={bufferedRanges:n};t.trigger({type:"bufferedrangeschanged",metadata:o}),this.resetSegmentDownloads_(e);return}this[`${e}StalledDownloads_`]++,this.logger_(`found #${this[`${e}StalledDownloads_`]} ${e} appends that did not increase buffer (possible stalled download)`,{playlistId:i.playlist_&&i.playlist_.id,buffered:Xl(n)}),!(this[`${e}StalledDownloads_`]<10)&&(this.logger_(`${e} loader stalled download exclusion`),this.resetSegmentDownloads_(e),this.tech_.trigger({type:"usage",name:`vhs-${e}-download-exclusion`}),e!=="subtitle"&&t.excludePlaylist({error:{message:`Excessive ${e} segment downloading detected.`},playlistExclusionDuration:1/0}))}checkCurrentTime_(){if(this.tech_.paused()||this.tech_.seeking())return;const e=this.tech_.currentTime(),t=this.tech_.buffered();if(this.lastRecordedTime===e&&(!t.length||e+fa>=t.end(t.length-1)))return this.techWaiting_();if(this.consecutiveUpdates>=5&&e===this.lastRecordedTime)this.consecutiveUpdates++,this.waiting_();else if(e===this.lastRecordedTime)this.consecutiveUpdates++;else{this.playedRanges_.push(Zs([this.lastRecordedTime,e]));const i={playedRanges:this.playedRanges_};this.playlistController_.trigger({type:"playedrangeschanged",metadata:i}),this.consecutiveUpdates=0,this.lastRecordedTime=e}}resetTimeUpdate_(){this.consecutiveUpdates=0}fixesBadSeeks_(){if(!this.tech_.seeking())return!1;const t=this.seekable(),i=this.tech_.currentTime(),n=this.afterSeekableWindow_(t,i,this.media(),this.allowSeeksWithinUnsafeLiveWindow);let r;if(n&&(r=t.end(t.length-1)),this.beforeSeekableWindow_(t,i)){const b=t.start(0);r=b+(b===t.end(0)?0:fa)}if(typeof r<"u")return this.logger_(`Trying to seek outside of seekable at time ${i} with seekable range ${bk(t)}. Seeking to ${r}.`),this.tech_.setCurrentTime(r),!0;const o=this.playlistController_.sourceUpdater_,u=this.tech_.buffered(),c=o.audioBuffer?o.audioBuffered():null,d=o.videoBuffer?o.videoBuffered():null,f=this.media(),p=f.partTargetDuration?f.partTargetDuration:(f.targetDuration-ha)*2,g=[c,d];for(let b=0;b ${i.end(0)}]. Attempting to resume playback by seeking to the current time.`),this.tech_.trigger({type:"usage",name:"vhs-unknown-waiting"});return}}techWaiting_(){const e=this.seekable(),t=this.tech_.currentTime();if(this.tech_.seeking())return!0;if(this.beforeSeekableWindow_(e,t)){const u=e.end(e.length-1);return this.logger_(`Fell out of live window at time ${t}. Seeking to live point (seekable end) ${u}`),this.resetTimeUpdate_(),this.tech_.setCurrentTime(u),this.tech_.trigger({type:"usage",name:"vhs-live-resync"}),!0}const i=this.tech_.vhs.playlistController_.sourceUpdater_,n=this.tech_.buffered();if(this.videoUnderflow_({audioBuffered:i.audioBuffered(),videoBuffered:i.videoBuffered(),currentTime:t}))return this.resetTimeUpdate_(),this.tech_.setCurrentTime(t),this.tech_.trigger({type:"usage",name:"vhs-video-underflow"}),!0;const o=mm(n,t);return o.length>0?(this.logger_(`Stopped at ${t} and seeking to ${o.start(0)}`),this.resetTimeUpdate_(),this.skipTheGap_(t),!0):!1}afterSeekableWindow_(e,t,i,n=!1){if(!e.length)return!1;let r=e.end(e.length-1)+fa;const o=!i.endList,u=typeof i.partTargetDuration=="number";return o&&(u||n)&&(r=e.end(e.length-1)+i.targetDuration*3),t>r}beforeSeekableWindow_(e,t){return!!(e.length&&e.start(0)>0&&t2)return{start:r,end:o}}return null}}const S8={errorInterval:30,getSource(s){const t=this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource();return s(t)}},dD=function(s,e){let t=0,i=0;const n=Oi(S8,e);s.ready(()=>{s.trigger({type:"usage",name:"vhs-error-reload-initialized"})});const r=function(){i&&s.currentTime(i)},o=function(f){f!=null&&(i=s.duration()!==1/0&&s.currentTime()||0,s.one("loadedmetadata",r),s.src(f),s.trigger({type:"usage",name:"vhs-error-reload"}),s.play())},u=function(){if(Date.now()-t{Object.defineProperty(fs,s,{get(){return Le.log.warn(`using Vhs.${s} is UNSAFE be sure you know what you are doing`),Xs[s]},set(e){if(Le.log.warn(`using Vhs.${s} is UNSAFE be sure you know what you are doing`),typeof e!="number"||e<0){Le.log.warn(`value of Vhs.${s} must be greater than or equal to 0`);return}Xs[s]=e}})});const fD="videojs-vhs",mD=function(s,e){const t=e.media();let i=-1;for(let n=0;n{s.addQualityLevel(t)}),mD(s,e.playlists)};fs.canPlaySource=function(){return Le.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};const L8=(s,e,t)=>{if(!s)return s;let i={};e&&e.attributes&&e.attributes.CODECS&&(i=_h(oa(e.attributes.CODECS))),t&&t.attributes&&t.attributes.CODECS&&(i.audio=t.attributes.CODECS);const n=Sc(i.video),r=Sc(i.audio),o={};for(const u in s)o[u]={},r&&(o[u].audioContentType=r),n&&(o[u].videoContentType=n),e.contentProtection&&e.contentProtection[u]&&e.contentProtection[u].pssh&&(o[u].pssh=e.contentProtection[u].pssh),typeof s[u]=="string"&&(o[u].url=s[u]);return Oi(s,o)},R8=(s,e)=>s.reduce((t,i)=>{if(!i.contentProtection)return t;const n=e.reduce((r,o)=>{const u=i.contentProtection[o];return u&&u.pssh&&(r[o]={pssh:u.pssh}),r},{});return Object.keys(n).length&&t.push(n),t},[]),I8=({player:s,sourceKeySystems:e,audioMedia:t,mainPlaylists:i})=>{if(!s.eme.initializeMediaKeys)return Promise.resolve();const n=t?i.concat([t]):i,r=R8(n,Object.keys(e)),o=[],u=[];return r.forEach(c=>{u.push(new Promise((d,f)=>{s.tech_.one("keysessioncreated",d)})),o.push(new Promise((d,f)=>{s.eme.initializeMediaKeys({keySystems:c},p=>{if(p){f(p);return}d()})}))}),Promise.race([Promise.all(o),Promise.race(u)])},N8=({player:s,sourceKeySystems:e,media:t,audioMedia:i})=>{const n=L8(e,t,i);return n?(s.currentSource().keySystems=n,n&&!s.eme?(Le.log.warn("DRM encrypted source cannot be decrypted without a DRM plugin"),!1):!0):!1},pD=()=>{if(!de.localStorage)return null;const s=de.localStorage.getItem(fD);if(!s)return null;try{return JSON.parse(s)}catch{return null}},O8=s=>{if(!de.localStorage)return!1;let e=pD();e=e?Oi(e,s):s;try{de.localStorage.setItem(fD,JSON.stringify(e))}catch{return!1}return e},M8=s=>s.toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,")===0?JSON.parse(s.substring(s.indexOf(",")+1)):s,gD=(s,e)=>{s._requestCallbackSet||(s._requestCallbackSet=new Set),s._requestCallbackSet.add(e)},yD=(s,e)=>{s._responseCallbackSet||(s._responseCallbackSet=new Set),s._responseCallbackSet.add(e)},vD=(s,e)=>{s._requestCallbackSet&&(s._requestCallbackSet.delete(e),s._requestCallbackSet.size||delete s._requestCallbackSet)},xD=(s,e)=>{s._responseCallbackSet&&(s._responseCallbackSet.delete(e),s._responseCallbackSet.size||delete s._responseCallbackSet)};fs.supportsNativeHls=(function(){if(!at||!at.createElement)return!1;const s=at.createElement("video");return Le.getTech("Html5").isSupported()?["application/vnd.apple.mpegurl","audio/mpegurl","audio/x-mpegurl","application/x-mpegurl","video/x-mpegurl","video/mpegurl","application/mpegurl"].some(function(t){return/maybe|probably/i.test(s.canPlayType(t))}):!1})();fs.supportsNativeDash=(function(){return!at||!at.createElement||!Le.getTech("Html5").isSupported()?!1:/maybe|probably/i.test(at.createElement("video").canPlayType("application/dash+xml"))})();fs.supportsTypeNatively=s=>s==="hls"?fs.supportsNativeHls:s==="dash"?fs.supportsNativeDash:!1;fs.isSupported=function(){return Le.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};fs.xhr.onRequest=function(s){gD(fs.xhr,s)};fs.xhr.onResponse=function(s){yD(fs.xhr,s)};fs.xhr.offRequest=function(s){vD(fs.xhr,s)};fs.xhr.offResponse=function(s){xD(fs.xhr,s)};const P8=Le.getComponent("Component");class bD extends P8{constructor(e,t,i){if(super(t,i.vhs),typeof i.initialBandwidth=="number"&&(this.options_.bandwidth=i.initialBandwidth),this.logger_=Er("VhsHandler"),t.options_&&t.options_.playerId){const n=Le.getPlayer(t.options_.playerId);this.player_=n}if(this.tech_=t,this.source_=e,this.stats={},this.ignoreNextSeekingEvent_=!1,this.setOptions_(),this.options_.overrideNative&&t.overrideNativeAudioTracks&&t.overrideNativeVideoTracks)t.overrideNativeAudioTracks(!0),t.overrideNativeVideoTracks(!0);else if(this.options_.overrideNative&&(t.featuresNativeVideoTracks||t.featuresNativeAudioTracks))throw new Error("Overriding native VHS requires emulated tracks. See https://git.io/vMpjB");this.on(at,["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],n=>{const r=at.fullscreenElement||at.webkitFullscreenElement||at.mozFullScreenElement||at.msFullscreenElement;r&&r.contains(this.tech_.el())?this.playlistController_.fastQualityChange_():this.playlistController_.checkABR_()}),this.on(this.tech_,"seeking",function(){if(this.ignoreNextSeekingEvent_){this.ignoreNextSeekingEvent_=!1;return}this.setCurrentTime(this.tech_.currentTime())}),this.on(this.tech_,"error",function(){this.tech_.error()&&this.playlistController_&&this.playlistController_.pauseLoading()}),this.on(this.tech_,"play",this.play)}setOptions_(e={}){if(this.options_=Oi(this.options_,e),this.options_.withCredentials=this.options_.withCredentials||!1,this.options_.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions!==!1,this.options_.useDevicePixelRatio=this.options_.useDevicePixelRatio||!1,this.options_.usePlayerObjectFit=this.options_.usePlayerObjectFit||!1,this.options_.useBandwidthFromLocalStorage=typeof this.source_.useBandwidthFromLocalStorage<"u"?this.source_.useBandwidthFromLocalStorage:this.options_.useBandwidthFromLocalStorage||!1,this.options_.useForcedSubtitles=this.options_.useForcedSubtitles||!1,this.options_.useNetworkInformationApi=typeof this.options_.useNetworkInformationApi<"u"?this.options_.useNetworkInformationApi:!0,this.options_.useDtsForTimestampOffset=this.options_.useDtsForTimestampOffset||!1,this.options_.customTagParsers=this.options_.customTagParsers||[],this.options_.customTagMappers=this.options_.customTagMappers||[],this.options_.cacheEncryptionKeys=this.options_.cacheEncryptionKeys||!1,this.options_.llhls=this.options_.llhls!==!1,this.options_.bufferBasedABR=this.options_.bufferBasedABR||!1,typeof this.options_.playlistExclusionDuration!="number"&&(this.options_.playlistExclusionDuration=60),typeof this.options_.bandwidth!="number"&&this.options_.useBandwidthFromLocalStorage){const i=pD();i&&i.bandwidth&&(this.options_.bandwidth=i.bandwidth,this.tech_.trigger({type:"usage",name:"vhs-bandwidth-from-local-storage"})),i&&i.throughput&&(this.options_.throughput=i.throughput,this.tech_.trigger({type:"usage",name:"vhs-throughput-from-local-storage"}))}typeof this.options_.bandwidth!="number"&&(this.options_.bandwidth=Xs.INITIAL_BANDWIDTH),this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===Xs.INITIAL_BANDWIDTH,["withCredentials","useDevicePixelRatio","usePlayerObjectFit","customPixelRatio","limitRenditionByPlayerDimensions","bandwidth","customTagParsers","customTagMappers","cacheEncryptionKeys","playlistSelector","initialPlaylistSelector","bufferBasedABR","liveRangeSafeTimeDelta","llhls","useForcedSubtitles","useNetworkInformationApi","useDtsForTimestampOffset","exactManifestTimings","leastPixelDiffSelector"].forEach(i=>{typeof this.source_[i]<"u"&&(this.options_[i]=this.source_[i])}),this.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions,this.useDevicePixelRatio=this.options_.useDevicePixelRatio,this.usePlayerObjectFit=this.options_.usePlayerObjectFit;const t=this.options_.customPixelRatio;typeof t=="number"&&t>=0&&(this.customPixelRatio=t)}setOptions(e={}){this.setOptions_(e)}src(e,t){if(!e)return;this.setOptions_(),this.options_.src=M8(this.source_.src),this.options_.tech=this.tech_,this.options_.externVhs=fs,this.options_.sourceType=$A(t),this.options_.seekTo=r=>{this.tech_.setCurrentTime(r)},this.options_.player_=this.player_,this.playlistController_=new v8(this.options_);const i=Oi({liveRangeSafeTimeDelta:fa},this.options_,{seekable:()=>this.seekable(),media:()=>this.playlistController_.media(),playlistController:this.playlistController_});this.playbackWatcher_=new _8(i),this.attachStreamingEventListeners_(),this.playlistController_.on("error",()=>{const r=Le.players[this.tech_.options_.playerId];let o=this.playlistController_.error;typeof o=="object"&&!o.code?o.code=3:typeof o=="string"&&(o={message:o,code:3}),r.error(o)});const n=this.options_.bufferBasedABR?fs.movingAverageBandwidthSelector(.55):fs.STANDARD_PLAYLIST_SELECTOR;this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):n.bind(this),this.playlistController_.selectInitialPlaylist=fs.INITIAL_PLAYLIST_SELECTOR.bind(this),this.playlists=this.playlistController_.mainPlaylistLoader_,this.mediaSource=this.playlistController_.mediaSource,Object.defineProperties(this,{selectPlaylist:{get(){return this.playlistController_.selectPlaylist},set(r){this.playlistController_.selectPlaylist=r.bind(this)}},throughput:{get(){return this.playlistController_.mainSegmentLoader_.throughput.rate},set(r){this.playlistController_.mainSegmentLoader_.throughput.rate=r,this.playlistController_.mainSegmentLoader_.throughput.count=1}},bandwidth:{get(){let r=this.playlistController_.mainSegmentLoader_.bandwidth;const o=de.navigator.connection||de.navigator.mozConnection||de.navigator.webkitConnection,u=1e7;if(this.options_.useNetworkInformationApi&&o){const c=o.downlink*1e3*1e3;c>=u&&r>=u?r=Math.max(r,c):r=c}return r},set(r){this.playlistController_.mainSegmentLoader_.bandwidth=r,this.playlistController_.mainSegmentLoader_.throughput={rate:0,count:0}}},systemBandwidth:{get(){const r=1/(this.bandwidth||1);let o;return this.throughput>0?o=1/this.throughput:o=0,Math.floor(1/(r+o))},set(){Le.log.error('The "systemBandwidth" property is read-only')}}}),this.options_.bandwidth&&(this.bandwidth=this.options_.bandwidth),this.options_.throughput&&(this.throughput=this.options_.throughput),Object.defineProperties(this.stats,{bandwidth:{get:()=>this.bandwidth||0,enumerable:!0},mediaRequests:{get:()=>this.playlistController_.mediaRequests_()||0,enumerable:!0},mediaRequestsAborted:{get:()=>this.playlistController_.mediaRequestsAborted_()||0,enumerable:!0},mediaRequestsTimedout:{get:()=>this.playlistController_.mediaRequestsTimedout_()||0,enumerable:!0},mediaRequestsErrored:{get:()=>this.playlistController_.mediaRequestsErrored_()||0,enumerable:!0},mediaTransferDuration:{get:()=>this.playlistController_.mediaTransferDuration_()||0,enumerable:!0},mediaBytesTransferred:{get:()=>this.playlistController_.mediaBytesTransferred_()||0,enumerable:!0},mediaSecondsLoaded:{get:()=>this.playlistController_.mediaSecondsLoaded_()||0,enumerable:!0},mediaAppends:{get:()=>this.playlistController_.mediaAppends_()||0,enumerable:!0},mainAppendsToLoadedData:{get:()=>this.playlistController_.mainAppendsToLoadedData_()||0,enumerable:!0},audioAppendsToLoadedData:{get:()=>this.playlistController_.audioAppendsToLoadedData_()||0,enumerable:!0},appendsToLoadedData:{get:()=>this.playlistController_.appendsToLoadedData_()||0,enumerable:!0},timeToLoadedData:{get:()=>this.playlistController_.timeToLoadedData_()||0,enumerable:!0},buffered:{get:()=>Xl(this.tech_.buffered()),enumerable:!0},currentTime:{get:()=>this.tech_.currentTime(),enumerable:!0},currentSource:{get:()=>this.tech_.currentSource_,enumerable:!0},currentTech:{get:()=>this.tech_.name_,enumerable:!0},duration:{get:()=>this.tech_.duration(),enumerable:!0},main:{get:()=>this.playlists.main,enumerable:!0},playerDimensions:{get:()=>this.tech_.currentDimensions(),enumerable:!0},seekable:{get:()=>Xl(this.tech_.seekable()),enumerable:!0},timestamp:{get:()=>Date.now(),enumerable:!0},videoPlaybackQuality:{get:()=>this.tech_.getVideoPlaybackQuality(),enumerable:!0}}),this.tech_.one("canplay",this.playlistController_.setupFirstPlay.bind(this.playlistController_)),this.tech_.on("bandwidthupdate",()=>{this.options_.useBandwidthFromLocalStorage&&O8({bandwidth:this.bandwidth,throughput:Math.round(this.throughput)})}),this.playlistController_.on("selectedinitialmedia",()=>{T8(this)}),this.playlistController_.sourceUpdater_.on("createdsourcebuffers",()=>{this.setupEme_()}),this.on(this.playlistController_,"progress",function(){this.tech_.trigger("progress")}),this.on(this.playlistController_,"firstplay",function(){this.ignoreNextSeekingEvent_=!0}),this.setupQualityLevels_(),this.tech_.el()&&(this.mediaSourceUrl_=de.URL.createObjectURL(this.playlistController_.mediaSource),(Le.browser.IS_ANY_SAFARI||Le.browser.IS_IOS)&&this.options_.overrideNative&&this.options_.sourceType==="hls"&&typeof this.tech_.addSourceElement=="function"?(this.tech_.addSourceElement(this.mediaSourceUrl_),this.tech_.addSourceElement(this.source_.src)):this.tech_.src(this.mediaSourceUrl_))}createKeySessions_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;this.logger_("waiting for EME key session creation"),I8({player:this.player_,sourceKeySystems:this.source_.keySystems,audioMedia:e&&e.media(),mainPlaylists:this.playlists.main.playlists}).then(()=>{this.logger_("created EME key session"),this.playlistController_.sourceUpdater_.initializedEme()}).catch(t=>{this.logger_("error while creating EME key session",t),this.player_.error({message:"Failed to initialize media keys for EME",code:3})})}handleWaitingForKey_(){this.logger_("waitingforkey fired, attempting to create any new key sessions"),this.createKeySessions_()}setupEme_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader,t=N8({player:this.player_,sourceKeySystems:this.source_.keySystems,media:this.playlists.media(),audioMedia:e&&e.media()});if(this.player_.tech_.on("keystatuschange",i=>{this.playlistController_.updatePlaylistByKeyStatus(i.keyId,i.status)}),this.handleWaitingForKey_=this.handleWaitingForKey_.bind(this),this.player_.tech_.on("waitingforkey",this.handleWaitingForKey_),!t){this.playlistController_.sourceUpdater_.initializedEme();return}this.createKeySessions_()}setupQualityLevels_(){const e=Le.players[this.tech_.options_.playerId];!e||!e.qualityLevels||this.qualityLevels_||(this.qualityLevels_=e.qualityLevels(),this.playlistController_.on("selectedinitialmedia",()=>{D8(this.qualityLevels_,this)}),this.playlists.on("mediachange",()=>{mD(this.qualityLevels_,this.playlists)}))}static version(){return{"@videojs/http-streaming":hD,"mux.js":w8,"mpd-parser":A8,"m3u8-parser":C8,"aes-decrypter":k8}}version(){return this.constructor.version()}canChangeType(){return oD.canChangeType()}play(){this.playlistController_.play()}setCurrentTime(e){this.playlistController_.setCurrentTime(e)}duration(){return this.playlistController_.duration()}seekable(){return this.playlistController_.seekable()}dispose(){this.playbackWatcher_&&this.playbackWatcher_.dispose(),this.playlistController_&&this.playlistController_.dispose(),this.qualityLevels_&&this.qualityLevels_.dispose(),this.tech_&&this.tech_.vhs&&delete this.tech_.vhs,this.mediaSourceUrl_&&de.URL.revokeObjectURL&&(de.URL.revokeObjectURL(this.mediaSourceUrl_),this.mediaSourceUrl_=null),this.tech_&&this.tech_.off("waitingforkey",this.handleWaitingForKey_),super.dispose()}convertToProgramTime(e,t){return jB({playlist:this.playlistController_.media(),time:e,callback:t})}seekToProgramTime(e,t,i=!0,n=2){return Gk({programTime:e,playlist:this.playlistController_.media(),retryCount:n,pauseAfterSeek:i,seekTo:this.options_.seekTo,tech:this.options_.tech,callback:t})}setupXhrHooks_(){this.xhr.onRequest=e=>{gD(this.xhr,e)},this.xhr.onResponse=e=>{yD(this.xhr,e)},this.xhr.offRequest=e=>{vD(this.xhr,e)},this.xhr.offResponse=e=>{xD(this.xhr,e)},this.player_.trigger("xhr-hooks-ready")}attachStreamingEventListeners_(){const e=["seekablerangeschanged","bufferedrangeschanged","contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"],t=["gapjumped","playedrangeschanged"];e.forEach(i=>{this.playlistController_.on(i,n=>{this.player_.trigger(Cs({},n))})}),t.forEach(i=>{this.playbackWatcher_.on(i,n=>{this.player_.trigger(Cs({},n))})})}}const xp={name:"videojs-http-streaming",VERSION:hD,canHandleSource(s,e={}){const t=Oi(Le.options,e);return!t.vhs.experimentalUseMMS&&!lh("avc1.4d400d,mp4a.40.2",!1)?!1:xp.canPlayType(s.type,t)},handleSource(s,e,t={}){const i=Oi(Le.options,t);return e.vhs=new bD(s,e,i),e.vhs.xhr=Uk(),e.vhs.setupXhrHooks_(),e.vhs.src(s.src,s.type),e.vhs},canPlayType(s,e){const t=$A(s);if(!t)return"";const i=xp.getOverrideNative(e);return!fs.supportsTypeNatively(t)||i?"maybe":""},getOverrideNative(s={}){const{vhs:e={}}=s,t=!(Le.browser.IS_ANY_SAFARI||Le.browser.IS_IOS),{overrideNative:i=t}=e;return i}},B8=()=>lh("avc1.4d400d,mp4a.40.2",!0);B8()&&Le.getTech("Html5").registerSourceHandler(xp,0);Le.VhsHandler=bD;Le.VhsSourceHandler=xp;Le.Vhs=fs;Le.use||Le.registerComponent("Vhs",fs);Le.options.vhs=Le.options.vhs||{};(!Le.getPlugin||!Le.getPlugin("reloadSourceOnError"))&&Le.registerPlugin("reloadSourceOnError",E8);const F8="",Vl=s=>{const e=s.startsWith("/")?s:`/${s}`;return`${F8}${e}`};async function U8(s,e){return fetch(Vl(s),{...e,credentials:"include"})}const bt=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},j8=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=$8},$8=Number.MAX_SAFE_INTEGER||9007199254740991;let It=(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})({}),De=(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.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",s.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",s.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",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.ASSET_LIST_LOAD_ERROR="assetListLoadError",s.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",s.ASSET_LIST_PARSING_ERROR="assetListParsingError",s.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",s.INTERNAL_EXCEPTION="internalException",s.INTERNAL_ABORTED="aborted",s.ATTACH_MEDIA_ERROR="attachMediaError",s.UNKNOWN="unknown",s})({}),$=(function(s){return s.MEDIA_ATTACHING="hlsMediaAttaching",s.MEDIA_ATTACHED="hlsMediaAttached",s.MEDIA_DETACHING="hlsMediaDetaching",s.MEDIA_DETACHED="hlsMediaDetached",s.MEDIA_ENDED="hlsMediaEnded",s.STALL_RESOLVED="hlsStallResolved",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.BUFFERED_TO_END="hlsBufferedToEnd",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.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",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_TRACK_UPDATED="hlsSubtitleTrackUpdated",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.ASSET_LIST_LOADING="hlsAssetListLoading",s.ASSET_LIST_LOADED="hlsAssetListLoaded",s.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",s.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",s.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",s.INTERSTITIAL_STARTED="hlsInterstitialStarted",s.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",s.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",s.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",s.INTERSTITIAL_ENDED="hlsInterstitialEnded",s.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",s.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",s.EVENT_CUE_ENTER="hlsEventCueEnter",s})({});var yi={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},At={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class qu{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 H8{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 qu(e),this.fast_=new qu(t),this.defaultTTFB_=n,this.ttfb_=new qu(e)}update(e,t){const{slow_:i,fast_:n,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new qu(e,i.getEstimate(),i.getTotalWeight())),n.halfLife!==t&&(this.fast_=new qu(t,n.getEstimate(),n.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new qu(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_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function V8(s,e,t){return(e=z8(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function zi(){return zi=Object.assign?Object.assign.bind():function(s){for(var e=1;e`):Jo}function p2(s,e,t){return e[s]?e[s].bind(e):K8(s,t)}const vx=yx();function Y8(s,e,t){const i=yx();if(typeof console=="object"&&s===!0||typeof s=="object"){const n=["debug","log","info","warn","error"];n.forEach(r=>{i[r]=p2(r,s,t)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return yx()}n.forEach(r=>{vx[r]=p2(r,s)})}else zi(vx,i);return i}const Ui=vx;function ul(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function W8(s){return typeof self<"u"&&s===self.ManagedMediaSource}function TD(s,e){const t=Object.keys(s),i=Object.keys(e),n=t.length,r=i.length;return!n||!r||n===r&&!t.some(o=>i.indexOf(o)===-1)}function cr(s,e=!1){if(typeof TextDecoder<"u"){const d=new TextDecoder("utf-8").decode(s);if(e){const f=d.indexOf("\0");return f!==-1?d.substring(0,f):d}return d.replace(/\0/g,"")}const t=s.length;let i,n,r,o="",u=0;for(;u>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(i);break;case 12:case 13:n=s[u++],o+=String.fromCharCode((i&31)<<6|n&63);break;case 14:n=s[u++],r=s[u++],o+=String.fromCharCode((i&15)<<12|(n&63)<<6|(r&63)<<0);break}}return o}function an(s){let e="";for(let t=0;t1||n===1&&(t=this.levelkeys[i[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!bt(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return As(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var i;const n=t[e];n&&!((i=this._decryptdata)!=null&&i.keyId)&&(this._decryptdata=n.getDecryptData(this.sn,t))}}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,c=u[e];if(!c){u[e]={startPTS:t,endPTS:i,startDTS:n,endDTS:r,partial:o};return}c.startPTS=Math.min(c.startPTS,t),c.endPTS=Math.max(c.endPTS,i),c.startDTS=Math.min(c.startDTS,n),c.endDTS=Math.max(c.endDTS,r)}}class Z8 extends SD{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.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)}}function ED(s,e){const t=Object.getPrototypeOf(s);if(t){const i=Object.getOwnPropertyDescriptor(t,e);return i||ED(t,e)}}function J8(s,e){const t=ED(s,e);t&&(t.enumerable=!0,Object.defineProperty(s,e,t))}const y2=Math.pow(2,32)-1,e6=[].push,wD={video:1,audio:2,id3:3,text:4};function js(s){return String.fromCharCode.apply(null,s)}function AD(s,e){const t=s[e]<<8|s[e+1];return t<0?65536+t:t}function Qt(s,e){const t=CD(s,e);return t<0?4294967296+t:t}function v2(s,e){let t=Qt(s,e);return t*=Math.pow(2,32),t+=Qt(s,e+4),t}function CD(s,e){return s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3]}function t6(s){const e=s.byteLength;for(let t=0;t8&&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 mi(s,e){const t=[];if(!e.length)return t;const i=s.byteLength;for(let n=0;n1?n+r:i;if(o===e[0])if(e.length===1)t.push(s.subarray(n+8,u));else{const c=mi(s.subarray(n+8,u),e.slice(1));c.length&&e6.apply(t,c)}n=u}return t}function i6(s){const e=[],t=s[0];let i=8;const n=Qt(s,i);i+=4;let r=0,o=0;t===0?(r=Qt(s,i),o=Qt(s,i+4),i+=8):(r=v2(s,i),o=v2(s,i+8),i+=16),i+=2;let u=s.length+o;const c=AD(s,i);i+=2;for(let d=0;d>>31===1)return Ui.warn("SIDX has hierarchical references (not supported)"),null;const b=Qt(s,f);f+=4,e.push({referenceSize:g,subsegmentDuration:b,info:{duration:b/n,start:u,end:u+g-1}}),u+=g,f+=4,i=f}return{earliestPresentationTime:r,timescale:n,version:t,referencesCount:c,references:e}}function kD(s){const e=[],t=mi(s,["moov","trak"]);for(let n=0;n{const r=Qt(n,4),o=e[r];o&&(o.default={duration:Qt(n,12),flags:Qt(n,20)})}),e}function s6(s){const e=s.subarray(8),t=e.subarray(86),i=js(e.subarray(4,8));let n=i,r;const o=i==="enca"||i==="encv";if(o){const d=mi(e,[i])[0].subarray(i==="enca"?28:78);mi(d,["sinf"]).forEach(p=>{const g=mi(p,["schm"])[0];if(g){const v=js(g.subarray(4,8));if(v==="cbcs"||v==="cenc"){const b=mi(p,["frma"])[0];b&&(n=js(b))}}})}const u=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const c=mi(t,["avcC"])[0];c&&c.length>3&&(n+="."+vm(c[1])+vm(c[2])+vm(c[3]),r=ym(u==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=mi(e,[i])[0],d=mi(c.subarray(28),["esds"])[0];if(d&&d.length>7){let f=4;if(d[f++]!==3)break;f=iv(d,f),f+=2;const p=d[f++];if(p&128&&(f+=2),p&64&&(f+=d[f++]),d[f++]!==4)break;f=iv(d,f);const g=d[f++];if(g===64)n+="."+vm(g);else break;if(f+=12,d[f++]!==5)break;f=iv(d,f);const v=d[f++];let b=(v&248)>>3;b===31&&(b+=1+((v&7)<<3)+((d[f]&224)>>5)),n+="."+b}break}case"hvc1":case"hev1":{const c=mi(t,["hvcC"])[0];if(c&&c.length>12){const d=c[1],f=["","A","B","C"][d>>6],p=d&31,g=Qt(c,2),v=(d&32)>>5?"H":"L",b=c[12],_=c.subarray(6,12);n+="."+f+p,n+="."+n6(g).toString(16).toUpperCase(),n+="."+v+b;let S="";for(let D=_.length;D--;){const R=_[D];(R||S)&&(S="."+R.toString(16).toUpperCase()+S)}n+=S}r=ym(u=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{n=ym(n,t)||n;break}case"vp09":{const c=mi(t,["vpcC"])[0];if(c&&c.length>6){const d=c[4],f=c[5],p=c[6]>>4&15;n+="."+aa(d)+"."+aa(f)+"."+aa(p)}break}case"av01":{const c=mi(t,["av1C"])[0];if(c&&c.length>2){const d=c[1]>>>5,f=c[1]&31,p=c[2]>>>7?"H":"M",g=(c[2]&64)>>6,v=(c[2]&32)>>5,b=d===2&&g?v?12:10:g?10:8,_=(c[2]&16)>>4,S=(c[2]&8)>>3,D=(c[2]&4)>>2,R=c[2]&3;n+="."+d+"."+aa(f)+p+"."+aa(b)+"."+_+"."+S+D+R+"."+aa(1)+"."+aa(1)+"."+aa(1)+"."+0,r=ym("dav1",t)}break}}return{codec:n,encrypted:o,supplemental:r}}function ym(s,e){const t=mi(e,["dvvC"]),i=t.length?t[0]:mi(e,["dvcC"])[0];if(i){const n=i[2]>>1&127,r=i[2]<<5&32|i[3]>>3&31;return s+"."+aa(n)+"."+aa(r)}}function n6(s){let e=0;for(let t=0;t<32;t++)e|=(s>>t&1)<<31-t;return e>>>0}function iv(s,e){const t=e+5;for(;s[e++]&128&&e{const r=i.subarray(8,24);r.some(o=>o!==0)||(Ui.log(`[eme] Patching keyId in 'enc${n?"a":"v"}>sinf>>tenc' box: ${an(r)} -> ${an(t)}`),i.set(t,8))})}function a6(s){const e=[];return DD(s,t=>e.push(t.subarray(8,24))),e}function DD(s,e){mi(s,["moov","trak"]).forEach(i=>{const n=mi(i,["mdia","minf","stbl","stsd"])[0];if(!n)return;const r=n.subarray(8);let o=mi(r,["enca"]);const u=o.length>0;u||(o=mi(r,["encv"])),o.forEach(c=>{const d=u?c.subarray(28):c.subarray(78);mi(d,["sinf"]).forEach(p=>{const g=LD(p);g&&e(g,u)})})})}function LD(s){const e=mi(s,["schm"])[0];if(e){const t=js(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const i=mi(s,["schi","tenc"])[0];if(i)return i}}}function o6(s,e,t){const i={},n=mi(s,["moof","traf"]);for(let r=0;ri[r].duration)){let r=1/0,o=0;const u=mi(s,["sidx"]);for(let c=0;cp+g.info.duration||0,0);o=Math.max(o,f+d.earliestPresentationTime/d.timescale)}}o&&bt(o)&&Object.keys(i).forEach(c=>{i[c].duration||(i[c].duration=o*i[c].timescale-i[c].start)})}return i}function l6(s){const e={valid:null,remainder:null},t=mi(s,["moof"]);if(t.length<2)return e.remainder=s,e;const i=t[t.length-1];return e.valid=s.slice(0,i.byteOffset-8),e.remainder=s.slice(i.byteOffset-8),e}function _r(s,e){const t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function x2(s,e){const t=[],i=e.samples,n=e.timescale,r=e.id;let o=!1;return mi(i,["moof"]).map(c=>{const d=c.byteOffset-8;mi(c,["traf"]).map(p=>{const g=mi(p,["tfdt"]).map(v=>{const b=v[0];let _=Qt(v,4);return b===1&&(_*=Math.pow(2,32),_+=Qt(v,8)),_/n})[0];return g!==void 0&&(s=g),mi(p,["tfhd"]).map(v=>{const b=Qt(v,4),_=Qt(v,0)&16777215,S=(_&1)!==0,D=(_&2)!==0,R=(_&8)!==0;let L=0;const P=(_&16)!==0;let U=0;const V=(_&32)!==0;let M=8;b===r&&(S&&(M+=8),D&&(M+=4),R&&(L=Qt(v,M),M+=4),P&&(U=Qt(v,M),M+=4),V&&(M+=4),e.type==="video"&&(o=cg(e.codec)),mi(p,["trun"]).map(G=>{const N=G[0],O=Qt(G,0)&16777215,K=(O&1)!==0;let Q=0;const W=(O&4)!==0,re=(O&256)!==0;let J=0;const Y=(O&512)!==0;let z=0;const Z=(O&1024)!==0,ie=(O&2048)!==0;let ce=0;const j=Qt(G,4);let ee=8;K&&(Q=Qt(G,ee),ee+=4),W&&(ee+=4);let he=Q+d;for(let Te=0;Te>1&63;return t===39||t===40}else return(e&31)===6}function Mb(s,e,t,i){const n=RD(s);let r=0;r+=e;let o=0,u=0,c=0;for(;r=n.length)break;c=n[r++],o+=c}while(c===255);u=0;do{if(r>=n.length)break;c=n[r++],u+=c}while(c===255);const d=n.length-r;let f=r;if(ud){Ui.error(`Malformed SEI payload. ${u} is too small, only ${d} bytes left to parse.`);break}if(o===4){if(n[f++]===181){const g=AD(n,f);if(f+=2,g===49){const v=Qt(n,f);if(f+=4,v===1195456820){const b=n[f++];if(b===3){const _=n[f++],S=31&_,D=64&_,R=D?2+S*3:0,L=new Uint8Array(R);if(D){L[0]=_;for(let P=1;P16){const p=[];for(let b=0;b<16;b++){const _=n[f++].toString(16);p.push(_.length==1?"0"+_:_),(b===3||b===5||b===7||b===9)&&p.push("-")}const g=u-16,v=new Uint8Array(g);for(let b=0;b>24&255,r[1]=i>>16&255,r[2]=i>>8&255,r[3]=i&255,r.set(s,4),n=0,i=8;n0?(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.byteLength>0&&new DataView(o.buffer).setUint32(0,t.byteLength,!1),d6([112,115,115,104],new Uint8Array([i,0,0,0]),s,r,n,o,t)}function f6(s){const e=[];if(s instanceof ArrayBuffer){const t=s.byteLength;let i=0;for(;i+32>>24;if(r!==0&&r!==1)return{offset:t,size:e};const o=s.buffer,u=an(new Uint8Array(o,t+12,16));let c=null,d=null,f=0;if(r===0)f=28;else{const g=s.getUint32(28);if(!g||i<32+g*16)return{offset:t,size:e};c=[];for(let v=0;v/\(Windows.+Firefox\//i.test(navigator.userAgent),Ic={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Pb(s,e){const t=Ic[e];return!!t&&!!t[s.slice(0,4)]}function Sh(s,e,t=!0){return!s.split(",").some(i=>!Bb(i,e,t))}function Bb(s,e,t=!0){var i;const n=ul(t);return(i=n?.isTypeSupported(Eh(s,e)))!=null?i:!1}function Eh(s,e){return`${e}/mp4;codecs=${s}`}function b2(s){if(s){const e=s.substring(0,4);return Ic.video[e]}return 2}function bp(s){const e=ID();return s.split(",").reduce((t,i)=>{const r=e&&cg(i)?9:Ic.video[i];return r?(r*2+t)/(t?3:2):(Ic.audio[i]+t)/(t?2:1)},0)}const sv={};function p6(s,e=!0){if(sv[s])return sv[s];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let n=0;np6(t.toLowerCase(),e))}function y6(s,e){const t=[];if(s){const i=s.split(",");for(let n=0;n4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(s)!==-1)&&(T2(s,"audio")||T2(s,"video")))return s;if(e){const t=e.split(",");if(t.length>1){if(s){for(let i=t.length;i--;)if(t[i].substring(0,4)===s.substring(0,4))return t[i]}return t[0]}}return e||s}function T2(s,e){return Pb(s,e)&&Bb(s,e)}function v6(s){const e=s.split(",");for(let t=0;t2&&i[0]==="avc1"&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}function x6(s){if(s.startsWith("av01.")){const e=s.split("."),t=["0","111","01","01","01","0"];for(let i=e.length;i>4&&i<10;i++)e[i]=t[i-4];return e.join(".")}return s}function _2(s){const e=ul(s)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function xx(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const b6={supported:!0,powerEfficient:!0,smooth:!0},T6={supported:!1,smooth:!1,powerEfficient:!1},ND={supported:!0,configurations:[],decodingInfoResults:[b6]};function OD(s,e){return{supported:!1,configurations:e,decodingInfoResults:[T6],error:s}}function _6(s,e,t,i,n,r){const o=s.videoCodec,u=s.audioCodec?s.audioGroups:null,c=r?.audioCodec,d=r?.channels,f=d?parseInt(d):c?1/0:2;let p=null;if(u!=null&&u.length)try{u.length===1&&u[0]?p=e.groups[u[0]].channels:p=u.reduce((g,v)=>{if(v){const b=e.groups[v];if(!b)throw new Error(`Audio track group ${v} not found`);Object.keys(b.channels).forEach(_=>{g[_]=(g[_]||0)+b.channels[_]})}return g},{2:0})}catch{return!0}return o!==void 0&&(o.split(",").some(g=>cg(g))||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))||!!p&&bt(f)&&Object.keys(p).some(g=>parseInt(g)>f)}function MD(s,e,t,i={}){const n=s.videoCodec;if(!n&&!s.audioCodec||!t)return Promise.resolve(ND);const r=[],o=S6(s),u=o.length,c=E6(s,e,u>0),d=c.length;for(let f=u||1*d||1;f--;){const p={type:"media-source"};if(u&&(p.video=o[f%u]),d){p.audio=c[f%d];const g=p.audio.bitrate;p.video&&g&&(p.video.bitrate-=g)}r.push(p)}if(n){const f=navigator.userAgent;if(n.split(",").some(p=>cg(p))&&ID())return Promise.resolve(OD(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${f})`),r))}return Promise.all(r.map(f=>{const p=A6(f);return i[p]||(i[p]=t.decodingInfo(f))})).then(f=>({supported:!f.some(p=>!p.supported),configurations:r,decodingInfoResults:f})).catch(f=>({supported:!1,configurations:r,decodingInfoResults:[],error:f}))}function S6(s){var e;const t=(e=s.videoCodec)==null?void 0:e.split(","),i=PD(s),n=s.width||640,r=s.height||480,o=s.frameRate||30,u=s.videoRange.toLowerCase();return t?t.map(c=>{const d={contentType:Eh(x6(c),"video"),width:n,height:r,bitrate:i,framerate:o};return u!=="sdr"&&(d.transferFunction=u),d}):[]}function E6(s,e,t){var i;const n=(i=s.audioCodec)==null?void 0:i.split(","),r=PD(s);return n&&s.audioGroups?s.audioGroups.reduce((o,u)=>{var c;const d=u?(c=e.groups[u])==null?void 0:c.tracks:null;return d?d.reduce((f,p)=>{if(p.groupId===u){const g=parseFloat(p.channels||"");n.forEach(v=>{const b={contentType:Eh(v,"audio"),bitrate:t?w6(v,r):r};g&&(b.channels=""+g),f.push(b)})}return f},o):o},[]):[]}function w6(s,e){if(e<=1)return 1;let t=128e3;return s==="ec-3"?t=768e3:s==="ac-3"&&(t=64e4),Math.min(e/2,t)}function PD(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function A6(s){let e="";const{audio:t,video:i}=s;if(i){const n=xx(i.contentType);e+=`${n}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(t){const n=xx(t.contentType);e+=`${i?"_":""}${n}_c${t.channels}`}return e}const bx=["NONE","TYPE-0","TYPE-1",null];function C6(s){return bx.indexOf(s)>-1}const _p=["SDR","PQ","HLG"];function k6(s){return!!s&&_p.indexOf(s)>-1}var Um={No:"",Yes:"YES",v2:"v2"};function S2(s){const{canSkipUntil:e,canSkipDateRanges:t,age:i}=s,n=i!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const i=(t=e.supplemental)==null?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return w2(this._audioGroups,e)}hasSubtitleGroup(e){return w2(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 w2(s,e){return!e||!s?!1:s.indexOf(e)!==-1}function D6(){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 L6(s,e){let t=!1,i=[];if(s&&(t=s!=="SDR",i=[s]),e){i=e.allowedVideoRanges||_p.slice(0);const n=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:n&&D6(),t||(i=["SDR"])}return{preferHDR:t,allowedVideoRanges:i}}const R6=s=>{const e=new WeakSet;return(t,i)=>{if(s&&(i=s(t,i)),typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i)}return i}},Qi=(s,e)=>JSON.stringify(s,R6(e));function I6(s,e,t,i,n){const r=Object.keys(s),o=i?.channels,u=i?.audioCodec,c=n?.videoCodec,d=o&&parseInt(o)===2;let f=!1,p=!1,g=1/0,v=1/0,b=1/0,_=1/0,S=0,D=[];const{preferHDR:R,allowedVideoRanges:L}=L6(e,n);for(let G=r.length;G--;){const N=s[r[G]];f||(f=N.channels[2]>0),g=Math.min(g,N.minHeight),v=Math.min(v,N.minFramerate),b=Math.min(b,N.minBitrate),L.filter(K=>N.videoRanges[K]>0).length>0&&(p=!0)}g=bt(g)?g:0,v=bt(v)?v:0;const P=Math.max(1080,g),U=Math.max(30,v);b=bt(b)?b:t,t=Math.max(b,t),p||(e=void 0);const V=r.length>1;return{codecSet:r.reduce((G,N)=>{const O=s[N];if(N===G)return G;if(D=p?L.filter(K=>O.videoRanges[K]>0):[],V){if(O.minBitrate>t)return sa(N,`min bitrate of ${O.minBitrate} > current estimate of ${t}`),G;if(!O.hasDefaultAudio)return sa(N,"no renditions with default or auto-select sound found"),G;if(u&&N.indexOf(u.substring(0,4))%5!==0)return sa(N,`audio codec preference "${u}" not found`),G;if(o&&!d){if(!O.channels[o])return sa(N,`no renditions with ${o} channel sound found (channels options: ${Object.keys(O.channels)})`),G}else if((!u||d)&&f&&O.channels[2]===0)return sa(N,"no renditions with stereo sound found"),G;if(O.minHeight>P)return sa(N,`min resolution of ${O.minHeight} > maximum of ${P}`),G;if(O.minFramerate>U)return sa(N,`min framerate of ${O.minFramerate} > maximum of ${U}`),G;if(!D.some(K=>O.videoRanges[K]>0))return sa(N,`no variants with VIDEO-RANGE of ${Qi(D)} found`),G;if(c&&N.indexOf(c.substring(0,4))%5!==0)return sa(N,`video codec preference "${c}" not found`),G;if(O.maxScore=bp(G)||O.fragmentError>s[G].fragmentError)?G:(_=O.minIndex,S=O.maxScore,N)},void 0),videoRanges:D,preferHDR:R,minFramerate:v,minBitrate:b,minIndex:_}}function sa(s,e){Ui.log(`[abr] start candidates with "${s}" ignored because ${e}`)}function BD(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 N6(s,e,t,i){return s.slice(t,i+1).reduce((n,r,o)=>{if(!r.codecSet)return n;const u=r.audioGroups;let c=n[r.codecSet];c||(n[r.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:o,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!u,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,r.bitrate);const d=Math.min(r.height,r.width);return c.minHeight=Math.min(c.minHeight,d),c.minFramerate=Math.min(c.minFramerate,r.frameRate),c.minIndex=Math.min(c.minIndex,o),c.maxScore=Math.max(c.maxScore,r.score),c.fragmentError+=r.fragmentError,c.videoRanges[r.videoRange]=(c.videoRanges[r.videoRange]||0)+1,u&&u.forEach(f=>{if(!f)return;const p=e.groups[f];p&&(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?p.hasDefault:p.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(p.channels).forEach(g=>{c.channels[g]=(c.channels[g]||0)+p.channels[g]}))}),n},{})}function A2(s){if(!s)return s;const{lang:e,assocLang:t,characteristics:i,channels:n,audioCodec:r}=s;return{lang:e,assocLang:t,characteristics:i,channels:n,audioCodec:r}}function pa(s,e,t){if("attrs"in s){const i=e.indexOf(s);if(i!==-1)return i}for(let i=0;ii.indexOf(n)===-1)}function Gl(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 P6(s,e,t,i,n){const r=e[i],u=e.reduce((g,v,b)=>{const _=v.uri;return(g[_]||(g[_]=[])).push(b),g},{})[r.uri];u.length>1&&(i=Math.max.apply(Math,u));const c=r.videoRange,d=r.frameRate,f=r.codecSet.substring(0,4),p=C2(e,i,g=>{if(g.videoRange!==c||g.frameRate!==d||g.codecSet.substring(0,4)!==f)return!1;const v=g.audioGroups,b=t.filter(_=>!v||v.indexOf(_.groupId)!==-1);return pa(s,b,n)>-1});return p>-1?p:C2(e,i,g=>{const v=g.audioGroups,b=t.filter(_=>!v||v.indexOf(_.groupId)!==-1);return pa(s,b,n)>-1})}function C2(s,e,t){for(let i=e;i>-1;i--)if(t(s[i]))return i;for(let i=e+1;i{var i;const{fragCurrent:n,partCurrent:r,hls:o}=this,{autoLevelEnabled:u,media:c}=o;if(!n||!c)return;const d=performance.now(),f=r?r.stats:n.stats,p=r?r.duration:n.duration,g=d-f.loading.start,v=o.minAutoLevel,b=n.level,_=this._nextAutoLevel;if(f.aborted||f.loaded&&f.loaded===f.total||b<=v){this.clearTimer(),this._nextAutoLevel=-1;return}if(!u)return;const S=_>-1&&_!==b,D=!!t||S;if(!D&&(c.paused||!c.playbackRate||!c.readyState))return;const R=o.mainForwardBufferInfo;if(!D&&R===null)return;const L=this.bwEstimator.getEstimateTTFB(),P=Math.abs(c.playbackRate);if(g<=Math.max(L,1e3*(p/(P*2))))return;const U=R?R.len/P:0,V=f.loading.first?f.loading.first-f.loading.start:-1,M=f.loaded&&V>-1,G=this.getBwEstimate(),N=o.levels,O=N[b],K=Math.max(f.loaded,Math.round(p*(n.bitrate||O.averageBitrate)/8));let Q=M?g-V:g;Q<1&&M&&(Q=Math.min(g,f.loaded*8/G));const W=M?f.loaded*1e3/Q:0,re=L/1e3,J=W?(K-f.loaded)/W:K*8/G+re;if(J<=U)return;const Y=W?W*8:G,z=((i=t?.details||this.hls.latestLevelDetails)==null?void 0:i.live)===!0,Z=this.hls.config.abrBandWidthUpFactor;let ie=Number.POSITIVE_INFINITY,ce;for(ce=b-1;ce>v;ce--){const Te=N[ce].maxBitrate,xe=!N[ce].details||z;if(ie=this.getTimeToLoadFrag(re,Y,p*Te,xe),ie=J||ie>p*10)return;M?this.bwEstimator.sample(g-Math.min(L,V),f.loaded):this.bwEstimator.sampleTTFB(g);const j=N[ce].maxBitrate;this.getBwEstimate()*Z>j&&this.resetEstimator(j);const ee=this.findBestLevel(j,v,ce,0,U,1,1);ee>-1&&(ce=ee),this.warn(`Fragment ${n.sn}${r?" part "+r.index:""} of level ${b} is loading too slowly; Fragment duration: ${n.duration.toFixed(3)} Time to underbuffer: ${U.toFixed(3)} s Estimated load time for current fragment: ${J.toFixed(3)} s Estimated load time for down switch fragment: ${ie.toFixed(3)} s TTFB estimate: ${V|0} ms Current BW estimate: ${bt(G)?G|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${ce} @ ${j|0} bps`),o.nextLoadLevel=o.nextAutoLevel=ce,this.clearTimer();const he=()=>{if(this.clearTimer(),this.fragCurrent===n&&this.hls.loadLevel===ce&&ce>0){const Te=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${ce>0?"and switching down":""} Fragment duration: ${n.duration.toFixed(3)} s Time to underbuffer: ${Te.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,ce>v){let xe=this.findBestLevel(this.hls.levels[v].bitrate,v,ce,0,Te,1,1);xe===-1&&(xe=v),this.hls.nextLoadLevel=this.hls.nextAutoLevel=xe,this.resetEstimator(this.hls.levels[xe].bitrate)}}};S||J>ie*2?he():this.timer=self.setInterval(he,ie*1e3),o.trigger($.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:r,stats:f})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new H8(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.FRAG_LOADING,this.onFragLoading,this),e.on($.FRAG_LOADED,this.onFragLoaded,this),e.on($.FRAG_BUFFERED,this.onFragBuffered,this),e.on($.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on($.LEVEL_LOADED,this.onLevelLoaded,this),e.on($.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on($.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.FRAG_LOADING,this.onFragLoading,this),e.off($.FRAG_LOADED,this.onFragLoaded,this),e.off($.FRAG_BUFFERED,this.onFragBuffered,this),e.off($.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off($.LEVEL_LOADED,this.onLevelLoaded,this),e.off($.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off($.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off($.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){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 De.BUFFER_ADD_CODEC_ERROR:case De.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case De.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,c=o-u.loading.start,d=u.loading.first?u.loading.first-u.loading.start:-1;if(u.loaded&&d>-1){const p=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(p,d),u.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,i,n){const r=e+i/t,o=n?e+this.lastLevelLoadSec:0;return r+o}onLevelLoaded(e,t){const i=this.hls.config,{loading:n}=t.stats,r=n.end-n.first;bt(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){const n=i?i.stats:t.stats;if(t.type===At.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,c=(o.loaded?o.loaded.duration:0)+r;o.loaded={bytes:u,duration:c},o.realBitrate=Math.round(8*u/c)}if(t.bitrateTest){const r={stats:n,frag:t,part:i,id:t.type};this.onFragBuffered($.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!==At.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 this.warn(`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;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:n,config:r,minAutoLevel:o}=i,u=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),d=this.getStarvationDelay();let f=r.abrBandWidthFactor,p=r.abrBandWidthUpFactor;if(d){const S=this.findBestLevel(c,o,n,d,0,f,p);if(S>=0)return this.rebufferNotice=-1,S}let g=u?Math.min(u,r.maxStarvationDelay):r.maxStarvationDelay;if(!d){const S=this.bitrateTestDelay;S&&(g=(u?Math.min(u,r.maxLoadingDelay):r.maxLoadingDelay)-S,this.info(`bitrate test took ${Math.round(1e3*S)}ms, set first fragment max fetchDuration to ${Math.round(1e3*g)} ms`),f=p=1)}const v=this.findBestLevel(c,o,n,d,g,f,p);if(this.rebufferNotice!==v&&(this.rebufferNotice=v,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${v}`)),v>-1)return v;const b=i.levels[o],_=i.loadLevelObj;return _&&b?.bitrate<_.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 c;const d=n+r,f=this.lastLoadedFragLevel,p=f===-1?this.hls.firstLevel:f,{fragCurrent:g,partCurrent:v}=this,{levels:b,allAudioTracks:_,loadLevel:S,config:D}=this.hls;if(b.length===1)return 0;const R=b[p],L=!!((c=this.hls.latestLevelDetails)!=null&&c.live),P=S===-1||f===-1;let U,V="SDR",M=R?.frameRate||0;const{audioPreference:G,videoPreference:N}=D,O=this.audioTracksByGroup||(this.audioTracksByGroup=BD(_));let K=-1;if(P){if(this.firstSelection!==-1)return this.firstSelection;const Y=this.codecTiers||(this.codecTiers=N6(b,O,t,i)),z=I6(Y,V,e,G,N),{codecSet:Z,videoRanges:ie,minFramerate:ce,minBitrate:j,minIndex:ee,preferHDR:he}=z;K=ee,U=Z,V=he?ie[ie.length-1]:ie[0],M=ce,e=Math.max(e,j),this.log(`picked start tier ${Qi(z)}`)}else U=R?.codecSet,V=R?.videoRange;const Q=v?v.duration:g?g.duration:0,W=this.bwEstimator.getEstimateTTFB()/1e3,re=[];for(let Y=i;Y>=t;Y--){var J;const z=b[Y],Z=Y>p;if(!z)continue;if(D.useMediaCapabilities&&!z.supportedResult&&!z.supportedPromise){const xe=navigator.mediaCapabilities;typeof xe?.decodingInfo=="function"&&_6(z,O,V,M,e,G)?(z.supportedPromise=MD(z,O,xe,this.supportedCache),z.supportedPromise.then(Ae=>{if(!this.hls)return;z.supportedResult=Ae;const Ke=this.hls.levels,lt=Ke.indexOf(z);Ae.error?this.warn(`MediaCapabilities decodingInfo error: "${Ae.error}" for level ${lt} ${Qi(Ae)}`):Ae.supported?Ae.decodingInfoResults.some(nt=>nt.smooth===!1||nt.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${lt} not smooth or powerEfficient: ${Qi(Ae)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${lt} ${Qi(Ae)}`),lt>-1&&Ke.length>1&&(this.log(`Removing unsupported level ${lt}`),this.hls.removeLevel(lt),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Ae=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Ae}`)})):z.supportedResult=ND}if((U&&z.codecSet!==U||V&&z.videoRange!==V||Z&&M>z.frameRate||!Z&&M>0&&Mxe.smooth===!1))&&(!P||Y!==K)){re.push(Y);continue}const ie=z.details,ce=(v?ie?.partTarget:ie?.averagetargetduration)||Q;let j;Z?j=u*e:j=o*e;const ee=Q&&n>=Q*2&&r===0?z.averageBitrate:z.maxBitrate,he=this.getTimeToLoadFrag(W,j,ee*ce,ie===void 0);if(j>=ee&&(Y===f||z.loadError===0&&z.fragmentError===0)&&(he<=W||!bt(he)||L&&!this.bitrateTestDelay||he${Y} adjustedbw(${Math.round(j)})-bitrate=${Math.round(j-ee)} ttfb:${W.toFixed(1)} avgDuration:${ce.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${he.toFixed(1)} firstSelection:${P} codecSet:${z.codecSet} videoRange:${z.videoRange} hls.loadLevel:${S}`)),P&&(this.firstSelection=Y),Y}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}}const FD={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 F6(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!bt(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;for(let r=0;r0&&u<15e-7&&(t+=15e-7),r&&s.level!==r.level&&r.end<=s.end&&(r=e[2+s.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!s||s.level===r.level)&&k2(t,i,r)===0||U6(r,s,Math.min(n,i))))return r;const o=FD.search(e,k2.bind(null,t,i));return o&&(o!==s||!r)?o:r}function U6(s,e,t){if(e&&e.start===0&&e.level0){const i=e.tagList.reduce((n,r)=>(r[0]==="INF"&&(n+=parseFloat(r[1])),n),t);return s.start<=i}return!1}function k2(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 j6(s,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>s}function UD(s,e,t){if(s&&s.startCC<=e&&s.endCC>=e){let i=s.fragments;const{fragmentHint:n}=s;n&&(i=i.concat(n));let r;return FD.search(i,o=>o.cce?-1:(r=o,o.end<=t?1:o.start>t?-1:0)),r||null}return null}function Ep(s){switch(s.details){case De.FRAG_LOAD_TIMEOUT:case De.KEY_LOAD_TIMEOUT:case De.LEVEL_LOAD_TIMEOUT:case De.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function jD(s){return s.details.startsWith("key")}function $D(s){return jD(s)&&!!s.frag&&!s.frag.decryptdata}function D2(s,e){const t=Ep(e);return s.default[`${t?"timeout":"error"}Retry`]}function Fb(s,e){const t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function L2(s){return Fi(Fi({},s),{errorRetry:null,timeoutRetry:null})}function wp(s,e,t,i){if(!s)return!1;const n=i?.code,r=e499)}function Tx(s){return s===0&&navigator.onLine===!1}var nn={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},ar={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class H6 extends wr{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on($.ERROR,this.onError,this),e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off($.ERROR,this.onError,this),e.off($.ERROR,this.onErrorOut,this),e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===At.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,i=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||i===-1?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if((i=e.details)!=null&&i.hasKey(t))return!0;const n=e.audioGroups;if(n)return this.hls.allAudioTracks.filter(o=>n.indexOf(o.groupId)>=0).some(o=>{var u;return(u=o.details)==null?void 0:u.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;const n=this.hls,r=t.context;switch(t.details){case De.FRAG_LOAD_ERROR:case De.FRAG_LOAD_TIMEOUT:case De.KEY_LOAD_ERROR:case De.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case De.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=pc();return}case De.FRAG_GAP:case De.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=nn.SendAlternateToPenaltyBox;return}case De.LEVEL_EMPTY_ERROR:case De.LEVEL_PARSING_ERROR:{var o;const c=t.parent===At.MAIN?t.level:n.loadLevel;t.details===De.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(o=o.levelDetails)!=null&&o.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case De.LEVEL_LOAD_ERROR:case De.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case De.AUDIO_TRACK_LOAD_ERROR:case De.AUDIO_TRACK_LOAD_TIMEOUT:case De.SUBTITLE_LOAD_ERROR:case De.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const c=n.loadLevelObj;if(c&&(r.type===yi.AUDIO_TRACK&&c.hasAudioGroup(r.groupId)||r.type===yi.SUBTITLE_TRACK&&c.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=nn.SendAlternateToPenaltyBox,t.errorAction.flags=ar.MoveAllAlternatesMatchingHost;return}}return;case De.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:nn.SendAlternateToPenaltyBox,flags:ar.MoveAllAlternatesMatchingHDCP};return;case De.KEY_SYSTEM_SESSION_UPDATE_FAILED:case De.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case De.KEY_SYSTEM_NO_SESSION:t.errorAction={action:nn.SendAlternateToPenaltyBox,flags:ar.MoveAllAlternatesMatchingKey};return;case De.BUFFER_ADD_CODEC_ERROR:case De.REMUX_ALLOC_ERROR:case De.BUFFER_APPEND_ERROR:if(!t.errorAction){var u;t.errorAction=this.getLevelSwitchAction(t,(u=t.level)!=null?u:n.loadLevel)}return;case De.INTERNAL_EXCEPTION:case De.BUFFER_APPENDING_ERROR:case De.BUFFER_FULL_ERROR:case De.LEVEL_SWITCH_ERROR:case De.BUFFER_STALLED_ERROR:case De.BUFFER_SEEK_OVER_HOLE:case De.BUFFER_NUDGE_ON_STALL:t.errorAction=pc();return}t.type===It.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=pc())}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,n=D2(i.config.playlistLoadPolicy,e),r=this.playlistError++;if(wp(n,r,Ep(e),e.response))return{action:nn.RetryRequest,flags:ar.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=D2(jD(e)?o:r,e),c=t.levels.reduce((f,p)=>f+p.fragmentError,0);if(n&&(e.details!==De.FRAG_GAP&&n.fragmentError++,!$D(e)&&wp(u,c,Ep(e),e.response)))return{action:nn.RetryRequest,flags:ar.None,retryConfig:u,retryCount:c};const d=this.getLevelSwitchAction(e,i);return u&&(d.retryConfig=u,d.retryCount=c),d}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const n=this.hls.levels[t];if(n){var r,o;const d=e.details;n.loadError++,d===De.BUFFER_APPEND_ERROR&&n.fragmentError++;let f=-1;const{levels:p,loadLevel:g,minAutoLevel:v,maxAutoLevel:b}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);const _=(r=e.frag)==null?void 0:r.type,D=(_===At.AUDIO&&d===De.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(d===De.BUFFER_ADD_CODEC_ERROR||d===De.BUFFER_APPEND_ERROR))&&p.some(({audioCodec:V})=>n.audioCodec!==V),L=e.sourceBufferName==="video"&&(d===De.BUFFER_ADD_CODEC_ERROR||d===De.BUFFER_APPEND_ERROR)&&p.some(({codecSet:V,audioCodec:M})=>n.codecSet!==V&&n.audioCodec===M),{type:P,groupId:U}=(o=e.context)!=null?o:{};for(let V=p.length;V--;){const M=(V+g)%p.length;if(M!==g&&M>=v&&M<=b&&p[M].loadError===0){var u,c;const G=p[M];if(d===De.FRAG_GAP&&_===At.MAIN&&e.frag){const N=p[M].details;if(N){const O=au(e.frag,N.fragments,e.frag.start);if(O!=null&&O.gap)continue}}else{if(P===yi.AUDIO_TRACK&&G.hasAudioGroup(U)||P===yi.SUBTITLE_TRACK&&G.hasSubtitleGroup(U))continue;if(_===At.AUDIO&&(u=n.audioGroups)!=null&&u.some(N=>G.hasAudioGroup(N))||_===At.SUBTITLE&&(c=n.subtitleGroups)!=null&&c.some(N=>G.hasSubtitleGroup(N))||D&&n.audioCodec===G.audioCodec||L&&n.codecSet===G.codecSet||!D&&n.codecSet!==G.codecSet)continue}f=M;break}}if(f>-1&&i.loadLevel!==f)return e.levelRetry=!0,this.playlistError=0,{action:nn.SendAlternateToPenaltyBox,flags:ar.None,nextAutoLevel:f}}return{action:nn.SendAlternateToPenaltyBox,flags:ar.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case nn.DoNothing:break;case nn.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==De.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}=i,r=i.nextAutoLevel;switch(n){case ar.None:this.switchLevel(e,r);break;case ar.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(e.frag),d=t.levels[c],f=d?.attrs["HDCP-LEVEL"];if(i.hdcpLevel=f,f==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(f){t.maxHdcpLevel=bx[bx.indexOf(f)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case ar.MoveAllAlternatesMatchingKey:{const c=e.decryptdata;if(c){const d=this.hls.levels,f=d.length;for(let g=f;g--;)if(this.variantHasKey(d[g],c)){var o,u;this.log(`Banned key found in level ${g} (${d[g].bitrate}bps) or audio group "${(o=d[g].audioGroups)==null?void 0:o.join(",")}" (${(u=e.frag)==null?void 0:u.type} fragment) ${an(c.keyId||[])}`),d[g].fragmentError++,d[g].loadError++,this.log(`Removing level ${g} with key error (${e.error})`),this.hls.removeLevel(g)}const p=e.frag;if(this.hls.levels.length{const c=this.fragments[u];if(!c||o>=c.body.sn)return;if(!c.buffered&&(!c.loaded||r)){c.body.type===i&&this.removeFragment(c.body);return}const d=c.range[e];if(d){if(d.time.length===0){this.removeFragment(c.body);return}d.time.some(f=>{const p=!this.isTimeBuffered(f.startPTS,f.endPTS,t);return p&&this.removeFragment(c.body),p})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const i=e.frag,n=Ku(i),r=this.fragments[n];if(!r||r.buffered&&i.gap)return;const o=!i.relurl;Object.keys(t).forEach(u=>{const c=i.elementaryStreams[u];if(!c)return;const d=t[u],f=o||c.partial===!0;r.range[u]=this.getBufferedTimes(i,e.part,f,d)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,i),xm(r)||this.removeParts(i.sn-1,i.type)):this.removeFragment(r.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=R2(i,n=>n.fragment.sn>=e))}fragBuffered(e,t){const i=Ku(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,this.bufferedEnd(n,e))}getBufferedTimes(e,t,i,n){const r={time:[],partial:i},o=e.start,u=e.end,c=e.minEndPTS||u,d=e.maxStartPTS||o;for(let f=0;f=p&&c<=g){r.time.push({startPTS:Math.max(o,n.start(f)),endPTS:Math.min(u,n.end(f))});break}else if(op){const v=Math.max(o,n.start(f)),b=Math.min(u,n.end(f));b>v&&(r.partial=!0,r.time.push({startPTS:v,endPTS:b}))}else if(u<=p)break}return r}getPartialFragment(e){let t=null,i,n,r,o=0;const{bufferPadding:u,fragments:c}=this;return Object.keys(c).forEach(d=>{const f=c[d];f&&xm(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||xm(t))}getState(e){const t=Ku(e),i=this.fragments[t];return i?i.buffered?xm(i)?$s.PARTIAL:$s.OK:$s.APPENDING:$s.NOT_LOADED}isTimeBuffered(e,t,i){let n,r;for(let o=0;o=n&&t<=r)return!0;if(t<=n)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const i=t.frag,n=t.part?null:t,r=Ku(i);this.fragments[r]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:n,timeRanges:r,type:o}=t;if(i.sn==="initSegment")return;const u=i.type;if(n){let d=this.activePartLists[u];d||(this.activePartLists[u]=d=[]),d.push(n)}this.timeRanges=r;const c=r[o];this.detectEvictedFragments(o,c,u,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Ku(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let n=i.length;n--;){const r=t[i[n]];if(r?.body.type===e)return!0}return!1}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 c=u.body;c.type!==i||n&&!c.gap||c.starte&&(u.buffered||r)&&this.removeFragment(c)})}removeFragment(e){const t=Ku(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const n=e.sn;this.activePartLists[e.type]=R2(i,r=>r.fragment.sn!==n)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(i=>i.clearElementaryStreamInfo())}}function xm(s){var e,t,i;return s.buffered&&!!(s.body.gap||(e=s.range.video)!=null&&e.partial||(t=s.range.audio)!=null&&t.partial||(i=s.range.audiovideo)!=null&&i.partial)}function Ku(s){return`${s.type}_${s.level}_${s.sn}`}function R2(s,e){return s.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var cl={cbc:0,ctr:1};class G6{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case cl.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case cl.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function z6(s){const e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?s.slice(0,e-t):s}class q6{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],c=this.invSubMix,d=c[0],f=c[1],p=c[2],g=c[3],v=new Uint32Array(256);let b=0,_=0,S=0;for(S=0;S<256;S++)S<128?v[S]=S<<1:v[S]=S<<1^283;for(S=0;S<256;S++){let D=_^_<<1^_<<2^_<<3^_<<4;D=D>>>8^D&255^99,e[b]=D,t[D]=b;const R=v[b],L=v[R],P=v[L];let U=v[D]*257^D*16843008;n[b]=U<<24|U>>>8,r[b]=U<<16|U>>>16,o[b]=U<<8|U>>>24,u[b]=U,U=P*16843009^L*65537^R*257^b*16843008,d[D]=U<<24|U>>>8,f[D]=U<<16|U>>>16,p[D]=U<<8|U>>>24,g[D]=U,b?(b=R^v[v[v[P^R]]],_^=v[v[_]]):b=_=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,n=0;for(;n{const u=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(u,t,i,n);const c=this.flush();c?r(c.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,n)}softwareDecrypt(e,t,i,n){const{currentIV:r,currentResult:o,remainderData:u}=this;if(n!==cl.cbc||t.byteLength!==16)return Ui.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),u&&(e=_r(u,e),this.remainderData=null);const c=this.getValidChunk(e);if(!c.length)return null;r&&(i=r);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new q6),d.expandKey(t);const f=o;return this.currentResult=d.decrypt(c.buffer,0,i),this.currentIV=c.slice(-16).buffer,f||null}webCryptoDecrypt(e,t,i,n){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,n));this.key=t,this.fastAesKey=new K6(this.subtle,t,n)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new G6(this.subtle,new Uint8Array(i),n).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(Ui.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i,n)))}onWebCryptoError(e,t,i,n){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,n);const o=this.flush();if(o)return o.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%W6;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(Ui.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const I2=Math.pow(2,17);class X6{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 Wa({type:It.NETWORK_ERROR,details:De.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,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(b=>b[0]==="GAP")){c(O2(e));return}else e.gap=!1;const d=this.loader=r?new r(n):new o(n),f=N2(e);e.loader=d;const p=L2(n.fragLoadPolicy.default),g={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:I2};e.stats=d.stats;const v={onSuccess:(b,_,S,D)=>{this.resetLoader(e,d);let R=b.data;S.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(R.slice(0,16)),R=R.slice(16)),u({frag:e,part:null,payload:R,networkDetails:D})},onError:(b,_,S,D)=>{this.resetLoader(e,d),c(new Wa({type:It.NETWORK_ERROR,details:De.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Fi({url:i,data:void 0},b),error:new Error(`HTTP Error ${b.code} ${b.text}`),networkDetails:S,stats:D}))},onAbort:(b,_,S)=>{this.resetLoader(e,d),c(new Wa({type:It.NETWORK_ERROR,details:De.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:S,stats:b}))},onTimeout:(b,_,S)=>{this.resetLoader(e,d),c(new Wa({type:It.NETWORK_ERROR,details:De.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:S,stats:b}))}};t&&(v.onProgress=(b,_,S,D)=>t({frag:e,part:null,payload:S,networkDetails:D})),d.load(f,g,v)})}loadPart(e,t,i){this.abort();const n=this.config,r=n.fLoader,o=n.loader;return new Promise((u,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(O2(e,t));return}const d=this.loader=r?new r(n):new o(n),f=N2(e,t);e.loader=d;const p=L2(n.fragLoadPolicy.default),g={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:I2};t.stats=d.stats,d.load(f,g,{onSuccess:(v,b,_,S)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);const D={frag:e,part:t,payload:v.data,networkDetails:S};i(D),u(D)},onError:(v,b,_,S)=>{this.resetLoader(e,d),c(new Wa({type:It.NETWORK_ERROR,details:De.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Fi({url:f.url,data:void 0},v),error:new Error(`HTTP Error ${v.code} ${v.text}`),networkDetails:_,stats:S}))},onAbort:(v,b,_)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,d),c(new Wa({type:It.NETWORK_ERROR,details:De.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:_,stats:v}))},onTimeout:(v,b,_)=>{this.resetLoader(e,d),c(new Wa({type:It.NETWORK_ERROR,details:De.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:_,stats:v}))}})})}updateStatsFromPart(e,t){const i=e.stats,n=t.stats,r=n.total;if(i.loaded+=n.loaded,r){const c=Math.round(e.duration/t.duration),d=Math.min(Math.round(i.loaded/r),c),p=(c-d)*Math.round(i.loaded/d);i.total=i.loaded+p}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 N2(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(bt(n)&&bt(r)){var o;let u=n,c=r;if(s.sn==="initSegment"&&Q6((o=s.decryptdata)==null?void 0:o.method)){const d=r-n;d%16&&(c=r+(16-d%16)),n!==0&&(i.resetIV=!0,u=n-16)}i.rangeStart=u,i.rangeEnd=c}return i}function O2(s,e){const t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:It.MEDIA_ERROR,details:De.FRAG_GAP,fatal:!1,frag:s,error:t,networkDetails:null};return e&&(i.part=e),(e||s).stats.aborted=!0,new Wa(i)}function Q6(s){return s==="AES-128"||s==="AES-256"}class Wa extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class HD extends wr{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class jb{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=bm(),this.buffering={audio:bm(),video:bm(),audiovideo:bm()},this.level=e,this.sn=t,this.id=i,this.size=n,this.part=r,this.partial=o}}function bm(){return{start:0,executeStart:0,executeEnd:0,end:0}}const M2={length:0,start:()=>0,end:()=>0};class ti{static isBuffered(e,t){if(e){const i=ti.getBuffered(e);for(let n=i.length;n--;)if(t>=i.start(n)&&t<=i.end(n))return!0}return!1}static bufferedRanges(e){if(e){const t=ti.getBuffered(e);return ti.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let i=0;i1&&e.sort((f,p)=>f.start-p.start||p.end-f.end);let n=-1,r=[];if(i)for(let f=0;f=e[f].start&&t<=e[f].end&&(n=f);const p=r.length;if(p){const g=r[p-1].end;e[f].start-gg&&(r[p-1].end=e[f].end):r.push(e[f])}else r.push(e[f])}else r=e;let o=0,u,c=t,d=t;for(let f=0;f=p&&t<=g&&(n=f),t+i>=p&&t{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 B2(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 Z6(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}"`))}const J6=/^(\d+)x(\d+)$/,F2=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ds{constructor(e,t){typeof e=="string"&&(e=ds.parseAttrList(e,t)),zi(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;nNumber.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]}enumeratedStringList(e,t){const i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((n,r)=>(n[r.toLowerCase()]=!0,n),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=J6.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;const n={};for(F2.lastIndex=0;(i=F2.exec(e))!==null;){const o=i[1].trim();let u=i[2];const c=u.indexOf('"')===0&&u.lastIndexOf('"')===u.length-1;let d=!1;if(c)u=u.slice(1,-1);else switch(o){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(t&&(c||d))u=_x(t,u);else if(!d&&!c)switch(o){case"CLOSED-CAPTIONS":if(u==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Ui.warn(`${e}: attribute ${o} is missing quotes`)}n[o]=u}return n}}const eU="com.apple.hls.interstitial";function tU(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function iU(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class GD{constructor(e,t,i=0){var n;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=(n=t?.tagOrder)!=null?n:i,t){const r=t.attr;for(const o in r)if(Object.prototype.hasOwnProperty.call(e,o)&&e[o]!==r[o]){Ui.warn(`DATERANGE tag attribute: "${o}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=o;break}e=zi(new ds({}),r,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const r=t?.endDate||new Date(this.attr["END-DATE"]);bt(r.getTime())&&(this._endDate=r)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(Ui.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(bt(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===eU}get isValid(){return!!this.id&&!this._badValueForSameId&&bt(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const sU=10;class nU{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}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}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return this.fragments.length?bt(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||sU}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(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function Ap(s,e){return s.length===e.length?!s.some((t,i)=>t!==e[i]):!1}function U2(s,e){return!s&&!e?!0:!s||!e?!1:Ap(s,e)}function gc(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function $b(s){switch(s){case"AES-128":case"AES-256":return cl.cbc;case"AES-256-CTR":return cl.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function Hb(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function Sx(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}function rU(s){const e=Sx(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function zD(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 qD(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=Hb(o)):t=rU(o)}}return t}const Cp=typeof self<"u"?self:void 0;var hs={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},on={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function jm(s){switch(s){case on.FAIRPLAY:return hs.FAIRPLAY;case on.PLAYREADY:return hs.PLAYREADY;case on.WIDEVINE:return hs.WIDEVINE;case on.CLEARKEY:return hs.CLEARKEY}}function nv(s){switch(s){case hs.FAIRPLAY:return on.FAIRPLAY;case hs.PLAYREADY:return on.PLAYREADY;case hs.WIDEVINE:return on.WIDEVINE;case hs.CLEARKEY:return on.CLEARKEY}}function sh(s){const{drmSystems:e,widevineLicenseUrl:t}=s,i=e?[hs.FAIRPLAY,hs.WIDEVINE,hs.PLAYREADY,hs.CLEARKEY].filter(n=>!!e[n]):[];return!i[hs.WIDEVINE]&&t&&i.push(hs.WIDEVINE),i}const KD=(function(s){return Cp!=null&&(s=Cp.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function aU(s,e,t,i){let n;switch(s){case hs.FAIRPLAY:n=["cenc","sinf"];break;case hs.WIDEVINE:case hs.PLAYREADY:n=["cenc"];break;case hs.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return oU(n,e,t,i)}function oU(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 lU(s){var e;return!!s&&(s.sessionType==="persistent-license"||!!((e=s.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function YD(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 c=Hb(u).subarray(0,16);return zD(c),c}}return null}let Yu={};class al{static clearKeyUriToKeyIdMap(){Yu={}}static setKeyIdForUri(e,t){Yu[e]=t}static addKeyIdForUri(e){const t=Object.keys(Yu).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),Yu[e]=i,i}constructor(e,t,i,n=[1],r=null,o){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&&!gc(e),o!=null&&o.startsWith("0x")&&(this.keyId=new Uint8Array(_D(o)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Ap(e.keyFormatVersions,this.keyFormatVersions)&&U2(e.iv,this.iv)&&U2(e.keyId,this.keyId)}isSupported(){if(this.method){if(gc(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case on.FAIRPLAY:case on.WIDEVINE:case on.PLAYREADY:case on.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(gc(this.method)){let r=this.iv;return r||(typeof e!="number"&&(Ui.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),r=cU(e)),new al(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){const r=Yu[this.uri];if(r&&!Ap(this.keyId,r)&&al.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=qD(this.uri);if(i)switch(this.keyFormat){case on.WIDEVINE:if(this.pssh=i,!this.keyId){const r=f6(i.buffer);if(r.length){var n;const o=r[0];this.keyId=(n=o.kids)!=null&&n.length?o.kids[0]:null}}this.keyId||(this.keyId=j2(t));break;case on.PLAYREADY:{const r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=h6(r,null,i),this.keyId=YD(i);break}default:{let r=i.subarray(0,16);if(r.length!==16){const o=new Uint8Array(16);o.set(r,16-r.length),r=o}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r;r=uU(t),r||(r=j2(t),r||(r=Yu[this.uri])),r&&(this.keyId=r,al.setKeyIdForUri(this.uri,r))}return this}}function uU(s){const e=s?.[on.WIDEVINE];return e?e.keyId:null}function j2(s){const e=s?.[on.PLAYREADY];if(e){const t=qD(e.uri);if(t)return YD(t)}return null}function cU(s){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}const $2=/#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,H2=/#EXT-X-MEDIA:(.*)/g,dU=/^#EXT(?:INF|-X-TARGETDURATION):/m,rv=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),hU=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.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 ga{static findGroup(e,t){for(let i=0;i0&&r.length({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:o.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(H2.lastIndex=0;(n=H2.exec(e))!==null;){const d=new ds(n[1],i),f=d.TYPE;if(f){const p=u[f],g=r[f]||[];r[f]=g;const v=d.LANGUAGE,b=d["ASSOC-LANGUAGE"],_=d.CHANNELS,S=d.CHARACTERISTICS,D=d["INSTREAM-ID"],R={attrs:d,bitrate:0,id:c++,groupId:d["GROUP-ID"]||"",name:d.NAME||v||"",type:f,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:v,url:d.URI?ga.resolve(d.URI,t):""};if(b&&(R.assocLang=b),_&&(R.channels=_),S&&(R.characteristics=S),D&&(R.instreamId=D),p!=null&&p.length){const L=ga.findGroup(p,R.groupId)||p[0];q2(R,L,"audioCodec"),q2(R,L,"textCodec")}g.push(R)}}return r}static parseLevelPlaylist(e,t,i,n,r,o){var u;const c={url:t},d=new nU(t),f=d.fragments,p=[];let g=null,v=0,b=0,_=0,S=0,D=0,R=null,L=new tv(n,c),P,U,V,M=-1,G=!1,N=null,O;if(rv.lastIndex=0,d.m3u8=e,d.hasVariableRefs=P2(e),((u=rv.exec(e))==null?void 0:u[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(P=rv.exec(e))!==null;){G&&(G=!1,L=new tv(n,c),L.playlistOffset=_,L.setStart(_),L.sn=v,L.cc=S,D&&(L.bitrate=D),L.level=i,g&&(L.initSegment=g,g.rawProgramDateTime&&(L.rawProgramDateTime=g.rawProgramDateTime,g.rawProgramDateTime=null),N&&(L.setByteRange(N),N=null)));const re=P[1];if(re){L.duration=parseFloat(re);const J=(" "+P[2]).slice(1);L.title=J||null,L.tagList.push(J?["INF",re,J]:["INF",re])}else if(P[3]){if(bt(L.duration)){L.playlistOffset=_,L.setStart(_),V&&Y2(L,V,d),L.sn=v,L.level=i,L.cc=S,f.push(L);const J=(" "+P[3]).slice(1);L.relurl=_x(d,J),Ex(L,R,p),R=L,_+=L.duration,v++,b=0,G=!0}}else{if(P=P[0].match(hU),!P){Ui.warn("No matches on slow regex match for level playlist!");continue}for(U=1;U0&&W2(d,J,P),v=d.startSN=parseInt(Y);break;case"SKIP":{d.skippedSegments&&za(d,J,P);const Z=new ds(Y,d),ie=Z.decimalInteger("SKIPPED-SEGMENTS");if(bt(ie)){d.skippedSegments+=ie;for(let j=ie;j--;)f.push(null);v+=ie}const ce=Z.enumeratedString("RECENTLY-REMOVED-DATERANGES");ce&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(ce.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&za(d,J,P),d.targetduration=Math.max(parseInt(Y),1);break;case"VERSION":d.version!==null&&za(d,J,P),d.version=parseInt(Y);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||za(d,J,P),d.live=!1;break;case"#":(Y||z)&&L.tagList.push(z?[Y,z]:[Y]);break;case"DISCONTINUITY":S++,L.tagList.push(["DIS"]);break;case"GAP":L.gap=!0,L.tagList.push([J]);break;case"BITRATE":L.tagList.push([J,Y]),D=parseInt(Y)*1e3,bt(D)?L.bitrate=D:D=0;break;case"DATERANGE":{const Z=new ds(Y,d),ie=new GD(Z,d.dateRanges[Z.ID],d.dateRangeTagCount);d.dateRangeTagCount++,ie.isValid||d.skippedSegments?d.dateRanges[ie.id]=ie:Ui.warn(`Ignoring invalid DATERANGE tag: "${Y}"`),L.tagList.push(["EXT-X-DATERANGE",Y]);break}case"DEFINE":{{const Z=new ds(Y,d);"IMPORT"in Z?Z6(d,Z,o):B2(d,Z,t)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?za(d,J,P):f.length>0&&W2(d,J,P),d.startCC=S=parseInt(Y);break;case"KEY":{const Z=V2(Y,t,d);if(Z.isSupported()){if(Z.method==="NONE"){V=void 0;break}V||(V={});const ie=V[Z.keyFormat];ie!=null&&ie.matches(Z)||(ie&&(V=zi({},V)),V[Z.keyFormat]=Z)}else Ui.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${Y}"`);break}case"START":d.startTimeOffset=G2(Y);break;case"MAP":{const Z=new ds(Y,d);if(L.duration){const ie=new tv(n,c);K2(ie,Z,i,V),g=ie,L.initSegment=g,g.rawProgramDateTime&&!L.rawProgramDateTime&&(L.rawProgramDateTime=g.rawProgramDateTime)}else{const ie=L.byteRangeEndOffset;if(ie){const ce=L.byteRangeStartOffset;N=`${ie-ce}@${ce}`}else N=null;K2(L,Z,i,V),g=L,G=!0}g.cc=S;break}case"SERVER-CONTROL":{O&&za(d,J,P),O=new ds(Y),d.canBlockReload=O.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=O.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&O.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=O.optionalFloat("PART-HOLD-BACK",0),d.holdBack=O.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&za(d,J,P);const Z=new ds(Y);d.partTarget=Z.decimalFloatingPoint("PART-TARGET");break}case"PART":{let Z=d.partList;Z||(Z=d.partList=[]);const ie=b>0?Z[Z.length-1]:void 0,ce=b++,j=new ds(Y,d),ee=new Z8(j,L,c,ce,ie);Z.push(ee),L.duration+=ee.duration;break}case"PRELOAD-HINT":{const Z=new ds(Y,d);d.preloadHint=Z;break}case"RENDITION-REPORT":{const Z=new ds(Y,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(Z);break}default:Ui.warn(`line parsed but not handled: ${P}`);break}}}R&&!R.relurl?(f.pop(),_-=R.duration,d.partList&&(d.fragmentHint=R)):d.partList&&(Ex(L,R,p),L.cc=S,d.fragmentHint=L,V&&Y2(L,V,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const K=f.length,Q=f[0],W=f[K-1];if(_+=d.skippedSegments*d.targetduration,_>0&&K&&W){d.averagetargetduration=_/K;const re=W.sn;d.endSN=re!=="initSegment"?re:0,d.live||(W.endList=!0),M>0&&(mU(f,M),Q&&p.unshift(Q))}return d.fragmentHint&&(_+=d.fragmentHint.duration),d.totalduration=_,p.length&&d.dateRangeTagCount&&Q&&WD(p,d),d.endCC=S,d}}function WD(s,e){let t=s.length;if(!t)if(e.hasProgramDateTime){const u=e.fragments[e.fragments.length-1];s.push(u),t++}else return;const i=s[t-1],n=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let u=r.length;u--;){const c=e.dateRanges[r[u]],d=c.startDate.getTime();c.tagAnchor=i.ref;for(let f=t;f--;){var o;if(((o=s[f])==null?void 0:o.sn)=u||i===0){var o;const c=(((o=t[i+1])==null?void 0:o.start)||n)-r.start;if(e<=u+c*1e3){const d=t[i].sn-s.startSN;if(d<0)return-1;const f=s.fragments;if(f.length>t.length){const g=(t[i+1]||f[f.length-1]).sn-s.startSN;for(let v=g;v>d;v--){const b=f[v].programDateTime;if(e>=b&&ei);["video","audio","text"].forEach(i=>{const n=t.filter(r=>Pb(r,i));n.length&&(e[`${i}Codec`]=n.map(r=>r.split("/")[0]).join(","),t=t.filter(r=>n.indexOf(r)===-1))}),e.unknownCodecs=t}function q2(s,e,t){const i=e[t];i&&(s[t]=i)}function mU(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 Ex(s,e,t){s.rawProgramDateTime?t.push(s):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime)}function K2(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 Y2(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)}function za(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function W2(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function av(s,e){const t=e.startPTS;if(bt(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.setDuration(i)}else e.sn>s.sn?s.cc===e.cc&&s.minEndPTS?e.setStart(s.start+(s.minEndPTS-s.start)):e.setStart(s.start+s.duration):e.setStart(Math.max(s.start-e.duration,0))}function XD(s,e,t,i,n,r,o){i-t<=0&&(o.warn("Fragment should have a positive duration",e),i=t+e.duration,r=n+e.duration);let c=t,d=i;const f=e.startPTS,p=e.endPTS;if(bt(f)){const D=Math.abs(f-t);s&&D>s.totalduration?o.warn(`media timestamps and playlist times differ by ${D}s for level ${e.level} ${s.url}`):bt(e.deltaPTS)?e.deltaPTS=Math.max(D,e.deltaPTS):e.deltaPTS=D,c=Math.max(t,f),t=Math.min(t,f),n=e.startDTS!==void 0?Math.min(n,e.startDTS):n,d=Math.min(i,p),i=Math.max(i,p),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}const g=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(i-e.start),e.startPTS=t,e.maxStartPTS=c,e.startDTS=n,e.endPTS=i,e.minEndPTS=d,e.endDTS=r;const v=e.sn;if(!s||vs.endSN)return 0;let b;const _=v-s.startSN,S=s.fragments;for(S[_]=e,b=_;b>0;b--)av(S[b],S[b-1]);for(b=_;b=0;f--){const p=n[f].initSegment;if(p){i=p;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let r;vU(s,e,(f,p,g,v)=>{if((!e.startCC||e.skippedSegments)&&p.cc!==f.cc){const b=f.cc-p.cc;for(let _=g;_{var p;f&&(!f.initSegment||f.initSegment.relurl===((p=i)==null?void 0:p.relurl))&&(f.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=o.some(f=>!f),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let f=e.skippedSegments;f--;)o.shift();e.startSN=o[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=gU(s.dateRanges,e,t));const f=s.fragments.filter(p=>p.rawProgramDateTime);if(s.hasProgramDateTime&&!e.hasProgramDateTime)for(let p=1;p{p.elementaryStreams=f.elementaryStreams,p.stats=f.stats}),r?XD(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,t):QD(s,e),o.length&&(e.totalduration=e.edge-o[0].start),e.driftStartTime=s.driftStartTime,e.driftStart=s.driftStart;const d=e.advancedDateTime;if(e.advanced&&d){const f=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=f),e.driftEndTime=d,e.driftEnd=f}else e.driftEndTime=s.driftEndTime,e.driftEnd=s.driftEnd,e.advancedDateTime=s.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=s.requestScheduled)}function gU(s,e,t){const{dateRanges:i,recentlyRemovedDateranges:n}=e,r=zi({},s);n&&n.forEach(c=>{delete r[c]});const u=Object.keys(r).length;return u?(Object.keys(i).forEach(c=>{const d=r[c],f=new GD(i[c].attr,d);f.isValid?(r[c]=f,d||(f.tagOrder+=u)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Qi(i[c].attr)}"`)}),r):i}function yU(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 vU(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,c=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let d=n;d<=r;d++){const f=c[o+d];let p=u[d];if(i&&!p&&f&&(p=e.fragments[d]=f),f&&p){t(f,p,d,u);const g=f.relurl,v=p.relurl;if(g&&xU(g,v)){e.playlistParsingError=X2(`media sequence mismatch ${p.sn}:`,s,e,f,p);return}else if(f.cc!==p.cc){e.playlistParsingError=X2(`discontinuity sequence mismatch (${f.cc}!=${p.cc})`,s,e,f,p);return}}}}function X2(s,e,t,i,n){return new Error(`${s} ${n.url} Playlist starting @${e.startSN} ${e.m3u8} Playlist starting @${t.startSN} ${t.m3u8}`)}function QD(s,e,t=!0){const i=e.startSN+e.skippedSegments-s.startSN,n=s.fragments,r=i>=0;let o=0;if(r&&ie){const r=i[i.length-1].duration*1e3;r{var i;(i=e.details)==null||i.fragments.forEach(n=>{n.level=t,n.initSegment&&(n.initSegment.level=t)})})}function xU(s,e){return s!==e&&e?Z2(s)!==Z2(e):!1}function Z2(s){return s.replace(/\?[^?]*$/,"")}function mh(s,e){for(let i=0,n=s.length;is.startCC)}function J2(s,e){const t=s.start+e;s.startPTS=t,s.setStart(t),s.endPTS=t+s.duration}function iL(s,e){const t=e.fragments;for(let i=0,n=t.length;i{const{config:o,fragCurrent:u,media:c,mediaBuffer:d,state:f}=this,p=c?c.currentTime:0,g=ti.bufferInfo(d||c,p,o.maxBufferHole),v=!g.len;if(this.log(`Media seeking to ${bt(p)?p.toFixed(3):p}, state: ${f}, ${v?"out of":"in"} buffer`),this.state===qe.ENDED)this.resetLoadingState();else if(u){const b=o.maxFragLookUpTolerance,_=u.start-b,S=u.start+u.duration+b;if(v||Sg.end){const D=p>S;(p<_||D)&&(D&&u.loader&&(this.log(`Cancelling fragment load for seek (sn: ${u.sn})`),u.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(p,1/0,this.playlistType,!0);const b=this.lastCurrentTime;if(p>b&&(this.lastCurrentTime=p),!this.loadingParts){const _=Math.max(g.end,p),S=this.shouldLoadParts(this.getLevelDetails(),_);S&&(this.log(`LL-Part loading ON after seeking to ${p.toFixed(2)} with buffer @${_.toFixed(2)}`),this.loadingParts=S)}}this.hls.hasEnoughToStart||(this.log(`Setting ${v?"startPosition":"nextLoadPosition"} to ${p} for seek without enough to start`),this.nextLoadPosition=p,v&&(this.startPosition=p)),v&&this.state===qe.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new X6(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Ub(e.config)}registerListeners(){const{hls:e}=this;e.on($.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.MANIFEST_LOADED,this.onManifestLoaded,this),e.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off($.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.MANIFEST_LOADED,this.onManifestLoaded,this),e.off($.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===qe.STOPPED)return;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=qe.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,n=this.config.timelineOffset||0;if(i<=n)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=ti.bufferedInfo(r,e.start,0));const o=e.nextStart;if(o&&o>n&&o{const o=r.frag;if(this.fragContextChanged(o)){this.warn(`${o.type} sn: ${o.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(o,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(o);return}o.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,i,n).then(r=>{if(!r)return;const o=this.state,u=r.frag;if(this.fragContextChanged(u)){(o===qe.FRAG_LOADING||!this.fragCurrent&&o===qe.PARSING)&&(this.fragmentTracker.removeFragment(u),this.state=qe.IDLE);return}"payload"in r&&(this.log(`Loaded ${u.type} sn: ${u.sn} of ${this.playlistLabel()} ${u.level}`),this.hls.trigger($.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===qe.STOPPED||this.state===qe.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===$s.APPENDING){const r=e.type,o=this.getFwdBufferInfo(this.mediaBuffer,r),u=Math.max(e.duration,o?o.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.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)===$s.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)}waitForLive(e){const t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:i};this.hls.trigger($.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{const n=i?.frag;if(!n||this.fragContextChanged(n)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:n}=this,{frag:r,payload:o}=i,u=r.decryptdata;if(o&&o.byteLength>0&&u!=null&&u.key&&u.iv&&gc(u.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(o),u.key.buffer,u.iv.buffer,$b(u.method)).catch(d=>{throw n.trigger($.ERROR,{type:It.MEDIA_ERROR,details:De.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:r}),d}).then(d=>{const f=self.performance.now();return n.trigger($.FRAG_DECRYPTED,{frag:r,payload:d,stats:{tstart:c,tdecrypt:f}}),i.payload=d,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===qe.STOPPED||this.state===qe.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!==qe.STOPPED&&(this.state=qe.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()}unhandledEncryptionError(e,t){var i,n;const r=e.tracks;if(r&&!t.encrypted&&((i=r.audio)!=null&&i.encrypted||(n=r.video)!=null&&n.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const o=this.media,u=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${o?"attached mediaKeys: "+o.mediaKeys:"detached"})`);return this.warn(u.message),!o||o.mediaKeys?!1:(this.hls.trigger($.ERROR,{type:It.KEY_SYSTEM_ERROR,details:De.KEY_SYSTEM_NO_KEYS,fatal:!1,error:u,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?_U.toString(ti.getBuffered(i)):"(detached)"})`),As(e)){var n;if(e.type!==At.SUBTITLE){const o=e.elementaryStreams;if(!Object.keys(o).some(u=>!!o[u])){this.state=qe.IDLE;return}}const r=(n=this.levels)==null?void 0:n[e.level];r!=null&&r.fragmentError&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0)}this.state=qe.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:n,partsLoaded:r}=e,o=!r||r.length===0||r.some(c=>!c),u=new jb(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;this.fragCurrent=e;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)){if(this.log(`Loading key for ${e.sn} of [${o.startSN}-${o.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=qe.KEY_LOADING,this.fragCurrent=e,u=this.keyLoader.load(e).then(g=>{if(!this.fragContextChanged(g.frag))return this.hls.trigger($.KEY_LOADED,g),this.state===qe.KEY_LOADING&&(this.state=qe.IDLE),g}),this.hls.trigger($.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(u=this.keyLoader.loadClear(e,o.encryptedFragments,this.startFragRequested),u&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(As(e)&&(!c||e.sn!==c.sn)){const g=this.shouldLoadParts(t.details,e.end);g!==this.loadingParts&&(this.log(`LL-Part loading ${g?"ON":"OFF"} loading sn ${c?.sn}->${e.sn}`),this.loadingParts=g)}if(i=Math.max(e.start,i||0),this.loadingParts&&As(e)){const g=o.partList;if(g&&n){i>o.fragmentEnd&&o.fragmentHint&&(e=o.fragmentHint);const v=this.getNextPart(g,e,i);if(v>-1){const b=g[v];e=this.fragCurrent=b.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${b.index} (${v}/${g.length-1}) of ${this.fragInfo(e,!1,b)}) cc: ${e.cc} [${o.startSN}-${o.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=b.start+b.duration,this.state=qe.FRAG_LOADING;let _;return u?_=u.then(S=>!S||this.fragContextChanged(S.frag)?null:this.doFragPartsLoad(e,b,t,n)).catch(S=>this.handleFragLoadError(S)):_=this.doFragPartsLoad(e,b,t,n).catch(S=>this.handleFragLoadError(S)),this.hls.trigger($.FRAG_LOADING,{frag:e,part:b,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):_}else if(!e.url||this.loadedEndOfParts(g,i))return Promise.resolve(null)}}if(As(e)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(d=o.partList)==null?void 0:d.filter(g=>g.loaded).map(g=>`[${g.start}-${g.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+o.startSN+"-"+o.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),bt(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=qe.FRAG_LOADING;const f=this.config.progressive&&e.type!==At.SUBTITLE;let p;return f&&u?p=u.then(g=>!g||this.fragContextChanged(g.frag)?null:this.fragmentLoader.load(e,n)).catch(g=>this.handleFragLoadError(g)):p=Promise.all([this.fragmentLoader.load(e,f?n:void 0),u]).then(([g])=>(!f&&n&&n(g),g)).catch(g=>this.handleFragLoadError(g)),this.hls.trigger($.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 c=[],d=(u=i.details)==null?void 0:u.partList,f=p=>{this.fragmentLoader.loadPart(e,p,n).then(g=>{c[p.index]=g;const v=g.part;this.hls.trigger($.FRAG_LOADED,g);const b=Q2(i.details,e.sn,p.index+1)||eL(d,e.sn,p.index+1);if(b)f(b);else return r({frag:e,part:v,partsLoaded:c})}).catch(o)};f(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===De.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===It.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger($.ERROR,t)}else this.hls.trigger($.ERROR,{type:It.OTHER_ERROR,details:De.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==qe.PARSING){!this.fragCurrent&&this.state!==qe.STOPPED&&this.state!==qe.ERROR&&(this.state=qe.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);const u=this.getLevelDetails(),d=u&&i.sn>u.endSN||this.shouldLoadParts(u,i.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(i,n,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i;const r=e.partList[0];if(r.fragment.type===At.SUBTITLE)return!1;const o=r.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=o){var n;if((this.hls.hasEnoughToStart?((n=this.media)==null?void 0:n.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}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 ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const u=t[n],c=u.details,d=o>-1?Q2(c,r,o):null,f=d?d.fragment:JD(c,r,i);return f?(i&&i!==f&&(f.stats=i.stats),{frag:f,part:d,level:u}):null}bufferFragmentData(e,t,i,n,r){if(this.state!==qe.PARSING)return;const{data1:o,data2:u}=e;let c=o;if(u&&(c=_r(o,u)),!c.length)return;const d=this.initPTS[t.cc],f=d?-d.baseTime/d.timescale:void 0,p={type:e.type,frag:t,part:i,chunkMeta:n,offset:f,parent:t.type,data:c};if(this.hls.trigger($.BUFFER_APPENDING,p),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!ti.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,n=ti.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){var i;const n=this.getLoadPosition();if(!bt(n))return null;const o=this.lastCurrentTime>n||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,o)}getFwdBufferInfoAtPos(e,t,i,n){const r=ti.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||o.gap)){const u=Math.max(Math.min(r.nextStart,o.end)-t,n);return ti.bufferInfo(e,t,u)}}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=At.MAIN){const i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;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,u=r.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const p=r.initialLiveManifestSize;if(n=o?g:v)||c.start:e;this.log(`Setting startPosition to ${b} to match start frag at live edge. mainStart: ${g} liveSyncPosition: ${v} frag.start: ${(d=c)==null?void 0:d.start}`),this.startPosition=this.nextLoadPosition=b}}else e<=o&&(c=i[0]);if(!c){const p=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,p,t)}let f=this.filterReplacedPrimary(c,t);if(!f&&c){const p=c.sn-t.startSN;f=this.filterReplacedPrimary(i[p+1]||null,t)}return this.mapToInitFragWhenRequired(f)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===$s.OK||i===$s.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,n,r){let o=null;if(e.gap&&(o=this.getNextFragment(this.nextLoadPosition,t),o&&!o.gap&&i.nextStart)){const u=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,n,0);if(u!==null&&i.len+u.len>=r){const c=o.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,o}get primaryPrefetch(){if(ew(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(ew(this.config)&&e.type!==At.SUBTITLE){const i=this.hls.interstitialsManager,n=i?.bufferingItem;if(n){const o=n.event;if(o){if(o.appendInPlace||Math.abs(e.start-n.start)>1||n.start===0)return null}else if(e.end<=n.start&&t?.live===!1||e.start>n.end&&n.nextEvent&&(n.nextEvent.appendInPlace||e.start-n.end>1))return null}const r=i?.playerQueue;if(r)for(let o=r.length;o--;){const u=r[o].interstitial;if(u.appendInPlace&&e.start>=u.startTime&&e.end<=u.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let n=-1,r=!1,o=!0;for(let u=0,c=e.length;u-1&&ii.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,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=F6(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=UD(e,i.cc,i.end),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:c}=i,{maxFragLookUpTolerance:d}=n,f=i.partList,p=!!(this.loadingParts&&f!=null&&f.length&&c);p&&!this.bitrateTest&&f[f.length-1].fragment.sn===c.sn&&(o=o.concat(c),u=c.sn);let g;if(et-d||(v=this.media)!=null&&v.paused||!this.startFragRequested?0:d;g=au(r,o,e,_)}else g=o[o.length-1];if(g){const b=g.sn-i.startSN,_=this.fragmentTracker.getState(g);if((_===$s.OK||_===$s.PARTIAL&&g.gap)&&(r=g),r&&g.sn===r.sn&&(!p||f[0].fragment.sn>g.sn||!i.live)&&g.level===r.level){const D=o[b+1];g.sn${e.startSN} fragments: ${n}`),c}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;i=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&As(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==qe.FRAG_LOADING_WAITING_RETRY)&&(this.state=qe.IDLE)}onFragmentOrKeyLoadError(e,t){var i;if(t.chunkMeta&&!t.frag){const D=this.getCurrentContext(t.chunkMeta);D&&(t.frag=D.frag)}const n=t.frag;if(!n||n.type!==e||!this.levels)return;if(this.fragContextChanged(n)){var r;this.warn(`Frag load error must match current frag to retry ${n.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const o=t.details===De.FRAG_GAP;o&&this.fragmentTracker.fragBuffered(n,!0);const u=t.errorAction;if(!u){this.state=qe.ERROR;return}const{action:c,flags:d,retryCount:f=0,retryConfig:p}=u,g=!!p,v=g&&c===nn.RetryRequest,b=g&&!u.resolved&&d===ar.MoveAllAlternatesMatchingHost,_=(i=this.hls.latestLevelDetails)==null?void 0:i.live;if(!v&&b&&As(n)&&!n.endList&&_&&!$D(t))this.resetFragmentErrors(e),this.treatAsGap(n),u.resolved=!0;else if((v||b)&&f=t||i&&!Tx(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=qe.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===qe.PARSING||this.state===qe.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 (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),o}return!1}resetFragmentErrors(e){e===At.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==qe.STOPPED&&(this.state=qe.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const n=ti.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,i),this.state===qe.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==qe.STOPPED&&(this.state=qe.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,n){const r=i.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,d)=>{const f=e.elementaryStreams[d];if(f){const p=f.endPTS-f.startPTS;if(p<=0)return this.warn(`Could not parse fragment ${e.sn} ${d} duration reliably (${p})`),c||!1;const g=n?0:XD(r,e,f.startPTS,f.endPTS,f.startDTS,f.endDTS,this);return this.hls.trigger($.LEVEL_PTS_UPDATED,{details:r,level:i,drift:g,type:d,frag:e,start:f.startPTS,end:f.endPTS}),!0}return c},!1)){var u;const c=((u=this.transmuxer)==null?void 0:u.error)===null;if((i.fragmentError===0||c&&(i.fragmentError<2||e.endList))&&this.treatAsGap(e,i),c){const d=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(d.message),this.hls.trigger($.ERROR,{type:It.MEDIA_ERROR,details:De.FRAG_PARSING_ERROR,fatal:!1,error:d,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=qe.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger($.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===At.MAIN?"level":"track"}fragInfo(e,t=!0,i){var n,r;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${((n=t&&!i?e.startPTS:(i||e).start)!=null?n:NaN).toFixed(3)}-${((r=t&&!i?e.endPTS:(i||e).end)!=null?r:NaN).toFixed(3)}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function ew(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class nL{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=SU(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function SU(s,e){const t=new Uint8Array(e);let i=0;for(let n=0;n0)return s.subarray(t,t+i)}function LU(s,e,t,i){const n=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],o=r>>2&15;if(o>12){const v=new Error(`invalid ADTS sampling index:${o}`);s.emit($.ERROR,$.ERROR,{type:It.MEDIA_ERROR,details:De.FRAG_PARSING_ERROR,fatal:!0,error:v,reason:v.message});return}const u=(r>>6&3)+1,c=e[t+3]>>6&3|(r&1)<<2,d="mp4a.40."+u,f=n[o];let p=o;(u===5||u===29)&&(p-=3);const g=[u<<3|(p&14)>>1,(p&1)<<7|c<<3];return Ui.log(`manifest codec:${i}, parsed codec:${d}, channels:${c}, rate:${f} (ADTS object type:${u} sampling index:${o})`),{config:g,samplerate:f,channelCount:c,codec:d,parsedCodec:d,manifestCodec:i}}function aL(s,e){return s[e]===255&&(s[e+1]&246)===240}function oL(s,e){return s[e+1]&1?7:9}function qb(s,e){return(s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function RU(s,e){return e+5=s.length)return!1;const i=qb(s,e);if(i<=t)return!1;const n=e+i;return n===s.length||Dp(s,n)}return!1}function lL(s,e,t,i,n){if(!s.samplerate){const r=LU(e,t,i,n);if(!r)return;zi(s,r)}}function uL(s){return 1024*9e4/s}function OU(s,e){const t=oL(s,e);if(e+t<=s.length){const i=qb(s,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function cL(s,e,t,i,n){const r=uL(s.samplerate),o=i+n*r,u=OU(e,t);let c;if(u){const{frameLength:p,headerLength:g}=u,v=g+p,b=Math.max(0,t+v-e.length);b?(c=new Uint8Array(v-g),c.set(e.subarray(t+g,e.length),0)):c=e.subarray(t+g,t+v);const _={unit:c,pts:o};return b||s.samples.push(_),{sample:_,length:v,missing:b}}const d=e.length-t;return c=new Uint8Array(d),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:o},length:d,missing:-1}}function MU(s,e){return zb(s,e)&&dg(s,e+6)+10<=s.length-e}function PU(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function lv(s,e=0,t=1/0){return BU(s,e,t,Uint8Array)}function BU(s,e,t,i){const n=FU(s);let r=1;"BYTES_PER_ELEMENT"in i&&(r=i.BYTES_PER_ELEMENT);const o=UU(s)?s.byteOffset:0,u=(o+s.byteLength)/r,c=(o+e)/r,d=Math.floor(Math.max(0,Math.min(c,u))),f=Math.floor(Math.min(d+Math.max(t,0),u));return new i(n,d,f-d)}function FU(s){return s instanceof ArrayBuffer?s:s.buffer}function UU(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function jU(s){const e={key:s.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(s.size<2)return;if(s.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const i=s.data.subarray(1).indexOf(0);if(i===-1)return;const n=cr(lv(s.data,1,i)),r=s.data[2+i],o=s.data.subarray(3+i).indexOf(0);if(o===-1)return;const u=cr(lv(s.data,3+i,o));let c;return n==="-->"?c=cr(lv(s.data,4+i+o)):c=PU(s.data.subarray(4+i+o)),e.mimeType=n,e.pictureType=r,e.description=u,e.data=c,e}function $U(s){if(s.size<2)return;const e=cr(s.data,!0),t=new Uint8Array(s.data.subarray(e.length+1));return{key:s.type,info:e,data:t.buffer}}function HU(s){if(s.size<2)return;if(s.type==="TXXX"){let t=1;const i=cr(s.data.subarray(t),!0);t+=i.length+1;const n=cr(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=cr(s.data.subarray(1));return{key:s.type,info:"",data:e}}function VU(s){if(s.type==="WXXX"){if(s.size<2)return;let t=1;const i=cr(s.data.subarray(t),!0);t+=i.length+1;const n=cr(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=cr(s.data);return{key:s.type,info:"",data:e}}function GU(s){return s.type==="PRIV"?$U(s):s.type[0]==="W"?VU(s):s.type==="APIC"?jU(s):HU(s)}function zU(s){const e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=dg(s,4),i=10;return{type:e,size:t,data:s.subarray(i,i+t)}}const Tm=10,qU=10;function dL(s){let e=0;const t=[];for(;zb(s,e);){const i=dg(s,e+6);s[e+5]>>6&1&&(e+=Tm),e+=Tm;const n=e+i;for(;e+qU0&&u.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:lr.audioId3,duration:Number.POSITIVE_INFINITY});n{if(bt(s))return s*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};let _m=null;const WU=[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],XU=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],QU=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],ZU=[0,1,1,4];function fL(s,e,t,i,n){if(t+24>e.length)return;const r=mL(e,t);if(r&&t+r.frameLength<=e.length){const o=r.samplesPerFrame*9e4/r.sampleRate,u=i+n*o,c={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(c),{sample:c,length:r.frameLength,missing:0}}}function mL(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,c=t===3?3-i:i===3?3:4,d=WU[c*14+n-1]*1e3,p=XU[(t===3?0:t===2?1:2)*3+r],g=u===3?1:2,v=QU[t][i],b=ZU[i],_=v*8*b,S=Math.floor(v*d/p+o)*b;if(_m===null){const L=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);_m=L?parseInt(L[1]):0}return _m&&_m<=87&&i===2&&d>=224e3&&u===0&&(s[e+3]=s[e+3]|128),{sampleRate:p,channelCount:g,frameLength:S,samplesPerFrame:_}}}function Wb(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function pL(s,e){return e+1{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),c=8-u;r[0]=4278190080>>>24+c<>c,t=t?t<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],c=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][c*3+r]*2;if(t+f>e.length)return-1;const p=e[t+6]>>5;let g=0;p===2?g+=2:(p&1&&p!==1&&(g+=2),p&4&&(g+=2));const v=(e[t+6]<<8|e[t+7])>>12-g&1,_=[2,1,2,3,3,4,4,5][p]+v,S=e[t+5]>>3,D=e[t+5]&7,R=new Uint8Array([r<<6|S<<1|D>>2,(D&3)<<6|p<<3|v<<2|c>>4,c<<4&224]),L=1536/u*9e4,P=i+n*L,U=e.subarray(t,t+f);return s.config=R,s.channelCount=_,s.samplerate=u,s.samples.push({unit:U,pts:P}),f}class ij extends Yb{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=Ch(e,0);let i=t?.length||0;if(t&&e[i]===11&&e[i+1]===119&&Kb(t)!==void 0&&yL(e,i)<=16)return!1;for(let n=e.length;i{const o=c6(r);if(sj.test(o.schemeIdUri)){const u=iw(o,t);let c=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const d=o.payload;i.samples.push({data:d,len:d.byteLength,dts:u,pts:u,type:lr.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&o.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const u=iw(o,t);i.samples.push({data:o.payload,len:o.payload.byteLength,dts:u,pts:u,type:lr.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function iw(s,e){return bt(s.presentationTime)?s.presentationTime/s.timeScale:e+s.presentationTimeDelta/s.timeScale}class rj{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Ub(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,cl.cbc)}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 c=new Uint8Array(u);n.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(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{r.data=this.getAvcDecryptedUnit(o,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,n)}).catch(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}}}}class xL{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],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)}}parseNALu(e,t,i){const n=t.byteLength;let r=e.naluState||0;const o=r,u=[];let c=0,d,f,p,g=-1,v=0;for(r===-1&&(g=0,v=this.getNALuType(t,0),r=0,c=1);c=0){const b={data:t.subarray(g,f),type:v};u.push(b)}else{const b=this.getLastNalUnit(e.samples);b&&(o&&c<=4-o&&b.state&&(b.data=b.data.subarray(0,b.data.byteLength-o)),f>0&&(b.data=_r(b.data,t.subarray(0,f)),b.state=0))}c=0&&r>=0){const b={data:t.subarray(g,n),type:v,state:r};u.push(b)}if(u.length===0){const b=this.getLastNalUnit(e.samples);b&&(b.data=_r(b.data,t))}return e.naluState=r,u}}class ph{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&&Ui.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<>>e)!==0)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)}}class aj extends xL{parsePES(e,t,i,n){const r=this.parseNALu(e,i.data,n);let o=this.VideoSample,u,c=!1;i.data=null,o&&r.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(d=>{var f,p;switch(d.type){case 1:{let _=!1;u=!0;const S=d.data;if(c&&S.length>4){const D=this.readSliceType(S);(D===2||D===4||D===7||D===9)&&(_=!0)}if(_){var g;(g=o)!=null&&g.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.frame=!0,o.key=_;break}case 5:u=!0,(f=o)!=null&&f.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 6:{u=!0,Mb(d.data,1,i.pts,t.samples);break}case 7:{var v,b;u=!0,c=!0;const _=d.data,S=this.readSPS(_);if(!e.sps||e.width!==S.width||e.height!==S.height||((v=e.pixelRatio)==null?void 0:v[0])!==S.pixelRatio[0]||((b=e.pixelRatio)==null?void 0:b[1])!==S.pixelRatio[1]){e.width=S.width,e.height=S.height,e.pixelRatio=S.pixelRatio,e.sps=[_];const D=_.subarray(1,4);let R="avc1.";for(let L=0;L<3;L++){let P=D[L].toString(16);P.length<2&&(P="0"+P),R+=P}e.codec=R}break}case 8:u=!0,e.pps=[d.data];break;case 9:u=!0,e.audFound=!0,(p=o)!=null&&p.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:u=!0;break;default:u=!1;break}o&&u&&o.units.push(d)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new ph(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,n=8,r;for(let o=0;o{var f,p;switch(d.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),o.frame=!0,u=!0;break;case 16:case 17:case 18:case 21:if(u=!0,c){var g;(g=o)!=null&&g.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 19:case 20:u=!0,(f=o)!=null&&f.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 39:u=!0,Mb(d.data,2,i.pts,t.samples);break;case 32:u=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=zi(e.params,this.readVPS(d.data)),this.initVPS=d.data),e.vps=[d.data];break;case 33:if(u=!0,c=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],d.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const v=this.readSPS(d.data);e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.codec=v.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const b in v.params)e.params[b]=v.params[b]}this.pushParameterSet(e.sps,d.data,e.vps),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0;break;case 34:if(u=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const v=this.readPPS(d.data);for(const b in v)e.params[b]=v[b]}this.pushParameterSet(e.pps,d.data,e.vps)}break;case 35:u=!0,e.audFound=!0,(p=o)!=null&&p.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:u=!1;break}o&&u&&o.units.push(d)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let n=0;n=2&&e[n]===3&&e[n-1]===0&&e[n-2]===0||(t[i]=e[n],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new ph(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const i=t.readBits(3),n=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:n}}readSPS(e){const t=new ph(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const n=t.readBits(2),r=t.readBoolean(),o=t.readBits(5),u=t.readUByte(),c=t.readUByte(),d=t.readUByte(),f=t.readUByte(),p=t.readUByte(),g=t.readUByte(),v=t.readUByte(),b=t.readUByte(),_=t.readUByte(),S=t.readUByte(),D=t.readUByte(),R=[],L=[];for(let Ze=0;Ze0)for(let Ze=i;Ze<8;Ze++)t.readBits(2);for(let Ze=0;Ze1&&t.readEG();for(let Dt=0;Dt0&&ge<16?(ee=st[ge-1],he=Ve[ge-1]):ge===255&&(ee=t.readBits(16),he=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),Ke=t.readBoolean(),Ke&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(xe=t.readBits(32),Ae=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const Ve=t.readBoolean(),et=t.readBoolean();let vt=!1;(Ve||et)&&(vt=t.readBoolean(),vt&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),vt&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let ot=0;ot<=i;ot++){Te=t.readBoolean();const ht=Te||t.readBoolean();let rt=!1;ht?t.readEG():rt=t.readBoolean();const Gt=rt?1:t.readUEG()+1;if(Ve)for(let Bt=0;Bt>Ze&1)<<31-Ze)>>>0;let xt=pt.toString(16);return o===1&&xt==="2"&&(xt="6"),{codecString:`hvc1.${it}${o}.${xt}.${r?"H":"L"}${D}.B0`,params:{general_tier_flag:r,general_profile_idc:o,general_profile_space:n,general_profile_compatibility_flags:[u,c,d,f],general_constraint_indicator_flags:[p,g,v,b,_,S],general_level_idc:D,bit_depth:Q+8,bit_depth_luma_minus8:Q,bit_depth_chroma_minus8:W,min_spatial_segmentation_idc:j,chroma_format_idc:P,frame_rate:{fixed:Te,fps:Ae/xe}},width:nt,height:yt,pixelRatio:[ee,he]}}readPPS(e){const t=new ph(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const n=t.readBoolean(),r=t.readBoolean();let o=1;return r&&n?o=0:r?o=3:n&&(o=2),{parallelismType:o}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Ws=188;class el{constructor(e,t,i,n){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=n,this.videoParser=null}static probe(e,t){const i=el.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){const t=e.length;let i=Math.min(Ws*5,t-Ws)+1,n=0;for(;n1&&(o===0&&u>2||c+Ws>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:wD[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=el.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=el.createTrack("audio",n),this._id3Track=el.createTrack("id3"),this._txtTrack=el.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}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,c=this._id3Track,d=this._txtTrack;let f=o.pid,p=o.pesData,g=u.pid,v=c.pid,b=u.pesData,_=c.pesData,S=null,D=this.pmtParsed,R=this._pmtId,L=e.length;if(this.remainderData&&(e=_r(this.remainderData,e),L=e.length,this.remainderData=null),L>4;let K;if(O>1){if(K=M+5+e[M+4],K===M+Ws)continue}else K=M+4;switch(N){case f:G&&(p&&(r=Wu(p,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,d,r,!1)),p={data:[],size:0}),p&&(p.data.push(e.subarray(K,M+Ws)),p.size+=M+Ws-K);break;case g:if(G){if(b&&(r=Wu(b,this.logger)))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,M+Ws)),b.size+=M+Ws-K);break;case v:G&&(_&&(r=Wu(_,this.logger))&&this.parseID3PES(c,r),_={data:[],size:0}),_&&(_.data.push(e.subarray(K,M+Ws)),_.size+=M+Ws-K);break;case 0:G&&(K+=e[K]+1),R=this._pmtId=lj(e,K);break;case R:{G&&(K+=e[K]+1);const Q=uj(e,K,this.typeSupported,i,this.observer,this.logger);f=Q.videoPid,f>0&&(o.pid=f,o.segmentCodec=Q.segmentVideoCodec),g=Q.audioPid,g>0&&(u.pid=g,u.segmentCodec=Q.segmentAudioCodec),v=Q.id3Pid,v>0&&(c.pid=v),S!==null&&!D&&(this.logger.warn(`MPEG-TS PMT found at ${M} after unknown PID '${S}'. Backtracking to sync byte @${P} to parse all TS packets.`),S=null,M=P-188),D=this.pmtParsed=!0;break}case 17:case 8191:break;default:S=N;break}}else U++;U>0&&Cx(this.observer,new Error(`Found ${U} TS packet/s that do not start with 0x47`),void 0,this.logger),o.pesData=p,u.pesData=b,c.pesData=_;const V={audioTrack:u,videoTrack:o,id3Track:c,textTrack:d};return n&&this.extractRemainingSamples(V),V}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,c=n.pesData;let d;if(o&&(d=Wu(o,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,r,d,!0),i.pesData=null)):i.pesData=o,u&&(d=Wu(u,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,d);break;case"mp3":this.parseMPEGPES(t,d);break;case"ac3":this.parseAC3PES(t,d);break}t.pesData=null}else u!=null&&u.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=u;c&&(d=Wu(c,this.logger))?(this.parseID3PES(n,d),n.pesData=null):n.pesData=c}demuxSampleAes(e,t,i){const n=this.demux(e,i,!0,!this.config.progressive),r=this.sampleAes=new rj(this.observer,this.config,t);return this.decrypt(n,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new aj:e==="hevc"&&(this.videoParser=new oj))}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.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let i=0;const n=this.aacOverFlow;let r=t.data;if(n){this.aacOverFlow=null;const p=n.missing,g=n.sample.unit.byteLength;if(p===-1)r=_r(n.sample.unit,r);else{const v=g-p;n.sample.unit.set(r.subarray(0,p),v),e.samples.push(n.sample),i=n.missing}}let o,u;for(o=i,u=r.length;o0;)u+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=zi({},t,{type:this._videoTrack?lr.emsg:lr.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Ax(s,e){return((s[e+1]&31)<<8)+s[e+2]}function lj(s,e){return(s[e+10]&31)<<8|s[e+11]}function uj(s,e,t,i,n,r){const o={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},u=(s[e+1]&15)<<8|s[e+2],c=e+3+u-4,d=(s[e+10]&15)<<8|s[e+11];for(e+=12+d;e0){let g=e+5,v=p;for(;v>2;){s[g]===106&&(t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(o.audioPid=f,o.segmentAudioCodec="ac3"));const _=s[g+1]+2;g+=_,v-=_}}break;case 194:case 135:return Cx(n,new Error("Unsupported EC-3 in M2TS found"),void 0,r),o;case 36:o.videoPid===-1&&(o.videoPid=f,o.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=p+5}return o}function Cx(s,e,t,i){i.warn(`parsing error: ${e.message}`),s.emit($.ERROR,$.ERROR,{type:It.MEDIA_ERROR,details:De.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function uv(s,e){e.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function Wu(s,e){let t=0,i,n,r,o,u;const c=s.data;if(!s||s.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=_r(c[0],c[1]),c.splice(1,1);if(i=c[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(n=(i[4]<<8)+i[5],n&&n>s.size-6)return null;const f=i[7];f&192&&(o=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,f&64?(u=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,o-u>60*9e4&&(e.warn(`${Math.round((o-u)/9e4)}s delta between PTS and DTS, align them`),o=u)):u=o),r=i[8];let p=r+9;if(s.size<=p)return null;s.size-=p;const g=new Uint8Array(s.size);for(let v=0,b=c.length;v_){p-=_;continue}else i=i.subarray(p),_-=p,p=0;g.set(i,t),t+=_}return n&&(n-=r+3),{data:g,pts:o,dts:u,len:n}}return null}class cj{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 Yo=Math.pow(2,32)-1;class Ce{static init(){Ce.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in Ce.types)Ce.types.hasOwnProperty(e)&&(Ce.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]);Ce.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]);Ce.STTS=Ce.STSC=Ce.STCO=r,Ce.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Ce.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Ce.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Ce.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]),c=new Uint8Array([0,0,0,1]);Ce.FTYP=Ce.box(Ce.types.ftyp,o,c,o,u),Ce.DINF=Ce.box(Ce.types.dinf,Ce.box(Ce.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>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 Ce.box(Ce.types.mdia,Ce.mdhd(e.timescale||0,e.duration||0),Ce.hdlr(e.type),Ce.minf(e))}static mfhd(e){return Ce.box(Ce.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"?Ce.box(Ce.types.minf,Ce.box(Ce.types.smhd,Ce.SMHD),Ce.DINF,Ce.stbl(e)):Ce.box(Ce.types.minf,Ce.box(Ce.types.vmhd,Ce.VMHD),Ce.DINF,Ce.stbl(e))}static moof(e,t,i){return Ce.box(Ce.types.moof,Ce.mfhd(e),Ce.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=Ce.trak(e[t]);return Ce.box.apply(null,[Ce.types.moov,Ce.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(Ce.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=Ce.trex(e[t]);return Ce.box.apply(null,[Ce.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(Yo+1)),n=Math.floor(t%(Yo+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 Ce.box(Ce.types.mvhd,r)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let n,r;for(n=0;n>>8&255),t.push(o&255),t=t.concat(Array.prototype.slice.call(r));for(n=0;n>>8&255),i.push(o&255),i=i.concat(Array.prototype.slice.call(r));const u=Ce.box(Ce.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),c=e.width,d=e.height,f=e.pixelRatio[0],p=e.pixelRatio[1];return Ce.box(Ce.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,d>>8&255,d&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,Ce.box(Ce.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Ce.box(Ce.types.pasp,new Uint8Array([f>>24,f>>16&255,f>>8&255,f&255,p>>24,p>>16&255,p>>8&255,p&255])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return Ce.box(Ce.types.mp4a,Ce.audioStsd(e),Ce.box(Ce.types.esds,Ce.esds(e)))}static mp3(e){return Ce.box(Ce.types[".mp3"],Ce.audioStsd(e))}static ac3(e){return Ce.box(Ce.types["ac-3"],Ce.audioStsd(e),Ce.box(Ce.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return Ce.box(Ce.types.stsd,Ce.STSD,Ce.mp4a(e));if(t==="ac3"&&e.config)return Ce.box(Ce.types.stsd,Ce.STSD,Ce.ac3(e));if(t==="mp3"&&e.codec==="mp3")return Ce.box(Ce.types.stsd,Ce.STSD,Ce.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return Ce.box(Ce.types.stsd,Ce.STSD,Ce.avc1(e));if(t==="hevc"&&e.vps)return Ce.box(Ce.types.stsd,Ce.STSD,Ce.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,i=(e.duration||0)*(e.timescale||0),n=e.width||0,r=e.height||0,o=Math.floor(i/(Yo+1)),u=Math.floor(i%(Yo+1));return Ce.box(Ce.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=Ce.sdtp(e),n=e.id,r=Math.floor(t/(Yo+1)),o=Math.floor(t%(Yo+1));return Ce.box(Ce.types.traf,Ce.box(Ce.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255])),Ce.box(Ce.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])),Ce.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,Ce.box(Ce.types.trak,Ce.tkhd(e),Ce.mdia(e))}static trex(e){const t=e.id;return Ce.box(Ce.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,c,d,f,p,g;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>>24&255,d>>>16&255,d>>>8&255,d&255,f>>>24&255,f>>>16&255,f>>>8&255,f&255,p.isLeading<<2|p.dependsOn,p.isDependedOn<<6|p.hasRedundancy<<4|p.paddingValue<<1|p.isNonSync,p.degradPrio&61440,p.degradPrio&15,g>>>24&255,g>>>16&255,g>>>8&255,g&255],12+16*u);return Ce.box(Ce.types.trun,o)}static initSegment(e){Ce.types||Ce.init();const t=Ce.moov(e);return _r(Ce.FTYP,t)}static hvc1(e){const t=e.params,i=[e.vps,e.sps,e.pps],n=4,r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),n-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]);let o=r.length;for(let b=0;b>8,i[b][_].length&255]),o),o+=2,u.set(i[b][_],o),o+=i[b][_].length}const d=Ce.box(Ce.types.hvcC,u),f=e.width,p=e.height,g=e.pixelRatio[0],v=e.pixelRatio[1];return Ce.box(Ce.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,f>>8&255,f&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]),d,Ce.box(Ce.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Ce.box(Ce.types.pasp,new Uint8Array([g>>24,g>>16&255,g>>8&255,g&255,v>>24,v>>16&255,v>>8&255,v&255])))}}Ce.types=void 0;Ce.HDLR_TYPES=void 0;Ce.STTS=void 0;Ce.STSC=void 0;Ce.STCO=void 0;Ce.STSZ=void 0;Ce.VMHD=void 0;Ce.SMHD=void 0;Ce.STSD=void 0;Ce.FTYP=void 0;Ce.DINF=void 0;const bL=9e4;function Xb(s,e,t=1,i=!1){const n=s*e*t;return i?Math.round(n):n}function dj(s,e,t=1,i=!1){return Xb(s,e,1/t,i)}function Yd(s,e=!1){return Xb(s,1e3,1/bL,e)}function hj(s,e=1){return Xb(s,bL,1/e)}function sw(s){const{baseTime:e,timescale:t,trackId:i}=s;return`${e/t} (${e}/${t}) trackId: ${i}`}const fj=10*1e3,mj=1024,pj=1152,gj=1536;let Xu=null,cv=null;function nw(s,e,t,i){return{duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:s?2:1,isNonSync:s?0:1}}}class $m extends wr{constructor(e,t,i,n){if(super("mp4-remuxer",n),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,Xu===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Xu=o?parseInt(o[1]):0}if(cv===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);cv=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&sw(t)} > ${e&&sw(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,n=e.reduce((r,o)=>{let u=o.pts,c=u-r;return c<-4294967296&&(t=!0,u=or(u,i),c=u-r),c>0?r:u},i);return t&&this.debug("PTS rollover detected"),n}remux(e,t,i,n,r,o,u,c){let d,f,p,g,v,b,_=r,S=r;const D=e.pid>-1,R=t.pid>-1,L=t.samples.length,P=e.samples.length>0,U=u&&L>0||L>1;if((!D||P)&&(!R||U)||this.ISGenerated||u){if(this.ISGenerated){var M,G,N,O;const re=this.videoTrackConfig;(re&&(t.width!==re.width||t.height!==re.height||((M=t.pixelRatio)==null?void 0:M[0])!==((G=re.pixelRatio)==null?void 0:G[0])||((N=t.pixelRatio)==null?void 0:N[1])!==((O=re.pixelRatio)==null?void 0:O[1]))||!re&&U||this.nextAudioTs===null&&P)&&this.resetInitSegment()}this.ISGenerated||(p=this.generateIS(e,t,r,o));const K=this.isVideoContiguous;let Q=-1,W;if(U&&(Q=yj(t.samples),!K&&this.config.forceKeyFrameOnDiscontinuity))if(b=!0,Q>0){this.warn(`Dropped ${Q} out of ${L} video samples due to a missing keyframe`);const re=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(Q),t.dropped+=Q,S+=(t.samples[0].pts-re)/t.inputTimeScale,W=S}else Q===-1&&(this.warn(`No keyframe found out of ${L} video samples`),b=!1);if(this.ISGenerated){if(P&&U){const re=this.getVideoStartPts(t.samples),Y=(or(e.samples[0].pts,re)-re)/t.inputTimeScale;_+=Math.max(0,Y),S+=Math.max(0,-Y)}if(P){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),p=this.generateIS(e,t,r,o)),f=this.remuxAudio(e,_,this.isAudioContiguous,o,R||U||c===At.AUDIO?S:void 0),U){const re=f?f.endPTS-f.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),p=this.generateIS(e,t,r,o)),d=this.remuxVideo(t,S,K,re)}}else U&&(d=this.remuxVideo(t,S,K,0));d&&(d.firstKeyFrame=Q,d.independent=Q!==-1,d.firstKeyFramePTS=W)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(v=TL(i,r,this._initPTS,this._initDTS)),n.samples.length&&(g=_L(n,r,this._initPTS))),{audio:f,video:d,initSegment:p,independent:b,text:g,id3:v}}computeInitPts(e,t,i,n){const r=Math.round(i*t);let o=or(e,r);if(o0?j-1:j].dts&&(R=!0)}R&&o.sort(function(j,ee){const he=j.dts-ee.dts,Te=j.pts-ee.pts;return he||Te}),b=o[0].dts,_=o[o.length-1].dts;const P=_-b,U=P?Math.round(P/(c-1)):v||e.inputTimeScale/30;if(i){const j=b-L,ee=j>U,he=j<-1;if((ee||he)&&(ee?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Yd(j,!0)} ms (${j}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Yd(-j,!0)} ms (${j}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!he||L>=o[0].pts||Xu)){b=L;const Te=o[0].pts-j;if(ee)o[0].dts=b,o[0].pts=Te;else{let xe=!0;for(let Ae=0;AeTe&&xe);Ae++){const Ke=o[Ae].pts;if(o[Ae].dts-=j,o[Ae].pts-=j,Ae0?ee.dts-o[j-1].dts:U;if(xe=j>0?ee.pts-o[j-1].pts:U,Ke.stretchShortVideoTrack&&this.nextAudioTs!==null){const nt=Math.floor(Ke.maxBufferHole*r),yt=(n?S+n*r:this.nextAudioTs+f)-ee.pts;yt>nt?(v=yt-lt,v<0?v=lt:Q=!0,this.log(`It is approximately ${yt/90} ms to the next segment; using duration ${v/90} ms for the last video frame.`)):v=lt}else v=lt}const Ae=Math.round(ee.pts-ee.dts);W=Math.min(W,v),J=Math.max(J,v),re=Math.min(re,xe),Y=Math.max(Y,xe),u.push(nw(ee.key,v,Te,Ae))}if(u.length){if(Xu){if(Xu<70){const j=u[0].flags;j.dependsOn=2,j.isNonSync=0}}else if(cv&&Y-re0&&(n&&Math.abs(L-(D+R))<9e3||Math.abs(or(_[0].pts,L)-(D+R))<20*f),_.forEach(function(Y){Y.pts=or(Y.pts,L)}),!i||D<0){const Y=_.length;if(_=_.filter(z=>z.pts>=0),Y!==_.length&&this.warn(`Removed ${_.length-Y} of ${Y} samples (initPTS ${R} / ${o})`),!_.length)return;r===0?D=0:n&&!b?D=Math.max(0,L-R):D=_[0].pts-R}if(e.segmentCodec==="aac"){const Y=this.config.maxAudioFramesDrift;for(let z=0,Z=D+R;z<_.length;z++){const ie=_[z],ce=ie.pts,j=ce-Z,ee=Math.abs(1e3*j/o);if(j<=-Y*f&&b)z===0&&(this.warn(`Audio frame @ ${(ce/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*j/o)} ms.`),this.nextAudioTs=D=ce-R,Z=ce);else if(j>=Y*f&&ee0){M+=S;try{V=new Uint8Array(M)}catch(ee){this.observer.emit($.ERROR,$.ERROR,{type:It.MUX_ERROR,details:De.REMUX_ALLOC_ERROR,fatal:!1,error:ee,bytes:M,reason:`fail allocating audio mdat ${M}`});return}g||(new DataView(V.buffer).setUint32(0,M),V.set(Ce.types.mdat,4))}else return;V.set(ie,S);const j=ie.byteLength;S+=j,v.push(nw(!0,d,j,0)),U=ce}const N=v.length;if(!N)return;const O=v[v.length-1];D=U-R,this.nextAudioTs=D+c*O.duration;const K=g?new Uint8Array(0):Ce.moof(e.sequenceNumber++,P/c,zi({},e,{samples:v}));e.samples=[];const Q=(P-R)/o,W=this.nextAudioTs/o,J={data1:K,data2:V,startPTS:Q,endPTS:W,startDTS:Q,endDTS:W,type:"audio",hasAudio:!0,hasVideo:!1,nb:N};return this.isAudioContiguous=!0,J}}function or(s,e){let t;if(e===null)return s;for(e4294967296;)s+=t;return s}function yj(s){for(let e=0;eo.pts-u.pts);const r=s.samples;return s.samples=[],{samples:r}}class vj extends wr{constructor(e,t,i,n){super("passthrough-remuxer",n),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,n){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,n),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:i,videoCodec:n}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:r,video:o}=this.initData=kD(e);if(t)r6(e,t);else{const c=r||o;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}r&&(i=rw(r,Wi.AUDIO,this)),o&&(n=rw(o,Wi.VIDEO,this));const u={};r&&o?u.audiovideo={container:"video/mp4",codec:i+","+n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:r?u.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:e,id:"audio"}:o?u.video={container:"video/mp4",codec:n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=u}remux(e,t,i,n,r,o){var u,c;let{initPTS:d,lastEndTime:f}=this;const p={audio:void 0,video:void 0,text:n,id3:i,initSegment:void 0};bt(f)||(f=this.lastEndTime=r||0);const g=t.samples;if(!g.length)return p;const v={initPTS:void 0,timescale:void 0,trackId:void 0};let b=this.initData;if((u=b)!=null&&u.length||(this.generateInitSegment(g),b=this.initData),!((c=b)!=null&&c.length))return this.warn("Failed to generate initSegment."),p;this.emitInitSegment&&(v.tracks=this.initTracks,this.emitInitSegment=!1);const _=o6(g,b,this),S=b.audio?_[b.audio.id]:null,D=b.video?_[b.video.id]:null,R=Sm(D,1/0),L=Sm(S,1/0),P=Sm(D,0,!0),U=Sm(S,0,!0);let V=r,M=0;const G=S&&(!D||!d&&L0?this.lastEndTime=K:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const Q=!!b.audio,W=!!b.video;let re="";Q&&(re+="audio"),W&&(re+="video");const J=(b.audio?b.audio.encrypted:!1)||(b.video?b.video.encrypted:!1),Y={data1:g,startPTS:O,startDTS:O,endPTS:K,endDTS:K,type:re,hasAudio:Q,hasVideo:W,nb:1,dropped:0,encrypted:J};p.audio=Q&&!W?Y:void 0,p.video=W?Y:void 0;const z=D?.sampleCount;if(z){const Z=D.keyFrameIndex,ie=Z!==-1;Y.nb=z,Y.dropped=Z===0||this.isVideoContiguous?0:ie?Z:z,Y.independent=ie,Y.firstKeyFrame=Z,ie&&D.keyFrameStart&&(Y.firstKeyFramePTS=(D.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(p.independent=ie),this.isVideoContiguous||(this.isVideoContiguous=ie),Y.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${Z}/${z} dropped: ${Y.dropped} start: ${Y.firstKeyFramePTS||"NA"}`)}return p.initSegment=v,p.id3=TL(i,r,d,d),n.samples.length&&(p.text=_L(n,r,d)),p}}function Sm(s,e,t=!1){return s?.start!==void 0?(s.start+(t?s.duration:0))/s.timescale:e}function xj(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 rw(s,e,t){const i=s.codec;return i&&i.length>4?i:e===Wi.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?Tp(i,!1):(t.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):(t.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}let Xa;try{Xa=self.performance.now.bind(self.performance)}catch{Xa=Date.now}const Hm=[{demux:nj,remux:vj},{demux:el,remux:$m},{demux:ej,remux:$m},{demux:ij,remux:$m}];Hm.splice(2,0,{demux:tj,remux:$m});class aw{constructor(e,t,i,n,r,o){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=r,this.logger=o}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,n){const r=i.transmuxing;r.executeStart=Xa();let o=new Uint8Array(e);const{currentTransmuxState:u,transmuxConfig:c}=this;n&&(this.currentTransmuxState=n);const{contiguous:d,discontinuity:f,trackSwitch:p,accurateTimeOffset:g,timeOffset:v,initSegmentChange:b}=n||u,{audioCodec:_,videoCodec:S,defaultInitPts:D,duration:R,initSegmentData:L}=c,P=bj(o,t);if(P&&gc(P.method)){const G=this.getDecrypter(),N=$b(P.method);if(G.isSync()){let O=G.softwareDecrypt(o,P.key.buffer,P.iv.buffer,N);if(i.part>-1){const Q=G.flush();O=Q&&Q.buffer}if(!O)return r.executeEnd=Xa(),dv(i);o=new Uint8Array(O)}else return this.asyncResult=!0,this.decryptionPromise=G.webCryptoDecrypt(o,P.key.buffer,P.iv.buffer,N).then(O=>{const K=this.push(O,null,i);return this.decryptionPromise=null,K}),this.decryptionPromise}const U=this.needsProbing(f,p);if(U){const G=this.configureTransmuxer(o);if(G)return this.logger.warn(`[transmuxer] ${G.message}`),this.observer.emit($.ERROR,$.ERROR,{type:It.MEDIA_ERROR,details:De.FRAG_PARSING_ERROR,fatal:!1,error:G,reason:G.message}),r.executeEnd=Xa(),dv(i)}(f||p||b||U)&&this.resetInitSegment(L,_,S,R,t),(f||b||U)&&this.resetInitialTimestamp(D),d||this.resetContiguity();const V=this.transmux(o,P,v,g,i);this.asyncResult=kh(V);const M=this.currentTransmuxState;return M.contiguous=!0,M.discontinuity=!1,M.trackSwitch=!1,r.executeEnd=Xa(),V}flush(e){const t=e.transmuxing;t.executeStart=Xa();const{decrypter:i,currentTransmuxState:n,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const o=[],{timeOffset:u}=n;if(i){const p=i.flush();p&&o.push(this.push(p.buffer,null,e))}const{demuxer:c,remuxer:d}=this;if(!c||!d){t.executeEnd=Xa();const p=[dv(e)];return this.asyncResult?Promise.resolve(p):p}const f=c.flush(u);return kh(f)?(this.asyncResult=!0,f.then(p=>(this.flushRemux(o,p,e),o))):(this.flushRemux(o,f,e),this.asyncResult?Promise.resolve(o):o)}flushRemux(e,t,i){const{audioTrack:n,videoTrack:r,id3Track:o,textTrack:u}=t,{accurateTimeOffset:c,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===At.MAIN?"level":"track"} ${i.level}`);const f=this.remuxer.remux(n,r,o,u,d,c,!0,this.id);e.push({remuxResult:f,chunkMeta:i}),i.transmuxing.executeEnd=Xa()}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:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,o,u,c,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}=this;let r;for(let p=0,g=Hm.length;p0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const dv=s=>({remuxResult:{},chunkMeta:s});function kh(s){return"then"in s&&s.then instanceof Function}class Tj{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 _j{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}}let ow=0;class SL{constructor(e,t,i,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=ow++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=c=>{const d=c.data,f=this.hls;if(!(!f||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case"init":{var p;const g=(p=this.workerContext)==null?void 0:p.objectURL;g&&self.URL.revokeObjectURL(g);break}case"transmuxComplete":{this.handleTransmuxComplete(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{f.logger[d.data.logType]&&f.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,f.trigger(d.event,d.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const d=new Error(`${c.message} (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger($.ERROR,{type:It.OTHER_ERROR,details:De.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;const o=(c,d)=>{d=d||{},d.frag=this.frag||void 0,c===$.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new Gb,this.observer.on($.FRAG_DECRYPTED,o),this.observer.on($.ERROR,o);const u=_2(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(r.workerPath||AU()){try{r.workerPath?(c.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=kU(r.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=CU());const{worker:f}=this.workerContext;f.addEventListener("message",this.onWorkerMessage),f.addEventListener("error",this.onWorkerError),f.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:u,id:t,config:Qi(r)})}catch(f){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,f),this.terminateWorker(),this.error=null,this.transmuxer=new aw(this.observer,u,r,"",t,e.logger)}return}}this.transmuxer=new aw(this.observer,u,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=ow++;const t=this.hls.config,i=_2(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:Qi(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),DU(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,n,r,o,u,c,d,f){var p,g;d.transmuxing.start=self.performance.now();const{instanceNo:v,transmuxer:b}=this,_=o?o.start:r.start,S=r.decryptdata,D=this.frag,R=!(D&&r.cc===D.cc),L=!(D&&d.level===D.level),P=D?d.sn-D.sn:-1,U=this.part?d.part-this.part.index:-1,V=P===0&&d.id>1&&d.id===D?.stats.chunkCount,M=!L&&(P===1||P===0&&(U===1||V&&U<=0)),G=self.performance.now();(L||P||r.stats.parsing.start===0)&&(r.stats.parsing.start=G),o&&(U||!M)&&(o.stats.parsing.start=G);const N=!(D&&((p=r.initSegment)==null?void 0:p.url)===((g=D.initSegment)==null?void 0:g.url)),O=new _j(R,M,c,L,_,N);if(!M||R||N){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===At.MAIN?"level":"track"}: ${d.level} id: ${d.id} discontinuity: ${R} trackSwitch: ${L} contiguous: ${M} accurateTimeOffset: ${c} timeOffset: ${_} initSegmentChange: ${N}`);const K=new Tj(i,n,t,u,f);this.configureTransmuxer(K)}if(this.frag=r,this.part=o,this.workerContext)this.workerContext.worker.postMessage({instanceNo:v,cmd:"demux",data:e,decryptdata:S,chunkMeta:d,state:O},e instanceof ArrayBuffer?[e]:[]);else if(b){const K=b.push(e,S,d,O);kh(K)?K.then(Q=>{this.handleTransmuxComplete(Q)}).catch(Q=>{this.transmuxerError(Q,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(K)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){const n=i.flush(e);kh(n)?n.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger($.ERROR,{type:It.MEDIA_ERROR,details:De.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const lw=100;class Sj extends Vb{constructor(e,t,i){super(e,t,i,"audio-stream-controller",At.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on($.LEVEL_LOADED,this.onLevelLoaded,this),e.on($.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on($.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on($.BUFFER_RESET,this.onBufferReset,this),e.on($.BUFFER_CREATED,this.onBufferCreated,this),e.on($.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on($.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on($.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on($.FRAG_LOADING,this.onFragLoading,this),e.on($.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off($.LEVEL_LOADED,this.onLevelLoaded,this),e.off($.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off($.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off($.BUFFER_RESET,this.onBufferReset,this),e.off($.BUFFER_CREATED,this.onBufferCreated,this),e.off($.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off($.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off($.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off($.FRAG_LOADING,this.onFragLoading,this),e.off($.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r,trackId:o}){if(i===At.MAIN){const u=t.cc,c=this.fragCurrent;if(this.initPTS[u]={baseTime:n,timescale:r,trackId:o},this.log(`InitPTS for cc: ${u} found from main: ${n/r} (${n}/${r}) trackId: ${o}`),this.mainAnchor=t,this.state===qe.WAITING_INIT_PTS){const d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==u)&&this.syncWithAnchor(t,d?.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==u?(c.abortRequests(),this.syncWithAnchor(t,c)):this.state===qe.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;const n=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(t&&n?.cc===t.cc)return;const r=(n||e).cc,o=this.getLevelDetails(),u=this.getLoadPosition(),c=UD(o,r,u);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===qe.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=qe.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(lw),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=qe.IDLE):this.state=qe.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case qe.IDLE:this.doTickIdle();break;case qe.WAITING_TRACK:{const{levels:e,trackId:t}=this,i=e?.[t],n=i?.details;if(n&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(n))break;this.state=qe.WAITING_INIT_PTS}break}case qe.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case qe.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:n,complete:r}=e,o=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=qe.FRAG_LOADING;const u=n.flush().buffer,c={frag:t,part:i,payload:u,networkDetails:null};this._handleFragmentLoadProgress(c),r&&super._handleFragmentLoadComplete(c)}else o&&o.cc!==e.frag.cc&&this.syncWithAnchor(o,e.frag)}else this.state=qe.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:n,trackId:r}=this,o=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!o.startFragPrefetch)||!(i!=null&&i[r]))return;const u=i[r],c=u.details;if(!c||this.waitForLive(u)||this.waitForCdnTuneIn(c)){this.state=qe.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,Wi.AUDIO,At.AUDIO));const f=this.getFwdBufferInfo(d,At.AUDIO);if(f===null)return;if(!this.switchingTrack&&this._streamEnded(f,c)){t.trigger($.BUFFER_EOS,{type:"audio"}),this.state=qe.ENDED;return}const p=f.len,g=t.maxBufferLength,v=c.fragments,b=v[0].start,_=this.getLoadPosition(),S=this.flushing?_:f.end;if(this.switchingTrack&&n){const L=_;c.PTSKnown&&Lb||f.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=b+.05)}if(p>=g&&!this.switchingTrack&&SR.end){const P=this.fragmentTracker.getFragAtPos(S,At.MAIN);P&&P.end>R.end&&(R=P,this.mainFragLoading={frag:P,targetBufferTime:null})}if(D.start>R.end)return}this.loadFragment(D,u,S)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new wh(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.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==qe.STOPPED&&(this.setInterval(lw),this.state=qe.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded($.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:n}=this,{details:r,id:o,groupId:u,track:c}=t;if(!n){this.warn(`Audio tracks reset while loading track ${o} "${c.name}" of "${u}"`);return}const d=this.mainDetails;if(!d||r.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==qe.STOPPED&&(this.state=qe.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${o} "${c.name}" of "${u}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const f=n[o];let p=0;if(r.live||(i=f.details)!=null&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(f.details){var g;p=this.alignPlaylists(r,f.details,(g=this.levelLastLoaded)==null?void 0:g.details)}r.alignedSliding||(sL(r,d),r.alignedSliding||kp(r,d),p=r.fragmentStart)}f.details=r,this.levelLastLoaded=f,this.startFragRequested||this.setStartPosition(d,p),this.hls.trigger($.AUDIO_TRACK_UPDATED,{details:r,id:o,groupId:t.groupId}),this.state===qe.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=qe.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:n,payload:r}=e,{config:o,trackId:u,levels:c}=this;if(!c){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 d=c[u];if(!d){this.warn("Audio track is undefined on fragment load progress");return}const f=d.details;if(!f){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const p=o.defaultAudioCodec||d.audioCodec||"mp4a.40.2";let g=this.transmuxer;g||(g=this.transmuxer=new SL(this.hls,At.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const v=this.initPTS[i.cc],b=(t=i.initSegment)==null?void 0:t.data;if(v!==void 0){const S=n?n.index:-1,D=S!==-1,R=new jb(i.level,i.sn,i.stats.chunkCount,r.byteLength,S,D);g.push(r,b,p,"",i,n,f.totalduration,!1,R,v)}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:_}=this.waitingData=this.waitingData||{frag:i,part:n,cache:new nL,complete:!1};_.push(new Uint8Array(r)),this.state!==qe.STOPPED&&(this.state=qe.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===At.MAIN&&As(t.frag)&&(this.mainFragLoading=t,this.state===qe.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:i,part:n}=t;if(i.type!==At.AUDIO){!this.audioOnly&&i.type===At.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);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(As(i)){this.fragPrevious=i;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger($.AUDIO_TRACK_SWITCHED,Fi({},r)))}this.fragBufferedComplete(i,n),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=qe.ERROR;return}switch(t.details){case De.FRAG_GAP:case De.FRAG_PARSING_ERROR:case De.FRAG_DECRYPT_ERROR:case De.FRAG_LOAD_ERROR:case De.FRAG_LOAD_TIMEOUT:case De.KEY_LOAD_ERROR:case De.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(At.AUDIO,t);break;case De.AUDIO_TRACK_LOAD_ERROR:case De.AUDIO_TRACK_LOAD_TIMEOUT:case De.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===qe.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===yi.AUDIO_TRACK&&(this.state=qe.IDLE);break;case De.BUFFER_ADD_CODEC_ERROR:case De.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case De.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case De.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==Wi.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Wi.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===qe.ENDED&&(this.state=qe.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,At.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:c,part:d,level:f}=u,{details:p}=f,{audio:g,text:v,id3:b,initSegment:_}=r;if(this.fragContextChanged(c)||!p){this.fragmentTracker.removeFragment(c);return}if(this.state=qe.PARSING,this.switchingTrack&&g&&this.completeAudioSwitch(this.switchingTrack),_!=null&&_.tracks){const S=c.initSegment||c;if(this.unhandledEncryptionError(_,c))return;this._bufferInitSegment(f,_.tracks,S,o),n.trigger($.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:i,tracks:_.tracks})}if(g){const{startPTS:S,endPTS:D,startDTS:R,endDTS:L}=g;d&&(d.elementaryStreams[Wi.AUDIO]={startPTS:S,endPTS:D,startDTS:R,endDTS:L}),c.setElementaryStreamInfo(Wi.AUDIO,S,D,R,L),this.bufferFragmentData(g,c,d,o)}if(b!=null&&(t=b.samples)!=null&&t.length){const S=zi({id:i,frag:c,details:p},b);n.trigger($.FRAG_PARSING_METADATA,S)}if(v){const S=zi({id:i,frag:c,details:p},v);n.trigger($.FRAG_PARSING_USERDATA,S)}}_bufferInitSegment(e,t,i,n){if(this.state!==qe.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=At.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($.BUFFER_CODECS,t);const u=r.initSegment;if(u!=null&&u.byteLength){const c={type:"audio",frag:i,part:null,chunkMeta:n,parent:i.type,data:u};this.hls.trigger($.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===$s.NOT_LOADED||n===$s.PARTIAL){var r;if(!As(e))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=qe.WAITING_INIT_PTS;const o=this.mainDetails;o&&o.fragmentStart!==t.details.fragmentStart&&kp(t.details,o)}else 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;iu({name:t,lang:i,assocLang:n,characteristics:r,audioCodec:o,channels:u},e,Gl)||(Sp(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger($.AUDIO_TRACK_SWITCHED,Fi({},e))}}class Qb extends wr{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const n=t?.renditionReports;if(n){let r=-1;for(let o=0;o=0&&f>t.partTarget&&(c+=1)}const d=i&&S2(i);return new E2(u,c>=0?c:void 0,d)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return 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;n.advancedDateTime=Date.now()-u;const c=this.hls.config.timelineOffset;if(c!==n.appliedTimelineOffset){const f=Math.max(c||0,0);n.appliedTimelineOffset=f,n.fragments.forEach(p=>{p.setStart(p.playlistOffset+f)})}if(n.live||i!=null&&i.live){const f="levelInfo"in t?t.levelInfo:t.track;if(n.reloaded(i),i&&n.fragments.length>0){pU(i,n,this);const R=n.playlistParsingError;if(R){this.warn(R);const L=this.hls;if(!L.config.ignorePlaylistParsingErrors){var d;const{networkDetails:P}=t;L.trigger($.ERROR,{type:It.NETWORK_ERROR,details:De.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:R,reason:R.message,level:t.level||void 0,parent:(d=n.fragments[0])==null?void 0:d.type,networkDetails:P,stats:r});return}n.playlistParsingError=null}}n.requestScheduled===-1&&(n.requestScheduled=r.loading.start);const p=this.hls.mainForwardBufferInfo,g=p?p.end-p.len:0,v=(n.edge-g)*1e3,b=ZD(n,v);if(n.requestScheduled+b0){if(N>n.targetduration*3)this.log(`Playlist last advanced ${G.toFixed(2)}s ago. Omitting segment and part directives.`),S=void 0,D=void 0;else if(i!=null&&i.tuneInGoal&&N-n.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${O} with playlist age: ${n.age}`),O=0;else{const K=Math.floor(O/n.targetduration);if(S+=K,D!==void 0){const Q=Math.round(O%n.targetduration/n.partTarget);D+=Q}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${G.toFixed(2)}s goal: ${O} skip sn ${K} to part ${D}`)}n.tuneInGoal=O}if(_=this.getDeliveryDirectives(n,t.deliveryDirectives,S,D),R||!M){n.requestScheduled=o,this.loadingPlaylist(f,_);return}}else(n.canBlockReload||n.canSkipUntil)&&(_=this.getDeliveryDirectives(n,t.deliveryDirectives,S,D));_&&S!==void 0&&n.canBlockReload&&(n.requestScheduled=r.loading.first+Math.max(b-u*2,b/2)),this.scheduleLoading(f,_,n)}else this.clearTimer()}scheduleLoading(e,t,i){const n=i||e.details;if(!n){this.loadingPlaylist(e,t);return}const r=self.performance.now(),o=n.requestScheduled;if(r>=o){this.loadingPlaylist(e,t);return}const u=o-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(u)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),u)}getDeliveryDirectives(e,t,i,n){let r=S2(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,n=t.part,r=Um.No),new E2(i,n,r)}checkRetry(e){const t=e.details,i=Ep(e),n=e.errorAction,{action:r,retryCount:o=0,retryConfig:u}=n||{},c=!!n&&!!u&&(r===nn.RetryRequest||!n.resolved&&r===nn.SendAlternateToPenaltyBox);if(c){var d;if(o>=u.maxNumRetry)return!1;if(i&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${o+1}/${u.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const f=Fb(u,o);this.clearTimer(),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 c}}function EL(s,e){if(s.length!==e.length)return!1;for(let t=0;ts[n]!==e[n])}function kx(s,e){return e.label.toLowerCase()===s.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(s.lang||"").toLowerCase())}class Ej extends Qb{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($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.MANIFEST_PARSED,this.onManifestParsed,this),e.on($.LEVEL_LOADING,this.onLevelLoading,this),e.on($.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on($.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.MANIFEST_PARSED,this.onManifestParsed,this),e.off($.LEVEL_LOADING,this.onLevelLoading,this),e.off($.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off($.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off($.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(g=>!i||i.indexOf(g.groupId)!==-1);if(u.length)this.selectDefaultTrack&&!u.some(g=>g.default)&&(this.selectDefaultTrack=!1),u.forEach((g,v)=>{g.id=v});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=u;const c=this.hls.config.audioPreference;if(!r&&c){const g=pa(c,u,Gl);if(g>-1)r=u[g];else{const v=pa(c,this.tracks);r=this.tracks[v]}}let d=this.findTrackId(r);d===-1&&r&&(d=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($.AUDIO_TRACKS_UPDATED,f);const p=this.trackId;if(d!==-1&&p===-1)this.setAudioTrack(d);else if(u.length&&p===-1){var o;const g=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(g.message),this.hls.trigger($.ERROR,{type:It.MEDIA_ERROR,details:De.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:g})}}}onError(e,t){t.fatal||!t.context||t.context.type===yi.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){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&&iu(e,n,Gl))return n;const r=pa(e,this.tracksInGroup,Gl);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=P6(e,t.levels,i,o,Gl);if(u===-1)return null;t.nextLoadLevel=u}if(e.channels||e.audioCodec){const o=pa(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.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($.AUDIO_TRACK_SWITCHING,Fi({},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{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const i=(t=e[0])==null?void 0:t.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const n=t[0];try{n.execute()}catch(r){var i;if(n.onError(r),this.queues===null||this.tracks===null)return;const o=(i=this.tracks[e])==null?void 0:i.buffer;o!=null&&o.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"":` ${this.list("video")} ${this.list("audio")} ${this.list("audiovideo")}}`}list(e){var t,i;return(t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const i=(t=this.tracks)==null?void 0:t[e],n=i?.buffer;return n?`SourceBuffer${n.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}}const uw=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,wL="HlsJsTrackRemovedError";class Aj extends Error{constructor(e){super(e),this.name=wL}}class Cj extends wr{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=i=>{var n;this.hls&&((n=this.mediaSource)==null?void 0:n.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=i=>{const{media:n,mediaSource:r}=this;i&&this.log("Media source opened"),!(!n||!r)&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger($.MEDIA_ATTACHED,{media:n,mediaSource:r}),this.mediaSource!==null&&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&&this.error(`Media element src was set while attaching MediaSource (${n} > ${i})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=W8(ul(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.MANIFEST_PARSED,this.onManifestParsed,this),e.on($.BUFFER_RESET,this.onBufferReset,this),e.on($.BUFFER_APPENDING,this.onBufferAppending,this),e.on($.BUFFER_CODECS,this.onBufferCodecs,this),e.on($.BUFFER_EOS,this.onBufferEos,this),e.on($.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on($.LEVEL_UPDATED,this.onLevelUpdated,this),e.on($.FRAG_PARSED,this.onFragParsed,this),e.on($.FRAG_CHANGED,this.onFragChanged,this),e.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.MANIFEST_PARSED,this.onManifestParsed,this),e.off($.BUFFER_RESET,this.onBufferReset,this),e.off($.BUFFER_APPENDING,this.onBufferAppending,this),e.off($.BUFFER_CODECS,this.onBufferCodecs,this),e.off($.BUFFER_EOS,this.onBufferEos,this),e.off($.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off($.LEVEL_UPDATED,this.onLevelUpdated,this),e.off($.FRAG_PARSED,this.onFragParsed,this),e.off($.FRAG_CHANGED,this.onFragChanged,this),e.off($.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const i={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const o=this.isQueued();(r||o)&&this.warn(`Transfering MediaSource with${o?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const n=this.transferData;return!this.sourceBufferCount&&n&&n.mediaSource===t?zi(i,n.tracks):this.sourceBuffers.forEach(r=>{const[o]=r;o&&(i[o]=zi({},this.tracks[o]),this.removeBuffer(o)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var i;let n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsTotal=n,this.log(`${n} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&n&&this.bufferCreated()}onMediaAttaching(e,t){const i=this.media=t.media;this.transferData=this.overrides=void 0;const n=ul(this.appendSource);if(n){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const o=this.mediaSource=t.mediaSource||new n;if(this.assignMediaSource(o),r)this._objectUrl=i.src,this.attachTransferred();else{const u=this._objectUrl=self.URL.createObjectURL(o);if(this.appendSource)try{i.removeAttribute("src");const c=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||c&&o instanceof c,cw(i),kj(i,u),i.load()}catch{i.src=u}else i.src=u}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const i=this.tracks,n=t.tracks,r=n?Object.keys(n):null,o=r?r.length:0,u=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(n&&r&&o){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) required tracks: ${Qi(i,(c,d)=>c==="initSegment"?void 0:d)}; transfer tracks: ${Qi(n,(c,d)=>c==="initSegment"?void 0:d)}}`),!TD(n,i)){t.mediaSource=null,t.tracks=void 0;const c=e.currentTime,d=this.details,f=Math.max(c,d?.fragments[0].start||0);if(f-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${f}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(n)}"->"${Object.keys(i)}") start time: ${f} currentTime: ${c}`),this.onMediaDetaching($.MEDIA_DETACHING,{}),this.onMediaAttaching($.MEDIA_ATTACHING,t),e.currentTime=f;return}this.transferData=void 0,r.forEach(c=>{const d=c,f=n[d];if(f){const p=f.buffer;if(p){const g=this.fragmentTracker,v=f.id;if(g.hasFragments(v)||g.hasParts(v)){const S=ti.getBuffered(p);g.detectEvictedFragments(d,S,v,null,!0)}const b=hv(d),_=[d,p];this.sourceBuffers[b]=_,p.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,f)}}}),u(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),u()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:r,_objectUrl:o}=this;if(r){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([u])=>{u&&this.removeBuffer(u)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const u=r.readyState==="open";try{const c=r.sourceBuffers;for(let d=c.length;d--;)u&&c[d].abort(),r.removeSourceBuffer(c[d]);u&&r.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),i||(o&&self.URL.revokeObjectURL(o),this.mediaSrc===o?(n.removeAttribute("src"),this.appendSource&&cw(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger($.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[hv(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new wj(this.tracks)}onBufferCodecs(e,t){var i;const n=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const o="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),u=!o&&this.sourceBufferCount&&this.media&&r.some(c=>!n[c]);if(o||u){this.warn(`Unsupported transition between "${Object.keys(n)}" and "${r}" SourceBuffers`);return}r.forEach(c=>{var d,f;const p=t[c],{id:g,codec:v,levelCodec:b,container:_,metadata:S,supplemental:D}=p;let R=n[c];const L=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],P=L!=null&&L.buffer?L:R,U=P?.pendingCodec||P?.codec,V=P?.levelCodec;R||(R=n[c]={buffer:void 0,listeners:[],codec:v,supplemental:D,container:_,levelCodec:b,metadata:S,id:g});const M=Fm(U,V),G=M?.replace(uw,"$1");let N=Fm(v,b);const O=(f=N)==null?void 0:f.replace(uw,"$1");N&&M&&G!==O&&(c.slice(0,5)==="audio"&&(N=Tp(N,this.appendSource)),this.log(`switching codec ${U} to ${N}`),N!==(R.pendingCodec||R.codec)&&(R.pendingCodec=N),R.container=_,this.appendChangeType(c,_,N))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((i=t.audio)==null?void 0:i.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){const n=`${t};codecs=${i}`,r={label:`change-type=${n}`,execute:()=>{const o=this.tracks[e];if(o){const u=o.buffer;u!=null&&u.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),u.changeType(n),o.codec=i,o.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn(`Failed to change ${e} SourceBuffer type`,o)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,n=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,At.MAIN))==null?void 0:t.gap)===!0)return;const o={label:"block-audio",execute:()=>{var u;const c=this.tracks.video;(this.lastVideoAppendEnd>n||c!=null&&c.buffer&&ti.isBuffered(c.buffer,n)||((u=this.fragmentTracker.getAppendedFrag(n,At.MAIN))==null?void 0:u.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:u=>{this.warn("Error executing block-audio operation",u)}};this.blockedAudioAppend={op:o,frag:e},this.append(o,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:n,type:r,parent:o,frag:u,part:c,chunkMeta:d,offset:f}=t,p=d.buffering[r],{sn:g,cc:v}=u,b=self.performance.now();p.start=b;const _=u.stats.buffering,S=c?c.stats.buffering:null;_.start===0&&(_.start=b),S&&S.start===0&&(S.start=b);const D=i.audio;let R=!1;r==="audio"&&D?.container==="audio/mpeg"&&(R=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const L=i.video,P=L?.buffer;if(P&&g!=="initSegment"){const M=c||u,G=this.blockedAudioAppend;if(r==="audio"&&o!=="main"&&!this.blockedAudioAppend&&!(L.ending||L.ended)){const O=M.start+M.duration*.05,K=P.buffered,Q=this.currentOp("video");!K.length&&!Q?this.blockAudio(M):!Q&&!ti.isBuffered(P,O)&&this.lastVideoAppendEndO||N{var M;p.executeStart=self.performance.now();const G=(M=this.tracks[r])==null?void 0:M.buffer;G&&(R?this.updateTimestampOffset(G,U,.1,r,g,v):f!==void 0&&bt(f)&&this.updateTimestampOffset(G,f,1e-6,r,g,v)),this.appendExecutor(n,r)},onStart:()=>{},onComplete:()=>{const M=self.performance.now();p.executeEnd=p.end=M,_.first===0&&(_.first=M),S&&S.first===0&&(S.first=M);const G={};this.sourceBuffers.forEach(([N,O])=>{N&&(G[N]=ti.getBuffered(O))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger($.BUFFER_APPENDED,{type:r,frag:u,part:c,chunkMeta:d,parent:u.type,timeRanges:G})},onError:M=>{var G;const N={type:It.MEDIA_ERROR,parent:u.type,details:De.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:u,part:c,chunkMeta:d,error:M,err:M,fatal:!1},O=(G=this.media)==null?void 0:G.error;if(M.code===DOMException.QUOTA_EXCEEDED_ERR||M.name=="QuotaExceededError"||"quota"in M)N.details=De.BUFFER_FULL_ERROR;else if(M.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!O)N.errorAction=pc(!0);else if(M.name===wL&&this.sourceBufferCount===0)N.errorAction=pc(!0);else{const K=++this.appendErrors[r];this.warn(`Failed ${K}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${O||"no media error"})`),(K>=this.hls.config.appendErrorMaxRetry||O)&&(N.fatal=!0)}this.hls.trigger($.ERROR,N)}};this.log(`queuing "${r}" append sn: ${g}${c?" p: "+c.index:""} of ${u.type===At.MAIN?"level":"track"} ${u.level} cc: ${v}`),this.append(V,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger($.BUFFER_FLUSHED,{type:e})},onError:n=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,n)}}}onBufferFlushing(e,t){const{type:i,startOffset:n,endOffset:r}=t;i?this.append(this.getFlushOp(i,n,r),i):this.sourceBuffers.forEach(([o])=>{o&&this.append(this.getFlushOp(o,n,r),o)})}onFragParsed(e,t){const{frag:i,part:n}=t,r=[],o=n?n.elementaryStreams:i.elementaryStreams;o[Wi.AUDIOVIDEO]?r.push("audiovideo"):(o[Wi.AUDIO]&&r.push("audio"),o[Wi.VIDEO]&&r.push("video"));const u=()=>{const c=self.performance.now();i.stats.buffering.end=c,n&&(n.stats.buffering.end=c);const d=n?n.stats:i.stats;this.hls.trigger($.FRAG_BUFFERED,{frag:i,part:n,stats:d,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).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([o])=>{if(o){const u=this.tracks[o];(!t.type||t.type===o)&&(u.ending=!0,u.ended||(u.ended=!0,this.log(`${o} buffer reached EOS`)))}});const n=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([o])=>{var u;return o&&!((u=this.tracks[o])!=null&&u.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:o}=this;if(!o||o.readyState!=="open"){o&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${o.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),o.endOfStream(),this.hls.trigger($.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger($.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===De.BUFFER_APPEND_ERROR&&t.frag){var i;const n=(i=t.errorAction)==null?void 0:i.nextAutoLevel;bt(n)&&n!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||t===null||!this.sourceBufferCount)return;const n=e.config,r=i.currentTime,o=t.levelTargetDuration,u=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(bt(u)&&u>=0){const d=Math.max(u,o),f=Math.floor(r/o)*o-d;this.flushBackBuffer(r,o,f)}const c=n.frontBufferFlushThreshold;if(bt(c)&&c>0){const d=Math.max(n.maxBufferLength,c),f=Math.max(d,o),p=Math.floor(r/o)*o+f;this.flushFrontBuffer(r,o,p)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([n,r])=>{if(r){const u=ti.getBuffered(r);if(u.length>0&&i>u.start(0)){var o;this.hls.trigger($.BACK_BUFFER_REACHED,{bufferEnd:i});const c=this.tracks[n];if((o=this.details)!=null&&o.live)this.hls.trigger($.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(c!=null&&c.ended){this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger($.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([n,r])=>{if(r){const o=ti.getBuffered(r),u=o.length;if(u<2)return;const c=o.start(u-1),d=o.end(u-1);if(i>c||e>=c&&e<=d)return;this.hls.trigger($.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:n})}})}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||i?.readyState!=="open")return null;const n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){const d=Math.max(0,t.fragmentStart),f=Math.max(d,n);return{duration:1/0,start:d,end:f}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return bt(r)?{duration:r}:null;const o=this.media.duration,u=bt(i.duration)?i.duration:0;return n>u&&n>o||!bt(o)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:i}){const n=this.mediaSource;!this.media||!n||n.readyState!=="open"||(n.duration!==e&&(bt(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),n.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${t}-${i}.`),n.setLiveSeekableRange(t,i)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Qi(i)}`),this.tracksReady){var n;const r=(n=this.transferData)==null?void 0:n.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,i])=>{if(t){const n=this.tracks[t];e[t]={buffer:i,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}}),this.hls.trigger($.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger($.ERROR,{type:It.MEDIA_ERROR,details:De.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const o=r,u=e[o];if(this.isPending(u)){const c=this.getTrackCodec(u,o),d=`${u.container};codecs=${c}`;u.codec=c,this.log(`creating sourceBuffer(${d})${this.currentOp(o)?" Queued":""} ${Qi(u)}`);try{const f=i.addSourceBuffer(d),p=hv(o),g=[o,f];t[p]=g,u.buffer=f}catch(f){var n;this.error(`error while trying to add sourceBuffer: ${f.message}`),this.shiftAndExecuteNext(o),(n=this.operationQueue)==null||n.removeBlockers(),delete this.tracks[o],this.hls.trigger($.ERROR,{type:It.MEDIA_ERROR,details:De.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:f,sourceBufferName:o,mimeType:d,parent:u.id});return}this.trackSourceBuffer(o,u)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let n=e.codec;i&&(t==="video"||t==="audiovideo")&&Sh(i,"video")&&(n=y6(n,i));const r=Fm(n,e.levelCodec);return r?t.slice(0,5)==="audio"?Tp(r,this.appendSource):r:""}trackSourceBuffer(e,t){const i=t.buffer;if(!i)return;const n=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:n,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(r,o)=>{const u=o.removedRanges;u!=null&&u.length&&this.hls.trigger($.BUFFER_FLUSHED,{type:r})})}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 t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const i=this.currentOp(e);i&&(i.onComplete(),this.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($.ERROR,{type:It.MEDIA_ERROR,details:De.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const r=this.currentOp(e);r&&r.onError(n)}updateTimestampOffset(e,t,i,n,r,o){const u=t-e.timestampOffset;Math.abs(u)>=i&&(this.log(`Updating ${n} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${o})`),e.timestampOffset=t)}removeExecutor(e,t,i){const{media:n,mediaSource:r}=this,o=this.tracks[e],u=o?.buffer;if(!n||!r||!u){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const c=bt(n.duration)?n.duration:1/0,d=bt(r.duration)?r.duration:1/0,f=Math.max(0,t),p=Math.min(i,c,d);p>f&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${f},${p}] from the ${e} SourceBuffer`),u.remove(f,p)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],n=i?.buffer;if(!n)throw new Aj(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,n.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,n=t.map(o=>this.appendBlocker(o));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(o=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;const n=(i=this.tracks[t])==null?void 0:i.buffer;!n||n.updating||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){const n=this.tracks[e];if(!n)return;const r=n.buffer;if(!r)return;const o=i.bind(this,e);n.listeners.push({event:t,listener:o}),r.addEventListener(t,o)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach(n=>{i.removeEventListener(n.event,n.listener)}),t.listeners.length=0)}}function cw(s){const e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t)})}function kj(s,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t)}function hv(s){return s==="audio"?1:0}class Zb{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($.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on($.MANIFEST_PARSED,this.onManifestParsed,this),e.on($.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on($.BUFFER_CODECS,this.onBufferCodecs,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off($.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off($.MANIFEST_PARSED,this.onManifestParsed,this),e.off($.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off($.BUFFER_CODECS,this.onBufferCodecs,this),e.off($.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&&bt(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&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,Zb.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 Math.min(e,this.hls.config.maxDevicePixelRatio)}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,c)=>c?u.width!==c.width||u.height!==c.height:!0;let r=e.length-1;const o=Math.max(t,i);for(let u=0;u=o||c.height>=o)&&n(c,e[u+1])){r=u;break}}return r}}const Dj={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Un=Dj,Lj={HLS:"h"},Rj=Lj;class Sa{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof Sa?i:new Sa(i))),this.value=e,this.params=t}}const Ij="Dict";function Nj(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 Oj(s,e,t,i){return new Error(`failed to ${s} "${Nj(e)}" as ${t}`,{cause:i})}function Ea(s,e,t){return Oj("serialize",s,e,t)}class AL{constructor(e){this.description=e}}const dw="Bare Item",Mj="Boolean";function Pj(s){if(typeof s!="boolean")throw Ea(s,Mj);return s?"?1":"?0"}function Bj(s){return btoa(String.fromCharCode(...s))}const Fj="Byte Sequence";function Uj(s){if(ArrayBuffer.isView(s)===!1)throw Ea(s,Fj);return`:${Bj(s)}:`}const jj="Integer";function $j(s){return s<-999999999999999||99999999999999912)throw Ea(s,Vj);const t=e.toString();return t.includes(".")?t:`${t}.0`}const zj="String",qj=/[\x00-\x1f\x7f]+/;function Kj(s){if(qj.test(s))throw Ea(s,zj);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Yj(s){return s.description||s.toString().slice(7,-1)}const Wj="Token";function hw(s){const e=Yj(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Ea(e,Wj);return e}function Dx(s){switch(typeof s){case"number":if(!bt(s))throw Ea(s,dw);return Number.isInteger(s)?CL(s):Gj(s);case"string":return Kj(s);case"symbol":return hw(s);case"boolean":return Pj(s);case"object":if(s instanceof Date)return Hj(s);if(s instanceof Uint8Array)return Uj(s);if(s instanceof AL)return hw(s);default:throw Ea(s,dw)}}const Xj="Key";function Lx(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw Ea(s,Xj);return s}function Jb(s){return s==null?"":Object.entries(s).map(([e,t])=>t===!0?`;${Lx(e)}`:`;${Lx(e)}=${Dx(t)}`).join("")}function DL(s){return s instanceof Sa?`${Dx(s.value)}${Jb(s.params)}`:Dx(s)}function Qj(s){return`(${s.value.map(DL).join(" ")})${Jb(s.params)}`}function Zj(s,e={whitespace:!0}){if(typeof s!="object"||s==null)throw Ea(s,Ij);const t=s instanceof Map?s.entries():Object.entries(s),i=e?.whitespace?" ":"";return Array.from(t).map(([n,r])=>{r instanceof Sa||(r=new Sa(r));let o=Lx(n);return r.value===!0?o+=Jb(r.params):(o+="=",Array.isArray(r.value)?o+=Qj(r):o+=DL(r)),o}).join(`,${i}`)}function LL(s,e){return Zj(s,e)}const na="CMCD-Object",xs="CMCD-Request",Ul="CMCD-Session",Wo="CMCD-Status",Jj={br:na,ab:na,d:na,ot:na,tb:na,tpb:na,lb:na,tab:na,lab:na,url:na,pb:xs,bl:xs,tbl:xs,dl:xs,ltc:xs,mtp:xs,nor:xs,nrr:xs,rc:xs,sn:xs,sta:xs,su:xs,ttfb:xs,ttfbb:xs,ttlb:xs,cmsdd:xs,cmsds:xs,smrt:xs,df:xs,cs:xs,ts:xs,cid:Ul,pr:Ul,sf:Ul,sid:Ul,st:Ul,v:Ul,msd:Ul,bs:Wo,bsd:Wo,cdn:Wo,rtp:Wo,bg:Wo,pt:Wo,ec:Wo,e:Wo},e7={REQUEST:xs};function t7(s){return Object.keys(s).reduce((e,t)=>{var i;return(i=s[t])===null||i===void 0||i.forEach(n=>e[n]=t),e},{})}function i7(s,e){const t={};if(!s)return t;const i=Object.keys(s),n=e?t7(e):{};return i.reduce((r,o)=>{var u;const c=Jj[o]||n[o]||e7.REQUEST,d=(u=r[c])!==null&&u!==void 0?u:r[c]={};return d[o]=s[o],r},t)}function s7(s){return["ot","sf","st","e","sta"].includes(s)}function n7(s){return typeof s=="number"?bt(s):s!=null&&s!==""&&s!==!1}const RL="event";function r7(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("/")+t.search+t.hash}const Vm=s=>Math.round(s),Rx=(s,e)=>Array.isArray(s)?s.map(t=>Rx(t,e)):s instanceof Sa&&typeof s.value=="string"?new Sa(Rx(s.value,e),s.params):(e.baseUrl&&(s=r7(s,e.baseUrl)),e.version===1?encodeURIComponent(s):s),Em=s=>Vm(s/100)*100,a7=(s,e)=>{let t=s;return e.version>=2&&(s instanceof Sa&&typeof s.value=="string"?t=new Sa([s]):typeof s=="string"&&(t=[s])),Rx(t,e)},o7={br:Vm,d:Vm,bl:Em,dl:Em,mtp:Em,nor:a7,rtp:Em,tb:Vm},IL="request",NL="response",eT=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],l7=["e"],u7=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function hg(s){return u7.test(s)}function c7(s){return eT.includes(s)||l7.includes(s)||hg(s)}const OL=["d","dl","nor","ot","rtp","su"];function d7(s){return eT.includes(s)||OL.includes(s)||hg(s)}const h7=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function f7(s){return eT.includes(s)||OL.includes(s)||h7.includes(s)||hg(s)}const m7=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function p7(s){return m7.includes(s)||hg(s)}const g7={[NL]:f7,[RL]:c7,[IL]:d7};function ML(s,e={}){const t={};if(s==null||typeof s!="object")return t;const i=e.version||s.v||1,n=e.reportingMode||IL,r=i===1?p7:g7[n];let o=Object.keys(s).filter(r);const u=e.filter;typeof u=="function"&&(o=o.filter(u));const c=n===NL||n===RL;c&&!o.includes("ts")&&o.push("ts"),i>1&&!o.includes("v")&&o.push("v");const d=zi({},o7,e.formatters),f={version:i,reportingMode:n,baseUrl:e.baseUrl};return o.sort().forEach(p=>{let g=s[p];const v=d[p];if(typeof v=="function"&&(g=v(g,f)),p==="v"){if(i===1)return;g=i}p=="pr"&&g===1||(c&&p==="ts"&&!bt(g)&&(g=Date.now()),n7(g)&&(s7(p)&&typeof g=="string"&&(g=new AL(g)),t[p]=g))}),t}function y7(s,e={}){const t={};if(!s)return t;const i=ML(s,e),n=i7(i,e?.customHeaderMap);return Object.entries(n).reduce((r,[o,u])=>{const c=LL(u,{whitespace:!1});return c&&(r[o]=c),r},t)}function v7(s,e,t){return zi(s,y7(e,t))}const x7="CMCD";function b7(s,e={}){return s?LL(ML(s,e),{whitespace:!1}):""}function T7(s,e={}){if(!s)return"";const t=b7(s,e);return encodeURIComponent(t)}function _7(s,e={}){if(!s)return"";const t=T7(s,e);return`${x7}=${t}`}const fw=/CMCD=[^&#]+/;function S7(s,e,t){const i=_7(e,t);if(!i)return s;if(fw.test(s))return s.replace(fw,i);const n=s.includes("?")?"&":"?";return`${s}${n}${i}`}class E7{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:Un.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=n=>{try{const{frag:r,part:o}=n,u=this.hls.levels[r.level],c=this.getObjectType(r),d={d:(o||r).duration*1e3,ot:c};(c===Un.VIDEO||c===Un.AUDIO||c==Un.MUXED)&&(d.br=u.bitrate/1e3,d.tb=this.getTopBandwidth(c)/1e3,d.bl=this.getBufferLength(c));const f=o?this.getNextPart(o):this.getNextFrag(r);f!=null&&f.url&&f.url!==r.url&&(d.nor=f.url),this.apply(n,d)}catch(r){this.hls.logger.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||e.sessionId,this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on($.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($.MEDIA_DETACHED,this.onMediaDetached,this),e.on($.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off($.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($.MEDIA_DETACHED,this.onMediaDetached,this),e.off($.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),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:Rj.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){zi(t,this.createData());const i=t.ot===Un.INIT||t.ot===Un.VIDEO||t.ot===Un.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((o,u)=>(n.includes(u)&&(o[u]=t[u]),o),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),v7(e.headers,t,r)):e.url=S7(e.url,t,r)}getNextFrag(e){var t;const i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){const n=e.sn-i.startSN;return i.fragments[n+1]}}getNextPart(e){var t;const{index:i,fragment:n}=e,r=(t=this.hls.levels[n.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:o}=n;for(let u=r.length-1;u>=0;u--){const c=r[u];if(c.index===i&&c.fragment.sn===o)return r[u+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Un.TIMED_TEXT;if(e.sn==="initSegment")return Un.INIT;if(t==="audio")return Un.AUDIO;if(t==="main")return this.hls.audioTracks.length?Un.VIDEO:Un.MUXED}getTopBandwidth(e){let t=0,i;const n=this.hls;if(e===Un.AUDIO)i=n.audioTracks;else{const r=n.maxAutoLevel,o=r>-1?r+1:n.levels.length;i=n.levels.slice(0,o)}return i.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,i=e===Un.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:ti.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 w7=3e5;class A7 extends wr{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.MANIFEST_LOADED,this.onManifestLoaded,this),e.on($.MANIFEST_PARSED,this.onManifestParsed,this),e.on($.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.MANIFEST_LOADED,this.onManifestLoaded,this),e.off($.MANIFEST_PARSED,this.onManifestParsed,this),e.off($.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){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===nn.SendAlternateToPenaltyBox&&i.flags===ar.MoveAllAlternatesMatchingHost){const n=this.levels;let r=this._pathwayPriority,o=this.pathwayId;if(t.context){const{groupId:u,pathwayId:c,type:d}=t.context;u&&n?o=this.getPathwayForGroupId(u,d,o):c&&(o=c)}o in this.penalizedPathways||(this.penalizedPathways[o]=performance.now()),!r&&n&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==o),t.details===De.BUFFER_APPEND_ERROR&&!t.fatal?i.resolved=!0:i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${o} levels: ${n&&n.length} priorities: ${Qi(r)} penalized: ${Qi(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]>w7&&delete i[r]});for(let r=0;r0){this.log(`Setting Pathway to "${o}"`),this.pathwayId=o,tL(t),this.hls.trigger($.LEVELS_UPDATED,{levels:t});const d=this.hls.levels[u];c&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=u);break}}}getPathwayForGroupId(e,t,i){const n=this.getLevelsForPathway(i).concat(this.levels||[]);for(let r=0;r{const{ID:o,"BASE-ID":u,"URI-REPLACEMENT":c}=r;if(t.some(f=>f.pathwayId===o))return;const d=this.getLevelsForPathway(u).map(f=>{const p=new ds(f.attrs);p["PATHWAY-ID"]=o;const g=p.AUDIO&&`${p.AUDIO}_clone_${o}`,v=p.SUBTITLES&&`${p.SUBTITLES}_clone_${o}`;g&&(i[p.AUDIO]=g,p.AUDIO=g),v&&(n[p.SUBTITLES]=v,p.SUBTITLES=v);const b=PL(f.uri,p["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),_=new wh({attrs:p,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 S=1;S{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":_,"PATHWAY-CLONES":S,"PATHWAY-PRIORITY":D}=b;if(_)try{this.uri=new self.URL(_,n).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${_}`);return}this.scheduleRefresh(this.uri||g.url),S&&this.clonePathways(S);const R={steeringManifest:b,url:n.toString()};this.hls.trigger($.STEERING_MANIFEST_LOADED,R),D&&this.updatePathwayPriority(D)},onError:(f,p,g,v)=>{if(this.log(`Error loading steering manifest: ${f.code} ${f.text} (${p.url})`),this.stopLoad(),f.code===410){this.enabled=!1,this.log(`Steering manifest ${p.url} no longer available`);return}let b=this.timeToLoad*1e3;if(f.code===429){const _=this.loader;if(typeof _?.getResponseHeader=="function"){const S=_.getResponseHeader("Retry-After");S&&(b=parseFloat(S)*1e3)}this.log(`Steering manifest ${p.url} rate limited`);return}this.scheduleRefresh(this.uri||p.url,b)},onTimeout:(f,p,g)=>{this.log(`Timeout loading steering manifest (${p.url})`),this.scheduleRefresh(this.uri||p.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(r,c,d)}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 mw(s,e,t,i){s&&Object.keys(e).forEach(n=>{const r=s.filter(o=>o.groupId===n).map(o=>{const u=zi({},o);return u.details=void 0,u.attrs=new ds(u.attrs),u.url=u.attrs.URI=PL(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 PL(s,e,t,i){const{HOST:n,PARAMS:r,[t]:o}=i;let u;e&&(u=o?.[e],u&&(s=u));const c=new self.URL(s);return n&&!u&&(c.host=n),r&&Object.keys(r).sort().forEach(d=>{d&&c.searchParams.set(d,r[d])}),c.href}class yc extends wr{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=yc.CDMCleanupPromise?[yc.CDMCleanupPromise]:[],this.bannedKeyIds={},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=sh(this.config));const u=o.map(nv).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(u)}this.keyFormatPromise.then(o=>{const u=jm(o);if(i!=="sinf"||u!==hs.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${i}" for selected key-system ${u}`);return}let c;try{const v=js(new Uint8Array(n)),b=Hb(JSON.parse(v).sinf),_=LD(b);if(!_)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(_.subarray(8,24))}catch(v){this.warn(`${r} Failed to parse sinf: ${v}`);return}const d=an(c),{keyIdToKeySessionPromise:f,mediaKeySessions:p}=this;let g=f[d];for(let v=0;vthis.generateRequestWithPreferredKeySession(b,i,n,"encrypted-event-key-match")),g.catch(D=>this.handleError(D));break}}g||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${p.length}.`))}).catch(o=>this.handleError(o))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),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($.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on($.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on($.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on($.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on($.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off($.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off($.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off($.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off($.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off($.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,n=t?.[e];if(n)return n.licenseUrl;if(e===hs.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,c)=>!!o&&c.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 c=d=>{const f=d.shift();this.getMediaKeysPromise(f,n,r).then(p=>o({keySystem:f,mediaKeys:p})).catch(p=>{d.length?c(d):p instanceof rr?u(p):u(new rr({type:It.KEY_SYSTEM_ERROR,details:De.KEY_SYSTEM_NO_ACCESS,error:p,fatal:!0},p.message))})};c(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let n=`Configured requestMediaKeySystemAccess is not a function ${i}`;return KD===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){var n;const r=aU(e,t,i,this.config.drmSystemOptions||{});let o=this.keySystemAccessPromises[e],u=(n=o)==null?void 0:n.keySystemAccess;if(!u){this.log(`Requesting encrypted media "${e}" key-system access with config: ${Qi(r)}`),u=this.requestMediaKeySystemAccess(e,r);const c=o=this.keySystemAccessPromises[e]={keySystemAccess:u};return u.catch(d=>{this.log(`Failed to obtain access to key-system "${e}": ${d}`)}),u.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);const f=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const p=c.mediaKeys=d.createMediaKeys().then(g=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,f.then(v=>v?this.setMediaKeysServerCertificate(g,e,v):g)));return p.catch(g=>{this.error(`Failed to create media-keys for "${e}"}: ${g}`)}),p})}return u.then(()=>o.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${an(e.keyId||[])} keyUri: ${e.uri}`);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=wm(t),r="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(i,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${an(e.decryptdata.keyId||[])} } (data length: ${t.byteLength})`),i.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>nv(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:i})=>this.attemptSetMediaKeys(t,i))}selectKeySystem(e){return new Promise((t,i)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:n})=>{const r=nv(n);r?t(r):i(new Error(`Unable to find format for key-system "${n}"`))}).catch(i)})}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){const t=sh(this.config),i=e.map(jm).filter(n=>!!n&&t.indexOf(n)!==-1);return this.selectKeySystem(i)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let i=0;i(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(c,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:d,decryptdata:t}))))).then(c=>{const d="cenc",f=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,d,f,"playlist-key")});return u.catch(c=>this.handleError(c,e.frag)),this.keyIdToKeySessionPromise[i]=u,u}return o.catch(u=>{if(u instanceof rr){const c=Fi({},u.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const d=new rr(c,u.message);this.handleError(d,e.frag)}}),o}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof rr){t&&(e.data.frag=t);const i=e.data.decryptdata;this.error(`${e.message}${i?` (${an(i.keyId||[])})`:""}`),this.hls.trigger($.ERROR,e.data)}else this.error(e.message),this.hls.trigger($.ERROR,{type:It.KEY_SYSTEM_ERROR,details:De.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=wm(e),i=this.keyIdToKeySessionPromise[t];if(!i){const n=jm(e.keyFormat),r=n?[n]:sh(this.config);return this.attemptKeySystemAccess(r)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=sh(this.config)),e.length===0)throw new rr({type:It.KEY_SYSTEM_ERROR,details:De.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Qi({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const n=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(t):new Promise((r,o)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return o(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(o)}}));return this.mediaKeys=t,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;const o=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(o)try{const b=o.call(this.hls,t,i,e);if(!b)throw new Error("Invalid response from configured generateRequest filter");t=b.initDataType,i=b.initData?b.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(b){if(this.warn(b.message),this.hls&&this.hls.config.debug)throw b}if(i===null)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e);const u=wm(e.decryptdata),c=e.decryptdata.uri;this.log(`Generating key-session request for "${n}" keyId: ${u} URI: ${c} (init data type: ${t} length: ${i.byteLength})`);const d=new Gb,f=e._onmessage=b=>{const _=e.mediaKeysSession;if(!_){d.emit("error",new Error("invalid state"));return}const{messageType:S,message:D}=b;this.log(`"${S}" message event for session "${_.sessionId}" message size: ${D.byteLength}`),S==="license-request"||S==="license-renewal"?this.renewLicense(e,D).catch(R=>{d.eventNames().length?d.emit("error",R):this.handleError(R)}):S==="license-release"?e.keySystem===hs.FAIRPLAY&&this.updateKeySession(e,Sx("acknowledged")).then(()=>this.removeSession(e)).catch(R=>this.handleError(R)):this.warn(`unhandled media key message type "${S}"`)},p=(b,_)=>{_.keyStatus=b;let S;b.startsWith("usable")?d.emit("resolved"):b==="internal-error"||b==="output-restricted"||b==="output-downscaled"?S=pw(b,_.decryptdata):b==="expired"?S=new Error(`key expired (keyId: ${u})`):b==="released"?S=new Error("key released"):b==="status-pending"||this.warn(`unhandled key status change "${b}" (keyId: ${u})`),S&&(d.eventNames().length?d.emit("error",S):this.handleError(S))},g=e._onkeystatuseschange=b=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const S=this.getKeyStatuses(e);if(!Object.keys(S).some(P=>S[P]!=="status-pending"))return;if(S[u]==="expired"){this.log(`Expired key ${Qi(S)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let R=S[u];if(R)p(R,e);else{var L;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(L=e.keyStatusTimeouts)[u]||(L[u]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const U=this.getKeyStatus(e.decryptdata);if(U&&U!=="status-pending")return this.log(`No status for keyId ${u} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${U} from other session.`),p(U,e);this.log(`key status for ${u} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),R="internal-error",p(R,e)},1e3)),this.log(`No status for keyId ${u} (${Qi(S)}).`)}};En(e.mediaKeysSession,"message",f),En(e.mediaKeysSession,"keystatuseschange",g);const v=new Promise((b,_)=>{d.on("error",_),d.on("resolved",b)});return e.mediaKeysSession.generateRequest(t,i).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${u} URI: ${c}`)}).catch(b=>{throw new rr({type:It.KEY_SYSTEM_ERROR,details:De.KEY_SYSTEM_NO_SESSION,error:b,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${b}`)}).then(()=>v).catch(b=>(d.removeAllListeners(),this.removeSession(e).then(()=>{throw b}))).then(()=>(d.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((i,n)=>{if(typeof n=="string"&&typeof i=="object"){const u=n;n=i,i=u}const r="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);if(e.keySystem===hs.PLAYREADY&&r.length===16){const u=an(r);t[u]=i,zD(r)}const o=an(r);i==="internal-error"&&(this.bannedKeyIds[o]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${o} key-session "${e.mediaKeysSession.sessionId}"`),t[o]=i}),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 c={responseType:"arraybuffer",url:r},d=t.certLoadPolicy.default,f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},p={onSuccess:(g,v,b,_)=>{o(g.data)},onError:(g,v,b,_)=>{u(new rr({type:It.KEY_SYSTEM_ERROR,details:De.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:b,response:Fi({url:c.url,data:void 0},g)},`"${e}" certificate request failed (${r}). Status: ${g.code} (${g.text})`))},onTimeout:(g,v,b)=>{u(new rr({type:It.KEY_SYSTEM_ERROR,details:De.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:b,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(g,v,b)=>{u(new Error("aborted"))}};n.load(c,f,p)})):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 rr({type:It.KEY_SYSTEM_ERROR,details:De.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 rr({type:It.KEY_SYSTEM_ERROR,details:De.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:n,fatal:!1},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 p=0,g=r.length;p in key message");return Sx(atob(d))}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 c=u.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const d=this.config.licenseResponseCallback;if(d)try{c=d.call(this.hls,u,o,e)}catch(f){this.error(f)}n(c)}else{const c=i.errorRetry,d=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||u.status>=400&&u.status<500)r(new rr({type:It.KEY_SYSTEM_ERROR,details:De.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,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=d-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:c,licenseChallenge:d})=>{e.keySystem==hs.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(c,d)),c.send(d)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,En(i,"encrypted",this.onMediaEncrypted),En(i,"waitingforkey",this.onWaitingForKey);const n=this.mediaResolved;n?n():this.mediaKeys=i.mediaKeys}onMediaDetached(){const e=this.media;e&&(Vn(e,"encrypted",this.onMediaEncrypted),Vn(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,n=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,al.clearKeyUriToKeyIdMap();const r=n.length;yc.CDMCleanupPromise=Promise.all(n.map(o=>this.removeSession(o)).concat((i==null||(e=i.setMediaKeys(null))==null?void 0:e.catch(o=>{this.log(`Could not clear media keys: ${o}`),this.hls&&this.hls.trigger($.ERROR,{type:It.OTHER_ERROR,details:De.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${o}`)})}))||Promise.resolve())).catch(o=>{this.log(`Could not close sessions and clear media keys: ${o}`),this.hls&&this.hls.trigger($.ERROR,{type:It.OTHER_ERROR,details:De.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${o}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}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,decryptdata:n}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${an(n?.keyId||[])}`),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 r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:o}=e;o&&Object.keys(o).forEach(d=>self.clearTimeout(o[d]));const{drmSystemOptions:u}=this.config;return(lU(u)?new Promise((d,f)=>{self.setTimeout(()=>f(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(d).catch(f)}):Promise.resolve()).catch(d=>{this.log(`Could not remove session: ${d}`),this.hls&&this.hls.trigger($.ERROR,{type:It.OTHER_ERROR,details:De.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${d}`)})}).then(()=>t.close()).catch(d=>{this.log(`Could not close session: ${d}`),this.hls&&this.hls.trigger($.ERROR,{type:It.OTHER_ERROR,details:De.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}yc.CDMCleanupPromise=void 0;function wm(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return an(s.keyId)}function C7(s,e){if(s.keyId&&e.mediaKeysSession.keyStatuses.has(s.keyId))return e.mediaKeysSession.keyStatuses.get(s.keyId);if(s.matches(e.decryptdata))return e.keyStatus}class rr 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}}function pw(s,e){const t=s==="output-restricted",i=t?De.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:De.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new rr({type:It.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${s}"`)}class k7{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($.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on($.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off($.MEDIA_DETACHING,this.onMediaDetaching,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)}}onMediaDetaching(){this.media=null}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,c=1e3*o/r,d=this.hls;if(d.trigger($.FPS_DROP,{currentDropped:o,currentDecoded:u,totalDroppedFrames:i}),c>0&&o>d.config.fpsDroppedMonitoringThreshold*u){let f=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+f),f>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=f)&&(f=f-1,d.trigger($.FPS_DROP_LEVEL_CAPPING,{level:f,droppedLevel:d.currentLevel}),d.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)}}function BL(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 FL(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){Ui.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){Ui.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${n}`)}}t==="disabled"&&(s.mode=t)}function nc(s,e){const t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues)for(let i=s.cues.length;i--;)e&&s.cues[i].removeEventListener("enter",e),s.removeCue(s.cues[i]);t==="disabled"&&(s.mode=t)}function Ix(s,e,t,i){const n=s.mode;if(n==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const r=L7(s.cues,e,t);for(let o=0;os[t].endTime)return-1;let i=0,n=t,r;for(;i<=n;)if(r=Math.floor((n+i)/2),es[r].startTime&&i-1)for(let r=n,o=s.length;r=e&&u.endTime<=t)i.push(u);else if(u.startTime>t)return i}return i}function Gm(s){const e=[];for(let t=0;tthis.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const i=Gm(this.media.textTracks);for(let r=0;r-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on($.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.MANIFEST_PARSED,this.onManifestParsed,this),e.on($.LEVEL_LOADING,this.onLevelLoading,this),e.on($.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off($.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.MANIFEST_PARSED,this.onManifestParsed,this),e.off($.LEVEL_LOADING,this.onLevelLoading,this),e.off($.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off($.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const i=this.media;if(!i)return;const n=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,n)return;Gm(i.textTracks).forEach(o=>{nc(o)})}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,p)=>{f.id=p});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const u=this.hls.config.subtitlePreference;if(!r&&u){this.selectDefaultTrack=!1;const f=pa(u,o);if(f>-1)r=o[f];else{const p=pa(u,this.tracks);r=this.tracks[p]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const d={subtitleTracks:o};this.log(`Updating subtitle tracks, ${o.length} track(s) found in "${i?.join(",")}" group-id`),this.hls.trigger($.SUBTITLE_TRACKS_UPDATED,d),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let n=0;n-1){const r=this.tracksInGroup[n];return this.setSubtitleTrack(n),r}else{if(i)return null;{const r=pa(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,n=e.groupId,r=this.getUrlWithDirectives(e.url,t),o=e.details,u=o?.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${n}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${u&&o.live?" age "+u.toFixed(1)+(o.type&&" "+o.type||""):""} ${r}`),this.hls.trigger($.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Gm(e.textTracks),i=this.currentTrack;let n;if(i&&(n=t.filter(r=>kx(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||!bt(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,n=t[e]||null;if(this.trackId=e,this.currentTrack=n,this.toggleTrackModes(),!n){this.hls.trigger($.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:c,type:d,url:f}=n;this.hls.trigger($.SUBTITLE_TRACK_SWITCH,{id:o,groupId:u,name:c,type:d,url:f});const p=this.switchParams(n.url,i?.details,n.details);this.loadPlaylist(p)}}function I7(){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)})}}}function gh(s){let e=5381,t=s.length;for(;t;)e=e*33^s.charCodeAt(--t);return(e>>>0).toString()}const vc=.025;let Lp=(function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s})({});function N7(s,e,t){return`${s.identifier}-${t+1}-${gh(e)}`}class O7{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const i=this.playoutLimit;return e<=0||isNaN(i)?!1:i===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>i}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return fv(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,i=fv(t,e);return t-i<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=bt(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return fv(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)0||this.assetListResponse!==null}toString(){return M7(this)}}function fv(s,e){return s-e.start":s.cue.post?"":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function Ju(s){const e=s.timelineStart,t=s.duration||0;return`["${s.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class P7{constructor(e,t,i,n){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger($.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=i,this.assetItem=n;const o=()=>{this.hasDetails=!0};r.once($.LEVEL_LOADED,o),r.once($.AUDIO_TRACK_LOADED,o),r.once($.SUBTITLE_TRACK_LOADED,o),r.on($.MEDIA_ATTACHING,(u,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on($.BUFFER_APPENDED,()=>{const f=this.bufferedEnd;this.reachedPlayout(f)&&(this._bufferedEosTime=f,r.trigger($.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=UL(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset,r=ti.bufferInfo(e,n,0);return this.getAssetTime(r.end)>=i-.02}reachedPlayout(e){const i=this.interstitial.playoutLimit;return this.startOffset+e>=i}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=ti.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const i=t-this.startOffset;if(i>0&&i1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=i=>delete i.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var n;(n=this.hls)==null||n.on(e,t)}once(e,t,i){var n;(n=this.hls)==null||n.once(e,t)}off(e,t,i){var n;(n=this.hls)==null||n.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Ju(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const gw=.033;class B7 extends wr{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,n)=>e<=n.startOffset&&t>n.startOffset?(delete n.error,i+1):i,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);const n=this.items;if(n)for(n[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(r=n[i])!=null&&r.event;){var r;i--}return i}findItemIndexAtTime(e,t){const i=this.items;if(i)for(let n=0;nr.start&&e1)for(let r=0;ru&&(t!u.includes(d.identifier)):[];o.length&&o.sort((d,f)=>{const p=d.cue.pre,g=d.cue.post,v=f.cue.pre,b=f.cue.post;if(p&&!v)return-1;if(v&&!p||g&&!b)return 1;if(b&&!g)return-1;if(!p&&!v&&!g&&!b){const _=d.startTime,S=f.startTime;if(_!==S)return _-S}return d.dateRange.tagOrder-f.dateRange.tagOrder}),this.events=o,c.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(e,c)}updateSchedule(e,t=[],i=!1){const n=this.events||[];if(n.length||t.length||this.length<2){const r=this.items,o=this.parseSchedule(n,e);(i||t.length||r?.length!==o.length||o.some((c,d)=>Math.abs(c.playout.start-r[d].playout.start)>.005||Math.abs(c.playout.end-r[d].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,i){const n=[],r=Object.keys(e);for(let o=0;o!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,d=0;if(e.forEach((f,p)=>{const g=f.cue.pre,v=f.cue.post,b=e[p-1]||null,_=f.appendInPlace,S=v?r:f.startOffset,D=f.duration,R=f.timelineOccupancy===Lp.Range?D:0,L=f.resumptionOffset,P=b?.startTime===S,U=S+f.cumulativeDuration;let V=_?U+D:S+L;if(g||!v&&S<=0){const G=d;d+=R,f.timelineStart=U;const N=o;o+=D,i.push({event:f,start:U,end:V,playout:{start:N,end:o},integrated:{start:G,end:d}})}else if(S<=r){if(!P){const O=S-c;if(O>gw){const K=c,Q=d;d+=O;const W=o;o+=O;const re={previousEvent:e[p-1]||null,nextEvent:f,start:K,end:K+O,playout:{start:W,end:o},integrated:{start:Q,end:d}};i.push(re)}else O>0&&b&&(b.cumulativeDuration+=O,i[i.length-1].end=S)}v&&(V=U),f.timelineStart=U;const G=d;d+=R;const N=o;o+=D,i.push({event:f,start:U,end:V,playout:{start:N,end:o},integrated:{start:G,end:d}})}else return;const M=f.resumeTime;v||M>r?c=r:c=M}),c{const d=u.cue.pre,f=u.cue.post,p=d?0:f?n:u.startTime;this.updateAssetDurations(u),o===p?u.cumulativeDuration=r:(r=0,o=p),!f&&u.snapOptions.in&&(u.resumeAnchor=au(null,i.fragments,u.startOffset+u.resumptionOffset,0,0)||void 0),u.appendInPlace&&!u.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(u,t)||(u.appendInPlace=!1)),!u.appendInPlace&&c+1vc?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${n}`),!1):!Object.keys(t).some(o=>{const u=t[o].details,c=u.edge;if(i>=c)return this.log(`"${e.identifier}" resumption ${i} past ${o} playlist end ${c}`),!1;const d=au(null,u.fragments,i);if(!d)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${o} playlist (${u.fragStart}-${u.fragmentEnd})`),!0;const f=o==="audio"?.175:0;return Math.abs(d.start-i){const S=g.data,D=S?.ASSETS;if(!Array.isArray(D)){const R=this.assignAssetListError(e,De.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),b.url,v,_);this.hls.trigger($.ERROR,R);return}e.assetListResponse=S,this.hls.trigger($.ASSET_LIST_LOADED,{event:e,assetListResponse:S,networkDetails:_})},onError:(g,v,b,_)=>{const S=this.assignAssetListError(e,De.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${g.code} ${g.text} (${v.url})`),v.url,_,b);this.hls.trigger($.ERROR,S)},onTimeout:(g,v,b)=>{const _=this.assignAssetListError(e,De.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${v.url})`),v.url,g,b);this.hls.trigger($.ERROR,_)}};return u.load(c,f,p),this.hls.trigger($.ASSET_LIST_LOADING,{event:e}),u}assignAssetListError(e,t,i,n,r,o){return e.error=i,{type:It.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:i,networkDetails:o,stats:r}}}function yw(s){var e;s==null||(e=s.play())==null||e.catch(()=>{})}function Am(s,e){return`[${s}] Advancing timeline position to ${e}`}class U7 extends wr{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled||!this.schedule)return;const n=i-this.timelinePos;if(Math.abs(n)<1/7056e5)return;const o=n<=-.01;this.timelinePos=i,this.bufferedPos=i;const u=this.playingItem;if(!u){this.checkBuffer();return}if(o&&this.schedule.resetErrorsInRange(i,i-n)&&this.updateSchedule(!0),this.checkBuffer(),o&&i=u.end){var c;const v=this.findItemIndex(u);let b=this.schedule.findItemIndexAtTime(i);if(b===-1&&(b=v+(o?-1:1),this.log(`seeked ${o?"back ":""}to position not covered by schedule ${i} (resolving from ${v} to ${b})`)),!this.isInterstitial(u)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!o&&b>v){const _=this.schedule.findJumpRestrictedIndex(v+1,b);if(_>v){this.setSchedulePosition(_);return}}this.setSchedulePosition(b);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(u)){const v=u.event.assetList[0];v&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,v))}return}const f=d.timelineStart,p=d.duration||0;if(o&&i=f+p){var g;(g=u.event)!=null&&g.appendInPlace&&(this.clearAssetPlayers(u.event,u),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,d)}},this.onTimeupdate=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;const n=this.playingItem;if(!n||this.playingLastItem)return;if(i>=n.end){this.timelinePos=n.end;const u=this.findItemIndex(n);this.setSchedulePosition(u+1)}const r=this.playingAsset;if(!r)return;const o=r.timelineStart+(r.duration||0);i>=o&&this.setScheduleToAssetAtTime(i,r)},this.onScheduleUpdate=(i,n)=>{const r=this.schedule;if(!r)return;const o=this.playingItem,u=r.events||[],c=r.items||[],d=r.durations,f=i.map(_=>_.identifier),p=!!(u.length||f.length);(p||n)&&this.log(`INTERSTITIALS_UPDATED (${u.length}): ${u} Schedule: ${c.map(_=>Nr(_))} pos: ${this.timelinePos}`),f.length&&this.log(`Removed events ${f}`);let g=null,v=null;o&&(g=this.updateItem(o,this.timelinePos),this.itemsMatch(o,g)?this.playingItem=g:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const b=this.bufferingItem;if(b&&(v=this.updateItem(b,this.bufferedPos),this.itemsMatch(b,v)?this.bufferingItem=v:b.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(b.event,null))),i.forEach(_=>{_.assetList.forEach(S=>{this.clearAssetPlayer(S.identifier,null)})}),this.playerQueue.forEach(_=>{if(_.interstitial.appendInPlace){const S=_.assetItem.timelineStart,D=_.timelineOffset-S;if(D)try{_.timelineOffset=S}catch(R){Math.abs(D)>vc&&this.warn(`${R} ("${_.assetId}" ${_.timelineOffset}->${S})`)}}}),p||n){if(this.hls.trigger($.INTERSTITIALS_UPDATED,{events:u.slice(0),schedule:c.slice(0),durations:d,removedIds:f}),this.isInterstitial(o)&&f.includes(o.event.identifier)){this.warn(`Interstitial "${o.event.identifier}" removed while playing`),this.primaryFallback(o.event);return}o&&this.trimInPlace(g,o),b&&v!==g&&this.trimInPlace(v,b),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new F7(e),this.schedule=new B7(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on($.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.LEVEL_UPDATED,this.onLevelUpdated,this),e.on($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on($.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on($.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on($.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on($.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on($.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on($.BUFFER_APPENDED,this.onBufferAppended,this),e.on($.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on($.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on($.MEDIA_ENDED,this.onMediaEnded,this),e.on($.ERROR,this.onError,this),e.on($.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off($.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.LEVEL_UPDATED,this.onLevelUpdated,this),e.off($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off($.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off($.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off($.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off($.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off($.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off($.BUFFER_CODECS,this.onBufferCodecs,this),e.off($.BUFFER_APPENDED,this.onBufferAppended,this),e.off($.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off($.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off($.MEDIA_ENDED,this.onMediaEnded,this),e.off($.ERROR,this.onError,this),e.off($.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Vn(e,"play",this.onPlay),Vn(e,"pause",this.onPause),Vn(e,"seeking",this.onSeeking),Vn(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;En(i,"seeking",this.onSeeking),En(i,"timeupdate",this.onTimeupdate),En(i,"play",this.onPlay),En(i,"pause",this.onPause)}onMediaAttached(e,t){const i=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!n){this.clearScheduleState();const r=this.findItemIndex(i);this.setSchedulePosition(r)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const i=!!t.transferMedia,n=this.media;if(this.media=null,!i&&(n&&this.removeMediaListeners(n),this.detachedData)){const r=this.getBufferingPlayer();r&&(this.log(`Removing schedule state for detachedData and ${r}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,i=p=>p&&e.getAssetPlayer(p.identifier),n=(p,g,v,b,_)=>{if(p){let S=p[g].start;const D=p.event;if(D){if(g==="playout"||D.timelineOccupancy!==Lp.Point){const R=i(v);R?.interstitial===D&&(S+=R.assetItem.startOffset+R[_])}}else{const R=b==="bufferedPos"?o():e[b];S+=R-p.start}return S}return 0},r=(p,g)=>{var v;if(p!==0&&g!=="primary"&&(v=e.schedule)!=null&&v.length){var b;const _=e.schedule.findItemIndexAtTime(p),S=(b=e.schedule.items)==null?void 0:b[_];if(S){const D=S[g].start-S.start;return p+D}}return p},o=()=>{const p=e.bufferedPos;return p===Number.MAX_VALUE?u("primary"):Math.max(p,0)},u=p=>{var g,v;return(g=e.primaryDetails)!=null&&g.live?e.primaryDetails.edge:((v=e.schedule)==null?void 0:v.durations[p])||0},c=(p,g)=>{var v,b;const _=e.effectivePlayingItem;if(_!=null&&(v=_.event)!=null&&v.restrictions.skip||!e.schedule)return;e.log(`seek to ${p} "${g}"`);const S=e.effectivePlayingItem,D=e.schedule.findItemIndexAtTime(p,g),R=(b=e.schedule.items)==null?void 0:b[D],L=e.getBufferingPlayer(),P=L?.interstitial,U=P?.appendInPlace,V=S&&e.itemsMatch(S,R);if(S&&(U||V)){const M=i(e.playingAsset),G=M?.media||e.primaryMedia;if(G){const N=g==="primary"?G.currentTime:n(S,g,e.playingAsset,"timelinePos","currentTime"),O=p-N,K=(U?N:G.currentTime)+O;if(K>=0&&(!M||U||K<=M.duration)){G.currentTime=K;return}}}if(R){let M=p;if(g!=="primary"){const N=R[g].start,O=p-N;M=R.start+O}const G=!e.isInterstitial(R);if((!e.isInterstitial(S)||S.event.appendInPlace)&&(G||R.event.appendInPlace)){const N=e.media||(U?L?.media:null);N&&(N.currentTime=M)}else if(S){const N=e.findItemIndex(S);if(D>N){const K=e.schedule.findJumpRestrictedIndex(N+1,D);if(K>N){e.setSchedulePosition(K);return}}let O=0;if(G)e.timelinePos=M,e.checkBuffer();else{const K=R.event.assetList,Q=p-(R[g]||R).start;for(let W=K.length;W--;){const re=K[W];if(re.duration&&Q>=re.startOffset&&Q{const p=e.effectivePlayingItem;if(e.isInterstitial(p))return p;const g=t();return e.isInterstitial(g)?g:null},f={get bufferedEnd(){const p=t(),g=e.bufferingItem;if(g&&g===p){var v;return n(g,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-g.playout.start||((v=e.bufferingAsset)==null?void 0:v.startOffset)||0}return 0},get currentTime(){const p=d(),g=e.effectivePlayingItem;return g&&g===p?n(g,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-g.playout.start:0},set currentTime(p){const g=d(),v=e.effectivePlayingItem;v&&v===g&&c(p+v.playout.start,"playout")},get duration(){const p=d();return p?p.playout.end-p.playout.start:0},get assetPlayers(){var p;const g=(p=d())==null?void 0:p.event.assetList;return g?g.map(v=>e.getAssetPlayer(v.identifier)):[]},get playingIndex(){var p;const g=(p=d())==null?void 0:p.event;return g&&e.effectivePlayingAsset?g.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var p;return((p=e.schedule)==null||(p=p.events)==null?void 0:p.slice(0))||[]},get schedule(){var p;return((p=e.schedule)==null||(p=p.items)==null?void 0:p.slice(0))||[]},get interstitialPlayer(){return d()?f:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const p=t();return e.findItemIndex(p)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const p=e.effectivePlayingItem;return e.findItemIndex(p)},primary:{get bufferedEnd(){return o()},get currentTime(){const p=e.timelinePos;return p>0?p:0},set currentTime(p){c(p,"primary")},get duration(){return u("primary")},get seekableStart(){var p;return((p=e.primaryDetails)==null?void 0:p.fragmentStart)||0}},integrated:{get bufferedEnd(){return n(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return n(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(p){c(p,"integrated")},get duration(){return u("integrated")},get seekableStart(){var p;return r(((p=e.primaryDetails)==null?void 0:p.fragmentStart)||0,"integrated")}},skip:()=>{const p=e.effectivePlayingItem,g=p?.event;if(g&&!g.restrictions.skip){const v=e.findItemIndex(p);if(g.appendInPlace){const b=p.playout.start+p.event.duration;c(b+.001,"playout")}else e.advanceAfterAssetEnded(g,v,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,i=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!i?!1:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let n=this.media;!n&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(n=this.primaryMedia);const r=(t=n)==null?void 0:t.currentTime;if(!(r===void 0||!bt(r)))return r}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){const i=e.interstitial.appendInPlace,n=e.media;if(i&&n===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&n){this.detachedData={media:n};return}const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${Qi(r)}`),this.detachedData=r}else t&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}transferMediaTo(e,t){var i,n;if(e.media===t)return;let r=null;const o=this.hls,u=e!==o,c=u&&e.interstitial.appendInPlace,d=(i=this.detachedData)==null?void 0:i.mediaSource;let f;if(o.media)c&&(r=o.transferMedia(),this.detachedData=r),f="Primary";else if(d){const b=this.getBufferingPlayer();b?(r=b.transferMedia(),f=`${b}`):f="detached MediaSource"}else f="detached media";if(!r){if(d)r=this.detachedData,this.log(`using detachedData: MediaSource ${Qi(r)}`);else if(!this.detachedData||o.media===t){const b=this.playerQueue;b.length>1&&b.forEach(_=>{if(u&&_.interstitial.appendInPlace!==c){const S=_.interstitial;this.clearInterstitial(_.interstitial,null),S.appendInPlace=!1,S.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${S}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const p=r&&"mediaSource"in r&&((n=r.mediaSource)==null?void 0:n.readyState)!=="closed",g=p&&r?r:t;this.log(`${p?"transfering MediaSource":"attaching media"} to ${u?e:"Primary"} from ${f} (media.currentTime: ${t.currentTime})`);const v=this.schedule;if(g===r&&v){const b=u&&e.assetId===v.assetIdAtEnd;g.overrides={duration:v.duration,endOfStream:!u||b,cueRemoval:!u}}e.attachMedia(g)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e?.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const i=this.timelinePos,n=this.effectivePlayingItem;if(i===-1){const r=this.hls.startPosition;if(this.log(Am("checkStart",r)),this.timelinePos=r,t.length&&t[0].cue.pre){const o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(r>=0||!this.primaryLive){const o=this.timelinePos=r>0?r:0,u=e.findItemIndexAtTime(o);this.setSchedulePosition(u)}}else if(n&&!this.playingItem){const r=e.findItemIndex(n);this.setSchedulePosition(r)}}advanceAssetBuffering(e,t){const i=e.event,n=i.findAssetIndex(t),r=mv(i,n);if(!i.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var o;const u=(o=this.schedule.items)==null?void 0:o[this.findItemIndex(e)+1];u&&this.bufferedToItem(u)}}advanceAfterAssetEnded(e,t,i){const n=mv(e,i);if(e.isAssetPastPlayoutLimit(n)){if(this.schedule){const r=this.schedule.items;if(r){const o=t+1,u=r.length;if(o>=u){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Nr(r)}) pos: ${this.timelinePos}`);const o=this.waitingItem||this.playingItem,u=this.playingLastItem;if(this.isInterstitial(o)){const f=o.event,p=this.playingAsset,g=p?.identifier,v=g?this.getAssetPlayer(g):null;if(v&&g&&(!this.eventItemsMatch(o,r)||t!==void 0&&g!==f.assetList[t].identifier)){var c;const b=f.findAssetIndex(p);if(this.log(`INTERSTITIAL_ASSET_ENDED ${b+1}/${f.assetList.length} ${Ju(p)}`),this.endedAsset=p,this.playingAsset=null,this.hls.trigger($.INTERSTITIAL_ASSET_ENDED,{asset:p,assetListIndex:b,event:f,schedule:n.slice(0),scheduleIndex:e,player:v}),o!==this.playingItem){this.itemsMatch(o,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(f,this.findItemIndex(this.playingItem),b);return}this.retreiveMediaSource(g,r),v.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&v.detachMedia()}if(!this.eventItemsMatch(o,r)&&(this.endedItem=o,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${f} ${Nr(o)}`),f.hasPlayed=!0,this.hls.trigger($.INTERSTITIAL_ENDED,{event:f,schedule:n.slice(0),scheduleIndex:e}),f.cue.once)){var d;this.updateSchedule();const b=(d=this.schedule)==null?void 0:d.items;if(r&&b){const _=this.findItemIndex(r);this.advanceSchedule(_,b,t,o,u)}return}}this.advanceSchedule(e,n,t,o,u)}advanceSchedule(e,t,i,n,r){const o=this.schedule;if(!o)return;const u=t[e]||null,c=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(f=>{const p=f.interstitial,g=o.findEventIndex(p.identifier);(ge+1)&&this.clearInterstitial(p,u)}),this.isInterstitial(u)){this.timelinePos=Math.min(Math.max(this.timelinePos,u.start),u.end);const f=u.event;if(i===void 0){i=o.findAssetIndex(f,this.timelinePos);const b=mv(f,i-1);if(f.isAssetPastPlayoutLimit(b)||f.appendInPlace&&this.timelinePos===u.end){this.advanceAfterAssetEnded(f,e,i);return}i=b}const p=this.waitingItem;this.assetsBuffered(u,c)||this.setBufferingItem(u);let g=this.preloadAssets(f,i);if(this.eventItemsMatch(u,p||n)||(this.waitingItem=u,this.log(`INTERSTITIAL_STARTED ${Nr(u)} ${f.appendInPlace?"append in place":""}`),this.hls.trigger($.INTERSTITIAL_STARTED,{event:f,schedule:t.slice(0),scheduleIndex:e})),!f.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${f}`);return}if(f.assetListLoader&&(f.assetListLoader.destroy(),f.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${f}`);return}this.waitingItem=this.endedItem=null,this.playingItem=u;const v=f.assetList[i];if(!v){this.advanceAfterAssetEnded(f,e,i||0);return}if(g||(g=this.getAssetPlayer(v.identifier)),g===null||g.destroyed){const b=f.assetList.length;this.warn(`asset ${i+1}/${b} player destroyed ${f}`),g=this.createAssetPlayer(f,v,i),g.loadSource()}if(!this.eventItemsMatch(u,this.bufferingItem)&&f.appendInPlace&&this.isAssetBuffered(v))return;this.startAssetPlayer(g,i,t,e,c),this.shouldPlay&&yw(g.media)}else u?(this.resumePrimary(u,e,n),this.shouldPlay&&yw(this.hls.media)):r&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(o.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var n,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Nr(e)}`),!((n=this.detachedData)!=null&&n.mediaSource)){let u=this.timelinePos;(u=e.end)&&(u=this.getPrimaryResumption(e,t),this.log(Am("resumePrimary",u)),this.timelinePos=u),this.attachPrimary(u,e)}if(!i)return;const o=(r=this.schedule)==null?void 0:r.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Nr(e)}`),this.hls.trigger($.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const i=e.start;if(this.primaryLive){const n=this.primaryDetails;if(t===0)return this.hls.startPosition;if(n&&(in.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:ti.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const n=this.primaryMedia;if(!n)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,n),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(Am("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;const n=this.hls;!n.loadingEnabled||!n.media||Math.abs((((i=n.mainForwardBufferInfo)==null?void 0:i.start)||n.media.currentTime)-e)>.5?n.startLoad(e,t):n.bufferingEnabled||n.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off($.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on($.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const i=this.hls.levels[t.level];if(!i.details)return;const n=Fi(Fi({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=n,this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const i=this.hls.audioTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=Fi(Fi({},this.altSelection),{},{audio:i});return}const r=Fi(Fi({},n),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=Fi(Fi({},this.altSelection),{},{subtitles:i});return}const r=Fi(Fi({},n),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(e,t){const i=A2(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setAudioOption(t)||n.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=A2(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setSubtitleOption(t)||t.id!==-1&&n.setSubtitleOption(i)))}onBufferCodecs(e,t){const i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const n=this.timelinePos;this.bufferedPos=n,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos.25){e.event.assetList.forEach((r,o)=>{e.event.isAssetPastPlayoutLimit(o)&&this.clearAssetPlayer(r.identifier,null)});const i=e.end+.25,n=ti.bufferInfo(this.primaryMedia,i,0);(n.end>i||(n.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${Nr(e)} (was ${Nr(t)})`),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const i=this.mediaSelection;i&&((t=this.schedule)==null||t.updateSchedule(i,[],e))}checkBuffer(e){var t;const i=(t=this.schedule)==null?void 0:t.items;if(!i)return;const n=ti.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=n.len<1),this.updateBufferedPos(n.end,i,e)}updateBufferedPos(e,t,i){const n=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!n)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const o=this.playingItem,u=this.findItemIndex(o);let c=n.findItemIndexAtTime(e);if(this.bufferedPos=r.end||(d=g.event)!=null&&d.appendInPlace&&e+.01>=g.start)&&(c=p),this.isInterstitial(r)){const v=r.event;if(p-u>1&&v.appendInPlace===!1||v.assetList.length===0&&v.assetListLoader)return}if(this.bufferedPos=e,c>f&&c>u)this.bufferedToItem(g);else{const v=this.primaryDetails;this.primaryLive&&v&&e>v.edge-v.targetduration&&g.start{const r=this.getAssetPlayer(n.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){const{items:n,events:r}=i;if(!n||!r)return t;const o=this.isInterstitial(e),u=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const c=u?u.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Nr(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(o){const d=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((f,p)=>{const g=this.getAssetPlayer(f.identifier);g&&(p===d&&g.loadSource(),g.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger($.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;const n=this.detachedData;n?n.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){const i=e.event,n=i.assetList.length===0&&!i.assetListLoader,r=i.cue.once;if(n||!r){const o=this.preloadAssets(i,t);if(o!=null&&o.interstitial.appendInPlace){const u=this.primaryMedia;u&&this.bufferAssetPlayer(o,u)}}}preloadAssets(e,t){const i=e.assetUrl,n=e.assetList.length,r=n===0&&!e.assetListLoader,o=e.cue.once;if(r){const c=e.timelineStart;if(e.appendInPlace){var u;const g=this.playingItem;!this.isInterstitial(g)&&(g==null||(u=g.nextEvent)==null?void 0:u.identifier)===e.identifier&&this.flushFrontBuffer(c+.25)}let d,f=0;if(!this.playingItem&&this.primaryLive&&(f=this.hls.startPosition,f===-1&&(f=this.hls.liveSyncPosition||0)),f&&!(e.cue.pre||e.cue.post)){const g=f-c;g>0&&(d=Math.round(g*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:n} ${e}${d?` live-start: ${f} start-offset: ${d}`:""}`),i)return this.createAsset(e,0,0,c,e.duration,i);const p=this.assetListLoader.loadAssetList(e,d);p&&(e.assetListLoader=p)}else if(!o&&n){for(let d=t;d{this.hls.trigger($.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let i=0;i1){const U=t.duration;U&&P{if(P.live){var U;const G=new Error(`Interstitials MUST be VOD assets ${e}`),N={fatal:!0,type:It.OTHER_ERROR,details:De.INTERSTITIAL_ASSET_ITEM_ERROR,error:G},O=((U=this.schedule)==null?void 0:U.findEventIndex(e.identifier))||-1;this.handleAssetItemError(N,e,O,i,G.message);return}const V=P.edge-P.fragmentStart,M=t.duration;(_||M===null||V>M)&&(_=!1,this.log(`Interstitial asset "${p}" duration change ${M} > ${V}`),t.duration=V,this.updateSchedule())};b.on($.LEVEL_UPDATED,(P,{details:U})=>S(U)),b.on($.LEVEL_PTS_UPDATED,(P,{details:U})=>S(U)),b.on($.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const D=(P,U)=>{const V=this.getAssetPlayer(p);if(V&&U.tracks){V.off($.BUFFER_CODECS,D),V.tracks=U.tracks;const M=this.primaryMedia;this.bufferingAsset===V.assetItem&&M&&!V.media&&this.bufferAssetPlayer(V,M)}};b.on($.BUFFER_CODECS,D);const R=()=>{var P;const U=this.getAssetPlayer(p);if(this.log(`buffered to end of asset ${U}`),!U||!this.schedule)return;const V=this.schedule.findEventIndex(e.identifier),M=(P=this.schedule.items)==null?void 0:P[V];this.isInterstitial(M)&&this.advanceAssetBuffering(M,t)};b.on($.BUFFERED_TO_END,R);const L=P=>()=>{if(!this.getAssetPlayer(p)||!this.schedule)return;this.shouldPlay=!0;const V=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,V,P)};return b.once($.MEDIA_ENDED,L(i)),b.once($.PLAYOUT_LIMIT_REACHED,L(1/0)),b.on($.ERROR,(P,U)=>{if(!this.schedule)return;const V=this.getAssetPlayer(p);if(U.details===De.BUFFER_STALLED_ERROR){if(V!=null&&V.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(U,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${U.error} ${e}`)}),b.on($.DESTROYING,()=>{if(!this.getAssetPlayer(p)||!this.schedule)return;const U=new Error(`Asset player destroyed unexpectedly ${p}`),V={fatal:!0,type:It.OTHER_ERROR,details:De.INTERSTITIAL_ASSET_ITEM_ERROR,error:U};this.handleAssetItemError(V,e,this.schedule.findEventIndex(e.identifier),i,U.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Ju(t)}`),this.hls.trigger($.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:b}),b}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){const i=this.getAssetPlayerQueueIndex(e);if(i!==-1){const n=this.playerQueue[i];this.log(`clear ${n} toSegment: ${t&&Nr(t)}`),this.transferMediaFromPlayer(n,t),this.playerQueue.splice(i,1),n.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,n,r){const{interstitial:o,assetItem:u,assetId:c}=e,d=o.assetList.length,f=this.playingAsset;this.endedAsset=null,this.playingAsset=u,(!f||f.identifier!==c)&&(f&&(this.clearAssetPlayer(f.identifier,i[n]),delete f.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${d} ${Ju(u)}`),this.hls.trigger($.INTERSTITIAL_ASSET_STARTED,{asset:u,assetListIndex:t,event:o,schedule:i.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var i,n;if(!this.schedule)return;const{interstitial:r,assetItem:o}=e,u=this.schedule.findEventIndex(r.identifier),c=(i=this.schedule.items)==null?void 0:i[u];if(!c)return;e.loadSource(),this.setBufferingItem(c),this.bufferingAsset=o;const d=this.getBufferingPlayer();if(d===e)return;const f=r.appendInPlace;if(f&&d?.interstitial.appendInPlace===!1)return;const p=d?.tracks||((n=this.detachedData)==null?void 0:n.tracks)||this.requiredTracks;if(f&&o!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(p&&!TD(p,e.tracks)){const g=new Error(`Asset ${Ju(o)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(p)}')`),v={fatal:!0,type:It.OTHER_ERROR,details:De.INTERSTITIAL_ASSET_ITEM_ERROR,error:g},b=r.findAssetIndex(o);this.handleAssetItemError(v,r,u,b,g.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,i=this.primaryMedia;if(!t||!i)return;const n=i.currentTime,r=t.findAssetIndex(e,n),o=e.assetList[r];if(o){const u=this.getAssetPlayer(o.identifier);if(u){const c=u.currentTime||n-o.timelineStart,d=u.duration-c;if(this.warn(`Stalled at ${c} of ${c+d} in ${u} ${e} (media.currentTime: ${n})`),c&&(d/i.playbackRate<.5||u.bufferedInPlaceToEnd(i))&&u.hls){const f=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,f,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime!_.error))t.error=b;else for(let _=n;_{const D=parseFloat(_.DURATION);this.createAsset(r,S,f,c+f,D,_.URI),f+=D}),r.duration=f,this.log(`Loaded asset-list with duration: ${f} (was: ${d}) ${r}`);const p=this.waitingItem,g=p?.event.identifier===o;this.updateSchedule();const v=(n=this.bufferingItem)==null?void 0:n.event;if(g){var b;const _=this.schedule.findEventIndex(o),S=(b=this.schedule.items)==null?void 0:b[_];if(S){if(!this.playingItem&&this.timelinePos>S.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==_){r.error=new Error(`Interstitial ${u.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(S)}this.setSchedulePosition(_)}else if(v?.identifier===o){const _=r.assetList[0];if(_){const S=this.getAssetPlayer(_.identifier);if(v.appendInPlace){const D=this.primaryMedia;S&&D&&this.bufferAssetPlayer(S,D)}else S&&S.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case De.ASSET_LIST_PARSING_ERROR:case De.ASSET_LIST_LOAD_ERROR:case De.ASSET_LIST_LOAD_TIMEOUT:{const i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break}case De.BUFFER_STALLED_ERROR:{const i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace){this.handleInPlaceStall(i.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const vw=500;class j7 extends Vb{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",At.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on($.LEVEL_LOADED,this.onLevelLoaded,this),e.on($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on($.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on($.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on($.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off($.LEVEL_LOADED,this.onLevelLoaded,this),e.off($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off($.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off($.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off($.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=qe.IDLE,this.setInterval(vw),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:n}=t;if(this.fragContextChanged(i)||(As(i)&&(this.fragPrevious=i),this.state=qe.IDLE),!n)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let o;const u=i.start;for(let d=0;d=r[d].start&&u<=r[d].end){o=r[d];break}const c=i.start+i.duration;o?o.end=c:(o={start:u,end:c},r.push(o)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}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;unew wh(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const n=new wh(i);return this.tracksBuffered[n.id]=[],n}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,At.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.state!==qe.STOPPED&&this.setInterval(vw)}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 c=r[u];if(u>=r.length||!c)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 d=0;if(o.live||(i=c.details)!=null&&i.live){if(o.deltaUpdateFailed)return;const p=this.mainDetails;if(!p){this.startFragRequested=!1;return}const g=p.fragments[0];if(!c.details)o.hasProgramDateTime&&p.hasProgramDateTime?(kp(o,p),d=o.fragmentStart):g&&(d=g.start,wx(o,d));else{var f;d=this.alignPlaylists(o,c.details,(f=this.levelLastLoaded)==null?void 0:f.details),d===0&&g&&(d=g.start,wx(o,d))}p&&!this.startFragRequested&&this.setStartPosition(p,d)}c.details=o,this.levelLastLoaded=c,u===n&&(this.hls.trigger($.SUBTITLE_TRACK_UPDATED,{details:o,id:u,groupId:t.groupId}),this.tick(),o.live&&!this.fragCurrent&&this.media&&this.state===qe.IDLE&&(au(null,o.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.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&&gc(n.method)){const o=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer,$b(n.method)).catch(u=>{throw r.trigger($.ERROR,{type:It.MEDIA_ERROR,details:De.FRAG_DECRYPT_ERROR,fatal:!1,error:u,reason:u.message,frag:t}),u}).then(u=>{const c=performance.now();r.trigger($.FRAG_DECRYPTED,{frag:t,payload:u,stats:{tstart:o,tdecrypt:c}})}).catch(u=>{this.warn(`${u.name}: ${u.message}`),this.state=qe.IDLE})}}doTick(){if(!this.media){this.state=qe.IDLE;return}if(this.state===qe.IDLE){const{currentTrackId:e,levels:t}=this,i=t?.[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;const{config:n}=this,r=this.getLoadPosition(),o=ti.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,n.maxBufferHole),{end:u,len:c}=o,d=i.details,f=this.hls.maxBufferLength+d.levelTargetDuration;if(c>f)return;const p=d.fragments,g=p.length,v=d.edge;let b=null;const _=this.fragPrevious;if(uv-R?0:R;b=au(_,p,Math.max(p[0].start,u),L),!b&&_&&_.start{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)}}}}const H7={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},jL=s=>String.fromCharCode(H7[s]||s),Mr=15,qa=100,V7={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},G7={17:2,18:4,21:6,22:8,23:10,19:13,20:15},z7={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},q7={25:2,26:4,29:6,30:8,31:10,27:13,28:15},K7=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Y7{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;Ui.log(`${this.time} [${e}] ${i}`)}}}const jl=function(e){const t=[];for(let i=0;iqa&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=qa)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i=144&&this.backSpace();const t=jL(e);if(this.pos>=qa){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t"pacData = "+Qi(e));let t=e.row-1;if(this.nrRollUpRows&&t"bkgData = "+Qi(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;r0&&(e?i="["+t.join(" | ")+"]":i=t.join(` `)),i}getTextAndFormat(){return this.rows}}class xw{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 pv(i),this.nonDisplayedMemory=new pv(i),this.lastOutputScreen=new pv(i),this.currRollUpRow=this.displayedMemory.rows[Mr-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[Mr-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;it+": "+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: "+Qi(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 bw{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Z7(),this.logger=void 0;const n=this.logger=new Y7;this.channels=[null,new xw(e,t,n),new xw(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"["+jl([t[i],t[i+1]])+"] -> ("+jl([n,r])+")");const c=this.cmdHistory;if(n>=16&&n<=31){if(Q7(n,r,c)){Cm(null,null,c),this.logger.log(3,()=>"Repeated command ("+jl([n,r])+") is dropped");continue}Cm(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 Cm(null,null,c);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 "+jl([n,r])+" orig: "+jl([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 ("+jl([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?V7[e]:z7[e]:i=o===1?G7[e]:q7[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 '"+jL(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 = "+jl(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=K7[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;e100)throw new Error("Position must be between 0 and 100.");V=O,this.hasBeenReset=!0}})),Object.defineProperty(f,"positionAlign",r({},p,{get:function(){return M},set:function(O){const K=n(O);if(!K)throw new SyntaxError("An invalid or illegal string was specified.");M=K,this.hasBeenReset=!0}})),Object.defineProperty(f,"size",r({},p,{get:function(){return G},set:function(O){if(O<0||O>100)throw new Error("Size must be between 0 and 100.");G=O,this.hasBeenReset=!0}})),Object.defineProperty(f,"align",r({},p,{get:function(){return N},set:function(O){const K=n(O);if(!K)throw new SyntaxError("An invalid or illegal string was specified.");N=K,this.hasBeenReset=!0}})),f.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o})();class J7{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function HL(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 e${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=0&&i<=100)return this.set(e,i),!0}return!1}}function VL(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],c=o[1];e(u,c)}}const Nx=new tT(0,0,""),km=Nx.align==="middle"?"middle":"center";function t$(s,e,t){const i=s;function n(){const u=HL(s);if(u===null)throw new Error("Malformed timestamp: "+i);return s=s.replace(/^[^\sa-zA-Z-]+/,""),u}function r(u,c){const d=new e$;VL(u,function(g,v){let b;switch(g){case"region":for(let _=t.length-1;_>=0;_--)if(t[_].id===v){d.set(g,t[_].region);break}break;case"vertical":d.alt(g,v,["rl","lr"]);break;case"line":b=v.split(","),d.integer(g,b[0]),d.percent(g,b[0])&&d.set("snapToLines",!1),d.alt(g,b[0],["auto"]),b.length===2&&d.alt("lineAlign",b[1],["start",km,"end"]);break;case"position":b=v.split(","),d.percent(g,b[0]),b.length===2&&d.alt("positionAlign",b[1],["start",km,"end","line-left","line-right","auto"]);break;case"size":d.percent(g,v);break;case"align":d.alt(g,v,["start",km,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let f=d.get("line","auto");f==="auto"&&Nx.line===-1&&(f=-1),c.line=f,c.lineAlign=d.get("lineAlign","start"),c.snapToLines=d.get("snapToLines",!0),c.size=d.get("size",100),c.align=d.get("align",km);let p=d.get("position","auto");p==="auto"&&Nx.position===50&&(p=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=p}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 GL(s){return s.replace(//gi,` `)}class i${constructor(){this.state="INITIAL",this.buffer="",this.decoder=new J7,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=GL(r);o")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{t$(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 s$=/\r\n|\n\r|\n|\r/g,gv=function(e,t,i=0){return e.slice(i,i+t.length)===t},n$=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(!bt(t)||!bt(i)||!bt(n)||!bt(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*n,t+=3600*1e3*r,t};function iT(s,e,t){return gh(s.toString())+gh(e.toString())+gh(t)}const r$=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 a$(s,e,t,i,n,r,o){const u=new i$,c=cr(new Uint8Array(s)).trim().replace(s$,` `).split(` `),d=[],f=e?hj(e.baseTime,e.timescale):0;let p="00:00.000",g=0,v=0,b,_=!0;u.oncue=function(S){const D=t[i];let R=t.ccOffset;const L=(g-f)/9e4;if(D!=null&&D.new&&(v!==void 0?R=t.ccOffset=D.start:r$(t,i,L)),L){if(!e){b=new Error("Missing initPTS for VTT MPEGTS");return}R=L-t.presentationOffset}const P=S.endTime-S.startTime,U=or((S.startTime+R-v)*9e4,n*9e4)/9e4;S.startTime=Math.max(U,0),S.endTime=Math.max(U+P,0);const V=S.text.trim();S.text=decodeURIComponent(encodeURIComponent(V)),S.id||(S.id=iT(S.startTime,S.endTime,V)),S.endTime>0&&d.push(S)},u.onparsingerror=function(S){b=S},u.onflush=function(){if(b){o(b);return}r(d)},c.forEach(S=>{if(_)if(gv(S,"X-TIMESTAMP-MAP=")){_=!1,S.slice(16).split(",").forEach(D=>{gv(D,"LOCAL:")?p=D.slice(6):gv(D,"MPEGTS:")&&(g=parseInt(D.slice(7)))});try{v=n$(p)/1e3}catch(D){b=D}return}else S===""&&(_=!1);u.parse(S+` `)}),u.flush()}const yv="stpp.ttml.im1t",zL=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,qL=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,o$={left:"start",center:"center",right:"end",start:"start",end:"end"};function Tw(s,e,t,i){const n=mi(new Uint8Array(s),["mdat"]);if(n.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const r=n.map(u=>cr(u)),o=dj(e.baseTime,1,e.timescale);try{r.forEach(u=>t(l$(u,o)))}catch(u){i(u)}}function l$(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((p,g)=>(p[g]=n.getAttribute(`ttp:${g}`)||r[g],p),{}),u=n.getAttribute("xml:space")!=="preserve",c=_w(vv(n,"styling","style")),d=_w(vv(n,"layout","region")),f=vv(n,"body","[begin]");return[].map.call(f,p=>{const g=KL(p,u);if(!g||!p.hasAttribute("begin"))return null;const v=bv(p.getAttribute("begin"),o),b=bv(p.getAttribute("dur"),o);let _=bv(p.getAttribute("end"),o);if(v===null)throw Sw(p);if(_===null){if(b===null)throw Sw(p);_=v+b}const S=new tT(v-e,_-e,g);S.id=iT(S.startTime,S.endTime,S.text);const D=d[p.getAttribute("region")],R=c[p.getAttribute("style")],L=u$(D,R,c),{textAlign:P}=L;if(P){const U=o$[P];U&&(S.lineAlign=U),S.align=P}return zi(S,L),S}).filter(p=>p!==null)}function vv(s,e,t){const i=s.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function _w(s){return s.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function KL(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?KL(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function u$(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,c)=>{const d=xv(e,i,c)||xv(s,i,c)||xv(n,i,c);return d&&(u[c]=d),u},{})}function xv(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function Sw(s){return new Error(`Could not parse ttml timestamp ${s}`)}function bv(s,e){if(!s)return null;let t=HL(s);return t===null&&(zL.test(s)?t=c$(s,e):qL.test(s)&&(t=d$(s,e))),t}function c$(s,e){const t=zL.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 d$(s,e){const t=qL.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 Dm{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}}class h${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=ww(),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($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.MANIFEST_LOADED,this.onManifestLoaded,this),e.on($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on($.FRAG_LOADING,this.onFragLoading,this),e.on($.FRAG_LOADED,this.onFragLoaded,this),e.on($.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on($.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on($.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on($.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on($.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.MANIFEST_LOADED,this.onManifestLoaded,this),e.off($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off($.FRAG_LOADING,this.onFragLoading,this),e.off($.FRAG_LOADED,this.onFragLoaded,this),e.off($.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off($.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off($.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off($.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off($.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new Dm(this,"textTrack1"),t=new Dm(this,"textTrack2"),i=new Dm(this,"textTrack3"),n=new Dm(this,"textTrack4");this.cea608Parser1=new bw(1,e,t),this.cea608Parser2=new bw(3,i,n)}addCues(e,t,i,n,r){let o=!1;for(let u=r.length;u--;){const c=r[u],d=f$(c[0],c[1],t,i);if(d>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],i),o=!0,d/(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($.CUES_PARSED,{type:"captions",cues:u,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r,trackId:o}){const{unparsedVttFrags:u}=this;i===At.MAIN&&(this.initPTS[t.cc]={baseTime:n,timescale:r,trackId:o}),u.length&&(this.unparsedVttFrags=[],u.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded($.FRAG_LOADED,c):this.hls.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let n=0;n{nc(n[r]),delete n[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ww(),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;ir.textCodec===yv);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(EL(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const o=this.media,u=o?Gm(o.textTracks):null;if(this.tracks.forEach((c,d)=>{let f;if(u){let p=null;for(let g=0;gd!==null).map(d=>d.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.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($.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===At.MAIN){var i,n;const{cea608Parser1:r,cea608Parser2:o,lastSn:u}=this,{cc:c,sn:d}=t.frag,f=(i=(n=t.part)==null?void 0:n.index)!=null?i:-1;r&&o&&(d!==u+1||d===u&&f!==this.lastPartIndex+1||c!==this.lastCc)&&(r.reset(),o.reset()),this.lastCc=c,this.lastSn=d,this.lastPartIndex=f}}onFragLoaded(e,t){const{frag:i,payload:n}=t;if(i.type===At.SUBTITLE)if(n.byteLength){const r=i.decryptdata,o="stats"in t;if(r==null||!r.encrypted||o){const u=this.tracks[i.level],c=this.vttCCs;c[i.cc]||(c[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),u&&u.textCodec===yv?this._parseIMSC1(i,n):this._parseVTTs(t)}}else this.hls.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;Tw(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),i.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{i.logger.log(`Failed to parse IMSC1: ${n}`),i.trigger($.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 c=this.hls,d=(t=i.initSegment)!=null&&t.data?_r(i.initSegment.data,new Uint8Array(n)).buffer:n;a$(d,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,f=>{this._appendCues(f,i.level),c.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},f=>{const p=f.message==="Missing initPTS for VTT MPEGTS";p?o.push(e):this._fallbackToIMSC1(i,n),c.logger.log(`Failed to parse VTT cue: ${f}`),!(p&&u>i.cc)&&c.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:f})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||Tw(t,this.initPTS[e.cc],()=>{i.textCodec=yv,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=>FL(n,r))}else{const n=this.tracks[t];if(!n)return;const r=n.default?"default":"subtitles"+t;i.trigger($.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===At.SUBTITLE&&this.onFragLoaded($.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:n}=t;if(!(i.type===At.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let r=0;rIx(u[c],t,i))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:u}=this;Object.keys(u).forEach(c=>Ix(u[c],t,n))}}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let n=2;for(let r=0;r=16?c--:c++;const v=GL(d.trim()),b=iT(e,t,v);s!=null&&(p=s.cues)!=null&&p.getCueById(b)||(o=new f(e,t,v),o.id=b,o.line=g+1,o.align="left",o.position=10+Math.min(80,Math.floor(c*8/32)*10),n.push(o))}return s&&n.length&&(n.sort((g,v)=>g.line==="auto"||v.line==="auto"?0:g.line>8&&v.line>8?v.line-g.line:g.line-v.line),n.forEach(g=>FL(s,g))),n}};function g$(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const y$=/(\d+)-(\d+)\/(\d+)/;class Aw{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||T$,this.controller=new self.AbortController,this.stats=new Ob}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=v$(e,this.controller.signal),o=e.responseType==="arraybuffer",u=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&&bt(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout),(kh(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(p=>{var g;this.response=this.loader=p;const v=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},d-(v-n.loading.start)),!p.ok){const{status:_,statusText:S}=p;throw new _$(S||"fetch, bad network response",_,p)}n.loading.first=v,n.total=b$(p.headers)||n.total;const b=(g=this.callbacks)==null?void 0:g.onProgress;return b&&bt(t.highWaterMark)?this.loadProgressively(p,n,e,t.highWaterMark,b):o?p.arrayBuffer():e.responseType==="json"?p.json():p.text()}).then(p=>{var g,v;const b=this.response;if(!b)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const _=p[u];_&&(n.loaded=n.total=_);const S={url:b.url,data:p,code:b.status},D=(g=this.callbacks)==null?void 0:g.onProgress;D&&!bt(t.highWaterMark)&&D(n,e,p,b),(v=this.callbacks)==null||v.onSuccess(S,n,e,b)}).catch(p=>{var g;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const v=p&&p.code||0,b=p?p.message:null;(g=this.callbacks)==null||g.onError({code:v,text:b},e,p?p.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 nL,u=e.body.getReader(),c=()=>u.read().then(d=>{if(d.done)return o.dataLength&&r(t,i,o.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const f=d.value,p=f.length;return t.loaded+=p,p=n&&r(t,i,o.flush().buffer,e)):r(t,i,f.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function v$(s,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(zi({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function x$(s){const e=y$.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function b$(s){const e=s.get("Content-Range");if(e){const i=x$(e);if(bt(i))return i}const t=s.get("Content-Length");if(t)return parseInt(t)}function T$(s,e){return new self.Request(s.url,e)}class _$ extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const S$=/^age:\s*[\d.]+\s*$/im;class WL{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 Ob,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=>{var u;(u=this.callbacks)==null||u.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&&bt(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 d=t.status,f=t.responseType==="text"?t.responseText:null;if(d>=200&&d<300){const b=f??t.response;if(b!=null){var o,u;i.loading.end=Math.max(self.performance.now(),i.loading.first);const _=t.responseType==="arraybuffer"?b.byteLength:b.length;i.loaded=i.total=_,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);const S=(o=this.callbacks)==null?void 0:o.onProgress;S&&S(i,e,b,t);const D={url:t.responseURL,data:b,code:d};(u=this.callbacks)==null||u.onSuccess(D,i,e,t);return}}const p=r.loadPolicy.errorRetry,g=i.retry,v={url:e.url,data:void 0,code:d};if(wp(p,g,!1,v))this.retry(p);else{var c;Ui.error(`${d} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:d,text:t.statusText},e,t,i)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(wp(e,t,!0))this.retry(e);else{var i;Ui.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=Fb(e,i.retry),i.retry++,Ui.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&&S$.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}}const E$={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},w$=Fi(Fi({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:WL,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:B6,bufferController:Cj,capLevelController:Zb,errorController:H6,fpsController:k7,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:KD,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:E$},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},A$()),{},{subtitleStreamController:j7,subtitleTrackController:R7,timelineController:h$,audioStreamController:Sj,audioTrackController:Ej,emeController:yc,cmcdController:E7,contentSteeringController:A7,interstitialsController:U7});function A$(){return{cueHandler:p$,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 C$(s,e,t){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 i=Ox(s),n=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(o=>{const u=`${o==="level"?"playlist":o}LoadPolicy`,c=e[u]===void 0,d=[];r.forEach(f=>{const p=`${o}Loading${f}`,g=e[p];if(g!==void 0&&c){d.push(p);const v=i[u].default;switch(e[u]={default:v},f){case"TimeOut":v.maxLoadTimeMs=g,v.maxTimeToFirstByteMs=g;break;case"MaxRetry":v.errorRetry.maxNumRetry=g,v.timeoutRetry.maxNumRetry=g;break;case"RetryDelay":v.errorRetry.retryDelayMs=g,v.timeoutRetry.retryDelayMs=g;break;case"MaxRetryTimeout":v.errorRetry.maxRetryDelayMs=g,v.timeoutRetry.maxRetryDelayMs=g;break}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${u}": ${Qi(e[u])}`)}),Fi(Fi({},i),e)}function Ox(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(Ox):Object.keys(s).reduce((e,t)=>(e[t]=Ox(s[t]),e),{}):s}function k$(s,e){const t=s.loader;t!==Aw&&t!==WL?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):g$()&&(s.loader=Aw,s.progressive=!0,s.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const zm=2,D$=.1,L$=.05,R$=100;class I$ extends HD{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger($.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on($.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off($.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(R$),this.mediaSource=t.mediaSource;const i=this.media=t.media;En(i,"playing",this.onMediaPlaying),En(i,"waiting",this.onMediaWaiting),En(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(Vn(i,"playing",this.onMediaPlaying),Vn(i,"waiting",this.onMediaWaiting),Vn(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,n;const r=(i=this.hls)==null?void 0:i.config;if(!r)return;const o=this.media;if(!o)return;const{seeking:u}=o,c=this.seeking&&!u,d=!this.seeking&&u,f=o.paused&&!u||o.ended||o.playbackRate===0;if(this.seeking=u,e!==t){t&&(this.ended=0),this.moved=!0,u||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!f&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(d||c){c&&this.stallResolved(e);return}if(f){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&o.ended&&this.hls&&(this.ended=e||1,this.hls.trigger($.MEDIA_ENDED,{stalled:!1}));return}if(!ti.getBuffered(o).length){this.nudgeRetry=0;return}const p=ti.bufferInfo(o,e,0),g=p.nextStart||0,v=this.fragmentTracker;if(u&&v&&this.hls){const V=Cw(this.hls.inFlightFragments,e),M=p.len>zm,G=!g||V||g-e>zm&&!v.getPartialFragment(e);if(M||G)return;this.moved=!1}const b=(n=this.hls)==null?void 0:n.latestLevelDetails;if(!this.moved&&this.stalled!==null&&v){if(!(p.len>0)&&!g)return;const M=Math.max(g,p.start||0)-e,N=!!(b!=null&&b.live)?b.targetduration*2:zm,O=Lm(e,v);if(M>0&&(M<=N||O)){o.paused||this._trySkipBufferHole(O);return}}const _=r.detectStallWithCurrentTimeMs,S=self.performance.now(),D=this.waiting;let R=this.stalled;if(R===null)if(D>0&&S-D<_)R=this.stalled=D;else{this.stalled=S;return}const L=S-R;if(!u&&(L>=_||D)&&this.hls){var P;if(((P=this.mediaSource)==null?void 0:P.readyState)==="ended"&&!(b!=null&&b.live)&&Math.abs(e-(b?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger($.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(p),!this.media||!this.hls)return}const U=ti.bufferInfo(o,e,r.maxBufferHole);this._tryFixBufferStall(U,L,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger($.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;const n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&n&&n.length>1&&e>n.end(0)){const r=ti.bufferedInfo(ti.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const o=ti.timeRangesToArray(n),u=ti.bufferedInfo(o,t,0).bufferedIndex;if(u>-1&&uu)&&f-d<1&&e-d<2){const p=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${d} -> ${f} buffered index: ${c}`);this.warn(p.message),this.media.currentTime+=1e-6;let g=Lm(e,this.fragmentTracker);g&&"fragment"in g?g=g.fragment:g||(g=void 0);const v=ti.bufferInfo(this.media,e,0);this.hls.trigger($.ERROR,{type:It.MEDIA_ERROR,details:De.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:p,reason:p.message,frag:g,buffer:v.len,bufferInfo:v})}}}}}_tryFixBufferStall(e,t,i){var n,r;const{fragmentTracker:o,media:u}=this,c=(n=this.hls)==null?void 0:n.config;if(!u||!o||!c)return;const d=(r=this.hls)==null?void 0:r.latestLevelDetails,f=Lm(i,o);if((f||d!=null&&d.live&&i1&&e.len>c.maxBufferHole||e.nextStart&&(e.nextStart-ic.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const i=this.fragmentTracker,n=e.nextStart;if(i&&n){const r=i.getFragAtPos(t,At.MAIN),o=i.getFragAtPos(n,At.MAIN);if(r&&o)return o.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:i,stallReported:n,stalled:r}=this;if(!n&&r!==null&&i&&t){this.stallReported=!0;const o=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${Qi(e)})`);this.warn(o.message),t.trigger($.ERROR,{type:It.MEDIA_ERROR,details:De.BUFFER_STALLED_ERROR,fatal:!1,error:o,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:i,media:n}=this,r=(t=this.hls)==null?void 0:t.config;if(!n||!i||!r)return 0;const o=n.currentTime,u=ti.bufferInfo(n,o,0),c=o0&&u.len<1&&n.readyState<3,g=c-o;if(g>0&&(f||p)){if(g>r.maxBufferHole){let b=!1;if(o===0){const _=i.getAppendedFrag(0,At.MAIN);_&&c<_.end&&(b=!0)}if(!b&&e){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||Cw(this.hls.inFlightFragments,c))return 0;let S=!1,D=e.end;for(;D"u"))return self.VTTCue||self.TextTrackCue}function Tv(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,Qi(n?Fi({type:n},i):i))}return r}const Rm=(()=>{const s=Mx();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class O${constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger($.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on($.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on($.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on($.LEVEL_UPDATED,this.onLevelUpdated,this),e.on($.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off($.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off($.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off($.LEVEL_UPDATED,this.onLevelUpdated,this),e.off($.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var i;this.media=t.media,((i=t.overrides)==null?void 0:i.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&nc(this.id3Track,this.onEventCueEnter),this.id3Track=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;tRm&&(p=Rm),p-f<=0&&(p=f+N$);for(let v=0;vf.type===lr.audioId3&&c:n==="video"?d=f=>f.type===lr.emsg&&u:d=f=>f.type===lr.audioId3&&c||f.type===lr.emsg&&u,Ix(r,t,i,d)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:i,timelineOffset:n,enableDateRangeMetadataCues:r,interstitialsController:o}=this.hls.config;if(!r)return;const u=Mx();if(i&&n&&!o){const{fragmentStart:_,fragmentEnd:S}=e;let D=this.assetCue;D?(D.startTime=_,D.endTime=S):u&&(D=this.assetCue=Tv(u,_,S,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),D&&(D.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(D),D.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:d}=e,f=Object.keys(d);let p=this.dateRangeCuesAppended;if(c&&t){var g;if((g=c.cues)!=null&&g.length){const _=Object.keys(p).filter(S=>!f.includes(S));for(let S=_.length;S--;){var v;const D=_[S],R=(v=p[D])==null?void 0:v.cues;delete p[D],R&&Object.keys(R).forEach(L=>{const P=R[L];if(P){P.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(P)}catch{}}})}}else p=this.dateRangeCuesAppended={}}const b=e.fragments[e.fragments.length-1];if(!(f.length===0||!bt(b?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let _=0;_{if(Q!==D.id){const W=d[Q];if(W.class===D.class&&W.startDate>D.startDate&&(!K||D.startDate.01&&(Q.startTime=R,Q.endTime=V);else if(u){let W=D.attr[K];iU(K)&&(W=_D(W));const J=Tv(u,R,V,{key:K,data:W},lr.dateRange);J&&(J.id=S,this.id3Track.addCue(J),P[K]=J,o&&(K==="X-ASSET-LIST"||K==="X-ASSET-URL")&&J.addEventListener("enter",this.onEventCueEnter))}}p[S]={cues:P,dateRange:D,durationKnown:U}}}}}class M${constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,i=this.levelDetails;if(!t||!i)return;this.currentTime=t.currentTime;const n=this.computeLatency();if(n===null)return;this._latency=n;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:o}=this.config;if(!r||o===1||!i.live)return;const u=this.targetLatency;if(u===null)return;const c=n-u,d=Math.min(this.maxLatency,u+i.targetduration);if(c.05&&this.forwardBufferLength>1){const p=Math.min(2,Math.max(1,o)),g=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,v=Math.min(p,Math.max(1,g));this.changeMediaPlaybackRate(t,v)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:i,targetduration:n}=e,{liveSyncDuration:r,liveSyncDurationCount:o,lowLatencyMode:u}=this.config,c=this.hls.userConfig;let d=u&&i||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||d===0)&&(d=r!==void 0?r:o*n);const f=n;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,f)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const i=this.levelDetails;if(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 e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;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}=this,t=this.levelDetails;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.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on($.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.LEVEL_UPDATED,this.onLevelUpdated,this),e.on($.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off($.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.LEVEL_UPDATED,this.onLevelUpdated,this),e.off($.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===De.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,n;e.playbackRate!==t&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(n=this.targetLatency)==null?void 0:n.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class P$ extends Qb{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($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.MANIFEST_LOADED,this.onManifestLoaded,this),e.on($.LEVEL_LOADED,this.onLevelLoaded,this),e.on($.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on($.FRAG_BUFFERED,this.onFragBuffered,this),e.on($.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.MANIFEST_LOADED,this.onManifestLoaded,this),e.off($.LEVEL_LOADED,this.onLevelLoaded,this),e.off($.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off($.FRAG_BUFFERED,this.onFragBuffered,this),e.off($.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,c=!1,d=!1;t.levels.forEach(f=>{const p=f.attrs;let{audioCodec:g,videoCodec:v}=f;g&&(f.audioCodec=g=Tp(g,i)||void 0),v&&(v=f.videoCodec=v6(v));const{width:b,height:_,unknownCodecs:S}=f,D=S?.length||0;if(u||(u=!!(b&&_)),c||(c=!!v),d||(d=!!g),D||g&&!this.isAudioSupported(g)||v&&!this.isVideoSupported(v)){this.log(`Some or all CODECS not supported "${p.CODECS}"`);return}const{CODECS:R,"FRAME-RATE":L,"HDCP-LEVEL":P,"PATHWAY-ID":U,RESOLUTION:V,"VIDEO-RANGE":M}=p,N=`${`${U||"."}-`}${f.bitrate}-${V}-${L}-${R}-${M}-${P}`;if(r[N])if(r[N].uri!==f.url&&!f.attrs["PATHWAY-ID"]){const O=o[N]+=1;f.attrs["PATHWAY-ID"]=new Array(O+1).join(".");const K=this.createLevel(f);r[N]=K,n.push(K)}else r[N].addGroupId("audio",p.AUDIO),r[N].addGroupId("text",p.SUBTITLES);else{const O=this.createLevel(f);r[N]=O,o[N]=1,n.push(O)}}),this.filterAndSortMediaOptions(n,t,u,c,d)}createLevel(e){const t=new wh(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const n=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(n.message),t.supportedResult=OD(n,[])}return t}isAudioSupported(e){return Sh(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Sh(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,n,r){var o;let u=[],c=[],d=e;const f=((o=t.stats)==null?void 0:o.parsing)||{};if((i||n)&&r&&(d=d.filter(({videoCodec:R,videoRange:L,width:P,height:U})=>(!!R||!!(P&&U))&&k6(L))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let R="no level with compatible codecs found in manifest",L=R;t.levels.length&&(L=`one or more CODECS in variant not supported: ${Qi(t.levels.map(U=>U.attrs.CODECS).filter((U,V,M)=>M.indexOf(U)===V))}`,this.warn(L),R+=` (${L})`);const P=new Error(R);this.hls.trigger($.ERROR,{type:It.MEDIA_ERROR,details:De.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:P,reason:L})}}),f.end=performance.now();return}t.audioTracks&&(u=t.audioTracks.filter(R=>!R.audioCodec||this.isAudioSupported(R.audioCodec)),Dw(u)),t.subtitles&&(c=t.subtitles,Dw(c));const p=d.slice(0);d.sort((R,L)=>{if(R.attrs["HDCP-LEVEL"]!==L.attrs["HDCP-LEVEL"])return(R.attrs["HDCP-LEVEL"]||"")>(L.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&R.height!==L.height)return R.height-L.height;if(R.frameRate!==L.frameRate)return R.frameRate-L.frameRate;if(R.videoRange!==L.videoRange)return _p.indexOf(R.videoRange)-_p.indexOf(L.videoRange);if(R.videoCodec!==L.videoCodec){const P=b2(R.videoCodec),U=b2(L.videoCodec);if(P!==U)return U-P}if(R.uri===L.uri&&R.codecSet!==L.codecSet){const P=bp(R.codecSet),U=bp(L.codecSet);if(P!==U)return U-P}return R.averageBitrate!==L.averageBitrate?R.averageBitrate-L.averageBitrate:0});let g=p[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==p.length)){for(let R=0;RP&&P===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=U)}break}const b=r&&!n,_=this.hls.config,S=!!(_.audioStreamController&&_.audioTrackController),D={levels:d,audioTracks:u,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:n,altAudio:S&&!b&&u.some(R=>!!R.url)};f.end=performance.now(),this.hls.trigger($.MANIFEST_PARSED,D)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}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"),p=e<0;if(this.hls.trigger($.ERROR,{type:It.OTHER_ERROR,details:De.LEVEL_SWITCH_ERROR,level:e,fatal:p,error:f,reason:f.message}),p)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&&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 c={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($.LEVEL_SWITCHING,c);const d=o.details;if(!d||d.live){const f=this.switchParams(o.uri,n?.details,d);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}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),i=e.filter(n=>t.indexOf(n)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i}}onError(e,t){t.fatal||!t.context||t.context.type===yi.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===At.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=t.levelInfo;if(!o){var u;this.warn(`Invalid level index ${n}`),(u=t.deliveryDirectives)!=null&&u.skip&&(r.deltaUpdateFailed=!0);return}if(o===this.currentLevel||t.withoutMultiVariant){o.fragmentError===0&&(o.loadError=0);let c=o.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(n,t,c)}else(i=t.deliveryDirectives)!=null&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=this.getUrlWithDirectives(e.uri,t),n=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],o=e.details,u=o?.age;this.log(`Loading level index ${n}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${u&&o.live?" age "+u.toFixed(1)+(o.type&&" "+o.type||""):""} ${i}`),this.hls.trigger($.LEVEL_LOADING,{url:i,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||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;if(this._levels.length===1)return;const i=this._levels.filter((r,o)=>o!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(u=>u.level=-1)),!1));tL(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const n=i.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger($.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($.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function Dw(s){const e={};s.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function XL(){return self.SourceBuffer||self.WebKitSourceBuffer}function QL(){if(!ul())return!1;const e=XL();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function B$(){if(!QL())return!1;const s=ul();return typeof s?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(Eh(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(Eh(e,"audio"))))}function F$(){var s;const e=XL();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}const U$=100;class j$ extends Vb{constructor(e,t,i){super(e,t,i,"stream-controller",At.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const n=this.media,r=n?n.currentTime:null;if(r===null||!bt(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const o=this.getFwdBufferInfoAtPos(n,r,At.MAIN,0);if(o===null||o.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${o?o.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on($.MANIFEST_PARSED,this.onManifestParsed,this),e.on($.LEVEL_LOADING,this.onLevelLoading,this),e.on($.LEVEL_LOADED,this.onLevelLoaded,this),e.on($.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on($.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on($.BUFFER_CREATED,this.onBufferCreated,this),e.on($.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on($.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on($.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off($.MANIFEST_PARSED,this.onManifestParsed,this),e.off($.LEVEL_LOADED,this.onLevelLoaded,this),e.off($.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off($.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off($.BUFFER_CREATED,this.onBufferCreated,this),e.off($.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off($.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off($.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:i,hls:n}=this;if(this.stopLoad(),this.setInterval(U$),this.level=-1,!this.startFragRequested){let r=n.startLevel;r===-1&&(n.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=n.firstAutoLevel),n.nextLoadLevel=r,this.level=n.loadLevel,this._hasEnoughToStart=!!t}i>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=qe.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=qe.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case qe.WAITING_LEVEL:{const{levels:e,level:t}=this,i=e?.[t],n=i?.details;if(n&&(!n.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(n))break;this.state=qe.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=qe.IDLE;break}break}case qe.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===qe.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:n}=this;if(t===null||!n&&!this.primaryPrefetch&&(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 c=this.getLevelDetails();if(c&&this._streamEnded(u,c)){const _={};this.altAudio===2&&(_.type="video"),this.hls.trigger($.BUFFER_EOS,_),this.state=qe.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 d=o.details;if(!d||this.state===qe.WAITING_LEVEL||this.waitForLive(o)){this.level=r,this.state=qe.WAITING_LEVEL,this.startFragRequested=!1;return}const f=u.len,p=this.getMaxBufferLength(o.maxBitrate);if(f>=p)return;this.backtrackFragment&&this.backtrackFragment.start>u.end&&(this.backtrackFragment=null);const g=this.backtrackFragment?this.backtrackFragment.start:u.end;let v=this.getNextFragment(g,d);if(this.couldBacktrack&&!this.fragPrevious&&v&&As(v)&&this.fragmentTracker.getState(v)!==$s.OK){var b;const S=((b=this.backtrackFragment)!=null?b:v).sn-d.startSN,D=d.fragments[S-1];D&&v.cc===D.cc&&(v=D,this.fragmentTracker.removeFragment(D))}else this.backtrackFragment&&u.len&&(this.backtrackFragment=null);if(v&&this.isLoopLoading(v,g)){if(!v.gap){const S=this.audioOnly&&!this.altAudio?Wi.AUDIO:Wi.VIDEO,D=(S===Wi.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;D&&this.afterBufferFlushed(D,S,At.MAIN)}v=this.getNextFragmentLoopLoading(v,d,u,At.MAIN,p)}v&&(v.initSegment&&!v.initSegment.data&&!this.bitrateTest&&(v=v.initSegment),this.loadFragment(v,o,g))}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);n===$s.NOT_LOADED||n===$s.PARTIAL?As(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,At.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=o-t.maxFragLookUpTolerance&&r<=u;if(n!==null&&i.duration>n&&(r{this.hls&&this.hls.trigger($.AUDIO_TRACK_SWITCHED,t)}),i.trigger($.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger($.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=Sp(t.url,this.hls);if(i){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=i?2:0,this.tick()}onBufferCreated(e,t){const i=t.tracks;let n,r,o=!1;for(const u in i){const c=i[u];if(c.id==="main"){if(r=u,n=c,u==="video"){const d=i[u];d&&(this.videoBuffer=d.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,r=i.type===At.MAIN;if(r){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===qe.PARSED&&(this.state=qe.IDLE);return}const u=n?n.stats:i.stats;this.fragLastKbps=Math.round(8*u.total/(u.buffering.end-u.loading.first)),As(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,n)}const o=this.media;o&&(!this._hasEnoughToStart&&ti.getBuffered(o).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=qe.ERROR;return}switch(t.details){case De.FRAG_GAP:case De.FRAG_PARSING_ERROR:case De.FRAG_DECRYPT_ERROR:case De.FRAG_LOAD_ERROR:case De.FRAG_LOAD_TIMEOUT:case De.KEY_LOAD_ERROR:case De.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(At.MAIN,t);break;case De.LEVEL_LOAD_ERROR:case De.LEVEL_LOAD_TIMEOUT:case De.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===qe.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===yi.LEVEL&&(this.state=qe.IDLE);break;case De.BUFFER_ADD_CODEC_ERROR:case De.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case De.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case De.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=qe.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Wi.AUDIO||!this.altAudio){const i=(t===Wi.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t,At.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t0&&(c{const{hls:n}=this,r=i?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=qe.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const o=r.stats;o.parsing.start=o.parsing.end=o.buffering.start=o.buffering.end=self.performance.now(),n.trigger($.FRAG_LOADED,i),r.bitrateTest=!1}).catch(i=>{this.state===qe.STOPPED||this.state===qe.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:i}=this,{remuxResult:n,chunkMeta:r}=e,o=this.getCurrentContext(r);if(!o){this.resetWhenMissingContext(r);return}const{frag:u,part:c,level:d}=o,{video:f,text:p,id3:g,initSegment:v}=n,{details:b}=d,_=this.altAudio?void 0:n.audio;if(this.fragContextChanged(u)){this.fragmentTracker.removeFragment(u);return}if(this.state=qe.PARSING,v){const S=v.tracks;if(S){const P=u.initSegment||u;if(this.unhandledEncryptionError(v,u))return;this._bufferInitSegment(d,S,P,r),i.trigger($.FRAG_PARSING_INIT_SEGMENT,{frag:P,id:t,tracks:S})}const D=v.initPTS,R=v.timescale,L=this.initPTS[u.cc];if(bt(D)&&(!L||L.baseTime!==D||L.timescale!==R)){const P=v.trackId;this.initPTS[u.cc]={baseTime:D,timescale:R,trackId:P},i.trigger($.INIT_PTS_FOUND,{frag:u,id:t,initPTS:D,timescale:R,trackId:P})}}if(f&&b){_&&f.type==="audiovideo"&&this.logMuxedErr(u);const S=b.fragments[u.sn-1-b.startSN],D=u.sn===b.startSN,R=!S||u.cc>S.cc;if(n.independent!==!1){const{startPTS:L,endPTS:P,startDTS:U,endDTS:V}=f;if(c)c.elementaryStreams[f.type]={startPTS:L,endPTS:P,startDTS:U,endDTS:V};else if(f.firstKeyFrame&&f.independent&&r.id===1&&!R&&(this.couldBacktrack=!0),f.dropped&&f.independent){const M=this.getMainFwdBufferInfo(),G=(M?M.end:this.getLoadPosition())+this.config.maxBufferHole,N=f.firstKeyFramePTS?f.firstKeyFramePTS:L;if(!D&&Gzm&&(u.gap=!0);u.setElementaryStreamInfo(f.type,L,P,U,V),this.backtrackFragment&&(this.backtrackFragment=u),this.bufferFragmentData(f,u,c,r,D||R)}else if(D||R)u.gap=!0;else{this.backtrack(u);return}}if(_){const{startPTS:S,endPTS:D,startDTS:R,endDTS:L}=_;c&&(c.elementaryStreams[Wi.AUDIO]={startPTS:S,endPTS:D,startDTS:R,endDTS:L}),u.setElementaryStreamInfo(Wi.AUDIO,S,D,R,L),this.bufferFragmentData(_,u,c,r)}if(b&&g!=null&&g.samples.length){const S={id:t,frag:u,details:b,samples:g.samples};i.trigger($.FRAG_PARSING_METADATA,S)}if(b&&p){const S={id:t,frag:u,details:b,samples:p.samples};i.trigger($.FRAG_PARSING_USERDATA,S)}}logMuxedErr(e){this.warn(`${As(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,n){if(this.state!==qe.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:r,video:o,audiovideo:u}=t;if(r){const d=e.audioCodec;let f=Fm(r.codec,d);f==="mp4a"&&(f="mp4a.40.5");const p=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){f&&(f.indexOf("mp4a.40.5")!==-1?f="mp4a.40.2":f="mp4a.40.5");const g=r.metadata;g&&"channelCount"in g&&(g.channelCount||1)!==1&&p.indexOf("firefox")===-1&&(f="mp4a.40.5")}f&&f.indexOf("mp4a.40.5")!==-1&&p.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(f="mp4a.40.2",this.log(`Android: force audio codec to ${f}`)),d&&d!==f&&this.log(`Swapping manifest audio codec "${d}" for "${f}"`),r.levelCodec=f,r.id=At.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${f||""}/${d||""}/${r.codec}]`),delete t.audiovideo}if(o){o.levelCodec=e.videoCodec,o.id=At.MAIN;const d=o.codec;if(d?.length===4)switch(d){case"hvc1":case"hev1":o.codec="hvc1.1.6.L120.90";break;case"av01":o.codec="av01.0.04M.08";break;case"avc1":o.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${o.container}, codecs[level/parsed]=[${e.videoCodec||""}/${d}]${o.codec!==d?" parsed-corrected="+o.codec:""}${o.supplemental?" supplemental="+o.supplemental:""}`),delete t.audiovideo}u&&(this.log(`Init audiovideo buffer, container:${u.container}, codecs[level/parsed]=[${e.codecs}/${u.codec}]`),delete t.video,delete t.audio);const c=Object.keys(t);if(c.length){if(this.hls.trigger($.BUFFER_CODECS,t),!this.hls)return;c.forEach(d=>{const p=t[d].initSegment;p!=null&&p.byteLength&&this.hls.trigger($.BUFFER_APPENDING,{type:d,data:p,frag:i,part:null,chunkMeta:n,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,At.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,i=e?.[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=qe.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(ti.isBuffered(e,i)?t=this.getAppendedFrag(i):ti.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($.FRAG_CHANGED,{frag:t}),(!n||n.level!==r)&&this.hls.trigger($.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return bt(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(bt(t)){const i=this.getLevelDetails(),n=this.currentFrag||(i?au(null,i.fragments,t):null);if(n){const r=n.programDateTime;if(r!==null){const o=r+(t-n.start)*1e3;return new Date(o)}}}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 $$ extends wr{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[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.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=De.KEY_LOAD_ERROR,i,n,r){return new Wa({type:It.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:i,networkDetails:n})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let n=0,r=t.length;n{if(!this.emeController)return;o.setKeyFormat(u);const c=jm(u);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const n=sh(this.config);if(n.length)return this.emeController.getKeySystemAccess(n)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,n;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const d=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,De.KEY_LOAD_ERROR,d))}const o=r.uri;if(!o)return Promise.reject(this.createKeyLoadError(e,De.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${o}"`)));const u=_v(r);let c=this.keyIdToKeyInfo[u];if((i=c)!=null&&i.decryptdata.key)return r.key=c.decryptdata.key,Promise.resolve({frag:e,keyInfo:c});if(this.emeController&&(n=c)!=null&&n.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(f=>{const{keyInfo:p}=f;return r.key=p.decryptdata.key,{frag:e,keyInfo:p}})}switch(this.log(`${this.keyIdToKeyInfo[u]?"Rel":"L"}oading${r.keyId?" keyId: "+an(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),c=this.keyIdToKeyInfo[u]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(c,e):this.loadKeyEME(c,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(c,e);default:return Promise.reject(this.createKeyLoadError(e,De.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){var n;if(!e.decryptdata.keyId&&(n=t.initSegment)!=null&&n.data){const o=a6(t.initSegment.data);if(o.length){let u=o[0];u.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${an(u)}`),al.setKeyIdForUri(e.decryptdata.uri,u)):(u=al.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${an(u)}`)),e.decryptdata.keyId=u}}if(!e.decryptdata.keyId&&!As(t))return Promise.resolve(i);const r=this.emeController.loadKey(i);return(e.keyLoadPromise=r.then(o=>(e.mediaKeySessionContext=o,i))).catch(o=>{throw e.keyLoadPromise=null,"data"in o&&(o.data.frag=t),o})}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 c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},d=i.keyLoadPolicy.default,f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},p={onSuccess:(g,v,b,_)=>{const{frag:S,keyInfo:D}=b,R=_v(D.decryptdata);if(!S.decryptdata||D!==this.keyIdToKeyInfo[R])return u(this.createKeyLoadError(S,De.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),_));D.decryptdata.key=S.decryptdata.key=new Uint8Array(g.data),S.keyLoader=null,D.loader=null,o({frag:S,keyInfo:D})},onError:(g,v,b,_)=>{this.resetLoader(v),u(this.createKeyLoadError(t,De.KEY_LOAD_ERROR,new Error(`HTTP Error ${g.code} loading key ${g.text}`),b,Fi({url:c.url,data:void 0},g)))},onTimeout:(g,v,b)=>{this.resetLoader(v),u(this.createKeyLoadError(t,De.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),b))},onAbort:(g,v,b)=>{this.resetLoader(v),u(this.createKeyLoadError(t,De.INTERNAL_ABORTED,new Error("key loading aborted"),b))}};r.load(c,f,p)})}resetLoader(e){const{frag:t,keyInfo:i,url:n}=e,r=i.loader;t.keyLoader===r&&(t.keyLoader=null,i.loader=null);const o=_v(i.decryptdata)||n;delete this.keyIdToKeyInfo[o],r&&r.destroy()}}function _v(s){if(s.keyFormat!==on.FAIRPLAY){const e=s.keyId;if(e)return an(e)}return s.uri}function Lw(s){const{type:e}=s;switch(e){case yi.AUDIO_TRACK:return At.AUDIO;case yi.SUBTITLE_TRACK:return At.SUBTITLE;default:return At.MAIN}}function Sv(s,e){let t=s.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class H${constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.LEVEL_LOADING,this.onLevelLoading,this),e.on($.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on($.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on($.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.LEVEL_LOADING,this.onLevelLoading,this),e.off($.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off($.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off($.LEVELS_UPDATED,this.onLevelsUpdated,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:yi.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:n,pathwayId:r,url:o,deliveryDirectives:u,levelInfo:c}=t;this.load({id:i,level:n,pathwayId:r,responseType:"text",type:yi.LEVEL,url:o,deliveryDirectives:u,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:o,track:u}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:yi.AUDIO_TRACK,url:r,deliveryDirectives:o,levelOrTrack:u})}onSubtitleTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:o,track:u}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:yi.SUBTITLE_TRACK,url:r,deliveryDirectives:o,levelOrTrack:u})}onLevelsUpdated(e,t){const i=this.loaders[yi.LEVEL];if(i){const n=i.context;n&&!t.levels.some(r=>r===n.levelOrTrack)&&(i.abort(),delete this.loaders[yi.LEVEL])}}load(e){var t;const i=this.hls.config;let n=this.getInternalLoader(e);if(n){const d=this.hls.logger,f=n.context;if(f&&f.levelOrTrack===e.levelOrTrack&&(f.url===e.url||f.deliveryDirectives&&!e.deliveryDirectives)){f.url===e.url?d.log(`[playlist-loader]: ignore ${e.url} ongoing request`):d.log(`[playlist-loader]: ignore ${e.url} in favor of ${f.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let r;if(e.type===yi.MANIFEST?r=i.manifestLoadPolicy.default:r=zi({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),bt((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===yi.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===yi.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===yi.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){const f=d.partTarget,p=d.targetduration;if(f&&p){const g=Math.max(f*3,p*.8)*1e3;r=zi({},r,{maxTimeToFirstByteMs:Math.min(g,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(g,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},c={onSuccess:(d,f,p,g)=>{const v=this.getInternalLoader(p);this.resetInternalLoader(p.type);const b=d.data;f.parsing.start=performance.now(),ga.isMediaPlaylist(b)||p.type!==yi.MANIFEST?this.handleTrackOrLevelPlaylist(d,f,p,g||null,v):this.handleMasterPlaylist(d,f,p,g)},onError:(d,f,p,g)=>{this.handleNetworkError(f,p,!1,d,g)},onTimeout:(d,f,p)=>{this.handleNetworkError(f,p,!0,void 0,d)}};n.load(e,u,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,n){const r=this.hls,o=e.data,u=Sv(e,i),c=ga.parseMasterPlaylist(o,u);if(c.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,c.playlistParsingError,n,t);return}const{contentSteering:d,levels:f,sessionData:p,sessionKeys:g,startTimeOffset:v,variableList:b}=c;this.variableList=b,f.forEach(R=>{const{unknownCodecs:L}=R;if(L){const{preferManagedMediaSource:P}=this.hls.config;let{audioCodec:U,videoCodec:V}=R;for(let M=L.length;M--;){const G=L[M];Sh(G,"audio",P)?(R.audioCodec=U=U?`${U},${G}`:G,Ic.audio[U.substring(0,4)]=2,L.splice(M,1)):Sh(G,"video",P)&&(R.videoCodec=V=V?`${V},${G}`:G,Ic.video[V.substring(0,4)]=2,L.splice(M,1))}}});const{AUDIO:_=[],SUBTITLES:S,"CLOSED-CAPTIONS":D}=ga.parseMasterPlaylistMedia(o,u,c);_.length&&!_.some(L=>!L.url)&&f[0].audioCodec&&!f[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),_.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ds({}),bitrate:0,url:""})),r.trigger($.MANIFEST_LOADED,{levels:f,audioTracks:_,subtitles:S,captions:D,contentSteering:d,url:u,stats:t,networkDetails:n,sessionData:p,sessionKeys:g,startTimeOffset:v,variableList:b})}handleTrackOrLevelPlaylist(e,t,i,n,r){const o=this.hls,{id:u,level:c,type:d}=i,f=Sv(e,i),p=bt(c)?c:bt(u)?u:0,g=Lw(i),v=ga.parseLevelPlaylist(e.data,f,p,g,0,this.variableList);if(d===yi.MANIFEST){const b={attrs:new ds({}),bitrate:0,details:v,name:"",url:f};v.requestScheduled=t.loading.start+ZD(v,0),o.trigger($.MANIFEST_LOADED,{levels:[b],audioTracks:[],url:f,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=v,this.handlePlaylistLoaded(v,e,t,i,n,r)}handleManifestParsingError(e,t,i,n,r){this.hls.trigger($.ERROR,{type:It.NETWORK_ERROR,details:De.MANIFEST_PARSING_ERROR,fatal:t.type===yi.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===yi.LEVEL?o+=`: ${e.level} id: ${e.id}`:(e.type===yi.AUDIO_TRACK||e.type===yi.SUBTITLE_TRACK)&&(o+=` id: ${e.id} group-id: "${e.groupId}"`);const u=new Error(o);this.hls.logger.warn(`[playlist-loader]: ${o}`);let c=De.UNKNOWN,d=!1;const f=this.getInternalLoader(e);switch(e.type){case yi.MANIFEST:c=i?De.MANIFEST_LOAD_TIMEOUT:De.MANIFEST_LOAD_ERROR,d=!0;break;case yi.LEVEL:c=i?De.LEVEL_LOAD_TIMEOUT:De.LEVEL_LOAD_ERROR,d=!1;break;case yi.AUDIO_TRACK:c=i?De.AUDIO_TRACK_LOAD_TIMEOUT:De.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case yi.SUBTITLE_TRACK:c=i?De.SUBTITLE_TRACK_LOAD_TIMEOUT:De.SUBTITLE_LOAD_ERROR,d=!1;break}f&&this.resetInternalLoader(e.type);const p={type:It.NETWORK_ERROR,details:c,fatal:d,url:e.url,loader:f,context:e,error:u,networkDetails:t,stats:r};if(n){const g=t?.url||e.url;p.response=Fi({url:g,data:void 0},n)}this.hls.trigger($.ERROR,p)}handlePlaylistLoaded(e,t,i,n,r,o){const u=this.hls,{type:c,level:d,levelOrTrack:f,id:p,groupId:g,deliveryDirectives:v}=n,b=Sv(t,n),_=Lw(n);let S=typeof n.level=="number"&&_===At.MAIN?d:void 0;const D=e.playlistParsingError;if(D){if(this.hls.logger.warn(`${D} ${e.url}`),!u.config.ignorePlaylistParsingErrors){u.trigger($.ERROR,{type:It.NETWORK_ERROR,details:De.LEVEL_PARSING_ERROR,fatal:!1,url:b,error:D,reason:D.message,response:t,context:n,level:S,parent:_,networkDetails:r,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){const R=e.playlistParsingError=new Error("No Segments found in Playlist");u.trigger($.ERROR,{type:It.NETWORK_ERROR,details:De.LEVEL_EMPTY_ERROR,fatal:!1,url:b,error:R,reason:R.message,response:t,context:n,level:S,parent:_,networkDetails:r,stats:i});return}switch(e.live&&o&&(o.getCacheAge&&(e.ageHeader=o.getCacheAge()||0),(!o.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case yi.MANIFEST:case yi.LEVEL:if(S){if(!f)S=0;else if(f!==u.levels[S]){const R=u.levels.indexOf(f);R>-1&&(S=R)}}u.trigger($.LEVEL_LOADED,{details:e,levelInfo:f||u.levels[0],level:S||0,id:p||0,stats:i,networkDetails:r,deliveryDirectives:v,withoutMultiVariant:c===yi.MANIFEST});break;case yi.AUDIO_TRACK:u.trigger($.AUDIO_TRACK_LOADED,{details:e,track:f,id:p||0,groupId:g||"",stats:i,networkDetails:r,deliveryDirectives:v});break;case yi.SUBTITLE_TRACK:u.trigger($.SUBTITLE_TRACK_LOADED,{details:e,track:f,id:p||0,groupId:g||"",stats:i,networkDetails:r,deliveryDirectives:v});break}}}class ur{static get version(){return Ah}static isMSESupported(){return QL()}static isSupported(){return B$()}static getMediaSource(){return ul()}static get Events(){return $}static get MetadataSchema(){return lr}static get ErrorTypes(){return It}static get ErrorDetails(){return De}static get DefaultConfig(){return ur.defaultConfig?ur.defaultConfig:w$}static set DefaultConfig(e){ur.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Gb,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=Y8(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=C$(ur.DefaultConfig,e,t);this.userConfig=e,i.progressive&&k$(i,t);const{abrController:n,bufferController:r,capLevelController:o,errorController:u,fpsController:c}=i,d=new u(this),f=this.abrController=new n(this),p=new V6(this),g=i.interstitialsController,v=g?this.interstitialsController=new g(this,ur):null,b=this.bufferController=new r(this,p),_=this.capLevelController=new o(this),S=new c(this),D=new H$(this),R=i.contentSteeringController,L=R?new R(this):null,P=this.levelController=new P$(this,L),U=new O$(this),V=new $$(this.config,this.logger),M=this.streamController=new j$(this,p,V),G=this.gapController=new I$(this,p);_.setStreamController(M),S.setStreamController(M);const N=[D,P,M];v&&N.splice(1,0,v),L&&N.splice(1,0,L),this.networkControllers=N;const O=[f,b,G,_,S,U,p];this.audioTrackController=this.createController(i.audioTrackController,N);const K=i.audioStreamController;K&&N.push(this.audioStreamController=new K(this,p,V)),this.subtitleTrackController=this.createController(i.subtitleTrackController,N);const Q=i.subtitleStreamController;Q&&N.push(this.subtititleStreamController=new Q(this,p,V)),this.createController(i.timelineController,O),V.emeController=this.emeController=this.createController(i.emeController,O),this.cmcdController=this.createController(i.cmcdController,O),this.latencyController=this.createController(M$,O),this.coreComponents=O,N.push(d);const W=d.onErrorOut;typeof W=="function"&&this.on($.ERROR,W,d),this.on($.MANIFEST_LOADED,D.onManifestLoaded,D)}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(this.logger.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===$.ERROR;this.trigger($.ERROR,{type:It.OTHER_ERROR,details:De.INTERNAL_EXCEPTION,fatal:n,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger($.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){if(!e||"media"in e&&!e.media){const r=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger($.ERROR,{type:It.OTHER_ERROR,details:De.ATTACH_MEDIA_ERROR,fatal:!0,error:r});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,i=t?e.media:e,n=t?e:{media:i};this._media=i,this.trigger($.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia"),this.trigger($.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger($.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,i=this._url,n=this._url=Nb.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),t&&i&&(i!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger($.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", ":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[At.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[At.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[At.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=I7()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){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 abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){C6(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=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()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0: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}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const i=BD(t);return MD(e,i,navigator.mediaCapabilities)}}ur.defaultConfig=void 0;function Rw(s,e){const t=s.includes("?")?"&":"?";return`${s}${t}v=${e}`}function ZL({src:s,muted:e=Qm,className:t}){const i=A.useRef(null),[n,r]=A.useState(!1),[o,u]=A.useState(null),[c,d]=A.useState(1),f=A.useMemo(()=>Rw(s,c),[s,c]);return A.useEffect(()=>{let p=!1,g=null,v=null,b=null;const _=i.current;if(!_)return;const S=_;r(!1),u(null),Zm(S,{muted:e});const D=()=>{v&&window.clearTimeout(v),b&&window.clearInterval(b),v=null,b=null},R=()=>{p||(D(),d(V=>V+1))};async function L(){const V=Date.now();for(;!p&&Date.now()-V<9e4;){try{const M=Rw(s,Date.now()),G=await fetch(M,{cache:"no-store"});if(G.status===403)return{ok:!1,reason:"private"};if(G.status===404)return{ok:!1,reason:"offline"};if(G.ok&&(await G.text()).includes("#EXTINF"))return{ok:!0}}catch{}await new Promise(M=>setTimeout(M,500))}return{ok:!1}}async function P(){const V=await L();if(!p){if(!V.ok){if(V.reason==="private"||V.reason==="offline"){u(V.reason),r(!0);return}window.setTimeout(()=>{p||R()},800);return}if(S.canPlayType("application/vnd.apple.mpegurl")){S.pause(),S.removeAttribute("src"),S.load(),S.src=f,S.load(),S.play().catch(()=>{});let M=Date.now(),G=-1;const N=()=>{S.currentTime>G+.01&&(G=S.currentTime,M=Date.now())},O=()=>{v||(v=window.setTimeout(()=>{v=null,!p&&Date.now()-M>3500&&R()},800))};return S.addEventListener("timeupdate",N),S.addEventListener("waiting",O),S.addEventListener("stalled",O),S.addEventListener("error",O),b=window.setInterval(()=>{p||!S.paused&&Date.now()-M>6e3&&R()},2e3),()=>{S.removeEventListener("timeupdate",N),S.removeEventListener("waiting",O),S.removeEventListener("stalled",O),S.removeEventListener("error",O)}}if(!ur.isSupported()){r(!0);return}g=new ur({lowLatencyMode:!0,liveSyncDurationCount:2,maxBufferLength:8}),g.on(ur.Events.ERROR,(M,G)=>{if(g&&G.fatal){if(G.type===ur.ErrorTypes.NETWORK_ERROR){g.startLoad();return}if(G.type===ur.ErrorTypes.MEDIA_ERROR){g.recoverMediaError();return}R()}}),g.loadSource(f),g.attachMedia(S),g.on(ur.Events.MANIFEST_PARSED,()=>{S.play().catch(()=>{})})}}let U;return(async()=>{const V=await P();typeof V=="function"&&(U=V)})(),()=>{p=!0,D();try{U?.()}catch{}try{g?.destroy()}catch{}}},[s,e,f]),n?y.jsx("div",{className:"text-xs text-gray-400 italic",children:o==="private"?"Private":o==="offline"?"Offline":"–"}):y.jsx("video",{ref:i,className:t,playsInline:!0,autoPlay:!0,muted:e,preload:"auto",crossOrigin:"anonymous",onClick:()=>{const p=i.current;p&&(p.muted=!1,p.play().catch(()=>{}))}})}const tl=s=>(s||"").replaceAll("\\","/").split("/").pop()||"",sT=s=>s.startsWith("HOT ")?s.slice(4):s,V$=s=>(s||"").trim().toLowerCase(),G$=s=>{const e=String(s??"").trim();if(!e)return[];const t=e.split(/[\n,;|]+/g).map(r=>r.trim()).filter(Boolean),i=new Set,n=[];for(const r of t){const o=r.toLowerCase();i.has(o)||(i.add(o),n.push(r))}return n.sort((r,o)=>r.localeCompare(o,void 0,{sensitivity:"base"})),n};function Iw(s){if(!Number.isFinite(s)||s<=0)return"—";const e=Math.floor(s/1e3),t=Math.floor(e/3600),i=Math.floor(e%3600/60),n=e%60;return t>0?`${t}h ${i}m`:i>0?`${i}m ${n}s`:`${n}s`}function z$(s){if(typeof s!="number"||!Number.isFinite(s)||s<=0)return"—";const e=["B","KB","MB","GB","TB"];let t=s,i=0;for(;t>=1024&&i=100?0:t>=10?1:2;return`${t.toFixed(n)} ${e[i]}`}function Nw(s){if(!s)return"—";const e=s instanceof Date?s:new Date(s),t=e.getTime();return Number.isFinite(t)?e.toLocaleString(void 0,{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):"—"}const Ev=(...s)=>{for(const e of s){const t=typeof e=="string"?Number(e):e;if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t}return null};function q$(s){if(!s||!Number.isFinite(s))return"—";const e=s>=10?0:2;return`${s.toFixed(e)} fps`}function K$(s,e){if(!s||!e)return"—";const t=Math.round(e);return`${s}×${e} (${t}p)`}function Y$(s){const e=tl(s||""),t=sT(e);if(!t)return null;const n=t.replace(/\.[^.]+$/,"").match(/_(\d{1,2})_(\d{1,2})_(\d{4})__(\d{1,2})-(\d{2})-(\d{2})$/);if(!n)return null;const r=Number(n[1]),o=Number(n[2]),u=Number(n[3]),c=Number(n[4]),d=Number(n[5]),f=Number(n[6]);return[r,o,u,c,d,f].every(p=>Number.isFinite(p))?new Date(u,r-1,o,c,d,f):null}const W$=s=>{const e=tl(s||""),t=sT(e);if(!t)return"—";const i=t.replace(/\.[^.]+$/,""),n=i.match(/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}$/);if(n?.[1])return n[1];const r=i.lastIndexOf("_");return r>0?i.slice(0,r):i},X$=s=>{const e=s,t=e.sizeBytes??e.fileSizeBytes??e.bytes??e.size??null;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:null};function Ka(...s){return s.filter(Boolean).join(" ")}function Q$(s){const[e,t]=A.useState(!1);return A.useEffect(()=>{if(typeof window>"u")return;const i=window.matchMedia(s),n=()=>t(i.matches);return n(),i.addEventListener?i.addEventListener("change",n):i.addListener(n),()=>{i.removeEventListener?i.removeEventListener("change",n):i.removeListener(n)}},[s]),e}function Z$({job:s,expanded:e,onClose:t,onToggleExpand:i,modelKey:n,modelsByKey:r,isHot:o=!1,isFavorite:u=!1,isLiked:c=!1,isWatching:d=!1,onKeep:f,onDelete:p,onToggleHot:g,onToggleFavorite:v,onToggleLike:b,onToggleWatch:_,onStopJob:S,startMuted:D=aO}){const R=A.useMemo(()=>tl(s.output?.trim()||"")||s.id,[s.output,s.id]),L=A.useMemo(()=>tl(s.output?.trim()||""),[s.output]),P=A.useMemo(()=>tl(s.output?.trim()||""),[s.output]),U=A.useMemo(()=>z$(X$(s)),[s]),V=s,M=s.status==="running",[G,N]=A.useState(!1),O=M&&G,K=A.useMemo(()=>(P||"").replace(/\.[^.]+$/,""),[P]),Q=A.useMemo(()=>M?s.id:K||s.id,[M,s.id,K]),W=L.startsWith("HOT "),re=A.useMemo(()=>{const oe=(n||"").trim();return oe||W$(s.output)},[n,s.output]),J=A.useMemo(()=>sT(L),[L]),Y=A.useMemo(()=>{const oe=Date.parse(String(s.startedAt||"")),pe=Date.parse(String(s.endedAt||""));if(Number.isFinite(oe)&&Number.isFinite(pe)&&pe>oe)return Iw(pe-oe);const Ge=s.durationSeconds;return typeof Ge=="number"&&Number.isFinite(Ge)&&Ge>0?Iw(Ge*1e3):"—"},[s]),z=A.useMemo(()=>{const oe=Y$(s.output);if(oe)return Nw(oe);const pe=V.startedAt??V.endedAt??V.createdAt??V.fileCreatedAt??V.ctime??null,Ge=pe?new Date(pe):null;return Nw(Ge&&Number.isFinite(Ge.getTime())?Ge:null)},[s.output,V.startedAt,V.endedAt,V.createdAt,V.fileCreatedAt,V.ctime]),Z=A.useMemo(()=>V$((n||re||"").trim()),[n,re]),ie=A.useMemo(()=>{const oe=r?.[Z];return G$(oe?.tags)},[r,Z]),ce=A.useMemo(()=>Vl(`/api/record/preview?id=${encodeURIComponent(Q)}&file=preview.jpg`),[Q]),j=A.useMemo(()=>Vl(`/api/record/preview?id=${encodeURIComponent(Q)}&file=thumbs.jpg`),[Q]),ee=A.useMemo(()=>Vl(`/api/record/preview?id=${encodeURIComponent(Q)}&play=1&file=index_hq.m3u8`),[Q]),[he,Te]=A.useState(ce);A.useEffect(()=>{Te(ce)},[ce]);const xe=A.useMemo(()=>Ev(V.videoWidth,V.width,V.meta?.width),[V.videoWidth,V.width,V.meta?.width]),Ae=A.useMemo(()=>Ev(V.videoHeight,V.height,V.meta?.height),[V.videoHeight,V.height,V.meta?.height]),Ke=A.useMemo(()=>Ev(V.fps,V.frameRate,V.meta?.fps,V.meta?.frameRate),[V.fps,V.frameRate,V.meta?.fps,V.meta?.frameRate]),lt=A.useMemo(()=>K$(xe,Ae),[xe,Ae]),nt=A.useMemo(()=>q$(Ke),[Ke]);A.useEffect(()=>{const oe=pe=>pe.key==="Escape"&&t();return window.addEventListener("keydown",oe),()=>window.removeEventListener("keydown",oe)},[t]);const yt=A.useMemo(()=>{const oe=`/api/record/preview?id=${encodeURIComponent(Q)}&file=index_hq.m3u8&play=1`;return Vl(M?`${oe}&t=${Date.now()}`:oe)},[Q,M]);A.useEffect(()=>{if(!M){N(!1);return}let oe=!0;const pe=new AbortController;return N(!1),(async()=>{for(let mt=0;mt<120&&oe&&!pe.signal.aborted;mt++){try{const Vt=await U8(yt,{method:"GET",cache:"no-store",signal:pe.signal,headers:{"cache-control":"no-cache"}});if(Vt.ok){const Wt=await Vt.text(),qt=Wt.includes("#EXTM3U"),Ft=/#EXTINF:/i.test(Wt)||/\.ts(\?|$)/i.test(Wt)||/\.m4s(\?|$)/i.test(Wt);if(qt&&Ft){oe&&N(!0);return}}}catch{}await new Promise(Vt=>setTimeout(Vt,500))}})(),()=>{oe=!1,pe.abort()}},[M,yt]);const it=A.useMemo(()=>{if(M)return{src:"",type:""};const oe=tl(s.output?.trim()||"");if(oe){const pe=oe.toLowerCase().split(".").pop(),Ge=pe==="mp4"?"video/mp4":pe==="ts"?"video/mp2t":"application/octet-stream";return{src:Vl(`/api/record/video?file=${encodeURIComponent(oe)}`),type:Ge}}return{src:Vl(`/api/record/video?id=${encodeURIComponent(s.id)}`),type:"video/mp4"}},[M,s.output,s.id]),Ot=A.useRef(null),pt=A.useRef(null),xt=A.useRef(null),[Pt,Ze]=A.useState(!1),[,Nt]=A.useState(0);A.useEffect(()=>{if(typeof window>"u")return;const oe=window.visualViewport;if(!oe)return;const pe=()=>Nt(Ge=>Ge+1);return pe(),oe.addEventListener("resize",pe),oe.addEventListener("scroll",pe),window.addEventListener("resize",pe),window.addEventListener("orientationchange",pe),()=>{oe.removeEventListener("resize",pe),oe.removeEventListener("scroll",pe),window.removeEventListener("resize",pe),window.removeEventListener("orientationchange",pe)}},[]);const[wt,jt]=A.useState(56),[gt,Dt]=A.useState(null),ge=!e,st=Q$("(min-width: 640px)"),Ve=ge&&st,et="player_window_v1",vt=420,ot=280,ht=12,rt=320,Gt=200;A.useEffect(()=>{if(!Pt)return;const oe=pt.current;if(!oe||oe.isDisposed?.())return;const pe=oe.el();if(!pe)return;const Ge=pe.querySelector(".vjs-control-bar");if(!Ge)return;const mt=()=>{const Wt=Math.round(Ge.getBoundingClientRect().height||0);Wt>0&&jt(Wt)};mt();let Vt=null;return typeof ResizeObserver<"u"&&(Vt=new ResizeObserver(mt),Vt.observe(Ge)),window.addEventListener("resize",mt),()=>{window.removeEventListener("resize",mt),Vt?.disconnect()}},[Pt,e]),A.useEffect(()=>Ze(!0),[]),A.useEffect(()=>{let oe=document.getElementById("player-root");oe||(oe=document.createElement("div"),oe.id="player-root");let pe=null;if(st){const Ge=Array.from(document.querySelectorAll("dialog[open]"));pe=Ge.length?Ge[Ge.length-1]:null}pe=pe??document.body,pe.appendChild(oe),oe.style.position="relative",oe.style.zIndex="2147483647",Dt(oe)},[st]),A.useEffect(()=>{const oe=pt.current;if(!oe||oe.isDisposed?.()||!O||!it.src)return;const pe=()=>{try{const Wt=oe.liveTracker;if(Wt&&typeof Wt.seekToLiveEdge=="function"){Wt.seekToLiveEdge();return}const qt=Wt?.liveCurrentTime?.();typeof qt=="number"&&Number.isFinite(qt)&&qt>0&&oe.currentTime(Math.max(0,qt-.2))}catch{}},Ge=()=>pe();oe.on("loadedmetadata",Ge);const mt=()=>pe();oe.on("playing",mt);const Vt=window.setInterval(()=>{try{if(oe.paused()||oe.seeking?.())return;const qt=oe.liveTracker?.liveCurrentTime?.();if(typeof qt!="number"||!Number.isFinite(qt))return;const Ft=oe.currentTime()||0;qt-Ft>4&&oe.currentTime(Math.max(0,qt-.2))}catch{}},1500);return pe(),()=>{try{oe.off("loadedmetadata",Ge)}catch{}try{oe.off("playing",mt)}catch{}window.clearInterval(Vt)}},[O,it.src,it.type]),A.useEffect(()=>{const oe=pt.current;if(!oe||oe.isDisposed?.()||!M||!G)return;let pe=-1,Ge=Date.now();const mt=window.setInterval(()=>{try{if(oe.paused())return;const Vt=oe.currentTime()||0;if(Vt<=pe+.01){if(Date.now()-Ge>4e3){const qt=oe.liveTracker;qt?.seekToLiveEdge?qt.seekToLiveEdge():oe.currentTime(Math.max(0,Vt+.5)),Ge=Date.now()}}else pe=Vt,Ge=Date.now()}catch{}},1e3);return()=>window.clearInterval(mt)},[M,G]),A.useLayoutEffect(()=>{if(!Pt||!Ot.current||pt.current||M)return;const oe=document.createElement("video");oe.className="video-js vjs-big-play-centered w-full h-full",oe.setAttribute("playsinline","true"),Ot.current.appendChild(oe),xt.current=oe;const pe=Le(oe,{autoplay:!0,muted:D,controls:!0,preload:"metadata",playsinline:!0,responsive:!0,fluid:!1,fill:!0,liveui:!0,html5:{vhs:{lowLatencyMode:!0}},inactivityTimeout:0,controlBar:{skipButtons:{backward:10,forward:10},volumePanel:{inline:!1},children:["skipBackward","playToggle","skipForward","volumePanel","currentTimeDisplay","durationDisplay","timeDivider","progressControl","spacer","playbackRateMenuButton","fullscreenToggle"]},playbackRates:[.5,1,1.25,1.5,2]});return pt.current=pe,pe.userActive(!0),pe.on("userinactive",()=>pe.userActive(!0)),()=>{try{pt.current&&(pt.current.dispose(),pt.current=null)}finally{xt.current&&(xt.current.remove(),xt.current=null)}}},[Pt,D,M]),A.useEffect(()=>{const oe=pt.current;if(!oe||oe.isDisposed?.())return;const pe=oe.el();pe&&pe.classList.toggle("is-live-download",!!O)},[O]),A.useEffect(()=>{if(!Pt)return;const oe=pt.current;if(!oe||oe.isDisposed?.())return;const pe=oe.currentTime()||0;if(oe.muted(D),!it.src){try{oe.pause(),oe.reset?.(),oe.error(null)}catch{}return}oe.src({src:it.src,type:it.type});const Ge=()=>{const mt=oe.play?.();mt&&typeof mt.catch=="function"&&mt.catch(()=>{})};oe.one("loadedmetadata",()=>{if(oe.isDisposed?.())return;try{oe.playbackRate(1)}catch{}const mt=/mpegurl/i.test(it.type);pe>0&&!mt&&oe.currentTime(pe),Ge()}),Ge()},[Pt,it.src,it.type,D]),A.useEffect(()=>{if(!Pt)return;const oe=pt.current;if(!oe||oe.isDisposed?.())return;const pe=()=>{s.status==="running"&&N(!1)};return oe.on("error",pe),()=>{try{oe.off("error",pe)}catch{}}},[Pt,s.status]),A.useEffect(()=>{const oe=pt.current;!oe||oe.isDisposed?.()||queueMicrotask(()=>oe.trigger("resize"))},[e]);const Bt=A.useCallback(()=>{const oe=pt.current;if(!(!oe||oe.isDisposed?.())){try{oe.pause(),oe.reset?.()}catch{}try{oe.src({src:"",type:"video/mp4"}),oe.load?.()}catch{}}},[]);A.useEffect(()=>{const oe=pe=>{const mt=(pe.detail?.file??"").trim();if(!mt)return;const Vt=tl(s.output?.trim()||"");Vt&&Vt===mt&&Bt()};return window.addEventListener("player:release",oe),()=>window.removeEventListener("player:release",oe)},[s.output,Bt]),A.useEffect(()=>{const oe=pe=>{const mt=(pe.detail?.file??"").trim();if(!mt)return;const Vt=tl(s.output?.trim()||"");Vt&&Vt===mt&&(Bt(),t())};return window.addEventListener("player:close",oe),()=>window.removeEventListener("player:close",oe)},[s.output,Bt,t]);const Lt=()=>{if(typeof window>"u")return{w:0,h:0,ox:0,oy:0,bottomInset:0};const oe=window.visualViewport;if(oe&&Number.isFinite(oe.width)&&Number.isFinite(oe.height)){const Vt=Math.floor(oe.width),Wt=Math.floor(oe.height),qt=Math.floor(oe.offsetLeft||0),Ft=Math.floor(oe.offsetTop||0),Js=Math.max(0,Math.floor(window.innerHeight-(oe.height+oe.offsetTop)));return{w:Vt,h:Wt,ox:qt,oy:Ft,bottomInset:Js}}const pe=document.documentElement,Ge=pe?.clientWidth||window.innerWidth,mt=pe?.clientHeight||window.innerHeight;return{w:Ge,h:mt,ox:0,oy:0,bottomInset:0}},si=A.useCallback((oe,pe)=>{if(typeof window>"u")return oe;const{w:Ge,h:mt}=Lt(),Vt=Ge-ht*2,Wt=mt-ht*2;let qt=oe.w,Ft=oe.h;pe&&Number.isFinite(pe)&&pe>.1?(qt=Math.max(rt,qt),Ft=qt/pe,FtVt&&(qt=Vt,Ft=qt/pe),Ft>Wt&&(Ft=Wt,qt=Ft*pe)):(qt=Math.max(rt,Math.min(qt,Vt)),Ft=Math.max(Gt,Math.min(Ft,Wt)));const Js=Math.max(ht,Math.min(oe.x,Ge-qt-ht)),_s=Math.max(ht,Math.min(oe.y,mt-Ft-ht));return{x:Js,y:_s,w:qt,h:Ft}},[]),We=A.useCallback(()=>{if(typeof window>"u")return{x:ht,y:ht,w:vt,h:ot};try{const qt=window.localStorage.getItem(et);if(qt){const Ft=JSON.parse(qt);if(typeof Ft.x=="number"&&typeof Ft.y=="number"&&typeof Ft.w=="number"&&typeof Ft.h=="number"){const Js=Ft.w,_s=Ft.h,cs=Ft.x,wn=Ft.y;return si({x:cs,y:wn,w:Js,h:_s},Js/_s)}}}catch{}const{w:oe,h:pe}=Lt(),Ge=vt,mt=ot,Vt=Math.max(ht,oe-Ge-ht),Wt=Math.max(ht,pe-mt-ht);return si({x:Vt,y:Wt,w:Ge,h:mt},Ge/mt)},[si]),[Ct,Mt]=A.useState(()=>We()),pi=Ve&&Ct.w<380,Ei=A.useCallback(oe=>{if(!(typeof window>"u"))try{window.localStorage.setItem(et,JSON.stringify(oe))}catch{}},[]),Tt=A.useRef(Ct);A.useEffect(()=>{Tt.current=Ct},[Ct]),A.useEffect(()=>{Ve&&Mt(We())},[Ve,We]),A.useEffect(()=>{if(!Ve)return;const oe=()=>Mt(pe=>si(pe,pe.w/pe.h));return window.addEventListener("resize",oe),()=>window.removeEventListener("resize",oe)},[Ve,si]);const ft=A.useRef(null);A.useEffect(()=>{const oe=pt.current;if(!(!oe||oe.isDisposed?.()))return ft.current!=null&&cancelAnimationFrame(ft.current),ft.current=requestAnimationFrame(()=>{ft.current=null;try{oe.trigger("resize")}catch{}}),()=>{ft.current!=null&&(cancelAnimationFrame(ft.current),ft.current=null)}},[Ve,Ct.w,Ct.h]);const[ui,Pe]=A.useState(!1),[H,q]=A.useState(!1),ne=A.useRef(null),Se=A.useRef(null),Je=A.useRef(null),_t=A.useCallback(oe=>{const{w:pe,h:Ge}=Lt(),mt=ht,Vt=pe-oe.w-ht,Wt=Ge-oe.h-ht,Ft=oe.x+oe.w/2{const pe=Je.current;if(!pe)return;const Ge=oe.clientX-pe.sx,mt=oe.clientY-pe.sy,Vt=pe.start,Wt=si({x:Vt.x+Ge,y:Vt.y+mt,w:Vt.w,h:Vt.h});Se.current={x:Wt.x,y:Wt.y},ne.current==null&&(ne.current=requestAnimationFrame(()=>{ne.current=null;const qt=Se.current;qt&&Mt(Ft=>({...Ft,x:qt.x,y:qt.y}))}))},[si]),Ai=A.useCallback(()=>{Je.current&&(q(!1),ne.current!=null&&(cancelAnimationFrame(ne.current),ne.current=null),Je.current=null,window.removeEventListener("pointermove",ei),window.removeEventListener("pointerup",Ai),Mt(oe=>{const pe=_t(si(oe));return queueMicrotask(()=>Ei(pe)),pe}))},[ei,_t,si,Ei]),is=A.useCallback(oe=>{if(!Ve||ui||oe.button!==0)return;oe.preventDefault(),oe.stopPropagation();const pe=Tt.current;Je.current={sx:oe.clientX,sy:oe.clientY,start:pe},q(!0),window.addEventListener("pointermove",ei),window.addEventListener("pointerup",Ai)},[Ve,ui,ei,Ai]),Ii=A.useRef(null),ji=A.useRef(null),Zi=A.useRef(null),gi=A.useCallback(oe=>{const pe=Zi.current;if(!pe)return;const Ge=oe.clientX-pe.sx,mt=oe.clientY-pe.sy,Vt=pe.ratio,Wt=pe.dir.includes("w"),qt=pe.dir.includes("e"),Ft=pe.dir.includes("n"),Js=pe.dir.includes("s");let _s=pe.start.w,cs=pe.start.h,wn=pe.start.x,An=pe.start.y;const{w:ro,h:ao}=Lt(),oo=24,Vc=pe.start.x+pe.start.w,lo=pe.start.y+pe.start.h,Yn=Math.abs(ro-ht-Vc)<=oo,$r=Math.abs(ao-ht-lo)<=oo,Aa=Ji=>{Ji=Math.max(rt,Ji);let ps=Ji/Vt;return ps{Ji=Math.max(Gt,Ji);let ps=Ji*Vt;return ps=Math.abs(mt)){const ps=qt?pe.start.w+Ge:pe.start.w-Ge,{newW:zs,newH:qs}=Aa(ps);_s=zs,cs=qs}else{const ps=Js?pe.start.h+mt:pe.start.h-mt,{newW:zs,newH:qs}=Ar(ps);_s=zs,cs=qs}Wt&&(wn=pe.start.x+(pe.start.w-_s)),Ft&&(An=pe.start.y+(pe.start.h-cs))}else if(qt||Wt){const Ji=qt?pe.start.w+Ge:pe.start.w-Ge,{newW:ps,newH:zs}=Aa(Ji);_s=ps,cs=zs,Wt&&(wn=pe.start.x+(pe.start.w-_s)),An=$r?pe.start.y+(pe.start.h-cs):pe.start.y}else if(Ft||Js){const Ji=Js?pe.start.h+mt:pe.start.h-mt,{newW:ps,newH:zs}=Ar(Ji);_s=ps,cs=zs,Ft&&(An=pe.start.y+(pe.start.h-cs)),Yn?wn=pe.start.x+(pe.start.w-_s):wn=pe.start.x}const lu=si({x:wn,y:An,w:_s,h:cs},Vt);ji.current=lu,Ii.current==null&&(Ii.current=requestAnimationFrame(()=>{Ii.current=null;const Ji=ji.current;Ji&&Mt(Ji)}))},[si]),ss=A.useCallback(()=>{Zi.current&&(Pe(!1),Ii.current!=null&&(cancelAnimationFrame(Ii.current),Ii.current=null),Zi.current=null,window.removeEventListener("pointermove",gi),window.removeEventListener("pointerup",ss),Ei(Tt.current))},[gi,Ei]),ci=A.useCallback(oe=>pe=>{if(!Ve||pe.button!==0)return;pe.preventDefault(),pe.stopPropagation();const Ge=Tt.current;Zi.current={dir:oe,sx:pe.clientX,sy:pe.clientY,start:Ge,ratio:Ge.w/Ge.h},Pe(!0),window.addEventListener("pointermove",gi),window.addEventListener("pointerup",ss)},[Ve,gi,ss]),[Ni,ri]=A.useState(!1),[Yt,Xt]=A.useState(!1);A.useEffect(()=>{const oe=window.matchMedia?.("(hover: hover) and (pointer: fine)"),pe=()=>ri(!!oe?.matches);return pe(),oe?.addEventListener?.("change",pe),()=>oe?.removeEventListener?.("change",pe)},[]);const Hs=Ve&&(Yt||H||ui),[qi,Vs]=A.useState(!1);if(A.useEffect(()=>{s.status!=="running"&&Vs(!1)},[s.id,s.status]),!Pt||!gt)return null;const Kn="inline-flex items-center justify-center rounded-md p-2 transition bg-white/75 text-gray-900 ring-1 ring-black/10 hover:bg-white/90 active:scale-[0.98] dark:bg-black/45 dark:text-white dark:ring-white/10 dark:hover:bg-black/60 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-500",Zt=String(s.phase??"").toLowerCase(),vi=Zt==="stopping"||Zt==="remuxing"||Zt==="moving",di=!S||!M||vi||qi,Ns=y.jsx("div",{className:"flex items-center gap-1 min-w-0",children:M?y.jsxs(y.Fragment,{children:[y.jsx(li,{variant:"primary",color:"red",size:"sm",rounded:"md",disabled:di,title:vi||qi?"Stoppe…":"Stop","aria-label":vi||qi?"Stoppe…":"Stop",onClick:async oe=>{if(oe.preventDefault(),oe.stopPropagation(),!di)try{Vs(!0),await S?.(s.id)}finally{Vs(!1)}},className:Ka("shadow-none shrink-0",pi&&"px-2"),children:y.jsx("span",{className:"whitespace-nowrap",children:vi||qi?"Stoppe…":pi?"Stop":"Stoppen"})}),y.jsx(va,{job:s,variant:"overlay",collapseToMenu:!0,busy:vi||qi,isFavorite:u,isLiked:c,isWatching:d,onToggleWatch:_?oe=>_(oe):void 0,showHot:!1,showKeep:!1,showDelete:!1,onToggleFavorite:v?oe=>v(oe):void 0,onToggleLike:b?oe=>b(oe):void 0,order:["watch","favorite","like","details"],className:"gap-1 min-w-0 flex-1"})]}):y.jsx(va,{job:s,variant:"overlay",collapseToMenu:!0,isHot:o||W,isFavorite:u,isLiked:c,isWatching:d,onToggleWatch:_?oe=>_(oe):void 0,onToggleFavorite:v?oe=>v(oe):void 0,onToggleLike:b?oe=>b(oe):void 0,onToggleHot:g?async oe=>{Bt(),await new Promise(Ge=>setTimeout(Ge,150)),await g(oe),await new Promise(Ge=>setTimeout(Ge,0));const pe=pt.current;if(pe&&!pe.isDisposed?.()){const Ge=pe.play?.();Ge&&typeof Ge.catch=="function"&&Ge.catch(()=>{})}}:void 0,onKeep:f?async oe=>{Bt(),t(),await new Promise(pe=>setTimeout(pe,150)),await f(oe)}:void 0,onDelete:p?async oe=>{Bt(),t(),await new Promise(pe=>setTimeout(pe,150)),await p(oe)}:void 0,order:["watch","favorite","like","hot","keep","delete","details"],className:"gap-1 min-w-0 flex-1"})}),Os=e||Ve,Li="env(safe-area-inset-bottom)",Gs=`calc(${wt}px + env(safe-area-inset-bottom))`,we=M?Li:Gs,Ne=M?"calc(8px + env(safe-area-inset-bottom))":`calc(${wt+8}px + env(safe-area-inset-bottom))`,ke=Ve?"top-4":"top-2",tt=e&&st,je=y.jsx("div",{className:Ka("relative overflow-visible",e||Ve?"flex-1 min-h-0":"aspect-video"),onMouseEnter:()=>{!Ve||!Ni||Xt(!0)},onMouseLeave:()=>{!Ve||!Ni||Xt(!1)},children:y.jsxs("div",{className:Ka("relative w-full h-full",Ve&&"vjs-mini"),children:[M?y.jsxs("div",{className:"absolute inset-0 bg-black",children:[y.jsx(ZL,{src:ee,muted:D,className:"w-full h-full object-contain"}),y.jsxs("div",{className:"absolute right-2 bottom-2 z-[60] pointer-events-none inline-flex items-center gap-1.5 rounded-full bg-red-600/90 px-2 py-1 text-[11px] font-semibold text-white shadow-sm",children:[y.jsx("span",{className:"inline-block size-1.5 rounded-full bg-white animate-pulse"}),"Live"]})]}):y.jsx("div",{ref:Ot,className:"absolute inset-0"}),y.jsx("div",{className:Ka("absolute inset-x-2 z-30",ke),children:y.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto_auto] items-start gap-2",children:[y.jsx("div",{className:"min-w-0 pointer-events-auto overflow-visible",children:tt?null:Ns}),Ve?y.jsxs("button",{type:"button","aria-label":"Player-Fenster verschieben",title:"Ziehen zum Verschieben",onPointerDown:is,onClick:oe=>{oe.preventDefault(),oe.stopPropagation()},className:Ka(Kn,"px-3 gap-1 cursor-grab active:cursor-grabbing select-none",Hs?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none -translate-y-1",H&&"scale-[0.98] opacity-90"),children:[y.jsx("span",{className:"h-1 w-1 rounded-full bg-black/35 dark:bg-white/35"}),y.jsx("span",{className:"h-1 w-1 rounded-full bg-black/35 dark:bg-white/35"}),y.jsx("span",{className:"h-1 w-1 rounded-full bg-black/35 dark:bg-white/35"})]}):null,y.jsxs("div",{className:"shrink-0 flex items-center gap-1 pointer-events-auto",children:[y.jsx("button",{type:"button",className:Kn,onClick:i,"aria-label":e?"Minimieren":"Maximieren",title:e?"Minimieren":"Maximieren",children:e?y.jsx(fO,{className:"h-5 w-5"}):y.jsx(pO,{className:"h-5 w-5"})}),y.jsx("button",{type:"button",className:Kn,onClick:t,"aria-label":"Schließen",title:"Schließen",children:y.jsx(qx,{className:"h-5 w-5"})})]})]})}),y.jsx("div",{className:Ka("player-ui pointer-events-none absolute inset-x-0 z-40","bg-gradient-to-t from-black/70 to-transparent","transition-all duration-200 ease-out",e?"h-28":"h-24"),style:{bottom:we}}),y.jsxs("div",{className:Ka("player-ui pointer-events-none absolute inset-x-2 z-50","flex items-end justify-between gap-2","transition-all duration-200 ease-out"),style:{bottom:Ne},children:[y.jsxs("div",{className:"min-w-0",children:[y.jsx("div",{className:"truncate text-sm font-semibold text-white",children:re}),y.jsx("div",{className:"truncate text-[11px] text-white/80",children:J||R})]}),y.jsxs("div",{className:"shrink-0 flex items-center gap-1.5 text-[11px] text-white",children:[!M&&y.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-semibold",children:s.status}),o||W?y.jsx("span",{className:"rounded bg-amber-500/25 px-1.5 py-0.5 font-semibold text-white",children:"HOT"}):null,!M&&y.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:Y}),U!=="—"?y.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:U}):null]})]})]})}),ut=y.jsx("div",{className:"w-[360px] shrink-0 border-r border-white/10 bg-black/40 text-white",children:y.jsxs("div",{className:"h-full p-4 flex flex-col gap-3 overflow-y-auto",children:[y.jsx("div",{className:"rounded-lg overflow-hidden ring-1 ring-white/10 bg-black/30",children:y.jsx("div",{className:"relative aspect-video",children:y.jsx("img",{src:he,alt:"Vorschau",className:"absolute inset-0 h-full w-full object-cover",loading:"lazy",onError:()=>{he!==j&&Te(j)}})})}),y.jsxs("div",{className:"space-y-1",children:[y.jsx("div",{className:"text-lg font-semibold truncate",children:re}),y.jsx("div",{className:"text-xs text-white/70 break-all",children:J||R})]}),y.jsx("div",{className:"pointer-events-auto",children:y.jsxs("div",{className:"flex items-center justify-center gap-2 flex-wrap",children:[M?y.jsx(li,{variant:"primary",color:"red",size:"sm",rounded:"md",disabled:di,title:vi||qi?"Stoppe…":"Stop","aria-label":vi||qi?"Stoppe…":"Stop",onClick:async oe=>{if(oe.preventDefault(),oe.stopPropagation(),!di)try{Vs(!0),await S?.(s.id)}finally{Vs(!1)}},className:"shadow-none",children:vi||qi?"Stoppe…":"Stoppen"}):null,y.jsx(va,{job:s,variant:"table",collapseToMenu:!1,busy:vi||qi,isHot:o||W,isFavorite:u,isLiked:c,isWatching:d,onToggleWatch:_?oe=>_(oe):void 0,onToggleFavorite:v?oe=>v(oe):void 0,onToggleLike:b?oe=>b(oe):void 0,onToggleHot:g?async oe=>{Bt(),await new Promise(Ge=>setTimeout(Ge,150)),await g(oe),await new Promise(Ge=>setTimeout(Ge,0));const pe=pt.current;if(pe&&!pe.isDisposed?.()){const Ge=pe.play?.();Ge&&typeof Ge.catch=="function"&&Ge.catch(()=>{})}}:void 0,onKeep:f?async oe=>{Bt(),t(),await new Promise(pe=>setTimeout(pe,150)),await f(oe)}:void 0,onDelete:p?async oe=>{Bt(),t(),await new Promise(pe=>setTimeout(pe,150)),await p(oe)}:void 0,order:M?["watch","favorite","like","details"]:["watch","favorite","like","hot","details","keep","delete"],className:"flex items-center justify-start gap-1"})]})}),y.jsxs("div",{className:"grid grid-cols-2 gap-x-3 gap-y-2 text-sm",children:[y.jsx("div",{className:"text-white/60",children:"Status"}),y.jsx("div",{className:"font-medium",children:s.status}),y.jsx("div",{className:"text-white/60",children:"Auflösung"}),y.jsx("div",{className:"font-medium",children:lt}),y.jsx("div",{className:"text-white/60",children:"FPS"}),y.jsx("div",{className:"font-medium",children:nt}),y.jsx("div",{className:"text-white/60",children:"Laufzeit"}),y.jsx("div",{className:"font-medium",children:Y}),y.jsx("div",{className:"text-white/60",children:"Größe"}),y.jsx("div",{className:"font-medium",children:U}),y.jsx("div",{className:"text-white/60",children:"Datum"}),y.jsx("div",{className:"font-medium",children:z}),y.jsx("div",{className:"col-span-2",children:ie.length?y.jsx("div",{className:"flex flex-wrap gap-1.5",children:ie.map(oe=>y.jsx("span",{className:"rounded bg-white/10 px-2 py-0.5 text-xs text-white/90",children:oe},oe))}):y.jsx("span",{className:"text-white/50",children:"—"})})]})]})}),le=y.jsx(xa,{edgeToEdgeMobile:!0,noBodyPadding:!0,className:Ka("relative flex flex-col shadow-2xl ring-1 ring-black/10 dark:ring-white/10","w-full",Os?"h-full":"h-[220px] max-h-[40vh]",e?"rounded-2xl":Ve?"rounded-lg":"rounded-none"),bodyClassName:"flex flex-col flex-1 min-h-0 p-0",children:y.jsxs("div",{className:"flex flex-1 min-h-0",children:[tt?ut:null,je]})}),{w:ae,h:ye,ox:be,oy:Me,bottomInset:Fe}=Lt(),Qe={left:be+16,top:Me+16,width:Math.max(0,ae-32),height:Math.max(0,ye-32)},ct=e?Qe:Ve?{left:Ct.x,top:Ct.y,width:Ct.w,height:Ct.h}:void 0;return xc.createPortal(y.jsxs(y.Fragment,{children:[y.jsx("style",{children:` /* Live-Download: Progress/Seek-Bar ausblenden */ .is-live-download .vjs-progress-control { display: none !important; } `}),e||Ve?y.jsxs("div",{className:Ka("fixed z-[2147483647]",!ui&&!H&&"transition-[left,top,width,height] duration-300 ease-[cubic-bezier(.2,.9,.2,1)]"),style:{...ct,willChange:ui?"left, top, width, height":void 0},children:[le,Ve?y.jsxs("div",{className:"pointer-events-none absolute inset-0",children:[y.jsx("div",{className:"pointer-events-auto absolute -left-1 bottom-2 top-2 w-3 cursor-ew-resize",onPointerDown:ci("w")}),y.jsx("div",{className:"pointer-events-auto absolute -right-1 bottom-2 top-2 w-3 cursor-ew-resize",onPointerDown:ci("e")}),y.jsx("div",{className:"pointer-events-auto absolute left-2 right-2 -top-1 h-3 cursor-ns-resize",onPointerDown:ci("n")}),y.jsx("div",{className:"pointer-events-auto absolute left-2 right-2 -bottom-1 h-3 cursor-ns-resize",onPointerDown:ci("s")}),y.jsx("div",{className:"pointer-events-auto absolute -left-1 -top-1 h-4 w-4 cursor-nwse-resize",onPointerDown:ci("nw")}),y.jsx("div",{className:"pointer-events-auto absolute -right-1 -top-1 h-4 w-4 cursor-nesw-resize",onPointerDown:ci("ne")}),y.jsx("div",{className:"pointer-events-auto absolute -left-1 -bottom-1 h-4 w-4 cursor-nesw-resize",onPointerDown:ci("sw")}),y.jsx("div",{className:"pointer-events-auto absolute -right-1 -bottom-1 h-4 w-4 cursor-nwse-resize",onPointerDown:ci("se")})]}):null]}):y.jsx("div",{className:` fixed z-[2147483647] inset-x-0 w-full shadow-2xl md:bottom-4 md:left-1/2 md:right-auto md:inset-x-auto md:w-[min(760px,calc(100vw-32px))] md:-translate-x-1/2 `,style:{bottom:`calc(${Fe}px + env(safe-area-inset-bottom))`},children:le})]}),gt)}function JL({jobId:s,thumbTick:e,autoTickMs:t=1e4,blur:i=!1,alignStartAt:n,alignEndAt:r=null,alignEveryMs:o,fastRetryMs:u,fastRetryMax:c,fastRetryWindowMs:d,className:f}){const[p,g]=A.useState(()=>typeof document>"u"?!0:!document.hidden),v=i?"blur-md":"",[b,_]=A.useState(0),[S,D]=A.useState(!1),R=A.useRef(null),[L,P]=A.useState(!1),U=A.useRef(null),V=A.useRef(0),M=A.useRef(!1),G=A.useRef(!1),N=W=>{if(typeof W=="number"&&Number.isFinite(W))return W;if(W instanceof Date)return W.getTime();const re=Date.parse(String(W??""));return Number.isFinite(re)?re:NaN};A.useEffect(()=>{const W=()=>g(!document.hidden);return document.addEventListener("visibilitychange",W),()=>document.removeEventListener("visibilitychange",W)},[]),A.useEffect(()=>()=>{U.current&&window.clearTimeout(U.current)},[]),A.useEffect(()=>{typeof e!="number"&&(!L||!p||G.current||(G.current=!0,_(W=>W+1)))},[L,e,p]),A.useEffect(()=>{if(typeof e=="number"||!L||!p)return;const W=Number(o??t??1e4);if(!Number.isFinite(W)||W<=0)return;const re=n?N(n):NaN,J=r?N(r):NaN;if(Number.isFinite(re)){let z;const Z=()=>{const ie=Date.now();if(Number.isFinite(J)&&ie>=J)return;const j=Math.max(0,ie-re)%W,ee=j===0?W:W-j;z=window.setTimeout(()=>{_(he=>he+1),Z()},ee)};return Z(),()=>{z&&window.clearTimeout(z)}}const Y=window.setInterval(()=>{_(z=>z+1)},W);return()=>window.clearInterval(Y)},[e,t,L,p,n,r,o]),A.useEffect(()=>{const W=R.current;if(!W)return;const re=new IntersectionObserver(J=>{const Y=J[0];P(!!(Y&&(Y.isIntersecting||Y.intersectionRatio>0)))},{root:null,threshold:0,rootMargin:"300px 0px"});return re.observe(W),()=>re.disconnect()},[]);const O=typeof e=="number"?e:b;A.useEffect(()=>{D(!1)},[O]),A.useEffect(()=>{M.current=!1,V.current=0,G.current=!1,D(!1),_(W=>W+1)},[s]);const K=A.useMemo(()=>`/api/record/preview?id=${encodeURIComponent(s)}&v=${O}`,[s,O]),Q=A.useMemo(()=>`/api/record/preview?id=${encodeURIComponent(s)}&hover=1&file=index_hq.m3u8`,[s]);return y.jsx(LA,{content:(W,{close:re})=>W&&y.jsx("div",{className:"w-[420px] max-w-[calc(100vw-1.5rem)]",children:y.jsxs("div",{className:"relative aspect-video overflow-hidden rounded-lg bg-black",children:[y.jsx(ZL,{src:Q,muted:!1,className:["w-full h-full relative z-0"].filter(Boolean).join(" ")}),y.jsxs("div",{className:"absolute left-2 top-2 inline-flex items-center gap-1.5 rounded-full bg-red-600/90 px-2 py-1 text-[11px] font-semibold text-white shadow-sm",children:[y.jsx("span",{className:"inline-block size-1.5 rounded-full bg-white animate-pulse"}),"Live"]}),y.jsx("button",{type:"button",className:"absolute right-2 top-2 z-20 inline-flex items-center justify-center rounded-md p-1.5 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white/70 bg-white/75 text-gray-900 ring-1 ring-black/10 hover:bg-white/90 dark:bg-black/40 dark:text-white dark:ring-white/10 dark:hover:bg-black/55","aria-label":"Live-Vorschau schließen",title:"Vorschau schließen",onClick:J=>{J.preventDefault(),J.stopPropagation(),re()},children:y.jsx(qx,{className:"h-4 w-4"})})]})}),children:y.jsx("div",{ref:R,className:["block relative rounded bg-gray-100 dark:bg-white/5 overflow-hidden",f||"w-full h-full"].join(" "),children:S?y.jsx("div",{className:"absolute inset-0 grid place-items-center px-1 text-center text-[10px] text-gray-500 dark:text-gray-400",children:"keine Vorschau"}):y.jsx("img",{src:K,loading:L?"eager":"lazy",fetchPriority:L?"high":"auto",alt:"",className:["block w-full h-full object-cover object-center",v].filter(Boolean).join(" "),onLoad:()=>{M.current=!0,V.current=0,U.current&&window.clearTimeout(U.current),D(!1)},onError:()=>{if(D(!0),!u||!L||!p||M.current)return;const W=n?N(n):NaN,re=Number(d??6e4);if(!(!Number.isFinite(W)||Date.now()-W=Y||(U.current&&window.clearTimeout(U.current),U.current=window.setTimeout(()=>{V.current+=1,_(z=>z+1)},u))}})})})}const Oc=new Map;let Ow=!1;function J$(){Ow||(Ow=!0,document.addEventListener("visibilitychange",()=>{if(document.hidden)for(const s of Oc.values())s.es&&(s.es.close(),s.es=null,s.dispatchers.clear());else for(const s of Oc.values())s.refs>0&&!s.es&&eR(s)}))}function eR(s){if(!s.es&&!document.hidden){s.es=new EventSource(s.url);for(const[e,t]of s.listeners.entries()){const i=n=>{let r=null;try{r=JSON.parse(String(n.data??"null"))}catch{return}for(const o of t)o(r)};s.dispatchers.set(e,i),s.es.addEventListener(e,i)}s.es.onerror=()=>{}}}function e9(s){s.es&&(s.es.close(),s.es=null,s.dispatchers.clear())}function t9(s){let e=Oc.get(s);return e||(e={url:s,es:null,refs:0,listeners:new Map,dispatchers:new Map},Oc.set(s,e)),e}function tR(s,e,t){J$();const i=t9(s);let n=i.listeners.get(e);if(n||(n=new Set,i.listeners.set(e,n)),n.add(t),i.refs+=1,i.es){if(!i.dispatchers.has(e)){const r=o=>{let u=null;try{u=JSON.parse(String(o.data??"null"))}catch{return}for(const c of i.listeners.get(e)??[])c(u)};i.dispatchers.set(e,r),i.es.addEventListener(e,r)}}else eR(i);return()=>{const r=Oc.get(s);if(!r)return;const o=r.listeners.get(e);o&&(o.delete(t),o.size===0&&r.listeners.delete(e)),r.refs=Math.max(0,r.refs-1),r.refs===0&&(e9(r),Oc.delete(s))}}const Rp=s=>{const e=s;return e.modelName??e.model??e.modelKey??e.username??e.name??"—"},iR=s=>{const e=s;return e.sourceUrl??e.url??e.roomUrl??""},sR=s=>{const e=s;return String(e.imageUrl??e.image_url??"").trim()},Mw=s=>{const e=s;return String(e.key??e.id??Rp(s))},Or=s=>{if(typeof s=="number"&&Number.isFinite(s))return s<1e12?s*1e3:s;if(typeof s=="string"){const e=Date.parse(s);return Number.isFinite(e)?e:0}return s instanceof Date?s.getTime():0},Pw=s=>{if(s.kind==="job"){const t=s.job;return Or(t.addedAt)||Or(t.createdAt)||Or(t.enqueuedAt)||Or(t.queuedAt)||Or(t.requestedAt)||Or(t.startedAt)||0}const e=s.pending;return Or(e.addedAt)||Or(e.createdAt)||Or(e.enqueuedAt)||Or(e.queuedAt)||Or(e.requestedAt)||0},nR=s=>{switch(s){case"stopping":return"Stop wird angefordert…";case"remuxing":return"Remux zu MP4…";case"moving":return"Verschiebe nach Done…";case"assets":return"Erstelle Vorschau…";default:return""}};async function i9(s,e){const t=await fetch(s,e);if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(i||`HTTP ${t.status}`)}return t.json()}function s9({job:s}){const e=String(s?.phase??"").trim(),t=Number(s?.progress??0),n=(e?nR(e)||e:"")||String(s?.status??"").trim().toLowerCase(),r=Number.isFinite(t)&&t>0&&t<100,o=!r&&!!e&&(!Number.isFinite(t)||t<=0||t>=100);return y.jsx("div",{className:"min-w-0",children:r?y.jsx(bc,{label:n,value:Math.max(0,Math.min(100,t)),showPercent:!0,size:"sm",className:"w-full min-w-0 sm:min-w-[220px]"}):o?y.jsx(bc,{label:n,indeterminate:!0,size:"sm",className:"w-full min-w-0 sm:min-w-[220px]"}):y.jsx("div",{className:"truncate",children:y.jsx("span",{className:"font-medium",children:n})})})}function n9({r:s,nowMs:e,blurPreviews:t,modelsByKey:i,stopRequestedIds:n,markStopRequested:r,onOpenPlayer:o,onStopJob:u,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f}){if(s.kind==="pending"){const W=s.pending,re=Rp(W),J=iR(W),Y=(W.currentShow||"unknown").toLowerCase();return y.jsxs("div",{className:` relative overflow-hidden rounded-2xl border border-white/40 bg-white/35 shadow-sm backdrop-blur-xl supports-[backdrop-filter]:bg-white/25 ring-1 ring-black/5 transition-all hover:-translate-y-0.5 hover:shadow-md active:translate-y-0 dark:border-white/10 dark:bg-gray-950/35 dark:supports-[backdrop-filter]:bg-gray-950/25 `,children:[y.jsx("div",{className:"pointer-events-none absolute inset-0 bg-gradient-to-br from-white/70 via-white/20 to-white/60 dark:from-white/10 dark:via-transparent dark:to-white/5"}),y.jsxs("div",{className:"relative p-3",children:[y.jsxs("div",{className:"flex items-start justify-between gap-2",children:[y.jsxs("div",{className:"min-w-0",children:[y.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",title:re,children:re}),y.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-xs text-gray-600 dark:text-gray-300",children:[y.jsx("span",{className:"inline-flex items-center gap-1 rounded-full bg-gray-900/5 px-2 py-0.5 font-medium dark:bg-white/10",children:"Wartend"}),y.jsx("span",{className:"inline-flex items-center rounded-full bg-gray-900/5 px-2 py-0.5 text-[11px] font-medium uppercase tracking-wide text-gray-700 dark:bg-white/10 dark:text-gray-200",children:Y})]})]}),y.jsx("span",{className:"shrink-0 rounded-full bg-gray-900/5 px-2.5 py-1 text-xs font-medium text-gray-800 dark:bg-white/10 dark:text-gray-200",children:"⏳"})]}),y.jsx("div",{className:"mt-3",children:(()=>{const z=sR(W);return y.jsx("div",{className:"relative aspect-[16/9] w-full overflow-hidden rounded-xl bg-gray-100 ring-1 ring-black/5 dark:bg-white/10 dark:ring-white/10",children:z?y.jsx("img",{src:z,alt:re,className:["h-full w-full object-cover",t?"blur-md":""].join(" "),loading:"lazy",referrerPolicy:"no-referrer",onError:Z=>{Z.currentTarget.style.display="none"}}):y.jsx("div",{className:"grid h-full w-full place-items-center",children:y.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-300",children:"Waiting…"})})})})()}),J?y.jsx("a",{href:J,target:"_blank",rel:"noreferrer",className:"mt-3 block truncate text-xs text-indigo-600 hover:underline dark:text-indigo-400",onClick:z=>z.stopPropagation(),title:J,children:J}):null]})]})}const p=s.job,g=Px(p.output),v=nT(p.output||""),b=String(p.phase??"").trim(),_=b?nR(b)||b:"",S=!!n[p.id],D=String(p.status??"").toLowerCase(),R=!!b||D!=="running"||S,L=D||"unknown",P=_||L,U=Number(p.progress??0),V=Number.isFinite(U)&&U>0&&U<100,M=!V&&!!b&&(!Number.isFinite(U)||U<=0||U>=100),G=g&&g!=="—"?g.toLowerCase():"",N=G?i[G]:void 0,O=!!N?.favorite,K=N?.liked===!0,Q=!!N?.watching;return y.jsxs("div",{className:` group relative overflow-hidden rounded-2xl border border-white/40 bg-white/35 shadow-sm backdrop-blur-xl supports-[backdrop-filter]:bg-white/25 ring-1 ring-black/5 transition-all hover:-translate-y-0.5 hover:shadow-md active:translate-y-0 dark:border-white/10 dark:bg-gray-950/35 dark:supports-[backdrop-filter]:bg-gray-950/25 `,onClick:()=>o(p),role:"button",tabIndex:0,onKeyDown:W=>{(W.key==="Enter"||W.key===" ")&&o(p)},children:[y.jsx("div",{className:"pointer-events-none absolute inset-0 bg-gradient-to-br from-white/70 via-white/20 to-white/60 dark:from-white/10 dark:via-transparent dark:to-white/5"}),y.jsx("div",{className:"pointer-events-none absolute -inset-10 opacity-0 blur-2xl transition-opacity duration-300 group-hover:opacity-100 bg-white/40 dark:bg-white/10"}),y.jsxs("div",{className:"relative p-3",children:[y.jsxs("div",{className:"flex items-start gap-3",children:[y.jsx("div",{className:` relative shrink-0 overflow-hidden rounded-lg w-[112px] h-[64px] bg-gray-100 ring-1 ring-black/5 dark:bg-white/10 dark:ring-white/10 `,children:y.jsx(JL,{jobId:p.id,blur:t,alignStartAt:p.startedAt,alignEndAt:p.endedAt??null,alignEveryMs:1e4,fastRetryMs:1e3,fastRetryMax:25,fastRetryWindowMs:6e4,className:"w-full h-full"})}),y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsxs("div",{className:"flex items-start justify-between gap-2",children:[y.jsxs("div",{className:"min-w-0",children:[y.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[y.jsx("div",{className:"truncate text-base font-semibold text-gray-900 dark:text-white",title:g,children:g}),y.jsx("span",{className:["shrink-0 inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold","bg-gray-900/5 text-gray-800 dark:bg-white/10 dark:text-gray-200",R?"ring-1 ring-amber-500/30":"ring-1 ring-emerald-500/25"].join(" "),title:L,children:L})]}),y.jsx("div",{className:"mt-0.5 truncate text-xs text-gray-600 dark:text-gray-300",title:p.output,children:v||"—"})]}),y.jsxs("div",{className:"shrink-0 flex flex-col items-end gap-1",children:[y.jsx("span",{className:"rounded-full bg-gray-900/5 px-2 py-0.5 text-[11px] font-medium text-gray-900 dark:bg-white/10 dark:text-gray-200",children:rR(p,e)}),y.jsx("span",{className:"rounded-full bg-gray-900/5 px-2 py-0.5 text-[11px] font-medium text-gray-900 dark:bg-white/10 dark:text-gray-200",children:oR(aR(p))})]})]}),p.sourceUrl?y.jsx("a",{href:p.sourceUrl,target:"_blank",rel:"noreferrer",className:"mt-1 block truncate text-xs text-indigo-600 hover:underline dark:text-indigo-400",onClick:W=>W.stopPropagation(),title:p.sourceUrl,children:p.sourceUrl}):null]})]}),V||M?y.jsx("div",{className:"mt-3",children:V?y.jsx(bc,{label:P,value:Math.max(0,Math.min(100,U)),showPercent:!0,size:"sm",className:"w-full"}):y.jsx(bc,{label:P,indeterminate:!0,size:"sm",className:"w-full"})}):null,y.jsxs("div",{className:"mt-3 flex items-center justify-between gap-2 border-t border-white/30 pt-3 dark:border-white/10",children:[y.jsx("div",{className:"flex items-center gap-1",onClick:W=>W.stopPropagation(),onMouseDown:W=>W.stopPropagation(),children:y.jsx(va,{job:p,variant:"table",busy:R,isFavorite:O,isLiked:K,isWatching:Q,showHot:!1,showKeep:!1,showDelete:!1,showFavorite:!0,showLike:!0,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f,order:["watch","favorite","like","details"],className:"flex items-center gap-1"})}),y.jsx(li,{size:"sm",variant:"primary",disabled:R,className:"shrink-0",onClick:W=>{W.stopPropagation(),!R&&(r(p.id),u(p.id))},children:R?"Stoppe…":"Stop"})]})]})]})}const nT=s=>(s||"").replaceAll("\\","/").trim().split("/").pop()||"",Px=s=>{const e=nT(s||"");if(!e)return"—";const t=e.replace(/\.[^.]+$/,""),i=t.match(/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}$/);if(i?.[1])return i[1];const n=t.lastIndexOf("_");return n>0?t.slice(0,n):t},r9=s=>{if(!Number.isFinite(s)||s<=0)return"—";const e=Math.floor(s/1e3),t=Math.floor(e/3600),i=Math.floor(e%3600/60),n=e%60;return t>0?`${t}h ${i}m`:i>0?`${i}m ${n}s`:`${n}s`},rR=(s,e)=>{const t=Date.parse(String(s.startedAt||""));if(!Number.isFinite(t))return"—";const i=s.endedAt?Date.parse(String(s.endedAt)):e;return Number.isFinite(i)?r9(i-t):"—"},aR=s=>{const e=s,t=e.sizeBytes??e.fileSizeBytes??e.bytes??e.size??null;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:null},oR=s=>{if(!s||!Number.isFinite(s)||s<=0)return"—";const e=["B","KB","MB","GB","TB"];let t=s,i=0;for(;t>=1024&&i=10?1:2;return`${t.toFixed(n).replace(/\.0+$/,"")} ${e[i]}`};function a9({jobs:s,pending:e=[],onOpenPlayer:t,onStopJob:i,onToggleFavorite:n,onToggleLike:r,onToggleWatch:o,modelsByKey:u={},blurPreviews:c}){const[d,f]=A.useState(!1),[p,g]=A.useState(!1),v=A.useRef(null),[b,_]=A.useState(!1),S=A.useCallback(async()=>{try{const Z=!!(await i9("/api/autostart/state",{cache:"no-store"}))?.paused;v.current=Z,g(Z)}catch{}},[]);A.useEffect(()=>{S();const z=tR("/api/autostart/state/stream","autostart",Z=>{const ie=!!Z?.paused;v.current!==ie&&(v.current=ie,g(ie))});return()=>{z()}},[S]);const D=A.useCallback(async()=>{if(!(b||p)){_(!0);try{await fetch("/api/autostart/pause",{method:"POST"}),g(!0)}catch{}finally{_(!1)}}},[b,p]),R=A.useCallback(async()=>{if(!(b||!p)){_(!0);try{await fetch("/api/autostart/resume",{method:"POST"}),g(!1)}catch{}finally{_(!1)}}},[b,p]),[L,P]=A.useState({}),[U,V]=A.useState({}),M=A.useCallback(z=>{const Z=Array.isArray(z)?z:[z];P(ie=>{const ce={...ie};for(const j of Z)j&&(ce[j]=!0);return ce}),V(ie=>{const ce={...ie};for(const j of Z)j&&(ce[j]=!0);return ce})},[]);A.useEffect(()=>{P(z=>{const Z=Object.keys(z);if(Z.length===0)return z;const ie={};for(const ce of Z){const j=s.find(Te=>Te.id===ce);if(!j)continue;String(j.phase??"").trim()||j.status!=="running"||(ie[ce]=!0)}return ie})},[s]);const[G,N]=A.useState(()=>Date.now()),O=A.useMemo(()=>s.some(z=>!z.endedAt&&z.status==="running"),[s]);A.useEffect(()=>{if(!O)return;const z=window.setInterval(()=>N(Date.now()),15e3);return()=>window.clearInterval(z)},[O]);const K=A.useMemo(()=>s.filter(z=>{const Z=String(z.phase??"").trim(),ie=!!L[z.id];return!(!!Z||z.status!=="running"||ie)}).map(z=>z.id),[s,L]),Q=A.useMemo(()=>[{key:"preview",header:"Vorschau",widthClassName:"w-[96px]",cell:z=>{if(z.kind==="job"){const j=z.job;return y.jsx("div",{className:"grid w-[96px] h-[60px] overflow-hidden rounded-md",children:y.jsx(JL,{jobId:j.id,blur:c,alignStartAt:j.startedAt,alignEndAt:j.endedAt??null,alignEveryMs:1e4,fastRetryMs:1e3,fastRetryMax:25,fastRetryWindowMs:6e4,className:"w-full h-full"})})}const Z=z.pending,ie=Rp(Z),ce=sR(Z);return ce?y.jsx("div",{className:"grid w-[96px] h-[60px] overflow-hidden rounded-md bg-gray-100 ring-1 ring-black/5 dark:bg-white/10 dark:ring-white/10",children:y.jsx("img",{src:ce,alt:ie,className:["h-full w-full object-cover",c?"blur-md":""].join(" "),loading:"lazy",referrerPolicy:"no-referrer",onError:j=>{j.currentTarget.style.display="none"}})}):y.jsx("div",{className:"h-[60px] w-[96px] rounded-md bg-gray-100 dark:bg-white/10 grid place-items-center text-sm text-gray-500",children:"⏳"})}},{key:"model",header:"Modelname",widthClassName:"w-[170px]",cell:z=>{if(z.kind==="job"){const j=z.job,ee=nT(j.output||""),he=Px(j.output),Te=String(j.status??"").toLowerCase(),xe=!!L[j.id],Ae=!!U[j.id],Ke=Te==="stopped"||Ae&&!!j.endedAt,lt=Ke?"stopped":Te||"unknown",nt=!Ke&&xe,yt=nt?"stopping":lt;return y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[y.jsx("span",{className:"min-w-0 block max-w-[170px] truncate font-medium",title:he,children:he}),y.jsx("span",{className:["shrink-0 inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold ring-1",Te==="running"?"bg-emerald-500/15 text-emerald-900 ring-emerald-500/30 dark:bg-emerald-400/10 dark:text-emerald-200 dark:ring-emerald-400/25":Ke?"bg-slate-500/15 text-slate-900 ring-slate-500/30 dark:bg-slate-400/10 dark:text-slate-200 dark:ring-slate-400/25":Te==="failed"?"bg-red-500/15 text-red-900 ring-red-500/30 dark:bg-red-400/10 dark:text-red-200 dark:ring-red-400/25":Te==="finished"?"bg-emerald-500/15 text-emerald-900 ring-emerald-500/30 dark:bg-emerald-400/10 dark:text-emerald-200 dark:ring-emerald-400/25":nt?"bg-amber-500/15 text-amber-900 ring-amber-500/30 dark:bg-amber-400/10 dark:text-amber-200 dark:ring-amber-400/25":"bg-gray-900/5 text-gray-800 ring-gray-900/10 dark:bg-white/10 dark:text-gray-200 dark:ring-white/10"].join(" "),title:yt,children:yt})]}),y.jsx("span",{className:"block max-w-[220px] truncate",title:j.output,children:ee}),j.sourceUrl?y.jsx("a",{href:j.sourceUrl,target:"_blank",rel:"noreferrer",title:j.sourceUrl,className:"block max-w-[260px] truncate text-indigo-600 dark:text-indigo-400 hover:underline",onClick:it=>it.stopPropagation(),children:j.sourceUrl}):y.jsx("span",{className:"block max-w-[260px] truncate text-gray-500 dark:text-gray-400",children:"—"})]})}const Z=z.pending,ie=Rp(Z),ce=iR(Z);return y.jsxs(y.Fragment,{children:[y.jsx("span",{className:"block max-w-[170px] truncate font-medium",title:ie,children:ie}),ce?y.jsx("a",{href:ce,target:"_blank",rel:"noreferrer",title:ce,className:"block max-w-[260px] truncate text-indigo-600 dark:text-indigo-400 hover:underline",onClick:j=>j.stopPropagation(),children:ce}):y.jsx("span",{className:"block max-w-[260px] truncate text-gray-500 dark:text-gray-400",children:"—"})]})}},{key:"status",header:"Status",widthClassName:"w-[260px] min-w-[240px]",cell:z=>{if(z.kind==="job"){const ce=z.job;return y.jsx(s9,{job:ce})}const ie=(z.pending.currentShow||"unknown").toLowerCase();return y.jsx("div",{className:"min-w-0",children:y.jsx("div",{className:"truncate",children:y.jsx("span",{className:"font-medium",children:ie})})})}},{key:"runtime",header:"Dauer",widthClassName:"w-[90px]",cell:z=>z.kind==="job"?rR(z.job,G):"—"},{key:"size",header:"Größe",align:"right",widthClassName:"w-[110px]",cell:z=>z.kind==="job"?y.jsx("span",{className:"tabular-nums text-sm text-gray-900 dark:text-white",children:oR(aR(z.job))}):y.jsx("span",{className:"tabular-nums text-sm text-gray-500 dark:text-gray-400",children:"—"})},{key:"actions",header:"Aktion",srOnlyHeader:!0,align:"right",widthClassName:"w-[320px] min-w-[300px]",cell:z=>{if(z.kind!=="job")return y.jsx("div",{className:"pr-2 text-right text-sm text-gray-500 dark:text-gray-400",children:"—"});const Z=z.job,ie=String(Z.phase??"").trim(),ce=!!L[Z.id],j=!!ie||Z.status!=="running"||ce,ee=Px(Z.output||""),he=ee&&ee!=="—"?u[ee.toLowerCase()]:void 0,Te=!!he?.favorite,xe=he?.liked===!0,Ae=!!he?.watching;return y.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 pr-2",children:[y.jsx(va,{job:Z,variant:"table",busy:j,isFavorite:Te,isLiked:xe,isWatching:Ae,showHot:!1,showKeep:!1,showDelete:!1,showFavorite:!0,showLike:!0,onToggleFavorite:n,onToggleLike:r,onToggleWatch:o,order:["watch","favorite","like","details"],className:"flex items-center gap-1"}),(()=>{const Ke=String(Z.phase??"").trim(),lt=!!L[Z.id],nt=!!Ke||Z.status!=="running"||lt;return y.jsx(li,{size:"sm",variant:"primary",disabled:nt,className:"shrink-0",onClick:yt=>{yt.stopPropagation(),!nt&&(M(Z.id),i(Z.id))},children:nt?"Stoppe…":"Stop"})})()]})}}],[c,M,u,G,i,n,r,o,L,U]),W=e.length>0,re=s.length>0,J=A.useMemo(()=>{const z=[...s.map(Z=>({kind:"job",job:Z})),...e.map(Z=>({kind:"pending",pending:Z}))];return z.sort((Z,ie)=>Pw(ie)-Pw(Z)),z},[s,e]),Y=A.useCallback(async()=>{if(!d&&K.length!==0){f(!0);try{M(K),await Promise.allSettled(K.map(z=>Promise.resolve(i(z))))}finally{f(!1)}}},[d,K,M,i]);return y.jsxs("div",{className:"grid gap-3",children:[y.jsx("div",{className:"sticky top-[56px] z-20",children:y.jsx("div",{className:` rounded-xl border border-gray-200/70 bg-white/80 shadow-sm backdrop-blur supports-[backdrop-filter]:bg-white/60 dark:border-white/10 dark:bg-gray-950/60 dark:supports-[backdrop-filter]:bg-gray-950/40 `,children:y.jsxs("div",{className:"flex items-center justify-between gap-2 p-3",children:[y.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[y.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:"Downloads"}),y.jsx("span",{className:"shrink-0 rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-900 dark:bg-white/10 dark:text-gray-200",children:J.length})]}),y.jsxs("div",{className:"shrink-0 flex items-center gap-2",children:[y.jsx(li,{size:"sm",variant:p?"secondary":"primary",disabled:b,onClick:z=>{z.preventDefault(),z.stopPropagation(),p?R():D()},className:"hidden sm:inline-flex",title:p?"Autostart fortsetzen":"Autostart pausieren",leadingIcon:p?y.jsx(oM,{className:"size-4 shrink-0"}):y.jsx(uM,{className:"size-4 shrink-0"}),children:"Autostart"}),y.jsx(li,{size:"sm",variant:"primary",disabled:d||K.length===0,onClick:z=>{z.preventDefault(),z.stopPropagation(),Y()},className:"hidden sm:inline-flex",title:K.length===0?"Nichts zu stoppen":"Alle laufenden stoppen",children:d?"Stoppe alle…":`Alle stoppen (${K.length})`})]})]})})}),W||re?y.jsxs(y.Fragment,{children:[y.jsx("div",{className:"mt-3 grid gap-4 sm:hidden",children:J.map(z=>y.jsx(n9,{r:z,nowMs:G,blurPreviews:c,modelsByKey:u,stopRequestedIds:L,markStopRequested:M,onOpenPlayer:t,onStopJob:i,onToggleFavorite:n,onToggleLike:r,onToggleWatch:o},z.kind==="job"?`job:${z.job.id}`:`pending:${Mw(z.pending)}`))}),y.jsx("div",{className:"mt-3 hidden sm:block overflow-x-auto",children:y.jsx(Gx,{rows:J,columns:Q,getRowKey:z=>z.kind==="job"?`job:${z.job.id}`:`pending:${Mw(z.pending)}`,striped:!0,fullWidth:!0,stickyHeader:!0,compact:!1,card:!0,onRowClick:z=>{z.kind==="job"&&t(z.job)}})})]}):y.jsx(xa,{grayBody:!0,children:y.jsxs("div",{className:"flex items-center gap-3",children:[y.jsx("div",{className:"grid h-10 w-10 place-items-center rounded-xl bg-white/70 ring-1 ring-gray-200 dark:bg-white/5 dark:ring-white/10",children:y.jsx("span",{className:"text-lg",children:"⏸️"})}),y.jsxs("div",{className:"min-w-0",children:[y.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Keine laufenden Downloads"}),y.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Starte oben eine URL – hier siehst du Live-Status und kannst Jobs stoppen."})]})]})})]})}function Bx({open:s,onClose:e,title:t,children:i,footer:n,icon:r,width:o="max-w-lg"}){return y.jsx(oh,{show:s,as:A.Fragment,children:y.jsxs(rc,{as:"div",className:"relative z-50",onClose:e,children:[y.jsx(oh.Child,{as:A.Fragment,enter:"ease-out duration-300",enterFrom:"opacity-0",enterTo:"opacity-100",leave:"ease-in duration-200",leaveFrom:"opacity-100",leaveTo:"opacity-0",children:y.jsx("div",{className:"fixed inset-0 bg-gray-500/75 dark:bg-gray-900/50"})}),y.jsx("div",{className:"fixed inset-0 z-50 overflow-y-auto px-4 py-6 sm:px-6",children:y.jsx("div",{className:"min-h-full flex items-start justify-center sm:items-center",children:y.jsx(oh.Child,{as:A.Fragment,enter:"ease-out duration-300",enterFrom:"opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95",enterTo:"opacity-100 translate-y-0 sm:scale-100",leave:"ease-in duration-200",leaveFrom:"opacity-100 translate-y-0 sm:scale-100",leaveTo:"opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95",children:y.jsxs(rc.Panel,{className:["relative w-full transform rounded-lg bg-white text-left shadow-xl transition-all","max-h-[calc(100vh-3rem)] sm:max-h-[calc(100vh-4rem)]","flex flex-col","dark:bg-gray-800 dark:outline dark:-outline-offset-1 dark:outline-white/10",o].join(" "),children:[r&&y.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-green-100 dark:bg-green-500/10",children:r}),y.jsxs("div",{className:"px-6 pt-6 flex items-start justify-between gap-3",children:[y.jsx("div",{className:"min-w-0",children:t?y.jsx(rc.Title,{className:"text-base font-semibold text-gray-900 dark:text-white truncate",children:t}):null}),y.jsx("button",{type:"button",onClick:e,className:`\r inline-flex shrink-0 items-center justify-center rounded-lg p-1.5\r text-gray-500 hover:text-gray-900 hover:bg-black/5\r focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600\r dark:text-gray-400 dark:hover:text-white dark:hover:bg-white/10 dark:focus-visible:outline-indigo-500\r `,"aria-label":"Schließen",title:"Schließen",children:y.jsx(qx,{className:"size-5"})})]}),y.jsx("div",{className:"px-6 pb-6 pt-4 text-sm text-gray-700 dark:text-gray-300 overflow-y-auto",children:i}),n?y.jsx("div",{className:"px-6 py-4 border-t border-gray-200/70 dark:border-white/10 flex justify-end gap-3",children:n}):null]})})})})]})})}async function wv(s,e){const t=await fetch(s,e);if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(i||`HTTP ${t.status}`)}return t.json()}const Bw=(s,e)=>y.jsx("span",{className:wi("inline-flex items-center rounded-md px-2 py-0.5 text-xs","bg-indigo-50 text-indigo-700 dark:bg-indigo-500/10 dark:text-indigo-200"),children:e});function o9(s){let e=(s??"").trim();if(!e)return null;/^https?:\/\//i.test(e)||(e=`https://${e}`);try{const t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.toString()}catch{return null}}function Av(s){if(!s)return[];const e=s.split(/[\n,;|]+/g).map(i=>i.trim()).filter(Boolean),t=Array.from(new Set(e));return t.sort((i,n)=>i.localeCompare(n,void 0,{sensitivity:"base"})),t}function l9(s){return String(s??"").trim().toLowerCase().replace(/^www\./,"")}function u9(s){const t=String(s||"").replaceAll("\\","/").split("/");return t[t.length-1]||""}function c9(s){const e=String(s||"");return e.toUpperCase().startsWith("HOT ")?e.slice(4).trim():e}function d9(s){const e=u9(s||""),t=c9(e);if(!t)return"—";const i=t.replace(/\.[^.]+$/,""),n=i.match(/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}$/);if(n?.[1])return n[1];const r=i.lastIndexOf("_");return r>0?i.slice(0,r):i}function Fw(s){if(s.isUrl&&/^https?:\/\//i.test(String(s.input??"")))return String(s.input);const e=l9(s.host),t=String(s.modelKey??"").trim();return!e||!t?null:e.includes("chaturbate.com")||e.includes("chaturbate")?`https://chaturbate.com/${encodeURIComponent(t)}/`:e.includes("myfreecams.com")||e.includes("myfreecams")?`https://www.myfreecams.com/#${encodeURIComponent(t)}`:null}function Uw({title:s,active:e,hiddenUntilHover:t,onClick:i,icon:n}){return y.jsx("span",{className:wi(t&&!e?"opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto transition-opacity":"opacity-100"),children:y.jsx(li,{variant:e?"soft":"secondary",size:"xs",className:wi("px-2 py-1 leading-none",e?"":"bg-transparent shadow-none hover:bg-gray-50 dark:hover:bg-white/10"),title:s,onClick:i,children:y.jsx("span",{className:"text-base leading-none",children:n})})})}function jw(s){return s==null?{isNull:!0,kind:"string",value:""}:s instanceof Date?{isNull:!1,kind:"number",value:s.getTime()}:typeof s=="number"?{isNull:!1,kind:"number",value:s}:typeof s=="boolean"?{isNull:!1,kind:"number",value:s?1:0}:typeof s=="bigint"?{isNull:!1,kind:"number",value:Number(s)}:{isNull:!1,kind:"string",value:String(s).toLocaleLowerCase()}}function h9(){const[s,e]=A.useState([]),t=A.useRef({}),[i,n]=A.useState(!1),[r,o]=A.useState(null),[u,c]=A.useState(""),[d,f]=A.useState(1),p=10,[g,v]=A.useState([]),[b,_]=A.useState({}),[S,D]=A.useState(!1),[R,L]=A.useState({key:"videos",direction:"desc"}),P=A.useCallback(async()=>{D(!0);try{const ge=await fetch("/api/record/done?all=1&includeKeep=1",{cache:"no-store"});if(!ge.ok)return;const st=await ge.json().catch(()=>null),Ve=Array.isArray(st?.items)?st.items:Array.isArray(st)?st:[],et={};for(const vt of Ve){const ot=d9(vt.output);if(!ot||ot==="—")continue;const ht=ot.trim().toLowerCase();ht&&(et[ht]=(et[ht]??0)+1)}_(et)}finally{D(!1)}},[]),U=A.useMemo(()=>new Set(g.map(ge=>ge.toLowerCase())),[g]),V=A.useCallback(ge=>{const st=ge.toLowerCase();v(Ve=>Ve.some(vt=>vt.toLowerCase()===st)?Ve.filter(vt=>vt.toLowerCase()!==st):[...Ve,ge])},[]),M=A.useCallback(()=>v([]),[]);A.useEffect(()=>{const ge=st=>{const Ve=st,et=Array.isArray(Ve.detail?.tags)?Ve.detail.tags:[];v(et)};return window.addEventListener("models:set-tag-filter",ge),()=>window.removeEventListener("models:set-tag-filter",ge)},[]);const[G,N]=A.useState(""),[O,K]=A.useState(null),[Q,W]=A.useState(null),[re,J]=A.useState(!1),[Y,z]=A.useState(!1),[Z,ie]=A.useState(null),[ce,j]=A.useState(null),[ee,he]=A.useState("favorite"),[Te,xe]=A.useState(!1),[Ae,Ke]=A.useState(null);async function lt(){if(Z){xe(!0),j(null),o(null);try{const ge=new FormData;ge.append("file",Z),ge.append("kind",ee);const st=await fetch("/api/models/import",{method:"POST",body:ge});if(!st.ok)throw new Error(await st.text());const Ve=await st.json();j(`✅ Import: ${Ve.inserted} neu, ${Ve.updated} aktualisiert, ${Ve.skipped} übersprungen`),z(!1),ie(null),await it(),window.dispatchEvent(new Event("models-changed"))}catch(ge){Ke(ge?.message??String(ge))}finally{xe(!1)}}}function nt(ge){return{output:`${ge}_01_01_2000__00-00-00.mp4`}}const yt=()=>{Ke(null),j(null),ie(null),he("favorite"),z(!0)},it=A.useCallback(async()=>{n(!0),o(null);try{const ge=await wv("/api/models/list",{cache:"no-store"});e(Array.isArray(ge)?ge:[]),P()}catch(ge){o(ge?.message??String(ge))}finally{n(!1)}},[P]);A.useEffect(()=>{P()},[P]),A.useEffect(()=>{it()},[it]),A.useEffect(()=>{const ge=st=>{const et=st?.detail??{};if(et?.model){const vt=et.model;e(ot=>{const ht=ot.findIndex(Gt=>Gt.id===vt.id);if(ht===-1)return ot;const rt=ot.slice();return rt[ht]=vt,rt});return}if(et?.removed&&et?.id){const vt=String(et.id);e(ot=>ot.filter(ht=>ht.id!==vt));return}it()};return window.addEventListener("models-changed",ge),()=>window.removeEventListener("models-changed",ge)},[it]),A.useEffect(()=>{const ge=G.trim();if(!ge){K(null),W(null);return}const st=o9(ge);if(!st){K(null),W("Bitte nur gültige http(s) URLs einfügen (keine Modelnamen).");return}const Ve=window.setTimeout(async()=>{try{const et=await wv("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:st})});if(!et?.isUrl){K(null),W("Bitte nur URLs einfügen (keine Modelnamen).");return}K(et),W(null)}catch(et){K(null),W(et?.message??String(et))}},300);return()=>window.clearTimeout(Ve)},[G]);const Ot=A.useMemo(()=>s.map(ge=>({m:ge,hay:`${ge.modelKey} ${ge.host??""} ${ge.input??""} ${ge.tags??""}`.toLowerCase()})),[s]),pt=A.useDeferredValue(u),xt=A.useMemo(()=>[{key:"statusAll",header:"Status",align:"center",cell:ge=>{const st=ge.liked===!0,Ve=ge.favorite===!0,et=ge.watching===!0,vt=!et&&!Ve&&!st;return y.jsxs("div",{className:"group flex items-center justify-center gap-1 w-[110px]",children:[y.jsx("span",{className:wi(vt&&!et?"opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto transition-opacity":"opacity-100"),children:y.jsx(li,{variant:et?"soft":"secondary",size:"xs",className:wi("px-2 py-1 leading-none",!et&&"bg-transparent shadow-none hover:bg-gray-50 dark:hover:bg-white/10"),title:et?"Nicht mehr beobachten":"Beobachten",onClick:ot=>{ot.stopPropagation(),Dt(ge.id,{watched:!et})},children:y.jsx("span",{className:wi("text-base leading-none",et?"text-indigo-600 dark:text-indigo-400":"text-gray-400 dark:text-gray-500"),children:"👁"})})}),y.jsx(Uw,{title:Ve?"Favorit entfernen":"Als Favorit markieren",active:Ve,hiddenUntilHover:vt,onClick:ot=>{ot.stopPropagation(),Ve?Dt(ge.id,{favorite:!1}):Dt(ge.id,{favorite:!0,liked:!1})},icon:y.jsx("span",{className:Ve?"text-amber-500":"text-gray-400 dark:text-gray-500",children:"★"})}),y.jsx(Uw,{title:st?"Gefällt mir entfernen":"Gefällt mir",active:st,hiddenUntilHover:vt,onClick:ot=>{ot.stopPropagation(),st?Dt(ge.id,{liked:!1}):Dt(ge.id,{liked:!0,favorite:!1})},icon:y.jsx("span",{className:st?"text-rose-500":"text-gray-400 dark:text-gray-500",children:"♥"})})]})}},{key:"model",header:"Model",sortable:!0,sortValue:ge=>(ge.modelKey||"").toLowerCase(),cell:ge=>{const st=Fw(ge);return y.jsxs("div",{className:"min-w-0",children:[y.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[y.jsx("div",{className:"font-medium truncate",children:ge.modelKey}),st?y.jsx("span",{className:"shrink-0 text-xs text-gray-400 dark:text-gray-500",title:st,onClick:Ve=>{Ve.stopPropagation(),window.open(st,"_blank","noreferrer")},children:"↗"}):null]}),y.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 truncate",children:ge.host??"—"}),st?y.jsx("div",{className:"text-xs text-indigo-600 dark:text-indigo-400 truncate max-w-[520px]",children:st}):null]})}},{key:"videos",header:"Videos",sortable:!0,sortValue:ge=>{const st=String(ge.modelKey||"").trim().toLowerCase(),Ve=b[st];return typeof Ve=="number"?Ve:0},align:"right",cell:ge=>{const st=String(ge.modelKey||"").trim().toLowerCase(),Ve=b[st];return y.jsx("span",{className:"tabular-nums text-sm text-gray-900 dark:text-white w-[64px] inline-block text-right",children:typeof Ve=="number"?Ve:S?"…":0})}},{key:"tags",header:"Tags",sortable:!0,sortValue:ge=>Av(ge.tags).length,cell:ge=>{const st=Av(ge.tags),Ve=st.slice(0,6),et=st.length-Ve.length,vt=st.join(", ");return y.jsxs("div",{className:"flex flex-wrap gap-2 max-w-[520px]",title:vt||void 0,children:[ge.hot?Bw(!0,"🔥 HOT"):null,ge.keep?Bw(!0,"📌 Behalten"):null,Ve.map(ot=>y.jsx(Br,{tag:ot,title:ot,active:U.has(ot.toLowerCase()),onClick:V},ot)),et>0?y.jsxs(Br,{title:vt,children:["+",et]}):null,!ge.hot&&!ge.keep&&st.length===0?y.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"—"}):null]})}},{key:"actions",header:"",align:"right",cell:ge=>y.jsx("div",{className:"flex justify-end w-[56px]",children:y.jsx(va,{job:nt(ge.modelKey),variant:"table",order:["details"],className:"flex items-center"})})}],[U,V,b,S]),Pt=A.useMemo(()=>{const ge=pt.trim().toLowerCase(),st=ge?Ot.filter(Ve=>Ve.hay.includes(ge)).map(Ve=>Ve.m):s;return U.size===0?st:st.filter(Ve=>{const et=Av(Ve.tags);if(et.length===0)return!1;const vt=new Set(et.map(ot=>ot.toLowerCase()));for(const ot of U)if(!vt.has(ot))return!1;return!0})},[s,Ot,pt,U]),Ze=A.useMemo(()=>{if(!R)return Pt;const ge=xt.find(et=>et.key===R.key);if(!ge)return Pt;const st=R.direction==="asc"?1:-1,Ve=Pt.map((et,vt)=>({r:et,i:vt}));return Ve.sort((et,vt)=>{let ot=0;if(ge.sortFn)ot=ge.sortFn(et.r,vt.r);else{const ht=ge.sortValue?ge.sortValue(et.r):et.r?.[ge.key],rt=ge.sortValue?ge.sortValue(vt.r):vt.r?.[ge.key],Gt=jw(ht),Bt=jw(rt);Gt.isNull&&!Bt.isNull?ot=1:!Gt.isNull&&Bt.isNull?ot=-1:Gt.kind==="number"&&Bt.kind==="number"?ot=Gt.valueBt.value?1:0:ot=String(Gt.value).localeCompare(String(Bt.value),void 0,{numeric:!0})}return ot===0?et.i-vt.i:ot*st}),Ve.map(et=>et.r)},[Pt,R,xt]);A.useEffect(()=>{f(1)},[u,g]);const Nt=Ze.length,wt=A.useMemo(()=>Math.max(1,Math.ceil(Nt/p)),[Nt,p]);A.useEffect(()=>{d>wt&&f(wt)},[d,wt]);const jt=A.useMemo(()=>{const ge=(d-1)*p;return Ze.slice(ge,ge+p)},[Ze,d,p]),gt=async()=>{if(O){if(!O.isUrl){W("Bitte nur URLs einfügen (keine Modelnamen).");return}J(!0),o(null);try{const ge=await wv("/api/models/upsert",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)});e(st=>{const Ve=st.filter(et=>et.id!==ge.id);return[ge,...Ve]}),N(""),K(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:ge}}))}catch(ge){o(ge?.message??String(ge))}finally{J(!1)}}};async function Dt(ge,st){if(o(null),t.current[ge])return;t.current[ge]=!0;const Ve=s.find(et=>et.id===ge)??null;if(Ve){const et={...Ve,...st};typeof st?.watched=="boolean"&&(et.watching=st.watched),st?.favorite===!0&&(et.liked=!1),st?.liked===!0&&(et.favorite=!1),e(vt=>vt.map(ot=>ot.id===ge?et:ot)),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:et}}))}try{const et=await fetch("/api/models/flags",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:ge,...st})});if(et.status===204){e(ot=>ot.filter(ht=>ht.id!==ge)),Ve?window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:Ve.id,modelKey:Ve.modelKey}})):window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:ge}}));return}if(!et.ok){const ot=await et.text().catch(()=>"");throw new Error(ot||`HTTP ${et.status}`)}const vt=await et.json();e(ot=>{const ht=ot.findIndex(Gt=>Gt.id===vt.id);if(ht===-1)return ot;const rt=ot.slice();return rt[ht]=vt,rt}),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:vt}}))}catch(et){Ve&&(e(vt=>vt.map(ot=>ot.id===ge?Ve:ot)),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:Ve}}))),o(et?.message??String(et))}finally{delete t.current[ge]}}return y.jsxs("div",{className:"space-y-4",children:[y.jsx(xa,{header:y.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Model hinzufügen"}),grayBody:!0,children:y.jsxs("div",{className:"grid gap-2",children:[y.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[y.jsx("input",{value:G,onChange:ge=>N(ge.target.value),placeholder:"https://…",className:"flex-1 rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white"}),y.jsx(li,{className:"px-3 py-2 text-sm",onClick:gt,disabled:!O||re,title:O?"In Models speichern":"Bitte gültige URL einfügen",children:"Hinzufügen"}),y.jsx(li,{className:"px-3 py-2 text-sm",onClick:it,disabled:i,children:"Aktualisieren"})]}),Q?y.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:Q}):O?y.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Gefunden: ",y.jsx("span",{className:"font-medium",children:O.modelKey}),O.host?y.jsxs("span",{className:"opacity-70",children:[" • ",O.host]}):null]}):null,r?y.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:r}):null]})}),y.jsxs(xa,{header:y.jsxs("div",{className:"space-y-2",children:[y.jsxs("div",{className:"grid gap-2 sm:flex sm:items-center sm:justify-between",children:[y.jsxs("div",{className:"flex items-center justify-between gap-2",children:[y.jsxs("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:["Models ",y.jsxs("span",{className:"text-gray-500 dark:text-gray-400",children:["(",Pt.length,")"]})]}),y.jsx("div",{className:"sm:hidden",children:y.jsx(li,{variant:"secondary",size:"md",onClick:yt,children:"Import"})})]}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("div",{className:"hidden sm:block",children:y.jsx(li,{variant:"secondary",size:"md",onClick:yt,children:"Importieren"})}),y.jsx("input",{value:u,onChange:ge=>c(ge.target.value),placeholder:"Suchen…",className:`\r w-full sm:w-[260px]\r rounded-md px-3 py-2 text-sm\r bg-white text-gray-900 shadow-sm ring-1 ring-gray-200\r focus:outline-none focus:ring-2 focus:ring-indigo-500\r dark:bg-white/10 dark:text-white dark:ring-white/10\r `})]})]}),g.length>0?y.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.jsx("span",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Tag-Filter:"}),y.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[g.map(ge=>y.jsx(Br,{tag:ge,active:!0,onClick:V,title:ge},ge)),y.jsx(li,{size:"sm",variant:"soft",className:"text-xs font-medium text-gray-600 hover:underline dark:text-gray-300",onClick:M,children:"Zurücksetzen"})]})]}):null]}),noBodyPadding:!0,children:[y.jsx("div",{className:"overflow-x-auto",children:y.jsx("div",{className:"min-w-[980px]",children:y.jsx(Gx,{rows:jt,columns:xt,getRowKey:ge=>ge.id,striped:!0,compact:!0,fullWidth:!0,stickyHeader:!0,sort:R,onSortChange:ge=>L(ge),onRowClick:ge=>{const st=Fw(ge);st&&window.open(st,"_blank","noreferrer")}})})}),y.jsx(NA,{page:d,pageSize:p,totalItems:Nt,onPageChange:f})]}),y.jsx(Bx,{open:Y,onClose:()=>!Te&&z(!1),title:"Models importieren",footer:y.jsxs(y.Fragment,{children:[y.jsx(li,{variant:"secondary",onClick:()=>z(!1),disabled:Te,children:"Abbrechen"}),y.jsx(li,{variant:"primary",onClick:lt,isLoading:Te,disabled:!Z||Te,children:"Import starten"})]}),children:y.jsxs("div",{className:"space-y-3",children:[y.jsx("div",{className:"text-sm text-gray-700 dark:text-gray-300",children:"Wähle eine CSV-Datei zum Import aus."}),y.jsxs("div",{className:"space-y-2",children:[y.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Import-Typ"}),y.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:gap-4",children:[y.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[y.jsx("input",{type:"radio",name:"import-kind",value:"favorite",checked:ee==="favorite",onChange:()=>he("favorite"),disabled:Te}),"Favoriten (★)"]}),y.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[y.jsx("input",{type:"radio",name:"import-kind",value:"liked",checked:ee==="liked",onChange:()=>he("liked"),disabled:Te}),"Gefällt mir (♥)"]})]})]}),y.jsx("input",{type:"file",accept:".csv,text/csv",onChange:ge=>{const st=ge.target.files?.[0]??null;Ke(null),ie(st)},className:"block w-full text-sm text-gray-700 file:mr-4 file:rounded-md file:border-0 file:bg-gray-100 file:px-3 file:py-2 file:text-sm file:font-semibold file:text-gray-900 hover:file:bg-gray-200 dark:text-gray-200 dark:file:bg-white/10 dark:file:text-white dark:hover:file:bg-white/20"}),Z?y.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-400",children:["Ausgewählt: ",y.jsx("span",{className:"font-medium",children:Z.name})]}):null,Ae?y.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:Ae}):null,ce?y.jsx("div",{className:"rounded-md bg-green-50 px-3 py-2 text-xs text-green-700 dark:bg-green-500/10 dark:text-green-200",children:ce}):null]})})]})}function bn(...s){return s.filter(Boolean).join(" ")}const f9=new Intl.NumberFormat("de-DE");function Cv(s){return s==null||!Number.isFinite(s)?"—":f9.format(s)}function m9(s){if(s==null||!Number.isFinite(s))return"—";const e=["B","KB","MB","GB","TB"];let t=s,i=0;for(;t>=1024&&i0?`${t}:${String(i).padStart(2,"0")}:${String(n).padStart(2,"0")}`:`${i}:${String(n).padStart(2,"0")}`}function Wd(s){if(!s)return"—";const e=typeof s=="string"?new Date(s):s;return Number.isNaN(e.getTime())?String(s):e.toLocaleString("de-DE",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"})}function p9(s){return s?s.split(",").map(e=>e.trim()).filter(Boolean):[]}function zl(s){return(s||"").split(/[\\/]/).pop()||""}function g9(s){return String(s||"").replaceAll("\\","/")}function y9(s){return(g9(s||"").toLowerCase().match(/\/keep\/([^/]+)\//)?.[1]||"").trim().toLowerCase()}function rT(s){return s.startsWith("HOT ")?s.slice(4):s}function v9(s){return String(s||"").startsWith("HOT ")}function x9(s,e){const t=String(s||"");return t&&t.replace(/([\\/])[^\\/]*$/,`$1${e}`)}function b9(s){return v9(s)?rT(s):`HOT ${s}`}function Hw(s){const e=zl(s||""),t=rT(e);if(!t)return"—";const i=t.replace(/\.[^.]+$/,""),n=i.match(/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}$/);if(n?.[1])return n[1];const r=i.lastIndexOf("_");return r>0?i.slice(0,r):i}function kv(s){return s?String(s).replace(/[\s\S]*?<\/script>/gi,"").replace(/[\s\S]*?<\/style>/gi,"").replace(/<\/?[^>]+>/g," ").replace(/\s+/g," ").trim():""}function T9(s){if(!s)return"";const e=String(s).trim();return e?e.startsWith("http://")||e.startsWith("https://")?e:e.startsWith("/")?`https://chaturbate.com${e}`:`https://chaturbate.com/${e}`:""}function Ya(s){return bn("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset",s)}const Dv=s=>s?"blur-md scale-[1.03] brightness-90":"";function _9(s){let e=String(s??"").trim();if(!e)return"";if(e=e.replace(/^https?:\/\//i,""),e.includes("/")){const t=e.split("/").filter(Boolean);e=t[t.length-1]||e}return e.includes(":")&&(e=e.split(":").pop()||e),e.trim().toLowerCase()}function S9(s){const e=s??{},t=e.cf_clearance||e["cf-clearance"]||e.cfclearance||"",i=e.sessionId||e.sessionid||e.session_id||e["session-id"]||"",n=[];return t&&n.push(`cf_clearance=${t}`),i&&n.push(`sessionid=${i}`),n.join("; ")}function E9({open:s,modelKey:e,onClose:t,onOpenPlayer:i,cookies:n,runningJobs:r,blurPreviews:o,onToggleWatch:u,onToggleFavorite:c,onToggleLike:d,onToggleHot:f,onDelete:p}){const[g,v]=A.useState([]),[b,_]=A.useState(!1),[S,D]=A.useState(null),[R,L]=A.useState(null),[P,U]=A.useState(!1),[V,M]=A.useState(null),[G,N]=A.useState(null),[O,K]=A.useState(!1),[Q,W]=A.useState([]),[re,J]=A.useState(!1),[Y,z]=A.useState([]),[Z,ie]=A.useState(!1),[ce,j]=A.useState(0),[ee,he]=A.useState(null),Te=A.useCallback(async()=>{try{const H=await(await fetch("/api/models/list",{cache:"no-store"})).json().catch(()=>null);v(Array.isArray(H)?H:[])}catch{}},[]),xe=A.useCallback(async()=>{try{const q=await(await fetch("/api/record/done?all=1&sort=completed_desc&includeKeep=1",{cache:"no-store"})).json().catch(()=>null),ne=Array.isArray(q)?q:Array.isArray(q?.items)?q.items:[];W(ne)}catch{}},[]);function Ae(Pe){return{id:`model:${Pe}`,output:`${Pe}_01_01_2000__00-00-00.mp4`,status:"finished"}}const Ke=A.useCallback((Pe,H)=>{const q=String(Pe??"").trim();q&&he({src:q,alt:H})},[]);A.useEffect(()=>{s||j(0)},[s]);const[lt,nt]=A.useState(1),yt=25,it=_9(e),Ot=A.useMemo(()=>Array.isArray(r)?r:Y,[r,Y]);A.useEffect(()=>{s&&nt(1)},[s,e]),A.useEffect(()=>{if(!s)return;let Pe=!0;return _(!0),fetch("/api/models/list",{cache:"no-store"}).then(H=>H.json()).then(H=>{Pe&&v(Array.isArray(H)?H:[])}).catch(()=>{Pe&&v([])}).finally(()=>{Pe&&_(!1)}),()=>{Pe=!1}},[s]),A.useEffect(()=>{if(!s||!it)return;let Pe=!0;return U(!0),D(null),L(null),fetch("/api/chaturbate/online",{cache:"no-store"}).then(H=>H.json()).then(H=>{if(!Pe)return;L({enabled:H?.enabled,fetchedAt:H?.fetchedAt,lastError:H?.lastError});const ne=(Array.isArray(H?.rooms)?H.rooms:[]).find(Se=>String(Se?.username??"").trim().toLowerCase()===it)??null;D(ne)}).catch(()=>{Pe&&(L({enabled:void 0,fetchedAt:void 0,lastError:"Fetch fehlgeschlagen"}),D(null))}).finally(()=>{Pe&&U(!1)}),()=>{Pe=!1}},[s,it]),A.useEffect(()=>{if(!s||!it)return;let Pe=!0;K(!0),M(null),N(null);const H=S9(n),q=`/api/chaturbate/biocontext?model=${encodeURIComponent(it)}${ce>0?"&refresh=1":""}`;return fetch(q,{cache:"no-store",headers:H?{"X-Chaturbate-Cookie":H}:void 0}).then(async ne=>{if(!ne.ok){const Se=await ne.text().catch(()=>"");throw new Error(Se||`HTTP ${ne.status}`)}return ne.json()}).then(ne=>{Pe&&(N({enabled:ne?.enabled,fetchedAt:ne?.fetchedAt,lastError:ne?.lastError}),M(ne?.bio??null))}).catch(ne=>{Pe&&(N({enabled:void 0,fetchedAt:void 0,lastError:ne?.message||"Fetch fehlgeschlagen"}),M(null))}).finally(()=>{Pe&&K(!1)}),()=>{Pe=!1}},[s,it,ce,n]),A.useEffect(()=>{if(!s)return;let Pe=!0;return J(!0),fetch("/api/record/done?all=1&sort=completed_desc&includeKeep=1",{cache:"no-store"}).then(q=>q.json()).then(q=>{if(!Pe)return;const ne=Array.isArray(q)?q:Array.isArray(q?.items)?q.items:[];W(ne)}).catch(()=>{Pe&&W([])}).finally(()=>{Pe&&J(!1)}),()=>{Pe=!1}},[s]),A.useEffect(()=>{if(!s||Array.isArray(r))return;let Pe=!0;return ie(!0),fetch("/api/record/jobs",{cache:"no-store"}).then(H=>H.json()).then(H=>{Pe&&z(Array.isArray(H)?H:[])}).catch(()=>{Pe&&z([])}).finally(()=>{Pe&&ie(!1)}),()=>{Pe=!1}},[s,r]);const pt=A.useMemo(()=>it?g.find(Pe=>(Pe.modelKey||"").toLowerCase()===it)??null:null,[g,it]),xt=A.useMemo(()=>it?Q.filter(Pe=>{const H=Pe.output||"",q=y9(H);if(q)return q===it;const ne=Hw(H);return ne!=="—"&&ne.trim().toLowerCase()===it}):[],[Q,it]),Pt=A.useMemo(()=>Math.max(1,Math.ceil(xt.length/yt)),[xt.length]),Ze=A.useMemo(()=>{const Pe=(lt-1)*yt;return xt.slice(Pe,Pe+yt)},[xt,lt]),Nt=A.useMemo(()=>it?Ot.filter(Pe=>{const H=Hw(Pe.output);return H!=="—"&&H.trim().toLowerCase()===it}):[],[Ot,it]),wt=A.useMemo(()=>{const Pe=p9(pt?.tags),H=Array.isArray(S?.tags)?S.tags:[],q=new Map;for(const ne of[...Pe,...H]){const Se=String(ne).trim().toLowerCase();Se&&(q.has(Se)||q.set(Se,String(ne).trim()))}return Array.from(q.values()).sort((ne,Se)=>ne.localeCompare(Se,"de"))},[pt?.tags,S?.tags]),jt=S?.display_name||pt?.modelKey||it||"Model",gt=S?.image_url_360x270||S?.image_url||"",Dt=S?.image_url||gt,ge=S?.chat_room_url_revshare||S?.chat_room_url||"",st=(S?.current_show||"").trim().toLowerCase(),Ve=st?st==="public"?"Public":st==="private"?"Private":st:"",et=(V?.location||"").trim(),vt=V?.follower_count,ot=V?.display_age,ht=(V?.room_status||"").trim(),rt=V?.last_broadcast?Wd(V.last_broadcast):"—",Gt=kv(V?.about_me),Bt=kv(V?.wish_list),Lt=Array.isArray(V?.social_medias)?V.social_medias:[],si=Array.isArray(V?.photo_sets)?V.photo_sets:[],We=Array.isArray(V?.interested_in)?V.interested_in:[],Ct=b||re||Z||P||O,Mt=({icon:Pe,label:H,value:q})=>y.jsxs("div",{className:"rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2 dark:border-white/10 dark:bg-white/5",children:[y.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600 dark:text-gray-300",children:[Pe,H]}),y.jsx("div",{className:"mt-0.5 text-sm font-semibold text-gray-900 dark:text-white",children:q})]}),pi=A.useCallback(async Pe=>{const H=Pe.output||"",q=zl(H);if(!q){await f?.(Pe);return}const ne=b9(q);W(Se=>Se.map(Je=>zl(Je.output||"")!==q?Je:{...Je,output:x9(Je.output||"",ne)})),await f?.(Pe),xe()},[f,xe]),Ei=A.useCallback(async Pe=>{const H=Pe.output||"",q=zl(H);q&&W(ne=>ne.filter(Se=>zl(Se.output||"")!==q)),await p?.(Pe),xe()},[p,xe]),Tt=A.useCallback(async()=>{it&&(v(Pe=>Pe.map(H=>(H.modelKey||"").toLowerCase()===it?{...H,favorite:!H.favorite}:H)),await c?.(Ae(it)),Te())},[it,c,Te]),ft=A.useCallback(async()=>{it&&(v(Pe=>Pe.map(H=>(H.modelKey||"").toLowerCase()===it?{...H,liked:H.liked!==!0}:H)),await d?.(Ae(it)),Te())},[it,d,Te]),ui=A.useCallback(async()=>{it&&(v(Pe=>Pe.map(H=>(H.modelKey||"").toLowerCase()===it?{...H,watching:!H.watching}:H)),await u?.(Ae(it)),Te())},[it,u,Te]);return y.jsxs(Bx,{open:s,onClose:t,title:jt,width:"max-w-6xl",footer:y.jsx(li,{variant:"secondary",onClick:t,children:"Schließen"}),children:[y.jsxs("div",{className:"space-y-6",children:[y.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[y.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:it?y.jsxs("span",{children:["Key: ",y.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:it}),R?.fetchedAt?y.jsxs("span",{className:"ml-2 text-gray-500 dark:text-gray-400",children:["· Online-Stand: ",Wd(R.fetchedAt)]}):null,G?.fetchedAt?y.jsxs("span",{className:"ml-2 text-gray-500 dark:text-gray-400",children:["· Bio-Stand: ",Wd(G.fetchedAt)]}):null]}):"—"}),y.jsx("div",{className:"flex items-center gap-2",children:ge?y.jsxs("a",{href:ge,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 rounded-lg border border-gray-200/70 bg-white/70 px-2.5 py-1.5 text-xs font-medium text-gray-900 shadow-sm backdrop-blur hover:bg-white dark:border-white/10 dark:bg-white/5 dark:text-white",children:[y.jsx(yy,{className:"size-4"}),"Room öffnen"]}):null})]}),y.jsxs("div",{className:"grid gap-5 lg:grid-cols-[320px_1fr]",children:[y.jsx("div",{className:"space-y-4",children:y.jsxs("div",{className:"overflow-hidden rounded-2xl border border-gray-200/70 bg-white/70 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[y.jsxs("div",{className:"relative",children:[gt?y.jsx("button",{type:"button",className:"block w-full cursor-zoom-in",onClick:()=>Ke(Dt,jt),"aria-label":"Bild vergrößern",children:y.jsx("img",{src:gt,alt:jt,className:bn("h-52 w-full object-cover transition",Dv(o))})}):y.jsx("div",{className:"h-52 w-full bg-gradient-to-br from-indigo-500/10 via-transparent to-sky-500/10"}),y.jsx("div",{"aria-hidden":!0,className:"pointer-events-none absolute inset-0 bg-gradient-to-t from-black/40 via-black/0 to-black/0"}),y.jsxs("div",{className:"absolute left-3 top-3 flex flex-wrap items-center gap-2",children:[Ve?y.jsx("span",{className:Ya("bg-emerald-500/10 text-emerald-900 ring-emerald-200 backdrop-blur dark:text-emerald-200 dark:ring-emerald-400/20"),children:Ve}):null,ht?y.jsx("span",{className:Ya(ht.toLowerCase()==="online"?"bg-emerald-500/10 text-emerald-900 ring-emerald-200 backdrop-blur dark:text-emerald-200 dark:ring-emerald-400/20":"bg-gray-500/10 text-gray-900 ring-gray-200 backdrop-blur dark:text-gray-200 dark:ring-white/15"),children:ht}):null,S?.is_hd?y.jsx("span",{className:Ya("bg-indigo-500/10 text-indigo-900 ring-indigo-200 backdrop-blur dark:text-indigo-200 dark:ring-indigo-400/20"),children:"HD"}):null,S?.is_new?y.jsx("span",{className:Ya("bg-amber-500/10 text-amber-900 ring-amber-200 backdrop-blur dark:text-amber-200 dark:ring-amber-400/20"),children:"NEW"}):null]}),y.jsxs("div",{className:"absolute bottom-3 left-3 right-3",children:[y.jsx("div",{className:"truncate text-sm font-semibold text-white drop-shadow",children:S?.display_name||S?.username||pt?.modelKey||it||"—"}),y.jsx("div",{className:"truncate text-xs text-white/85 drop-shadow",children:S?.username?`@${S.username}`:pt?.modelKey?`@${pt.modelKey}`:""})]}),y.jsxs("div",{className:"absolute bottom-3 right-3 flex items-center gap-2",children:[y.jsx("button",{type:"button",onClick:Pe=>{Pe.preventDefault(),Pe.stopPropagation(),Tt()},className:bn("inline-flex items-center justify-center rounded-full p-2 ring-1 ring-inset backdrop-blur","cursor-pointer hover:scale-[1.03] active:scale-[0.98] transition",pt?.favorite?"bg-amber-500/25 ring-amber-200/30":"bg-black/20 ring-white/15"),title:pt?.favorite?"Favorit entfernen":"Als Favorit markieren","aria-pressed":!!pt?.favorite,"aria-label":pt?.favorite?"Favorit entfernen":"Als Favorit markieren",children:y.jsxs("span",{className:"relative inline-block size-4",children:[y.jsx(Hv,{className:bn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",pt?.favorite?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0","text-white/70")}),y.jsx(yh,{className:bn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",pt?.favorite?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12","text-amber-200")})]})}),y.jsx("button",{type:"button",onClick:Pe=>{Pe.preventDefault(),Pe.stopPropagation(),ft()},className:bn("inline-flex items-center justify-center rounded-full p-2 ring-1 ring-inset backdrop-blur","cursor-pointer hover:scale-[1.03] active:scale-[0.98] transition",pt?.liked?"bg-rose-500/25 ring-rose-200/30":"bg-black/20 ring-white/15"),title:pt?.liked?"Like entfernen":"Liken","aria-pressed":pt?.liked===!0,"aria-label":pt?.liked?"Like entfernen":"Liken",children:y.jsxs("span",{className:"relative inline-block size-4",children:[y.jsx(Jm,{className:bn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",pt?.liked?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0","text-white/70")}),y.jsx(_c,{className:bn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",pt?.liked?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12","text-rose-200")})]})}),y.jsx("button",{type:"button",onClick:Pe=>{Pe.preventDefault(),Pe.stopPropagation(),ui()},className:bn("inline-flex items-center justify-center rounded-full p-2 ring-1 ring-inset backdrop-blur","cursor-pointer hover:scale-[1.03] active:scale-[0.98] transition",pt?.watching?"bg-sky-500/25 ring-sky-200/30":"bg-black/20 ring-white/15"),title:pt?.watching?"Watch entfernen":"Auf Watch setzen","aria-pressed":!!pt?.watching,"aria-label":pt?.watching?"Watch entfernen":"Auf Watch setzen",children:y.jsxs("span",{className:"relative inline-block size-4",children:[y.jsx($v,{className:bn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",pt?.watching?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0","text-white/70")}),y.jsx(Tc,{className:bn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",pt?.watching?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12","text-sky-200")})]})})]})]}),y.jsxs("div",{className:"p-4",children:[y.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[y.jsx(Mt,{icon:y.jsx(XO,{className:"size-4"}),label:"Viewer",value:Cv(S?.num_users)}),y.jsx(Mt,{icon:y.jsx(NS,{className:"size-4"}),label:"Follower",value:Cv(S?.num_followers??vt)})]}),y.jsxs("dl",{className:"mt-4 grid gap-2 text-xs",children:[y.jsxs("div",{className:"flex items-center justify-between gap-2",children:[y.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[y.jsx(BO,{className:"size-4"}),"Location"]}),y.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:S?.location||et||"—"})]}),y.jsxs("div",{className:"flex items-center justify-between gap-2",children:[y.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[y.jsx(IO,{className:"size-4"}),"Sprache"]}),y.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:S?.spoken_languages||"—"})]}),y.jsxs("div",{className:"flex items-center justify-between gap-2",children:[y.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[y.jsx(LS,{className:"size-4"}),"Online"]}),y.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:$w(S?.seconds_online)})]}),y.jsxs("div",{className:"flex items-center justify-between gap-2",children:[y.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[y.jsx(Jm,{className:"size-4"}),"Alter"]}),y.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:ot!=null?String(ot):S?.age!=null?String(S.age):"—"})]}),y.jsxs("div",{className:"flex items-center justify-between gap-2",children:[y.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[y.jsx(LS,{className:"size-4"}),"Last broadcast"]}),y.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:rt})]})]}),R?.enabled===!1?y.jsx("div",{className:"mt-3 rounded-lg border border-amber-200/60 bg-amber-50/70 px-3 py-2 text-xs text-amber-900 dark:border-amber-400/20 dark:bg-amber-400/10 dark:text-amber-200",children:"Chaturbate-Online ist aktuell deaktiviert."}):R?.lastError?y.jsxs("div",{className:"mt-3 rounded-lg border border-rose-200/60 bg-rose-50/70 px-3 py-2 text-xs text-rose-900 dark:border-rose-400/20 dark:bg-rose-400/10 dark:text-rose-200",children:["Online-Info: ",R.lastError]}):null,G?.enabled===!1?y.jsx("div",{className:"mt-3 rounded-lg border border-amber-200/60 bg-amber-50/70 px-3 py-2 text-xs text-amber-900 dark:border-amber-400/20 dark:bg-amber-400/10 dark:text-amber-200",children:"BioContext ist aktuell deaktiviert."}):G?.lastError?y.jsxs("div",{className:"mt-3 rounded-lg border border-rose-200/60 bg-rose-50/70 px-3 py-2 text-xs text-rose-900 dark:border-rose-400/20 dark:bg-rose-400/10 dark:text-rose-200",children:["BioContext: ",G.lastError]}):null]})]})}),y.jsxs("div",{className:"space-y-4",children:[y.jsxs("div",{className:"rounded-2xl border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[y.jsxs("div",{className:"flex items-center justify-between gap-3",children:[y.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Room Subject"}),Ct?y.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Lade…"}):null]}),y.jsx("div",{className:"mt-2 text-sm text-gray-800 dark:text-gray-100",children:S?.room_subject?y.jsx("p",{className:"line-clamp-4 whitespace-pre-wrap break-words",children:S.room_subject}):y.jsx("p",{className:"text-gray-600 dark:text-gray-300",children:"Keine Subject-Info vorhanden."})})]}),y.jsxs("div",{className:"rounded-2xl border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[y.jsxs("div",{className:"flex items-center justify-between gap-3",children:[y.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Bio"}),y.jsxs("div",{className:"flex items-center gap-2",children:[O?y.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Lade…"}):null,y.jsx(li,{variant:"secondary",className:"h-7 px-2 text-xs",disabled:O||!e,onClick:()=>j(Pe=>Pe+1),title:"BioContext neu abrufen",children:"Aktualisieren"})]})]}),y.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[y.jsxs("div",{className:"rounded-xl border border-gray-200/70 bg-white/60 p-3 dark:border-white/10 dark:bg-white/5",children:[y.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-gray-700 dark:text-gray-200",children:[y.jsx(kO,{className:"size-4"}),"Über mich"]}),y.jsx("div",{className:"mt-2 text-sm text-gray-800 dark:text-gray-100",children:Gt?y.jsx("p",{className:"line-clamp-6 whitespace-pre-wrap",children:Gt}):y.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"—"})})]}),y.jsxs("div",{className:"rounded-xl border border-gray-200/70 bg-white/60 p-3 dark:border-white/10 dark:bg-white/5",children:[y.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-gray-700 dark:text-gray-200",children:[y.jsx(NS,{className:"size-4"}),"Wishlist"]}),y.jsx("div",{className:"mt-2 text-sm text-gray-800 dark:text-gray-100",children:Bt?y.jsx("p",{className:"line-clamp-6 whitespace-pre-wrap",children:Bt}):y.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"—"})})]})]}),y.jsxs("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[y.jsxs("div",{className:"rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2 text-xs dark:border-white/10 dark:bg-white/5",children:[y.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Real name:"})," ",y.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:V?.real_name?kv(V.real_name):"—"})]}),y.jsxs("div",{className:"rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2 text-xs dark:border-white/10 dark:bg-white/5",children:[y.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Body type:"})," ",y.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:V?.body_type||"—"})]}),y.jsxs("div",{className:"rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2 text-xs dark:border-white/10 dark:bg-white/5",children:[y.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Smoke/Drink:"})," ",y.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:V?.smoke_drink||"—"})]}),y.jsxs("div",{className:"rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2 text-xs dark:border-white/10 dark:bg-white/5",children:[y.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Sex:"})," ",y.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:V?.sex||"—"})]})]}),We.length?y.jsxs("div",{className:"mt-3",children:[y.jsx("div",{className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:"Interested in"}),y.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:We.map(Pe=>y.jsx("span",{className:Ya("bg-sky-500/10 text-sky-900 ring-sky-200 dark:text-sky-200 dark:ring-sky-400/20"),children:Pe},Pe))})]}):null]}),y.jsxs("div",{className:"rounded-2xl border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[y.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Tags"}),wt.length?y.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:wt.map(Pe=>y.jsx(Br,{tag:Pe},Pe))}):y.jsx("div",{className:"mt-2 text-sm text-gray-600 dark:text-gray-300",children:"Keine Tags vorhanden."})]}),y.jsxs("div",{className:"rounded-2xl border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[y.jsxs("div",{className:"flex items-center justify-between gap-3",children:[y.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Socials"}),Lt.length?y.jsxs("span",{className:"text-xs text-gray-600 dark:text-gray-300",children:[Lt.length," Links"]}):null]}),Lt.length?y.jsx("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:Lt.map(Pe=>{const H=T9(Pe.link);return y.jsxs("a",{href:H,target:"_blank",rel:"noreferrer",className:bn("group flex items-center gap-3 rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2 text-gray-900","transition hover:border-indigo-200 hover:bg-gray-50/80 hover:text-gray-900 dark:border-white/10 dark:bg-white/5 dark:text-white dark:hover:border-indigo-400/30 dark:hover:bg-white/10 dark:hover:text-white"),title:Pe.title_name,children:[y.jsx("div",{className:"flex size-9 items-center justify-center rounded-lg bg-black/5 dark:bg-white/5",children:Pe.image_url?y.jsx("img",{src:Pe.image_url,alt:"",className:"size-5"}):y.jsx(OO,{className:"size-5"})}),y.jsxs("div",{className:"min-w-0",children:[y.jsx("div",{className:"truncate text-sm font-medium text-gray-900 dark:text-white",children:Pe.title_name}),y.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:Pe.label_text?Pe.label_text:Pe.tokens!=null?`${Pe.tokens} token(s)`:"Link"})]}),y.jsx(yy,{className:"ml-auto size-4 text-gray-400 transition group-hover:text-indigo-500 dark:text-gray-500 dark:group-hover:text-indigo-400"})]},Pe.id)})}):y.jsx("div",{className:"mt-2 text-sm text-gray-600 dark:text-gray-300",children:"Keine Social-Medias vorhanden."})]}),y.jsxs("div",{className:"rounded-2xl border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[y.jsxs("div",{className:"flex items-center justify-between gap-3",children:[y.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Photo sets"}),si.length?y.jsxs("span",{className:"text-xs text-gray-600 dark:text-gray-300",children:[si.length," Sets"]}):null]}),si.length?y.jsx("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:si.slice(0,6).map(Pe=>y.jsxs("div",{className:"overflow-hidden rounded-xl border border-gray-200/70 bg-white/60 dark:border-white/10 dark:bg-white/5",children:[y.jsxs("div",{className:"relative",children:[Pe.cover_url?y.jsx("button",{type:"button",className:"block w-full cursor-zoom-in",onClick:()=>Ke(Pe.cover_url,Pe.name),"aria-label":"Bild vergrößern",children:y.jsx("img",{src:Pe.cover_url,alt:Pe.name,className:bn("h-28 w-full object-cover transition",Dv(o))})}):y.jsx("div",{className:"flex h-28 w-full items-center justify-center bg-black/5 dark:bg-white/5",children:y.jsx(UO,{className:"size-6 text-gray-500"})}),y.jsxs("div",{className:"absolute left-2 top-2 flex flex-wrap gap-2",children:[Pe.is_video?y.jsx("span",{className:Ya("bg-indigo-500/10 text-indigo-900 ring-indigo-200 dark:text-indigo-200 dark:ring-indigo-400/20"),children:"Video"}):y.jsx("span",{className:Ya("bg-gray-500/10 text-gray-900 ring-gray-200 dark:text-gray-200 dark:ring-white/15"),children:"Photos"}),Pe.fan_club_only?y.jsx("span",{className:Ya("bg-amber-500/10 text-amber-900 ring-amber-200 dark:text-amber-200 dark:ring-amber-400/20"),children:"FanClub"}):null]})]}),y.jsxs("div",{className:"p-3",children:[y.jsx("div",{className:"truncate text-sm font-medium text-gray-900 dark:text-white",children:Pe.name}),y.jsxs("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:["Tokens: ",y.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:Cv(Pe.tokens)}),Pe.user_can_access===!0?y.jsx("span",{className:"ml-2",children:"· Zugriff: ✅"}):null]})]})]},Pe.id))}):y.jsx("div",{className:"mt-2 text-sm text-gray-600 dark:text-gray-300",children:"Keine Photo-Sets vorhanden."})]})]})]}),y.jsxs("div",{className:"rounded-2xl border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[y.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[y.jsxs("div",{children:[y.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Abgeschlossene Downloads"}),y.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Inkl. Dateien aus ",y.jsx("span",{className:"font-medium",children:"/done/keep/"})]})]}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx(li,{size:"sm",variant:"secondary",disabled:re||lt<=1,onClick:()=>nt(Pe=>Math.max(1,Pe-1)),children:"Zurück"}),y.jsxs("span",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Seite ",lt," / ",Pt]}),y.jsx(li,{size:"sm",variant:"secondary",disabled:re||lt>=Pt,onClick:()=>nt(Pe=>Math.min(Pt,Pe+1)),children:"Weiter"})]})]}),y.jsx("div",{className:"mt-3",children:re?y.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Lade Downloads…"}):xt.length===0?y.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine abgeschlossenen Downloads für dieses Model gefunden."}):y.jsx("div",{className:"grid gap-2",children:Ze.map(Pe=>{const H=zl(Pe.output||""),q=H.startsWith("HOT "),ne=Pe.endedAt?Wd(Pe.endedAt):"—";return y.jsxs("div",{role:i?"button":void 0,tabIndex:i?0:void 0,className:bn("group flex w-full items-center justify-between gap-3 overflow-hidden rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2","transition hover:border-indigo-200 hover:bg-gray-50/80 dark:border-white/10 dark:bg-white/5 dark:hover:border-indigo-400/30 dark:hover:bg-white/10",i?"cursor-pointer":""),onClick:()=>i?.(Pe),onKeyDown:Se=>{i&&(Se.key==="Enter"||Se.key===" ")&&i(Pe)},children:[y.jsxs("div",{className:"min-w-0",children:[y.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[y.jsx("div",{className:"min-w-0 flex-1 truncate text-sm font-medium text-gray-900 dark:text-white",children:rT(H)||"—"}),q?y.jsx("span",{className:Ya("shrink-0 bg-orange-500/10 text-orange-900 ring-orange-200 dark:text-orange-200 dark:ring-orange-400/20"),children:"HOT"}):null]}),y.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-600 dark:text-gray-300",children:[y.jsxs("span",{children:["Datum: ",y.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:ne})]}),y.jsxs("span",{children:["Dauer:"," ",y.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:$w(Pe.durationSeconds)})]}),y.jsxs("span",{children:["Größe:"," ",y.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:m9(Pe.sizeBytes)})]})]})]}),y.jsx("div",{className:"shrink-0 flex items-center gap-2",children:y.jsx("span",{onClick:Se=>Se.stopPropagation(),onMouseDown:Se=>Se.stopPropagation(),onKeyDown:Se=>Se.stopPropagation(),children:y.jsx(va,{job:Pe,variant:"table",isHot:q,isFavorite:!!pt?.favorite,isLiked:pt?.liked===!0,isWatching:!!pt?.watching,onToggleHot:pi,onDelete:Ei,order:["hot","delete"],className:"flex items-center"})})})]},`${Pe.id}-${H}`)})})})]}),y.jsxs("div",{className:"rounded-2xl border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[y.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Laufende Jobs"}),y.jsx("div",{className:"mt-2",children:Z?y.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Lade…"}):Nt.length===0?y.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine laufenden Jobs."}):y.jsx("div",{className:"grid gap-2",children:Nt.map(Pe=>y.jsx("div",{className:"overflow-hidden rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2 text-sm dark:border-white/10 dark:bg-white/5",children:y.jsxs("div",{className:"flex items-start gap-3",children:[y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsx("div",{className:"break-words line-clamp-2 font-medium text-gray-900 dark:text-white",children:zl(Pe.output||"")}),y.jsxs("div",{className:"mt-0.5 text-xs text-gray-600 dark:text-gray-300",children:["Start:"," ",y.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:Wd(Pe.startedAt)})]})]}),i?y.jsx(li,{size:"sm",variant:"secondary",className:"shrink-0",onClick:()=>i(Pe),children:"Öffnen"}):null]})},Pe.id))})})]})]}),y.jsx(Bx,{open:!!ee,onClose:()=>he(null),title:ee?.alt||"Bild",width:"max-w-4xl",footer:y.jsxs("div",{className:"flex items-center justify-end gap-2",children:[ee?.src?y.jsxs("a",{href:ee.src,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 rounded-lg border border-gray-200/70 bg-white/70 px-3 py-1.5 text-xs font-medium text-gray-900 shadow-sm backdrop-blur hover:bg-white dark:border-white/10 dark:bg-white/5 dark:text-white",children:[y.jsx(yy,{className:"size-4"}),"In neuem Tab"]}):null,y.jsx(li,{variant:"secondary",onClick:()=>he(null),children:"Schließen"})]}),children:y.jsx("div",{className:"grid place-items-center",children:ee?.src?y.jsx("img",{src:ee.src,alt:ee.alt||"",className:bn("max-h-[80vh] w-auto max-w-full rounded-xl object-contain",Dv(o))}):null})})]})}const Im=s=>Math.max(0,Math.min(1,s));function Nm(s){return s==="good"?"bg-emerald-500":s==="warn"?"bg-amber-500":"bg-red-500"}function w9(s){return s==null?"–":`${Math.round(s)}ms`}function Vw(s){return s==null?"–":`${Math.round(s)}%`}function Lv(s){if(s==null||!Number.isFinite(s)||s<=0)return"–";const e=["B","KB","MB","GB","TB"];let t=s,i=0;for(;t>=1024&&i=10?1:2;return`${t.toFixed(n)} ${e[i]}`}function A9(s=1e3){const[e,t]=$t.useState(null);return $t.useEffect(()=>{let i=0,n=performance.now(),r=0,o=!0,u=!1;const c=g=>{if(!o||!u)return;r+=1;const v=g-n;if(v>=s){const b=Math.round(r*1e3/v);t(b),r=0,n=g}i=requestAnimationFrame(c)},d=()=>{o&&(document.hidden||u||(u=!0,n=performance.now(),r=0,i=requestAnimationFrame(c)))},f=()=>{u=!1,cancelAnimationFrame(i)},p=()=>{document.hidden?f():d()};return d(),document.addEventListener("visibilitychange",p),()=>{o=!1,document.removeEventListener("visibilitychange",p),f()}},[s]),e}function Gw({mode:s="inline",className:e,pollMs:t=3e3}){const i=A9(1e3),[n,r]=$t.useState(null),[o,u]=$t.useState(null),[c,d]=$t.useState(null),[f,p]=$t.useState(null),[g,v]=$t.useState(null),b=5*1024*1024*1024,_=8*1024*1024*1024,S=$t.useRef(!1);$t.useEffect(()=>{const W=`/api/perf/stream?ms=${encodeURIComponent(String(t))}`,re=tR(W,"perf",J=>{const Y=typeof J?.cpuPercent=="number"?J.cpuPercent:null,z=typeof J?.diskFreeBytes=="number"?J.diskFreeBytes:null,Z=typeof J?.diskTotalBytes=="number"?J.diskTotalBytes:null,ie=typeof J?.diskUsedPercent=="number"?J.diskUsedPercent:null;u(Y),d(z),p(Z),v(ie);const ce=typeof J?.serverMs=="number"?J.serverMs:null;r(ce!=null?Math.max(0,Date.now()-ce):null)});return()=>re()},[t]);const D=n==null?"bad":n<=120?"good":n<=300?"warn":"bad",R=i==null?"bad":i>=55?"good":i>=30?"warn":"bad",L=o==null?"bad":o<=60?"good":o<=85?"warn":"bad",P=Im((n??999)/500),U=Im((i??0)/60),V=Im((o??0)/100),M=c!=null&&f!=null&&f>0?c/f:null,G=g??(M!=null?(1-M)*100:null),N=Im((G??0)/100);c==null?S.current=!1:S.current?c>=_&&(S.current=!1):c<=b&&(S.current=!0);const O=c==null||S.current||M==null?"bad":M>=.15?"good":M>=.07?"warn":"bad",K=c==null?"Disk: –":`Free: ${Lv(c)} / Total: ${Lv(f)} · Used: ${Vw(G)}`,Q=s==="floating"?"fixed bottom-4 right-4 z-[80]":"flex items-center";return y.jsx("div",{className:`${Q} ${e??""}`,children:y.jsxs("div",{className:`\r rounded-lg border border-gray-200/70 bg-white/70 px-2.5 py-1.5 shadow-sm backdrop-blur\r dark:border-white/10 dark:bg-white/5\r grid grid-cols-2 gap-x-3 gap-y-2\r sm:flex sm:items-center sm:gap-3\r `,children:[y.jsxs("div",{className:"flex items-center gap-2",title:K,children:[y.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"Disk"}),y.jsx("div",{className:"h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:y.jsx("div",{className:`h-full ${Nm(O)}`,style:{width:`${Math.round(N*100)}%`}})}),y.jsx("span",{className:"text-[11px] w-11 tabular-nums text-gray-900 dark:text-gray-100",children:Lv(c)})]}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"Ping"}),y.jsx("div",{className:"h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:y.jsx("div",{className:`h-full ${Nm(D)}`,style:{width:`${Math.round(P*100)}%`}})}),y.jsx("span",{className:"text-[11px] w-10 tabular-nums text-gray-900 dark:text-gray-100",children:w9(n)})]}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"FPS"}),y.jsx("div",{className:"h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:y.jsx("div",{className:`h-full ${Nm(R)}`,style:{width:`${Math.round(U*100)}%`}})}),y.jsx("span",{className:"text-[11px] w-8 tabular-nums text-gray-900 dark:text-gray-100",children:i??"–"})]}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"CPU"}),y.jsx("div",{className:"h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:y.jsx("div",{className:`h-full ${Nm(L)}`,style:{width:`${Math.round(V*100)}%`}})}),y.jsx("span",{className:"text-[11px] w-10 tabular-nums text-gray-900 dark:text-gray-100",children:Vw(o)})]})]})})}function C9(s,e){const t=[];for(let i=0;i{t!=null&&(window.clearTimeout(t),t=null)},c=()=>{if(i){try{i.abort()}catch{}i=null}},d=p=>{o||(u(),t=window.setTimeout(()=>{f()},p))},f=async()=>{if(!o)try{const p=(s.getModels?.()??[]).map(K=>String(K||"").trim()).filter(Boolean),v=(s.getShow?.()??[]).map(K=>String(K||"").trim()).filter(Boolean).slice().sort(),b=p.slice().sort(),_=b.length===0&&!!s.fetchAllWhenNoModels;if(b.length===0&&!_){c();const K={enabled:r?.enabled??!1,rooms:[]};r=K,s.onData(K);const Q=document.hidden?Math.max(15e3,e):e;d(Q);return}const S=_?[]:b,D=`${v.join(",")}|${_?"__ALL__":S.join(",")}`,R=D;n=D,c();const L=new AbortController;i=L;const U=_?[[]]:C9(S,350);let V=[],M=!1,G=0,N=!1;for(const K of U){if(L.signal.aborted||R!==n||o)return;const Q=await fetch("/api/chaturbate/online",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({q:K,show:v,refresh:!1}),signal:L.signal,cache:"no-store"});if(!Q.ok)continue;N=!0;const W=await Q.json();M=M||!!W?.enabled,V.push(...Array.isArray(W?.rooms)?W.rooms:[]);const re=Number(W?.total??0);Number.isFinite(re)&&re>G&&(G=re)}if(!N){const K=document.hidden?Math.max(15e3,e):e;d(K);return}const O={enabled:M,rooms:k9(V),total:G};if(L.signal.aborted||R!==n||o)return;r=O,s.onData(O)}catch(p){if(p?.name==="AbortError")return;s.onError?.(p)}finally{const p=document.hidden?Math.max(15e3,e):e;d(p)}};return f(),()=>{o=!0,u(),c()}}async function qw(s,e){const t=await fetch(s,e);if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(i||`HTTP ${t.status}`)}return t.json()}function Kw(s,e,t){const i=`/api/generated/cover?category=${encodeURIComponent(s)}`,n=e?`&v=${e}`:"";return`${i}${n}${t?"&refresh=1":""}`}function Yw(s){if(!s)return[];const e=s.split(/[\n,;|]+/g).map(t=>t.trim()).filter(Boolean);return Array.from(new Set(e))}function lR(s){return String(s||"").replaceAll("\\","/").split("/").pop()||""}function uR(s){return s.toUpperCase().startsWith("HOT ")?s.slice(4).trim():s}function D9(s){const e=uR(lR(s||""));return e?e.replace(/\.[^.]+$/,""):""}const L9=/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}/;function R9(s){const t=uR(lR(s)).replace(/\.[^.]+$/,""),i=t.match(L9);if(i?.[1]?.trim())return i[1].trim();const n=t.lastIndexOf("_");return n>0?t.slice(0,n).trim():t?t.trim():null}function Ww(s){const e=D9(s);return e?`/generated/meta/${encodeURIComponent(e)}/thumbs.jpg`:null}async function Xw(s,e,t){const i=`/api/generated/cover?category=${encodeURIComponent(s)}&src=${encodeURIComponent(e)}`+(t?"&refresh=1":"");await fetch(i,{method:"GET",cache:"no-store"})}function I9(){const[s,e]=A.useState([]),[t,i]=A.useState(!1),[n,r]=A.useState(null),[o,u]=A.useState(()=>Date.now()),c=A.useRef({}),d=A.useCallback((v,b)=>{const _={};for(const D of Array.isArray(v)?v:[]){const R=String(D?.modelKey??"").trim().toLowerCase();if(!R)continue;const L=Yw(D?.tags).map(P=>P.toLowerCase());L.length&&(_[R]=L)}const S={};for(const D of Array.isArray(b)?b:[]){const R=String(D?.output??"");if(!R)continue;const L=(R9(R)||"").trim().toLowerCase();if(!L)continue;const P=_[L];if(!(!P||P.length===0))for(const U of P)U&&(S[U]||(S[U]=[]),S[U].push(R))}for(const[D,R]of Object.entries(S))S[D]=Array.from(new Set(R));c.current=S},[]),f=A.useCallback(v=>{const b=String(v||"").trim();if(b){try{localStorage.setItem("finishedDownloads_pendingTags",JSON.stringify([b]))}catch{}window.dispatchEvent(new CustomEvent("app:navigate-tab",{detail:{tab:"finished"}})),window.dispatchEvent(new CustomEvent("finished-downloads:tag-filter",{detail:{tags:[b],mode:"replace"}}))}},[]),p=A.useCallback(async()=>{i(!0),r(null);try{const v=await qw("/api/models/list",{cache:"no-store"}),b=await qw("/api/record/done?page=1&pageSize=2000&sort=completed_desc",{cache:"no-store"}),_=Array.isArray(b?.items)?b.items:Array.isArray(b)?b:[];d(Array.isArray(v)?v:[],_);const S=new Map;for(const U of Array.isArray(v)?v:[])for(const V of Yw(U?.tags)){const M=V.toLowerCase();S.set(M,(S.get(M)??0)+1)}const D=c.current||{},R=Array.from(S.entries()).map(([U,V])=>({tag:U,modelsCount:V,downloadsCount:(D[U]||[]).length})).sort((U,V)=>U.tag.localeCompare(V.tag,void 0,{sensitivity:"base"}));e(R);const L=60;let P=0;for(const U of R){if(P>=L)break;const V=D[U.tag]||[];if(V.length===0)continue;const M=V[Math.floor(Math.random()*V.length)],G=M?Ww(M):null;G&&(P++,Xw(U.tag,G,!1).catch(()=>{}))}u(Date.now())}catch(v){r(v?.message??String(v)),e([]),c.current={}}finally{i(!1)}},[d]);A.useEffect(()=>{p()},[p]);const g=A.useCallback(async()=>{try{const v=c.current||{},b=await Promise.all(s.map(async S=>{const D=v[S.tag]||[],R=D.length?D[Math.floor(Math.random()*D.length)]:"",L=R?Ww(R):null;try{if(L)return await Xw(S.tag,L,!0),{tag:S.tag,ok:!0,status:200,text:""};const P=await fetch(Kw(S.tag,Date.now(),!0),{method:"GET",cache:"no-store"}),U=P.ok?"":await P.text().catch(()=>""),V=P.ok||P.status===404;return{tag:S.tag,ok:V,status:P.status,text:U}}catch(P){return{tag:S.tag,ok:!1,status:0,text:P?.message??String(P)}}})),_=b.filter(S=>!S.ok&&S.status!==404);if(_.length){console.warn("Cover renew failed:",_.slice(0,20));const S=_.slice(0,8).map(D=>`${D.tag} (${D.status||"ERR"})`).join(", ");r(`Covers fehlgeschlagen: ${_.length}/${b.length} — z.B.: ${S}`)}else r(null)}finally{u(Date.now())}},[s]);return y.jsxs(xa,{header:y.jsxs("div",{className:"flex items-center justify-between gap-2",children:[y.jsxs("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:["Kategorien ",y.jsxs("span",{className:"text-gray-500 dark:text-gray-400",children:["(",s.length,")"]})]}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx(li,{variant:"secondary",size:"md",onClick:g,disabled:t,children:"Cover erneuern"}),y.jsx(li,{variant:"secondary",size:"md",onClick:p,disabled:t,children:"Aktualisieren"})]})]}),grayBody:!0,children:[n?y.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:n}):null,s.length===0&&!t?y.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine Kategorien/Tags gefunden."}):null,y.jsx("div",{className:"mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:s.map(v=>{const b=Kw(v.tag,o);return y.jsxs("button",{type:"button",onClick:()=>f(v.tag),className:wi("group text-left rounded-xl ring-1 ring-gray-200/70 dark:ring-white/10","bg-white/70 hover:bg-white dark:bg-white/5 dark:hover:bg-white/10","overflow-hidden transition","focus:outline-none focus:ring-2 focus:ring-indigo-500"),title:"In FinishedDownloads öffnen (Tag-Filter setzen)",children:[y.jsx("div",{className:"relative h-24",children:y.jsx("img",{src:b,alt:v.tag,className:"absolute inset-0 h-full w-full object-cover",loading:"lazy"})}),y.jsx("div",{className:"px-3 py-3",children:y.jsxs("div",{className:"flex items-start justify-between gap-2",children:[y.jsxs("div",{className:"min-w-0",children:[y.jsx("div",{className:"font-semibold text-gray-900 dark:text-white truncate",children:v.tag}),y.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:[v.downloadsCount," Downloads • ",v.modelsCount," Models"]})]}),y.jsx("span",{className:"shrink-0 rounded-md bg-gray-100 px-2 py-1 text-xs font-semibold text-gray-900 dark:bg-white/10 dark:text-white tabular-nums",children:v.downloadsCount})]})})]},v.tag)})})]})}const Rv="record_cookies";function Om(s){return Object.fromEntries(Object.entries(s??{}).map(([t,i])=>[t.trim().toLowerCase(),String(i??"").trim()]).filter(([t,i])=>t.length>0&&i.length>0))}async function Fs(s,e){const t=await fetch(s,e);if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(i||`HTTP ${t.status}`)}return t.json()}const Qw={recordDir:"records",doneDir:"records/done",ffmpegPath:"",autoAddToDownloadList:!1,autoStartAddedDownloads:!1,useChaturbateApi:!1,useMyFreeCamsWatcher:!1,autoDeleteSmallDownloads:!1,autoDeleteSmallDownloadsBelowMB:200,blurPreviews:!1,teaserPlayback:"hover",teaserAudio:!1,lowDiskPauseBelowGB:3e3};function qm(s){let e=(s??"").trim();if(!e)return null;e=e.replace(/^[("'[{<]+/,"").replace(/[)"'\]}>.,;:]+$/,""),/^https?:\/\//i.test(e)||(e=`https://${e}`);try{const t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.toString()}catch{return null}}function Qu(s){const e=(s??"").trim();if(!e)return null;for(const t of e.split(/\s+/g)){const i=qm(t);if(i)return i}return null}function Zw(s){try{const e=new URL(s).hostname.replace(/^www\./i,"").toLowerCase();return e==="chaturbate.com"||e.endsWith(".chaturbate.com")?"chaturbate":e==="myfreecams.com"||e.endsWith(".myfreecams.com")?"mfc":null}catch{return null}}const Us=s=>(s||"").replaceAll("\\","/").split("/").pop()||"";function N9(s,e){const i=(s||"").replaceAll("\\","/").split("/");return i[i.length-1]=e,i.join("/")}function O9(s){return s.startsWith("HOT ")?s.slice(4):s}const M9=/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}/;function Xd(s){const t=O9(Us(s)).replace(/\.[^.]+$/,""),i=t.match(M9);if(i?.[1]?.trim())return i[1].trim();const n=t.lastIndexOf("_");return n>0?t.slice(0,n):t||null}function P9(){const s=MA(),[e,t]=A.useState(!1);A.useEffect(()=>{const we=window,Ne=typeof we.requestIdleCallback=="function"?we.requestIdleCallback(()=>t(!0),{timeout:1500}):window.setTimeout(()=>t(!0),800);return()=>{typeof we.cancelIdleCallback=="function"?we.cancelIdleCallback(Ne):window.clearTimeout(Ne)}},[]);const i=8,n="finishedDownloads_sort",[r,o]=A.useState(()=>{try{return window.localStorage.getItem(n)||"completed_desc"}catch{return"completed_desc"}});A.useEffect(()=>{try{window.localStorage.setItem(n,r)}catch{}},[r]);const[u,c]=A.useState(null),[d,f]=A.useState(""),[p,g]=A.useState([]),[v,b]=A.useState([]),[_,S]=A.useState(1),[D,R]=A.useState(0),[L,P]=A.useState(0),[U,V]=A.useState(0),[M,G]=A.useState(()=>Date.now()),[N,O]=A.useState(()=>Date.now());A.useEffect(()=>{const we=window.setInterval(()=>O(Date.now()),1e3);return()=>window.clearInterval(we)},[]);const K=we=>(we||"").toLowerCase().trim(),Q=we=>{const Ne=Math.max(0,Math.floor(we/1e3));if(Ne<2)return"gerade eben";if(Ne<60)return`vor ${Ne} Sekunden`;const ke=Math.floor(Ne/60);if(ke===1)return"vor 1 Minute";if(ke<60)return`vor ${ke} Minuten`;const tt=Math.floor(ke/60);return tt===1?"vor 1 Stunde":`vor ${tt} Stunden`},W=A.useMemo(()=>{const we=N-M;return`(zuletzt aktualisiert: ${Q(we)})`},[N,M]),[re,J]=A.useState({}),Y=A.useCallback(we=>{const Ne={};for(const ke of Array.isArray(we)?we:[]){const tt=(ke?.modelKey||"").trim().toLowerCase();if(!tt)continue;const je=le=>(le.favorite?4:0)+(le.liked===!0?2:0)+(le.watching?1:0),ut=Ne[tt];(!ut||je(ke)>=je(ut))&&(Ne[tt]=ke)}return Ne},[]),z=A.useCallback(async()=>{try{const we=await Fs("/api/models/list",{cache:"no-store"});J(Y(Array.isArray(we)?we:[])),G(Date.now())}catch{}},[Y]),[Z,ie]=A.useState(null),ce=A.useRef(null),[j,ee]=A.useState(null);A.useEffect(()=>{const we=Ne=>{let je=(Ne.detail?.modelKey??"").trim().replace(/^https?:\/\//i,"");je.includes("/")&&(je=je.split("/").filter(Boolean).pop()||je),je.includes(":")&&(je=je.split(":").pop()||je),je=je.trim().toLowerCase(),je&&ee(je)};return window.addEventListener("open-model-details",we),()=>window.removeEventListener("open-model-details",we)},[]);const he=A.useCallback(we=>{const Ne=Date.now(),ke=ce.current;if(!ke){ce.current={ts:Ne,list:[we]};return}ke.ts=Ne;const tt=ke.list.findIndex(je=>je.id===we.id);tt>=0?ke.list[tt]=we:ke.list.unshift(we)},[]);A.useEffect(()=>{z();const we=Ne=>{const tt=Ne?.detail??{},je=tt?.model;if(je&&typeof je=="object"){const ut=String(je.modelKey??"").toLowerCase().trim();ut&&J(le=>({...le,[ut]:je}));try{he(je)}catch{}ie(le=>le?.id===je.id?je:le),G(Date.now());return}if(tt?.removed){const ut=String(tt?.id??"").trim(),le=String(tt?.modelKey??"").toLowerCase().trim();le&&J(ae=>{const{[le]:ye,...be}=ae;return be}),ut&&ie(ae=>ae?.id===ut?null:ae),G(Date.now());return}z()};return window.addEventListener("models-changed",we),()=>window.removeEventListener("models-changed",we)},[z,he]);const[Te,xe]=A.useState(null),[Ae,Ke]=A.useState(!1),[lt,nt]=A.useState(!1),[yt,it]=A.useState({}),[Ot,pt]=A.useState(!1),[xt,Pt]=A.useState("running"),[Ze,Nt]=A.useState(null),[wt,jt]=A.useState(!1),[gt,Dt]=A.useState(0),ge=A.useCallback(()=>Dt(we=>we+1),[]),st=A.useRef(null),Ve=A.useCallback(()=>{ge(),st.current&&window.clearTimeout(st.current),st.current=window.setTimeout(()=>ge(),3500)},[ge]),[et,vt]=A.useState(Qw),ot=A.useRef(et);A.useEffect(()=>{ot.current=et},[et]);const ht=!!et.autoAddToDownloadList,rt=!!et.autoStartAddedDownloads,[Gt,Bt]=A.useState([]),[Lt,si]=A.useState({}),We=A.useRef(!1),Ct=A.useRef({}),Mt=A.useRef([]);A.useEffect(()=>{We.current=Ae},[Ae]),A.useEffect(()=>{Ct.current=yt},[yt]),A.useEffect(()=>{Mt.current=p},[p]);const pi=A.useRef(null),Ei=A.useRef(""),[Tt,ft]=A.useState({}),ui=A.useRef({});A.useEffect(()=>{ui.current=Tt},[Tt]);const Pe=A.useCallback(we=>{const Ne=String(we?.host??"").toLowerCase(),ke=String(we?.input??"").toLowerCase();return Ne.includes("chaturbate")||ke.includes("chaturbate.com")},[]),H=A.useMemo(()=>{const we=new Set;for(const Ne of Object.values(re)){if(!Pe(Ne))continue;const ke=K(String(Ne?.modelKey??""));ke&&we.add(ke)}return Array.from(we)},[re,Pe]),q=A.useRef(re);A.useEffect(()=>{q.current=re},[re]);const ne=A.useRef(Lt);A.useEffect(()=>{ne.current=Lt},[Lt]);const Se=A.useRef(H);A.useEffect(()=>{Se.current=H},[H]);const Je=A.useRef(xt);A.useEffect(()=>{Je.current=xt},[xt]);const _t=A.useCallback(async(we,Ne)=>{const ke=qm(we);if(!ke)return!1;const tt=!!Ne?.silent;tt||xe(null);const je=Zw(ke);if(!je)return tt||xe("Nur chaturbate.com oder myfreecams.com werden unterstützt."),!1;const ut=Ct.current;if(je==="chaturbate"&&!Yt(ut))return tt||xe('Für Chaturbate müssen die Cookies "cf_clearance" und "sessionId" gesetzt sein.'),!1;if(Mt.current.some(ae=>ae.status!=="running"?!1:qm(String(ae.sourceUrl||""))===ke))return!0;if(je==="chaturbate"&&ot.current.useChaturbateApi)try{const ae=await Fs("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:ke})}),ye=String(ae?.modelKey??"").trim().toLowerCase();if(ye){if(We.current)return si(Fe=>({...Fe||{},[ye]:ke})),!0;const be=ui.current[ye],Me=String(be?.current_show??"");if(be&&Me&&Me!=="public")return si(Fe=>({...Fe||{},[ye]:ke})),!0}}catch{}else if(We.current)return pi.current=ke,!0;if(We.current)return!1;Ke(!0),We.current=!0;try{const ae=Object.entries(ut).map(([be,Me])=>`${be}=${Me}`).join("; "),ye=await Fs("/api/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:ke,cookie:ae})});return g(be=>[ye,...be]),Mt.current=[ye,...Mt.current],!0}catch(ae){return tt||xe(ae?.message??String(ae)),!1}finally{Ke(!1),We.current=!1}},[]);A.useEffect(()=>{let we=!1;const Ne=async()=>{try{const je=await Fs("/api/settings",{cache:"no-store"});!we&&je&&vt({...Qw,...je})}catch{}},ke=()=>{Ne()},tt=()=>{Ne()};return window.addEventListener("recorder-settings-updated",ke),window.addEventListener("focus",tt),document.addEventListener("visibilitychange",tt),Ne(),()=>{we=!0,window.removeEventListener("recorder-settings-updated",ke),window.removeEventListener("focus",tt),document.removeEventListener("visibilitychange",tt)}},[]),A.useEffect(()=>{let we=!1;const Ne=async()=>{try{const tt=await Fs("/api/models/meta",{cache:"no-store"}),je=Number(tt?.count??0);!we&&Number.isFinite(je)&&(P(je),G(Date.now()))}catch{}};Ne();const ke=window.setInterval(Ne,document.hidden?6e4:3e4);return()=>{we=!0,window.clearInterval(ke)}},[]);const ei=A.useMemo(()=>Object.entries(yt).map(([we,Ne])=>({name:we,value:Ne})),[yt]),Ai=A.useCallback(we=>{ce.current=null,ie(null),Nt(we),jt(!1)},[]),is=p.filter(we=>we.status==="running"),Ii=A.useMemo(()=>{let we=0;for(const Ne of Object.values(re)){if(!Ne?.watching||!Pe(Ne))continue;const ke=K(String(Ne?.modelKey??""));ke&&Tt[ke]&&we++}return we},[re,Tt,Pe]),{onlineFavCount:ji,onlineLikedCount:Zi}=A.useMemo(()=>{let we=0,Ne=0;for(const ke of Object.values(re)){const tt=K(String(ke?.modelKey??""));tt&&Tt[tt]&&(ke?.favorite&&we++,ke?.liked===!0&&Ne++)}return{onlineFavCount:we,onlineLikedCount:Ne}},[re,Tt]),gi=[{id:"running",label:"Laufende Downloads",count:is.length},{id:"finished",label:"Abgeschlossene Downloads",count:D},{id:"models",label:"Models",count:L},{id:"categories",label:"Kategorien"},{id:"settings",label:"Einstellungen"}],ss=A.useMemo(()=>d.trim().length>0&&!Ae,[d,Ae]);A.useEffect(()=>{let we=!1;return(async()=>{try{const ke=await Fs("/api/cookies",{cache:"no-store"}),tt=Om(ke?.cookies);if(we||it(tt),Object.keys(tt).length===0){const je=localStorage.getItem(Rv);if(je)try{const ut=JSON.parse(je),le=Om(ut);Object.keys(le).length>0&&(we||it(le),await Fs("/api/cookies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cookies:le})}))}catch{}}}catch{const ke=localStorage.getItem(Rv);if(ke)try{const tt=JSON.parse(ke);we||it(Om(tt))}catch{}}finally{we||pt(!0)}})(),()=>{we=!0}},[]),A.useEffect(()=>{Ot&&localStorage.setItem(Rv,JSON.stringify(yt))},[yt,Ot]),A.useEffect(()=>{let we=!1,Ne;const ke=async()=>{try{const je=await fetch(`/api/record/done?page=1&pageSize=1&withCount=1&sort=${encodeURIComponent(r)}`,{cache:"no-store"});if(!je.ok)return;const ut=await je.json().catch(()=>null),le=Number(ut?.count??ut?.totalCount??0),ae=Number.isFinite(le)&&le>=0?le:0;we||(R(ae),G(Date.now()))}catch{}finally{if(!we){const je=document.hidden?6e4:3e4;Ne=window.setTimeout(ke,je)}}},tt=()=>{document.hidden||ke()};return document.addEventListener("visibilitychange",tt),ke(),()=>{we=!0,Ne&&window.clearTimeout(Ne),document.removeEventListener("visibilitychange",tt)}},[r]),A.useEffect(()=>{const we=Math.max(1,Math.ceil(D/i));_>we&&S(we)},[D,_]),A.useEffect(()=>{let we=!1,Ne=null,ke=null,tt=!1;const je=be=>{const Me=Array.isArray(be)?be:[];if(we)return;const Fe=Mt.current,Qe=new Map(Fe.map(oe=>[oe.id,oe.status])),ct=Me.some(oe=>{const pe=Qe.get(oe.id);return pe&&pe!==oe.status&&(oe.status==="finished"||oe.status==="stopped")});g(Me),Mt.current=Me,G(Date.now()),ct&&Ve(),Nt(oe=>{if(!oe)return oe;const pe=Me.find(Ge=>Ge.id===oe.id);return pe||(oe.status==="running"?null:oe)})},ut=async()=>{if(!(we||tt)){tt=!0;try{const be=await Fs("/api/record/list");je(be)}catch{}finally{tt=!1}}},le=()=>{ke||(ke=window.setInterval(ut,document.hidden?15e3:5e3))};ut(),Ne=new EventSource("/api/record/stream");const ae=be=>{try{je(JSON.parse(be.data))}catch{}};Ne.addEventListener("jobs",ae),Ne.onerror=()=>le();const ye=()=>{document.hidden||ut()};return document.addEventListener("visibilitychange",ye),window.addEventListener("hover",ye),()=>{we=!0,ke&&window.clearInterval(ke),document.removeEventListener("visibilitychange",ye),window.removeEventListener("hover",ye),Ne?.removeEventListener("jobs",ae),Ne?.close(),Ne=null}},[Ve]),A.useEffect(()=>{if(xt!=="finished")return;let we=!1;const Ne={current:!1},ke=new AbortController,tt=async()=>{if(!(we||Ne.current)){Ne.current=!0;try{const ae=await fetch(`/api/record/done?page=${_}&pageSize=${i}&sort=${encodeURIComponent(r)}&withCount=1`,{cache:"no-store",signal:ke.signal});if(!ae.ok)throw new Error(`HTTP ${ae.status}`);const ye=await ae.json().catch(()=>null),be=Array.isArray(ye?.items)?ye.items:Array.isArray(ye)?ye:[],Me=typeof ye?.count=="number"?ye.count:typeof ye?.totalCount=="number"?ye.totalCount:be.length;we||(b(be),R(Number.isFinite(Me)?Me:be.length))}catch{we||(b([]),R(0))}finally{Ne.current=!1}}};tt();const ut=window.setInterval(()=>{document.hidden||tt()},2e4),le=()=>{document.hidden||tt()};return document.addEventListener("visibilitychange",le),()=>{we=!0,ke.abort(),window.clearInterval(ut),document.removeEventListener("visibilitychange",le)}},[xt,_,r]);const ci=A.useCallback(async we=>{try{const Ne=typeof we=="number"?we:_,ke=await Fs(`/api/record/done?page=${Ne}&pageSize=${i}&sort=${encodeURIComponent(r)}&withCount=1`,{cache:"no-store"}),tt=Array.isArray(ke?.items)?ke.items:[],je=Number(ke?.count??ke?.totalCount??tt.length),ut=Number.isFinite(je)&&je>=0?je:tt.length;R(ut);const le=Math.max(1,Math.ceil(ut/i)),ae=Math.min(Math.max(1,Ne),le);if(ae!==_&&S(ae),ae===Ne)b(tt);else{const ye=await Fs(`/api/record/done?page=${ae}&pageSize=${i}&sort=${encodeURIComponent(r)}&withCount=1`,{cache:"no-store"}),be=Array.isArray(ye?.items)?ye.items:[];b(be)}}catch{}},[_,r]);function Ni(we){const Ne=qm(we);if(!Ne)return!1;try{return new URL(Ne).hostname.includes("chaturbate.com")}catch{return!1}}function ri(we,Ne){const ke=Object.fromEntries(Object.entries(we).map(([tt,je])=>[tt.trim().toLowerCase(),je]));for(const tt of Ne){const je=ke[tt.toLowerCase()];if(je)return je}}function Yt(we){const Ne=ri(we,["cf_clearance"]),ke=ri(we,["sessionid","session_id","sessionId"]);return!!(Ne&&ke)}async function Xt(we){try{await Fs(`/api/record/stop?id=${encodeURIComponent(we)}`,{method:"POST"})}catch(Ne){s.error("Stop fehlgeschlagen",Ne?.message??String(Ne))}}A.useEffect(()=>{const we=Ne=>{const tt=Number(Ne.detail?.delta??0);if(!Number.isFinite(tt)||tt===0){ci();return}R(je=>Math.max(0,je+tt)),ci()};return window.addEventListener("finished-downloads:count-hint",we),()=>window.removeEventListener("finished-downloads:count-hint",we)},[ci]),A.useEffect(()=>{const we=Ne=>{const ke=Ne.detail||{};ke.tab==="finished"&&Pt("finished"),ke.tab==="categories"&&Pt("categories"),ke.tab==="models"&&Pt("models"),ke.tab==="running"&&Pt("running"),ke.tab==="settings"&&Pt("settings")};return window.addEventListener("app:navigate-tab",we),()=>window.removeEventListener("app:navigate-tab",we)},[]),A.useEffect(()=>{if(!Ze){ie(null),c(null);return}const we=(Xd(Ze.output||"")||"").trim().toLowerCase();c(we||null);const Ne=we?re[we]:void 0;ie(Ne??null)},[Ze,re]);async function Hs(){return _t(d)}const qi=A.useCallback(async we=>{const Ne=Us(we.output||"");if(Ne){window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:Ne,phase:"start"}}));try{const ke=await Fs(`/api/record/delete?file=${encodeURIComponent(Ne)}`,{method:"POST"});window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:Ne,phase:"success"}})),window.setTimeout(()=>{b(je=>je.filter(ut=>Us(ut.output||"")!==Ne)),g(je=>je.filter(ut=>Us(ut.output||"")!==Ne)),Nt(je=>je&&Us(je.output||"")===Ne?null:je)},320),window.setTimeout(()=>{ci()},350);const tt=typeof ke?.undoToken=="string"?ke.undoToken:"";return tt?{undoToken:tt}:{}}catch(ke){window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:Ne,phase:"error"}})),s.error("Löschen fehlgeschlagen",ke?.message??String(ke));return}}},[s,ci]),Vs=A.useCallback(async we=>{await qi(we)},[qi]),Kn=A.useCallback(async we=>{const Ne=Us(we.output||"");if(Ne){window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:Ne,phase:"start"}}));try{await Fs(`/api/record/keep?file=${encodeURIComponent(Ne)}`,{method:"POST"}),window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:Ne,phase:"success"}})),window.setTimeout(()=>{b(ke=>ke.filter(tt=>Us(tt.output||"")!==Ne)),g(ke=>ke.filter(tt=>Us(tt.output||"")!==Ne)),Nt(ke=>ke&&Us(ke.output||"")===Ne?null:ke)},320),ci()}catch(ke){window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:Ne,phase:"error"}})),s.error("Keep fehlgeschlagen",ke?.message??String(ke));return}}},[xt,ci,s]),Ts=A.useCallback(async we=>{const Ne=Us(we.output||"");if(Ne)try{const ke=await Fs(`/api/record/toggle-hot?file=${encodeURIComponent(Ne)}`,{method:"POST"});window.dispatchEvent(new CustomEvent("finished-downloads:rename",{detail:{oldFile:ke.oldFile,newFile:ke.newFile}}));const tt=je=>N9(je||"",ke.newFile);Nt(je=>je&&{...je,output:tt(je.output||"")}),b(je=>je.map(ut=>ut.id===we.id||Us(ut.output||"")===Ne?{...ut,output:tt(ut.output||"")}:ut)),g(je=>je.map(ut=>ut.id===we.id||Us(ut.output||"")===Ne?{...ut,output:tt(ut.output||"")}:ut))}catch(ke){s.error("Umbenennen fehlgeschlagen",ke?.message??String(ke))}},[s]);async function Zt(we){const Ne=await fetch("/api/models/flags",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(we)});if(Ne.status===204)return null;if(!Ne.ok){const ke=await Ne.text().catch(()=>"");throw new Error(ke||`HTTP ${Ne.status}`)}return Ne.json()}const vi=A.useCallback(we=>{const Ne=ce.current;!Ne||!we||(Ne.ts=Date.now(),Ne.list=Ne.list.filter(ke=>ke.id!==we))},[]),di=A.useRef({}),Ns=A.useCallback(async we=>{const Ne=Us(we.output||""),ke=!!(Ze&&Us(Ze.output||"")===Ne),tt=Fe=>{try{const Qe=String(Fe.sourceUrl??Fe.SourceURL??""),ct=Qu(Qe);return ct?new URL(ct).hostname.replace(/^www\./i,"").toLowerCase():""}catch{return""}},je=(Xd(we.output||"")||"").trim().toLowerCase();if(je){const Fe=je;if(di.current[Fe])return;di.current[Fe]=!0;const Qe=re[je]??{id:"",input:"",host:tt(we)||void 0,modelKey:je,watching:!1,favorite:!1,liked:null,isUrl:!1},ct=!Qe.favorite,oe={...Qe,modelKey:Qe.modelKey||je,favorite:ct,liked:ct?!1:Qe.liked};J(pe=>({...pe,[je]:oe})),he(oe),ke&&ie(oe);try{const pe=await Zt({...oe.id?{id:oe.id}:{},host:oe.host||tt(we)||"",modelKey:je,favorite:ct,...ct?{liked:!1}:{}});if(!pe){J(mt=>{const{[je]:Vt,...Wt}=mt;return Wt}),Qe.id&&vi(Qe.id),ke&&ie(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:Qe.id,modelKey:je}}));return}const Ge=K(pe.modelKey||je);Ge&&J(mt=>({...mt,[Ge]:pe})),he(pe),ke&&ie(pe),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:pe}}))}catch(pe){J(Ge=>({...Ge,[je]:Qe})),he(Qe),ke&&ie(Qe),s.error("Favorit umschalten fehlgeschlagen",pe?.message??String(pe))}finally{delete di.current[Fe]}return}let ut=ke?Z:null;if(ut||(ut=await Gs(we,{ensure:!0})),!ut)return;const le=K(ut.modelKey||ut.id||"");if(!le||di.current[le])return;di.current[le]=!0;const ae=ut,ye=!ae.favorite,be={...ae,favorite:ye,liked:ye?!1:ae.liked},Me=K(ae.modelKey||"");Me&&J(Fe=>({...Fe,[Me]:be})),he(be),ke&&ie(be);try{const Fe=await Zt({id:ae.id,favorite:ye,...ye?{liked:!1}:{}});if(!Fe){J(ct=>{const oe=K(ae.modelKey||"");if(!oe)return ct;const{[oe]:pe,...Ge}=ct;return Ge}),vi(ae.id),ke&&ie(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:ae.id,modelKey:ae.modelKey}}));return}const Qe=K(Fe.modelKey||"");Qe&&J(ct=>({...ct,[Qe]:Fe})),he(Fe),ke&&ie(Fe),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:Fe}}))}catch(Fe){const Qe=K(ae.modelKey||"");Qe&&J(ct=>({...ct,[Qe]:ae})),he(ae),ke&&ie(ae),s.error("Favorit umschalten fehlgeschlagen",Fe?.message??String(Fe))}finally{delete di.current[le]}},[s,Ze,Z,Gs,Zt,he,vi,re]),Os=A.useCallback(async we=>{const Ne=Us(we.output||""),ke=!!(Ze&&Us(Ze.output||"")===Ne),tt=Fe=>{try{const Qe=String(Fe.sourceUrl??Fe.SourceURL??""),ct=Qu(Qe);return ct?new URL(ct).hostname.replace(/^www\./i,"").toLowerCase():""}catch{return""}},je=(Xd(we.output||"")||"").trim().toLowerCase();if(je){const Fe=je;if(di.current[Fe])return;di.current[Fe]=!0;const Qe=re[je]??{id:"",input:"",host:tt(we)||void 0,modelKey:je,watching:!1,favorite:!1,liked:null,isUrl:!1},ct=Qe.liked!==!0,oe={...Qe,modelKey:Qe.modelKey||je,liked:ct,favorite:ct?!1:Qe.favorite};J(pe=>({...pe,[je]:oe})),he(oe),ke&&ie(oe);try{const pe=await Zt({...oe.id?{id:oe.id}:{},host:oe.host||tt(we)||"",modelKey:je,liked:ct,...ct?{favorite:!1}:{}});if(!pe){J(mt=>{const{[je]:Vt,...Wt}=mt;return Wt}),Qe.id&&vi(Qe.id),ke&&ie(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:Qe.id,modelKey:je}}));return}const Ge=K(pe.modelKey||je);Ge&&J(mt=>({...mt,[Ge]:pe})),he(pe),ke&&ie(pe),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:pe}}))}catch(pe){J(Ge=>({...Ge,[je]:Qe})),he(Qe),ke&&ie(Qe),s.error("Like umschalten fehlgeschlagen",pe?.message??String(pe))}finally{delete di.current[Fe]}return}let ut=ke?Z:null;if(ut||(ut=await Gs(we,{ensure:!0})),!ut)return;const le=K(ut.modelKey||ut.id||"");if(!le||di.current[le])return;di.current[le]=!0;const ae=ut,ye=ae.liked!==!0,be={...ae,liked:ye,favorite:ye?!1:ae.favorite},Me=K(ae.modelKey||"");Me&&J(Fe=>({...Fe,[Me]:be})),he(be),ke&&ie(be);try{const Fe=ye?await Zt({id:ae.id,liked:!0,favorite:!1}):await Zt({id:ae.id,liked:!1});if(!Fe){J(ct=>{const oe=K(ae.modelKey||"");if(!oe)return ct;const{[oe]:pe,...Ge}=ct;return Ge}),vi(ae.id),ke&&ie(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:ae.id,modelKey:ae.modelKey}}));return}const Qe=K(Fe.modelKey||"");Qe&&J(ct=>({...ct,[Qe]:Fe})),he(Fe),ke&&ie(Fe),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:Fe}}))}catch(Fe){const Qe=K(ae.modelKey||"");Qe&&J(ct=>({...ct,[Qe]:ae})),he(ae),ke&&ie(ae),s.error("Like umschalten fehlgeschlagen",Fe?.message??String(Fe))}finally{delete di.current[le]}},[s,Ze,Z,Gs,Zt,he,vi,re]),Li=A.useCallback(async we=>{const Ne=Us(we.output||""),ke=!!(Ze&&Us(Ze.output||"")===Ne),tt=Fe=>{try{const Qe=String(Fe.sourceUrl??Fe.SourceURL??""),ct=Qu(Qe);return ct?new URL(ct).hostname.replace(/^www\./i,"").toLowerCase():""}catch{return""}},je=(Xd(we.output||"")||"").trim().toLowerCase();if(je){const Fe=je;if(di.current[Fe])return;di.current[Fe]=!0;const Qe=re[je]??{id:"",input:"",host:tt(we)||void 0,modelKey:je,watching:!1,favorite:!1,liked:null,isUrl:!1},ct=!Qe.watching,oe={...Qe,modelKey:Qe.modelKey||je,watching:ct};J(pe=>({...pe,[je]:oe})),he(oe),ke&&ie(oe);try{const pe=await Zt({...oe.id?{id:oe.id}:{},host:oe.host||tt(we)||"",modelKey:je,watched:ct});if(!pe){J(mt=>{const{[je]:Vt,...Wt}=mt;return Wt}),Qe.id&&vi(Qe.id),ke&&ie(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:Qe.id,modelKey:je}}));return}const Ge=K(pe.modelKey||je);Ge&&J(mt=>({...mt,[Ge]:pe})),he(pe),ke&&ie(pe),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:pe}}))}catch(pe){J(Ge=>({...Ge,[je]:Qe})),he(Qe),ke&&ie(Qe),s.error("Watched umschalten fehlgeschlagen",pe?.message??String(pe))}finally{delete di.current[Fe]}return}let ut=ke?Z:null;if(ut||(ut=await Gs(we,{ensure:!0})),!ut)return;const le=K(ut.modelKey||ut.id||"");if(!le||di.current[le])return;di.current[le]=!0;const ae=ut,ye=!ae.watching,be={...ae,watching:ye},Me=K(ae.modelKey||"");Me&&J(Fe=>({...Fe,[Me]:be})),he(be),ke&&ie(be);try{const Fe=await Zt({id:ae.id,watched:ye});if(!Fe){J(ct=>{const oe=K(ae.modelKey||"");if(!oe)return ct;const{[oe]:pe,...Ge}=ct;return Ge}),vi(ae.id),ke&&ie(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:ae.id,modelKey:ae.modelKey}}));return}const Qe=K(Fe.modelKey||"");Qe&&J(ct=>({...ct,[Qe]:Fe})),he(Fe),ke&&ie(Fe),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:Fe}}))}catch(Fe){const Qe=K(ae.modelKey||"");Qe&&J(ct=>({...ct,[Qe]:ae})),he(ae),ke&&ie(ae),s.error("Watched umschalten fehlgeschlagen",Fe?.message??String(Fe))}finally{delete di.current[le]}},[s,Ze,Z,Gs,Zt,he,vi,re]);async function Gs(we,Ne){const ke=!!Ne?.ensure,tt=be=>{const Me=Date.now(),Fe=ce.current;if(!Fe){ce.current={ts:Me,list:[be]};return}Fe.ts=Me;const Qe=Fe.list.findIndex(ct=>ct.id===be.id);Qe>=0?Fe.list[Qe]=be:Fe.list.unshift(be)},je=async be=>{if(!be)return null;const Me=be.trim().toLowerCase();if(!Me)return null;const Fe=re[Me];if(Fe)return tt(Fe),Fe;if(ke){let Ge;try{const Vt=we.sourceUrl??we.SourceURL??"",Wt=Qu(Vt);Wt&&(Ge=new URL(Wt).hostname.replace(/^www\./i,"").toLowerCase())}catch{}const mt=await Fs("/api/models/ensure",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({modelKey:be,...Ge?{host:Ge}:{}})});return he(mt),mt}const Qe=Date.now(),ct=ce.current;if(!ct||Qe-ct.ts>3e4){const Ge=Object.values(re);if(Ge.length)ce.current={ts:Qe,list:Ge};else{const mt=await Fs("/api/models/list",{cache:"no-store"});ce.current={ts:Qe,list:Array.isArray(mt)?mt:[]}}}const pe=(ce.current?.list??[]).find(Ge=>(Ge.modelKey||"").trim().toLowerCase()===Me);return pe||null},ut=Xd(we.output||"");if(ut)return je(ut);const le=we.status==="running",ae=we.sourceUrl??we.SourceURL??"",ye=Qu(ae);if(le&&ye){const be=await Fs("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:ye})}),Me=await Fs("/api/models/upsert",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(be)});return he(Me),Me}return null}return A.useEffect(()=>{if(!ht&&!rt||!navigator.clipboard?.readText)return;let we=!1,Ne=!1,ke=null;const tt=async()=>{if(!(we||Ne)){Ne=!0;try{const le=await navigator.clipboard.readText(),ae=Qu(le);if(!ae||!Zw(ae)||ae===Ei.current)return;Ei.current=ae,ht&&f(ae),rt&&(We.current?pi.current=ae:(pi.current=null,await _t(ae)))}catch{}finally{Ne=!1}}},je=le=>{we||(ke=window.setTimeout(async()=>{await tt(),je(document.hidden?5e3:1500)},le))},ut=()=>{tt()};return window.addEventListener("hover",ut),document.addEventListener("visibilitychange",ut),je(0),()=>{we=!0,ke&&window.clearTimeout(ke),window.removeEventListener("hover",ut),document.removeEventListener("visibilitychange",ut)}},[ht,rt,_t]),A.useEffect(()=>{if(Ae||!rt)return;const we=pi.current;we&&(pi.current=null,_t(we))},[Ae,rt,_t]),A.useEffect(()=>{const we=zw({getModels:()=>{if(!ot.current.useChaturbateApi)return[];const Ne=q.current,ke=ne.current,tt=Object.values(Ne).filter(ut=>!!ut?.watching&&String(ut?.host??"").toLowerCase().includes("chaturbate")).map(ut=>String(ut?.modelKey??"").trim().toLowerCase()).filter(Boolean),je=Object.keys(ke||{}).map(ut=>String(ut||"").trim().toLowerCase()).filter(Boolean);return Array.from(new Set([...tt,...je]))},getShow:()=>["public","private","hidden","away"],intervalMs:12e3,onData:Ne=>{(async()=>{if(!Ne?.enabled){ft({}),ui.current={},Bt([]),G(Date.now());return}const ke={};for(const le of Array.isArray(Ne.rooms)?Ne.rooms:[]){const ae=String(le?.username??"").trim().toLowerCase();ae&&(ke[ae]=le)}ft(ke),ui.current=ke;const tt=Se.current;for(const le of tt||[]){const ae=String(le||"").trim().toLowerCase();ae&&ke[ae]}if(!ot.current.useChaturbateApi)Bt([]);else if(Je.current==="running"){const le=q.current,ae=ne.current,ye=Array.from(new Set(Object.values(le).filter(Qe=>!!Qe?.watching&&String(Qe?.host??"").toLowerCase().includes("chaturbate")).map(Qe=>String(Qe?.modelKey??"").trim().toLowerCase()).filter(Boolean))),be=Object.keys(ae||{}).map(Qe=>String(Qe||"").trim().toLowerCase()).filter(Boolean),Me=new Set(be),Fe=Array.from(new Set([...ye,...be]));if(Fe.length===0)Bt([]);else{const Qe=[];for(const ct of Fe){const oe=ke[ct];if(!oe)continue;const pe=String(oe?.username??"").trim(),Ge=String(oe?.current_show??"unknown");if(Ge==="public"&&!Me.has(ct))continue;const mt=`https://chaturbate.com/${(pe||ct).trim()}/`;Qe.push({id:ct,modelKey:pe||ct,url:mt,currentShow:Ge,imageUrl:String(oe?.image_url??"")})}Qe.sort((ct,oe)=>ct.modelKey.localeCompare(oe.modelKey,void 0,{sensitivity:"base"})),Bt(Qe)}}if(!ot.current.useChaturbateApi||We.current)return;const je=ne.current,ut=Object.keys(je||{}).map(le=>String(le||"").toLowerCase()).filter(Boolean);for(const le of ut){const ae=ke[le];if(!ae||String(ae.current_show??"")!=="public")continue;const ye=je[le];if(!ye)continue;await _t(ye,{silent:!0})&&si(Me=>{const Fe={...Me||{}};return delete Fe[le],ne.current=Fe,Fe})}G(Date.now())})()}});return()=>we()},[]),A.useEffect(()=>{if(!et.useChaturbateApi){V(0);return}const we=zw({getModels:()=>[],getShow:()=>["public","private","hidden","away"],intervalMs:3e4,fetchAllWhenNoModels:!0,onData:Ne=>{if(!Ne?.enabled){V(0);return}const ke=Number(Ne?.total??0);V(Number.isFinite(ke)?ke:0),G(Date.now())},onError:Ne=>{console.error("[ALL-online poller] error",Ne)}});return()=>we()},[et.useChaturbateApi]),y.jsxs("div",{className:"min-h-[100dvh] bg-gray-50 text-gray-900 dark:bg-gray-950 dark:text-gray-100",children:[y.jsxs("div",{"aria-hidden":"true",className:"pointer-events-none fixed inset-0 overflow-hidden",children:[y.jsx("div",{className:"absolute -top-28 left-1/2 h-80 w-[52rem] -translate-x-1/2 rounded-full bg-indigo-500/10 blur-3xl dark:bg-indigo-400/10"}),y.jsx("div",{className:"absolute -bottom-28 right-[-6rem] h-80 w-[46rem] rounded-full bg-sky-500/10 blur-3xl dark:bg-sky-400/10"})]}),y.jsxs("div",{className:"relative",children:[y.jsx("header",{className:"z-30 bg-white/70 backdrop-blur dark:bg-gray-950/60 sm:sticky sm:top-0 sm:border-b sm:border-gray-200/70 sm:dark:border-white/10",children:y.jsxs("div",{className:"mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-3 sm:py-4 space-y-2 sm:space-y-3",children:[y.jsxs("div",{className:"flex items-center sm:items-start justify-between gap-3 sm:gap-4",children:[y.jsx("div",{className:"min-w-0",children:y.jsxs("div",{className:"min-w-0",children:[y.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[y.jsx("h1",{className:"text-lg font-semibold tracking-tight text-gray-900 dark:text-white",children:"Recorder"}),y.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[y.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-gray-100/80 px-2 py-1 text-[11px] font-semibold text-gray-900 ring-1 ring-gray-200/60 dark:bg-white/10 dark:text-gray-100 dark:ring-white/10",title:"online",children:[y.jsx(dM,{className:"size-4 opacity-80"}),y.jsx("span",{className:"tabular-nums",children:U})]}),y.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-gray-100/80 px-2 py-1 text-[11px] font-semibold text-gray-900 ring-1 ring-gray-200/60 dark:bg-white/10 dark:text-gray-100 dark:ring-white/10",title:"Watched online",children:[y.jsx(Tc,{className:"size-4 opacity-80"}),y.jsx("span",{className:"tabular-nums",children:Ii})]}),y.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-gray-100/80 px-2 py-1 text-[11px] font-semibold text-gray-900 ring-1 ring-gray-200/60 dark:bg-white/10 dark:text-gray-100 dark:ring-white/10",title:"Fav online",children:[y.jsx(_c,{className:"size-4 opacity-80"}),y.jsx("span",{className:"tabular-nums",children:ji})]}),y.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-gray-100/80 px-2 py-1 text-[11px] font-semibold text-gray-900 ring-1 ring-gray-200/60 dark:bg-white/10 dark:text-gray-100 dark:ring-white/10",title:"Like online",children:[y.jsx(nM,{className:"size-4 opacity-80"}),y.jsx("span",{className:"tabular-nums",children:Zi})]})]}),y.jsx("div",{className:"hidden sm:block text-[11px] text-gray-500 dark:text-gray-400",children:W})]}),y.jsxs("div",{className:"sm:hidden mt-1 w-full",children:[y.jsx("div",{className:"text-[11px] text-gray-500 dark:text-gray-400",children:W}),y.jsxs("div",{className:"mt-2 flex items-stretch gap-2",children:[e?y.jsx(Gw,{mode:"inline",className:"flex-1"}):y.jsx("div",{className:"flex-1"}),y.jsx(li,{variant:"secondary",onClick:()=>nt(!0),className:"px-3 shrink-0",children:"Cookies"})]})]})]})}),y.jsxs("div",{className:"hidden sm:flex items-center gap-2 h-full",children:[e?y.jsx(Gw,{mode:"inline"}):null,y.jsx(li,{variant:"secondary",onClick:()=>nt(!0),className:"h-9 px-3",children:"Cookies"})]})]}),y.jsxs("div",{className:"grid gap-2 sm:grid-cols-[1fr_auto] sm:items-stretch",children:[y.jsxs("div",{className:"relative",children:[y.jsx("label",{className:"sr-only",children:"Source URL"}),y.jsx("input",{value:d,onChange:we=>f(we.target.value),placeholder:"https://…",className:"block w-full rounded-lg px-3 py-2.5 text-sm bg-white text-gray-900 shadow-sm ring-1 ring-gray-200 focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:bg-white/10 dark:text-white dark:ring-white/10"})]}),y.jsx(li,{variant:"primary",onClick:Hs,disabled:!ss,className:"w-full sm:w-auto rounded-lg",children:"Start"})]}),Te?y.jsx("div",{className:"rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-500/30 dark:bg-red-500/10 dark:text-red-200",children:y.jsxs("div",{className:"flex items-start justify-between gap-3",children:[y.jsx("div",{className:"min-w-0 break-words",children:Te}),y.jsx("button",{type:"button",className:"shrink-0 rounded px-2 py-1 text-xs font-medium text-red-700 hover:bg-red-100 dark:text-red-200 dark:hover:bg-white/10",onClick:()=>xe(null),"aria-label":"Fehlermeldung schließen",title:"Schließen",children:"✕"})]})}):null,Ni(d)&&!Yt(yt)?y.jsxs("div",{className:"text-xs text-amber-700 dark:text-amber-300",children:["⚠️ Für Chaturbate werden die Cookies ",y.jsx("code",{children:"cf_clearance"})," und ",y.jsx("code",{children:"sessionId"})," benötigt."]}):null,Ae?y.jsx("div",{className:"pt-1",children:y.jsx(bc,{label:"Starte Download…",indeterminate:!0})}):null,y.jsx("div",{className:"hidden sm:block pt-2",children:y.jsx(wS,{tabs:gi,value:xt,onChange:Pt,ariaLabel:"Tabs",variant:"barUnderline"})})]})}),y.jsx("div",{className:"sm:hidden sticky top-0 z-20 border-b border-gray-200/70 bg-white/70 backdrop-blur dark:border-white/10 dark:bg-gray-950/60",children:y.jsx("div",{className:"mx-auto max-w-7xl px-4 py-2",children:y.jsx(wS,{tabs:gi,value:xt,onChange:Pt,ariaLabel:"Tabs",variant:"barUnderline"})})}),y.jsxs("main",{className:"mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-6 space-y-6",children:[xt==="running"?y.jsx(a9,{jobs:is,modelsByKey:re,pending:Gt,onOpenPlayer:Ai,onStopJob:Xt,onToggleFavorite:Ns,onToggleLike:Os,onToggleWatch:Li,blurPreviews:!!et.blurPreviews}):null,xt==="finished"?y.jsx(IM,{jobs:p,modelsByKey:re,doneJobs:v,doneTotal:D,page:_,pageSize:i,onPageChange:S,onOpenPlayer:Ai,onDeleteJob:qi,onToggleHot:Ts,onToggleFavorite:Ns,onToggleLike:Os,onToggleWatch:Li,blurPreviews:!!et.blurPreviews,teaserPlayback:et.teaserPlayback??"hover",teaserAudio:!!et.teaserAudio,assetNonce:gt,sortMode:r,onSortModeChange:we=>{o(we),S(1)}}):null,xt==="models"?y.jsx(h9,{}):null,xt==="categories"?y.jsx(I9,{}):null,xt==="settings"?y.jsx(X5,{onAssetsGenerated:ge}):null]}),y.jsx(q5,{open:lt,onClose:()=>nt(!1),initialCookies:ei,onApply:we=>{const Ne=Om(Object.fromEntries(we.map(ke=>[ke.name,ke.value])));it(Ne),Fs("/api/cookies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cookies:Ne})}).catch(()=>{})}}),y.jsx(E9,{open:!!j,modelKey:j,onClose:()=>ee(null),onOpenPlayer:Ai,runningJobs:is,cookies:yt,blurPreviews:et.blurPreviews,onToggleHot:Ts,onDelete:Vs,onToggleFavorite:Ns,onToggleLike:Os,onToggleWatch:Li}),Ze?y.jsx(Z$,{job:Ze,modelKey:u??void 0,modelsByKey:re,expanded:wt,onToggleExpand:()=>jt(we=>!we),onClose:()=>Nt(null),isHot:Us(Ze.output||"").startsWith("HOT "),isFavorite:!!Z?.favorite,isLiked:Z?.liked===!0,isWatching:!!Z?.watching,onKeep:Kn,onDelete:Vs,onToggleHot:Ts,onToggleFavorite:Ns,onToggleLike:Os,onStopJob:Xt,onToggleWatch:Li}):null]})]})}NI.createRoot(document.getElementById("root")).render(y.jsx(A.StrictMode,{children:y.jsx(kM,{position:"top-right",maxToasts:3,defaultDurationMs:3500,children:y.jsx(P9,{})})}));